Jotley / app / macOS / ProcessTap / ProcessTap.swift
| 1 | // Includes material adapted from AudioCap by Guilherme Rambo (copyright 2024). |
| 2 | // Upstream material retains BSD-2-Clause; see docs/Rambo-BSD-2-Clause.txt. |
| 3 | |
| 4 | import OSLog |
| 5 | import AVFoundation |
| 6 | import AudioToolbox |
| 7 | import SwiftUI |
| 8 | |
| 9 | extension Notification.Name { |
| 10 | static let processTapRecordingStateChanged = Notification.Name("processTapRecordingStateChanged") |
| 11 | } |
| 12 | |
| 13 | enum TapTarget { |
| 14 | case systemAudio |
| 15 | |
| 16 | var loggingProcessName: String { |
| 17 | return "SystemAudioOutput" |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | /// Core Audio asks for consent when a tap-backed device starts I/O. |
| 22 | /// This short-lived setup probe discards every buffer. It creates no note/file, |
| 23 | /// never includes a microphone, and leaves the user's speaker output unmuted. |
| 24 | final class JotleySystemAudioPermissionProbe { |
| 25 | private var tap: AudioObjectID = 0 |
| 26 | private var device: AudioObjectID = 0 |
| 27 | private var io: AudioDeviceIOProcID? |
| 28 | func start() throws { |
| 29 | stop() |
| 30 | let description = CATapDescription(stereoGlobalTapButExcludeProcesses: []) |
| 31 | description.uuid = UUID() |
| 32 | description.isPrivate = true |
| 33 | description.muteBehavior = .unmuted |
| 34 | try require(AudioHardwareCreateProcessTap(description, &tap)) |
| 35 | do { |
| 36 | let output = try AudioDeviceID.readDefaultOutputDevice().readDeviceUID() |
| 37 | let aggregate: [String: Any] = [ |
| 38 | kAudioAggregateDeviceNameKey: "Jotley System Audio Setup", |
| 39 | kAudioAggregateDeviceUIDKey: UUID().uuidString, |
| 40 | kAudioAggregateDeviceIsPrivateKey: true, |
| 41 | kAudioAggregateDeviceMainSubDeviceKey: output, |
| 42 | kAudioAggregateDeviceSubDeviceListKey: [[kAudioSubDeviceUIDKey: output]], |
| 43 | kAudioAggregateDeviceTapAutoStartKey: false, |
| 44 | kAudioAggregateDeviceTapListKey: [[kAudioSubTapUIDKey: description.uuid.uuidString, |
| 45 | kAudioSubTapDriftCompensationKey: true]] |
| 46 | ] |
| 47 | try require(AudioHardwareCreateAggregateDevice(aggregate as CFDictionary, &device)) |
| 48 | try require(AudioDeviceCreateIOProcIDWithBlock(&io, device, |
| 49 | DispatchQueue(label: "ai.jotley.system-audio-permission")) { _, _, _, _, _ in |
| 50 | // Intentionally discard all input; onboarding never transcribes or saves it. |
| 51 | }) |
| 52 | try require(AudioDeviceStart(device, io)) |
| 53 | } catch { stop(); throw error } |
| 54 | } |
| 55 | private func require(_ result: OSStatus) throws { |
| 56 | guard result == noErr else { |
| 57 | stop() |
| 58 | throw LocalError.message("macOS could not start system audio setup. You can use microphone-only transcription and enable app audio later.") |
| 59 | } |
| 60 | } |
| 61 | func stop() { |
| 62 | if let io { AudioDeviceStop(device, io); AudioDeviceDestroyIOProcID(device, io) } |
| 63 | io = nil |
| 64 | if device != 0 { AudioHardwareDestroyAggregateDevice(device); device = 0 } |
| 65 | if tap != 0 { AudioHardwareDestroyProcessTap(tap); tap = 0 } |
| 66 | } |
| 67 | deinit { stop() } |
| 68 | } |
| 69 | |
| 70 | @Observable |
| 71 | final class ProcessTap { |
| 72 | |
| 73 | typealias InvalidationHandler = (ProcessTap) -> Void |
| 74 | |
| 75 | let target: TapTarget |
| 76 | let muteWhenRunning: Bool |
| 77 | let logger: Logger |
| 78 | |
| 79 | private(set) var errorMessage: String? = nil |
| 80 | |
| 81 | init(muteWhenRunning: Bool = false) { |
| 82 | self.target = .systemAudio |
| 83 | self.muteWhenRunning = muteWhenRunning |
| 84 | self.logger = Logger(subsystem: LocalPaths.bundleID, category: "\(String(describing: ProcessTap.self))(\(self.target.loggingProcessName))") |
| 85 | } |
| 86 | |
| 87 | @ObservationIgnored |
| 88 | private var processTapID: AudioObjectID = .unknown |
| 89 | @ObservationIgnored |
| 90 | private var aggregateDeviceID = AudioObjectID.unknown |
| 91 | @ObservationIgnored |
| 92 | private var deviceProcID: AudioDeviceIOProcID? |
| 93 | @ObservationIgnored |
| 94 | private(set) var tapStreamDescription: AudioStreamBasicDescription? |
| 95 | @ObservationIgnored |
| 96 | public var aggregateDeviceStreamDescription: AudioStreamBasicDescription? |
| 97 | @ObservationIgnored |
| 98 | private var invalidationHandler: InvalidationHandler? |
| 99 | |
| 100 | @ObservationIgnored |
| 101 | private(set) var activated = false |
| 102 | |
| 103 | @MainActor |
| 104 | func activate() { |
| 105 | // Skip only when the tap is already prepared AND usable. A previous |
| 106 | // activation that failed inside prepare() leaves `activated == true` but no |
| 107 | // valid tap/stream description — in that state we must re-prepare instead of |
| 108 | // skipping forever. Otherwise the first record on a fresh install (which can |
| 109 | // fail before audio permission is granted) poisons every later attempt and |
| 110 | // the user can never start a recording. |
| 111 | if activated, aggregateDeviceStreamDescription != nil, processTapID.isValid { |
| 112 | return |
| 113 | } |
| 114 | activated = true |
| 115 | |
| 116 | logger.debug(#function) |
| 117 | self.errorMessage = nil |
| 118 | |
| 119 | do { |
| 120 | try prepare() |
| 121 | } catch { |
| 122 | logger.error("\(error, privacy: .public)") |
| 123 | self.errorMessage = error.localizedDescription |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | func invalidate() { |
| 128 | guard activated else { return } |
| 129 | defer { activated = false } |
| 130 | |
| 131 | logger.debug(#function) |
| 132 | |
| 133 | invalidationHandler?(self) |
| 134 | self.invalidationHandler = nil |
| 135 | |
| 136 | if aggregateDeviceID.isValid { |
| 137 | var err: OSStatus |
| 138 | |
| 139 | err = AudioDeviceStop(aggregateDeviceID, deviceProcID) |
| 140 | if err != noErr { |
| 141 | logger.warning("Failed to stop aggregate device: \(err, privacy: .public)") |
| 142 | } |
| 143 | |
| 144 | if let deviceProcID { |
| 145 | err = AudioDeviceDestroyIOProcID(aggregateDeviceID, deviceProcID) |
| 146 | if err != noErr { |
| 147 | logger.warning("Failed to destroy device I/O proc: \(err, privacy: .public)") |
| 148 | } |
| 149 | self.deviceProcID = nil |
| 150 | } |
| 151 | |
| 152 | err = AudioHardwareDestroyAggregateDevice(aggregateDeviceID) |
| 153 | if err != noErr { |
| 154 | logger.warning("Failed to destroy aggregate device: \(err, privacy: .public)") |
| 155 | } |
| 156 | aggregateDeviceID = .unknown |
| 157 | } |
| 158 | |
| 159 | if processTapID.isValid { |
| 160 | let errTapDestroy = AudioHardwareDestroyProcessTap(processTapID) |
| 161 | if errTapDestroy != noErr { |
| 162 | logger.warning("Failed to destroy audio tap: \(errTapDestroy, privacy: .public)") |
| 163 | } |
| 164 | self.processTapID = .unknown |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | private func prepare() throws { |
| 169 | logger.info("-[ProcessTap prepare] CALLED") |
| 170 | errorMessage = nil |
| 171 | |
| 172 | // Global tap continues capturing apps that start after recording begins. |
| 173 | let tapDescription = CATapDescription(stereoGlobalTapButExcludeProcesses: []) |
| 174 | tapDescription.uuid = UUID() |
| 175 | logger.info("-[ProcessTap prepare] tapDescription.uuid: \(tapDescription.uuid.uuidString)") |
| 176 | tapDescription.muteBehavior = muteWhenRunning ? .mutedWhenTapped : .unmuted |
| 177 | logger.info("-[ProcessTap prepare] tapDescription.muteBehavior: \(self.muteWhenRunning ? "mutedWhenTapped" : "unmuted")") |
| 178 | |
| 179 | var tapID: AUAudioObjectID = .unknown |
| 180 | let errTapCreation = AudioHardwareCreateProcessTap(tapDescription, &tapID) |
| 181 | logger.info("-[ProcessTap prepare] AudioHardwareCreateProcessTap result: OSStatus \(errTapCreation), tapID: \(tapID)") |
| 182 | |
| 183 | guard errTapCreation == noErr else { |
| 184 | self.errorMessage = "System audio tap creation failed with error \(errTapCreation)" |
| 185 | logger.error("-[ProcessTap prepare] \(self.errorMessage ?? "Unknown error")") |
| 186 | throw CoreAudioError.general(self.errorMessage ?? "Unknown error creating tap.") |
| 187 | } |
| 188 | |
| 189 | self.processTapID = tapID |
| 190 | logger.info("-[ProcessTap prepare] Process tap successfully created. self.processTapID: \(self.processTapID)") |
| 191 | |
| 192 | let allDeviceIDs = try AudioObjectID.system.getAllHardwareDevices() |
| 193 | logger.info("-[ProcessTap prepare] allDeviceIDs (hardware devices) fetched. Count: \(allDeviceIDs.count). IDs: \(allDeviceIDs.map { String($0) }.joined(separator: ", "))") |
| 194 | |
| 195 | var outputUIDs: [String] = [] |
| 196 | for devID in allDeviceIDs { |
| 197 | do { |
| 198 | let outputChans = try devID.getTotalOutputChannelCount() |
| 199 | if outputChans > 0 { |
| 200 | let devUID = try devID.readDeviceUID() |
| 201 | outputUIDs.append(devUID) |
| 202 | logger.info("-[ProcessTap prepare] Found output device: ID \(devID), UID \(devUID), OutputChannels \(outputChans)") |
| 203 | } |
| 204 | } catch { |
| 205 | logger.warning("-[ProcessTap prepare] Ignored device \(devID) while checking output channels: \(error.localizedDescription)") |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | if outputUIDs.isEmpty { |
| 210 | logger.error("-[ProcessTap prepare] No hardware output devices found with output channels!") |
| 211 | throw CoreAudioError.general("No hardware output devices found!") |
| 212 | } |
| 213 | logger.info("-[ProcessTap prepare] outputUIDs collected. Count: \(outputUIDs.count). UIDs: \(outputUIDs.joined(separator: ", "))") |
| 214 | |
| 215 | let systemOutputID: AudioDeviceID |
| 216 | do { |
| 217 | // Use the regular default output device (speakers/headphones), not the "system sounds" output |
| 218 | // This avoids issues where virtual audio devices like BlackHole are set as system output |
| 219 | systemOutputID = try AudioDeviceID.readDefaultOutputDevice() |
| 220 | logger.info("-[ProcessTap prepare] Default output device ID: \(systemOutputID)") |
| 221 | } catch { |
| 222 | logger.error("-[ProcessTap prepare] Failed to read default output device ID: \(error.localizedDescription)") |
| 223 | throw error |
| 224 | } |
| 225 | |
| 226 | let mainSubdeviceUID: String |
| 227 | do { |
| 228 | mainSubdeviceUID = try systemOutputID.readDeviceUID() |
| 229 | logger.info("-[ProcessTap prepare] Main subdevice UID (from default output): \(mainSubdeviceUID)") |
| 230 | } catch { |
| 231 | logger.error("-[ProcessTap prepare] Failed to read device UID for systemOutputID \(systemOutputID): \(error.localizedDescription)") |
| 232 | throw error |
| 233 | } |
| 234 | |
| 235 | let microphoneDeviceID: AudioDeviceID |
| 236 | do { |
| 237 | microphoneDeviceID = try AudioDeviceID.readDefaultInputDevice() |
| 238 | logger.info("-[ProcessTap prepare] Default microphone device ID: \(microphoneDeviceID)") |
| 239 | print("🎤 [ProcessTap prepare] Successfully found microphone device ID: \(microphoneDeviceID)") |
| 240 | } catch { |
| 241 | logger.error("-[ProcessTap prepare] Failed to read default microphone device ID: \(error.localizedDescription)") |
| 242 | print("❌ [ProcessTap prepare] Failed to get microphone: \(error.localizedDescription)") |
| 243 | throw error |
| 244 | } |
| 245 | |
| 246 | let microphoneUID: String |
| 247 | do { |
| 248 | microphoneUID = try microphoneDeviceID.readDeviceUID() |
| 249 | logger.info("-[ProcessTap prepare] Microphone UID: \(microphoneUID)") |
| 250 | print("🎤 [ProcessTap prepare] Microphone UID: \(microphoneUID)") |
| 251 | } catch { |
| 252 | logger.error("-[ProcessTap prepare] Failed to read device UID for microphoneDeviceID \(microphoneDeviceID): \(error.localizedDescription)") |
| 253 | print("❌ [ProcessTap prepare] Failed to read microphone UID: \(error.localizedDescription)") |
| 254 | throw error |
| 255 | } |
| 256 | |
| 257 | let aggregateDeviceName = "Tap-MicSysAgg-\(mainSubdeviceUID.prefix(8))" |
| 258 | let subDeviceListForAggregate: [[String: String]] = [ |
| 259 | [kAudioSubDeviceUIDKey: mainSubdeviceUID], // System audio first (more reliable) |
| 260 | [kAudioSubDeviceUIDKey: microphoneUID] // Microphone second |
| 261 | ] |
| 262 | let aggregateUID = UUID().uuidString |
| 263 | |
| 264 | let descriptionForAggregate: [String: Any] = [ |
| 265 | kAudioAggregateDeviceNameKey: aggregateDeviceName, |
| 266 | kAudioAggregateDeviceUIDKey: aggregateUID, |
| 267 | kAudioAggregateDeviceMainSubDeviceKey: mainSubdeviceUID, // Use system audio as main device |
| 268 | kAudioAggregateDeviceIsPrivateKey: true, |
| 269 | kAudioAggregateDeviceIsStackedKey: false, |
| 270 | kAudioAggregateDeviceTapAutoStartKey: false, |
| 271 | kAudioAggregateDeviceSubDeviceListKey: subDeviceListForAggregate, |
| 272 | kAudioAggregateDeviceTapListKey: [ |
| 273 | [ |
| 274 | kAudioSubTapDriftCompensationKey: true, |
| 275 | kAudioSubTapUIDKey: tapDescription.uuid.uuidString |
| 276 | ] |
| 277 | ] |
| 278 | ] |
| 279 | logger.info("-[ProcessTap prepare] Aggregate device description prepared: \(String(describing: descriptionForAggregate))") |
| 280 | |
| 281 | aggregateDeviceID = AudioObjectID.unknown |
| 282 | do { |
| 283 | let errAggDeviceCreation = AudioHardwareCreateAggregateDevice(descriptionForAggregate as CFDictionary, &aggregateDeviceID) |
| 284 | logger.info("-[ProcessTap prepare] AudioHardwareCreateAggregateDevice result: OSStatus \(errAggDeviceCreation), aggregateDeviceID: \(self.aggregateDeviceID)") |
| 285 | |
| 286 | if errAggDeviceCreation != noErr { |
| 287 | logger.error("-[ProcessTap prepare] AudioHardwareCreateAggregateDevice failed with error: \(errAggDeviceCreation).") |
| 288 | AudioHardwareDestroyProcessTap(self.processTapID) |
| 289 | self.processTapID = .unknown |
| 290 | logger.info("-[ProcessTap prepare] Cleaned up processTapID \(self.processTapID) due to aggregate device creation failure.") |
| 291 | throw CoreAudioError.general("Failed to create aggregate device: \(errAggDeviceCreation)") |
| 292 | } |
| 293 | logger.info("-[ProcessTap prepare] Aggregate device successfully created. self.aggregateDeviceID: \(self.aggregateDeviceID)") |
| 294 | |
| 295 | var deviceOutputASBD = AudioStreamBasicDescription() |
| 296 | var propertyAddress = AudioObjectPropertyAddress( |
| 297 | mSelector: kAudioDevicePropertyStreamFormat, |
| 298 | mScope: kAudioDevicePropertyScopeInput, |
| 299 | mElement: kAudioObjectPropertyElementMain |
| 300 | ) |
| 301 | var propertyDataSize = UInt32(MemoryLayout<AudioStreamBasicDescription>.stride) |
| 302 | |
| 303 | let status = AudioObjectGetPropertyData( |
| 304 | self.aggregateDeviceID, |
| 305 | &propertyAddress, |
| 306 | 0, |
| 307 | nil, |
| 308 | &propertyDataSize, |
| 309 | &deviceOutputASBD |
| 310 | ) |
| 311 | |
| 312 | guard status == noErr else { |
| 313 | logger.error("-[ProcessTap prepare] Failed to read aggregate device output stream format: OSStatus \(status)") |
| 314 | AudioHardwareDestroyAggregateDevice(self.aggregateDeviceID) |
| 315 | self.aggregateDeviceID = .unknown |
| 316 | AudioHardwareDestroyProcessTap(self.processTapID) |
| 317 | self.processTapID = .unknown |
| 318 | throw CoreAudioError.propertyReadError(property: "AggregateDeviceOutputFormat", osStatus: status) |
| 319 | } |
| 320 | self.aggregateDeviceStreamDescription = deviceOutputASBD |
| 321 | logger.info("-[ProcessTap prepare] Aggregate device output stream description read successfully: \(String(describing: self.aggregateDeviceStreamDescription))") |
| 322 | |
| 323 | } catch { |
| 324 | logger.error("-[ProcessTap prepare] EXCEPTION during aggregate device creation or output format read: \(error.localizedDescription)") |
| 325 | if self.processTapID.isValid && !(error is CoreAudioError && "\(error)".contains("ProcessTap")) { |
| 326 | AudioHardwareDestroyProcessTap(self.processTapID) |
| 327 | self.processTapID = .unknown |
| 328 | } |
| 329 | throw error |
| 330 | } |
| 331 | |
| 332 | do { |
| 333 | self.tapStreamDescription = try tapID.readAudioTapStreamBasicDescription() |
| 334 | logger.info("-[ProcessTap prepare] Tap (processTapID \(tapID)) stream basic description read successfully: \(String(describing: self.tapStreamDescription))") |
| 335 | } catch { |
| 336 | logger.error("-[ProcessTap prepare] Failed to read audio tap stream basic description for tapID #\(tapID): \(error.localizedDescription)") |
| 337 | if self.aggregateDeviceID.isValid { AudioHardwareDestroyAggregateDevice(self.aggregateDeviceID) } |
| 338 | self.aggregateDeviceID = .unknown |
| 339 | if self.processTapID.isValid { AudioHardwareDestroyProcessTap(self.processTapID) } |
| 340 | self.processTapID = .unknown |
| 341 | logger.info("-[ProcessTap prepare] Cleaned up aggregateDeviceID and processTapID due to tap stream description failure.") |
| 342 | throw error |
| 343 | } |
| 344 | logger.info("-[ProcessTap prepare] COMPLETED SUCCESSFULLY") |
| 345 | |
| 346 | } |
| 347 | |
| 348 | func run(on queue: DispatchQueue, ioBlock: @escaping AudioDeviceIOBlock, invalidationHandler: @escaping InvalidationHandler) throws { |
| 349 | assert(activated, "\(#function) called with inactive tap!") |
| 350 | assert(self.invalidationHandler == nil, "\(#function) called with tap already active!") |
| 351 | |
| 352 | errorMessage = nil |
| 353 | logger.debug("Run tap!") |
| 354 | self.invalidationHandler = invalidationHandler |
| 355 | |
| 356 | var err = AudioDeviceCreateIOProcIDWithBlock(&deviceProcID, aggregateDeviceID, queue, ioBlock) |
| 357 | guard err == noErr else { |
| 358 | // Leave the tap re-runnable on failure: clear the handler we just set so a |
| 359 | // retry doesn't trip the `invalidationHandler == nil` assertion. |
| 360 | self.invalidationHandler = nil |
| 361 | throw CoreAudioError.general("Failed to create device I/O proc: \(err)") |
| 362 | } |
| 363 | |
| 364 | err = AudioDeviceStart(aggregateDeviceID, deviceProcID) |
| 365 | guard err == noErr else { |
| 366 | if let deviceProcID { AudioDeviceDestroyIOProcID(aggregateDeviceID, deviceProcID) } |
| 367 | self.deviceProcID = nil |
| 368 | self.invalidationHandler = nil |
| 369 | throw CoreAudioError.general("Failed to start audio device: \(err)") |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | deinit { invalidate() } |
| 374 | |
| 375 | } |