Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ec72bd3a4c | |||
| 6da3615707 |
+1
-1
@@ -9,7 +9,7 @@ build/
|
|||||||
*.d
|
*.d
|
||||||
*.swp
|
*.swp
|
||||||
.DS_Store
|
.DS_Store
|
||||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
.swiftpm/
|
||||||
xcuserdata/
|
xcuserdata/
|
||||||
*.xcuserstate
|
*.xcuserstate
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
**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
|
## 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`
|
- Node tree / Group nesting / bus routing → `docs/protocols/node-tree.md`
|
||||||
- Routines / tasks / clock / MIDI / OSC → `docs/tooling/routine-task.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`
|
- `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`
|
- 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 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`
|
- Linux OSC (`OSCClient` / `OSCServer` POSIX-UDP transport off Apple, `OSCServerError`; codec unchanged) → `Sources/Lyrebird/OSC/OSCServer.swift`
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
/* Begin PBXBuildFile section */
|
/* Begin PBXBuildFile section */
|
||||||
0306C7C02FAC451300952EAF /* GVerbTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7BF2FAC451300952EAF /* GVerbTest.swift */; };
|
0306C7C02FAC451300952EAF /* GVerbTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7BF2FAC451300952EAF /* GVerbTest.swift */; };
|
||||||
0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7C12FAC45F200952EAF /* ReverbDemo.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 */; };
|
035A2F422FAA4F67007F6289 /* PercPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F3F2FAA4F67007F6289 /* PercPitchShift.swift */; };
|
||||||
035A2F432FAA4F67007F6289 /* PercSpectralPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F412FAA4F67007F6289 /* PercSpectralPitchShift.swift */; };
|
035A2F432FAA4F67007F6289 /* PercSpectralPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F412FAA4F67007F6289 /* PercSpectralPitchShift.swift */; };
|
||||||
035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F492FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift */; };
|
035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F492FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift */; };
|
||||||
@@ -21,11 +22,13 @@
|
|||||||
C1A000000000000000000013 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C1A000000000000000000012 /* Lyrebird */; };
|
C1A000000000000000000013 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C1A000000000000000000012 /* Lyrebird */; };
|
||||||
C1A000000000000000000016 /* SineTone.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A000000000000000000014 /* SineTone.swift */; };
|
C1A000000000000000000016 /* SineTone.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A000000000000000000014 /* SineTone.swift */; };
|
||||||
C1A000000000000000000017 /* DelaySample.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A000000000000000000015 /* DelaySample.swift */; };
|
C1A000000000000000000017 /* DelaySample.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A000000000000000000015 /* DelaySample.swift */; };
|
||||||
|
C1A00000000000000000001B /* BlipVoice.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A00000000000000000001A /* BlipVoice.swift */; };
|
||||||
/* End PBXBuildFile section */
|
/* End PBXBuildFile section */
|
||||||
|
|
||||||
/* Begin PBXFileReference section */
|
/* Begin PBXFileReference section */
|
||||||
0306C7BF2FAC451300952EAF /* GVerbTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GVerbTest.swift; sourceTree = "<group>"; };
|
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>"; };
|
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>"; };
|
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>"; };
|
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>"; };
|
035A2F402FAA4F67007F6289 /* PercPlayBuffer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercPlayBuffer.swift; sourceTree = "<group>"; };
|
||||||
@@ -38,6 +41,7 @@
|
|||||||
C1A000000000000000000006 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
C1A000000000000000000006 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||||
C1A000000000000000000014 /* SineTone.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineTone.swift; sourceTree = "<group>"; };
|
C1A000000000000000000014 /* SineTone.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineTone.swift; sourceTree = "<group>"; };
|
||||||
C1A000000000000000000015 /* DelaySample.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DelaySample.swift; sourceTree = "<group>"; };
|
C1A000000000000000000015 /* DelaySample.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DelaySample.swift; sourceTree = "<group>"; };
|
||||||
|
C1A00000000000000000001A /* BlipVoice.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BlipVoice.swift; sourceTree = "<group>"; };
|
||||||
/* End PBXFileReference section */
|
/* End PBXFileReference section */
|
||||||
|
|
||||||
/* Begin PBXFrameworksBuildPhase section */
|
/* Begin PBXFrameworksBuildPhase section */
|
||||||
@@ -56,6 +60,7 @@
|
|||||||
isa = PBXGroup;
|
isa = PBXGroup;
|
||||||
children = (
|
children = (
|
||||||
0306C7C12FAC45F200952EAF /* ReverbDemo.swift */,
|
0306C7C12FAC45F200952EAF /* ReverbDemo.swift */,
|
||||||
|
99B83EC83F6C48D98441D7F7 /* EventPatternDemo.swift */,
|
||||||
035B00032FAB0000007F0001 /* DemoProtocol.swift */,
|
035B00032FAB0000007F0001 /* DemoProtocol.swift */,
|
||||||
035B00042FAB0000007F0001 /* BufferDemos.swift */,
|
035B00042FAB0000007F0001 /* BufferDemos.swift */,
|
||||||
);
|
);
|
||||||
@@ -92,6 +97,7 @@
|
|||||||
035B00092FAB0000007F0001 /* General */ = {
|
035B00092FAB0000007F0001 /* General */ = {
|
||||||
isa = PBXGroup;
|
isa = PBXGroup;
|
||||||
children = (
|
children = (
|
||||||
|
C1A00000000000000000001A /* BlipVoice.swift */,
|
||||||
C1A000000000000000000015 /* DelaySample.swift */,
|
C1A000000000000000000015 /* DelaySample.swift */,
|
||||||
C1A000000000000000000014 /* SineTone.swift */,
|
C1A000000000000000000014 /* SineTone.swift */,
|
||||||
);
|
);
|
||||||
@@ -207,11 +213,13 @@
|
|||||||
035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */,
|
035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */,
|
||||||
035A2F442FAA4F67007F6289 /* PercBufferRead.swift in Sources */,
|
035A2F442FAA4F67007F6289 /* PercBufferRead.swift in Sources */,
|
||||||
0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */,
|
0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */,
|
||||||
|
631D4C5B1150427CB8D15210 /* EventPatternDemo.swift in Sources */,
|
||||||
035A2F452FAA4F67007F6289 /* PercPlayBuffer.swift in Sources */,
|
035A2F452FAA4F67007F6289 /* PercPlayBuffer.swift in Sources */,
|
||||||
C1A000000000000000000007 /* main.swift in Sources */,
|
C1A000000000000000000007 /* main.swift in Sources */,
|
||||||
C1A000000000000000000016 /* SineTone.swift in Sources */,
|
C1A000000000000000000016 /* SineTone.swift in Sources */,
|
||||||
035A2F472FAA6950007F6289 /* PercTimeStretch.swift in Sources */,
|
035A2F472FAA6950007F6289 /* PercTimeStretch.swift in Sources */,
|
||||||
C1A000000000000000000017 /* DelaySample.swift in Sources */,
|
C1A000000000000000000017 /* DelaySample.swift in Sources */,
|
||||||
|
C1A00000000000000000001B /* BlipVoice.swift in Sources */,
|
||||||
);
|
);
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
// 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 ``BlipVoice`` 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
|
||||||
|
private let tempoBPM: Double = 132.0
|
||||||
|
|
||||||
|
/// Beats the bass waits before its first note. Shared tempo means both parts share a beat
|
||||||
|
/// grid, so this is a plain offset on that grid.
|
||||||
|
private let leadInBeats: Double = 2.0
|
||||||
|
|
||||||
|
init(engine: SynthesisEngine) {
|
||||||
|
self.engine = engine
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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.
|
||||||
|
private func makeLead() -> EventPattern<BlipVoice> {
|
||||||
|
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 freqs: [Double] = phrase.compactMap(\.frequency)
|
||||||
|
return EventPattern(make: { BlipVoice() })
|
||||||
|
.bind(\.freq, .sequence(freqs, 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bass: one slow phrase at the same tempo, entered `leadInBeats` after the lead and
|
||||||
|
/// outlasting it. No cross-pattern clock — ``ParallelEventPattern`` launches both children
|
||||||
|
/// from the one `play` call, so they share a start instant and (at equal tempo) a beat grid.
|
||||||
|
private func makeBass() -> EventPattern<BlipVoice> {
|
||||||
|
let phrase: [Pitch] = [.named(.a, 2), .named(.a, 2), .named(.g, 2), .named(.e, 2)]
|
||||||
|
let freqs: [Double] = phrase.compactMap(\.frequency)
|
||||||
|
return EventPattern(make: { BlipVoice() })
|
||||||
|
.bind(\.freq, .sequence(freqs, repeats: 1))
|
||||||
|
.bind(\.amp, .uniformRandom(low: 0.2, high: 0.3))
|
||||||
|
.dur(.sequence([1.0]))
|
||||||
|
.legato(0.9)
|
||||||
|
.tempo(tempoBPM)
|
||||||
|
.repeats(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runDemo() {
|
||||||
|
print("\n── EventPattern demo ──")
|
||||||
|
|
||||||
|
// Start both together, staggering the bass `leadInBeats` in, and control them as one handle.
|
||||||
|
let ensemble: ParallelEventPattern = ParallelEventPattern()
|
||||||
|
ensemble.add(makeLead())
|
||||||
|
ensemble.addAfter(beats: leadInBeats, eventPattern: makeBass())
|
||||||
|
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.")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
// BlipVoice.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
|
/// 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.
|
||||||
|
///
|
||||||
|
/// Used by ``EventPatternDemo`` for both the lead and the bass part.
|
||||||
|
final class BlipVoice: SynthesizerBase, EventGated {
|
||||||
|
/// Envelope release length in seconds — how long a note rings after its gate closes.
|
||||||
|
/// Exposed so a caller 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,11 +7,18 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import LyrebirdSynth
|
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,
|
// `makeDefaultAudioDriver()` selects the platform backend — Core Audio on Apple,
|
||||||
// ALSA on Linux (needs libasound) — so the demo builds and runs on both.
|
// ALSA on Linux (needs libasound) — so the demo builds and runs on both.
|
||||||
let engine = SynthesisEngine(
|
let engine = SynthesisEngine(
|
||||||
blockSize: 512,
|
blockSize: 512,
|
||||||
sampleRate: 44100,
|
controlBlockSize: 64,
|
||||||
|
sampleRate: 48000,
|
||||||
numOutputChannels: 2,
|
numOutputChannels: 2,
|
||||||
numInputChannels: 2,
|
numInputChannels: 2,
|
||||||
driver: makeDefaultAudioDriver()
|
driver: makeDefaultAudioDriver()
|
||||||
@@ -24,7 +31,10 @@ do {
|
|||||||
exit(1)
|
exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// BufferDemos(engine: engine).runDemo()
|
switch demo {
|
||||||
ReverbDemo(engine: engine).runDemo()
|
case .buffer: BufferDemos(engine: engine).runDemo()
|
||||||
|
case .reverb: ReverbDemo(engine: engine).runDemo()
|
||||||
|
case .eventPattern: EventPatternDemo(engine: engine).runDemo()
|
||||||
|
}
|
||||||
|
|
||||||
engine.stop()
|
engine.stop()
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import PackageDescription
|
|||||||
// macOS: swift run LyrebirdGUIDemo (or open the thin Xcode project)
|
// macOS: swift run LyrebirdGUIDemo (or open the thin Xcode project)
|
||||||
// Linux: swift run LyrebirdGUIDemo (needs libgtk-4-dev + libasound2-dev)
|
// 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(
|
let package = Package(
|
||||||
name: "LyrebirdGUIDemo",
|
name: "LyrebirdGUIDemo",
|
||||||
platforms: [.macOS(.v15)],
|
platforms: [.macOS(.v15)],
|
||||||
|
|||||||
@@ -27,7 +27,8 @@ so the controls, the oscilloscope, and the CPU meters are identical.
|
|||||||
## Run it
|
## Run it
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
swift run LyrebirdGUIDemo # vector oscillator (default)
|
swift run LyrebirdGUIDemo # event conductor (default)
|
||||||
|
LYREBIRD_DEMO=vector swift run LyrebirdGUIDemo # vector oscillator
|
||||||
LYREBIRD_DEMO=sine swift run LyrebirdGUIDemo # stereo sine tone
|
LYREBIRD_DEMO=sine swift run LyrebirdGUIDemo # stereo sine tone
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -47,12 +48,16 @@ LYREBIRD_DEMO=sine swift run LyrebirdGUIDemo # stereo sine tone
|
|||||||
|
|
||||||
## What each demo shows
|
## What each demo shows
|
||||||
|
|
||||||
|
- **conductor** (default) — `ConductorDemoVoice` driven by an `EventConductor`:
|
||||||
|
start/stop the engine, then toggle a top and a bottom part, each entering on the
|
||||||
|
next beat and repeating while it runs, over a live oscilloscope. Showcases the
|
||||||
|
2.4.0 event system. Nothing plays until you start the engine and a part.
|
||||||
- **vector** — `VectorOscillatorUI`: an XY pad crossfades four corner wavetables
|
- **vector** — `VectorOscillatorUI`: an XY pad crossfades four corner wavetables
|
||||||
(sine / saw-ish / triangle / Hanning); frequency and amplitude knobs; a live
|
(sine / saw-ish / triangle / Hanning); frequency and amplitude knobs; a live
|
||||||
oscilloscope and CPU-load strip.
|
oscilloscope and CPU-load strip.
|
||||||
- **sine** — `SineToneUI`: a frequency slider, amplitude and pan knobs, a level
|
- **sine** — `SineToneUI`: a frequency slider, amplitude and pan knobs, a level
|
||||||
readout, the scope and CPU strip, and a static envelope plot.
|
readout, the scope and CPU strip, and a static envelope plot.
|
||||||
|
|
||||||
Add a synth by dropping a `SynthesizerBase` subclass and a node-based view into
|
Add a synth by dropping a `SynthesizerBase` subclass into
|
||||||
`LyrebirdGUIDemoKit`, then extend `DemoSelection` and the `demoContent()` switch
|
`LyrebirdGUIDemoKit/Synthesizers/` and a node-based view into `LyrebirdGUIDemoKit`,
|
||||||
in `main.swift`.
|
then extend `DemoSelection` and the `demoContent()` switch in `main.swift`.
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
// • Linux — a GTK4 `App`/`WindowGroup` scene run by `GTK4Backend`.
|
// • Linux — a GTK4 `App`/`WindowGroup` scene run by `GTK4Backend`.
|
||||||
//
|
//
|
||||||
// Run either with `swift run LyrebirdGUIDemo`. Pick the synth with
|
// Run either with `swift run LyrebirdGUIDemo`. Pick the synth with
|
||||||
// `LYREBIRD_DEMO=vector` (default) or `LYREBIRD_DEMO=sine`.
|
// `LYREBIRD_DEMO=conductor` (default), `vector`, or `sine`.
|
||||||
//
|
//
|
||||||
// `@ViewBuilder` and the window hosts come from SwiftUI on macOS and from
|
// `@ViewBuilder` and the window hosts come from SwiftUI on macOS and from
|
||||||
// SwiftOpenUI (re-exported through `LyrebirdUI`) on Linux — hence the single
|
// SwiftOpenUI (re-exported through `LyrebirdUI`) on Linux — hence the single
|
||||||
@@ -30,7 +30,7 @@ import LyrebirdGUIDemoKit
|
|||||||
let selection: DemoSelection = DemoSelection.fromEnvironment()
|
let selection: DemoSelection = DemoSelection.fromEnvironment()
|
||||||
|
|
||||||
private let demoBlockSize: Int = 512
|
private let demoBlockSize: Int = 512
|
||||||
private let demoSampleRate: Double = 44_100.0
|
private let demoSampleRate: Double = 48_000.0
|
||||||
private let demoScopeBufferSize: Int = 2048
|
private let demoScopeBufferSize: Int = 2048
|
||||||
|
|
||||||
// Oscilloscope tap on the stereo output buses. Must be set before `start()`.
|
// Oscilloscope tap on the stereo output buses. Must be set before `start()`.
|
||||||
@@ -102,6 +102,8 @@ func demoContent() -> some View {
|
|||||||
scope: demoScope,
|
scope: demoScope,
|
||||||
engine: statusEngine
|
engine: statusEngine
|
||||||
)
|
)
|
||||||
|
} else if selection == .conductor {
|
||||||
|
ConductorDemoView(scope: demoScope, engine: statusEngine)
|
||||||
} else {
|
} else {
|
||||||
SineToneDemoView(
|
SineToneDemoView(
|
||||||
frequencyNode: sineFreq,
|
frequencyNode: sineFreq,
|
||||||
@@ -117,12 +119,15 @@ func demoContent() -> some View {
|
|||||||
// Start the engine and add the selected synth. `engine.start()` / `add` are
|
// 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
|
// @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).
|
// calls. On a build with no live backend the GUI still runs (silently).
|
||||||
|
// The conductor demo is the exception: its view starts and stops the engine itself.
|
||||||
|
if selection != .conductor {
|
||||||
do {
|
do {
|
||||||
try demoEngine.start()
|
try demoEngine.start()
|
||||||
try demoEngine.add(activeSynth)
|
try demoEngine.add(activeSynth)
|
||||||
} catch {
|
} catch {
|
||||||
print("[Lyrebird] demo engine setup failed: \(error)")
|
print("[Lyrebird] demo engine setup failed: \(error)")
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if !isLiveAudioAvailable {
|
if !isLiveAudioAvailable {
|
||||||
print("[Lyrebird] no live audio backend — the controls still work, but there is no sound.")
|
print("[Lyrebird] no live audio backend — the controls still work, but there is no sound.")
|
||||||
|
|||||||
@@ -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()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,16 +11,21 @@ import Foundation
|
|||||||
/// selection so one binary covers every patch.
|
/// selection so one binary covers every patch.
|
||||||
public enum DemoSelection: String, Sendable {
|
public enum DemoSelection: String, Sendable {
|
||||||
|
|
||||||
/// Vector oscillator with an XY blend pad (the default).
|
/// Vector oscillator with an XY blend pad.
|
||||||
case vector
|
case vector
|
||||||
|
|
||||||
/// Stereo sine tone with frequency / amplitude / pan controls.
|
/// Stereo sine tone with frequency / amplitude / pan controls.
|
||||||
case sine
|
case sine
|
||||||
|
|
||||||
/// Resolve the selection from `LYREBIRD_DEMO` (defaults to `.vector`).
|
/// 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.
|
||||||
|
/// This is the default — it showcases the headline event system.
|
||||||
|
case conductor
|
||||||
|
|
||||||
|
/// Resolve the selection from `LYREBIRD_DEMO` (defaults to `.conductor`).
|
||||||
public static func fromEnvironment() -> DemoSelection {
|
public static func fromEnvironment() -> DemoSelection {
|
||||||
let raw: String = ProcessInfo.processInfo.environment["LYREBIRD_DEMO"]?.lowercased() ?? "vector"
|
let raw: String = ProcessInfo.processInfo.environment["LYREBIRD_DEMO"]?.lowercased() ?? "conductor"
|
||||||
return DemoSelection(rawValue: raw) ?? .vector
|
return DemoSelection(rawValue: raw) ?? .conductor
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Title-bar text for the window hosting this demo.
|
/// Title-bar text for the window hosting this demo.
|
||||||
@@ -28,6 +33,7 @@ public enum DemoSelection: String, Sendable {
|
|||||||
switch self {
|
switch self {
|
||||||
case .vector: return "Lyrebird — Vector Oscillator"
|
case .vector: return "Lyrebird — Vector Oscillator"
|
||||||
case .sine: return "Lyrebird — Sine Tone"
|
case .sine: return "Lyrebird — Sine Tone"
|
||||||
|
case .conductor: return "Lyrebird — Event Conductor"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+47
@@ -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))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,7 +12,7 @@ import LyrebirdUI
|
|||||||
// ── Demo selector ─────────────────────────────────────────────────────────────
|
// ── Demo selector ─────────────────────────────────────────────────────────────
|
||||||
// Change `demo` to `.sineTone` or `.binDelay` to switch demos.
|
// Change `demo` to `.sineTone` or `.binDelay` to switch demos.
|
||||||
private enum Demo { case vector, binDelay, sineTone }
|
private enum Demo { case vector, binDelay, sineTone }
|
||||||
private let demo: Demo = .vector
|
private let demo: Demo = .binDelay
|
||||||
// ──────────────────────────────────────────────────────────────────────────────
|
// ──────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import LyrebirdSynth
|
|||||||
|
|
||||||
let engine = SynthesisEngine(
|
let engine = SynthesisEngine(
|
||||||
blockSize: 512,
|
blockSize: 512,
|
||||||
sampleRate: 44100,
|
sampleRate: 48_000,
|
||||||
numOutputChannels: 2,
|
numOutputChannels: 2,
|
||||||
numInputChannels: 0,
|
numInputChannels: 0,
|
||||||
driver: CoreAudioDriver()
|
driver: CoreAudioDriver()
|
||||||
|
|||||||
@@ -196,7 +196,7 @@
|
|||||||
CODE_SIGN_IDENTITY = "Apple Development";
|
CODE_SIGN_IDENTITY = "Apple Development";
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
COMBINE_HIDPI_IMAGES = YES;
|
COMBINE_HIDPI_IMAGES = YES;
|
||||||
CURRENT_PROJECT_VERSION = 2;
|
CURRENT_PROJECT_VERSION = 3;
|
||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||||
ENABLE_HARDENED_RUNTIME = YES;
|
ENABLE_HARDENED_RUNTIME = YES;
|
||||||
@@ -208,12 +208,13 @@
|
|||||||
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||||
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||||
|
INFOPLIST_KEY_CFBundleDisplayName = "Lyrebird Scratch";
|
||||||
LD_RUNPATH_SEARCH_PATHS = (
|
LD_RUNPATH_SEARCH_PATHS = (
|
||||||
"$(inherited)",
|
"$(inherited)",
|
||||||
"@executable_path/../Frameworks",
|
"@executable_path/../Frameworks",
|
||||||
);
|
);
|
||||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||||
MARKETING_VERSION = 1.6.2;
|
MARKETING_VERSION = 2.4.1;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||||
@@ -238,7 +239,7 @@
|
|||||||
CODE_SIGN_IDENTITY = "Apple Development";
|
CODE_SIGN_IDENTITY = "Apple Development";
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
COMBINE_HIDPI_IMAGES = YES;
|
COMBINE_HIDPI_IMAGES = YES;
|
||||||
CURRENT_PROJECT_VERSION = 2;
|
CURRENT_PROJECT_VERSION = 3;
|
||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
ENABLE_HARDENED_RUNTIME = YES;
|
ENABLE_HARDENED_RUNTIME = YES;
|
||||||
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
||||||
@@ -249,12 +250,13 @@
|
|||||||
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||||
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||||
|
INFOPLIST_KEY_CFBundleDisplayName = "Lyrebird Scratch";
|
||||||
LD_RUNPATH_SEARCH_PATHS = (
|
LD_RUNPATH_SEARCH_PATHS = (
|
||||||
"$(inherited)",
|
"$(inherited)",
|
||||||
"@executable_path/../Frameworks",
|
"@executable_path/../Frameworks",
|
||||||
);
|
);
|
||||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||||
MARKETING_VERSION = 1.6.2;
|
MARKETING_VERSION = 2.4.1;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
<key>CFBundlePackageType</key>
|
<key>CFBundlePackageType</key>
|
||||||
<string>APPL</string>
|
<string>APPL</string>
|
||||||
<key>CFBundleShortVersionString</key>
|
<key>CFBundleShortVersionString</key>
|
||||||
<string>1.6.3</string>
|
<string>2.4.1</string>
|
||||||
<key>CFBundleVersion</key>
|
<key>CFBundleVersion</key>
|
||||||
<string>3</string>
|
<string>3</string>
|
||||||
<key>LSMinimumSystemVersion</key>
|
<key>LSMinimumSystemVersion</key>
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"originHash" : "00d9a3997266cf2e38ebfa0f16e7978ca242180f4745b918a490a4758ba8e753",
|
||||||
|
"pins" : [
|
||||||
|
{
|
||||||
|
"identity" : "linenoise-swift",
|
||||||
|
"kind" : "remoteSourceControl",
|
||||||
|
"location" : "https://github.com/andybest/linenoise-swift",
|
||||||
|
"state" : {
|
||||||
|
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
|
||||||
|
"version" : "0.0.3"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"identity" : "nimble",
|
||||||
|
"kind" : "remoteSourceControl",
|
||||||
|
"location" : "https://github.com/Quick/Nimble.git",
|
||||||
|
"state" : {
|
||||||
|
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
|
||||||
|
"version" : "7.3.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"version" : 3
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
// Package.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// swift-tools-version: 6.0
|
||||||
|
import PackageDescription
|
||||||
|
|
||||||
|
// The live-coding scratchpad as a SwiftPM package, so the umbrella
|
||||||
|
// `Lyrebird.xcworkspace` shows it the same way as `LyrebirdGUIDemo` — a package,
|
||||||
|
// not a nested `.xcodeproj`. A sibling `LyrebirdScratch.xcodeproj` is kept on
|
||||||
|
// disk for distribution builds (custom app icon, entitlements, the module-
|
||||||
|
// staging run-script that makes an *exported* `.app` self-contained); the
|
||||||
|
// package form is the dev-run / in-workspace view.
|
||||||
|
//
|
||||||
|
// macOS only. The Linux scratchpad host is `LyrebirdScratchLinuxDemo` in the
|
||||||
|
// `LiveCompile/` sub-package (GTK4 / SwiftOpenUI); this executable is the AppKit
|
||||||
|
// (NSTextView + menu) counterpart.
|
||||||
|
//
|
||||||
|
// Dynamic products on purpose: the live-compile stack dlopens freshly compiled
|
||||||
|
// snippet dylibs that `import LyrebirdSynth` / `LyrebirdLiveCompile`. Linking the
|
||||||
|
// single shared `libLyrebirdDynamic` + `libLyrebirdLiveCompileUIDynamic` (rather
|
||||||
|
// than static-folding a second copy of LyrebirdSynth's ObjC classes into this
|
||||||
|
// executable) is what avoids duplicate class registration at dlopen time — the
|
||||||
|
// same reason the `LiveCompile` sub-package exists.
|
||||||
|
//
|
||||||
|
// Run: `swift build` first (so the …Dynamic dylibs exist in the build dir for
|
||||||
|
// the snippet link), then `swift run LyrebirdScratch`. As a bare SwiftPM
|
||||||
|
// executable there is no Hardened Runtime or App Sandbox, so the swiftc
|
||||||
|
// shell-out and the unsigned-snippet dlopen both work without entitlements (the
|
||||||
|
// `.xcodeproj` needs `disable-library-validation` only because an Xcode app
|
||||||
|
// target enables Hardened Runtime by default).
|
||||||
|
let package = Package(
|
||||||
|
name: "LyrebirdScratch",
|
||||||
|
platforms: [.macOS(.v15)],
|
||||||
|
dependencies: [
|
||||||
|
.package(name: "Lyrebird", path: "../.."),
|
||||||
|
.package(name: "LyrebirdLiveCompile", path: "../../LiveCompile"),
|
||||||
|
],
|
||||||
|
targets: [
|
||||||
|
.executableTarget(
|
||||||
|
name: "LyrebirdScratch",
|
||||||
|
dependencies: [
|
||||||
|
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
|
||||||
|
.product(name: "LyrebirdLiveCompileUIDynamic", package: "LyrebirdLiveCompile"),
|
||||||
|
],
|
||||||
|
path: "LyrebirdScratch",
|
||||||
|
exclude: [
|
||||||
|
"Info.plist",
|
||||||
|
"LyrebirdScratch.entitlements",
|
||||||
|
"Assets.xcassets",
|
||||||
|
]
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
+1
-1
@@ -214,7 +214,7 @@ Scratchpad features:
|
|||||||
- **Run (fresh)** — clears the previous snippet's synths and runs the buffer.
|
- **Run (fresh)** — clears the previous snippet's synths and runs the buffer.
|
||||||
- **Run (additive)** — layers the new snippet on top of what's already playing.
|
- **Run (additive)** — layers the new snippet on top of what's already playing.
|
||||||
- **Line evaluation** — select one or more lines and Run evaluates just those.
|
- **Line evaluation** — select one or more lines and Run evaluates just those.
|
||||||
- **Stop audio** — a panic button that clears all snippet audio without tearing
|
- **Kill audio** — a panic button that clears all snippet audio without tearing
|
||||||
down the engine.
|
down the engine.
|
||||||
- **Live oscilloscope** — shows the session's stereo output in real time.
|
- **Live oscilloscope** — shows the session's stereo output in real time.
|
||||||
- **Save / load** — a File menu (`New`, `Open…`, `Save`, `Save As…`) with
|
- **Save / load** — a File menu (`New`, `Open…`, `Save`, `Save As…`) with
|
||||||
|
|||||||
+22
-6
@@ -1,18 +1,18 @@
|
|||||||
# Lyrebird — Start Here
|
# Lyrebird — Start Here
|
||||||
|
|
||||||
Eight demo projects live in this workspace. This guide covers how to open them, what each one does, where to add your own synthesizers, and the gotchas that will bite you if you don't know about them.
|
Nine demo projects live in this workspace. This guide covers how to open them, what each one does, where to add your own synthesizers, and the gotchas that will bite you if you don't know about them.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Opening the Workspace
|
## Opening the Workspace
|
||||||
|
|
||||||
Open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj` file. The workspace links all eight demo projects together so they share the local Lyrebird package.
|
Open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj` file. The workspace links all nine demo projects together so they share the local Lyrebird package.
|
||||||
|
|
||||||
Once open, pick a scheme from the scheme picker at the top of the Xcode window and hit Run.
|
Once open, pick a scheme from the scheme picker at the top of the Xcode window and hit Run.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## The Eight Demos
|
## The Nine Demos
|
||||||
|
|
||||||
### LyrebirdQuickstartDemo — Fastest Sound
|
### LyrebirdQuickstartDemo — Fastest Sound
|
||||||
|
|
||||||
@@ -61,6 +61,17 @@ final class MySynth: SynthesizerBase {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### LyrebirdGUIDemo — Cross-Platform GUI (macOS + Linux)
|
||||||
|
|
||||||
|
One SwiftPM package whose SwiftUI-style UI builds on **both** macOS (AppKit) and Linux (GTK4 via SwiftOpenUI) from shared source — the same selection drives either front end. Three patches ship, chosen by `LYREBIRD_DEMO`.
|
||||||
|
|
||||||
|
- **Where the synths live:** `Demos/LyrebirdGUIDemo/Sources/LyrebirdGUIDemoKit/Synthesizers/` — `ConductorDemoVoice`, `VectorOscillatorUI`, `SineToneUI`. The views, `DemoSelection`, and the demo controllers sit alongside in `LyrebirdGUIDemoKit/`.
|
||||||
|
- **Patches:** `conductor` (default) — a live `EventConductor` ensemble with engine start/stop and top/bottom part toggles; `vector` — an XY blend pad over four wavetables; `sine` — a frequency/amp/pan tone. Nothing plays until you start it.
|
||||||
|
- **Run it:** `cd Demos/LyrebirdGUIDemo && swift run LyrebirdGUIDemo` (add `LYREBIRD_DEMO=vector` or `=sine` to pick another patch). On Linux needs `libgtk-4-dev` plus `libasound2-dev` + a sound device for audio.
|
||||||
|
- **It's a package, not an `.xcodeproj`:** open the folder (or `Package.swift`) in Xcode, pick the `LyrebirdGUIDemo` scheme, and Run.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
### LyrebirdiOSDemo — iOS App
|
### LyrebirdiOSDemo — iOS App
|
||||||
|
|
||||||
A SwiftUI app using `iOSAudioDriver` (RemoteIO). Same `@UIParam` knob system as the macOS demo.
|
A SwiftUI app using `iOSAudioDriver` (RemoteIO). Same `@UIParam` knob system as the macOS demo.
|
||||||
@@ -143,7 +154,11 @@ A container app + `.appex` extension target shipping **Realized Sound: LyrebirdF
|
|||||||
|
|
||||||
### LyrebirdScratch — Live-Coding Scratchpad
|
### LyrebirdScratch — Live-Coding Scratchpad
|
||||||
|
|
||||||
A macOS app that compiles a typed Swift snippet against the live engine at ⌘↩. Backed by `LyrebirdScratchView` and `LiveSession` from the `LyrebirdLiveCompile` SPM target.
|
A macOS app that compiles a typed Swift snippet against the live engine at ⌘↩. Backed by `LyrebirdScratchView` and `LiveSession` from the `LyrebirdLiveCompile` SPM target. (Linux has its own GTK4 host — `swift run LyrebirdScratchLinuxDemo` in `LiveCompile/`; see `LINUX_README.md`.)
|
||||||
|
|
||||||
|
Build it either way, like `LyrebirdGUIDemo`:
|
||||||
|
- **Package** — `Demos/LyrebirdScratch/Package.swift` builds the AppKit host as a plain executable. From that folder: `swift build` then `swift run LyrebirdScratch` (the `swift build` first makes the `…Dynamic` dylibs the snippet link needs). This is how it appears in `Lyrebird.xcworkspace`.
|
||||||
|
- **Xcode project** — the sibling `LyrebirdScratch.xcodeproj` is kept for distribution builds (custom app icon, entitlements, and a run-script that bundles the Lyrebird module artifacts into an exported `.app`).
|
||||||
|
|
||||||
**v1 surface:**
|
**v1 surface:**
|
||||||
- Type arbitrary Swift code in the editor pane. The snippet body has `context: SnippetContext` in scope.
|
- Type arbitrary Swift code in the editor pane. The snippet body has `context: SnippetContext` in scope.
|
||||||
@@ -154,10 +169,11 @@ A macOS app that compiles a typed Swift snippet against the live engine at ⌘
|
|||||||
- `context.reportMessage(_:)` — writes a string back to the host status bar.
|
- `context.reportMessage(_:)` — writes a string back to the host status bar.
|
||||||
- **⌘↩** — compile and replace. Removes the previous run's anonymous synths (named slots persist), compiles the snippet via `swiftc -emit-library`, `dlopen`s the resulting dylib, calls `lyrebird_snippet_entry`.
|
- **⌘↩** — compile and replace. Removes the previous run's anonymous synths (named slots persist), compiles the snippet via `swiftc -emit-library`, `dlopen`s the resulting dylib, calls `lyrebird_snippet_entry`.
|
||||||
- **⌘⇧↩** — compile additive. Prior synths stay in the engine.
|
- **⌘⇧↩** — compile additive. Prior synths stay in the engine.
|
||||||
- **Clear Synths** toolbar button — full reset: removes all tracked synths *and* every named slot immediately.
|
- **Kill All Sound** (⌘K, menu) — panic stop / full reset: removes all tracked synths *and* every named slot immediately.
|
||||||
|
- **⌃Space** (Show Completions) / Esc / F5 — manual code completion at the caret (Swift mode).
|
||||||
|
|
||||||
**Why this app cannot be sandboxed:**
|
**Why this app cannot be sandboxed:**
|
||||||
`swiftc` is a subprocess (`posix_spawn`); the output dylib is unsigned. Both are blocked by the macOS App Sandbox. This app is a direct-distribution developer tool only. The entitlements file (`LyrebirdScratch.entitlements`) sets `com.apple.security.cs.disable-library-validation = true` to let Hardened Runtime `dlopen` the unsigned snippet dylib.
|
`swiftc` is a subprocess (`posix_spawn`); the output dylib is unsigned. Both are blocked by the macOS App Sandbox. This app is a direct-distribution developer tool only. In the `.xcodeproj` build the entitlements file (`LyrebirdScratch.entitlements`) sets `com.apple.security.cs.disable-library-validation = true` to let Hardened Runtime `dlopen` the unsigned snippet dylib. The package (`swift run`) build is a bare executable with neither the App Sandbox nor Hardened Runtime, so it needs no entitlement — the shell-out and `dlopen` just work.
|
||||||
|
|
||||||
**Dylib lifetime:** loaded dylibs are never unloaded. `Synthesizer` instances reference types from the dylib; unloading while they are active would crash. Every ⌘↩ evaluation writes a new uniquely-named dylib to a per-session temp dir. This is intentional v1 behaviour; a future release may revisit with an XPC worker approach.
|
**Dylib lifetime:** loaded dylibs are never unloaded. `Synthesizer` instances reference types from the dylib; unloading while they are active would crash. Every ⌘↩ evaluation writes a new uniquely-named dylib to a per-session temp dir. This is intentional v1 behaviour; a future release may revisit with an XPC worker approach.
|
||||||
|
|
||||||
|
|||||||
@@ -182,7 +182,78 @@ public actor SnippetCompletionService {
|
|||||||
// User line 0 sits at wrapped line `userBodyLineOffset - 1` (0-based);
|
// User line 0 sits at wrapped line `userBodyLineOffset - 1` (0-based);
|
||||||
// the column is unchanged (the preamble adds only whole lines).
|
// the column is unchanged (the preamble adds only whole lines).
|
||||||
let wrappedLine: Int = line + (_userBodyLineOffset - 1)
|
let wrappedLine: Int = line + (_userBodyLineOffset - 1)
|
||||||
return try await _client.completion(uri: _fileURI, line: wrappedLine, character: character)
|
let items: [LSPCompletionItem] = try await _client.completion(
|
||||||
|
uri: _fileURI, line: wrappedLine, character: character)
|
||||||
|
// sourcekit-lsp returns a bare-identifier completion as the *whole*
|
||||||
|
// visible-symbol universe (hundreds of SDK/stdlib globals), unsorted and
|
||||||
|
// unfiltered — LSP expects the client to narrow it by the typed prefix.
|
||||||
|
// Member completion (after `.`) is already server-scoped, so its prefix
|
||||||
|
// is empty and this leaves it untouched. Without this, typing `OscS` and
|
||||||
|
// asking for completion floods the window with Darwin/IOKit globals and
|
||||||
|
// buries (or truncates away) the real `Osc*` types.
|
||||||
|
let prefix: String = SnippetCompletionService.partialWord(
|
||||||
|
in: userBody, line: line, character: character)
|
||||||
|
return SnippetCompletionService.filterAndRank(items, prefix: prefix)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The identifier fragment immediately before the caret — letters, digits and
|
||||||
|
/// underscores — on the user-body `line` up to `character` (zero-based,
|
||||||
|
/// UTF-16). Empty when the character before the caret is not an identifier
|
||||||
|
/// character (e.g. a `.` member completion, or start of line).
|
||||||
|
static func partialWord(in userBody: String, line: Int, character: Int) -> String {
|
||||||
|
let lines: [Substring] = userBody.split(separator: "\n", omittingEmptySubsequences: false)
|
||||||
|
guard line >= 0, line < lines.count else { return "" }
|
||||||
|
let units: [UInt16] = Array(lines[line].utf16)
|
||||||
|
let end: Int = min(character, units.count)
|
||||||
|
var start: Int = end
|
||||||
|
while start > 0, isIdentifierUTF16(units[start - 1]) {
|
||||||
|
start -= 1
|
||||||
|
}
|
||||||
|
guard start < end else { return "" }
|
||||||
|
return String(decoding: units[start..<end], as: UTF16.self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// ASCII letter / digit / underscore — the same identifier class the editor's
|
||||||
|
/// `rangeForUserCompletion` uses to pick the word the completion replaces.
|
||||||
|
private static func isIdentifierUTF16(_ u: UInt16) -> Bool {
|
||||||
|
let underscore: UInt16 = 95
|
||||||
|
let zero: UInt16 = 48, nine: UInt16 = 57
|
||||||
|
let upperA: UInt16 = 65, upperZ: UInt16 = 90
|
||||||
|
let lowerA: UInt16 = 97, lowerZ: UInt16 = 122
|
||||||
|
return u == underscore
|
||||||
|
|| (u >= zero && u <= nine)
|
||||||
|
|| (u >= upperA && u <= upperZ)
|
||||||
|
|| (u >= lowerA && u <= lowerZ)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Narrow `items` to those matching `prefix` (case-insensitive, by `label`)
|
||||||
|
/// and order best-first. An empty `prefix` keeps every item (member
|
||||||
|
/// completion is already scoped by the server) and only sorts it. With a
|
||||||
|
/// prefix, exact case-insensitive prefix matches come first, then anything
|
||||||
|
/// that merely contains the fragment (so a mistyped case or an internal match
|
||||||
|
/// still surfaces), each group ordered by the server's `sortText` then label.
|
||||||
|
static func filterAndRank(_ items: [LSPCompletionItem], prefix: String) -> [LSPCompletionItem] {
|
||||||
|
func ordered(_ group: [LSPCompletionItem]) -> [LSPCompletionItem] {
|
||||||
|
group.sorted { a, b in
|
||||||
|
let ka: String = a.sortText ?? a.label
|
||||||
|
let kb: String = b.sortText ?? b.label
|
||||||
|
if ka != kb { return ka < kb }
|
||||||
|
return a.label < b.label
|
||||||
|
}
|
||||||
|
}
|
||||||
|
guard !prefix.isEmpty else { return ordered(items) }
|
||||||
|
let needle: String = prefix.lowercased()
|
||||||
|
var prefixed: [LSPCompletionItem] = []
|
||||||
|
var contained: [LSPCompletionItem] = []
|
||||||
|
for item: LSPCompletionItem in items {
|
||||||
|
let hay: String = item.label.lowercased()
|
||||||
|
if hay.hasPrefix(needle) {
|
||||||
|
prefixed.append(item)
|
||||||
|
} else if hay.contains(needle) {
|
||||||
|
contained.append(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ordered(prefixed) + ordered(contained)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Shut down the server and remove the workspace. Safe to call more than once.
|
/// Shut down the server and remove the workspace. Safe to call more than once.
|
||||||
|
|||||||
@@ -302,7 +302,7 @@ public struct LyrebirdScratchLinuxView: View {
|
|||||||
Button {
|
Button {
|
||||||
model.killAudio()
|
model.killAudio()
|
||||||
} label: {
|
} label: {
|
||||||
Text("Stop audio")
|
Text("Kill audio")
|
||||||
}
|
}
|
||||||
Button {
|
Button {
|
||||||
model.clear()
|
model.clear()
|
||||||
|
|||||||
@@ -54,13 +54,14 @@ window.open {
|
|||||||
| ⌘↩ | Compile + run the **whole buffer**. Removes the previous run's *anonymous* synths first (named slots persist). |
|
| ⌘↩ | Compile + run the **whole buffer**. Removes the previous run's *anonymous* synths first (named slots persist). |
|
||||||
| ⌘⇧↩ | Compile + run the whole buffer additively. Keeps previously played synths in the engine. |
|
| ⌘⇧↩ | Compile + run the whole buffer additively. Keeps previously played synths in the engine. |
|
||||||
| ⌘E | Compile + run just the **selection**, always additively — adds it to whatever is already playing. No-op with no selection. Works in both Swift and Graph DSL modes. |
|
| ⌘E | Compile + run just the **selection**, always additively — adds it to whatever is already playing. No-op with no selection. Works in both Swift and Graph DSL modes. |
|
||||||
| Esc / F5 | Invoke code completion at the caret (Swift mode). Manual only — never auto-triggered on `.`. See the Code completion section below. |
|
| Esc / F5 / ⌃Space | Invoke code completion at the caret (Swift mode). Manual only — never auto-triggered on `.`. ⌃Space is the **Show Completions** menu item; Esc and F5 map to the same handler. See the Code completion section below. |
|
||||||
| ⌥⌘F | **Format Code** — pretty-print the buffer with the toolchain's `swift-format`. No-op on a blank buffer; a parse error is logged to the console and leaves the text untouched. |
|
| ⌥⌘F | **Format Code** — pretty-print the buffer with the toolchain's `swift-format`. No-op on a blank buffer; a parse error is logged to the console and leaves the text untouched. |
|
||||||
| ⌥⌘R | **Render to File…** — bounce the selection (or the whole buffer) to an audio file offline instead of playing it live. The save dialog carries a **Format** popup (WAV 32-bit float / 16-bit / 24-bit, AIFF, CAF, RF64 WAV for files past 4 GB, or compressed AAC / Apple Lossless `.m4a`) and a **Duration** field; it remembers the last format. Renders faster-than-real-time via `NRTDriver` at the live engine's sample rate and channel count, then reveals the file in Finder. Only **sample-clock** timing renders — see *NRT: sample-clock timing only* under Functional snippets & scheduling. |
|
| ⌥⌘R | **Render to File…** — bounce the selection (or the whole buffer) to an audio file offline instead of playing it live. The save dialog carries a **Format** popup (WAV 32-bit float / 16-bit / 24-bit, AIFF, CAF, RF64 WAV for files past 4 GB, or compressed AAC / Apple Lossless `.m4a`) and a **Duration** field; it remembers the last format. Renders faster-than-real-time via `NRTDriver` at the live engine's sample rate and channel count, then reveals the file in Finder. Only **sample-clock** timing renders — see *NRT: sample-clock timing only* under Functional snippets & scheduling. |
|
||||||
|
| ⌘K | **Kill All Sound** — panic stop. Calls ``LyrebirdScratchModel/clearTracked()``: removes the anonymous tracked synths *and* every named slot, and silences the engine. |
|
||||||
|
|
||||||
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
|
The toolbar exposes the run actions as buttons; **Kill All Sound** (⌘K) lives in
|
||||||
``LyrebirdScratchModel/clearTracked()`` — a full reset that removes both the
|
the menu and calls ``LyrebirdScratchModel/clearTracked()`` — a full reset that
|
||||||
anonymous tracked synths and every named slot.
|
removes both the anonymous tracked synths and every named slot.
|
||||||
|
|
||||||
**Run Selection (⌘E)** evaluates only the highlighted text and *adds* it to the
|
**Run Selection (⌘E)** evaluates only the highlighted text and *adds* it to the
|
||||||
running graph, without touching the rest of the buffer or the whole-buffer
|
running graph, without touching the rest of the buffer or the whole-buffer
|
||||||
@@ -459,7 +460,7 @@ macOS view; the difference is the editor and its chrome:
|
|||||||
- **Run** — a *Run (fresh)* button clears the previous snippet's synths; *Run
|
- **Run** — a *Run (fresh)* button clears the previous snippet's synths; *Run
|
||||||
(additive)* layers on top. Selecting one or more lines evaluates just those
|
(additive)* layers on top. Selecting one or more lines evaluates just those
|
||||||
(the selection is mirrored out of the editor).
|
(the selection is mirrored out of the editor).
|
||||||
- **Stop audio** — a panic button calling ``LiveSession/resetAll()``.
|
- **Kill audio** — a panic button calling ``LiveSession/resetAll()``.
|
||||||
- **Live scope** — a `LyrebirdScopeView` of the session's output.
|
- **Live scope** — a `LyrebirdScopeView` of the session's output.
|
||||||
- **Save / load** — a native File menu (`New`, `Open…`, `Save`, `Save As…`) with
|
- **Save / load** — a native File menu (`New`, `Open…`, `Save`, `Save As…`) with
|
||||||
`Ctrl+N` / `Ctrl+O` / `Ctrl+S` / `Ctrl+Shift+S` accelerators, backed by
|
`Ctrl+N` / `Ctrl+O` / `Ctrl+S` / `Ctrl+Shift+S` accelerators, backed by
|
||||||
|
|||||||
@@ -141,6 +141,17 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
|||||||
find.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
|
find.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
|
||||||
menu.addItem(find)
|
menu.addItem(find)
|
||||||
menu.addItem(NSMenuItem.separator())
|
menu.addItem(NSMenuItem.separator())
|
||||||
|
// Manual code-completion (Swift mode). No target: routed down the
|
||||||
|
// responder chain to the focused `ScratchTextView`, which funnels it to
|
||||||
|
// the same async LSP fetch as Esc / F5. ⌃Space mirrors the Linux editor;
|
||||||
|
// if the system has claimed ⌃Space (input-source switching), Esc / F5
|
||||||
|
// still work.
|
||||||
|
let complete: NSMenuItem = NSMenuItem(title: "Show Completions",
|
||||||
|
action: #selector(ScratchTextView.scratchShowCompletions(_:)),
|
||||||
|
keyEquivalent: " ")
|
||||||
|
complete.keyEquivalentModifierMask = [.control]
|
||||||
|
menu.addItem(complete)
|
||||||
|
menu.addItem(NSMenuItem.separator())
|
||||||
let format: NSMenuItem = target(NSMenuItem(title: "Format Code",
|
let format: NSMenuItem = target(NSMenuItem(title: "Format Code",
|
||||||
action: #selector(formatCode(_:)),
|
action: #selector(formatCode(_:)),
|
||||||
keyEquivalent: "f"))
|
keyEquivalent: "f"))
|
||||||
@@ -173,7 +184,7 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
|||||||
render.keyEquivalentModifierMask = [.command, .option]
|
render.keyEquivalentModifierMask = [.command, .option]
|
||||||
menu.addItem(render)
|
menu.addItem(render)
|
||||||
menu.addItem(NSMenuItem.separator())
|
menu.addItem(NSMenuItem.separator())
|
||||||
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
|
menu.addItem(target(NSMenuItem(title: "Kill All Sound",
|
||||||
action: #selector(clearSynths(_:)),
|
action: #selector(clearSynths(_:)),
|
||||||
keyEquivalent: "k")))
|
keyEquivalent: "k")))
|
||||||
menu.addItem(NSMenuItem.separator())
|
menu.addItem(NSMenuItem.separator())
|
||||||
|
|||||||
@@ -40,6 +40,8 @@ public final class LyrebirdScratchModel: ObservableObject {
|
|||||||
public nonisolated static let defaultPlaceholder: String = """
|
public nonisolated static let defaultPlaceholder: String = """
|
||||||
// ⌘↩ — compile + run (removes synths from the previous run first).
|
// ⌘↩ — compile + run (removes synths from the previous run first).
|
||||||
// ⌘⇧↩ — additive run (keep previously played synths around).
|
// ⌘⇧↩ — additive run (keep previously played synths around).
|
||||||
|
// ⌘K — kill all sound (stop everything now; the engine stays running).
|
||||||
|
// ⌃Space (or Esc / F5) — code completion (Swift mode).
|
||||||
//
|
//
|
||||||
// The snippet body has `context: SnippetContext` in scope.
|
// The snippet body has `context: SnippetContext` in scope.
|
||||||
// `context.play { <graph> }` → play a bare generator graph, no subclass needed.
|
// `context.play { <graph> }` → play a bare generator graph, no subclass needed.
|
||||||
@@ -212,9 +214,20 @@ public final class LyrebirdScratchModel: ObservableObject {
|
|||||||
|
|
||||||
/// Which evaluator ``run(additive:)`` sends the buffer through. `.swift`
|
/// Which evaluator ``run(additive:)`` sends the buffer through. `.swift`
|
||||||
/// compiles a snippet dylib; `.graphDSL` interprets a generator graph
|
/// compiles a snippet dylib; `.graphDSL` interprets a generator graph
|
||||||
/// instantly. Toggle via ``switchMode(to:)`` so the seed placeholder swaps
|
/// instantly. See ``ScratchEvalMode``.
|
||||||
/// with the mode. See ``ScratchEvalMode``.
|
///
|
||||||
@Published public private(set) var evalMode: ScratchEvalMode = .swift
|
/// Publicly settable so a SwiftUI `Picker` can two-way-bind it directly —
|
||||||
|
/// a single synchronous `@Published` write with no deferred `Task`, which
|
||||||
|
/// is what keeps the segmented control and this value from desyncing. The
|
||||||
|
/// mode's *side-effects* (placeholder swap, baseline/diagnostic reset) are
|
||||||
|
/// not run by the setter: a UI host applies them from
|
||||||
|
/// `.onChange(of:)` via ``applyModeSwitchSideEffects(from:to:)`` (so the
|
||||||
|
/// multi-property mutation runs outside the view-update pass), and
|
||||||
|
/// programmatic callers use ``switchMode(to:)``, which does both. (A
|
||||||
|
/// programmatic `switchMode` under a mounted view therefore applies the
|
||||||
|
/// side-effects once directly and once more via `onChange` — an idempotent
|
||||||
|
/// repeat; see ``applyModeSwitchSideEffects(from:to:)``.)
|
||||||
|
@Published public var evalMode: ScratchEvalMode = .swift
|
||||||
|
|
||||||
public let session: LiveSession
|
public let session: LiveSession
|
||||||
|
|
||||||
@@ -495,12 +508,33 @@ public final class LyrebirdScratchModel: ObservableObject {
|
|||||||
/// markers against a buffer the current mode never evaluated.
|
/// markers against a buffer the current mode never evaluated.
|
||||||
public func switchMode(to mode: ScratchEvalMode) {
|
public func switchMode(to mode: ScratchEvalMode) {
|
||||||
guard mode != evalMode else { return }
|
guard mode != evalMode else { return }
|
||||||
if text == LyrebirdScratchModel.defaultPlaceholder(for: evalMode) {
|
let previous: ScratchEvalMode = evalMode
|
||||||
|
evalMode = mode
|
||||||
|
applyModeSwitchSideEffects(from: previous, to: mode)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply the consequences of a mode change — swap the seed placeholder (only
|
||||||
|
/// when the buffer still holds the previous mode's untouched placeholder),
|
||||||
|
/// drop the last-run baseline, and clear diagnostics from a prior run in the
|
||||||
|
/// old mode.
|
||||||
|
///
|
||||||
|
/// Split out of ``switchMode(to:)`` so a SwiftUI host can bind ``evalMode``
|
||||||
|
/// directly and run these from `.onChange(of:)` — outside the view-update
|
||||||
|
/// pass, which is where mutating several `@Published` properties at once is
|
||||||
|
/// allowed. The UI's normal path is a plain `evalMode` write reacted to in
|
||||||
|
/// `onChange`; `switchMode(to:)` is the programmatic path and applies the
|
||||||
|
/// side-effects itself. When a programmatic `switchMode(to:)` happens while a
|
||||||
|
/// view is mounted, `onChange` then fires this a *second* time — a harmless
|
||||||
|
/// repeat: the placeholder swap is a no-op (the buffer no longer equals the
|
||||||
|
/// previous placeholder after the first pass) and the baseline/diagnostic
|
||||||
|
/// resets are idempotent. No-op when `previous == to`.
|
||||||
|
public func applyModeSwitchSideEffects(from previous: ScratchEvalMode, to mode: ScratchEvalMode) {
|
||||||
|
guard previous != mode else { return }
|
||||||
|
if text == LyrebirdScratchModel.defaultPlaceholder(for: previous) {
|
||||||
text = LyrebirdScratchModel.defaultPlaceholder(for: mode)
|
text = LyrebirdScratchModel.defaultPlaceholder(for: mode)
|
||||||
}
|
}
|
||||||
lastEvaluatedText = nil
|
lastEvaluatedText = nil
|
||||||
diagnostics = []
|
diagnostics = []
|
||||||
evalMode = mode
|
|
||||||
reevalState = derivedIdleState()
|
reevalState = derivedIdleState()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -671,7 +705,7 @@ public final class LyrebirdScratchModel: ObservableObject {
|
|||||||
// (unsafe), so the mapped-snippet count is unchanged — refresh the mirror
|
// (unsafe), so the mapped-snippet count is unchanged — refresh the mirror
|
||||||
// so the UI stays truthful about it.
|
// so the UI stays truthful about it.
|
||||||
loadedSnippetCount = session.loadedSnippetCount
|
loadedSnippetCount = session.loadedSnippetCount
|
||||||
statusMessage = "Cleared all synths (tracked + slots)."
|
statusMessage = "Killed all sound (tracked synths + named slots cleared)."
|
||||||
lastEvaluatedText = nil
|
lastEvaluatedText = nil
|
||||||
reevalState = derivedIdleState()
|
reevalState = derivedIdleState()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -130,6 +130,12 @@ public struct LyrebirdScratchView: View {
|
|||||||
// Settle a `.queued` readiness badge once its swap has fired.
|
// Settle a `.queued` readiness badge once its swap has fired.
|
||||||
model.refreshQueuedState()
|
model.refreshQueuedState()
|
||||||
}
|
}
|
||||||
|
// The mode Picker binds `evalMode` directly (synchronous, desync-free);
|
||||||
|
// its side-effects run here, outside the view-update pass, so mutating
|
||||||
|
// several @Published properties at once is allowed.
|
||||||
|
.onChange(of: model.evalMode) { previous, mode in
|
||||||
|
model.applyModeSwitchSideEffects(from: previous, to: mode)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The editor column: engine controls, editor, status, engine panel.
|
/// The editor column: engine controls, editor, status, engine panel.
|
||||||
@@ -393,14 +399,14 @@ public struct LyrebirdScratchView: View {
|
|||||||
/// evaluators. Routes through ``LyrebirdScratchModel/switchMode(to:)`` so the
|
/// evaluators. Routes through ``LyrebirdScratchModel/switchMode(to:)`` so the
|
||||||
/// seed placeholder follows the mode.
|
/// seed placeholder follows the mode.
|
||||||
private var modePicker: some View {
|
private var modePicker: some View {
|
||||||
Picker("Mode", selection: Binding(
|
// Bind `evalMode` directly: the segmented control writes one @Published
|
||||||
get: { model.evalMode },
|
// value synchronously, so the displayed segment and `model.evalMode`
|
||||||
// Defer to the next main-actor tick: the Picker's `set` runs inside
|
// can't desync (the old deferred-`Task` set let a re-render — e.g. the
|
||||||
// SwiftUI's view-update pass, and `switchMode` mutates @Published
|
// @Published burst from ⌘K's kill — revert the segment before the Task
|
||||||
// state ("Publishing changes from within view updates is not
|
// applied the switch, after which `switchMode`'s equality guard ate the
|
||||||
// allowed"). Scheduling it off the current pass avoids that.
|
// next click and the toggle appeared stuck). The mode's side-effects run
|
||||||
set: { newMode in Task { @MainActor in model.switchMode(to: newMode) } }
|
// from `.onChange(of: model.evalMode)` on the body, off the update pass.
|
||||||
)) {
|
Picker("Mode", selection: $model.evalMode) {
|
||||||
ForEach(ScratchEvalMode.allCases, id: \.self) { mode in
|
ForEach(ScratchEvalMode.allCases, id: \.self) { mode in
|
||||||
Text(mode.title).tag(mode)
|
Text(mode.title).tag(mode)
|
||||||
}
|
}
|
||||||
@@ -604,6 +610,15 @@ final class ScratchTextView: NSTextView {
|
|||||||
onManualComplete?()
|
onManualComplete?()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Menu-driven completion trigger (Edit ▸ Show Completions, ⌃Space). Routed
|
||||||
|
/// down the responder chain to the focused editor so the menu item needs no
|
||||||
|
/// explicit target; funnels to the same async-fetch path as Esc / F5 rather
|
||||||
|
/// than AppKit's bare `complete(_:)`, so the candidates are fetched before
|
||||||
|
/// the window opens.
|
||||||
|
@objc func scratchShowCompletions(_ sender: Any?) {
|
||||||
|
onManualComplete?()
|
||||||
|
}
|
||||||
|
|
||||||
/// Width of the line-number gutter drawn by ``ScratchLineNumberGutter``.
|
/// Width of the line-number gutter drawn by ``ScratchLineNumberGutter``.
|
||||||
/// `ScratchEditor.configure` reserves this as the text view's left inset so
|
/// `ScratchEditor.configure` reserves this as the text view's left inset so
|
||||||
/// the gutter overlay doesn't cover the text.
|
/// the gutter overlay doesn't cover the text.
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
// SnippetCompletionFilterTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS) || os(Linux)
|
||||||
|
import Testing
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
/// Unit coverage for the prefix narrowing that `SnippetCompletionService`
|
||||||
|
/// applies to a raw sourcekit-lsp completion list. sourcekit-lsp returns a
|
||||||
|
/// bare-identifier completion as the whole visible-symbol universe, unsorted and
|
||||||
|
/// unfiltered; without this narrowing the editor floods with SDK globals and
|
||||||
|
/// buries the real matches. No LSP server is launched — these exercise the pure
|
||||||
|
/// `partialWord` / `filterAndRank` helpers.
|
||||||
|
@Suite("Snippet completion prefix filtering")
|
||||||
|
struct SnippetCompletionFilterTests {
|
||||||
|
|
||||||
|
private func item(_ label: String, sortText: String? = nil) -> LSPCompletionItem {
|
||||||
|
LSPCompletionItem(
|
||||||
|
label: label,
|
||||||
|
detail: nil,
|
||||||
|
insertText: label,
|
||||||
|
kind: nil,
|
||||||
|
sortText: sortText
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: partialWord
|
||||||
|
|
||||||
|
@Test func partialWordReadsIdentifierBeforeCaretOnLaterLine() {
|
||||||
|
let body: String = "// a comment line\ncontext.reportMessage(\"hi\")\nOscS"
|
||||||
|
let prefix: String = SnippetCompletionService.partialWord(in: body, line: 2, character: 4)
|
||||||
|
#expect(prefix == "OscS")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func partialWordIsEmptyRightAfterADot() {
|
||||||
|
// Member completion: the char before the caret is `.`, not an identifier.
|
||||||
|
let body: String = "let x = OscSin."
|
||||||
|
let prefix: String = SnippetCompletionService.partialWord(in: body, line: 0, character: 15)
|
||||||
|
#expect(prefix == "")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func partialWordIsEmptyAtLineStart() {
|
||||||
|
let body: String = "foo\nbar"
|
||||||
|
let prefix: String = SnippetCompletionService.partialWord(in: body, line: 1, character: 0)
|
||||||
|
#expect(prefix == "")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func partialWordClampsCharacterPastLineEnd() {
|
||||||
|
let body: String = "OscSin"
|
||||||
|
let prefix: String = SnippetCompletionService.partialWord(in: body, line: 0, character: 999)
|
||||||
|
#expect(prefix == "OscSin")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func partialWordStopsAtNonIdentifierBoundary() {
|
||||||
|
let body: String = "Pan2(input: OscS"
|
||||||
|
let prefix: String = SnippetCompletionService.partialWord(in: body, line: 0, character: 16)
|
||||||
|
#expect(prefix == "OscS")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: filterAndRank
|
||||||
|
|
||||||
|
@Test func filterDropsNonMatchingGlobalsAndKeepsPrefixMatches() {
|
||||||
|
let items: [LSPCompletionItem] = [
|
||||||
|
item("IOHIDTransactionSetDirection(_:_:)"),
|
||||||
|
item("OscSaw"),
|
||||||
|
item("kOSNotificationMessageID"),
|
||||||
|
item("OscSin"),
|
||||||
|
item("CFNetDiagnosticSetName(_:_:)"),
|
||||||
|
]
|
||||||
|
let out: [LSPCompletionItem] = SnippetCompletionService.filterAndRank(items, prefix: "OscS")
|
||||||
|
let labels: [String] = out.map { $0.label }
|
||||||
|
#expect(labels == ["OscSaw", "OscSin"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func filterIsCaseInsensitiveAndRanksPrefixBeforeContains() {
|
||||||
|
let items: [LSPCompletionItem] = [
|
||||||
|
item("myOscSub"), // contains, not prefix
|
||||||
|
item("oscSin"), // prefix (case-insensitive)
|
||||||
|
item("Unrelated"),
|
||||||
|
]
|
||||||
|
let out: [LSPCompletionItem] = SnippetCompletionService.filterAndRank(items, prefix: "OSCS")
|
||||||
|
let labels: [String] = out.map { $0.label }
|
||||||
|
#expect(labels == ["oscSin", "myOscSub"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func emptyPrefixKeepsEveryItemSortedBySortText() {
|
||||||
|
// Member completion path: nothing is dropped, only ordered.
|
||||||
|
let items: [LSPCompletionItem] = [
|
||||||
|
item("Control", sortText: "2"),
|
||||||
|
item("Audio", sortText: "1"),
|
||||||
|
]
|
||||||
|
let out: [LSPCompletionItem] = SnippetCompletionService.filterAndRank(items, prefix: "")
|
||||||
|
#expect(out.map { $0.label } == ["Audio", "Control"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func noMatchYieldsEmptyRatherThanGlobalFlood() {
|
||||||
|
let items: [LSPCompletionItem] = [
|
||||||
|
item("IOHIDTransactionSetDirection(_:_:)"),
|
||||||
|
item("kOSNotificationMessageID"),
|
||||||
|
]
|
||||||
|
let out: [LSPCompletionItem] = SnippetCompletionService.filterAndRank(items, prefix: "OscS")
|
||||||
|
#expect(out.isEmpty)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -97,7 +97,7 @@ struct LyrebirdScratchModelTests {
|
|||||||
await model.run(additive: false)
|
await model.run(additive: false)
|
||||||
model.clearTracked()
|
model.clearTracked()
|
||||||
#expect(model.trackedSynthCount == 0)
|
#expect(model.trackedSynthCount == 0)
|
||||||
#expect(model.statusMessage == "Cleared all synths (tracked + slots).")
|
#expect(model.statusMessage == "Killed all sound (tracked synths + named slots cleared).")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
+3
@@ -22,6 +22,9 @@
|
|||||||
<FileRef
|
<FileRef
|
||||||
location = "group:Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj">
|
location = "group:Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj">
|
||||||
</FileRef>
|
</FileRef>
|
||||||
|
<FileRef
|
||||||
|
location = "group:Demos/LyrebirdScratch">
|
||||||
|
</FileRef>
|
||||||
<FileRef
|
<FileRef
|
||||||
location = "group:Demos/LyrebirdScratch/LyrebirdScratch.xcodeproj">
|
location = "group:Demos/LyrebirdScratch/LyrebirdScratch.xcodeproj">
|
||||||
</FileRef>
|
</FileRef>
|
||||||
|
|||||||
@@ -251,7 +251,7 @@ Workspace scheme selector exposes eleven entries:
|
|||||||
| `LyrebirdUI` | Builds the `LyrebirdUI` module only (SwiftUI parameter controls + visualisations) | macOS |
|
| `LyrebirdUI` | Builds the `LyrebirdUI` module only (SwiftUI parameter controls + visualisations) | macOS |
|
||||||
| `LyrebirdDemo` | CLI — plays through default output via `makeDefaultAudioDriver()` | macOS · Linux |
|
| `LyrebirdDemo` | CLI — plays through default output via `makeDefaultAudioDriver()` | macOS · Linux |
|
||||||
| `LyrebirdMacOSDemo` | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS |
|
| `LyrebirdMacOSDemo` | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS |
|
||||||
| `LyrebirdGUIDemo` | Cross-platform GUI — one shared source; SwiftUI here, GTK4 on Linux (`LYREBIRD_DEMO=vector`/`sine`) | macOS · Linux |
|
| `LyrebirdGUIDemo` | Cross-platform GUI — one shared source; SwiftUI here, GTK4 on Linux (`LYREBIRD_DEMO=conductor`/`vector`/`sine`) | macOS · Linux |
|
||||||
| `LyrebirdiOSDemo` | SwiftUI app — same UI via `iOSAudioDriver` (RemoteIO) | iOS |
|
| `LyrebirdiOSDemo` | SwiftUI app — same UI via `iOSAudioDriver` (RemoteIO) | iOS |
|
||||||
| `LyrebirdNRTDemo` | CLI — offline render via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
|
| `LyrebirdNRTDemo` | CLI — offline render via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
|
||||||
| `LyrebirdScoreDemo` | CLI — builds notated `Score`s (result-builder DSL), exports MusicXML, renders via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
|
| `LyrebirdScoreDemo` | CLI — builds notated `Score`s (result-builder DSL), exports MusicXML, renders via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
|
||||||
@@ -294,7 +294,7 @@ The CLI demo projects build and run on Linux too — each is its own package, so
|
|||||||
(cd Demos/LyrebirdQuickstartDemo && swift run) # a 440 Hz sine (needs libasound + a sound device)
|
(cd Demos/LyrebirdQuickstartDemo && swift run) # a 440 Hz sine (needs libasound + a sound device)
|
||||||
(cd Demos/LyrebirdDemo && swift run) # reverb smoke-test through default output
|
(cd Demos/LyrebirdDemo && swift run) # reverb smoke-test through default output
|
||||||
(cd Demos/LyrebirdScoreDemo && swift run) # notated Score → MusicXML + a rendered WAV (no device)
|
(cd Demos/LyrebirdScoreDemo && swift run) # notated Score → MusicXML + a rendered WAV (no device)
|
||||||
(cd Demos/LyrebirdGUIDemo && swift run) # cross-platform GUI via GTK4 (needs libgtk-4-dev); LYREBIRD_DEMO=vector|sine
|
(cd Demos/LyrebirdGUIDemo && swift run) # cross-platform GUI via GTK4 (needs libgtk-4-dev); LYREBIRD_DEMO=conductor|vector|sine
|
||||||
```
|
```
|
||||||
|
|
||||||
The four CLI demos plus `LyrebirdGUIDemo` (a GTK4 window here, SwiftUI on macOS) run on Linux; the AUv3 / iOS / `LyrebirdMacOSDemo` GUI demos are Apple-only. Full walk-through — toolchain, VS Code, building, running a sample: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
|
The four CLI demos plus `LyrebirdGUIDemo` (a GTK4 window here, SwiftUI on macOS) run on Linux; the AUv3 / iOS / `LyrebirdMacOSDemo` GUI demos are Apple-only. Full walk-through — toolchain, VS Code, building, running a sample: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
|
||||||
@@ -322,7 +322,7 @@ All nine live in [`Demos/`](Demos/). Each is its own SwiftPM package depending o
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| [`LyrebirdQuickstartDemo`](Demos/LyrebirdQuickstartDemo/) | CLI — fastest sound: a one-oscillator `SineTone` plays 440 Hz for 10 s, then exits (mirrors the `quickstart` template) | macOS · Linux |
|
| [`LyrebirdQuickstartDemo`](Demos/LyrebirdQuickstartDemo/) | CLI — fastest sound: a one-oscillator `SineTone` plays 440 Hz for 10 s, then exits (mirrors the `quickstart` template) | macOS · Linux |
|
||||||
| [`LyrebirdDemo`](Demos/LyrebirdDemo/) | CLI — plays through default output via `makeDefaultAudioDriver()` (Core Audio on macOS, ALSA on Linux) | macOS · Linux |
|
| [`LyrebirdDemo`](Demos/LyrebirdDemo/) | CLI — plays through default output via `makeDefaultAudioDriver()` (Core Audio on macOS, ALSA on Linux) | macOS · Linux |
|
||||||
| [`LyrebirdGUIDemo`](Demos/LyrebirdGUIDemo/) | GUI — live `@UIParam` controls, XY pad, oscilloscope, CPU meters, from one shared source; AppKit/SwiftUI on macOS, GTK4/SwiftOpenUI on Linux (`LYREBIRD_DEMO=vector`/`sine`) | macOS · Linux |
|
| [`LyrebirdGUIDemo`](Demos/LyrebirdGUIDemo/) | GUI — live `EventConductor` ensemble (default), XY pad, sine tone, oscilloscope, CPU meters, from one shared source; AppKit/SwiftUI on macOS, GTK4/SwiftOpenUI on Linux (`LYREBIRD_DEMO=conductor`/`vector`/`sine`) | macOS · Linux |
|
||||||
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | SwiftUI app — live oscilloscope, `@UIParam` knobs, vector / sine / spectral-bin-delay patches | macOS |
|
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | SwiftUI app — live oscilloscope, `@UIParam` knobs, vector / sine / spectral-bin-delay patches | macOS |
|
||||||
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | SwiftUI app — same UI system via `iOSAudioDriver` (RemoteIO) | iOS |
|
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | SwiftUI app — same UI system via `iOSAudioDriver` (RemoteIO) | iOS |
|
||||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
|
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
|
||||||
@@ -330,7 +330,7 @@ All nine live in [`Demos/`](Demos/). Each is its own SwiftPM package depending o
|
|||||||
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro | macOS |
|
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro | macOS |
|
||||||
| [`LyrebirdScratch`](Demos/LyrebirdScratch/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
| [`LyrebirdScratch`](Demos/LyrebirdScratch/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||||
|
|
||||||
Each demo has a `Synthesizers/` folder — drop new `SynthesizerBase` subclasses there. See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for step-by-step instructions and per-demo notes.
|
Most demos have a `Synthesizers/` folder — drop new `SynthesizerBase` subclasses there. (`LyrebirdAUv3Demo` keeps its voice in `LyrebirdFMExtension/`; `LyrebirdScratch` has none — it compiles snippets at runtime.) See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for step-by-step instructions and per-demo notes.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+73
@@ -7,6 +7,79 @@ functionality in a backward-compatible way.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 2.4.1 — Scratchpad polish and demo cleanup
|
||||||
|
|
||||||
|
A maintenance release: no framework API changes. It sharpens the LiveCompile
|
||||||
|
scratchpad's UX and tidies the demos and their documentation.
|
||||||
|
|
||||||
|
**Scratchpad — "Kill All Sound".** The panic command that stops every tracked
|
||||||
|
synth and clears the slots is now named **Kill All Sound** (⌘K) in the macOS
|
||||||
|
menu, and **Kill audio** on the Linux button, so the control is discoverable
|
||||||
|
rather than buried under a vague label.
|
||||||
|
|
||||||
|
**Scratchpad — mode switch fixed.** Switching the editor between Swift and
|
||||||
|
graph-DSL mode no longer desyncs when ⌘K (or any command) fires mid-switch. The
|
||||||
|
segmented control now binds the model's mode directly and applies the
|
||||||
|
placeholder/diagnostic reset as an `onChange` side effect, so the picker and the
|
||||||
|
model can never disagree.
|
||||||
|
|
||||||
|
**Scratchpad — code completion restored.** Manual completion (⌃Space) works
|
||||||
|
again and no longer floods the editor: the client now derives the typed prefix
|
||||||
|
and filters/ranks the language-server candidates against it, instead of dumping
|
||||||
|
the entire visible-symbol universe over the caret. Member completion after `.`
|
||||||
|
is unchanged (already server-scoped).
|
||||||
|
|
||||||
|
**Demos — cleanup.** The GUI demo's three voices moved into a `Synthesizers/`
|
||||||
|
folder to match the per-demo convention, and the CLI `EventPattern` demo was
|
||||||
|
split so its lead and bass builders are separate helpers and its `BlipVoice`
|
||||||
|
lives in its own file. Demo READMEs and `LYREBIRD_START_HERE` were corrected to
|
||||||
|
match the code — the cross-platform GUI demo now defaults to the event
|
||||||
|
conductor, and the live-coding scratchpad's Linux (GTK4) support is documented
|
||||||
|
alongside macOS.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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
|
## 2.3.0 — Edit-ended callback on continuous controls
|
||||||
|
|
||||||
A small, additive, source-compatible release. The continuous `LyrebirdUI`
|
A small, additive, source-compatible release. The continuous `LyrebirdUI`
|
||||||
|
|||||||
@@ -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`.
|
``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
|
## See Also
|
||||||
|
|
||||||
|
- ``EventPattern``
|
||||||
|
- ``MonoEventPattern``
|
||||||
|
- ``ParallelEventPattern``
|
||||||
|
- ``EventConductor``
|
||||||
|
- ``EventConductorHandle``
|
||||||
|
- ``EventQuantum``
|
||||||
|
- ``EventGated``
|
||||||
|
- ``EventSustainAware``
|
||||||
- ``LyrebirdClock``
|
- ``LyrebirdClock``
|
||||||
- ``ValueComputable``
|
- ``ValueComputable``
|
||||||
- <doc:Scheduling>
|
- <doc:Scheduling>
|
||||||
|
|||||||
@@ -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.
|
// `elapsedSamples` value at the most recent tempo change.
|
||||||
private var _sampleTempoChangeSamples: SampleTime = 0
|
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(
|
internal init(
|
||||||
engine: SynthesisEngine,
|
engine: SynthesisEngine,
|
||||||
control: RoutineControl
|
control: RoutineControl
|
||||||
@@ -345,6 +350,89 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
|
|||||||
param.value = value
|
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
|
/// 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
|
/// on `target`. **Blocks** the routine/task body for the duration — like ``wait(seconds:)``, so it
|
||||||
/// sequences naturally with the body's other timed events.
|
/// sequences naturally with the body's other timed events.
|
||||||
@@ -415,6 +503,9 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
|
|||||||
_pauseAccumulated += pauseDuration
|
_pauseAccumulated += pauseDuration
|
||||||
_pauseAccumulatedSamples += _engine.currentTime - pauseStartSamples
|
_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())
|
let remaining: TimeInterval = adjustedTarget.timeIntervalSince(Date())
|
||||||
if remaining <= 0 { break }
|
if remaining <= 0 { break }
|
||||||
Thread.sleep(forTimeInterval: min(LyrebirdRoutineContext.pollIntervalSeconds, remaining))
|
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
|
/// One-shot carrier that returns a (possibly non-`Sendable`) value from a synchronous
|
||||||
/// main-thread hop in ``LyrebirdRoutineContext/onMain(_:)``.
|
/// main-thread hop in ``LyrebirdRoutineContext/onMain(_:)``.
|
||||||
///
|
///
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
/// The current Lyrebird framework and CLI version.
|
/// The current Lyrebird framework and CLI version.
|
||||||
public let lyrebirdVersion: String = "2.3.0"
|
public let lyrebirdVersion: String = "2.4.1"
|
||||||
|
|
||||||
/// The banner printed when the interactive shell or REPL session starts.
|
/// The banner printed when the interactive shell or REPL session starts.
|
||||||
public let welcomeBanner: String = """
|
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 }
|
||||||
|
}
|
||||||
@@ -134,6 +134,43 @@ swift package update Lyrebird # resolves to the new tag if Package.swift `fro
|
|||||||
swift build && swift test
|
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
|
## Flags
|
||||||
|
|
||||||
- `--dev PATH` / `--release PATH` — override the default repo locations.
|
- `--dev PATH` / `--release PATH` — override the default repo locations.
|
||||||
|
|||||||
@@ -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
|
## LyrebirdRoutine
|
||||||
|
|
||||||
Runs a closure **once** on a dedicated background thread (`Thread`, `.userInitiated` QoS).
|
Runs a closure **once** on a dedicated background thread (`Thread`, `.userInitiated` QoS).
|
||||||
|
|||||||
@@ -209,4 +209,7 @@ minimal scratch window → (optional) full GtkSourceView editor.
|
|||||||
— the Process/EventList family (`LyrebirdEventListPerformanceView` inline,
|
— the Process/EventList family (`LyrebirdEventListPerformanceView` inline,
|
||||||
hosting `LyrebirdEventListView` + per-process `LyrebirdProcessView` strips,
|
hosting `LyrebirdEventListView` + per-process `LyrebirdProcessView` strips,
|
||||||
plus `presentInWindow` for EventListPerformance / EventList / RunningProcesses).
|
plus `presentInWindow` for EventListPerformance / EventList / RunningProcesses).
|
||||||
5. (Stretch) live-coding scratchpad usable on Linux — not started.
|
5. ✅ Live-coding scratchpad usable on Linux — done. GTK4 host
|
||||||
|
`LyrebirdScratchLinuxDemo` (`LinuxScratchView` / `LinuxScratchModel` on the
|
||||||
|
SwiftOpenUI backend, GtkSourceView editor + completion + save/load + live
|
||||||
|
scope). Run + setup in `LINUX_README.md`; full surface in LiveCoding.docc.
|
||||||
|
|||||||
@@ -277,6 +277,8 @@ Sources/Lyrebird/Lyrebird.docc/REPLGuide.md 0 2dc70e99b6404557 none
|
|||||||
Sources/Lyrebird/Lyrebird.docc/RoutineTask.md 0 97969b7e340a3fad 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 14 86a37ee4afa1de70 none
|
||||||
Sources/Lyrebird/Lyrebird.docc/RoutineTask.md 16 62b70fad58edb312 engine
|
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/RoutineTask.md 2 925a5e2121afa5e3 engine
|
||||||
Sources/Lyrebird/Lyrebird.docc/Scheduling.md 0 2c95d843ffa87129 none
|
Sources/Lyrebird/Lyrebird.docc/Scheduling.md 0 2c95d843ffa87129 none
|
||||||
Sources/Lyrebird/Lyrebird.docc/Scheduling.md 2 f6081f955c94e613 engine
|
Sources/Lyrebird/Lyrebird.docc/Scheduling.md 2 f6081f955c94e613 engine
|
||||||
@@ -365,6 +367,7 @@ Sources/Lyrebird/Math/LyrebirdMusicMath.swift 5 c93b09a35c5656b6 none
|
|||||||
Sources/Lyrebird/Math/LyrebirdMusicMath.swift 6 1e2f63b9517d115d none
|
Sources/Lyrebird/Math/LyrebirdMusicMath.swift 6 1e2f63b9517d115d none
|
||||||
Sources/Lyrebird/Math/LyrebirdMusicMath.swift 7 63878da5cac0b38e none
|
Sources/Lyrebird/Math/LyrebirdMusicMath.swift 7 63878da5cac0b38e none
|
||||||
Sources/Lyrebird/OSC/OSCClient.swift 0 8d156b807b49c1a5 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/Scheduling/LyrebirdTask.swift 1 ca99def354fe2f0a engine
|
||||||
Sources/Lyrebird/Score/Glissando.swift 0 673ddef8256aa6b3 none
|
Sources/Lyrebird/Score/Glissando.swift 0 673ddef8256aa6b3 none
|
||||||
Sources/Lyrebird/Score/NoteDisplay.swift 0 f706dacb94d58307 none
|
Sources/Lyrebird/Score/NoteDisplay.swift 0 f706dacb94d58307 none
|
||||||
@@ -566,8 +569,9 @@ docs/tooling/project-system.md 1 a92cddd62262b494 none
|
|||||||
docs/tooling/project-system.md 3 491d32c269a92cbf none
|
docs/tooling/project-system.md 3 491d32c269a92cbf none
|
||||||
docs/tooling/repl.md 0 fe33a7d93a42d23c none
|
docs/tooling/repl.md 0 fe33a7d93a42d23c none
|
||||||
docs/tooling/routine-task.md 1 13ef865253b3351c none
|
docs/tooling/routine-task.md 1 13ef865253b3351c none
|
||||||
docs/tooling/routine-task.md 11 b95b191b847d061e engine
|
docs/tooling/routine-task.md 11 be652d2b3b6f274f none
|
||||||
docs/tooling/routine-task.md 9 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 0 81b40cbafc6f2d80 none
|
||||||
docs/tooling/targets.md 1 611af51e70b6320e none
|
docs/tooling/targets.md 1 611af51e70b6320e none
|
||||||
docs/ui/gui-system.md 0 84caaf99ee346e95 none
|
docs/ui/gui-system.md 0 84caaf99ee346e95 none
|
||||||
|
|||||||
Reference in New Issue
Block a user