Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 56726223f6 | |||
| 8e600f3a66 | |||
| 06bdcbbe92 | |||
| 162da89319 | |||
| 9f244b1939 | |||
| 24ea32e47c | |||
| c14efe998a | |||
| 63b630b317 | |||
| 3668739d20 | |||
| 6e7f4c0076 | |||
| f8878324fd | |||
| 844dc4d9cd | |||
| 2c20b02e59 | |||
| b6fdee8bfc | |||
| 77580ee98e | |||
| ea0aa84ca7 | |||
| 3e33f09e07 | |||
| d6875da2cb | |||
| 5e6534a615 | |||
| 9ec92277de | |||
| 90dc00f323 |
@@ -1,4 +1,8 @@
|
|||||||
.build/
|
.build/
|
||||||
|
.build-linux/
|
||||||
|
.build-glibc/
|
||||||
|
.build-docker*/
|
||||||
|
build/
|
||||||
.claude/settings.local.json
|
.claude/settings.local.json
|
||||||
.claude/worktrees/
|
.claude/worktrees/
|
||||||
*.o
|
*.o
|
||||||
@@ -8,3 +12,17 @@
|
|||||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||||
xcuserdata/
|
xcuserdata/
|
||||||
*.xcuserstate
|
*.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-*/
|
||||||
|
|||||||
@@ -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_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_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_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_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. |
|
| `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`. |
|
| `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 / 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`
|
- 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`
|
- Bus memory / In / Out → `docs/engine/bus-system.md`
|
||||||
- Sample-accurate scheduling → `docs/engine/scheduling.md`
|
- Sample-accurate scheduling → `docs/engine/scheduling.md`
|
||||||
- ParallelGroup / multi-core → `docs/engine/multi-core.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`
|
- 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`
|
- `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`
|
- 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`
|
- 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`
|
- TemporalStream / language-side value generation → `Sources/Lyrebird/Lyrebird.docc/TemporalDemand.md`
|
||||||
- Polyphonic voice pool / step sequencer → `docs/tooling/routine-task.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`
|
- 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`
|
- Project scaffolding / package targets → `docs/tooling/project-system.md`, `docs/tooling/targets.md`
|
||||||
- Dev workflow / phase branches / build → `docs/tooling/workflow.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`
|
- Xcode project templates → `docs/tooling/xcode-templates.md`
|
||||||
- AUv3 plugin internals (`LyrebirdAudioUnit`, `LyrebirdAUVoicePoolBinding`, `AUInput`, preset codable, parameter slots) → `Sources/Lyrebird/Lyrebird.docc/AUv3.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**
|
**Platform / build**
|
||||||
- macOS 15+ / iOS 18+ / swift-tools 6.0 — `Synchronization.Atomic` requires macOS 15.
|
- 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`).
|
- 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`
|
**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.
|
- 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.
|
- `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.
|
- 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.
|
- `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`.
|
- 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`.
|
- `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.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.
|
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
|
## 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:
|
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`
|
- `_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.
|
- `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.
|
- `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.
|
- `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.
|
- `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.
|
- `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).
|
- `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`).
|
- `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.
|
- `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`.
|
- `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`.
|
- `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`.
|
- `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:)`
|
- `_mulAdd.applyIfNeeded(to:graph:count:)`
|
||||||
- `fillRampedResult(into:from:to:mulAdd: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`.
|
- `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(_:)`
|
- `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`)
|
- `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`).
|
- `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.
|
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
|
## Code Review
|
||||||
|
|||||||
@@ -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.
|
- **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.
|
- **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.
|
- **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.
|
- **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.
|
- **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).
|
- **Denormal hygiene** — flush denormals to zero in feedback paths (filters, delays, reverbs).
|
||||||
@@ -127,7 +127,7 @@ let package = Package(
|
|||||||
.library(name: "LyrebirdMyExtension", targets: ["LyrebirdMyExtension"]),
|
.library(name: "LyrebirdMyExtension", targets: ["LyrebirdMyExtension"]),
|
||||||
],
|
],
|
||||||
dependencies: [
|
dependencies: [
|
||||||
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"),
|
.package(url: "https://git.lyrebirdsynth.net/josh/Lyrebird", from: "1.0.0"),
|
||||||
],
|
],
|
||||||
targets: [
|
targets: [
|
||||||
.target(
|
.target(
|
||||||
|
|||||||
@@ -7,12 +7,14 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
|
|
||||||
|
// `makeDefaultAudioDriver()` selects the platform backend — Core Audio on Apple,
|
||||||
|
// ALSA on Linux (needs libasound) — so the demo builds and runs on both.
|
||||||
let engine = SynthesisEngine(
|
let engine = SynthesisEngine(
|
||||||
blockSize: 512,
|
blockSize: 512,
|
||||||
sampleRate: 44100,
|
sampleRate: 44100,
|
||||||
numOutputChannels: 2,
|
numOutputChannels: 2,
|
||||||
numInputChannels: 2,
|
numInputChannels: 2,
|
||||||
driver: CoreAudioDriver()
|
driver: makeDefaultAudioDriver()
|
||||||
)
|
)
|
||||||
|
|
||||||
do {
|
do {
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"originHash" : "c2996d6577ec0139a89be2f2d57d304047b7d5bf7f7eba2577fde9dc2fdc0b91",
|
||||||
|
"pins" : [
|
||||||
|
{
|
||||||
|
"identity" : "linenoise-swift",
|
||||||
|
"kind" : "remoteSourceControl",
|
||||||
|
"location" : "https://github.com/andybest/linenoise-swift",
|
||||||
|
"state" : {
|
||||||
|
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
|
||||||
|
"version" : "0.0.3"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"identity" : "nimble",
|
||||||
|
"kind" : "remoteSourceControl",
|
||||||
|
"location" : "https://github.com/Quick/Nimble.git",
|
||||||
|
"state" : {
|
||||||
|
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
|
||||||
|
"version" : "7.3.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"version" : 3
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
// Package.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// swift-tools-version: 6.0
|
||||||
|
import PackageDescription
|
||||||
|
|
||||||
|
// A single cross-platform GUI demo: one shared library of synths + views, and a
|
||||||
|
// thin executable entry point that bootstraps the native toolkit per platform —
|
||||||
|
// AppKit/SwiftUI on macOS, GTK4/SwiftOpenUI on Linux. The view bodies are written
|
||||||
|
// to the subset of the View DSL that both backends share, so the UI is one source.
|
||||||
|
//
|
||||||
|
// macOS: swift run LyrebirdGUIDemo (or open the thin Xcode project)
|
||||||
|
// Linux: swift run LyrebirdGUIDemo (needs libgtk-4-dev + libasound2-dev)
|
||||||
|
//
|
||||||
|
// Select the synth with LYREBIRD_DEMO=vector (default) or LYREBIRD_DEMO=sine.
|
||||||
|
let package = Package(
|
||||||
|
name: "LyrebirdGUIDemo",
|
||||||
|
platforms: [.macOS(.v15)],
|
||||||
|
products: [
|
||||||
|
.library(name: "LyrebirdGUIDemoKit", targets: ["LyrebirdGUIDemoKit"]),
|
||||||
|
.executable(name: "LyrebirdGUIDemo", targets: ["LyrebirdGUIDemo"]),
|
||||||
|
],
|
||||||
|
dependencies: [
|
||||||
|
.package(path: "../.."),
|
||||||
|
],
|
||||||
|
targets: [
|
||||||
|
.target(
|
||||||
|
name: "LyrebirdGUIDemoKit",
|
||||||
|
dependencies: [
|
||||||
|
.product(name: "Lyrebird", package: "Lyrebird"),
|
||||||
|
.product(name: "LyrebirdUI", package: "Lyrebird"),
|
||||||
|
],
|
||||||
|
path: "Sources/LyrebirdGUIDemoKit"
|
||||||
|
),
|
||||||
|
.executableTarget(
|
||||||
|
name: "LyrebirdGUIDemo",
|
||||||
|
dependencies: [
|
||||||
|
"LyrebirdGUIDemoKit",
|
||||||
|
.product(name: "Lyrebird", package: "Lyrebird"),
|
||||||
|
.product(name: "LyrebirdUI", package: "Lyrebird"),
|
||||||
|
],
|
||||||
|
path: "Sources/LyrebirdGUIDemo"
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
<!--
|
||||||
|
README.md
|
||||||
|
Lyrebird
|
||||||
|
Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
SPDX-License-Identifier: MIT
|
||||||
|
-->
|
||||||
|
|
||||||
|
# LyrebirdGUIDemo — one GUI demo, two platforms
|
||||||
|
|
||||||
|
A live-controllable synth GUI that builds and runs from a single source tree on
|
||||||
|
**macOS** (AppKit + SwiftUI) and **Linux** (GTK4 + SwiftOpenUI). It is the
|
||||||
|
cross-platform counterpart to the richer, macOS-only `LyrebirdMacOSDemo` Xcode
|
||||||
|
project.
|
||||||
|
|
||||||
|
The split follows the "mostly in a package, thin entry points" shape:
|
||||||
|
|
||||||
|
| Piece | Where | Platform |
|
||||||
|
|---|---|---|
|
||||||
|
| Synths + views | `Sources/LyrebirdGUIDemoKit/` | shared — one source |
|
||||||
|
| App bootstrap | `Sources/LyrebirdGUIDemo/main.swift` | one `#if` (AppKit vs GTK4) |
|
||||||
|
|
||||||
|
The view bodies are written to the subset of the View DSL that SwiftUI and
|
||||||
|
SwiftOpenUI share, so there is **one** body per view — not a macOS copy and a
|
||||||
|
Linux copy. Both back ends bind the same core `@UIParam` / `UIParamNode` model,
|
||||||
|
so the controls, the oscilloscope, and the CPU meters are identical.
|
||||||
|
|
||||||
|
## Run it
|
||||||
|
|
||||||
|
```bash
|
||||||
|
swift run LyrebirdGUIDemo # vector oscillator (default)
|
||||||
|
LYREBIRD_DEMO=sine swift run LyrebirdGUIDemo # stereo sine tone
|
||||||
|
```
|
||||||
|
|
||||||
|
- **macOS** — no extra setup; a native window opens with live audio via Core Audio.
|
||||||
|
- **Linux** — needs `libgtk-4-dev` (GUI) and `libasound2-dev` + a sound device
|
||||||
|
(audio). Without a sound backend the window still opens and the controls work;
|
||||||
|
there is just no sound (`isLiveAudioAvailable` reports it, and the console says so).
|
||||||
|
|
||||||
|
## Open in an IDE
|
||||||
|
|
||||||
|
- **Xcode (macOS)** — open the folder (or `Package.swift`); Xcode treats it as a
|
||||||
|
SwiftPM package. Pick the `LyrebirdGUIDemo` scheme and Run. No `.xcodeproj` to
|
||||||
|
maintain — the package *is* the project.
|
||||||
|
- **VS Code (Linux)** — open the folder with the Swift extension
|
||||||
|
(`swiftlang.swift-vscode`); it picks up `Package.swift`. Run `LyrebirdGUIDemo`
|
||||||
|
from the test/run explorer or a terminal.
|
||||||
|
|
||||||
|
## What each demo shows
|
||||||
|
|
||||||
|
- **vector** — `VectorOscillatorUI`: an XY pad crossfades four corner wavetables
|
||||||
|
(sine / saw-ish / triangle / Hanning); frequency and amplitude knobs; a live
|
||||||
|
oscilloscope and CPU-load strip.
|
||||||
|
- **sine** — `SineToneUI`: a frequency slider, amplitude and pan knobs, a level
|
||||||
|
readout, the scope and CPU strip, and a static envelope plot.
|
||||||
|
|
||||||
|
Add a synth by dropping a `SynthesizerBase` subclass and a node-based view into
|
||||||
|
`LyrebirdGUIDemoKit`, then extend `DemoSelection` and the `demoContent()` switch
|
||||||
|
in `main.swift`.
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
// main.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// Thin cross-platform entry point. The shared synths + views live in
|
||||||
|
// `LyrebirdGUIDemoKit`; this file only bootstraps the native toolkit and opens a
|
||||||
|
// window hosting the selected demo view:
|
||||||
|
//
|
||||||
|
// • macOS — AppKit `NSApplication` + `LyrebirdWindow` (SwiftUI content).
|
||||||
|
// • Linux — a GTK4 `App`/`WindowGroup` scene run by `GTK4Backend`.
|
||||||
|
//
|
||||||
|
// Run either with `swift run LyrebirdGUIDemo`. Pick the synth with
|
||||||
|
// `LYREBIRD_DEMO=vector` (default) or `LYREBIRD_DEMO=sine`.
|
||||||
|
//
|
||||||
|
// `@ViewBuilder` and the window hosts come from SwiftUI on macOS and from
|
||||||
|
// SwiftOpenUI (re-exported through `LyrebirdUI`) on Linux — hence the single
|
||||||
|
// `#if canImport(SwiftUI)` import guard.
|
||||||
|
#if canImport(SwiftUI)
|
||||||
|
import SwiftUI
|
||||||
|
#endif
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
import LyrebirdGUIDemoKit
|
||||||
|
|
||||||
|
// MARK: - Shared setup (runs on both platforms)
|
||||||
|
|
||||||
|
let selection: DemoSelection = DemoSelection.fromEnvironment()
|
||||||
|
|
||||||
|
private let demoBlockSize: Int = 512
|
||||||
|
private let demoSampleRate: Double = 44_100.0
|
||||||
|
private let demoScopeBufferSize: Int = 2048
|
||||||
|
|
||||||
|
// Oscilloscope tap on the stereo output buses. Must be set before `start()`.
|
||||||
|
let demoScope: ScopeCapture = ScopeCapture(buses: [0, 1], bufferSize: demoScopeBufferSize)
|
||||||
|
|
||||||
|
// Core Audio on Apple, ALSA on a Linux build with libasound, else a silent
|
||||||
|
// OfflineDriver. The GUI runs either way; `isLiveAudioAvailable` reports which.
|
||||||
|
let demoDriver: any AudioDriver = makeDefaultAudioDriver()
|
||||||
|
let demoEngine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: demoBlockSize,
|
||||||
|
sampleRate: demoSampleRate,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
driver: demoDriver
|
||||||
|
)
|
||||||
|
demoEngine.scopeTap = demoScope
|
||||||
|
|
||||||
|
// Both synths are cheap to build; only the selected one is added to the engine.
|
||||||
|
// Building both keeps the node extraction below branch-free (no force-unwrap).
|
||||||
|
let vectorSynth: VectorOscillatorUI = VectorOscillatorUI()
|
||||||
|
let sineSynth: SineToneUI = SineToneUI()
|
||||||
|
let activeSynth: SynthesizerBase = (selection == .vector) ? vectorSynth : sineSynth
|
||||||
|
|
||||||
|
// Extract the projected parameter nodes here, in main.swift's top-level
|
||||||
|
// `@MainActor` context: `SynthesizerBase` is `@MainActor`, so `synth.$…` is only
|
||||||
|
// reachable on the main actor. The nodes are not actor-isolated, so the
|
||||||
|
// (nonisolated, on Linux) view body can read them freely.
|
||||||
|
let vectorX: UIParamNode = vectorSynth.$x
|
||||||
|
let vectorY: UIParamNode = vectorSynth.$y
|
||||||
|
let vectorFreq: UIParamNode = vectorSynth.$frequency
|
||||||
|
let vectorAmp: UIParamNode = vectorSynth.$amplitude
|
||||||
|
|
||||||
|
let sineFreq: UIParamNode = sineSynth.$frequency
|
||||||
|
let sineAmp: UIParamNode = sineSynth.$amplitude
|
||||||
|
let sinePan: UIParamNode = sineSynth.$pan
|
||||||
|
|
||||||
|
// A static example envelope for the sine demo's envelope plot.
|
||||||
|
let demoEnvelope: Envelope = Envelope(
|
||||||
|
levels: [0.0001, 1.0, 0.6, 0.4, 0.0001],
|
||||||
|
durations: [0.05, 0.15, 0.4, 0.3],
|
||||||
|
curves: [.exponential, .exponential, .lin, .exponential],
|
||||||
|
loopNode: 2,
|
||||||
|
releaseNode: 4
|
||||||
|
)
|
||||||
|
|
||||||
|
// `SynthesisEngine` is not Sendable; the status view only reads plain CPU-load
|
||||||
|
// doubles off it, and this demo runs entirely on the UI thread, so a nonisolated
|
||||||
|
// handle is safe (mirrors the Linux UI demo).
|
||||||
|
nonisolated(unsafe) let statusEngine: SynthesisEngine = demoEngine
|
||||||
|
|
||||||
|
/// Builds the view for the active selection. `if`/`else` maps to the DSL's
|
||||||
|
/// `buildEither`, which both backends provide.
|
||||||
|
///
|
||||||
|
/// Isolation differs by backend: SwiftUI's `View` is `@MainActor`, so on macOS
|
||||||
|
/// this must be `@MainActor` to construct the view (and it is called from
|
||||||
|
/// AppKit's main-actor launch). SwiftOpenUI's `View` is nonisolated, so on Linux
|
||||||
|
/// this stays nonisolated and is callable from the nonisolated scene closure.
|
||||||
|
#if canImport(SwiftUI)
|
||||||
|
@MainActor
|
||||||
|
#endif
|
||||||
|
@ViewBuilder
|
||||||
|
func demoContent() -> some View {
|
||||||
|
if selection == .vector {
|
||||||
|
VectorOscillatorDemoView(
|
||||||
|
xNode: vectorX,
|
||||||
|
yNode: vectorY,
|
||||||
|
frequencyNode: vectorFreq,
|
||||||
|
amplitudeNode: vectorAmp,
|
||||||
|
scope: demoScope,
|
||||||
|
engine: statusEngine
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
SineToneDemoView(
|
||||||
|
frequencyNode: sineFreq,
|
||||||
|
amplitudeNode: sineAmp,
|
||||||
|
panNode: sinePan,
|
||||||
|
scope: demoScope,
|
||||||
|
engine: statusEngine,
|
||||||
|
envelope: demoEnvelope
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start the engine and add the selected synth. `engine.start()` / `add` are
|
||||||
|
// @MainActor; main.swift's top level is main-actor isolated, so these are direct
|
||||||
|
// calls. On a build with no live backend the GUI still runs (silently).
|
||||||
|
do {
|
||||||
|
try demoEngine.start()
|
||||||
|
try demoEngine.add(activeSynth)
|
||||||
|
} catch {
|
||||||
|
print("[Lyrebird] demo engine setup failed: \(error)")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !isLiveAudioAvailable {
|
||||||
|
print("[Lyrebird] no live audio backend — the controls still work, but there is no sound.")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - macOS front end (AppKit + SwiftUI)
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import AppKit
|
||||||
|
|
||||||
|
final class DemoAppDelegate: NSObject, NSApplicationDelegate {
|
||||||
|
|
||||||
|
var window: LyrebirdWindow?
|
||||||
|
|
||||||
|
func applicationDidFinishLaunching(_ notification: Notification) {
|
||||||
|
let w: LyrebirdWindow = LyrebirdWindow(
|
||||||
|
title: selection.windowTitle,
|
||||||
|
width: 380,
|
||||||
|
height: 620
|
||||||
|
)
|
||||||
|
w.open { demoContent() }
|
||||||
|
window = w
|
||||||
|
}
|
||||||
|
|
||||||
|
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
func applicationWillTerminate(_ notification: Notification) {
|
||||||
|
demoEngine.stop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MainActor.assumeIsolated {
|
||||||
|
let app: NSApplication = NSApplication.shared
|
||||||
|
app.setActivationPolicy(.regular)
|
||||||
|
let delegate: DemoAppDelegate = DemoAppDelegate()
|
||||||
|
app.delegate = delegate
|
||||||
|
app.run()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Linux front end (GTK4 + SwiftOpenUI)
|
||||||
|
|
||||||
|
#else
|
||||||
|
|
||||||
|
struct DemoApp: App {
|
||||||
|
var body: some Scene {
|
||||||
|
WindowGroup(selection.windowTitle) {
|
||||||
|
demoContent()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
GTK4Backend().run(DemoApp.self)
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
// DemoSelection.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Which synthesizer the demo runs, chosen by the `LYREBIRD_DEMO` environment
|
||||||
|
/// variable. Both front ends (AppKit on macOS, GTK4 on Linux) read the same
|
||||||
|
/// selection so one binary covers every patch.
|
||||||
|
public enum DemoSelection: String, Sendable {
|
||||||
|
|
||||||
|
/// Vector oscillator with an XY blend pad (the default).
|
||||||
|
case vector
|
||||||
|
|
||||||
|
/// Stereo sine tone with frequency / amplitude / pan controls.
|
||||||
|
case sine
|
||||||
|
|
||||||
|
/// Resolve the selection from `LYREBIRD_DEMO` (defaults to `.vector`).
|
||||||
|
public static func fromEnvironment() -> DemoSelection {
|
||||||
|
let raw: String = ProcessInfo.processInfo.environment["LYREBIRD_DEMO"]?.lowercased() ?? "vector"
|
||||||
|
return DemoSelection(rawValue: raw) ?? .vector
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Title-bar text for the window hosting this demo.
|
||||||
|
public var windowTitle: String {
|
||||||
|
switch self {
|
||||||
|
case .vector: return "Lyrebird — Vector Oscillator"
|
||||||
|
case .sine: return "Lyrebird — Sine Tone"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
// SineToneDemoView.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if canImport(SwiftUI)
|
||||||
|
import SwiftUI
|
||||||
|
#endif
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
|
||||||
|
/// Live controls for ``SineToneUI``: a frequency slider, amplitude and pan knobs,
|
||||||
|
/// a level readout, a CPU-load strip, an oscilloscope, and a static envelope plot.
|
||||||
|
///
|
||||||
|
/// Node-based for the same reason as ``VectorOscillatorDemoView`` — the body must
|
||||||
|
/// compile under both SwiftUI's `@MainActor` body and SwiftOpenUI's nonisolated one.
|
||||||
|
public struct SineToneDemoView: View {
|
||||||
|
|
||||||
|
let frequencyNode: UIParamNode
|
||||||
|
let amplitudeNode: UIParamNode
|
||||||
|
let panNode: UIParamNode
|
||||||
|
let scope: ScopeCapture
|
||||||
|
let engine: SynthesisEngine
|
||||||
|
let envelope: Envelope
|
||||||
|
|
||||||
|
public init(
|
||||||
|
frequencyNode: UIParamNode,
|
||||||
|
amplitudeNode: UIParamNode,
|
||||||
|
panNode: UIParamNode,
|
||||||
|
scope: ScopeCapture,
|
||||||
|
engine: SynthesisEngine,
|
||||||
|
envelope: Envelope
|
||||||
|
) {
|
||||||
|
self.frequencyNode = frequencyNode
|
||||||
|
self.amplitudeNode = amplitudeNode
|
||||||
|
self.panNode = panNode
|
||||||
|
self.scope = scope
|
||||||
|
self.engine = engine
|
||||||
|
self.envelope = envelope
|
||||||
|
}
|
||||||
|
|
||||||
|
public var body: some View {
|
||||||
|
VStack {
|
||||||
|
Text("Lyrebird — Sine Tone")
|
||||||
|
.font(.headline)
|
||||||
|
ParameterSlider("Frequency", node: frequencyNode, range: 440.0...880.0)
|
||||||
|
HStack {
|
||||||
|
ParameterKnob("Amplitude", node: amplitudeNode, range: 0.0...1.0)
|
||||||
|
ParameterKnob("Pan", node: panNode, range: -1.0...1.0)
|
||||||
|
ParameterLabel("Level", node: amplitudeNode, decimalPlaces: 2)
|
||||||
|
}
|
||||||
|
LyrebirdStatusView(engine: engine)
|
||||||
|
LyrebirdScopeView(capture: scope)
|
||||||
|
.frame(height: 120)
|
||||||
|
LyrebirdEnvelopeView(envelope)
|
||||||
|
}
|
||||||
|
.padding()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
// SineToneUI.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
|
/// A stereo sine tone whose frequency, amplitude, and pan are live-controllable
|
||||||
|
/// from the UI. The `@UIParam` slots are the same model both the SwiftUI (macOS)
|
||||||
|
/// and SwiftOpenUI (Linux) controls bind to — one synthesizer, two front ends.
|
||||||
|
public final class SineToneUI: SynthesizerBase {
|
||||||
|
|
||||||
|
/// Frequency in Hz. Slider range: 440–880 Hz.
|
||||||
|
@UIParam public var frequency: Double = 440.0
|
||||||
|
|
||||||
|
/// Output amplitude (linear gain). Knob range: 0–1.
|
||||||
|
@UIParam public var amplitude: Double = 0.25
|
||||||
|
|
||||||
|
/// Stereo pan position. Knob range: -1 (hard left) … 0 (center) … +1 (hard right).
|
||||||
|
@UIParam public var pan: Double = 0.0
|
||||||
|
|
||||||
|
public override init() {
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
public override func build() {
|
||||||
|
let osc: OscSin.Audio = OscSin.Audio(freq: $frequency)
|
||||||
|
output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
// VectorOscillatorDemoView.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// One platform `#if` at the import site; identical body beneath. On macOS SwiftUI
|
||||||
|
// supplies the View DSL; on Linux `LyrebirdUI` re-exports the SwiftOpenUI DSL, so
|
||||||
|
// `VStack` / `Text` / `.padding()` resolve on both. The Lyrebird controls
|
||||||
|
// (`ParameterXY`, `ParameterKnob`, …) and views live in `LyrebirdUI` on every
|
||||||
|
// platform and bind the same core `UIParamNode`s this view is handed.
|
||||||
|
#if canImport(SwiftUI)
|
||||||
|
import SwiftUI
|
||||||
|
#endif
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
|
||||||
|
/// Live controls for ``VectorOscillatorUI``: an XY blend pad, frequency and
|
||||||
|
/// amplitude knobs, a CPU-load strip, and an oscilloscope of the stereo output.
|
||||||
|
///
|
||||||
|
/// The view holds the projected `UIParamNode`s rather than the `@MainActor`
|
||||||
|
/// synthesizer, because SwiftOpenUI's `body` is nonisolated (unlike SwiftUI's).
|
||||||
|
/// The caller extracts the nodes on the main actor and hands them in; the nodes
|
||||||
|
/// themselves are not actor-isolated, so a nonisolated body reads them freely.
|
||||||
|
public struct VectorOscillatorDemoView: View {
|
||||||
|
|
||||||
|
let xNode: UIParamNode
|
||||||
|
let yNode: UIParamNode
|
||||||
|
let frequencyNode: UIParamNode
|
||||||
|
let amplitudeNode: UIParamNode
|
||||||
|
let scope: ScopeCapture
|
||||||
|
let engine: SynthesisEngine
|
||||||
|
|
||||||
|
public init(
|
||||||
|
xNode: UIParamNode,
|
||||||
|
yNode: UIParamNode,
|
||||||
|
frequencyNode: UIParamNode,
|
||||||
|
amplitudeNode: UIParamNode,
|
||||||
|
scope: ScopeCapture,
|
||||||
|
engine: SynthesisEngine
|
||||||
|
) {
|
||||||
|
self.xNode = xNode
|
||||||
|
self.yNode = yNode
|
||||||
|
self.frequencyNode = frequencyNode
|
||||||
|
self.amplitudeNode = amplitudeNode
|
||||||
|
self.scope = scope
|
||||||
|
self.engine = engine
|
||||||
|
}
|
||||||
|
|
||||||
|
public var body: some View {
|
||||||
|
VStack {
|
||||||
|
Text("Lyrebird — Vector Oscillator")
|
||||||
|
.font(.headline)
|
||||||
|
ParameterXY(
|
||||||
|
xLabel: "X (A↔B)", xNode: xNode, xRange: 0.0...1.0,
|
||||||
|
yLabel: "Y (AB↔CD)", yNode: yNode, yRange: 0.0...1.0
|
||||||
|
)
|
||||||
|
.frame(width: 240, height: 240)
|
||||||
|
HStack {
|
||||||
|
ParameterKnob("Frequency", node: frequencyNode, range: 40.0...2000.0)
|
||||||
|
ParameterKnob("Amplitude", node: amplitudeNode, range: 0.0...1.0)
|
||||||
|
ParameterLabel("Freq (Hz)", node: frequencyNode, decimalPlaces: 1)
|
||||||
|
}
|
||||||
|
LyrebirdStatusView(engine: engine)
|
||||||
|
LyrebirdScopeView(capture: scope)
|
||||||
|
.frame(height: 120)
|
||||||
|
}
|
||||||
|
.padding()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
// VectorOscillatorUI.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
|
/// A stereo vector oscillator whose XY position, frequency, and amplitude are
|
||||||
|
/// live-controllable from the UI.
|
||||||
|
///
|
||||||
|
/// Four corner wavetables are crossfaded on a 2D XY plane:
|
||||||
|
///
|
||||||
|
/// C (triangle) ── D (Hanning) (y = 1)
|
||||||
|
/// │ │
|
||||||
|
/// A (sine) ──── B (saw-ish) (y = 0)
|
||||||
|
/// x=0 x=1
|
||||||
|
///
|
||||||
|
/// Moving X blends A↔B (and C↔D); moving Y blends the AB mix into the CD mix.
|
||||||
|
public final class VectorOscillatorUI: SynthesizerBase {
|
||||||
|
|
||||||
|
/// X-axis blend position. 0 = corner A/C, 1 = corner B/D. Normalized [0, 1].
|
||||||
|
@UIParam public var x: Double = 0.5
|
||||||
|
|
||||||
|
/// Y-axis blend position. 0 = bottom (A, B), 1 = top (C, D). Normalized [0, 1].
|
||||||
|
@UIParam public var y: Double = 0.5
|
||||||
|
|
||||||
|
/// Oscillator frequency in Hz. Slider range: 40–2000 Hz.
|
||||||
|
@UIParam public var frequency: Double = 220.0
|
||||||
|
|
||||||
|
/// Output amplitude (linear gain). Knob range: 0–1.
|
||||||
|
@UIParam public var amplitude: Double = 0.25
|
||||||
|
|
||||||
|
private let bufferA: LyrebirdBuffer // corner A: sine
|
||||||
|
private let bufferB: LyrebirdBuffer // corner B: 16-partial saw-ish
|
||||||
|
private let bufferC: LyrebirdBuffer // corner C: triangle
|
||||||
|
private let bufferD: LyrebirdBuffer // corner D: Hanning window shape
|
||||||
|
|
||||||
|
public override init() {
|
||||||
|
let tableSize: Int = lyrebirdDefaultTableSize
|
||||||
|
|
||||||
|
let a: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
|
||||||
|
a.fillSine()
|
||||||
|
|
||||||
|
let b: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
|
||||||
|
b.fill(partials: 16)
|
||||||
|
|
||||||
|
let c: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
|
||||||
|
c.fillTriangle()
|
||||||
|
|
||||||
|
let d: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
|
||||||
|
d.fillHanning()
|
||||||
|
|
||||||
|
self.bufferA = a
|
||||||
|
self.bufferB = b
|
||||||
|
self.bufferC = c
|
||||||
|
self.bufferD = d
|
||||||
|
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
public override func build() {
|
||||||
|
let osc: VectorOscillator.Audio = VectorOscillator.Audio(
|
||||||
|
bufferA: bufferA,
|
||||||
|
bufferB: bufferB,
|
||||||
|
bufferC: bufferC,
|
||||||
|
bufferD: bufferD,
|
||||||
|
freq: $frequency,
|
||||||
|
x: $x,
|
||||||
|
y: $y,
|
||||||
|
mul: $amplitude
|
||||||
|
)
|
||||||
|
output(bus: 0, source: Pan2(input: osc, pan: 0.0))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,9 +7,21 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
|
|
||||||
// Output to the Desktop — triggers the NSDesktopFolderUsageDescription TCC prompt on first run.
|
// Offline render has no audio device, so this demo runs the same on macOS and Linux.
|
||||||
let outputURL = FileManager.default.homeDirectoryForCurrentUser
|
// Only the output container differs: CAF is Apple-only (it goes through `ExtAudioFile`),
|
||||||
|
// so off Apple we write the portable WAV codec instead.
|
||||||
|
#if canImport(AudioToolbox)
|
||||||
|
// Apple: CAF on the Desktop — triggers the NSDesktopFolderUsageDescription TCC prompt on first run.
|
||||||
|
let outputURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||||
.appendingPathComponent("Desktop/nrt_output.caf")
|
.appendingPathComponent("Desktop/nrt_output.caf")
|
||||||
|
let outputFormat: AudioFileFormat = .cafFloat32
|
||||||
|
#else
|
||||||
|
// Linux (and any non-Apple): WAV in the current working directory — no special-folder
|
||||||
|
// permission needed, and `WavFileWriter` is the portable encoder off Apple.
|
||||||
|
let outputURL: URL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
|
||||||
|
.appendingPathComponent("nrt_output.wav")
|
||||||
|
let outputFormat: AudioFileFormat = .wavFloat32
|
||||||
|
#endif
|
||||||
|
|
||||||
// Render parameters.
|
// Render parameters.
|
||||||
let sampleRate: Double = 48000
|
let sampleRate: Double = 48000
|
||||||
@@ -43,7 +55,7 @@ let tailDuration: Double = 0.1
|
|||||||
let lastStart = voices.map(\.start).max() ?? 0.0
|
let lastStart = voices.map(\.start).max() ?? 0.0
|
||||||
let totalDur = lastStart + interSetDelay + voiceLength + tailDuration
|
let totalDur = lastStart + interSetDelay + voiceLength + tailDuration
|
||||||
|
|
||||||
let driver = NRTDriver(outputURL: outputURL, duration: totalDur)
|
let driver = NRTDriver(outputURL: outputURL, duration: totalDur, format: outputFormat)
|
||||||
let engine = SynthesisEngine(
|
let engine = SynthesisEngine(
|
||||||
blockSize: blockSize,
|
blockSize: blockSize,
|
||||||
sampleRate: sampleRate,
|
sampleRate: sampleRate,
|
||||||
@@ -77,7 +89,7 @@ do {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
fputs("engine.schedule failed: \(error)\n", stderr)
|
FileHandle.standardError.write(Data("engine.schedule failed: \(error)\n".utf8))
|
||||||
exit(1)
|
exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,7 +99,7 @@ do {
|
|||||||
try engine.start()
|
try engine.start()
|
||||||
print("Done.")
|
print("Done.")
|
||||||
} catch {
|
} catch {
|
||||||
fputs("Render failed: \(error)\n", stderr)
|
FileHandle.standardError.write(Data("Render failed: \(error)\n".utf8))
|
||||||
exit(1)
|
exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,13 +17,15 @@ import LyrebirdSynth
|
|||||||
let quickstartDuration: Double = 5.0
|
let quickstartDuration: Double = 5.0
|
||||||
|
|
||||||
do {
|
do {
|
||||||
// The engine owns Core Audio and runs the graph on the RT thread.
|
// The engine owns the audio device and runs the graph on the RT thread.
|
||||||
|
// `makeDefaultAudioDriver()` picks the platform backend — Core Audio on Apple,
|
||||||
|
// ALSA on Linux (needs libasound) — so this demo builds and runs on both.
|
||||||
let engine = SynthesisEngine(
|
let engine = SynthesisEngine(
|
||||||
blockSize: 512,
|
blockSize: 512,
|
||||||
sampleRate: 48000,
|
sampleRate: 48000,
|
||||||
numOutputChannels: 2,
|
numOutputChannels: 2,
|
||||||
numInputChannels: 0,
|
numInputChannels: 0,
|
||||||
driver: CoreAudioDriver()
|
driver: makeDefaultAudioDriver()
|
||||||
)
|
)
|
||||||
|
|
||||||
try engine.start()
|
try engine.start()
|
||||||
@@ -39,6 +41,6 @@ do {
|
|||||||
engine.stop() // closes the device
|
engine.stop() // closes the device
|
||||||
print("Done.")
|
print("Done.")
|
||||||
} catch {
|
} catch {
|
||||||
fputs("Lyrebird quickstart failed to start: \(error)\n", stderr)
|
FileHandle.standardError.write(Data("Lyrebird quickstart failed to start: \(error)\n".utf8))
|
||||||
exit(1)
|
exit(1)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,17 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
|
|
||||||
|
/// Directory this demo writes its output files to: the Desktop on Apple (matching the
|
||||||
|
/// Xcode scheme), the current working directory elsewhere (Linux has no Desktop folder
|
||||||
|
/// to grant, and `swift run` starts from a known location).
|
||||||
|
func demoOutputDirectory() -> URL {
|
||||||
|
#if canImport(AudioToolbox)
|
||||||
|
return FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Desktop")
|
||||||
|
#else
|
||||||
|
return URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
/// Builds a multi-part Score using every DSL node type, exports MusicXML, round-trips
|
/// Builds a multi-part Score using every DSL node type, exports MusicXML, round-trips
|
||||||
/// the document, and reports render statistics.
|
/// the document, and reports render statistics.
|
||||||
///
|
///
|
||||||
@@ -58,15 +69,15 @@ final class ScoreDemo: DemoProtocol {
|
|||||||
/// Export MusicXML and print the round-trip event count. Does not interact with
|
/// Export MusicXML and print the round-trip event count. Does not interact with
|
||||||
/// the engine or schedule any voices.
|
/// the engine or schedule any voices.
|
||||||
func runDemo() {
|
func runDemo() {
|
||||||
// Step 1 — write MusicXML to Desktop.
|
// Step 1 — write MusicXML to the demo output directory.
|
||||||
let xmlURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
let xmlURL: URL = demoOutputDirectory()
|
||||||
.appendingPathComponent("Desktop/LyrebirdScoreDemo.musicxml")
|
.appendingPathComponent("LyrebirdScoreDemo.musicxml")
|
||||||
let xmlString: String = score.toMusicXMLString()
|
let xmlString: String = score.toMusicXMLString()
|
||||||
do {
|
do {
|
||||||
try xmlString.write(to: xmlURL, atomically: true, encoding: .utf8)
|
try xmlString.write(to: xmlURL, atomically: true, encoding: .utf8)
|
||||||
print("MusicXML written → \(xmlURL.path)")
|
print("MusicXML written → \(xmlURL.path)")
|
||||||
} catch {
|
} catch {
|
||||||
fputs("Failed to write MusicXML: \(error)\n", stderr)
|
FileHandle.standardError.write(Data("Failed to write MusicXML: \(error)\n".utf8))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 2 — round-trip sanity check.
|
// Step 2 — round-trip sanity check.
|
||||||
@@ -105,7 +116,7 @@ final class ScoreDemo: DemoProtocol {
|
|||||||
print("Score key (G major): \(rt.keySignature == .gMajor ? "OK" : "MISMATCH(\(rt.keySignature))")")
|
print("Score key (G major): \(rt.keySignature == .gMajor ? "OK" : "MISMATCH(\(rt.keySignature))")")
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
fputs("MusicXML round-trip failed: \(error)\n", stderr)
|
FileHandle.standardError.write(Data("MusicXML round-trip failed: \(error)\n".utf8))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 2b — sectioned showcase: multiple Sections assembled into one
|
// Step 2b — sectioned showcase: multiple Sections assembled into one
|
||||||
@@ -119,8 +130,8 @@ final class ScoreDemo: DemoProtocol {
|
|||||||
// `rehearsalMarksAsStaffText: true` option emits boxed <words> staff text
|
// `rehearsalMarksAsStaffText: true` option emits boxed <words> staff text
|
||||||
// instead, but that attaches to a staff and can collide with notation.
|
// instead, but that attaches to a staff and can collide with notation.
|
||||||
let showcase: Score = ScoreDemo.makeSectionedShowcase()
|
let showcase: Score = ScoreDemo.makeSectionedShowcase()
|
||||||
let showcaseURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
let showcaseURL: URL = demoOutputDirectory()
|
||||||
.appendingPathComponent("Desktop/LyrebirdScoreSections.musicxml")
|
.appendingPathComponent("LyrebirdScoreSections.musicxml")
|
||||||
do {
|
do {
|
||||||
try showcase.toMusicXMLString().write(to: showcaseURL, atomically: true, encoding: .utf8)
|
try showcase.toMusicXMLString().write(to: showcaseURL, atomically: true, encoding: .utf8)
|
||||||
print("Sectioned showcase written → \(showcaseURL.path)")
|
print("Sectioned showcase written → \(showcaseURL.path)")
|
||||||
@@ -132,7 +143,7 @@ final class ScoreDemo: DemoProtocol {
|
|||||||
print("Sections → rehearsal marks: \(markList)")
|
print("Sections → rehearsal marks: \(markList)")
|
||||||
print("Sectioned showcase parts: \(showcase.parts.map { $0.name }.joined(separator: ", "))")
|
print("Sectioned showcase parts: \(showcase.parts.map { $0.name }.joined(separator: ", "))")
|
||||||
} catch {
|
} catch {
|
||||||
fputs("Failed to write sectioned showcase: \(error)\n", stderr)
|
FileHandle.standardError.write(Data("Failed to write sectioned showcase: \(error)\n".utf8))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 3 — report render parameters.
|
// Step 3 — report render parameters.
|
||||||
@@ -185,7 +196,7 @@ final class ScoreDemo: DemoProtocol {
|
|||||||
try engine.schedule(voice, after: startSeconds)
|
try engine.schedule(voice, after: startSeconds)
|
||||||
scheduledCount += 1
|
scheduledCount += 1
|
||||||
} catch {
|
} catch {
|
||||||
fputs("engine.schedule failed for beat \(event.beat): \(error)\n", stderr)
|
FileHandle.standardError.write(Data("engine.schedule failed for beat \(event.beat): \(error)\n".utf8))
|
||||||
failedCount += 1
|
failedCount += 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,9 +7,16 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
|
|
||||||
// Output paths — both land on the Desktop.
|
// Audio output. CAF is Apple-only (ExtAudioFile), so off Apple we render the
|
||||||
let cafURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
// portable WAV codec; `demoOutputDirectory()` is the Desktop on Apple and the
|
||||||
.appendingPathComponent("Desktop/LyrebirdScoreDemo.caf")
|
// current working directory elsewhere (see ScoreDemo.swift).
|
||||||
|
#if canImport(AudioToolbox)
|
||||||
|
let outputFormat: AudioFileFormat = .cafFloat32
|
||||||
|
let audioURL: URL = demoOutputDirectory().appendingPathComponent("LyrebirdScoreDemo.caf")
|
||||||
|
#else
|
||||||
|
let outputFormat: AudioFileFormat = .wavFloat32
|
||||||
|
let audioURL: URL = demoOutputDirectory().appendingPathComponent("LyrebirdScoreDemo.wav")
|
||||||
|
#endif
|
||||||
|
|
||||||
// Render parameters.
|
// Render parameters.
|
||||||
let sampleRate: Double = 48000
|
let sampleRate: Double = 48000
|
||||||
@@ -23,7 +30,7 @@ let totalDuration: Double = demo.totalDuration
|
|||||||
demo.runDemo()
|
demo.runDemo()
|
||||||
|
|
||||||
// Create NRTDriver and engine.
|
// Create NRTDriver and engine.
|
||||||
let driver: NRTDriver = NRTDriver(outputURL: cafURL, duration: totalDuration)
|
let driver: NRTDriver = NRTDriver(outputURL: audioURL, duration: totalDuration, format: outputFormat)
|
||||||
let engine: SynthesisEngine = SynthesisEngine(
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
blockSize: blockSize,
|
blockSize: blockSize,
|
||||||
sampleRate: sampleRate,
|
sampleRate: sampleRate,
|
||||||
@@ -37,12 +44,12 @@ let engine: SynthesisEngine = SynthesisEngine(
|
|||||||
// isolated, so this is a plain direct call — no MainActor hop needed.
|
// isolated, so this is a plain direct call — no MainActor hop needed.
|
||||||
demo.scheduleVoices(engine: engine)
|
demo.scheduleVoices(engine: engine)
|
||||||
|
|
||||||
print(String(format: "Rendering %.2f s → %@", totalDuration, cafURL.path))
|
print(String(format: "Rendering %.2f s → %@", totalDuration, audioURL.path))
|
||||||
|
|
||||||
do {
|
do {
|
||||||
try engine.start()
|
try engine.start()
|
||||||
print("Done.")
|
print("Done.")
|
||||||
} catch {
|
} catch {
|
||||||
fputs("Render failed: \(error)\n", stderr)
|
FileHandle.standardError.write(Data("Render failed: \(error)\n".utf8))
|
||||||
exit(1)
|
exit(1)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; };
|
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; };
|
||||||
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||||
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||||
|
C8D00000000000000000041 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000040 /* Assets.xcassets */; };
|
||||||
/* End PBXBuildFile section */
|
/* End PBXBuildFile section */
|
||||||
|
|
||||||
/* Begin PBXCopyFilesBuildPhase section */
|
/* Begin PBXCopyFilesBuildPhase section */
|
||||||
@@ -36,6 +37,7 @@
|
|||||||
C8D00000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
C8D00000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||||
C8D00000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
C8D00000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||||
C8D00000000000000000009 /* LyrebirdScratch.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScratch.entitlements; sourceTree = "<group>"; };
|
C8D00000000000000000009 /* LyrebirdScratch.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScratch.entitlements; sourceTree = "<group>"; };
|
||||||
|
C8D00000000000000000040 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||||
/* End PBXFileReference section */
|
/* End PBXFileReference section */
|
||||||
|
|
||||||
/* Begin PBXFrameworksBuildPhase section */
|
/* Begin PBXFrameworksBuildPhase section */
|
||||||
@@ -74,6 +76,7 @@
|
|||||||
C8D00000000000000000008 /* AppDelegate.swift */,
|
C8D00000000000000000008 /* AppDelegate.swift */,
|
||||||
C8D00000000000000000006 /* Info.plist */,
|
C8D00000000000000000006 /* Info.plist */,
|
||||||
C8D00000000000000000009 /* LyrebirdScratch.entitlements */,
|
C8D00000000000000000009 /* LyrebirdScratch.entitlements */,
|
||||||
|
C8D00000000000000000040 /* Assets.xcassets */,
|
||||||
);
|
);
|
||||||
path = LyrebirdScratch;
|
path = LyrebirdScratch;
|
||||||
sourceTree = "<group>";
|
sourceTree = "<group>";
|
||||||
@@ -89,6 +92,7 @@
|
|||||||
C8D00000000000000000012 /* Frameworks */,
|
C8D00000000000000000012 /* Frameworks */,
|
||||||
C8D00000000000000000013 /* Resources */,
|
C8D00000000000000000013 /* Resources */,
|
||||||
C8D00000000000000000035 /* Embed Frameworks */,
|
C8D00000000000000000035 /* Embed Frameworks */,
|
||||||
|
C8D00000000000000000042 /* Bundle Lyrebird swiftmodules */,
|
||||||
);
|
);
|
||||||
buildRules = (
|
buildRules = (
|
||||||
);
|
);
|
||||||
@@ -111,7 +115,7 @@
|
|||||||
attributes = {
|
attributes = {
|
||||||
BuildIndependentTargetsInParallel = 1;
|
BuildIndependentTargetsInParallel = 1;
|
||||||
LastSwiftUpdateCheck = 1600;
|
LastSwiftUpdateCheck = 1600;
|
||||||
LastUpgradeCheck = 2620;
|
LastUpgradeCheck = 2660;
|
||||||
TargetAttributes = {
|
TargetAttributes = {
|
||||||
C8D00000000000000000014 = {
|
C8D00000000000000000014 = {
|
||||||
CreatedOnToolsVersion = 16.0;
|
CreatedOnToolsVersion = 16.0;
|
||||||
@@ -145,11 +149,30 @@
|
|||||||
isa = PBXResourcesBuildPhase;
|
isa = PBXResourcesBuildPhase;
|
||||||
buildActionMask = 2147483647;
|
buildActionMask = 2147483647;
|
||||||
files = (
|
files = (
|
||||||
|
C8D00000000000000000041 /* Assets.xcassets in Resources */,
|
||||||
);
|
);
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
};
|
};
|
||||||
/* End PBXResourcesBuildPhase section */
|
/* End PBXResourcesBuildPhase section */
|
||||||
|
|
||||||
|
/* Begin PBXShellScriptBuildPhase section */
|
||||||
|
C8D00000000000000000042 /* Bundle Lyrebird swiftmodules */ = {
|
||||||
|
isa = PBXShellScriptBuildPhase;
|
||||||
|
alwaysOutOfDate = 1;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
inputPaths = (
|
||||||
|
);
|
||||||
|
name = "Bundle Lyrebird swiftmodules";
|
||||||
|
outputPaths = (
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
shellPath = /bin/sh;
|
||||||
|
shellScript = "# Bundle the Lyrebird module artifacts into the app so the live-compile scratchpad\n# can `import LyrebirdSynth` / `import LyrebirdLiveCompile` on any machine — they\n# otherwise resolve only from BUILT_PRODUCTS_DIR / the dev source tree, both absent\n# once the .app is exported. LiveSession stages Contents/Resources/LyrebirdArtifacts\n# at launch; artifactSourceDir() / discoverSPMModuleMaps() then find them.\nset -e\nART=\"${TARGET_BUILD_DIR}/${CONTENTS_FOLDER_PATH}/Resources/LyrebirdArtifacts\"\nDEST=\"${ART}/Modules\"\n/bin/rm -rf \"${ART}\"\n/bin/mkdir -p \"${DEST}\"\n# 1. Swift module interfaces the snippet imports (+ their transitive deps).\nfor m in LyrebirdSynth LyrebirdLiveCompile LyrebirdLiveCompileUI LyrebirdGraphDSLEmbedded; do\n SRC=\"${BUILT_PRODUCTS_DIR}/${m}.swiftmodule\"\n if [ -e \"${SRC}\" ]; then /bin/cp -R \"${SRC}\" \"${DEST}/\"; fi\ndone\n# 2. LyrebirdC C-shim Clang module (LyrebirdSynth depends on it; a snippet importing\n# LyrebirdSynth needs its module map + header). The SPM source map uses a header path\n# relative to the map dir, so map + include/ copied together stay self-contained and\n# relocatable — placed at LyrebirdArtifacts/LyrebirdC.build so discoverSPMModuleMaps()\n# finds it once staged.\nCSRC=\"${SRCROOT}/../../Sources/LyrebirdC\"\nif [ -f \"${CSRC}/module.modulemap\" ]; then\n CDEST=\"${ART}/LyrebirdC.build\"\n /bin/mkdir -p \"${CDEST}\"\n /bin/cp \"${CSRC}/module.modulemap\" \"${CDEST}/\"\n [ -d \"${CSRC}/include\" ] && /bin/cp -R \"${CSRC}/include\" \"${CDEST}/\"\nfi\necho \"Bundled Lyrebird modules + LyrebirdC shim into ${ART}\"\n";
|
||||||
|
};
|
||||||
|
/* End PBXShellScriptBuildPhase section */
|
||||||
|
|
||||||
/* Begin PBXSourcesBuildPhase section */
|
/* Begin PBXSourcesBuildPhase section */
|
||||||
C8D00000000000000000011 /* Sources */ = {
|
C8D00000000000000000011 /* Sources */ = {
|
||||||
isa = PBXSourcesBuildPhase;
|
isa = PBXSourcesBuildPhase;
|
||||||
@@ -166,14 +189,16 @@
|
|||||||
C8D00000000000000000016 /* Debug */ = {
|
C8D00000000000000000016 /* Debug */ = {
|
||||||
isa = XCBuildConfiguration;
|
isa = XCBuildConfiguration;
|
||||||
buildSettings = {
|
buildSettings = {
|
||||||
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
|
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
|
||||||
AUTOMATION_APPLE_EVENTS = NO;
|
AUTOMATION_APPLE_EVENTS = NO;
|
||||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
|
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
|
||||||
CODE_SIGN_IDENTITY = "Apple Development";
|
CODE_SIGN_IDENTITY = "Apple Development";
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
COMBINE_HIDPI_IMAGES = YES;
|
COMBINE_HIDPI_IMAGES = YES;
|
||||||
|
CURRENT_PROJECT_VERSION = 2;
|
||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
|
||||||
ENABLE_HARDENED_RUNTIME = YES;
|
ENABLE_HARDENED_RUNTIME = YES;
|
||||||
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
||||||
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
|
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
|
||||||
@@ -181,12 +206,14 @@
|
|||||||
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
|
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
|
||||||
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
|
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
|
||||||
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||||
|
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||||
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||||
LD_RUNPATH_SEARCH_PATHS = (
|
LD_RUNPATH_SEARCH_PATHS = (
|
||||||
"$(inherited)",
|
"$(inherited)",
|
||||||
"@executable_path/../Frameworks",
|
"@executable_path/../Frameworks",
|
||||||
);
|
);
|
||||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||||
|
MARKETING_VERSION = 1.6.2;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||||
@@ -204,13 +231,15 @@
|
|||||||
C8D00000000000000000017 /* Release */ = {
|
C8D00000000000000000017 /* Release */ = {
|
||||||
isa = XCBuildConfiguration;
|
isa = XCBuildConfiguration;
|
||||||
buildSettings = {
|
buildSettings = {
|
||||||
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
|
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
|
||||||
AUTOMATION_APPLE_EVENTS = NO;
|
AUTOMATION_APPLE_EVENTS = NO;
|
||||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
|
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
|
||||||
CODE_SIGN_IDENTITY = "Apple Development";
|
CODE_SIGN_IDENTITY = "Apple Development";
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
COMBINE_HIDPI_IMAGES = YES;
|
COMBINE_HIDPI_IMAGES = YES;
|
||||||
|
CURRENT_PROJECT_VERSION = 2;
|
||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
|
||||||
ENABLE_HARDENED_RUNTIME = YES;
|
ENABLE_HARDENED_RUNTIME = YES;
|
||||||
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
||||||
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
|
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
|
||||||
@@ -218,12 +247,14 @@
|
|||||||
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
|
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
|
||||||
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
|
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
|
||||||
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||||
|
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||||
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||||
LD_RUNPATH_SEARCH_PATHS = (
|
LD_RUNPATH_SEARCH_PATHS = (
|
||||||
"$(inherited)",
|
"$(inherited)",
|
||||||
"@executable_path/../Frameworks",
|
"@executable_path/../Frameworks",
|
||||||
);
|
);
|
||||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||||
|
MARKETING_VERSION = 1.6.2;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||||
@@ -273,6 +304,7 @@
|
|||||||
COPY_PHASE_STRIP = NO;
|
COPY_PHASE_STRIP = NO;
|
||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||||
|
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||||
ENABLE_TESTABILITY = YES;
|
ENABLE_TESTABILITY = YES;
|
||||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||||
@@ -336,6 +368,7 @@
|
|||||||
COPY_PHASE_STRIP = NO;
|
COPY_PHASE_STRIP = NO;
|
||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||||
|
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||||
ENABLE_NS_ASSERTIONS = NO;
|
ENABLE_NS_ASSERTIONS = NO;
|
||||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"images" : [
|
||||||
|
{ "idiom" : "mac", "scale" : "1x", "size" : "16x16", "filename" : "icon_16.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "2x", "size" : "16x16", "filename" : "icon_32.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "1x", "size" : "32x32", "filename" : "icon_32.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "2x", "size" : "32x32", "filename" : "icon_64.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "1x", "size" : "128x128", "filename" : "icon_128.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "2x", "size" : "128x128", "filename" : "icon_256.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "1x", "size" : "256x256", "filename" : "icon_256.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "2x", "size" : "256x256", "filename" : "icon_512.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "1x", "size" : "512x512", "filename" : "icon_512.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "2x", "size" : "512x512", "filename" : "icon_1024.png" }
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 338 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 720 B |
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
@@ -13,14 +13,14 @@
|
|||||||
<key>CFBundlePackageType</key>
|
<key>CFBundlePackageType</key>
|
||||||
<string>APPL</string>
|
<string>APPL</string>
|
||||||
<key>CFBundleShortVersionString</key>
|
<key>CFBundleShortVersionString</key>
|
||||||
<string>1.0</string>
|
<string>1.6.3</string>
|
||||||
<key>CFBundleVersion</key>
|
<key>CFBundleVersion</key>
|
||||||
<string>1</string>
|
<string>3</string>
|
||||||
<key>LSMinimumSystemVersion</key>
|
<key>LSMinimumSystemVersion</key>
|
||||||
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
||||||
<key>NSPrincipalClass</key>
|
|
||||||
<string>NSApplication</string>
|
|
||||||
<key>NSHumanReadableCopyright</key>
|
<key>NSHumanReadableCopyright</key>
|
||||||
<string>Copyright © 2026 Realized Sound. All rights reserved.</string>
|
<string>Copyright © 2026 Realized Sound. All rights reserved.</string>
|
||||||
|
<key>NSPrincipalClass</key>
|
||||||
|
<string>NSApplication</string>
|
||||||
</dict>
|
</dict>
|
||||||
</plist>
|
</plist>
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
How to add Lyrebird to a project and scaffold the five kinds of app it supports: real-time, real-time + UI, non-real-time (offline) render, AUv3 plugin, and iOS.
|
How to add Lyrebird to a project and scaffold the five kinds of app it supports: real-time, real-time + UI, non-real-time (offline) render, AUv3 plugin, and iOS.
|
||||||
|
|
||||||
The package is hosted at <https://realizedsound.mooo.com/josh/Lyrebird>.
|
The package is hosted at <https://git.lyrebirdsynth.net/josh/Lyrebird>.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -29,7 +29,7 @@ let package = Package(
|
|||||||
name: "MyPiece",
|
name: "MyPiece",
|
||||||
platforms: [.macOS(.v15), .iOS(.v18)],
|
platforms: [.macOS(.v15), .iOS(.v18)],
|
||||||
dependencies: [
|
dependencies: [
|
||||||
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"),
|
.package(url: "https://git.lyrebirdsynth.net/josh/Lyrebird", from: "1.0.0"),
|
||||||
],
|
],
|
||||||
targets: [
|
targets: [
|
||||||
.executableTarget(
|
.executableTarget(
|
||||||
|
|||||||
@@ -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`).
|
||||||
@@ -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.
|
||||||
@@ -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
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
/// Errors raised while staging compile artifacts into Application Support.
|
/// Errors raised while staging compile artifacts into Application Support.
|
||||||
enum ArtifactStagingError: Error {
|
enum ArtifactStagingError: Error {
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
/// Handle to one successfully compiled and loaded snippet.
|
/// Handle to one successfully compiled and loaded snippet.
|
||||||
///
|
///
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
// The editor (`LyrebirdScratchView`) renders diagnostics in its
|
// The editor (`LyrebirdScratchView`) renders diagnostics in its
|
||||||
// margin gutter using `(line, column)` directly.
|
// margin gutter using `(line, column)` directly.
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
public struct Diagnostic: Equatable, Sendable {
|
public struct Diagnostic: Equatable, Sendable {
|
||||||
/// 1-based line number in the **user's** snippet body. May be `nil` when the
|
/// 1-based line number in the **user's** snippet body. May be `nil` when the
|
||||||
|
|||||||
@@ -22,7 +22,7 @@
|
|||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
public enum DiagnosticParser {
|
public enum DiagnosticParser {
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
//
|
//
|
||||||
// Severity classifier for a parsed swiftc diagnostic line.
|
// Severity classifier for a parsed swiftc diagnostic line.
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
public enum DiagnosticSeverity: String, Equatable, Sendable {
|
public enum DiagnosticSeverity: String, Equatable, Sendable {
|
||||||
case error
|
case error
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
// (line, column); build errors carry no span → `line: nil` with the message
|
// (line, column); build errors carry no span → `line: nil` with the message
|
||||||
// alone.
|
// alone.
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import LyrebirdGraphDSLEmbedded
|
import LyrebirdGraphDSLEmbedded
|
||||||
|
|
||||||
/// Maps interpreted-graph-DSL errors to editor diagnostics.
|
/// Maps interpreted-graph-DSL errors to editor diagnostics.
|
||||||
|
|||||||
@@ -6,9 +6,9 @@
|
|||||||
|
|
||||||
// LyrebirdLiveCompile
|
// 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.
|
/// One code-completion candidate returned by sourcekit-lsp.
|
||||||
public struct LSPCompletionItem: Sendable, Equatable {
|
public struct LSPCompletionItem: Sendable, Equatable {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
public enum LiveCompileError: Error, CustomStringConvertible, Equatable, Sendable {
|
public enum LiveCompileError: Error, CustomStringConvertible, Equatable, Sendable {
|
||||||
/// `xcrun -f swiftc` and the fallback paths all failed.
|
/// `xcrun -f swiftc` and the fallback paths all failed.
|
||||||
|
|||||||
@@ -9,14 +9,16 @@
|
|||||||
// `LiveCompiler.compile(source:)` shells out to `swiftc -emit-library`, then
|
// `LiveCompiler.compile(source:)` shells out to `swiftc -emit-library`, then
|
||||||
// `dlopen`s the resulting dylib and resolves the snippet entry symbol. No UI,
|
// `dlopen`s the resulting dylib and resolves the snippet entry symbol. No UI,
|
||||||
// no `SynthesisEngine` binding (those are handled by the harness and session
|
// 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
|
import Foundation
|
||||||
#if os(macOS)
|
#if canImport(Darwin)
|
||||||
import Darwin
|
import Darwin // dlopen / dlsym / dlerror
|
||||||
|
#elseif canImport(Glibc)
|
||||||
|
import Glibc // dlopen / dlsym / dlerror on Linux
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
/// Symbol the snippet preamble must export. Snippets declare:
|
/// Symbol the snippet preamble must export. Snippets declare:
|
||||||
///
|
///
|
||||||
@@ -26,10 +28,37 @@ import Darwin
|
|||||||
/// ```
|
/// ```
|
||||||
public let lyrebirdSnippetEntrySymbol: String = "lyrebird_snippet_entry"
|
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
|
/// 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 {
|
public enum LiveCompiler {
|
||||||
|
|
||||||
|
static var sharedLibraryExtension: String { livecompileSharedLibraryExtension }
|
||||||
|
|
||||||
/// Compile `source` to a dylib and resolve the snippet entry symbol.
|
/// Compile `source` to a dylib and resolve the snippet entry symbol.
|
||||||
///
|
///
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
@@ -52,7 +81,7 @@ public enum LiveCompiler {
|
|||||||
let workDir: URL = FileManager.default.temporaryDirectory
|
let workDir: URL = FileManager.default.temporaryDirectory
|
||||||
.appendingPathComponent("LyrebirdLiveCompile-\(snippetID)", isDirectory: true)
|
.appendingPathComponent("LyrebirdLiveCompile-\(snippetID)", isDirectory: true)
|
||||||
let sourcePath: String = workDir.appendingPathComponent("Snippet.swift").path
|
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 {
|
do {
|
||||||
try FileManager.default.createDirectory(
|
try FileManager.default.createDirectory(
|
||||||
@@ -112,11 +141,17 @@ public enum LiveCompiler {
|
|||||||
|
|
||||||
/// First-success search:
|
/// First-success search:
|
||||||
/// 1. `xcrun -f swiftc` (honours `DEVELOPER_DIR` and the user's active Xcode).
|
/// 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 {
|
static func findSwiftc() throws -> String {
|
||||||
if let xcrun: String = swiftcViaXcrun() {
|
if let xcrun: String = swiftcViaXcrun() {
|
||||||
return xcrun
|
return xcrun
|
||||||
}
|
}
|
||||||
|
if let onPath: String = swiftcOnPath() {
|
||||||
|
return onPath
|
||||||
|
}
|
||||||
let candidates: [String] = [
|
let candidates: [String] = [
|
||||||
"/usr/bin/swiftc",
|
"/usr/bin/swiftc",
|
||||||
"/usr/local/bin/swiftc",
|
"/usr/local/bin/swiftc",
|
||||||
@@ -128,6 +163,11 @@ public enum LiveCompiler {
|
|||||||
throw LiveCompileError.swiftcNotFound
|
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
|
/// `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.
|
/// active Xcode. `nil` when xcrun is missing or returns non-zero.
|
||||||
static func sdkPathViaXcrun() -> String? {
|
static func sdkPathViaXcrun() -> String? {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
// `CompiledSnippet` so the dylibs stay mapped — see the leak-by-design note in
|
// `CompiledSnippet` so the dylibs stay mapped — see the leak-by-design note in
|
||||||
// `CompiledSnippet.swift`.
|
// `CompiledSnippet.swift`.
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import Foundation
|
import Foundation
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
|
|
||||||
@@ -665,6 +665,13 @@ public final class LiveSession: @unchecked Sendable {
|
|||||||
for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) {
|
for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) {
|
||||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
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
|
return args
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -690,7 +697,15 @@ public final class LiveSession: @unchecked Sendable {
|
|||||||
args += ["-Xlinker", "-rpath", "-Xlinker", path.path]
|
args += ["-Xlinker", "-rpath", "-Xlinker", path.path]
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
#if os(macOS)
|
||||||
args += ["-Xlinker", "-undefined", "-Xlinker", "dynamic_lookup"]
|
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
|
return args
|
||||||
}
|
}
|
||||||
@@ -754,6 +769,44 @@ public final class LiveSession: @unchecked Sendable {
|
|||||||
return found
|
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
|
// MARK: - Build-dir discovery
|
||||||
|
|
||||||
/// Best-effort discovery of the SPM `.build/<triple>/<config>` directory
|
/// 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`
|
// (→ libLyrebirdDynamic.dylib); the module/target is `LyrebirdSynth`
|
||||||
// (LyrebirdSynth.swiftmodule). The consumer-facing `Lyrebird` product
|
// (LyrebirdSynth.swiftmodule). The consumer-facing `Lyrebird` product
|
||||||
// is static and produces no dylib, so it is not a marker here.
|
// 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 {
|
for start: URL in candidates {
|
||||||
var cur: URL = start
|
var cur: URL = start
|
||||||
for _ in 0..<maxWalk {
|
for _ in 0..<maxWalk {
|
||||||
@@ -805,7 +861,9 @@ public final class LiveSession: @unchecked Sendable {
|
|||||||
/// already resolved in the running process.
|
/// already resolved in the running process.
|
||||||
public static func hasLyrebirdDylib(in buildDir: URL) -> Bool {
|
public static func hasLyrebirdDylib(in buildDir: URL) -> Bool {
|
||||||
FileManager.default.fileExists(
|
FileManager.default.fileExists(
|
||||||
atPath: buildDir.appendingPathComponent("libLyrebirdDynamic.dylib").path
|
atPath: buildDir.appendingPathComponent(
|
||||||
|
"libLyrebirdDynamic.\(livecompileSharedLibraryExtension)"
|
||||||
|
).path
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
extension LiveSession {
|
extension LiveSession {
|
||||||
|
|
||||||
@@ -164,12 +164,30 @@ extension LiveSession {
|
|||||||
try? fm.copyItem(at: dylib, to: staging.appendingPathComponent(dylib.lastPathComponent))
|
try? fm.copyItem(at: dylib, to: staging.appendingPathComponent(dylib.lastPathComponent))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 2.5. Self-contained C-shim module dirs (`<Module>.build/` holding a
|
||||||
|
// `module.modulemap` whose header path is relative to the map — as shipped
|
||||||
|
// in the app bundle's LyrebirdArtifacts). Copy the whole dir verbatim so the
|
||||||
|
// relative header resolves at the staged location; no path rewrite needed.
|
||||||
|
// (The absolute-`umbrella header` dev-build maps are handled separately in
|
||||||
|
// step 3 — a relative-header map is skipped there, so no double-write.)
|
||||||
|
copySelfContainedModuleMapDirs(from: src, writeInto: staging)
|
||||||
|
|
||||||
// 3. C module maps + their umbrella headers. Files are written under the
|
// 3. C module maps + their umbrella headers. Files are written under the
|
||||||
// temp `staging` dir, but the umbrella path baked into each map must
|
// temp `staging` dir, but the umbrella path baked into each map must
|
||||||
// reference the FINAL `dest` (where they land after the atomic swap) —
|
// reference the FINAL `dest` (where they land after the atomic swap) —
|
||||||
// the temp dir is deleted.
|
// the temp dir is deleted.
|
||||||
stageClangModuleMaps(from: src, writeInto: staging, finalRoot: dest)
|
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
|
// Receipt: store the source stamp so the next call can skip an unchanged
|
||||||
// source.
|
// source.
|
||||||
let stampText: String = String(srcStamp.timeIntervalSince1970)
|
let stampText: String = String(srcStamp.timeIntervalSince1970)
|
||||||
@@ -210,10 +228,29 @@ extension LiveSession {
|
|||||||
includingPropertiesForKeys: nil
|
includingPropertiesForKeys: nil
|
||||||
) else { return [] }
|
) else { return [] }
|
||||||
return entries.filter {
|
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 `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).
|
/// a prior staging root (has a receipt or a `Modules/` dir).
|
||||||
private static func isReplaceableStagingDest(_ dest: URL) -> Bool {
|
private static func isReplaceableStagingDest(_ dest: URL) -> Bool {
|
||||||
@@ -232,6 +269,32 @@ extension LiveSession {
|
|||||||
/// occupy after the caller's atomic swap of `writeInto` onto `finalRoot`.
|
/// occupy after the caller's atomic swap of `writeInto` onto `finalRoot`.
|
||||||
/// Best-effort per map: a map with no resolvable umbrella header, or one that
|
/// Best-effort per map: a map with no resolvable umbrella header, or one that
|
||||||
/// fails to copy, is skipped without aborting the rest.
|
/// fails to copy, is skipped without aborting the rest.
|
||||||
|
/// Copy each `<Module>.build/` directory under `src` that holds a
|
||||||
|
/// `module.modulemap` **without** an `umbrella header` directive — i.e. a
|
||||||
|
/// self-contained map whose `header "…"` path is relative to the map's own
|
||||||
|
/// directory (as bundled in the app's `LyrebirdArtifacts`). The whole dir is
|
||||||
|
/// copied verbatim (map + adjacent headers), so the relative path resolves at
|
||||||
|
/// the staged location and `discoverSPMModuleMaps` finds the copied map. Maps
|
||||||
|
/// with an absolute `umbrella header` are left for ``stageClangModuleMaps``.
|
||||||
|
private static func copySelfContainedModuleMapDirs(from src: URL, writeInto staging: URL) {
|
||||||
|
let fm: FileManager = FileManager.default
|
||||||
|
guard let entries: [URL] = try? fm.contentsOfDirectory(
|
||||||
|
at: src,
|
||||||
|
includingPropertiesForKeys: nil
|
||||||
|
) else { return }
|
||||||
|
|
||||||
|
for buildDir: URL in entries where buildDir.pathExtension == "build" {
|
||||||
|
let map: URL = buildDir.appendingPathComponent("module.modulemap", isDirectory: false)
|
||||||
|
guard fm.fileExists(atPath: map.path),
|
||||||
|
let text: String = try? String(contentsOf: map, encoding: .utf8),
|
||||||
|
umbrellaHeaderPath(in: text) == nil // self-contained (relative header) only
|
||||||
|
else { continue }
|
||||||
|
let stagedDir: URL = staging.appendingPathComponent(buildDir.lastPathComponent, isDirectory: true)
|
||||||
|
try? fm.removeItem(at: stagedDir)
|
||||||
|
try? fm.copyItem(at: buildDir, to: stagedDir)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static func stageClangModuleMaps(from src: URL, writeInto staging: URL, finalRoot dest: URL) {
|
private static func stageClangModuleMaps(from src: URL, writeInto staging: URL, finalRoot dest: URL) {
|
||||||
let fm: FileManager = FileManager.default
|
let fm: FileManager = FileManager.default
|
||||||
guard let entries: [URL] = try? fm.contentsOfDirectory(
|
guard let entries: [URL] = try? fm.contentsOfDirectory(
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
// cases (toolchain missing, dlopen failure, etc.) pass through under
|
// cases (toolchain missing, dlopen failure, etc.) pass through under
|
||||||
// `.compilerError`.
|
// `.compilerError`.
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
|
public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
|
||||||
/// Snippet failed to compile. `diagnostics` are already line-mapped via the
|
/// 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
|
// across the Swift and DSL paths. The only difference is speed: a graph edit
|
||||||
// re-evaluates in microseconds instead of a swiftc round-trip.
|
// re-evaluates in microseconds instead of a swiftc round-trip.
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
import LyrebirdGraphDSLEmbedded
|
import LyrebirdGraphDSLEmbedded
|
||||||
|
|
||||||
|
|||||||
@@ -17,9 +17,9 @@
|
|||||||
// that file, which is what lets `import LyrebirdSynth` and the injected
|
// that file, which is what lets `import LyrebirdSynth` and the injected
|
||||||
// `context: SnippetContext` resolve for an otherwise free-standing file.
|
// `context: SnippetContext` resolve for an otherwise free-standing file.
|
||||||
//
|
//
|
||||||
// macOS only.
|
// macOS/Linux only.
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
/// Provides code completion for a live-coding editor buffer.
|
/// 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) {
|
for url: URL in LiveSession.discoverSPMModuleMaps(in: session.importPaths) {
|
||||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
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 {
|
for path: URL in session.librarySearchPaths {
|
||||||
args += ["-L", path.path]
|
args += ["-L", path.path]
|
||||||
}
|
}
|
||||||
@@ -106,8 +113,16 @@ public actor SnippetCompletionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static func sdkPath() -> String? {
|
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()
|
let p: Process = Process()
|
||||||
p.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")
|
p.executableURL = URL(fileURLWithPath: xcrunPath)
|
||||||
p.arguments = ["--show-sdk-path", "--sdk", "macosx"]
|
p.arguments = ["--show-sdk-path", "--sdk", "macosx"]
|
||||||
let out: Pipe = Pipe()
|
let out: Pipe = Pipe()
|
||||||
p.standardOutput = out
|
p.standardOutput = out
|
||||||
@@ -123,12 +138,20 @@ public actor SnippetCompletionService {
|
|||||||
/// Minimum-deployment target triple. Arch matches the running process;
|
/// Minimum-deployment target triple. Arch matches the running process;
|
||||||
/// the OS floor matches the package's `macOS 15` minimum.
|
/// the OS floor matches the package's `macOS 15` minimum.
|
||||||
private static func targetTriple() -> String {
|
private static func targetTriple() -> String {
|
||||||
|
#if os(macOS)
|
||||||
#if arch(arm64)
|
#if arch(arm64)
|
||||||
let arch: String = "arm64"
|
return "arm64-apple-macosx15.0"
|
||||||
#else
|
#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
|
#endif
|
||||||
return "\(arch)-apple-macosx15.0"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Launch sourcekit-lsp and open the (empty) document. Call once before the
|
/// 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
|
// synth that the host will track for re-evaluation cleanup, and report back via
|
||||||
// the test-friendly `reportSampleRate(_:)` / `reportMessage(_:)` helpers.
|
// the test-friendly `reportSampleRate(_:)` / `reportMessage(_:)` helpers.
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
|
|
||||||
public final class SnippetContext {
|
public final class SnippetContext {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
//
|
//
|
||||||
// C ABI signature of the snippet's exported entry point.
|
// 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
|
/// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. The host
|
||||||
/// passes a pointer to a `LiveSession` (or harness context) here; snippets need
|
/// 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
|
// from the opaque pointer the host hands in. The user's body is dropped in as
|
||||||
// the function body.
|
// the function body.
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
public enum SnippetHarness {
|
public enum SnippetHarness {
|
||||||
|
|
||||||
|
|||||||
@@ -12,9 +12,9 @@
|
|||||||
// `initialize` / `initialized`, `textDocument/didOpen` / `didChange`, and
|
// `initialize` / `initialized`, `textDocument/didOpen` / `didChange`, and
|
||||||
// `textDocument/completion`.
|
// `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
|
import Foundation
|
||||||
|
|
||||||
/// Nanoseconds in one second — for `Task.sleep`.
|
/// 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
|
/// Resolve `sourcekit-lsp` from the active toolchain via `xcrun`, falling
|
||||||
/// back to the conventional Xcode path.
|
/// back to the conventional Xcode path.
|
||||||
private static func resolveExecutable() -> URL {
|
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()
|
let xcrun: Process = Process()
|
||||||
xcrun.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")
|
xcrun.executableURL = URL(fileURLWithPath: xcrunPath)
|
||||||
xcrun.arguments = ["--find", "sourcekit-lsp"]
|
xcrun.arguments = ["--find", "sourcekit-lsp"]
|
||||||
let out: Pipe = Pipe()
|
let out: Pipe = Pipe()
|
||||||
xcrun.standardOutput = out
|
xcrun.standardOutput = out
|
||||||
|
|||||||
@@ -6,9 +6,9 @@
|
|||||||
|
|
||||||
// LyrebirdLiveCompile
|
// 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.
|
/// A failure from the `sourcekit-lsp` client.
|
||||||
public enum SourceKitLSPError: Error, CustomStringConvertible {
|
public enum SourceKitLSPError: Error, CustomStringConvertible {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
// few hundred ms after ⌘↩, then the swap lands exactly on the downbeat rather
|
// few hundred ms after ⌘↩, then the swap lands exactly on the downbeat rather
|
||||||
// than whenever the compile happened to finish.
|
// than whenever the compile happened to finish.
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import Foundation
|
import Foundation
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
|
|
||||||
|
|||||||
@@ -7,14 +7,14 @@
|
|||||||
// LyrebirdLiveCompile — snippet source formatting.
|
// LyrebirdLiveCompile — snippet source formatting.
|
||||||
//
|
//
|
||||||
// Shells out to the toolchain's `swift-format` (the same way `LiveCompiler`
|
// 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
|
// shells to `swiftc`) to pretty-print a snippet. macOS/Linux only — iOS cannot
|
||||||
// subprocesses. Writes the source to a temp file and runs `swift-format format
|
// 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
|
// <file>`, capturing stdout — avoids the write-stdin/read-stdout pipe deadlock
|
||||||
// a streaming approach risks on large output.
|
// a streaming approach risks on large output.
|
||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
/// Stateless `swift-format` wrapper.
|
/// Stateless `swift-format` wrapper.
|
||||||
public enum SwiftFormatter {
|
public enum SwiftFormatter {
|
||||||
@@ -72,14 +72,20 @@ public enum SwiftFormatter {
|
|||||||
label: "net.realizedsound.lyrebird.swift-format-drain",
|
label: "net.realizedsound.lyrebird.swift-format-drain",
|
||||||
attributes: .concurrent
|
attributes: .concurrent
|
||||||
)
|
)
|
||||||
var outData: Data = Data()
|
// Box the drained bytes in reference cells: on Linux the `DispatchQueue`
|
||||||
var errData: Data = Data()
|
// 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()
|
group.enter()
|
||||||
drainQueue.async { outData = outHandle.readDataToEndOfFile(); group.leave() }
|
drainQueue.async { outBox.data = outHandle.readDataToEndOfFile(); group.leave() }
|
||||||
group.enter()
|
group.enter()
|
||||||
drainQueue.async { errData = errHandle.readDataToEndOfFile(); group.leave() }
|
drainQueue.async { errBox.data = errHandle.readDataToEndOfFile(); group.leave() }
|
||||||
group.wait()
|
group.wait()
|
||||||
process.waitUntilExit()
|
process.waitUntilExit()
|
||||||
|
let outData: Data = outBox.data
|
||||||
|
let errData: Data = errBox.data
|
||||||
|
|
||||||
guard process.terminationStatus == 0 else {
|
guard process.terminationStatus == 0 else {
|
||||||
let stderr: String = String(data: errData, encoding: .utf8) ?? ""
|
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
|
#endif
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
/// Errors raised while formatting snippet source with `swift-format`.
|
/// Errors raised while formatting snippet source with `swift-format`.
|
||||||
public enum SwiftFormatterError: Error {
|
public enum SwiftFormatterError: Error {
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
// SwiftToolchainStatus.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#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
|
||||||
|
/// Tools). The Graph DSL mode does not need a toolchain, so a `.missing*` status is
|
||||||
|
/// a soft condition — it gates only the Swift-compile path. Produced by ``ToolchainProbe``.
|
||||||
|
public enum SwiftToolchainStatus: Equatable, Sendable {
|
||||||
|
/// `swiftc` and the macOS SDK both resolve — the Swift scratchpad can compile.
|
||||||
|
case available
|
||||||
|
/// No developer tools at all (`xcode-select -p` fails and `swiftc` is unresolved).
|
||||||
|
/// Fix: install the Command Line Tools (`xcode-select --install`) or Xcode.
|
||||||
|
case missingDeveloperTools
|
||||||
|
/// A developer directory is selected but `swiftc` could not be resolved.
|
||||||
|
/// Fix: install/repair Xcode or the Command Line Tools.
|
||||||
|
case missingSwiftc
|
||||||
|
/// `swiftc` resolves but the macOS SDK does not — usually an incomplete Xcode.
|
||||||
|
/// Fix: install a full Xcode.
|
||||||
|
case missingSDK
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
// ToolchainProbe.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS) || os(Linux)
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Detects whether a usable Swift toolchain is present, so the app can warn the user
|
||||||
|
/// (with install guidance) instead of only failing into the console on the first Run.
|
||||||
|
///
|
||||||
|
/// The resolvers are injectable so the `.missing*` branches can be unit-tested without
|
||||||
|
/// actually uninstalling the toolchain; the defaults wrap the real `LiveCompiler`
|
||||||
|
/// resolution (`xcrun -f swiftc`, `xcrun --show-sdk-path`) plus `xcode-select -p`.
|
||||||
|
///
|
||||||
|
/// **Not RT-related.** Runs `xcrun` / `xcode-select` subprocesses — call off the main
|
||||||
|
/// thread (a couple of fast execs).
|
||||||
|
public struct ToolchainProbe: Sendable {
|
||||||
|
|
||||||
|
private let swiftcResolver: @Sendable () -> String?
|
||||||
|
private let sdkResolver: @Sendable () -> String?
|
||||||
|
private let developerDirResolver: @Sendable () -> String?
|
||||||
|
|
||||||
|
/// - Parameters:
|
||||||
|
/// - swiftcResolver: Returns the `swiftc` path, or `nil` when unresolved.
|
||||||
|
/// - sdkResolver: Returns the macOS SDK path, or `nil` when unresolved.
|
||||||
|
/// - developerDirResolver: Returns the active developer dir (`xcode-select -p`),
|
||||||
|
/// or `nil` when no developer directory is configured.
|
||||||
|
public init(
|
||||||
|
swiftcResolver: @escaping @Sendable () -> String? = ToolchainProbe.defaultSwiftcResolver,
|
||||||
|
sdkResolver: @escaping @Sendable () -> String? = ToolchainProbe.defaultSDKResolver,
|
||||||
|
developerDirResolver: @escaping @Sendable () -> String? = ToolchainProbe.developerDirViaXcodeSelect
|
||||||
|
) {
|
||||||
|
self.swiftcResolver = swiftcResolver
|
||||||
|
self.sdkResolver = sdkResolver
|
||||||
|
self.developerDirResolver = developerDirResolver
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Default `swiftc` resolver — wraps the internal `LiveCompiler.findSwiftc()` so the
|
||||||
|
/// public `init` default argument does not reference internal API.
|
||||||
|
public static func defaultSwiftcResolver() -> String? { try? LiveCompiler.findSwiftc() }
|
||||||
|
|
||||||
|
/// Default macOS SDK resolver — wraps the internal `LiveCompiler.sdkPathViaXcrun()`.
|
||||||
|
public static func defaultSDKResolver() -> String? { LiveCompiler.sdkPathViaXcrun() }
|
||||||
|
|
||||||
|
/// Classify the current toolchain state.
|
||||||
|
public func status() -> SwiftToolchainStatus {
|
||||||
|
let swiftc: String? = swiftcResolver()
|
||||||
|
let sdk: String? = sdkResolver()
|
||||||
|
if swiftc != nil && sdk != nil { return .available }
|
||||||
|
if swiftc == nil {
|
||||||
|
// No swiftc: distinguish "no developer tools at all" from "tools present
|
||||||
|
// but swiftc unresolved" by whether a developer dir is configured.
|
||||||
|
return developerDirResolver() == nil ? .missingDeveloperTools : .missingSwiftc
|
||||||
|
}
|
||||||
|
// swiftc resolves but the SDK does not.
|
||||||
|
return .missingSDK
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Active developer directory via `xcode-select -p`, or `nil` when unset / xcode-select
|
||||||
|
/// is missing / returns non-zero.
|
||||||
|
public static func developerDirViaXcodeSelect() -> String? {
|
||||||
|
let xcodeSelectPath: String = "/usr/bin/xcode-select"
|
||||||
|
guard FileManager.default.isExecutableFile(atPath: xcodeSelectPath) else { return nil }
|
||||||
|
let process: Process = Process()
|
||||||
|
process.executableURL = URL(fileURLWithPath: xcodeSelectPath)
|
||||||
|
process.arguments = ["-p"]
|
||||||
|
let stdout: Pipe = Pipe()
|
||||||
|
process.standardOutput = stdout
|
||||||
|
process.standardError = FileHandle.nullDevice
|
||||||
|
do {
|
||||||
|
try process.run()
|
||||||
|
process.waitUntilExit()
|
||||||
|
} catch {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
guard process.terminationStatus == 0 else { return nil }
|
||||||
|
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
|
||||||
|
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
|
||||||
|
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
return trimmed.isEmpty ? nil : trimmed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
// from each swiftc-reported line so error rows point back at the row the user
|
// from each swiftc-reported line so error rows point back at the row the user
|
||||||
// typed.
|
// typed.
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
public struct WrappedSnippet: Equatable {
|
public struct WrappedSnippet: Equatable {
|
||||||
public let source: String
|
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,19 @@ Compile diagnostics from a failing snippet are parsed by `DiagnosticParser`
|
|||||||
and rendered beneath the editor with line numbers already remapped from the wrapped
|
and rendered beneath the editor with line numbers already remapped from the wrapped
|
||||||
source back to the user's snippet coordinates.
|
source back to the user's snippet coordinates.
|
||||||
|
|
||||||
The view is macOS-only — `LyrebirdLiveCompile` shells out to `swiftc`, which is
|
`LyrebirdScratchView` (the `NSTextView` editor described here) is macOS-only, but
|
||||||
unavailable on iOS. The nested `LiveCompile/` sub-package declares
|
the scratchpad itself runs on **Linux** too, through a GTK4 counterpart —
|
||||||
`platforms: [.macOS(.v15)]` and cannot be added to an iOS target.
|
`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
|
||||||
|
> (`ToolchainProbe`) and, if none is found, shows an alert (once per launch) with
|
||||||
|
> install guidance (Install Command Line Tools / Get Xcode). **Graph DSL mode needs no
|
||||||
|
> toolchain** — it interprets generator-graph expressions in-process — so it's the
|
||||||
|
> zero-install fallback.
|
||||||
|
|
||||||
## Hosting
|
## Hosting
|
||||||
|
|
||||||
@@ -435,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
|
interpreted and needs no compiler — and best-effort: any LSP failure yields no
|
||||||
candidates rather than an error.
|
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
|
## 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`) —
|
- Syntax highlighting is a lightweight built-in lexer (`ScratchSwiftTokenizer`) —
|
||||||
approximate by design, not a full parser. Completion (above) uses the real
|
approximate by design, not a full parser. Completion (above) uses the real
|
||||||
compiler via sourcekit-lsp; the two are independent.
|
compiler via sourcekit-lsp; the two are independent.
|
||||||
|
|||||||
@@ -39,6 +39,11 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
|||||||
mainMenu.addItem(windowMenuItem())
|
mainMenu.addItem(windowMenuItem())
|
||||||
|
|
||||||
NSApplication.shared.mainMenu = mainMenu
|
NSApplication.shared.mainMenu = mainMenu
|
||||||
|
|
||||||
|
// Launch check: if the Swift toolchain is missing, warn with install guidance
|
||||||
|
// (the Swift scratchpad needs swiftc). Fires once per launch — the probe runs
|
||||||
|
// off-main and the alert (if any) is dispatched back to the main thread.
|
||||||
|
warnIfSwiftToolchainMissing()
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: App menu
|
// MARK: App menu
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
// ToolchainAlert.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import AppKit
|
||||||
|
import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
/// User-facing text for a missing-toolchain warning. Pure/value type so the
|
||||||
|
/// status → message mapping is unit-testable without presenting a modal.
|
||||||
|
public struct ToolchainAlertContent: Equatable {
|
||||||
|
/// Alert title (the `NSAlert.messageText`).
|
||||||
|
public let title: String
|
||||||
|
/// Alert body explaining the problem and the fix (the `NSAlert.informativeText`).
|
||||||
|
public let message: String
|
||||||
|
/// Whether "Install Command Line Tools" is an appropriate remedy (it is for a
|
||||||
|
/// missing toolchain, but not for a present-but-incomplete SDK).
|
||||||
|
public let offersCommandLineToolsInstall: Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Map a toolchain status to alert content, or `nil` when nothing needs saying
|
||||||
|
/// (`.available`). Pure — no side effects.
|
||||||
|
public func toolchainAlertContent(for status: SwiftToolchainStatus) -> ToolchainAlertContent? {
|
||||||
|
let dslNote: String = " The Graph DSL mode works without a toolchain if you'd rather not install one."
|
||||||
|
switch status {
|
||||||
|
case .available:
|
||||||
|
return nil
|
||||||
|
case .missingDeveloperTools:
|
||||||
|
return ToolchainAlertContent(
|
||||||
|
title: "Swift toolchain not found",
|
||||||
|
message: "The Swift scratchpad compiles snippets with swiftc, which needs "
|
||||||
|
+ "Xcode or the Command Line Tools." + dslNote,
|
||||||
|
offersCommandLineToolsInstall: true
|
||||||
|
)
|
||||||
|
case .missingSwiftc:
|
||||||
|
return ToolchainAlertContent(
|
||||||
|
title: "Swift compiler not found",
|
||||||
|
message: "A developer directory is selected, but swiftc could not be resolved. "
|
||||||
|
+ "Install or repair Xcode or the Command Line Tools." + dslNote,
|
||||||
|
offersCommandLineToolsInstall: true
|
||||||
|
)
|
||||||
|
case .missingSDK:
|
||||||
|
return ToolchainAlertContent(
|
||||||
|
title: "macOS SDK not found",
|
||||||
|
message: "swiftc was found but the macOS SDK is missing — your Xcode may be "
|
||||||
|
+ "incomplete. Install a full Xcode." + dslNote,
|
||||||
|
offersCommandLineToolsInstall: false
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// App Store product page for Xcode.
|
||||||
|
private let xcodeAppStoreURL: String = "macappstore://apps.apple.com/app/xcode/id497799835"
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
extension LyrebirdScratchMenuController {
|
||||||
|
|
||||||
|
/// Probe for a Swift toolchain off the main thread and, if missing, present a
|
||||||
|
/// one-time warning alert with install guidance. Safe no-op when the toolchain is
|
||||||
|
/// available. Called once at launch from `installMainMenu`.
|
||||||
|
public func warnIfSwiftToolchainMissing(probe: ToolchainProbe = ToolchainProbe()) {
|
||||||
|
DispatchQueue.global(qos: .utility).async {
|
||||||
|
let status: SwiftToolchainStatus = probe.status()
|
||||||
|
guard let content: ToolchainAlertContent = toolchainAlertContent(for: status) else { return }
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
LyrebirdScratchMenuController.presentToolchainAlert(content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Present the toolchain warning as a modal `NSAlert` with install actions.
|
||||||
|
static func presentToolchainAlert(_ content: ToolchainAlertContent) {
|
||||||
|
let alert: NSAlert = NSAlert()
|
||||||
|
alert.messageText = content.title
|
||||||
|
alert.informativeText = content.message
|
||||||
|
alert.alertStyle = .warning
|
||||||
|
|
||||||
|
// Buttons are added in first→last order; NSAlert returns .alertFirstButtonReturn
|
||||||
|
// for the first, +1 for the next, etc.
|
||||||
|
let installButton: NSButton? = content.offersCommandLineToolsInstall
|
||||||
|
? alert.addButton(withTitle: "Install Command Line Tools")
|
||||||
|
: nil
|
||||||
|
let xcodeButton: NSButton = alert.addButton(withTitle: "Get Xcode")
|
||||||
|
let okButton: NSButton = alert.addButton(withTitle: "OK")
|
||||||
|
|
||||||
|
// Make OK the default (Return) so an accidental Return dismisses rather than
|
||||||
|
// launching the installer / App Store. Clearing the other buttons' key
|
||||||
|
// equivalents removes their default-button status.
|
||||||
|
installButton?.keyEquivalent = ""
|
||||||
|
xcodeButton.keyEquivalent = ""
|
||||||
|
okButton.keyEquivalent = "\r"
|
||||||
|
|
||||||
|
let response: NSApplication.ModalResponse = alert.runModal()
|
||||||
|
let firstButton: NSApplication.ModalResponse = .alertFirstButtonReturn
|
||||||
|
let secondButton: NSApplication.ModalResponse =
|
||||||
|
NSApplication.ModalResponse(rawValue: firstButton.rawValue + 1)
|
||||||
|
|
||||||
|
if content.offersCommandLineToolsInstall {
|
||||||
|
if response == firstButton {
|
||||||
|
launchCommandLineToolsInstaller()
|
||||||
|
} else if response == secondButton {
|
||||||
|
openXcodeInAppStore()
|
||||||
|
}
|
||||||
|
// third button = OK: dismiss.
|
||||||
|
} else {
|
||||||
|
if response == firstButton {
|
||||||
|
openXcodeInAppStore()
|
||||||
|
}
|
||||||
|
// second button = OK: dismiss.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Launch Apple's Command Line Tools installer (`xcode-select --install`). This
|
||||||
|
/// opens Apple's own GUI installer dialog — the app never installs silently.
|
||||||
|
private static func launchCommandLineToolsInstaller() {
|
||||||
|
let xcodeSelectPath: String = "/usr/bin/xcode-select"
|
||||||
|
// Mirror the executable-file pre-check used by the other subprocess helpers.
|
||||||
|
guard FileManager.default.isExecutableFile(atPath: xcodeSelectPath) else {
|
||||||
|
openXcodeInAppStore()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let process: Process = Process()
|
||||||
|
process.executableURL = URL(fileURLWithPath: xcodeSelectPath)
|
||||||
|
process.arguments = ["--install"]
|
||||||
|
do {
|
||||||
|
try process.run()
|
||||||
|
} catch {
|
||||||
|
// If we can't launch it, fall back to the App Store (Xcode includes the tools).
|
||||||
|
openXcodeInAppStore()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open Xcode's App Store product page.
|
||||||
|
private static func openXcodeInAppStore() {
|
||||||
|
guard let url: URL = URL(string: xcodeAppStoreURL) else { return }
|
||||||
|
NSWorkspace.shared.open(url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -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
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import Testing
|
import Testing
|
||||||
import Foundation
|
import Foundation
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import Testing
|
|||||||
import Foundation
|
import Foundation
|
||||||
@testable import LyrebirdLiveCompile
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
@Suite("DiagnosticParser")
|
@Suite("DiagnosticParser")
|
||||||
struct DiagnosticParserTests {
|
struct DiagnosticParserTests {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import Testing
|
import Testing
|
||||||
import LyrebirdGraphDSLEmbedded
|
import LyrebirdGraphDSLEmbedded
|
||||||
@testable import LyrebirdLiveCompile
|
@testable import LyrebirdLiveCompile
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import Testing
|
|||||||
import Foundation
|
import Foundation
|
||||||
@testable import LyrebirdLiveCompile
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
@Suite("LiveCompiler")
|
@Suite("LiveCompiler")
|
||||||
struct LiveCompilerTests {
|
struct LiveCompilerTests {
|
||||||
@@ -30,7 +30,11 @@ struct LiveCompilerTests {
|
|||||||
|
|
||||||
let snippet: CompiledSnippet = try LiveCompiler.compile(source: source)
|
let snippet: CompiledSnippet = try LiveCompiler.compile(source: source)
|
||||||
#expect(snippet.moduleName.hasPrefix("LBSnippet_"))
|
#expect(snippet.moduleName.hasPrefix("LBSnippet_"))
|
||||||
|
#if os(macOS)
|
||||||
#expect(snippet.dylibPath.hasSuffix(".dylib"))
|
#expect(snippet.dylibPath.hasSuffix(".dylib"))
|
||||||
|
#else
|
||||||
|
#expect(snippet.dylibPath.hasSuffix(".so"))
|
||||||
|
#endif
|
||||||
|
|
||||||
var marker: Int32 = 0
|
var marker: Int32 = 0
|
||||||
withUnsafeMutablePointer(to: &marker) { ptr in
|
withUnsafeMutablePointer(to: &marker) { ptr in
|
||||||
@@ -103,6 +107,11 @@ struct LiveCompilerTests {
|
|||||||
for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) {
|
for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) {
|
||||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
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
|
return args
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import Foundation
|
|||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
@testable import LyrebirdLiveCompile
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
@Suite("LiveSession diagnostics")
|
@Suite("LiveSession diagnostics")
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import Testing
|
import Testing
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
import LyrebirdGraphDSLEmbedded
|
import LyrebirdGraphDSLEmbedded
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import Foundation
|
|||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
@testable import LyrebirdLiveCompile
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
@Suite("LiveSession")
|
@Suite("LiveSession")
|
||||||
@@ -34,7 +34,12 @@ struct LiveSessionTests {
|
|||||||
@Test
|
@Test
|
||||||
func buildDirDiscoveryFindsLyrebirdDylib() throws {
|
func buildDirDiscoveryFindsLyrebirdDylib() throws {
|
||||||
let buildDir: URL = try #require(LiveSession.currentBuildDir())
|
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))
|
#expect(FileManager.default.fileExists(atPath: dylib.path))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import Testing
|
import Testing
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
@testable import LyrebirdLiveCompile
|
@testable import LyrebirdLiveCompile
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import Testing
|
import Testing
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
@testable import LyrebirdLiveCompile
|
@testable import LyrebirdLiveCompile
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import Testing
|
import Testing
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
@testable import LyrebirdLiveCompile
|
@testable import LyrebirdLiveCompile
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import Testing
|
import Testing
|
||||||
import Foundation
|
import Foundation
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import Testing
|
|||||||
import Foundation
|
import Foundation
|
||||||
@testable import LyrebirdLiveCompile
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
|
|
||||||
@Suite("SnippetHarness")
|
@Suite("SnippetHarness")
|
||||||
struct SnippetHarnessTests {
|
struct SnippetHarnessTests {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import Testing
|
import Testing
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
@testable import LyrebirdLiveCompile
|
@testable import LyrebirdLiveCompile
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import Testing
|
import Testing
|
||||||
import Foundation
|
import Foundation
|
||||||
@testable import LyrebirdLiveCompile
|
@testable import LyrebirdLiveCompile
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import Testing
|
import Testing
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
@testable import LyrebirdLiveCompile
|
@testable import LyrebirdLiveCompile
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS) || os(Linux)
|
||||||
import Testing
|
import Testing
|
||||||
import Foundation
|
import Foundation
|
||||||
@testable import LyrebirdLiveCompile
|
@testable import LyrebirdLiveCompile
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
// ToolchainProbeTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS) || os(Linux)
|
||||||
|
import Testing
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
@Suite("ToolchainProbe")
|
||||||
|
struct ToolchainProbeTests {
|
||||||
|
|
||||||
|
private func probe(swiftc: String?, sdk: String?, devDir: String?) -> ToolchainProbe {
|
||||||
|
ToolchainProbe(
|
||||||
|
swiftcResolver: { swiftc },
|
||||||
|
sdkResolver: { sdk },
|
||||||
|
developerDirResolver: { devDir }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("swiftc + SDK both present → available")
|
||||||
|
func availableWhenBothResolve() {
|
||||||
|
#expect(probe(swiftc: "/usr/bin/swiftc", sdk: "/SDK", devDir: "/Dev").status() == .available)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("no swiftc and no developer dir → missingDeveloperTools")
|
||||||
|
func missingDeveloperTools() {
|
||||||
|
#expect(probe(swiftc: nil, sdk: nil, devDir: nil).status() == .missingDeveloperTools)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("no swiftc but developer dir present → missingSwiftc")
|
||||||
|
func missingSwiftc() {
|
||||||
|
#expect(probe(swiftc: nil, sdk: nil, devDir: "/Dev").status() == .missingSwiftc)
|
||||||
|
// SDK value is irrelevant when swiftc is unresolved.
|
||||||
|
#expect(probe(swiftc: nil, sdk: "/SDK", devDir: "/Dev").status() == .missingSwiftc)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("swiftc present but SDK missing → missingSDK")
|
||||||
|
func missingSDK() {
|
||||||
|
#expect(probe(swiftc: "/usr/bin/swiftc", sdk: nil, devDir: "/Dev").status() == .missingSDK)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("default probe on a build machine finds developer tools")
|
||||||
|
func defaultProbeFindsDeveloperTools() {
|
||||||
|
// Any machine that can build/test this package has a developer directory, so
|
||||||
|
// the real (non-injected) resolvers must never report missingDeveloperTools —
|
||||||
|
// this smoke-tests that the default xcode-select / xcrun probes actually run.
|
||||||
|
// (Not asserting strict `.available`: a full-SDK requirement would couple the
|
||||||
|
// suite to the host's exact toolchain completeness.)
|
||||||
|
#expect(ToolchainProbe().status() != .missingDeveloperTools)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
// ToolchainAlertTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdLiveCompile
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
@Suite("ToolchainAlert content")
|
||||||
|
struct ToolchainAlertTests {
|
||||||
|
|
||||||
|
@Test("available status produces no alert content")
|
||||||
|
func availableIsNil() {
|
||||||
|
#expect(toolchainAlertContent(for: .available) == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("missing-toolchain statuses offer the Command Line Tools install")
|
||||||
|
func missingOffersCLTInstall() {
|
||||||
|
for status: SwiftToolchainStatus in [.missingDeveloperTools, .missingSwiftc] {
|
||||||
|
let content: ToolchainAlertContent? = toolchainAlertContent(for: status)
|
||||||
|
#expect(content != nil)
|
||||||
|
#expect(content?.offersCommandLineToolsInstall == true)
|
||||||
|
#expect(content?.title.isEmpty == false)
|
||||||
|
// Steers the user to the dependency-free fallback.
|
||||||
|
#expect(content?.message.contains("Graph DSL") == true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("missing-SDK does not offer CLT install (needs a full Xcode)")
|
||||||
|
func missingSDKNoCLT() {
|
||||||
|
let content: ToolchainAlertContent? = toolchainAlertContent(for: .missingSDK)
|
||||||
|
#expect(content != nil)
|
||||||
|
#expect(content?.offersCommandLineToolsInstall == false)
|
||||||
|
#expect(content?.message.contains("Xcode") == true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -10,6 +10,9 @@
|
|||||||
<FileRef
|
<FileRef
|
||||||
location = "group:Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo.xcodeproj">
|
location = "group:Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo.xcodeproj">
|
||||||
</FileRef>
|
</FileRef>
|
||||||
|
<FileRef
|
||||||
|
location = "group:Demos/LyrebirdGUIDemo">
|
||||||
|
</FileRef>
|
||||||
<FileRef
|
<FileRef
|
||||||
location = "group:Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj">
|
location = "group:Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj">
|
||||||
</FileRef>
|
</FileRef>
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
// swift-tools-version: 6.0
|
// swift-tools-version: 6.0
|
||||||
import PackageDescription
|
import PackageDescription
|
||||||
|
// ProcessInfo — read the LYREBIRD_DISABLE_ALSA opt-out below.
|
||||||
|
import Foundation
|
||||||
|
|
||||||
let package = Package(
|
let package = Package(
|
||||||
name: "Lyrebird",
|
name: "Lyrebird",
|
||||||
@@ -21,7 +23,10 @@ let package = Package(
|
|||||||
// double-registration crash fixed in Phase 167). External consumers
|
// double-registration crash fixed in Phase 167). External consumers
|
||||||
// never reference this product — they use `Lyrebird` (static) above.
|
// never reference this product — they use `Lyrebird` (static) above.
|
||||||
.library(name: "LyrebirdDynamic", type: .dynamic, targets: ["LyrebirdSynth"]),
|
.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"]),
|
.library(name: "LyrebirdGraphDSL", targets: ["LyrebirdGraphDSL"]),
|
||||||
.executable(name: "LyrebirdCLI", targets: ["LyrebirdCLI"]),
|
.executable(name: "LyrebirdCLI", targets: ["LyrebirdCLI"]),
|
||||||
],
|
],
|
||||||
@@ -58,19 +63,38 @@ let package = Package(
|
|||||||
name: "LyrebirdC",
|
name: "LyrebirdC",
|
||||||
path: "Sources/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(
|
.target(
|
||||||
// Module/target renamed `Lyrebird` → `LyrebirdSynth` (the `Lyrebird`
|
// Module/target renamed `Lyrebird` → `LyrebirdSynth` (the `Lyrebird`
|
||||||
// product above still vends it). Folder path kept as `Sources/Lyrebird`
|
// product above still vends it). Folder path kept as `Sources/Lyrebird`
|
||||||
// so the source tree and `Lyrebird.docc` catalog don't move.
|
// so the source tree and `Lyrebird.docc` catalog don't move.
|
||||||
name: "LyrebirdSynth",
|
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",
|
path: "Sources/Lyrebird",
|
||||||
linkerSettings: [
|
linkerSettings: [
|
||||||
.linkedFramework("CoreAudio"),
|
// Apple-only frameworks. Guarded with `.when(platforms:)` so a
|
||||||
.linkedFramework("AudioToolbox"),
|
// non-Apple target (Linux/Windows feasibility) does not fail at
|
||||||
.linkedFramework("Accelerate"),
|
// link-configuration time before source-level errors surface.
|
||||||
.linkedFramework("CoreMIDI"),
|
// macOS/iOS builds are unaffected.
|
||||||
.linkedFramework("AVFoundation"),
|
.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(
|
.executableTarget(
|
||||||
@@ -87,15 +111,9 @@ let package = Package(
|
|||||||
]
|
]
|
||||||
// Swift 6 language mode (Phase 202): inherits the swift-tools 6.0 default.
|
// Swift 6 language mode (Phase 202): inherits the swift-tools 6.0 default.
|
||||||
),
|
),
|
||||||
.target(
|
// NOTE: LyrebirdUI, LyrebirdUITests, and LyrebirdTests are appended after
|
||||||
name: "LyrebirdUI",
|
// the `Package(...)` initializer under `#if os(macOS)` — they need Apple
|
||||||
dependencies: [
|
// frameworks and must be absent from a native Linux/Windows manifest.
|
||||||
"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.
|
|
||||||
),
|
|
||||||
// Phase 167 — `LyrebirdLiveCompile` (and its SwiftUI host
|
// Phase 167 — `LyrebirdLiveCompile` (and its SwiftUI host
|
||||||
// `LyrebirdLiveCompileUI`) moved to the `LiveCompile/` nested SwiftPM
|
// `LyrebirdLiveCompileUI`) moved to the `LiveCompile/` nested SwiftPM
|
||||||
// package. It depends on the internal `.product(name: "LyrebirdDynamic",
|
// 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`
|
// cause of an ObjC class double-registration crash during `swift test`
|
||||||
// in the single-package layout. The consumer-facing `Lyrebird` product
|
// in the single-package layout. The consumer-facing `Lyrebird` product
|
||||||
// stays static (see products list). See `LiveCompile/Package.swift`.
|
// stays static (see products list). See `LiveCompile/Package.swift`.
|
||||||
.executableTarget(
|
// LyrebirdBenchmark micro-benchmarks Accelerate/vDSP primitives directly
|
||||||
name: "LyrebirdBenchmark",
|
// (`import Accelerate`), so it is Apple-only and appended under
|
||||||
dependencies: ["LyrebirdSynth"],
|
// `#if os(macOS)` below the initializer — otherwise `swift test` on Linux
|
||||||
path: "Sources/LyrebirdBenchmark",
|
// would try to build it and fail on the missing Accelerate module.
|
||||||
swiftSettings: [.unsafeFlags(["-O"])]
|
|
||||||
),
|
|
||||||
// Interpreted graph-DSL. Pure Swift over core `LyrebirdSynth` types —
|
// Interpreted graph-DSL. Pure Swift over core `LyrebirdSynth` types —
|
||||||
// no swiftc, no AppKit — so it is cross-platform (iOS included). The
|
// no swiftc, no AppKit — so it is cross-platform (iOS included). The
|
||||||
// `DSLBuiltin` registry it consumes is emitted by the separate
|
// `DSLBuiltin` registry it consumes is emitted by the separate
|
||||||
@@ -122,22 +138,13 @@ let package = Package(
|
|||||||
path: "Sources/LyrebirdGraphDSL"
|
path: "Sources/LyrebirdGraphDSL"
|
||||||
),
|
),
|
||||||
.testTarget(
|
.testTarget(
|
||||||
name: "LyrebirdTests",
|
name: "LyrebirdDSPTests",
|
||||||
dependencies: ["LyrebirdSynth"],
|
dependencies: ["LyrebirdDSP"],
|
||||||
path: "Tests/LyrebirdTests",
|
path: "Tests/LyrebirdDSPTests",
|
||||||
linkerSettings: [
|
linkerSettings: [
|
||||||
.linkedFramework("AudioToolbox"),
|
.linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])),
|
||||||
.linkedFramework("Accelerate"),
|
|
||||||
]
|
]
|
||||||
),
|
),
|
||||||
.testTarget(
|
|
||||||
name: "LyrebirdUITests",
|
|
||||||
dependencies: [
|
|
||||||
"LyrebirdUI",
|
|
||||||
"LyrebirdSynth",
|
|
||||||
],
|
|
||||||
path: "Tests/LyrebirdUITests"
|
|
||||||
),
|
|
||||||
.testTarget(
|
.testTarget(
|
||||||
name: "LyrebirdGraphDSLTests",
|
name: "LyrebirdGraphDSLTests",
|
||||||
dependencies: [
|
dependencies: [
|
||||||
@@ -146,8 +153,8 @@ let package = Package(
|
|||||||
],
|
],
|
||||||
path: "Tests/LyrebirdGraphDSLTests",
|
path: "Tests/LyrebirdGraphDSLTests",
|
||||||
linkerSettings: [
|
linkerSettings: [
|
||||||
.linkedFramework("AudioToolbox"),
|
.linkedFramework("AudioToolbox", .when(platforms: [.macOS, .iOS])),
|
||||||
.linkedFramework("Accelerate"),
|
.linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])),
|
||||||
]
|
]
|
||||||
),
|
),
|
||||||
.testTarget(
|
.testTarget(
|
||||||
@@ -155,5 +162,180 @@ let package = Package(
|
|||||||
dependencies: ["LyrebirdCLI"],
|
dependencies: ["LyrebirdCLI"],
|
||||||
path: "Tests/LyrebirdCLITests"
|
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
|
||||||
|
|||||||
@@ -1,14 +1,33 @@
|
|||||||
# Lyrebird
|
# 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.
|
Informed by 20+ years of SuperCollider practice, adapted to Swift idioms and a single-process architecture.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Try it — run a demo
|
||||||
|
|
||||||
|
The fastest way in is a demo project, not a snippet to copy. Each demo under [`Demos/`](Demos/) is a standalone SwiftPM package that depends on this checkout, so `swift run` from its folder builds and runs it — on **macOS** (Xcode optional) and **Linux** (VS Code optional), no project file to open:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://git.lyrebirdsynth.net/josh/Lyrebird.git
|
||||||
|
cd Lyrebird
|
||||||
|
|
||||||
|
(cd Demos/LyrebirdQuickstartDemo && swift run) # a 440 Hz sine — the shortest path to sound
|
||||||
|
(cd Demos/LyrebirdNRTDemo && swift run) # offline render → an audio file, no sound device needed
|
||||||
|
(cd Demos/LyrebirdDemo && swift run) # a fuller reverb smoke-test through your default output
|
||||||
|
```
|
||||||
|
|
||||||
|
These three run the same on macOS and Linux. Each has a `Synthesizers/` folder — drop a `SynthesizerBase` subclass in, re-run, and you are building your own voice. The GUI demos (SwiftUI on macOS/iOS; the GTK4 UI on Linux) and the full list are under [Demo projects](#demo-projects).
|
||||||
|
|
||||||
|
On Linux the live-audio demos need `libasound2-dev`; the offline NRT demo needs nothing. Full Linux setup is in the [On Linux](#on-linux--vs-code-or-any-editor-no-xcode) notes and [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## A quick taste
|
## 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
|
### Generators — compose a signal graph with operators
|
||||||
|
|
||||||
@@ -28,6 +47,42 @@ let env = EnvelopeGen.Control(envelope: Envelope(
|
|||||||
let voice = carrier * env * 0.2 // ready to route to a bus
|
let voice = carrier * env * 0.2 // ready to route to a bus
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Generators — or write your own
|
||||||
|
|
||||||
|
A Generator is an RT-safe DSP node: subclass `GeneratorBase`, conform to `AudioGenerator`, fill the inherited pre-allocated `_result` buffer, and return it. No allocation, locks, or runtime type checks on the render thread — inputs are classified once at `init`. This is a complete hard-clip distortion:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
|
/// Hard-clip distortion — clamps its input signal to ±`level`.
|
||||||
|
final class HardClip: GeneratorBase, AudioGenerator {
|
||||||
|
private let input: any ValidGeneratorInput
|
||||||
|
private let level: Double
|
||||||
|
|
||||||
|
init(input: any ValidGeneratorInput, level: Double = 0.5) {
|
||||||
|
self.input = input._resolvedInput() // resolve/classify inputs off the RT thread
|
||||||
|
self.level = level
|
||||||
|
super.init() // allocates _result: one mono channel, 512 frames
|
||||||
|
}
|
||||||
|
|
||||||
|
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||||
|
_checkCount(count) // bounds guard — no force-unwraps on the RT thread
|
||||||
|
guard let signal = input.calculatedSamples(graph: graph, count: count).first else {
|
||||||
|
return _result
|
||||||
|
}
|
||||||
|
for i in 0..<count {
|
||||||
|
_result[0][i] = max(-level, min(level, signal[i])) // clamp, in place
|
||||||
|
}
|
||||||
|
return _result // pre-allocated buffer; the engine reads it directly
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wire it like any built-in generator — operators and literals compose it the same way:
|
||||||
|
let dirty = HardClip(input: OscSin.Audio(freq: 220.0), level: 0.2) * 0.5
|
||||||
|
```
|
||||||
|
|
||||||
|
`floatValue` comes free from the `AudioGenerator` extension. A generator that also makes sense at control rate (LFOs, envelopes) uses a paired `enum Name { class Audio; class Control }` namespace instead — see [`docs/protocols/writing-generators.md`](docs/protocols/writing-generators.md) for the full guide, shared helpers, and the multi-channel rules.
|
||||||
|
|
||||||
### Synthesizers — a graph plus live parameters
|
### Synthesizers — a graph plus live parameters
|
||||||
|
|
||||||
A `SynthesizerBase` subclass owns a graph built in `build()` and exposes `@LiveParam` (atomic, RT-safe) or `@UIParam` (SwiftUI-bindable) properties. The `$name` projection injects each parameter into the graph as a smoothed control-rate node:
|
A `SynthesizerBase` subclass owns a graph built in `build()` and exposes `@LiveParam` (atomic, RT-safe) or `@UIParam` (SwiftUI-bindable) properties. The `$name` projection injects each parameter into the graph as a smoothed control-rate node:
|
||||||
@@ -128,10 +183,15 @@ The REPL is text-only and works from any project that depends on Lyrebird; the s
|
|||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
| Platform | OS | Xcode | Swift |
|
| Platform | OS | IDE | Swift |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| macOS | 15+ | 16+ | 6.0 |
|
| macOS | 15+ | Xcode 16+ | 6.0 |
|
||||||
| iOS | 18+ | 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).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -140,7 +200,7 @@ The REPL is text-only and works from any project that depends on Lyrebird; the s
|
|||||||
Add the package:
|
Add the package:
|
||||||
|
|
||||||
```
|
```
|
||||||
https://realizedsound.mooo.com/josh/Lyrebird.git
|
https://git.lyrebirdsynth.net/josh/Lyrebird.git
|
||||||
```
|
```
|
||||||
|
|
||||||
**File ▸ Add Package Dependencies…** → that URL → **Up to Next Major** from `1.0.0` → add the `Lyrebird` product (and `LyrebirdUI` for the SwiftUI controls). Write `import LyrebirdSynth` in your code (the product is `Lyrebird`; the module it vends is `LyrebirdSynth`).
|
**File ▸ Add Package Dependencies…** → that URL → **Up to Next Major** from `1.0.0` → add the `Lyrebird` product (and `LyrebirdUI` for the SwiftUI controls). Write `import LyrebirdSynth` in your code (the product is `Lyrebird`; the module it vends is `LyrebirdSynth`).
|
||||||
@@ -149,6 +209,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**.
|
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://git.lyrebirdsynth.net/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
|
## Opening in Xcode
|
||||||
@@ -163,18 +242,19 @@ xed . # opens Package.swift — Xcode auto-generates schemes for every target
|
|||||||
|
|
||||||
### Schemes
|
### Schemes
|
||||||
|
|
||||||
Workspace scheme selector exposes ten entries:
|
Workspace scheme selector exposes eleven entries:
|
||||||
|
|
||||||
| Scheme | Purpose | Platform |
|
| Scheme | Purpose | Platform |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `Lyrebird-Package` | Umbrella — builds Lyrebird + LyrebirdUI + LyrebirdLiveCompile + LyrebirdC + LyrebirdBenchmark + LyrebirdCLI, runs the test suites, launches/profiles `LyrebirdCLI` | macOS |
|
| `Lyrebird-Package` | Umbrella — builds Lyrebird + LyrebirdUI + LyrebirdLiveCompile + LyrebirdC + LyrebirdBenchmark + LyrebirdCLI, runs the test suites, launches/profiles `LyrebirdCLI` | macOS |
|
||||||
| `LyrebirdQuickstartDemo` | CLI — fastest sound: a one-oscillator `SineTone` that plays 440 Hz for 10 s and exits | macOS |
|
| `LyrebirdQuickstartDemo` | CLI — fastest sound: a one-oscillator `SineTone` that plays 440 Hz for 10 s and exits | macOS · Linux |
|
||||||
| `LyrebirdUI` | Builds the `LyrebirdUI` module only (SwiftUI parameter controls + visualisations) | macOS |
|
| `LyrebirdUI` | Builds the `LyrebirdUI` module only (SwiftUI parameter controls + visualisations) | macOS |
|
||||||
| `LyrebirdDemo` | CLI — plays through default output via `CoreAudioDriver` | macOS |
|
| `LyrebirdDemo` | CLI — plays through default output via `makeDefaultAudioDriver()` | macOS · Linux |
|
||||||
| `LyrebirdMacOSDemo` | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS |
|
| `LyrebirdMacOSDemo` | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS |
|
||||||
|
| `LyrebirdGUIDemo` | Cross-platform GUI — one shared source; SwiftUI here, GTK4 on Linux (`LYREBIRD_DEMO=vector`/`sine`) | macOS · Linux |
|
||||||
| `LyrebirdiOSDemo` | SwiftUI app — same UI via `iOSAudioDriver` (RemoteIO) | iOS |
|
| `LyrebirdiOSDemo` | SwiftUI app — same UI via `iOSAudioDriver` (RemoteIO) | iOS |
|
||||||
| `LyrebirdNRTDemo` | CLI — offline render to CAF via `NRTDriver` | macOS |
|
| `LyrebirdNRTDemo` | CLI — offline render via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
|
||||||
| `LyrebirdScoreDemo` | CLI — builds notated `Score`s (result-builder DSL), exports MusicXML, renders to CAF via `NRTDriver` | macOS |
|
| `LyrebirdScoreDemo` | CLI — builds notated `Score`s (result-builder DSL), exports MusicXML, renders via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
|
||||||
| `LyrebirdAUv3Demo` | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro, etc. Run the host app once to register the extension. | macOS |
|
| `LyrebirdAUv3Demo` | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro, etc. Run the host app once to register the extension. | macOS |
|
||||||
| `LyrebirdScratch` | Live-coding scratchpad — type Swift snippets, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
| `LyrebirdScratch` | Live-coding scratchpad — type Swift snippets, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||||
|
|
||||||
@@ -190,6 +270,35 @@ 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. |
|
| 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. |
|
| `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 CLI demo projects build and run on Linux too — each is its own package, so run it from its folder (`swift run` picks up the single executable):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
(cd Demos/LyrebirdNRTDemo && swift run) # offline render → ./nrt_output.wav (no audio device needed)
|
||||||
|
(cd Demos/LyrebirdQuickstartDemo && swift run) # a 440 Hz sine (needs libasound + a sound device)
|
||||||
|
(cd Demos/LyrebirdDemo && swift run) # reverb smoke-test through default output
|
||||||
|
(cd Demos/LyrebirdScoreDemo && swift run) # notated Score → MusicXML + a rendered WAV (no device)
|
||||||
|
(cd Demos/LyrebirdGUIDemo && swift run) # cross-platform GUI via GTK4 (needs libgtk-4-dev); LYREBIRD_DEMO=vector|sine
|
||||||
|
```
|
||||||
|
|
||||||
|
The four CLI demos plus `LyrebirdGUIDemo` (a GTK4 window here, SwiftUI on macOS) run on Linux; the AUv3 / iOS / `LyrebirdMacOSDemo` GUI demos are Apple-only. 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
|
## Building and testing from the terminal
|
||||||
@@ -200,23 +309,24 @@ swift test # run all 5481 tests
|
|||||||
swift test --filter LyrebirdTests # run one suite
|
swift test --filter LyrebirdTests # run one suite
|
||||||
swift run lyrebird # run the CLI
|
swift run lyrebird # run the CLI
|
||||||
swift run lyrebird repl # Swift REPL with Lyrebird available
|
swift run lyrebird repl # Swift REPL with Lyrebird available
|
||||||
swift run LyrebirdDemo # run the hardware smoke-test demo
|
(cd Demos/LyrebirdDemo && swift run) # run a demo project (each Demos/* is its own package)
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Demo projects
|
## Demo projects
|
||||||
|
|
||||||
All eight live in [`Demos/`](Demos/). Open via `Lyrebird.xcworkspace`.
|
All nine live in [`Demos/`](Demos/). Each is its own SwiftPM package depending on the local checkout, so a demo runs with `swift run` from its folder on **any** platform it supports — no Xcode needed. On macOS you can also open them together via `Lyrebird.xcworkspace`. The demos marked **Linux** build and run on Linux as well (see the Linux VS Code section above); `LyrebirdGUIDemo` is the cross-platform GUI — SwiftUI on macOS, GTK4 on Linux, one source.
|
||||||
|
|
||||||
| Demo | What it does | Platform |
|
| Demo | What it does | Platform |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| [`LyrebirdQuickstartDemo`](Demos/LyrebirdQuickstartDemo/) | CLI — fastest sound: a one-oscillator `SineTone` plays 440 Hz for 10 s, then exits (mirrors the `quickstart` template) | macOS |
|
| [`LyrebirdQuickstartDemo`](Demos/LyrebirdQuickstartDemo/) | CLI — fastest sound: a one-oscillator `SineTone` plays 440 Hz for 10 s, then exits (mirrors the `quickstart` template) | macOS · Linux |
|
||||||
| [`LyrebirdDemo`](Demos/LyrebirdDemo/) | CLI — plays through default output via `CoreAudioDriver` | macOS |
|
| [`LyrebirdDemo`](Demos/LyrebirdDemo/) | CLI — plays through default output via `makeDefaultAudioDriver()` (Core Audio on macOS, ALSA on Linux) | macOS · Linux |
|
||||||
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS |
|
| [`LyrebirdGUIDemo`](Demos/LyrebirdGUIDemo/) | GUI — live `@UIParam` controls, XY pad, oscilloscope, CPU meters, from one shared source; AppKit/SwiftUI on macOS, GTK4/SwiftOpenUI on Linux (`LYREBIRD_DEMO=vector`/`sine`) | macOS · Linux |
|
||||||
|
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | SwiftUI app — live oscilloscope, `@UIParam` knobs, vector / sine / spectral-bin-delay patches | macOS |
|
||||||
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | SwiftUI app — same UI system via `iOSAudioDriver` (RemoteIO) | iOS |
|
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | SwiftUI app — same UI system via `iOSAudioDriver` (RemoteIO) | iOS |
|
||||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render to CAF file via `NRTDriver` | macOS |
|
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
|
||||||
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | CLI — notated `Score` → MusicXML export + offline render to CAF via `NRTDriver` | macOS |
|
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | CLI — notated `Score` → MusicXML export + offline render via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
|
||||||
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro | macOS |
|
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro | macOS |
|
||||||
| [`LyrebirdScratch`](Demos/LyrebirdScratch/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
| [`LyrebirdScratch`](Demos/LyrebirdScratch/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||||
|
|
||||||
@@ -254,14 +364,10 @@ Arrow-key editing, tab completion, persistent history (`~/.lyrebird_history`). `
|
|||||||
|
|
||||||
Lyrebird supports out-of-tree Swift packages that add `Generator` or `Synthesizer` implementations. Extension packages depend on Lyrebird via SwiftPM, host their own source, and ship their own version releases — core users pin the version range they want.
|
Lyrebird supports out-of-tree Swift packages that add `Generator` or `Synthesizer` implementations. Extension packages depend on Lyrebird via SwiftPM, host their own source, and ship their own version releases — core users pin the version range they want.
|
||||||
|
|
||||||
| Package | Description |
|
|
||||||
|---|---|
|
|
||||||
| [`LyrebirdATK`](#) | First-order Ambisonics toolkit (37 `Foa*` UGens, MIT KEMAR HRIR set, binaural decoder). Worked example for the Extension SDK. |
|
|
||||||
|
|
||||||
Building your own extension package:
|
Building your own extension package:
|
||||||
|
|
||||||
- **API contract**: [`docs/protocols/extension-sdk.md`](docs/protocols/extension-sdk.md) — tier-1 stable public surface + tier-2 `@_spi(LyrebirdExtensions)` symbols and versioning policy.
|
- **API contract**: [`docs/protocols/extension-sdk.md`](docs/protocols/extension-sdk.md) — tier-1 stable public surface + tier-2 `@_spi(LyrebirdExtensions)` symbols and versioning policy.
|
||||||
- **Walk-through**: [`docs/extension-authors-guide.md`](docs/extension-authors-guide.md) — end-to-end build a new extension package using LyrebirdATK as the reference.
|
- **Walk-through**: [`docs/extension-authors-guide.md`](docs/extension-authors-guide.md) — end-to-end build a new extension package.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -279,6 +385,7 @@ LyrebirdII/
|
|||||||
├── Demos/
|
├── Demos/
|
||||||
│ ├── LyrebirdQuickstartDemo/ # fastest sound — SineTone plays 10 s then exits
|
│ ├── LyrebirdQuickstartDemo/ # fastest sound — SineTone plays 10 s then exits
|
||||||
│ ├── LyrebirdDemo/ # (same as Sources/LyrebirdDemo — workspace target)
|
│ ├── LyrebirdDemo/ # (same as Sources/LyrebirdDemo — workspace target)
|
||||||
|
│ ├── LyrebirdGUIDemo/ # cross-platform GUI — SwiftUI (macOS) + GTK4 (Linux), one source
|
||||||
│ ├── LyrebirdMacOSDemo/ # macOS SwiftUI app
|
│ ├── LyrebirdMacOSDemo/ # macOS SwiftUI app
|
||||||
│ ├── LyrebirdiOSDemo/ # iOS SwiftUI app
|
│ ├── LyrebirdiOSDemo/ # iOS SwiftUI app
|
||||||
│ ├── LyrebirdNRTDemo/ # offline renderer
|
│ ├── LyrebirdNRTDemo/ # offline renderer
|
||||||
|
|||||||
@@ -7,6 +7,309 @@ functionality in a backward-compatible way.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 2.3.0 — Edit-ended callback on continuous controls
|
||||||
|
|
||||||
|
A small, additive, source-compatible release. The continuous `LyrebirdUI`
|
||||||
|
controls drive their parameter node(s) continuously while dragging, which gives
|
||||||
|
a host no single "the user finished this edit" signal. This adds one.
|
||||||
|
|
||||||
|
**New — `.onEditingEnded` on the continuous controls.** `ParameterKnob`,
|
||||||
|
`ParameterSlider`, `ParameterXY`, and `MultiSlider` gain an `.onEditingEnded`
|
||||||
|
modifier (both the SwiftUI and the Linux/GTK4 variants) that fires **once per
|
||||||
|
drag gesture**, reporting the value(s) at the start and end of the drag. A host
|
||||||
|
can use it to record a single edit per gesture — an undo checkpoint, say —
|
||||||
|
instead of one per intermediate update. The payload matches each control:
|
||||||
|
`(previous, new)` doubles for the knob and slider, a pair of `(x, y)` tuples for
|
||||||
|
the XY pad, and the before/after cell-value arrays for the multi-slider.
|
||||||
|
|
||||||
|
Additive and drop-in over 2.2.x: every control's public initializer is
|
||||||
|
unchanged (the callback is attached by the modifier), so existing call sites and
|
||||||
|
DocC links are unaffected. See `docs/ui/gui-system.md` for examples.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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
|
||||||
|
modeling (consumed by the ShoeGaze 2.0 amp pedals):
|
||||||
|
|
||||||
|
- **`ToneStack`** — passive Fender/Marshall/Vox tone stack (bass/mid/treble). Models the
|
||||||
|
interactive RC network as a whole (Yeh & Smith closed form → bilinear → 3rd-order IIR), so the
|
||||||
|
controls load each other exactly as on the real amp. Model-selectable via `ToneStackModel`.
|
||||||
|
- **`TriodeStage`** — tube-style preamp gain stage: a biased asymmetric `tanh` soft-clip (grid
|
||||||
|
bias → even-harmonic warmth) evaluated at 2×/4× oversampling, with an output coupling
|
||||||
|
(DC-block) high-pass. A musically-voiced static waveshaper; a full wave-digital triode remains
|
||||||
|
future work.
|
||||||
|
- **`LSTMAmp`** + `NeuralAmpModel` — real-time neural amp-capture inference (single-layer LSTM,
|
||||||
|
GuitarML Proteus / NeuralPi topology), pure Swift, RT-safe (pre-allocated weights, no
|
||||||
|
render-thread allocation). `NeuralAmpModel` is a `Codable` weight container with a validating
|
||||||
|
decoder. An importer for external NAM `.nam` / Proteus JSON files is planned for a later release.
|
||||||
|
|
||||||
|
All three are additive; existing code is unaffected.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1.6.4 — `LookAheadLimiter` release time decoupled from look-ahead
|
||||||
|
|
||||||
|
A patch release. One backward-compatible library addition.
|
||||||
|
|
||||||
|
`LookAheadLimiter` gains a `releaseTime` parameter, independent of
|
||||||
|
`lookAheadTime`:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
LookAheadLimiter(in:maxAmplitude:lookAheadTime:releaseTime:sampleRate:)
|
||||||
|
```
|
||||||
|
|
||||||
|
Previously the gain-release one-pole coefficient was derived from
|
||||||
|
`lookAheadTime` (default 5 ms), so the release was fast enough to modulate the
|
||||||
|
gain within a single cycle of a low-frequency signal — audible as distortion on
|
||||||
|
sustained bass when the limiter was driven hard. `releaseTime` (default
|
||||||
|
`0.050`) is now a separate control, read per block from a `ValidGeneratorInput`
|
||||||
|
so it can be driven by a live parameter / knob. The look-ahead window size and
|
||||||
|
the no-overshoot ceiling guarantee are unchanged.
|
||||||
|
|
||||||
|
The new parameter has a default, so existing call sites are source-compatible.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1.6.3 — Notarization-ready `macos-ui-xcode` template
|
||||||
|
|
||||||
|
A patch release. Project-scaffolding fixes; no library API changes.
|
||||||
|
|
||||||
|
The `macos-ui-xcode` template (`lyrebird new MyApp --template macos-ui-xcode`)
|
||||||
|
now scaffolds a distributable, notarization-ready macOS performance app out of
|
||||||
|
the box:
|
||||||
|
|
||||||
|
- **Entitlements shipped and wired** — `<name>.entitlements` grants
|
||||||
|
`com.apple.security.device.audio-input` (wired via `CODE_SIGN_ENTITLEMENTS`
|
||||||
|
in both build configs), plus `NSMicrophoneUsageDescription` in `Info.plist`.
|
||||||
|
Under the Hardened Runtime (already enabled) the OS hard-kills the process the
|
||||||
|
moment the AUHAL input bus opens without these. They are harmless for
|
||||||
|
output-only synths — no permission prompt fires until input is actually used.
|
||||||
|
The app is deliberately **unsandboxed**: a live-performance app needs
|
||||||
|
unrestricted audio-device / file / MIDI / OSC access the App Sandbox gates.
|
||||||
|
|
||||||
|
- **Compiles under Swift 6** — fixed a latent actor-isolation error that kept
|
||||||
|
the generated project from building: `NoteController` (calls the engine's
|
||||||
|
`@MainActor add(_:)`) and `AppDelegate` (constructs the main-actor controller
|
||||||
|
and synth) are now `@MainActor`. Xcode app templates are excluded from the
|
||||||
|
`swift build` CI matrix, so this had never been compile-checked; it is now
|
||||||
|
verified end-to-end with `xcodebuild`.
|
||||||
|
|
||||||
|
A normal Lyrebird app needs no module-bundling: Lyrebird is statically linked
|
||||||
|
from SPM source. (The swiftmodule / `LyrebirdC` bundling in `LyrebirdScratch`,
|
||||||
|
added in 1.6.2, is unique to its runtime `swiftc` scratchpad.)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1.6.2 — Live Scratch: distributable / notarized app
|
||||||
|
|
||||||
|
A patch release. Live Scratch packaging only; no library API changes.
|
||||||
|
|
||||||
|
A notarized, moved-off-the-build-machine `LyrebirdScratch.app` could not compile
|
||||||
|
snippets — the Swift scratchpad shells out to `swiftc`, and the modules it needs
|
||||||
|
(`LyrebirdSynth`, `LyrebirdLiveCompile`, and the `LyrebirdC` C-shim they depend on)
|
||||||
|
lived only in the dev build tree. Two failures surfaced in order — `no such module
|
||||||
|
'LyrebirdSynth'`, then `missing required module 'LyrebirdC'`. Both are now fixed:
|
||||||
|
|
||||||
|
- **Swiftmodules bundled** — a build phase copies the Lyrebird `.swiftmodule`s into
|
||||||
|
`Resources/LyrebirdArtifacts/Modules` inside the app, and the live compiler adds
|
||||||
|
that directory to its import search path.
|
||||||
|
- **LyrebirdC module relocatable** — the SPM *source* `module.modulemap` (relative
|
||||||
|
header path, so map + `include/` are self-contained) is bundled into
|
||||||
|
`LyrebirdArtifacts/LyrebirdC.build/`, and staging copies relative-header module
|
||||||
|
maps verbatim so the Clang module resolves from the bundle rather than the
|
||||||
|
absolute dev path Xcode's generated map baked in.
|
||||||
|
|
||||||
|
Verified end-to-end: a snippet compile resolving modules **only** from the app
|
||||||
|
bundle typechecks clean, and the notarized app runs the Swift scratchpad on a
|
||||||
|
machine without the dev tree.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1.6.1 — Live Scratch: Swift-toolchain detection
|
||||||
|
|
||||||
|
A patch release. Live Scratch quality-of-life; no library API changes.
|
||||||
|
|
||||||
|
The Swift scratchpad compiles snippets by shelling out to `swiftc` (Xcode or the
|
||||||
|
Command Line Tools). Previously a missing toolchain only surfaced as a compile
|
||||||
|
error in the console on the first Run. Now the app **detects it at launch** and
|
||||||
|
shows an alert with actionable install guidance:
|
||||||
|
|
||||||
|
- **Install Command Line Tools** — launches Apple's own installer (`xcode-select
|
||||||
|
--install`); the app never installs anything silently.
|
||||||
|
- **Get Xcode** — opens the App Store product page.
|
||||||
|
|
||||||
|
The check is alert-only and never blocks the app: the **Graph DSL mode needs no
|
||||||
|
toolchain**, so it's the zero-install fallback. (`ToolchainProbe` classifies the
|
||||||
|
toolchain into available / missing-developer-tools / missing-swiftc / missing-SDK,
|
||||||
|
with injectable resolvers so the missing states are unit-tested without uninstalling
|
||||||
|
anything.)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 1.6.0 — Soundfile format expansion
|
## 1.6.0 — Soundfile format expansion
|
||||||
|
|
||||||
A minor release. Backward-compatible — the existing default write formats are
|
A minor release. Backward-compatible — the existing default write formats are
|
||||||
|
|||||||
@@ -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 */
|
||||||
@@ -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
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if canImport(AudioToolbox)
|
||||||
import Foundation
|
import Foundation
|
||||||
import AudioToolbox
|
import AudioToolbox
|
||||||
|
|
||||||
@@ -40,3 +41,4 @@ public struct LyrebirdAUFactoryPreset: Sendable {
|
|||||||
self.sourceSlots = sourceSlots
|
self.sourceSlots = sourceSlots
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#endif
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if canImport(AudioToolbox)
|
||||||
import Foundation
|
import Foundation
|
||||||
import AudioToolbox
|
import AudioToolbox
|
||||||
|
|
||||||
@@ -26,3 +27,4 @@ public struct LyrebirdAUParameterEntry {
|
|||||||
/// and to write new values via `_writeAtomicValue`.
|
/// and to write new values via `_writeAtomicValue`.
|
||||||
public let node: any LiveParameterValue
|
public let node: any LiveParameterValue
|
||||||
}
|
}
|
||||||
|
#endif
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if canImport(AudioToolbox)
|
||||||
import Foundation
|
import Foundation
|
||||||
import AVFoundation
|
import AVFoundation
|
||||||
import AudioToolbox
|
import AudioToolbox
|
||||||
@@ -74,3 +75,4 @@ public let lyrebirdAUParameterDefaultFlags: AudioUnitParameterOptions = [
|
|||||||
.flag_IsWritable,
|
.flag_IsWritable,
|
||||||
.flag_CanRamp,
|
.flag_CanRamp,
|
||||||
]
|
]
|
||||||
|
#endif
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if canImport(AudioToolbox)
|
||||||
import Foundation
|
import Foundation
|
||||||
import AVFoundation
|
import AVFoundation
|
||||||
import AudioToolbox
|
import AudioToolbox
|
||||||
@@ -100,3 +101,4 @@ public enum LyrebirdAUParameterMapping {
|
|||||||
return (tree, nodes)
|
return (tree, nodes)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#endif
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if canImport(AudioToolbox)
|
||||||
import Foundation
|
import Foundation
|
||||||
import AudioToolbox
|
import AudioToolbox
|
||||||
|
|
||||||
@@ -118,3 +119,4 @@ public enum LyrebirdAUPresetSourceRegistry {
|
|||||||
return _factories.keys.sorted()
|
return _factories.keys.sorted()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#endif
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if canImport(AudioToolbox)
|
||||||
import Foundation
|
import Foundation
|
||||||
import AudioToolbox
|
import AudioToolbox
|
||||||
|
|
||||||
@@ -136,3 +137,4 @@ public final class LyrebirdAUVoicePoolBinding<S: SynthesizerBase> {
|
|||||||
/// `Double(velocity) / Double(midiVelocityMax)` yields the conventional `[0,1]`
|
/// `Double(velocity) / Double(midiVelocityMax)` yields the conventional `[0,1]`
|
||||||
/// range used by `@LiveParam` amplitude parameters.
|
/// range used by `@LiveParam` amplitude parameters.
|
||||||
public let midiVelocityMax: UInt8 = 127
|
public let midiVelocityMax: UInt8 = 127
|
||||||
|
#endif
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if canImport(AudioToolbox)
|
||||||
import Foundation
|
import Foundation
|
||||||
import AVFoundation
|
import AVFoundation
|
||||||
import AudioToolbox
|
import AudioToolbox
|
||||||
@@ -721,3 +722,4 @@ public let lyrebirdAUFullStateSourcesKey: String = "sources"
|
|||||||
/// Sub-key inside the root payload that holds the per-parameter source-slot
|
/// Sub-key inside the root payload that holds the per-parameter source-slot
|
||||||
/// generator type IDs: `[paramName: presetTypeID]`.
|
/// generator type IDs: `[paramName: presetTypeID]`.
|
||||||
public let lyrebirdAUFullStateSourceTypesKey: String = "sourceTypes"
|
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, ¶ms) == 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
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if canImport(AudioToolbox)
|
||||||
import Foundation
|
import Foundation
|
||||||
import AudioToolbox
|
import AudioToolbox
|
||||||
import AVFoundation
|
import AVFoundation
|
||||||
@@ -510,3 +511,4 @@ public let auv3DriverDefaultMaxFramesToRender: Int = 1024
|
|||||||
/// the ring. Larger values give more slack for hosts that pull busses
|
/// the ring. Larger values give more slack for hosts that pull busses
|
||||||
/// asynchronously at the cost of memory.
|
/// asynchronously at the cost of memory.
|
||||||
public let auv3RingBufferHeadroomFactor: Int = 2
|
public let auv3RingBufferHeadroomFactor: Int = 2
|
||||||
|
#endif
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
#if os(macOS)
|
#if os(macOS)
|
||||||
|
#if canImport(AudioToolbox)
|
||||||
import CoreAudio
|
import CoreAudio
|
||||||
import AudioToolbox
|
import AudioToolbox
|
||||||
import Synchronization
|
import Synchronization
|
||||||
@@ -822,3 +823,4 @@ private func lyrebirdRenderCallback(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
#endif
|
#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
|
||||||
|
}
|
||||||