12 KiB
GUI System
Lyrebird provides native macOS UI via SwiftUI in the LyrebirdUI module. Controls bind
directly to Synthesizer parameters — the same parameter update path used by code is used
by the UI, so there is no special "GUI mode". Any parameter controllable from code is
automatically controllable from a GUI control, and vice versa.
The core Lyrebird module has no UI dependency — LyrebirdUI is imported only by
targets that need GUI windows.
import LyrebirdSynth // engine, protocols, generators — no UI
import LyrebirdUI // LyrebirdWindow, @UIParam, ParameterSlider, etc.
@LiveParam vs @UIParam
Lyrebird provides two property wrappers for RT-safe parameters:
@LiveParam |
@UIParam |
|
|---|---|---|
| Module | Lyrebird (no UI) |
LyrebirdUI |
| Projected value | ParameterNode |
UIParamNode |
IS a Generator? |
Yes (AudioGenerator) |
No (ValidGeneratorInput only) |
| RT delivery to oscillators/filters | Per-sample linear ramp | Block-constant (atomic read) |
| SwiftUI binding | No | Yes — @Observable, all Parameter* controls |
| When to use | Code-only synths; any param needing smooth per-sample ramps | Synths with SwiftUI UI controls |
Identical RT behavior: both @LiveParam and @UIParam deliver a linearly-interpolated
ramp from the previous block's last value to the new atomic target via their projected
ControlGenerator node. @UIParam adds an @Observable value for SwiftUI binding on
top — there is no behavioral difference at the audio thread.
Core Concept: @UIParam
A struct property wrapper that is simultaneously:
- A
ValidGeneratorInput(via its projectedUIParamNode, aControlGenerator) — wire$paramNamedirectly into the audio graph inbuild(). - An
@Observablevalue — SwiftUI views bind to the node and redraw automatically when the value changes. - RT-safe — the audio render callback reads via a lock-free
Atomic<UInt64>load; the main thread writes via a releasing atomic store. No locks, no queue drain.
import LyrebirdUI
final class MySynth: SynthesizerBase {
@UIParam var amplitude: Double = 0.5
@UIParam var frequency: Double = 440.0
override func build() {
let osc = OscSin.Audio(freq: $frequency)
output(bus: 0, source: osc * $amplitude)
}
}
@UIParam properties auto-register at build() time via Mirror reflection — no
declareParameter call is needed. The property name (with leading _ of property-wrapper
backing storage stripped) is the parameter key for updateParameter / OSC handlers.
Projected value
$paramName returns a UIParamNode — an @Observable class that conforms to
ValidGeneratorInput. This is the object you pass to UI controls:
ParameterSlider("Freq", node: synth.$frequency, range: 20...20000)
Reading and writing from code
synth.amplitude = 0.2 // atomic store → RT thread picks up next block
synth.frequency = 880.0 // UI slider updates automatically via @Observable
Opening a Control Window
LyrebirdWindow is a @MainActor class that wraps NSWindow + NSHostingController.
Create an instance, then call open { ... } with any SwiftUI content:
let window = LyrebirdWindow(title: "My Synth", width: 400, height: 300)
window.open {
VStack {
ParameterSlider("Amplitude", node: synth.$amplitude, range: 0...1)
ParameterSlider("Frequency", node: synth.$frequency, range: 20...20000)
ParameterButton("Free") { engine.rootGroup.remove(synth) }
}
.padding()
}
// Later
window.close()
open can be called again on the same instance to replace the content.
LyrebirdWindow API
// Init — no window is shown yet
LyrebirdWindow(title: String = "Lyrebird", width: CGFloat = 400, height: CGFloat = 300)
// Show (or replace) the window with SwiftUI content
func open<Content: View>(@ViewBuilder content: () -> Content)
// Close and release the window
func close()
Full SwiftUI is available inside the open closure — mix Lyrebird controls with any
standard SwiftUI views.
Built-in Controls
All controls accept a UIParamNode (the $paramName projected value).
Changes are bidirectional: UI → audio (atomic store) and code → UI (@Observable).
ParameterSlider
Continuous value control with an optional exponential taper.
ParameterSlider("Amplitude", node: synth.$amplitude, range: 0.0...1.0)
ParameterSlider("Cutoff", node: synth.$cutoff, range: 20.0...20000.0, taper: .exponential)
Taper options: .linear (default), .exponential — exponential maps equal visual
steps to equal ratios, useful for frequency and time parameters.
ParameterButton
Momentary action button or latching toggle.
// Momentary — runs action closure on press; no node binding
ParameterButton("Trigger") { synth.trigger() }
// Toggle — flips node between 0.0 (off) and 1.0 (on) on each press
ParameterButton("Mute", node: synth.$muted, style: .toggle)
The toggle button renders with an accent-colour highlight when the node value ≥ 0.5. Custom off/on values:
var btn = ParameterButton("Bypass", node: synth.$bypass, style: .toggle)
btn.offValue = 0.0
btn.onValue = 1.0
ParameterKnob
Rotary dial; drag vertically to change value. Equivalent in behaviour to ParameterSlider.
ParameterKnob("Resonance", node: synth.$resonance, range: 0...1)
ParameterXY
Two-dimensional control pad for simultaneous X/Y parameter control. X increases left-to-right; Y increases bottom-to-top.
ParameterXY(
xLabel: "Pan", xNode: synth.$pan, xRange: -1...1,
yLabel: "Amplitude", yNode: synth.$amplitude, yRange: 0...1
)
ParameterLabel
Read-only display that updates automatically via @Observable.
ParameterLabel("Level", node: synth.$amplitude)
ParameterLabel("Freq (Hz)", node: synth.$frequency, decimalPlaces: 1)
LyrebirdStatusView
Compact engine status display showing average and peak CPU load. Polls the engine at 10 Hz; embed anywhere in a SwiftUI hierarchy.
LyrebirdStatusView(engine: engine)
Renders two labeled rows — CPU Avg and CPU Peak — each with a color-coded bar
(green < 50 %, yellow 50–80 %, red > 80 %) and a numeric percentage. Values above 100 % mean
the engine is running over budget. Peak resets automatically every 5 s (matches the engine's
built-in timer); engine.resetPeakCPU() triggers an immediate manual reset.
Takes a direct SynthesisEngine reference — does not require a UIParamNode or @UIParam:
// Embed alongside synth controls in any view
VStack {
ParameterSlider("Frequency", node: synth.$frequency, range: 20...20000)
ParameterKnob("Amplitude", node: synth.$amplitude, range: 0...1)
Divider()
LyrebirdStatusView(engine: engine)
}
LyrebirdScopeView
Real-time dual-channel oscilloscope. Polls a ScopeCapture at ~30 Hz and renders
each channel's waveform using Canvas. Channels are stacked vertically: channel 0 (left bus)
in cyan, channel 1 (right bus) in orange. Each channel has a zero guide line and a hairline
separator between channels. Background is near-black.
// 1. Create and attach the capture tap before engine.start()
let scope = ScopeCapture(buses: [0, 1], bufferSize: 2048)
engine.scopeTap = scope
try engine.start()
// 2. Embed the view
LyrebirdScopeView(capture: scope)
.frame(height: 120)
The bufferSize determines how many samples are displayed per frame. At 44100 Hz / 512
blockSize, bufferSize: 2048 ≈ 46 ms of history (≈ 4 blocks per frame flip). Use a larger
bufferSize for more temporal context; smaller for a tighter, faster-updating trace.
LyrebirdScopeView takes only the ScopeCapture reference — no engine reference
needed in the view itself:
LyrebirdScopeView(capture: scopeCapture)
.frame(height: 120)
.frame(maxWidth: .infinity)
See Sources/LyrebirdUI/LyrebirdScopeView.swift and the engine-side tap documentation in
docs/engine/synthesis-engine.md.
Threading Model
UI gesture / code assignment (main thread)
→ synth.amplitude = 0.2
→ UIParamNode.update(0.2)
→ @Observable value = 0.2 (SwiftUI re-renders on next run loop)
→ Atomic<UInt64>.store(bitPattern, ordering: .releasing)
RT audio thread (render callback)
→ UIParamNode.calculatedSamples(graph:count:)
→ Atomic<UInt64>.load(ordering: .acquiring) (lock-free, no allocation)
→ linear ramp from previous value to new target
→ fills pre-allocated _result buffer in-place
Key invariant: the RT thread never accesses UIParamNode.value or the
@Observable registrar — it reads only _atomicBits. The main thread never touches
_result or _previousValue. These are disjoint fields; @unchecked Sendable is
correct and safe.
Module Structure
Sources/
├── Lyrebird/ # engine, protocols, generators — no SwiftUI/AppKit imports
│ └── ScopeCapture.swift double-buffer RT bus tap; @unchecked Sendable
└── LyrebirdUI/ # LyrebirdWindow, @UIParam, controls — depends on Lyrebird
├── UIParamNode.swift @Observable backing; ValidGeneratorInput; Atomic RT reads
├── UIParam.swift @propertyWrapper; wrappedValue + $projectedValue
├── LyrebirdWindow.swift @MainActor NSWindow + NSHostingController
├── LyrebirdStatusView.swift CPU avg/peak display; polls engine at 10 Hz
├── LyrebirdScopeView.swift dual-channel oscilloscope; Canvas; polls capture at 30 Hz
└── Controls/
├── ParameterSlider.swift
├── ParameterButton.swift
├── ParameterKnob.swift
├── ParameterXY.swift
└── ParameterLabel.swift
LyrebirdUI builds under Swift 6 language mode (Phase 202) — cleanly, with no
actor-isolation diagnostics. The earlier .swiftLanguageMode(.v5) pin was removed once
the core Synthesizer isolation surface landed (Phase 201); the SwiftUI/AppKit interop
needed no special handling.
Full Example
import AppKit
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
// Example — your synthesizer, defined by subclassing SynthesizerBase
// 1. Declare the synthesizer with @UIParam properties
final class DrumSynth: SynthesizerBase {
@UIParam var pitch: Double = 60.0
@UIParam var decay: Double = 0.3
@UIParam var amplitude: Double = 0.8
override func build() {
let osc = OscSin.Audio(freq: $pitch)
output(bus: 0, source: osc * $amplitude)
}
}
// 2. Track add/remove state in an @Observable controller
@Observable
final class DrumController {
private let engine: SynthesisEngine
let synth = DrumSynth()
private(set) var isPlaying = false
init(engine: SynthesisEngine) { self.engine = engine }
func toggle() {
if isPlaying {
engine.remove(synth)
} else {
do { try engine.add(synth) } catch { print("[Lyrebird] engine.add failed: \(error)") }
}
isPlaying.toggle()
}
}
// 3. Build the control view
struct DrumView: View {
let controller: DrumController
var body: some View {
VStack(spacing: 16) {
HStack {
Text("Drum Synth").font(.headline)
Spacer()
Button(controller.isPlaying ? "Stop" : "Start") { controller.toggle() }
.buttonStyle(.bordered)
.tint(controller.isPlaying ? .red : .green)
}
ParameterSlider("Pitch", node: controller.synth.$pitch, range: 30...90)
ParameterSlider("Decay", node: controller.synth.$decay, range: 0.05...2.0,
taper: .exponential)
ParameterKnob ("Amplitude", node: controller.synth.$amplitude, range: 0...1)
}
.padding()
}
}
// 4. Open the window
let controller = DrumController(engine: engine)
let window = LyrebirdWindow(title: "Drum", width: 360, height: 240)
window.open { DrumView(controller: controller) }