Files
Lyrebird/LiveCompile/Sources/LyrebirdLiveCompile/LiveSession.swift
T
josh b6fdee8bfc Lyrebird 2.0.0 — Linux support
Consolidated release: the cross-platform Linux port (engine, generators, CLI,
REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable
WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux
live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive.
See RELEASES.md and LINUX_README.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-10 21:09:11 -07:00

904 lines
42 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// LiveSession.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile
//
// `LiveSession` owns the `SynthesisEngine` and tracks every `Synthesizer` that
// each snippet `play(_:)`s, so the next non-additive re-evaluation can
// `engine.remove(_:)` them before running fresh user code. Also caches every
// `CompiledSnippet` so the dylibs stay mapped — see the leak-by-design note in
// `CompiledSnippet.swift`.
#if os(macOS) || os(Linux)
import Foundation
import LyrebirdSynth
/// Host-side owner of one live-coding session.
///
/// Holds the `SynthesisEngine` that snippets target, the swiftc flags used to
/// compile snippets, and the tracking lists needed for re-evaluation cleanup.
/// Snippets receive a `SnippetContext` bound to this session through
/// `compileAndRun(_:additive:)`.
///
/// `@unchecked Sendable`: a `LiveSession` is shared between its `@MainActor`
/// owner (`LyrebirdScratchModel`) and the `nonisolated` `compileAndRunAsync` it calls, so
/// Swift 6 requires it to be `Sendable`. The conformance is sound by construction:
///
/// - `engine` and all `-I` / `-L` / `-l` / `rpath` configuration are immutable `let`.
/// - The mutable graph state — `trackedSynths`, `loadedSnippets`, and the named-slot map
/// `slottedSynths` — is accessed exclusively under `trackingLock` (`track`,
/// `clearTracked`, `trackedSynthCount`, `runEntry`, `assignSlot`, `clearSlot`,
/// `clearSlots`, `slotCount`, `slotNames`).
/// - `reportedSampleRate` / `lastSnippetMessage` are test-only side channels (`@testable`),
/// written by the single in-flight snippet entry under the documented
/// one-invocation-at-a-time precondition (see `compileAndRunAsync`) and read by tests
/// after it completes — no concurrent access in practice.
public final class LiveSession: @unchecked Sendable {
public let engine: SynthesisEngine
/// Output-tapping oscilloscope capture for the editor's scope view. When a
/// fresh tap is installed at init (the engine is not yet running and has no
/// tap), this is that capture; if the engine already had a `scopeTap`, this
/// reuses it; it is `nil` only when no tap is present (attachment declined,
/// or the engine was already running with no tap). Must be installed before
/// `start()`.
public let scope: ScopeCapture?
/// `-I` paths threaded to `swiftc` for module discovery.
public let importPaths: [URL]
/// `-L` paths threaded to `swiftc` for library search.
public let librarySearchPaths: [URL]
/// Bare library names threaded to `swiftc` as `-l<name>`.
public let libraries: [String]
/// `-Xlinker -rpath -Xlinker <path>` entries baked into the snippet dylib
/// so `dlopen` resolves dependent dylibs (`libLyrebirdDynamic.dylib` etc.) at
/// runtime without `DYLD_LIBRARY_PATH` ceremony.
public let rpaths: [URL]
// Prewarm lifecycle — guarded by `trackingLock`. `_prewarmed` flips true
// when a prewarm completes; `_prewarming` guards a call in flight so
// repeat calls (e.g. a view re-appearing) don't spawn a second swiftc.
private var _prewarmed: Bool = false
private var _prewarming: Bool = false
/// Side-channel for snippet `context.reportSampleRate(_:)` calls. Tests read
/// via `@testable import`; not part of the public API.
internal var reportedSampleRate: Double?
/// Most recent snippet `context.reportMessage(_:)` value (tests read this via
/// `@testable import`). Backed by the internal message log (`_messageLog`).
internal var lastSnippetMessage: String? { _messageLog.last }
/// Accumulated `context.reportMessage(_:)` output (and host-side notices like
/// a dropped slot swap) since the last drain. Main-thread only — appended
/// during the synchronous snippet entry, drained by the host after each run.
private var _messageLog: [String] = []
/// Append a snippet/host message to the log. Main-thread only.
internal func appendMessage(_ message: String) {
_messageLog.append(message)
}
/// Return and clear the accumulated messages. Called by the host after a run
/// to move them into its console.
public func drainMessages() -> [String] {
let out: [String] = _messageLog
_messageLog.removeAll()
return out
}
// Tracked state — all access guarded by `trackingLock`.
private let trackingLock: NSLock = NSLock()
private var trackedSynths: [any Synthesizer] = []
private var loadedSnippets: [CompiledSnippet] = []
// A named-slot occupant plus the sample time its add was scheduled at.
// The add time lets a later teardown schedule the occupant's removal no
// earlier than its own add, so a still-pending *scheduled* voice (quantized
// swap not yet fired) is never orphaned by an immediate clear or an earlier
// re-swap. See `removeSlotOccupant`.
private struct SlotEntry {
let synth: any Synthesizer
let addTime: SampleTime
}
// Named slots — `Pdef`-style persistent voices, keyed by name. Kept
// separate from the anonymous `trackedSynths` so they SURVIVE a
// non-additive re-evaluation: re-running a `context.play(slot: "bass") { … }`
// definition replaces just that voice in place (via `assignSlot`) instead of
// being cleared with the anonymous synths. Guarded by `trackingLock`.
private var slottedSynths: [String: SlotEntry] = [:]
// Swap-quantization config + pending-swap signal — all guarded by
// `trackingLock`. When `_swapClock` is set and `_swapQuantize` is not
// `.immediate`, a slot swap schedules the new voice's add and the old
// voice's removal at the next musical boundary instead of taking effect at
// once (latency masking). `_pendingSwapBeat` is the latest target beat of a
// not-yet-fired scheduled swap, surfaced via ``pendingSwapBeat``.
private var _swapClock: LyrebirdClock?
private var _swapQuantize: SwapQuantize = .immediate
private var _pendingSwapBeat: Double?
/// Samples per channel the scope captures per display frame.
private static let scopeBufferSize: Int = 1024
/// - Parameter attachScope: When `true` (default) and the engine is not yet
/// running and has no existing tap, install a ``ScopeCapture`` on the first
/// one or two output buses for the editor's scope view.
public init(
engine: SynthesisEngine,
attachScope: Bool = true,
importPaths: [URL] = LiveSession.defaultImportPaths(),
librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(),
libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
rpaths: [URL] = LiveSession.defaultRpaths()
) {
self.engine = engine
// Install the scope tap before the host calls `start()` (the RT thread
// caches `scopeTap` at start; setting it afterwards is a no-op).
if attachScope, !engine.isRunning, engine.scopeTap == nil, engine.numOutputChannels >= 1 {
let buses: [Int] = Array(0..<min(2, engine.numOutputChannels))
let capture: ScopeCapture = ScopeCapture(buses: buses, bufferSize: LiveSession.scopeBufferSize)
engine.scopeTap = capture
self.scope = capture
} else {
self.scope = engine.scopeTap
}
self.importPaths = importPaths
self.librarySearchPaths = librarySearchPaths
self.libraries = libraries
self.rpaths = rpaths
}
/// Wrap `userBody` in the standard harness, compile, and call the snippet's
/// `lyrebird_snippet_entry` with a `SnippetContext` bound to this session.
///
/// - Parameters:
/// - userBody: Swift code that runs inside the snippet entry. Has access
/// to a local `context: SnippetContext`.
/// - additive: When `false` (default), removes every previously tracked
/// synth before running. When `true`, leaves prior synths in place
/// (⌘⇧↩ semantics in the future `LyrebirdScratchView` editor).
/// - Returns: The compiled snippet handle. Retained internally so the dylib
/// stays mapped; callers can ignore it.
/// `@MainActor`: runs the snippet entry — and thus the user body's
/// `MainActor.assumeIsolated { … }` and any `context.play(_:)` → `engine.add` — on the
/// main thread, synchronously (swiftc compile included). The async variant
/// ``compileAndRunAsync(_:additive:)`` keeps the compile off-main.
@discardableResult
@MainActor
public func compileAndRun(_ userBody: String, additive: Bool = false) throws -> CompiledSnippet {
if !additive {
clearTracked()
}
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: userBody)
let snippet: CompiledSnippet = try compileWrapped(wrapped)
runEntry(of: snippet)
return snippet
}
/// Asynchronous variant of ``compileAndRun(_:additive:)``. The swiftc compile runs on a
/// background `Task.detached` so `LyrebirdScratchView`'s editor stays responsive; the
/// engine-touching steps (`clearTracked()` and the snippet entry via `runEntry`) then run
/// on the **main actor**.
///
/// Running the entry on the main actor matters: the snippet's
/// `context.play(_:)` calls `engine.add(_:)`, which is `@MainActor` and
/// mutates `engine.nodeTreeMirror` — state observed by SwiftUI on the main thread. A
/// `nonisolated async` method resumes on the generic executor, NOT the caller's actor, so
/// the hop is explicit here rather than assumed.
///
/// - Precondition: only one in-flight invocation at a time per `LiveSession`.
/// Concurrent calls can interleave `clearTracked()` with the prior call's
/// not-yet-completed `runEntry`, silently dropping tracked synths. The
/// built-in caller `LyrebirdScratchModel` serialises through its
/// `isCompiling` flag; out-of-tree callers must enforce the same.
///
/// - Parameters:
/// - userBody: Same as the synchronous variant.
/// - additive: Same as the synchronous variant.
/// - Returns: The compiled snippet handle. Retained internally.
@discardableResult
public func compileAndRunAsync(_ userBody: String, additive: Bool = false) async throws -> CompiledSnippet {
if !additive {
// `clearTracked()` calls `engine.remove` (touches `nodeTreeMirror`) — main only.
await MainActor.run { clearTracked() }
}
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: userBody)
let args: [String] = makeSwiftcArgs()
let snippet: CompiledSnippet = try await Task.detached(priority: .userInitiated) {
try LiveSession.compileBlocking(wrapped: wrapped, extraArgs: args)
}.value
// Snippet entry runs the user's `context.play(_:)` → `engine.add` (@MainActor).
await MainActor.run { runEntry(of: snippet) }
return snippet
}
// Synchronous compile body used by both `compileAndRun` and the detached
// background `Task` inside `compileAndRunAsync`. Wraps the
// `LiveCompileError` → `LiveSessionError` translation in one place.
private static func compileBlocking(wrapped: WrappedSnippet, extraArgs: [String]) throws -> CompiledSnippet {
do {
return try LiveCompiler.compile(
source: wrapped.source,
extraSwiftcArgs: extraArgs
)
} catch let error as LiveCompileError {
if case .compileFailed(_, let stderr) = error {
let diagnostics: [Diagnostic] = DiagnosticParser.parse(
stderr: stderr,
userBodyLineOffset: wrapped.userBodyLineOffset
)
throw LiveSessionError.snippetCompileFailed(
diagnostics: diagnostics,
underlying: error
)
}
throw LiveSessionError.compilerError(error)
}
}
private func compileWrapped(_ wrapped: WrappedSnippet) throws -> CompiledSnippet {
try LiveSession.compileBlocking(wrapped: wrapped, extraArgs: makeSwiftcArgs())
}
private func runEntry(of snippet: CompiledSnippet) {
let context: SnippetContext = SnippetContext(session: self)
withExtendedLifetime(context) {
let opaque: UnsafeMutableRawPointer = Unmanaged.passUnretained(context).toOpaque()
snippet.entry(opaque)
}
trackingLock.lock(); defer { trackingLock.unlock() }
loadedSnippets.append(snippet)
}
/// Currently tracked synth count. Thread-safe.
public var trackedSynthCount: Int {
trackingLock.lock(); defer { trackingLock.unlock() }
return trackedSynths.count
}
/// Remove every tracked synth from the engine and clear the tracking list.
/// Called automatically by `compileAndRun(_:additive: false)`.
public func clearTracked() {
let snapshot: [any Synthesizer]
do {
trackingLock.lock(); defer { trackingLock.unlock() }
snapshot = trackedSynths
trackedSynths.removeAll()
}
for synth: any Synthesizer in snapshot {
_ = engine.remove(synth)
}
}
/// Internal hook for `SnippetContext.play(_:)`. Thread-safe.
func track(_ synth: any Synthesizer) {
trackingLock.lock(); defer { trackingLock.unlock() }
trackedSynths.append(synth)
}
// MARK: - Named slots
/// Number of named slots currently holding a synth. Thread-safe.
public var slotCount: Int {
trackingLock.lock(); defer { trackingLock.unlock() }
return slottedSynths.count
}
/// Names of the currently-populated slots. Thread-safe.
public var slotNames: [String] {
trackingLock.lock(); defer { trackingLock.unlock() }
return Array(slottedSynths.keys)
}
/// Install `synth` into the named `slot` immediately, replacing any synth
/// previously held there.
///
/// Internal hook for the immediate path of ``swapSlot(_:synth:)``. **Call
/// after `engine.add(synth)` has succeeded** — the new voice is live before
/// the old one is torn down, so a slot replacement is a brief overlap rather
/// than a silent gap. The previous occupant is removed via
/// ``removeSlotOccupant(_:desired:)`` (scheduled no earlier than its own
/// add, so a still-pending scheduled voice is never orphaned). Thread-safe;
/// `engine.remove` runs outside the lock.
func assignSlot(_ name: String, synth: any Synthesizer) {
let now: SampleTime = engine.currentTime
let previous: SlotEntry?
do {
trackingLock.lock(); defer { trackingLock.unlock() }
previous = slottedSynths[name]
slottedSynths[name] = SlotEntry(synth: synth, addTime: now)
}
if let previous: SlotEntry = previous {
removeSlotOccupant(previous, desired: now)
}
}
/// Remove every named-slot synth from the engine and clear all slots.
/// Anonymous tracked synths are untouched — pair with ``clearTracked()``
/// for a full reset.
public func clearSlots() {
let now: SampleTime = engine.currentTime
let snapshot: [SlotEntry]
do {
trackingLock.lock(); defer { trackingLock.unlock() }
snapshot = Array(slottedSynths.values)
slottedSynths.removeAll()
}
for entry: SlotEntry in snapshot {
removeSlotOccupant(entry, desired: now)
}
}
/// Remove the synth in the named `slot` (if any) from the engine and clear
/// the slot. No-op when the slot is empty. Returns `true` if a synth was
/// removed.
@discardableResult
public func clearSlot(_ name: String) -> Bool {
let now: SampleTime = engine.currentTime
let previous: SlotEntry?
do {
trackingLock.lock(); defer { trackingLock.unlock() }
previous = slottedSynths.removeValue(forKey: name)
}
if let previous: SlotEntry = previous {
removeSlotOccupant(previous, desired: now)
return true
}
return false
}
/// **Gracefully release** the synth in the named `slot` (trigger its
/// envelope release phase) and drop the slot handle, so the voice tails out
/// and then frees itself via its own done-action — rather than being hard-cut
/// like ``clearSlot(_:)``. This is the live-coding "let go of this voice"
/// gesture: pair it with ``SnippetContext/play(slot:_:)-…`` to start a
/// persistent voice under a name and release it later from a separate
/// evaluation.
///
/// The handle is dropped **only if the release succeeds**, so a voice with no
/// gate to release (its `release(engine:)` throws) stays in the slot and can
/// still be stopped with ``clearSlot(_:)`` — it is never orphaned.
///
/// On success the voice is moved from the slot map into the anonymous
/// tracked list, so it remains reachable by ``clearTracked()`` / ``resetAll()``
/// (the toolbar "Clear Synths"). A well-behaved voice self-frees via its
/// done-action before then; a mis-configured one that never self-frees is
/// still reclaimable rather than leaked until a process restart. (A later
/// hard `engine.remove` on an already-self-freed synth is a harmless no-op.)
///
/// - Parameter name: Slot to release.
/// - Returns: `true` if a gated voice was released; `false` if the slot was
/// empty or its occupant had no gate (reported via `lastSnippetMessage`).
///
/// The identity guard below (`… === entry.synth`) is load-bearing, not
/// defensive dead code: `clearSlot` / `clearSlots` / `resetAll` are
/// nonisolated and may run on another thread while this `release(engine:)`
/// call is in flight on the main actor.
@MainActor
@discardableResult
public func releaseSlot(_ name: String) -> Bool {
let entry: SlotEntry?
do {
trackingLock.lock(); defer { trackingLock.unlock() }
entry = slottedSynths[name]
}
guard let entry: SlotEntry = entry else { return false }
do {
try entry.synth.release(engine: engine)
// Released — free the name for reuse and keep the voice reachable by
// the tracked-synth sweep (its safety net until it self-frees).
trackingLock.lock(); defer { trackingLock.unlock() }
if slottedSynths[name]?.synth === entry.synth {
slottedSynths[name] = nil
trackedSynths.append(entry.synth)
}
return true
} catch {
appendMessage(
"slot '\(name)': release failed (\(error)) — use clearSlot() to stop it")
return false
}
}
/// Remove a slot occupant, scheduling the removal no earlier than the
/// occupant's own add time (`max(desired, addTime)`) so a still-pending
/// scheduled add is never orphaned. `desired` is the caller's intended
/// removal time — a swap boundary, or the current time for an immediate
/// teardown. Because the occupant's add is always enqueued before this
/// removal and the engine's per-block event sort is stable at equal times,
/// an add and removal landing on the same sample apply add-then-removal, so
/// the voice is always cleaned up. Runs outside `trackingLock`.
@discardableResult
private func removeSlotOccupant(_ entry: SlotEntry, desired: SampleTime) -> Bool {
let removeAt: SampleTime = max(desired, entry.addTime)
return engine.remove(entry.synth, at: removeAt)
}
// MARK: - Session reset + snippet accounting
/// Panic / clear-everything valve: remove every snippet-played synth — both
/// the anonymous tracked ones (``clearTracked()``) and every named slot
/// (``clearSlots()``) — from the engine, and clear the pending-swap signal.
/// Stops all snippet audio and gives a clean slate without tearing down the
/// engine.
///
/// It does **not** reclaim the compiled snippet dylibs — see
/// ``loadedSnippetCount``. Reclaiming that memory would require `dlclose`,
/// which is unsafe for these Swift dylibs: `dlopen` registers their type
/// metadata and protocol-conformance records into process-global runtime
/// caches that `dlclose` does not deregister, so unmapping the dylib leaves
/// those caches dangling. Mapped snippet memory is therefore reclaimed only
/// by restarting the process. (The interpreted-graph path on the roadmap
/// avoids dylibs entirely and is the structural fix.)
///
/// - Precondition: same one-invocation-at-a-time caveat as
/// ``compileAndRunAsync(_:additive:)``. Calling this concurrently with an
/// in-flight compile can interleave the internal `clearTracked()` with a
/// not-yet-completed `runEntry`, missing a just-added synth (which then
/// leaks until process restart). The built-in ``LyrebirdScratchModel``
/// serialises through its `isCompiling` flag. This is also not a single
/// atomic critical section — the synth removal and the pending-swap clear
/// take `trackingLock` separately — which is acceptable for a panic valve.
public func resetAll() {
clearTracked()
clearSlots()
trackingLock.lock(); defer { trackingLock.unlock() }
_pendingSwapBeat = nil
}
/// Number of compiled snippet dylibs currently mapped into the process.
///
/// Each ⌘↩ compiles a new dylib that stays mapped for the process's lifetime
/// (unloading is unsafe — see ``resetAll()``), so within a session this only
/// grows. Exposed for host observability, e.g. a "restart to reclaim memory"
/// nudge after a very long session. Thread-safe.
public var loadedSnippetCount: Int {
trackingLock.lock(); defer { trackingLock.unlock() }
return loadedSnippets.count
}
// MARK: - Swap quantization (on-beat latency masking)
/// Clock that slot swaps quantize against. When `nil` (default), swaps are
/// always immediate regardless of ``swapQuantize``. Setting it clears any
/// pending-swap signal (``pendingSwapBeat``). Thread-safe.
public var swapClock: LyrebirdClock? {
get { trackingLock.lock(); defer { trackingLock.unlock() }; return _swapClock }
set {
trackingLock.lock(); defer { trackingLock.unlock() }
_swapClock = newValue
_pendingSwapBeat = nil
}
}
/// When a named-slot swap becomes audible. Defaults to ``SwapQuantize/immediate``.
/// Only takes effect when ``swapClock`` is also set. Setting it clears any
/// pending-swap signal (``pendingSwapBeat``). Thread-safe.
public var swapQuantize: SwapQuantize {
get { trackingLock.lock(); defer { trackingLock.unlock() }; return _swapQuantize }
set {
trackingLock.lock(); defer { trackingLock.unlock() }
_swapQuantize = newValue
_pendingSwapBeat = nil
}
}
/// Target beat of the latest scheduled-but-not-yet-fired slot swap, or `nil`
/// when none is pending (immediate mode, the boundary has already passed, or
/// the swap config changed). Self-clearing: returns `nil` once the clock
/// reaches the target beat. Drives the editor's `.queued` readiness state.
///
/// When several slots have swaps pending at different beats this reports the
/// latest of them — treat it as "some swap is still outstanding", not "this
/// specific run's swap". Thread-safe, but not atomic against a concurrent
/// swap: the `_swapClock` snapshot and the `clock.currentBeat` read happen in
/// separate critical sections, so a swap scheduled between them may not yet
/// be reflected. Fine for the main-actor UI that consumes it.
public var pendingSwapBeat: Double? {
let target: Double?
let clock: LyrebirdClock?
do {
trackingLock.lock(); defer { trackingLock.unlock() }
target = _pendingSwapBeat
clock = _swapClock
}
guard let target: Double = target, let clock: LyrebirdClock = clock else { return nil }
return clock.currentBeat < target ? target : nil
}
/// Install `synth` into the named `slot`, quantizing the swap per
/// ``swapQuantize`` / ``swapClock``.
///
/// Immediate mode (`.immediate` or no clock): adds `synth` now and removes
/// the previous slot synth now (via ``assignSlot(_:synth:)``). Quantized
/// mode: schedules `synth`'s add and the previous synth's removal at the same
/// upcoming boundary sample time, so the swap is glitch-free and on-grid,
/// and records the target beat for ``pendingSwapBeat``.
///
/// Backs ``SnippetContext/play(slot:_:)``. `@MainActor` because it touches
/// the engine's node tree (`add`/`schedule`/`remove`).
///
/// - Throws: `EngineAddError` if the engine rejects the add/schedule; the
/// prior slot synth is left in place on throw.
@MainActor
func swapSlot(_ name: String, synth: any Synthesizer) throws {
let clock: LyrebirdClock?
let quantize: SwapQuantize
do {
trackingLock.lock(); defer { trackingLock.unlock() }
clock = _swapClock
quantize = _swapQuantize
}
if let clock: LyrebirdClock = clock, let beat: Double = quantize.targetBeat(clock: clock) {
let time: SampleTime = clock.sampleTime(beat: beat)
try engine.schedule(synth, at: time)
scheduleSlotReplace(name, newSynth: synth, at: time, targetBeat: beat)
} else {
try engine.add(synth)
assignSlot(name, synth: synth)
}
}
/// Commit a scheduled slot replacement: swap the dictionary entry, schedule
/// removal of the previous synth at the boundary `time` (no earlier than its
/// own add), and record the pending target beat. Call only after
/// `engine.schedule(new, at: time)` succeeded. `engine.remove` runs outside
/// the lock; a dropped removal (pending queue full) is surfaced via
/// `lastSnippetMessage` rather than silently leaving an overlap.
private func scheduleSlotReplace(
_ name: String,
newSynth: any Synthesizer,
at time: SampleTime,
targetBeat: Double
) {
let previous: SlotEntry?
do {
trackingLock.lock(); defer { trackingLock.unlock() }
previous = slottedSynths[name]
slottedSynths[name] = SlotEntry(synth: newSynth, addTime: time)
_pendingSwapBeat = max(_pendingSwapBeat ?? targetBeat, targetBeat)
}
if let previous: SlotEntry = previous {
let removed: Bool = removeSlotOccupant(previous, desired: time)
if !removed {
appendMessage(
"slot '\(name)': previous voice removal dropped (pending queue full) — voices may overlap")
}
}
}
// MARK: - Prewarm
/// `true` once a ``prewarm()`` has **succeeded** for this session. A prewarm
/// that failed (e.g. missing toolchain) leaves this `false` so a later call
/// retries. Thread-safe.
public var isPrewarmed: Bool {
trackingLock.lock(); defer { trackingLock.unlock() }
return _prewarmed
}
/// Warm the module cache in the background so the first real ⌘↩ is fast.
///
/// The cold `LyrebirdSynth` `.pcm` build costs ~2–3 s; without a prewarm it
/// lands on the user's first compile. This kicks a detached, `.utility`
/// type-check of a trivial import-only snippet (via
/// ``LiveCompiler/prewarm(extraSwiftcArgs:)``) that warms swiftc's default
/// module cache, so the first `compileAndRunAsync` hits a warm cache
/// (~0.1 s). All the work — including the filesystem walk that builds the
/// compiler flags — runs on the detached task, not the caller's thread.
///
/// Idempotent: a call while a prewarm has already succeeded or is in flight
/// is a no-op. A *failed* prewarm leaves ``isPrewarmed`` `false` (a later
/// call retries); the real compile then simply pays the build itself, so the
/// failure is non-fatal and intentionally not thrown.
///
/// - Returns: The detached `Task`, so callers/tests can `await` its `value`.
/// The no-op case returns an already-scheduled empty task.
@discardableResult
public func prewarm() -> Task<Void, Never> {
let shouldRun: Bool
do {
trackingLock.lock(); defer { trackingLock.unlock() }
shouldRun = !_prewarmed && !_prewarming
if shouldRun { _prewarming = true }
}
guard shouldRun else { return Task {} }
return Task.detached(priority: .utility) { [weak self] in
guard let self: LiveSession = self else { return }
// Off-main: build the flags (a small filesystem walk) here rather
// than on the caller (this method is a synchronous `nonisolated`
// call, so anything before the detached task runs on the caller).
let args: [String] = self.makeModuleResolutionArgs()
do {
try LiveCompiler.prewarm(extraSwiftcArgs: args)
self.finishPrewarm(succeeded: true)
} catch {
self.finishPrewarm(succeeded: false)
}
}
}
/// Record a ``prewarm()`` outcome: clear the in-flight flag, and mark warmed
/// only on success so a failed attempt can retry.
private func finishPrewarm(succeeded: Bool) {
trackingLock.lock(); defer { trackingLock.unlock() }
_prewarming = false
if succeeded { _prewarmed = true }
}
// MARK: - swiftc flag construction
/// Module-resolution flags shared by the real compile and the prewarm:
/// `-I` import paths plus the Xcode + bare-SPM Clang module maps. No linker
/// flags — a `-typecheck` prewarm needs none. Deliberately does **not** pin
/// `-module-cache-path`: prewarm and the real compile both use swiftc's
/// default cache, so the prewarm warms exactly the cache the compile reads.
/// (Pinning a dedicated cache built fresh diverges its module metadata from
/// the already-loaded `libLyrebirdLiveCompileDynamic`, which turns the test
/// bundle's benign ObjC class-duplication warning into a hard cast crash.)
private func makeModuleResolutionArgs() -> [String] {
var args: [String] = []
for path: URL in importPaths {
args += ["-I", path.path]
}
// Clang module maps (e.g. `LyrebirdC.modulemap`) generated by Xcode for
// SPM C targets — surface each as `-Xcc -fmodule-map-file=<path>` so
// swiftc's embedded clang can resolve the underlying C module declared
// in a Swift module's dependency record.
for url: URL in LiveSession.discoverClangModuleMaps(in: importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
}
// Bare-SPM (`swift build` / `swift test`) layout: C-target module maps
// live at `<buildDir>/<CTarget>.build/module.modulemap`, which the Xcode
// discovery above does not cover. Surface them so a snippet's
// `import LyrebirdSynth` can resolve the underlying `LyrebirdC` clang
// module outside Xcode too.
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
}
private func makeSwiftcArgs() -> [String] {
var args: [String] = makeModuleResolutionArgs()
// When a Lyrebird dylib exists in any -L path, link against it
// (-l<name>) and bake an rpath. When no dylib is found (Xcode SPM
// case — modules statically linked into the host app), use
// `-undefined dynamic_lookup` so the snippet's dylib defers symbol
// resolution to runtime, where dyld finds Lyrebird's symbols in the
// already-loaded host process.
let hasDylib: Bool = librarySearchPaths.contains { url in
LiveSession.hasLyrebirdDylib(in: url)
}
if hasDylib {
for path: URL in librarySearchPaths {
args += ["-L", path.path]
}
for lib: String in libraries {
args += ["-l\(lib)"]
}
for path: URL in rpaths {
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
}
/// Walk up from each import path looking for Xcode's
/// `Build/Intermediates.noindex/GeneratedModuleMaps/` directory and return
/// every `*.modulemap` it contains. Empty on `swift build` SPM layouts
/// (where C modules use the package's own `include/module.modulemap`).
static func discoverClangModuleMaps(in importPaths: [URL]) -> [URL] {
let maxWalk: Int = 6
var found: [URL] = []
var visited: Set<String> = Set<String>()
for start: URL in importPaths {
var cur: URL = start
for _ in 0..<maxWalk {
let probe: URL = cur
.appendingPathComponent("Build")
.appendingPathComponent("Intermediates.noindex")
.appendingPathComponent("GeneratedModuleMaps")
if FileManager.default.fileExists(atPath: probe.path),
!visited.contains(probe.path) {
visited.insert(probe.path)
if let entries: [URL] = try? FileManager.default.contentsOfDirectory(at: probe, includingPropertiesForKeys: nil) {
for entry: URL in entries where entry.pathExtension == "modulemap" {
found.append(entry)
}
}
}
let parent: URL = cur.deletingLastPathComponent()
if parent == cur { break }
cur = parent
}
}
return found
}
/// Locate SPM-generated Clang module maps for a `swift build` / `swift test`
/// layout. Each C target's map is emitted at
/// `<buildDir>/<CTarget>.build/module.modulemap`; the umbrella header path
/// inside is absolute, so the map alone is enough to resolve the module (no
/// extra `-I` needed). Empty under an Xcode SPM layout, where
/// `discoverClangModuleMaps` handles the `GeneratedModuleMaps` location
/// instead.
static func discoverSPMModuleMaps(in importPaths: [URL]) -> [URL] {
var found: [URL] = []
var visited: Set<String> = Set<String>()
for base: URL in importPaths {
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
at: base,
includingPropertiesForKeys: nil
) else { continue }
for entry: URL in entries where entry.pathExtension == "build" {
let probe: URL = entry.appendingPathComponent("module.modulemap")
if FileManager.default.fileExists(atPath: probe.path),
!visited.contains(probe.path) {
visited.insert(probe.path)
found.append(probe)
}
}
}
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
/// that contains `libLyrebirdDynamic.dylib` and the swiftmodule directories. Used
/// as the default for `importPaths`/`librarySearchPaths`/`rpaths`. Hosts can
/// override by passing explicit URLs.
///
/// Searches, in order:
/// 1. Walks up from `Bundle(for: LiveSession.self).bundleURL` — this resolves
/// to the directory holding `libLyrebirdLiveCompileDynamic.dylib` at runtime,
/// which is the SPM debug/release dir.
/// 2. Walks up from `Bundle.main.executableURL` — fallback for the case
/// where the host bundles the dylibs into an `.app`.
public static func currentBuildDir() -> URL? {
let maxWalk: Int = 6
let candidates: [URL] = [
Bundle(for: LiveSession.self).bundleURL,
Bundle.main.executableURL ?? Bundle.main.bundleURL,
]
// Accept either an SPM-produced .dylib (swift build) or just the
// LyrebirdSynth.swiftmodule (Xcode SPM static-linked into the host app).
// The swiftmodule alone is enough for `-I` module resolution; linking
// falls back to `-undefined dynamic_lookup` when no dylib is found.
// Note: LiveCompile depends on the internal `LyrebirdDynamic` product
// (→ 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.\(livecompileSharedLibraryExtension)",
"LyrebirdSynth.swiftmodule",
]
for start: URL in candidates {
var cur: URL = start
for _ in 0..<maxWalk {
for marker: String in markers {
let probe: URL = cur.appendingPathComponent(marker)
if FileManager.default.fileExists(atPath: probe.path) {
return cur
}
}
let parent: URL = cur.deletingLastPathComponent()
if parent == cur { break }
cur = parent
}
}
return nil
}
/// `true` when a `libLyrebirdDynamic.dylib` actually exists in `buildDir`.
/// Used to decide whether to link against the dylib at compile time or fall
/// back to `-undefined dynamic_lookup` so the snippet binds to symbols
/// already resolved in the running process.
public static func hasLyrebirdDylib(in buildDir: URL) -> Bool {
FileManager.default.fileExists(
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 dir: URL = resolvedArtifactsDir() else { return [] }
return [dir, dir.appendingPathComponent("Modules")]
}
public static func defaultLibrarySearchPaths() -> [URL] {
guard let dir: URL = resolvedArtifactsDir() else { return [] }
return [dir]
}
public static func defaultRpaths() -> [URL] {
guard let dir: URL = resolvedArtifactsDir() else { return [] }
return [dir]
}
}
#endif