11 Commits

Author SHA1 Message Date
josh 24ea32e47c v2.2.0 release: live-parameter ramp origin primed at synth add
A @UIParam/@LiveParam value assigned after construction but before the first render
is now delivered flat on the first block instead of ramping from the property-
declaration default (fixes e.g. a NoiseGate restored from saved rig state latching
open and ignoring its threshold). Backed by a new internal-facing
LiveParameterValue._primeRampOrigin() (default no-op, source-compatible); live
changes after start still ramp. See RELEASES.md for the full behavior-change note.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-03 12:25:29 -08:00
josh c14efe998a docs(readme): add Linux equivalents for adding the package and opening the project
Mirror of Lyrebird dev HEAD. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 18:44:50 -07:00
josh 63b630b317 docs(readme): name VS Code as the Linux IDE in Requirements
Mirror of Lyrebird dev HEAD. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 16:40:58 -07:00
josh 3668739d20 docs(readme): add Linux row to the Requirements table
Mirror of Lyrebird dev HEAD. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 16:40:05 -07:00
josh 6e7f4c0076 docs(readme): note Linux support alongside macOS/iOS
Mirror of Lyrebird dev HEAD (c8cbb52f). README intro + quick-taste engine line now
name the platform audio backends (Core Audio on Apple, ALSA on Linux). No code change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 16:36:10 -07:00
josh f8878324fd v2.1.1 release: delay-click fix + internal consolidation
Mirror of Lyrebird dev HEAD (9f791c7c) minus maintainer-only paths. Patch release:
fixes the allpass fractional-delay click (DelayLine/CombFilter/AllpassFilter/
DelayLineFeedback under a modulated delay) and lands the internal code-quality
consolidation pass (~160 deduped sites + shared base classes/helpers, bit-identical
output). No public API removed or changed. See RELEASES.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-07 21:20:49 -07:00
josh 844dc4d9cd v2.1.0 release: Swift 6.4 modernization
Typed throws across the closed-error-set APIs (OSC, MIDI, engine add/schedule,
bus/config/parameter, and the WAV/RF64/Spectral file codecs — source-compatible
narrowing, new .ioFailure cases), plus internal hardening: NSLock-guarded
scheduling/MIDI state moved to Mutex<State>, and the Spectral/FFT scratch owners
moved to a ~Copyable RTScratchBuffer RAII buffer. No API or behavioral change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 19:54:59 -07:00
josh 2c20b02e59 docs: consumer migration guide for Lyrebird 1.x → 2.0
Mirror of the dev-repo docs commit: add docs/migrating-to-2.0.md (module
rename + @UIParam/UIParamNode move into core LyrebirdSynth, with the fix)
and the cross-reference from DEVELOPMENT_AND_RELEASE.md. Docs-only; will be
reconciled by the next full release sync.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-23 21:21:45 -07:00
josh b6fdee8bfc Lyrebird 2.0.0 — Linux support
Consolidated release: the cross-platform Linux port (engine, generators, CLI,
REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable
WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux
live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive.
See RELEASES.md and LINUX_README.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-10 21:09:11 -07:00
josh 77580ee98e v1.7.2 release: sample-rate-invariant TriodeStage coupling + Mesa/Soldano tone stacks
- TriodeStage coupling DC-blocker corner is now held constant in Hz across sample
  rates (was a fixed pole whose corner drifted up with Fs, thinning low end at high
  rates); evaluated at init, off the RT thread.
- New ToneStackModel cases .mesa and .soldano (Faust tonestacks-library values).
- GrayNoise output clamped to [-1, 1] (Int32.min edge).
2026-08-03 15:57:54 -07:00
josh ea0aa84ca7 v1.7.1 release: GuitarML Proteus/NeuralPi model importer
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-01 20:31:38 -07:00
488 changed files with 19799 additions and 3935 deletions
+18
View File
@@ -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-*/
+22 -7
View File
@@ -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<T>` 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`
@@ -129,9 +135,9 @@ One-liners. Detail and rationale lives in linked docs.
- Open every `_computeSamples` with `_checkCount(count)` — the inherited helper that traps if `count > _result[0].count`. Replaces the long-form `precondition(...)` boilerplate.
- `floatValue` is provided by the `AudioGenerator` protocol extension (returns `calculatedSamples(...).first?.first ?? 0`). Do not redeclare in `AudioGenerator` conformers unless you need different scalar semantics (e.g. `ConstantGeneratorInput`). `ControlGenerator` conformers must provide their own `floatValue` returning the block target.
- Buffer factories `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` (in `ResultBuffer.swift`) replace `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals when a generator owns a separately-allocated scratch buffer.
- Every `ControlGenerator.Control.init` calls `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. Never call on the RT thread.
- Every sub-blocking `ControlGenerator.Control.init` calls `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. Never call on the RT thread. **Exception:** `BlockRateControlGenerator` conformers never sub-block and omit the call (see the bypass bullet below).
- `Control._computeSamples` uses `count` (not `graph.engine.blockSize`) for phase/state advancement — `_computeSamples` may run N times per audio block in sub-block mode.
- Generators with per-audio-block state (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers) override `calculatedSamples` to bypass the sub-block loop. Canonical pattern: `Out.Control`. See `docs/protocols/writing-generators.md` §15 for the bypass list and decision rule.
- Control generators with per-audio-block state (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, analysers) must advance once per audio block, bypassing the sub-block loop. Conform to `BlockRateControlGenerator` (marker protocol in `GeneratorCore/BlockRateControlGenerator.swift`) — its `calculatedSamples` default routes to the block-rate gateway and the conformer skips `_setupSubBlockBuffer()`. This replaced the old per-generator `calculatedSamples { _calculatedSamplesBlockRate(...) }` forwarder. A true sub-blocking Control must NOT conform. See `docs/protocols/writing-generators.md` §15 for the decision rule.
- Multi-row generators (any with `_result.count > 1`) override `var outputChannelCount: Int { get }` to return the fixed channel count set at `init`. `GeneratorBase` defaults to `1`. Missing override silently mono-izes the generator under `+ - * /` operators. Channel count must be derivable from a `let` at init — never runtime-mutable. Detail + cases: `docs/stdlib/multichannel.md`.
- `mul:` / `add:` parameters are channel-aware: mono input broadcasts; equal-N applies element-wise; mismatched multi-row precondition-traps. Same policy as `BinaryOpGenerator`. Detail: `docs/stdlib/multichannel.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
@@ -323,9 +331,12 @@ Tool: `Tools/AnnotateBindings/annotate_bindings.py` drives `sourcekit-lsp` to fi
Module-level helpers exist to eliminate repeated boilerplate; inlining any of them in a new generator is a review violation:
- `_checkCount(_:)` — `GeneratorBase` method; first line of every `_computeSamples`
- `_calculatedSamplesBlockRate(graph:count:)` — `Generator` extension; canonical body of any `calculatedSamples` override that bypasses the `ControlGenerator` sub-block path (IIR filters, bus writers, buffer-position advancers, trigger detectors, random drawers)
- `BlockRateControlGenerator` — `GeneratorCore/BlockRateControlGenerator.swift`; marker protocol a `ControlGenerator` conforms to when its state must advance once per audio block (IIR filters, bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, analysers). Supplies the block-rate `calculatedSamples` gateway for free and lets the conformer skip `_setupSubBlockBuffer()`. The standard way to bypass sub-blocking — superseded the per-generator `_calculatedSamplesBlockRate` forwarder. A true sub-blocker must NOT conform.
- `_calculatedSamplesBlockRate(graph:count:)` — `Generator` extension; the block-rate gateway the `BlockRateControlGenerator` default calls. Call it directly only in the rare case a generator needs the bypass but cannot conform to the marker
- `OscillatorBase` — `Generators/Oscillators/OscillatorBase.swift`; extend instead of declaring `_freqInput` / `_freqIsGenerator` / `_phase` / `_mulAdd` inline. Designated `init(freq:phase:mul:add:)` performs canonical phase normalisation. Used by LF / band-limited oscillators (LFSawtooth, LFSquare, LFTriangle, LFDutyCycle, OscSawtooth, OscSquare, OscTriangle, OscDutyCycle) and `Impulse` (post-super-init writes `_phase = 1.0 - initPhase` so `initPhase == 0` fires at sample 0). Table-lookup oscillators (`OscSin`, `OscTable`) intentionally excluded — they store `_phase` in table-index units to avoid a per-sample multiply in the inner loop.
- `NoiseBase` — `Generators/Noise/NoiseBase.swift`; extend instead of declaring `rngState: UInt64` + `_mulAdd: MulAddSpec` inline. Designated `init(initialRngState:mul:add:)`. Used by 23 noise generators across 3 tiers (parameterless, extra-state, distribution-parameterised). LF noise variants and Crackle intentionally excluded.
- `UnaryMathBase` — `Generators/Math/UnaryMathBase.swift`; extend instead of declaring `inputSource` + `_mulAdd` inline. Designated `init(_:mul:add:)`. The shared `_Base` for the single-input math operators — each is `public class _Base: UnaryMathBase {}`, with `Audio`/`Control` supplying only the per-operator kernel. Used by 14 operators (Abs, Ceil, Floor, Round, Sign, Sqrt, Log, Exp, Sin, Cos, Tan, Tanh, Reciprocal, DbAmp). Multi-input math (Max, Min, Ring1–4, ExpExp, ExpLin, …) keeps its own `_Base`.
- `SpectralFeatureControlBase` — `Generators/Spectral/SpectralFeatureControlBase.swift`; shared base for the control-rate spectral feature analysers (SpectralCentroid, SpectralSpread, SpectralFlatness, SpectralEntropy, SpectralFlux, SpectralRolloff). Owns the analysis handle, spectral buffer, MulAddSpec, ramp state, sub-block bypass, and the drive-analysis → `computeFeature` → ramp body; each `Control` subclass adds only its own params/state and overrides `computeFeature(graph:count:) -> Double`.
- `runRBJBiquadBlock(...)` — `Generators/Filters/RBJBiquadHelpers.swift`; module-internal helper holding the shared `_computeSamples` body for `(freq, q)` RBJ biquad filters (LP / HP / AP / Notch). Concrete filters pass the coefficient formula as a closure.
- `runTwoPoleResonatorScalarBlock(input:into:y1:y2:b0:na1:na2:count:)` / `runTwoPoleResonatorInterpolatedBlock(input:into:y1:y2:start:end:count:)` — `Generators/Filters/FilterHelpers.swift`; shared per-sample loop body for two-pole resonator filters (`y[n] = b0·x[n] − na1·y[n−1] − na2·y[n−2]`). Consumed by `RingingFilter` + `ResonatingFilter` — concrete filter passes its coefficient-computation function and one-line helper calls.
- `sampleOrFallback(_:scalar:at:)` — `Generators/Filters/FilterHelpers.swift`; per-sample coefficient lookup with zero-fallback past block end. Replaces the `xxxSamples.map { i < $0.count ? $0[i] : 0 } ?? scalarX` pattern. Used by `SecondOrderSection` (5 coefficient slots) + `FirstOrderSection` (3 slots). `Lag`/`Decay` family use a different end-clamp + `lagCoeff` wrapping convention; helper doesn't apply there.
@@ -333,7 +344,7 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th
- `leakyIntegratorStep(state:x:b1:)` — `Generators/Filters/FilterHelpers.swift`; `y = x + b1·state`, mutates state, returns y. SC `Decay`/`Decay2` convention (input not attenuated by `1 − b1`). Used by `Decay.Audio` + `Decay2.Audio` (cascade two for attack/decay difference).
- `attackReleaseSmoother(state:target:attackCoeff:attackComp:releaseCoeff:releaseComp:direction:)` — `Generators/Dynamics/DynamicsHelpers.swift`; asymmetric attack/release smoother step with direction selector (`.rising` for envelope followers; `.falling` for compressor/expander gain-target smoothing). Used by `AmplitudeFollower.Audio` (`.rising`) + `Compressor.Audio` / `Expander.Audio` (`.falling`).
- `sampleOrZero(_ p: UnsafePointer<Double>, _ i: Int, _ n: Int) -> Double` — `GeneratorCore/HotLoopHelpers.swift`; `i < n ? p[i] : 0`. Replaces the per-sample `(i < n) ? srcP[i] : 0` boilerplate inside hot loops that read an input row via raw pointer. Module-internal helper used across Filters (Lag / Lag2 / LagUpDown / Lag2UpDown / LeakDC / Decay / Decay2 / SecondOrderSection / FirstOrderSection / RBJBiquad / CombFilter / AllpassFilter) and Delays (DelayLine / DelayLineFeedback). `@_spi(LyrebirdExtensions) public` so out-of-tree generators can adopt the same helper.
- `resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate input resolution. Replaces the 8-line `if _xxxIsGenerator { xxxSamples = ...; scalarXxx = 0 } else { xxxSamples = nil; scalarXxx = ... }` boilerplate at the top of any `_computeSamples` that pulls multiple `ValidGeneratorInput` parameters. Used by `Flute` (6 params), `Clarinet` (4 params), `PanXYDistance` (4 params), `PanAzDistance` (4 params). Tuple destructure at the call site is the CLAUDE.md-documented exception to the explicit-type-annotation rule. `@inline(__always) @_spi(LyrebirdExtensions) public`.
- `resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate input resolution. Replaces the 8-line `if _xxxIsGenerator { xxxSamples = ...; scalarXxx = 0 } else { xxxSamples = nil; scalarXxx = ... }` boilerplate at the top of any `_computeSamples` that pulls multiple `ValidGeneratorInput` parameters. Used across many multi-input generators (`Flute`, `Clarinet`, `KarplusStrong`/`GatedKarplusStrong`, `BowedString`, `PlayBuffer`, `SpatialDistance`, `MuTronIII`, `Hilbert`, the spatial panners, and more). Tuple destructure at the call site is the CLAUDE.md-documented exception to the explicit-type-annotation rule. `@inline(__always) @_spi(LyrebirdExtensions) public`.
- `applySpatialDistanceFiltering(...)` — `Generators/Panning/SpatialDistanceHelpers.swift`; module-internal shared per-sample pipeline for `PanXYDistance` (Cartesian) and `PanAzDistance` (polar). Both callers pre-compute `(panX, panY)` and the Chebyshev distance metric `posD` from their respective coordinate frames; the rest of the pipeline (amplitude attenuation, cutoff-coefficient caching, Doppler read-rate, delay-line write/read/wrap/clamp, one-pole lowpass, equal-power 4-corner pan) is identical and lives here. Mutates delay-line + one-pole state in place via `inout`. `@inline(__always) internal`.
- `plateReverbInputDiffusion(...)` / `plateReverbTankHalf(...)` — `Generators/Reverb/PlateReverbHelpers.swift`; PlateReverb-specific per-sample sub-blocks. `plateReverbInputDiffusion` runs the 4-stage cascaded Schroeder allpass network on a single sample. `plateReverbTankHalf` runs one half of the figure-of-eight tank (modulated allpass → delay 1 → damping LP → decay scale → allpass 2 → delay 2 write). Consumed twice per sample by `PlateReverb._computeSamples` (left and right halves). All state mutated `inout`. `@inline(__always) internal`.
- `gverbReadEarlyTaps(...)` / `gverbFDNDamperCascade(...)` — `Generators/Reverb/GVerbHelpers.swift`; GVerb-specific per-sample sub-blocks. `gverbReadEarlyTaps` reads four pre-FDN early-reflection taps with branchless wrap + per-tap gains and returns a 4-tuple. `gverbFDNDamperCascade` applies the FDN one-pole LP damper cascade `y = x*(1-damp) + prev*damp` to four raw FDN reads, mutates `fdnDampState[0..3]` with denormal flush, returns 4-tuple. Both `@inline(__always) internal`.
@@ -341,11 +352,15 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th
- `_mulAdd.applyIfNeeded(to:graph:count:)`
- `fillRampedResult(into:from:to:mulAdd:graph:count:)`
- `fillScalarRampedResult(into:previousOutputValue:target:count:)` — `MulAdd.swift`; canonical body of every `Math.Control` `_computeSamples` ramp (28 generators). Distinct from `fillRampedResult` because the caller has pre-folded `mul`/`add` into the scalar `target` — the helper writes the ramp without re-applying `MulAddSpec.apply`.
- `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)`
- `fillHeldResult(into:value:previousOutputValue:mulAdd:graph:count:)` — `MulAdd.swift`; held-constant counterpart of `fillScalarRampedResult` — fills a block with one value, applies mul/add, sets `previousOutputValue` to the last sample. For block-rate `Control` paths whose output holds one value (one-pole smoothers `Lag`/`Decay`/`LeakDC`/`Slew`/`Formlet`, block-constant analysis `ZeroCrossing`/`Slope`/`RunningMin`/`Max`, trigger/counter latches `Trig`/`Schmidt`/`PulseCount`/`Stepper`; 20 sites). No-op at `count == 0`. NOT for per-sample-varying output.
- `MulAddSpec.applyScalar(_:graph:)` — `MulAdd.swift`; folds scalar `mul`/`add` into one block-constant `target` (returns it unchanged on identity). The scalar counterpart of `applyIfNeeded`; used by the 36 scalar-fold paths (Math.Control plus Routing/Waveshaping crossfades and shapers) before `fillScalarRampedResult`.
- `firstGeneratorSampleOrFloat(_:isGenerator:graph:count:)` / `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate read of a generator-or-scalar input. `first…` reads the block's first sample (`0` if empty) — oscillator/LF/noise `Control` paths; `last…` reads the final sample (ramp endpoint) — dynamics + delay-time paths. Both fall back to `floatValue` for non-generators
- `xorshift64Next(_:)`
- `lyrebirdSeedXorshift64(from:mixConstant:)` / `lyrebirdSeedXorshift64(from:)` — `Math/LyrebirdConstants.swift`; init-time xorshift64 seed helper. Two-arg form decorrelates Audio/Control pairs via `mixConstant`; one-arg form is the convenience for stand-alone single-state owners (e.g. `DemandTemporalTendency` / `DemandTemporalBrownian`)
- `catmullRomCubic(_:_:_:_:t:)` — `Math/CubicInterpolation.swift`; the single shared 4-point Catmull-Rom cubic kernel. Pass `(pM1, p0, p1, p2, t:)` — the sample before the segment, the two bracketing it, the one after, and `t ∈ [0, 1]`. Use instead of inlining the `t²`/`t³` expanded form. `@inline(__always) @_spi(LyrebirdExtensions) public`. Consumers: oscillator table reads (`OscSin` / `oscillatorTableReadCubic`), `PlayBuffer`, `chaoticInterpolate`, and the fractional-delay lines (`DelayLine` / `DelayLineFeedback` / `CombFilter` / `AllpassFilter`).
- `RTScratchBuffer<Element>` — `Buffers/RTScratchBuffer.swift`; a `~Copyable` single-owner heap scratch buffer that replaces hand-paired `allocate`/`deinitialize`/`deallocate` in scratch-owning generators (the Spectral/FFT family). `init(count:)` zero-fills (`Element: Numeric`); `init(count:repeating:)` fills any value. `@inline(__always)` `baseAddress`/`count`/`subscript` (`nonmutating set`) so the hot loop matches the raw pointer. Store as a `let` assigned in `init` — never a per-call local. Not for `[UnsafeMutablePointer]` per-channel arrays (a `~Copyable` cannot be `Array`-stored) or capacity-1 scalar boxes used via `.pointee`. `@_spi(LyrebirdExtensions) public`.
Full table, signatures, examples, and the per-generator exceptions (notably `MathGenerators.Control` and the non-standard ControlGenerator ramp paths) live in `docs/protocols/writing-generators.md` §13. That document is the single source of truth — when adding or removing a helper, update §13 and reference it from here.
## Code Review
+1 -1
View File
@@ -50,7 +50,7 @@ If a unit is useful at both rates, implement both via the **enum namespace patte
- **First line of every `_computeSamples` is `_checkCount(count)`.** It traps if `count` exceeds the pre-allocated buffer. No grow path exists.
- **Pre-allocate everything in `init`.** Bus memory, scratch buffers, vDSP setup objects. `init` runs off the RT thread; `_computeSamples` must only read/write existing storage. Use `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` instead of `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals.
- **Use `count`, never `engine.blockSize`,** for phase/state advancement — a `Control._computeSamples` may run several times per audio block in sub-block mode.
- **Generators with per-audio-block state** (bus writers, position advancers, gain smoothers, trigger detectors, random drawers) override `calculatedSamples` to bypass the sub-block loop via `_calculatedSamplesBlockRate(graph:count:)`. See §15 for the bypass list.
- **Control generators with per-audio-block state** (bus writers, position advancers, gain smoothers, trigger detectors, random drawers, analysers) conform the `Control` to `BlockRateControlGenerator` to bypass the sub-block loop (no `calculatedSamples` override, no `_setupSubBlockBuffer()`). See writing-generators.md §15.
- **Multi-row generators** (`_result.count > 1`) call `super.init(channels: N)` and override `outputChannelCount`. Missing the override silently mono-izes the generator under `+ - * /`. Channel count must be a `let` fixed at init.
- **Extend the right base** where one exists: `OscillatorBase`, `NoiseBase`. Don't re-declare `_phase` / `_mulAdd` / `rngState` inline.
- **Denormal hygiene** — flush denormals to zero in feedback paths (filters, delays, reverbs).
+781
View File
@@ -0,0 +1,781 @@
<!--
LINUX_PLAN.md
Lyrebird
Copyright (c) 2026 Joshua Parmenter / realizedsound
SPDX-License-Identifier: MIT
-->
# 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 `<fenv.h>` 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
<tmp> 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`).
+282
View File
@@ -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.
+33
View File
@@ -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
@@ -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 {
@@ -14,7 +14,7 @@
import Foundation
#if os(macOS)
#if os(macOS) || os(Linux)
/// Handle to one successfully compiled and loaded snippet.
///
@@ -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
@@ -22,7 +22,7 @@
import Foundation
#if os(macOS)
#if os(macOS) || os(Linux)
public enum DiagnosticParser {
@@ -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
@@ -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.
@@ -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 {
@@ -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.
@@ -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<name>.<ext>`, and the
/// resident Lyrebird library is `libLyrebirdDynamic.<ext>`.
#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? {
@@ -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
/// `<CTarget>.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<String> = Set<String>()
for start: URL in importPaths {
var cur: URL = start
for _ in 0..<maxWalk {
for rel: String in relativeMaps {
let probe: URL = cur.appendingPathComponent(rel)
if FileManager.default.fileExists(atPath: probe.path),
!visited.contains(probe.path) {
visited.insert(probe.path)
found.append(probe)
}
}
let parent: URL = cur.deletingLastPathComponent()
if parent == cur { break }
cur = parent
}
}
return found
}
#endif
// MARK: - Build-dir discovery
/// Best-effort discovery of the SPM `.build/<triple>/<config>` 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..<maxWalk {
@@ -805,7 +861,9 @@ public final class LiveSession: @unchecked Sendable {
/// already resolved in the running process.
public static func hasLyrebirdDylib(in buildDir: URL) -> Bool {
FileManager.default.fileExists(
atPath: buildDir.appendingPathComponent("libLyrebirdDynamic.dylib").path
atPath: buildDir.appendingPathComponent(
"libLyrebirdDynamic.\(livecompileSharedLibraryExtension)"
).path
)
}
@@ -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 `<Module>.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 {
@@ -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
@@ -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
@@ -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
@@ -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 {
@@ -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
@@ -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 {
@@ -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
@@ -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 {
@@ -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
@@ -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
// <file>`, 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
@@ -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 {
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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.
@@ -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)
@@ -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
@@ -8,7 +8,7 @@ import Testing
import Foundation
@testable import LyrebirdLiveCompile
#if os(macOS)
#if os(macOS) || os(Linux)
@Suite("DiagnosticParser")
struct DiagnosticParserTests {
@@ -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
@@ -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
}
@@ -9,7 +9,7 @@ import Foundation
import LyrebirdSynth
@testable import LyrebirdLiveCompile
#if os(macOS)
#if os(macOS) || os(Linux)
@MainActor
@Suite("LiveSession diagnostics")
@@ -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
@@ -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))
}
@@ -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
@@ -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
@@ -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
@@ -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
@@ -8,7 +8,7 @@ import Testing
import Foundation
@testable import LyrebirdLiveCompile
#if os(macOS)
#if os(macOS) || os(Linux)
@Suite("SnippetHarness")
struct SnippetHarnessTests {
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
+219 -37
View File
@@ -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
+48 -5
View File
@@ -1,6 +1,6 @@
# Lyrebird
A native macOS/iOS audio synthesis framework written in Swift. Implement `Generator` and `Synthesizer` protocols; the Lyrebird engine handles Core Audio I/O and signal graph evaluation with no heap allocation on the real-time thread.
A native macOS, iOS, and Linux audio synthesis framework written in Swift. Implement `Generator` and `Synthesizer` protocols; the Lyrebird engine handles platform audio I/O (Core Audio on Apple, ALSA on Linux) and signal graph evaluation with no heap allocation on the real-time thread.
Informed by 20+ years of SuperCollider practice, adapted to Swift idioms and a single-process architecture.
@@ -8,7 +8,7 @@ Informed by 20+ years of SuperCollider practice, adapted to Swift idioms and a s
## A quick taste
Three layers, each usable on its own: **Generators** are the unit signal graph, **Synthesizers** package a graph plus live parameters into a playable voice, and the **Engine** drives Core Audio and schedules voices sample-accurately.
Three layers, each usable on its own: **Generators** are the unit signal graph, **Synthesizers** package a graph plus live parameters into a playable voice, and the **Engine** drives the platform audio backend (Core Audio on Apple, ALSA on Linux) and schedules voices sample-accurately.
### Generators — compose a signal graph with operators
@@ -128,10 +128,15 @@ The REPL is text-only and works from any project that depends on Lyrebird; the s
## Requirements
| Platform | OS | Xcode | Swift |
| Platform | OS | IDE | Swift |
|---|---|---|---|
| macOS | 15+ | 16+ | 6.0 |
| iOS | 18+ | 16+ | 6.0 |
| macOS | 15+ | Xcode 16+ | 6.0 |
| iOS | 18+ | Xcode 16+ | 6.0 |
| Linux | Ubuntu 22.04+ ¹ | VS Code ² | 6.0 |
¹ Any swift.org-supported distribution with a Swift 6.0+ toolchain. Install `libasound2-dev` for live audio via the ALSA driver; offline/NRT rendering needs no audio device or ALSA.
² VS Code with the [Swift extension](https://marketplace.visualstudio.com/items?itemName=swiftlang.swift-vscode) (build/debug via SourceKit-LSP); any editor works with the `swift` CLI. Linux setup walk-through: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
---
@@ -149,6 +154,25 @@ 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 (or any SwiftPM project without the Xcode UI)** — there's no "Add Package Dependencies" dialog, so declare it in `Package.swift`:
```swift
dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"),
],
targets: [
.executableTarget(
name: "MyApp",
dependencies: [
.product(name: "Lyrebird", package: "Lyrebird"),
// .product(name: "LyrebirdUI", package: "Lyrebird"), // Apple-only — SwiftUI controls
]
),
]
```
Then `import LyrebirdSynth`. On Linux the non-UI core — engine, generators, CLI, offline render, live ALSA audio, MIDI, and OSC — builds and runs with no Xcode and no SwiftUI (`LyrebirdUI` is Apple-only; a GTK4 UI ships as a separate demo). Full setup: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
---
## Opening in Xcode
@@ -190,6 +214,25 @@ Use `Lyrebird-Package` for day-to-day development of the engine and tests.
| Build fails with Swift driver errors | Xcode 26 bug affecting the **demo workspace** (which dynamic-links for live-coding) — it already sets `SWIFT_USE_INTEGRATED_DRIVER = NO` + `parallelizeBuildables = NO`. Your own project links Lyrebird statically and is unaffected. |
| `dyld: Library not loaded` | Only the bundled demos/AUv3 use the dynamic `LyrebirdDynamic` product; their entitlements already set `disable-library-validation`. External consumers link the static `Lyrebird` product and never hit this. |
### On Linux — VS Code or any editor (no Xcode)
Xcode, the `.xcworkspace`, and the schemes above are Apple-only. On Linux there's no workspace to open — point an editor at the package directory and drive it from the terminal:
```bash
code --install-extension swiftlang.swift-vscode # once: the official Swift extension (SourceKit-LSP: autocomplete, jump-to-def, debug)
code . # open the package in VS Code
```
There are no schemes — run targets directly:
```bash
swift build && swift test # build + run the Linux test suites
swift run LyrebirdCLI repl # the CLI (also `new`, scaffolding, …)
LYREBIRD_ENABLE_LINUX_UI=1 swift run LyrebirdUILinuxDemo # the GTK4 UI demo
```
The SwiftUI / AUv3 / iOS demos in the scheme table do not build on Linux. Full walk-through — toolchain, VS Code, building, running a sample: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
---
## Building and testing from the terminal
+162
View File
@@ -7,6 +7,168 @@ functionality in a backward-compatible way.
---
## 2.2.0 — Live-parameter ramp origin primed at synth add
A small-but-behavioral release. One fix to how `@UIParam` / `@LiveParam` values
are delivered on a synth's first rendered block, plus the internal hook that
backs it. The public API is source-compatible — the one new protocol member is
internal-facing and ships with a default implementation — so this is drop-in
over 2.1.x, but the delivery change is observable and is called out below.
**Fix — a parameter set before the first render is now delivered flat.** When a
value is assigned to an `@UIParam` / `@LiveParam` *after the synth is
constructed but before it first renders* — most commonly when restoring saved
state onto a freshly built synth — the parameter is now delivered as a flat
block at that value from sample 0. Previously the first rendered block ramped
from the property-declaration default up to the assigned value over one
(sub-)block, because the property-wrapper setter advances the atomic target but
not the interpolation origin, which stayed at the construction-time default.
For most parameters that one-block (~a few ms) glide was benign. For a value
feeding a decision stage it was not: a `Schmidt` trigger fed a threshold that
swept up from the default would latch on the transient and, if the steady signal
sat inside the hysteresis band, never reset — e.g. a `NoiseGate` restored from a
saved rig would open on load and ignore its threshold. Priming the origin at add
removes the sweep.
Mechanically: `SynthesizerBase`, as part of the `Mirror`-based live-parameter
auto-registration it already runs at add time (`rebuildGraph()`, main thread,
before the node is visible to the RT thread), now also primes each parameter's
ramp origin to its current value via a new `LiveParameterValue._primeRampOrigin()`.
`ParameterNode` and `UIParamNode` implement it; external conformers inherit a
no-op default, so nothing is source-broken. A re-add (`remove` → change value →
`add`) likewise re-primes to the then-current value.
**Behavior change to be aware of.** Two deliveries changed, both toward "the
value you set before starting is the value you get":
- A value assigned between construction and first render is **flat** on block
one, not a ramp from the declaration default. Code that (knowingly or not)
relied on that opening glide will no longer see it. If you want an opening
ramp, drive the parameter from a source/envelope or change it after start.
- A synth removed, re-assigned while out of the tree, then re-added starts
**flat at the new value** rather than gliding from the value it last rendered.
Live changes made **while the synth is running** are unchanged — they still ramp
per (sub-)block from the last rendered value, as before. The source-slot /
crossfade path is unaffected (the source overwrites the origin each block).
Pinned by `LiveParamRampOriginTests` (flat delivery for `@UIParam` and
`@LiveParam`, live-change-still-ramps, remove/change/re-add, and source-slot
non-interference).
---
## 2.1.1 — Delay-click fix + internal consolidation
A patch release: one audible bug fix in the delay/comb/allpass family, plus a
large internal code-quality pass. No public API is removed or changed — the few
new types are internal-facing scaffolding — so this is drop-in over 2.1.0.
**Fix — allpass fractional-delay click under modulation.** The allpass
interpolation mode (`.allpass`) of `DelayLine`, `CombFilter`, `AllpassFilter`,
and `DelayLineFeedback` mishandled its recursive filter state when a modulated
delay crossed an exact integer-sample boundary: `AllpassFilter` and
`DelayLineFeedback` produced an audible click (a sample-to-sample step several
times the surrounding signal), and the four generators disagreed on the
behavior. All four now record the integer-delayed sample as the interpolator's
previous output, which is click-free and consistent. Only `.allpass`
interpolation under a *modulated* delay was affected; `.none` / `.linear` /
`.cubic` and static delays were already correct. Guarded by a per-generator
regression suite.
**Internal consolidation (no behavioral change).** Roughly 160 duplicated
call-site patterns and several near-identical generator shells were folded into
shared helpers and base classes — block-boundary input reads, the per-sample
phase wrap, the scalar mul/add fold, the held-constant control fill, the
single-input math operators (`UnaryMathBase`), the chaotic oscillators'
render body, the spectral FFT-size guards, the spectral feature analysers
(`SpectralFeatureControlBase`), and the ~96 block-rate control generators that
bypass sub-blocking (now a `BlockRateControlGenerator` marker protocol, which
also drops an unused ~4 KB per-instance buffer allocation). Output is
bit-identical across the generator library; the full test suite is unchanged.
---
## 2.1.0 — Swift 6.4 modernization
An internal-hardening release adopting modern Swift on the 6.4 toolchain. No
behavioral change, and the public surface stays source-compatible.
**Typed throws.** The closed-error-set APIs now declare their concrete error
type instead of untyped `throws`, so a caller gets an exhaustive `catch` with no
downcast: OSC (`OSCDecodeError` / `OSCServerError`), MIDI (`MIDIError`, on both
the CoreMIDI and ALSA backends), the engine's bus / config / parameter setters,
the public node-add surface — `add` / `schedule` — (`EngineAddError`), and the
self-contained file codecs (`WavFileError` / `RF64WriterError` /
`SpectralFileError`). Narrowing an API from `throws` to `throws(E)` is
source-compatible — existing `try` call sites are unaffected. The WAV and
Spectral codecs gain an `.ioFailure` case that funnels an underlying
`FileHandle` failure into the typed error.
**Concurrency & memory hardening (internal).** NSLock-guarded state in the
scheduling and MIDI classes moved into `Mutex<State>` for compiler-enforced lock
discipline, and the Spectral/FFT scratch owners moved from hand-managed raw
pointers to a `~Copyable` `RTScratchBuffer` (compiler-guaranteed single free, no
ARC on the handle). No API or behavioral change.
---
## 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:
- **`ProteusModelImporter`** — loads a GuitarML **Proteus / NeuralPi** model JSON (single-layer
LSTM capture) into a `NeuralAmpModel` for `LSTMAmp`. The state-dict tensors map straight onto
`NeuralAmpModel`'s layout (PyTorch gate order; `skip` → residual); unsupported topologies and
inconsistent tensor shapes throw. Model files are user-supplied — none are bundled (GuitarML
models are GPL-3.0). A binary NAM `.nam` importer remains future work.
---
## 1.7.0 — Amp-modeling core: tone stack, triode stage, neural amp
A minor release. Three new, backward-compatible generators — the DSP core for guitar-amp
+17
View File
@@ -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 <alsa/asoundlib.h> 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 <alsa/asoundlib.h>
#endif /* LYREBIRD_CALSA_SHIM_H */
+5
View File
@@ -0,0 +1,5 @@
module CALSA [system] {
header "include/calsa-shim.h"
link "asound"
export *
}
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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<S: SynthesizerBase> {
/// `Double(velocity) / Double(midiVelocityMax)` yields the conventional `[0,1]`
/// range used by `@LiveParam` amplitude parameters.
public let midiVelocityMax: UInt8 = 127
#endif
@@ -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
@@ -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<SynthesisEngine>?
private var blockSize: Int = 0
private var sampleRate: Double = 0
private var outputChannels: Int = 0
private var inputChannels: Int = 0
/// Interleaved staging buffers handed to ALSA. Raw pointers rather than
/// arrays so their addresses are stable for the thread's lifetime.
private var interleavedOutput: UnsafeMutablePointer<Float>?
private var interleavedInput: UnsafeMutablePointer<Float>?
/// Planar input handed to `processBlock`, pre-allocated so the loop never
/// grows it.
private var inputStagingBuffers: [[Float]] = []
private let _isRunning: Atomic<Bool> = Atomic<Bool>(false)
private let _hasRealtimePriority: Atomic<Bool> = Atomic<Bool>(false)
/// Set when a `stop()` gave up waiting for the render thread. The thread is
/// still out there, still testing `_isRunning`, so the driver must never
/// start another one: a wedged transfer that finally returns would find the
/// flag true again and resume rendering alongside its replacement.
private let _abandonedThread: Atomic<Bool> = Atomic<Bool>(false)
private let _lastError: Mutex<ALSAError?> = Mutex<ALSAError?>(nil)
private var renderThread: Thread?
private let threadExited: DispatchSemaphore = DispatchSemaphore(value: 0)
// MARK: - Init
public init() {
// Initialise the RT-identity TLS key from this known non-RT call site,
// so the render thread's first `markCurrentThreadAsRT()` cannot be the
// allocating one.
RTThreadIdentity.warmUp()
}
deinit {
stop()
// Belt and braces: `Thread { [weak self] in self?.renderLoop(...) }`
// holds `self` strongly for the whole call, so `deinit` cannot actually
// run while an abandoned loop is still inside it. If that ever changes,
// freeing these buffers would be a use-after-free, so the guard stays.
guard !_abandonedThread.load(ordering: .acquiring) else { return }
interleavedOutput?.deallocate()
interleavedInput?.deallocate()
}
/// ALSA's period granularity is the engine block, so control-rate
/// resolution matches the other live drivers.
public var suggestedControlBlockSize: Int? { lyrebirdDefaultControlBlockSize }
// MARK: - AudioDriver
public func setup(engine: SynthesisEngine) throws {
guard !_abandonedThread.load(ordering: .acquiring) else {
// Reallocating the staging buffers would pull them out from under
// the thread that never came back.
throw ALSAError.renderThreadDidNotExit
}
engineRef = Unmanaged.passUnretained(engine)
blockSize = engine.blockSize
sampleRate = engine.sampleRate
outputChannels = engine.numOutputChannels
inputChannels = engine.numInputChannels
interleavedOutput?.deallocate()
interleavedOutput = UnsafeMutablePointer<Float>.allocate(
capacity: blockSize * max(outputChannels, 1)
)
interleavedOutput?.initialize(repeating: 0, count: blockSize * max(outputChannels, 1))
interleavedInput?.deallocate()
interleavedInput = nil
inputStagingBuffers = []
if inputChannels > 0 {
let inputPointer: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(
capacity: blockSize * inputChannels
)
inputPointer.initialize(repeating: 0, count: blockSize * inputChannels)
interleavedInput = inputPointer
inputStagingBuffers = [[Float]](
repeating: [Float](repeating: 0, count: blockSize),
count: inputChannels
)
}
}
public func start() throws {
guard engineRef != nil, blockSize > 0 else { throw ALSAError.notConfigured }
guard !_abandonedThread.load(ordering: .acquiring) else {
// A previous render thread never came back. Starting a second one
// would put two threads on one engine the moment the first unwedges.
throw ALSAError.renderThreadDidNotExit
}
guard !_isRunning.load(ordering: .acquiring) else { return }
// A loop that ended on its own leaves a finished thread and a signalled
// semaphore behind; clear them before starting another.
if renderThread != nil { stop() }
// That `stop()` can itself time out and latch — re-check, or the exact
// state the latch exists to prevent gets created a few lines below.
guard !_abandonedThread.load(ordering: .acquiring) else {
throw ALSAError.renderThreadDidNotExit
}
_lastError.withLock { $0 = nil }
do {
try openPlayback()
if inputChannels > 0 {
try openCapture()
}
} catch {
// Never leave a half-open device: a playback handle that opened
// before capture failed would otherwise stay claimed until deinit.
closeDevices()
throw error
}
// Drain a stale signal from a previous run that timed out in `stop()`
// and whose thread signalled afterwards; leaving it pending would make
// the next `stop()` return from its wait immediately.
while threadExited.wait(timeout: .now()) == .success {}
_hasRealtimePriority.store(false, ordering: .releasing)
_isRunning.store(true, ordering: .releasing)
// The engine is held unowned for the driver's normal life (it owns the
// driver, so retaining it back would be a cycle), but the render thread
// must not outlive it — and an abandoned thread can, since nothing can
// stop it. Retain for exactly the thread's lifetime: the loop's `defer`
// releases, so a thread that never returns pins the engine forever,
// which is the point.
//
// `retain()` bumps the pointee's count without ever materialising a
// Swift reference — `takeUnretainedValue()` on a since-freed engine
// would be undefined behaviour, not a recoverable `nil`. `engineRef` is
// already known non-nil (checked at the top of `start()`).
guard let engineUnmanaged: Unmanaged<SynthesisEngine> = engineRef else {
_isRunning.store(false, ordering: .releasing)
throw ALSAError.notConfigured
}
// Carried across the thread boundary as a bit pattern: `Thread`'s
// closure is `@Sendable`, and neither `Unmanaged` nor a raw pointer is
// Sendable under Swift 6 — the same reason `SynthesizerBase` stores its
// engine binding as an `Atomic<UInt>`. The retain is real; the loop's
// `defer` releases it.
let engineBits: UInt = Self.retainForRenderThread(engineUnmanaged)
let thread: Thread = Thread { [weak self] in
guard let self: ALSAAudioDriver = self else {
Self.releaseEngine(bits: engineBits)
return
}
self.renderLoop(engineBits: engineBits)
}
thread.name = "lyrebird.alsa.render"
renderThread = thread
thread.start()
}
public func stop() {
// Already abandoned: that thread is gone as far as this driver is
// concerned and its resources are deliberately leaked, so `renderThread`
// must not be touched again. A `deinit`-driven `stop()` can run on the
// render thread itself once a wedged transfer finally returns, which
// would race the original `stop()`'s write from the caller's thread.
guard !_abandonedThread.load(ordering: .acquiring) else { return }
_isRunning.store(false, ordering: .releasing)
guard renderThread != nil else {
closeDevices()
return
}
// Join whenever a thread was launched — including one that already
// exited on its own error path. Closing the PCM handles while the
// thread could still touch them is a use-after-free, so the wait is not
// conditional on the running flag. The loop tests the flag once per
// block and so leaves within roughly one block period.
let exited: Bool = threadExited.wait(timeout: .now() + Self.threadJoinTimeout) == .success
renderThread = nil
guard exited else {
// The thread is stuck inside a transfer. Closing its PCM handles or
// freeing the buffers it is reading would be exactly the
// use-after-free the join exists to prevent, so abandon them
// instead: a leak is recoverable, a wild write is not. The handles
// stay open until the process exits, so a subsequent `start()` may
// fail with the device busy — which is the truth, and better than
// pretending the stop succeeded.
// Nothing is written here on purpose. The thread that owns these
// handles and buffers is still alive and still reading them; the
// abandon latch is what keeps every later path — `closeDevices()`,
// `deinit`, a second `start()` — from touching them. Clearing the
// properties would be its own data race, on top of the
// use-after-free the join exists to prevent.
_lastError.withLock { $0 = .renderThreadDidNotExit }
_abandonedThread.store(true, ordering: .releasing)
return
}
closeDevices()
}
// MARK: - Device setup
private func openPlayback() throws {
var pcm: OpaquePointer?
let openResult: Int32 = snd_pcm_open(&pcm, device, SND_PCM_STREAM_PLAYBACK, 0)
guard openResult >= 0, let handle: OpaquePointer = pcm else {
throw ALSAError.playbackDeviceOpenFailed(device: device, code: Int(openResult))
}
playbackPCM = handle
try configure(handle, channels: outputChannels, stream: "playback")
}
private func openCapture() throws {
var pcm: OpaquePointer?
let openResult: Int32 = snd_pcm_open(&pcm, captureDevice, SND_PCM_STREAM_CAPTURE, 0)
guard openResult >= 0, let handle: OpaquePointer = pcm else {
throw ALSAError.captureDeviceOpenFailed(device: captureDevice, code: Int(openResult))
}
capturePCM = handle
try configure(handle, channels: inputChannels, stream: "capture")
// One clock for both streams — without this, two independently clocked
// devices drift and the loop eventually blocks on one of them.
if let playback: OpaquePointer = playbackPCM {
linkedStreams = snd_pcm_link(handle, playback) >= 0
}
}
/// Applies format, access mode, rate, channel count, and latency in one
/// call. `snd_pcm_set_params` is ALSA's own convenience over the hw/sw
/// params dance and negotiates a period for the requested latency.
private func configure(_ pcm: OpaquePointer, channels: Int, stream: String) throws {
let latencySeconds: Double =
Double(blockSize * periodsPerBuffer) / sampleRate
let latencyMicroseconds: UInt32 = UInt32(latencySeconds * Self.microsecondsPerSecond)
let softResample: Int32 = allowSoftwareResampling ? 1 : 0
let paramResult: Int32 = snd_pcm_set_params(
pcm,
SND_PCM_FORMAT_FLOAT_LE,
SND_PCM_ACCESS_RW_INTERLEAVED,
UInt32(channels),
UInt32(sampleRate),
softResample,
latencyMicroseconds
)
guard paramResult >= 0 else {
throw ALSAError.parameterNegotiationFailed(stream: stream, code: Int(paramResult))
}
let prepareResult: Int32 = snd_pcm_prepare(pcm)
guard prepareResult >= 0 else {
throw ALSAError.prepareFailed(stream: stream, code: Int(prepareResult))
}
}
private func closeDevices() {
// A thread we gave up waiting for still owns these handles. Closing
// them out from under it is the use-after-free this whole path exists
// to avoid; they stay open until the process exits.
guard !_abandonedThread.load(ordering: .acquiring) else { return }
if let capture: OpaquePointer = capturePCM {
// Unlink before closing so a restart can link a fresh pair.
if linkedStreams { snd_pcm_unlink(capture) }
snd_pcm_drop(capture)
snd_pcm_close(capture)
capturePCM = nil
}
if let playback: OpaquePointer = playbackPCM {
snd_pcm_drop(playback)
snd_pcm_close(playback)
playbackPCM = nil
}
linkedStreams = false
}
// MARK: - Render thread
/// Retains `engine` for the render thread and returns its pointer as a bit
/// pattern — the form that survives `Thread`'s `@Sendable` closure boundary.
/// Balanced by exactly one ``releaseEngine(bits:)``.
///
/// Exposed so the retain/release round trip can be pinned by a test: the
/// balance across the render loop's exit paths only runs against real
/// hardware, and an imbalance here is a leak or a use-after-free.
@_spi(LyrebirdExtensions)
public static func retainForRenderThread(_ engine: Unmanaged<SynthesisEngine>) -> UInt {
UInt(bitPattern: engine.retain().toOpaque())
}
/// Balances one ``retainForRenderThread(_:)``.
@_spi(LyrebirdExtensions)
public static func releaseEngine(bits: UInt) {
guard let pointer: UnsafeMutableRawPointer = UnsafeMutableRawPointer(bitPattern: bits) else { return }
Unmanaged<SynthesisEngine>.fromOpaque(pointer).release()
}
private func renderLoop(engineBits: UInt) {
guard let enginePointer: UnsafeMutableRawPointer = UnsafeMutableRawPointer(bitPattern: engineBits) else {
// Unreachable: `engineBits` is the bit pattern of a live heap
// pointer, never 0. Balance the retain anyway so the one path that
// does not reach the `defer` below cannot leak the engine.
Self.releaseEngine(bits: engineBits)
_lastError.withLock { $0 = .renderLoopPreconditionFailed }
_isRunning.store(false, ordering: .releasing)
threadExited.signal()
return
}
let retainedEngine: Unmanaged<SynthesisEngine> = Unmanaged.fromOpaque(enginePointer)
RTThreadIdentity.markCurrentThreadAsRT()
enableFlushToZero()
if requestsRealtimePriority {
_hasRealtimePriority.store(Self.raiseCurrentThreadPriority(), ordering: .releasing)
}
defer {
// Clear the flag on every exit, including the error paths, so the
// driver's state matches reality and a later `start()` is not
// silently ignored. Signalled last: `stop()` closes the PCM handles
// as soon as it sees this, and by then the loop must be done with
// them.
_isRunning.store(false, ordering: .releasing)
// Balances the `passRetained` in `start()`. Reached on every exit
// path this loop has; only a thread that never returns keeps the
// engine alive, which is exactly the case that needs it.
retainedEngine.release()
threadExited.signal()
}
let engine: SynthesisEngine = retainedEngine.takeUnretainedValue()
guard let playback: OpaquePointer = playbackPCM,
let output: UnsafeMutablePointer<Float> = interleavedOutput else {
// Exiting here produces silence with no other symptom, so record why
// rather than letting a driver that never ran look healthy.
_lastError.withLock { $0 = .renderLoopPreconditionFailed }
return
}
// Read once, before the loop. The abandon path deliberately writes
// nothing, but `closeDevices()` does nil these after a clean join, and
// hoisting means the loop body does not depend on that ordering
// holding at every iteration.
let capture: OpaquePointer? = capturePCM
let input: UnsafeMutablePointer<Float>? = interleavedInput
while _isRunning.load(ordering: .acquiring) {
if let capture: OpaquePointer = capture,
let input: UnsafeMutablePointer<Float> = input {
guard transfer(pcm: capture, buffer: input, isCapture: true) else { return }
lyrebirdDeinterleave(
input,
into: &inputStagingBuffers,
frameCount: blockSize,
channelCount: inputChannels
)
}
engine.processBlock(inputSamples: inputStagingBuffers)
lyrebirdInterleave(
engine.audioBuses,
into: output,
frameCount: blockSize,
channelCount: outputChannels
)
guard transfer(pcm: playback, buffer: output, isCapture: false) else { return }
}
}
/// Moves exactly `blockSize` frames in or out, resuming after short
/// transfers and recovering from underruns.
///
/// - Returns: `false` when the stream is unrecoverable or the driver was
/// asked to stop, meaning the render loop should exit.
private func transfer(
pcm: OpaquePointer,
buffer: UnsafeMutablePointer<Float>,
isCapture: Bool
) -> Bool {
let channels: Int = isCapture ? inputChannels : outputChannels
var framesDone: Int = 0
var consecutiveStalls: Int = 0
var consecutiveInterrupts: Int = 0
while framesDone < blockSize {
guard _isRunning.load(ordering: .acquiring) else { return false }
let cursor: UnsafeMutablePointer<Float> = buffer + framesDone * channels
let remaining: UInt = UInt(blockSize - framesDone)
let result: Int = isCapture
? snd_pcm_readi(pcm, cursor, remaining)
: snd_pcm_writei(pcm, cursor, remaining)
switch ALSARecoveryAction.classify(result) {
case .transferred(let frames):
framesDone += frames
// A zero-frame transfer makes no progress, so it cannot reset
// the budget — otherwise a device that keeps returning 0 spins
// this loop forever at `SCHED_FIFO`, which is the failure the
// budget exists to stop.
if frames > 0 {
consecutiveStalls = 0
consecutiveInterrupts = 0
} else if !tolerateStall(result: result, isCapture: isCapture, count: &consecutiveStalls) {
return false
}
case .interrupted:
// A signal, not a device problem: reissue without spending the
// stall budget, since profilers and interval timers deliver
// these to perfectly healthy streams. Still bounded, and with a
// yield — a signal source faster than the syscall would
// otherwise busy-spin a `SCHED_FIFO` thread with nothing but
// `_isRunning` to break out.
consecutiveInterrupts += 1
guard consecutiveInterrupts <= Self.maxConsecutiveInterrupts else {
_lastError.withLock {
$0 = .transferFailed(
stream: isCapture ? "capture" : "playback",
code: result
)
}
return false
}
sched_yield()
continue
case .wouldBlock:
// A blocking PCM should not return would-block, but a plugin
// chain (dmix, a non-blocking `.asoundrc` device) can. Spinning
// on it from a `SCHED_FIFO` thread would starve the machine, so
// sleep on the device and give up if it never becomes ready.
guard tolerateStall(result: result, isCapture: isCapture, count: &consecutiveStalls) else {
return false
}
_ = snd_pcm_wait(pcm, Self.deviceWaitMilliseconds)
case .recover:
// Underrun or suspend: re-prepare and reissue from the same
// frame. The samples already handed over are gone either way.
// An xrun moves no frames, so it spends the budget like any
// other no-progress result — clearing it here let a device
// alternating underruns with would-block returns loop forever.
guard tolerateStall(result: result, isCapture: isCapture, count: &consecutiveStalls) else {
return false
}
if snd_pcm_recover(pcm, Int32(result), Self.recoverSilently) < 0 {
_lastError.withLock {
$0 = .prepareFailed(
stream: isCapture ? "capture" : "playback",
code: result
)
}
return false
}
case .fail:
_lastError.withLock {
$0 = .transferFailed(
stream: isCapture ? "capture" : "playback",
code: result
)
}
return false
}
}
return true
}
/// Counts one transfer that moved no frames, and reports whether the
/// stream has any patience left.
///
/// - Returns: `false` once the budget is spent, having recorded the error.
private func tolerateStall(result: Int, isCapture: Bool, count: inout Int) -> Bool {
count += 1
guard Self.stallBudgetExhausted(consecutiveStalls: count) else { return true }
_lastError.withLock {
$0 = .transferFailed(
stream: isCapture ? "capture" : "playback",
code: result
)
}
return false
}
/// Whether this many consecutive no-progress transfers means the stream is
/// dead rather than merely slow.
///
/// Exposed so the boundary can be pinned by a test: the loop that consults
/// it only runs against real hardware, and an off-by-one here either kills
/// a healthy stream one attempt early or never gives up at all.
@_spi(LyrebirdExtensions)
public static func stallBudgetExhausted(consecutiveStalls: Int) -> Bool {
consecutiveStalls > maxConsecutiveStalls
}
/// Asks the kernel for `SCHED_FIFO` on the calling thread.
///
/// - Returns: `true` if granted. Denial is the normal case for an
/// unprivileged process and is not an error — audio still runs, just
/// without scheduling protection.
private static func raiseCurrentThreadPriority() -> Bool {
let lowest: Int32 = sched_get_priority_min(SCHED_FIFO)
let highest: Int32 = sched_get_priority_max(SCHED_FIFO)
guard lowest >= 0, highest > lowest else { return false }
let span: Double = Double(highest - lowest)
var params: sched_param = sched_param()
params.sched_priority = lowest + Int32(span * realtimePriorityFraction)
return pthread_setschedparam(pthread_self(), SCHED_FIFO, &params) == 0
}
}
#endif
@@ -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
}
@@ -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
}
}
}
@@ -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
@@ -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
@@ -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
}
@@ -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<Float>,
frameCount: Int,
channelCount: Int
) {
for channel: Int in 0..<channelCount {
// Binding the row to a local `[Float]` would retain/release it once per
// channel per block on the render thread; borrowing it in place through
// `withUnsafeBufferPointer` does not.
guard channel < buses.count else {
for frame: Int in 0..<frameCount {
out[frame * channelCount + channel] = 0
}
continue
}
buses[channel].withUnsafeBufferPointer { src in
guard let base: UnsafePointer<Float> = src.baseAddress else { return }
let available: Int = min(frameCount, src.count)
for frame: Int in 0..<available {
out[frame * channelCount + channel] = base[frame]
}
for frame: Int in available..<frameCount {
out[frame * channelCount + channel] = 0
}
}
}
}
/// Scatters `frameCount` interleaved frames into planar `buses`.
///
/// The inverse of ``lyrebirdInterleave(_:into:frameCount:channelCount:)``.
/// Buses shorter than `frameCount` are filled as far as they go; channels
/// beyond `buses.count` are dropped. Nothing is resized, so this is safe to
/// call on the render thread once the buses are pre-allocated.
///
/// - Parameters:
/// - src: Source of `frameCount * channelCount` interleaved samples.
/// - buses: Planar destination buffers, pre-allocated by the caller.
/// - frameCount: Frames to read.
/// - channelCount: Channels per frame in `src`.
@_spi(LyrebirdExtensions)
public func lyrebirdDeinterleave(
_ src: UnsafePointer<Float>,
into buses: inout [[Float]],
frameCount: Int,
channelCount: Int
) {
let channels: Int = min(channelCount, buses.count)
for channel: Int in 0..<channels {
buses[channel].withUnsafeMutableBufferPointer { dst in
guard let base: UnsafeMutablePointer<Float> = dst.baseAddress else { return }
let available: Int = min(frameCount, dst.count)
for frame: Int in 0..<available {
base[frame] = src[frame * channelCount + channel]
}
}
}
}
+154 -93
View File
@@ -5,11 +5,20 @@
// SPDX-License-Identifier: MIT
import Foundation
#if canImport(AudioToolbox)
import AudioToolbox
#endif
/// Non-Real-Time audio driver. Renders synchronously to a soundfile in the
/// container/encoding chosen at init (``AudioFileFormat``, default `.cafFloat32`).
/// `start()` blocks until rendering is complete — suitable for score/script workflows.
///
/// On Apple platforms every ``AudioFileFormat`` is available (via `ExtAudioFile`
/// and, for the RF64 cases, ``RF64Writer``). Off Apple the driver uses the
/// portable WAV codec (``WavFileWriter`` / ``WavFileReader``): the WAV encodings
/// (`.wavFloat32` / `.wavInt16` / `.wavInt24`) render and WAV inputs read; the
/// Apple-only containers (CAF / AIFF-C / AAC / ALAC) throw
/// ``NRTDriverError/unsupportedFormatOnPlatform(_:)``.
public final class NRTDriver: AudioDriver {
private let outputURL: URL
@@ -25,18 +34,20 @@ public final class NRTDriver: AudioDriver {
/// Pre-allocated interleaved write buffer: blockSize * numOutputChannels floats.
private var writeBuffer: [Float] = []
private var inputChannelCount: Int = 0
// Pre-allocated input staging — no alloc during the render loop.
private var inputStagingBuffers: [[Float]] = [] // [channel][sample], blockSize each
#if canImport(AudioToolbox)
// Input file state — opened in setup(), disposed in start()'s defer block.
private var inputFileRef: ExtAudioFileRef?
private var inputChannelCount: Int = 0
// Pre-allocated input buffers — no alloc during the render loop.
private var inputReadBuffer: [Float] = [] // interleaved: blockSize × inputChannelCount
private var inputStagingBuffers: [[Float]] = [] // [channel][sample], blockSize each
#else
private var inputReader: WavFileReader?
#endif
/// Optional trigger listener. When set, `_drainSync` is called after each `processBlock`
/// so that trigger handlers can add new synthesizers that render in subsequent blocks.
/// Handlers receive a `LyrebirdMessageContext(nrtEngine:)` — `ctx.add(synth)` enqueues
/// directly to `pendingQueue` without a `DispatchQueue.main.async` hop.
public var triggerListener: TriggerListener?
/// - Parameters:
@@ -44,14 +55,10 @@ public final class NRTDriver: AudioDriver {
/// (`.caf` / `.wav` / `.aiff`); see ``AudioFileFormat/fileExtension``.
/// - duration: Render duration in seconds.
/// - format: Container and PCM encoding for the output file. Defaults to
/// `.cafFloat32`. CAF is 64-bit-sized (no 4 GB cap) and carries any channel
/// count, so it suits long or multichannel offline renders; `.wavFloat32` /
/// `.aiffFloat32` / the integer WAV cases are available for interchange.
/// `.cafFloat32`. Off Apple, choose a `.wav*` case (CAF/AIFF/AAC throw).
/// - inputURL: Optional soundfile whose samples are written to the engine's input buses
/// each block, as if they came from a microphone. Channels are mapped in order starting
/// at input bus 0. The engine's `numInputChannels` must be ≥ the file's channel count
/// (extra input buses receive silence). If the file is shorter than `duration`, the
/// remaining blocks receive silence.
/// each block. Off Apple the input must be a WAV file **at the engine sample rate** —
/// the portable reader does no sample-rate conversion (the Apple `ExtAudioFile` path does).
/// - inputStartOffset: Seconds to skip into `inputURL` before rendering begins. Clamped
/// to 0 if negative.
public init(
@@ -61,7 +68,6 @@ public final class NRTDriver: AudioDriver {
inputURL: URL? = nil,
inputStartOffset: Double = 0.0
) {
self.outputURL = outputURL
self.outputFormat = format
self.duration = duration
@@ -79,6 +85,7 @@ public final class NRTDriver: AudioDriver {
guard let inputURL: URL else { return }
#if canImport(AudioToolbox)
// Open the input file.
var rawInputFileRef: ExtAudioFileRef?
let openStatus: OSStatus = ExtAudioFileOpenURL(inputURL as CFURL, &rawInputFileRef)
@@ -100,7 +107,6 @@ public final class NRTDriver: AudioDriver {
inputChannelCount = min(Int(fileFmt.mChannelsPerFrame), engine.numInputChannels)
// Set client format: interleaved Float32 at engine sample rate.
// ExtAudioFile handles sample-rate conversion automatically if file SR differs.
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
mSampleRate: engine.sampleRate,
mFormatID: kAudioFormatLinearPCM,
@@ -135,36 +141,34 @@ public final class NRTDriver: AudioDriver {
inputReadBuffer = [Float](repeating: 0, count: engine.blockSize * inputChannelCount)
inputStagingBuffers = [[Float]](repeating: [Float](repeating: 0, count: engine.blockSize),
count: inputChannelCount)
#else
// Portable WAV input.
let reader: WavFileReader = try WavFileReader(url: inputURL)
inputChannelCount = min(reader.channels, engine.numInputChannels)
if inputStartOffset > 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..<totalBlocks` range crash. Throw instead.
// The `< Double(Int.max)` bound also rejects a finite-but-astronomical
// duration whose block count would overflow the `Int(_:)` conversion.
// Validate duration before any Double→Int conversion.
let blocksDouble: Double = (duration * engine.sampleRate / Double(engine.blockSize)).rounded(.up)
guard duration.isFinite, duration >= 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..<totalBlocks {
// Build input for this block.
let inputSamples: [[Float]]
if let inputRef: ExtAudioFileRef = inputFileRef {
// Zero staging so that EOF blocks and unused trailing frames are silent.
for ch: Int in 0..<inputChannelCount {
for i: Int in 0..<bs { inputStagingBuffers[ch][i] = 0 }
}
var framesToRead: UInt32 = UInt32(bs)
let readStatus: OSStatus = inputReadBuffer.withUnsafeMutableBufferPointer { ptr in
var bufList: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: UInt32(inputChannelCount),
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.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..<framesRead {
for ch: Int in 0..<inputChannelCount {
inputStagingBuffers[ch][f] = inputReadBuffer[f * inputChannelCount + ch]
}
}
inputSamples = inputStagingBuffers
} else {
inputSamples = []
}
let inputSamples: [[Float]] = try _readInputBlock(bs: bs)
engine.processBlock(inputSamples: inputSamples)
triggerListener?._drainSync()
// Interleave output buses into the write buffer
for ch: Int in 0..<nch {
let bus: [Float] = engine.audioBuses[ch]
for s: Int in 0..<bs {
@@ -289,8 +254,6 @@ public final class NRTDriver: AudioDriver {
}
}
// Write interleaved block to file — a failure means a corrupt or truncated
// file, so we throw rather than silently swallow the error.
if let rf64Writer: RF64Writer {
try writeBuffer.withUnsafeBufferPointer { ptr in
try rf64Writer.writeFloat32Interleaved(ptr, frames: bs)
@@ -314,14 +277,43 @@ public final class NRTDriver: AudioDriver {
}
}
// Patch the RF64 ds64 sizes now (idempotent with the defer) so the file is
// finalised before this method returns.
try rf64Writer?.close()
// Synchronous render is done and the freeWorker timer only starts after this
// returns — emit any per-block event-drop warning here so it reaches the console
// even if the process exits before that timer (or `stop()`) runs.
engine.drainPerBlockEventDropWarning()
#else
// Portable WAV render path.
// Close the input reader's file handle regardless of how the render exits
// (mirrors the Apple branch's ExtAudioFileDispose defer).
defer {
inputReader?.close()
inputReader = nil
}
let encoding: WavEncoding = try Self.wavEncoding(for: outputFormat)
let writer: WavFileWriter = try WavFileWriter(
url: outputURL, channels: nch, sampleRate: engine.sampleRate, encoding: encoding
)
// Mirror the Apple branch's `ExtAudioFileDispose` defer: a throw from
// `processBlock` or a write would otherwise leave the handle open and
// the file's RIFF/`data` sizes at zero. `finalize()` is idempotent, so
// the explicit call below is unaffected.
defer { try? writer.finalize() }
for _ in 0..<totalBlocks {
let inputSamples: [[Float]] = try _readInputBlock(bs: bs)
engine.processBlock(inputSamples: inputSamples)
triggerListener?._drainSync()
for ch: Int in 0..<nch {
let bus: [Float] = engine.audioBuses[ch]
for s: Int in 0..<bs {
writeBuffer[s * nch + ch] = bus[s]
}
}
try writer.write(interleaved: writeBuffer, frames: bs)
}
try writer.finalize()
engine.drainPerBlockEventDropWarning()
#endif
}
public func stop() {
@@ -329,8 +321,76 @@ public final class NRTDriver: AudioDriver {
}
/// Requests sample-accurate control resolution by default.
/// Override by passing an explicit `controlBlockSize` to `SynthesisEngine.init`.
public var suggestedControlBlockSize: Int? { lyrebirdSampleAccurateControlBlockSize }
// MARK: - Input block assembly
/// Reads one block of input into the pre-allocated staging buffers (zero-filled
/// past EOF) and returns them. Returns `[]` when no input file is configured.
///
/// A read error must not be swallowed: an offline render that silently
/// substitutes silence for a truncated or unreadable input file reports
/// success and produces a wrong result, which is far worse than failing.
/// On Apple this throws ``NRTDriverError/inputReadFailed(_:)`` (the
/// `ExtAudioFile` status); off Apple the underlying ``WavFileError`` from
/// the portable reader propagates as-is.
private func _readInputBlock(bs: Int) throws -> [[Float]] {
guard inputChannelCount > 0 else { return [] }
for ch: Int in 0..<inputChannelCount {
for i: Int in 0..<bs { inputStagingBuffers[ch][i] = 0 }
}
#if canImport(AudioToolbox)
guard let inputRef: ExtAudioFileRef = inputFileRef else { return [] }
var framesToRead: UInt32 = UInt32(bs)
let readStatus: OSStatus = inputReadBuffer.withUnsafeMutableBufferPointer { ptr in
var bufList: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: UInt32(inputChannelCount),
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.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..<framesRead {
for ch: Int in 0..<inputChannelCount {
inputStagingBuffers[ch][f] = inputReadBuffer[f * inputChannelCount + ch]
}
}
#else
guard let reader: WavFileReader = inputReader else { return [] }
let fileChannels: Int = reader.channels
let block: [Float] = try reader.read(frames: bs)
let framesRead: Int = fileChannels > 0 ? block.count / fileChannels : 0
for f: Int in 0..<framesRead {
for ch: Int in 0..<inputChannelCount {
inputStagingBuffers[ch][f] = block[f * fileChannels + ch]
}
}
#endif
return inputStagingBuffers
}
#if !canImport(AudioToolbox)
/// Maps a WAV ``AudioFileFormat`` to a ``WavEncoding``; the Apple-only
/// containers throw ``NRTDriverError/unsupportedFormatOnPlatform(_:)``.
private static func wavEncoding(for format: AudioFileFormat) throws -> 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)
}
@@ -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
@@ -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<AudioConverterRef?>.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<UInt32>.size), &rate
)
guard setStatus == noErr else { return setStatus }
var config: CFPropertyList? = nil
return withUnsafePointer(to: &config) { ptr in
ExtAudioFileSetProperty(
fileRef, kExtAudioFileProperty_ConverterConfig,
UInt32(MemoryLayout<CFPropertyList?>.size), ptr
)
}
}
}
#endif
+22 -168
View File
@@ -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<AudioConverterRef?>.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<UInt32>.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<CFPropertyList?>.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
}
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
import LyrebirdDSP
import Foundation
import Synchronization
@@ -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..<samplesThisChunk {
writeBuf[i] = Float(storage[srcOffset + i])
}
try writer.write(interleaved: writeBuf, frames: framesThisChunk)
srcOffset += samplesThisChunk
}
}
try writer.finalize()
#endif
}
#if !canImport(AudioToolbox)
/// Maps a WAV ``AudioFileFormat`` to a ``WavEncoding`` for the portable
/// writer; the Apple-only containers throw
/// ``LyrebirdBufferIOError/unsupportedFormatOnPlatform(_:)``. RF64 is written
/// by ``RF64Writer`` before this is reached.
static func wavEncoding(for format: AudioFileFormat) throws -> 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..<framesRead {
storage[destOffset + i] = Double(block[i * fileChannelCount + channel])
}
destOffset += framesRead
}
if normalise && framesToRead > 0 {
var peak: Double = 0.0
for i: Int in 0..<framesToRead {
let v: Double = abs(storage[i])
if v > peak { peak = v }
}
if peak > 0.0 {
for i: Int in 0..<framesToRead { storage[i] /= peak }
}
}
}
}
/// Reads every channel of a WAV into an interleaved multichannel buffer, in
/// chunks, with optional global-peak normalisation. Mirrors ``readAllChannels``.
private func portableReadAllChannels(
_ reader: WavFileReader,
into buffer: LyrebirdBuffer,
framesToRead: Int,
normalise: Bool
) throws {
let fileChannelCount: Int = reader.channels
let bufChannelCount: Int = buffer.channelCount
try buffer.withMutableStorage { storage, _, _ in
var destFrame: Int = 0
while destFrame < framesToRead {
let framesThisChunk: Int = min(lyrebirdFileIOChunkFrames, framesToRead - destFrame)
let block: [Float] = try reader.read(frames: framesThisChunk)
let framesRead: Int = fileChannelCount > 0 ? block.count / fileChannelCount : 0
if framesRead == 0 { break }
for f: Int in 0..<framesRead {
for ch: Int in 0..<bufChannelCount {
storage[(destFrame + f) * bufChannelCount + ch] =
Double(block[f * fileChannelCount + ch])
}
}
destFrame += framesRead
}
if normalise && framesToRead > 0 {
let totalSamples: Int = framesToRead * bufChannelCount
var peak: Double = 0.0
for i: Int in 0..<totalSamples {
let v: Double = abs(storage[i])
if v > peak { peak = v }
}
if peak > 0.0 {
for i: Int in 0..<totalSamples { storage[i] /= peak }
}
}
}
}
#endif
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
import LyrebirdDSP
import Foundation
// MARK: - LyrebirdBuffer wavetable generation extensions
+3 -3
View File
@@ -81,7 +81,7 @@ public final class RF64Writer {
format: AudioFileFormat,
sampleRate: Double,
channels: Int
) throws {
) throws(RF64WriterError) {
guard format == .rf64Float32 || format == .rf64Int24 else {
throw RF64WriterError.unsupportedFormat(format)
}
@@ -173,7 +173,7 @@ public final class RF64Writer {
/// Append `frames` interleaved frames of native Float32 samples, converting to the
/// file encoding. `samples` must contain at least `frames * channels` values.
public func writeFloat32Interleaved(_ samples: UnsafeBufferPointer<Float>, frames: Int) throws {
public func writeFloat32Interleaved(_ samples: UnsafeBufferPointer<Float>, frames: Int) throws(RF64WriterError) {
guard frames > 0 else { return }
let sampleCount: Int = frames * channels
@@ -212,7 +212,7 @@ public final class RF64Writer {
///
/// The `FileHandle` is closed unconditionally (even if patching throws) so a failed
/// finalise never leaks the descriptor.
public func close() throws {
public func close() throws(RF64WriterError) {
guard !closed else { return }
closed = true
defer { try? fileHandle.close() }
@@ -0,0 +1,111 @@
// RTScratchBuffer.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// A single-owner, heap-allocated scratch buffer with compiler-enforced lifetime.
///
/// `RTScratchBuffer` replaces the hand-paired `UnsafeMutablePointer.allocate` /
/// `deinitialize` / `deallocate` dance that scratch-owning generators (the
/// Spectral / FFT family) repeat across many buffers. Because the type is
/// `~Copyable`, the compiler guarantees:
///
/// - it is freed **exactly once**, at `deinit`, with the correct element count —
/// no forgotten free, no double free, no count mismatch;
/// - it cannot be copied, so two owners can never alias the same allocation.
///
/// It carries no ARC: the handle is a raw pointer, so reading or writing an
/// element is a plain load/store with no retain/release traffic. Every accessor
/// is `@inline(__always)`, so a generator's hot loop compiles to the same code
/// as the raw-pointer form it replaces.
///
/// **RT usage.** Allocation happens in `init` (off the render thread, at
/// generator setup); `deinit` runs when the owning generator is freed, which the
/// engine does off the RT thread via its free queue. Element access
/// (`subscript`, ``baseAddress``) is RT-safe — no allocation, no locking, no ARC.
/// Pass ``baseAddress`` to Accelerate / vDSP calls exactly as with a raw pointer.
///
/// ```swift
/// // In a generator:
/// private let _scratch: RTScratchBuffer<Float>
/// init(size: Int) {
/// _scratch = RTScratchBuffer(count: size) // allocated + zero-filled
/// }
/// // deinit is automatic — no teardown code needed.
///
/// func process(count: Int) {
/// vDSP_vsq(input, 1, _scratch.baseAddress, 1, vDSP_Length(count))
/// let peak: Float = _scratch[0]
/// }
/// ```
@_spi(LyrebirdExtensions)
public struct RTScratchBuffer<Element>: ~Copyable {
@usableFromInline let _base: UnsafeMutablePointer<Element>
@usableFromInline let _count: Int
/// Allocates `count` elements, each initialised to `value`.
///
/// Use this when the buffer needs a non-zero initial fill (e.g. a unity gain
/// table initialised to `1`), where the zero-filling ``init(count:)`` would
/// silently seed the wrong value.
///
/// - Parameters:
/// - count: Element capacity. Must be `> 0`.
/// - value: Value written to every element.
@inlinable
public init(count: Int, repeating value: Element) {
precondition(count > 0, "RTScratchBuffer requires count > 0")
_count = count
_base = UnsafeMutablePointer<Element>.allocate(capacity: count)
_base.initialize(repeating: value, count: count)
}
/// Allocates `count` elements, zero-filled. Convenience for numeric buffers.
///
/// - Parameter count: Element capacity. Must be `> 0`.
@inlinable
public init(count: Int) where Element: Numeric {
self.init(count: count, repeating: .zero)
}
/// Base pointer, for Accelerate / vDSP interop and raw indexing. Valid only
/// for the duration of the call — never persist it beyond the lifetime of the
/// buffer (i.e. of the generator that owns it), exactly as with the raw
/// `UnsafeMutablePointer` this replaces.
@inlinable @inline(__always)
public var baseAddress: UnsafeMutablePointer<Element> { _base }
/// Element capacity.
@inlinable @inline(__always)
public var count: Int { _count }
/// Element access. No bounds check — callers stay within `count`, exactly as
/// they must with the raw pointer this replaces.
///
/// The setter is `nonmutating`: writing an element stores through the base
/// pointer and leaves the struct's own fields untouched, so a buffer held as a
/// `let` (the usual case in a generator) is still writable — matching the raw
/// `UnsafeMutablePointer` this replaces.
@inlinable @inline(__always)
public subscript(_ index: Int) -> Element {
get {
#if DEBUG
precondition(index >= 0 && index < _count, "RTScratchBuffer index out of range")
#endif
return _base[index]
}
nonmutating set {
#if DEBUG
precondition(index >= 0 && index < _count, "RTScratchBuffer index out of range")
#endif
_base[index] = newValue
}
}
deinit {
_base.deinitialize(count: _count)
_base.deallocate()
}
}
@@ -0,0 +1,59 @@
// WavEncoding.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// PCM sample encodings supported by Lyrebird's portable WAV reader/writer.
///
/// The portable WAV codec exists so offline render (`NRTDriver`), disk streaming
/// generators, and buffer file I/O keep working on platforms without Apple's
/// `AudioToolbox`/`ExtAudioFile`. It handles canonical RIFF/WAVE with a single
/// `fmt ` chunk and a single `data` chunk — the format every tool writes and
/// reads. CAF and AIFF containers remain Apple-only (they route through
/// `ExtAudioFile` under `#if canImport(AudioToolbox)`).
public enum WavEncoding: Sendable, Equatable {
/// 32-bit IEEE float (WAVE format tag 3). The default — lossless for the
/// engine's internal `Double`/`Float` sample representation.
case float32
/// 16-bit signed integer PCM (WAVE format tag 1).
case int16
/// 24-bit signed integer PCM, packed 3 bytes/sample (WAVE format tag 1).
case int24
/// WAVE `wFormatTag`: 1 = integer PCM, 3 = IEEE float.
var formatTag: UInt16 {
switch self {
case .float32: return 3
case .int16, .int24: return 1
}
}
/// Bytes per single-channel sample.
var bytesPerSample: Int {
switch self {
case .float32: return 4
case .int16: return 2
case .int24: return 3
}
}
/// Bits per single-channel sample (WAVE `wBitsPerSample`).
var bitsPerSample: UInt16 {
UInt16(bytesPerSample * 8)
}
/// Whether this is an integer PCM tag.
///
/// RIFF holds non-PCM tags to a stricter header: the `fmt ` body must
/// declare `cbSize` (18 bytes rather than 16) and the file must carry a
/// `fact` chunk. `WavFileWriter` branches on this.
var isPCM: Bool {
switch self {
case .int16, .int24: return true
case .float32: return false
}
}
}
@@ -0,0 +1,30 @@
// WavFileError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Errors thrown by the portable WAV reader/writer.
public enum WavFileError: Error, Equatable {
/// The destination file could not be created.
case cannotCreate(URL)
/// The source file could not be opened for reading.
case cannotOpen(URL)
/// The file is not a RIFF/WAVE container (bad magic).
case notWave
/// The file's `fmt ` chunk describes an encoding the portable codec does not
/// handle (only int16 / int24 / float32 PCM are supported; use the
/// `AudioToolbox` path on Apple for compressed or exotic formats).
case unsupportedFormat(formatTag: UInt16, bitsPerSample: UInt16)
/// The file ended before the header or declared data could be read. Also
/// covers a `fmt ` chunk too short to hold the fields it must declare.
case truncated
/// A plain WAV cannot describe more than 4 GB — its RIFF and `data` sizes
/// are 32-bit. Writing past that needs RF64/W64 instead.
case fileTooLarge(bytes: Int)
/// An underlying file-system operation (`FileHandle` read / seek / write)
/// failed. Associated value is the system error's description.
case ioFailure(String)
}
@@ -0,0 +1,253 @@
// WavFileReader.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Streaming reader for canonical RIFF/WAVE PCM files, portable to every
/// platform (no `AudioToolbox` dependency).
///
/// Parses the `fmt ` and `data` chunks at construction, then serves interleaved
/// `Float` samples in `[-1, 1]` a block at a time via ``read(frames:)`` — the
/// mirror of ``WavFileWriter`` and the shape `NRTDriver`'s input path needs.
public final class WavFileReader {
/// Interleaved channel count.
public let channels: Int
/// Sample rate in Hz.
public let sampleRate: Double
/// Total number of frames (per-channel sample groups) in the file.
public let frameCount: Int
/// Decoded PCM encoding.
public let encoding: WavEncoding
private let handle: FileHandle
private let bytesPerFrame: Int
private var framesRemaining: Int
/// Opens `url` and parses its WAVE header.
public init(url: URL) throws(WavFileError) {
guard let h: FileHandle = try? FileHandle(forReadingFrom: url) else {
throw WavFileError.cannotOpen(url)
}
self.handle = h
// RIFF/WAVE magic: "RIFF" <size:4> "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 Self.fhOffset(h)
let fileByteCount: Int = Int(try Self.fhSeekToEnd(h))
try Self.fhSeek(h, to: 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 Self.fhOffset(h)))
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 Self.fhOffset(h)
let target: UInt64 = current + UInt64(max(0, skip))
guard target <= UInt64(fileByteCount) else { break }
try Self.fhSeek(h, to: 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(WavFileError) -> [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..<sampleCount {
let bits: UInt32 = Self.loadLE32(rawPtr, byteOffset: i * 4)
out[i] = Float(bitPattern: bits)
}
case .int16:
let inv: Float = 1.0 / 32768.0
for i: Int in 0..<sampleCount {
let v: Int16 = Int16(bitPattern: Self.loadLE16(rawPtr, byteOffset: i * 2))
out[i] = Float(v) * inv
}
case .int24:
let inv: Float = 1.0 / 8388608.0
for i: Int in 0..<sampleCount {
let b0: Int32 = Int32(rawPtr[i * 3])
let b1: Int32 = Int32(rawPtr[i * 3 + 1])
let b2: Int32 = Int32(rawPtr[i * 3 + 2])
var v: Int32 = b0 | (b1 << 8) | (b2 << 16)
if (v & 0x0080_0000) != 0 { v |= ~0x00FF_FFFF } // sign-extend 24→32
out[i] = Float(v) * inv
}
}
}
return out
}
/// Advances past `frames` frames without materialising them.
///
/// Seeks rather than reading: skipping into a long file — a start offset a
/// minute into a stereo 48 kHz recording is ~23 M samples — would otherwise
/// allocate the whole skipped region just to discard it. Skipping past the
/// end simply exhausts the reader.
///
/// - Parameter frames: Frames to advance by. Non-positive values do nothing.
public func skip(frames: Int) throws(WavFileError) {
let toSkip: Int = min(frames, framesRemaining)
guard toSkip > 0 else { return }
let current: UInt64 = try Self.fhOffset(handle)
try Self.fhSeek(handle, to: 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
}
}
/// Wraps `FileHandle.offset()`, funneling its foreign error into `WavFileError`.
private static func fhOffset(_ h: FileHandle) throws(WavFileError) -> UInt64 {
do { return try h.offset() }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
/// Wraps `FileHandle.seekToEnd()`, funneling its foreign error into `WavFileError`.
private static func fhSeekToEnd(_ h: FileHandle) throws(WavFileError) -> UInt64 {
do { return try h.seekToEnd() }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
/// Wraps `FileHandle.seek(toOffset:)`, funneling its foreign error into `WavFileError`.
private static func fhSeek(_ h: FileHandle, to offset: UInt64) throws(WavFileError) {
do { try h.seek(toOffset: offset) }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
private static func readExact(_ h: FileHandle, _ count: Int) throws(WavFileError) -> Data {
guard count > 0 else { return Data() }
let d: Data?
do { d = try h.read(upToCount: count) }
catch { throw WavFileError.ioFailure(String(describing: error)) }
guard let d, 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)
}
}
@@ -0,0 +1,278 @@
// 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(WavFileError) {
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)
}
let h: FileHandle
do { h = try FileHandle(forWritingTo: url) }
catch { throw WavFileError.ioFailure(String(describing: error)) }
self.handle = h
try Self.fhSeekToEnd(h)
}
/// 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(WavFileError) {
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..<needed {
var le: UInt32 = samples[i].bitPattern.littleEndian
withUnsafeBytes(of: &le) { out.append(contentsOf: $0) }
}
case .int16:
// Full-scale maps to 32767 / 8388607, not 32768 / 8388608, so an
// input of exactly +1.0 cannot overflow the signed range. The
// reader divides by the power of two, which is the usual pairing;
// the resulting round-trip difference is ~0.003 %, well below the
// quantisation step.
let scale: Float = 32767.0
for i: Int in 0..<needed {
let clamped: Float = min(1.0, max(-1.0, samples[i]))
var le: Int16 = Int16((clamped * scale).rounded()).littleEndian
withUnsafeBytes(of: &le) { out.append(contentsOf: $0) }
}
case .int24:
let scale: Float = 8388607.0
for i: Int in 0..<needed {
let clamped: Float = min(1.0, max(-1.0, samples[i]))
let v: Int32 = Int32((clamped * scale).rounded())
out.append(UInt8(truncatingIfNeeded: v))
out.append(UInt8(truncatingIfNeeded: v >> 8))
out.append(UInt8(truncatingIfNeeded: v >> 16))
}
}
try Self.fhWrite(handle, 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(WavFileError) {
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 Self.fhSeekToEnd(handle)
try Self.fhWrite(handle, [UInt8(0)])
padByteWritten = true
}
let riffChunkSize: UInt32 = try Self.riffChunkSize(
headerBytes: headerByteCount,
dataBytes: dataBytesWritten + padByteCount
)
let dataChunkSize: UInt32 = UInt32(dataBytesWritten)
try Self.fhSeek(handle, to: Self.riffChunkSizeOffset)
try Self.fhWrite(handle, 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 Self.fhSeek(handle, to: Self.factSampleCountOffset)
try Self.fhWrite(handle, Self.leBytes(frames))
}
try Self.fhSeek(handle, to: dataChunkSizeOffset)
try Self.fhWrite(handle, Self.leBytes(dataChunkSize))
try Self.fhClose(handle)
// 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(WavFileError) -> UInt32 {
let payload: Int = headerBytes - 8 + dataBytes
guard payload <= Int(UInt32.max) else {
throw WavFileError.fileTooLarge(bytes: payload)
}
return UInt32(payload)
}
// MARK: - FileHandle wrappers (funnel foreign errors into WavFileError)
/// Wraps `FileHandle.seekToEnd()`, funneling its foreign error into `WavFileError`.
private static func fhSeekToEnd(_ h: FileHandle) throws(WavFileError) {
do { try h.seekToEnd() }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
/// Wraps `FileHandle.seek(toOffset:)`, funneling its foreign error into `WavFileError`.
private static func fhSeek(_ h: FileHandle, to offset: UInt64) throws(WavFileError) {
do { try h.seek(toOffset: offset) }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
/// Wraps `FileHandle.write(contentsOf:)`, funneling its foreign error into `WavFileError`.
private static func fhWrite(_ h: FileHandle, _ bytes: [UInt8]) throws(WavFileError) {
do { try h.write(contentsOf: bytes) }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
/// Wraps `FileHandle.write(contentsOf:)` for a `Data` payload.
private static func fhWrite(_ h: FileHandle, _ bytes: Data) throws(WavFileError) {
do { try h.write(contentsOf: bytes) }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
/// Wraps `FileHandle.close()`, funneling its foreign error into `WavFileError`.
private static func fhClose(_ h: FileHandle) throws(WavFileError) {
do { try h.close() }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
// 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)]
}
}
+1 -1
View File
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
import LyrebirdDSP
import Foundation
// MARK: - WavetableSet
+13 -7
View File
@@ -76,7 +76,7 @@ public final class BusAllocator: @unchecked Sendable {
/// Allocates the first contiguous block of `channelCount` free audio buses.
/// Throws `BusAllocatorError.noFreeBus` if no block of that size is available.
public func allocateAudioBus(channelCount: Int) throws -> AudioBus {
public func allocateAudioBus(channelCount: Int) throws(BusAllocatorError) -> AudioBus {
let index: Int = try _allocate(in: &audioFreeList, channelCount: channelCount)
return AudioBus(index: index, channelCount: channelCount)
}
@@ -94,7 +94,7 @@ public final class BusAllocator: @unchecked Sendable {
/// Allocates the first contiguous block of `channelCount` free control buses.
/// Throws `BusAllocatorError.noFreeBus` if no block of that size is available.
public func allocateControlBus(channelCount: Int = 1) throws -> ControlBus {
public func allocateControlBus(channelCount: Int = 1) throws(BusAllocatorError) -> ControlBus {
let index: Int = try _allocate(in: &controlFreeList, channelCount: channelCount)
return ControlBus(index: index, channelCount: channelCount)
}
@@ -113,13 +113,15 @@ public final class BusAllocator: @unchecked Sendable {
private func _allocate(
in freeList: inout [Bool],
channelCount: Int
) throws -> Int {
) throws(BusAllocatorError) -> Int {
precondition(channelCount >= 1, "BusAllocator: channelCount must be >= 1")
return try _lock.withLock {
// The search runs under the lock and returns the start index, or `nil`
// when no block of the requested size is free; the throw happens outside
// the lock because `NSLock.withLock` is `rethrows` and does not narrow to
// the closure's typed error.
let allocated: Int? = _lock.withLock { () -> Int? in
let n: Int = freeList.count
guard channelCount <= n else {
throw BusAllocatorError.noFreeBus(channelCount: channelCount)
}
guard channelCount <= n else { return nil }
var start: Int = 0
outer: while start <= n - channelCount {
for i: Int in start..<(start + channelCount) {
@@ -133,8 +135,12 @@ public final class BusAllocator: @unchecked Sendable {
}
return start
}
return nil
}
guard let index: Int = allocated else {
throw BusAllocatorError.noFreeBus(channelCount: channelCount)
}
return index
}
/// Marks `[startIndex, startIndex + channelCount)` slots back to free. When
+1 -1
View File
@@ -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.
///
@@ -65,10 +65,7 @@ public final class SpectrumCapture: SpectralProcessor, @unchecked Sendable {
/// - fftSize: FFT frame size. Must match the `SpectralChain.Audio` this capture is registered on.
/// Must be a power of two ≥ 4. Default: 2048.
public init(fftSize: Int = 2048) {
precondition(
fftSize >= 4 && (fftSize & (fftSize - 1)) == 0,
"SpectrumCapture: fftSize must be a power of two >= 4, got \(fftSize)"
)
lyrebirdRequireFFTSize(fftSize, typeName: "SpectrumCapture")
self.fftSize = fftSize
let bc: Int = fftSize / 2 + 1
self.binCount = bc
+57 -20
View File
@@ -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
}
+86 -20
View File
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
import LyrebirdDSP
import Foundation
import Synchronization
@@ -41,6 +41,30 @@ import Synchronization
/// it is callable from any non-RT thread. From a `LyrebirdRoutine` / `LyrebirdTask` body, go
/// through the context (``LyrebirdRoutineContext/add(_:)``, which dispatches to main) rather
/// than calling the engine directly. See `ARCHITECTURE.md` §1 and §9.
///
/// **Deliberately NOT `Sendable`.** This was evaluated and rejected on purpose:
/// - *Checked* `Sendable` is infeasible — the engine holds mutable per-block RT
/// state (node tree, bus memory, block cursors) whose safety comes from the
/// architecture (single-producer `pendingQueue`, atomics, the render-callback
/// happens-before barrier), not from the type system. Those fields cannot be
/// made Sendable-clean without dismantling the RT design.
/// - *`@unchecked`* `Sendable` would be a blanket "safe to share across threads"
/// assertion that is only true for *specific* access patterns (main-thread
/// mutation via the queue; RT-thread reads in `processBlock`) and false for
/// others (mutating config while running, or touching the engine from the RT
/// thread). Declaring it would erase the compiler friction that currently
/// forces each genuine cross-thread transfer to be spelled `nonisolated(unsafe)`
/// at the call site — and those few sites (e.g. `LyrebirdAudioUnit` config
/// hand-off, a UI closure capture) are a *feature*: each is a visible, reviewed
/// "verified safe here" marker on the most concurrency-sensitive object in the
/// system.
///
/// The cost of staying non-Sendable is tiny (a handful of `nonisolated(unsafe)`
/// captures) and the benefit is real (no false safety guarantee, every transfer
/// stays auditable). Classes that hold an engine reference therefore remain
/// `@unchecked Sendable` themselves, keeping their own mutable state in a `Mutex`
/// and naming the engine reference as the sole hand-verified item. Do not add a
/// `Sendable` conformance here without re-opening that trade-off.
public final class SynthesisEngine {
/// Process-unique identity. Used by the engine ownership-binding system
@@ -901,9 +925,7 @@ public final class SynthesisEngine {
self.bufferSwapKillQueue = SPSCQueue<UnsafeRawPointer>(
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
@@ -962,7 +984,7 @@ public final class SynthesisEngine {
/// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` if the engine is
/// currently running; ``SynthesisEngineConfigError/invalidValue(_:)`` if
/// `rate` is non-finite or `<= 0`.
public func setSampleRate(_ rate: Double) throws {
public func setSampleRate(_ rate: Double) throws(SynthesisEngineConfigError) {
guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning }
guard rate.isFinite, rate > 0 else {
throw SynthesisEngineConfigError.invalidValue(
@@ -984,7 +1006,7 @@ public final class SynthesisEngine {
/// `numAudioBuses`.
/// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` /
/// ``SynthesisEngineConfigError/invalidValue(_:)``.
public func setNumOutputChannels(_ count: Int) throws {
public func setNumOutputChannels(_ count: Int) throws(SynthesisEngineConfigError) {
guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning }
guard count >= 1 else {
throw SynthesisEngineConfigError.invalidValue(
@@ -1015,7 +1037,7 @@ public final class SynthesisEngine {
/// `numAudioBuses` together with `numOutputChannels`.
/// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` /
/// ``SynthesisEngineConfigError/invalidValue(_:)``.
public func setNumInputChannels(_ count: Int) throws {
public func setNumInputChannels(_ count: Int) throws(SynthesisEngineConfigError) {
guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning }
guard count >= 0 else {
throw SynthesisEngineConfigError.invalidValue(
@@ -1163,13 +1185,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 +1230,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 +1243,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 +1283,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 +1296,8 @@ public final class SynthesisEngine {
n.prev = nil
if n.synth === mainGroup {
mainNode = n
} else {
_unbindNodeAndDescendants(n)
}
node = next
}
@@ -1368,7 +1434,7 @@ public final class SynthesisEngine {
@MainActor public func schedule(
_ synth: any Synthesizer,
at time: SampleTime
) throws {
) throws(EngineAddError) {
precondition(
synth !== rootGroup && synth !== mainGroup,
"Cannot add the engine's persistent rootGroup or mainGroup as a child Synthesizer"
@@ -1397,7 +1463,7 @@ public final class SynthesisEngine {
@MainActor public func schedule(
_ synth: any Synthesizer,
after seconds: Double
) throws {
) throws(EngineAddError) {
precondition(
synth !== rootGroup && synth !== mainGroup,
"Cannot add the engine's persistent rootGroup or mainGroup as a child Synthesizer"
@@ -1467,7 +1533,7 @@ public final class SynthesisEngine {
/// Equivalent to `schedule(_:at:currentTime)`. The synthesizer lands at the head of
/// `mainGroup` — newest-first order. Safe to call from the main thread.
/// - Throws: `EngineAddError` — see `schedule(_:at:)` for cases.
@MainActor public func add(_ synth: any Synthesizer) throws {
@MainActor public func add(_ synth: any Synthesizer) throws(EngineAddError) {
try schedule(synth, at: currentTime)
}
@@ -1484,7 +1550,7 @@ public final class SynthesisEngine {
@MainActor public func add(
_ synth: any Synthesizer,
position: NodePosition
) throws {
) throws(EngineAddError) {
precondition(
synth !== rootGroup && synth !== mainGroup,
"Cannot add the engine's persistent rootGroup or mainGroup as a child Synthesizer"
@@ -1516,7 +1582,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..<audioBuses.count {
audioBuses[i].withUnsafeMutableBufferPointer { buf in
@@ -1632,7 +1698,7 @@ public final class SynthesisEngine {
_currentTime.store(blockStart + SampleTime(blockSize), ordering: .releasing)
// 5. CPU usage statistics — RT-private EMA + atomic publish.
let elapsedNs: Double = Double(mach_absolute_time() &- blockStartTick) * _machTicksToNs
let elapsedNs: Double = Double(LyrebirdMonotonicClock.ticks() &- blockStartTick) * _machTicksToNs
let cpuLoad: Double = elapsedNs / _blockDurationNs
if _cpuEMAInitialized {
@@ -0,0 +1,46 @@
// BlockRateControlGenerator.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// MARK: - BlockRateControlGenerator
/// A `ControlGenerator` whose state must advance exactly once per audio block —
/// IIR filters, bus writers, buffer-position advancers, gain smoothers, trigger
/// detectors, random drawers, analysers, etc. These generators do **not** sub-block.
///
/// Conforming to this marker supplies the block-rate `calculatedSamples` gateway for
/// free, replacing the per-generator forwarder:
///
/// ```swift
/// // Before: every such Control hand-wrote this bypass …
/// public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
/// _calculatedSamplesBlockRate(graph: graph, count: count)
/// }
/// // … and called _setupSubBlockBuffer() in init for a buffer it never used.
///
/// // After: just conform.
/// public final class Control: _Base, BlockRateControlGenerator { … }
/// ```
///
/// Because `calculatedSamples` is a `ValidGeneratorInput` requirement, the witness for a
/// conformer resolves to the most-refined protocol extension that provides it — this one
/// — so it overrides the `ControlGenerator` sub-block gateway. A conformer therefore runs
/// `_computeSamples` once per audio block and never touches `_subBlockBuffer`, so it also
/// skips the `_setupSubBlockBuffer()` allocation.
///
/// Conform **only** generators that genuinely bypass sub-blocking (previously via the
/// explicit `_calculatedSamplesBlockRate` forwarder). A true sub-blocking `ControlGenerator`
/// must NOT conform — it needs the `ControlGenerator` sub-block path and its
/// `_subBlockBuffer`.
public protocol BlockRateControlGenerator: ControlGenerator {}
extension BlockRateControlGenerator {
public func calculatedSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
}
+12 -13
View File
@@ -135,8 +135,9 @@ public protocol ControlGenerator: Generator {
///
/// Used by `calculatedSamples` when `controlBlockSize < count` to accumulate
/// results from multiple `_computeSamples` calls without heap allocation.
/// Initialise to `[[]]` (via `GeneratorBase` default). Call `_setupSubBlockBuffer()`
/// in the designated `Control.init` to resize for sub-block assembly. Never call on the RT thread.
/// Initialise to `[[]]` (via `GeneratorBase` default). A sub-blocking `Control.init`
/// calls `_setupSubBlockBuffer()` to resize for sub-block assembly (never on the RT
/// thread); `BlockRateControlGenerator` conformers never sub-block and skip it.
var _subBlockBuffer: [[Double]] { get set }
}
@@ -205,18 +206,16 @@ extension Generator {
/// Bypass-sub-block fan-out cache helper.
///
/// Used by generators that override `calculatedSamples` to force `_computeSamples` to
/// run exactly once per audio block, bypassing the `ControlGenerator` extension's
/// sub-block path. Required for any generator whose state must advance once per audio
/// block (IIR filters, bus writers, buffer-position advancers, gain smoothers, trigger
/// detectors, random drawers). See `docs/protocols/writing-generators.md` §15.
/// The block-rate gateway: runs `_computeSamples` exactly once per audio block,
/// bypassing the `ControlGenerator` extension's sub-block path. Required for any
/// generator whose state must advance once per audio block (IIR filters, bus writers,
/// buffer-position advancers, gain smoothers, trigger detectors, random drawers,
/// analysers). See `docs/protocols/writing-generators.md` §15.
///
/// Drop-in replacement for the canonical bypass block:
/// ```swift
/// public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] {
/// _calculatedSamplesBlockRate(graph: graph, count: count)
/// }
/// ```
/// The standard way to get this behaviour is to conform the control generator to
/// `BlockRateControlGenerator`, whose `calculatedSamples` default calls this method —
/// prefer that over hand-writing a `calculatedSamples` forwarder. Call this directly
/// only when the bypass is needed but the marker cannot apply.
@inline(__always)
public func _calculatedSamplesBlockRate(
graph: SynthGraph,
@@ -22,8 +22,10 @@
/// post-super reassignment. `outputChannelCount` must be overridden to return the
/// fixed channel count.
///
/// `Audio` conformers inherit `_subBlockBuffer` as `[[]]` (no allocation); `Control` conformers
/// resize it to `lyrebirdDefaultResultBufferSize` via `_setupSubBlockBuffer()` in `init`.
/// `Audio` conformers inherit `_subBlockBuffer` as `[[]]` (no allocation); sub-blocking
/// `Control` conformers resize it to `lyrebirdDefaultResultBufferSize` via
/// `_setupSubBlockBuffer()` in `init`. `BlockRateControlGenerator` conformers never
/// sub-block and leave it unallocated.
open class GeneratorBase {
public var _segmentSerial: UInt64 = 0
public var _cachedResult: [[Double]] = [[]]
@@ -58,3 +58,63 @@ public func resolveGeneratorOrScalar(
}
return (nil, source.floatValue(graph: graph))
}
// MARK: - Block-constant generator reads
/// Reads the **first** sample of a generator's block output, or returns the scalar
/// `floatValue` when the input is not a Generator. RT-safe.
///
/// Use for block-constant parameters read once at the top of a `Control._computeSamples`:
/// the first-sample read picks up the value at the block boundary while keeping the rest
/// of the per-block math at block-rate. The companion `lastGeneratorSampleOrFloat` reads
/// the block's final sample instead (ramp endpoint).
///
/// - Parameters:
/// - input: Any `ValidGeneratorInput` — scalar, `ParameterNode`, or generator.
/// - isGenerator: Pre-computed at init (`input is any Generator`). Never use `is` on the RT thread.
/// - graph: The current synthesis graph.
/// - count: Number of samples in the current block.
/// - Returns: the first sample of `input.calculatedSamples(...)` (or `0` if the block is
/// empty) when `isGenerator` is true; `input.floatValue(graph:)` otherwise.
@inline(__always)
@_spi(LyrebirdExtensions)
public func firstGeneratorSampleOrFloat(
_ input: any ValidGeneratorInput,
isGenerator: Bool,
graph: SynthGraph,
count: Int
) -> Double {
guard isGenerator else { return input.floatValue(graph: graph) }
return input.calculatedSamples(graph: graph, count: count).first?.first ?? 0
}
/// Reads the **last** sample of a generator's block output, or returns the scalar
/// `floatValue` when the input is not a Generator. RT-safe.
///
/// Use for block-constant parameters that must still capture `ParameterNode` ramps:
/// the last-sample read picks up the ramp endpoint while keeping coefficient math
/// at block-rate. The companion `firstGeneratorSampleOrFloat` reads the block's first
/// sample instead.
///
/// - Parameters:
/// - input: Any `ValidGeneratorInput` — scalar, `ParameterNode`, or generator.
/// - isGenerator: Pre-computed at init (`input is any Generator`). Never use `is` on the RT thread.
/// - graph: The current synthesis graph.
/// - count: Number of samples in the current block.
/// - Returns: `buf[count - 1]` when `isGenerator` is true and the block is non-empty;
/// `input.floatValue(graph:)` otherwise.
@inline(__always)
@_spi(LyrebirdExtensions)
public func lastGeneratorSampleOrFloat(
_ input: any ValidGeneratorInput,
isGenerator: Bool,
graph: SynthGraph,
count: Int
) -> Double {
guard isGenerator else { return input.floatValue(graph: graph) }
guard let buf: [Double] = input.calculatedSamples(graph: graph, count: count).first,
count > 0 else {
return input.floatValue(graph: graph)
}
return buf[count - 1]
}
+53 -38
View File
@@ -4,39 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
// MARK: - Block-constant generator read helper
/// Reads the last sample of a generator's block output, or returns the scalar
/// `floatValue` when the input is not a Generator. RT-safe.
///
/// Use for block-constant parameters that must still capture `ParameterNode` ramps:
/// the last-sample read picks up the ramp endpoint while keeping coefficient math
/// at block-rate.
///
/// - Parameters:
/// - input: Any `ValidGeneratorInput` — scalar, `ParameterNode`, or generator.
/// - isGenerator: Pre-computed at init (`input is any Generator`). Never use `is` on the RT thread.
/// - graph: The current synthesis graph.
/// - count: Number of samples in the current block.
/// - Returns: `buf[count - 1]` when `isGenerator` is true and the block is non-empty;
/// `input.floatValue(graph:)` otherwise.
@_spi(LyrebirdExtensions)
@inline(__always)
public func lastGeneratorSampleOrFloat(
_ input: any ValidGeneratorInput,
isGenerator: Bool,
graph: SynthGraph,
count: Int
) -> Double {
guard isGenerator else { return input.floatValue(graph: graph) }
guard let buf: [Double] = input.calculatedSamples(graph: graph, count: count).first,
count > 0 else {
return input.floatValue(graph: graph)
}
return buf[count - 1]
}
import LyrebirdDSP
// MARK: - Scalar extraction
@@ -63,9 +31,9 @@ public func extractScalar(_ input: any ValidGeneratorInput) -> Double? {
/// _mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
/// ```
/// `applyIfNeeded` short-circuits internally on `isIdentity`, so the call site
/// never needs an `if !isIdentity` guard. `MathGenerators.Control` does not call
/// through this struct — it computes its scalar `target = input * mulFloat + addFloat`
/// before the ramp, documented in `docs/protocols/writing-generators.md` §13.
/// never needs an `if !isIdentity` guard. `MathGenerators.Control` applies mul/add to
/// its scalar `target` before the ramp (not to the output buffer after) via `applyScalar`
/// below — documented in `docs/protocols/writing-generators.md` §13.
@_spi(LyrebirdExtensions)
public struct MulAddSpec {
public let mulInput: any ValidGeneratorInput
@@ -115,6 +83,20 @@ public struct MulAddSpec {
if !isIdentity { apply(to: &channels, graph: graph, count: count) }
}
/// Applies the scalar `(target × mul) + add` to a single block-constant value,
/// short-circuiting to `target` on identity. Reads `mul`/`add` at block rate via
/// `floatValue`.
///
/// For `Math.Control` paths that compute one scalar target per block and hand it to
/// `fillScalarRampedResult` — the documented exception to the buffer-based
/// `apply`/`applyIfNeeded`. Replaces the inline
/// `if !isIdentity { target = target * mulInput.floatValue + addInput.floatValue }`.
@inline(__always)
public func applyScalar(_ target: Double, graph: SynthGraph) -> Double {
guard !isIdentity else { return target }
return target * mulInput.floatValue(graph: graph) + addInput.floatValue(graph: graph)
}
/// Applies `(x × mul) + add` via vDSP to every channel in `channels`.
///
/// **Channel-aware broadcast (matches `BinaryOpGenerator` policy).** When `mul` or
@@ -247,8 +229,7 @@ public func fillRampedResult(
/// Usage in a Math-style ControlGenerator._computeSamples:
/// ```swift
/// var target = someScalarOp(input.floatValue(graph: graph))
/// if !_mulAdd.isIdentity { target = target * _mulAdd.mulInput.floatValue(graph: graph)
/// + _mulAdd.addInput.floatValue(graph: graph) }
/// target = _mulAdd.applyScalar(target, graph: graph)
/// fillScalarRampedResult(
/// into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
/// return _result
@@ -279,6 +260,40 @@ public func fillScalarRampedResult(
}
}
/// Fills `result[0]` with a single block-constant `value`, applies `mulAdd` if
/// non-identity, and sets `previousOutputValue` to the (post-mulAdd) last sample.
/// No-op when `count == 0` (leaving `previousOutputValue` unchanged).
///
/// The held counterpart of `fillScalarRampedResult`: block-rate `ControlGenerator`
/// paths whose output holds one value for the whole block — one-pole/leaky
/// smoothers (`Lag`, `Decay`, `LeakDC`, `Slew`, `Formlet`), block-constant analysis
/// outputs (`ZeroCrossing`, `Slope`, `RunningMin`/`Max`), and trigger/counter latches
/// (`Trig`, `Schmidt`, `PulseCount`, `Stepper`, …). Replaces the repeated
/// `vDSP_vfillD` (or per-sample constant fill) + `applyIfNeeded` + last-sample tail.
@_spi(LyrebirdExtensions)
@inline(__always)
public func fillHeldResult(
into result: inout [[Double]],
value: Double,
previousOutputValue: inout Double,
mulAdd: MulAddSpec,
graph: SynthGraph,
count: Int
) {
guard count > 0 else { return }
precondition(!result.isEmpty,
"fillHeldResult: result has no rows")
precondition(count <= result[0].count,
"fillHeldResult: count exceeds result buffer")
var fillValue: Double = value
result[0].withUnsafeMutableBufferPointer { (buf: inout UnsafeMutableBufferPointer<Double>) in
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
}
mulAdd.applyIfNeeded(to: &result, graph: graph, count: count)
previousOutputValue = result[0][count - 1]
}
// MARK: - Per-channel vDSP dispatch
/// Pure-scalar `(x * mulScalar) + addScalar` for one channel. No `Optional`
@@ -42,7 +42,7 @@ public enum BeatTrack {
/// once at init. Defaults to ``beatTrackPreferredBPM``.
/// - windowSeconds: ODF history length for autocorrelation. Read once at
/// init. Defaults to ``beatTrackMaxWindowSeconds``.
public final class Control: GeneratorBase, ControlGenerator {
public final class Control: GeneratorBase, BlockRateControlGenerator {
/// Internal ODF source + the input refs each mode needs. Only one mode's
/// state is live; the spectral-flux state (`_prevMag`, `_isFirstFrame`)
@@ -197,19 +197,8 @@ public enum BeatTrack {
featureRateHz: beatTrackFeatureRateHz
)
super.init(channels: beatTrackOutputRowCount)
_setupSubBlockBuffer(channels: beatTrackOutputRowCount)
}
// MARK: - Compute
// Bypass the sub-block loop: the ODF advances once per audio block (the
// spectral buffer once per FFT hop) and the tracker state must too.
public func calculatedSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
public func _computeSamples(
graph: SynthGraph,
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
import LyrebirdDSP
import Foundation
/// Peak ODF value across one audio block. Onsets are impulsive, so the max
@@ -38,7 +38,7 @@ public enum Loudness {
/// - calibrationDB: dBFS→SPL offset. Defaults to ``loudnessDefaultCalibrationDB``.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset (sones). Defaults to `0.0`.
public final class Control: GeneratorBase, ControlGenerator {
public final class Control: GeneratorBase, BlockRateControlGenerator {
private let _analysis: SpectralChain.Audio?
private let _spectral: SpectralBuffer
@@ -127,17 +127,8 @@ public enum Loudness {
)
self._mulAdd = MulAddSpec(mul: mul, add: add)
super.init()
_setupSubBlockBuffer()
}
// Bypass the sub-block loop: the spectral buffer advances once per FFT
// hop and the loudness state (temporal mask) advances once per block.
public func calculatedSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
public func _computeSamples(
graph: SynthGraph,
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
import LyrebirdDSP
/// File-scope zero-fill block for RunningMax — fallback when upstream returns no channel.
private let runningMaxZeroBlock: [Double] = [Double](
@@ -143,7 +143,7 @@ public enum RunningMax {
/// - trig: Reset trigger. ≤0 → >0 rising edges reset the running maximum. Defaults to `0.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public final class Control: _Base, BlockRateControlGenerator {
public var previousOutputValue: Double = 0.0
/// - Parameters:
@@ -158,17 +158,8 @@ public enum RunningMax {
add: any ValidGeneratorInput = 0.0
) {
super.init(input: input, trig: trig, mul: mul, add: add)
_setupSubBlockBuffer()
}
/// Bypass sub-block loop: the running-maximum state machine must scan the full
/// audio-rate input block exactly once per audio block.
public func calculatedSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
public func _computeSamples(
graph: SynthGraph,
@@ -203,16 +194,7 @@ public enum RunningMax {
_prevTrig = prevTrig
_initialized = initialized
var fillValue: Double = extreme
_result[0].withUnsafeMutableBufferPointer { buf in
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
guard count > 0 else { return _result }
previousOutputValue = _result[0][count - 1]
fillHeldResult(into: &_result, value: extreme, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
return _result
}
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
import LyrebirdDSP
/// File-scope zero-fill block for RunningMin — fallback when upstream returns no channel.
private let runningMinZeroBlock: [Double] = [Double](
@@ -143,7 +143,7 @@ public enum RunningMin {
/// - trig: Reset trigger. ≤0 → >0 rising edges reset the running minimum. Defaults to `0.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public final class Control: _Base, BlockRateControlGenerator {
public var previousOutputValue: Double = 0.0
/// - Parameters:
@@ -158,17 +158,8 @@ public enum RunningMin {
add: any ValidGeneratorInput = 0.0
) {
super.init(input: input, trig: trig, mul: mul, add: add)
_setupSubBlockBuffer()
}
/// Bypass sub-block loop: the running-minimum state machine must scan the full
/// audio-rate input block exactly once per audio block.
public func calculatedSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
public func _computeSamples(
graph: SynthGraph,
@@ -203,16 +194,7 @@ public enum RunningMin {
_prevTrig = prevTrig
_initialized = initialized
var fillValue: Double = extreme
_result[0].withUnsafeMutableBufferPointer { buf in
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
vDSP_vfillD(&fillValue, base, 1, vDSP_Length(count))
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
guard count > 0 else { return _result }
previousOutputValue = _result[0][count - 1]
fillHeldResult(into: &_result, value: extreme, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
return _result
}

Some files were not shown because too many files have changed in this diff Show More