e36074e9d3
Two blocking findings from external review: 1. UIParamNode itself ramps from previousOutputValue (seeded at the compile-time default, advanced only by RT render — update() doesn't touch it) to the target over the first block. So a node told to start muted still ramped full-gain→0 across block 0; the earlier "hard gate" only moved the leak from Lag to the param's own ramp. The mutedInputRendersSilent test passed by accident (the test-loop tone is quiet in that first block). Fix: prime previousOutputValue to the target. Race-free before a node is spliced into the graph (addBoard) and safe on a spliced node while the engine is stopped; a running engine keeps the ramp as a click-free live toggle. New setInputMuteGain(_:muted:seedRamp:) / primeInputMute helpers; setInputMuted seeds only when engine.isRunning == false. 2. EngineConfigView.startEngine called setInputMuted(true) AFTER engine.start(), so the engine came up unmuted for the first blocks. Moved it before start() (engine stopped there, so the gain is seeded with no ramp). Also: correct the setInputMuted doc (abrupt kill-switch, not "smoothed"). Regression test stoppedMutePrimesNodesSoTheresNoStartRamp asserts the ramp start equals the target (no pending ramp) after a stopped mute and for a board added while muted. 464 tests pass; both app targets build. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
253 lines
11 KiB
Swift
253 lines
11 KiB
Swift
// 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
|
||
/// When `true`, renders only the Start/Stop transport button (the sample-rate / channel-count
|
||
/// controls are hidden). Used by the compact (iPhone / narrow iPad) layout, which keeps the
|
||
/// transport on screen and moves the config controls into a Settings sheet.
|
||
private let transportOnly: Bool
|
||
|
||
@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 alertTitle: String = ""
|
||
@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 = { },
|
||
transportOnly: Bool = false
|
||
) {
|
||
self.shoeGaze = shoeGaze
|
||
self.hardwareSampleRate = hardwareSampleRate
|
||
self.applyConfig = applyConfig
|
||
self.onConfigApplied = onConfigApplied
|
||
self.transportOnly = transportOnly
|
||
_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
|
||
return Group {
|
||
if transportOnly {
|
||
transportButton
|
||
} else {
|
||
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(shoeGaze.engine.isRunning)
|
||
|
||
Stepper(value: $pendingInputs, in: 0...EngineConfigView.maxInputs) {
|
||
Text("In: \(pendingInputs)").foregroundStyle(Color.white)
|
||
}
|
||
.disabled(shoeGaze.engine.isRunning)
|
||
.fixedSize()
|
||
|
||
Stepper(value: $pendingOutputs, in: 1...EngineConfigView.maxOutputs) {
|
||
Text("Out: \(pendingOutputs)").foregroundStyle(Color.white)
|
||
}
|
||
.disabled(shoeGaze.engine.isRunning)
|
||
.fixedSize()
|
||
|
||
transportButton
|
||
}
|
||
}
|
||
}
|
||
.alert(alertTitle, isPresented: $showAlert) {
|
||
Button("OK", role: .cancel) { }
|
||
} message: {
|
||
Text(alertText)
|
||
}
|
||
// Resync the pending fields whenever the engine is rebuilt out from under this view (e.g.
|
||
// the iOS live-input rebuild swaps in a new engine with a different input-channel count).
|
||
// Keyed on the engine's object identity so it re-runs on every swap; the @State initial
|
||
// values are seeded only once, so without this the stepper would keep showing the old
|
||
// engine's channel counts even though audio reads the new one.
|
||
.task(id: ObjectIdentifier(shoeGaze.engine)) {
|
||
pendingSampleRate = shoeGaze.engine.sampleRate
|
||
pendingInputs = shoeGaze.engine.numInputChannels
|
||
pendingOutputs = shoeGaze.engine.numOutputChannels
|
||
}
|
||
// Apply config edits to the (stopped) engine immediately so dependent UI — notably the
|
||
// input-source picker, which lists `0..<engine.numInputChannels` — reflects the new channel
|
||
// counts before Start. While running, the controls are disabled, so these never fire then.
|
||
.onChange(of: pendingInputs) { applyConfigWhileStopped() }
|
||
.onChange(of: pendingOutputs) { applyConfigWhileStopped() }
|
||
.onChange(of: pendingSampleRate) { applyConfigWhileStopped() }
|
||
}
|
||
|
||
/// The Start / Stop transport button, shared by the full and transport-only layouts.
|
||
private var transportButton: some View {
|
||
let isRunning: Bool = shoeGaze.engine.isRunning
|
||
return Button(isRunning ? "Stop" : "Start") {
|
||
if isRunning { stopEngine() } else { startEngine() }
|
||
}
|
||
.buttonStyle(.borderedProminent)
|
||
.tint(isRunning ? .red : .green)
|
||
}
|
||
|
||
/// Reconfigures the stopped engine with the pending values and notifies the host so views that
|
||
/// read non-observable engine state refresh. No-op while the engine is running.
|
||
private func applyConfigWhileStopped() {
|
||
guard !shoeGaze.engine.isRunning else { return }
|
||
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
|
||
)
|
||
}
|
||
onConfigApplied()
|
||
} catch {
|
||
print("[EngineConfigView] live reconfigure failed: \(error)")
|
||
}
|
||
}
|
||
|
||
private func label(_ text: String) -> some View {
|
||
Text(text)
|
||
.font(.subheadline)
|
||
.foregroundStyle(Color.white.opacity(EngineConfigView.labelOpacity))
|
||
}
|
||
|
||
// MARK: - Transport
|
||
|
||
private func startEngine() {
|
||
do {
|
||
// Transport-only mode does not own the config controls — the engine is already
|
||
// configured (via the full instance's live apply, or the init defaults). Re-applying
|
||
// this instance's cached pending state here would revert edits made in the Settings
|
||
// sheet, so skip the reconfigure and just start.
|
||
if !transportOnly {
|
||
if let applyConfig: (Double, Int, Int) throws -> Void = applyConfig {
|
||
try applyConfig(pendingSampleRate, pendingInputs, pendingOutputs)
|
||
} else {
|
||
try shoeGaze.reconfigureEngine(
|
||
sampleRate: pendingSampleRate,
|
||
inputChannels: pendingInputs,
|
||
outputChannels: pendingOutputs
|
||
)
|
||
}
|
||
}
|
||
// A deliberate user Start comes up with the input muted so accidental noise can't leak
|
||
// the instant the engine spins up. Set it BEFORE start (engine is stopped here, so the
|
||
// gain is seeded with no ramp) — asserting it after start would leave the first render
|
||
// blocks unmuted. Transient stop/start-around-rebuild paths call `engine.start()`
|
||
// directly and are unaffected — they preserve the current mute state.
|
||
shoeGaze.setInputMuted(true)
|
||
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 — and
|
||
// `setSampleRate` only stores the logical rate, so leaving the engine running would play
|
||
// pitch-/time-shifted audio. Stop it (mirroring the macOS thrown-mismatch path) and alert.
|
||
if let hardware: Double = hardwareSampleRate(),
|
||
abs(hardware - shoeGaze.engine.sampleRate) > EngineConfigView.rateEpsilon {
|
||
shoeGaze.engine.stop()
|
||
presentMismatch(requested: shoeGaze.engine.sampleRate, hardware: hardware)
|
||
transportTick.toggle()
|
||
onConfigApplied()
|
||
return
|
||
}
|
||
transportTick.toggle()
|
||
onConfigApplied()
|
||
}
|
||
|
||
private func stopEngine() {
|
||
shoeGaze.stopEngine()
|
||
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
|
||
// Any other failure (invalid value, board reconstruction, driver setup) still needs to be
|
||
// surfaced — otherwise Start appears to do nothing.
|
||
alertTitle = "Couldn’t Start Engine"
|
||
alertText = "The engine could not start with the chosen configuration: "
|
||
+ "\(error.localizedDescription)"
|
||
showAlert = true
|
||
}
|
||
|
||
private func presentMismatch(requested: Double, hardware: Double) {
|
||
alertTitle = "Sample Rate Mismatch"
|
||
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
|
||
}
|
||
}
|