// SnippetContext.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT // LyrebirdLiveCompile // // `SnippetContext` is the public API surface the user's snippet talks to. The // host (via `LiveSession.compileAndRun`) constructs one of these, passes the // opaque pointer to the snippet's `lyrebird_snippet_entry`, and the preamble // hands the snippet a typed `context: SnippetContext` reference. // // Surface is intentionally minimal for v1 (open question 4 in the plan). Snippets // read `context.engine` for `SynthesisEngine`, call `context.play(_:)` to add a // synth that the host will track for re-evaluation cleanup, and report back via // the test-friendly `reportSampleRate(_:)` / `reportMessage(_:)` helpers. #if os(macOS) import LyrebirdSynth public final class SnippetContext { /// Owning session. `unowned` because the host guarantees the session /// outlives the snippet `entry` call (entry is invoked synchronously inside /// `LiveSession.compileAndRun` under a `withExtendedLifetime` on `self`). public unowned let session: LiveSession /// Convenience accessor — same as `session.engine`. public var engine: SynthesisEngine { session.engine } init(session: LiveSession) { self.session = session } /// Add `synth` to the engine and track it so the next non-additive /// re-evaluation (`LiveSession.compileAndRun(_:additive: false)`) removes it. /// - Returns: `true` if the engine accepted the enqueue; `false` if /// `engine.add` threw (e.g. cross-engine binding, double-add, queue full). @discardableResult @MainActor public func play(_ synth: any Synthesizer) -> Bool { do { try session.engine.add(synth) session.track(synth) return true } catch { session.appendMessage("engine.add failed: \(error)") return false } } /// Play `synth` into a **named slot**, replacing whatever synth was there /// before — the `Pdef`-style hot-swap primitive. /// /// Unlike ``play(_:)``, a slotted synth is *not* torn down by the next /// non-additive re-evaluation. Re-running a `play(slot:)` for the same name /// swaps that one voice in place (the new voice starts before the old is /// removed — a brief overlap, no gap), while other slots keep playing. /// This lets you mutate one voice at a time, live. /// /// ```swift /// context.play(slot: "bass") { OscSaw.Audio(freq: 55, mul: 0.2) } /// ``` /// /// Clear a slot with `context.session.clearSlot("bass")`, or all slots with /// `context.session.clearSlots()`. /// /// The swap is immediate by default, or quantized to the next beat/bar when /// the session has a ``LiveSession/swapClock`` and a non-`.immediate` /// ``LiveSession/swapQuantize`` — see ``LiveSession/swapSlot(_:synth:)``. /// /// - Parameters: /// - name: Slot identifier. Re-using a name replaces that slot's synth. /// - synth: The `Synthesizer` to install. /// - Returns: `true` if the engine accepted the add/schedule; `false` if it /// threw (in which case the prior slot synth is left in place). @discardableResult @MainActor public func play(slot name: String, _ synth: any Synthesizer) -> Bool { do { try session.swapSlot(name, synth: synth) return true } catch { session.appendMessage("play(slot: \"\(name)\") failed: \(error)") return false } } /// Play a bare generator graph into a **named slot** — the `Pdef`-style /// hot-swap primitive with no `SynthesizerBase` subclass to declare. /// /// See ``play(slot:_:)`` for the slot semantics. /// /// ```swift /// context.play(slot: "lead") { Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0) } /// ``` /// /// - Parameters: /// - name: Slot identifier. Re-using a name replaces that slot's synth. /// - bus: Output bus the graph is written to (multi-channel sources /// continue into following buses). Defaults to `0`. /// - make: Builds and returns the output graph. Called once, inside the /// synthesizer's `build()`. /// - Returns: `true` if the engine accepted the enqueue; `false` otherwise. @discardableResult @MainActor public func play( slot name: String, bus: any ValidBus = 0, _ make: @escaping () -> any ValidGeneratorInput ) -> Bool { play(slot: name, ClosureSynthesizer(bus: bus, make)) } /// Add a bare generator graph to the engine — the fastest path to sound in /// a snippet, with no `SynthesizerBase` subclass to declare. /// /// ```swift /// context.play { OscSin.Audio(freq: 440, mul: 0.1) } /// context.play(bus: 0) { Pan2(input: saw, pan: 0) } /// ``` /// /// Wraps `make` in a ``ClosureSynthesizer`` and forwards to ``play(_:)`` — /// the synth is tracked for cleanup on the next non-additive re-evaluation /// just like any other. Construct the generators inside the closure. /// /// - Parameters: /// - bus: Output bus the graph is written to (multi-channel sources /// continue into following buses). Defaults to `0`. /// - make: Builds and returns the output graph. Called once, inside the /// synthesizer's `build()`. /// - Returns: `true` if the engine accepted the enqueue; `false` if /// `engine.add` threw. @discardableResult @MainActor public func play( bus: any ValidBus = 0, _ make: @escaping () -> any ValidGeneratorInput ) -> Bool { play(ClosureSynthesizer(bus: bus, make)) } /// **Gracefully release** the voice in a named slot — trigger its envelope /// release phase and let it tail out and free itself — then drop the slot. /// /// The live-coding "start a voice, let go of it later" gesture: name a slot /// with ``play(slot:_:)``, then release it from a *separate* evaluation (e.g. /// select the line and hit ⌘E): /// /// ```swift /// context.play(slot: "pad") { EnvGen(gate: 1, ...) * OscSaw.Audio(freq: 110) } /// // …later, in another evaluation: /// context.release(slot: "pad") /// ``` /// /// The released voice must free itself (an `EnvGen`/gate with a free-on-done /// action) to leave the engine. For an immediate hard stop instead, use /// ``free(slot:)``. /// /// - Parameter name: Slot to release. /// - Returns: `true` if a gated voice was released; `false` if the slot was /// empty or its occupant has no gate. @discardableResult @MainActor public func release(slot name: String) -> Bool { session.releaseSlot(name) } /// **Immediately** stop and remove the voice in a named slot — a hard cut, /// no release tail. The counterpart to ``release(slot:)``. /// /// - Parameter name: Slot to free. /// - Returns: `true` if a voice was removed; `false` if the slot was empty. @discardableResult @MainActor public func free(slot name: String) -> Bool { session.clearSlot(name) } /// Snippet-side hook for test verification: report the engine's sample rate /// back through the session so tests can confirm the `context.engine` /// linkage compiled and called correctly. public func reportSampleRate(_ rate: Double) { session.reportedSampleRate = rate } /// Snippet-side hook for test verification: record an arbitrary message /// back on the session. Lets tests confirm the snippet body executed. public func reportMessage(_ message: String) { session.appendMessage(message) } } #endif