Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 844dc4d9cd | |||
| 2c20b02e59 | |||
| b6fdee8bfc | |||
| 77580ee98e | |||
| ea0aa84ca7 | |||
| 3e33f09e07 | |||
| d6875da2cb | |||
| 5e6534a615 | |||
| 9ec92277de | |||
| 90dc00f323 | |||
| 8eb64f883f | |||
| 62b2f5dbec |
@@ -1,4 +1,8 @@
|
||||
.build/
|
||||
.build-linux/
|
||||
.build-glibc/
|
||||
.build-docker*/
|
||||
build/
|
||||
.claude/settings.local.json
|
||||
.claude/worktrees/
|
||||
*.o
|
||||
@@ -8,3 +12,17 @@
|
||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||
xcuserdata/
|
||||
*.xcuserstate
|
||||
|
||||
# Linux container scratch build trees (docker runs with the repo mounted).
|
||||
.build-alsa/
|
||||
.build-alsa-amd64/
|
||||
.build-noalsa/
|
||||
|
||||
# Spike sub-packages build their own .build when run from their directory.
|
||||
spikes/**/.build/
|
||||
|
||||
# Local SwiftOpenUI fork clone for the @Observable GUI spike (patched, user-local).
|
||||
spikes/SwiftOpenUI/
|
||||
|
||||
# All local Docker/scratch build trees.
|
||||
.build-*/
|
||||
|
||||
@@ -12,7 +12,7 @@ Eight agents live in `~/.claude/agents/` (maintainer's source of truth) and are
|
||||
| `lyrebird_generator_agent` | **Any new Generator** — oscillator, filter, effect, noise, math operator, bus I/O. |
|
||||
| `lyrebird_engine_agent` | Engine internals — SynthesisEngine, CoreAudioDriver/iOSAudioDriver, AUHAL, SPSCQueue, ScheduledEvent, Group/ParallelGroup, RT thread architecture. |
|
||||
| `lyrebird_language_agent` | Non-RT language side — SynthesizerBase, @LiveParam, ParameterNode, LyrebirdRoutine/Task/Clock, Pattern, MIDI, OSC, NRT, Score, demand pattern usage. |
|
||||
| `lyrebird_swiftui_agent` | LyrebirdUI module — @UIParam, ParameterKnob/Slider/XY/Button/Label, scope/envelope views, platform-conditional code. |
|
||||
| `lyrebird_swiftui_agent` | LyrebirdUI module — ParameterKnob/Slider/XY/Button/Label, scope/envelope views, platform-conditional code. (@UIParam/UIParamNode themselves live in core `Lyrebird`.) |
|
||||
| `lyrebird_architect_agent` | Cross-cutting analysis — duplicate patterns, API consistency, SC naming alignment, refactor planning. **No implementation.** |
|
||||
| `lyrebird_review_agent` | Pre-merge review (via `/lyrebird_review`) — RT safety, bus rules, protocol correctness, helper usage, test coverage. |
|
||||
| `pr_review_agent` | General pre-PR review — bugs, security, code smells. Broader scope than `lyrebird_review`. |
|
||||
@@ -52,6 +52,8 @@ These guards catch classes of regression that **`swift build` / `swift test` str
|
||||
|
||||
**Engine / RT core**
|
||||
- Engine init, audio driver, render pass → `docs/engine/synthesis-engine.md`, `docs/engine/core-audio-driver.md`, `docs/signal-flow/signal-flow.md`
|
||||
- Linux live audio (`ALSAAudioDriver`, `makeDefaultAudioDriver()`, libasound build requirement) → `docs/engine/alsa-audio-driver.md`
|
||||
- Portable WAV read/write off Apple (`WavFileWriter` / `WavFileReader`, header layout, `WavFileError`) → `docs/engine/portable-wav-codec.md`
|
||||
- Bus memory / In / Out → `docs/engine/bus-system.md`
|
||||
- Sample-accurate scheduling → `docs/engine/scheduling.md`
|
||||
- ParallelGroup / multi-core → `docs/engine/multi-core.md`
|
||||
@@ -75,6 +77,8 @@ These guards catch classes of regression that **`swift build` / `swift test` str
|
||||
- Routines / tasks / clock / MIDI / OSC → `docs/tooling/routine-task.md`
|
||||
- `Pattern<T>` factory catalog (sequence, series, geometric, uniformRandom, brownian, gaussian, cauchy, beta, shuffle, nonRepeatingRandom, weightedRandom, closure, repeating, limit, drop, stutter, switching, concatenate, roundRobin, tuple, interleave, map, filter, reject, accumulate, difference, wrap, clip, round, smooth) → `docs/tooling/routine-task.md` (§ Pattern Factory Reference) + `Sources/Lyrebird/Lyrebird.docc/RoutineTask.md`
|
||||
- MIDI clock sync (`MIDIClockFollower`) → `docs/tooling/midi-clock-sync.md`
|
||||
- Linux MIDI (`MIDI` via ALSA sequencer — `MIDI/ALSAMIDI.swift`, `ALSASeqMIDIEvent` mapping; needs CALSA/libasound) → `Sources/Lyrebird/MIDI/ALSAMIDI.swift`
|
||||
- Linux OSC (`OSCClient` / `OSCServer` POSIX-UDP transport off Apple, `OSCServerError`; codec unchanged) → `Sources/Lyrebird/OSC/OSCServer.swift`
|
||||
- Non-RT parameter value sources / `ValueComputable` / `ValueComputableClosure` (consumed by `LyrebirdProcess` parameters) → `Sources/Lyrebird/Lyrebird.docc/ValueComputable.md`
|
||||
- TemporalStream / language-side value generation → `Sources/Lyrebird/Lyrebird.docc/TemporalDemand.md`
|
||||
- Polyphonic voice pool / step sequencer → `docs/tooling/routine-task.md`
|
||||
@@ -87,6 +91,7 @@ These guards catch classes of regression that **`swift build` / `swift test` str
|
||||
- CLI / REPL / hot-swap → `docs/tooling/cli-guide.md`, `docs/tooling/repl.md`
|
||||
- Project scaffolding / package targets → `docs/tooling/project-system.md`, `docs/tooling/targets.md`
|
||||
- Dev workflow / phase branches / build → `docs/tooling/workflow.md`
|
||||
- Linux user setup (toolchain, VS Code, build/test, run a sample) → `docs/linux-getting-started.md`
|
||||
- Xcode project templates → `docs/tooling/xcode-templates.md`
|
||||
- AUv3 plugin internals (`LyrebirdAudioUnit`, `LyrebirdAUVoicePoolBinding`, `AUInput`, preset codable, parameter slots) → `Sources/Lyrebird/Lyrebird.docc/AUv3.md`
|
||||
|
||||
@@ -109,7 +114,8 @@ One-liners. Detail and rationale lives in linked docs.
|
||||
|
||||
**Platform / build**
|
||||
- macOS 15+ / iOS 18+ / swift-tools 6.0 — `Synchronization.Atomic` requires macOS 15.
|
||||
- No AVAudioEngine. Use `kAudioUnitSubType_HALOutput` (full duplex AUHAL) on macOS, RemoteIO on iOS.
|
||||
- No AVAudioEngine. Use `kAudioUnitSubType_HALOutput` (full duplex AUHAL) on macOS, RemoteIO on iOS, blocking `snd_pcm_writei` on a dedicated thread (ALSA) on Linux.
|
||||
- Never name a concrete driver in code that is meant to build on more than one platform — call `makeDefaultAudioDriver()`. Which drivers exist depends on how Lyrebird itself was built (a Linux build without libasound, or one cross-compiled from macOS, has no `ALSAAudioDriver`), so a consumer-side `#if` is a guess. Code already locked to one platform is exempt and should name its driver directly — e.g. the AppKit-only `ui-demo` scaffold template emits `CoreAudioDriver()`.
|
||||
- No Xcode Playgrounds. All tests use Swift Testing (`@Test`, `#expect`, `@Suite`).
|
||||
|
||||
**RT thread (render callback)** — `docs/engine/synthesis-engine.md`, `docs/protocols/writing-generators.md`
|
||||
@@ -193,6 +199,8 @@ Throws `EngineAddError`: `.boundToOtherEngine(current:prior:)` (cross-engine), `
|
||||
|
||||
`engine.remove(_:)` and `engine.remove(_:at:)` still return `Bool` — they unbind synchronously on successful enqueue. Documented constraint: allow one `processBlock` between `remove` and re-add of the same instance.
|
||||
|
||||
`engine.stop()` also unbinds every non-persistent synth it was hosting (including ones nested inside drained `Group` subtrees) as part of its node-tree teardown, so a stop-then-re-add of the same instance — to the same engine or a different one — needs no such wait; the RT thread is already halted before `stop()`'s unbind pass runs. See `docs/engine/synthesis-engine.md` § `stop()` node-tree teardown contract.
|
||||
|
||||
Call-site pattern: every `engine.add` invocation needs `try`. In non-throwing contexts (closures dispatched to `DispatchQueue.main.async`, non-throwing methods), wrap in `do { try engine.add(synth) } catch { print("[Lyrebird] engine.add failed: \(error)") }` — the existing `LyrebirdRoutineContext` / `LyrebirdMessageContext` / `LyrebirdProcessContext` adapters use this pattern.
|
||||
|
||||
## Swift Code Style Rules
|
||||
@@ -346,6 +354,8 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th
|
||||
- `lyrebirdSeedXorshift64(from:mixConstant:)` / `lyrebirdSeedXorshift64(from:)` — `Math/LyrebirdConstants.swift`; init-time xorshift64 seed helper. Two-arg form decorrelates Audio/Control pairs via `mixConstant`; one-arg form is the convenience for stand-alone single-state owners (e.g. `DemandTemporalTendency` / `DemandTemporalBrownian`)
|
||||
- `catmullRomCubic(_:_:_:_:t:)` — `Math/CubicInterpolation.swift`; the single shared 4-point Catmull-Rom cubic kernel. Pass `(pM1, p0, p1, p2, t:)` — the sample before the segment, the two bracketing it, the one after, and `t ∈ [0, 1]`. Use instead of inlining the `t²`/`t³` expanded form. `@inline(__always) @_spi(LyrebirdExtensions) public`. Consumers: oscillator table reads (`OscSin` / `oscillatorTableReadCubic`), `PlayBuffer`, `chaoticInterpolate`, and the fractional-delay lines (`DelayLine` / `DelayLineFeedback` / `CombFilter` / `AllpassFilter`).
|
||||
|
||||
- `RTScratchBuffer<Element>` — `Buffers/RTScratchBuffer.swift`; a `~Copyable` single-owner heap scratch buffer that replaces hand-paired `allocate`/`deinitialize`/`deallocate` in scratch-owning generators (the Spectral/FFT family). `init(count:)` zero-fills (`Element: Numeric`); `init(count:repeating:)` fills any value. `@inline(__always)` `baseAddress`/`count`/`subscript` (`nonmutating set`) so the hot loop matches the raw pointer. Store as a `let` assigned in `init` — never a per-call local. Not for `[UnsafeMutablePointer]` per-channel arrays (a `~Copyable` cannot be `Array`-stored) or capacity-1 scalar boxes used via `.pointee`. `@_spi(LyrebirdExtensions) public`.
|
||||
|
||||
Full table, signatures, examples, and the per-generator exceptions (notably `MathGenerators.Control` and the non-standard ControlGenerator ramp paths) live in `docs/protocols/writing-generators.md` §13. That document is the single source of truth — when adding or removing a helper, update §13 and reference it from here.
|
||||
|
||||
## Code Review
|
||||
|
||||
@@ -11,30 +11,11 @@
|
||||
C8D0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000008 /* AppDelegate.swift */; };
|
||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; };
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; };
|
||||
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; 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, ); }; };
|
||||
C8D00000000000000000041 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000040 /* Assets.xcassets */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
C8D00000000000000000004 /* LyrebirdScratchDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdScratchDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
C8D00000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; 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>"; };
|
||||
C8D00000000000000000009 /* LyrebirdScratchDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScratchDemo.entitlements; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
C8D00000000000000000012 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */,
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
C8D00000000000000000035 /* Embed Frameworks */ = {
|
||||
isa = PBXCopyFilesBuildPhase;
|
||||
@@ -50,11 +31,32 @@
|
||||
};
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
C8D00000000000000000004 /* LyrebirdScratch.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdScratch.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
C8D00000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; 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>"; };
|
||||
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 */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
C8D00000000000000000012 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */,
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
C8D00000000000000000002 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C8D00000000000000000005 /* LyrebirdScratchDemo */,
|
||||
C8D00000000000000000005 /* LyrebirdScratch */,
|
||||
C8D00000000000000000003 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
@@ -62,45 +64,47 @@
|
||||
C8D00000000000000000003 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C8D00000000000000000004 /* LyrebirdScratchDemo.app */,
|
||||
C8D00000000000000000004 /* LyrebirdScratch.app */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
C8D00000000000000000005 /* LyrebirdScratchDemo */ = {
|
||||
C8D00000000000000000005 /* LyrebirdScratch */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C8D00000000000000000007 /* main.swift */,
|
||||
C8D00000000000000000008 /* AppDelegate.swift */,
|
||||
C8D00000000000000000006 /* Info.plist */,
|
||||
C8D00000000000000000009 /* LyrebirdScratchDemo.entitlements */,
|
||||
C8D00000000000000000009 /* LyrebirdScratch.entitlements */,
|
||||
C8D00000000000000000040 /* Assets.xcassets */,
|
||||
);
|
||||
path = LyrebirdScratchDemo;
|
||||
path = LyrebirdScratch;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
C8D00000000000000000014 /* LyrebirdScratchDemo */ = {
|
||||
C8D00000000000000000014 /* LyrebirdScratch */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratchDemo" */;
|
||||
buildConfigurationList = C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratch" */;
|
||||
buildPhases = (
|
||||
C8D00000000000000000011 /* Sources */,
|
||||
C8D00000000000000000012 /* Frameworks */,
|
||||
C8D00000000000000000013 /* Resources */,
|
||||
C8D00000000000000000035 /* Embed Frameworks */,
|
||||
C8D00000000000000000042 /* Bundle Lyrebird swiftmodules */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = LyrebirdScratchDemo;
|
||||
name = LyrebirdScratch;
|
||||
packageProductDependencies = (
|
||||
C8D0000000000000000001D /* LyrebirdDynamic */,
|
||||
C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */,
|
||||
);
|
||||
productName = LyrebirdScratchDemo;
|
||||
productReference = C8D00000000000000000004 /* LyrebirdScratchDemo.app */;
|
||||
productName = LyrebirdScratch;
|
||||
productReference = C8D00000000000000000004 /* LyrebirdScratch.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
@@ -111,14 +115,14 @@
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 2620;
|
||||
LastUpgradeCheck = 2660;
|
||||
TargetAttributes = {
|
||||
C8D00000000000000000014 = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratchDemo" */;
|
||||
buildConfigurationList = C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratch" */;
|
||||
compatibilityVersion = "Xcode 14.0";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
@@ -135,7 +139,7 @@
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
C8D00000000000000000014 /* LyrebirdScratchDemo */,
|
||||
C8D00000000000000000014 /* LyrebirdScratch */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
@@ -145,11 +149,30 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C8D00000000000000000041 /* Assets.xcassets in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* 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 */
|
||||
C8D00000000000000000011 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
@@ -166,19 +189,40 @@
|
||||
C8D00000000000000000016 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
|
||||
AUTOMATION_APPLE_EVENTS = NO;
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
|
||||
CODE_SIGN_IDENTITY = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 2;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdScratchDemo/Info.plist;
|
||||
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
||||
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
|
||||
ENABLE_RESOURCE_ACCESS_CAMERA = NO;
|
||||
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
|
||||
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
|
||||
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratchDemo;
|
||||
MARKETING_VERSION = 1.6.2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
RUNTIME_EXCEPTION_ALLOW_DYLD_ENVIRONMENT_VARIABLES = NO;
|
||||
RUNTIME_EXCEPTION_ALLOW_JIT = NO;
|
||||
RUNTIME_EXCEPTION_ALLOW_UNSIGNED_EXECUTABLE_MEMORY = NO;
|
||||
RUNTIME_EXCEPTION_DEBUGGING_TOOL = NO;
|
||||
RUNTIME_EXCEPTION_DISABLE_EXECUTABLE_PAGE_PROTECTION = NO;
|
||||
RUNTIME_EXCEPTION_DISABLE_LIBRARY_VALIDATION = NO;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
@@ -187,18 +231,39 @@
|
||||
C8D00000000000000000017 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
|
||||
AUTOMATION_APPLE_EVENTS = NO;
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
|
||||
CODE_SIGN_IDENTITY = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 2;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdScratchDemo/Info.plist;
|
||||
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
||||
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
|
||||
ENABLE_RESOURCE_ACCESS_CAMERA = NO;
|
||||
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
|
||||
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
|
||||
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratchDemo;
|
||||
MARKETING_VERSION = 1.6.2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
RUNTIME_EXCEPTION_ALLOW_DYLD_ENVIRONMENT_VARIABLES = NO;
|
||||
RUNTIME_EXCEPTION_ALLOW_JIT = NO;
|
||||
RUNTIME_EXCEPTION_ALLOW_UNSIGNED_EXECUTABLE_MEMORY = NO;
|
||||
RUNTIME_EXCEPTION_DEBUGGING_TOOL = NO;
|
||||
RUNTIME_EXCEPTION_DISABLE_EXECUTABLE_PAGE_PROTECTION = NO;
|
||||
RUNTIME_EXCEPTION_DISABLE_LIBRARY_VALIDATION = NO;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
@@ -239,6 +304,7 @@
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
@@ -263,9 +329,6 @@
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
// Xcode 26 explicit-module-build regression: SPM dynamic-library
|
||||
// framework binaries (LyrebirdDynamic / LyrebirdLiveCompileUIDynamic)
|
||||
// are not emitted under the integrated driver. Classic driver fixes it.
|
||||
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
||||
};
|
||||
name = Debug;
|
||||
@@ -305,6 +368,7 @@
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
@@ -322,7 +386,6 @@
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
// Xcode 26 explicit-module-build regression — see Debug config.
|
||||
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
||||
};
|
||||
name = Release;
|
||||
@@ -330,7 +393,7 @@
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratchDemo" */ = {
|
||||
C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratch" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
C8D00000000000000000016 /* Debug */,
|
||||
@@ -339,7 +402,7 @@
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratchDemo" */ = {
|
||||
C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratch" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
C8D00000000000000000019 /* Debug */,
|
||||
@@ -16,9 +16,9 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "C8D00000000000000000014"
|
||||
BuildableName = "LyrebirdScratchDemo.app"
|
||||
BlueprintName = "LyrebirdScratchDemo"
|
||||
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj">
|
||||
BuildableName = "LyrebirdScratch.app"
|
||||
BlueprintName = "LyrebirdScratch"
|
||||
ReferencedContainer = "container:LyrebirdScratch.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
@@ -31,7 +31,7 @@
|
||||
shouldAutocreateTestPlan = "YES">
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
@@ -45,9 +45,9 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "C8D00000000000000000014"
|
||||
BuildableName = "LyrebirdScratchDemo.app"
|
||||
BlueprintName = "LyrebirdScratchDemo"
|
||||
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj">
|
||||
BuildableName = "LyrebirdScratch.app"
|
||||
BlueprintName = "LyrebirdScratch"
|
||||
ReferencedContainer = "container:LyrebirdScratch.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
@@ -62,9 +62,9 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "C8D00000000000000000014"
|
||||
BuildableName = "LyrebirdScratchDemo.app"
|
||||
BlueprintName = "LyrebirdScratchDemo"
|
||||
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj">
|
||||
BuildableName = "LyrebirdScratch.app"
|
||||
BlueprintName = "LyrebirdScratch"
|
||||
ReferencedContainer = "container:LyrebirdScratch.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
@@ -20,6 +20,21 @@ import LyrebirdLiveCompileUI
|
||||
// this demo used was `LyrebirdWindow`, an `NSWindow`/`NSHostingController`
|
||||
// wrapper with no `LyrebirdSynth` dependency — inlined below instead.
|
||||
|
||||
// Entitlements / signing posture (rationale kept here because Xcode strips
|
||||
// comments from `LyrebirdScratch.entitlements` on every project resave):
|
||||
//
|
||||
// • App Sandbox is intentionally OFF. Live-compile shells out to `swiftc`
|
||||
// (`posix_spawn`, disallowed under the sandbox) and `dlopen`s the resulting
|
||||
// UNSIGNED snippet dylib (rejected by the sandbox). This is a direct-
|
||||
// distribution developer tool, not a Mac App Store app; sandbox-off is the
|
||||
// only viable configuration. (An XPC-worker split could revisit this.)
|
||||
// • Hardened Runtime is ON, so the entitlement
|
||||
// `com.apple.security.cs.disable-library-validation = true` is REQUIRED —
|
||||
// without it dyld rejects `dlopen` of the unsigned, non-team-signed snippet
|
||||
// dylib ("code signing blocked mmap()").
|
||||
//
|
||||
// Do not remove that entitlement or the app can't load compiled snippets.
|
||||
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
@@ -31,6 +46,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
@MainActor
|
||||
init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
// Stage the Lyrebird compile artifacts into ~/Library/Application Support
|
||||
// (ungated) before the session reads its default -I/-L/rpath. Without
|
||||
// this the snippet compiler points swiftc at the SPM build dir under
|
||||
// ~/Documents, tripping the macOS Documents-folder permission gate.
|
||||
// Best-effort: if staging fails the session falls back to the build dir.
|
||||
LiveSession.stageArtifacts()
|
||||
self.session = LiveSession(engine: engine)
|
||||
}
|
||||
|
||||
@@ -39,7 +60,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
do {
|
||||
try engine.start()
|
||||
} catch {
|
||||
print("[LyrebirdScratchDemo] Engine failed to start: \(error)")
|
||||
print("[LyrebirdScratch] Engine failed to start: \(error)")
|
||||
}
|
||||
|
||||
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session)
|
||||
@@ -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>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<string>1.6.3</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<string>3</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>Copyright © 2026 Realized Sound. All rights reserved.</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,45 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!--
|
||||
App Sandbox is intentionally OFF.
|
||||
|
||||
LyrebirdScratchDemo shells out to `swiftc` at runtime to compile user-
|
||||
typed Swift snippets, then calls `dlopen` on the resulting unsigned dylib.
|
||||
Both operations are blocked by the macOS App Sandbox:
|
||||
|
||||
- `posix_spawn` / `fork` for the swiftc subprocess is disallowed in a
|
||||
sandboxed process (com.apple.security.temporary-exception.mach-lookup
|
||||
grants exist for specific Apple tools only, not arbitrary executables).
|
||||
- `dlopen` of a dylib that was not shipped with the app bundle and is
|
||||
not code-signed with a matching team ID is rejected by the sandbox.
|
||||
|
||||
This app is a direct-distribution developer tool, not a Mac App Store
|
||||
submission. Sandbox OFF is the only viable configuration for v1.
|
||||
This could be revisited if an XPC-worker approach is adopted.
|
||||
|
||||
com.apple.security.app-sandbox key is absent (defaults false).
|
||||
-->
|
||||
|
||||
<!--
|
||||
Hardened Runtime — Disable Library Validation.
|
||||
|
||||
With Hardened Runtime enabled (ENABLE_HARDENED_RUNTIME = YES in the
|
||||
Xcode project), `dlopen` of a dylib that was not signed with the same
|
||||
Team ID as the host app is rejected by the dynamic linker.
|
||||
|
||||
LyrebirdScratchDemo writes snippet dylibs to a per-session temp dir
|
||||
via `swiftc -emit-library`; those dylibs are unsigned (swiftc does not
|
||||
sign them). The `CS_ALLOW_UNSIGNED_EXECUTABLE_MEMORY` (library-
|
||||
validation disable) entitlement tells the kernel to skip the
|
||||
code-signing check for loaded libraries, allowing `dlopen` to succeed.
|
||||
|
||||
Without this entitlement the app would crash with DYLD_PRINT_LIBRARIES
|
||||
reporting: "Library not loaded: ... Reason: tried: ... no suitable image
|
||||
found. Did find: ... code signing blocked mmap() of '...'"
|
||||
-->
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -368,6 +368,6 @@ The repo ships eight runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.
|
||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | `nrt` |
|
||||
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | `score` |
|
||||
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | `auv3` |
|
||||
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | live-coding scratchpad |
|
||||
| [`LyrebirdScratch`](Demos/LyrebirdScratch/) | live-coding scratchpad |
|
||||
|
||||
See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for per-demo notes and gotchas.
|
||||
|
||||
@@ -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.
|
||||
@@ -141,7 +141,7 @@ A container app + `.appex` extension target shipping **Realized Sound: LyrebirdF
|
||||
|
||||
---
|
||||
|
||||
### LyrebirdScratchDemo — Live-Coding Scratchpad
|
||||
### LyrebirdScratch — Live-Coding Scratchpad
|
||||
|
||||
A macOS app that compiles a typed Swift snippet against the live engine at ⌘↩. Backed by `LyrebirdScratchView` and `LiveSession` from the `LyrebirdLiveCompile` SPM target.
|
||||
|
||||
@@ -157,7 +157,7 @@ A macOS app that compiles a typed Swift snippet against the live engine at ⌘
|
||||
- **Clear Synths** toolbar button — full reset: removes all tracked synths *and* every named slot immediately.
|
||||
|
||||
**Why this app cannot be sandboxed:**
|
||||
`swiftc` is a subprocess (`posix_spawn`); the output dylib is unsigned. Both are blocked by the macOS App Sandbox. This app is a direct-distribution developer tool only. The entitlements file (`LyrebirdScratchDemo.entitlements`) sets `com.apple.security.cs.disable-library-validation = true` to let Hardened Runtime `dlopen` the unsigned snippet dylib.
|
||||
`swiftc` is a subprocess (`posix_spawn`); the output dylib is unsigned. Both are blocked by the macOS App Sandbox. This app is a direct-distribution developer tool only. The entitlements file (`LyrebirdScratch.entitlements`) sets `com.apple.security.cs.disable-library-validation = true` to let Hardened Runtime `dlopen` the unsigned snippet dylib.
|
||||
|
||||
**Dylib lifetime:** loaded dylibs are never unloaded. `Synthesizer` instances reference types from the dylib; unloading while they are active would crash. Every ⌘↩ evaluation writes a new uniquely-named dylib to a per-session temp dir. This is intentional v1 behaviour; a future release may revisit with an XPC worker approach.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// ArtifactStagingError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Errors raised while staging compile artifacts into Application Support.
|
||||
enum ArtifactStagingError: Error {
|
||||
/// The staging destination already exists, is non-empty, and does not look
|
||||
/// like a prior staging root — refused rather than clobbered.
|
||||
case destinationNotAStagingRoot(String)
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Handle to one successfully compiled and loaded snippet.
|
||||
///
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
// The editor (`LyrebirdScratchView`) renders diagnostics in its
|
||||
// margin gutter using `(line, column)` directly.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
public struct Diagnostic: Equatable, Sendable {
|
||||
/// 1-based line number in the **user's** snippet body. May be `nil` when the
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
public enum DiagnosticParser {
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
//
|
||||
// Severity classifier for a parsed swiftc diagnostic line.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
public enum DiagnosticSeverity: String, Equatable, Sendable {
|
||||
case error
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// (line, column); build errors carry no span → `line: nil` with the message
|
||||
// alone.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import LyrebirdGraphDSLEmbedded
|
||||
|
||||
/// Maps interpreted-graph-DSL errors to editor diagnostics.
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// One parsed code-completion candidate from `sourcekit-lsp`. macOS only.
|
||||
// One parsed code-completion candidate from `sourcekit-lsp`. macOS/Linux only.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// One code-completion candidate returned by sourcekit-lsp.
|
||||
public struct LSPCompletionItem: Sendable, Equatable {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
public enum LiveCompileError: Error, CustomStringConvertible, Equatable, Sendable {
|
||||
/// `xcrun -f swiftc` and the fallback paths all failed.
|
||||
|
||||
@@ -9,14 +9,16 @@
|
||||
// `LiveCompiler.compile(source:)` shells out to `swiftc -emit-library`, then
|
||||
// `dlopen`s the resulting dylib and resolves the snippet entry symbol. No UI,
|
||||
// no `SynthesisEngine` binding (those are handled by the harness and session
|
||||
// layers). macOS only — iOS cannot exec swiftc.
|
||||
// layers). macOS/Linux only — iOS cannot exec swiftc.
|
||||
|
||||
import Foundation
|
||||
#if os(macOS)
|
||||
import Darwin
|
||||
#if canImport(Darwin)
|
||||
import Darwin // dlopen / dlsym / dlerror
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc // dlopen / dlsym / dlerror on Linux
|
||||
#endif
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Symbol the snippet preamble must export. Snippets declare:
|
||||
///
|
||||
@@ -26,10 +28,37 @@ import Darwin
|
||||
/// ```
|
||||
public let lyrebirdSnippetEntrySymbol: String = "lyrebird_snippet_entry"
|
||||
|
||||
/// Platform shared-library extension: `dylib` (Mach-O) on macOS, `so` (ELF) on
|
||||
/// Linux. A snippet is `swiftc -emit-library`'d to `lib<name>.<ext>`, and the
|
||||
/// resident Lyrebird library is `libLyrebirdDynamic.<ext>`.
|
||||
#if os(macOS)
|
||||
let livecompileSharedLibraryExtension: String = "dylib"
|
||||
#else
|
||||
let livecompileSharedLibraryExtension: String = "so"
|
||||
#endif
|
||||
|
||||
/// Search `$PATH` for an executable named `name`, returning the first hit or
|
||||
/// `nil`. Covers toolchains installed outside the hard-coded locations — most
|
||||
/// notably a swiftly install (`~/.local/share/swiftly/bin`) on Linux, which puts
|
||||
/// both `swiftc` and `sourcekit-lsp` on `$PATH` but not in `/usr/bin`.
|
||||
func livecompileExecutableOnPath(_ name: String) -> String? {
|
||||
guard let pathEnv: String = ProcessInfo.processInfo.environment["PATH"] else { return nil }
|
||||
for dir: Substring in pathEnv.split(separator: ":") where !dir.isEmpty {
|
||||
let base: String = String(dir)
|
||||
let candidate: String = base.hasSuffix("/") ? base + name : base + "/" + name
|
||||
if FileManager.default.isExecutableFile(atPath: candidate) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// One-shot snippet compiler. Stateless — every `compile(source:)` allocates a
|
||||
/// fresh temp dir, dylib name, and `dlopen` handle.
|
||||
/// fresh temp dir, shared-library name, and `dlopen` handle.
|
||||
public enum LiveCompiler {
|
||||
|
||||
static var sharedLibraryExtension: String { livecompileSharedLibraryExtension }
|
||||
|
||||
/// Compile `source` to a dylib and resolve the snippet entry symbol.
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -52,7 +81,7 @@ public enum LiveCompiler {
|
||||
let workDir: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LyrebirdLiveCompile-\(snippetID)", isDirectory: true)
|
||||
let sourcePath: String = workDir.appendingPathComponent("Snippet.swift").path
|
||||
let dylibPath: String = workDir.appendingPathComponent("lib\(moduleName).dylib").path
|
||||
let dylibPath: String = workDir.appendingPathComponent("lib\(moduleName).\(sharedLibraryExtension)").path
|
||||
|
||||
do {
|
||||
try FileManager.default.createDirectory(
|
||||
@@ -112,11 +141,17 @@ public enum LiveCompiler {
|
||||
|
||||
/// First-success search:
|
||||
/// 1. `xcrun -f swiftc` (honours `DEVELOPER_DIR` and the user's active Xcode).
|
||||
/// 2. Hard-coded toolchain paths.
|
||||
/// 2. An executable `swiftc` on `$PATH` — covers a swiftly install
|
||||
/// (`~/.local/share/swiftly/bin`) and any Linux toolchain layout that
|
||||
/// isn't in the hard-coded list.
|
||||
/// 3. Hard-coded toolchain paths.
|
||||
static func findSwiftc() throws -> String {
|
||||
if let xcrun: String = swiftcViaXcrun() {
|
||||
return xcrun
|
||||
}
|
||||
if let onPath: String = swiftcOnPath() {
|
||||
return onPath
|
||||
}
|
||||
let candidates: [String] = [
|
||||
"/usr/bin/swiftc",
|
||||
"/usr/local/bin/swiftc",
|
||||
@@ -128,6 +163,11 @@ public enum LiveCompiler {
|
||||
throw LiveCompileError.swiftcNotFound
|
||||
}
|
||||
|
||||
/// Search `$PATH` for an executable `swiftc`. Returns the first hit, or `nil`.
|
||||
static func swiftcOnPath() -> String? {
|
||||
livecompileExecutableOnPath("swiftc")
|
||||
}
|
||||
|
||||
/// `xcrun --show-sdk-path` — returns the macOS SDK path used by the user's
|
||||
/// active Xcode. `nil` when xcrun is missing or returns non-zero.
|
||||
static func sdkPathViaXcrun() -> String? {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// `CompiledSnippet` so the dylibs stay mapped — see the leak-by-design note in
|
||||
// `CompiledSnippet.swift`.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -665,6 +665,13 @@ public final class LiveSession: @unchecked Sendable {
|
||||
for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
#if os(Linux)
|
||||
// Source-only system-library module maps (CALSA, LyrebirdC) — see the
|
||||
// helper. Without CALSA's, a Linux `import LyrebirdSynth` fails to resolve.
|
||||
for url: URL in LiveSession.discoverSourceSystemModuleMaps(in: importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
#endif
|
||||
return args
|
||||
}
|
||||
|
||||
@@ -690,7 +697,15 @@ public final class LiveSession: @unchecked Sendable {
|
||||
args += ["-Xlinker", "-rpath", "-Xlinker", path.path]
|
||||
}
|
||||
} else {
|
||||
#if os(macOS)
|
||||
args += ["-Xlinker", "-undefined", "-Xlinker", "dynamic_lookup"]
|
||||
#else
|
||||
// ELF has no Mach-O flat-namespace deferred lookup: a snippet resolves
|
||||
// Lyrebird symbols by NEEDED-linking libLyrebirdDynamic.so, which needs
|
||||
// it present in a -L path (i.e. hasDylib == true). Reaching here on
|
||||
// Linux means no such library was found; emit no link flag so the link
|
||||
// fails loudly rather than adding a macOS-only one.
|
||||
#endif
|
||||
}
|
||||
return args
|
||||
}
|
||||
@@ -754,6 +769,44 @@ public final class LiveSession: @unchecked Sendable {
|
||||
return found
|
||||
}
|
||||
|
||||
#if os(Linux)
|
||||
/// Linux only: locate the `CALSA` **system-library** module map, which lives
|
||||
/// only in the package *source* tree (`Sources/CALSA/module.modulemap`),
|
||||
/// never in the build dir — a `.systemLibrary` target emits no
|
||||
/// `<CTarget>.build/module.modulemap`. `LyrebirdSynth` transitively imports
|
||||
/// `CALSA` on Linux (the ALSA driver), so a snippet's `import LyrebirdSynth`
|
||||
/// fails with `missing required module 'CALSA'` unless the map is surfaced.
|
||||
/// macOS never hits this (Core Audio, no CALSA import). `LyrebirdC` is a
|
||||
/// regular C target and IS covered by `discoverSPMModuleMaps` (build-tree
|
||||
/// map) — adding its source map too would `redefinition of module 'LyrebirdC'`.
|
||||
/// Walks up from each import path (bounded) to the package root.
|
||||
static func discoverSourceSystemModuleMaps(in importPaths: [URL]) -> [URL] {
|
||||
let maxWalk: Int = 8
|
||||
let relativeMaps: [String] = [
|
||||
"Sources/CALSA/module.modulemap",
|
||||
]
|
||||
var found: [URL] = []
|
||||
var visited: Set<String> = Set<String>()
|
||||
for start: URL in importPaths {
|
||||
var cur: URL = start
|
||||
for _ in 0..<maxWalk {
|
||||
for rel: String in relativeMaps {
|
||||
let probe: URL = cur.appendingPathComponent(rel)
|
||||
if FileManager.default.fileExists(atPath: probe.path),
|
||||
!visited.contains(probe.path) {
|
||||
visited.insert(probe.path)
|
||||
found.append(probe)
|
||||
}
|
||||
}
|
||||
let parent: URL = cur.deletingLastPathComponent()
|
||||
if parent == cur { break }
|
||||
cur = parent
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Build-dir discovery
|
||||
|
||||
/// Best-effort discovery of the SPM `.build/<triple>/<config>` directory
|
||||
@@ -781,7 +834,10 @@ public final class LiveSession: @unchecked Sendable {
|
||||
// (→ libLyrebirdDynamic.dylib); the module/target is `LyrebirdSynth`
|
||||
// (LyrebirdSynth.swiftmodule). The consumer-facing `Lyrebird` product
|
||||
// is static and produces no dylib, so it is not a marker here.
|
||||
let markers: [String] = ["libLyrebirdDynamic.dylib", "LyrebirdSynth.swiftmodule"]
|
||||
let markers: [String] = [
|
||||
"libLyrebirdDynamic.\(livecompileSharedLibraryExtension)",
|
||||
"LyrebirdSynth.swiftmodule",
|
||||
]
|
||||
for start: URL in candidates {
|
||||
var cur: URL = start
|
||||
for _ in 0..<maxWalk {
|
||||
@@ -805,23 +861,42 @@ public final class LiveSession: @unchecked Sendable {
|
||||
/// already resolved in the running process.
|
||||
public static func hasLyrebirdDylib(in buildDir: URL) -> Bool {
|
||||
FileManager.default.fileExists(
|
||||
atPath: buildDir.appendingPathComponent("libLyrebirdDynamic.dylib").path
|
||||
atPath: buildDir.appendingPathComponent(
|
||||
"libLyrebirdDynamic.\(livecompileSharedLibraryExtension)"
|
||||
).path
|
||||
)
|
||||
}
|
||||
|
||||
/// Prefer a populated staged artifacts dir (App Support, ungated) over the
|
||||
/// SPM build dir (which lives under `~/Documents` in a dev checkout). Hosts
|
||||
/// that want staging call ``stageArtifacts(from:to:)`` before constructing
|
||||
/// the session; these defaults then resolve to the staged copy.
|
||||
private static func resolvedArtifactsDir() -> URL? {
|
||||
// Prefer the staged dir only when it is populated AND current relative to
|
||||
// the live build dir — so a stale copy left by a different build (or a
|
||||
// partial stage) never masquerades as the resolved artifacts for a host
|
||||
// that did not itself stage.
|
||||
if let staged: URL = stagedArtifactsDir(),
|
||||
isArtifactsDirPopulated(staged),
|
||||
stagedDirIsCurrent(staged) {
|
||||
return staged
|
||||
}
|
||||
return currentBuildDir()
|
||||
}
|
||||
|
||||
public static func defaultImportPaths() -> [URL] {
|
||||
guard let buildDir: URL = currentBuildDir() else { return [] }
|
||||
return [buildDir, buildDir.appendingPathComponent("Modules")]
|
||||
guard let dir: URL = resolvedArtifactsDir() else { return [] }
|
||||
return [dir, dir.appendingPathComponent("Modules")]
|
||||
}
|
||||
|
||||
public static func defaultLibrarySearchPaths() -> [URL] {
|
||||
guard let buildDir: URL = currentBuildDir() else { return [] }
|
||||
return [buildDir]
|
||||
guard let dir: URL = resolvedArtifactsDir() else { return [] }
|
||||
return [dir]
|
||||
}
|
||||
|
||||
public static func defaultRpaths() -> [URL] {
|
||||
guard let buildDir: URL = currentBuildDir() else { return [] }
|
||||
return [buildDir]
|
||||
guard let dir: URL = resolvedArtifactsDir() else { return [] }
|
||||
return [dir]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
// LiveSessionArtifactStaging.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Snippet compilation needs the Lyrebird module artifacts (swiftmodules, the
|
||||
// Lyrebird dylibs, and the C-shim Clang module map + its umbrella header). In a
|
||||
// dev checkout those live in the SPM build dir under `~/Documents`, so a
|
||||
// non-sandboxed host reading them — and the `swiftc` it spawns reading them —
|
||||
// trips the macOS "wants to access your Documents folder" TCC gate.
|
||||
//
|
||||
// Staging copies the minimal artifact set into
|
||||
// `~/Library/Application Support/LyrebirdScratch/LiveCompile/`, an ungated
|
||||
// location, and rewrites the C module map's absolute umbrella-header path to the
|
||||
// staged copy. The default `-I` / `-L` / rpath resolution then prefers the
|
||||
// staged dir, so a shipped app compiles snippets without ever touching a
|
||||
// permission-gated folder.
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
extension LiveSession {
|
||||
|
||||
/// Name of the artifacts subdirectory a host may ship inside its app bundle
|
||||
/// (`<App>.app/Contents/Resources/<name>`). Staging prefers this over the
|
||||
/// dev build dir when present, so a shipped app never reads outside its
|
||||
/// bundle or App Support.
|
||||
public static let bundledArtifactsDirName: String = "LyrebirdArtifacts"
|
||||
|
||||
/// `~/Library/Application Support/LyrebirdScratch/LiveCompile` — the ungated
|
||||
/// destination for staged compile artifacts. `nil` only if the Application
|
||||
/// Support directory can't be resolved.
|
||||
public static func stagedArtifactsDir() -> URL? {
|
||||
guard let base: URL = FileManager.default.urls(
|
||||
for: .applicationSupportDirectory,
|
||||
in: .userDomainMask
|
||||
).first else { return nil }
|
||||
return base
|
||||
.appendingPathComponent("LyrebirdScratch", isDirectory: true)
|
||||
.appendingPathComponent("LiveCompile", isDirectory: true)
|
||||
}
|
||||
|
||||
/// Whether `dir` is a usable compile root: it has a `Modules/` directory
|
||||
/// holding at least one `.swiftmodule`.
|
||||
public static func isArtifactsDirPopulated(_ dir: URL) -> Bool {
|
||||
let modules: URL = dir.appendingPathComponent("Modules", isDirectory: true)
|
||||
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
|
||||
at: modules,
|
||||
includingPropertiesForKeys: nil
|
||||
) else { return false }
|
||||
return entries.contains { $0.pathExtension == "swiftmodule" }
|
||||
}
|
||||
|
||||
/// Where to stage FROM. Prefers a `LyrebirdArtifacts` directory shipped in
|
||||
/// the app bundle's `Resources` (self-contained, never under a gated
|
||||
/// folder); falls back to the dev SPM build dir.
|
||||
public static func artifactSourceDir() -> URL? {
|
||||
if let resources: URL = Bundle.main.resourceURL {
|
||||
let bundled: URL = resources.appendingPathComponent(
|
||||
bundledArtifactsDirName,
|
||||
isDirectory: true
|
||||
)
|
||||
if isArtifactsDirPopulated(bundled) { return bundled }
|
||||
}
|
||||
return currentBuildDir()
|
||||
}
|
||||
|
||||
/// Copy the minimal artifact set from `source` (default: ``artifactSourceDir()``)
|
||||
/// into `destination` (default: ``stagedArtifactsDir()``), rewriting the C
|
||||
/// module map to point at a staged copy of its umbrella header. Idempotent:
|
||||
/// skips the copy when the destination is already newer than the source.
|
||||
/// Best-effort — returns the staged dir on success, `nil` on any failure or
|
||||
/// when no source/destination could be resolved.
|
||||
///
|
||||
/// - Note: In a dev checkout the source is the build dir under `~/Documents`,
|
||||
/// so the one-time copy still reads that gated folder; every subsequent
|
||||
/// launch reuses the staged copy and reads only App Support. A shipped app
|
||||
/// whose `Resources/LyrebirdArtifacts` is populated never reads a gated
|
||||
/// folder at all.
|
||||
@discardableResult
|
||||
public static func stageArtifacts(
|
||||
from source: URL? = nil,
|
||||
to destination: URL? = nil
|
||||
) -> URL? {
|
||||
guard let dest: URL = destination ?? stagedArtifactsDir() else { return nil }
|
||||
guard let src: URL = source ?? artifactSourceDir() else { return nil }
|
||||
do {
|
||||
try stageArtifactsThrowing(from: src, to: dest)
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
return isArtifactsDirPopulated(dest) ? dest : nil
|
||||
}
|
||||
|
||||
// MARK: - Implementation
|
||||
|
||||
static let stageReceiptName: String = ".stage-receipt"
|
||||
|
||||
/// Slack in the receipt-vs-source stamp comparison. A `Date` stores seconds
|
||||
/// since 2001; the receipt records `timeIntervalSince1970`, so reconstructing
|
||||
/// it adds then subtracts the ~978-million-second epoch offset — floating-
|
||||
/// point arithmetic at that magnitude perturbs the sub-second fraction, so a
|
||||
/// bit-exact `>=` can spuriously read "stale" (the string encoding itself is
|
||||
/// exact; the loss is in the epoch conversion, not the receipt). mtime
|
||||
/// staleness needs no sub-second resolution — a rebuild moves mtimes by far
|
||||
/// more than a second.
|
||||
private static let stageStampToleranceSeconds: TimeInterval = 1.0
|
||||
|
||||
/// Whether a staged dir at `dest` is current relative to the artifact source
|
||||
/// it would stage from. When no source is discoverable (a shipped app with no
|
||||
/// build dir and no bundled artifacts), any populated staged dir is trusted.
|
||||
/// Otherwise the receipt must be at or after the source's newest artifact —
|
||||
/// so a staged copy left by a *different* build (or a partial stage that never
|
||||
/// wrote a receipt) is ignored and the resolver falls back to the build dir.
|
||||
/// Compared against ``artifactSourceDir()`` (not the build dir directly) so
|
||||
/// the base matches what ``stageArtifacts(from:to:)`` actually copies from.
|
||||
static func stagedDirIsCurrent(_ dest: URL) -> Bool {
|
||||
guard let source: URL = artifactSourceDir() else { return true }
|
||||
guard let prior: Date = stageReceiptDate(dest.appendingPathComponent(stageReceiptName, isDirectory: false))
|
||||
else { return false }
|
||||
return prior.timeIntervalSince1970 >= sourceArtifactStamp(source).timeIntervalSince1970 - stageStampToleranceSeconds
|
||||
}
|
||||
|
||||
private static func stageArtifactsThrowing(from src: URL, to dest: URL) throws {
|
||||
let fm: FileManager = FileManager.default
|
||||
let srcStamp: Date = sourceArtifactStamp(src)
|
||||
|
||||
// Up to date? A populated dest whose receipt is at or after the source's
|
||||
// newest artifact mtime needs no re-copy.
|
||||
if isArtifactsDirPopulated(dest),
|
||||
let prior: Date = stageReceiptDate(dest.appendingPathComponent(stageReceiptName, isDirectory: false)),
|
||||
prior.timeIntervalSince1970 >= srcStamp.timeIntervalSince1970 - stageStampToleranceSeconds {
|
||||
return
|
||||
}
|
||||
|
||||
// Refuse to clobber a directory we did not create: an existing, non-empty
|
||||
// `dest` must look like a prior staging root (a receipt or a `Modules/`
|
||||
// dir) before we replace it. Guards a typo'd `to:` from wiping real data.
|
||||
if fm.fileExists(atPath: dest.path), !isReplaceableStagingDest(dest) {
|
||||
throw ArtifactStagingError.destinationNotAStagingRoot(dest.path)
|
||||
}
|
||||
|
||||
// Build everything in a private sibling temp dir, then atomically swap it
|
||||
// over `dest`. `dest` is therefore only ever fully-complete or absent — a
|
||||
// failed/partial stage never leaves a dir that *looks* valid, and two
|
||||
// stagers racing the same `dest` can't observe a half-written tree.
|
||||
let staging: URL = dest.deletingLastPathComponent()
|
||||
.appendingPathComponent(".\(dest.lastPathComponent).staging-\(UUID().uuidString)", isDirectory: true)
|
||||
try fm.createDirectory(at: staging, withIntermediateDirectories: true)
|
||||
defer { try? fm.removeItem(at: staging) }
|
||||
|
||||
// 1. Swift modules.
|
||||
let srcModules: URL = src.appendingPathComponent("Modules", isDirectory: true)
|
||||
if fm.fileExists(atPath: srcModules.path) {
|
||||
try fm.copyItem(at: srcModules, to: staging.appendingPathComponent("Modules", isDirectory: true))
|
||||
}
|
||||
|
||||
// 2. Lyrebird dylibs (the snippet links these and bakes an rpath here;
|
||||
// at dlopen dyld matches the already-loaded install name, so the copy is
|
||||
// a link-time search target, not a second loaded image).
|
||||
for dylib: URL in lyrebirdDylibs(in: src) {
|
||||
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
|
||||
// temp `staging` dir, but the umbrella path baked into each map must
|
||||
// reference the FINAL `dest` (where they land after the atomic swap) —
|
||||
// the temp dir is deleted.
|
||||
stageClangModuleMaps(from: src, writeInto: staging, finalRoot: dest)
|
||||
|
||||
#if os(Linux)
|
||||
// 3.5. CALSA (the ALSA system library) has no `<Module>.build/` map in the
|
||||
// build dir — its module map lives only in the package source — so the
|
||||
// steps above miss it and a snippet's `import LyrebirdSynth` can't resolve
|
||||
// CALSA from the staged root. Copy the source module dir (map + relative
|
||||
// include/) into a self-contained `CALSA.build/` that `discoverSPMModuleMaps`
|
||||
// then finds at the staged location. macOS never imports CALSA.
|
||||
stageCALSAModuleMap(from: src, writeInto: staging)
|
||||
#endif
|
||||
|
||||
// Receipt: store the source stamp so the next call can skip an unchanged
|
||||
// source.
|
||||
let stampText: String = String(srcStamp.timeIntervalSince1970)
|
||||
try stampText.write(
|
||||
to: staging.appendingPathComponent(stageReceiptName, isDirectory: false),
|
||||
atomically: true,
|
||||
encoding: .utf8
|
||||
)
|
||||
|
||||
// Re-check the clobber guard immediately before the swap: the copy phase
|
||||
// above is a window in which something could have materialized a
|
||||
// non-staging directory at `dest`. Holding the guard across the whole
|
||||
// operation, not just at entry, keeps `replaceItemAt` from silently
|
||||
// wiping a dir we would have refused.
|
||||
if fm.fileExists(atPath: dest.path), !isReplaceableStagingDest(dest) {
|
||||
throw ArtifactStagingError.destinationNotAStagingRoot(dest.path)
|
||||
}
|
||||
|
||||
// Atomic swap into place.
|
||||
if fm.fileExists(atPath: dest.path) {
|
||||
_ = try fm.replaceItemAt(dest, withItemAt: staging)
|
||||
} else {
|
||||
try fm.createDirectory(at: dest.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
do {
|
||||
try fm.moveItem(at: staging, to: dest)
|
||||
} catch {
|
||||
// A concurrent stager may have created `dest` between the check
|
||||
// and the move; if it is now a valid root, treat as success.
|
||||
guard isArtifactsDirPopulated(dest) else { throw error }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Lyrebird dylibs present at the top level of `src`.
|
||||
private static func lyrebirdDylibs(in src: URL) -> [URL] {
|
||||
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
|
||||
at: src,
|
||||
includingPropertiesForKeys: nil
|
||||
) else { return [] }
|
||||
return entries.filter {
|
||||
$0.pathExtension == livecompileSharedLibraryExtension
|
||||
&& $0.lastPathComponent.hasPrefix("libLyrebird")
|
||||
}
|
||||
}
|
||||
|
||||
#if os(Linux)
|
||||
/// Copy the CALSA source module dir (`Sources/CALSA/`: `module.modulemap` +
|
||||
/// `include/calsa-shim.h`) into `staging/CALSA.build/`, so the staged root is a
|
||||
/// self-contained compile root for a snippet that transitively imports CALSA.
|
||||
/// The map's header path is relative, so it resolves verbatim at the staged
|
||||
/// location. Best-effort: if the source map isn't found (e.g. a detached build
|
||||
/// dir), staging proceeds without it and the snippet compile surfaces the gap.
|
||||
private static func stageCALSAModuleMap(from src: URL, writeInto staging: URL) {
|
||||
let fm: FileManager = FileManager.default
|
||||
guard let calsaMap: URL = LiveSession.discoverSourceSystemModuleMaps(in: [src]).first else {
|
||||
return
|
||||
}
|
||||
let calsaSrcDir: URL = calsaMap.deletingLastPathComponent()
|
||||
let stagedDir: URL = staging.appendingPathComponent("CALSA.build", isDirectory: true)
|
||||
try? fm.copyItem(at: calsaSrcDir, to: stagedDir)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// A `dest` is safe to replace when it doesn't exist, is empty, or looks like
|
||||
/// a prior staging root (has a receipt or a `Modules/` dir).
|
||||
private static func isReplaceableStagingDest(_ dest: URL) -> Bool {
|
||||
let fm: FileManager = FileManager.default
|
||||
guard fm.fileExists(atPath: dest.path) else { return true }
|
||||
if fm.fileExists(atPath: dest.appendingPathComponent(stageReceiptName).path) { return true }
|
||||
if fm.fileExists(atPath: dest.appendingPathComponent("Modules").path) { return true }
|
||||
let contents: [URL] = (try? fm.contentsOfDirectory(at: dest, includingPropertiesForKeys: nil)) ?? []
|
||||
return contents.isEmpty
|
||||
}
|
||||
|
||||
/// For each `<Module>.build/module.modulemap` under `src` whose umbrella
|
||||
/// header exists, copy the header's `include` directory into
|
||||
/// `writeInto/<Module>.headers` and write a staged map whose umbrella path
|
||||
/// points at `finalRoot/<Module>.headers/<header>` — the location those files
|
||||
/// 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
|
||||
/// 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) {
|
||||
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),
|
||||
let umbrella: String = umbrellaHeaderPath(in: text)
|
||||
else { continue }
|
||||
|
||||
let headerURL: URL = URL(fileURLWithPath: umbrella)
|
||||
guard fm.fileExists(atPath: headerURL.path) else { continue }
|
||||
|
||||
let includeDir: URL = headerURL.deletingLastPathComponent()
|
||||
let moduleName: String = buildDir.deletingPathExtension().lastPathComponent
|
||||
let headerName: String = headerURL.lastPathComponent
|
||||
// Files go under the temp staging dir…
|
||||
let stagedHeaders: URL = staging.appendingPathComponent("\(moduleName).headers", isDirectory: true)
|
||||
let stagedMapDir: URL = staging.appendingPathComponent(buildDir.lastPathComponent, isDirectory: true)
|
||||
// …but the baked umbrella path names their final resting place.
|
||||
let finalHeader: URL = dest
|
||||
.appendingPathComponent("\(moduleName).headers", isDirectory: true)
|
||||
.appendingPathComponent(headerName, isDirectory: false)
|
||||
let rewritten: String = text.replacingOccurrences(of: umbrella, with: finalHeader.path)
|
||||
do {
|
||||
try? fm.removeItem(at: stagedHeaders)
|
||||
try fm.copyItem(at: includeDir, to: stagedHeaders)
|
||||
try fm.createDirectory(at: stagedMapDir, withIntermediateDirectories: true)
|
||||
try rewritten.write(
|
||||
to: stagedMapDir.appendingPathComponent("module.modulemap", isDirectory: false),
|
||||
atomically: true,
|
||||
encoding: .utf8
|
||||
)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the path inside `umbrella header "..."` from a Clang module map.
|
||||
static func umbrellaHeaderPath(in modulemap: String) -> String? {
|
||||
guard let marker: Range<String.Index> = modulemap.range(of: "umbrella header") else { return nil }
|
||||
let after: Substring = modulemap[marker.upperBound...]
|
||||
guard let open: String.Index = after.firstIndex(of: "\"") else { return nil }
|
||||
let afterOpen: Substring = after[after.index(after: open)...]
|
||||
guard let close: String.Index = afterOpen.firstIndex(of: "\"") else { return nil }
|
||||
return String(afterOpen[..<close])
|
||||
}
|
||||
|
||||
/// Newest modification date among the artifacts we actually copy — a cheap
|
||||
/// staleness proxy that avoids walking the whole build tree. Derives the
|
||||
/// dylib set from the same wildcard scan the copy step uses, so a new/renamed
|
||||
/// Lyrebird dylib can't slip past the freshness check.
|
||||
///
|
||||
/// It does not probe the C module map or its umbrella header directly: a
|
||||
/// header edit forces `swift build` to rebuild the downstream swiftmodules
|
||||
/// too, which moves `Modules/`'s mtime — so a header change is caught
|
||||
/// transitively. (A hand-edited header with no rebuild would not re-stage,
|
||||
/// but that state never occurs from a normal build.)
|
||||
private static func sourceArtifactStamp(_ src: URL) -> Date {
|
||||
let fm: FileManager = FileManager.default
|
||||
var newest: Date = Date.distantPast
|
||||
var probes: [URL] = [src.appendingPathComponent("Modules", isDirectory: true)]
|
||||
probes += lyrebirdDylibs(in: src)
|
||||
for probe: URL in probes {
|
||||
if let attrs: [FileAttributeKey: Any] = try? fm.attributesOfItem(atPath: probe.path),
|
||||
let date: Date = attrs[.modificationDate] as? Date,
|
||||
date > newest {
|
||||
newest = date
|
||||
}
|
||||
}
|
||||
return newest
|
||||
}
|
||||
|
||||
private static func stageReceiptDate(_ receipt: URL) -> Date? {
|
||||
guard let text: String = try? String(contentsOf: receipt, encoding: .utf8),
|
||||
let interval: TimeInterval = TimeInterval(text.trimmingCharacters(in: .whitespacesAndNewlines))
|
||||
else { return nil }
|
||||
return Date(timeIntervalSince1970: interval)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -11,7 +11,7 @@
|
||||
// cases (toolchain missing, dlopen failure, etc.) pass through under
|
||||
// `.compilerError`.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
|
||||
/// Snippet failed to compile. `diagnostics` are already line-mapped via the
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
// across the Swift and DSL paths. The only difference is speed: a graph edit
|
||||
// re-evaluates in microseconds instead of a swiftc round-trip.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import LyrebirdSynth
|
||||
import LyrebirdGraphDSLEmbedded
|
||||
|
||||
|
||||
@@ -17,9 +17,9 @@
|
||||
// that file, which is what lets `import LyrebirdSynth` and the injected
|
||||
// `context: SnippetContext` resolve for an otherwise free-standing file.
|
||||
//
|
||||
// macOS only.
|
||||
// macOS/Linux only.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// Provides code completion for a live-coding editor buffer.
|
||||
@@ -92,6 +92,13 @@ public actor SnippetCompletionService {
|
||||
for url: URL in LiveSession.discoverSPMModuleMaps(in: session.importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
#if os(Linux)
|
||||
// CALSA's system-library module map is source-only (see LiveSession);
|
||||
// completion needs it too, or `import LyrebirdSynth` fails to resolve.
|
||||
for url: URL in LiveSession.discoverSourceSystemModuleMaps(in: session.importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
#endif
|
||||
for path: URL in session.librarySearchPaths {
|
||||
args += ["-L", path.path]
|
||||
}
|
||||
@@ -106,8 +113,16 @@ public actor SnippetCompletionService {
|
||||
}
|
||||
|
||||
private static func sdkPath() -> String? {
|
||||
// Linux needs no `-sdk`, and `xcrun` does not exist there. Crucially,
|
||||
// guard the spawn: on Linux, `Process.run()` throws when the launch path
|
||||
// is missing, and a subsequent `waitUntilExit()` on a process that never
|
||||
// started BLOCKS FOREVER (it is a no-op on macOS) — the completion hang.
|
||||
// The macOS xcrun helpers in LiveCompiler avoid this by checking
|
||||
// `isExecutableFile(atPath:)` first; do the same here.
|
||||
let xcrunPath: String = "/usr/bin/xcrun"
|
||||
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
|
||||
let p: Process = Process()
|
||||
p.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")
|
||||
p.executableURL = URL(fileURLWithPath: xcrunPath)
|
||||
p.arguments = ["--show-sdk-path", "--sdk", "macosx"]
|
||||
let out: Pipe = Pipe()
|
||||
p.standardOutput = out
|
||||
@@ -123,12 +138,20 @@ public actor SnippetCompletionService {
|
||||
/// Minimum-deployment target triple. Arch matches the running process;
|
||||
/// the OS floor matches the package's `macOS 15` minimum.
|
||||
private static func targetTriple() -> String {
|
||||
#if os(macOS)
|
||||
#if arch(arm64)
|
||||
let arch: String = "arm64"
|
||||
return "arm64-apple-macosx15.0"
|
||||
#else
|
||||
let arch: String = "x86_64"
|
||||
return "x86_64-apple-macosx15.0"
|
||||
#endif
|
||||
#else
|
||||
// Linux GNU triple; the Swift/LLVM spelling of arm64 is `aarch64`.
|
||||
#if arch(arm64)
|
||||
return "aarch64-unknown-linux-gnu"
|
||||
#else
|
||||
return "x86_64-unknown-linux-gnu"
|
||||
#endif
|
||||
#endif
|
||||
return "\(arch)-apple-macosx15.0"
|
||||
}
|
||||
|
||||
/// Launch sourcekit-lsp and open the (empty) document. Call once before the
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
// synth that the host will track for re-evaluation cleanup, and report back via
|
||||
// the test-friendly `reportSampleRate(_:)` / `reportMessage(_:)` helpers.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import LyrebirdSynth
|
||||
|
||||
public final class SnippetContext {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
//
|
||||
// C ABI signature of the snippet's exported entry point.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. The host
|
||||
/// passes a pointer to a `LiveSession` (or harness context) here; snippets need
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// from the opaque pointer the host hands in. The user's body is dropped in as
|
||||
// the function body.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
public enum SnippetHarness {
|
||||
|
||||
@@ -27,6 +27,7 @@ public enum SnippetHarness {
|
||||
/// `compileAndRun` is `@MainActor`).
|
||||
public static func wrap(userBody: String) -> WrappedSnippet {
|
||||
let preamble: String = """
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile
|
||||
|
||||
|
||||
@@ -12,9 +12,9 @@
|
||||
// `initialize` / `initialized`, `textDocument/didOpen` / `didChange`, and
|
||||
// `textDocument/completion`.
|
||||
//
|
||||
// macOS only — the whole live-compile surface shells out to the toolchain.
|
||||
// macOS/Linux only — the whole live-compile surface shells out to the toolchain.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// Nanoseconds in one second — for `Task.sleep`.
|
||||
@@ -80,8 +80,22 @@ public final class SourceKitLSPClient: @unchecked Sendable {
|
||||
/// Resolve `sourcekit-lsp` from the active toolchain via `xcrun`, falling
|
||||
/// back to the conventional Xcode path.
|
||||
private static func resolveExecutable() -> URL {
|
||||
// Guard the xcrun spawn: `xcrun` is macOS-only, and on Linux
|
||||
// `Process.run()` throws for a missing launch path while a following
|
||||
// `waitUntilExit()` on the never-started process BLOCKS FOREVER (a no-op
|
||||
// on macOS). Skip straight to the conventional path there, where the
|
||||
// toolchain ships `/usr/bin/sourcekit-lsp`.
|
||||
let xcrunPath: String = "/usr/bin/xcrun"
|
||||
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else {
|
||||
// No xcrun (Linux): prefer a `sourcekit-lsp` on $PATH (swiftly, a
|
||||
// custom toolchain, …) over the conventional /usr/bin location.
|
||||
if let onPath: String = livecompileExecutableOnPath("sourcekit-lsp") {
|
||||
return URL(fileURLWithPath: onPath)
|
||||
}
|
||||
return URL(fileURLWithPath: "/usr/bin/sourcekit-lsp")
|
||||
}
|
||||
let xcrun: Process = Process()
|
||||
xcrun.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")
|
||||
xcrun.executableURL = URL(fileURLWithPath: xcrunPath)
|
||||
xcrun.arguments = ["--find", "sourcekit-lsp"]
|
||||
let out: Pipe = Pipe()
|
||||
xcrun.standardOutput = out
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// Errors surfaced by ``SourceKitLSPClient``. macOS only.
|
||||
// Errors surfaced by ``SourceKitLSPClient``. macOS/Linux only.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// A failure from the `sourcekit-lsp` client.
|
||||
public enum SourceKitLSPError: Error, CustomStringConvertible {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// few hundred ms after ⌘↩, then the swap lands exactly on the downbeat rather
|
||||
// than whenever the compile happened to finish.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
// SwiftFormatter.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — snippet source formatting.
|
||||
//
|
||||
// Shells out to the toolchain's `swift-format` (the same way `LiveCompiler`
|
||||
// shells to `swiftc`) to pretty-print a snippet. macOS/Linux only — iOS cannot
|
||||
// exec subprocesses. Writes the source to a temp file and runs `swift-format format
|
||||
// <file>`, capturing stdout — avoids the write-stdin/read-stdout pipe deadlock
|
||||
// a streaming approach risks on large output.
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Stateless `swift-format` wrapper.
|
||||
public enum SwiftFormatter {
|
||||
|
||||
/// Format `source` and return the pretty-printed result. Runs synchronously
|
||||
/// (spawns `swift-format`); call off the main thread.
|
||||
///
|
||||
/// - Parameter source: Swift source to format. Top-level snippet code is
|
||||
/// accepted — `swift-format` formats whatever parses.
|
||||
/// - Returns: The formatted source.
|
||||
/// - Throws: ``SwiftFormatterError`` for a missing tool, a non-zero exit
|
||||
/// (typically a parse error), or an I/O failure.
|
||||
public static func format(source: String) throws -> String {
|
||||
let tool: String = try findSwiftFormat()
|
||||
|
||||
let id: String = UUID().uuidString.replacingOccurrences(of: "-", with: "")
|
||||
let workDir: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LyrebirdSwiftFormat-\(id)", isDirectory: true)
|
||||
let sourcePath: String = workDir.appendingPathComponent("Snippet.swift").path
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true)
|
||||
} catch {
|
||||
throw SwiftFormatterError.ioFailed("\(error)")
|
||||
}
|
||||
// Register cleanup as soon as the dir exists, so a later write failure
|
||||
// doesn't leak it.
|
||||
defer { try? FileManager.default.removeItem(at: workDir) }
|
||||
do {
|
||||
try source.write(toFile: sourcePath, atomically: true, encoding: .utf8)
|
||||
} catch {
|
||||
throw SwiftFormatterError.ioFailed("\(error)")
|
||||
}
|
||||
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: tool)
|
||||
process.arguments = ["format", sourcePath]
|
||||
let stdoutPipe: Pipe = Pipe()
|
||||
let stderrPipe: Pipe = Pipe()
|
||||
process.standardOutput = stdoutPipe
|
||||
process.standardError = stderrPipe
|
||||
do {
|
||||
try process.run()
|
||||
} catch {
|
||||
throw SwiftFormatterError.ioFailed("swift-format launch failed: \(error)")
|
||||
}
|
||||
// Drain stdout AND stderr concurrently before waiting. `swift-format` can
|
||||
// emit both a large formatted buffer and (on a broken snippet) a large
|
||||
// diagnostic stream; reading them sequentially would deadlock if the
|
||||
// stream we aren't reading yet fills its OS pipe buffer while the child
|
||||
// blocks writing to it.
|
||||
let outHandle: FileHandle = stdoutPipe.fileHandleForReading
|
||||
let errHandle: FileHandle = stderrPipe.fileHandleForReading
|
||||
let group: DispatchGroup = DispatchGroup()
|
||||
let drainQueue: DispatchQueue = DispatchQueue(
|
||||
label: "net.realizedsound.lyrebird.swift-format-drain",
|
||||
attributes: .concurrent
|
||||
)
|
||||
// Box the drained bytes in reference cells: on Linux the `DispatchQueue`
|
||||
// closures are `@Sendable` and cannot mutate a captured `var`. Each
|
||||
// closure writes its own box (no shared mutation), and `group.wait()`
|
||||
// fences before the reads below.
|
||||
let outBox: SwiftFormatterDataBox = SwiftFormatterDataBox()
|
||||
let errBox: SwiftFormatterDataBox = SwiftFormatterDataBox()
|
||||
group.enter()
|
||||
drainQueue.async { outBox.data = outHandle.readDataToEndOfFile(); group.leave() }
|
||||
group.enter()
|
||||
drainQueue.async { errBox.data = errHandle.readDataToEndOfFile(); group.leave() }
|
||||
group.wait()
|
||||
process.waitUntilExit()
|
||||
let outData: Data = outBox.data
|
||||
let errData: Data = errBox.data
|
||||
|
||||
guard process.terminationStatus == 0 else {
|
||||
let stderr: String = String(data: errData, encoding: .utf8) ?? ""
|
||||
throw SwiftFormatterError.formatFailed(exitCode: process.terminationStatus, stderr: stderr)
|
||||
}
|
||||
guard let formatted: String = String(data: outData, encoding: .utf8) else {
|
||||
throw SwiftFormatterError.ioFailed("swift-format produced non-UTF8 output")
|
||||
}
|
||||
return formatted
|
||||
}
|
||||
|
||||
/// Whether a `swift-format` executable is available on this machine.
|
||||
public static var isAvailable: Bool {
|
||||
(try? findSwiftFormat()) != nil
|
||||
}
|
||||
|
||||
// MARK: - Tool resolution
|
||||
|
||||
/// First-success search: `xcrun -f swift-format`, then hard-coded paths.
|
||||
static func findSwiftFormat() throws -> String {
|
||||
if let viaXcrun: String = swiftFormatViaXcrun() {
|
||||
return viaXcrun
|
||||
}
|
||||
let candidates: [String] = [
|
||||
"/usr/bin/swift-format",
|
||||
"/usr/local/bin/swift-format",
|
||||
"/opt/homebrew/bin/swift-format",
|
||||
]
|
||||
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
|
||||
return path
|
||||
}
|
||||
throw SwiftFormatterError.toolNotFound
|
||||
}
|
||||
|
||||
private static func swiftFormatViaXcrun() -> String? {
|
||||
let xcrunPath: String = "/usr/bin/xcrun"
|
||||
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: xcrunPath)
|
||||
process.arguments = ["-f", "swift-format"]
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -0,0 +1,20 @@
|
||||
// SwiftFormatterError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Errors raised while formatting snippet source with `swift-format`.
|
||||
public enum SwiftFormatterError: Error {
|
||||
/// No `swift-format` executable could be located (no Xcode / toolchain, or
|
||||
/// an older toolchain that predates the bundled formatter).
|
||||
case toolNotFound
|
||||
/// `swift-format` exited non-zero — usually a parse error in the source.
|
||||
case formatFailed(exitCode: Int32, stderr: String)
|
||||
/// A filesystem or process I/O failure.
|
||||
case ioFailed(String)
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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
|
||||
// typed.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
public struct WrappedSnippet: Equatable {
|
||||
public let source: String
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
// LinuxScratchView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Minimal Linux/GTK4 live-coding scratch surface. The macOS editor
|
||||
// (LyrebirdScratchView / NSTextView) is `#if os(macOS)`-gated elsewhere; this is
|
||||
// the SwiftOpenUI counterpart: a plain code editor + Run/Clear + a console,
|
||||
// driving a `LiveSession` (compile the snippet to a .so, dlopen it, run it). No
|
||||
// syntax highlighting / gutter / completion — that is the full-parity
|
||||
// GtkSourceView editor (a later step). `import LyrebirdUI` re-exports the
|
||||
// SwiftOpenUI View DSL + the GTK4 backend and provides `LyrebirdScopeView`.
|
||||
#if os(Linux)
|
||||
import Foundation
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile // LiveSession
|
||||
import LyrebirdUI
|
||||
|
||||
/// A seed snippet: the fastest path to sound — a bare generator graph via
|
||||
/// `context.play { … }` — plus a console line.
|
||||
public let lyrebirdLinuxScratchSeed: String = """
|
||||
// Edit, then Run. `context` is your live LiveSession. Ctrl+Space for completions.
|
||||
context.play { OscSin.Audio(freq: 330, mul: 0.15) }
|
||||
context.reportMessage("playing 330 Hz")
|
||||
"""
|
||||
|
||||
/// Observable state for the Linux scratch view: the running flag and the console
|
||||
/// log. The `LiveSession` compiles/runs off the main thread; results are folded
|
||||
/// back onto the main actor (== the GTK main loop) so the `@Observable` reads
|
||||
/// refresh the view.
|
||||
///
|
||||
/// `@unchecked Sendable`: main-thread-confined UI state plus an
|
||||
/// `@unchecked Sendable` `LiveSession`; the run closure hops to the main actor
|
||||
/// before touching `console` / `isRunning`.
|
||||
@Observable
|
||||
public final class LinuxScratchModel: @unchecked Sendable {
|
||||
|
||||
public var console: String = ""
|
||||
public var isRunning: Bool = false
|
||||
|
||||
/// The editor's document text and current selection. Owned by the model (not
|
||||
/// the view) so file open/save and the dirty flag have one source of truth.
|
||||
public var source: String
|
||||
public var selection: String = ""
|
||||
|
||||
/// Path of the file backing the document, or `nil` for an unsaved buffer.
|
||||
public var currentPath: String? = nil
|
||||
/// Set when the buffer has unsaved edits; drives the title's `●` marker.
|
||||
public var isDirty: Bool = false
|
||||
/// Suppresses dirty-marking while the model itself replaces the text (new /
|
||||
/// open), so a load doesn't immediately look unsaved.
|
||||
@ObservationIgnored private var suppressDirty: Bool = false
|
||||
|
||||
@ObservationIgnored public let session: LiveSession
|
||||
@ObservationIgnored public let completionService: SnippetCompletionService
|
||||
/// Imperative handle to push loaded text into the reused editor widget.
|
||||
@ObservationIgnored public let editor: CodeEditorController = CodeEditorController()
|
||||
|
||||
public init(session: LiveSession, initialSource: String = lyrebirdLinuxScratchSeed) {
|
||||
self.session = session
|
||||
self.source = initialSource
|
||||
self.completionService = SnippetCompletionService(session: session)
|
||||
}
|
||||
|
||||
/// The editor's two-way binding calls this; marks the buffer dirty unless the
|
||||
/// change came from a programmatic load. Ignores an unchanged value so a
|
||||
/// widget echo of the same text never flips the dirty flag — which also makes
|
||||
/// a load robust whether or not GtkSourceView delivers its change signal
|
||||
/// synchronously: `replaceDocument` has already set `source`, so the echoed
|
||||
/// value compares equal and returns here before touching `isDirty`.
|
||||
public func setSource(_ newValue: String) {
|
||||
guard newValue != source else { return }
|
||||
source = newValue
|
||||
if !suppressDirty { isDirty = true }
|
||||
}
|
||||
|
||||
/// A short title for the window/header: the filename (or `untitled.swift`)
|
||||
/// with a leading `●` when there are unsaved edits.
|
||||
public var displayTitle: String {
|
||||
let name: String = currentPath.map(Self.lastComponent) ?? "untitled.swift"
|
||||
return (isDirty ? "● " : "") + name
|
||||
}
|
||||
|
||||
/// Ctrl+Space completion source for the editor: the buffer text + caret
|
||||
/// (line, column) → sourcekit-lsp completions mapped to editor candidates.
|
||||
/// Errors (server hiccups) yield no candidates rather than surfacing.
|
||||
public var completionProvider: @Sendable (String, Int, Int) async -> [CodeCompletionItem] {
|
||||
let service: SnippetCompletionService = completionService
|
||||
return { (text: String, line: Int, column: Int) in
|
||||
let items: [LSPCompletionItem] = (try? await service.completions(
|
||||
userBody: text, line: line, character: column)) ?? []
|
||||
return items.map { (item: LSPCompletionItem) in
|
||||
CodeCompletionItem(label: item.label, insertText: item.insertText)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compile + run `source`. `additive` keeps the previous run's synths;
|
||||
/// otherwise they are cleared first. Non-blocking: swiftc runs off-main.
|
||||
public func run(source: String, additive: Bool) {
|
||||
guard !isRunning else { return }
|
||||
isRunning = true
|
||||
append(additive ? "▶ running (additive)…" : "▶ running…")
|
||||
let sess: LiveSession = session
|
||||
Task { [weak self] in
|
||||
do {
|
||||
_ = try await sess.compileAndRunAsync(source, additive: additive)
|
||||
let messages: [String] = sess.drainMessages()
|
||||
await self?.finish(ok: true, messages: messages, error: nil)
|
||||
} catch {
|
||||
let messages: [String] = sess.drainMessages()
|
||||
await self?.finish(ok: false, messages: messages, error: "\(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func clear() {
|
||||
console = ""
|
||||
}
|
||||
|
||||
/// Panic valve: stop and remove all snippet audio without tearing down the
|
||||
/// engine (``LiveSession/resetAll()``). Leaves the editor and session intact
|
||||
/// so the next Run starts clean.
|
||||
///
|
||||
/// Guarded by `isRunning` for the same reason the macOS host's
|
||||
/// `resetSession()` guards on `isCompiling`: `resetAll()`'s documented
|
||||
/// precondition forbids running it concurrently with an in-flight
|
||||
/// `compileAndRunAsync`, whose `clearTracked()`/`runEntry` interleave can
|
||||
/// leak a just-added synth. A no-op while a compile is running is the safe
|
||||
/// choice — the audio it starts is cleared by the next Stop.
|
||||
public func killAudio() {
|
||||
guard !isRunning else { return }
|
||||
session.resetAll()
|
||||
append("■ audio stopped")
|
||||
}
|
||||
|
||||
// MARK: - File open / save
|
||||
//
|
||||
// Snippets are plain Swift source, so a document is just a `.swift` text
|
||||
// file. The native `GtkFileDialog` (via `GTK4FileDialog`) picks the path;
|
||||
// its completion runs on the GTK main thread, same as these methods (they
|
||||
// are invoked from button actions), so the `@Observable` writes are safe.
|
||||
|
||||
/// Reset to a fresh unsaved buffer seeded with the starter snippet.
|
||||
public func newDocument() {
|
||||
replaceDocument(text: lyrebirdLinuxScratchSeed, path: nil)
|
||||
append("✎ new document")
|
||||
}
|
||||
|
||||
/// Present an Open dialog, then load the chosen file.
|
||||
public func openDocument() {
|
||||
GTK4FileDialog.open(title: "Open Lyrebird snippet") { [weak self] (path: String?) in
|
||||
guard let self, let path: String = path else { return }
|
||||
self.loadFile(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Load `path` into the editor (replacing the buffer).
|
||||
public func loadFile(_ path: String) {
|
||||
do {
|
||||
let text: String = try String(contentsOfFile: path, encoding: .utf8)
|
||||
replaceDocument(text: text, path: path)
|
||||
append("📂 opened " + Self.lastComponent(path))
|
||||
} catch {
|
||||
append("✗ open failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Save to the current path, or fall through to Save As when there is none.
|
||||
public func save() {
|
||||
if let path: String = currentPath {
|
||||
writeFile(path)
|
||||
} else {
|
||||
saveAs()
|
||||
}
|
||||
}
|
||||
|
||||
/// Present a Save dialog (pre-filled with the current name), then write.
|
||||
public func saveAs() {
|
||||
let suggested: String = currentPath.map(Self.lastComponent) ?? "untitled.swift"
|
||||
GTK4FileDialog.save(title: "Save Lyrebird snippet", suggestedName: suggested) { [weak self] (path: String?) in
|
||||
guard let self, let path: String = path else { return }
|
||||
self.writeFile(path)
|
||||
}
|
||||
}
|
||||
|
||||
private func writeFile(_ path: String) {
|
||||
do {
|
||||
try source.write(toFile: path, atomically: true, encoding: .utf8)
|
||||
currentPath = path
|
||||
isDirty = false
|
||||
append("💾 saved " + Self.lastComponent(path))
|
||||
} catch {
|
||||
append("✗ save failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the buffer with `text` and adopt `path`, without marking dirty.
|
||||
/// Pushes into the live widget too — the reused editor doesn't otherwise
|
||||
/// mirror an external text change (see `CodeEditorController`).
|
||||
private func replaceDocument(text: String, path: String?) {
|
||||
suppressDirty = true
|
||||
source = text
|
||||
editor.setText(text)
|
||||
currentPath = path
|
||||
isDirty = false
|
||||
suppressDirty = false
|
||||
}
|
||||
|
||||
private static func lastComponent(_ path: String) -> String {
|
||||
(path as NSString).lastPathComponent
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func finish(ok: Bool, messages: [String], error: String?) {
|
||||
for message: String in messages {
|
||||
append(message)
|
||||
}
|
||||
if let error: String = error {
|
||||
append("✗ " + error)
|
||||
} else {
|
||||
append("✓ done")
|
||||
}
|
||||
isRunning = false
|
||||
}
|
||||
|
||||
private func append(_ line: String) {
|
||||
console += (console.isEmpty ? "" : "\n") + line
|
||||
}
|
||||
}
|
||||
|
||||
/// The minimal Linux scratch editor: a `TextEditor` over the snippet source,
|
||||
/// Run (fresh / additive) + Clear buttons, a live oscilloscope of the session's
|
||||
/// output, and a console. Host it in a `LyrebirdWindow` or a `WindowGroup`.
|
||||
public struct LyrebirdScratchLinuxView: View {
|
||||
|
||||
@State private var model: LinuxScratchModel
|
||||
|
||||
/// - Parameters:
|
||||
/// - session: The `LiveSession` that compiles + runs snippets.
|
||||
/// - initialSource: Seed editor text. Defaults to a play-a-tone snippet.
|
||||
public init(session: LiveSession, initialSource: String = lyrebirdLinuxScratchSeed) {
|
||||
_model = State(wrappedValue: LinuxScratchModel(session: session, initialSource: initialSource))
|
||||
}
|
||||
|
||||
/// Host an externally-owned model — used when the app also wires the model's
|
||||
/// file actions into the menu bar (`.commands`), which needs the same
|
||||
/// instance the view renders.
|
||||
public init(model: LinuxScratchModel) {
|
||||
_model = State(wrappedValue: model)
|
||||
}
|
||||
|
||||
/// What Run evaluates: the selection if the user has selected something
|
||||
/// (non-whitespace), otherwise the whole document.
|
||||
private var evaluationSource: String {
|
||||
model.selection.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
? model.source : model.selection
|
||||
}
|
||||
|
||||
/// Append a hint to the Run buttons when a selection is what will run.
|
||||
private func runLabel(base: String) -> String {
|
||||
model.selection.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
? base
|
||||
: base + " — selection"
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text("Lyrebird — Linux scratch — " + model.displayTitle)
|
||||
|
||||
// File actions (New / Open… / Save / Save As…) live in the menu bar
|
||||
// with Ctrl+N/O/S accelerators — see `lyrebirdScratchFileCommands`,
|
||||
// wired via `.commands` on the demo's WindowGroup. A snippet is plain
|
||||
// Swift source, so a document is just a `.swift` text file, saved and
|
||||
// loaded through the native GtkFileDialog.
|
||||
|
||||
// GtkSourceView-backed editor: Swift syntax highlighting + gutter.
|
||||
// The selection is mirrored out so Run can evaluate just the selected
|
||||
// lines (like the macOS editor); with nothing selected it runs the
|
||||
// whole buffer. The controller lets a file open replace the buffer.
|
||||
CodeEditor(
|
||||
text: Binding(get: { model.source }, set: { model.setSource($0) }),
|
||||
selection: Binding(get: { model.selection }, set: { model.selection = $0 }),
|
||||
controller: model.editor,
|
||||
completionProvider: model.completionProvider
|
||||
)
|
||||
.frame(height: 260)
|
||||
|
||||
HStack(spacing: 8) {
|
||||
Button {
|
||||
model.run(source: evaluationSource, additive: false)
|
||||
} label: {
|
||||
Text(model.isRunning ? "Running…" : runLabel(base: "Run (fresh)"))
|
||||
}
|
||||
Button {
|
||||
model.run(source: evaluationSource, additive: true)
|
||||
} label: {
|
||||
Text(runLabel(base: "Run (additive)"))
|
||||
}
|
||||
Button {
|
||||
model.killAudio()
|
||||
} label: {
|
||||
Text("Stop audio")
|
||||
}
|
||||
Button {
|
||||
model.clear()
|
||||
} label: {
|
||||
Text("Clear")
|
||||
}
|
||||
}
|
||||
|
||||
if let scope: ScopeCapture = model.session.scope {
|
||||
LyrebirdScopeView(capture: scope)
|
||||
}
|
||||
|
||||
Text("Console")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
Text(model.console)
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.frame(height: 140)
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
|
||||
/// The scratchpad's File menu commands — New / Open… / Save / Save As… — with
|
||||
/// Ctrl+N / Ctrl+O / Ctrl+S / Ctrl+Shift+S accelerators (SwiftOpenUI maps the
|
||||
/// `.command` modifier to Ctrl on Linux). Attach to the hosting `WindowGroup`
|
||||
/// with `.commands { lyrebirdScratchFileCommands(model: model) }`; SwiftOpenUI
|
||||
/// declares commands on the Scene, not inside a View, so the app must own the
|
||||
/// model and pass the same instance to `LyrebirdScratchLinuxView(model:)`.
|
||||
@CommandsBuilder
|
||||
public func lyrebirdScratchFileCommands(model: LinuxScratchModel) -> some Commands {
|
||||
CommandGroup(replacing: .newItem) {
|
||||
CommandMenuItem("New", shortcut: KeyboardShortcut("n")) { model.newDocument() }
|
||||
CommandMenuItem("Open…", shortcut: KeyboardShortcut("o")) { model.openDocument() }
|
||||
}
|
||||
CommandGroup(replacing: .saveItem) {
|
||||
CommandMenuItem("Save", shortcut: KeyboardShortcut("s")) { model.save() }
|
||||
CommandMenuItem("Save As…", shortcut: KeyboardShortcut("s", modifiers: [.command, .shift])) { model.saveAs() }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -15,9 +15,19 @@ Compile diagnostics from a failing snippet are parsed by `DiagnosticParser`
|
||||
and rendered beneath the editor with line numbers already remapped from the wrapped
|
||||
source back to the user's snippet coordinates.
|
||||
|
||||
The view is macOS-only — `LyrebirdLiveCompile` shells out to `swiftc`, which is
|
||||
unavailable on iOS. The nested `LiveCompile/` sub-package declares
|
||||
`platforms: [.macOS(.v15)]` and cannot be added to an iOS target.
|
||||
`LyrebirdScratchView` (the `NSTextView` editor described here) is macOS-only, but
|
||||
the scratchpad itself runs on **Linux** too, through a GTK4 counterpart —
|
||||
`LyrebirdScratchLinuxView` / `LinuxScratchModel` on the SwiftOpenUI backend. Both
|
||||
drive the same `LyrebirdLiveCompile` engine; only the editor UI differs. See
|
||||
[Linux (GTK4)](#linux-gtk4) below. What is genuinely unavailable is **iOS**:
|
||||
`LyrebirdLiveCompile` shells out to `swiftc`, which iOS does not provide.
|
||||
|
||||
> Note: **Swift mode needs a Swift toolchain** (Xcode or the Command Line Tools) —
|
||||
> it compiles snippets with `swiftc`. At launch the app probes for one
|
||||
> (`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
|
||||
|
||||
@@ -45,6 +55,8 @@ window.open {
|
||||
| ⌘⇧↩ | Compile + run the whole buffer additively. Keeps previously played synths in the engine. |
|
||||
| ⌘E | Compile + run just the **selection**, always additively — adds it to whatever is already playing. No-op with no selection. Works in both Swift and Graph DSL modes. |
|
||||
| Esc / F5 | Invoke code completion at the caret (Swift mode). Manual only — never auto-triggered on `.`. See the Code completion section below. |
|
||||
| ⌥⌘F | **Format Code** — pretty-print the buffer with the toolchain's `swift-format`. No-op on a blank buffer; a parse error is logged to the console and leaves the text untouched. |
|
||||
| ⌥⌘R | **Render to File…** — bounce the selection (or the whole buffer) to an audio file offline instead of playing it live. The save dialog carries a **Format** popup (WAV 32-bit float / 16-bit / 24-bit, AIFF, CAF, RF64 WAV for files past 4 GB, or compressed AAC / Apple Lossless `.m4a`) and a **Duration** field; it remembers the last format. Renders faster-than-real-time via `NRTDriver` at the live engine's sample rate and channel count, then reveals the file in Finder. Only **sample-clock** timing renders — see *NRT: sample-clock timing only* under Functional snippets & scheduling. |
|
||||
|
||||
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
|
||||
``LyrebirdScratchModel/clearTracked()`` — a full reset that removes both the
|
||||
@@ -115,8 +127,12 @@ Oldest first, auto-scrolled to the newest, capped at
|
||||
## Functional snippets & scheduling
|
||||
|
||||
A Swift-mode snippet is **real Swift**, not just a graph expression — loops,
|
||||
`let` bindings, functions, arrays all work. The one rule for anything
|
||||
time-based: **schedule** events, don't `Thread.sleep`. The snippet body runs
|
||||
`let` bindings, functions, arrays all work. The harness preamble imports
|
||||
**Foundation**, `LyrebirdSynth`, and `LyrebirdLiveCompile`, so `pow`, `sin`,
|
||||
`sqrt`, `Date`, and the whole generator library are in scope without any
|
||||
`import` — which is good, because a snippet **can't** declare one (its body is
|
||||
wrapped inside the entry function, and `import` is only legal at file scope). The
|
||||
one rule for anything time-based: **schedule** events, don't `Thread.sleep`. The snippet body runs
|
||||
once, synchronously, on the main thread; sleeping in a loop would freeze the UI
|
||||
(the audio thread is separate, but the editor isn't). Use
|
||||
`engine.schedule(_:after:)` for sample-accurate timing instead.
|
||||
@@ -142,9 +158,96 @@ context.reportMessage("scheduled 10 tones")
|
||||
|
||||
The loop returns immediately after scheduling all ten adds; the engine fires
|
||||
each at its time (`0, 0.35, 0.70 … s`). A 0.2 s tone with 0.35 s spacing leaves a
|
||||
short gap between each. (This is *fire-and-forget* scheduling for a fixed
|
||||
sequence; for an open-ended or reactive sequence — a repeating pattern, tempo
|
||||
following — reach for `LyrebirdRoutine` / `LyrebirdClock` on the language side.)
|
||||
short gap between each. This is *fire-and-forget* scheduling for a fixed sequence.
|
||||
|
||||
### The one rule: retention
|
||||
|
||||
The snippet body runs **once, synchronously, then returns**. Anything that fires
|
||||
*later* must be held by something that outlives the snippet — the snippet itself
|
||||
is transient. Three things self-sustain, and everything below builds on them:
|
||||
|
||||
- **`engine.schedule(…)`** — the engine holds the pending event.
|
||||
- **`LyrebirdRoutine` / `LyrebirdTask`** — the routine runs on a dedicated
|
||||
background thread that retains it until the body finishes or `stop()` is called.
|
||||
- **`context.play(…)` synths** — the session tracks them (and named slots).
|
||||
|
||||
A `Thread.sleep` or busy `while` loop in the snippet *body* is the anti-pattern:
|
||||
it runs on the **main thread**, so it freezes the editor UI (the RT audio thread
|
||||
keeps going, but you can't type). Anything that *waits* belongs on a routine's
|
||||
background thread, not in the body.
|
||||
|
||||
### Mechanisms
|
||||
|
||||
| Mechanism | Use for | Timing API |
|
||||
|---|---|---|
|
||||
| `context.engine.schedule(_:after:)` / `schedule(_:at:)` | One-shot "play this at time T" | Seconds, or a `SampleTime` |
|
||||
| `LyrebirdRoutine` | A sequence with pauses; open-ended loops | `ctx.wait(seconds:)` / `wait(beats:)` / `waitUntil(sampleTime:)` |
|
||||
| `LyrebirdTask` | Same as a routine but **pausable** (`pause()` / `resume()`) | same as routine |
|
||||
| `LyrebirdClock` | Beat → sample-time reference | `clock.sampleTime(beat:)`, `nextBeat(after:)` → feed `schedule(_:at:)` or `ctx.waitUntil(sampleTime:)` |
|
||||
| Trigger generators (`Impulse` → `Demand` / `TriggeredRandom` / gate) | Timing *inside* the audio graph — arps, gated LFOs, step patterns | Sample-accurate, in the running synth |
|
||||
| `LyrebirdProcess` / `LyrebirdEventList`, `Score` / `ScorePlayer` | Structured / pre-composed timelines | Event lists |
|
||||
|
||||
All of these are reachable from a snippet through `context.engine` and the public
|
||||
`LyrebirdSynth` types — nothing extra is injected.
|
||||
|
||||
### Waiting: `LyrebirdRoutine`
|
||||
|
||||
For "play N things with a pause between each" — the reactive counterpart to the
|
||||
fire-and-forget loop above — use a routine. Its body runs on a background thread
|
||||
(so `wait` never freezes the UI), and `routine.start(engine:)` keeps it alive
|
||||
after the snippet returns:
|
||||
|
||||
```swift
|
||||
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0]
|
||||
let routine = LyrebirdRoutine { ctx in
|
||||
for freq in scale {
|
||||
ctx.add(ClosureSynthesizer {
|
||||
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
|
||||
* OscSin.Audio(freq: freq)
|
||||
})
|
||||
try ctx.wait(seconds: 0.3) // background-thread wait — UI stays live
|
||||
}
|
||||
}
|
||||
routine.start(engine: context.engine) // self-sustaining; survives the snippet
|
||||
```
|
||||
|
||||
`ctx.add(_:)` hops to the main-actor `engine.add` for you. `ctx.wait(beats:)`
|
||||
waits at `ctx.tempo` (default 120 BPM; set `ctx.tempo = …` in the body to change
|
||||
it); `ctx.waitUntil(sampleTime:)` waits to an absolute engine time, which is where
|
||||
`LyrebirdClock.sampleTime(beat:)` comes in for on-grid spacing. Call
|
||||
`routine.stop()` (e.g. from a later ⌘E) to cancel — the body exits at its next
|
||||
`wait`.
|
||||
|
||||
### Caveats
|
||||
|
||||
- **Never block the main thread** — no `Thread.sleep` / busy loops in the snippet
|
||||
body. Wait on a routine instead.
|
||||
- `Task { }` / `DispatchQueue.main.asyncAfter` *technically* work (they fire later
|
||||
on main and the session keeps `context` alive), but prefer `engine.schedule`
|
||||
(sample-accurate) or a routine (proper timed waits) over ad-hoc dispatch.
|
||||
- A `LyrebirdClock` used only to compute schedule times is fine to let go; if
|
||||
you need it *driving* something over time, a routine's thread keeps it alive.
|
||||
|
||||
### NRT: sample-clock timing only
|
||||
|
||||
**Render to File (⌥⌘R) is offline.** The `NRTDriver` renders faster than real
|
||||
time in a tight **synchronous burst** — 10 s of audio in a fraction of a second —
|
||||
and it does **not** wait for anything on the wall clock. So only timing expressed
|
||||
in **engine / sample time** survives a render; wall-clock timing silently drops out.
|
||||
|
||||
| Mechanism | Live | Render to File |
|
||||
|---|---|---|
|
||||
| `engine.schedule(_:after:/at:)` | ✅ | ✅ — fires at its sample time as blocks render |
|
||||
| In-graph triggers (`Impulse` → `Demand` / gates) | ✅ | ✅ — per-sample, driven by the render itself (best for NRT) |
|
||||
| `LyrebirdClock.sampleTime(beat:)` → `schedule(_:at:)` | ✅ | ✅ — pure beat→sample math |
|
||||
| `LyrebirdRoutine` / `LyrebirdTask` (`wait(seconds:/beats:)`) | ✅ | ❌ — **wall-clock sleeps on a background thread; the render finishes before they fire, so their `ctx.add`s never make the file** |
|
||||
| Real-time playback (`playTimeline`, live `ScorePlayer`) | ✅ | ❌ — the sample-accurate scheduling underneath is fine; the wall-clock playback driver isn't |
|
||||
|
||||
Rule of thumb: if the timing is a routine's `wait`, it's for **live** play; to make
|
||||
the same idea render, re-express it as `engine.schedule(_:after:)` (fixed
|
||||
sequence) or an `Impulse`-driven graph (periodic / patterned). This is a real
|
||||
footgun — routine timing works when you play it and silently produces an empty or
|
||||
truncated bounce when you render it.
|
||||
|
||||
> Note: **Graph DSL mode** evaluates only generator-graph expressions — no loops
|
||||
> or scheduling. Functional code like the above needs **Swift mode**.
|
||||
@@ -289,6 +392,37 @@ through its own diagnostics.
|
||||
> which turns a benign ObjC class-duplication warning into a hard cast crash when
|
||||
> a snippet is `dlopen`'d.
|
||||
|
||||
## Compile artifacts & Application Support
|
||||
|
||||
Swift-mode compilation points `swiftc` at the Lyrebird module artifacts: the
|
||||
swiftmodules, the Lyrebird dylibs, and the C-shim (`LyrebirdC`) Clang module map.
|
||||
In a dev checkout those live in the SPM build dir under `~/Documents`, so a
|
||||
non-sandboxed host — and the `swiftc` subprocess it spawns — trips the macOS
|
||||
"wants to access your Documents folder" permission gate. (The scratch/compile
|
||||
temp dirs use `/var/folders/…` and are never the cause.)
|
||||
|
||||
``LiveSession/stageArtifacts(from:to:)`` copies the minimal set into
|
||||
`~/Library/Application Support/LyrebirdScratch/LiveCompile/` — an ungated
|
||||
location — and **rewrites the C module map's absolute umbrella-header path** to a
|
||||
staged copy of the header, so the staged directory is a fully self-contained
|
||||
compile root. ``LiveSession/defaultImportPaths()`` / `defaultLibrarySearchPaths()`
|
||||
/ `defaultRpaths()` then prefer the staged dir when it is populated. Staging is
|
||||
idempotent (a receipt file skips an unchanged source) and best-effort (falls back
|
||||
to the build dir on any failure). A host calls it once before constructing the
|
||||
session:
|
||||
|
||||
```swift
|
||||
LiveSession.stageArtifacts() // stage into App Support
|
||||
let session = LiveSession(engine: engine) // defaults resolve to the staged dir
|
||||
```
|
||||
|
||||
For a **standalone** app, ship the artifacts inside the bundle at
|
||||
`Contents/Resources/LyrebirdArtifacts` (name = ``LiveSession/bundledArtifactsDirName``);
|
||||
``LiveSession/artifactSourceDir()`` prefers that over the build dir, so a shipped
|
||||
`LyrebirdScratch.app` in `/Applications` stages without ever reading a
|
||||
permission-gated folder. In a dev checkout the one-time stage copy still reads
|
||||
the build dir under `~/Documents`; every later launch reuses the staged copy.
|
||||
|
||||
## Code completion
|
||||
|
||||
Swift code completion is provided by the toolchain's `sourcekit-lsp`, driven over
|
||||
@@ -311,9 +445,39 @@ row in the wrapped document. Completion is Swift-mode only — graph-DSL mode is
|
||||
interpreted and needs no compiler — and best-effort: any LSP failure yields no
|
||||
candidates rather than an error.
|
||||
|
||||
## Linux (GTK4)
|
||||
|
||||
On Linux the scratchpad is `LyrebirdScratchLinuxView`, driven by
|
||||
`LinuxScratchModel`, on the GTK4 SwiftOpenUI backend (re-exported through
|
||||
`LyrebirdUI`). It runs the same `LiveSession` compile→`dlopen`→run path as the
|
||||
macOS view; the difference is the editor and its chrome:
|
||||
|
||||
- **Editor** — a `GtkSourceView` with Swift syntax highlighting, a line-number
|
||||
gutter, and auto-indent (needs `libgtksourceview-5-dev`).
|
||||
- **Completion** — **Ctrl+Space** at the caret shows sourcekit-lsp completions,
|
||||
filtered by the identifier prefix already typed.
|
||||
- **Run** — a *Run (fresh)* button clears the previous snippet's synths; *Run
|
||||
(additive)* layers on top. Selecting one or more lines evaluates just those
|
||||
(the selection is mirrored out of the editor).
|
||||
- **Stop audio** — a panic button calling ``LiveSession/resetAll()``.
|
||||
- **Live scope** — a `LyrebirdScopeView` of the session's output.
|
||||
- **Save / load** — a native File menu (`New`, `Open…`, `Save`, `Save As…`) with
|
||||
`Ctrl+N` / `Ctrl+O` / `Ctrl+S` / `Ctrl+Shift+S` accelerators, backed by
|
||||
`GtkFileDialog`. Snippets are plain `.swift` files; `LinuxScratchModel` tracks
|
||||
`currentPath` / `isDirty` and surfaces a `●` marker in the title. The File menu
|
||||
commands are provided by `lyrebirdScratchFileCommands(model:)`, attached to the
|
||||
hosting `WindowGroup` with `.commands` (SwiftOpenUI declares commands on the
|
||||
Scene, so the app owns the model and shares it with
|
||||
`LyrebirdScratchLinuxView(model:)`).
|
||||
|
||||
`LyrebirdScratchLinuxDemo` is the runnable entry point. Because a snippet links
|
||||
the engine's dynamic libraries, run `swift build` in `LiveCompile/` before
|
||||
`swift run LyrebirdScratchLinuxDemo`. See `LINUX_README.md` for the full setup.
|
||||
|
||||
## Limitations
|
||||
|
||||
- macOS only.
|
||||
- Snippet compilation shells out to `swiftc`, so the scratchpad is desktop-only
|
||||
(macOS and Linux); it is unavailable on iOS.
|
||||
- Syntax highlighting is a lightweight built-in lexer (`ScratchSwiftTokenizer`) —
|
||||
approximate by design, not a full parser. Completion (above) uses the real
|
||||
compiler via sourcekit-lsp; the two are independent.
|
||||
|
||||
@@ -28,7 +28,7 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
|
||||
/// Construct the full menu bar (App / File / Edit / Run / View / Window /
|
||||
/// Help) and assign it to `NSApplication.shared.mainMenu`.
|
||||
public func installMainMenu(appName: String = "LyrebirdScratchDemo") {
|
||||
public func installMainMenu(appName: String = "LyrebirdScratch") {
|
||||
let mainMenu: NSMenu = NSMenu()
|
||||
|
||||
mainMenu.addItem(appMenuItem(appName: appName))
|
||||
@@ -39,6 +39,11 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
mainMenu.addItem(windowMenuItem())
|
||||
|
||||
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
|
||||
@@ -135,6 +140,12 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
keyEquivalent: "f")
|
||||
find.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
|
||||
menu.addItem(find)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let format: NSMenuItem = target(NSMenuItem(title: "Format Code",
|
||||
action: #selector(formatCode(_:)),
|
||||
keyEquivalent: "f"))
|
||||
format.keyEquivalentModifierMask = [.command, .option]
|
||||
menu.addItem(format)
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
@@ -156,6 +167,12 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
action: #selector(runSelection(_:)),
|
||||
keyEquivalent: "e")))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let render: NSMenuItem = target(NSMenuItem(title: "Render to File…",
|
||||
action: #selector(renderToFile(_:)),
|
||||
keyEquivalent: "r"))
|
||||
render.keyEquivalentModifierMask = [.command, .option]
|
||||
menu.addItem(render)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
|
||||
action: #selector(clearSynths(_:)),
|
||||
keyEquivalent: "k")))
|
||||
@@ -231,6 +248,12 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
case #selector(resetSession(_:)):
|
||||
// Don't tear the session down mid-compile.
|
||||
return !model.isCompiling
|
||||
case #selector(formatCode(_:)):
|
||||
// Not mid-compile; the model's formatter no-ops on a blank buffer.
|
||||
return !model.isCompiling
|
||||
case #selector(renderToFile(_:)):
|
||||
// Needs an evaluatable buffer and no compile/render in flight.
|
||||
return model.reevalState.canEvaluate
|
||||
default:
|
||||
return true
|
||||
}
|
||||
@@ -300,6 +323,44 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
Task { @MainActor in _ = await model.runSelection() }
|
||||
}
|
||||
|
||||
@objc private func formatCode(_ sender: Any?) {
|
||||
Task { @MainActor in await model.formatBuffer() }
|
||||
}
|
||||
|
||||
@objc private func renderToFile(_ sender: Any?) {
|
||||
// Single save dialog: an accessory view carries the format popup + duration,
|
||||
// and keeps the filename extension in sync with the chosen container.
|
||||
let defaultRenderDuration: Double = 5.0
|
||||
let panel: NSSavePanel = NSSavePanel()
|
||||
panel.message = "Render the snippet (or selection) to an audio file"
|
||||
let accessory: RenderOptionsAccessory = RenderOptionsAccessory(
|
||||
baseName: "render", initialDuration: defaultRenderDuration, savePanel: panel
|
||||
)
|
||||
panel.accessoryView = accessory
|
||||
|
||||
guard panel.runModal() == .OK, let chosenURL: URL = panel.url else { return }
|
||||
|
||||
guard let duration: Double = accessory.durationSeconds else {
|
||||
let invalid: NSAlert = NSAlert()
|
||||
invalid.messageText = "Invalid duration"
|
||||
invalid.informativeText = "Enter a positive number of seconds (e.g. 5.0)."
|
||||
invalid.runModal()
|
||||
return
|
||||
}
|
||||
|
||||
let format: AudioFileFormat = accessory.selectedFormat
|
||||
// This is the source of truth for the final extension: force it to match the
|
||||
// chosen format so a hand-typed name with the wrong (or no) extension still
|
||||
// produces a correctly-named file. (The accessory's own panel-name sync is a
|
||||
// live-preview convenience; enforcement happens here.)
|
||||
let url: URL = chosenURL.deletingPathExtension().appendingPathExtension(format.fileExtension)
|
||||
|
||||
Task { @MainActor in
|
||||
let ok: Bool = await model.renderToFile(url: url, format: format, duration: duration)
|
||||
if ok { NSWorkspace.shared.activateFileViewerSelecting([url]) }
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func resetSession(_ sender: Any?) {
|
||||
model.resetSession()
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import Foundation
|
||||
import CoreGraphics
|
||||
import LyrebirdSynth
|
||||
// Re-exported so consumers that link only the `LyrebirdLiveCompileUI` product
|
||||
// (e.g. the LyrebirdScratchDemo app) get the `LyrebirdLiveCompile` API
|
||||
// (e.g. the LyrebirdScratch app) get the `LyrebirdLiveCompile` API
|
||||
// (`LiveSession`, …) without separately linking the `LyrebirdLiveCompile`
|
||||
// dynamic product — which clashes in Xcode with the static target embed.
|
||||
@_exported import LyrebirdLiveCompile
|
||||
@@ -516,6 +516,113 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
///
|
||||
/// No-op while a compile is in flight (matching the run methods' guard) — a
|
||||
/// reset must not tear the session down under an active `compileAndRunAsync`.
|
||||
/// Pretty-print the buffer with `swift-format` (off the main thread),
|
||||
/// replacing the text on success. Logs the outcome to the console; on a
|
||||
/// parse error or missing toolchain the buffer is left untouched.
|
||||
public func formatBuffer() async {
|
||||
guard !isCompiling else { return }
|
||||
let source: String = text
|
||||
guard !LyrebirdScratchModel.isBlank(source) else { return }
|
||||
// Hold the busy flag across the subprocess round-trip so a second Format
|
||||
// (or a Run) can't overlap, and re-check the buffer before applying: the
|
||||
// user may keep typing while `swift-format` runs, and a result computed
|
||||
// from the now-stale `source` must not clobber those edits. `reevalState`
|
||||
// goes `.compiling` too so the Run/Render menu items (validated on
|
||||
// `reevalState.canEvaluate`) actually disable during the format.
|
||||
isCompiling = true
|
||||
reevalState = .compiling
|
||||
defer {
|
||||
isCompiling = false
|
||||
reevalState = derivedIdleState()
|
||||
}
|
||||
do {
|
||||
let formatted: String = try await Task.detached(priority: .userInitiated) {
|
||||
try SwiftFormatter.format(source: source)
|
||||
}.value
|
||||
guard text == source else {
|
||||
appendConsole(.error, "Buffer changed during formatting — result discarded.")
|
||||
return
|
||||
}
|
||||
if formatted != source {
|
||||
text = formatted
|
||||
}
|
||||
appendConsole(.info, "Formatted.")
|
||||
} catch {
|
||||
appendConsole(.error, "Format failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Render the current selection (or the whole buffer when nothing is
|
||||
/// selected) to an audio file, offline. Builds the snippet graph on a
|
||||
/// throwaway engine driven by an `NRTDriver` — matching the live engine's
|
||||
/// sample rate / channel count / bus layout — then renders `duration`
|
||||
/// seconds off the main thread (`NRTDriver.start()` blocks). Logs the
|
||||
/// outcome to the console.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - url: Destination file. Its extension should match `format`.
|
||||
/// - format: Container and PCM encoding (``AudioFileFormat``). Defaults to
|
||||
/// `.cafFloat32`. RF64/CAF are uncapped; plain WAV/AIFF throw past 4 GB.
|
||||
/// - duration: Render length in seconds. Must be finite and > 0.
|
||||
/// - Returns: `true` when the file was rendered (so the caller can reveal it).
|
||||
@discardableResult
|
||||
public func renderToFile(
|
||||
url: URL,
|
||||
format: AudioFileFormat = .cafFloat32,
|
||||
duration: Double
|
||||
) async -> Bool {
|
||||
guard !isCompiling else { return false }
|
||||
guard duration > 0, duration.isFinite else {
|
||||
appendConsole(.error, "Render duration must be a positive number of seconds.")
|
||||
return false
|
||||
}
|
||||
let code: String = hasSelection ? selectionText : text
|
||||
guard !LyrebirdScratchModel.isBlank(code) else {
|
||||
appendConsole(.error, "Nothing to render.")
|
||||
return false
|
||||
}
|
||||
// Gate the Run/Render menu items (validated on `reevalState.canEvaluate`)
|
||||
// and any re-entrancy for the render's duration.
|
||||
isCompiling = true
|
||||
reevalState = .compiling
|
||||
defer {
|
||||
isCompiling = false
|
||||
reevalState = derivedIdleState()
|
||||
}
|
||||
|
||||
let live: SynthesisEngine = session.engine
|
||||
let offline: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: live.blockSize,
|
||||
controlBlockSize: live.controlBlockSize,
|
||||
sampleRate: live.sampleRate,
|
||||
numOutputChannels: live.numOutputChannels,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: live.numAudioBuses,
|
||||
numControlBuses: live.numControlBuses,
|
||||
driver: NRTDriver(outputURL: url, duration: duration, format: format)
|
||||
)
|
||||
let offlineSession: LiveSession = LiveSession(engine: offline, attachScope: false)
|
||||
do {
|
||||
// Build the graph on the offline engine (compile off-main, add on main).
|
||||
try await offlineSession.compileAndRunAsync(code, additive: true)
|
||||
// Render synchronously, off the main thread; NRTDriver writes the CAF.
|
||||
// `stop()` runs inside the detached task (where `offline` lives): the
|
||||
// driver returns with the engine still `isRunning`, and only `stop()`
|
||||
// drains the node tree — without it every rendered graph leaks
|
||||
// (matches EngineHost's NRT job teardown). Keeping it here also avoids
|
||||
// a cross-actor use of the non-Sendable engine after the detached run.
|
||||
try await Task.detached(priority: .userInitiated) {
|
||||
defer { offline.stop() }
|
||||
try offline.start()
|
||||
}.value
|
||||
appendConsole(.info, "Rendered \(String(format: "%.2f", duration)) s → \(url.lastPathComponent)")
|
||||
return true
|
||||
} catch {
|
||||
appendConsole(.error, "Render failed: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
public func resetSession() {
|
||||
guard !isCompiling else { return }
|
||||
session.resetAll()
|
||||
|
||||
@@ -58,9 +58,35 @@ import LyrebirdLiveCompile
|
||||
public struct LyrebirdScratchView: View {
|
||||
|
||||
@StateObject private var model: LyrebirdScratchModel
|
||||
@State private var engineTick: Int = 0
|
||||
/// Snapshot of the engine's non-`@Published` live stats, refreshed on the
|
||||
/// heartbeat. Bound in place by the status rows — deliberately NOT via
|
||||
/// `.id(tick)`, which forces a subview teardown/rebuild every tick and churns
|
||||
/// the surrounding layout, nudging the editor's scroll position ("screen
|
||||
/// jumping" while scrolled down). Updating an `@State` value re-renders the
|
||||
/// labels in place with stable identity, so the layout stays put.
|
||||
@State private var stats: EngineStats = EngineStats()
|
||||
private let engineRefresh = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
|
||||
|
||||
/// Non-`@Published` engine values polled on the heartbeat.
|
||||
private struct EngineStats: Equatable {
|
||||
var isRunning: Bool = false
|
||||
var averageCPU: Double = 0
|
||||
var peakCPU: Double = 0
|
||||
var synthesizerCount: Int = 0
|
||||
var groupCount: Int = 0
|
||||
}
|
||||
|
||||
private func snapshotStats() -> EngineStats {
|
||||
let e: SynthesisEngine = model.session.engine
|
||||
return EngineStats(
|
||||
isRunning: e.isRunning,
|
||||
averageCPU: e.averageCPU,
|
||||
peakCPU: e.peakCPU,
|
||||
synthesizerCount: e.synthesizerCount,
|
||||
groupCount: e.groupCount
|
||||
)
|
||||
}
|
||||
|
||||
/// Construct with a fresh `LyrebirdScratchModel` wrapping `session`.
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -99,7 +125,8 @@ public struct LyrebirdScratchView: View {
|
||||
model.session.prewarm()
|
||||
}
|
||||
.onReceive(engineRefresh) { _ in
|
||||
engineTick &+= 1
|
||||
let next: EngineStats = snapshotStats()
|
||||
if next != stats { stats = next }
|
||||
// Settle a `.queued` readiness badge once its swap has fired.
|
||||
model.refreshQueuedState()
|
||||
}
|
||||
@@ -175,21 +202,21 @@ public struct LyrebirdScratchView: View {
|
||||
return HStack(spacing: toolbarSpacing) {
|
||||
Button {
|
||||
model.toggleEngine()
|
||||
engineTick &+= 1
|
||||
stats = snapshotStats()
|
||||
} label: {
|
||||
HStack(spacing: reevalBadgeSpacing) {
|
||||
Circle()
|
||||
.fill(engine.isRunning ? Color.green : Color.red)
|
||||
.fill(stats.isRunning ? Color.green : Color.red)
|
||||
.frame(width: engineDotSize, height: engineDotSize)
|
||||
Text(engine.isRunning ? "engine running" : "▶ start engine")
|
||||
Text(stats.isRunning ? "engine running" : "▶ start engine")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(engine.isRunning ? Color.secondary : Color.primary)
|
||||
.foregroundStyle(stats.isRunning ? Color.secondary : Color.primary)
|
||||
}
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help(engine.isRunning ? "Stop the audio engine" : "Start the audio engine")
|
||||
.help(stats.isRunning ? "Stop the audio engine" : "Start the audio engine")
|
||||
Spacer()
|
||||
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(engine.averageCPU))")
|
||||
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(stats.averageCPU))")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer().frame(width: 8)
|
||||
@@ -205,7 +232,6 @@ public struct LyrebirdScratchView: View {
|
||||
}
|
||||
.padding(.horizontal, toolbarPadding)
|
||||
.padding(.vertical, 6)
|
||||
.id(engineTick)
|
||||
}
|
||||
|
||||
/// Warning strip shown once mapped snippet dylibs cross the restart
|
||||
@@ -226,19 +252,16 @@ public struct LyrebirdScratchView: View {
|
||||
}
|
||||
|
||||
/// Bottom engine panel: a live output oscilloscope plus a compact status
|
||||
/// readout (sample rate, CPU average/peak meters, node counts). Refreshed on
|
||||
/// the editor heartbeat via `.id(engineTick)`.
|
||||
/// readout (sample rate, CPU average/peak meters, node counts). The status
|
||||
/// text refreshes in place off the ``stats`` snapshot — no `.id(tick)`
|
||||
/// teardown, so the surrounding layout (and the editor's scroll) stays put.
|
||||
private var enginePanel: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
// The scope keeps a stable identity so its 30 Hz `.task` poll loop
|
||||
// is NOT cancelled/restarted by the `.id(engineTick)` heartbeat —
|
||||
// that only wraps the status text below.
|
||||
if let scope: ScopeCapture = model.session.scope {
|
||||
ScratchScopeView(capture: scope)
|
||||
.frame(height: scopeHeight)
|
||||
}
|
||||
engineStatusRow
|
||||
.id(engineTick)
|
||||
}
|
||||
.padding(.horizontal, toolbarPadding)
|
||||
.padding(.vertical, 6)
|
||||
@@ -257,9 +280,9 @@ public struct LyrebirdScratchView: View {
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
cpuMeter(label: "CPU avg", value: engine.averageCPU)
|
||||
cpuMeter(label: "CPU peak", value: engine.peakCPU)
|
||||
Text("synths \(engine.synthesizerCount) · groups \(engine.groupCount) · snippets \(model.loadedSnippetCount)")
|
||||
cpuMeter(label: "CPU avg", value: stats.averageCPU)
|
||||
cpuMeter(label: "CPU peak", value: stats.peakCPU)
|
||||
Text("synths \(stats.synthesizerCount) · groups \(stats.groupCount) · snippets \(model.loadedSnippetCount)")
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
@@ -580,6 +603,11 @@ final class ScratchTextView: NSTextView {
|
||||
override func cancelOperation(_ sender: Any?) {
|
||||
onManualComplete?()
|
||||
}
|
||||
|
||||
/// Width of the line-number gutter drawn by ``ScratchLineNumberGutter``.
|
||||
/// `ScratchEditor.configure` reserves this as the text view's left inset so
|
||||
/// the gutter overlay doesn't cover the text.
|
||||
static let lineNumberGutterWidth: CGFloat = 40
|
||||
}
|
||||
|
||||
/// `NSViewRepresentable` wrapping a ``ScratchTextView`` inside an
|
||||
@@ -718,6 +746,10 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
scroll.autoresizingMask = [.width, .height]
|
||||
|
||||
let tv: ScratchTextView = ScratchTextView(frame: .zero)
|
||||
// Opt into TextKit 1: accessing `layoutManager` permanently switches the
|
||||
// text view off TextKit 2, where `self.layoutManager` is nil — the gutter
|
||||
// drawing needs it to place numbers against laid-out line rects.
|
||||
_ = tv.layoutManager
|
||||
tv.autoresizingMask = [.width]
|
||||
tv.isVerticallyResizable = true
|
||||
tv.isHorizontallyResizable = false
|
||||
@@ -734,6 +766,10 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
guard let coordinator: Coordinator = coordinator, let tv: ScratchTextView = tv else { return }
|
||||
coordinator.triggerCompletion(tv)
|
||||
}
|
||||
// Line-number gutter: a floating overlay pinned to the left of the visible
|
||||
// area (see `ScratchLineNumberGutter` for why not an `NSRulerView`).
|
||||
let gutter: ScratchLineNumberGutter = ScratchLineNumberGutter(scrollView: scroll, textView: tv)
|
||||
scroll.addFloatingSubview(gutter, for: .vertical)
|
||||
return scroll
|
||||
}
|
||||
|
||||
@@ -791,6 +827,15 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
tv.textStorage?.setAttributedString(attributed)
|
||||
tv.typingAttributes = attrs
|
||||
applyHighlight(to: tv, font: font, paragraph: paragraph)
|
||||
// A direct `setAttributedString` bypasses `NSTextView`'s edit path, so the
|
||||
// gutter (which redraws on `NSText.didChangeNotification`) isn't told to
|
||||
// refresh. Nudge it explicitly after a programmatic replace (format /
|
||||
// load / reset) so the line count doesn't go stale.
|
||||
if let scroll: NSScrollView = tv.enclosingScrollView {
|
||||
for sub: NSView in scroll.subviews {
|
||||
(sub as? ScratchLineNumberGutter)?.refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Syntax highlighting
|
||||
@@ -856,7 +901,11 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
tv.smartInsertDeleteEnabled = false
|
||||
tv.allowsUndo = true
|
||||
tv.usesFindBar = true
|
||||
tv.textContainerInset = NSSize(width: editorInset, height: editorInset)
|
||||
// Left inset reserves the column the `ScratchLineNumberGutter` overlay
|
||||
// draws line numbers into (see `ScratchLineNumberGutter.draw(_:)`).
|
||||
// `textContainerInset` is symmetric, so the right margin matches —
|
||||
// harmless whitespace.
|
||||
tv.textContainerInset = NSSize(width: ScratchTextView.lineNumberGutterWidth, height: editorInset)
|
||||
tv.drawsBackground = true
|
||||
tv.backgroundColor = .textBackgroundColor
|
||||
tv.textColor = .labelColor
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
// RenderOptionsAccessory.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Accessory view embedded in the "Render to File" `NSSavePanel`: a container/encoding
|
||||
/// popup and a duration field. Selecting a format rewrites the panel's filename
|
||||
/// extension and remembers the choice (`UserDefaults`) so the next render defaults to it.
|
||||
///
|
||||
/// The sample rate and channel count are intentionally **not** exposed here — the
|
||||
/// offline render mirrors the live engine (WYSIWYG with what was just heard).
|
||||
@MainActor
|
||||
final class RenderOptionsAccessory: NSView {
|
||||
|
||||
// MARK: - Format catalogue
|
||||
|
||||
/// One selectable output format. `token` is the persistence key (stable across
|
||||
/// reordering / re-titling of the list, unlike a raw index or the display title).
|
||||
private struct Option {
|
||||
let title: String
|
||||
let format: AudioFileFormat
|
||||
let token: String
|
||||
}
|
||||
|
||||
private static let options: [Option] = [
|
||||
Option(title: "WAV — 32-bit float", format: .wavFloat32, token: "wavF32"),
|
||||
Option(title: "WAV — 16-bit integer", format: .wavInt16, token: "wavI16"),
|
||||
Option(title: "WAV — 24-bit integer", format: .wavInt24, token: "wavI24"),
|
||||
Option(title: "AIFF — 32-bit float", format: .aiffFloat32, token: "aiffF32"),
|
||||
Option(title: "CAF — 32-bit float (uncapped)", format: .cafFloat32, token: "cafF32"),
|
||||
Option(title: "RF64 WAV — 32-bit float (>4 GB)", format: .rf64Float32, token: "rf64F32"),
|
||||
Option(title: "RF64 WAV — 24-bit integer (>4 GB)", format: .rf64Int24, token: "rf64I24"),
|
||||
Option(title: "AAC — 256 kbps (M4A)", format: .aacHigh, token: "aacHigh"),
|
||||
Option(title: "AAC — 128 kbps (M4A)", format: .aacMedium, token: "aacMedium"),
|
||||
Option(title: "Apple Lossless (M4A)", format: .alac, token: "alac"),
|
||||
]
|
||||
|
||||
/// Persisted last-used format token. Defaults to CAF (the pre-accessory behaviour).
|
||||
private static let defaultsKey: String = "com.lyrebird.scratch.renderFormatToken"
|
||||
private static let fallbackToken: String = "cafF32"
|
||||
|
||||
// MARK: - Layout metrics
|
||||
|
||||
private static let accessoryWidth: CGFloat = 380
|
||||
private static let accessoryHeight: CGFloat = 96
|
||||
private static let contentMargin: CGFloat = 16
|
||||
private static let gridSpacing: CGFloat = 8
|
||||
private static let minDurationFieldWidth: CGFloat = 80
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
private let formatPopup: NSPopUpButton = NSPopUpButton(frame: .zero, pullsDown: false)
|
||||
private let durationField: NSTextField = NSTextField(frame: .zero)
|
||||
|
||||
private let baseName: String
|
||||
private weak var savePanel: NSSavePanel?
|
||||
|
||||
// MARK: - Public read-out
|
||||
|
||||
/// The format for the currently selected popup item.
|
||||
var selectedFormat: AudioFileFormat {
|
||||
let index: Int = formatPopup.indexOfSelectedItem
|
||||
guard index >= 0 && index < RenderOptionsAccessory.options.count else {
|
||||
return .cafFloat32
|
||||
}
|
||||
return RenderOptionsAccessory.options[index].format
|
||||
}
|
||||
|
||||
/// Parsed duration in seconds, or `nil` when the field is not a positive number.
|
||||
var durationSeconds: Double? { RenderOptionsAccessory.parseDuration(durationField.stringValue) }
|
||||
|
||||
/// Parse a duration string to a positive, finite seconds value (or `nil`). Pure —
|
||||
/// extracted so it can be unit-tested without the modal panel.
|
||||
static func parseDuration(_ raw: String) -> Double? {
|
||||
let trimmed: String = raw.trimmingCharacters(in: .whitespaces)
|
||||
guard let value: Double = Double(trimmed), value > 0, value.isFinite else { return nil }
|
||||
return value
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - baseName: Filename stem (no extension); the format's extension is appended.
|
||||
/// - initialDuration: Seconds pre-filled in the duration field.
|
||||
/// - savePanel: The panel to keep the filename extension in sync with.
|
||||
init(baseName: String, initialDuration: Double, savePanel: NSSavePanel) {
|
||||
self.baseName = baseName
|
||||
self.savePanel = savePanel
|
||||
super.init(frame: NSRect(x: 0, y: 0,
|
||||
width: RenderOptionsAccessory.accessoryWidth,
|
||||
height: RenderOptionsAccessory.accessoryHeight))
|
||||
|
||||
let startIndex: Int = RenderOptionsAccessory.persistedIndex()
|
||||
|
||||
formatPopup.addItems(withTitles: RenderOptionsAccessory.options.map(\.title))
|
||||
formatPopup.selectItem(at: startIndex)
|
||||
formatPopup.target = self
|
||||
formatPopup.action = #selector(formatChanged)
|
||||
formatPopup.translatesAutoresizingMaskIntoConstraints = false
|
||||
|
||||
durationField.stringValue = String(format: "%.2f", initialDuration)
|
||||
durationField.translatesAutoresizingMaskIntoConstraints = false
|
||||
|
||||
let formatLabel: NSTextField = RenderOptionsAccessory.makeLabel("Format:")
|
||||
let durationLabel: NSTextField = RenderOptionsAccessory.makeLabel("Duration (s):")
|
||||
|
||||
let grid: NSGridView = NSGridView(views: [
|
||||
[formatLabel, formatPopup],
|
||||
[durationLabel, durationField],
|
||||
])
|
||||
grid.translatesAutoresizingMaskIntoConstraints = false
|
||||
grid.rowSpacing = RenderOptionsAccessory.gridSpacing
|
||||
grid.columnSpacing = RenderOptionsAccessory.gridSpacing
|
||||
grid.column(at: 0).xPlacement = .trailing
|
||||
addSubview(grid)
|
||||
|
||||
let margin: CGFloat = RenderOptionsAccessory.contentMargin
|
||||
NSLayoutConstraint.activate([
|
||||
grid.leadingAnchor.constraint(equalTo: leadingAnchor, constant: margin),
|
||||
grid.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -margin),
|
||||
grid.topAnchor.constraint(equalTo: topAnchor, constant: margin),
|
||||
grid.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -margin),
|
||||
durationField.widthAnchor.constraint(
|
||||
greaterThanOrEqualToConstant: RenderOptionsAccessory.minDurationFieldWidth),
|
||||
])
|
||||
|
||||
// Seed the panel filename once from baseName + the initial format's extension.
|
||||
savePanel.nameFieldStringValue = baseName + "." + selectedFormat.fileExtension
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
|
||||
|
||||
// MARK: - Actions
|
||||
|
||||
@objc private func formatChanged() {
|
||||
syncPanelExtension()
|
||||
let index: Int = formatPopup.indexOfSelectedItem
|
||||
if index >= 0 && index < RenderOptionsAccessory.options.count {
|
||||
UserDefaults.standard.set(RenderOptionsAccessory.options[index].token,
|
||||
forKey: RenderOptionsAccessory.defaultsKey)
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-extension the panel's current filename to match the selected format,
|
||||
/// **preserving any stem the user typed** — only the extension is replaced.
|
||||
private func syncPanelExtension() {
|
||||
guard let panel: NSSavePanel = savePanel else { return }
|
||||
let currentStem: String = (panel.nameFieldStringValue as NSString).deletingPathExtension
|
||||
let stem: String = currentStem.isEmpty ? baseName : currentStem
|
||||
panel.nameFieldStringValue = stem + "." + selectedFormat.fileExtension
|
||||
}
|
||||
|
||||
/// Test seam: select a format by index as if the user picked it from the popup
|
||||
/// (fires the same `formatChanged` side effects — panel re-extension + persistence).
|
||||
func selectFormatForTesting(at index: Int) {
|
||||
formatPopup.selectItem(at: index)
|
||||
formatChanged()
|
||||
}
|
||||
|
||||
/// Test seam: clear the persisted last-format so a test can start from the
|
||||
/// default and not leak state into other tests or the real app.
|
||||
static func clearPersistedFormatForTesting() {
|
||||
UserDefaults.standard.removeObject(forKey: defaultsKey)
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private static func persistedIndex() -> Int {
|
||||
let token: String = UserDefaults.standard.string(forKey: defaultsKey) ?? fallbackToken
|
||||
if let index: Int = options.firstIndex(where: { $0.token == token }) { return index }
|
||||
return options.firstIndex(where: { $0.token == fallbackToken }) ?? 0
|
||||
}
|
||||
|
||||
private static func makeLabel(_ text: String) -> NSTextField {
|
||||
let label: NSTextField = NSTextField(labelWithString: text)
|
||||
label.translatesAutoresizingMaskIntoConstraints = false
|
||||
return label
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,164 @@
|
||||
// ScratchLineNumberGutter.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Line-number gutter for `ScratchEditor`'s text view, implemented as a plain
|
||||
// floating overlay `NSView` rather than an `NSRulerView`. Enabling
|
||||
// `NSScrollView.rulersVisible` in this SwiftUI `NSViewRepresentable` mis-tiles
|
||||
// the document view (text goes invisible and stops taking input), and drawing
|
||||
// inside a layer-backed `NSTextView` never reaches `draw(_:)`. A floating
|
||||
// subview draws normally and leaves the text view untouched. It reads the text
|
||||
// view's layout manager and the clip view's scroll offset to place one
|
||||
// right-aligned number per source line in the visible region.
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
|
||||
final class ScratchLineNumberGutter: NSView {
|
||||
|
||||
private weak var textView: NSTextView?
|
||||
private weak var scrollView: NSScrollView?
|
||||
|
||||
init(scrollView: NSScrollView, textView: NSTextView) {
|
||||
self.scrollView = scrollView
|
||||
self.textView = textView
|
||||
let height: CGFloat = scrollView.contentView.bounds.height
|
||||
super.init(frame: NSRect(x: 0, y: 0, width: ScratchTextView.lineNumberGutterWidth, height: height))
|
||||
self.autoresizingMask = [.height]
|
||||
|
||||
let clip: NSClipView = scrollView.contentView
|
||||
clip.postsBoundsChangedNotifications = true
|
||||
let center: NotificationCenter = NotificationCenter.default
|
||||
center.addObserver(self, selector: #selector(refresh),
|
||||
name: NSView.boundsDidChangeNotification, object: clip)
|
||||
center.addObserver(self, selector: #selector(refresh),
|
||||
name: NSText.didChangeNotification, object: textView)
|
||||
center.addObserver(self, selector: #selector(refresh),
|
||||
name: NSView.frameDidChangeNotification, object: textView)
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("ScratchLineNumberGutter does not support NSCoder init")
|
||||
}
|
||||
|
||||
deinit {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
override var isFlipped: Bool { true }
|
||||
|
||||
/// Redraw the whole gutter after an edit / scroll / relayout. A programmatic
|
||||
/// text replace (format / load / reset) can happen without an
|
||||
/// `NSText.didChangeNotification`, so the host also nudges this directly.
|
||||
@objc func refresh() { needsDisplay = true }
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
gutterFillColor.setFill()
|
||||
bounds.fill()
|
||||
gutterDividerColor.setStroke()
|
||||
let divider: NSBezierPath = NSBezierPath()
|
||||
let dividerX: CGFloat = bounds.maxX - dividerHalfPixel
|
||||
divider.move(to: NSPoint(x: dividerX, y: bounds.minY))
|
||||
divider.line(to: NSPoint(x: dividerX, y: bounds.maxY))
|
||||
divider.lineWidth = 1
|
||||
divider.stroke()
|
||||
|
||||
guard let textView: NSTextView = textView,
|
||||
let layoutManager: NSLayoutManager = textView.layoutManager,
|
||||
let container: NSTextContainer = textView.textContainer,
|
||||
let clip: NSClipView = scrollView?.contentView else { return }
|
||||
|
||||
let visibleRect: NSRect = clip.documentVisibleRect
|
||||
let inset: CGFloat = textView.textContainerInset.height
|
||||
let ns: NSString = textView.string as NSString
|
||||
let total: Int = ns.length
|
||||
let attrs: [NSAttributedString.Key: Any] = [
|
||||
.font: gutterFont,
|
||||
.foregroundColor: gutterTextColor,
|
||||
]
|
||||
|
||||
// Glyphs visible in the clip, then the source-line walk over that range.
|
||||
let glyphRange: NSRange = layoutManager.glyphRange(forBoundingRect: visibleRect, in: container)
|
||||
let charRange: NSRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
|
||||
|
||||
// Snap to the START of the first visible source line before counting: when
|
||||
// word-wrap puts a wrapped continuation fragment at the top of the visible
|
||||
// area, `charRange.location` lands mid-line, and `lineNumber(at:)` would
|
||||
// over-count by one (throwing off every number below it).
|
||||
let firstLineStart: Int = ns.lineRange(for: NSRange(location: min(charRange.location, total), length: 0)).location
|
||||
var lineIndex: Int = lineNumber(at: firstLineStart, in: ns)
|
||||
var cursor: Int = firstLineStart
|
||||
let visibleEnd: Int = NSMaxRange(charRange)
|
||||
while cursor < visibleEnd && cursor < total {
|
||||
let lineRange: NSRange = ns.lineRange(for: NSRange(location: cursor, length: 0))
|
||||
// Position from the line *fragment* rect (the row's box), not the glyph
|
||||
// bounding rect. `boundingRect` is inconsistent across a trailing
|
||||
// newline and blank lines — it's what left the last number cramped
|
||||
// against the trailing empty line. The fragment rect is one clean,
|
||||
// uniform-height box per row.
|
||||
let firstGlyph: Int = layoutManager.glyphIndexForCharacter(at: lineRange.location)
|
||||
let fragment: NSRect = layoutManager.lineFragmentRect(
|
||||
forGlyphAt: firstGlyph,
|
||||
effectiveRange: nil,
|
||||
withoutAdditionalLayout: true
|
||||
)
|
||||
drawNumber(lineIndex, docY: fragment.minY + inset, lineHeight: fragment.height,
|
||||
visibleMinY: visibleRect.minY, attrs: attrs)
|
||||
let advance: Int = NSMaxRange(lineRange)
|
||||
if advance <= cursor { break }
|
||||
cursor = advance
|
||||
lineIndex += 1
|
||||
}
|
||||
|
||||
// Trailing empty line (empty doc, or one ending in a newline): drawn from
|
||||
// the layout manager's extra fragment, which `boundingRect` on a
|
||||
// zero-length range does not cover.
|
||||
let endsWithNewline: Bool = total > 0 && CharacterSet.newlines.contains(
|
||||
Unicode.Scalar(ns.character(at: total - 1)) ?? Unicode.Scalar(0)
|
||||
)
|
||||
if total == 0 || endsWithNewline {
|
||||
let extra: NSRect = layoutManager.extraLineFragmentRect
|
||||
if extra.height > 0 {
|
||||
drawNumber(lineIndex, docY: extra.minY + inset, lineHeight: extra.height,
|
||||
visibleMinY: visibleRect.minY, attrs: attrs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func drawNumber(_ n: Int, docY: CGFloat, lineHeight: CGFloat, visibleMinY: CGFloat,
|
||||
attrs: [NSAttributedString.Key: Any]) {
|
||||
// Document Y → gutter-local Y (the gutter floats over the visible area).
|
||||
let y: CGFloat = docY - visibleMinY
|
||||
let label: NSString = "\(n)" as NSString
|
||||
let size: CGSize = label.size(withAttributes: attrs)
|
||||
let point: NSPoint = NSPoint(
|
||||
x: bounds.maxX - size.width - rightInset,
|
||||
y: y + (lineHeight - size.height) * verticalCenterFraction
|
||||
)
|
||||
label.draw(at: point, withAttributes: attrs)
|
||||
}
|
||||
|
||||
/// 1-based source line number of the character at `loc`. Counts CR/LF/CRLF.
|
||||
private func lineNumber(at loc: Int, in text: NSString) -> Int {
|
||||
if loc <= 0 { return 1 }
|
||||
var line: Int = 1
|
||||
text.enumerateSubstrings(in: NSRange(location: 0, length: loc),
|
||||
options: [.byLines, .substringNotRequired]) { _, _, _, _ in
|
||||
line += 1
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
private let rightInset: CGFloat = 6
|
||||
private let dividerHalfPixel: CGFloat = 0.5
|
||||
private let gutterFontSize: CGFloat = 11
|
||||
private let verticalCenterFraction: CGFloat = 0.5
|
||||
private let gutterFillColor: NSColor = .controlBackgroundColor
|
||||
private let gutterDividerColor: NSColor = .separatorColor
|
||||
private let gutterTextColor: NSColor = .tertiaryLabelColor
|
||||
private var gutterFont: NSFont { NSFont.monospacedSystemFont(ofSize: gutterFontSize, weight: .regular) }
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,145 +0,0 @@
|
||||
// ScratchLineNumberRuler.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// Vertical line-number gutter for `ScratchEditor`'s `NSTextView`. Installed as
|
||||
// the scroll view's `verticalRulerView` so it tracks scroll position for free.
|
||||
// Reads laid-out glyph rects from the text view's layout manager and writes one
|
||||
// 1-based line label per visible line into the ruler's bounds.
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
|
||||
/// `NSRulerView` subclass rendering one right-aligned line number per laid-out
|
||||
/// line of the host `NSTextView`. Tracks the text view's scroll origin via the
|
||||
/// `boundsDidChangeNotification` posted by the enclosing `NSClipView` and
|
||||
/// invalidates itself on every text edit and frame change.
|
||||
final class ScratchLineNumberRuler: NSRulerView {
|
||||
|
||||
/// Re-resolved on every `draw` so the ruler picks up font / layout-manager
|
||||
/// swaps the text view performs after attachment.
|
||||
private weak var textView: NSTextView?
|
||||
|
||||
init(scrollView: NSScrollView, textView: NSTextView) {
|
||||
self.textView = textView
|
||||
super.init(scrollView: scrollView, orientation: .verticalRuler)
|
||||
self.clientView = textView
|
||||
self.ruleThickness = gutterWidth
|
||||
let center: NotificationCenter = NotificationCenter.default
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSText.didChangeNotification,
|
||||
object: textView)
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSView.frameDidChangeNotification,
|
||||
object: textView)
|
||||
let clipView: NSClipView = scrollView.contentView
|
||||
clipView.postsBoundsChangedNotifications = true
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSView.boundsDidChangeNotification,
|
||||
object: clipView)
|
||||
}
|
||||
|
||||
required init(coder: NSCoder) {
|
||||
fatalError("ScratchLineNumberRuler does not support NSCoder init")
|
||||
}
|
||||
|
||||
deinit {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
@objc private func invalidateForChange(_ note: Notification) {
|
||||
needsDisplay = true
|
||||
}
|
||||
|
||||
override func drawHashMarksAndLabels(in rect: NSRect) {
|
||||
guard let textView: NSTextView,
|
||||
let layoutManager: NSLayoutManager = textView.layoutManager,
|
||||
let textContainer: NSTextContainer = textView.textContainer else {
|
||||
return
|
||||
}
|
||||
|
||||
gutterFillColor.setFill()
|
||||
rect.fill()
|
||||
gutterDividerColor.setStroke()
|
||||
let dividerPath: NSBezierPath = NSBezierPath()
|
||||
let dividerX: CGFloat = bounds.maxX - dividerHalfPixel
|
||||
dividerPath.move(to: NSPoint(x: dividerX, y: rect.minY))
|
||||
dividerPath.line(to: NSPoint(x: dividerX, y: rect.maxY))
|
||||
dividerPath.lineWidth = 1
|
||||
dividerPath.stroke()
|
||||
|
||||
let nsText: NSString = textView.string as NSString
|
||||
let totalLength: Int = nsText.length
|
||||
let visibleRect: NSRect = scrollView?.contentView.bounds ?? .zero
|
||||
let glyphRange: NSRange = layoutManager.glyphRange(forBoundingRect: visibleRect, in: textContainer)
|
||||
let charRange: NSRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
|
||||
let inset: CGFloat = textView.textContainerInset.height
|
||||
let attrs: [NSAttributedString.Key: Any] = [
|
||||
.font: rulerFont,
|
||||
.foregroundColor: gutterTextColor,
|
||||
]
|
||||
|
||||
var lineIndex: Int = lineNumber(at: charRange.location, in: nsText)
|
||||
var cursor: Int = charRange.location
|
||||
let visibleEnd: Int = NSMaxRange(charRange)
|
||||
while cursor < visibleEnd && cursor <= totalLength {
|
||||
// `lineRange(for:)` advances cursor by the full line including its
|
||||
// terminator, so `\r`, `\n`, and `\r\n` line endings are all
|
||||
// handled by Foundation.
|
||||
let probeLength: Int = (cursor == totalLength) ? 0 : 0
|
||||
let lineRange: NSRange = nsText.lineRange(for: NSRange(location: cursor, length: probeLength))
|
||||
let lineGlyphRange: NSRange = layoutManager.glyphRange(forCharacterRange: lineRange,
|
||||
actualCharacterRange: nil)
|
||||
let usedRect: NSRect = layoutManager.boundingRect(forGlyphRange: lineGlyphRange,
|
||||
in: textContainer)
|
||||
let yInView: CGFloat = usedRect.minY + inset - visibleRect.minY
|
||||
let label: NSString = "\(lineIndex)" as NSString
|
||||
let size: CGSize = label.size(withAttributes: attrs)
|
||||
let drawPoint: NSPoint = NSPoint(
|
||||
x: bounds.maxX - size.width - rightInset,
|
||||
y: yInView + ((usedRect.height - size.height) * 0.5)
|
||||
)
|
||||
label.draw(at: drawPoint, withAttributes: attrs)
|
||||
|
||||
let advance: Int = NSMaxRange(lineRange)
|
||||
if advance <= cursor { break } // defensive — empty trailing line
|
||||
cursor = advance
|
||||
lineIndex += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 1-based line number of the character at `loc`. Delegates to
|
||||
// `NSString.enumerateSubstrings(.byLines)` so CR, LF, and CRLF endings are
|
||||
// all counted correctly. Linear in `loc`, runs once per draw on the prefix
|
||||
// that precedes the first visible line.
|
||||
private func lineNumber(at loc: Int, in text: NSString) -> Int {
|
||||
if loc <= 0 { return 1 }
|
||||
var line: Int = 1
|
||||
let prefixRange: NSRange = NSRange(location: 0, length: loc)
|
||||
text.enumerateSubstrings(in: prefixRange,
|
||||
options: [.byLines, .substringNotRequired]) { _, _, _, _ in
|
||||
line += 1
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
private let gutterWidth: CGFloat = 40
|
||||
private let rightInset: CGFloat = 6
|
||||
private let dividerHalfPixel: CGFloat = 0.5 // crisp 1px divider on Retina
|
||||
private let rulerFontSize: CGFloat = 11
|
||||
private let gutterFillColor: NSColor = NSColor.controlBackgroundColor
|
||||
private let gutterDividerColor: NSColor = NSColor.separatorColor
|
||||
private let gutterTextColor: NSColor = NSColor.tertiaryLabelColor
|
||||
private var rulerFont: NSFont {
|
||||
NSFont.monospacedSystemFont(ofSize: rulerFontSize, weight: .regular)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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)
|
||||
@@ -0,0 +1,134 @@
|
||||
// ArtifactStagingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
/// Verifies that a staged artifacts directory is a self-contained, working
|
||||
/// compile root: a snippet compiled against the staged `-I` / `-L` / rpath
|
||||
/// succeeds without reaching back into the original build tree.
|
||||
@Suite("LiveSession artifact staging")
|
||||
struct ArtifactStagingTests {
|
||||
|
||||
/// The dev SPM build dir the tests run from — the staging source.
|
||||
private func buildDir() -> URL? {
|
||||
LiveSession.currentBuildDir()
|
||||
}
|
||||
|
||||
@Test func umbrellaHeaderPathParses() {
|
||||
let map: String = """
|
||||
module LyrebirdC {
|
||||
umbrella header "/abs/path/Sources/LyrebirdC/include/LyrebirdC.h"
|
||||
export *
|
||||
}
|
||||
"""
|
||||
#expect(LiveSession.umbrellaHeaderPath(in: map) == "/abs/path/Sources/LyrebirdC/include/LyrebirdC.h")
|
||||
}
|
||||
|
||||
@Test func umbrellaHeaderPathNilWhenAbsent() {
|
||||
#expect(LiveSession.umbrellaHeaderPath(in: "module Foo { export * }") == nil)
|
||||
}
|
||||
|
||||
@Test func stageProducesPopulatedRootWithStagedModuleMap() throws {
|
||||
guard let src: URL = buildDir() else {
|
||||
// No build dir discoverable (unusual for a test run) — nothing to stage.
|
||||
return
|
||||
}
|
||||
let dest: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: dest) }
|
||||
|
||||
let staged: URL? = LiveSession.stageArtifacts(from: src, to: dest)
|
||||
#expect(staged == dest)
|
||||
#expect(LiveSession.isArtifactsDirPopulated(dest))
|
||||
|
||||
// The staged C module map must point at the staged header copy, not the
|
||||
// original absolute path under the source tree.
|
||||
let stagedMap: URL = dest
|
||||
.appendingPathComponent("LyrebirdC.build", isDirectory: true)
|
||||
.appendingPathComponent("module.modulemap", isDirectory: false)
|
||||
if FileManager.default.fileExists(atPath: stagedMap.path) {
|
||||
let text: String = try String(contentsOf: stagedMap, encoding: .utf8)
|
||||
#expect(text.contains("\(dest.path)/LyrebirdC.headers"))
|
||||
#expect(!text.contains("/Sources/LyrebirdC/include"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func refusesToClobberNonStagingDir() throws {
|
||||
guard let src: URL = buildDir() else { return }
|
||||
let dest: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: dest, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: dest) }
|
||||
// A pre-existing file that does NOT look like a staging root.
|
||||
let precious: URL = dest.appendingPathComponent("precious.txt", isDirectory: false)
|
||||
try "keep me".write(to: precious, atomically: true, encoding: .utf8)
|
||||
|
||||
let staged: URL? = LiveSession.stageArtifacts(from: src, to: dest)
|
||||
#expect(staged == nil) // refused
|
||||
#expect(FileManager.default.fileExists(atPath: precious.path)) // untouched
|
||||
}
|
||||
|
||||
@Test func idempotentSecondStageKeepsRoot() throws {
|
||||
guard let src: URL = buildDir() else { return }
|
||||
let dest: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: dest) }
|
||||
|
||||
#expect(LiveSession.stageArtifacts(from: src, to: dest) == dest)
|
||||
// Second call with an unchanged source: still a valid, current root.
|
||||
#expect(LiveSession.stageArtifacts(from: src, to: dest) == dest)
|
||||
#expect(LiveSession.isArtifactsDirPopulated(dest))
|
||||
#expect(LiveSession.stagedDirIsCurrent(dest))
|
||||
}
|
||||
|
||||
@Test func snippetCompilesFromStagedRoot() async throws {
|
||||
guard let src: URL = buildDir() else { return }
|
||||
guard LiveSession.hasLyrebirdDylib(in: src) else {
|
||||
// Xcode-SPM layout (no dylib) — the staged-link path under test needs
|
||||
// the bare-SPM dylib present; skip when absent.
|
||||
return
|
||||
}
|
||||
let dest: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: dest) }
|
||||
|
||||
guard let staged: URL = LiveSession.stageArtifacts(from: src, to: dest) else {
|
||||
Issue.record("staging produced no root")
|
||||
return
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
// Point the session ONLY at the staged root — no original build dir.
|
||||
let session: LiveSession = await LiveSession(
|
||||
engine: engine,
|
||||
attachScope: false,
|
||||
importPaths: [staged, staged.appendingPathComponent("Modules")],
|
||||
librarySearchPaths: [staged],
|
||||
libraries: ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
|
||||
rpaths: [staged]
|
||||
)
|
||||
// A trivial snippet that touches the LyrebirdSynth API proves the module
|
||||
// resolves from the staged root.
|
||||
try await session.compileAndRunAsync("context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||
await session.clearTracked()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -8,15 +8,18 @@ import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
@Suite("DiagnosticParser")
|
||||
struct DiagnosticParserTests {
|
||||
|
||||
@Test
|
||||
func parsesSingleErrorAtUserBodyLine() throws {
|
||||
// Wrapped snippet preamble is 8 lines; user body starts at line 9.
|
||||
// swiftc reports an error on wrapped line 10 → maps to user line 2.
|
||||
// Representative offset: for a preamble whose user body starts at line 9,
|
||||
// a swiftc error on wrapped line 10 maps to user line 2. (This tests the
|
||||
// parser's arithmetic directly; the actual harness offset — which shifts
|
||||
// when the preamble changes — is exercised by
|
||||
// `endToEndOffsetMatchesSnippetHarness` below.)
|
||||
let stderr: String = "/tmp/Snippet.swift:10:14: error: cannot find 'foo' in scope"
|
||||
let diagnostics: [Diagnostic] = DiagnosticParser.parse(stderr: stderr, userBodyLineOffset: 9)
|
||||
try #require(diagnostics.count == 1)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import LyrebirdGraphDSLEmbedded
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@@ -8,7 +8,7 @@ import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
@Suite("LiveCompiler")
|
||||
struct LiveCompilerTests {
|
||||
@@ -30,7 +30,11 @@ struct LiveCompilerTests {
|
||||
|
||||
let snippet: CompiledSnippet = try LiveCompiler.compile(source: source)
|
||||
#expect(snippet.moduleName.hasPrefix("LBSnippet_"))
|
||||
#if os(macOS)
|
||||
#expect(snippet.dylibPath.hasSuffix(".dylib"))
|
||||
#else
|
||||
#expect(snippet.dylibPath.hasSuffix(".so"))
|
||||
#endif
|
||||
|
||||
var marker: Int32 = 0
|
||||
withUnsafeMutablePointer(to: &marker) { ptr in
|
||||
@@ -103,6 +107,11 @@ struct LiveCompilerTests {
|
||||
for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
#if os(Linux)
|
||||
for url: URL in LiveSession.discoverSourceSystemModuleMaps(in: importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
#endif
|
||||
return args
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import Foundation
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
@MainActor
|
||||
@Suite("LiveSession diagnostics")
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
import LyrebirdGraphDSLEmbedded
|
||||
|
||||
@@ -9,7 +9,7 @@ import Foundation
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
@MainActor
|
||||
@Suite("LiveSession")
|
||||
@@ -34,7 +34,12 @@ struct LiveSessionTests {
|
||||
@Test
|
||||
func buildDirDiscoveryFindsLyrebirdDylib() throws {
|
||||
let buildDir: URL = try #require(LiveSession.currentBuildDir())
|
||||
let dylib: URL = buildDir.appendingPathComponent("libLyrebirdDynamic.dylib")
|
||||
#if os(macOS)
|
||||
let libName: String = "libLyrebirdDynamic.dylib"
|
||||
#else
|
||||
let libName: String = "libLyrebirdDynamic.so"
|
||||
#endif
|
||||
let dylib: URL = buildDir.appendingPathComponent(libName)
|
||||
#expect(FileManager.default.fileExists(atPath: dylib.path))
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -8,7 +8,7 @@ import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
@Suite("SnippetHarness")
|
||||
struct SnippetHarnessTests {
|
||||
@@ -16,6 +16,9 @@ struct SnippetHarnessTests {
|
||||
@Test
|
||||
func wrappedSourceContainsPreambleAndUserBody() {
|
||||
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: "context.reportMessage(\"hello\")")
|
||||
// Foundation so snippets can use `pow`, `sin`, `Date`, … without an import
|
||||
// (a snippet can't declare one — its body is inside the entry function).
|
||||
#expect(wrapped.source.contains("import Foundation"))
|
||||
#expect(wrapped.source.contains("import LyrebirdSynth"))
|
||||
#expect(wrapped.source.contains("import LyrebirdLiveCompile"))
|
||||
#expect(wrapped.source.contains("@_cdecl(\"lyrebird_snippet_entry\")"))
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
@@ -15,6 +15,34 @@ import LyrebirdSynth
|
||||
@Suite("Snippet scheduled loop")
|
||||
struct SnippetScheduledLoopTests {
|
||||
|
||||
@Test func snippetCanUseFoundationMath() throws {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
controlBlockSize: 64,
|
||||
sampleRate: 44_100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
let session: LiveSession = LiveSession(engine: engine, attachScope: false)
|
||||
try engine.start()
|
||||
// `pow` / `sin` come from Foundation, which the harness preamble imports —
|
||||
// a snippet can't add the import itself. This would fail to compile
|
||||
// ("cannot find 'pow' in scope") without it.
|
||||
let snippet: String = """
|
||||
let semitone: Double = pow(2.0, 1.0 / 12.0)
|
||||
let freq: Double = 440.0 * semitone
|
||||
context.play { OscSin.Audio(freq: freq) * (0.1 * sin(0.0) + 0.1) }
|
||||
context.reportMessage("math ok \\(freq)")
|
||||
"""
|
||||
try session.compileAndRun(snippet)
|
||||
#expect(session.lastSnippetMessage?.hasPrefix("math ok") == true)
|
||||
session.clearTracked()
|
||||
}
|
||||
|
||||
@Test func loopSchedulesTenSelfFreeingTones() throws {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// SwiftFormatterTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@Suite("SwiftFormatter")
|
||||
struct SwiftFormatterTests {
|
||||
|
||||
@Test func formatsMessySource() throws {
|
||||
guard SwiftFormatter.isAvailable else { return } // no toolchain formatter — skip
|
||||
let messy: String = "let x=1\nstruct Foo{let a:Int}\n"
|
||||
let formatted: String = try SwiftFormatter.format(source: messy)
|
||||
// Canonical spacing appears; the mangled originals are gone.
|
||||
#expect(formatted.contains("let x = 1"))
|
||||
#expect(!formatted.contains("let x=1"))
|
||||
#expect(!formatted.contains("struct Foo"))
|
||||
}
|
||||
|
||||
@Test func alreadyFormattedIsStable() throws {
|
||||
guard SwiftFormatter.isAvailable else { return }
|
||||
let clean: String = "let x = 1\n"
|
||||
let once: String = try SwiftFormatter.format(source: clean)
|
||||
let twice: String = try SwiftFormatter.format(source: once)
|
||||
#expect(once == twice) // idempotent
|
||||
}
|
||||
|
||||
@Test func parseErrorThrowsFormatFailed() {
|
||||
guard SwiftFormatter.isAvailable else { return }
|
||||
// Unbalanced brace — swift-format should exit non-zero.
|
||||
let broken: String = "func f( {\n"
|
||||
var caught: SwiftFormatterError?
|
||||
do {
|
||||
_ = try SwiftFormatter.format(source: broken)
|
||||
} catch let error as SwiftFormatterError {
|
||||
caught = error
|
||||
} catch {
|
||||
Issue.record("unexpected error type: \(error)")
|
||||
}
|
||||
guard case .formatFailed = caught else {
|
||||
Issue.record("expected .formatFailed, got \(String(describing: caught))")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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,105 @@
|
||||
// RenderOptionsAccessoryTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import AppKit
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
// Serialized: these tests mutate a shared `UserDefaults` key (the persisted
|
||||
// last-format), so they must not interleave.
|
||||
@Suite("RenderOptionsAccessory", .serialized)
|
||||
@MainActor
|
||||
struct RenderOptionsAccessoryTests {
|
||||
|
||||
// Popup order (see RenderOptionsAccessory.options).
|
||||
private let wavFloat32Index: Int = 0
|
||||
private let wavInt24Index: Int = 2
|
||||
private let rf64Float32Index: Int = 5
|
||||
|
||||
private func makeAccessory() -> (RenderOptionsAccessory, NSSavePanel) {
|
||||
let panel: NSSavePanel = NSSavePanel()
|
||||
let accessory: RenderOptionsAccessory = RenderOptionsAccessory(
|
||||
baseName: "render", initialDuration: 5.0, savePanel: panel
|
||||
)
|
||||
return (accessory, panel)
|
||||
}
|
||||
|
||||
// MARK: - Duration parsing
|
||||
|
||||
@Test("parseDuration accepts positive finite numbers and rejects the rest")
|
||||
func durationParsing() {
|
||||
#expect(RenderOptionsAccessory.parseDuration("5.0") == 5.0)
|
||||
#expect(RenderOptionsAccessory.parseDuration(" 2.5 ") == 2.5)
|
||||
#expect(RenderOptionsAccessory.parseDuration("0") == nil)
|
||||
#expect(RenderOptionsAccessory.parseDuration("-1") == nil)
|
||||
#expect(RenderOptionsAccessory.parseDuration("") == nil)
|
||||
#expect(RenderOptionsAccessory.parseDuration("abc") == nil)
|
||||
#expect(RenderOptionsAccessory.parseDuration("nan") == nil)
|
||||
#expect(RenderOptionsAccessory.parseDuration("inf") == nil)
|
||||
}
|
||||
|
||||
// MARK: - Format read-out
|
||||
|
||||
@Test("Selecting a format updates selectedFormat")
|
||||
func selectedFormatReflectsPopup() {
|
||||
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||
let (accessory, _): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||
|
||||
accessory.selectFormatForTesting(at: wavFloat32Index)
|
||||
#expect(accessory.selectedFormat == .wavFloat32)
|
||||
accessory.selectFormatForTesting(at: wavInt24Index)
|
||||
#expect(accessory.selectedFormat == .wavInt24)
|
||||
accessory.selectFormatForTesting(at: rf64Float32Index)
|
||||
#expect(accessory.selectedFormat == .rf64Float32)
|
||||
}
|
||||
|
||||
// MARK: - Panel filename sync
|
||||
|
||||
@Test("Changing format preserves a user-typed filename stem")
|
||||
func formatChangePreservesUserStem() {
|
||||
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||
let (accessory, panel): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||
|
||||
// User renames the target, then switches format.
|
||||
panel.nameFieldStringValue = "mySound.caf"
|
||||
accessory.selectFormatForTesting(at: wavFloat32Index)
|
||||
#expect(panel.nameFieldStringValue == "mySound.wav")
|
||||
|
||||
// Switching again keeps the stem, swaps only the extension.
|
||||
accessory.selectFormatForTesting(at: rf64Float32Index)
|
||||
#expect(panel.nameFieldStringValue == "mySound.wav") // RF64 keeps .wav
|
||||
}
|
||||
|
||||
@Test("Empty filename falls back to the base name")
|
||||
func emptyStemFallsBackToBaseName() {
|
||||
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||
let (accessory, panel): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||
panel.nameFieldStringValue = ""
|
||||
accessory.selectFormatForTesting(at: wavInt24Index)
|
||||
#expect(panel.nameFieldStringValue == "render.wav")
|
||||
}
|
||||
|
||||
// MARK: - Persistence
|
||||
|
||||
@Test("Last-selected format persists to a fresh accessory")
|
||||
func formatSelectionPersists() {
|
||||
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||
|
||||
let (first, _): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||
first.selectFormatForTesting(at: rf64Float32Index) // persists "rf64F32"
|
||||
|
||||
// A brand-new accessory should open on the remembered format.
|
||||
let (second, _): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||
#expect(second.selectedFormat == .rf64Float32)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,48 @@
|
||||
// ScratchModelFormatTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
@Suite("LyrebirdScratchModel formatting")
|
||||
@MainActor
|
||||
struct ScratchModelFormatTests {
|
||||
|
||||
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LyrebirdScratchModel(session: LiveSession(engine: engine, attachScope: false), initialText: text)
|
||||
}
|
||||
|
||||
@Test func formatRewritesMessyBufferAndLogs() async {
|
||||
guard SwiftFormatter.isAvailable else { return } // no toolchain formatter — skip
|
||||
let model: LyrebirdScratchModel = makeModel(text: "let x=1\n")
|
||||
await model.formatBuffer()
|
||||
#expect(model.text.contains("let x = 1"))
|
||||
#expect(model.consoleEntries.contains { $0.kind == .info })
|
||||
}
|
||||
|
||||
@Test func formatBlankBufferIsNoOp() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: " \n")
|
||||
let before: String = model.text
|
||||
await model.formatBuffer()
|
||||
#expect(model.text == before)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,125 @@
|
||||
// ScratchModelRenderTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
@Suite("LyrebirdScratchModel render-to-file")
|
||||
@MainActor
|
||||
struct ScratchModelRenderTests {
|
||||
|
||||
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LyrebirdScratchModel(session: LiveSession(engine: engine, attachScope: false), initialText: text)
|
||||
}
|
||||
|
||||
@Test func rendersWholeBufferToCAF() async throws {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let duration: Double = 0.25
|
||||
let ok: Bool = await model.renderToFile(url: url, duration: duration)
|
||||
#expect(ok)
|
||||
#expect(FileManager.default.fileExists(atPath: url.path))
|
||||
#expect(model.consoleEntries.contains { $0.kind == .info })
|
||||
|
||||
// The CAF should hold roughly `duration` seconds at the engine's rate.
|
||||
var fileRef: ExtAudioFileRef?
|
||||
#expect(ExtAudioFileOpenURL(url as CFURL, &fileRef) == noErr)
|
||||
guard let fileRef: ExtAudioFileRef = fileRef else {
|
||||
Issue.record("could not open rendered CAF")
|
||||
return
|
||||
}
|
||||
defer { ExtAudioFileDispose(fileRef) }
|
||||
var frames: Int64 = 0
|
||||
var size: UInt32 = UInt32(MemoryLayout<Int64>.size)
|
||||
#expect(ExtAudioFileGetProperty(fileRef, kExtAudioFileProperty_FileLengthFrames, &size, &frames) == noErr)
|
||||
// Allow a block of slack either way.
|
||||
let expected: Double = duration * 48_000
|
||||
#expect(Double(frames) > expected - 128 && Double(frames) < expected + 512)
|
||||
}
|
||||
|
||||
@Test func rendersSelectionWhenPresent() async {
|
||||
// Whole buffer has two statements; select only the first and render it.
|
||||
let model: LyrebirdScratchModel = makeModel(
|
||||
text: "context.play { OscSin.Audio(freq: 440) * 0.1 }\ncontext.play { OscSin.Audio(freq: 880) * 0.1 }")
|
||||
model.updateSelection("context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||
#expect(model.hasSelection)
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let ok: Bool = await model.renderToFile(url: url, duration: 0.1)
|
||||
#expect(ok)
|
||||
#expect(FileManager.default.fileExists(atPath: url.path))
|
||||
}
|
||||
|
||||
@Test func nonPositiveDurationFails() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let ok: Bool = await model.renderToFile(url: url, duration: 0)
|
||||
#expect(!ok)
|
||||
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||
#expect(model.consoleEntries.contains { $0.kind == .error })
|
||||
}
|
||||
|
||||
@Test func blankBufferRendersNothing() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: " \n")
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let ok: Bool = await model.renderToFile(url: url, duration: 0.1)
|
||||
#expect(!ok)
|
||||
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||
}
|
||||
|
||||
/// The `format:` argument reaches the NRT driver: rendering to a WAV Int24 target
|
||||
/// and an RF64 target produces files with the requested on-disk encoding.
|
||||
@Test(arguments: [
|
||||
(AudioFileFormat.wavInt24, "wav", UInt32(24), false),
|
||||
(AudioFileFormat.rf64Float32, "wav", UInt32(32), true),
|
||||
])
|
||||
func rendersHonourFormat(format: AudioFileFormat, ext: String, bits: UInt32, isFloat: Bool) async throws {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBRenderTest-\(UUID().uuidString)").appendingPathExtension(ext)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let ok: Bool = await model.renderToFile(url: url, format: format, duration: 0.1)
|
||||
#expect(ok)
|
||||
#expect(FileManager.default.fileExists(atPath: url.path))
|
||||
|
||||
var fileRef: ExtAudioFileRef?
|
||||
#expect(ExtAudioFileOpenURL(url as CFURL, &fileRef) == noErr)
|
||||
let ref: ExtAudioFileRef = try #require(fileRef)
|
||||
defer { ExtAudioFileDispose(ref) }
|
||||
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
|
||||
var size: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
|
||||
#expect(ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileDataFormat, &size, &asbd) == noErr)
|
||||
#expect(asbd.mBitsPerChannel == bits)
|
||||
#expect((asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0) == isFloat)
|
||||
}
|
||||
}
|
||||
|
||||
#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
|
||||
@@ -20,7 +20,7 @@
|
||||
location = "group:Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj">
|
||||
location = "group:Demos/LyrebirdScratch/LyrebirdScratch.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj">
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
// ProcessInfo — read the LYREBIRD_DISABLE_ALSA opt-out below.
|
||||
import Foundation
|
||||
|
||||
let package = Package(
|
||||
name: "Lyrebird",
|
||||
@@ -21,7 +23,10 @@ let package = Package(
|
||||
// double-registration crash fixed in Phase 167). External consumers
|
||||
// never reference this product — they use `Lyrebird` (static) above.
|
||||
.library(name: "LyrebirdDynamic", type: .dynamic, targets: ["LyrebirdSynth"]),
|
||||
.library(name: "LyrebirdUI", targets: ["LyrebirdUI"]),
|
||||
// LyrebirdUI (SwiftUI/AppKit) product + targets are appended after this
|
||||
// literal under `#if os(macOS)` — they are Apple-only and must be absent
|
||||
// from the manifest on a native Linux/Windows host. See the block below
|
||||
// the `Package(...)` initializer.
|
||||
.library(name: "LyrebirdGraphDSL", targets: ["LyrebirdGraphDSL"]),
|
||||
.executable(name: "LyrebirdCLI", targets: ["LyrebirdCLI"]),
|
||||
],
|
||||
@@ -58,19 +63,38 @@ let package = Package(
|
||||
name: "LyrebirdC",
|
||||
path: "Sources/LyrebirdC"
|
||||
),
|
||||
// Vector-math seam. On Apple this target re-exports Accelerate
|
||||
// (`@_exported import Accelerate`); on non-Apple platforms it supplies
|
||||
// API-compatible scalar replacements for the vDSP/vForce primitives the
|
||||
// synthesis core uses. Every core file writes `import LyrebirdDSP` in
|
||||
// place of `import Accelerate`. See Sources/LyrebirdDSP/AccelerateShim.swift.
|
||||
.target(
|
||||
name: "LyrebirdDSP",
|
||||
path: "Sources/LyrebirdDSP",
|
||||
linkerSettings: [
|
||||
.linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])),
|
||||
]
|
||||
),
|
||||
.target(
|
||||
// Module/target renamed `Lyrebird` → `LyrebirdSynth` (the `Lyrebird`
|
||||
// product above still vends it). Folder path kept as `Sources/Lyrebird`
|
||||
// so the source tree and `Lyrebird.docc` catalog don't move.
|
||||
name: "LyrebirdSynth",
|
||||
dependencies: ["LyrebirdC"],
|
||||
// `CALSA` (libasound, for the Linux `ALSAAudioDriver`) is appended
|
||||
// to these dependencies on a Linux host — see the block below the
|
||||
// `Package(...)` initializer.
|
||||
dependencies: ["LyrebirdC", "LyrebirdDSP"],
|
||||
path: "Sources/Lyrebird",
|
||||
linkerSettings: [
|
||||
.linkedFramework("CoreAudio"),
|
||||
.linkedFramework("AudioToolbox"),
|
||||
.linkedFramework("Accelerate"),
|
||||
.linkedFramework("CoreMIDI"),
|
||||
.linkedFramework("AVFoundation"),
|
||||
// Apple-only frameworks. Guarded with `.when(platforms:)` so a
|
||||
// non-Apple target (Linux/Windows feasibility) does not fail at
|
||||
// link-configuration time before source-level errors surface.
|
||||
// macOS/iOS builds are unaffected.
|
||||
.linkedFramework("CoreAudio", .when(platforms: [.macOS, .iOS])),
|
||||
.linkedFramework("AudioToolbox", .when(platforms: [.macOS, .iOS])),
|
||||
.linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])),
|
||||
.linkedFramework("CoreMIDI", .when(platforms: [.macOS, .iOS])),
|
||||
.linkedFramework("AVFoundation", .when(platforms: [.macOS, .iOS])),
|
||||
]
|
||||
),
|
||||
.executableTarget(
|
||||
@@ -87,15 +111,9 @@ let package = Package(
|
||||
]
|
||||
// Swift 6 language mode (Phase 202): inherits the swift-tools 6.0 default.
|
||||
),
|
||||
.target(
|
||||
name: "LyrebirdUI",
|
||||
dependencies: [
|
||||
"LyrebirdSynth",
|
||||
],
|
||||
path: "Sources/LyrebirdUI"
|
||||
// SwiftUI + AppKit + Observation are system frameworks — no linkerSettings needed.
|
||||
// Swift 6 language mode (Phase 202): inherits the swift-tools 6.0 default.
|
||||
),
|
||||
// NOTE: LyrebirdUI, LyrebirdUITests, and LyrebirdTests are appended after
|
||||
// the `Package(...)` initializer under `#if os(macOS)` — they need Apple
|
||||
// frameworks and must be absent from a native Linux/Windows manifest.
|
||||
// Phase 167 — `LyrebirdLiveCompile` (and its SwiftUI host
|
||||
// `LyrebirdLiveCompileUI`) moved to the `LiveCompile/` nested SwiftPM
|
||||
// package. It depends on the internal `.product(name: "LyrebirdDynamic",
|
||||
@@ -105,12 +123,10 @@ let package = Package(
|
||||
// cause of an ObjC class double-registration crash during `swift test`
|
||||
// in the single-package layout. The consumer-facing `Lyrebird` product
|
||||
// stays static (see products list). See `LiveCompile/Package.swift`.
|
||||
.executableTarget(
|
||||
name: "LyrebirdBenchmark",
|
||||
dependencies: ["LyrebirdSynth"],
|
||||
path: "Sources/LyrebirdBenchmark",
|
||||
swiftSettings: [.unsafeFlags(["-O"])]
|
||||
),
|
||||
// LyrebirdBenchmark micro-benchmarks Accelerate/vDSP primitives directly
|
||||
// (`import Accelerate`), so it is Apple-only and appended under
|
||||
// `#if os(macOS)` below the initializer — otherwise `swift test` on Linux
|
||||
// would try to build it and fail on the missing Accelerate module.
|
||||
// Interpreted graph-DSL. Pure Swift over core `LyrebirdSynth` types —
|
||||
// no swiftc, no AppKit — so it is cross-platform (iOS included). The
|
||||
// `DSLBuiltin` registry it consumes is emitted by the separate
|
||||
@@ -122,22 +138,13 @@ let package = Package(
|
||||
path: "Sources/LyrebirdGraphDSL"
|
||||
),
|
||||
.testTarget(
|
||||
name: "LyrebirdTests",
|
||||
dependencies: ["LyrebirdSynth"],
|
||||
path: "Tests/LyrebirdTests",
|
||||
name: "LyrebirdDSPTests",
|
||||
dependencies: ["LyrebirdDSP"],
|
||||
path: "Tests/LyrebirdDSPTests",
|
||||
linkerSettings: [
|
||||
.linkedFramework("AudioToolbox"),
|
||||
.linkedFramework("Accelerate"),
|
||||
.linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])),
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LyrebirdUITests",
|
||||
dependencies: [
|
||||
"LyrebirdUI",
|
||||
"LyrebirdSynth",
|
||||
],
|
||||
path: "Tests/LyrebirdUITests"
|
||||
),
|
||||
.testTarget(
|
||||
name: "LyrebirdGraphDSLTests",
|
||||
dependencies: [
|
||||
@@ -146,8 +153,8 @@ let package = Package(
|
||||
],
|
||||
path: "Tests/LyrebirdGraphDSLTests",
|
||||
linkerSettings: [
|
||||
.linkedFramework("AudioToolbox"),
|
||||
.linkedFramework("Accelerate"),
|
||||
.linkedFramework("AudioToolbox", .when(platforms: [.macOS, .iOS])),
|
||||
.linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])),
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
@@ -155,5 +162,180 @@ let package = Package(
|
||||
dependencies: ["LyrebirdCLI"],
|
||||
path: "Tests/LyrebirdCLITests"
|
||||
),
|
||||
// Platform-neutral core tests. Unlike `LyrebirdTests` (Apple-only —
|
||||
// some files import AudioToolbox/Accelerate directly), this target
|
||||
// compiles and runs on every supported platform, so the golden-value
|
||||
// DSP tests it holds actually execute on Linux in CI. That is the only
|
||||
// place the portable FFT/biquad/vector fallbacks in `LyrebirdDSP` are
|
||||
// verified through the real generators; `LyrebirdDSPTests` compares to
|
||||
// real vDSP and is therefore Apple-only by construction.
|
||||
.testTarget(
|
||||
name: "LyrebirdPortableTests",
|
||||
dependencies: ["LyrebirdSynth"],
|
||||
path: "Tests/LyrebirdPortableTests",
|
||||
linkerSettings: [
|
||||
.linkedFramework("AudioToolbox", .when(platforms: [.macOS, .iOS])),
|
||||
.linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])),
|
||||
]
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
// LyrebirdUI — the cross-platform UI module. Public control/view names are the
|
||||
// same on every platform; each file switches its body by backend
|
||||
// (`#if canImport(SwiftUI)` → real SwiftUI on Apple / `#else` → SwiftOpenUI on
|
||||
// Linux). Base dependency is `LyrebirdSynth` (the shared `@UIParam` model);
|
||||
// the Linux block below adds the SwiftOpenUI + BackendGTK4 backend deps. On
|
||||
// Apple, SwiftUI/AppKit are system frameworks so no package dep is needed.
|
||||
package.products.append(
|
||||
.library(name: "LyrebirdUI", targets: ["LyrebirdUI"])
|
||||
)
|
||||
package.targets.append(
|
||||
.target(
|
||||
name: "LyrebirdUI",
|
||||
dependencies: ["LyrebirdSynth"],
|
||||
path: "Sources/LyrebirdUI"
|
||||
)
|
||||
)
|
||||
|
||||
// Apple-only pieces, added only when the manifest host is macOS.
|
||||
//
|
||||
// `#if` cannot appear as an element inside an array literal in a package
|
||||
// manifest, so these are appended to the already-built `package` instead of
|
||||
// being conditionalized in place. On a native Linux/Windows host (in-container
|
||||
// `swift build`/`swift test`, CI) they are simply absent, so nothing tries to
|
||||
// compile SwiftUI/AppKit or the AudioToolbox-importing test files.
|
||||
//
|
||||
// • LyrebirdUITests — exercises LyrebirdUI (the module itself is now
|
||||
// cross-platform and appended above the initializer).
|
||||
// • LyrebirdBenchmark — micro-benchmarks Accelerate/vDSP primitives directly.
|
||||
// • LyrebirdTests — the main suite; still imports Apple frameworks
|
||||
// directly in some files (e.g. AUv3 driver tests).
|
||||
// Porting its platform-neutral majority to run on
|
||||
// Linux, plus Linux-runnable golden DSP tests, is a
|
||||
// separate work item.
|
||||
//
|
||||
// Cross-compiling from a Mac keeps the host as macOS, so Apple-SDK builds are
|
||||
// unaffected — they still see every target.
|
||||
#if os(macOS)
|
||||
package.targets.append(contentsOf: [
|
||||
.executableTarget(
|
||||
name: "LyrebirdBenchmark",
|
||||
dependencies: ["LyrebirdSynth"],
|
||||
path: "Sources/LyrebirdBenchmark",
|
||||
swiftSettings: [.unsafeFlags(["-O"])]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LyrebirdTests",
|
||||
dependencies: ["LyrebirdSynth"],
|
||||
path: "Tests/LyrebirdTests",
|
||||
linkerSettings: [
|
||||
.linkedFramework("AudioToolbox", .when(platforms: [.macOS, .iOS])),
|
||||
.linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])),
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LyrebirdUITests",
|
||||
dependencies: [
|
||||
"LyrebirdUI",
|
||||
"LyrebirdSynth",
|
||||
],
|
||||
path: "Tests/LyrebirdUITests"
|
||||
),
|
||||
])
|
||||
#endif
|
||||
|
||||
// Linux live audio. `ALSAAudioDriver` needs libasound's headers, which are not
|
||||
// installed by default on a build box (`apt-get install libasound2-dev`), so
|
||||
// the target is added only when the manifest is being evaluated ON Linux —
|
||||
// where those headers can actually exist. A macOS host never sees it, whether
|
||||
// building for Apple platforms or cross-compiling to Linux; a cross-compiled
|
||||
// Linux binary therefore has no live-audio driver, only offline NRT rendering.
|
||||
// Build natively on Linux to get audio out.
|
||||
//
|
||||
// Escape hatch: set `LYREBIRD_DISABLE_ALSA=1` to build the rest of Lyrebird on
|
||||
// a Linux box that has no ALSA development package. Everything except the
|
||||
// driver still works — `ALSAAudioDriver` is `#if canImport(CALSA)`-guarded and
|
||||
// simply will not exist, and `makeDefaultAudioDriver()` returns an
|
||||
// `OfflineDriver` instead. Note that SwiftPM caches evaluated manifests, so
|
||||
// flipping this variable on an existing checkout may need the cache cleared
|
||||
// (`rm -rf .build`, or a fresh `--scratch-path`) before it takes effect.
|
||||
#if os(Linux)
|
||||
if ProcessInfo.processInfo.environment["LYREBIRD_DISABLE_ALSA"] == nil {
|
||||
package.targets.append(
|
||||
.systemLibrary(
|
||||
name: "CALSA",
|
||||
path: "Sources/CALSA",
|
||||
pkgConfig: "alsa",
|
||||
providers: [
|
||||
.apt(["libasound2-dev"]),
|
||||
]
|
||||
)
|
||||
)
|
||||
if let synthIndex: Int = package.targets.firstIndex(where: { $0.name == "LyrebirdSynth" }) {
|
||||
package.targets[synthIndex].dependencies.append(.target(name: "CALSA"))
|
||||
}
|
||||
// The portable test target needs it too: its ALSA tests are guarded on
|
||||
// `canImport(CALSA)`, which is only true where the module is a dependency.
|
||||
// Without this the guard is always false and the driver's tests silently
|
||||
// never run.
|
||||
if let testIndex: Int = package.targets.firstIndex(where: { $0.name == "LyrebirdPortableTests" }) {
|
||||
package.targets[testIndex].dependencies.append(.target(name: "CALSA"))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// Linux backend for the cross-platform `LyrebirdUI`: SwiftOpenUI (GTK4). This is
|
||||
// now a DEFAULT Linux dependency — building `LyrebirdUI` on Linux pulls
|
||||
// SwiftOpenUI and needs `libgtk-4-dev`. (The default *core* Linux CI lane builds
|
||||
// only LyrebirdSynth / LyrebirdGraphDSL / LyrebirdCLI, so it does not build the
|
||||
// UI or need GTK; a plain `swift build` on Linux does.)
|
||||
//
|
||||
// Pinned to a personal fork commit carrying the GTK4 drag fix ("GTK4: continuous
|
||||
// drag for Canvas value controls": @Observable narrow path + live subtree redraw
|
||||
// + global interaction deferral with linked-control redraw). Move the pin to
|
||||
// `codelynx/SwiftOpenUI` + a version once the fix lands upstream and a release is
|
||||
// tagged. See spikes/SwiftOpenUIKnob/FORK_PATCH_PLAN.md.
|
||||
//
|
||||
// `LyrebirdUI`'s controls bind core `@UIParam` / `UIParamNode` (in
|
||||
// `LyrebirdSynth`), the same model the SwiftUI controls use, so one synthesizer's
|
||||
// parameters drive both platforms.
|
||||
#if os(Linux)
|
||||
// Set LYREBIRD_SWIFTOPENUI_LOCAL=/path/to/SwiftOpenUI to build against a local
|
||||
// fork checkout instead of the pinned release — used to iterate the GTK4 fork
|
||||
// without a push/pin round-trip (this Mac can't build the GTK4 backend; a Linux
|
||||
// container or the VM does). Unset (the default), it resolves the pinned tag.
|
||||
package.dependencies.append(
|
||||
ProcessInfo.processInfo.environment["LYREBIRD_SWIFTOPENUI_LOCAL"].map {
|
||||
.package(name: "SwiftOpenUI", path: $0)
|
||||
} ??
|
||||
// Pinned to the fork's tagged release 0.5.0 (== commit a392026): 0.1.0
|
||||
// (Patches A–F narrow-path + GTK4Backend.openStandaloneWindow → LyrebirdWindow
|
||||
// / presentInWindow + GTK4PointerTracking → Linux MouseTracker), plus the
|
||||
// GtkSourceView-backed `CodeEditor` view (Swift highlighting + gutter) used by
|
||||
// the Linux live-compile scratch editor — which adds a system dependency on
|
||||
// libgtksourceview-5-dev. A tag rather than a bare commit gives a stable,
|
||||
// human-readable release reference; bump it when the fork cuts a new release.
|
||||
// (Upstreaming to codelynx/SwiftOpenUI remains the open follow-on — see
|
||||
// docs/ui/linux-parity-plan.md.)
|
||||
.package(
|
||||
url: "https://github.com/joshpar/SwiftOpenUI",
|
||||
exact: "0.7.0"
|
||||
)
|
||||
)
|
||||
// Give the cross-platform LyrebirdUI target its Linux (GTK4) backend deps.
|
||||
if let uiIndex: Int = package.targets.firstIndex(where: { $0.name == "LyrebirdUI" }) {
|
||||
package.targets[uiIndex].dependencies.append(contentsOf: [
|
||||
.product(name: "SwiftOpenUI", package: "SwiftOpenUI"),
|
||||
.product(name: "BackendGTK4", package: "SwiftOpenUI"),
|
||||
])
|
||||
}
|
||||
// Runnable GTK4 GUI demo: `swift run LyrebirdUILinuxDemo`.
|
||||
package.targets.append(
|
||||
.executableTarget(
|
||||
name: "LyrebirdUILinuxDemo",
|
||||
dependencies: ["LyrebirdSynth", "LyrebirdUI"],
|
||||
path: "Sources/LyrebirdUILinuxDemo"
|
||||
)
|
||||
)
|
||||
#endif
|
||||
|
||||
@@ -100,7 +100,7 @@ tone.amp = 0.1
|
||||
engine.remove(tone) // fades out at the next block boundary
|
||||
```
|
||||
|
||||
Prefer a GUI? The `LyrebirdScratchDemo` app embeds `LyrebirdScratchView`: type a snippet, press **⌘↩** to compile-and-hot-swap it against the live engine (or **⌘⇧↩** to layer additively). Each snippet receives a `SnippetContext` — `context.engine` and `context.play(_:)`:
|
||||
Prefer a GUI? The `LyrebirdScratch` app embeds `LyrebirdScratchView`: type a snippet, press **⌘↩** to compile-and-hot-swap it against the live engine (or **⌘⇧↩** to layer additively). Each snippet receives a `SnippetContext` — `context.engine` and `context.play(_:)`:
|
||||
|
||||
```swift
|
||||
// Snippet body — `context: SnippetContext` is in scope.
|
||||
@@ -149,6 +149,8 @@ That's it — the `Lyrebird` product links **statically**, so there's no dynamic
|
||||
|
||||
Full walk-through (SPM manifest form, local-path dev dependency, per-template details): [`INSTALLATION_AND_USAGE.md`](INSTALLATION_AND_USAGE.md). DocC version: **Getting Started ▸ Adding Lyrebird to your own Xcode project**.
|
||||
|
||||
**On Linux?** The non-UI core — engine, generators, CLI, offline render, live ALSA audio, MIDI, and OSC — builds and runs on Linux (no Xcode, no SwiftUI). Start here: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
|
||||
|
||||
---
|
||||
|
||||
## Opening in Xcode
|
||||
@@ -176,7 +178,7 @@ Workspace scheme selector exposes ten entries:
|
||||
| `LyrebirdNRTDemo` | CLI — offline render to CAF via `NRTDriver` | macOS |
|
||||
| `LyrebirdScoreDemo` | CLI — builds notated `Score`s (result-builder DSL), exports MusicXML, renders to CAF via `NRTDriver` | 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 |
|
||||
| `LyrebirdScratchDemo` | 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 |
|
||||
|
||||
Use `Lyrebird-Package` for day-to-day development of the engine and tests.
|
||||
|
||||
@@ -218,7 +220,7 @@ All eight live in [`Demos/`](Demos/). Open via `Lyrebird.xcworkspace`.
|
||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render to CAF file via `NRTDriver` | macOS |
|
||||
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | CLI — notated `Score` → MusicXML export + offline render to CAF via `NRTDriver` | 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 |
|
||||
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | 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 |
|
||||
|
||||
Each demo has a `Synthesizers/` folder — drop new `SynthesizerBase` subclasses there. See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for step-by-step instructions and per-demo notes.
|
||||
|
||||
@@ -284,7 +286,7 @@ LyrebirdII/
|
||||
│ ├── LyrebirdNRTDemo/ # offline renderer
|
||||
│ ├── LyrebirdScoreDemo/ # notated Score → MusicXML + offline render
|
||||
│ ├── LyrebirdAUv3Demo/ # AUv3 `aumu` plugin reference (LyrebirdFM)
|
||||
│ └── LyrebirdScratchDemo/ # live-coding scratchpad (macOS, no sandbox)
|
||||
│ └── LyrebirdScratch/ # live-coding scratchpad (macOS, no sandbox)
|
||||
├── Tests/
|
||||
│ ├── LyrebirdTests/ # 5253 engine + generator tests
|
||||
│ ├── LyrebirdUITests/ # SwiftUI component tests
|
||||
|
||||
@@ -7,6 +7,361 @@ functionality in a backward-compatible way.
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
|
||||
A minor release. Backward-compatible — the existing default write formats are
|
||||
unchanged; everything here is additive. One shared `AudioFileFormat` enum now
|
||||
drives every writer (`LyrebirdBuffer.write`, offline `NRTDriver` renders, and the
|
||||
real-time `DiskOut.Audio` recorder).
|
||||
|
||||
### New — audio output formats
|
||||
|
||||
```swift
|
||||
// Buffer / NRT / DiskOut (PCM):
|
||||
try buf.write(to: url, format: .wavInt24, sampleRate: 48000) // 16 / 24-bit WAV
|
||||
try buf.write(to: url, format: .aiffFloat32, sampleRate: 48000) // AIFF-C float
|
||||
try buf.write(to: url, format: .cafFloat32, sampleRate: 48000) // CAF (uncapped)
|
||||
|
||||
// Files past 4 GB — RF64/BW64, keeps the .wav extension:
|
||||
try buf.write(to: url, format: .rf64Float32, sampleRate: 96000)
|
||||
try buf.write(to: url, format: .rf64Int24, sampleRate: 96000)
|
||||
|
||||
// Compressed .m4a — offline writers only (LyrebirdBuffer.write / NRTDriver):
|
||||
try buf.write(to: url, format: .aacHigh, sampleRate: 44100) // AAC ~256 kbps
|
||||
try buf.write(to: url, format: .aacMedium, sampleRate: 44100) // AAC ~128 kbps
|
||||
try buf.write(to: url, format: .alac, sampleRate: 44100) // Apple Lossless
|
||||
```
|
||||
|
||||
- **WAV bit depths** — 16-bit and 24-bit signed-integer PCM alongside 32-bit float.
|
||||
- **AIFF-C** and **CAF** float output across all writers.
|
||||
- **RF64 / BW64** (EBU Tech 3306) — the 64-bit-sized WAV variant for files past the
|
||||
4 GB limit, written by Lyrebird's own `RF64Writer` (CoreAudio has no RF64 *writer*;
|
||||
it reads them back fine). Opt-in `.rf64Float32` / `.rf64Int24`.
|
||||
- **Compressed AAC + Apple Lossless** (`.m4a`) — encoded natively through
|
||||
`ExtAudioFile`/`AudioConverter`, no third-party dependency. **Offline writers only**
|
||||
(`LyrebirdBuffer.write`, `NRTDriver`); `DiskOut.Audio` streams PCM/RF64 only. (MP3 is
|
||||
not offered — CoreAudio has no MP3 encoder.)
|
||||
- **Selectable NRT output** — `NRTDriver` / `NRTJob` take a `format:` (default CAF/float,
|
||||
unchanged), so offline renders and the multi-engine batch pool can bounce to any format.
|
||||
|
||||
### New — large-file safety
|
||||
|
||||
Plain WAV and AIFF-C carry 32-bit size fields (a 4 GB cap). A write projected past
|
||||
that now **throws `fileTooLargeForContainer`** (buffer / NRT) or stops cleanly and sets
|
||||
a pollable `fileTooLarge` flag (streaming `DiskOut`) instead of silently producing a
|
||||
truncated file. CAF and RF64 are 64-bit-sized and uncapped. `NRTDriver` also validates
|
||||
its `duration` (finite, non-negative) — `NRTDriverError.invalidDuration`.
|
||||
|
||||
### New — Live Scratch: Render-to-File format picker
|
||||
|
||||
The Scratch **Render to File** (⌥⌘R) save dialog now carries a **Format** popup (WAV
|
||||
32-bit float / 16-bit / 24-bit, AIFF, CAF, RF64 WAV, and compressed AAC / Apple
|
||||
Lossless) plus the duration field, folded into one dialog. It remembers the last
|
||||
format. Sample rate and channel count still mirror the live engine.
|
||||
|
||||
### Changed
|
||||
|
||||
- **`DiskOutFormat` is deprecated** — it is now a type alias for `AudioFileFormat`.
|
||||
Existing `DiskOutFormat.wavFloat32` / `.aiff` / etc. spellings keep compiling (with a
|
||||
deprecation warning); migrate to `AudioFileFormat` directly.
|
||||
- `LyrebirdEventList.record(directory:format:)` now takes an `AudioFileFormat`. Stem
|
||||
recording is PCM/RF64 only — a compressed format is rejected with a logged message
|
||||
(stems stream through `DiskOut`, which does not do compressed).
|
||||
|
||||
---
|
||||
|
||||
## 1.5.0 — `LyrebirdRandom` + the Live Scratch editor grows up
|
||||
|
||||
A minor release. Backward-compatible — new public API plus a wave of Live Scratch
|
||||
tooling. No changes to existing behavior.
|
||||
|
||||
### New — scalar draws from any distribution (`LyrebirdRandom`)
|
||||
|
||||
Lyrebird had distribution-tied **signals** (noise generators), **sequences**
|
||||
(`Pattern`, `TemporalStream`), and the `DistributionKind` sampling math — but no
|
||||
ergonomic way to get *one value* from a named distribution. `LyrebirdRandom`
|
||||
fills that gap:
|
||||
|
||||
```swift
|
||||
var r = LyrebirdRandom(seed: 42)
|
||||
let freq: Double = r.exponentialRange(low: 200, high: 2000) // Hz, log-uniform
|
||||
let dur: Double = r.uniform(low: 0.1, high: 0.5) // seconds
|
||||
let jitter: Double = r.gauss(mean: 0, dev: 0.02)
|
||||
let skew: Double = r.beta(low: 0, high: 1, alpha: 2, beta: 5)
|
||||
let spike: Double = r.laplace(scale: 1.0)
|
||||
```
|
||||
|
||||
- **`LyrebirdRandom`** — a seedable value type owning a xorshift64 state, so a
|
||||
seed gives a fully reproducible stream of draws (what scored/rendered music
|
||||
wants). Named methods for every family in `DistributionKind` (uniform, low/
|
||||
high/mean-biased, exponential-range, exponential, gamma, laplace, asymmetric
|
||||
laplace, half-cosine, logistic, poisson, arcsin, beta, cauchy, gauss), plus a
|
||||
generic `value(_:parX:parY:parA:parB:)` reaching any kind.
|
||||
- **`LyrebirdRandom.shared`** (`SharedRandom`) — a process-wide, thread-safe
|
||||
source for throwaway draws (system-seeded, non-reproducible). The global
|
||||
**`Random`** is a shorthand for it, for the common non-seeded case:
|
||||
`Random.uniform(low: 0, high: 1)`. (Takes a lock — not RT-safe; use an owned
|
||||
`LyrebirdRandom` inside a Generator.)
|
||||
- **`DistributionKind.sample(parX:parY:parA:parB:using:)`** — the public
|
||||
single-draw dispatcher, now the single source of truth for the case→sampler
|
||||
mapping: `TemporalTendency` and `DemandTemporalTendency` were refactored onto it
|
||||
(behavior pinned by the golden-value tests), so a scalar draw and a stream of
|
||||
the same distribution agree given the same seed.
|
||||
|
||||
For a plain uniform scalar the Swift stdlib (`Double.random(in:)`) is still the
|
||||
lightest choice; reach for `LyrebirdRandom` when you want a *shaped* distribution
|
||||
or a reproducible seeded stream.
|
||||
|
||||
### Live Scratch — renamed and a lot more capable
|
||||
|
||||
The macOS live-coding scratchpad graduated from a demo to a shipping app:
|
||||
**`LyrebirdScratchDemo` → `LyrebirdScratch`** (bundle id
|
||||
`net.realizedsound.LyrebirdScratch`; project, scheme, entitlements renamed). New
|
||||
in the editor:
|
||||
|
||||
- **Render to File (⌥⌘R)** — bounce the selection (or whole buffer) to a **CAF**
|
||||
file offline instead of playing it live. Prompts for a path and duration, builds
|
||||
the graph on a throwaway `NRTDriver` engine mirroring the live engine's settings
|
||||
(so the bounce matches what you heard), renders faster-than-real-time off the
|
||||
main thread, and reveals the file in Finder. Only **sample-clock** timing renders
|
||||
(`engine.schedule`, in-graph triggers) — wall-clock routine/task waits don't.
|
||||
- **Format Code (⌥⌘F)** — pretty-print the buffer with the toolchain's
|
||||
`swift-format`. No-op on a blank buffer; parse errors go to the console.
|
||||
- **Line-number gutter** — a floating `ScratchLineNumberGutter` overlay,
|
||||
positioned from each row's line-fragment rect so numbers align on blank and
|
||||
wrapped lines. (An `NSRulerView` attempt was abandoned — `rulersVisible`
|
||||
mis-tiles the document view inside a SwiftUI `NSViewRepresentable`, blanking the
|
||||
editor.)
|
||||
- **`Foundation` in scope** — snippets can use `pow`, `sin`, `sqrt`, `Date`, … with
|
||||
no `import` (a snippet can't declare one — its body is wrapped in the entry
|
||||
function).
|
||||
- **Manual code completion (Esc / F5)** — no more auto-trigger on `.` that
|
||||
ambushed typing; completion replaces the partial word, not the receiver.
|
||||
- **Fixed — editor scroll-jump**: the engine status readout refreshed via
|
||||
`.id(engineTick)`, tearing down subviews every heartbeat and nudging the scroll
|
||||
offset. Stats now update in place from an `@State` snapshot.
|
||||
|
||||
### New — compile artifacts stage into Application Support (no Documents prompt)
|
||||
|
||||
Swift-mode compilation points `swiftc` at the Lyrebird module artifacts, which in
|
||||
a dev checkout live under `~/Documents` — tripping the macOS "wants to access your
|
||||
Documents folder" gate. `LiveSession.stageArtifacts()` copies the minimal set into
|
||||
`~/Library/Application Support/LyrebirdScratch/LiveCompile/` (ungated), rewriting
|
||||
the C module map's absolute umbrella-header path to a staged copy so the compile
|
||||
is self-contained. Idempotent (a receipt skips an unchanged source), best-effort
|
||||
(falls back to the build dir). A **shipped** app carrying its artifacts in
|
||||
`Contents/Resources/LyrebirdArtifacts` never reads a gated folder — groundwork for
|
||||
a standalone `LyrebirdScratch.app` download.
|
||||
|
||||
### Docs
|
||||
|
||||
New guidance on snippet **timing / scheduling** — `engine.schedule`,
|
||||
`LyrebirdRoutine` / `LyrebirdTask` (background-thread waits), `LyrebirdClock`,
|
||||
in-graph triggers — the retention rule (the snippet is transient), and which
|
||||
mechanisms survive an offline NRT render vs. which are wall-clock-only.
|
||||
|
||||
---
|
||||
|
||||
## 1.4.2 — Live-coding: Run Selection + graceful slot release
|
||||
|
||||
A minor release. Backward-compatible — additive conveniences to the (macOS-only)
|
||||
|
||||
@@ -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
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
@@ -40,3 +41,4 @@ public struct LyrebirdAUFactoryPreset: Sendable {
|
||||
self.sourceSlots = sourceSlots
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
@@ -26,3 +27,4 @@ public struct LyrebirdAUParameterEntry {
|
||||
/// and to write new values via `_writeAtomicValue`.
|
||||
public let node: any LiveParameterValue
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
import AudioToolbox
|
||||
@@ -74,3 +75,4 @@ public let lyrebirdAUParameterDefaultFlags: AudioUnitParameterOptions = [
|
||||
.flag_IsWritable,
|
||||
.flag_CanRamp,
|
||||
]
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
import AudioToolbox
|
||||
@@ -100,3 +101,4 @@ public enum LyrebirdAUParameterMapping {
|
||||
return (tree, nodes)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
@@ -118,3 +119,4 @@ public enum LyrebirdAUPresetSourceRegistry {
|
||||
return _factories.keys.sorted()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
@@ -136,3 +137,4 @@ public final class LyrebirdAUVoicePoolBinding<S: SynthesizerBase> {
|
||||
/// `Double(velocity) / Double(midiVelocityMax)` yields the conventional `[0,1]`
|
||||
/// range used by `@LiveParam` amplitude parameters.
|
||||
public let midiVelocityMax: UInt8 = 127
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
import AudioToolbox
|
||||
@@ -721,3 +722,4 @@ public let lyrebirdAUFullStateSourcesKey: String = "sources"
|
||||
/// Sub-key inside the root payload that holds the per-parameter source-slot
|
||||
/// generator type IDs: `[paramName: presetTypeID]`.
|
||||
public let lyrebirdAUFullStateSourceTypesKey: String = "sourceTypes"
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,648 @@
|
||||
// ALSAAudioDriver.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Linux live audio. `CALSA` (libasound) is only a dependency of `LyrebirdSynth`
|
||||
// on Linux — see Package.swift — so on Apple platforms this file compiles away
|
||||
// entirely and `CoreAudioDriver` / `iOSAudioDriver` remain the only RT drivers.
|
||||
#if canImport(CALSA)
|
||||
import CALSA
|
||||
import Foundation
|
||||
import Synchronization
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#endif
|
||||
|
||||
/// A real-time ALSA driver that connects a ``SynthesisEngine`` to Linux audio
|
||||
/// hardware.
|
||||
///
|
||||
/// The transport is a blocking `snd_pcm_writei` loop on a dedicated thread —
|
||||
/// the simplest shape that is correct: no callback re-entrancy, no ALSA async
|
||||
/// handler restrictions, and back-pressure comes for free from the device.
|
||||
/// Every buffer is allocated in ``setup(engine:)``, so the loop body itself
|
||||
/// performs no allocation.
|
||||
///
|
||||
/// **Typical usage**:
|
||||
/// ```swift
|
||||
/// let driver = ALSAAudioDriver()
|
||||
/// let engine = SynthesisEngine(
|
||||
/// blockSize: 512, sampleRate: 44100,
|
||||
/// numOutputChannels: 2, numInputChannels: 0,
|
||||
/// driver: driver
|
||||
/// )
|
||||
/// try engine.start()
|
||||
/// // … audio running …
|
||||
/// engine.stop()
|
||||
/// ```
|
||||
///
|
||||
/// **Duplex** — when the engine requests input channels, a capture PCM is
|
||||
/// opened as well and `snd_pcm_link` ties the two streams to one clock so they
|
||||
/// cannot drift. If the device pair refuses to link, the driver still runs
|
||||
/// (read-then-write ordering keeps them approximately aligned) and reports it
|
||||
/// through ``linkedStreams``.
|
||||
///
|
||||
/// **Sample format** — `SND_PCM_FORMAT_FLOAT_LE`, matching the engine's `Float`
|
||||
/// buses exactly, so no conversion or dithering happens anywhere in the path.
|
||||
/// ALSA converts to the hardware's own format underneath.
|
||||
///
|
||||
/// > Note: this driver has been verified to build and to fail cleanly with no
|
||||
/// > sound device present; it has not yet been run against real Linux audio
|
||||
/// > hardware. See LINUX_PLAN.md.
|
||||
public final class ALSAAudioDriver: AudioDriver, @unchecked Sendable {
|
||||
|
||||
// Unchecked Sendable: every stored property is written either in `init` or
|
||||
// in `setup`/`start` before the render thread exists, and read-only
|
||||
// afterwards, except `_isRunning` / `_hasRealtimePriority` (atomic) and
|
||||
// `_lastError` (mutex), which the render thread writes while it runs.
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// ALSA device name for playback. `"default"` follows the user's
|
||||
/// `~/.asoundrc` / system configuration, which is what a desktop app wants;
|
||||
/// `"hw:0,0"` addresses a card directly and bypasses dmix.
|
||||
public var device: String = "default"
|
||||
|
||||
/// ALSA device name for capture. Used only when the engine requests input
|
||||
/// channels.
|
||||
public var captureDevice: String = "default"
|
||||
|
||||
/// Ring-buffer depth as a multiple of the engine's block size. Larger
|
||||
/// tolerates more scheduling jitter at the cost of latency.
|
||||
public var periodsPerBuffer: Int = defaultPeriodsPerBuffer
|
||||
|
||||
/// When `true`, ALSA resamples if the hardware cannot do the engine's rate.
|
||||
/// When `false`, a rate the device cannot produce is an error instead of a
|
||||
/// silent quality loss.
|
||||
public var allowSoftwareResampling: Bool = false
|
||||
|
||||
/// When `true`, the render thread asks for `SCHED_FIFO`. Failure is not
|
||||
/// fatal — unprivileged processes normally cannot get it, and the driver
|
||||
/// runs at normal priority instead (see ``hasRealtimePriority``).
|
||||
public var requestsRealtimePriority: Bool = true
|
||||
|
||||
// MARK: - Status
|
||||
|
||||
/// Whether `SCHED_FIFO` was actually granted to the render thread.
|
||||
///
|
||||
/// Set by the render thread itself, after `start()` has already returned,
|
||||
/// so it is atomic rather than a plain `var` — a caller polling it right
|
||||
/// after `start()` would otherwise race the write.
|
||||
public var hasRealtimePriority: Bool { _hasRealtimePriority.load(ordering: .acquiring) }
|
||||
|
||||
/// Whether capture and playback were successfully clock-linked. Always
|
||||
/// `false` when the engine requests no input channels.
|
||||
public private(set) var linkedStreams: Bool = false
|
||||
|
||||
/// The error that ended the render loop, if it ended on its own.
|
||||
///
|
||||
/// Written by the render thread as it exits and read from wherever `stop()`
|
||||
/// is called, so it is behind a mutex — the lock is only ever taken on the
|
||||
/// failure path and by callers, never in the steady-state loop.
|
||||
public var lastError: ALSAError? { _lastError.withLock { $0 } }
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Four periods is the usual desktop compromise: enough slack that an
|
||||
/// ordinary scheduling hiccup does not underrun, short enough to stay
|
||||
/// playable.
|
||||
private static let defaultPeriodsPerBuffer: Int = 4
|
||||
private static let microsecondsPerSecond: Double = 1_000_000
|
||||
/// `SCHED_FIFO` priority as a fraction of the policy's usable range. Well
|
||||
/// clear of the top so a runaway render loop cannot lock out the kernel's
|
||||
/// own high-priority threads.
|
||||
private static let realtimePriorityFraction: Double = 0.75
|
||||
/// How long `stop()` waits for the render thread to leave its loop before
|
||||
/// closing the PCM handles anyway.
|
||||
private static let threadJoinTimeout: TimeInterval = 2.0
|
||||
/// `snd_pcm_recover` argument: 1 silences its own logging to stderr.
|
||||
private static let recoverSilently: Int32 = 1
|
||||
/// How long `snd_pcm_wait` blocks for the device to become writable again
|
||||
/// after a would-block return, in milliseconds. Waiting beats spinning: the
|
||||
/// render thread may hold `SCHED_FIFO`, where a busy loop starves the box.
|
||||
private static let deviceWaitMilliseconds: Int32 = 200
|
||||
/// Consecutive no-progress transfers (would-block, or zero frames moved)
|
||||
/// tolerated before the stream is declared dead. At the wait above this is
|
||||
/// ~2 s of a device that never becomes ready, which no working
|
||||
/// configuration does.
|
||||
@_spi(LyrebirdExtensions)
|
||||
public static let maxConsecutiveStalls: Int = 10
|
||||
/// Consecutive signal interruptions tolerated. Far larger than the stall
|
||||
/// budget because a signal says nothing about the device's health — this is
|
||||
/// a bound only so a pathological signal source cannot spin the loop.
|
||||
private static let maxConsecutiveInterrupts: Int = 1000
|
||||
|
||||
// MARK: - State
|
||||
|
||||
private var playbackPCM: OpaquePointer?
|
||||
private var capturePCM: OpaquePointer?
|
||||
|
||||
private var engineRef: Unmanaged<SynthesisEngine>?
|
||||
private var blockSize: Int = 0
|
||||
private var sampleRate: Double = 0
|
||||
private var outputChannels: Int = 0
|
||||
private var inputChannels: Int = 0
|
||||
|
||||
/// Interleaved staging buffers handed to ALSA. Raw pointers rather than
|
||||
/// arrays so their addresses are stable for the thread's lifetime.
|
||||
private var interleavedOutput: UnsafeMutablePointer<Float>?
|
||||
private var interleavedInput: UnsafeMutablePointer<Float>?
|
||||
|
||||
/// Planar input handed to `processBlock`, pre-allocated so the loop never
|
||||
/// grows it.
|
||||
private var inputStagingBuffers: [[Float]] = []
|
||||
|
||||
private let _isRunning: Atomic<Bool> = Atomic<Bool>(false)
|
||||
private let _hasRealtimePriority: Atomic<Bool> = Atomic<Bool>(false)
|
||||
/// Set when a `stop()` gave up waiting for the render thread. The thread is
|
||||
/// still out there, still testing `_isRunning`, so the driver must never
|
||||
/// start another one: a wedged transfer that finally returns would find the
|
||||
/// flag true again and resume rendering alongside its replacement.
|
||||
private let _abandonedThread: Atomic<Bool> = Atomic<Bool>(false)
|
||||
private let _lastError: Mutex<ALSAError?> = Mutex<ALSAError?>(nil)
|
||||
private var renderThread: Thread?
|
||||
private let threadExited: DispatchSemaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
public init() {
|
||||
// Initialise the RT-identity TLS key from this known non-RT call site,
|
||||
// so the render thread's first `markCurrentThreadAsRT()` cannot be the
|
||||
// allocating one.
|
||||
RTThreadIdentity.warmUp()
|
||||
}
|
||||
|
||||
deinit {
|
||||
stop()
|
||||
// Belt and braces: `Thread { [weak self] in self?.renderLoop(...) }`
|
||||
// holds `self` strongly for the whole call, so `deinit` cannot actually
|
||||
// run while an abandoned loop is still inside it. If that ever changes,
|
||||
// freeing these buffers would be a use-after-free, so the guard stays.
|
||||
guard !_abandonedThread.load(ordering: .acquiring) else { return }
|
||||
interleavedOutput?.deallocate()
|
||||
interleavedInput?.deallocate()
|
||||
}
|
||||
|
||||
/// ALSA's period granularity is the engine block, so control-rate
|
||||
/// resolution matches the other live drivers.
|
||||
public var suggestedControlBlockSize: Int? { lyrebirdDefaultControlBlockSize }
|
||||
|
||||
// MARK: - AudioDriver
|
||||
|
||||
public func setup(engine: SynthesisEngine) throws {
|
||||
guard !_abandonedThread.load(ordering: .acquiring) else {
|
||||
// Reallocating the staging buffers would pull them out from under
|
||||
// the thread that never came back.
|
||||
throw ALSAError.renderThreadDidNotExit
|
||||
}
|
||||
engineRef = Unmanaged.passUnretained(engine)
|
||||
blockSize = engine.blockSize
|
||||
sampleRate = engine.sampleRate
|
||||
outputChannels = engine.numOutputChannels
|
||||
inputChannels = engine.numInputChannels
|
||||
|
||||
interleavedOutput?.deallocate()
|
||||
interleavedOutput = UnsafeMutablePointer<Float>.allocate(
|
||||
capacity: blockSize * max(outputChannels, 1)
|
||||
)
|
||||
interleavedOutput?.initialize(repeating: 0, count: blockSize * max(outputChannels, 1))
|
||||
|
||||
interleavedInput?.deallocate()
|
||||
interleavedInput = nil
|
||||
inputStagingBuffers = []
|
||||
if inputChannels > 0 {
|
||||
let inputPointer: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(
|
||||
capacity: blockSize * inputChannels
|
||||
)
|
||||
inputPointer.initialize(repeating: 0, count: blockSize * inputChannels)
|
||||
interleavedInput = inputPointer
|
||||
inputStagingBuffers = [[Float]](
|
||||
repeating: [Float](repeating: 0, count: blockSize),
|
||||
count: inputChannels
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
public func start() throws {
|
||||
guard engineRef != nil, blockSize > 0 else { throw ALSAError.notConfigured }
|
||||
guard !_abandonedThread.load(ordering: .acquiring) else {
|
||||
// A previous render thread never came back. Starting a second one
|
||||
// would put two threads on one engine the moment the first unwedges.
|
||||
throw ALSAError.renderThreadDidNotExit
|
||||
}
|
||||
guard !_isRunning.load(ordering: .acquiring) else { return }
|
||||
|
||||
// A loop that ended on its own leaves a finished thread and a signalled
|
||||
// semaphore behind; clear them before starting another.
|
||||
if renderThread != nil { stop() }
|
||||
// That `stop()` can itself time out and latch — re-check, or the exact
|
||||
// state the latch exists to prevent gets created a few lines below.
|
||||
guard !_abandonedThread.load(ordering: .acquiring) else {
|
||||
throw ALSAError.renderThreadDidNotExit
|
||||
}
|
||||
|
||||
_lastError.withLock { $0 = nil }
|
||||
do {
|
||||
try openPlayback()
|
||||
if inputChannels > 0 {
|
||||
try openCapture()
|
||||
}
|
||||
} catch {
|
||||
// Never leave a half-open device: a playback handle that opened
|
||||
// before capture failed would otherwise stay claimed until deinit.
|
||||
closeDevices()
|
||||
throw error
|
||||
}
|
||||
|
||||
// Drain a stale signal from a previous run that timed out in `stop()`
|
||||
// and whose thread signalled afterwards; leaving it pending would make
|
||||
// the next `stop()` return from its wait immediately.
|
||||
while threadExited.wait(timeout: .now()) == .success {}
|
||||
|
||||
_hasRealtimePriority.store(false, ordering: .releasing)
|
||||
_isRunning.store(true, ordering: .releasing)
|
||||
|
||||
// The engine is held unowned for the driver's normal life (it owns the
|
||||
// driver, so retaining it back would be a cycle), but the render thread
|
||||
// must not outlive it — and an abandoned thread can, since nothing can
|
||||
// stop it. Retain for exactly the thread's lifetime: the loop's `defer`
|
||||
// releases, so a thread that never returns pins the engine forever,
|
||||
// which is the point.
|
||||
//
|
||||
// `retain()` bumps the pointee's count without ever materialising a
|
||||
// Swift reference — `takeUnretainedValue()` on a since-freed engine
|
||||
// would be undefined behaviour, not a recoverable `nil`. `engineRef` is
|
||||
// already known non-nil (checked at the top of `start()`).
|
||||
guard let engineUnmanaged: Unmanaged<SynthesisEngine> = engineRef else {
|
||||
_isRunning.store(false, ordering: .releasing)
|
||||
throw ALSAError.notConfigured
|
||||
}
|
||||
// Carried across the thread boundary as a bit pattern: `Thread`'s
|
||||
// closure is `@Sendable`, and neither `Unmanaged` nor a raw pointer is
|
||||
// Sendable under Swift 6 — the same reason `SynthesizerBase` stores its
|
||||
// engine binding as an `Atomic<UInt>`. The retain is real; the loop's
|
||||
// `defer` releases it.
|
||||
let engineBits: UInt = Self.retainForRenderThread(engineUnmanaged)
|
||||
let thread: Thread = Thread { [weak self] in
|
||||
guard let self: ALSAAudioDriver = self else {
|
||||
Self.releaseEngine(bits: engineBits)
|
||||
return
|
||||
}
|
||||
self.renderLoop(engineBits: engineBits)
|
||||
}
|
||||
thread.name = "lyrebird.alsa.render"
|
||||
renderThread = thread
|
||||
thread.start()
|
||||
}
|
||||
|
||||
public func stop() {
|
||||
// Already abandoned: that thread is gone as far as this driver is
|
||||
// concerned and its resources are deliberately leaked, so `renderThread`
|
||||
// must not be touched again. A `deinit`-driven `stop()` can run on the
|
||||
// render thread itself once a wedged transfer finally returns, which
|
||||
// would race the original `stop()`'s write from the caller's thread.
|
||||
guard !_abandonedThread.load(ordering: .acquiring) else { return }
|
||||
|
||||
_isRunning.store(false, ordering: .releasing)
|
||||
guard renderThread != nil else {
|
||||
closeDevices()
|
||||
return
|
||||
}
|
||||
// Join whenever a thread was launched — including one that already
|
||||
// exited on its own error path. Closing the PCM handles while the
|
||||
// thread could still touch them is a use-after-free, so the wait is not
|
||||
// conditional on the running flag. The loop tests the flag once per
|
||||
// block and so leaves within roughly one block period.
|
||||
let exited: Bool = threadExited.wait(timeout: .now() + Self.threadJoinTimeout) == .success
|
||||
renderThread = nil
|
||||
guard exited else {
|
||||
// The thread is stuck inside a transfer. Closing its PCM handles or
|
||||
// freeing the buffers it is reading would be exactly the
|
||||
// use-after-free the join exists to prevent, so abandon them
|
||||
// instead: a leak is recoverable, a wild write is not. The handles
|
||||
// stay open until the process exits, so a subsequent `start()` may
|
||||
// fail with the device busy — which is the truth, and better than
|
||||
// pretending the stop succeeded.
|
||||
// Nothing is written here on purpose. The thread that owns these
|
||||
// handles and buffers is still alive and still reading them; the
|
||||
// abandon latch is what keeps every later path — `closeDevices()`,
|
||||
// `deinit`, a second `start()` — from touching them. Clearing the
|
||||
// properties would be its own data race, on top of the
|
||||
// use-after-free the join exists to prevent.
|
||||
_lastError.withLock { $0 = .renderThreadDidNotExit }
|
||||
_abandonedThread.store(true, ordering: .releasing)
|
||||
return
|
||||
}
|
||||
closeDevices()
|
||||
}
|
||||
|
||||
// MARK: - Device setup
|
||||
|
||||
private func openPlayback() throws {
|
||||
var pcm: OpaquePointer?
|
||||
let openResult: Int32 = snd_pcm_open(&pcm, device, SND_PCM_STREAM_PLAYBACK, 0)
|
||||
guard openResult >= 0, let handle: OpaquePointer = pcm else {
|
||||
throw ALSAError.playbackDeviceOpenFailed(device: device, code: Int(openResult))
|
||||
}
|
||||
playbackPCM = handle
|
||||
try configure(handle, channels: outputChannels, stream: "playback")
|
||||
}
|
||||
|
||||
private func openCapture() throws {
|
||||
var pcm: OpaquePointer?
|
||||
let openResult: Int32 = snd_pcm_open(&pcm, captureDevice, SND_PCM_STREAM_CAPTURE, 0)
|
||||
guard openResult >= 0, let handle: OpaquePointer = pcm else {
|
||||
throw ALSAError.captureDeviceOpenFailed(device: captureDevice, code: Int(openResult))
|
||||
}
|
||||
capturePCM = handle
|
||||
try configure(handle, channels: inputChannels, stream: "capture")
|
||||
|
||||
// One clock for both streams — without this, two independently clocked
|
||||
// devices drift and the loop eventually blocks on one of them.
|
||||
if let playback: OpaquePointer = playbackPCM {
|
||||
linkedStreams = snd_pcm_link(handle, playback) >= 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies format, access mode, rate, channel count, and latency in one
|
||||
/// call. `snd_pcm_set_params` is ALSA's own convenience over the hw/sw
|
||||
/// params dance and negotiates a period for the requested latency.
|
||||
private func configure(_ pcm: OpaquePointer, channels: Int, stream: String) throws {
|
||||
let latencySeconds: Double =
|
||||
Double(blockSize * periodsPerBuffer) / sampleRate
|
||||
let latencyMicroseconds: UInt32 = UInt32(latencySeconds * Self.microsecondsPerSecond)
|
||||
let softResample: Int32 = allowSoftwareResampling ? 1 : 0
|
||||
|
||||
let paramResult: Int32 = snd_pcm_set_params(
|
||||
pcm,
|
||||
SND_PCM_FORMAT_FLOAT_LE,
|
||||
SND_PCM_ACCESS_RW_INTERLEAVED,
|
||||
UInt32(channels),
|
||||
UInt32(sampleRate),
|
||||
softResample,
|
||||
latencyMicroseconds
|
||||
)
|
||||
guard paramResult >= 0 else {
|
||||
throw ALSAError.parameterNegotiationFailed(stream: stream, code: Int(paramResult))
|
||||
}
|
||||
|
||||
let prepareResult: Int32 = snd_pcm_prepare(pcm)
|
||||
guard prepareResult >= 0 else {
|
||||
throw ALSAError.prepareFailed(stream: stream, code: Int(prepareResult))
|
||||
}
|
||||
}
|
||||
|
||||
private func closeDevices() {
|
||||
// A thread we gave up waiting for still owns these handles. Closing
|
||||
// them out from under it is the use-after-free this whole path exists
|
||||
// to avoid; they stay open until the process exits.
|
||||
guard !_abandonedThread.load(ordering: .acquiring) else { return }
|
||||
if let capture: OpaquePointer = capturePCM {
|
||||
// Unlink before closing so a restart can link a fresh pair.
|
||||
if linkedStreams { snd_pcm_unlink(capture) }
|
||||
snd_pcm_drop(capture)
|
||||
snd_pcm_close(capture)
|
||||
capturePCM = nil
|
||||
}
|
||||
if let playback: OpaquePointer = playbackPCM {
|
||||
snd_pcm_drop(playback)
|
||||
snd_pcm_close(playback)
|
||||
playbackPCM = nil
|
||||
}
|
||||
linkedStreams = false
|
||||
}
|
||||
|
||||
// MARK: - Render thread
|
||||
|
||||
/// Retains `engine` for the render thread and returns its pointer as a bit
|
||||
/// pattern — the form that survives `Thread`'s `@Sendable` closure boundary.
|
||||
/// Balanced by exactly one ``releaseEngine(bits:)``.
|
||||
///
|
||||
/// Exposed so the retain/release round trip can be pinned by a test: the
|
||||
/// balance across the render loop's exit paths only runs against real
|
||||
/// hardware, and an imbalance here is a leak or a use-after-free.
|
||||
@_spi(LyrebirdExtensions)
|
||||
public static func retainForRenderThread(_ engine: Unmanaged<SynthesisEngine>) -> UInt {
|
||||
UInt(bitPattern: engine.retain().toOpaque())
|
||||
}
|
||||
|
||||
/// Balances one ``retainForRenderThread(_:)``.
|
||||
@_spi(LyrebirdExtensions)
|
||||
public static func releaseEngine(bits: UInt) {
|
||||
guard let pointer: UnsafeMutableRawPointer = UnsafeMutableRawPointer(bitPattern: bits) else { return }
|
||||
Unmanaged<SynthesisEngine>.fromOpaque(pointer).release()
|
||||
}
|
||||
|
||||
private func renderLoop(engineBits: UInt) {
|
||||
guard let enginePointer: UnsafeMutableRawPointer = UnsafeMutableRawPointer(bitPattern: engineBits) else {
|
||||
// Unreachable: `engineBits` is the bit pattern of a live heap
|
||||
// pointer, never 0. Balance the retain anyway so the one path that
|
||||
// does not reach the `defer` below cannot leak the engine.
|
||||
Self.releaseEngine(bits: engineBits)
|
||||
_lastError.withLock { $0 = .renderLoopPreconditionFailed }
|
||||
_isRunning.store(false, ordering: .releasing)
|
||||
threadExited.signal()
|
||||
return
|
||||
}
|
||||
let retainedEngine: Unmanaged<SynthesisEngine> = Unmanaged.fromOpaque(enginePointer)
|
||||
RTThreadIdentity.markCurrentThreadAsRT()
|
||||
enableFlushToZero()
|
||||
if requestsRealtimePriority {
|
||||
_hasRealtimePriority.store(Self.raiseCurrentThreadPriority(), ordering: .releasing)
|
||||
}
|
||||
defer {
|
||||
// Clear the flag on every exit, including the error paths, so the
|
||||
// driver's state matches reality and a later `start()` is not
|
||||
// silently ignored. Signalled last: `stop()` closes the PCM handles
|
||||
// as soon as it sees this, and by then the loop must be done with
|
||||
// them.
|
||||
_isRunning.store(false, ordering: .releasing)
|
||||
// Balances the `passRetained` in `start()`. Reached on every exit
|
||||
// path this loop has; only a thread that never returns keeps the
|
||||
// engine alive, which is exactly the case that needs it.
|
||||
retainedEngine.release()
|
||||
threadExited.signal()
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = retainedEngine.takeUnretainedValue()
|
||||
guard let playback: OpaquePointer = playbackPCM,
|
||||
let output: UnsafeMutablePointer<Float> = interleavedOutput else {
|
||||
// Exiting here produces silence with no other symptom, so record why
|
||||
// rather than letting a driver that never ran look healthy.
|
||||
_lastError.withLock { $0 = .renderLoopPreconditionFailed }
|
||||
return
|
||||
}
|
||||
|
||||
// Read once, before the loop. The abandon path deliberately writes
|
||||
// nothing, but `closeDevices()` does nil these after a clean join, and
|
||||
// hoisting means the loop body does not depend on that ordering
|
||||
// holding at every iteration.
|
||||
let capture: OpaquePointer? = capturePCM
|
||||
let input: UnsafeMutablePointer<Float>? = interleavedInput
|
||||
|
||||
while _isRunning.load(ordering: .acquiring) {
|
||||
if let capture: OpaquePointer = capture,
|
||||
let input: UnsafeMutablePointer<Float> = input {
|
||||
guard transfer(pcm: capture, buffer: input, isCapture: true) else { return }
|
||||
lyrebirdDeinterleave(
|
||||
input,
|
||||
into: &inputStagingBuffers,
|
||||
frameCount: blockSize,
|
||||
channelCount: inputChannels
|
||||
)
|
||||
}
|
||||
|
||||
engine.processBlock(inputSamples: inputStagingBuffers)
|
||||
|
||||
lyrebirdInterleave(
|
||||
engine.audioBuses,
|
||||
into: output,
|
||||
frameCount: blockSize,
|
||||
channelCount: outputChannels
|
||||
)
|
||||
guard transfer(pcm: playback, buffer: output, isCapture: false) else { return }
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves exactly `blockSize` frames in or out, resuming after short
|
||||
/// transfers and recovering from underruns.
|
||||
///
|
||||
/// - Returns: `false` when the stream is unrecoverable or the driver was
|
||||
/// asked to stop, meaning the render loop should exit.
|
||||
private func transfer(
|
||||
pcm: OpaquePointer,
|
||||
buffer: UnsafeMutablePointer<Float>,
|
||||
isCapture: Bool
|
||||
) -> Bool {
|
||||
let channels: Int = isCapture ? inputChannels : outputChannels
|
||||
var framesDone: Int = 0
|
||||
var consecutiveStalls: Int = 0
|
||||
var consecutiveInterrupts: Int = 0
|
||||
|
||||
while framesDone < blockSize {
|
||||
guard _isRunning.load(ordering: .acquiring) else { return false }
|
||||
let cursor: UnsafeMutablePointer<Float> = buffer + framesDone * channels
|
||||
let remaining: UInt = UInt(blockSize - framesDone)
|
||||
let result: Int = isCapture
|
||||
? snd_pcm_readi(pcm, cursor, remaining)
|
||||
: snd_pcm_writei(pcm, cursor, remaining)
|
||||
|
||||
switch ALSARecoveryAction.classify(result) {
|
||||
case .transferred(let frames):
|
||||
framesDone += frames
|
||||
// A zero-frame transfer makes no progress, so it cannot reset
|
||||
// the budget — otherwise a device that keeps returning 0 spins
|
||||
// this loop forever at `SCHED_FIFO`, which is the failure the
|
||||
// budget exists to stop.
|
||||
if frames > 0 {
|
||||
consecutiveStalls = 0
|
||||
consecutiveInterrupts = 0
|
||||
} else if !tolerateStall(result: result, isCapture: isCapture, count: &consecutiveStalls) {
|
||||
return false
|
||||
}
|
||||
case .interrupted:
|
||||
// A signal, not a device problem: reissue without spending the
|
||||
// stall budget, since profilers and interval timers deliver
|
||||
// these to perfectly healthy streams. Still bounded, and with a
|
||||
// yield — a signal source faster than the syscall would
|
||||
// otherwise busy-spin a `SCHED_FIFO` thread with nothing but
|
||||
// `_isRunning` to break out.
|
||||
consecutiveInterrupts += 1
|
||||
guard consecutiveInterrupts <= Self.maxConsecutiveInterrupts else {
|
||||
_lastError.withLock {
|
||||
$0 = .transferFailed(
|
||||
stream: isCapture ? "capture" : "playback",
|
||||
code: result
|
||||
)
|
||||
}
|
||||
return false
|
||||
}
|
||||
sched_yield()
|
||||
continue
|
||||
case .wouldBlock:
|
||||
// A blocking PCM should not return would-block, but a plugin
|
||||
// chain (dmix, a non-blocking `.asoundrc` device) can. Spinning
|
||||
// on it from a `SCHED_FIFO` thread would starve the machine, so
|
||||
// sleep on the device and give up if it never becomes ready.
|
||||
guard tolerateStall(result: result, isCapture: isCapture, count: &consecutiveStalls) else {
|
||||
return false
|
||||
}
|
||||
_ = snd_pcm_wait(pcm, Self.deviceWaitMilliseconds)
|
||||
case .recover:
|
||||
// Underrun or suspend: re-prepare and reissue from the same
|
||||
// frame. The samples already handed over are gone either way.
|
||||
// An xrun moves no frames, so it spends the budget like any
|
||||
// other no-progress result — clearing it here let a device
|
||||
// alternating underruns with would-block returns loop forever.
|
||||
guard tolerateStall(result: result, isCapture: isCapture, count: &consecutiveStalls) else {
|
||||
return false
|
||||
}
|
||||
if snd_pcm_recover(pcm, Int32(result), Self.recoverSilently) < 0 {
|
||||
_lastError.withLock {
|
||||
$0 = .prepareFailed(
|
||||
stream: isCapture ? "capture" : "playback",
|
||||
code: result
|
||||
)
|
||||
}
|
||||
return false
|
||||
}
|
||||
case .fail:
|
||||
_lastError.withLock {
|
||||
$0 = .transferFailed(
|
||||
stream: isCapture ? "capture" : "playback",
|
||||
code: result
|
||||
)
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// Counts one transfer that moved no frames, and reports whether the
|
||||
/// stream has any patience left.
|
||||
///
|
||||
/// - Returns: `false` once the budget is spent, having recorded the error.
|
||||
private func tolerateStall(result: Int, isCapture: Bool, count: inout Int) -> Bool {
|
||||
count += 1
|
||||
guard Self.stallBudgetExhausted(consecutiveStalls: count) else { return true }
|
||||
_lastError.withLock {
|
||||
$0 = .transferFailed(
|
||||
stream: isCapture ? "capture" : "playback",
|
||||
code: result
|
||||
)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/// Whether this many consecutive no-progress transfers means the stream is
|
||||
/// dead rather than merely slow.
|
||||
///
|
||||
/// Exposed so the boundary can be pinned by a test: the loop that consults
|
||||
/// it only runs against real hardware, and an off-by-one here either kills
|
||||
/// a healthy stream one attempt early or never gives up at all.
|
||||
@_spi(LyrebirdExtensions)
|
||||
public static func stallBudgetExhausted(consecutiveStalls: Int) -> Bool {
|
||||
consecutiveStalls > maxConsecutiveStalls
|
||||
}
|
||||
|
||||
/// Asks the kernel for `SCHED_FIFO` on the calling thread.
|
||||
///
|
||||
/// - Returns: `true` if granted. Denial is the normal case for an
|
||||
/// unprivileged process and is not an error — audio still runs, just
|
||||
/// without scheduling protection.
|
||||
private static func raiseCurrentThreadPriority() -> Bool {
|
||||
let lowest: Int32 = sched_get_priority_min(SCHED_FIFO)
|
||||
let highest: Int32 = sched_get_priority_max(SCHED_FIFO)
|
||||
guard lowest >= 0, highest > lowest else { return false }
|
||||
let span: Double = Double(highest - lowest)
|
||||
var params: sched_param = sched_param()
|
||||
params.sched_priority = lowest + Int32(span * realtimePriorityFraction)
|
||||
return pthread_setschedparam(pthread_self(), SCHED_FIFO, ¶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
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
import AVFoundation
|
||||
@@ -510,3 +511,4 @@ public let auv3DriverDefaultMaxFramesToRender: Int = 1024
|
||||
/// the ring. Larger values give more slack for hosts that pull busses
|
||||
/// asynchronously at the cost of memory.
|
||||
public let auv3RingBufferHeadroomFactor: Int = 2
|
||||
#endif
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if canImport(AudioToolbox)
|
||||
import CoreAudio
|
||||
import AudioToolbox
|
||||
import Synchronization
|
||||
@@ -822,3 +823,4 @@ private func lyrebirdRenderCallback(
|
||||
)
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// DefaultAudioDriver.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Returns the live-audio driver for the platform this build targets.
|
||||
///
|
||||
/// Which drivers exist is not a property of the operating system alone — the
|
||||
/// Linux `ALSAAudioDriver` is present only when the build linked libasound
|
||||
/// (see the `LYREBIRD_DISABLE_ALSA` opt-out in `Package.swift`, and note that a
|
||||
/// Linux binary cross-compiled from macOS has no ALSA at all). Only code inside
|
||||
/// this module can see that, so any `#if` written in *consumer* code to pick a
|
||||
/// driver is guessing. Call this instead:
|
||||
///
|
||||
/// ```swift
|
||||
/// let engine = SynthesisEngine(
|
||||
/// blockSize: 512, sampleRate: 44100,
|
||||
/// numOutputChannels: 2, numInputChannels: 0,
|
||||
/// driver: makeDefaultAudioDriver()
|
||||
/// )
|
||||
/// ```
|
||||
///
|
||||
/// Resolution order: `iOSAudioDriver` on iOS, `CoreAudioDriver` on macOS,
|
||||
/// `ALSAAudioDriver` on a Linux build with ALSA, and ``OfflineDriver`` where
|
||||
/// no live backend exists. (`ALSAAudioDriver` is written in code font rather
|
||||
/// than as a symbol link because it does not exist in an Apple build, where
|
||||
/// this documentation is generated.)
|
||||
///
|
||||
/// > Important: the ``OfflineDriver`` fallback runs the graph on demand and
|
||||
/// > produces no sound. Check ``isLiveAudioAvailable`` when silence would be a
|
||||
/// > surprise — for example before printing "now playing" to a user.
|
||||
public func makeDefaultAudioDriver() -> any AudioDriver {
|
||||
#if canImport(AudioToolbox)
|
||||
#if os(iOS)
|
||||
return iOSAudioDriver()
|
||||
#else
|
||||
return CoreAudioDriver()
|
||||
#endif
|
||||
#elseif canImport(CALSA)
|
||||
return ALSAAudioDriver()
|
||||
#else
|
||||
return OfflineDriver()
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Whether this build has a live-audio backend at all.
|
||||
///
|
||||
/// `false` means ``makeDefaultAudioDriver()`` returns an ``OfflineDriver`` and
|
||||
/// nothing will reach a speaker: a Linux build without libasound, a Linux
|
||||
/// binary cross-compiled from macOS, or a platform with no driver yet.
|
||||
public var isLiveAudioAvailable: Bool {
|
||||
#if canImport(AudioToolbox) || canImport(CALSA)
|
||||
return true
|
||||
#else
|
||||
return false
|
||||
#endif
|
||||
}
|
||||