-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickVoiceCore.swift
More file actions
259 lines (217 loc) · 8.53 KB
/
QuickVoiceCore.swift
File metadata and controls
259 lines (217 loc) · 8.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import Foundation
import AVFoundation
import AppKit
import ApplicationServices
final class AudioRecorder: NSObject {
private var recorder: AVAudioRecorder?
private(set) var isRecording = false
let outputURL: URL = {
let tmp = FileManager.default.temporaryDirectory
return tmp.appendingPathComponent("quickvoice_recording.wav")
}()
func startRecording() throws {
let settings: [String: Any] = [
AVFormatIDKey: Int(kAudioFormatLinearPCM),
AVSampleRateKey: 16000.0,
AVNumberOfChannelsKey: 1,
AVLinearPCMBitDepthKey: 16,
AVLinearPCMIsFloatKey: false,
AVLinearPCMIsBigEndianKey: false,
]
let recorder = try AVAudioRecorder(url: outputURL, settings: settings)
recorder.delegate = self
guard recorder.record() else {
throw RecorderError.failedToStart
}
self.recorder = recorder
isRecording = true
}
func stopRecording() -> URL? {
guard isRecording, let recorder else { return nil }
recorder.stop()
self.recorder = nil
isRecording = false
return outputURL
}
enum RecorderError: LocalizedError {
case failedToStart
var errorDescription: String? {
switch self {
case .failedToStart:
return "Failed to start audio recording."
}
}
}
}
extension AudioRecorder: AVAudioRecorderDelegate {
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
if !flag {
isRecording = false
}
}
}
// MARK: - Transcriber
final class Transcriber {
private let parakeetPath = "/Users/sunil/.local/bin/parakeet-mlx"
func transcribe(audioURL: URL) async throws -> String {
let outputDir = audioURL.deletingLastPathComponent().path
let result = try await runProcess(
executablePath: parakeetPath,
arguments: [
"--output-format", "txt",
"--output-dir", outputDir,
"--fp32",
audioURL.path
]
)
if result.exitCode != 0 {
throw TranscriberError.processFailure(result.stderr)
}
let txtURL = audioURL.deletingPathExtension().appendingPathExtension("txt")
guard FileManager.default.fileExists(atPath: txtURL.path) else {
throw TranscriberError.noOutput
}
let text = try String(contentsOf: txtURL, encoding: .utf8)
.trimmingCharacters(in: .whitespacesAndNewlines)
try? FileManager.default.removeItem(at: txtURL)
return text
}
private func runProcess(executablePath: String, arguments: [String]) async throws -> ProcessResult {
try await withCheckedThrowingContinuation { continuation in
let process = Process()
process.executableURL = URL(fileURLWithPath: executablePath)
process.arguments = arguments
let stdoutPipe = Pipe()
let stderrPipe = Pipe()
process.standardOutput = stdoutPipe
process.standardError = stderrPipe
process.terminationHandler = { proc in
let stdout = String(data: stdoutPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
let stderr = String(data: stderrPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
continuation.resume(returning: ProcessResult(
exitCode: proc.terminationStatus,
stdout: stdout,
stderr: stderr
))
}
do {
try process.run()
} catch {
continuation.resume(throwing: error)
}
}
}
struct ProcessResult {
let exitCode: Int32
let stdout: String
let stderr: String
}
enum TranscriberError: LocalizedError {
case processFailure(String)
case noOutput
var errorDescription: String? {
switch self {
case .processFailure(let stderr):
return "Transcription failed: \(stderr)"
case .noOutput:
return "No transcription output file produced."
}
}
}
}
// MARK: - MediaController
/// Pauses media playback when recording starts, resumes when recording ends.
/// Uses the MediaRemote private framework to check playback state before acting,
/// preventing Apple Music from launching when nothing is playing.
final class MediaController {
static let shared = MediaController()
private typealias MRSendCommandFn = @convention(c) (UInt32, CFDictionary?) -> Bool
private typealias MRIsPlayingFn = @convention(c) (DispatchQueue, @escaping (Bool) -> Void) -> Void
private var sendCommand: MRSendCommandFn?
private var getIsPlaying: MRIsPlayingFn?
private var didPauseMedia = false
private init() {
guard let handle = dlopen(
"/System/Library/PrivateFrameworks/MediaRemote.framework/MediaRemote",
RTLD_NOW
) else { return }
if let ptr = dlsym(handle, "MRMediaRemoteSendCommand") {
sendCommand = unsafeBitCast(ptr, to: MRSendCommandFn.self)
}
if let ptr = dlsym(handle, "MRMediaRemoteGetNowPlayingApplicationIsPlaying") {
getIsPlaying = unsafeBitCast(ptr, to: MRIsPlayingFn.self)
}
}
func pauseMedia() {
guard let getIsPlaying, let sendCommand else { return }
let semaphore = DispatchSemaphore(value: 0)
var isPlaying = false
getIsPlaying(DispatchQueue.global(qos: .userInitiated)) { playing in
isPlaying = playing
semaphore.signal()
}
guard semaphore.wait(timeout: .now() + 0.5) == .success, isPlaying else { return }
didPauseMedia = sendCommand(1, nil) // kMRPause
}
func resumeMedia() {
guard didPauseMedia, let sendCommand else { return }
didPauseMedia = false
_ = sendCommand(0, nil) // kMRPlay
}
}
// MARK: - CursorPaster
/// Pastes text at the current cursor position by temporarily placing it on the
/// clipboard, simulating Cmd+V, then restoring the original clipboard contents.
/// Uses .hidSystemState / .cghidEventTap (matches open-wispr's working pattern)
/// to avoid Fn key ghosting issues with .combinedSessionState.
enum CursorPaster {
static func pasteAtCursor(_ text: String) {
guard AXIsProcessTrusted() else {
NSLog("QuickVoice: Accessibility not granted, cannot paste. Relaunch after granting permission.")
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(text, forType: .string)
return
}
let pasteboard = NSPasteboard.general
// Save current clipboard
var savedContents: [(NSPasteboard.PasteboardType, Data)] = []
for item in pasteboard.pasteboardItems ?? [] {
for type in item.types {
if let data = item.data(forType: type) {
savedContents.append((type, data))
}
}
}
// Set transcript to clipboard, marked as transient for clipboard managers
pasteboard.clearContents()
pasteboard.setString(text, forType: .string)
pasteboard.setData(
Data(),
forType: NSPasteboard.PasteboardType("org.nspasteboard.TransientType")
)
let changeCountAfterSet = pasteboard.changeCount
// Simulate Cmd+V after a brief delay for clipboard to settle
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
simulatePaste()
}
// Restore original clipboard after paste completes
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
guard pasteboard.changeCount == changeCountAfterSet else { return }
if !savedContents.isEmpty {
pasteboard.clearContents()
for (type, data) in savedContents {
pasteboard.setData(data, forType: type)
}
}
}
}
private static func simulatePaste() {
let source = CGEventSource(stateID: .hidSystemState)
let vDown = CGEvent(keyboardEventSource: source, virtualKey: 0x09, keyDown: true)
let vUp = CGEvent(keyboardEventSource: source, virtualKey: 0x09, keyDown: false)
vDown?.flags = .maskCommand
vUp?.flags = .maskCommand
vDown?.post(tap: .cghidEventTap)
vUp?.post(tap: .cghidEventTap)
}
}