v2.4.0 release: event patterns + live event conductor

This commit is contained in:
2026-12-03 08:45:07 -08:00
parent a175c437de
commit 6da3615707
40 changed files with 4223 additions and 19 deletions
@@ -9,6 +9,7 @@
/* Begin PBXBuildFile section */
0306C7C02FAC451300952EAF /* GVerbTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7BF2FAC451300952EAF /* GVerbTest.swift */; };
0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7C12FAC45F200952EAF /* ReverbDemo.swift */; };
631D4C5B1150427CB8D15210 /* EventPatternDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99B83EC83F6C48D98441D7F7 /* EventPatternDemo.swift */; };
035A2F422FAA4F67007F6289 /* PercPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F3F2FAA4F67007F6289 /* PercPitchShift.swift */; };
035A2F432FAA4F67007F6289 /* PercSpectralPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F412FAA4F67007F6289 /* PercSpectralPitchShift.swift */; };
035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F492FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift */; };
@@ -26,6 +27,7 @@
/* Begin PBXFileReference section */
0306C7BF2FAC451300952EAF /* GVerbTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GVerbTest.swift; sourceTree = "<group>"; };
0306C7C12FAC45F200952EAF /* ReverbDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReverbDemo.swift; sourceTree = "<group>"; };
99B83EC83F6C48D98441D7F7 /* EventPatternDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventPatternDemo.swift; sourceTree = "<group>"; };
035A2F3E2FAA4F67007F6289 /* PercBufferRead.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercBufferRead.swift; sourceTree = "<group>"; };
035A2F3F2FAA4F67007F6289 /* PercPitchShift.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercPitchShift.swift; sourceTree = "<group>"; };
035A2F402FAA4F67007F6289 /* PercPlayBuffer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercPlayBuffer.swift; sourceTree = "<group>"; };
@@ -56,6 +58,7 @@
isa = PBXGroup;
children = (
0306C7C12FAC45F200952EAF /* ReverbDemo.swift */,
99B83EC83F6C48D98441D7F7 /* EventPatternDemo.swift */,
035B00032FAB0000007F0001 /* DemoProtocol.swift */,
035B00042FAB0000007F0001 /* BufferDemos.swift */,
);
@@ -207,6 +210,7 @@
035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */,
035A2F442FAA4F67007F6289 /* PercBufferRead.swift in Sources */,
0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */,
631D4C5B1150427CB8D15210 /* EventPatternDemo.swift in Sources */,
035A2F452FAA4F67007F6289 /* PercPlayBuffer.swift in Sources */,
C1A000000000000000000007 /* main.swift in Sources */,
C1A000000000000000000016 /* SineTone.swift in Sources */,
@@ -0,0 +1,110 @@
// EventPatternDemo.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
/// Demonstrates ``EventPattern`` — Lyrebird's event-driven player: bound value patterns drive a
/// fresh self-freeing voice per event, played as a dur/legato-timed stream.
///
/// Also shows two patterns running together via ``ParallelEventPattern``: a lead phrase and a
/// bass line that enters a few beats in on the same beat grid, with a single
/// ``EventPatternHandle/waitUntilComplete(releasePadding:)`` blocking until the longer of the two
/// finishes.
final class EventPatternDemo: DemoProtocol {
private let engine: SynthesisEngine
init(engine: SynthesisEngine) {
self.engine = engine
}
/// A gated voice (``EventGated``): a sine through an `EnvelopeGen` whose gate holds it at full
/// level while the note sounds, then plays a release and frees the voice via
/// `doneAction: .freeNode` when `EventPattern` closes the gate at the note's sustain. No
/// external removal, so the release is never hard-cut — nothing to tune, no click.
private final class BlipVoice: SynthesizerBase, EventGated {
/// Envelope release length in seconds — how long a note rings after its gate closes.
/// Exposed so the demo can let the final note's tail finish before stopping the engine.
nonisolated static let releaseSeconds: Double = 0.3
/// Envelope attack length in seconds.
nonisolated static let attackSeconds: Double = 0.01
@LiveParam var freq: Double = 440.0
@LiveParam var amp: Double = 0.2
@LiveParam var gate: Double = 1.0 // open by default so the attack fires on add
var eventGate: ParameterNode { $gate }
override func build() {
// `releaseNode: 1` holds at `levels[1]` (full) while the gate is open; when the gate
// drops to 0 the generator plays segment 1 (the release to 0) and then self-frees.
let envelope: Envelope = Envelope(
levels: [0.0, 1.0, 0.0],
durations: [BlipVoice.attackSeconds, BlipVoice.releaseSeconds],
curves: [.welch, .welch],
releaseNode: 1
)
let shaped: EnvelopeGen.Audio = EnvelopeGen.Audio(
envelope: envelope,
gate: $gate,
doneAction: .freeNode
)
let source: OscSin.Audio = OscSin.Audio(freq: $freq, mul: $amp)
output(bus: 0, source: source * shaped)
}
}
func runDemo() {
print("\n── EventPattern demo ──")
let tempoBPM: Double = 132.0
// Pattern 1 — the lead: a short A-minor-pentatonic phrase, written as named pitches rather
// than raw Hz (equivalent MIDI form: `Pitch.midi(69).frequency`, etc.), played three times.
let phrase: [Pitch] = [
.named(.a, 4), .named(.c, 5), .named(.d, 5), .named(.e, 5),
.named(.g, 5), .named(.e, 5), .named(.d, 5), .named(.c, 5),
]
let leadFreqs: [Double] = phrase.compactMap(\.frequency)
let lead: EventPattern<BlipVoice> = EventPattern(make: { BlipVoice() })
.bind(\.freq, .sequence(leadFreqs, repeats: 1))
.bind(\.amp, .uniformRandom(low: 0.15, high: 0.3))
.dur(.sequence([0.25, 0.25, 0.25, 0.5]))
.legato(0.8)
.tempo(tempoBPM)
.repeats(3)
// Pattern 2 — a bass line that enters `leadInBeats` after the lead and outlasts it.
// There is no cross-pattern clock: `ParallelEventPattern` launches both children from the
// one `play` call, so they share a start instant, and at the SAME tempo they share a beat
// grid. `addAfter(beats:)` staggers the bass's entry on that grid — the bass simply waits
// `leadInBeats` beats before its first note.
let leadInBeats: Double = 2.0
let bassPhrase: [Pitch] = [.named(.a, 2), .named(.a, 2), .named(.g, 2), .named(.e, 2)]
let bassFreqs: [Double] = bassPhrase.compactMap(\.frequency)
let bass: EventPattern<BlipVoice> = EventPattern(make: { BlipVoice() })
.bind(\.freq, .sequence(bassFreqs, repeats: 1))
.bind(\.amp, .uniformRandom(low: 0.2, high: 0.3))
.dur(.sequence([1.0]))
.legato(0.9)
.tempo(tempoBPM)
.repeats(1)
// Start both together, staggering the bass two beats in, and control them as one handle.
let ensemble: ParallelEventPattern = ParallelEventPattern()
ensemble.add(lead)
ensemble.addAfter(beats: leadInBeats, eventPattern: bass)
let handle: EventPatternHandle = ensemble.play(on: engine)
// `waitUntilComplete` blocks until EVERY child task has finished — so it waits for the
// longer-running bass, not just the lead. `releasePadding` then lets the final note's
// envelope release ring out before `main.swift` stops the engine — without it,
// `engine.stop()` would cut the tail (an end-of-phrase click).
handle.waitUntilComplete(releasePadding: BlipVoice.releaseSeconds)
print("\nEventPattern demo complete.")
}
}
+13 -3
View File
@@ -7,11 +7,18 @@
import Foundation
import LyrebirdSynth
// ── Demo selector ─────────────────────────────────────────────────────────────
// Change `demo` to `.buffer`, `.reverb`, or `.eventPattern` to switch demos.
private enum Demo { case buffer, reverb, eventPattern }
private let demo: Demo = .eventPattern
// ──────────────────────────────────────────────────────────────────────────────
// `makeDefaultAudioDriver()` selects the platform backend — Core Audio on Apple,
// ALSA on Linux (needs libasound) — so the demo builds and runs on both.
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 44100,
controlBlockSize: 64,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 2,
driver: makeDefaultAudioDriver()
@@ -24,7 +31,10 @@ do {
exit(1)
}
// BufferDemos(engine: engine).runDemo()
ReverbDemo(engine: engine).runDemo()
switch demo {
case .buffer: BufferDemos(engine: engine).runDemo()
case .reverb: ReverbDemo(engine: engine).runDemo()
case .eventPattern: EventPatternDemo(engine: engine).runDemo()
}
engine.stop()
+1 -1
View File
@@ -15,7 +15,7 @@ import PackageDescription
// macOS: swift run LyrebirdGUIDemo (or open the thin Xcode project)
// Linux: swift run LyrebirdGUIDemo (needs libgtk-4-dev + libasound2-dev)
//
// Select the synth with LYREBIRD_DEMO=vector (default) or LYREBIRD_DEMO=sine.
// Select the synth with LYREBIRD_DEMO=vector (default), sine, or conductor.
let package = Package(
name: "LyrebirdGUIDemo",
platforms: [.macOS(.v15)],
@@ -12,7 +12,7 @@
// • Linux — a GTK4 `App`/`WindowGroup` scene run by `GTK4Backend`.
//
// Run either with `swift run LyrebirdGUIDemo`. Pick the synth with
// `LYREBIRD_DEMO=vector` (default) or `LYREBIRD_DEMO=sine`.
// `LYREBIRD_DEMO=vector` (default), `sine`, or `conductor`.
//
// `@ViewBuilder` and the window hosts come from SwiftUI on macOS and from
// SwiftOpenUI (re-exported through `LyrebirdUI`) on Linux — hence the single
@@ -30,7 +30,7 @@ import LyrebirdGUIDemoKit
let selection: DemoSelection = DemoSelection.fromEnvironment()
private let demoBlockSize: Int = 512
private let demoSampleRate: Double = 44_100.0
private let demoSampleRate: Double = 48_000.0
private let demoScopeBufferSize: Int = 2048
// Oscilloscope tap on the stereo output buses. Must be set before `start()`.
@@ -102,6 +102,8 @@ func demoContent() -> some View {
scope: demoScope,
engine: statusEngine
)
} else if selection == .conductor {
ConductorDemoView(scope: demoScope, engine: statusEngine)
} else {
SineToneDemoView(
frequencyNode: sineFreq,
@@ -117,11 +119,14 @@ func demoContent() -> some View {
// Start the engine and add the selected synth. `engine.start()` / `add` are
// @MainActor; main.swift's top level is main-actor isolated, so these are direct
// calls. On a build with no live backend the GUI still runs (silently).
do {
try demoEngine.start()
try demoEngine.add(activeSynth)
} catch {
print("[Lyrebird] demo engine setup failed: \(error)")
// The conductor demo is the exception: its view starts and stops the engine itself.
if selection != .conductor {
do {
try demoEngine.start()
try demoEngine.add(activeSynth)
} catch {
print("[Lyrebird] demo engine setup failed: \(error)")
}
}
if !isLiveAudioAvailable {
@@ -0,0 +1,156 @@
// ConductorDemoController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Observation
import LyrebirdSynth
/// Owns the engine lifecycle, the ``EventConductor`` and the on/off state of the two parts for
/// ``ConductorDemoView``.
///
/// A pattern is single-shot, so each toggle-on builds a fresh ``EventPattern`` and hands it to the
/// conductor, entering on the next beat. ``EventConductor/add(_:quantize:)`` returns an
/// ``EventConductorHandle``; toggling a part off calls ``EventConductorHandle/stop()`` on its
/// handle, which releases that part alone (its gated voices ring out) without touching the other.
///
/// `@unchecked Sendable`: main-thread-confined — every method is called from a button action.
@Observable
final class ConductorDemoController: @unchecked Sendable {
/// Shared tempo of the conductor and both parts, in beats per minute.
private static let tempoBPM: Double = 120.0
/// Top part: events per beat grid, in beats.
private static let topEventBeats: Double = 0.5
/// Bottom part: one event per beat.
private static let bottomEventBeats: Double = 1.0
/// Sustain fraction of each event's duration.
private static let legato: Double = 0.8
/// Top part: A-minor pentatonic phrase.
private static let topPhrase: [Pitch] = [
.named(.a, 4), .named(.c, 5), .named(.d, 5), .named(.e, 5),
.named(.g, 5), .named(.e, 5), .named(.d, 5), .named(.c, 5),
]
/// Bottom part: a simple root-fifth bass figure.
private static let bottomPhrase: [Pitch] = [
.named(.a, 2), .named(.a, 2), .named(.g, 2), .named(.e, 2),
]
private static let topAmpLow: Double = 0.10
private static let topAmpHigh: Double = 0.18
private static let bottomAmpLow: Double = 0.20
private static let bottomAmpHigh: Double = 0.28
private let engine: SynthesisEngine
/// `true` while the engine (and conductor) is running.
private(set) var engineRunning: Bool = false
/// `true` while the top part is switched on.
private(set) var topOn: Bool = false
/// `true` while the bottom part is switched on.
private(set) var bottomOn: Bool = false
@ObservationIgnored private var conductor: EventConductor?
@ObservationIgnored private var topHandle: EventConductorHandle?
@ObservationIgnored private var bottomHandle: EventConductorHandle?
init(engine: SynthesisEngine) {
self.engine = engine
}
/// Starts the engine and a fresh conductor, or stops both (releasing any playing parts).
func toggleEngine() {
if engineRunning {
topHandle?.stop()
bottomHandle?.stop()
conductor?.stop()
conductor = nil
topHandle = nil
bottomHandle = nil
topOn = false
bottomOn = false
MainActor.assumeIsolated { engine.stop() }
engineRunning = false
} else {
do {
try MainActor.assumeIsolated { try engine.start() }
} catch {
print("[Lyrebird] engine.start failed: \(error)")
return
}
let newConductor: EventConductor = EventConductor(tempo: ConductorDemoController.tempoBPM)
MainActor.assumeIsolated { newConductor.start(on: engine) }
conductor = newConductor
engineRunning = true
}
}
/// Toggles the top (melodic) part. Entering is quantised to the next beat; stopping releases it
/// immediately through its handle.
func toggleTop() {
guard let active: EventConductor = conductor else { return }
if topOn {
topHandle?.stop()
topHandle = nil
topOn = false
} else {
let pattern: EventPattern<ConductorDemoVoice> = makePattern(
phrase: ConductorDemoController.topPhrase,
eventBeats: ConductorDemoController.topEventBeats,
ampLow: ConductorDemoController.topAmpLow,
ampHigh: ConductorDemoController.topAmpHigh
)
topHandle = active.add(pattern, quantize: .nextBeat)
topOn = true
}
}
/// Toggles the bottom (bass) part. Entering is quantised to the next beat; stopping releases it
/// immediately through its handle.
func toggleBottom() {
guard let active: EventConductor = conductor else { return }
if bottomOn {
bottomHandle?.stop()
bottomHandle = nil
bottomOn = false
} else {
let pattern: EventPattern<ConductorDemoVoice> = makePattern(
phrase: ConductorDemoController.bottomPhrase,
eventBeats: ConductorDemoController.bottomEventBeats,
ampLow: ConductorDemoController.bottomAmpLow,
ampHigh: ConductorDemoController.bottomAmpHigh
)
bottomHandle = active.add(pattern, quantize: .nextBeat)
bottomOn = true
}
}
/// Builds a fresh, endlessly looping pattern: both the phrase and the duration are infinite
/// `.sequence` patterns, so the part plays until its handle is stopped.
private func makePattern(
phrase: [Pitch],
eventBeats: Double,
ampLow: Double,
ampHigh: Double
) -> EventPattern<ConductorDemoVoice> {
let freqs: [Double] = phrase.compactMap(\.frequency)
// Key-path formation on a `@LiveParam` needs the main actor.
return MainActor.assumeIsolated {
EventPattern(make: { ConductorDemoVoice() })
.bind(\.freq, .sequence(freqs))
.bind(\.amp, .uniformRandom(low: ampLow, high: ampHigh))
.dur(.sequence([eventBeats]))
.legato(ConductorDemoController.legato)
.tempo(ConductorDemoController.tempoBPM)
}
}
}
@@ -0,0 +1,62 @@
// ConductorDemoView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if canImport(SwiftUI)
import SwiftUI
#endif
import LyrebirdSynth
import LyrebirdUI
/// Demonstrates ``EventConductor``: start the engine, then toggle a top and a bottom part on and
/// off. Each part loops forever while on and enters on the next beat of the conductor's clock, so
/// the two lock together however late they are pressed. Includes the CPU status strip and an
/// oscilloscope.
///
/// Written to the View-DSL subset shared by SwiftUI and SwiftOpenUI, so it runs on macOS and Linux.
/// Buttons use the `action:label:` form, which fires reliably on both backends.
public struct ConductorDemoView: View {
let scope: ScopeCapture
let engine: SynthesisEngine
@State private var controller: ConductorDemoController
public init(scope: ScopeCapture, engine: SynthesisEngine) {
self.scope = scope
self.engine = engine
_controller = State(wrappedValue: ConductorDemoController(engine: engine))
}
public var body: some View {
VStack {
Text("Lyrebird — Event Conductor")
.font(.headline)
Button {
controller.toggleEngine()
} label: {
Text(controller.engineRunning ? "Stop Engine" : "Start Engine")
}
Button {
controller.toggleTop()
} label: {
Text(controller.topOn ? "Top Part: ON (tap to stop)" : "Top Part: off (starts on next beat)")
}
.disabled(!controller.engineRunning)
Button {
controller.toggleBottom()
} label: {
Text(controller.bottomOn
? "Bottom Part: ON (tap to stop)"
: "Bottom Part: off (starts on next beat)")
}
.disabled(!controller.engineRunning)
LyrebirdStatusView(engine: engine)
LyrebirdScopeView(capture: scope)
.frame(height: 120)
}
.padding()
}
}
@@ -0,0 +1,47 @@
// ConductorDemoVoice.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// A gated sine voice for the conductor demo. ``EventPattern`` holds its gate open for the note's
/// sustain, then closes it; the envelope plays its release and frees the voice, so a part that is
/// toggled off rings out cleanly instead of being cut.
final class ConductorDemoVoice: SynthesizerBase, EventGated {
/// Envelope attack length in seconds.
nonisolated static let attackSeconds: Double = 0.01
/// Envelope release length in seconds — how long a note rings after its gate closes.
nonisolated static let releaseSeconds: Double = 0.3
/// Oscillator frequency in Hz. Bound per event by the pattern.
@LiveParam var freq: Double = 440.0
/// Linear output gain, 0...1. Bound per event by the pattern.
@LiveParam var amp: Double = 0.2
/// Envelope gate. Open by default so the attack fires when the voice is added.
@LiveParam var gate: Double = 1.0
var eventGate: ParameterNode { $gate }
override func build() {
let envelope: Envelope = Envelope(
levels: [0.0, 1.0, 0.0],
durations: [ConductorDemoVoice.attackSeconds, ConductorDemoVoice.releaseSeconds],
curves: [.welch, .welch],
releaseNode: 1
)
let shaped: EnvelopeGen.Audio = EnvelopeGen.Audio(
envelope: envelope,
gate: $gate,
doneAction: .freeNode
)
let source: OscSin.Audio = OscSin.Audio(freq: $freq, mul: $amp)
let mono: any ValidGeneratorInput = source * shaped
output(bus: 0, source: Pan2(input: mono, pan: 0.0))
}
}
@@ -17,10 +17,14 @@ public enum DemoSelection: String, Sendable {
/// Stereo sine tone with frequency / amplitude / pan controls.
case sine
/// Live event ensemble: engine start/stop plus top and bottom parts driven by an
/// ``EventConductor``. The view owns the engine, so nothing starts at launch.
case conductor
/// Resolve the selection from `LYREBIRD_DEMO` (defaults to `.vector`).
public static func fromEnvironment() -> DemoSelection {
let raw: String = ProcessInfo.processInfo.environment["LYREBIRD_DEMO"]?.lowercased() ?? "vector"
return DemoSelection(rawValue: raw) ?? .vector
let raw: String = ProcessInfo.processInfo.environment["LYREBIRD_DEMO"]?.lowercased() ?? "conductor"
return DemoSelection(rawValue: raw) ?? .conductor
}
/// Title-bar text for the window hosting this demo.
@@ -28,6 +32,7 @@ public enum DemoSelection: String, Sendable {
switch self {
case .vector: return "Lyrebird — Vector Oscillator"
case .sine: return "Lyrebird — Sine Tone"
case .conductor: return "Lyrebird — Event Conductor"
}
}
}
@@ -12,7 +12,7 @@ import LyrebirdUI
// ── Demo selector ─────────────────────────────────────────────────────────────
// Change `demo` to `.sineTone` or `.binDelay` to switch demos.
private enum Demo { case vector, binDelay, sineTone }
private let demo: Demo = .vector
private let demo: Demo = .binDelay
// ──────────────────────────────────────────────────────────────────────────────
final class AppDelegate: NSObject, NSApplicationDelegate {
@@ -9,7 +9,7 @@ import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 44100,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()