Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6da3615707 | |||
| a175c437de | |||
| 56726223f6 |
@@ -46,7 +46,7 @@ These guards catch classes of regression that **`swift build` / `swift test` str
|
||||
|
||||
**Golden values need a test, not a guard.** A typecheck proves an example still *compiles*; it cannot see a documented result drift. Where a doc asserts concrete output (`// → 0.744, 0.046, …`), pin it with a test — `DistributionKindGoldenValueTests` and `_DocTheorySnippetCheckTests` are the two instances. This is not optional pedantry: three of the four `DistributionKind` sequences had silently drifted, and their fences also passed a `seed:` argument to a type that has no such parameter.
|
||||
|
||||
`check-doc-snippets.sh` checks the fences recorded in `scripts/doc-snippets-manifest.txt` (currently **426** of 1458). That set is produced by asking the **compiler** which fences compile — `--classify` — never by hand-annotating fences. A fence that compiles under no preamble self-excludes, which is how iOS-only examples, `Package.swift` snippets and pseudo-code drop out with no skip list. **Coverage is therefore partial by construction**: a fragment like `try engine.add(MySynth())`, which needs both an `engine` and a `MySynth` in scope, is *not* checked. The fix for an important uncovered example is to make it self-contained in the doc — which is better documentation anyway — not to grow the preamble table. Re-run `--classify` after adding examples or deliberately changing what is checkable.
|
||||
`check-doc-snippets.sh` checks the fences recorded in `scripts/doc-snippets-manifest.txt` (currently **578** of 1584). That set is produced by asking the **compiler** which fences compile — `--classify` — never by hand-annotating fences. A fence that compiles under no preamble self-excludes, which is how iOS-only examples, `Package.swift` snippets and pseudo-code drop out with no skip list. **Coverage is therefore partial by construction**: a fragment like `try engine.add(MySynth())`, which needs both an `engine` and a `MySynth` in scope, is *not* checked. The fix for an important uncovered example is to make it self-contained in the doc — which is better documentation anyway — not to grow the preamble table. Re-run `--classify` after adding examples or deliberately changing what is checkable.
|
||||
|
||||
## Task → Doc Map
|
||||
|
||||
@@ -76,6 +76,7 @@ These guards catch classes of regression that **`swift build` / `swift test` str
|
||||
- Node tree / Group nesting / bus routing → `docs/protocols/node-tree.md`
|
||||
- Routines / tasks / clock / MIDI / OSC → `docs/tooling/routine-task.md`
|
||||
- `Pattern<T>` factory catalog (sequence, series, geometric, uniformRandom, brownian, gaussian, cauchy, beta, shuffle, nonRepeatingRandom, weightedRandom, closure, repeating, limit, drop, stutter, switching, concatenate, roundRobin, tuple, interleave, map, filter, reject, accumulate, difference, wrap, clip, round, smooth) → `docs/tooling/routine-task.md` (§ Pattern Factory Reference) + `Sources/Lyrebird/Lyrebird.docc/RoutineTask.md`
|
||||
- Event patterns — `EventPattern` (SC `Pbind`: typed keyPath bindings → voice `@LiveParam`s, dur/legato scheduling, `EventGated` gate note-off or `EventSustainAware` self-timed release; non-blocking gate close via `LyrebirdRoutineContext.set(_:to:afterBeats:)`), `MonoEventPattern` (SC `Pmono`/`PmonoArtic`: one reused voice, params updated per event, optional `EventRetriggerable` re-strike), `ParallelEventPattern` (SC `Ppar`: heterogeneous `EventPatternPlayable` children started together, one merged `EventPatternHandle`; `add` = enter-with-group, `addAfter(beats:)` = staggered entry via `startAfterBeats` lead-in), `EventConductor` (live, clock-driven ensemble — thread-safe `add(_:quantize:)` from UI/OSC/MIDI while running, returns an `EventConductorHandle` for per-part stop; clock-deferred entry quantised by `EventQuantum` against the conductor's own clock, tempo-independent; patterns keep own timing after entry), `EventConductorHandle` (stop one part: cancels if pending, stops if playing), `EventPatternHandle` → `docs/tooling/routine-task.md` (§ EventPattern / § EventConductor) + `Sources/Lyrebird/Patterns/Events/`
|
||||
- MIDI clock sync (`MIDIClockFollower`) → `docs/tooling/midi-clock-sync.md`
|
||||
- Linux MIDI (`MIDI` via ALSA sequencer — `MIDI/ALSAMIDI.swift`, `ALSASeqMIDIEvent` mapping; needs CALSA/libasound) → `Sources/Lyrebird/MIDI/ALSAMIDI.swift`
|
||||
- Linux OSC (`OSCClient` / `OSCServer` POSIX-UDP transport off Apple, `OSCServerError`; codec unchanged) → `Sources/Lyrebird/OSC/OSCServer.swift`
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
/* Begin PBXBuildFile section */
|
||||
0306C7C02FAC451300952EAF /* GVerbTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7BF2FAC451300952EAF /* GVerbTest.swift */; };
|
||||
0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7C12FAC45F200952EAF /* ReverbDemo.swift */; };
|
||||
631D4C5B1150427CB8D15210 /* EventPatternDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99B83EC83F6C48D98441D7F7 /* EventPatternDemo.swift */; };
|
||||
035A2F422FAA4F67007F6289 /* PercPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F3F2FAA4F67007F6289 /* PercPitchShift.swift */; };
|
||||
035A2F432FAA4F67007F6289 /* PercSpectralPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F412FAA4F67007F6289 /* PercSpectralPitchShift.swift */; };
|
||||
035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F492FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift */; };
|
||||
@@ -26,6 +27,7 @@
|
||||
/* Begin PBXFileReference section */
|
||||
0306C7BF2FAC451300952EAF /* GVerbTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GVerbTest.swift; sourceTree = "<group>"; };
|
||||
0306C7C12FAC45F200952EAF /* ReverbDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReverbDemo.swift; sourceTree = "<group>"; };
|
||||
99B83EC83F6C48D98441D7F7 /* EventPatternDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventPatternDemo.swift; sourceTree = "<group>"; };
|
||||
035A2F3E2FAA4F67007F6289 /* PercBufferRead.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercBufferRead.swift; sourceTree = "<group>"; };
|
||||
035A2F3F2FAA4F67007F6289 /* PercPitchShift.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercPitchShift.swift; sourceTree = "<group>"; };
|
||||
035A2F402FAA4F67007F6289 /* PercPlayBuffer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercPlayBuffer.swift; sourceTree = "<group>"; };
|
||||
@@ -56,6 +58,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
0306C7C12FAC45F200952EAF /* ReverbDemo.swift */,
|
||||
99B83EC83F6C48D98441D7F7 /* EventPatternDemo.swift */,
|
||||
035B00032FAB0000007F0001 /* DemoProtocol.swift */,
|
||||
035B00042FAB0000007F0001 /* BufferDemos.swift */,
|
||||
);
|
||||
@@ -207,6 +210,7 @@
|
||||
035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */,
|
||||
035A2F442FAA4F67007F6289 /* PercBufferRead.swift in Sources */,
|
||||
0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */,
|
||||
631D4C5B1150427CB8D15210 /* EventPatternDemo.swift in Sources */,
|
||||
035A2F452FAA4F67007F6289 /* PercPlayBuffer.swift in Sources */,
|
||||
C1A000000000000000000007 /* main.swift in Sources */,
|
||||
C1A000000000000000000016 /* SineTone.swift in Sources */,
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
// EventPatternDemo.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Demonstrates ``EventPattern`` — Lyrebird's event-driven player: bound value patterns drive a
|
||||
/// fresh self-freeing voice per event, played as a dur/legato-timed stream.
|
||||
///
|
||||
/// Also shows two patterns running together via ``ParallelEventPattern``: a lead phrase and a
|
||||
/// bass line that enters a few beats in on the same beat grid, with a single
|
||||
/// ``EventPatternHandle/waitUntilComplete(releasePadding:)`` blocking until the longer of the two
|
||||
/// finishes.
|
||||
final class EventPatternDemo: DemoProtocol {
|
||||
|
||||
private let engine: SynthesisEngine
|
||||
|
||||
init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
}
|
||||
|
||||
/// A gated voice (``EventGated``): a sine through an `EnvelopeGen` whose gate holds it at full
|
||||
/// level while the note sounds, then plays a release and frees the voice via
|
||||
/// `doneAction: .freeNode` when `EventPattern` closes the gate at the note's sustain. No
|
||||
/// external removal, so the release is never hard-cut — nothing to tune, no click.
|
||||
private final class BlipVoice: SynthesizerBase, EventGated {
|
||||
/// Envelope release length in seconds — how long a note rings after its gate closes.
|
||||
/// Exposed so the demo can let the final note's tail finish before stopping the engine.
|
||||
nonisolated static let releaseSeconds: Double = 0.3
|
||||
/// Envelope attack length in seconds.
|
||||
nonisolated static let attackSeconds: Double = 0.01
|
||||
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.2
|
||||
@LiveParam var gate: Double = 1.0 // open by default so the attack fires on add
|
||||
|
||||
var eventGate: ParameterNode { $gate }
|
||||
|
||||
override func build() {
|
||||
// `releaseNode: 1` holds at `levels[1]` (full) while the gate is open; when the gate
|
||||
// drops to 0 the generator plays segment 1 (the release to 0) and then self-frees.
|
||||
let envelope: Envelope = Envelope(
|
||||
levels: [0.0, 1.0, 0.0],
|
||||
durations: [BlipVoice.attackSeconds, BlipVoice.releaseSeconds],
|
||||
curves: [.welch, .welch],
|
||||
releaseNode: 1
|
||||
)
|
||||
let shaped: EnvelopeGen.Audio = EnvelopeGen.Audio(
|
||||
envelope: envelope,
|
||||
gate: $gate,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
let source: OscSin.Audio = OscSin.Audio(freq: $freq, mul: $amp)
|
||||
output(bus: 0, source: source * shaped)
|
||||
}
|
||||
}
|
||||
|
||||
func runDemo() {
|
||||
print("\n── EventPattern demo ──")
|
||||
|
||||
let tempoBPM: Double = 132.0
|
||||
|
||||
// Pattern 1 — the lead: a short A-minor-pentatonic phrase, written as named pitches rather
|
||||
// than raw Hz (equivalent MIDI form: `Pitch.midi(69).frequency`, etc.), played three times.
|
||||
let phrase: [Pitch] = [
|
||||
.named(.a, 4), .named(.c, 5), .named(.d, 5), .named(.e, 5),
|
||||
.named(.g, 5), .named(.e, 5), .named(.d, 5), .named(.c, 5),
|
||||
]
|
||||
let leadFreqs: [Double] = phrase.compactMap(\.frequency)
|
||||
let lead: EventPattern<BlipVoice> = EventPattern(make: { BlipVoice() })
|
||||
.bind(\.freq, .sequence(leadFreqs, repeats: 1))
|
||||
.bind(\.amp, .uniformRandom(low: 0.15, high: 0.3))
|
||||
.dur(.sequence([0.25, 0.25, 0.25, 0.5]))
|
||||
.legato(0.8)
|
||||
.tempo(tempoBPM)
|
||||
.repeats(3)
|
||||
|
||||
// Pattern 2 — a bass line that enters `leadInBeats` after the lead and outlasts it.
|
||||
// There is no cross-pattern clock: `ParallelEventPattern` launches both children from the
|
||||
// one `play` call, so they share a start instant, and at the SAME tempo they share a beat
|
||||
// grid. `addAfter(beats:)` staggers the bass's entry on that grid — the bass simply waits
|
||||
// `leadInBeats` beats before its first note.
|
||||
let leadInBeats: Double = 2.0
|
||||
let bassPhrase: [Pitch] = [.named(.a, 2), .named(.a, 2), .named(.g, 2), .named(.e, 2)]
|
||||
let bassFreqs: [Double] = bassPhrase.compactMap(\.frequency)
|
||||
let bass: EventPattern<BlipVoice> = EventPattern(make: { BlipVoice() })
|
||||
.bind(\.freq, .sequence(bassFreqs, repeats: 1))
|
||||
.bind(\.amp, .uniformRandom(low: 0.2, high: 0.3))
|
||||
.dur(.sequence([1.0]))
|
||||
.legato(0.9)
|
||||
.tempo(tempoBPM)
|
||||
.repeats(1)
|
||||
|
||||
// Start both together, staggering the bass two beats in, and control them as one handle.
|
||||
let ensemble: ParallelEventPattern = ParallelEventPattern()
|
||||
ensemble.add(lead)
|
||||
ensemble.addAfter(beats: leadInBeats, eventPattern: bass)
|
||||
let handle: EventPatternHandle = ensemble.play(on: engine)
|
||||
|
||||
// `waitUntilComplete` blocks until EVERY child task has finished — so it waits for the
|
||||
// longer-running bass, not just the lead. `releasePadding` then lets the final note's
|
||||
// envelope release ring out before `main.swift` stops the engine — without it,
|
||||
// `engine.stop()` would cut the tail (an end-of-phrase click).
|
||||
handle.waitUntilComplete(releasePadding: BlipVoice.releaseSeconds)
|
||||
print("\nEventPattern demo complete.")
|
||||
}
|
||||
}
|
||||
@@ -7,11 +7,18 @@
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// ── Demo selector ─────────────────────────────────────────────────────────────
|
||||
// Change `demo` to `.buffer`, `.reverb`, or `.eventPattern` to switch demos.
|
||||
private enum Demo { case buffer, reverb, eventPattern }
|
||||
private let demo: Demo = .eventPattern
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
// `makeDefaultAudioDriver()` selects the platform backend — Core Audio on Apple,
|
||||
// ALSA on Linux (needs libasound) — so the demo builds and runs on both.
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 44100,
|
||||
controlBlockSize: 64,
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 2,
|
||||
driver: makeDefaultAudioDriver()
|
||||
@@ -24,7 +31,10 @@ do {
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// BufferDemos(engine: engine).runDemo()
|
||||
ReverbDemo(engine: engine).runDemo()
|
||||
switch demo {
|
||||
case .buffer: BufferDemos(engine: engine).runDemo()
|
||||
case .reverb: ReverbDemo(engine: engine).runDemo()
|
||||
case .eventPattern: EventPatternDemo(engine: engine).runDemo()
|
||||
}
|
||||
|
||||
engine.stop()
|
||||
|
||||
@@ -15,7 +15,7 @@ import PackageDescription
|
||||
// macOS: swift run LyrebirdGUIDemo (or open the thin Xcode project)
|
||||
// Linux: swift run LyrebirdGUIDemo (needs libgtk-4-dev + libasound2-dev)
|
||||
//
|
||||
// Select the synth with LYREBIRD_DEMO=vector (default) or LYREBIRD_DEMO=sine.
|
||||
// Select the synth with LYREBIRD_DEMO=vector (default), sine, or conductor.
|
||||
let package = Package(
|
||||
name: "LyrebirdGUIDemo",
|
||||
platforms: [.macOS(.v15)],
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// • Linux — a GTK4 `App`/`WindowGroup` scene run by `GTK4Backend`.
|
||||
//
|
||||
// Run either with `swift run LyrebirdGUIDemo`. Pick the synth with
|
||||
// `LYREBIRD_DEMO=vector` (default) or `LYREBIRD_DEMO=sine`.
|
||||
// `LYREBIRD_DEMO=vector` (default), `sine`, or `conductor`.
|
||||
//
|
||||
// `@ViewBuilder` and the window hosts come from SwiftUI on macOS and from
|
||||
// SwiftOpenUI (re-exported through `LyrebirdUI`) on Linux — hence the single
|
||||
@@ -30,7 +30,7 @@ import LyrebirdGUIDemoKit
|
||||
let selection: DemoSelection = DemoSelection.fromEnvironment()
|
||||
|
||||
private let demoBlockSize: Int = 512
|
||||
private let demoSampleRate: Double = 44_100.0
|
||||
private let demoSampleRate: Double = 48_000.0
|
||||
private let demoScopeBufferSize: Int = 2048
|
||||
|
||||
// Oscilloscope tap on the stereo output buses. Must be set before `start()`.
|
||||
@@ -102,6 +102,8 @@ func demoContent() -> some View {
|
||||
scope: demoScope,
|
||||
engine: statusEngine
|
||||
)
|
||||
} else if selection == .conductor {
|
||||
ConductorDemoView(scope: demoScope, engine: statusEngine)
|
||||
} else {
|
||||
SineToneDemoView(
|
||||
frequencyNode: sineFreq,
|
||||
@@ -117,11 +119,14 @@ func demoContent() -> some View {
|
||||
// Start the engine and add the selected synth. `engine.start()` / `add` are
|
||||
// @MainActor; main.swift's top level is main-actor isolated, so these are direct
|
||||
// calls. On a build with no live backend the GUI still runs (silently).
|
||||
do {
|
||||
// The conductor demo is the exception: its view starts and stops the engine itself.
|
||||
if selection != .conductor {
|
||||
do {
|
||||
try demoEngine.start()
|
||||
try demoEngine.add(activeSynth)
|
||||
} catch {
|
||||
} catch {
|
||||
print("[Lyrebird] demo engine setup failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
if !isLiveAudioAvailable {
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
// ConductorDemoController.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Owns the engine lifecycle, the ``EventConductor`` and the on/off state of the two parts for
|
||||
/// ``ConductorDemoView``.
|
||||
///
|
||||
/// A pattern is single-shot, so each toggle-on builds a fresh ``EventPattern`` and hands it to the
|
||||
/// conductor, entering on the next beat. ``EventConductor/add(_:quantize:)`` returns an
|
||||
/// ``EventConductorHandle``; toggling a part off calls ``EventConductorHandle/stop()`` on its
|
||||
/// handle, which releases that part alone (its gated voices ring out) without touching the other.
|
||||
///
|
||||
/// `@unchecked Sendable`: main-thread-confined — every method is called from a button action.
|
||||
@Observable
|
||||
final class ConductorDemoController: @unchecked Sendable {
|
||||
|
||||
/// Shared tempo of the conductor and both parts, in beats per minute.
|
||||
private static let tempoBPM: Double = 120.0
|
||||
|
||||
/// Top part: events per beat grid, in beats.
|
||||
private static let topEventBeats: Double = 0.5
|
||||
|
||||
/// Bottom part: one event per beat.
|
||||
private static let bottomEventBeats: Double = 1.0
|
||||
|
||||
/// Sustain fraction of each event's duration.
|
||||
private static let legato: Double = 0.8
|
||||
|
||||
/// Top part: A-minor pentatonic phrase.
|
||||
private static let topPhrase: [Pitch] = [
|
||||
.named(.a, 4), .named(.c, 5), .named(.d, 5), .named(.e, 5),
|
||||
.named(.g, 5), .named(.e, 5), .named(.d, 5), .named(.c, 5),
|
||||
]
|
||||
|
||||
/// Bottom part: a simple root-fifth bass figure.
|
||||
private static let bottomPhrase: [Pitch] = [
|
||||
.named(.a, 2), .named(.a, 2), .named(.g, 2), .named(.e, 2),
|
||||
]
|
||||
|
||||
private static let topAmpLow: Double = 0.10
|
||||
private static let topAmpHigh: Double = 0.18
|
||||
private static let bottomAmpLow: Double = 0.20
|
||||
private static let bottomAmpHigh: Double = 0.28
|
||||
|
||||
private let engine: SynthesisEngine
|
||||
|
||||
/// `true` while the engine (and conductor) is running.
|
||||
private(set) var engineRunning: Bool = false
|
||||
|
||||
/// `true` while the top part is switched on.
|
||||
private(set) var topOn: Bool = false
|
||||
|
||||
/// `true` while the bottom part is switched on.
|
||||
private(set) var bottomOn: Bool = false
|
||||
|
||||
@ObservationIgnored private var conductor: EventConductor?
|
||||
@ObservationIgnored private var topHandle: EventConductorHandle?
|
||||
@ObservationIgnored private var bottomHandle: EventConductorHandle?
|
||||
|
||||
init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
}
|
||||
|
||||
/// Starts the engine and a fresh conductor, or stops both (releasing any playing parts).
|
||||
func toggleEngine() {
|
||||
if engineRunning {
|
||||
topHandle?.stop()
|
||||
bottomHandle?.stop()
|
||||
conductor?.stop()
|
||||
conductor = nil
|
||||
topHandle = nil
|
||||
bottomHandle = nil
|
||||
topOn = false
|
||||
bottomOn = false
|
||||
MainActor.assumeIsolated { engine.stop() }
|
||||
engineRunning = false
|
||||
} else {
|
||||
do {
|
||||
try MainActor.assumeIsolated { try engine.start() }
|
||||
} catch {
|
||||
print("[Lyrebird] engine.start failed: \(error)")
|
||||
return
|
||||
}
|
||||
let newConductor: EventConductor = EventConductor(tempo: ConductorDemoController.tempoBPM)
|
||||
MainActor.assumeIsolated { newConductor.start(on: engine) }
|
||||
conductor = newConductor
|
||||
engineRunning = true
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggles the top (melodic) part. Entering is quantised to the next beat; stopping releases it
|
||||
/// immediately through its handle.
|
||||
func toggleTop() {
|
||||
guard let active: EventConductor = conductor else { return }
|
||||
if topOn {
|
||||
topHandle?.stop()
|
||||
topHandle = nil
|
||||
topOn = false
|
||||
} else {
|
||||
let pattern: EventPattern<ConductorDemoVoice> = makePattern(
|
||||
phrase: ConductorDemoController.topPhrase,
|
||||
eventBeats: ConductorDemoController.topEventBeats,
|
||||
ampLow: ConductorDemoController.topAmpLow,
|
||||
ampHigh: ConductorDemoController.topAmpHigh
|
||||
)
|
||||
topHandle = active.add(pattern, quantize: .nextBeat)
|
||||
topOn = true
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggles the bottom (bass) part. Entering is quantised to the next beat; stopping releases it
|
||||
/// immediately through its handle.
|
||||
func toggleBottom() {
|
||||
guard let active: EventConductor = conductor else { return }
|
||||
if bottomOn {
|
||||
bottomHandle?.stop()
|
||||
bottomHandle = nil
|
||||
bottomOn = false
|
||||
} else {
|
||||
let pattern: EventPattern<ConductorDemoVoice> = makePattern(
|
||||
phrase: ConductorDemoController.bottomPhrase,
|
||||
eventBeats: ConductorDemoController.bottomEventBeats,
|
||||
ampLow: ConductorDemoController.bottomAmpLow,
|
||||
ampHigh: ConductorDemoController.bottomAmpHigh
|
||||
)
|
||||
bottomHandle = active.add(pattern, quantize: .nextBeat)
|
||||
bottomOn = true
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a fresh, endlessly looping pattern: both the phrase and the duration are infinite
|
||||
/// `.sequence` patterns, so the part plays until its handle is stopped.
|
||||
private func makePattern(
|
||||
phrase: [Pitch],
|
||||
eventBeats: Double,
|
||||
ampLow: Double,
|
||||
ampHigh: Double
|
||||
) -> EventPattern<ConductorDemoVoice> {
|
||||
let freqs: [Double] = phrase.compactMap(\.frequency)
|
||||
// Key-path formation on a `@LiveParam` needs the main actor.
|
||||
return MainActor.assumeIsolated {
|
||||
EventPattern(make: { ConductorDemoVoice() })
|
||||
.bind(\.freq, .sequence(freqs))
|
||||
.bind(\.amp, .uniformRandom(low: ampLow, high: ampHigh))
|
||||
.dur(.sequence([eventBeats]))
|
||||
.legato(ConductorDemoController.legato)
|
||||
.tempo(ConductorDemoController.tempoBPM)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// ConductorDemoView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
#endif
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Demonstrates ``EventConductor``: start the engine, then toggle a top and a bottom part on and
|
||||
/// off. Each part loops forever while on and enters on the next beat of the conductor's clock, so
|
||||
/// the two lock together however late they are pressed. Includes the CPU status strip and an
|
||||
/// oscilloscope.
|
||||
///
|
||||
/// Written to the View-DSL subset shared by SwiftUI and SwiftOpenUI, so it runs on macOS and Linux.
|
||||
/// Buttons use the `action:label:` form, which fires reliably on both backends.
|
||||
public struct ConductorDemoView: View {
|
||||
|
||||
let scope: ScopeCapture
|
||||
let engine: SynthesisEngine
|
||||
|
||||
@State private var controller: ConductorDemoController
|
||||
|
||||
public init(scope: ScopeCapture, engine: SynthesisEngine) {
|
||||
self.scope = scope
|
||||
self.engine = engine
|
||||
_controller = State(wrappedValue: ConductorDemoController(engine: engine))
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack {
|
||||
Text("Lyrebird — Event Conductor")
|
||||
.font(.headline)
|
||||
Button {
|
||||
controller.toggleEngine()
|
||||
} label: {
|
||||
Text(controller.engineRunning ? "Stop Engine" : "Start Engine")
|
||||
}
|
||||
Button {
|
||||
controller.toggleTop()
|
||||
} label: {
|
||||
Text(controller.topOn ? "Top Part: ON (tap to stop)" : "Top Part: off (starts on next beat)")
|
||||
}
|
||||
.disabled(!controller.engineRunning)
|
||||
Button {
|
||||
controller.toggleBottom()
|
||||
} label: {
|
||||
Text(controller.bottomOn
|
||||
? "Bottom Part: ON (tap to stop)"
|
||||
: "Bottom Part: off (starts on next beat)")
|
||||
}
|
||||
.disabled(!controller.engineRunning)
|
||||
LyrebirdStatusView(engine: engine)
|
||||
LyrebirdScopeView(capture: scope)
|
||||
.frame(height: 120)
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// ConductorDemoVoice.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A gated sine voice for the conductor demo. ``EventPattern`` holds its gate open for the note's
|
||||
/// sustain, then closes it; the envelope plays its release and frees the voice, so a part that is
|
||||
/// toggled off rings out cleanly instead of being cut.
|
||||
final class ConductorDemoVoice: SynthesizerBase, EventGated {
|
||||
|
||||
/// Envelope attack length in seconds.
|
||||
nonisolated static let attackSeconds: Double = 0.01
|
||||
|
||||
/// Envelope release length in seconds — how long a note rings after its gate closes.
|
||||
nonisolated static let releaseSeconds: Double = 0.3
|
||||
|
||||
/// Oscillator frequency in Hz. Bound per event by the pattern.
|
||||
@LiveParam var freq: Double = 440.0
|
||||
|
||||
/// Linear output gain, 0...1. Bound per event by the pattern.
|
||||
@LiveParam var amp: Double = 0.2
|
||||
|
||||
/// Envelope gate. Open by default so the attack fires when the voice is added.
|
||||
@LiveParam var gate: Double = 1.0
|
||||
|
||||
var eventGate: ParameterNode { $gate }
|
||||
|
||||
override func build() {
|
||||
let envelope: Envelope = Envelope(
|
||||
levels: [0.0, 1.0, 0.0],
|
||||
durations: [ConductorDemoVoice.attackSeconds, ConductorDemoVoice.releaseSeconds],
|
||||
curves: [.welch, .welch],
|
||||
releaseNode: 1
|
||||
)
|
||||
let shaped: EnvelopeGen.Audio = EnvelopeGen.Audio(
|
||||
envelope: envelope,
|
||||
gate: $gate,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
let source: OscSin.Audio = OscSin.Audio(freq: $freq, mul: $amp)
|
||||
let mono: any ValidGeneratorInput = source * shaped
|
||||
output(bus: 0, source: Pan2(input: mono, pan: 0.0))
|
||||
}
|
||||
}
|
||||
@@ -17,10 +17,14 @@ public enum DemoSelection: String, Sendable {
|
||||
/// Stereo sine tone with frequency / amplitude / pan controls.
|
||||
case sine
|
||||
|
||||
/// Live event ensemble: engine start/stop plus top and bottom parts driven by an
|
||||
/// ``EventConductor``. The view owns the engine, so nothing starts at launch.
|
||||
case conductor
|
||||
|
||||
/// Resolve the selection from `LYREBIRD_DEMO` (defaults to `.vector`).
|
||||
public static func fromEnvironment() -> DemoSelection {
|
||||
let raw: String = ProcessInfo.processInfo.environment["LYREBIRD_DEMO"]?.lowercased() ?? "vector"
|
||||
return DemoSelection(rawValue: raw) ?? .vector
|
||||
let raw: String = ProcessInfo.processInfo.environment["LYREBIRD_DEMO"]?.lowercased() ?? "conductor"
|
||||
return DemoSelection(rawValue: raw) ?? .conductor
|
||||
}
|
||||
|
||||
/// Title-bar text for the window hosting this demo.
|
||||
@@ -28,6 +32,7 @@ public enum DemoSelection: String, Sendable {
|
||||
switch self {
|
||||
case .vector: return "Lyrebird — Vector Oscillator"
|
||||
case .sine: return "Lyrebird — Sine Tone"
|
||||
case .conductor: return "Lyrebird — Event Conductor"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import LyrebirdUI
|
||||
// ── Demo selector ─────────────────────────────────────────────────────────────
|
||||
// Change `demo` to `.sineTone` or `.binDelay` to switch demos.
|
||||
private enum Demo { case vector, binDelay, sineTone }
|
||||
private let demo: Demo = .vector
|
||||
private let demo: Demo = .binDelay
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
|
||||
@@ -9,7 +9,7 @@ import LyrebirdSynth
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 44100,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
|
||||
@@ -156,7 +156,7 @@ let engine = SynthesisEngine(
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver())
|
||||
driver: makeDefaultAudioDriver())
|
||||
|
||||
try engine.start()
|
||||
try engine.add(SineTone())
|
||||
|
||||
@@ -47,6 +47,42 @@ let env = EnvelopeGen.Control(envelope: Envelope(
|
||||
let voice = carrier * env * 0.2 // ready to route to a bus
|
||||
```
|
||||
|
||||
### Generators — or write your own
|
||||
|
||||
A Generator is an RT-safe DSP node: subclass `GeneratorBase`, conform to `AudioGenerator`, fill the inherited pre-allocated `_result` buffer, and return it. No allocation, locks, or runtime type checks on the render thread — inputs are classified once at `init`. This is a complete hard-clip distortion:
|
||||
|
||||
```swift
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Hard-clip distortion — clamps its input signal to ±`level`.
|
||||
final class HardClip: GeneratorBase, AudioGenerator {
|
||||
private let input: any ValidGeneratorInput
|
||||
private let level: Double
|
||||
|
||||
init(input: any ValidGeneratorInput, level: Double = 0.5) {
|
||||
self.input = input._resolvedInput() // resolve/classify inputs off the RT thread
|
||||
self.level = level
|
||||
super.init() // allocates _result: one mono channel, 512 frames
|
||||
}
|
||||
|
||||
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count) // bounds guard — no force-unwraps on the RT thread
|
||||
guard let signal = input.calculatedSamples(graph: graph, count: count).first else {
|
||||
return _result
|
||||
}
|
||||
for i in 0..<count {
|
||||
_result[0][i] = max(-level, min(level, signal[i])) // clamp, in place
|
||||
}
|
||||
return _result // pre-allocated buffer; the engine reads it directly
|
||||
}
|
||||
}
|
||||
|
||||
// Wire it like any built-in generator — operators and literals compose it the same way:
|
||||
let dirty = HardClip(input: OscSin.Audio(freq: 220.0), level: 0.2) * 0.5
|
||||
```
|
||||
|
||||
`floatValue` comes free from the `AudioGenerator` extension. A generator that also makes sense at control rate (LFOs, envelopes) uses a paired `enum Name { class Audio; class Control }` namespace instead — see [`docs/protocols/writing-generators.md`](docs/protocols/writing-generators.md) for the full guide, shared helpers, and the multi-channel rules.
|
||||
|
||||
### Synthesizers — a graph plus live parameters
|
||||
|
||||
A `SynthesizerBase` subclass owns a graph built in `build()` and exposes `@LiveParam` (atomic, RT-safe) or `@UIParam` (SwiftUI-bindable) properties. The `$name` projection injects each parameter into the graph as a smoothed control-rate node:
|
||||
@@ -76,7 +112,7 @@ let engine = SynthesisEngine(
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()) // NRTDriver for offline, iOSAudioDriver for iOS
|
||||
driver: makeDefaultAudioDriver()) // CoreAudio on macOS, iOS driver on iOS, ALSA on Linux; NRTDriver for offline
|
||||
|
||||
try engine.start()
|
||||
try engine.add(FMTone()) // sounds immediately
|
||||
@@ -85,7 +121,7 @@ try engine.schedule(tone, after: 2.5) // sample-accurate, 2.5 s from now
|
||||
tone.carrierFreq = 660 // live, atomic, no glitch
|
||||
```
|
||||
|
||||
Swap `CoreAudioDriver()` for `NRTDriver(outputURL:duration:)` and the identical graph renders offline to a CAF file. See [`INSTALLATION_AND_USAGE.md`](INSTALLATION_AND_USAGE.md) to add the package and scaffold projects, and [`ARCHITECTURE.md`](ARCHITECTURE.md) for how the threading and scheduling work underneath.
|
||||
Swap `makeDefaultAudioDriver()` for `NRTDriver(outputURL:duration:)` and the identical graph renders offline to a CAF file. See [`INSTALLATION_AND_USAGE.md`](INSTALLATION_AND_USAGE.md) to add the package and scaffold projects, and [`ARCHITECTURE.md`](ARCHITECTURE.md) for how the threading and scheduling work underneath.
|
||||
|
||||
### Live coding — prototype in the interpreter
|
||||
|
||||
@@ -100,7 +136,7 @@ import LyrebirdSynth
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512, sampleRate: 48_000,
|
||||
numOutputChannels: 2, numInputChannels: 0,
|
||||
driver: CoreAudioDriver())
|
||||
driver: makeDefaultAudioDriver())
|
||||
try engine.start()
|
||||
|
||||
// Define a synth right in the session.
|
||||
|
||||
+41
@@ -7,6 +7,47 @@ functionality in a backward-compatible way.
|
||||
|
||||
---
|
||||
|
||||
## 2.4.0 — Event patterns and the live event conductor
|
||||
|
||||
An additive, source-compatible release that adds a declarative, event-driven
|
||||
layer on top of the existing routine/clock system. It is modelled on the
|
||||
pattern-event idea familiar from other synthesis environments, but the public
|
||||
API is named for what each type does rather than after any one of them.
|
||||
|
||||
**New — `EventPattern`.** A declarative pattern that binds typed key paths on a
|
||||
voice to value patterns and plays one voice per event, scheduling each event's
|
||||
start and release from a duration/`legato` pattern. A voice releases in one of
|
||||
two ways, and never both: a self-timed envelope if it conforms to
|
||||
`EventSustainAware` (it is handed the event's sustain in seconds), or a
|
||||
pattern-driven gate note-off if it conforms to `EventGated`. When a voice
|
||||
conforms to both, the **gate wins** — `setEventSustain` is skipped so the two
|
||||
release paths never fire together. A plain voice (neither conformance) is
|
||||
removed by the pattern after `sustain + releaseTail`.
|
||||
|
||||
**New — `MonoEventPattern`.** One reused voice whose parameters are rewritten
|
||||
per event, with an optional `EventRetriggerable` re-strike. Gains a
|
||||
`play(on:startAfterBeats:)` lead-in so a mono part can enter an ensemble on a
|
||||
delayed beat.
|
||||
|
||||
**New — `ParallelEventPattern`.** Heterogeneous `EventPatternPlayable` children
|
||||
started together under one merged `EventPatternHandle`; `add` enters with the
|
||||
group and `addAfter(beats:)` staggers a child's entry.
|
||||
|
||||
**New — `EventConductor` + `EventConductorHandle`.** A live, clock-driven
|
||||
ensemble you can feed while it runs: `add(_:quantize:)` is thread-safe from a
|
||||
UI, OSC, or MIDI callback, and entry is **clock-deferred** — quantised by an
|
||||
`EventQuantum` (`.now`, `.nextBeat`, `.nextMultiple(ofBeats:)`, `.atBeat`,
|
||||
`.afterBeats`) against the conductor's own clock, so entry is tempo-independent
|
||||
and each part keeps its own timing afterward. `add` returns an
|
||||
`EventConductorHandle` that stops a single part — cancelling it if it is still
|
||||
pending, stopping it if it is already playing.
|
||||
|
||||
All new types; no existing API changed, so this is drop-in over 2.3.x. See
|
||||
`docs/tooling/routine-task.md` (§ EventPattern / § EventConductor) and the new
|
||||
`.conductor` demo in `LyrebirdGUIDemo`.
|
||||
|
||||
---
|
||||
|
||||
## 2.3.0 — Edit-ended callback on continuous controls
|
||||
|
||||
A small, additive, source-compatible release. The continuous `LyrebirdUI`
|
||||
|
||||
@@ -18,10 +18,12 @@ let engine = SynthesisEngine(
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
```
|
||||
|
||||
> Note: ``makeDefaultAudioDriver()`` returns the live-audio driver for the platform the build targets — `CoreAudioDriver` on macOS, `iOSAudioDriver` on iOS, `ALSAAudioDriver` on a Linux build with libasound, and ``OfflineDriver`` (silent) where no live backend exists. Prefer it over a concrete driver so one source builds and runs on every platform; name a concrete driver only in code already locked to a single platform. Check ``isLiveAudioAvailable`` when silence would be a surprise.
|
||||
|
||||
The full parameter list is ``SynthesisEngine/init(blockSize:controlBlockSize:sampleRate:numOutputChannels:numInputChannels:numAudioBuses:numControlBuses:eventQueueCapacity:maxEventsPerBlock:driver:)``:
|
||||
|
||||
| Parameter | Meaning | Default |
|
||||
|
||||
@@ -86,7 +86,7 @@ let engine = SynthesisEngine(
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
try engine.start()
|
||||
try engine.add(MySynth())
|
||||
|
||||
@@ -7,7 +7,7 @@ A native macOS audio synthesis framework for Swift.
|
||||
Lyrebird provides a signal-graph engine backed by Core Audio. You define instruments and effects as ``Synthesizer`` instances containing networks of ``Generator`` objects, then add them to a running ``SynthesisEngine``. All signal processing runs on the Core Audio real-time thread with no heap allocation in steady state.
|
||||
|
||||
```swift
|
||||
let driver = CoreAudioDriver()
|
||||
let driver = makeDefaultAudioDriver()
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512, sampleRate: 44100,
|
||||
numOutputChannels: 2, numInputChannels: 0,
|
||||
|
||||
@@ -25,7 +25,7 @@ Lyrebird provides two ways to use multiple cores:
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512, sampleRate: 44100,
|
||||
numOutputChannels: 2, numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
|
||||
let voices = ParallelGroup(engine: engine)
|
||||
|
||||
@@ -22,7 +22,7 @@ NRT rendering is the correct approach for:
|
||||
|
||||
## Approach 1 — NRTDriver
|
||||
|
||||
Replace `CoreAudioDriver()` with `NRTDriver(outputURL:duration:)`. Everything else stays the same.
|
||||
Replace `makeDefaultAudioDriver()` with `NRTDriver(outputURL:duration:)`. Everything else stays the same.
|
||||
|
||||
```swift
|
||||
import Foundation
|
||||
|
||||
@@ -879,7 +879,7 @@ let events: [LyrebirdEvent] = [
|
||||
|
||||
// MARK: - Live performance
|
||||
|
||||
let driver = CoreAudioDriver()
|
||||
let driver = makeDefaultAudioDriver()
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 44100,
|
||||
|
||||
@@ -111,7 +111,7 @@ let engine = SynthesisEngine(
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 2,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
|
||||
// engine.add(MySynth())
|
||||
|
||||
@@ -50,7 +50,7 @@ import LyrebirdSynth
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512, sampleRate: 44100,
|
||||
numOutputChannels: 2, numInputChannels: 2,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
try engine.start()
|
||||
|
||||
|
||||
@@ -478,8 +478,128 @@ bass.start(engine: engine)
|
||||
|
||||
``LyrebirdClock`` is `Sendable`. Multiple routines may read `currentBeat`, `sampleTime(beat:)`, and `nextBeat(after:)` concurrently. Only one thread should write `bpm`.
|
||||
|
||||
## Event-driven patterns
|
||||
|
||||
``EventPattern`` is the heart of Lyrebird's event-driven playback: it binds named value ``Pattern``s to a voice's `@LiveParam` parameters and plays them as a dur-driven stream of voices, so you do not hand-roll the spawn loop above. Binding is **typed** — a `ReferenceWritableKeyPath` into a concrete voice type, checked at compile time — with no untyped event dictionary and no default-event prototype. The voice owns its amplitude envelope; the pattern owns timing.
|
||||
|
||||
Each event pulls one value from every bound pattern plus the duration pattern, makes a voice, writes the values, adds it, and reaps it, then waits the event's duration. The stream ends when the duration pattern or **any** bound pattern is exhausted; `repeats` replays the whole set.
|
||||
|
||||
**How a voice ends** follows one rule — the pattern never hard-removes a voice that frees itself. A voice conforming to ``EventGated`` is held open by its gate for the note and note-off'd (gate → `0`) after `sustain`, so its envelope release plays out and frees it; a voice conforming to ``EventSustainAware`` instead builds a fixed-duration self-freeing envelope from the sustain it is handed. In both cases the release is never cut. A voice conforming to neither is removed after `sustain + releaseTail` beats — the only case ``EventPattern/releaseTail(_:)`` affects.
|
||||
|
||||
```swift
|
||||
import LyrebirdSynth
|
||||
|
||||
// A voice whose envelope frees it; EventPattern shapes the envelope via setEventSustain.
|
||||
final class PluckVoice: SynthesizerBase, EventSustainAware {
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.2
|
||||
private var sustain: Double = 0.5
|
||||
|
||||
func setEventSustain(seconds: Double) {
|
||||
sustain = seconds
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let env: Envelope = Envelope(levels: [0.0, 1.0, 0.0], durations: [0.005, sustain], curves: [0, 0])
|
||||
let gen: EnvelopeGen.Audio = EnvelopeGen.Audio(envelope: env, doneAction: .freeNode)
|
||||
output(bus: 0, source: OscSin.Audio(freq: $freq, mul: $amp) * gen)
|
||||
}
|
||||
}
|
||||
|
||||
func playPluck(on engine: SynthesisEngine) -> EventPatternHandle {
|
||||
EventPattern(make: { PluckVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0, 660.0]))
|
||||
.bind(\.amp, .uniformRandom(low: 0.1, high: 0.4))
|
||||
.dur(.sequence([0.25, 0.25, 0.5]))
|
||||
.legato(0.9)
|
||||
.tempo(132.0)
|
||||
.play(on: engine)
|
||||
}
|
||||
```
|
||||
|
||||
### Note-off with EventGated
|
||||
|
||||
A voice conforming to ``EventGated`` exposes its gate `@LiveParam` as `eventGate`; the pattern opens it on add (default the parameter open so the attack fires) and closes it after `sustain`. Give the voice an `EnvelopeGen` with a gate and a `releaseNode`: it holds at the sustain level while the gate is open, plays its release when the gate closes, and frees itself via `doneAction: .freeNode`. Nothing truncates the release, and there is no `releaseTail` to tune.
|
||||
|
||||
```swift
|
||||
import LyrebirdSynth
|
||||
|
||||
// A gated voice: the gate holds it open; EventPattern closes it at the note's sustain.
|
||||
final class GatedVoice: SynthesizerBase, EventGated {
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.2
|
||||
@LiveParam var gate: Double = 1.0 // open by default so the attack fires on add
|
||||
|
||||
var eventGate: ParameterNode { $gate }
|
||||
|
||||
override func build() {
|
||||
// releaseNode: 1 holds at levels[1] while gate > 0; gate → 0 plays segment 1 (release).
|
||||
let env: Envelope = Envelope(
|
||||
levels: [0.0, 1.0, 0.0],
|
||||
durations: [0.01, 0.3],
|
||||
curves: [.welch, .welch],
|
||||
releaseNode: 1
|
||||
)
|
||||
let gen: EnvelopeGen.Audio = EnvelopeGen.Audio(envelope: env, gate: $gate, doneAction: .freeNode)
|
||||
output(bus: 0, source: OscSin.Audio(freq: $freq, mul: $amp) * gen)
|
||||
}
|
||||
}
|
||||
|
||||
func playGated(on engine: SynthesisEngine) -> EventPatternHandle {
|
||||
EventPattern(make: { GatedVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0, 660.0]))
|
||||
.dur(.sequence([0.25, 0.25, 0.5]))
|
||||
.legato(0.8)
|
||||
.tempo(132.0)
|
||||
.play(on: engine)
|
||||
}
|
||||
```
|
||||
|
||||
### Monophonic and parallel
|
||||
|
||||
``MonoEventPattern`` reuses **one** persistent voice, updating its parameters per event instead of spawning a new voice. A voice conforming to ``EventRetriggerable`` is re-struck on every event after the first (per-event articulation); when it also conforms to ``EventSustainAware``, its sustain is set before each `retrigger()`. A persistent ``EventGated`` voice is held open across the stream and note-off'd once, at the end.
|
||||
|
||||
``ParallelEventPattern`` plays several patterns at once. It holds a heterogeneous set of children — any mix of ``EventPattern``, ``MonoEventPattern`` and nested `ParallelEventPattern`s (anything conforming to ``EventPatternPlayable``) — and returns one ``EventPatternHandle`` that stops or awaits them all. The children share no common clock; same-tempo children begin within thread-start latency of each other and are not re-synchronised afterwards. ``ParallelEventPattern/add(_:)`` adds a child that enters with the group; ``ParallelEventPattern/addAfter(beats:eventPattern:)`` staggers a child a fixed number of beats into the shared start grid. All children must be composed before `play` — the group is a fire-once start. To push patterns in **live**, after playback has begun, use ``EventConductor`` instead.
|
||||
|
||||
```swift
|
||||
func playTogether(on engine: SynthesisEngine) -> EventPatternHandle {
|
||||
let bass: EventPattern<PluckVoice> = EventPattern(make: { PluckVoice() })
|
||||
.bind(\.freq, .sequence([110.0, 110.0, 165.0, 110.0]))
|
||||
.dur(.sequence([1.0]))
|
||||
let lead: EventPattern<PluckVoice> = EventPattern(make: { PluckVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0, 660.0]))
|
||||
.dur(.sequence([0.5]))
|
||||
return ParallelEventPattern([bass, lead]).play(on: engine)
|
||||
}
|
||||
```
|
||||
|
||||
Playback runs on a background `LyrebirdTask`; voice construction and `@LiveParam` writes hop to the main thread. The returned ``EventPatternHandle`` stops playback (``EventPatternHandle/stop()``), reports whether anything is still playing (``EventPatternHandle/isPlaying``), or blocks until a finite pattern finishes (``EventPatternHandle/waitUntilComplete(releasePadding:)``).
|
||||
|
||||
### Live insertion — EventConductor
|
||||
|
||||
Where ``ParallelEventPattern`` composes every child up front and fires once, ``EventConductor`` keeps a background clock running and accepts patterns **while it plays**, from any thread — a UI button, an OSC handler, a MIDI callback. Each enters quantised to the shared beat grid.
|
||||
|
||||
```swift
|
||||
let conductor: EventConductor = EventConductor(tempo: 128.0)
|
||||
conductor.start(on: engine)
|
||||
conductor.add(drums, quantize: .now) // start the groove now
|
||||
// … later, from a GUI button / OSC / MIDI callback, on any thread …
|
||||
let bassPart = conductor.add(bass, quantize: .nextMultiple(ofBeats: 4)) // drops in on the next bar
|
||||
bassPart.stop() // … and later stops the bass alone
|
||||
```
|
||||
|
||||
``EventConductor/add(_:quantize:)`` enqueues under a lock and returns an ``EventConductorHandle`` at once; the conductor's own task starts due patterns on the main thread. ``EventConductorHandle/stop()`` stops that one part — cancelling it if still pending, stopping it if already playing — without disturbing the others, which is what the conductor's own ``EventConductor/stop()`` does. ``EventQuantum`` names the entry boundary — ``EventQuantum/now``, ``EventQuantum/nextBeat``, ``EventQuantum/nextMultiple(ofBeats:)``, ``EventQuantum/atBeat(_:)``, ``EventQuantum/afterBeats(_:)``. The clock quantises only each pattern's **entry**; once started a pattern keeps its own relative timing at its own tempo, so patterns may be polytempo. For finite content, ``EventConductor/waitUntilIdle(releasePadding:)`` blocks until nothing is pending and no child is still playing, after which the caller typically calls ``EventConductor/stop()``.
|
||||
|
||||
## See Also
|
||||
|
||||
- ``EventPattern``
|
||||
- ``MonoEventPattern``
|
||||
- ``ParallelEventPattern``
|
||||
- ``EventConductor``
|
||||
- ``EventConductorHandle``
|
||||
- ``EventQuantum``
|
||||
- ``EventGated``
|
||||
- ``EventSustainAware``
|
||||
- ``LyrebirdClock``
|
||||
- ``ValueComputable``
|
||||
- <doc:Scheduling>
|
||||
|
||||
@@ -63,7 +63,7 @@ swift run LyrebirdDemo
|
||||
|
||||
Demonstrates: `SynthesizerBase`, `@LiveParam`, `OscSin`, `DelayLine`, `engine.add`/`remove`, and RT-safe parameter updates. Runs real-time audio via ``CoreAudioDriver``.
|
||||
|
||||
**Copy this target** when you want a headless synthesis starting point. Swap `CoreAudioDriver()` for `NRTDriver(outputURL:duration:)` for offline rendering — see <doc:NRTGuide>.
|
||||
**Copy this target** when you want a headless synthesis starting point. Swap `makeDefaultAudioDriver()` for `NRTDriver(outputURL:duration:)` for offline rendering — see <doc:NRTGuide>.
|
||||
|
||||
### LyrebirdUIDemo — GUI starting point
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// EventBinding.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// One `keyPath → Pattern` binding inside an ``EventPattern``.
|
||||
///
|
||||
/// Pairs a writable key path into a voice's `@LiveParam` (`\.freq`, `\.amp`, …) with the
|
||||
/// `Pattern<Double>` that drives it. On each event the pattern yields one value, written to
|
||||
/// the voice through the key path before the voice is added to the engine.
|
||||
///
|
||||
/// The key path targets a `@LiveParam`-backed `Double`, whose setter is an RT-safe atomic
|
||||
/// store, so the write is picked up by the render thread on the next block.
|
||||
///
|
||||
/// Internal — callers build bindings through ``EventPattern/bind(_:_:)``. Accessed only on
|
||||
/// the main thread, inside the pattern's per-event `onMain` hop (single consumer).
|
||||
internal struct EventBinding<V: Synthesizer> {
|
||||
|
||||
/// Writable key path into the voice's `@LiveParam Double` parameter.
|
||||
let keyPath: ReferenceWritableKeyPath<V, Double>
|
||||
|
||||
/// Value source for this parameter. One value is pulled per event via ``nextValue()``.
|
||||
let pattern: Pattern<Double>
|
||||
|
||||
/// Pulls the next value for this binding without touching a voice.
|
||||
///
|
||||
/// - Returns: The next value, or `nil` if the pattern is exhausted — which ends the whole
|
||||
/// event stream (any exhausted input ends it).
|
||||
/// Pulling before making a voice avoids constructing a voice that is then discarded.
|
||||
@MainActor func nextValue() -> Double? {
|
||||
pattern.next()
|
||||
}
|
||||
|
||||
/// Writes a previously pulled value into `voice` through the key path.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: The value to write.
|
||||
/// - voice: The voice whose parameter is being set.
|
||||
@MainActor func write(_ value: Double, to voice: V) {
|
||||
voice[keyPath: keyPath] = value
|
||||
}
|
||||
|
||||
/// Returns the pattern to its initial state (used when an ``EventPattern`` repeats).
|
||||
func reset() {
|
||||
pattern.reset()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
// EventConductor.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Synchronization
|
||||
|
||||
/// Poll granularity of the conductor's driving task, in seconds. Matches the routine context's
|
||||
/// own poll cadence, so a quantised entry lands within roughly this of its beat boundary.
|
||||
private let eventConductorPollSeconds: Double = 0.01
|
||||
|
||||
/// A running, clock-driven ensemble you push event patterns into **live** — from a UI button, an
|
||||
/// OSC handler, a MIDI callback, any thread — each entering quantised to a shared beat grid.
|
||||
///
|
||||
/// Where ``ParallelEventPattern`` is a fire-once group (every child composed before `play`), an
|
||||
/// `EventConductor` keeps a background clock running and accepts ``add(_:quantize:)`` at any time
|
||||
/// from any thread. Each added pattern begins on the boundary named by its ``EventQuantum`` — the
|
||||
/// next beat, the next bar, an absolute beat, or a relative lead-in — so a pattern triggered from
|
||||
/// a control surface drops into the groove on the beat rather than the instant the control fired.
|
||||
///
|
||||
/// ```swift
|
||||
/// let conductor: EventConductor = EventConductor(tempo: 128.0)
|
||||
/// conductor.start(on: engine)
|
||||
/// conductor.add(drums, quantize: .now) // start the groove now
|
||||
/// // … later, from a GUI button / OSC / MIDI callback, on any thread …
|
||||
/// let bassPart = conductor.add(bass, quantize: .nextMultiple(ofBeats: 4)) // drops in on the next bar
|
||||
/// // … later still …
|
||||
/// bassPart.stop() // stops the bass alone; the drums play on
|
||||
/// ```
|
||||
///
|
||||
/// ## What the clock governs
|
||||
///
|
||||
/// The shared clock quantises only each pattern's **entry**, and it does so against the
|
||||
/// conductor's own beat grid: a resolved pattern is held until the conductor's clock reaches its
|
||||
/// target beat, then started immediately. Entry therefore aligns to the conductor's grid within
|
||||
/// the poll granularity (~`eventConductorPollSeconds`), **independent of the pattern's own tempo**.
|
||||
/// Once started, a pattern runs its own relative `wait(beats:)` chain at its own tempo, exactly as
|
||||
/// it would under ``EventPattern`` or ``ParallelEventPattern`` — so patterns can be polytempo, and
|
||||
/// the conductor does not re-align their individual events after entry.
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// ``add(_:quantize:)`` is safe to call from any thread: it enqueues under a lock and returns an
|
||||
/// ``EventConductorHandle`` at once. The conductor's own background task drains the queue each poll
|
||||
/// and starts due patterns on the main thread (voice construction is main-actor-isolated). Call
|
||||
/// ``EventConductorHandle/stop()`` on that handle to stop one part alone; ``stop()`` on the
|
||||
/// conductor stops them all. ``stop()``, ``isRunning``, ``hasActiveChildren`` and ``currentBeat``
|
||||
/// are likewise thread-safe. A pattern whose start is in flight when ``stop()`` is called is
|
||||
/// stopped as soon as it has entered, so nothing outlives the conductor.
|
||||
///
|
||||
/// ## Lifecycle
|
||||
///
|
||||
/// The conductor runs until ``stop()``. For finite content, ``waitUntilIdle(releasePadding:)``
|
||||
/// blocks until nothing is pending and no child is still playing (pumping the main run loop so the
|
||||
/// dispatched starts land), after which the caller typically calls ``stop()``.
|
||||
///
|
||||
/// - SeeAlso: ``EventConductorHandle``, ``EventQuantum``, ``ParallelEventPattern``, ``EventPatternPlayable``, ``EventPattern``
|
||||
public final class EventConductor: @unchecked Sendable {
|
||||
|
||||
/// Conductor lifecycle phase.
|
||||
private enum Phase {
|
||||
case idle // created, not yet started
|
||||
case running // driving task live
|
||||
case stopped // stopped; ignores further adds
|
||||
}
|
||||
|
||||
/// Guards every mutable field below. Held only for short, lock-local work — never across the
|
||||
/// main-thread hop that starts a child.
|
||||
private let _lock: NSLock = NSLock()
|
||||
|
||||
private var _phase: Phase = .idle
|
||||
|
||||
/// Patterns added but not yet resolved against the clock, each with the quantum that places it
|
||||
/// and the ``EventConductorHandle`` returned to the caller.
|
||||
private var _inbox: [(part: EventConductorHandle, pattern: any EventPatternPlayable, quantize: EventQuantum)] = []
|
||||
|
||||
/// Resolved patterns awaiting their target beat. Each poll, those whose target beat has arrived
|
||||
/// are started; the rest stay here. Resolving against the conductor's clock (not a per-pattern
|
||||
/// lead-in) is what makes entry tempo-independent.
|
||||
private var _pending: [(part: EventConductorHandle, pattern: any EventPatternPlayable, targetBeat: Double)] = []
|
||||
|
||||
/// Count of patterns selected to start this poll but whose entry has not yet been recorded — a
|
||||
/// pattern is never invisible to ``waitUntilIdle(releasePadding:)`` in the gap between selection
|
||||
/// and the main-thread start.
|
||||
private var _starting: Int = 0
|
||||
|
||||
/// Parts that have entered (or are entering). Finished parts are pruned lazily on append and on
|
||||
/// ``hasActiveChildren`` so a long-running conductor does not accumulate them without bound.
|
||||
private var _active: [EventConductorHandle] = []
|
||||
|
||||
/// The engine, captured at ``start(on:)``. Immutable once running.
|
||||
private var _engine: SynthesisEngine?
|
||||
|
||||
/// The background driving task. Immutable once running.
|
||||
private var _task: LyrebirdTask?
|
||||
|
||||
/// The conductor clock's latest beat position, as `Double` bit pattern, updated each poll.
|
||||
/// Read lock-free by ``currentBeat``.
|
||||
private let _currentBeatBits: Atomic<UInt64> = Atomic<UInt64>(0)
|
||||
|
||||
/// Playback tempo in beats per minute. Set at init before ``start(on:)``.
|
||||
private let _tempo: Double
|
||||
|
||||
/// Creates a conductor at `tempo` BPM. Add patterns with ``add(_:quantize:)`` before or after
|
||||
/// ``start(on:)``.
|
||||
///
|
||||
/// - Parameter tempo: Beats per minute. Must be positive. Defaults to `120.0`.
|
||||
public init(tempo: Double = 120.0) {
|
||||
precondition(tempo > 0 && tempo.isFinite, "tempo must be positive and finite")
|
||||
_tempo = tempo
|
||||
}
|
||||
|
||||
// MARK: - Control
|
||||
|
||||
/// Starts the conductor's clock on `engine`. No-op if already started.
|
||||
///
|
||||
/// Any patterns already queued by ``add(_:quantize:)`` are serviced on the first poll, relative
|
||||
/// to beat `0`.
|
||||
///
|
||||
/// - Parameter engine: Engine the patterns' voices are added to.
|
||||
@MainActor public func start(on engine: SynthesisEngine) {
|
||||
_lock.lock()
|
||||
guard _phase == .idle else {
|
||||
_lock.unlock()
|
||||
return
|
||||
}
|
||||
_phase = .running
|
||||
_engine = engine
|
||||
let task: LyrebirdTask = LyrebirdTask { [self] ctx in
|
||||
try _run(ctx: ctx)
|
||||
}
|
||||
_task = task
|
||||
_lock.unlock()
|
||||
task.start(engine: engine)
|
||||
}
|
||||
|
||||
/// Enqueues `pattern` to enter at the boundary named by `quantize`, returning a handle that
|
||||
/// stops that pattern alone. Thread-safe — call from a UI, OSC or MIDI callback on any thread.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pattern: The pattern to start — an ``EventPattern``, ``MonoEventPattern`` or
|
||||
/// ``ParallelEventPattern``.
|
||||
/// - quantize: When it should enter, against the conductor's clock. Defaults to
|
||||
/// ``EventQuantum/nextBeat``.
|
||||
/// - Returns: An ``EventConductorHandle`` for this part. ``EventConductorHandle/stop()`` cancels
|
||||
/// it if still pending, or stops it if already playing, without disturbing the other parts.
|
||||
/// After ``stop()`` the returned handle is already cancelled (its ``EventConductorHandle/isPlaying``
|
||||
/// is `false`) and the pattern is never started.
|
||||
@discardableResult
|
||||
public func add(
|
||||
_ pattern: any EventPatternPlayable,
|
||||
quantize: EventQuantum = .nextBeat
|
||||
) -> EventConductorHandle {
|
||||
// Validate on the caller's thread so a bad quantum traps at the call site, not later on
|
||||
// the conductor's background task.
|
||||
quantize.validate()
|
||||
let part: EventConductorHandle = EventConductorHandle()
|
||||
_lock.lock()
|
||||
if _phase != .stopped {
|
||||
_inbox.append((part, pattern, quantize))
|
||||
} else {
|
||||
part.markCancelledBeforeEntry()
|
||||
}
|
||||
_lock.unlock()
|
||||
return part
|
||||
}
|
||||
|
||||
/// Stops the conductor and every pattern it started. Idempotent; no further ``add(_:quantize:)``
|
||||
/// is honoured afterwards. A pattern whose start is in flight is stopped as soon as it enters.
|
||||
public func stop() {
|
||||
_lock.lock()
|
||||
_phase = .stopped
|
||||
let task: LyrebirdTask? = _task
|
||||
// Cancel everything still pending so its handle reports stopped and it never enters.
|
||||
for item: (part: EventConductorHandle, pattern: any EventPatternPlayable, quantize: EventQuantum) in _inbox {
|
||||
item.part.markCancelledBeforeEntry()
|
||||
}
|
||||
for item: (part: EventConductorHandle, pattern: any EventPatternPlayable, targetBeat: Double) in _pending {
|
||||
item.part.markCancelledBeforeEntry()
|
||||
}
|
||||
let active: [EventConductorHandle] = _active
|
||||
_inbox.removeAll(keepingCapacity: false)
|
||||
_pending.removeAll(keepingCapacity: false)
|
||||
_active.removeAll(keepingCapacity: false)
|
||||
_lock.unlock()
|
||||
task?.stop()
|
||||
for part: EventConductorHandle in active {
|
||||
part.stop()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - State
|
||||
|
||||
/// `true` while the conductor's clock is running (started and not stopped).
|
||||
public var isRunning: Bool {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
return _phase == .running
|
||||
}
|
||||
|
||||
/// `true` while any pattern the conductor started is still playing. Prunes finished handles as
|
||||
/// a side effect.
|
||||
public var hasActiveChildren: Bool {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
_active.removeAll { !$0.isPlaying }
|
||||
return !_active.isEmpty
|
||||
}
|
||||
|
||||
/// The conductor clock's current beat position (`0` before ``start(on:)``). Updated each poll,
|
||||
/// so it is accurate to within the poll granularity.
|
||||
public var currentBeat: Double {
|
||||
Double(bitPattern: _currentBeatBits.load(ordering: .relaxed))
|
||||
}
|
||||
|
||||
/// Blocks the calling thread until nothing is pending and no started pattern is still playing,
|
||||
/// then waits an extra `releasePadding` seconds for release tails to ring out.
|
||||
///
|
||||
/// Intended for finite content, and only after ``start(on:)``: add the patterns, `waitUntilIdle`,
|
||||
/// then ``stop()``. On the main thread it pumps the run loop so the conductor's dispatched starts
|
||||
/// land; off-main it polls. Returns immediately if the conductor is stopped or not yet started
|
||||
/// (before ``start(on:)`` nothing can drain, so do not call it then). If patterns may still be
|
||||
/// added later (a live performance), do not call this — drive ``stop()`` directly instead.
|
||||
///
|
||||
/// - Parameter releasePadding: Extra seconds to wait after the last pattern finishes. Negative
|
||||
/// values are clamped to `0`. Defaults to `0`.
|
||||
public func waitUntilIdle(releasePadding: Double = 0) {
|
||||
while true {
|
||||
_lock.lock()
|
||||
let idle: Bool = _phase != .running
|
||||
|| (_inbox.isEmpty && _pending.isEmpty && _starting == 0
|
||||
&& !_active.contains { $0.isPlaying })
|
||||
_lock.unlock()
|
||||
if idle { break }
|
||||
_tick(seconds: eventConductorPollSeconds)
|
||||
}
|
||||
let padding: Double = max(0.0, releasePadding)
|
||||
guard padding > 0 else { return }
|
||||
_tick(seconds: padding)
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
/// The conductor's driving-task body: set tempo, then poll — servicing the inbox and
|
||||
/// publishing the beat position — until stopped.
|
||||
private func _run(ctx: LyrebirdRoutineContext) throws {
|
||||
ctx.tempo = _tempo
|
||||
while true {
|
||||
_serviceInbox(ctx: ctx)
|
||||
_currentBeatBits.store(ctx.currentBeat.bitPattern, ordering: .relaxed)
|
||||
try ctx.wait(seconds: eventConductorPollSeconds)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves newly-added patterns against the clock, then starts every pending pattern whose
|
||||
/// target beat has arrived — on the main thread, with no lead-in. Runs on the conductor's task
|
||||
/// thread.
|
||||
private func _serviceInbox(ctx: LyrebirdRoutineContext) {
|
||||
let beatNow: Double = ctx.currentBeat
|
||||
|
||||
_lock.lock()
|
||||
guard _phase == .running, let engine: SynthesisEngine = _engine else {
|
||||
_lock.unlock()
|
||||
return
|
||||
}
|
||||
// Resolve inbox → pending against the current beat.
|
||||
for item: (part: EventConductorHandle, pattern: any EventPatternPlayable, quantize: EventQuantum) in _inbox {
|
||||
_pending.append((item.part, item.pattern, item.quantize.targetBeat(from: beatNow)))
|
||||
}
|
||||
_inbox.removeAll(keepingCapacity: true)
|
||||
// Select the pending parts whose boundary has arrived; keep the rest.
|
||||
guard !_pending.isEmpty else {
|
||||
_lock.unlock()
|
||||
return
|
||||
}
|
||||
var due: [(part: EventConductorHandle, pattern: any EventPatternPlayable)] = []
|
||||
var stillPending: [(part: EventConductorHandle, pattern: any EventPatternPlayable, targetBeat: Double)] = []
|
||||
for item: (part: EventConductorHandle, pattern: any EventPatternPlayable, targetBeat: Double) in _pending {
|
||||
if item.targetBeat <= beatNow {
|
||||
due.append((item.part, item.pattern))
|
||||
} else {
|
||||
stillPending.append(item)
|
||||
}
|
||||
}
|
||||
_pending = stillPending
|
||||
// Track the due parts in `_active` now, under the same lock that removed them from
|
||||
// `_pending`. A due part is therefore never invisible to ``stop()`` in the gap before its
|
||||
// start hop: if ``stop()`` lands during the hop it snapshots and stops the part, and the
|
||||
// `attach` below then stops the just-started pattern.
|
||||
if !due.isEmpty {
|
||||
_active.removeAll { !$0.isPlaying }
|
||||
for item: (part: EventConductorHandle, pattern: any EventPatternPlayable) in due {
|
||||
_active.append(item.part)
|
||||
}
|
||||
}
|
||||
_starting += due.count
|
||||
_lock.unlock()
|
||||
|
||||
for item: (part: EventConductorHandle, pattern: any EventPatternPlayable) in due {
|
||||
_lock.lock()
|
||||
let runningBeforeHop: Bool = _phase == .running
|
||||
_lock.unlock()
|
||||
// Skip if the conductor stopped or the caller cancelled this part before it entered —
|
||||
// no voice is built. The part stays in `_active` but reports `isPlaying == false`, so it
|
||||
// is pruned on the next selection or ``hasActiveChildren`` read.
|
||||
guard runningBeforeHop, !item.part.isCancelled else {
|
||||
item.part.markCancelledBeforeEntry()
|
||||
_lock.lock()
|
||||
_starting -= 1
|
||||
_lock.unlock()
|
||||
continue
|
||||
}
|
||||
|
||||
let args: StartArgs = StartArgs(engine: engine, pattern: item.pattern)
|
||||
let handle: EventPatternHandle = ctx.onMain {
|
||||
args.pattern.play(on: args.engine)
|
||||
}
|
||||
|
||||
// Hand over the real handle. `attach` stops it at once if the part was cancelled during
|
||||
// the hop — by the caller's ``EventConductorHandle/stop()`` or by ``stop()``'s snapshot.
|
||||
item.part.attach(handle)
|
||||
_lock.lock()
|
||||
_starting -= 1
|
||||
_lock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
/// One wait step for ``waitUntilIdle(releasePadding:)`` — pump the main run loop when on main so
|
||||
/// dispatched starts run, else a plain sleep.
|
||||
private func _tick(seconds: Double) {
|
||||
if Thread.isMainThread {
|
||||
RunLoop.current.run(until: Date().addingTimeInterval(seconds))
|
||||
} else {
|
||||
Thread.sleep(forTimeInterval: seconds)
|
||||
}
|
||||
}
|
||||
|
||||
/// Cross-thread carrier so the `@Sendable` task body can hand the (non-`Sendable`) engine and
|
||||
/// pattern to the synchronous main-thread hop. The hop is a full barrier; the two threads never
|
||||
/// touch an instance concurrently.
|
||||
private struct StartArgs: @unchecked Sendable {
|
||||
let engine: SynthesisEngine
|
||||
let pattern: any EventPatternPlayable
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// EventConductorHandle.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A stoppable reference to one pattern handed to an ``EventConductor`` through
|
||||
/// ``EventConductor/add(_:quantize:)``.
|
||||
///
|
||||
/// Returned the instant you add a pattern — before it has entered. Because the conductor holds a
|
||||
/// pattern until its quantised beat arrives, the underlying ``EventPatternHandle`` does not exist
|
||||
/// yet, so this handle stands in for it. ``stop()`` works in either phase: before entry it cancels
|
||||
/// the pending start (the pattern never enters, no voice is built); after entry it stops the
|
||||
/// started pattern, so its gated voices release. Stopping one part this way leaves every other part
|
||||
/// the conductor is running untouched — unlike ``EventConductor/stop()``, which stops them all.
|
||||
///
|
||||
/// Thread-safe: ``stop()`` and ``isPlaying`` may be called from any thread (a UI button, an OSC or
|
||||
/// MIDI callback).
|
||||
///
|
||||
/// - SeeAlso: ``EventConductor``, ``EventPatternHandle``
|
||||
public final class EventConductorHandle: @unchecked Sendable {
|
||||
|
||||
private let _lock: NSLock = NSLock()
|
||||
|
||||
/// The real handle, set by the conductor once the pattern has entered. `nil` while pending.
|
||||
private var _real: EventPatternHandle?
|
||||
|
||||
/// `true` once ``stop()`` has been called (in either phase) or the conductor cancelled the
|
||||
/// pending start. Before entry this tells the conductor to skip starting the pattern.
|
||||
private var _cancelled: Bool = false
|
||||
|
||||
internal init() {}
|
||||
|
||||
/// `true` while this part is pending entry or still playing; `false` once it has finished, been
|
||||
/// stopped, or been cancelled before entry.
|
||||
public var isPlaying: Bool {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
if let real: EventPatternHandle = _real {
|
||||
return real.isPlaying
|
||||
}
|
||||
// Not yet entered: still pending (so "playing") unless it was cancelled.
|
||||
return !_cancelled
|
||||
}
|
||||
|
||||
/// Stops this part only. Before the pattern enters, cancels its pending start; after entry,
|
||||
/// stops the started pattern so its gated voices release. Idempotent; safe from any thread.
|
||||
public func stop() {
|
||||
_lock.lock()
|
||||
_cancelled = true
|
||||
let real: EventPatternHandle? = _real
|
||||
_lock.unlock()
|
||||
real?.stop()
|
||||
}
|
||||
|
||||
/// `true` if the part has been stopped or cancelled — the conductor reads this before entry to
|
||||
/// skip the start.
|
||||
internal var isCancelled: Bool {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
return _cancelled
|
||||
}
|
||||
|
||||
/// Called by the conductor when the pattern enters, handing over the real handle. If the part
|
||||
/// was stopped while still pending, the just-started pattern is stopped at once.
|
||||
internal func attach(_ real: EventPatternHandle) {
|
||||
_lock.lock()
|
||||
_real = real
|
||||
let cancelled: Bool = _cancelled
|
||||
_lock.unlock()
|
||||
if cancelled {
|
||||
real.stop()
|
||||
}
|
||||
}
|
||||
|
||||
/// Called by the conductor when a pending part will never enter — the conductor stopped, or the
|
||||
/// part's beat was reached after it had been cancelled. Marks it finished so ``isPlaying``
|
||||
/// reports `false`.
|
||||
internal func markCancelledBeforeEntry() {
|
||||
_lock.lock()
|
||||
_cancelled = true
|
||||
_lock.unlock()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// EventGated.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Opt-in refinement a voice adopts so an event pattern can drive its **gate** — a gate-driven
|
||||
/// note-on/note-off model.
|
||||
///
|
||||
/// An ``EventGated`` voice exposes the gate `ParameterNode` projected from one of its
|
||||
/// `@LiveParam` properties (`$gate`). The event pattern opens the gate when the voice is added
|
||||
/// (so the attack fires) and closes it — sets it to `0` — when the note's sustain elapses. The
|
||||
/// voice's own `EnvelopeGen` does the rest: give it `gate: $gate` and an `Envelope` with a
|
||||
/// `releaseNode`, so it holds at the sustain level while the gate is open and plays its release
|
||||
/// segment when the gate closes, then frees itself via `doneAction: .freeNode`. Nothing truncates
|
||||
/// the release — the pattern supplies the gate and the note's sustain, and the voice's own envelope
|
||||
/// owns the release.
|
||||
///
|
||||
/// ```swift
|
||||
/// final class PluckVoice: SynthesizerBase, EventGated {
|
||||
/// @LiveParam var freq: Double = 440.0
|
||||
/// @LiveParam var amp: Double = 0.2
|
||||
/// @LiveParam var gate: Double = 1.0 // defaults OPEN so the attack fires on add
|
||||
///
|
||||
/// var eventGate: ParameterNode { $gate }
|
||||
///
|
||||
/// override func build() {
|
||||
/// let env: Envelope = Envelope(
|
||||
/// levels: [0.0, 1.0, 0.0],
|
||||
/// durations: [0.01, 0.3],
|
||||
/// curves: [.welch, .welch],
|
||||
/// releaseNode: 1 // hold at levels[1] while gate > 0
|
||||
/// )
|
||||
/// let shaped: EnvelopeGen.Audio = EnvelopeGen.Audio(
|
||||
/// envelope: env, gate: $gate, doneAction: .freeNode
|
||||
/// )
|
||||
/// output(bus: 0, source: OscSin.Audio(freq: $freq, mul: $amp) * shaped)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Conformance is optional and is an alternative to ``EventSustainAware``. A gated voice is driven
|
||||
/// by its gate (held open for the note, closed at `sustain`); a sustain-aware voice instead builds
|
||||
/// a fixed-duration self-timed envelope from a `sustain`-in-seconds hand-off. Either way an event
|
||||
/// pattern never hard-removes the voice — it trusts the voice to free itself via `doneAction`. A
|
||||
/// voice conforming to **neither** is removed by the pattern after `sustain + releaseTail` beats.
|
||||
///
|
||||
/// - SeeAlso: ``EventSustainAware``, ``EventPattern``, ``MonoEventPattern``
|
||||
public protocol EventGated: Synthesizer {
|
||||
|
||||
/// The gate parameter node — project a `@LiveParam` with `$`, e.g. `$gate`.
|
||||
///
|
||||
/// Read on the main actor. Default the backing parameter **open** (`≥ 1.0`) so the voice's
|
||||
/// attack fires the moment it is added. The event pattern sets it to `0` when the note's
|
||||
/// sustain elapses, driving the voice's `EnvelopeGen` release.
|
||||
@MainActor var eventGate: ParameterNode { get }
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
// EventPattern.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Default fraction of each event's duration for which a voice sounds.
|
||||
private let eventPatternDefaultLegato: Double = 0.9
|
||||
|
||||
/// Default playback tempo in beats per minute.
|
||||
private let eventPatternDefaultTempo: Double = 120.0
|
||||
|
||||
/// The heart of Lyrebird's event-driven playback: binds named value ``Pattern``s to a voice's
|
||||
/// `@LiveParam` parameters and plays them as a timed stream of voices.
|
||||
///
|
||||
/// Each event pulls one value from every bound pattern plus the duration pattern, makes a
|
||||
/// fresh voice, writes the pulled values into its parameters, adds it to the engine, and reaps
|
||||
/// it — then waits the event's duration before the next event. The stream ends when the
|
||||
/// duration pattern or **any** bound pattern is exhausted (any exhausted input ends it),
|
||||
/// optionally repeating the whole bound set.
|
||||
///
|
||||
/// **How a voice ends** follows one rule: the voice owns its envelope; the pattern owns
|
||||
/// timing. A voice conforming to ``EventGated`` is held open by its gate for the note and gets a
|
||||
/// note-off (gate → `0`) after `sustain` beats, so its envelope release plays out and frees it. A
|
||||
/// voice conforming to ``EventSustainAware`` instead builds a fixed-duration self-freeing envelope
|
||||
/// from the sustain it is handed. In **both** cases the pattern never hard-removes the voice — it
|
||||
/// trusts `doneAction`, so the release is never cut. A voice conforming to neither is removed after
|
||||
/// `sustain + releaseTail` beats (see ``releaseTail(_:)``).
|
||||
///
|
||||
/// Binding is **typed**: a `ReferenceWritableKeyPath` into a concrete voice type, checked at
|
||||
/// compile time. There is no untyped event dictionary and no default-event prototype — you pass
|
||||
/// the values you actually want, in the units the voice expects.
|
||||
///
|
||||
/// ```swift
|
||||
/// final class PluckVoice: SynthesizerBase, EventSustainAware {
|
||||
/// @LiveParam var freq: Double = 440.0
|
||||
/// @LiveParam var amp: Double = 0.2
|
||||
/// // … build() wires an envelope that frees the voice; setEventSustain shapes it …
|
||||
/// }
|
||||
///
|
||||
/// let handle: EventPatternHandle = EventPattern(make: { PluckVoice() })
|
||||
/// .bind(\.freq, .sequence([440.0, 550.0, 660.0]))
|
||||
/// .bind(\.amp, .uniformRandom(low: 0.1, high: 0.4))
|
||||
/// .dur(.sequence([0.25, 0.25, 0.5]))
|
||||
/// .legato(0.9)
|
||||
/// .tempo(132.0)
|
||||
/// .play(on: engine)
|
||||
/// ```
|
||||
///
|
||||
/// Playback runs on a background `LyrebirdTask`; voice construction and parameter writes hop
|
||||
/// to the main thread (`@LiveParam` and `SynthesizerBase` are main-actor-isolated). The
|
||||
/// returned ``EventPatternHandle`` stops playback or waits for a finite stream to finish.
|
||||
///
|
||||
/// Not thread-safe: configure (`bind`/`dur`/…) before `play`, and drive a single `play` at a
|
||||
/// time. Its patterns are pulled by exactly one playback task.
|
||||
///
|
||||
/// - SeeAlso: ``EventGated``, ``EventSustainAware``, ``EventPatternHandle``, ``Pattern``
|
||||
public final class EventPattern<V: Synthesizer>: @unchecked Sendable {
|
||||
|
||||
/// Factory for a fresh voice per event. Called on the main thread.
|
||||
private let _make: @MainActor () -> V
|
||||
|
||||
/// `keyPath → Pattern` bindings, applied in order each event.
|
||||
private var _bindings: [EventBinding<V>] = []
|
||||
|
||||
/// Duration (delta) pattern in beats. Defaults to an infinite stream of `1.0`.
|
||||
private var _durPattern: Pattern<Double> = Pattern<Double>.sequence([1.0])
|
||||
|
||||
/// Fraction of each duration a voice sustains (`sustain = delta * legato`).
|
||||
private var _legato: Double = eventPatternDefaultLegato
|
||||
|
||||
/// Extra beats of grace after `sustain` before a **plain** voice is removed, so its envelope
|
||||
/// release tail is not hard-cut. Unused by ``EventGated`` / ``EventSustainAware`` voices, which
|
||||
/// free themselves.
|
||||
private var _releaseTail: Double = 0.0
|
||||
|
||||
/// Number of times to play the whole bound set (resetting between). `1` = once.
|
||||
private var _repeats: Int = 1
|
||||
|
||||
/// Playback tempo in beats per minute.
|
||||
private var _tempo: Double = eventPatternDefaultTempo
|
||||
|
||||
/// Creates an event pattern.
|
||||
///
|
||||
/// - Parameter make: Factory returning a fresh voice for each event. Runs on the main
|
||||
/// thread. Construct and return a new instance — do not reuse one across events (see
|
||||
/// `MonoEventPattern` for single-voice reuse).
|
||||
public init(make: @escaping @MainActor () -> V) {
|
||||
_make = make
|
||||
}
|
||||
|
||||
// MARK: - Builder
|
||||
|
||||
/// Binds a voice parameter to a value pattern.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - keyPath: Writable key path into a `@LiveParam Double` on the voice (`\.freq`).
|
||||
/// - pattern: Value source; one value is pulled per event.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func bind(
|
||||
_ keyPath: ReferenceWritableKeyPath<V, Double>,
|
||||
_ pattern: Pattern<Double>
|
||||
) -> Self {
|
||||
_bindings.append(EventBinding(keyPath: keyPath, pattern: pattern))
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets the duration (delta) pattern, in beats. One value is pulled per event; the stream
|
||||
/// ends if it is exhausted.
|
||||
///
|
||||
/// - Parameter pattern: Beats-per-event value source.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func dur(_ pattern: Pattern<Double>) -> Self {
|
||||
_durPattern = pattern
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets the legato factor: a voice sustains for `delta * legato` beats. Values above `1.0`
|
||||
/// overlap successive voices.
|
||||
///
|
||||
/// - Parameter value: Sustain fraction of each duration. Must be `≥ 0`. Defaults to `0.9`.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func legato(_ value: Double) -> Self {
|
||||
precondition(value >= 0, "legato must be non-negative")
|
||||
_legato = value
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets extra beats of grace after `sustain` before a **plain** voice is removed, so its
|
||||
/// envelope release tail is not cut short.
|
||||
///
|
||||
/// Affects only voices that conform to **neither** ``EventGated`` nor ``EventSustainAware`` —
|
||||
/// those free themselves (gate release or a self-timed envelope) and are never hard-removed, so
|
||||
/// this value does nothing for them.
|
||||
///
|
||||
/// - Parameter beats: Grace in beats. Defaults to `0.0`.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func releaseTail(_ beats: Double) -> Self {
|
||||
_releaseTail = beats
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets how many times to play the whole bound set (resetting all patterns between).
|
||||
///
|
||||
/// - Parameter count: Number of passes. `1` plays once; pass `Int.max` for effectively
|
||||
/// endless playback. Values below `1` play nothing.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func repeats(_ count: Int) -> Self {
|
||||
_repeats = count
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets the playback tempo.
|
||||
///
|
||||
/// - Parameter bpm: Beats per minute. Must be positive. Defaults to `120.0`.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func tempo(_ bpm: Double) -> Self {
|
||||
precondition(bpm > 0, "tempo must be positive")
|
||||
_tempo = bpm
|
||||
return self
|
||||
}
|
||||
|
||||
// MARK: - Play
|
||||
|
||||
/// Starts playback on a background task after an optional lead-in, and returns a handle to
|
||||
/// control it.
|
||||
///
|
||||
/// Snapshots the current configuration into an `EventStream` **before** starting the
|
||||
/// task, so later builder calls cannot race with the running stream.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: Engine the voices are added to.
|
||||
/// - beats: Lead-in before the first event, in beats at this pattern's tempo. `0` starts
|
||||
/// immediately. The task is live (waiting) for the lead-in, so `stop()` works during it.
|
||||
/// - Returns: A handle to stop playback or await a finite stream.
|
||||
@discardableResult
|
||||
@MainActor public func play(
|
||||
on engine: SynthesisEngine,
|
||||
startAfterBeats beats: Double
|
||||
) -> EventPatternHandle {
|
||||
let task: LyrebirdTask = makeTask(stream: makeEventStream(), startOffsetBeats: beats)
|
||||
task.start(engine: engine)
|
||||
return EventPatternHandle(tasks: [task])
|
||||
}
|
||||
|
||||
/// Builds a fresh `EventStream` from the current configuration. Each call returns an
|
||||
/// independent stream (patterns are shared by reference, so reuse is single-consumer).
|
||||
@MainActor internal func makeEventStream() -> EventStream<V> {
|
||||
EventStream(
|
||||
make: _make,
|
||||
bindings: _bindings,
|
||||
durPattern: _durPattern,
|
||||
legato: _legato,
|
||||
repeats: _repeats,
|
||||
tempo: _tempo
|
||||
)
|
||||
}
|
||||
|
||||
/// Builds the driving task for a pre-snapshot `stream`, without starting it. The body
|
||||
/// captures the snapshot, not `self`, so builder mutation after `play` cannot affect it.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - stream: The pre-snapshot event stream to drive.
|
||||
/// - startOffsetBeats: Lead-in in beats before the first event (`0` = none).
|
||||
@MainActor internal func makeTask(
|
||||
stream: EventStream<V>,
|
||||
startOffsetBeats: Double
|
||||
) -> LyrebirdTask {
|
||||
let tempoBPM: Double = _tempo
|
||||
let releaseTailBeats: Double = _releaseTail
|
||||
return LyrebirdTask { ctx in
|
||||
ctx.tempo = tempoBPM
|
||||
do {
|
||||
// Lead-in: wait before the first event so a staggered child enters on the group's
|
||||
// shared start grid. The task is live (waiting) throughout, so stop() still works.
|
||||
if startOffsetBeats > 0 {
|
||||
try ctx.wait(beats: startOffsetBeats)
|
||||
}
|
||||
while let event: ResolvedEvent = ctx.onMain({ stream.nextResolved() }) {
|
||||
ctx.add(event.voice)
|
||||
if let gate: ParameterNode = event.gate {
|
||||
// Gate note-off: the gate is already open (the voice defaults it open, so the
|
||||
// attack fires on add); close it after `sustain` so the voice's envelope
|
||||
// release plays out and frees it. Non-blocking and overlap-safe, so a
|
||||
// legato > 1 voice's note-off lands after the next voice has already begun.
|
||||
ctx.set(gate, to: 0.0, afterBeats: event.sustain)
|
||||
} else if !event.selfFreeing {
|
||||
// Plain voice (neither EventGated nor EventSustainAware): it will not free
|
||||
// itself, so reap it after its tail. This is the only path releaseTail affects.
|
||||
ctx.remove(event.voice, afterBeats: event.sustain + releaseTailBeats)
|
||||
}
|
||||
// EventSustainAware (selfFreeing, no gate): trust its self-timed, self-freeing
|
||||
// envelope — no removal, so the release is never hard-cut.
|
||||
try ctx.wait(beats: event.delta)
|
||||
}
|
||||
// Finite stream done: let the final voices' gate-closes fire at their proper times
|
||||
// before the body returns, so trailing note-offs are not dropped.
|
||||
try ctx.waitForScheduledSets()
|
||||
} catch LyrebirdRoutineError.stopped {
|
||||
// Stopped mid-stream: close every outstanding gate now so its voice releases and
|
||||
// self-frees, rather than hanging at the sustain level.
|
||||
ctx._flushScheduledSets()
|
||||
throw LyrebirdRoutineError.stopped
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension EventPattern: EventPatternPlayable {}
|
||||
@@ -0,0 +1,93 @@
|
||||
// EventPatternHandle.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A running event pattern — ``EventPattern``, ``MonoEventPattern`` or ``ParallelEventPattern`` —
|
||||
/// returned by `play(...)`.
|
||||
///
|
||||
/// Holds the background `LyrebirdTask`(s) driving the pattern. Use it to stop playback, ask
|
||||
/// whether anything is still playing, or block until a finite pattern finishes.
|
||||
///
|
||||
/// ```swift
|
||||
/// let handle: EventPatternHandle = pattern.play(on: engine)
|
||||
/// // … later …
|
||||
/// handle.stop()
|
||||
/// ```
|
||||
public final class EventPatternHandle: @unchecked Sendable {
|
||||
|
||||
/// The background tasks driving playback. One for a single ``EventPattern``; several for a
|
||||
/// `ParallelEventPattern`.
|
||||
private let _tasks: [LyrebirdTask]
|
||||
|
||||
/// Wraps the tasks driving an event pattern.
|
||||
///
|
||||
/// - Parameter tasks: The started `LyrebirdTask`(s). Must be non-empty.
|
||||
internal init(tasks: [LyrebirdTask]) {
|
||||
precondition(!tasks.isEmpty, "EventPatternHandle requires at least one task")
|
||||
_tasks = tasks
|
||||
}
|
||||
|
||||
/// Merges several single-pattern handles into one that controls them all — used by
|
||||
/// ``ParallelEventPattern`` so stopping or awaiting the parent covers every child.
|
||||
///
|
||||
/// - Parameter handles: The child handles. Must be non-empty.
|
||||
internal convenience init(merging handles: [EventPatternHandle]) {
|
||||
self.init(tasks: handles.flatMap { $0._tasks })
|
||||
}
|
||||
|
||||
/// `true` while any driving task is still live — running or paused (a paused task has not
|
||||
/// finished and may resume).
|
||||
public var isPlaying: Bool {
|
||||
_tasks.contains { $0.state == .running || $0.state == .paused }
|
||||
}
|
||||
|
||||
/// Stops playback: no further events are spawned. Already-added voices are reaped as they
|
||||
/// would be at a normal stream end — outstanding gate note-offs fire immediately so
|
||||
/// ``EventGated`` voices release and self-free, self-timed ``EventSustainAware`` voices free
|
||||
/// themselves, and plain voices keep their scheduled removal. A ``MonoEventPattern``'s
|
||||
/// persistent voice is gate-closed if ``EventGated``, otherwise removed after its `releaseTail`.
|
||||
/// Idempotent.
|
||||
public func stop() {
|
||||
for task: LyrebirdTask in _tasks {
|
||||
task.stop()
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocks the calling thread until every driving task has finished, then waits an additional
|
||||
/// `releasePadding` seconds.
|
||||
///
|
||||
/// Only returns for a finite pattern (one whose value patterns exhaust, or after ``stop()``).
|
||||
///
|
||||
/// The pattern's task finishes at the **final note-off** — but a voice's envelope release plays
|
||||
/// on after that, on the audio thread. A caller that tears the engine down the instant this
|
||||
/// returns (a CLI demo, an offline render) would cut that tail, clicking the last note. Pass
|
||||
/// `releasePadding` equal to (or a little above) the voices' longest release so the tail rings
|
||||
/// out first. A long-lived app keeps the engine running and the tail decays naturally, so the
|
||||
/// default `0` is right there.
|
||||
///
|
||||
/// Pumps the main run loop while waiting — through the padding too — so main-dispatched engine
|
||||
/// edits (a voice's `doneAction` self-free, say) still land. Never call from a context that
|
||||
/// must stay responsive.
|
||||
///
|
||||
/// - Parameter releasePadding: Extra seconds to wait after the pattern completes, for release
|
||||
/// tails to ring out. Negative values are clamped to `0`. Defaults to `0`.
|
||||
public func waitUntilComplete(releasePadding: Double = 0) {
|
||||
for task: LyrebirdTask in _tasks {
|
||||
task.waitUntilComplete()
|
||||
}
|
||||
let padding: Double = max(0.0, releasePadding)
|
||||
guard padding > 0 else { return }
|
||||
// On the main thread, keep the run loop serviced so dispatched engine ops still drain while
|
||||
// the tail rings; off-main (e.g. a test thread) a plain sleep suffices — the audio decays
|
||||
// on the RT thread regardless.
|
||||
if Thread.isMainThread {
|
||||
RunLoop.current.run(until: Date().addingTimeInterval(padding))
|
||||
} else {
|
||||
Thread.sleep(forTimeInterval: padding)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// EventPatternPlayable.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// A configured event pattern that can be started on an engine, returning a handle.
|
||||
///
|
||||
/// Both ``EventPattern`` (polyphonic) and ``MonoEventPattern`` (monophonic) conform, so a
|
||||
/// ``ParallelEventPattern`` can hold a heterogeneous set of children (`[any EventPatternPlayable]`)
|
||||
/// and start them together.
|
||||
///
|
||||
/// - SeeAlso: ``EventPattern``, ``MonoEventPattern``, ``ParallelEventPattern``
|
||||
public protocol EventPatternPlayable {
|
||||
|
||||
/// Starts playback on a background task after an optional lead-in, and returns a handle.
|
||||
///
|
||||
/// The driving task is live for the whole lead-in (it is simply waiting), so the returned
|
||||
/// handle reports ``EventPatternHandle/isPlaying`` and honours ``EventPatternHandle/stop()``
|
||||
/// during it. The handle must wrap at least one task, even when the configured stream yields
|
||||
/// no events, so that ``ParallelEventPattern`` can merge children's handles unconditionally.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: Engine the voices are added to.
|
||||
/// - beats: Lead-in before the first event, in beats at the pattern's own tempo. `0` starts
|
||||
/// immediately. ``ParallelEventPattern`` uses it to stagger a child's entry on the group's
|
||||
/// shared start grid (see ``ParallelEventPattern/addAfter(beats:eventPattern:)``).
|
||||
/// - Returns: A handle to stop playback or await a finite stream.
|
||||
@MainActor func play(on engine: SynthesisEngine, startAfterBeats beats: Double) -> EventPatternHandle
|
||||
}
|
||||
|
||||
public extension EventPatternPlayable {
|
||||
|
||||
/// Starts playback immediately — no lead-in. Equivalent to `play(on:startAfterBeats: 0)`.
|
||||
///
|
||||
/// - Parameter engine: Engine the voices are added to.
|
||||
/// - Returns: A handle to stop playback or await a finite stream.
|
||||
@discardableResult
|
||||
@MainActor func play(on engine: SynthesisEngine) -> EventPatternHandle {
|
||||
play(on: engine, startAfterBeats: 0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// EventQuantum.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// When a pattern handed to an ``EventConductor`` should begin, expressed against the conductor's
|
||||
/// shared beat clock.
|
||||
///
|
||||
/// A conductor quantises only the **entry** of each pattern: the first event lands on the chosen
|
||||
/// boundary, after which the pattern runs its own relative timing at its own tempo. The conductor
|
||||
/// resolves the quantum to a target beat on its own clock and holds the pattern until that beat
|
||||
/// arrives, then starts it immediately — so entry aligns to the conductor's grid regardless of the
|
||||
/// pattern's own tempo.
|
||||
///
|
||||
/// - SeeAlso: ``EventConductor``
|
||||
public enum EventQuantum: Sendable {
|
||||
|
||||
/// Begin at the next service tick — effectively immediately (within the conductor's poll
|
||||
/// granularity), with no grid alignment.
|
||||
case now
|
||||
|
||||
/// Begin on the next whole beat strictly after now.
|
||||
case nextBeat
|
||||
|
||||
/// Begin on the next multiple of `ofBeats` strictly after now — e.g. `4.0` is the next bar in
|
||||
/// 4/4, `2.0` the next half-bar. Must be positive.
|
||||
case nextMultiple(ofBeats: Double)
|
||||
|
||||
/// Begin at an absolute beat on the conductor's timeline. A beat already in the past is due
|
||||
/// immediately and starts at the next service tick.
|
||||
case atBeat(Double)
|
||||
|
||||
/// Begin `ofBeats` beats from now — a relative lead-in. The direct analogue of
|
||||
/// ``ParallelEventPattern/addAfter(beats:eventPattern:)``. A negative value starts now.
|
||||
case afterBeats(Double)
|
||||
|
||||
/// Traps if the quantum carries an invalid parameter. Called by ``EventConductor/add(_:quantize:)``
|
||||
/// on the caller's thread so a bad value surfaces at the call site, not later on the conductor's
|
||||
/// background task. ``targetBeat(from:)`` keeps its own check as a backstop.
|
||||
internal func validate() {
|
||||
switch self {
|
||||
case .now, .nextBeat:
|
||||
break
|
||||
case .nextMultiple(let ofBeats):
|
||||
precondition(ofBeats > 0 && ofBeats.isFinite, "nextMultiple ofBeats must be positive and finite")
|
||||
case .atBeat(let beat):
|
||||
precondition(beat.isFinite, "atBeat must be finite")
|
||||
case .afterBeats(let ofBeats):
|
||||
precondition(ofBeats.isFinite, "afterBeats must be finite")
|
||||
}
|
||||
}
|
||||
|
||||
/// The target beat this quantum resolves to, given the conductor's current beat position.
|
||||
///
|
||||
/// - Parameter beatNow: The conductor clock's current beat at service time.
|
||||
/// - Returns: The beat at which the pattern should enter. The conductor holds the pattern until
|
||||
/// its clock reaches this beat, then starts it.
|
||||
internal func targetBeat(from beatNow: Double) -> Double {
|
||||
switch self {
|
||||
case .now:
|
||||
return beatNow
|
||||
case .nextBeat:
|
||||
return beatNow.rounded(.down) + 1.0
|
||||
case .nextMultiple(let ofBeats):
|
||||
precondition(ofBeats > 0, "nextMultiple ofBeats must be positive")
|
||||
return ((beatNow / ofBeats).rounded(.down) + 1.0) * ofBeats
|
||||
case .atBeat(let beat):
|
||||
return beat
|
||||
case .afterBeats(let ofBeats):
|
||||
return beatNow + max(0.0, ofBeats)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// EventRetriggerable.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Opt-in articulation hook for the single reused voice of a ``MonoEventPattern``.
|
||||
///
|
||||
/// A ``MonoEventPattern`` holds one voice and updates its parameters per event. By default the
|
||||
/// voice is not re-struck between events — it plays continuously with its parameters gliding. A
|
||||
/// voice that conforms to `EventRetriggerable` additionally re-articulates — closing and reopening
|
||||
/// its envelope — on each event after the first: ``MonoEventPattern`` calls ``retrigger()`` on
|
||||
/// every event *after* the first (the first is articulated by `build()` when the voice is added),
|
||||
/// so the voice can restart its amplitude envelope for a fresh attack.
|
||||
///
|
||||
/// Conformance is optional. A ``MonoEventPattern`` voice that does not conform simply has its
|
||||
/// parameters updated each event with no re-articulation.
|
||||
///
|
||||
/// - SeeAlso: ``MonoEventPattern``, ``EventSustainAware``
|
||||
public protocol EventRetriggerable: Synthesizer {
|
||||
|
||||
/// Re-articulates the voice for a new event — typically restarting its amplitude envelope.
|
||||
///
|
||||
/// Called on the main actor, once per event after the first, before the event's duration is
|
||||
/// waited out. When the voice also conforms to ``EventSustainAware``, its
|
||||
/// ``EventSustainAware/setEventSustain(seconds:)`` is called *before* `retrigger()`, so an
|
||||
/// envelope restarted here is already sized to this event's sustain.
|
||||
@MainActor func retrigger()
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// EventStream.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Minutes-to-seconds divisor for the beats→seconds conversion. Module scope (shared by the
|
||||
/// event-stream variants) because a `static` stored property is not allowed on a generic type.
|
||||
internal let eventStreamSecondsPerMinute: Double = 60.0
|
||||
|
||||
/// The pure per-event pull logic shared by ``EventPattern`` and its variants.
|
||||
///
|
||||
/// An `EventStream` holds the voice factory, the key-path bindings, and the duration pattern,
|
||||
/// and yields one resolved event at a time via ``next()``: it makes a voice, writes every
|
||||
/// bound parameter, hands the voice its sustain, and returns it with the event's timing.
|
||||
/// Exhaustion of the duration pattern or **any** binding ends the current pass; `repeats`
|
||||
/// replays the whole bound set (resetting the patterns between).
|
||||
///
|
||||
/// This type owns no threads and touches no engine — it is the deterministic core that the
|
||||
/// background playback loop drives through `ctx.onMain`. Keeping it separate makes the event
|
||||
/// logic directly unit-testable on the main actor, and lets `MonoEventPattern` /
|
||||
/// `ParallelEventPattern` reuse it.
|
||||
///
|
||||
/// Not thread-safe: pulled by exactly one consumer, on the main actor.
|
||||
///
|
||||
/// `@unchecked Sendable`: the playback loop runs on a background task that *holds* the stream
|
||||
/// reference but only ever calls ``next()`` inside a `ctx.onMain` hop — every access to the
|
||||
/// stream's mutable state happens on the main actor. The reference crosses the actor boundary;
|
||||
/// the state it guards does not.
|
||||
internal final class EventStream<V: Synthesizer>: @unchecked Sendable {
|
||||
|
||||
/// One resolved event: the configured voice, its timing (in beats), and how it is reaped.
|
||||
struct Event {
|
||||
let voice: V
|
||||
let delta: Double
|
||||
let sustain: Double
|
||||
/// The voice's gate node when it conforms to ``EventGated``, else `nil`. The playback loop
|
||||
/// opens it at add and schedules it to `0` after `sustain` beats (gate note-off).
|
||||
let gate: ParameterNode?
|
||||
/// `true` when the voice frees itself (``EventGated`` or ``EventSustainAware``), so the
|
||||
/// loop must **not** hard-remove it; `false` for a plain voice, which is removed after
|
||||
/// `sustain + releaseTail`.
|
||||
let selfFreeing: Bool
|
||||
}
|
||||
|
||||
private let _make: @MainActor () -> V
|
||||
private let _bindings: [EventBinding<V>]
|
||||
private let _durPattern: Pattern<Double>
|
||||
private let _legato: Double
|
||||
private let _tempo: Double
|
||||
private var _repeatsLeft: Int
|
||||
|
||||
/// - Parameters:
|
||||
/// - make: Voice factory, called once per event on the main actor.
|
||||
/// - bindings: Key-path/pattern bindings applied in order each event.
|
||||
/// - durPattern: Duration (delta) pattern in beats.
|
||||
/// - legato: Sustain fraction of each duration (`sustain = delta * legato`).
|
||||
/// - repeats: Number of passes over the whole bound set (`1` = once).
|
||||
/// - tempo: Tempo in BPM, used to convert sustain beats to seconds.
|
||||
init(
|
||||
make: @escaping @MainActor () -> V,
|
||||
bindings: [EventBinding<V>],
|
||||
durPattern: Pattern<Double>,
|
||||
legato: Double,
|
||||
repeats: Int,
|
||||
tempo: Double
|
||||
) {
|
||||
_make = make
|
||||
_bindings = bindings
|
||||
_durPattern = durPattern
|
||||
_legato = legato
|
||||
_tempo = tempo
|
||||
_repeatsLeft = repeats
|
||||
}
|
||||
|
||||
/// Tracks whether the current pass yielded any event, so a pass that produces nothing
|
||||
/// ends the stream instead of looping (guards against an empty pattern with a huge
|
||||
/// `repeats`, which would otherwise spin on the main actor).
|
||||
private var _producedThisPass: Bool = false
|
||||
|
||||
/// Returns the next resolved event, or `nil` when the stream is fully exhausted (all
|
||||
/// passes complete, a pattern ran out on the final pass, or a whole pass produced nothing).
|
||||
@MainActor func next() -> Event? {
|
||||
while _repeatsLeft > 0 {
|
||||
if let event: Event = pullOne() {
|
||||
_producedThisPass = true
|
||||
return event
|
||||
}
|
||||
// Current pass exhausted. A pass that yielded nothing ends the stream — otherwise
|
||||
// an empty pattern with a large `repeats` would loop with no progress.
|
||||
if !_producedThisPass { return nil }
|
||||
_repeatsLeft -= 1
|
||||
if _repeatsLeft > 0 {
|
||||
resetPatterns()
|
||||
_producedThisPass = false
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Pulls one event from the current pass, or `nil` if a pattern is exhausted.
|
||||
///
|
||||
/// Binding values are pulled **before** the voice is made, so an exhausted pattern does
|
||||
/// not leave a constructed-then-discarded voice.
|
||||
@MainActor private func pullOne() -> Event? {
|
||||
guard let delta: Double = _durPattern.next() else { return nil }
|
||||
var values: [Double] = []
|
||||
values.reserveCapacity(_bindings.count)
|
||||
for binding: EventBinding<V> in _bindings {
|
||||
guard let value: Double = binding.nextValue() else { return nil }
|
||||
values.append(value)
|
||||
}
|
||||
let voice: V = _make()
|
||||
for (binding, value): (EventBinding<V>, Double) in zip(_bindings, values) {
|
||||
binding.write(value, to: voice)
|
||||
}
|
||||
// `EventPattern.legato(_:)` preconditions `legato >= 0`; `max(0, …)` keeps the
|
||||
// `setEventSustain` "always ≥ 0" contract defensively for any other construction path.
|
||||
let sustain: Double = max(0.0, delta * _legato)
|
||||
let secondsPerBeat: Double = eventStreamSecondsPerMinute / _tempo
|
||||
let gated: EventGated? = voice as? EventGated
|
||||
let gateNode: ParameterNode? = gated?.eventGate
|
||||
// Gate wins: when a voice is gated, the pattern's scheduled gate note-off drives its
|
||||
// release, so a voice that is *also* `EventSustainAware` is not self-timed as well — the two
|
||||
// release mechanisms never both fire. A non-gated sustain-aware voice self-times as before.
|
||||
let aware: EventSustainAware? = (gated == nil) ? (voice as? EventSustainAware) : nil
|
||||
aware?.setEventSustain(seconds: sustain * secondsPerBeat)
|
||||
// A gated or sustain-aware voice frees itself (gate release / self-timed envelope +
|
||||
// `doneAction`); the loop must not hard-remove it. A plain voice has neither and is reaped.
|
||||
let selfFreeing: Bool = gated != nil || aware != nil
|
||||
return Event(
|
||||
voice: voice,
|
||||
delta: delta,
|
||||
sustain: sustain,
|
||||
gate: gateNode,
|
||||
selfFreeing: selfFreeing
|
||||
)
|
||||
}
|
||||
|
||||
/// Resolves the next event and erases its voice type for the background playback loop, so the
|
||||
/// `@Sendable` task body never names the generic `V`. See ``ResolvedEvent``.
|
||||
@MainActor func nextResolved() -> ResolvedEvent? {
|
||||
guard let e: Event = next() else { return nil }
|
||||
return ResolvedEvent(
|
||||
voice: e.voice,
|
||||
delta: e.delta,
|
||||
sustain: e.sustain,
|
||||
gate: e.gate,
|
||||
selfFreeing: e.selfFreeing
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the duration and all bound patterns to their initial state.
|
||||
@MainActor private func resetPatterns() {
|
||||
_durPattern.reset()
|
||||
for binding: EventBinding<V> in _bindings {
|
||||
binding.reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// EventSustainAware.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Opt-in refinement a voice adopts so an event pattern can tell it how long the current note
|
||||
/// should sound.
|
||||
///
|
||||
/// An event pattern binds parameter values and handles each voice's removal, but it does not
|
||||
/// own the voice's amplitude envelope — the voice does. A voice that conforms to
|
||||
/// `EventSustainAware` is handed the computed sustain (in seconds) for each event, so it can
|
||||
/// shape or trigger a fixed-duration, self-freeing envelope that matches the pattern's timing.
|
||||
/// This keeps the division of labour central to the event-driven system: the pattern owns timing
|
||||
/// and merely supplies the note's sustain; the voice owns its envelope.
|
||||
///
|
||||
/// Conformance is optional. A voice that does not conform still plays — ``EventPattern`` simply
|
||||
/// removes it after `sustain + releaseTail` beats with no envelope hand-off.
|
||||
///
|
||||
/// `EventSustainAware` and ``EventGated`` are **alternative** release mechanisms — a self-timed
|
||||
/// envelope versus a pattern-driven gate note-off. A voice may conform to both, but the **gate
|
||||
/// wins**: when a voice is also ``EventGated``, the pattern drives release through the gate and
|
||||
/// does *not* call ``setEventSustain(seconds:)``, so the two never both fire. `setEventSustain`
|
||||
/// is therefore only invoked on a voice that is not gated.
|
||||
///
|
||||
/// - SeeAlso: ``EventPattern``, ``MonoEventPattern``, ``EventGated``
|
||||
public protocol EventSustainAware: Synthesizer {
|
||||
|
||||
/// Informs the voice how long this note should sustain, in seconds.
|
||||
///
|
||||
/// Called on the main thread. ``EventPattern`` calls it once per voice, just before the
|
||||
/// voice is added to the engine. ``MonoEventPattern`` calls it once per event — before each
|
||||
/// `retrigger()` — on the single persistent voice, so it may already be in the engine. The
|
||||
/// voice typically uses this to configure a fixed-duration envelope whose `doneAction` frees
|
||||
/// or re-articulates it, so it terminates on its own schedule.
|
||||
///
|
||||
/// - Parameter seconds: Note duration in seconds (`sustain` beats converted at the
|
||||
/// pattern's tempo). Always `≥ 0`.
|
||||
@MainActor func setEventSustain(seconds: Double)
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
// MonoEventPattern.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Default fraction of each event's duration for which the voice sounds.
|
||||
private let monoEventPatternDefaultLegato: Double = 0.9
|
||||
|
||||
/// Default playback tempo in beats per minute.
|
||||
private let monoEventPatternDefaultTempo: Double = 120.0
|
||||
|
||||
/// The monophonic event-driven player: binds named value ``Pattern``s to **one persistent
|
||||
/// voice**, updating its parameters per event instead of spawning a new voice each time.
|
||||
///
|
||||
/// The voice is made once (on the main thread) and added to the engine once. Each event pulls
|
||||
/// one value from every bound pattern plus the duration pattern, writes them into the voice's
|
||||
/// `@LiveParam` parameters, optionally re-articulates the voice (``EventRetriggerable``), then
|
||||
/// waits the event's duration. The stream ends when the duration pattern or **any** bound
|
||||
/// pattern is exhausted (the same rule as ``EventPattern``), optionally repeating the whole
|
||||
/// bound set. When the stream ends **or** playback is stopped, a voice conforming to ``EventGated``
|
||||
/// gets a note-off (its gate is closed) so its envelope release plays out and frees it; any other
|
||||
/// voice is removed after ``releaseTail(_:)`` beats.
|
||||
///
|
||||
/// A voice conforming to ``EventRetriggerable`` is re-struck (``EventRetriggerable/retrigger()``)
|
||||
/// on every event after the first — per-event articulation. A voice that does not conform plays
|
||||
/// continuously with its parameters gliding per event — no re-strike.
|
||||
///
|
||||
/// > Important: unlike ``EventPattern``, the voice here is **persistent** — added once and reused
|
||||
/// > for every event. Give it a sustaining envelope that holds across events. The cleanest shape is
|
||||
/// > an ``EventGated`` voice: a gated `EnvelopeGen` with a `releaseNode` holds open while the gate
|
||||
/// > is up and frees via `doneAction: .freeNode` only when the gate closes at stream end, and
|
||||
/// > ``EventRetriggerable/retrigger()`` re-strikes it per event. What you must **not** give it is an
|
||||
/// > *ungated* one-shot self-freeing envelope: a voice that frees itself after the first event's
|
||||
/// > sustain is gone before the next event, and the stream falls silent. Those belong with
|
||||
/// > ``EventPattern``, which spawns a fresh voice per event.
|
||||
///
|
||||
/// ```swift
|
||||
/// let handle: EventPatternHandle = MonoEventPattern(make: { LeadVoice() })
|
||||
/// .bind(\.freq, .sequence([440.0, 550.0, 660.0]))
|
||||
/// .dur(.sequence([0.25, 0.25, 0.5]))
|
||||
/// .tempo(132.0)
|
||||
/// .play(on: engine)
|
||||
/// ```
|
||||
///
|
||||
/// Playback runs on a background `LyrebirdTask`; voice construction and parameter writes hop to
|
||||
/// the main thread. The returned ``EventPatternHandle`` stops playback or waits for a finite
|
||||
/// stream to finish.
|
||||
///
|
||||
/// Not thread-safe: configure (`bind`/`dur`/…) before `play`, and drive a single `play` at a
|
||||
/// time. Its patterns are pulled by exactly one playback task.
|
||||
///
|
||||
/// - SeeAlso: ``EventPattern``, ``EventGated``, ``EventRetriggerable``, ``EventSustainAware``, ``EventPatternHandle``
|
||||
public final class MonoEventPattern<V: Synthesizer>: @unchecked Sendable {
|
||||
|
||||
/// Factory for the single persistent voice. Called once, on the main thread.
|
||||
private let _make: @MainActor () -> V
|
||||
|
||||
/// `keyPath → Pattern` bindings, applied in order each event.
|
||||
private var _bindings: [EventBinding<V>] = []
|
||||
|
||||
/// Duration (delta) pattern in beats. Defaults to an infinite stream of `1.0`.
|
||||
private var _durPattern: Pattern<Double> = Pattern<Double>.sequence([1.0])
|
||||
|
||||
/// Fraction of each duration the voice sustains (`sustain = delta * legato`), handed to a
|
||||
/// voice conforming to ``EventSustainAware``.
|
||||
private var _legato: Double = monoEventPatternDefaultLegato
|
||||
|
||||
/// Extra beats of grace after the final event before a **non-gated** voice is removed, so its
|
||||
/// release tail is not hard-cut. Unused by an ``EventGated`` voice, which is note-off'd via its
|
||||
/// gate and frees itself.
|
||||
private var _releaseTail: Double = 0.0
|
||||
|
||||
/// Number of times to play the whole bound set (resetting between). `1` = once.
|
||||
private var _repeats: Int = 1
|
||||
|
||||
/// Playback tempo in beats per minute.
|
||||
private var _tempo: Double = monoEventPatternDefaultTempo
|
||||
|
||||
/// Creates a monophonic event pattern.
|
||||
///
|
||||
/// - Parameter make: Factory returning the single persistent voice, made once on the main
|
||||
/// thread. For a fresh voice per event, use ``EventPattern`` instead.
|
||||
public init(make: @escaping @MainActor () -> V) {
|
||||
_make = make
|
||||
}
|
||||
|
||||
// MARK: - Builder
|
||||
|
||||
/// Binds a voice parameter to a value pattern.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - keyPath: Writable key path into a `@LiveParam Double` on the voice (`\.freq`).
|
||||
/// - pattern: Value source; one value is pulled per event.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func bind(
|
||||
_ keyPath: ReferenceWritableKeyPath<V, Double>,
|
||||
_ pattern: Pattern<Double>
|
||||
) -> Self {
|
||||
_bindings.append(EventBinding(keyPath: keyPath, pattern: pattern))
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets the duration (delta) pattern, in beats. One value is pulled per event; the stream
|
||||
/// ends if it is exhausted.
|
||||
///
|
||||
/// - Parameter pattern: Beats-per-event value source.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func dur(_ pattern: Pattern<Double>) -> Self {
|
||||
_durPattern = pattern
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets the legato factor: the sustain handed to an ``EventSustainAware`` voice is
|
||||
/// `delta * legato` beats.
|
||||
///
|
||||
/// - Parameter value: Sustain fraction of each duration. Must be `≥ 0`. Defaults to `0.9`.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func legato(_ value: Double) -> Self {
|
||||
precondition(value >= 0, "legato must be non-negative")
|
||||
_legato = value
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets extra beats of grace after the final event before a **non-gated** voice is removed, so
|
||||
/// its envelope release tail is not cut short.
|
||||
///
|
||||
/// Unused by an ``EventGated`` voice: that voice is note-off'd via its gate at stream end and
|
||||
/// frees itself, so its release is never hard-cut regardless of this value.
|
||||
///
|
||||
/// - Parameter beats: Grace in beats. Defaults to `0.0`.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func releaseTail(_ beats: Double) -> Self {
|
||||
_releaseTail = beats
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets how many times to play the whole bound set (resetting all patterns between).
|
||||
///
|
||||
/// - Parameter count: Number of passes. `1` plays once; pass `Int.max` for effectively
|
||||
/// endless playback. Values below `1` play nothing.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func repeats(_ count: Int) -> Self {
|
||||
_repeats = count
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets the playback tempo.
|
||||
///
|
||||
/// - Parameter bpm: Beats per minute. Must be positive. Defaults to `120.0`.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func tempo(_ bpm: Double) -> Self {
|
||||
precondition(bpm > 0, "tempo must be positive")
|
||||
_tempo = bpm
|
||||
return self
|
||||
}
|
||||
|
||||
// MARK: - Play
|
||||
|
||||
/// Starts playback on a background task and returns a handle to control it.
|
||||
///
|
||||
/// Makes the persistent voice and snapshots the current configuration into a
|
||||
/// `MonoEventStream` **before** starting the task, so later builder calls cannot race with
|
||||
/// the running stream.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: Engine the voice is added to.
|
||||
/// - beats: Lead-in before the first event, in beats at this pattern's tempo. `0` starts
|
||||
/// immediately. The task is live (waiting) for the lead-in, so `stop()` works during it.
|
||||
/// - Returns: A handle to stop playback or await a finite stream.
|
||||
@discardableResult
|
||||
@MainActor public func play(
|
||||
on engine: SynthesisEngine,
|
||||
startAfterBeats beats: Double
|
||||
) -> EventPatternHandle {
|
||||
let task: LyrebirdTask = makeTask(stream: makeEventStream(), startOffsetBeats: beats)
|
||||
task.start(engine: engine)
|
||||
return EventPatternHandle(tasks: [task])
|
||||
}
|
||||
|
||||
/// Makes the persistent voice and builds a fresh `MonoEventStream` from the current
|
||||
/// configuration. Each call makes an independent voice and stream (patterns are shared by
|
||||
/// reference, so reuse is single-consumer).
|
||||
@MainActor internal func makeEventStream() -> MonoEventStream<V> {
|
||||
MonoEventStream(
|
||||
voice: _make(),
|
||||
bindings: _bindings,
|
||||
durPattern: _durPattern,
|
||||
legato: _legato,
|
||||
repeats: _repeats,
|
||||
tempo: _tempo
|
||||
)
|
||||
}
|
||||
|
||||
/// Builds the driving task for a pre-snapshot `stream`, without starting it. The body
|
||||
/// captures the snapshot, not `self`, so builder mutation after `play` cannot affect it.
|
||||
/// The voice is added on the first event and removed once the stream ends.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - stream: The pre-snapshot event stream to drive.
|
||||
/// - startOffsetBeats: Lead-in in beats before the first event (`0` = none).
|
||||
@MainActor internal func makeTask(
|
||||
stream: MonoEventStream<V>,
|
||||
startOffsetBeats: Double
|
||||
) -> LyrebirdTask {
|
||||
let tempoBPM: Double = _tempo
|
||||
let releaseTailBeats: Double = _releaseTail
|
||||
return LyrebirdTask { ctx in
|
||||
ctx.tempo = tempoBPM
|
||||
// Lead-in before the first event (0 = none). Thrown `stopped` here skips straight to
|
||||
// the defer, which leaks nothing — the voice has not been added yet.
|
||||
if startOffsetBeats > 0 {
|
||||
try ctx.wait(beats: startOffsetBeats)
|
||||
}
|
||||
// The voice is carried on each event (type-erased to `any Synthesizer`) rather than
|
||||
// captured from outside the `@Sendable` body — the body must not name the non-Sendable
|
||||
// generic `V`. It is the same instance every event.
|
||||
var addedVoice: (any Synthesizer)? = nil
|
||||
// The persistent voice's gate node, captured on the first event when it is EventGated.
|
||||
var gateNode: ParameterNode? = nil
|
||||
// Tear the voice down when the body exits — on normal completion *and* when `stop()`
|
||||
// makes `ctx.wait` throw `LyrebirdRoutineError.stopped`. A trailing statement after
|
||||
// the loop would be skipped on the throw, leaking the persistent voice.
|
||||
defer {
|
||||
if let gate: ParameterNode = gateNode {
|
||||
// Gated voice: close the gate so its envelope release plays out and frees it
|
||||
// (no hard-remove, so the release is not cut). Atomic store, safe on this thread.
|
||||
gate.value = 0.0
|
||||
} else if let voice: any Synthesizer = addedVoice {
|
||||
// Non-gated voice: reap after its tail.
|
||||
ctx.remove(voice, afterBeats: releaseTailBeats)
|
||||
}
|
||||
}
|
||||
while let event: ResolvedEvent = ctx.onMain({ stream.nextResolved() }) {
|
||||
if addedVoice == nil {
|
||||
ctx.add(event.voice)
|
||||
addedVoice = event.voice
|
||||
gateNode = event.gate
|
||||
}
|
||||
try ctx.wait(beats: event.delta)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension MonoEventPattern: EventPatternPlayable {}
|
||||
@@ -0,0 +1,157 @@
|
||||
// MonoEventStream.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// The pure per-event pull logic for ``MonoEventPattern`` — the single-voice counterpart of
|
||||
/// `EventStream`.
|
||||
///
|
||||
/// Unlike `EventStream`, which makes a fresh voice per event, a `MonoEventStream` writes each
|
||||
/// event's values into **one persistent voice** (created once, before playback). ``next()``
|
||||
/// pulls one value from the duration pattern and every binding, writes them into the voice,
|
||||
/// re-articulates the voice on each event after the first (when it conforms to
|
||||
/// ``EventRetriggerable``), hands it the event sustain (when it conforms to
|
||||
/// ``EventSustainAware``), and returns the event timing. Exhaustion of the duration pattern or
|
||||
/// **any** binding ends the current pass; `repeats` replays the whole bound set.
|
||||
///
|
||||
/// This type owns no threads and touches no engine — it is the deterministic core the
|
||||
/// background playback loop drives through `ctx.onMain`, directly unit-testable on the main
|
||||
/// actor. The repeat/exhaustion bookkeeping mirrors `EventStream`; the only difference is that
|
||||
/// values are written into the reused voice rather than a freshly made one.
|
||||
///
|
||||
/// Not thread-safe: pulled by exactly one consumer, on the main actor.
|
||||
///
|
||||
/// `@unchecked Sendable`: the playback loop runs on a background task that *holds* the stream
|
||||
/// reference but only ever calls ``next()`` inside a `ctx.onMain` hop — every access to the
|
||||
/// stream's mutable state (and to the voice) happens on the main actor. The reference crosses
|
||||
/// the actor boundary; the state it guards does not.
|
||||
internal final class MonoEventStream<V: Synthesizer>: @unchecked Sendable {
|
||||
|
||||
/// One resolved event: the persistent voice (the same instance every event) and the beats to
|
||||
/// wait before the next event. The voice is carried here so the playback loop can add/remove
|
||||
/// it without capturing a non-`Sendable` value across the task boundary. Sustain is applied
|
||||
/// to the voice inside ``next()`` (via `setEventSustain`), so it is not carried out.
|
||||
struct Event {
|
||||
let voice: V
|
||||
let delta: Double
|
||||
/// The persistent voice's gate node when it conforms to ``EventGated``, else `nil`. The
|
||||
/// same node every event (one persistent voice); the playback loop reads it once, on the
|
||||
/// first event, to drive the end-of-stream note-off.
|
||||
let gate: ParameterNode?
|
||||
}
|
||||
|
||||
/// The single persistent voice every event writes into.
|
||||
let voice: V
|
||||
|
||||
private let _bindings: [EventBinding<V>]
|
||||
private let _durPattern: Pattern<Double>
|
||||
private let _legato: Double
|
||||
private let _tempo: Double
|
||||
private var _repeatsLeft: Int
|
||||
|
||||
/// `false` until the first event has been produced, so re-articulation is skipped on the
|
||||
/// first event (the voice's `build()` articulates it when it is added).
|
||||
private var _hasArticulated: Bool = false
|
||||
|
||||
/// Tracks whether the current pass yielded any event, so a pass that produces nothing ends
|
||||
/// the stream instead of looping (guards an empty pattern with a huge `repeats`).
|
||||
private var _producedThisPass: Bool = false
|
||||
|
||||
/// - Parameters:
|
||||
/// - voice: The persistent voice every event writes into. Created on the main actor.
|
||||
/// - bindings: Key-path/pattern bindings applied in order each event.
|
||||
/// - durPattern: Duration (delta) pattern in beats.
|
||||
/// - legato: Sustain fraction of each duration (`sustain = delta * legato`).
|
||||
/// - repeats: Number of passes over the whole bound set (`1` = once).
|
||||
/// - tempo: Tempo in BPM, used to convert sustain beats to seconds.
|
||||
init(
|
||||
voice: V,
|
||||
bindings: [EventBinding<V>],
|
||||
durPattern: Pattern<Double>,
|
||||
legato: Double,
|
||||
repeats: Int,
|
||||
tempo: Double
|
||||
) {
|
||||
self.voice = voice
|
||||
_bindings = bindings
|
||||
_durPattern = durPattern
|
||||
_legato = legato
|
||||
_tempo = tempo
|
||||
_repeatsLeft = repeats
|
||||
}
|
||||
|
||||
/// Returns the next resolved event, or `nil` when the stream is fully exhausted (all passes
|
||||
/// complete, a pattern ran out on the final pass, or a whole pass produced nothing).
|
||||
@MainActor func next() -> Event? {
|
||||
while _repeatsLeft > 0 {
|
||||
if let event: Event = pullOne() {
|
||||
_producedThisPass = true
|
||||
return event
|
||||
}
|
||||
if !_producedThisPass { return nil }
|
||||
_repeatsLeft -= 1
|
||||
if _repeatsLeft > 0 {
|
||||
resetPatterns()
|
||||
_producedThisPass = false
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Pulls one event from the current pass and writes it into the persistent voice, or `nil`
|
||||
/// if a pattern is exhausted. Values are pulled **before** they are written, so an exhausted
|
||||
/// pattern leaves the voice's parameters untouched for that aborted event.
|
||||
@MainActor private func pullOne() -> Event? {
|
||||
guard let delta: Double = _durPattern.next() else { return nil }
|
||||
var values: [Double] = []
|
||||
values.reserveCapacity(_bindings.count)
|
||||
for binding: EventBinding<V> in _bindings {
|
||||
guard let value: Double = binding.nextValue() else { return nil }
|
||||
values.append(value)
|
||||
}
|
||||
for (binding, value): (EventBinding<V>, Double) in zip(_bindings, values) {
|
||||
binding.write(value, to: voice)
|
||||
}
|
||||
let sustain: Double = max(0.0, delta * _legato)
|
||||
let secondsPerBeat: Double = eventStreamSecondsPerMinute / _tempo
|
||||
let gateNode: ParameterNode? = (voice as? EventGated)?.eventGate
|
||||
// Gate wins: a gated voice releases via its gate note-off, so it is not also self-timed even
|
||||
// if it conforms to `EventSustainAware`. For a non-gated sustain-aware voice, hand over this
|
||||
// event's sustain *before* re-articulating, so a voice that sizes its restarted envelope to
|
||||
// the sustain uses this event's value, not the previous one's.
|
||||
if gateNode == nil, let aware: EventSustainAware = voice as? EventSustainAware {
|
||||
aware.setEventSustain(seconds: sustain * secondsPerBeat)
|
||||
}
|
||||
// Re-articulate every event after the first; the first is articulated by `build()` when
|
||||
// the voice is added to the engine.
|
||||
if _hasArticulated, let retriggerable: EventRetriggerable = voice as? EventRetriggerable {
|
||||
retriggerable.retrigger()
|
||||
}
|
||||
_hasArticulated = true
|
||||
return Event(voice: voice, delta: delta, gate: gateNode)
|
||||
}
|
||||
|
||||
/// Resolves the next event and erases its voice type for the background playback loop, so the
|
||||
/// `@Sendable` task body never names the generic `V`. Mono uses only `voice`, `delta` and
|
||||
/// `gate`; `sustain` is already applied to the voice inside ``next()`` and `selfFreeing` is
|
||||
/// unused here. See ``ResolvedEvent``.
|
||||
@MainActor func nextResolved() -> ResolvedEvent? {
|
||||
guard let e: Event = next() else { return nil }
|
||||
return ResolvedEvent(
|
||||
voice: e.voice,
|
||||
delta: e.delta,
|
||||
sustain: 0.0,
|
||||
gate: e.gate,
|
||||
selfFreeing: false
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the duration and all bound patterns to their initial state.
|
||||
@MainActor private func resetPatterns() {
|
||||
_durPattern.reset()
|
||||
for binding: EventBinding<V> in _bindings {
|
||||
binding.reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// ParallelEventPattern.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Plays several event patterns at once — Lyrebird's parallel event-driven player.
|
||||
///
|
||||
/// Holds a set of children — any mix of ``EventPattern``, ``MonoEventPattern`` and even nested
|
||||
/// `ParallelEventPattern`s (anything conforming to ``EventPatternPlayable``) — and starts each
|
||||
/// on its own background `LyrebirdTask` when `play(on:)` is called. The children are started back to back on the
|
||||
/// main thread and share **no common clock**: each runs its own tempo and its own relative
|
||||
/// `wait(beats:)` chain. Children with the same tempo begin within thread-start latency of each
|
||||
/// other (sub-millisecond in practice) but are not re-synchronised afterwards, so small
|
||||
/// per-event timing drift can accumulate over long runs; children with different tempos run
|
||||
/// polytemporally. The returned ``EventPatternHandle`` controls them all at once:
|
||||
/// ``EventPatternHandle/stop()`` stops every child, ``EventPatternHandle/isPlaying`` is `true`
|
||||
/// while any child is still live, and ``EventPatternHandle/waitUntilComplete(releasePadding:)``
|
||||
/// returns once all finite children have finished.
|
||||
///
|
||||
/// A child added with ``addAfter(beats:eventPattern:)`` enters a fixed number of beats into the
|
||||
/// group's timeline: because every child is launched from the one `play` call and shares that
|
||||
/// start instant, the lead-in staggers its entry on the group's start grid. This is a static,
|
||||
/// composed-before-`play` stagger — see *Not thread-safe* below for why live insertion is not
|
||||
/// supported here.
|
||||
///
|
||||
/// ```swift
|
||||
/// let lead: MonoEventPattern<LeadVoice> = MonoEventPattern(make: { LeadVoice() })
|
||||
/// .bind(\.freq, .sequence([440.0, 550.0, 660.0]))
|
||||
/// .dur(.sequence([0.5]))
|
||||
///
|
||||
/// let bass: EventPattern<BassVoice> = EventPattern(make: { BassVoice() })
|
||||
/// .bind(\.freq, .sequence([55.0, 55.0, 82.5, 55.0]))
|
||||
/// .dur(.sequence([1.0]))
|
||||
///
|
||||
/// let handle: EventPatternHandle = ParallelEventPattern()
|
||||
/// .add(lead) // enters with the group
|
||||
/// .addAfter(beats: 2.0, eventPattern: bass) // enters two beats in
|
||||
/// .play(on: engine)
|
||||
/// ```
|
||||
///
|
||||
/// Not thread-safe: compose all children (`add` / `addAfter`) before `play`, and drive a single
|
||||
/// `play` at a time. Each child's patterns are pulled by exactly one playback task. There is no
|
||||
/// supported way to add a child **after** `play` — the group is a fire-once start, not a live,
|
||||
/// beat-quantised conductor you push patterns into from a UI, OSC or MIDI callback.
|
||||
///
|
||||
/// - SeeAlso: ``EventPatternPlayable``, ``EventPattern``, ``MonoEventPattern``, ``EventPatternHandle``
|
||||
public final class ParallelEventPattern: @unchecked Sendable {
|
||||
|
||||
/// The child patterns played in parallel, in the order added, each with the beats of lead-in
|
||||
/// before it enters (`0` = starts with the group).
|
||||
private var _children: [(offset: Double, child: any EventPatternPlayable)]
|
||||
|
||||
/// Creates a parallel pattern with no children. Add them with ``add(_:)`` or
|
||||
/// ``addAfter(beats:eventPattern:)``.
|
||||
public init() {
|
||||
_children = []
|
||||
}
|
||||
|
||||
/// Creates a parallel pattern over the given children, all entering with the group.
|
||||
///
|
||||
/// - Parameter children: The patterns to play at once.
|
||||
public init(_ children: [any EventPatternPlayable]) {
|
||||
_children = children.map { (0.0, $0) }
|
||||
}
|
||||
|
||||
/// Appends a child pattern that enters with the group.
|
||||
///
|
||||
/// - Parameter child: The pattern to play alongside the others.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func add(_ child: any EventPatternPlayable) -> Self {
|
||||
_children.append((0.0, child))
|
||||
return self
|
||||
}
|
||||
|
||||
/// Appends a child pattern that enters `beats` beats after the group starts.
|
||||
///
|
||||
/// All children are launched together when ``play(on:startAfterBeats:)`` is called and share
|
||||
/// that one start instant; `beats` is a lead-in the child waits out (at its own tempo) before
|
||||
/// its first event, so a child added with `addAfter(beats: 2)` enters two beats into the
|
||||
/// group's timeline. This is a **fixed, pre-`play` stagger** — not a live, beat-quantised
|
||||
/// insertion while the group is already running.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - beats: Lead-in before the child's first event, in beats at the child's tempo. Must be
|
||||
/// `≥ 0`.
|
||||
/// - eventPattern: The pattern to play, entering after the lead-in.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func addAfter(beats: Double, eventPattern: any EventPatternPlayable) -> Self {
|
||||
precondition(beats >= 0 && beats.isFinite, "addAfter beats must be non-negative and finite")
|
||||
_children.append((beats, eventPattern))
|
||||
return self
|
||||
}
|
||||
|
||||
/// Starts every child on `engine` and returns one handle controlling them all.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: Engine the children's voices are added to.
|
||||
/// - beats: Lead-in applied to the whole group before any child enters, in beats. Each
|
||||
/// child's own ``addAfter(beats:eventPattern:)`` offset is added on top. `0` starts now.
|
||||
/// - Returns: A handle whose ``EventPatternHandle/stop()`` stops every child and whose
|
||||
/// ``EventPatternHandle/waitUntilComplete(releasePadding:)`` returns once all finite children
|
||||
/// finish.
|
||||
/// - Precondition: at least one child has been added; an empty pattern traps.
|
||||
@discardableResult
|
||||
@MainActor public func play(
|
||||
on engine: SynthesisEngine,
|
||||
startAfterBeats beats: Double
|
||||
) -> EventPatternHandle {
|
||||
precondition(!_children.isEmpty, "ParallelEventPattern requires at least one child")
|
||||
let handles: [EventPatternHandle] = _children.map {
|
||||
$0.child.play(on: engine, startAfterBeats: beats + $0.offset)
|
||||
}
|
||||
return EventPatternHandle(merging: handles)
|
||||
}
|
||||
}
|
||||
|
||||
// A ParallelEventPattern is itself playable, so one may be nested as a child of another
|
||||
// (nested parallel groups). Its merged handle already wraps at least one task.
|
||||
extension ParallelEventPattern: EventPatternPlayable {}
|
||||
@@ -0,0 +1,36 @@
|
||||
// ResolvedEvent.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// A type-erased view of one resolved event, handed to the background playback loop.
|
||||
///
|
||||
/// The playback loops in ``EventPattern`` and ``MonoEventPattern`` run inside a `@Sendable`
|
||||
/// `LyrebirdTask` body. Naming the generic voice type `V` there — for example annotating an
|
||||
/// `EventStream<V>.Event` binding, or an `addedVoice: V?` — captures the non-`Sendable` metatype
|
||||
/// `V.Type` in that isolated closure, which Swift's concurrency checking flags. `ResolvedEvent`
|
||||
/// erases the voice to `any Synthesizer`, so the loop never mentions `V`: the stream (captured as
|
||||
/// an instance, which is safe) resolves each event on the main actor and hands back this
|
||||
/// non-generic value, which carries everything the loop needs.
|
||||
///
|
||||
/// `MonoEventPattern` uses only `voice`, `delta` and `gate`; `sustain` and `selfFreeing` are
|
||||
/// meaningful only to the polyphonic ``EventPattern`` reaping paths.
|
||||
struct ResolvedEvent {
|
||||
|
||||
/// The configured voice, type-erased.
|
||||
let voice: any Synthesizer
|
||||
|
||||
/// Beats to wait before the next event.
|
||||
let delta: Double
|
||||
|
||||
/// Beats the voice sounds (`delta * legato`). Drives the `EventGated` note-off time.
|
||||
let sustain: Double
|
||||
|
||||
/// The voice's gate node when it conforms to `EventGated`, else `nil`.
|
||||
let gate: ParameterNode?
|
||||
|
||||
/// `true` when the voice frees itself (`EventGated` or `EventSustainAware`), so it is not
|
||||
/// hard-removed.
|
||||
let selfFreeing: Bool
|
||||
}
|
||||
@@ -64,6 +64,11 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
|
||||
// `elapsedSamples` value at the most recent tempo change.
|
||||
private var _sampleTempoChangeSamples: SampleTime = 0
|
||||
|
||||
// Pending non-blocking parameter writes, each due at a `now`-timeline timestamp. Accessed
|
||||
// only on the body's own thread (like `tempo`), so no lock is needed — the array crosses no
|
||||
// thread boundary. The `param.value` writes it performs are themselves atomic and RT-safe.
|
||||
private var _scheduledSets: [_ScheduledSet] = []
|
||||
|
||||
internal init(
|
||||
engine: SynthesisEngine,
|
||||
control: RoutineControl
|
||||
@@ -345,6 +350,89 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
|
||||
param.value = value
|
||||
}
|
||||
|
||||
/// Schedules `param` to be set to `value` after `seconds`, **without blocking** the body.
|
||||
///
|
||||
/// Unlike ``set(_:to:)`` (which writes immediately) and ``ramp(_:to:seconds:)`` (which blocks
|
||||
/// for the glide), this records a one-shot future write and returns at once — so the body can
|
||||
/// start the next event while earlier writes are still pending. Several scheduled writes
|
||||
/// coexist and fire independently, which is what lets overlapping voices (legato `> 1`) each
|
||||
/// get their own note-off.
|
||||
///
|
||||
/// The write is serviced on this context's own timeline: due writes fire during any
|
||||
/// ``wait(seconds:)`` / ``wait(beats:)`` and during ``waitForScheduledSets()``, at the ~10 ms
|
||||
/// poll granularity. Pause time (`LyrebirdTask.pause()`) is excluded — a pause defers a pending
|
||||
/// write by the pause duration — and a stop abandons pending writes unless the body first calls
|
||||
/// ``waitForScheduledSets()`` (drain at their proper times) or the internal flush (fire now).
|
||||
///
|
||||
/// The target time is captured relative to the current ``now``; a non-positive `seconds` makes
|
||||
/// the write due at the next service.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - param: The `@LiveParam` node — `synth.$someLiveParam`. (`@UIParam` is not accepted —
|
||||
/// see ``set(_:to:)``.)
|
||||
/// - value: The value to write when the delay elapses.
|
||||
/// - seconds: Delay from now, in seconds.
|
||||
public func set(
|
||||
_ param: ParameterNode,
|
||||
to value: Double,
|
||||
after seconds: Double
|
||||
) {
|
||||
_scheduledSets.append(_ScheduledSet(fireAtNow: now + max(0.0, seconds), param: param, value: value))
|
||||
}
|
||||
|
||||
/// Schedules `param` to be set to `value` after `beats` beats at the current ``tempo``.
|
||||
/// See ``set(_:to:after:)``.
|
||||
public func set(
|
||||
_ param: ParameterNode,
|
||||
to value: Double,
|
||||
afterBeats beats: Double
|
||||
) {
|
||||
set(param, to: value, after: beats * 60.0 / tempo)
|
||||
}
|
||||
|
||||
/// Blocks until every write scheduled by ``set(_:to:after:)`` / ``set(_:to:afterBeats:)`` has
|
||||
/// fired at its proper time. Used at the end of a finite stream so trailing writes (a final
|
||||
/// voice's note-off, say) are not dropped when the body returns.
|
||||
///
|
||||
/// Throws `LyrebirdRoutineError.stopped` if the owning routine is stopped while draining.
|
||||
public func waitForScheduledSets() throws {
|
||||
while !_scheduledSets.isEmpty {
|
||||
if control.shouldStop.load(ordering: .relaxed) { throw LyrebirdRoutineError.stopped }
|
||||
let earliest: Double = _scheduledSets.reduce(Double.greatestFiniteMagnitude) {
|
||||
Swift.min($0, $1.fireAtNow)
|
||||
}
|
||||
let remaining: Double = earliest - now
|
||||
// `_sleepUntil` services due writes each poll, so sleeping to `earliest` fires it;
|
||||
// a non-positive remaining falls through to an immediate service on the next pass.
|
||||
_nextWakeTime = try _sleepUntil(Date().addingTimeInterval(max(0.0, remaining)))
|
||||
_serviceScheduledSets()
|
||||
}
|
||||
}
|
||||
|
||||
/// Fires every pending scheduled write immediately, regardless of its due time, and clears the
|
||||
/// list. Used on stop so outstanding gates close (voices release and self-free) rather than
|
||||
/// hanging at their sustain level.
|
||||
internal func _flushScheduledSets() {
|
||||
for s: _ScheduledSet in _scheduledSets { s.param.value = s.value }
|
||||
_scheduledSets.removeAll(keepingCapacity: false)
|
||||
}
|
||||
|
||||
/// Fires any scheduled writes whose due time has arrived, in schedule order, and drops them.
|
||||
/// Called from the wait poll loop — a no-op when nothing is pending.
|
||||
private func _serviceScheduledSets() {
|
||||
guard !_scheduledSets.isEmpty else { return }
|
||||
let t: Double = now
|
||||
var i: Int = 0
|
||||
while i < _scheduledSets.count {
|
||||
if _scheduledSets[i].fireAtNow <= t {
|
||||
let s: _ScheduledSet = _scheduledSets.remove(at: i)
|
||||
s.param.value = s.value
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -415,6 +503,9 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
|
||||
_pauseAccumulated += pauseDuration
|
||||
_pauseAccumulatedSamples += _engine.currentTime - pauseStartSamples
|
||||
}
|
||||
// Fire any parameter writes scheduled via `set(_:to:after:)` whose due time has
|
||||
// arrived. Placed before the remaining-time check so the final wake still services.
|
||||
_serviceScheduledSets()
|
||||
let remaining: TimeInterval = adjustedTarget.timeIntervalSince(Date())
|
||||
if remaining <= 0 { break }
|
||||
Thread.sleep(forTimeInterval: min(LyrebirdRoutineContext.pollIntervalSeconds, remaining))
|
||||
@@ -440,6 +531,14 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// One pending non-blocking parameter write: the value to store, the node to store it into, and
|
||||
/// the `now`-timeline timestamp at which it becomes due. Lives only on the body thread.
|
||||
private struct _ScheduledSet {
|
||||
let fireAtNow: Double
|
||||
let param: ParameterNode
|
||||
let value: Double
|
||||
}
|
||||
|
||||
/// One-shot carrier that returns a (possibly non-`Sendable`) value from a synchronous
|
||||
/// main-thread hop in ``LyrebirdRoutineContext/onMain(_:)``.
|
||||
///
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// The current Lyrebird framework and CLI version.
|
||||
public let lyrebirdVersion: String = "2.3.0"
|
||||
public let lyrebirdVersion: String = "2.4.0"
|
||||
|
||||
/// The banner printed when the interactive shell or REPL session starts.
|
||||
public let welcomeBanner: String = """
|
||||
|
||||
@@ -0,0 +1,496 @@
|
||||
// EventConductorTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Synchronization
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Shared fixture
|
||||
|
||||
/// A fresh voice per event, counting `build()` calls so a test can observe when (and whether) the
|
||||
/// conductor has started a pattern.
|
||||
private final class CondVoice: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 0.0
|
||||
nonisolated static let buildCount: Atomic<Int> = Atomic<Int>(0)
|
||||
|
||||
override func build() {
|
||||
CondVoice.buildCount.wrappingAdd(1, ordering: .releasing)
|
||||
output(bus: 0, source: $freq)
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a two-event finite pattern at `tempo`.
|
||||
@MainActor private func makeFinitePattern(tempo: Double) -> EventPattern<CondVoice> {
|
||||
EventPattern(make: { CondVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
|
||||
.dur(.sequence([0.02]))
|
||||
.tempo(tempo)
|
||||
}
|
||||
|
||||
/// Builds a never-ending fast pattern at `tempo` — its build counter keeps climbing until stopped,
|
||||
/// so a test can detect a child the conductor failed to halt.
|
||||
@MainActor private func makeInfinitePattern(tempo: Double) -> EventPattern<CondVoice> {
|
||||
EventPattern(make: { CondVoice() })
|
||||
.bind(\.freq, .uniformRandom(low: 100.0, high: 200.0))
|
||||
.dur(.sequence([0.05]))
|
||||
.tempo(tempo)
|
||||
}
|
||||
|
||||
// MARK: - Conductor playback
|
||||
|
||||
/// `EventConductor` live, clock-driven playback. Serialized because the fixture shares a static
|
||||
/// build counter.
|
||||
@Suite("EventConductor", .serialized)
|
||||
struct EventConductorTests {
|
||||
|
||||
@Test func quantiseDelaysEntryThenPlays() async {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// afterBeats(2) at 120 BPM = a 1.0 s lead-in before the first voice is built.
|
||||
let conductor: EventConductor = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 120.0)
|
||||
c.start(on: engine)
|
||||
c.add(makeFinitePattern(tempo: 120.0), quantize: .afterBeats(2.0))
|
||||
return c
|
||||
}
|
||||
|
||||
// Well inside the lead-in: nothing built yet, but the conductor clock is running.
|
||||
try? await Task.sleep(for: .milliseconds(300))
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 0)
|
||||
#expect(conductor.isRunning)
|
||||
|
||||
// After the boundary the pattern runs to completion: both events fire.
|
||||
let deadline: Date = Date().addingTimeInterval(2.0)
|
||||
while CondVoice.buildCount.load(ordering: .acquiring) < 2, Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 2)
|
||||
conductor.stop()
|
||||
}
|
||||
|
||||
@Test func nextMultipleEntersOnGrid() async {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// nextMultiple(ofBeats: 2) at 120 BPM: the next bar line is at beat 2 = 1.0 s out.
|
||||
let conductor: EventConductor = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 120.0)
|
||||
c.start(on: engine)
|
||||
c.add(makeFinitePattern(tempo: 120.0), quantize: .nextMultiple(ofBeats: 2.0))
|
||||
return c
|
||||
}
|
||||
|
||||
try? await Task.sleep(for: .milliseconds(300))
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 0)
|
||||
|
||||
let deadline: Date = Date().addingTimeInterval(2.5)
|
||||
while CondVoice.buildCount.load(ordering: .acquiring) < 2, Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 2)
|
||||
conductor.stop()
|
||||
}
|
||||
|
||||
@Test func liveAddAfterStartPlaysAndIdles() async {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// Start the conductor empty, as a running engine would sit waiting for input. The pattern
|
||||
// is built on the main actor (its `\.freq` key path is main-actor-isolated) but not yet
|
||||
// handed over; the conductor supplies the engine later.
|
||||
let (conductor, pattern): (EventConductor, EventPattern<CondVoice>) = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 240.0)
|
||||
c.start(on: engine)
|
||||
let p: EventPattern<CondVoice> = EventPattern(make: { CondVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0, 660.0], repeats: 1))
|
||||
.dur(.sequence([0.02]))
|
||||
.tempo(240.0)
|
||||
return (c, p)
|
||||
}
|
||||
|
||||
// Add it AFTER start, from off the main thread — standing in for a UI / OSC / MIDI callback.
|
||||
conductor.add(pattern, quantize: .nextBeat)
|
||||
|
||||
// waitUntilIdle (off main here) blocks until the pattern has entered and finished.
|
||||
conductor.waitUntilIdle()
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 3)
|
||||
#expect(!conductor.hasActiveChildren)
|
||||
conductor.stop()
|
||||
}
|
||||
|
||||
@Test func addBeforeStartIsServicedAfterStart() async {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// Queue a pattern, THEN start — the conductor must service the pre-start inbox on its first
|
||||
// poll relative to beat 0.
|
||||
let conductor: EventConductor = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 240.0)
|
||||
c.add(makeFinitePattern(tempo: 240.0), quantize: .now) // before start
|
||||
c.start(on: engine)
|
||||
return c
|
||||
}
|
||||
|
||||
conductor.waitUntilIdle()
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 2)
|
||||
#expect(!conductor.hasActiveChildren)
|
||||
conductor.stop()
|
||||
}
|
||||
|
||||
@Test func multipleAddsInOnePollAllPlay() async {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// Three finite patterns added before the first poll — all must enter and finish.
|
||||
let conductor: EventConductor = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 240.0)
|
||||
c.add(makeFinitePattern(tempo: 240.0), quantize: .now)
|
||||
c.add(makeFinitePattern(tempo: 240.0), quantize: .now)
|
||||
c.add(makeFinitePattern(tempo: 240.0), quantize: .now)
|
||||
c.start(on: engine)
|
||||
return c
|
||||
}
|
||||
|
||||
conductor.waitUntilIdle()
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 6) // 3 patterns × 2 events
|
||||
#expect(!conductor.hasActiveChildren)
|
||||
conductor.stop()
|
||||
}
|
||||
|
||||
@Test func polytempoEntryAlignsToConductorClock() async {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// Conductor at 120, pattern at 60 (half tempo). Entry must align to the CONDUCTOR'S grid —
|
||||
// the bar at conductor beat 2 (1.0 s) — not be stretched by the pattern's slow tempo.
|
||||
let conductor: EventConductor = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 120.0)
|
||||
c.start(on: engine)
|
||||
let slow: EventPattern<CondVoice> = EventPattern(make: { CondVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
|
||||
.dur(.sequence([0.02]))
|
||||
.tempo(60.0)
|
||||
c.add(slow, quantize: .nextMultiple(ofBeats: 2.0))
|
||||
return c
|
||||
}
|
||||
|
||||
// Still inside the 1.0 s conductor lead-in: nothing built.
|
||||
try? await Task.sleep(for: .milliseconds(300))
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 0)
|
||||
|
||||
// Enters on the conductor's bar line and runs to completion.
|
||||
let deadline: Date = Date().addingTimeInterval(2.5)
|
||||
while CondVoice.buildCount.load(ordering: .acquiring) < 2, Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 2)
|
||||
conductor.stop()
|
||||
}
|
||||
|
||||
@Test func currentBeatAdvancesWhileRunning() async {
|
||||
let conductor: EventConductor = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 120.0)
|
||||
c.start(on: engine)
|
||||
return c
|
||||
}
|
||||
#expect(conductor.currentBeat >= 0.0)
|
||||
try? await Task.sleep(for: .milliseconds(500))
|
||||
// 500 ms at 120 BPM ≈ 1.0 beat; assert a generous lower bound to avoid CI-load flake.
|
||||
#expect(conductor.currentBeat > 0.3)
|
||||
conductor.stop()
|
||||
}
|
||||
|
||||
@Test func stopDuringStartHaltsEverything() async {
|
||||
// Race stop() against the inbox service across many iterations with a randomised sub-poll
|
||||
// delay, so some iterations land stop() mid-hop (the post-hop `.stopped` branch) rather than
|
||||
// before the first 10 ms poll. After each iteration nothing may keep playing.
|
||||
for iteration: Int in 0..<24 {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
let (conductor, patterns): (EventConductor, [EventPattern<CondVoice>]) = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 240.0)
|
||||
c.start(on: engine)
|
||||
let ps: [EventPattern<CondVoice>] = (0..<4).map { _ in makeInfinitePattern(tempo: 240.0) }
|
||||
return (c, ps)
|
||||
}
|
||||
|
||||
for pattern: EventPattern<CondVoice> in patterns {
|
||||
conductor.add(pattern, quantize: .now)
|
||||
}
|
||||
// 0–15 ms: sometimes before the first poll, sometimes mid-service.
|
||||
let delayMs: Int = (iteration * 7) % 16
|
||||
if delayMs > 0 {
|
||||
try? await Task.sleep(for: .milliseconds(delayMs))
|
||||
}
|
||||
conductor.stop()
|
||||
|
||||
// Let any in-flight start land and any missed child reveal itself by climbing the counter.
|
||||
try? await Task.sleep(for: .milliseconds(120))
|
||||
let countA: Int = CondVoice.buildCount.load(ordering: .acquiring)
|
||||
try? await Task.sleep(for: .milliseconds(120))
|
||||
let countB: Int = CondVoice.buildCount.load(ordering: .acquiring)
|
||||
|
||||
#expect(countA == countB, "iteration \(iteration): a child kept building after stop()")
|
||||
#expect(!conductor.hasActiveChildren, "iteration \(iteration): active child survived stop()")
|
||||
#expect(!conductor.isRunning)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func stopHaltsConductorAndChildren() async {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// An infinite pattern, started immediately.
|
||||
let conductor: EventConductor = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 120.0)
|
||||
c.start(on: engine)
|
||||
c.add(makeInfinitePattern(tempo: 120.0), quantize: .now)
|
||||
return c
|
||||
}
|
||||
|
||||
try? await Task.sleep(for: .milliseconds(200))
|
||||
#expect(conductor.hasActiveChildren)
|
||||
|
||||
conductor.stop()
|
||||
let deadline: Date = Date().addingTimeInterval(2.0)
|
||||
while conductor.hasActiveChildren, Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(!conductor.hasActiveChildren)
|
||||
#expect(!conductor.isRunning)
|
||||
|
||||
// A stopped conductor ignores further adds.
|
||||
let countAfterStop: Int = CondVoice.buildCount.load(ordering: .acquiring)
|
||||
await MainActor.run { conductor.add(makeFinitePattern(tempo: 120.0), quantize: .now) }
|
||||
try? await Task.sleep(for: .milliseconds(150))
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == countAfterStop)
|
||||
}
|
||||
|
||||
@Test func concurrentAddsFromManyThreadsAllPlay() async {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
let patternCount: Int = 8
|
||||
let (conductor, patterns): (EventConductor, [EventPattern<CondVoice>]) = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 240.0)
|
||||
c.start(on: engine)
|
||||
let ps: [EventPattern<CondVoice>] = (0..<patternCount).map { _ in makeFinitePattern(tempo: 240.0) }
|
||||
return (c, ps)
|
||||
}
|
||||
|
||||
// Hammer add(_:) from many threads at once — the lock-guarded inbox must accept them all.
|
||||
let box: PatternBox = PatternBox(patterns)
|
||||
DispatchQueue.concurrentPerform(iterations: patternCount) { i in
|
||||
box.add(into: conductor, index: i)
|
||||
}
|
||||
|
||||
conductor.waitUntilIdle()
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == patternCount * 2)
|
||||
#expect(!conductor.hasActiveChildren)
|
||||
conductor.stop()
|
||||
}
|
||||
|
||||
@Test func addReturnsHandlePlayingUntilDone() async {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
let (conductor, pattern): (EventConductor, EventPattern<CondVoice>) = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 240.0)
|
||||
c.start(on: engine)
|
||||
return (c, makeFinitePattern(tempo: 240.0))
|
||||
}
|
||||
|
||||
let handle: EventConductorHandle = conductor.add(pattern, quantize: .now)
|
||||
#expect(handle.isPlaying) // pending → reports playing before it even enters
|
||||
conductor.waitUntilIdle()
|
||||
#expect(!handle.isPlaying) // finite pattern finished
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 2)
|
||||
conductor.stop()
|
||||
}
|
||||
|
||||
@Test func perPartStopLeavesOtherPartsPlaying() async {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
let (conductor, patternA, patternB): (EventConductor, EventPattern<CondVoice>, EventPattern<CondVoice>) = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 240.0)
|
||||
c.start(on: engine)
|
||||
return (c, makeInfinitePattern(tempo: 240.0), makeInfinitePattern(tempo: 240.0))
|
||||
}
|
||||
|
||||
let handleA: EventConductorHandle = conductor.add(patternA, quantize: .now)
|
||||
let handleB: EventConductorHandle = conductor.add(patternB, quantize: .now)
|
||||
|
||||
// Wait until both have entered and are building voices.
|
||||
let entryDeadline: Date = Date().addingTimeInterval(1.0)
|
||||
while !conductor.hasActiveChildren, Date() < entryDeadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
try? await Task.sleep(for: .milliseconds(150))
|
||||
#expect(handleA.isPlaying)
|
||||
#expect(handleB.isPlaying)
|
||||
|
||||
// Stop ONE part. Its pattern tears down (an infinite pattern's teardown is not instant), so
|
||||
// poll its handle with a deadline rather than assuming a fixed delay.
|
||||
handleA.stop()
|
||||
let aStopDeadline: Date = Date().addingTimeInterval(2.0)
|
||||
while handleA.isPlaying, Date() < aStopDeadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(!handleA.isPlaying) // the stopped part is gone
|
||||
|
||||
// The other part must keep playing and keep building voices.
|
||||
let countAfterStopA: Int = CondVoice.buildCount.load(ordering: .acquiring)
|
||||
try? await Task.sleep(for: .milliseconds(250))
|
||||
let countLater: Int = CondVoice.buildCount.load(ordering: .acquiring)
|
||||
|
||||
#expect(handleB.isPlaying) // the other part survives
|
||||
#expect(conductor.hasActiveChildren)
|
||||
#expect(countLater > countAfterStopA) // part B kept building
|
||||
|
||||
conductor.stop()
|
||||
let stopDeadline: Date = Date().addingTimeInterval(2.0)
|
||||
while handleB.isPlaying, Date() < stopDeadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(!handleB.isPlaying)
|
||||
#expect(!conductor.hasActiveChildren)
|
||||
}
|
||||
|
||||
@Test func handleStopBeforeEntryNeverBuilds() async {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// afterBeats(1) at 240 BPM = a 0.25 s lead-in, so the entry falls WELL INSIDE the wait
|
||||
// window below: were the pre-entry cancel skip removed, the pattern would enter and build.
|
||||
// The immediate stop() must prevent that.
|
||||
let (conductor, pattern): (EventConductor, EventPattern<CondVoice>) = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 240.0)
|
||||
c.start(on: engine)
|
||||
return (c, makeInfinitePattern(tempo: 240.0))
|
||||
}
|
||||
|
||||
let handle: EventConductorHandle = conductor.add(pattern, quantize: .afterBeats(1.0))
|
||||
handle.stop() // cancel while still pending
|
||||
|
||||
// waitUntilIdle must return (covers `_starting` decrement on the skip path); the entry
|
||||
// window (0.25 s) elapses well within the wait.
|
||||
conductor.waitUntilIdle()
|
||||
try? await Task.sleep(for: .milliseconds(350))
|
||||
#expect(!handle.isPlaying)
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 0) // never entered
|
||||
#expect(!conductor.hasActiveChildren)
|
||||
conductor.stop()
|
||||
}
|
||||
|
||||
@Test func addAfterStopReturnsStoppedHandle() async {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
let (conductor, pattern): (EventConductor, EventPattern<CondVoice>) = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 240.0)
|
||||
c.start(on: engine)
|
||||
return (c, makeInfinitePattern(tempo: 240.0))
|
||||
}
|
||||
conductor.stop()
|
||||
|
||||
// Adding to a stopped conductor returns an already-cancelled handle and never builds.
|
||||
let handle: EventConductorHandle = conductor.add(pattern, quantize: .now)
|
||||
#expect(!handle.isPlaying)
|
||||
try? await Task.sleep(for: .milliseconds(150))
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 0)
|
||||
}
|
||||
|
||||
@Test func conductorStopCancelsPendingHandle() async {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// A part queued far out, then the whole conductor stopped before it enters: its handle must
|
||||
// report not-playing and it must never build a voice.
|
||||
let (conductor, pattern): (EventConductor, EventPattern<CondVoice>) = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 120.0)
|
||||
c.start(on: engine)
|
||||
return (c, makeInfinitePattern(tempo: 120.0))
|
||||
}
|
||||
let handle: EventConductorHandle = conductor.add(pattern, quantize: .afterBeats(8.0)) // 4 s out
|
||||
try? await Task.sleep(for: .milliseconds(100)) // let it resolve into _pending
|
||||
conductor.stop()
|
||||
|
||||
try? await Task.sleep(for: .milliseconds(150))
|
||||
#expect(!handle.isPlaying)
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 0)
|
||||
}
|
||||
|
||||
@Test func handleAddedBeforeStartCanBeStopped() async {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// Add BEFORE start (the _inbox path), stop the handle, THEN start. It must never enter.
|
||||
let (conductor, handle): (EventConductor, EventConductorHandle) = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 240.0)
|
||||
let h: EventConductorHandle = c.add(makeInfinitePattern(tempo: 240.0), quantize: .now)
|
||||
h.stop()
|
||||
c.start(on: engine)
|
||||
return (c, h)
|
||||
}
|
||||
|
||||
try? await Task.sleep(for: .milliseconds(200))
|
||||
#expect(!handle.isPlaying)
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 0)
|
||||
#expect(!conductor.hasActiveChildren)
|
||||
conductor.stop()
|
||||
}
|
||||
|
||||
@Test func handleStopRacingEntryNeverLeaksAChild() async {
|
||||
// Stress the per-part stop against the entry hop: add one infinite part `.now`, stop its
|
||||
// handle after a randomised sub-poll delay, and confirm nothing keeps playing. Exercises the
|
||||
// pre-hop skip and the attach-after-cancel path.
|
||||
for iteration: Int in 0..<24 {
|
||||
CondVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
let (conductor, pattern): (EventConductor, EventPattern<CondVoice>) = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let c: EventConductor = EventConductor(tempo: 240.0)
|
||||
c.start(on: engine)
|
||||
return (c, makeInfinitePattern(tempo: 240.0))
|
||||
}
|
||||
|
||||
let handle: EventConductorHandle = conductor.add(pattern, quantize: .now)
|
||||
let delayMs: Int = (iteration * 7) % 16
|
||||
if delayMs > 0 {
|
||||
try? await Task.sleep(for: .milliseconds(delayMs))
|
||||
}
|
||||
handle.stop()
|
||||
|
||||
let deadline: Date = Date().addingTimeInterval(2.0)
|
||||
while handle.isPlaying, Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(!handle.isPlaying, "iteration \(iteration): part kept playing after handle.stop()")
|
||||
|
||||
// Counter must stabilise — no orphaned child building on.
|
||||
let countA: Int = CondVoice.buildCount.load(ordering: .acquiring)
|
||||
try? await Task.sleep(for: .milliseconds(120))
|
||||
#expect(CondVoice.buildCount.load(ordering: .acquiring) == countA,
|
||||
"iteration \(iteration): a child kept building after handle.stop()")
|
||||
conductor.stop()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Carries the main-built patterns into the `concurrentPerform` closure without tripping Sendable
|
||||
/// checking — the array is read-only after construction and each index is touched once.
|
||||
private final class PatternBox: @unchecked Sendable {
|
||||
private let patterns: [EventPattern<CondVoice>]
|
||||
init(_ patterns: [EventPattern<CondVoice>]) { self.patterns = patterns }
|
||||
func add(into conductor: EventConductor, index: Int) {
|
||||
conductor.add(patterns[index], quantize: .now)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
// EventPatternTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Synchronization
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Shared fixtures
|
||||
|
||||
/// Voice recording the parameter values it was configured with and the sustain it was handed.
|
||||
/// A `SynthesizerBase` so `engine.add` invokes `build()` immediately (a bare `Synthesizer`
|
||||
/// only builds on a later rebuild, which the offline test engine never triggers). Key paths
|
||||
/// into its `@LiveParam`s are formed on the main actor (both suites do so).
|
||||
private final class EventTestVoice: SynthesizerBase, EventSustainAware {
|
||||
@LiveParam var freq: Double = 0.0
|
||||
@LiveParam var amp: Double = 0.0
|
||||
var sustainSeconds: Double = -1.0
|
||||
|
||||
/// Counts `build()` calls so the playback suite can see real spawns.
|
||||
nonisolated static let buildCount: Atomic<Int> = Atomic<Int>(0)
|
||||
|
||||
func setEventSustain(seconds: Double) {
|
||||
sustainSeconds = seconds
|
||||
}
|
||||
|
||||
override func build() {
|
||||
EventTestVoice.buildCount.wrappingAdd(1, ordering: .releasing)
|
||||
output(bus: 0, source: $amp)
|
||||
}
|
||||
}
|
||||
|
||||
/// Voice that does **not** conform to `EventSustainAware` — proves the no-hand-off branch
|
||||
/// resolves cleanly.
|
||||
private final class PlainEventVoice: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 0.0
|
||||
|
||||
override func build() {
|
||||
output(bus: 0, source: $freq)
|
||||
}
|
||||
}
|
||||
|
||||
/// Voice conforming to `EventGated`: exposes a gate `@LiveParam` (default open) that `EventPattern`
|
||||
/// drives. Used to prove the gate note-off path — opened on add, closed after `sustain`, and the
|
||||
/// voice is never hard-removed by the pattern.
|
||||
private final class GatedEventVoice: SynthesizerBase, EventGated {
|
||||
@LiveParam var freq: Double = 0.0
|
||||
@LiveParam var gate: Double = 1.0
|
||||
|
||||
var eventGate: ParameterNode { $gate }
|
||||
|
||||
override func build() {
|
||||
output(bus: 0, source: $freq * $gate)
|
||||
}
|
||||
}
|
||||
|
||||
/// Voice conforming to BOTH ``EventGated`` and ``EventSustainAware``. Proves gate precedence: the
|
||||
/// pattern drives release through the gate and never calls `setEventSustain`, so `sustainSeconds`
|
||||
/// keeps its sentinel value.
|
||||
private final class GatedAndSustainVoice: SynthesizerBase, EventGated, EventSustainAware {
|
||||
@LiveParam var freq: Double = 0.0
|
||||
@LiveParam var gate: Double = 1.0
|
||||
var sustainSeconds: Double = -1.0
|
||||
|
||||
var eventGate: ParameterNode { $gate }
|
||||
|
||||
func setEventSustain(seconds: Double) {
|
||||
sustainSeconds = seconds
|
||||
}
|
||||
|
||||
override func build() {
|
||||
output(bus: 0, source: $freq * $gate)
|
||||
}
|
||||
}
|
||||
|
||||
/// Carries a captured gated voice out of the main-actor setup block so the playback suite can
|
||||
/// inspect its gate value and binding after waiting off-main. `@unchecked Sendable`: written and
|
||||
/// read only inside `MainActor.run` hops.
|
||||
private final class GatedVoiceHolder: @unchecked Sendable {
|
||||
var voice: GatedEventVoice?
|
||||
}
|
||||
|
||||
/// The gated voice's current gate value (reads the `@LiveParam` node). Read on the main actor.
|
||||
@MainActor private func gateValue(_ voice: GatedEventVoice?) -> Double {
|
||||
voice?.gate ?? -1.0
|
||||
}
|
||||
|
||||
/// `true` while a gated voice is still bound to an engine. Read on the main actor.
|
||||
@MainActor private func isBoundGated(_ voice: GatedEventVoice?) -> Bool {
|
||||
guard let voice: GatedEventVoice = voice else { return false }
|
||||
return voice._engineBinding.load(ordering: .acquiring) != 0
|
||||
}
|
||||
|
||||
// MARK: - Pure-logic suite
|
||||
|
||||
/// `EventPattern` event resolution — driven synchronously through the `EventStream` core on
|
||||
/// the main actor. No background task, no engine: deterministic. Key paths (`\.freq`) are
|
||||
/// formed on the main actor, which is where user setup code runs.
|
||||
///
|
||||
/// Note: `Pattern.sequence` defaults to `repeats: -1` (infinite cycling), so tests that expect a
|
||||
/// bounded stream pass `repeats: 1`.
|
||||
@MainActor
|
||||
@Suite("EventPattern")
|
||||
struct EventPatternLogicTests {
|
||||
|
||||
/// Drains a pattern's stream synchronously, returning the resolved events. `max` bounds
|
||||
/// infinite streams.
|
||||
private func drain<V: Synthesizer>(
|
||||
_ pattern: EventPattern<V>,
|
||||
max: Int = 100
|
||||
) -> [EventStream<V>.Event] {
|
||||
let stream: EventStream<V> = pattern.makeEventStream()
|
||||
var events: [EventStream<V>.Event] = []
|
||||
while events.count < max, let event: EventStream<V>.Event = stream.next() {
|
||||
events.append(event)
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
@Test func bindsParametersInSequence() {
|
||||
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0, 660.0], repeats: 1))
|
||||
.bind(\.amp, .sequence([0.1, 0.2, 0.3], repeats: 1))
|
||||
|
||||
let events: [EventStream<EventTestVoice>.Event] = drain(pattern)
|
||||
#expect(events.count == 3)
|
||||
#expect(events.map(\.voice.freq) == [440.0, 550.0, 660.0])
|
||||
#expect(events.map(\.voice.amp) == [0.1, 0.2, 0.3])
|
||||
}
|
||||
|
||||
@Test func endsWhenAnyBoundPatternExhausts() {
|
||||
// freq has 2 values, amp has 5 — the stream must stop after 2 events.
|
||||
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
|
||||
.bind(\.amp, .sequence([0.1, 0.2, 0.3, 0.4, 0.5], repeats: 1))
|
||||
|
||||
#expect(drain(pattern).count == 2)
|
||||
}
|
||||
|
||||
@Test func durExhaustionEndsStream() {
|
||||
// A finite dur pattern ends the stream even when a binding is infinite.
|
||||
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
|
||||
.bind(\.freq, .uniformRandom(low: 100.0, high: 200.0))
|
||||
.dur(.sequence([0.25, 0.25], repeats: 1))
|
||||
|
||||
#expect(drain(pattern).count == 2)
|
||||
}
|
||||
|
||||
@Test func legatoDeterminesSustain() {
|
||||
// delta = 1 beat, legato 0.5 → sustain 0.5 beat; tempo 120 → 0.25 s.
|
||||
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
|
||||
.bind(\.freq, .sequence([440.0], repeats: 1))
|
||||
.dur(.sequence([1.0]))
|
||||
.legato(0.5)
|
||||
.tempo(120.0)
|
||||
|
||||
let events: [EventStream<EventTestVoice>.Event] = drain(pattern)
|
||||
#expect(events.count == 1)
|
||||
let event: EventStream<EventTestVoice>.Event? = events.first
|
||||
#expect(abs((event?.sustain ?? -1.0) - 0.5) < 1e-9)
|
||||
#expect(abs((event?.voice.sustainSeconds ?? -1.0) - 0.25) < 1e-9)
|
||||
}
|
||||
|
||||
@Test func repeatsReplaysTheWholeSet() {
|
||||
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
|
||||
.repeats(3)
|
||||
|
||||
let freqs: [Double] = drain(pattern).map(\.voice.freq)
|
||||
#expect(freqs == [440.0, 550.0, 440.0, 550.0, 440.0, 550.0])
|
||||
}
|
||||
|
||||
@Test func nonAwareVoiceResolves() {
|
||||
let pattern: EventPattern<PlainEventVoice> = EventPattern(make: { PlainEventVoice() })
|
||||
.bind(\.freq, .sequence([100.0, 200.0, 300.0], repeats: 1))
|
||||
|
||||
let events: [EventStream<PlainEventVoice>.Event] = drain(pattern)
|
||||
#expect(events.map(\.voice.freq) == [100.0, 200.0, 300.0])
|
||||
}
|
||||
|
||||
@Test func gatedVoiceCarriesGateAndIsSelfFreeing() {
|
||||
let pattern: EventPattern<GatedEventVoice> = EventPattern(make: { GatedEventVoice() })
|
||||
.bind(\.freq, .sequence([440.0], repeats: 1))
|
||||
|
||||
let events: [EventStream<GatedEventVoice>.Event] = drain(pattern)
|
||||
#expect(events.count == 1)
|
||||
#expect(events.first?.gate != nil) // gate node captured → note-off is driven
|
||||
#expect(events.first?.selfFreeing == true) // not hard-removed
|
||||
}
|
||||
|
||||
@Test func sustainAwareVoiceHasNoGateButIsSelfFreeing() {
|
||||
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
|
||||
.bind(\.freq, .sequence([440.0], repeats: 1))
|
||||
|
||||
let event: EventStream<EventTestVoice>.Event? = drain(pattern).first
|
||||
#expect(event?.gate == nil) // sustain model, no gate
|
||||
#expect(event?.selfFreeing == true) // still not hard-removed (self-timed envelope)
|
||||
}
|
||||
|
||||
@Test func gatedVoiceWinsOverSustainAware() {
|
||||
// A voice conforming to both: the gate drives release, so `setEventSustain` is NOT called
|
||||
// and the two release mechanisms never both fire.
|
||||
let pattern: EventPattern<GatedAndSustainVoice> = EventPattern(make: { GatedAndSustainVoice() })
|
||||
.bind(\.freq, .sequence([440.0], repeats: 1))
|
||||
.dur(.sequence([1.0]))
|
||||
.legato(1.0)
|
||||
.tempo(60.0)
|
||||
|
||||
let event: EventStream<GatedAndSustainVoice>.Event? = drain(pattern).first
|
||||
#expect(event?.gate != nil) // gate drives release
|
||||
#expect(event?.selfFreeing == true) // not hard-removed
|
||||
#expect(event?.voice.sustainSeconds == -1.0) // setEventSustain NOT called → gate wins
|
||||
}
|
||||
|
||||
@Test func plainVoiceIsNotSelfFreeing() {
|
||||
let pattern: EventPattern<PlainEventVoice> = EventPattern(make: { PlainEventVoice() })
|
||||
.bind(\.freq, .sequence([100.0], repeats: 1))
|
||||
|
||||
let event: EventStream<PlainEventVoice>.Event? = drain(pattern).first
|
||||
#expect(event?.gate == nil)
|
||||
#expect(event?.selfFreeing == false) // neither protocol → hard-removed as a backstop
|
||||
}
|
||||
|
||||
@Test func repeatsBelowOnePlaysNothing() {
|
||||
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
|
||||
.bind(\.freq, .sequence([440.0], repeats: 1))
|
||||
.repeats(0)
|
||||
|
||||
#expect(drain(pattern).isEmpty)
|
||||
}
|
||||
|
||||
@Test func emptyPassWithHugeRepeatsTerminates() {
|
||||
// A pass yielding nothing must end the stream rather than spin — the guard against an
|
||||
// empty pattern combined with a very large `repeats`.
|
||||
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
|
||||
.bind(\.freq, .sequence([], repeats: 1))
|
||||
.repeats(Int.max)
|
||||
|
||||
#expect(drain(pattern).isEmpty)
|
||||
}
|
||||
|
||||
@Test func tempoScalesSustainSeconds() {
|
||||
// delta 1 beat, legato 1.0, tempo 60 → sustain 1 beat = 1.0 s.
|
||||
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
|
||||
.bind(\.freq, .sequence([440.0], repeats: 1))
|
||||
.dur(.sequence([1.0]))
|
||||
.legato(1.0)
|
||||
.tempo(60.0)
|
||||
|
||||
let events: [EventStream<EventTestVoice>.Event] = drain(pattern)
|
||||
#expect(events.count == 1)
|
||||
#expect(abs((events.first?.voice.sustainSeconds ?? -1.0) - 1.0) < 1e-9)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Playback suite (real play(on:))
|
||||
|
||||
/// `EventPattern.play(on:)` driving the engine through a background `LyrebirdTask`. The suite
|
||||
/// is **not** `@MainActor`: the body's `ctx.add` / `ctx.onMain` hops need the real main thread
|
||||
/// free to service them, so each test waits off-main while the pattern builds voices. Key
|
||||
/// paths are formed inside a `MainActor.run` (the pattern is `@unchecked Sendable`).
|
||||
@Suite("EventPattern Playback", .serialized)
|
||||
struct EventPatternPlaybackTests {
|
||||
|
||||
@Test func playsConfiguredVoicesOnEngine() async {
|
||||
EventTestVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
return EventPattern(make: { EventTestVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
|
||||
.dur(.sequence([0.02]))
|
||||
.tempo(240.0)
|
||||
.play(on: engine)
|
||||
}
|
||||
handle.waitUntilComplete()
|
||||
|
||||
// `ctx.add` is dispatched async to main, so `build()` runs after the body ends; poll
|
||||
// off-main (leaving main free to drain those adds) until both voices are built.
|
||||
let deadline: Date = Date().addingTimeInterval(2.0)
|
||||
while EventTestVoice.buildCount.load(ordering: .acquiring) < 2, Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(EventTestVoice.buildCount.load(ordering: .acquiring) == 2)
|
||||
}
|
||||
|
||||
@Test func stopHaltsSpawning() async {
|
||||
EventTestVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// Infinite stream at a modest rate (0.05 beat @ 120 bpm = 25 ms/event).
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
return EventPattern(make: { EventTestVoice() })
|
||||
.bind(\.freq, .uniformRandom(low: 100.0, high: 200.0))
|
||||
.dur(.sequence([0.05]))
|
||||
.tempo(120.0)
|
||||
.play(on: engine)
|
||||
}
|
||||
|
||||
try? await Task.sleep(for: .milliseconds(150)) // a few events spawn
|
||||
handle.stop()
|
||||
|
||||
let deadline: Date = Date().addingTimeInterval(2.0)
|
||||
while handle.isPlaying, Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(!handle.isPlaying)
|
||||
|
||||
let afterStop: Int = EventTestVoice.buildCount.load(ordering: .acquiring)
|
||||
#expect(afterStop > 0) // it really was spawning
|
||||
try? await Task.sleep(for: .milliseconds(120)) // nothing new should spawn
|
||||
#expect(EventTestVoice.buildCount.load(ordering: .acquiring) == afterStop)
|
||||
}
|
||||
|
||||
@Test func finiteStreamStopsPlayingWhenComplete() async {
|
||||
EventTestVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
return EventPattern(make: { EventTestVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0, 660.0], repeats: 1))
|
||||
.dur(.sequence([0.02]))
|
||||
.tempo(240.0)
|
||||
.play(on: engine)
|
||||
}
|
||||
handle.waitUntilComplete()
|
||||
|
||||
// A finite pattern's task has finished once `waitUntilComplete` returns, so the handle
|
||||
// reports not playing (neither running nor paused).
|
||||
let deadline: Date = Date().addingTimeInterval(2.0)
|
||||
while handle.isPlaying, Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(!handle.isPlaying)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Gate playback suite (EventGated note-off)
|
||||
|
||||
/// `EventPattern` driving an ``EventGated`` voice: the gate opens on add and is closed after
|
||||
/// `sustain` (the note-off), and the pattern never hard-removes the voice. Not `@MainActor` — the
|
||||
/// body's hops need the real main thread free, so each test waits off-main.
|
||||
@Suite("EventPattern Gate Playback", .serialized)
|
||||
struct EventPatternGatePlaybackTests {
|
||||
|
||||
/// Polls off-main (leaving main free to drain dispatched engine ops) until `check` holds or the
|
||||
/// deadline passes; returns the final value.
|
||||
private func poll(timeout: Double = 2.0, _ check: @escaping @MainActor () -> Bool) async -> Bool {
|
||||
let deadline: Date = Date().addingTimeInterval(timeout)
|
||||
while await MainActor.run(body: check) == false, Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
return await MainActor.run(body: check)
|
||||
}
|
||||
|
||||
@Test func gatedVoiceGetsNoteOffAndIsNotHardRemoved() async {
|
||||
let holder: GatedVoiceHolder = GatedVoiceHolder()
|
||||
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let voice: GatedEventVoice = GatedEventVoice()
|
||||
holder.voice = voice
|
||||
// Single short event → one voice, one scheduled note-off at sustain.
|
||||
return EventPattern(make: { voice })
|
||||
.bind(\.freq, .sequence([440.0], repeats: 1))
|
||||
.dur(.sequence([0.05]))
|
||||
.legato(0.5)
|
||||
.tempo(240.0)
|
||||
.play(on: engine)
|
||||
}
|
||||
// `waitUntilComplete` returns only after the body's `waitForScheduledSets` has fired the
|
||||
// note-off, so the gate is already closed by the time it returns.
|
||||
handle.waitUntilComplete()
|
||||
|
||||
#expect(await poll { gateValue(holder.voice) == 0.0 }) // note-off fired
|
||||
// The gated voice was never hard-removed — it would free only via `doneAction` during
|
||||
// rendering, which the offline test engine does not drive. So it is still bound.
|
||||
#expect(await poll { isBoundGated(holder.voice) })
|
||||
}
|
||||
|
||||
@Test func stopClosesOutstandingGate() async {
|
||||
let holder: GatedVoiceHolder = GatedVoiceHolder()
|
||||
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let voice: GatedEventVoice = GatedEventVoice()
|
||||
holder.voice = voice
|
||||
// One very long event: the voice is added, its note-off scheduled far in the future,
|
||||
// and the body parks in `wait`. `stop()` must close the gate now rather than leak it open.
|
||||
return EventPattern(make: { voice })
|
||||
.bind(\.freq, .sequence([440.0], repeats: 1))
|
||||
.dur(.sequence([100.0]))
|
||||
.legato(1.0)
|
||||
.tempo(60.0)
|
||||
.play(on: engine)
|
||||
}
|
||||
|
||||
#expect(await poll { gateValue(holder.voice) == 1.0 }) // gate open while sounding
|
||||
handle.stop()
|
||||
|
||||
#expect(await poll { !handle.isPlaying })
|
||||
#expect(await poll { gateValue(holder.voice) == 0.0 }) // stop flushed the note-off
|
||||
}
|
||||
|
||||
@Test func releasePaddingDelaysReturnPastCompletion() async {
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
return EventPattern(make: { GatedEventVoice() })
|
||||
.bind(\.freq, .sequence([440.0], repeats: 1))
|
||||
.dur(.sequence([0.01]))
|
||||
.tempo(240.0)
|
||||
.play(on: engine)
|
||||
}
|
||||
// The suite is off-main, so `waitUntilComplete` takes the plain-sleep padding branch. The
|
||||
// short pattern finishes near-instantly, so the measured time is dominated by the padding.
|
||||
let padding: Double = 0.3
|
||||
let start: Date = Date()
|
||||
handle.waitUntilComplete(releasePadding: padding)
|
||||
let elapsed: Double = Date().timeIntervalSince(start)
|
||||
#expect(elapsed >= padding)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// EventQuantumTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable import LyrebirdSynth
|
||||
|
||||
/// `EventQuantum.targetBeat(from:)` — pure resolution of each quantum against a current beat.
|
||||
@Suite("EventQuantum")
|
||||
struct EventQuantumTests {
|
||||
|
||||
@Test func nowResolvesToNow() {
|
||||
#expect(EventQuantum.now.targetBeat(from: 3.4) == 3.4)
|
||||
}
|
||||
|
||||
@Test func nextBeatIsStrictlyAfterNow() {
|
||||
#expect(EventQuantum.nextBeat.targetBeat(from: 3.4) == 4.0)
|
||||
// On an exact beat, the next boundary is the following whole beat, not the current one.
|
||||
#expect(EventQuantum.nextBeat.targetBeat(from: 3.0) == 4.0)
|
||||
}
|
||||
|
||||
@Test func nextMultipleSnapsToTheNextGridLine() {
|
||||
#expect(EventQuantum.nextMultiple(ofBeats: 4.0).targetBeat(from: 5.2) == 8.0)
|
||||
// On an exact bar line, the next bar is the following one.
|
||||
#expect(EventQuantum.nextMultiple(ofBeats: 4.0).targetBeat(from: 4.0) == 8.0)
|
||||
#expect(EventQuantum.nextMultiple(ofBeats: 2.0).targetBeat(from: 0.5) == 2.0)
|
||||
}
|
||||
|
||||
@Test func atBeatIsAbsolute() {
|
||||
#expect(EventQuantum.atBeat(10.0).targetBeat(from: 2.0) == 10.0)
|
||||
}
|
||||
|
||||
@Test func atBeatInThePastResolvesToThatPastBeat() {
|
||||
// A beat already gone by resolves to itself (below now); the conductor treats it as already due.
|
||||
#expect(EventQuantum.atBeat(1.0).targetBeat(from: 5.0) == 1.0)
|
||||
}
|
||||
|
||||
@Test func nextBeatHandlesNearBoundaryFloat() {
|
||||
// Just shy of beat 3 rounds down to 2, so the next whole beat is 3.
|
||||
#expect(EventQuantum.nextBeat.targetBeat(from: 2.9999999999) == 3.0)
|
||||
}
|
||||
|
||||
@Test func afterBeatsIsRelativeAndClampsNegative() {
|
||||
#expect(EventQuantum.afterBeats(2.5).targetBeat(from: 2.0) == 4.5)
|
||||
#expect(EventQuantum.afterBeats(-1.0).targetBeat(from: 2.0) == 2.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
// MonoEventPatternTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Synchronization
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Shared fixtures
|
||||
|
||||
/// Single reused voice for `MonoEventPattern`. Records the sustain it was handed and counts its
|
||||
/// own re-articulations. A `SynthesizerBase` so `engine.add` invokes `build()` immediately.
|
||||
private final class MonoTestVoice: SynthesizerBase, EventRetriggerable, EventSustainAware {
|
||||
@LiveParam var freq: Double = 0.0
|
||||
var sustainSeconds: Double = -1.0
|
||||
|
||||
/// Number of `retrigger()` calls — expected to be one less than the event count (the first
|
||||
/// event is articulated by `build()` on add, not by `retrigger()`).
|
||||
var retriggerCount: Int = 0
|
||||
|
||||
/// Counts `build()` calls so the playback suite can prove the voice is added exactly once.
|
||||
nonisolated static let buildCount: Atomic<Int> = Atomic<Int>(0)
|
||||
|
||||
func setEventSustain(seconds: Double) {
|
||||
sustainSeconds = seconds
|
||||
}
|
||||
|
||||
func retrigger() {
|
||||
retriggerCount += 1
|
||||
}
|
||||
|
||||
override func build() {
|
||||
MonoTestVoice.buildCount.wrappingAdd(1, ordering: .releasing)
|
||||
output(bus: 0, source: $freq)
|
||||
}
|
||||
}
|
||||
|
||||
/// Voice conforming to neither optional protocol — proves a plain persistent voice (no
|
||||
/// re-articulation, no sustain hand-off) resolves cleanly.
|
||||
private final class PlainMonoVoice: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 0.0
|
||||
|
||||
override func build() {
|
||||
output(bus: 0, source: $freq)
|
||||
}
|
||||
}
|
||||
|
||||
/// Mono voice conforming to BOTH ``EventGated`` and ``EventSustainAware``. Proves gate precedence
|
||||
/// in the mono stream: a gated voice releases through its gate and is not also self-timed, so
|
||||
/// `setEventSustain` is never called and `sustainSeconds` keeps its sentinel.
|
||||
private final class GatedMonoVoice: SynthesizerBase, EventGated, EventSustainAware {
|
||||
@LiveParam var freq: Double = 0.0
|
||||
@LiveParam var gate: Double = 1.0
|
||||
var sustainSeconds: Double = -1.0
|
||||
|
||||
var eventGate: ParameterNode { $gate }
|
||||
|
||||
func setEventSustain(seconds: Double) {
|
||||
sustainSeconds = seconds
|
||||
}
|
||||
|
||||
override func build() {
|
||||
output(bus: 0, source: $freq * $gate)
|
||||
}
|
||||
}
|
||||
|
||||
/// Carries the persistent voice out of the main-actor setup block so the playback suite can
|
||||
/// inspect it (binding state, retrigger count) after waiting off-main. `@unchecked Sendable`:
|
||||
/// the voice is written and read only inside `MainActor.run` hops.
|
||||
private final class VoiceHolder: @unchecked Sendable {
|
||||
var voice: MonoTestVoice?
|
||||
}
|
||||
|
||||
/// `true` while `voice` is still bound to an engine (its ownership atomic is non-zero). Read on
|
||||
/// the main actor.
|
||||
@MainActor private func isBound(_ voice: MonoTestVoice?) -> Bool {
|
||||
guard let voice: MonoTestVoice = voice else { return false }
|
||||
return voice._engineBinding.load(ordering: .acquiring) != 0
|
||||
}
|
||||
|
||||
// MARK: - Pure-logic suite
|
||||
|
||||
/// `MonoEventPattern` event resolution — driven synchronously through the `MonoEventStream` core
|
||||
/// on the main actor. No background task, no engine: deterministic.
|
||||
///
|
||||
/// Note: `Pattern.sequence` defaults to `repeats: -1` (infinite cycling), so tests that expect a
|
||||
/// bounded stream pass `repeats: 1`.
|
||||
@MainActor
|
||||
@Suite("MonoEventPattern")
|
||||
struct MonoEventPatternLogicTests {
|
||||
|
||||
/// Drains a pattern's stream synchronously, snapshotting the reused voice's `freq` after each
|
||||
/// event. Returns the voice and the per-event `freq` snapshots.
|
||||
private func drainFreqs<V: Synthesizer>(
|
||||
_ pattern: MonoEventPattern<V>,
|
||||
reading freq: KeyPath<V, Double>,
|
||||
max: Int = 100
|
||||
) -> (voice: V, freqs: [Double]) {
|
||||
let stream: MonoEventStream<V> = pattern.makeEventStream()
|
||||
var freqs: [Double] = []
|
||||
while freqs.count < max, stream.next() != nil {
|
||||
freqs.append(stream.voice[keyPath: freq])
|
||||
}
|
||||
return (stream.voice, freqs)
|
||||
}
|
||||
|
||||
@Test func writesSequenceToOneVoice() {
|
||||
var makeCount: Int = 0
|
||||
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: {
|
||||
makeCount += 1
|
||||
return MonoTestVoice()
|
||||
})
|
||||
.bind(\.freq, .sequence([440.0, 550.0, 660.0], repeats: 1))
|
||||
|
||||
let result: (voice: MonoTestVoice, freqs: [Double]) = drainFreqs(pattern, reading: \.freq)
|
||||
#expect(result.freqs == [440.0, 550.0, 660.0])
|
||||
// One voice made for the whole stream.
|
||||
#expect(makeCount == 1)
|
||||
}
|
||||
|
||||
@Test func retriggerSkipsTheFirstEvent() {
|
||||
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: { MonoTestVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0, 660.0], repeats: 1))
|
||||
|
||||
let result: (voice: MonoTestVoice, freqs: [Double]) = drainFreqs(pattern, reading: \.freq)
|
||||
#expect(result.freqs.count == 3)
|
||||
// 3 events → 2 re-articulations (first is build()'s job).
|
||||
#expect(result.voice.retriggerCount == 2)
|
||||
}
|
||||
|
||||
@Test func endsWhenAnyBoundPatternExhausts() {
|
||||
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: { MonoTestVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
|
||||
.dur(.sequence([0.25, 0.25, 0.25, 0.25, 0.25], repeats: 1))
|
||||
|
||||
#expect(drainFreqs(pattern, reading: \.freq).freqs.count == 2)
|
||||
}
|
||||
|
||||
@Test func durExhaustionEndsStream() {
|
||||
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: { MonoTestVoice() })
|
||||
.bind(\.freq, .uniformRandom(low: 100.0, high: 200.0))
|
||||
.dur(.sequence([0.25, 0.25], repeats: 1))
|
||||
|
||||
#expect(drainFreqs(pattern, reading: \.freq).freqs.count == 2)
|
||||
}
|
||||
|
||||
@Test func repeatsReplaysTheWholeSet() {
|
||||
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: { MonoTestVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
|
||||
.repeats(3)
|
||||
|
||||
#expect(drainFreqs(pattern, reading: \.freq).freqs == [440.0, 550.0, 440.0, 550.0, 440.0, 550.0])
|
||||
}
|
||||
|
||||
@Test func legatoDeterminesSustainSeconds() {
|
||||
// delta 1 beat, legato 0.5 → sustain 0.5 beat; tempo 120 → 0.25 s.
|
||||
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: { MonoTestVoice() })
|
||||
.bind(\.freq, .sequence([440.0], repeats: 1))
|
||||
.dur(.sequence([1.0]))
|
||||
.legato(0.5)
|
||||
.tempo(120.0)
|
||||
|
||||
let result: (voice: MonoTestVoice, freqs: [Double]) = drainFreqs(pattern, reading: \.freq)
|
||||
#expect(result.freqs.count == 1)
|
||||
#expect(abs(result.voice.sustainSeconds - 0.25) < 1e-9)
|
||||
}
|
||||
|
||||
@Test func gatedMonoVoiceWinsOverSustainAware() {
|
||||
// A mono voice conforming to both: the gate drives release, so `setEventSustain` is never
|
||||
// called and `sustainSeconds` keeps its sentinel.
|
||||
let pattern: MonoEventPattern<GatedMonoVoice> = MonoEventPattern(make: { GatedMonoVoice() })
|
||||
.bind(\.freq, .sequence([440.0], repeats: 1))
|
||||
.dur(.sequence([1.0]))
|
||||
.legato(1.0)
|
||||
.tempo(60.0)
|
||||
|
||||
let result: (voice: GatedMonoVoice, freqs: [Double]) = drainFreqs(pattern, reading: \.freq)
|
||||
#expect(result.freqs.count == 1)
|
||||
#expect(result.voice.sustainSeconds == -1.0) // gated → setEventSustain not called
|
||||
}
|
||||
|
||||
@Test func plainVoiceResolvesWithoutOptionalProtocols() {
|
||||
let pattern: MonoEventPattern<PlainMonoVoice> = MonoEventPattern(make: { PlainMonoVoice() })
|
||||
.bind(\.freq, .sequence([100.0, 200.0, 300.0], repeats: 1))
|
||||
|
||||
#expect(drainFreqs(pattern, reading: \.freq).freqs == [100.0, 200.0, 300.0])
|
||||
}
|
||||
|
||||
@Test func repeatsBelowOnePlaysNothing() {
|
||||
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: { MonoTestVoice() })
|
||||
.bind(\.freq, .sequence([440.0], repeats: 1))
|
||||
.repeats(0)
|
||||
|
||||
#expect(drainFreqs(pattern, reading: \.freq).freqs.isEmpty)
|
||||
}
|
||||
|
||||
@Test func emptyPassWithHugeRepeatsTerminates() {
|
||||
// A pass yielding nothing must end the stream rather than spin, even with huge repeats.
|
||||
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: { MonoTestVoice() })
|
||||
.bind(\.freq, .sequence([], repeats: 1))
|
||||
.repeats(Int.max)
|
||||
|
||||
#expect(drainFreqs(pattern, reading: \.freq).freqs.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Playback suite (real play(on:))
|
||||
|
||||
/// `MonoEventPattern.play(on:)` driving the engine through a background `LyrebirdTask`. Not
|
||||
/// `@MainActor`: the body's hops need the real main thread free, so each test waits off-main.
|
||||
@Suite("MonoEventPattern Playback", .serialized)
|
||||
struct MonoEventPatternPlaybackTests {
|
||||
|
||||
/// Polls off-main (leaving main free to drain dispatched engine ops) until `check` holds or
|
||||
/// the deadline passes; returns the final value.
|
||||
private func poll(timeout: Double = 2.0, _ check: @escaping @MainActor () -> Bool) async -> Bool {
|
||||
let deadline: Date = Date().addingTimeInterval(timeout)
|
||||
while await MainActor.run(body: check) == false, Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
return await MainActor.run(body: check)
|
||||
}
|
||||
|
||||
@Test func addsAndRetriggersThenRemovesAtStreamEnd() async {
|
||||
MonoTestVoice.buildCount.store(0, ordering: .releasing)
|
||||
let holder: VoiceHolder = VoiceHolder()
|
||||
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let voice: MonoTestVoice = MonoTestVoice()
|
||||
holder.voice = voice
|
||||
return MonoEventPattern(make: { voice })
|
||||
.bind(\.freq, .sequence([440.0, 550.0, 660.0], repeats: 1))
|
||||
.dur(.sequence([0.02]))
|
||||
.tempo(240.0)
|
||||
.play(on: engine)
|
||||
}
|
||||
handle.waitUntilComplete()
|
||||
|
||||
// The persistent voice is added once (one build), re-struck on the 2nd and 3rd events,
|
||||
// and unbound once the finite stream ends.
|
||||
let unbound: Bool = await poll { isBound(holder.voice) == false }
|
||||
#expect(unbound)
|
||||
#expect(MonoTestVoice.buildCount.load(ordering: .acquiring) == 1)
|
||||
await MainActor.run {
|
||||
#expect(holder.voice?.retriggerCount == 2)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func removesVoiceOnStop() async {
|
||||
let holder: VoiceHolder = VoiceHolder()
|
||||
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let voice: MonoTestVoice = MonoTestVoice()
|
||||
holder.voice = voice
|
||||
return MonoEventPattern(make: { voice })
|
||||
.bind(\.freq, .uniformRandom(low: 100.0, high: 200.0))
|
||||
.dur(.sequence([0.05]))
|
||||
.tempo(120.0)
|
||||
.play(on: engine)
|
||||
}
|
||||
|
||||
// Let the voice get added, then stop — the voice must still be removed even though
|
||||
// `ctx.wait` throws `.stopped` out of the loop before the trailing remove.
|
||||
_ = await poll { isBound(holder.voice) }
|
||||
handle.stop()
|
||||
|
||||
#expect(await poll { !handle.isPlaying })
|
||||
#expect(await poll { isBound(holder.voice) == false })
|
||||
}
|
||||
|
||||
@Test func repeatsZeroAddsNothing() async {
|
||||
MonoTestVoice.buildCount.store(0, ordering: .releasing)
|
||||
let holder: VoiceHolder = VoiceHolder()
|
||||
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let voice: MonoTestVoice = MonoTestVoice()
|
||||
holder.voice = voice
|
||||
return MonoEventPattern(make: { voice })
|
||||
.bind(\.freq, .sequence([440.0], repeats: 1))
|
||||
.dur(.sequence([0.02]))
|
||||
.repeats(0)
|
||||
.play(on: engine)
|
||||
}
|
||||
handle.waitUntilComplete()
|
||||
_ = await poll { !handle.isPlaying }
|
||||
|
||||
// No events → the voice is never added (never built) and never bound.
|
||||
#expect(MonoTestVoice.buildCount.load(ordering: .acquiring) == 0)
|
||||
#expect(await MainActor.run { isBound(holder.voice) } == false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
// ParallelEventPatternTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Synchronization
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Shared fixtures
|
||||
|
||||
/// Voice for the polyphonic child — a fresh instance per event, so `build()` runs once per
|
||||
/// spawned voice.
|
||||
private final class ParPolyVoice: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 0.0
|
||||
nonisolated static let buildCount: Atomic<Int> = Atomic<Int>(0)
|
||||
|
||||
override func build() {
|
||||
ParPolyVoice.buildCount.wrappingAdd(1, ordering: .releasing)
|
||||
output(bus: 0, source: $freq)
|
||||
}
|
||||
}
|
||||
|
||||
/// Voice for the monophonic child — one reused instance, so `build()` runs exactly once.
|
||||
private final class ParMonoVoice: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 0.0
|
||||
nonisolated static let buildCount: Atomic<Int> = Atomic<Int>(0)
|
||||
|
||||
override func build() {
|
||||
ParMonoVoice.buildCount.wrappingAdd(1, ordering: .releasing)
|
||||
output(bus: 0, source: $freq)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Playback suite
|
||||
|
||||
/// `ParallelEventPattern.play(on:)` running a heterogeneous set of children (one `EventPattern`,
|
||||
/// one `MonoEventPattern`) on one engine through their own background tasks. Serialized because
|
||||
/// the fixtures share static build counters.
|
||||
@Suite("ParallelEventPattern Playback", .serialized)
|
||||
struct ParallelEventPatternPlaybackTests {
|
||||
|
||||
@Test func playsEveryChildToCompletion() async {
|
||||
ParPolyVoice.buildCount.store(0, ordering: .releasing)
|
||||
ParMonoVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let poly: EventPattern<ParPolyVoice> = EventPattern(make: { ParPolyVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
|
||||
.dur(.sequence([0.02]))
|
||||
.tempo(240.0)
|
||||
let mono: MonoEventPattern<ParMonoVoice> = MonoEventPattern(make: { ParMonoVoice() })
|
||||
.bind(\.freq, .sequence([100.0, 200.0, 300.0], repeats: 1))
|
||||
.dur(.sequence([0.02]))
|
||||
.tempo(240.0)
|
||||
return ParallelEventPattern([poly, mono]).play(on: engine)
|
||||
}
|
||||
handle.waitUntilComplete()
|
||||
|
||||
// Poly spawns one voice per event (2); mono adds one reused voice (1).
|
||||
let deadline: Date = Date().addingTimeInterval(2.0)
|
||||
while (ParPolyVoice.buildCount.load(ordering: .acquiring) < 2
|
||||
|| ParMonoVoice.buildCount.load(ordering: .acquiring) < 1), Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 2)
|
||||
#expect(ParMonoVoice.buildCount.load(ordering: .acquiring) == 1)
|
||||
|
||||
let stopped: Bool = await MainActor.run { !handle.isPlaying }
|
||||
#expect(stopped)
|
||||
}
|
||||
|
||||
@Test func isPlayingStaysTrueWhileAnyChildRuns() async {
|
||||
ParPolyVoice.buildCount.store(0, ordering: .releasing)
|
||||
ParMonoVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// A short finite poly child (2 quick events) alongside a long finite mono child (~0.5 s).
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let short: EventPattern<ParPolyVoice> = EventPattern(make: { ParPolyVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
|
||||
.dur(.sequence([0.02]))
|
||||
.tempo(240.0)
|
||||
let long: MonoEventPattern<ParMonoVoice> = MonoEventPattern(make: { ParMonoVoice() })
|
||||
.bind(\.freq, .sequence(Array(repeating: 100.0, count: 20), repeats: 1))
|
||||
.dur(.sequence([0.05]))
|
||||
.tempo(120.0)
|
||||
return ParallelEventPattern([short, long]).play(on: engine)
|
||||
}
|
||||
|
||||
// Once the short child has spawned both its voices it is done, but the long child keeps
|
||||
// the merged handle playing.
|
||||
let shortDone: Date = Date().addingTimeInterval(1.0)
|
||||
while ParPolyVoice.buildCount.load(ordering: .acquiring) < 2, Date() < shortDone {
|
||||
try? await Task.sleep(for: .milliseconds(10))
|
||||
}
|
||||
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 2)
|
||||
#expect(await MainActor.run { handle.isPlaying })
|
||||
|
||||
handle.waitUntilComplete()
|
||||
let deadline: Date = Date().addingTimeInterval(2.0)
|
||||
while handle.isPlaying, Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(!handle.isPlaying)
|
||||
}
|
||||
|
||||
@Test func nestedParallelPatternPlays() async {
|
||||
ParPolyVoice.buildCount.store(0, ordering: .releasing)
|
||||
ParMonoVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// A ParallelEventPattern nested as a child of another.
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let poly: EventPattern<ParPolyVoice> = EventPattern(make: { ParPolyVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
|
||||
.dur(.sequence([0.02]))
|
||||
.tempo(240.0)
|
||||
let mono: MonoEventPattern<ParMonoVoice> = MonoEventPattern(make: { ParMonoVoice() })
|
||||
.bind(\.freq, .sequence([100.0], repeats: 1))
|
||||
.dur(.sequence([0.02]))
|
||||
.tempo(240.0)
|
||||
let inner: ParallelEventPattern = ParallelEventPattern([mono])
|
||||
return ParallelEventPattern([poly, inner]).play(on: engine)
|
||||
}
|
||||
handle.waitUntilComplete()
|
||||
|
||||
let deadline: Date = Date().addingTimeInterval(2.0)
|
||||
while (ParPolyVoice.buildCount.load(ordering: .acquiring) < 2
|
||||
|| ParMonoVoice.buildCount.load(ordering: .acquiring) < 1), Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 2)
|
||||
#expect(ParMonoVoice.buildCount.load(ordering: .acquiring) == 1)
|
||||
#expect(await MainActor.run { !handle.isPlaying })
|
||||
}
|
||||
|
||||
@Test func stopStopsEveryChild() async {
|
||||
ParPolyVoice.buildCount.store(0, ordering: .releasing)
|
||||
ParMonoVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// Built with the no-arg initializer + add(_:), driving the builder path. Both children
|
||||
// are infinite.
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let poly: EventPattern<ParPolyVoice> = EventPattern(make: { ParPolyVoice() })
|
||||
.bind(\.freq, .uniformRandom(low: 100.0, high: 200.0))
|
||||
.dur(.sequence([0.05]))
|
||||
.tempo(120.0)
|
||||
let mono: MonoEventPattern<ParMonoVoice> = MonoEventPattern(make: { ParMonoVoice() })
|
||||
.bind(\.freq, .uniformRandom(low: 100.0, high: 200.0))
|
||||
.dur(.sequence([0.05]))
|
||||
.tempo(120.0)
|
||||
return ParallelEventPattern()
|
||||
.add(poly)
|
||||
.add(mono)
|
||||
.play(on: engine)
|
||||
}
|
||||
|
||||
try? await Task.sleep(for: .milliseconds(150))
|
||||
handle.stop()
|
||||
|
||||
let deadline: Date = Date().addingTimeInterval(2.0)
|
||||
while handle.isPlaying, Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(!handle.isPlaying)
|
||||
|
||||
// Both children were spawning, and both halt after stop.
|
||||
let polyAfterStop: Int = ParPolyVoice.buildCount.load(ordering: .acquiring)
|
||||
let monoAfterStop: Int = ParMonoVoice.buildCount.load(ordering: .acquiring)
|
||||
#expect(polyAfterStop > 0)
|
||||
#expect(monoAfterStop == 1) // mono adds its single voice once
|
||||
try? await Task.sleep(for: .milliseconds(120))
|
||||
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == polyAfterStop)
|
||||
#expect(ParMonoVoice.buildCount.load(ordering: .acquiring) == monoAfterStop)
|
||||
}
|
||||
|
||||
@Test func addAfterStaggersChildEntry() async {
|
||||
ParPolyVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// One child, staggered two beats in. At 120 BPM that is a 1.0 s lead-in before its first
|
||||
// voice is built; the task is live (waiting) throughout.
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let delayed: EventPattern<ParPolyVoice> = EventPattern(make: { ParPolyVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
|
||||
.dur(.sequence([0.02]))
|
||||
.tempo(120.0)
|
||||
return ParallelEventPattern()
|
||||
.addAfter(beats: 2.0, eventPattern: delayed)
|
||||
.play(on: engine)
|
||||
}
|
||||
|
||||
// Well inside the 1.0 s lead-in, no voice has been built yet, but the handle is playing.
|
||||
try? await Task.sleep(for: .milliseconds(300))
|
||||
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 0)
|
||||
#expect(await MainActor.run { handle.isPlaying })
|
||||
|
||||
// After the lead-in elapses the stream runs to completion: both events fire.
|
||||
handle.waitUntilComplete()
|
||||
let deadline: Date = Date().addingTimeInterval(2.0)
|
||||
while ParPolyVoice.buildCount.load(ordering: .acquiring) < 2, Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 2)
|
||||
#expect(await MainActor.run { !handle.isPlaying })
|
||||
}
|
||||
|
||||
@Test func addAfterZeroEntersWithGroup() async {
|
||||
ParPolyVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// addAfter(beats: 0) is equivalent to add(_:) — no lead-in, enters immediately.
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let child: EventPattern<ParPolyVoice> = EventPattern(make: { ParPolyVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
|
||||
.dur(.sequence([0.02]))
|
||||
.tempo(240.0)
|
||||
return ParallelEventPattern()
|
||||
.addAfter(beats: 0.0, eventPattern: child)
|
||||
.play(on: engine)
|
||||
}
|
||||
|
||||
handle.waitUntilComplete()
|
||||
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 2)
|
||||
#expect(await MainActor.run { !handle.isPlaying })
|
||||
}
|
||||
|
||||
@Test func stopDuringLeadInBuildsNoVoice() async {
|
||||
ParPolyVoice.buildCount.store(0, ordering: .releasing)
|
||||
|
||||
// A long-staggered child stopped mid-lead-in must self-terminate without building a voice.
|
||||
let handle: EventPatternHandle = await MainActor.run {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let delayed: EventPattern<ParPolyVoice> = EventPattern(make: { ParPolyVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
|
||||
.dur(.sequence([0.02]))
|
||||
.tempo(120.0)
|
||||
return ParallelEventPattern()
|
||||
.addAfter(beats: 8.0, eventPattern: delayed) // 4 s lead-in at 120 BPM
|
||||
.play(on: engine)
|
||||
}
|
||||
|
||||
// Still well inside the lead-in: playing, nothing built.
|
||||
try? await Task.sleep(for: .milliseconds(300))
|
||||
#expect(await MainActor.run { handle.isPlaying })
|
||||
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 0)
|
||||
|
||||
handle.stop()
|
||||
let deadline: Date = Date().addingTimeInterval(2.0)
|
||||
while (await MainActor.run { handle.isPlaying }), Date() < deadline {
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
#expect(await MainActor.run { !handle.isPlaying })
|
||||
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 0) // never reached its first event
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// RoutineContextScheduledSetTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Synchronization
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
/// `LyrebirdRoutineContext.set(_:to:after:)` — non-blocking scheduled parameter writes, serviced
|
||||
/// on the body's own timeline during waits. These back the event-pattern gate note-off.
|
||||
///
|
||||
/// Not `@MainActor`: `LyrebirdTask.run` blocks the calling thread and the body runs off-main, so
|
||||
/// running the test off-main leaves the main queue free (matching the other `LyrebirdTask` suites).
|
||||
/// A bare `ParameterNode` is the write target — its value get/set is atomic and thread-safe, so no
|
||||
/// synthesizer or engine graph is needed to observe the write.
|
||||
@Suite("RoutineContext scheduled set") struct RoutineContextScheduledSetTests {
|
||||
|
||||
@Test func scheduledSetFiresAfterDelayNotBefore() {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let node: ParameterNode = ParameterNode(1.0)
|
||||
let before: Ref<Double> = Ref(-1.0)
|
||||
let after: Ref<Double> = Ref(-1.0)
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
ctx.set(node, to: 0.0, after: 0.05)
|
||||
before.value = node.value // not yet due — still 1.0
|
||||
try ctx.wait(seconds: 0.15) // services the pending set en route
|
||||
after.value = node.value // fired — 0.0
|
||||
}
|
||||
|
||||
#expect(before.value == 1.0)
|
||||
#expect(after.value == 0.0)
|
||||
}
|
||||
|
||||
@Test func multipleScheduledSetsFireIndependently() {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let a: ParameterNode = ParameterNode(0.0)
|
||||
let b: ParameterNode = ParameterNode(0.0)
|
||||
let midA: Ref<Double> = Ref(-1.0)
|
||||
let midB: Ref<Double> = Ref(-1.0)
|
||||
let endA: Ref<Double> = Ref(-1.0)
|
||||
let endB: Ref<Double> = Ref(-1.0)
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
ctx.set(a, to: 1.0, after: 0.04) // fires first
|
||||
ctx.set(b, to: 1.0, after: 0.12) // fires later
|
||||
try ctx.wait(seconds: 0.08) // past a, before b
|
||||
midA.value = a.value // 1.0
|
||||
midB.value = b.value // still 0.0
|
||||
try ctx.wait(seconds: 0.10) // past b
|
||||
endA.value = a.value
|
||||
endB.value = b.value // 1.0
|
||||
}
|
||||
|
||||
#expect(midA.value == 1.0)
|
||||
#expect(midB.value == 0.0)
|
||||
#expect(endA.value == 1.0)
|
||||
#expect(endB.value == 1.0)
|
||||
}
|
||||
|
||||
@Test func waitForScheduledSetsDrainsPending() {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let node: ParameterNode = ParameterNode(1.0)
|
||||
let result: Ref<Double> = Ref(-1.0)
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
ctx.set(node, to: 0.0, after: 0.05)
|
||||
// No explicit wait — `waitForScheduledSets` must itself block until the write fires.
|
||||
try ctx.waitForScheduledSets()
|
||||
result.value = node.value
|
||||
}
|
||||
|
||||
#expect(result.value == 0.0)
|
||||
}
|
||||
|
||||
@Test func flushFiresPendingSetsImmediately() {
|
||||
let engine: SynthesisEngine = makeTestEngine()
|
||||
let node: ParameterNode = ParameterNode(1.0)
|
||||
let afterFlush: Ref<Double> = Ref(-1.0)
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
ctx.set(node, to: 0.0, after: 100.0) // due far in the future
|
||||
ctx._flushScheduledSets() // fire now regardless of due time
|
||||
afterFlush.value = node.value
|
||||
}
|
||||
|
||||
#expect(afterFlush.value == 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal reference box so a `@Sendable` task body can report a result back to the test.
|
||||
/// `@unchecked Sendable`: the body writes `value`, the test reads it only after `LyrebirdTask.run`
|
||||
/// has joined the body thread — no concurrent access.
|
||||
private final class Ref<T>: @unchecked Sendable {
|
||||
var value: T
|
||||
init(_ value: T) { self.value = value }
|
||||
}
|
||||
@@ -115,7 +115,7 @@ import LyrebirdSynth
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512, sampleRate: 48000,
|
||||
numOutputChannels: 2, numInputChannels: 2,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver() // CoreAudio (macOS) / iOS / ALSA (Linux)
|
||||
)
|
||||
do { try engine.start() } catch { print("Engine failed: \(error)"); exit(1) }
|
||||
|
||||
|
||||
@@ -134,6 +134,43 @@ swift package update Lyrebird # resolves to the new tag if Package.swift `fro
|
||||
swift build && swift test
|
||||
```
|
||||
|
||||
### 6. Re-render the online docs (every public/gitea release)
|
||||
|
||||
`lyrebirdsynth.net/docs` is a static DocC export (WordPress on Bluehost, uploaded
|
||||
over SSH). It does **not** regenerate itself — after a public release that changed
|
||||
docs or public API, rebuild the site folders so the maintainer can re-upload, or the
|
||||
online docs go stale. Render from the **released HEAD** into the durable folder
|
||||
`~/Documents/lyrebird-docs-site/` (not a scratch dir):
|
||||
|
||||
```bash
|
||||
DEST=~/Documents/lyrebird-docs-site
|
||||
cd ~/Documents/src/Lyrebird
|
||||
|
||||
# Core — all guides + symbol reference.
|
||||
swift package --allow-writing-to-directory "$DEST/lyrebird" generate-documentation \
|
||||
--target LyrebirdSynth --disable-indexing --transform-for-static-hosting \
|
||||
--hosting-base-path docs/lyrebird --output-path "$DEST/lyrebird"
|
||||
```
|
||||
|
||||
UI needs one caveat: `Sources/LyrebirdUI/LyrebirdUIExports.swift` does
|
||||
`@_exported import SwiftUI`, which makes DocC fold the **entire** SwiftUI API into
|
||||
LyrebirdUI's reference (165k pages / 2.3G instead of the correct ~34 real types /
|
||||
261M). Temporarily demote it to a plain `import` for the UI build only, then restore:
|
||||
|
||||
```bash
|
||||
E=Sources/LyrebirdUI/LyrebirdUIExports.swift
|
||||
perl -pi -e 's/^\@_exported import SwiftUI/import SwiftUI/' "$E"
|
||||
swift package --allow-writing-to-directory "$DEST/lyrebirdui" generate-documentation \
|
||||
--target LyrebirdUI --disable-indexing --transform-for-static-hosting \
|
||||
--hosting-base-path docs/lyrebirdui --output-path "$DEST/lyrebirdui"
|
||||
git checkout -- "$E" # restore @_exported — MUST run even if the build fails
|
||||
```
|
||||
|
||||
Keep `$DEST/index.html` (landing), `$DEST/.htaccess` (Apache rewrite for DocC
|
||||
client-side routes — **required** or deep links 404 under WordPress), and
|
||||
`$DEST/UPLOAD.md` (rsync-over-SSH to `~/public_html/docs/`). Expected: core ~115M,
|
||||
UI ~261M. Tell the maintainer the folder is ready; the upload itself is theirs.
|
||||
|
||||
## Flags
|
||||
|
||||
- `--dev PATH` / `--release PATH` — override the default repo locations.
|
||||
|
||||
@@ -52,7 +52,7 @@ let cfg = SynthesisEngineConfig(
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
let engine = try host.makeEngine(role: .rtOutput(deviceID: 0), config: cfg)
|
||||
```
|
||||
|
||||
@@ -43,13 +43,13 @@ A Lyrebird program is a normal Swift program that uses the Lyrebird library. Her
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// The engine owns Core Audio and runs the audio graph.
|
||||
// The engine owns the audio device and runs the audio graph.
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
|
||||
// A synthesizer describes the sound.
|
||||
@@ -98,7 +98,7 @@ let engine: SynthesisEngine = SynthesisEngine(
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
```
|
||||
|
||||
@@ -108,7 +108,7 @@ let engine: SynthesisEngine = SynthesisEngine(
|
||||
- `blockSize: 512` — the engine processes audio 512 samples at a time. (Lyrebird caps this at 512.)
|
||||
- `sampleRate: 48000` — 48,000 samples per second.
|
||||
- `numOutputChannels: 2` — stereo out. `numInputChannels: 0` — no microphone input.
|
||||
- `driver: CoreAudioDriver()` — talk to the Mac's audio hardware. (iOS uses a different driver; guide 4.)
|
||||
- `driver: makeDefaultAudioDriver()` — connect to the platform's audio hardware. It picks the backend automatically: Core Audio on macOS, the iOS driver on iOS, ALSA on Linux (and a silent offline driver where no live audio exists), so the same line works everywhere. (guide 4.)
|
||||
|
||||
### Describing the sound
|
||||
|
||||
|
||||
@@ -227,7 +227,7 @@ import LyrebirdSynth
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512, sampleRate: 44100,
|
||||
numOutputChannels: 2, numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
try engine.start()
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ let engine = SynthesisEngine(
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
try engine.start()
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ Use `NRTDriver` for most cases — it is a drop-in replacement for `CoreAudioDri
|
||||
|
||||
### Basic usage
|
||||
|
||||
Replace `CoreAudioDriver()` with `NRTDriver(outputURL:duration:)`. Everything else stays the same.
|
||||
Replace `makeDefaultAudioDriver()` with `NRTDriver(outputURL:duration:)`. Everything else stays the same.
|
||||
|
||||
```swift
|
||||
import Foundation
|
||||
|
||||
@@ -146,7 +146,7 @@ let engine = SynthesisEngine(
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 2,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
|
||||
// Add your Synthesizers here.
|
||||
|
||||
@@ -69,7 +69,7 @@ import LyrebirdSynth
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512, sampleRate: 44100,
|
||||
numOutputChannels: 2, numInputChannels: 2,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
try engine.start()
|
||||
|
||||
|
||||
@@ -104,6 +104,83 @@ The same factories on the demand side are implemented as separate `DemandGenerat
|
||||
|
||||
---
|
||||
|
||||
## EventPattern — event-driven playback
|
||||
|
||||
`EventPattern` is the heart of Lyrebird's event-driven playback: it binds named value `Pattern`s to a voice's parameters and plays them as a timed stream of voices. Each event pulls one value from every bound pattern plus the duration pattern, makes a fresh voice, writes the pulled values into its parameters, adds it to the engine, and reaps it (see Lifecycle below) — then waits the event's duration before the next event.
|
||||
|
||||
```swift
|
||||
final class PluckVoice: SynthesizerBase, EventSustainAware {
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.2
|
||||
private var sustainSeconds: Double = 1.0
|
||||
|
||||
func setEventSustain(seconds: Double) { sustainSeconds = seconds }
|
||||
|
||||
override func build() {
|
||||
// An envelope sized to `sustainSeconds` that frees the voice when it finishes
|
||||
// (`.freeNode` → SynthesizerBase auto-frees when the envelope completes).
|
||||
let env: EnvelopeGen.Audio = EnvelopeGen.Audio(
|
||||
envelope: Envelope(levels: [0, 1, 0], durations: [0.01, sustainSeconds], curves: [0, 0]),
|
||||
doneAction: .freeNode
|
||||
)
|
||||
output(bus: 0, source: OscSin.Audio(freq: $freq) * $amp * env)
|
||||
}
|
||||
}
|
||||
|
||||
let handle: EventPatternHandle = EventPattern(make: { PluckVoice() })
|
||||
.bind(\.freq, .sequence([440.0, 550.0, 660.0]))
|
||||
.bind(\.amp, .uniformRandom(low: 0.1, high: 0.4))
|
||||
.dur(.sequence([0.25, 0.25, 0.5]))
|
||||
.legato(0.9)
|
||||
.tempo(132.0)
|
||||
.play(on: engine)
|
||||
```
|
||||
|
||||
### Design
|
||||
|
||||
- **Typed binding, not an event dictionary.** A binding is a `ReferenceWritableKeyPath` into a concrete voice type (`\.freq`), checked at compile time. There is no untyped event dictionary.
|
||||
- **No default-event prototype.** There is no name-to-name conversion chain (degree → note → freq, dB → amp) and no sustain/legato prototype math. The voice owns its envelope; the pattern owns timing. Pass the values you actually want in the units the voice expects.
|
||||
- Binding key paths must be *formed* on the main actor (a `@LiveParam` is main-actor-isolated). Ordinary setup code already runs there; this only matters for off-main test code.
|
||||
|
||||
### Lifecycle
|
||||
|
||||
Per event (in beats): `delta` is pulled from the `dur` pattern, `sustain = delta * legato`. The voice is added, then reaped by one of three paths:
|
||||
|
||||
- **`EventGated`** — the voice exposes its gate `@LiveParam` as `eventGate`. The pattern opens the gate on add (default the parameter open so the attack fires) and schedules a note-off (gate → `0`) `sustain` beats later, via a non-blocking, overlap-safe `ctx.set(_:to:afterBeats:)` — a `legato` above `1.0` overlaps successive voices. The voice's gated `EnvelopeGen` (`releaseNode` + `doneAction: .freeNode`) plays its release and frees itself. The pattern never hard-removes it.
|
||||
- **`EventSustainAware`** — the voice is handed `sustain` in seconds just before being added, so it shapes a fixed-duration self-freeing envelope. Also never hard-removed.
|
||||
- **Plain** (neither protocol) — the voice is scheduled for removal `sustain + releaseTail` beats later (`ctx.remove(afterBeats:)`). This is the only path `releaseTail` affects.
|
||||
|
||||
The stream ends when the `dur` pattern or **any** bound pattern is exhausted; `.repeats(n)` replays the whole bound set `n` times (resetting the patterns between). On `stop()`, outstanding gate note-offs are fired immediately so gated voices release and self-free rather than hanging open.
|
||||
|
||||
### Monophonic and parallel
|
||||
|
||||
- `MonoEventPattern` reuses a single persistent voice: one voice is made and added once, its parameters updated per event, and torn down when the stream ends **or** when the handle is stopped. A voice conforming to `EventRetriggerable` is re-struck (`retrigger()`) on every event after the first — per-event articulation; a voice that does not conform plays continuously with its parameters gliding per event. When the voice is also `EventSustainAware`, its sustain is set before each `retrigger()`. An `EventGated` voice is held open across the whole stream and note-off'd once at teardown (gate → `0`, release plays, self-frees); a non-gated voice is removed after `releaseTail` beats.
|
||||
- `ParallelEventPattern` plays several patterns at once: it holds any mix of `EventPattern` and `MonoEventPattern` children (`EventPatternPlayable`) and starts each on its own task back to back. The children share no common clock — same-tempo children begin within thread-start latency of each other and are not re-synchronised afterwards (small drift can accumulate over long runs); different tempos run polytemporally. `add(_:)` adds a child that enters with the group; `addAfter(beats:eventPattern:)` staggers a child's entry a fixed number of beats into the group's start grid (the child simply waits that lead-in before its first event). It returns one `EventPatternHandle` whose `stop()` stops every child and whose `waitUntilComplete(releasePadding:)` returns once all finite children finish. The group is a **fire-once start**: compose every child before `play`. For live, beat-quantised insertion after playback has begun (a UI button, an OSC or MIDI callback), use `EventConductor` instead — see below.
|
||||
|
||||
### EventConductor — live, clock-driven ensemble
|
||||
|
||||
`ParallelEventPattern` composes its children up front and fires once. `EventConductor` keeps a background clock running and lets you push patterns in **while it plays**, from any thread:
|
||||
|
||||
```swift
|
||||
let conductor = EventConductor(tempo: 128.0)
|
||||
conductor.start(on: engine)
|
||||
let drumsPart = conductor.add(drums, quantize: .now) // start the groove now
|
||||
// … later, from a GUI button / OSC / MIDI callback, on any thread …
|
||||
let bassPart = conductor.add(bass, quantize: .nextMultiple(ofBeats: 4)) // drops in on the next bar
|
||||
// … later still …
|
||||
bassPart.stop() // stops the bass alone; the drums play on
|
||||
```
|
||||
|
||||
- `add(_:quantize:)` is thread-safe — call it from a UI, OSC or MIDI handler on any thread. It enqueues under a lock and returns an `EventConductorHandle` at once; the conductor's own task drains the queue each poll (~10 ms) and starts due patterns on the main thread (voice construction is main-actor-isolated). Defaults to `.nextBeat`.
|
||||
- The returned `EventConductorHandle` stops **one part**: `stop()` cancels it if still pending (no voice is built) or stops it if already playing (its gated voices release), leaving the other parts running. `isPlaying` reports pending-or-playing. This is the per-part counterpart to the conductor's own `stop()`, which stops everything. Perfect for a toggle button per part.
|
||||
- `EventQuantum` names the entry boundary: `.now`, `.nextBeat`, `.nextMultiple(ofBeats:)` (the next bar/grid line), `.atBeat(_:)` (absolute), `.afterBeats(_:)` (a relative lead-in, the direct analogue of `ParallelEventPattern.addAfter`).
|
||||
- **The clock quantises only each pattern's _entry_.** A resolved pattern is held until the conductor's clock reaches its target beat, then started — so entry aligns to the conductor's grid within the poll granularity (~10 ms), **independent of the pattern's own tempo**. Once started, a pattern runs its own relative `wait(beats:)` chain at its own tempo — exactly as under `EventPattern`/`ParallelEventPattern` — so patterns can be polytempo, and the conductor does not re-align their individual events afterwards.
|
||||
- `stop()` halts the clock and every pattern it started (idempotent; further `add` is ignored). `isRunning`, `hasActiveChildren`, and `currentBeat` are thread-safe reads. For finite content, `waitUntilIdle(releasePadding:)` blocks until nothing is pending and no child is still playing, then waits out the release tails — add the patterns, `waitUntilIdle`, then `stop()`.
|
||||
|
||||
Playback runs on a background `LyrebirdTask`; voice construction and parameter writes hop to the main thread. The returned `EventPatternHandle` has `stop()`, `isPlaying`, and `waitUntilComplete(releasePadding:)` — the latter blocks until every finite pattern finishes, then waits an extra `releasePadding` seconds so the last voices' envelope release tails ring out before a caller (a CLI demo, an offline render) tears the engine down. A long-lived app keeps the engine running and leaves `releasePadding` at its `0` default.
|
||||
|
||||
---
|
||||
|
||||
## LyrebirdRoutine
|
||||
|
||||
Runs a closure **once** on a dedicated background thread (`Thread`, `.userInitiated` QoS).
|
||||
|
||||
@@ -63,7 +63,7 @@ swift run LyrebirdDemo
|
||||
|
||||
Demonstrates: `SynthesizerBase`, `@LiveParam`, `OscSin`, `DelayLine`, `engine.add`/`remove`, and RT-safe parameter updates from the main thread. Runs real-time audio via `CoreAudioDriver`, plays for a few seconds, then stops.
|
||||
|
||||
**Copy this target** when you want a headless synthesis starting point. Swap `CoreAudioDriver()` for `NRTDriver(outputURL:duration:)` to render offline to a file — see [nrt-guide.md](nrt-guide.md).
|
||||
**Copy this target** when you want a headless synthesis starting point. Swap `makeDefaultAudioDriver()` for `NRTDriver(outputURL:duration:)` to render offline to a file — see [nrt-guide.md](nrt-guide.md).
|
||||
|
||||
### `LyrebirdUIDemo` — GUI starting point
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ import LyrebirdSynth
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: 512, sampleRate: 44100,
|
||||
numOutputChannels: 2, numInputChannels: 2,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
try engine.start()
|
||||
|
||||
@@ -153,7 +153,7 @@ let engine = SynthesisEngine(
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 2,
|
||||
driver: CoreAudioDriver()
|
||||
driver: makeDefaultAudioDriver()
|
||||
)
|
||||
|
||||
let kick = KickDrum()
|
||||
|
||||
@@ -6,8 +6,9 @@ LYREBIRD_START_HERE.md 0 a2547833f11acd72 none
|
||||
LYREBIRD_START_HERE.md 3 c0653ad6f9dc0f5b none
|
||||
LYREBIRD_START_HERE.md 4 3d0d1e2673fda229 none
|
||||
README.md 0 1d7c7c19c5a6d112 none
|
||||
README.md 1 3190dd60b6a8f7f8 none
|
||||
README.md 3 4bd7e864af2f05fd none
|
||||
README.md 1 9e7419986634c82c none
|
||||
README.md 2 3190dd60b6a8f7f8 none
|
||||
README.md 4 d4768129a1cfed0f none
|
||||
Sources/Lyrebird/AudioDrivers/CoreAudioDriver.swift 0 2b7f04ec486a9a5d none
|
||||
Sources/Lyrebird/AudioDrivers/DefaultAudioDriver.swift 0 5b79c5afb54ed465 none
|
||||
Sources/Lyrebird/Buffers/WavetableSet.swift 0 d2f7469591d6a837 none
|
||||
@@ -106,7 +107,7 @@ Sources/Lyrebird/Lyrebird.docc/DiagnosticsGuide.md 3 4f36c6bd97e3df32 none
|
||||
Sources/Lyrebird/Lyrebird.docc/DiagnosticsGuide.md 4 f1c7f9029c6f48ea none
|
||||
Sources/Lyrebird/Lyrebird.docc/DiagnosticsGuide.md 8 8efe9dc71d2dd8dd engine
|
||||
Sources/Lyrebird/Lyrebird.docc/DiagnosticsGuide.md 9 a0ccfaf1137b9c84 engine
|
||||
Sources/Lyrebird/Lyrebird.docc/EngineSetup.md 0 cfce51934da66872 none
|
||||
Sources/Lyrebird/Lyrebird.docc/EngineSetup.md 0 7cfe8e6e89b6005e none
|
||||
Sources/Lyrebird/Lyrebird.docc/EngineSetup.md 1 6a365ef4f437a5f0 engine
|
||||
Sources/Lyrebird/Lyrebird.docc/EngineSetup.md 2 f4d72dca55661e7f engine
|
||||
Sources/Lyrebird/Lyrebird.docc/EngineSetup.md 3 3d81a4c501cf0801 engine
|
||||
@@ -240,8 +241,8 @@ Sources/Lyrebird/Lyrebird.docc/Generators/WritingGenerators.md 2 2134b4cd357e438
|
||||
Sources/Lyrebird/Lyrebird.docc/Generators/WritingGenerators.md 4 b4dc205b9aa5fc5a none
|
||||
Sources/Lyrebird/Lyrebird.docc/GettingStarted.md 0 3ab248f11418d799 none
|
||||
Sources/Lyrebird/Lyrebird.docc/GettingStarted.md 1 45ba41d51b1116b5 none
|
||||
Sources/Lyrebird/Lyrebird.docc/GettingStarted.md 2 df30c1eb8663478c synth
|
||||
Sources/Lyrebird/Lyrebird.docc/Lyrebird.md 0 34c2d1c25110eceb synth
|
||||
Sources/Lyrebird/Lyrebird.docc/GettingStarted.md 2 c5ca5bc6162803a3 synth
|
||||
Sources/Lyrebird/Lyrebird.docc/Lyrebird.md 0 cf74375c53429db5 synth
|
||||
Sources/Lyrebird/Lyrebird.docc/MultiCore.md 1 8c645d659f87c9e7 none
|
||||
Sources/Lyrebird/Lyrebird.docc/NRTGuide.md 0 5493b7be98c51e79 none
|
||||
Sources/Lyrebird/Lyrebird.docc/NRTGuide.md 10 2d0a41bdf5b1bbd8 none
|
||||
@@ -269,13 +270,15 @@ Sources/Lyrebird/Lyrebird.docc/ParameterInputs.md 0 d31f119c2f2c873c none
|
||||
Sources/Lyrebird/Lyrebird.docc/ParameterInputs.md 1 6320b52dca1af028 none
|
||||
Sources/Lyrebird/Lyrebird.docc/ParameterInputs.md 6 6b933bd11ae2b8d3 engine
|
||||
Sources/Lyrebird/Lyrebird.docc/PolyphonicVoices.md 1 9baae05324ee9c36 engine
|
||||
Sources/Lyrebird/Lyrebird.docc/ProcessSystem.md 31 16ac8c55fec10e72 none
|
||||
Sources/Lyrebird/Lyrebird.docc/ProjectSystem.md 1 5ca73171977bcda7 none
|
||||
Sources/Lyrebird/Lyrebird.docc/ProcessSystem.md 31 5e03e7865c8f4ace none
|
||||
Sources/Lyrebird/Lyrebird.docc/ProjectSystem.md 1 371e7bb6ce49e53f none
|
||||
Sources/Lyrebird/Lyrebird.docc/ProjectSystem.md 2 bd3f90eb47fd6006 none
|
||||
Sources/Lyrebird/Lyrebird.docc/REPLGuide.md 0 44e28203300162fe none
|
||||
Sources/Lyrebird/Lyrebird.docc/REPLGuide.md 0 2dc70e99b6404557 none
|
||||
Sources/Lyrebird/Lyrebird.docc/RoutineTask.md 0 97969b7e340a3fad none
|
||||
Sources/Lyrebird/Lyrebird.docc/RoutineTask.md 14 86a37ee4afa1de70 none
|
||||
Sources/Lyrebird/Lyrebird.docc/RoutineTask.md 16 62b70fad58edb312 engine
|
||||
Sources/Lyrebird/Lyrebird.docc/RoutineTask.md 18 6c7cd38b55be4255 none
|
||||
Sources/Lyrebird/Lyrebird.docc/RoutineTask.md 19 de8e6d005257a668 none
|
||||
Sources/Lyrebird/Lyrebird.docc/RoutineTask.md 2 925a5e2121afa5e3 engine
|
||||
Sources/Lyrebird/Lyrebird.docc/Scheduling.md 0 2c95d843ffa87129 none
|
||||
Sources/Lyrebird/Lyrebird.docc/Scheduling.md 2 f6081f955c94e613 engine
|
||||
@@ -364,6 +367,7 @@ Sources/Lyrebird/Math/LyrebirdMusicMath.swift 5 c93b09a35c5656b6 none
|
||||
Sources/Lyrebird/Math/LyrebirdMusicMath.swift 6 1e2f63b9517d115d none
|
||||
Sources/Lyrebird/Math/LyrebirdMusicMath.swift 7 63878da5cac0b38e none
|
||||
Sources/Lyrebird/OSC/OSCClient.swift 0 8d156b807b49c1a5 none
|
||||
Sources/Lyrebird/Patterns/Events/EventGated.swift 0 895e2f84f48852ef none
|
||||
Sources/Lyrebird/Scheduling/LyrebirdTask.swift 1 ca99def354fe2f0a engine
|
||||
Sources/Lyrebird/Score/Glissando.swift 0 673ddef8256aa6b3 none
|
||||
Sources/Lyrebird/Score/NoteDisplay.swift 0 f706dacb94d58307 none
|
||||
@@ -395,6 +399,7 @@ Sources/Lyrebird/TemporalStream/Algorithms/TemporalTendency.swift 0 c710ddd78ba4
|
||||
Sources/Lyrebird/TemporalStream/Algorithms/TemporalTendency.swift 2 da1b4e7b74d72598 none
|
||||
Sources/LyrebirdUI/LyrebirdUI.docc/GUISystem.md 0 a7c7ea54be39417e none
|
||||
Sources/LyrebirdUI/MouseTracker.swift 0 5b5368aaa517dfa7 none
|
||||
Sources/LyrebirdUI/MouseTracker.swift 1 5b5368aaa517dfa7 none
|
||||
docs/diagnostics-guide.md 10 dc9b6d6a6320a78c engine
|
||||
docs/diagnostics-guide.md 2 42a857719bcee2d7 none
|
||||
docs/diagnostics-guide.md 3 4f36c6bd97e3df32 none
|
||||
@@ -405,7 +410,7 @@ docs/engine/alsa-audio-driver.md 0 d255cf28c7eff929 none
|
||||
docs/engine/bus-system.md 0 7aa0d214382e2c02 none
|
||||
docs/engine/bus-system.md 4 1420e89a6b21dffd member
|
||||
docs/engine/bus-system.md 5 5882de3452d3fb30 member
|
||||
docs/engine/multi-engine-host.md 1 10672b6a8d764ee0 none
|
||||
docs/engine/multi-engine-host.md 1 0032b031fd5a5dbc none
|
||||
docs/engine/scheduling.md 0 2c95d843ffa87129 none
|
||||
docs/engine/scheduling.md 5 18f17a73ca3ff9ae none
|
||||
docs/engine/synthesis-engine.md 1 a5fd826f8cdc7143 engine
|
||||
@@ -413,9 +418,9 @@ docs/engine/synthesis-engine.md 5 b86ed5cdad961753 engine
|
||||
docs/engine/synthesis-engine.md 7 420a077205369626 engine
|
||||
docs/engine/synthesis-engine.md 8 17aeb564649952e4 engine
|
||||
docs/learning-swift/01-hello-world.md 0 03653506ac9beeb2 none
|
||||
docs/learning-swift/01-hello-world.md 1 ed87a599242dc1ac none
|
||||
docs/learning-swift/01-hello-world.md 1 960bf10c1da5bae7 none
|
||||
docs/learning-swift/01-hello-world.md 2 0df7f63da21f430c none
|
||||
docs/learning-swift/01-hello-world.md 3 7fb514e0b937b06b none
|
||||
docs/learning-swift/01-hello-world.md 3 370a407cba47b238 none
|
||||
docs/learning-swift/01-hello-world.md 4 5f8c95401204fb36 none
|
||||
docs/learning-swift/02-swift-basics.md 0 560d2988df332558 none
|
||||
docs/learning-swift/02-swift-basics.md 1 74425300ee178185 none
|
||||
@@ -430,6 +435,7 @@ docs/learning-swift/03-types-and-functional.md 5 ba1ff2d440140b4d none
|
||||
docs/learning-swift/03-types-and-functional.md 7 bd9afda685bee4eb none
|
||||
docs/learning-swift/03-types-and-functional.md 8 1f72f3e7f59aa2ba none
|
||||
docs/learning-swift/04-xcode-and-packages.md 3 391201fc9e1fa104 none
|
||||
docs/migrating-to-2.0.md 2 d5ea5668715939f8 none
|
||||
docs/protocols/generator.md 0 759d4352212759f3 none
|
||||
docs/protocols/generator.md 2 a0f4ffb20378c07d none
|
||||
docs/protocols/generator.md 3 0f13c732d11665c0 none
|
||||
@@ -552,19 +558,20 @@ docs/stdlib/theory.md 7 cb778d54e742c021 none
|
||||
docs/stdlib/theory.md 8 ac601091423d2985 none
|
||||
docs/stdlib/theory.md 9 74dda0c11f3d34c4 none
|
||||
docs/tooling/cli-guide.md 0 1407c405647e96de none
|
||||
docs/tooling/cli-guide.md 1 5173fda0e36a5213 none
|
||||
docs/tooling/midi-clock-sync.md 0 526a3779a15793c6 none
|
||||
docs/tooling/cli-guide.md 1 d458830d43b7be3e none
|
||||
docs/tooling/midi-clock-sync.md 0 dd95b6fa4608e119 none
|
||||
docs/tooling/nrt-guide.md 0 046617aa0016f750 none
|
||||
docs/tooling/nrt-guide.md 14 f06ebc900acda570 none
|
||||
docs/tooling/nrt-guide.md 4 11c60dfed731ac6c none
|
||||
docs/tooling/nrt-guide.md 7 5b70d42bbb32382d engine
|
||||
docs/tooling/nrt-guide.md 9 7a2bd7072c940754 none
|
||||
docs/tooling/project-system.md 1 f4208870a115401f none
|
||||
docs/tooling/project-system.md 1 a92cddd62262b494 none
|
||||
docs/tooling/project-system.md 3 491d32c269a92cbf none
|
||||
docs/tooling/repl.md 0 28355170a44f09cd none
|
||||
docs/tooling/repl.md 0 fe33a7d93a42d23c none
|
||||
docs/tooling/routine-task.md 1 13ef865253b3351c none
|
||||
docs/tooling/routine-task.md 11 b95b191b847d061e engine
|
||||
docs/tooling/routine-task.md 9 be652d2b3b6f274f none
|
||||
docs/tooling/routine-task.md 11 be652d2b3b6f274f none
|
||||
docs/tooling/routine-task.md 13 b95b191b847d061e engine
|
||||
docs/tooling/routine-task.md 2 349a3e7d68141cb4 engine
|
||||
docs/tooling/targets.md 0 81b40cbafc6f2d80 none
|
||||
docs/tooling/targets.md 1 611af51e70b6320e none
|
||||
docs/ui/gui-system.md 0 84caaf99ee346e95 none
|
||||
|
||||
@@ -253,9 +253,15 @@ def modules_dir(root: Path) -> Path:
|
||||
proc = subprocess.run(["swift", "build", "--show-bin-path"], cwd=root,
|
||||
capture_output=True, text=True)
|
||||
if proc.returncode == 0 and proc.stdout.strip():
|
||||
d = Path(proc.stdout.strip()) / "Modules"
|
||||
bin_dir = Path(proc.stdout.strip())
|
||||
d = bin_dir / "Modules"
|
||||
if d.is_dir():
|
||||
return d
|
||||
# Newer SwiftPM build layouts (e.g. .build/out/Products/Debug) drop the
|
||||
# Modules/ subdir and place the .swiftmodule bundles directly in the bin
|
||||
# dir. Use the bin dir itself as the import search path in that case.
|
||||
if any(bin_dir.glob("*.swiftmodule")):
|
||||
return bin_dir
|
||||
raise RuntimeError("could not locate the built Modules dir; run `swift build` first")
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user