commit current state

This commit is contained in:
2026-06-22 15:40:23 -07:00
parent e36dc3a527
commit c6f567535b
14 changed files with 431 additions and 101 deletions
@@ -0,0 +1,57 @@
// ShoeGaze+Engine.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
extension ShoeGaze {
/// Reconfigures the engine's sample rate and channel counts while preserving the rig.
///
/// The engine must be **stopped** (the underlying `SynthesisEngine` setters throw
/// `SynthesisEngineConfigError.engineIsRunning` otherwise). The current rig is captured,
/// the engine is reconfigured, and every board is rebuilt from the snapshot so that
/// sample-rate-dependent nodes — e.g. ``TestLoopSource``'s Karplus-Strong delay line, sized at
/// init from the engine rate — are recreated at the new rate. Reconstruction reuses the atomic
/// ``rebuildAllBoards(from:)`` (teardown-on-failure), so a failure leaves an empty rig rather
/// than a half-built one.
///
/// If the current `inputSource` is `.liveInput(channel:)` and `channel` is no longer valid
/// under `inputChannels`, the source is reset to `.testLoop` before rebuilding.
///
/// - Parameters:
/// - sampleRate: New engine sample rate in Hz.
/// - inputChannels: New hardware input-channel count (`>= 0`).
/// - outputChannels: New hardware output-channel count (`>= 1`).
/// - Throws: `SynthesisEngineConfigError.engineIsRunning` if the engine is running;
/// `SynthesisEngineConfigError.invalidValue` for out-of-range values; or any error from
/// board reconstruction.
public func reconfigureEngine(
sampleRate: Double,
inputChannels: Int,
outputChannels: Int
) throws {
guard !engine.isRunning else { throw SynthesisEngineConfigError.engineIsRunning }
let snapshot: ShoeGazeState = captureState()
// Tear the rig down BEFORE reconfiguring: changing the channel counts re-partitions the
// bus allocator's hardware reservation, which would invalidate (double-free) any rig buses
// still allocated under the old layout.
teardown()
try engine.setSampleRate(sampleRate)
try engine.setNumOutputChannels(outputChannels)
try engine.setNumInputChannels(inputChannels)
// A live-input source pointing at a channel that no longer exists would make the rebuild's
// addBoard() throw; fall back to the test loop.
if case .liveInput(let channel) = inputSource, channel >= inputChannels {
inputSource = .testLoop
}
try rebuildAllBoards(from: snapshot)
}
}
@@ -0,0 +1,174 @@
// EngineConfigView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdSynth
import LyrebirdShoeGaze
/// Engine configuration + transport: sample rate, input/output channel counts, and a Start/Stop
/// toggle, with a sample-rate-mismatch alert on start.
///
/// The config controls are editable only while the engine is stopped (the underlying
/// `SynthesisEngine` setters require it). Pressing Start applies the pending values via
/// `ShoeGaze.reconfigureEngine(...)` — which preserves the rig — then starts the engine. On macOS
/// a mismatch surfaces as a thrown `CoreAudioError.sampleRateMismatch` (the engine stays stopped);
/// on iOS the committed session rate is compared against the request after start. Either way an
/// alert reports the requested vs hardware rate; the user picks a matching rate.
///
/// - Parameters:
/// - shoeGaze: The session whose engine is configured and started/stopped.
/// - hardwareSampleRate: Returns the actual hardware/session rate, or `nil` if unknown. Supplied
/// by the host app (macOS: `CoreAudioDriver.deviceSampleRate`; iOS: `iOSAudioDriver.sessionSampleRate`).
public struct EngineConfigView: View {
// MARK: - Constants
/// Standard sample rates offered in the picker.
private static let standardRates: [Double] = [44_100, 48_000, 88_200, 96_000]
/// Channel-count stepper bounds.
private static let maxInputs: Int = 8
private static let maxOutputs: Int = 8
/// Sample-rate comparison tolerance in Hz.
private static let rateEpsilon: Double = 0.5
private static let rowSpacing: CGFloat = 12
private static let labelOpacity: Double = 0.65
// MARK: - Properties
private let shoeGaze: ShoeGaze
private let hardwareSampleRate: () -> Double?
private let applyConfig: ((Double, Int, Int) throws -> Void)?
private let onConfigApplied: () -> Void
@State private var pendingSampleRate: Double
@State private var pendingInputs: Int
@State private var pendingOutputs: Int
@State private var transportTick: Bool = false
@State private var showAlert: Bool = false
@State private var alertText: String = ""
// MARK: - Init
/// - Parameter applyConfig: Optional override for applying the chosen `(sampleRate, inputs,
/// outputs)` while stopped (e.g. a controller that rebuilds a non-board showcase). When `nil`,
/// `ShoeGaze.reconfigureEngine(...)` is used, which preserves the board rig.
/// - Parameter onConfigApplied: Called after the engine is (re)configured or started/stopped,
/// so a host can refresh views that read non-observable engine state (e.g. an input-channel
/// picker that lists `0..<engine.numInputChannels`).
public init(
shoeGaze: ShoeGaze,
hardwareSampleRate: @escaping () -> Double? = { nil },
applyConfig: ((Double, Int, Int) throws -> Void)? = nil,
onConfigApplied: @escaping () -> Void = { }
) {
self.shoeGaze = shoeGaze
self.hardwareSampleRate = hardwareSampleRate
self.applyConfig = applyConfig
self.onConfigApplied = onConfigApplied
_pendingSampleRate = State(initialValue: shoeGaze.engine.sampleRate)
_pendingInputs = State(initialValue: shoeGaze.engine.numInputChannels)
_pendingOutputs = State(initialValue: shoeGaze.engine.numOutputChannels)
}
// MARK: - Body
public var body: some View {
_ = transportTick
let isRunning: Bool = shoeGaze.engine.isRunning
return HStack(spacing: EngineConfigView.rowSpacing) {
label("Rate")
Picker("Rate", selection: $pendingSampleRate) {
ForEach(EngineConfigView.standardRates, id: \.self) { rate in
Text("\(Int(rate)) Hz").tag(rate)
}
}
.labelsHidden()
.pickerStyle(.menu)
.disabled(isRunning)
Stepper(value: $pendingInputs, in: 0...EngineConfigView.maxInputs) {
Text("In: \(pendingInputs)").foregroundStyle(Color.white)
}
.disabled(isRunning)
.fixedSize()
Stepper(value: $pendingOutputs, in: 1...EngineConfigView.maxOutputs) {
Text("Out: \(pendingOutputs)").foregroundStyle(Color.white)
}
.disabled(isRunning)
.fixedSize()
Button(isRunning ? "Stop" : "Start") {
if isRunning { stopEngine() } else { startEngine() }
}
.buttonStyle(.borderedProminent)
.tint(isRunning ? .red : .green)
}
.alert("Sample Rate Mismatch", isPresented: $showAlert) {
Button("OK", role: .cancel) { }
} message: {
Text(alertText)
}
}
private func label(_ text: String) -> some View {
Text(text)
.font(.subheadline)
.foregroundStyle(Color.white.opacity(EngineConfigView.labelOpacity))
}
// MARK: - Transport
private func startEngine() {
do {
if let applyConfig: (Double, Int, Int) throws -> Void = applyConfig {
try applyConfig(pendingSampleRate, pendingInputs, pendingOutputs)
} else {
try shoeGaze.reconfigureEngine(
sampleRate: pendingSampleRate,
inputChannels: pendingInputs,
outputChannels: pendingOutputs
)
}
try shoeGaze.engine.start()
} catch {
handleStartError(error)
transportTick.toggle()
onConfigApplied() // config may have applied even if start failed (e.g. rate mismatch)
return
}
// Started OK. On iOS the session may have committed a different rate than requested.
if let hardware: Double = hardwareSampleRate(),
abs(hardware - shoeGaze.engine.sampleRate) > EngineConfigView.rateEpsilon {
presentMismatch(requested: shoeGaze.engine.sampleRate, hardware: hardware)
}
transportTick.toggle()
onConfigApplied()
}
private func stopEngine() {
shoeGaze.engine.stop()
transportTick.toggle()
onConfigApplied()
}
private func handleStartError(_ error: Error) {
#if os(macOS)
if let coreAudio: CoreAudioError = error as? CoreAudioError,
case .sampleRateMismatch(let requested, let deviceRate) = coreAudio {
presentMismatch(requested: requested, hardware: deviceRate)
return
}
#endif
print("[EngineConfigView] engine start failed: \(error)")
}
private func presentMismatch(requested: Double, hardware: Double) {
alertText = "Requested \(Int(requested)) Hz, but the hardware is running at "
+ "\(Int(hardware)) Hz. Set the sample rate to \(Int(hardware)) Hz and start again."
showAlert = true
}
}
@@ -55,6 +55,7 @@ public struct ShoeGazeBuilderView: View {
// MARK: - Properties
private let shoeGaze: ShoeGaze
private let hardwareSampleRate: () -> Double?
/// Index of the board currently being edited.
@State private var selectedBoardIndex: Int = 0
@@ -75,10 +76,17 @@ public struct ShoeGazeBuilderView: View {
/// Creates a builder view.
///
/// - Parameter shoeGaze: The `ShoeGaze` manager whose boards and engine are edited. The
/// caller should create at least one board before presenting this view.
public init(shoeGaze: ShoeGaze) {
/// - Parameters:
/// - shoeGaze: The `ShoeGaze` manager whose boards and engine are edited. The caller should
/// create at least one board before presenting this view.
/// - hardwareSampleRate: Returns the actual hardware/session sample rate (or `nil`), used by
/// the engine-config Start to warn on a mismatch. Defaults to `nil`.
public init(
shoeGaze: ShoeGaze,
hardwareSampleRate: @escaping () -> Double? = { nil }
) {
self.shoeGaze = shoeGaze
self.hardwareSampleRate = hardwareSampleRate
}
// MARK: - Body
@@ -132,7 +140,6 @@ public struct ShoeGazeBuilderView: View {
private var transportRow: some View {
_ = transportTick
let isRunning: Bool = shoeGaze.engine.isRunning
return HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
Text("ShoeGaze Builder")
.font(.title2).bold()
@@ -150,18 +157,11 @@ public struct ShoeGazeBuilderView: View {
}
}
Spacer()
Button("Start") {
do { try shoeGaze.engine.start() }
catch { print("[ShoeGazeBuilderView] engine.start() failed: \(error)") }
transportTick.toggle()
}
.buttonStyle(.borderedProminent).tint(.green).disabled(isRunning)
Button("Stop") {
shoeGaze.engine.stop()
transportTick.toggle()
}
.buttonStyle(.bordered).tint(.red).disabled(!isRunning)
EngineConfigView(
shoeGaze: shoeGaze,
hardwareSampleRate: hardwareSampleRate,
onConfigApplied: { transportTick.toggle() }
)
}
}
@@ -174,7 +174,7 @@ public struct ShoeGazeBuilderView: View {
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity))
Picker("Input", selection: inputBinding) {
Text("Test Loop").tag(ShoeGazeBuilderView.testLoopTag)
ForEach(0..<shoeGaze.engine.numInputChannels, id: \.self) { channel in
ForEach(Array(0..<max(0, shoeGaze.engine.numInputChannels)), id: \.self) { channel in
Text("In \(channel)").tag(channel)
}
}
+11 -26
View File
@@ -68,6 +68,7 @@ public struct ShoeGazeView: View {
// MARK: - Properties
private let shoeGaze: ShoeGaze
private let hardwareSampleRate: () -> Double?
/// Bumped on each transport button press to force a re-read of the engine's
/// running state. The button labels/enabled-state read `shoeGaze.engine.isRunning`
@@ -87,11 +88,16 @@ public struct ShoeGazeView: View {
/// Creates a top-level ShoeGaze view.
///
/// - Parameter shoeGaze: The `ShoeGaze` manager whose boards and engine will
/// be displayed. The caller is responsible for engine lifecycle; this view
/// provides Start and Stop transport buttons as a convenience.
public init(shoeGaze: ShoeGaze) {
/// - Parameters:
/// - shoeGaze: The `ShoeGaze` manager whose boards and engine will be displayed.
/// - hardwareSampleRate: Returns the actual hardware/session sample rate (or `nil`), used by
/// the engine-config Start to warn on a mismatch. Defaults to `nil`.
public init(
shoeGaze: ShoeGaze,
hardwareSampleRate: @escaping () -> Double? = { nil }
) {
self.shoeGaze = shoeGaze
self.hardwareSampleRate = hardwareSampleRate
}
// MARK: - Body
@@ -153,7 +159,6 @@ public struct ShoeGazeView: View {
// Referencing `transportTick` makes a press (which toggles it) re-evaluate this
// view so `engine.isRunning` is re-read; toggling any @State invalidates the view.
_ = transportTick
let isRunning: Bool = shoeGaze.engine.isRunning
return HStack(spacing: ShoeGazeView.transportSpacing) {
Text("ShoeGaze")
.font(.title2)
@@ -166,27 +171,7 @@ public struct ShoeGazeView: View {
.buttonStyle(.bordered)
.tint(.orange)
Button("Start") {
do {
try shoeGaze.engine.start()
} catch {
// Surface start errors to the console; the UI remains in the
// non-running state so the user can retry.
print("[ShoeGazeView] engine.start() failed: \(error)")
}
transportTick.toggle()
}
.buttonStyle(.borderedProminent)
.tint(.green)
.disabled(isRunning)
Button("Stop") {
shoeGaze.engine.stop()
transportTick.toggle()
}
.buttonStyle(.bordered)
.tint(.red)
.disabled(!isRunning)
EngineConfigView(shoeGaze: shoeGaze, hardwareSampleRate: hardwareSampleRate)
}
}