1.0.0 release

This commit is contained in:
2026-06-01 18:27:40 -07:00
parent b1ab0f102c
commit 1f20fcab20
1151 changed files with 230703 additions and 14 deletions
+138
View File
@@ -0,0 +1,138 @@
# Lyrebird Extension SDK
This document lists the public surface available to **out-of-tree Swift packages** that add
`Generator` or `Synthesizer` implementations on top of the `Lyrebird` core module.
The surface is split into two stability tiers:
1. **Stable public API** — covered by Lyrebird's SemVer. Breaking changes only on a MAJOR
version bump.
2. **`@_spi(LyrebirdExtensions)` API** — low-level RT helpers that extension packages need
to implement generators correctly. Signatures may evolve in MINOR releases; pin tightly
if you depend on these (`.upToNextMinor(from:)`).
## Importing
```swift
import LyrebirdSynth // stable public API
@_spi(LyrebirdExtensions) import LyrebirdSynth // stable + SPI helpers
```
Only declare the SPI import in files that need it. Consumers of your extension package never
need the SPI import — they import your module and use its public types.
## Tier 1 — Stable public API
### Generator protocol & base
| Symbol | File |
|---|---|
| `protocol Generator` | `GeneratorCore/Generator.swift` |
| `protocol AudioGenerator` | `GeneratorCore/Generator.swift` |
| `protocol ControlGenerator` | `GeneratorCore/Generator.swift` |
| `class GeneratorBase` | `GeneratorCore/GeneratorBase.swift` |
| `protocol GeneratorEnum` | `GeneratorCore/GeneratorTypes.swift` |
| `enum ProcessingRate` | `GeneratorCore/GeneratorTypes.swift` |
| `class GeneratorArray` | `GeneratorCore/GeneratorArray.swift` |
| `+ - * /` operators on `GeneratorArray` | `GeneratorCore/GeneratorArray.swift` |
| `func expand<G: Generator>(...)` | `GeneratorCore/GeneratorArray.swift` |
### Generator input
| Symbol | File |
|---|---|
| `protocol ValidGeneratorInput` | `GeneratorCore/ValidGeneratorInput.swift` |
| `protocol ConstantGeneratorInput` | `GeneratorCore/ValidGeneratorInput.swift` |
| `struct Closure` | `GeneratorCore/ValidGeneratorInput.swift` |
| `typealias ClosureBody` | `GeneratorCore/ValidGeneratorInput.swift` |
### `GeneratorBase` storage (you read/write these in your subclass)
| Symbol | Visibility |
|---|---|
| `var _segmentSerial: UInt64` | `public` |
| `var _cachedResult: [[Double]]` | `public` |
| `var _subBlockBuffer: [[Double]]` | `public` |
| `func _setupSubBlockBuffer(channels: Int = 1)` | `public` |
### Synthesizer side (parameter & graph)
| Symbol | File |
|---|---|
| `struct SynthGraph` | `Synthesizer/SynthGraph.swift` |
| `class SynthesisEngine` | `Engine/SynthesisEngine.swift` |
| `@propertyWrapper struct LiveParam` | `Parameters/LiveParam.swift` |
| `protocol LiveParameterWrapper` | `Parameters/LiveParam.swift` |
| `protocol LiveParameterValue` | `Parameters/LiveParam.swift` |
| `final class ParameterNode` | `Parameters/ParameterNode.swift` |
### Resources / data types
| Symbol | File |
|---|---|
| `struct HRIRFile` | `Buffers/HRIRFile.swift` |
| `let lyrebirdDefaultResultBufferSize: Int` | `Math/LyrebirdConstants.swift` |
## Tier 2 — `@_spi(LyrebirdExtensions)` API
These RT-safe helpers are mandatory when implementing new generators. They are SPI to keep
the public Lyrebird API surface small for application code, but are stable enough to use
across MINOR versions; pin extension packages to a specific MINOR range and bump explicitly
when Lyrebird's MINOR rolls over.
### MulAdd helpers (`GeneratorCore/MulAdd.swift`)
| Symbol | Signature |
|---|---|
| `struct MulAddSpec` | stored `mul`/`add` inputs + precomputed identity flag |
| `MulAddSpec.init(mul:add:)` | call at `init` time |
| `MulAddSpec.applyIfNeeded(to:graph:count:)` | call at end of `_computeSamples` |
| `MulAddSpec.apply(to:graph:count:)` | unconditional apply (rare; prefer `applyIfNeeded`) |
| `MulAddSpec.identity` | static — for generators with no `mul`/`add` knobs |
| `func extractScalar(_:)` | init-time scalar detection |
| `func fillRampedResult(into:from:to:mulAdd:graph:count:)` | ControlGenerator ramp helper |
| `func lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` | block-constant capture from a generator input |
### PRNG (`Generators/Noise/WhiteNoise.swift`)
| Symbol | Signature |
|---|---|
| `func xorshift64NextRaw(_:)` | raw `UInt64` step |
| `func xorshift64Next(_:)` | step → `Double` in `[-1, 1]` |
### Test-helper hooks (`Engine/SynthesisEngine.swift`)
For out-of-tree extension packages building their own `advanceBlock`-style test helpers:
| Symbol | Signature |
|---|---|
| `SynthesisEngine.segmentSerial` | acquiring load (read-only) |
| `SynthesisEngine.advanceSegmentSerial()` | wrapping increment — call between back-to-back `calculatedSamples` calls in tests to simulate a block boundary |
## Versioning policy
Lyrebird 1.x:
- Stable public API: SemVer. Breaking change → 2.0.
- `@_spi(LyrebirdExtensions)` API: signatures may change in MINOR releases. Extension
packages should pin tightly:
```swift
.package(url: "...Lyrebird", "1.4.0"..<"1.5.0")
```
## Namespacing guidance
- **Module name**: prefer `Lyrebird<Vendor>` (e.g. `LyrebirdATK`). Swift module names already
prevent type collisions; the prefix makes the dependency obvious in `Package.swift`.
- **Type prefix**: match your domain (`Foa*`, `Hoa*`, `Pd*`, …). Keep it short and consistent
within the package.
- **Parameter-key prefix**: when your `Synthesizer` reads parameters by string key, prefix
them (`"atk.azimuth"`, not `"azimuth"`) to avoid collisions in user code that mixes
multiple extension packages.
## See also
- [Writing Generators](writing-generators.md) — full generator-author guide.
- `docs/extension-authors-guide.md` — end-to-end walkthrough of building and publishing an
extension package, using `LyrebirdATK` as a worked example.
+280
View File
@@ -0,0 +1,280 @@
# Generator Protocol
The base unit of signal production in Lyrebird.
## Protocol Hierarchy
```swift
protocol Generator: AnyObject {
var rate: ProcessingRate { get }
func calculatedSamples(graph: SynthGraph, count: Int) -> [[LyrebirdFloat]]
func floatValue(graph: SynthGraph) -> LyrebirdFloat
}
protocol AudioGenerator: Generator {} // rate == .audio
protocol ControlGenerator: Generator {} // rate == .control
enum ProcessingRate {
case audio // sample rate (e.g. 44100 Hz)
case control // block rate (e.g. 44100 / blockSize Hz)
case spectral // integer multiple of control rate
case demand // marks the DemandGenerator value-source tier; Demand.Audio/Control report .audio/.control
}
/// Marks a caseless namespace enum whose nested Audio and Control classes are a matched
/// generator pair. Conforming types declare AudioType and ControlType so documentation,
/// generic code, and tooling can discover the pair at compile time.
protocol GeneratorEnum {
associatedtype AudioType: AudioGenerator
associatedtype ControlType: ControlGenerator
}
```
## Control-Rate Variants
Paired generators use an `enum` namespace with nested `Audio` and `Control` classes (e.g. `OscSin.Audio`, `OscSin.Control`). The `Control` variant conforms to
`ControlGenerator` instead of `AudioGenerator`. The `Control` variant runs once per block rather
than once per sample, trading temporal resolution for CPU efficiency.
### When to create a Control variant
Create a `Control` variant when **all** of the following are true:
1. **The generator produces an independent signal** — it has its own internal state (phase
accumulator, PRNG, period counter) that advances over time without depending on an audio-rate
input buffer.
2. **It is commonly used as a modulator (LFO), not audio content** — the output is wired to a
parameter input of another generator rather than to an `Out` bus directly.
3. **Block-rate accuracy is sufficient** — oscillator frequencies below roughly
`sampleRate / (blockSize × 4)` are indistinguishable from audio-rate in practice; noise and
impulse generators are similarly well-served at block rate.
Current generators that meet all three criteria: `OscSin`, `OscTable`, `Impulse`, `WhiteNoise`,
`LFStepNoise`, `LFLineNoise`.
### When NOT to create a Control variant
| Generator type | Reason |
|---|---|
| Filters (`RBJLowPass`, `ButterworthLowPass`, etc.) | Input-driven; filters already accept control-rate input via the interpolated ramp mechanism — no separate class needed |
| Delay lines (`DelayLine`, `DelayLineFeedback`) | Require audio-rate state; a block-rate delay makes no acoustical sense |
| Math generators (`BinaryOpGenerator`, `BipolarMappingGenerator`, `UnipolarMappingGenerator`, etc.) | Rate follows their inputs; they have no independent state to run at a different rate |
| `EnvelopeGen.Audio` | Amplitude envelopes — per-sample shape accuracy is essential for click-free fade-outs and fast transients |
### How downstream consumers interact with Control-rate generators
A `ControlGenerator`'s `_computeSamples` override produces a full `blockSize`-sample
**interpolated ramp** from the previous block's output value to the current block's output value.
This means any `AudioGenerator` that calls `calculatedSamples(count: blockSize)` on a
`ControlGenerator` input receives a smooth audio-rate buffer — the filter or oscillator is
unaware of the source rate. No special handling is required in the downstream generator.
### Naming convention (enum namespace pattern)
Use an `enum` namespace with nested `_Base`, `Audio`, and `Control` classes. Both classes live in the same source file. Add a `GeneratorEnum` conformance extension at the bottom of the file to advertise the pair.
```
OscSin.Audio / OscSin.Control — OscSin.swift
OscTable.Audio / OscTable.Control — OscTable.swift
Impulse.Audio / Impulse.Control — Impulse.swift
WhiteNoise.Audio / WhiteNoise.Control — WhiteNoise.swift
LFStepNoise.Audio / LFStepNoise.Control — LFNoise.swift
LFLineNoise.Audio / LFLineNoise.Control — LFNoise.swift
EnvelopeGen.Audio / EnvelopeGen.Control — EnvelopeGen.swift
PlayBuffer.Audio / PlayBuffer.Control — PlayBuffer.swift
RecordBuffer.Audio / RecordBuffer.Control — RecordBuffer.swift
In.Audio / In.Control — In.swift
Out.Audio / Out.Control — Out.swift
SendTrigger.Audio / SendTrigger.Control — SendTrigger.swift
Demand.Audio / Demand.Control — Demand/Demand.swift
```
Every namespace enum adds a `GeneratorEnum` extension:
```swift
extension OscSin: GeneratorEnum {
public typealias AudioType = OscSin.Audio
public typealias ControlType = OscSin.Control
}
```
This lets generic code and DocC resolve the pair at compile time:
```swift
func describe<G: GeneratorEnum>(_ type: G.Type) {
print("Audio:", G.AudioType.self, "Control:", G.ControlType.self)
}
describe(OscSin.self) // Audio: OscSin.Audio Control: OscSin.Control
```
---
## Type Aliases
```swift
typealias LyrebirdFloat = Double
typealias LyrebirdInt = Int
typealias LyrebirdFloatClosureBody = (SynthGraph, Int) -> LyrebirdFloat
```
## ValidGeneratorInput Protocol
Enables seamless mixing of constants, generators, parameter keys, and closures as generator inputs. All of the following are valid:
```swift
OscSin.Audio(freq: 440.0) // Float literal
OscSin.Audio(freq: someGenerator) // another Generator
OscSin.Audio(freq: "FreqParam") // string parameter key — resolved at runtime
OscSin.Audio(freq: { g, i in ... }) // closure
```
```swift
protocol ValidGeneratorInput {
func calculatedSamples(graph: SynthGraph, count: Int) -> [[LyrebirdFloat]]
func floatValue(graph: SynthGraph) -> LyrebirdFloat
func intValue(graph: SynthGraph) -> LyrebirdInt
func needsInterpolation() -> Bool
func sampleBlock(graph: SynthGraph, count: Int, previousValue: LyrebirdFloat) -> [LyrebirdFloat]
}
// Conforming types: Double, Int, String, any Generator, Closure
// Contract: calculatedSamples must always return a non-empty outer array (at least one channel).
```
## Operator Overloading
Math operators on Generator inputs create `BinaryOpGenerator` instances:
```swift
let sig = OscSin.Audio(freq: 440) * 0.5 // BinaryOpGenerator (*)
let mix = sig1 + sig2 // BinaryOpGenerator (+)
```
Operators: `*`, `+`, `-`, `/`
### Operator Precedence
The overloads reuse Swift's standard operator symbols, so **standard Swift precedence applies**:
| Operators | Precedence group | Associativity |
|---|---|---|
| `*`, `/` | `MultiplicationPrecedence` | left |
| `+`, `-` | `AdditionPrecedence` | left |
`*` and `/` bind before `+` and `-`; equal-precedence operators are left-to-right:
```swift
osc * 0.5 + env // → (osc * 0.5) + env
osc + env * 0.5 // → osc + (env * 0.5)
osc - env - lfo // → (osc - env) - lfo (left-associative)
(osc + env) * 0.5 // parentheses work normally
```
Note: `Double op Double` always resolves to the Swift stdlib — not a `BinaryOpGenerator`. At
least one operand must be a `Generator` or `any ValidGeneratorInput`.
### BinaryOpGenerator — multi-channel broadcasting
`BinaryOpGenerator` reads each operand's `outputChannelCount` at construction time and
allocates `_result` to `max(lhs, rhs)` rows. Per-channel rules:
- `1 × 1` → 1-row output (classic mono).
- `1 × N` or `N × 1` → N-row output, mono operand broadcasts to every channel.
- `N × N` → N-row output, element-wise.
- `N × M` with both > 1 and N ≠ M → `precondition` traps at `init`. No implicit
wrap-extend, no truncation. Compose explicitly via `ChannelSelect` or `GeneratorArray`.
`outputChannelCount` is a `Generator` protocol requirement (default `1` from `GeneratorBase`).
Multi-row generators (`Pan2`, `Pan4`, `PanN`, `AmbiEncoder1/Decoder1`, `SVF`,
`FrequencyShifter.Audio`, `Chorus.Audio`, `GeneratorArray`, `TimeStretch.Audio`, multi-channel
`In` / `BufferRead` / `PlayBuffer`, etc.) must override it. A missing override silently
mono-izes the generator under arithmetic.
> **Channel-aware `mul:` / `add:`** — `MulAddSpec.apply` follows the same broadcast policy
> as `BinaryOpGenerator`: mono `mul`/`add` broadcasts across every output channel; `mul`/`add`
> matching the output channel count applies per-channel; mismatched multi-row inputs trap at
> the apply site. The `*` operator and `mul:` parameter now have parallel semantics.
### BinaryOpGenerator — scalar fast-path
When one or both operands are non-Generator literals (`Double` or `Int`), `BinaryOpGenerator`
uses `floatValue` instead of `calculatedSamples` for that side. This avoids the per-block
`[[LyrebirdFloat](repeating:count:)]` heap allocation that the `Double`/`Int` conformers would
otherwise produce. The classification is performed once in `init` and stored as `lhsIsLiteral`
/ `rhsIsLiteral` — no type-metadata checks on the RT thread.
```swift
// Fast path: rhs is a literal — only the generator side calls calculatedSamples.
let sig = OscSin.Audio(freq: 440) * 0.5 // 0.5 → floatValue; OscSin → calculatedSamples
// Both time-varying: both sides call calculatedSamples.
let am = OscSin.Audio(freq: 440) * OscSin.Audio(freq: 2.0)
```
### Fan-out caching
A single `Generator` instance can safely feed multiple downstream consumers. The segment-serial
fan-out cache ensures `_computeSamples` is called exactly once per `evaluateSegment`
call regardless of how many consumers evaluate the same generator. State advances by exactly
`count` samples per block — no double-advance artefacts.
```swift
// osc is shared between two signal paths — fan-out cache ensures one evaluation per block:
let osc = OscSin.Audio(freq: 440)
let fm = OscSin.Audio(freq: osc * 200 + 880) // osc as FM modulator
let mix = fm * 0.3 + osc * 0.05 // osc also in direct mix
output(bus: 0, source: Pan2(input: mix))
```
## count: Int Parameter
The `count` parameter in `calculatedSamples(graph:count:)` specifies exactly how many samples to
produce. This is normally `blockSize`, but during sub-block splitting (scheduling) it may be
smaller — a segment from event boundary to event boundary within a block.
Generators **must** advance their stateful accumulators by exactly `count` samples per call,
regardless of whether `count < blockSize`. This ensures correct timing across block boundaries.
## Pre-allocated output buffer pattern
Every stdlib generator pre-allocates `_result` to `lyrebirdDefaultResultBufferSize` (512) samples
in `init`, and opens `calculatedSamples` with:
```swift
precondition(count <= _result[0].count,
"count \(count) exceeds the pre-allocated buffer (\(_result[0].count) samples). ...")
```
This fires in both debug and release if the buffer is undersized — no grow path, no RT allocation.
`SynthesisEngine.init` enforces `blockSize <= lyrebirdDefaultResultBufferSize`, so the precondition
is never violated in engine-driven usage. New generators **must** follow this pattern exactly.
```swift
// Canonical new-generator calculatedSamples skeleton:
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[LyrebirdFloat]] {
precondition(count <= _result[0].count,
"count \(count) exceeds pre-allocated buffer. "
+ "Ensure blockSize <= lyrebirdDefaultResultBufferSize.")
// ... fill _result[0][0..<count] ...
return _result
}
```
## Statefulness
Each Generator instance owns its own state. Examples:
- `OscSin`: phase accumulator
- `EnvelopeGen.Audio` / `EnvelopeGen.Control`: current segment, elapsed time
- `DelayLine`: circular buffer, write head position
- `FirstOrderSection`: previous input and output sample
State is never shared between instances — graph-copy-per-Synthesizer ensures isolation.
## Legacy Reference
These files are in `legacy/Lyrebird/LyrebirdSynth/Lyrebird/` — the legacy prototype. They are **not** in the current codebase; they are design references only.
- `LyrebirdTypes.swift` — `ValidGeneratorInput` pattern, type aliases
- `LyrebirdUgen.swift` — base Generator class (legacy name: UGen)
- `MathUGens.swift` — `BinaryOpGenerator` pattern, operator overloading
- `OscUGens.swift` — sine table, phase accumulator pattern
+385
View File
@@ -0,0 +1,385 @@
# Node Tree and Group Actions
The Lyrebird signal graph is a tree of `Synthesizer` nodes owned by `SynthesisEngine`. Every node that produces or processes audio lives in this tree; nodes outside the tree are never evaluated.
---
## Tree Structure
```
SynthesisEngine
└── rootGroup (Group, persistent)
├── [pre-main nodes] ← .before(engine.mainGroup) — input limiters, gates, etc.
├── mainGroup (Group, persistent) ← default engine.add(_:) target
│ ├── Synthesizer ← newest-added evaluates first
│ └── Synthesizer
└── [post-main nodes] ← .after(engine.mainGroup) — decoders, master reverb
```
`rootGroup` is the engine's root `Group` — a doubly-linked list of child `Synthesizer` nodes evaluated in order. `mainGroup` is a persistent child of `rootGroup` and the default target for `engine.add(_:)`. Both groups are created at engine init and never freed.
**Evaluation order within mainGroup:** `engine.add(_:)` uses head-insertion — the most-recently-added node evaluates first. This means if synth B depends on bus output from synth A, add B first and then A.
`Group` itself conforms to `Synthesizer`, so groups can be nested to any depth.
---
## Defining a Synthesizer
Subclass `SynthesizerBase` and override `build()`. Declare mutable parameters with `@LiveParam`. Register `Out.Audio` (or `Out.Control`) generators with `addOutputGenerator` — or use the shorthand helpers `output(bus:source:)` and `controlOutput(bus:source:)`.
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SineTone: SynthesizerBase {
@LiveParam var freq: LyrebirdFloat = 440.0
@LiveParam var amp: LyrebirdFloat = 0.5
override func build() {
let osc = OscSin.Audio(freq: $freq, phase: 0.0)
output(bus: 0, source: osc * $amp) // shorthand for addOutputGenerator(Out(...))
}
}
```
`build()` runs once on the **main thread** when the node is scheduled. All generator allocation happens here; the RT audio thread only calls `evaluate(graph:count:)`.
---
## Adding Nodes
### Immediately (at current sample time)
```swift
let tone = SineTone()
try engine.add(tone)
```
`add(_:)` is equivalent to `schedule(_:at: engine.currentTime)`. The engine reads `currentTime` via an atomic load — safe from the main thread.
### At an absolute sample time
```swift
// Start tone2 at exactly sample 44100 (1 second at 44.1 kHz)
let tone2 = SineTone()
try engine.schedule(tone2, at: 44100)
```
The `SampleTime` value is compared to `engine.currentTime` each block. When the scheduled sample falls within the current block window, the engine adds the node mid-block via sub-block splitting, so the onset is sample-accurate.
### After a relative duration in seconds
```swift
let tone3 = SineTone()
try engine.schedule(tone3, after: 2.0) // 2 seconds from now
```
`schedule(_:after:)` converts the duration to a `SampleTime` delta using `engine.seconds(_:)` and adds it to the current atomic clock. Internally identical to `schedule(_:at:)`.
### How the add path works
Before posting the `.add` event, the engine calls `rebuildGraph()` on `SynthesizerBase` instances (which clears then calls `build()`) on the **main thread**. The linked-list `PreparedNode` is also pre-allocated on the main thread. The RT thread in `applyEvent` only wires pointer references — no allocation on the RT thread.
---
## Removing Nodes
### Immediately
```swift
engine.remove(tone)
```
### At an absolute sample time
```swift
// Remove tone2 exactly 2 seconds after it was added
engine.remove(tone2, at: 44100 + engine.seconds(2.0))
```
Removed nodes are handed to `freeQueue`, where a background drain thread releases them via ARC — the RT thread never calls `release()` directly.
### Convenience: schedule paired add and remove
```swift
let note = SineTone()
let startTime = engine.currentTime + engine.seconds(0.5)
let stopTime = startTime + engine.seconds(1.0)
try engine.schedule(note, at: startTime)
engine.remove(note, at: stopTime)
```
Both events enqueue to the same `pendingQueue`. The engine processes them in target-time order within each block.
---
## Updating Parameters While Running
Assign `@LiveParam` properties from the main thread at any time after the node is added. Changes cross to the RT thread via an atomic write and produce a per-sample linear ramp on the next block.
```swift
tone.freq = 880.0 // no try, no string — RT-safe atomic write
tone.amp = 0.3
```
For external/REPL access by name (e.g. OSC handlers receiving the parameter name as a String), use `try synth.updateParameter("freq", value: 880.0)` — the by-name route writes the same atomic. See `docs/protocols/synthesizer.md`.
---
## Nested Groups
Nesting groups controls evaluation order without needing to track individual nodes. Add a `Group` to the engine the same way you add any `Synthesizer`.
```swift
let instruments = Group()
let effects = Group()
try engine.add(instruments) // evaluated before effects
try engine.add(effects)
```
> **Evaluation order is global.** Every `Synthesizer` in `instruments` is evaluated before any `Synthesizer` in `effects`. This matters for bus routing: a node writing to a bus must appear earlier in the tree than any node reading from the same bus.
---
## Node Positioning
By default `engine.add(_:)` inserts at the head of `mainGroup` (newest-first). Use the `position:` overload to control placement precisely.
### NodePosition cases
| Case | Meaning |
|------|---------|
| `.tail(of: group)` | Append to end of `group` |
| `.head(of: group)` | Prepend to front of `group` (evaluated first within that group) |
| `.before(target)` | Insert immediately before `target` in whatever group contains it |
| `.after(target)` | Insert immediately after `target` in whatever group contains it |
```swift
let instruments = Group()
try engine.add(instruments)
let bass = BassSynth()
try engine.add(bass, position: .tail(of: instruments)) // append
let lead = LeadSynth()
try engine.add(lead, position: .head(of: instruments)) // prepend — runs before bass
let pad = PadSynth()
try engine.add(pad, position: .after(bass)) // insert after bass
```
`.before` and `.after` search the entire node tree recursively (O(n)). If the target is not found, the node falls back to `mainGroup` head insertion.
### Global pre/post processing
Use `engine.mainGroup` as a position anchor to install global processing nodes that run before or after all default-added instruments:
```swift
// Evaluate before all instruments (e.g. input limiter on the live input bus)
try engine.add(InputLimiter(), position: .before(engine.mainGroup))
// Default instrument — lands in mainGroup
try engine.add(MySynth())
// Evaluate after all instruments (e.g. ambisonic decoder, master reverb)
try engine.add(MasterReverb(), position: .after(engine.mainGroup))
```
Multiple `.before(engine.mainGroup)` insertions are ordered so that each new pre-main node appears immediately before `mainGroup` (pushing earlier pre-main nodes further away). The same rule applies for `.after(engine.mainGroup)` insertions.
---
## Group Lifecycle — release and free
Every `Synthesizer` has two lifecycle methods:
```swift
try synth.release(engine: engine) // graceful: set gate → 0 (throws SynthesizerError.noGate if unsupported)
synth.free(engine: engine) // immediate: remove from tree now
```
`Group` provides cascade implementations of both.
### Group.release(engine:)
Releases all direct children, then self-frees when the group empties:
1. For each child: call `child.release(engine:)`. If it throws `.noGate`, call `child.free(engine:)` immediately.
2. Starts a 0.1 s repeating timer that reads `group.count` (atomically safe). When count reaches 0, calls `group.free(engine:)`.
**Persistent groups** (`rootGroup` and `mainGroup`) are exceptions: `release(engine:)` still cascades to all children, but the group itself never self-frees. The groups remain attached and ready to accept new children after the cascade drains to zero.
```swift
let instruments = Group()
// … populate instruments with gated synths …
try engine.add(instruments)
// Later: gracefully release all notes and remove the group when silent.
instruments.release(engine: engine)
```
### Group.free(engine:)
Immediately tears down the group and all its children — no envelope release:
```swift
instruments.free(engine: engine)
// On next block: all children enqueued to freeQueue, group removed from tree.
```
### Synthesizer.release — user implementation
Override `release(engine:)` in synthesizers that have an envelope gate:
```swift
final class GatedNote: SynthesizerBase {
@LiveParam var gate: LyrebirdFloat = 1.0
override func build() {
// … gate drives EnvelopeGen …
}
// Signal envelope to release (gate → 0).
override func release(engine: SynthesisEngine) throws {
gate = 0.0 // @LiveParam atomic write — no try needed
}
}
```
Or use the by-name route, which writes the same atomic on the auto-registered `@LiveParam`:
```swift
override func release(engine: SynthesisEngine) throws {
try updateParameter("gate", value: 0.0)
}
```
---
## Bus-Based Communication Between Nodes
Nodes communicate via audio buses (`Out.Audio` / `In.Audio`) or control buses (`Out.Control` / `In.Control`). Bus writes accumulate with `+=` — multiple nodes can write to the same bus and their outputs mix.
`In.Audio` and `In.Control` accept an optional `channels:` parameter to read N consecutive buses as a single N-channel generator (channel count fixed at init, no RT allocation):
```swift
In.Audio(bus: 4, channels: 2) // reads audioBuses[4] and [5]; returns 2-channel output
In.Control(bus: 10, channels: 2) // reads controlBuses[10] and [11]; independent ramps
```
With `BusAllocator`, pass an `AudioBus` directly and channel count is derived automatically:
```swift
let stereo = try engine.busAllocator.allocateAudioBus(channelCount: 2)
In.Audio(bus: stereo) // reads stereo.index and stereo.index+1
```
```swift
// Example — DrumSynth and ReverbEffect are user-defined SynthesizerBase subclasses
// Node A: writes to bus 4 (an intermediate "effects send" bus)
class DrumSynth: SynthesizerBase {
override func build() {
let drum = WhiteNoise.Audio() * 0.8
output(bus: 0, source: drum) // dry output on bus 0
output(bus: 4, source: drum) // parallel send to bus 4 for an effect
}
}
// Node B: reads from bus 4 and writes to the main output
// Must appear AFTER DrumSynth in the tree so bus 4 is populated first.
class ReverbEffect: SynthesizerBase {
override func build() {
let wet = input(bus: 4) // reads what DrumSynth wrote to bus 4
output(bus: 0, source: wet * 0.4)
}
}
let drums = DrumSynth()
let reverb = ReverbEffect()
try engine.add(drums) // added first → evaluated first → bus 4 populated
try engine.add(reverb) // added second → evaluated second → reads populated bus 4
```
Audio buses are zeroed at the start of every block. Control buses persist across blocks.
---
## Auto-Free with EnvelopeGen
When `EnvelopeGen.Audio` or `EnvelopeGen.Control` finishes and its `doneAction` is `.freeNode`,
it sets an atomic flag. Poll the flag from a non-RT context (main thread, scheduling loop, or
timer) and post the removal:
```swift
// Example — PianoNote is a user-defined SynthesizerBase subclass
class PianoNote: SynthesizerBase {
let env: EnvelopeGen.Audio
init() {
env = EnvelopeGen.Audio(
envelope: Envelope(levels: [0, 1, 0], durations: [0.01, 0.3], curves: [0, 0]),
doneAction: .freeNode
)
}
override func build() {
output(bus: 0, source: env)
}
}
let note = PianoNote()
try engine.add(note)
// Poll from main thread (e.g. in a display-link callback or timer):
if note.env.needsFree {
engine.remove(note)
}
```
Do not call `engine.remove` from within the RT audio callback — that would post to `pendingQueue` from the RT thread.
---
## Polyphonic Voice Management
For instruments that need multiple simultaneous notes, use `VoicePool` instead of managing individual synthesizer instances manually. The pool allocates N voices into a `Group` at init time and handles note-on/note-off assignment and steal arbitration on the main thread.
```swift
let group = Group()
try engine.add(group)
let pool = try VoicePool(
voiceCount: 8, group: group, engine: engine,
stealStrategy: .oldest
) { MySynth() }
let voice = pool.noteOn(note: 60) // allocates or steals
voice.freq = midiToHz(60)
voice.gate = 1.0
voice.gate = 0.0
pool.noteOff(note: 60) // marks voice free; gate down yourself
```
See `docs/protocols/synthesizer.md` — "Polyphonic Voice Pools" section for steal strategy reference and MIDI wiring.
---
## Thread Safety Summary
| Operation | Thread | Notes |
|---|---|---|
| `engine.add` / `engine.schedule` | Main | `build()` and `PreparedNode` allocation happen here before enqueueing |
| `engine.remove` | Main | Pre-retains the synth ref before enqueueing — no RT retain |
| `tone.freq = 880.0` (`@LiveParam`) | Main | Releasing `Atomic<UInt64>` store; RT reads with acquiring load |
| `updateParameter` (string-key) | Main | Enqueues to per-synth `SPSCQueue`; applied at next block boundary |
| `engine.add(_:position:)` | Main | Like `add(_:)` — builds graph, allocates node, posts `.addNode` event |
| `VoicePool` methods | Main | Language-side only; no RT involvement |
| `synth.release(engine:)` | Main | Language-side only; posts parameter or remove events |
| `synth.free(engine:)` | Main | Posts immediate remove / groupFree event |
| `Group.addToTail` / `remove` / `addBefore` / `addAfter` | RT (audio) | Called inside `applyEvent` — no allocation, pointer wiring only |
| `evaluate(graph:count:)` | RT (audio) | Never add, remove, or allocate here |
The key invariant: **every mutation that allocates or retains happens before the event enters `pendingQueue`**. The RT thread only wires pointers and reads atomic values.
+341
View File
@@ -0,0 +1,341 @@
# Synthesizer Protocol
The composable unit of instrument or effect in Lyrebird. Any type conforming to `Synthesizer` can be added to the signal graph tree.
## Current Implementation State
**Complete.** The protocol, node tree, `Group`, and `SynthesizerBase` are fully implemented and tested (152 tests passing).
---
## Protocol Definition
```swift
public protocol Synthesizer: AnyObject {
/// Configure the internal generator DAG. Called once on the scheduling thread.
func build()
/// Evaluate one segment of the signal graph. Called on the RT audio thread.
/// Default: no-op; SynthesizerBase provides the real one.
func evaluate(graph: SynthGraph, count: Int)
/// Begin a graceful release (e.g. set gate → 0).
/// Default throws `SynthesizerError.noGate`. Override in synthesizers with EnvelopeGen.
func release(engine: SynthesisEngine) throws
/// Immediately remove this node from the signal graph.
/// Default posts an engine remove event. Group overrides with full cascade teardown.
func free(engine: SynthesisEngine)
}
```
Default `evaluate` and `free` are provided by a protocol extension. Default `release` throws `SynthesizerError.noGate` — override it in synthesizers that have a gate input.
---
## Synthesizer Lifecycle
### release(engine:) — graceful shutdown
Signal the synthesizer to begin releasing (set gate → 0, trigger doneAction envelope, etc.). Synthesizers that don't support release throw `SynthesizerError.noGate`.
```swift
final class GatedNote: SynthesizerBase {
@LiveParam var gate: LyrebirdFloat = 1.0
override func build() { /* … gate drives EnvelopeGen … */ }
override func release(engine: SynthesisEngine) throws {
gate = 0.0 // atomic write — no try, no string
}
}
let note = GatedNote()
try engine.add(note)
// Later — begin release:
try? note.release(engine: engine)
```
For string-key gate parameters:
```swift
override func release(engine: SynthesisEngine) throws {
try updateParameter("gate", value: 0.0)
}
```
### free(engine:) — immediate removal
Removes the node from the signal graph at the current sample time, without waiting for an envelope to complete.
```swift
note.free(engine: engine)
```
### SynthesizerError
```swift
public enum SynthesizerError: Error {
case noGate // thrown by default release(engine:) when no gate is supported
}
```
Catch `.noGate` to distinguish synthesizers that don't support release from ones that throw real errors:
```swift
do {
try synth.release(engine: engine)
} catch SynthesizerError.noGate {
synth.free(engine: engine) // no gate — free immediately
}
```
### Group lifecycle cascade
`Group` provides cascade implementations of both lifecycle methods. See `docs/protocols/node-tree.md` — "Group Lifecycle" section.
---
## SynthesizerBase
Most Synthesizer implementations should subclass `SynthesizerBase` rather than conforming to `Synthesizer` directly.
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SineTone: SynthesizerBase {
@LiveParam var freq: LyrebirdFloat = 440.0
@LiveParam var amp: LyrebirdFloat = 0.5
override func build() {
let osc = OscSin.Audio(freq: $freq, phase: 0.0)
output(bus: 0, source: osc * $amp)
}
}
```
- Override `build()` and call `addOutputGenerator(_:)` with each root generator (typically `Out.Audio` or `Out.Control`).
- `evaluate(graph:count:)` is `final` — the engine drives it automatically.
- Do not override `evaluate` in subclasses; override `build` instead.
## Adding to the Engine
```swift
let note1 = SineTone()
let note2 = SineTone() // independent instance — own phase, own envelope
try engine.add(note1)
try engine.add(note2)
```
`engine.add(_:)` posts an `.add` event to the pending queue. Before enqueueing, the engine:
1. Calls `rebuildGraph()` (clears then calls `build()`) on `SynthesizerBase` instances, or `build()` on plain `Synthesizer` conformers — on the **main thread**.
2. Pre-allocates the linked-list `PreparedNode` — on the **main thread**.
The RT audio thread in `applyEvent` only wires pointer references into `Group.addToTail` — no allocation occurs on the RT thread.
## Removing from the Engine
```swift
engine.remove(note1)
engine.remove(note2, at: someTime) // sample-accurate removal
```
Removed instances are handed off to `freeQueue` for ARC deallocation on the background drain thread — never on the RT audio thread.
## Node Tree
```
SynthesisEngine
└── rootGroup (Group)
├── Group (optional nesting)
│ ├── Synthesizer ← evaluated first
│ └── Synthesizer
└── Synthesizer ← evaluated last
```
- `Group` is itself a `Synthesizer` — groups can be nested arbitrarily.
- Children are evaluated in insertion order (tail-append by default).
- Evaluation order controls bus routing: if A writes to bus 2 and B reads from bus 2, A must precede B in the tree.
- `Group.addToTail` / `addToHead` / `remove` are `internal` — use `engine.add(_:)` and `engine.remove(_:)` from user code.
## `@LiveParam` and `@UIParam` — Live Parameters
`@LiveParam` (in `Lyrebird`) and `@UIParam` (in `LyrebirdUI`) are the only live-parameter
mechanisms. Both auto-register at `build()` time via `Mirror` reflection — no
`declareParameter` call is required.
```swift
final class SineTone: SynthesizerBase {
@LiveParam var freq: Double = 440.0
@LiveParam var amp: Double = 0.2
override func build() {
let osc = OscSin.Audio(freq: $freq)
output(bus: 0, source: osc * $amp)
}
}
let tone = SineTone()
try engine.add(tone)
tone.freq = 880.0 // typed direct write
try? tone.updateParameter("freq", value: 880.0) // by-name (e.g. from OSC)
```
### How it works
| Thread | Operation |
|--------|-----------|
| Main thread | `tone.freq = 880.0` → releasing `Atomic<UInt64>` store |
| RT thread | `_computeSamples` → acquiring load → linear ramp from previous to new target |
The projected value `$freq` is a `ParameterNode` — a `ControlGenerator`. When wired into
`OscSin.Audio(freq: $freq)`, OscSin detects it as a `Generator` and calls `calculatedSamples`,
producing a linearly-interpolated audio-rate buffer ramping to the new value. The ramp is
sized to the engine's control block: one ramp per audio block when `controlBlockSize ==
blockSize` (default), or K ramps per audio block when `controlBlockSize < blockSize`.
### Auto-registration via Mirror
`SynthesizerBase.rebuildGraph()` walks `Mirror(reflecting: self)` plus the superclass chain
at the end of `build()`, finding any `@LiveParam` / `@UIParam` properties (via the internal
`LiveParameterWrapper` protocol). The property name with the leading `_` of property-wrapper
backing storage stripped becomes the parameter key.
### Fan-out safety
`ParameterNode` has the standard segment-serial fan-out cache. Wiring `$freq` into multiple
downstream generators is safe — `_computeSamples` runs exactly once per segment regardless of
fan-out count.
### `updateParameter` (by-name path)
`updateParameter` is the by-name route. Use it for external integrations that arrive as
`String` (OSC, MIDI, REPL, JSON presets):
```swift
try tone.updateParameter("freq", value: 880.0) // throws on unknown key
try? tone.updateParameter("freq", value: 880.0) // silent ignore for fire-and-forget
```
Throws `ParameterUpdateError.keyNotFound(key)` if no live parameter exists for `key`. The
write is the same atomic store as the typed setter — both are equivalent.
### `@UIParam`
`@UIParam` is `@LiveParam` plus an `@Observable` `value` for SwiftUI binding. The projected
node (`UIParamNode`) delegates RT work to an internal `ParameterNode`, so audio-rate
delivery is identical. Use `@UIParam` whenever SwiftUI controls bind to the parameter — see
`docs/ui/gui-system.md`.
### Runtime source-swap
Beyond scalar writes, any `@LiveParam` (or `@UIParam`) slot supports replacing the wired
generator at runtime without stopping the synthesizer.
```swift
// Assign an LFO as the source for freq — takes effect at the next audio block boundary:
tone.$freq.source = LFSawtooth.Control(freq: 0.5, mul: 100, add: 440)
// Revert to scalar (the last value written via `tone.freq = ...`):
tone.$freq.source = nil
// Soft crossfade over 4 blocks (~23 ms at 44.1 kHz / 256-sample block):
tone.$freq.setSource(newLFO, crossfadeBlocks: 4)
// Equivalent SynthesizerBase convenience helper:
tone.setSource(tone.$freq, to: newLFO)
```
The two public API surfaces are:
- **`ParameterNode.source`** — get/set property on the projected value (`synth.$freq`).
Reading returns the last value assigned on the main thread (eventually consistent with the
audio thread within one block). The setter performs a hard swap (no crossfade).
- **`SynthesizerBase.setSource(_:to:crossfadeBlocks:)`** — convenience wrapper taking the
`ParameterNode` directly; useful in generic or programmatic contexts.
Crossfade semantics: `crossfadeBlocks = 0` (default) = hard swap at the next block boundary.
A value > 0 linearly blends old and new source outputs over that many blocks. A mid-crossfade
swap kills the in-progress old source immediately and starts a fresh crossfade.
For the complete contract — threading rules, queue limits, and the known limitation on
updating a source generator's own parameters — see `Sources/Lyrebird/Lyrebird.docc/ParameterInputs.md`
(the DocC-rendered material under "Live source-swap").
### Subclass parameters
Subclasses can declare additional `@LiveParam` / `@UIParam` properties — both subclass and
inherited parameters are registered. Note: Swift forbids re-declaring `@LiveParam var x` in
a subclass when the parent already has one (would require `override` on a property-wrapper
backing store, which is unsupported), so subclass parameters must use distinct names.
## Auto-Free
When `EnvelopeGen.Audio` or `EnvelopeGen.Control` signals completion with `doneAction: .freeNode`, it sets `needsFree = true`
(an `Atomic<Bool>` releasing store on the RT thread). The **caller** must read this flag from a
non-RT context (main thread or scheduling loop) after `processBlock` returns and post a `.remove`
event to the pending queue:
```swift
// After engine.processBlock — on main/scheduling thread:
if envelopeGen.needsFree {
engine.remove(synth)
}
```
Do not call `engine.remove` from within the RT callback — that would post to `pendingQueue` from
the RT thread, which violates the no-queue-posts-from-RT rule. The removed instance is routed
through `freeQueue` for off-RT deallocation.
## Polyphonic Voice Pools
`VoicePool<S: SynthesizerBase>` manages N pre-allocated synthesizer instances as polyphonic voices. All logic is language-side — no RT changes.
### Setup
```swift
let group = Group()
try engine.add(group)
let pool = try VoicePool(
voiceCount: 8,
group: group,
engine: engine,
stealStrategy: .oldest
) {
let s = MySynth()
s.gate = 0.0
return s
}
```
`VoicePoolError.invalidVoiceCount` is thrown when `voiceCount < 1`.
### Note-on / note-off
```swift
let voice = pool.noteOn(note: 60) // allocates or steals; returns S
voice.freq = midiToHz(60)
voice.gate = 1.0
voice.gate = 0.0
pool.noteOff(note: 60) // marks voice free; pool does not gate it down
pool.allNotesOff() // marks all voices free
```
### Steal strategies
| Case | Behavior |
|---|---|
| `.oldest` | Steals the voice playing longest (min trigger serial). Default. |
| `.roundRobin` | Cycles through voices in index order. |
| `.quietest` | Reads `@LiveParam` named `"amplitude"`, `"amp"`, or `"gain"` via `Mirror`; steals the lowest. Falls back to `.oldest` when no amp param found. |
| `.lowestAmplitude` | Alias for `.quietest`. |
All pool methods are main-thread only.
## Legacy Reference
These files are in `legacy/Lyrebird/LyrebirdSynth/Lyrebird/` — the legacy prototype. They are **not** in the current codebase; they are design references only.
- `LyrebirdNode.swift` — Group, linked list, head/tail
- `LyrebirdGraph.swift` — build closure, parameter dict, graph copy
- `AudioSampleGraphs.swift` — example Synthesizer definitions
File diff suppressed because it is too large Load Diff