| 1 | |
| 2 | import AppKit |
| 3 | import AVFoundation |
| 4 | import ScreenCaptureKit |
| 5 | |
| 6 | private let audioSampleRate = 48000 |
| 7 | private let audioChannels = 2 |
| 8 | private let audioFrameBytes = 4 |
| 9 | |
| 10 | private func audioGUIAvailable() -> Bool { |
| 11 | var info = stat() |
| 12 | return stat("/dev/console", &info) == 0 && info.st_uid == getuid() && info.st_uid >= 500 && |
| 13 | (CGSessionCopyCurrentDictionary() as? [String: Any])?["CGSSessionScreenIsLocked"] as? Bool != true |
| 14 | } |
| 15 | |
| 16 | private func writeAudioBytes(_ fd: Int32, _ data: Data) throws { |
| 17 | try data.withUnsafeBytes { bytes in |
| 18 | var offset = 0 |
| 19 | while offset < bytes.count { |
| 20 | let written = Darwin.write(fd, bytes.baseAddress!.advanced(by: offset), bytes.count - offset) |
| 21 | if written < 0 && errno == EINTR { continue } |
| 22 | guard written > 0 else { throw Failure(7, "audio_connection_closed") } |
| 23 | offset += written |
| 24 | } |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | private final class AudioPCMConverter { |
| 29 | private let outputFormat = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: Double(audioSampleRate), channels: AVAudioChannelCount(audioChannels), interleaved: true)! |
| 30 | private var converter: AVAudioConverter? |
| 31 | private var inputFormat: AVAudioFormat? |
| 32 | |
| 33 | func convert(_ input: AVAudioPCMBuffer) throws -> Data { |
| 34 | guard input.format.sampleRate == Double(audioSampleRate), input.format.channelCount == audioChannels, |
| 35 | input.frameLength > 0, input.frameLength <= 16384 else { throw Failure(7, "audio_format_invalid") } |
| 36 | if inputFormat != input.format { |
| 37 | converter = AVAudioConverter(from: input.format, to: outputFormat) |
| 38 | inputFormat = input.format |
| 39 | } |
| 40 | guard let converter, let output = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: input.frameLength) else { |
| 41 | throw Failure(7, "audio_format_invalid") |
| 42 | } |
| 43 | try converter.convert(to: output, from: input) |
| 44 | let buffer = output.audioBufferList.pointee.mBuffers |
| 45 | let count = Int(output.frameLength) * audioFrameBytes |
| 46 | guard count <= Int(buffer.mDataByteSize), let data = buffer.mData else { throw Failure(7, "audio_format_invalid") } |
| 47 | return Data(bytes: data, count: count) |
| 48 | } |
| 49 | |
| 50 | func convert(_ sample: CMSampleBuffer) throws -> Data { |
| 51 | guard sample.isValid, let description = sample.formatDescription else { throw Failure(7, "audio_format_invalid") } |
| 52 | guard let basic = CMAudioFormatDescriptionGetStreamBasicDescription(description), |
| 53 | basic.pointee.mFormatID == kAudioFormatLinearPCM, basic.pointee.mBytesPerFrame > 0, |
| 54 | basic.pointee.mSampleRate == Double(audioSampleRate), basic.pointee.mChannelsPerFrame == audioChannels else { |
| 55 | throw Failure(7, "audio_format_invalid") |
| 56 | } |
| 57 | let format = AVAudioFormat(cmAudioFormatDescription: description) |
| 58 | var required = 0 |
| 59 | var block: CMBlockBuffer? |
| 60 | let flags = UInt32(kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment) |
| 61 | _ = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sample, bufferListSizeNeededOut: &required, |
| 62 | bufferListOut: nil, bufferListSize: 0, blockBufferAllocator: kCFAllocatorDefault, |
| 63 | blockBufferMemoryAllocator: kCFAllocatorDefault, flags: flags, blockBufferOut: &block) |
| 64 | guard required > 0, required <= 4096 else { throw Failure(7, "audio_format_invalid") } |
| 65 | let memory = UnsafeMutableRawPointer.allocate(byteCount: required, alignment: 16) |
| 66 | defer { memory.deallocate() } |
| 67 | let list = memory.bindMemory(to: AudioBufferList.self, capacity: 1) |
| 68 | let status = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sample, bufferListSizeNeededOut: nil, |
| 69 | bufferListOut: list, bufferListSize: required, blockBufferAllocator: kCFAllocatorDefault, |
| 70 | blockBufferMemoryAllocator: kCFAllocatorDefault, flags: flags, blockBufferOut: &block) |
| 71 | guard status == noErr, let input = AVAudioPCMBuffer(pcmFormat: format, bufferListNoCopy: list, deallocator: nil) else { |
| 72 | throw Failure(7, "audio_format_invalid") |
| 73 | } |
| 74 | return try withExtendedLifetime(block) { try convert(input) } |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | private final class AudioSamples: NSObject, SCStreamOutput, SCStreamDelegate, @unchecked Sendable { |
| 79 | private let lock = NSLock() |
| 80 | private let converter = AudioPCMConverter() |
| 81 | private var pending = Data() |
| 82 | private var failed = false |
| 83 | private let limit = audioSampleRate * audioChannels * 2 / 5 |
| 84 | |
| 85 | func stream(_ stream: SCStream, didOutputSampleBuffer sampleBuffer: CMSampleBuffer, of type: SCStreamOutputType) { |
| 86 | guard type == .audio, sampleBuffer.isValid, CMSampleBufferDataIsReady(sampleBuffer), CMSampleBufferGetNumSamples(sampleBuffer) > 0 else { return } |
| 87 | do { |
| 88 | append(try converter.convert(sampleBuffer)) |
| 89 | } catch { |
| 90 | stop() |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | func stream(_ stream: SCStream, didStopWithError error: Error) { |
| 95 | stop() |
| 96 | } |
| 97 | |
| 98 | func append(_ pcm: Data) { |
| 99 | lock.lock(); defer { lock.unlock() } |
| 100 | if !failed { |
| 101 | pending.append(pcm) |
| 102 | if pending.count > limit { pending.removeFirst(pending.count - limit) } |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | func stop() { |
| 107 | lock.lock(); failed = true; pending.removeAll(); lock.unlock() |
| 108 | } |
| 109 | |
| 110 | func next() throws -> Data { |
| 111 | lock.lock(); defer { lock.unlock() } |
| 112 | guard !failed else { throw Failure(7, "audio_capture_failed") } |
| 113 | let count = min(pending.count, 3840) |
| 114 | let result = Data(pending.prefix(count)) |
| 115 | pending.removeFirst(count) |
| 116 | return result |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | enum MacAudioCapture { |
| 121 | static func status() -> [String: Any] { |
| 122 | let gui = audioGUIAvailable() |
| 123 | let permission = CGPreflightScreenCaptureAccess() |
| 124 | return ["supported": true, "available": gui && permission, "format": "s16le", |
| 125 | "sample_rate": audioSampleRate, "channels": audioChannels, |
| 126 | "reason": !gui ? "requires_gui_login" : (!permission ? "screen_recording_permission" : "")] |
| 127 | } |
| 128 | |
| 129 | static func respond(_ fd: Int32) async { |
| 130 | var stream: SCStream? |
| 131 | var ready = false |
| 132 | do { |
| 133 | try requireGuest() |
| 134 | let epoch = try await MacGUISession.shared.validate() |
| 135 | var timeout = timeval(tv_sec: 2, tv_usec: 0) |
| 136 | setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) |
| 137 | guard audioGUIAvailable() else { throw Failure(4, "requires_gui_login") } |
| 138 | |
| 139 | |
| 140 | guard CGPreflightScreenCaptureAccess() else { throw Failure(6, "screen_recording_permission") } |
| 141 | let content = try await SCShareableContent.excludingDesktopWindows(true, onScreenWindowsOnly: true) |
| 142 | guard let display = content.displays.first else { throw Failure(7, "audio_display_unavailable") } |
| 143 | let filter = SCContentFilter(display: display, excludingApplications: [], exceptingWindows: []) |
| 144 | let configuration = SCStreamConfiguration() |
| 145 | configuration.capturesAudio = true |
| 146 | configuration.sampleRate = audioSampleRate |
| 147 | configuration.channelCount = audioChannels |
| 148 | configuration.width = 2 |
| 149 | configuration.height = 2 |
| 150 | configuration.minimumFrameInterval = CMTime(value: 1, timescale: 1) |
| 151 | configuration.queueDepth = 3 |
| 152 | let samples = AudioSamples() |
| 153 | let capture = SCStream(filter: filter, configuration: configuration, delegate: samples) |
| 154 | stream = capture |
| 155 | try capture.addStreamOutput(samples, type: .audio, sampleHandlerQueue: DispatchQueue(label: "dev.cage.GuestAudio.samples")) |
| 156 | try await capture.startCapture() |
| 157 | guard audioGUIAvailable() else { throw Failure(4, "requires_gui_login") } |
| 158 | let header: [String: Any] = ["ready": true, "format": "s16le", "sample_rate": audioSampleRate, "channels": audioChannels] |
| 159 | try writeAudioBytes(fd, JSONSerialization.data(withJSONObject: header) + Data([10])) |
| 160 | ready = true |
| 161 | var checked = Date.distantPast |
| 162 | while !Task.isCancelled { |
| 163 | if Date().timeIntervalSince(checked) >= 0.5 { |
| 164 | guard audioGUIAvailable(), CGPreflightScreenCaptureAccess() else { break } |
| 165 | try await MacGUISession.shared.validate(epoch) |
| 166 | checked = Date() |
| 167 | } |
| 168 | var byte: UInt8 = 0 |
| 169 | let incoming = recv(fd, &byte, 1, MSG_PEEK | MSG_DONTWAIT) |
| 170 | if incoming == 0 || incoming > 0 { break } |
| 171 | if errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR { break } |
| 172 | let packet = try samples.next() |
| 173 | if packet.isEmpty { try await Task.sleep(nanoseconds: 20_000_000) } |
| 174 | else { try writeAudioBytes(fd, packet) } |
| 175 | } |
| 176 | } catch { |
| 177 | GuestDiagnostic.record("window", (error as? Failure)?.message ?? "audio_capture_failed") |
| 178 | if !ready { |
| 179 | let reason = (error as? Failure)?.message ?? "audio_capture_failed" |
| 180 | if let data = try? JSONSerialization.data(withJSONObject: ["error": reason]) { |
| 181 | try? writeAudioBytes(fd, data + Data([10])) |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | if let stream { try? await stream.stopCapture() } |
| 186 | } |
| 187 | |
| 188 | static func selfTest() throws { |
| 189 | let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48000, channels: 2, interleaved: false)! |
| 190 | let input = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 4)! |
| 191 | input.frameLength = 4 |
| 192 | let left: [Float] = [-0.75, 0, 0.5, 0.75] |
| 193 | let right: [Float] = [0.75, 0.5, 0, -0.75] |
| 194 | for index in 0..<4 { |
| 195 | input.floatChannelData![0][index] = left[index] |
| 196 | input.floatChannelData![1][index] = right[index] |
| 197 | } |
| 198 | let converter = AudioPCMConverter() |
| 199 | let bytes = try converter.convert(input) |
| 200 | guard bytes.count == 16 else { throw Failure(7, "audio_test_length") } |
| 201 | for index in 0..<8 { |
| 202 | let value = Int16(bitPattern: UInt16(bytes[index * 2]) | UInt16(bytes[index * 2 + 1]) << 8) |
| 203 | let expected = index % 2 == 0 ? left[index / 2] : right[index / 2] |
| 204 | guard abs(Double(value) / 32768 - Double(expected)) < 0.001 else { throw Failure(7, "audio_test_channels") } |
| 205 | } |
| 206 | let again = try converter.convert(input) |
| 207 | guard again == bytes else { throw Failure(7, "audio_test_continuity") } |
| 208 | var timing = CMSampleTimingInfo(duration: CMTime(value: 1, timescale: 48000), presentationTimeStamp: .zero, decodeTimeStamp: .invalid) |
| 209 | var sample: CMSampleBuffer? |
| 210 | let created = CMSampleBufferCreate(allocator: kCFAllocatorDefault, dataBuffer: nil, dataReady: false, |
| 211 | makeDataReadyCallback: nil, refcon: nil, formatDescription: format.formatDescription, |
| 212 | sampleCount: 4, sampleTimingEntryCount: 1, sampleTimingArray: &timing, |
| 213 | sampleSizeEntryCount: 0, sampleSizeArray: nil, sampleBufferOut: &sample) |
| 214 | guard created == noErr, let sample, |
| 215 | CMSampleBufferSetDataBufferFromAudioBufferList(sample, blockBufferAllocator: kCFAllocatorDefault, |
| 216 | blockBufferMemoryAllocator: kCFAllocatorDefault, flags: 0, bufferList: input.audioBufferList) == noErr else { |
| 217 | throw Failure(7, "audio_test_sample_creation") |
| 218 | } |
| 219 | CMSampleBufferSetDataReady(sample) |
| 220 | guard try converter.convert(sample) == bytes else { throw Failure(7, "audio_test_sample_conversion") } |
| 221 | let queued = AudioSamples() |
| 222 | queued.append(Data(repeating: 0, count: 10000)) |
| 223 | queued.append(Data(repeating: 1, count: 40000)) |
| 224 | var collected = Data() |
| 225 | while true { |
| 226 | let packet = try queued.next() |
| 227 | if packet.isEmpty { break } |
| 228 | guard packet.count <= 3840, packet.count % 4 == 0 else { throw Failure(7, "audio_test_packet_size") } |
| 229 | collected.append(packet) |
| 230 | } |
| 231 | guard collected == Data(repeating: 1, count: 38400) else { throw Failure(7, "audio_test_queue_limit") } |
| 232 | queued.stop() |
| 233 | do { |
| 234 | _ = try queued.next() |
| 235 | throw Failure(7, "audio_test_stop") |
| 236 | } catch let error as Failure { |
| 237 | guard error.message == "audio_capture_failed" else { throw error } |
| 238 | } |
| 239 | print("macOS audio: CoreMedia samples, 48 kHz stereo s16le, consecutive buffers, bounded queue and stopped capture passed") |
| 240 | } |
| 241 | } |