diff --git a/.gitignore b/.gitignore index f2c957a..96b924a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,8 @@ .build/ +.build-linux/ +.build-glibc/ +.build-docker*/ +build/ .claude/settings.local.json .claude/worktrees/ *.o @@ -8,3 +12,17 @@ .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata xcuserdata/ *.xcuserstate + +# Linux container scratch build trees (docker runs with the repo mounted). +.build-alsa/ +.build-alsa-amd64/ +.build-noalsa/ + +# Spike sub-packages build their own .build when run from their directory. +spikes/**/.build/ + +# Local SwiftOpenUI fork clone for the @Observable GUI spike (patched, user-local). +spikes/SwiftOpenUI/ + +# All local Docker/scratch build trees. +.build-*/ diff --git a/CLAUDE.md b/CLAUDE.md index 64202b8..5a62302 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,7 +12,7 @@ Eight agents live in `~/.claude/agents/` (maintainer's source of truth) and are | `lyrebird_generator_agent` | **Any new Generator** — oscillator, filter, effect, noise, math operator, bus I/O. | | `lyrebird_engine_agent` | Engine internals — SynthesisEngine, CoreAudioDriver/iOSAudioDriver, AUHAL, SPSCQueue, ScheduledEvent, Group/ParallelGroup, RT thread architecture. | | `lyrebird_language_agent` | Non-RT language side — SynthesizerBase, @LiveParam, ParameterNode, LyrebirdRoutine/Task/Clock, Pattern, MIDI, OSC, NRT, Score, demand pattern usage. | -| `lyrebird_swiftui_agent` | LyrebirdUI module — @UIParam, ParameterKnob/Slider/XY/Button/Label, scope/envelope views, platform-conditional code. | +| `lyrebird_swiftui_agent` | LyrebirdUI module — ParameterKnob/Slider/XY/Button/Label, scope/envelope views, platform-conditional code. (@UIParam/UIParamNode themselves live in core `Lyrebird`.) | | `lyrebird_architect_agent` | Cross-cutting analysis — duplicate patterns, API consistency, SC naming alignment, refactor planning. **No implementation.** | | `lyrebird_review_agent` | Pre-merge review (via `/lyrebird_review`) — RT safety, bus rules, protocol correctness, helper usage, test coverage. | | `pr_review_agent` | General pre-PR review — bugs, security, code smells. Broader scope than `lyrebird_review`. | @@ -52,6 +52,8 @@ These guards catch classes of regression that **`swift build` / `swift test` str **Engine / RT core** - Engine init, audio driver, render pass → `docs/engine/synthesis-engine.md`, `docs/engine/core-audio-driver.md`, `docs/signal-flow/signal-flow.md` +- Linux live audio (`ALSAAudioDriver`, `makeDefaultAudioDriver()`, libasound build requirement) → `docs/engine/alsa-audio-driver.md` +- Portable WAV read/write off Apple (`WavFileWriter` / `WavFileReader`, header layout, `WavFileError`) → `docs/engine/portable-wav-codec.md` - Bus memory / In / Out → `docs/engine/bus-system.md` - Sample-accurate scheduling → `docs/engine/scheduling.md` - ParallelGroup / multi-core → `docs/engine/multi-core.md` @@ -75,6 +77,8 @@ These guards catch classes of regression that **`swift build` / `swift test` str - Routines / tasks / clock / MIDI / OSC → `docs/tooling/routine-task.md` - `Pattern` factory catalog (sequence, series, geometric, uniformRandom, brownian, gaussian, cauchy, beta, shuffle, nonRepeatingRandom, weightedRandom, closure, repeating, limit, drop, stutter, switching, concatenate, roundRobin, tuple, interleave, map, filter, reject, accumulate, difference, wrap, clip, round, smooth) → `docs/tooling/routine-task.md` (§ Pattern Factory Reference) + `Sources/Lyrebird/Lyrebird.docc/RoutineTask.md` - MIDI clock sync (`MIDIClockFollower`) → `docs/tooling/midi-clock-sync.md` +- Linux MIDI (`MIDI` via ALSA sequencer — `MIDI/ALSAMIDI.swift`, `ALSASeqMIDIEvent` mapping; needs CALSA/libasound) → `Sources/Lyrebird/MIDI/ALSAMIDI.swift` +- Linux OSC (`OSCClient` / `OSCServer` POSIX-UDP transport off Apple, `OSCServerError`; codec unchanged) → `Sources/Lyrebird/OSC/OSCServer.swift` - Non-RT parameter value sources / `ValueComputable` / `ValueComputableClosure` (consumed by `LyrebirdProcess` parameters) → `Sources/Lyrebird/Lyrebird.docc/ValueComputable.md` - TemporalStream / language-side value generation → `Sources/Lyrebird/Lyrebird.docc/TemporalDemand.md` - Polyphonic voice pool / step sequencer → `docs/tooling/routine-task.md` @@ -87,6 +91,7 @@ These guards catch classes of regression that **`swift build` / `swift test` str - CLI / REPL / hot-swap → `docs/tooling/cli-guide.md`, `docs/tooling/repl.md` - Project scaffolding / package targets → `docs/tooling/project-system.md`, `docs/tooling/targets.md` - Dev workflow / phase branches / build → `docs/tooling/workflow.md` +- Linux user setup (toolchain, VS Code, build/test, run a sample) → `docs/linux-getting-started.md` - Xcode project templates → `docs/tooling/xcode-templates.md` - AUv3 plugin internals (`LyrebirdAudioUnit`, `LyrebirdAUVoicePoolBinding`, `AUInput`, preset codable, parameter slots) → `Sources/Lyrebird/Lyrebird.docc/AUv3.md` @@ -109,7 +114,8 @@ One-liners. Detail and rationale lives in linked docs. **Platform / build** - macOS 15+ / iOS 18+ / swift-tools 6.0 — `Synchronization.Atomic` requires macOS 15. -- No AVAudioEngine. Use `kAudioUnitSubType_HALOutput` (full duplex AUHAL) on macOS, RemoteIO on iOS. +- No AVAudioEngine. Use `kAudioUnitSubType_HALOutput` (full duplex AUHAL) on macOS, RemoteIO on iOS, blocking `snd_pcm_writei` on a dedicated thread (ALSA) on Linux. +- Never name a concrete driver in code that is meant to build on more than one platform — call `makeDefaultAudioDriver()`. Which drivers exist depends on how Lyrebird itself was built (a Linux build without libasound, or one cross-compiled from macOS, has no `ALSAAudioDriver`), so a consumer-side `#if` is a guess. Code already locked to one platform is exempt and should name its driver directly — e.g. the AppKit-only `ui-demo` scaffold template emits `CoreAudioDriver()`. - No Xcode Playgrounds. All tests use Swift Testing (`@Test`, `#expect`, `@Suite`). **RT thread (render callback)** — `docs/engine/synthesis-engine.md`, `docs/protocols/writing-generators.md` @@ -193,6 +199,8 @@ Throws `EngineAddError`: `.boundToOtherEngine(current:prior:)` (cross-engine), ` `engine.remove(_:)` and `engine.remove(_:at:)` still return `Bool` — they unbind synchronously on successful enqueue. Documented constraint: allow one `processBlock` between `remove` and re-add of the same instance. +`engine.stop()` also unbinds every non-persistent synth it was hosting (including ones nested inside drained `Group` subtrees) as part of its node-tree teardown, so a stop-then-re-add of the same instance — to the same engine or a different one — needs no such wait; the RT thread is already halted before `stop()`'s unbind pass runs. See `docs/engine/synthesis-engine.md` § `stop()` node-tree teardown contract. + Call-site pattern: every `engine.add` invocation needs `try`. In non-throwing contexts (closures dispatched to `DispatchQueue.main.async`, non-throwing methods), wrap in `do { try engine.add(synth) } catch { print("[Lyrebird] engine.add failed: \(error)") }` — the existing `LyrebirdRoutineContext` / `LyrebirdMessageContext` / `LyrebirdProcessContext` adapters use this pattern. ## Swift Code Style Rules diff --git a/LINUX_PLAN.md b/LINUX_PLAN.md new file mode 100644 index 0000000..964b037 --- /dev/null +++ b/LINUX_PLAN.md @@ -0,0 +1,781 @@ + + +# Lyrebird — Linux Support Plan + +Hand-off plan for finishing Linux support. Branch: +`feasibility/cross-platform-linux-windows`. Companion docs: +`docs/cross-platform-feasibility.md` (how the port was done) and +`docs/windows-support-plan.md` (Windows, deferred). + +**A next agent can pick this up cold from this file.** Every item lists what, +why, where (paths), first steps, and an acceptance check. + +--- + +## 1. Current state (what already works) + +The whole non-UI toolchain **cross-compiles to Linux**, verified from macOS: + +| Target | musl SDK | glibc SDK | +|---|---|---| +| `LyrebirdSynth` (core engine + generators) | ✅ | ✅ | +| `LyrebirdGraphDSL` | ✅ | ✅ | +| `LyrebirdCLI` | ✗ (LineNoise `import Glibc`) | ✅ | + +macOS/iOS builds are **byte-identical** to before the port (all Apple-only code +is behind `#if canImport(...)` or re-exported by `LyrebirdDSP`). Full macOS +suite (5644 tests) passes; the branch passed `/lyrebird_review` twice. + +**Architecture that made this work** (do not undo): +- `Sources/LyrebirdDSP/` — a target that `@_exported import`s Accelerate + the + platform C-lib on Apple, and supplies portable scalar/FFT/biquad/vForce + fallbacks off Apple. Generator/synth code writes `import LyrebirdDSP` (never + `import Accelerate`/`import Darwin`) and carries **zero** platform `#if`. +- Portable WAV codec (`Sources/Lyrebird/Buffers/Wav*.swift`) replaces + `ExtAudioFile` off Apple. +- Platform-abstraction files keep their own local `#if`: `MonotonicClock.swift`, + `RTThreadIdentity.swift`, `PlatformCompat.swift` (OSStatus shim), + `AudioFileFormat+AudioToolbox.swift`. + +### How to build / verify Linux locally (from a Mac) + +Two cross-compile SDKs are installed (reusable): + +```bash +# musl (static single binary; best for the core library) +TC=~/Library/Developer/Toolchains/swift-6.3.3-RELEASE.xctoolchain/usr/bin/swift +$TC build --swift-sdk aarch64-swift-linux-musl --target LyrebirdSynth --scratch-path .build-linux + +# glibc / Ubuntu 24.04 (the target for CLI + real distros) +$TC build --swift-sdk 6.3.3-RELEASE_ubuntu_noble_aarch64 --target LyrebirdCLI --scratch-path .build-glibc +``` + +**Critical:** use the **swift.org** toolchain (path above), NOT Xcode's — the +Static Linux SDK's `Foundation.swiftmodule` was built by swift.org's compiler and +a mismatch buries the real errors under ~1244 bogus "Foundation compiled by older +compiler" errors. + +The glibc SDK was generated with `swift-sdk-generator` (swift.org ships no +prebuilt glibc bundle). To regenerate: +`swift run swift-sdk-generator make-linux-sdk --distribution-name ubuntu --distribution-version 24.04 --swift-version 6.3.3-RELEASE`. + +### Standing maintenance — after every `git merge main` + +New generators land on main importing `Darwin`/`Accelerate` directly, which +breaks Linux. Every merge: + +```bash +# 1. migrate any new unguarded imports to LyrebirdDSP: +grep -rlnE "^import Accelerate|^import Darwin" Sources/Lyrebird --include='*.swift' +# (skip RTThreadIdentity / MonotonicClock / DiskOutError — their Darwin is guarded) +# 2. new direct `stderr` / `fputs` usage breaks Linux — Swift 6 flags the imported +# C `stderr` global as "not concurrency-safe". Use the portable helper instead: +# core -> lyrebirdPrintError(_:) (Sources/Lyrebird/Utilities/StandardError.swift) +# LyrebirdCLI -> printError(_:) (Sources/LyrebirdCLI/StandardError.swift) +grep -rnE "\bfputs\b|\bstderr\b" Sources/Lyrebird Sources/LyrebirdCLI --include='*.swift' +# 3. delete Finder sync cruft that appears during merges: +find Sources Tests -regex '.* [0-9]+\.swift' -delete +# 4. rebuild Linux to confirm — cross-compile (both SDKs) AND, when Docker is +# available, run the suite natively (matches CI exactly). The stock swift +# image has no ALSA headers, so either add them (needed to compile +# ALSAAudioDriver) or opt out: +# docker build -t lyrebird-alsa - <<'DOCKERFILE' +# FROM swift:6.3.3 +# RUN apt-get update && apt-get install -y --no-install-recommends libasound2-dev pkg-config +# DOCKERFILE +# docker run --rm -v "$PWD":/pkg -w /pkg lyrebird-alsa swift test +# # …or, without the ALSA package: +# docker run --rm -e LYREBIRD_DISABLE_ALSA=1 -v "$PWD":/pkg -w /pkg swift:6.3.3 swift test +``` + +**Scaffolded projects need their own check.** `swift test` never compiles the +source the CLI *emits*, so template regressions are invisible to it — that is +how the `nrt`/`score` templates came to reference a `LyrebirdCLI`-internal +symbol, and how they kept rendering to CAF (an Apple-only container that throws +off Apple) while still compiling. The gated suite builds **and runs** every SPM +template against this checkout: + +```bash +LYREBIRD_RUN_BUILD_TESTS=1 swift test --no-parallel --filter ProjectScaffolderBuild +# …and inside the Linux container, where it matters most: +# docker run --rm -v "$PWD":/pkg -w /pkg lyrebird-alsa \ +# bash -c 'LYREBIRD_RUN_BUILD_TESTS=1 swift test --no-parallel --filter ProjectScaffolderBuild' +``` + +Run it after touching `ProjectScaffolder` or any public API a template uses. + +**Two arch/build gotchas the CI bring-up already paid for:** + +- **BitBucket runners are x86_64; the Mac + its local Docker are arm64.** Some + breakage is x86-only and invisible on an arm64 box — e.g. C code that uses a + Darwin-only `` macro under an `#if defined(__x86_64__)` branch compiles + on arm64 Linux (wrong branch, and note Linux arm64 predefines `__aarch64__`, + **not** Apple's `__arm64__`) but breaks on x86 glibc. To reproduce CI exactly, + emulate the runner arch locally: + `docker run --rm --platform linux/amd64 -v "$PWD":/pkg -w /pkg swift:6.3.3 swift test`. +- **A library-only build does not compile C target sources — only headers.** + `swift build --target LyrebirdSynth` (a library) will not surface a bad + `Sources/LyrebirdC/*.c`; the `.c` is compiled only when an executable/test + links it. So the build *gate* can be green while `swift test` fails. Always + verify with `swift test` (which links), not just the build gate. + +### Verifying on macOS: always `swift test --no-parallel` + +Plain `swift test` on macOS reports **~45 failures** on a clean tree. They are +**not real** — `--no-parallel` is the project's canonical command +(`docs/00-working-order.md` step 1) and the full suite passes under it. + +The flakes are main-thread starvation, concentrated in `LyrebirdProcess`, +`LyrebirdEventList*`, `RoutineTests` and `ActorIsolationGuardTests`: those tests +dispatch to the main queue and then wait on a wall-clock timeout, while the +parallel runner has `@MainActor` suites saturating main. Recognisable by the +message shape — `got 0 of 3`, `.timedOut`, `Body should have entered`, +`Expected ~0.2s between events, got 2.3s` — never a wrong numeric result. +Parallel is also *slower* here (≈286 s vs ≈94 s), so there is no reason to use +it. Phase 148 fixed an earlier batch in these same suites; residual +parallel-only flakes are recorded in `docs/01-completed-working-order.md`. + +**Do not debug these before re-running serially.** If a failure is suspected to +be real, the cheap discriminator is a clean-tree baseline: `git worktree add + HEAD` and run the same command there — a failure present at HEAD is not +yours. + +Linux in-container runs (`docker run … swift test`) have not shown this; the +affected suites are macOS-host-only, so CI is unaffected. + +### IDE for Linux +**VS Code + the official Swift extension** (`swiftlang.swift-vscode`) — +SourceKit-LSP, LLDB, test explorer, SPM. Best-maintained non-Xcode path. + +--- + +## 2. Remaining work — prioritized + +Ordered by value for a *usable* Linux Lyrebird. Items 1–3 make it real; 4–8 are +capability/coverage. + +**Status board** (update the box when an item lands; each item's own heading +carries the same marker): + +| # | Item | Priority | Status | +|---|---|---|---| +| 3 | Linux CI lane | HIGH | ✅ done — green on BitBucket | +| 2 | Golden DSP tests on Linux | HIGH | ✅ done — 6 goldens green in CI | +| 1 | `ALSAAudioDriver` (live audio) | HIGH | ◑ plays on hardware; deeper checks pending | +| 6 | DiskIn + buffer file I/O | MEDIUM | ✅ done — WavFileReader backend | +| 4 | MIDI on Linux | MEDIUM | ⚠️ built, untested on hardware | +| 5 | OSC on Linux | MEDIUM | ✅ done — POSIX UDP, loopback-verified | +| 8 | SwiftOpenUI GUI spike | EXPLORATION | ✅ drag works on hardware (@State + @Observable patch); patch PR-ready | +| 7 | CLI on musl (LineNoise) | LOW | ☐ decision | + +### Item 1 — `ALSAAudioDriver` (live audio) — HIGH — ⚠️ BUILT, NOT YET HEARD +**What:** A driver conforming to `AudioDriver` that opens a Linux audio device +and calls `engine.processBlock(inputSamples:)` from a render thread. +**Why:** Without it, Linux only does offline NRT-to-WAV. This is the capability +that makes Linux usable. +**Delivered:** `Sources/Lyrebird/AudioDrivers/ALSAAudioDriver.swift` — a +blocking `snd_pcm_writei` loop on a dedicated thread, the shape the plan +recommended (no callback re-entrancy, no ALSA async-handler restrictions, +back-pressure straight from the device). **Full reference: +`docs/engine/alsa-audio-driver.md`** — transport, duplex, xrun policy, +lifecycle, and the build requirement; that document is canonical, this section +is the plan-level summary. + +**Do not name a driver in portable code** — call `makeDefaultAudioDriver()` +(`AudioDrivers/DefaultAudioDriver.swift`), which resolves to `iOSAudioDriver` / +`CoreAudioDriver` / `ALSAAudioDriver` / `OfflineDriver` from *inside* the +module. Which drivers exist is not a function of the OS alone (a Linux build +without libasound, or one cross-compiled from macOS, has no ALSA), so a +consumer-side `#if` is guessing. `isLiveAudioAvailable` reports whether the +build has any live backend at all. + +- **Format** `SND_PCM_FORMAT_FLOAT_LE`, matching the engine's `Float` buses, so + nothing in the path converts or dithers. +- **Setup** via `snd_pcm_set_params` (ALSA's own convenience over the + hw/sw-params dance), latency = `blockSize × periodsPerBuffer / sampleRate`. +- **Duplex** when the engine asks for input channels: a capture PCM is opened + and `snd_pcm_link`ed to playback so the two cannot drift; `linkedStreams` + reports whether the kernel accepted the link. +- **RT thread** marks itself via `RTThreadIdentity.markCurrentThreadAsRT()`, + calls `enableFlushToZero()`, and requests `SCHED_FIFO` at 75 % of the policy + range — denial is normal for an unprivileged process and is reported through + `hasRealtimePriority` rather than failing the start. +- **No allocation in the loop**: interleave/deinterleave staging buffers are + raw pointers allocated in `setup(engine:)`. +- **Xrun policy** is factored out into `ALSARecoveryAction.classify(_:)` — + `-EINTR`/`-EAGAIN` retry, `-EPIPE`/`-ESTRPIPE` recover via `snd_pcm_recover`, + anything else stops the loop and lands in `lastError`. The errno values are + spelled out as Linux constants rather than taken from the host's `errno.h`, + so the classification cannot differ per platform (`EAGAIN` is 11 on Linux, 35 + on Darwin) and the tests mean the same thing everywhere. + +**Build requirement — libasound2-dev.** The `CALSA` system-library target +(`Sources/CALSA/`) needs ALSA's headers. `Package.swift` adds that target only +when the manifest is evaluated **on a Linux host**, so: +- macOS/iOS builds never see it (verified: `swift build`/`swift test` unchanged). +- **Cross-compiling to Linux from a Mac produces a binary with no live-audio + driver** — the host is macOS, so `CALSA` is absent and the driver compiles + away. Build natively on Linux to get audio out; cross-compiles remain + offline-only. +- A native Linux build without the package fails with + `error: 'alsa/asoundlib.h' file not found` → `could not build C module 'CALSA'`. + Fix: `apt-get install libasound2-dev pkg-config`, which the CI lane now does. + Escape hatch for a box that deliberately has no audio stack: + `LYREBIRD_DISABLE_ALSA=1 swift build` (verified — everything but the driver + builds). + +**Verified (headless):** 11 new tests in `LyrebirdPortableTests`, green on +macOS and on Linux arm64 + x86_64: +- interleave/deinterleave: frame order, missing channel → silence, short bus → + padded, round-trip identity, extra channel dropped (all platforms — a + transposed index here yields channel-swapped audio, not an error, which is + exactly what nobody notices on a headless box); +- `ALSARecoveryAction` classification of every branch (all platforms); +- Linux-only: `start()` before `setup` throws `.notConfigured`; an unopenable + device throws `.playbackDeviceOpenFailed` and leaves `lastError` clear; + repeated/early `stop()` is safe; defaults and `suggestedControlBlockSize`. + These also serve as the guard that the driver is actually *in* the build — if + the `CALSA` dependency ever stops resolving, the whole file compiles away to + nothing and every other test would still pass. + +**Acceptance — basic playback CONFIRMED on hardware.** On an Ubuntu 24.04 arm64 +Parallels VM (2026-08-21), the `quickstart` template played its 10-second sine to +the speakers via `makeDefaultAudioDriver()` → `ALSAAudioDriver`. The driver moves +a real speaker — the headline capability is proven. Still to exercise on hardware: +1. ~~sine to speakers~~ ✅ (confirmed at the template default rate; still worth a + pass at both 44.1 and 48 kHz and a couple of block sizes); +2. xrun recovery under load (the `-EPIPE` path is written but never taken); +3. duplex: confirm `snd_pcm_link` succeeds on a real duplex device and that + input reaches the engine; +4. `SCHED_FIFO` grant under a `limits.conf`-configured user; +5. latency sanity vs `periodsPerBuffer`. +Basic output is no longer unproven; the robustness checks (2–5) remain open. + +**Follow-ups, deliberately not done here:** +- **PipeWire backend.** ALSA-through-PipeWire's compat layer works, but a native + PipeWire driver is the better long-term desktop path. `AudioDriver` is the + seam; nothing in this driver blocks it. +- ~~**Scaffolder templates emit `CoreAudioDriver()`**~~ ✅ **done** — the CLI + templates (`quickstart`, `basic`, `demo`) now emit + `makeDefaultAudioDriver()`. The first attempt emitted the + `#if canImport(AudioToolbox)` switch in the *generated* source; review caught + that this breaks exactly where it matters — Windows, a cross-compiled Linux + build, and `LYREBIRD_DISABLE_ALSA=1` all lack `ALSAAudioDriver`, so the + emitted `#else` would not compile. Hence the library-side factory. The + `ui-demo` and Xcode templates keep `CoreAudioDriver` deliberately: they import + AppKit / are Xcode projects, so they are Apple-only by construction. + Also fixed here: the `nrt` and `score` templates emitted `printError(...)`, a + helper that exists only inside the `LyrebirdCLI` target, so **every + scaffolded `nrt`/`score` project failed to compile** — a regression from the + earlier stderr port on this branch. They now emit a self-contained + `FileHandle`-based helper. All five CLI templates are verified by scaffolding + and **building** them in the Linux container, not by string inspection. + +### Item 2 — Golden-value DSP tests that run on Linux — HIGH — ✅ DONE +**What:** Tests asserting concrete numeric output of the portable FFT/biquad +**through the real generators**, runnable off Apple. +**Why:** `Tests/LyrebirdDSPTests/ScalarDSPParityTests.swift` compares to *real +vDSP* and is therefore `#if canImport(Accelerate)` — **Apple-only**. Nothing +verified that the portable DSP produces correct *audio* on Linux; a packing or +scaling bug in the portable FFT would have shipped silently. +**Delivered:** a new platform-neutral test target `LyrebirdPortableTests` +(`Tests/LyrebirdPortableTests/`, in the main `targets:` array so a Linux host +sees it) holding **6 golden-value tests**, no `#if` guards anywhere: + +| Test | Portable code it pins | +|---|---| +| `butterworthLowPassOrder4ImpulseResponse` | `vDSP_biquadD` opaque-setup cascade (`PortableBiquad.swift`) | +| `butterworthHighPassOrder2ImpulseResponse` | same, different coefficient path | +| `klankImpulseResponse` | vector kernel — `vsmulD` / `vmulD` / **`vsubD`** / `sveD` | +| `resonatorBankImpulseResponse` | same kernel, `(freq, decay, amp)` spec order | +| `analysisMagnitudeSpectrumOfBinCentredSine` | forward `vDSP_fft_zrip` + `ctoz` packing and real-FFT scaling | +| `resynthesisReconstructsInputSine` | inverse FFT + windowed overlap-add round trip | + +Goldens were captured on macOS (arm64, vDSP-backed) and are compared with a +`absolute + relative × |golden|` tolerance — `1e-9` for the double-precision +filter responses, `1e-5` for the `Float`-internal spectral paths. +`Tests/LyrebirdPortableTests/PortableTestSupport.swift` holds the local +engine/collect helpers (test targets cannot share sources) and deliberately uses +only the public + `@_spi(LyrebirdExtensions)` surface. + +**Both directions of the check were verified** (a golden test that cannot fail is +worse than none): +- swapping `vDSP_vsubD`'s operands in `AccelerateShim.swift` → Klank and + ResonatorBank fail on Linux with diffs of `1e7`+ (the classic vDSP + reversed-operand bug, caught). +- swapping real/imag in `vDSP_ctoz` (`PortableFFT.swift`) → both spectral tests + fail with diffs of ~0.29 on a unit-amplitude sine. +Each sabotage was reverted immediately after the run. + +**Verified green:** macOS (`swift test --no-parallel`, vDSP path — see the +serial-run note above) and Linux in-container on +both architectures — `docker run --rm [--platform linux/amd64] -v "$PWD":/pkg +-w /pkg swift:6.3.3 swift test` — so the CI lane (Item 3, x86_64 runners) runs +them on every push with no config change; only the explanatory comment in +`bitbucket-pipelines.yml` was updated. + +**Regenerating a golden** (only after establishing the change was intended — +unexplained drift is the bug this target exists to catch): run the same graph on +macOS and print each sample with `String(format: "%+.15e")`. + +**Not done here (deliberate):** the ~165 files of `LyrebirdTests` are still +macOS-host-only. Most are platform-neutral and could migrate to +`LyrebirdPortableTests` over time, which would widen Linux coverage well beyond +DSP; that is bulk mechanical work, independent of this item, and best done in +slices rather than as one move. + +### Item 3 — Linux CI lane — HIGH — ✅ DONE +**What:** CI building + testing on Linux. +**Why:** Locks in the port so a main-merge can't silently regress it (see the +standing-maintenance hazard). CI is also the only place tests actually *run* on +Linux without a local Linux box. +**Delivered:** `bitbucket-pipelines.yml` (the repo remote is BitBucket, not +GitHub) using the official `swift:6.3.3` image. `size: 2x` (8 GB). Builds +`LyrebirdSynth` / `LyrebirdGraphDSL` / `LyrebirdCLI`, then `swift test` runs +every target the Linux manifest exposes: **LyrebirdDSPTests, LyrebirdGraphDSLTests, +LyrebirdCLITests — 239 tests, all green** natively in-container. +**Verified locally** in the same image via Docker Desktop (arm64): +`docker run --rm -v "$PWD":/pkg -w /pkg swift:6.3.3 swift test`. + +Supporting changes made to get here: +- **Manifest split** (`Package.swift`): the Apple-only targets — `LyrebirdUI`, + `LyrebirdUITests`, `LyrebirdTests` (imports `AudioToolbox` directly in some + files), and `LyrebirdBenchmark` (micro-benchmarks vDSP) — are appended under + `#if os(macOS)` *after* the `Package(...)` initializer (an `#if` cannot be an + array element in a manifest). On a Linux/Windows host they are simply absent, + so `swift test` compiles only the portable surface. macOS/iOS builds see every + target unchanged; the two remaining test targets' `AudioToolbox`/`Accelerate` + links are now `.when(platforms: [.macOS, .iOS])`. +- **Core `stderr` fix**: a `git merge main` had landed + `fputs(..., stderr)` in `Score/ScoreElementDSL.swift`, which fails Swift 6 + concurrency checking on Linux — the exact standing-maintenance hazard. Added + `Utilities/StandardError.swift` (`lyrebirdPrintError(_:)`, `FileHandle`-based) + and routed the call through it. Grep guard added to the maintenance list above. + +**Registry compile-memory (resolved):** the generated +`Sources/LyrebirdGraphDSL/Generated/GeneratedDSLRegistry.swift` used to be one +~300-element array literal; the type-checker checked it as a single expression and +needed several GB, so two concurrent heavy compiles OOM-killed the compiler on an +8 GB runner. Fixed in `Tools/DSLRegistryGen`: `emitRegistry` now emits the entries +as fixed-size (`registryChunkSize = 32`) `private static let _chunkN` arrays +concatenated into `generated`, so each chunk type-checks independently. Verified +building at full parallelism on Linux from a clean scratch — no OOM — so CI runs +default `-j` (no cap). Regenerate with `bash scripts/generate-dsl-registry.sh` +after changing a public generator init; the `--check` drift guard stays green. + +**Acceptance:** green CI on push to the branch — Pipelines is enabled on the +BitBucket repo. + +### Item 4 — MIDI on Linux — MEDIUM — ⚠️ BUILT, NOT YET RECEIVED FROM HARDWARE +**What:** `Sources/Lyrebird/MIDI/` was `#if canImport(CoreMIDI)`-guarded out, so +there was no MIDI in/out on Linux. +**Delivered:** an ALSA-sequencer backend behind the same `MIDI` public API as the +CoreMIDI one. +- **Shared, tested mapping.** `MIDI/ALSASeqMIDIEvent.swift` — a pure enum + + `midiMessage(for:)` that turns a decoded seq event into a `MIDIMessage`, + routing channel-voice events through the existing + `MIDIMessage.from(status:data1:data2:)` so Linux applies the identical parsing + (note-on velocity 0 → note-off, the pitch-bend offset) the CoreMIDI path does. + Pure Swift, no ALSA import, so it is unit-tested on **both** platforms + (`ALSASeqMIDIEventTests`, 8 tests). +- **The backend.** `MIDI/ALSAMIDI.swift`, guarded + `#if !canImport(CoreMIDI) && canImport(CALSA)`, defines `MIDI` for native + Linux: `snd_seq_open`, in/out simple ports, source enumeration + (`snd_seq_query_next_client/port`), auto-subscribe to readable sources, a + `poll()`-based input thread (200 ms cadence so `stop()` is responsive) that + decodes events via the shared mapping and dispatches on the `lyrebird.midi` + queue, and `send` / `sendVirtual` building seq events from `MIDIMessage`. + The handler registry, dispatch contract, and lifecycle discipline mirror the + CoreMIDI class; the two definitions are mutually exclusive so exactly one + `MIDI` compiles per platform. +- `MIDISource` / `MIDIDestination` are now cross-platform: `endpointRef` on + Apple, ALSA `client:port` off Apple. `MIDIError` gained `Equatable` and its + `OSStatus`-carrying cases double as ALSA return-code carriers (`OSStatus` is + `Int32` off Apple). `MIDIMessage` / `+UMP` / `MIDIHandlerToken` were already + neutral. + +**Availability:** like `ALSAAudioDriver`, `MIDI` exists on Linux only where +CALSA is linked — absent under `LYREBIRD_DISABLE_ALSA=1` or a cross-compile from +macOS. Consumers that need MIDI everywhere must guard accordingly. + +**Verified (headless):** `ALSAMIDITests` (Linux-only) — handler registry, the +not-started send/create guards, safe repeated stop, empty pre-start +enumeration, and a tolerant start/stop that accepts either a real open or a +clean `clientCreateFailed` when `/dev/snd/seq` is absent (the container case), +checking a failed start does not latch `isStarted`. macOS +`swift test --no-parallel` 5714/5714; Linux arm64 302 / x86_64 302; +`LYREBIRD_DISABLE_ALSA=1` 289. + +**Acceptance NOT met — no controller has been received from.** The container has +no sequencer device, so the poll loop, event decode from a live controller, +subscription, and `send` to real hardware have never run. Outstanding on a Linux +box with ALSA + a connected controller: +1. receive note-on / note-off / CC / pitch-bend / program-change from a + controller and confirm the decoded `MIDIMessage`; +2. `send` to a hardware synth and hear it; +3. `createVirtualInput` / `createVirtualOutput` visible to other clients + (`aconnect -l`) and round-trip; +4. hot-plug: a controller connected after `start()` appears (the poll loop does + not currently re-enumerate — see below). + +**Known limitations / follow-ups:** +- **No hot-plug re-enumeration.** CoreMIDI's `MIDIClientCreateWithBlock` + notification re-runs `_refreshEndpoints` / `_connectAllSources`; the ALSA + backend enumerates and subscribes once at `start()`. A device connected later + is not auto-subscribed. ALSA exposes this via the System announce port + (subscribe to client 0 port 1 and handle `SND_SEQ_EVENT_PORT_START`); left as + a follow-up. +- **UMP / MIDI 2.0.** The CoreMIDI path sends MIDI 1.0 over the UMP API; the + ALSA path is MIDI 1.0 via legacy seq events. Functionally equivalent for the + `MIDIMessage` set; a native UMP seq path is not implemented. + +### Item 5 — OSC on Linux — MEDIUM — ✅ DONE +**What:** `OSCClient` / `OSCServer` used Apple's `Network.framework` +(`NWConnection` / `NWListener`), guarded out on Linux. +**Delivered:** POSIX BSD-socket transports under `#else`, no dependencies. The +OSC 1.0 codec (`OSCArgument` / `OSCCodec` / `OSCMessage`) was already portable; +only the transport was swapped, and the handler registry / decode+dispatch is +now shared code rather than living inside the `Network` guard. +- `OSCClient`: a connected UDP socket (`getaddrinfo` → `socket` → `connect`), + opened lazily on the first send on the serial `sendQueue`, reused after. A + resolution/connect failure is latched so a bad host does not re-resolve every + send. `sendto` with a nil destination avoids the name clash with the class's + own `send`. +- `OSCServer`: `socket` + `SO_REUSEADDR` + `bind` to `INADDR_ANY:port`, then a + dedicated receive thread running a `poll()` loop (200 ms cadence) that + `recv`s datagrams and hands them to the shared decode+dispatch. `stop()` + shuts the socket down (unblocking any wait), clears the run flag, joins, and + closes — the same discipline as the ALSA backends. New `OSCServerError` + (`socketFailed` / `bindFailed`, carrying `errno`) is thrown off Apple; on + Apple `NWListener` throws its own error. `OSCHandlerToken` moved out of the + `Network` guard so it exists on both platforms. + +**Acceptance MET — verified over real loopback, on both platforms.** Unlike the +ALSA MIDI and audio backends, OSC needs no hardware: `OSCLoopbackTests` +(`Tests/LyrebirdPortableTests`) binds an `OSCServer` on 127.0.0.1 and sends to it +with `OSCClient`, asserting a full argument round trip, glob-pattern address +matching, that a removed handler stops receiving, and safe idempotent stop. It +exercises `Network.framework` on macOS and the POSIX transport on Linux, and +passes on both — including **Linux without ALSA** (OSC is pure POSIX, so it does +not depend on CALSA and runs under `LYREBIRD_DISABLE_ALSA=1`). macOS +`swift test --no-parallel` 5718/5718; Linux arm64 306 / x86_64 306; +`LYREBIRD_DISABLE_ALSA=1` 293. + +### Item 6 — DiskIn + LyrebirdBuffer file I/O on Linux — MEDIUM — ✅ DONE +**What:** `Generators/BufferIO/DiskIn.swift` and `Buffers/LyrebirdBufferFileIO.swift` +were fully `#if canImport(AudioToolbox)`-guarded (no portable fallback), so +soundfile-into-buffer loads and disk streaming did not exist off Apple. +**Delivered:** portable `#else` branches on the `WavFileReader` / +`WavFileWriter` backend, mirroring `DiskOut` / `NRTDriver`: +- `LyrebirdBuffer.load` / `loadAllChannels` / `fill` read WAV via + `WavFileReader`; the chunked read + channel-extract + optional peak + normalisation is replicated in two portable helpers + (`portableReadMono` / `portableReadAllChannels`). `channelOutOfRange` / + `invalidChannelCount` stay cross-platform; open/read failures surface as + `WavFileError` (matching the documented `NRTDriver` decision, rather than + wrapping). +- `LyrebirdBuffer.write` gains a `WavFileWriter` branch (RF64 already went + through the portable `RF64Writer` on both platforms); the Apple-only + containers throw a new `LyrebirdBufferIOError.unsupportedFormatOnPlatform`. +- `DiskIn.Audio` streams via `WavFileReader`, reopening the file to loop (the + reader is forward-only). **Sample-rate handling:** `ExtAudioFile` resamples + to the engine rate transparently; the portable reader hands back the file's + native frames, so `DiskIn` folds `fileSampleRate / engineSampleRate` into the + read-position advance (`_readRateScale`, `1.0` on Apple) — a 44.1 kHz file on + a 48 kHz engine plays at the right speed and pitch via the existing linear + interpolation. The buffer-load paths do **not** resample on either platform + (they keep the file's own rate), so no scale is needed there. +- `LyrebirdBufferIOError` split: the `OSStatus` cases are Apple-only; the + semantic cases (`channelOutOfRange`, `invalidChannelCount`, + `fileTooLargeForContainer`) are cross-platform; `unsupportedFormatOnPlatform` + is added off Apple. `DiskInError` stays Apple-only — the portable `DiskIn` + throws `WavFileError`. + +**Verified:** new `Tests/LyrebirdPortableTests/PortableFileIOTests.swift` — +mono/stereo load round trips, channel select, `channelOutOfRange`, fill +truncate + zero-pad, peak normalisation, int16 write→load round trip, DiskIn +sample-accurate streaming at matching rate, and (off-Apple only) DiskIn +sample-rate-ratio folding + `write` to a CAF throwing +`unsupportedFormatOnPlatform`. Fixtures are written with `WavFileWriter`, so the +suite runs on both platforms; on Apple the same paths exercise `ExtAudioFile` +and a round trip that agrees on both is the guarantee. macOS +`swift test --no-parallel` 5706/5706; Linux arm64 + x86_64 289/289; +`LYREBIRD_DISABLE_ALSA=1` 281/281. + +**One test is portable-only by nature:** the SR-ratio DiskIn test is +`#if !canImport(AudioToolbox)`, because on Apple `ExtAudioFile` does the +conversion inside `DiskIn` (advancing at rate 1) and the exact file-frame +mapping the test asserts only holds for the portable read-position scaling. + +### Item 7 — CLI on musl (LineNoise) — LOW / decision +**What:** `LyrebirdCLI` builds on glibc but not musl — the `LineNoise` +dependency does `import Glibc` with no `Musl` support. +**Why / decision:** glibc is the standard Linux target, so this is optional. +Options: (a) accept CLI = glibc-only (recommended); (b) fork/patch LineNoise for +`Musl`; (c) swap the line-editing dependency. Document the choice; don't spend +effort unless a static-musl CLI binary is specifically wanted. + +### Item 8 — GUI spike: **SwiftOpenUI** for `LyrebirdUI` on Linux — EXPLORATION +**What:** Evaluate `codelynx/SwiftOpenUI` (MIT) as the path to run `LyrebirdUI` +on Linux. It is a SwiftUI-API reimplementation: **on macOS it imports real +SwiftUI**; on Linux it renders via **GTK4** (needs `libgtk-4-dev`) — the same +"real API on Apple / portable backend elsewhere" pattern Lyrebird already uses +for `LyrebirdDSP`. +**Why it looks reasonable:** its coverage matches what `LyrebirdUI` actually +needs — `Canvas`/`Path`/`Circle`/`Rectangle` (the knobs, scope, and envelope +views are custom-drawn), drag/tap gestures (the XY pad), and the +`@State`/`@Binding` wrappers that `@UIParam` builds on. MIT-licensed. +**Risks / unknowns (why it's a spike, not a commitment):** +- Maturity is modest (~31 stars, effectively one author) — bus-factor risk; the + "Stable" self-label is optimistic. SwiftUI reimplementations always have edge + gaps. +- Lyrebird's AppKit `NSEvent` mouse monitor (`MouseInputBridge`, installed via + `MouseInput.install(_:)`) is Apple-only — a GTK input path is needed for the + mouse-driven generators. +- `@UIParam` (`Sources/LyrebirdUI/`) + `ParameterKnob`/`Slider`/`XY`/scope/ + envelope views must actually compile + render against SwiftOpenUI's surface. +**Compile-probe done (container, no display) — the hard 20% answered.** +`codelynx/SwiftOpenUI` (`develop` @ 8100d9c, MIT). Modules `SwiftOpenUI` + +`BackendGTK4` (a `.systemLibrary` on `libgtk-4-dev`). Built the framework **and a +LyrebirdUI-style Canvas knob** in a GTK4 container (`swift:6.3.3` + `libgtk-4-dev`): +SwiftOpenUI + BackendGTK4 compile on Linux, and the knob (custom drawing + +`@Observable` model + drag) compiles. What the probe found: + +- **`GraphicsContext` is NOT provided — this is the shim.** SwiftOpenUI's + `Canvas(renderer: { ctx, size in … })` hands back a **Cairo-backed + `DrawingContext`** (`setColor` / `moveTo` / `lineTo` / `arc` / `stroke()` / + `fill()`), not SwiftUI's `GraphicsContext`. So every LyrebirdUI custom-drawn + view — `ParameterKnob`, `LyrebirdScopeView`, `LyrebirdEnvelopeView`, + `LyrebirdSpectrumView`, `LyrebirdScatterView` (the 9 `Canvas` + 6 + `GraphicsContext` call sites) — needs its drawing body **rewritten** from + `GraphicsContext.fill/stroke/draw` to `DrawingContext`. The rewrite is + mechanical (both are imperative 2-D drawing) and was proven to compile, but it + is per-view work, not a drop-in. +- **`@Observable` works on Linux (stdlib `Observation`), but SwiftOpenUI does not + re-export it** — a consumer must add `import Observation` explicitly (real + SwiftUI re-exports it). SwiftOpenUI's `DependencyTracking` claims + `@Observable`-driven rebuilds, so `@UIParam`'s backing model should drive + re-renders — but that is runtime behavior still to confirm on a display. +- **Gestures fit.** `.onDrag { (d: DragGestureValue) in … }` carries + `translation`, which is what the knob/XY drags need; the closure shape differs + from SwiftUI's `DragGesture().onChanged`, so a light rewrite. +- Declarative controls (`Slider`, `Button`, `Text`, `VStack`/`HStack`) and the + `@State`/`@Observable` binding port with light friction. + +**Update 10 — RESUME with fork patches (2026-09-05).** Re-verified upstream +`develop @ 8100d9c` still has the observation→full-rebuild→gesture-teardown +(`GTKViewHost.rebuild()` still gates the narrow path on `!fromObservation`); no +`@GestureState`, no gesture-identity reconciliation. Confirmed the blocker lives +in the GTK4 render/gesture layer, **below** the state wrappers — so no +`@State`/`@Binding`/`@Observable` choice routes around it (the single-control +`@State` "success" is an artifact of Problem 1's idle-starvation masking Problem +2). Decision: **keep the SwiftUI path for the Linux pre-release** and fix it in +the fork. Two patches planned (B: live redraw via high-priority `queue_draw` +during drag; C: reuse the existing `beginInteractiveUpdate`/`endInteractiveUpdate` +deferral so no rebuild recreates the gesture mid-drag). Full plan, fork-commit +strategy, and validation: **`spikes/SwiftOpenUIKnob/FORK_PATCH_PLAN.md`**. +Patches are the next work session. + +**Update 9 — INTERACTIVE-UI BLOCKER (hardware, 2026-08-22). All 8 views build +and the timer-driven ones work; live drag interaction does NOT.** On-hardware +testing of the full demo found two distinct SwiftOpenUI GTK4-backend problems, +both root-caused from the pinned fork source. Both are BEYOND the drag-observable +patch already submitted upstream (that patch fixed single-control gesture +*streaming*, which does work — see below). + +What works on hardware: the scope animates, the CPU meters update, audio tracks +live (dragging a knob changes the sound continuously). What fails: the *visual* +of interactive controls. + +Bisected with `LYREBIRD_DEMO={knob,controls,full}` (diagnostic scaffolding in +`Sources/LyrebirdUILinuxDemo/`, commit 22dd5b6a — kept until this is resolved): +- `knob` (one knob): gesture STREAMS (sound tracks continuously), but the knob + Canvas only redraws on mouse-UP. +- `controls` (all controls, no animated views): knob/XY drop back to one tick per + gesture; native slider moves but its sound update only lands on mouse-up. +- `full`: scope animates; every interactive control is one-tick. + +Root causes (in `.build-*/checkouts/SwiftOpenUI/Sources/Backend/GTK4/Rendering/`): +1. **Idle-starved redraw (Problem 1).** `GTKViewHost.scheduleRebuild` schedules + the redraw with plain `g_idle_add` (default idle priority). During a continuous + drag, higher-priority pointer-motion events saturate the GLib loop and starve + the idle rebuild, so the Canvas only redraws when motion stops (release). Audio + is unaffected because `node.update(_:)` runs directly in the `onChanged` + closure, not via a rebuild. Fix direction: high-priority `gtk_widget_queue_draw` + on the Canvas during drag, not an idle-scheduled full-tree rebuild. +2. **Drag-gesture teardown under sibling rebuilds (Problem 2).** With several + controls bound to one node, a drag triggers a mid-drag rebuild that recreates + the dragged Canvas widget → the `GtkGestureDrag` detaches → one tick. The + single-control case only survives because its rebuild is idle-starved (so the + widget is never recreated during the drag). Fix direction: reconcile the drag- + gesture widget by IDENTITY so it survives rebuilds — exactly the preferred fix + in `spikes/SwiftOpenUIKnob/UPSTREAM_ISSUE.md`, and the drop-target code + (`GTKDropState` widget-pinning) is the in-repo precedent. + +Decision (2026-08-22): PAUSE the interactive-UI push and gauge the SwiftOpenUI +maintainer's responsiveness on the submitted PR first. If it is accepted → dig +into Problems 1 & 2 (extend the issue/PR). If rejected with rationale → iterate. +If it goes stale → reconsider the Linux UI approach (swift-cross-ui, or a thinner +GTK layer). Not blocking anything else on the branch — the headless core, audio, +scope/CPU readouts, and static views are all fine; only live *dragging* is +affected. Investigation cost is already paid and captured here, so resuming does +not require re-bisecting. + +**Update 8 — control + visualization set ported.** All eight `LyrebirdUI` +controls/views now have `Linux*` counterparts in `LyrebirdUILinux`: +`LinuxParameterKnob` / `Slider` / `Label` / `Button` / `XY` (controls) and +`LinuxScopeView` / `LinuxEnvelopeView` / `LinuxStatusView` (visualization). The +animated views (scope, CPU status) use an `@Observable` model polled by a +Foundation `Timer` on `RunLoop.main` (pumped by the GTK4 backend), NOT +SwiftOpenUI's off-main `.task`. See Update 9 for the interaction blocker found +when these were tested together on hardware. + +**Update 7 — symmetric import shape + runnable demo.** Two ergonomics changes +so friends can clone and run: +- **Re-export shims** give both platforms one import shape. `LyrebirdUILinux` + gets `LinuxUIExports.swift` (`@_exported import SwiftOpenUI` + + `@_exported import BackendGTK4`); the macOS `LyrebirdUI` gets + `LyrebirdUIExports.swift` (`@_exported import SwiftUI`). Downstream code is + then `import LyrebirdSynth` + one `#if canImport(LyrebirdUI)` selecting + `LyrebirdUI` (Apple) vs `LyrebirdUILinux` (Linux); body code beneath is + identical because both bind the same core `@UIParam`/`UIParamNode`. In-repo + precedent for `@_exported`: `Sources/LyrebirdDSP/AccelerateShim.swift`. +- **Runnable demo** — new `LyrebirdUILinuxDemo` executable target (opt-in, same + `LYREBIRD_ENABLE_LINUX_UI=1` gate): `KnobDemoSynth` (`@UIParam` + frequency/amplitude sine → `Pan2`), `KnobDemoView` (two `LinuxParameterKnob`s), + and a `main.swift` that starts the engine on `makeDefaultAudioDriver()` (ALSA + if present, else silent Offline) then runs the GTK4 loop. Run with + `LYREBIRD_ENABLE_LINUX_UI=1 swift run LyrebirdUILinuxDemo`. Turn the freq knob, + hear the pitch track (needs a live ALSA device; GUI works regardless). + +**Next steps (full cross-platform `LyrebirdUI` merge — deferred).** The symmetric +shape above still keeps two module names. A *true* single unconditional +`import LyrebirdUI` on both platforms needs the modules merged: +1. Make the `LyrebirdUI` target cross-platform: build on Linux too, with internal + `#if canImport(SwiftUI)` (Apple) / `#else` SwiftOpenUI (Linux) branches per + control, and depend on SwiftOpenUI + BackendGTK4 on Linux only. +2. Port the *remaining* controls. Done so far: `ParameterKnob`, `ParameterSlider`, + `ParameterButton`, `ParameterLabel`, `ParameterXY`, `LyrebirdScopeView`, + `LyrebirdEnvelopeView`, and `LyrebirdStatusView` (CPU meters) — all as `Linux*` + in `LyrebirdUILinux`. The core control + visualization set is now ported. + Deferred by choice: the large `LyrebirdEngineStatusView` (601 lines — a + composite of start/stop + counts + a gain slider + a mute toggle + CPU, mostly + duplicating already-ported controls) and the node-tree / message-banner / + running-processes diagnostic views; port those only if the friends round wants + them. NOTES: (a) the scope introduced the periodic-redraw + pattern for animated viz views — an `@Observable` model polled by a Foundation + `Timer` on `RunLoop.main` (which the GTK4 backend pumps ~every 5 ms), NOT + SwiftOpenUI's `.task` (whose closure runs off-main and would race the + observation registrar); its 30 Hz redraw is compile-verified but still needs + on-hardware confirmation. (b) The envelope is static (draws once, no timer). + `DrawingContext` has no text drawing, so the envelope's "L"/"R" marker letters + are omitted (dashed green/orange lines still mark loop/release) — the status + views likely need text, so plan on real `Text` views over/around a `Canvas` + rather than text inside it. +3. Fold `LyrebirdUILinux` + `LyrebirdUILinuxDemo` back into `LyrebirdUI` / + a shared demo; retire the separate module. +4. Gate the whole thing on the SwiftOpenUI dep being available (fork now, + upstream + tag later). Larger review surface — its own branch. +Do this only after the fork→upstream switch settles, so the merged module isn't +pinned to a personal fork. + +**Update 6 — shared parameter model moved to core.** The SwiftUI-free +`@UIParam` property wrapper and its `@Observable` `UIParamNode` backing object +moved from the macOS-only `LyrebirdUI` module into core `LyrebirdSynth` +(`Sources/Lyrebird/Parameters/`). Neither imports SwiftUI — only `Observation` +(stdlib, Linux-OK) — so nothing platform-gates them. `LinuxParameterKnob` now +binds a real `UIParamNode` (via a synthesizer's `@UIParam` projected value +`synth.$paramName`) with a value `range`, exactly as the macOS `ParameterKnob` +does — one parameter model drives both platforms. Because `UIParamNode` is +`@Observable`, `node.update(_:)` from a drag takes the GTK4 backend's narrow +redraw path (the fork fix), so the gesture survives. The `UIParamTests` suite +moved to `LyrebirdPortableTests` so Linux exercises it too. The placeholder +`LinuxKnobModel` is gone. No macOS API broke: every real `@UIParam` consumer +already imports `LyrebirdSynth`. Remaining: switch the SwiftOpenUI dep to +upstream `codelynx/SwiftOpenUI` + a tagged release once the PR lands. + +**Update 5 — `LyrebirdUILinux` target scaffolded (depends on the fork).** An +opt-in Linux UI target now lives in the main package: build with +`LYREBIRD_ENABLE_LINUX_UI=1` on a Linux host with `libgtk-4-dev`. It depends on +the personal fork `github.com/joshpar/SwiftOpenUI` pinned to commit `1ac66079` +(the drag fix), plus `BackendGTK4`, and holds the first ported control — +`LinuxParameterKnob` (Canvas/`DrawingContext` + `.onDrag`, `@Observable`-backed). +Gated so the **default** Linux build/CI stays lean and fork-free (verified: a +flag-off resolve fetches no fork). macOS/iOS builds never see the target. +Caveats: (1) SwiftPM writes `Package.resolved` at the package root regardless of +`--scratch-path`, so a flagged build adds the fork pin locally — **do not commit +a fork-polluted `Package.resolved`** (the committed one stays fork-free). (2) The +control binds to a local `@Observable`; the shared-model step — moving the +SwiftUI-free `@UIParam` / `UIParamNode` from the macOS-only `LyrebirdUI` module +into core `LyrebirdSynth` so macOS and Linux UIs share one parameter model — is +the next reviewed change. Switch the dep to upstream `codelynx/SwiftOpenUI` + a +tagged release once the PR lands. + +**Update 4 — `@Observable` PATCH CONFIRMED on hardware (2026-08-21).** With +`swiftopenui-drag-observable.patch` applied to a fork, the `@Observable` knob +(`spikes/SwiftOpenUIKnobObservable/`) tracks the drag continuously — so +`@UIParam` (which is `@Observable`-backed) can drive a `Canvas` control on Linux +**directly, no `@State` shim**. The patch is display-validated and PR-ready +(`spikes/SwiftOpenUIKnob/PR_DESCRIPTION.md`, `UPSTREAM_ISSUE.md`). **Verdict: +GO** — SwiftOpenUI is a viable single-codebase UI path for Linux, pending (a) +the patch landing upstream or being vendored, and (b) the per-view +`GraphicsContext → DrawingContext` drawing rewrite (mechanical, already shown to +compile). The remaining LyrebirdUI port work is now ordinary, not blocked. + +**Update 3 — `@State` drag CONFIRMED on hardware (2026-08-21).** On the Ubuntu +24.04 arm64 VM the `@State` knob tracks the drag continuously — the narrow +mutation path preserves the `GtkGestureDrag`, so the core question ("can a +Canvas control take live drag input on GTK4?") is answered **yes**. The no-fork +`@State` usage pattern is a viable single-codebase path today; LyrebirdUI's +`@UIParam` (which is `@Observable`-backed) would draw from a local `@State` and +sync to the param. The `@Observable` framework patch +(`swiftopenui-drag-observable.patch`) — which would let `@UIParam` drive the +Canvas directly, no `@State` shim — remains **compile-only**; validate it against +a fork (`PATCH_TESTING.md`) before filing the PR. + +**Update 2 — drag fix identified (compile-verified), pending display +validation.** Root cause is narrow: SwiftOpenUI's GTK4 backend has a narrow +mutation path that redraws a `Canvas` in place and preserves the drag gesture, +but it is skipped for `@Observable`-driven changes (it falls through to a full +rebuild to re-register observation, and the rebuild destroys the gesture). Two +fixes, both in `spikes/SwiftOpenUIKnob/` (`PATCH_TESTING.md`): a **no-fork +`@State` usage pattern** (the narrow path already covers `@State` Canvas +redraws), and a **framework patch** (`swiftopenui-drag-observable.patch`) that +runs the describe pass under `withObservationTracking` so `@Observable` takes +the narrow path too. Both need the user's GTK4 display to confirm; if they hold, +SwiftOpenUI remains the single-codebase path. + +**Update 1 (hardware run, Ubuntu 24.04 arm64): renders + `@Observable` +re-renders, but continuous drag is broken.** A drag handler that writes the +bound value triggers a body rebuild that replaces the GTK drag-gesture widget +(SwiftOpenUI defers that only for *drop*, not drag), so a knob moves one step +per press instead of tracking the drag — the exact interaction every LyrebirdUI +knob/slider/XY needs. See `spikes/SwiftOpenUIKnob/README.md` for the confirmed +root cause and diagnostic. This is now the gating unknown, ahead of the +GraphicsContext rewrite. Resolving it needs an upstream fix (defer the rebuild +for drag gestures, or reuse the gesture widget) or a UI structure that keeps the +gesture widget stable across value redraws. + +**Verdict: conditional GO.** The framework builds on Linux and the hard 20% +(custom drawing) is portable via a mechanical per-view `GraphicsContext → +DrawingContext` rewrite that compiles — not a drop-in, but not a wall either. +Still gated on a **display run** (Parallels) to confirm the knob actually +renders, `@Observable` drives re-render, and drag behaves — the container has no +X/Wayland. Risks unchanged: 32 stars / one author, "Stable" self-label +optimistic. Alternative if the display run disappoints: `swift-cross-ui` +(stackotter — own API, bigger rewrite) or stay headless on Linux. + +**Reproduce the display run on Parallels:** `apt install libgtk-4-dev`; a +minimal SwiftPM app depending on `SwiftOpenUI` + `BackendGTK4` (Linux) with an +`App`/`WindowGroup`, `import Observation`, a `Canvas(renderer:)` knob drawn via +`DrawingContext`, and `.onDrag`; entry `GTK4Backend().run(App.self)`; then +`swift run`. The exact ~60-line spike is available on request. + +--- + +Windows is planned separatelyWindows is planned separately and on hold (`docs/windows-support-plan.md`). diff --git a/LINUX_README.md b/LINUX_README.md new file mode 100644 index 0000000..6564d36 --- /dev/null +++ b/LINUX_README.md @@ -0,0 +1,282 @@ +# Lyrebird on Linux + +Lyrebird is a native audio-synthesis framework in Swift. You implement `Generator` +and `Synthesizer` types; the engine handles audio I/O and signal-graph evaluation. +As of **2.0**, Lyrebird runs on Linux with full parity across the engine, the +standard generator library, offline render, live audio (ALSA), MIDI, OSC, the +GTK4 GUI, and the live-coding scratchpad. + +This is the Linux guide: install, build, run, scaffold a project, and the feature +map. For the macOS/iOS story and the framework internals, see the top-level docs. + +--- + +## 1. Requirements + +**Distribution.** Ubuntu 24.04 LTS is the tested target — it matches the CI image +(`swift:6.3.3`). Other modern glibc distributions work but are untested. (An ARM64 +Ubuntu VM — e.g. Parallels on Apple silicon — is a supported dev setup.) + +**Swift toolchain.** Use the **swift.org** toolchain (6.0+), *not* a distro +package. [swiftly](https://www.swift.org/install/linux/) is the easiest installer: + +```bash +curl -O https://download.swift.org/swiftly/linux/swiftly-$(uname -m).tar.gz +tar zxf swiftly-$(uname -m).tar.gz && ./swiftly init +# in a new shell: +swiftly install latest +swift --version +``` + +If a new shell can't find `swift`/`swiftc`/`sourcekit-lsp`, add swiftly's bin +directory to `PATH` (Lyrebird's tools search `PATH`, so this is all that's needed): + +```bash +echo 'export PATH="$HOME/.local/share/swiftly/bin:$PATH"' >> ~/.bashrc +source ~/.bashrc +``` + +**System packages.** Install what you need for the features you want: + +```bash +# Build/link the core + tests: +sudo apt install build-essential pkg-config + +# Live audio + MIDI (ALSA backends). Without this, build with +# LYREBIRD_DISABLE_ALSA=1 — everything compiles, but there is no sound or MIDI: +sudo apt install libasound2-dev + +# The GTK4 GUI and the live-coding scratchpad: +sudo apt install libgtk-4-dev libgtksourceview-5-dev libfontconfig-dev +``` + +**IDE.** There is no Xcode on Linux. The maintained path is **VS Code + the +official Swift extension** (`swiftlang.swift-vscode`) — SourceKit-LSP completion, +diagnostics, LLDB debugging, and a test explorer: + +```bash +code --install-extension swiftlang.swift-vscode +``` + +Open the repository folder; the extension reads `Package.swift` automatically. +Neovim/Emacs with `sourcekit-lsp` also work. + +--- + +## 2. Build and test + +```bash +git clone git@bitbucket.org:realizedsound/lyrebird.git +cd lyrebird +swift build +swift test --no-parallel # --no-parallel avoids a known parallel-runner teardown flake +``` + +On a Linux host the manifest omits the Apple-only targets, so `swift build` / +`swift test` compile the portable surface: the core engine + generators +(`LyrebirdSynth`), the interpreted graph DSL (`LyrebirdGraphDSL`), the CLI +(`LyrebirdCLI`), the GTK4 UI (`LyrebirdUI` + backend), and the Linux demos. + +No sound stack on the box? Build and test everything except the ALSA driver: + +```bash +LYREBIRD_DISABLE_ALSA=1 swift test --no-parallel +``` + +The **LiveCompile** live-coding subsystem is a separate SwiftPM package under +`LiveCompile/` (it dynamically links the engine, so it builds on its own): + +```bash +cd LiveCompile +swift build +swift test --no-parallel +``` + +--- + +## 3. Set up a project + +Scaffold a new Swift package wired to Lyrebird with the CLI: + +```bash +swift run LyrebirdCLI new MyProject --template quickstart +cd MyProject +swift run +``` + +Templates: + +| `--template` | What you get | +|---|---| +| `quickstart` | Fastest sound — a 440 Hz sine to the speakers. | +| `basic` | Default starter synth + engine setup. | +| `demo` | A richer multi-generator example. | +| `nrt` | Offline render to a WAV (`output.wav`) — no audio device needed. | +| `score` | Render from notation (MusicXML in, WAV out). | +| `ui-demo` | A GUI scaffold (AppKit on macOS; see the GTK4 demos below on Linux). | + +The generated project calls `makeDefaultAudioDriver()`, which resolves to +`ALSAAudioDriver` on Linux (or a silent `OfflineDriver` when there is no live +backend — check `isLiveAudioAvailable`). Never name a concrete driver directly in +portable code; `makeDefaultAudioDriver()` picks the right one for how the package +was built. + +--- + +## 4. Run the built-in samples + +### Offline render — works with no audio device + +The surest first run. Renders a WAV end-to-end, no hardware involved: + +```bash +swift run LyrebirdCLI new MyRender --template nrt +cd MyRender && swift run # writes output.wav +``` + +### Live audio — needs a working sound device + +In a VM, make sure the guest has audio (`aplay -l` should list a device): + +```bash +swift run LyrebirdCLI new MyTone --template quickstart +cd MyTone && swift run # a sine tone for a few seconds +``` + +### REPL + +```bash +swift run LyrebirdCLI repl +``` + +Drops into a Swift REPL with `import LyrebirdSynth` wired up — define generators +and synthesizers and add them to a running engine live. + +### GTK4 GUI demo + +A live parameter-control window (needs `libgtk-4-dev` + a display; sound needs +`libasound2-dev` + a device): + +```bash +swift run LyrebirdUILinuxDemo +``` + +The default window shows live CPU-load meters, a live oscilloscope of the stereo +output, an example envelope plot, and controls for two parameters (frequency and +amplitude): an XY pad, a knob, a slider, and a readout each, plus a gate toggle +and reset. Every control bound to a parameter observes the same `@UIParam` node, +so moving one (say the freq knob) updates the others live — the same parameter +model the macOS SwiftUI controls use. + +Pick a focused demo with `LYREBIRD_DEMO`: + +| `LYREBIRD_DEMO` | Demo | +|---|---| +| `full` (default) | The full control panel described above. | +| `knob` | A single knob driving a sine tone. | +| `mouse` | `Mouse.X` / `Mouse.Y` / `Mouse.Click` driving synthesis from pointer position. | +| `events` | The process / event-list performance views. | +| `narrowtest` | A narrow-path redraw isolation harness (development aid). | + +```bash +LYREBIRD_DEMO=mouse swift run LyrebirdUILinuxDemo +``` + +### Live-coding scratchpad + +A GTK4 window with a real code editor that compiles and runs Swift snippets into +the live engine — Lyrebird's answer to a live-coding environment. It lives in the +`LiveCompile` package and needs `libgtksourceview-5-dev`: + +```bash +cd LiveCompile +swift build # build first: the snippet links the engine's dynamic libs +swift run LyrebirdScratchLinuxDemo +``` + +> The `swift build` step is required before `swift run`: a snippet links against +> `libLyrebirdDynamic` / `libLyrebirdLiveCompileDynamic`, which `swift build` +> produces but `swift run` alone does not. + +Type Swift, evaluate, hear it. `context` is your live session: + +```swift +context.play { OscSin.Audio(freq: 330, mul: 0.15) } +context.reportMessage("playing 330 Hz") +``` + +Scratchpad features: + +- **Swift editor** — GtkSourceView with syntax highlighting, a line-number gutter, + and auto-indent. +- **Code completion** — `Ctrl+Space` at the caret shows sourcekit-lsp completions + (types, members, parameters), filtered by what you've typed. +- **Run (fresh)** — clears the previous snippet's synths and runs the buffer. +- **Run (additive)** — layers the new snippet on top of what's already playing. +- **Line evaluation** — select one or more lines and Run evaluates just those. +- **Stop audio** — a panic button that clears all snippet audio without tearing + down the engine. +- **Live oscilloscope** — shows the session's stereo output in real time. +- **Save / load** — a File menu (`New`, `Open…`, `Save`, `Save As…`) with + `Ctrl+N` / `Ctrl+O` / `Ctrl+S` / `Ctrl+Shift+S` accelerators and native file + dialogs. Snippets are plain `.swift` files; the title shows a `●` when there are + unsaved edits. + +--- + +## 5. Feature map + +| 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 | ✅ | ALSA; needs `libasound2-dev` + a device | +| MIDI in/out | ✅ | ALSA sequencer | +| OSC | ✅ | POSIX UDP | +| GTK4 GUI (`LyrebirdUI`) | ✅ | knob / slider / label / button / XY pad + scope + envelope + CPU status; standalone windows; mouse input; on the [SwiftOpenUI](https://github.com/joshpar/SwiftOpenUI) GTK4 backend | +| Live-coding scratchpad | ✅ | `LiveCompile`; editor + completion + save/load + live scope | +| SwiftUI UI | ❌ | macOS/iOS only (Lyrebird uses GTK4 on Linux) | +| AUv3 plugin | ❌ | Apple-only | + +The GTK4 UI builds on a pinned release of the +[joshpar/SwiftOpenUI](https://github.com/joshpar/SwiftOpenUI) fork (see +`Package.swift`). To develop against a local checkout of the fork, point +`LYREBIRD_SWIFTOPENUI_LOCAL` at it: + +```bash +LYREBIRD_SWIFTOPENUI_LOCAL=/path/to/SwiftOpenUI swift build +``` + +--- + +## 6. Troubleshooting + +- **No sound / `isLiveAudioAvailable` is false.** Confirm ALSA sees a device with + `aplay -l`. In a VM, enable guest audio. To work without any sound stack, build + with `LYREBIRD_DISABLE_ALSA=1`. +- **`swiftc` / `sourcekit-lsp` not found** (common with swiftly). Add + `~/.local/share/swiftly/bin` to `PATH` (see §1). Lyrebird searches `PATH`, so + no further configuration is needed. +- **`gtk/gtk.h` or `gtksourceview/gtksource.h` not found.** Install the dev + packages: `libgtk-4-dev`, `libgtksourceview-5-dev`, `libfontconfig-dev`. +- **Scratchpad snippet fails to link** (`cannot find -lLyrebirdLiveCompileDynamic`). + Run `swift build` in `LiveCompile/` before `swift run` (see §4). +- **`Package.resolved` shows up as modified after a Linux build.** The Linux + dependency resolve records the SwiftOpenUI pin; run `git checkout Package.resolved` + before committing to keep the tree clean. + +--- + +## 7. Reference + +- `docs/linux-getting-started.md` — the original getting-started walkthrough. +- `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. +- `Sources/Lyrebird/MIDI/ALSAMIDI.swift`, `Sources/Lyrebird/OSC/OSCServer.swift` — + the Linux MIDI and OSC backends. +- `LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md` + — the live-coding subsystem. diff --git a/LiveCompile/Package.swift b/LiveCompile/Package.swift index a6489c1..1dfc088 100644 --- a/LiveCompile/Package.swift +++ b/LiveCompile/Package.swift @@ -106,3 +106,36 @@ let package = Package( ), ] ) + +#if os(Linux) +// On Linux the editor UI is SwiftOpenUI/GTK4 (the macOS AppKit surface is +// #if os(macOS)-gated out). Wire the cross-platform LyrebirdUI product — which +// @_exported re-exports SwiftOpenUI + BackendGTK4 and provides LyrebirdWindow / +// LyrebirdScopeView — into the UI target, plus a runnable minimal scratch demo: +// LYREBIRD_ENABLE_LINUX_UI is not needed; `swift run LyrebirdScratchLinuxDemo`. +if let uiIndex: Int = package.targets.firstIndex(where: { $0.name == "LyrebirdLiveCompileUI" }) { + package.targets[uiIndex].dependencies.append( + .product(name: "LyrebirdUI", package: "Lyrebird") + ) +} +package.targets.append( + .executableTarget( + name: "LyrebirdScratchLinuxDemo", + dependencies: [ + "LyrebirdLiveCompile", + "LyrebirdLiveCompileUI", + .product(name: "LyrebirdDynamic", package: "Lyrebird"), + .product(name: "LyrebirdUI", package: "Lyrebird"), + ], + path: "Sources/LyrebirdScratchLinuxDemo" + // NOTE: a live-compiled snippet links `-lLyrebirdDynamic + // -lLyrebirdLiveCompileDynamic`, so those shared libraries must exist in + // the build dir before you Run. A same-package target can't depend on a + // same-package product to force them, so build the whole package first — + // `swift build` (builds all products, incl. the …Dynamic .so's) — then + // `swift run LyrebirdScratchLinuxDemo`. `swift run` alone only builds the + // executable's own graph and would leave the snippet link unable to find + // libLyrebirdLiveCompileDynamic.so. + ) +) +#endif diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/ArtifactStagingError.swift b/LiveCompile/Sources/LyrebirdLiveCompile/ArtifactStagingError.swift index abbcbb3..9fd17e4 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/ArtifactStagingError.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/ArtifactStagingError.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) /// Errors raised while staging compile artifacts into Application Support. enum ArtifactStagingError: Error { diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/CompiledSnippet.swift b/LiveCompile/Sources/LyrebirdLiveCompile/CompiledSnippet.swift index bf190ea..790fd76 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/CompiledSnippet.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/CompiledSnippet.swift @@ -14,7 +14,7 @@ import Foundation -#if os(macOS) +#if os(macOS) || os(Linux) /// Handle to one successfully compiled and loaded snippet. /// diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/Diagnostic.swift b/LiveCompile/Sources/LyrebirdLiveCompile/Diagnostic.swift index 0f2c0a0..85fad7c 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/Diagnostic.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/Diagnostic.swift @@ -13,7 +13,7 @@ // The editor (`LyrebirdScratchView`) renders diagnostics in its // margin gutter using `(line, column)` directly. -#if os(macOS) +#if os(macOS) || os(Linux) public struct Diagnostic: Equatable, Sendable { /// 1-based line number in the **user's** snippet body. May be `nil` when the diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticParser.swift b/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticParser.swift index 617e282..ad9b875 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticParser.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticParser.swift @@ -22,7 +22,7 @@ import Foundation -#if os(macOS) +#if os(macOS) || os(Linux) public enum DiagnosticParser { diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticSeverity.swift b/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticSeverity.swift index 1559bd4..fabeb12 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticSeverity.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticSeverity.swift @@ -8,7 +8,7 @@ // // Severity classifier for a parsed swiftc diagnostic line. -#if os(macOS) +#if os(macOS) || os(Linux) public enum DiagnosticSeverity: String, Equatable, Sendable { case error diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/GraphDSLDiagnosticMapper.swift b/LiveCompile/Sources/LyrebirdLiveCompile/GraphDSLDiagnosticMapper.swift index 4e837c3..f7ce801 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/GraphDSLDiagnosticMapper.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/GraphDSLDiagnosticMapper.swift @@ -12,7 +12,7 @@ // (line, column); build errors carry no span → `line: nil` with the message // alone. -#if os(macOS) +#if os(macOS) || os(Linux) import LyrebirdGraphDSLEmbedded /// Maps interpreted-graph-DSL errors to editor diagnostics. diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/LSPCompletionItem.swift b/LiveCompile/Sources/LyrebirdLiveCompile/LSPCompletionItem.swift index 1ccf1cf..7ba38e7 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/LSPCompletionItem.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/LSPCompletionItem.swift @@ -6,9 +6,9 @@ // LyrebirdLiveCompile // -// One parsed code-completion candidate from `sourcekit-lsp`. macOS only. +// One parsed code-completion candidate from `sourcekit-lsp`. macOS/Linux only. -#if os(macOS) +#if os(macOS) || os(Linux) /// One code-completion candidate returned by sourcekit-lsp. public struct LSPCompletionItem: Sendable, Equatable { diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompileError.swift b/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompileError.swift index f360ade..b384e39 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompileError.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompileError.swift @@ -12,7 +12,7 @@ import Foundation -#if os(macOS) +#if os(macOS) || os(Linux) public enum LiveCompileError: Error, CustomStringConvertible, Equatable, Sendable { /// `xcrun -f swiftc` and the fallback paths all failed. diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompiler.swift b/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompiler.swift index 4bb1873..0c47fd6 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompiler.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompiler.swift @@ -9,14 +9,16 @@ // `LiveCompiler.compile(source:)` shells out to `swiftc -emit-library`, then // `dlopen`s the resulting dylib and resolves the snippet entry symbol. No UI, // no `SynthesisEngine` binding (those are handled by the harness and session -// layers). macOS only — iOS cannot exec swiftc. +// layers). macOS/Linux only — iOS cannot exec swiftc. import Foundation -#if os(macOS) -import Darwin +#if canImport(Darwin) +import Darwin // dlopen / dlsym / dlerror +#elseif canImport(Glibc) +import Glibc // dlopen / dlsym / dlerror on Linux #endif -#if os(macOS) +#if os(macOS) || os(Linux) /// Symbol the snippet preamble must export. Snippets declare: /// @@ -26,10 +28,37 @@ import Darwin /// ``` public let lyrebirdSnippetEntrySymbol: String = "lyrebird_snippet_entry" +/// Platform shared-library extension: `dylib` (Mach-O) on macOS, `so` (ELF) on +/// Linux. A snippet is `swiftc -emit-library`'d to `lib.`, and the +/// resident Lyrebird library is `libLyrebirdDynamic.`. +#if os(macOS) +let livecompileSharedLibraryExtension: String = "dylib" +#else +let livecompileSharedLibraryExtension: String = "so" +#endif + +/// Search `$PATH` for an executable named `name`, returning the first hit or +/// `nil`. Covers toolchains installed outside the hard-coded locations — most +/// notably a swiftly install (`~/.local/share/swiftly/bin`) on Linux, which puts +/// both `swiftc` and `sourcekit-lsp` on `$PATH` but not in `/usr/bin`. +func livecompileExecutableOnPath(_ name: String) -> String? { + guard let pathEnv: String = ProcessInfo.processInfo.environment["PATH"] else { return nil } + for dir: Substring in pathEnv.split(separator: ":") where !dir.isEmpty { + let base: String = String(dir) + let candidate: String = base.hasSuffix("/") ? base + name : base + "/" + name + if FileManager.default.isExecutableFile(atPath: candidate) { + return candidate + } + } + return nil +} + /// One-shot snippet compiler. Stateless — every `compile(source:)` allocates a -/// fresh temp dir, dylib name, and `dlopen` handle. +/// fresh temp dir, shared-library name, and `dlopen` handle. public enum LiveCompiler { + static var sharedLibraryExtension: String { livecompileSharedLibraryExtension } + /// Compile `source` to a dylib and resolve the snippet entry symbol. /// /// - Parameters: @@ -52,7 +81,7 @@ public enum LiveCompiler { let workDir: URL = FileManager.default.temporaryDirectory .appendingPathComponent("LyrebirdLiveCompile-\(snippetID)", isDirectory: true) let sourcePath: String = workDir.appendingPathComponent("Snippet.swift").path - let dylibPath: String = workDir.appendingPathComponent("lib\(moduleName).dylib").path + let dylibPath: String = workDir.appendingPathComponent("lib\(moduleName).\(sharedLibraryExtension)").path do { try FileManager.default.createDirectory( @@ -112,11 +141,17 @@ public enum LiveCompiler { /// First-success search: /// 1. `xcrun -f swiftc` (honours `DEVELOPER_DIR` and the user's active Xcode). - /// 2. Hard-coded toolchain paths. + /// 2. An executable `swiftc` on `$PATH` — covers a swiftly install + /// (`~/.local/share/swiftly/bin`) and any Linux toolchain layout that + /// isn't in the hard-coded list. + /// 3. Hard-coded toolchain paths. static func findSwiftc() throws -> String { if let xcrun: String = swiftcViaXcrun() { return xcrun } + if let onPath: String = swiftcOnPath() { + return onPath + } let candidates: [String] = [ "/usr/bin/swiftc", "/usr/local/bin/swiftc", @@ -128,6 +163,11 @@ public enum LiveCompiler { throw LiveCompileError.swiftcNotFound } + /// Search `$PATH` for an executable `swiftc`. Returns the first hit, or `nil`. + static func swiftcOnPath() -> String? { + livecompileExecutableOnPath("swiftc") + } + /// `xcrun --show-sdk-path` — returns the macOS SDK path used by the user's /// active Xcode. `nil` when xcrun is missing or returns non-zero. static func sdkPathViaXcrun() -> String? { diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/LiveSession.swift b/LiveCompile/Sources/LyrebirdLiveCompile/LiveSession.swift index 6817e0b..acc3cbf 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/LiveSession.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/LiveSession.swift @@ -12,7 +12,7 @@ // `CompiledSnippet` so the dylibs stay mapped — see the leak-by-design note in // `CompiledSnippet.swift`. -#if os(macOS) +#if os(macOS) || os(Linux) import Foundation import LyrebirdSynth @@ -665,6 +665,13 @@ public final class LiveSession: @unchecked Sendable { for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) { args += ["-Xcc", "-fmodule-map-file=\(url.path)"] } + #if os(Linux) + // Source-only system-library module maps (CALSA, LyrebirdC) — see the + // helper. Without CALSA's, a Linux `import LyrebirdSynth` fails to resolve. + for url: URL in LiveSession.discoverSourceSystemModuleMaps(in: importPaths) { + args += ["-Xcc", "-fmodule-map-file=\(url.path)"] + } + #endif return args } @@ -690,7 +697,15 @@ public final class LiveSession: @unchecked Sendable { args += ["-Xlinker", "-rpath", "-Xlinker", path.path] } } else { + #if os(macOS) args += ["-Xlinker", "-undefined", "-Xlinker", "dynamic_lookup"] + #else + // ELF has no Mach-O flat-namespace deferred lookup: a snippet resolves + // Lyrebird symbols by NEEDED-linking libLyrebirdDynamic.so, which needs + // it present in a -L path (i.e. hasDylib == true). Reaching here on + // Linux means no such library was found; emit no link flag so the link + // fails loudly rather than adding a macOS-only one. + #endif } return args } @@ -754,6 +769,44 @@ public final class LiveSession: @unchecked Sendable { return found } + #if os(Linux) + /// Linux only: locate the `CALSA` **system-library** module map, which lives + /// only in the package *source* tree (`Sources/CALSA/module.modulemap`), + /// never in the build dir — a `.systemLibrary` target emits no + /// `.build/module.modulemap`. `LyrebirdSynth` transitively imports + /// `CALSA` on Linux (the ALSA driver), so a snippet's `import LyrebirdSynth` + /// fails with `missing required module 'CALSA'` unless the map is surfaced. + /// macOS never hits this (Core Audio, no CALSA import). `LyrebirdC` is a + /// regular C target and IS covered by `discoverSPMModuleMaps` (build-tree + /// map) — adding its source map too would `redefinition of module 'LyrebirdC'`. + /// Walks up from each import path (bounded) to the package root. + static func discoverSourceSystemModuleMaps(in importPaths: [URL]) -> [URL] { + let maxWalk: Int = 8 + let relativeMaps: [String] = [ + "Sources/CALSA/module.modulemap", + ] + var found: [URL] = [] + var visited: Set = Set() + for start: URL in importPaths { + var cur: URL = start + for _ in 0../` directory @@ -781,7 +834,10 @@ public final class LiveSession: @unchecked Sendable { // (→ libLyrebirdDynamic.dylib); the module/target is `LyrebirdSynth` // (LyrebirdSynth.swiftmodule). The consumer-facing `Lyrebird` product // is static and produces no dylib, so it is not a marker here. - let markers: [String] = ["libLyrebirdDynamic.dylib", "LyrebirdSynth.swiftmodule"] + let markers: [String] = [ + "libLyrebirdDynamic.\(livecompileSharedLibraryExtension)", + "LyrebirdSynth.swiftmodule", + ] for start: URL in candidates { var cur: URL = start for _ in 0.. Bool { FileManager.default.fileExists( - atPath: buildDir.appendingPathComponent("libLyrebirdDynamic.dylib").path + atPath: buildDir.appendingPathComponent( + "libLyrebirdDynamic.\(livecompileSharedLibraryExtension)" + ).path ) } diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionArtifactStaging.swift b/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionArtifactStaging.swift index ee4a053..9ddc121 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionArtifactStaging.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionArtifactStaging.swift @@ -19,7 +19,7 @@ import Foundation -#if os(macOS) +#if os(macOS) || os(Linux) extension LiveSession { @@ -178,6 +178,16 @@ extension LiveSession { // the temp dir is deleted. stageClangModuleMaps(from: src, writeInto: staging, finalRoot: dest) + #if os(Linux) + // 3.5. CALSA (the ALSA system library) has no `.build/` map in the + // build dir — its module map lives only in the package source — so the + // steps above miss it and a snippet's `import LyrebirdSynth` can't resolve + // CALSA from the staged root. Copy the source module dir (map + relative + // include/) into a self-contained `CALSA.build/` that `discoverSPMModuleMaps` + // then finds at the staged location. macOS never imports CALSA. + stageCALSAModuleMap(from: src, writeInto: staging) + #endif + // Receipt: store the source stamp so the next call can skip an unchanged // source. let stampText: String = String(srcStamp.timeIntervalSince1970) @@ -218,10 +228,29 @@ extension LiveSession { includingPropertiesForKeys: nil ) else { return [] } return entries.filter { - $0.pathExtension == "dylib" && $0.lastPathComponent.hasPrefix("libLyrebird") + $0.pathExtension == livecompileSharedLibraryExtension + && $0.lastPathComponent.hasPrefix("libLyrebird") } } + #if os(Linux) + /// Copy the CALSA source module dir (`Sources/CALSA/`: `module.modulemap` + + /// `include/calsa-shim.h`) into `staging/CALSA.build/`, so the staged root is a + /// self-contained compile root for a snippet that transitively imports CALSA. + /// The map's header path is relative, so it resolves verbatim at the staged + /// location. Best-effort: if the source map isn't found (e.g. a detached build + /// dir), staging proceeds without it and the snippet compile surfaces the gap. + private static func stageCALSAModuleMap(from src: URL, writeInto staging: URL) { + let fm: FileManager = FileManager.default + guard let calsaMap: URL = LiveSession.discoverSourceSystemModuleMaps(in: [src]).first else { + return + } + let calsaSrcDir: URL = calsaMap.deletingLastPathComponent() + let stagedDir: URL = staging.appendingPathComponent("CALSA.build", isDirectory: true) + try? fm.copyItem(at: calsaSrcDir, to: stagedDir) + } + #endif + /// A `dest` is safe to replace when it doesn't exist, is empty, or looks like /// a prior staging root (has a receipt or a `Modules/` dir). private static func isReplaceableStagingDest(_ dest: URL) -> Bool { diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionError.swift b/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionError.swift index 4aa6503..0307b80 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionError.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionError.swift @@ -11,7 +11,7 @@ // cases (toolchain missing, dlopen failure, etc.) pass through under // `.compilerError`. -#if os(macOS) +#if os(macOS) || os(Linux) public enum LiveSessionError: Error, CustomStringConvertible, Sendable { /// Snippet failed to compile. `diagnostics` are already line-mapped via the diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionGraphDSL.swift b/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionGraphDSL.swift index c2ccebf..09cc4c0 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionGraphDSL.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionGraphDSL.swift @@ -13,7 +13,7 @@ // across the Swift and DSL paths. The only difference is speed: a graph edit // re-evaluates in microseconds instead of a swiftc round-trip. -#if os(macOS) +#if os(macOS) || os(Linux) import LyrebirdSynth import LyrebirdGraphDSLEmbedded diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetCompletionService.swift b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetCompletionService.swift index f302f54..a6a94df 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetCompletionService.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetCompletionService.swift @@ -17,9 +17,9 @@ // that file, which is what lets `import LyrebirdSynth` and the injected // `context: SnippetContext` resolve for an otherwise free-standing file. // -// macOS only. +// macOS/Linux only. -#if os(macOS) +#if os(macOS) || os(Linux) import Foundation /// Provides code completion for a live-coding editor buffer. @@ -92,6 +92,13 @@ public actor SnippetCompletionService { for url: URL in LiveSession.discoverSPMModuleMaps(in: session.importPaths) { args += ["-Xcc", "-fmodule-map-file=\(url.path)"] } + #if os(Linux) + // CALSA's system-library module map is source-only (see LiveSession); + // completion needs it too, or `import LyrebirdSynth` fails to resolve. + for url: URL in LiveSession.discoverSourceSystemModuleMaps(in: session.importPaths) { + args += ["-Xcc", "-fmodule-map-file=\(url.path)"] + } + #endif for path: URL in session.librarySearchPaths { args += ["-L", path.path] } @@ -106,8 +113,16 @@ public actor SnippetCompletionService { } private static func sdkPath() -> String? { + // Linux needs no `-sdk`, and `xcrun` does not exist there. Crucially, + // guard the spawn: on Linux, `Process.run()` throws when the launch path + // is missing, and a subsequent `waitUntilExit()` on a process that never + // started BLOCKS FOREVER (it is a no-op on macOS) — the completion hang. + // The macOS xcrun helpers in LiveCompiler avoid this by checking + // `isExecutableFile(atPath:)` first; do the same here. + let xcrunPath: String = "/usr/bin/xcrun" + guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil } let p: Process = Process() - p.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + p.executableURL = URL(fileURLWithPath: xcrunPath) p.arguments = ["--show-sdk-path", "--sdk", "macosx"] let out: Pipe = Pipe() p.standardOutput = out @@ -123,12 +138,20 @@ public actor SnippetCompletionService { /// Minimum-deployment target triple. Arch matches the running process; /// the OS floor matches the package's `macOS 15` minimum. private static func targetTriple() -> String { + #if os(macOS) #if arch(arm64) - let arch: String = "arm64" + return "arm64-apple-macosx15.0" #else - let arch: String = "x86_64" + return "x86_64-apple-macosx15.0" + #endif + #else + // Linux GNU triple; the Swift/LLVM spelling of arm64 is `aarch64`. + #if arch(arm64) + return "aarch64-unknown-linux-gnu" + #else + return "x86_64-unknown-linux-gnu" + #endif #endif - return "\(arch)-apple-macosx15.0" } /// Launch sourcekit-lsp and open the (empty) document. Call once before the diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetContext.swift b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetContext.swift index d221bf7..1184849 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetContext.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetContext.swift @@ -16,7 +16,7 @@ // synth that the host will track for re-evaluation cleanup, and report back via // the test-friendly `reportSampleRate(_:)` / `reportMessage(_:)` helpers. -#if os(macOS) +#if os(macOS) || os(Linux) import LyrebirdSynth public final class SnippetContext { diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetEntry.swift b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetEntry.swift index 607ff83..ca08906 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetEntry.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetEntry.swift @@ -8,7 +8,7 @@ // // C ABI signature of the snippet's exported entry point. -#if os(macOS) +#if os(macOS) || os(Linux) /// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. The host /// passes a pointer to a `LiveSession` (or harness context) here; snippets need diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetHarness.swift b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetHarness.swift index dd0bbc8..c3c7566 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetHarness.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetHarness.swift @@ -12,7 +12,7 @@ // from the opaque pointer the host hands in. The user's body is dropped in as // the function body. -#if os(macOS) +#if os(macOS) || os(Linux) public enum SnippetHarness { diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/SourceKitLSPClient.swift b/LiveCompile/Sources/LyrebirdLiveCompile/SourceKitLSPClient.swift index 8906109..68e4a0b 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/SourceKitLSPClient.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/SourceKitLSPClient.swift @@ -12,9 +12,9 @@ // `initialize` / `initialized`, `textDocument/didOpen` / `didChange`, and // `textDocument/completion`. // -// macOS only — the whole live-compile surface shells out to the toolchain. +// macOS/Linux only — the whole live-compile surface shells out to the toolchain. -#if os(macOS) +#if os(macOS) || os(Linux) import Foundation /// Nanoseconds in one second — for `Task.sleep`. @@ -80,8 +80,22 @@ public final class SourceKitLSPClient: @unchecked Sendable { /// Resolve `sourcekit-lsp` from the active toolchain via `xcrun`, falling /// back to the conventional Xcode path. private static func resolveExecutable() -> URL { + // Guard the xcrun spawn: `xcrun` is macOS-only, and on Linux + // `Process.run()` throws for a missing launch path while a following + // `waitUntilExit()` on the never-started process BLOCKS FOREVER (a no-op + // on macOS). Skip straight to the conventional path there, where the + // toolchain ships `/usr/bin/sourcekit-lsp`. + let xcrunPath: String = "/usr/bin/xcrun" + guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { + // No xcrun (Linux): prefer a `sourcekit-lsp` on $PATH (swiftly, a + // custom toolchain, …) over the conventional /usr/bin location. + if let onPath: String = livecompileExecutableOnPath("sourcekit-lsp") { + return URL(fileURLWithPath: onPath) + } + return URL(fileURLWithPath: "/usr/bin/sourcekit-lsp") + } let xcrun: Process = Process() - xcrun.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + xcrun.executableURL = URL(fileURLWithPath: xcrunPath) xcrun.arguments = ["--find", "sourcekit-lsp"] let out: Pipe = Pipe() xcrun.standardOutput = out diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/SourceKitLSPError.swift b/LiveCompile/Sources/LyrebirdLiveCompile/SourceKitLSPError.swift index d8ab326..4292c8d 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/SourceKitLSPError.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/SourceKitLSPError.swift @@ -6,9 +6,9 @@ // LyrebirdLiveCompile // -// Errors surfaced by ``SourceKitLSPClient``. macOS only. +// Errors surfaced by ``SourceKitLSPClient``. macOS/Linux only. -#if os(macOS) +#if os(macOS) || os(Linux) /// A failure from the `sourcekit-lsp` client. public enum SourceKitLSPError: Error, CustomStringConvertible { diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/SwapQuantize.swift b/LiveCompile/Sources/LyrebirdLiveCompile/SwapQuantize.swift index 7fbad58..0d83215 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/SwapQuantize.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/SwapQuantize.swift @@ -12,7 +12,7 @@ // few hundred ms after ⌘↩, then the swap lands exactly on the downbeat rather // than whenever the compile happened to finish. -#if os(macOS) +#if os(macOS) || os(Linux) import Foundation import LyrebirdSynth diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/SwiftFormatter.swift b/LiveCompile/Sources/LyrebirdLiveCompile/SwiftFormatter.swift index 3797b42..7db0478 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/SwiftFormatter.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/SwiftFormatter.swift @@ -7,14 +7,14 @@ // LyrebirdLiveCompile — snippet source formatting. // // Shells out to the toolchain's `swift-format` (the same way `LiveCompiler` -// shells to `swiftc`) to pretty-print a snippet. macOS only — iOS cannot exec -// subprocesses. Writes the source to a temp file and runs `swift-format format +// shells to `swiftc`) to pretty-print a snippet. macOS/Linux only — iOS cannot +// exec subprocesses. Writes the source to a temp file and runs `swift-format format // `, capturing stdout — avoids the write-stdin/read-stdout pipe deadlock // a streaming approach risks on large output. import Foundation -#if os(macOS) +#if os(macOS) || os(Linux) /// Stateless `swift-format` wrapper. public enum SwiftFormatter { @@ -72,14 +72,20 @@ public enum SwiftFormatter { label: "net.realizedsound.lyrebird.swift-format-drain", attributes: .concurrent ) - var outData: Data = Data() - var errData: Data = Data() + // Box the drained bytes in reference cells: on Linux the `DispatchQueue` + // closures are `@Sendable` and cannot mutate a captured `var`. Each + // closure writes its own box (no shared mutation), and `group.wait()` + // fences before the reads below. + let outBox: SwiftFormatterDataBox = SwiftFormatterDataBox() + let errBox: SwiftFormatterDataBox = SwiftFormatterDataBox() group.enter() - drainQueue.async { outData = outHandle.readDataToEndOfFile(); group.leave() } + drainQueue.async { outBox.data = outHandle.readDataToEndOfFile(); group.leave() } group.enter() - drainQueue.async { errData = errHandle.readDataToEndOfFile(); group.leave() } + drainQueue.async { errBox.data = errHandle.readDataToEndOfFile(); group.leave() } group.wait() process.waitUntilExit() + let outData: Data = outBox.data + let errData: Data = errBox.data guard process.terminationStatus == 0 else { let stderr: String = String(data: errData, encoding: .utf8) ?? "" @@ -137,4 +143,13 @@ public enum SwiftFormatter { } } +/// Reference cell for one drained pipe's bytes, so the concurrent drain closures +/// write through a reference instead of mutating a captured `var` (which the +/// Linux `@Sendable` `DispatchQueue` closures forbid). `@unchecked Sendable`: +/// each instance is written by exactly one closure and read only after +/// `DispatchGroup.wait()`. +private final class SwiftFormatterDataBox: @unchecked Sendable { + var data: Data = Data() +} + #endif diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/SwiftFormatterError.swift b/LiveCompile/Sources/LyrebirdLiveCompile/SwiftFormatterError.swift index aca26ce..2408d14 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/SwiftFormatterError.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/SwiftFormatterError.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) /// Errors raised while formatting snippet source with `swift-format`. public enum SwiftFormatterError: Error { diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/SwiftToolchainStatus.swift b/LiveCompile/Sources/LyrebirdLiveCompile/SwiftToolchainStatus.swift index ea89545..c910cf6 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/SwiftToolchainStatus.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/SwiftToolchainStatus.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) /// Result of probing for a usable Swift toolchain (the Swift scratchpad compiles /// snippets by shelling out to `swiftc`, which requires Xcode or the Command Line diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/ToolchainProbe.swift b/LiveCompile/Sources/LyrebirdLiveCompile/ToolchainProbe.swift index 4784a36..2e50bf1 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/ToolchainProbe.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/ToolchainProbe.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) import Foundation /// Detects whether a usable Swift toolchain is present, so the app can warn the user diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/WrappedSnippet.swift b/LiveCompile/Sources/LyrebirdLiveCompile/WrappedSnippet.swift index 0f05e80..d18180c 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/WrappedSnippet.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/WrappedSnippet.swift @@ -12,7 +12,7 @@ // from each swiftc-reported line so error rows point back at the row the user // typed. -#if os(macOS) +#if os(macOS) || os(Linux) public struct WrappedSnippet: Equatable { public let source: String diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/LinuxScratchView.swift b/LiveCompile/Sources/LyrebirdLiveCompileUI/LinuxScratchView.swift new file mode 100644 index 0000000..05c43c1 --- /dev/null +++ b/LiveCompile/Sources/LyrebirdLiveCompileUI/LinuxScratchView.swift @@ -0,0 +1,347 @@ +// LinuxScratchView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// Minimal Linux/GTK4 live-coding scratch surface. The macOS editor +// (LyrebirdScratchView / NSTextView) is `#if os(macOS)`-gated elsewhere; this is +// the SwiftOpenUI counterpart: a plain code editor + Run/Clear + a console, +// driving a `LiveSession` (compile the snippet to a .so, dlopen it, run it). No +// syntax highlighting / gutter / completion — that is the full-parity +// GtkSourceView editor (a later step). `import LyrebirdUI` re-exports the +// SwiftOpenUI View DSL + the GTK4 backend and provides `LyrebirdScopeView`. +#if os(Linux) +import Foundation +import Observation +import LyrebirdSynth +import LyrebirdLiveCompile // LiveSession +import LyrebirdUI + +/// A seed snippet: the fastest path to sound — a bare generator graph via +/// `context.play { … }` — plus a console line. +public let lyrebirdLinuxScratchSeed: String = """ +// Edit, then Run. `context` is your live LiveSession. Ctrl+Space for completions. +context.play { OscSin.Audio(freq: 330, mul: 0.15) } +context.reportMessage("playing 330 Hz") +""" + +/// Observable state for the Linux scratch view: the running flag and the console +/// log. The `LiveSession` compiles/runs off the main thread; results are folded +/// back onto the main actor (== the GTK main loop) so the `@Observable` reads +/// refresh the view. +/// +/// `@unchecked Sendable`: main-thread-confined UI state plus an +/// `@unchecked Sendable` `LiveSession`; the run closure hops to the main actor +/// before touching `console` / `isRunning`. +@Observable +public final class LinuxScratchModel: @unchecked Sendable { + + public var console: String = "" + public var isRunning: Bool = false + + /// The editor's document text and current selection. Owned by the model (not + /// the view) so file open/save and the dirty flag have one source of truth. + public var source: String + public var selection: String = "" + + /// Path of the file backing the document, or `nil` for an unsaved buffer. + public var currentPath: String? = nil + /// Set when the buffer has unsaved edits; drives the title's `●` marker. + public var isDirty: Bool = false + /// Suppresses dirty-marking while the model itself replaces the text (new / + /// open), so a load doesn't immediately look unsaved. + @ObservationIgnored private var suppressDirty: Bool = false + + @ObservationIgnored public let session: LiveSession + @ObservationIgnored public let completionService: SnippetCompletionService + /// Imperative handle to push loaded text into the reused editor widget. + @ObservationIgnored public let editor: CodeEditorController = CodeEditorController() + + public init(session: LiveSession, initialSource: String = lyrebirdLinuxScratchSeed) { + self.session = session + self.source = initialSource + self.completionService = SnippetCompletionService(session: session) + } + + /// The editor's two-way binding calls this; marks the buffer dirty unless the + /// change came from a programmatic load. Ignores an unchanged value so a + /// widget echo of the same text never flips the dirty flag — which also makes + /// a load robust whether or not GtkSourceView delivers its change signal + /// synchronously: `replaceDocument` has already set `source`, so the echoed + /// value compares equal and returns here before touching `isDirty`. + public func setSource(_ newValue: String) { + guard newValue != source else { return } + source = newValue + if !suppressDirty { isDirty = true } + } + + /// A short title for the window/header: the filename (or `untitled.swift`) + /// with a leading `●` when there are unsaved edits. + public var displayTitle: String { + let name: String = currentPath.map(Self.lastComponent) ?? "untitled.swift" + return (isDirty ? "● " : "") + name + } + + /// Ctrl+Space completion source for the editor: the buffer text + caret + /// (line, column) → sourcekit-lsp completions mapped to editor candidates. + /// Errors (server hiccups) yield no candidates rather than surfacing. + public var completionProvider: @Sendable (String, Int, Int) async -> [CodeCompletionItem] { + let service: SnippetCompletionService = completionService + return { (text: String, line: Int, column: Int) in + let items: [LSPCompletionItem] = (try? await service.completions( + userBody: text, line: line, character: column)) ?? [] + return items.map { (item: LSPCompletionItem) in + CodeCompletionItem(label: item.label, insertText: item.insertText) + } + } + } + + /// Compile + run `source`. `additive` keeps the previous run's synths; + /// otherwise they are cleared first. Non-blocking: swiftc runs off-main. + public func run(source: String, additive: Bool) { + guard !isRunning else { return } + isRunning = true + append(additive ? "▶ running (additive)…" : "▶ running…") + let sess: LiveSession = session + Task { [weak self] in + do { + _ = try await sess.compileAndRunAsync(source, additive: additive) + let messages: [String] = sess.drainMessages() + await self?.finish(ok: true, messages: messages, error: nil) + } catch { + let messages: [String] = sess.drainMessages() + await self?.finish(ok: false, messages: messages, error: "\(error)") + } + } + } + + public func clear() { + console = "" + } + + /// Panic valve: stop and remove all snippet audio without tearing down the + /// engine (``LiveSession/resetAll()``). Leaves the editor and session intact + /// so the next Run starts clean. + /// + /// Guarded by `isRunning` for the same reason the macOS host's + /// `resetSession()` guards on `isCompiling`: `resetAll()`'s documented + /// precondition forbids running it concurrently with an in-flight + /// `compileAndRunAsync`, whose `clearTracked()`/`runEntry` interleave can + /// leak a just-added synth. A no-op while a compile is running is the safe + /// choice — the audio it starts is cleared by the next Stop. + public func killAudio() { + guard !isRunning else { return } + session.resetAll() + append("■ audio stopped") + } + + // MARK: - File open / save + // + // Snippets are plain Swift source, so a document is just a `.swift` text + // file. The native `GtkFileDialog` (via `GTK4FileDialog`) picks the path; + // its completion runs on the GTK main thread, same as these methods (they + // are invoked from button actions), so the `@Observable` writes are safe. + + /// Reset to a fresh unsaved buffer seeded with the starter snippet. + public func newDocument() { + replaceDocument(text: lyrebirdLinuxScratchSeed, path: nil) + append("✎ new document") + } + + /// Present an Open dialog, then load the chosen file. + public func openDocument() { + GTK4FileDialog.open(title: "Open Lyrebird snippet") { [weak self] (path: String?) in + guard let self, let path: String = path else { return } + self.loadFile(path) + } + } + + /// Load `path` into the editor (replacing the buffer). + public func loadFile(_ path: String) { + do { + let text: String = try String(contentsOfFile: path, encoding: .utf8) + replaceDocument(text: text, path: path) + append("📂 opened " + Self.lastComponent(path)) + } catch { + append("✗ open failed: \(error)") + } + } + + /// Save to the current path, or fall through to Save As when there is none. + public func save() { + if let path: String = currentPath { + writeFile(path) + } else { + saveAs() + } + } + + /// Present a Save dialog (pre-filled with the current name), then write. + public func saveAs() { + let suggested: String = currentPath.map(Self.lastComponent) ?? "untitled.swift" + GTK4FileDialog.save(title: "Save Lyrebird snippet", suggestedName: suggested) { [weak self] (path: String?) in + guard let self, let path: String = path else { return } + self.writeFile(path) + } + } + + private func writeFile(_ path: String) { + do { + try source.write(toFile: path, atomically: true, encoding: .utf8) + currentPath = path + isDirty = false + append("💾 saved " + Self.lastComponent(path)) + } catch { + append("✗ save failed: \(error)") + } + } + + /// Replace the buffer with `text` and adopt `path`, without marking dirty. + /// Pushes into the live widget too — the reused editor doesn't otherwise + /// mirror an external text change (see `CodeEditorController`). + private func replaceDocument(text: String, path: String?) { + suppressDirty = true + source = text + editor.setText(text) + currentPath = path + isDirty = false + suppressDirty = false + } + + private static func lastComponent(_ path: String) -> String { + (path as NSString).lastPathComponent + } + + @MainActor + private func finish(ok: Bool, messages: [String], error: String?) { + for message: String in messages { + append(message) + } + if let error: String = error { + append("✗ " + error) + } else { + append("✓ done") + } + isRunning = false + } + + private func append(_ line: String) { + console += (console.isEmpty ? "" : "\n") + line + } +} + +/// The minimal Linux scratch editor: a `TextEditor` over the snippet source, +/// Run (fresh / additive) + Clear buttons, a live oscilloscope of the session's +/// output, and a console. Host it in a `LyrebirdWindow` or a `WindowGroup`. +public struct LyrebirdScratchLinuxView: View { + + @State private var model: LinuxScratchModel + + /// - Parameters: + /// - session: The `LiveSession` that compiles + runs snippets. + /// - initialSource: Seed editor text. Defaults to a play-a-tone snippet. + public init(session: LiveSession, initialSource: String = lyrebirdLinuxScratchSeed) { + _model = State(wrappedValue: LinuxScratchModel(session: session, initialSource: initialSource)) + } + + /// Host an externally-owned model — used when the app also wires the model's + /// file actions into the menu bar (`.commands`), which needs the same + /// instance the view renders. + public init(model: LinuxScratchModel) { + _model = State(wrappedValue: model) + } + + /// What Run evaluates: the selection if the user has selected something + /// (non-whitespace), otherwise the whole document. + private var evaluationSource: String { + model.selection.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + ? model.source : model.selection + } + + /// Append a hint to the Run buttons when a selection is what will run. + private func runLabel(base: String) -> String { + model.selection.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + ? base + : base + " — selection" + } + + public var body: some View { + VStack(alignment: .leading, spacing: 8) { + Text("Lyrebird — Linux scratch — " + model.displayTitle) + + // File actions (New / Open… / Save / Save As…) live in the menu bar + // with Ctrl+N/O/S accelerators — see `lyrebirdScratchFileCommands`, + // wired via `.commands` on the demo's WindowGroup. A snippet is plain + // Swift source, so a document is just a `.swift` text file, saved and + // loaded through the native GtkFileDialog. + + // GtkSourceView-backed editor: Swift syntax highlighting + gutter. + // The selection is mirrored out so Run can evaluate just the selected + // lines (like the macOS editor); with nothing selected it runs the + // whole buffer. The controller lets a file open replace the buffer. + CodeEditor( + text: Binding(get: { model.source }, set: { model.setSource($0) }), + selection: Binding(get: { model.selection }, set: { model.selection = $0 }), + controller: model.editor, + completionProvider: model.completionProvider + ) + .frame(height: 260) + + HStack(spacing: 8) { + Button { + model.run(source: evaluationSource, additive: false) + } label: { + Text(model.isRunning ? "Running…" : runLabel(base: "Run (fresh)")) + } + Button { + model.run(source: evaluationSource, additive: true) + } label: { + Text(runLabel(base: "Run (additive)")) + } + Button { + model.killAudio() + } label: { + Text("Stop audio") + } + Button { + model.clear() + } label: { + Text("Clear") + } + } + + if let scope: ScopeCapture = model.session.scope { + LyrebirdScopeView(capture: scope) + } + + Text("Console") + .font(.caption) + .foregroundStyle(.secondary) + Text(model.console) + .font(.caption) + .monospacedDigit() + .frame(height: 140) + } + .padding() + } +} + +/// The scratchpad's File menu commands — New / Open… / Save / Save As… — with +/// Ctrl+N / Ctrl+O / Ctrl+S / Ctrl+Shift+S accelerators (SwiftOpenUI maps the +/// `.command` modifier to Ctrl on Linux). Attach to the hosting `WindowGroup` +/// with `.commands { lyrebirdScratchFileCommands(model: model) }`; SwiftOpenUI +/// declares commands on the Scene, not inside a View, so the app must own the +/// model and pass the same instance to `LyrebirdScratchLinuxView(model:)`. +@CommandsBuilder +public func lyrebirdScratchFileCommands(model: LinuxScratchModel) -> some Commands { + CommandGroup(replacing: .newItem) { + CommandMenuItem("New", shortcut: KeyboardShortcut("n")) { model.newDocument() } + CommandMenuItem("Open…", shortcut: KeyboardShortcut("o")) { model.openDocument() } + } + CommandGroup(replacing: .saveItem) { + CommandMenuItem("Save", shortcut: KeyboardShortcut("s")) { model.save() } + CommandMenuItem("Save As…", shortcut: KeyboardShortcut("s", modifiers: [.command, .shift])) { model.saveAs() } + } +} +#endif diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md index 51acfcd..cb65e35 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md +++ b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md @@ -15,9 +15,12 @@ Compile diagnostics from a failing snippet are parsed by `DiagnosticParser` and rendered beneath the editor with line numbers already remapped from the wrapped source back to the user's snippet coordinates. -The view is macOS-only — `LyrebirdLiveCompile` shells out to `swiftc`, which is -unavailable on iOS. The nested `LiveCompile/` sub-package declares -`platforms: [.macOS(.v15)]` and cannot be added to an iOS target. +`LyrebirdScratchView` (the `NSTextView` editor described here) is macOS-only, but +the scratchpad itself runs on **Linux** too, through a GTK4 counterpart — +`LyrebirdScratchLinuxView` / `LinuxScratchModel` on the SwiftOpenUI backend. Both +drive the same `LyrebirdLiveCompile` engine; only the editor UI differs. See +[Linux (GTK4)](#linux-gtk4) below. What is genuinely unavailable is **iOS**: +`LyrebirdLiveCompile` shells out to `swiftc`, which iOS does not provide. > Note: **Swift mode needs a Swift toolchain** (Xcode or the Command Line Tools) — > it compiles snippets with `swiftc`. At launch the app probes for one @@ -442,9 +445,39 @@ row in the wrapped document. Completion is Swift-mode only — graph-DSL mode is interpreted and needs no compiler — and best-effort: any LSP failure yields no candidates rather than an error. +## Linux (GTK4) + +On Linux the scratchpad is `LyrebirdScratchLinuxView`, driven by +`LinuxScratchModel`, on the GTK4 SwiftOpenUI backend (re-exported through +`LyrebirdUI`). It runs the same `LiveSession` compile→`dlopen`→run path as the +macOS view; the difference is the editor and its chrome: + +- **Editor** — a `GtkSourceView` with Swift syntax highlighting, a line-number + gutter, and auto-indent (needs `libgtksourceview-5-dev`). +- **Completion** — **Ctrl+Space** at the caret shows sourcekit-lsp completions, + filtered by the identifier prefix already typed. +- **Run** — a *Run (fresh)* button clears the previous snippet's synths; *Run + (additive)* layers on top. Selecting one or more lines evaluates just those + (the selection is mirrored out of the editor). +- **Stop audio** — a panic button calling ``LiveSession/resetAll()``. +- **Live scope** — a `LyrebirdScopeView` of the session's output. +- **Save / load** — a native File menu (`New`, `Open…`, `Save`, `Save As…`) with + `Ctrl+N` / `Ctrl+O` / `Ctrl+S` / `Ctrl+Shift+S` accelerators, backed by + `GtkFileDialog`. Snippets are plain `.swift` files; `LinuxScratchModel` tracks + `currentPath` / `isDirty` and surfaces a `●` marker in the title. The File menu + commands are provided by `lyrebirdScratchFileCommands(model:)`, attached to the + hosting `WindowGroup` with `.commands` (SwiftOpenUI declares commands on the + Scene, so the app owns the model and shares it with + `LyrebirdScratchLinuxView(model:)`). + +`LyrebirdScratchLinuxDemo` is the runnable entry point. Because a snippet links +the engine's dynamic libraries, run `swift build` in `LiveCompile/` before +`swift run LyrebirdScratchLinuxDemo`. See `LINUX_README.md` for the full setup. + ## Limitations -- macOS only. +- Snippet compilation shells out to `swiftc`, so the scratchpad is desktop-only + (macOS and Linux); it is unavailable on iOS. - Syntax highlighting is a lightweight built-in lexer (`ScratchSwiftTokenizer`) — approximate by design, not a full parser. Completion (above) uses the real compiler via sourcekit-lsp; the two are independent. diff --git a/LiveCompile/Sources/LyrebirdScratchLinuxDemo/main.swift b/LiveCompile/Sources/LyrebirdScratchLinuxDemo/main.swift new file mode 100644 index 0000000..112584f --- /dev/null +++ b/LiveCompile/Sources/LyrebirdScratchLinuxDemo/main.swift @@ -0,0 +1,77 @@ +// main.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// Runnable Linux live-coding scratchpad: +// +// swift run LyrebirdScratchLinuxDemo +// +// Opens a GTK4 window with a code editor + Run/Clear + a live scope + a console. +// Type Swift, press Run: the snippet is compiled to a .so, dlopen'd, and run +// against the shared libLyrebirdDynamic, playing into the running engine. Needs +// libgtk-4-dev to build and (for sound) a live ALSA device; without ALSA the +// editor still compiles + runs snippets, just silently. +import Foundation +import LyrebirdSynth +import LyrebirdLiveCompile +import LyrebirdLiveCompileUI +import LyrebirdUI // GTK4Backend / App / WindowGroup, via @_exported re-exports + +private let scratchBlockSize: Int = 512 +private let scratchSampleRate: Double = 44_100.0 +private let scratchOutputChannels: Int = 2 +private let scratchInputChannels: Int = 0 + +let scratchDriver: any AudioDriver = makeDefaultAudioDriver() +let scratchEngine: SynthesisEngine = SynthesisEngine( + blockSize: scratchBlockSize, + sampleRate: scratchSampleRate, + numOutputChannels: scratchOutputChannels, + numInputChannels: scratchInputChannels, + driver: scratchDriver +) + +// Construct the session BEFORE start() so it can install its scope tap (the RT +// thread caches the tap at start()). +let scratchSession: LiveSession = LiveSession(engine: scratchEngine) + +do { + try scratchEngine.start() +} catch { + print("[Lyrebird] scratch engine start failed: \(error)") +} + +if !isLiveAudioAvailable { + print("[Lyrebird] no live audio backend — snippets still compile + run, but there is no sound.") +} + +// Register the GTK pointer sink so a snippet's `Mouse.X.Control()` / +// `Mouse.Y.Control()` / `Mouse.Click.Control()` read live values. Without this +// the shared `MouseInput` bridge is never installed and `Mouse.X` sits at its +// default, so e.g. `OscSin.Audio(freq: Mouse.X.Control() * 100)` never +// modulates. Install timing is not sensitive on Linux (SwiftOpenUI attaches the +// pointer controllers to every window it opens); the snippet reads the same +// process-global singleton in the shared libLyrebird. +MouseTracker.installShared() + +// The app owns the model so the File menu commands (New / Open… / Save / +// Save As…, with Ctrl+N/O/S accelerators) can bind to the same instance the +// view renders — SwiftOpenUI declares `.commands` on the Scene, not the View. +let scratchModel: LinuxScratchModel = LinuxScratchModel(session: scratchSession) + +// `LiveSession` / `LinuxScratchModel` are `@unchecked Sendable`, so they cross +// into SwiftOpenUI's nonisolated scene closure directly. +struct LyrebirdScratchApp: App { + var body: some Scene { + WindowGroup("Lyrebird Scratch") { + LyrebirdScratchLinuxView(model: scratchModel) + } + .commands { + lyrebirdScratchFileCommands(model: scratchModel) + } + } +} + +GTK4Backend().run(LyrebirdScratchApp.self) diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/ArtifactStagingTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/ArtifactStagingTests.swift index 9071193..e19f979 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/ArtifactStagingTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/ArtifactStagingTests.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) import Testing import Foundation import LyrebirdSynth diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/DiagnosticParserTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/DiagnosticParserTests.swift index 3d50523..9eb3e00 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/DiagnosticParserTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/DiagnosticParserTests.swift @@ -8,7 +8,7 @@ import Testing import Foundation @testable import LyrebirdLiveCompile -#if os(macOS) +#if os(macOS) || os(Linux) @Suite("DiagnosticParser") struct DiagnosticParserTests { diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/GraphDSLDiagnosticMapperTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/GraphDSLDiagnosticMapperTests.swift index 723088f..45a3c57 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/GraphDSLDiagnosticMapperTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/GraphDSLDiagnosticMapperTests.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) import Testing import LyrebirdGraphDSLEmbedded @testable import LyrebirdLiveCompile diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveCompilerTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveCompilerTests.swift index bc2581c..a1668d5 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveCompilerTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveCompilerTests.swift @@ -8,7 +8,7 @@ import Testing import Foundation @testable import LyrebirdLiveCompile -#if os(macOS) +#if os(macOS) || os(Linux) @Suite("LiveCompiler") struct LiveCompilerTests { @@ -30,7 +30,11 @@ struct LiveCompilerTests { let snippet: CompiledSnippet = try LiveCompiler.compile(source: source) #expect(snippet.moduleName.hasPrefix("LBSnippet_")) + #if os(macOS) #expect(snippet.dylibPath.hasSuffix(".dylib")) + #else + #expect(snippet.dylibPath.hasSuffix(".so")) + #endif var marker: Int32 = 0 withUnsafeMutablePointer(to: &marker) { ptr in @@ -103,6 +107,11 @@ struct LiveCompilerTests { for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) { args += ["-Xcc", "-fmodule-map-file=\(url.path)"] } + #if os(Linux) + for url: URL in LiveSession.discoverSourceSystemModuleMaps(in: importPaths) { + args += ["-Xcc", "-fmodule-map-file=\(url.path)"] + } + #endif return args } diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionDiagnosticsTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionDiagnosticsTests.swift index b6c5766..2946edf 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionDiagnosticsTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionDiagnosticsTests.swift @@ -9,7 +9,7 @@ import Foundation import LyrebirdSynth @testable import LyrebirdLiveCompile -#if os(macOS) +#if os(macOS) || os(Linux) @MainActor @Suite("LiveSession diagnostics") diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionGraphDSLTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionGraphDSLTests.swift index 3ba1f9b..8f1ab21 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionGraphDSLTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionGraphDSLTests.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) import Testing import LyrebirdSynth import LyrebirdGraphDSLEmbedded diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionTests.swift index a1b2232..845ea0e 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionTests.swift @@ -9,7 +9,7 @@ import Foundation import LyrebirdSynth @testable import LyrebirdLiveCompile -#if os(macOS) +#if os(macOS) || os(Linux) @MainActor @Suite("LiveSession") @@ -34,7 +34,12 @@ struct LiveSessionTests { @Test func buildDirDiscoveryFindsLyrebirdDylib() throws { let buildDir: URL = try #require(LiveSession.currentBuildDir()) - let dylib: URL = buildDir.appendingPathComponent("libLyrebirdDynamic.dylib") + #if os(macOS) + let libName: String = "libLyrebirdDynamic.dylib" + #else + let libName: String = "libLyrebirdDynamic.so" + #endif + let dylib: URL = buildDir.appendingPathComponent(libName) #expect(FileManager.default.fileExists(atPath: dylib.path)) } diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/MessageLogTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/MessageLogTests.swift index 4c5dc25..fcaa65e 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/MessageLogTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/MessageLogTests.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) import Testing import LyrebirdSynth @testable import LyrebirdLiveCompile diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/ScopeAttachTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/ScopeAttachTests.swift index 00e46bc..b6677c4 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/ScopeAttachTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/ScopeAttachTests.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) import Testing import LyrebirdSynth @testable import LyrebirdLiveCompile diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/SlotReleaseTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/SlotReleaseTests.swift index 5073bdd..eb1db49 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/SlotReleaseTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/SlotReleaseTests.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) import Testing import LyrebirdSynth @testable import LyrebirdLiveCompile diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetCompletionServiceTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetCompletionServiceTests.swift index a9ce3a3..865aa46 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetCompletionServiceTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetCompletionServiceTests.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) import Testing import Foundation import LyrebirdSynth diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetHarnessTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetHarnessTests.swift index 1153975..859b5fc 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetHarnessTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetHarnessTests.swift @@ -8,7 +8,7 @@ import Testing import Foundation @testable import LyrebirdLiveCompile -#if os(macOS) +#if os(macOS) || os(Linux) @Suite("SnippetHarness") struct SnippetHarnessTests { diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetScheduledLoopTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetScheduledLoopTests.swift index 6c9a635..2a30236 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetScheduledLoopTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetScheduledLoopTests.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) import Testing import LyrebirdSynth @testable import LyrebirdLiveCompile diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/SourceKitLSPClientTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/SourceKitLSPClientTests.swift index d90b63d..3ece62d 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/SourceKitLSPClientTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/SourceKitLSPClientTests.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) import Testing import Foundation @testable import LyrebirdLiveCompile diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/SwapQuantizeTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/SwapQuantizeTests.swift index e3e4002..29968ca 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/SwapQuantizeTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/SwapQuantizeTests.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) import Testing import LyrebirdSynth @testable import LyrebirdLiveCompile diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/SwiftFormatterTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/SwiftFormatterTests.swift index 7866124..0e89280 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/SwiftFormatterTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/SwiftFormatterTests.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) import Testing import Foundation @testable import LyrebirdLiveCompile diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/ToolchainProbeTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/ToolchainProbeTests.swift index 996c5d0..e1fab5c 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/ToolchainProbeTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/ToolchainProbeTests.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -#if os(macOS) +#if os(macOS) || os(Linux) import Testing @testable import LyrebirdLiveCompile diff --git a/LiveCompile/Tests/LyrebirdLiveCompileUITests/LinuxScratchModelTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileUITests/LinuxScratchModelTests.swift new file mode 100644 index 0000000..e1491cc --- /dev/null +++ b/LiveCompile/Tests/LyrebirdLiveCompileUITests/LinuxScratchModelTests.swift @@ -0,0 +1,155 @@ +// LinuxScratchModelTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// Pure-logic tests for the Linux scratch model's document / file surface +// (dirty-tracking, new/load/save, title). Deliberately avoids the paths that +// open a native GtkFileDialog (`openDocument()`, `saveAs()`) — those need a +// running GTK application and a display, so they are exercised by hand on the +// VM, not here. The paths covered are headless-safe: `CodeEditorController`'s +// `setText` is a no-op until a widget is attached, and `save()` with a +// `currentPath` set writes the file directly without a dialog. +#if os(Linux) +import Testing +import Foundation +import LyrebirdSynth +@testable import LyrebirdLiveCompile +@testable import LyrebirdLiveCompileUI + +@Suite("LinuxScratchModel document + file I/O") +struct LinuxScratchModelTests { + + private func makeModel(initialSource: String = lyrebirdLinuxScratchSeed) -> LinuxScratchModel { + let engine: SynthesisEngine = SynthesisEngine( + blockSize: 64, + controlBlockSize: 16, + sampleRate: 48_000, + numOutputChannels: 2, + numInputChannels: 0, + numAudioBuses: 16, + numControlBuses: 16, + eventQueueCapacity: lyrebirdDefaultEventQueueCapacity, + driver: OfflineDriver() + ) + return LinuxScratchModel(session: LiveSession(engine: engine), initialSource: initialSource) + } + + private func tempPath(_ ext: String = "swift") -> String { + FileManager.default.temporaryDirectory + .appendingPathComponent("lyrebird-scratch-\(UUID().uuidString).\(ext)") + .path + } + + // MARK: - Dirty tracking + + @Test func freshModelIsCleanWithSeed() { + let model: LinuxScratchModel = makeModel() + #expect(model.source == lyrebirdLinuxScratchSeed) + #expect(model.isDirty == false) + #expect(model.currentPath == nil) + } + + @Test func setSourceMarksDirtyOnRealChange() { + let model: LinuxScratchModel = makeModel() + model.setSource(model.source + "\n// edit") + #expect(model.isDirty == true) + } + + @Test func setSourceIgnoresUnchangedEcho() { + let model: LinuxScratchModel = makeModel() + // A widget echo of the identical value must not flip the dirty flag. + model.setSource(model.source) + #expect(model.isDirty == false) + } + + // MARK: - New + + @Test func newDocumentResetsToSeedAndClean() { + let model: LinuxScratchModel = makeModel() + model.setSource("context.play { OscSin.Audio(freq: 440) }") + model.currentPath = "/tmp/whatever.swift" + #expect(model.isDirty == true) + + model.newDocument() + #expect(model.source == lyrebirdLinuxScratchSeed) + #expect(model.currentPath == nil) + #expect(model.isDirty == false) + } + + // MARK: - Load + + @Test func loadFileReplacesBufferAndAdoptsPathClean() throws { + let path: String = tempPath() + let body: String = "context.play { OscSin.Audio(freq: 220, mul: 0.2) }\n" + try body.write(toFile: path, atomically: true, encoding: .utf8) + defer { try? FileManager.default.removeItem(atPath: path) } + + let model: LinuxScratchModel = makeModel() + model.loadFile(path) + #expect(model.source == body) + #expect(model.currentPath == path) + #expect(model.isDirty == false) + } + + @Test func loadFileMissingPathKeepsBuffer() { + let model: LinuxScratchModel = makeModel() + let before: String = model.source + model.loadFile("/nonexistent/does-not-exist.swift") + // Failure is reported to the console; the buffer is untouched. + #expect(model.source == before) + #expect(model.currentPath == nil) + } + + // MARK: - Save + + @Test func saveWritesToCurrentPathAndClears() throws { + let path: String = tempPath() + defer { try? FileManager.default.removeItem(atPath: path) } + + let model: LinuxScratchModel = makeModel() + let code: String = "context.play { WhiteNoise.Audio(mul: 0.1) }" + model.setSource(code) + model.currentPath = path + #expect(model.isDirty == true) + + model.save() // currentPath is set -> writes directly, no dialog + #expect(model.isDirty == false) + let onDisk: String = try String(contentsOfFile: path, encoding: .utf8) + #expect(onDisk == code) + } + + @Test func saveThenLoadRoundTrip() throws { + let path: String = tempPath() + defer { try? FileManager.default.removeItem(atPath: path) } + + let writer: LinuxScratchModel = makeModel() + let code: String = "context.play { OscSaw.Audio(freq: 110, mul: 0.15) }" + writer.setSource(code) + writer.currentPath = path + writer.save() + + let reader: LinuxScratchModel = makeModel() + reader.loadFile(path) + #expect(reader.source == code) + #expect(reader.currentPath == path) + #expect(reader.isDirty == false) + } + + // MARK: - Title + + @Test func displayTitleUntitledWhenNoPath() { + let model: LinuxScratchModel = makeModel() + #expect(model.displayTitle == "untitled.swift") + } + + @Test func displayTitleShowsFilenameAndDirtyMarker() { + let model: LinuxScratchModel = makeModel() + model.currentPath = "/home/user/tune.swift" + #expect(model.displayTitle == "tune.swift") + model.setSource(model.source + " ") + #expect(model.displayTitle == "● tune.swift") + } +} +#endif diff --git a/Package.swift b/Package.swift index 771ac7f..3e8d101 100644 --- a/Package.swift +++ b/Package.swift @@ -1,5 +1,7 @@ // swift-tools-version: 6.0 import PackageDescription +// ProcessInfo — read the LYREBIRD_DISABLE_ALSA opt-out below. +import Foundation let package = Package( name: "Lyrebird", @@ -21,7 +23,10 @@ let package = Package( // double-registration crash fixed in Phase 167). External consumers // never reference this product — they use `Lyrebird` (static) above. .library(name: "LyrebirdDynamic", type: .dynamic, targets: ["LyrebirdSynth"]), - .library(name: "LyrebirdUI", targets: ["LyrebirdUI"]), + // LyrebirdUI (SwiftUI/AppKit) product + targets are appended after this + // literal under `#if os(macOS)` — they are Apple-only and must be absent + // from the manifest on a native Linux/Windows host. See the block below + // the `Package(...)` initializer. .library(name: "LyrebirdGraphDSL", targets: ["LyrebirdGraphDSL"]), .executable(name: "LyrebirdCLI", targets: ["LyrebirdCLI"]), ], @@ -58,19 +63,38 @@ let package = Package( name: "LyrebirdC", path: "Sources/LyrebirdC" ), + // Vector-math seam. On Apple this target re-exports Accelerate + // (`@_exported import Accelerate`); on non-Apple platforms it supplies + // API-compatible scalar replacements for the vDSP/vForce primitives the + // synthesis core uses. Every core file writes `import LyrebirdDSP` in + // place of `import Accelerate`. See Sources/LyrebirdDSP/AccelerateShim.swift. + .target( + name: "LyrebirdDSP", + path: "Sources/LyrebirdDSP", + linkerSettings: [ + .linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])), + ] + ), .target( // Module/target renamed `Lyrebird` → `LyrebirdSynth` (the `Lyrebird` // product above still vends it). Folder path kept as `Sources/Lyrebird` // so the source tree and `Lyrebird.docc` catalog don't move. name: "LyrebirdSynth", - dependencies: ["LyrebirdC"], + // `CALSA` (libasound, for the Linux `ALSAAudioDriver`) is appended + // to these dependencies on a Linux host — see the block below the + // `Package(...)` initializer. + dependencies: ["LyrebirdC", "LyrebirdDSP"], path: "Sources/Lyrebird", linkerSettings: [ - .linkedFramework("CoreAudio"), - .linkedFramework("AudioToolbox"), - .linkedFramework("Accelerate"), - .linkedFramework("CoreMIDI"), - .linkedFramework("AVFoundation"), + // Apple-only frameworks. Guarded with `.when(platforms:)` so a + // non-Apple target (Linux/Windows feasibility) does not fail at + // link-configuration time before source-level errors surface. + // macOS/iOS builds are unaffected. + .linkedFramework("CoreAudio", .when(platforms: [.macOS, .iOS])), + .linkedFramework("AudioToolbox", .when(platforms: [.macOS, .iOS])), + .linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])), + .linkedFramework("CoreMIDI", .when(platforms: [.macOS, .iOS])), + .linkedFramework("AVFoundation", .when(platforms: [.macOS, .iOS])), ] ), .executableTarget( @@ -87,15 +111,9 @@ let package = Package( ] // Swift 6 language mode (Phase 202): inherits the swift-tools 6.0 default. ), - .target( - name: "LyrebirdUI", - dependencies: [ - "LyrebirdSynth", - ], - path: "Sources/LyrebirdUI" - // SwiftUI + AppKit + Observation are system frameworks — no linkerSettings needed. - // Swift 6 language mode (Phase 202): inherits the swift-tools 6.0 default. - ), + // NOTE: LyrebirdUI, LyrebirdUITests, and LyrebirdTests are appended after + // the `Package(...)` initializer under `#if os(macOS)` — they need Apple + // frameworks and must be absent from a native Linux/Windows manifest. // Phase 167 — `LyrebirdLiveCompile` (and its SwiftUI host // `LyrebirdLiveCompileUI`) moved to the `LiveCompile/` nested SwiftPM // package. It depends on the internal `.product(name: "LyrebirdDynamic", @@ -105,12 +123,10 @@ let package = Package( // cause of an ObjC class double-registration crash during `swift test` // in the single-package layout. The consumer-facing `Lyrebird` product // stays static (see products list). See `LiveCompile/Package.swift`. - .executableTarget( - name: "LyrebirdBenchmark", - dependencies: ["LyrebirdSynth"], - path: "Sources/LyrebirdBenchmark", - swiftSettings: [.unsafeFlags(["-O"])] - ), + // LyrebirdBenchmark micro-benchmarks Accelerate/vDSP primitives directly + // (`import Accelerate`), so it is Apple-only and appended under + // `#if os(macOS)` below the initializer — otherwise `swift test` on Linux + // would try to build it and fail on the missing Accelerate module. // Interpreted graph-DSL. Pure Swift over core `LyrebirdSynth` types — // no swiftc, no AppKit — so it is cross-platform (iOS included). The // `DSLBuiltin` registry it consumes is emitted by the separate @@ -122,22 +138,13 @@ let package = Package( path: "Sources/LyrebirdGraphDSL" ), .testTarget( - name: "LyrebirdTests", - dependencies: ["LyrebirdSynth"], - path: "Tests/LyrebirdTests", + name: "LyrebirdDSPTests", + dependencies: ["LyrebirdDSP"], + path: "Tests/LyrebirdDSPTests", linkerSettings: [ - .linkedFramework("AudioToolbox"), - .linkedFramework("Accelerate"), + .linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])), ] ), - .testTarget( - name: "LyrebirdUITests", - dependencies: [ - "LyrebirdUI", - "LyrebirdSynth", - ], - path: "Tests/LyrebirdUITests" - ), .testTarget( name: "LyrebirdGraphDSLTests", dependencies: [ @@ -146,8 +153,8 @@ let package = Package( ], path: "Tests/LyrebirdGraphDSLTests", linkerSettings: [ - .linkedFramework("AudioToolbox"), - .linkedFramework("Accelerate"), + .linkedFramework("AudioToolbox", .when(platforms: [.macOS, .iOS])), + .linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])), ] ), .testTarget( @@ -155,5 +162,180 @@ let package = Package( dependencies: ["LyrebirdCLI"], path: "Tests/LyrebirdCLITests" ), + // Platform-neutral core tests. Unlike `LyrebirdTests` (Apple-only — + // some files import AudioToolbox/Accelerate directly), this target + // compiles and runs on every supported platform, so the golden-value + // DSP tests it holds actually execute on Linux in CI. That is the only + // place the portable FFT/biquad/vector fallbacks in `LyrebirdDSP` are + // verified through the real generators; `LyrebirdDSPTests` compares to + // real vDSP and is therefore Apple-only by construction. + .testTarget( + name: "LyrebirdPortableTests", + dependencies: ["LyrebirdSynth"], + path: "Tests/LyrebirdPortableTests", + linkerSettings: [ + .linkedFramework("AudioToolbox", .when(platforms: [.macOS, .iOS])), + .linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])), + ] + ), ] ) + +// LyrebirdUI — the cross-platform UI module. Public control/view names are the +// same on every platform; each file switches its body by backend +// (`#if canImport(SwiftUI)` → real SwiftUI on Apple / `#else` → SwiftOpenUI on +// Linux). Base dependency is `LyrebirdSynth` (the shared `@UIParam` model); +// the Linux block below adds the SwiftOpenUI + BackendGTK4 backend deps. On +// Apple, SwiftUI/AppKit are system frameworks so no package dep is needed. +package.products.append( + .library(name: "LyrebirdUI", targets: ["LyrebirdUI"]) +) +package.targets.append( + .target( + name: "LyrebirdUI", + dependencies: ["LyrebirdSynth"], + path: "Sources/LyrebirdUI" + ) +) + +// Apple-only pieces, added only when the manifest host is macOS. +// +// `#if` cannot appear as an element inside an array literal in a package +// manifest, so these are appended to the already-built `package` instead of +// being conditionalized in place. On a native Linux/Windows host (in-container +// `swift build`/`swift test`, CI) they are simply absent, so nothing tries to +// compile SwiftUI/AppKit or the AudioToolbox-importing test files. +// +// • LyrebirdUITests — exercises LyrebirdUI (the module itself is now +// cross-platform and appended above the initializer). +// • LyrebirdBenchmark — micro-benchmarks Accelerate/vDSP primitives directly. +// • LyrebirdTests — the main suite; still imports Apple frameworks +// directly in some files (e.g. AUv3 driver tests). +// Porting its platform-neutral majority to run on +// Linux, plus Linux-runnable golden DSP tests, is a +// separate work item. +// +// Cross-compiling from a Mac keeps the host as macOS, so Apple-SDK builds are +// unaffected — they still see every target. +#if os(macOS) +package.targets.append(contentsOf: [ + .executableTarget( + name: "LyrebirdBenchmark", + dependencies: ["LyrebirdSynth"], + path: "Sources/LyrebirdBenchmark", + swiftSettings: [.unsafeFlags(["-O"])] + ), + .testTarget( + name: "LyrebirdTests", + dependencies: ["LyrebirdSynth"], + path: "Tests/LyrebirdTests", + linkerSettings: [ + .linkedFramework("AudioToolbox", .when(platforms: [.macOS, .iOS])), + .linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])), + ] + ), + .testTarget( + name: "LyrebirdUITests", + dependencies: [ + "LyrebirdUI", + "LyrebirdSynth", + ], + path: "Tests/LyrebirdUITests" + ), +]) +#endif + +// Linux live audio. `ALSAAudioDriver` needs libasound's headers, which are not +// installed by default on a build box (`apt-get install libasound2-dev`), so +// the target is added only when the manifest is being evaluated ON Linux — +// where those headers can actually exist. A macOS host never sees it, whether +// building for Apple platforms or cross-compiling to Linux; a cross-compiled +// Linux binary therefore has no live-audio driver, only offline NRT rendering. +// Build natively on Linux to get audio out. +// +// Escape hatch: set `LYREBIRD_DISABLE_ALSA=1` to build the rest of Lyrebird on +// a Linux box that has no ALSA development package. Everything except the +// driver still works — `ALSAAudioDriver` is `#if canImport(CALSA)`-guarded and +// simply will not exist, and `makeDefaultAudioDriver()` returns an +// `OfflineDriver` instead. Note that SwiftPM caches evaluated manifests, so +// flipping this variable on an existing checkout may need the cache cleared +// (`rm -rf .build`, or a fresh `--scratch-path`) before it takes effect. +#if os(Linux) +if ProcessInfo.processInfo.environment["LYREBIRD_DISABLE_ALSA"] == nil { + package.targets.append( + .systemLibrary( + name: "CALSA", + path: "Sources/CALSA", + pkgConfig: "alsa", + providers: [ + .apt(["libasound2-dev"]), + ] + ) + ) + if let synthIndex: Int = package.targets.firstIndex(where: { $0.name == "LyrebirdSynth" }) { + package.targets[synthIndex].dependencies.append(.target(name: "CALSA")) + } + // The portable test target needs it too: its ALSA tests are guarded on + // `canImport(CALSA)`, which is only true where the module is a dependency. + // Without this the guard is always false and the driver's tests silently + // never run. + if let testIndex: Int = package.targets.firstIndex(where: { $0.name == "LyrebirdPortableTests" }) { + package.targets[testIndex].dependencies.append(.target(name: "CALSA")) + } +} +#endif + +// Linux backend for the cross-platform `LyrebirdUI`: SwiftOpenUI (GTK4). This is +// now a DEFAULT Linux dependency — building `LyrebirdUI` on Linux pulls +// SwiftOpenUI and needs `libgtk-4-dev`. (The default *core* Linux CI lane builds +// only LyrebirdSynth / LyrebirdGraphDSL / LyrebirdCLI, so it does not build the +// UI or need GTK; a plain `swift build` on Linux does.) +// +// Pinned to a personal fork commit carrying the GTK4 drag fix ("GTK4: continuous +// drag for Canvas value controls": @Observable narrow path + live subtree redraw +// + global interaction deferral with linked-control redraw). Move the pin to +// `codelynx/SwiftOpenUI` + a version once the fix lands upstream and a release is +// tagged. See spikes/SwiftOpenUIKnob/FORK_PATCH_PLAN.md. +// +// `LyrebirdUI`'s controls bind core `@UIParam` / `UIParamNode` (in +// `LyrebirdSynth`), the same model the SwiftUI controls use, so one synthesizer's +// parameters drive both platforms. +#if os(Linux) +// Set LYREBIRD_SWIFTOPENUI_LOCAL=/path/to/SwiftOpenUI to build against a local +// fork checkout instead of the pinned release — used to iterate the GTK4 fork +// without a push/pin round-trip (this Mac can't build the GTK4 backend; a Linux +// container or the VM does). Unset (the default), it resolves the pinned tag. +package.dependencies.append( + ProcessInfo.processInfo.environment["LYREBIRD_SWIFTOPENUI_LOCAL"].map { + .package(name: "SwiftOpenUI", path: $0) + } ?? + // Pinned to the fork's tagged release 0.5.0 (== commit a392026): 0.1.0 + // (Patches A–F narrow-path + GTK4Backend.openStandaloneWindow → LyrebirdWindow + // / presentInWindow + GTK4PointerTracking → Linux MouseTracker), plus the + // GtkSourceView-backed `CodeEditor` view (Swift highlighting + gutter) used by + // the Linux live-compile scratch editor — which adds a system dependency on + // libgtksourceview-5-dev. A tag rather than a bare commit gives a stable, + // human-readable release reference; bump it when the fork cuts a new release. + // (Upstreaming to codelynx/SwiftOpenUI remains the open follow-on — see + // docs/ui/linux-parity-plan.md.) + .package( + url: "https://github.com/joshpar/SwiftOpenUI", + exact: "0.7.0" + ) +) +// Give the cross-platform LyrebirdUI target its Linux (GTK4) backend deps. +if let uiIndex: Int = package.targets.firstIndex(where: { $0.name == "LyrebirdUI" }) { + package.targets[uiIndex].dependencies.append(contentsOf: [ + .product(name: "SwiftOpenUI", package: "SwiftOpenUI"), + .product(name: "BackendGTK4", package: "SwiftOpenUI"), + ]) +} +// Runnable GTK4 GUI demo: `swift run LyrebirdUILinuxDemo`. +package.targets.append( + .executableTarget( + name: "LyrebirdUILinuxDemo", + dependencies: ["LyrebirdSynth", "LyrebirdUI"], + path: "Sources/LyrebirdUILinuxDemo" + ) +) +#endif diff --git a/README.md b/README.md index 9406e66..9c7b6b4 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,8 @@ That's it — the `Lyrebird` product links **statically**, so there's no dynamic Full walk-through (SPM manifest form, local-path dev dependency, per-template details): [`INSTALLATION_AND_USAGE.md`](INSTALLATION_AND_USAGE.md). DocC version: **Getting Started ▸ Adding Lyrebird to your own Xcode project**. +**On Linux?** The non-UI core — engine, generators, CLI, offline render, live ALSA audio, MIDI, and OSC — builds and runs on Linux (no Xcode, no SwiftUI). Start here: [`docs/linux-getting-started.md`](docs/linux-getting-started.md). + --- ## Opening in Xcode diff --git a/RELEASES.md b/RELEASES.md index ecf4ccb..a949891 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -7,6 +7,50 @@ functionality in a backward-compatible way. --- +## 2.0.0 — Linux support + +The major release: Lyrebird now runs on **Linux**, in addition to macOS and iOS. +Everything on Apple platforms is unchanged — the entire Linux surface is additive +— but the port is large enough to warrant a major version. + +**Cross-platform core.** The engine, the full generator library, the CLI, the +REPL, offline render (NRT → WAV), and the interpreted graph DSL build and run on +Linux (Ubuntu 24.04, swift.org toolchain). A new `LyrebirdDSP` module provides +portable `vDSP`/`vv` implementations so the DSP that relied on Accelerate runs +off Apple; the portable FFT, biquad, and vector paths are golden-value verified. +CI covers x86_64; ARM64 (e.g. a Parallels VM) is a supported dev target. + +**Live audio, MIDI, OSC on Linux.** + +- **`ALSAAudioDriver`** — live full-duplex audio over ALSA. `makeDefaultAudioDriver()` + resolves to it on Linux; build with `LYREBIRD_DISABLE_ALSA=1` on boxes with no + sound stack. +- **ALSA-sequencer MIDI** and a **POSIX-UDP OSC** transport, replacing the + CoreMIDI / Network.framework backends off Apple. +- A **portable WAV codec** (`WavFileWriter` / `WavFileReader`) for soundfile I/O + and DiskIn where AudioToolbox is unavailable (CAF/AIFF/AAC stay Apple-only). + +**GTK4 GUI.** `LyrebirdUI` is now one cross-platform module — SwiftUI on Apple, +GTK4 (on the SwiftOpenUI backend) on Linux. Ported controls: knob, slider, label, +button, XY pad, plus the oscilloscope, envelope, and CPU-status views, with +standalone windows and live mouse input (`Mouse.X` / `Mouse.Y` / `Mouse.Click`). +Every control bound to a `@UIParam` node stays in sync — the same parameter model +the macOS controls use. + +**Live-coding scratchpad on Linux.** The `LiveCompile` live-coding subsystem runs +on Linux: a GtkSourceView editor with Swift highlighting and a gutter, `Ctrl+Space` +sourcekit-lsp completion, run-fresh / run-additive / line-evaluation, a Stop-audio +panic button, a live oscilloscope, and a native File menu (New / Open… / Save / +Save As…) with `Ctrl+N/O/S` accelerators and `GtkFileDialog` save/load. + +**Behavioral change (all platforms).** `SynthesisEngine.stop()` now tears down the +node tree and unbinds every non-persistent synth it was hosting, so a stop → re-add +of the same instance needs no intervening `processBlock`. + +See `LINUX_README.md` for Linux setup, build, and usage. + +--- + ## 1.7.1 — Neural-amp model importer A patch release. One backward-compatible addition: diff --git a/Sources/CALSA/include/calsa-shim.h b/Sources/CALSA/include/calsa-shim.h new file mode 100644 index 0000000..9218b0a --- /dev/null +++ b/Sources/CALSA/include/calsa-shim.h @@ -0,0 +1,17 @@ +// calsa-shim.h +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT +// +// Single include point for the ALSA C library (libasound), used by +// ALSAAudioDriver on Linux. Kept as a shim header rather than pointing the +// module map straight at so the include path resolves the +// same way regardless of where the distribution installs the ALSA headers. + +#ifndef LYREBIRD_CALSA_SHIM_H +#define LYREBIRD_CALSA_SHIM_H + +#include + +#endif /* LYREBIRD_CALSA_SHIM_H */ diff --git a/Sources/CALSA/module.modulemap b/Sources/CALSA/module.modulemap new file mode 100644 index 0000000..0621d34 --- /dev/null +++ b/Sources/CALSA/module.modulemap @@ -0,0 +1,5 @@ +module CALSA [system] { + header "include/calsa-shim.h" + link "asound" + export * +} diff --git a/Sources/Lyrebird/AUv3/LyrebirdAUFactoryPreset.swift b/Sources/Lyrebird/AUv3/LyrebirdAUFactoryPreset.swift index 8529430..0493cab 100644 --- a/Sources/Lyrebird/AUv3/LyrebirdAUFactoryPreset.swift +++ b/Sources/Lyrebird/AUv3/LyrebirdAUFactoryPreset.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(AudioToolbox) import Foundation import AudioToolbox @@ -40,3 +41,4 @@ public struct LyrebirdAUFactoryPreset: Sendable { self.sourceSlots = sourceSlots } } +#endif diff --git a/Sources/Lyrebird/AUv3/LyrebirdAUParameterEntry.swift b/Sources/Lyrebird/AUv3/LyrebirdAUParameterEntry.swift index 2640001..3ce28ae 100644 --- a/Sources/Lyrebird/AUv3/LyrebirdAUParameterEntry.swift +++ b/Sources/Lyrebird/AUv3/LyrebirdAUParameterEntry.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(AudioToolbox) import Foundation import AudioToolbox @@ -26,3 +27,4 @@ public struct LyrebirdAUParameterEntry { /// and to write new values via `_writeAtomicValue`. public let node: any LiveParameterValue } +#endif diff --git a/Sources/Lyrebird/AUv3/LyrebirdAUParameterInfo.swift b/Sources/Lyrebird/AUv3/LyrebirdAUParameterInfo.swift index 634d82e..d02d42f 100644 --- a/Sources/Lyrebird/AUv3/LyrebirdAUParameterInfo.swift +++ b/Sources/Lyrebird/AUv3/LyrebirdAUParameterInfo.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(AudioToolbox) import Foundation import AVFoundation import AudioToolbox @@ -74,3 +75,4 @@ public let lyrebirdAUParameterDefaultFlags: AudioUnitParameterOptions = [ .flag_IsWritable, .flag_CanRamp, ] +#endif diff --git a/Sources/Lyrebird/AUv3/LyrebirdAUParameterMapping.swift b/Sources/Lyrebird/AUv3/LyrebirdAUParameterMapping.swift index 00a8ffc..67c05f5 100644 --- a/Sources/Lyrebird/AUv3/LyrebirdAUParameterMapping.swift +++ b/Sources/Lyrebird/AUv3/LyrebirdAUParameterMapping.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(AudioToolbox) import Foundation import AVFoundation import AudioToolbox @@ -100,3 +101,4 @@ public enum LyrebirdAUParameterMapping { return (tree, nodes) } } +#endif diff --git a/Sources/Lyrebird/AUv3/LyrebirdAUPresetCodable.swift b/Sources/Lyrebird/AUv3/LyrebirdAUPresetCodable.swift index d75de01..1b0abc6 100644 --- a/Sources/Lyrebird/AUv3/LyrebirdAUPresetCodable.swift +++ b/Sources/Lyrebird/AUv3/LyrebirdAUPresetCodable.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(AudioToolbox) import Foundation import AudioToolbox @@ -118,3 +119,4 @@ public enum LyrebirdAUPresetSourceRegistry { return _factories.keys.sorted() } } +#endif diff --git a/Sources/Lyrebird/AUv3/LyrebirdAUVoicePoolBinding.swift b/Sources/Lyrebird/AUv3/LyrebirdAUVoicePoolBinding.swift index 54b65fa..e82f86b 100644 --- a/Sources/Lyrebird/AUv3/LyrebirdAUVoicePoolBinding.swift +++ b/Sources/Lyrebird/AUv3/LyrebirdAUVoicePoolBinding.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(AudioToolbox) import Foundation import AudioToolbox @@ -136,3 +137,4 @@ public final class LyrebirdAUVoicePoolBinding { /// `Double(velocity) / Double(midiVelocityMax)` yields the conventional `[0,1]` /// range used by `@LiveParam` amplitude parameters. public let midiVelocityMax: UInt8 = 127 +#endif diff --git a/Sources/Lyrebird/AUv3/LyrebirdAudioUnit.swift b/Sources/Lyrebird/AUv3/LyrebirdAudioUnit.swift index 53a5209..edb8a11 100644 --- a/Sources/Lyrebird/AUv3/LyrebirdAudioUnit.swift +++ b/Sources/Lyrebird/AUv3/LyrebirdAudioUnit.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(AudioToolbox) import Foundation import AVFoundation import AudioToolbox @@ -721,3 +722,4 @@ public let lyrebirdAUFullStateSourcesKey: String = "sources" /// Sub-key inside the root payload that holds the per-parameter source-slot /// generator type IDs: `[paramName: presetTypeID]`. public let lyrebirdAUFullStateSourceTypesKey: String = "sourceTypes" +#endif diff --git a/Sources/Lyrebird/AudioDrivers/ALSAAudioDriver.swift b/Sources/Lyrebird/AudioDrivers/ALSAAudioDriver.swift new file mode 100644 index 0000000..c39273e --- /dev/null +++ b/Sources/Lyrebird/AudioDrivers/ALSAAudioDriver.swift @@ -0,0 +1,648 @@ +// ALSAAudioDriver.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// Linux live audio. `CALSA` (libasound) is only a dependency of `LyrebirdSynth` +// on Linux — see Package.swift — so on Apple platforms this file compiles away +// entirely and `CoreAudioDriver` / `iOSAudioDriver` remain the only RT drivers. +#if canImport(CALSA) +import CALSA +import Foundation +import Synchronization +#if canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#endif + +/// A real-time ALSA driver that connects a ``SynthesisEngine`` to Linux audio +/// hardware. +/// +/// The transport is a blocking `snd_pcm_writei` loop on a dedicated thread — +/// the simplest shape that is correct: no callback re-entrancy, no ALSA async +/// handler restrictions, and back-pressure comes for free from the device. +/// Every buffer is allocated in ``setup(engine:)``, so the loop body itself +/// performs no allocation. +/// +/// **Typical usage**: +/// ```swift +/// let driver = ALSAAudioDriver() +/// let engine = SynthesisEngine( +/// blockSize: 512, sampleRate: 44100, +/// numOutputChannels: 2, numInputChannels: 0, +/// driver: driver +/// ) +/// try engine.start() +/// // … audio running … +/// engine.stop() +/// ``` +/// +/// **Duplex** — when the engine requests input channels, a capture PCM is +/// opened as well and `snd_pcm_link` ties the two streams to one clock so they +/// cannot drift. If the device pair refuses to link, the driver still runs +/// (read-then-write ordering keeps them approximately aligned) and reports it +/// through ``linkedStreams``. +/// +/// **Sample format** — `SND_PCM_FORMAT_FLOAT_LE`, matching the engine's `Float` +/// buses exactly, so no conversion or dithering happens anywhere in the path. +/// ALSA converts to the hardware's own format underneath. +/// +/// > Note: this driver has been verified to build and to fail cleanly with no +/// > sound device present; it has not yet been run against real Linux audio +/// > hardware. See LINUX_PLAN.md. +public final class ALSAAudioDriver: AudioDriver, @unchecked Sendable { + + // Unchecked Sendable: every stored property is written either in `init` or + // in `setup`/`start` before the render thread exists, and read-only + // afterwards, except `_isRunning` / `_hasRealtimePriority` (atomic) and + // `_lastError` (mutex), which the render thread writes while it runs. + + // MARK: - Configuration + + /// ALSA device name for playback. `"default"` follows the user's + /// `~/.asoundrc` / system configuration, which is what a desktop app wants; + /// `"hw:0,0"` addresses a card directly and bypasses dmix. + public var device: String = "default" + + /// ALSA device name for capture. Used only when the engine requests input + /// channels. + public var captureDevice: String = "default" + + /// Ring-buffer depth as a multiple of the engine's block size. Larger + /// tolerates more scheduling jitter at the cost of latency. + public var periodsPerBuffer: Int = defaultPeriodsPerBuffer + + /// When `true`, ALSA resamples if the hardware cannot do the engine's rate. + /// When `false`, a rate the device cannot produce is an error instead of a + /// silent quality loss. + public var allowSoftwareResampling: Bool = false + + /// When `true`, the render thread asks for `SCHED_FIFO`. Failure is not + /// fatal — unprivileged processes normally cannot get it, and the driver + /// runs at normal priority instead (see ``hasRealtimePriority``). + public var requestsRealtimePriority: Bool = true + + // MARK: - Status + + /// Whether `SCHED_FIFO` was actually granted to the render thread. + /// + /// Set by the render thread itself, after `start()` has already returned, + /// so it is atomic rather than a plain `var` — a caller polling it right + /// after `start()` would otherwise race the write. + public var hasRealtimePriority: Bool { _hasRealtimePriority.load(ordering: .acquiring) } + + /// Whether capture and playback were successfully clock-linked. Always + /// `false` when the engine requests no input channels. + public private(set) var linkedStreams: Bool = false + + /// The error that ended the render loop, if it ended on its own. + /// + /// Written by the render thread as it exits and read from wherever `stop()` + /// is called, so it is behind a mutex — the lock is only ever taken on the + /// failure path and by callers, never in the steady-state loop. + public var lastError: ALSAError? { _lastError.withLock { $0 } } + + // MARK: - Constants + + /// Four periods is the usual desktop compromise: enough slack that an + /// ordinary scheduling hiccup does not underrun, short enough to stay + /// playable. + private static let defaultPeriodsPerBuffer: Int = 4 + private static let microsecondsPerSecond: Double = 1_000_000 + /// `SCHED_FIFO` priority as a fraction of the policy's usable range. Well + /// clear of the top so a runaway render loop cannot lock out the kernel's + /// own high-priority threads. + private static let realtimePriorityFraction: Double = 0.75 + /// How long `stop()` waits for the render thread to leave its loop before + /// closing the PCM handles anyway. + private static let threadJoinTimeout: TimeInterval = 2.0 + /// `snd_pcm_recover` argument: 1 silences its own logging to stderr. + private static let recoverSilently: Int32 = 1 + /// How long `snd_pcm_wait` blocks for the device to become writable again + /// after a would-block return, in milliseconds. Waiting beats spinning: the + /// render thread may hold `SCHED_FIFO`, where a busy loop starves the box. + private static let deviceWaitMilliseconds: Int32 = 200 + /// Consecutive no-progress transfers (would-block, or zero frames moved) + /// tolerated before the stream is declared dead. At the wait above this is + /// ~2 s of a device that never becomes ready, which no working + /// configuration does. + @_spi(LyrebirdExtensions) + public static let maxConsecutiveStalls: Int = 10 + /// Consecutive signal interruptions tolerated. Far larger than the stall + /// budget because a signal says nothing about the device's health — this is + /// a bound only so a pathological signal source cannot spin the loop. + private static let maxConsecutiveInterrupts: Int = 1000 + + // MARK: - State + + private var playbackPCM: OpaquePointer? + private var capturePCM: OpaquePointer? + + private var engineRef: Unmanaged? + private var blockSize: Int = 0 + private var sampleRate: Double = 0 + private var outputChannels: Int = 0 + private var inputChannels: Int = 0 + + /// Interleaved staging buffers handed to ALSA. Raw pointers rather than + /// arrays so their addresses are stable for the thread's lifetime. + private var interleavedOutput: UnsafeMutablePointer? + private var interleavedInput: UnsafeMutablePointer? + + /// Planar input handed to `processBlock`, pre-allocated so the loop never + /// grows it. + private var inputStagingBuffers: [[Float]] = [] + + private let _isRunning: Atomic = Atomic(false) + private let _hasRealtimePriority: Atomic = Atomic(false) + /// Set when a `stop()` gave up waiting for the render thread. The thread is + /// still out there, still testing `_isRunning`, so the driver must never + /// start another one: a wedged transfer that finally returns would find the + /// flag true again and resume rendering alongside its replacement. + private let _abandonedThread: Atomic = Atomic(false) + private let _lastError: Mutex = Mutex(nil) + private var renderThread: Thread? + private let threadExited: DispatchSemaphore = DispatchSemaphore(value: 0) + + // MARK: - Init + + public init() { + // Initialise the RT-identity TLS key from this known non-RT call site, + // so the render thread's first `markCurrentThreadAsRT()` cannot be the + // allocating one. + RTThreadIdentity.warmUp() + } + + deinit { + stop() + // Belt and braces: `Thread { [weak self] in self?.renderLoop(...) }` + // holds `self` strongly for the whole call, so `deinit` cannot actually + // run while an abandoned loop is still inside it. If that ever changes, + // freeing these buffers would be a use-after-free, so the guard stays. + guard !_abandonedThread.load(ordering: .acquiring) else { return } + interleavedOutput?.deallocate() + interleavedInput?.deallocate() + } + + /// ALSA's period granularity is the engine block, so control-rate + /// resolution matches the other live drivers. + public var suggestedControlBlockSize: Int? { lyrebirdDefaultControlBlockSize } + + // MARK: - AudioDriver + + public func setup(engine: SynthesisEngine) throws { + guard !_abandonedThread.load(ordering: .acquiring) else { + // Reallocating the staging buffers would pull them out from under + // the thread that never came back. + throw ALSAError.renderThreadDidNotExit + } + engineRef = Unmanaged.passUnretained(engine) + blockSize = engine.blockSize + sampleRate = engine.sampleRate + outputChannels = engine.numOutputChannels + inputChannels = engine.numInputChannels + + interleavedOutput?.deallocate() + interleavedOutput = UnsafeMutablePointer.allocate( + capacity: blockSize * max(outputChannels, 1) + ) + interleavedOutput?.initialize(repeating: 0, count: blockSize * max(outputChannels, 1)) + + interleavedInput?.deallocate() + interleavedInput = nil + inputStagingBuffers = [] + if inputChannels > 0 { + let inputPointer: UnsafeMutablePointer = UnsafeMutablePointer.allocate( + capacity: blockSize * inputChannels + ) + inputPointer.initialize(repeating: 0, count: blockSize * inputChannels) + interleavedInput = inputPointer + inputStagingBuffers = [[Float]]( + repeating: [Float](repeating: 0, count: blockSize), + count: inputChannels + ) + } + } + + public func start() throws { + guard engineRef != nil, blockSize > 0 else { throw ALSAError.notConfigured } + guard !_abandonedThread.load(ordering: .acquiring) else { + // A previous render thread never came back. Starting a second one + // would put two threads on one engine the moment the first unwedges. + throw ALSAError.renderThreadDidNotExit + } + guard !_isRunning.load(ordering: .acquiring) else { return } + + // A loop that ended on its own leaves a finished thread and a signalled + // semaphore behind; clear them before starting another. + if renderThread != nil { stop() } + // That `stop()` can itself time out and latch — re-check, or the exact + // state the latch exists to prevent gets created a few lines below. + guard !_abandonedThread.load(ordering: .acquiring) else { + throw ALSAError.renderThreadDidNotExit + } + + _lastError.withLock { $0 = nil } + do { + try openPlayback() + if inputChannels > 0 { + try openCapture() + } + } catch { + // Never leave a half-open device: a playback handle that opened + // before capture failed would otherwise stay claimed until deinit. + closeDevices() + throw error + } + + // Drain a stale signal from a previous run that timed out in `stop()` + // and whose thread signalled afterwards; leaving it pending would make + // the next `stop()` return from its wait immediately. + while threadExited.wait(timeout: .now()) == .success {} + + _hasRealtimePriority.store(false, ordering: .releasing) + _isRunning.store(true, ordering: .releasing) + + // The engine is held unowned for the driver's normal life (it owns the + // driver, so retaining it back would be a cycle), but the render thread + // must not outlive it — and an abandoned thread can, since nothing can + // stop it. Retain for exactly the thread's lifetime: the loop's `defer` + // releases, so a thread that never returns pins the engine forever, + // which is the point. + // + // `retain()` bumps the pointee's count without ever materialising a + // Swift reference — `takeUnretainedValue()` on a since-freed engine + // would be undefined behaviour, not a recoverable `nil`. `engineRef` is + // already known non-nil (checked at the top of `start()`). + guard let engineUnmanaged: Unmanaged = engineRef else { + _isRunning.store(false, ordering: .releasing) + throw ALSAError.notConfigured + } + // Carried across the thread boundary as a bit pattern: `Thread`'s + // closure is `@Sendable`, and neither `Unmanaged` nor a raw pointer is + // Sendable under Swift 6 — the same reason `SynthesizerBase` stores its + // engine binding as an `Atomic`. The retain is real; the loop's + // `defer` releases it. + let engineBits: UInt = Self.retainForRenderThread(engineUnmanaged) + let thread: Thread = Thread { [weak self] in + guard let self: ALSAAudioDriver = self else { + Self.releaseEngine(bits: engineBits) + return + } + self.renderLoop(engineBits: engineBits) + } + thread.name = "lyrebird.alsa.render" + renderThread = thread + thread.start() + } + + public func stop() { + // Already abandoned: that thread is gone as far as this driver is + // concerned and its resources are deliberately leaked, so `renderThread` + // must not be touched again. A `deinit`-driven `stop()` can run on the + // render thread itself once a wedged transfer finally returns, which + // would race the original `stop()`'s write from the caller's thread. + guard !_abandonedThread.load(ordering: .acquiring) else { return } + + _isRunning.store(false, ordering: .releasing) + guard renderThread != nil else { + closeDevices() + return + } + // Join whenever a thread was launched — including one that already + // exited on its own error path. Closing the PCM handles while the + // thread could still touch them is a use-after-free, so the wait is not + // conditional on the running flag. The loop tests the flag once per + // block and so leaves within roughly one block period. + let exited: Bool = threadExited.wait(timeout: .now() + Self.threadJoinTimeout) == .success + renderThread = nil + guard exited else { + // The thread is stuck inside a transfer. Closing its PCM handles or + // freeing the buffers it is reading would be exactly the + // use-after-free the join exists to prevent, so abandon them + // instead: a leak is recoverable, a wild write is not. The handles + // stay open until the process exits, so a subsequent `start()` may + // fail with the device busy — which is the truth, and better than + // pretending the stop succeeded. + // Nothing is written here on purpose. The thread that owns these + // handles and buffers is still alive and still reading them; the + // abandon latch is what keeps every later path — `closeDevices()`, + // `deinit`, a second `start()` — from touching them. Clearing the + // properties would be its own data race, on top of the + // use-after-free the join exists to prevent. + _lastError.withLock { $0 = .renderThreadDidNotExit } + _abandonedThread.store(true, ordering: .releasing) + return + } + closeDevices() + } + + // MARK: - Device setup + + private func openPlayback() throws { + var pcm: OpaquePointer? + let openResult: Int32 = snd_pcm_open(&pcm, device, SND_PCM_STREAM_PLAYBACK, 0) + guard openResult >= 0, let handle: OpaquePointer = pcm else { + throw ALSAError.playbackDeviceOpenFailed(device: device, code: Int(openResult)) + } + playbackPCM = handle + try configure(handle, channels: outputChannels, stream: "playback") + } + + private func openCapture() throws { + var pcm: OpaquePointer? + let openResult: Int32 = snd_pcm_open(&pcm, captureDevice, SND_PCM_STREAM_CAPTURE, 0) + guard openResult >= 0, let handle: OpaquePointer = pcm else { + throw ALSAError.captureDeviceOpenFailed(device: captureDevice, code: Int(openResult)) + } + capturePCM = handle + try configure(handle, channels: inputChannels, stream: "capture") + + // One clock for both streams — without this, two independently clocked + // devices drift and the loop eventually blocks on one of them. + if let playback: OpaquePointer = playbackPCM { + linkedStreams = snd_pcm_link(handle, playback) >= 0 + } + } + + /// Applies format, access mode, rate, channel count, and latency in one + /// call. `snd_pcm_set_params` is ALSA's own convenience over the hw/sw + /// params dance and negotiates a period for the requested latency. + private func configure(_ pcm: OpaquePointer, channels: Int, stream: String) throws { + let latencySeconds: Double = + Double(blockSize * periodsPerBuffer) / sampleRate + let latencyMicroseconds: UInt32 = UInt32(latencySeconds * Self.microsecondsPerSecond) + let softResample: Int32 = allowSoftwareResampling ? 1 : 0 + + let paramResult: Int32 = snd_pcm_set_params( + pcm, + SND_PCM_FORMAT_FLOAT_LE, + SND_PCM_ACCESS_RW_INTERLEAVED, + UInt32(channels), + UInt32(sampleRate), + softResample, + latencyMicroseconds + ) + guard paramResult >= 0 else { + throw ALSAError.parameterNegotiationFailed(stream: stream, code: Int(paramResult)) + } + + let prepareResult: Int32 = snd_pcm_prepare(pcm) + guard prepareResult >= 0 else { + throw ALSAError.prepareFailed(stream: stream, code: Int(prepareResult)) + } + } + + private func closeDevices() { + // A thread we gave up waiting for still owns these handles. Closing + // them out from under it is the use-after-free this whole path exists + // to avoid; they stay open until the process exits. + guard !_abandonedThread.load(ordering: .acquiring) else { return } + if let capture: OpaquePointer = capturePCM { + // Unlink before closing so a restart can link a fresh pair. + if linkedStreams { snd_pcm_unlink(capture) } + snd_pcm_drop(capture) + snd_pcm_close(capture) + capturePCM = nil + } + if let playback: OpaquePointer = playbackPCM { + snd_pcm_drop(playback) + snd_pcm_close(playback) + playbackPCM = nil + } + linkedStreams = false + } + + // MARK: - Render thread + + /// Retains `engine` for the render thread and returns its pointer as a bit + /// pattern — the form that survives `Thread`'s `@Sendable` closure boundary. + /// Balanced by exactly one ``releaseEngine(bits:)``. + /// + /// Exposed so the retain/release round trip can be pinned by a test: the + /// balance across the render loop's exit paths only runs against real + /// hardware, and an imbalance here is a leak or a use-after-free. + @_spi(LyrebirdExtensions) + public static func retainForRenderThread(_ engine: Unmanaged) -> UInt { + UInt(bitPattern: engine.retain().toOpaque()) + } + + /// Balances one ``retainForRenderThread(_:)``. + @_spi(LyrebirdExtensions) + public static func releaseEngine(bits: UInt) { + guard let pointer: UnsafeMutableRawPointer = UnsafeMutableRawPointer(bitPattern: bits) else { return } + Unmanaged.fromOpaque(pointer).release() + } + + private func renderLoop(engineBits: UInt) { + guard let enginePointer: UnsafeMutableRawPointer = UnsafeMutableRawPointer(bitPattern: engineBits) else { + // Unreachable: `engineBits` is the bit pattern of a live heap + // pointer, never 0. Balance the retain anyway so the one path that + // does not reach the `defer` below cannot leak the engine. + Self.releaseEngine(bits: engineBits) + _lastError.withLock { $0 = .renderLoopPreconditionFailed } + _isRunning.store(false, ordering: .releasing) + threadExited.signal() + return + } + let retainedEngine: Unmanaged = Unmanaged.fromOpaque(enginePointer) + RTThreadIdentity.markCurrentThreadAsRT() + enableFlushToZero() + if requestsRealtimePriority { + _hasRealtimePriority.store(Self.raiseCurrentThreadPriority(), ordering: .releasing) + } + defer { + // Clear the flag on every exit, including the error paths, so the + // driver's state matches reality and a later `start()` is not + // silently ignored. Signalled last: `stop()` closes the PCM handles + // as soon as it sees this, and by then the loop must be done with + // them. + _isRunning.store(false, ordering: .releasing) + // Balances the `passRetained` in `start()`. Reached on every exit + // path this loop has; only a thread that never returns keeps the + // engine alive, which is exactly the case that needs it. + retainedEngine.release() + threadExited.signal() + } + + let engine: SynthesisEngine = retainedEngine.takeUnretainedValue() + guard let playback: OpaquePointer = playbackPCM, + let output: UnsafeMutablePointer = interleavedOutput else { + // Exiting here produces silence with no other symptom, so record why + // rather than letting a driver that never ran look healthy. + _lastError.withLock { $0 = .renderLoopPreconditionFailed } + return + } + + // Read once, before the loop. The abandon path deliberately writes + // nothing, but `closeDevices()` does nil these after a clean join, and + // hoisting means the loop body does not depend on that ordering + // holding at every iteration. + let capture: OpaquePointer? = capturePCM + let input: UnsafeMutablePointer? = interleavedInput + + while _isRunning.load(ordering: .acquiring) { + if let capture: OpaquePointer = capture, + let input: UnsafeMutablePointer = input { + guard transfer(pcm: capture, buffer: input, isCapture: true) else { return } + lyrebirdDeinterleave( + input, + into: &inputStagingBuffers, + frameCount: blockSize, + channelCount: inputChannels + ) + } + + engine.processBlock(inputSamples: inputStagingBuffers) + + lyrebirdInterleave( + engine.audioBuses, + into: output, + frameCount: blockSize, + channelCount: outputChannels + ) + guard transfer(pcm: playback, buffer: output, isCapture: false) else { return } + } + } + + /// Moves exactly `blockSize` frames in or out, resuming after short + /// transfers and recovering from underruns. + /// + /// - Returns: `false` when the stream is unrecoverable or the driver was + /// asked to stop, meaning the render loop should exit. + private func transfer( + pcm: OpaquePointer, + buffer: UnsafeMutablePointer, + isCapture: Bool + ) -> Bool { + let channels: Int = isCapture ? inputChannels : outputChannels + var framesDone: Int = 0 + var consecutiveStalls: Int = 0 + var consecutiveInterrupts: Int = 0 + + while framesDone < blockSize { + guard _isRunning.load(ordering: .acquiring) else { return false } + let cursor: UnsafeMutablePointer = buffer + framesDone * channels + let remaining: UInt = UInt(blockSize - framesDone) + let result: Int = isCapture + ? snd_pcm_readi(pcm, cursor, remaining) + : snd_pcm_writei(pcm, cursor, remaining) + + switch ALSARecoveryAction.classify(result) { + case .transferred(let frames): + framesDone += frames + // A zero-frame transfer makes no progress, so it cannot reset + // the budget — otherwise a device that keeps returning 0 spins + // this loop forever at `SCHED_FIFO`, which is the failure the + // budget exists to stop. + if frames > 0 { + consecutiveStalls = 0 + consecutiveInterrupts = 0 + } else if !tolerateStall(result: result, isCapture: isCapture, count: &consecutiveStalls) { + return false + } + case .interrupted: + // A signal, not a device problem: reissue without spending the + // stall budget, since profilers and interval timers deliver + // these to perfectly healthy streams. Still bounded, and with a + // yield — a signal source faster than the syscall would + // otherwise busy-spin a `SCHED_FIFO` thread with nothing but + // `_isRunning` to break out. + consecutiveInterrupts += 1 + guard consecutiveInterrupts <= Self.maxConsecutiveInterrupts else { + _lastError.withLock { + $0 = .transferFailed( + stream: isCapture ? "capture" : "playback", + code: result + ) + } + return false + } + sched_yield() + continue + case .wouldBlock: + // A blocking PCM should not return would-block, but a plugin + // chain (dmix, a non-blocking `.asoundrc` device) can. Spinning + // on it from a `SCHED_FIFO` thread would starve the machine, so + // sleep on the device and give up if it never becomes ready. + guard tolerateStall(result: result, isCapture: isCapture, count: &consecutiveStalls) else { + return false + } + _ = snd_pcm_wait(pcm, Self.deviceWaitMilliseconds) + case .recover: + // Underrun or suspend: re-prepare and reissue from the same + // frame. The samples already handed over are gone either way. + // An xrun moves no frames, so it spends the budget like any + // other no-progress result — clearing it here let a device + // alternating underruns with would-block returns loop forever. + guard tolerateStall(result: result, isCapture: isCapture, count: &consecutiveStalls) else { + return false + } + if snd_pcm_recover(pcm, Int32(result), Self.recoverSilently) < 0 { + _lastError.withLock { + $0 = .prepareFailed( + stream: isCapture ? "capture" : "playback", + code: result + ) + } + return false + } + case .fail: + _lastError.withLock { + $0 = .transferFailed( + stream: isCapture ? "capture" : "playback", + code: result + ) + } + return false + } + } + return true + } + + /// Counts one transfer that moved no frames, and reports whether the + /// stream has any patience left. + /// + /// - Returns: `false` once the budget is spent, having recorded the error. + private func tolerateStall(result: Int, isCapture: Bool, count: inout Int) -> Bool { + count += 1 + guard Self.stallBudgetExhausted(consecutiveStalls: count) else { return true } + _lastError.withLock { + $0 = .transferFailed( + stream: isCapture ? "capture" : "playback", + code: result + ) + } + return false + } + + /// Whether this many consecutive no-progress transfers means the stream is + /// dead rather than merely slow. + /// + /// Exposed so the boundary can be pinned by a test: the loop that consults + /// it only runs against real hardware, and an off-by-one here either kills + /// a healthy stream one attempt early or never gives up at all. + @_spi(LyrebirdExtensions) + public static func stallBudgetExhausted(consecutiveStalls: Int) -> Bool { + consecutiveStalls > maxConsecutiveStalls + } + + /// Asks the kernel for `SCHED_FIFO` on the calling thread. + /// + /// - Returns: `true` if granted. Denial is the normal case for an + /// unprivileged process and is not an error — audio still runs, just + /// without scheduling protection. + private static func raiseCurrentThreadPriority() -> Bool { + let lowest: Int32 = sched_get_priority_min(SCHED_FIFO) + let highest: Int32 = sched_get_priority_max(SCHED_FIFO) + guard lowest >= 0, highest > lowest else { return false } + let span: Double = Double(highest - lowest) + var params: sched_param = sched_param() + params.sched_priority = lowest + Int32(span * realtimePriorityFraction) + return pthread_setschedparam(pthread_self(), SCHED_FIFO, ¶ms) == 0 + } +} + +#endif diff --git a/Sources/Lyrebird/AudioDrivers/ALSAError.swift b/Sources/Lyrebird/AudioDrivers/ALSAError.swift new file mode 100644 index 0000000..4940630 --- /dev/null +++ b/Sources/Lyrebird/AudioDrivers/ALSAError.swift @@ -0,0 +1,37 @@ +// ALSAError.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Errors thrown by `ALSAAudioDriver` during setup or start. +/// +/// Every case carries the raw ALSA return code where one exists; pass it to +/// `snd_strerror` for the system's own description. Declared unconditionally +/// (not behind the Linux guard) so cross-platform code can name the type. +public enum ALSAError: Error, Equatable, Sendable { + /// `snd_pcm_open` failed for the playback device. Associated values are the + /// device name asked for and the ALSA error code. + case playbackDeviceOpenFailed(device: String, code: Int) + /// `snd_pcm_open` failed for the capture device. + case captureDeviceOpenFailed(device: String, code: Int) + /// `snd_pcm_set_params` rejected the requested format, rate, channel count, + /// or latency for the named stream. + case parameterNegotiationFailed(stream: String, code: Int) + /// `snd_pcm_prepare` failed — either before the render loop started, or + /// when recovering from an underrun inside it. + case prepareFailed(stream: String, code: Int) + /// A `snd_pcm_writei` / `snd_pcm_readi` transfer failed with an error the + /// render loop cannot recover from (device removed, bad descriptor). + case transferFailed(stream: String, code: Int) + /// `setup(engine:)` was never called, so there is nothing to start. + case notConfigured + /// The render thread did not leave its loop within the stop timeout — + /// almost always a transfer wedged inside the driver. The PCM handles and + /// staging buffers are deliberately leaked rather than freed under a thread + /// that may still be using them. + case renderThreadDidNotExit + /// The render loop exited before it could start: the engine reference or a + /// staging buffer was missing. + case renderLoopPreconditionFailed +} diff --git a/Sources/Lyrebird/AudioDrivers/ALSARecoveryAction.swift b/Sources/Lyrebird/AudioDrivers/ALSARecoveryAction.swift new file mode 100644 index 0000000..fb8d950 --- /dev/null +++ b/Sources/Lyrebird/AudioDrivers/ALSARecoveryAction.swift @@ -0,0 +1,68 @@ +// ALSARecoveryAction.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// What an ALSA PCM transfer's return value tells the render loop to do next. +/// +/// `snd_pcm_writei` / `snd_pcm_readi` return a frame count on success and a +/// negative errno on failure, and the correct response differs per error: an +/// underrun is routine and recoverable, a signal interruption just needs the +/// same call again, and anything else means the device is gone. Getting this +/// wrong is how a driver either spins forever or dies on the first xrun. The +/// two transient cases are kept apart deliberately: a signal is not a device +/// problem and must not consume the patience budget that a device which never +/// becomes ready does. +/// +/// The classification is pure arithmetic over the return value, so it is +/// tested on every platform even though the driver that consumes it +/// (`ALSAAudioDriver`) only compiles on Linux. +public enum ALSARecoveryAction: Equatable, Sendable { + /// Transfer succeeded. The associated value is the number of frames moved, + /// which may be fewer than requested — the caller must resume from there. + case transferred(frames: Int) + /// A signal interrupted the call (`-EINTR`). Reissue immediately: nothing + /// is wrong with the device, and a profiler or interval timer can deliver + /// signals indefinitely without the stream being unhealthy. + case interrupted + /// The device is not ready (`-EAGAIN`). Wait for it, and give up if it + /// never becomes ready — this one *is* evidence of a sick stream. + case wouldBlock + /// Underrun/overrun (`-EPIPE`) or suspend (`-ESTRPIPE`). Call + /// `snd_pcm_recover` (or `snd_pcm_prepare`), then reissue. + case recover + /// Unrecoverable. Surface the error and stop the render thread. + case fail + + // Linux errno values, spelled out rather than imported. ALSA is a Linux + // API, so these are the numbers it returns wherever this code is compiled; + // taking them from the host's `errno.h` instead would make the same input + // classify differently on a non-Linux host (`EAGAIN` is 11 on Linux and 35 + // on Darwin), which would make the tests lie. + private static let eintr: Int = 4 + private static let eagain: Int = 11 + private static let epipe: Int = 32 + private static let estrpipe: Int = 86 + + /// Classifies the return value of an ALSA PCM transfer call. + /// + /// - Parameter result: Value returned by `snd_pcm_writei` / `snd_pcm_readi` + /// — frames transferred when non-negative, negative errno otherwise. + /// - Returns: The action the render loop should take. + public static func classify(_ result: Int) -> ALSARecoveryAction { + if result >= 0 { + return .transferred(frames: result) + } + switch -result { + case eintr: + return .interrupted + case eagain: + return .wouldBlock + case epipe, estrpipe: + return .recover + default: + return .fail + } + } +} diff --git a/Sources/Lyrebird/AudioDrivers/AUv3Driver.swift b/Sources/Lyrebird/AudioDrivers/AUv3Driver.swift index 56bae95..f6e87b9 100644 --- a/Sources/Lyrebird/AudioDrivers/AUv3Driver.swift +++ b/Sources/Lyrebird/AudioDrivers/AUv3Driver.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(AudioToolbox) import Foundation import AudioToolbox import AVFoundation @@ -510,3 +511,4 @@ public let auv3DriverDefaultMaxFramesToRender: Int = 1024 /// the ring. Larger values give more slack for hosts that pull busses /// asynchronously at the cost of memory. public let auv3RingBufferHeadroomFactor: Int = 2 +#endif diff --git a/Sources/Lyrebird/AudioDrivers/CoreAudioDriver.swift b/Sources/Lyrebird/AudioDrivers/CoreAudioDriver.swift index a56c9f7..2c638c3 100644 --- a/Sources/Lyrebird/AudioDrivers/CoreAudioDriver.swift +++ b/Sources/Lyrebird/AudioDrivers/CoreAudioDriver.swift @@ -5,6 +5,7 @@ // SPDX-License-Identifier: MIT #if os(macOS) +#if canImport(AudioToolbox) import CoreAudio import AudioToolbox import Synchronization @@ -822,3 +823,4 @@ private func lyrebirdRenderCallback( ) } #endif +#endif diff --git a/Sources/Lyrebird/AudioDrivers/DefaultAudioDriver.swift b/Sources/Lyrebird/AudioDrivers/DefaultAudioDriver.swift new file mode 100644 index 0000000..0329145 --- /dev/null +++ b/Sources/Lyrebird/AudioDrivers/DefaultAudioDriver.swift @@ -0,0 +1,58 @@ +// DefaultAudioDriver.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Returns the live-audio driver for the platform this build targets. +/// +/// Which drivers exist is not a property of the operating system alone — the +/// Linux `ALSAAudioDriver` is present only when the build linked libasound +/// (see the `LYREBIRD_DISABLE_ALSA` opt-out in `Package.swift`, and note that a +/// Linux binary cross-compiled from macOS has no ALSA at all). Only code inside +/// this module can see that, so any `#if` written in *consumer* code to pick a +/// driver is guessing. Call this instead: +/// +/// ```swift +/// let engine = SynthesisEngine( +/// blockSize: 512, sampleRate: 44100, +/// numOutputChannels: 2, numInputChannels: 0, +/// driver: makeDefaultAudioDriver() +/// ) +/// ``` +/// +/// Resolution order: `iOSAudioDriver` on iOS, `CoreAudioDriver` on macOS, +/// `ALSAAudioDriver` on a Linux build with ALSA, and ``OfflineDriver`` where +/// no live backend exists. (`ALSAAudioDriver` is written in code font rather +/// than as a symbol link because it does not exist in an Apple build, where +/// this documentation is generated.) +/// +/// > Important: the ``OfflineDriver`` fallback runs the graph on demand and +/// > produces no sound. Check ``isLiveAudioAvailable`` when silence would be a +/// > surprise — for example before printing "now playing" to a user. +public func makeDefaultAudioDriver() -> any AudioDriver { + #if canImport(AudioToolbox) + #if os(iOS) + return iOSAudioDriver() + #else + return CoreAudioDriver() + #endif + #elseif canImport(CALSA) + return ALSAAudioDriver() + #else + return OfflineDriver() + #endif +} + +/// Whether this build has a live-audio backend at all. +/// +/// `false` means ``makeDefaultAudioDriver()`` returns an ``OfflineDriver`` and +/// nothing will reach a speaker: a Linux build without libasound, a Linux +/// binary cross-compiled from macOS, or a platform with no driver yet. +public var isLiveAudioAvailable: Bool { + #if canImport(AudioToolbox) || canImport(CALSA) + return true + #else + return false + #endif +} diff --git a/Sources/Lyrebird/AudioDrivers/InterleaveHelpers.swift b/Sources/Lyrebird/AudioDrivers/InterleaveHelpers.swift new file mode 100644 index 0000000..d759caf --- /dev/null +++ b/Sources/Lyrebird/AudioDrivers/InterleaveHelpers.swift @@ -0,0 +1,87 @@ +// InterleaveHelpers.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// Channel-layout conversion shared by audio drivers whose hardware API wants +// interleaved frames while the engine works in per-channel planar buses. +// +// Deliberately free of any platform import: the ALSA driver that consumes these +// only compiles on Linux, but the conversion itself is ordinary arithmetic and +// is the easiest part of a driver to get subtly wrong (transposed indices +// produce audio that is quiet, channel-swapped, or aliased rather than silent). +// Keeping it here means it compiles — and is tested — on every platform. + +/// Writes `frameCount` frames of planar `buses` into an interleaved buffer. +/// +/// Channels beyond `buses.count`, and frames beyond a bus's own length, are +/// written as silence, so a short or missing bus can never read out of bounds. +/// +/// - Parameters: +/// - buses: Planar per-channel sample buffers. Only the first `channelCount` +/// are read. +/// - out: Destination for `frameCount * channelCount` interleaved samples. +/// Must have room for all of them. +/// - frameCount: Frames to write. +/// - channelCount: Channels per frame in `out`. +@_spi(LyrebirdExtensions) +public func lyrebirdInterleave( + _ buses: [[Float]], + into out: UnsafeMutablePointer, + frameCount: Int, + channelCount: Int +) { + for channel: Int in 0.. = src.baseAddress else { return } + let available: Int = min(frameCount, src.count) + for frame: Int in 0.., + into buses: inout [[Float]], + frameCount: Int, + channelCount: Int +) { + let channels: Int = min(channelCount, buses.count) + for channel: Int in 0.. = dst.baseAddress else { return } + let available: Int = min(frameCount, dst.count) + for frame: Int in 0.. 0 { + let skipFrames: Int = Int(inputStartOffset * reader.sampleRate) + if skipFrames > 0 { try reader.skip(frames: skipFrames) } + } + inputReader = reader + inputStagingBuffers = [[Float]](repeating: [Float](repeating: 0, count: engine.blockSize), + count: inputChannelCount) + #endif } - /// Render synchronously to the output file. - /// - /// - Throws: `NRTDriverError.invalidDuration` if `duration` is negative, NaN, - /// or infinite; `NRTDriverError.fileTooLargeForContainer` if a WAV/AIFF render - /// is projected past the 4 GB RIFF cap (use `.cafFloat32` for long renders); - /// or the file/IO error cases on create/write failure. For the `.rf64*` - /// formats, a ``RF64WriterError`` may surface instead of an `NRTDriverError`. + /// Render synchronously to the output file. See ``NRTDriverError`` for the + /// failure cases (invalid duration, 4 GB container overflow, format + /// unsupported off Apple, and the underlying I/O errors). public func start() throws { guard let engine: SynthesisEngine else { return } - // Validate duration before any Double→Int conversion: Int(_:) traps on a - // non-finite or out-of-range value, and a negative duration would make the - // render loop's `0..= 0, blocksDouble < Double(Int.max) else { throw NRTDriverError.invalidDuration(duration) } - - // Total render blocks — computed once and shared by the large-file guard and - // the render loop below, so the two can never drift out of sync. let totalBlocks: Int = Int(blocksDouble) - // Large-file guard: reject a WAV/AIFF render projected past the 4 GB RIFF/AIFF - // cap before opening the file, so we never emit a truncated/corrupt output. - // CAF is exempt. `projectedByteCount` (inside riffOverflow) saturates on - // overflow, so a frame count near Int.max still yields the correct decision. + // Large-file guard: reject a WAV/AIFF render past the 4 GB RIFF/AIFF cap. let (projectedFrames, framesOverflow): (Int, Bool) = totalBlocks.multipliedReportingOverflow(by: engine.blockSize) let effectiveFrames: Int = framesOverflow ? Int.max : projectedFrames @@ -176,17 +180,18 @@ public final class NRTDriver: AudioDriver { ) } + let bs: Int = engine.blockSize + let nch: Int = engine.numOutputChannels + + #if canImport(AudioToolbox) // Dispose the input file regardless of which output backend construction (or - // the render) throws below — registered before backend selection so an early - // throw can't leak it. + // the render) throws below. defer { if let ref: ExtAudioFileRef = inputFileRef { ExtAudioFileDispose(ref) } inputFileRef = nil } - // Choose the output backend: RF64Writer (hand-rolled 64-bit WAV) for the RF64 - // cases, else ExtAudioFile for CAF / WAV / AIFF. The engine renders Float32, so - // both back-ends receive native Float32 interleaved samples. + // Choose the output backend: RF64Writer for the RF64 cases, else ExtAudioFile. let rf64Writer: RF64Writer? = outputFormat.usesRF64Writer ? try RF64Writer(url: outputURL, format: outputFormat, sampleRate: engine.sampleRate, channels: engine.numOutputChannels) @@ -210,8 +215,6 @@ public final class NRTDriver: AudioDriver { guard status == noErr, let createdRef: ExtAudioFileRef else { throw NRTDriverError.cannotCreateFile(status) } - // Client format: always native Float32 interleaved. ExtAudioFile converts - // Float32 → int16/int24 on write for the integer WAV formats. var clientFormat: AudioStreamBasicDescription = outputFormat.makeClientASBD( sampleRate: engine.sampleRate, channels: engine.numOutputChannels @@ -226,7 +229,6 @@ public final class NRTDriver: AudioDriver { ExtAudioFileDispose(createdRef) throw NRTDriverError.cannotSetFormat(status) } - // Compressed (AAC) formats: push the target bitrate into the encoder. let encoderStatus: OSStatus = outputFormat.applyEncoderConfig(to: createdRef) guard encoderStatus == noErr else { ExtAudioFileDispose(createdRef) @@ -235,53 +237,16 @@ public final class NRTDriver: AudioDriver { extFileRef = createdRef } - // Guarantee disposal even if an error is thrown mid-render. defer { if let ref: ExtAudioFileRef = extFileRef { ExtAudioFileDispose(ref) } - try? rf64Writer?.close() // idempotent; explicit close below patches ds64 sizes + try? rf64Writer?.close() } - // Render loop — synchronous, no RT constraints. `totalBlocks` was computed - // once above (shared with the large-file guard). - let bs: Int = engine.blockSize - let nch: Int = engine.numOutputChannels - for _ in 0...size), - mData: ptr.baseAddress - ) - ) - return ExtAudioFileRead(inputRef, &framesToRead, &bufList) - } - guard readStatus == noErr else { throw NRTDriverError.inputReadFailed(readStatus) } - let framesRead: Int = Int(framesToRead) - for f: Int in 0.. [[Float]] { + guard inputChannelCount > 0 else { return [] } + for ch: Int in 0...size), + mData: ptr.baseAddress + ) + ) + return ExtAudioFileRead(inputRef, &framesToRead, &bufList) + } + guard readStatus == noErr else { throw NRTDriverError.inputReadFailed(readStatus) } + let framesRead: Int = Int(framesToRead) + for f: Int in 0.. 0 ? block.count / fileChannels : 0 + for f: Int in 0.. WavEncoding { + switch format { + case .wavFloat32: return .float32 + case .wavInt16: return .int16 + case .wavInt24: return .int24 + // RF64 needs 64-bit `ds64` sizing the portable classic-RIFF writer does + // not emit; mapping it to a 32-bit WAV would silently truncate/trap past + // 4 GB. Unsupported off Apple until a portable RF64 writer exists. + case .rf64Float32, .rf64Int24, .cafFloat32, .aiffFloat32, .aacHigh, .aacMedium, .alac: + throw NRTDriverError.unsupportedFormatOnPlatform(format) + } + } + #endif } // MARK: - Errors @@ -347,8 +407,9 @@ public enum NRTDriverError: Error { /// `duration` was negative, NaN, or infinite. Pass a finite, non-negative value. case invalidDuration(Double) /// The render is projected to exceed the output container's 4 GB (32-bit size - /// field) limit. Only WAV/AIFF are capped; CAF is exempt. `projectedBytes` is - /// the estimated audio-data size, `cap` is `lyrebirdMaxRIFFBytes`. Re-run with - /// `format: .cafFloat32` (64-bit sizes, uncapped) or shorten the duration. + /// field) limit. Only WAV/AIFF are capped; CAF is exempt. case fileTooLargeForContainer(projectedBytes: Int, cap: Int) + /// The requested format is not available on this (non-Apple) platform. Only the + /// WAV encodings render off Apple; use `.wavFloat32` / `.wavInt16` / `.wavInt24`. + case unsupportedFormatOnPlatform(AudioFileFormat) } diff --git a/Sources/Lyrebird/AudioDrivers/iOSAudioDriver.swift b/Sources/Lyrebird/AudioDrivers/iOSAudioDriver.swift index f808467..4252949 100644 --- a/Sources/Lyrebird/AudioDrivers/iOSAudioDriver.swift +++ b/Sources/Lyrebird/AudioDrivers/iOSAudioDriver.swift @@ -5,6 +5,7 @@ // SPDX-License-Identifier: MIT #if os(iOS) +#if canImport(AudioToolbox) import CoreAudio import AudioToolbox import AVFoundation @@ -339,3 +340,4 @@ private func lyrebirdIOSRenderCallback( ) } #endif +#endif diff --git a/Sources/Lyrebird/Buffers/AudioFileFormat+AudioToolbox.swift b/Sources/Lyrebird/Buffers/AudioFileFormat+AudioToolbox.swift new file mode 100644 index 0000000..2910972 --- /dev/null +++ b/Sources/Lyrebird/Buffers/AudioFileFormat+AudioToolbox.swift @@ -0,0 +1,145 @@ +// AudioFileFormat+AudioToolbox.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// AudioToolbox-backed members of `AudioFileFormat`: `ExtAudioFile` container +// type IDs, the file/client `AudioStreamBasicDescription` factories, and the +// compressed-encoder configuration. Split out from the portable enum so the +// core (and every soundfile-format consumer) builds on platforms without +// AudioToolbox; on Linux/Windows these members simply do not exist and the +// portable WAV codec is used instead. + +#if canImport(AudioToolbox) +import AudioToolbox + +extension AudioFileFormat { + + /// AudioToolbox container type ID passed to `ExtAudioFileCreateWithURL`. + /// + /// Not meaningful for the RF64 cases (they are written by ``RF64Writer``, not + /// `ExtAudioFile`); those return `kAudioFileWAVEType` as an inert default. + public var audioFileTypeID: AudioFileTypeID { + switch self { + case .wavFloat32, .wavInt16, .wavInt24, .rf64Float32, .rf64Int24: + return kAudioFileWAVEType + case .aiffFloat32: + return kAudioFileAIFCType // AIFF-C: carries Float32; classic AIFF does not + case .cafFloat32: + return kAudioFileCAFType + case .aacHigh, .aacMedium, .alac: + return kAudioFileM4AType + } + } +} + +// MARK: - ASBD factories (module-internal) + +/// Encoder packet geometry (samples per packet) for the compressed codecs. +private let aacFramesPerPacket: UInt32 = 1024 +private let alacFramesPerPacket: UInt32 = 4096 + +extension AudioFileFormat { + + /// Build the *file* `AudioStreamBasicDescription` for this format: linear PCM + /// with the case's bit depth, encoding flags, and endianness, interleaved + /// across `channels`. + /// + /// - Parameters: + /// - sampleRate: Sample rate embedded in the file header, in Hz. + /// - channels: Interleaved channel count. Must be ≥ 1. + func makeFileASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription { + if isCompressed { + var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription() + asbd.mSampleRate = sampleRate + asbd.mChannelsPerFrame = UInt32(channels) + if aacBitrate != nil { + asbd.mFormatID = kAudioFormatMPEG4AAC + asbd.mFramesPerPacket = aacFramesPerPacket + } else { + asbd.mFormatID = kAudioFormatAppleLossless + asbd.mFramesPerPacket = alacFramesPerPacket + asbd.mFormatFlags = kAppleLosslessFormatFlag_24BitSourceData + } + return asbd + } + + let bytesPerSample: UInt32 = fileBitsPerChannel / Self.bitsPerByte + let bytesPerFrame: UInt32 = bytesPerSample * UInt32(channels) + + var flags: AudioFormatFlags = kAudioFormatFlagIsPacked + flags |= isFloatEncoding ? kAudioFormatFlagIsFloat : kAudioFormatFlagIsSignedInteger + if isBigEndian { flags |= kAudioFormatFlagIsBigEndian } + + return AudioStreamBasicDescription( + mSampleRate: sampleRate, + mFormatID: kAudioFormatLinearPCM, + mFormatFlags: flags, + mBytesPerPacket: bytesPerFrame, + mFramesPerPacket: 1, + mBytesPerFrame: bytesPerFrame, + mChannelsPerFrame: UInt32(channels), + mBitsPerChannel: fileBitsPerChannel, + mReserved: 0 + ) + } + + /// Build the *client* `AudioStreamBasicDescription`: always native-endian + /// Float32 interleaved across `channels`, independent of the file encoding. + /// + /// - Parameters: + /// - sampleRate: Sample rate, in Hz. Should match the file ASBD. + /// - channels: Interleaved channel count. Must be ≥ 1. + func makeClientASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription { + let bytesPerFrame: UInt32 = lyrebirdBytesPerSample * UInt32(channels) + return AudioStreamBasicDescription( + mSampleRate: sampleRate, + mFormatID: kAudioFormatLinearPCM, + mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked, + mBytesPerPacket: bytesPerFrame, + mFramesPerPacket: 1, + mBytesPerFrame: bytesPerFrame, + mChannelsPerFrame: UInt32(channels), + mBitsPerChannel: lyrebirdBitsPerSample, + mReserved: 0 + ) + } +} + +// MARK: - Compressed encoder configuration + +extension AudioFileFormat { + + /// After an `ExtAudioFile` for a compressed format has been created and its client + /// (Float32) format set, push the target AAC bitrate into the underlying + /// `AudioConverter`. No-op for non-AAC formats. + /// + /// Returns `noErr` on success (or when nothing needed doing), else the failing + /// `OSStatus`. Call from a non-RT thread, before the first `ExtAudioFileWrite`. + func applyEncoderConfig(to fileRef: ExtAudioFileRef) -> OSStatus { + guard let bitrate: Int = aacBitrate else { return noErr } + + var converter: AudioConverterRef? + var converterSize: UInt32 = UInt32(MemoryLayout.size) + let getStatus: OSStatus = ExtAudioFileGetProperty( + fileRef, kExtAudioFileProperty_AudioConverter, &converterSize, &converter + ) + guard getStatus == noErr, let converter: AudioConverterRef else { return getStatus } + + var rate: UInt32 = UInt32(bitrate) + let setStatus: OSStatus = AudioConverterSetProperty( + converter, kAudioConverterEncodeBitRate, UInt32(MemoryLayout.size), &rate + ) + guard setStatus == noErr else { return setStatus } + + var config: CFPropertyList? = nil + return withUnsafePointer(to: &config) { ptr in + ExtAudioFileSetProperty( + fileRef, kExtAudioFileProperty_ConverterConfig, + UInt32(MemoryLayout.size), ptr + ) + } + } +} +#endif diff --git a/Sources/Lyrebird/Buffers/AudioFileFormat.swift b/Sources/Lyrebird/Buffers/AudioFileFormat.swift index 1c6324a..444b405 100644 --- a/Sources/Lyrebird/Buffers/AudioFileFormat.swift +++ b/Sources/Lyrebird/Buffers/AudioFileFormat.swift @@ -4,28 +4,23 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import AudioToolbox - /// Container-and-encoding format shared by every Lyrebird soundfile writer: /// ``LyrebirdBuffer/write(to:format:sampleRate:)`` (offline buffer dump), /// ``DiskOut/Audio`` (real-time streaming recorder), and the NRT driver /// (offline score render). /// /// Each case pins both the container (WAV / AIFF-C / CAF) and the PCM sample -/// encoding (Float32, or signed-integer 16/24-bit). Writers always hand -/// `ExtAudioFile` native-Float32 samples as the *client* format (see -/// `makeClientASBD(sampleRate:channels:)`) and let it convert to the *file* -/// format (`makeFileASBD(sampleRate:channels:)`) — so integer encodings cost -/// the caller nothing beyond selecting the case. +/// encoding (Float32, or signed-integer 16/24-bit). The enum and its derived +/// properties are pure Swift and portable; the AudioToolbox-backed members +/// (`ExtAudioFile` type IDs and `AudioStreamBasicDescription` factories) live in +/// `AudioFileFormat+AudioToolbox.swift` under `#if canImport(AudioToolbox)`. /// /// ## Container notes /// - **WAV** — little-endian, cross-platform standard. Supports Float32 and /// signed-integer PCM. Classic RIFF caps total file size at 4 GB (32-bit size /// fields); large renders should fall back to `.cafFloat32`. -/// - **AIFF-C** (`.aiffFloat32`) — big-endian by spec. Uses `kAudioFileAIFCType` -/// (not classic `kAudioFileAIFFType`, which is integer-only) so it can carry -/// Float32 while keeping the `.aiff` extension. Best restricted to ≤ 2 channels -/// for compatibility with legacy readers; also 4 GB-capped. +/// - **AIFF-C** (`.aiffFloat32`) — big-endian by spec. Best restricted to +/// ≤ 2 channels for compatibility with legacy readers; also 4 GB-capped. /// - **CAF** (`.cafFloat32`) — Apple's flexible container: any sample rate, any /// channel count up to `lyrebirdMaxFileChannelCount`, 64-bit sizes (no 4 GB /// cap). Default for buffer and NRT writes. @@ -79,24 +74,7 @@ public enum AudioFileFormat: Sendable { /// CAF / Float32. Alias for ``cafFloat32``. public static let caf: AudioFileFormat = .cafFloat32 - // MARK: - Derived properties - - /// AudioToolbox container type ID passed to `ExtAudioFileCreateWithURL`. - /// - /// Not meaningful for the RF64 cases (they are written by ``RF64Writer``, not - /// `ExtAudioFile`); those return `kAudioFileWAVEType` as an inert default. - public var audioFileTypeID: AudioFileTypeID { - switch self { - case .wavFloat32, .wavInt16, .wavInt24, .rf64Float32, .rf64Int24: - return kAudioFileWAVEType - case .aiffFloat32: - return kAudioFileAIFCType // AIFF-C: carries Float32; classic AIFF does not - case .cafFloat32: - return kAudioFileCAFType - case .aacHigh, .aacMedium, .alac: - return kAudioFileM4AType - } - } + // MARK: - Derived properties (portable) /// Filesystem extension for the output file (no leading dot). public var fileExtension: String { @@ -154,8 +132,8 @@ public enum AudioFileFormat: Sendable { /// Target AAC encode bitrate in bits/second, or `nil` for non-AAC formats. public var aacBitrate: Int? { switch self { - case .aacHigh: return aacHighBitrate - case .aacMedium: return aacMediumBitrate + case .aacHigh: return Self.aacHighBitrate + case .aacMedium: return Self.aacMediumBitrate case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32, .rf64Float32, .rf64Int24, .alac: return nil @@ -171,8 +149,6 @@ public enum AudioFileFormat: Sendable { /// ``RF64Writer`` — see ``usesRF64Writer``. public var supportsLargeFiles: Bool { switch self { - // CAF/RF64 are 64-bit-sized; the compressed M4A cases are not RIFF at all, - // so the 4 GB RIFF/AIFF guard never applies to them either. case .cafFloat32, .rf64Float32, .rf64Int24, .aacHigh, .aacMedium, .alac: return true case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32: @@ -193,7 +169,7 @@ public enum AudioFileFormat: Sendable { } } -// MARK: - Large-file guard +// MARK: - Large-file guard (portable) extension AudioFileFormat { @@ -203,11 +179,9 @@ extension AudioFileFormat { /// /// Pure integer arithmetic — safe to evaluate for hypothetical sizes without /// allocating anything. **Saturates to `Int.max` on overflow** rather than - /// trapping: any frame count large enough to overflow the byte product is, by - /// definition, far past any container cap, so a saturated value gives the guard - /// the correct "over cap" answer without a crash. + /// trapping. func projectedByteCount(frameCount: Int, channels: Int) -> Int { - let bytesPerSample: Int = Int(fileBitsPerChannel / bitsPerByte) + let bytesPerSample: Int = Int(fileBitsPerChannel / Self.bitsPerByte) let (samples, sampleOverflow): (Int, Bool) = frameCount.multipliedReportingOverflow(by: channels) if sampleOverflow { return Int.max } let (bytes, byteOverflow): (Int, Bool) = samples.multipliedReportingOverflow(by: bytesPerSample) @@ -217,10 +191,6 @@ extension AudioFileFormat { /// Returns `(projected, cap)` when writing `frameCount × channels` frames in /// this format would overflow the container's addressable size, or `nil` when /// the write fits (or the container is 64-bit — see ``supportsLargeFiles``). - /// - /// The single decision point behind both the `LyrebirdBuffer.write` and - /// `NRTDriver` large-file guards, so the guard reads off the format rather - /// than a hardcoded case list. func riffOverflow(frameCount: Int, channels: Int) -> (projected: Int, cap: Int)? { guard !supportsLargeFiles else { return nil } let projected: Int = projectedByteCount(frameCount: frameCount, channels: channels) @@ -228,134 +198,18 @@ extension AudioFileFormat { } } -// MARK: - ASBD factories (module-internal) - -/// Number of bits in a byte — names the `/ 8` in bytes-per-sample derivations. -private let bitsPerByte: UInt32 = 8 - -/// Encoder packet geometry (samples per packet) for the compressed codecs. -private let aacFramesPerPacket: UInt32 = 1024 -private let alacFramesPerPacket: UInt32 = 4096 - -/// AAC target bitrates (bits/second) for the two quality tiers. -private let aacHighBitrate: Int = 256_000 -private let aacMediumBitrate: Int = 128_000 +// MARK: - Shared format constants extension AudioFileFormat { + // Nested rather than file-scope: these are visible across files (the + // `+AudioToolbox` extension needs them), and names this generic do not + // belong in the module's global namespace. - /// Build the *file* `AudioStreamBasicDescription` for this format: linear PCM - /// with the case's bit depth, encoding flags, and endianness, interleaved - /// across `channels`. - /// - /// This is the descriptor handed to `ExtAudioFileCreateWithURL`. Pair it with - /// `makeClientASBD(sampleRate:channels:)` as the client format so - /// `ExtAudioFile` performs any Float32 → integer / endian conversion. - /// - /// - Parameters: - /// - sampleRate: Sample rate embedded in the file header, in Hz. - /// - channels: Interleaved channel count. Must be ≥ 1. - func makeFileASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription { - // Compressed codecs (AAC / ALAC): the encoder fills in the packet geometry. - // We supply the format ID, channel count, sample rate, and frames-per-packet; - // `AudioConverter` (behind `ExtAudioFile`) computes the rest. - if isCompressed { - var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription() - asbd.mSampleRate = sampleRate - asbd.mChannelsPerFrame = UInt32(channels) - // AAC vs ALAC: the AAC tiers carry a bitrate, ALAC does not. Deriving the - // codec from `aacBitrate` avoids a `switch self` with an unreachable - // default that could silently leave `mFormatID == 0` for a future case. - if aacBitrate != nil { - asbd.mFormatID = kAudioFormatMPEG4AAC - asbd.mFramesPerPacket = aacFramesPerPacket - } else { - asbd.mFormatID = kAudioFormatAppleLossless - asbd.mFramesPerPacket = alacFramesPerPacket - asbd.mFormatFlags = kAppleLosslessFormatFlag_24BitSourceData - } - return asbd - } + /// Number of bits in a byte — names the `/ 8` in bytes-per-sample derivations. + static let bitsPerByte: UInt32 = 8 - let bytesPerSample: UInt32 = fileBitsPerChannel / bitsPerByte - let bytesPerFrame: UInt32 = bytesPerSample * UInt32(channels) - - var flags: AudioFormatFlags = kAudioFormatFlagIsPacked - flags |= isFloatEncoding ? kAudioFormatFlagIsFloat : kAudioFormatFlagIsSignedInteger - if isBigEndian { flags |= kAudioFormatFlagIsBigEndian } - - return AudioStreamBasicDescription( - mSampleRate: sampleRate, - mFormatID: kAudioFormatLinearPCM, - mFormatFlags: flags, - mBytesPerPacket: bytesPerFrame, - mFramesPerPacket: 1, - mBytesPerFrame: bytesPerFrame, - mChannelsPerFrame: UInt32(channels), - mBitsPerChannel: fileBitsPerChannel, - mReserved: 0 - ) - } - - /// Build the *client* `AudioStreamBasicDescription`: always native-endian - /// Float32 interleaved across `channels`, independent of the file encoding. - /// - /// Every Lyrebird writer feeds `ExtAudioFile` Float32 samples; the file format - /// (from `makeFileASBD(sampleRate:channels:)`) drives the conversion. - /// - /// - Parameters: - /// - sampleRate: Sample rate, in Hz. Should match the file ASBD. - /// - channels: Interleaved channel count. Must be ≥ 1. - func makeClientASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription { - let bytesPerFrame: UInt32 = lyrebirdBytesPerSample * UInt32(channels) - return AudioStreamBasicDescription( - mSampleRate: sampleRate, - mFormatID: kAudioFormatLinearPCM, - mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked, - mBytesPerPacket: bytesPerFrame, - mFramesPerPacket: 1, - mBytesPerFrame: bytesPerFrame, - mChannelsPerFrame: UInt32(channels), - mBitsPerChannel: lyrebirdBitsPerSample, - mReserved: 0 - ) - } -} - -// MARK: - Compressed encoder configuration - -extension AudioFileFormat { - - /// After an `ExtAudioFile` for a compressed format has been created and its client - /// (Float32) format set, push the target AAC bitrate into the underlying - /// `AudioConverter`. No-op for non-AAC formats (ALAC has no bitrate; PCM has none). - /// - /// Returns `noErr` on success (or when nothing needed doing), else the failing - /// `OSStatus`. Call from a non-RT thread, before the first `ExtAudioFileWrite`. - func applyEncoderConfig(to fileRef: ExtAudioFileRef) -> OSStatus { - guard let bitrate: Int = aacBitrate else { return noErr } - - var converter: AudioConverterRef? - var converterSize: UInt32 = UInt32(MemoryLayout.size) - let getStatus: OSStatus = ExtAudioFileGetProperty( - fileRef, kExtAudioFileProperty_AudioConverter, &converterSize, &converter - ) - guard getStatus == noErr, let converter: AudioConverterRef else { return getStatus } - - var rate: UInt32 = UInt32(bitrate) - let setStatus: OSStatus = AudioConverterSetProperty( - converter, kAudioConverterEncodeBitRate, UInt32(MemoryLayout.size), &rate - ) - guard setStatus == noErr else { return setStatus } - - // Notify ExtAudioFile that the converter config changed so it re-reads it. - // The property value is a `CFPropertyList?` = NULL; pass a pointer to a nil - // variable (NOT a null data pointer — CoreAudio dereferences the pointer). - var config: CFPropertyList? = nil - return withUnsafePointer(to: &config) { ptr in - ExtAudioFileSetProperty( - fileRef, kExtAudioFileProperty_ConverterConfig, - UInt32(MemoryLayout.size), ptr - ) - } - } + /// AAC target bitrate (bits/second) for the high-quality tier. + static let aacHighBitrate: Int = 256_000 + /// AAC target bitrate (bits/second) for the medium-quality tier. + static let aacMediumBitrate: Int = 128_000 } diff --git a/Sources/Lyrebird/Buffers/LyrebirdBuffer.swift b/Sources/Lyrebird/Buffers/LyrebirdBuffer.swift index a3a9c7c..e5d769e 100644 --- a/Sources/Lyrebird/Buffers/LyrebirdBuffer.swift +++ b/Sources/Lyrebird/Buffers/LyrebirdBuffer.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation import Synchronization diff --git a/Sources/Lyrebird/Buffers/LyrebirdBufferFileIO.swift b/Sources/Lyrebird/Buffers/LyrebirdBufferFileIO.swift index 04a3ce8..fc6a672 100644 --- a/Sources/Lyrebird/Buffers/LyrebirdBufferFileIO.swift +++ b/Sources/Lyrebird/Buffers/LyrebirdBufferFileIO.swift @@ -5,12 +5,15 @@ // SPDX-License-Identifier: MIT import Foundation +#if canImport(AudioToolbox) import AudioToolbox +#endif // MARK: - LyrebirdBufferIOError /// Errors thrown by `LyrebirdBuffer` file I/O methods. public enum LyrebirdBufferIOError: Error, Equatable { + #if canImport(AudioToolbox) /// `ExtAudioFileOpenURL` failed with the given status code. case cannotOpenFile(OSStatus) /// Querying the file's `AudioStreamBasicDescription` failed. @@ -21,22 +24,30 @@ public enum LyrebirdBufferIOError: Error, Equatable { case cannotSetClientFormat(OSStatus) /// `ExtAudioFileRead` returned a non-zero status. case readFailed(OSStatus) - /// The requested channel index is outside the range of channels in the file. - case channelOutOfRange(requested: Int, available: Int) - /// The file's ASBD reports a channel count that is 0 or exceeds `lyrebirdMaxFileChannelCount`. - /// This guard fires in `queryFileProperties` before any allocation using the channel count. - case invalidChannelCount(Int) /// `ExtAudioFileCreateWithURL` failed when creating the output file. case cannotCreateOutputFile(OSStatus) /// Setting the output file's client format failed. case cannotSetOutputFormat(OSStatus) /// `ExtAudioFileWrite` returned a non-zero status. case writeFailed(OSStatus) + #endif + /// The requested channel index is outside the range of channels in the file. + case channelOutOfRange(requested: Int, available: Int) + /// The file's ASBD reports a channel count that is 0 or exceeds `lyrebirdMaxFileChannelCount`. + /// This guard fires in `queryFileProperties` before any allocation using the channel count. + case invalidChannelCount(Int) /// The requested WAV/AIFF write is projected to exceed the container's 4 GB /// (32-bit size field) limit. `projectedBytes` is the estimated audio-data /// size; `cap` is `lyrebirdMaxRIFFBytes`. Re-issue the write with `.cafFloat32` /// (64-bit sizes, uncapped), shorten the buffer, or split it. case fileTooLargeForContainer(projectedBytes: Int, cap: Int) + #if !canImport(AudioToolbox) + /// A non-WAV container (`.caf` / `.aiff` / `.aac` / `.alac` / RF64) was + /// requested for `write(to:format:)` off Apple, where only the portable WAV + /// encodings are available. Reading uses the portable ``WavFileReader``, + /// whose failures surface as ``WavFileError``. + case unsupportedFormatOnPlatform(AudioFileFormat) + #endif } // MARK: - Constants @@ -45,8 +56,10 @@ public enum LyrebirdBufferIOError: Error, Equatable { /// Small enough to keep stack pressure low; large enough to amortize the per-call overhead. private let lyrebirdFileIOChunkFrames: Int = 4096 +#if canImport(AudioToolbox) /// Bit depth of the Float32 client format used for all file I/O reads and writes. private let lyrebirdFileIOBitsPerSample: UInt32 = 32 +#endif // MARK: - LyrebirdBuffer + File I/O @@ -77,6 +90,7 @@ public extension LyrebirdBuffer { channel: Int = 0, normalise: Bool = false ) throws -> LyrebirdBuffer { + #if canImport(AudioToolbox) var fileRef: ExtAudioFileRef? let openStatus: OSStatus = ExtAudioFileOpenURL(url as CFURL, &fileRef) guard openStatus == noErr, let fileRef: ExtAudioFileRef else { @@ -103,6 +117,27 @@ public extension LyrebirdBuffer { normalise: normalise ) return buffer + #else + // Portable WAV read. `WavFileReader` throws `WavFileError` on a bad or + // non-WAV file. Like the Apple path, the buffer keeps the file's own + // sample rate — neither path resamples on load. + let reader: WavFileReader = try WavFileReader(url: url) + defer { reader.close() } + let fileChannelCount: Int = reader.channels + guard channel < fileChannelCount else { + throw LyrebirdBufferIOError.channelOutOfRange( + requested: channel, available: fileChannelCount + ) + } + let fileFrameCount: Int = reader.frameCount + let buffer: LyrebirdBuffer = LyrebirdBuffer(count: max(1, fileFrameCount)) + buffer.setSampleRate(reader.sampleRate) + try portableReadMono( + reader, into: buffer, channel: channel, + framesToRead: fileFrameCount, normalise: normalise + ) + return buffer + #endif } // MARK: - loadAllChannels(url:normalise:) @@ -126,6 +161,7 @@ public extension LyrebirdBuffer { url: URL, normalise: Bool = false ) throws -> LyrebirdBuffer { + #if canImport(AudioToolbox) var fileRef: ExtAudioFileRef? let openStatus: OSStatus = ExtAudioFileOpenURL(url as CFURL, &fileRef) guard openStatus == noErr, let fileRef: ExtAudioFileRef else { @@ -150,6 +186,25 @@ public extension LyrebirdBuffer { normalise: normalise ) return buffer + #else + let reader: WavFileReader = try WavFileReader(url: url) + defer { reader.close() } + let fileChannelCount: Int = reader.channels + guard fileChannelCount >= 1 && fileChannelCount <= lyrebirdMaxFileChannelCount else { + throw LyrebirdBufferIOError.invalidChannelCount(fileChannelCount) + } + let fileFrameCount: Int = reader.frameCount + let buffer: LyrebirdBuffer = LyrebirdBuffer( + count: max(1, fileFrameCount), + channelCount: fileChannelCount + ) + buffer.setSampleRate(reader.sampleRate) + try portableReadAllChannels( + reader, into: buffer, + framesToRead: fileFrameCount, normalise: normalise + ) + return buffer + #endif } // MARK: - fill(fromFile:channel:normalise:) @@ -178,6 +233,8 @@ public extension LyrebirdBuffer { ) precondition(isValid, "fill(fromFile:) called on an invalidated LyrebirdBuffer") + let framesToRead: Int + #if canImport(AudioToolbox) var fileRef: ExtAudioFileRef? let openStatus: OSStatus = ExtAudioFileOpenURL(url as CFURL, &fileRef) guard openStatus == noErr, let fileRef: ExtAudioFileRef else { @@ -193,7 +250,7 @@ public extension LyrebirdBuffer { } self.setSampleRate(fileSampleRate) - let framesToRead: Int = min(fileFrameCount, count) + framesToRead = min(fileFrameCount, count) try readSamples( from: fileRef, into: self, @@ -203,6 +260,22 @@ public extension LyrebirdBuffer { framesToRead: framesToRead, normalise: normalise ) + #else + let reader: WavFileReader = try WavFileReader(url: url) + defer { reader.close() } + let fileChannelCount: Int = reader.channels + guard channel < fileChannelCount else { + throw LyrebirdBufferIOError.channelOutOfRange( + requested: channel, available: fileChannelCount + ) + } + self.setSampleRate(reader.sampleRate) + framesToRead = min(reader.frameCount, count) + try portableReadMono( + reader, into: self, channel: channel, + framesToRead: framesToRead, normalise: normalise + ) + #endif // Zero-pad if the file was shorter than the buffer. if framesToRead < count { @@ -294,6 +367,7 @@ public extension LyrebirdBuffer { return } + #if canImport(AudioToolbox) // File format: container/encoding/endianness per `format`. var fileFormat: AudioStreamBasicDescription = format.makeFileASBD(sampleRate: sampleRate, channels: channelCount) @@ -366,11 +440,57 @@ public extension LyrebirdBuffer { srcOffset += samplesThisChunk } } + #else + // Portable WAV output. The Apple-only containers (CAF / AIFF-C / AAC / + // ALAC) have no portable encoder; RF64 was already handled above by the + // cross-platform `RF64Writer`. Everything else is a classic-RIFF WAV. + let encoding: WavEncoding = try Self.wavEncoding(for: format) + let writer: WavFileWriter = try WavFileWriter( + url: url, channels: channelCount, sampleRate: sampleRate, encoding: encoding + ) + // Finalize even if a write throws partway, so the file's header sizes + // are patched rather than left at zero. `finalize()` is idempotent. + defer { try? writer.finalize() } + let samplesPerChunk: Int = lyrebirdFileIOChunkFrames * channelCount + var writeBuf: [Float] = [Float](repeating: 0, count: samplesPerChunk) + try withStorage { storage, frameCount, nch in + let totalSamples: Int = frameCount * nch + var srcOffset: Int = 0 + while srcOffset < totalSamples { + let samplesThisChunk: Int = min(samplesPerChunk, totalSamples - srcOffset) + let framesThisChunk: Int = samplesThisChunk / nch + for i: Int in 0.. WavEncoding { + switch format { + case .wavFloat32: return .float32 + case .wavInt16: return .int16 + case .wavInt24: return .int24 + case .rf64Float32, .rf64Int24, .cafFloat32, .aiffFloat32, .aacHigh, .aacMedium, .alac: + throw LyrebirdBufferIOError.unsupportedFormatOnPlatform(format) + } + } + #endif } // MARK: - Private helpers +#if canImport(AudioToolbox) + /// Query an open `ExtAudioFileRef` for its frame count, channel count, and sample rate. /// /// Validates that `mChannelsPerFrame` is in `[1, lyrebirdMaxFileChannelCount]` before @@ -588,3 +708,84 @@ private func readAllChannels( } } } +#else + +// MARK: - Portable read helpers (non-Apple) + +/// Reads one channel of a WAV into a mono buffer's storage, in chunks, with +/// optional peak normalisation. Mirrors the Apple ``readSamples`` helper. +private func portableReadMono( + _ reader: WavFileReader, + into buffer: LyrebirdBuffer, + channel: Int, + framesToRead: Int, + normalise: Bool +) throws { + let fileChannelCount: Int = reader.channels + try buffer.withMutableStorage { storage, _, _ in + var destOffset: Int = 0 + while destOffset < framesToRead { + let framesThisChunk: Int = min(lyrebirdFileIOChunkFrames, framesToRead - destOffset) + let block: [Float] = try reader.read(frames: framesThisChunk) + let framesRead: Int = fileChannelCount > 0 ? block.count / fileChannelCount : 0 + if framesRead == 0 { break } + for i: Int in 0.. 0 { + var peak: Double = 0.0 + for i: Int in 0.. peak { peak = v } + } + if peak > 0.0 { + for i: Int in 0.. 0 ? block.count / fileChannelCount : 0 + if framesRead == 0 { break } + for f: Int in 0.. 0 { + let totalSamples: Int = framesToRead * bufChannelCount + var peak: Double = 0.0 + for i: Int in 0.. peak { peak = v } + } + if peak > 0.0 { + for i: Int in 0.. "WAVE". + let riff: Data = try Self.readExact(h, 12) + guard riff.prefix(4).elementsEqual(Array("RIFF".utf8)), + riff.subdata(in: 8..<12).elementsEqual(Array("WAVE".utf8)) else { + throw WavFileError.notWave + } + + var fmtTag: UInt16 = 0 + var numChannels: UInt16 = 0 + var rate: UInt32 = 0 + var bits: UInt16 = 0 + var dataLength: Int = 0 + var foundFmt: Bool = false + var foundData: Bool = false + // File length, for clamping a `data` size the file cannot back. Taken + // by seeking to the end and back rather than stat-ing the path, so it + // describes the handle actually being read. + let scanStart: UInt64 = try h.offset() + let fileByteCount: Int = Int(try h.seekToEnd()) + try h.seek(toOffset: scanStart) + + // Walk chunks until the data chunk is located (its body is left unread + // so reads stream from the current file offset). + while true { + guard let chunkHeader: Data = try? Self.readExact(h, 8), chunkHeader.count == 8 else { + break + } + let id: Data = chunkHeader.prefix(4) + let size: Int = Int(Self.readLE32(chunkHeader, at: 4)) + if id.elementsEqual(Array("fmt ".utf8)) { + // A `fmt ` chunk always carries at least the 16 PCM bytes. + // Anything shorter is malformed, and reading the fields at + // their fixed offsets would index past the chunk and trap. + guard size >= Self.minimumFmtChunkSize else { throw WavFileError.truncated } + let fmt: Data = try Self.readExact(h, size) + guard fmt.count >= Self.minimumFmtChunkSize else { throw WavFileError.truncated } + fmtTag = Self.readLE16(fmt, at: 0) + numChannels = Self.readLE16(fmt, at: 2) + rate = Self.readLE32(fmt, at: 4) + bits = Self.readLE16(fmt, at: 14) + // WAVE_FORMAT_EXTENSIBLE is what most 24-bit and multichannel + // writers emit; the real encoding lives in the first two bytes + // of the SubFormat GUID, and the rest of the header is + // identical. Rejecting it outright would refuse ordinary files. + if fmtTag == Self.waveFormatExtensible, fmt.count >= Self.extensibleFmtChunkSize { + fmtTag = Self.readLE16(fmt, at: Self.subFormatTagOffset) + } + foundFmt = true + // Chunks are word-aligned: skip a pad byte after an odd size. + if size % 2 == 1 { _ = try? Self.readExact(h, 1) } + } else if id.elementsEqual(Array("data".utf8)) { + // Trust the file, but not past its own end: streaming writers + // leave a placeholder size (often 0xFFFFFFFF) they never patch, + // and believing it yields a nonsense frame count and a + // `.truncated` throw partway through a render instead of a + // clean EOF. + let remaining: Int = max(0, fileByteCount - Int(try h.offset())) + dataLength = min(size, remaining) + foundData = true + break + } else { + // Unknown chunk (e.g. "fact", "LIST"): skip its padded body by + // seeking. Reading it would materialise the whole thing just to + // discard it, and a file with embedded artwork or a large + // "LIST" ahead of `data` makes that a real allocation. + let skip: Int = size + (size % 2) + let current: UInt64 = try h.offset() + let target: UInt64 = current + UInt64(max(0, skip)) + guard target <= UInt64(fileByteCount) else { break } + try h.seek(toOffset: target) + } + } + + guard foundFmt, foundData else { throw WavFileError.truncated } + guard let enc: WavEncoding = Self.encoding(formatTag: fmtTag, bits: bits) else { + throw WavFileError.unsupportedFormat(formatTag: fmtTag, bitsPerSample: bits) + } + + self.encoding = enc + self.channels = Int(numChannels) + self.sampleRate = Double(rate) + self.bytesPerFrame = Int(numChannels) * enc.bytesPerSample + let totalFrames: Int = bytesPerFrame > 0 ? dataLength / bytesPerFrame : 0 + self.frameCount = totalFrames + self.framesRemaining = totalFrames + } + + /// Reads up to `frames` frames, returning interleaved `Float` samples. The + /// returned array holds `framesRead * channels` values; `framesRead` may be + /// smaller than requested at end of file (and zero once exhausted). + public func read(frames: Int) throws -> [Float] { + let toRead: Int = min(frames, framesRemaining) + guard toRead > 0 else { return [] } + let byteCount: Int = toRead * bytesPerFrame + let raw: Data = try Self.readExact(handle, byteCount) + framesRemaining -= toRead + + let sampleCount: Int = toRead * channels + var out: [Float] = [Float](repeating: 0, count: sampleCount) + raw.withUnsafeBytes { (rawPtr: UnsafeRawBufferPointer) in + switch encoding { + case .float32: + for i: Int in 0.. 0 else { return } + let current: UInt64 = try handle.offset() + try handle.seek(toOffset: current + UInt64(toSkip * bytesPerFrame)) + framesRemaining -= toSkip + } + + /// Closes the underlying file handle. + public func close() { + try? handle.close() + } + + // MARK: - Parsing helpers + + /// Smallest legal `fmt ` chunk: the 16 bytes of a plain PCM header. + private static let minimumFmtChunkSize: Int = 16 + /// `fmt ` size that carries the full `WAVEFORMATEXTENSIBLE` payload. + private static let extensibleFmtChunkSize: Int = 40 + /// Byte offset of the SubFormat GUID's leading format tag within `fmt `. + private static let subFormatTagOffset: Int = 24 + /// `WAVE_FORMAT_EXTENSIBLE` — the real tag hides in the SubFormat GUID. + private static let waveFormatExtensible: UInt16 = 0xFFFE + + private static func encoding(formatTag: UInt16, bits: UInt16) -> WavEncoding? { + switch (formatTag, bits) { + case (3, 32): return .float32 + case (1, 16): return .int16 + case (1, 24): return .int24 + default: return nil + } + } + + private static func readExact(_ h: FileHandle, _ count: Int) throws -> Data { + guard count > 0 else { return Data() } + guard let d: Data = try h.read(upToCount: count), d.count == count else { + throw WavFileError.truncated + } + return d + } + + private static func readLE16(_ d: Data, at offset: Int) -> UInt16 { + let base: Data.Index = d.startIndex + offset + return UInt16(d[base]) | (UInt16(d[base + 1]) << 8) + } + + private static func readLE32(_ d: Data, at offset: Int) -> UInt32 { + let base: Data.Index = d.startIndex + offset + return UInt32(d[base]) | (UInt32(d[base + 1]) << 8) + | (UInt32(d[base + 2]) << 16) | (UInt32(d[base + 3]) << 24) + } + + private static func loadLE16(_ p: UnsafeRawBufferPointer, byteOffset: Int) -> UInt16 { + UInt16(p[byteOffset]) | (UInt16(p[byteOffset + 1]) << 8) + } + + private static func loadLE32(_ p: UnsafeRawBufferPointer, byteOffset: Int) -> UInt32 { + UInt32(p[byteOffset]) | (UInt32(p[byteOffset + 1]) << 8) + | (UInt32(p[byteOffset + 2]) << 16) | (UInt32(p[byteOffset + 3]) << 24) + } +} diff --git a/Sources/Lyrebird/Buffers/WavFileWriter.swift b/Sources/Lyrebird/Buffers/WavFileWriter.swift new file mode 100644 index 0000000..13d24d7 --- /dev/null +++ b/Sources/Lyrebird/Buffers/WavFileWriter.swift @@ -0,0 +1,243 @@ +// WavFileWriter.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Streaming writer for canonical RIFF/WAVE PCM files, portable to every +/// platform (no `AudioToolbox` dependency). +/// +/// Designed for the offline-render block model: construct once, call +/// ``write(interleaved:frames:)`` per rendered block, then ``finalize()`` to +/// patch the RIFF/`data` chunk sizes. Samples are supplied interleaved +/// (`frame0ch0, frame0ch1, frame1ch0, …`) as `Float` in `[-1, 1]`; integer +/// encodings clamp and round, float32 stores losslessly. +public final class WavFileWriter { + + private let channels: Int + private let encoding: WavEncoding + private let handle: FileHandle + private var dataBytesWritten: Int = 0 + private var finalized: Bool = false + /// Whether the RIFF word-align pad byte has already been appended. + private var padByteWritten: Bool = false + /// Byte count of this file's header, which depends on the encoding — see + /// ``headerSize(for:)``. + private let headerByteCount: Int + /// Offset of the `data` chunk's size field, patched by ``finalize()``. + private let dataChunkSizeOffset: UInt64 + + // Integer PCM uses the canonical 44-byte header: 12 RIFF/WAVE + 24 `fmt ` + // (8 header + 16 body) + 8 `data` header. + private static let pcmHeaderSize: Int = 44 + /// Non-PCM tags (float32) must declare `cbSize`, making the `fmt ` body 18 + /// bytes, and must carry a `fact` chunk. That is 2 more `fmt ` bytes plus a + /// 12-byte `fact` chunk: 44 + 2 + 12. + private static let nonPCMHeaderSize: Int = 58 + private static let riffChunkSizeOffset: UInt64 = 4 + /// `fact`'s sample-count field, present only in the non-PCM layout. + private static let factSampleCountOffset: UInt64 = 46 + private static let pcmDataChunkSizeOffset: UInt64 = 40 + private static let nonPCMDataChunkSizeOffset: UInt64 = 54 + /// `fmt ` body size for plain PCM tags, and for tags that need `cbSize`. + private static let pcmFmtBodySize: UInt32 = 16 + private static let extendedFmtBodySize: UInt32 = 18 + /// `fact` chunk body: one `UInt32` sample count. + private static let factBodySize: UInt32 = 4 + + /// Header length for `encoding`. Non-PCM formats carry more (see above). + private static func headerSize(for encoding: WavEncoding) -> Int { + encoding.isPCM ? pcmHeaderSize : nonPCMHeaderSize + } + + /// - Parameters: + /// - url: Destination file path. Overwritten if it exists. + /// - channels: Interleaved channel count. Must be ≥ 1. + /// - sampleRate: Sample rate in Hz. + /// - encoding: PCM encoding. Defaults to ``WavEncoding/float32``. + public init( + url: URL, + channels: Int, + sampleRate: Double, + encoding: WavEncoding = .float32 + ) throws { + precondition(channels >= 1, "WavFileWriter requires at least one channel") + self.channels = channels + self.encoding = encoding + self.headerByteCount = Self.headerSize(for: encoding) + self.dataChunkSizeOffset = encoding.isPCM + ? Self.pcmDataChunkSizeOffset + : Self.nonPCMDataChunkSizeOffset + + let header: Data = Self.makeHeader( + channels: channels, + sampleRate: sampleRate, + encoding: encoding + ) + let fm: FileManager = FileManager.default + guard fm.createFile(atPath: url.path, contents: header) else { + throw WavFileError.cannotCreate(url) + } + self.handle = try FileHandle(forWritingTo: url) + try handle.seekToEnd() + } + + /// Appends one block of interleaved `Float` samples. + /// + /// - Parameters: + /// - samples: Interleaved buffer, length ≥ `frames * channels`. + /// - frames: Number of frames (per-channel sample groups) to write. + public func write(interleaved samples: [Float], frames: Int) throws { + let needed: Int = frames * channels + precondition(samples.count >= needed, "interleaved buffer shorter than frames * channels") + var out: Data = Data(capacity: needed * encoding.bytesPerSample) + switch encoding { + case .float32: + for i: Int in 0..> 8)) + out.append(UInt8(truncatingIfNeeded: v >> 16)) + } + } + try handle.write(contentsOf: out) + dataBytesWritten += out.count + } + + deinit { + // Last-resort finalize: a writer dropped without one leaves an open + // descriptor and a header whose sizes are still zero, i.e. a file no + // reader can use. Errors here have nowhere to go, hence `try?`. + try? finalize() + } + + /// Patches the RIFF and `data` chunk sizes and closes the file. Idempotent. + public func finalize() throws { + guard !finalized else { return } + // Chunks are word-aligned: an odd `data` payload (possible with int24) + // needs a pad byte, which counts toward the RIFF size but not the + // `data` size. Recorded before the patch sequence below, so a + // `finalize()` that throws partway and is retried — by an explicit + // second call, or by `deinit` — does not append a second pad byte while + // sizing the file for one. + let padByteCount: Int = dataBytesWritten % 2 + if padByteCount > 0 && !padByteWritten { + try handle.seekToEnd() + try handle.write(contentsOf: [UInt8(0)]) + padByteWritten = true + } + let riffChunkSize: UInt32 = try Self.riffChunkSize( + headerBytes: headerByteCount, + dataBytes: dataBytesWritten + padByteCount + ) + let dataChunkSize: UInt32 = UInt32(dataBytesWritten) + + try handle.seek(toOffset: Self.riffChunkSizeOffset) + try handle.write(contentsOf: Self.leBytes(riffChunkSize)) + if !encoding.isPCM { + // `fact` carries the per-channel sample count, which is only known + // now that writing has finished. + let bytesPerFrame: Int = channels * encoding.bytesPerSample + let frames: UInt32 = bytesPerFrame > 0 + ? UInt32(dataBytesWritten / bytesPerFrame) + : 0 + try handle.seek(toOffset: Self.factSampleCountOffset) + try handle.write(contentsOf: Self.leBytes(frames)) + } + try handle.seek(toOffset: dataChunkSizeOffset) + try handle.write(contentsOf: Self.leBytes(dataChunkSize)) + try handle.close() + // Set last: a throw above must leave the writer retryable rather than + // latching "finalized" over a file whose sizes are still zero. + finalized = true + } + + /// RIFF chunk size for a file with this header and payload. + /// + /// Split out so the 4 GB boundary can be tested without writing 4 GB: the + /// conversion below would *trap* rather than throw, and a trap in a render + /// that has been running for an hour is the worst possible outcome. + /// + /// - Throws: ``WavFileError/fileTooLarge(bytes:)`` past `UInt32.max`. + @_spi(LyrebirdExtensions) + public static func riffChunkSize(headerBytes: Int, dataBytes: Int) throws -> UInt32 { + let payload: Int = headerBytes - 8 + dataBytes + guard payload <= Int(UInt32.max) else { + throw WavFileError.fileTooLarge(bytes: payload) + } + return UInt32(payload) + } + + // MARK: - Header + + private static func makeHeader( + channels: Int, + sampleRate: Double, + encoding: WavEncoding + ) -> Data { + let numChannels: UInt16 = UInt16(channels) + let rate: UInt32 = UInt32(sampleRate.rounded()) + let blockAlign: UInt16 = UInt16(channels * encoding.bytesPerSample) + let byteRate: UInt32 = rate * UInt32(blockAlign) + // RIFF requires a non-PCM tag to declare `cbSize` (so the `fmt ` body + // is 18 bytes, not 16) and to carry a `fact` chunk. Strict readers + // reject a float32 file that omits either. + let isPCM: Bool = encoding.isPCM + let subchunk1Size: UInt32 = isPCM ? pcmFmtBodySize : extendedFmtBodySize + + var d: Data = Data(capacity: headerSize(for: encoding)) + d.append(contentsOf: Array("RIFF".utf8)) + d.append(contentsOf: leBytes(UInt32(0))) // patched in finalize + d.append(contentsOf: Array("WAVE".utf8)) + d.append(contentsOf: Array("fmt ".utf8)) + d.append(contentsOf: leBytes(subchunk1Size)) + d.append(contentsOf: leBytes(encoding.formatTag)) + d.append(contentsOf: leBytes(numChannels)) + d.append(contentsOf: leBytes(rate)) + d.append(contentsOf: leBytes(byteRate)) + d.append(contentsOf: leBytes(blockAlign)) + d.append(contentsOf: leBytes(encoding.bitsPerSample)) + if !isPCM { + d.append(contentsOf: leBytes(UInt16(0))) // cbSize: no extension + d.append(contentsOf: Array("fact".utf8)) + d.append(contentsOf: leBytes(factBodySize)) + d.append(contentsOf: leBytes(UInt32(0))) // patched in finalize + } + d.append(contentsOf: Array("data".utf8)) + d.append(contentsOf: leBytes(UInt32(0))) // patched in finalize + return d + } + + // Extract bytes low-first from the native value. The right shifts already + // yield little-endian order on any host, so no `.littleEndian` pre-swap + // (which, combined with these shifts, would double-transform on a big-endian host). + private static func leBytes(_ value: UInt32) -> [UInt8] { + return [UInt8(truncatingIfNeeded: value), UInt8(truncatingIfNeeded: value >> 8), + UInt8(truncatingIfNeeded: value >> 16), UInt8(truncatingIfNeeded: value >> 24)] + } + + private static func leBytes(_ value: UInt16) -> [UInt8] { + return [UInt8(truncatingIfNeeded: value), UInt8(truncatingIfNeeded: value >> 8)] + } +} diff --git a/Sources/Lyrebird/Buffers/WavetableSet.swift b/Sources/Lyrebird/Buffers/WavetableSet.swift index de0d8b5..bb6de9e 100644 --- a/Sources/Lyrebird/Buffers/WavetableSet.swift +++ b/Sources/Lyrebird/Buffers/WavetableSet.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation // MARK: - WavetableSet diff --git a/Sources/Lyrebird/Buses/ScratchBuses.swift b/Sources/Lyrebird/Buses/ScratchBuses.swift index 158bc78..a09ae67 100644 --- a/Sources/Lyrebird/Buses/ScratchBuses.swift +++ b/Sources/Lyrebird/Buses/ScratchBuses.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Per-child scratch audio bus memory for `ParallelGroup` concurrent evaluation. /// diff --git a/Sources/Lyrebird/Engine/RTThreadIdentity.swift b/Sources/Lyrebird/Engine/RTThreadIdentity.swift index aab0f74..09c25aa 100644 --- a/Sources/Lyrebird/Engine/RTThreadIdentity.swift +++ b/Sources/Lyrebird/Engine/RTThreadIdentity.swift @@ -4,7 +4,17 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +// Thread-local-storage APIs: pthread (`pthread_key_*` / `*specific`) on Apple & +// POSIX, Win32 (`Tls*`) on Windows. +#if canImport(Darwin) import Darwin +#elseif canImport(WinSDK) +import WinSDK +#elseif canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#endif /// Identifies whether the calling thread is currently inside an audio driver's /// render callback. @@ -25,31 +35,54 @@ import Darwin /// at one TLS pointer read in the steady state. internal enum RTThreadIdentity { - // MARK: - pthread TLS key + // MARK: - TLS key /// Sentinel bit pattern stored in the TLS slot to mark "this is an RT - /// thread". Stored as `UInt` (Sendable) and bridged to the pointer type - /// expected by `pthread_setspecific` / `pthread_getspecific` at use sites. + /// thread". Bridged to the pointer type the TLS APIs expect at use sites. /// Any non-zero bit pattern works; `1` is distinct from any real heap /// address. private static let _markerBitPattern: UInt = 1 - /// pthread TLS key. Created lazily on first access — always from a - /// non-RT call site (engine init / driver setup) because - /// ``warmUp()`` is invoked there. RT call sites read this after the - /// warm-up, so `pthread_key_create` never runs on the RT thread. - /// - /// `nonisolated(unsafe)` because `pthread_key_t` (a `CUnsignedInt` on - /// Darwin) is a trivially-Sendable scalar; the strict-concurrency - /// checker can't see through the C typealias. The key is written exactly - /// once during the lazy init closure (synchronised by Swift's static-let - /// guarantee) and read-only thereafter. + /// TLS key/index. Created lazily on first access — always from a non-RT + /// call site (engine init / driver setup) because ``warmUp()`` is invoked + /// there, so the allocating call (`pthread_key_create` / `TlsAlloc`) never + /// runs on the RT thread. Written exactly once (Swift's static-let + /// guarantee), read-only thereafter. + #if canImport(WinSDK) + private static let _tlsIndex: DWORD = { + let index: DWORD = TlsAlloc() + // TLS_OUT_OF_INDEXES == 0xFFFFFFFF == DWORD.max. + precondition(index != DWORD.max, "TlsAlloc failed") + return index + }() + #else private static let _key: pthread_key_t = { var key: pthread_key_t = 0 let status: Int32 = pthread_key_create(&key, nil) precondition(status == 0, "pthread_key_create failed with status \(status)") return key }() + #endif + + /// Read the calling thread's TLS slot. O(1), allocation-free, RT-safe. + @inline(__always) + private static func _tlsGet() -> UnsafeMutableRawPointer? { + #if canImport(WinSDK) + return TlsGetValue(_tlsIndex) + #else + return pthread_getspecific(_key) + #endif + } + + /// Write the calling thread's TLS slot. O(1), allocation-free, RT-safe. + @inline(__always) + private static func _tlsSet(_ value: UnsafeMutableRawPointer?) { + #if canImport(WinSDK) + _ = TlsSetValue(_tlsIndex, value) + #else + pthread_setspecific(_key, value) + #endif + } // MARK: - API @@ -57,19 +90,23 @@ internal enum RTThreadIdentity { /// site (engine init / driver setup). Avoids a first-touch allocation on /// the RT thread. internal static func warmUp() { + #if canImport(WinSDK) + _ = _tlsIndex + #else _ = _key + #endif } /// Mark the calling thread as an RT render thread. Idempotent — safe to /// call on every render callback entry; only writes the TLS slot when it /// isn't already marked. /// - /// RT-safe: at most one `pthread_setspecific` call per thread, otherwise - /// a single TLS pointer comparison. No allocation, no locking. + /// RT-safe: at most one TLS write per thread, otherwise a single TLS + /// pointer comparison. No allocation, no locking. internal static func markCurrentThreadAsRT() { let sentinel: UnsafeMutableRawPointer? = UnsafeMutableRawPointer(bitPattern: _markerBitPattern) - if pthread_getspecific(_key) != sentinel { - pthread_setspecific(_key, sentinel) + if _tlsGet() != sentinel { + _tlsSet(sentinel) } } @@ -79,7 +116,7 @@ internal enum RTThreadIdentity { /// any thread. internal static var isCurrentThreadRT: Bool { let sentinel: UnsafeMutableRawPointer? = UnsafeMutableRawPointer(bitPattern: _markerBitPattern) - return pthread_getspecific(_key) == sentinel + return _tlsGet() == sentinel } #if DEBUG @@ -87,11 +124,11 @@ internal enum RTThreadIdentity { /// /// Production never unmarks — an RT render thread stays an RT render thread for the /// engine's life. But tests that call ``markCurrentThreadAsRT()`` on a transient - /// `DispatchQueue(label:)` worker must clear it before that pthread returns to the + /// `DispatchQueue(label:)` worker must clear it before that thread returns to the /// system pool; otherwise the stale marker can false-trip `_lyrebirdAssertNotOnRTThread` /// in a later test that the pool hands the same thread. Not compiled in release. internal static func _clearCurrentThreadRTMarkForTesting() { - pthread_setspecific(_key, nil) + _tlsSet(nil) } #endif } diff --git a/Sources/Lyrebird/Engine/SynthesisEngine.swift b/Sources/Lyrebird/Engine/SynthesisEngine.swift index 49f43c5..6b81ca8 100644 --- a/Sources/Lyrebird/Engine/SynthesisEngine.swift +++ b/Sources/Lyrebird/Engine/SynthesisEngine.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation import Synchronization @@ -901,9 +901,7 @@ public final class SynthesisEngine { self.bufferSwapKillQueue = SPSCQueue( capacity: SynthesisEngine.bufferSwapKillQueueCapacity ) - var tbInfo: mach_timebase_info_data_t = mach_timebase_info_data_t() - mach_timebase_info(&tbInfo) - _machTicksToNs = Double(tbInfo.numer) / Double(tbInfo.denom) + _machTicksToNs = LyrebirdMonotonicClock.ticksToNanos _blockDurationNs = (Double(blockSize) / sampleRate) * SynthesisEngine.nanosecondsPerSecond // Install mainGroup as the sole initial child of rootGroup. This runs pre-start on the @@ -1163,13 +1161,25 @@ public final class SynthesisEngine { /// Steps: /// 1. Drain `pendingQueue` of any events that never reached `applyEvent`, /// releasing `.remove` events' retained refs to balance ARC. - /// 2. `mainGroup._drainNodes` drops every direct child; ARC cascades - /// through nested `PreparedNode` chains to release entire subtrees. + /// 2. `mainGroup._drainNodes` drops every direct child, unbinding each + /// drained synth (and every synth nested inside a drained `Group` + /// subtree) from `self` via `_unbindNodeAndDescendants(_:)` before ARC + /// cascades through the nested `PreparedNode` chains to release the + /// entire subtree. /// 3. Walk `rootGroup` and preserve only the `PreparedNode` that wraps /// `mainGroup`. All other direct children (`.before(mainGroup)` / - /// `.after(mainGroup)` installations) are unlinked. + /// `.after(mainGroup)` installations) are unlinked and unbound the + /// same way. /// 4. Reset `_synthesizerCount` / `_groupCount` to zero. /// 5. Reseed `nodeTreeMirror` so SwiftUI observers see the empty baseline. + /// + /// Unbinding here (rather than leaving it to ARC) is what lets a caller + /// re-`add` the same synth instance — to this engine or a different one — + /// immediately after `stop()` returns, with no `EngineAddError.doubleAdd` + /// and no "wait one processBlock" constraint (unlike `remove(_:)`, whose + /// unbind races the RT thread and therefore documents that wait). `stop()` + /// has already halted the RT thread via `driver.stop()`, so there is no + /// such race here. private func _drainAllNonPersistentNodes() { // 1. Pending queue (events posted by main but never dequeued by the RT // thread). `.remove` carries an `Unmanaged.passRetained` ref that @@ -1196,9 +1206,12 @@ public final class SynthesisEngine { // `carryOverEvents`'s and is wiped at the top of the next block, // so any release here would also double-fire. _releaseRemoveRefs(in: &carryOverEvents) - // 3. mainGroup direct children — ARC cascades to nested chains. - mainGroup._drainNodes { _ in } - // 4. rootGroup: preserve only the mainGroup PreparedNode. + // 3. mainGroup direct children — unbind each drained synth (and its + // nested-Group descendants), then let ARC cascade release the + // subtree as before. + mainGroup._drainNodes { n in self._unbindNodeAndDescendants(n) } + // 4. rootGroup: preserve only the mainGroup PreparedNode; unbind and + // unlink everything else. _drainRootKeepingMainGroup() // 5. Counters and mirror. _synthesizerCount.store(0, ordering: .relaxed) @@ -1206,6 +1219,30 @@ public final class SynthesisEngine { nodeTreeMirror.reset(rootGroup: rootGroup, mainGroup: mainGroup) } + /// Unbind `node.synth` from `self` (no-op if `node.synth` is not a + /// `SynthesizerBase`, or is already unbound), then recurse into a nested + /// `Group`'s children so every synth in a drained subtree is fully + /// detached — not just the top-level node the caller drained. + /// + /// `ParallelGroup` children are intentionally not descended into: they are + /// added via `ParallelGroup.add(_:)` rather than `engine.add(_:)`, so they + /// were never individually bound in the first place (only the enclosing + /// `ParallelGroup` synth — which is not a `SynthesizerBase` either — was + /// ever passed to `engine.add`). Same opaque-`ParallelGroup` convention as + /// `Group.removeRecursive` / `Group._walkSubtreeForCountDecrement`. + /// + /// Called only from `stop()`'s teardown path, after `driver.stop()` has + /// returned — main thread, RT thread not running, safe to call `_unbind`. + private func _unbindNodeAndDescendants(_ node: PreparedNode) { + (node.synth as? SynthesizerBase)?._unbind(from: self) + guard let nested: Group = node.groupRef else { return } + var child: PreparedNode? = nested.head + while let n: PreparedNode = child { + _unbindNodeAndDescendants(n) + child = n.next + } + } + /// Walk `buf` and release any `.remove` event's `Unmanaged.passRetained` /// ref, then clear the array keeping its reserved capacity. Used during /// `stop()` teardown to balance ARC on events that were staged on the RT @@ -1222,7 +1259,10 @@ public final class SynthesisEngine { /// Walk `rootGroup`'s linked list, preserve only the `PreparedNode` whose /// `synth === mainGroup`, and unlink everything else. Pre/post-main user /// nodes (installed via `.before(mainGroup)` / `.after(mainGroup)`) are - /// dropped; their refs release via ARC as the enclosing scope ends. + /// unbound (see `_unbindNodeAndDescendants(_:)`) and dropped; their refs + /// release via ARC as the enclosing scope ends. `mainGroup` itself is left + /// untouched — never unbound (it is not a `SynthesizerBase` to begin with) + /// and never unlinked. private func _drainRootKeepingMainGroup() { var mainNode: PreparedNode? = nil var node: PreparedNode? = rootGroup.head @@ -1232,6 +1272,8 @@ public final class SynthesisEngine { n.prev = nil if n.synth === mainGroup { mainNode = n + } else { + _unbindNodeAndDescendants(n) } node = next } @@ -1516,7 +1558,7 @@ public final class SynthesisEngine { /// Process one block of audio. /// Called by the Core Audio render callback and directly by tests / NRTDriver. public func processBlock(inputSamples: [[Float]]) { - let blockStartTick: UInt64 = mach_absolute_time() + let blockStartTick: UInt64 = LyrebirdMonotonicClock.ticks() // 1. Zero all audio buses (control buses are never zeroed — they persist) for i: Int in 0...size) let queryStatus: OSStatus = ExtAudioFileGetProperty(rawRef, @@ -206,11 +229,10 @@ public enum DiskIn { ExtAudioFileDispose(rawRef) throw DiskInError.cannotOpenFile(queryStatus) } - let fileChannels: Int = min(Int(fileFmt.mChannelsPerFrame), channelCount) + fileChannels = min(Int(fileFmt.mChannelsPerFrame), channelCount) _fileChannelCount = fileChannels + _readRateScale = 1.0 - // Set client format: interleaved Float32 at engine SR. - // ExtAudioFile performs SR conversion transparently. let float32ByteSize: UInt32 = UInt32(MemoryLayout.size) let float32BitsPerChannel: UInt32 = 32 var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription( @@ -234,6 +256,17 @@ public enum DiskIn { ExtAudioFileDispose(rawRef) throw DiskInError.cannotSetFormat(setFmtStatus) } + #else + // Throws `WavFileError` on a bad or non-WAV file — matching the + // portable `NRTDriver` input path, which lets that error propagate + // rather than wrapping it. + _wavURL = url + let reader: WavFileReader = try WavFileReader(url: url) + fileChannels = min(reader.channels, channelCount) + _fileChannelCount = fileChannels + _readRateScale = reader.sampleRate > 0 ? reader.sampleRate / sampleRate : 1.0 + _wavReader = reader + #endif // Pre-allocate double buffer: 2 halves × channelCount × bufferFrames. // Channels beyond _fileChannelCount are zero-initialised and never written. @@ -281,7 +314,11 @@ public enum DiskIn { // thread — calling sync on the same serial queue deadlocks. BG has // finished its current iteration before deinit can start, so _fileRef // is not being accessed concurrently; direct disposal is safe. + #if canImport(AudioToolbox) if let ref: ExtAudioFileRef = _fileRef { ExtAudioFileDispose(ref) } + #else + _wavReader?.close() + #endif } // MARK: - Background internals @@ -326,14 +363,17 @@ public enum DiskIn { } guard !_atEOF || loop else { return 0 } - guard let fileRef: ExtAudioFileRef = _fileRef else { return 0 } var totalRead: Int = 0 let maxAttempts: Int = 16 // guard against zero-length files in loop mode for _ in 0.. 0 ? block.count / _fileChannelCount : 0 + for f: Int in 0.. WavEncoding { + switch format { + case .wavFloat32: return .float32 + case .wavInt16: return .int16 + case .wavInt24: return .int24 + // RF64 needs 64-bit `ds64` sizing the portable classic-RIFF writer does + // not emit; mapping it to a 32-bit WAV would silently truncate/trap past + // 4 GB. Unsupported off Apple until a portable RF64 writer exists. + case .rf64Float32, .rf64Int24, .cafFloat32, .aiffFloat32, .aacHigh, .aacMedium, .alac: + throw DiskOutError.unsupportedFormatOnPlatform(format) + } + } + #endif + /// Audio-rate streaming recorder to a soundfile. /// /// The generator passes the input signal through as its output, so it can be @@ -122,11 +142,17 @@ public enum DiskOut { // MARK: - BG file state (BG-only after init) + #if canImport(AudioToolbox) private var _fileRef: ExtAudioFileRef? /// RF64 backend for the `.rf64Float32` / `.rf64Int24` formats (`ExtAudioFile` /// can't write RF64). Exactly one of `_fileRef` / `_rf64Writer` is non-nil. private var _rf64Writer: RF64Writer? + #else + /// Portable WAV backend (off Apple). The WAV encodings stream; the + /// Apple-only containers throw at init. + private var _wavWriter: WavFileWriter? + #endif /// Output container/encoding — fixed at init. Read by the BG drain's /// large-file guard (`riffOverflow`); CAF/RF64 are exempt. @@ -215,6 +241,7 @@ public enum DiskOut { // everything else through ExtAudioFile. Client samples are always native // Float32 interleaved — ExtAudioFile handles Float32 → int16/int24, and // RF64Writer handles Float32 → RF64 float/int24, transparently. + #if canImport(AudioToolbox) if format.usesRF64Writer { do { _rf64Writer = try RF64Writer( @@ -266,6 +293,19 @@ public enum DiskOut { throw DiskOutError.cannotSetFormat(setFmtStatus) } } + #else + // Portable WAV backend. Off Apple, only the WAV encodings stream. + do { + let encoding: WavEncoding = try DiskOut.wavEncoding(for: format) + _wavWriter = try WavFileWriter( + url: url, channels: channelCount, sampleRate: sampleRate, encoding: encoding + ) + } catch { + // Pre-`super.init()` throw — `deinit` won't run; free the ring. + _ringStorage.deallocate() + throw error + } + #endif super.init(channels: channelCount) _startBGLoop() @@ -283,6 +323,7 @@ public enum DiskOut { guard !_stopped.load(ordering: .acquiring) else { return } _stopped.store(true, ordering: .releasing) _backgroundQueue.sync { } // wait for BG poll loop to exit and final drain + #if canImport(AudioToolbox) if let ref: ExtAudioFileRef = _fileRef { ExtAudioFileDispose(ref) _fileRef = nil @@ -293,6 +334,12 @@ public enum DiskOut { do { try writer.close() } catch { _writeError.store(true, ordering: .releasing) } _rf64Writer = nil } + #else + if let writer: WavFileWriter = _wavWriter { + do { try writer.finalize() } catch { _writeError.store(true, ordering: .releasing) } + _wavWriter = nil + } + #endif } deinit { @@ -303,11 +350,15 @@ public enum DiskOut { // thread — calling sync on the same serial queue deadlocks. BG has // finished its current iteration before deinit can start, so _fileRef // is not being accessed concurrently; direct disposal is safe. + #if canImport(AudioToolbox) if let ref: ExtAudioFileRef = _fileRef { ExtAudioFileDispose(ref) } // RF64Writer.close() patches the ds64 sizes; its own deinit is a // best-effort fallback, but call it here so a forgotten close() still // finalises the file. Safe for the same no-concurrent-BG reason above. try? _rf64Writer?.close() + #else + try? _wavWriter?.finalize() + #endif } // Free the raw ring storage. Safe here for the same reason the file // disposal is: the BG loop upgrades its `[weak self]` to a strong @@ -342,7 +393,11 @@ public enum DiskOut { let rHead: Int = _framesRead.load(ordering: .relaxed) let wHead: Int = _framesWritten.load(ordering: .acquiring) let available: Int = wHead - rHead + #if canImport(AudioToolbox) guard available > 0, (_fileRef != nil || _rf64Writer != nil) else { return } + #else + guard available > 0, _wavWriter != nil else { return } + #endif // Once the file has hit the container cap, discard remaining frames // without writing (keeps the ring draining so the RT side never stalls). @@ -374,6 +429,7 @@ public enum DiskOut { _interleavedWriteBuf[f * channelCount + ch] = _ringStorage[ch * _ringSize + pos] } } + #if canImport(AudioToolbox) if let rf64Writer: RF64Writer = _rf64Writer { _interleavedWriteBuf.withUnsafeBufferPointer { ptr in do { try rf64Writer.writeFloat32Interleaved(ptr, frames: toWrite) } @@ -398,6 +454,12 @@ public enum DiskOut { } } } + #else + if let wavWriter: WavFileWriter = _wavWriter { + do { try wavWriter.write(interleaved: _interleavedWriteBuf, frames: toWrite) } + catch { _writeError.store(true, ordering: .releasing) } + } + #endif _cumulativeFramesWritten += toWrite totalDrained += toWrite } diff --git a/Sources/Lyrebird/Generators/BufferIO/DiskOutError.swift b/Sources/Lyrebird/Generators/BufferIO/DiskOutError.swift index 34e0b83..faab326 100644 --- a/Sources/Lyrebird/Generators/BufferIO/DiskOutError.swift +++ b/Sources/Lyrebird/Generators/BufferIO/DiskOutError.swift @@ -4,7 +4,11 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import AudioToolbox +// `OSStatus` comes from Darwin on Apple; off Apple it is the shim in +// PlatformCompat.swift (same module, no import needed). +#if canImport(Darwin) +import Darwin +#endif // MARK: - Errors @@ -16,4 +20,8 @@ public enum DiskOutError: Error { /// for `DiskOut`, and render offline (`LyrebirdBuffer.write` / `NRTDriver`) for /// AAC / ALAC output. case compressedFormatNotSupported(AudioFileFormat) + /// The requested container is not available on this (non-Apple) platform. + /// Only the WAV encodings stream off Apple; use `.wavFloat32` / `.wavInt16` / + /// `.wavInt24`. + case unsupportedFormatOnPlatform(AudioFileFormat) } diff --git a/Sources/Lyrebird/Generators/BusIO/MixIn.swift b/Sources/Lyrebird/Generators/BusIO/MixIn.swift index 96c7c0f..b9e288d 100644 --- a/Sources/Lyrebird/Generators/BusIO/MixIn.swift +++ b/Sources/Lyrebird/Generators/BusIO/MixIn.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Multi-source audio-bus summing generator. /// diff --git a/Sources/Lyrebird/Generators/Dynamics/AmplitudeFollower.swift b/Sources/Lyrebird/Generators/Dynamics/AmplitudeFollower.swift index fb3a242..6508712 100644 --- a/Sources/Lyrebird/Generators/Dynamics/AmplitudeFollower.swift +++ b/Sources/Lyrebird/Generators/Dynamics/AmplitudeFollower.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP /// Envelope follower with asymmetric attack and release smoothing. /// @@ -170,7 +170,6 @@ public enum AmplitudeFollower { _setupSubBlockBuffer() } - // Bypass sub-block loop: smoothing state must update once per audio block. // Sub-blocking would apply the coeff N times per block, making time constants N× shorter. public func calculatedSamples( diff --git a/Sources/Lyrebird/Generators/Dynamics/Balance.swift b/Sources/Lyrebird/Generators/Dynamics/Balance.swift index eb4878f..c324a84 100644 --- a/Sources/Lyrebird/Generators/Dynamics/Balance.swift +++ b/Sources/Lyrebird/Generators/Dynamics/Balance.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP /// Smallest positive `hp` cutoff allowed. Below this the one-pole integrator coefficient /// would round to `1.0` (comp → 0), freezing the mean-square estimate. Clamps `hp` here. diff --git a/Sources/Lyrebird/Generators/Dynamics/Compressor.swift b/Sources/Lyrebird/Generators/Dynamics/Compressor.swift index 2fd6d02..bfd5dea 100644 --- a/Sources/Lyrebird/Generators/Dynamics/Compressor.swift +++ b/Sources/Lyrebird/Generators/Dynamics/Compressor.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP /// Feed-forward dynamic range compressor with optional soft knee. /// @@ -235,7 +235,6 @@ public enum Compressor { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 1.0 // matches _prevGain initial value - /// - Parameters: /// - input: Signal to compress. /// - threshold: Compression threshold in dB (e.g. `−6.0`). Gain reduction is applied above this level. Typical range −60 to 0. Defaults to `−6.0`. @@ -259,7 +258,6 @@ public enum Compressor { _setupSubBlockBuffer() } - // Bypass sub-block loop: _prevGain must advance once per audio block. // Sub-blocking would apply the gain smoother N times per block, shrinking time constants by N×. public func calculatedSamples( diff --git a/Sources/Lyrebird/Generators/Dynamics/DynamicsHelpers.swift b/Sources/Lyrebird/Generators/Dynamics/DynamicsHelpers.swift index a1f2eca..694258f 100644 --- a/Sources/Lyrebird/Generators/Dynamics/DynamicsHelpers.swift +++ b/Sources/Lyrebird/Generators/Dynamics/DynamicsHelpers.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP // MARK: - Asymmetric attack/release smoother diff --git a/Sources/Lyrebird/Generators/Dynamics/Expander.swift b/Sources/Lyrebird/Generators/Dynamics/Expander.swift index 0b93542..db25350 100644 --- a/Sources/Lyrebird/Generators/Dynamics/Expander.swift +++ b/Sources/Lyrebird/Generators/Dynamics/Expander.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP /// Downward expander and noise gate with optional soft knee. /// @@ -230,7 +230,6 @@ public enum Expander { public var previousOutputValue: Double = 0.0 private var _rampTarget: Double = 1.0 // matches _prevGain initial value - /// - Parameters: /// - input: Signal to expand. /// - threshold: Expansion threshold in dB. Gain is reduced for signal levels below this threshold. Defaults to `−40.0`. @@ -251,7 +250,6 @@ public enum Expander { _setupSubBlockBuffer() } - // Bypass sub-block loop: _prevGain must advance once per audio block. // Sub-blocking would apply the gain smoother N times per block, shrinking time constants by N×. public func calculatedSamples( diff --git a/Sources/Lyrebird/Generators/Dynamics/FreqTracker.swift b/Sources/Lyrebird/Generators/Dynamics/FreqTracker.swift index 1e10c15..b4a16a5 100644 --- a/Sources/Lyrebird/Generators/Dynamics/FreqTracker.swift +++ b/Sources/Lyrebird/Generators/Dynamics/FreqTracker.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP /// Monophonic pitch tracker using the YIN algorithm (de Cheveigné & Kawahara 2002). /// @@ -97,7 +97,6 @@ public final class FreqTracker: GeneratorBase, AudioGenerator { // MARK: - Fan-out cache - /// - Parameters: /// - input: Signal to track. /// - fftSize: Analysis window in **decimated** samples. Power of 2 in [64, 512]. diff --git a/Sources/Lyrebird/Generators/Dynamics/LookAheadLimiter.swift b/Sources/Lyrebird/Generators/Dynamics/LookAheadLimiter.swift index c387116..0cd27ea 100644 --- a/Sources/Lyrebird/Generators/Dynamics/LookAheadLimiter.swift +++ b/Sources/Lyrebird/Generators/Dynamics/LookAheadLimiter.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP /// True look-ahead limiter. Delays the output by `lookAheadTime` seconds and uses /// the look-ahead window to compute gain reduction before peaks arrive, guaranteeing diff --git a/Sources/Lyrebird/Generators/Dynamics/Normalizer.swift b/Sources/Lyrebird/Generators/Dynamics/Normalizer.swift index 976411b..f5a70b0 100644 --- a/Sources/Lyrebird/Generators/Dynamics/Normalizer.swift +++ b/Sources/Lyrebird/Generators/Dynamics/Normalizer.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP /// Look-ahead peak normalizer. Delays the output by `dur` seconds and uses the look-ahead /// window to scale the signal so its peak tracks `level` — scaling **up** quiet passages and diff --git a/Sources/Lyrebird/Generators/Filters/ButterworthBandPass.swift b/Sources/Lyrebird/Generators/Filters/ButterworthBandPass.swift index f1a7b96..c28cdfe 100644 --- a/Sources/Lyrebird/Generators/Filters/ButterworthBandPass.swift +++ b/Sources/Lyrebird/Generators/Filters/ButterworthBandPass.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation /// Cascaded Butterworth bandpass filter, orders 1–8 per section (2 × order total poles). diff --git a/Sources/Lyrebird/Generators/Filters/ButterworthBandReject.swift b/Sources/Lyrebird/Generators/Filters/ButterworthBandReject.swift index 97b752e..c753c34 100644 --- a/Sources/Lyrebird/Generators/Filters/ButterworthBandReject.swift +++ b/Sources/Lyrebird/Generators/Filters/ButterworthBandReject.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation /// Cascaded Butterworth band-reject (notch) filter, orders 1–8 per section (2 × order total poles). diff --git a/Sources/Lyrebird/Generators/Filters/ButterworthSectionEngine.swift b/Sources/Lyrebird/Generators/Filters/ButterworthSectionEngine.swift index b549a23..c066fae 100644 --- a/Sources/Lyrebird/Generators/Filters/ButterworthSectionEngine.swift +++ b/Sources/Lyrebird/Generators/Filters/ButterworthSectionEngine.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation /// Internal cascade engine for a single Butterworth LP or HP section. diff --git a/Sources/Lyrebird/Generators/Filters/Decay.swift b/Sources/Lyrebird/Generators/Filters/Decay.swift index 345072e..d6c2733 100644 --- a/Sources/Lyrebird/Generators/Filters/Decay.swift +++ b/Sources/Lyrebird/Generators/Filters/Decay.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Leaky integrator with 60 dB decay time. /// diff --git a/Sources/Lyrebird/Generators/Filters/Decay2.swift b/Sources/Lyrebird/Generators/Filters/Decay2.swift index 0bd364e..c2f82e0 100644 --- a/Sources/Lyrebird/Generators/Filters/Decay2.swift +++ b/Sources/Lyrebird/Generators/Filters/Decay2.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Two-integrator decay that rounds off the sharp attack of ``Decay``. /// diff --git a/Sources/Lyrebird/Generators/Filters/Formlet.swift b/Sources/Lyrebird/Generators/Filters/Formlet.swift index a37a71d..1beb719 100644 --- a/Sources/Lyrebird/Generators/Filters/Formlet.swift +++ b/Sources/Lyrebird/Generators/Filters/Formlet.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// FOF-like resonant filter parameterised by attack and decay times. /// diff --git a/Sources/Lyrebird/Generators/Filters/Klank.swift b/Sources/Lyrebird/Generators/Filters/Klank.swift index 0bb4918..82a7426 100644 --- a/Sources/Lyrebird/Generators/Filters/Klank.swift +++ b/Sources/Lyrebird/Generators/Filters/Klank.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Number of channels (= per-resonator parameters) required by ``Klank``: `freq`, `amp`, /// `decay`. Each ``LyrebirdBuffer`` frame supplies one resonator's parameters. The channel diff --git a/Sources/Lyrebird/Generators/Filters/Lag.swift b/Sources/Lyrebird/Generators/Filters/Lag.swift index fd9a0c9..aa54db8 100644 --- a/Sources/Lyrebird/Generators/Filters/Lag.swift +++ b/Sources/Lyrebird/Generators/Filters/Lag.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// One-pole exponential smoother with 60 dB lag time. /// diff --git a/Sources/Lyrebird/Generators/Filters/Lag2.swift b/Sources/Lyrebird/Generators/Filters/Lag2.swift index 4ad9e76..f72c823 100644 --- a/Sources/Lyrebird/Generators/Filters/Lag2.swift +++ b/Sources/Lyrebird/Generators/Filters/Lag2.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Two-cascaded one-pole smoother — smoother transition curve than a single ``Lag``. /// diff --git a/Sources/Lyrebird/Generators/Filters/Lag2UpDown.swift b/Sources/Lyrebird/Generators/Filters/Lag2UpDown.swift index d4368bf..8e14c83 100644 --- a/Sources/Lyrebird/Generators/Filters/Lag2UpDown.swift +++ b/Sources/Lyrebird/Generators/Filters/Lag2UpDown.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Two-cascaded asymmetric one-pole smoother with separate 60 dB lag times for rising and falling. /// diff --git a/Sources/Lyrebird/Generators/Filters/LagHelpers.swift b/Sources/Lyrebird/Generators/Filters/LagHelpers.swift index 0cfca6a..2831b8e 100644 --- a/Sources/Lyrebird/Generators/Filters/LagHelpers.swift +++ b/Sources/Lyrebird/Generators/Filters/LagHelpers.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP // Shared 60 dB coefficient helper for Lag, Decay, and LeakDC family generators. diff --git a/Sources/Lyrebird/Generators/Filters/LagUpDown.swift b/Sources/Lyrebird/Generators/Filters/LagUpDown.swift index a413cf5..3c58d1d 100644 --- a/Sources/Lyrebird/Generators/Filters/LagUpDown.swift +++ b/Sources/Lyrebird/Generators/Filters/LagUpDown.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Asymmetric one-pole smoother with separate 60 dB lag times for rising and falling signals. /// diff --git a/Sources/Lyrebird/Generators/Filters/LeakDC.swift b/Sources/Lyrebird/Generators/Filters/LeakDC.swift index a3d0d5a..8946726 100644 --- a/Sources/Lyrebird/Generators/Filters/LeakDC.swift +++ b/Sources/Lyrebird/Generators/Filters/LeakDC.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Default DC-blocking coefficient for audio-rate `LeakDC`. public let leakDCDefaultAudioCoef: Double = 0.995 diff --git a/Sources/Lyrebird/Generators/Filters/MoogLadder.swift b/Sources/Lyrebird/Generators/Filters/MoogLadder.swift index 8575a14..05594e5 100644 --- a/Sources/Lyrebird/Generators/Filters/MoogLadder.swift +++ b/Sources/Lyrebird/Generators/Filters/MoogLadder.swift @@ -4,8 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate -import Darwin +import LyrebirdDSP /// Resonance feedback gain factor: `k = 4 · resonance`. `resonance = 1.0` /// corresponds to `k = 4.0`, the classic ladder self-oscillation threshold @@ -179,7 +178,7 @@ public enum MoogLadder { let scalarK: Double if !cutoffIsGenerator && !resonanceIsGenerator { let fc: Double = max(moogLadderMinCutoffHz, scalarCutoff) - scalarG = min(moogLadderMaxCutoffCoeff, 1.0 - Darwin.exp(-twoPiOverSrOs * fc)) + scalarG = min(moogLadderMaxCutoffCoeff, 1.0 - exp(-twoPiOverSrOs * fc)) let r: Double = min(moogLadderMaxResonance, max(0.0, scalarResonance)) scalarK = moogLadderResonanceGain * r } else { @@ -206,7 +205,7 @@ public enum MoogLadder { rawRes = scalarResonance } let fc: Double = max(moogLadderMinCutoffHz, rawCutoff) - g = min(moogLadderMaxCutoffCoeff, 1.0 - Darwin.exp(-twoPiOverSrOs * fc)) + g = min(moogLadderMaxCutoffCoeff, 1.0 - exp(-twoPiOverSrOs * fc)) let r: Double = min(moogLadderMaxResonance, max(0.0, rawRes)) k = moogLadderResonanceGain * r } else { @@ -237,15 +236,15 @@ public enum MoogLadder { private func ladderStep(input x: Double, g: Double, k: Double) -> Double { // half-sample feedback compensation: xfb = x − k·(y4 − 0.5·x) let xfb: Double = x - k * (y4 - moogLadderHalfSampleComp * x) - let s: Double = Darwin.tanh(xfb) + let s: Double = tanh(xfb) - y1 = y1 + g * (s - Darwin.tanh(y1)) - let t1: Double = Darwin.tanh(y1) - y2 = y2 + g * (t1 - Darwin.tanh(y2)) - let t2: Double = Darwin.tanh(y2) - y3 = y3 + g * (t2 - Darwin.tanh(y3)) - let t3: Double = Darwin.tanh(y3) - y4 = y4 + g * (t3 - Darwin.tanh(y4)) + y1 = y1 + g * (s - tanh(y1)) + let t1: Double = tanh(y1) + y2 = y2 + g * (t1 - tanh(y2)) + let t2: Double = tanh(y2) + y3 = y3 + g * (t2 - tanh(y3)) + let t3: Double = tanh(y3) + y4 = y4 + g * (t3 - tanh(y4)) y1 = denormalsToZero(y1) y2 = denormalsToZero(y2) diff --git a/Sources/Lyrebird/Generators/Filters/MuTronIII.swift b/Sources/Lyrebird/Generators/Filters/MuTronIII.swift index a00d1f5..6de28da 100644 --- a/Sources/Lyrebird/Generators/Filters/MuTronIII.swift +++ b/Sources/Lyrebird/Generators/Filters/MuTronIII.swift @@ -4,8 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate -import Darwin +import LyrebirdDSP /// Mu-Tron III auto-wah / envelope-controlled filter. /// @@ -296,10 +295,10 @@ public enum MuTronIII { let sweep: Double = _directionUp ? env : (1.0 - env) // Exponential pitch sweep from freqLo to freqHi. - let cutoff: Double = safeFreqLo * Darwin.pow(safeFreqHi / safeFreqLo, sweep) + let cutoff: Double = safeFreqLo * pow(safeFreqHi / safeFreqLo, sweep) // Chamberlin SVF frequency coefficient. - let f: Double = min(fCoeffMax, 2.0 * Darwin.sin(piOverSr * cutoff)) + let f: Double = min(fCoeffMax, 2.0 * sin(piOverSr * cutoff)) // Chamberlin SVF recurrence. _svfLow = _svfLow + f * _svfBand @@ -383,7 +382,6 @@ public enum MuTronIII { _setupSubBlockBuffer() } - // Bypass sub-block loop: IIR state (envelope follower + SVF) must advance exactly // once per audio block, processing each input sample exactly once. public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { @@ -467,8 +465,8 @@ public enum MuTronIII { let env: Double = max(0.0, min(_prevAmp, 1.0)) let sweep: Double = _directionUp ? env : (1.0 - env) - let cutoff: Double = safeFreqLo * Darwin.pow(safeFreqHi / safeFreqLo, sweep) - let f: Double = min(fCoeffMax, 2.0 * Darwin.sin(piOverSr * cutoff)) + let cutoff: Double = safeFreqLo * pow(safeFreqHi / safeFreqLo, sweep) + let f: Double = min(fCoeffMax, 2.0 * sin(piOverSr * cutoff)) _svfLow = _svfLow + f * _svfBand let high: Double = x - _svfLow - q1 * _svfBand diff --git a/Sources/Lyrebird/Generators/Filters/ResonatorBank.swift b/Sources/Lyrebird/Generators/Filters/ResonatorBank.swift index 40cd175..998d3bb 100644 --- a/Sources/Lyrebird/Generators/Filters/ResonatorBank.swift +++ b/Sources/Lyrebird/Generators/Filters/ResonatorBank.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Number of channels (= per-resonator parameters) required by ``ResonatorBank``: `freq`, /// `decay`, `amp`. Each ``LyrebirdBuffer`` frame supplies one resonator's parameters. diff --git a/Sources/Lyrebird/Generators/Filters/SVFHelpers.swift b/Sources/Lyrebird/Generators/Filters/SVFHelpers.swift index d94f708..af9b235 100644 --- a/Sources/Lyrebird/Generators/Filters/SVFHelpers.swift +++ b/Sources/Lyrebird/Generators/Filters/SVFHelpers.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP /// Minimum damping denominator — prevents the `1/q` divide-by-zero in the SVF. let svfMinQDamping: Double = 0.0001 @@ -63,7 +63,7 @@ func runSVFBlock( // generator — matching the original per-sample formula for that mixed case. let scalarFCoeff: Double = freqIsGenerator ? 0.0 - : min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * scalarFreq))) + : min(fCoeffMax, max(0.0, 2.0 * sin(piOverSr * scalarFreq))) let scalarQ1: Double = qIsGenerator ? 0.0 : 1.0 / max(minQDamping, scalarQ) // Block-boundary cutoff-coefficient ramp for the generator-driven case. @@ -74,8 +74,8 @@ func runSVFBlock( let lastRaw: Double = fs[min(fs.count - 1, count - 1)] // `max(0.0, ...)` matches the scalar path: a freq above the sample rate makes // `sin(π·freq/sr)` negative, which would destabilise the Chamberlin recurrence. - let cFirst: Double = firstRaw > 0.0 ? min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * firstRaw))) : 0.0 - let cLast: Double = lastRaw > 0.0 ? min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * lastRaw))) : 0.0 + let cFirst: Double = firstRaw > 0.0 ? min(fCoeffMax, max(0.0, 2.0 * sin(piOverSr * firstRaw))) : 0.0 + let cLast: Double = lastRaw > 0.0 ? min(fCoeffMax, max(0.0, 2.0 * sin(piOverSr * lastRaw))) : 0.0 fFirst = cFirst fStep = count > 1 ? (cLast - cFirst) / Double(count - 1) : 0.0 } diff --git a/Sources/Lyrebird/Generators/Filters/Slew.swift b/Sources/Lyrebird/Generators/Filters/Slew.swift index 23a1f0a..3a55653 100644 --- a/Sources/Lyrebird/Generators/Filters/Slew.swift +++ b/Sources/Lyrebird/Generators/Filters/Slew.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Linear slew-rate limiter. Equivalent to SuperCollider `Slew`. /// diff --git a/Sources/Lyrebird/Generators/Filters/ToneStack.swift b/Sources/Lyrebird/Generators/Filters/ToneStack.swift index 9703384..3a65146 100644 --- a/Sources/Lyrebird/Generators/Filters/ToneStack.swift +++ b/Sources/Lyrebird/Generators/Filters/ToneStack.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP /// Passive guitar-amplifier tone stack (bass / mid / treble) — the interactive Fender / /// Marshall / Vox EQ network, not three independent bands. diff --git a/Sources/Lyrebird/Generators/Granular/BufferGrain.swift b/Sources/Lyrebird/Generators/Granular/BufferGrain.swift index 66e360b..c0ae211 100644 --- a/Sources/Lyrebird/Generators/Granular/BufferGrain.swift +++ b/Sources/Lyrebird/Generators/Granular/BufferGrain.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation /// Maps pan position in [−1, 1] to angle in [0, π/2] for equal-power panning. diff --git a/Sources/Lyrebird/Generators/Granular/FMGrain.swift b/Sources/Lyrebird/Generators/Granular/FMGrain.swift index 564fe62..b0a4496 100644 --- a/Sources/Lyrebird/Generators/Granular/FMGrain.swift +++ b/Sources/Lyrebird/Generators/Granular/FMGrain.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation /// Pre-computed constant: tableSize / (2π), converts FM modulator [-1,1] output to diff --git a/Sources/Lyrebird/Generators/Granular/FormantGrain.swift b/Sources/Lyrebird/Generators/Granular/FormantGrain.swift index 83dd3e7..438ec05 100644 --- a/Sources/Lyrebird/Generators/Granular/FormantGrain.swift +++ b/Sources/Lyrebird/Generators/Granular/FormantGrain.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation // MARK: - File-scope constants diff --git a/Sources/Lyrebird/Generators/Granular/InputGrain.swift b/Sources/Lyrebird/Generators/Granular/InputGrain.swift index 795db76..1389593 100644 --- a/Sources/Lyrebird/Generators/Granular/InputGrain.swift +++ b/Sources/Lyrebird/Generators/Granular/InputGrain.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation /// Granular synthesizer that records a live audio input into a circular capture buffer diff --git a/Sources/Lyrebird/Generators/Granular/SineGrain.swift b/Sources/Lyrebird/Generators/Granular/SineGrain.swift index 86b2214..6713e04 100644 --- a/Sources/Lyrebird/Generators/Granular/SineGrain.swift +++ b/Sources/Lyrebird/Generators/Granular/SineGrain.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation /// Granular synthesizer that generates a windowed sine tone inside each grain. diff --git a/Sources/Lyrebird/Generators/Granular/TimeStretch.swift b/Sources/Lyrebird/Generators/Granular/TimeStretch.swift index caebd8c..1643855 100644 --- a/Sources/Lyrebird/Generators/Granular/TimeStretch.swift +++ b/Sources/Lyrebird/Generators/Granular/TimeStretch.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP public enum TimeStretch { diff --git a/Sources/Lyrebird/Generators/Granular/TuneablePitchShift.swift b/Sources/Lyrebird/Generators/Granular/TuneablePitchShift.swift index 2413c93..debcab0 100644 --- a/Sources/Lyrebird/Generators/Granular/TuneablePitchShift.swift +++ b/Sources/Lyrebird/Generators/Granular/TuneablePitchShift.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Tunable grain-pool granular pitch shifter on live audio input. /// diff --git a/Sources/Lyrebird/Generators/Math/BinaryOpVectorHelpers.swift b/Sources/Lyrebird/Generators/Math/BinaryOpVectorHelpers.swift index 0b66c13..a3ecfbe 100644 --- a/Sources/Lyrebird/Generators/Math/BinaryOpVectorHelpers.swift +++ b/Sources/Lyrebird/Generators/Math/BinaryOpVectorHelpers.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// The four arithmetic operators `BinaryOpGenerator` can dispatch to vDSP. A /// generator built from an arbitrary closure (not one of these four) carries no diff --git a/Sources/Lyrebird/Generators/Math/LinLin.swift b/Sources/Lyrebird/Generators/Math/LinLin.swift index 68bd30d..b03604f 100644 --- a/Sources/Lyrebird/Generators/Math/LinLin.swift +++ b/Sources/Lyrebird/Generators/Math/LinLin.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP // MARK: - LinLin diff --git a/Sources/Lyrebird/Generators/Math/UnaryMathVectorHelpers.swift b/Sources/Lyrebird/Generators/Math/UnaryMathVectorHelpers.swift index 87b763f..a0df47b 100644 --- a/Sources/Lyrebird/Generators/Math/UnaryMathVectorHelpers.swift +++ b/Sources/Lyrebird/Generators/Math/UnaryMathVectorHelpers.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP // Vectorised inner loops for the unary math waveshapers (Sin / Cos / Exp / Log / // Sqrt / Floor / Ceil / Abs). Each `.Audio._computeSamples` resolves its input diff --git a/Sources/Lyrebird/Generators/Neural/LSTMAmp.swift b/Sources/Lyrebird/Generators/Neural/LSTMAmp.swift index 40be34a..abd7c1b 100644 --- a/Sources/Lyrebird/Generators/Neural/LSTMAmp.swift +++ b/Sources/Lyrebird/Generators/Neural/LSTMAmp.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP /// Real-time neural guitar-amp inference: a single-layer LSTM followed by a dense output, /// run one audio sample at a time. This is the GuitarML "Proteus" / NeuralPi topology — diff --git a/Sources/Lyrebird/Generators/Panning/AmbiDecoder1.swift b/Sources/Lyrebird/Generators/Panning/AmbiDecoder1.swift index 14ef87e..80408a0 100644 --- a/Sources/Lyrebird/Generators/Panning/AmbiDecoder1.swift +++ b/Sources/Lyrebird/Generators/Panning/AmbiDecoder1.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// 1st-order B-format Ambisonics decoder. /// diff --git a/Sources/Lyrebird/Generators/Panning/Pan2.swift b/Sources/Lyrebird/Generators/Panning/Pan2.swift index 82190ad..eb9e045 100644 --- a/Sources/Lyrebird/Generators/Panning/Pan2.swift +++ b/Sources/Lyrebird/Generators/Panning/Pan2.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Angle scale: maps pan position in [−1, 1] to angle in [0, π/2]. /// Pre-computed as a module-level constant; warmed up in SynthesisEngine.start() so the diff --git a/Sources/Lyrebird/Generators/Panning/Pan4.swift b/Sources/Lyrebird/Generators/Panning/Pan4.swift index 691766f..e9e8880 100644 --- a/Sources/Lyrebird/Generators/Panning/Pan4.swift +++ b/Sources/Lyrebird/Generators/Panning/Pan4.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Open base class for 4-speaker equal-power square panners. /// diff --git a/Sources/Lyrebird/Generators/Panning/PanAz.swift b/Sources/Lyrebird/Generators/Panning/PanAz.swift index 53aa48e..f80441b 100644 --- a/Sources/Lyrebird/Generators/Panning/PanAz.swift +++ b/Sources/Lyrebird/Generators/Panning/PanAz.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation /// Equal-power 4-speaker square panner driven by a polar **azimuth** angle. diff --git a/Sources/Lyrebird/Generators/Panning/PanAzDistance.swift b/Sources/Lyrebird/Generators/Panning/PanAzDistance.swift index 23001c2..b3e80a6 100644 --- a/Sources/Lyrebird/Generators/Panning/PanAzDistance.swift +++ b/Sources/Lyrebird/Generators/Panning/PanAzDistance.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation /// Equal-power 4-speaker square panner with polar (azimuth + distance) position diff --git a/Sources/Lyrebird/Generators/Panning/PanN.swift b/Sources/Lyrebird/Generators/Panning/PanN.swift index 6e07ef2..3a22662 100644 --- a/Sources/Lyrebird/Generators/Panning/PanN.swift +++ b/Sources/Lyrebird/Generators/Panning/PanN.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// π/2 — the angle scale for PanN equal-power interpolation between adjacent speakers. /// Pre-computed at module load time; warmed up in `SynthesisEngine.start()`. diff --git a/Sources/Lyrebird/Generators/Panning/PanXY.swift b/Sources/Lyrebird/Generators/Panning/PanXY.swift index 866f273..b12b3a9 100644 --- a/Sources/Lyrebird/Generators/Panning/PanXY.swift +++ b/Sources/Lyrebird/Generators/Panning/PanXY.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Equal-power 4-speaker square panner driven by cartesian `x` / `y` coordinates. /// diff --git a/Sources/Lyrebird/Generators/Panning/PanXYDistance.swift b/Sources/Lyrebird/Generators/Panning/PanXYDistance.swift index bcffe9f..faa564c 100644 --- a/Sources/Lyrebird/Generators/Panning/PanXYDistance.swift +++ b/Sources/Lyrebird/Generators/Panning/PanXYDistance.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation /// Equal-power 4-speaker square panner with source-distance modelling. diff --git a/Sources/Lyrebird/Generators/Reverb/ConvolutionReverb.swift b/Sources/Lyrebird/Generators/Reverb/ConvolutionReverb.swift index ac0f4ce..30b89d7 100644 --- a/Sources/Lyrebird/Generators/Reverb/ConvolutionReverb.swift +++ b/Sources/Lyrebird/Generators/Reverb/ConvolutionReverb.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP // MARK: - ConvolutionReverb constants diff --git a/Sources/Lyrebird/Generators/Routing/ChannelSelect.swift b/Sources/Lyrebird/Generators/Routing/ChannelSelect.swift index 85d8b11..9202ea7 100644 --- a/Sources/Lyrebird/Generators/Routing/ChannelSelect.swift +++ b/Sources/Lyrebird/Generators/Routing/ChannelSelect.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Single-channel extractor for multi-output generators. /// diff --git a/Sources/Lyrebird/Generators/Routing/CrossFade.swift b/Sources/Lyrebird/Generators/Routing/CrossFade.swift index 20154d2..3e8c4ad 100644 --- a/Sources/Lyrebird/Generators/Routing/CrossFade.swift +++ b/Sources/Lyrebird/Generators/Routing/CrossFade.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP /// Half-pi constant for CrossFade equal-power gain derivation. private let crossFadeHalfPi: Double = .pi / 2 diff --git a/Sources/Lyrebird/Generators/Routing/SumChannels.swift b/Sources/Lyrebird/Generators/Routing/SumChannels.swift index 3a7a671..36ea7e4 100644 --- a/Sources/Lyrebird/Generators/Routing/SumChannels.swift +++ b/Sources/Lyrebird/Generators/Routing/SumChannels.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Multi-channel-to-mono fold-down generator. /// diff --git a/Sources/Lyrebird/Generators/Spectral/AdditiveSynthesizer.swift b/Sources/Lyrebird/Generators/Spectral/AdditiveSynthesizer.swift index 01e3f21..b1add78 100644 --- a/Sources/Lyrebird/Generators/Spectral/AdditiveSynthesizer.swift +++ b/Sources/Lyrebird/Generators/Spectral/AdditiveSynthesizer.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Additive resynthesis from a `SpectralFrameBuffer`. /// diff --git a/Sources/Lyrebird/Generators/Spectral/OnsetDetector.swift b/Sources/Lyrebird/Generators/Spectral/OnsetDetector.swift index cb73b55..2e62ae5 100644 --- a/Sources/Lyrebird/Generators/Spectral/OnsetDetector.swift +++ b/Sources/Lyrebird/Generators/Spectral/OnsetDetector.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation import Synchronization diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralBinDelay.swift b/Sources/Lyrebird/Generators/Spectral/SpectralBinDelay.swift index 9906bdb..a0e93d2 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralBinDelay.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralBinDelay.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Per-bin spectral delay with per-bin feedback. /// diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralBlur.swift b/Sources/Lyrebird/Generators/Spectral/SpectralBlur.swift index 97b857c..85934a0 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralBlur.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralBlur.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Synchronization /// Magnitude moving-average ("box blur") across complex bins. Smears spectral diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralBrickwall.swift b/Sources/Lyrebird/Generators/Spectral/SpectralBrickwall.swift index cfe8a98..c02ac62 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralBrickwall.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralBrickwall.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Synchronization /// Hard brick-wall spectral filter. Zeroes magnitudes (and DC/Nyquist when diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralBufferRead.swift b/Sources/Lyrebird/Generators/Spectral/SpectralBufferRead.swift index 40010d6..1ef63a0 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralBufferRead.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralBufferRead.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Synchronization /// Random-access spectral buffer playback via a normalized position pointer. diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralChain.swift b/Sources/Lyrebird/Generators/Spectral/SpectralChain.swift index 3446bee..5ee5c4d 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralChain.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralChain.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Consolidated short-time Fourier transform pipeline. A single audio-rate /// Generator that owns the entire chain: input accumulation, windowed forward diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralComplexClosure.swift b/Sources/Lyrebird/Generators/Spectral/SpectralComplexClosure.swift index 4fd3eab..67801cf 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralComplexClosure.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralComplexClosure.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Context passed to a ``SpectralComplexClosureBody`` on each FFT hop. /// diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralConvolve.swift b/Sources/Lyrebird/Generators/Spectral/SpectralConvolve.swift index 100c96a..368510f 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralConvolve.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralConvolve.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Frequency-domain convolution: per-bin complex multiply between the live /// spectrum and a second `SpectralBuffer` (`other`). Equivalent to diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralDiffuse.swift b/Sources/Lyrebird/Generators/Spectral/SpectralDiffuse.swift index 1ade879..07aceef 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralDiffuse.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralDiffuse.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Synchronization /// Per-instance xorshift64 mixer constant for `SpectralDiffuse` PRNG seeding — diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralFormantShift.swift b/Sources/Lyrebird/Generators/Spectral/SpectralFormantShift.swift index 4e5aeae..1ea986b 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralFormantShift.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralFormantShift.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Synchronization /// Magnitude-envelope-preserving formant shifter. Estimates the smooth spectral diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralFreeze.swift b/Sources/Lyrebird/Generators/Spectral/SpectralFreeze.swift index 26dca08..4151e4a 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralFreeze.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralFreeze.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Synchronization /// Phase-vocoder spectral freeze. diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralGate.swift b/Sources/Lyrebird/Generators/Spectral/SpectralGate.swift index ef573da..c389a71 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralGate.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralGate.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Synchronization /// Per-bin spectral gate. Bins whose magnitude is below `threshold` are scaled diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralMagnitudeScale.swift b/Sources/Lyrebird/Generators/Spectral/SpectralMagnitudeScale.swift index 03ae786..b78148a 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralMagnitudeScale.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralMagnitudeScale.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Scales all bin magnitudes (including DC and Nyquist) by a constant factor. /// diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralPhaseShift.swift b/Sources/Lyrebird/Generators/Spectral/SpectralPhaseShift.swift index b599375..7f5b1dd 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralPhaseShift.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralPhaseShift.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Synchronization /// Half of π — used for the `.deg90` and `.deg270` cardinal phase shifts. diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralPitchShift.swift b/Sources/Lyrebird/Generators/Spectral/SpectralPitchShift.swift index a3eebb1..2a4079d 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralPitchShift.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralPitchShift.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Synchronization /// Phase-vocoder pitch shifter — register as a `.mono(_)` stage on diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralPlayBuffer.swift b/Sources/Lyrebird/Generators/Spectral/SpectralPlayBuffer.swift index df09693..37e2cb1 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralPlayBuffer.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralPlayBuffer.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Synchronization /// Phase-vocoder spectral buffer playback with time-stretching. diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralStereoDiffuse.swift b/Sources/Lyrebird/Generators/Spectral/SpectralStereoDiffuse.swift index 3b198fa..634270d 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralStereoDiffuse.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralStereoDiffuse.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Synchronization /// XOR mask applied to the user-supplied (or clock-derived) seed for diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralTilt.swift b/Sources/Lyrebird/Generators/Spectral/SpectralTilt.swift index 9029bcb..e2017ca 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralTilt.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralTilt.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Per-bin spectral tilt EQ: applies a constant dB/octave slope around a pivot /// frequency. Phase is untouched. diff --git a/Sources/Lyrebird/Generators/Waveshaping/TriodeStage.swift b/Sources/Lyrebird/Generators/Waveshaping/TriodeStage.swift index 5e33a75..a7bc5d3 100644 --- a/Sources/Lyrebird/Generators/Waveshaping/TriodeStage.swift +++ b/Sources/Lyrebird/Generators/Waveshaping/TriodeStage.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP /// A tube-style preamp gain stage: an asymmetric saturating nonlinearity driven by `drive` /// and offset by a grid `bias`, evaluated at 2×/4× oversampling, followed by an output diff --git a/Sources/Lyrebird/Lyrebird.docc/AIAssistants.md b/Sources/Lyrebird/Lyrebird.docc/AIAssistants.md index 3e1792a..198800e 100644 --- a/Sources/Lyrebird/Lyrebird.docc/AIAssistants.md +++ b/Sources/Lyrebird/Lyrebird.docc/AIAssistants.md @@ -86,7 +86,7 @@ Analysis only; does not implement. ### `lyrebird_swiftui_agent` -Works on the `LyrebirdUI` module — `@UIParam`/`UIParamNode`, `ParameterKnob`/`Slider`/`XY`/`Button`/`Label`, `LyrebirdStatusView`, `LyrebirdScopeView`, `LyrebirdEnvelopeView`, `LyrebirdWindow`, and platform-conditional `#if os(macOS)` code. +Works on the `LyrebirdUI` module — `ParameterKnob`/`Slider`/`XY`/`Button`/`Label`, `LyrebirdStatusView`, `LyrebirdScopeView`, `LyrebirdEnvelopeView`, `LyrebirdWindow`, and platform-conditional `#if os(macOS)` code. (The `@UIParam`/`UIParamNode` parameter model these controls bind to lives in core `Lyrebird`.) Knows the `@UIParam` vs. `@LiveParam` threading difference, `Canvas`-based visualization patterns, `@Observable` binding, and SwiftUI task-based polling for engine data. diff --git a/Sources/Lyrebird/Lyrebird.docc/BufferGuide.md b/Sources/Lyrebird/Lyrebird.docc/BufferGuide.md index 5145af9..91cce61 100644 --- a/Sources/Lyrebird/Lyrebird.docc/BufferGuide.md +++ b/Sources/Lyrebird/Lyrebird.docc/BufferGuide.md @@ -99,7 +99,11 @@ Chebyshev polynomials, window factories, waveshaper curves) see ### File I/O `LyrebirdBuffer.load(url:)` (mono) and `loadAllChannels(url:)` (multi-channel) -read AIFF / WAV / CAF files via ExtAudioFile and set `sampleRate` automatically. +read soundfiles and set `sampleRate` automatically. On Apple they read AIFF / +WAV / CAF (and more) via `ExtAudioFile`; off Apple (Linux/Windows) they read +**WAV only**, through the portable `WavFileReader` (see `docs/engine/portable-wav-codec.md`). `write(to:format:)` follows the +same split: any format on Apple, the WAV encodings off it (other containers +throw `LyrebirdBufferIOError.unsupportedFormatOnPlatform`). `fill(fromFile:)` overlays file contents into an existing buffer. See ``LyrebirdBuffer/load(url:channel:normalise:)`` for the full file-I/O surface. diff --git a/Sources/Lyrebird/Lyrebird.docc/ExternalIntegrations.md b/Sources/Lyrebird/Lyrebird.docc/ExternalIntegrations.md index 3b05db2..dcbe635 100644 --- a/Sources/Lyrebird/Lyrebird.docc/ExternalIntegrations.md +++ b/Sources/Lyrebird/Lyrebird.docc/ExternalIntegrations.md @@ -150,7 +150,7 @@ Multiple handlers can be registered; all fire for every incoming message. ## OSC -`OSCServer` listens on a UDP port and dispatches messages to handlers registered for matching address patterns. `OSCClient` sends to any host:port. +`OSCServer` listens on a UDP port and dispatches messages to handlers registered for matching address patterns. `OSCClient` sends to any host:port. The transport is `Network.framework` on Apple and a POSIX UDP socket off Apple, where `start()` throws `OSCServerError` (`.socketFailed` / `.bindFailed`, carrying `errno`; or `.threadDidNotExit` if a prior `stop()` was abandoned) instead of Apple's `NWError`. ### Basic server @@ -258,7 +258,7 @@ server.removeHandler(token) ```swift try server.start() // binds UDP port, starts accepting connections // ... -server.stop() // cancels listener, cleans up NWListener +server.stop() // closes the listening transport (NWListener on Apple, the POSIX socket off it) ``` ## Combining MIDI and OSC diff --git a/Sources/Lyrebird/Lyrebird.docc/NRTGuide.md b/Sources/Lyrebird/Lyrebird.docc/NRTGuide.md index e9688e6..ca73342 100644 --- a/Sources/Lyrebird/Lyrebird.docc/NRTGuide.md +++ b/Sources/Lyrebird/Lyrebird.docc/NRTGuide.md @@ -354,6 +354,17 @@ do { | Silent output / all-zeros file | Synthesizers added after `start()` | Move all `engine.add()` before `start()` | | File truncated short | `duration` too short | 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`. + + ## See Also - diff --git a/Sources/Lyrebird/Lyrebird.docc/ParameterInputs.md b/Sources/Lyrebird/Lyrebird.docc/ParameterInputs.md index f12036f..d783b04 100644 --- a/Sources/Lyrebird/Lyrebird.docc/ParameterInputs.md +++ b/Sources/Lyrebird/Lyrebird.docc/ParameterInputs.md @@ -24,7 +24,7 @@ Default rule: | Need | Use | Threading | Smoothing | |------|-----|-----------|-----------| | Double scalar mutated post-init from main thread | `@LiveParam` | atomic store | per-(sub-)block linear ramp | -| Double scalar with SwiftUI binding | `@UIParam` (`LyrebirdUI`) | atomic + `@Observable` | per-(sub-)block linear ramp | +| Double scalar with a UI binding | `@UIParam` (`Lyrebird`) | atomic + `@Observable` | per-(sub-)block linear ramp | | Audio-rate / control-rate signal | wire `Generator` directly | RT graph | per the source | | Compile-time constant | pass `Double` literal | n/a | none | | RT→main edge event | `SendTrigger` + `TriggerListener` | SPSC trigger queue | n/a | @@ -152,10 +152,13 @@ number of voices, buffer reference) pass it at `init`. If it belongs to *perform ## `@UIParam` -A strict superset of `@LiveParam` defined in `LyrebirdUI`: +A strict superset of `@LiveParam`, defined in core `Lyrebird`; the UI controls that bind +to it live in the cross-platform `LyrebirdUI` module (SwiftUI on Apple, SwiftOpenUI/GTK4 +on Linux): ```swift -import LyrebirdUI +import LyrebirdSynth // @UIParam +import LyrebirdUI // ParameterSlider (Apple) final class MySynth: SynthesizerBase { @UIParam var frequency: Double = 440.0 diff --git a/Sources/Lyrebird/MIDI/ALSAMIDI.swift b/Sources/Lyrebird/MIDI/ALSAMIDI.swift new file mode 100644 index 0000000..1376c05 --- /dev/null +++ b/Sources/Lyrebird/MIDI/ALSAMIDI.swift @@ -0,0 +1,499 @@ +// ALSAMIDI.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// Linux MIDI via the ALSA sequencer. Present only where CALSA (libasound) is a +// dependency and CoreMIDI is not — i.e. a native Linux build. The public API +// mirrors the CoreMIDI `MIDI` class in `MIDI.swift`; the two are mutually +// exclusive (`#if canImport(CoreMIDI)` there, the complement here), so exactly +// one definition of `MIDI` compiles per platform. +#if !canImport(CoreMIDI) && canImport(CALSA) +import CALSA +import Foundation +import Synchronization +#if canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#endif + +/// Language-side ALSA-sequencer MIDI integration for Lyrebird. +/// +/// Handlers fire on a background dispatch queue (never the RT audio thread), the +/// same contract as the CoreMIDI backend. Incoming events are read on a +/// dedicated poll thread, translated through ``ALSASeqMIDIEvent`` / +/// ``midiMessage(for:)`` — the shared, platform-neutral mapping — and dispatched. +/// +/// > Note: this backend has been verified to build and to fail cleanly with no +/// > sequencer available; receiving from a real controller has not yet been +/// > exercised on hardware. See LINUX_PLAN.md. +public final class MIDI: @unchecked Sendable { + + private let engine: SynthesisEngine + private let clientName: String + + // @unchecked Sendable invariant: `engine` / `clientName` are immutable. + // `seq`, `inputPort`, `outputPort`, `virtualOutputPort`, `isStarted`, and + // `pollThread` are mutated only under `stateLock`; `handlers` / `_sources` + // / `_destinations` only under `lock`; `_running` / `_abandonedThread` are + // atomic. No field is touched without one of those. + + // ALSA's own address sentinels for "deliver to my subscribers", used by + // `sendVirtual`. Spelled out because the C macros that name them + // (`SND_SEQ_ADDRESS_SUBSCRIBERS` / `_UNKNOWN`) are not imported into Swift. + private static let addressSubscribers: UInt8 = 254 + private static let addressUnknown: UInt8 = 253 + /// Poll wake-up cadence, so `stop()` is seen within roughly this long. + private static let pollTimeoutMilliseconds: Int32 = 200 + /// How long `stop()` waits for the poll thread to leave its loop. The loop + /// wakes every `pollTimeoutMilliseconds`, so this is only ever approached + /// under severe scheduler starvation. + private static let threadJoinTimeout: TimeInterval = 2.0 + + // stateLock serializes the seq handle, port ids, and isStarted. + private let stateLock: NSLock = NSLock() + private var isStarted: Bool = false + private var seq: OpaquePointer? + private var inputPort: Int32 = -1 + private var outputPort: Int32 = -1 + private var virtualOutputPort: Int32 = -1 + + // lock serializes handlers, _sources, and _destinations. + private let lock: NSLock = NSLock() + private var handlers: [(token: MIDIHandlerToken, onMessage: @Sendable (MIDIMessage, LyrebirdMessageContext) -> Void)] = [] + private let nextTokenID: Atomic = Atomic(0) + private var _sources: [MIDISource] = [] + private var _destinations: [MIDIDestination] = [] + + private let handlerQueue: DispatchQueue = DispatchQueue(label: "lyrebird.midi", qos: .userInteractive) + private let _running: Atomic = Atomic(false) + /// Set when a `stop()` gave up waiting for the poll thread. The thread is + /// still alive and still holds `seq`, so the handle is leaked rather than + /// closed under it, and no later `start()` may run — exactly the discipline + /// `ALSAAudioDriver` uses for its render thread. + private let _abandonedThread: Atomic = Atomic(false) + /// `pollThread` is written in `start()` and cleared in `stop()`, both under + /// `stateLock`. As with the CoreMIDI backend, the `isStarted` compare-and-set + /// in `start()` guards against concurrent `start()` calls; the lifecycle + /// (start → use → stop) is otherwise expected to be driven from one thread. + private var pollThread: Thread? + private let threadExited: DispatchSemaphore = DispatchSemaphore(value: 0) + + /// Enumerated MIDI sources at the time of last update. Thread-safe. + public var sources: [MIDISource] { lock.withLock { _sources } } + /// Enumerated MIDI destinations at the time of last update. Thread-safe. + public var destinations: [MIDIDestination] { lock.withLock { _destinations } } + + public init( + engine: SynthesisEngine, + clientName: String = "Lyrebird" + ) { + self.engine = engine + self.clientName = clientName + } + + deinit { stop() } + + // MARK: - Lifecycle + + /// Open the ALSA sequencer client, create I/O ports, connect to all current + /// readable sources, and start the input poll thread. + /// + /// - Throws: `MIDIError.alreadyStarted` if already running; the + /// `clientCreateFailed` / `portCreateFailed` cases (carrying the negative + /// ALSA return code) on setup failure. + public func start() throws { + guard !_abandonedThread.load(ordering: .acquiring) else { + // A previous poll thread never returned; its (leaked) handle is + // still being read. Opening a second client would leave two threads + // and two handles live. + throw MIDIError.threadDidNotExit + } + var shouldProceed: Bool = false + stateLock.withLock { if !isStarted { isStarted = true; shouldProceed = true } } + guard shouldProceed else { throw MIDIError.alreadyStarted } + + var handle: OpaquePointer? + var didSucceed: Bool = false + defer { + if !didSucceed { + if let h: OpaquePointer = handle { snd_seq_close(h) } + stateLock.withLock { isStarted = false; seq = nil; inputPort = -1; outputPort = -1 } + } + } + + let openRC: Int32 = snd_seq_open(&handle, "default", SND_SEQ_OPEN_DUPLEX, 0) + guard openRC >= 0, let seqHandle: OpaquePointer = handle else { + throw MIDIError.clientCreateFailed(OSStatus(openRC)) + } + _ = snd_seq_set_client_name(seqHandle, clientName) + + let inPort: Int32 = snd_seq_create_simple_port( + seqHandle, "LyrebirdIn", + UInt32(SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE), + UInt32(SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION) + ) + guard inPort >= 0 else { throw MIDIError.portCreateFailed(OSStatus(inPort)) } + + let outPort: Int32 = snd_seq_create_simple_port( + seqHandle, "LyrebirdOut", + UInt32(SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ), + UInt32(SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION) + ) + guard outPort >= 0 else { throw MIDIError.portCreateFailed(OSStatus(outPort)) } + + stateLock.withLock { + seq = seqHandle + inputPort = inPort + outputPort = outPort + } + didSucceed = true + + _refreshEndpoints() + _connectAllSources() + + // Publish the thread under `stateLock`, then raise `_running`, then + // launch. `thread.start()` is last, so the poll loop never observes + // half-published state. + let thread: Thread = Thread { [weak self] in self?._pollLoop() } + thread.name = "lyrebird.midi.poll" + stateLock.withLock { pollThread = thread } + _running.store(true, ordering: .releasing) + thread.start() + } + + /// Stop the poll thread and close the sequencer client. Idempotent. + public func stop() { + let wasStarted: Bool = stateLock.withLock { + let prev: Bool = isStarted + isStarted = false + return prev + } + guard wasStarted else { return } + + _running.store(false, ordering: .releasing) + // The poll loop wakes every `pollTimeoutMilliseconds` and exits when it + // sees the cleared flag, so the join succeeds well within the timeout. + // If it somehow does not, the seq handle is leaked rather than closed + // under a thread that may still call `snd_seq_event_input` on it — a + // leak is recoverable, a use-after-free is not (the same discipline the + // audio driver's abandoned-thread path uses). + let hadThread: Bool = stateLock.withLock { + let had: Bool = pollThread != nil + pollThread = nil + return had + } + let joined: Bool = hadThread + ? threadExited.wait(timeout: .now() + Self.threadJoinTimeout) == .success + : true + let handle: OpaquePointer? = stateLock.withLock { + let h: OpaquePointer? = seq + seq = nil + inputPort = -1 + outputPort = -1 + virtualOutputPort = -1 + return h + } + if joined { + if let h: OpaquePointer = handle { snd_seq_close(h) } + } else { + // Abandon: the thread is still out there reading the handle. + _abandonedThread.store(true, ordering: .releasing) + } + lock.withLock { _sources = []; _destinations = [] } + } + + // MARK: - Handlers (identical contract to the CoreMIDI backend) + + /// Register a handler that fires, on the `lyrebird.midi` background queue, + /// for every incoming MIDI message. + /// + /// - Parameters: + /// - name: Human-readable label for debugging (not used for matching). + /// - onMessage: Closure invoked for each incoming message. + /// - Returns: Token for later removal via ``removeHandler(_:)``. + @discardableResult + public func addHandler( + name: String, + onMessage: @Sendable @escaping (MIDIMessage, LyrebirdMessageContext) -> Void + ) -> MIDIHandlerToken { + let id: UInt64 = nextTokenID.add(1, ordering: .relaxed).newValue + let token: MIDIHandlerToken = MIDIHandlerToken(id: id) + lock.withLock { handlers.append((token, onMessage)) } + return token + } + + /// Remove the handler identified by `token`. Thread-safe. + public func removeHandler(_ token: MIDIHandlerToken) { + lock.withLock { handlers.removeAll { $0.token == token } } + } + + // MARK: - Virtual ports + + /// Create a virtual MIDI input (a writable sequencer port other clients can + /// send to). Incoming messages are dispatched to registered handlers. + /// + /// Each call adds a distinct named port; the ids are not tracked + /// individually because `stop()`'s `snd_seq_close` frees every port the + /// client owns. Call once per virtual input you want. + public func createVirtualInput(name: String) throws { + let handle: OpaquePointer? = stateLock.withLock { seq } + guard let seqHandle: OpaquePointer = handle else { throw MIDIError.notStarted } + let port: Int32 = snd_seq_create_simple_port( + seqHandle, name, + UInt32(SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE), + UInt32(SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION) + ) + guard port >= 0 else { throw MIDIError.virtualPortFailed(OSStatus(port)) } + } + + /// Create a virtual MIDI output (a readable sequencer port other clients can + /// subscribe to). Messages sent via ``sendVirtual(_:)`` reach its subscribers. + public func createVirtualOutput(name: String) throws { + let handle: OpaquePointer? = stateLock.withLock { seq } + guard let seqHandle: OpaquePointer = handle else { throw MIDIError.notStarted } + let port: Int32 = snd_seq_create_simple_port( + seqHandle, name, + UInt32(SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ), + UInt32(SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION) + ) + guard port >= 0 else { throw MIDIError.virtualPortFailed(OSStatus(port)) } + stateLock.withLock { virtualOutputPort = port } + } + + // MARK: - Send + + /// Send `message` to a specific destination endpoint. + /// + /// - Throws: `MIDIError.notStarted` if the client is not open, or + /// `MIDIError.sendFailed` (carrying the ALSA return code) on failure. + public func send(_ message: MIDIMessage, to destination: MIDIDestination) throws { + let (handle, srcPort): (OpaquePointer?, Int32) = stateLock.withLock { (seq, outputPort) } + guard let seqHandle: OpaquePointer = handle, srcPort >= 0 else { throw MIDIError.notStarted } + try _output(message, on: seqHandle, sourcePort: srcPort, + destClient: UInt8(truncatingIfNeeded: destination.client), + destPort: UInt8(truncatingIfNeeded: destination.port)) + } + + /// Send `message` to the subscribers of the virtual output port created by + /// ``createVirtualOutput(name:)``. + public func sendVirtual(_ message: MIDIMessage) throws { + let (handle, srcPort): (OpaquePointer?, Int32) = stateLock.withLock { (seq, virtualOutputPort) } + guard let seqHandle: OpaquePointer = handle, srcPort >= 0 else { throw MIDIError.notStarted } + try _output(message, on: seqHandle, sourcePort: srcPort, + destClient: Self.addressSubscribers, destPort: Self.addressUnknown) + } + + // MARK: - Private: output + + private func _output( + _ message: MIDIMessage, + on seqHandle: OpaquePointer, + sourcePort: Int32, + destClient: UInt8, + destPort: UInt8 + ) throws { + var ev: snd_seq_event_t = snd_seq_event_t() + ev.queue = UInt8(truncatingIfNeeded: SND_SEQ_QUEUE_DIRECT) + ev.source.port = UInt8(truncatingIfNeeded: sourcePort) + ev.dest.client = destClient + ev.dest.port = destPort + + // Sysex carries a variable-length payload the event points into, so the + // buffer must outlive the (synchronous) `output_direct` call. + if case .sysex(let bytes) = message { + ev.type = UInt8(truncatingIfNeeded: SND_SEQ_EVENT_SYSEX.rawValue) + // Mark the event variable-length, or `output_direct` treats it as a + // fixed event and never reads `data.ext` — the payload is dropped. + ev.flags |= UInt8(truncatingIfNeeded: SND_SEQ_EVENT_LENGTH_VARIABLE) + var mutable: [UInt8] = bytes + let rc: Int32 = mutable.withUnsafeMutableBytes { raw in + ev.data.ext.len = UInt32(raw.count) + ev.data.ext.ptr = raw.baseAddress + return snd_seq_event_output_direct(seqHandle, &ev) + } + guard rc >= 0 else { throw MIDIError.sendFailed(OSStatus(rc)) } + return + } + + guard Self.fillChannelEvent(message, into: &ev) else { return } + let rc: Int32 = snd_seq_event_output_direct(seqHandle, &ev) + guard rc >= 0 else { throw MIDIError.sendFailed(OSStatus(rc)) } + } + + /// Populates `ev`'s type and union for a channel-voice or realtime message. + /// Returns `false` for a message this backend does not emit (e.g. `.other`), + /// which the caller drops rather than sending a malformed event. + private static func fillChannelEvent(_ message: MIDIMessage, into ev: inout snd_seq_event_t) -> Bool { + switch message { + case .noteOn(let ch, let note, let vel): + ev.type = UInt8(truncatingIfNeeded: SND_SEQ_EVENT_NOTEON.rawValue) + ev.data.note.channel = ch; ev.data.note.note = note; ev.data.note.velocity = vel + case .noteOff(let ch, let note, let vel): + ev.type = UInt8(truncatingIfNeeded: SND_SEQ_EVENT_NOTEOFF.rawValue) + ev.data.note.channel = ch; ev.data.note.note = note; ev.data.note.velocity = vel + case .polyAftertouch(let ch, let note, let pressure): + ev.type = UInt8(truncatingIfNeeded: SND_SEQ_EVENT_KEYPRESS.rawValue) + ev.data.note.channel = ch; ev.data.note.note = note; ev.data.note.velocity = pressure + case .controlChange(let ch, let cc, let value): + ev.type = UInt8(truncatingIfNeeded: SND_SEQ_EVENT_CONTROLLER.rawValue) + ev.data.control.channel = ch; ev.data.control.param = UInt32(cc); ev.data.control.value = Int32(value) + case .programChange(let ch, let program): + ev.type = UInt8(truncatingIfNeeded: SND_SEQ_EVENT_PGMCHANGE.rawValue) + ev.data.control.channel = ch; ev.data.control.value = Int32(program) + case .aftertouch(let ch, let pressure): + ev.type = UInt8(truncatingIfNeeded: SND_SEQ_EVENT_CHANPRESS.rawValue) + ev.data.control.channel = ch; ev.data.control.value = Int32(pressure) + case .pitchBend(let ch, let value): + ev.type = UInt8(truncatingIfNeeded: SND_SEQ_EVENT_PITCHBEND.rawValue) + ev.data.control.channel = ch; ev.data.control.value = Int32(value) + case .clock: ev.type = UInt8(truncatingIfNeeded: SND_SEQ_EVENT_CLOCK.rawValue) + case .start: ev.type = UInt8(truncatingIfNeeded: SND_SEQ_EVENT_START.rawValue) + case .continue: ev.type = UInt8(truncatingIfNeeded: SND_SEQ_EVENT_CONTINUE.rawValue) + case .stop: ev.type = UInt8(truncatingIfNeeded: SND_SEQ_EVENT_STOP.rawValue) + case .activeSensing: ev.type = UInt8(truncatingIfNeeded: SND_SEQ_EVENT_SENSING.rawValue) + case .reset: ev.type = UInt8(truncatingIfNeeded: SND_SEQ_EVENT_RESET.rawValue) + case .sysex, .other: + return false + } + return true + } + + // MARK: - Private: input poll loop + + private func _pollLoop() { + defer { threadExited.signal() } + let handle: OpaquePointer? = stateLock.withLock { seq } + guard let seqHandle: OpaquePointer = handle else { return } + let ctx: LyrebirdMessageContext = LyrebirdMessageContext(engine: engine) + + let fdCount: Int32 = snd_seq_poll_descriptors_count(seqHandle, Int16(POLLIN)) + guard fdCount > 0 else { return } + var fds: [pollfd] = [pollfd](repeating: pollfd(), count: Int(fdCount)) + _ = fds.withUnsafeMutableBufferPointer { buf in + snd_seq_poll_descriptors(seqHandle, buf.baseAddress, UInt32(fdCount), Int16(POLLIN)) + } + + while _running.load(ordering: .acquiring) { + let ready: Int32 = fds.withUnsafeMutableBufferPointer { buf in + poll(buf.baseAddress, UInt(fdCount), Self.pollTimeoutMilliseconds) + } + guard ready > 0 else { continue } // 0 = timeout (re-check running), <0 = signal + while _running.load(ordering: .acquiring), + snd_seq_event_input_pending(seqHandle, 1) > 0 { + var evPtr: UnsafeMutablePointer? + guard snd_seq_event_input(seqHandle, &evPtr) >= 0, + let ev: UnsafeMutablePointer = evPtr else { break } + if let decoded: ALSASeqMIDIEvent = Self.decode(ev.pointee) { + _dispatch(midiMessage(for: decoded), ctx: ctx) + } + } + } + } + + /// Translates a raw sequencer event into the neutral ``ALSASeqMIDIEvent``, + /// or `nil` for a type this backend ignores. The semantic mapping to + /// ``MIDIMessage`` lives in ``midiMessage(for:)``; this only reads fields. + private static func decode(_ ev: snd_seq_event_t) -> ALSASeqMIDIEvent? { + switch UInt32(ev.type) { + case SND_SEQ_EVENT_NOTEON.rawValue: + return .noteOn(channel: ev.data.note.channel, note: ev.data.note.note, velocity: ev.data.note.velocity) + case SND_SEQ_EVENT_NOTEOFF.rawValue: + return .noteOff(channel: ev.data.note.channel, note: ev.data.note.note, velocity: ev.data.note.velocity) + case SND_SEQ_EVENT_KEYPRESS.rawValue: + return .keyPressure(channel: ev.data.note.channel, note: ev.data.note.note, pressure: ev.data.note.velocity) + case SND_SEQ_EVENT_CONTROLLER.rawValue: + return .controller(channel: ev.data.control.channel, + param: UInt8(truncatingIfNeeded: ev.data.control.param), + value: UInt8(truncatingIfNeeded: ev.data.control.value)) + case SND_SEQ_EVENT_PGMCHANGE.rawValue: + return .programChange(channel: ev.data.control.channel, + program: UInt8(truncatingIfNeeded: ev.data.control.value)) + case SND_SEQ_EVENT_CHANPRESS.rawValue: + return .channelPressure(channel: ev.data.control.channel, + pressure: UInt8(truncatingIfNeeded: ev.data.control.value)) + case SND_SEQ_EVENT_PITCHBEND.rawValue: + return .pitchBend(channel: ev.data.control.channel, value: Int(ev.data.control.value)) + case SND_SEQ_EVENT_SYSEX.rawValue: + let len: Int = Int(ev.data.ext.len) + guard len > 0, let base: UnsafeMutableRawPointer = ev.data.ext.ptr else { return .sysex([]) } + let bytes: [UInt8] = Array(UnsafeRawBufferPointer(start: base, count: len).bindMemory(to: UInt8.self)) + return .sysex(bytes) + case SND_SEQ_EVENT_CLOCK.rawValue: return .clock + case SND_SEQ_EVENT_START.rawValue: return .start + case SND_SEQ_EVENT_CONTINUE.rawValue: return .continue + case SND_SEQ_EVENT_STOP.rawValue: return .stop + case SND_SEQ_EVENT_SENSING.rawValue: return .activeSensing + case SND_SEQ_EVENT_RESET.rawValue: return .reset + default: return nil + } + } + + private func _dispatch(_ message: MIDIMessage, ctx: LyrebirdMessageContext) { + let snapshot: [(token: MIDIHandlerToken, onMessage: @Sendable (MIDIMessage, LyrebirdMessageContext) -> Void)] = lock.withLock { handlers } + handlerQueue.async { + for entry in snapshot { entry.onMessage(message, ctx) } + } + } + + // MARK: - Private: endpoint enumeration + + /// Enumerate every readable source / writable destination port on the + /// sequencer, skipping the ALSA System client and our own client. + private func _refreshEndpoints() { + let handle: OpaquePointer? = stateLock.withLock { seq } + guard let seqHandle: OpaquePointer = handle else { return } + let selfClient: Int32 = snd_seq_client_id(seqHandle) + + var newSrcs: [MIDISource] = [] + var newDests: [MIDIDestination] = [] + + var clientInfo: OpaquePointer? + guard snd_seq_client_info_malloc(&clientInfo) >= 0, let cinfo: OpaquePointer = clientInfo else { return } + defer { snd_seq_client_info_free(cinfo) } + var portInfo: OpaquePointer? + guard snd_seq_port_info_malloc(&portInfo) >= 0, let pinfo: OpaquePointer = portInfo else { return } + defer { snd_seq_port_info_free(pinfo) } + + snd_seq_client_info_set_client(cinfo, -1) + while snd_seq_query_next_client(seqHandle, cinfo) >= 0 { + let client: Int32 = snd_seq_client_info_get_client(cinfo) + if client == selfClient || client == 0 { continue } // skip self + System + let clientName: String = String(cString: snd_seq_client_info_get_name(cinfo)) + + snd_seq_port_info_set_client(pinfo, client) + snd_seq_port_info_set_port(pinfo, -1) + while snd_seq_query_next_port(seqHandle, pinfo) >= 0 { + let port: Int32 = snd_seq_port_info_get_port(pinfo) + let caps: UInt32 = snd_seq_port_info_get_capability(pinfo) + let portName: String = String(cString: snd_seq_port_info_get_name(pinfo)) + let label: String = "\(clientName): \(portName)" + + let readMask: UInt32 = UInt32(SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ) + if caps & readMask == readMask { + newSrcs.append(MIDISource(name: label, client: client, port: port)) + } + let writeMask: UInt32 = UInt32(SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE) + if caps & writeMask == writeMask { + newDests.append(MIDIDestination(name: label, client: client, port: port)) + } + } + } + lock.withLock { _sources = newSrcs; _destinations = newDests } + } + + /// Subscribe our input port to every enumerated source, so a controller's + /// output reaches our handlers without the caller wiring it by hand. + private func _connectAllSources() { + let (handle, inPort): (OpaquePointer?, Int32) = stateLock.withLock { (seq, inputPort) } + guard let seqHandle: OpaquePointer = handle, inPort >= 0 else { return } + let srcs: [MIDISource] = lock.withLock { _sources } + for src: MIDISource in srcs { + _ = snd_seq_connect_from(seqHandle, inPort, src.client, src.port) + } + } +} + +#endif diff --git a/Sources/Lyrebird/MIDI/ALSASeqMIDIEvent.swift b/Sources/Lyrebird/MIDI/ALSASeqMIDIEvent.swift new file mode 100644 index 0000000..a3842d4 --- /dev/null +++ b/Sources/Lyrebird/MIDI/ALSASeqMIDIEvent.swift @@ -0,0 +1,77 @@ +// ALSASeqMIDIEvent.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// A decoded ALSA sequencer event, in the subset Lyrebird's Linux MIDI backend +/// understands. +/// +/// This is the seam between the ALSA C API and `MIDIMessage`: the driver +/// translates a `snd_seq_event_t` into one of these cases (a small switch on +/// the event type and its union fields), and ``midiMessage(for:)`` turns it +/// into the platform-neutral ``MIDIMessage``. Keeping the translation in two +/// steps means the second — the part with the real semantic decisions (running +/// note-on-velocity-0, the pitch-bend offset) — is pure Swift with no ALSA +/// dependency, so it is unit-tested on every platform rather than only against +/// a connected controller. +/// +/// Channel is 0-based (ALSA's own convention), matching ``MIDIMessage``. +public enum ALSASeqMIDIEvent: Equatable, Sendable { + case noteOn(channel: UInt8, note: UInt8, velocity: UInt8) + case noteOff(channel: UInt8, note: UInt8, velocity: UInt8) + case keyPressure(channel: UInt8, note: UInt8, pressure: UInt8) + case controller(channel: UInt8, param: UInt8, value: UInt8) + case programChange(channel: UInt8, program: UInt8) + case channelPressure(channel: UInt8, pressure: UInt8) + /// ALSA reports pitch bend already signed, in `[-8192, 8191]`, which is + /// exactly ``MIDIMessage/pitchBend(channel:value:)``'s convention. + case pitchBend(channel: UInt8, value: Int) + case sysex([UInt8]) + case clock + case start + case `continue` + case stop + case activeSensing + case reset +} + +/// Converts a decoded sequencer event into a ``MIDIMessage``. +/// +/// Channel-voice events are routed through ``MIDIMessage/from(status:data1:data2:)`` +/// so the Linux backend applies the identical parsing the CoreMIDI backend does +/// — most importantly, a note-on with velocity 0 becomes a `noteOff`. +/// Pitch bend is clamped into the 14-bit signed range before that shared parser +/// re-derives the offset, so an out-of-range value cannot wrap. +public func midiMessage(for event: ALSASeqMIDIEvent) -> MIDIMessage { + switch event { + case .noteOn(let ch, let note, let vel): + return MIDIMessage.from(status: 0x90 | (ch & 0x0F), data1: note, data2: vel) + case .noteOff(let ch, let note, let vel): + return MIDIMessage.from(status: 0x80 | (ch & 0x0F), data1: note, data2: vel) + case .keyPressure(let ch, let note, let pressure): + return MIDIMessage.from(status: 0xA0 | (ch & 0x0F), data1: note, data2: pressure) + case .controller(let ch, let param, let value): + return MIDIMessage.from(status: 0xB0 | (ch & 0x0F), data1: param, data2: value) + case .programChange(let ch, let program): + return MIDIMessage.from(status: 0xC0 | (ch & 0x0F), data1: program) + case .channelPressure(let ch, let pressure): + return MIDIMessage.from(status: 0xD0 | (ch & 0x0F), data1: pressure) + case .pitchBend(let ch, let value): + let clamped: Int = min(8191, max(-8192, value)) + let raw14: Int = clamped + 8192 + return MIDIMessage.from( + status: 0xE0 | (ch & 0x0F), + data1: UInt8(raw14 & 0x7F), + data2: UInt8((raw14 >> 7) & 0x7F) + ) + case .sysex(let bytes): + return .sysex(bytes) + case .clock: return .clock + case .start: return .start + case .continue: return .continue + case .stop: return .stop + case .activeSensing: return .activeSensing + case .reset: return .reset + } +} diff --git a/Sources/Lyrebird/MIDI/MIDI.swift b/Sources/Lyrebird/MIDI/MIDI.swift index 193161b..f3ecb72 100644 --- a/Sources/Lyrebird/MIDI/MIDI.swift +++ b/Sources/Lyrebird/MIDI/MIDI.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(CoreMIDI) import CoreMIDI import Foundation import Synchronization @@ -415,3 +416,4 @@ public final class MIDI: @unchecked Sendable { } // `MIDIError` lives in `MIDI/MIDIError.swift`. +#endif diff --git a/Sources/Lyrebird/MIDI/MIDIDestination.swift b/Sources/Lyrebird/MIDI/MIDIDestination.swift index 5e39098..5586743 100644 --- a/Sources/Lyrebird/MIDI/MIDIDestination.swift +++ b/Sources/Lyrebird/MIDI/MIDIDestination.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(CoreMIDI) import CoreMIDI /// A MIDI destination endpoint (hardware or virtual). @@ -11,3 +12,19 @@ public struct MIDIDestination: Sendable { public let name: String public let endpointRef: MIDIEndpointRef } +#elseif canImport(CALSA) + +/// A MIDI destination endpoint (hardware or virtual), addressed by its ALSA +/// sequencer `client:port` pair. +public struct MIDIDestination: Sendable, Equatable { + public let name: String + public let client: Int32 + public let port: Int32 + + public init(name: String, client: Int32, port: Int32) { + self.name = name + self.client = client + self.port = port + } +} +#endif diff --git a/Sources/Lyrebird/MIDI/MIDIError.swift b/Sources/Lyrebird/MIDI/MIDIError.swift index 3d03c9e..6e3a970 100644 --- a/Sources/Lyrebird/MIDI/MIDIError.swift +++ b/Sources/Lyrebird/MIDI/MIDIError.swift @@ -7,11 +7,15 @@ import Foundation /// Errors thrown by `MIDI` lifecycle and send operations. -public enum MIDIError: Error, Sendable { +public enum MIDIError: Error, Sendable, Equatable { case clientCreateFailed(OSStatus) case portCreateFailed(OSStatus) case virtualPortFailed(OSStatus) case sendFailed(OSStatus) case notStarted case alreadyStarted + /// A `stop()` gave up waiting for the input thread to exit, so the client + /// was abandoned (its handle leaked); a later `start()` is refused rather + /// than running a second thread alongside the first. Linux/ALSA only. + case threadDidNotExit } diff --git a/Sources/Lyrebird/MIDI/MIDISource.swift b/Sources/Lyrebird/MIDI/MIDISource.swift index 3d0b3e1..b1beb63 100644 --- a/Sources/Lyrebird/MIDI/MIDISource.swift +++ b/Sources/Lyrebird/MIDI/MIDISource.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(CoreMIDI) import CoreMIDI /// A MIDI source endpoint (hardware or virtual). @@ -11,3 +12,19 @@ public struct MIDISource: Sendable { public let name: String public let endpointRef: MIDIEndpointRef } +#elseif canImport(CALSA) + +/// A MIDI source endpoint (hardware or virtual), addressed by its ALSA +/// sequencer `client:port` pair. +public struct MIDISource: Sendable, Equatable { + public let name: String + public let client: Int32 + public let port: Int32 + + public init(name: String, client: Int32, port: Int32) { + self.name = name + self.client = client + self.port = port + } +} +#endif diff --git a/Sources/Lyrebird/Math/LyrebirdConstants.swift b/Sources/Lyrebird/Math/LyrebirdConstants.swift index 6f720b8..81bcc49 100644 --- a/Sources/Lyrebird/Math/LyrebirdConstants.swift +++ b/Sources/Lyrebird/Math/LyrebirdConstants.swift @@ -127,7 +127,7 @@ func lyrebirdSeedXorshift64( from seed: UInt64?, mixConstant: UInt64 ) -> UInt64 { - let raw: UInt64 = seed ?? clock_gettime_nsec_np(CLOCK_UPTIME_RAW) + let raw: UInt64 = seed ?? LyrebirdMonotonicClock.ticks() let mixed: UInt64 = (raw == 0 ? lyrebirdGranularDefaultSeed : raw) ^ mixConstant return mixed == 0 ? mixConstant : mixed } diff --git a/Sources/Lyrebird/Math/LyrebirdMusicMath.swift b/Sources/Lyrebird/Math/LyrebirdMusicMath.swift index 297adae..a9d998d 100644 --- a/Sources/Lyrebird/Math/LyrebirdMusicMath.swift +++ b/Sources/Lyrebird/Math/LyrebirdMusicMath.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP // MARK: - RT safety // diff --git a/Sources/Lyrebird/NodeTree/Group.swift b/Sources/Lyrebird/NodeTree/Group.swift index 5c9b9a8..8379c69 100644 --- a/Sources/Lyrebird/NodeTree/Group.swift +++ b/Sources/Lyrebird/NodeTree/Group.swift @@ -333,7 +333,13 @@ public final class Group: Synthesizer { /// Walk every direct child `PreparedNode`, call `handler` on it, then clear the list. /// /// Clears `head`, `tail`, and resets `_atomicCount` to 0 after draining. - /// RT-thread only — called from `SynthesisEngine.applyEvent(.groupFree)`. + /// + /// Two call sites with different thread contracts: + /// - `SynthesisEngine.applyEvent(.groupFree)` — RT thread, during the block. + /// - `SynthesisEngine.stop()` node-tree teardown — main thread, AFTER + /// `driver.stop()` has halted the RT thread (no concurrent access). + /// Both are single-threaded with respect to this group; the handler must not + /// allocate/lock when invoked from the RT path. internal func _drainNodes(_ handler: (PreparedNode) -> Void) { var node: PreparedNode? = head while let n: PreparedNode = node { diff --git a/Sources/Lyrebird/NodeTree/ParallelGroup.swift b/Sources/Lyrebird/NodeTree/ParallelGroup.swift index 0d7e490..987c1d6 100644 --- a/Sources/Lyrebird/NodeTree/ParallelGroup.swift +++ b/Sources/Lyrebird/NodeTree/ParallelGroup.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Foundation /// A node container that evaluates its children concurrently on multiple CPU cores. diff --git a/Sources/Lyrebird/OSC/OSCClient.swift b/Sources/Lyrebird/OSC/OSCClient.swift index 24aa330..86abb2b 100644 --- a/Sources/Lyrebird/OSC/OSCClient.swift +++ b/Sources/Lyrebird/OSC/OSCClient.swift @@ -5,28 +5,43 @@ // SPDX-License-Identifier: MIT import Foundation +#if canImport(Network) import Network +#elseif canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#endif /// Language-side OSC 1.0 UDP sender for Lyrebird. /// -/// Create one client per remote endpoint. The underlying `NWConnection` is created -/// lazily on the first send and reused for subsequent calls. +/// Create one client per remote endpoint. On Apple the transport is +/// `Network.framework`'s `NWConnection`; off Apple it is a connected POSIX UDP +/// socket. Either way the socket/connection is created lazily on the first send +/// and reused. The OSC 1.0 encoding (`OSCCodec`) is shared. /// /// ```swift /// let client = OSCClient(host: "127.0.0.1", port: 57120) -/// -/// // Convenience form /// client.send(address: "/freq", args: [.float32(440.0)]) /// ``` // @unchecked Sendable invariant: `host`, `port`, and `sendQueue` are immutable -// post-init. Mutable `connection` is created, used, and torn down only on -// `sendQueue` (a serial `DispatchQueue`); no caller-thread reads/writes occur. +// post-init. Mutable transport state is created, used, and torn down only on +// `sendQueue` (a serial `DispatchQueue`); no caller-thread access occurs. public final class OSCClient: @unchecked Sendable { + private let hostString: String + private let portValue: UInt16 + private let sendQueue: DispatchQueue = DispatchQueue(label: "lyrebird.osc.client", qos: .userInteractive) + + #if canImport(Network) private let host: NWEndpoint.Host private let port: NWEndpoint.Port private var connection: NWConnection? - private let sendQueue: DispatchQueue = DispatchQueue(label: "lyrebird.osc.client", qos: .userInteractive) + #else + /// Connected UDP socket, or -1 before the first send / after a failure. + private var fd: Int32 = -1 + private var resolveFailed: Bool = false + #endif /// Create a client that sends to `host`:`port` via UDP. /// @@ -37,15 +52,26 @@ public final class OSCClient: @unchecked Sendable { host: String, port: UInt16 ) { + self.hostString = host + self.portValue = port + #if canImport(Network) self.host = NWEndpoint.Host(host) self.port = NWEndpoint.Port(integerLiteral: port) + #endif } + #if !canImport(Network) + deinit { + // The socket is only ever touched on sendQueue; by deinit no send can be + // in flight, so closing directly is safe. + if fd >= 0 { close(fd) } + } + #endif + // MARK: - Send /// Send an OSC message by address and argument list. /// - /// Encodes the message using the OSC 1.0 binary format and fires the UDP datagram. /// Thread-safe — may be called from any thread. /// /// - Parameters: @@ -58,25 +84,28 @@ public final class OSCClient: @unchecked Sendable { send(OSCMessage(address: address, arguments: args)) } - /// Send an `OSCMessage`. - /// - /// Thread-safe — may be called from any thread. + /// Send an `OSCMessage`. Thread-safe — may be called from any thread. /// /// - Parameter message: The message to encode and send. public func send(_ message: OSCMessage) { let data: Data = OSCCodec.encode(message) - // All connection state is only accessed on sendQueue to prevent data races. - // async to avoid blocking the calling thread (UDP is fire-and-forget). + // All transport state is only accessed on sendQueue to prevent races. + // async to avoid blocking the caller (UDP is fire-and-forget). sendQueue.async { [weak self] in guard let self: OSCClient = self else { return } - let conn: NWConnection = self._connection() - conn.send(content: data, completion: .idempotent) + self._transmit(data) } } - // MARK: - Private + // MARK: - Private transport + #if canImport(Network) // Must only be called from sendQueue. + private func _transmit(_ data: Data) { + let conn: NWConnection = _connection() + conn.send(content: data, completion: .idempotent) + } + private func _connection() -> NWConnection { if let existing: NWConnection = connection { return existing } let conn: NWConnection = NWConnection(host: host, port: port, using: .udp) @@ -84,4 +113,49 @@ public final class OSCClient: @unchecked Sendable { connection = conn return conn } + #else + // Must only be called from sendQueue. + private func _transmit(_ data: Data) { + guard _ensureSocket() else { return } + _ = data.withUnsafeBytes { raw -> Int in + guard let base: UnsafeRawPointer = raw.baseAddress else { return -1 } + // `sendto` with a nil destination behaves as `send` on a connected + // socket, and avoids the name clash with this class's own `send`. + return sendto(fd, base, raw.count, Int32(MSG_NOSIGNAL), nil, 0) + } + } + + /// Opens and connects the UDP socket on first use. A resolution/connect + /// failure is latched so a bad host does not re-resolve on every send. + private func _ensureSocket() -> Bool { + if fd >= 0 { return true } + if resolveFailed { return false } + + var hints: addrinfo = addrinfo() + hints.ai_family = AF_INET + hints.ai_socktype = Int32(SOCK_DGRAM.rawValue) + hints.ai_protocol = Int32(IPPROTO_UDP) + + var result: UnsafeMutablePointer? + let rc: Int32 = getaddrinfo(hostString, String(portValue), &hints, &result) + guard rc == 0, let info: UnsafeMutablePointer = result else { + resolveFailed = true + return false + } + defer { freeaddrinfo(info) } + + let sock: Int32 = socket(info.pointee.ai_family, info.pointee.ai_socktype, info.pointee.ai_protocol) + guard sock >= 0 else { resolveFailed = true; return false } + // Connected UDP: the kernel remembers the peer, so `send` needs no addr, + // and a later `send` to an unreachable port surfaces as an error rather + // than being silently dropped. + guard connect(sock, info.pointee.ai_addr, info.pointee.ai_addrlen) == 0 else { + close(sock) + resolveFailed = true + return false + } + fd = sock + return true + } + #endif } diff --git a/Sources/Lyrebird/OSC/OSCServer.swift b/Sources/Lyrebird/OSC/OSCServer.swift index 48e42ad..3895174 100644 --- a/Sources/Lyrebird/OSC/OSCServer.swift +++ b/Sources/Lyrebird/OSC/OSCServer.swift @@ -5,8 +5,14 @@ // SPDX-License-Identifier: MIT import Foundation -import Network import Synchronization +#if canImport(Network) +import Network +#elseif canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#endif /// Opaque token returned by `addHandler`; pass to `removeHandler` to unregister. public struct OSCHandlerToken: Sendable, Equatable { @@ -16,8 +22,10 @@ public struct OSCHandlerToken: Sendable, Equatable { /// Language-side OSC 1.0 UDP server for Lyrebird. /// /// Listens on a UDP port and dispatches incoming messages to registered handlers. -/// Handlers fire on a background queue (never the RT audio thread). Use the supplied -/// `LyrebirdMessageContext` to schedule synths or update parameters. +/// Handlers fire on a background queue (never the RT audio thread). On Apple the +/// transport is `Network.framework`'s `NWListener`; off Apple it is a POSIX UDP +/// socket read on a dedicated thread. The message decode, address matching, and +/// dispatch (`OSCCodec`) are shared. /// /// ```swift /// let server = OSCServer(port: 57120, engine: engine) @@ -36,11 +44,41 @@ public final class OSCServer: @unchecked Sendable { private let lock: NSLock = NSLock() private var handlers: [(token: OSCHandlerToken, address: String, handler: @Sendable (OSCMessage, LyrebirdMessageContext) -> Void)] = [] private let nextTokenID: Atomic = Atomic(0) + private let handlerQueue: DispatchQueue = DispatchQueue(label: "lyrebird.osc.handlers", qos: .userInteractive) + #if canImport(Network) private var listener: NWListener? private let listenerLock: NSLock = NSLock() private let listenerQueue: DispatchQueue = DispatchQueue(label: "lyrebird.osc.listener", qos: .userInteractive) - private let handlerQueue: DispatchQueue = DispatchQueue(label: "lyrebird.osc.handlers", qos: .userInteractive) + #else + // `fd` and `recvThread` are mutated only under `socketLock`; `_running` / + // `_abandonedThread` are atomic. That, plus the immutable `_port` / `engine` + // and the `lock`-guarded handler registry, is what makes the @unchecked + // Sendable sound. + private let socketLock: NSLock = NSLock() + /// Set-once under `socketLock` so two concurrent `start()` calls cannot both + /// bind and launch a thread — the loser returns (`start()` is idempotent). + /// Cleared by `stop()`. Mirrors the MIDI backend's `isStarted` claim; the + /// Apple path gets the same guarantee from `NWListener`'s duplicate-cancel. + private var isStarted: Bool = false + private var fd: Int32 = -1 + private var recvThread: Thread? + private let _running: Atomic = Atomic(false) + /// Set when a `stop()` gave up waiting for the receive thread; the socket is + /// then leaked rather than closed under it, and a later `start()` is + /// refused — the same discipline `ALSAAudioDriver` uses for its render thread. + private let _abandonedThread: Atomic = Atomic(false) + private let threadExited: DispatchSemaphore = DispatchSemaphore(value: 0) + /// UDP datagrams above this are rare for OSC; a fixed read buffer keeps the + /// receive loop allocation-free. + private static let receiveBufferBytes: Int = 65_536 + /// Poll cadence so `stop()` is seen promptly. + private static let pollTimeoutMilliseconds: Int32 = 200 + /// How long `stop()` waits for the receive thread to leave its loop. The + /// `shutdown()` before the wait unblocks a pending `recv`, so this is only + /// approached under severe scheduler starvation. + private static let threadJoinTimeout: TimeInterval = 2.0 + #endif public var port: UInt16 { _port } @@ -52,10 +90,65 @@ public final class OSCServer: @unchecked Sendable { self.engine = engine } - // MARK: - Lifecycle + #if !canImport(Network) + deinit { stop() } + #endif + // MARK: - Handler registration (shared) + + /// Register a handler for messages whose address matches `address`. + /// + /// `address` supports the OSC 1.0 glob operators: `?` (any char), `*` (any + /// sequence excluding `/`), `[abc]` / `[a-z]` (character class), `{a,b}` + /// (alternation). + /// + /// - Parameters: + /// - address: OSC address pattern to match against incoming addresses. + /// - handler: Closure invoked on the handler queue when a match is found. + /// - Returns: Token for later removal via ``removeHandler(_:)``. + @discardableResult + public func addHandler( + address: String, + handler: @Sendable @escaping (OSCMessage, LyrebirdMessageContext) -> Void + ) -> OSCHandlerToken { + let id: UInt64 = nextTokenID.add(1, ordering: .relaxed).newValue + let token: OSCHandlerToken = OSCHandlerToken(id: id) + lock.withLock { handlers.append((token, address, handler)) } + return token + } + + /// Remove the handler identified by `token`. Safe after the server is stopped. + public func removeHandler(_ token: OSCHandlerToken) { + lock.withLock { handlers.removeAll { $0.token == token } } + } + + // MARK: - Decode + dispatch (shared) + + private func _handle( + _ data: Data, + ctx: LyrebirdMessageContext + ) { + let messages: [OSCMessage] + do { + messages = try OSCCodec.decode(data) + } catch { + lyrebirdPrintError("[Lyrebird] OSC decode failed: \(error)\n") + return + } + let snapshot: [(token: OSCHandlerToken, address: String, handler: @Sendable (OSCMessage, LyrebirdMessageContext) -> Void)] = lock.withLock { handlers } + handlerQueue.async { + for msg: OSCMessage in messages { + for entry: (token: OSCHandlerToken, address: String, handler: @Sendable (OSCMessage, LyrebirdMessageContext) -> Void) in snapshot where OSCCodec.oscAddressMatches(entry.address, msg.address) { + entry.handler(msg, ctx) + } + } + } + } + + // MARK: - Lifecycle (platform transport) + + #if canImport(Network) public func start() throws { - // Fast pre-check outside the expensive NWListener construction. if listenerLock.withLock({ listener != nil }) { return } let nwPort: NWEndpoint.Port = NWEndpoint.Port(integerLiteral: _port) @@ -66,7 +159,6 @@ public final class OSCServer: @unchecked Sendable { } newListener.start(queue: listenerQueue) - // Re-check under lock; cancel duplicate if we lost a concurrent race. let duplicate: NWListener? = listenerLock.withLock { if listener != nil { return newListener } listener = newListener @@ -82,52 +174,12 @@ public final class OSCServer: @unchecked Sendable { } } - // MARK: - Handler registration - - /// Register a handler for messages whose address matches `address`. - /// - /// `address` supports the OSC 1.0 glob operators: `?` (any char), `*` (any sequence - /// excluding `/`), `[abc]` / `[a-z]` (character class), `{a,b}` (alternation). - /// - /// ```swift - /// server.addHandler(address: "/synth/*") { msg, ctx in ... } // wildcard - /// server.addHandler(address: "/{freq,amp}") { msg, ctx in ... } // alternation - /// ``` - /// - /// - Parameters: - /// - address: OSC address pattern to match against incoming message addresses. - /// - handler: Closure invoked on `lyrebird.osc.handlers` queue when a match is found. - /// - Returns: Token for later removal via ``removeHandler(_:)``. - @discardableResult - public func addHandler( - address: String, - handler: @Sendable @escaping (OSCMessage, LyrebirdMessageContext) -> Void - ) -> OSCHandlerToken { - let id: UInt64 = nextTokenID.add(1, ordering: .relaxed).newValue - let token: OSCHandlerToken = OSCHandlerToken(id: id) - lock.withLock { handlers.append((token, address, handler)) } - return token - } - - /// Remove the handler identified by `token`. Safe to call even after the server is stopped. - public func removeHandler(_ token: OSCHandlerToken) { - lock.withLock { handlers.removeAll { $0.token == token } } - } - - // MARK: - Private: connection accept + receive loop - - private func _accept( - _ connection: NWConnection, - ctx: LyrebirdMessageContext - ) { + private func _accept(_ connection: NWConnection, ctx: LyrebirdMessageContext) { connection.start(queue: listenerQueue) _receive(connection, ctx: ctx) } - private func _receive( - _ connection: NWConnection, - ctx: LyrebirdMessageContext - ) { + private func _receive(_ connection: NWConnection, ctx: LyrebirdMessageContext) { connection.receiveMessage { [weak self] data, _, isComplete, error in if let data: Data, !data.isEmpty { self?._handle(data, ctx: ctx) @@ -136,25 +188,112 @@ public final class OSCServer: @unchecked Sendable { self?._receive(connection, ctx: ctx) } } - - private func _handle( - _ data: Data, - ctx: LyrebirdMessageContext - ) { - let messages: [OSCMessage] - do { - messages = try OSCCodec.decode(data) - } catch { - print("[Lyrebird] OSC decode failed: \(error)") - return + #else + /// Bind a UDP socket to the port and start the receive thread. + /// + /// - Throws: ``OSCServerError`` on socket / bind failure (carrying `errno`). + public func start() throws { + guard !_abandonedThread.load(ordering: .acquiring) else { + // A previous receive thread never returned; its (leaked) socket is + // still being read. Binding a second one would leave two live. + throw OSCServerError.threadDidNotExit } - let snapshot: [(token: OSCHandlerToken, address: String, handler: @Sendable (OSCMessage, LyrebirdMessageContext) -> Void)] = lock.withLock { handlers } - handlerQueue.async { - for msg: OSCMessage in messages { - for entry: (token: OSCHandlerToken, address: String, handler: @Sendable (OSCMessage, LyrebirdMessageContext) -> Void) in snapshot where OSCCodec.oscAddressMatches(entry.address, msg.address) { - entry.handler(msg, ctx) - } + // Atomic claim: the first caller to flip `isStarted` proceeds; any + // concurrent or repeat `start()` returns without a second bind/thread. + let claimed: Bool = socketLock.withLock { + if isStarted { return false } + isStarted = true + return true + } + guard claimed else { return } + + let sock: Int32 = socket(AF_INET, Int32(SOCK_DGRAM.rawValue), Int32(IPPROTO_UDP)) + guard sock >= 0 else { + socketLock.withLock { isStarted = false } + throw OSCServerError.socketFailed(code: Int(errno)) + } + + var reuse: Int32 = 1 + _ = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, socklen_t(MemoryLayout.size)) + + var addr: sockaddr_in = sockaddr_in() + addr.sin_family = sa_family_t(AF_INET) + addr.sin_port = _port.bigEndian // network byte order + addr.sin_addr.s_addr = INADDR_ANY // already 0; explicit for clarity + let bindRC: Int32 = withUnsafePointer(to: &addr) { ptr in + ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sa in + bind(sock, sa, socklen_t(MemoryLayout.size)) } } + guard bindRC == 0 else { + let code: Int = Int(errno) + close(sock) + socketLock.withLock { isStarted = false } // release the claim on failure + throw OSCServerError.bindFailed(code: code) + } + + // Publish the socket + thread under the lock, then raise `_running`, then + // launch. `thread.start()` is last, so the receive loop never observes + // half-published state; a concurrent `stop()` either runs entirely before + // the fd is visible (and no-ops) or sees the fully-installed pair. + let thread: Thread = Thread { [weak self] in self?._recvLoop(sock) } + thread.name = "lyrebird.osc.recv" + socketLock.withLock { fd = sock; recvThread = thread } + _running.store(true, ordering: .releasing) + thread.start() } + + public func stop() { + _running.store(false, ordering: .releasing) + let (sock, hadThread): (Int32, Bool) = socketLock.withLock { + let s: Int32 = fd + let had: Bool = recvThread != nil + fd = -1 + recvThread = nil + isStarted = false + return (s, had) + } + if sock >= 0 { + // Shut the socket down first so a blocked recv returns, then let the + // thread observe `_running == false` and exit before we close. + shutdown(sock, Int32(SHUT_RDWR)) + } + // Close only once the receive thread has actually left its loop. On the + // (not-expected — poll wakes every 200 ms and shutdown unblocks recv) + // chance the join times out, the fd is leaked and the server abandoned + // rather than closing under a thread that may still `recv` on it. + let joined: Bool = hadThread + ? threadExited.wait(timeout: .now() + Self.threadJoinTimeout) == .success + : true + if joined { + if sock >= 0 { close(sock) } + } else { + _abandonedThread.store(true, ordering: .releasing) + } + } + + private func _recvLoop(_ sock: Int32) { + defer { threadExited.signal() } + let ctx: LyrebirdMessageContext = LyrebirdMessageContext(engine: engine) + var buffer: [UInt8] = [UInt8](repeating: 0, count: Self.receiveBufferBytes) + var pfd: pollfd = pollfd(fd: sock, events: Int16(POLLIN), revents: 0) + + while _running.load(ordering: .acquiring) { + let ready: Int32 = poll(&pfd, 1, Self.pollTimeoutMilliseconds) + guard ready > 0 else { continue } // 0 = timeout (re-check running) + let n: Int = buffer.withUnsafeMutableBytes { raw -> Int in + guard let base: UnsafeMutableRawPointer = raw.baseAddress else { return -1 } + return recv(sock, base, raw.count, 0) + } + guard n > 0 else { + // UDP is connectionless: recv returning 0 means an empty + // datagram (which a peer may legitimately send), not a closed + // connection — dropping out here would silently kill the + // listener. -1 is interrupted/would-block. Either way, loop. + continue + } + _handle(Data(buffer[0..` load. /// /// ## When to use @UIParam vs @LiveParam /// -/// Use `@UIParam` (this type, in `LyrebirdUI`) when SwiftUI controls bind to the parameter. -/// Use `@LiveParam` (in `Lyrebird`) when no UI is involved. +/// Use `@UIParam` (this type) when a UI control binds to the parameter — SwiftUI on Apple +/// platforms, SwiftOpenUI/GTK4 on Linux. Use `@LiveParam` when no UI is involved. Both live +/// in the core `LyrebirdSynth` module; the UI controls live in the cross-platform +/// `LyrebirdUI` module (SwiftUI on Apple, SwiftOpenUI/GTK4 on Linux). /// /// `@UIParam` is a strict superset of `@LiveParam`: identical RT thread behavior — the /// projected `UIParamNode` is a `ControlGenerator` that delivers a linearly-interpolated @@ -27,7 +27,8 @@ import LyrebirdSynth /// ## Usage /// /// ```swift -/// import LyrebirdUI +/// import LyrebirdSynth // @UIParam +/// import LyrebirdUI // ParameterSlider — SwiftUI on Apple, SwiftOpenUI/GTK4 on Linux /// /// class MySynth: SynthesizerBase { /// @UIParam var frequency: Double = 440.0 diff --git a/Sources/LyrebirdUI/UIParamNode.swift b/Sources/Lyrebird/Parameters/UIParamNode.swift similarity index 95% rename from Sources/LyrebirdUI/UIParamNode.swift rename to Sources/Lyrebird/Parameters/UIParamNode.swift index d03167e..5925809 100644 --- a/Sources/LyrebirdUI/UIParamNode.swift +++ b/Sources/Lyrebird/Parameters/UIParamNode.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: MIT import Observation -import LyrebirdSynth /// UIParamNode — the `@Observable` backing object for an `@UIParam` property wrapper. /// @@ -31,6 +30,12 @@ import LyrebirdSynth /// `value` or the `@Observable` registrar. The `Atomic` inside `_node` is the /// sole cross-thread communication channel. /// +/// > Note: "main thread" here means whichever single thread runs the UI toolkit's +/// > event loop — the main actor under SwiftUI on Apple platforms, or the GTK4 +/// > main loop under SwiftOpenUI on Linux (both run on the process's main thread). +/// > `value` and `update(_:)` must be reached only from that one thread; they are +/// > not safe to call from a GTK idle/worker callback or any off-main dispatch. +/// /// ## Rate /// /// `UIParamNode` conforms to `ControlGenerator`. When `controlBlockSize == blockSize` diff --git a/Sources/Lyrebird/Patterns/PatternFactories.swift b/Sources/Lyrebird/Patterns/PatternFactories.swift index 39144b5..0fbc510 100644 --- a/Sources/Lyrebird/Patterns/PatternFactories.swift +++ b/Sources/Lyrebird/Patterns/PatternFactories.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Darwin +import LyrebirdDSP // MARK: - Atomic value sources (generic T) diff --git a/Sources/Lyrebird/Scheduling/LyrebirdRoutineContext.swift b/Sources/Lyrebird/Scheduling/LyrebirdRoutineContext.swift index 3c557ef..a6253f4 100644 --- a/Sources/Lyrebird/Scheduling/LyrebirdRoutineContext.swift +++ b/Sources/Lyrebird/Scheduling/LyrebirdRoutineContext.swift @@ -428,7 +428,9 @@ public final class LyrebirdRoutineContext: @unchecked Sendable { control.pauseCondition.lock() defer { control.pauseCondition.unlock() } while control.isPaused.load(ordering: .relaxed) { - control.pauseCondition.wait( + // Return value (signaled-before-deadline) is intentionally unused — + // the loop re-checks `isPaused` / `shouldStop` each poll regardless. + _ = control.pauseCondition.wait( until: Date(timeIntervalSinceNow: LyrebirdRoutineContext.pollIntervalSeconds) ) if control.shouldStop.load(ordering: .relaxed) { diff --git a/Sources/Lyrebird/Score/MusicXML/MusicXMLError.swift b/Sources/Lyrebird/Score/MusicXML/MusicXMLError.swift index 06dcdc6..9d39a14 100644 --- a/Sources/Lyrebird/Score/MusicXML/MusicXMLError.swift +++ b/Sources/Lyrebird/Score/MusicXML/MusicXMLError.swift @@ -5,6 +5,9 @@ // SPDX-License-Identifier: MIT import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif /// Errors thrown by ``Score/fromMusicXML(data:)`` parsing. public enum MusicXMLError: Error, Equatable, Sendable { diff --git a/Sources/Lyrebird/Score/MusicXML/MusicXMLParser+Build.swift b/Sources/Lyrebird/Score/MusicXML/MusicXMLParser+Build.swift index 669d8e7..b85498c 100644 --- a/Sources/Lyrebird/Score/MusicXML/MusicXMLParser+Build.swift +++ b/Sources/Lyrebird/Score/MusicXML/MusicXMLParser+Build.swift @@ -5,6 +5,9 @@ // SPDX-License-Identifier: MIT import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif extension _MusicXMLParser { func parsedScore() throws -> Score { diff --git a/Sources/Lyrebird/Score/MusicXML/MusicXMLParser+Commit.swift b/Sources/Lyrebird/Score/MusicXML/MusicXMLParser+Commit.swift index 89bc543..180a8d3 100644 --- a/Sources/Lyrebird/Score/MusicXML/MusicXMLParser+Commit.swift +++ b/Sources/Lyrebird/Score/MusicXML/MusicXMLParser+Commit.swift @@ -5,6 +5,9 @@ // SPDX-License-Identifier: MIT import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif extension _MusicXMLParser { // MARK: - Note commit diff --git a/Sources/Lyrebird/Score/MusicXML/MusicXMLParser+Delegate.swift b/Sources/Lyrebird/Score/MusicXML/MusicXMLParser+Delegate.swift index 0c45956..d860efd 100644 --- a/Sources/Lyrebird/Score/MusicXML/MusicXMLParser+Delegate.swift +++ b/Sources/Lyrebird/Score/MusicXML/MusicXMLParser+Delegate.swift @@ -5,6 +5,9 @@ // SPDX-License-Identifier: MIT import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif extension _MusicXMLParser { // MARK: - XMLParserDelegate diff --git a/Sources/Lyrebird/Score/MusicXML/MusicXMLParser.swift b/Sources/Lyrebird/Score/MusicXML/MusicXMLParser.swift index 0407851..f220568 100644 --- a/Sources/Lyrebird/Score/MusicXML/MusicXMLParser.swift +++ b/Sources/Lyrebird/Score/MusicXML/MusicXMLParser.swift @@ -5,6 +5,9 @@ // SPDX-License-Identifier: MIT import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif /// Internal `XMLParserDelegate` that walks a `score-partwise` MusicXML /// document and produces a ``Score``. diff --git a/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLAnnotate.swift b/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLAnnotate.swift index d892f97..a8c5ee8 100644 --- a/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLAnnotate.swift +++ b/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLAnnotate.swift @@ -5,6 +5,9 @@ // SPDX-License-Identifier: MIT import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif extension Score { // MARK: - Atom collection (tree walk) diff --git a/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLAtoms.swift b/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLAtoms.swift index e8c1c46..6d697c5 100644 --- a/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLAtoms.swift +++ b/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLAtoms.swift @@ -5,6 +5,9 @@ // SPDX-License-Identifier: MIT import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif extension Score { // MARK: - Internal atom representation diff --git a/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLDecode.swift b/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLDecode.swift index 410af2c..1be6a42 100644 --- a/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLDecode.swift +++ b/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLDecode.swift @@ -5,6 +5,9 @@ // SPDX-License-Identifier: MIT import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif extension Score { diff --git a/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLEmit.swift b/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLEmit.swift index f853bc1..fb2311b 100644 --- a/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLEmit.swift +++ b/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLEmit.swift @@ -5,6 +5,9 @@ // SPDX-License-Identifier: MIT import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif extension Score { // MARK: - Atom emission diff --git a/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLEncode.swift b/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLEncode.swift index c7c74d9..1db917d 100644 --- a/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLEncode.swift +++ b/Sources/Lyrebird/Score/MusicXML/Score+MusicXMLEncode.swift @@ -5,6 +5,9 @@ // SPDX-License-Identifier: MIT import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif extension Score { diff --git a/Sources/Lyrebird/Score/MusicXML/_NoteContext.swift b/Sources/Lyrebird/Score/MusicXML/_NoteContext.swift index 3c148ee..fe6acf1 100644 --- a/Sources/Lyrebird/Score/MusicXML/_NoteContext.swift +++ b/Sources/Lyrebird/Score/MusicXML/_NoteContext.swift @@ -5,6 +5,9 @@ // SPDX-License-Identifier: MIT import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif /// Per-`` accumulator state for ``_MusicXMLParser``. /// diff --git a/Sources/Lyrebird/Score/MusicXML/_PartBuilder.swift b/Sources/Lyrebird/Score/MusicXML/_PartBuilder.swift index 15a5505..67a0397 100644 --- a/Sources/Lyrebird/Score/MusicXML/_PartBuilder.swift +++ b/Sources/Lyrebird/Score/MusicXML/_PartBuilder.swift @@ -5,6 +5,9 @@ // SPDX-License-Identifier: MIT import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif /// Mutable per-part accumulator used during parsing. internal struct _PartBuilder { diff --git a/Sources/Lyrebird/Score/MusicXML/_PartEntry.swift b/Sources/Lyrebird/Score/MusicXML/_PartEntry.swift index 35d4e2d..4be03c5 100644 --- a/Sources/Lyrebird/Score/MusicXML/_PartEntry.swift +++ b/Sources/Lyrebird/Score/MusicXML/_PartEntry.swift @@ -5,6 +5,9 @@ // SPDX-License-Identifier: MIT import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif /// One parsed musical event stored with its absolute beat position and voice number. /// diff --git a/Sources/Lyrebird/Score/ScoreElementDSL.swift b/Sources/Lyrebird/Score/ScoreElementDSL.swift index d495c08..b0e57d6 100644 --- a/Sources/Lyrebird/Score/ScoreElementDSL.swift +++ b/Sources/Lyrebird/Score/ScoreElementDSL.swift @@ -385,7 +385,7 @@ public func Tuplet( noteDuration: base, children: kids ) { - fputs("[Lyrebird] warning: \(warning)\n", stderr) + lyrebirdPrintError("[Lyrebird] warning: \(warning)\n") Task { @MainActor in LyrebirdMessageCenter.shared.warning(warning, source: "Tuplet") } diff --git a/Sources/Lyrebird/Spectral/CepstralEnvelopeEstimator.swift b/Sources/Lyrebird/Spectral/CepstralEnvelopeEstimator.swift index 9e064a6..eb1f7e4 100644 --- a/Sources/Lyrebird/Spectral/CepstralEnvelopeEstimator.swift +++ b/Sources/Lyrebird/Spectral/CepstralEnvelopeEstimator.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP /// Real cepstrum-based spectral envelope estimator. /// diff --git a/Sources/Lyrebird/Spectral/SpectralBuffer.swift b/Sources/Lyrebird/Spectral/SpectralBuffer.swift index 45ce792..0953e07 100644 --- a/Sources/Lyrebird/Spectral/SpectralBuffer.swift +++ b/Sources/Lyrebird/Spectral/SpectralBuffer.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Synchronization /// A pre-allocated buffer for one FFT frame in polar (magnitude + phase) format. diff --git a/Sources/Lyrebird/Spectral/SpectralFrameBuffer.swift b/Sources/Lyrebird/Spectral/SpectralFrameBuffer.swift index a3539b5..57de1e7 100644 --- a/Sources/Lyrebird/Spectral/SpectralFrameBuffer.swift +++ b/Sources/Lyrebird/Spectral/SpectralFrameBuffer.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import Accelerate +import LyrebirdDSP import Synchronization /// Pre-allocated multi-frame polar spectral buffer for recording and replaying FFT frames. diff --git a/Sources/Lyrebird/Utilities/MonotonicClock.swift b/Sources/Lyrebird/Utilities/MonotonicClock.swift new file mode 100644 index 0000000..7a7eb45 --- /dev/null +++ b/Sources/Lyrebird/Utilities/MonotonicClock.swift @@ -0,0 +1,75 @@ +// MonotonicClock.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// Single platform-abstraction point for a monotonic tick source. Keeping the +// `#if` here lets the RT engine and the RNG seed stay platform-free. The source +// is Mach's `mach_absolute_time` on Apple (unchanged behaviour), +// `QueryPerformanceCounter` on Windows, and `clock_gettime(CLOCK_MONOTONIC)` +// elsewhere. All three are monotonic, high-resolution, allocation-free, RT-safe. + +#if canImport(Darwin) +import Darwin +#elseif canImport(WinSDK) +import WinSDK +#elseif canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#endif + +enum LyrebirdMonotonicClock { + + #if canImport(Darwin) + + /// Multiply a tick delta from ``ticks()`` by this to get nanoseconds. + static let ticksToNanos: Double = { + var info: mach_timebase_info_data_t = mach_timebase_info_data_t() + mach_timebase_info(&info) + return Double(info.numer) / Double(info.denom) + }() + + /// Monotonic tick count (Mach absolute time units). + @inline(__always) + static func ticks() -> UInt64 { + return mach_absolute_time() + } + + #elseif canImport(WinSDK) + + /// `QueryPerformanceCounter` returns ticks; scale by `1e9 / frequency` to get + /// nanoseconds (same tick+factor shape as the Apple mach path). + static let ticksToNanos: Double = { + let nanosPerSecond: Double = 1_000_000_000.0 + var frequency: LARGE_INTEGER = LARGE_INTEGER() + QueryPerformanceFrequency(&frequency) + let ticksPerSecond: Double = Double(frequency.QuadPart) + return ticksPerSecond > 0 ? nanosPerSecond / ticksPerSecond : 1.0 + }() + + /// Monotonic tick count (`QueryPerformanceCounter` units). + @inline(__always) + static func ticks() -> UInt64 { + var counter: LARGE_INTEGER = LARGE_INTEGER() + QueryPerformanceCounter(&counter) + return UInt64(counter.QuadPart) + } + + #else + + /// `ticks()` already returns nanoseconds off Apple, so the factor is 1. + static let ticksToNanos: Double = 1.0 + + /// Monotonic tick count in nanoseconds (`CLOCK_MONOTONIC`). + @inline(__always) + static func ticks() -> UInt64 { + var ts: timespec = timespec() + clock_gettime(CLOCK_MONOTONIC, &ts) + let nanosPerSecond: UInt64 = 1_000_000_000 + return UInt64(ts.tv_sec) &* nanosPerSecond &+ UInt64(ts.tv_nsec) + } + + #endif +} diff --git a/Sources/Lyrebird/Utilities/PlatformCompat.swift b/Sources/Lyrebird/Utilities/PlatformCompat.swift new file mode 100644 index 0000000..f2f8106 --- /dev/null +++ b/Sources/Lyrebird/Utilities/PlatformCompat.swift @@ -0,0 +1,17 @@ +// PlatformCompat.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// Small portable stand-ins for Apple C-API scalar types that leak into +// otherwise-portable code (error payloads, status codes). Only defined off +// Apple, where the real types (from Darwin/CoreFoundation) are unavailable. + +#if !canImport(Darwin) + +/// Mirror of Apple's `OSStatus` (a signed 32-bit result code). Used as the +/// payload of file-I/O and MIDI error cases that are shared with portable code. +public typealias OSStatus = Int32 + +#endif diff --git a/Sources/Lyrebird/Utilities/StandardError.swift b/Sources/Lyrebird/Utilities/StandardError.swift new file mode 100644 index 0000000..bba01a7 --- /dev/null +++ b/Sources/Lyrebird/Utilities/StandardError.swift @@ -0,0 +1,19 @@ +// StandardError.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Writes `message` to standard error. +/// +/// Uses `FileHandle.standardError` rather than the C `stderr` global: on Linux, +/// Swift 6 flags a direct reference to the imported `stderr` (a mutable global +/// `var`) as `reference to var 'stderr' is not concurrency-safe`. `FileHandle` +/// carries no such hazard and is identical across platforms. Not RT-safe — for +/// non-RT diagnostic output only. +@inline(__always) +func lyrebirdPrintError(_ message: String) { + try? FileHandle.standardError.write(contentsOf: Data(message.utf8)) +} diff --git a/Sources/LyrebirdC/DenormalUtils.c b/Sources/LyrebirdC/DenormalUtils.c index 9936f7f..ee99036 100644 --- a/Sources/LyrebirdC/DenormalUtils.c +++ b/Sources/LyrebirdC/DenormalUtils.c @@ -1,20 +1,55 @@ #include "LyrebirdC.h" -#include -// Apple's exposes two different "flush denormals to zero" environments: -// - arm64: FE_DFL_DISABLE_DENORMS_ENV (sets FPCR.FZ) -// - x86_64: FE_DFL_DISABLE_SSE_DENORMS_ENV (sets MXCSR.FZ + DAZ for SSE) -// Universal-binary builds compile this TU for both archs, so each must use -// the macro that exists on its target arch. Same end effect for SIMD float -// math in the RT path either way. +// Header selection is platform/arch dependent: +// - Apple: exposes the arch-specific "flush denormals" environments. +// - non-Apple x86: SSE control via the Intel intrinsics headers. +#if defined(__APPLE__) +#include +#elif defined(__x86_64__) || defined(__i386__) +#include // _MM_SET_FLUSH_ZERO_MODE (FTZ) +#include // _MM_SET_DENORMALS_ZERO_MODE (DAZ) +#endif + +// Enable flush-to-zero / denormals-are-zero for float SIMD math on the RT path. +// Denormal handling is catastrophically slow on most FPUs, so audio DSP disables +// it. The mechanism differs by platform and arch; the end effect is the same. +// +// This is thread-local state, so every thread that runs DSP has to set it: +// engine start does so for the setup thread, and each driver's render callback +// (CoreAudioDriver, iOSAudioDriver, ALSAAudioDriver) calls it on entry. It is a +// few register writes — cheap enough per callback, never per-sample. void lyrebird_enable_flush_to_zero(void) { +#if defined(__APPLE__) + // Apple's exposes two arch-specific environments: + // - arm64: FE_DFL_DISABLE_DENORMS_ENV (sets FPCR.FZ) + // - x86_64: FE_DFL_DISABLE_SSE_DENORMS_ENV (sets MXCSR.FZ + DAZ for SSE) + // Universal-binary builds compile this TU for both archs; each uses the + // macro that exists on its target arch. These macros are Darwin-only. #if defined(__arm64__) fesetenv(FE_DFL_DISABLE_DENORMS_ENV); #elif defined(__i386__) || defined(__x86_64__) fesetenv(FE_DFL_DISABLE_SSE_DENORMS_ENV); #else - // Unsupported arch — leave FPU in default IEEE-754 mode. Denormals are - // still processed but the build doesn't fail. + (void)0; +#endif +#elif defined(__x86_64__) || defined(__i386__) + // Non-Apple x86 (Linux/Windows): set SSE flush-to-zero + denormals-are-zero + // directly in MXCSR. FZ is SSE1, so it is safe on any x86 that gets here; + // DAZ needs SSE3, which is baseline on x86_64 but NOT on 32-bit x86 — a + // pre-SSE3 i386 CPU faults on the instruction, so it is gated. + _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); +#if defined(__x86_64__) || defined(__SSE3__) + _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); +#endif +#elif defined(__aarch64__) + // Non-Apple AArch64 (Linux): set FPCR.FZ (bit 24) to flush denormals to zero. + unsigned long fpcr; + __asm__ __volatile__("mrs %0, fpcr" : "=r"(fpcr)); + fpcr |= (1UL << 24); + __asm__ __volatile__("msr fpcr, %0" : : "r"(fpcr)); +#else + // Unsupported arch — leave the FPU in default IEEE-754 mode. Denormals are + // still processed correctly, just without the performance win. (void)0; #endif } diff --git a/Sources/LyrebirdC/include/LyrebirdC.h b/Sources/LyrebirdC/include/LyrebirdC.h index dafeabc..9f009d3 100644 --- a/Sources/LyrebirdC/include/LyrebirdC.h +++ b/Sources/LyrebirdC/include/LyrebirdC.h @@ -5,7 +5,9 @@ /// On ARM64, sets FPCR bit 24 (FZ — flush subnormal outputs to zero). /// On x86-64, sets MXCSR bit 15 (FZ) and bit 6 (DAZ — treat subnormal inputs as zero). /// -/// Uses `fesetenv(FE_DFL_DISABLE_DENORMS_ENV)`, the macOS-standard mechanism for disabling -/// subnormal processing. This is thread-local state; call it at the start of each audio -/// render callback to guarantee the RT thread always runs with denormals suppressed. +/// The mechanism is platform-specific: Apple uses `fesetenv` with the Darwin-only +/// `FE_DFL_DISABLE_*_DENORMS_ENV` environments; non-Apple x86 uses the SSE MXCSR +/// intrinsics; non-Apple AArch64 writes FPCR directly. This is thread-local state; +/// call it at the start of each audio render callback to guarantee the RT thread +/// always runs with denormals suppressed. void lyrebird_enable_flush_to_zero(void); diff --git a/Sources/LyrebirdCLI/InteractiveShell.swift b/Sources/LyrebirdCLI/InteractiveShell.swift index cfde498..04ffba9 100644 --- a/Sources/LyrebirdCLI/InteractiveShell.swift +++ b/Sources/LyrebirdCLI/InteractiveShell.swift @@ -172,7 +172,7 @@ public enum InteractiveShell { // Ctrl+C or Ctrl+D — clean exit. break shellLoop } catch { - fputs("lyrebird: input error: \(error)\n", stderr) + printError("lyrebird: input error: \(error)\n") break shellLoop } @@ -183,11 +183,11 @@ public enum InteractiveShell { do { try REPLLauncher.launch() } catch CLIError.swiftNotFound { - fputs("error: swift not found. Install Xcode or a Swift toolchain.\n", stderr) + printError("error: swift not found. Install Xcode or a Swift toolchain.\n") } catch CLIError.buildFailed(let code) { - fputs("error: swift build failed (exit code \(code)). REPL not started.\n", stderr) + printError("error: swift build failed (exit code \(code)). REPL not started.\n") } catch { - fputs("error: \(error)\n", stderr) + printError("error: \(error)\n") } case .new(let name, let template, let lyrebirdPath): @@ -215,7 +215,7 @@ public enum InteractiveShell { do { try ProjectRunner.run(release: release) } catch ProjectRunner.Error.swiftNotFound { - fputs("error: swift not found. Install Xcode or a Swift toolchain.\n", stderr) + printError("error: swift not found. Install Xcode or a Swift toolchain.\n") } catch ProjectRunner.Error.buildFailed(let code) { print("Build failed (exit code \(code)).") } catch { diff --git a/Sources/LyrebirdCLI/LyrebirdCLI.swift b/Sources/LyrebirdCLI/LyrebirdCLI.swift index b4b66c3..4a5c107 100644 --- a/Sources/LyrebirdCLI/LyrebirdCLI.swift +++ b/Sources/LyrebirdCLI/LyrebirdCLI.swift @@ -47,18 +47,18 @@ struct LyrebirdCLIMain { print("Open Xcode → File → New → File from Template…") print("→ scroll to the 'Lyrebird' section.") } catch TemplateInstaller.Error.destinationExists(let path) { - fputs("error: '\(path)' already exists. Pass --force to replace it.\n", stderr) + printError("error: '\(path)' already exists. Pass --force to replace it.\n") exit(1) } catch TemplateInstaller.Error.bundleMissingTemplates(let path) { - fputs("error: bundled templates not found at \(path).\n", stderr) - fputs(" This usually means the lyrebird binary was built without\n", stderr) - fputs(" its resource bundle. Rebuild with `swift build`.\n", stderr) + printError("error: bundled templates not found at \(path).\n") + printError(" This usually means the lyrebird binary was built without\n") + printError(" its resource bundle. Rebuild with `swift build`.\n") exit(1) } catch TemplateInstaller.Error.fileSystemError(let path, let reason) { - fputs("error: could not write '\(path)': \(reason)\n", stderr) + printError("error: could not write '\(path)': \(reason)\n") exit(1) } catch { - fputs("error: \(error)\n", stderr) + printError("error: \(error)\n") exit(1) } } @@ -74,10 +74,10 @@ struct LyrebirdCLIMain { print(" \(TemplateInstaller.destinationURL.path)") } } catch TemplateInstaller.Error.fileSystemError(let path, let reason) { - fputs("error: could not remove '\(path)': \(reason)\n", stderr) + printError("error: could not remove '\(path)': \(reason)\n") exit(1) } catch { - fputs("error: \(error)\n", stderr) + printError("error: \(error)\n") exit(1) } } @@ -92,13 +92,13 @@ struct LyrebirdCLIMain { do { try REPLLauncher.launch() } catch CLIError.swiftNotFound { - fputs("error: swift not found. Install Xcode or a Swift toolchain.\n", stderr) + printError("error: swift not found. Install Xcode or a Swift toolchain.\n") exit(1) } catch CLIError.buildFailed(let code) { - fputs("error: swift build failed (exit code \(code)). REPL not started.\n", stderr) + printError("error: swift build failed (exit code \(code)). REPL not started.\n") exit(code) } catch { - fputs("error: \(error)\n", stderr) + printError("error: \(error)\n") exit(1) } } @@ -121,13 +121,13 @@ struct LyrebirdCLIMain { if let path: String = effectivePath { print("Lyrebird dependency: local checkout at \(path)") } else { - fputs(""" + printError(""" warning: no local Lyrebird checkout found; pinning published \ \(ProjectScaffolder.lyrebirdPackageURL)@\(ProjectScaffolder.lyrebirdMinimumVersion). \ The generated template may use API newer than that release — if it \ fails to build, re-run with --lyrebird-path . - """, stderr) + """) } do { @@ -138,16 +138,16 @@ struct LyrebirdCLIMain { ) print("Created \(name)/") } catch ProjectScaffolder.Error.projectExists(let n) { - fputs("error: directory '\(n)' already exists.\n", stderr) + printError("error: directory '\(n)' already exists.\n") exit(1) } catch ProjectScaffolder.Error.invalidName(let n) { - fputs("error: '\(n)' is not a valid Swift module name.\n", stderr) + printError("error: '\(n)' is not a valid Swift module name.\n") exit(1) } catch ProjectScaffolder.Error.fileSystemError(let path, let reason) { - fputs("error: could not create '\(path)': \(reason)\n", stderr) + printError("error: could not create '\(path)': \(reason)\n") exit(1) } catch { - fputs("error: \(error)\n", stderr) + printError("error: \(error)\n") exit(1) } } @@ -156,12 +156,12 @@ struct LyrebirdCLIMain { do { try ProjectRunner.run(release: release) } catch ProjectRunner.Error.swiftNotFound { - fputs("error: swift not found. Install Xcode or a Swift toolchain.\n", stderr) + printError("error: swift not found. Install Xcode or a Swift toolchain.\n") exit(1) } catch ProjectRunner.Error.buildFailed(let code) { exit(code) } catch { - fputs("error: \(error)\n", stderr) + printError("error: \(error)\n") exit(1) } } @@ -176,16 +176,16 @@ struct LyrebirdCLIMain { let dest: String = path ?? SynthExporter.defaultOutputPath(for: name) print("Exported \(dest)") } catch SynthExporter.Error.invalidName(let n) { - fputs("error: '\(n)' is not a valid Swift identifier.\n", stderr) + printError("error: '\(n)' is not a valid Swift identifier.\n") exit(1) } catch SynthExporter.Error.fileExists(let p) { - fputs("error: '\(p)' already exists. Pass --overwrite to replace it.\n", stderr) + printError("error: '\(p)' already exists. Pass --overwrite to replace it.\n") exit(1) } catch SynthExporter.Error.fileSystemError(let p, let reason) { - fputs("error: could not write '\(p)': \(reason)\n", stderr) + printError("error: could not write '\(p)': \(reason)\n") exit(1) } catch { - fputs("error: \(error)\n", stderr) + printError("error: \(error)\n") exit(1) } } diff --git a/Sources/LyrebirdCLI/ProjectRunner.swift b/Sources/LyrebirdCLI/ProjectRunner.swift index 449e997..c46adca 100644 --- a/Sources/LyrebirdCLI/ProjectRunner.swift +++ b/Sources/LyrebirdCLI/ProjectRunner.swift @@ -82,19 +82,13 @@ public enum ProjectRunner { // MARK: - Helpers - /// Returns the path to the `swift` binary. + /// Returns the path to the `swift` binary, located via ``lyrebirdLocateSwift()`` + /// (searches `PATH` — honouring swiftly / Homebrew / custom toolchains — then + /// the well-known absolute locations). /// - /// Checks, in order: - /// - `/usr/bin/swift` — Xcode Command Line Tools / Xcode toolchain - /// - `/usr/local/bin/swift` — standalone toolchain (Intel Mac default) - /// - `/opt/homebrew/bin/swift` — Homebrew toolchain on Apple Silicon - /// - /// Throws `ProjectRunner.Error.swiftNotFound` if none of the candidates exist. + /// Throws `ProjectRunner.Error.swiftNotFound` if no `swift` is found. static func findSwift() throws -> String { - let candidates: [String] = ["/usr/bin/swift", "/usr/local/bin/swift", "/opt/homebrew/bin/swift"] - for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) { - return path - } - throw Error.swiftNotFound + guard let path: String = lyrebirdLocateSwift() else { throw Error.swiftNotFound } + return path } } diff --git a/Sources/LyrebirdCLI/ProjectScaffolder.swift b/Sources/LyrebirdCLI/ProjectScaffolder.swift index f26f813..5696647 100644 --- a/Sources/LyrebirdCLI/ProjectScaffolder.swift +++ b/Sources/LyrebirdCLI/ProjectScaffolder.swift @@ -14,7 +14,9 @@ public enum ProjectTemplate: String, CaseIterable, Equatable { /// `main` that plays a 440 Hz tone for ten seconds and exits. The fastest way /// to hear Lyrebird after installing the CLI. case quickstart = "quickstart" - /// Minimal engine setup with `CoreAudioDriver` and `RunLoop.main.run()`. + /// Minimal engine setup with the platform's live-audio driver + /// (`CoreAudioDriver` on Apple, `ALSAAudioDriver` on Linux) and + /// `RunLoop.main.run()`. case basic = "basic" /// Real-time demo: `SineTone` synthesizer with `@LiveParam` frequency and amplitude. case demo = "demo" @@ -474,14 +476,20 @@ public enum ProjectScaffolder { } } + // Lyrebird picks the platform's live-audio driver: Core Audio on Apple, + // ALSA on a Linux build with libasound. Where no live backend exists it + // returns an OfflineDriver, which runs the graph but makes no sound — + // `isLiveAudioAvailable` says which you got. + let driver: any AudioDriver = makeDefaultAudioDriver() + do { - // The engine owns Core Audio and runs the graph on the RT thread. + // The engine owns the audio device and runs the graph on the RT thread. let engine = SynthesisEngine( blockSize: \(scaffoldDefaultBlockSize), sampleRate: \(scaffoldDefaultSampleRate), numOutputChannels: \(scaffoldDefaultOutputChannels), numInputChannels: 0, - driver: CoreAudioDriver() + driver: driver ) try engine.start() // opens the output device @@ -506,13 +514,19 @@ public enum ProjectScaffolder { import Foundation import LyrebirdSynth + // Lyrebird picks the platform's live-audio driver: Core Audio on Apple, + // ALSA on a Linux build with libasound. Where no live backend exists it + // returns an OfflineDriver, which runs the graph but makes no sound — + // `isLiveAudioAvailable` says which you got. + let driver: any AudioDriver = makeDefaultAudioDriver() + // Configure the synthesis engine. let engine = SynthesisEngine( blockSize: \(scaffoldDefaultBlockSize), sampleRate: \(scaffoldDefaultSampleRate), numOutputChannels: \(scaffoldDefaultOutputChannels), numInputChannels: \(scaffoldDefaultInputChannels), - driver: CoreAudioDriver() + driver: driver ) // Add your Synthesizers here. @@ -551,12 +565,18 @@ public enum ProjectScaffolder { // MARK: - Main + // Lyrebird picks the platform's live-audio driver: Core Audio on Apple, + // ALSA on a Linux build with libasound. Where no live backend exists it + // returns an OfflineDriver, which runs the graph but makes no sound — + // `isLiveAudioAvailable` says which you got. + let driver: any AudioDriver = makeDefaultAudioDriver() + let engine = SynthesisEngine( blockSize: \(scaffoldDefaultBlockSize), sampleRate: \(scaffoldDefaultSampleRate), numOutputChannels: \(scaffoldDefaultOutputChannels), numInputChannels: \(scaffoldDefaultInputChannels), - driver: CoreAudioDriver() + driver: driver ) do { @@ -625,9 +645,19 @@ public enum ProjectScaffolder { } } + // Diagnostics go to stderr. Written through FileHandle rather than + // `fputs(_:stderr)` because Swift 6 rejects the imported C `stderr` + // global as not concurrency-safe on Linux. + func printError(_ message: String) { + FileHandle.standardError.write(Data(message.utf8)) + } + // MARK: - Render - let outputURL = URL(fileURLWithPath: "output.caf") + // WAV, not CAF: CAF is an Apple container, and NRTDriver throws + // `unsupportedFormatOnPlatform` for it off Apple. A scaffolded project + // should run everywhere it compiles. + let outputURL = URL(fileURLWithPath: "output.wav") let renderDuration = \(scaffoldDefaultNRTDuration) let engine = SynthesisEngine( @@ -635,14 +665,14 @@ public enum ProjectScaffolder { sampleRate: \(scaffoldDefaultSampleRate), numOutputChannels: \(scaffoldDefaultOutputChannels), numInputChannels: 0, - driver: NRTDriver(outputURL: outputURL, duration: renderDuration) + driver: NRTDriver(outputURL: outputURL, duration: renderDuration, format: .wavFloat32) ) // Add synthesizers BEFORE start() — NRTDriver renders synchronously inside start(). do { try engine.add(\(name)Synth()) } catch { - fputs("engine.add failed: \\(error)\\n", stderr) + printError("engine.add failed: \\(error)\\n") exit(1) } @@ -650,7 +680,7 @@ public enum ProjectScaffolder { try engine.start() print("Rendered \\(renderDuration)s → \\(outputURL.path)") } catch { - fputs("Render failed: \\(error)\\n", stderr) + printError("Render failed: \\(error)\\n") exit(1) } """ @@ -744,6 +774,13 @@ public enum ProjectScaffolder { } } + // Diagnostics go to stderr. Written through FileHandle rather than + // `fputs(_:stderr)` because Swift 6 rejects the imported C `stderr` + // global as not concurrency-safe on Linux. + func printError(_ message: String) { + FileHandle.standardError.write(Data(message.utf8)) + } + // MARK: - Output location // Write next to this project's source rather than the launch directory. @@ -762,7 +799,7 @@ public enum ProjectScaffolder { try xml.write(to: xmlURL, atomically: true, encoding: .utf8) print("MusicXML written → \\(xmlURL.path)") } catch { - fputs("MusicXML export failed: \\(error)\\n", stderr) + printError("MusicXML export failed: \\(error)\\n") exit(1) } @@ -771,21 +808,22 @@ public enum ProjectScaffolder { let restored = try Score.fromMusicXML(data: score.toMusicXMLData()) print("Round-trip events: \\(score.allEvents.count) → \\(restored.allEvents.count)") } catch { - fputs("MusicXML round-trip failed: \\(error)\\n", stderr) + printError("MusicXML round-trip failed: \\(error)\\n") } // MARK: - Render the score offline let tailSeconds = 1.5 let renderDuration = score.totalBeats * secondsPerBeat + tailSeconds - let outputURL = outputDir.appendingPathComponent("score.caf") + // WAV, not CAF — see the nrt template: CAF is Apple-only. + let outputURL = outputDir.appendingPathComponent("score.wav") let engine = SynthesisEngine( blockSize: \(scaffoldDefaultBlockSize), sampleRate: \(scaffoldDefaultSampleRate), numOutputChannels: \(scaffoldDefaultOutputChannels), numInputChannels: 0, - driver: NRTDriver(outputURL: outputURL, duration: renderDuration) + driver: NRTDriver(outputURL: outputURL, duration: renderDuration, format: .wavFloat32) ) // Schedule one voice per sounding event BEFORE start() — NRTDriver @@ -805,7 +843,7 @@ public enum ProjectScaffolder { try engine.schedule(voice, after: event.beat * secondsPerBeat) scheduled += 1 } catch { - fputs("engine.schedule failed: \\(error)\\n", stderr) + printError("engine.schedule failed: \\(error)\\n") } } print("Scheduled \\(scheduled) voices.") @@ -814,7 +852,7 @@ public enum ProjectScaffolder { try engine.start() print("Rendered \\(renderDuration)s → \\(outputURL.path)") } catch { - fputs("Render failed: \\(error)\\n", stderr) + printError("Render failed: \\(error)\\n") exit(1) } """ diff --git a/Sources/LyrebirdCLI/REPLLauncher.swift b/Sources/LyrebirdCLI/REPLLauncher.swift index 8721646..23adb8a 100644 --- a/Sources/LyrebirdCLI/REPLLauncher.swift +++ b/Sources/LyrebirdCLI/REPLLauncher.swift @@ -51,16 +51,13 @@ public enum REPLLauncher { .appendingPathComponent(".lyrebird_history").path } - /// Returns the path to the `swift` binary. - /// - /// Checks `/usr/bin/swift` (Xcode toolchain on macOS) and `/usr/local/bin/swift` - /// (standalone toolchain). Throws `CLIError.swiftNotFound` if neither exists. + /// Returns the path to the `swift` binary, located via ``lyrebirdLocateSwift()`` + /// (searches `PATH` — honouring swiftly / Homebrew / custom toolchains — then + /// the well-known absolute locations). Throws `CLIError.swiftNotFound` if none + /// is found. public static func findSwift() throws -> String { - let candidates: [String] = ["/usr/bin/swift", "/usr/local/bin/swift"] - for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) { - return path - } - throw CLIError.swiftNotFound + guard let path: String = lyrebirdLocateSwift() else { throw CLIError.swiftNotFound } + return path } /// Builds a `Process` that runs `swift` with the given arguments in `directory`. diff --git a/Sources/LyrebirdCLI/StandardError.swift b/Sources/LyrebirdCLI/StandardError.swift new file mode 100644 index 0000000..92a80bb --- /dev/null +++ b/Sources/LyrebirdCLI/StandardError.swift @@ -0,0 +1,18 @@ +// StandardError.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Writes `message` to standard error. +/// +/// Uses `FileHandle.standardError` rather than the C `stderr` global: on Linux, +/// Swift 6 flags a direct reference to the imported `stderr` (a mutable global +/// `var`) as `reference to var 'stderr' is not concurrency-safe`. `FileHandle` +/// carries no such hazard and is identical across platforms. +@inline(__always) +func printError(_ message: String) { + try? FileHandle.standardError.write(contentsOf: Data(message.utf8)) +} diff --git a/Sources/LyrebirdCLI/SwiftToolchain.swift b/Sources/LyrebirdCLI/SwiftToolchain.swift new file mode 100644 index 0000000..0a57261 --- /dev/null +++ b/Sources/LyrebirdCLI/SwiftToolchain.swift @@ -0,0 +1,44 @@ +// SwiftToolchain.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Locates the `swift` executable for `lyrebird run` / `lyrebird repl`. +/// +/// Searches `PATH` first, so whatever toolchain the user's shell resolves +/// `swift` to is honoured — a swiftly shim (`~/.local/share/swiftly/bin/swift`), +/// Homebrew, or a custom prefix — then falls back to the well-known absolute +/// locations for a bare environment with an empty `PATH`. Returns `nil` if no +/// `swift` executable is found anywhere. +/// +/// The hardcoded fallbacks alone were macOS-only (`/usr/bin/swift` etc.) and +/// missed every non-default Linux install, most notably swiftly. +func lyrebirdLocateSwift() -> String? { + let fileManager: FileManager = FileManager.default + let executableName: String = "swift" + + // PATH, in order — the active toolchain wins over the fallbacks below. + if let pathEnv: String = ProcessInfo.processInfo.environment["PATH"] { + let directories: [String] = pathEnv + .split(separator: ":", omittingEmptySubsequences: true) + .map(String.init) + for directory: String in directories { + let candidate: String = directory.hasSuffix("/") + ? directory + executableName + : directory + "/" + executableName + if fileManager.isExecutableFile(atPath: candidate) { + return candidate + } + } + } + + // Well-known absolute locations, for an environment with no usable PATH. + let fallbacks: [String] = ["/usr/bin/swift", "/usr/local/bin/swift", "/opt/homebrew/bin/swift"] + for path: String in fallbacks where fileManager.isExecutableFile(atPath: path) { + return path + } + return nil +} diff --git a/Sources/LyrebirdCLI/Version.swift b/Sources/LyrebirdCLI/Version.swift index 8f6d4f8..2daa155 100644 --- a/Sources/LyrebirdCLI/Version.swift +++ b/Sources/LyrebirdCLI/Version.swift @@ -5,7 +5,7 @@ // SPDX-License-Identifier: MIT /// The current Lyrebird framework and CLI version. -public let lyrebirdVersion: String = "1.0.0" +public let lyrebirdVersion: String = "2.0.0" /// The banner printed when the interactive shell or REPL session starts. public let welcomeBanner: String = """ diff --git a/Sources/LyrebirdDSP/AccelerateShim.swift b/Sources/LyrebirdDSP/AccelerateShim.swift new file mode 100644 index 0000000..17c9a4b --- /dev/null +++ b/Sources/LyrebirdDSP/AccelerateShim.swift @@ -0,0 +1,317 @@ +// AccelerateShim.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// `LyrebirdDSP` is the seam that lets the synthesis core build off Apple +// platforms. Every Lyrebird file that previously wrote `import Accelerate` +// writes `import LyrebirdDSP` instead: +// +// * On Apple, this module re-exports Accelerate wholesale +// (`@_exported import Accelerate`), so `vDSP_*` / `vv*` / FFT / biquad all +// resolve to the real, hardware-accelerated implementations. Call sites are +// byte-identical to before — there is no behavioural or performance change. +// +// * On non-Apple platforms, Accelerate does not exist. This file (plus +// `ScalarDSP.swift`, `PortableBiquad.swift`, `PortableFFT.swift`, +// `ComplexFFTCore.swift`) supplies API-compatible replacements for every +// vDSP/vForce primitive Lyrebird uses — vector ops and vForce here, the +// biquad-setup family in `PortableBiquad.swift`, and the FFT family +// (`vDSP_fft_zrip`, `vDSP_create_fftsetup`, `vDSP_ctoz`, …) in +// `PortableFFT.swift`. All are parity-tested against real vDSP on Apple in +// `Tests/LyrebirdDSPTests`. + +// Re-export the platform C library so every consumer gets scalar math +// (`sin`, `cos`, `pow`, `tanh`, `exp`, `log`, …) — and libc — through the single +// `import LyrebirdDSP`, with no per-file platform `#if`. This is the scalar-math +// counterpart to the vDSP re-export below. +#if canImport(Darwin) +@_exported import Darwin +#elseif canImport(Glibc) +@_exported import Glibc +#elseif canImport(Musl) +@_exported import Musl +#elseif canImport(ucrt) +@_exported import ucrt +#endif + +#if canImport(Accelerate) + +@_exported import Accelerate + +#else + +// (The platform C library — sin/cos/sqrt/… — is @_exported at the top of this +// file, so the scalar cores below and every consumer already have it in scope.) + +// MARK: - vDSP type shims + +public typealias vDSP_Length = UInt +public typealias vDSP_Stride = Int + +// MARK: - Double vector ops + +@inline(__always) +public func vDSP_vclrD(_ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbClear(c, ic, Int(n)) +} + +@inline(__always) +public func vDSP_vfillD(_ a: UnsafePointer, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbFill(a.pointee, c, ic, Int(n)) +} + +@inline(__always) +public func vDSP_vsmulD(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbVScalarMul(a, ia, b.pointee, c, ic, Int(n)) +} + +@inline(__always) +public func vDSP_vaddD(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ ib: vDSP_Stride, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbVAdd(a, ia, b, ib, c, ic, Int(n)) +} + +@inline(__always) +public func vDSP_vmulD(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ ib: vDSP_Stride, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbVMul(a, ia, b, ib, c, ic, Int(n)) +} + +/// `vDSP_vsubD` takes the subtrahend `b` first, then the minuend `a`; result is `a - b`. +@inline(__always) +public func vDSP_vsubD(_ b: UnsafePointer, _ ib: vDSP_Stride, _ a: UnsafePointer, _ ia: vDSP_Stride, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbVSub(a, ia, b, ib, c, ic, Int(n)) +} + +@inline(__always) +public func vDSP_vsaddD(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbVScalarAdd(a, ia, b.pointee, c, ic, Int(n)) +} + +/// `d = a * b + c` where `b` and `c` are scalars. +@inline(__always) +public func vDSP_vsmsaD(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ c: UnsafePointer, _ d: UnsafeMutablePointer, _ id: vDSP_Stride, _ n: vDSP_Length) { + _lbVScalarMulScalarAdd(a, ia, b.pointee, c.pointee, d, id, Int(n)) +} + +/// `d = a * b + c` where `b` is a scalar and `c` is a vector. +@inline(__always) +public func vDSP_vsmaD(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ c: UnsafePointer, _ ic: vDSP_Stride, _ d: UnsafeMutablePointer, _ id: vDSP_Stride, _ n: vDSP_Length) { + _lbVScalarMulVAdd(a, ia, b.pointee, c, ic, d, id, Int(n)) +} + +@inline(__always) +public func vDSP_vabsD(_ a: UnsafePointer, _ ia: vDSP_Stride, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbVAbs(a, ia, c, ic, Int(n)) +} + +@inline(__always) +public func vDSP_vsdivD(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbVScalarDiv(a, ia, b.pointee, c, ic, Int(n)) +} + +/// `vDSP_vdivD` takes the divisor `b` first, then the dividend `a`; result is `a / b`. +@inline(__always) +public func vDSP_vdivD(_ b: UnsafePointer, _ ib: vDSP_Stride, _ a: UnsafePointer, _ ia: vDSP_Stride, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbVDiv(a, ia, b, ib, c, ic, Int(n)) +} + +/// `c = a / b` where `a` is a scalar. +@inline(__always) +public func vDSP_svdivD(_ a: UnsafePointer, _ b: UnsafePointer, _ ib: vDSP_Stride, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbScalarVDiv(a.pointee, b, ib, c, ic, Int(n)) +} + +/// `c[i] = a + i * b` where `a` (start) and `b` (step) are scalars. +@inline(__always) +public func vDSP_vrampD(_ a: UnsafePointer, _ b: UnsafePointer, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbVRamp(a.pointee, b.pointee, c, ic, Int(n)) +} + +@inline(__always) +public func vDSP_maxmgvD(_ a: UnsafePointer, _ ia: vDSP_Stride, _ c: UnsafeMutablePointer, _ n: vDSP_Length) { + c.pointee = _lbMaxMagnitude(a, ia, Int(n)) +} + +@inline(__always) +public func vDSP_sveD(_ a: UnsafePointer, _ ia: vDSP_Stride, _ c: UnsafeMutablePointer, _ n: vDSP_Length) { + c.pointee = _lbSum(a, ia, Int(n)) +} + +// MARK: - Float vector ops + +@inline(__always) +public func vDSP_vclr(_ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbClear(c, ic, Int(n)) +} + +@inline(__always) +public func vDSP_vsmul(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbVScalarMul(a, ia, b.pointee, c, ic, Int(n)) +} + +@inline(__always) +public func vDSP_vadd(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ ib: vDSP_Stride, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbVAdd(a, ia, b, ib, c, ic, Int(n)) +} + +@inline(__always) +public func vDSP_vmul(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ ib: vDSP_Stride, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbVMul(a, ia, b, ib, c, ic, Int(n)) +} + +@inline(__always) +public func vDSP_vsadd(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbVScalarAdd(a, ia, b.pointee, c, ic, Int(n)) +} + +@inline(__always) +public func vDSP_vsma(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ c: UnsafePointer, _ ic: vDSP_Stride, _ d: UnsafeMutablePointer, _ id: vDSP_Stride, _ n: vDSP_Length) { + _lbVScalarMulVAdd(a, ia, b.pointee, c, ic, d, id, Int(n)) +} + +@inline(__always) +public func vDSP_vramp(_ a: UnsafePointer, _ b: UnsafePointer, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbVRamp(a.pointee, b.pointee, c, ic, Int(n)) +} + +/// `d[i] = a[i] + c * (b[i] - a[i])` where `c` is a scalar interpolation factor. +@inline(__always) +public func vDSP_vintb(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ ib: vDSP_Stride, _ c: UnsafePointer, _ d: UnsafeMutablePointer, _ id: vDSP_Stride, _ n: vDSP_Length) { + _lbVInterp(a, ia, b, ib, c.pointee, d, id, Int(n)) +} + +/// `c[i] = max(a[i], b)` where `b` is a scalar threshold (low-clamp). +@inline(__always) +public func vDSP_vthr(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbVThreshold(a, ia, b.pointee, c, ic, Int(n)) +} + +@inline(__always) +public func vDSP_dotpr(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ ib: vDSP_Stride, _ c: UnsafeMutablePointer, _ n: vDSP_Length) { + c.pointee = _lbDot(a, ia, b, ib, Int(n)) +} + +/// `output = input · (start + i·step)`; `start` is advanced past the block. +@inline(__always) +public func vDSP_vrampmul(_ input: UnsafePointer, _ iStride: vDSP_Stride, _ start: UnsafeMutablePointer, _ step: UnsafePointer, _ output: UnsafeMutablePointer, _ oStride: vDSP_Stride, _ n: vDSP_Length) { + _lbRampMul(input, iStride, start, step.pointee, output, oStride, Int(n)) +} + +/// Hann-window flags (only the standard denormalized window is used). +public let vDSP_HANN_DENORM: Int = 0 +public let vDSP_HANN_NORM: Int = 1 + +/// Fills `c` with a symmetric Hann window of length `n` (flag ignored; the +/// codebase only requests `vDSP_HANN_DENORM`). +@inline(__always) +public func vDSP_hann_window(_ c: UnsafeMutablePointer, _ n: vDSP_Length, _ flag: Int32) { + _lbHannWindow(c, Int(n)) +} + +// MARK: - Conversion & matrix + +/// Double→Float conversion. +@inline(__always) +public func vDSP_vdpsp(_ a: UnsafePointer, _ ia: vDSP_Stride, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ n: vDSP_Length) { + _lbConvertDoubleToFloat(a, ia, c, ic, Int(n)) +} + +/// Row-major matrix multiply `C[M×N] = A[M×P] · B[P×N]`. +@inline(__always) +public func vDSP_mmulD(_ a: UnsafePointer, _ ia: vDSP_Stride, _ b: UnsafePointer, _ ib: vDSP_Stride, _ c: UnsafeMutablePointer, _ ic: vDSP_Stride, _ m: vDSP_Length, _ n: vDSP_Length, _ p: vDSP_Length) { + _lbMatMul(a, ia, b, ib, c, ic, Int(m), Int(n), Int(p)) +} + +// MARK: - vForce transcendentals (n is a pointer to the Int32 element count) + +@inline(__always) +public func vvsin(_ y: UnsafeMutablePointer, _ x: UnsafePointer, _ n: UnsafePointer) { + let count: Int = Int(n.pointee) + for i: Int in 0.., _ x: UnsafePointer, _ n: UnsafePointer) { + let count: Int = Int(n.pointee) + for i: Int in 0.., _ x: UnsafePointer, _ n: UnsafePointer) { + let count: Int = Int(n.pointee) + for i: Int in 0.., _ x: UnsafePointer, _ n: UnsafePointer) { + let count: Int = Int(n.pointee) + for i: Int in 0.., _ x: UnsafePointer, _ n: UnsafePointer) { + let count: Int = Int(n.pointee) + for i: Int in 0.., _ x: UnsafePointer, _ n: UnsafePointer) { + let count: Int = Int(n.pointee) + for i: Int in 0.., _ x: UnsafePointer, _ n: UnsafePointer) { + let count: Int = Int(n.pointee) + for i: Int in 0.., _ x: UnsafePointer, _ n: UnsafePointer) { + let count: Int = Int(n.pointee) + for i: Int in 0.., _ x: UnsafePointer, _ n: UnsafePointer) { + let count: Int = Int(n.pointee) + for i: Int in 0.., _ x: UnsafePointer, _ n: UnsafePointer) { + let count: Int = Int(n.pointee) + for i: Int in 0.., _ x: UnsafePointer, _ n: UnsafePointer) { + let count: Int = Int(n.pointee) + for i: Int in 0.., _ x: UnsafePointer, _ n: UnsafePointer) { + let count: Int = Int(n.pointee) + for i: Int in 0.., _ cosOut: UnsafeMutablePointer, _ x: UnsafePointer, _ n: UnsafePointer) { + let count: Int = Int(n.pointee) + for i: Int in 0.., _ y: UnsafePointer, _ x: UnsafePointer, _ n: UnsafePointer) { + let count: Int = Int(n.pointee) + for i: Int in 0.., + _ im: UnsafeMutablePointer, + _ n: Int, + _ forward: Bool +) { + // Bit-reversal permutation. + var j: Int = 0 + for i: Int in 0..<(n - 1) { + if i < j { + let tr: Float = re[i]; re[i] = re[j]; re[j] = tr + let ti: Float = im[i]; im[i] = im[j]; im[j] = ti + } + var m: Int = n >> 1 + while m >= 1 && j >= m { j -= m; m >>= 1 } + j += m + } + + let sign: Float = forward ? -1 : 1 + var len: Int = 2 + while len <= n { + let half: Int = len >> 1 + let base: Float = sign * 2 * Float.pi / Float(len) + var group: Int = 0 + while group < n { + for k: Int in 0.., + _ imagp: UnsafeMutablePointer, + _ half: Int, + _ workRe: UnsafeMutablePointer, + _ workIm: UnsafeMutablePointer +) { + let n: Int = half * 2 + for jIdx: Int in 0.., + _ imagp: UnsafeMutablePointer, + _ half: Int, + _ workRe: UnsafeMutablePointer, + _ workIm: UnsafeMutablePointer +) { + let n: Int = half * 2 + // Rebuild the full Hermitian-symmetric spectrum from the packed half. + workRe[0] = realp[0]; workIm[0] = 0 + workRe[half] = imagp[0]; workIm[half] = 0 + for k: Int in 1.. + public var imagp: UnsafeMutablePointer + public init( + realp: UnsafeMutablePointer, + imagp: UnsafeMutablePointer + ) { + self.realp = realp + self.imagp = imagp + } +} + +#endif diff --git a/Sources/LyrebirdDSP/PortableBiquad.swift b/Sources/LyrebirdDSP/PortableBiquad.swift new file mode 100644 index 0000000..f745368 --- /dev/null +++ b/Sources/LyrebirdDSP/PortableBiquad.swift @@ -0,0 +1,75 @@ +// PortableBiquad.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// Portable stand-ins for Accelerate's opaque-setup biquad API, used off Apple +// platforms (on Apple the real vDSP is re-exported by AccelerateShim.swift). +// The setup object holds a copy of the packed coefficients; the per-block work +// delegates to the parity-tested `_lbRunBiquad` core. Only the `Double` +// (`…D`) variants are provided — the codebase uses no float biquad. + +#if !canImport(Accelerate) + +/// Opaque handle to a biquad coefficient setup, matching Accelerate's type. +public typealias vDSP_biquad_SetupD = OpaquePointer + +/// Heap-boxed coefficient store behind the opaque handle. +/// +/// Coefficients live in a raw allocation rather than a Swift `Array` because +/// the per-block path reads them on the render thread: reaching into an array +/// there would retain and release it once per block, which is exactly the ARC +/// traffic the RT rules exclude. +private final class _LBBiquadSetup { + let coeffs: UnsafeMutablePointer + let sectionCount: Int + + init(coefficients: UnsafePointer, sectionCount: Int) { + let count: Int = sectionCount * coefficientsPerSection + let storage: UnsafeMutablePointer = .allocate(capacity: count) + storage.initialize(from: coefficients, count: count) + self.coeffs = storage + self.sectionCount = sectionCount + } + + deinit { + coeffs.deinitialize(count: sectionCount * coefficientsPerSection) + coeffs.deallocate() + } +} + +/// A biquad section is `[b0, b1, b2, a1, a2]`. +private let coefficientsPerSection: Int = 5 + +/// Builds a setup from `m` sections of `[b0, b1, b2, a1, a2]` coefficients. +/// Allocates — call off the RT thread (as vDSP requires too). +public func vDSP_biquad_CreateSetupD( + _ coefficients: UnsafePointer, + _ m: vDSP_Length +) -> vDSP_biquad_SetupD? { + let box: _LBBiquadSetup = _LBBiquadSetup(coefficients: coefficients, sectionCount: Int(m)) + return vDSP_biquad_SetupD(Unmanaged.passRetained(box).toOpaque()) +} + +/// Releases a setup created by ``vDSP_biquad_CreateSetupD(_:_:)``. +public func vDSP_biquad_DestroySetupD(_ setup: vDSP_biquad_SetupD) { + Unmanaged<_LBBiquadSetup>.fromOpaque(UnsafeRawPointer(setup)).release() +} + +/// Runs the biquad cascade over `n` samples. `delays` must be caller-allocated +/// (`2 * sectionCount + 2` doubles) and zero-initialised before first use. +public func vDSP_biquadD( + _ setup: vDSP_biquad_SetupD, + _ delays: UnsafeMutablePointer, + _ input: UnsafePointer, + _ iStride: vDSP_Stride, + _ output: UnsafeMutablePointer, + _ oStride: vDSP_Stride, + _ n: vDSP_Length +) { + let box: _LBBiquadSetup = Unmanaged<_LBBiquadSetup>.fromOpaque(UnsafeRawPointer(setup)).takeUnretainedValue() + _lbRunBiquad(box.coeffs, box.sectionCount, delays, input, Int(iStride), output, Int(oStride), Int(n)) +} + +#endif diff --git a/Sources/LyrebirdDSP/PortableFFT.swift b/Sources/LyrebirdDSP/PortableFFT.swift new file mode 100644 index 0000000..904150c --- /dev/null +++ b/Sources/LyrebirdDSP/PortableFFT.swift @@ -0,0 +1,187 @@ +// PortableFFT.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// Portable stand-ins for Accelerate's single-precision real-FFT API, used off +// Apple platforms (on Apple the real vDSP is re-exported by AccelerateShim.swift). +// The FFT setup boxes pre-allocated scratch so the transform allocates nothing; +// the transform and complex-vector helpers delegate to the parity-tested cores +// in ComplexFFTCore.swift. The FFT setup is single-consumer (one per instance, +// used from one thread at a time), like Lyrebird's spectral generators use it. + +#if !canImport(Accelerate) + +// MARK: - FFT type / constant shims + +public typealias FFTSetup = OpaquePointer +public typealias FFTDirection = Int32 +public typealias FFTRadix = Int32 + +public let kFFTDirection_Forward: FFTDirection = 1 +public let kFFTDirection_Inverse: FFTDirection = -1 +public let kFFTRadix2: FFTRadix = 0 + +/// Heap-boxed FFT setup: dimensions + pre-allocated length-`n` scratch. +/// +/// The scratch is a raw allocation rather than a Swift `Array` because the +/// transform runs on the render thread, where reaching into an array would +/// retain and release it once per call — the ARC traffic the RT rules exclude. +private final class _LBFFTSetup { + /// Half the maximum transform length this setup was built for. + let half: Int + let workRe: UnsafeMutablePointer + let workIm: UnsafeMutablePointer + + init(log2n: Int) { + let n: Int = 1 << log2n + self.half = n / 2 + self.workRe = .allocate(capacity: n) + self.workIm = .allocate(capacity: n) + self.workRe.initialize(repeating: 0, count: n) + self.workIm.initialize(repeating: 0, count: n) + } + + deinit { + let n: Int = half * 2 + workRe.deinitialize(count: n) + workIm.deinitialize(count: n) + workRe.deallocate() + workIm.deallocate() + } +} + +// MARK: - FFT setup lifecycle + +/// Allocates an FFT setup for length `2^log2n`. Only `kFFTRadix2` is supported. +/// +/// A radix this implementation does not have traps rather than silently +/// producing a radix-2 transform of data that is not radix-2 — a wrong spectrum +/// is far harder to notice than a crash. +public func vDSP_create_fftsetup(_ log2n: vDSP_Length, _ radix: FFTRadix) -> FFTSetup? { + precondition( + radix == kFFTRadix2, + "PortableFFT implements radix 2 only; got radix \(radix)" + ) + let box: _LBFFTSetup = _LBFFTSetup(log2n: Int(log2n)) + return FFTSetup(Unmanaged.passRetained(box).toOpaque()) +} + +/// Releases a setup from ``vDSP_create_fftsetup(_:_:)``. +public func vDSP_destroy_fftsetup(_ setup: FFTSetup) { + Unmanaged<_LBFFTSetup>.fromOpaque(UnsafeRawPointer(setup)).release() +} + +// MARK: - Real FFT + +/// In-place packed real FFT. +/// +/// `stride` must be 1 — every Lyrebird call site passes 1, and a strided +/// transform is not implemented. Passing anything else traps instead of +/// quietly transforming the wrong samples. +public func vDSP_fft_zrip( + _ setup: FFTSetup, + _ ioData: UnsafePointer, + _ stride: vDSP_Stride, + _ log2n: vDSP_Length, + _ direction: FFTDirection +) { + precondition(stride == 1, "PortableFFT supports stride 1 only; got \(stride)") + let box: _LBFFTSetup = Unmanaged<_LBFFTSetup>.fromOpaque(UnsafeRawPointer(setup)).takeUnretainedValue() + // vDSP's contract is that one setup serves any transform *up to* its size, + // so the length comes from `log2n`, not from the setup. Only asking for + // more than the setup was built for is an error — the scratch would not + // fit. + let half: Int = (1 << Int(log2n)) / 2 + precondition( + half <= box.half, + "PortableFFT setup holds \(box.half * 2) points; got log2n \(log2n) (\(half * 2) points)" + ) + let split: DSPSplitComplex = ioData.pointee + if direction == kFFTDirection_Forward { + _lbRealFFTForward(split.realp, split.imagp, half, box.workRe, box.workIm) + } else { + _lbRealFFTInverse(split.realp, split.imagp, half, box.workRe, box.workIm) + } +} + +// MARK: - Interleaved ↔ split conversion + +/// Interleaved → split. `strideC` counts `Float`s (call sites pass 2). +public func vDSP_ctoz( + _ c: UnsafePointer, + _ strideC: vDSP_Stride, + _ z: UnsafePointer, + _ strideZ: vDSP_Stride, + _ n: vDSP_Length +) { + let split: DSPSplitComplex = z.pointee + let cf: UnsafePointer = UnsafeRawPointer(c).assumingMemoryBound(to: Float.self) + for k: Int in 0.., + _ strideZ: vDSP_Stride, + _ c: UnsafeMutablePointer, + _ strideC: vDSP_Stride, + _ n: vDSP_Length +) { + let split: DSPSplitComplex = z.pointee + let cf: UnsafeMutablePointer = UnsafeMutableRawPointer(c).assumingMemoryBound(to: Float.self) + for k: Int in 0.., + _ strideA: vDSP_Stride, + _ c: UnsafeMutablePointer, + _ strideC: vDSP_Stride, + _ n: vDSP_Length +) { + let s: DSPSplitComplex = a.pointee + for k: Int in 0.., + _ strideA: vDSP_Stride, + _ b: UnsafePointer, + _ strideB: vDSP_Stride, + _ c: UnsafePointer, + _ strideC: vDSP_Stride, + _ o: UnsafePointer, + _ strideO: vDSP_Stride, + _ n: vDSP_Length +) { + let A: DSPSplitComplex = a.pointee + let B: DSPSplitComplex = b.pointee + let C: DSPSplitComplex = c.pointee + let O: DSPSplitComplex = o.pointee + for k: Int in 0..( + _ c: UnsafeMutablePointer, + _ ic: Int, + _ n: Int +) { + var ci: Int = 0 + for _: Int in 0..( + _ scalar: T, + _ c: UnsafeMutablePointer, + _ ic: Int, + _ n: Int +) { + var ci: Int = 0 + for _: Int in 0..( + _ a: UnsafePointer, + _ ia: Int, + _ scalar: T, + _ c: UnsafeMutablePointer, + _ ic: Int, + _ n: Int +) { + var ai: Int = 0 + var ci: Int = 0 + for _: Int in 0..( + _ a: UnsafePointer, + _ ia: Int, + _ b: UnsafePointer, + _ ib: Int, + _ c: UnsafeMutablePointer, + _ ic: Int, + _ n: Int +) { + var ai: Int = 0 + var bi: Int = 0 + var ci: Int = 0 + for _: Int in 0..( + _ a: UnsafePointer, + _ ia: Int, + _ b: UnsafePointer, + _ ib: Int, + _ c: UnsafeMutablePointer, + _ ic: Int, + _ n: Int +) { + var ai: Int = 0 + var bi: Int = 0 + var ci: Int = 0 + for _: Int in 0..( + _ a: UnsafePointer, + _ ia: Int, + _ b: UnsafePointer, + _ ib: Int, + _ c: UnsafeMutablePointer, + _ ic: Int, + _ n: Int +) { + var ai: Int = 0 + var bi: Int = 0 + var ci: Int = 0 + for _: Int in 0..( + _ a: UnsafePointer, + _ ia: Int, + _ scalar: T, + _ c: UnsafeMutablePointer, + _ ic: Int, + _ n: Int +) { + var ai: Int = 0 + var ci: Int = 0 + for _: Int in 0..( + _ a: UnsafePointer, + _ ia: Int, + _ mul: T, + _ add: T, + _ d: UnsafeMutablePointer, + _ id: Int, + _ n: Int +) { + var ai: Int = 0 + var di: Int = 0 + for _: Int in 0..( + _ a: UnsafePointer, + _ ia: Int, + _ mul: T, + _ c: UnsafePointer, + _ ic: Int, + _ d: UnsafeMutablePointer, + _ id: Int, + _ n: Int +) { + var ai: Int = 0 + var ci: Int = 0 + var di: Int = 0 + for _: Int in 0..( + _ a: UnsafePointer, + _ ia: Int, + _ c: UnsafeMutablePointer, + _ ic: Int, + _ n: Int +) { + var ai: Int = 0 + var ci: Int = 0 + for _: Int in 0..( + _ a: UnsafePointer, + _ ia: Int, + _ scalar: T, + _ c: UnsafeMutablePointer, + _ ic: Int, + _ n: Int +) { + var ai: Int = 0 + var ci: Int = 0 + for _: Int in 0..( + _ a: UnsafePointer, + _ ia: Int, + _ b: UnsafePointer, + _ ib: Int, + _ c: UnsafeMutablePointer, + _ ic: Int, + _ n: Int +) { + var ai: Int = 0 + var bi: Int = 0 + var ci: Int = 0 + for _: Int in 0..( + _ scalar: T, + _ b: UnsafePointer, + _ ib: Int, + _ c: UnsafeMutablePointer, + _ ic: Int, + _ n: Int +) { + var bi: Int = 0 + var ci: Int = 0 + for _: Int in 0..( + _ start: T, + _ step: T, + _ c: UnsafeMutablePointer, + _ ic: Int, + _ n: Int +) { + var ci: Int = 0 + var value: T = start + for _: Int in 0..( + _ a: UnsafePointer, + _ ia: Int, + _ b: UnsafePointer, + _ ib: Int, + _ t: T, + _ d: UnsafeMutablePointer, + _ id: Int, + _ n: Int +) { + var ai: Int = 0 + var bi: Int = 0 + var di: Int = 0 + for _: Int in 0..( + _ a: UnsafePointer, + _ ia: Int, + _ threshold: T, + _ c: UnsafeMutablePointer, + _ ic: Int, + _ n: Int +) { + var ai: Int = 0 + var ci: Int = 0 + for _: Int in 0.. threshold ? v : threshold + ai += ia + ci += ic + } +} + +/// Returns `max(|a[i]|)` +@inline(__always) +func _lbMaxMagnitude( + _ a: UnsafePointer, + _ ia: Int, + _ n: Int +) -> T { + var ai: Int = 0 + var result: T = 0 + for _: Int in 0.. result { result = m } + ai += ia + } + return result +} + +/// Returns `sum(a[i])` +@inline(__always) +func _lbSum( + _ a: UnsafePointer, + _ ia: Int, + _ n: Int +) -> T { + var ai: Int = 0 + var result: T = 0 + for _: Int in 0..( + _ a: UnsafePointer, + _ ia: Int, + _ b: UnsafePointer, + _ ib: Int, + _ n: Int +) -> T { + var ai: Int = 0 + var bi: Int = 0 + var result: T = 0 + for _: Int in 0.., + _ iStride: Int, + _ start: UnsafeMutablePointer, + _ step: Float, + _ output: UnsafeMutablePointer, + _ oStride: Int, + _ n: Int +) { + var s: Float = start.pointee + var ii: Int = 0 + var oi: Int = 0 + for _: Int in 0.., _ n: Int) { + if n <= 0 { return } + let denom: Float = Float(n) + let twoPi: Float = 2 * Float.pi + for i: Int in 0.., + _ ia: Int, + _ c: UnsafeMutablePointer, + _ ic: Int, + _ n: Int +) { + var ai: Int = 0 + var ci: Int = 0 + for _: Int in 0.., + _ m: Int, + _ delays: UnsafeMutablePointer, + _ input: UnsafePointer, + _ iStride: Int, + _ output: UnsafeMutablePointer, + _ oStride: Int, + _ n: Int +) { + for sample: Int in 0.., + _ sa: Int, + _ b: UnsafePointer, + _ sb: Int, + _ c: UnsafeMutablePointer, + _ sc: Int, + _ m: Int, + _ n: Int, + _ p: Int +) { + for i: Int in 0.. + private let height: CGFloat + + // MARK: - State + + @State private var values: [Double] + + // Fixed per-column width (points). The Apple side fills the available width + // via GeometryReader; on Linux the Canvas needs a concrete width, so each bar + // gets a fixed column and the row is `count × columnWidth` wide. + private let columnWidth: Double = 14 + + // MARK: - Init + + /// - Parameters: + /// - buffer: Backing `LyrebirdBuffer`. Mono only. Initial values are read + /// once from `buffer[startIndex + i]` at construction. + /// - count: Number of sliders. Must be ≥ 1 and `startIndex + count <= buffer.count`. + /// - startIndex: First buffer index this view writes to. Defaults to `0`. + /// - range: Value range. Bar-top maps to `range.upperBound`, bar-bottom to + /// `range.lowerBound`. + /// - height: View height in points. Default `100`. + public init( + buffer: LyrebirdBuffer, + count: Int, + startIndex: Int = 0, + range: ClosedRange, + height: CGFloat = 100 + ) { + precondition(buffer.channelCount == 1, + "MultiSlider: buffer must be mono, got channelCount=\(buffer.channelCount)") + precondition(count >= 1, + "MultiSlider: count must be >= 1, got \(count)") + precondition(startIndex >= 0 && startIndex + count <= buffer.count, + "MultiSlider: startIndex \(startIndex) + count \(count) " + + "exceeds buffer.count \(buffer.count)") + precondition(range.lowerBound < range.upperBound, + "MultiSlider: range must be non-empty, got \(range)") + + self.buffer = buffer + self.count = count + self.startIndex = startIndex + self.range = range + self.height = height + + var initial: [Double] = [Double](repeating: range.lowerBound, count: count) + for i: Int in 0..= 0 && column < count else { return } + let hgt: Double = Double(height) + let yClamped: Double = min(max(drag.location.y, 0), hgt) + let norm: Double = 1 - (yClamped / hgt) + let span: Double = range.upperBound - range.lowerBound + let value: Double = range.lowerBound + norm * span + values[column] = value + buffer.setValue(value, at: startIndex + column) + } + ) + } +} +#endif diff --git a/Sources/LyrebirdUI/Controls/ParameterButton.swift b/Sources/LyrebirdUI/Controls/ParameterButton.swift index 143e0c5..e94fa13 100644 --- a/Sources/LyrebirdUI/Controls/ParameterButton.swift +++ b/Sources/LyrebirdUI/Controls/ParameterButton.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -101,3 +102,124 @@ public struct ParameterButton: View { } } } + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.ParameterButton`. Two styles: a +// `.momentary` button that runs a closure on press (no node), and a `.toggle` +// that flips a bound core `UIParamNode` between `offValue` and `onValue`. Uses +// SwiftOpenUI's native `Button`; no BackendGTK4 import (no Cairo drawing). +// +// SwiftOpenUI is always present in this target (see Package.swift), so no +// `canImport` guard is needed. +import SwiftOpenUI +import LyrebirdSynth + +/// A button for the Linux/GTK4 UI. Mirrors `LyrebirdUI.ParameterButton`: +/// `.momentary` runs an action on press; `.toggle` flips a bound ``UIParamNode`` +/// between `offValue` and `onValue`, highlighting when on. +public struct ParameterButton: View { + + // MARK: - Style + + public enum Style { + /// Executes the action closure on each press. + case momentary + /// Flips the node between `offValue` and `onValue` on each press. + case toggle + } + + // MARK: - Properties + + private let label: String + private let node: UIParamNode? + private let style: Style + private let action: (() -> Void)? + + /// Value representing the "off" state for `.toggle` style (default 0). + public var offValue: Double = 0.0 + /// Value representing the "on" state for `.toggle` style (default 1). + public var onValue: Double = 1.0 + + // Presentation constants. + private let labelMinWidth: Double = 60 + private let cornerRadiusPoints: Double = 6 + private let onHighlightOpacity: Double = 0.3 + private let toggleThreshold: Double = 0.5 + + // MARK: - Inits + + /// Creates a momentary button that runs `action` on press. + /// + /// - Parameters: + /// - label: Button text. + /// - action: Closure called each time the button is pressed. + public init( + _ label: String, + action: @escaping () -> Void + ) { + self.label = label + self.node = nil + self.style = .momentary + self.action = action + } + + /// Creates a toggle button bound to a `UIParamNode`. + /// + /// The node's value is interpreted as a boolean: any value ≥ 0.5 is "on". + /// + /// - Parameters: + /// - label: Button text. + /// - node: The `UIParamNode` to toggle (pass `synth.$paramName`). + /// - style: Must be `.toggle`; `.momentary` is handled by the other initializer. + public init( + _ label: String, + node: UIParamNode, + style: Style = .toggle + ) { + self.label = label + self.node = node + self.style = style + self.action = nil + } + + // MARK: - Body + + public var body: some View { + // ONE static Button node — deliberately NOT a `@ViewBuilder` if/else. + // A conditional builds a `_ConditionalView`, which the GTK4 backend's + // descriptor differ can plan as a structural replace; because the narrow + // in-place mutation path requires EVERY node in the plan to be + // narrow-applicable (`allSatisfy`), a single such node poisons the whole + // plan and forces a FULL rebuild of the window on every state change — + // tearing down in-flight drag gestures on sibling controls (knob / XY) + // and adding latency. A single static node keeps changes on the narrow + // path. The `.momentary` case simply carries `isToggledOn == false` and a + // `.clear` background; `press()` re-reads the node's value at click time + // (not captured) so a fast second click before the async rebuild still + // flips correctly. + Button(action: { press() }) { + Text(label) + .frame(minWidth: labelMinWidth) + } + .buttonStyle(.bordered) + .background(isToggledOn ? Color.cyan.opacity(onHighlightOpacity) : Color.clear) + .cornerRadius(cornerRadiusPoints) + } + + // MARK: - Private helpers + + private var isToggledOn: Bool { + guard case .toggle = style else { return false } + return (node?.value ?? 0) >= toggleThreshold + } + + private func press() { + switch style { + case .momentary: + action?() + case .toggle: + node?.update(isToggledOn ? offValue : onValue) + } + } +} +#endif diff --git a/Sources/LyrebirdUI/Controls/ParameterKnob.swift b/Sources/LyrebirdUI/Controls/ParameterKnob.swift index 80c41f7..0bfcb52 100644 --- a/Sources/LyrebirdUI/Controls/ParameterKnob.swift +++ b/Sources/LyrebirdUI/Controls/ParameterKnob.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -24,7 +25,7 @@ public struct ParameterKnob: View { private let range: ClosedRange /// Pixels of vertical drag that span the full parameter range. Default 200. - public var dragSensitivity: CGFloat = 200 + public var dragSensitivity: Double = 200 // MARK: - Private drag state @@ -110,7 +111,7 @@ public struct ParameterKnob: View { } let delta: CGFloat = dragStartPosition - gesture.location.y // up = positive let span: Double = range.upperBound - range.lowerBound - let change: Double = Double(delta / dragSensitivity) * span + let change: Double = (Double(delta) / dragSensitivity) * span let clamped: Double = min(max(dragStartValue + change, range.lowerBound), range.upperBound) node.update(clamped) } @@ -134,3 +135,119 @@ public struct ParameterKnob: View { formattedParameterValue(node.value) } } + +#else +// Experimental Linux GUI, built only under `LYREBIRD_ENABLE_LINUX_UI=1` +// (see Package.swift). This is the first control ported from `LyrebirdUI`'s +// SwiftUI `ParameterKnob` to SwiftOpenUI's GTK4 surface: a rotary knob drawn +// with the Cairo-backed `DrawingContext` (SwiftOpenUI's stand-in for SwiftUI's +// `GraphicsContext`) and a `.onDrag` vertical drag-to-set. +// +// It binds to the same core `UIParamNode` the macOS `ParameterKnob` binds to, +// so a synthesizer's `@UIParam` drives both platforms from one model. Because +// `UIParamNode` is `@Observable`, a drag-driven `node.update(_:)` takes the +// GTK4 backend's narrow mutation (redraw-in-place) path carried by the pinned +// SwiftOpenUI fork, so the in-flight drag gesture survives and the knob tracks +// continuously. +// +// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift), +// so no `canImport` guard is needed; `BackendGTK4` carries the Cairo-backed +// `DrawingContext` drawing methods (setColor/arc/moveTo/…), which are extensions +// not present in SwiftOpenUI's core. +import SwiftOpenUI +import BackendGTK4 +import LyrebirdSynth +import Foundation + +/// A rotary knob for the Linux/GTK4 UI, drawn on a `Canvas` and set by a +/// vertical drag. Binds to a core ``UIParamNode`` (via a synthesizer's +/// `@UIParam` projected value, `synth.$paramName`) — the same model the macOS +/// `ParameterKnob` uses. Mirrors that control's behaviour: −135°…+135° sweep, +/// drag-up increases. +public struct ParameterKnob: View { + private let label: String + private let node: UIParamNode + private let range: ClosedRange + + /// Pixels of vertical drag spanning the full parameter range. Matches the + /// macOS knob's default. + public var dragSensitivity: Double = 200 + + // Drag origin, captured on the first `onChanged` of each gesture. An + // explicit flag avoids a sentinel collision when the value is genuinely at + // the range's lower bound. + @State private var dragStartValue: Double = 0 + @State private var dragInProgress: Bool = false + + /// Creates a knob bound to a `UIParamNode`. + /// + /// - Parameters: + /// - label: Text displayed below the knob. + /// - node: The `UIParamNode` to bind to (pass `synth.$paramName`). + /// - range: The minimum and maximum parameter values. + public init( + _ label: String, + node: UIParamNode, + range: ClosedRange + ) { + self.label = label + self.node = node + self.range = range + } + + public var body: some View { + VStack { + Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in + let cx: Double = Double(size.width) / 2 + let cy: Double = Double(size.height) / 2 + let radius: Double = min(cx, cy) - 4 + + // Dial face ring. + ctx.setColor(r: 0.20, g: 0.20, b: 0.20) + ctx.setLineWidth(3) + ctx.arc(centerX: cx, centerY: cy, radius: radius, + startAngle: 0, endAngle: 2 * Double.pi) + ctx.stroke() + + // Indicator: −135°…+135° sweep (270° total), like the macOS knob. + let startAngleRadians: Double = 0.75 * Double.pi + let sweepRadians: Double = 1.5 * Double.pi + let angle: Double = startAngleRadians + normalise(node.value) * sweepRadians + ctx.setColor(r: 0.30, g: 0.80, b: 1.0) + ctx.setLineWidth(3) + ctx.moveTo(x: cx, y: cy) + ctx.lineTo(x: cx + radius * cos(angle), y: cy + radius * sin(angle)) + ctx.stroke() + }) + .frame(width: 50, height: 50) + .onDrag( + minimumDistance: 0, + onChanged: { (drag: DragGestureValue) in + if !dragInProgress { + dragInProgress = true + dragStartValue = node.value + } + // Up (negative height) increases, matching the macOS knob. + let span: Double = range.upperBound - range.lowerBound + let change: Double = (-drag.height / dragSensitivity) * span + let target: Double = min(range.upperBound, + max(range.lowerBound, dragStartValue + change)) + node.update(target) + }, + onEnded: { (_: DragGestureValue) in + dragInProgress = false + } + ) + Text(label) + } + .padding() + } + + private func normalise(_ value: Double) -> Double { + let lo: Double = range.lowerBound + let hi: Double = range.upperBound + guard hi > lo else { return 0 } + return min(max((value - lo) / (hi - lo), 0), 1) + } +} +#endif diff --git a/Sources/LyrebirdUI/Controls/ParameterLabel.swift b/Sources/LyrebirdUI/Controls/ParameterLabel.swift index 2209be2..66666d3 100644 --- a/Sources/LyrebirdUI/Controls/ParameterLabel.swift +++ b/Sources/LyrebirdUI/Controls/ParameterLabel.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -59,3 +60,68 @@ public struct ParameterLabel: View { String(format: "%.\(decimalPlaces)f", node.value) } } + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.ParameterLabel`: a read-only display of +// a core `UIParamNode`'s current value, updated automatically via `@Observable` +// (no polling). Uses only the core View DSL; no BackendGTK4 import. +// +// SwiftOpenUI is always present in this target (see Package.swift), so no +// `canImport` guard is needed. +import SwiftOpenUI +import LyrebirdSynth +import Foundation // String(format:) for the value readout + +/// A read-only label for the Linux/GTK4 UI that shows a ``UIParamNode``'s +/// current value. Mirrors `LyrebirdUI.ParameterLabel`: a leading descriptive +/// label and a trailing monospaced value. Refreshes automatically because +/// `UIParamNode` is `@Observable`. +public struct ParameterLabel: View { + + // MARK: - Properties + + private let label: String + private let node: UIParamNode + private let decimalPlaces: Int + + // Layout constants (points), matching the macOS label. + private let labelMinWidth: Double = 80 + private let valueMinWidth: Double = 60 + + // MARK: - Init + + /// Creates a read-only parameter label. + /// + /// - Parameters: + /// - label: Descriptive text displayed before the value. + /// - node: The `UIParamNode` to monitor (pass `synth.$paramName`). + /// - decimalPlaces: Number of decimal places shown. Default 3. + public init( + _ label: String, + node: UIParamNode, + decimalPlaces: Int = 3 + ) { + self.label = label + self.node = node + self.decimalPlaces = decimalPlaces + } + + // MARK: - Body + + public var body: some View { + HStack { + Text(label) + .frame(minWidth: labelMinWidth, alignment: .leading) + Text(formattedValue) + .monospacedDigit() + .frame(minWidth: valueMinWidth, alignment: .trailing) + } + } + + // MARK: - Formatting + + private var formattedValue: String { + String(format: "%.\(decimalPlaces)f", node.value) + } +} +#endif diff --git a/Sources/LyrebirdUI/Controls/ParameterSlider.swift b/Sources/LyrebirdUI/Controls/ParameterSlider.swift index dbf00fb..5113d1b 100644 --- a/Sources/LyrebirdUI/Controls/ParameterSlider.swift +++ b/Sources/LyrebirdUI/Controls/ParameterSlider.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -84,6 +85,8 @@ public struct ParameterSlider: View { private func toLinear(_ value: Double) -> Double { let lo: Double = range.lowerBound let hi: Double = range.upperBound + // Degenerate range: avoid a 0/0 NaN thumb position. + guard hi > lo else { return 0 } switch taper { case .linear: return (value - lo) / (hi - lo) @@ -116,3 +119,167 @@ public struct ParameterSlider: View { } } } + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.ParameterSlider`. Drawn on a `Canvas` +// with a `.onDrag` gesture — the same custom-drawn approach as +// `ParameterKnob` — rather than a native `Slider` (GtkScale). This is what +// lets a slider drag update the parameter on every motion event (like the knob +// and the macOS slider), and, crucially, lets the slider **track live** when a +// paired control bound to the same node is dragged: a Canvas closure reads +// `node.value` at paint time, so the GTK4 backend's per-drag redraw of every +// linked control repaints it in step. A native GtkScale, whose thumb position is +// pushed on rebuild (deferred during a drag), could only reconcile on release. +// +// Binds to a core `UIParamNode` (via `synth.$paramName`) with the same linear / +// exponential taper mapping the macOS slider uses. `BackendGTK4` carries the +// Cairo-backed `DrawingContext` drawing methods. +import SwiftOpenUI +import BackendGTK4 +import LyrebirdSynth +import Foundation // log/pow for the exponential taper + +/// A labelled continuous slider for the Linux/GTK4 UI, bound to a core +/// ``UIParamNode``. Mirrors `LyrebirdUI.ParameterSlider`: a leading label, a +/// horizontal Canvas-drawn track with a draggable thumb, and a trailing value +/// readout, with an optional exponential taper for ratio-based parameters +/// (frequency, time). +public struct ParameterSlider: View { + + // MARK: - Taper + + /// Value mapping applied between the slider's linear position and the + /// parameter value. + public enum Taper { + /// No mapping — slider position maps directly to parameter value. + case linear + /// Exponential mapping — equal visual steps produce equal ratios + /// (good for frequency, time). + case exponential + } + + // MARK: - Properties + + private let label: String + private let node: UIParamNode + private let range: ClosedRange + private let taper: Taper + + // Layout constants (points), matching the macOS slider's proportions. + private let labelMinWidth: Double = 80 + private let valueMinWidth: Double = 60 + /// Track dimensions. The drag maps pointer x over this fixed width, so it + /// matches the Canvas's own size (`.frame(width: trackWidth, …)`). + private let trackWidth: Double = 160 + private let trackHeight: Double = 24 + /// Thumb radius; the usable track is inset by this so the thumb stays fully + /// visible at both ends. + private let thumbRadius: Double = 7 + + // MARK: - Init + + /// Creates a slider bound to a `UIParamNode`. + /// + /// - Parameters: + /// - label: Text displayed beside the slider. + /// - node: The `UIParamNode` to bind to (pass `synth.$paramName`). + /// - range: The minimum and maximum parameter values. + /// - taper: Value mapping. Default `.linear`. + public init( + _ label: String, + node: UIParamNode, + range: ClosedRange, + taper: Taper = .linear + ) { + self.label = label + self.node = node + self.range = range + self.taper = taper + } + + // MARK: - Body + + public var body: some View { + HStack { + Text(label) + .frame(minWidth: labelMinWidth, alignment: .leading) + Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in + let w: Double = Double(size.width) + let h: Double = Double(size.height) + let cy: Double = h / 2 + let x0: Double = thumbRadius + let x1: Double = w - thumbRadius + let usable: Double = max(x1 - x0, 1) + let pos: Double = toLinear(node.value) + let thumbX: Double = x0 + pos * usable + + // Track background (full width). + ctx.setColor(r: 0.20, g: 0.20, b: 0.20) + ctx.setLineWidth(4) + ctx.moveTo(x: x0, y: cy) + ctx.lineTo(x: x1, y: cy) + ctx.stroke() + + // Filled portion up to the thumb. + ctx.setColor(r: 0.30, g: 0.80, b: 1.0) + ctx.setLineWidth(4) + ctx.moveTo(x: x0, y: cy) + ctx.lineTo(x: thumbX, y: cy) + ctx.stroke() + + // Thumb. + ctx.setColor(r: 0.90, g: 0.90, b: 0.95) + ctx.arc(centerX: thumbX, centerY: cy, radius: thumbRadius, + startAngle: 0, endAngle: 2 * Double.pi) + ctx.fill() + }) + .frame(width: trackWidth, height: trackHeight) + .onDrag( + minimumDistance: 0, + onChanged: { (drag: DragGestureValue) in + // Absolute: the thumb follows the pointer x within the track. + let x0: Double = thumbRadius + let usable: Double = max(trackWidth - 2 * thumbRadius, 1) + let pos: Double = min(1, max(0, (drag.location.x - x0) / usable)) + node.update(fromLinear(pos)) + } + ) + Text(formattedValue) + .frame(minWidth: valueMinWidth, alignment: .trailing) + .monospacedDigit() + } + } + + // MARK: - Private helpers + + private func toLinear(_ value: Double) -> Double { + let lo: Double = range.lowerBound + let hi: Double = range.upperBound + // Degenerate range: avoid a 0/0 NaN thumb position. + guard hi > lo else { return 0 } + switch taper { + case .linear: + return (value - lo) / (hi - lo) + case .exponential: + guard lo > 0, hi > lo else { return (value - lo) / (hi - lo) } + return log(value / lo) / log(hi / lo) + } + } + + private func fromLinear(_ position: Double) -> Double { + let lo: Double = range.lowerBound + let hi: Double = range.upperBound + switch taper { + case .linear: + return lo + position * (hi - lo) + case .exponential: + guard lo > 0, hi > lo else { return lo + position * (hi - lo) } + return lo * pow(hi / lo, position) + } + } + + private var formattedValue: String { + formattedParameterValue(node.value) + } +} +#endif diff --git a/Sources/LyrebirdUI/Controls/ParameterXY.swift b/Sources/LyrebirdUI/Controls/ParameterXY.swift index 434ac63..200feed 100644 --- a/Sources/LyrebirdUI/Controls/ParameterXY.swift +++ b/Sources/LyrebirdUI/Controls/ParameterXY.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -163,3 +164,148 @@ public struct ParameterXY: View { formattedParameterValue(v) } } + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.ParameterXY`: a two-dimensional pad that +// drives two core `UIParamNode`s at once. Drawn on a single `Canvas` (background, +// centre grid, cursor) with an absolute-position `.onDrag` — the touch point maps +// straight to the cursor, X left→right, Y bottom→top. +// +// Same gesture path as `ParameterKnob`: the drag calls `node.update(_:)`, +// and because `UIParamNode` is `@Observable` the Canvas redraw takes the GTK4 +// backend's narrow `.canvasContent` mutation path (the pinned fork's fix), so the +// cursor tracks continuously without the gesture being torn down by a rebuild. +// +// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift), +// so no `canImport` guard is needed; `BackendGTK4` carries the Cairo-backed +// `DrawingContext` drawing methods. +import SwiftOpenUI +import BackendGTK4 +import LyrebirdSynth +import Foundation // CGSize (Canvas renderer size) + +/// A two-axis control pad for the Linux/GTK4 UI, bound to two ``UIParamNode``s. +/// Mirrors `LyrebirdUI.ParameterXY`: drag within the pad to set X (horizontal, +/// left→right) and Y (vertical, bottom→top) independently. +public struct ParameterXY: View { + + // MARK: - Properties + + private let xLabel: String + private let xNode: UIParamNode + private let xRange: ClosedRange + + private let yLabel: String + private let yNode: UIParamNode + private let yRange: ClosedRange + + // Presentation constants (points). + private let padSize: Double = 160 + private let cursorRadius: Double = 6 + + // MARK: - Init + + /// Creates an XY pad bound to two `UIParamNode` values. + /// + /// - Parameters: + /// - xLabel: Label for the X axis. + /// - xNode: The `UIParamNode` controlled by horizontal position. + /// - xRange: Value range for the X axis. + /// - yLabel: Label for the Y axis. + /// - yNode: The `UIParamNode` controlled by vertical position. + /// - yRange: Value range for the Y axis. + public init( + xLabel: String, + xNode: UIParamNode, + xRange: ClosedRange, + yLabel: String, + yNode: UIParamNode, + yRange: ClosedRange + ) { + self.xLabel = xLabel + self.xNode = xNode + self.xRange = xRange + self.yLabel = yLabel + self.yNode = yNode + self.yRange = yRange + } + + // MARK: - Body + + public var body: some View { + VStack { + Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in + let w: Double = Double(size.width) + let h: Double = Double(size.height) + + // Background fill. + ctx.setColor(r: 0.15, g: 0.15, b: 0.15) + ctx.rectangle(x: 0, y: 0, width: w, height: h) + ctx.fill() + + // Border. + ctx.setColor(r: 0.40, g: 0.40, b: 0.40) + ctx.setLineWidth(1) + ctx.rectangle(x: 0, y: 0, width: w, height: h) + ctx.stroke() + + // Centre grid lines (faint). + let midX: Double = w / 2 + let midY: Double = h / 2 + ctx.setColor(r: 0.40, g: 0.40, b: 0.40, a: 0.4) + ctx.setLineWidth(0.5) + ctx.moveTo(x: midX, y: 0) + ctx.lineTo(x: midX, y: h) + ctx.moveTo(x: 0, y: midY) + ctx.lineTo(x: w, y: midY) + ctx.stroke() + + // Cursor: X left→right, Y bottom→top (flip vertical). + let nx: Double = normalise(xNode.value, range: xRange) + let ny: Double = 1.0 - normalise(yNode.value, range: yRange) + let cx: Double = nx * w + let cy: Double = ny * h + ctx.setColor(r: 0.30, g: 0.80, b: 1.0) + ctx.arc(centerX: cx, centerY: cy, radius: cursorRadius, + startAngle: 0, endAngle: 2 * Double.pi) + ctx.fill() + }) + .frame(width: padSize, height: padSize) + .onDrag( + minimumDistance: 0, + onChanged: { (drag: DragGestureValue) in + // Absolute position: the touch point is the cursor. + let nx: Double = min(max(drag.location.x / padSize, 0), 1) + let ny: Double = min(max(drag.location.y / padSize, 0), 1) + xNode.update(denormalise(nx, range: xRange)) + yNode.update(denormalise(1.0 - ny, range: yRange)) // flip Y + } + ) + Text("\(xLabel): \(formattedParameterValue(xNode.value))") + .monospacedDigit() + Text("\(yLabel): \(formattedParameterValue(yNode.value))") + .monospacedDigit() + } + .padding() + } + + // MARK: - Helpers + + private func normalise( + _ value: Double, + range: ClosedRange + ) -> Double { + let lo: Double = range.lowerBound + let hi: Double = range.upperBound + guard hi > lo else { return 0 } + return min(max((value - lo) / (hi - lo), 0), 1) + } + + private func denormalise( + _ position: Double, + range: ClosedRange + ) -> Double { + range.lowerBound + position * (range.upperBound - range.lowerBound) + } +} +#endif diff --git a/Sources/LyrebirdUI/Controls/PlatformColors.swift b/Sources/LyrebirdUI/Controls/PlatformColors.swift index 8cf4127..62f1698 100644 --- a/Sources/LyrebirdUI/Controls/PlatformColors.swift +++ b/Sources/LyrebirdUI/Controls/PlatformColors.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI #if os(macOS) import AppKit @@ -20,3 +21,27 @@ extension Color { public static let lyrebirdSeparator = Color(UIColor.separator) #endif } + +#else +// Linux/GTK4 counterpart to the Apple `PlatformColors`. AppKit/UIKit system +// colours have no GTK4 equivalent, so these are fixed neutral tones chosen to +// read on both light and dark GTK themes: a faint panel fill and a mid-grey +// hairline separator. `Color` here is SwiftOpenUI's, not SwiftUI's. +// +// SwiftOpenUI is always present in this target (see Package.swift). +import SwiftOpenUI + +extension Color { + // Computed (not stored) because SwiftOpenUI's `Color` is not `Sendable`, so a + // `static let` would be a non-concurrency-safe global. A computed `static var` + // rebuilds the value on each access — trivially cheap for a plain colour. + /// Subtle panel background used behind grouped controls/diagnostics views. + public static var lyrebirdControlBackground: Color { + Color(red: 0.5, green: 0.5, blue: 0.5, opacity: 0.08) + } + /// Hairline separator/stroke colour. + public static var lyrebirdSeparator: Color { + Color(red: 0.5, green: 0.5, blue: 0.5, opacity: 0.35) + } +} +#endif diff --git a/Sources/LyrebirdUI/LyrebirdEngineStatusView.swift b/Sources/LyrebirdUI/LyrebirdEngineStatusView.swift index 7c61307..5ab98b1 100644 --- a/Sources/LyrebirdUI/LyrebirdEngineStatusView.swift +++ b/Sources/LyrebirdUI/LyrebirdEngineStatusView.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -57,6 +58,11 @@ public struct LyrebirdEngineStatusView: View { public let engine: SynthesisEngine + /// Called after the user starts the engine via this panel's Start button + /// (immediately after a successful `engine.start()`). Use it to (re)add the + /// synths the host wants running — `engine.stop()` tears down non-persistent + /// nodes, so anything added earlier is gone after a stop/start cycle. + public let onEngineStarted: (() -> Void)? @State private var isRunning: Bool = false @State private var synthesizerCount: Int = 0 @State private var groupCount: Int = 0 @@ -95,9 +101,16 @@ public struct LyrebirdEngineStatusView: View { /// Creates a status view bound to the given engine. /// - /// - Parameter engine: The `SynthesisEngine` instance to monitor. - public init(engine: SynthesisEngine) { + /// - Parameters: + /// - engine: The `SynthesisEngine` instance to monitor. + /// - onEngineStarted: Optional closure run after the Start button + /// successfully starts the engine (e.g. to re-add synths). + public init( + engine: SynthesisEngine, + onEngineStarted: (() -> Void)? = nil + ) { self.engine = engine + self.onEngineStarted = onEngineStarted // Seed @State from the engine's live values so the first frame matches // the engine instead of generic defaults. Without this the Picker would // render blank when the engine's sample rate differs from the @@ -474,6 +487,7 @@ public struct LyrebirdEngineStatusView: View { do { try engine.start() lastStartError = nil + onEngineStarted?() } catch { lastStartError = "Start failed: \(error)" } @@ -599,3 +613,736 @@ extension LyrebirdEngineStatusView { } } #endif + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdEngineStatusView`: the live engine +// status panel (run state + Start/Stop, synth/group counts, CPU bars, node-tree + +// messages sections, pre-run config, master output). The 10 Hz poll moves off +// SwiftOpenUI's off-main `.task` onto a `Timer` on `RunLoop.main` inside an +// `@Observable` model. CPU bars are `Canvas`-drawn (as in `LyrebirdStatusView`) +// rather than `GeometryReader`/`ZStack`. Section chevrons become text glyphs +// (▼ / ▶). The "Open Window" buttons work here too — `LyrebirdWindow` now has a +// GTK4 body — opening the node-tree / messages panels in detached windows, in +// addition to the inline expand. +// +// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift). +import SwiftOpenUI +import BackendGTK4 +import LyrebirdSynth +import Observation +import Foundation + +/// 10 Hz engine status poll interval. +// Deliberately slower than the Apple side's 10 Hz. This view mixes a periodic +// @Observable poll with native GTK widgets (Stop button, Mute switch, expand +// buttons, volume GtkScale) AND several `if` conditionals. A conditional forces +// SwiftOpenUI's GTK4 differ off its narrow in-place path onto a full-window +// rebuild on every model tick; native-widget clicks that land mid-rebuild are +// dropped. A 2 Hz poll leaves ~500 ms of stable tree between rebuilds so clicks +// land reliably. (The proper fix is fork-side: narrow updates through +// conditionals, or isolating each polled value in its own conditional-free leaf +// child so its rebuild stays local.) +private let linuxEngineStatusPollIntervalSeconds: TimeInterval = 0.5 + +/// Polls a `SynthesisEngine`'s live state on a main-thread timer and publishes it +/// for ``LyrebirdEngineStatusView``. Internal — only the view is public. +/// +/// `@unchecked Sendable`: main-thread-confined; the `Timer` block is `@Sendable`, +/// same rationale as `LyrebirdScopeModel`. +@Observable +final class LinuxEngineStatusModel: @unchecked Sendable { + + var isRunning: Bool = false + var synthesizerCount: Int = 0 + var groupCount: Int = 0 + var averageCPU: Double = 0.0 + var peakCPU: Double = 0.0 + + var sampleRate: Double = 48000 + var numOutputChannels: Int = 2 + var numInputChannels: Int = 0 + + @ObservationIgnored private var timer: Timer? + @ObservationIgnored private let engine: SynthesisEngine + + init(engine: SynthesisEngine) { + self.engine = engine + self.isRunning = engine.isRunning + self.sampleRate = engine.sampleRate + self.numOutputChannels = engine.numOutputChannels + self.numInputChannels = engine.numInputChannels + } + + deinit { + timer?.invalidate() + } + + func start() { + guard timer == nil else { return } + refresh() + let t: Timer = Timer.scheduledTimer( + withTimeInterval: linuxEngineStatusPollIntervalSeconds, + repeats: true + ) { [weak self] _ in + self?.refresh() + } + timer = t + } + + func stop() { + timer?.invalidate() + timer = nil + } + + func refresh() { + isRunning = engine.isRunning + synthesizerCount = engine.synthesizerCount + groupCount = engine.groupCount + averageCPU = engine.averageCPU + peakCPU = engine.peakCPU + if sampleRate != engine.sampleRate { sampleRate = engine.sampleRate } + if numOutputChannels != engine.numOutputChannels { numOutputChannels = engine.numOutputChannels } + if numInputChannels != engine.numInputChannels { numInputChannels = engine.numInputChannels } + } +} + +/// A live engine status panel for the Linux/GTK4 UI. Mirrors +/// `LyrebirdUI.LyrebirdEngineStatusView`; same public API/init as the Apple side. +public struct LyrebirdEngineStatusView: View { + + public let engine: SynthesisEngine + + /// Called after the user starts the engine via this panel's Start button. + /// Use it to (re)add synths — `engine.stop()` tears down non-persistent + /// nodes, so anything added earlier is gone after a stop/start cycle. + public let onEngineStarted: (() -> Void)? + @State private var model: LinuxEngineStatusModel + + // Non-polled UI state. + @State private var lastStartError: String? + @State private var masterGainDb: Double = 0.0 + @State private var masterGainDbText: String = "+0.0" + @FocusState private var gainTextFocused: Bool + @State private var isMuted: Bool = false + @State private var lastConfigError: String? + @State private var isMessagesExpanded: Bool = false + @State private var isNodeTreeExpanded: Bool = false + // Detached windows opened by the "Open Window" buttons — now that + // `LyrebirdWindow` exists on Linux, these mirror the macOS panel. + @State private var messageWindow: LyrebirdWindow? + @State private var nodeTreeWindow: LyrebirdWindow? + + private static let sampleRateOptions: [Double] = [ + 44100, 48000, 88200, 96000, 176400, 192000 + ] + private static let outputChannelRange: ClosedRange = 1...32 + private static let inputChannelRange: ClosedRange = 0...32 + private static let gainDbRange: ClosedRange = -90.0...12.0 + /// Persistent groups always present: rootGroup + mainGroup. + private static let persistentGroupCount: Int = 2 + + // Layout constants (points). + private let dotSize: Double = 10 + + /// Creates a status view bound to the given engine. + /// + /// - Parameters: + /// - engine: The `SynthesisEngine` instance to monitor. + /// - onEngineStarted: Optional closure run after the Start button + /// successfully starts the engine (e.g. to re-add synths). + public init( + engine: SynthesisEngine, + onEngineStarted: (() -> Void)? = nil + ) { + self.engine = engine + self.onEngineStarted = onEngineStarted + _model = State(wrappedValue: LinuxEngineStatusModel(engine: engine)) + _isMuted = State(wrappedValue: engine.isMuted) + let initialDb: Double = LyrebirdEngineStatusView.linearToDb(engine.masterGain) + _masterGainDb = State(wrappedValue: initialDb) + _masterGainDbText = State(wrappedValue: String(format: "%+.1f", initialDb)) + } + + /// Linear amplitude → dB with a finite floor at the slider's lower bound. + private static func linearToDb(_ linear: Double) -> Double { + guard linear > 0, linear.isFinite else { return gainDbRange.lowerBound } + let db: Double = 20.0 * log10(linear) + return min(max(db, gainDbRange.lowerBound), gainDbRange.upperBound) + } + + /// Picker rates = standard list plus the current rate if not already present. + private var sampleRatePickerOptions: [Double] { + var rates: [Double] = LyrebirdEngineStatusView.sampleRateOptions + if !rates.contains(model.sampleRate) { + rates.append(model.sampleRate) + rates.sort() + } + return rates + } + + public var body: some View { + VStack(alignment: .leading, spacing: 10) { + HStack(spacing: 8) { + Circle() + .fill(model.isRunning ? Color.green : Color.secondary.opacity(0.4)) + .frame(width: dotSize, height: dotSize) + Text(model.isRunning ? "Running" : "Stopped") + .font(.headline) + Spacer() + // Use the `action:label:` form (not `Button(_ title:action:)`): + // the string-title form's action was not firing on GTK4 here, + // while this form — as used by the working expand buttons — does. + Button { + toggleEngine() + } label: { + Text(model.isRunning ? "Stop" : "Start") + } + } + + if let err: String = lastStartError { + Text(err) + .font(.caption) + .foregroundStyle(.red) + } + + Divider() + + HStack(spacing: 16) { + CountTile(label: "Synths", value: model.synthesizerCount) + CountTile( + label: "Groups", + value: model.groupCount + LyrebirdEngineStatusView.persistentGroupCount, + subtitle: "incl. rootGroup, mainGroup" + ) + } + + Divider() + + VStack(alignment: .leading, spacing: 6) { + CPURow(label: "CPU Avg", value: model.averageCPU) + CPURow(label: "CPU Peak", value: model.peakCPU) + } + + Divider() + + nodeTreeSection + + Divider() + + messagesSection + + Divider() + + configurationSection + + Divider() + + outputSection + } + .padding(12) + .background(Color.lyrebirdControlBackground) + .frame(minWidth: 260) + .onAppear { model.start() } + .onDisappear { model.stop() } + } + + private var configurationSection: some View { + VStack(alignment: .leading, spacing: 6) { + Text("Configuration") + .font(.caption) + .monospacedDigit() + .foregroundStyle(.secondary) + + HStack { + Text("Sample Rate") + .frame(width: 110, alignment: .leading) + Picker("", selection: Binding( + get: { model.sampleRate }, + set: { newValue in + model.sampleRate = newValue + pushConfigToEngine { try engine.setSampleRate(newValue) } + } + )) { + ForEach(sampleRatePickerOptions, id: \.self) { rate in + Text("\(Int(rate)) Hz").tag(rate) + } + } + .labelsHidden() + } + + Stepper( + "Output Channels: \(model.numOutputChannels)", + value: Binding( + get: { model.numOutputChannels }, + set: { newValue in + model.numOutputChannels = newValue + pushConfigToEngine { try engine.setNumOutputChannels(newValue) } + } + ), + in: LyrebirdEngineStatusView.outputChannelRange + ) + + Stepper( + "Input Channels: \(model.numInputChannels)", + value: Binding( + get: { model.numInputChannels }, + set: { newValue in + model.numInputChannels = newValue + pushConfigToEngine { try engine.setNumInputChannels(newValue) } + } + ), + in: LyrebirdEngineStatusView.inputChannelRange + ) + + if let err: String = lastConfigError { + Text(err) + .font(.caption) + .foregroundStyle(.red) + } + } + .disabled(model.isRunning) + .opacity(model.isRunning ? 0.5 : 1.0) + } + + /// Guard config setters so a mirror-driven change while running can't bubble a + /// spurious `engineIsRunning` error. Controls are `.disabled` while running, + /// so the only path here during a run would be the mirror. + private func pushConfigToEngine(_ apply: () throws -> Void) { + guard !model.isRunning else { return } + applyConfig(apply) + } + + private var outputSection: some View { + VStack(alignment: .leading, spacing: 6) { + Text("Output") + .font(.caption) + .monospacedDigit() + .foregroundStyle(.secondary) + + Toggle("Mute", isOn: $isMuted) + .onChange(of: isMuted) { _, newValue in + engine.isMuted = newValue + } + + HStack(spacing: 8) { + Text("Volume") + .frame(width: 60, alignment: .leading) + // Canvas-drawn, not a native GtkScale: the GtkScale drops/mis-hits + // pointer events here (drag catches outside the thumb, misses clicks). + // A Canvas + `.onDrag` maps pointer-x across a fixed track like + // `ParameterSlider`. `onChange(of: masterGainDb)` still drives the + // engine (fires for drag and for text-field commits). + LinuxValueSlider( + value: $masterGainDb, + range: LyrebirdEngineStatusView.gainDbRange, + // Applies live on every drag motion (rebuilds are deferred + // during a drag, so onChange alone would lag to mouse-up). + // Also updates the dB readout text here for the same reason. + onEditing: { db in + engine.masterGain = pow(10.0, db / 20.0) + if !gainTextFocused { + masterGainDbText = String(format: "%+.1f", db) + } + } + ) + .onChange(of: masterGainDb) { _, db in + // Handles the text-field commit path + final sync. + engine.masterGain = pow(10.0, db / 20.0) + if !gainTextFocused { + masterGainDbText = String(format: "%+.1f", db) + } + } + // The editable TextField tracks the drag live via the fork's + // narrow-mutation path (SwiftOpenUI Patch F makes the full panel — + // buttons, Picker/Stepper/Toggle, shapes, conditionals, the bound + // TextField — narrow-applicable). `onEditing` above sets the text on + // each motion; the field follows AND stays typeable. + TextField("dB", text: $masterGainDbText) + .font(.caption) + .monospacedDigit() + .multilineTextAlignment(.trailing) + .focused($gainTextFocused) + .frame(width: 70) + .textFieldStyle(.roundedBorder) + .onSubmit(commitMasterGainText) + .onChange(of: gainTextFocused) { _, focused in + if !focused { commitMasterGainText() } + } + Text("dB") + .font(.caption) + .foregroundStyle(.secondary) + } + } + } + + private func commitMasterGainText() { + var trimmed: String = masterGainDbText.trimmingCharacters(in: .whitespaces) + // Strip only a leading `+` — a blanket replace would also remove the `+` + // inside scientific notation like `1e+2`. + if trimmed.first == "+" { trimmed.removeFirst() } + if let parsed: Double = Double(trimmed) { + let range: ClosedRange = LyrebirdEngineStatusView.gainDbRange + let clamped: Double = min(max(parsed, range.lowerBound), range.upperBound) + masterGainDb = clamped // triggers slider .onChange → engine update + masterGainDbText = String(format: "%+.1f", clamped) + } else { + masterGainDbText = String(format: "%+.1f", masterGainDb) + } + } + + private func applyConfig(_ apply: () throws -> Void) { + do { + try apply() + lastConfigError = nil + } catch { + lastConfigError = "Config: \(error)" + } + } + + private var nodeTreeSection: some View { + VStack(alignment: .leading, spacing: 6) { + HStack(spacing: 8) { + Button { + isNodeTreeExpanded.toggle() + } label: { + HStack(spacing: 4) { + Text(isNodeTreeExpanded ? "▼" : "▶") + .font(.caption2) + Text("Node Tree") + .font(.caption) + .monospacedDigit() + } + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + Spacer() + // `action:label:` form — the string-title `Button` form's action + // does not fire on GTK4 here (see the Start/Stop button note). + Button { + openNodeTreeWindow() + } label: { + Text("Open Window") + .font(.caption) + } + } + + // Persistent-groups strip — always visible so the user sees at a + // glance that `rootGroup` and `mainGroup` are alive. + persistentGroupsStrip + + if isNodeTreeExpanded { + LyrebirdNodeTreeView(mirror: engine.nodeTreeMirror) + .frame(minHeight: 180, maxHeight: 300) + } + } + } + + private var persistentGroupsStrip: some View { + let snap: NodeTreeSnapshot = engine.nodeTreeMirror.snapshot + let root: NodeTreeSnapshot.Node = snap.root + let mainNode: NodeTreeSnapshot.Node? = root.children.first + let mainChildCount: Int = mainNode?.children.count ?? 0 + return HStack(spacing: 6) { + Text("▼") + .font(.caption2) + .foregroundStyle(.tertiary) + Text("rootGroup") + .font(.caption2) + .monospacedDigit() + .foregroundStyle(.secondary) + Text("(\(root.children.count))") + .font(.caption2) + .monospacedDigit() + .foregroundStyle(.tertiary) + Text("▸") + .font(.caption2) + .foregroundStyle(.tertiary) + Text("mainGroup") + .font(.caption2) + .monospacedDigit() + .foregroundStyle(.secondary) + Text("(\(mainChildCount))") + .font(.caption2) + .monospacedDigit() + .foregroundStyle(.tertiary) + Spacer() + } + .padding(.leading, 6) + } + + private var messagesSection: some View { + VStack(alignment: .leading, spacing: 6) { + HStack(spacing: 8) { + Button { + isMessagesExpanded.toggle() + } label: { + HStack(spacing: 4) { + Text(isMessagesExpanded ? "▼" : "▶") + .font(.caption2) + Text("Messages") + .font(.caption) + .monospacedDigit() + } + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + Spacer() + Button { + openMessageWindow() + } label: { + Text("Open Window") + .font(.caption) + } + } + + // `LyrebirdMessageView()` / `LyrebirdMessageBanner()` have @MainActor + // inits (they read `LyrebirdMessageCenter.shared`) and return a + // non-Sendable View, which can't cross back out of an `assumeIsolated` + // closure. Instead resolve the (Sendable) shared center on the main + // actor, then use the nonisolated `init(center:)`. + let center: LyrebirdMessageCenter = MainActor.assumeIsolated { LyrebirdMessageCenter.shared } + if isMessagesExpanded { + LyrebirdMessageView(center: center) + .frame(minHeight: 160, maxHeight: 260) + } else { + LyrebirdMessageBanner(center: center, onOpenFull: { + isMessagesExpanded = true + }) + } + } + } + + // `LyrebirdWindow` / `presentInWindow` are nonisolated on Linux (GTK-thread- + // confined), so these fire directly from the nonisolated SwiftOpenUI button + // action — no actor hop needed. + private func openNodeTreeWindow() { + if let existing: LyrebirdWindow = nodeTreeWindow { + existing.close() + nodeTreeWindow = nil + } + nodeTreeWindow = LyrebirdNodeTreeView.presentInWindow(engine: engine) + } + + private func openMessageWindow() { + if let existing: LyrebirdWindow = messageWindow { + existing.close() + messageWindow = nil + } + messageWindow = LyrebirdMessageView.presentInWindow() + } + + private func toggleEngine() { + if engine.isRunning { + engine.stop() + lastStartError = nil + } else { + do { + try engine.start() + lastStartError = nil + onEngineStarted?() + } catch { + lastStartError = "Start failed: \(error)" + } + } + model.refresh() + } +} + +// MARK: - Standalone window (Linux) + +extension LyrebirdEngineStatusView { + + /// Opens a `LyrebirdWindow` hosting an engine status view. + /// + /// Use when no parent view is available — a script or command-line demo can + /// call this to surface engine status in its own GTK window. Requires a + /// running `GtkApplication` loop. The returned `LyrebirdWindow` owns the GTK + /// window; close it with `.close()`. + /// + /// - Parameters: + /// - engine: The `SynthesisEngine` to monitor. + /// - title: Window title-bar text. Defaults to `"Engine Status"`. + /// - width: Initial window width in points. Defaults to `320`. + /// - height: Initial window height in points. Defaults to `480`. + /// - Returns: The `LyrebirdWindow` hosting the view. + @discardableResult + public static func presentInWindow( + engine: SynthesisEngine, + title: String = "Engine Status", + width: Double = 320, + height: Double = 480 + ) -> LyrebirdWindow { + let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height) + win.open { + LyrebirdEngineStatusView(engine: engine) + } + return win + } +} + +// MARK: - Sub-views + +private struct CountTile: View { + let label: String + let value: Int + let subtitle: String? + + init( + label: String, + value: Int, + subtitle: String? = nil + ) { + self.label = label + self.value = value + self.subtitle = subtitle + } + + var body: some View { + VStack(alignment: .leading, spacing: 2) { + Text(label) + .font(.caption) + .monospacedDigit() + .foregroundStyle(.secondary) + Text("\(value)") + .font(.title3) + .monospacedDigit() + .foregroundStyle(.primary) + if let sub: String = subtitle { + Text(sub) + .font(.caption2) + .monospacedDigit() + .foregroundStyle(.tertiary) + .lineLimit(1) + .truncationMode(.middle) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } +} + +/// A labelled CPU-load bar for the Linux/GTK4 UI. The bar itself is `Canvas`-drawn +/// (`DrawingContext` has no text primitive); label + percentage are real `Text`. +private struct CPURow: View { + let label: String + let value: Double + + private static let maxDisplayPercent: Double = 999.9 + private static let warningThreshold: Double = 0.5 + private static let criticalThreshold: Double = 0.8 + + private let labelWidth: Double = 60 + private let barWidth: Double = 120 + private let barHeight: Double = 6 + private let percentWidth: Double = 56 + + private var displayPercent: Double { + min(value * 100.0, CPURow.maxDisplayPercent) + } + + private var barRGB: (r: Double, g: Double, b: Double) { + if value < CPURow.warningThreshold { return (0.0, 0.8, 0.0) } // green + if value < CPURow.criticalThreshold { return (1.0, 0.8, 0.0) } // yellow + return (1.0, 0.2, 0.2) // red + } + + var body: some View { + HStack(spacing: 8) { + Text(label) + .font(.caption) + .monospacedDigit() + .foregroundStyle(.secondary) + .frame(width: labelWidth, alignment: .leading) + Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in + let w: Double = Double(size.width) + let h: Double = Double(size.height) + // Track. + ctx.setColor(r: 0.5, g: 0.5, b: 0.5, a: 0.15) + ctx.rectangle(x: 0, y: 0, width: w, height: h) + ctx.fill() + // Filled portion, clamped to the track width. + let frac: Double = min(max(value, 0.0), 1.0) + let rgb: (r: Double, g: Double, b: Double) = barRGB + ctx.setColor(r: rgb.r, g: rgb.g, b: rgb.b) + ctx.rectangle(x: 0, y: 0, width: w * frac, height: h) + ctx.fill() + }) + .frame(width: barWidth, height: barHeight) + Text(String(format: "%.1f%%", displayPercent)) + .font(.caption) + .monospacedDigit() + .foregroundStyle(.primary) + .frame(width: percentWidth, alignment: .trailing) + } + } +} + +/// A Canvas-drawn horizontal slider bound to a `Binding` for the +/// Linux/GTK4 UI. Used instead of the native `Slider` (GtkScale), whose pointer +/// hit-testing is unreliable here (drag catches outside the thumb, misses +/// clicks). Same drawing/drag approach as `ParameterSlider`, but over a plain +/// `Binding` + range (linear) rather than a `UIParamNode`. +private struct LinuxValueSlider: View { + @Binding var value: Double + let range: ClosedRange + /// Fired directly on every drag motion with the new value. The fork defers + /// host rebuilds during a drag, so an `onChange(of:)` observer would not see + /// intermediate values until mouse-up; this callback applies the live effect + /// (e.g. the engine gain) on each motion, exactly as the Canvas knobs write + /// their node in the drag handler. + var onEditing: ((Double) -> Void)? = nil + + private let trackWidth: Double = 240 + private let trackHeight: Double = 24 + private let thumbRadius: Double = 7 + + var body: some View { + Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in + let w: Double = Double(size.width) + let h: Double = Double(size.height) + let cy: Double = h / 2 + let x0: Double = thumbRadius + let x1: Double = w - thumbRadius + let usable: Double = max(x1 - x0, 1) + let span: Double = range.upperBound - range.lowerBound + let pos: Double = span > 0 ? (value - range.lowerBound) / span : 0 + let clampedPos: Double = min(1, max(0, pos)) + let thumbX: Double = x0 + clampedPos * usable + + // Track background. + ctx.setColor(r: 0.20, g: 0.20, b: 0.20) + ctx.setLineWidth(4) + ctx.moveTo(x: x0, y: cy) + ctx.lineTo(x: x1, y: cy) + ctx.stroke() + + // Filled portion up to the thumb. + ctx.setColor(r: 0.30, g: 0.80, b: 1.0) + ctx.setLineWidth(4) + ctx.moveTo(x: x0, y: cy) + ctx.lineTo(x: thumbX, y: cy) + ctx.stroke() + + // Thumb. + ctx.setColor(r: 0.90, g: 0.90, b: 0.95) + ctx.arc(centerX: thumbX, centerY: cy, radius: thumbRadius, + startAngle: 0, endAngle: 2 * Double.pi) + ctx.fill() + }) + .frame(width: trackWidth, height: trackHeight) + .onDrag( + minimumDistance: 0, + onChanged: { (drag: DragGestureValue) in + let x0: Double = thumbRadius + let usable: Double = max(trackWidth - 2 * thumbRadius, 1) + let pos: Double = min(1, max(0, (drag.location.x - x0) / usable)) + let span: Double = range.upperBound - range.lowerBound + let newValue: Double = range.lowerBound + pos * span + value = newValue + onEditing?(newValue) + } + ) + } +} + + +#endif diff --git a/Sources/LyrebirdUI/LyrebirdEnvelopeView.swift b/Sources/LyrebirdUI/LyrebirdEnvelopeView.swift index 114ae71..f4c3fa8 100644 --- a/Sources/LyrebirdUI/LyrebirdEnvelopeView.swift +++ b/Sources/LyrebirdUI/LyrebirdEnvelopeView.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -100,8 +101,8 @@ func _envelopeYBounds(levels: [Double]) -> (yMin: Double, yMax: Double) { public struct LyrebirdEnvelopeView: View { private let envelope: Envelope - private let width: CGFloat - private let height: CGFloat + private let width: Double + private let height: Double private static let backgroundBrightness: CGFloat = 0.08 private static let backgroundColor: Color = Color(white: backgroundBrightness) @@ -121,8 +122,8 @@ public struct LyrebirdEnvelopeView: View { public init( _ envelope: Envelope, - width: CGFloat = 300, - height: CGFloat = 120 + width: Double = 300, + height: Double = 120 ) { self.envelope = envelope self.width = width @@ -257,3 +258,253 @@ public struct LyrebirdEnvelopeView: View { return height * (1.0 - CGFloat(t)) } } + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdEnvelopeView`: plots a core +// `Envelope` as a colour-coded shape on a single `Canvas`. Static — it draws a +// fixed spec once, no timer or polling. +// +// Divergence from macOS: `DrawingContext` has no text drawing, so the "L"/"R" +// letters beside the loop/release markers are omitted. The dashed marker line +// still shows each boundary, colour-coded green (loop) / orange (release) to +// match the segment colours. +// +// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift). +import SwiftOpenUI +import BackendGTK4 +import LyrebirdSynth +import Foundation + +// MARK: - Region + +/// Render region for one envelope segment. +enum _LinuxEnvelopeRegion { + case preLoop + case loop + case release + + /// Trace colour as an RGB triple for `DrawingContext.setColor`. + var rgb: (r: Double, g: Double, b: Double) { + switch self { + case .preLoop: return (0.0, 0.8, 1.0) // cyan + case .loop: return (0.0, 0.8, 0.0) // green + case .release: return (1.0, 0.53, 0.0) // orange + } + } +} + +// MARK: - Pure helpers + +/// Returns the render region for a single segment index given loopNode/releaseNode. +/// +/// Loop-only semantics (loopNode set, releaseNode nil): only the segment *at* loopNode +/// is coloured `.loop`. Segments after it are the gate-off release path — they play once +/// after gate drops and are correctly classified as `.preLoop`. +func _linuxRegionForSegment( + index: Int, + loopNode: Int?, + releaseNode: Int? +) -> _LinuxEnvelopeRegion { + switch (loopNode, releaseNode) { + case (let ln?, let rn?): + if index < ln { return .preLoop } + if index < rn { return .loop } + return .release + case (let ln?, nil): + return index == ln ? .loop : .preLoop + case (nil, let rn?): + return index < rn ? .preLoop : .release + case (nil, nil): + return .preLoop + } +} + +/// Returns cumulative boundary times: `[0, d0, d0+d1, …, totalDuration]`. +/// Length is `durations.count + 1`. +func _linuxSegmentBoundaryTimes(durations: [Double]) -> [Double] { + var times: [Double] = [0] + var elapsed: Double = 0 + for d: Double in durations { + elapsed += d + times.append(elapsed) + } + return times +} + +/// Returns Y display bounds for `levels` with 10 % headroom on each side. +/// Returns `(0, 1)` when `levels` is empty. +func _linuxEnvelopeYBounds(levels: [Double]) -> (yMin: Double, yMax: Double) { + let minimumLevelRange: Double = 1e-6 + let headroomFactor: Double = 0.1 + guard let lo: Double = levels.min(), let hi: Double = levels.max() else { return (0, 1) } + let range: Double = max(hi - lo, minimumLevelRange) + let headroom: Double = range * headroomFactor + return (lo - headroom, hi + headroom) +} + +// MARK: - LyrebirdEnvelopeView + +/// Plots an `Envelope` as a colour-coded shape for the Linux/GTK4 UI. Segments +/// are cyan before any loop/release, green in the loop region, orange in the +/// release region; horizontal hairlines mark segment levels; dashed vertical +/// lines mark the loop (green) and release (orange) boundaries. +public struct LyrebirdEnvelopeView: View { + + private let envelope: Envelope + private let width: Double + private let height: Double + + // Presentation constants. + private let cornerRadius: Double = 4 + /// Path points per canvas pixel — smooth enough for all curve shapes. + private let oversample: Double = 2 + private let signalLineWidth: Double = 1.5 + private let guideLineWidth: Double = 0.5 + private let markerLineWidth: Double = 1 + private let markerOpacity: Double = 0.7 + private let levelTickOpacity: Double = 0.2 + private let markerDash: [CGFloat] = [4, 3] + + /// Creates an envelope plot. + /// + /// - Parameters: + /// - envelope: The `Envelope` to plot. + /// - width: Canvas width in points. Default 300. + /// - height: Canvas height in points. Default 120. + public init( + _ envelope: Envelope, + width: Double = 300, + height: Double = 120 + ) { + self.envelope = envelope + self.width = width + self.height = height + } + + public var body: some View { + Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in + draw(ctx: ctx, size: size) + }) + .frame(width: width, height: height) + .clipShape(RoundedRectangle(cornerRadius: cornerRadius)) + } + + // MARK: - Drawing + + private func draw(ctx: DrawingContext, size: CGSize) { + let w: Double = Double(size.width) + let h: Double = Double(size.height) + + // Background. + ctx.setColor(r: 0.08, g: 0.08, b: 0.08) + ctx.rectangle(x: 0, y: 0, width: w, height: h) + ctx.fill() + + let bounds: (yMin: Double, yMax: Double) = _linuxEnvelopeYBounds(levels: envelope.levels) + let segCount: Int = envelope.segmentCount + + // Degenerate: no segments or zero duration → flat line at the first level. + guard segCount > 0 && envelope.totalDuration > 0 else { + let v: Double = envelope.levels.first ?? 0 + let y: Double = yFor(v, bounds: bounds, height: h) + ctx.setColor(r: 0.0, g: 0.8, b: 1.0) + ctx.setLineWidth(signalLineWidth) + ctx.moveTo(x: 0, y: y) + ctx.lineTo(x: w, y: y) + ctx.stroke() + return + } + + let boundaryTimes: [Double] = _linuxSegmentBoundaryTimes(durations: envelope.durations) + let totalSamples: Int = Int(ceil(w * oversample)) + + // Horizontal level hairlines. + ctx.setColor(r: 1.0, g: 1.0, b: 1.0, a: levelTickOpacity) + ctx.setLineWidth(guideLineWidth) + for level: Double in envelope.levels { + let y: Double = yFor(level, bounds: bounds, height: h) + ctx.moveTo(x: 0, y: y) + ctx.lineTo(x: w, y: y) + } + ctx.stroke() + + // One coloured polyline per segment. + for seg: Int in 0.. Double { + (t / envelope.totalDuration) * w + } + + private func yFor( + _ v: Double, + bounds: (yMin: Double, yMax: Double), + height h: Double + ) -> Double { + let t: Double = (v - bounds.yMin) / (bounds.yMax - bounds.yMin) + return h * (1.0 - t) + } +} +#endif diff --git a/Sources/LyrebirdUI/LyrebirdEventListPerformanceView.swift b/Sources/LyrebirdUI/LyrebirdEventListPerformanceView.swift index edd9583..a1b11dc 100644 --- a/Sources/LyrebirdUI/LyrebirdEventListPerformanceView.swift +++ b/Sources/LyrebirdUI/LyrebirdEventListPerformanceView.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -163,3 +164,180 @@ extension LyrebirdEventListPerformanceView { } } #endif + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdEventListPerformanceView`: a +// ``LyrebirdEventListView`` on top plus a live stack of ``LyrebirdProcessView`` +// strips, one per running process. The 10 Hz membership poll moves off +// SwiftOpenUI's off-main `.task` onto a `Timer` on `RunLoop.main` inside an +// `@Observable` model, keeping the identity-stable reassignment so child strips +// keep their own timers/state across ticks. +// +// SwiftOpenUI is always present in this target (see Package.swift). +import SwiftOpenUI +import LyrebirdSynth +import Observation +import Foundation + +/// 10 Hz — matches ``LyrebirdProcessView`` / ``LyrebirdEventListView``. +private let linuxEventListPerformancePollIntervalSeconds: TimeInterval = 0.1 + +/// Polls an event list's running processes on a main-thread timer and publishes +/// an identity-stable snapshot for ``LyrebirdEventListPerformanceView``. Internal. +/// +/// `@unchecked Sendable`: main-thread-confined; the `Timer` block is `@Sendable`, +/// same rationale as `LyrebirdScopeModel`. +@Observable +final class LinuxEventListPerformanceModel: @unchecked Sendable { + + var runningProcesses: [LyrebirdProcess] = [] + + @ObservationIgnored private var timer: Timer? + @ObservationIgnored private let eventList: LyrebirdEventList + + init(eventList: LyrebirdEventList) { + self.eventList = eventList + } + + deinit { + timer?.invalidate() + } + + func start() { + guard timer == nil else { return } + refresh() + let t: Timer = Timer.scheduledTimer( + withTimeInterval: linuxEventListPerformancePollIntervalSeconds, + repeats: true + ) { [weak self] _ in + self?.refresh() + } + timer = t + } + + func stop() { + timer?.invalidate() + timer = nil + } + + func refresh() { + let snapshot: [LyrebirdProcess] = eventList.allProcesses.filter { $0.isRunning } + if !snapshot.elementsEqualByIdentity(to: runningProcesses) { + runningProcesses = snapshot + } + } +} + +/// A composite event-list performance view for the Linux/GTK4 UI. Mirrors +/// `LyrebirdUI.LyrebirdEventListPerformanceView`; same public API/init as the +/// Apple side. +public struct LyrebirdEventListPerformanceView: View { + + public let eventList: LyrebirdEventList + public let engine: SynthesisEngine + + @State private var model: LinuxEventListPerformanceModel + + /// Creates a performance view bound to the given event list. + /// + /// - Parameters: + /// - eventList: The `LyrebirdEventList` to drive. + /// - engine: The `SynthesisEngine` that hosts both the list and any ad-hoc + /// `Start` actions on individual process strips. + public init( + eventList: LyrebirdEventList, + engine: SynthesisEngine + ) { + self.eventList = eventList + self.engine = engine + _model = State(wrappedValue: LinuxEventListPerformanceModel(eventList: eventList)) + } + + public var body: some View { + VStack(alignment: .leading, spacing: 12) { + LyrebirdEventListView(eventList: eventList) + + Divider() + + if model.runningProcesses.isEmpty { + emptyState + } else { + ScrollView { + VStack(alignment: .leading, spacing: 8) { + ForEach(model.runningProcesses, id: \.identityKey) { proc in + LyrebirdProcessView(process: proc, engine: engine) + } + } + } + } + } + .padding(12) + .background(Color.lyrebirdControlBackground) + .frame(minWidth: 360, minHeight: 320) + .onAppear { model.start() } + .onDisappear { model.stop() } + } + + private var emptyState: some View { + VStack(alignment: .leading, spacing: 4) { + Text("No processes running") + .font(.caption) + .foregroundStyle(.secondary) + Text("Press Next to fire the queued event.") + .font(.caption2) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, alignment: .leading) + } +} + +// MARK: - Stable identity for ForEach + +private extension LyrebirdProcess { + /// `ObjectIdentifier`-based key used for `ForEach` so processes with + /// duplicate user-supplied `id` strings still render distinct views. + var identityKey: ObjectIdentifier { ObjectIdentifier(self) } +} + +private extension Array where Element == LyrebirdProcess { + func elementsEqualByIdentity(to other: [LyrebirdProcess]) -> Bool { + guard count == other.count else { return false } + for (a, b) in zip(self, other) where a !== b { return false } + return true + } +} + +// MARK: - Standalone window (Linux) + +extension LyrebirdEventListPerformanceView { + + /// Opens a `LyrebirdWindow` hosting an event-list performance view. Requires + /// a running `GtkApplication` loop. + /// + /// - Parameters: + /// - eventList: The `LyrebirdEventList` to drive. + /// - engine: The `SynthesisEngine` for individual process Start actions. + /// - title: Window title-bar text. Defaults to the event list ID. + /// - width: Initial window width in points. Defaults to `420`. + /// - height: Initial window height in points. Defaults to `520`. + /// - Returns: The `LyrebirdWindow` hosting the view. + @discardableResult + public static func presentInWindow( + eventList: LyrebirdEventList, + engine: SynthesisEngine, + title: String? = nil, + width: Double = 420, + height: Double = 520 + ) -> LyrebirdWindow { + let win: LyrebirdWindow = LyrebirdWindow( + title: title ?? eventList.id, + width: width, + height: height + ) + win.open { + LyrebirdEventListPerformanceView(eventList: eventList, engine: engine) + } + return win + } +} +#endif diff --git a/Sources/LyrebirdUI/LyrebirdEventListView.swift b/Sources/LyrebirdUI/LyrebirdEventListView.swift index 211fb3d..b586e7d 100644 --- a/Sources/LyrebirdUI/LyrebirdEventListView.swift +++ b/Sources/LyrebirdUI/LyrebirdEventListView.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -331,3 +332,359 @@ extension LyrebirdEventListView { } } #endif + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdEventListView`: transport for a +// `LyrebirdEventList` (state dot + id, now/next event rows, dB amp slider, +// Next/Back/Skip, Set Next, Reset/Release All/Kill All). The 10 Hz poll moves off +// SwiftOpenUI's off-main `.task` onto a `Timer` on `RunLoop.main` inside an +// `@Observable` model, which also carries the transport-derived UI flags. The +// text field for "Set Next" stays plain `@State` on the view. dB↔amp maths reuse +// the cross-platform `DbSliderConversion`; the amp control is a native `Slider`. +// +// SwiftOpenUI is always present in this target (see Package.swift). +import SwiftOpenUI +import LyrebirdSynth +import Observation +import Foundation + +/// 10 Hz event-list poll interval. +private let linuxEventListPollIntervalSeconds: TimeInterval = 0.1 + +/// Polls a `LyrebirdEventList`'s transport state on a main-thread timer and +/// publishes it for ``LyrebirdEventListView``. Internal — only the view is public. +/// +/// `@unchecked Sendable`: main-thread-confined; the `Timer` block is `@Sendable`, +/// same rationale as `LyrebirdScopeModel`. +@Observable +final class LinuxEventListModel: @unchecked Sendable { + + var isRunning: Bool = false + var currentEvent: Int? = nil + var nextEvent: Int? = nil + var playIndex: Int = 0 + var amp: Double = 1.0 + var hasBeenStopped: Bool = false + + @ObservationIgnored let eventList: LyrebirdEventList + @ObservationIgnored private var timer: Timer? + + init(eventList: LyrebirdEventList) { + self.eventList = eventList + // `amp` is @MainActor; construction happens on the GTK main thread. + self.amp = MainActor.assumeIsolated { eventList.amp } + } + + deinit { + timer?.invalidate() + } + + func start() { + guard timer == nil else { return } + refresh() + let t: Timer = Timer.scheduledTimer( + withTimeInterval: linuxEventListPollIntervalSeconds, + repeats: true + ) { [weak self] _ in + self?.refresh() + } + timer = t + } + + func stop() { + timer?.invalidate() + timer = nil + } + + // Runs on the GTK main thread (view init / onAppear / RunLoop.main timer), so + // `assumeIsolated` reaches the @MainActor `amp` safely. The other members are + // nonisolated already. + func refresh() { + isRunning = eventList.isRunning + currentEvent = eventList.currentEvent + nextEvent = eventList.nextEvent + playIndex = eventList.index + amp = MainActor.assumeIsolated { eventList.amp } + if !isRunning && currentEvent != nil { + hasBeenStopped = true + } + } +} + +/// A control panel for driving a `LyrebirdEventList` on the Linux/GTK4 UI. +/// Mirrors `LyrebirdUI.LyrebirdEventListView`; same public API/init as the Apple +/// side. +public struct LyrebirdEventListView: View { + + public let eventList: LyrebirdEventList + + @State private var model: LinuxEventListModel + @State private var setNextField: String = "" + + // Layout constants (points). + private let dotSize: Double = 10 + private let ampLabelWidth: Double = 36 + private let dbReadoutWidth: Double = 56 + private let setNextFieldWidth: Double = 80 + private let disabledDotOpacity: Double = 0.4 + + /// Creates an event-list control view bound to the given list. + /// + /// - Parameter eventList: The `LyrebirdEventList` to control. + public init(eventList: LyrebirdEventList) { + self.eventList = eventList + _model = State(wrappedValue: LinuxEventListModel(eventList: eventList)) + } + + public var body: some View { + VStack(alignment: .leading, spacing: 12) { + header + Divider() + currentNextRows + Divider() + ampRow + Divider() + transportRow + setNextRow + stopRow + } + .padding(12) + .background(Color.lyrebirdControlBackground) + .frame(minWidth: 320) + .onAppear { model.start() } + .onDisappear { model.stop() } + } + + // MARK: - Sub-rows + + private var header: some View { + HStack(spacing: 8) { + Circle() + .fill(model.isRunning ? Color.green : Color.secondary.opacity(disabledDotOpacity)) + .frame(width: dotSize, height: dotSize) + Text(eventList.id) + .font(.headline) + Spacer() + Text("\(eventList.eventCount) events") + .font(.caption) + .monospacedDigit() + .foregroundStyle(.secondary) + } + } + + private var currentNextRows: some View { + VStack(alignment: .leading, spacing: 6) { + EventRow( + label: "Now", + index: model.currentEvent, + description: descriptionForEvent(at: model.currentEvent) + ) + EventRow( + label: "Next", + index: model.nextEvent, + description: descriptionForEvent(at: model.nextEvent) + ) + } + } + + private var ampRow: some View { + HStack(spacing: 8) { + Text("Amp") + .font(.caption) + .monospacedDigit() + .foregroundStyle(.secondary) + .frame(width: ampLabelWidth, alignment: .leading) + Slider(value: Binding( + get: { dbFromAmp(model.amp) }, + set: { newDb in + let newAmp: Double = ampFromDb(newDb) + model.amp = newAmp + // Bind `eventList` (Sendable) to a local so the @MainActor + // closure captures it, not `self` (the non-Sendable View). + let el: LyrebirdEventList = eventList + MainActor.assumeIsolated { el.amp = newAmp } + } + ), in: LyrebirdEventListView.minDb ... LyrebirdEventListView.maxDb) + Text(dbDisplay(dbFromAmp(model.amp))) + .font(.caption) + .monospacedDigit() + .foregroundStyle(.primary) + .frame(width: dbReadoutWidth, alignment: .trailing) + } + } + + // MARK: - dB <-> linear amplitude (shared via `DbSliderConversion`) + + private static let minDb: Double = DbSliderConversion.minDb + private static let maxDb: Double = DbSliderConversion.maxDb + + private func ampFromDb(_ db: Double) -> Double { DbSliderConversion.ampFromDb(db) } + private func dbFromAmp(_ amp: Double) -> Double { DbSliderConversion.dbFromAmp(amp) } + private func dbDisplay(_ db: Double) -> String { DbSliderConversion.dbDisplay(db) } + + private var transportRow: some View { + HStack(spacing: 8) { + Button("Next") { + let el: LyrebirdEventList = eventList + MainActor.assumeIsolated { el.next() } + } + .disabled(model.nextEvent == nil) + + Spacer() + + Button("Back") { + let cur: Int = eventList.index + guard cur > 0 else { return } + eventList.index = cur - 1 + model.refresh() + } + .disabled(model.playIndex <= 0) + Button("Skip") { + let cur: Int = eventList.index + guard cur < eventList.eventCount else { return } + eventList.index = cur + 1 + model.refresh() + } + .disabled(model.nextEvent == nil) + } + } + + private var setNextRow: some View { + HStack(spacing: 8) { + Text("Set Next") + .font(.caption) + .monospacedDigit() + .foregroundStyle(.secondary) + TextField("index", text: $setNextField) + .frame(maxWidth: setNextFieldWidth) + .textFieldStyle(.roundedBorder) + Button("Apply") { + applySetNext() + } + .disabled(parsedSetNext() == nil) + Spacer() + } + } + + private var stopRow: some View { + HStack(spacing: 8) { + Button("Reset") { + let el: LyrebirdEventList = eventList + MainActor.assumeIsolated { el.reset() } + model.hasBeenStopped = false + model.refresh() + } + .disabled(!model.hasBeenStopped) + + Spacer() + + Button("Release All") { + let el: LyrebirdEventList = eventList + MainActor.assumeIsolated { el.releaseAll() } + model.hasBeenStopped = true + model.refresh() + } + .disabled(!model.isRunning || model.hasBeenStopped) + + Button("Kill All") { + let el: LyrebirdEventList = eventList + MainActor.assumeIsolated { el.killAll() } + model.hasBeenStopped = true + model.refresh() + } + .disabled(!model.isRunning || model.hasBeenStopped) + } + } + + // MARK: - Helpers + + private func descriptionForEvent(at index: Int?) -> String { + guard let i: Int = index, i >= 0, i < eventList.eventCount else { return "—" } + let event: LyrebirdEvent = eventList.events[i] + let startIDs: [String] = event.starts.map(\.id) + let releaseIDs: [String] = event.releases.map(\.id) + + var parts: [String] = [] + if !startIDs.isEmpty { parts.append("▶ " + startIDs.joined(separator: ", ")) } + if !releaseIDs.isEmpty { parts.append("⏹ " + releaseIDs.joined(separator: ", ")) } + return parts.isEmpty ? "(empty event)" : parts.joined(separator: " ") + } + + private func parsedSetNext() -> Int? { + guard let i: Int = Int(setNextField.trimmingCharacters(in: .whitespaces)) else { return nil } + guard i >= 0, i < eventList.eventCount else { return nil } + return i + } + + private func applySetNext() { + guard let i: Int = parsedSetNext() else { return } + eventList.index = i + setNextField = "" + model.refresh() + } +} + +// MARK: - Sub-views + +private struct EventRow: View { + let label: String + let index: Int? + let description: String + + private let labelWidth: Double = 36 + private let indexWidth: Double = 32 + + var body: some View { + HStack(spacing: 8) { + Text(label) + .font(.caption) + .monospacedDigit() + .foregroundStyle(.secondary) + .frame(width: labelWidth, alignment: .leading) + Text(indexText) + .font(.caption) + .monospacedDigit() + .foregroundStyle(.primary) + .frame(width: indexWidth, alignment: .leading) + Text(description) + .font(.caption) + .foregroundStyle(.primary) + .lineLimit(2) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + + private var indexText: String { + if let i: Int = index { return "#\(i)" } + return "—" + } +} + +// MARK: - Standalone window (Linux) + +extension LyrebirdEventListView { + + /// Opens a `LyrebirdWindow` hosting an event-list control view. Requires a + /// running `GtkApplication` loop. + /// + /// - Parameters: + /// - eventList: The `LyrebirdEventList` to control. + /// - title: Window title-bar text. Defaults to `"Event List"`. + /// - width: Initial window width in points. Defaults to `360`. + /// - height: Initial window height in points. Defaults to `260`. + /// - Returns: The `LyrebirdWindow` hosting the view. + @discardableResult + public static func presentInWindow( + eventList: LyrebirdEventList, + title: String = "Event List", + width: Double = 360, + height: Double = 260 + ) -> LyrebirdWindow { + let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height) + win.open { + LyrebirdEventListView(eventList: eventList) + } + return win + } +} +#endif diff --git a/Sources/LyrebirdUI/LyrebirdMessageBanner.swift b/Sources/LyrebirdUI/LyrebirdMessageBanner.swift index a7eb0b8..9f992d9 100644 --- a/Sources/LyrebirdUI/LyrebirdMessageBanner.swift +++ b/Sources/LyrebirdUI/LyrebirdMessageBanner.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -124,3 +125,117 @@ public struct LyrebirdMessageBanner: View { return Array(all[start.. Void)? + + // Presentation constants (points). + private let stripeWidth: Double = 3 + private let stripeHeight: Double = 11 + private let cornerRadiusPoints: Double = 4 + + /// Creates a banner bound to `LyrebirdMessageCenter.shared`. + /// + /// - Parameters: + /// - lineCount: How many recent messages to show. Defaults to `3`. + /// - onOpenFull: Tap action. Defaults to `nil`. + @MainActor + public init( + lineCount: Int = 3, + onOpenFull: (() -> Void)? = nil + ) { + self.center = LyrebirdMessageCenter.shared + self.lineCount = lineCount + self.onOpenFull = onOpenFull + } + + /// Creates a banner bound to the given center. + /// + /// - Parameters: + /// - center: Center to observe. + /// - lineCount: How many recent messages to show. Defaults to `3`. + /// - onOpenFull: Tap action. Defaults to `nil`. + public init( + center: LyrebirdMessageCenter, + lineCount: Int = 3, + onOpenFull: (() -> Void)? = nil + ) { + self.center = center + self.lineCount = lineCount + self.onOpenFull = onOpenFull + } + + public var body: some View { + // A single static Button keeps state changes on the backend's narrow + // in-place mutation path (see ParameterButton's Linux body for the + // rationale). The empty state and the populated rows both live inside + // the one button; `press()` re-reads at click time. + Button(action: { onOpenFull?() }) { + VStack(alignment: .leading, spacing: 3) { + let recent: [LyrebirdMessage] = recentMessages + if recent.isEmpty { + Text("No messages") + .font(.caption) + .foregroundStyle(.secondary) + } else { + ForEach(recent) { msg in + bannerRow(msg) + } + } + } + .padding(6) + } + .buttonStyle(.plain) + .background(Color.lyrebirdControlBackground) + .cornerRadius(cornerRadiusPoints) + .disabled(onOpenFull == nil) + } + + private func bannerRow(_ msg: LyrebirdMessage) -> some View { + HStack(spacing: 6) { + Capsule() + .fill(LyrebirdMessageTierStyle.color(for: msg.tier)) + .frame(width: stripeWidth, height: stripeHeight) + Text(msg.text) + .font(.caption) + .lineLimit(1) + .truncationMode(.tail) + Spacer(minLength: 0) + } + } + + private var recentMessages: [LyrebirdMessage] { + // `LyrebirdMessageCenter` is @MainActor; the SwiftOpenUI body runs on the + // GTK main thread, so `assumeIsolated` reaches `messages` safely. Bind the + // center to a local first so the `@MainActor` closure captures the + // (Sendable) center, not `self` (the non-Sendable View). + let c: LyrebirdMessageCenter = center + let all: [LyrebirdMessage] = MainActor.assumeIsolated { c.messages } + guard all.count > lineCount else { return all } + let start: Int = all.count - lineCount + return Array(all[start.. Color { + switch tier { + case .info: return .blue + case .warning: return .orange + case .error: return .red + } + } + + static func shortLabel(for tier: LyrebirdMessageTier) -> String { + switch tier { + case .info: return "INFO" + case .warning: return "WARN" + case .error: return "ERR" + } + } +} +#endif diff --git a/Sources/LyrebirdUI/LyrebirdMessageView.swift b/Sources/LyrebirdUI/LyrebirdMessageView.swift index ebc9f85..9646640 100644 --- a/Sources/LyrebirdUI/LyrebirdMessageView.swift +++ b/Sources/LyrebirdUI/LyrebirdMessageView.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -81,6 +82,12 @@ public struct LyrebirdMessageView: View { } } + /// Current messages. On Apple the body is `@MainActor`, so this is a plain + /// read (the Linux counterpart hops via `assumeIsolated`). + private var messagesSnapshot: [LyrebirdMessage] { + center.messages + } + private var filterRow: some View { HStack(spacing: 8) { ForEach(LyrebirdMessageTier.allCases, id: \.self) { tier in @@ -129,17 +136,17 @@ public struct LyrebirdMessageView: View { // MARK: - Helpers private var filteredMessages: [LyrebirdMessage] { - center.messages.filter { enabledTiers.contains($0.tier) } + messagesSnapshot.filter { enabledTiers.contains($0.tier) } } private var emptyStateText: String { - if center.messages.isEmpty { return "No messages." } + if messagesSnapshot.isEmpty { return "No messages." } return "No messages match the current filter." } private func count(of tier: LyrebirdMessageTier) -> Int { var n: Int = 0 - for msg: LyrebirdMessage in center.messages where msg.tier == tier { + for msg: LyrebirdMessage in messagesSnapshot where msg.tier == tier { n += 1 } return n @@ -273,3 +280,296 @@ extension LyrebirdMessageView { } } #endif + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdMessageView`: a full scrollable +// view over a `LyrebirdMessageCenter` ring — a header (title, count, Clear), a +// per-tier filter row with live counts, and a scrolling list of rows. Live +// updates come from `@Bindable` on the `@Observable` center (body reads are +// observation-tracked, same as the Apple side). Text is drawn with real `Text` +// widgets, so the readout is complete. +// +// Dropped vs the Apple side (document per project rule): the auto-scroll to the +// newest row (`ScrollViewReader`/`onChange`/`withAnimation`) and per-row text +// selection are omitted; the list simply scrolls. `presentInWindow` opens a +// detached GTK window (needs a running `GtkApplication`). +// +// SwiftOpenUI is always present in this target (see Package.swift). +import SwiftOpenUI +import LyrebirdSynth +import Foundation // DateFormatter for the row timestamp + +/// Full scrollable view over a `LyrebirdMessageCenter` ring for the Linux/GTK4 +/// UI. Mirrors `LyrebirdUI.LyrebirdMessageView` (minus auto-scroll and text +/// selection); same public API/init as the Apple side. +public struct LyrebirdMessageView: View { + + @Bindable private var center: LyrebirdMessageCenter + + @State private var enabledTiers: Set = + Set(LyrebirdMessageTier.allCases) + + // Presentation constants (points). + private let minPanelWidth: Double = 360 + private let minPanelHeight: Double = 200 + private let timeColumnWidth: Double = 80 + private let stripeWidth: Double = 3 + private let stripeHeight: Double = 14 + + /// Creates a message view bound to `LyrebirdMessageCenter.shared`. + @MainActor + public init() { + self.center = LyrebirdMessageCenter.shared + } + + /// Creates a message view bound to the given center. + /// + /// - Parameter center: The center to observe. + public init(center: LyrebirdMessageCenter) { + self.center = center + } + + public var body: some View { + VStack(alignment: .leading, spacing: 8) { + headerRow + filterRow + Divider() + listBody + } + .padding(12) + .background(Color.lyrebirdControlBackground) + .frame(minWidth: minPanelWidth, minHeight: minPanelHeight) + } + + // MARK: - Sub-rows + + // `LyrebirdMessageCenter` is @MainActor; the SwiftOpenUI body / actions run on + // the GTK main thread, so `assumeIsolated` reaches `messages` / `clear()` + // safely. The center is bound to a local first so the `@MainActor` closure + // captures the (Sendable) center rather than `self` (the non-Sendable View). + private var messagesSnapshot: [LyrebirdMessage] { + let c: LyrebirdMessageCenter = center + return MainActor.assumeIsolated { c.messages } + } + + private var headerRow: some View { + let all: [LyrebirdMessage] = messagesSnapshot + let c: LyrebirdMessageCenter = center + return HStack(spacing: 8) { + Text("Messages") + .font(.headline) + Spacer() + Text("\(all.count)") + .font(.caption) + .monospacedDigit() + .foregroundStyle(.secondary) + // action:label: form — the string-title Button's action does not + // fire on GTK4 here (same as the EngineStatus Stop button). + Button { + MainActor.assumeIsolated { c.clear() } + } label: { + Text("Clear") + } + .disabled(all.isEmpty) + } + } + + private var filterRow: some View { + HStack(spacing: 8) { + ForEach(LyrebirdMessageTier.allCases, id: \.self) { tier in + TierFilterChip( + tier: tier, + count: count(of: tier), + isEnabled: enabledTiers.contains(tier), + toggle: { toggle(tier) } + ) + } + Spacer() + } + } + + private var listBody: some View { + let visible: [LyrebirdMessage] = filteredMessages + return ScrollView { + VStack(alignment: .leading, spacing: 4) { + if visible.isEmpty { + Text(emptyStateText) + .font(.caption) + .foregroundStyle(.secondary) + } else { + ForEach(visible) { msg in + MessageRow( + message: msg, + timeColumnWidth: timeColumnWidth, + stripeWidth: stripeWidth, + stripeHeight: stripeHeight + ) + } + } + } + } + } + + // MARK: - Helpers + + private var filteredMessages: [LyrebirdMessage] { + messagesSnapshot.filter { enabledTiers.contains($0.tier) } + } + + private var emptyStateText: String { + if messagesSnapshot.isEmpty { return "No messages." } + return "No messages match the current filter." + } + + private func count(of tier: LyrebirdMessageTier) -> Int { + var n: Int = 0 + for msg: LyrebirdMessage in messagesSnapshot where msg.tier == tier { + n += 1 + } + return n + } + + private func toggle(_ tier: LyrebirdMessageTier) { + if enabledTiers.contains(tier) { + enabledTiers.remove(tier) + } else { + enabledTiers.insert(tier) + } + } +} + +// MARK: - Sub-views + +private struct TierFilterChip: View { + let tier: LyrebirdMessageTier + let count: Int + let isEnabled: Bool + let toggle: () -> Void + + private let dotSize: Double = 8 + private let cornerRadiusPoints: Double = 4 + private let disabledDotOpacity: Double = 0.35 + private let disabledChipOpacity: Double = 0.55 + + var body: some View { + Button(action: toggle) { + HStack(spacing: 4) { + Circle() + .fill(LyrebirdMessageTierStyle.color(for: tier)) + .frame(width: dotSize, height: dotSize) + .opacity(isEnabled ? 1.0 : disabledDotOpacity) + Text(LyrebirdMessageTierStyle.shortLabel(for: tier)) + .font(.caption) + .monospacedDigit() + Text("\(count)") + .font(.caption2) + .monospacedDigit() + .foregroundStyle(.secondary) + } + .padding(.horizontal, 6) + .padding(.vertical, 3) + } + .buttonStyle(.plain) + .background(Color.lyrebirdControlBackground) + .cornerRadius(cornerRadiusPoints) + .opacity(isEnabled ? 1.0 : disabledChipOpacity) + } +} + +private struct MessageRow: View { + let message: LyrebirdMessage + let timeColumnWidth: Double + let stripeWidth: Double + let stripeHeight: Double + + var body: some View { + HStack(spacing: 8) { + Text(MessageRow.formatTime(message.timestamp)) + .font(.caption) + .monospacedDigit() + .foregroundStyle(.secondary) + .frame(width: timeColumnWidth, alignment: .leading) + Capsule() + .fill(LyrebirdMessageTierStyle.color(for: message.tier)) + .frame(width: stripeWidth, height: stripeHeight) + VStack(alignment: .leading, spacing: 2) { + if let src: String = message.source, !src.isEmpty { + Text(src) + .font(.caption2) + .monospacedDigit() + .foregroundStyle(.secondary) + } + Text(message.text) + .font(.callout) + .foregroundStyle(.primary) + } + Spacer(minLength: 0) + } + .padding(.horizontal, 4) + } + + private static let timeFormatter: DateFormatter = { + let f: DateFormatter = DateFormatter() + f.dateFormat = "HH:mm:ss.SSS" + return f + }() + + private static func formatTime(_ date: Date) -> String { + timeFormatter.string(from: date) + } +} + +// MARK: - Standalone window (Linux) + +extension LyrebirdMessageView { + + /// Opens a `LyrebirdWindow` hosting a message view bound to the shared + /// `LyrebirdMessageCenter`. Requires a running `GtkApplication` loop. + /// + /// - Important: Call on the GTK main thread (as the "Open Window" buttons and + /// any top-level demo/`main()` code do). It reaches the `@MainActor` + /// `LyrebirdMessageCenter.shared` via `assumeIsolated`, which traps if + /// invoked off the main thread — from a background/script thread, use the + /// `presentInWindow(center:...)` overload with an explicitly-resolved center. + /// + /// - Parameters: + /// - title: Window title-bar text. Defaults to `"Messages"`. + /// - width: Initial width in points. Defaults to `460`. + /// - height: Initial height in points. Defaults to `360`. + /// - Returns: The `LyrebirdWindow` hosting the view. + @discardableResult + public static func presentInWindow( + title: String = "Messages", + width: Double = 460, + height: Double = 360 + ) -> LyrebirdWindow { + // `LyrebirdMessageCenter.shared` is `@MainActor`; this runs on the GTK + // main thread, so `assumeIsolated` reaches it (no `self` captured — no + // sending-race), same hop the messages section uses. + let center: LyrebirdMessageCenter = MainActor.assumeIsolated { + LyrebirdMessageCenter.shared + } + return presentInWindow( + center: center, + title: title, + width: width, + height: height + ) + } + + /// Opens a `LyrebirdWindow` hosting a message view bound to `center`. + @discardableResult + public static func presentInWindow( + center: LyrebirdMessageCenter, + title: String = "Messages", + width: Double = 460, + height: Double = 360 + ) -> LyrebirdWindow { + let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height) + win.open { + LyrebirdMessageView(center: center) + } + return win + } +} +#endif diff --git a/Sources/LyrebirdUI/LyrebirdNodeTreeView.swift b/Sources/LyrebirdUI/LyrebirdNodeTreeView.swift index 29c6d01..1789855 100644 --- a/Sources/LyrebirdUI/LyrebirdNodeTreeView.swift +++ b/Sources/LyrebirdUI/LyrebirdNodeTreeView.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -262,3 +263,251 @@ extension LyrebirdNodeTreeView { } } #endif + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdNodeTreeView`: a live indented +// tree of the engine's `NodeTreeMirror`, rows head→tail. Live updates come from +// reading `mirror.snapshot` in the body (observation-tracked, `NodeTreeMirror` +// is `@Observable`). Groups expand/collapse via a tapped glyph. +// +// Differences vs the Apple side: SF-Symbol chevrons/dots become text glyphs +// (▼ / ▶ / •) — `DrawingContext` has no image atlas and Text is available here; +// monospaced fonts fall back to the default font. `presentInWindow` opens a +// detached GTK window (needs a running `GtkApplication`). +// +// SwiftOpenUI is always present in this target (see Package.swift). +import SwiftOpenUI +import LyrebirdSynth + +/// Live indented tree of the engine's `NodeTreeMirror` for the Linux/GTK4 UI. +/// Mirrors `LyrebirdUI.LyrebirdNodeTreeView`; same public API/init as the Apple +/// side. +public struct LyrebirdNodeTreeView: View { + + private let mirror: NodeTreeMirror + + @State private var expanded: Set = [] + + private let minPanelWidth: Double = 320 + private let minPanelHeight: Double = 220 + + /// Creates a node-tree view bound to the given engine's mirror. + public init(engine: SynthesisEngine) { + self.mirror = engine.nodeTreeMirror + } + + /// Creates a node-tree view bound to the given mirror. + public init(mirror: NodeTreeMirror) { + self.mirror = mirror + } + + public var body: some View { + VStack(alignment: .leading, spacing: 6) { + headerRow + Divider() + ScrollView { + VStack(alignment: .leading, spacing: 2) { + NodeRowList( + node: mirror.snapshot.root, + depth: 0, + expanded: $expanded + ) + } + .padding(top: 4, bottom: 4, leading: 0, trailing: 0) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + .padding(12) + .background(Color.lyrebirdControlBackground) + .frame(minWidth: minPanelWidth, minHeight: minPanelHeight) + .onAppear { _seedDefaultExpansion() } + } + + private var headerRow: some View { + HStack(spacing: 8) { + Text("Node Tree") + .font(.headline) + Spacer() + Button("Expand All") { _expandAll() } + .font(.caption) + Button("Collapse All") { expanded.removeAll() } + .font(.caption) + } + } + + /// Default expansion: root + mainGroup open, deeper nodes collapsed. + private func _seedDefaultExpansion() { + guard expanded.isEmpty else { return } + let root: NodeTreeSnapshot.Node = mirror.snapshot.root + expanded.insert(root.id) + for child: NodeTreeSnapshot.Node in root.children where _isContainer(child.kind) { + expanded.insert(child.id) + } + } + + private func _expandAll() { + var ids: Set = [] + _collectContainerIds(mirror.snapshot.root, into: &ids) + expanded = ids + } + + private func _collectContainerIds( + _ node: NodeTreeSnapshot.Node, + into ids: inout Set + ) { + if _isContainer(node.kind) { + ids.insert(node.id) + } + for child: NodeTreeSnapshot.Node in node.children { + _collectContainerIds(child, into: &ids) + } + } + + private func _isContainer(_ kind: NodeTreeSnapshot.Node.Kind) -> Bool { + switch kind { + case .group, .parallelGroup: return true + case .synth: return false + } + } +} + +// MARK: - Recursive row list + +private struct NodeRowList: View { + let node: NodeTreeSnapshot.Node + let depth: Int + @Binding var expanded: Set + + var body: some View { + let isContainer: Bool = _isContainer(node.kind) + let isExpanded: Bool = expanded.contains(node.id) + VStack(alignment: .leading, spacing: 2) { + NodeRow( + node: node, + depth: depth, + isContainer: isContainer, + isExpanded: isExpanded, + toggle: { + if isExpanded { expanded.remove(node.id) } + else { expanded.insert(node.id) } + } + ) + if isContainer && isExpanded { + ForEach(node.children) { child in + NodeRowList( + node: child, + depth: depth + 1, + expanded: $expanded + ) + } + } + } + } + + private func _isContainer(_ kind: NodeTreeSnapshot.Node.Kind) -> Bool { + switch kind { + case .group, .parallelGroup: return true + case .synth: return false + } + } +} + +// MARK: - Single row + +private struct NodeRow: View { + let node: NodeTreeSnapshot.Node + let depth: Int + let isContainer: Bool + let isExpanded: Bool + let toggle: () -> Void + + private static let indentPoints: Double = 14 + private static let glyphWidth: Double = 12 + private static let identityHexSuffixLen: Int = 4 + + var body: some View { + HStack(spacing: 6) { + Spacer() + .frame(width: Double(depth) * NodeRow.indentPoints) + + Text(glyph) + .font(.caption2) + .foregroundStyle(.secondary) + .frame(width: NodeRow.glyphWidth, alignment: .center) + + Text(node.displayName) + .font(.callout) + .foregroundStyle(.primary) + + if let badge: String = childCountBadge { + Text(badge) + .font(.caption2) + .foregroundStyle(.secondary) + } + + Text(_identityShort(node.id)) + .font(.caption2) + .foregroundStyle(.tertiary) + + Spacer(minLength: 0) + } + .onTapGesture { if isContainer { toggle() } } + } + + /// Expand/collapse glyph for containers; a bullet for leaf synth nodes. + private var glyph: String { + guard isContainer else { return "•" } + return isExpanded ? "▼" : "▶" + } + + private var childCountBadge: String? { + guard isContainer else { return nil } + return "(\(node.children.count))" + } + + private func _identityShort(_ id: ObjectIdentifier) -> String { + // Use `hashValue` rather than parsing `String(describing:)`. The + // textual form of `ObjectIdentifier` is a stdlib implementation + // detail with no API guarantee; `hashValue` is process-stable for + // a given object identity (Hashable conformance) and yields a + // deterministic short hex disambiguator. + let mask: Int = (1 << (NodeRow.identityHexSuffixLen * 4)) - 1 + let masked: Int = id.hashValue & mask + let raw: String = String(masked, radix: 16, uppercase: false) + let padded: String + if raw.count < NodeRow.identityHexSuffixLen { + padded = String(repeating: "0", count: NodeRow.identityHexSuffixLen - raw.count) + raw + } else { + padded = raw + } + return "#" + padded + } +} + +// MARK: - Standalone window (Linux) + +extension LyrebirdNodeTreeView { + + /// Opens a `LyrebirdWindow` hosting a node-tree view. Requires a running + /// `GtkApplication` loop. + /// + /// - Parameters: + /// - engine: The engine to mirror. + /// - title: Window title-bar text. Defaults to `"Node Tree"`. + /// - width: Initial width in points. Defaults to `420`. + /// - height: Initial height in points. Defaults to `420`. + @discardableResult + public static func presentInWindow( + engine: SynthesisEngine, + title: String = "Node Tree", + width: Double = 420, + height: Double = 420 + ) -> LyrebirdWindow { + let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height) + win.open { + LyrebirdNodeTreeView(engine: engine) + } + return win + } +} +#endif diff --git a/Sources/LyrebirdUI/LyrebirdProcessView.swift b/Sources/LyrebirdUI/LyrebirdProcessView.swift index e45c3f3..9118f89 100644 --- a/Sources/LyrebirdUI/LyrebirdProcessView.swift +++ b/Sources/LyrebirdUI/LyrebirdProcessView.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -220,3 +221,250 @@ extension LyrebirdProcessView { } } #endif + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdProcessView`: a control panel for +// one `LyrebirdProcess` (state dot + id, dB amp slider, Start/Release). The 10 Hz +// lifecycle poll moves off SwiftOpenUI's off-main `.task` onto a `Timer` on +// `RunLoop.main` inside an `@Observable` model — the amp/running/releasing state +// lives there so the `@Bindable` body tracks it. dB↔amp maths reuse the +// cross-platform `DbSliderConversion`. +// +// The amp control uses SwiftOpenUI's native `Slider` (GtkScale). Unlike the +// Canvas-drawn `ParameterSlider`, a native scale does not live-track other +// controls mid-drag — acceptable here (a single transport slider, not a linked +// modulation source). +// +// SwiftOpenUI is always present in this target (see Package.swift). +import SwiftOpenUI +import LyrebirdSynth +import Observation +import Foundation + +/// 10 Hz process lifecycle poll interval. +private let linuxProcessPollIntervalSeconds: TimeInterval = 0.1 + +/// Polls one `LyrebirdProcess`'s lifecycle + amp on a main-thread timer and +/// publishes them for ``LyrebirdProcessView``. Internal — only the view is public. +/// +/// `@unchecked Sendable`: main-thread-confined; the `Timer` block is `@Sendable`, +/// same rationale as `LyrebirdScopeModel`. +@Observable +final class LinuxProcessModel: @unchecked Sendable { + + var isRunning: Bool = false + var isReleasing: Bool = false + var amp: Double = 1.0 + + @ObservationIgnored let process: LyrebirdProcess + @ObservationIgnored private var timer: Timer? + + init(process: LyrebirdProcess) { + self.process = process + // `amp` is @MainActor; construction happens on the GTK main thread. + self.amp = MainActor.assumeIsolated { process.amp } + } + + deinit { + timer?.invalidate() + } + + func start() { + guard timer == nil else { return } + refresh() + let t: Timer = Timer.scheduledTimer( + withTimeInterval: linuxProcessPollIntervalSeconds, + repeats: true + ) { [weak self] _ in + self?.refresh() + } + timer = t + } + + func stop() { + timer?.invalidate() + timer = nil + } + + // SwiftOpenUI view/timer callbacks are nonisolated but always run on the GTK + // main thread, so `assumeIsolated` reaches `LyrebirdProcess`'s @MainActor + // `amp` safely. `isRunning` / `isReleasing` are nonisolated already. + func refresh() { + isRunning = process.isRunning + isReleasing = process.isReleasing + amp = MainActor.assumeIsolated { process.amp } + } +} + +/// A control panel for a single `LyrebirdProcess` on the Linux/GTK4 UI. Mirrors +/// `LyrebirdUI.LyrebirdProcessView`; same public API/init as the Apple side. +public struct LyrebirdProcessView: View { + + public let process: LyrebirdProcess + public let engine: SynthesisEngine + + @State private var model: LinuxProcessModel + + // Layout constants (points). + private let dotSize: Double = 10 + private let ampLabelWidth: Double = 36 + private let dbReadoutWidth: Double = 56 + private let disabledDotOpacity: Double = 0.4 + + /// Creates a process control view bound to the given process. + /// + /// - Parameters: + /// - process: The `LyrebirdProcess` to control. + /// - engine: The `SynthesisEngine` used by the **Start** button. + public init( + process: LyrebirdProcess, + engine: SynthesisEngine + ) { + self.process = process + self.engine = engine + _model = State(wrappedValue: LinuxProcessModel(process: process)) + } + + public var body: some View { + VStack(alignment: .leading, spacing: 12) { + header + Divider() + ampRow + Divider() + transportRow + } + .padding(12) + .background(Color.lyrebirdControlBackground) + .frame(minWidth: 280) + .onAppear { model.start() } + .onDisappear { model.stop() } + } + + // MARK: - Sub-rows + + private var header: some View { + HStack(spacing: 8) { + Circle() + .fill(stateColor) + .frame(width: dotSize, height: dotSize) + Text(process.id) + .font(.headline) + Spacer() + Text(stateLabel) + .font(.caption) + .monospacedDigit() + .foregroundStyle(.secondary) + } + } + + private var ampRow: some View { + HStack(spacing: 8) { + Text("Amp") + .font(.caption) + .monospacedDigit() + .foregroundStyle(.secondary) + .frame(width: ampLabelWidth, alignment: .leading) + Slider(value: Binding( + get: { dbFromAmp(model.amp) }, + set: { newDb in + let newAmp: Double = ampFromDb(newDb) + model.amp = newAmp + // Bind `process` (Sendable) to a local so the @MainActor + // closure captures it, not `self` (the non-Sendable View). + let p: LyrebirdProcess = process + MainActor.assumeIsolated { p.amp = newAmp } + } + ), in: LyrebirdProcessView.minDb ... maxDb) + Text(dbDisplay(dbFromAmp(model.amp))) + .font(.caption) + .monospacedDigit() + .foregroundStyle(.primary) + .frame(width: dbReadoutWidth, alignment: .trailing) + } + } + + // MARK: - dB <-> linear amplitude (shared via `DbSliderConversion`) + + private static let minDb: Double = DbSliderConversion.minDb + + /// Per-process slider ceiling, sourced from ``LyrebirdProcess/maxUIAmpDb``. + private var maxDb: Double { process.maxUIAmpDb } + + private func ampFromDb(_ db: Double) -> Double { DbSliderConversion.ampFromDb(db) } + private func dbFromAmp(_ amp: Double) -> Double { DbSliderConversion.dbFromAmp(amp, maxDb: maxDb) } + private func dbDisplay(_ db: Double) -> String { DbSliderConversion.dbDisplay(db) } + + private var transportRow: some View { + HStack(spacing: 8) { + Button("Start") { + // `process` is Sendable; `engine` is not, so bind it via + // `nonisolated(unsafe)` (safe — all runs on the GTK main thread). + // Capturing these locals keeps `self` (the View) out of the + // @MainActor closure. + let p: LyrebirdProcess = process + nonisolated(unsafe) let e: SynthesisEngine = engine + MainActor.assumeIsolated { p.play(engine: e) } + model.refresh() + } + .disabled(model.isRunning) + + Button("Release") { + let p: LyrebirdProcess = process + MainActor.assumeIsolated { p.release() } + model.refresh() + } + .disabled(!model.isRunning || model.isReleasing) + + Spacer() + } + } + + // MARK: - Helpers + + private var stateColor: Color { + if model.isReleasing { return .yellow } + if model.isRunning { return .green } + return Color.secondary.opacity(disabledDotOpacity) + } + + private var stateLabel: String { + if model.isReleasing { return "Releasing" } + if model.isRunning { return "Running" } + return "Idle" + } +} + +// MARK: - Standalone window (Linux) + +extension LyrebirdProcessView { + + /// Opens a `LyrebirdWindow` hosting a process control view. Requires a + /// running `GtkApplication` loop. + /// + /// - Parameters: + /// - process: The `LyrebirdProcess` to control. + /// - engine: The `SynthesisEngine` used by the **Start** button. + /// - title: Window title-bar text. Defaults to the process ID. + /// - width: Initial window width in points. Defaults to `300`. + /// - height: Initial window height in points. Defaults to `180`. + /// - Returns: The `LyrebirdWindow` hosting the view. + @discardableResult + public static func presentInWindow( + process: LyrebirdProcess, + engine: SynthesisEngine, + title: String? = nil, + width: Double = 300, + height: Double = 180 + ) -> LyrebirdWindow { + let win: LyrebirdWindow = LyrebirdWindow( + title: title ?? process.id, + width: width, + height: height + ) + win.open { + LyrebirdProcessView(process: process, engine: engine) + } + return win + } +} +#endif diff --git a/Sources/LyrebirdUI/LyrebirdRunningProcessesView.swift b/Sources/LyrebirdUI/LyrebirdRunningProcessesView.swift index 94eacd2..989ac75 100644 --- a/Sources/LyrebirdUI/LyrebirdRunningProcessesView.swift +++ b/Sources/LyrebirdUI/LyrebirdRunningProcessesView.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -193,3 +194,188 @@ extension LyrebirdRunningProcessesView { } } #endif + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdRunningProcessesView`: one +// ``LyrebirdProcessView`` per currently-running `LyrebirdProcess` in an event +// list. The 10 Hz refresh moves off SwiftOpenUI's off-main `.task` onto a `Timer` +// on `RunLoop.main` inside an `@Observable` model. The identity-stable +// reassignment (only swap the array when the running set changes) is preserved so +// child rows keep their own poll timers and per-row state across ticks. +// +// SwiftOpenUI is always present in this target (see Package.swift). +import SwiftOpenUI +import LyrebirdSynth +import Observation +import Foundation + +/// 10 Hz — matches ``LyrebirdProcessView``. +private let linuxRunningProcessesPollIntervalSeconds: TimeInterval = 0.1 + +/// Polls an event list's running processes on a main-thread timer and publishes +/// an identity-stable snapshot for ``LyrebirdRunningProcessesView``. Internal. +/// +/// `@unchecked Sendable`: main-thread-confined; the `Timer` block is `@Sendable`, +/// same rationale as `LyrebirdScopeModel`. +@Observable +final class LinuxRunningProcessesModel: @unchecked Sendable { + + var running: [LyrebirdProcess] = [] + + @ObservationIgnored private var timer: Timer? + @ObservationIgnored private let eventList: LyrebirdEventList + + init(eventList: LyrebirdEventList) { + self.eventList = eventList + } + + deinit { + timer?.invalidate() + } + + func start() { + guard timer == nil else { return } + refresh() + let t: Timer = Timer.scheduledTimer( + withTimeInterval: linuxRunningProcessesPollIntervalSeconds, + repeats: true + ) { [weak self] _ in + self?.refresh() + } + timer = t + } + + func stop() { + timer?.invalidate() + timer = nil + } + + func refresh() { + let snapshot: [LyrebirdProcess] = eventList.allProcesses.filter { $0.isRunning } + if !LinuxRunningProcessesModel.sameIdentities(snapshot, running) { + running = snapshot + } + } + + /// `true` when two arrays contain the same `LyrebirdProcess` instances in the + /// same order. Identity-only — does not inspect process state. + private static func sameIdentities( + _ a: [LyrebirdProcess], + _ b: [LyrebirdProcess] + ) -> Bool { + guard a.count == b.count else { return false } + for i: Int in 0.. — Running"`. + /// - width: Initial window width in points. Defaults to `360`. + /// - height: Initial window height in points. Defaults to `420`. + /// - Returns: The ``LyrebirdWindow`` hosting the view. + @discardableResult + public static func presentInWindow( + eventList: LyrebirdEventList, + engine: SynthesisEngine, + title: String? = nil, + width: Double = 360, + height: Double = 420 + ) -> LyrebirdWindow { + let win: LyrebirdWindow = LyrebirdWindow( + title: title ?? "\(eventList.id) — Running", + width: width, + height: height + ) + win.open { + LyrebirdRunningProcessesView(eventList: eventList, engine: engine) + } + return win + } +} +#endif diff --git a/Sources/LyrebirdUI/LyrebirdScatterView.swift b/Sources/LyrebirdUI/LyrebirdScatterView.swift index 922d620..8b09d4c 100644 --- a/Sources/LyrebirdUI/LyrebirdScatterView.swift +++ b/Sources/LyrebirdUI/LyrebirdScatterView.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI /// A Canvas-based scatter plot for an array of `Double` values. @@ -117,3 +118,128 @@ public struct LyrebirdScatterView: View { return height * (1.0 - CGFloat(t)) } } + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdScatterView`: a Canvas scatter +// plot of an array of `Double`s, one filled dot per sample. The SwiftUI +// `GraphicsContext`/`Path` drawing is rewritten to imperative `DrawingContext` +// (Cairo) calls: a background fill, an optional zero guide line, and one +// `arc`+`fill` per dot. Y-bounds reuse the shared `_linuxEnvelopeYBounds`. +// +// No axis text is drawn (`DrawingContext` has no text primitive) — the Apple +// side draws none either, so there is no feature loss here. +// +// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift). +import SwiftOpenUI +import BackendGTK4 +import Foundation // CGSize / CGFloat + +/// A Canvas scatter plot for the Linux/GTK4 UI. Mirrors +/// `LyrebirdUI.LyrebirdScatterView`; same public API/init as the Apple side. +public struct LyrebirdScatterView: View { + + private let samples: [Double] + private let yRange: ClosedRange? + private let pointColor: Color + private let showZeroLine: Bool + private let width: CGFloat + private let height: CGFloat + + // Background is a fixed dark panel; drawn inside the renderer since the + // Cairo backend has no `clipShape`. + private static let backgroundRGB: (r: Double, g: Double, b: Double) = (0.08, 0.08, 0.08) + private static let scatterDotRadius: Double = 2.5 + private static let zeroLineOpacity: Double = 0.25 + private static let guideLineWidth: Double = 0.5 + + public init( + _ samples: [Double], + yRange: ClosedRange? = nil, + pointColor: Color = .cyan, + showZeroLine: Bool = true, + width: CGFloat = 300, + height: CGFloat = 120 + ) { + self.samples = samples + self.yRange = yRange + self.pointColor = pointColor + self.showZeroLine = showZeroLine + self.width = width + self.height = height + } + + public var body: some View { + Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in + _draw(ctx: ctx, size: size) + }) + .frame(width: Double(width), height: Double(height)) + } + + // MARK: - Drawing + + private func _draw( + ctx: DrawingContext, + size: CGSize + ) { + let w: Double = Double(size.width) + let h: Double = Double(size.height) + + // Background panel. + let bg: (r: Double, g: Double, b: Double) = LyrebirdScatterView.backgroundRGB + ctx.setColor(r: bg.r, g: bg.g, b: bg.b) + ctx.rectangle(x: 0, y: 0, width: w, height: h) + ctx.fill() + + guard !samples.isEmpty else { return } + + let (yMin, yMax): (Double, Double) = _yBounds() + + if showZeroLine && yMin <= 0 && yMax >= 0 { + let zy: Double = _yFor(0, yMin: yMin, yMax: yMax, height: h) + ctx.setColor(r: 1.0, g: 1.0, b: 1.0, a: LyrebirdScatterView.zeroLineOpacity) + ctx.setLineWidth(LyrebirdScatterView.guideLineWidth) + ctx.moveTo(x: 0, y: zy) + ctx.lineTo(x: w, y: zy) + ctx.stroke() + } + + let count: Int = samples.count + let r: Double = LyrebirdScatterView.scatterDotRadius + let fullCircle: Double = 2.0 * Double.pi + ctx.setColor(r: pointColor.red, g: pointColor.green, b: pointColor.blue, a: pointColor.alpha) + + if count == 1 { + let px: Double = w / 2 + let py: Double = h / 2 + ctx.arc(centerX: px, centerY: py, radius: r, startAngle: 0, endAngle: fullCircle) + ctx.fill() + return + } + + for i: Int in 0.. (Double, Double) { + if let r: ClosedRange = yRange { return (r.lowerBound, r.upperBound) } + return _linuxEnvelopeYBounds(levels: samples) + } + + private func _yFor( + _ v: Double, + yMin: Double, + yMax: Double, + height: Double + ) -> Double { + guard yMax > yMin else { return height / 2 } + let t: Double = (v - yMin) / (yMax - yMin) + return height * (1.0 - t) + } +} +#endif diff --git a/Sources/LyrebirdUI/LyrebirdScopeModel.swift b/Sources/LyrebirdUI/LyrebirdScopeModel.swift new file mode 100644 index 0000000..2a4bb69 --- /dev/null +++ b/Sources/LyrebirdUI/LyrebirdScopeModel.swift @@ -0,0 +1,62 @@ +// LyrebirdScopeModel.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if !canImport(SwiftUI) +import LyrebirdSynth +import Observation +import Foundation + +/// Observable model that polls a `ScopeCapture` on a main-thread timer and +/// publishes the latest per-channel sample frame for ``LyrebirdScopeView`` to draw. +/// +/// `@unchecked Sendable`: every access is confined to the UI (GTK main) thread — +/// the poll `Timer` fires on `RunLoop.main`, and `start`/`stop`/`channels` are +/// only touched from that thread — but `Timer`'s block is `@Sendable`, so the +/// capture requires the conformance. The confinement, not the type system, is +/// what makes it safe (same rationale as `UIParamNode`). +@Observable +public final class LyrebirdScopeModel: @unchecked Sendable { + + /// Latest snapshot: `[channelIndex][sampleIndex]`. Written on the main thread + /// by the poll timer; read by the `Canvas` renderer. + public internal(set) var channels: [[Float]] = [] + + @ObservationIgnored private var timer: Timer? + @ObservationIgnored private let capture: ScopeCapture + @ObservationIgnored private let pollInterval: TimeInterval + + /// - Parameters: + /// - capture: The `ScopeCapture` to poll (typically the engine's `scopeTap`). + /// - pollInterval: Seconds between snapshots. Default ≈ 30 Hz. + public init( + capture: ScopeCapture, + pollInterval: TimeInterval = 1.0 / 30.0 + ) { + self.capture = capture + self.pollInterval = pollInterval + } + + deinit { + timer?.invalidate() + } + + /// Begin polling. Idempotent. Must be called on the main thread. + public func start() { + guard timer == nil else { return } + let t: Timer = Timer.scheduledTimer(withTimeInterval: pollInterval, repeats: true) { [weak self] _ in + guard let self else { return } + self.channels = self.capture.snapshot() + } + timer = t + } + + /// Stop polling. Idempotent. + public func stop() { + timer?.invalidate() + timer = nil + } +} +#endif diff --git a/Sources/LyrebirdUI/LyrebirdScopeView.swift b/Sources/LyrebirdUI/LyrebirdScopeView.swift index a2f29db..56478d2 100644 --- a/Sources/LyrebirdUI/LyrebirdScopeView.swift +++ b/Sources/LyrebirdUI/LyrebirdScopeView.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -97,3 +98,130 @@ public struct LyrebirdScopeView: View { with: .color(LyrebirdScopeView.backgroundColor)) } } + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdScopeView`: a real-time +// oscilloscope that polls a core `ScopeCapture` (via ``LyrebirdScopeModel``) and +// draws each channel's waveform stacked vertically on a single `Canvas`. +// +// Periodic redraw uses a Foundation `Timer` on `RunLoop.main` (in the model), +// which the GTK4 backend pumps (~every 5 ms) from its GLib main loop — so the +// poll fires on the GTK main thread and the `@Observable` model write is +// main-thread-safe. That is deliberately NOT SwiftOpenUI's `.task`, whose closure +// runs off the main thread (unlike SwiftUI's main-actor `.task`) and would race +// the observation registrar. The model write is an `@Observable` change read by +// the `Canvas`, so it takes the backend's narrow `.canvasContent` redraw path +// (the pinned fork's fix). +// +// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift). +import SwiftOpenUI +import BackendGTK4 +import LyrebirdSynth +import Foundation + +/// A real-time dual-channel oscilloscope for the Linux/GTK4 UI. Mirrors +/// `LyrebirdUI.LyrebirdScopeView`: channels stacked vertically, each with a dim +/// zero-line, separated by a hairline; channel 0 cyan, 1 orange, 2 green, 3 yellow. +public struct LyrebirdScopeView: View { + + @State private var model: LyrebirdScopeModel + + // Presentation constants. + private let scopeWidth: Double = 320 + private let scopeHeight: Double = 120 + private let cornerRadius: Double = 4 + /// Fraction of each channel's half-row height used for waveform excursion, + /// leaving headroom so ±1 signals don't touch the channel boundary. + private let waveformHeightFraction: Double = 0.44 + private let zeroLineOpacity: Double = 0.25 + private let separatorOpacity: Double = 0.3 + + /// Creates a scope bound to a `ScopeCapture` (e.g. the engine's `scopeTap`). + /// + /// - Parameter capture: The capture to visualise. + public init(capture: ScopeCapture) { + _model = State(wrappedValue: LyrebirdScopeModel(capture: capture)) + } + + public var body: some View { + // Read the observed `channels` at BODY level, not only inside the Canvas + // renderer below. `withObservationTracking` wraps body evaluation, but the + // renderer closure runs at DRAW time (outside that scope), so a + // `model.channels` read there registers no dependency — the observation is + // one-shot and the trace freezes after the first frame. Reading it here + // re-registers on every timer tick, so the body re-evaluates and the + // Canvas redraws continuously (the same reason the CPU-bar view, which + // reads its model for the percentage labels, animates). + let chans: [[Float]] = model.channels + return Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in + let w: Double = Double(size.width) + let h: Double = Double(size.height) + + // Background. + ctx.setColor(r: 0.08, g: 0.08, b: 0.08) + ctx.rectangle(x: 0, y: 0, width: w, height: h) + ctx.fill() + + guard !chans.isEmpty else { return } + let count: Int = chans.count + let rowH: Double = h / Double(count) + + for ch: Int in 0.. 1 else { continue } + let color: (r: Double, g: Double, b: Double) = channelColor(ch) + let xStep: Double = w / Double(samples.count - 1) + ctx.setColor(r: color.r, g: color.g, b: color.b) + ctx.setLineWidth(1.0) + for i: Int in 0.. (r: Double, g: Double, b: Double) { + let palette: [(r: Double, g: Double, b: Double)] = [ + (0.0, 0.8, 1.0), + (1.0, 0.53, 0.0), + (0.0, 0.8, 0.0), + (1.0, 0.8, 0.0) + ] + return palette[ch % palette.count] + } +} +#endif diff --git a/Sources/LyrebirdUI/LyrebirdSpectrumView.swift b/Sources/LyrebirdUI/LyrebirdSpectrumView.swift index 6069d25..66c78a0 100644 --- a/Sources/LyrebirdUI/LyrebirdSpectrumView.swift +++ b/Sources/LyrebirdUI/LyrebirdSpectrumView.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -230,3 +231,268 @@ public struct LyrebirdSpectrumView: View { return max(0, min(1, (db - floorDB) / (ceilDB - floorDB))) } } + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdSpectrumView`: a real-time +// spectrum / waterfall analyzer. The SwiftUI `GraphicsContext`/`Path` drawing is +// rewritten to imperative `DrawingContext` (Cairo) calls. Polling moves off +// SwiftOpenUI's `.task` (which runs OFF the main thread) onto a Foundation +// `Timer` on `RunLoop.main` inside an `@Observable` model — the same pattern as +// `LyrebirdStatusView` / `LyrebirdScopeModel`. +// +// No axis/frequency text is drawn (`DrawingContext` has no text primitive) — the +// Apple side draws none either, so there is no feature loss. +// +// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift). +import SwiftOpenUI +import BackendGTK4 +import LyrebirdSynth +import Observation +import Foundation + +/// Poll interval for the spectrum model (~30 Hz). +private let linuxSpectrumPollIntervalSeconds: TimeInterval = 1.0 / 30.0 + +/// Polls a `SpectrumCapture` on a main-thread timer and publishes the current +/// magnitude frame (plus a bounded history for waterfall mode) for +/// ``LyrebirdSpectrumView`` to draw. Internal — only the view is public. +/// +/// `@unchecked Sendable`: main-thread-confined (the poll `Timer` fires on +/// `RunLoop.main`), but `Timer`'s block is `@Sendable`, so the capture requires +/// the conformance — same rationale as `LyrebirdScopeModel`. +@Observable +final class LinuxSpectrumModel: @unchecked Sendable { + + var magnitudes: [Float] = [] + var history: [[Float]] = [] + + @ObservationIgnored private var timer: Timer? + @ObservationIgnored private let capture: SpectrumCapture + @ObservationIgnored private let waterfallRows: Int + + init(capture: SpectrumCapture, waterfallRows: Int) { + self.capture = capture + self.waterfallRows = waterfallRows + } + + deinit { + timer?.invalidate() + } + + func start() { + guard timer == nil else { return } + let t: Timer = Timer.scheduledTimer( + withTimeInterval: linuxSpectrumPollIntervalSeconds, + repeats: true + ) { [weak self] _ in + guard let self else { return } + let snap: [Float] = self.capture.snapshot() + self.magnitudes = snap + if self.waterfallRows > 0 { + var h: [[Float]] = self.history + h.insert(snap, at: 0) + if h.count > self.waterfallRows { h.removeLast() } + self.history = h + } + } + timer = t + } + + func stop() { + timer?.invalidate() + timer = nil + } +} + +/// A real-time spectrum analyzer / waterfall for the Linux/GTK4 UI. Mirrors +/// `LyrebirdUI.LyrebirdSpectrumView`; same public API/init as the Apple side. +public struct LyrebirdSpectrumView: View { + + // MARK: - Configuration + + /// The spectrum capture object to poll. + public let capture: SpectrumCapture + + /// Audio sample rate in Hz, used to map bin indices to frequencies. + public let sampleRate: Double + + /// Minimum displayed frequency in Hz. Default: 20 Hz. + public let minHz: Double + + /// Maximum displayed frequency in Hz. Default: 20 000 Hz. + public let maxHz: Double + + /// Lower dB bound for the magnitude axis. Default: −80 dB. + public let floorDB: Double + + /// Upper dB bound for the magnitude axis. Default: 0 dB. + public let ceilDB: Double + + /// Number of history rows shown in waterfall mode. + /// `0` (default) selects spectrum-line mode; any positive value selects waterfall mode. + public let waterfallRows: Int + + // MARK: - State + + @State private var model: LinuxSpectrumModel + + // MARK: - Constants + + private static let backgroundRGB: (r: Double, g: Double, b: Double) = (0.08, 0.08, 0.08) + private static let spectrumRGB: (r: Double, g: Double, b: Double) = (0.0, 0.667, 0.0) // green + private static let spectrumLineWidth: Double = 1.0 + private static let zeroLineOpacity: Double = 0.2 + /// Prevent log(0) in dB conversion. + private static let magnitudeFloor: Double = 1e-10 + private static let waterfallHue: Double = 0.33 // green + private static let waterfallSaturationBoost: Double = 1.5 + + // MARK: - Init + + /// - Parameters: + /// - capture: The `SpectrumCapture` registered as a processor on a `SpectralChain.Audio`. + /// - sampleRate: Audio sample rate in Hz. Used to compute bin-to-frequency mapping. + /// - minHz: Minimum frequency displayed on the X axis. Default: 20 Hz. + /// - maxHz: Maximum frequency displayed on the X axis. Default: 20 000 Hz. + /// - floorDB: Minimum dB level displayed on the Y axis. Default: −80 dB. + /// - ceilDB: Maximum dB level displayed on the Y axis. Default: 0 dB. + /// - waterfallRows: Number of waterfall history rows. `0` = spectrum line, `> 0` = waterfall spectrogram. + public init( + capture: SpectrumCapture, + sampleRate: Double, + minHz: Double = 20, + maxHz: Double = 20_000, + floorDB: Double = -80, + ceilDB: Double = 0, + waterfallRows: Int = 0 + ) { + precondition(sampleRate > 0, + "LyrebirdSpectrumView: sampleRate must be > 0, got \(sampleRate)") + precondition(minHz > 0 && minHz < maxHz, + "LyrebirdSpectrumView: minHz must be > 0 and < maxHz") + precondition(floorDB < ceilDB, + "LyrebirdSpectrumView: floorDB must be < ceilDB") + self.capture = capture + self.sampleRate = sampleRate + self.minHz = minHz + self.maxHz = maxHz + self.floorDB = floorDB + self.ceilDB = ceilDB + let rows: Int = max(0, waterfallRows) + self.waterfallRows = rows + _model = State(wrappedValue: LinuxSpectrumModel(capture: capture, waterfallRows: rows)) + } + + // MARK: - Body + + public var body: some View { + Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in + let w: Double = Double(size.width) + let h: Double = Double(size.height) + let bg: (r: Double, g: Double, b: Double) = Self.backgroundRGB + ctx.setColor(r: bg.r, g: bg.g, b: bg.b) + ctx.rectangle(x: 0, y: 0, width: w, height: h) + ctx.fill() + guard model.magnitudes.count > 1 else { return } + if waterfallRows > 0 { + _drawWaterfall(ctx: ctx, width: w, height: h) + } else { + _drawSpectrum(ctx: ctx, width: w, height: h) + } + }) + .onAppear { model.start() } + .onDisappear { model.stop() } + } + + // MARK: - Spectrum line + + private func _drawSpectrum(ctx: DrawingContext, width: Double, height: Double) { + let mags: [Float] = model.magnitudes + + // Zero-dB guide line. + let zeroY: Double = height * (1.0 - _dbFrac(Float(1.0))) + ctx.setColor(r: 1.0, g: 1.0, b: 1.0, a: Self.zeroLineOpacity) + ctx.setLineWidth(0.5) + ctx.moveTo(x: 0, y: zeroY) + ctx.lineTo(x: width, y: zeroY) + ctx.stroke() + + let halfSize: Int = capture.fftSize / 2 + let line: (r: Double, g: Double, b: Double) = Self.spectrumRGB + ctx.setColor(r: line.r, g: line.g, b: line.b) + ctx.setLineWidth(Self.spectrumLineWidth) + var started: Bool = false + for k: Int in 0...halfSize { + guard k < mags.count else { break } + let xFrac: Double = _xFrac(bin: k) + guard xFrac >= 0 && xFrac <= 1 else { continue } + let x: Double = xFrac * width + let y: Double = height * (1.0 - _dbFrac(mags[k])) + if !started { + ctx.moveTo(x: x, y: y) + started = true + } else { + ctx.lineTo(x: x, y: y) + } + } + ctx.stroke() + } + + // MARK: - Waterfall + + private func _drawWaterfall(ctx: DrawingContext, width: Double, height: Double) { + let hist: [[Float]] = model.history + guard !hist.isEmpty else { return } + let rowH: Double = height / Double(waterfallRows) + let halfSize: Int = capture.fftSize / 2 + // Number of horizontal pixel columns to iterate over. + let cols: Int = max(1, Int(width)) + + for (rowIdx, rowMags) in hist.enumerated() { + guard rowIdx < waterfallRows else { break } + let y: Double = Double(rowIdx) * rowH + + var prevX: Double = 0 + for col: Int in 0..= 0 && bin < rowMags.count else { continue } + + let x: Double = Double(col) + let dbFrac: Double = _dbFrac(rowMags[bin]) + if x > prevX { + let brightness: Double = dbFrac + let color: Color = Color( + hue: Self.waterfallHue, + saturation: min(1.0, brightness * Self.waterfallSaturationBoost), + brightness: brightness + ) + ctx.setColor(r: color.red, g: color.green, b: color.blue) + ctx.rectangle(x: prevX, y: y, width: x - prevX, height: rowH) + ctx.fill() + } + prevX = x + } + } + } + + // MARK: - Coordinate helpers + + /// Normalized X position [0, 1] for `bin` on a log-frequency axis. + /// Returns values outside [0, 1] for bins outside [minHz, maxHz]. + private func _xFrac(bin: Int) -> Double { + let freq: Double = Double(bin) * sampleRate / Double(capture.fftSize) + guard freq > 0 else { return -1 } + return log(freq / minHz) / log(maxHz / minHz) + } + + /// Normalized Y position [0, 1] for a linear magnitude value. + /// 0 = `floorDB`, 1 = `ceilDB`. + private func _dbFrac(_ mag: Float) -> Double { + let db: Double = 20.0 * log10(max(Self.magnitudeFloor, Double(mag))) + return max(0, min(1, (db - floorDB) / (ceilDB - floorDB))) + } +} +#endif diff --git a/Sources/LyrebirdUI/LyrebirdStatusView.swift b/Sources/LyrebirdUI/LyrebirdStatusView.swift index ebb2664..d515b42 100644 --- a/Sources/LyrebirdUI/LyrebirdStatusView.swift +++ b/Sources/LyrebirdUI/LyrebirdStatusView.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -89,3 +90,145 @@ private struct CPURow: View { } } } + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdStatusView`: a compact live +// readout of a `SynthesisEngine`'s average and peak CPU load, as two colour-coded +// bars with percentage labels. +// +// Live update reuses the scope's pattern — an `@Observable` model polled by a +// Foundation `Timer` on `RunLoop.main` (pumped by the GTK4 backend), NOT +// SwiftOpenUI's off-main `.task`. Labels and percentages are real `Text` views +// (`DrawingContext` has no text drawing); only the bar itself is a `Canvas`. +// +// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift). +import SwiftOpenUI +import BackendGTK4 +import LyrebirdSynth +import Observation +import Foundation + +/// Default CPU-meter poll interval, in seconds (≈ 10 Hz). +private let linuxStatusDefaultPollInterval: TimeInterval = 0.1 + +/// Polls a `SynthesisEngine`'s CPU meters on a main-thread timer and publishes +/// them for ``LyrebirdStatusView`` to draw. Internal — only the view is public. +/// +/// `@unchecked Sendable`: main-thread-confined (the poll `Timer` fires on +/// `RunLoop.main`; all access is on that thread), but `Timer`'s block is +/// `@Sendable`, so the capture requires the conformance — same rationale as +/// `LyrebirdScopeModel` / `UIParamNode`. +@Observable +final class LyrebirdStatusModel: @unchecked Sendable { + + var averageCPU: Double = 0.0 + var peakCPU: Double = 0.0 + + @ObservationIgnored private var timer: Timer? + @ObservationIgnored private let engine: SynthesisEngine + @ObservationIgnored private let pollInterval: TimeInterval + + init( + engine: SynthesisEngine, + pollInterval: TimeInterval = linuxStatusDefaultPollInterval + ) { + self.engine = engine + self.pollInterval = pollInterval + } + + deinit { + timer?.invalidate() + } + + func start() { + guard timer == nil else { return } + let t: Timer = Timer.scheduledTimer(withTimeInterval: pollInterval, repeats: true) { [weak self] _ in + guard let self else { return } + self.averageCPU = self.engine.averageCPU + self.peakCPU = self.engine.peakCPU + } + timer = t + } + + func stop() { + timer?.invalidate() + timer = nil + } +} + +/// A compact real-time CPU-load readout for the Linux/GTK4 UI. Mirrors +/// `LyrebirdUI.LyrebirdStatusView`: average and peak block-fraction load as two +/// bars — green below 50 %, yellow 50–80 %, red above 80 %. `1.0` = one full +/// block consumed; `> 1.0` = over budget (xruns likely). +public struct LyrebirdStatusView: View { + + @State private var model: LyrebirdStatusModel + + /// Creates a CPU-load readout for the given engine. + /// + /// - Parameter engine: The `SynthesisEngine` to monitor. + public init(engine: SynthesisEngine) { + _model = State(wrappedValue: LyrebirdStatusModel(engine: engine)) + } + + public var body: some View { + VStack(alignment: .leading) { + LinuxCPURow(label: "CPU Avg", value: model.averageCPU) + LinuxCPURow(label: "CPU Peak", value: model.peakCPU) + } + .onAppear { model.start() } + .onDisappear { model.stop() } + } +} + +/// One labelled CPU bar. Private — an implementation detail of ``LyrebirdStatusView``. +private struct LinuxCPURow: View { + let label: String + let value: Double // 0.0 = idle, 1.0 = full block, > 1.0 = overload + + private let labelWidth: Double = 60 + private let percentWidth: Double = 52 + private let barWidth: Double = 120 + private let barHeight: Double = 8 + private let maxDisplayPercent: Double = 999.9 + private let warningThreshold: Double = 0.5 + private let criticalThreshold: Double = 0.8 + + var body: some View { + HStack { + Text(label) + .monospacedDigit() + .frame(minWidth: labelWidth, alignment: .leading) + Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in + let w: Double = Double(size.width) + let h: Double = Double(size.height) + // Track. + ctx.setColor(r: 0.5, g: 0.5, b: 0.5, a: 0.15) + ctx.rectangle(x: 0, y: 0, width: w, height: h) + ctx.fill() + // Filled portion, clamped to the track width. + let frac: Double = min(max(value, 0.0), 1.0) + let rgb: (r: Double, g: Double, b: Double) = barColor + ctx.setColor(r: rgb.r, g: rgb.g, b: rgb.b) + ctx.rectangle(x: 0, y: 0, width: w * frac, height: h) + ctx.fill() + }) + .frame(width: barWidth, height: barHeight) + Text(percentText) + .monospacedDigit() + .frame(minWidth: percentWidth, alignment: .trailing) + } + } + + private var barColor: (r: Double, g: Double, b: Double) { + if value < warningThreshold { return (0.0, 0.8, 0.0) } // green + if value < criticalThreshold { return (1.0, 0.8, 0.0) } // yellow + return (1.0, 0.2, 0.2) // red + } + + private var percentText: String { + let displayPercent: Double = min(value * 100.0, maxDisplayPercent) + return String(format: "%.1f%%", displayPercent) + } +} +#endif diff --git a/Sources/LyrebirdUI/LyrebirdSynthView.swift b/Sources/LyrebirdUI/LyrebirdSynthView.swift index 6f365b6..8343e60 100644 --- a/Sources/LyrebirdUI/LyrebirdSynthView.swift +++ b/Sources/LyrebirdUI/LyrebirdSynthView.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +#if canImport(SwiftUI) import SwiftUI import LyrebirdSynth @@ -97,7 +98,7 @@ public struct LyrebirdSynthView: View { } /// One discovered `@UIParam` slot, paired with its display name + range. - public struct Entry: Identifiable { + public struct Entry: Identifiable, Sendable { public let id: String public let propertyName: String public let displayName: String @@ -173,3 +174,129 @@ public let lyrebirdSynthViewDefaultMin: Double = 0 /// Default upper bound used when `parameterMetadata` does not supply a range. public let lyrebirdSynthViewDefaultMax: Double = 1 + +#else +// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdSynthView`: an auto-generated +// parameter grid for a `SynthesizerBase` subclass, one ``ParameterKnob`` per +// `@UIParam` slot. The `@UIParam` discovery (`Mirror` walk), the ``Entry`` type, +// and the range/default constants are identical to the Apple side — only the +// `body` swaps the SwiftUI `ScrollView`/`LazyVGrid` for SwiftOpenUI's data-based +// `LazyVGrid` (`columns:data:content:`, no per-item ForEach). Adaptive columns +// map onto GtkGridView's min-column-count behaviour. +// +// SwiftOpenUI is always present in this target (see Package.swift), so no +// `canImport` guard is needed. +import SwiftOpenUI +import LyrebirdSynth + +/// Auto-generated parameter grid for a `SynthesizerBase` subclass on Linux/GTK4. +/// Mirrors `LyrebirdUI.LyrebirdSynthView`: walks the synth's `Mirror` chain for +/// `@UIParam` slots and renders one ``ParameterKnob`` per slot in an adaptive +/// grid. Same public API/init as the Apple side. +/// +/// **`@UIParam` only.** `@LiveParam` slots are skipped — they have no +/// `@Observable` projected value to drive a knob. +public struct LyrebirdSynthView: View { + + public let entries: [Entry] + + /// - Parameter synth: The `SynthesizerBase` instance to introspect. + /// + /// > Note: The Apple side also accepts a `[String: LyrebirdAUParameterInfo]` + /// > metadata dictionary for per-knob ranges, but that type lives under + /// > `#if canImport(AudioToolbox)` (Apple-only), so on Linux every slot uses + /// > the default `lyrebirdSynthViewDefaultMin...Max` range. Pass pre-built + /// > ``Entry`` values via `init(entries:)` for custom ranges. + public init(synth: SynthesizerBase) { + self.entries = LyrebirdSynthView.discover(synth: synth) + } + + /// - Parameter entries: Pre-built list of discovered entries. + public init(entries: [Entry]) { + self.entries = entries + } + + public var body: some View { + ScrollView { + LazyVGrid( + columns: [GridItem(.adaptive(minimum: lyrebirdSynthViewColumnMinWidth))], + data: entries + ) { entry in + ParameterKnob( + entry.displayName, + node: entry.node, + range: entry.range + ) + } + .padding() + } + } + + /// One discovered `@UIParam` slot, paired with its display name + range. + public struct Entry: Identifiable, Sendable { + public let id: String + public let propertyName: String + public let displayName: String + public let node: UIParamNode + public let range: ClosedRange + + public init( + propertyName: String, + displayName: String, + node: UIParamNode, + range: ClosedRange + ) { + self.id = propertyName + self.propertyName = propertyName + self.displayName = displayName + self.node = node + self.range = range + } + } + + /// Walks the synth's `Mirror` (with superclass chain) looking for `@UIParam` + /// properties and emits one ``Entry`` per slot. Slot order matches the + /// `Mirror` walk used by `SynthesizerBase._autoRegisterLiveParams()`. Every + /// slot uses the default range (no `LyrebirdAUParameterInfo` on Linux). + public static func discover(synth: SynthesizerBase) -> [Entry] { + var entries: [Entry] = [] + var mirrors: [Mirror] = [] + var current: Mirror? = Mirror(reflecting: synth) + while let m: Mirror = current { + mirrors.append(m) + current = m.superclassMirror + } + let range: ClosedRange = lyrebirdSynthViewDefaultMin...lyrebirdSynthViewDefaultMax + for mirror: Mirror in mirrors.reversed() { + for child: Mirror.Child in mirror.children { + guard let label: String = child.label else { continue } + let key: String = label.hasPrefix("_") ? String(label.dropFirst()) : label + guard let wrapper: any LiveParameterWrapper = child.value as? LiveParameterWrapper else { continue } + guard let node: UIParamNode = wrapper._projectedAsValidInput as? UIParamNode else { continue } + entries.append(Entry( + propertyName: key, + displayName: key, + node: node, + range: range + )) + } + } + return entries + } +} + +/// Minimum column width (points) for ``LyrebirdSynthView``'s adaptive grid. +public let lyrebirdSynthViewColumnMinWidth: Double = 120 + +// NOTE: the Apple side's `lyrebirdSynthViewGridSpacing` / `lyrebirdSynthViewItemSpacing` +// are intentionally absent on Linux — SwiftOpenUI's `LazyVGrid(columns:data:content:)` +// exposes no per-item spacing parameter (grid layout is driven by GtkGridView's +// column count), so there is nothing to apply them to. The Linux grid uses +// GtkGridView's default gutter. + +/// Default lower bound used when `parameterMetadata` does not supply a range. +public let lyrebirdSynthViewDefaultMin: Double = 0 + +/// Default upper bound used when `parameterMetadata` does not supply a range. +public let lyrebirdSynthViewDefaultMax: Double = 1 +#endif diff --git a/Sources/LyrebirdUI/LyrebirdUIExports.swift b/Sources/LyrebirdUI/LyrebirdUIExports.swift new file mode 100644 index 0000000..eb92f72 --- /dev/null +++ b/Sources/LyrebirdUI/LyrebirdUIExports.swift @@ -0,0 +1,16 @@ +// LyrebirdUIExports.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if canImport(SwiftUI) +// Re-export SwiftUI so downstream Apple app / synth code needs only +// `import LyrebirdUI` to get both the Lyrebird controls and the SwiftUI View +// DSL they build on. The Linux counterpart is `LyrebirdUILinuxExports.swift` +// in this same module (guarded `#if !canImport(SwiftUI)`), which re-exports +// SwiftOpenUI + BackendGTK4. Downstream code writes one `import LyrebirdUI` on +// every platform; the control bodies switch backend by `#if canImport(SwiftUI)` +// beneath, both binding the same core `@UIParam` / `UIParamNode` model. +@_exported import SwiftUI +#endif diff --git a/Sources/LyrebirdUI/LyrebirdUILinuxExports.swift b/Sources/LyrebirdUI/LyrebirdUILinuxExports.swift new file mode 100644 index 0000000..631ec7c --- /dev/null +++ b/Sources/LyrebirdUI/LyrebirdUILinuxExports.swift @@ -0,0 +1,24 @@ +// LyrebirdUILinuxExports.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// Re-exports so downstream Linux app / synth code needs only +// `import LyrebirdUILinux` to get the SwiftOpenUI View DSL *and* the GTK4 +// backend's `DrawingContext` drawing methods (setColor/arc/moveTo/stroke), +// which live as extensions in `BackendGTK4` rather than SwiftOpenUI's core. +// +// This mirrors how, on Apple platforms, importing a UI umbrella brings the +// underlying toolkit along — the goal is one platform `#if` at the import site +// (`import LyrebirdUI` vs `import LyrebirdUILinux`) and identical body code +// beneath it, since both bind the same core `@UIParam` / `UIParamNode` model. +// +// Both modules are guaranteed present inside this target: `Package.swift` only +// appends `LyrebirdUILinux` together with its `SwiftOpenUI` + `BackendGTK4` +// dependencies (Linux, `LYREBIRD_ENABLE_LINUX_UI=1`), so no `canImport` guard +// is needed here. +#if !canImport(SwiftUI) +@_exported import SwiftOpenUI +@_exported import BackendGTK4 +#endif diff --git a/Sources/LyrebirdUI/LyrebirdWindow.swift b/Sources/LyrebirdUI/LyrebirdWindow.swift index 7a3a122..a61b552 100644 --- a/Sources/LyrebirdUI/LyrebirdWindow.swift +++ b/Sources/LyrebirdUI/LyrebirdWindow.swift @@ -5,6 +5,7 @@ // SPDX-License-Identifier: MIT #if os(macOS) +#if canImport(SwiftUI) import AppKit import SwiftUI @@ -159,3 +160,125 @@ public final class LyrebirdWindow { } } #endif + +#elseif os(Linux) +import Foundation +import SwiftOpenUI +import BackendGTK4 + +/// LyrebirdWindow — a standalone GTK4 window hosting SwiftOpenUI content. +/// +/// The Linux counterpart to the macOS `NSWindow` + `NSHostingController` host. +/// Opens a top-level `GtkApplicationWindow` (via +/// `GTK4Backend.openStandaloneWindow`) whose child is the rendered SwiftOpenUI +/// view. Same public shape as the macOS side — `init(title:width:height:)`, +/// `open(content:)`, `close()` — so `presentInWindow(...)` convenience methods +/// work identically on both platforms. +/// +/// ## Requirements +/// +/// A `GtkApplication` main loop must already be running — i.e. the process is +/// inside `GTK4Backend().run(App)`. Opening a window from a CLI/REPL with no +/// running application is a no-op (`open` leaves the window closed); use the +/// declarative `App`/`WindowGroup` scene as the process entry point, then open +/// further windows imperatively with `LyrebirdWindow`. +/// +/// ## Threading +/// +/// GTK is single-threaded; every method must run on the GTK main thread. Unlike +/// the macOS `@MainActor` class, this is left nonisolated to match the rest of +/// the Linux/GTK4 UI and the SwiftOpenUI backend, which are all confined to the +/// GTK main loop rather than the Swift main actor — a nonisolated SwiftOpenUI +/// `body` and `Button` action can then drive it without an actor hop. +public final class LyrebirdWindow { + + // MARK: - Configuration + + /// Window title-bar text. + public let title: String + + /// Initial window width in points. + public let width: Double + + /// Initial window height in points. + public let height: Double + + // MARK: - Private state + + private var handle: GTK4StandaloneWindowHandle? + + /// Bumped on every `open()`. The `onClose` closure captures the generation + /// live at open time and only clears `handle` if it still matches, so a stale + /// destroy signal from a previously-closed window (were it ever delivered + /// asynchronously) can't null out a newer window's handle on rapid reuse. + private var generation: Int = 0 + + // MARK: - Init + + /// Creates a `LyrebirdWindow` with the given display properties. + /// + /// The window is not shown until `open(content:)` is called. + /// + /// - Parameters: + /// - title: Text shown in the window's title bar. + /// - width: Initial window width (default 400 pt). + /// - height: Initial window height (default 300 pt). + public init( + title: String = "Lyrebird", + width: Double = 400, + height: Double = 300 + ) { + self.title = title + self.width = width + self.height = height + } + + // MARK: - State + + /// Whether a window is currently open for this instance. + public var isOpen: Bool { handle?.isOpen ?? false } + + // MARK: - Open + + /// Opens the window and displays the provided SwiftOpenUI content. + /// + /// If a window is already open for this instance, it is closed and replaced + /// with a new one hosting the updated content. If no `GtkApplication` is + /// running, this is a no-op. + /// + /// - Parameter content: A `@ViewBuilder` closure returning any SwiftOpenUI + /// `View`. + public func open(@ViewBuilder content: () -> Content) { + closeWindow() + generation &+= 1 + let token: Int = generation + // `onClose` fires on the GTK main thread when the user closes the window; + // clear our handle so `isOpen` reflects it — but only if this is still the + // current window (guard against a stale callback from a replaced one). + handle = GTK4Backend.openStandaloneWindow( + title: title, + width: Int(width), + height: Int(height), + onClose: { [weak self] in + guard let self, self.generation == token else { return } + self.handle = nil + }, + content: content + ) + } + + // MARK: - Close + + /// Closes and destroys the window. + public func close() { + closeWindow() + } + + // MARK: - Private + + private func closeWindow() { + handle?.close() + handle = nil + } +} +#endif diff --git a/Sources/LyrebirdUI/MouseTracker.swift b/Sources/LyrebirdUI/MouseTracker.swift index 79429ce..88c25b3 100644 --- a/Sources/LyrebirdUI/MouseTracker.swift +++ b/Sources/LyrebirdUI/MouseTracker.swift @@ -5,6 +5,7 @@ // SPDX-License-Identifier: MIT #if os(macOS) +#if canImport(SwiftUI) import AppKit import Synchronization import LyrebirdSynth @@ -160,4 +161,113 @@ private let mouseButtonReleased: Double = 0.0 private let normalizedMin: Double = 0.0 private let normalizedMax: Double = 1.0 -#endif // os(macOS) +#endif // canImport(SwiftUI) + +#elseif os(Linux) +import Synchronization +import LyrebirdSynth +import BackendGTK4 + +/// Linux `MouseInputBridge` conformer driven by a window-local GTK pointer +/// source (`GtkEventControllerMotion` + `GtkGestureClick`), the GTK4 counterpart +/// to the macOS `NSEvent`-monitor `MouseTracker`. +/// +/// Position is normalised to the window the pointer is over: +/// - `x` = 0 (left edge) … 1 (right edge) +/// - `y` = 0 (bottom edge) … 1 (top edge) — flipped from GTK's top-left origin +/// - `button` = 0.0 (released) or 1.0 (primary button held) +/// +/// Values are exposed via lock-free `Synchronization.Atomic` reads, +/// safe for the audio render thread, exactly like the macOS tracker. +/// +/// Install once at app startup so `Mouse.X.Control()` / `Mouse.Y.Control()` / +/// `Mouse.Click.Control()` read live values: +/// +/// ```swift +/// import LyrebirdSynth +/// import LyrebirdUI +/// +/// MouseTracker.installShared() +/// ``` +/// +/// Unlike macOS this is window-local: it reports while the pointer is over one +/// of the app's windows (SwiftOpenUI attaches the controllers to every window +/// it opens). `x` / `y` are fully covered; `button` is best-effort — a +/// window-level click gesture sees presses not consumed by an interactive child. +/// +/// ## Threading +/// +/// `installShared()` and the forwarded pointer callbacks run on the GTK main +/// thread. No `@MainActor` — the Linux UI is GTK-main-loop-confined, not on the +/// Swift main actor (see `LyrebirdWindow`). +public final class MouseTracker: MouseInputBridge, @unchecked Sendable { + // Sendable invariant: `_x`/`_y`/`_button`/`_installed` are immutable `Atomic`s — + // all reads/writes lock-free. The pointer-sink closures are set once (gated by + // the `_installed` CAS) and only store into those atomics. + + /// Process-wide `MouseTracker` instance. + public static let shared: MouseTracker = MouseTracker() + + private let _x: Atomic + private let _y: Atomic + private let _button: Atomic + private let _installed: Atomic = Atomic(false) + + /// Allocates the atomic state slots. Does not install the pointer sink — + /// `installShared()` does that. + public override init() { + _x = Atomic(mouseTrackerInitialPosition) + _y = Atomic(mouseTrackerInitialPosition) + _button = Atomic(mouseButtonReleased) + super.init() + } + + // MARK: - MouseInputBridge overrides + + public override var x: Double { _x.load(ordering: .relaxed) } + public override var y: Double { _y.load(ordering: .relaxed) } + public override var button: Double { _button.load(ordering: .relaxed) } + + // MARK: - Install + + /// Installs `MouseTracker.shared` as the active `MouseInput` bridge AND + /// registers the GTK pointer sink. Idempotent via the `_installed` atomic CAS. + /// + /// Install timing is not sensitive: SwiftOpenUI attaches the pointer + /// controllers to every window it opens and reads the installed sink at event + /// time, so calling this before or after `GTK4Backend().run(_:)` both work. + public static func installShared() { + shared._installIfNeeded() + } + + private func _installIfNeeded() { + let (exchanged, _) = _installed.compareExchange( + expected: false, desired: true, ordering: .acquiringAndReleasing) + guard exchanged else { return } + + MouseInput.install(self) + GTK4PointerTracking.install( + onMove: { [weak self] (nx: Double, ny: Double) in + // Clamp to [0, 1] to honour the normalized-range contract even if + // an edge/drag-out event reports slightly out of bounds — parity + // with the macOS tracker's clamp. + self?._x.store(min(max(nx, 0.0), 1.0), ordering: .relaxed) + self?._y.store(min(max(ny, 0.0), 1.0), ordering: .relaxed) + }, + onButton: { [weak self] (pressed: Bool) in + self?._button.store( + pressed ? mouseButtonPressed : mouseButtonReleased, + ordering: .relaxed + ) + } + ) + } +} + +// MARK: - MouseTracker constants + +private let mouseTrackerInitialPosition: Double = 0.5 +private let mouseButtonPressed: Double = 1.0 +private let mouseButtonReleased: Double = 0.0 + +#endif // os(macOS) / os(Linux) diff --git a/Sources/LyrebirdUILinuxDemo/EventVoiceSynth.swift b/Sources/LyrebirdUILinuxDemo/EventVoiceSynth.swift new file mode 100644 index 0000000..fc0254b --- /dev/null +++ b/Sources/LyrebirdUILinuxDemo/EventVoiceSynth.swift @@ -0,0 +1,30 @@ +// EventVoiceSynth.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// A fixed-pitch sine voice added by a `LyrebirdProcess` body in the events demo +/// (`LYREBIRD_DEMO=events`). The process's own envelope gates it, so firing an +/// event in the `LyrebirdEventListPerformanceView` starts an audible, visibly +/// "running" process strip. +final class EventVoiceSynth: SynthesizerBase { + + /// Output gain, kept low so several stacked voices don't clip. + private let voiceGain: Double = 0.12 + + private let voiceFreq: Double + + /// - Parameter freq: Oscillator frequency in Hz. + init(freq: Double) { + self.voiceFreq = freq + super.init() + } + + override func build() { + let osc: OscSin.Audio = OscSin.Audio(freq: voiceFreq) + output(bus: 0, source: Pan2(input: osc * voiceGain)) + } +} diff --git a/Sources/LyrebirdUILinuxDemo/KnobDemoSynth.swift b/Sources/LyrebirdUILinuxDemo/KnobDemoSynth.swift new file mode 100644 index 0000000..7b91f52 --- /dev/null +++ b/Sources/LyrebirdUILinuxDemo/KnobDemoSynth.swift @@ -0,0 +1,22 @@ +// KnobDemoSynth.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// A minimal sine-tone synthesizer whose frequency and amplitude are `@UIParam` +/// slots, so the Linux GTK4 knobs bind to the same RT-safe parameter model the +/// macOS SwiftUI controls use. Turning a knob updates the atomic the render +/// thread reads at the next block — audible immediately when a live ALSA device +/// is present. +final class KnobDemoSynth: SynthesizerBase { + @UIParam var frequency: Double = 220.0 + @UIParam var amplitude: Double = 0.2 + + override func build() { + let osc: OscSin.Audio = OscSin.Audio(freq: $frequency) + output(bus: 0, source: Pan2(input: osc * $amplitude)) + } +} diff --git a/Sources/LyrebirdUILinuxDemo/KnobDemoView.swift b/Sources/LyrebirdUILinuxDemo/KnobDemoView.swift new file mode 100644 index 0000000..b3b5811 --- /dev/null +++ b/Sources/LyrebirdUILinuxDemo/KnobDemoView.swift @@ -0,0 +1,391 @@ +// KnobDemoView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth // UIParamNode +import LyrebirdUI // View DSL + ParameterKnob, via @_exported re-exports +import Foundation // CGSize (narrowtest Canvas renderer) +import Observation // @Observable (mouse readout model) + +/// Two knobs bound to a synthesizer's `@UIParam` slots — frequency and +/// amplitude. Drag up to increase; the sine tone tracks in real time. +/// +/// The view holds the projected `UIParamNode`s directly rather than the +/// `SynthesizerBase`. `SynthesizerBase` is `@MainActor`-isolated, so reading +/// `synth.$frequency` is only legal from a main-actor context — and SwiftOpenUI's +/// `View.body` is *nonisolated* (unlike SwiftUI's `@MainActor` body). So the +/// caller extracts the nodes on the main actor (`main.swift` top-level code is +/// `@MainActor`) and hands them in; `UIParamNode` itself is not actor-isolated, +/// so reading `node.value` from the nonisolated body is fine. +struct KnobDemoView: View { + let frequencyNode: UIParamNode + let amplitudeNode: UIParamNode + let scope: ScopeCapture + let envelope: Envelope + let engine: SynthesisEngine + + /// Frequency knob range, in Hz — roughly A2…A5. + private let freqMin: Double = 110.0 + private let freqMax: Double = 880.0 + + /// Values the reset button restores. + private let resetFreq: Double = 220.0 + private let resetAmp: Double = 0.2 + + var body: some View { + VStack { + Text("Lyrebird — Linux UI demo") + // Live CPU-load meters (engine average / peak). + LyrebirdStatusView(engine: engine) + // Live oscilloscope of the stereo output. + LyrebirdScopeView(capture: scope) + // Static plot of an example envelope (cyan pre-loop, green loop, + // orange release; dashed markers at the loop/release boundaries). + LyrebirdEnvelopeView(envelope) + // XY pad drives both nodes at once (X = freq, Y = amp); it shares the + // same nodes as the controls below, so all of them stay in sync. + ParameterXY( + xLabel: "freq", xNode: frequencyNode, xRange: freqMin...freqMax, + yLabel: "amp", yNode: amplitudeNode, yRange: 0.0...1.0 + ) + // Knob and slider bind the SAME node, so moving one updates the + // other — the shared `@UIParam` model observed from several controls. + ParameterKnob("freq", node: frequencyNode, range: freqMin...freqMax) + ParameterSlider("freq", node: frequencyNode, range: freqMin...freqMax, taper: .exponential) + ParameterLabel("freq (Hz)", node: frequencyNode, decimalPlaces: 1) + ParameterKnob("amp", node: amplitudeNode, range: 0.0...1.0) + ParameterSlider("amp", node: amplitudeNode, range: 0.0...1.0) + // Toggle gates the amp node on/off (0 ↔ 1); the amp knob/slider + // follow it, since all three observe the same node. Highlights when on. + ParameterButton("gate", node: amplitudeNode, style: .toggle) + // Momentary: restores defaults. Writes through the nodes (not the + // @MainActor synth), so it is callable from the nonisolated handler. + ParameterButton("reset") { + frequencyNode.update(resetFreq) + amplitudeNode.update(resetAmp) + } + } + .padding() + } +} + +// MARK: - Diagnostic variants (selected by the LYREBIRD_DEMO env var) + +/// Diagnostic: a single knob, nothing else. Isolates the control from the +/// multi-view / animation context. +struct DemoKnobOnlyView: View { + let frequencyNode: UIParamNode + + private let freqMin: Double = 110.0 + private let freqMax: Double = 880.0 + + var body: some View { + VStack { + Text("knob only") + ParameterKnob("freq", node: frequencyNode, range: freqMin...freqMax) + } + .padding() + } +} + +/// Diagnostic: all parameter controls, but NO animated views (scope / CPU) and +/// no envelope. Isolates the interactive controls from the timer-driven redraws. +struct DemoControlsView: View { + let frequencyNode: UIParamNode + let amplitudeNode: UIParamNode + + private let freqMin: Double = 110.0 + private let freqMax: Double = 880.0 + private let resetFreq: Double = 220.0 + private let resetAmp: Double = 0.2 + + var body: some View { + VStack { + Text("controls (no animated views)") + ParameterXY( + xLabel: "freq", xNode: frequencyNode, xRange: freqMin...freqMax, + yLabel: "amp", yNode: amplitudeNode, yRange: 0.0...1.0 + ) + ParameterKnob("freq", node: frequencyNode, range: freqMin...freqMax) + ParameterSlider("freq", node: frequencyNode, range: freqMin...freqMax, taper: .exponential) + ParameterLabel("freq (Hz)", node: frequencyNode, decimalPlaces: 1) + ParameterKnob("amp", node: amplitudeNode, range: 0.0...1.0) + ParameterSlider("amp", node: amplitudeNode, range: 0.0...1.0) + ParameterButton("gate", node: amplitudeNode, style: .toggle) + ParameterButton("reset") { + frequencyNode.update(resetFreq) + amplitudeNode.update(resetAmp) + } + } + .padding() + } +} + +/// Showcase of the ported diagnostics / monitor views (`LYREBIRD_DEMO=monitors`): +/// the parameter knobs, a `LyrebirdScatterView`, a per-bin `MultiSlider`, and +/// `LyrebirdEngineStatusView` — the last of which itself embeds the node-tree and +/// message sections, so it exercises `LyrebirdNodeTreeView` + +/// `LyrebirdMessageBanner`/`LyrebirdMessageView` too. +/// +/// No outer `ScrollView`: a GTK `ScrolledWindow` pans on pointer-drag, which +/// fights the Canvas controls' own drag gestures (dragging a knob or the +/// MultiSlider would scroll the page). Instead the panels are split into two +/// side-by-side columns so the total height fits without scrolling — the tall +/// `LyrebirdEngineStatusView` gets its own column. Widen (or the panels stack +/// off-screen); the knobs are placed directly (not the scrolling +/// `LyrebirdSynthView` grid) to keep them drag-friendly. +struct DemoMonitorsView: View { + let entries: [LyrebirdSynthView.Entry] + let scatter: [Double] + let multiBuffer: LyrebirdBuffer + let multiCount: Int + let engine: SynthesisEngine + let onEngineStarted: (() -> Void)? + + var body: some View { + HStack(alignment: .top, spacing: 20) { + // Left column: knobs + read-only visualisers + the per-bin slider. + VStack(alignment: .leading) { + Text("Lyrebird — Linux monitors demo") + + HStack { + ForEach(entries) { entry in + ParameterKnob(entry.displayName, node: entry.node, range: entry.range) + } + } + + Text("Scatter (LyrebirdScatterView)") + LyrebirdScatterView(scatter) + + Text("Per-bin MultiSlider — drag to edit") + MultiSlider(buffer: multiBuffer, count: multiCount, range: 0.0...1.0, height: 100) + } + + // Right column: the tall engine-status panel (embeds node tree + + // messages + config + output). + LyrebirdEngineStatusView( + engine: engine, + onEngineStarted: onEngineStarted + ) + } + .padding() + } +} + +/// Narrow-path isolation view (`LYREBIRD_DEMO=narrowtest`). A Canvas slider plus a +/// `Text` readout and an editable `TextField`, each wrapped in the modifiers that +/// used to poison the narrow-mutation path (`.onChange` / `.focused` / +/// `.textFieldStyle` / `.onSubmit` / `.monospacedDigit`). Crucially it contains NO +/// opaque Class-2 widgets (no Picker/Stepper/Toggle), so it isolates the Phase-1a +/// transparent-describe fix: if dragging the slider updates the label AND the +/// field LIVE (not only at mouse-up), the transparent-describe fix works and the opaque-leaf fix is worth doing. +struct DemoNarrowTestView: View { + @State private var db: Double = -6.0 + @State private var dbText: String = "-6.0" + @FocusState private var focused: Bool + + private let lo: Double = -12 + private let hi: Double = 12 + private let trackWidth: Double = 220 + private let trackHeight: Double = 24 + private let thumbRadius: Double = 7 + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Narrow-path test") + Text("Drag the slider: the label and the text field should track LIVE.") + .font(.caption) + .foregroundStyle(.secondary) + + HStack(spacing: 8) { + Text("Gain") + .frame(width: 44, alignment: .leading) + slider + // Live label wrapped in ex-poison modifiers. + Text(String(format: "%+.1f dB", db)) + .font(.caption) + .monospacedDigit() + .frame(width: 70, alignment: .trailing) + .onChange(of: db) { _, _ in } + // Editable field wrapped in ex-poison modifiers. + TextField("dB", text: $dbText) + .font(.caption) + .monospacedDigit() + .focused($focused) + .frame(width: 70) + .textFieldStyle(.roundedBorder) + .onSubmit { } + .onChange(of: dbText) { _, _ in } + } + } + .padding() + } + + private var slider: some View { + Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in + let w: Double = Double(size.width) + let h: Double = Double(size.height) + let cy: Double = h / 2 + let x0: Double = thumbRadius + let x1: Double = w - thumbRadius + let usable: Double = max(x1 - x0, 1) + let span: Double = hi - lo + let pos: Double = span > 0 ? (db - lo) / span : 0 + let thumbX: Double = x0 + min(1, max(0, pos)) * usable + ctx.setColor(r: 0.20, g: 0.20, b: 0.20) + ctx.setLineWidth(4) + ctx.moveTo(x: x0, y: cy) + ctx.lineTo(x: x1, y: cy) + ctx.stroke() + ctx.setColor(r: 0.30, g: 0.80, b: 1.0) + ctx.setLineWidth(4) + ctx.moveTo(x: x0, y: cy) + ctx.lineTo(x: thumbX, y: cy) + ctx.stroke() + ctx.setColor(r: 0.90, g: 0.90, b: 0.95) + ctx.arc(centerX: thumbX, centerY: cy, radius: thumbRadius, + startAngle: 0, endAngle: 2 * Double.pi) + ctx.fill() + }) + .frame(width: trackWidth, height: trackHeight) + .onDrag(minimumDistance: 0, onChanged: { (drag: DragGestureValue) in + let usable: Double = max(trackWidth - 2 * thumbRadius, 1) + let pos: Double = min(1, max(0, (drag.location.x - thumbRadius) / usable)) + let v: Double = lo + pos * (hi - lo) + db = v + dbText = String(format: "%+.1f", v) + }) + } +} + +// MARK: - Mouse input demo (LYREBIRD_DEMO=mouse) + +/// Polls the installed `MouseInput` bridge (fed by `MouseTracker`) on a +/// main-thread `Timer`, publishing normalized pointer state for the readout — +/// same idiom as the CPU / scope models. +/// +/// `@unchecked Sendable`: main-thread-confined (the poll `Timer` fires on +/// `RunLoop.main`; all access is on that thread), but `Timer`'s block is +/// `@Sendable`, so the capture requires the conformance — same rationale as +/// `LyrebirdScopeModel` / `LyrebirdStatusModel`. +@Observable +final class MouseReadoutModel: @unchecked Sendable { + + var x: Double = 0.5 + var y: Double = 0.5 + var button: Double = 0.0 + + @ObservationIgnored private var timer: Timer? + private let pollInterval: TimeInterval = 0.05 // 20 Hz — snappy readout + + deinit { + timer?.invalidate() + } + + func start() { + guard timer == nil else { return } + refresh() + let t: Timer = Timer.scheduledTimer(withTimeInterval: pollInterval, repeats: true) { [weak self] _ in + self?.refresh() + } + timer = t + } + + func stop() { + timer?.invalidate() + timer = nil + } + + private func refresh() { + x = MouseInput.currentX + y = MouseInput.currentY + button = MouseInput.currentButton + } +} + +/// Live readout of the pointer source (`LYREBIRD_DEMO=mouse`). Move the pointer +/// over the window: X→frequency, Y→amplitude drive the `MouseDemoSynth` sine, and +/// the values here should track. Validates the Linux `MouseTracker` + +/// `GtkEventControllerMotion` pointer bridge. +struct DemoMouseView: View { + @State private var model: MouseReadoutModel = MouseReadoutModel() + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Mouse input demo") + Text("Move the pointer over this window (X → frequency, Y → amplitude); click to test the button.") + .font(.caption) + .foregroundStyle(.secondary) + + Text(String(format: "Mouse.X: %.3f", model.x)) + .monospacedDigit() + Text(String(format: "Mouse.Y: %.3f", model.y)) + .monospacedDigit() + Text(String(format: "Mouse.Click: %.0f", model.button)) + .monospacedDigit() + } + .padding() + .onAppear { model.start() } + .onDisappear { model.stop() } + } +} + +// MARK: - Events / process views demo (LYREBIRD_DEMO=events) + +/// On-display exercise of the ported process/event-list views +/// (`LYREBIRD_DEMO=events`). Embeds `LyrebirdEventListPerformanceView` — which +/// itself hosts `LyrebirdEventListView` (transport) plus one `LyrebirdProcessView` +/// strip per running process — and offers buttons to open each view in its own +/// detached `LyrebirdWindow` via `presentInWindow`, so the standalone-window path +/// is exercised for these views too (not just EngineStatus). +/// +/// Press **Next** in the transport to fire the queued events; each starts a +/// sustaining `EventVoiceSynth`, so a running-process strip appears (and a tone +/// sounds when a live audio backend is present). +struct DemoEventsView: View { + let eventList: LyrebirdEventList + let engine: SynthesisEngine + + @State private var perfWindow: LyrebirdWindow? + @State private var listWindow: LyrebirdWindow? + @State private var runningWindow: LyrebirdWindow? + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Lyrebird — Linux events / processes demo") + Text("Press Next to fire events; each starts a process strip below.") + .font(.caption) + .foregroundStyle(.secondary) + + LyrebirdEventListPerformanceView(eventList: eventList, engine: engine) + + HStack(spacing: 8) { + Button { + perfWindow?.close() + perfWindow = LyrebirdEventListPerformanceView.presentInWindow( + eventList: eventList, engine: engine + ) + } label: { + Text("Open Perf Window").font(.caption) + } + Button { + listWindow?.close() + listWindow = LyrebirdEventListView.presentInWindow(eventList: eventList) + } label: { + Text("Open EventList Window").font(.caption) + } + Button { + runningWindow?.close() + runningWindow = LyrebirdRunningProcessesView.presentInWindow( + eventList: eventList, engine: engine + ) + } label: { + Text("Open Running Window").font(.caption) + } + } + } + .padding() + } +} diff --git a/Sources/LyrebirdUILinuxDemo/MouseDemoSynth.swift b/Sources/LyrebirdUILinuxDemo/MouseDemoSynth.swift new file mode 100644 index 0000000..e787a2d --- /dev/null +++ b/Sources/LyrebirdUILinuxDemo/MouseDemoSynth.swift @@ -0,0 +1,28 @@ +// MouseDemoSynth.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// A sine tone driven entirely by the pointer via the `Mouse.*` control +/// generators — no `@UIParam`s. Horizontal position sets frequency, vertical +/// sets amplitude, so moving the pointer over the window sweeps the tone. Used +/// by `LYREBIRD_DEMO=mouse` to validate the Linux `MouseTracker` pointer source. +final class MouseDemoSynth: SynthesizerBase { + + /// Frequency sweep range (Hz), mapped from `Mouse.X` (0…1). + private let freqBase: Double = 110.0 + private let freqSpan: Double = 770.0 // → 110…880 Hz + + /// Amplitude ceiling, mapped from `Mouse.Y` (0…1). + private let ampMax: Double = 0.3 + + override func build() { + let freq: any ValidGeneratorInput = Mouse.X.Control() * freqSpan + freqBase + let amp: any ValidGeneratorInput = Mouse.Y.Control() * ampMax + let osc: OscSin.Audio = OscSin.Audio(freq: freq) + output(bus: 0, source: Pan2(input: osc * amp)) + } +} diff --git a/Sources/LyrebirdUILinuxDemo/main.swift b/Sources/LyrebirdUILinuxDemo/main.swift new file mode 100644 index 0000000..4a9239a --- /dev/null +++ b/Sources/LyrebirdUILinuxDemo/main.swift @@ -0,0 +1,320 @@ +// main.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// Runnable Linux GUI demo for LyrebirdUILinux. Build/run on a Linux host with +// libgtk-4-dev (and libasound2-dev for sound): +// +// LYREBIRD_ENABLE_LINUX_UI=1 swift run LyrebirdUILinuxDemo +// +// Note the import shape: only LyrebirdSynth (engine + @UIParam) and +// LyrebirdUILinux (View DSL + GTK4 backend, via @_exported re-exports). No +// direct SwiftOpenUI / BackendGTK4 imports needed here. +import LyrebirdSynth +import LyrebirdUI +import Foundation // ProcessInfo (demo-mode env var) + +// MARK: - Audio engine + +private let demoBlockSize: Int = 512 +private let demoSampleRate: Double = 44_100.0 +private let demoOutputChannels: Int = 2 +private let demoInputChannels: Int = 0 + +// Core Audio on Apple, ALSA on a Linux build with libasound, else a silent +// OfflineDriver. The GUI runs either way; `isLiveAudioAvailable` reports which. +let demoDriver: any AudioDriver = makeDefaultAudioDriver() + +let demoEngine: SynthesisEngine = SynthesisEngine( + blockSize: demoBlockSize, + sampleRate: demoSampleRate, + numOutputChannels: demoOutputChannels, + numInputChannels: demoInputChannels, + driver: demoDriver +) + +// Oscilloscope tap on the stereo output buses. Must be set before start(). +private let demoScopeBufferSize: Int = 2048 +let demoScope: ScopeCapture = ScopeCapture(buses: [0, 1], bufferSize: demoScopeBufferSize) +demoEngine.scopeTap = demoScope + +let demoSynth: KnobDemoSynth = KnobDemoSynth() + +// Pointer-driven sine for the `mouse` mode (Mouse.X → freq, Mouse.Y → amp). +let mouseSynth: MouseDemoSynth = MouseDemoSynth() + +// Which demo to run — read early so the `monitors` mode can launch with the +// engine OFF (its EngineStatus panel drives Start/Stop). Every other mode starts +// the engine and adds the synth now, since they have no transport control. +let demoMode: String = ProcessInfo.processInfo.environment["LYREBIRD_DEMO"] ?? "full" +let launchEngineRunning: Bool = (demoMode != "monitors") + +// Install the GTK pointer bridge BEFORE `engine.start()` so the `Mouse.*.Control` +// generators see live values with proper happens-before visibility on the RT +// thread (see MouseInput.install docs). Harmless in non-mouse modes — it just +// registers the bridge; SwiftOpenUI only attaches the pointer controllers to the +// windows it opens, and no generator reads it unless a patch uses Mouse.*. +MouseTracker.installShared() + +if launchEngineRunning { + do { + try demoEngine.start() + switch demoMode { + case "mouse": + try demoEngine.add(mouseSynth) + case "events": + break // the LyrebirdEventList schedules its own processes on Next. + default: + try demoEngine.add(demoSynth) + } + } catch { + print("[Lyrebird] demo engine setup failed: \(error)") + } +} + +if !isLiveAudioAvailable { + print("[Lyrebird] no live audio backend — the knobs still work, but there is no sound.") +} + +// `engine.stop()` tears down the node tree AND unbinds every non-persistent synth +// (see the stop() contract in docs/engine/synthesis-engine.md), so no manual +// teardown is needed — the synth just has to be re-added on the next Start. The +// EngineStatus panel's `onEngineStarted` runs this after a successful start. +// `add` is @MainActor; the Start action fires on the GTK main thread, so +// `assumeIsolated` is valid. `demoSynth` is Sendable (@MainActor class); the +// engine is not, so it is bound `nonisolated(unsafe)`. +nonisolated(unsafe) let addEngine: SynthesisEngine = demoEngine +nonisolated(unsafe) let reAddSynthOnStart: () -> Void = { + MainActor.assumeIsolated { + do { + try addEngine.add(demoSynth) + } catch { + print("[Lyrebird] re-add synth on start failed: \(error)") + } + } +} + +// Extract the projected parameter nodes here, in main.swift's top-level +// `@MainActor` context: `SynthesizerBase` is `@MainActor`, so `demoSynth.$…` is +// only reachable on the main actor. The nodes themselves are not actor-isolated, +// so the (nonisolated) SwiftOpenUI view body can read them freely. +let frequencyNode: UIParamNode = demoSynth.$frequency +let amplitudeNode: UIParamNode = demoSynth.$amplitude + +// SwiftOpenUI's scene closure is nonisolated and `SynthesisEngine` is not +// Sendable, so the main-actor top-level `demoEngine` can't be referenced inside +// it directly (unlike the Sendable nodes/scope/envelope). This demo runs entirely +// on the GTK main thread and the status view only reads `engine.averageCPU` / +// `peakCPU` (plain Double loads), so a nonisolated handle is safe here. +nonisolated(unsafe) let statusEngine: SynthesisEngine = demoEngine + +// A static example envelope for the envelope plot (loop node 1, release node 2). +let demoEnvelope: Envelope = Envelope( + levels: [0.0, 1.0, 0.6, 0.0], + durations: [0.01, 0.3, 0.2], + curves: [.sine, .lin, .exponential], + loopNode: 1, + releaseNode: 2 +) + +// MARK: - "monitors" demo scaffolding +// +// Extra data sources for the diagnostics/monitor views ported to Linux. All are +// Sendable (`UIParamNode` / `LyrebirdBuffer` are `@unchecked Sendable`, `Entry` +// is `Sendable`, `[Double]` is Sendable) so they cross into SwiftOpenUI's +// nonisolated scene closure like the nodes above. + +// Parameter entries with EXPLICIT ranges. `LyrebirdSynthView.discover` can't +// carry per-slot ranges on Linux (that metadata type is Apple-only), so it would +// default every knob to 0…1 — wrong for frequency (Hz). Build them by hand from +// the already-extracted nodes so the frequency knob spans a musical range. +let demoFreqRange: ClosedRange = 110.0...880.0 +let demoAmpRange: ClosedRange = 0.0...1.0 +let demoSynthEntries: [LyrebirdSynthView.Entry] = [ + LyrebirdSynthView.Entry( + propertyName: "frequency", displayName: "frequency", + node: frequencyNode, range: demoFreqRange + ), + LyrebirdSynthView.Entry( + propertyName: "amplitude", displayName: "amplitude", + node: amplitudeNode, range: demoAmpRange + ), +] + +// A per-bin buffer driven by the MultiSlider (a rising ramp to start). +private let demoMultiBinCount: Int = 48 +let demoMultiBuffer: LyrebirdBuffer = { + let buf: LyrebirdBuffer = LyrebirdBuffer(count: demoMultiBinCount) + buf.fill { (i: Int, n: Int) in Double(i) / Double(n) } + return buf +}() + +// A static scatter of one Gaussian-ish cloud for the scatter plot. +let demoScatterData: [Double] = (0..<160).map { (i: Int) in + let t: Double = Double(i) / 160.0 + return 0.5 + 0.4 * sin(t * .pi * 6) * (1.0 - t) +} + +// MARK: - "events" demo scaffolding +// +// A `LyrebirdEventList` of four one-shot events, each starting a sustaining +// `EventVoiceSynth` at a distinct pitch. `LyrebirdEventList` is `@unchecked +// Sendable`, so (like the nodes) it crosses into SwiftOpenUI's nonisolated scene +// closure. Built after `engine.start()` above. +let eventDemoPitches: [Double] = [220.0, 277.18, 329.63, 440.0] // A3, C#4, E4, A4 +let eventDemoEnvelope: Envelope = Envelope( + levels: [0.0, 1.0, 0.0], + durations: [0.08, 0.6], + curves: [.lin, .lin], + releaseNode: 2 +) +let eventDemoEvents: [LyrebirdEvent] = eventDemoPitches.enumerated().map { (index: Int, pitch: Double) in + let proc: LyrebirdProcess = LyrebirdProcess( + id: "voice-\(index)", + envelope: eventDemoEnvelope, + numChannels: 2, + body: { (ctx: LyrebirdProcessContext) in ctx.add(EventVoiceSynth(freq: pitch)) } + ) + return LyrebirdEvent(starts: [proc]) +} +let eventDemoList: LyrebirdEventList? = { + do { + return try LyrebirdEventList( + id: "events-demo", + events: eventDemoEvents, + engine: demoEngine, + bus: AudioBus(index: 0, channelCount: 2) + ) + } catch { + print("[Lyrebird] events demo list build failed: \(error)") + return nil + } +}() + +// Seed a few diagnostics messages so the message views/banner have content. +LyrebirdMessageCenter.shared.info("Linux UI demo started", source: "LyrebirdUILinuxDemo") +LyrebirdMessageCenter.shared.warning("This is an example warning", source: "demo") +LyrebirdMessageCenter.shared.error("This is an example error", source: "demo") + +// MARK: - GTK4 app +// +// Diagnostic selector: set LYREBIRD_DEMO to isolate what breaks interaction. +// knob → a single knob (control in isolation) +// controls → all controls, no animated views (isolates the timer redraws) +// monitors → the ported diagnostics/monitor views (SynthView grid, Scatter, +// MultiSlider, EngineStatus incl. node-tree + messages) +// narrowtest → narrow-path isolation: Canvas slider + Text/TextField wrapped in the +// ex-poison modifiers, NO opaque widgets — label+field should track live +// mouse → pointer-source test: live Mouse.X/Y/Click readout over a +// pointer-driven sine (validates the Linux MouseTracker) +// events → process/event-list views on-display: LyrebirdEventListPerformanceView +// (EventListView transport + RunningProcesses/ProcessView strips) + +// presentInWindow buttons for each +// (unset) → the full demo +// Each mode is a distinct App/View with a FIXED body — no in-body @ViewBuilder +// conditional, which would itself change the rebuild plan under test. + +struct KnobDemoApp: App { + var body: some Scene { + WindowGroup("Lyrebird Knob Demo") { + KnobDemoView( + frequencyNode: frequencyNode, + amplitudeNode: amplitudeNode, + scope: demoScope, + envelope: demoEnvelope, + engine: statusEngine + ) + } + } +} + +struct KnobOnlyDemoApp: App { + var body: some Scene { + WindowGroup("Lyrebird Knob Demo") { + DemoKnobOnlyView(frequencyNode: frequencyNode) + } + } +} + +struct ControlsDemoApp: App { + var body: some Scene { + WindowGroup("Lyrebird Knob Demo") { + DemoControlsView( + frequencyNode: frequencyNode, + amplitudeNode: amplitudeNode + ) + } + } +} + +/// Showcase of the ported diagnostics / monitor views: the auto-generated +/// parameter grid, a scatter plot, a per-bin MultiSlider, and the engine status +/// panel (which itself embeds the node-tree and message sections). +struct MonitorsDemoApp: App { + var body: some Scene { + WindowGroup("Lyrebird Monitors Demo") { + DemoMonitorsView( + entries: demoSynthEntries, + scatter: demoScatterData, + multiBuffer: demoMultiBuffer, + multiCount: demoMultiBinCount, + engine: statusEngine, + onEngineStarted: reAddSynthOnStart + ) + } + } +} + +/// Narrow-path isolation test (no engine, no opaque widgets). +struct NarrowTestApp: App { + var body: some Scene { + WindowGroup("Lyrebird Narrow-Path Test") { + DemoNarrowTestView() + } + } +} + +/// Pointer-source test: a live Mouse.X/Y/Click readout over a pointer-driven +/// sine. Validates the Linux `MouseTracker`. +struct MouseDemoApp: App { + var body: some Scene { + WindowGroup("Lyrebird Mouse Demo") { + DemoMouseView() + } + } +} + +/// On-display exercise of the ported process/event-list views: the composite +/// `LyrebirdEventListPerformanceView` inline plus buttons to open each view in a +/// detached `LyrebirdWindow`. +struct EventsDemoApp: App { + var body: some Scene { + WindowGroup("Lyrebird Events Demo") { + if let list: LyrebirdEventList = eventDemoList { + DemoEventsView(eventList: list, engine: statusEngine) + } else { + Text("Events demo failed to build — see console.") + .padding() + } + } + } +} + +switch demoMode { +case "knob": + GTK4Backend().run(KnobOnlyDemoApp.self) +case "narrowtest": + GTK4Backend().run(NarrowTestApp.self) +case "mouse": + GTK4Backend().run(MouseDemoApp.self) +case "events": + GTK4Backend().run(EventsDemoApp.self) +case "controls": + GTK4Backend().run(ControlsDemoApp.self) +case "monitors": + GTK4Backend().run(MonitorsDemoApp.self) +default: + GTK4Backend().run(KnobDemoApp.self) +} diff --git a/Tests/LyrebirdCLITests/ProjectScaffolderBuildTests.swift b/Tests/LyrebirdCLITests/ProjectScaffolderBuildTests.swift index 0b762ac..2f1861d 100644 --- a/Tests/LyrebirdCLITests/ProjectScaffolderBuildTests.swift +++ b/Tests/LyrebirdCLITests/ProjectScaffolderBuildTests.swift @@ -62,7 +62,17 @@ struct ProjectScaffolderBuildTests { /// Raw strings (not `ProjectTemplate` cases) are the parametrized arguments /// because `@Test(arguments:)` requires `Sendable` and the public /// `ProjectTemplate` enum does not declare the conformance. - static let spmTemplateRawValues: [String] = ["quickstart", "basic", "demo", "nrt", "score", "ui-demo"] + /// + /// `ui-demo` emits `import AppKit` / `NSApplication`, so it is Apple-only by + /// construction and is dropped off Apple rather than being expected to + /// build there. + static let spmTemplateRawValues: [String] = { + var templates: [String] = ["quickstart", "basic", "demo", "nrt", "score"] + #if canImport(AppKit) + templates.append("ui-demo") + #endif + return templates + }() @Test(arguments: spmTemplateRawValues) func templateBuildsAgainstLiveLyrebird(_ rawValue: String) throws { @@ -100,15 +110,54 @@ struct ProjectScaffolderBuildTests { `swift build` failed for template \(template.rawValue) (exit \(result.exitCode)): \(result.output) """) + guard result.exitCode == 0 else { return } + + // Compiling is not the same as working. The offline-render templates + // pick an output container, and a container the platform cannot write + // (CAF off Apple) fails only at run time — a build-only check calls + // that healthy. So actually run them and require the file to appear. + guard let expectedOutput: String = Self.renderedOutputFileName(for: template) else { return } + let run: (exitCode: Int32, output: String) = try Self.runSwiftRun(in: projectRoot) + #expect(run.exitCode == 0, + """ + `swift run` failed for template \(template.rawValue) (exit \(run.exitCode)): + \(run.output) + """) + let renderedPath: String = (projectRoot as NSString).appendingPathComponent(expectedOutput) + #expect(fm.fileExists(atPath: renderedPath), + "template \(template.rawValue) ran but wrote no \(expectedOutput)") + } + + /// The file a template is expected to render, or `nil` for templates that + /// open an audio device or a window instead of writing one. + private static func renderedOutputFileName(for template: ProjectTemplate) -> String? { + switch template.rawValue { + case "nrt": return "output.wav" + case "score": return "score.wav" + default: return nil + } + } + + /// Run `swift run` in `directory`, capturing merged stdout+stderr. + private static func runSwiftRun(in directory: String) throws -> (exitCode: Int32, output: String) { + try runProcess(["swift", "run"], in: directory) } // MARK: - swift build runner /// Run `swift build` in `directory`, capturing merged stdout+stderr. private static func runSwiftBuild(in directory: String) throws -> (exitCode: Int32, output: String) { + try runProcess(["swift", "build"], in: directory) + } + + /// Run a command in `directory`, capturing merged stdout+stderr. + private static func runProcess( + _ arguments: [String], + in directory: String + ) throws -> (exitCode: Int32, output: String) { let process: Process = Process() process.executableURL = URL(fileURLWithPath: "/usr/bin/env") - process.arguments = ["swift", "build"] + process.arguments = arguments process.currentDirectoryURL = URL(fileURLWithPath: directory) let pipe: Pipe = Pipe() diff --git a/Tests/LyrebirdCLITests/ProjectScaffolderTests.swift b/Tests/LyrebirdCLITests/ProjectScaffolderTests.swift index c459bb4..6d1bb33 100644 --- a/Tests/LyrebirdCLITests/ProjectScaffolderTests.swift +++ b/Tests/LyrebirdCLITests/ProjectScaffolderTests.swift @@ -91,9 +91,29 @@ struct ProjectScaffolderTests { #expect(source.contains("import LyrebirdSynth")) } - @Test func mainSwiftReferencesCoreAudioDriver() { - let source: String = ProjectScaffolder.mainSwift(name: "Demo") - #expect(source.contains("CoreAudioDriver")) + @Test func mainSwiftDefersDriverChoiceToTheLibrary() { + // A scaffolded CLI project has to build wherever it was created, and + // which drivers exist is not something consumer code can test for: the + // Linux driver is absent from a build without libasound, and from a + // Linux binary cross-compiled on a Mac. Naming a concrete driver — or + // writing the `#if` in the emitted source — produces a project that + // fails to compile on those configurations. + for template: ProjectTemplate in [.quickstart, .basic, .demo] { + let source: String = ProjectScaffolder.mainSwift(name: "Demo", template: template) + #expect(source.contains("makeDefaultAudioDriver()"), "\(template)") + #expect(source.contains("driver: driver"), "\(template)") + #expect(!source.contains("CoreAudioDriver()"), "\(template)") + #expect(!source.contains("ALSAAudioDriver()"), "\(template)") + } + } + + @Test func appKitTemplateStaysAppleOnly() { + // The GUI template imports AppKit, so it is macOS-only by construction; + // a platform switch there would imply a portability it does not have. + let source: String = ProjectScaffolder.mainSwift(name: "Demo", template: .uiDemo) + #expect(source.contains("import AppKit")) + #expect(source.contains("CoreAudioDriver()")) + #expect(!source.contains("ALSAAudioDriver")) } // MARK: - testsSwift template @@ -633,7 +653,9 @@ struct ProjectScaffolderTests { let source: String = ProjectScaffolder.mainSwift(name: "Demo", template: .demo) #expect(source.contains("@LiveParam")) #expect(source.contains("SineTone")) - #expect(source.contains("CoreAudioDriver")) + // Driver choice belongs to the library — see + // `mainSwiftDefersDriverChoiceToTheLibrary`. + #expect(source.contains("makeDefaultAudioDriver()")) } @Test func demoMainSwiftContainsName() { @@ -712,7 +734,10 @@ struct ProjectScaffolderTests { let source: String = ProjectScaffolder.mainSwift(name: "MyRender", template: .nrt) #expect(source.contains("NRTDriver")) #expect(source.contains("renderDuration")) - #expect(source.contains("output.caf")) + // WAV, not CAF: CAF is Apple-only, so a CAF render fails at run time + // on Linux even though the project compiles there. + #expect(source.contains("output.wav")) + #expect(source.contains(".wavFloat32")) } @Test func nrtMainSwiftContainsName() { @@ -738,7 +763,8 @@ struct ProjectScaffolderTests { @Test func scoreMainSwiftRendersOfflineWithNRTDriver() { let source: String = ProjectScaffolder.mainSwift(name: "MyPiece", template: .score) #expect(source.contains("NRTDriver")) - #expect(source.contains("score.caf")) + #expect(source.contains("score.wav")) + #expect(source.contains(".wavFloat32")) #expect(source.contains("engine.schedule")) // Must not embed the Lyrebird copyright in emitted user source. #expect(!source.contains("Joshua Parmenter")) diff --git a/Tests/LyrebirdDSPTests/ScalarDSPParityTests.swift b/Tests/LyrebirdDSPTests/ScalarDSPParityTests.swift new file mode 100644 index 0000000..0c69127 --- /dev/null +++ b/Tests/LyrebirdDSPTests/ScalarDSPParityTests.swift @@ -0,0 +1,374 @@ +// ScalarDSPParityTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +@testable import LyrebirdDSP + +// The portable scalar cores in `ScalarDSP.swift` are the non-Apple fallback for +// Accelerate's vDSP. A wrong operand order (vDSP's `vsub`/`vdiv` take the +// second operand first) would be a silent, Linux-only DSP bug. These tests run +// each scalar core against the *real* vDSP on Apple and require agreement, so +// the fallback is proven against the thing it replaces. Off Apple there is no +// reference to compare to, so the suite is Apple-only. + +#if canImport(Accelerate) +import Accelerate + +@Suite("ScalarDSP vDSP parity") +struct ScalarDSPParityTests { + + private static let n: Int = 37 // deliberately not a power of two + private static let tolerance: Double = 1e-12 + + private func makeInput(_ seed: Double) -> [Double] { + var out: [Double] = [Double](repeating: 0, count: Self.n) + for i: Int in 0.., UnsafeMutablePointer) -> Void + ) { + input.withUnsafeBufferPointer { ip in + output.withUnsafeMutableBufferPointer { op in + guard let iBase: UnsafePointer = ip.baseAddress, + let oBase: UnsafeMutablePointer = op.baseAddress else { + Issue.record("empty buffer") + return + } + body(iBase, oBase) + } + } + } + + @Test("c = a * scalar (vsmulD)") + func vScalarMul() { + let a: [Double] = makeInput(0.1) + var scalar: Double = 1.75 + var ref: [Double] = [Double](repeating: 0, count: Self.n) + var got: [Double] = [Double](repeating: 0, count: Self.n) + vDSP_vsmulD(a, 1, &scalar, &ref, 1, vDSP_Length(Self.n)) + withBases(a, &got) { aBase, gBase in + _lbVScalarMul(aBase, 1, scalar, gBase, 1, Self.n) + } + expectClose(got, ref, "vsmul") + } + + @Test("c = a + b (vaddD)") + func vAdd() { + let a: [Double] = makeInput(0.1) + let b: [Double] = makeInput(2.3) + var ref: [Double] = [Double](repeating: 0, count: Self.n) + var got: [Double] = [Double](repeating: 0, count: Self.n) + vDSP_vaddD(a, 1, b, 1, &ref, 1, vDSP_Length(Self.n)) + b.withUnsafeBufferPointer { bp in + guard let bBase: UnsafePointer = bp.baseAddress else { Issue.record("empty"); return } + withBases(a, &got) { aBase, gBase in + _lbVAdd(aBase, 1, bBase, 1, gBase, 1, Self.n) + } + } + expectClose(got, ref, "vadd") + } + + @Test("c = a - b, operand order (vsubD)") + func vSub() { + let a: [Double] = makeInput(0.1) + let b: [Double] = makeInput(2.3) + var ref: [Double] = [Double](repeating: 0, count: Self.n) + var got: [Double] = [Double](repeating: 0, count: Self.n) + // vDSP_vsubD(B, IB, A, IA, C, IC, N) computes C = A - B. + vDSP_vsubD(b, 1, a, 1, &ref, 1, vDSP_Length(Self.n)) + b.withUnsafeBufferPointer { bp in + guard let bBase: UnsafePointer = bp.baseAddress else { Issue.record("empty"); return } + withBases(a, &got) { aBase, gBase in + _lbVSub(aBase, 1, bBase, 1, gBase, 1, Self.n) + } + } + expectClose(got, ref, "vsub") + } + + @Test("c = a / b, operand order (vdivD)") + func vDiv() { + let a: [Double] = makeInput(0.1) + let b: [Double] = makeInput(2.3).map { $0 + 5.0 } // keep divisor away from 0 + var ref: [Double] = [Double](repeating: 0, count: Self.n) + var got: [Double] = [Double](repeating: 0, count: Self.n) + // vDSP_vdivD(B, IB, A, IA, C, IC, N) computes C = A / B. + vDSP_vdivD(b, 1, a, 1, &ref, 1, vDSP_Length(Self.n)) + b.withUnsafeBufferPointer { bp in + guard let bBase: UnsafePointer = bp.baseAddress else { Issue.record("empty"); return } + withBases(a, &got) { aBase, gBase in + _lbVDiv(aBase, 1, bBase, 1, gBase, 1, Self.n) + } + } + expectClose(got, ref, "vdiv") + } + + @Test("d = a*mul + add (vsmsaD)") + func vScalarMulScalarAdd() { + let a: [Double] = makeInput(0.1) + var mul: Double = 2.5 + var add: Double = -1.25 + var ref: [Double] = [Double](repeating: 0, count: Self.n) + var got: [Double] = [Double](repeating: 0, count: Self.n) + vDSP_vsmsaD(a, 1, &mul, &add, &ref, 1, vDSP_Length(Self.n)) + withBases(a, &got) { aBase, gBase in + _lbVScalarMulScalarAdd(aBase, 1, mul, add, gBase, 1, Self.n) + } + expectClose(got, ref, "vsmsa") + } + + @Test("d = a*mul + c(vector) (vsmaD)") + func vScalarMulVAdd() { + let a: [Double] = makeInput(0.1) + let c: [Double] = makeInput(1.7) + var mul: Double = 0.8 + var ref: [Double] = [Double](repeating: 0, count: Self.n) + var got: [Double] = [Double](repeating: 0, count: Self.n) + vDSP_vsmaD(a, 1, &mul, c, 1, &ref, 1, vDSP_Length(Self.n)) + c.withUnsafeBufferPointer { cp in + guard let cBase: UnsafePointer = cp.baseAddress else { Issue.record("empty"); return } + withBases(a, &got) { aBase, gBase in + _lbVScalarMulVAdd(aBase, 1, mul, cBase, 1, gBase, 1, Self.n) + } + } + expectClose(got, ref, "vsma") + } + + @Test("scalar reductions (maxmgvD, sveD)") + func reductions() { + let a: [Double] = makeInput(0.1) + var refMax: Double = 0 + var refSum: Double = 0 + vDSP_maxmgvD(a, 1, &refMax, vDSP_Length(Self.n)) + vDSP_sveD(a, 1, &refSum, vDSP_Length(Self.n)) + var gotMax: Double = 0 + var gotSum: Double = 0 + a.withUnsafeBufferPointer { ap in + guard let aBase: UnsafePointer = ap.baseAddress else { Issue.record("empty"); return } + gotMax = _lbMaxMagnitude(aBase, 1, Self.n) + gotSum = _lbSum(aBase, 1, Self.n) + } + #expect(abs(gotMax - refMax) <= Self.tolerance) + #expect(abs(gotSum - refSum) <= 1e-10) + } + + @Test("double→float conversion (vdpsp)") + func convertDoubleToFloat() { + let a: [Double] = makeInput(0.1) + var ref: [Float] = [Float](repeating: 0, count: Self.n) + var got: [Float] = [Float](repeating: 0, count: Self.n) + vDSP_vdpsp(a, 1, &ref, 1, vDSP_Length(Self.n)) + a.withUnsafeBufferPointer { ap in + got.withUnsafeMutableBufferPointer { gp in + guard let aBase: UnsafePointer = ap.baseAddress, + let gBase: UnsafeMutablePointer = gp.baseAddress else { Issue.record("empty"); return } + _lbConvertDoubleToFloat(aBase, 1, gBase, 1, Self.n) + } + } + for i: Int in 0.. = ip.baseAddress else { Issue.record("empty"); return } + vDSP_biquadD(setup, &refDelay, iBase, 1, &ref, 1, vDSP_Length(Self.n)) + } + input.withUnsafeBufferPointer { ip in + got.withUnsafeMutableBufferPointer { gp in + coeffs.withUnsafeBufferPointer { cp in + guard let iBase = ip.baseAddress, let gBase = gp.baseAddress, let cBase = cp.baseAddress else { Issue.record("empty"); return } + _lbRunBiquad(cBase, m, &gotDelay, iBase, 1, gBase, 1, Self.n) + } + } + } + for i: Int in 0.. = g.baseAddress else { Issue.record("empty"); return } + _lbVRamp(0.3, 0.07, gBase, 1, Self.n) + } + expectClose(got, ref, "vramp") + } +} +#endif diff --git a/Tests/LyrebirdPortableTests/ALSAAudioDriverTests.swift b/Tests/LyrebirdPortableTests/ALSAAudioDriverTests.swift new file mode 100644 index 0000000..f69dbee --- /dev/null +++ b/Tests/LyrebirdPortableTests/ALSAAudioDriverTests.swift @@ -0,0 +1,156 @@ +// ALSAAudioDriverTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// Linux-only: `ALSAAudioDriver` exists solely where libasound does. These tests +// run headless — a CI container has no sound device — so they cover the paths +// that must behave correctly *without* hardware: refusing to start unconfigured, +// failing cleanly on a device that cannot be opened, and surviving redundant +// stops. Their other job is to prove the driver was actually compiled into the +// module: if the CALSA dependency ever stops resolving, the whole file compiles +// away to nothing and everything else would still pass. +// +// Guarded on `canImport(CALSA)` rather than `os(Linux)` so the file tracks the +// driver's own condition exactly: a Linux build with `LYREBIRD_DISABLE_ALSA=1` +// has no driver, and an `os(Linux)` guard would leave these tests referencing a +// type that is not there. +#if canImport(CALSA) + +import Testing +@_spi(LyrebirdExtensions) import LyrebirdSynth + +@MainActor +@Suite("ALSAAudioDriver (headless)") +struct ALSAAudioDriverTests { + + /// A name no ALSA configuration will resolve, so `snd_pcm_open` fails on + /// any machine — with or without a sound card. + private static let unopenableDevice: String = "lyrebird-nonexistent-pcm" + + @Test func startWithoutSetupThrowsNotConfigured() { + let driver: ALSAAudioDriver = ALSAAudioDriver() + #expect(throws: ALSAError.notConfigured) { + try driver.start() + } + } + + @Test func startOnUnopenableDeviceThrowsAndDoesNotRun() throws { + let driver: ALSAAudioDriver = ALSAAudioDriver() + driver.device = Self.unopenableDevice + let engine: SynthesisEngine = SynthesisEngine( + blockSize: 64, + sampleRate: 44100, + numOutputChannels: 2, + numInputChannels: 0, + driver: driver + ) + try driver.setup(engine: engine) + + var thrown: ALSAError? + do { + try driver.start() + } catch let error as ALSAError { + thrown = error + } + guard case .playbackDeviceOpenFailed(let device, _)? = thrown else { + Issue.record("expected playbackDeviceOpenFailed, got \(String(describing: thrown))") + return + } + #expect(device == Self.unopenableDevice) + #expect(driver.lastError == nil, "no render thread ran, so nothing should have failed inside one") + } + + @Test func failedStartLeavesNoWedgedState() throws { + // A start that throws must not leave the running flag set or a device + // half-open, or every later start would fail for the wrong reason. + let driver: ALSAAudioDriver = ALSAAudioDriver() + driver.device = Self.unopenableDevice + let engine: SynthesisEngine = SynthesisEngine( + blockSize: 64, + sampleRate: 44100, + numOutputChannels: 2, + numInputChannels: 0, + driver: driver + ) + try driver.setup(engine: engine) + + for attempt: Int in 0..<3 { + var thrown: ALSAError? + do { + try driver.start() + } catch let error as ALSAError { + thrown = error + } + guard case .playbackDeviceOpenFailed? = thrown else { + Issue.record("attempt \(attempt): expected playbackDeviceOpenFailed, got \(String(describing: thrown))") + return + } + driver.stop() + } + } + + @Test func engineRetainRoundTripBalances() throws { + // The render thread pins the engine with a retain handed over as a bit + // pattern, released by the loop's `defer`. Nothing hardware is involved + // in that balance, so pin it here rather than leaving it to run only on + // a real device: a missing release leaks the engine, a double release + // is a use-after-free. + weak var weakEngine: SynthesisEngine? + var bits: UInt = 0 + do { + let engine: SynthesisEngine = SynthesisEngine( + blockSize: 64, + sampleRate: 44100, + numOutputChannels: 2, + numInputChannels: 0, + driver: OfflineDriver() + ) + weakEngine = engine + bits = ALSAAudioDriver.retainForRenderThread(Unmanaged.passUnretained(engine)) + } + // The local strong reference is gone, but the render-thread retain is + // still holding the engine alive. + #expect(weakEngine != nil, "retainForRenderThread must keep the engine alive") + + ALSAAudioDriver.releaseEngine(bits: bits) + #expect(weakEngine == nil, "releaseEngine must balance the retain exactly") + } + + @Test func stallBudgetGivesUpOnlyAfterTheLimit() { + // The loop that consults this only runs against real hardware, so the + // boundary is pinned here: one attempt early kills a stream that was + // merely slow, one late means a wedged device spins forever at + // SCHED_FIFO. + #expect(ALSAAudioDriver.stallBudgetExhausted(consecutiveStalls: 1) == false) + #expect(ALSAAudioDriver.stallBudgetExhausted( + consecutiveStalls: ALSAAudioDriver.maxConsecutiveStalls) == false) + #expect(ALSAAudioDriver.stallBudgetExhausted( + consecutiveStalls: ALSAAudioDriver.maxConsecutiveStalls + 1) == true) + } + + @Test func stopIsSafeBeforeStartAndWhenRepeated() { + let driver: ALSAAudioDriver = ALSAAudioDriver() + driver.stop() + driver.stop() + } + + @Test func defaultsTargetTheUserConfiguredDevice() { + let driver: ALSAAudioDriver = ALSAAudioDriver() + // "default" honours ~/.asoundrc and dmix; addressing hw:N,M directly + // would lock out every other application on the machine. + #expect(driver.device == "default") + #expect(driver.captureDevice == "default") + #expect(driver.allowSoftwareResampling == false) + #expect(driver.linkedStreams == false) + #expect(driver.hasRealtimePriority == false) + } + + @Test func suggestsTheSameControlBlockSizeAsOtherLiveDrivers() { + let driver: ALSAAudioDriver = ALSAAudioDriver() + #expect(driver.suggestedControlBlockSize == 64) + } +} + +#endif diff --git a/Tests/LyrebirdPortableTests/ALSAMIDITests.swift b/Tests/LyrebirdPortableTests/ALSAMIDITests.swift new file mode 100644 index 0000000..d456b0d --- /dev/null +++ b/Tests/LyrebirdPortableTests/ALSAMIDITests.swift @@ -0,0 +1,93 @@ +// ALSAMIDITests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// Linux-only: the ALSA-sequencer `MIDI` backend exists where CALSA does and +// CoreMIDI does not. These run headless — a CI container may or may not expose +// the kernel sequencer — so they cover the parts that need no controller: the +// handler registry, the not-started guards, and safe teardown, plus a tolerant +// start/stop that accepts either outcome. Receiving from real hardware is the +// deferred acceptance check (see LINUX_PLAN.md). The file also guards that the +// backend is actually compiled in: if CALSA stops resolving, it vanishes and +// every other test still passes. +#if !canImport(CoreMIDI) && canImport(CALSA) + +import Testing +@_spi(LyrebirdExtensions) import LyrebirdSynth + +@MainActor +@Suite("ALSA MIDI (headless)") +struct ALSAMIDITests { + + private func makeEngine() -> SynthesisEngine { + SynthesisEngine( + blockSize: 64, sampleRate: 44100, + numOutputChannels: 2, numInputChannels: 0, + driver: OfflineDriver() + ) + } + + @Test func addHandlerReturnsDistinctTokensAndRemoveIsSafe() { + let midi: MIDI = MIDI(engine: makeEngine()) + let a: MIDIHandlerToken = midi.addHandler(name: "a") { _, _ in } + let b: MIDIHandlerToken = midi.addHandler(name: "b") { _, _ in } + #expect(a != b) + midi.removeHandler(a) + midi.removeHandler(b) + midi.removeHandler(a) // removing twice is a no-op, not a crash + } + + @Test func sendBeforeStartThrowsNotStarted() { + let midi: MIDI = MIDI(engine: makeEngine()) + let dest: MIDIDestination = MIDIDestination(name: "x", client: 128, port: 0) + #expect(throws: MIDIError.notStarted) { + try midi.send(.noteOn(channel: 0, note: 60, velocity: 100), to: dest) + } + #expect(throws: MIDIError.notStarted) { + try midi.sendVirtual(.noteOn(channel: 0, note: 60, velocity: 100)) + } + #expect(throws: MIDIError.notStarted) { + try midi.createVirtualOutput(name: "out") + } + } + + @Test func stopBeforeStartAndRepeatedStopAreSafe() { + let midi: MIDI = MIDI(engine: makeEngine()) + midi.stop() + midi.stop() + } + + @Test func sourcesAreEmptyBeforeStart() { + let midi: MIDI = MIDI(engine: makeEngine()) + #expect(midi.sources.isEmpty) + #expect(midi.destinations.isEmpty) + } + + @Test func startThenStopEitherOpensOrFailsCleanly() { + // The kernel sequencer may be absent in a container. Success must leave + // a startable/stoppable client; failure must be a setup error, not a + // crash, and must leave the client re-startable. + let midi: MIDI = MIDI(engine: makeEngine()) + do { + try midi.start() + // Opened: a second start is rejected, and stop tears down cleanly. + #expect(throws: MIDIError.alreadyStarted) { try midi.start() } + midi.stop() + // After a clean stop it can start again (or fail cleanly again). + do { try midi.start(); midi.stop() } catch is MIDIError {} catch { Issue.record("unexpected \(error)") } + } catch let error as MIDIError { + guard case .clientCreateFailed = error else { + Issue.record("expected clientCreateFailed when the sequencer is absent, got \(error)") + return + } + // A failed start must not have latched isStarted — retry is allowed. + #expect(throws: MIDIError.self) { try midi.start() } + } catch { + Issue.record("unexpected error type \(error)") + } + } +} + +#endif diff --git a/Tests/LyrebirdPortableTests/ALSARecoveryActionTests.swift b/Tests/LyrebirdPortableTests/ALSARecoveryActionTests.swift new file mode 100644 index 0000000..48f1a83 --- /dev/null +++ b/Tests/LyrebirdPortableTests/ALSARecoveryActionTests.swift @@ -0,0 +1,47 @@ +// ALSARecoveryActionTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import LyrebirdSynth + +// The xrun policy decides whether the render loop recovers, retries, or dies. +// It is pure arithmetic over ALSA's return value, so it is tested on every +// platform even though the driver consuming it is Linux-only. + +@Suite("ALSA transfer recovery policy") +struct ALSARecoveryActionTests { + + @Test func successReportsFramesTransferred() { + #expect(ALSARecoveryAction.classify(512) == .transferred(frames: 512)) + } + + @Test func shortTransferIsStillSuccess() { + // A partial write is normal; the loop resumes from where it stopped. + #expect(ALSARecoveryAction.classify(37) == .transferred(frames: 37)) + } + + @Test func zeroFramesIsSuccessNotAnError() { + #expect(ALSARecoveryAction.classify(0) == .transferred(frames: 0)) + } + + @Test func signalInterruptionIsDistinctFromDeviceNotReady() { + // Kept apart on purpose: a signal is not a device fault, so it reissues + // immediately and must not spend the patience budget that a device + // which never becomes ready does. + #expect(ALSARecoveryAction.classify(-4) == .interrupted) // -EINTR + #expect(ALSARecoveryAction.classify(-11) == .wouldBlock) // -EAGAIN + } + + @Test func underrunAndSuspendRecover() { + #expect(ALSARecoveryAction.classify(-32) == .recover) // -EPIPE (xrun) + #expect(ALSARecoveryAction.classify(-86) == .recover) // -ESTRPIPE (suspended) + } + + @Test func unknownErrorIsFatal() { + #expect(ALSARecoveryAction.classify(-19) == .fail) // -ENODEV, device unplugged + #expect(ALSARecoveryAction.classify(-77) == .fail) // -EBADFD + } +} diff --git a/Tests/LyrebirdPortableTests/ALSASeqMIDIEventTests.swift b/Tests/LyrebirdPortableTests/ALSASeqMIDIEventTests.swift new file mode 100644 index 0000000..ab6937a --- /dev/null +++ b/Tests/LyrebirdPortableTests/ALSASeqMIDIEventTests.swift @@ -0,0 +1,76 @@ +// ALSASeqMIDIEventTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import LyrebirdSynth + +// The seq-event → MIDIMessage mapping is the one piece of the Linux MIDI backend +// that carries real semantic decisions (note-on velocity 0 → note-off, the +// pitch-bend offset). It is pure Swift, so it is pinned here on every platform +// rather than only against a connected controller. + +@Suite("ALSA sequencer MIDI mapping") +struct ALSASeqMIDIEventTests { + + @Test func noteOnMaps() { + #expect(midiMessage(for: .noteOn(channel: 2, note: 60, velocity: 100)) + == .noteOn(channel: 2, note: 60, velocity: 100)) + } + + @Test func noteOnWithZeroVelocityBecomesNoteOff() { + // The exact convention the CoreMIDI path applies, so a controller that + // sends note-on/vel-0 for note-off behaves the same on both platforms. + #expect(midiMessage(for: .noteOn(channel: 0, note: 64, velocity: 0)) + == .noteOff(channel: 0, note: 64, velocity: 0)) + } + + @Test func noteOffMaps() { + #expect(midiMessage(for: .noteOff(channel: 9, note: 40, velocity: 20)) + == .noteOff(channel: 9, note: 40, velocity: 20)) + } + + @Test func controllerMaps() { + #expect(midiMessage(for: .controller(channel: 1, param: 7, value: 127)) + == .controlChange(channel: 1, controller: 7, value: 127)) + } + + @Test func programAndPressureMap() { + #expect(midiMessage(for: .programChange(channel: 3, program: 12)) + == .programChange(channel: 3, program: 12)) + #expect(midiMessage(for: .channelPressure(channel: 3, pressure: 55)) + == .aftertouch(channel: 3, pressure: 55)) + #expect(midiMessage(for: .keyPressure(channel: 3, note: 60, pressure: 44)) + == .polyAftertouch(channel: 3, note: 60, pressure: 44)) + } + + @Test func pitchBendPreservesSignedValue() { + #expect(midiMessage(for: .pitchBend(channel: 0, value: 0)) + == .pitchBend(channel: 0, value: 0)) + #expect(midiMessage(for: .pitchBend(channel: 5, value: -8192)) + == .pitchBend(channel: 5, value: -8192)) + #expect(midiMessage(for: .pitchBend(channel: 5, value: 8191)) + == .pitchBend(channel: 5, value: 8191)) + } + + @Test func pitchBendClampsOutOfRangeRatherThanWrapping() { + // An out-of-range value must saturate, not overflow the 14-bit field. + #expect(midiMessage(for: .pitchBend(channel: 0, value: 99999)) + == .pitchBend(channel: 0, value: 8191)) + #expect(midiMessage(for: .pitchBend(channel: 0, value: -99999)) + == .pitchBend(channel: 0, value: -8192)) + } + + @Test func realtimeAndSysexMap() { + #expect(midiMessage(for: .clock) == .clock) + #expect(midiMessage(for: .start) == .start) + #expect(midiMessage(for: .continue) == .continue) + #expect(midiMessage(for: .stop) == .stop) + #expect(midiMessage(for: .activeSensing) == .activeSensing) + #expect(midiMessage(for: .reset) == .reset) + #expect(midiMessage(for: .sysex([0xF0, 0x7E, 0x7F, 0xF7])) + == .sysex([0xF0, 0x7E, 0x7F, 0xF7])) + } +} diff --git a/Tests/LyrebirdPortableTests/FilterGoldenValueTests.swift b/Tests/LyrebirdPortableTests/FilterGoldenValueTests.swift new file mode 100644 index 0000000..57605a4 --- /dev/null +++ b/Tests/LyrebirdPortableTests/FilterGoldenValueTests.swift @@ -0,0 +1,180 @@ +// FilterGoldenValueTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +@_spi(LyrebirdExtensions) import LyrebirdSynth + +// Golden impulse responses for the filters that route their inner loop through +// the vector-math seam (`LyrebirdDSP`). On Apple that seam is real Accelerate; +// off Apple it is the portable scalar re-implementation, and nothing else +// verifies that the substitution produces the same *audio* — the parity suite +// in `LyrebirdDSPTests` compares against real vDSP and is therefore Apple-only. +// +// These goldens were captured on macOS (arm64, vDSP-backed). A packing error, +// a wrong scale factor, or a swapped operand (vDSP's `vsub`/`vdiv` take the +// second operand first — the classic way to get this wrong) moves these numbers +// far more than the tolerance allows. +// +// Regenerating: run the same graph on macOS and print `String(format: "%+.15e")` +// per sample. Only do that after establishing the change was intended — an +// unexplained golden drift is the bug this file exists to catch. + +@MainActor +@Suite("Portable DSP golden values — filters") +struct FilterGoldenValueTests { + + /// Impulse responses run O(1e-2) down to O(1e-5) across a response, so the + /// tolerance is written as a floor plus a proportional term: the floor + /// keeps the small tail samples from demanding impossible precision, and + /// the relative term carries the large ones. These are IIR filters whose + /// coefficients come from the platform's `tan`/`exp`, so a last-bit libm + /// difference compounds down the response — at 1e-7 relative, that has room + /// to breathe while still pinning ~7 significant digits. + private static let absoluteTolerance: Double = 1e-9 + private static let relativeTolerance: Double = 1e-7 + private static let goldenSampleCount: Int = 32 + + /// A single impulse at sample 0 (`Impulse` at 1 Hz does not repeat inside + /// one 64-sample block at 44.1 kHz). + private func impulse() -> Impulse.Audio { + Impulse.Audio(freq: 1.0) + } + + // MARK: - Butterworth cascade (vDSP_biquadD opaque-setup path) + + @Test func butterworthLowPassOrder4ImpulseResponse() throws { + let engine: SynthesisEngine = makePortableTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + defer { engine.stop() } + + let filter: ButterworthLowPass.Audio = ButterworthLowPass.Audio( + input: impulse(), + freq: 1000.0, + order: 4 + ) + let out: [Double] = collectPortableBlocks(filter, engine: engine, blocks: 1) + + let golden: [Double] = [ + +2.152095121410931e-05, +1.641584629441634e-04, +6.181119607743385e-04, + +1.580531666013951e-03, +3.174639459072925e-03, +5.440148926700136e-03, + +8.352290048424874e-03, +1.183836980297112e-02, +1.579203946268454e-02, + +2.008543829951385e-02, +2.457938189196052e-02, +2.913176110580052e-02, + +3.360431504564020e-02, +3.786793778308615e-02, +4.180667442658070e-02, + +4.532055709715214e-02, +4.832742562570271e-02, +5.076387132477716e-02, + +5.258543506425273e-02, +5.376618316618124e-02, +5.429777641318197e-02, + +5.418813883228489e-02, +5.345982397463169e-02, +5.214816726824802e-02, + +5.029930378515230e-02, +4.796812154322546e-02, +4.521621136182290e-02, + +4.210986540661170e-02, +3.871816798451624e-02, +3.511121396581181e-02, + +3.135848248891489e-02, +2.752738640479642e-02, + ] + #expect(golden.count == Self.goldenSampleCount) + expectMatchesGolden(out, golden, absolute: Self.absoluteTolerance, + relative: Self.relativeTolerance, "ButterworthLowPass order 4 @ 1 kHz") + } + + @Test func butterworthHighPassOrder2ImpulseResponse() throws { + let engine: SynthesisEngine = makePortableTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + defer { engine.stop() } + + let filter: ButterworthHighPass.Audio = ButterworthHighPass.Audio( + input: impulse(), + freq: 2000.0, + order: 2 + ) + let out: [Double] = collectPortableBlocks(filter, engine: engine, blocks: 1) + + let golden: [Double] = [ + +8.173653471988668e-01, -3.260532537283749e-01, -2.509776927823263e-01, + -1.839145896391800e-01, -1.267185424557680e-01, -7.996528515637492e-02, + -4.333706504275574e-02, -1.594032798238100e-02, +3.443212698672361e-03, + +1.616692265076786e-02, +2.358340028385290e-02, +2.695373298540346e-02, + +2.739300334053809e-02, +2.584368988589170e-02, +2.306950121182690e-02, + +1.966328190177202e-02, +1.606379176647005e-02, +1.257728686358794e-02, + +9.400857984146530e-03, +6.645373641256291e-03, +4.356615194170972e-03, + +2.533781752345395e-03, +1.144992174962703e-03, +1.397371003516062e-04, + -5.415452602600245e-04, -9.604599425804916e-04, -1.175833047846857e-03, + -1.240675703549870e-03, -1.200546080581319e-03, -1.092956025864731e-03, + -9.475158033258457e-04, -7.865624259116227e-04, + ] + #expect(golden.count == Self.goldenSampleCount) + expectMatchesGolden(out, golden, absolute: Self.absoluteTolerance, + relative: Self.relativeTolerance, "ButterworthHighPass order 2 @ 2 kHz") + } + + // MARK: - Resonator banks (vDSP vector kernel: vsmulD / vmulD / vsubD / sveD) + + @Test func klankImpulseResponse() throws { + let engine: SynthesisEngine = makePortableTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + defer { engine.stop() } + + // Two modes: (freq, amp, decay). + let spec: LyrebirdBuffer = LyrebirdBuffer(count: 2, channelCount: klankSpecChannelCount) + spec.setValue(440.0, frame: 0, channel: klankFreqChannel) + spec.setValue(1.0, frame: 0, channel: klankAmpChannel) + spec.setValue(0.5, frame: 0, channel: klankDecayChannel) + spec.setValue(1320.0, frame: 1, channel: klankFreqChannel) + spec.setValue(0.7, frame: 1, channel: klankAmpChannel) + spec.setValue(0.25, frame: 1, channel: klankDecayChannel) + + let bank: Klank.Audio = Klank.Audio(input: impulse(), buffer: spec) + let out: [Double] = collectPortableBlocks(bank, engine: engine, blocks: 1) + + let golden: [Double] = [ + +7.516780834059488e-04, +1.485928026159716e-03, +2.186657458347529e-03, + +2.838891794961642e-03, +3.429262631979223e-03, +3.946439424747222e-03, + +4.381489452541366e-03, +4.728153616775348e-03, +4.983028599068313e-03, + +5.145649213721204e-03, +5.218468310109081e-03, +5.206735189726312e-03, + +5.118277072830178e-03, +4.963191555058374e-03, +4.753461115256087e-03, + +4.502503462429247e-03, +4.224673746663460e-03, +3.934736327817053e-03, + +3.647324838731323e-03, +3.376409660659641e-03, +3.134791635034020e-03, + +2.933639878788013e-03, +2.782089984828247e-03, +2.686916731598987e-03, + +2.652292772810991e-03, +2.679641724461021e-03, +2.767590719423414e-03, + +2.912023978509201e-03, +3.106235375324165e-03, +3.341174476490087e-03, + +3.605777241969424e-03, +3.887369588332656e-03, + ] + #expect(golden.count == Self.goldenSampleCount) + expectMatchesGolden(out, golden, absolute: Self.absoluteTolerance, + relative: Self.relativeTolerance, "Klank 440/1320 Hz") + } + + @Test func resonatorBankImpulseResponse() throws { + let engine: SynthesisEngine = makePortableTestEngine(blockSize: 64, sampleRate: 44100) + try engine.start() + defer { engine.stop() } + + // Two resonators: (freq, decay, amp) — note the channel order differs + // from Klank's, which is exactly the kind of thing a golden pins down. + let spec: LyrebirdBuffer = LyrebirdBuffer(count: 2, channelCount: resonatorBankChannelCount) + spec.setValue(300.0, frame: 0, channel: resonatorBankFreqChannel) + spec.setValue(0.4, frame: 0, channel: resonatorBankDecayChannel) + spec.setValue(1.0, frame: 0, channel: resonatorBankAmpChannel) + spec.setValue(900.0, frame: 1, channel: resonatorBankFreqChannel) + spec.setValue(0.2, frame: 1, channel: resonatorBankDecayChannel) + spec.setValue(0.5, frame: 1, channel: resonatorBankAmpChannel) + + let bank: ResonatorBank.Audio = ResonatorBank.Audio(input: impulse(), buffer: spec) + let out: [Double] = collectPortableBlocks(bank, engine: engine, blocks: 1) + + let golden: [Double] = [ + +7.829622372711453e-04, +1.557867646906840e-03, +2.317707696839478e-03, + +3.055706174578748e-03, +3.765419676725673e-03, +4.440832554694747e-03, + +5.076444786145945e-03, +5.667351359912787e-03, +6.209311903449615e-03, + +6.698809443657687e-03, +7.133097371698757e-03, +7.510233877089432e-03, + +7.829103322772969e-03, +8.089424247582720e-03, +8.291743902008049e-03, + +8.437419443840962e-03, +8.528586138498235e-03, +8.568113121003890e-03, + +8.559547479309104e-03, +8.507047608511223e-03, +8.415306959516080e-03, + +8.289469460939336e-03, +8.135038027046442e-03, +7.957777675122603e-03, + +7.763614861067067e-03, +7.558534700859674e-03, +7.348477776928855e-03, + +7.139238231888766e-03, +6.936364827597349e-03, +6.745066595464517e-03, + +6.570124625307941e-03, +6.415811436146689e-03, + ] + #expect(golden.count == Self.goldenSampleCount) + expectMatchesGolden(out, golden, absolute: Self.absoluteTolerance, + relative: Self.relativeTolerance, "ResonatorBank 300/900 Hz") + } +} diff --git a/Tests/LyrebirdPortableTests/InterleaveHelpersTests.swift b/Tests/LyrebirdPortableTests/InterleaveHelpersTests.swift new file mode 100644 index 0000000..200933f --- /dev/null +++ b/Tests/LyrebirdPortableTests/InterleaveHelpersTests.swift @@ -0,0 +1,87 @@ +// InterleaveHelpersTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +@_spi(LyrebirdExtensions) import LyrebirdSynth + +// Planar↔interleaved conversion is the part of a hardware driver that fails +// quietly: a transposed index produces channel-swapped or aliased audio rather +// than an error, and on a headless CI box nobody hears it. These run everywhere. + +@Suite("Driver channel interleaving") +struct InterleaveHelpersTests { + + private func interleaved( + _ buses: [[Float]], + frameCount: Int, + channelCount: Int + ) -> [Float] { + var out: [Float] = [Float](repeating: .nan, count: frameCount * channelCount) + out.withUnsafeMutableBufferPointer { dst in + guard let base: UnsafeMutablePointer = dst.baseAddress else { return } + lyrebirdInterleave(buses, into: base, frameCount: frameCount, channelCount: channelCount) + } + return out + } + + @Test func interleavesStereoInFrameOrder() { + let buses: [[Float]] = [ + [1, 2, 3], + [-1, -2, -3], + ] + let out: [Float] = interleaved(buses, frameCount: 3, channelCount: 2) + #expect(out == [1, -1, 2, -2, 3, -3]) + } + + @Test func missingChannelIsWrittenAsSilence() { + // Engine configured for more output channels than buses provided. + let buses: [[Float]] = [[1, 2]] + let out: [Float] = interleaved(buses, frameCount: 2, channelCount: 3) + #expect(out == [1, 0, 0, 2, 0, 0]) + } + + @Test func shortBusIsPaddedWithSilence() { + let buses: [[Float]] = [ + [1, 2], + [-1, -2, -3, -4], + ] + // Channel 0 runs out after two frames; the rest of its frames are + // silence while channel 1 keeps playing. + let out: [Float] = interleaved(buses, frameCount: 4, channelCount: 2) + #expect(out == [1, -1, 2, -2, 0, -3, 0, -4]) + } + + @Test func deinterleaveIsTheInverseOfInterleave() { + let frameCount: Int = 5 + let channelCount: Int = 3 + let original: [[Float]] = (0.. = src.baseAddress else { return } + lyrebirdDeinterleave(base, into: &recovered, frameCount: frameCount, channelCount: channelCount) + } + #expect(recovered == original) + } + + @Test func deinterleaveIgnoresChannelsWithNoDestinationBus() { + // Two channels arriving, one staging bus: the extra channel is dropped + // rather than overrunning the array. + let packed: [Float] = [1, -1, 2, -2] + var buses: [[Float]] = [[Float](repeating: 0, count: 2)] + packed.withUnsafeBufferPointer { src in + guard let base: UnsafePointer = src.baseAddress else { return } + lyrebirdDeinterleave(base, into: &buses, frameCount: 2, channelCount: 2) + } + #expect(buses == [[1, 2]]) + } +} diff --git a/Tests/LyrebirdPortableTests/OSCLoopbackTests.swift b/Tests/LyrebirdPortableTests/OSCLoopbackTests.swift new file mode 100644 index 0000000..741072c --- /dev/null +++ b/Tests/LyrebirdPortableTests/OSCLoopbackTests.swift @@ -0,0 +1,279 @@ +// OSCLoopbackTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +@_spi(LyrebirdExtensions) import LyrebirdSynth +#if canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#endif + +// End-to-end OSC over real UDP loopback: an `OSCServer` bound to 127.0.0.1 and an +// `OSCClient` sending to it. On Apple this drives `Network.framework`; off Apple +// it drives the POSIX-socket transport added for Linux — and, unlike the MIDI and +// audio backends, needs no hardware, so it runs everywhere and is the actual +// acceptance check for OSC on Linux. +@MainActor +@Suite("OSC UDP loopback") +struct OSCLoopbackTests { + + private func makeEngine() -> SynthesisEngine { + SynthesisEngine( + blockSize: 64, sampleRate: 44100, + numOutputChannels: 2, numInputChannels: 0, + driver: OfflineDriver() + ) + } + + /// Bind a server on some free port in a high range, retrying past a port + /// already in use. Returns the started server and its port. + private func startServer( + _ engine: SynthesisEngine, + configure: (OSCServer) -> Void + ) throws -> OSCServer { + var lastError: (any Error)? + for candidate: UInt16 in stride(from: UInt16(9800), through: UInt16(9840), by: 1) { + let server: OSCServer = OSCServer(port: candidate, engine: engine) + configure(server) + do { + try server.start() + return server + } catch { + lastError = error // port in use — try the next + } + } + throw lastError ?? OSCTestError.noFreePort + } + + private enum OSCTestError: Error { case noFreePort } + + /// Fire the client repeatedly until the handler signals or the deadline + /// passes — covers both the listener-not-yet-ready startup race and UDP's + /// own permission to drop a datagram. + private func waitForDelivery( + send: () -> Void, + arrived: DispatchSemaphore, + timeout: TimeInterval = 3.0 + ) -> Bool { + let deadline: Date = Date(timeIntervalSinceNow: timeout) + while Date() < deadline { + send() + if arrived.wait(timeout: .now() + 0.05) == .success { return true } + } + return false + } + + @Test func messageRoundTripsWithArguments() throws { + let engine: SynthesisEngine = makeEngine() + let arrived: DispatchSemaphore = DispatchSemaphore(value: 0) + let received: LockedBox = LockedBox() + + let server: OSCServer = try startServer(engine) { s in + s.addHandler(address: "/synth/freq") { msg, _ in + received.set(address: msg.address, + int: msg[0]?.intValue, + float: msg[1]?.floatValue, + string: msg[2]?.stringValue) + arrived.signal() + } + } + defer { server.stop() } + + let client: OSCClient = OSCClient(host: "127.0.0.1", port: server.port) + let delivered: Bool = waitForDelivery( + send: { + client.send(address: "/synth/freq", + args: [.int32(440), .float32(1.5), .string("hi")]) + }, + arrived: arrived + ) + + #expect(delivered, "the message never arrived over loopback") + #expect(received.address == "/synth/freq") + #expect(received.int == 440) + #expect(received.float == 1.5) + #expect(received.string == "hi") + } + + @Test func patternAddressMatchesOnDelivery() throws { + let engine: SynthesisEngine = makeEngine() + let arrived: DispatchSemaphore = DispatchSemaphore(value: 0) + let hitCount: LockedCounter = LockedCounter() + + let server: OSCServer = try startServer(engine) { s in + // Glob pattern: should match "/synth/cutoff". + s.addHandler(address: "/synth/*") { _, _ in + hitCount.increment() + arrived.signal() + } + } + defer { server.stop() } + + let client: OSCClient = OSCClient(host: "127.0.0.1", port: server.port) + let delivered: Bool = waitForDelivery( + send: { client.send(address: "/synth/cutoff", args: [.float32(0.5)]) }, + arrived: arrived + ) + #expect(delivered, "the wildcard handler never fired") + #expect(hitCount.value >= 1) + } + + @Test func removedHandlerStopsReceiving() throws { + let engine: SynthesisEngine = makeEngine() + let arrived: DispatchSemaphore = DispatchSemaphore(value: 0) + let hits: LockedCounter = LockedCounter() + + var token: OSCHandlerToken? + let server: OSCServer = try startServer(engine) { s in + token = s.addHandler(address: "/x") { _, _ in + hits.increment() + arrived.signal() + } + } + defer { server.stop() } + + // Confirm the handler works, then remove it and confirm silence. + let client: OSCClient = OSCClient(host: "127.0.0.1", port: server.port) + #expect(waitForDelivery(send: { client.send(address: "/x") }, arrived: arrived), + "handler should fire before removal") + if let token: OSCHandlerToken = token { server.removeHandler(token) } + + let countAfterRemoval: Int = hits.value + // Send several more; none should reach the removed handler. + for _ in 0..<10 { client.send(address: "/x") } + Thread.sleep(forTimeInterval: 0.3) + #expect(hits.value == countAfterRemoval, "a removed handler must not keep receiving") + } + + // The POSIX receive loop must survive a zero-length UDP datagram — a valid + // packet any peer can send. The bug this guards (recv==0 treated as a close, + // killing the listener) lived only in the non-Network transport, so the test + // does too. On Apple the empty datagram is filtered by the `!data.isEmpty` + // guard in the NWListener path. + #if !canImport(Network) + @Test func emptyDatagramDoesNotKillListener() throws { + let engine: SynthesisEngine = makeEngine() + let arrived: DispatchSemaphore = DispatchSemaphore(value: 0) + + let server: OSCServer = try startServer(engine) { s in + s.addHandler(address: "/ping") { _, _ in arrived.signal() } + } + defer { server.stop() } + + // Fire a raw zero-length datagram straight at the port. + let raw: Int32 = socket(AF_INET, Int32(SOCK_DGRAM.rawValue), 0) + #expect(raw >= 0) + if raw >= 0 { + var addr: sockaddr_in = sockaddr_in() + addr.sin_family = sa_family_t(AF_INET) + addr.sin_port = server.port.bigEndian + _ = inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr) + _ = withUnsafePointer(to: &addr) { ptr in + ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sa in + connect(raw, sa, socklen_t(MemoryLayout.size)) + } + } + // A couple of empty datagrams — the old code broke on the first. + for _ in 0..<3 { _ = sendto(raw, nil, 0, Int32(MSG_NOSIGNAL), nil, 0) } + close(raw) + } + + // The listener must still be alive: a normal message gets through. + let client: OSCClient = OSCClient(host: "127.0.0.1", port: server.port) + let delivered: Bool = waitForDelivery( + send: { client.send(address: "/ping") }, + arrived: arrived + ) + #expect(delivered, "an empty datagram killed the listener") + } + #endif + + @Test func doubleStartIsIdempotent() throws { + // Calling start() on an already-started server returns without binding a + // second socket or launching a second thread, and the server keeps + // working. On Apple this is NWListener's duplicate-cancel; off Apple it + // is the atomic `isStarted` claim. + let engine: SynthesisEngine = makeEngine() + let arrived: DispatchSemaphore = DispatchSemaphore(value: 0) + let server: OSCServer = try startServer(engine) { s in + s.addHandler(address: "/twice") { _, _ in arrived.signal() } + } + defer { server.stop() } + + try server.start() // second start — must be a clean no-op + try server.start() // and a third + + let client: OSCClient = OSCClient(host: "127.0.0.1", port: server.port) + #expect(waitForDelivery(send: { client.send(address: "/twice") }, arrived: arrived), + "server should still deliver after redundant start() calls") + } + + // Linux-only: the atomic `isStarted` claim being hardened lives in the POSIX + // branch. On Apple, `NWListener` reports a bind failure asynchronously, so a + // fixed-port concurrent-start test cannot assert deterministically there — + // and that path was already duplicate-safe via NWListener's own cancel. + #if !canImport(Network) + @Test func concurrentStartsAreSerializedByTheClaim() throws { + // Start the server on a known-free port, then fire many start() calls at + // it concurrently. Each must return cleanly (the claim sees `isStarted` + // already set) — no second bind, no second thread, no crash — and the + // server must keep delivering. + let engine: SynthesisEngine = makeEngine() + let arrived: DispatchSemaphore = DispatchSemaphore(value: 0) + let server: OSCServer = try startServer(engine) { s in + s.addHandler(address: "/race") { _, _ in arrived.signal() } + } + defer { server.stop() } + + let group: DispatchGroup = DispatchGroup() + let failures: LockedCounter = LockedCounter() + for _ in 0..<8 { + DispatchQueue.global().async(group: group) { + do { try server.start() } catch { failures.increment() } + } + } + group.wait() + #expect(failures.value == 0, "\(failures.value) redundant concurrent start()s threw") + + let client: OSCClient = OSCClient(host: "127.0.0.1", port: server.port) + #expect(waitForDelivery(send: { client.send(address: "/race") }, arrived: arrived), + "server should still deliver after concurrent start() calls") + } + #endif + + @Test func stopIsIdempotentAndSafeBeforeStart() { + let server: OSCServer = OSCServer(port: 9899, engine: makeEngine()) + server.stop() + server.stop() + } +} + +// MARK: - Small thread-safe test boxes + +private final class LockedBox: @unchecked Sendable { + private let lock: NSLock = NSLock() + private var _address: String? + private var _int: Int32? + private var _float: Float? + private var _string: String? + + func set(address: String?, int: Int32?, float: Float?, string: String?) { + lock.withLock { _address = address; _int = int; _float = float; _string = string } + } + var address: String? { lock.withLock { _address } } + var int: Int32? { lock.withLock { _int } } + var float: Float? { lock.withLock { _float } } + var string: String? { lock.withLock { _string } } +} + +private final class LockedCounter: @unchecked Sendable { + private let lock: NSLock = NSLock() + private var _value: Int = 0 + func increment() { lock.withLock { _value += 1 } } + var value: Int { lock.withLock { _value } } +} diff --git a/Tests/LyrebirdPortableTests/PortableFileIOTests.swift b/Tests/LyrebirdPortableTests/PortableFileIOTests.swift new file mode 100644 index 0000000..08ec0db --- /dev/null +++ b/Tests/LyrebirdPortableTests/PortableFileIOTests.swift @@ -0,0 +1,264 @@ +// PortableFileIOTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +@_spi(LyrebirdExtensions) import LyrebirdSynth + +// Exercises the off-Apple file-I/O paths — `LyrebirdBuffer.load` / `loadAllChannels` +// / `fill` / `write` and `DiskIn.Audio` — through the portable `WavFileWriter` / +// `WavFileReader` backend. Fixtures are written with `WavFileWriter` (portable, +// both platforms) so these run everywhere, unlike the AudioToolbox-based +// `LyrebirdBufferFileIOTests` in the macOS-only suite. On Apple these same paths +// go through `ExtAudioFile`; a round trip that agrees on both is the point. + +@Suite("Portable file I/O — LyrebirdBuffer") +struct PortableBufferFileIOTests { + + private func tempURL() -> URL { + FileManager.default.temporaryDirectory + .appendingPathComponent("lyrebird-fileio-\(UUID().uuidString).wav") + } + + /// Distinct, in-range value for (frame, channel) so a transposed read shows up. + private func sample(frame: Int, channel: Int) -> Float { + Float((sin(Double(frame) * 0.02 + Double(channel) * 1.3)) * 0.6) + } + + private func writeWAV(frames: Int, channels: Int, sampleRate: Double = 44100) throws -> URL { + let url: URL = tempURL() + var interleaved: [Float] = [Float](repeating: 0, count: frames * channels) + for f: Int in 0.. URL { + FileManager.default.temporaryDirectory + .appendingPathComponent("lyrebird-diskin-\(UUID().uuidString).wav") + } + + private func ramp(frame: Int, channel: Int) -> Float { + Float(sin(Double(frame) * 0.013 + Double(channel))) * 0.5 + } + + private func writeWAV(frames: Int, channels: Int, sampleRate: Double) throws -> URL { + let url: URL = tempURL() + var interleaved: [Float] = [Float](repeating: 0, count: frames * channels) + for f: Int in 0.. fileFrames / 2) + } + #endif + + @Test func nonWavFileThrows() throws { + let url: URL = tempURL() + defer { try? FileManager.default.removeItem(at: url) } + try Data([0, 1, 2, 3, 4, 5, 6, 7]).write(to: url) + #expect(throws: (any Error).self) { + _ = try DiskIn.Audio(url: url, channelCount: 1, sampleRate: 44100) + } + } +} diff --git a/Tests/LyrebirdPortableTests/PortableTestSupport.swift b/Tests/LyrebirdPortableTests/PortableTestSupport.swift new file mode 100644 index 0000000..c80de48 --- /dev/null +++ b/Tests/LyrebirdPortableTests/PortableTestSupport.swift @@ -0,0 +1,76 @@ +// PortableTestSupport.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +@_spi(LyrebirdExtensions) import LyrebirdSynth + +// Local copies of the engine/collect helpers used by `LyrebirdTests`. SwiftPM +// test targets cannot share sources, and this target is deliberately limited to +// the public (+ extension-SPI) surface — part of what is being proven is that +// the portable surface is reachable and correct off Apple. + +/// Offline engine for deterministic block-by-block generator evaluation. +func makePortableTestEngine( + blockSize: Int = 64, + sampleRate: Double = 44100 +) -> SynthesisEngine { + SynthesisEngine( + blockSize: blockSize, + sampleRate: sampleRate, + numOutputChannels: 2, + numInputChannels: 2, + driver: OfflineDriver() + ) +} + +/// Drive a generator for `blocks` blocks and return `blockSize` samples per block. +func collectPortableBlocks( + _ gen: any Generator, + engine: SynthesisEngine, + blocks: Int, + channel: Int = 0 +) -> [Double] { + let bs: Int = engine.blockSize + var out: [Double] = [] + out.reserveCapacity(blocks * bs) + for _ in 0..= golden.count, + "\(label): produced \(actual.count) samples, golden has \(golden.count)", + sourceLocation: sourceLocation) + guard actual.count >= golden.count else { return } + for i: Int in 0.. magnitudes[peakBin] { + peakBin = bin + } + #expect(peakBin == Self.analysisBin, "peak landed in bin \(peakBin)") + } + + @Test func resynthesisReconstructsInputSine() throws { + let engine: SynthesisEngine = makePortableTestEngine( + blockSize: Self.hopSize, + sampleRate: Self.sampleRate + ) + try engine.start() + defer { engine.stop() } + + let chain: SpectralChain.Audio = SpectralChain.Audio( + input: OscSin.Audio(freq: Self.binFrequency), + fftSize: Self.fftSize, + hopSize: Self.hopSize + ) + + var resynthesised: [Double] = [] + for _ in 0.. URL { + FileManager.default.temporaryDirectory + .appendingPathComponent("lyrebird-wavhdr-\(UUID().uuidString).wav") + } + + /// Builds a WAV whose `fmt ` chunk is written verbatim, so a test can hand + /// the reader a header no writer of ours would produce. + private func writeWav(fmtChunk: [UInt8], dataBytes: [UInt8], to url: URL) throws { + var file: [UInt8] = [] + func appendLE32(_ value: UInt32) { + file.append(contentsOf: [ + UInt8(truncatingIfNeeded: value), + UInt8(truncatingIfNeeded: value >> 8), + UInt8(truncatingIfNeeded: value >> 16), + UInt8(truncatingIfNeeded: value >> 24), + ]) + } + file.append(contentsOf: Array("RIFF".utf8)) + appendLE32(UInt32(4 + 8 + fmtChunk.count + 8 + dataBytes.count)) + file.append(contentsOf: Array("WAVE".utf8)) + file.append(contentsOf: Array("fmt ".utf8)) + appendLE32(UInt32(fmtChunk.count)) + file.append(contentsOf: fmtChunk) + file.append(contentsOf: Array("data".utf8)) + appendLE32(UInt32(dataBytes.count)) + file.append(contentsOf: dataBytes) + try Data(file).write(to: url) + } + + private func le16(_ value: UInt16) -> [UInt8] { + [UInt8(truncatingIfNeeded: value), UInt8(truncatingIfNeeded: value >> 8)] + } + + private func le32(_ value: UInt32) -> [UInt8] { + [ + UInt8(truncatingIfNeeded: value), + UInt8(truncatingIfNeeded: value >> 8), + UInt8(truncatingIfNeeded: value >> 16), + UInt8(truncatingIfNeeded: value >> 24), + ] + } + + /// 16-byte PCM `fmt ` body. + private func pcmFmt(tag: UInt16, channels: UInt16, rate: UInt32, bits: UInt16) -> [UInt8] { + let blockAlign: UInt16 = channels * (bits / 8) + var out: [UInt8] = [] + out += le16(tag) + out += le16(channels) + out += le32(rate) + out += le32(rate * UInt32(blockAlign)) + out += le16(blockAlign) + out += le16(bits) + return out + } + + @Test("a fmt chunk too short to hold its fields throws instead of trapping") + func shortFmtChunkThrows() throws { + // 14 bytes: everything except bitsPerSample, which the reader loads at + // offset 14. Before the length check this indexed past the chunk. + let url: URL = tempURL() + defer { try? FileManager.default.removeItem(at: url) } + let truncatedFmt: [UInt8] = Array(pcmFmt(tag: 1, channels: 1, rate: 44100, bits: 16).prefix(14)) + try writeWav(fmtChunk: truncatedFmt, dataBytes: [0, 0, 0, 0], to: url) + + #expect(throws: WavFileError.truncated) { + _ = try WavFileReader(url: url) + } + } + + @Test("WAVE_FORMAT_EXTENSIBLE is read via its SubFormat GUID") + func extensibleFormatIsAccepted() throws { + // What most 24-bit and multichannel writers actually emit. The header + // is a PCM header with tag 0xFFFE plus a 22-byte extension whose GUID + // opens with the real format tag (1 = PCM). + let url: URL = tempURL() + defer { try? FileManager.default.removeItem(at: url) } + + var fmt: [UInt8] = pcmFmt(tag: 0xFFFE, channels: 2, rate: 48000, bits: 24) + fmt += le16(22) // cbSize + fmt += le16(24) // validBitsPerSample + fmt += le32(3) // channel mask: front left + right + fmt += le16(1) // SubFormat GUID: leading tag = PCM + fmt += [UInt8](repeating: 0, count: 14) // rest of the GUID + + // Two frames of stereo 24-bit silence. + let data: [UInt8] = [UInt8](repeating: 0, count: 2 * 2 * 3) + try writeWav(fmtChunk: fmt, dataBytes: data, to: url) + + let reader: WavFileReader = try WavFileReader(url: url) + defer { reader.close() } + #expect(reader.encoding == .int24) + #expect(reader.channels == 2) + #expect(reader.sampleRate == 48000) + #expect(reader.frameCount == 2) + } + + @Test("an unreadable extensible SubFormat is still reported, not guessed") + func extensibleWithUnsupportedSubFormatThrows() throws { + let url: URL = tempURL() + defer { try? FileManager.default.removeItem(at: url) } + + var fmt: [UInt8] = pcmFmt(tag: 0xFFFE, channels: 1, rate: 44100, bits: 16) + fmt += le16(22) + fmt += le16(16) + fmt += le32(4) + fmt += le16(0x0011) // ADPCM — not something we decode + fmt += [UInt8](repeating: 0, count: 14) + try writeWav(fmtChunk: fmt, dataBytes: [0, 0], to: url) + + #expect(throws: WavFileError.unsupportedFormat(formatTag: 0x0011, bitsPerSample: 16)) { + _ = try WavFileReader(url: url) + } + } + + @Test("a float32 file declares cbSize and carries a fact chunk") + func float32HeaderIsSpecCompliant() throws { + // RIFF requires non-PCM tags to declare `cbSize` — an 18-byte `fmt ` + // body — and to carry a `fact` chunk holding the sample count. Writers + // that emit the plain 16-byte PCM header for float data are rejected by + // strict readers. + let url: URL = tempURL() + defer { try? FileManager.default.removeItem(at: url) } + let channels: Int = 2 + let frames: Int = 10 + + let writer: WavFileWriter = try WavFileWriter( + url: url, channels: channels, sampleRate: 48000, encoding: .float32 + ) + try writer.write( + interleaved: [Float](repeating: 0.25, count: frames * channels), + frames: frames + ) + try writer.finalize() + + let bytes: [UInt8] = [UInt8](try Data(contentsOf: url)) + func le16(at offset: Int) -> UInt16 { + UInt16(bytes[offset]) | (UInt16(bytes[offset + 1]) << 8) + } + func le32(at offset: Int) -> UInt32 { + UInt32(bytes[offset]) + | (UInt32(bytes[offset + 1]) << 8) + | (UInt32(bytes[offset + 2]) << 16) + | (UInt32(bytes[offset + 3]) << 24) + } + + #expect(String(decoding: bytes[12..<16], as: UTF8.self) == "fmt ") + #expect(le32(at: 16) == 18, "fmt body must be 18 bytes for a non-PCM tag") + #expect(le16(at: 20) == 3, "format tag 3 = IEEE float") + #expect(le16(at: 36) == 0, "cbSize: no format extension") + #expect(String(decoding: bytes[38..<42], as: UTF8.self) == "fact") + #expect(le32(at: 42) == 4, "fact body is one UInt32") + #expect(le32(at: 46) == UInt32(frames), "fact holds the per-channel sample count") + #expect(String(decoding: bytes[50..<54], as: UTF8.self) == "data") + #expect(le32(at: 54) == UInt32(frames * channels * 4)) + // RIFF size counts everything after the first eight bytes. + #expect(le32(at: 4) == UInt32(bytes.count - 8)) + } + + @Test("an integer file keeps the canonical 44-byte header") + func int16HeaderStaysCanonical() throws { + let url: URL = tempURL() + defer { try? FileManager.default.removeItem(at: url) } + let writer: WavFileWriter = try WavFileWriter( + url: url, channels: 1, sampleRate: 44100, encoding: .int16 + ) + try writer.write(interleaved: [Float](repeating: 0, count: 4), frames: 4) + try writer.finalize() + + let bytes: [UInt8] = [UInt8](try Data(contentsOf: url)) + func le32(at offset: Int) -> UInt32 { + UInt32(bytes[offset]) + | (UInt32(bytes[offset + 1]) << 8) + | (UInt32(bytes[offset + 2]) << 16) + | (UInt32(bytes[offset + 3]) << 24) + } + #expect(le32(at: 16) == 16, "PCM fmt body stays 16 bytes") + #expect(String(decoding: bytes[36..<40], as: UTF8.self) == "data") + #expect(le32(at: 40) == UInt32(4 * 2)) + #expect(bytes.count == 44 + 4 * 2) + } + + @Test("the 4 GB RIFF boundary throws instead of trapping") + func riffSizeOverflowThrows() throws { + // The conversion this guards used to be a plain `UInt32(...)`, which + // traps — and a trap an hour into an offline render is the worst + // possible outcome. Tested through the size computation so the boundary + // can be crossed without writing four gigabytes. + let header: Int = 44 + let justUnder: Int = Int(UInt32.max) - header + 8 + #expect(try WavFileWriter.riffChunkSize(headerBytes: header, dataBytes: justUnder) == UInt32.max) + + #expect(throws: WavFileError.fileTooLarge(bytes: Int(UInt32.max) + 1)) { + _ = try WavFileWriter.riffChunkSize(headerBytes: header, dataBytes: justUnder + 1) + } + } + + @Test("an odd data payload is padded to a word boundary") + func oddDataPayloadIsPadded() throws { + // int24 mono with an odd frame count produces an odd `data` chunk. RIFF + // requires the next chunk to start on a word boundary, so a pad byte + // follows the payload — counted in the RIFF size, not the data size. + let url: URL = tempURL() + defer { try? FileManager.default.removeItem(at: url) } + let frames: Int = 3 // 3 frames x 1 channel x 3 bytes = 9, odd + + let writer: WavFileWriter = try WavFileWriter( + url: url, channels: 1, sampleRate: 44100, encoding: .int24 + ) + try writer.write(interleaved: [Float](repeating: 0.5, count: frames), frames: frames) + try writer.finalize() + + let bytes: [UInt8] = [UInt8](try Data(contentsOf: url)) + func le32(at offset: Int) -> UInt32 { + UInt32(bytes[offset]) + | (UInt32(bytes[offset + 1]) << 8) + | (UInt32(bytes[offset + 2]) << 16) + | (UInt32(bytes[offset + 3]) << 24) + } + #expect(le32(at: 40) == UInt32(frames * 3), "data size counts payload only") + #expect(bytes.count == 44 + frames * 3 + 1, "a pad byte follows the payload") + #expect(le32(at: 4) == UInt32(bytes.count - 8), "RIFF size includes the pad") + #expect(bytes[bytes.count - 1] == 0) + } + + @Test("a data size larger than the file is clamped to what is there") + func oversizedDataChunkIsClamped() throws { + // Streaming writers leave a placeholder `data` size they never patch. + // Believing it produces a nonsense frame count and a mid-render throw + // rather than a clean end of file. + let url: URL = tempURL() + defer { try? FileManager.default.removeItem(at: url) } + let realFrames: Int = 4 + let channels: Int = 2 + + var file: [UInt8] = [] + file += Array("RIFF".utf8) + file += le32(0xFFFF_FFFF) + file += Array("WAVE".utf8) + file += Array("fmt ".utf8) + file += le32(16) + file += pcmFmt(tag: 1, channels: UInt16(channels), rate: 44100, bits: 16) + file += Array("data".utf8) + file += le32(0xFFFF_FFFF) // lying placeholder + file += [UInt8](repeating: 0, count: realFrames * channels * 2) + try Data(file).write(to: url) + + let reader: WavFileReader = try WavFileReader(url: url) + defer { reader.close() } + #expect(reader.frameCount == realFrames) + let all: [Float] = try reader.read(frames: realFrames * 4) + #expect(all.count == realFrames * channels) + } +} diff --git a/Tests/LyrebirdPortableTests/WavCodecTests.swift b/Tests/LyrebirdPortableTests/WavCodecTests.swift new file mode 100644 index 0000000..c1eb526 --- /dev/null +++ b/Tests/LyrebirdPortableTests/WavCodecTests.swift @@ -0,0 +1,154 @@ +// WavCodecTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth + +@Suite("Portable WAV codec") +struct WavCodecTests { + + private func tempURL(_ ext: String) -> URL { + let dir: URL = FileManager.default.temporaryDirectory + return dir.appendingPathComponent("lyrebird-wavtest-\(UUID().uuidString).\(ext)") + } + + private func makeInterleaved(frames: Int, channels: Int) -> [Float] { + var out: [Float] = [Float](repeating: 0, count: frames * channels) + for f: Int in 0.. String { return "try DSLArgument.\(helper)(\(source), \(where_))" } +/// Number of registry entries per emitted chunk array. +/// +/// The registry is emitted as several `private static let _chunkN` arrays +/// concatenated into `generated`, rather than one big `[ ... ]` literal. A +/// single literal of all ~300 entries is checked by the Swift type-checker as +/// one expression and needs several GB of RAM to compile — enough to OOM-kill +/// the compiler (SIGKILL) on a memory-constrained Linux/CI runner. Splitting it +/// lets each chunk type-check independently, keeping peak memory low and the +/// Linux build parallelizable. +let registryChunkSize: Int = 32 + +/// Renders one `DSLBuiltin(...)` entry (trailing `,\n`) at the indentation used +/// inside a chunk array literal. +func emitRegistryEntry(_ g: ScannedGenerator) -> String { + let exposed: [ScannedParameter] = g.exposedParameters + let paramList: String = exposed + .map { " DSLParameter(label: \"\($0.label)\", hasDefault: \(effectiveHasDefault($0))),\n" } + .joined() + let callArgs: String = exposed + .map { p in + let expr: String = argumentExpression(p, builtin: g.name) + let prefix: String = p.isPositional ? "" : "\(p.label): " + return " \(prefix)\(expr)" + } + .joined(separator: ",\n") + // Empty-argument constructors emit `Foo()`; otherwise a multi-line call. + let makeBody: String = exposed.isEmpty + ? " \(g.constructor)()" + : " \(g.constructor)(\n\(callArgs)\n )" + return """ + DSLBuiltin( + name: "\(g.name)", + rate: .\(g.rate), + parameters: [ + \(paramList) ], + make: { args in + \(makeBody) + } + ),\n + """ +} + func emitRegistry(_ generators: [ScannedGenerator]) -> String { + // Split entries into fixed-size chunks so each emitted array literal stays + // small enough to type-check cheaply. Always emit at least one chunk (even + // when empty) so `generated` has a well-formed initializer. + let chunks: [[ScannedGenerator]] = stride(from: 0, to: max(generators.count, 1), by: registryChunkSize) + .map { start in + let end: Int = min(start + registryChunkSize, generators.count) + return start < end ? Array(generators[start.. String { /// sources. A generator appears here when all of its init parameters are /// either DSL-expressible (a signal/number) or have a Swift default that /// can be omitted. - static let generated: [DSLBuiltin] = [\n + /// + /// Assembled from `_chunkN` arrays below. The split keeps each emitted + /// literal small enough for the type-checker to compile in modest memory; + /// a single ~300-element literal OOM-kills the compiler on constrained + /// Linux/CI runners. + static let generated: [DSLBuiltin] = \(concatExpr)\n\n """ - for g: ScannedGenerator in generators { - let exposed: [ScannedParameter] = g.exposedParameters - let paramList: String = exposed - .map { " DSLParameter(label: \"\($0.label)\", hasDefault: \(effectiveHasDefault($0))),\n" } - .joined() - let callArgs: String = exposed - .map { p in - let expr: String = argumentExpression(p, builtin: g.name) - let prefix: String = p.isPositional ? "" : "\(p.label): " - return " \(prefix)\(expr)" - } - .joined(separator: ",\n") - // Empty-argument constructors emit `Foo()`; otherwise a multi-line call. - let makeBody: String = exposed.isEmpty - ? " \(g.constructor)()" - : " \(g.constructor)(\n\(callArgs)\n )" - out += """ - DSLBuiltin( - name: "\(g.name)", - rate: .\(g.rate), - parameters: [ - \(paramList) ], - make: { args in - \(makeBody) - } - ),\n - """ + for (index, chunk): (Int, [ScannedGenerator]) in chunks.enumerated() { + out += " private static let \(chunkNames[index]): [DSLBuiltin] = [\n" + for g: ScannedGenerator in chunk { + out += emitRegistryEntry(g) + } + out += " ]\n\n" } out += """ - ] } """ diff --git a/bitbucket-pipelines.yml b/bitbucket-pipelines.yml new file mode 100644 index 0000000..0d5ffd0 --- /dev/null +++ b/bitbucket-pipelines.yml @@ -0,0 +1,93 @@ +# bitbucket-pipelines.yml +# Lyrebird — Linux CI +# +# Builds and tests the Linux-supported surface of Lyrebird on the official +# swift.org Ubuntu image, so a change that breaks the cross-platform port +# (e.g. a new generator importing Accelerate/Darwin directly, C `stderr` usage +# that trips Swift 6 concurrency on Linux, or a broken `#else`/`#elseif +# os(Linux)` UI body) fails CI instead of shipping silently. +# +# One job, because `swift test` on a Linux host builds the WHOLE package graph — +# and that graph now includes the cross-platform `LyrebirdUI` module, its GTK4 +# backend (via the SwiftOpenUI fork), and the `LyrebirdUILinuxDemo` executable. +# So the test job already compiles the Linux UI; it just needs the GTK dev +# headers present. That makes the UI a first-class part of this job (its +# regression lock — a macOS build can't see the Linux bodies, they're `#if`-d +# out on Apple), and avoids a second parallel runner, which on BitBucket would +# cost extra build minutes to recompile the same graph. +# +# The macOS/iOS build is unaffected: the Apple-only test targets (LyrebirdTests, +# LyrebirdBenchmark — see Package.swift) are omitted on a Linux host; LyrebirdUI +# itself is cross-platform (SwiftUI on Apple, SwiftOpenUI/GTK4 on Linux). +# +# Runners: BitBucket's Linux runners are x86_64, so this is a native amd64 +# build — a second architecture beyond the Apple arm64 dev machines, which is +# extra coverage, not a limitation. + +image: swift:6.3.3 + +definitions: + caches: + # Persist the SwiftPM build tree between runs to avoid recompiling the + # whole graph every time. Keyed on the image's Swift version. + swiftpm-build: .build + steps: + - step: &linux-build-test + name: Linux build + test (GTK4, Swift 6.3.3) + # The graph is large (core + SwiftOpenUI + the GTK4 backend + the demo); + # give the compiler 8 GB — a 4 GB box OOM-cancels the link. + size: 2x + caches: + - swiftpm-build + script: + - swift --version + # Dev packages the Linux graph compiles against: + # libgtk-4-dev — the SwiftOpenUI `CGTK` system library (pkgConfig + # "gtk4"); without it `swift test` fails building + # the UI graph with "gtk/gtk.h file not found". + # libgtksourceview-5-dev — the SwiftOpenUI `CGtkSource` system library + # (pkgConfig "gtksourceview-5") behind the CodeEditor + # view (the live-compile scratch editor). + # libfontconfig-dev — BackendGTK4 links fontconfig for its bundled-font + # registration; gtk4's pkg-config --libs doesn't name it. + # libasound2-dev — the core `CALSA` system-library target (the Linux + # ALSA live-audio backend). See the LYREBIRD_DISABLE_ALSA + # escape hatch in Package.swift for boxes with no audio. + # pkg-config — resolves the above for SwiftPM. + - apt-get update && apt-get install -y --no-install-recommends libgtk-4-dev libgtksourceview-5-dev libfontconfig-dev libasound2-dev pkg-config + # Core build gate — the three portable shipping targets, checked + # explicitly so a core-only regression fails fast with a clear target. + - swift build --target LyrebirdSynth --target LyrebirdGraphDSL --target LyrebirdCLI + # UI build gate — compiles the full LyrebirdUI + BackendGTK4 chain and + # links the demo executable (compile-only; CI has no display, so no + # `swift run`). The SwiftOpenUI fork is fetched from its pinned revision + # (Package.swift), exactly as a developer's Linux build does. This is the + # Linux-UI regression lock. + - swift build --product LyrebirdUILinuxDemo + # Run the Linux-runnable test targets (LyrebirdDSPTests, + # LyrebirdGraphDSLTests, LyrebirdCLITests, LyrebirdPortableTests). + # `swift test` builds and runs every target the Linux manifest exposes + # (the Apple-only test targets are omitted on a Linux host — see + # Package.swift). LyrebirdPortableTests carries the golden-value DSP + # checks: this run is the only place the portable FFT/biquad/vector + # fallbacks are verified to produce correct audio, since the parity + # suite they replace compares against real vDSP and is Apple-only. + - swift test + # The documented escape hatch for a Linux box with no ALSA + # development package. Exercised here because it is a manifest-level + # branch: nothing else in this job compiles the package *without* + # `CALSA`, so a regression there would only surface on a user's + # machine. `swift test`, not just `swift build` — the ALSA driver's + # own tests are `#if canImport(CALSA)`-guarded, and a guard that does + # not match the driver's condition breaks compilation of the test + # target alone, which a build-only check cannot see. + - LYREBIRD_DISABLE_ALSA=1 swift test --scratch-path .build-noalsa + +pipelines: + # Every branch push (covers the feature branch and main). + default: + - step: *linux-build-test + # Pull requests targeting main. + pull-requests: + '**': + - step: *linux-build-test diff --git a/docs/cross-platform-feasibility.md b/docs/cross-platform-feasibility.md new file mode 100644 index 0000000..b4e4ba1 --- /dev/null +++ b/docs/cross-platform-feasibility.md @@ -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, _ 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 --checksum +# 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 +``` diff --git a/docs/engine/alsa-audio-driver.md b/docs/engine/alsa-audio-driver.md new file mode 100644 index 0000000..12f943b --- /dev/null +++ b/docs/engine/alsa-audio-driver.md @@ -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. diff --git a/docs/engine/multi-core.md b/docs/engine/multi-core.md index 79e5f8a..b9c051b 100644 --- a/docs/engine/multi-core.md +++ b/docs/engine/multi-core.md @@ -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** diff --git a/docs/engine/portable-wav-codec.md b/docs/engine/portable-wav-codec.md new file mode 100644 index 0000000..29d2542 --- /dev/null +++ b/docs/engine/portable-wav-codec.md @@ -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. diff --git a/docs/engine/synthesis-engine.md b/docs/engine/synthesis-engine.md index eb72e67..efc8765 100644 --- a/docs/engine/synthesis-engine.md +++ b/docs/engine/synthesis-engine.md @@ -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` 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. diff --git a/docs/linux-getting-started.md b/docs/linux-getting-started.md new file mode 100644 index 0000000..3f0563d --- /dev/null +++ b/docs/linux-getting-started.md @@ -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. diff --git a/docs/protocols/synthesizer.md b/docs/protocols/synthesizer.md index fd21fce..5d885f3 100644 --- a/docs/protocols/synthesizer.md +++ b/docs/protocols/synthesizer.md @@ -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. diff --git a/docs/tooling/nrt-guide.md b/docs/tooling/nrt-guide.md index 71657a8..fe741f1 100644 --- a/docs/tooling/nrt-guide.md +++ b/docs/tooling/nrt-guide.md @@ -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 diff --git a/docs/ui/gui-system.md b/docs/ui/gui-system.md index 47a5ec4..4149033 100644 --- a/docs/ui/gui-system.md +++ b/docs/ui/gui-system.md @@ -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) | diff --git a/docs/ui/linux-parity-plan.md b/docs/ui/linux-parity-plan.md new file mode 100644 index 0000000..cf14634 --- /dev/null +++ b/docs/ui/linux-parity-plan.md @@ -0,0 +1,212 @@ + + +# 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(@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` 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. diff --git a/docs/ui/linux-view-port-plan.md b/docs/ui/linux-view-port-plan.md new file mode 100644 index 0000000..ce1ffcb --- /dev/null +++ b/docs/ui/linux-view-port-plan.md @@ -0,0 +1,168 @@ + + +# 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. diff --git a/docs/windows-support-plan.md b/docs/windows-support-plan.md new file mode 100644 index 0000000..73d8dd8 --- /dev/null +++ b/docs/windows-support-plan.md @@ -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 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. diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh new file mode 100755 index 0000000..15e31bc --- /dev/null +++ b/scripts/ci-local.sh @@ -0,0 +1,162 @@ +#!/usr/bin/env bash +# scripts/ci-local.sh +# Local Docker mirror of bitbucket-pipelines.yml — run the Linux CI steps on +# your own machine before pushing, so most breaks are caught without spending +# BitBucket build minutes. This is the fast half of the hybrid CI: local Docker +# for every push, BitBucket only at real gates (merge to develop/main, releases) +# for the authoritative x86_64 run + status check. +# +# Usage: +# scripts/ci-local.sh # native (host arch, e.g. arm64) — fast +# scripts/ci-local.sh --amd64 # emulate x86_64 (qemu) to match BitBucket +# scripts/ci-local.sh --livecompile # also build the LiveCompile sub-package +# scripts/ci-local.sh --clean # discard the cached build tree first +# scripts/ci-local.sh --amd64 --livecompile --clean # flags combine +# +# Why --amd64: your dev machine is arm64; BitBucket's runners are x86_64. arm64 +# Docker misses x86-only breaks (flush-to-zero, alignment, codegen). The native +# run catches ~all logic breaks in a fraction of the time; do one --amd64 pass +# before a release/merge to catch the arch-specific ones without hosted minutes. +# +# --livecompile builds the LiveCompile sub-package + the Linux scratch demo +# against the local SwiftOpenUI fork (LYREBIRD_SWIFTOPENUI_LOCAL). This is NOT +# part of the hosted pipeline (the pipeline builds the main package only), so it +# is opt-in here — and it lets the whole run resolve against the fork checkout +# even before a fork release tag is pushed. +# +# Build cache: the Linux build tree lives in a per-arch NAMED DOCKER VOLUME +# (lyrebird-ci-build-, plus lyrebird-ci-live- for --livecompile), +# NOT in the repo's ./.build. That keeps Linux artifacts off your host (no macOS +# ./.build pollution, no "module cache compiled with path X" breakage from a +# changing mount point) while still persisting the cache between runs. --clean +# just deletes those volumes. +# +# Env overrides: +# LYREBIRD_CI_IMAGE Docker image (default lyrebird-linux-full:local) +# LYREBIRD_SWIFTOPENUI_LOCAL_HOST fork path for --livecompile +# (default ~/Documents/src/SwiftOpenUI) +# +# Network: a cold run clones the package dependencies (swift-docc-plugin, Nimble, +# …) from GitHub, exactly as the hosted pipeline does — so the first run needs +# internet. The per-arch build volume then caches them, so later runs (and +# --amd64 after its first) are offline-capable until you --clean. +# +# Requires: Docker, and the lyrebird-linux-full:local image. The image does not +# ship libgtksourceview-5-dev, so the run apt-installs the GTK dev packages +# (idempotent) exactly as the hosted pipeline does — bake them into a dedicated +# image later if the per-run apt cost becomes annoying. +set -euo pipefail + +IMAGE="${LYREBIRD_CI_IMAGE:-lyrebird-linux-full:local}" +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +FORK_HOST="${LYREBIRD_SWIFTOPENUI_LOCAL_HOST:-$HOME/Documents/src/SwiftOpenUI}" + +# The repo is always mounted at the SAME container path (/work) so SwiftPM's +# precompiled module cache — which bakes in the absolute path — stays valid. +MOUNT_PATH="/work" + +PLATFORM_ARGS=() +ARCH_TAG="$(uname -m)" # arm64 / x86_64 for native +ARCH_LABEL="native ($ARCH_TAG)" +RUN_LIVECOMPILE=0 +RUN_CLEAN=0 + +for arg in "$@"; do + case "$arg" in + --amd64) PLATFORM_ARGS=(--platform linux/amd64); ARCH_TAG="amd64"; ARCH_LABEL="emulated linux/amd64" ;; + --livecompile) RUN_LIVECOMPILE=1 ;; + --clean) RUN_CLEAN=1 ;; + -h|--help) sed -n '2,45p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "unknown arg: $arg (try --help)" >&2; exit 2 ;; + esac +done + +BUILD_VOL="lyrebird-ci-build-${ARCH_TAG}" +LIVE_VOL="lyrebird-ci-live-${ARCH_TAG}" + +echo "== Lyrebird local CI ==" +echo "image: $IMAGE" +echo "arch: $ARCH_LABEL" +echo "repo mount: $REPO_ROOT -> $MOUNT_PATH (source only; build tree in volume $BUILD_VOL)" +echo "livecompile: $RUN_LIVECOMPILE clean: $RUN_CLEAN" +echo + +if [[ "$RUN_CLEAN" == 1 ]]; then + echo "== clean: removing build-cache volumes ==" + docker volume rm -f "$BUILD_VOL" "$LIVE_VOL" >/dev/null 2>&1 || true +fi + +# The main-package steps, verbatim from bitbucket-pipelines.yml (only the +# no-ALSA scratch path is redirected under the build volume so it doesn't land +# in the source tree). +read -r -d '' PIPELINE <<'EOF' || true +set -euo pipefail +mkdir -p "$HOME/.cache" +swift --version +apt-get update && apt-get install -y --no-install-recommends libgtk-4-dev libgtksourceview-5-dev libfontconfig-dev libasound2-dev pkg-config +echo "== core build gate ==" +swift build --target LyrebirdSynth --target LyrebirdGraphDSL --target LyrebirdCLI +echo "== UI build gate (LyrebirdUILinuxDemo) ==" +swift build --product LyrebirdUILinuxDemo +echo "== swift test ==" +swift test +echo "== swift test (LYREBIRD_DISABLE_ALSA) ==" +LYREBIRD_DISABLE_ALSA=1 swift test --scratch-path /work/.build/noalsa +EOF + +if [[ "$RUN_LIVECOMPILE" == 1 ]]; then + PIPELINE="$PIPELINE"' +echo "== LiveCompile sub-package (against local fork /fork) ==" +cd /work/LiveCompile +swift build +swift build --product LyrebirdScratchLinuxDemo +echo "== LiveCompile tests ==" +# --no-parallel + a hard timeout: a snippet-compiling test that fails to build +# can otherwise hang forever awaiting a callback (see the LiveCompile notes). +timeout --signal=KILL 1200 swift test --no-parallel' +fi + +# The repo is mounted writable because SwiftPM writes Package.resolved at the +# package root during resolution. The build trees live in the named volumes, so +# the only thing a run can touch in the working copy is Package.resolved — which +# a plain (non-livecompile) run's Linux resolve rewrites to add the by-URL +# SwiftOpenUI pin. Restore it after the run (below) so the working copy stays +# clean. (A --livecompile run resolves the fork as a path dependency, which +# doesn't appear in Package.resolved, so there is nothing to restore there.) +# HOME points at a fresh dir inside the build volume so SwiftPM's global package +# cache (~/.cache/org.swift.swiftpm) is clean and writable — the base image +# ships an inconsistent one that makes a cold `swift build` fail resolving +# swift-docc-plugin ("cannot change to .../repositories/...: No such file"). +# Living in the volume, it also persists warm between runs. +DOCKER_ARGS=(--rm) +[[ ${#PLATFORM_ARGS[@]} -gt 0 ]] && DOCKER_ARGS+=("${PLATFORM_ARGS[@]}") +DOCKER_ARGS+=( + -v "$REPO_ROOT:$MOUNT_PATH" + -v "$BUILD_VOL:$MOUNT_PATH/.build" + -e "HOME=$MOUNT_PATH/.build/home" +) + +if [[ "$RUN_LIVECOMPILE" == 1 ]]; then + if [[ ! -d "$FORK_HOST" ]]; then + echo "livecompile: fork not found at $FORK_HOST" >&2 + echo " set LYREBIRD_SWIFTOPENUI_LOCAL_HOST to the SwiftOpenUI fork path." >&2 + exit 3 + fi + DOCKER_ARGS+=( + -v "$FORK_HOST:/fork:ro" + -v "$LIVE_VOL:$MOUNT_PATH/LiveCompile/.build" + -e LYREBIRD_SWIFTOPENUI_LOCAL=/fork + ) +fi + +# Keep the working copy clean regardless of how the run exits: a plain run's +# Linux resolve rewrites Package.resolved (adds the by-URL SwiftOpenUI pin). +restore_resolved() { + git -C "$REPO_ROOT" checkout -- Package.resolved 2>/dev/null || true +} +trap restore_resolved EXIT + +docker run "${DOCKER_ARGS[@]}" -w "$MOUNT_PATH" "$IMAGE" bash -lc "$PIPELINE" + +echo +echo "== local CI PASSED ($ARCH_LABEL) ==" diff --git a/scripts/doc-snippets-manifest.txt b/scripts/doc-snippets-manifest.txt index 5e8e5eb..bd1913d 100644 --- a/scripts/doc-snippets-manifest.txt +++ b/scripts/doc-snippets-manifest.txt @@ -2,12 +2,14 @@ CLAUDE.md 0 32f17b53fdca9658 none CLAUDE.md 4 484fda136104c034 none INSTALLATION_AND_USAGE.md 6 6ee5041ca9018275 none INSTALLATION_AND_USAGE.md 7 8a7f2353f90dea3e none +LYREBIRD_START_HERE.md 0 a2547833f11acd72 none LYREBIRD_START_HERE.md 3 c0653ad6f9dc0f5b none LYREBIRD_START_HERE.md 4 3d0d1e2673fda229 none README.md 0 1d7c7c19c5a6d112 none README.md 1 3190dd60b6a8f7f8 none README.md 3 4bd7e864af2f05fd none Sources/Lyrebird/AudioDrivers/CoreAudioDriver.swift 0 2b7f04ec486a9a5d none +Sources/Lyrebird/AudioDrivers/DefaultAudioDriver.swift 0 5b79c5afb54ed465 none Sources/Lyrebird/Buffers/WavetableSet.swift 0 d2f7469591d6a837 none Sources/Lyrebird/Capture/ScopeCapture.swift 0 08174c110eb5680b engine Sources/Lyrebird/Diagnostics/LyrebirdMessageCenter.swift 0 42a857719bcee2d7 none @@ -361,7 +363,7 @@ Sources/Lyrebird/Math/LyrebirdMusicMath.swift 4 0ed12cba2d54fb0c none Sources/Lyrebird/Math/LyrebirdMusicMath.swift 5 c93b09a35c5656b6 none Sources/Lyrebird/Math/LyrebirdMusicMath.swift 6 1e2f63b9517d115d none Sources/Lyrebird/Math/LyrebirdMusicMath.swift 7 63878da5cac0b38e none -Sources/Lyrebird/OSC/OSCClient.swift 0 fd200fc7a209f81d none +Sources/Lyrebird/OSC/OSCClient.swift 0 8d156b807b49c1a5 none Sources/Lyrebird/Scheduling/LyrebirdTask.swift 1 ca99def354fe2f0a engine Sources/Lyrebird/Score/Glissando.swift 0 673ddef8256aa6b3 none Sources/Lyrebird/Score/NoteDisplay.swift 0 f706dacb94d58307 none @@ -399,6 +401,7 @@ docs/diagnostics-guide.md 3 4f36c6bd97e3df32 none docs/diagnostics-guide.md 4 f1c7f9029c6f48ea none docs/diagnostics-guide.md 8 8efe9dc71d2dd8dd engine docs/diagnostics-guide.md 9 a0ccfaf1137b9c84 engine +docs/engine/alsa-audio-driver.md 0 d255cf28c7eff929 none docs/engine/bus-system.md 0 7aa0d214382e2c02 none docs/engine/bus-system.md 4 1420e89a6b21dffd member docs/engine/bus-system.md 5 5882de3452d3fb30 member @@ -564,5 +567,5 @@ docs/tooling/routine-task.md 11 b95b191b847d061e engine docs/tooling/routine-task.md 9 be652d2b3b6f274f none docs/tooling/targets.md 0 81b40cbafc6f2d80 none docs/tooling/targets.md 1 611af51e70b6320e none -docs/ui/gui-system.md 0 4b0e892ca2593cf1 none +docs/ui/gui-system.md 0 84caaf99ee346e95 none docs/ui/gui-system.md 1 35476e25ce32f68f none