// 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 } // The tapped bus indices depend on the channel layout (input buses follow the output // buses), so the scope tap must be rebuilt for the final configuration — on every exit // path, including a thrown rebuild, so `engine.scopeTap` never points at a stale layout. defer { installScopeTap() } 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) } /// Applies a rig snapshot's saved hardware channel layout (``ShoeGazeState/numInputChannels`` / /// ``ShoeGazeState/numOutputChannels``) to the engine — a **deliberate opt-in**. /// /// ``loadRig(from:)`` persists a rig's I/O but does not auto-apply it: forcing the engine's /// channel layout on every load would override the user's global engine config and clobber the /// enable-live-input flow. Call this explicitly (e.g. from the engine-config UI, or a "match rig /// I/O" action) when you do want the rig's saved layout. Reuses ``reconfigureEngine(...)`` — so /// it captures the current rig and rebuilds every board at the new layout. /// /// A no-op (returns `false`) when the snapshot carries no saved counts or they already match. /// /// - Parameter state: The rig snapshot whose channel layout should be applied. /// - Returns: `true` if the engine was reconfigured, `false` if nothing needed to change. /// - Throws: `SynthesisEngineConfigError.engineIsRunning` if the engine is running, or any error /// from ``reconfigureEngine(sampleRate:inputChannels:outputChannels:)``. @discardableResult public func applyChannelLayout(from state: ShoeGazeState) throws -> Bool { guard !engine.isRunning else { throw SynthesisEngineConfigError.engineIsRunning } guard let inCount: Int = state.numInputChannels, let outCount: Int = state.numOutputChannels else { return false } guard inCount != engine.numInputChannels || outCount != engine.numOutputChannels else { return false } try reconfigureEngine( sampleRate: engine.sampleRate, inputChannels: inCount, outputChannels: outCount ) return true } /// 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) { // `SynthesisEngine` caches its scope tap as `_rtScopeTap` at `start()`; assigning a new tap // while running would silently diverge the RT thread's cached tap from `engine.scopeTap`. precondition(!engine.isRunning, "installScopeTap must be called while the engine is stopped") let numOut: Int = engine.numOutputChannels let numIn: Int = engine.numInputChannels var buses: [Int] = [] for ch: Int in 0.. 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)" } }