Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8519cabe42 | |||
| abc64df4d7 |
@@ -48,13 +48,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
menuController.installMainMenu()
|
||||
self.menuController = menuController
|
||||
|
||||
let windowWidth: CGFloat = 720
|
||||
let windowHeight: CGFloat = 560
|
||||
let hosting: NSHostingController<LyrebirdScratchView> =
|
||||
NSHostingController(rootView: LyrebirdScratchView(model: model))
|
||||
let initialSize: CGSize = CGSize(width: windowWidth, height: windowHeight)
|
||||
let win: NSWindow = NSWindow(
|
||||
contentRect: NSRect(origin: .zero, size: initialSize),
|
||||
contentRect: NSRect(origin: .zero, size: CGSize(width: 720, height: 560)),
|
||||
styleMask: [.titled, .closable, .resizable, .miniaturizable],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
@@ -63,7 +60,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
win.isReleasedWhenClosed = false
|
||||
win.title = "Lyrebird — Live Scratch"
|
||||
win.contentViewController = hosting
|
||||
win.center()
|
||||
// Base geometry: three-quarters of the screen wide, three-quarters tall,
|
||||
// anchored to the left edge and vertically centered in the visible area
|
||||
// (below the menu bar, above the Dock).
|
||||
let visible: NSRect = (win.screen ?? NSScreen.main)?.visibleFrame
|
||||
?? NSRect(x: 0, y: 0, width: 1440, height: 900)
|
||||
let width: CGFloat = visible.width * 0.75
|
||||
let height: CGFloat = visible.height * 0.75
|
||||
let originX: CGFloat = visible.minX
|
||||
let originY: CGFloat = visible.minY + (visible.height - height) / 2
|
||||
win.setFrame(NSRect(x: originX, y: originY, width: width, height: height), display: true)
|
||||
win.makeKeyAndOrderFront(nil)
|
||||
self.window = win
|
||||
}
|
||||
|
||||
@@ -202,6 +202,7 @@ final class MySynth: SynthesizerBase {
|
||||
|
||||
| Topic | Doc |
|
||||
|-------|-----|
|
||||
| New to Swift? Intro for Lyrebird users | `docs/learning-swift/README.md` |
|
||||
| Engine setup and Core Audio | `docs/engine/synthesis-engine.md` |
|
||||
| Bus system, In/Out generators | `docs/engine/bus-system.md` |
|
||||
| Sample-accurate scheduling | `docs/engine/scheduling.md` |
|
||||
|
||||
@@ -40,6 +40,14 @@ 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]
|
||||
|
||||
@@ -64,9 +72,27 @@ public final class LiveSession: @unchecked Sendable {
|
||||
/// via `@testable import`; not part of the public API.
|
||||
internal var reportedSampleRate: Double?
|
||||
|
||||
/// Side-channel for snippet `context.reportMessage(_:)` calls. Tests read
|
||||
/// via `@testable import`; not part of the public API.
|
||||
internal var lastSnippetMessage: String?
|
||||
/// 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()
|
||||
@@ -100,14 +126,31 @@ public final class LiveSession: @unchecked Sendable {
|
||||
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
|
||||
@@ -313,6 +356,59 @@ public final class LiveSession: @unchecked Sendable {
|
||||
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
|
||||
@@ -474,8 +570,8 @@ public final class LiveSession: @unchecked Sendable {
|
||||
if let previous: SlotEntry = previous {
|
||||
let removed: Bool = removeSlotOccupant(previous, desired: time)
|
||||
if !removed {
|
||||
lastSnippetMessage =
|
||||
"slot '\(name)': previous voice removal dropped (pending queue full) — voices may overlap"
|
||||
appendMessage(
|
||||
"slot '\(name)': previous voice removal dropped (pending queue full) — voices may overlap")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ public final class SnippetContext {
|
||||
session.track(synth)
|
||||
return true
|
||||
} catch {
|
||||
session.lastSnippetMessage = "engine.add failed: \(error)"
|
||||
session.appendMessage("engine.add failed: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,7 @@ public final class SnippetContext {
|
||||
try session.swapSlot(name, synth: synth)
|
||||
return true
|
||||
} catch {
|
||||
session.lastSnippetMessage = "play(slot: \"\(name)\") failed: \(error)"
|
||||
session.appendMessage("play(slot: \"\(name)\") failed: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -136,6 +136,41 @@ public final class SnippetContext {
|
||||
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.
|
||||
@@ -146,7 +181,7 @@ public final class SnippetContext {
|
||||
/// 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.lastSnippetMessage = message
|
||||
session.appendMessage(message)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+128
-16
@@ -41,19 +41,41 @@ window.open {
|
||||
|
||||
| Shortcut | Action |
|
||||
|----------|--------|
|
||||
| ⌘↩ | Compile + run. Removes the previous run's *anonymous* synths first (named slots persist). |
|
||||
| ⌘⇧↩ | Compile + run additively. Keeps previously played synths in the engine. |
|
||||
| ⌘↩ | Compile + run the **whole buffer**. Removes the previous run's *anonymous* synths first (named slots persist). |
|
||||
| ⌘⇧↩ | 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. |
|
||||
|
||||
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
|
||||
``LyrebirdScratchModel/clearTracked()`` — a full reset that removes both the
|
||||
anonymous tracked synths and every named slot.
|
||||
|
||||
**Run Selection (⌘E)** evaluates only the highlighted text and *adds* it to the
|
||||
running graph, without touching the rest of the buffer or the whole-buffer
|
||||
re-evaluation baseline (the buffer's clean/dirty status still reflects the last
|
||||
whole run). This is the live-coding "evaluate this line/region" gesture: audition
|
||||
a single voice or tweak, layer it in, keep going. It reads the editor selection
|
||||
via ``LyrebirdScratchModel/updateSelection(_:)`` and runs it through
|
||||
``LyrebirdScratchModel/runSelection()``; disabled when nothing is selected.
|
||||
|
||||
The engine status pill at the top-left is also a **Start/Stop** button
|
||||
(``LyrebirdScratchModel/toggleEngine()``): green "engine running" when live,
|
||||
red "▶ start engine" when stopped. A snippet is only audible while the engine
|
||||
is running; the host normally starts it at launch, but this lets the user
|
||||
recover from a failed start (e.g. no output device) without relaunching.
|
||||
|
||||
## Engine panel (scope + status)
|
||||
|
||||
The panel at the bottom of the window is a small always-on view of the running
|
||||
engine:
|
||||
|
||||
- A live dual-channel **oscilloscope** of the output (``ScratchScopeView``),
|
||||
fed by a ``ScopeCapture`` that ``LiveSession`` attaches to the first one or two
|
||||
output buses at init (it must be installed before `start()`). Pass
|
||||
`attachScope: false` to `LiveSession.init` to opt out.
|
||||
- **CPU average / peak** meter bars and the **synth / group / snippet** counts,
|
||||
so overrun and node growth are visible at a glance.
|
||||
|
||||
## Snippet API surface
|
||||
|
||||
A snippet has one local in scope:
|
||||
@@ -71,8 +93,61 @@ context: SnippetContext
|
||||
subclass needed (wraps it in a `ClosureSynthesizer`).
|
||||
- `context.play(slot:_:)` / `context.play(slot:) { <graph> }` — play into a
|
||||
**named slot** (see below).
|
||||
- `context.reportMessage(_:)` — write back to the host (used by tests; handy for
|
||||
`print`-style probes during development).
|
||||
- `context.reportMessage(_:)` — print a line to the **Console** panel (see
|
||||
below); the live-coding equivalent of `print`.
|
||||
|
||||
## Console
|
||||
|
||||
An always-open panel down the right side of the window is the log:
|
||||
|
||||
- **Report messages** — every `context.reportMessage(_:)` line (and host notices
|
||||
like a failed `engine.add` or a dropped slot swap).
|
||||
- **Errors** — compile and Graph DSL diagnostics, with their `line:col`, shown
|
||||
here rather than in a transient bottom strip so they stay visible while you
|
||||
fix them.
|
||||
- **Run notices** — a one-line result for each run.
|
||||
|
||||
Oldest first, auto-scrolled to the newest, capped at
|
||||
``LyrebirdScratchModel/maxConsoleEntries`` lines. **Clear** empties it; a
|
||||
**Reset Session** clears it too. The model exposes the log as
|
||||
``LyrebirdScratchModel/consoleEntries``.
|
||||
|
||||
## 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
|
||||
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.
|
||||
|
||||
For example, a `for` loop that plays ten short sine tones a third of a second
|
||||
apart — a C-major run — each a decaying `Line` envelope times a sine that frees
|
||||
itself when done (`doneAction: .freeNode`), so the voices never pile up:
|
||||
|
||||
```swift
|
||||
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0,
|
||||
440.0, 493.88, 523.25, 587.33, 659.25]
|
||||
for i in 0..<10 {
|
||||
let freq: Double = scale[i]
|
||||
let tone = ClosureSynthesizer {
|
||||
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
|
||||
* OscSin.Audio(freq: freq)
|
||||
}
|
||||
do { try context.engine.schedule(tone, after: Double(i) * 0.35) }
|
||||
catch { context.reportMessage("schedule \(i) failed: \(error)") }
|
||||
}
|
||||
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.)
|
||||
|
||||
> Note: **Graph DSL mode** evaluates only generator-graph expressions — no loops
|
||||
> or scheduling. Functional code like the above needs **Swift mode**.
|
||||
|
||||
## Named slots (hot-swap)
|
||||
|
||||
@@ -95,11 +170,35 @@ voice at a time while the rest of the patch keeps going (the `Pdef` idiom).
|
||||
| `context.play(_:)` / `context.play { }` | Removed on the next non-additive run. |
|
||||
| `context.play(slot:) { }` | Persists; a same-name re-run replaces it in place. |
|
||||
|
||||
Clear a slot with `context.session.clearSlot("bass")`, all slots with
|
||||
`context.session.clearSlots()`. The toolbar **Clear Synths** button is a full
|
||||
reset — anonymous synths *and* every slot. A slot definition you delete from the
|
||||
buffer and stop re-running is *not* auto-removed (a `Pdef`-style gotcha) — clear
|
||||
it explicitly or hit Clear Synths.
|
||||
### Start a voice, release it later
|
||||
|
||||
The slot **name is the handle** — the persistent reference you keep across
|
||||
evaluations. (Swift `let`/`var` bindings do not carry from one snippet to the
|
||||
next: each ⌘↩ / ⌘E is a separately-compiled unit, so a variable declared in one
|
||||
run is invisible to the next.) So the "start something, let go of it later"
|
||||
gesture is: name a slot in one evaluation, then release it by name from another —
|
||||
a natural pairing with **Run Selection** (⌘E):
|
||||
|
||||
```swift
|
||||
// Select this line, ⌘E — starts a persistent, gated voice named "pad":
|
||||
context.play(slot: "pad") { EnvGen(gate: 1, /* … release-on-done */) * OscSaw.Audio(freq: 110) }
|
||||
|
||||
// …later, select this line, ⌘E — graceful release: the envelope tails out,
|
||||
// then the voice frees itself:
|
||||
context.release(slot: "pad")
|
||||
```
|
||||
|
||||
- `context.release(slot:)` triggers the voice's envelope **release** phase and
|
||||
drops the handle; the voice must free itself (an `EnvGen`/gate with a
|
||||
free-on-done action) to leave the engine.
|
||||
- `context.free(slot:)` is the **immediate** hard stop (no tail) — the
|
||||
counterpart to `release`.
|
||||
|
||||
Clear a slot with `context.free(slot: "bass")` (or `context.session.clearSlot`),
|
||||
all slots with `context.session.clearSlots()`. The toolbar **Clear Synths**
|
||||
button is a full reset — anonymous synths *and* every slot. A slot definition you
|
||||
delete from the buffer and stop re-running is *not* auto-removed (a `Pdef`-style
|
||||
gotcha) — release/free it explicitly or hit Clear Synths.
|
||||
|
||||
## Threading
|
||||
|
||||
@@ -194,11 +293,13 @@ through its own diagnostics.
|
||||
|
||||
Swift code completion is provided by the toolchain's `sourcekit-lsp`, driven over
|
||||
stdio by ``SourceKitLSPClient`` and bridged to the editor by
|
||||
``SnippetCompletionService``. Typing `.` after an expression pops the standard
|
||||
completion window; the candidates are the real symbols the snippet would see at
|
||||
compile time — `LyrebirdSynth` generators (`OscSin.` → `Audio`, `Control`, …),
|
||||
the injected `context` (`context.` → `play`, `engine`, …), and the Swift
|
||||
standard library.
|
||||
``SnippetCompletionService``. Press **Esc** (or **F5** — the standard macOS
|
||||
completion keys) to complete at the caret; the candidates are the real symbols the snippet would
|
||||
see at compile time — `LyrebirdSynth` generators (`OscSin.` → `Audio`, `Control`,
|
||||
…), the injected `context` (`context.` → `play`, `engine`, …), and the Swift
|
||||
standard library. Completion is **manual, never auto-triggered on `.`** — an
|
||||
unrequested popup ambushes typing and the built-in completion window is awkward
|
||||
to dismiss mid-edit.
|
||||
|
||||
How it resolves those symbols for an otherwise free-standing file: the service
|
||||
maintains a small temp workspace holding the snippet **wrapped** in the same
|
||||
@@ -216,8 +317,8 @@ candidates rather than an error.
|
||||
- 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.
|
||||
- Completion currently triggers on `.`; a manual-invoke shortcut is a possible
|
||||
follow-up.
|
||||
- Completion is invoked manually with **Esc** (or **F5**); there is no
|
||||
auto-trigger on `.`.
|
||||
- The host `.app` must not be sandboxed and must allow library validation to be
|
||||
disabled, since `swiftc` is invoked via `Process` and the resulting unsigned
|
||||
dylib is `dlopen`'d.
|
||||
@@ -251,6 +352,17 @@ orange and a warning banner appears — nudging the user to restart to reclaim t
|
||||
memory, or to switch to Graph DSL mode (which maps no dylibs). It is a nudge, not
|
||||
a hard stop: the choice stays with the user.
|
||||
|
||||
Two Run-menu commands act on this:
|
||||
|
||||
- **Reset Session** (``LyrebirdScratchModel/resetSession()``) — an *in-process*
|
||||
reset: stops all snippet audio, shuts down the code-completion server (freeing
|
||||
its subprocess and temp workspace), and clears diagnostics and the run
|
||||
baseline. **Non-destructive** — your buffer is left untouched, so it needs no
|
||||
confirmation. It does **not** unload the mapped snippet dylibs.
|
||||
- **Restart to Reclaim Memory…** — relaunches the app (after a confirmation,
|
||||
since unsaved buffer edits are lost), the only way to actually free the mapped
|
||||
dylibs. The fresh process starts at zero.
|
||||
|
||||
## Graph DSL mode (instant, no compile)
|
||||
|
||||
The status-bar toggle switches the editor between two evaluators:
|
||||
|
||||
@@ -152,10 +152,20 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
keyEquivalent: "\r")
|
||||
runAdd.keyEquivalentModifierMask = [.command, .shift]
|
||||
menu.addItem(target(runAdd))
|
||||
menu.addItem(target(NSMenuItem(title: "Run Selection",
|
||||
action: #selector(runSelection(_:)),
|
||||
keyEquivalent: "e")))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
|
||||
action: #selector(clearSynths(_:)),
|
||||
keyEquivalent: "k")))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(target(NSMenuItem(title: "Reset Session",
|
||||
action: #selector(resetSession(_:)),
|
||||
keyEquivalent: "")))
|
||||
menu.addItem(target(NSMenuItem(title: "Restart to Reclaim Memory…",
|
||||
action: #selector(restartApp(_:)),
|
||||
keyEquivalent: "")))
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
@@ -215,6 +225,12 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
switch menuItem.action {
|
||||
case #selector(runSnippet(_:)), #selector(runSnippetAdditive(_:)):
|
||||
return model.reevalState.canEvaluate
|
||||
case #selector(runSelection(_:)):
|
||||
// Needs a selection to run and an evaluator that isn't mid-compile.
|
||||
return model.hasSelection && model.reevalState.canEvaluate
|
||||
case #selector(resetSession(_:)):
|
||||
// Don't tear the session down mid-compile.
|
||||
return !model.isCompiling
|
||||
default:
|
||||
return true
|
||||
}
|
||||
@@ -280,6 +296,52 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
Task { @MainActor in _ = await model.run(additive: true) }
|
||||
}
|
||||
|
||||
@objc private func runSelection(_ sender: Any?) {
|
||||
Task { @MainActor in _ = await model.runSelection() }
|
||||
}
|
||||
|
||||
@objc private func resetSession(_ sender: Any?) {
|
||||
model.resetSession()
|
||||
}
|
||||
|
||||
@objc private func restartApp(_ sender: Any?) {
|
||||
let alert: NSAlert = NSAlert()
|
||||
alert.messageText = "Restart to reclaim memory?"
|
||||
alert.informativeText =
|
||||
"Relaunches the app to free the \(model.loadedSnippetCount) mapped snippet "
|
||||
+ "dylibs (compiled snippets can't be unloaded any other way). Unsaved changes "
|
||||
+ "in the buffer will be lost."
|
||||
alert.addButton(withTitle: "Restart")
|
||||
alert.addButton(withTitle: "Cancel")
|
||||
guard alert.runModal() == .alertFirstButtonReturn else { return }
|
||||
LyrebirdScratchMenuController.relaunchApp()
|
||||
}
|
||||
|
||||
/// Relaunch the host `.app`: open a fresh instance, then terminate this one
|
||||
/// once it is confirmed on its way. The new process starts with zero mapped
|
||||
/// snippet dylibs — the only way to reclaim that memory. On a launch failure
|
||||
/// the current process is **kept** (and the user informed) rather than
|
||||
/// terminated into oblivion.
|
||||
private static func relaunchApp() {
|
||||
let url: URL = Bundle.main.bundleURL
|
||||
let config: NSWorkspace.OpenConfiguration = NSWorkspace.OpenConfiguration()
|
||||
config.createsNewApplicationInstance = true
|
||||
NSWorkspace.shared.openApplication(at: url, configuration: config) { app, error in
|
||||
DispatchQueue.main.async {
|
||||
if let error: Error = error {
|
||||
let alert: NSAlert = NSAlert()
|
||||
alert.messageText = "Restart failed"
|
||||
alert.informativeText =
|
||||
"Could not relaunch the app (\(error.localizedDescription)). "
|
||||
+ "The current session is unchanged."
|
||||
alert.runModal()
|
||||
} else if app != nil {
|
||||
NSApp.terminate(nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func clearSynths(_ sender: Any?) {
|
||||
model.clearTracked()
|
||||
}
|
||||
|
||||
@@ -99,6 +99,48 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
/// Updated by `run(additive:)` and `clearTracked()`.
|
||||
@Published public private(set) var statusMessage: String = ""
|
||||
|
||||
/// Accumulated console log shown in the always-open right panel: snippet
|
||||
/// `context.reportMessage(_:)` output, compile/DSL errors, and run notices,
|
||||
/// oldest first. Capped at ``maxConsoleEntries``.
|
||||
@Published public private(set) var consoleEntries: [ScratchConsoleEntry] = []
|
||||
|
||||
/// Upper bound on retained console lines; the oldest are dropped past it.
|
||||
public nonisolated static let maxConsoleEntries: Int = 500
|
||||
|
||||
private var _consoleSeq: Int = 0
|
||||
|
||||
/// Append one console line, trimming the log to ``maxConsoleEntries``.
|
||||
private func appendConsole(_ kind: ScratchConsoleEntry.Kind, _ text: String, location: String? = nil) {
|
||||
_consoleSeq += 1
|
||||
consoleEntries.append(ScratchConsoleEntry(id: _consoleSeq, kind: kind, text: text, location: location))
|
||||
let overflow: Int = consoleEntries.count - LyrebirdScratchModel.maxConsoleEntries
|
||||
if overflow > 0 { consoleEntries.removeFirst(overflow) }
|
||||
}
|
||||
|
||||
/// Empty the console.
|
||||
public func clearConsole() {
|
||||
consoleEntries.removeAll()
|
||||
}
|
||||
|
||||
/// After a run resolves, move the snippet's report messages into the console
|
||||
/// (they arrive in order during the run), then the run outcome: on failure,
|
||||
/// each diagnostic as an error line; on success, a one-line notice.
|
||||
private func recordRunConsole(succeeded: Bool) {
|
||||
for message: String in session.drainMessages() {
|
||||
appendConsole(.message, message)
|
||||
}
|
||||
if succeeded {
|
||||
appendConsole(.info, statusMessage)
|
||||
} else if diagnostics.isEmpty {
|
||||
appendConsole(.error, statusMessage)
|
||||
} else {
|
||||
for diagnostic: Diagnostic in diagnostics {
|
||||
let location: String? = diagnostic.line.map { "\($0):\(diagnostic.column)" }
|
||||
appendConsole(.error, diagnostic.message, location: location)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mirror of `session.trackedSynthCount`, refreshed after every `run` /
|
||||
/// `clearTracked` call so the toolbar can show the count without polling.
|
||||
@Published public private(set) var trackedSynthCount: Int
|
||||
@@ -151,6 +193,23 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
/// horizontally.
|
||||
@Published public var wrapsLines: Bool = true
|
||||
|
||||
/// The current editor selection text (empty when nothing is selected).
|
||||
/// Pushed by the editor on selection change; drives ``hasSelection`` and
|
||||
/// ``runSelection()``.
|
||||
@Published public private(set) var selectionText: String = ""
|
||||
|
||||
/// `true` when the editor has a non-whitespace selection available to run.
|
||||
public var hasSelection: Bool {
|
||||
!selectionText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
}
|
||||
|
||||
/// Record the editor's current selection. Called by the editor's
|
||||
/// selection-change delegate; empty string clears it.
|
||||
public func updateSelection(_ text: String) {
|
||||
guard text != selectionText else { return } // avoid redundant republish
|
||||
selectionText = text
|
||||
}
|
||||
|
||||
/// Which evaluator ``run(additive:)`` sends the buffer through. `.swift`
|
||||
/// compiles a snippet dylib; `.graphDSL` interprets a generator graph
|
||||
/// instantly. Toggle via ``switchMode(to:)`` so the seed placeholder swaps
|
||||
@@ -229,7 +288,11 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
/// resolves (edits made mid-compile are re-evaluated once it finishes).
|
||||
private func recomputeReevalStateAfterEdit() {
|
||||
guard !isCompiling else { return }
|
||||
reevalState = derivedIdleState()
|
||||
// Assign only on a real change: after the first edit dirties the buffer,
|
||||
// every later keystroke re-derives `.dirty` — republishing an unchanged
|
||||
// value would re-render the whole view for nothing.
|
||||
let next: ReevalState = derivedIdleState()
|
||||
if next != reevalState { reevalState = next }
|
||||
}
|
||||
|
||||
/// Settle a `.queued` state once its scheduled swap has become audible.
|
||||
@@ -268,29 +331,48 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
@discardableResult
|
||||
public func run(additive: Bool) async -> Bool {
|
||||
switch evalMode {
|
||||
case .swift: return await runSwiftSnippet(additive: additive)
|
||||
case .graphDSL: return runGraphDSLBuffer(additive: additive)
|
||||
case .swift: return await runSwiftSnippet(body: text, additive: additive, recordBaseline: true)
|
||||
case .graphDSL: return runGraphDSLBuffer(body: text, additive: additive, recordBaseline: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Swift path: compile the buffer to a dylib off-main and run it.
|
||||
private func runSwiftSnippet(additive: Bool) async -> Bool {
|
||||
/// Evaluate just the current editor selection as an **additive** run: the
|
||||
/// selected text is compiled/interpreted and added to whatever is already
|
||||
/// playing (never a non-additive replace), and it does not disturb the
|
||||
/// whole-buffer re-evaluation baseline — the buffer's `.clean`/`.dirty`
|
||||
/// status still reflects the last *whole* run. No-op when nothing is
|
||||
/// selected. Works in both Swift and Graph DSL modes.
|
||||
@discardableResult
|
||||
public func runSelection() async -> Bool {
|
||||
guard hasSelection else { return false }
|
||||
let body: String = selectionText
|
||||
switch evalMode {
|
||||
case .swift: return await runSwiftSnippet(body: body, additive: true, recordBaseline: false)
|
||||
case .graphDSL: return runGraphDSLBuffer(body: body, additive: true, recordBaseline: false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Swift path: compile `body` to a dylib off-main and run it.
|
||||
/// `recordBaseline` distinguishes a whole-buffer run (updates the `.clean`
|
||||
/// baseline) from a selection run (leaves it untouched).
|
||||
private func runSwiftSnippet(body: String, additive: Bool, recordBaseline: Bool) async -> Bool {
|
||||
guard !isCompiling else { return false }
|
||||
let body: String = text
|
||||
diagnostics = []
|
||||
statusMessage = "Compiling…"
|
||||
isCompiling = true
|
||||
reevalState = .compiling
|
||||
var runSucceeded: Bool = false
|
||||
defer {
|
||||
isCompiling = false
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
loadedSnippetCount = session.loadedSnippetCount
|
||||
recordRunConsole(succeeded: runSucceeded)
|
||||
}
|
||||
do {
|
||||
try await session.compileAndRunAsync(body, additive: additive)
|
||||
let mode: String = additive ? "additive" : "replaced"
|
||||
statusMessage = "Ran (\(mode)). Tracked synths: \(session.trackedSynthCount)."
|
||||
settleReevalAfterSuccess(body: body)
|
||||
statusMessage = "Ran \(runDescription(additive: additive, recordBaseline: recordBaseline))."
|
||||
settleReeval(body: body, recordBaseline: recordBaseline)
|
||||
runSucceeded = true
|
||||
return true
|
||||
} catch let sessionError as LiveSessionError {
|
||||
switch sessionError {
|
||||
@@ -303,7 +385,7 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
message: "\(underlying)",
|
||||
rawLine: 0
|
||||
)]
|
||||
statusMessage = "Compile failed — see diagnostics below."
|
||||
statusMessage = "Compile failed — see console."
|
||||
} else {
|
||||
diagnostics = diags
|
||||
let plural: String = diags.count == 1 ? "" : "s"
|
||||
@@ -316,31 +398,32 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
diagnostics = diags
|
||||
statusMessage = "DSL error — \(diags.count) diagnostic(s)."
|
||||
}
|
||||
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||
return false
|
||||
} catch {
|
||||
statusMessage = "Error: \(error)"
|
||||
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Graph-DSL path: interpret the buffer in-process — instant, no swiftc, so
|
||||
/// no `isCompiling` spinner and no `await`. A parse/build failure leaves the
|
||||
/// Graph-DSL path: interpret `body` in-process — instant, no swiftc, so no
|
||||
/// `isCompiling` spinner and no `await`. A parse/build failure leaves the
|
||||
/// currently-playing graph untouched (the session builds before it mutates).
|
||||
private func runGraphDSLBuffer(additive: Bool) -> Bool {
|
||||
private func runGraphDSLBuffer(body: String, additive: Bool, recordBaseline: Bool) -> Bool {
|
||||
guard !isCompiling else { return false }
|
||||
let body: String = text
|
||||
diagnostics = []
|
||||
var runSucceeded: Bool = false
|
||||
defer {
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
loadedSnippetCount = session.loadedSnippetCount
|
||||
recordRunConsole(succeeded: runSucceeded)
|
||||
}
|
||||
do {
|
||||
try session.runGraphDSL(body, additive: additive)
|
||||
let mode: String = additive ? "additive" : "replaced"
|
||||
statusMessage = "Ran DSL (\(mode)). Tracked synths: \(session.trackedSynthCount)."
|
||||
settleReevalAfterSuccess(body: body)
|
||||
statusMessage = "Ran DSL \(runDescription(additive: additive, recordBaseline: recordBaseline))."
|
||||
settleReeval(body: body, recordBaseline: recordBaseline)
|
||||
runSucceeded = true
|
||||
return true
|
||||
} catch let sessionError as LiveSessionError {
|
||||
if case .graphDSLFailed(let diags, _) = sessionError {
|
||||
@@ -350,21 +433,23 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
} else {
|
||||
statusMessage = "Error: \(sessionError)"
|
||||
}
|
||||
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||
return false
|
||||
} catch {
|
||||
statusMessage = "Error: \(error)"
|
||||
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Record the just-run text as the baseline and settle the readiness state:
|
||||
/// `.queued` when the buffer is unchanged and a quantized slot swap is
|
||||
/// scheduled but not yet audible, otherwise the derived idle state (`.clean`,
|
||||
/// or `.dirty` if the buffer was edited while the run was in flight).
|
||||
private func settleReevalAfterSuccess(body: String) {
|
||||
lastEvaluatedText = body
|
||||
/// Settle the readiness state after a successful run. For a whole-buffer run
|
||||
/// (`recordBaseline`), record the run text as the `.clean` baseline; for a
|
||||
/// selection run, leave the baseline untouched (the buffer's status still
|
||||
/// reflects the last whole run). Either way resolve to `.queued` when the
|
||||
/// buffer is unchanged and a quantized swap is pending, else the derived
|
||||
/// idle state.
|
||||
private func settleReeval(body: String, recordBaseline: Bool) {
|
||||
if recordBaseline { lastEvaluatedText = body }
|
||||
let idle: ReevalState = derivedIdleState()
|
||||
if idle == .clean, let beat: Double = session.pendingSwapBeat {
|
||||
reevalState = .queued(untilBeat: beat)
|
||||
@@ -373,6 +458,33 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
/// Settle the readiness state after a *failed* run. A whole-buffer failure
|
||||
/// sets `.failed` (the badge should reflect that the buffer doesn't run). A
|
||||
/// selection failure must NOT touch the whole-buffer badge — the buffer and
|
||||
/// its last whole-run baseline are unaffected — so it recomputes the derived
|
||||
/// idle state and marks the status line as a selection failure. Diagnostics
|
||||
/// (already set by the caller) still surface the error either way.
|
||||
private func settleReevalAfterFailure(recordBaseline: Bool) {
|
||||
if recordBaseline {
|
||||
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||
} else {
|
||||
statusMessage = "Selection — " + statusMessage
|
||||
reevalState = derivedIdleState()
|
||||
}
|
||||
}
|
||||
|
||||
/// Status-line phrase for a run: distinguishes a whole-buffer replace/add
|
||||
/// from a selection add, and includes the live tracked-synth count.
|
||||
private func runDescription(additive: Bool, recordBaseline: Bool) -> String {
|
||||
let what: String
|
||||
if !recordBaseline {
|
||||
what = "selection (added)"
|
||||
} else {
|
||||
what = additive ? "additive" : "replaced"
|
||||
}
|
||||
return "(\(what)). Tracked synths: \(session.trackedSynthCount)"
|
||||
}
|
||||
|
||||
/// Switch evaluation mode. When the buffer still holds the *current* mode's
|
||||
/// untouched placeholder, swap in the target mode's placeholder so the seed
|
||||
/// example matches the mode; any edited buffer is left as-is.
|
||||
@@ -392,6 +504,34 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
reevalState = derivedIdleState()
|
||||
}
|
||||
|
||||
/// In-process session reset: stop all snippet audio, shut down the code-
|
||||
/// completion server (freeing its subprocess + temp workspace), and clear
|
||||
/// diagnostics and the run baseline. **Non-destructive** — the editor buffer
|
||||
/// (the user's code) is left untouched, so this needs no confirmation.
|
||||
///
|
||||
/// It reclaims everything it *can* in-process — but **not** the compiled
|
||||
/// snippet dylibs (`loadedSnippetCount`), which cannot be unloaded safely
|
||||
/// (`dlclose` is unsafe for Swift dylibs). Only relaunching the process frees
|
||||
/// those; the status line says so, and the "Restart" command does it.
|
||||
///
|
||||
/// 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`.
|
||||
public func resetSession() {
|
||||
guard !isCompiling else { return }
|
||||
session.resetAll()
|
||||
_completion?.shutdownSynchronously()
|
||||
_completion = nil // recreated lazily on next completion
|
||||
diagnostics = []
|
||||
consoleEntries.removeAll()
|
||||
lastEvaluatedText = nil
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
loadedSnippetCount = session.loadedSnippetCount
|
||||
reevalState = derivedIdleState()
|
||||
statusMessage = loadedSnippetCount > 0
|
||||
? "Session reset. \(loadedSnippetCount) snippet dylibs still mapped — Restart to reclaim that memory."
|
||||
: "Session reset."
|
||||
}
|
||||
|
||||
/// Start the audio engine if stopped, or stop it if running. Surfaces the
|
||||
/// outcome (including a start failure — e.g. no audio device) on the status
|
||||
/// line. The host normally starts the engine at launch; this lets the user
|
||||
|
||||
@@ -85,6 +85,28 @@ public struct LyrebirdScratchView: View {
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
HStack(spacing: 0) {
|
||||
mainColumn
|
||||
Divider()
|
||||
consolePanel
|
||||
.frame(width: consoleWidth)
|
||||
}
|
||||
.frame(minWidth: scratchMinWidth + consoleWidth, minHeight: scratchMinHeight)
|
||||
.onAppear {
|
||||
// Warm the module cache in the background so the first ⌘↩ is ~0.1 s
|
||||
// instead of paying the ~2–3 s cold `LyrebirdSynth` .pcm build.
|
||||
// Idempotent — safe if `onAppear` fires again.
|
||||
model.session.prewarm()
|
||||
}
|
||||
.onReceive(engineRefresh) { _ in
|
||||
engineTick &+= 1
|
||||
// Settle a `.queued` readiness badge once its swap has fired.
|
||||
model.refreshQueuedState()
|
||||
}
|
||||
}
|
||||
|
||||
/// The editor column: engine controls, editor, status, engine panel.
|
||||
private var mainColumn: some View {
|
||||
VStack(spacing: 0) {
|
||||
engineBar
|
||||
if let hint: String = model.snippetMemoryHint {
|
||||
@@ -101,27 +123,50 @@ public struct LyrebirdScratchView: View {
|
||||
wrapsLines: model.wrapsLines,
|
||||
requestCompletions: { line, character in
|
||||
await model.completionItems(line: line, character: character)
|
||||
}
|
||||
},
|
||||
onSelectionChanged: { selected in model.updateSelection(selected) }
|
||||
)
|
||||
.frame(minHeight: editorMinHeight)
|
||||
Divider()
|
||||
statusBar
|
||||
if !model.diagnostics.isEmpty {
|
||||
Divider()
|
||||
diagnosticsList
|
||||
Divider()
|
||||
enginePanel
|
||||
}
|
||||
}
|
||||
|
||||
/// Always-open right-side console: report messages, errors, and run notices,
|
||||
/// oldest first, auto-scrolled to the newest.
|
||||
private var consolePanel: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Text("Console")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Button("Clear") { model.clearConsole() }
|
||||
.buttonStyle(.plain)
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.disabled(model.consoleEntries.isEmpty)
|
||||
}
|
||||
.padding(.horizontal, statusHPad)
|
||||
.padding(.vertical, statusVPad)
|
||||
Divider()
|
||||
ScrollViewReader { proxy in
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 2) {
|
||||
ForEach(model.consoleEntries) { entry in
|
||||
ConsoleRow(entry: entry)
|
||||
}
|
||||
Color.clear.frame(height: 1).id(consoleBottomID)
|
||||
}
|
||||
.padding(diagnosticListPadding)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.onChange(of: model.consoleEntries.count) { _, _ in
|
||||
proxy.scrollTo(consoleBottomID, anchor: .bottom)
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(minWidth: scratchMinWidth, minHeight: scratchMinHeight)
|
||||
.onAppear {
|
||||
// Warm the module cache in the background so the first ⌘↩ is ~0.1 s
|
||||
// instead of paying the ~2–3 s cold `LyrebirdSynth` .pcm build.
|
||||
// Idempotent — safe if `onAppear` fires again.
|
||||
model.session.prewarm()
|
||||
}
|
||||
.onReceive(engineRefresh) { _ in
|
||||
engineTick &+= 1
|
||||
// Settle a `.queued` readiness badge once its swap has fired.
|
||||
model.refreshQueuedState()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,6 +225,73 @@ public struct LyrebirdScratchView: View {
|
||||
.background(Color.orange.opacity(0.12))
|
||||
}
|
||||
|
||||
/// 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)`.
|
||||
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)
|
||||
}
|
||||
|
||||
/// Heartbeat-refreshed engine readout: rate/channels, CPU meters, node counts.
|
||||
private var engineStatusRow: some View {
|
||||
let engine: SynthesisEngine = model.session.engine
|
||||
return VStack(alignment: .leading, spacing: 6) {
|
||||
HStack {
|
||||
Text("Engine")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch")
|
||||
.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)")
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
|
||||
/// One labelled CPU meter bar. `value` is a fraction of one block period
|
||||
/// (`[0, 1]`); the fill greens/oranges/reds as it approaches overrun.
|
||||
private func cpuMeter(label: String, value: Double) -> some View {
|
||||
let clamped: CGFloat = CGFloat(min(max(value, 0), 1))
|
||||
let fill: Color = value > cpuMeterCriticalThreshold
|
||||
? .red
|
||||
: (value > cpuMeterWarningThreshold ? .orange : .green)
|
||||
return HStack(spacing: 6) {
|
||||
Text(label)
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: cpuLabelWidth, alignment: .leading)
|
||||
GeometryReader { geo in
|
||||
ZStack(alignment: .leading) {
|
||||
RoundedRectangle(cornerRadius: 2).fill(Color.secondary.opacity(0.15))
|
||||
RoundedRectangle(cornerRadius: 2).fill(fill)
|
||||
.frame(width: geo.size.width * clamped)
|
||||
}
|
||||
}
|
||||
.frame(height: meterHeight)
|
||||
Text(formatCPU(value))
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: cpuValueWidth, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
|
||||
private func formatCPU(_ value: Double) -> String {
|
||||
String(format: "%.0f%%", value * 100)
|
||||
}
|
||||
@@ -190,6 +302,14 @@ public struct LyrebirdScratchView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate just the current selection, additively. No-op when nothing is
|
||||
/// selected.
|
||||
public func runSelection() {
|
||||
Task { @MainActor in
|
||||
_ = await model.runSelection()
|
||||
}
|
||||
}
|
||||
|
||||
public func presentOpenPanel() {
|
||||
let panel: NSOpenPanel = NSOpenPanel()
|
||||
panel.allowedContentTypes = [.swiftSource]
|
||||
@@ -322,18 +442,6 @@ public struct LyrebirdScratchView: View {
|
||||
}
|
||||
}
|
||||
|
||||
private var diagnosticsList: some View {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: diagnosticRowSpacing) {
|
||||
ForEach(Array(model.diagnostics.enumerated()), id: \.offset) { _, diag in
|
||||
DiagnosticRow(diagnostic: diag)
|
||||
}
|
||||
}
|
||||
.padding(diagnosticListPadding)
|
||||
}
|
||||
.frame(minHeight: diagnosticsMinHeight, maxHeight: diagnosticsMaxHeight)
|
||||
}
|
||||
|
||||
// Layout constants — all in points. Kept private; tuned to match
|
||||
// LyrebirdEngineStatusView's visual density.
|
||||
private let scratchMinWidth: CGFloat = 520
|
||||
@@ -350,26 +458,38 @@ public struct LyrebirdScratchView: View {
|
||||
private let diagnosticsMaxHeight: CGFloat = 200
|
||||
private let engineDotSize: CGFloat = 8
|
||||
private let reevalBadgeSpacing: CGFloat = 4
|
||||
private let scopeHeight: CGFloat = 88
|
||||
private let meterHeight: CGFloat = 6
|
||||
private let consoleWidth: CGFloat = 300
|
||||
private let consoleBottomID: String = "scratch.console.bottom"
|
||||
private let cpuLabelWidth: CGFloat = 58
|
||||
private let cpuValueWidth: CGFloat = 40
|
||||
/// CPU-meter fill turns orange above this fraction of one block period, red
|
||||
/// above ``cpuMeterCriticalThreshold``.
|
||||
private let cpuMeterWarningThreshold: Double = 0.5
|
||||
private let cpuMeterCriticalThreshold: Double = 0.8
|
||||
}
|
||||
|
||||
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
|
||||
/// message in a compact monospaced row.
|
||||
private struct DiagnosticRow: View {
|
||||
private struct ConsoleRow: View {
|
||||
|
||||
let diagnostic: Diagnostic
|
||||
let entry: ScratchConsoleEntry
|
||||
|
||||
var body: some View {
|
||||
HStack(alignment: .firstTextBaseline, spacing: rowGutter) {
|
||||
Text(locationString)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(minWidth: locationColumnWidth, alignment: .leading)
|
||||
Text(diagnostic.severity.rawValue)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(color(for: diagnostic.severity))
|
||||
.frame(minWidth: severityColumnWidth, alignment: .leading)
|
||||
Text(diagnostic.message)
|
||||
HStack(alignment: .firstTextBaseline, spacing: 6) {
|
||||
Text(glyph)
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(color)
|
||||
.frame(width: 14, alignment: .leading)
|
||||
if let location: String = entry.location {
|
||||
Text(location)
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
Text(entry.text)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(entry.kind == .error ? Color.primary : color)
|
||||
.textSelection(.enabled)
|
||||
.multilineTextAlignment(.leading)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
@@ -377,58 +497,88 @@ private struct DiagnosticRow: View {
|
||||
}
|
||||
}
|
||||
|
||||
private var locationString: String {
|
||||
if let line: Int = diagnostic.line {
|
||||
return "\(line):\(diagnostic.column)"
|
||||
/// Leading glyph per kind: an X for errors, an arrow for messages, a dot for
|
||||
/// info notices.
|
||||
private var glyph: String {
|
||||
switch entry.kind {
|
||||
case .error: return "✗"
|
||||
case .message: return "›"
|
||||
case .info: return "·"
|
||||
}
|
||||
// No user-body line. A swiftc preamble hit carries a real (1-based)
|
||||
// rawLine; a graph-DSL file-scope error carries rawLine 0 (there is no
|
||||
// harness/preamble at all), so label the two cases distinctly.
|
||||
return diagnostic.rawLine >= 1
|
||||
? "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
|
||||
: "(file)"
|
||||
}
|
||||
|
||||
private func color(for severity: DiagnosticSeverity) -> Color {
|
||||
switch severity {
|
||||
private var color: Color {
|
||||
switch entry.kind {
|
||||
case .error: return .red
|
||||
case .warning: return .orange
|
||||
case .note: return .secondary
|
||||
case .message: return .cyan
|
||||
case .info: return .secondary
|
||||
}
|
||||
}
|
||||
|
||||
private let rowGutter: CGFloat = 8
|
||||
private let locationColumnWidth: CGFloat = 80
|
||||
private let severityColumnWidth: CGFloat = 56
|
||||
}
|
||||
|
||||
/// `NSTextView` subclass that fixes member-completion behavior.
|
||||
///
|
||||
/// The default `rangeForUserCompletion` scans back over the whole dotted
|
||||
/// expression, so completing a member right after a `.` (e.g. `context.` →
|
||||
/// `engine`) would *replace* the receiver (`context`) with the chosen member
|
||||
/// instead of inserting after the dot. When the character before the insertion
|
||||
/// point is a `.`, this override returns an empty range at the caret, so the
|
||||
/// completion is a pure insertion and `context.engine` is produced.
|
||||
/// UTF-16 code unit for `.` (the member-access operator that triggers and
|
||||
/// shapes completion).
|
||||
private let dotCharacterCode: unichar = 46
|
||||
/// expression, so a candidate would *replace* the receiver rather than the
|
||||
/// partial word being typed. Completing a member after `context.` → `engine`
|
||||
/// would replace `context`; accepting an argument label after `OscSin.Audio(`
|
||||
/// → `freq:` would replace `OscSin.Audio`. The correct replace range is just
|
||||
/// the run of identifier characters immediately before the caret (empty after
|
||||
/// any boundary — `.`, `(`, `,`, whitespace), so the candidate inserts there.
|
||||
|
||||
/// Whether `selection` is a bare insertion point sitting immediately after a
|
||||
/// `.` in `text` — the member-completion trigger condition.
|
||||
private func caretFollowsDot(in text: NSString, selection: NSRange) -> Bool {
|
||||
guard selection.length == 0, selection.location > 0, selection.location <= text.length
|
||||
else { return false }
|
||||
return text.character(at: selection.location - 1) == dotCharacterCode
|
||||
/// Whether `c` (a UTF-16 code unit) is a Swift identifier character —
|
||||
/// ASCII letter, digit, or underscore. Sufficient for completion-range
|
||||
/// scanning; identifiers with non-ASCII scalars are not a concern here.
|
||||
private func isIdentifierCodeUnit(_ c: unichar) -> Bool {
|
||||
let underscore: unichar = 95
|
||||
let zero: unichar = 48, nine: unichar = 57
|
||||
let upperA: unichar = 65, upperZ: unichar = 90
|
||||
let lowerA: unichar = 97, lowerZ: unichar = 122
|
||||
return c == underscore
|
||||
|| (c >= zero && c <= nine)
|
||||
|| (c >= upperA && c <= upperZ)
|
||||
|| (c >= lowerA && c <= lowerZ)
|
||||
}
|
||||
|
||||
final class ScratchTextView: NSTextView {
|
||||
/// Invoked when the user asks for completion (the standard completion key —
|
||||
/// Esc / F5). Set by `makeNSView`, right after `configure`; runs the async fetch and then
|
||||
/// shows the completion window. Completion is manual only.
|
||||
var onManualComplete: (() -> Void)?
|
||||
|
||||
override var rangeForUserCompletion: NSRange {
|
||||
let sel: NSRange = selectedRange()
|
||||
if caretFollowsDot(in: string as NSString, selection: sel) {
|
||||
return NSRange(location: sel.location, length: 0)
|
||||
// Never replace across an actual selection — defer to the default.
|
||||
guard sel.length == 0, sel.location <= (string as NSString).length else {
|
||||
return super.rangeForUserCompletion
|
||||
}
|
||||
return super.rangeForUserCompletion
|
||||
let ns: NSString = string as NSString
|
||||
var start: Int = sel.location
|
||||
while start > 0 && isIdentifierCodeUnit(ns.character(at: start - 1)) {
|
||||
start -= 1
|
||||
}
|
||||
return NSRange(location: start, length: sel.location - start)
|
||||
}
|
||||
|
||||
/// Intercept the built-in `complete:` command (bound to Esc / F5) so the
|
||||
/// candidates are fetched asynchronously first, then shown. Without this,
|
||||
/// pressing Esc would call the delegate with an empty (never-fetched) list.
|
||||
/// Everything else falls through to the normal editor commands.
|
||||
override func doCommand(by selector: Selector) {
|
||||
if selector == #selector(NSStandardKeyBindingResponding.complete(_:)) {
|
||||
onManualComplete?()
|
||||
return
|
||||
}
|
||||
super.doCommand(by: selector)
|
||||
}
|
||||
|
||||
/// Esc is delivered as `cancelOperation:` (not `complete:`) by the default
|
||||
/// key bindings, so it never reaches `doCommand(by:)`'s `complete:` arm —
|
||||
/// only F5 does. Route it here too so Esc invokes completion as documented.
|
||||
/// The completion window, once open, consumes Esc itself to dismiss, so this
|
||||
/// only fires when the window is closed.
|
||||
override func cancelOperation(_ sender: Any?) {
|
||||
onManualComplete?()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -444,6 +594,9 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
/// Async source of code-completion candidates for a zero-based user-space
|
||||
/// (line, UTF-16 character). Supplied by the view from the model.
|
||||
let requestCompletions: @MainActor (_ line: Int, _ character: Int) async -> [LSPCompletionItem]
|
||||
/// Called with the current selected substring whenever the selection
|
||||
/// changes (empty when nothing is selected). Drives "Run Selection".
|
||||
let onSelectionChanged: @MainActor (String) -> Void
|
||||
|
||||
@MainActor
|
||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||
@@ -455,17 +608,67 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
/// applies its results if it is still the newest (so a slow older request
|
||||
/// can't clobber a fresher one that landed first).
|
||||
private var _completionGeneration: Int = 0
|
||||
/// Pending debounced re-highlight; cancelled and rescheduled on each edit
|
||||
/// so a burst of keystrokes re-tokenizes the buffer once, not per key.
|
||||
private var _highlightWork: DispatchWorkItem?
|
||||
/// Last selection substring pushed to the model, so an unchanged selection
|
||||
/// (the common case while typing — caret moves, selection stays empty)
|
||||
/// doesn't republish `@Published` state and re-render the whole view.
|
||||
private var _lastSelectionPushed: String = ""
|
||||
/// Last `wrapsLines` value applied, so `updateNSView` can skip re-applying
|
||||
/// wrap/paragraph settings on a pure text republish (every keystroke).
|
||||
var lastWraps: Bool?
|
||||
|
||||
/// Idle delay before re-highlighting after an edit. Short enough to feel
|
||||
/// instant once typing pauses; long enough to coalesce a fast burst.
|
||||
private static let highlightDebounce: TimeInterval = 0.045
|
||||
|
||||
init(_ parent: ScratchEditor) { self.parent = parent }
|
||||
|
||||
func textDidChange(_ notification: Notification) {
|
||||
guard let tv: NSTextView = notification.object as? NSTextView else { return }
|
||||
parent.text = tv.string
|
||||
parent.applyHighlight(to: tv)
|
||||
// Auto-trigger member completion right after a `.` is typed.
|
||||
if caretFollowsDot(in: tv.string as NSString, selection: tv.selectedRange()) {
|
||||
triggerCompletion(tv)
|
||||
scheduleHighlight(tv)
|
||||
// Completion is manual (Esc), never auto-triggered on `.`: an
|
||||
// unrequested popup ambushes typing and the built-in completion
|
||||
// window is awkward to dismiss mid-edit.
|
||||
}
|
||||
|
||||
/// Coalesce full-buffer re-highlighting: cancel any pending pass and run
|
||||
/// one shortly after the edits stop. Newly typed characters render in the
|
||||
/// base color immediately (via `typingAttributes`); syntax colors catch
|
||||
/// up a beat later, avoiding an O(n) tokenize on every keystroke.
|
||||
private func scheduleHighlight(_ tv: NSTextView) {
|
||||
_highlightWork?.cancel()
|
||||
let work: DispatchWorkItem = DispatchWorkItem { [weak self, weak tv] in
|
||||
guard let self: Coordinator = self, let tv: NSTextView = tv else { return }
|
||||
self.parent.applyHighlight(to: tv)
|
||||
}
|
||||
_highlightWork = work
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + Coordinator.highlightDebounce, execute: work)
|
||||
}
|
||||
|
||||
/// Push the current selected substring up to the model so "Run Selection"
|
||||
/// knows what (if anything) is selected — but only when it actually
|
||||
/// changed, to avoid a per-caret-move `@Published` republish.
|
||||
func textViewDidChangeSelection(_ notification: Notification) {
|
||||
guard let tv: NSTextView = notification.object as? NSTextView else { return }
|
||||
let sel: NSRange = tv.selectedRange()
|
||||
let selected: String
|
||||
if sel.length > 0, sel.location + sel.length <= (tv.string as NSString).length {
|
||||
selected = (tv.string as NSString).substring(with: sel)
|
||||
} else {
|
||||
selected = ""
|
||||
}
|
||||
guard selected != _lastSelectionPushed else { return }
|
||||
_lastSelectionPushed = selected
|
||||
// Defer the @Published mutation: a programmatic text change (via
|
||||
// `updateNSView` → `replaceText`) can clamp the selection and re-post
|
||||
// this notification from inside a SwiftUI update pass. Scheduling on
|
||||
// the next main-actor tick keeps that off the render pass ("Publishing
|
||||
// changes from within view updates is not allowed").
|
||||
let notify: @MainActor (String) -> Void = parent.onSelectionChanged
|
||||
Task { @MainActor in notify(selected) }
|
||||
}
|
||||
|
||||
/// The text view calls this synchronously from `complete(_:)`; return the
|
||||
@@ -525,6 +728,12 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
scroll.documentView = tv
|
||||
|
||||
configure(tv, in: scroll, with: context.coordinator)
|
||||
// Manual completion (Esc): fetch candidates, then show the window.
|
||||
let coordinator: Coordinator = context.coordinator
|
||||
tv.onManualComplete = { [weak coordinator, weak tv] in
|
||||
guard let coordinator: Coordinator = coordinator, let tv: ScratchTextView = tv else { return }
|
||||
coordinator.triggerCompletion(tv)
|
||||
}
|
||||
return scroll
|
||||
}
|
||||
|
||||
@@ -533,14 +742,23 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
guard let tv: NSTextView = scroll.documentView as? NSTextView else { return }
|
||||
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
||||
let fontChanged: Bool = (tv.font?.pointSize ?? -1) != fontSize
|
||||
if fontChanged {
|
||||
tv.font = font
|
||||
}
|
||||
let wrapChanged: Bool = context.coordinator.lastWraps != wrapsLines
|
||||
context.coordinator.lastWraps = wrapsLines
|
||||
let textChanged: Bool = tv.string != text
|
||||
|
||||
// Fast path: a pure text republish (the per-keystroke case) needs no work
|
||||
// here — the `NSTextView` already holds the text (it's the editor of
|
||||
// record), highlighting is debounced in the Coordinator, and font/wrap
|
||||
// are unchanged. Skip the paragraph-style measure + attribute churn.
|
||||
guard textChanged || fontChanged || wrapChanged else { return }
|
||||
|
||||
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: font)
|
||||
if fontChanged { tv.font = font }
|
||||
tv.defaultParagraphStyle = paragraphStyle
|
||||
tv.typingAttributes = makeAttrs(font: font, paragraph: paragraphStyle)
|
||||
applyWrap(to: tv, in: scroll)
|
||||
if tv.string != text {
|
||||
if textChanged {
|
||||
// External change (load, reset, mode switch) — replace + re-highlight.
|
||||
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
|
||||
} else if fontChanged {
|
||||
applyHighlight(to: tv, font: font, paragraph: paragraphStyle)
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
// ScratchConsoleEntry.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// One line in the scratch editor's console panel — a report message, an error,
|
||||
// or a run notice.
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
/// A single entry in the always-open console.
|
||||
public struct ScratchConsoleEntry: Identifiable, Equatable {
|
||||
|
||||
/// What kind of line this is, for coloring.
|
||||
public enum Kind: Equatable {
|
||||
/// `context.reportMessage(_:)` output (and host notices).
|
||||
case message
|
||||
/// A compile / DSL error.
|
||||
case error
|
||||
/// A run outcome / informational notice.
|
||||
case info
|
||||
}
|
||||
|
||||
/// Monotonic id (also the display order).
|
||||
public let id: Int
|
||||
public let kind: Kind
|
||||
public let text: String
|
||||
/// `"line:col"` for an error with a known source position, else `nil`.
|
||||
public let location: String?
|
||||
|
||||
public init(id: Int, kind: Kind, text: String, location: String? = nil) {
|
||||
self.id = id
|
||||
self.kind = kind
|
||||
self.text = text
|
||||
self.location = location
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,85 @@
|
||||
// ScratchScopeView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// A compact real-time oscilloscope for the scratch editor's engine panel.
|
||||
// Reimplemented here (rather than reusing `LyrebirdUI.LyrebirdScopeView`) because
|
||||
// the LiveCompile stack must not link `LyrebirdUI` — that would static-fold a
|
||||
// second copy of `LyrebirdSynth`'s ObjC classes. It reads the same core
|
||||
// `ScopeCapture` the engine writes to.
|
||||
|
||||
#if os(macOS)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Polls a ``ScopeCapture`` at ~30 Hz and draws each captured channel's waveform
|
||||
/// with `Canvas`. Channels stack vertically; channel 0 cyan, channel 1 orange.
|
||||
struct ScratchScopeView: View {
|
||||
|
||||
let capture: ScopeCapture
|
||||
|
||||
@State private var channels: [[Float]] = []
|
||||
|
||||
private static let pollIntervalNs: UInt64 = 33_333_333 // ~30 Hz
|
||||
private static let channelColors: [Color] = [.cyan, .orange, .green, .yellow]
|
||||
private static let backgroundColor: Color = Color(white: 0.08)
|
||||
private static let zeroLineOpacity: Double = 0.25
|
||||
private static let separatorOpacity: Double = 0.3
|
||||
private static let waveformHeightFraction: CGFloat = 0.44
|
||||
|
||||
var body: some View {
|
||||
Canvas { ctx, size in
|
||||
ctx.fill(Path(CGRect(origin: .zero, size: size)),
|
||||
with: .color(ScratchScopeView.backgroundColor))
|
||||
guard !channels.isEmpty else { return }
|
||||
let count: Int = channels.count
|
||||
let rowH: CGFloat = size.height / CGFloat(count)
|
||||
|
||||
for (ch, samples): (Int, [Float]) in channels.enumerated() {
|
||||
let midY: CGFloat = rowH * (CGFloat(ch) + 0.5)
|
||||
let halfH: CGFloat = rowH * ScratchScopeView.waveformHeightFraction
|
||||
|
||||
var guide: Path = Path()
|
||||
guide.move(to: CGPoint(x: 0, y: midY))
|
||||
guide.addLine(to: CGPoint(x: size.width, y: midY))
|
||||
ctx.stroke(guide, with: .color(.white.opacity(ScratchScopeView.zeroLineOpacity)),
|
||||
lineWidth: 0.5)
|
||||
|
||||
if ch < count - 1 {
|
||||
let sepY: CGFloat = rowH * CGFloat(ch + 1)
|
||||
var sep: Path = Path()
|
||||
sep.move(to: CGPoint(x: 0, y: sepY))
|
||||
sep.addLine(to: CGPoint(x: size.width, y: sepY))
|
||||
ctx.stroke(sep, with: .color(.white.opacity(ScratchScopeView.separatorOpacity)),
|
||||
lineWidth: 0.5)
|
||||
}
|
||||
|
||||
guard samples.count > 1 else { continue }
|
||||
let color: Color = ScratchScopeView.channelColors[ch % ScratchScopeView.channelColors.count]
|
||||
let xStep: CGFloat = size.width / CGFloat(samples.count - 1)
|
||||
var path: Path = Path()
|
||||
for (i, sample): (Int, Float) in samples.enumerated() {
|
||||
let x: CGFloat = CGFloat(i) * xStep
|
||||
let y: CGFloat = midY - CGFloat(sample) * halfH
|
||||
if i == 0 { path.move(to: CGPoint(x: x, y: y)) }
|
||||
else { path.addLine(to: CGPoint(x: x, y: y)) }
|
||||
}
|
||||
ctx.stroke(path, with: .color(color), lineWidth: 1.0)
|
||||
}
|
||||
}
|
||||
.background(ScratchScopeView.backgroundColor)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 4))
|
||||
.task {
|
||||
while !Task.isCancelled {
|
||||
channels = capture.snapshot()
|
||||
try? await Task.sleep(nanoseconds: ScratchScopeView.pollIntervalNs)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,43 @@
|
||||
// MessageLogTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@MainActor
|
||||
@Suite("LiveSession message log")
|
||||
struct MessageLogTests {
|
||||
|
||||
private func makeSession() -> LiveSession {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LiveSession(engine: engine)
|
||||
}
|
||||
|
||||
@Test func accumulatesAndDrains() {
|
||||
let session: LiveSession = makeSession()
|
||||
session.appendMessage("a")
|
||||
session.appendMessage("b")
|
||||
#expect(session.lastSnippetMessage == "b") // last value, for tests
|
||||
#expect(session.drainMessages() == ["a", "b"])
|
||||
// Drained → empty.
|
||||
#expect(session.lastSnippetMessage == nil)
|
||||
#expect(session.drainMessages().isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,63 @@
|
||||
// ScopeAttachTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@MainActor
|
||||
@Suite("LiveSession scope attach")
|
||||
struct ScopeAttachTests {
|
||||
|
||||
private func makeEngine(outChannels: Int = 2) -> SynthesisEngine {
|
||||
SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: outChannels,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
}
|
||||
|
||||
@Test func attachesStereoScopeByDefault() {
|
||||
let engine: SynthesisEngine = makeEngine(outChannels: 2)
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
let scope: ScopeCapture? = session.scope
|
||||
#expect(scope != nil)
|
||||
#expect(scope?.buses == [0, 1])
|
||||
// Installed on the engine so the RT thread writes to it.
|
||||
#expect(engine.scopeTap === scope)
|
||||
}
|
||||
|
||||
@Test func attachScopeFalseInstallsNothing() {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let session: LiveSession = LiveSession(engine: engine, attachScope: false)
|
||||
#expect(session.scope == nil)
|
||||
#expect(engine.scopeTap == nil)
|
||||
}
|
||||
|
||||
@Test func monoEngineTapsOneBus() {
|
||||
let engine: SynthesisEngine = makeEngine(outChannels: 1)
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
#expect(session.scope?.buses == [0])
|
||||
}
|
||||
|
||||
@Test func reusesExistingTapRatherThanReplacing() {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let existing: ScopeCapture = ScopeCapture(buses: [0], bufferSize: 256)
|
||||
engine.scopeTap = existing
|
||||
let session: LiveSession = LiveSession(engine: engine) // attach on, but a tap exists
|
||||
#expect(session.scope === existing)
|
||||
#expect(engine.scopeTap === existing)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,94 @@
|
||||
// SlotReleaseTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@MainActor
|
||||
@Suite("LiveSession slot release")
|
||||
struct SlotReleaseTests {
|
||||
|
||||
/// A synth whose graceful `release` succeeds (records the call) — stands in
|
||||
/// for a gated `EnvGen` voice.
|
||||
private final class GatedSynth: SynthesizerBase, @unchecked Sendable {
|
||||
var released: Bool = false
|
||||
override func build() { addOutputGenerator(Out.Audio(bus: 0, source: 0.1)) }
|
||||
override func release(engine: SynthesisEngine) throws { released = true }
|
||||
}
|
||||
|
||||
/// A synth with no gate — inherits the default `release` that throws `.noGate`.
|
||||
private final class GatelessSynth: SynthesizerBase, @unchecked Sendable {
|
||||
override func build() { addOutputGenerator(Out.Audio(bus: 0, source: 0.1)) }
|
||||
}
|
||||
|
||||
private func makeStartedSession() throws -> LiveSession {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
try engine.start()
|
||||
return session
|
||||
}
|
||||
|
||||
@Test func releaseGatedSlotTriggersReleaseAndDropsHandle() throws {
|
||||
let session: LiveSession = try makeStartedSession()
|
||||
let voice: GatedSynth = GatedSynth()
|
||||
try session.swapSlot("pad", synth: voice)
|
||||
#expect(session.slotNames.contains("pad"))
|
||||
|
||||
let released: Bool = session.releaseSlot("pad")
|
||||
#expect(released)
|
||||
#expect(voice.released) // graceful release fired
|
||||
#expect(session.slotNames.contains("pad") == false) // handle dropped, name free
|
||||
// Safety net: the released voice moves to the tracked list so it stays
|
||||
// reclaimable by resetAll() / Clear Synths even if it never self-frees.
|
||||
#expect(session.trackedSynthCount == 1)
|
||||
session.resetAll()
|
||||
#expect(session.trackedSynthCount == 0)
|
||||
session.engine.stop()
|
||||
}
|
||||
|
||||
@Test func nameIsReusableAfterRelease() throws {
|
||||
let session: LiveSession = try makeStartedSession()
|
||||
try session.swapSlot("pad", synth: GatedSynth())
|
||||
#expect(session.releaseSlot("pad"))
|
||||
// The name is free again — a fresh voice claims the slot cleanly.
|
||||
try session.swapSlot("pad", synth: GatedSynth())
|
||||
#expect(session.slotNames.contains("pad"))
|
||||
#expect(session.slotCount == 1)
|
||||
session.engine.stop()
|
||||
}
|
||||
|
||||
@Test func releaseGatelessSlotFailsAndKeepsHandle() throws {
|
||||
let session: LiveSession = try makeStartedSession()
|
||||
try session.swapSlot("bass", synth: GatelessSynth())
|
||||
|
||||
let released: Bool = session.releaseSlot("bass")
|
||||
#expect(released == false)
|
||||
// Not orphaned — still in the slot, still stoppable with a hard clear.
|
||||
#expect(session.slotNames.contains("bass"))
|
||||
#expect(session.clearSlot("bass"))
|
||||
session.engine.stop()
|
||||
}
|
||||
|
||||
@Test func releaseEmptySlotReturnsFalse() throws {
|
||||
let session: LiveSession = try makeStartedSession()
|
||||
#expect(session.releaseSlot("nothing-here") == false)
|
||||
session.engine.stop()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,76 @@
|
||||
// SnippetScheduledLoopTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
/// Proves the scratch editor runs *functional* Swift — a real `for` loop that
|
||||
/// schedules a timed sequence — not just single-graph expressions.
|
||||
@MainActor
|
||||
@Suite("Snippet scheduled loop")
|
||||
struct SnippetScheduledLoopTests {
|
||||
|
||||
@Test func loopSchedulesTenSelfFreeingTones() 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)
|
||||
try engine.start()
|
||||
|
||||
// A `for` loop that schedules ten short sine tones, 0.35 s apart. Each is
|
||||
// a decaying amplitude envelope (`Line` with `doneAction: .freeNode`)
|
||||
// times a sine, so it plays ~0.2 s and then frees itself — no manual
|
||||
// cleanup, no blocking the main thread.
|
||||
let snippet: String = """
|
||||
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0,
|
||||
440.0, 493.88, 523.25, 587.33, 659.25]
|
||||
for i in 0..<10 {
|
||||
let freq: Double = scale[i]
|
||||
let tone = ClosureSynthesizer {
|
||||
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
|
||||
* OscSin.Audio(freq: freq)
|
||||
}
|
||||
do { try context.engine.schedule(tone, after: Double(i) * 0.35) }
|
||||
catch { context.reportMessage("schedule failed: \\(error)") }
|
||||
}
|
||||
context.reportMessage("scheduled 10 tones")
|
||||
"""
|
||||
|
||||
try session.compileAndRun(snippet)
|
||||
// The `for` loop and the scheduling calls compiled and ran.
|
||||
#expect(session.lastSnippetMessage == "scheduled 10 tones")
|
||||
|
||||
// Advance ~4.5 s of audio; the scheduled adds fire over time. (Each
|
||||
// tone's `.freeNode` self-frees via the engine's async auto-free watcher
|
||||
// in the running app — that background timer doesn't get a turn inside
|
||||
// this synchronous processBlock loop, so here the tones accumulate; the
|
||||
// auto-free path itself is covered by `AutoFreeOnDoneTests`.)
|
||||
let blocks: Int = Int(4.5 * 44_100 / 512)
|
||||
var peakActive: Int = 0
|
||||
var producedAudio: Bool = false
|
||||
for _ in 0..<blocks {
|
||||
engine.processBlock(inputSamples: [])
|
||||
peakActive = max(peakActive, engine.synthesizerCount)
|
||||
if engine.audioBuses[0].contains(where: { $0 != 0 }) { producedAudio = true }
|
||||
}
|
||||
|
||||
#expect(peakActive == 10, "all ten scheduled tones should have entered the tree over time")
|
||||
#expect(producedAudio, "the scheduled tones should have written audio to the bus")
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -64,7 +64,9 @@ struct LyrebirdScratchModelTests {
|
||||
#expect(model.diagnostics.isEmpty)
|
||||
#expect(model.statusMessage.contains("replaced"))
|
||||
#expect(model.statusMessage.contains("Tracked synths: 0"))
|
||||
#expect(session.lastSnippetMessage == "hello")
|
||||
// The report message is drained from the session into the console.
|
||||
#expect(model.consoleEntries.contains { $0.kind == .message && $0.text == "hello" })
|
||||
#expect(session.lastSnippetMessage == nil) // drained
|
||||
#expect(model.isCompiling == false)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
// ScratchModelConsoleTests.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 console")
|
||||
@MainActor
|
||||
struct ScratchModelConsoleTests {
|
||||
|
||||
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), initialText: text)
|
||||
}
|
||||
|
||||
@Test func successfulRunLogsInfo() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false)
|
||||
#expect(model.consoleEntries.contains { $0.kind == .info })
|
||||
}
|
||||
|
||||
@Test func failedRunLogsErrorEntries() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "NotAGenerator(freq: 1)")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false)
|
||||
#expect(model.consoleEntries.contains { $0.kind == .error })
|
||||
#expect(model.consoleEntries.contains { $0.text.contains("NotAGenerator") })
|
||||
}
|
||||
|
||||
@Test func reportMessagesAppearAsMessages() async {
|
||||
// A DSL run pushes no messages; drive the log directly to prove the
|
||||
// message → console wiring (drainMessages → .message entries).
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
model.session.appendMessage("hello from snippet")
|
||||
_ = await model.run(additive: false)
|
||||
#expect(model.consoleEntries.contains { $0.kind == .message && $0.text == "hello from snippet" })
|
||||
}
|
||||
|
||||
@Test func clearConsoleEmpties() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false)
|
||||
#expect(!model.consoleEntries.isEmpty)
|
||||
model.clearConsole()
|
||||
#expect(model.consoleEntries.isEmpty)
|
||||
}
|
||||
|
||||
@Test func resetSessionClearsConsole() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false)
|
||||
#expect(!model.consoleEntries.isEmpty)
|
||||
model.resetSession()
|
||||
#expect(model.consoleEntries.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,58 @@
|
||||
// ScratchModelResetTests.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 resetSession")
|
||||
@MainActor
|
||||
struct ScratchModelResetTests {
|
||||
|
||||
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), initialText: text)
|
||||
}
|
||||
|
||||
@Test func resetStopsAudioAndClearsDiagnosticsButKeepsBuffer() async {
|
||||
let source: String = "OscSin(freq: 440) * 0.1"
|
||||
let model: LyrebirdScratchModel = makeModel(text: source)
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false) // tracked 1
|
||||
#expect(model.trackedSynthCount == 1)
|
||||
|
||||
model.resetSession()
|
||||
|
||||
#expect(model.trackedSynthCount == 0) // audio stopped
|
||||
#expect(model.diagnostics.isEmpty)
|
||||
// Non-destructive: the user's buffer is preserved.
|
||||
#expect(model.text == source)
|
||||
#expect(model.statusMessage.contains("reset"))
|
||||
}
|
||||
|
||||
@Test func resetLeavesAFreshDirtyBaseline() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false) // .clean
|
||||
model.resetSession()
|
||||
// The placeholder buffer was never run in this fresh session → .dirty.
|
||||
#expect(model.reevalState == .dirty)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,104 @@
|
||||
// ScratchModelRunSelectionTests.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 run selection")
|
||||
@MainActor
|
||||
struct ScratchModelRunSelectionTests {
|
||||
|
||||
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), initialText: text)
|
||||
}
|
||||
|
||||
@Test func hasSelectionReflectsNonWhitespaceSelection() {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
#expect(model.hasSelection == false)
|
||||
model.updateSelection("OscSin(freq: 220) * 0.1")
|
||||
#expect(model.hasSelection)
|
||||
model.updateSelection(" \n ") // whitespace only
|
||||
#expect(model.hasSelection == false)
|
||||
model.updateSelection("")
|
||||
#expect(model.hasSelection == false)
|
||||
}
|
||||
|
||||
@Test func runSelectionWithNoSelectionIsNoOp() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
let ok: Bool = await model.runSelection()
|
||||
#expect(ok == false)
|
||||
#expect(model.trackedSynthCount == 0)
|
||||
}
|
||||
|
||||
@Test func runSelectionAddsToRunningWithoutDisturbingBaseline() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
|
||||
// Whole-buffer run establishes the baseline → clean, one synth.
|
||||
_ = await model.run(additive: false)
|
||||
#expect(model.reevalState == .clean)
|
||||
#expect(model.trackedSynthCount == 1)
|
||||
|
||||
// Run a selected fragment: additive (adds a second synth) and leaves the
|
||||
// whole-buffer baseline intact (buffer still matches the last whole run).
|
||||
model.updateSelection("OscSin(freq: 220) * 0.1")
|
||||
let ok: Bool = await model.runSelection()
|
||||
#expect(ok)
|
||||
#expect(model.trackedSynthCount == 2)
|
||||
#expect(model.reevalState == .clean) // baseline untouched
|
||||
#expect(model.diagnostics.isEmpty)
|
||||
}
|
||||
|
||||
@Test func selectionRunAddsEvenFromADirtyBuffer() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false) // tracked 1, .clean
|
||||
// Dirty the buffer (edited since the last whole run).
|
||||
model.text = "OscSin(freq: 440) * 0.1\n# edited"
|
||||
#expect(model.reevalState == .dirty)
|
||||
|
||||
model.updateSelection("OscSin(freq: 330) * 0.1")
|
||||
_ = await model.runSelection() // additive → tracked 2
|
||||
model.updateSelection("OscSin(freq: 110) * 0.1")
|
||||
_ = await model.runSelection() // additive → tracked 3
|
||||
#expect(model.trackedSynthCount == 3)
|
||||
// The selection runs never replaced, and the buffer stays dirty.
|
||||
#expect(model.reevalState == .dirty)
|
||||
}
|
||||
|
||||
@Test func failedSelectionRunLeavesWholeBufferBadgeUntouched() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false) // .clean
|
||||
#expect(model.reevalState == .clean)
|
||||
|
||||
// A selection with an unknown generator fails to build.
|
||||
model.updateSelection("NotAGenerator(freq: 1)")
|
||||
let ok: Bool = await model.runSelection()
|
||||
#expect(ok == false)
|
||||
#expect(!model.diagnostics.isEmpty)
|
||||
// The whole-buffer badge must stay clean — the buffer itself is fine.
|
||||
#expect(model.reevalState == .clean)
|
||||
#expect(model.statusMessage.hasPrefix("Selection"))
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -38,14 +38,49 @@ struct ScratchTextViewTests {
|
||||
#expect(range == NSRange(location: text.utf16.count, length: 0))
|
||||
}
|
||||
|
||||
/// Mid-identifier (no preceding dot) falls through to the default behavior,
|
||||
/// which covers the whole partial word so it gets replaced on completion.
|
||||
@Test func partialIdentifierUsesDefaultWordRange() {
|
||||
/// Mid-identifier (no preceding dot): the range covers the run of identifier
|
||||
/// characters before the caret, so the partial word gets replaced.
|
||||
@Test func partialIdentifierCoversWordRange() {
|
||||
let tv: ScratchTextView = makeTextView("OscSi", caret: 5)
|
||||
let range: NSRange = tv.rangeForUserCompletion
|
||||
// Default range spans the partial word `OscSi` (length 5 from offset 0).
|
||||
#expect(range == NSRange(location: 0, length: 5))
|
||||
}
|
||||
|
||||
/// Right after an open paren, the range is EMPTY at the caret — an argument
|
||||
/// label (`freq:`) inserts there instead of replacing the receiver
|
||||
/// (`OscSin.Audio(` → erases `OscSin.Audio` bug).
|
||||
@Test func afterOpenParenRangeIsEmptyAtCaret() {
|
||||
let text: String = "OscSin.Audio("
|
||||
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
|
||||
let range: NSRange = tv.rangeForUserCompletion
|
||||
#expect(range == NSRange(location: text.utf16.count, length: 0))
|
||||
}
|
||||
|
||||
/// After a comma + space (next argument position), the range is empty too.
|
||||
@Test func afterCommaSpaceRangeIsEmptyAtCaret() {
|
||||
let text: String = "OscSin.Audio(freq: 440, "
|
||||
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
|
||||
let range: NSRange = tv.rangeForUserCompletion
|
||||
#expect(range == NSRange(location: text.utf16.count, length: 0))
|
||||
}
|
||||
|
||||
/// A partial argument label inside parens replaces just that partial word,
|
||||
/// not the receiver expression.
|
||||
@Test func partialArgLabelCoversOnlyThePartial() {
|
||||
let text: String = "OscSin.Audio(fr"
|
||||
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
|
||||
let range: NSRange = tv.rangeForUserCompletion
|
||||
// `fr` starts at offset 13 (after `OscSin.Audio(`), length 2.
|
||||
#expect(range == NSRange(location: 13, length: 2))
|
||||
}
|
||||
|
||||
/// Underscore is an identifier character, so a leading-underscore partial is
|
||||
/// covered whole.
|
||||
@Test func underscoreIsIdentifierChar() {
|
||||
let tv: ScratchTextView = makeTextView("_foo", caret: 4)
|
||||
let range: NSRange = tv.rangeForUserCompletion
|
||||
#expect(range == NSRange(location: 0, length: 4))
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -122,6 +122,8 @@ The REPL is text-only and works from any project that depends on Lyrebird; the s
|
||||
|
||||
**Read [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md)** — it covers the eight demo projects, how to open the workspace, where to add synthesizers, and the gotchas that will bite you.
|
||||
|
||||
**New to Swift itself?** [`docs/learning-swift/`](docs/learning-swift/README.md) is a four-part intro to Swift written for Lyrebird users (not iOS developers): a Hello-World tone, Swift basics and best practices, the type system and functional style applied to synthesis graphs, and Xcode / packages / Debug-vs-Release / debugging.
|
||||
|
||||
---
|
||||
|
||||
## Requirements
|
||||
@@ -337,6 +339,7 @@ swift package --disable-sandbox preview-documentation --target Lyrebird
|
||||
| Topic | Doc |
|
||||
|---|---|
|
||||
| **Start here / demo projects** | [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) |
|
||||
| **New to Swift? Intro for Lyrebird users** | [`docs/learning-swift/README.md`](docs/learning-swift/README.md) |
|
||||
| **What's new / release notes** | [`RELEASES.md`](RELEASES.md) |
|
||||
| Engine setup and Core Audio | `docs/engine/synthesis-engine.md` |
|
||||
| Bus memory / In / Out | `docs/engine/bus-system.md` |
|
||||
|
||||
+114
@@ -7,6 +7,120 @@ functionality in a backward-compatible way.
|
||||
|
||||
---
|
||||
|
||||
## 1.4.2 — Live-coding: Run Selection + graceful slot release
|
||||
|
||||
A minor release. Backward-compatible — additive conveniences to the (macOS-only)
|
||||
live-coding editor that make per-fragment evaluation and voice lifecycle feel
|
||||
like a proper live-coding environment. No changes to existing public API.
|
||||
|
||||
### New — Run Selection (⌘E)
|
||||
|
||||
Evaluate just the **highlighted text** and *add* it to whatever is already
|
||||
playing — always additively, never a replace. It leaves the rest of the buffer
|
||||
and the whole-buffer re-evaluation baseline (the clean/dirty badge still reflects
|
||||
your last full run) untouched. This is the live-coding "evaluate this line/region,
|
||||
keep going" gesture: audition a single voice, layer it in, iterate. Works in both
|
||||
Swift and Graph DSL modes; no-op with no selection. ⌘↩ / ⌘⇧↩ (whole buffer) are
|
||||
unchanged.
|
||||
|
||||
### New — Start a voice, release it later (`context.release(slot:)`)
|
||||
|
||||
Named slots are the persistent **handle** across evaluations — the slot *name* is
|
||||
your reference (Swift `let`/`var` bindings can't carry from one snippet to the
|
||||
next, since each ⌘↩/⌘E is a separately-compiled unit). Pair that with Run
|
||||
Selection to start a voice in one evaluation and let it go in another:
|
||||
|
||||
```swift
|
||||
// ⌘E this line — start a persistent, gated voice named "pad":
|
||||
context.play(slot: "pad") { EnvGen(gate: 1, /* free-on-done */) * OscSaw.Audio(freq: 110) }
|
||||
|
||||
// …later, ⌘E this line — graceful release: the envelope tails out, then frees:
|
||||
context.release(slot: "pad")
|
||||
```
|
||||
|
||||
- `context.release(slot:)` triggers the voice's envelope **release** phase and
|
||||
frees the name; the voice self-frees via its done-action (and, as a safety net,
|
||||
stays reclaimable by **Clear Synths** if it never does).
|
||||
- `context.free(slot:)` is the **immediate** hard stop — the counterpart, no tail.
|
||||
|
||||
### New — Engine panel (scope + status)
|
||||
|
||||
A panel at the bottom of the scratch window gives an always-on view of the
|
||||
running engine: a live dual-channel **oscilloscope** of the output (fed by a
|
||||
`ScopeCapture` the session attaches to the output buses), plus **CPU
|
||||
average/peak** meter bars and **synth / group / snippet** counts.
|
||||
|
||||
### New — Reset Session + Restart to Reclaim Memory
|
||||
|
||||
Two Run-menu commands for the by-design snippet-dylib cost:
|
||||
|
||||
- **Reset Session** — an in-process, *non-destructive* reset: stops all snippet
|
||||
audio, shuts down the code-completion server (freeing its subprocess and temp
|
||||
files), and clears diagnostics. Your buffer is untouched.
|
||||
- **Restart to Reclaim Memory…** — relaunches the app (with a confirmation), the
|
||||
only way to actually free the mapped snippet dylibs, which cannot be unloaded
|
||||
in-process.
|
||||
|
||||
### New — Console panel
|
||||
|
||||
An always-open panel down the right side logs everything: snippet
|
||||
`context.reportMessage(_:)` output (the live-coding `print`), compile / Graph DSL
|
||||
**errors** with their `line:col`, and a one-line notice per run — oldest first,
|
||||
auto-scrolled, with a **Clear** button. Errors moved here from the old transient
|
||||
bottom strip so they stay visible while you fix them.
|
||||
|
||||
### Faster typing
|
||||
|
||||
Cut the per-keystroke cost in the editor: syntax highlighting is debounced
|
||||
(coalesced after a brief pause instead of a full-buffer re-tokenize on every
|
||||
key), `updateNSView` fast-paths a pure text change, and redundant `@Published`
|
||||
republishes (selection, re-eval state) are elided.
|
||||
|
||||
### Changed — code completion is now manual (Esc / F5)
|
||||
|
||||
Completion no longer auto-opens on `.`. The auto-trigger ambushed typing — after
|
||||
`Pan2.` the popup opened and couldn't be dismissed by deleting, trapping the
|
||||
caret until a candidate was picked. Invoke completion deliberately with **Esc**
|
||||
(or **F5**); a member request after a dot still resolves. Wider default scratch
|
||||
window too (75% of the visible screen width).
|
||||
|
||||
---
|
||||
|
||||
## 1.4.1 — "Learning Swift for Lyrebird" intro guide
|
||||
|
||||
A documentation-only release, continuing the doc improvements begun in 1.3. No
|
||||
source or public-API changes. Adds a four-part introduction to Swift written
|
||||
specifically for Lyrebird users coming from SuperCollider, Max/MSP, Csound, and
|
||||
similar tools — people who want just enough Swift to be productive without
|
||||
wading through iOS-development tutorials.
|
||||
|
||||
### New — `docs/learning-swift/`
|
||||
|
||||
Four short guides, meant to be read in order, each grounded in audio examples
|
||||
rather than app-building:
|
||||
|
||||
1. **Hello, World** — from a one-line `print` to a working 440 Hz tone, every
|
||||
line of a Lyrebird program explained (engine → synthesizer → generator graph
|
||||
→ output bus).
|
||||
2. **Swift Basics & Best Practices** — `let`/`var`, the scalar types, optionals
|
||||
(and why Lyrebird forbids force-unwrap `!`), control flow, functions, error
|
||||
handling, and `struct` vs `class`.
|
||||
3. **Types & Functional Programming** — enums, protocols, operator overloading,
|
||||
closures, and `map`/`filter`/`reduce` applied to building synthesis graphs;
|
||||
`expand` as `map` for multichannel generators.
|
||||
4. **Xcode, Packages & Debugging** — Xcode vs. SwiftPM, adding Lyrebird as a
|
||||
package, **Debug vs. Release** build configurations (and why Debug audio can
|
||||
glitch), and breakpoints — including the rule to never break or `print` on
|
||||
the real-time render thread, using `debugTap`/`debugTag` instead.
|
||||
|
||||
Throughout, examples use explicit **type annotations** on every binding — the
|
||||
same practice the Lyrebird codebase enforces — for readability and faster
|
||||
compilation on large, generic audio-graph expressions.
|
||||
|
||||
Linked from `README.md` and `LYREBIRD_START_HERE.md` for discovery.
|
||||
|
||||
---
|
||||
|
||||
## 1.4.0 — Live-coding scratch editor, interpreted Graph DSL, `ClosureSynthesizer` + `SampleLoop`
|
||||
|
||||
A minor release. Fully backward-compatible — no changes to existing public API.
|
||||
|
||||
@@ -30,6 +30,9 @@ ALLOW_DIRTY=0
|
||||
EXCLUSIONS=(
|
||||
"legacy"
|
||||
"PLAN.md"
|
||||
"DOC_UPDATE_PLAN.md"
|
||||
"docs/00-working-order.md"
|
||||
"docs/01-completed-working-order.md"
|
||||
".claude"
|
||||
".githooks"
|
||||
".swiftpm"
|
||||
|
||||
@@ -23,6 +23,9 @@ Then it strips the maintainer-only paths that are tracked in dev but must **not*
|
||||
|---|---|
|
||||
| `legacy/` | old pre-modernization reference code |
|
||||
| `PLAN.md` | private planning doc |
|
||||
| `DOC_UPDATE_PLAN.md` | private planning doc |
|
||||
| `docs/00-working-order.md` | maintainer phase-planning doc (what to build next) |
|
||||
| `docs/01-completed-working-order.md` | maintainer phase-planning doc (completed phases) |
|
||||
| `.claude/` | agent working-copy mirror (release ships `claude/` installer source only) |
|
||||
| `.githooks/` | dev-only pre-commit hooks |
|
||||
| `.swiftpm/` | local Xcode package state |
|
||||
@@ -31,8 +34,9 @@ The sync uses `rsync -a -c --delete` (checksum-based, so only real content diffe
|
||||
transfer; `--delete` clears stale files + Finder cruft on the release side). A moo-URL guard
|
||||
on the release remote prevents `--apply` from ever touching the wrong directory.
|
||||
|
||||
`docs/` (including `00-working-order.md` / `01-completed-working-order.md`) **does** ship —
|
||||
only top-level `PLAN.md` is excluded from the planning material.
|
||||
Most of `docs/` ships. The two phase-planning docs (`docs/00-working-order.md`,
|
||||
`docs/01-completed-working-order.md`) are **excluded** — they're maintainer-internal and
|
||||
mean nothing to consumers — along with the top-level `PLAN.md` / `DOC_UPDATE_PLAN.md`.
|
||||
|
||||
## Steps
|
||||
|
||||
|
||||
@@ -1,282 +0,0 @@
|
||||
# Working Order
|
||||
|
||||
Phases are ordered by dependency. Each phase should have tests before moving on.
|
||||
|
||||
Completed phases (1–34, 36–95, 96a, 97, 99, 101, 102a, 102b, 103, 104a, 104b, 104c, 104d, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 159, 160, 161, 162, 163, 170, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 196, 197, 198, 88b, MCE-A, MCE-B, 85.5, 86.75a, 86.75b, LyrebirdBufferUpdates, 77-review-cleanup, 71b, 49b, 46, iOS-1–iOS-4, Score Phases A–D, 204, 222, GC-1–GC-9B, GC-11, GC-12, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, LC-1, LC-2, LC-3, LC-4, LC-5, LC-6, LC-7) are archived in `docs/01-completed-working-order.md`.
|
||||
|
||||
## Phase Completion Checklist
|
||||
|
||||
Before merging any phase branch to `main`:
|
||||
|
||||
1. All tests pass (`swift test --no-parallel` — the parallel runner has a known SIGABRT teardown flake)
|
||||
2. If the phase touched a **public signature**, `.docc`, or doc comments: `bash scripts/check-docc.sh` (no new DocC warnings) **and** `bash scripts/check-doc-snippets.sh` (recorded doc examples still compile)
|
||||
3. If the phase touched **`SynthesizerBase` / `Synthesizer` actor isolation**: `bash scripts/check-swift6-consumer.sh` — the test suite cannot catch isolation regressions (it doesn't build under `-default-isolation MainActor`)
|
||||
4. Run `/lyrebird_review` — no blocking findings
|
||||
5. Fix any blocking issues found; re-run `/lyrebird_review` until clean
|
||||
6. Merge to `main` with a `--no-ff` merge commit
|
||||
7. `/lyrebird_review` updates `MEMORY.md` automatically on a clean pass
|
||||
8. Move the completed phase section from this file into `docs/01-completed-working-order.md` (append at the bottom) and update the summary table below
|
||||
|
||||
## Generator Authoring Rules
|
||||
|
||||
See `docs/protocols/writing-generators.md` for the full guide. Quick checklist:
|
||||
|
||||
- No RT allocation in `_computeSamples` — pre-allocate in `init`
|
||||
- Open `_computeSamples` with `_checkCount(count)` (inherited from `GeneratorBase`)
|
||||
- Inherit `GeneratorBase` — do NOT redeclare `_segmentSerial`/`_cachedResult`/`_subBlockBuffer`/`_result`
|
||||
- `ControlGenerator.Control.init` must call `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels:N)` for multi-channel)
|
||||
- Route `floatValue` through `calculatedSamples(blockSize)` for AudioGenerator; return scalar target directly for ControlGenerator
|
||||
- Add `calculatedSamples` bypass override if the generator has per-audio-block state (phase accumulators, gain smoothers, buffer positions) — see Out.Control as the canonical pattern
|
||||
- Apply `denormalsToZero()` to all IIR feedback state after each write
|
||||
- Power-of-two table sizes enforced by `precondition`
|
||||
|
||||
---
|
||||
|
||||
## Completed Phases (summary)
|
||||
|
||||
Full details in `docs/01-completed-working-order.md`.
|
||||
|
||||
| Phase | Title | Tests at completion |
|
||||
|-------|-------|---------------------|
|
||||
| 1 | SynthesisEngine + Core Audio | 28 |
|
||||
| 1b | Scheduling + NRT Rendering | — |
|
||||
| 2 | Bus System | — |
|
||||
| 3 | Generator Protocol | — |
|
||||
| 4 | In / Out Generators | — |
|
||||
| 5 | Synthesizer Protocol + Node Tree | — |
|
||||
| 6 | Parameter System | 192 |
|
||||
| 7 | REPL + LineNoise | — |
|
||||
| 8 | Built-in Generator Stdlib | 319 |
|
||||
| 8b | Buffer System + Shared Tables | 345 |
|
||||
| 9 | lyrebird CLI + Project System | 416 |
|
||||
| 10 | Swift Testing Suite | 447 |
|
||||
| 11 | Interpret-then-Compile Polish | 447 |
|
||||
| 12 | GUI System (LyrebirdUI) | 474 |
|
||||
| 13 | Generator Fan-out / Shared Signal Semantics | 483 |
|
||||
| 14 | Denormal Handling | 494 |
|
||||
| 15 | AIFF / WAV File I/O for LyrebirdBuffer | 511 |
|
||||
| 16 | Multichannel `LyrebirdBuffer` | 527 |
|
||||
| 17 | Table-Lookup Generator Polish | 540 |
|
||||
| 18 | Generator Authoring Guide | 540 |
|
||||
| 19 | Bus / Output Ergonomics | 549 |
|
||||
| 20 | LyrebirdBufferFileIO Channel-Count Validation | 556 |
|
||||
| — | Operator overloads + ConstantGeneratorInput | 570 |
|
||||
| 21 | Sample Rate Mismatch Detection | 671 |
|
||||
| 22 | Audio-Rate Input Modulation (FM / AM / PM) | 593 |
|
||||
| 23 | Full RBJ Cookbook Filters | 671 |
|
||||
| 24 | Butterworth Filters | 692 |
|
||||
| 25 | Resonating, Comb, and Allpass Filters | 752 |
|
||||
| 26 | Multi-Channel Expansion (MCE) | 671 |
|
||||
| 27 | Control-Rate Generator Variants | 805 |
|
||||
| 28 | `ParameterNode` + `@LiveParam` | 826 |
|
||||
| 29 | RecordBuf + PlayBuf (Audio + Control variants) | 872 | ← archived |
|
||||
| 29b | PlayBuf Reverse Playback | 879 | ← archived |
|
||||
| 30 | LyrebirdRoutine + LyrebirdTask + Pattern | 905 |
|
||||
| 31 | FFT / IFFT Spectral Infrastructure | 930 |
|
||||
| 32 | Granular Synthesis (BufferGrain, SineGrain, FMGrain, InputGrain) | 973 |
|
||||
| 33 | Panning Suite (PanN, Pan4, AmbiEncoder1, AmbiDecoder1) | 1016 |
|
||||
| 33b | Accelerate / vDSP Optimization | 1019 |
|
||||
| 33b-fixes | RT safety + vDSP correctness fixes | 1038 |
|
||||
| — | RoutineContext beat API | 1046 |
|
||||
| — | EnvelopeGen.Control + _Base fixes | 1060 |
|
||||
| 34 | Multi-Core Support (ParallelGroup) | 1078 |
|
||||
| 36 | LyrebirdClock | 1092 |
|
||||
| 37 | MIDI (Language-Side) | 1146 |
|
||||
| 38 | OSC (Language-Side) | 1146 |
|
||||
| 39 | Demand-Rate Generators | 1174 |
|
||||
| 40 | Engine CPU Statistics + LyrebirdStatusView | 1180 |
|
||||
| 41 | Stereo Scope + Pan (ScopeCapture / LyrebirdScopeView) | 1187 |
|
||||
| 42 | TriggerListener (RT→Language Trigger Infrastructure) | — |
|
||||
| 43 | SendTrigger Generators + NRT Support | 1238 |
|
||||
| — | Envelope.releaseNode + EnvelopeGen.gate (gated ADSR hold) | 1264 |
|
||||
| — | Envelope.loopNode (single-segment gate-controlled loop; _released flag) | 1271 |
|
||||
| — | EnvelopeCurve renames (.sin→.sine/.exp→.exponential); digital osc for sine/welch | 1281 |
|
||||
| — | EnvelopePoll.Audio/Control — stateless valueAtTime lookup; audio-rate time input | 1293 |
|
||||
| 44 | Runtime Envelope Swap (EnvelopePacket + setEnvelope) | 1300 |
|
||||
| 45 | LyrebirdEnvelopeView (SwiftUI envelope shape plotter) | 1320 |
|
||||
| iOS-1 | iOSAudioDriver (RemoteIO); CoreAudioDriver `#if os(macOS)` guard | 1320 |
|
||||
| iOS-2 | Package.swift `.iOS(.v18)`; AVFoundation linker; DenormalUtils verified | 1320 |
|
||||
| iOS-3 | LyrebirdWindow `#if os(macOS)`; PlatformColors for ParameterKnob/XY | 1320 |
|
||||
| iOS-4 | LyrebirdiOSDemo Xcode project; workspace entry; correct session rate init | 1320 |
|
||||
| — | LyrebirdMusicMath: free functions, midiToHz/hzToMidi, dB/amp/power, linToExp, equalPowerFade | 1369 |
|
||||
| 47 | Dynamics Generators (AmplitudeFollower, FreqTracker, LookAheadLimiter, Compressor, Expander) | 1404 |
|
||||
| 48 | ChannelSelect — inline channel extraction ([n] subscript on all generators) | 1420 |
|
||||
| 49 | Bus Allocator — AudioBus/ControlBus value types + BusAllocator on SynthesisEngine | 1434 |
|
||||
| 49b | In.Audio / In.Control multi-channel — static channels param, AudioBus passthrough | 1444 |
|
||||
| 50 | Group Semantics + Node Positioning — release/free lifecycle, NodePosition, addBefore/addAfter | 1472 |
|
||||
| 51 | DiskIn.Audio + DiskOut.Audio — streaming soundfile I/O (double-buffer + ring-buffer) | 1472 |
|
||||
| 46 | NRTDriver soundfile input — inputURL + inputStartOffset; ExtAudioFile SR conversion | 1472 |
|
||||
| 52 | Math generators — Tanh/Pow/Clip/Fold/Wrap/SoftClip/LinLin/LinExp/ExpLin/ExpExp + unary/binary (Abs/Sign/Floor/Ceil/Round/Sqrt/Reciprocal/Log/Exp/Min/Max); Bipolar+UnipolarMappingGenerator | 1547 |
|
||||
| 53 | FreeVerb — stereo reverb (Jezar Freeverb); 8 comb + 4 allpass per channel; .left/.right aliases; DocC Reverbs topic | 1555 |
|
||||
| 54 | GVerb — Griesinger algorithmic stereo reverb (SC-faithful rewrite); FDN+Hadamard 4-line network; tap-delay early reflections; 3+3 post-sum allpass diffusers; dryLevel param; .left/.right aliases | 2507 |
|
||||
| — | Control-rate sub-blocking (controlRateConsiderations): GeneratorBase, ControlGenerator.calculatedSamples sub-block loop, 11 .Control bypass overrides, phase-advancement uses count | 1618 |
|
||||
| — | controlRateConsiderations fast-follow: _swapSerial gate prevents mid-block EnvelopePacket drain in sub-block mode; defensive channel zero-fill; fanOutCache + subBlockSwap tests; SynthesisEngine driverSuggestion capture; doc callouts | 1619 |
|
||||
| 55 | Noise Family (Spectral-Colour + Event): xorshift64NextRaw split; PinkNoise/BrownNoise/GrayNoise/ClipNoise/Dust/Dust2 (Audio+Control each); bypass guards on all full-bandwidth Control variants | 1715 |
|
||||
| 56 | Noise Family (Chaotic + Smooth): Crackle (2-pole chaotic map, bypass guard) + LFCurveNoise (SC LFNoise2 parabolic interp); floatValue fan-out cache fix; PinkNoise b5 sign fix; GrayNoise bitPattern fix | 1747 |
|
||||
| 57 | Distribution Library + Standalone Distribution Noise Generators: DistributionKind enum; DistributionSampling math (Marsaglia-Tsang gamma, Box-Muller gauss, Knuth Poisson, etc.); UniformNoise/LpRandNoise/HpRandNoise/MeanRandNoise/GaussNoise/ExpRandNoise/ExponentialNoise/GammaNoise/LaplaceNoise/ALaplaceNoise/HcosNoise/LogisticNoise/PoissonNoise/ArcsinNoise/BetaRandNoise/CauchyNoise (Audio+Control each) | 1877 |
|
||||
| 58 | TemporalStream language side: TemporalParameter (.value/.envelope/.closure); TemporalAlgorithm protocol; TemporalStream (wall-clock + beat-clock timing); TemporalSequence/TemporalRandomPick/TemporalTendency/TemporalBrownian/TemporalClosure algorithms; 163 tests | 1910 |
|
||||
| — | DSeq→DSequence, DRand→DRandom rename for verbosity | 1910 |
|
||||
| 59 | TimedDemand synthesis side: RTTemporalParameter (Sendable, no closure); TimedDemandGenerator protocol; TimedDemand.Audio/Control (sample-accurate currentTime+i elapsed); DTemporalTendency (16 distributions); DTemporalBrownian (RT walk, auto-centring) | 1950 |
|
||||
| 60 | Distribution Preview: LyrebirdScatterView (Canvas scatter plot, degenerate-range guard); DemandGenerator.samples(count:); TimedDemandGenerator.samples(count:timespan:); TemporalStream.collect(_:); TemporalDemand.md Previewing Distributions section | 1959 |
|
||||
| 61 | PitchShift.Audio — granular live-input pitch shifter; circular capture buffer; auto hop management; pitchRatio [0.25, 4.0]; mono out + MCE | 1978 |
|
||||
| 62 | SpectralPitchShift — phase-vocoder SpectralProcessor; true-frequency bin tracking; magnitude remapping by ratio; synthesis phase accumulator; out-of-range bins zeroed | 1978 |
|
||||
| 63 | Granular Modulation Upgrade + TimeStretch — BufferGrain/InputGrain/SineGrain/FMGrain ValidGeneratorInput promotion; rate→pitchRatio rename; TimeStretch.Audio fixed-hop granular time-stretcher | 1995 |
|
||||
| — | SineBufferGrain→SineGrain, FMBufferGrain→FMGrain, InputBufferGrain→InputGrain rename (drop "Buf" suffix from non-buffer granular generators) | 1995 |
|
||||
| 64 | Spectral Frame Buffer — SpectralFrameBuffer (framesWritten/interpolatePhases/trimmed) + SpectralRecordBuffer + SpectralPlayBuffer (startPos) + SpectralBufferRead (normalized position) + .lbsf file I/O | 2031 |
|
||||
| 65 | PlayBuf→PlayBuffer + RecordBuf→RecordBuffer rename; @available deprecated typealiases; docs + agent file updated | 2031 |
|
||||
| 66 | Buffer Metadata + Duration Helpers | 2040 |
|
||||
| 67 | BufferRead — normalized-position random-access buffer reader; Audio+Control; multi-channel; lyrebirdBufferRead helper; GeneratorEnum | 2053 |
|
||||
| 68 | TimeStretch Multi-Channel + Remove Pan — N-channel output matching buffer.channelCount; pan/panSpread removed | 2074 |
|
||||
| 69 | LyrebirdBuffer Wavetable Generation Utilities — fill(partials:), fillChebyshev, fillWindow, fillWaveshaper, fillBandLimited, fillPartials, fillInharmonicPartials, WavetableSet | 2119 |
|
||||
| 70 | Ring Modulator Variants — Ring1/Ring2/Ring3/Ring4 Audio+Control binary math generators; SC AM/RM family | 2127 |
|
||||
| 71 | Band-Limited Oscillators (BLEP) — OscSawtooth / OscSquare / OscTriangle / OscDutyCycle Audio+Control; polyBLEP/BLAMP correction; audio-rate PWM | 2174 |
|
||||
| 71b | Non-Band-Limited LFO Oscillators — LFSawtooth / LFSquare / LFTriangle / LFDutyCycle Audio+Control; raw piecewise math; audio-rate PWM on LFDutyCycle | 2232 |
|
||||
| 72 | Euclidean Rhythm + Markov Chain Patterns — euclideanRhythm(pulses:steps:rotation:)->Pattern<Bool>; TemporalMarkov new TemporalAlgorithm | 2267 |
|
||||
| 73 | Jitter / Triggered Random Generators — TriggeredRandom.Control + Jitter.Control | 2289 |
|
||||
| 74 | Gendy Stochastic Synthesis — Gendy1/2/3 Audio+Control; linear/cubic/fixed-dur breakpoint state machines; all 16 DistributionKind variants | 2364 |
|
||||
| 75 | Spectral Feature Extraction — SpectralCentroid/Flatness/Spread/Flux/Entropy/Rolloff (Control-only, bypass sub-block loop) | 2399 |
|
||||
| 75b | Live Parameter Refactor — `@LiveParam` / `@UIParam` Mirror auto-registration; `ParameterNode` + `UIParamNode` → `ControlGenerator`; `updateParameter` direct atomic; deleted `declareParameter` × 3, `ControlParameter`, `ConstantParameter`, `String: ValidGeneratorInput`, SPSC param queue | 2377 |
|
||||
| 76 | State Variable Filter (SVF) — Chamberlin recurrence, 4-channel output (LP/HP/BP/Notch) from one coefficient set; `freq` + `q` ValidGeneratorInput; SVF.Control bypasses sub-block loop (audio-input IIR must advance once per block) | 2403 |
|
||||
| 77 | WavetableMorph Oscillator — Audio + Control; `[LyrebirdBuffer]` + `position: ValidGeneratorInput` [0, N-1] per-sample linear interp between adjacent tables; freq + phase as ValidGeneratorInput; TableInterpolation .none/.linear/.cubic for inner reads | 2426 |
|
||||
| 77-review-cleanup | Scalar `ValidGeneratorInput` intra-block ramp fixes — `_xIsGenerator` guards + per-sample paths in pan family / dynamics / LF*Noise.Audio / DelayLineFeedback; new `lastGeneratorSampleOrFloat` helper; WavetableMorph dead `_tableCountFloat` removed; rmsValue test helper extracted | 2448 |
|
||||
| 78 | Karplus-Strong / Waveguide String — `KarplusStrong.Audio` (trigger-based) + `GatedKarplusStrong.Audio` (continuous gate); `exciter` + `trigger`/`gate` + `freq` + `feedback` + `coef` (one-pole, SC formula) + `sampleRate` + `maxDelayTime`; fractional delay with linear interp; `_refillRemaining` gradual fill; Audio-only | 2471 |
|
||||
| 79 | Flanger / Chorus / Phaser — `Flanger.Audio` (sine-LFO modulated delay + feedback), `Chorus.Audio` (2-tap stereo, LFOs 180° apart, `.left`/`.right`), `Phaser.Audio` (4/6/8 cascaded first-order AP stages, LFO sweeps coefficient); all Audio-only, ValidGeneratorInput for all mod params | 2506 |
|
||||
| 80 | FrequencyShifter — `FrequencyShifter.Audio` SSB Weaver method; two 4-stage IIR all-pass chains (90° Hilbert approx); quadrature oscillator at `shiftHz`; inharmonic 2-ch output (`.upper`/`.lower`); `shiftHz: ValidGeneratorInput`; Audio-only | 2520 |
|
||||
| 81 | Polyphonic Voice Allocator — `VoicePool<S: SynthesizerBase>`; noteOn/noteOff/allNotesOff; `.oldest`/`.roundRobin`/`.quietest`/`.lowestAmplitude` steal strategies; `.quietest` reads `@LiveParam` amp via Mirror, falls back to `.oldest` | 2541 |
|
||||
| 82 | Step Sequencer — `StepSequencer` language-side beat sequencer driven by `LyrebirdClock`; `SequencerStep` with pitch/velocity/gate/probability/duration/parameterLocks; rests; NSLock-protected callbacks; `Atomic<Int>` currentStep; idle-burst-fire prevention | 2563 |
|
||||
| 83 | AdditiveSynthesizer — `AdditiveSynthesizer.Audio` resynthesizes `SpectralFrameBuffer` as N sines via vDSP (vadd phases + vvsinf + dotpr); position `ValidGeneratorInput`; maxPartials cap; anti-aliasing; lazy phaseIncrement init | 2583 |
|
||||
| 84 | FormantGrain (FOF) — `FormantGrain.Audio` IRCAM CHANT FOF formant-grain synthesizer; sine² rise + exponential decay; per-pulse octaviation sign-flip; pool-overflow steal-oldest policy; glottalFreq clamped to ≤ sampleRate; unconditional phase wrap via truncatingRemainder; new `Lyrebird.docc/Generators/GranularSynthesis.md` topic covering the family | 2597 |
|
||||
| 85 | Spectrum / Spectrogram View — `SpectrumCapture` (SpectralProcessor, ping-pong double-buffer) + `LyrebirdSpectrumView` (Canvas log-frequency X / dB Y, optional waterfall spectrogram) | 2606 |
|
||||
| 85.5 | Smoothing Filters — `Lag`/`LagUpDown`/`Lag2`/`Lag2UpDown`/`Decay`/`Decay2`/`LeakDC` (Audio+Control each); shared `lagCoeff()` helper; Control variants use control rate for coefficient | 2677 |
|
||||
| 86.75a | Classic SC PV ports — `SpectralPartialFilter` / `SpectralNoiseFilter` (`ClassifierMode.frequency`/`.phase` multi-frame stability classifiers, ring history with warmup), `SpectralMagnitudeMap` (`LyrebirdBuffer` transfer function on normalized mags), `SpectralHarmonicEnhance` (1/i-falloff harmonic series, Double index arithmetic for large fftSize). Atomic<Float>/<Bool> params, no shared base class | 2694 |
|
||||
| LyrebirdBufferUpdates | `LyrebirdBuffer.setValue(_:at:)` / `setValue(_:frame:channel:)` / `setRangeValues(_:startingAt:)` — live language-side parameter writes safe under concurrent block-rate RT reads. NSLock serialises lang writers; RT snapshots once per block, relies on hw-atomic 8-byte aligned `Double` stores. `invalidate()` takes the same lock | 2705 |
|
||||
| 86.75b | Classic SC PV ports — `SpectralBinDelay` (per-bin delay + feedback ring; `LyrebirdBuffer` per-bin parameter snapshot per hop), `SpectralCrossMap` (dual-FFT magnitude masking via new `SpectralProcessor2` protocol; bandpass / bandreject continuous mode; freeze hold), `LyrebirdUI.MultiSlider` (N-column vertical slider row writing into a `LyrebirdBuffer`) | 2720 |
|
||||
| 87 | `ResonatorBank.Audio` — Klank-style parallel two-pole (Ringz) resonator bank driven from a 3-channel `LyrebirdBuffer` of `[freq, decay, amp]` triplets. Coefficients recomputed once per audio block; per-sample inner loop vectorised across the bank via `vDSP_vsmulD`/`vmulD`/`vsubD` + `vDSP_sveD`. Audio-only; mono summed output | 2783 |
|
||||
| MCE-A | Channel-aware `BinaryOpGenerator` + `outputChannelCount` on Generator protocol — `+ - * /` between any operands now respects channel shape: `1×N`/`N×1` mono-broadcast, `N×N` element-wise, `N×M` with both > 1 and N ≠ M traps at init. ~17 multi-row generators override `outputChannelCount`. `mul:`/`add:` channel-0-only asymmetry preserved and documented loudly | 2803 |
|
||||
| MCE-B | `GeneratorArray op N-row-generator` precondition trap — element-wise GeneratorArray operators now refuse multi-row other operand (silent-drop fix); routed through `_generatorArrayCheckOtherOperandMono` helper. `GeneratorArray.init` left permissive (existing AmbiDecoder1 patterns rely on row-0-only silent-drop) | 2804 |
|
||||
| 88 | `VectorOscillator.Audio` — 4-corner XY bilinear-blend wavetable oscillator; freq/x/y/phase all ValidGeneratorInput. Shared `OscillatorTableReadHelpers.swift` (per-mode `oscillatorTableReadNone/Linear/Cubic` + `oscillatorTableRead` dispatcher) replaces fileprivate copies in OscTable + WavetableMorph; FP-boundary-safe `% tableSize` on base index. Silence-path `_mulAdd.applyIfNeeded` propagated to OscTable.Audio + WavetableMorph.Audio + VectorOscillator.Audio. Audio-only; .Control + GeneratorEnum + UI demo deferred to Phase 88b | 2828 |
|
||||
| 88b | `VectorOscillator.Control` (matches WavetableMorph.Control semantics — Generator inputs read first sample, ramped output via `fillRampedResult`, `_setupSubBlockBuffer()`) + `GeneratorEnum` conformance + `VectorOscillatorUI` demo (macOS + iOS): synthesizer with `@UIParam x/y/frequency/amplitude` and four built-in wavetables (sine, 16-partial saw, triangle, Hanning), `VectorOscillatorView` using existing `LyrebirdUI.ParameterXY` for X/Y, `AppDelegate` switched to `enum Demo { case vector, binDelay, sineTone }` selector defaulted to `.vector` | 2837 |
|
||||
| 89 | `SpatialDistance.Audio` — physically-plausible source-distance model: `1/distance` amplitude (clamped at `referenceDistance`), one-pole air-absorption lowpass with cutoff ∝ `(referenceDistance/distance)²`, velocity-driven Doppler via fractional read-rate `(1 − velocity/speedOfSound)` clamped to `[0.25, 4.0]`. All params `ValidGeneratorInput`. Audio-only (no GeneratorEnum); circular delay buffer pre-allocated from `maxDelayTime`; one-entry cutoff cache skips `exp()` for scalar distance | 2849 |
|
||||
| 89.5 | `SpringReverb.Audio` (Schroeder spring tank — 8 cascaded all-pass dispersion stages in feedback loop with one-pole HF damping; mono-out by default, optional 2-tank stereo via `stereo: Bool` flag with detuned right-tank all-pass lengths) + `PlateReverb.Audio` (Dattorro 1997 figure-of-eight EMT 140 model — pre-delay → bandwidth LP → 4 input diffusers → cross-coupled tank with modulated AP + delay + damping + decay + AP + delay; native stereo mono-in/2-row out, `.left`/`.right` aliases, 7 Dattorro Table 1 taps per channel scaled from 29761 Hz reference). Both Audio-only, no `.Control`, no GeneratorEnum. All Dattorro/Schroeder coefficients in file-private named constants. `denormalsToZero` on every IIR feedback state write | 2872 |
|
||||
| 90 | STK Instrument Models — `BowedString.Audio` (Smith/Cook split-waveguide, two delay lines + bridge LP + Cook friction table), `Flute.Audio` (Cook slide flute, bore+jet delay lines + cubic jet nonlinearity + breath noise), `Clarinet.Audio` (Cook single-reed cylindrical bore, half-wavelength delay + sign-inverted reflection + reed table + breath noise). All Audio-only, no `.Control`, no GeneratorEnum (consistent with Phases 78–80 precedent). `xorshift64Next` shared PRNG for Flute/Clarinet. `denormalsToZero` on every delay write. `PhysicalModels.md` DocC topic. | 2902 |
|
||||
| 91 | Oversampling primitives — `HalfbandUpsampler2x` / `HalfbandDownsampler2x` (polyphase 2×) + `HalfbandUpsampler4x` / `HalfbandDownsampler4x` (cascaded 4×) as RT-safe public value types in `Sources/Lyrebird/Oversampling/`. Shared 23-tap symmetric Type-1 linear-phase Hamming-windowed sinc halfband FIR (`HalfbandFIR.swift`); centre tap held at exactly `0.5`, six folded paired taps normalised so total filter DC gain = `1.0` exactly; group delay 11 samples at upsampled rate. All state pre-allocated in `init()`; `process(_:)` / `reset()` allocation-free. New `Oversampling.md` DocC topic. Replaces the original "wrapper Generator" framing — sub-rate child Generators would break bus / fan-out cache invariants and the helper-struct shape is what Phase 92 Moog ladder actually wants. | 2921 |
|
||||
| 92 | `MoogLadder.Audio` — Huovilainen-style 4-pole resonant lowpass with per-stage `tanh` saturation, internal 2× oversampling via Phase 91 `HalfbandUpsampler2x` + `HalfbandDownsampler2x`, and SC-style half-sample feedback compensation (`xfb = x − k·(y4 − 0.5·x)`). Self-oscillates near `resonance = 1.0`, clamped to `moogLadderMaxResonance = 1.4`; cutoff coefficient capped at `0.999`. Mono Audio-only (no GeneratorEnum, no `.Control`). `cutoff`/`resonance` `ValidGeneratorInput`. tanh count optimised: 5 per oversampled sample by caching `tanh(yN)` between stages. `denormalsToZero` on every stage. New "Saturating Ladder Filters" section in `Filters.md` DocC. | 2949 |
|
||||
| 93 | `ConvolutionReverb.Audio` — uniformly partitioned FFT overlap-save convolution against an `LyrebirdBuffer` IR. `partitionSize` (power of two, default 256) sets FFT size `N = 2P` and inherent latency. IR is partitioned into `ceil(ir.count / P)` blocks at init; each partition's `vDSP_fft_zrip` forward FFT is precomputed once into per-channel split-complex storage. RT path: input accumulator fills P samples, runs forward FFT into a numPartitions-slot frequency-delay line, dispatches `vDSP_zvma` complex multiply-accumulate against every IR partition spectrum (with scalar fix-up for the packed bin-0 DC/Nyquist real values), inverse FFT, scales by `1/(4N)` (forward ×2 × forward ×2 × inverse ×N), copies last P samples (overlap-save) into a per-channel output stage. `outputChannelCount` matches `ir.channelCount`; mono input is convolved separately against each IR channel. `mix`, `mul`, `add` are `ValidGeneratorInput`. All FFT/FDL/IR storage uses `UnsafeMutablePointer<Float>` allocated in `init`, freed in `deinit`. `convolutionReverbMaxPartitionSize` = 8192, `convolutionReverbMaxPartitionCount` = 16384 cap total IR length. | 2962 |
|
||||
| 94 | `MIDIFile` SMF parser (formats 0 + 1, PPQ division) + `MIDIFilePlayer` clock-driven playback. Pure language-side parser in `Sources/Lyrebird/MIDI/SMF/`: `MIDIFileError` enum, `MIDIFileEvent` (beat-stamped event with `Kind` covering `.midi(MIDIMessage)` channel events + `.tempo`/`.timeSignature`/`.keySignature`/`.trackName`/`.instrumentName`/`.text`/`.copyright`/`.lyric`/`.marker`/`.cuePoint`/`.endOfTrack` meta), `MIDIFileTrack`, `MIDIFile`. Internal `SMFParser` reads MThd/MTrk chunks, decodes VLQ delta times, honours running status, surfaces meta events through `decodeMetaEvent`, silently skips SysEx / unknown meta. Tick→beat conversion at parse time (`beat = tick / ticksPerQuarter`) so result is tempo-independent. `allEvents`/`allChannelEvents`/`tempoMap`/`totalBeats` convenience views; merge across tracks is stable on `(beat, trackIndex)`. `MIDIFilePlayer` owns a `LyrebirdRoutine`, walks `allEvents` calling `ctx.wait(beats:)` between events, dispatches `.midi` to `handler`, applies `.tempo` to `clock.bpm` when `applyTempoMap == true` (else forwards), routes everything else to optional `metaHandler`. `play`/`stop`/`reset`/`state` lifecycle. Rejects format 2 + SMPTE division at parse time. | 2983 |
|
||||
| 96a | `MIDIClockFollower` language-side BPM follower (`Sources/Lyrebird/MIDI/Sync/MIDIClockFollower.swift`): rolling window of last *N* tick `SampleTime`s (default 24 = quarter-note window) → inter-tick avg → `60 / (avgSec * 24)` BPM, clamped to `[minBPM, maxBPM]`, epsilon-gated push to `clock.bpm` *outside* the follower's lock to avoid lock-ordering vs `LyrebirdClock._lock`. Default `_isRunning = true` so free-running clock sources without transport messages work; `.stop` gates `_handleClock` until `.start`/`.continue` re-enables. New `MIDIMessage.continue` (0xFB) added to enum (keyword-escaped), parser, and `bytes()`. Internal `init(timeProvider:)` allows synthetic-clock test injection. Phase 96b (Ableton Link) not planned. | 3122 |
|
||||
| 95 | `ScannedSynthesizer.Audio` — Mathews/Verplank 2000 1D mass-spring scanned synthesis. Power-of-two ring of N masses (default 64, max 1024). Per audio block: two-pass Jacobi explicit-Euler update — pass 1 fills `_accelerations[]` from old positions/velocities (avoiding in-place Gauss-Seidel asymmetry), pass 2 integrates `v += a·dt` and `x += v·dt`. Per-mass: discrete 1D Laplacian × stiffness − damping·v − centeringForce·x + excitationForce[i]. Excitation injected at single configurable mass index, sampled once per block via `lastGeneratorSampleOrFloat`. Per-sample audio-rate phasor scans `_positions[]` as a wavetable through `oscillatorTableRead` (none/linear/cubic). New `[Double]` overloads of `oscillatorTableRead*` helpers added in `OscillatorTableReadHelpers.swift`. New `ScannedSynthesizerShape` enum (`.gaussian`/`.sine`/`.impulse`/`.zeros`) for init-time displacement preset. Audio-only, no `.Control`, no `GeneratorEnum`. New DocC topic `Generators/ScannedSynthesis.md`. | 3138 |
|
||||
| 97 | `MuTronIII` — envelope-controlled resonant filter (Audio + Control) modelling the Musitronics Mu-Tron III (1972) auto-wah. Topology: full-wave rectify × `sensitivity` → asymmetric one-pole envelope follower (inlined, not composed) → exponential cutoff sweep `freqLo·pow(freqHi/freqLo, env)` → inlined Chamberlin SVF (selectable `MuTronIIIMode` `.lowpass`/`.bandpass`/`.highpass` and `MuTronIIISweep` `.up`/`.down` — both `let` constants set at init). Mono output. Guards: `_inputIsGenerator` classification + scalar fast path (avoids `Double.calculatedSamples` heap alloc), sensitivity clamped ≥ 0, `freqLo`/`freqHi` clamped to `[0.001, Nyquist]` with monotone ratio, peak floor `1.0` (Chamberlin stability `q1 + f < 2` at `f → 1.0` from Nyquist sweep), denormals zeroed on `_prevAmp` + `_svfLow` + `_svfBand`. `Control` uses standard `calculatedSamples` bypass for once-per-block IIR state advancement; output `fillRampedResult` from previous to current target. New types: `MuTronIIIMode`, `MuTronIIISweep`. 24 tests including deterministic Chamberlin sample 0/1 verification at `1e-12`. | 3162 |
|
||||
| 102a | Ambisonic Toolkit (FOA extra encoders) — `FoaEncodeOmni` (omni: W=input, X=Y=Z=0; full amplitude on W vs FoaPanB's plane-wave 1/√2 convention) + `FoaEncodeStereo` (left, right, angle) summing two opposing FoaPanB encodes at ±angle. Static `angle: Double` arg; coefficients (`foaRsqrt2`, `cos(angle)`, `sin(angle)`) pre-computed at init. Direct `GeneratorBase, AudioGenerator` finals with 4-row output. lyrebird_review clean on first pass. 28 new tests. | 3595 |
|
||||
| 103 | Runtime Source-Swap for `@LiveParam` Slots — `synth.$freq.source = SineOsc.Control(...)` replaces the generator wired into a parameter slot without stopping the synth. RT-safe (no allocation, no locks, no ARC retain/release on the audio thread) via `SourcePacket` carrying `Unmanaged<AnyObject>` over per-parameter `ParameterSourceQueue` (SPSC, capacity 4). Engine-wide `parameterSourceKillQueue` (SPSC, capacity 256) holds old slots until the main-thread drain (hooked into the existing background timer) releases them; overflow degrades gracefully. Crossfade-N-blocks soft swap (mid-block-snapshot mix; scalar↔generator transitions handled; mid-crossfade swap kills in-progress old slot). UIParamNode parity via `calculatedSamples` forwarding. KeyPath approach rejected due to Swift 6 generic-on-open-class constraints; `synth.setSource(synth.$freq, to: lfo)` taking a `ParameterNode` directly is the secondary API. Two review passes — pass 1 caught `as?` on RT path (replaced with class-to-class-protocol `as!`) and `UIParamNode` missing `calculatedSamples` override (would have silently bypassed source-swap pipeline). 69 new tests across 5 files including end-to-end integration through a running engine. | 3703 |
|
||||
| 104d | AUv3 aux output + sidechain input — Multi-bus extension on top of 104a/b/c. New `LyrebirdAUBusSpec` value type (name + channelCount). Two new `open class var` hooks on `LyrebirdAudioUnit`: `lyrebirdOutputBusses` + `lyrebirdInputBusses` returning `[LyrebirdAUBusSpec]`. Defaults derive from existing single-bus `lyrebirdOutputChannels` / `lyrebirdInputChannels` so single-bus subclasses (LyrebirdFM, every 104a-c demo) keep working unchanged. Init builds N `AUAudioUnitBus` per spec array, sums channels for engine init, builds AU-bus-to-engine-bus offset maps (`auOutputBusOffsets` / `auInputBusOffsets` now stored on `SynthesisEngine` as `public internal(set) var`). `internalRenderBlock` closure captures `outputBusNumber` and passes through to `AUv3Driver.render(outputBusNumber:...)`. Driver gains `configureBusMap(outputBusChannelCounts:inputBusChannelCounts:)` called by `allocateRenderResources` before engine.start; per-output-bus `AUv3RingBuffer`s replace single ring; per-input-bus host ABL + Float backing; `_fillInputStagingFromHost` iterates input busses and pulls each via `AURenderPullInputBlock(...,inputBusNumber:...)`. New `AUv3RingBuffer.write(fromAudioBuses:sourceBusOffset:channelCount:count:)` slices engine.audioBuses per bus. `AUInput.Audio` gains `init(busIndex:channel:)` designated init; existing `init(channel:)` is now a convenience for `busIndex: 0`; compute consults `engine.auInputBusOffsets[busIndex] + channel`. Saturation guard in `_distributeEngineOutputToRings` resets a ring when its `availableToWrite < blockSize` — handles asymmetric host bus pulls (RT crash otherwise). Named `auv3RingBufferHeadroomFactor: Int = 2` constant for ring sizing. Two review passes: pass 1 caught RT crash on asymmetric pulls (saturation guard added) + missing render-loop sidechain coverage (added) + magic number `2` (named) + AUInput.Audio class-level doc gap (busIndex entry added); pass 2 clean. 9 new tests across 1 file (single-bus backcompat + multi-output exposes + multi-output engine layout + multi-output rendering routes independently + asymmetric pulls don't crash + two input busses exposed + sidechain offset map populated + AU input busIndex resolves + render-loop dispatches per-input-bus pullInputBlock). | 3788 |
|
||||
| 114 | Generator boilerplate reduction (`_result` on `GeneratorBase`, `_checkCount(_:)`, default `floatValue` on `AudioGenerator`, `makeSampleBuffer`/`makeResultBuffer` factories) — eliminates ~1000 lines of mechanical boilerplate. Mono `AudioGenerator` is six lines instead of ~18; multi-row generators call `super.init(channels: N)` and drop manual `_result = …` allocation. `FreqTracker`, `FreeVerb`, `GVerb` got `outputChannelCount` overrides en route (silently mono-ized under operator arithmetic before). `GranularBase.init(seed:channels:)` lets stereo grain subclasses thread channel count through. ~150 generator files + 17 test files swept; `docs/protocols/writing-generators.md`, `Sources/Lyrebird/Lyrebird.docc/Generators/WritingGenerators.md`, and `CLAUDE.md` rewritten around the new patterns. Three review passes: passes 1 + 2 each caught doc-only regressions (class-level + protocol-level `GeneratorBase`/`Generator` summaries that still described post-super reassignment instead of `super.init(channels: N)`, plus the DocC article's five pre-Phase-114 code blocks); pass 3 clean. 3544 tests — same count as Phase 113. | 3544 |
|
||||
| 148 | Flaky timing tests — three `TestBlockDriver` fixtures (`LyrebirdProcess`/`LyrebirdEventList`/`LyrebirdEventListRecording`) drove the engine at ~1.45 ms audio per 1 ms wall sleep ≈ barely realtime, so 1.5 s wall-clock test timeouts expired before envelope releases / process completions could fire `onFinished` (10–18 failures/run). Burst 32 `processBlock` calls per `Thread.sleep` (≈ 46× realtime). `_running` flag tightened to `Atomic<Bool>` (`Synchronization`) since 32 reads/iter widened the prior plain-`var` race; `_thread` stored property added for parity; sleep duration named (`wallSleepSeconds`). 10 consecutive `swift test --filter` runs clean. Misdiagnosed `FLAKY_TIMING_TESTS.md` census deleted — `releaseElapsed ≈ 62.3 × 10⁹ s` is a `Date.distantFuture`-class sentinel delta, not a mach-timebase bug. | 3610 |
|
||||
| 149 | `lyrebird repl` fix — `swift package repl` was removed from the Swift toolchain; the CLI's `repl` subcommand + the `lyrebird>` interactive-shell `repl` command had been silently broken. `REPLLauncher` rewritten as a two-step invocation: `swift build` stages `.build/debug/Modules/Lyrebird.swiftmodule` + `libLyrebird.dylib` + `LyrebirdC.build/module.modulemap`, then `swift repl -I .build/debug/Modules -I .build/debug/LyrebirdC.build -L .build/debug -lLyrebird` (same flags SPM was computing internally). New `CLIError.buildFailed(exitCode:)` surfaced in both `InteractiveShell` and `LyrebirdCLIMain.runREPL`; `build(in:)` checks `process.terminationReason == .exit` first so signal kills surface as `exitCode: 1` rather than the raw signal number. WIP recovered from an orphaned agent worktree (`claude/infallible-boyd-97598a`) during a branch-cleanup sweep; 3-way applied cleanly to current `main`. Two-pass review — pass 1 caught missing test coverage on the `buildFailed` path + missing `-I`/`-L` flag-token assertions + signal-kill exit-code leak; pass 2 clean. | 3611 |
|
||||
| 151 | AppKit-in-core layering fix + `lyrebird_review_cycle` cleanup. Two batches landed together. (1) **AppKit extraction**: new `open class MouseInputBridge` in core (default no-op returns 0.5/0.5/0.0) + `enum MouseInput` registry (`Atomic<UnsafeMutableRawPointer?>` typed pointer with `nonisolated(unsafe)`; **scalar accessors** `currentX`/`currentY`/`currentButton: Double` to avoid returning a class reference on RT path with ARC retain/release; `.relaxed` ordering with documented "install before `engine.start()`" happens-before fence; identity-check fast path on `install(_:)`; `NSLock` serialises install/uninstall; `uninstall()` is `@_spi(LyrebirdExtensions)`). `Mouse.swift` made cross-platform, all three `Mouse.*.Control` get `_calculatedSamplesBlockRate` bypass override. `MouseTracker` deleted from core, recreated in `LyrebirdUI` as `MouseInputBridge` subclass; `installShared()` asserts main thread, idempotent via `Atomic<Bool>` CAS gating both registry install + main-queue NSEvent monitor install. CLAUDE.md module-layering rule extended to ban `AppKit`/`UIKit` in core alongside `SwiftUI`. (2) **Review-cycle cleanup**: RT ARC fixes — SynthesisEngine input-bus copy uses index-loop with `inputSamples[ch].withUnsafeBufferPointer` (no inner-`[Float]` `let` retain) + `Swift.max(0, …)` clamp + `min(src.count, dst.count)` element-wise update (step-1 zero-fill makes tail-clear unnecessary); ScopeCapture `borrowing [[Float]]` parameter + subscript-borrow access; In.swift / AUInput.swift subscript-borrow rewrites with `precondition(offset + count <= buf.count)` bounds restoration; In.floatValue uses `withUnsafeBufferPointer` + `preconditionFailure(...)`. `LyrebirdAUPresetCodable.makeGenerator` lock-during-callback fix (dequeue-then-invoke). 4 granular `outputChannelCount: Int { granularChannelCount }` overrides on `BufferGrain`/`SineGrain`/`FMGrain`/`InputGrain` (silent stereo→mono regression under `* 0.5`), pinned by 4 binary-op tests. New `fillScalarRampedResult(into:previousOutputValue:target:count:)` helper in `MulAdd.swift` with 28-site `Math.Control` sweep; registered in CLAUDE.md "Shared RT-Safe Helpers" + writing-generators.md §13. New `DynamicsBase: GeneratorBase` shared base (`public class`, `static let dbAmplitudeScale`/`logFloor`/`softKneeParabolaFactor`, dual-location `/// - Parameters:` docs at base + `Compressor._Base` + `Expander._Base`); Compressor + Expander `_Base` collapsed to subclasses. `GeneratorEnum`-omitted comments on `SpectralChain`/`AdditiveSynthesizer`/`FormantGrain`. Sendable invariant comments on `ScorePlayer`/`MIDIClockFollower`/`SpectralFrameBuffer`. `MouseTracker` `deinit` removed (singleton process-lifetime). 8 review-fix passes total before clean. | 3697 |
|
||||
| 152 | Pre-run engine reconfig + master gain / mute. `SynthesisEngine.sampleRate` / `numOutputChannels` / `numInputChannels` promoted from `let` to `public private(set) var` with three new setters (`setSampleRate(_:)` / `setNumOutputChannels(_:)` / `setNumInputChannels(_:)`) gated by `engineIsRunning` + `invalidValue` errors from new `SynthesisEngineConfigError`; identity writes short-circuit so bus-allocator free list doesn't churn. `setSampleRate` recomputes `_blockDurationNs`. Master output gain (`masterGain: Double` via `Atomic<UInt64>` bit-packed pattern, NaN/Inf-rejecting setter) + `isMuted: Bool` (`Atomic<Bool>`) live on the engine; end-of-`processBlock` per-channel `vDSP_vrampmul` linear ramp from `_previousAppliedGain` to live target avoids slider/mute clicks. Per-channel `var start = from` reseed each iteration because `vDSP_vrampmul` mutates `*start` in place — first review pass caught a regression where channels 1–3 flat-multiplied at target instead of ramping. `_previousAppliedGain` reseeded from live state in `start()` so stop→start cycle that ended muted doesn't replay stale ramp. `BusAllocator.hardwareAudioEnd` becomes mutable; new internal `_reconfigureHardwareReservation(numOutputChannels:numInputChannels:)` invalidates audio buses + remarks reservation under existing `NSLock`; control buses untouched. `_release` refactored to `honoursHardwareReservation: Bool` + read live `hardwareAudioEnd` inside lock — closes TOCTOU race. `LyrebirdEngineStatusView` gets Configuration section (sample-rate `Picker` 44.1k / 48k / 88.2k / 96k / 176.4k / 192k dynamically augmented with engine's current rate when non-stock; output/input channel `Stepper`s 1…32 / 0…32) gated `.disabled(isRunning)`, Output section (`Toggle("Mute")` + `Slider` in `-90…+12` dB paired with `TextField` formatted `%+.1f`, shared `masterGainDb` state). View `init` seeds every `@State` from live engine values; private `linearToDb` finite-floors at slider lower bound; `pushConfigToEngine` guards setter `.onChange` against running-while-mirroring drift. Two new test suites — `SynthesisEngineConfigTests` (3 setters × happy / running-throws / invalid / overflow + post-resize bus allocation lands after reservation) + `MasterGainMuteTests` (get/set round-trip, NaN/Inf rejection, end-of-block ramp math `expectedLast = to + (from - to) / n`, 4-channel ramp regression catching the `*start`-leak, mute zeros output, master gain doesn't touch input buses, stop→start regression for `_previousAppliedGain` reseed). Two review passes — pass 1 caught the `vDSP_vrampmul` channel-leakage bug + unnecessary atomic surface area + missing reseed-on-start + reservation invalidation gap; pass 2 clean. | 3727 |
|
||||
| 153 | `LyrebirdEventList` fire-time tracking + body-closure backref. Two new public methods on `LyrebirdEventList` — `fireTimes(forEvent:) -> [Double]` (every offset at which the index fired; empty if not yet / out-of-range, no trap) + `firstFireTime(forEvent:) -> Double?` — filter `_timeline` rather than maintain a parallel index (timelines are short). New `private let _timelineLock = NSLock()` protects `_timeline` across five mutation sites (`_appendTimelineEntry` / `clearTimeline` / `setTimeline` / `loadTimeline` / the `_timeline.removeAll()` in `reset`) and both cross-thread readers; bare `var timeline` getter + `saveTimeline` / `playTimeline` remain unsynchronized (main-thread only, same thread as mutators) with a new `- Important:` doc note. `@unchecked Sendable` rationale at top of class rewritten to spell out the new locking protocol vs. main-only state. `LyrebirdProcess` gains `internal weak var _owningEventList: LyrebirdEventList?` set in the ownership-claim loop alongside `_eventListStartProvider` / `_eventListStartSampleTimeProvider`; weak so the process doesn't retain the list (list already retains the process via `_allProcesses`). `LyrebirdProcessContext` gains matching `internal weak var _owningEventList` + public `var eventList: LyrebirdEventList?` computed accessor; populated by `LyrebirdProcess._play` next to existing `context._eventListStart = _eventListStartProvider?()`. Body / `onRelease` closures can now write `ctx.eventList?.firstFireTime(forEvent: 0)` to cross-reference earlier events. Six new tests appended to existing `LyrebirdEventList` suite — empty-before-play, monotonic first-fire-time (origin == 0.0, indices 1+2 strictly monotone-positive), out-of-range / negative indices return empty/nil without trapping, multi-fire capture (two `play(eventIndex: 1)` → two distinct entries), context.eventList identity for owned + standalone, body closure reads `ctx.eventList?.firstFireTime(forEvent: 0) == 0.0` after a 10 ms sleep (synchronous `_appendTimelineEntry` inside `play(eventIndex:)` runs before the background task wakes). Two-pass review — pass 1 caught stale `@unchecked Sendable` rationale comment claiming `_timeline` was main-thread only (contradicting the new cross-thread accessors) + two `t1!` / `t2!` force-unwraps in `#expect` (CLAUDE.md prohibits force-unwraps in test code too); fixes used `try #require(...)` bindings; pass 2 clean. | 3727 |
|
||||
| 163 | `midiToRatio` / `ratioToMidi` SC-style musical-math additions — surfaces existing `semitonesToRatio` / `ratioToSemitones` under SC-flavored names that mirror the `midiToHz` / `hzToMidi` pair, plus dot-syntax on `Double` (`12.0.midiToRatio` → `2.0`, `2.0.ratioToMidi` → `12.0`) and `Int` (`12.midiToRatio` → `2.0`, `(-12).midiToRatio` → `0.5`). Free functions (Double + Int overloads + array overload), `extension Double` / `extension Int` computed-var dot syntax (module-qualified `Lyrebird.midiToRatio(self)` inside the extensions to disambiguate from the property name), `Collection<Double>` / `Collection<Int>` methods paired with the existing `semitonesToRatio()` / `midiToHz()` collection methods. Driven by the MyPiece pitch-shift use case where the composer reasons in semitones but the generator expects a ratio (`PitchShift.Audio(pitchRatio: 7.midiToRatio)`). 14 new tests (octave check, round-trip, equivalence with `semitonesToRatio`, dot syntax Double + Int, array overloads, non-positive edge → `-.infinity` / NaN inherited from `log2`, three collection-method forms). Docs updated end-to-end (`docs/stdlib/generators.md`, `Sources/Lyrebird/Lyrebird.docc/Generators/MusicalMath.md`) with the SC convention paragraph + PitchShift call-site example. Two review passes — pass 1 flagged absent Collection-method symmetry + missing non-positive edge test (both non-blocking but addressed); pass 2 clean. | 3876 |
|
||||
| 162 | `Envelope.releaseNode` aligned with SuperCollider's level-index convention — fixes a sharp edge where `Envelope([0,1,0], [2,2], releaseNode: 1)` was silently holding at the post-decay zero instead of the audible peak. Pre-Phase-162 `releaseNode` was a SEGMENT INDEX (hold value `levels[releaseNode + 1]`); now a LEVEL INDEX (hold value `levels[releaseNode]`) — matches SuperCollider's `Env` convention and the user's mental model. Valid range `[1, levels.count - 1]`. `EnvelopePacket` converts the public level index → internal segment index `releaseNode - 1` at packet construction so RT-side `EnvelopeGen` arithmetic stays untouched. `LyrebirdProcess.release(reltime:)` reads `_envelope.levels[releaseNodeIdx]` directly. `loopNode` (still a segment index) cross-validation is now `loopNode < releaseNode - 1`. 45 in-tree `releaseNode: N` literals bumped to `N + 1` to preserve their existing hold-level behavior; three doc examples whose values had been incorrect under both old and new semantics were also fixed end-to-end. View helper `_regionForSegment` already treated `releaseNode` as a release-region-start boundary equivalent to a level index, so no view code change. Tests: 4-test `LyrebirdProcessReleaseNodeHoldTest` regression suite (level-index identity for the exact MyPiece envelope, peak-hold under gate, out-of-range clamps to nil, final-level edge case); `StdlibGeneratorTests` assertions `env.releaseNode == N` updated to match bumped public values. Two review passes — pass 1 caught 11 stale comments + a force-unwrap; pass 2 caught 4 remaining stale comments. | 3862 |
|
||||
| 161 | Auto-free synths on envelope done — surfaces SC-style "envelope done → node freed" semantics. New `Sources/Lyrebird/Envelopes/DoneActionWatchable.swift` protocol (`var needsFree: Bool { get }`, AnyObject-constrained) conformed by `EnvelopeGen.Audio` + `EnvelopeGen.Control`. `SynthesizerBase.autoFreeOnDone(_:)` opt-in inside `build()` designates a lifecycle probe; engine `add`/`schedule`/`remove` hooks register/unregister via a new `_AutoFreeEntry` registry. Single shared `DispatchSourceTimer` on `lyrebird.autofree` utility queue, 10 ms cadence (matches LyrebirdProcess watcher). Tick: snapshot registry, read atomic `needsFree`, remove fired entries from registry BEFORE dispatching `engine.remove(synth)` on main — closes a double-fire race that would otherwise corrupt `NodeTreeMirror` via duplicate `didRemove`. Dead-entry sweep handles both `synth == nil` and `probe == nil` so orphaned slots can't pin the timer. `engine.stop()` cancels the timer, clears entries, and barriers via `_autoFreeWorker.sync {}`; late-arriving `DispatchQueue.main.async` blocks guard `args.engine.isRunning` so a tick that escapes the barrier exits cleanly instead of enqueuing a stranded `.remove` event into `pendingQueue`. Cross-thread carrier `_AutoFreeRemovalArgs: @unchecked Sendable` mirrors the existing `ContextAddArgs` / `GroupFreeArgs` idiom. Five new tests (`Tests/LyrebirdTests/Envelopes/AutoFreeOnDoneTests.swift`): Control + Audio envelope auto-free, manual-remove-before-fire unregister, multiple staggered synths, and a no-opt-in synth that stays in the tree. Three review passes — pass 1 caught the double-remove race + orphaned-probe gap + ARC leak via late-firing main.async after stop(); pass 2 caught a narrow remaining window where main.async could land post-stop; pass 3 clean. | 3855 |
|
||||
| 160 | Node tree visualization — main-thread `NodeTreeMirror` (`@Observable public final class`) that tracks every language-side `engine.add` / `schedule` / `remove` / `Group.free` and publishes an immutable `NodeTreeSnapshot` for SwiftUI. New `Sources/Lyrebird/NodeTree/NodeTreeSnapshot.swift` (value-type `Node` with `Kind = .synth(className:) / .group / .parallelGroup`, `ObjectIdentifier id`, head→tail children) and `NodeTreeMirror.swift` (internal mutable tree keyed by `ObjectIdentifier`; updated **after** a successful `pendingQueue.enqueue` so the mirror's view stays consistent with the RT thread's view; skipped on overflow). `SynthesisEngine` gains a `public let nodeTreeMirror` seeded after `rootGroup`/`mainGroup` install; hooks added to `schedule(_:at:)`, `schedule(_:after:)`, `add(_:position:)`, `remove(_:at:)`. `Group.free(engine:)` records the update post-enqueue; `Group.release(engine:)`'s background timer hops to `DispatchQueue.main.async` via a new `GroupFreeArgs: @unchecked Sendable` carrier (same `LyrebirdRoutineContext.Args` idiom) before invoking `free` so the mirror is never mutated from `.global(qos: .utility)`. `ParallelGroup.head` promoted `private → internal` so the mirror can walk the main-thread-populated children at engine.add time. New `LyrebirdNodeTreeView` in `LyrebirdUI`: recursive disclosure rows, head→tail order, depth-indented; per-row glyph (chevron / dot), display name, child-count badge for groups, 4-hex identity suffix derived from `ObjectIdentifier.hashValue` (stable across processes; no parsing of stdlib internal `String(describing:)` format). Header has Expand All / Collapse All; macOS `presentInWindow(...)`. `LyrebirdEngineStatusView` gains a collapsible Node Tree section above the Messages section + macOS Open Window button (close-and-reopen toggle). Eleven new `NodeTreeMirrorTests` + one regression test for child-remove preserving the parent group: initial snapshot shape, head/tail/before/after insertion, remove, nested groups, ParallelGroup head→tail walk on add, Group.free dropping subtree, displayName matches runtime class, `.before` fallback on unknown anchor. Three review passes — pass 1 caught a thread-safety violation (`Group.release` timer mutating mirror on utility queue) + multi-param init style + magic-number `6` + dead-code `timestamp` + redundant `@Bindable`; pass 2 caught inaccurate "before"-vs-"after" doc wording and a brittle `String(describing: ObjectIdentifier)` parse; pass 3 clean. | 3839 |
|
||||
| 159 | `LyrebirdMessage` + `LyrebirdMessageView` — user-visible diagnostic channel kept strictly off the RT thread. New `Sources/Lyrebird/Diagnostics/` subfolder with `LyrebirdMessageTier` (info / warning / error), `LyrebirdMessage` (Identifiable Sendable struct), and `LyrebirdMessageCenter` (`@Observable @MainActor` singleton with bounded FIFO ring, default capacity 200). `LyrebirdMessageView` in `LyrebirdUI` provides a scrollable list with per-tier filter chips, count badges, Clear button, auto-scroll to newest, and macOS `presentInWindow(...)`. `LyrebirdMessageBanner` is a compact 3-line embed surfaced inside `LyrebirdEngineStatusView` as a collapsible Messages section between CPU metrics and configuration; the engine status view also offers an "Open Window" button on macOS. Shared tier-colour / short-label helpers live in `LyrebirdMessageHelpers.swift` per the `*Helpers.swift` rule. `print()` is intentionally untouched — library authors opt into `post()` for user-visible messages while keeping the developer-console stream. Eight new `@MainActor` tests cover post / tier routing / capacity pruning / capacity-reduction prune / clear / identity / capacity-1 / `allCases` ordering. Two review passes — pass 1 caught two-public-types-in-one-file and a cross-file helper not in a `*Helpers.swift`; both fixed plus a missing subfolder rationale added to CLAUDE.md. | 3827 |
|
||||
| 154 | Explicit `: Type` annotations on every inferred `let` / `var` binding across `Sources/` (351 files, 6177 sites) and `Tests/` (223 files, 14249 sites) — Xcode type-checker speedup + readability win. Motivation: Xcode's expression checker is markedly slower on long, generic-heavy synth-graph expressions when intermediate locals are inferred; annotating the binding short-circuits that work. New `Tools/AnnotateBindings/annotate_bindings.py` drives `/usr/bin/sourcekit-lsp` over LSP JSON-RPC: per file, sends `textDocument/didOpen` then requests `textDocument/inlayHint` for the full range and applies the LSP `textEdits` that come back. Applied set filtered by a strict guard that rejects every Swift position where `: T` would not parse: (a) line-suffix must match `(let\|var\|for)\s+<identifier>$` (no intervening `{`, `[`, `(`, `,`); (b) tuple-pattern destructures (`let (a, b) = …`); (c) closure-header / capture-list (`{ ptr in`, `{ [weak self] in`); (d) `case let .foo(x)` / `catch let err …` pattern positions. Iterated four times during initial bring-up: closure-param hints `{ ptr: T in` broke 16 files → `_has_binding_keyword_before` added; `[weak self: T]` capture-list hints broke 1 file → stricter `<identifier>$` suffix added; `catch let err: T as P` broke `LiveSession.swift` → `_PATTERN_CONTEXT_RE` added. One manual fix: `LyrebirdScratchView.swift` had `let engineRefresh = Timer.publish(...).autoconnect()` annotated as `Publishers.Autoconnect<…>` (Combine type not imported in that file) → reverted to inferred form. One stale untracked `Sources/Lyrebird/Generators/UI/MouseTracker.swift` discovered (Phase 151 deleted this exact path; canonical lives in `Sources/LyrebirdUI/`) → removed manually. Tool ships unit-free using only Python stdlib; idempotent (running twice produces no second round of edits because every binding now ends in `<identifier>$:`). `swift build` clean; `swift test --no-parallel` → 3725 tests in 422 suites pass. Two-agent review (lyrebird_review_agent + caveman line sweep) clean — only non-blocking tool nits flagged (hardcoded `/usr/bin/sourcekit-lsp` path, hardcoded `REPO_ROOT` default, regex doesn't strip `//` comments, file URI not percent-encoded). | 3725 |
|
||||
| 170 | `GeneratorInputProvider` as first-class `ValidGeneratorInput`. New `_resolvedInput() -> any ValidGeneratorInput` protocol requirement (default returns `self`; provider overrides to call `make()`). Every Generator init resolves `any ValidGeneratorInput` slots once at the top before storing / classifying — provider becomes transparently substitutable for any input source at the call site with no `.make()` boundary call. Helper-boundary resolution at 5 sites (`MulAddSpec` / `OscillatorBase` / `LFNoiseBase` / `NoiseBase` / `DynamicsBase`) covers many Generators automatically; sweep touches 139 Generator inits across all 22 generator-folder families. Provider's other `ValidGeneratorInput` accessors are `preconditionFailure` traps with a shared `_unresolvedProviderTrapMessage` string — unreachable in correct code, fire at first audio block if a provider somehow survives unresolved. Init-time only, non-RT, zero render-path overhead. End-to-end validated by MyPiece `TimeStretchMoment.build()` passing the provider directly to `AmbiEncoder1.azimuth`. One review-fix pass closed 7 blocking findings (3 missed-sweep files, 5 raw-param `is any Generator` classification sites that shadowed correctly-resolved inherited flags, 9 distribution-noise `_Base` inits, 1 helper-boundary policy violation in `AmbiEncoder1`, 1 stale docc example, 1 plan-doc snippet contradicting the skip-list); re-review clean. | 3961 |
|
||||
| 181 | sampleOrZero sweep — third + final sub-phase of the 179-181 code-dedup follow-on. New `Sources/Lyrebird/GeneratorCore/HotLoopHelpers.swift` with `@inline(__always) @_spi(LyrebirdExtensions) public func sampleOrZero(_ p: UnsafePointer<Double>, _ i: Int, _ n: Int) -> Double` returning `i < n ? p[i] : 0`. Replaces per-sample `(i < n) ? srcP[i] : 0` boilerplate across 16 files (Filter family + Delay primitives). 4 files (DelayLine / DelayLineFeedback / CombFilter / AllpassFilter) had pre-existing `sampleAt(_ i:)` inline closures — deleted; call sites use `sampleOrZero` directly. CLAUDE.md + writing-generators.md §13 registered. Output bit-equivalent across 358 affected tests. Closes the 179-181 follow-on to the 174-178 perf sweep. | 358+ |
|
||||
| 180 | Smoother step helpers — second sub-phase of the 179-181 code-dedup follow-on. Two related abstractions: (A) `onePoleLowPassStep(state:x:b1:comp:)` (`y = b1·state + comp·x`) + `leakyIntegratorStep(state:x:b1:)` (`y = x + b1·state`) in `FilterHelpers.swift` — applied across Lag / Lag2 / LagUpDown / Lag2UpDown / Decay / Decay2 inner loops. (B) new `Sources/Lyrebird/Generators/Dynamics/DynamicsHelpers.swift` with `AttackReleaseDirection` enum (`.rising` / `.falling`) + `attackReleaseSmoother(state:target:attackCoeff:attackComp:releaseCoeff:releaseComp:direction:)` — applied across AmplitudeFollower (`.rising`) + Compressor / Expander (`.falling`). All `@inline(__always)` — generated code identical to inlined form. Review-fix pass registered new helpers in CLAUDE.md + writing-generators.md §13 (mandatory per convention) + `import Foundation` → `import Darwin` for Dynamics family consistency. Output bit-equivalent across 124 affected tests. | 124+ |
|
||||
| 179 | Filter helper consolidation — first sub-phase of the 179-181 code-dedup follow-on to the 174-178 perf sweep. Two new `@inline(__always)` module-internal helpers in `Generators/Filters/FilterHelpers.swift`: (A) `runTwoPoleResonatorScalarBlock` + `runTwoPoleResonatorInterpolatedBlock` — `RingingFilter.processScalar` / `processInterpolated` and `ResonatingFilter.processScalar` / `processInterpolated` bodies were byte-identical post-Phase-178 except for the coefficient function; both consumers now shrink to a coefficient closure + one-line helper calls (~80 lines deleted across the two files). (B) `sampleOrFallback(_:scalar:at:)` — per-sample coefficient lookup with zero-fallback past block end. Replaces 8 verbose sites in SecondOrderSection (5) + FirstOrderSection (3). Review-fix pass added 4 missing class-level `/// - Parameters:` doc blocks on touched Generator types (pre-existing gaps). Output bit-equivalent across 358 filter-suite tests. | 358 |
|
||||
| 178 | IIR filter library sweep — final sub-phase of the 174-178 generator perf sweep. State hoist + raw-pointer hoist + once-per-block denormal flush pattern applied to 12 IIR filter files. Largest win: the two shared `processBlock` overloads on `BiquadState` + `FirstOrderState` in `RBJBiquad.swift` — amortised across every RBJ filter (LP/HP/BP/BPSkirt/AP/Notch/PeakingEQ/LowShelf/HighShelf) and every Butterworth filter (cascade biquad + first-order stages). Direct sweep also touched Lag/Lag2/LagUpDown/Lag2UpDown/LeakDC/Decay/Decay2/SecondOrderSection/FirstOrderSection/RingingFilter/ResonatingFilter. Skipped (deferred): MoogLadder / SVF / MuTronIII (nonlinear oversampled, tanh dominates), ResonatorBank (needs vDSP rather than state-hoist), Hilbert (small site). Two review-fix passes — first eliminated RT-path per-sample Optional dispatch (`srcP?[i] ?? 0`) across all 12 newly-touched files + 4 Phase-176 delay primitives for consistency; second pass cosmetic. Output bit-equivalent across 358 affected tests. | 358 |
|
||||
| 177 | `DiskOut.Audio` perf pass — fused ring-write + `_result` passthrough into one per-sample loop (was two passes). Mono fast path with raw-pointer hoist on `_ringBuffer[0]` (Float) / `_result[0]` (Double) / input row via nested `withUnsafe(Mutable)BufferPointer`. Four sub-branches `(canWrite, hasInput)`: fused write+passthrough / silence-fill both / passthrough only / silence result only. `wHead` hoisted to local + single `_framesWritten.store` at end. Multi-channel path kept on bounds-checked subscripts. BG-thread + producer-consumer atomics handshake unchanged. One review-fix pass eliminated an RT-path `[]` allocation in the zero-input-row degenerate branch. Output bit-equivalent across 11 DiskIn/DiskOut + EventList recording integration tests. | 11+ |
|
||||
| 176 | Delay-line primitives perf pass — DelayLine / DelayLineFeedback / CombFilter / AllpassFilter all already used PoT ring + bitmask wrap; new wins from state hoist (`writePos`, `allpassPrevOut`/`InputOut`/`OutputOut`), raw-pointer hoist via nested `withUnsafe(Mutable)BufferPointer` on buffer(s) + input + `_result[0]`, interpolation `switch` lifted out of per-sample loop into 4 explicit per-mode branches (`.none` / `.linear` / `.cubic` / `.allpass`), `cubicInterp` converted from instance method to `@inline(__always) fileprivate static`. One new `ringWrapStressManyWrapsOfShortRing` test covers DelayLine across ~172 ring wraps. Review-fix pass addressed magic-number `64` × 3 in new test + stale `cubicInterp` doc reference. Output bit-equivalent across 124 affected tests. | 124+ |
|
||||
| 175 | Reverb family modulo elimination — branchless ring-buffer wrap replaces every per-sample `% size` operation across SpringReverb (2 sites), PlateReverb (9 sites), GVerb (12 sites). Non-PoT sizes cannot fold to a bitmask so original code emitted real `idiv` on the RT path. `denormalsToZero` preserved per CLAUDE.md convention (NRTDriver no thread-level FTZ). FreeVerb deferred — already branchless wraps, structural flat-buffer refactor needed for further wins. Three new `denormalLongTailStaysFinite` tests exercise many ring wraps with real DSP (initial draft was vacuous via fan-out cache; review-fix pass hoisted shared engine + per-block `advanceBlock`). Output bit-equivalent across 43 reverb-suite tests. | 43+ |
|
||||
| 174 | Dynamics family perf pass — `AmplitudeFollower.Audio`, `Compressor.Audio`, `Expander.Audio`. State hoisted to locals across block (`_prevAmp` / `_prevGain`), once-per-block denormal flush, precompute `attackComp = 1.0 - attackCoeff` + `releaseComp = 1.0 - releaseCoeff` once per block, explicit if/else over attack/release branches replaces shared coefficient ternary, raw-pointer hoist on input + `_result[0]`, drop redundant `Double(...)` casts. Control variants untouched (one smoother step per audio block, not per sample). 3 new denormal-cadence tests (`denormalCadenceAmplitudeFollower` / `denormalCadenceCompressor` / `denormalCadenceExpander`). Review-fix pass strengthened the AmplitudeFollower test (initial draft was vacuous — pure zero input never left state). Output bit-equivalent across 41 dynamics-suite tests. | 41+ |
|
||||
| 173 | Input Conditioning Optimization (three sub-phases on independent branches): **173a** `LookAheadLimiter` perf pass — drop the parallel `_peakRing` (deque payload now carries `(peak, expireAtPos)` inline), branchless wrap on all ring/deque indices (kills every per-sample `%` on non-PoT capacities), precompute `_attackComp = 1.0 - _releaseCoeff`, denormal flush moved from per-sample to once-per-block, zero-look-ahead fast path (no ring, no deque), all state hoisted to locals with single writeback. **173b** `RecordBuffer.Audio._computeSamples` perf rewrite — `LyrebirdBuffer._rawStorageMutable` hoisted once per block, all param arrays + `_result[0]` lifted to raw pointers via nested `withUnsafe(Mutable)BufferPointer`, fill + buffer-write passes fused into one per-sample loop, block-constant fast-path detection on first + last sample of `run` / `recLevel` / `preLevel` (`runStable` / `preBlockZero` / `recBlockOne` flags), mono branch dispatches between four tightened loops with the hottest case collapsing to a single mul-free store per sample. Channel-count validation moved from RT-path `precondition` to `Audio.init`. **173c** new `MixIn.Audio(buses: [AudioBus], mul:, add:)` in `Generators/BusIO/` (sums N non-contiguous audio buses channel-wise into one output — replaces `signal + In.Audio(bus:)` chains) + new `SumChannels.Audio(input:, mul:, add:)` in `Generators/Routing/` (collapses any multi-channel input to mono via row summation; mono passthrough; `vDSP_vaddD` chain for multi-channel). Both Audio-only (no Control variant, `GeneratorEnum` conformance intentionally omitted). 27 new tests across `LookAheadLimiter` (2), `RecordBuffer` (5), `MixIn.Audio` (7), `SumChannels.Audio` (7). Touched-suite filter runs 241+/241+ pass deterministically; full `swift test --no-parallel` hits the intermittent pre-existing `RTThreadIdentity.markingIsThreadLocalNotProcessGlobal` TLS-leak / `LyrebirdBuffer` retain-race flakes only. Driven by MyPiece's `MixAndRecordInputs` / `ConditionAndRecordInputs` synthesizers running hot at session start (mix N input buses → optional `LookAheadLimiter` → `RecordBuffer`). Each sub-phase shipped on its own branch with full `/lyrebird_review` cycle (173a + 173b each had two review-fix passes; 173c one review-fix pass). | 3985+ |
|
||||
| 172 | `LyrebirdEventList` master-amp routing redesign + `ReplaceOut.Audio` / `ReplaceOut.Control` primitives + pre/post-master sub-groups. Triggered by a real-world MyPiece bug: `LyrebirdProcess._play` accepted a `procOutOverride` parameter and `LyrebirdEventList` used it to silently override every contained process's declared `procOut` to point at an internally-allocated `_masterBus`, silently breaking any process designed to feed a downstream effect chain (e.g. ambisonic-routed B-format → global decoder). Coupled fix: (1) `LyrebirdEventList.init` takes caller-supplied `bus: AudioBus` (replaces `masterChannels: Int`), default `AudioBus(index: 0, channelCount: 2)`; (2) `procOutOverride` parameter removed from `LyrebirdProcess._play` — dead code that was the original-bug mechanism; (3) new `ReplaceOut.Audio` / `ReplaceOut.Control` first-class overwrite bus-write primitives parallel to `Out` (`vDSP_vdpsp` direct to bus slice; engine plumb `setAudioBus` / `setControlBus`; `ScratchBuses.replace` overwrites this child's scratch slot inside `ParallelGroup` — does NOT scrub other siblings or pre-parallel content; `SynthGraph.setSamplesOnAudioBus` routes; `SynthesizerBase.replaceOutput(bus:source:)` helper); (4) `EventListMasterSynth` rewritten as `In.Audio(bus) * smoothAmp -> replaceOutput(bus)` (multi-channel via `BinaryOpGenerator` mono-broadcast); supersedes an interim "delta-add" trick (`bus += bus * (amp - 1)`); (5) new `preMasterGroup` / `postMasterGroup` sub-groups inside `_masterGroup` for caller-owned FX synths around the master amp, with `addPreMaster(_:)` / `addPostMaster(_:)` convenience helpers — synth lifetime bounded by EventList session (freed via `_masterGroup.free()` on teardown; fresh empty groups re-allocated for next session). Unblocks ambisonic decoders / bus-level limiters / master tap recorders. Sweep migrates `Tests/LyrebirdTests/Process/LyrebirdEventList{,Recording,Timeline,BuildFromFile}Tests.swift`, `ProcessSystem.md`, and MyPiece's `QuartetEventManager.createEventList()`. 19 new tests across `ReplaceOutAudioGeneratorTests.swift` (9) + `ReplaceOutControlGeneratorTests.swift` (4) + `LyrebirdEventListPrePostGroupTests.swift` (6). One `/lyrebird_review` cycle — blocking finding (two `@Suite` per file) fixed by splitting Audio + Control suites; non-blocking nits addressed (`_lyrebirdAssertNotOnRTThread()` guard on `outputChannelCount`; duplicate-precondition removal; sink-only `floatValue=0` doc; Control vs Audio channel-count divergence doc; explicit row-count guard; `ScratchBuses.replace` dirty-mark inside the write block; stable-sort pending-queue ordering comment; pre/post group lifecycle comments; design doc reordered to lead with `ReplaceOut`, delta-add moved to "Historical Note"). New `docs/engine/eventlist-routing-design.md` captures the bug, fix, ReplaceOut refactor + trade-off table, pre/post group design, lifecycle / ordering, migration. MyPiece `xcodebuild` BUILD SUCCEEDED with `bus: dependencyContainer.ambisonicRoutingBus`; ambisonic-decode chain now hears all four quad-channel feeds. | 3980 |
|
||||
| 113 | Pan4 family refactor (`PanAz`, `PanAzDistance`, `PanXY`, `PanXYDistance`) — reshapes the 4-speaker panning family around an `open class Pan4` base class holding the shared infrastructure (4-row output buffer pre-allocated to `lyrebirdDefaultResultBufferSize`, `_mulAdd`, `outputChannelCount = 4`, named channel aliases inherited via extension). Four concrete subclasses provide the actual generator behaviour. Old leaf `Pan4` (azimuth + elevation `@LiveParam` in `[-1, 1]`) retired — its azimuth-only behaviour now lives in `PanAz` with proper radian semantics. New shared `Pan4Helpers.swift` (module-internal, `@inline(__always)`): `azimuthToSquareBoundary(_ az: Double) -> (x, y)` projects azimuth radians onto the unit-square boundary via `1 / max(|sin|, |cos|)` so the trajectory hits speaker corners at `±π/4` and `±3π/4` (rather than the inscribed unit circle leaving corners unreachable); `writeEqualPowerSquarePanSample(into:sampleIndex:source:x:y:)` clamps `(x, y)` to `[-1, 1]²` and writes equal-power gains to the four `_result` rows. **`PanAz`** — `@LiveParam azimuth: Double` in radians (0 = front centre, wraps modulo 2π via `sin`/`cos`); position fixed to unit-square boundary. **`PanAzDistance`** — `azimuth` + `distance` (0 = listener, 1 = boundary, >1 = beyond) + `velocity`; same 1/d amp + air-absorption LP + Doppler pipeline as `PanXYDistance`, single mono LP + single delay line before panning; negative distance treated as `|distance|` (direction from azimuth). **`PanXY`** — `@LiveParam x`/`y` cartesian; refactored to inherit from `Pan4` and call the shared helper. **`PanXYDistance`** — cartesian + Chebyshev distance shaping; refactored to inherit from `Pan4` and use shared helper for the pan-write. `SpatialDistance` file-private constants promoted to module-internal `SpatialDistanceConstants.swift` for reuse across distance-model generators. Test migration: old `Pan4Tests` (in `PanningTests.swift`) rewritten as `PanAzTests` with corner positions at `±π/4` / `±3π/4` and cardinal-edge tests at `0` / `±π/2` / `π`; `Pan4ParameterRampingTests.swift` → `PanAzParameterRampingTests.swift` (git mv + rewrite); `ChannelSelectTests` Pan4-alias test updated to use `PanAz` at `az = -π/4`; new `PanAzDistanceTests.swift` (rate, channel count, boundary corner = PanAz, distance=0 equal-energy collapse, 1/d halving, negative-distance symmetry, Doppler down-shift, mul, fan-out cache); existing PanXY tests stay green via inheritance. Two review cycles total: first (initial PanXY/PanXYDistance with old Pan4 still elevation-based) caught dead `_referenceDistance` + `_sampleRate` + two-`@Suite`-per-file + `try?` swallow; second (this family refactor) clean on the first sweep — vtable dispatch through `AudioGenerator` protocol witness verified, no RT `is`/`as?`, helper inlining clean, channel-alias inheritance through extension on Pan4 correct. Docs swept: `docs/stdlib/generators.md` Panning Extensions section rewritten around the four-row family table; `docs/stdlib/multichannel.md` intro + named-aliases table; `Sources/Lyrebird/Lyrebird.docc/Generators/MultiChannel.md` intro list. | 3544 |
|
||||
| 112 | Extension authors guide + README extensions section — new `docs/extension-authors-guide.md` walks end-to-end through building an out-of-tree Swift package adding Generator/Synthesizer implementations. Companion to `docs/protocols/extension-sdk.md` (SPI surface list). Covers wiring, versioned releases, and pitfalls (SPI imports in tests, `Bundle.module` per-package, package-name case-sensitivity in target deps, SSH vs HTTPS for private repos, SemVer + compatibility matrix). LyrebirdATK is the canonical worked example — authors clone its `Package.swift` / `Sources` / `Tests` / `README` / `LICENSE` as templates. README.md gets an "Extensions" section between "The lyrebird CLI" and "Project structure" listing known extension packages + pointers to the SDK doc and authors guide; documentation table picks up two new rows. Doc-only commit; no source code changed. | 3499 |
|
||||
| 111 | Extract Ambisonic Toolkit (FOA) to LyrebirdATK external package — entire `Foa*` UGen set (37 generators in `Sources/Lyrebird/Generators/Ambisonic/`), bundled MIT KEMAR HRIR data (`Resources/HRTF/KEMAR/kemar-full.lbhr`, 1.47 MB), and `HRIRFile.bundledKemar{Full,FullURL}` static accessors removed from core. The exact same code (untouched algorithmically) now ships as the **LyrebirdATK** external Swift package — first worked example of the Extension SDK (Phase 110). Consumers add `LyrebirdATK` as a separate package dependency + `import LyrebirdATK` alongside `import Lyrebird`. Bundled-KEMAR `Bundle.module` lookup moved to `LyrebirdATK/Sources/LyrebirdATK/HRIRFile+BundledKEMAR.swift` where `Bundle.module` resolves to the LyrebirdATK package's resource bundle. Generic `HRIRFile.load(contentsOf:)` loader stays in core, unchanged. Six KEMAR-loading tests moved 1:1 to `LyrebirdATK/Tests/LyrebirdATKTests/HRIRFileBundledKEMARTests.swift`; 28 `Foa*` test suites moved out; synthetic / negative / round-trip loader tests stay in core. `docs/stdlib/ambisonic-toolkit.md` → `LyrebirdATK/docs/ATK-Guide.md`; `docs/stdlib/generators.md` ATK section rewritten as a pointer; `scripts/build-kemar-hrir.py` → `LyrebirdATK/scripts/`. `Package.swift` Lyrebird target — `resources: [.process("Resources")]` removed. Deliberate API-breaking change; recommended tag **Lyrebird 2.0.0** after merging (consumers on prior FOA-bundled Lyrebird stay pinned to `0.9.x`). Verification: core `swift test` 3499 / 405 suites; LyrebirdATK `swift test` (against this branch via local path dep) 322 / 36 suites; sum 3821 = pre-extraction total (no tests deleted, every removed test moved 1:1). | 3499 |
|
||||
| 110 | Extension SDK foundation — promotes the shared RT-safe helper symbols required by external Generator packages to `@_spi(LyrebirdExtensions) public`. `MulAdd.swift`: `MulAddSpec` (struct + init + stored props), `applyIfNeeded`, `apply`, `identity` static, `extractScalar`, `fillRampedResult`, `lastGeneratorSampleOrFloat`. `WhiteNoise.swift`: `xorshift64Next` + `xorshift64NextRaw`. `@_spi(LyrebirdExtensions)` keeps the surface invisible to ordinary `import Lyrebird` consumers while letting extension authors opt in with `@_spi(LyrebirdExtensions) import Lyrebird`; SPI symbols documented as MINOR-version-mutable. New `docs/protocols/extension-sdk.md` (tier-1 stable public + tier-2 SPI table, versioning policy, namespacing guidance); `docs/protocols/writing-generators.md` §13 cross-link. `Tests/LyrebirdTests/MulAddTests.swift` switched to `@testable @_spi(LyrebirdExtensions) import Lyrebird` (the `@testable` import alone does not grant SPI access). **Phase 110 follow-up**: two additional SPI hooks for out-of-tree test code building its own `advanceBlock`-style helper — `SynthesisEngine.segmentSerial` (read-only acquiring load) + `SynthesisEngine.advanceSegmentSerial()`, documented in a new "Test-helper hooks" subsection of `extension-sdk.md`. Bulk import sweep across 231 test files (mechanical, no test logic changed). | 3821 |
|
||||
| 109 | `SpectralPolarClosure` + `SpectralComplexClosure` — two closure-driven `SpectralProcessor` wrappers (same role `Closure` plays for time-domain DSP). Polar variant is zero-copy via existing buffer pointer accessors; DC/Nyquist round-tripped through pre-allocated single-element scratch (`_dcValue`/`_nyquistValue` are private). Complex variant uses `_readToRectangular`/`_writeFromRectangular` (vDSP packed split-complex: `real[0]=DC`, `imag[0]=Nyquist`) with two pre-allocated `UnsafeMutablePointer<Float>` scratch arrays freed in `deinit`. `Float` element type matches buffer storage. `hopSize` + `sampleRate` baked into closure class at init. `_frameIndex` mutable `Int` counter, RT single-threaded. New DocC topic `Generators/SpectralClosures.md`; new section in `docs/stdlib/spectral.md`. 12 tests for polar + 15 for complex including `complexFreezeLatchesSpectrum` (pre-allocated `memcpy` latch — canonical RT-safe freeze pattern). Two review passes — pass 1 caught dead `scratchReal`/`scratchImag` vars in freeze doc-example + typo `Latces`→`Latches`; pass 2 caught one non-blocking DocC terminology note (`inout`-like → captured reference box). | 3821 |
|
||||
| 108 | `PlayBuffer` rate + trigger → `ValidGeneratorInput` — promoted `PlayBuffer.playRate` (renamed to `rate`) + `PlayBuffer.trigger` from `@LiveParam Double` to `any ValidGeneratorInput` init params on both Audio and Control variants. Generator path uses `lastGeneratorSampleOrFloat` (Control) / `Optional<[Double]>?? scalarFallback` (Audio) — no per-sample heap allocation; scalar fast path calls `floatValue(graph:)` once. `Control.calculatedSamples` bypass retained for per-block phase state. +5 tests (generator-driven rate, generator-driven trigger via `Impulse`, scalar trigger reset, Control trigger reset, Control reverse). 4 demos + buffer-io-generators.md swept. Two review passes — pass 1 caught helper-inlining + dead `_zeroFallback`; pass 2 clean. | 3794 |
|
||||
| 107 | `LyrebirdBuffer.nativeRateScale` — sample-rate compensation helper moved off `PlayBuffer._Base` onto `LyrebirdBuffer` itself; any buffer-consuming generator now reuses it. Redundant `Double()` cast dropped (`sampleRate` already `Double?`). New 4-test `LyrebirdBufferRateScaleTests` @Suite covers nil/equal/up/downsampled; two prior cases in `PlayBufferTests` deleted. Six demos + `docs/stdlib/buffer-io-generators.md` swept. Single review pass clean — no findings. | 3790 |
|
||||
| 106 | FFT chain consolidation (legacy removal + synthOnly) — delete `FFTAnalysis.swift` + `IFFTSynthesis.swift`; all public spectral surface routes through `SpectralChain.Audio`. New `SpectralBufferGenerator` protocol (`spectralBuffer` + `hopSize`); `SpectralBufferRead` + `SpectralPlayBuffer` conform. New init `SpectralChain.Audio(spectralSource:fftSize:hopSize:…)` for fourth mode — synthOnly: aliases source `spectralBuffer`, drives source once per block, skips windowing + forward FFT, runs processors + fan-out + IFFT bank on aliased buffer. `_fftAnalysisRealp`/`_fftAnalysisImagp` switched to `Optional<UnsafeMutablePointer<Float>>` (`nil` in synthOnly; guarded deinit + use sites). Runtime precondition `count <= hopSize` in synthOnly `_computeSamples` prevents frame-loss when engine blockSize > hopSize. Migrated 7 `.Control` feature extractors (Centroid/Flatness/Spread/Flux/Entropy/Rolloff/OnsetDetector): `analysis:` init type changes from `FFTAnalysis` to `SpectralChain.Audio`. `SpectralChain.Audio.processors` widened `private` → `internal` for OnsetDetector.Control precondition. Doc sweep: `docs/stdlib/spectral.md` rewritten around `SpectralChain.Audio`; `docs/stdlib/generators.md` spectral section rewritten; all `.docc` topics (`SpectralChain.md`, `SpectralFeatures.md`, `SignalAnalysis.md`, `BuiltInGenerators.md`, `PitchShifting.md`, `GranularSynthesis.md`) updated; `LyrebirdBuffer` window docs + `SpectralBuffer` + `SpectrumCapture` + `LyrebirdSpectrumView` updated. Demos: dropped duplicate root-level `PercSpectralPitchShift.swift`; rewrote `Synthesizers/Spectral/PercSpectralPitchShift.swift` to use `SpectralChain.Audio`. New `PercSpectralStereoDiffuse` demo (mono → 2-channel decorrelated stereo via `SpectralStereoDiffuse` fan-out), wired as Demo 5 in `BufferDemos.swift` (TimeStretch shifts to Demo 6). Stale `Synthesizers/Buffer/` + `Synthesizers/Granular/` subfolder duplicates folded — newer flat root copies moved into subfolders via `git mv` to match Xcode pbxproj groups; pbxproj updated for new fan-out demo. Tests rewritten across `FFTTests`, `SpectralAutoPullTests`, `SpectralProcessor2Tests`, `SpectralChainTests`, `OnsetDetectorTests`. Phase 105 golden-buffer parity test removed (no legacy to compare). New `SpectralChain.Audio — synthOnly mode` test suite: `synthOnlyResynthesisProducesNonZeroAudio` + `synthOnlyDispatchesProcessorsOnAliasedBuffer` (verifies counter callCount > 0, lastSeenDC == source DC, chain.spectralBuffer === source.spectralBuffer identity). Two review passes — pass 1 caught missing synthOnly test coverage + class-level `/// - Parameters:` doc gap + fragile capacity-0 allocate/deallocate; pass 2 clean. | 3789 |
|
||||
| 105 | Spectral mono→N consolidation — `SpectralChain.Audio` Generator (`Sources/Lyrebird/Generators/Spectral/SpectralChain.swift`) collapses the legacy `FFTAnalysis` + `IFFTSynthesis` two-Generator pipeline into one. Three modes: mono resynthesis (default), mono→N fan-out (`fanOut` arg), analyze-only (`analyzeOnly: true` — no IFFT runs, audio output is silent, used by feature extractors). Internals: shared `vDSP_create_fftsetup` across N IFFTs; per-channel synthesis work buffers (`work realp/imagp`, `timeDomainBuf`, `overlapBuf`, `outputRing`) allocated in init; destinations[0] aliases `spectralBuffer` in the no-fanOut path (zero per-hop copy); analysis + synthesis hopCounters tick independently to match legacy `outputRingReadPos = ringSize - hopSize` one-hop latency. Golden-buffer test confirms sample-for-sample equivalence with `FFTAnalysis + IFFTSynthesis` for the mono path. New `SpectralFanOutProcessor` protocol (`process(source:into:channel:)` shape for mono→N decorrelation). First conformer `SpectralStereoDiffuse`: anti-correlated xorshift64 streams seeded from `seed` and `seed ^ spectralStereoDiffuseAntiSeedMask`; magnitudes memcpy-passthrough; phases blend toward independent uniform-random targets via shortest-angular-distance; `Atomic<Float>` amount [0, 1]; amount=0 is exact bypass. Legacy `FFTAnalysis` + `IFFTSynthesis` kept fully functional with class-level docstring "Note (Phase 105)" callouts pointing to `SpectralChain.Audio`; hard `@available(*, deprecated)` annotation deferred so internal feature extractors don't generate warnings — legacy-callsite migration is a future tightly-scoped phase. Two review passes — pass 1 caught a fan-out guard bug (`_destinations.count > 1` silently skipped fan-out for N=1 conformers, leaving uninitialised buffers fed to IFFT) + missing class-level `/// - Parameters:` block on `SpectralChain.Audio`; pass 2 clean. 17 new tests across 2 files. | 3779 |
|
||||
| 104c | AUv3 MIDI / UI / Presets / Effect-AU — `LyrebirdAudioUnit.midiHandler: ((MIDIMessage, AUEventSampleTime) -> Void)?` dispatched from `internalRenderBlock` via `_MIDIHandlerStorage` `Atomic<UInt64>` pointer swap (acquire/release; ARC-free on RT). `LyrebirdAUVoicePoolBinding` main-thread adapter wraps a `VoicePool` for note-on/off with subclass-configurable per-voice setup + optional channel filter (RT bridging documented but not bundled — users wire via CoreMIDI or SPSC drain). Effect-AU mode via `open class var lyrebirdInputChannels: Int { 0 }` — when > 0 the AU declares an input bus, `AUv3Driver` pulls one engine block of host input per `engine.processBlock` via `AURenderPullInputBlock` into pre-allocated host-input `AudioBufferList` + contiguous Float backing, copies into engine input buses (`[numOutputChannels, numOutputChannels + numInputChannels)`). New `AUInput.Audio(channel:)` Generator reads from those buses lazily at compute time (defensive zero-fill on out-of-range). New `LyrebirdUI.LyrebirdSynthView` Mirror-driven SwiftUI parameter grid — `@UIParam` slots only (LiveParam skipped — no `@Observable` projected value), `LazyVGrid` of `ParameterKnob`, per-knob range/unit/display-name from optional `[String: LyrebirdAUParameterInfo]` metadata. Factory-preset system: `LyrebirdAUFactoryPreset` value type (`name` + `scalarValues` + `sourceSlots`) returned from `factoryPresetsForLyrebird()` override, bridged into `AUAudioUnit.factoryPresets` + `currentPreset` automatically. Source-slot save/restore: `LyrebirdAUPresetCodable` protocol (`presetTypeID` + `presetEncodedParameters` + `presetMake(from:)`) + `LyrebirdAUPresetSourceRegistry` (`NSLock`-protected) — generators wired into `ParameterNode.source` (Phase 103) round-trip through `fullState` when registered. `fullState` payload restructured: scalars + sources + sourceTypes nested under sub-keys (`lyrebirdAUFullStateScalarKey` / `SourcesKey` / `SourceTypesKey`); legacy flat 104a payload still readable. Three review passes — pass 1 caught `_MIDIHandlerStorage.handler` data race (replaced with atomic pointer swap) + `withUnsafePointer` escape in `_fillInputStagingFromHost` + VoicePoolBinding's "RT-callable" doc lie (rewritten main-thread-only with bridging patterns) + RT string interpolation in AUInput precondition + missing dual `/// - Parameters:` doc blocks; pass 2 caught a `!` force unwrap in `_MIDIHandlerStorage.deinit` + 3 unnamed layout constants in LyrebirdSynthView; pass 3 clean. 25 new tests across 7 files. | 3762 |
|
||||
| 104b | AUv3 Reference Xcode Project — `Demos/LyrebirdAUv3Demo/` ships a working `aumu` AudioUnit v3 plugin (Realized Sound: LyrebirdFM, type/subtype/manufacturer `aumu`/`LBFM`/`RLZS`). Container app target embeds the `.appex` extension into `LyrebirdAUv3Demo.app/Contents/PlugIns/`. Hand-written `project.pbxproj` with both targets, Embed App Extensions copy phase (`dstSubfolderSpec = 13`), `PBXTargetDependency` wiring app → extension, shared `xcscheme` with `parallelizeBuildables="NO"` matching the Xcode 26 SPM convention. The extension target links only the `LyrebirdUI` SPM product — linking `Lyrebird` directly trips Xcode 26's "static library by both X and Y" conflict for the `type: .dynamic` package product. `LyrebirdFM.swift` example synth is a 2-op FM (`@LiveParam carrierFreq/modRatio/modIndex/amp`, mono fanned to stereo). `LyrebirdFMAudioUnit.swift` is 12 lines — `makeSynthesizer()` + `parameterMetadata()`. `LyrebirdFMAudioUnitViewController.swift` is the `AUAudioUnitFactory` (`createAudioUnit(with:)` builds the AU) + empty `AUViewController` stub (104c populates). `Info.plist` declares the `AudioComponents` array with `sandboxSafe = true`, `tags = [Synth]`, factory-via-principal-class. Both targets get `com.apple.security.app-sandbox`; container also gets `user-selected.read-only`. `xcodebuild` Debug + Release verified with `SWIFT_USE_INTEGRATED_DRIVER=NO` + ad-hoc signing; `.appex` correctly embedded. `auval -v aumu LBFM RLZS` + Logic / GarageBand / AUM smoke tests are manual Josh steps (autonomous `pluginkit` registration of an unsigned extension is sandbox-blocked, correctly). New top-level docs: `Demos/LyrebirdAUv3Demo/README.md` (template walkthrough), `docs/auv3-extension-guide.md` (step-by-step "ship your own plugin" guide). Single review pass — pass 1 caught one orphan `Lyrebird` SPM product dep + `BuildIndependentTargetsInParallel = 1` mismatch with scheme's `parallelizeBuildables=NO` + agent-internal memory path leak in the guide + Release launch action; pass 2 clean. No Lyrebird Swift sources changed — tests unchanged at 3737. | 3737 |
|
||||
| 104a | AUv3 Wrapper Infrastructure — headless Swift API bridging `SynthesisEngine` + `SynthesizerBase` into the `AUAudioUnit` contract. `AUv3Driver` (passive `AudioDriver`; engine ref held via `Unmanaged`, no ARC on RT) drives an `AUv3RingBuffer` (per-channel power-of-two ring) to decouple fixed `blockSize` from host-variable `frameCount`. `open class LyrebirdAudioUnit: AUAudioUnit` exposes subclass hooks `makeSynthesizer()` + `parameterMetadata()` + `lyrebirdBlockSize` + `lyrebirdOutputChannels` + `lyrebirdMaxFramesToRender`; builds parameter tree in `init` via Mirror walk (matches `_autoRegisterLiveParams` order); creates a fresh engine in `allocateRenderResources` at host-negotiated sample rate; tears down in `deallocateRenderResources` (synth survives the cycle). `LyrebirdAUParameterMapping` Mirror-driven discovery emits stable `AUParameterAddress` per `@LiveParam` / `@UIParam` slot; `LyrebirdAUParameterInfo` carries per-parameter min/max/unit/displayName/flags overrides (since `@LiveParam` itself has no bounds). `fullState` round-trips scalar `@LiveParam` values under namespaced `lyrebirdAUFullStateKey` — Phase 103 source-slot generators explicitly out of scope (104c). `Package.swift` widens AVFoundation link from iOS-only to all platforms. Headless — no Xcode `.appex` artefact (104b's job). Two review passes — pass 1 caught two stored `AUAudioUnitBusArray!` IUOs (replaced with `?` + guard-fatalError in getters), two public types in one file (`LyrebirdAUParameterEntry` split out), and five `baseAddress!` force unwraps in tests (replaced with `guard let` + `Issue.record`); pass 2 clean. 32 new tests across 4 files. | 3737 |
|
||||
| 102b | Ambisonic Toolkit (FOA binaural decoder) — `FoaDecodeBinaural`: 4-row B-format input → 2-row stereo headphone output via MIMO partitioned-FFT overlap-save convolution against 8 baked rendering filters (4 B-format channels × 2 ears). `FoaBinauralFilters.build(from:)` constructs filters at init by projection-decode summation over all HRIR positions (matching `FoaDecodeProjection` coefficients exactly). Bundled MIT KEMAR full set (710 positions, 512-sample IRs, 44.1 kHz) via `HRIRFile.bundledKemarFull`; user HRIR sets accepted via `HRIRFile.load(contentsOf:)`. Configurable `partitionSize` (power of two, default 256); inherent latency = one partition. `.left`/`.right` channel aliases. All buffers + FFT setups pre-allocated in `init`, freed in `deinit`; no RT allocation. 25 new tests. | 3634 |
|
||||
| 101 | Ambisonic Toolkit (FOA core) — 27 `Foa*` generators in `Sources/Lyrebird/Generators/Ambisonic/`: 20 Group A angle transforms (Rotate/Tilt/Tumble, Focus/Push/Press/Zoom/Direct{X,Y,Z}, DirectO, Asymmetry) via `_FoaAngleBase`; 3 Group B (Dominate{X,Y,Z}) via `_FoaGainBase` (dB cached for skip-when-constant pow); 3 Group C IIR filters (NFC, Proximity, PsychoShelf) with `denormalsToZero` on every feedback var; `FoaPanB` encoder + 3 closed-form decoders (DecodeProjection N-speaker projection, DecodeStereo, DecodeQuad). `FoaMatrix4` 16-tuple `Double` value type + `@inline(__always) foaApply`. Math translated literally from SC3 `AtkUGens.cpp` FILL_*_MATRIX macros. Coexists with `AmbiEncoder1`/`AmbiDecoder1`. Two review passes: pass 1 flagged 5 redundant `calculatedSamples` overrides on `AudioGenerator` conformers (§5 violation — protocol extension already handles segment-serial fan-out caching; bypass concern is `ControlGenerator`-only). All deleted; pass 2 clean. 263 new tests. | 3567 |
|
||||
| 100 | `SpectralFormantShift` — magnitude-envelope-preserving formant shift `SpectralProcessor`. Estimates the smooth envelope of the current frame via `.cepstral` (default, accurate; internal `CepstralEnvelopeEstimator` owns a second real `FFTSetup`, `vvlogf`/`vDSP_fft_zrip` inverse/lifter/forward/`vvexpf`, `2·N` round-trip rescale, `magnitudeFloor = 1e-12`) or `.magnitudeSmoothing(radiusBins:)` (two-pointer box blur), divides it out to whiten, resamples along the bin axis by `shiftRatio` with linear interpolation + one-bin fade past Nyquist, and reapplies. Phase untouched; DC/Nyquist signs preserved. `shiftRatio` `Atomic<Float>` clamped `[0.25, 4.0]`; `1.0` is bypass. Pairs with `SpectralPitchShift` to decouple pitch from formant motion. New public enum `FormantShiftMethod`. 10 new tests. | 3304 |
|
||||
| 99 | Spectral Filtering + Phase Manipulation — seven new public `SpectralProcessor` types operating on polar `SpectralBuffer`: `SpectralBrickwall` (`.lp`/`.hp`/`.bp`/`.br` modes; `vDSP_vclr` outside passband), `SpectralPhaseShift` (`.deg90`/`.deg180`/`.deg270`/`.radians` Hilbert-style rotation; live `radians` retunable), `SpectralGate` (linear + `thresholdDB:` convenience init via shared `dbToAmp`; `floor` ∈ [0,1] hard-gate-to-bypass blend), `SpectralTilt` (pre-computed dB/oct gain table around pivot Hz; DC bin forced to unity), `SpectralBlur` (magnitude box-blur via two-pointer running sum; `_blurOut` allocated init-time; edge bins shrink window), `SpectralDiffuse` (continuous phase randomization 0→1 via `lyrebirdSeedXorshift64(from:mixConstant:)` + named `spectralDiffuseMixConstant`; shortest-angular-distance blend), `SpectralConvolve` (frequency-domain complex multiply with second buffer for cross-synthesis or static IR; either-buffer-invalid → live cleared). Two shared helpers extracted to `Sources/Lyrebird/Spectral/`: `wrapPhasesInPlace` (consumed by refactored `SpectralFreeze` + new processors) and `binFromHz`. All `process` methods open `guard spectral.fftSize == _fftSize else { return }` (no RT string interpolation). Pre-allocated scratch; `Atomic<Float>`/`Atomic<Int>` for live params. New "Spectral Filtering & Phase" section in `docs/stdlib/spectral.md`. 50 new tests. Required five review passes (RT precondition string interp; `dbToAmp` helper adoption; DC-bin proxy fix; shared seed helper adoption; multi-line init format + class-level `/// - Parameters:` blocks; unused `Foundation` imports). | 3294 |
|
||||
| 182 | Pattern facade refactor + Demand* rename — `Pattern<T>` split into thin facade + module-internal `_PatternEngine<Element>` protocol; sequence behaviour moved into `SequencePatternEngine<T>`; exposed via `Pattern.sequence(_:repeats:)` static factory. Old `Pattern.init(values:repeats:)` removed. Four demand-rate sources renamed: `DSequence` → `DemandSequence`, `DRandom` → `DemandRandom`, `DTemporalBrownian` → `DemandTemporalBrownian`, `DTemporalTendency` → `DemandTemporalTendency`. `DemandGenerator` protocol name and `Demand.Audio`/`Demand.Control` puller names unchanged. No new types, no new RT behaviour — foundational phase for the 183-190 Pattern + Demand catalogue expansion. One review-fix pass (single-line init in `SequencePatternEngine` reformatted to multi-line). | 4010 |
|
||||
| 183 | Atomic numeric Pattern sources — seven new `Pattern<Double>` factory methods via `public extension Pattern where T == Double`: `series` (arithmetic), `geometric`, `uniformRandom` (Box-Muller is `gaussian`'s job — `uniformRandom` is `[low, high]` uniform), `brownian` (clamped random walk; `start` defaults to midpoint), `gaussian` (Box-Muller), `cauchy` (inverse-CDF), `beta` (two-Gamma method on `[0, 1]`). Seven new engines in `Sources/Lyrebird/Patterns/Engines/` conform to `_PatternEngine<Double>` (Phase 182). Random engines reuse the file-internal helpers in `Sources/Lyrebird/Distributions/DistributionSampling.swift` (`_sampleUniform` / `_sampleGauss` / `_sampleCauchy` / `_sampleBetaRand`) — same code consumed by `DemandTemporalTendency`. Seeding via `lyrebirdSeedXorshift64(from:)`. `reset()` rewinds only the response counter / position — PRNG state NOT restored (mirrors `DemandRandom` precedent so rhythmic retriggering keeps audible variety). One review-fix pass (4 missing `reset()` tests across the random engines + stale `import Foundation` + missing `isExhausted` assertion + caveman shadowing nit in `Brownian.next()`). 33 new tests across 7 files. | 4042 |
|
||||
| 184 | Discrete-pool Pattern sources + closure escape hatch — four new generic `Pattern<T>` factory methods on `public extension Pattern`: `shuffle` (Fisher-Yates permute once at init, then cycle; same permutation replays on `reset()` — SC `Pshuf` semantics), `nonRepeatingRandom` (random pick avoiding same *index* as previous; index-vs-value caveat documented for duplicate-value pools), `weightedRandom` (selection proportional to weight via cumulative distribution; init preconditions on equal count, finite non-negative weights, positive sum), `closure` (wraps `() -> T?`, latches once nil is returned). Four new engines in `Sources/Lyrebird/Patterns/Engines/` conform to `_PatternEngine<T>` (Phase 182). `reset()` rewinds counter / position / last-pick / latch state but NOT PRNG seed (mirrors `DemandRandom`). One review-fix pass (missing `!_values.isEmpty` guard in `WeightedRandomPatternEngine.next()`, plus caveman nits — `+Infinity` weights via `$0.isFinite` precondition, documented `u < cumulative[i]` strict-less-than fallthrough). 21 new tests across 4 files. | 4063 |
|
||||
| 185 | Length/range Pattern modifiers — four new generic `Pattern<T>` factory methods wrapping any upstream pattern: `repeating` (SC `Pn`; replays `count` times with `reset()` between cycles; `-1` infinite; latches if upstream empty after fresh reset), `limit` (SC `Pfin`; emits at most `count` items returned, not calls made; latches if upstream exhausts first; `count >= 0` precondition), `drop` (SC `Pdrop`; lazy drop on first `next()` then pass through; `count >= 0` precondition), `stutter` (SC `Pstutter`; for each source value, emit it n times where n is the next value from a `Pattern<Int>`; `count <= 0` consumes source but emits nothing; latches when either upstream returns nil while pulling a new pair). Four new engines in `Sources/Lyrebird/Patterns/Engines/` conform to `_PatternEngine<T>` (Phase 182). All `reset()` propagate to wrapped upstream pattern(s). One review-fix pass (two blockers — `RepeatPatternEngine.init` missing `precondition(count >= -1)` allowed any negative to silently run forever; `StutterPatternEngine.next()` returned `_currentValue: T?` directly making invariant violations silently propagate as exhaustion — fixed with defensive guard; also added missing `negativeCountSkipsValue` test). 19 new tests across 4 files. | 4081 |
|
||||
| 186 | Multi-pattern composition — five new factory methods on `public extension Pattern`: `switching` (SC `Pswitch1`; one value per index draw, out-of-range index latches), `concatenate` (sequential play; advances when active sub-pattern returns nil), `roundRobin` (SC `Ppatlace`; ragged patterns drop out individually with dead-slot tracking, latches when all dead), `tuple` (returns `Pattern<[T]>` — different element type from upstream; zips children into size-stable arrays, latches on any child nil), `interleave` (SC `Place`; outer-cycle semantic — each cycle emits one value per sub-list with `outerStep % sublist.count` wrap; empty sub-lists silently dropped; total emit = `lists.count × repeats`; precondition `repeats >= -1`). Five new engines in `Sources/Lyrebird/Patterns/Engines/`; `TuplePatternEngine` declares `Element = [T]` to make the differing return element type explicit. All `reset()` propagate to wrapped upstream pattern(s). Two review-fix passes (pass 1: `RoundRobin` defensive guard off-by-one + `Interleave` multiplication overflow path AND SC `Place` semantic divergence — rewrote engine to match SC exactly, eliminating both issues; pass 2: stale factory doc comment for `Pattern.interleave` still describing old `× maxLen` semantic — rewrote to `× repeats`). 24 new tests across 5 files. | 4105 |
|
||||
| 187 | Map/filter/transform Pattern catalogue — nine new factory methods across two extension blocks. Generic (`public extension Pattern`): `map` (SC `Pcollect`; result element type can differ from upstream), `filter` (SC `Pselect`; documented spin caveat for infinite-source-never-matching-predicate), `reject` (SC `Preject`; routes `FilterPatternEngine` with negated predicate). Numeric (`public extension Pattern where T == Double`): `accumulate` (SC `Paccum` running sum), `difference` (SC `Pdiff`; first value verbatim, subsequent = deltas), `wrap` (SC `Pwrap`; floor-modulo into half-open `[low, high)` with FP-boundary post-clamp; precondition `high > low`), `clip` (SC `Pclip`; clamps to `[low, high]`; precondition `high >= low`), `round` (SC `Pround`; `.toNearestOrAwayFromZero` mode for SC parity; precondition `step > 0`), `smooth` (SC `Psmooth`; one-pole exponential smoother; coefficient clamped to `[0, 1]`; first sample passes through). Five new engines (Map / Filter / Accumulate / Difference / Smooth); stateless transforms (wrap / clip / round) reuse `MapPatternEngine` via closure. `PatternFactories.swift` gained `import Darwin` for `floor()` (matches existing Math/ convention). Closes the Pattern-side of the 183-187 sweep. One Lyrebird review cycle clean; two caveman fix passes (SC `Pround` parity via `.toNearestOrAwayFromZero` — banker's rounding default diverges at half-ties like `2.5 → 2` vs SC `3`; `Pattern.wrap` FP-boundary post-clamp; misleading `low == high` doc removed; stale rounding-mode comment in test aligned). 28 new tests across 9 files. | 4132 |
|
||||
| 188 | Atomic numeric `Demand*` (Pattern-engine wrap consolidation) — four `public final class` `DemandGenerator` conformers built as ~30-line thin wrappers around the corresponding Phase 183 module-internal Pattern engines: `DemandSeries` ↔ `SeriesPatternEngine`, `DemandGeometric` ↔ `GeometricPatternEngine`, `DemandUniformRandom` ↔ `UniformRandomPatternEngine`, `DemandBrownian` ↔ `BrownianPatternEngine`. Each holds a `private let _engine: ConcreteEngineType` (Swift access permits private storage of internal types inside public classes) and forwards `nextValue()` / `reset()` / `isExhausted` in one line. Pattern engines were already RT-safe by construction (pure arithmetic, `xorshift64NextRaw`, no allocation / locks / String) so wrapping is bit-equivalent and saves ~120 lines of algorithm duplication. `DemandBrownian` is plain-parameter complement to `DemandTemporalBrownian`; `DemandUniformRandom` complements pool-based `DemandRandom` by drawing continuous values. `reset()` rewinds counter / position but NOT PRNG seed on random variants. Both Lyrebird + caveman reviews clean on first pass; no fixes. 13 new tests across 4 files. | 4145 |
|
||||
| 189 | Discrete-pool `Demand*` (Pattern-engine wrap consolidation) — three `public final class` `DemandGenerator` conformers wrapping the corresponding Phase 184 module-internal Pattern engines parameterised over `T=Double`: `DemandShuffle` ↔ `ShufflePatternEngine<Double>` (SC `Dshuf`), `DemandNonRepeatingRandom` ↔ `NonRepeatingRandomPatternEngine<Double>` (SC `Dxrand`), `DemandWeightedRandom` ↔ `WeightedRandomPatternEngine<Double>` (SC `Dwrand`). Same thin-wrap pattern as Phase 188 (`private let _engine`, one-line forwards). RT-safety verified: Fisher-Yates at init only, `next()` bodies pure arithmetic + `xorshift64NextRaw` + `_uniform01`, NonRepeating retry-loop bounded for pools ≥ 2, WeightedRandom uses pre-built cumulative array. One review-fix pass (missing `resetClearsExhaustion` test in `DemandShuffleTests`; every Phase 188 peer carries one — added). 12 new tests across 3 files. | 4157 |
|
||||
| 190 | Composition `Demand*` — closes the 182-190 Pattern + Demand catalogue expansion. Three new `public final class` `DemandGenerator` conformers composing other `DemandGenerator` instances directly (departure from the Phase 188-189 Pattern-engine-wrap strategy — Pattern engines take `Pattern<T>` upstream while the demand side composes other DemandGenerators, so direct impl is the cleaner fit): `DemandStutter` (scalar `Int` count, each upstream value emitted N times, `count >= 1` precondition; deliberately scalar count rather than `DemandGenerator`-driven for zero-allocation RT-path), `DemandSwitch` (SC `Dswitch1`; index source is itself a `DemandGenerator`, values floor-cast via `Int(idxRaw.rounded(.down))` so fractional negatives in `(-1.0, 0.0)` latch rather than silently picking `demands[0]`; latches on index/sub-source/out-of-range), `DemandConcatenate` (sequential play; advances on sub-source nil; while-loop correctly skips immediately-exhausted sub-sources). Each ~30 lines, RT-safe by construction. One review-fix pass (`Int(idxRaw)` truncate-toward-zero vs documented "floor-cast" — switched to `Int(idxRaw.rounded(.down))`, added `negativeFractionalIndexFloorsToLatch` test). 13 new tests across 3 files. **Pattern + Demand catalogue totals**: Pattern side = 30 factories on `Pattern<T>` (1 facade `sequence` + 29 new); Demand side = 14 public `DemandGenerator` types (10 new + 2 pre-existing renames + 2 pre-existing temporal). | 4170 |
|
||||
| 196 | Engine Ownership + Lifecycle Safety — set-once atomic binding (`SynthesizerBase._engineBinding: Atomic<UInt>` storing engine pointer bit pattern, two-pass CAS-loop with stale-pointer recovery via `EngineLifecycleCoordinator` registry lookup), opt-in two-tier binding on `LyrebirdBuffer` (exclusive CAS + saturated-subtract read-only refcount); new `engine.identifier: UUID`; new internal `EngineLifecycleCoordinator` singleton holding weak refs keyed by UUID under `NSLock` (lifecycle-lock site around `start`/`stop` deferred to Phase 197 host scope); new public `EngineAddError` enum (`boundToOtherEngine(current:prior: UUID?)`, `doubleAdd`, `pendingQueueFull`, `rebuildFailed` reserved); new internal typed `RetainQueue<T>` centralising the 8 RT-side `Unmanaged.passRetained` enqueue sites in `applyEvent`. Breaking pre-ship: `engine.add(_:)` / `add(_:position:)` / `schedule(_:at:)` / `schedule(_:after:)` Bool → throws, mechanical sweep of ~357 call sites across `Sources/`, `Tests/`, `Demos/`; `LyrebirdEventList.addPreMaster` / `addPostMaster` also throws. Partial-state rollback in `LyrebirdEventList._firstEventSetup` and `VoicePool.init` (committed-array + reverse-`engine.remove` on throw; instance-state writes deferred until full success). New `Tests/LyrebirdTests/MultiEngineRegressionTests.swift` (8 tests) covers two-engines-two-threads-1000-segments, cross-engine + double-add throws, remove + re-add, stale-pointer recovery (with documented address-reuse known limit and skip path), buffer read-only share, buffer exclusive blocks cross-engine, buffer unbind saturation. Docs: `synthesis-engine.md` gains Engine Identity + Ownership Binding sections; `multi-core.md` gains Object Ownership Rules subsection with canonical cross-engine wavetable share pattern; `CLAUDE.md` Interface Conventions gains `engine.add` throws entry. Review skills updated to `swift test --no-parallel` (canonical command per memory). Four `/lyrebird_review` cycles (3 with substantive fixes, 4th clean). 15 commits on `phase-196`. | ~4180 |
|
||||
| 197 | `EngineHost` Multi-Engine Facade — creation-owning `public final class EngineHost` (NSLock-protected role→engine + UUID→role maps); `public enum EngineHostRole` (`.nrtRender`, `.rtOutput(deviceID:)`, `.auxiliary`, `.custom`) — `.rtOutput` device-exclusivity enforced by role-Hashable identity, no separate `_claimedDevices` set; `public enum EngineHostError`; `public struct SynthesisEngineConfig` value carrier (not Sendable — driver field). APIs: `makeEngine(role:config:) throws`, `engine(for:)`/`role(for:)`/`engines`/`roles`/`engineCount` (lookup), `startAll() throws` / `stopAll()` (snapshot-and-iterate-unlocked with rollback on partial-start failure — failing engine captured inside loop's catch, no fragile re-iteration-by-elimination), `adopt(existing:role:) throws` (verifies engine in EngineLifecycleCoordinator). NRT batch render pool: `renderConcurrent(jobs:maxConcurrent:) -> AsyncThrowingStream<NRTResult, Error>` using `withThrowingTaskGroup` + `addTaskUnlessCancelled` seed-and-refill; pool engines inline (not host-registered); `defer { engine.stop() }` post-render; monotonic `DispatchTime` elapsed measurement. New `public struct NRTJob: Sendable` + `public struct NRTResult: Sendable`. **Lock-nesting safety**: host releases `_lock` before touching `EngineLifecycleCoordinator` (which has its own NSLock) — pre-validate under host lock, release, construct/query coordinator outside, re-acquire for commit with second validation. Closes the latent host→coordinator deadlock window. New 220-line `docs/engine/multi-engine-host.md`; `multi-core.md` "See also" updated; `CLAUDE.md` doc-map gains row. New `EngineHostTests.swift` (15 tests) + `MultiEngineRegressionTests.twoEnginesViaHostUniformityContract` proving host path produces identical observable behaviour to direct-ctor. **Five `/lyrebird_review` cycles** (passes 1-4 substantive fixes, pass 5 clean): lock-nesting, snapshot-and-iterate-unlocked, NRTJob numInputChannels silent-discard, magic 44100, false @MainActor doc, missing defer on pre-check (`.duplicateRole` would leak lock causing instance-wide deadlock), stale class-level + role + adopt + multi-engine-host.md docs on `.duplicateDevice` semantics, magic 1_000_000_000.0 literal, `addTaskUnlessCancelled` refill bug, cancellation doc accuracy, NRTJob.numInputChannels doc contradiction, doc-comment merging bug (class Quick Help mis-attributed to file-scope const). 9 commits on `phase-197`. | ~4204 |
|
||||
| 198 | Host Footgun Cleanup — discharges the eleven non-blocking findings (F1–F11) captured in POST_197_FIXES.md after the five-cycle phase-197 review. **F1 code fix**: `EngineHost.renderConcurrent` outer catch distinguishes caller-initiated cancel from a user `build` closure deliberately throwing `CancellationError` via `Task.isCancelled` guard — caller break ends stream cleanly; build-thrown surfaces as stream throw. Two regression tests cover both paths. **F2–F7 docs**: new "Caveats and footguns" section in `docs/engine/multi-engine-host.md` covering NRT pool memory cost (per-engine working-set table, mobile cap recommendation), in-flight files written after cancel (caller-side `Set<URL>` cleanup pattern), cross-job synth-instance sharing (WRONG vs RIGHT examples), cooperative pool starvation (user-side cap; host-side `DispatchQueue` redesign deferred to Phase 199+), `adopt` TOCTOU benign via ARC takeover. **F6 role doc**: `EngineHostRole.swift` `.rtOutput(deviceID:)` rewrote for macOS/iOS asymmetry — iOS deviceID is host-bookkeeping only because RemoteIO doesn't address devices. **F8 source-break**: dropped `.duplicateDevice(UInt32)` case from `EngineHostError` — had no producer (`.rtOutput` Hashable role discriminates by deviceID directly) and forced consumer switches to handle dead code. **F11 code comment**: `// TODO(phase-future, F11)` at `SynthesisEngine.init` call in `makeEngine` documenting non-throwing-init dependency. **Cleanup**: deleted `POST_197_FIXES.md`. F9 + F10 skipped after evaluation. **Two `/lyrebird_review` cycles** — pass 1 found one blocking (CancellationError-from-`build`-vs-caller-cancel ambiguity), pass 2 clean (review-agent no blocking; caveman LGTM on arch + 3 nits applied: rethrow caught CancellationError instance, `>= 1` result count robustness, `onTermination` fires-on-finished comment). 5 commits on `phase-198`. | ~4205 |
|
||||
| 204 | Score / MusicXML demo + CLI templates — `Demos/LyrebirdScoreDemo/` NRT-render demo + `ProjectTemplate.score` + `LyrebirdScore.xctemplate`, all driven by the existing Score DSL + MusicXML round-trip (no new core API). | 4214 |
|
||||
| 222 | `LyrebirdPaths` filesystem conveniences — `projectRoot(from:marker:)` (source-anchored via default-arg `#filePath`, extension-marker match) + sandbox-standard dir accessors; score template writes output via it. | 4516 |
|
||||
| 223 | `Generate` / `PatternNotes` algorithmic score generators — index-driven + `Pattern`-driven `[ScoreElement]` helpers (no new result-builder type); demo/template/docc examples. | 4526 |
|
||||
| 224 | `TimeSignature` + `MeterMap` model — `beatGrouping` primitive (compound/simple/additive), segmented meter map + anacrusis; `Score.meterMap` + `Part.meterMap?` polymeter override. Model-only foundation for the beat-timeline group. | 4544 |
|
||||
| 225 | `ScoreTimeline.fill` + shared `fillRests` — place elements at 0-based quarter beats, auto-fill rests, throw on overlap. Generic helper dedups all three gap-fill sites (Timeline/parser Fraction, MIDI Double); `Fraction: AdditiveArithmetic`. | 4558 |
|
||||
| 226 | `BeatPosition` musical addressing — `.quarters`/`.beat`/`.bar(_:beat:)`/`.bar(_:division:)` resolved to absolute quarters via `MeterMap`; `beat` = felt/conducted pulse (consistent across 4/4, compound 6/8, additive 3+3+2). Anacrusis + mid-piece meter accumulation; meter-layer naming aligned (`pulse*`→`beat*`, `beatUnitQuarters`→`divisionQuarters`). | 4579 |
|
||||
| 227 | `ScoreTimeline` overlap policies (`.trap`/`.truncatePrevious`) + multi-voice (`fillVoices` explicit, `fillAutoVoiced` greedy distribution). Double + BeatPosition overloads; `ScoreTimelineError.invalidVoice`. | 4586 |
|
||||
| 228 | Mid-piece meter-change notation (encoder) — `Score+MusicXMLEncode` consumes `meterMap`: `<time>` on change, per-measure capacity in both loops, `measureCount(atoms:meterMap:)`. Constant-meter byte-identical. Encoder-only (round-trip/anacrusis → 228b). | 4595 |
|
||||
| 228b | Parser meter round-trip — reads all `<time>` → `MeterMap` segments (sort, bar-1 guarantee, dedupe); `annotateBeams` per-measure capacity. Constant-meter byte-identical. Grouping re-inferred (MusicXML carries no grouping). | 4600 |
|
||||
| 228c | Anacrusis (pickup) notation + round-trip — `<measure number="0" implicit="yes">` (capacity = `anacrusis`), full bars 1-based, both loops + `measureCount` + beam accounting; parser recovers `anacrusis`. No-anacrusis byte-identical. | 4611 |
|
||||
| 229 | Polymeter notation — per-part `MeterMap` renders each part against its own meter (independent bar groupings/counts). Tests + `Meter`/`Polymeter`/`Beat timelines` docc + ScoreDemo material samples. Closes the beat-timeline group (223–229). | 4615 |
|
||||
| 230 | Configurable `SynthesisEngine.maxEventsPerBlock` (was hard-coded 256) — the per-block firing + carry-over look-ahead budget; threaded through `SynthesisEngineConfig`/`EngineHost`. RT-safe drop telemetry (`perBlockEventDropCount`) + one-line console warning drained off-RT (`freeWorker`/`stop()`/NRT post-render). `docs/engine/scheduling.md`. | 5456 |
|
||||
| 231 | `LyrebirdRoutineContext.onMain(_:)` — construct `@MainActor` synths inside a `@Sendable` routine/task body (result carried out of the main hop via a box; the shared bridge is `Void`-returning). Threading/isolation documented in `ARCHITECTURE.md` §9.2 + linked from GettingStarted / RoutineTask docs; records why `SynthesizerBase.init` cannot be `nonisolated` (MainActorConsumer fixture). | 5460 |
|
||||
| 232 | Doc sweep + DocC warning ratchet — `scripts/check-docc.sh` gates new DocC warnings against a 62-entry baseline (links pin full signatures; nothing else checks them). Fixed actively-wrong docs (SPSCQueue "rounds up" → traps; nonexistent `schedule(.remove:)`; `Package.swift` docc target), 11 `engine.add` examples missing `try`, and SynthesisEngine init/threading/NRT drift. | 5460 |
|
||||
| 233 | DocC link repair — 62 → 5 warnings. Score API grew params (`spanners:`, `meterMap:`, `normalType:`, `tie:`, `measureBarlines:`…) and DocC links pin full signatures, so every older link broke. Updated links; converted permanently-ambiguous overloads (`Chord`, `fill`, `dbToAmp`) and `internal` symbols to plain code. 5 article/symbol collisions left (DocC bug, IA decision). | 5460 |
|
||||
| 234 | DocC catalog to zero warnings — converted 5 filename-colliding articles (`SendTrigger`, `SpectralChain`, `StepSequencer`, `ValueComputable`, `GeneratorInputProvider`) into documentation extensions, so each guide merges into its symbol's page instead of shadowing the API reference. Baseline now empty; the gate is effectively strict. | 5460 |
|
||||
| 235 | Killed the three hand-copied API mirrors (`SynthesizerProtocol`, `GeneratorProtocol`, `EngineSetup`) — all three had already drifted — replacing them with gate-verified symbol-link tables; removed 75 references to the deleted `LyrebirdFloat`/`LyrebirdInt` types from live docs. | 5460 |
|
||||
| 236 | Doc-example compile harness — `check-doc-snippets.sh` typechecks doc fences against the real API via `swiftc -typecheck` + `#sourceLocation` (failures point at the .md line). Checked set classified by the compiler, not by hand: 323 of 1457. | 5460 |
|
||||
| 237 | Doc-example fallout — fixed `GettingStarted`'s flagship example (`doneAction`/`.freeEnclosing` never existed), made entry examples self-contained (coverage 382/1458; the original `try` rot now fails), harness `throws` wrapper + narrowest-first preambles, and pinned `DistributionKind`'s golden values (3 of 4 had drifted). | 5465 |
|
||||
| 238 | Doc-rot gap pass — extended the DocC gate to `LyrebirdUI` (was entirely unguarded; 0 warnings), implemented the `member` preamble (396 → 426 fences), confirmed zero remaining dead API forms, and established that the residual 1032 fences are continuation fragments no preamble can fix. | 5477 |
|
||||
| 239 | Doc checks in the review process — `check-doc-impact.sh` reports which docs a diff's public-API changes may have invalidated (validated against the commit that caused the original `engine.add` rot). Reports, never fails; suppresses refs the compile guard already covers; wired into `/lyrebird_review` step 2b. | 5477 |
|
||||
| LC-1 | Re-eval readiness signal (`ReevalState`) — `LyrebirdScratchModel` publishes `.empty`/`.clean`/`.dirty`/`.compiling`/`.failed` + `canEvaluate`; view status badge; menu Run gated on `canEvaluate` via `NSMenuItemValidation`. Folded in: `discoverSPMModuleMaps` fixes snippet `import LyrebirdSynth` under bare `swift build`/`swift test` (was Xcode-only). LiveCompile sub-package 47/47. | 5497 (+47 sub-pkg) |
|
||||
| LC-2 | Bare-graph play ergonomics — new public `ClosureSynthesizer` (`SynthesizerBase` from a closure, no `build()` override); `SnippetContext.play { }` forwarder; scratch placeholder leads with the one-liner. | 5502 (+48 sub-pkg) |
|
||||
| LC-3 | Named slots / `Pdef`-style hot-swap — `LiveSession` name→synth slot map (persists across non-additive re-eval); `SnippetContext.play(slot:) { }` replaces one voice in place; `clearSlot`/`clearSlots`; Clear Synths full-reset. | 5502 (+54 sub-pkg) |
|
||||
| LC-4 | On-beat swap (latency masking) — `SwapQuantize` (`.immediate`/`.nextBeat`/`.nextBar`); quantized slot swaps schedule add+remove on the next `LyrebirdClock` boundary (orphan-safe via per-slot add-time); `ReevalState.queued(untilBeat:)`. | 5502 (+63 sub-pkg) |
|
||||
| LC-5 | Module-cache prewarm (time-to-first-sound) — measured: warm compile ~0.12s, cold `.pcm` build ~2–3s; `LiveCompiler.prewarm`/`LiveSession.prewarm()` warm swiftc's default cache off-main at `onAppear`; auto-annotate dropped (measured worthless); dedicated `-module-cache-path` reverted (dlopen cast-crash). | 5502 (+67 sub-pkg) |
|
||||
| LC-6 | Scratch editor syntax highlighting — `ScratchSwiftTokenizer` (pure UTF-16 lexer) + `ScratchSyntaxHighlighter` paints token colors onto `NSTextStorage`; `isRichText`, re-highlight per edit. Completion (SourceKit-LSP) deferred. | 5502 (+80 sub-pkg) |
|
||||
| LC-7 | Session reset valve + snippet-memory accounting — `LiveSession.resetAll()` (panic clear) + `loadedSnippetCount`; dlclose rejected as unsafe (dangling Swift conformance-cache pointers). User-facing memory UI revisit deferred to end of arc. | 5502 (+83 sub-pkg) |
|
||||
|
||||
---
|
||||
|
||||
## Upcoming Phases
|
||||
|
||||
### LiveCompile / Scratch Improvements (LC-1 … LC-8)
|
||||
|
||||
Two tracks. **Track A** (LC-1…LC-7) polishes the existing Swift-compile scratchpad — full Swift power, macOS-only, floors at a few-hundred-ms warm eval (Swift has no supported in-process JIT). **Track B** (LC-8) is a separate bet: an interpreted Generator-graph DSL for instant, no-dylib, no-leak evaluation. iOS reach is a *bonus* of Track B, deprioritized as a driver.
|
||||
|
||||
Cross-cutting note: the async off-main compile path is **already implemented** (`LyrebirdScratchModel.run` awaits `LiveSession.compileAndRunAsync`, gated by `isCompiling`). So the near-term work is readiness signalling + ergonomics, not un-freezing.
|
||||
|
||||
- **LC-1 — Re-eval readiness signal.** ✅ Complete (see `docs/01-completed-working-order.md`). `ReevalState` published by `LyrebirdScratchModel`, view badge, menu Run gating on `canEvaluate`; folded in the `discoverSPMModuleMaps` bare-SPM compile fix.
|
||||
- **LC-2 — Bare-graph play ergonomics (time-to-first-sound).** ✅ Complete (see `docs/01-completed-working-order.md`). Public `ClosureSynthesizer` (core) + `SnippetContext.play { }` forwarder; placeholder leads with the one-liner.
|
||||
- **LC-3 — Named slots + hot-swap (`Pdef` analogue).** ✅ Complete (see `docs/01-completed-working-order.md`). `context.play(slot:) { }` replaces one voice in place; per-name tracking in `LiveSession` (persists across non-additive re-eval); `clearSlot`/`clearSlots`.
|
||||
- **LC-4 — On-beat swap (latency masking).** ✅ Complete (see `docs/01-completed-working-order.md`). `SwapQuantize` + `LiveSession.swapClock`/`swapQuantize`; quantized slot swaps schedule add+remove on the next `LyrebirdClock` boundary (orphan-safe); `ReevalState.queued(untilBeat:)`.
|
||||
- **LC-5 — Module-cache prewarm.** ✅ Complete (see `docs/01-completed-working-order.md`). Measurement showed the cost is purely the cold `.pcm` build; `LiveSession.prewarm()` warms swiftc's default cache in the background at session start (first ⌘↩ ~0.12s vs ~2.2s). Auto-annotate lever dropped — measured to shave nothing at warm.
|
||||
- **LC-6 — Editor UX.** ✅ Syntax highlighting complete (see `docs/01-completed-working-order.md`): `ScratchSwiftTokenizer` + `ScratchSyntaxHighlighter`, re-highlight per edit.
|
||||
- **LC-6b — Code completion (SourceKit-LSP).** ✅ Complete (see `docs/01-completed-working-order.md`). `SourceKitLSPClient` drives the toolchain's `sourcekit-lsp` over stdio; `SnippetCompletionService` resolves snippet symbols via a wrapped-snippet workspace + generated `compile_commands.json`; the editor pops the standard completion window on `.` (Swift mode only). Manual-invoke shortcut is a possible follow-up.
|
||||
- **LC-7 — Dylib leak mitigation.** ✅ Complete (see `docs/01-completed-working-order.md`). Reset valve (`LiveSession.resetAll()` + `loadedSnippetCount`; refcount-gated `dlclose` **rejected as unsafe** — dlopen registers Swift type metadata + conformance records into process-global caches that dlclose leaves dangling → crash even with zero live instances). **User-facing revisit done**: the editor mirrors `loadedSnippetCount` as a "snippets: N" count (orange past a 50-dylib threshold) and shows a warning banner nudging a restart or a switch to the leak-free Graph DSL mode; `snippetMemoryHint` is a unit-tested pure boundary.
|
||||
- **LC-8 — Interpreted Generator-graph DSL (Track B).** ✅ Complete (see `docs/01-completed-working-order.md`). Cross-platform `LyrebirdGraphDSL` target + `DSLBuiltin`/registry code-genned from generator sources (`Tools/DSLRegistryGen`, `scripts/generate-dsl-registry.sh` + `--check`; **304 builtins** = 165 audio + 121 control + 18 buffer). Language: `DSLLexer`→`DSLParser`→AST→`DSLGraphBuilder`→`DSLInterpreter.evaluate` — instant, no swiftc, no dylib, no leak. Rate suffix is the exact Swift name (`OscSin.Control`) for paste-compatibility; buffer resources via a `DSLValue`/`DSLResourceResolver` contract. Editor (8d): status-bar mode toggle in the scratch view runs the buffer through `LiveSession.runGraphDSL` on the same track/slot machinery, DSL errors in the same gutter. (Bus/URL/closure/demand builtins intentionally out of DSL scope — host-level or Swift-path.)
|
||||
|
||||
## Deferred / Future
|
||||
|
||||
- **HOA (Higher-Order Ambisonics)**: Deferred until demand is clear. FOA covered by Phases 101 + 102. HOA decoder requires Accelerate `vDSP_mmulD` matrix multiply path; encoder requires real spherical harmonic basis up to chosen order.
|
||||
- ~~AUv3 plugin export~~ → Phase 104 (split into 104a wrapper infrastructure, 104b Xcode example project + `auval`, 104c MIDI / UI / preset features).
|
||||
- ~~Runtime source-swapping~~ → Phase 103 (planned; replaces obsolete `declareParameter`-era description with `@LiveParam` slot swap via `ParameterNode._sourceSlot` + `Unmanaged<AnyObject>` SPSC queue).
|
||||
- **Single-sample feedback / History** (§7.2): `History.Audio` one-sample delay across blocks for zero-latency feedback. Engine-level change to permit designated feedback arcs in the DAG. Blocked on clear design.
|
||||
- **Hot-reload / live coding** (§9.4): Unblocked by Phase 103 (runtime source-swap). Scope after 103 ships: file-watcher → recompile → swap.
|
||||
- **CV/Gate Eurorack** (§9.3): Language-side only — `LinLin` scaling constants for ES-8/ES-9 ±5V range. Trivial; do inline when convenient.
|
||||
- ~~`.demand` rate (pull-based on-demand generators)~~ → Phase 39 ✓
|
||||
- ~~SIMD optimization pass~~ → Phase 33b ✓
|
||||
- ~~iOS Support~~ → Phases iOS-1–iOS-4 ✓
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,188 @@
|
||||
# 1 · Hello, World
|
||||
|
||||
The programmer's tradition is a program that prints `Hello, World`. Lyrebird's tradition is a program that makes a **tone**. We'll do both — the print first (to prove your toolchain works), then the sound.
|
||||
|
||||
By the end of this page you will have written, built, and run a Swift program that plays a 440 Hz sine wave, and you'll understand every line.
|
||||
|
||||
---
|
||||
|
||||
## Part 0 — Prove Swift works
|
||||
|
||||
Open **Terminal** (Applications → Utilities → Terminal). Check you have a Swift toolchain:
|
||||
|
||||
```sh
|
||||
swift --version
|
||||
```
|
||||
|
||||
You should see something like `Apple Swift version 6.0`. If you get "command not found", install Xcode from the Mac App Store, launch it once, and let it install command-line tools. (Guide 4 covers Xcode in depth.)
|
||||
|
||||
Now the classic:
|
||||
|
||||
```sh
|
||||
echo 'print("Hello, World")' > hello.swift
|
||||
swift hello.swift
|
||||
```
|
||||
|
||||
Swift can run a single file like a script. If you see `Hello, World`, your toolchain is alive. That's the smallest possible Swift program:
|
||||
|
||||
```swift
|
||||
print("Hello, World")
|
||||
```
|
||||
|
||||
- `print(...)` is a function that writes text to the console.
|
||||
- `"Hello, World"` is a **String** — text in double quotes.
|
||||
- No `main`, no boilerplate, no semicolons required. Swift keeps simple things simple.
|
||||
|
||||
---
|
||||
|
||||
## Part 1 — The shape of a Lyrebird program
|
||||
|
||||
A Lyrebird program is a normal Swift program that uses the Lyrebird library. Here is the entire "hello tone", which you'll build up in Part 2:
|
||||
|
||||
```swift
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// The engine owns Core Audio and runs the audio graph.
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
// A synthesizer describes the sound.
|
||||
final class SineTone: SynthesizerBase {
|
||||
override func build() {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.2)
|
||||
let panned: Pan2 = Pan2(input: sine, pan: 0.0)
|
||||
output(bus: 0, source: panned)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try engine.start() // open the audio device
|
||||
try engine.add(SineTone()) // start sounding
|
||||
print("Playing 440 Hz for 3 seconds…")
|
||||
Thread.sleep(forTimeInterval: 3.0)
|
||||
engine.stop() // close the device
|
||||
print("Done.")
|
||||
} catch {
|
||||
print("Something went wrong: \(error)")
|
||||
}
|
||||
```
|
||||
|
||||
Run that and you hear a sine tone for three seconds. Now let's read it.
|
||||
|
||||
---
|
||||
|
||||
## Part 2 — Reading it line by line
|
||||
|
||||
### The imports
|
||||
|
||||
```swift
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
```
|
||||
|
||||
`import` pulls in a module — a bundle of code someone else wrote. `Foundation` is Apple's standard utility library (it's where `Thread.sleep` lives). `LyrebirdSynth` is Lyrebird itself.
|
||||
|
||||
> **The naming quirk:** the Swift Package product is named `Lyrebird`, but the *module* you import is `LyrebirdSynth`. When you set up a project (guide 4) you'll add a dependency on `Lyrebird` — then write `import LyrebirdSynth`. Right for both, even though they don't match.
|
||||
|
||||
### Creating the engine
|
||||
|
||||
```swift
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
```
|
||||
|
||||
- `let engine: SynthesisEngine = ...` declares a **constant** named `engine`, and the `: SynthesisEngine` is a **type annotation** — it states the type explicitly. `let` means "this name won't be reassigned." (Swift also has `var` for values that change — guide 2.)
|
||||
- **Every example in this series annotates the type**, even though Swift can infer it. It documents the code for the reader and, in a large project, makes Swift and Xcode compile faster — the compiler doesn't have to work out each type. Guide 2 explains this properly; for now, read `name: Type = value` as "a constant of this type." (Swift also has `var` for values that change — guide 2.)
|
||||
- `SynthesisEngine(...)` **constructs** an engine. The words before each colon (`blockSize:`, `sampleRate:`, …) are **argument labels** — Swift names its arguments, which makes call sites read like sentences. You can't reorder or omit them.
|
||||
- `blockSize: 512` — the engine processes audio 512 samples at a time. (Lyrebird caps this at 512.)
|
||||
- `sampleRate: 48000` — 48,000 samples per second.
|
||||
- `numOutputChannels: 2` — stereo out. `numInputChannels: 0` — no microphone input.
|
||||
- `driver: CoreAudioDriver()` — talk to the Mac's audio hardware. (iOS uses a different driver; guide 4.)
|
||||
|
||||
### Describing the sound
|
||||
|
||||
```swift
|
||||
final class SineTone: SynthesizerBase {
|
||||
override func build() {
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.2)
|
||||
let panned: Pan2 = Pan2(input: sine, pan: 0.0)
|
||||
output(bus: 0, source: panned)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `final class SineTone: SynthesizerBase` defines a new type called `SineTone` that **inherits from** `SynthesizerBase`. The colon means "is a." Everything a synthesizer needs is in `SynthesizerBase`; you fill in the blanks. `final` means "no one will subclass this further" (good default; guide 2).
|
||||
- `override func build()` — `SynthesizerBase` has an empty `build()` method; you **override** it to supply your graph. Lyrebird calls `build()` for you when the synth is added.
|
||||
- `OscSin.Audio(freq: 440.0, mul: 0.2)` — an audio-rate sine oscillator at 440 Hz, with output multiplied by 0.2 so it isn't harsh. A raw sine at full scale is loud; `mul: 0.2` scales amplitude to 20%.
|
||||
- `Pan2(input: sine, pan: 0.0)` — takes a mono signal and places it in the stereo field. `pan: 0.0` is dead center; `-1` is hard left, `+1` hard right.
|
||||
- `output(bus: 0, source: panned)` — send the panned signal to output bus 0. `Pan2` produces two channels, so this fills both left and right. `output(...)` is a helper `SynthesizerBase` gives you.
|
||||
|
||||
Notice the **data flow**: `sine` feeds `panned` feeds `output`. Each generator is a node; wiring them by passing one as another's `input:` builds a graph. That's the core idea of Lyrebird.
|
||||
|
||||
### Running it
|
||||
|
||||
```swift
|
||||
do {
|
||||
try engine.start()
|
||||
try engine.add(SineTone())
|
||||
print("Playing 440 Hz for 3 seconds…")
|
||||
Thread.sleep(forTimeInterval: 3.0)
|
||||
engine.stop()
|
||||
print("Done.")
|
||||
} catch {
|
||||
print("Something went wrong: \(error)")
|
||||
}
|
||||
```
|
||||
|
||||
- `do { … } catch { … }` is Swift's **error handling**. Some operations can fail; those are marked `try`. If a `try` fails, control jumps to `catch`, where `error` describes what happened. (Guide 2 covers this properly.)
|
||||
- `try engine.start()` opens the audio device. It can fail (device busy, no output) — hence `try`.
|
||||
- `try engine.add(SineTone())` constructs a fresh `SineTone` and hands it to the engine. It starts sounding immediately. `add` can also fail (hence `try`), for example if you add the same instance twice.
|
||||
- `Thread.sleep(forTimeInterval: 3.0)` pauses the program for 3 seconds. Without this, the program would reach the end and exit instantly — you'd hear nothing. Audio runs on its own thread; the main program just needs to stay alive.
|
||||
- `engine.stop()` closes the device cleanly. (Not `try` — stopping doesn't fail.)
|
||||
- `\(error)` inside a string is **string interpolation**: it drops the value of `error` into the text.
|
||||
|
||||
---
|
||||
|
||||
## Part 3 — Make it yours
|
||||
|
||||
Change one thing at a time and re-run. This is the fastest way to build intuition:
|
||||
|
||||
- **Pitch:** `freq: 440.0` → `freq: 220.0` (an octave down) or `freq: 660.0` (a fifth up).
|
||||
- **Loudness:** `mul: 0.2` → `mul: 0.4`. Careful with headphones.
|
||||
- **Position:** `pan: 0.0` → `pan: -1.0` (hard left).
|
||||
- **Duration:** `forTimeInterval: 3.0` → `10.0`.
|
||||
- **A different wave:** `OscSin.Audio` → `OscSawtooth.Audio` (bright, buzzy) or `OscSquare.Audio` (hollow). Same `freq:`/`mul:` arguments.
|
||||
|
||||
Try two oscillators at once for a chord — a taste of what guide 3 makes systematic:
|
||||
|
||||
```swift
|
||||
override func build() {
|
||||
let a: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.15) // A4
|
||||
let e: OscSin.Audio = OscSin.Audio(freq: 660.0, mul: 0.15) // E5
|
||||
let mix: BinaryOpGenerator = a + e // generators add with +
|
||||
output(bus: 0, source: Pan2(input: mix, pan: 0.0))
|
||||
}
|
||||
```
|
||||
|
||||
`a + e` sums two signals — Lyrebird overloads `+` so audio math reads like arithmetic. More of that in guide 3.
|
||||
|
||||
---
|
||||
|
||||
## What you learned
|
||||
|
||||
- A Swift program can be as small as one `print`, or a full Lyrebird patch — same language, same rules.
|
||||
- `import`, `let` with a **type annotation** (`let x: Type = …`), argument labels, `class`/`override`, and `do`/`try`/`catch` — you've now seen Swift's most common building blocks in context.
|
||||
- Lyrebird's shape: **engine → synthesizer → generator graph → output bus**.
|
||||
|
||||
Next: [Swift Basics & Best Practices](02-swift-basics.md) — the same building blocks, slowed down and explained properly, so you can write your own from scratch.
|
||||
@@ -0,0 +1,276 @@
|
||||
# 2 · Swift Basics & Best Practices
|
||||
|
||||
Guide 1 showed a working program. This one slows down and teaches the pieces so you can write your own. Every concept is paired with a Lyrebird use so nothing feels abstract.
|
||||
|
||||
Keep a terminal open. You can test tiny snippets by putting them in a file and running `swift file.swift`, or in Xcode's REPL (`swift` with no arguments gives you an interactive prompt).
|
||||
|
||||
---
|
||||
|
||||
## Values, constants, and variables
|
||||
|
||||
```swift
|
||||
let sampleRate: Int = 48000 // a constant — cannot be reassigned
|
||||
var gain: Double = 0.5 // a variable — can change
|
||||
gain = 0.7 // fine
|
||||
// sampleRate = 44100 // ERROR: cannot assign to a 'let'
|
||||
```
|
||||
|
||||
- **`let` is your default.** Reach for `var` only when a value genuinely changes. Constants are easier to reason about and the compiler catches accidental mutation. This isn't just style — Lyrebird's whole design leans on immutable, copy-per-instance graphs, and `let` reinforces that habit.
|
||||
- **Write the type after the name** — the `: Int` / `: Double` above. That's a **type annotation**, and this series recommends it on *every* binding. Read the next section for why.
|
||||
|
||||
### Annotate your types — a best practice, not just a Lyrebird rule
|
||||
|
||||
Swift *can* infer a binding's type: `let sampleRate = 48000` compiles fine and `sampleRate` is an `Int`. But writing the type explicitly — `let sampleRate: Int = 48000` — is worth the few extra characters, for two concrete reasons:
|
||||
|
||||
1. **Clarity.** Swift is strongly typed; every value has exactly one type, and stating it means a reader (including future-you) never has to trace an expression to learn what they're holding. `let voices: [OscSin.Audio] = …` tells you at a glance.
|
||||
2. **Compile speed.** When you leave the type off, the compiler must *infer* it — and Swift's type inference is expensive, especially for the long, generic, operator-heavy expressions you build with audio graphs (`osc1 * env + osc2 * 0.3`, chains of `map`/`reduce`). Annotating the binding short-circuits that work. On a single file you won't notice; **across a large project it adds up to real build-time savings**, and Xcode's editor feels snappier too.
|
||||
|
||||
So: **annotate every `let` and `var`.** Every example in this series does. The Lyrebird codebase *requires* it for exactly these reasons — you'll see it in all the source — and it's a good habit in any Swift project of size.
|
||||
|
||||
> The rule has a few grammar exceptions where Swift simply won't accept an annotation — closure parameters (`{ x in … }`), tuple destructures (`let (a, b) = pair`), and pattern bindings (`case let .hz(f)`). Guide 3 points them out as they come up. Everywhere else: annotate.
|
||||
|
||||
---
|
||||
|
||||
## The basic scalar types
|
||||
|
||||
| Type | What it is | Example | Lyrebird use |
|
||||
|------|-----------|---------|--------------|
|
||||
| `Int` | whole number | `512` | block size, channel counts, bus numbers |
|
||||
| `Double` | 64-bit decimal | `440.0` | frequency, gain, pan, time in seconds |
|
||||
| `Bool` | true / false | `true` | flags, toggles |
|
||||
| `String` | text | `"hello"` | messages, file paths |
|
||||
|
||||
**Audio is almost always `Double` in Lyrebird.** Frequencies, amplitudes, pan positions, seconds — all `Double`. When you write `440.0` (with the decimal point) you get a `Double`; `440` alone is an `Int`. Mixing them is an error Swift makes you resolve explicitly:
|
||||
|
||||
```swift
|
||||
let freq: Double = 440.0
|
||||
let ratio: Int = 2 // Int
|
||||
// let up = freq * ratio // ERROR: Double * Int
|
||||
let up: Double = freq * Double(ratio) // convert first — OK, = 880.0
|
||||
```
|
||||
|
||||
That strictness feels fussy at first and saves you from whole categories of bugs. Convert deliberately with `Double(...)`, `Int(...)`, etc.
|
||||
|
||||
---
|
||||
|
||||
## Strings and interpolation
|
||||
|
||||
```swift
|
||||
let note: String = "A4"
|
||||
let hz: Double = 440.0
|
||||
print("Note \(note) is \(hz) Hz") // Note A4 is 440.0 Hz
|
||||
```
|
||||
|
||||
`\(...)` drops any value into a string. Great for `print` debugging. (One caution you'll meet later: building strings is forbidden on the real-time audio thread — but in your setup/control code it's free.)
|
||||
|
||||
---
|
||||
|
||||
## Collections
|
||||
|
||||
### Arrays — ordered lists
|
||||
|
||||
```swift
|
||||
let frequencies: [Double] = [440.0, 550.0, 660.0] // a major chord
|
||||
print(frequencies[0]) // 440.0 (indexing starts at 0)
|
||||
print(frequencies.count) // 3
|
||||
```
|
||||
|
||||
### Dictionaries — key/value lookups
|
||||
|
||||
```swift
|
||||
let noteToHz: [String: Double] = ["A4": 440.0, "C5": 523.25]
|
||||
print(noteToHz["A4"]) // Optional(440.0) — note the "Optional"!
|
||||
```
|
||||
|
||||
That `Optional` wrapper is important, and it's next.
|
||||
|
||||
---
|
||||
|
||||
## Optionals — Swift's "maybe there's a value"
|
||||
|
||||
A dictionary lookup might find nothing (`noteToHz["Z9"]`). Rather than crash or return a bogus value, Swift returns an **Optional**: a box that either holds a value or is `nil` (empty). An optional type is written with a trailing `?`:
|
||||
|
||||
```swift
|
||||
let maybeHz: Double? = noteToHz["A4"] // Double? — might be nil
|
||||
```
|
||||
|
||||
You **unwrap** an optional before using it. The safe, idiomatic way is `if let` / `guard let`:
|
||||
|
||||
```swift
|
||||
if let hz: Double = noteToHz["A4"] {
|
||||
print("Found \(hz)") // hz is a plain Double in here
|
||||
} else {
|
||||
print("No such note")
|
||||
}
|
||||
```
|
||||
|
||||
The annotation on an `if let` / `guard let` names the **unwrapped** type — `hz` is a plain `Double` inside the block, not a `Double?`.
|
||||
|
||||
Or supply a fallback with `??`:
|
||||
|
||||
```swift
|
||||
let hz: Double = noteToHz["Z9"] ?? 440.0 // use 440 if the lookup was nil
|
||||
```
|
||||
|
||||
> **The one rule you'll hear repeated:** avoid the force-unwrap operator `!` (as in `noteToHz["A4"]!`). It says "I promise this isn't nil" — and if you're wrong, the program crashes. Lyrebird's coding rules **forbid `!`** entirely, especially on the audio thread where a crash means a dropout or worse. Use `if let`, `guard let`, or `??`. Build the habit now.
|
||||
|
||||
`guard let` is the early-exit form, common at the top of functions:
|
||||
|
||||
```swift
|
||||
func describe(_ note: String) {
|
||||
guard let hz: Double = noteToHz[note] else {
|
||||
print("Unknown note")
|
||||
return // guard MUST leave the scope on failure
|
||||
}
|
||||
print("\(note) = \(hz) Hz") // hz is available for the rest of the function
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Control flow
|
||||
|
||||
```swift
|
||||
// if / else
|
||||
if gain > 1.0 {
|
||||
print("clipping risk")
|
||||
} else {
|
||||
print("safe")
|
||||
}
|
||||
|
||||
// for-in over a range (the loop variable takes an annotation too)
|
||||
for i: Int in 0..<4 { // 0, 1, 2, 3 (..< excludes the end)
|
||||
print(i)
|
||||
}
|
||||
for i: Int in 1...4 { // 1, 2, 3, 4 (... includes the end)
|
||||
print(i)
|
||||
}
|
||||
|
||||
// for-in over a collection
|
||||
for freq: Double in frequencies {
|
||||
print(freq)
|
||||
}
|
||||
|
||||
// while
|
||||
var x: Double = 1.0
|
||||
while x < 8.0 { x *= 2.0 } // 1, 2, 4 → x ends at 8
|
||||
|
||||
// switch — must be exhaustive
|
||||
let wave: String = "saw"
|
||||
switch wave {
|
||||
case "sine": print("smooth")
|
||||
case "saw": print("bright")
|
||||
default: print("something else")
|
||||
}
|
||||
```
|
||||
|
||||
Swift's `switch` is powerful and must cover every case (add `default` for the rest). No fall-through by accident.
|
||||
|
||||
---
|
||||
|
||||
## Functions
|
||||
|
||||
```swift
|
||||
func midiToHz(_ note: Int) -> Double {
|
||||
return 440.0 * pow(2.0, Double(note - 69) / 12.0)
|
||||
}
|
||||
|
||||
let hz: Double = midiToHz(69) // 440.0 (MIDI 69 = A4)
|
||||
```
|
||||
|
||||
- `func name(params) -> ReturnType { … }`.
|
||||
- `_ note: Int` — the `_` means "no argument label at the call site," so you write `midiToHz(69)` not `midiToHz(note: 69)`. Without the `_`, the label is required.
|
||||
- `-> Double` is the return type. A function returning nothing omits the arrow.
|
||||
|
||||
**Argument labels make calls read like prose** — you saw this with `OscSin.Audio(freq: 440.0, mul: 0.2)`. Use them; they're a Swift strength.
|
||||
|
||||
Default values reduce noise at call sites:
|
||||
|
||||
```swift
|
||||
func tone(freq: Double, mul: Double = 0.2) -> OscSin.Audio {
|
||||
return OscSin.Audio(freq: freq, mul: mul)
|
||||
}
|
||||
let a: OscSin.Audio = tone(freq: 440.0) // mul defaults to 0.2
|
||||
let b: OscSin.Audio = tone(freq: 440.0, mul: 0.5) // override it
|
||||
```
|
||||
|
||||
Lyrebird generators lean on defaults heavily — most take `mul:` and `add:` with sensible defaults so you only specify what matters.
|
||||
|
||||
---
|
||||
|
||||
## Error handling
|
||||
|
||||
Some functions can fail. They're marked `throws`, and you must call them with `try` inside a `do/catch`:
|
||||
|
||||
```swift
|
||||
do {
|
||||
try engine.start()
|
||||
try engine.add(SineTone())
|
||||
} catch {
|
||||
print("Engine problem: \(error)")
|
||||
}
|
||||
```
|
||||
|
||||
You saw this in guide 1. The rule: **if the compiler demands `try`, the call can fail** — decide what to do in `catch`. In small programs, printing the error and exiting is fine:
|
||||
|
||||
```swift
|
||||
do {
|
||||
try engine.start()
|
||||
} catch {
|
||||
print("Failed to start: \(error)")
|
||||
exit(1)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Structs vs classes — and why Lyrebird uses classes
|
||||
|
||||
Swift has two ways to make your own types:
|
||||
|
||||
- **`struct`** — a **value type**. Copied when assigned or passed. Two variables never share the same struct.
|
||||
- **`class`** — a **reference type**. Assigning passes a reference; two variables can point at the *same* object. Classes support inheritance (`: SomeBaseClass`).
|
||||
|
||||
```swift
|
||||
struct Point { var x: Double; var y: Double }
|
||||
var p1: Point = Point(x: 0.0, y: 0.0)
|
||||
var p2: Point = p1 // a COPY
|
||||
p2.x = 5.0 // p1.x is still 0
|
||||
|
||||
final class Counter { var n: Int = 0 }
|
||||
let c1: Counter = Counter()
|
||||
let c2: Counter = c1 // SAME object
|
||||
c2.n = 5 // c1.n is now 5 too
|
||||
```
|
||||
|
||||
Rule of thumb: **prefer `struct`** for plain data (a note, a frequency pair, a color). Use **`class`** when you need identity or inheritance.
|
||||
|
||||
**Synthesizers and generators are classes** — that's why guide 1 wrote `final class SineTone: SynthesizerBase`. A synthesizer *is a* `SynthesizerBase` (inheritance), and the engine tracks it by identity. You'll subclass `SynthesizerBase` for every sound you design and `override func build()` to describe its graph.
|
||||
|
||||
Mark classes you don't intend to subclass as `final` — it's clearer and lets the compiler optimize. Lyrebird's own synthesizer examples are all `final`.
|
||||
|
||||
---
|
||||
|
||||
## Best practices checklist
|
||||
|
||||
Carry these from day one — they're the difference between Swift that fights you and Swift that flows:
|
||||
|
||||
1. **`let` by default, `var` only when it changes.**
|
||||
2. **Annotate the type on every `let` and `var`** (`let freq: Double = 440.0`). Clearer for readers, and faster to compile because Swift skips inference — a real win on large projects. The only exceptions are the few places Swift's grammar forbids it (closure params, tuple destructures, pattern bindings).
|
||||
3. **Never force-unwrap with `!`.** Use `if let`, `guard let`, or `?? fallback`. (Non-negotiable in Lyrebird.)
|
||||
4. **Let argument labels do their job** — they make call sites self-documenting.
|
||||
5. **Prefer `struct` for data, `class` for identity/inheritance.** Mark classes `final` unless subclassing is intended.
|
||||
6. **Convert number types explicitly** (`Double(n)`); don't fight the compiler, follow it.
|
||||
7. **Handle errors where they happen** — `do/catch`, don't ignore `try`.
|
||||
8. **Name things for what they mean** — `cutoffHz`, not `f`; `voiceCount`, not `n`.
|
||||
9. **Small functions.** If `build()` gets long, extract helpers (guide 3 shows how).
|
||||
|
||||
The Lyrebird codebase enforces #2 as a hard rule, and adds one more on top: **no magic numbers** — name every non-trivial literal with a `let` (`let killQueueCapacity: Int = 32`). Both are documented in the project's `CLAUDE.md`. Annotation is a good habit in any Swift project; the magic-number rule matters most when you contribute to Lyrebird itself.
|
||||
|
||||
---
|
||||
|
||||
## What you learned
|
||||
|
||||
You can now read and write the Swift that Lyrebird programs are made of: values, types, optionals, control flow, functions, errors, and the struct/class distinction — plus the habits that keep it clean.
|
||||
|
||||
Next: [Types & Functional Programming](03-types-and-functional.md) — Swift's type system in depth and the functional tools (`map`, `filter`, closures) that make building synthesis graphs elegant.
|
||||
@@ -0,0 +1,272 @@
|
||||
# 3 · Types & Functional Programming
|
||||
|
||||
Swift's type system and its functional tools are exactly the parts that make Lyrebird pleasant. Instead of hand-wiring twelve oscillators, you *describe* twelve oscillators and let Swift build them. This guide connects Swift's types and functional style directly to synthesis.
|
||||
|
||||
---
|
||||
|
||||
## Part 1 — Swift's type system, the parts that matter here
|
||||
|
||||
### Type annotations — write them, especially here
|
||||
|
||||
Guide 2 made the case; this guide is where it pays off. Swift *can* infer a binding's type, so both of these compile:
|
||||
|
||||
```swift
|
||||
let freq = 440.0 // inferred Double — works, but don't
|
||||
let freq: Double = 440.0 // annotated — do this
|
||||
```
|
||||
|
||||
**Always annotate.** Two reasons, and both bite harder in this guide's territory:
|
||||
|
||||
- **Clarity.** The expressions you're about to build — `carrier * tremolo`, `voices.reduce(0.0) { $0 + $1 }`, chained `map`/`filter` — produce types that aren't obvious at a glance (`BinaryOpGenerator`, `GeneratorArray`, `any ValidGeneratorInput`). The annotation tells the reader exactly what they're holding.
|
||||
- **Compile speed.** Swift's type inference is *most* expensive on exactly these long, generic, operator-heavy graph expressions. Annotating the binding short-circuits the inference work. One file won't matter; a large project full of synth graphs will feel the difference, and so will the Xcode editor.
|
||||
|
||||
Every example below is annotated. The only spots left un-annotated are the three where Swift's grammar forbids it — **closure parameters** (`{ x in … }`), **tuple destructures** (`let (a, b) = pair`), and **pattern bindings** (`case let .hz(f)`) — all of which appear in this guide and are flagged where they do.
|
||||
|
||||
### Enums — a fixed set of named choices
|
||||
|
||||
An `enum` is one of a closed list of cases. Perfect for a mode, a waveform choice, a rate:
|
||||
|
||||
```swift
|
||||
enum Waveform {
|
||||
case sine, saw, square, triangle
|
||||
}
|
||||
|
||||
func makeOsc(_ w: Waveform, freq: Double) -> any AudioGenerator {
|
||||
switch w {
|
||||
case .sine: return OscSin.Audio(freq: freq)
|
||||
case .saw: return OscSawtooth.Audio(freq: freq)
|
||||
case .square: return OscSquare.Audio(freq: freq)
|
||||
case .triangle: return OscTriangle.Audio(freq: freq)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The compiler forces the `switch` to handle every case — add a new waveform and it *tells* you every place that needs updating. That's the safety enums buy. Lyrebird uses them widely (rate kinds, distribution kinds, error kinds).
|
||||
|
||||
Enums can carry values, too:
|
||||
|
||||
```swift
|
||||
enum Pitch {
|
||||
case hz(Double) // raw frequency
|
||||
case midi(Int) // MIDI note number
|
||||
}
|
||||
|
||||
func frequency(of p: Pitch) -> Double {
|
||||
switch p {
|
||||
case .hz(let f): return f
|
||||
case .midi(let n): return 440.0 * pow(2.0, Double(n - 69) / 12.0)
|
||||
}
|
||||
}
|
||||
|
||||
frequency(of: .midi(69)) // 440.0
|
||||
frequency(of: .hz(500.0)) // 500.0
|
||||
```
|
||||
|
||||
### Protocols — "any type that can do X"
|
||||
|
||||
A **protocol** is a contract: a set of capabilities a type promises to provide. This is the backbone of Lyrebird's design. You've already used several without naming them:
|
||||
|
||||
- `Generator` — anything that produces samples (oscillators, filters, effects).
|
||||
- `AudioGenerator` / `ControlGenerator` — generators that run at audio rate vs. control (block) rate.
|
||||
- `ValidGeneratorInput` — anything you can pass as a generator's input.
|
||||
|
||||
That last one is why you can write **any** of these as a `freq:` argument:
|
||||
|
||||
```swift
|
||||
OscSin.Audio(freq: 440.0) // a Double is a ValidGeneratorInput
|
||||
OscSin.Audio(freq: 440) // an Int is too
|
||||
OscSin.Audio(freq: someOtherOscillator) // a Generator is too — that's FM!
|
||||
```
|
||||
|
||||
`freq:` accepts `any ValidGeneratorInput`. A literal number gives a fixed frequency; passing another generator means that generator *modulates* the frequency. One protocol, three behaviors, no overloads to memorize.
|
||||
|
||||
The keyword `any` (as in `any AudioGenerator`, `any ValidGeneratorInput`) means "some value whose exact type I don't need to name, as long as it satisfies this protocol." You'll type it often.
|
||||
|
||||
### Operator overloading — audio math reads like math
|
||||
|
||||
Lyrebird defines `+ - * /` on generators, so signal processing looks like arithmetic:
|
||||
|
||||
```swift
|
||||
let carrier: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||||
let tremolo: OscSin.Audio = OscSin.Audio(freq: 5.0, mul: 0.5, add: 0.5) // 5 Hz, range 0…1
|
||||
let wobbled: BinaryOpGenerator = carrier * tremolo // amplitude modulation
|
||||
let mixed: BinaryOpGenerator = wobbled + noiseLayer // sum two signals
|
||||
```
|
||||
|
||||
Note the annotations: `carrier * tremolo` and `wobbled + noiseLayer` both produce a `BinaryOpGenerator` — the type Lyrebird's overloaded `*` and `+` return. Writing it out means you (and the compiler) don't have to work it out.
|
||||
|
||||
`carrier * tremolo` isn't multiplying two numbers — it builds a new generator that multiplies the two signals sample by sample. The result is itself a `Generator`, so you keep composing. This is the single most Swift-flavored thing about Lyrebird, and it comes straight from operator overloading.
|
||||
|
||||
---
|
||||
|
||||
## Part 2 — Closures, the gateway to functional style
|
||||
|
||||
A **closure** is a block of code you can pass around like a value — an anonymous function. Full form:
|
||||
|
||||
```swift
|
||||
let double: (Double) -> Double = { x in
|
||||
return x * 2.0
|
||||
}
|
||||
double(21.0) // 42.0
|
||||
```
|
||||
|
||||
The binding's type is `(Double) -> Double` — "takes a Double, returns a Double." Because we annotated it, the closure's own parameter `x` is inferred (closure parameters are one of the three places you *can't* write an annotation). Swift lets you shrink closures aggressively. When the type is known from context, you can drop the parameter types, the `return`, and even name parameters positionally with `$0`, `$1`:
|
||||
|
||||
```swift
|
||||
// These are the same closure, progressively shortened:
|
||||
{ (x: Double) -> Double in return x * 2.0 }
|
||||
{ x in x * 2.0 }
|
||||
{ $0 * 2.0 }
|
||||
```
|
||||
|
||||
`$0` is "the first argument." This terse form is everywhere in Swift and in Lyrebird — you saw it already:
|
||||
|
||||
```swift
|
||||
let oscs: GeneratorArray = expand([440.0, 880.0]) { OscSin.Audio(freq: $0) }
|
||||
// └── a closure: "given a frequency $0, make an oscillator"
|
||||
```
|
||||
|
||||
When a closure is the **last** argument, it moves outside the parentheses (trailing-closure syntax) — that's why `expand([...]) { … }` has the braces hanging off the end.
|
||||
|
||||
---
|
||||
|
||||
## Part 3 — `map`, `filter`, `reduce` on collections
|
||||
|
||||
These three functions replace most `for` loops in idiomatic Swift, and they shine when generating synthesis material.
|
||||
|
||||
### `map` — transform every element
|
||||
|
||||
```swift
|
||||
let midiNotes: [Int] = [60, 64, 67, 71] // a Cmaj7 chord
|
||||
let freqs: [Double] = midiNotes.map { midiToHz($0) } // → [261.6, 329.6, 392.0, 493.9]
|
||||
```
|
||||
|
||||
`map` runs the closure on each element and collects the results into a new array. No loop, no mutable accumulator, no index bookkeeping.
|
||||
|
||||
### `filter` — keep the elements that pass a test
|
||||
|
||||
```swift
|
||||
let audible: [Double] = freqs.filter { $0 < 20000.0 } // drop anything above hearing
|
||||
```
|
||||
|
||||
### `reduce` — combine everything into one value
|
||||
|
||||
```swift
|
||||
let total: Double = freqs.reduce(0.0) { $0 + $1 } // sum
|
||||
// or the shorthand:
|
||||
let total2: Double = freqs.reduce(0.0, +)
|
||||
```
|
||||
|
||||
`reduce` starts from an initial value (`0.0`) and folds each element in. `$0` is the running result, `$1` the current element.
|
||||
|
||||
### Chaining them
|
||||
|
||||
```swift
|
||||
let detuned: [Double] = midiNotes
|
||||
.map { midiToHz($0) } // notes → frequencies
|
||||
.map { $0 * 1.003 } // detune each up ~5 cents
|
||||
.filter { $0 < 8000.0 } // drop the highest partials
|
||||
```
|
||||
|
||||
Each step is a small, obvious transformation. Read top to bottom, it's a pipeline.
|
||||
|
||||
---
|
||||
|
||||
## Part 4 — Putting it together in a Synthesizer
|
||||
|
||||
Here's where functional style pays off. A chord synthesizer, built from an array of MIDI notes — no matter how many notes, the code is the same length:
|
||||
|
||||
```swift
|
||||
final class Chord: SynthesizerBase {
|
||||
// The notes to play. Change this array; the graph adapts.
|
||||
let notes: [Int] = [60, 64, 67, 71] // Cmaj7
|
||||
|
||||
override func build() {
|
||||
// 1. Notes → frequencies (map).
|
||||
let freqs: [Double] = notes.map { midiToHz($0) }
|
||||
|
||||
// 2. Frequencies → oscillators, one per note. Quieter as the chord grows.
|
||||
let level: Double = 0.2 / Double(freqs.count)
|
||||
let voices: [OscSin.Audio] = freqs.map {
|
||||
OscSin.Audio(freq: $0, mul: level)
|
||||
}
|
||||
|
||||
// 3. Sum all voices to a single mono signal (reduce, starting from silence).
|
||||
let mix: any ValidGeneratorInput = voices.reduce(0.0) { $0 + $1 }
|
||||
|
||||
// 4. Center it and send to output.
|
||||
output(bus: 0, source: Pan2(input: mix, pan: 0.0))
|
||||
}
|
||||
|
||||
// MIDI note number → frequency in Hz.
|
||||
func midiToHz(_ note: Int) -> Double {
|
||||
return 440.0 * pow(2.0, Double(note - 69) / 12.0)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Read step 3 carefully: `voices.reduce(0.0) { $0 + $1 }` starts from the scalar `0.0` and adds each oscillator in turn using Lyrebird's overloaded `+`. The result is a generator that sums the whole chord. Add a note to `notes` and everything downstream just works.
|
||||
|
||||
### Multichannel with `expand`
|
||||
|
||||
If instead of *mixing* the notes you want each on its **own output channel**, Lyrebird gives you `expand`, the generator-graph cousin of `map`:
|
||||
|
||||
```swift
|
||||
override func build() {
|
||||
let freqs: [Double] = notes.map { midiToHz($0) }
|
||||
// One generator per channel: channel 0 = first note, channel 1 = second, …
|
||||
let spread: GeneratorArray = expand(freqs) { OscSin.Audio(freq: $0, mul: 0.15) }
|
||||
output(bus: 0, source: spread)
|
||||
}
|
||||
```
|
||||
|
||||
`expand(inputs) { factory }` is `map` for building a multichannel `GeneratorArray`: it applies the factory closure to each input and bundles the results into one channel-per-element generator. Same mental model as `map`, tuned for the audio graph.
|
||||
|
||||
---
|
||||
|
||||
## Part 5 — Value types keep synthesizers safe
|
||||
|
||||
Recall from guide 2: `struct` is a value type, copied on assignment. Lyrebird leans on this. When the engine runs your synthesizer, it works with a **copy of the graph per instance** — no two playing voices share mutable state, which is what makes polyphony safe on the audio thread.
|
||||
|
||||
You benefit by keeping your *own* data in `struct`s and `let`s. A little value type to bundle note parameters:
|
||||
|
||||
```swift
|
||||
struct VoiceSpec {
|
||||
let freq: Double
|
||||
let amp: Double
|
||||
let pan: Double
|
||||
}
|
||||
|
||||
let specs: [VoiceSpec] = [
|
||||
VoiceSpec(freq: 220.0, amp: 0.2, pan: -0.5),
|
||||
VoiceSpec(freq: 440.0, amp: 0.2, pan: 0.5),
|
||||
]
|
||||
```
|
||||
|
||||
Then drive the graph from data:
|
||||
|
||||
```swift
|
||||
override func build() {
|
||||
let voices: [any ValidGeneratorInput] = specs.map { spec in
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: spec.freq, mul: spec.amp)
|
||||
return Pan2(input: osc, pan: spec.pan)
|
||||
}
|
||||
// Two Pan2 outputs, each already stereo — sum them.
|
||||
let mix: any ValidGeneratorInput = voices.reduce(0.0) { $0 + $1 }
|
||||
output(bus: 0, source: mix)
|
||||
}
|
||||
```
|
||||
|
||||
**Data describes the sound; `map` turns data into graph.** That separation — a plain array of specs, a functional transform into generators — is the pattern you'll reuse constantly.
|
||||
|
||||
---
|
||||
|
||||
## What you learned
|
||||
|
||||
- Swift's **enums, protocols, and operator overloading** are the machinery behind Lyrebird's expressive API — `any ValidGeneratorInput`, `freq:` accepting a modulator, `a + b` mixing signals.
|
||||
- **Closures** (`{ $0 * 2 }`) and the **functional trio** (`map`, `filter`, `reduce`) let you generate synthesis material from data with no loops.
|
||||
- `expand` is `map` for building multichannel generators.
|
||||
- Keeping your parameters in **value types** mirrors how Lyrebird keeps voices independent.
|
||||
- **Annotating every binding** earns the most here: graph expressions have non-obvious types, and inference on them is the slowest thing you can ask the compiler to do.
|
||||
|
||||
Next: [Xcode, Packages & Debugging](04-xcode-and-packages.md) — moving from single files to real projects: the IDE, adding Lyrebird as a package, Debug vs Release, and breakpoints.
|
||||
@@ -0,0 +1,260 @@
|
||||
# 4 · Xcode, Packages & Debugging
|
||||
|
||||
So far you've run single `.swift` files. Real work happens in **projects**: multiple files, dependencies like Lyrebird, a build configuration, and a debugger. This guide covers the tools — Xcode and Swift Package Manager — plus how to add Lyrebird, how to set up Debug vs Release, and how to debug a running synth without breaking the audio.
|
||||
|
||||
---
|
||||
|
||||
## Part 1 — Two ways to build, and when to use each
|
||||
|
||||
You have two toolchains, and they're two views of the *same* project:
|
||||
|
||||
| | Swift Package Manager (CLI) | Xcode (IDE) |
|
||||
|---|---|---|
|
||||
| Invoked with | `swift build`, `swift run`, `swift test` | GUI: pick a scheme, press ▶ |
|
||||
| Best for | quick iteration, servers, CI, headless CLI synths | editing with autocomplete, the visual debugger, GUI/iOS apps |
|
||||
| Debugger | `lldb` on the command line | graphical breakpoints, variable inspector |
|
||||
|
||||
They read the **same `Package.swift`**. Use the CLI for fast loops on a command-line piece; use Xcode when you want autocomplete, breakpoints you can click, or you're building a windowed/iOS app. Learn both — they complement each other.
|
||||
|
||||
### Installing Xcode
|
||||
|
||||
Install **Xcode** from the Mac App Store (it's large — several GB). Launch it once so it finishes installing components. That also gives you the command-line tools (`swift`, `xcodebuild`, `lldb`). Lyrebird needs **Xcode 16+, macOS 15+**.
|
||||
|
||||
Verify from Terminal:
|
||||
|
||||
```sh
|
||||
swift --version # expect Apple Swift version 6.0
|
||||
xcode-select -p # should print a path, not an error
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Part 2 — What a Swift package is
|
||||
|
||||
A **Swift package** is a folder with a `Package.swift` manifest describing what to build and what it depends on. The manifest *is* Swift code:
|
||||
|
||||
```swift
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "MyPiece",
|
||||
platforms: [.macOS(.v15)],
|
||||
dependencies: [
|
||||
// Lyrebird, fetched from its git host:
|
||||
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"),
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "MyPiece",
|
||||
dependencies: [
|
||||
.product(name: "Lyrebird", package: "Lyrebird"),
|
||||
// add this line only if you use the GUI module:
|
||||
// .product(name: "LyrebirdUI", package: "Lyrebird"),
|
||||
]
|
||||
),
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
Key ideas:
|
||||
|
||||
- **`dependencies`** lists packages you rely on. `from: "1.0.0"` means "1.0.0 or any compatible later version." SwiftPM downloads and pins them for you.
|
||||
- **`targets`** are the things *you* build. An `.executableTarget` produces a runnable program (it needs a `main.swift`); a `.testTarget` holds tests; a `.library` target is reusable code.
|
||||
- A target lists which **products** of a dependency it uses. Lyrebird vends `Lyrebird` (the core), `LyrebirdUI` (SwiftUI controls), and a few others.
|
||||
|
||||
> One inconsistency you may notice: `let package = Package(…)` here has **no** type annotation, even though guide 2 told you to annotate everything. `Package.swift` is a manifest, and every Swift package — Lyrebird's included — writes that line un-annotated by convention. It's the one place to follow the crowd. In your actual *program* code (`main.swift`, your synthesizers), keep annotating.
|
||||
|
||||
> **The naming quirk, one more time:** you depend on the product `Lyrebird`, but in your Swift files you write `import LyrebirdSynth`. Product name ≠ module name. This trips up everyone once; now it won't trip up you.
|
||||
|
||||
### The fastest way to scaffold: the `lyrebird` CLI
|
||||
|
||||
Lyrebird ships a command-line tool that writes the whole package for you:
|
||||
|
||||
```sh
|
||||
lyrebird new MyPiece # creates MyPiece/ with Package.swift + main.swift
|
||||
cd MyPiece
|
||||
lyrebird run # build and play
|
||||
```
|
||||
|
||||
That's the shortest path and it generates a correct `Package.swift`. See [`docs/tooling/cli-guide.md`](../tooling/cli-guide.md) for the full CLI. If you'd rather do it by hand, the manifest above is all you need.
|
||||
|
||||
### Using a local Lyrebird checkout
|
||||
|
||||
If you've cloned Lyrebird next to your project (common while learning, so you can read the source), depend on it by **path** instead of URL:
|
||||
|
||||
```swift
|
||||
dependencies: [
|
||||
.package(path: "../Lyrebird"), // relative to your Package.swift
|
||||
],
|
||||
```
|
||||
|
||||
This is exactly what the bundled demos do — look at `Demos/LyrebirdQuickstartDemo/Package.swift`.
|
||||
|
||||
---
|
||||
|
||||
## Part 3 — Opening and running in Xcode
|
||||
|
||||
Two ways to open a package in Xcode:
|
||||
|
||||
- **A package folder:** `File → Open…` and select the folder containing `Package.swift` (or run `xed .` from inside it in Terminal). Xcode reads the manifest, resolves dependencies, and you're ready.
|
||||
- **A workspace/project:** the Lyrebird demos ship a `Lyrebird.xcworkspace` — open *that*, not an individual `.xcodeproj`, so all demos share the one local package.
|
||||
|
||||
Once open:
|
||||
|
||||
1. **Pick a scheme** in the toolbar (top, next to the ▶/■ buttons). A **scheme** says *what to run* — e.g. `MyPiece`, or `LyrebirdQuickstartDemo`. For a package, Xcode makes one scheme per executable/test target.
|
||||
2. **Pick a destination** — "My Mac" for a macOS piece, or a connected iPhone / simulator for iOS. (iOS simulators produce no audio; use a real device for sound.)
|
||||
3. **Press ▶ (Run)** or `⌘R`. Xcode builds and launches. Output appears in the **console** at the bottom.
|
||||
4. **Press ■ (Stop)** or `⌘.` to end it.
|
||||
|
||||
**Targets vs. schemes, briefly:** a *target* is a buildable unit defined in `Package.swift` (your executable, the test bundle). A *scheme* is a saved recipe for building and running one or more targets in a chosen configuration. You edit build behavior (including Debug vs Release, next) by editing the scheme.
|
||||
|
||||
The CLI equivalents, for reference:
|
||||
|
||||
```sh
|
||||
swift build # compile (Debug by default)
|
||||
swift run # build + run
|
||||
swift test # run tests
|
||||
swift run -c release # build + run optimized (see below)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Part 4 — Debug vs Release configurations
|
||||
|
||||
Every build uses a **configuration**. Two ship by default:
|
||||
|
||||
| | **Debug** | **Release** |
|
||||
|---|---|---|
|
||||
| Optimization | none (`-Onone`) | full (`-O`) |
|
||||
| Speed | slow | fast (often 5–20× on DSP) |
|
||||
| Symbols / debug info | full | present, but code is reordered/inlined |
|
||||
| Safety checks | on | some elided |
|
||||
| Use for | editing, breakpoints, stepping | performance, real audio, shipping |
|
||||
|
||||
### Why this matters *a lot* for audio
|
||||
|
||||
Lyrebird runs your generator graph on a real-time thread that must finish each 512-sample block before the deadline. **Debug builds are unoptimized and can be 10× slower** — heavy patches that run cleanly in Release will glitch, crackle, or drop out in Debug. Two consequences:
|
||||
|
||||
- When something *sounds* wrong but *is* logically correct, **try a Release build before assuming a bug** — you may just be starved for CPU.
|
||||
- Any performance measurement in Debug is meaningless. Lyrebird's own benchmark docs say it outright: *"Always run with `-c release`; debug builds give meaningless numbers."*
|
||||
|
||||
So: **debug logic in Debug, judge sound and speed in Release.**
|
||||
|
||||
### Switching configuration — command line
|
||||
|
||||
```sh
|
||||
swift run # Debug
|
||||
swift run -c release # Release
|
||||
swift build -c release # Release build only
|
||||
```
|
||||
|
||||
### Switching configuration — Xcode
|
||||
|
||||
Xcode's ▶ Run button uses your scheme's **Run** action, which defaults to **Debug**. To change it:
|
||||
|
||||
1. Menu **Product → Scheme → Edit Scheme…** (or click the scheme name → *Edit Scheme…*).
|
||||
2. Select the **Run** action in the left column.
|
||||
3. On the **Info** tab, set **Build Configuration** to **Release** (or back to **Debug**).
|
||||
4. Close. Now ▶ builds that configuration.
|
||||
|
||||
A common workflow is to leave **Run = Debug** (so breakpoints and stepping work well) and switch to **Release** only when you want to hear the patch at full performance or profile it. The **Profile** action (`⌘I`, opens Instruments) already defaults to Release for exactly this reason.
|
||||
|
||||
### Per-target build settings
|
||||
|
||||
If you need finer control (a custom optimization flag, a compilation condition), a SwiftPM target can carry settings in `Package.swift`:
|
||||
|
||||
```swift
|
||||
.executableTarget(
|
||||
name: "MyPiece",
|
||||
dependencies: [ .product(name: "Lyrebird", package: "Lyrebird") ],
|
||||
swiftSettings: [
|
||||
// Example: define a flag you can check with #if in code.
|
||||
.define("VERBOSE_LOGGING", .when(configuration: .debug)),
|
||||
// Example: force optimization even in Debug for a hot target.
|
||||
.unsafeFlags(["-Ounchecked"], .when(configuration: .release)),
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
Then in code:
|
||||
|
||||
```swift
|
||||
#if VERBOSE_LOGGING
|
||||
print("Voice started at \(freq) Hz") // compiled in only for Debug
|
||||
#endif
|
||||
```
|
||||
|
||||
`#if … #endif` is **conditional compilation** — the code inside only exists in builds where the flag is set. Great for debug-only logging that costs nothing in Release. (You'll also see `#if os(iOS)` / `#if os(macOS)` in Lyrebird for platform-specific code.)
|
||||
|
||||
---
|
||||
|
||||
## Part 5 — Breakpoints and debugging
|
||||
|
||||
### Setting a breakpoint
|
||||
|
||||
In Xcode, click the **gutter** (the margin left of the line numbers) next to a line. A blue arrow appears — that's a breakpoint. Run in **Debug**; when execution reaches that line it **pauses**, and you can:
|
||||
|
||||
- **Inspect variables** in the Variables View (bottom-left), or hover over a value in the editor.
|
||||
- **Step** with the toolbar: *Step Over* (`F6`, run this line), *Step Into* (`F7`, descend into the call), *Step Out* (`F8`, finish the current function), *Continue* (`⌃⌘Y`, resume).
|
||||
- **Evaluate expressions** in the console with `po` (print object) or `p`:
|
||||
|
||||
```
|
||||
(lldb) po freqs
|
||||
(lldb) po engine.sampleRate
|
||||
(lldb) p 440.0 * 2
|
||||
```
|
||||
|
||||
### Conditional and action breakpoints
|
||||
|
||||
Right-click a breakpoint → **Edit Breakpoint…** to:
|
||||
|
||||
- Add a **condition** — pause only when it's true, e.g. `note > 100`. Invaluable when a loop runs thousands of times and only one iteration is wrong.
|
||||
- Add an **action** like *Log Message* or *Debugger Command*, optionally with **"Automatically continue"** — so it logs without stopping. This is a print statement you can add/remove without editing and rebuilding.
|
||||
|
||||
### The audio-thread rule — do NOT breakpoint the render callback
|
||||
|
||||
This is the one debugging pitfall unique to real-time audio, and it's important:
|
||||
|
||||
> **Never set a breakpoint inside a Generator's `_computeSamples` / render path.** That code runs on the real-time audio thread. Pausing it freezes audio production entirely — the device underruns, you get a horrible glitch or silence, and the state you're inspecting is already unrepresentative. The same goes for `print` on that thread: allocating a `String` mid-render can itself cause a dropout. (This is why Lyrebird's rules forbid `print`, allocation, and locks on the RT thread.)
|
||||
|
||||
Where you **can** freely breakpoint and print: your **setup and control code** — `build()`, `main.swift`, parameter changes, scheduling, anything that runs on the main thread before or between audio blocks. Break in `build()` to inspect the graph you're wiring; that's on the main thread and perfectly safe.
|
||||
|
||||
### Debugging what the audio thread is doing
|
||||
|
||||
Since you can't stop the render thread, Lyrebird gives you non-blocking tools instead:
|
||||
|
||||
- **`SynthesizerBase.debugTap`** — a per-instance, RT-safe tap for observing a live voice's output without breaking timing. See [`Sources/Lyrebird/Lyrebird.docc/Debugging.md`](../../Sources/Lyrebird/Lyrebird.docc/Debugging.md) for this and LLDB recipes for inspecting a live generator.
|
||||
- **`GeneratorBase.debugTag`** — label a generator so you can find it in the debugger.
|
||||
- The **message center** and **node-tree mirror** (`docs/diagnostics-guide.md`) surface what the engine is doing as inspectable, non-RT data.
|
||||
|
||||
For ordinary Swift logic bugs — a wrong frequency table, an off-by-one in a pattern, an optional that's unexpectedly `nil` — regular breakpoints in your main-thread code are exactly the right tool.
|
||||
|
||||
### Crashes and the "force-unwrap" reminder
|
||||
|
||||
If your program crashes with `Fatal error: Unexpectedly found nil while unwrapping an Optional`, you (or code you called) used `!` on a `nil` optional — the exact thing guide 2 warned against. The debugger stops on the offending line; read it, then replace the `!` with `if let` / `guard let` / `??`. In Lyrebird's own code this is a banned pattern precisely because on the audio thread that crash is a hard failure.
|
||||
|
||||
---
|
||||
|
||||
## Part 6 — A realistic workflow
|
||||
|
||||
Putting the whole toolchain together, a typical loop while developing a piece:
|
||||
|
||||
1. **Edit** in Xcode (autocomplete, inline errors) — or your editor of choice.
|
||||
2. **Run in Debug** (`⌘R`) to check logic; set breakpoints in `build()`/`main.swift` if something's off.
|
||||
3. **Switch the scheme to Release** (or `swift run -c release`) to hear it perform and confirm it's not CPU-starved.
|
||||
4. **Iterate.** For fast headless loops, `swift run` from Terminal beats a full IDE cycle.
|
||||
5. **Test** with `swift test` if you've written any (Lyrebird uses Swift Testing — `@Test`, `#expect`).
|
||||
|
||||
---
|
||||
|
||||
## What you learned
|
||||
|
||||
- A **Swift package** (`Package.swift`) declares dependencies and targets; add Lyrebird by URL or local path, then `import LyrebirdSynth`.
|
||||
- **Xcode** (schemes, destinations, ▶) and the **`swift` CLI** are two views of the same package — use each where it's strongest.
|
||||
- **Debug vs Release**: debug logic in Debug, judge sound and speed in Release; switch via *Edit Scheme → Run → Build Configuration* or `-c release`. Debug audio can glitch purely from being unoptimized.
|
||||
- **Breakpoints** are for your main-thread setup/control code. **Never** breakpoint or `print` on the render thread — use `debugTap`, `debugTag`, and the diagnostics tools instead.
|
||||
|
||||
---
|
||||
|
||||
That's the series. You can now write Swift, understand Lyrebird's shape, use its expressive type-driven API, and build/run/debug real projects. From here, the [main documentation](../../README.md) — the generator catalog, the synthesizer protocol, routines and patterns — is open to you. Go make sound.
|
||||
@@ -0,0 +1,36 @@
|
||||
# Learning Swift for Lyrebird
|
||||
|
||||
You saw Lyrebird make sound and you want in — but you've never written Swift, and every Swift tutorial you find is about buttons, table views, and iPhone apps. This series is different. It teaches **just enough Swift to be productive in Lyrebird**, using audio examples the whole way.
|
||||
|
||||
You do **not** need to be an iOS developer. You do not need SwiftUI (though it helps later, once you build GUIs). You need to be comfortable reading and writing small programs, understanding types, and running them. That's what these four documents give you.
|
||||
|
||||
## Who this is for
|
||||
|
||||
- Musicians, composers, and sound designers coming from SuperCollider, Max/MSP, Pd, Csound, or Faust.
|
||||
- Programmers in other languages (Python, JavaScript, C++) who want the Swift-specific parts fast.
|
||||
- Anyone who felt "I get the *idea* of Lyrebird, I just don't know how to type the Swift."
|
||||
|
||||
## The path
|
||||
|
||||
Read them in order. Each is short and ends where the next begins.
|
||||
|
||||
| # | Document | What you'll be able to do |
|
||||
|---|----------|---------------------------|
|
||||
| 1 | [Hello, World](01-hello-world.md) | Make Lyrebird produce a tone from a program you wrote and ran yourself. Understand every line of it. |
|
||||
| 2 | [Swift Basics & Best Practices](02-swift-basics.md) | Read and write Swift confidently: variables, functions, control flow, optionals, classes vs structs, and the style Lyrebird expects. |
|
||||
| 3 | [Types & Functional Programming](03-types-and-functional.md) | Use Swift's type system and functional tools (`map`, `filter`, closures) to build and control synthesis graphs cleanly. |
|
||||
| 4 | [Xcode, Packages & Debugging](04-xcode-and-packages.md) | Open, build, and run projects in Xcode; add Lyrebird as a package; configure Debug vs Release; set breakpoints and debug a running synth. |
|
||||
|
||||
## The one-minute mental model
|
||||
|
||||
Lyrebird is a **library**, not an app and not a language. You write a normal Swift program. In it you:
|
||||
|
||||
1. Create a `SynthesisEngine` — it owns the audio hardware.
|
||||
2. Describe sound by subclassing `SynthesizerBase` and wiring **generators** (oscillators, filters, effects) together in a `build()` method.
|
||||
3. Hand your synthesizer to the engine with `engine.add(...)`.
|
||||
|
||||
There is no separate scripting language to learn (unlike SuperCollider's sclang or Csound's orchestra). The language *is* Swift. That's the whole reason this series exists: learn a slice of Swift, and you've learned how to drive Lyrebird.
|
||||
|
||||
> **A naming quirk to know from the start:** in `Package.swift` you depend on a product called `Lyrebird`, but in your source you write `import LyrebirdSynth`. That's expected — the product and the module have different names. Both guides 1 and 4 remind you.
|
||||
|
||||
Start with [Hello, World](01-hello-world.md).
|
||||
Reference in New Issue
Block a user