Branchwell

Jotley / app / macOS / ProcessTap / ProcessTapRecorder.swift

1import AppKit
2import Foundation
3import AVFoundation
4import AudioToolbox
5import Combine
6
7@MainActor
8public final class ProcessTapRecorder: ObservableObject {
9 @Published public private(set) var recording = false
10 @Published public private(set) var paused = false
11 @Published public private(set) var starting = false
12 @Published public private(set) var finishing = false
13 public var isBusy: Bool { starting || finishing }
14 @Published public private(set) var errorMessage: String?
15 @Published public private(set) var elapsed: Double = 0
16 private let queue = DispatchQueue(label: "jotley.local.capture")
17 private var tap: ProcessTap?
18 private var engine: AVAudioEngine?
19 private var systemAudio = false
20 private var timer: Timer?
21 private var startedAt: Date?
22 private var previousElapsed = 0.0
23
24 private var liveSpeech: LiveSpeechSession?
25 @Published public private(set) var transcription = ""
26 @Published public private(set) var currentAudioLevel: Float = 0
27 public var isRecording: Bool { recording }
28 public var isRecordingNewNote: Bool { recording }
29 public var elapsedTime: Double { elapsed }
30 public var icon: NSImage? { NSImage(systemSymbolName: "mic.fill", accessibilityDescription: "Transcribing") }
31 public var existingTranscript = ""
32 public private(set) var transcriptTimeOffset: TimeInterval = 0
33 public var latestTranscriptDelta: String {
34 #if !SWIFT_PACKAGE
35 return transcriptValue.tentative
36 #else
37 return transcription
38 #endif
39 }
40 public var accumulatedTranscript: String {
41 #if !SWIFT_PACKAGE
42 return [existingTranscript, transcriptValue.text].filter { !$0.isEmpty }.joined(separator: " ")
43 #else
44 return transcription
45 #endif
46 }
47 public var onTranscript: ((LocalTranscript) -> Void)?
48 public var speechLocale = Locale(identifier: "en-US")
49 #if DEBUG && !SWIFT_PACKAGE
50 // Exercise the real start route without requesting microphone access in UI tests.
51 var simulatedStart: (@MainActor (URL, UUID, Bool) async throws -> Void)?
52 private var simulatedSession = false
53 func beginSimulatedLiveTranscription(_ snapshot: LocalTranscript) {
54 simulatedSession = true; recording = true; paused = false; elapsed = 32; currentAudioLevel = 0.12
55 transcriptTimeOffset = existingUtterances.compactMap(\.end).max() ?? 0
56 accept(snapshot)
57 }
58 func publishSimulatedLiveTranscript(_ snapshot: LocalTranscript) {
59 guard simulatedSession, recording else { return }
60 accept(snapshot)
61 }
62 #endif
63 public init() {}
64 private func accept(_ value: LocalTranscript) {
65 transcription = value.displayText
66 #if !SWIFT_PACKAGE
67 transcriptValue = value
68 #endif
69 onTranscript?(value)
70 }
71
72 public func start(root: URL, noteID: UUID, systemAudio: Bool) async throws {
73 guard !recording, !isBusy else { throw LocalError.message("A transcription session is already in progress.") }
74 starting = true
75 defer { starting = false }
76 #if DEBUG && !SWIFT_PACKAGE
77 if let simulatedStart { try await simulatedStart(root, noteID, systemAudio); return }
78 #endif
79 guard await Self.authorizeMicrophone(status: AVCaptureDevice.authorizationStatus(for: .audio), request: {
80 await AVCaptureDevice.requestAccess(for: .audio)
81 }) else {
82 throw LocalError.message("Microphone access was denied. Enable it in System Settings → Privacy & Security → Microphone.")
83 }
84 self.systemAudio = systemAudio
85 transcriptTimeOffset = 0
86 #if !SWIFT_PACKAGE
87 // Continue after the note's existing timestamps.
88 transcriptTimeOffset = existingUtterances.compactMap(\.end).max() ?? 0
89 #endif
90 elapsed = 0; previousElapsed = 0; errorMessage = nil
91 accept(LocalTranscript())
92 // Audio is never saved, so capture without live speech would produce nothing.
93 do {
94 liveSpeech = try await LiveSpeechSession.start(locale: speechLocale) { [weak self] value in
95 await MainActor.run { self?.accept(value) }
96 }
97 } catch {
98 throw LocalError.message("Live transcription unavailable: \(error.localizedDescription)")
99 }
100 do { try startSegment() } catch {
101 await liveSpeech?.cancel(); liveSpeech = nil; throw error
102 }
103 recording = true; paused = false
104 NotificationCenter.default.post(name: .processTapRecordingStateChanged, object: self)
105 timer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { [weak self] _ in
106 Task { @MainActor in
107 guard let self, let started = self.startedAt, !self.paused else { return }
108 self.elapsed = self.previousElapsed + Date().timeIntervalSince(started)
109 }
110 }
111 }
112 // macOS owns the grant. Never cache it in preferences or request it again
113 // after a grant/denial; re-read the system state when starting capture.
114 static func authorizeMicrophone(status: AVAuthorizationStatus, request: () async -> Bool) async -> Bool {
115 switch status {
116 case .authorized: return true
117 case .notDetermined: return await request()
118 case .denied, .restricted: return false
119 @unknown default: return false
120 }
121 }
122 private func startSegment() throws {
123 guard let live = liveSpeech else { throw LocalError.message("No transcription session.") }
124 do {
125 if systemAudio {
126 let tap = ProcessTap()
127 self.tap = tap
128 tap.activate()
129 guard tap.errorMessage == nil, var description = tap.aggregateDeviceStreamDescription,
130 let format = AVAudioFormat(streamDescription: &description) else {
131 throw LocalError.message(tap.errorMessage ?? "System audio capture is unavailable.")
132 }
133 try tap.run(on: queue, ioBlock: { [weak self] _, input, _, _, _ in
134 do {
135 let data = try Self.mix(input, format: format)
136 live.append(data, sampleRate: format.sampleRate)
137 let peak = data.withUnsafeBytes { bytes in bytes.bindMemory(to: Float.self).reduce(Float(0)) { max($0, abs($1)) } }
138 Task { @MainActor [weak self] in self?.currentAudioLevel = peak }
139 } catch {
140 Task { @MainActor [weak self] in self?.captureFailed(error) }
141 }
142 }, invalidationHandler: { _ in })
143 } else {
144 let engine = AVAudioEngine()
145 self.engine = engine
146 let input = engine.inputNode
147 let format = input.outputFormat(forBus: 0)
148 guard format.sampleRate > 0, format.channelCount > 0 else {
149 throw LocalError.message("No microphone input is available.")
150 }
151 input.installTap(onBus: 0, bufferSize: 4096, format: format) { [weak self] buffer, _ in
152 do {
153 let data = try Self.mix(UnsafePointer(buffer.audioBufferList), format: format)
154 live.append(data, sampleRate: format.sampleRate)
155 let peak = data.withUnsafeBytes { bytes in bytes.bindMemory(to: Float.self).reduce(Float(0)) { max($0, abs($1)) } }
156 Task { @MainActor [weak self] in self?.currentAudioLevel = peak }
157 } catch {
158 Task { @MainActor [weak self] in self?.captureFailed(error) }
159 }
160 }
161 try engine.start()
162 }
163 startedAt = Date()
164 } catch {
165 stopCapture(); throw error
166 }
167 }
168 private func captureFailed(_ error: Error) {
169 guard recording else { return }
170 errorMessage = "Capture stopped: \(error.localizedDescription). Words already transcribed are saved."
171 // Stop input immediately, but retain the active session until its owner
172 // finalizes speech and releases recording ownership. Marking it idle here
173 // would allow a new recording to replace state before the queued stop runs.
174 stopCapture()
175 Task {
176 #if !SWIFT_PACKAGE
177 if let owner = JotleyAppDelegate.shared?.recordingNotesViewModel { await owner.stopRecording() }
178 else { _ = await stop() }
179 #else
180 _ = await stop()
181 #endif
182 }
183 }
184 public func togglePause() throws {
185 guard recording, !isBusy else { return }
186 #if DEBUG && !SWIFT_PACKAGE
187 if simulatedSession { paused.toggle(); return }
188 #endif
189 if paused { try startSegment(); paused = false }
190 else {
191 stopCapture()
192 previousElapsed = elapsed; paused = true
193 }
194 }
195 private func stopCapture() {
196 if let startedAt { elapsed = previousElapsed + Date().timeIntervalSince(startedAt) }
197 startedAt = nil
198 tap?.invalidate(); tap = nil
199 engine?.stop(); engine?.inputNode.removeTap(onBus: 0); engine = nil
200 queue.sync {} // All capture callbacks finish before speech input ends.
201 }
202 public func stopCaptureSession() {
203 #if DEBUG && !SWIFT_PACKAGE
204 simulatedSession = false
205 #endif
206 stopCapture(); timer?.invalidate(); timer = nil
207 recording = false; paused = false
208 NotificationCenter.default.post(name: .processTapRecordingStateChanged, object: self)
209 }
210
211 public func stop() async -> String {
212 guard !finishing else { return transcription }
213 finishing = true
214 defer { finishing = false }
215 stopCaptureSession()
216 if let live = liveSpeech {
217 liveSpeech = nil
218 do { accept(try await live.finish()) }
219 catch { errorMessage = "Live transcription could not finish: \(error.localizedDescription). Words already transcribed are saved." }
220 }
221 currentAudioLevel = 0
222 return transcription
223 }
224 #if !SWIFT_PACKAGE
225 var existingUtterances: [TranscriptUtterance] = []
226 var transcriptUtterances: [TranscriptUtterance] {
227 return existingUtterances + transcriptValue.utterances.map { TranscriptUtterance(text: $0.text, start: transcriptTimeOffset + $0.start, end: transcriptTimeOffset + $0.end) }
228 }
229 var latestTranscriptTimestamp: String? {
230 guard let start = transcriptValue.tentativeStart else { return nil }
231 return TranscriptUtterance(text: transcriptValue.tentative, start: transcriptTimeOffset + start).timestampLabel
232 }
233 private var transcriptValue = LocalTranscript()
234 #endif
235
236 nonisolated private static func mix(_ input: UnsafePointer<AudioBufferList>, format: AVAudioFormat) throws -> Data {
237 let buffers = UnsafeMutableAudioBufferListPointer(UnsafeMutablePointer(mutating: input))
238 let bytes: Int
239 switch format.commonFormat {
240 case .pcmFormatFloat32: bytes = 4
241 case .pcmFormatInt16: bytes = 2
242 case .pcmFormatInt32: bytes = 4
243 default: throw LocalError.message("Unsupported capture sample format.")
244 }
245 let frameCount = buffers.map { Int($0.mDataByteSize) / (bytes * max(1, Int($0.mNumberChannels))) }.max() ?? 0
246 var samples = [Float](repeating: 0, count: frameCount)
247 var contributors = [Int](repeating: 0, count: frameCount)
248 for buffer in buffers {
249 guard let data = buffer.mData else { continue }
250 let channels = max(1, Int(buffer.mNumberChannels))
251 let frames = Int(buffer.mDataByteSize) / (bytes * channels)
252 for frame in 0..<frames {
253 var sum: Float = 0
254 for channel in 0..<channels {
255 let index = frame * channels + channel
256 switch format.commonFormat {
257 case .pcmFormatFloat32: sum += data.assumingMemoryBound(to: Float.self)[index]
258 case .pcmFormatInt16: sum += Float(data.assumingMemoryBound(to: Int16.self)[index]) / 32768
259 case .pcmFormatInt32: sum += Float(data.assumingMemoryBound(to: Int32.self)[index]) / 2147483648
260 default: break
261 }
262 }
263 samples[frame] += sum / Float(channels); contributors[frame] += 1
264 }
265 }
266 for frame in 0..<frameCount where contributors[frame] > 0 { samples[frame] /= Float(contributors[frame]) }
267 return samples.withUnsafeBufferPointer { Data(buffer: $0) }
268 }
269}