Files
ShoeGaze/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift
T
josh 46e075fb8c Add live-input mic permission, audio-input entitlement, and engine-config review fixes
Live input was silent on macOS because the apps ran under hardened runtime
without the microphone entitlement, so AUHAL input received silent zeros and
the OS never prompted. Fixes:

- Add com.apple.security.device.audio-input entitlement to the macOS Builder
  and Demo apps (CODE_SIGN_ENTITLEMENTS wired in both targets).
- Add MicrophonePermission helper (AVCaptureDevice.requestAccess) and gate
  live-input selection through it in the Builder view and Demo controller;
  deny falls back to the test loop with an explanatory alert.
- Fix ShoeGazeDemo inputChannels 6 -> 1 (built-in mics are mono; 6 made
  CoreAudio deliver silence).

Engine-config review fixes:
- installScopeTap now requires the engine stopped (precondition) and
  reconfigureEngine reinstalls the tap on every exit path via defer, so
  engine.scopeTap never points at a stale channel layout.
- EngineConfigView stops the engine on a post-start (iOS) sample-rate
  mismatch instead of running pitch-shifted, and surfaces non-mismatch
  start errors through the alert.
- Remove redundant installScopeTap call in the demo controller (ShoeGaze.init
  already installs it).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 09:36:35 -07:00

114 lines
5.3 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 }
// 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)
}
/// 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..<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)"
}
}