hop
Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.
Brought by drakestapleton
hop / Sources / SpeechEngine.swift
| 1 | import AVFoundation |
| 2 | import CoreAudio |
| 3 | import Speech |
| 4 | |
| 5 | /// Speech to text on this Mac with Apple's on-device recogniser. This part sends no audio and no text anywhere; |
| 6 | /// what happens to the text afterwards is decided by Dictation (typed at the cursor, or given to Ask or Agent). |
| 7 | /// Measured on 2,436 of the author's real dictations: 6.5% of words differ from the cloud service it replaces. |
| 8 | @MainActor |
| 9 | final class SpeechEngine { |
| 10 | enum Source { case microphone; case file(URL) } |
| 11 | enum Failure: LocalizedError { |
| 12 | case noMicrophone, microphoneDenied, noModel |
| 13 | var errorDescription: String? { |
| 14 | switch self { |
| 15 | case .noMicrophone: "No microphone found." |
| 16 | case .microphoneDenied: "Hop is not allowed to use the microphone. Turn it on in System Settings, Privacy & Security, Microphone." |
| 17 | case .noModel: "The speech model for this language is not available on this Mac." |
| 18 | } |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | var locale = Locale(identifier: "en-US") |
| 23 | var hints: [String] = [] // names and terms to listen for |
| 24 | var onPartial: (String) -> Void = { _ in } // text so far, while speaking |
| 25 | var onLevel: (Float) -> Void = { _ in } // 0...1 loudness, for the meter |
| 26 | |
| 27 | private var audio: AVAudioEngine? |
| 28 | private var analyzer: SpeechAnalyzer? |
| 29 | private var input: AsyncStream<AnalyzerInput>.Continuation? |
| 30 | private var results: Task<String, Never>? |
| 31 | private var feeder: Task<Void, Never>? |
| 32 | private var format: AVAudioFormat? |
| 33 | private(set) var ready = false |
| 34 | |
| 35 | static var microphoneAllowed: Bool { AVCaptureDevice.authorizationStatus(for: .audio) == .authorized } |
| 36 | static var microphoneUndecided: Bool { AVCaptureDevice.authorizationStatus(for: .audio) == .notDetermined } |
| 37 | static func askForMicrophone() async -> Bool { await AVCaptureDevice.requestAccess(for: .audio) } |
| 38 | |
| 39 | /// Fetches Apple's speech model the first time (from Apple, once) and loads it, so the first words are not lost. |
| 40 | func prepare() async throws { |
| 41 | guard !ready else { return } |
| 42 | let t = SpeechTranscriber(locale: locale, transcriptionOptions: [], reportingOptions: [.volatileResults], attributeOptions: []) |
| 43 | if await AssetInventory.status(forModules: [t]) != .installed { |
| 44 | guard let req = try await AssetInventory.assetInstallationRequest(supporting: [t]) else { throw Failure.noModel } |
| 45 | try await req.downloadAndInstall() |
| 46 | } |
| 47 | format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [t]) |
| 48 | let warm = SpeechAnalyzer(modules: [t], options: .init(priority: .userInitiated, modelRetention: .processLifetime)) |
| 49 | try await warm.prepareToAnalyze(in: format) |
| 50 | ready = true |
| 51 | } |
| 52 | |
| 53 | func start(_ source: Source) async throws { |
| 54 | try await prepare() |
| 55 | guard let format else { throw Failure.noModel } |
| 56 | let t = SpeechTranscriber(locale: locale, transcriptionOptions: [], reportingOptions: [.volatileResults], attributeOptions: []) |
| 57 | let ctx = AnalysisContext() |
| 58 | if !hints.isEmpty { ctx.contextualStrings[.general] = hints } |
| 59 | let (stream, cont) = AsyncStream<AnalyzerInput>.makeStream() |
| 60 | let a = SpeechAnalyzer(inputSequence: stream, modules: [t], |
| 61 | options: .init(priority: .userInitiated, modelRetention: .processLifetime), analysisContext: ctx) |
| 62 | analyzer = a; input = cont |
| 63 | results = Task { @MainActor [weak self] in |
| 64 | var done = "" |
| 65 | do { |
| 66 | for try await r in t.results { |
| 67 | let piece = String(r.text.characters) |
| 68 | if r.isFinal { done += piece; self?.onPartial(done) } else { self?.onPartial(done + piece) } |
| 69 | } |
| 70 | } catch {} |
| 71 | return done |
| 72 | } |
| 73 | switch source { |
| 74 | case .microphone: try startMicrophone(cont, format) |
| 75 | case .file(let url): feeder = Task.detached { Self.feed(url, into: cont, as: format) } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | /// Stops listening and returns everything that was said. |
| 80 | func finish() async -> String { |
| 81 | stopMicrophone() |
| 82 | await feeder?.value; feeder = nil |
| 83 | input?.finish(); input = nil |
| 84 | // Never leave the user waiting: if the recogniser does not wrap up in 5 seconds, take what it has. |
| 85 | let a = analyzer |
| 86 | let guardrail = Task { try? await Task.sleep(nanoseconds: 5_000_000_000); if !Task.isCancelled { await a?.cancelAndFinishNow() } } |
| 87 | try? await a?.finalizeAndFinishThroughEndOfInput() |
| 88 | guardrail.cancel() |
| 89 | let text = await results?.value ?? "" |
| 90 | analyzer = nil; results = nil |
| 91 | return text.trimmingCharacters(in: .whitespacesAndNewlines) |
| 92 | } |
| 93 | |
| 94 | func cancel() async { |
| 95 | stopMicrophone() |
| 96 | feeder?.cancel(); feeder = nil |
| 97 | input?.finish(); input = nil |
| 98 | await analyzer?.cancelAndFinishNow() |
| 99 | results?.cancel(); analyzer = nil; results = nil |
| 100 | } |
| 101 | |
| 102 | // MARK: Microphone |
| 103 | private func startMicrophone(_ cont: AsyncStream<AnalyzerInput>.Continuation, _ target: AVAudioFormat) throws { |
| 104 | guard Self.microphoneAllowed else { throw Failure.microphoneDenied } |
| 105 | let engine = AVAudioEngine() |
| 106 | let node = engine.inputNode |
| 107 | let inFormat = node.outputFormat(forBus: 0) |
| 108 | guard inFormat.sampleRate > 0, inFormat.channelCount > 0, let conv = AVAudioConverter(from: inFormat, to: target) else { throw Failure.noMicrophone } |
| 109 | let level = onLevel |
| 110 | node.installTap(onBus: 0, bufferSize: 2048, format: inFormat) { buf, _ in |
| 111 | if let ch = buf.floatChannelData?[0], buf.frameLength > 0 { |
| 112 | var sum: Float = 0 |
| 113 | for i in 0..<Int(buf.frameLength) { sum += ch[i] * ch[i] } |
| 114 | let rms = (sum / Float(buf.frameLength)).squareRoot() |
| 115 | let shown = min(1, max(0, (20 * log10(max(rms, 1e-6)) + 55) / 45)) |
| 116 | DispatchQueue.main.async { level(shown) } |
| 117 | } |
| 118 | if let out = Self.convert(buf, with: conv, to: target) { cont.yield(AnalyzerInput(buffer: out)) } |
| 119 | } |
| 120 | engine.prepare() |
| 121 | try engine.start() |
| 122 | audio = engine |
| 123 | } |
| 124 | |
| 125 | /// Opens the microphone for under a second and confirms sound arrives in the form the recogniser needs. |
| 126 | /// Returns nil when it works, otherwise what went wrong. Nothing is kept. |
| 127 | func microphoneCheck() async -> String? { |
| 128 | do { try await prepare() } catch { return error.localizedDescription } |
| 129 | guard Self.microphoneAllowed, let target = format else { return Failure.microphoneDenied.localizedDescription } |
| 130 | let engine = AVAudioEngine() |
| 131 | let node = engine.inputNode |
| 132 | let inFormat = node.outputFormat(forBus: 0) |
| 133 | guard inFormat.sampleRate > 0, inFormat.channelCount > 0, let conv = AVAudioConverter(from: inFormat, to: target) else { return Failure.noMicrophone.localizedDescription } |
| 134 | let frames = FrameCount() |
| 135 | node.installTap(onBus: 0, bufferSize: 2048, format: inFormat) { buf, _ in |
| 136 | if let out = Self.convert(buf, with: conv, to: target) { frames.add(Int(out.frameLength)) } |
| 137 | } |
| 138 | engine.prepare() |
| 139 | do { try engine.start() } catch { node.removeTap(onBus: 0); return "The microphone would not start: \(error.localizedDescription)" } |
| 140 | try? await Task.sleep(nanoseconds: 700_000_000) |
| 141 | node.removeTap(onBus: 0); engine.stop() |
| 142 | return frames.total > 0 ? nil : "No sound arrived from the microphone." |
| 143 | } |
| 144 | private final class FrameCount: @unchecked Sendable { |
| 145 | private let lock = NSLock(); private var n = 0 |
| 146 | func add(_ k: Int) { lock.lock(); n += k; lock.unlock() } |
| 147 | var total: Int { lock.lock(); defer { lock.unlock() }; return n } |
| 148 | } |
| 149 | |
| 150 | private func stopMicrophone() { |
| 151 | guard let engine = audio else { return } |
| 152 | engine.inputNode.removeTap(onBus: 0) |
| 153 | engine.stop() |
| 154 | audio = nil |
| 155 | } |
| 156 | |
| 157 | // MARK: Audio plumbing |
| 158 | nonisolated private static func convert(_ buf: AVAudioPCMBuffer, with conv: AVAudioConverter, to target: AVAudioFormat) -> AVAudioPCMBuffer? { |
| 159 | let cap = AVAudioFrameCount(Double(buf.frameLength) * target.sampleRate / buf.format.sampleRate) + 256 |
| 160 | guard let out = AVAudioPCMBuffer(pcmFormat: target, frameCapacity: cap) else { return nil } |
| 161 | var given = false |
| 162 | var err: NSError? |
| 163 | conv.convert(to: out, error: &err) { _, status in |
| 164 | if given { status.pointee = .noDataNow; return nil } |
| 165 | given = true; status.pointee = .haveData; return buf |
| 166 | } |
| 167 | return err == nil && out.frameLength > 0 ? out : nil |
| 168 | } |
| 169 | |
| 170 | /// Feeds a recording through the same live path the microphone uses (tests and measurements). |
| 171 | nonisolated private static func feed(_ url: URL, into cont: AsyncStream<AnalyzerInput>.Continuation, as target: AVAudioFormat) { |
| 172 | guard let file = try? AVAudioFile(forReading: url), let conv = AVAudioConverter(from: file.processingFormat, to: target) else { return } |
| 173 | while !Task.isCancelled, let buf = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: 4096), |
| 174 | (try? file.read(into: buf)) != nil, buf.frameLength > 0 { |
| 175 | if let out = convert(buf, with: conv, to: target) { cont.yield(AnalyzerInput(buffer: out)) } |
| 176 | } |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | /// Mutes the Mac's sound output while dictating (so music or a video does not end up in the text), then puts it back. |
| 181 | enum SystemAudio { |
| 182 | private static func defaultOutput() -> AudioDeviceID? { |
| 183 | var id = AudioDeviceID(0), size = UInt32(MemoryLayout<AudioDeviceID>.size) |
| 184 | var addr = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDefaultOutputDevice, |
| 185 | mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain) |
| 186 | return AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &addr, 0, nil, &size, &id) == noErr && id != 0 ? id : nil |
| 187 | } |
| 188 | private static var muteAddress = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyMute, |
| 189 | mScope: kAudioDevicePropertyScopeOutput, mElement: kAudioObjectPropertyElementMain) |
| 190 | static var muted: Bool? { |
| 191 | guard let dev = defaultOutput() else { return nil } |
| 192 | var v = UInt32(0), size = UInt32(MemoryLayout<UInt32>.size) |
| 193 | return AudioObjectGetPropertyData(dev, &muteAddress, 0, nil, &size, &v) == noErr ? v != 0 : nil |
| 194 | } |
| 195 | @discardableResult static func setMuted(_ on: Bool) -> Bool { |
| 196 | guard let dev = defaultOutput() else { return false } |
| 197 | var v = UInt32(on ? 1 : 0) |
| 198 | return AudioObjectSetPropertyData(dev, &muteAddress, 0, nil, UInt32(MemoryLayout<UInt32>.size), &v) == noErr |
| 199 | } |
| 200 | } |