Jotley / app / macOS / ProcessTap / CoreAudioUtils.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 Foundation |
| 5 | import AudioToolbox |
| 6 | |
| 7 | // Sole definition of CoreAudioError |
| 8 | enum CoreAudioError: LocalizedError { |
| 9 | case general(String) |
| 10 | case propertyReadError(property: String, osStatus: OSStatus) |
| 11 | case propertySizeError(property: String, osStatus: OSStatus) |
| 12 | case operationNotSupportedForObject(String) |
| 13 | case invalidPID(pid_t) |
| 14 | |
| 15 | public var errorDescription: String? { |
| 16 | switch self { |
| 17 | case .general(let message): |
| 18 | return message |
| 19 | case .propertyReadError(let property, let osStatus): |
| 20 | return "Error reading property '\(property)': OSStatus \(osStatus)." |
| 21 | case .propertySizeError(let property, let osStatus): |
| 22 | return "Error reading size for property '\(property)': OSStatus \(osStatus)." |
| 23 | case .operationNotSupportedForObject(let message): |
| 24 | return message |
| 25 | case .invalidPID(let pid): |
| 26 | return "Invalid process identifier: \(pid)." |
| 27 | } |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | // MARK: - Constants |
| 32 | |
| 33 | extension AudioObjectID { |
| 34 | /// Convenience for `kAudioObjectSystemObject`. |
| 35 | static let system = AudioObjectID(kAudioObjectSystemObject) |
| 36 | /// Convenience for `kAudioObjectUnknown`. |
| 37 | static let unknown = kAudioObjectUnknown |
| 38 | |
| 39 | /// `true` if this object has the value of `kAudioObjectUnknown`. |
| 40 | var isUnknown: Bool { self == .unknown } |
| 41 | |
| 42 | /// `false` if this object has the value of `kAudioObjectUnknown`. |
| 43 | var isValid: Bool { !isUnknown } |
| 44 | } |
| 45 | |
| 46 | // MARK: - Concrete Property Helpers |
| 47 | |
| 48 | extension AudioObjectID { |
| 49 | |
| 50 | /// Reads the value for `kAudioHardwarePropertyDefaultOutputDevice`. |
| 51 | /// This is the regular default output (speakers/headphones), not the "system sounds" output. |
| 52 | static func readDefaultOutputDevice() throws -> AudioDeviceID { |
| 53 | try AudioObjectID.system.readDefaultOutputDevice() |
| 54 | } |
| 55 | |
| 56 | /// Reads the value for `kAudioHardwarePropertyDefaultInputDevice`. |
| 57 | static func readDefaultInputDevice() throws -> AudioDeviceID { |
| 58 | try AudioObjectID.system.readDefaultInputDevice() |
| 59 | } |
| 60 | |
| 61 | /// Reads the value for `kAudioHardwarePropertyDefaultOutputDevice`, should only be called on the system object. |
| 62 | /// This is the regular default output (speakers/headphones), not the "system sounds" output. |
| 63 | func readDefaultOutputDevice() throws -> AudioDeviceID { |
| 64 | try requireSystemObject() |
| 65 | return try read(kAudioHardwarePropertyDefaultOutputDevice, defaultValue: AudioDeviceID.unknown) |
| 66 | } |
| 67 | |
| 68 | /// Reads the value for `kAudioHardwarePropertyDefaultInputDevice`, should only be called on the system object. |
| 69 | func readDefaultInputDevice() throws -> AudioDeviceID { |
| 70 | try requireSystemObject() |
| 71 | return try read(kAudioHardwarePropertyDefaultInputDevice, defaultValue: AudioDeviceID.unknown) |
| 72 | } |
| 73 | |
| 74 | /// Reads the value for `kAudioDevicePropertyDeviceUID` for the device represented by this audio object ID. |
| 75 | func readDeviceUID() throws -> String { try readString(kAudioDevicePropertyDeviceUID) } |
| 76 | |
| 77 | /// Reads the value for `kAudioTapPropertyFormat` for the device represented by this audio object ID. |
| 78 | func readAudioTapStreamBasicDescription() throws -> AudioStreamBasicDescription { |
| 79 | try read(kAudioTapPropertyFormat, defaultValue: AudioStreamBasicDescription()) |
| 80 | } |
| 81 | |
| 82 | private func requireSystemObject() throws { |
| 83 | if self != .system { throw CoreAudioError.operationNotSupportedForObject("Only supported for the system object.") } |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | // MARK: - Generic Property Access |
| 88 | |
| 89 | extension AudioObjectID { |
| 90 | |
| 91 | func read<T>(_ selector: AudioObjectPropertySelector, |
| 92 | scope: AudioObjectPropertyScope = kAudioObjectPropertyScopeGlobal, |
| 93 | element: AudioObjectPropertyElement = kAudioObjectPropertyElementMain, |
| 94 | defaultValue: T) throws -> T |
| 95 | { |
| 96 | try read(AudioObjectPropertyAddress(mSelector: selector, mScope: scope, mElement: element), defaultValue: defaultValue) |
| 97 | } |
| 98 | |
| 99 | func read<T>(_ address: AudioObjectPropertyAddress, defaultValue: T) throws -> T { |
| 100 | try read(address, defaultValue: defaultValue, inQualifierSize: 0, inQualifierData: nil) |
| 101 | } |
| 102 | |
| 103 | func readString(_ selector: AudioObjectPropertySelector, scope: AudioObjectPropertyScope = kAudioObjectPropertyScopeGlobal, element: AudioObjectPropertyElement = kAudioObjectPropertyElementMain) throws -> String { |
| 104 | try read(AudioObjectPropertyAddress(mSelector: selector, mScope: scope, mElement: element), defaultValue: "" as CFString) as String |
| 105 | } |
| 106 | |
| 107 | private func read<T>(_ inAddress: AudioObjectPropertyAddress, defaultValue: T, inQualifierSize: UInt32 = 0, inQualifierData: UnsafeRawPointer? = nil) throws -> T { |
| 108 | var address = inAddress |
| 109 | var dataSize: UInt32 = 0 |
| 110 | var err = AudioObjectGetPropertyDataSize(self, &address, inQualifierSize, inQualifierData, &dataSize) |
| 111 | |
| 112 | guard err == noErr else { |
| 113 | throw CoreAudioError.propertySizeError(property: String(describing: address), osStatus: err) |
| 114 | } |
| 115 | |
| 116 | var value: T = defaultValue |
| 117 | err = withUnsafeMutablePointer(to: &value) { ptr in |
| 118 | AudioObjectGetPropertyData(self, &address, inQualifierSize, inQualifierData, &dataSize, ptr) |
| 119 | } |
| 120 | |
| 121 | guard err == noErr else { |
| 122 | throw CoreAudioError.propertyReadError(property: String(describing: address), osStatus: err) |
| 123 | } |
| 124 | return value |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | // MARK: - Debugging Helpers |
| 129 | |
| 130 | private extension UInt32 { |
| 131 | var fourCharString: String { |
| 132 | String(cString: [ |
| 133 | UInt8((self >> 24) & 0xFF), |
| 134 | UInt8((self >> 16) & 0xFF), |
| 135 | UInt8((self >> 8) & 0xFF), |
| 136 | UInt8(self & 0xFF), |
| 137 | 0 |
| 138 | ]) |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | extension AudioObjectPropertyAddress: @retroactive CustomStringConvertible { |
| 143 | public var description: String { |
| 144 | let elementDescription = mElement == kAudioObjectPropertyElementMain ? "main" : mElement.fourCharString |
| 145 | return "\(mSelector.fourCharString)/\(mScope.fourCharString)/\(elementDescription)" |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | extension AudioObjectID { |
| 150 | func getAllHardwareDevices() throws -> [AudioDeviceID] { |
| 151 | try requireSystemObject() |
| 152 | |
| 153 | var address = AudioObjectPropertyAddress( |
| 154 | mSelector: kAudioHardwarePropertyDevices, |
| 155 | mScope: kAudioObjectPropertyScopeGlobal, |
| 156 | mElement: kAudioObjectPropertyElementMain |
| 157 | ) |
| 158 | |
| 159 | var dataSize: UInt32 = 0 |
| 160 | var err = AudioObjectGetPropertyDataSize(self, &address, 0, nil, &dataSize) |
| 161 | guard err == noErr else { |
| 162 | throw CoreAudioError.propertySizeError(property: kAudioHardwarePropertyDevices.fourCharString, osStatus: err) |
| 163 | } |
| 164 | |
| 165 | let deviceCount = Int(dataSize) / MemoryLayout<AudioDeviceID>.size |
| 166 | if deviceCount == 0 { |
| 167 | return [] |
| 168 | } |
| 169 | var deviceIDs = [AudioDeviceID](repeating: .unknown, count: deviceCount) |
| 170 | |
| 171 | err = AudioObjectGetPropertyData(self, &address, 0, nil, &dataSize, &deviceIDs) |
| 172 | guard err == noErr else { |
| 173 | throw CoreAudioError.propertyReadError(property: kAudioHardwarePropertyDevices.fourCharString, osStatus: err) |
| 174 | } |
| 175 | return deviceIDs |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | // MARK: - Microphone Threshold Feature |
| 180 | |
| 181 | /* |
| 182 | The Jotley app now supports separate noise thresholds for microphone and system audio. |
| 183 | |
| 184 | This feature ensures that: |
| 185 | 1. Background noise from the microphone is filtered out based on a configurable RMS threshold |
| 186 | 2. System audio continues to use its existing threshold |
| 187 | |
| 188 | How it works: |
| 189 | - Each audio buffer is analyzed to determine if it's from the microphone or system audio |
| 190 | - For microphone audio, a much higher threshold is applied (default: 10x the system audio threshold) |
| 191 | - The threshold is configurable through the ProcessTapRecorder.setMicrophoneThreshold method |
| 192 | |
| 193 | Usage: |
| 194 | ``` |
| 195 | let recorder = ProcessTapRecorder(tap: processTap) |
| 196 | // To adjust microphone sensitivity (higher value = less sensitive) |
| 197 | recorder.setMicrophoneThreshold(0.02) // Example value, adjust based on testing |
| 198 | ``` |
| 199 | */ |
| 200 | |
| 201 | extension AudioDeviceID { |
| 202 | func getTotalOutputChannelCount() throws -> UInt32 { |
| 203 | var address = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyStreamConfiguration, |
| 204 | mScope: kAudioDevicePropertyScopeOutput, mElement: kAudioObjectPropertyElementMain) |
| 205 | var size: UInt32 = 0 |
| 206 | let status = AudioObjectGetPropertyDataSize(self, &address, 0, nil, &size) |
| 207 | if status == kAudioHardwareUnknownPropertyError || size == 0 { return 0 } |
| 208 | guard status == noErr else { throw CoreAudioError.general("Cannot read output channel count: \(status)") } |
| 209 | let memory = UnsafeMutableRawPointer.allocate(byteCount: Int(size), alignment: MemoryLayout<AudioBufferList>.alignment) |
| 210 | defer { memory.deallocate() } |
| 211 | let result = AudioObjectGetPropertyData(self, &address, 0, nil, &size, memory) |
| 212 | guard result == noErr else { throw CoreAudioError.general("Cannot read output buffers: \(result)") } |
| 213 | return UnsafeMutableAudioBufferListPointer(memory.assumingMemoryBound(to: AudioBufferList.self)) |
| 214 | .reduce(0) { $0 + $1.mNumberChannels } |
| 215 | } |
| 216 | } |