Files
ShoeGaze/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift
T
josh 705b4ed534 iOS live input via permission-gated engine rebuild
Live input on iOS needs an input channel, but constructing the engine with one
up-front makes iOS prompt for the microphone at the first Start even in
test-loop mode. Instead the engine starts input-less (no prompt) and is rebuilt
on demand:

- ShoeGazeBuilderView gains an optional onEnableLiveInput hook. When the user
  picks live input but the engine has no input channel, the picker offers a
  "Live Input" option that calls the hook; the input binding routes there too.
  On macOS (engine already has an input channel) the hook is nil and live input
  is selected directly.
- The iOS app model implements the hook: request mic access, then on grant
  snapshot the rig (rigData), stop + teardown the engine, rebuild it with one
  input channel, restore the rig (loadRig), and select live input. The new
  ShoeGaze is published so the @Observable host view re-binds.
- Input persistence restores live on relaunch: a saved live choice with the mic
  already authorised triggers the same rebuild silently (no prompt).

Test: a rig captured on a 0-input engine restores onto a freshly built 1-input
engine and live input is then selectable.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 20:52:11 -07:00

185 lines
7.4 KiB
Swift

// ShoeGazeBuilderiOSAppModel.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AVFoundation
import Observation
import LyrebirdSynth
import LyrebirdShoeGaze
/// Observable model owning the `SynthesisEngine` and `ShoeGaze` session for the iOS builder.
///
/// `AVAudioSession` is activated at init so the hardware sample rate is known before the engine
/// is constructed (iOS devices typically lock to 48 000 Hz). The session is seeded with one board
/// holding a single pedal so the builder opens with an audible starting point; the user adds /
/// removes / reorders pedals from the palette. Input defaults to `.testLoop`, so no microphone
/// permission is required to start.
@Observable
@MainActor
final class ShoeGazeBuilderiOSAppModel {
// MARK: - Engine configuration constants
private static let blockSize: Int = 512
private static let outputChannels: Int = 2
// Kept at 0: with input channels the iOS driver switches the session to `.playAndRecord`
// and enables the RemoteIO input element, which makes iOS prompt for microphone access at
// engine start even in test-loop mode. iOS live input needs a permission-gated engine
// rebuild (request mic → reconstruct the engine with an input channel) before it can be
// enabled here without that surprise prompt.
private static let numAudioBuses: Int = 256
private static let seedPedalType: String = "Overdrive"
/// UserDefaults key persisting the input selection. Must match the key written by the
/// builder view (`ShoeGazeBuilderView.inputSelectionDefaultsKey`).
private static let inputSelectionDefaultsKey: String = "ShoeGaze.inputSelection"
/// Persisted value meaning "live input, channel 0".
private static let liveInputChannelZeroTag: Int = 0
// MARK: - Owned objects
/// The active ShoeGaze builder session. Swapped out when live input is enabled (the engine
/// is rebuilt with an input channel); the `@Observable` change re-binds the hosting view.
private(set) var shoeGaze: ShoeGaze
private var engine: SynthesisEngine
private var iosDriver: iOSAudioDriver
/// The sample rate the audio session actually committed to (for the config mismatch warning).
var hardwareSampleRate: Double? { iosDriver.sessionSampleRate }
// MARK: - Init
init() {
ShoeGazeBuilderiOSAppModel.configureAudioSession()
let built: (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) =
ShoeGazeBuilderiOSAppModel.buildEngine(inputChannels: 0)
self.engine = built.engine
self.iosDriver = built.driver
self.shoeGaze = built.shoeGaze
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
try shoeGaze.appendPedal(type: ShoeGazeBuilderiOSAppModel.seedPedalType, to: board)
} catch {
print("[ShoeGazeBuilderiOS] seed board failed: \(error)")
}
}
// MARK: - Audio session / engine construction
/// Activates the play-and-record audio session once. Idempotent; safe to call before each
/// engine build. Activating the session does not by itself prompt for microphone access —
/// the prompt only fires when an input-enabled engine first starts.
private static func configureAudioSession() {
let session: AVAudioSession = AVAudioSession.sharedInstance()
do {
try session.setCategory(.playAndRecord,
mode: .default,
options: [.defaultToSpeaker, .allowBluetoothHFP])
try session.setActive(true)
} catch {
print("[ShoeGazeBuilderiOS] AVAudioSession setup failed: \(error)")
}
}
/// Builds a fresh engine + driver + empty `ShoeGaze` with the given input-channel count.
private static func buildEngine(
inputChannels: Int
) -> (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) {
let sampleRate: Double = AVAudioSession.sharedInstance().sampleRate
let driver: iOSAudioDriver = iOSAudioDriver()
let engine: SynthesisEngine = SynthesisEngine(
blockSize: ShoeGazeBuilderiOSAppModel.blockSize,
sampleRate: sampleRate,
numOutputChannels: ShoeGazeBuilderiOSAppModel.outputChannels,
numInputChannels: inputChannels,
numAudioBuses: ShoeGazeBuilderiOSAppModel.numAudioBuses,
driver: driver
)
return (engine, driver, ShoeGaze(engine: engine))
}
// MARK: - Live input
/// Enables live input on iOS: requests microphone access, then (on grant) rebuilds the
/// engine with one input channel — preserving the current rig — and selects live input.
///
/// The rebuild is required because the input-channel count is fixed at engine construction,
/// and constructing with an input channel up-front would make iOS prompt for the microphone
/// at the first Start even in test-loop mode. Gating the rebuild behind an explicit request
/// keeps the prompt where the user expects it.
func enableLiveInput() {
MicrophonePermission.request { [weak self] granted in
guard let self, granted else { return }
self.rebuildWithLiveInput()
}
}
/// Snapshots the rig, rebuilds the engine with one input channel, restores the rig, and
/// selects live input on channel 0. No-op if the engine already has an input channel.
private func rebuildWithLiveInput() {
guard engine.numInputChannels == 0 else {
try? shoeGaze.setInputSource(.liveInput(channel: 0))
return
}
let wasRunning: Bool = engine.isRunning
let snapshot: Data? = try? shoeGaze.rigData()
engine.stop()
shoeGaze.teardown()
ShoeGazeBuilderiOSAppModel.configureAudioSession()
let rebuilt: (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) =
ShoeGazeBuilderiOSAppModel.buildEngine(inputChannels: 1)
self.engine = rebuilt.engine
self.iosDriver = rebuilt.driver
self.shoeGaze = rebuilt.shoeGaze
if let snapshot {
do {
try shoeGaze.loadRig(from: snapshot)
} catch {
print("[ShoeGazeBuilderiOS] rig restore after rebuild failed: \(error)")
seedFallbackBoard()
}
} else {
seedFallbackBoard()
}
do {
try shoeGaze.setInputSource(.liveInput(channel: 0))
UserDefaults.standard.set(
ShoeGazeBuilderiOSAppModel.liveInputChannelZeroTag,
forKey: ShoeGazeBuilderiOSAppModel.inputSelectionDefaultsKey
)
} catch {
print("[ShoeGazeBuilderiOS] selecting live input failed: \(error)")
}
if wasRunning { try? engine.start() }
}
/// Seeds a single default board so the rig is never empty after a failed restore.
private func seedFallbackBoard() {
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
try shoeGaze.appendPedal(type: ShoeGazeBuilderiOSAppModel.seedPedalType, to: board)
} catch {
print("[ShoeGazeBuilderiOS] fallback seed board failed: \(error)")
}
}
// MARK: - Transport
/// Stops the audio engine. Call from `.onDisappear`.
func stop() {
engine.stop()
}
}