Files
Lyrebird/Sources/LyrebirdUILinuxDemo/main.swift
T
josh b6fdee8bfc Lyrebird 2.0.0 — Linux support
Consolidated release: the cross-platform Linux port (engine, generators, CLI,
REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable
WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux
live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive.
See RELEASES.md and LINUX_README.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-10 21:09:11 -07:00

321 lines
12 KiB
Swift

// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Runnable Linux GUI demo for LyrebirdUILinux. Build/run on a Linux host with
// libgtk-4-dev (and libasound2-dev for sound):
//
// LYREBIRD_ENABLE_LINUX_UI=1 swift run LyrebirdUILinuxDemo
//
// Note the import shape: only LyrebirdSynth (engine + @UIParam) and
// LyrebirdUILinux (View DSL + GTK4 backend, via @_exported re-exports). No
// direct SwiftOpenUI / BackendGTK4 imports needed here.
import LyrebirdSynth
import LyrebirdUI
import Foundation // ProcessInfo (demo-mode env var)
// MARK: - Audio engine
private let demoBlockSize: Int = 512
private let demoSampleRate: Double = 44_100.0
private let demoOutputChannels: Int = 2
private let demoInputChannels: Int = 0
// Core Audio on Apple, ALSA on a Linux build with libasound, else a silent
// OfflineDriver. The GUI runs either way; `isLiveAudioAvailable` reports which.
let demoDriver: any AudioDriver = makeDefaultAudioDriver()
let demoEngine: SynthesisEngine = SynthesisEngine(
blockSize: demoBlockSize,
sampleRate: demoSampleRate,
numOutputChannels: demoOutputChannels,
numInputChannels: demoInputChannels,
driver: demoDriver
)
// Oscilloscope tap on the stereo output buses. Must be set before start().
private let demoScopeBufferSize: Int = 2048
let demoScope: ScopeCapture = ScopeCapture(buses: [0, 1], bufferSize: demoScopeBufferSize)
demoEngine.scopeTap = demoScope
let demoSynth: KnobDemoSynth = KnobDemoSynth()
// Pointer-driven sine for the `mouse` mode (Mouse.X → freq, Mouse.Y → amp).
let mouseSynth: MouseDemoSynth = MouseDemoSynth()
// Which demo to run — read early so the `monitors` mode can launch with the
// engine OFF (its EngineStatus panel drives Start/Stop). Every other mode starts
// the engine and adds the synth now, since they have no transport control.
let demoMode: String = ProcessInfo.processInfo.environment["LYREBIRD_DEMO"] ?? "full"
let launchEngineRunning: Bool = (demoMode != "monitors")
// Install the GTK pointer bridge BEFORE `engine.start()` so the `Mouse.*.Control`
// generators see live values with proper happens-before visibility on the RT
// thread (see MouseInput.install docs). Harmless in non-mouse modes — it just
// registers the bridge; SwiftOpenUI only attaches the pointer controllers to the
// windows it opens, and no generator reads it unless a patch uses Mouse.*.
MouseTracker.installShared()
if launchEngineRunning {
do {
try demoEngine.start()
switch demoMode {
case "mouse":
try demoEngine.add(mouseSynth)
case "events":
break // the LyrebirdEventList schedules its own processes on Next.
default:
try demoEngine.add(demoSynth)
}
} catch {
print("[Lyrebird] demo engine setup failed: \(error)")
}
}
if !isLiveAudioAvailable {
print("[Lyrebird] no live audio backend — the knobs still work, but there is no sound.")
}
// `engine.stop()` tears down the node tree AND unbinds every non-persistent synth
// (see the stop() contract in docs/engine/synthesis-engine.md), so no manual
// teardown is needed — the synth just has to be re-added on the next Start. The
// EngineStatus panel's `onEngineStarted` runs this after a successful start.
// `add` is @MainActor; the Start action fires on the GTK main thread, so
// `assumeIsolated` is valid. `demoSynth` is Sendable (@MainActor class); the
// engine is not, so it is bound `nonisolated(unsafe)`.
nonisolated(unsafe) let addEngine: SynthesisEngine = demoEngine
nonisolated(unsafe) let reAddSynthOnStart: () -> Void = {
MainActor.assumeIsolated {
do {
try addEngine.add(demoSynth)
} catch {
print("[Lyrebird] re-add synth on start failed: \(error)")
}
}
}
// Extract the projected parameter nodes here, in main.swift's top-level
// `@MainActor` context: `SynthesizerBase` is `@MainActor`, so `demoSynth.$…` is
// only reachable on the main actor. The nodes themselves are not actor-isolated,
// so the (nonisolated) SwiftOpenUI view body can read them freely.
let frequencyNode: UIParamNode = demoSynth.$frequency
let amplitudeNode: UIParamNode = demoSynth.$amplitude
// SwiftOpenUI's scene closure is nonisolated and `SynthesisEngine` is not
// Sendable, so the main-actor top-level `demoEngine` can't be referenced inside
// it directly (unlike the Sendable nodes/scope/envelope). This demo runs entirely
// on the GTK main thread and the status view only reads `engine.averageCPU` /
// `peakCPU` (plain Double loads), so a nonisolated handle is safe here.
nonisolated(unsafe) let statusEngine: SynthesisEngine = demoEngine
// A static example envelope for the envelope plot (loop node 1, release node 2).
let demoEnvelope: Envelope = Envelope(
levels: [0.0, 1.0, 0.6, 0.0],
durations: [0.01, 0.3, 0.2],
curves: [.sine, .lin, .exponential],
loopNode: 1,
releaseNode: 2
)
// MARK: - "monitors" demo scaffolding
//
// Extra data sources for the diagnostics/monitor views ported to Linux. All are
// Sendable (`UIParamNode` / `LyrebirdBuffer` are `@unchecked Sendable`, `Entry`
// is `Sendable`, `[Double]` is Sendable) so they cross into SwiftOpenUI's
// nonisolated scene closure like the nodes above.
// Parameter entries with EXPLICIT ranges. `LyrebirdSynthView.discover` can't
// carry per-slot ranges on Linux (that metadata type is Apple-only), so it would
// default every knob to 0…1 — wrong for frequency (Hz). Build them by hand from
// the already-extracted nodes so the frequency knob spans a musical range.
let demoFreqRange: ClosedRange<Double> = 110.0...880.0
let demoAmpRange: ClosedRange<Double> = 0.0...1.0
let demoSynthEntries: [LyrebirdSynthView.Entry] = [
LyrebirdSynthView.Entry(
propertyName: "frequency", displayName: "frequency",
node: frequencyNode, range: demoFreqRange
),
LyrebirdSynthView.Entry(
propertyName: "amplitude", displayName: "amplitude",
node: amplitudeNode, range: demoAmpRange
),
]
// A per-bin buffer driven by the MultiSlider (a rising ramp to start).
private let demoMultiBinCount: Int = 48
let demoMultiBuffer: LyrebirdBuffer = {
let buf: LyrebirdBuffer = LyrebirdBuffer(count: demoMultiBinCount)
buf.fill { (i: Int, n: Int) in Double(i) / Double(n) }
return buf
}()
// A static scatter of one Gaussian-ish cloud for the scatter plot.
let demoScatterData: [Double] = (0..<160).map { (i: Int) in
let t: Double = Double(i) / 160.0
return 0.5 + 0.4 * sin(t * .pi * 6) * (1.0 - t)
}
// MARK: - "events" demo scaffolding
//
// A `LyrebirdEventList` of four one-shot events, each starting a sustaining
// `EventVoiceSynth` at a distinct pitch. `LyrebirdEventList` is `@unchecked
// Sendable`, so (like the nodes) it crosses into SwiftOpenUI's nonisolated scene
// closure. Built after `engine.start()` above.
let eventDemoPitches: [Double] = [220.0, 277.18, 329.63, 440.0] // A3, C#4, E4, A4
let eventDemoEnvelope: Envelope = Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.08, 0.6],
curves: [.lin, .lin],
releaseNode: 2
)
let eventDemoEvents: [LyrebirdEvent] = eventDemoPitches.enumerated().map { (index: Int, pitch: Double) in
let proc: LyrebirdProcess = LyrebirdProcess(
id: "voice-\(index)",
envelope: eventDemoEnvelope,
numChannels: 2,
body: { (ctx: LyrebirdProcessContext) in ctx.add(EventVoiceSynth(freq: pitch)) }
)
return LyrebirdEvent(starts: [proc])
}
let eventDemoList: LyrebirdEventList? = {
do {
return try LyrebirdEventList(
id: "events-demo",
events: eventDemoEvents,
engine: demoEngine,
bus: AudioBus(index: 0, channelCount: 2)
)
} catch {
print("[Lyrebird] events demo list build failed: \(error)")
return nil
}
}()
// Seed a few diagnostics messages so the message views/banner have content.
LyrebirdMessageCenter.shared.info("Linux UI demo started", source: "LyrebirdUILinuxDemo")
LyrebirdMessageCenter.shared.warning("This is an example warning", source: "demo")
LyrebirdMessageCenter.shared.error("This is an example error", source: "demo")
// MARK: - GTK4 app
//
// Diagnostic selector: set LYREBIRD_DEMO to isolate what breaks interaction.
// knob → a single knob (control in isolation)
// controls → all controls, no animated views (isolates the timer redraws)
// monitors → the ported diagnostics/monitor views (SynthView grid, Scatter,
// MultiSlider, EngineStatus incl. node-tree + messages)
// narrowtest → narrow-path isolation: Canvas slider + Text/TextField wrapped in the
// ex-poison modifiers, NO opaque widgets — label+field should track live
// mouse → pointer-source test: live Mouse.X/Y/Click readout over a
// pointer-driven sine (validates the Linux MouseTracker)
// events → process/event-list views on-display: LyrebirdEventListPerformanceView
// (EventListView transport + RunningProcesses/ProcessView strips) +
// presentInWindow buttons for each
// (unset) → the full demo
// Each mode is a distinct App/View with a FIXED body — no in-body @ViewBuilder
// conditional, which would itself change the rebuild plan under test.
struct KnobDemoApp: App {
var body: some Scene {
WindowGroup("Lyrebird Knob Demo") {
KnobDemoView(
frequencyNode: frequencyNode,
amplitudeNode: amplitudeNode,
scope: demoScope,
envelope: demoEnvelope,
engine: statusEngine
)
}
}
}
struct KnobOnlyDemoApp: App {
var body: some Scene {
WindowGroup("Lyrebird Knob Demo") {
DemoKnobOnlyView(frequencyNode: frequencyNode)
}
}
}
struct ControlsDemoApp: App {
var body: some Scene {
WindowGroup("Lyrebird Knob Demo") {
DemoControlsView(
frequencyNode: frequencyNode,
amplitudeNode: amplitudeNode
)
}
}
}
/// Showcase of the ported diagnostics / monitor views: the auto-generated
/// parameter grid, a scatter plot, a per-bin MultiSlider, and the engine status
/// panel (which itself embeds the node-tree and message sections).
struct MonitorsDemoApp: App {
var body: some Scene {
WindowGroup("Lyrebird Monitors Demo") {
DemoMonitorsView(
entries: demoSynthEntries,
scatter: demoScatterData,
multiBuffer: demoMultiBuffer,
multiCount: demoMultiBinCount,
engine: statusEngine,
onEngineStarted: reAddSynthOnStart
)
}
}
}
/// Narrow-path isolation test (no engine, no opaque widgets).
struct NarrowTestApp: App {
var body: some Scene {
WindowGroup("Lyrebird Narrow-Path Test") {
DemoNarrowTestView()
}
}
}
/// Pointer-source test: a live Mouse.X/Y/Click readout over a pointer-driven
/// sine. Validates the Linux `MouseTracker`.
struct MouseDemoApp: App {
var body: some Scene {
WindowGroup("Lyrebird Mouse Demo") {
DemoMouseView()
}
}
}
/// On-display exercise of the ported process/event-list views: the composite
/// `LyrebirdEventListPerformanceView` inline plus buttons to open each view in a
/// detached `LyrebirdWindow`.
struct EventsDemoApp: App {
var body: some Scene {
WindowGroup("Lyrebird Events Demo") {
if let list: LyrebirdEventList = eventDemoList {
DemoEventsView(eventList: list, engine: statusEngine)
} else {
Text("Events demo failed to build — see console.")
.padding()
}
}
}
}
switch demoMode {
case "knob":
GTK4Backend().run(KnobOnlyDemoApp.self)
case "narrowtest":
GTK4Backend().run(NarrowTestApp.self)
case "mouse":
GTK4Backend().run(MouseDemoApp.self)
case "events":
GTK4Backend().run(EventsDemoApp.self)
case "controls":
GTK4Backend().run(ControlsDemoApp.self)
case "monitors":
GTK4Backend().run(MonitorsDemoApp.self)
default:
GTK4Backend().run(KnobDemoApp.self)
}