v1.3.0 release: graceful-release fix, quickstart template + demo, documentation accuracy pass

- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated
  synths were hard-freed instead of released).
- New: quickstart project template + LyrebirdQuickstartDemo.
- Docs: every example typechecked or provably illustrative (426->542); ~20
  wrong-API examples fixed; root docs brought under the compile guard.
- Fixed: NRT/Score demo Package.swift build from terminal again.

See RELEASES.md for details.
This commit is contained in:
2026-07-17 14:05:01 -07:00
parent 63d6e0746f
commit 560724d116
149 changed files with 5010 additions and 1029 deletions
@@ -240,6 +240,11 @@ public final class NRTDriver: AudioDriver {
throw NRTDriverError.writeFailed(writeStatus)
}
}
// Synchronous render is done and the freeWorker timer only starts after this
// returns — emit any per-block event-drop warning here so it reaches the console
// even if the process exits before that timer (or `stop()`) runs.
engine.drainPerBlockEventDropWarning()
}
public func stop() {
@@ -33,112 +33,138 @@
///
/// ## Per-distribution examples
///
/// All examples use `TemporalTendency` with fixed `.value(…)` parameters and
/// `seed: 0xDEADCAFE12345678`. Actual outputs vary with seed.
/// All examples build a ``TemporalStream`` over a ``TemporalTendency`` with fixed
/// `.value(…)` parameters and `seed: 0xDEADCAFE12345678` — the seed lives on the stream,
/// not on the algorithm. Actual outputs vary with seed. The values below are pinned by
/// `DistributionKindGoldenValueTests`, since a typecheck cannot see them drift.
///
/// **`.uniform`** — flat probability across \[lo, hi\]
/// ```swift
/// TemporalTendency(distribution: .uniform, parX: .value(0), parY: .value(1), seed: s)
/// TemporalStream(TemporalTendency(distribution: .uniform,
/// parX: .value(0), parY: .value(1)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 0.744, 0.046, 0.799, 0.681, 0.517
/// ```
///
/// **`.lpRand`** — squared uniform, biases toward lo
/// ```swift
/// TemporalTendency(distribution: .lpRand, parX: .value(0), parY: .value(1), seed: s)
/// // → 0.080, 0.337, 0.057, 0.830, 0.788
/// TemporalStream(TemporalTendency(distribution: .lpRand,
/// parX: .value(0), parY: .value(1)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 0.553, 0.002, 0.638, 0.464, 0.267
/// ```
///
/// **`.hpRand`** — squared uniform mirrored, biases toward hi
/// ```swift
/// TemporalTendency(distribution: .hpRand, parX: .value(0), parY: .value(1), seed: s)
/// // → 0.878, 0.944, 0.939, 0.983, 0.899
/// TemporalStream(TemporalTendency(distribution: .hpRand,
/// parX: .value(0), parY: .value(1)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 0.447, 0.998, 0.362, 0.536, 0.733
/// ```
///
/// **`.meanRand`** — average of two uniforms (triangular), biases toward midpoint
/// ```swift
/// TemporalTendency(distribution: .meanRand, parX: .value(0), parY: .value(1), seed: s)
/// // → 0.624, 0.559, 0.512, 0.586, 0.308
/// TemporalStream(TemporalTendency(distribution: .meanRand,
/// parX: .value(0), parY: .value(1)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 0.395, 0.740, 0.400, 0.410, 0.899
/// ```
///
/// **`.expRand`** — log-uniform, exponential density in \[lo, hi\]; lo and hi must be > 0
/// ```swift
/// TemporalTendency(distribution: .expRand, parX: .value(1), parY: .value(100), seed: s)
/// // → 15.709, 4.710, 14.831, 26.119, 47.853
/// TemporalStream(TemporalTendency(distribution: .expRand,
/// parX: .value(1), parY: .value(100)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 30.743, 1.234, 39.596, 23.035, 10.818
/// ```
///
/// **`.exponential`** — standard exponential; parX is the rate λ (higher = shorter tail)
/// ```swift
/// TemporalTendency(distribution: .exponential, parX: .value(1), seed: s)
/// // → 0.023, 0.489, 0.126, 2.077, 0.354
/// TemporalStream(TemporalTendency(distribution: .exponential, parX: .value(1)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 0.296, 3.085, 0.225, 0.384, 0.660
/// ```
///
/// **`.gamma`** — shape parameter k; k=1 → exponential, k>1 → bell shifted right
/// ```swift
/// TemporalTendency(distribution: .gamma, parX: .value(2), seed: s)
/// // → 0.412, 2.998, 0.709, 1.409, 3.985
/// TemporalStream(TemporalTendency(distribution: .gamma, parX: .value(2)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 2.812, 0.776, 1.756, 1.326, 3.649
/// ```
///
/// **`.laplace`** — double-exponential, sharp central peak; parX is scale b
/// ```swift
/// TemporalTendency(distribution: .laplace, parX: .value(1), seed: s)
/// // → 3.533, 0.530, -0.197, 0.195, -1.792
/// TemporalStream(TemporalTendency(distribution: .laplace, parX: .value(1)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 0.669, -2.392, 0.910, 0.450, 0.035
/// ```
///
/// **`.alaplace`** — asymmetric Laplace (p=0.7), right tail heavier; parX is scale b
/// ```swift
/// TemporalTendency(distribution: .alaplace, parX: .value(1), seed: s)
/// // → -0.706, 7.906, 1.867, -0.495, 1.675
/// TemporalStream(TemporalTendency(distribution: .alaplace, parX: .value(1)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 0.527, -3.898, 1.332, -0.039, -0.433
/// ```
///
/// **`.hcos`** — half-cosine, smooth bell centred at 0; output ≈ \[−d/π, d/π\]
/// ```swift
/// TemporalTendency(distribution: .hcos, parX: .value(1), seed: s)
/// // → -0.080, 0.021, 0.024, -0.366, 0.215
/// TemporalStream(TemporalTendency(distribution: .hcos, parX: .value(1)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 0.162, -0.363, 0.204, 0.118, 0.011
/// ```
///
/// **`.logistic`** — logistic distribution, heavier tails than Gaussian; parX is scale s
/// ```swift
/// TemporalTendency(distribution: .logistic, parX: .value(1), seed: s)
/// // → 0.299, 3.453, -1.994, 1.842, -0.640
/// TemporalStream(TemporalTendency(distribution: .logistic, parX: .value(1)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 1.066, -3.039, 1.379, 0.759, 0.068
/// ```
///
/// **`.poisson`** — integer counts; parX is mean λ (clamped to \[0.001, 30\])
/// ```swift
/// TemporalTendency(distribution: .poisson, parX: .value(3), seed: s)
/// // → 3.0, 3.0, 6.0, 5.0, 0.0
/// TemporalStream(TemporalTendency(distribution: .poisson, parX: .value(3)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 1.000, 4.000, 4.000, 1.000, 4.000
/// ```
///
/// **`.arcsin`** — U-shaped, concentrates near ±dispersion; output in \[−disp, disp\]
/// ```swift
/// TemporalTendency(distribution: .arcsin, parX: .value(1), seed: s)
/// // → 0.616, -0.148, -0.986, -0.987, -0.417
/// TemporalStream(TemporalTendency(distribution: .arcsin, parX: .value(1)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 0.693, -0.990, 0.807, 0.539, 0.054
/// ```
///
/// **`.betaRand`** — flexible shape in \[lo, hi\]; alpha/beta (parA/parB) control skew
/// ```swift
/// // alpha=2, beta=5 → left-skewed bell (peak near lo side)
/// TemporalTendency(distribution: .betaRand,
/// parX: .value(0), parY: .value(1),
/// parA: .value(2), parB: .value(5), seed: s)
/// // → 0.395, 0.539, 0.272, 0.386, 0.304
/// TemporalStream(TemporalTendency(distribution: .betaRand,
/// parX: .value(0), parY: .value(1),
/// parA: .value(2), parB: .value(5)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 0.482, 0.301, 0.471, 0.415, 0.066
///
/// // alpha=1, beta=1 → uniform; alpha=beta → symmetric; alpha<1, beta<1 → bimodal
/// ```
///
/// **`.cauchy`** — heavy-tailed, parX=mean, parY=spread; set parA>0 for positive-only
/// ```swift
/// TemporalTendency(distribution: .cauchy, parX: .value(0), parY: .value(1), seed: s)
/// // → -1.457, 0.800, 10.047, 1.641, -1.570
/// TemporalStream(TemporalTendency(distribution: .cauchy,
/// parX: .value(0), parY: .value(1)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 0.962, -6.916, 1.366, 0.640, 0.054
/// // (occasional extreme outliers are characteristic of Cauchy)
///
/// // Positive-only (parA > 0):
/// TemporalTendency(distribution: .cauchy, parX: .value(0), parY: .value(1), parA: .value(1))
/// TemporalStream(TemporalTendency(distribution: .cauchy, parX: .value(0),
/// parY: .value(1), parA: .value(1)))
/// ```
///
/// **`.gauss`** — Gaussian; parX=standard deviation, parY=mean
/// ```swift
/// TemporalTendency(distribution: .gauss, parX: .value(1), parY: .value(0), seed: s)
/// // → -0.554, 1.390, 0.086, -0.441, 2.156
/// TemporalStream(TemporalTendency(distribution: .gauss,
/// parX: .value(1), parY: .value(0)),
/// seed: 0xDEADCAFE12345678).collect(5)
/// // → 0.738, -0.281, -0.238, 0.068, 0.328
/// ```
public enum DistributionKind: Sendable {
+1
View File
@@ -165,6 +165,7 @@ public final class EngineHost: @unchecked Sendable {
numAudioBuses: config.numAudioBuses,
numControlBuses: config.numControlBuses,
eventQueueCapacity: config.eventQueueCapacity,
maxEventsPerBlock: config.maxEventsPerBlock,
driver: config.driver
)
@@ -19,6 +19,9 @@ import Foundation
/// would invoke the mutation off-main.
/// - `LyrebirdAudioUnit.allocateRenderResources()` — overrides a nonisolated `AUAudioUnit`
/// method; AU hosts *usually* call it on main, but the contract does not guarantee it.
/// - `LyrebirdRoutineContext.onMain(_:)` — lets a `@Sendable` routine/task body construct
/// `@MainActor` synthesizers. A body always runs on its own background thread, so this
/// caller always takes the off-main `.sync` branch.
///
/// A bare `MainActor.assumeIsolated` would **trap** (`dispatch_assert_queue_fail`) on those
/// off-main paths. This bridge instead:
+91 -12
View File
@@ -29,14 +29,18 @@ import Synchronization
/// driver: driver
/// )
/// try engine.start()
/// engine.add(MySynth())
/// try engine.add(MySynth())
/// // … audio running …
/// engine.stop()
/// ```
///
/// **Thread safety** — `processBlock` runs on the Core Audio RT thread. All public
/// scheduling methods (`add`, `remove`, `schedule`) are safe to call from the main thread.
/// Never call `processBlock` directly from the main thread while the engine is running.
/// **Thread safety** — `processBlock` runs on the Core Audio RT thread; never call it directly
/// while the engine is running. `add(_:)` / `schedule(_:at:)` are `@MainActor`-isolated: the
/// `pendingQueue` is single-producer, so every enqueue must come from the main thread.
/// `remove(_:)` is `nonisolated` — it unbinds via atomics and enqueues a pointer-only event, so
/// it is callable from any non-RT thread. From a `LyrebirdRoutine` / `LyrebirdTask` body, go
/// through the context (``LyrebirdRoutineContext/add(_:)``, which dispatches to main) rather
/// than calling the engine directly. See `ARCHITECTURE.md` §1 and §9.
public final class SynthesisEngine {
/// Process-unique identity. Used by the engine ownership-binding system
@@ -158,7 +162,12 @@ public final class SynthesisEngine {
/// Hard cap on events processed per block. The staging arrays are reserved to this capacity
/// in start(); if more events arrive, excess events are silently dropped rather than
/// triggering a realloc on the RT thread.
private static let maxEventsPerBlock: Int = 256
///
/// Bounds both the number of events firing within one block and the future-event
/// look-ahead carried across block boundaries (`carryOverEvents`). Set at `init` from
/// the `maxEventsPerBlock` parameter; immutable thereafter, so the RT thread reads it
/// as a plain `let` with no synchronisation. Default `lyrebirdDefaultMaxEventsPerBlock`.
public let maxEventsPerBlock: Int
/// Lock-free queue for events posted by the main thread, drained by the RT thread.
/// Capacity is set at init time and must be a power of two.
@@ -192,6 +201,64 @@ public final class SynthesisEngine {
_droppedCount.wrappingAdd(1, ordering: .relaxed)
}
/// Monotonic counter of scheduling events dropped by the RT thread because a single
/// block's event budget (`maxEventsPerBlock`) was exceeded — either too many events
/// fired in one block or the future-event look-ahead overflowed. Distinct from
/// `pendingQueueDroppedCount`, which counts main-thread enqueue failures. Read from
/// any thread; reset with `resetPerBlockEventDropCount()`.
private let _perBlockEventDroppedCount: Atomic<UInt64> = Atomic<UInt64>(0)
/// Latch set by the RT thread when it drops at least one event for exceeding
/// `maxEventsPerBlock`. A non-RT drain (`drainPerBlockEventDropWarning()`) checks,
/// prints a one-line console warning, and clears it — so the warning is emitted at
/// most once per drain interval regardless of how many events were dropped.
private let _perBlockEventDropped: Atomic<Bool> = Atomic<Bool>(false)
/// Number of scheduling events the RT thread dropped because `maxEventsPerBlock` was
/// exceeded since the engine started (or since the last `resetPerBlockEventDropCount()`).
/// A non-zero value means a block's onset density or future look-ahead exceeded the cap —
/// raise `maxEventsPerBlock` at engine init, or throttle scheduling on the caller side.
public var perBlockEventDropCount: UInt64 {
_perBlockEventDroppedCount.load(ordering: .acquiring)
}
/// Resets the per-block event-drop counter to zero. Call from any non-RT thread.
public func resetPerBlockEventDropCount() {
_perBlockEventDroppedCount.store(0, ordering: .releasing)
}
/// Records a per-block event-budget drop. RT-safe: two atomic ops, no allocation,
/// no locking, no string construction. Called from `processBlock`'s event-drain loop
/// when a staging array is already at `maxEventsPerBlock`.
///
/// The counter increment is `.relaxed`; the latch store is `.releasing` so it
/// synchronizes-with the drain's `.acquiring` CAS in `drainPerBlockEventDropWarning()`.
/// That release/acquire edge guarantees the drain thread, once it observes the latch
/// set, also sees the counter increment that precedes it in program order — so the
/// printed drop count is never stale.
@inline(__always)
private func _recordPerBlockEventDrop() {
_perBlockEventDroppedCount.wrappingAdd(1, ordering: .relaxed)
_perBlockEventDropped.store(true, ordering: .releasing)
}
/// Checks the per-block event-drop latch and, if set, prints a one-line console
/// warning naming `maxEventsPerBlock` and the cumulative drop count, then clears the
/// latch. Non-RT only — shares the `freeWorker`/stop drain sites with the kill-queue
/// overflow warning so no RT-thread `print` is ever attempted.
internal func drainPerBlockEventDropWarning() {
guard _perBlockEventDropped.compareExchange(
expected: true,
desired: false,
successOrdering: .acquiring,
failureOrdering: .relaxed
).exchanged else { return }
let dropped: UInt64 = _perBlockEventDroppedCount.load(ordering: .relaxed)
print("[Lyrebird] Warning: scheduling events dropped — a block exceeded "
+ "maxEventsPerBlock (\(maxEventsPerBlock)); \(dropped) event(s) dropped so far. "
+ "Raise maxEventsPerBlock at engine init, or throttle/spread scheduling.")
}
/// Update the synth/group counters by `delta` (typically `+1` or `-1`).
/// Called from `applyEvent` on the RT thread — uses relaxed atomic adds (no allocation,
/// no locks, no runtime type checks). The `isGroup` flag is read from `PreparedNode`,
@@ -732,13 +799,13 @@ public final class SynthesisEngine {
///
/// ```swift
/// // Pre-processing: runs before all instruments
/// engine.add(InputLimiter(), position: .before(engine.mainGroup))
/// try engine.add(InputLimiter(), position: .before(engine.mainGroup))
///
/// // Default instrument add — lands in mainGroup
/// engine.add(MySynth())
/// try engine.add(MySynth())
///
/// // Post-processing: runs after all instruments
/// engine.add(MasterReverb(), position: .after(engine.mainGroup))
/// try engine.add(MasterReverb(), position: .after(engine.mainGroup))
/// ```
public let mainGroup: Group = Group(persistent: true)
@@ -763,6 +830,7 @@ public final class SynthesisEngine {
numAudioBuses: Int = lyrebirdDefaultNumAudioBuses,
numControlBuses: Int = lyrebirdDefaultNumControlBuses,
eventQueueCapacity: Int = lyrebirdDefaultEventQueueCapacity,
maxEventsPerBlock: Int = lyrebirdDefaultMaxEventsPerBlock,
driver: AudioDriver
) {
// Initialise RT-thread identity TLS key from this known non-RT call
@@ -780,6 +848,10 @@ public final class SynthesisEngine {
eventQueueCapacity > 0 && eventQueueCapacity & (eventQueueCapacity - 1) == 0,
"eventQueueCapacity \(eventQueueCapacity) must be a power of two (e.g. 256, 512, 1024, 2048)."
)
precondition(
maxEventsPerBlock > 0,
"maxEventsPerBlock \(maxEventsPerBlock) must be positive."
)
// Resolution order: explicit caller value → driver suggestion → full block (no sub-blocking).
// Explicit values are validated strictly. Driver suggestions that don't fit blockSize are
// silently ignored (fall back to full-block mode) so small-blockSize test engines don't crash.
@@ -811,6 +883,7 @@ public final class SynthesisEngine {
self.numInputChannels = numInputChannels
self.numAudioBuses = numAudioBuses
self.numControlBuses = numControlBuses
self.maxEventsPerBlock = maxEventsPerBlock
self.busAllocator = BusAllocator(
numAudioBuses: numAudioBuses,
numControlBuses: numControlBuses,
@@ -998,9 +1071,9 @@ public final class SynthesisEngine {
// Pre-allocate staging arrays to the hard cap — no RT realloc as long as
// events-per-block stays within maxEventsPerBlock (excess are dropped).
carryOverEvents.reserveCapacity(SynthesisEngine.maxEventsPerBlock)
thisBlockEvents.reserveCapacity(SynthesisEngine.maxEventsPerBlock)
nextCarryOver.reserveCapacity(SynthesisEngine.maxEventsPerBlock)
carryOverEvents.reserveCapacity(maxEventsPerBlock)
thisBlockEvents.reserveCapacity(maxEventsPerBlock)
nextCarryOver.reserveCapacity(maxEventsPerBlock)
// Force eager initialization of module-level `let` constants used by RBJ filters.
// Swift module-level lets are protected by swift_once on first access; touching them
@@ -1076,6 +1149,7 @@ public final class SynthesisEngine {
}
self.drainParameterSourceKillQueue()
self.drainBufferSwapKillQueue()
self.drainPerBlockEventDropWarning()
}
_setState(.stopped)
}
@@ -1493,7 +1567,7 @@ public final class SynthesisEngine {
// Read clock atomically; only processBlock writes it (RT thread single-writer).
let blockStart: SampleTime = _currentTime.load(ordering: .relaxed)
let blockEnd: SampleTime = blockStart + SampleTime(blockSize)
let cap: Int = SynthesisEngine.maxEventsPerBlock
let cap: Int = maxEventsPerBlock
thisBlockEvents.removeAll(keepingCapacity: true)
nextCarryOver.removeAll(keepingCapacity: true)
@@ -1502,8 +1576,10 @@ public final class SynthesisEngine {
for event: ScheduledEvent in carryOverEvents {
if event.targetTime < blockEnd {
if thisBlockEvents.count < cap { thisBlockEvents.append(event) }
else { _recordPerBlockEventDrop() }
} else {
if nextCarryOver.count < cap { nextCarryOver.append(event) }
else { _recordPerBlockEventDrop() }
}
}
@@ -1512,8 +1588,10 @@ public final class SynthesisEngine {
let event: ScheduledEvent = pendingQueue.dequeue() {
if event.targetTime < blockEnd {
if thisBlockEvents.count < cap { thisBlockEvents.append(event) }
else { _recordPerBlockEventDrop() }
} else {
if nextCarryOver.count < cap { nextCarryOver.append(event) }
else { _recordPerBlockEventDrop() }
}
}
@@ -1780,6 +1858,7 @@ public final class SynthesisEngine {
}
self.drainParameterSourceKillQueue()
self.drainBufferSwapKillQueue()
self.drainPerBlockEventDropWarning()
}
timer.resume()
freeQueueTimer = timer
@@ -65,6 +65,10 @@ public struct SynthesisEngineConfig {
/// `lyrebirdDefaultEventQueueCapacity`.
public let eventQueueCapacity: Int
/// Per-block scheduling cap — events firing per block and future look-ahead
/// depth. Must be positive. Defaults to `lyrebirdDefaultMaxEventsPerBlock`.
public let maxEventsPerBlock: Int
/// Audio driver instance. Held by the engine via `let driver` after
/// `init`. Caller transfers ownership at construction time.
public let driver: AudioDriver
@@ -78,6 +82,7 @@ public struct SynthesisEngineConfig {
numAudioBuses: Int = lyrebirdDefaultNumAudioBuses,
numControlBuses: Int = lyrebirdDefaultNumControlBuses,
eventQueueCapacity: Int = lyrebirdDefaultEventQueueCapacity,
maxEventsPerBlock: Int = lyrebirdDefaultMaxEventsPerBlock,
driver: AudioDriver
) {
self.blockSize = blockSize
@@ -88,6 +93,7 @@ public struct SynthesisEngineConfig {
self.numAudioBuses = numAudioBuses
self.numControlBuses = numControlBuses
self.eventQueueCapacity = eventQueueCapacity
self.maxEventsPerBlock = maxEventsPerBlock
self.driver = driver
}
}
@@ -22,7 +22,7 @@ import Foundation
/// Control-rate, 4-output: see ``BeatTrack/Control`` for the row layout.
///
/// > This is an independent implementation of standard autocorrelation tempo
/// > induction with phase locking (see ``BeatTrackerCore``), not a port of any
/// > induction with phase locking (see `BeatTrackerCore`), not a port of any
/// > SuperCollider source.
public enum BeatTrack {
@@ -51,7 +51,7 @@ public enum DiskOut {
/// output(bus: 0, source: diskOut[0]) // pass-through to bus 0
/// }
/// }
/// engine.add(Writer())
/// try engine.add(Writer())
/// try engine.start() // render / play
/// diskOut.close() // flush remaining frames and close the file
/// ```
@@ -376,7 +376,7 @@ public enum EnvelopeGen {
/// ```swift
/// let env = Envelope(levels: [0, 1, 0], durations: [0.01, 0.5], curves: [.sine, .exponential])
/// let gen = EnvelopeGen.Audio(envelope: env, doneAction: .freeNode)
/// // After processBlock: if gen.needsFree { engine.schedule(.remove(synth), at: now) }
/// // After processBlock: if gen.needsFree { engine.remove(synth) }
/// ```
///
/// - Parameters:
@@ -46,7 +46,7 @@ private let klankLog0001: Double = log(0.001)
/// Each is any `ValidGeneratorInput`, snapshotted once per audio block (block-rate / "control
/// rate" respecification). Wire a control generator to glide the bank's tuning or ring time
/// while it sounds. The full table can additionally be swapped at run time via
/// ``setBuffer(_:engine:)`` (RT-safe ``RTBufferSlot`` handoff), so both per-mode editing and
/// ``Klank/Audio/setBuffer(_:engine:)`` (RT-safe ``RTBufferSlot`` handoff), so both per-mode editing and
/// whole-table replacement are available.
///
/// ## Difference equation (per resonator k)
+1 -1
View File
@@ -10,7 +10,7 @@
///
/// Control-rate only — intended for live gain knobs authored in dB (e.g. a pedal's
/// output-level control) that need to drive another generator's linear gain input
/// every block. Wraps the scalar ``dbToAmp(_:)`` helper so the conversion formula
/// every block. Wraps the scalar `dbToAmp(_:)` helper so the conversion formula
/// lives in one place.
///
/// - Parameter signal: Input value in decibels.
@@ -27,7 +27,7 @@ public let klangFreqChannel: Int = 0
public let klangAmpChannel: Int = 1
/// Buffer channel index of the per-partial initial phase (cycles, `[0, 1)`). Read once at
/// `init` to seed the phase accumulator; ignored on later ``setBuffer(_:engine:)`` swaps.
/// `init` to seed the phase accumulator; ignored on later ``Klang/Audio/setBuffer(_:engine:)`` swaps.
public let klangPhaseChannel: Int = 2
/// Bank of N summed sine partials — the additive-synthesis counterpart of ``Klank``.
@@ -44,7 +44,7 @@ public let klangPhaseChannel: Int = 2
///
/// Both are any `ValidGeneratorInput`, snapshotted once per audio block (block-rate / "control
/// rate"). `freq` and `amp` are re-read from the table each block, so live `setValue` edits and
/// whole-table ``setBuffer(_:engine:)`` swaps retune the bank while it sounds. The `phase`
/// whole-table ``Klang/Audio/setBuffer(_:engine:)`` swaps retune the bank while it sounds. The `phase`
/// channel is **only** read at `init` to seed each partial's running phase accumulator — phases
/// free-run thereafter and are unaffected by later table swaps (so the bank never clicks on a
/// respecification).
@@ -24,7 +24,7 @@ private let schmidtZeroBlock: [Double] = [Double](
///
/// ```swift
/// // Gate signal on amplitude with 0.1/0.3 hysteresis band.
/// let amp = AmplitudeFollower.Audio(input: In.Audio(bus: 0))
/// let amp = AmplitudeFollower.Audio(in: In.Audio(bus: 0))
/// let gate = Schmidt.Audio(input: amp, lo: 0.1, hi: 0.3)
/// ```
///
@@ -26,7 +26,7 @@ private let signalChangedZeroBlock: [Double] = [Double](
///
/// ```swift
/// // Cheap onset proxy — fires whenever amplitude jumps > 0.05.
/// let amp = AmplitudeFollower.Audio(input: In.Audio(bus: 0))
/// let amp = AmplitudeFollower.Audio(in: In.Audio(bus: 0))
/// let edge = SignalChanged.Audio(input: amp, threshold: 0.05)
/// addOutputGenerator(SendTrigger.Audio(trig: edge, id: 1))
/// ```
@@ -22,7 +22,7 @@ private let trigZeroBlock: [Double] = [Double](
///
/// ```swift
/// // Capture amplitude and hold it for 0.1 s every time a trigger fires.
/// let amp = AmplitudeFollower.Audio(input: In.Audio(bus: 0))
/// let amp = AmplitudeFollower.Audio(in: In.Audio(bus: 0))
/// let clock = Impulse.Audio(freq: 4.0)
/// let pulse = Trig.Audio(input: amp, dur: 0.1)
/// ```
+61 -27
View File
@@ -53,6 +53,10 @@ All bus parameters in `In`, `Out`, and the ``SynthesizerBase`` helpers accept an
This means you can store and pass bus allocations directly without extracting `.index`:
```swift
// In real code myAudioBus comes from engine.busAllocator — see "Allocating User Buses" below.
let myAudioBus: AudioBus = AudioBus(index: 4, channelCount: 2)
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
// Before: extract .index manually
output(bus: myAudioBus.index, source: sig)
@@ -69,17 +73,20 @@ consecutive control buses and delivers an interpolated audio-rate ramp per chann
The channel count is an init-time constant — no RT allocation.
```swift
let myAudioBus: AudioBus = AudioBus(index: 4, channelCount: 2)
let myCtrlBus: ControlBus = ControlBus(index: 10, channelCount: 2)
// Single-channel (plain Int)
In.Audio(bus: 2) // AudioGenerator — reads audioBuses[2], 1 channel
In.Control(bus: 10) // ControlGenerator — reads controlBuses[10], interpolated ramp
let a: In.Audio = In.Audio(bus: 2) // reads audioBuses[2], 1 channel
let b: In.Control = In.Control(bus: 10) // reads controlBuses[10], interpolated ramp
// AudioBus / ControlBus — channel count inferred from allocation
In.Audio(bus: myAudioBus) // reads myAudioBus.channelCount consecutive audio buses
In.Control(bus: myCtrlBus) // reads myCtrlBus.channelCount consecutive control buses
let c: In.Audio = In.Audio(bus: myAudioBus) // reads myAudioBus.channelCount audio buses
let d: In.Control = In.Control(bus: myCtrlBus) // reads myCtrlBus.channelCount control buses
// Explicit multi-channel override
In.Audio(bus: 4, channels: 3) // reads audioBuses[4], [5], [6]
In.Control(bus: 10, channels: 2) // reads controlBuses[10] and [11]; independent ramps
let e: In.Audio = In.Audio(bus: 4, channels: 3) // reads audioBuses[4], [5], [6]
let f: In.Control = In.Control(bus: 10, channels: 2) // controlBuses[10] and [11]; independent ramps
```
Use `input(bus:channels:)` inside `SynthesizerBase.build()` for a ``GeneratorArray`` of
@@ -95,11 +102,16 @@ input(bus: 2, channels: 2) // → GeneratorArray reading buses 2 and 3
same bus mix additively (polyphony, send-return routing).
```swift
Out.Audio(bus: 0, source: sig) // plain Int bus
Out.Audio(bus: myAudioBus, source: sig) // clamped to myAudioBus.channelCount
let myAudioBus: AudioBus = AudioBus(index: 4, channelCount: 2)
let myCtrlBus: ControlBus = ControlBus(index: 10, channelCount: 2)
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfo: OscSin.Control = OscSin.Control(freq: 2.0)
Out.Control(bus: 10, source: lfo) // plain Int bus
Out.Control(bus: myCtrlBus, source: lfo) // clamped to myCtrlBus.channelCount
let a: Out.Audio = Out.Audio(bus: 0, source: sig) // plain Int bus
let b: Out.Audio = Out.Audio(bus: myAudioBus, source: sig) // clamped to channelCount
let c: Out.Control = Out.Control(bus: 10, source: lfo) // plain Int bus
let d: Out.Control = Out.Control(bus: myCtrlBus, source: lfo) // clamped to channelCount
```
### Multi-Channel Out
@@ -108,11 +120,14 @@ When the source returns N channels, ``Out`` writes channel `ch` to `bus.index +
to both audio and control buses:
```swift
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
let stereoControlSrc: GeneratorArray = expand([2.0, 3.0]) { OscSin.Control(freq: $0) }
// Stereo audio source writes buses 0 and 1:
Out.Audio(bus: 0, source: Pan2(input: osc, pan: 0.0))
let a: Out.Audio = Out.Audio(bus: 0, source: Pan2(input: osc, pan: 0.0))
// Multi-channel control source writes controlBuses[10] and [11]:
Out.Control(bus: 10, source: stereoControlSrc)
let b: Out.Control = Out.Control(bus: 10, source: stereoControlSrc)
```
Mono sources return one channel and write only `bus.index`.
@@ -122,13 +137,29 @@ Mono sources return one channel and write only `bus.index`.
Inside `build()`, the helpers accept any ``ValidBus``:
```swift
override func build() {
let osc = OscSin.Audio(freq: freq)
output(bus: outbus, source: Pan2(input: osc * amp)) // AudioBus or Int
controlOutput(bus: ctrlBus, source: lfo) // ControlBus or Int
final class BusRoutingSynth: SynthesizerBase {
@LiveParam var freq: Double = 440.0
@LiveParam var amp: Double = 0.5
let sig = input(bus: inbus) // AudioBus or Int
let ctrl = controlInput(bus: ctrlInBus) // ControlBus or Int
// Hardcoded indices here for illustration. In real code, obtain user buses from
// engine.busAllocator (see "Allocating User Buses" below) rather than hand-picking
// indices, which risks colliding with hardware buses or other synths.
let outbus: AudioBus = AudioBus(index: 0, channelCount: 2)
let inbus: AudioBus = AudioBus(index: 4, channelCount: 1)
let ctrlBus: ControlBus = ControlBus(index: 10)
let ctrlInBus: ControlBus = ControlBus(index: 11)
override func build() {
let osc: OscSin.Audio = OscSin.Audio(freq: $freq)
let lfo: OscSin.Control = OscSin.Control(freq: 2.0)
output(bus: outbus, source: Pan2(input: osc * $amp)) // AudioBus or Int
controlOutput(bus: ctrlBus, source: lfo) // ControlBus or Int
let sig: In.Audio = input(bus: inbus) // AudioBus or Int
let ctrl: In.Control = controlInput(bus: ctrlInBus) // ControlBus or Int
output(bus: 2, source: sig * ctrl)
}
}
```
@@ -157,18 +188,21 @@ don't track raw indices manually. Hardware output and input buses are pre-reserv
allocation starts from the first free bus after them.
```swift
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfo: OscSin.Control = OscSin.Control(freq: 2.0)
// Allocate buses
let stereo = try engine.busAllocator.allocateAudioBus(channelCount: 2)
let ctrl = try engine.busAllocator.allocateControlBus() // single channel
let ctrl2ch = try engine.busAllocator.allocateControlBus(channelCount: 2)
let stereo: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 2)
let ctrl: ControlBus = try engine.busAllocator.allocateControlBus() // single channel
let ctrl2ch: ControlBus = try engine.busAllocator.allocateControlBus(channelCount: 2)
// Pass directly to In / Out / SynthesizerBase helpers — no .index needed
let reader = In.Audio(bus: stereo) // reads stereo.channelCount buses
let multi = In.Audio.multi(bus: stereo) // GeneratorArray — one gen per channel
let writer = Out.Audio(bus: stereo, source: sig) // clamped to stereo.channelCount
let ctrlIn = In.Control(bus: ctrl) // single-channel ramp
let ctrl2In = In.Control(bus: ctrl2ch) // 2-channel, buses ctrl2ch.index and +1
let ctrlOut = Out.Control(bus: ctrl2ch, source: lfo) // clamped to ctrl2ch.channelCount
let reader: In.Audio = In.Audio(bus: stereo) // reads stereo.channelCount buses
let multi: GeneratorArray = In.Audio.multi(bus: stereo) // one gen per channel
let writer: Out.Audio = Out.Audio(bus: stereo, source: sig) // clamped to channelCount
let ctrlIn: In.Control = In.Control(bus: ctrl) // single-channel ramp
let ctrl2In: In.Control = In.Control(bus: ctrl2ch) // 2-channel, ctrl2ch.index and +1
let ctrlOut: Out.Control = Out.Control(bus: ctrl2ch, source: lfo) // clamped to channelCount
// Release when the synthesizer is done
engine.busAllocator.releaseAudioBus(stereo)
+1 -1
View File
@@ -59,7 +59,7 @@ MyPiece/
**Templates** — `--template <name>`:
- SPM-only: `basic` (default), `demo`, `ui-demo`, `nrt` — open `Package.swift` in Xcode
- SPM-only: `quickstart` (fastest sound), `basic` (default), `demo`, `ui-demo`, `nrt`, `score` — open `Package.swift` in Xcode
- Xcode-project: `macos-ui-xcode`, `ios-ui`, `auv3` — emit a full `<name>.xcodeproj` for `.app` / `.appex` deliverables. See <doc:ProjectSystem> for full layout per template.
### `lyrebird run [--release]`
+74 -24
View File
@@ -8,21 +8,52 @@ Configure and start a ``SynthesisEngine`` with hardware I/O or offline rendering
## Initialization
Five parameters are required; every other one defaults.
```swift
SynthesisEngine(
blockSize: Int, // samples per render callback (e.g. 512)
sampleRate: Double, // e.g. 44100, 48000
numOutputChannels: Int, // hardware output channels (e.g. 2)
numInputChannels: Int, // hardware input channels (e.g. 0 or 2)
numAudioBuses: Int, // default 128
numControlBuses: Int, // default 4096
driver: AudioDriver // CoreAudioDriver, NRTDriver, or OfflineDriver
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()
)
```
`SynthesisEngine.init` enforces `blockSize ≤ lyrebirdDefaultResultBufferSize` (512) — this is the
maximum block size supported by all built-in generators. It also allocates and fills `sharedTables`
on the calling (non-RT) thread, so lookup tables are ready before the first render callback.
The full parameter list is ``SynthesisEngine/init(blockSize:controlBlockSize:sampleRate:numOutputChannels:numInputChannels:numAudioBuses:numControlBuses:eventQueueCapacity:maxEventsPerBlock:driver:)``:
| Parameter | Meaning | Default |
|---|---|---|
| `blockSize` | Samples per render callback (e.g. 512). | *required* |
| `controlBlockSize` | Control-rate sub-block size. `nil` asks the driver for its preference; if the driver has none, the engine runs at full-block control rate. | `nil` |
| `sampleRate` | Sample rate in Hz (e.g. 44100, 48000). | *required* |
| `numOutputChannels` | Hardware output channels reserved at bus indices `0..<n`. | *required* |
| `numInputChannels` | Hardware input channels, reserved directly above the outputs. | *required* |
| `numAudioBuses` | Total audio bus count. | ``lyrebirdDefaultNumAudioBuses`` |
| `numControlBuses` | Total control bus count. | ``lyrebirdDefaultNumControlBuses`` |
| `eventQueueCapacity` | `pendingQueue` ring occupancy. Must be a power of two. | ``lyrebirdDefaultEventQueueCapacity`` |
| `maxEventsPerBlock` | Per-block event budget — see below. | ``lyrebirdDefaultMaxEventsPerBlock`` |
| `driver` | ``CoreAudioDriver``, ``NRTDriver``, or ``OfflineDriver``. | *required* |
``SynthesisEngine/init(blockSize:controlBlockSize:sampleRate:numOutputChannels:numInputChannels:numAudioBuses:numControlBuses:eventQueueCapacity:maxEventsPerBlock:driver:)`` enforces `blockSize <= ` ``lyrebirdDefaultResultBufferSize`` — the maximum block size supported by all built-in generators. It also allocates and fills ``SynthesisEngine/sharedTables`` on the calling (non-RT) thread, so lookup tables are ready before the first render callback.
### Scheduling capacity
Two independent knobs bound scheduling. They are often confused:
| Parameter | Bounds | On overflow |
|---|---|---|
| `eventQueueCapacity` | `pendingQueue` ring occupancy — events enqueued but not yet drained *at one instant*. **Must be a power of two** (precondition, not rounded). | `add` / `schedule` throw `EngineAddError.pendingQueueFull`; `engine.pendingQueueDroppedCount` counts them |
| `maxEventsPerBlock` | Per-block budget: events *firing* in one block, **and** the future-event look-ahead carried across block boundaries. Must be `> 0`; power of two not required. | Surplus events are dropped by the RT thread; `engine.perBlockEventDropCount` counts them and a one-line console warning is printed off-RT |
`maxEventsPerBlock` — not `eventQueueCapacity` — is the ceiling that decides whether a large
batch of pre-scheduled events survives. The two are independent: `maxEventsPerBlock` may exceed
`eventQueueCapacity`, because carry-over accumulates across blocks while the ring only ever holds
a per-drain burst. Raising either costs pre-allocated memory only, never RT time.
Full model: <doc:Scheduling> and `docs/engine/scheduling.md`.
## Lifecycle
@@ -49,14 +80,25 @@ shared tables do not need to check `isValid`. Cache the reference in your genera
### User-Allocated Buffers
```swift
let buf = LyrebirdBuffer(count: lyrebirdDefaultTableSize)
buf.fill { i, n in Double(i) / Double(n) * 2.0 - 1.0 } // sawtooth
let osc = OscTable.Audio(table: buf, freq: 440.0)
try engine.add(mySynth) // buf now in RT use — do not fill again
final class TableSynth: SynthesizerBase {
// Filled at init — before the buffer ever reaches the RT thread.
let table: LyrebirdBuffer = {
let b: LyrebirdBuffer = LyrebirdBuffer(count: lyrebirdDefaultTableSize)
b.fill { i, n in Double(i) / Double(n) * 2.0 - 1.0 } // sawtooth
return b
}()
override func build() {
output(bus: 0, source: OscTable.Audio(table: table, freq: 440.0) * 0.2)
}
}
let mySynth: TableSynth = TableSynth()
try engine.add(mySynth) // table now in RT use — do not fill again
// Later, on the main thread:
buf.invalidate() // RT thread sees isValid == false and outputs silence
engine.remove(mySynth) // ARC releases buf when synth is freed via freeQueue
mySynth.table.invalidate() // RT thread sees isValid == false and outputs silence
engine.remove(mySynth) // ARC releases the table when the synth is freed via freeQueue
```
Fill methods must be called **before** the buffer enters RT use. `invalidate()` is RT-safe
@@ -101,18 +143,26 @@ where these fields live in scaffolded projects.
### Offline Rendering (NRTDriver)
```swift
let driver = NRTDriver(outputURL: url, duration: 10.0)
let engine = SynthesisEngine(
import Foundation
let url: URL = URL(fileURLWithPath: "/tmp/render.caf")
let driver: NRTDriver = NRTDriver(outputURL: url, duration: 10.0)
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 0,
driver: driver
)
// Pre-schedule the score
try engine.schedule(pad, at: 0)
try engine.schedule(kick, at: engine.seconds(0.5))
try engine.schedule(kick, at: engine.seconds(1.0))
engine.remove(pad, at: engine.seconds(8.0))
// Pre-schedule the score. Each onset needs its OWN instance — scheduling one
// instance twice throws `EngineAddError.doubleAdd`.
let pad: MySynth = MySynth()
let kick1: MySynth = MySynth()
let kick2: MySynth = MySynth()
try engine.schedule(pad, at: 0)
try engine.schedule(kick1, at: engine.seconds(0.5))
try engine.schedule(kick2, at: engine.seconds(1.0))
_ = engine.remove(pad, at: engine.seconds(8.0))
try engine.start() // renders synchronously, writes file, returns when done
```
@@ -54,7 +54,7 @@ midi.addHandler(name: "notes") { message, ctx in
switch message {
case .noteOn(_, let note, let vel) where vel > 0:
let synth = SineTone()
synth.$freq.value = midiNoteToHz(Double(note))
synth.$freq.value = midiToHz(Double(note))
synth.$amp.value = Double(vel) / 127.0
ctx.add(synth)
case .noteOff, .noteOn(_, _, 0):
@@ -86,7 +86,7 @@ midi.addHandler(name: "cc74") { message, ctx in
guard case .controlChange(_, 74, let value) = message,
let synth = activeSynth else { return }
let normalized = Double(value) / 127.0
try? ctx.set("cutoff", to: normalized * 8000.0, on: synth)
ctx.set("cutoff", to: normalized * 8000.0, on: synth)
}
```
@@ -160,7 +160,7 @@ let server = OSCServer(port: 57120, engine: engine)
server.addHandler(address: "/note") { msg, ctx in
guard let note = msg[0]?.intValue else { return }
let synth = SineTone()
synth.$freq.value = midiNoteToHz(Double(note))
synth.$freq.value = midiToHz(Double(note))
ctx.add(synth)
}
@@ -242,7 +242,7 @@ server.addHandler(address: "/synth/set") { msg, ctx in
guard let key = msg[0]?.stringValue,
let value = msg[1]?.floatValue,
let synth = activeSynth else { return }
try? ctx.set(key, to: Double(value), on: synth)
ctx.set(key, to: Double(value), on: synth)
}
```
@@ -272,7 +272,7 @@ let server = OSCServer(port: 57120, engine: engine)
// MIDI plays notes
midi.addHandler(name: "notes") { msg, ctx in
if case .noteOn(_, let note, let vel) = msg, vel > 0 {
let s = SineTone(); s.$freq.value = midiNoteToHz(Double(note)); ctx.add(s)
let s = SineTone(); s.$freq.value = midiToHz(Double(note)); ctx.add(s)
}
}
@@ -1,8 +1,4 @@
# GeneratorInputProvider
@Metadata {
@PageKind(article)
}
# ``GeneratorInputProvider``
Pass a fresh generator subgraph (or a scalar) per process spawn through any Generator slot that accepts `any ValidGeneratorInput`, without sharing RT state across Synthesizer instances.
@@ -9,16 +9,19 @@ Generators for reading from and writing to the Lyrebird bus system.
## Raw index form
```swift
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfo: OscSin.Control = OscSin.Control(freq: 2.0)
// Single-channel (default)
In.Audio(bus: 2) // AudioGenerator — reads audioBuses[2]
In.Control(bus: 10) // ControlGenerator — reads controlBuses[10], interpolated ramp
_ = In.Audio(bus: 2) // AudioGenerator — reads audioBuses[2]
_ = In.Control(bus: 10) // ControlGenerator — reads controlBuses[10], interpolated ramp
// Multi-channel — reads N consecutive buses, returns N channels (static at init)
In.Audio(bus: 4, channels: 3) // reads audioBuses[4], [5], [6]
In.Control(bus: 10, channels: 2) // reads controlBuses[10] and [11], independent ramps
_ = In.Audio(bus: 4, channels: 3) // reads audioBuses[4], [5], [6]
_ = In.Control(bus: 10, channels: 2) // reads controlBuses[10] and [11], independent ramps
Out.Audio(bus: 0, source: sig) // accumulates into audioBuses[0]
Out.Control(bus: 10, source: lfo) // accumulates into controlBuses[10]
_ = Out.Audio(bus: 0, source: sig) // accumulates into audioBuses[0]
_ = Out.Control(bus: 10, source: lfo) // accumulates into controlBuses[10]
```
## AudioBus / ControlBus form (preferred)
@@ -27,21 +30,24 @@ Use ``BusAllocator`` to obtain typed bus handles instead of raw integers, then p
to the convenience initialisers:
```swift
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfo: OscSin.Control = OscSin.Control(freq: 2.0)
let stereo = try engine.busAllocator.allocateAudioBus(channelCount: 2)
let ctrl = try engine.busAllocator.allocateControlBus()
// Multi-channel read — single generator, N-channel output (preferred)
In.Audio(bus: stereo) // channels == stereo.channelCount
_ = In.Audio(bus: stereo) // channels == stereo.channelCount
// Independent generators per channel — GeneratorArray
In.Audio.multi(bus: stereo)
_ = In.Audio.multi(bus: stereo)
// Write — clamped to stereo.channelCount channels
Out.Audio(bus: stereo, source: Pan2(input: osc, pan: 0.0))
_ = Out.Audio(bus: stereo, source: Pan2(input: osc, pan: 0.0))
// Control read / write
In.Control(bus: ctrl)
Out.Control(bus: ctrl, source: lfo)
_ = In.Control(bus: ctrl)
_ = Out.Control(bus: ctrl, source: lfo)
```
See <doc:BusSystem> for bus layout, reserved ranges, and allocator details.
@@ -13,15 +13,18 @@ Delay line generators shipped with the `Lyrebird` module.
Variable delay with no feedback. Power-of-2 circular buffer.
```swift
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfoGen: OscSin.Control = OscSin.Control(freq: 5.0, mul: 0.005, add: 0.02)
// Basic usage — sampleRate required to size the buffer correctly
DelayLine(input: sig, maxDelay: 1.0, delay: 0.25, sampleRate: 44100)
_ = DelayLine(input: sig, maxDelay: 1.0, delay: 0.25, sampleRate: 44100)
// Audio-rate modulation (vibrato, chorus, pitch effects)
DelayLine(input: sig, maxDelay: 0.05, delay: lfoGen, sampleRate: 44100,
interpolation: .cubic)
_ = DelayLine(input: sig, maxDelay: 0.05, delay: lfoGen, sampleRate: 44100,
interpolation: .cubic)
// 48 kHz engine
DelayLine(input: sig, maxDelay: 1.0, delay: 0.25, sampleRate: 48000)
_ = DelayLine(input: sig, maxDelay: 1.0, delay: 0.25, sampleRate: 48000)
```
### Parameters
@@ -52,17 +55,20 @@ Delay with exponential feedback decay. `decayTime` sets the time for the tail to
`targetAmp` (default −60 dB / 0.001). Supports audio-rate `delay` and `decayTime` modulation.
```swift
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfoGen: OscSin.Control = OscSin.Control(freq: 5.0, mul: 0.005, add: 0.02)
// Basic usage
DelayLineFeedback(input: sig, maxDelay: 1.0, delay: 0.25,
decayTime: 2.0, sampleRate: 44100)
_ = DelayLineFeedback(input: sig, maxDelay: 1.0, delay: 0.25,
decayTime: 2.0, sampleRate: 44100)
// Custom target amplitude (e.g. −40 dB)
DelayLineFeedback(input: sig, maxDelay: 0.5, delay: 0.25,
decayTime: 1.5, targetAmp: 0.01, sampleRate: 44100)
_ = DelayLineFeedback(input: sig, maxDelay: 0.5, delay: 0.25,
decayTime: 1.5, targetAmp: 0.01, sampleRate: 44100)
// Audio-rate delay modulation
DelayLineFeedback(input: sig, maxDelay: 0.5, delay: lfoGen,
decayTime: 2.0, sampleRate: 44100, interpolation: .linear)
_ = DelayLineFeedback(input: sig, maxDelay: 0.5, delay: lfoGen,
decayTime: 2.0, sampleRate: 44100, interpolation: .linear)
```
### Parameters
@@ -116,6 +116,7 @@ identical to ``EnvelopeGen/Audio``) and fills the output buffer with a linear ra
the block's target level. Intra-block shape detail is lost; use Audio-rate when that matters.
```swift
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
let env = Envelope(levels: [0, 1, 0.001], durations: [0.01, 0.5], curves: [.sine, .exponential])
// Audio-rate amplitude envelope. Constructed inside Synthesizer.build() with
@@ -135,6 +136,7 @@ let scaledEnv = EnvelopeGen.Audio(envelope: env,
// timeScale: stretches each segment's duration. Same shape, twice as long.
let slowEnv = EnvelopeGen.Audio(envelope: env, timeScale: 2.0 as Double)
_ = (ampEnv, filter, scaledEnv, slowEnv)
```
**Parameters:**
@@ -16,7 +16,8 @@ Butterworth cascades, and resonating/comb/allpass designs.
Single-pole IIR: `y[n] = a0·x[n] + a1·x[n-1] + b1·y[n-1]`
```swift
FirstOrderSection(input: sig, a0: 1.0, a1: 0.0, b1: 0.5)
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
_ = FirstOrderSection(input: sig, a0: 1.0, a1: 0.0, b1: 0.5)
```
All coefficient inputs accept any ``ValidGeneratorInput``. Generator inputs are read at audio
@@ -27,7 +28,8 @@ rate, enabling audio-rate coefficient modulation.
Two-pole biquad (Direct Form I): `y[n] = a0·x + a1·x[n-1] + a2·x[n-2] − b1·y[n-1] − b2·y[n-2]`
```swift
SecondOrderSection(input: sig, a0: 1.0, a1: 0.0, a2: 0.0, b1: 0.5, b2: 0.25)
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
_ = SecondOrderSection(input: sig, a0: 1.0, a1: 0.0, a2: 0.0, b1: 0.5, b2: 0.25)
```
Pass `b1` and `b2` as positive magnitudes — the subtraction is applied internally.
@@ -56,14 +58,17 @@ Frequencies above `0.999 × Nyquist` return silence. Shared infrastructure: `Biq
| ``RBJHighShelf`` | High-shelf boost/cut; `gain` in dB, `slope` controls transition steepness |
```swift
RBJLowPass.Audio(input: sig, freq: 800.0, q: 0.707) // Butterworth LPF
RBJHighPass.Audio(input: sig, freq: 400.0, q: 0.707)
RBJBandPass.Audio(input: sig, freq: 1000.0, bandwidth: 1.0) // 1-octave BPF
RBJNotch.Audio(input: sig, freq: 60.0, q: 10.0) // hum removal
RBJAllPass.Audio(input: sig, freq: lfoGen, q: 1.0) // phaser stage
RBJPeakingEQ.Audio(input: sig, freq: 1000.0, gain: 6.0, q: 1.0) // +6 dB at 1 kHz
RBJLowShelf.Audio(input: sig, freq: 200.0, gain: 6.0, slope: 1.0)
RBJHighShelf.Audio(input: sig, freq: 8000.0, gain: 3.0, slope: 1.0)
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfoGen: OscSin.Control = OscSin.Control(freq: 0.5, mul: 400.0, add: 800.0)
_ = RBJLowPass.Audio(input: sig, freq: 800.0, q: 0.707) // Butterworth LPF
_ = RBJHighPass.Audio(input: sig, freq: 400.0, q: 0.707)
_ = RBJBandPass.Audio(input: sig, freq: 1000.0, bandwidth: 1.0) // 1-octave BPF
_ = RBJNotch.Audio(input: sig, freq: 60.0, q: 10.0) // hum removal
_ = RBJAllPass.Audio(input: sig, freq: lfoGen, q: 1.0) // phaser stage
_ = RBJPeakingEQ.Audio(input: sig, freq: 1000.0, gain: 6.0, q: 1.0) // +6 dB at 1 kHz
_ = RBJLowShelf.Audio(input: sig, freq: 200.0, gain: 6.0, slope: 1.0)
_ = RBJHighShelf.Audio(input: sig, freq: 8000.0, gain: 3.0, slope: 1.0)
```
---
@@ -80,10 +85,11 @@ Cascaded biquad + first-order sections (bilinear transform, Butterworth Q formul
| ``ButterworthBandReject`` | N-th order band-reject (parallel LP + HP) |
```swift
ButterworthLowPass.Audio(input: sig, freq: 800.0, order: 4)
ButterworthHighPass.Audio(input: sig, freq: 400.0, order: 2)
ButterworthBandPass.Audio(input: sig, lowFreq: 400.0, highFreq: 1200.0, order: 4)
ButterworthBandReject.Audio(input: sig, lowFreq: 400.0, highFreq: 1200.0, order: 4)
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
_ = ButterworthLowPass.Audio(input: sig, freq: 800.0, order: 4)
_ = ButterworthHighPass.Audio(input: sig, freq: 400.0, order: 2)
_ = ButterworthBandPass.Audio(input: sig, lowFreq: 400.0, highFreq: 1200.0, order: 4)
_ = ButterworthBandReject.Audio(input: sig, lowFreq: 400.0, highFreq: 1200.0, order: 4)
```
---
@@ -99,24 +105,26 @@ ButterworthBandReject.Audio(input: sig, lowFreq: 400.0, highFreq: 1200.0, order:
| ``ResonatorBank`` | Klank-style parallel bank of N two-pole resonators driven from a `[freq, decay, amp]` ``LyrebirdBuffer``; vDSP-accelerated per-sample inner loop. Modal synthesis (marimba, vibraphone, bell, bowl). |
```swift
ResonatingFilter(input: sig, freq: 440.0, decayTime: 1.0)
RingingFilter(input: sig, freq: 440.0, bandwidth: 20.0)
CombFilter(input: sig, delay: 0.01, decayTime: 0.5)
AllpassFilter(input: sig, delay: 0.005, decayTime: 0.3)
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
_ = ResonatingFilter(input: sig, freq: 440.0, decayTime: 1.0)
_ = RingingFilter(input: sig, freq: 440.0, bandwidth: 20.0)
// maxDelay bounds the pre-allocated delay line; delay must stay <= maxDelay.
_ = CombFilter(input: sig, maxDelay: 0.05, delay: 0.01, decayTime: 0.5)
_ = AllpassFilter(input: sig, maxDelay: 0.05, delay: 0.005, decayTime: 0.3)
// Three-mode marimba-like bank: frame k = [freq, decay, amp]
let modes = LyrebirdBuffer(count: 3, channelCount: resonatorBankChannelCount)
let modes: LyrebirdBuffer = LyrebirdBuffer(count: 3, channelCount: resonatorBankChannelCount)
let triplets: [(Double, Double, Double)] = [
(300.0, 0.40, 1.00),
(1200.0, 0.25, 0.40),
(2700.0, 0.18, 0.20),
]
for (i, t) in triplets.enumerated() {
for (i, t): (Int, (Double, Double, Double)) in triplets.enumerated() {
modes.setValue(t.0, frame: i, channel: resonatorBankFreqChannel)
modes.setValue(t.1, frame: i, channel: resonatorBankDecayChannel)
modes.setValue(t.2, frame: i, channel: resonatorBankAmpChannel)
}
ResonatorBank.Audio(input: Impulse.Audio(freq: 0.5), buffer: modes)
_ = ResonatorBank.Audio(input: Impulse.Audio(freq: 0.5), buffer: modes)
```
---
@@ -128,8 +136,11 @@ ResonatorBank.Audio(input: Impulse.Audio(freq: 0.5), buffer: modes)
| ``MoogLadder`` | Huovilainen-style 4-pole resonant lowpass with per-stage `tanh` saturation, internal 2× oversampling, and SC-style half-sample feedback compensation. Self-oscillates near `resonance = 1.0`. |
```swift
MoogLadder.Audio(input: noise, freq: 1200.0, resonance: 0.7) // classic resonant LP
MoogLadder.Audio(input: noise, freq: lfo, resonance: 1.1) // ringing self-osc with cutoff sweep
let noise: WhiteNoise.Audio = WhiteNoise.Audio()
let lfo: OscSin.Control = OscSin.Control(freq: 0.5, mul: 400.0, add: 800.0)
_ = MoogLadder.Audio(input: noise, freq: 1200.0, resonance: 0.7) // classic resonant LP
_ = MoogLadder.Audio(input: noise, freq: lfo, resonance: 1.1) // ringing self-osc with cutoff sweep
```
---
@@ -150,14 +161,18 @@ control signals, building envelopes from impulses, and removing DC bias.
| ``LeakDC`` | One-pole DC blocker: `y[n] = x[n] − x[n−1] + coef · y[n−1]` |
```swift
Lag.Audio(input: env, time: 0.05) // 50 ms lag
LagUpDown.Audio(input: env, lagUp: 0.1, lagDown: 0.01) // slow attack, fast release
Lag2.Audio(input: sig, time: 0.05) // extra-smooth 50 ms
Lag2UpDown.Audio(input: env, lagUp: 0.1, lagDown: 0.01)
Decay.Audio(input: impulse, decayTime: 0.5) // 500 ms impulse tail
Decay2.Audio(input: impulse, attackTime: 0.01, decayTime: 0.5) // rounded attack
LeakDC.Audio(input: sig) // default coef 0.995
LeakDC.Control(input: sig) // default coef 0.9
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let env: OscSin.Audio = OscSin.Audio(freq: 1.0)
let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0)
_ = Lag.Audio(input: env, time: 0.05) // 50 ms lag
_ = LagUpDown.Audio(input: env, lagUp: 0.1, lagDown: 0.01) // slow attack, fast release
_ = Lag2.Audio(input: sig, time: 0.05) // extra-smooth 50 ms
_ = Lag2UpDown.Audio(input: env, lagUp: 0.1, lagDown: 0.01)
_ = Decay.Audio(input: impulse, decayTime: 0.5) // 500 ms impulse tail
_ = Decay2.Audio(input: impulse, attackTime: 0.01, decayTime: 0.5) // rounded attack
_ = LeakDC.Audio(input: sig) // default coef 0.995
_ = LeakDC.Control(input: sig) // default coef 0.9
```
### Slew Limiting
@@ -169,9 +184,13 @@ de-zippering, and taming abrupt control jumps. The state initialises to the firs
sample (no startup transient).
```swift
Slew.Audio(input: sig, up: 100.0, dn: 100.0) // ≤ 100 units/sec slope in either direction
Slew.Audio(input: pitch, up: 50.0, dn: 200.0) // slow glide up, fast fall
Slew.Control(input: cv, up: 10.0, dn: 10.0) // block-rate slew
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let pitch: OscSin.Control = OscSin.Control(freq: 1.0, mul: 100.0, add: 440.0)
let cv: OscSin.Control = OscSin.Control(freq: 1.0)
_ = Slew.Audio(input: sig, up: 100.0, dn: 100.0) // ≤ 100 units/sec slope in either direction
_ = Slew.Audio(input: pitch, up: 50.0, dn: 200.0) // slow glide up, fast fall
_ = Slew.Control(input: cv, up: 10.0, dn: 10.0) // block-rate slew
```
- `up` / `dn` — maximum rising / falling slope in units per second. Default `1.0` each.
@@ -8,33 +8,30 @@ The base unit of signal production in Lyrebird.
## Protocol Hierarchy
```swift
protocol Generator: AnyObject, ValidGeneratorInput {
var rate: ProcessingRate { get }
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]]
func floatValue(graph: SynthGraph) -> Double
var _segmentSerial: UInt64 { get set }
var _cachedResult: [[Double]] { get set }
}
``Generator`` refines `AnyObject` and ``ValidGeneratorInput``:
protocol AudioGenerator: Generator {} // rate == .audio (provided by extension)
protocol ControlGenerator: Generator {} // rate == .control (provided by extension)
| Requirement | Role |
|---|---|
| ``Generator/rate`` | ``ProcessingRate`` — supplied by the ``AudioGenerator`` / ``ControlGenerator`` extensions. |
| ``Generator/outputChannelCount`` | Channel count of `_result`. Defaults to `1`; **multi-row generators must override it** or they silently mono-ize under `+ - * /`. See <doc:MultiChannel>. |
| `_computeSamples(graph:count:)` | Produce `count` samples. The one method every generator implements. |
| ``Generator/floatValue(graph:)`` | Scalar value. Provided by the ``AudioGenerator`` extension; ``ControlGenerator`` conformers supply their own. |
| `_segmentSerial` / `_cachedResult` | Fan-out cache. Inherited from ``GeneratorBase`` — never redeclare. |
enum ProcessingRate {
case audio // one output sample per engine sample tick (e.g. 44100 Hz)
case control // one output value per block, interpolated to audio rate downstream
case spectral // reserved
case demand // reserved
}
Two refinements select the rate:
/// Marks a caseless namespace enum whose nested Audio and Control classes form a matched
/// generator pair. Conforming types declare AudioType and ControlType so DocC, generic
/// code, and tooling can discover the pair at compile time.
protocol GeneratorEnum {
associatedtype AudioType: AudioGenerator
associatedtype ControlType: ControlGenerator
}
```
| Protocol | Adds |
|---|---|
| ``AudioGenerator`` | Nothing — `rate == .audio` and `floatValue` come from its extension. |
| ``ControlGenerator`` | ``ControlGenerator/previousOutputValue`` and `_subBlockBuffer`, backing the block-rate ramp and the sub-block loop. |
``ProcessingRate`` has four cases: ``ProcessingRate/audio`` (one sample per engine tick),
``ProcessingRate/control`` (one value per block, interpolated downstream), and
``ProcessingRate/spectral`` / ``ProcessingRate/demand`` (reserved).
``GeneratorEnum`` marks a caseless namespace enum whose nested `Audio` and `Control` classes form a
matched pair, declaring ``GeneratorEnum/AudioType`` and ``GeneratorEnum/ControlType`` so DocC,
generic code, and tooling can discover the pair at compile time.
All built-in paired generators (`OscSin`, `OscTable`, `Impulse`, `WhiteNoise`, `LFStepNoise`,
`LFLineNoise`, `EnvelopeGen`, `PlayBuffer`, `RecordBuffer`, `In`, `Out`, `SendTrigger`, `Demand`)
@@ -75,15 +72,24 @@ typealias ClosureBody = (SynthGraph, Int) -> Double // RT-safe closure signatur
## ValidGeneratorInput Protocol
Enables seamless mixing of constants, generators, parameter keys, and closures as generator inputs.
Enables seamless mixing of constants, generators, and closures as generator inputs.
```swift
OscSin.Audio(freq: 440.0) // Float literal
OscSin.Audio(freq: someGenerator) // another Generator
OscSin.Audio(freq: "FreqParam") // string key — resolved from ParameterTable at RT
OscSin.Audio(freq: Closure { g, i in ... }) // closure (allocates — offline only)
let someGenerator: OscSin.Control = OscSin.Control(freq: 2.0, mul: 10.0, add: 440.0)
let a: OscSin.Audio = OscSin.Audio(freq: 440.0) // Double literal
let b: OscSin.Audio = OscSin.Audio(freq: 60) // Int literal
let c: OscSin.Audio = OscSin.Audio(freq: someGenerator) // another Generator
// Closure — allocates per block, so offline / non-RT use only.
let d: OscSin.Audio = OscSin.Audio(freq: Closure { graph, i in
440.0 + Double(i)
})
```
To drive an input from a live parameter, wire the projected value of a `@LiveParam`
(`$freq`, a ``ParameterNode``) straight into the generator — see <doc:ParameterInputs>.
```swift
protocol ValidGeneratorInput {
func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]]
@@ -92,7 +98,7 @@ protocol ValidGeneratorInput {
func needsInterpolation() -> Bool
func sampleBlock(graph: SynthGraph, count: Int, previousValue: Double) -> [Double]
}
// Conforming types: Double, Int, String, any Generator, Closure
// Conforming types: Double, Int, any Generator, Closure, GeneratorInputProvider
// Contract: calculatedSamples must always return a non-empty outer array.
```
@@ -101,8 +107,11 @@ protocol ValidGeneratorInput {
Math operators on ``Generator`` inputs create ``BinaryOpGenerator`` instances:
```swift
let sig = OscSin.Audio(freq: 440) * 0.5 // BinaryOpGenerator (*)
let mix = sig1 + sig2 // BinaryOpGenerator (+)
let sig1: OscSin.Audio = OscSin.Audio(freq: 440)
let sig2: OscSin.Audio = OscSin.Audio(freq: 660)
let scaled: any Generator = sig1 * 0.5 // BinaryOpGenerator (*)
let mix: any Generator = sig1 + sig2 // BinaryOpGenerator (+)
```
Operators: `*`, `+`, `-`, `/`
@@ -120,10 +129,14 @@ precedence applies** — no special rules to learn:
`*` 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 override as expected
let osc: OscSin.Audio = OscSin.Audio(freq: 440)
let env: OscSin.Audio = OscSin.Audio(freq: 1.0)
let lfo: OscSin.Audio = OscSin.Audio(freq: 2.0)
let a: any Generator = osc * 0.5 + env // → (osc * 0.5) + env
let b: any Generator = osc + env * 0.5 // → osc + (env * 0.5)
let c: any Generator = osc - env - lfo // → (osc - env) - lfo (left-associative)
let d: any Generator = (osc + env) * 0.5 // parentheses override as expected
```
> Note: `Double op Double` always resolves to the Swift stdlib, not a ``BinaryOpGenerator``.
@@ -169,21 +182,22 @@ automatically. See <doc:WritingGenerators> for the full pattern.
## Pre-Allocated Output Buffer Pattern
Every generator pre-allocates `_result` to `lyrebirdDefaultResultBufferSize` (512) samples in
`init`, and opens `_computeSamples` with a `precondition` that fires in both debug and release
if the engine is misconfigured:
`init`, and opens `_computeSamples` with `_checkCount(count)` — a ``GeneratorBase`` helper that
traps in both debug and release if the engine is misconfigured:
```swift
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
precondition(count <= _result[0].count,
"count \(count) exceeds pre-allocated buffer. "
+ "Ensure blockSize ≤ lyrebirdDefaultResultBufferSize.")
_checkCount(count)
// … fill _result[0][0..<count] …
return _result
}
```
Use `_checkCount(count)` rather than writing the `precondition` out by hand — it is the
canonical form, and inlining the long version in a new generator is a review violation.
`SynthesisEngine.init` enforces `blockSize ≤ lyrebirdDefaultResultBufferSize`, so the
precondition is never triggered in normal use.
check is never triggered in normal use.
## count: Int Parameter
@@ -77,17 +77,17 @@ position.
### Quick start
```swift
let buf = try LyrebirdBuffer(path: someAudioFileURL)
let buf = try LyrebirdBuffer.load(url: someAudioFileURL)
let g = BufferGrain(
buffer: buf,
position: 0.5, // normalized buffer position [0, 1]
positionSpread: 0.05, // ±5% random offset per grain
duration: 0.1, // grain length in seconds
amp: 0.4,
pan: 0.0, // centre, ±0 spread
pitchRatio: 1.0, // playback rate (×)
pitchDispersion: 0.05, // ±5% random pitch per grain
density: 30.0, // grains/sec
pan: 0.0, // centre, ±0 spread
amp: 0.4
density: 30.0 // grains/sec
)
output(bus: 0, source: g) // 2-channel; Out fans to bus 0 + bus 1
```
@@ -208,13 +208,13 @@ Hop-driven grain reader over a static buffer with a generator-driven read positi
without affecting pitch.
```swift
let buf = try LyrebirdBuffer(path: someAudioFileURL)
let buf = try LyrebirdBuffer.load(url: someAudioFileURL)
// Half-speed playback (no pitch change) — stream pos at 0.5× normal rate
let posLfo = LinLin.Audio(
input: OscSin.Control(freq: 0.5),
inLow: -1.0, inHigh: 1.0,
outLow: 0.0, outHigh: 1.0
OscSin.Control(freq: 0.5),
inLo: -1.0, inHi: 1.0,
outLo: 0.0, outHi: 1.0
)
let ts = TimeStretch.Audio(
buffer: buf,
@@ -11,8 +11,8 @@ Math utility generators and arithmetic operator overloads shipped with the `Lyre
## Math Generators
```swift
LinLin.Audio(input: lfo, inLow: -1.0, inHigh: 1.0, outLow: 200.0, outHigh: 800.0) // maps [-1,1] → [200,800]
LinLin.Audio(input: env, inLow: 0.0, inHigh: 1.0, outLow: 200.0, outHigh: 800.0) // maps [ 0,1] → [200,800]
LinLin.Audio(lfo, inLo: -1.0, inHi: 1.0, outLo: 200.0, outHi: 800.0) // maps [-1,1] → [200,800]
LinLin.Audio(env, inLo: 0.0, inHi: 1.0, outLo: 200.0, outHi: 800.0) // maps [ 0,1] → [200,800]
Pow.Audio(osc, exp: 2.0) // input ^ 2
(-1.0 as Double) * osc // −input (phase inversion)
Cos.Audio(phasor) // cosine waveshaper, input in radians
@@ -37,6 +37,11 @@ rule are decided at graph-construction time from each operand's `outputChannelCo
| `N × M`, both > 1, N ≠ M | — | `precondition` traps at `init` — no implicit wrap-extend, no truncation. |
```swift
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
let dry: OscSin.Audio = OscSin.Audio(freq: 220.0)
let dry2ch: Pan2 = Pan2(input: OscSin.Audio(freq: 220.0), pan: -0.5)
let wet2ch: Pan2 = Pan2(input: OscSin.Audio(freq: 440.0), pan: 0.5)
// Stereo × scalar — both channels scale.
let pan = Pan2(input: osc, pan: -0.3)
output(bus: 0, source: pan * 0.5)
@@ -80,10 +85,14 @@ output(bus: 0, source: oscs) // bus 0 = 440 Hz, bus 1 = 880 Hz
All four arithmetic operators work element-wise and return a new ``GeneratorArray``:
```swift
let oscs: GeneratorArray = expand([440.0, 880.0]) { OscSin.Audio(freq: $0) }
let otherOscs: GeneratorArray = expand([550.0, 660.0]) { OscSin.Audio(freq: $0) }
let quiet = oscs * 0.5 // each channel × 0.5
let louder = 2.0 * oscs // scalar op GeneratorArray
let sum = oscs + otherOscs // element-wise (counts must match)
let diff = oscs - 0.1 // subtract scalar from each channel
_ = (quiet, louder, sum, diff)
```
Mismatched-count `GeneratorArray op GeneratorArray` is caught by a `precondition` at build time.
@@ -101,6 +110,7 @@ Mismatched-count `GeneratorArray op GeneratorArray` is caught by a `precondition
| N | `bus` … `bus + N - 1` |
```swift
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
output(bus: 0, source: Pan2(input: osc, pan: 0.0)) // writes buses 0 and 1
output(bus: 0, source: expand([440.0, 880.0]) { OscSin.Audio(freq: $0) }) // same
```
@@ -135,8 +145,9 @@ Read N consecutive buses with `input(bus:channels:)` inside ``SynthesizerBase/bu
// Read stereo from buses 2–3, apply gain, write to output buses 0–1
output(bus: 0, source: input(bus: 2, channels: 2) * 0.5)
// Read hardware input (assuming numOutputChannels = 2)
output(bus: 0, source: input(bus: engine.numOutputChannels, channels: 2))
// Read hardware input (the first input bus sits just above the output buses;
// here numOutputChannels = 2, so input buses start at 2)
output(bus: 0, source: input(bus: 2, channels: 2))
```
`In.multi(bus:channels:)` is the underlying static helper if you need it outside
@@ -65,16 +65,18 @@ Two scales:
| Power / energy | `powToDb` / `dbToPow` | 10 × log₁₀ | FFT magnitudes, RMS |
```swift
ampToDb(1.0) // 0.0 dB — full scale
ampToDb(0.5) // −6.02 dB
dbToAmp(0.0) // 1.0
dbToAmp(-6.0) // ~0.501
_ = ampToDb(1.0) // 0.0 dB — full scale
_ = ampToDb(0.5) // −6.02 dB
_ = dbToAmp(0.0) // 1.0
_ = dbToAmp(-6.0) // ~0.501
// Set a @LiveParam in dB
synth.$gain.value = dbToAmp(-12.0)
// Convert a dB gain to a linear amplitude (e.g. to set a @LiveParam gain)
let gain: Double = dbToAmp(-12.0)
// Convert FFT bin magnitude
let dB = powToDb(magnitude)
// Convert an FFT bin magnitude
let magnitude: Double = 0.5
let dB: Double = powToDb(magnitude)
_ = (gain, dB)
```
`ampToDb` and `powToDb` return `-.infinity` for zero input and `NaN` for negative input.
@@ -105,17 +107,18 @@ driving a pitch-shift or playback-rate generator from semitone
intervals:
```swift
midiToRatio(12) // 2.0 — one octave up
midiToRatio(-12) // 0.5 — one octave down
ratioToMidi(2.0) // 12.0
_ = midiToRatio(12) // 2.0 — one octave up
_ = midiToRatio(-12) // 0.5 — one octave down
_ = ratioToMidi(2.0) // 12.0
// Dot syntax (SC-style `.midiratio` / `.ratiomidi`):
12.midiToRatio // 2.0
(-12).midiToRatio // 0.5
2.0.ratioToMidi // 12.0
_ = 12.midiToRatio // 2.0
_ = (-12).midiToRatio // 0.5
_ = 2.0.ratioToMidi // 12.0
// In context — PitchShift driven from semitone intervals:
PitchShift.Audio(input: src, pitchRatio: 7.midiToRatio) // perfect fifth up
let src: OscSin.Audio = OscSin.Audio(freq: 440.0)
_ = PitchShift.Audio(input: src, pitchRatio: 7.midiToRatio) // perfect fifth up
```
---
@@ -175,7 +178,9 @@ Maps a normalized value in [0, 1] onto an exponential range. Useful for filter s
```swift
// Frequency sweep from 200 Hz to 2000 Hz driven by a [0, 1] knob
let knobValue: Double = 0.5
let freq = linToExp(knobValue, low: 200.0, high: 2000.0)
_ = freq
```
### equalPowerFade
@@ -183,8 +188,12 @@ let freq = linToExp(knobValue, low: 200.0, high: 2000.0)
Returns `(gainA, gainB)` for a constant-power crossfade at `position` in [0, 1]. Both channels are −3 dB at the midpoint; combined power stays constant.
```swift
let mixPosition: Double = 0.5
let dry: OscSin.Audio = OscSin.Audio(freq: 220.0)
let wet: OscSin.Audio = OscSin.Audio(freq: 440.0)
let (dryGain, wetGain) = equalPowerFade(mixPosition)
Out.Audio(bus: 0, source: dry * dryGain + wet * wetGain)
_ = Out.Audio(bus: 0, source: dry * dryGain + wet * wetGain)
```
---
@@ -215,8 +215,9 @@ Gamma distribution parameterised by `mode`. Shape is derived from the mode so th
PDF falls at `mode`. Uses the Marsaglia-Tsang acceptance-rejection algorithm — expected ≈1.7 iterations.
```swift
GammaNoise.Audio(mode: 0.5)
GammaNoise.Control(mode: modulatorGen)
let modulatorGen: OscSin.Control = OscSin.Control(freq: 0.5, mul: 0.3, add: 0.5)
_ = GammaNoise.Audio(mode: 0.5)
_ = GammaNoise.Control(mode: modulatorGen)
```
### LaplaceNoise
@@ -262,8 +263,9 @@ Poisson distribution with mean `mean`. Outputs non-negative integer values as `D
`PoissonNoise.Control` is the most common usage — one Poisson draw per audio block.
```swift
PoissonNoise.Control(mean: 4.0) // integer values ≈ 0–10
PoissonNoise.Control(mean: modulatorGen) // audio-rate mean modulation
let modulatorGen: OscSin.Control = OscSin.Control(freq: 0.5, mul: 2.0, add: 4.0)
_ = PoissonNoise.Control(mean: 4.0) // integer values ≈ 0–10
_ = PoissonNoise.Control(mean: modulatorGen) // audio-rate mean modulation
```
### ArcsinNoise
@@ -282,7 +284,7 @@ Beta distribution mapped to `[lo, hi]` with shape parameters `lowProb` and `high
both equal 2 = triangular.
```swift
BetaRandNoise.Audio(lo: 0.0, hi: 1.0, lowProb: 2.0, highProb: 5.0)
_ = BetaRandNoise.Audio(lo: 0.0, hi: 1.0, lowProb: 2.0, highProb: 5.0)
```
### CauchyNoise
@@ -301,7 +303,8 @@ Gaussian (normal) distribution with standard deviation `dev` and `mean`.
Uses the Box-Muller transform — two uniform samples per output value.
```swift
GaussNoise.Audio(dev: 0.1, mean: 0.0) // zero-mean Gaussian noise
GaussNoise.Control(dev: 30.0, mean: 440.0) // random pitch per block ≈ 440±30 Hz
GaussNoise.Control(dev: lfoGen, mean: 440.0) // audio-rate stddev modulation
let lfoGen: OscSin.Control = OscSin.Control(freq: 0.5, mul: 10.0, add: 30.0)
_ = GaussNoise.Audio(dev: 0.1, mean: 0.0) // zero-mean Gaussian noise
_ = GaussNoise.Control(dev: 30.0, mean: 440.0) // random pitch per block ≈ 440±30 Hz
_ = GaussNoise.Control(dev: lfoGen, mean: 440.0) // audio-rate stddev modulation
```
@@ -22,10 +22,12 @@ steady state.
Table-lookup sine oscillator with a 32 768-sample single-cycle table and selectable interpolation.
```swift
OscSin.Audio(freq: 440.0) // constant freq, linear interp
OscSin.Audio(freq: lfo, phase: 0.25) // generator input, quarter-phase offset
OscSin.Audio(freq: 440.0, interpolation: .cubic) // Catmull-Rom cubic
OscSin.Audio(freq: 440.0, table: engine.sharedTables.sineTable) // share engine's pre-computed table
let lfo: OscSin.Control = OscSin.Control(freq: 5.0, mul: 10.0, add: 440.0)
_ = OscSin.Audio(freq: 440.0) // constant freq, linear interp
_ = OscSin.Audio(freq: lfo, phase: 0.25) // generator input, quarter-phase offset
_ = OscSin.Audio(freq: 440.0, interpolation: .cubic) // Catmull-Rom cubic
_ = OscSin.Audio(freq: 440.0, table: engine.sharedTables.sineTable) // share engine's pre-computed table
```
- `freq` — any ``ValidGeneratorInput``. Scalar inputs call `floatValue` once per block. Generator inputs are read at audio rate, enabling true FM synthesis.
@@ -97,9 +99,10 @@ enum namespace. All support `mul`/`add` and a `phase` offset.
Linear ascending ramp reset to −1 at each period. PolyBLEP step correction at the reset point.
```swift
OscSawtooth.Audio(freq: 440.0)
OscSawtooth.Audio(freq: lfo * 200 + 440, phase: 0.5) // phase offset, audio-rate FM
OscSawtooth.Control(freq: 2.0) // LFO use at control rate
let lfo: OscSin.Audio = OscSin.Audio(freq: 5.0)
_ = OscSawtooth.Audio(freq: 440.0)
_ = OscSawtooth.Audio(freq: lfo * 200 + 440, phase: 0.5) // phase offset, audio-rate FM
_ = OscSawtooth.Control(freq: 2.0) // LFO use at control rate
```
- `freq` — any ``ValidGeneratorInput``. Generator inputs enable audio-rate FM.
@@ -134,10 +137,11 @@ Variable duty-cycle pulse wave. PolyBLEP correction applied at both the rising e
when `dutyCycle` is a `Generator`.
```swift
OscDutyCycle.Audio(freq: 440.0) // 0.5 = square
OscDutyCycle.Audio(freq: 440.0, dutyCycle: 0.25) // 25% duty cycle
OscDutyCycle.Audio(freq: 440.0, dutyCycle: lfo * 0.4 + 0.5) // audio-rate PWM
OscDutyCycle.Control(freq: 1.0, dutyCycle: 0.3)
let lfo: OscSin.Audio = OscSin.Audio(freq: 5.0)
_ = OscDutyCycle.Audio(freq: 440.0) // 0.5 = square
_ = OscDutyCycle.Audio(freq: 440.0, dutyCycle: 0.25) // 25% duty cycle
_ = OscDutyCycle.Audio(freq: 440.0, dutyCycle: lfo * 0.4 + 0.5) // audio-rate PWM
_ = OscDutyCycle.Control(freq: 1.0, dutyCycle: 0.3)
```
- `dutyCycle` — normalized `[0, 1]`. Clamped internally. `0.5` = square wave. Defaults to `0.5`.
@@ -163,9 +167,10 @@ enum namespace.
Linear ascending ramp. Formula: `2 × phase − 1`. Range `[−1, 1]`.
```swift
LFSawtooth.Audio(freq: 0.5) // slow ascending ramp, 0.5 Hz
LFSawtooth.Audio(freq: lfo, phase: 0.5) // phase offset
LFSawtooth.Control(freq: 2.0) // one new ramp value per audio block
let lfo: OscSin.Audio = OscSin.Audio(freq: 0.5)
_ = LFSawtooth.Audio(freq: 0.5) // slow ascending ramp, 0.5 Hz
_ = LFSawtooth.Audio(freq: lfo, phase: 0.5) // phase offset
_ = LFSawtooth.Control(freq: 2.0) // one new ramp value per audio block
```
### LFSquare
@@ -194,9 +199,10 @@ Variable duty-cycle pulse with no BLEP correction. Same formula as ``OscDutyCycl
unfiltered. Supports audio-rate PWM via a Generator `dutyCycle` input.
```swift
LFDutyCycle.Audio(freq: 1.0, dutyCycle: 0.3) // 30% duty, 1 Hz
LFDutyCycle.Audio(freq: 2.0, dutyCycle: envGen) // envelope-driven PWM
LFDutyCycle.Control(freq: 0.5, dutyCycle: 0.75)
let envGen: OscSin.Audio = OscSin.Audio(freq: 0.5, mul: 0.3, add: 0.5)
_ = LFDutyCycle.Audio(freq: 1.0, dutyCycle: 0.3) // 30% duty, 1 Hz
_ = LFDutyCycle.Audio(freq: 2.0, dutyCycle: envGen) // envelope-driven PWM
_ = LFDutyCycle.Control(freq: 0.5, dutyCycle: 0.75)
```
- `dutyCycle` — normalized `[0, 1]`. Clamped internally. Defaults to `0.5`.
@@ -56,6 +56,9 @@ behave the same as in `TuneablePitchShift.Audio`.
### Quick start
```swift
let hardwareInputBus: Int = 4
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let mic = In.Audio(bus: hardwareInputBus)
let shifted = PitchShift.Audio(input: mic, pitchRatio: 0.75, windowSize: 0.05)
output(bus: 0, source: shifted)
@@ -63,6 +66,7 @@ output(bus: 0, source: shifted)
// Modulated ratio from another generator
let lfo = OscSin.Control(freq: 0.5) * 0.1 + 1.0 // ±10% vibrato
let shifted2 = PitchShift.Audio(input: sig, pitchRatio: lfo)
output(bus: 1, source: shifted2)
```
### Parameters
@@ -136,6 +140,10 @@ hop timing is fixed by `windowSize / overlap`, new grains trigger at the origina
### Quick start
```swift
let leftSig: OscSin.Audio = OscSin.Audio(freq: 220.0)
let rightSig: OscSin.Audio = OscSin.Audio(freq: 221.0)
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
// Mono pitch shift, one octave up
let shifted = TuneablePitchShift.Audio(input: OscSin.Audio(freq: 220.0), pitchRatio: 2.0)
output(bus: 0, source: shifted)
@@ -155,6 +163,7 @@ let shimmer = TuneablePitchShift.Audio(
pitchDispersion: 0.05, // ±5% random per grain
timeDispersion: 0.005 // ±5 ms jitter
)
output(bus: 0, source: shimmer)
```
### Parameters
@@ -332,11 +341,13 @@ inharmonicity is the defining sonic character of the effect, and is intentional.
### Quick start
```swift
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
// Shift all frequencies up by 50 Hz
let shifter = FrequencyShifter.Audio(
input: OscSin.Audio(freq: 440.0),
shiftHz: 50.0,
sampleRate: graph.engine.sampleRate
sampleRate: 44100.0
)
output(bus: 0, source: shifter.upper) // 490 Hz
output(bus: 1, source: shifter.lower) // 390 Hz
@@ -344,10 +355,12 @@ output(bus: 1, source: shifter.lower) // 390 Hz
// Audio-rate shiftHz modulation (Bode-style vibrato)
let lfo = OscSin.Audio(freq: 2.0) * 20.0 // ±20 Hz
let bode = FrequencyShifter.Audio(input: sig, shiftHz: lfo)
output(bus: 0, source: bode.upper)
// Thickening: mix shifted and dry signals
let shifted = FrequencyShifter.Audio(input: sig, shiftHz: 15.0)
let thickened = sig + shifted.upper * 0.5
output(bus: 1, source: thickened)
```
### Parameters
@@ -101,6 +101,9 @@ edge, then holds that value until the next trigger. The held value is delivered
control-rate ramp to downstream audio-rate generators.
```swift
let signal: WhiteNoise.Audio = WhiteNoise.Audio()
let trig: Impulse.Control = Impulse.Control(freq: 1.0)
// Change filter cutoff on each kick drum trigger
let kick = Impulse.Control(freq: 2.0)
let cutoff = TriggeredRandom.Control(trigger: kick, lo: 200.0, hi: 4000.0)
@@ -108,6 +111,7 @@ let filt = RBJLowPass.Audio(input: signal, freq: cutoff, q: 0.707)
// Deterministic output for testing — supply a fixed seed
let det = TriggeredRandom.Control(trigger: trig, lo: 0.0, hi: 1.0, seed: 42)
_ = (filt, det)
```
**Parameters:**
@@ -188,8 +188,8 @@ let verb = SpringReverb.Audio(
let stereoVerb = SpringReverb.Audio(
input: sig,
decay: 2.5,
stereo: true,
sampleRate: 44100
sampleRate: 44100,
stereo: true
)
output(bus: 0, source: stereoVerb[0])
output(bus: 1, source: stereoVerb[1])
@@ -22,8 +22,16 @@ which is currently selected — matching SuperCollider's `Select`. `which` may b
for per-sample source switching.
```swift
Select.Audio(which: index, inputs: [oscA, oscB, noise]) // pick one of three sources
Select.Control(which: 1.0, inputs: [a, b, c]) // block-rate selection
let index: OscSin.Control = OscSin.Control(freq: 1.0)
let oscA: OscSin.Audio = OscSin.Audio(freq: 220.0)
let oscB: OscSin.Audio = OscSin.Audio(freq: 440.0)
let noise: WhiteNoise.Audio = WhiteNoise.Audio()
let a: OscSin.Control = OscSin.Control(freq: 1.0)
let b: OscSin.Control = OscSin.Control(freq: 2.0)
let c: OscSin.Control = OscSin.Control(freq: 3.0)
_ = Select.Audio(which: index, inputs: [oscA, oscB, noise]) // pick one of three sources
_ = Select.Control(which: 1.0, inputs: [a, b, c]) // block-rate selection
```
- `which` — any ``ValidGeneratorInput``; truncated + clamped to a valid index.
@@ -37,8 +45,14 @@ Select.Control(which: 1.0, inputs: [a, b, c]) // block-rate selectio
overall output gain (SuperCollider's `level`).
```swift
CrossFade.Audio(inA: dry, inB: wet, pan: mix) // equal-power morph
LinearCrossFade.Audio(inA: a, inB: b, pan: 0.0) // linear 50/50
let dry: OscSin.Audio = OscSin.Audio(freq: 220.0)
let wet: OscSin.Audio = OscSin.Audio(freq: 440.0)
let mix: OscSin.Control = OscSin.Control(freq: 0.2)
let a: OscSin.Audio = OscSin.Audio(freq: 330.0)
let b: OscSin.Audio = OscSin.Audio(freq: 550.0)
_ = CrossFade.Audio(inA: dry, inB: wet, pan: mix) // equal-power morph
_ = LinearCrossFade.Audio(inA: a, inB: b, pan: 0.0) // linear 50/50
```
- `pan` — any ``ValidGeneratorInput`` in `[-1, 1]`. Defaults to `0.0`.
@@ -31,7 +31,7 @@ input → analyzer → threshold / latch → consumer
```swift
let mic = In.Audio(bus: 0)
let amp = AmplitudeFollower.Audio(input: mic, attackTime: 0.005, releaseTime: 0.05)
let amp = AmplitudeFollower.Audio(in: mic, attackTime: 0.005, releaseTime: 0.05)
let edge = SignalChanged.Audio(input: amp, threshold: 0.05)
addOutputGenerator(SendTrigger.Audio(trig: edge, id: 1))
@@ -55,7 +55,7 @@ output(bus: 0, source: osc)
```swift
let lfo = OscSin.Audio(freq: 0.5)
let gate = Impulse.Audio(freq: 1.0) > 0.0 // 1-sample-wide hi pulse per beat
let gate = Impulse.Audio(freq: 1.0) // 1-sample-wide hi pulse per beat (already a trigger)
let held = Gate.Audio(input: lfo, trig: gate)
```
@@ -50,6 +50,9 @@ closure returns (copied via the pre-allocated single-element pointers).
### Example — 6 dB magnitude attenuation
```swift
let sr: Double = 44100.0
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
let halver = SpectralPolarClosure(fftSize: 2048, hopSize: 512, sampleRate: sr) { ctx in
for i in 0..<ctx.binCount {
ctx.magnitudes[i] *= 0.5
@@ -64,6 +67,7 @@ output(bus: 0, source: chain)
### Example — spectral brightness tilt using frame index
```swift
let sr: Double = 44100.0
let tilt = SpectralPolarClosure(fftSize: 2048, hopSize: 512, sampleRate: sr) { ctx in
let factor = Float(ctx.frameIndex % 64) / 64.0 // slowly modulate
for i in 0..<ctx.binCount {
@@ -72,6 +76,7 @@ let tilt = SpectralPolarClosure(fftSize: 2048, hopSize: 512, sampleRate: sr) { c
ctx.magnitudes[i] *= binWeight
}
}
_ = tilt
```
---
@@ -78,14 +78,16 @@ low-frequency tones have centroid values close to their fundamental.
### Quick start
```swift
let sig: WhiteNoise.Audio = WhiteNoise.Audio()
let analysis = SpectralChain.Audio(input: sig, fftSize: 2048, hopSize: 512)
let centroid = SpectralCentroid.Control(analysis: analysis,
sampleRate: 44100.0)
// Route centroid to filter cutoff (clamp to sensible range with LinLin)
let cutoff = LinLin.Control(input: centroid, inLow: 0, inHigh: 8000,
outLow: 200, outHigh: 6000)
let cutoff = LinLin.Control(centroid, inLo: 0, inHi: 8000,
outLo: 200, outHi: 6000)
let filter = RBJLowPass.Audio(input: sig, freq: cutoff, q: 0.707)
_ = filter
```
### Parameters
@@ -122,6 +124,8 @@ No epsilon floor or zero-skipping is needed — IEEE 754 arithmetic handles it n
### Quick start
```swift
let sig: WhiteNoise.Audio = WhiteNoise.Audio()
let analysis = SpectralChain.Audio(input: sig, fftSize: 2048, hopSize: 512)
let flatness = SpectralFlatness.Control(analysis: analysis)
// Gate processing: apply heavy compression when signal is noisy (high flatness),
@@ -163,12 +167,15 @@ scan), so it does not need a separate ``SpectralCentroid/Control`` instance.
### Quick start
```swift
let sig: WhiteNoise.Audio = WhiteNoise.Audio()
let analysis = SpectralChain.Audio(input: sig, fftSize: 2048, hopSize: 512)
let spread = SpectralSpread.Control(analysis: analysis,
sampleRate: 44100.0)
// Use spread to modulate filter bandwidth: wider spectrum → wider band.
let q = LinLin.Control(input: spread, inLow: 0, inHigh: 4000, outLow: 8.0, outHigh: 0.5)
let q = LinLin.Control(spread, inLo: 0, inHi: 4000, outLo: 8.0, outHi: 0.5)
let bandpass = RBJBandPass.Audio(input: sig, freq: 1000.0, q: q)
_ = bandpass
```
### Parameters
@@ -248,6 +255,8 @@ frequency location, making it complementary to centroid and spread.
### Quick start
```swift
let sig: WhiteNoise.Audio = WhiteNoise.Audio()
let analysis = SpectralChain.Audio(input: sig, fftSize: 2048, hopSize: 512)
let entropy = SpectralEntropy.Control(analysis: analysis)
// Use entropy to crossfade between "noise" and "tone" processing paths.
@@ -285,6 +294,9 @@ are more sensitive to where energy first concentrates.
### Quick start
```swift
let sig: WhiteNoise.Audio = WhiteNoise.Audio()
let analysis = SpectralChain.Audio(input: sig, fftSize: 2048, hopSize: 512)
// Default — frequency below which 85% of energy falls
let rolloff = SpectralRolloff.Control(analysis: analysis,
sampleRate: 44100.0)
@@ -12,8 +12,8 @@ Each generator provides an `.Audio` (sample-accurate) and a `.Control` (block-ra
variant. The Control variants run the same state machine across the block but emit a flat
block-final value — trigger and counter outputs are discrete and are never smoothed/ramped.
For sending a trigger from the audio graph back to the language side, see ``SendTrigger``
(<doc:SendTrigger>). For latching and gating an arbitrary signal on a trigger, see
For sending a trigger from the audio graph back to the language side, see ``SendTrigger``.
For latching and gating an arbitrary signal on a trigger, see
``Gate`` / ``SampleAndHold`` in <doc:SignalAnalysis>.
---
@@ -25,8 +25,9 @@ For sending a trigger from the audio graph back to the language side, see ``Send
A new edge during the hold restarts the timer.
```swift
Trig.Audio(input: impulse, dur: 0.1) // hold the trigger level for 100 ms
Trig1.Audio(input: impulse, dur: 0.05) // 50 ms unity gate on each edge
let impulse: Impulse.Audio = Impulse.Audio(freq: 2.0)
_ = Trig.Audio(input: impulse, dur: 0.1) // hold the trigger level for 100 ms
_ = Trig1.Audio(input: impulse, dur: 0.05) // 50 ms unity gate on each edge
```
- `dur` — hold time in seconds (init-time scalar). Defaults to `0.1`.
@@ -37,8 +38,12 @@ Trig1.Audio(input: impulse, dur: 0.05) // 50 ms unity gate on each edge
``PulseCount`` accumulates a running count of rising edges with an optional reset.
```swift
TriggeredDelay.Audio(input: impulse, dur: 0.25) // echo the trigger 250 ms later
PulseCount.Audio(trig: clock, reset: bar) // count clocks, reset each bar
let impulse: Impulse.Audio = Impulse.Audio(freq: 2.0)
let clock: Impulse.Audio = Impulse.Audio(freq: 4.0)
let bar: Impulse.Audio = Impulse.Audio(freq: 1.0)
_ = TriggeredDelay.Audio(input: impulse, dur: 0.25) // echo the trigger 250 ms later
_ = PulseCount.Audio(trig: clock, reset: bar) // count clocks, reset each bar
```
- `dur` — delay in seconds (init-time scalar). Defaults to `0.1`.
@@ -50,7 +55,8 @@ PulseCount.Audio(trig: clock, reset: bar) // count clocks, reset each ba
`[min, max]`, with an optional reset to `resetval`. Ideal as a step-sequencer index.
```swift
Stepper.Audio(trig: clock, reset: 0.0, min: 0, max: 7, step: 1) // 0,1,…,7,0,…
let clock: Impulse.Audio = Impulse.Audio(freq: 4.0)
_ = Stepper.Audio(trig: clock, reset: 0.0, min: 0, max: 7, step: 1) // 0,1,…,7,0,…
```
- `min` / `max` / `step` / `resetval` — init-time `Int` scalars. `max >= min` required.
@@ -61,7 +67,8 @@ Stepper.Audio(trig: clock, reset: 0.0, min: 0, max: 7, step: 1) // 0,1,…,7,0
above `hi`, back to `0` when it falls below `lo`, and holds in between.
```swift
Schmidt.Audio(input: sig, lo: -0.2, hi: 0.2) // hysteresis band [-0.2, 0.2]
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
_ = Schmidt.Audio(input: sig, lo: -0.2, hi: 0.2) // hysteresis band [-0.2, 0.2]
```
- `lo` / `hi` — any ``ValidGeneratorInput``; switch-off and switch-on thresholds.
@@ -22,9 +22,11 @@ harmonic waveshaping or ``LyrebirdBuffer/fillWaveshaper(_:)`` for preset distort
The table is held via an RT-safe slot and can be swapped live with `setTable(_:engine:)`.
```swift
let curve = LyrebirdBuffer(count: 1024)
let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
let curve: LyrebirdBuffer = LyrebirdBuffer(count: 1024)
curve.fillChebyshev(coefficients: [0, 1, 0, 0.3]) // add a 3rd harmonic
let shaped = Waveshaper.Audio(table: curve, input: osc)
let shaped: Waveshaper.Audio = Waveshaper.Audio(table: curve, input: osc)
_ = shaped
```
- `table` — mono ``LyrebirdBuffer`` transfer curve (≥ 2 frames).
@@ -38,8 +40,9 @@ C1-continuous quadratic knee of width `amp · smooth`. Models transistor crossov
useful for grit and gating-style distortion.
```swift
CrossoverDistortion.Audio(input: sig, amp: 0.1, smooth: 0.0) // hard dead zone
CrossoverDistortion.Audio(input: sig, amp: 0.1, smooth: 0.5) // softened knee
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
_ = CrossoverDistortion.Audio(input: sig, amp: 0.1, smooth: 0.0) // hard dead zone
_ = CrossoverDistortion.Audio(input: sig, amp: 0.1, smooth: 0.5) // softened knee
```
- `amp` — dead-zone half-width (≥ 0, SuperCollider's crossover threshold). Defaults to `0.5`.
@@ -53,8 +56,9 @@ Produces glitch / dropout / bit-erosion textures. Audio-only — the stochastic
per sample and has no block-rate form.
```swift
Disintegrator.Audio(input: sig, probability: 0.3, multiplier: 0.0) // drop ~30% to silence
Disintegrator.Audio(input: sig, probability: 0.5, seed: 42) // deterministic
let sig: OscSin.Audio = OscSin.Audio(freq: 440.0)
_ = Disintegrator.Audio(input: sig, probability: 0.3, multiplier: 0.0) // drop ~30% to silence
_ = Disintegrator.Audio(input: sig, probability: 0.5, seed: 42) // deterministic
```
- `probability` — `[0, 1]` chance a sample is disintegrated. Defaults to `0.5`.
@@ -53,7 +53,25 @@ final class MySynth: SynthesizerBase {
override func build() {
let osc = OscSin.Audio(freq: 440.0) * 0.3
output(bus: 0, source: Pan2(input: osc, pan: 0))
doneAction = .freeEnclosing
}
}
```
This plays until you remove it. To have a synth free itself when its envelope
finishes, give the envelope a `doneAction` — see <doc:NodeTree>:
```swift
import LyrebirdSynth
final class MyPluckedNote: SynthesizerBase {
override func build() {
let env = EnvelopeGen.Audio(
envelope: Envelope(levels: [0, 1, 0], durations: [0.01, 0.6],
curves: [.sine, .exponential]),
doneAction: .freeNode // engine removes this synth when the envelope ends
)
let osc = OscSin.Audio(freq: 440.0) * env * 0.3
output(bus: 0, source: Pan2(input: osc, pan: 0))
}
}
```
@@ -61,6 +79,16 @@ final class MySynth: SynthesizerBase {
Then in the demo's `main.swift` (or app entry point):
```swift
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()
)
try engine.start()
try engine.add(MySynth())
```
@@ -101,14 +129,16 @@ Every scaffolded project ships an `<Name>.xcworkspace` that references the gener
**Available templates:**
Four lightweight Swift-Package-only templates (open with `Package.swift` in Xcode):
Six lightweight Swift-Package-only templates (open with `Package.swift` in Xcode):
| Template | Command | Starting point |
|---|---|---|
| `basic` (default) | `lyrebird new MyPiece` | Minimal engine + `RunLoop.main.run()` |
| `quickstart` | `lyrebird new MyFirstSound --template quickstart` | **Fastest sound** — a one-oscillator `SineTone` that plays 440 Hz for 10 s and exits |
| `basic` (default) | `lyrebird new MyPiece` | Minimal engine + `RunLoop.main.run()` (no synth wired yet) |
| `demo` | `lyrebird new MyPiece --template demo` | `SineTone` with `@LiveParam` freq and amp |
| `ui-demo` | `lyrebird new MyApp --template ui-demo` | AppKit window, `@UIParam` controls, `LyrebirdWindow` |
| `nrt` | `lyrebird new MyRender --template nrt` | `NRTDriver` renders to `output.caf` then exits |
| `score` | `lyrebird new MyScore --template score` | Builds a `Score` with the notation DSL, exports MusicXML, renders offline |
Three full `.xcodeproj`-bearing templates for `.app` / `.appex` deliverables that SwiftPM can't express:
@@ -271,6 +301,28 @@ Xcode compiles the `.docc` catalog and opens it in the Documentation window. Sym
---
## Threading — read this before you write a Routine or Task
Lyrebird runs your code on three kinds of thread, and the boundaries are not interchangeable:
- **Main thread** — where you construct synthesizers and call `engine.add` / `schedule`.
`SynthesizerBase` is `@MainActor`.
- **The RT audio thread** — runs the render callback. Never allocates, locks, or blocks.
You do not call into it; it calls your generators.
- **Routine / Task threads** — one background thread per `LyrebirdRoutine` / `LyrebirdTask`
body, for timed sequencing.
That last boundary is the one that surprises people: a task body is `@Sendable` and runs
off-main, so it **cannot construct a synthesizer directly**. Use `ctx.onMain { MySynth(...) }`
to build one inside the body, and `ctx.set` (with a `$param` node captured on main) to change
parameters — that one is a lock-free atomic write with no hop at all.
- <doc:RoutineTask> — the practical rules, with examples
- `ARCHITECTURE.md` §1 (thread model) and §9.2 (isolation from a routine or task) — the full
model and the reasoning behind it
---
## Next Steps
- <doc:EngineSetup> — engine parameters, lifecycle, driver options, threading rules
+2 -4
View File
@@ -65,7 +65,7 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass
### Spectral
- <doc:SpectralChain>
- ``SpectralChain``
### Signal Analysis
@@ -120,7 +120,6 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass
### Step Sequencer
- <doc:StepSequencer>
- ``StepSequencer``
- ``SequencerStep``
@@ -135,7 +134,7 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass
### Advanced
- <doc:MultiCore>
- <doc:SendTrigger>
- ``SendTrigger``
- <doc:AUv3>
### External Integrations
@@ -160,7 +159,6 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass
### Parameter Sources for Non-RT Loops
- <doc:ValueComputable>
- ``ValueComputable``
- ``ValueComputableClosure``
- ``ValueComputableBody``
+5 -1
View File
@@ -143,7 +143,11 @@ Key points:
- `after: startSec` is equivalent to `at: engine.seconds(startSec)` when called before `start()` — `currentTime` is `0` so both resolve to the same absolute sample offset.
- The envelope ends at level 0 and `doneAction` defaults to `.nothing` — synths stay in the graph but output silence. In NRT the render terminates at `totalDur` so no removal is needed. In RT, poll `env.needsFree` after each block and call `engine.remove()` when `true`.
- Set `NRTDriver(duration:)` to cover the latest possible start plus the full event length. Events whose scheduled start time falls beyond `duration` are never triggered.
- ``SynthesisEngine`` defaults to a pending event queue capacity of 1024. For large scores pass `eventQueueCapacity:` (must be a power of two) to ``SynthesisEngine/init(blockSize:controlBlockSize:sampleRate:numOutputChannels:numInputChannels:numAudioBuses:numControlBuses:eventQueueCapacity:driver:)`` — a non-power-of-two value traps at startup.
- **Large scores need two knobs raised, not one.** ``SynthesisEngine`` defaults to a pending event queue capacity of 1024 and a per-block event budget of 256. Pass both to ``SynthesisEngine/init(blockSize:controlBlockSize:sampleRate:numOutputChannels:numInputChannels:numAudioBuses:numControlBuses:eventQueueCapacity:maxEventsPerBlock:driver:)``:
- `eventQueueCapacity:` must hold every event you enqueue before `start()`, since NRT renders synchronously and nothing can refill the queue mid-render. Must be a power of two — a non-power-of-two value traps at startup.
- `maxEventsPerBlock:` bounds the future-event **look-ahead** carried across block boundaries. This is the one that silently bites: pre-schedule 5,000 events and the first block keeps only `maxEventsPerBlock` of them in carry-over and **drops the rest**. Check ``SynthesisEngine/perBlockEventDropCount`` (a console warning is also printed after the render).
Either raise both, or feed events just-in-time from a ``TriggerListener`` — `NRTDriver` drains its handlers after every block, so a handler can schedule the next few events as the render advances, keeping the in-flight count small. See <doc:Scheduling>.
### Soundfile input
+57 -21
View File
@@ -32,12 +32,12 @@ and `controlOutput(bus:source:)`.
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SineTone: SynthesizerBase {
final class MySynth: SynthesizerBase {
@LiveParam var freq: Double = 440.0
@LiveParam var amp: Double = 0.5
override func build() {
let osc = OscSin.Audio(freq: $freq, phase: 0.0, amp: 1.0)
let osc: OscSin.Audio = OscSin.Audio(freq: $freq, phase: 0.0)
output(bus: 0, source: osc * $amp)
}
}
@@ -51,7 +51,7 @@ happens here; the RT audio thread only calls `evaluate(graph:count:)`.
### Immediately (at current sample time)
```swift
let tone = SineTone()
let tone: MySynth = MySynth()
try engine.add(tone)
```
@@ -62,7 +62,7 @@ via an atomic load — safe from the main thread.
```swift
// Start tone2 at exactly sample 44100 (1 second at 44.1 kHz)
let tone2 = SineTone()
let tone2: MySynth = MySynth()
try engine.schedule(tone2, at: 44100)
```
@@ -72,7 +72,7 @@ via sub-block splitting, giving a sample-accurate onset.
### After a relative duration in seconds
```swift
let tone3 = SineTone()
let tone3: MySynth = MySynth()
try engine.schedule(tone3, after: 2.0) // 2 seconds from now
```
@@ -91,12 +91,18 @@ no allocation on the RT thread.
### Immediately
```swift
let tone: MySynth = MySynth()
try engine.add(tone)
engine.remove(tone)
```
### At an absolute sample time
```swift
let tone2: MySynth = MySynth()
try engine.schedule(tone2, at: 44100)
engine.remove(tone2, at: 44100 + engine.seconds(2.0))
```
@@ -106,9 +112,9 @@ The RT thread never calls `release()` directly.
### Schedule paired add and remove
```swift
let note = SineTone()
let startTime = engine.currentTime + engine.seconds(0.5)
let stopTime = startTime + engine.seconds(1.0)
let note: MySynth = MySynth()
let startTime: SampleTime = engine.currentTime + engine.seconds(0.5)
let stopTime: SampleTime = startTime + engine.seconds(1.0)
try engine.schedule(note, at: startTime)
engine.remove(note, at: stopTime)
@@ -121,6 +127,20 @@ Both events enqueue to the same `pendingQueue` and are sorted by target time wit
Update from the main thread at any time after the node is added. Two equivalent routes:
```swift
final class ParamSynth: SynthesizerBase {
@LiveParam var freq: Double = 440.0
@LiveParam var amp: Double = 0.5
override func build() {
output(bus: 0, source: OscSin.Audio(freq: $freq) * $amp)
}
}
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512, sampleRate: 44100, numOutputChannels: 2,
numInputChannels: 0, driver: OfflineDriver())
let tone: ParamSynth = ParamSynth()
try engine.add(tone)
tone.freq = 880.0 // typed direct write
try? tone.updateParameter("amp", value: 0.3) // by-name (e.g. from OSC)
```
@@ -152,16 +172,16 @@ By default `engine.add(_:)` inserts at the head of `mainGroup` (newest-first). U
`position:` overload to control placement precisely.
```swift
let instruments = Group()
let instruments: Group = Group()
try engine.add(instruments)
let bass = BassSynth()
let bass: MySynth = MySynth()
try engine.add(bass, position: .tail(of: instruments)) // append
let lead = LeadSynth()
let lead: MySynth = MySynth()
try engine.add(lead, position: .head(of: instruments)) // prepend — runs before bass
let pad = PadSynth()
let pad: MySynth = MySynth()
try engine.add(pad, position: .after(bass)) // insert after bass in its group
```
@@ -180,13 +200,13 @@ Use `engine.mainGroup` as a position anchor for global processing nodes:
```swift
// Run before all instruments (e.g. input limiter on live input bus)
try engine.add(InputLimiter(), position: .before(engine.mainGroup))
try engine.add(MySynth(), position: .before(engine.mainGroup))
// Default instrument add — lands in mainGroup
try engine.add(MySynth())
// Run after all instruments (e.g. ambisonic decoder, master reverb)
try engine.add(MasterReverb(), position: .after(engine.mainGroup))
try engine.add(MySynth(), position: .after(engine.mainGroup))
```
## Group Lifecycle
@@ -208,6 +228,10 @@ Releases all direct children, then self-frees when the group empties:
2. Starts a 0.1 s polling timer that watches `group.count` (atomically). When count reaches 0, calls `group.free(engine:)`.
```swift
let instruments: Group = Group()
try engine.add(instruments)
try engine.add(MySynth(), position: .tail(of: instruments))
instruments.release(engine: engine)
// All gated children begin release phase.
// When the last one finishes and is removed, instruments self-frees.
@@ -218,6 +242,10 @@ instruments.release(engine: engine)
Immediately tears down the group and all its children — no envelope release:
```swift
let instruments: Group = Group()
try engine.add(instruments)
try engine.add(MySynth(), position: .tail(of: instruments))
instruments.free(engine: engine)
// On next block: all children enqueued to freeQueue, group removed from tree.
```
@@ -266,10 +294,10 @@ it sets an atomic flag. Poll the flag from a non-RT context and post the removal
```swift
// Example — PianoNote is a user-defined SynthesizerBase subclass
class PianoNote: SynthesizerBase {
final class PianoNote: SynthesizerBase {
let env: EnvelopeGen.Audio
init() {
override init() {
env = EnvelopeGen.Audio(
envelope: Envelope(levels: [0, 1, 0], durations: [0.01, 0.3], curves: [0, 0]),
doneAction: .freeNode
@@ -281,7 +309,7 @@ class PianoNote: SynthesizerBase {
}
}
let note = PianoNote()
let note: PianoNote = PianoNote()
try engine.add(note)
// Poll from main thread (e.g. timer or display-link callback):
@@ -297,15 +325,23 @@ Do not call `engine.remove` from within the RT audio callback.
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()
final class Voice: SynthesizerBase {
@LiveParam var freq: Double = 440.0
@LiveParam var gate: Double = 0.0
override func build() {
output(bus: 0, source: OscSin.Audio(freq: $freq) * $gate * 0.2)
}
}
let group: Group = Group()
try engine.add(group)
let pool = try VoicePool(
let pool: VoicePool = try VoicePool(
voiceCount: 8, group: group, engine: engine,
stealStrategy: .oldest
) { MySynth() }
) { Voice() }
let voice = pool.noteOn(note: 60) // allocate or steal
let voice: Voice = pool.noteOn(note: 60) // allocate or steal
voice.freq = midiToHz(60)
voice.gate = 1.0
@@ -208,7 +208,7 @@ issues an atomic store.
These cases are not handled by `@LiveParam`:
- **Edge triggers / gates** — use ``SendTrigger`` to detect ≤0→>0 crossings on the RT
thread and post events to a ``TriggerListener`` handler. See <doc:SendTrigger>.
thread and post events to a ``TriggerListener`` handler. See ``SendTrigger``.
- **Envelope swap** — ``EnvelopeGen`` exposes a hot-swap path via an SPSC queue of
`EnvelopePacket` value types. Useful for live shape changes without rebuilding the synth.
- **Buffer / wavetable swap** — generators that hold a ``LyrebirdBuffer`` provide a
@@ -325,6 +325,6 @@ generator.
### See also
- <doc:SynthesizerProtocol>
- <doc:SendTrigger>
- ``SendTrigger``
- <doc:Envelopes>
- <doc:BusSystem>
+17 -125
View File
@@ -4,7 +4,7 @@
@PageKind(article)
}
Envelope-driven audio processes with a performance-paced event list, timeline capture, stem recording, and NRT offline replay.
Envelope-driven audio processes with a performance-paced event list, timeline capture, and stem recording.
## Overview
@@ -14,7 +14,7 @@ Envelope-driven audio processes with a performance-paced event list, timeline ca
- **Live performance**: step through events in real time, recording stems and capturing a performance timeline as you go.
- **Rehearsal and jump**: set ``LyrebirdEventList/index`` directly to revisit any event without releasing prior runners.
- **NRT offline replay**: load a saved timeline, wire the EventList to an `NRTDriver`-backed engine, and render all stems offline at faster-than-real-time speed.
- **Timeline replay**: capture a performance timeline as you play, save it to JSON, and replay it against a ``LyrebirdClock`` (see <doc:RoutineTask>).
- **Multi-take editing**: aggregate several performance log files via ``LyrebirdEventList/buildFromFile(id:engine:processFactories:tolerance:paths:amp:ampLag:bus:initProcess:killProcess:)`` to create a composite rehearsal EventList from the best moments of multiple takes.
---
@@ -29,7 +29,7 @@ let bell = LyrebirdProcess(
envelope: Envelope(
levels: [0.0, 1.0, 0.5, 0.0],
durations: [0.05, 2.0, 1.5],
curves: [.sin, .exp, .exp],
curves: [.sine, .exponential, .exponential],
releaseNode: 2 // level index — holds at levels[2] = 0.5 until release() is called
),
amp: 0.8,
@@ -61,8 +61,8 @@ let bell = LyrebirdProcess(
| `amp` | `Double` | `1.0` | Initial output amplitude `[0.0, 1.0]`. Live — writable after `play()`. |
| `ampLag` | `Double` | `0.01` | Lag time in seconds applied to `amp` changes. |
| `numChannels` | `Int` | required | Channel count of the private route bus. Must be `≥ 1`. |
| `procOut` | `Int` | `0` | Destination audio bus. Overridden by a parent ``LyrebirdEventList``. |
| `target` | ``LyrebirdProcessTarget`` | `.tail` | Node-tree insertion point for the process group (see below). |
| `procOut` | `any ValidBus` | `0` | Destination audio bus. Overridden by a parent ``LyrebirdEventList``. |
| `target` | ``LyrebirdProcessTarget`` | `.head` | Node-tree insertion point for the process group (see below). |
| `body` | `async` closure | required | Main process logic. Receives a ``LyrebirdProcessContext``. |
| `onRelease` | closure | `nil` | Invoked on the main thread when ``LyrebirdProcess/release(reltime:)`` is called, before the envelope tail begins. |
| `onFinished` | closure | `nil` | Invoked on the main thread after the group and bus are freed. |
@@ -246,8 +246,8 @@ ctx.numChannels // Int — channel count of the route bus
```swift
// Insert at head or tail of parent group (or engine root for standalone):
let p = LyrebirdProcess(id: "p", ..., target: .head, ...)
let p = LyrebirdProcess(id: "p", ..., target: .tail, ...) // default
let p = LyrebirdProcess(id: "p", ..., target: .head, ...) // default
let p = LyrebirdProcess(id: "p", ..., target: .tail, ...)
// Insert adjacent to a sibling process (must share the same EventList):
let p2 = LyrebirdProcess(id: "p2", ..., target: .before(p), ...)
@@ -266,7 +266,7 @@ let drone = LyrebirdProcess(
envelope: Envelope(
levels: [0.0, 0.8, 0.0],
durations: [0.5, 3.0],
curves: [.lin, .exp],
curves: [.lin, .exponential],
releaseNode: 1 // level index — holds at levels[1] = 0.8 (drone sustain)
),
numChannels: 2,
@@ -328,8 +328,8 @@ The caller advances the EventList manually by calling ``LyrebirdEventList/next()
Convenience inserters:
```swift
eventList.addPreMaster(decoder) // appended at .tail(of: preMasterGroup)
eventList.addPostMaster(limiter) // appended at .tail(of: postMasterGroup)
try eventList.addPreMaster(decoder) // appended at .tail(of: preMasterGroup)
try eventList.addPostMaster(limiter) // appended at .tail(of: postMasterGroup)
```
Synths added via these helpers are children of the master sub-group and are freed together with the EventList session (on ``LyrebirdEventList/killAll()``, ``LyrebirdEventList/releaseAll()``-driven envelope end, or ``LyrebirdEventList/reset()``). The sub-groups are re-allocated empty after teardown so subsequent playback starts clean.
@@ -349,7 +349,7 @@ let events: [LyrebirdEvent] = [
LyrebirdEvent(releases: [drone, wash]) // event 3: release remaining
]
let list = LyrebirdEventList(
let list = try LyrebirdEventList(
id: "my-performance",
events: events,
engine: engine,
@@ -645,7 +645,7 @@ The MyPiece project under `Lyrebird-Pieces/MyPiece` uses this exact shape for it
## Timeline
As the EventList runs, it silently captures a ``LyrebirdTimelineEntry`` for every event that fires. This timeline can be saved, loaded, and replayed — including offline against an NRT engine.
As the EventList runs, it silently captures a ``LyrebirdTimelineEntry`` for every event that fires. This timeline can be saved, loaded, and replayed against a ``LyrebirdClock``.
### Live Capture
@@ -701,71 +701,6 @@ list.isPlayingTimeline // Bool
``LyrebirdEventList/playTimeline(clock:)`` sorts entries by offset defensively before scheduling, converts each offset to a sample-accurate ``SampleTime``, and fires ``LyrebirdEventList/play(eventIndex:)`` on the main thread at the correct moment via a ``LyrebirdRoutine`` background thread. The `_isReplaying` flag is set for the duration to suppress re-capture, so the timeline array is not modified during replay.
### NRT Offline Replay Walkthrough
This is the primary use case for the timeline system: render a live performance as individual stems offline, at faster-than-real-time speed.
```swift
import LyrebirdSynth
// 1. Build the NRT engine.
let nrtDriver = NRTDriver(sampleRate: 44100, blockSize: 64)
let engine = try SynthesisEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 128,
numControlBuses: 64,
driver: nrtDriver
)
try engine.start()
// 2. Reconstruct the EventList with the same process definitions.
// (Processes must be rebuilt — they are single-use instances.)
let bell0 = LyrebirdProcess(id: "bell", envelope: bellEnvelope(), numChannels: 2,
body: { ctx in /* ... */ })
let drone0 = LyrebirdProcess(id: "drone", envelope: droneEnvelope(), numChannels: 2,
body: { ctx in /* ... */ })
let events: [LyrebirdEvent] = [
LyrebirdEvent(starts: [bell0]),
LyrebirdEvent(starts: [drone0], releases: [bell0])
]
let stemDir = URL(fileURLWithPath: "/tmp/nrt-render/stems")
let list = LyrebirdEventList(
id: "my-performance",
events: events,
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
// 3. Load the saved timeline.
let timelineURL = URL(fileURLWithPath: "/tmp/my-session/timeline.json")
try list.loadTimeline(from: timelineURL)
// 4. Enable stem recording before replay begins.
list.record(directory: stemDir, format: .wavFloat32)
// 5. Build a clock to drive replay timing.
let clock = LyrebirdClock(engine: engine, bpm: 120.0)
// 6. Start timeline playback — fires events at their recorded offsets.
list.playTimeline(clock: clock)
// 7. Drive the NRT engine forward in time until all events have fired
// and all processes have finished.
let totalDuration = (list.timeline.last?.offset ?? 0.0) + 10.0 // add tail margin
try nrtDriver.renderDuration(totalDuration)
// 8. Stems are now on disk in stemDir. Load them into your DAW aligned at 0.0.
engine.stop()
```
The offset embedded in each stem filename is the time origin for that stem within the session. In your DAW, set each clip's start position to the filename's offset and all stems will lock to the performance grid automatically.
---
## buildFromFile
@@ -859,7 +794,7 @@ try composite.saveTimeline(to: URL(fileURLWithPath: "/tmp/composite/timeline.jso
## End-to-End Example
The following example walks through a complete live-performance-to-NRT-render workflow.
The following example walks through a complete live-performance workflow — define process bodies, build an EventList, record stems, and drive events by hand.
```swift
import LyrebirdSynth
@@ -890,7 +825,7 @@ func bellEnvelope() -> Envelope {
Envelope(
levels: [0.0, 1.0, 0.6, 0.0],
durations: [0.05, 1.5, 2.0],
curves: [.sin, .exp, .exp],
curves: [.sine, .exponential, .exponential],
releaseNode: 2 // level index — sustain at levels[2] = 0.6
)
}
@@ -899,7 +834,7 @@ func droneEnvelope() -> Envelope {
Envelope(
levels: [0.0, 0.8, 0.0],
durations: [0.5, 3.0],
curves: [.lin, .exp],
curves: [.lin, .exponential],
releaseNode: 1 // level index — sustain at levels[1] = 0.8
)
}
@@ -951,7 +886,7 @@ try engine.start()
let stemDir = URL(fileURLWithPath: "/tmp/my-session/stems")
let timelineURL = URL(fileURLWithPath: "/tmp/my-session/timeline.json")
let list = LyrebirdEventList(
let list = try LyrebirdEventList(
id: "demo",
events: events,
engine: engine,
@@ -971,49 +906,6 @@ list.next() // fires event 2 — both released
// Save the performance timeline.
try list.saveTimeline(to: timelineURL)
engine.stop()
// MARK: - NRT replay
let nrtDriver = NRTDriver(sampleRate: 44100, blockSize: 64)
let nrtEngine = SynthesisEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 128,
numControlBuses: 64,
driver: nrtDriver
)
try nrtEngine.start()
// Rebuild events with fresh process instances.
let bell2 = LyrebirdProcess(id: "bell", envelope: bellEnvelope(), numChannels: 2,
body: { ctx in let s = BellSynth(); ctx.add(s) })
let drone2 = LyrebirdProcess(id: "drone", envelope: droneEnvelope(), numChannels: 2,
body: { ctx in let s = DroneSynth(); ctx.add(s) })
let nrtList = LyrebirdEventList(
id: "demo",
events: [
LyrebirdEvent(starts: [bell2]),
LyrebirdEvent(starts: [drone2]),
LyrebirdEvent(releases: [bell2, drone2])
],
engine: nrtEngine,
bus: AudioBus(index: 0, channelCount: 2)
)
try nrtList.loadTimeline(from: timelineURL)
nrtList.record(directory: stemDir, format: .wavFloat32)
let clock = LyrebirdClock(engine: nrtEngine, bpm: 120.0)
nrtList.playTimeline(clock: clock)
let lastOffset = nrtList.timeline.last?.offset ?? 0.0
try nrtDriver.renderDuration(lastOffset + 10.0)
nrtEngine.stop()
// Stems are in /tmp/my-session/stems — load into DAW aligned at 0.0.
```
---
@@ -1090,7 +982,7 @@ win.close()
- ``LyrebirdProcessError``
- ``LyrebirdTimelineEntry``
- ``LyrebirdTimelineError``
- <doc:ValueComputable>
- ``ValueComputable``
- <doc:ScoreSystem>
- <doc:SynthesizerProtocol>
- <doc:RoutineTask>
@@ -44,10 +44,12 @@ Swift-Package-only templates (lightweight; `Package.swift` opens in Xcode for Sw
| Template | Command | Description |
|---|---|---|
| `basic` (default) | `lyrebird new MyPiece` | Minimal engine + `RunLoop.main.run()` |
| `quickstart` | `lyrebird new MyFirstSound --template quickstart` | Fastest sound — a one-oscillator `SineTone` that plays 440 Hz for 10 s and exits |
| `basic` (default) | `lyrebird new MyPiece` | Minimal engine + `RunLoop.main.run()` (no synth wired yet) |
| `demo` | `lyrebird new MyPiece --template demo` | `SineTone` with `@LiveParam` frequency and amplitude |
| `ui-demo` | `lyrebird new MyApp --template ui-demo` | AppKit window with `@UIParam` controls and `LyrebirdWindow` |
| `nrt` | `lyrebird new MyRender --template nrt` | `NRTDriver` renders to `output.caf` then exits |
| `score` | `lyrebird new MyScore --template score` | Builds a `Score` with the notation DSL, exports MusicXML (round-trip checked), renders offline via `NRTDriver` |
Xcode-project templates (ship a full `.xcodeproj` for deliverables SwiftPM can't express — `.app` bundles, AUv3 extensions):
+78 -4
View File
@@ -16,8 +16,8 @@ A demand-rate value sequence. Not thread-safe; use within a single Routine/Task.
```swift
let freqs = Pattern.sequence([440.0, 550.0, 880.0], repeats: 2)
while let f = freqs.next() { ... } // iterates twice, then next() returns nil
freqs.reset() // restart from beginning
while let f = freqs.next() { _ = f } // iterates twice, then next() returns nil
freqs.reset() // restart from beginning
```
| Property/Method | Description |
@@ -132,11 +132,23 @@ The returned `Pattern` has `repeats: -1` (infinite). Call `reset()` to restart f
Runs a closure **once** on a dedicated background thread (`.userInitiated` QoS).
```swift
final class SineTone: SynthesizerBase {
@LiveParam var freq: Double = 440.0
override func build() {
output(bus: 0, source: OscSin.Audio(freq: $freq) * 0.2)
}
}
let routine = LyrebirdRoutine { ctx in
ctx.tempo = 120.0
let freqs = Pattern.sequence([440.0, 550.0, 660.0])
while let freq = freqs.next() {
let tone = SineTone(); tone.freq = freq
// SynthesizerBase is @MainActor — construct and configure it on main.
let tone: SineTone = ctx.onMain {
let t: SineTone = SineTone()
t.freq = freq
return t
}
ctx.add(tone)
try ctx.wait(beats: 1.0) // 0.5 s at 120 BPM; compensates for work above
ctx.remove(tone)
@@ -196,6 +208,38 @@ idle → running → paused → running → stopped
Passed to the body closure. Provides a routine clock, timed waits, and engine calls.
### Threading and actor isolation
A body is `@Sendable` and runs on its own background thread, while `SynthesizerBase` is
`@MainActor`. Two consequences shape every body you write:
- **To construct a synth inside the body, use `ctx.onMain`.** It runs a main-actor closure,
blocks the body until it returns, and hands the result back — so the number and parameters
of the synths can depend on the body's own logic instead of being pre-allocated outside and
captured. Keep the closure short; it blocks the body *and* main. `ctx.add` then dispatches
the (main-bound) `build()` for you. Note `onMain` hops **synchronously with no timeout**, so
it needs a main thread that is actually being serviced — a GUI run loop, or a caller parked
on `waitUntilComplete()` / `LyrebirdTask.run`. Don't `start()` a task and then block main on
a bare sleep or semaphore: `ctx.add` would merely queue, but `onMain` would hang.
- **To change a parameter, use `ctx.set` with a `$param` node captured on main.** Unlike
`ctx.add`, `ctx.set` is *not* a main hop — it is a lock-free atomic write that runs inline on
the body's own thread. Direct property writes (`synth.freq = 880`) are main-isolated and
unavailable from a body.
```swift
let cutoff: ParameterNode = filter.$cutoff // capture on main, once
LyrebirdTask.run(engine: engine) { ctx in
let grain: Grain = ctx.onMain { Grain(rate: nextRate()) } // construct in-body
ctx.add(grain)
ctx.set(cutoff, to: 1200) // atomic, no dispatch
try ctx.wait(seconds: 0.05)
}
```
The full model — what is main-bound and why, the pre- vs post-publication distinction, and why
`SynthesizerBase.init` cannot simply be made `nonisolated` — is documented in `ARCHITECTURE.md`
§9.2 ("Working with the isolation from a routine or task").
### Routine clock
The context exposes two parallel timelines: a **wall-clock** clock (driven by `Date()`) and a **sample-accurate** clock (driven by `engine.currentTime`).
@@ -298,6 +342,36 @@ ctx.remove(synth, at: sampleTime)
ctx.remove(synth, afterBeats: 4.0) // 4 beats at current tempo
```
### Live parameters
Change a running synth's `@LiveParam` from the body. Unlike the engine calls above, a `ParameterNode` write goes straight to its lock-free atomic — no main-thread hop — so it runs inline on the routine's own thread; the RT thread reads it at the next block.
> `@UIParam` (`UIParamNode`) is **not** a valid target — its `@Observable` value is main-thread-only. `ctx.set` / `ctx.ramp` take a `ParameterNode`; update `@UIParam` from the main thread.
```swift
ctx.set(param, to: 8.0) // step
try ctx.ramp(param, to: 0.5, seconds: 3) // glide over 3 s, then continue
try ctx.ramp(param, to: 0.5, beats: 2) // glide in beats at the current tempo
```
``LyrebirdRoutineContext/ramp(_:to:seconds:)`` **blocks** the body for its duration (like `wait`) and lands exactly on the target. It steps the scalar at the poll granularity; the `ParameterNode`'s own per-block interpolation blends the steps into a continuous glide, and no node source is installed — so a later ``LyrebirdRoutineContext/set(_:to:)`` still applies immediately.
`param` is the synth's **projected node, captured on the main actor first** — the `@MainActor` synth's `@LiveParam` property/`$`-projection isn't reachable from the background body:
```swift
let reverbSynth = GVerbTest(sampleRate: sr) // @MainActor setup
let reverbTime = reverbSynth.$reverbTime // ParameterNode — Sendable
LyrebirdTask.run(engine: engine) { ctx in // @Sendable body — background thread
ctx.add(reverbSynth)
try ctx.wait(beats: 2)
ctx.set(reverbTime, to: 8.0)
try ctx.ramp(reverbTime, to: 0.5, beats: 2)
}
```
For a synth driven mostly from routines, expose the node as a `nonisolated let ParameterNode` instead of `@LiveParam` — reachable from the body with no capture, at the cost of the plain-`Double` value sugar.
## Error Handling
```swift
@@ -407,6 +481,6 @@ bass.start(engine: engine)
## See Also
- ``LyrebirdClock``
- <doc:ValueComputable>
- ``ValueComputable``
- <doc:Scheduling>
- <doc:NodeTree>
+28 -2
View File
@@ -80,7 +80,7 @@ Fixed-capacity ring buffer with no allocation after `init`.
```swift
final class SPSCQueue<T> {
init(capacity: Int) // capacity rounded up to next power of 2
init(capacity: Int) // capacity MUST be a power of two — precondition, not rounded
func enqueue(_ value: T) -> Bool // producer (main thread) only
func dequeue() -> T? // consumer (RT thread) only
@@ -111,6 +111,32 @@ currentBlockStart = engine.currentTime
Events scheduled in the past (before `currentBlockStart`) are applied at offset 0.
## Per-Block Event Budget
Step 2's drain and the future-event **carry-over** are both capped at `maxEventsPerBlock`
(`SynthesisEngine.init` parameter, default 256) so the RT thread never reallocates its staging
arrays mid-render. The cap bounds two things per block:
- **Events firing this block** — the per-block onset density.
- **Look-ahead depth** — future-dated events are held in a carry-over buffer capped at the same
value. Anything beyond it is **dropped, not deferred**.
This — not `eventQueueCapacity` — is what decides whether a large batch of pre-scheduled events
survives. Dropping is silent on the audio path but instrumented off-RT:
```swift
engine.perBlockEventDropCount // events dropped for exceeding maxEventsPerBlock
engine.resetPerBlockEventDropCount()
engine.pendingQueueDroppedCount // separate: main-thread enqueue failures (queue full)
```
A one-line `[Lyrebird] Warning: … exceeded maxEventsPerBlock …` is printed at most once per
drain. The RT thread only bumps an atomic and sets a latch; a non-RT drain prints.
Either raise the cap (costs pre-allocated memory only, never RT time) or spread scheduling over
time — e.g. a just-in-time feed driven by a ``TriggerListener``, whose handlers `NRTDriver` runs
after every block — so no single block's onset density or look-ahead exceeds the budget.
## Generator count Parameter
Because segments are variable length, generators produce `count` samples rather than always
@@ -187,7 +213,7 @@ seq.onNoteOff = { _, step, _ in pool.noteOff(note: step.pitch) }
seq.start(engine: engine) // quantizes to clock.nextBeat() by default
```
Internally ``StepSequencer`` uses `waitUntil(sampleTime:)` at each step boundary, keeping it phase-locked to other routines and tasks sharing the same ``LyrebirdClock``. See <doc:StepSequencer> for the full API.
Internally ``StepSequencer`` uses `waitUntil(sampleTime:)` at each step boundary, keeping it phase-locked to other routines and tasks sharing the same ``LyrebirdClock``. See ``StepSequencer`` for the full API.
## Routine Elapsed Time
+50 -37
View File
@@ -133,7 +133,7 @@ let score = Score(
TempoChange(measure: 9, bpm: 72) // adagio at bar 9
]
) {
Part("melody") { … }
Part("melody") { Note(.c, 4, dur: .quarter) }
}
```
@@ -156,7 +156,7 @@ When two `TempoChange` values target the same measure, **first-in-array order wi
### MusicXML encoding
``Score/toMusicXMLString(divisions:)`` emits a tempo `<direction placement="above">` block at the start of each matching measure, in **every** part. The format is identical to the measure-1 base-tempo direction:
``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` emits a tempo `<direction placement="above">` block at the start of each matching measure, in **every** part. The format is identical to the measure-1 base-tempo direction:
```xml
<direction placement="above">
@@ -201,7 +201,7 @@ let score = Score(
]
)
) {
Part("melody") { … }
Part("melody") { Note(.c, 4, dur: .quarter) }
}
```
@@ -226,7 +226,7 @@ The `repeats:` parameter defaults to ``RepeatStructure/none`` (empty — zero `<
### MusicXML barline encoding
``Score/toMusicXMLString(divisions:)`` emits `<barline>` elements inside each matching `<measure>` block, in **every** part. Child element order follows the MusicXML 4.0 DTD (`<bar-style>`, `<ending>`, `<repeat>`):
``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` emits `<barline>` elements inside each matching `<measure>` block, in **every** part. Child element order follows the MusicXML 4.0 DTD (`<bar-style>`, `<ending>`, `<repeat>`):
**Left barline** (forward repeat and/or ending start) — emitted after `<attributes>` and the tempo direction, before the first note/rest:
@@ -300,7 +300,7 @@ let score = Score(
MeterMap.Segment(startBar: 5, .threeFour), // mid-piece change at bar 5
], anacrusis: Fraction(1, 1)) // one-quarter pickup
) {
Part("lead") { … }
Part("lead") { Note(.c, 4, dur: .quarter) }
}
```
@@ -358,8 +358,8 @@ distribution). See ``ScoreTimeline`` for the full surface.
```swift
let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4), keySignature: .gMajor) {
Part("melody") { … }
Part("bass", channel: 1, clef: .bass) { … }
Part("melody") { Note(.g, 4, dur: .quarter) }
Part("bass", channel: 1, clef: .bass) { Note(.g, 2, dur: .whole) }
}
```
@@ -394,7 +394,7 @@ Named static-let constants cover every key in the table:
### MusicXML round-trip
``Score/toMusicXMLString(divisions:)`` emits `<key>` inside `<attributes>` after `<divisions>` and before `<time>`, in every part's measure 1:
``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` emits `<key>` inside `<attributes>` after `<divisions>` and before `<time>`, in every part's measure 1:
```xml
<attributes>
@@ -445,7 +445,7 @@ Named conveniences for common instruments:
### Per-part key override
Pass `keySignature:` to the ``Part(_:channel:clef:keySignature:transpose:elements:)`` DSL constructor:
Pass `keySignature:` to the ``Part(_:channel:clef:keySignature:transpose:meterMap:offset:id:elements:)`` DSL constructor:
```swift
// Concert key G major. B♭ clarinet: written key A major (a major 2nd up).
@@ -463,7 +463,7 @@ let score = Score(bpm: 120, keySignature: .gMajor) {
### MusicXML encoding
``Score/toMusicXMLString(divisions:)`` emits each part's **effective key** in its `<key>` block:
``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` emits each part's **effective key** in its `<key>` block:
- Parts with a `keySignature` override → emit the override's fifths/mode.
- Parts with `keySignature == nil` → emit the score-level key (unchanged behaviour).
@@ -506,14 +506,14 @@ Resolution rules:
## Clef
Each ``ScorePart`` carries a ``Clef`` used when encoding to MusicXML. Set it via the
`clef:` parameter of the ``Part(_:channel:clef:elements:)`` DSL constructor:
`clef:` parameter of the ``Part(_:channel:clef:keySignature:transpose:meterMap:offset:id:elements:)`` DSL constructor:
```swift
Part("Violin", clef: .treble) { … }
Part("Viola", clef: .alto) { … }
Part("Cello", clef: .bass) { … }
Part("Guitar", clef: .treble8vb) { … } // sounds an octave lower
Part("Drums", clef: .percussion) { … }
let violin: ScorePart = Part("Violin", clef: .treble) { Note(.c, 4, dur: .quarter) }
let viola: ScorePart = Part("Viola", clef: .alto) { Note(.c, 4, dur: .quarter) }
let cello: ScorePart = Part("Cello", clef: .bass) { Note(.c, 3, dur: .quarter) }
let guitar: ScorePart = Part("Guitar", clef: .treble8vb) { Note(.c, 4, dur: .quarter) } // sounds an octave lower
let drums: ScorePart = Part("Drums", clef: .percussion) { Note(.c, 4, dur: .quarter) }
```
The default is ``Clef/auto``, which infers the clef at encode time from the
@@ -609,7 +609,7 @@ The flattened total span is exactly 2 beats (5 outer eighth slots × 2/5 each),
### MusicXML bracket engraving for nested tuplets
When you export nested tuplets via ``Score/toMusicXMLString(divisions:)``, each
When you export nested tuplets via ``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)``, each
bracket level receives the correct displayed number. The encoder applies a
**per-part** rule:
@@ -715,11 +715,14 @@ staff of a grand staff keeps its own dynamic line and genuinely different voice
dynamics (one voice `f`, another `p`) are always preserved.
This is controlled by the `collapseRedundantDynamics` parameter on
``Score/toMusicXMLString(divisions:collapseRedundantDynamics:)`` (and
``Score/toMusicXMLData(divisions:collapseRedundantDynamics:)``), which defaults
``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` (and
``Score/toMusicXMLData(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)``), which defaults
to `true`. Pass `false` to restore the raw one-direction-per-voice output:
```swift
let score = Score(bpm: 120) {
Part("melody") { Note(.c, 4, dur: .quarter) }
}
let clean: String = score.toMusicXMLString() // collapsed (default)
let raw: String = score.toMusicXMLString(collapseRedundantDynamics: false) // one per voice
```
@@ -872,7 +875,7 @@ composes freely with `Crescendo`, `Diminuendo`, `Tuplet`, and `Voice` wrappers.
When a note must simultaneously carry boundaries from *different* overlapping
spans — for example, a slur that starts on the same note where a crescendo ends
— use the `spanners:` parameter on ``Note`` or ``Chord``:
— use the `spanners:` parameter on `Note` or `Chord`:
```swift
Part("lead") {
@@ -1481,6 +1484,12 @@ Pitch.named(.cQuarterSharp, 4).frequency // C4 × 2^(0.5/12) ≈ 268.
on a ``LyrebirdRoutine`` thread. Two modes:
```swift
// Your own note renderer and sampler — anything that consumes a ScoreEvent / MIDIMessage.
struct NoteRenderer: Sendable { func handle(_ event: ScoreEvent) {} }
struct DrumSampler: Sendable { func handle(_ message: MIDIMessage) {} }
let mySynth: NoteRenderer = NoteRenderer()
let mySampler: DrumSampler = DrumSampler()
let score = Score(bpm: 120) {
Part("lead", channel: 0) {
Note(.c, 4, dur: .quarter)
@@ -1488,8 +1497,8 @@ let score = Score(bpm: 120) {
Note(.g, 4, dur: .half)
}
}
let clock = LyrebirdClock(engine: engine, bpm: 120)
let player = ScorePlayer(score: score, engine: engine, clock: clock)
let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: 120)
let player: ScorePlayer = ScorePlayer(score: score, engine: engine, clock: clock)
// Mode 1: emit one ScoreEvent per notated event. Caller drives note-off /
// sustain via event.performedDuration (sounding length) as needed.
@@ -1525,6 +1534,8 @@ no external dependency.
### Score → SMF bytes
```swift
import Foundation
let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead", channel: 0) {
Note(.c, 4, dur: .quarter)
@@ -1535,7 +1546,7 @@ let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Note(.c, 2, dur: .whole)
}
}
let data = score.toMIDIFileBytes(ticksPerQuarter: 480)
let data: Data = score.toMIDIFileBytes(ticksPerQuarter: 480)
try data.write(to: URL(fileURLWithPath: "/tmp/score.mid"))
```
@@ -1586,6 +1597,8 @@ format.
### Score → MusicXML
```swift
import Foundation
let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("Melody") {
Note(.cFlat, 4, dur: .quarter) // distinct from B3
@@ -1594,8 +1607,8 @@ let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .half)
}
}
let xml = score.toMusicXMLString() // String
let data = score.toMusicXMLData() // UTF-8 Data
let xml: String = score.toMusicXMLString() // String
let data: Data = score.toMusicXMLData() // UTF-8 Data
try data.write(to: URL(fileURLWithPath: "/tmp/score.musicxml"))
```
@@ -1614,7 +1627,7 @@ print("\(score.bpm) BPM, \(score.parts.count) parts")
Parses `<part-list>` for part names + IDs, walks each `<part>` `<measure>`
collecting `<note>` blocks. `<pitch>` (`<step>`, `<alter>`, `<octave>`)
maps directly back to ``Pitch/named(_:_:)`` preserving spelling.
`<chord/>` flag groups simultaneous notes into ``ScoreElement/chord(_:duration:dynamic:articulation:voice:)``.
`<chord/>` flag groups simultaneous notes into ``ScoreElement/chord(_:duration:dynamic:articulation:voice:tie:)``.
`<rest/>` advances cursor without emitting a note.
First `<sound tempo="...">` or `<metronome><per-minute>` becomes
``Score/bpm``. First `<time>` becomes ``Score/timeSignature``.
@@ -1630,7 +1643,7 @@ Articulations (`<staccato/>`, `<accent/>`, `<strong-accent/>`,
- Beat positions and durations (via configurable `<divisions>`,
default 480).
- Chord groupings (consecutive `<note>` elements with `<chord/>` ↔
``ScoreElement/chord(_:duration:dynamic:articulation:voice:)``).
``ScoreElement/chord(_:duration:dynamic:articulation:voice:tie:)``).
- Tempo + time signature.
- Track / part names.
- Voice numbers.
@@ -1719,11 +1732,11 @@ For example, a section starting at global bar 5 with a local `TempoChange(measur
Parts are matched across sections by ``ScorePart/id``, not by ``ScorePart/name``. This lets a section rename an instrument (e.g. `"Solo Lead"` in one section, `"Rhythm Lead"` in another) while still stitching their content together into the same flat part:
```swift
Section("A") {
Part("Solo Lead", id: "lead") { … }
let a: ScoreSection = Section("A") {
Part("Solo Lead", id: "lead") { Note(.c, 4, dur: .quarter) }
}
Section("B") {
Part("Rhythm Lead", id: "lead") { … } // same flat part as "Solo Lead"
let b: ScoreSection = Section("B") {
Part("Rhythm Lead", id: "lead") { Note(.e, 4, dur: .quarter) } // same flat part as "Solo Lead"
}
```
@@ -1764,12 +1777,12 @@ No authoring action is required — this happens during section lowering. The fi
```swift
// Simple: letter paper, portrait, default margins and scaling.
let score = Score(bpm: 120, pageLayout: PageLayout()) {
Part("Piano") { … }
let letterScore = Score(bpm: 120, pageLayout: PageLayout()) {
Part("Piano") { Note(.c, 4, dur: .quarter) }
}
// A4 landscape with custom margins.
let score = Score(
let a4Score = Score(
bpm: 120,
pageLayout: PageLayout(
size: .a4,
@@ -1777,12 +1790,12 @@ let score = Score(
margins: PageLayout.Margins(uniformMillimeters: 20.0)
)
) {
Part("Piano") { … }
Part("Piano") { Note(.c, 4, dur: .quarter) }
}
// Section-based score with page layout.
let score = Score(bpm: 120, pageLayout: PageLayout(size: .a4)) {
Section("Intro") { Part("lead") { … } }
let sectionScore = Score(bpm: 120, pageLayout: PageLayout(size: .a4)) {
Section("Intro") { Part("lead") { Note(.c, 4, dur: .quarter) } }
}
```
@@ -1,8 +1,4 @@
# RT-to-Language Triggers
@Metadata {
@PageKind(article)
}
# ``SendTrigger``
Detect signal edges on the audio thread and react in Swift — add synths, update state, sequence events.
@@ -68,7 +64,7 @@ addOutputGenerator(Out.Audio(bus: 0, source: osc))
### Value payload
The optional `value` argument captures a signal sample at the moment of each crossing. Pass any `ValidGeneratorInput` — a constant, a generator, or a parameter string.
The optional `value` argument captures a signal sample at the moment of each crossing. Pass any `ValidGeneratorInput` — a constant, a generator, or a closure.
```swift
let lfo = OscSin.Control(freq: 0.5) // 0.5 Hz LFO
@@ -1,4 +1,4 @@
# SpectralChain
# ``SpectralChain``
Consolidated STFT pipeline. One ``SpectralChain/Audio`` Generator owns
the forward FFT, the polar-domain processor chain, optional sidechain
@@ -1,8 +1,4 @@
# Step Sequencer
@Metadata {
@PageKind(article)
}
# ``StepSequencer``
Iterate a fixed step array on a `LyrebirdClock`-synchronized background thread with per-step pitch, velocity, gate, probability, and parameter locks.
@@ -8,16 +8,23 @@ The composable unit of instrument or effect in Lyrebird.
## Protocol Definition
```swift
public protocol Synthesizer: AnyObject {
func build() // allocate generators; main thread only
func evaluate(graph: SynthGraph, count: Int) // RT thread; default is no-op
func release(engine: SynthesisEngine) throws // graceful gate→0; default throws .noGate
func free(engine: SynthesisEngine) // immediate removal; default posts remove event
}
```
``Synthesizer`` is four requirements, split along the thread boundary — `build` / `release` / `free`
are the language side, `evaluate` is the RT side:
Default `evaluate` is a no-op (``SynthesizerBase`` provides the real one). Default `release` throws `SynthesizerError.noGate` — override it in synthesizers with a gate input. Default `free` posts an immediate engine remove event.
| Requirement | Isolation | Contract |
|---|---|---|
| ``Synthesizer/build()`` | `@MainActor` | Configure the generator DAG. Called once, when the synth is added. Allocate every generator here — never during `evaluate`. |
| ``Synthesizer/evaluate(graph:count:)`` | `nonisolated` | Evaluate one block segment. The RT render thread's **only** entry point into a Synthesizer; must not hop actors. Called once per segment — more than once per block when a scheduled event splits it. Default is a no-op; ``SynthesizerBase`` provides the real one. |
| ``Synthesizer/release(engine:)`` | `@MainActor` | Begin a graceful release (typically post `gate = 0`). Default throws ``SynthesizerError/noGate`` — override it in any synthesizer with a gate input. |
| ``Synthesizer/free(engine:)`` | `@MainActor` | Immediate removal. Posts a remove event at the current sample time; the synth stops evaluating once the RT thread applies it. |
The isolation split is the load-bearing part: see `ARCHITECTURE.md` §9.1. Language-side requirements
must never be called from the RT audio thread.
``SynthesizerBase`` declares `release(engine:)` and `free(engine:)` as `open` members mirroring
the protocol defaults, so a subclass `override` dispatches correctly when a caller holds an
`any Synthesizer` — which is how ``Group`` reaches its children. Subclass ``SynthesizerBase``
and `override`; do not rely on the protocol extension default to pick up your implementation.
## Synthesizer Lifecycle
@@ -38,6 +45,9 @@ final class GatedNote: SynthesizerBase {
Call `free(engine:)` for an immediate hard kill:
```swift
let note: MySynth = MySynth()
try engine.add(note)
note.free(engine: engine) // removed on next block boundary
```
@@ -74,35 +84,64 @@ final class SineTone: SynthesizerBase {
@LiveParam var amp: Double = 0.5
override func build() {
let osc = OscSin.Audio(freq: $freq, phase: 0.0)
let osc: OscSin.Audio = OscSin.Audio(freq: $freq, phase: 0.0)
output(bus: 0, source: osc * $amp)
}
}
// Update from the main thread. Both routes write the same atomic.
let note: SineTone = SineTone()
note.freq = 880.0 // typed direct write
try? note.updateParameter("freq", value: 880.0) // by-name (e.g. OSC handler)
```
`@LiveParam` / `@UIParam` properties are auto-registered via `Mirror` reflection at the end
of `build()`. The property name (with the leading `_` of property-wrapper backing storage
stripped) becomes the parameter key.
Update parameters from the main thread:
```swift
note.freq = 880.0 // typed direct write
try? note.updateParameter("freq", value: 880.0) // by-name (e.g. OSC handler)
```
Both routes write the same atomic. The RT audio thread picks up the new value at the start
of the next (sub-)block — never mid-block.
The RT audio thread picks up the new value at the start of the next (sub-)block — never
mid-block.
`updateParameter` throws `ParameterUpdateError.keyNotFound` if no live parameter exists for
the supplied key.
Or drive a `@LiveParam` from a `LyrebirdRoutine` / `LyrebirdTask` body — timed, sequential
control code on a background thread. The synth is `@MainActor`, so capture the projected node
(`$freq`, a `Sendable` `ParameterNode`) on the main actor, then use `ctx.set` / `ctx.ramp`:
```swift
final class SineTone: SynthesizerBase {
@LiveParam var freq: Double = 440.0
override func build() {
output(bus: 0, source: OscSin.Audio(freq: $freq) * 0.2)
}
}
let note: SineTone = SineTone()
let freq: ParameterNode = note.$freq // captured on the main actor
LyrebirdTask.run(engine: engine) { ctx in
ctx.add(note)
ctx.set(freq, to: 660) // step
try ctx.ramp(freq, to: 220, beats: 2) // timed glide
}
```
`ctx.set` / `ctx.ramp` take a `ParameterNode` only — `@UIParam`'s `UIParamNode` is `@Observable`
and main-thread-only. See <doc:RoutineTask> § Live parameters.
For the full decision matrix (when to use `@LiveParam` vs direct generator wiring vs
`SendTrigger` vs envelope/buffer swap), see <doc:ParameterInputs>.
## Convenience Helpers (SynthesizerBase)
These are all called from inside `build()`:
```swift
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfo: OscSin.Control = OscSin.Control(freq: 2.0)
// Audio output
output(bus: 0, source: signal) // one bus
output(buses: 0..<2, source: signal) // same source to multiple buses (fan-out cached)
@@ -111,20 +150,20 @@ output(buses: 0..<2, source: signal) // same source to multiple buses (f
controlOutput(bus: 5, source: lfo)
// Audio input (returns In.Audio generator)
let sig = input(bus: 2)
let sig: In.Audio = input(bus: 2)
// Control input (returns In.Control generator, interpolated)
let ctrl = controlInput(bus: 10)
let ctrl: In.Control = controlInput(bus: 10)
// Multi-channel audio input (returns GeneratorArray)
let stereo = input(bus: 2, channels: 2)
let stereo: GeneratorArray = input(bus: 2, channels: 2)
```
## Adding to the Engine
```swift
let note1 = SineTone()
let note2 = SineTone() // independent instance — own phase, own envelope
let note1: MySynth = MySynth()
let note2: MySynth = MySynth() // independent instance — own phase, own envelope
try engine.add(note1)
try engine.add(note2)
```
@@ -138,6 +177,13 @@ The RT audio thread in `applyEvent` only wires pointer references — no allocat
## Removing from the Engine
```swift
let note1: MySynth = MySynth()
let note2: MySynth = MySynth()
try engine.add(note1)
try engine.add(note2)
let someTime: SampleTime = engine.currentTime + engine.seconds(2.0)
engine.remove(note1)
engine.remove(note2, at: someTime) // sample-accurate removal
```
@@ -154,11 +200,21 @@ constructed inside ``SynthesizerBase/build()`` with `doneAction: .freeNode` self
with the synth's auto-free watcher — no explicit call needed:
```swift
public override func build() {
let env = EnvelopeGen.Control(envelope: myEnv,
timeScale: 8.0,
doneAction: .freeNode) // self-registers
output(bus: 0, source: someSignal * env)
final class PluckedNote: SynthesizerBase {
override func build() {
let myEnv: Envelope = Envelope(
levels: [0, 1, 0],
durations: [0.01, 0.3],
curves: [.sine, .exponential]
)
let someSignal: OscSin.Audio = OscSin.Audio(freq: 440.0)
let env: EnvelopeGen.Control = EnvelopeGen.Control(
envelope: myEnv,
timeScale: 8.0,
doneAction: .freeNode // self-registers
)
output(bus: 0, source: someSignal * env)
}
}
```
@@ -170,6 +226,10 @@ For probes constructed outside `build()`, or for custom ``DoneActionWatchable``
register explicitly:
```swift
let myProbe: EnvelopeGen.Control = EnvelopeGen.Control(
envelope: Envelope(levels: [0, 1, 0], durations: [0.01, 0.3], curves: [.sine, .exponential]),
doneAction: .freeNode
)
autoFreeOnDone(myProbe)
```
@@ -185,6 +245,8 @@ Do not call `engine.remove` from within the RT callback.
- `updateParameter` issues a releasing atomic store on the projected `ParameterNode` /
`UIParamNode`; the RT thread picks up the new value via an acquiring atomic load at the
start of the next (sub-)block — no queue, no dictionary mutation on the RT thread.
- **Double-add precondition:** adding the same instance while it is still active in the tree is
undefined behaviour. Always `engine.remove(synth)` and allow at least one `processBlock` to
complete before re-adding the same instance.
- **Double-add is an error, not undefined behaviour:** adding the same instance while it is
still active in the tree throws ``EngineAddError/doubleAdd(engine:)``; adding an instance
already bound to a different engine throws ``EngineAddError/boundToOtherEngine(current:prior:)``.
Both are backed by a single-shot atomic CAS. To re-add an instance, `engine.remove(synth)` and
allow at least one `processBlock` to complete first.
@@ -395,7 +395,7 @@ let tendency = DemandTemporalTendency(
// Two voices with different seeds and rates — both share one DemandTemporalTendency each
class MelodyVoice: SynthesizerBase {
override func buildGraph() {
override func build() {
let trig = Impulse.Control(freq: 3.0)
let pitch = TimedDemand.Control(trig: trig, demand: tendency)
let env = EnvelopeGen.Audio(
@@ -1,8 +1,4 @@
# Value Sources for Non-RT Loops
@Metadata {
@PageKind(article)
}
# ``ValueComputable``
A uniform `(index, timestamp) -> Double` parameter source — constants, closures, envelopes, patterns — readable from any non-RT loop.
@@ -163,6 +163,15 @@ public let lyrebirdDefaultNumControlBuses: Int = 4096
/// `SynthesisEngine.init`. Must be a power of two.
public let lyrebirdDefaultEventQueueCapacity: Int = 1024
/// Default per-block scheduling cap when none is supplied to `SynthesisEngine.init`.
///
/// Bounds two things per audio block: the number of events that may *fire* within the
/// block, and the number of future-dated events the engine carries across a block
/// boundary (the look-ahead depth). Events beyond this cap are dropped rather than
/// triggering an RT-thread realloc. Raise it for dense granular / batch-scheduled work
/// where either the per-block onset density or the pre-scheduled look-ahead exceeds 256.
public let lyrebirdDefaultMaxEventsPerBlock: Int = 256
/// Default sample rate in Hz when none is supplied (used by `NRTJob`
/// default and convenience constructors). 44100 matches the standard
/// CD-quality rate; callers that require a specific rate should pass
+3 -3
View File
@@ -8,13 +8,13 @@
///
/// ```swift
/// let group = Group()
/// engine.add(group)
/// try engine.add(group)
///
/// let tone = SineTone()
/// engine.add(tone, position: .head(of: group)) // insert at front of group
/// try engine.add(tone, position: .head(of: group)) // insert at front of group
///
/// let lead = LeadSynth()
/// engine.add(lead, position: .after(tone)) // insert immediately after tone
/// try engine.add(lead, position: .after(tone)) // insert immediately after tone
/// ```
public enum NodePosition {
/// Insert at the front of the specified group (evaluated first within that group).
@@ -21,7 +21,7 @@ import Foundation
/// for _ in 0..<32 {
/// group.add(GrainVoice()) // any Synthesizer subclass
/// }
/// engine.add(group)
/// try engine.add(group)
/// ```
///
/// All 32 voices run concurrently. Each voice writes to its own scratch copy of the
+9 -5
View File
@@ -21,9 +21,12 @@ public protocol LiveParameterWrapper {
///
/// `ParameterNode` (in `Lyrebird`) and `UIParamNode` (in `LyrebirdUI`) both conform.
public protocol LiveParameterValue: AnyObject {
/// Atomically writes `newValue`. Main-thread-only — the `@Observable` registrar in
/// `UIParamNode.update(_:)` is not thread-safe. The RT audio thread picks up the new
/// value at the next (sub-)block boundary.
/// Writes `newValue`; the RT audio thread picks it up at the next (sub-)block boundary. The
/// threading contract depends on the conformer — see each override: `ParameterNode` is a
/// releasing atomic store (callable from any single control-side producer — main thread or a
/// `LyrebirdRoutine`/`LyrebirdTask` body), while `UIParamNode` is **main-thread-only** because
/// its value is `@Observable`-tracked, not atomic. Callers holding only `any LiveParameterValue`
/// must assume the stricter main-thread-only contract.
func _writeAtomicValue(_ newValue: Double)
/// The current parameter value. Read main-thread-side by `VoicePool` for
@@ -149,8 +152,9 @@ public struct LiveParam: LiveParameterWrapper {
/// The current parameter value.
///
/// - Getter: acquiring atomic load via `ParameterNode.value`.
/// - Setter: releasing atomic store via `ParameterNode.value` — safe to call from
/// the main thread; the RT thread picks up the change at the next block boundary.
/// - Setter: releasing atomic store via `ParameterNode.value` — call from the control side
/// (the main thread, or a `LyrebirdRoutine` / `LyrebirdTask` body); the RT thread picks up
/// the change at the next block boundary.
public var wrappedValue: Double {
get { projectedValue.value }
nonmutating set { projectedValue.value = newValue }
@@ -92,9 +92,10 @@ public final class ParameterNode: GeneratorBase, ControlGenerator, LiveParameter
///
/// - Getter: acquiring atomic load (`_atomicBits.load(ordering: .acquiring)`) — safe to
/// call from any thread.
/// - Setter: releasing atomic store (`_atomicBits.store(…, ordering: .releasing)`) — call
/// only from the main thread. The RT audio thread picks up the new value at the start of
/// the next block.
/// - Setter: releasing atomic store (`_atomicBits.store(…, ordering: .releasing)`) — call from
/// the **control side**: the main thread, or a `LyrebirdRoutine` / `LyrebirdTask` body (which
/// runs on its own thread). Keep it to a single control-side producer. The RT audio thread
/// picks up the new value at the start of the next block. Do not write from the RT thread.
public var value: Double {
get { Double(bitPattern: _atomicBits.load(ordering: .acquiring)) }
set { _atomicBits.store(newValue.bitPattern, ordering: .releasing) }
@@ -217,7 +218,7 @@ public final class ParameterNode: GeneratorBase, ControlGenerator, LiveParameter
/// }
///
/// let synth = MySynth()
/// engine.add(synth)
/// try engine.add(synth)
/// synth.$freq.source = LFOGen.Control(freq: 0.5, mul: 100, add: 440) // LFO
/// // ... later ...
/// synth.$freq.source = nil // revert to scalar
@@ -310,7 +311,11 @@ public final class ParameterNode: GeneratorBase, ControlGenerator, LiveParameter
/// Atomically writes `newValue`. Used by `SynthesizerBase.updateParameter(_:value:)`
/// to dispatch by-name writes without knowing the concrete projected-node type.
/// Main-thread-only.
///
/// Delegates to the ``value`` setter — a releasing atomic store — so it inherits that setter's
/// contract: callable from the control side (main thread, or a `LyrebirdRoutine`/`LyrebirdTask`
/// body), never the RT thread. (The `UIParamNode` conformer of `LiveParameterValue` is stricter
/// — main-thread-only — because its `value` is `@Observable`, not atomic.)
public func _writeAtomicValue(_ newValue: Double) {
value = newValue
}
@@ -183,6 +183,72 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
_nextWakeTime = Date()
}
// MARK: - Main-thread construction
/// Runs `work` on the main thread and returns its result, **blocking** the routine/task
/// body until it completes.
///
/// `SynthesizerBase` is `@MainActor`-isolated, but a routine/task body is `@Sendable` and
/// runs on its own background thread — so a body cannot construct a synthesizer directly.
/// Without this, every synth a body might add has to be pre-allocated outside the body and
/// captured (the `BufferDemos` idiom). `onMain` lifts that restriction: construct inside the
/// loop, so the *count* and *parameters* of the synths can depend on the body's own logic.
///
/// ```swift
/// LyrebirdTask.run(engine: engine) { ctx in
/// while ctx.now < 10.0 {
/// let grain: Grain = ctx.onMain { Grain(startPos: nextPos(), rate: nextRate()) }
/// ctx.add(grain) // async hop; grain self-frees via its envelope
/// try ctx.wait(seconds: 0.05) // drift-compensated as usual
/// }
/// }
/// ```
///
/// ## Cost and drift compensation
///
/// The main hop is synchronous, so the time `work` takes counts as work done between
/// `wait` calls — which ``wait(seconds:)`` already compensates for by shortening the next
/// sleep. As long as construction is shorter than the wait interval the schedule stays on
/// time; if it overruns, the sleep is skipped and the deficit is not carried forward.
///
/// Keep `work` short — it blocks both this body *and* the main thread. Build one synth, not
/// a batch. Note that `build()` (the DAG construction) does **not** run here: it runs later,
/// on main, inside `ctx.add`'s dispatched `engine.add`.
///
/// ## Requires a serviced main thread
///
/// - Important: Unlike ``add(_:)`` / ``schedule(_:at:)`` — which are fire-and-forget
/// `DispatchQueue.main.async` and merely *delay* if main is busy — `onMain` hops
/// **synchronously and without a timeout**. If the host process's main thread is never
/// serviced, this call blocks the body forever with no diagnostic.
///
/// Main is serviced in the normal cases: a GUI app's run loop, or a CLI caller parked on
/// ``LyrebirdTask/waitUntilComplete()`` / ``LyrebirdTask/run(engine:body:)``, which pump the
/// main run loop precisely so dispatched work lands. The hazard is a process that calls
/// ``LyrebirdTask/start(engine:)`` and then blocks main on something that is *not* a run loop
/// (a bare `Thread.sleep`, a semaphore wait): `ctx.add` would silently queue up, but `onMain`
/// will hang. Park on `waitUntilComplete()` instead.
///
/// Re-entering the calling thread is not a hazard: `lyrebirdRunMainActorMutation` branches on
/// `Thread.isMainThread` and runs `work` inline (no dispatch) when already on main, so `onMain`
/// is self-deadlock-free regardless of which thread calls it.
///
/// - Parameter work: Main-actor-isolated closure — typically a synthesizer initializer.
/// - Returns: Whatever `work` returns. The result need not be `Sendable`; the synchronous
/// hop is a full barrier, so the value is carried back without a data race.
public func onMain<T>(_ work: @MainActor () throws -> T) rethrows -> T {
let box: _OnMainResultBox<T> = _OnMainResultBox<T>()
// The shared bridge returns Void (a non-Sendable T cannot cross back through
// `DispatchQueue.sync` directly), so the result travels out via the box instead.
try lyrebirdRunMainActorMutation { box.value = try work() }
guard let result: T = box.value else {
// Unreachable: the bridge runs `work` synchronously before returning, so the box
// is always populated unless `work` threw (in which case `try` already exited).
preconditionFailure("onMain: main-actor work did not produce a result")
}
return result
}
// MARK: - Engine calls (dispatched to main thread)
public func add(_ synth: any Synthesizer) {
@@ -247,6 +313,86 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
}
}
// MARK: - Live parameters
/// Sets a live parameter to `value` — the `ParameterNode` projected by a synth's `@LiveParam`
/// (`synth.$someLiveParam`). The RT thread picks the value up at the next block.
///
/// Unlike ``add(_:)`` / ``remove(_:)`` (engine graph edits, which hop to the main thread), a
/// `ParameterNode` write goes straight to its lock-free atomic — so it runs inline on the
/// routine/task body's own thread with no dispatch. Capture the projected node on the main actor
/// first (`let time = synth.$reverbTime`), then drive it from the body:
///
/// ```swift
/// let time = reverbSynth.$reverbTime // ParameterNode, captured on the main actor
/// LyrebirdTask.run(engine: engine) { ctx in
/// ctx.add(reverbSynth)
/// try ctx.wait(beats: 2)
/// ctx.set(time, to: 8.0) // long tail
/// try ctx.wait(beats: 2)
/// ctx.set(time, to: 0.5) // short tail
/// }
/// ```
///
/// > `@UIParam` (`UIParamNode`) is **not** accepted: its value is `@Observable`-tracked and
/// > main-thread-only, so it can't be written from the routine/task's background thread. Update
/// > `@UIParam` from the main thread instead.
///
/// - Parameters:
/// - param: The `@LiveParam` node — `synth.$someLiveParam`.
/// - value: The new value; applied at the next audio block.
public func set(_ param: ParameterNode, to value: Double) {
param.value = value
}
/// Glides a live parameter from its current value to `target` over `seconds`, then lands exactly
/// on `target`. **Blocks** the routine/task body for the duration — like ``wait(seconds:)``, so it
/// sequences naturally with the body's other timed events.
///
/// The glide is produced by stepping the scalar at the body's poll granularity; the parameter
/// node's own per-block linear interpolation blends the steps into a continuous ramp on the RT
/// thread. No node source is installed, so a later ``set(_:to:)`` still takes effect immediately.
/// A non-positive `seconds` jumps straight to `target`.
///
/// ```swift
/// let cutoff = filter.$cutoff
/// LyrebirdTask.run(engine: engine) { ctx in
/// ctx.add(filter)
/// try ctx.ramp(cutoff, to: 8000, seconds: 3) // 3 s sweep, then continue
/// try ctx.wait(seconds: 1)
/// }
/// ```
///
/// - Parameters:
/// - param: The `@LiveParam` node — `synth.$someLiveParam`. Its current value is read once
/// (an atomic load) to seed the glide. (`@UIParam` is not accepted — see ``set(_:to:)``.)
/// - target: The value to arrive at.
/// - seconds: Glide duration in seconds.
/// - Throws: Rethrows if the body is stopped/cancelled mid-glide (via the internal ``wait(seconds:)``).
public func ramp(_ param: ParameterNode, to target: Double, seconds: Double) throws {
guard seconds > 0 else {
param.value = target
return
}
let start: Double = param.value
let stepSeconds: Double = LyrebirdRoutineContext.pollIntervalSeconds
let steps: Int = max(1, Int((seconds / stepSeconds).rounded()))
for i: Int in 1...steps {
let fraction: Double = Double(i) / Double(steps)
param.value = start + (target - start) * fraction
try wait(seconds: seconds / Double(steps))
}
// The final step (i == steps) already wrote `start + (target - start)`, which is `target`
// to within a rounding ULP; this makes the landing exact.
param.value = target
}
/// Glides a `@LiveParam` node to `target` over `beats` beats at the current ``tempo``.
/// See ``ramp(_:to:seconds:)``.
public func ramp(_ param: ParameterNode, to target: Double, beats: Double) throws {
try ramp(param, to: target, seconds: beats * 60.0 / tempo)
}
// MARK: - Private
/// Sleep until `target` wall-clock time, polling every ~10 ms.
@@ -292,6 +438,17 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
}
}
/// One-shot carrier that returns a (possibly non-`Sendable`) value from a synchronous
/// main-thread hop in ``LyrebirdRoutineContext/onMain(_:)``.
///
/// `@unchecked Sendable`: the value is written on the main thread and read on the calling
/// thread, but `lyrebirdRunMainActorMutation` performs the write inside a synchronous
/// `DispatchQueue.main.sync` (or inline when already on main). That hop is a full barrier —
/// the write happens-before the read, and the two threads never touch the box concurrently.
private final class _OnMainResultBox<T>: @unchecked Sendable {
var value: T?
}
/// Cross-thread argument carrier. `@unchecked Sendable` because engine calls are serialized
/// through the main-thread dispatch, which is the sole producer for `pendingQueue`.
private struct Args: @unchecked Sendable {
+1 -1
View File
@@ -50,7 +50,7 @@ public struct BeatPosition: Sendable, Hashable {
// MARK: - Factories
/// Absolute 0-based quarter beats (meter-free). Quantized to
/// ``Fraction/beatApproxDenominator``.
/// `Fraction.beatApproxDenominator`.
public static func quarters(_ q: Double) -> BeatPosition {
BeatPosition(kind: .quarters(fractionFromBeats(q)))
}
+2 -2
View File
@@ -23,7 +23,7 @@ import Foundation
/// - ``auto`` — Infer the appropriate clef from the part's pitch content at encode time.
/// Resolves to `.treble` or `.bass` based on the median MIDI pitch of the part's
/// pitched events (median < ``autoBassThresholdMidi`` → `.bass`, else → `.treble`).
/// `.auto` is the default for the ``Part(_:channel:clef:elements:)`` DSL constructor.
/// `.auto` is the default for the ``Part(_:channel:clef:keySignature:transpose:meterMap:offset:id:elements:)`` DSL constructor.
public enum Clef: Sendable, Hashable {
/// G clef, line 2.
@@ -46,7 +46,7 @@ public enum Clef: Sendable, Hashable {
/// Infer treble or bass from the part's pitch range at encode time.
///
/// At ``Score/toMusicXMLString(divisions:)`` time the median MIDI pitch of the
/// At ``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` time the median MIDI pitch of the
/// part's non-rest pitched notes is computed. If the median is below
/// ``autoBassThresholdMidi`` (57 — A3), `.bass` is chosen; otherwise `.treble`.
/// If the part has no pitched notes, `.treble` is chosen.
+2 -2
View File
@@ -24,7 +24,7 @@ public enum Dynamic: Hashable, Sendable {
/// No sound — velocity zero, printed as `n` in MusicXML.
///
/// Use `.niente` at the start or end of a crescendo/diminuendo (al niente /
/// dal niente) or as the initial/final point of a ``dynamicCurve:`` to indicate
/// dal niente) or as the initial/final point of a `dynamicCurve:` to indicate
/// silence at that position. The `<n/>` MusicXML child element is the
/// standard MusicXML 4.0 representation.
case niente
@@ -66,7 +66,7 @@ public enum Dynamic: Hashable, Sendable {
}
}
/// MIDI velocity `[0, 127]` derived from ``velocity`` × ``midiMaxVelocity``,
/// MIDI velocity `[0, 127]` derived from ``velocity`` × `midiMaxVelocity`,
/// rounded.
public var midiVelocity: UInt8 {
UInt8(min(Dynamic.midiMaxVelocity,
+1 -1
View File
@@ -25,7 +25,7 @@
///
/// ## MusicXML round-trip
///
/// ``Score/toMusicXMLString(divisions:)`` emits `<key><fifths>N</fifths><mode>major|minor</mode></key>`
/// ``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` emits `<key><fifths>N</fifths><mode>major|minor</mode></key>`
/// after `<divisions>` and before `<time>` in measure 1 of every part.
/// ``Score/fromMusicXML(data:)`` reads `<fifths>` and `<mode>` from the FIRST `<key>`
/// encountered in the document and restores the ``KeySignature`` on the parsed ``Score``.
@@ -276,7 +276,7 @@ extension Score {
/// the per-staff redundant-dynamic collapse in the multi-voice encoder path.
///
/// Two atoms that open at the same metric `onset` on the same `staff` share a
/// key; when ``toMusicXMLString(divisions:collapseRedundantDynamics:)`` collapse
/// key; when ``toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` collapse
/// is enabled, the second identical dynamic at that key is suppressed. The dict
/// is reset at the start of every measure, so a dynamic re-appearing in a later
/// bar is always emitted.
@@ -225,8 +225,8 @@ extension Score {
// MARK: - Constants
/// Default `<divisions>` (ticks per quarter note) for the MusicXML encoder,
/// the default value of ``toMusicXMLString(divisions:)`` /
/// ``toMusicXMLData(divisions:)``.
/// the default value of ``toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` /
/// ``toMusicXMLData(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)``.
///
/// This is a **serialization** default, not a core model concept — it is
/// public only so callers can reference the same default they would get by
+1 -1
View File
@@ -5,7 +5,7 @@
// SPDX-License-Identifier: MIT
/// A notation-only mark applied to a note or chord via the `marks:` parameter
/// on ``Note(_:dur:dyn:art:voice:tie:spanners:display:marks:)`` and the `Chord`
/// on ``Note(_:dur:dyn:art:voice:tie:spanners:display:marks:dynamicCurve:)`` and the `Chord`
/// family of DSL functions.
///
/// Marks are **emit-only**: they produce MusicXML output inside `<notations>`
+2 -2
View File
@@ -14,8 +14,8 @@ import Foundation
/// scaling separate from the note-type size attribute.
///
/// Set via ``NoteDisplay/size`` and applied through the `display:` parameter
/// of ``Note(_:dur:dyn:art:voice:tie:spanners:display:)`` or
/// ``Chord(_:dur:dyn:art:voice:tie:spanners:display:)``.
/// of ``Note(_:dur:dyn:art:voice:tie:spanners:display:marks:dynamicCurve:)`` or
/// `Chord`.
///
/// > Note: Note size is **emit-only** — ``Score/fromMusicXML(data:)`` does not
/// > parse the `size` attribute back into `NoteDisplay`.
+2 -2
View File
@@ -20,8 +20,8 @@ import Foundation
/// than the hidden notehead. `.hidden` has no such ambiguity.
///
/// Set via ``NoteDisplay/notehead`` and applied to note/chord elements through
/// the `display:` parameter of ``Note(_:dur:dyn:art:voice:tie:spanners:display:)``
/// or ``Chord(_:dur:dyn:art:voice:tie:spanners:display:)``.
/// the `display:` parameter of ``Note(_:dur:dyn:art:voice:tie:spanners:display:marks:dynamicCurve:)``
/// or `Chord`.
///
/// > Note: Notehead shapes are **emit-only** — ``Score/fromMusicXML(data:)``
/// > does not parse `<notehead>` back into `NoteDisplay`.
+1 -1
View File
@@ -63,7 +63,7 @@ public struct RepeatStructure: Sendable, Hashable {
/// `true` when there is nothing to emit — the common default.
///
/// When `isEmpty` is `true`, ``Score/toMusicXMLString(divisions:)`` emits zero
/// When `isEmpty` is `true`, ``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` emits zero
/// `<barline>` elements (byte-identical output to a score without any
/// `RepeatStructure`).
public var isEmpty: Bool {
+6 -6
View File
@@ -52,7 +52,7 @@ public struct Score: Sendable {
/// via ``ScorePart/meterMap``).
///
/// Defaults to a single-segment map built from ``timeSignature``. When you
/// supply a `meterMap` to ``init(bpm:timeSignature:meterMap:keySignature:repeats:tempoChanges:parts:)``,
/// supply a `meterMap` to ``init(bpm:timeSignature:meterMap:keySignature:repeats:tempoChanges:parts:rehearsalMarks:measureBarlines:pageLayout:)``,
/// ``timeSignature`` is derived from its ``MeterMap/initial`` signature.
///
/// The MusicXML encoder renders the full map: a fresh `<time>` at each
@@ -68,7 +68,7 @@ public struct Score: Sendable {
/// Repeat and volta-ending structure for this score.
///
/// Defaults to ``RepeatStructure/none`` (no repeat barlines, no endings).
/// When non-empty, ``Score/toMusicXMLString(divisions:)`` emits `<barline>`
/// When non-empty, ``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` emits `<barline>`
/// elements in every part's matching measures. ``ScorePart/flatten()`` is
/// **unaffected** — playback does not unfold repeats (notation-only).
public let repeats: RepeatStructure
@@ -93,7 +93,7 @@ public struct Score: Sendable {
/// Rehearsal marks keyed by global 1-based measure number.
///
/// Empty for scores assembled via the flat ``init(parts:)`` path. When a score
/// Empty for scores assembled via the flat `init(parts:)` path. When a score
/// is assembled from ``ScoreSection`` values, each section contributes one
/// entry: `rehearsalMarks[sectionFirstGlobalMeasure] = section.name`.
///
@@ -141,7 +141,7 @@ public struct Score: Sendable {
/// - tempoChanges: Mid-piece tempo changes. Defaults to `[]`.
/// - parts: Parts in document order.
/// - rehearsalMarks: Global measure → rehearsal-mark label. Defaults to `[:]`
/// (no marks). Populated automatically by the ``Score/init(sections:bpm:keySignature:)``
/// (no marks). Populated automatically by the ``Score/init(sections:bpm:timeSignature:keySignature:pageLayout:)``
/// family of initializers; rarely supplied manually.
/// - measureBarlines: Global measure → right-barline style. Defaults to `[:]`
/// (no overrides). Populated automatically by the section initializers from
@@ -198,7 +198,7 @@ public struct Score: Sendable {
/// DSL initializer.
///
/// See ``init(bpm:timeSignature:meterMap:keySignature:repeats:tempoChanges:parts:rehearsalMarks:pageLayout:)``
/// See ``init(bpm:timeSignature:meterMap:keySignature:repeats:tempoChanges:parts:rehearsalMarks:measureBarlines:pageLayout:)``
/// for parameter semantics.
public init(
bpm: Double = 120.0,
@@ -277,7 +277,7 @@ public struct Score: Sendable {
/// DSL initializer for section-based scores.
///
/// See ``init(sections:bpm:keySignature:)`` for parameter semantics.
/// See ``init(sections:bpm:timeSignature:keySignature:pageLayout:)`` for parameter semantics.
///
/// ```swift
/// // A score-level timeSignature applies to every section that does not set
+11 -11
View File
@@ -22,7 +22,7 @@ import Foundation
/// `normal × children's nominal-duration sum`. Ratios compose under nesting.
/// - ``voice(_:_:)`` — an independent polyphonic voice that overlays the part
/// from beat zero rather than advancing the outer cursor. Use multiple
/// `Voice(n) { … }` blocks at the top level of a ``Part`` to express
/// `Voice(n) { … }` blocks at the top level of a `Part` to express
/// multi-voice staves. The voice number (`≥ 1`) becomes the MusicXML
/// `<voice>` number and is used to partition atoms into separate `<backup>`-
/// delimited streams during encoding.
@@ -52,7 +52,7 @@ public indirect enum ScoreElement: Sendable {
/// A silent rest of the given duration.
///
/// Unlike ``note(_:duration:dynamic:articulation:voice:tie:)`` and
/// ``chord(_:duration:dynamic:articulation:voice:)``, a rest carries no
/// ``ScoreElement/chord(_:duration:dynamic:articulation:voice:tie:)``, a rest carries no
/// `voice`, `dynamic`, or `articulation` of its own — by design. A rest
/// inside a ``voice(_:_:)`` block takes that block's voice number from
/// context at encode time (a rest in `Voice(2){…}` is emitted with
@@ -99,7 +99,7 @@ public indirect enum ScoreElement: Sendable {
/// An independent polyphonic voice within a part.
///
/// Children are flattened with a fresh cursor starting at beat zero, so
/// multiple `Voice(n)` blocks in the same ``Part`` overlay each other
/// multiple `Voice(n)` blocks in the same `Part` overlay each other
/// rather than sequencing end-to-end. The outer part cursor is NOT
/// advanced by a `voice` block; ``ScorePart/lastBeat()`` takes the max
/// beat across all voices.
@@ -109,7 +109,7 @@ public indirect enum ScoreElement: Sendable {
/// case triggers the multi-voice MusicXML path (`<backup>` + per-voice
/// streams); single-voice parts emit the unchanged legacy output.
///
/// > Note: A ``tuplet(_:_:_:_:)`` nested *inside* a `voice` block has its
/// > Note: A ``ScoreElement/tuplet(actual:normal:normalType:children:)`` nested *inside* a `voice` block has its
/// > `<time-modification>` and `<tuplet>` bracket dropped on the multi-voice
/// > encode path — only the sounding duration (already scaled by the tuplet
/// > ratio) is preserved. The playback timing is exact; the visual tuplet
@@ -216,7 +216,7 @@ public indirect enum ScoreElement: Sendable {
/// A multi-staff block (grand staff, e.g. piano left + right hand).
///
/// A `staff` block groups elements that belong to a specific notated staff
/// number within the part. Multiple `Staff(n) { }` blocks in the same ``Part``
/// number within the part. Multiple `Staff(n) { }` blocks in the same `Part`
/// body are rendered simultaneously — each has its own cursor starting at beat
/// zero and overlays the part from that point (analogous to ``voice(_:_:)``
/// for polyphony).
@@ -345,7 +345,7 @@ public indirect enum ScoreElement: Sendable {
/// ```
///
/// For clean, non-overlapping slur spans prefer the block form
/// ``slur(_:)``; for hairpin blocks prefer ``Crescendo`` / ``Diminuendo``.
/// ``slur(_:)``; for hairpin blocks prefer `Crescendo` / `Diminuendo`.
///
/// Flatten transparency: a `spanned` wrapper produces the **same**
/// ``ScoreEvent`` list as the unwrapped inner element — span annotations
@@ -370,8 +370,8 @@ public indirect enum ScoreElement: Sendable {
/// are merged with any glyph from the note's `art:` parameter into a single
/// `<articulations>` block, deduplicated.
///
/// Constructed by ``Note(_:dur:dyn:art:voice:tie:spanners:display:marks:)`` /
/// ``Chord(_:dur:dyn:art:voice:tie:spanners:display:marks:)`` when `marks` is
/// Constructed by ``Note(_:dur:dyn:art:voice:tie:spanners:display:marks:dynamicCurve:)`` /
/// `Chord` when `marks` is
/// non-empty; an empty `marks:[]` produces the plain element (byte-identical).
///
/// > Note: `marks:` is **emit-only** — ``Score/fromMusicXML(data:)`` does not
@@ -423,16 +423,16 @@ public indirect enum ScoreElement: Sendable {
/// Build-time-resolved measure-fill marker.
///
/// At ``Score`` init time (or ``ScoreSection`` lowering), `FillMeasure` is
/// expanded into a concrete ``.rest(duration:)`` spanning the remaining beats
/// expanded into a concrete ``ScoreElement/rest(duration:)`` spanning the remaining beats
/// of the current measure under the part's effective ``MeterMap``. If the
/// beat cursor already sits exactly on a barline, no rest is inserted (the
/// element is a no-op). The note following a `FillMeasure` therefore starts
/// on the next downbeat in both flatten and the printed score.
///
/// **Supported positions:** top level of a ``Part`` and inside a ``Voice``
/// **Supported positions:** top level of a `Part` and inside a `Voice`
/// block (the voice's local cursor is used for the fill calculation).
///
/// **Not supported inside a ``Tuplet``:** a `fillMeasure` nested inside a
/// **Not supported inside a `Tuplet`:** a `fillMeasure` nested inside a
/// tuplet is left unresolved by the expander (tuplet durations are
/// context-dependent and cannot be bar-aligned). It will be treated as a
/// zero-span no-op by flatten and the encoder — it emits nothing but also
+11 -11
View File
@@ -22,7 +22,7 @@ import Foundation
/// - tie: When `true`, ties this note to the immediately-following same-pitch note.
/// The pair sounds as one sustained note of summed duration, but is notated as two tied
/// noteheads in MusicXML. Tie chains (A.tie→B.tie→C) merge all three into one event.
/// (Chords support ties too via ``Chord(_:dur:dyn:art:voice:tie:)``.) A `tie==true` note
/// (Chords support ties too via `Chord`.) A `tie==true` note
/// whose next element is not a same-pitch same-voice note is treated as untied. Defaults to `false`.
/// - spanners: Explicit span-boundary annotations to apply to this note. When non-empty
/// the note is wrapped in a ``ScoreElement/spanned(_:_:)`` element; when empty the plain
@@ -95,7 +95,7 @@ public func Note(
/// emits its own notation glyph. Use `marks:` to add extra notation-only glyphs.
/// - voice: Voice number for multi-voice staves. Defaults to `0`.
/// - tie: When `true`, ties this note to the immediately-following same-pitch note.
/// See ``Note(_:dur:dyn:art:voice:tie:)`` for full semantics. Defaults to `false`.
/// See ``Note(_:dur:dyn:art:voice:tie:spanners:display:marks:dynamicCurve:)`` for full semantics. Defaults to `false`.
/// - spanners: Explicit span-boundary annotations to apply to this note. When non-empty
/// the note is wrapped in a ``ScoreElement/spanned(_:_:)`` element; when empty the plain
/// note is returned unchanged (existing output is byte-identical). Defaults to `[]`.
@@ -160,7 +160,7 @@ public func Note(
/// emits its own notation glyph. Use `marks:` to add extra notation-only glyphs.
/// - voice: Voice number for multi-voice staves. Defaults to `0`.
/// - tie: When `true`, ties this note to the immediately-following same-pitch note.
/// See ``Note(_:dur:dyn:art:voice:tie:)`` for full semantics. Defaults to `false`.
/// See ``Note(_:dur:dyn:art:voice:tie:spanners:display:marks:dynamicCurve:)`` for full semantics. Defaults to `false`.
/// - spanners: Explicit span-boundary annotations to apply to this note. When non-empty
/// the note is wrapped in a ``ScoreElement/spanned(_:_:)`` element; when empty the plain
/// note is returned unchanged (existing output is byte-identical). Defaults to `[]`.
@@ -299,7 +299,7 @@ public func Chord(
/// - voice: Voice number for multi-voice staves. Defaults to `0`.
/// - tie: When `true`, ties this chord to the immediately-following chord
/// that has the **same pitch set** (order-insensitive) and the same voice.
/// See ``Chord(_:dur:dyn:art:voice:tie:)`` for full semantics.
/// See `Chord` for full semantics.
/// Defaults to `false`.
/// - spanners: Explicit span-boundary annotations to apply to this chord. When
/// non-empty the chord is wrapped in a ``ScoreElement/spanned(_:_:)`` element;
@@ -430,7 +430,7 @@ func tupletContentsMismatchWarning(
+ "triplet occupies the time of its `inTimeOf` value, not its note count.)"
}
/// Independent polyphonic voice within a ``Part``.
/// Independent polyphonic voice within a `Part`.
///
/// Each `Voice` block starts its own cursor at beat zero rather than continuing
/// from where the previous block left off. Multiple `Voice` blocks in the same
@@ -472,7 +472,7 @@ public func Voice(
/// with `<wedge type="crescendo"/>` and the last with `<wedge type="stop"/>`;
/// intermediate notes carry no extra markup.
///
/// Nested inside a ``Tuplet`` or ``Voice``: the wedge still marks the first and
/// Nested inside a `Tuplet` or `Voice`: the wedge still marks the first and
/// last atoms of the span, regardless of how many measures or tuplet groups they
/// span.
///
@@ -655,7 +655,7 @@ public func Pedal(_ kind: PedalKind) -> ScoreElement {
/// }
/// ```
///
/// The part's *initial* clef stays the ``Part(_:channel:clef:keySignature:transpose:_:)``
/// The part's *initial* clef stays the ``Part(_:channel:clef:keySignature:transpose:meterMap:offset:id:elements:)``
/// `clef:` argument (emitted in measure-1 attributes); `ClefChange` layers on top.
///
/// - Parameter clef: The clef to switch to. Must **not** be ``Clef/auto`` —
@@ -673,7 +673,7 @@ public func ClefChange(_ clef: Clef) -> ScoreElement {
/// barline of the part's effective meter.
///
/// `FillMeasure()` is resolved at ``Score`` init time into a concrete
/// ``.rest(duration:)`` equal to the beats remaining until the next barline.
/// ``ScoreElement/rest(duration:)`` equal to the beats remaining until the next barline.
/// If the cursor already sits exactly on a barline it is a no-op (no rest is
/// inserted). The element following a `FillMeasure()` therefore begins on the
/// next downbeat in both flatten output and the printed score.
@@ -696,7 +696,7 @@ public func ClefChange(_ clef: Clef) -> ScoreElement {
/// }
/// ```
///
/// **Limitations:** not supported inside a ``Tuplet`` (left unresolved →
/// **Limitations:** not supported inside a `Tuplet` (left unresolved →
/// treated as a zero-span no-op). Always assemble the part inside a ``Score``
/// to trigger expansion; a ``ScorePart`` flattened in isolation leaves
/// `FillMeasure` unresolved and it will be silently skipped.
@@ -714,8 +714,8 @@ public func FillMeasure() -> ScoreElement {
/// receives both start and stop on the same note.
///
/// For overlapping spans — e.g. a slur that begins on the same note where a
/// crescendo ends — use the per-note ``spanners:`` parameter on ``Note`` or
/// ``Chord`` instead (wraps the note in a ``ScoreElement/spanned(_:_:)`` block).
/// crescendo ends — use the per-note `spanners:` parameter on `Note` or
/// `Chord` instead (wraps the note in a ``ScoreElement/spanned(_:_:)`` block).
///
/// ```swift
/// Slur {
+5 -5
View File
@@ -17,11 +17,11 @@ public struct ScorePart: Sendable {
/// are stitched together by matching `id` values across sections — the same
/// instrument in two consecutive sections must carry the same `id` (even if its
/// `name` differs for display). When you author a ``ScorePart`` outside of a
/// ``ScoreSection`` context (the flat ``Score(parts:)`` path) the `id` has no
/// ``ScoreSection`` context (the flat `Score(parts:)` path) the `id` has no
/// structural role, but it is still stored and accessible.
///
/// Defaults to `name` when not explicitly supplied — so existing call sites
/// (``Part(_:channel:clef:elements:)``) have their `id` automatically derived
/// (``Part(_:channel:clef:keySignature:transpose:meterMap:offset:id:elements:)``) have their `id` automatically derived
/// from `name` and require no changes.
public let id: String
@@ -34,14 +34,14 @@ public struct ScorePart: Sendable {
/// The clef assigned to this part.
///
/// Used by ``Score/toMusicXMLString(divisions:)`` to emit the correct
/// Used by ``Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)`` to emit the correct
/// `<clef>` block in the first measure's `<attributes>`. When set to
/// ``Clef/auto``, the encoder infers `.treble` or `.bass` from the
/// part's median MIDI pitch at encode time.
///
/// Defaults to ``Clef/treble`` on direct construction so existing code
/// that builds ``ScorePart`` values directly is unaffected. The DSL
/// constructor ``Part(_:channel:clef:elements:)`` defaults to
/// constructor ``Part(_:channel:clef:keySignature:transpose:meterMap:offset:id:elements:)`` defaults to
/// ``Clef/auto`` so authored scores self-classify.
public let clef: Clef
@@ -113,7 +113,7 @@ public struct ScorePart: Sendable {
/// - name: Human-readable part name (e.g. "lead", "bass", "drums").
/// - channel: MIDI channel hint in `[0, 15]`. Defaults to `0`.
/// - clef: Clef for MusicXML encoding. Defaults to ``Clef/treble`` on direct
/// construction (the ``Part(_:channel:clef:keySignature:transpose:meterMap:elements:)``
/// construction (the ``Part(_:channel:clef:keySignature:transpose:meterMap:offset:id:elements:)``
/// DSL constructor defaults to ``Clef/auto`` instead).
/// - keySignature: Per-part key-signature override. `nil` (default) inherits
/// the score-level key. Notation-only.
@@ -9,7 +9,7 @@ import Foundation
/// Result-builder for composing ``ScorePart`` arrays inline at the
/// ``Score`` level.
///
/// Paired with the free-function DSL constructor ``Part(_:channel:clef:elements:)``.
/// Paired with the free-function DSL constructor ``Part(_:channel:clef:keySignature:transpose:meterMap:offset:id:elements:)``.
@resultBuilder
public enum ScorePartBuilder {
+1 -1
View File
@@ -11,7 +11,7 @@ import Foundation
/// meter, key, tempo changes, and repeat structure.
///
/// Sections are an **authoring layer** that lowers to the existing flat ``Score``
/// representation. Call ``Score/init(sections:bpm:keySignature:)`` (or the DSL
/// representation. Call ``Score/init(sections:bpm:timeSignature:keySignature:pageLayout:)`` (or the DSL
/// initializers) to assemble sections into a score. The lowering algorithm:
///
/// 1. Collects an ordered union of part `id` values across all sections (first-
+11 -11
View File
@@ -14,7 +14,7 @@ import Foundation
/// overloads, 0-based, matching ``ScoreEvent/beat``) or musical ``BeatPosition``
/// values resolved against a ``MeterMap`` (the `meter:` overloads).
///
/// The result is a flat `[ScoreElement]` that drops straight into a ``Part``.
/// The result is a flat `[ScoreElement]` that drops straight into a `Part`.
/// Because the score result-builders are non-throwing, bind the timeline to a
/// `let` before the `Part`:
///
@@ -58,13 +58,13 @@ public enum ScoreTimeline {
try fillCore(absoluteItems(placed), overlap: overlap)
}
/// Variadic convenience over ``fill(_:overlap:)``.
/// Variadic convenience over `fill(_:overlap:)`.
///
/// - Parameters:
/// - placed: `(beat, element)` pairs.
/// - overlap: How to resolve overlapping elements. Defaults to `.trap`.
/// - Returns: See ``fill(_:overlap:)``.
/// - Throws: See ``fill(_:overlap:)``.
/// - Returns: See `fill(_:overlap:)`.
/// - Throws: See `fill(_:overlap:)`.
public static func from(
_ placed: (beat: Double, element: ScoreElement)...,
overlap: ScoreTimelineOverlap = .trap
@@ -77,8 +77,8 @@ public enum ScoreTimeline {
/// - Parameters:
/// - placed: Map of absolute beat → element. Beats must be `>= 0`.
/// - overlap: How to resolve overlapping elements. Defaults to `.trap`.
/// - Returns: See ``fill(_:overlap:)``.
/// - Throws: See ``fill(_:overlap:)``.
/// - Returns: See `fill(_:overlap:)`.
/// - Throws: See `fill(_:overlap:)`.
public static func fill(
_ placed: [Double: ScoreElement],
overlap: ScoreTimelineOverlap = .trap
@@ -105,8 +105,8 @@ public enum ScoreTimeline {
/// - placed: `(BeatPosition, element)` pairs. Order does not matter.
/// - meter: The governing meter map. Defaults to constant `4/4`.
/// - overlap: How to resolve overlapping elements. Defaults to `.trap`.
/// - Returns: See ``fill(_:overlap:)``.
/// - Throws: See ``fill(_:overlap:)``.
/// - Returns: See `fill(_:overlap:)`.
/// - Throws: See `fill(_:overlap:)`.
public static func fill(
_ placed: [(BeatPosition, ScoreElement)],
meter: MeterMap = MeterMap(.fourFour),
@@ -121,7 +121,7 @@ public enum ScoreTimeline {
/// - placed: `(BeatPosition, element)` pairs.
/// - meter: The governing meter map. Defaults to constant `4/4`.
/// - overlap: How to resolve overlapping elements. Defaults to `.trap`.
/// - Returns: See ``fill(_:overlap:)``.
/// - Returns: See `fill(_:overlap:)`.
/// - Throws: See ``fill(_:meter:overlap:)``.
public static func from(
_ placed: (BeatPosition, ScoreElement)...,
@@ -139,9 +139,9 @@ public enum ScoreTimeline {
///
/// - Parameter placed: `(beat, voice, element)` triples. `voice >= 1`.
/// - Returns: A `[ScoreElement]` of `.voice` blocks (one per voice, ascending),
/// ready to drop into a multi-voice ``Part``.
/// ready to drop into a multi-voice `Part`.
/// - Throws: ``ScoreTimelineError/invalidVoice(voice:)`` for `voice < 1`;
/// otherwise see ``fill(_:overlap:)`` (per-voice).
/// otherwise see `fill(_:overlap:)` (per-voice).
public static func fillVoices(
_ placed: [(beat: Double, voice: Int, element: ScoreElement)]
) throws -> [ScoreElement] {
@@ -254,6 +254,39 @@ open class SynthesizerBase: Synthesizer {
/// point.
open func build() {}
// MARK: - Lifecycle
/// Begin a graceful release (typically post `gate = 0.0` so an envelope enters its
/// release phase). The default throws ``SynthesizerError/noGate``.
///
/// Declared here — rather than relying on the `Synthesizer` protocol extension default —
/// so subclasses genuinely `override` it and the call dispatches through the class
/// vtable. A protocol-extension default is bound statically at `SynthesizerBase`'s
/// conformance, so a subclass method would be invisible to every caller holding an
/// `any Synthesizer` — including ``Group/release(engine:)``, which cascades to its
/// children through exactly that existential.
///
/// Language-side only — never call from the RT audio thread.
///
/// - Parameter engine: The engine this synthesizer is bound to.
/// - Throws: ``SynthesizerError/noGate`` unless overridden.
open func release(engine: SynthesisEngine) throws {
throw SynthesizerError.noGate
}
/// Immediately remove this synthesizer from the node tree.
///
/// Posts a remove event at the current sample time; the synthesizer stops evaluating once
/// the RT thread applies it. Declared here for the same dispatch reason as
/// ``release(engine:)``.
///
/// Language-side only — never call from the RT audio thread.
///
/// - Parameter engine: The engine to remove this synthesizer from.
open func free(engine: SynthesisEngine) {
engine.remove(self)
}
/// Register a generator as a root output. Called from within build().
/// Typically the argument is an Out or ControlOut generator.
///
+1 -1
View File
@@ -20,7 +20,7 @@ import Foundation
///
/// ```swift
/// let group = Group()
/// engine.add(group)
/// try engine.add(group)
///
/// let pool = try VoicePool(
/// voiceCount: 8,
+2 -1
View File
@@ -285,7 +285,8 @@ public enum InteractiveShell {
print("""
Commands:
new <name> [--template <t>] Scaffold a new Lyrebird Swift Package
Templates: basic (default), demo, ui-demo, nrt, score
Templates: quickstart (fastest sound), basic (default),
demo, ui-demo, nrt, score
run [--release] Build and run the current project
export <name> [--to p] Export a Synthesizer template to a .swift file
install-templates [--force] Install Xcode file templates to user dir
+1
View File
@@ -197,6 +197,7 @@ struct LyrebirdCLIMain {
Commands:
new <name> [--template <t>] Scaffold a new Lyrebird project
SPM templates (open Package.swift in Xcode):
quickstart fastest path to sound (plays 10 s)
basic (default), demo, ui-demo, nrt, score
Xcode-project templates (build to .app or .appex):
macos-ui-xcode macOS @UIParam synth app
+56 -3
View File
@@ -10,6 +10,10 @@ import Foundation
/// Template style for a scaffolded Lyrebird project.
public enum ProjectTemplate: String, CaseIterable, Equatable {
/// The shortest path to sound: a one-oscillator `SineTone`, the engine, and a
/// `main` that plays a 440 Hz tone for ten seconds and exits. The fastest way
/// to hear Lyrebird after installing the CLI.
case quickstart = "quickstart"
/// Minimal engine setup with `CoreAudioDriver` and `RunLoop.main.run()`.
case basic = "basic"
/// Real-time demo: `SineTone` synthesizer with `@LiveParam` frequency and amplitude.
@@ -34,6 +38,8 @@ public enum ProjectTemplate: String, CaseIterable, Equatable {
/// Case-insensitive init from a raw string. Accepts hyphen-free aliases too.
public init?(string: String) {
switch string.lowercased() {
case "quickstart", "quick-start", "quick":
self = .quickstart
case "basic": self = .basic
case "demo": self = .demo
case "ui-demo", "uidemo", "ui_demo": self = .uiDemo
@@ -58,7 +64,7 @@ public enum ProjectTemplate: String, CaseIterable, Equatable {
/// SwiftPM can express.
public var shipsXcodeProject: Bool {
switch self {
case .basic, .demo, .uiDemo, .nrt, .score: return false
case .quickstart, .basic, .demo, .uiDemo, .nrt, .score: return false
case .macosUIXcode, .iosUI, .auv3: return true
}
}
@@ -303,7 +309,7 @@ public enum ProjectScaffolder {
case .auv3:
try writeAUv3Files(name: name, projectRoot: projectRoot,
lyrebirdPath: lyrebirdPath, fm: fm)
case .basic, .demo, .uiDemo, .nrt, .score:
case .quickstart, .basic, .demo, .uiDemo, .nrt, .score:
// Unreachable — shipsXcodeProject filters these out at dispatch.
try? fm.removeItem(atPath: projectRoot)
throw Error.fileSystemError(
@@ -349,6 +355,8 @@ public enum ProjectScaffolder {
static let scaffoldDefaultOutputChannels: Int = 2
static let scaffoldDefaultInputChannels: Int = 2
static let scaffoldDefaultNRTDuration: Double = 4.0
/// Seconds the `quickstart` template plays its sine tone before exiting.
static let scaffoldQuickstartDurationSeconds: Double = 10.0
// MARK: - Package manifest
@@ -375,7 +383,7 @@ public enum ProjectScaffolder {
// the dep is local or remote.
let targetDeps: String
switch template {
case .basic, .demo, .nrt, .score:
case .quickstart, .basic, .demo, .nrt, .score:
targetDeps = #""Lyrebird""#
case .uiDemo:
targetDeps = #""Lyrebird", .product(name: "LyrebirdUI", package: "Lyrebird")"#
@@ -432,6 +440,7 @@ public enum ProjectScaffolder {
template: ProjectTemplate = .basic
) -> String {
switch template {
case .quickstart: return mainSwiftQuickstart(name: name)
case .basic: return mainSwiftBasic(name: name)
case .demo: return mainSwiftDemo(name: name)
case .uiDemo: return mainSwiftUIDemo(name: name)
@@ -445,6 +454,50 @@ public enum ProjectScaffolder {
}
}
// MARK: quickstart (the shortest path to sound)
private static func mainSwiftQuickstart(name: String) -> String {
"""
// \(name) — quickstart: the shortest path to sound.
//
// Run it: lyrebird run (or `swift run`)
// You'll hear a 440 Hz sine for \(Int(scaffoldQuickstartDurationSeconds)) seconds, then it exits.
import Foundation
import LyrebirdSynth
// A Synthesizer is a graph built in `build()`. This one is a single sine
// oscillator, scaled down so it isn't harsh, centred to both speakers
// with Pan2 and written to output bus 0 (left) / bus 1 (right).
final class SineTone: SynthesizerBase {
override func build() {
output(bus: 0, source: Pan2(input: OscSin.Audio(freq: 440.0) * 0.2))
}
}
do {
// The engine owns Core Audio and runs the graph on the RT thread.
let engine = SynthesisEngine(
blockSize: \(scaffoldDefaultBlockSize),
sampleRate: \(scaffoldDefaultSampleRate),
numOutputChannels: \(scaffoldDefaultOutputChannels),
numInputChannels: 0,
driver: CoreAudioDriver()
)
try engine.start() // opens the output device
try engine.add(SineTone()) // starts sounding immediately
print("\(name): playing a 440 Hz sine for \(Int(scaffoldQuickstartDurationSeconds)) seconds…")
Thread.sleep(forTimeInterval: \(scaffoldQuickstartDurationSeconds))
engine.stop() // closes the device
print("Done.")
} catch {
fatalError("Lyrebird quickstart failed to start: \\(error)")
}
"""
}
// MARK: basic
private static func mainSwiftBasic(name: String) -> String {
@@ -21,9 +21,9 @@ A `struct` property wrapper that is simultaneously:
import LyrebirdUI
class MySynth: SynthesizerBase {
@UIParam var amplitude: LyrebirdFloat = 0.5
@UIParam var frequency: LyrebirdFloat = 440.0
@UIParam var pan: LyrebirdFloat = 0.0
@UIParam var amplitude: Double = 0.5
@UIParam var frequency: Double = 440.0
@UIParam var pan: Double = 0.0
override func build() {
let osc = OscSin.Audio(freq: $frequency)
@@ -221,9 +221,9 @@ import LyrebirdSynth
import LyrebirdUI
final class SineTone: SynthesizerBase {
@UIParam var frequency: LyrebirdFloat = 440.0
@UIParam var amplitude: LyrebirdFloat = 0.25
@UIParam var pan: LyrebirdFloat = 0.0
@UIParam var frequency: Double = 440.0
@UIParam var amplitude: Double = 0.25
@UIParam var pan: Double = 0.0
override func build() {
let osc = OscSin.Audio(freq: $frequency)
@@ -245,7 +245,12 @@ final class SineController {
}
func toggle() {
isPlaying ? engine.remove(synth) : engine.add(synth)
if isPlaying {
engine.remove(synth)
} else {
// engine.add is throwing; toggle() is not, so handle the error here.
do { try engine.add(synth) } catch { print("[Lyrebird] engine.add failed: \(error)") }
}
isPlaying.toggle()
}
}
@@ -13,9 +13,9 @@ so any parameter controllable from code is automatically controllable from a GUI
import LyrebirdUI
class MySynth: SynthesizerBase {
@UIParam var frequency: LyrebirdFloat = 440.0
@UIParam var amplitude: LyrebirdFloat = 0.5
@UIParam var pan: LyrebirdFloat = 0.0
@UIParam var frequency: Double = 440.0
@UIParam var amplitude: Double = 0.5
@UIParam var pan: Double = 0.0
override func build() {
let osc = OscSin.Audio(freq: $frequency)