Files
Lyrebird/Sources/LyrebirdUI/LyrebirdUI.docc/GUISystem.md
T
josh 560724d116 v1.3.0 release: graceful-release fix, quickstart template + demo, documentation accuracy pass
- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated
  synths were hard-freed instead of released).
- New: quickstart project template + LyrebirdQuickstartDemo.
- Docs: every example typechecked or provably illustrative (426->542); ~20
  wrong-API examples fixed; root docs brought under the compile guard.
- Fixed: NRT/Score demo Package.swift build from terminal again.

See RELEASES.md for details.
2026-07-17 14:05:01 -07:00

8.9 KiB
Raw Blame History

GUI System

@Metadata { @PageKind(article) }

Native macOS SwiftUI controls that bind directly to SynthesizerBase parameters.

Core Concept: @UIParam

A struct property wrapper that is simultaneously:

  1. A ValidGeneratorInput (via its projected UIParamNode) — wire $paramName directly into the audio graph in build().
  2. An @Observable value — SwiftUI views bind to the node and redraw automatically when the value changes.
  3. 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

class MySynth: SynthesizerBase {
    @UIParam var amplitude: Double = 0.5
    @UIParam var frequency: Double = 440.0
    @UIParam var pan:       Double = 0.0

    override func build() {
        let osc = OscSin.Audio(freq: $frequency)
        output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
    }
}

Projected Value

$paramName returns a UIParamNode — an @Observable class that conforms to ValidGeneratorInput. Pass it to UI controls:

ParameterSlider("Freq", node: synth.$frequency, range: 20...20000)
ParameterKnob("Pan",    node: synth.$pan,        range: -1...1)

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
synth.pan       = -0.5  // move left

By-name updates (OSC / MIDI / REPL)

@UIParam properties are auto-registered by SynthesizerBase under their property name (with the leading _ of property-wrapper backing storage stripped). Both typed direct writes and by-name updates target the same atomic:

synth.frequency = 880.0                                   // typed direct write
try? synth.updateParameter("frequency", value: 880.0)     // by-name (e.g. from OSC)

No declareParameter call is needed.

Opening a Control Window

LyrebirdWindow is a @MainActor class that wraps NSWindow + NSHostingController.

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("Stop") { engine.remove(synth) }
    }
    .padding()
}

// Later
window.close()

open can be called again on the same instance to replace the content. Full SwiftUI is available inside the closure — mix Lyrebird controls with any standard SwiftUI views.

LyrebirdWindow API

LyrebirdWindow(title: String = "Lyrebird", width: CGFloat = 400, height: CGFloat = 300)
func open<Content: View>(@ViewBuilder content: () -> Content)
func close()

Built-In Controls

All controls accept a UIParamNode (the $paramName projected value). Changes are bidirectional: UI → audio (atomic store) and code → UI (@Observable).

ParameterSlider

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, suited to frequency and time parameters.

ParameterButton

// Momentary — runs closure on press
ParameterButton("Trigger") { synth.trigger() }

// Toggle — flips node between 0.0 and 1.0 on each press
ParameterButton("Mute", node: synth.$muted, style: .toggle)

The toggle renders with an accent-colour highlight when the node value ≥ 0.5.

ParameterKnob

Rotary dial; drag vertically to change value. Equivalent in behaviour to ParameterSlider.

ParameterKnob("Resonance", node: synth.$resonance, range: 0...1)
ParameterKnob("Pan",       node: synth.$pan,        range: -1...1)

ParameterXY

Two-dimensional control pad for simultaneous X/Y parameter control.

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)

Engine Monitoring

LyrebirdStatusView

Compact CPU load display. Polls SynthesisEngine.averageCPU and peakCPU at 10 Hz. Renders two color-coded bar rows (green < 50 %, yellow 50–80 %, red ≥ 80 %).

LyrebirdStatusView(engine: engine)

Takes a direct SynthesisEngine reference — no @UIParam needed. Peak resets automatically every 5 s; call engine.resetPeakCPU() for an immediate manual reset.

LyrebirdScopeView

Real-time dual-channel oscilloscope. Requires a ScopeCapture tap wired to the engine before start().

// 1. Create and attach the capture tap
let scope = ScopeCapture(buses: [0, 1], bufferSize: 2048)
engine.scopeTap = scope           // must be set before engine.start()
try engine.start()

// 2. Embed the view
LyrebirdScopeView(capture: scope)
    .frame(height: 120)

Channels are stacked vertically: channel 0 (left, bus 0) in cyan, channel 1 (right, bus 1) in orange. Each channel has a zero-line guide. Polls at ~30 Hz via .task.

bufferSize sets how many samples are displayed per frame. At 44100 Hz / 512 blockSize, bufferSize: 2048 shows ~46 ms of history. bufferSize must be ≥ engine.blockSize.

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
  → ScopeCapture.write(audioBuses:count:)   [if scopeTap set]
    → assign(from:) via UnsafeMutableBufferPointer — no allocation, no ARC

Main thread (30 Hz poll)
  → ScopeCapture.snapshot()
    → deep copy via withUnsafeBufferPointer { Array($0) }
    → allocates on main thread only

The RT thread never accesses UIParamNode.value or the @Observable registrar — it reads only the atomic bit pattern. The main thread never touches _result or _previousValue. These are disjoint fields; @unchecked Sendable is correct and safe.

Full Example

import AppKit
import SwiftUI
import LyrebirdSynth
import LyrebirdUI

final class SineTone: SynthesizerBase {
    @UIParam var frequency: Double = 440.0
    @UIParam var amplitude: Double = 0.25
    @UIParam var pan:       Double = 0.0

    override func build() {
        let osc = OscSin.Audio(freq: $frequency)
        output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
    }
}

@Observable
final class SineController {
    let engine: SynthesisEngine
    let synth = SineTone()
    let scope: ScopeCapture
    private(set) var isPlaying = false

    init(engine: SynthesisEngine) {
        self.engine = engine
        self.scope = ScopeCapture(buses: [0, 1], bufferSize: 2048)
        engine.scopeTap = scope
    }

    func toggle() {
        if isPlaying {
            engine.remove(synth)
        } else {
            // engine.add is throwing; toggle() is not, so handle the error here.
            do { try engine.add(synth) } catch { print("[Lyrebird] engine.add failed: \(error)") }
        }
        isPlaying.toggle()
    }
}

struct SineView: View {
    let controller: SineController

    var body: some View {
        VStack(spacing: 20) {
            HStack {
                Text("Sine Tone").font(.headline)
                Spacer()
                Button(controller.isPlaying ? "Stop" : "Start") { controller.toggle() }
                    .buttonStyle(.bordered)
                    .tint(controller.isPlaying ? .red : .green)
            }
            ParameterSlider("Frequency", node: controller.synth.$frequency, range: 440...880)
            HStack(spacing: 24) {
                ParameterKnob("Amplitude", node: controller.synth.$amplitude, range: 0...1)
                ParameterKnob("Pan",       node: controller.synth.$pan,       range: -1...1)
            }
            Divider()
            LyrebirdStatusView(engine: controller.engine)
            Divider()
            LyrebirdScopeView(capture: controller.scope)
                .frame(height: 120)
        }
        .padding()
    }
}

// AppDelegate setup
let scope = ScopeCapture(buses: [0, 1], bufferSize: 2048)
engine.scopeTap = scope
try engine.start()

let controller = SineController(engine: engine)
let window = LyrebirdWindow(title: "Sine Tone", width: 360, height: 480)
window.open { SineView(controller: controller) }