Files
ShoeGaze/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift
T
2026-06-22 21:07:13 -07:00

109 lines
4.8 KiB
Swift

// 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)
// The tapped bus indices depend on the channel layout (input buses follow the output
// buses), so rebuild the scope tap for the new configuration.
installScopeTap()
}
/// Default samples-per-frame captured by the scope tap.
public static let defaultScopeBufferSize: Int = 2_048
/// (Re)builds the ``scopeTap`` over the current hardware input + output buses and assigns it
/// to the engine, so the debug scope view can visualise both the live input signal and the
/// board output.
///
/// Lane order is **inputs first** (`In 0`, `In 1`, …) then **outputs** (`Out L`, `Out R`, …),
/// so the input waveform sits at the top of the scope. Must be called while the engine is
/// stopped — `SynthesisEngine` caches its scope tap at `start()`. Rebuilt automatically by
/// ``reconfigureEngine(sampleRate:inputChannels:outputChannels:)`` and at init.
///
/// - Parameter bufferSize: Samples per channel per display frame. Defaults to 2048.
public func installScopeTap(bufferSize: Int = ShoeGaze.defaultScopeBufferSize) {
let numOut: Int = engine.numOutputChannels
let numIn: Int = engine.numInputChannels
var buses: [Int] = []
for ch: Int in 0..<numIn { buses.append(numOut + ch) } // hardware inputs (top lanes)
for ch: Int in 0..<numOut { buses.append(ch) } // outputs (lower lanes)
guard !buses.isEmpty else {
engine.scopeTap = nil
scopeTap = nil
return
}
let capture: ScopeCapture = ScopeCapture(buses: buses, bufferSize: bufferSize)
engine.scopeTap = capture
scopeTap = capture
}
/// Human-readable label for a tapped audio-bus index under the current engine layout.
///
/// Output buses (`bus < numOutputChannels`) are `Out L` / `Out R` / `Out N`; the remaining
/// buses are hardware inputs `In 0`, `In 1`, … Used by the scope view to label each lane.
///
/// - Parameter bus: An audio-bus index, typically one of ``scopeTap``'s `buses`.
public func scopeLaneLabel(forBus bus: Int) -> String {
let numOut: Int = engine.numOutputChannels
guard bus >= numOut else {
let stereoNames: [String] = ["Out L", "Out R"]
return bus < stereoNames.count ? stereoNames[bus] : "Out \(bus)"
}
return "In \(bus - numOut)"
}
}