From 46e075fb8ce3ad5e3d677f55ae4fe0139e32477f Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Tue, 23 Jun 2026 09:36:35 -0700 Subject: [PATCH] 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 --- .../ShoeGazeBuilder.xcodeproj/project.pbxproj | 12 +++-- .../ShoeGazeBuilder.entitlements | 8 +++ Demo/ShoeGazeDemo.xcodeproj/project.pbxproj | 2 + Demo/ShoeGazeDemo/AppDelegate.swift | 2 +- Demo/ShoeGazeDemo/DemoRootView.swift | 12 +++++ Demo/ShoeGazeDemo/ShoeGazeDemo.entitlements | 8 +++ .../ShoeGazeDemo/ShoeGazeDemoController.swift | 24 ++++++++- .../Input/MicrophonePermission.swift | 52 +++++++++++++++++++ .../Presets/ShoeGaze+Engine.swift | 13 +++-- .../LyrebirdShoeGazeUI/EngineConfigView.swift | 16 ++++-- .../ShoeGazeBuilderView.swift | 25 +++++++++ 11 files changed, 160 insertions(+), 14 deletions(-) create mode 100644 Demo/ShoeGazeBuilder/ShoeGazeBuilder.entitlements create mode 100644 Demo/ShoeGazeDemo/ShoeGazeDemo.entitlements create mode 100644 Sources/LyrebirdShoeGaze/Input/MicrophonePermission.swift diff --git a/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj b/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj index 8317f7b..5c5f231 100644 --- a/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj +++ b/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj @@ -7,12 +7,12 @@ objects = { /* Begin PBXBuildFile section */ - C3B1000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B100000000000000000007 /* main.swift */; }; - C3B1000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B100000000000000000008 /* AppDelegate.swift */; }; C3B100000000000000000020 /* LyrebirdShoeGaze in Frameworks */ = {isa = PBXBuildFile; productRef = C3B10000000000000000001E /* LyrebirdShoeGaze */; }; C3B100000000000000000021 /* LyrebirdShoeGazeUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3B10000000000000000001F /* LyrebirdShoeGazeUI */; }; C3B100000000000000000022 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C3B100000000000000000023 /* Lyrebird */; }; C3B100000000000000000024 /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3B100000000000000000025 /* LyrebirdUI */; }; + C3B1000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B100000000000000000007 /* main.swift */; }; + C3B1000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B100000000000000000008 /* AppDelegate.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -152,14 +152,16 @@ C3B100000000000000000016 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { - CODE_SIGN_STYLE = Automatic; CODE_SIGNING_REQUIRED = NO; + CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilder/ShoeGazeBuilder.entitlements; + CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; DEVELOPMENT_TEAM = ""; ENABLE_HARDENED_RUNTIME = YES; INFOPLIST_FILE = ShoeGazeBuilder/Info.plist; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", @@ -175,13 +177,15 @@ C3B100000000000000000017 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - CODE_SIGN_STYLE = Automatic; CODE_SIGNING_REQUIRED = NO; + CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilder/ShoeGazeBuilder.entitlements; + CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = ""; ENABLE_HARDENED_RUNTIME = YES; INFOPLIST_FILE = ShoeGazeBuilder/Info.plist; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", diff --git a/Demo/ShoeGazeBuilder/ShoeGazeBuilder.entitlements b/Demo/ShoeGazeBuilder/ShoeGazeBuilder.entitlements new file mode 100644 index 0000000..b572d9c --- /dev/null +++ b/Demo/ShoeGazeBuilder/ShoeGazeBuilder.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.device.audio-input + + + diff --git a/Demo/ShoeGazeDemo.xcodeproj/project.pbxproj b/Demo/ShoeGazeDemo.xcodeproj/project.pbxproj index 0e6a0f9..b5f254b 100644 --- a/Demo/ShoeGazeDemo.xcodeproj/project.pbxproj +++ b/Demo/ShoeGazeDemo.xcodeproj/project.pbxproj @@ -160,6 +160,7 @@ C3B000000000000000000016 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + CODE_SIGN_ENTITLEMENTS = ShoeGazeDemo/ShoeGazeDemo.entitlements; CODE_SIGN_STYLE = Automatic; CODE_SIGNING_REQUIRED = NO; COMBINE_HIDPI_IMAGES = YES; @@ -183,6 +184,7 @@ C3B000000000000000000017 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + CODE_SIGN_ENTITLEMENTS = ShoeGazeDemo/ShoeGazeDemo.entitlements; CODE_SIGN_STYLE = Automatic; CODE_SIGNING_REQUIRED = NO; COMBINE_HIDPI_IMAGES = YES; diff --git a/Demo/ShoeGazeDemo/AppDelegate.swift b/Demo/ShoeGazeDemo/AppDelegate.swift index aa96e26..ab08347 100644 --- a/Demo/ShoeGazeDemo/AppDelegate.swift +++ b/Demo/ShoeGazeDemo/AppDelegate.swift @@ -29,7 +29,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private static let outputChannels: Int = 2 // Built-in mics are mono; default to one input channel so live input works out of the box // (CoreAudio can't satisfy more input channels than the device provides). Raise in the UI. - private static let inputChannels: Int = 6 + private static let inputChannels: Int = 1 private static let numAudioBuses: Int = 256 // MARK: - Window geometry constants diff --git a/Demo/ShoeGazeDemo/DemoRootView.swift b/Demo/ShoeGazeDemo/DemoRootView.swift index 765d86f..0a06f6e 100644 --- a/Demo/ShoeGazeDemo/DemoRootView.swift +++ b/Demo/ShoeGazeDemo/DemoRootView.swift @@ -95,6 +95,18 @@ struct DemoRootView: View { blue: DemoRootView.backgroundBlue ) ) + .alert( + "Microphone Access Needed", + isPresented: Binding( + get: { controller.microphoneAccessDenied }, + set: { controller.microphoneAccessDenied = $0 } + ) + ) { + Button("OK", role: .cancel) { } + } message: { + Text("Live input needs microphone access. Enable it in System Settings › Privacy & " + + "Security › Microphone, then select the input again.") + } } // MARK: - Toolbar diff --git a/Demo/ShoeGazeDemo/ShoeGazeDemo.entitlements b/Demo/ShoeGazeDemo/ShoeGazeDemo.entitlements new file mode 100644 index 0000000..b572d9c --- /dev/null +++ b/Demo/ShoeGazeDemo/ShoeGazeDemo.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.device.audio-input + + + diff --git a/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift b/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift index 01771ed..a3b38d0 100644 --- a/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift +++ b/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift @@ -127,9 +127,29 @@ final class ShoeGazeDemoController { /// Changes the input source policy and triggers a full rebuild. /// + /// Live input requires microphone authorisation first — without it macOS feeds the AUHAL input + /// silent zeros. The request is asynchronous, so `.liveInput` is applied only once the grant + /// resolves; a denial falls back to the test loop. + /// /// - Parameter source: `.testLoop` for the built-in test signal or `.liveInput(channel:)` /// for hardware microphone/instrument input on the given channel. func setInputSource(_ source: InputSource) { + guard case .liveInput = source else { + applyInputSource(source) + return + } + MicrophonePermission.request { [weak self] granted in + if !granted { self?.microphoneAccessDenied = true } + self?.applyInputSource(granted ? source : .testLoop) + } + } + + /// Set when live input is requested but microphone access is denied/restricted. The UI observes + /// this and presents an alert, then clears it. + var microphoneAccessDenied: Bool = false + + /// Applies an input-source change and triggers a full rebuild. + private func applyInputSource(_ source: InputSource) { inputSource = source rebuild() } @@ -182,8 +202,8 @@ final class ShoeGazeDemoController { inputSource = .testLoop } buildSession() - // Input buses follow the output buses, so the tapped indices change with the layout. - shoeGaze.installScopeTap() + // `buildSession()` creates a fresh `ShoeGaze`, whose `init` installs the scope tap for the + // new channel layout — no explicit `installScopeTap()` needed here. if wasRunning { start() } } diff --git a/Sources/LyrebirdShoeGaze/Input/MicrophonePermission.swift b/Sources/LyrebirdShoeGaze/Input/MicrophonePermission.swift new file mode 100644 index 0000000..24bfd62 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Input/MicrophonePermission.swift @@ -0,0 +1,52 @@ +// MicrophonePermission.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import AVFoundation + +/// Microphone (audio-input) authorisation helper for live-input mode. +/// +/// On macOS, an AUHAL input unit does **not** reliably trigger the system microphone prompt; +/// without an explicit `AVCaptureDevice.requestAccess(for: .audio)` the OS hands the app a stream +/// of silent zeros (no error). On iOS the record-permission prompt is likewise required before the +/// session delivers input. This helper centralises the cross-platform request so every app routes +/// live input through the same gate. +/// +/// The Info.plist must contain `NSMicrophoneUsageDescription`, or the request crashes at runtime. +public enum MicrophonePermission { + + /// Current authorisation state for audio capture. + public static var status: AVAuthorizationStatus { + AVCaptureDevice.authorizationStatus(for: .audio) + } + + /// `true` only when audio capture is already authorised. + public static var isAuthorized: Bool { + status == .authorized + } + + /// Ensures microphone access, prompting the user once if the state is undetermined. + /// + /// - `authorized` → `completion(true)` immediately (next run loop, on the main actor). + /// - `notDetermined` → shows the system prompt; `completion` fires with the user's choice. + /// - `denied` / `restricted` → `completion(false)` (the app must direct the user to Settings). + /// + /// `completion` is always delivered on the main actor so callers can drive UI / engine state + /// directly without further hops. + /// + /// - Parameter completion: Receives the final grant state. + public static func request(_ completion: @escaping @MainActor (Bool) -> Void) { + switch status { + case .authorized: + Task { @MainActor in completion(true) } + case .notDetermined: + AVCaptureDevice.requestAccess(for: .audio) { granted in + Task { @MainActor in completion(granted) } + } + default: + Task { @MainActor in completion(false) } + } + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift index 4a8e774..3088a8f 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Engine.swift @@ -35,6 +35,11 @@ extension ShoeGaze { ) 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 @@ -53,10 +58,6 @@ extension ShoeGaze { } 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. @@ -73,6 +74,10 @@ extension ShoeGaze { /// /// - 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 diff --git a/Sources/LyrebirdShoeGazeUI/EngineConfigView.swift b/Sources/LyrebirdShoeGazeUI/EngineConfigView.swift index 8576a71..c40414a 100644 --- a/Sources/LyrebirdShoeGazeUI/EngineConfigView.swift +++ b/Sources/LyrebirdShoeGazeUI/EngineConfigView.swift @@ -48,6 +48,7 @@ public struct EngineConfigView: View { @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 @@ -107,7 +108,7 @@ public struct EngineConfigView: View { .buttonStyle(.borderedProminent) .tint(isRunning ? .red : .green) } - .alert("Sample Rate Mismatch", isPresented: $showAlert) { + .alert(alertTitle, isPresented: $showAlert) { Button("OK", role: .cancel) { } } message: { Text(alertText) @@ -140,9 +141,12 @@ public struct EngineConfigView: View { 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. + // 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() @@ -163,10 +167,16 @@ public struct EngineConfigView: View { return } #endif - print("[EngineConfigView] engine start failed: \(error)") + // 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 diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index 98b2d46..8f5100f 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -63,6 +63,9 @@ public struct ShoeGazeBuilderView: View { /// Bumped on transport/edit actions to force a re-read of `engine.isRunning`. @State private var transportTick: Bool = false + /// Shown when live input is selected but microphone access is denied/restricted. + @State private var showMicDeniedAlert: Bool = false + #if !os(macOS) /// iOS file-dialog presentation flags + the document to export. (macOS uses the File menu.) @State private var showImporter: Bool = false @@ -117,6 +120,12 @@ public struct ShoeGazeBuilderView: View { blue: ShoeGazeBuilderView.backgroundBlue ) ) + .alert("Microphone Access Needed", isPresented: $showMicDeniedAlert) { + Button("OK", role: .cancel) { } + } message: { + Text("Live input needs microphone access. Enable it in System Settings › Privacy & " + + "Security › Microphone, then select the input again.") + } #if !os(macOS) .fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in handleImport(result) @@ -305,7 +314,23 @@ public struct ShoeGazeBuilderView: View { } /// Switches input source, stopping/restarting the engine around the graph rebuild. + /// + /// Live input requires microphone authorisation first — without it macOS feeds the AUHAL + /// input silent zeros. The request is asynchronous, so when the source is `.liveInput` the + /// actual switch is deferred until the grant resolves; a denial falls back to the test loop. private func switchInput(to source: InputSource) { + guard case .liveInput = source else { + applyInputSource(source) + return + } + MicrophonePermission.request { granted in + if !granted { showMicDeniedAlert = true } + applyInputSource(granted ? source : .testLoop) + } + } + + /// Applies an input-source change, stopping/restarting the engine around the graph rebuild. + private func applyInputSource(_ source: InputSource) { let wasRunning: Bool = shoeGaze.engine.isRunning if wasRunning { shoeGaze.engine.stop() } do {