Branchwell

Voxley / app · voxley.si / Sources / Voxley / LiveDictation.swift

1import AVFoundation
2import Speech
3
4@MainActor
5final class LiveDictation {
6 private let engine = AVAudioEngine()
7 private var analyzer: SpeechAnalyzer?
8 private var continuation: AsyncThrowingStream<AnalyzerInput, Error>.Continuation?
9 private var resultTask: Task<String, Error>?
10 private var analysisTask: Task<Void, Error>?
11 private var started: ContinuousClock.Instant?
12 private var hasTap = false
13
14 static func requestMicrophone() async -> Bool {
15 switch AVCaptureDevice.authorizationStatus(for: .audio) {
16 case .authorized: true
17 case .notDetermined: await AVCaptureDevice.requestAccess(for: .audio)
18 default: false
19 }
20 }
21
22 func start(
23 module: SpeechTranscriber, words: [String],
24 update: @escaping @Sendable (String) async -> Void,
25 meter: @escaping @Sendable (WaveformFrame) -> Void
26 ) async throws {
27 let input = engine.inputNode
28 let natural = input.outputFormat(forBus: 0)
29 guard natural.sampleRate > 0, natural.channelCount > 0,
30 let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [module], considering: natural)
31 else { throw VoxleyError.microphoneInput }
32 try Task.checkCancellation()
33
34 let analyzer = SpeechAnalyzer(modules: [module])
35 self.analyzer = analyzer
36 try await AppleModels.configure(analyzer, words: words)
37 try Task.checkCancellation()
38
39 let (stream, continuation) = AsyncThrowingStream<AnalyzerInput, Error>.makeStream(
40 bufferingPolicy: .bufferingOldest(128)
41 )
42 self.continuation = continuation
43 resultTask = Task { try await AppleModels.collect(module, update: update) }
44 let tap = try AudioTap(input: natural, output: format, continuation: continuation, meter: meter)
45 input.installTap(onBus: 0, bufferSize: 2048, format: nil, block: tap.block)
46 hasTap = true
47 try engine.start()
48 started = .now
49 analysisTask = Task { try await analyzer.start(inputSequence: stream) }
50 }
51
52 func finish() async throws -> String {
53 guard let analyzer, let resultTask, let analysisTask, let started,
54 started.duration(to: .now) > .milliseconds(200) else {
55 await cancel()
56 throw VoxleyError.emptyAudio
57 }
58 stopCapture()
59 do {
60 try await analysisTask.value
61 try await analyzer.finalizeAndFinishThroughEndOfInput()
62 return try await resultTask.value
63 } catch {
64 await cancel()
65 throw error
66 }
67 }
68
69 func cancel() async {
70 stopCapture()
71 analysisTask?.cancel()
72 resultTask?.cancel()
73 await analyzer?.cancelAndFinishNow()
74 }
75
76 private func stopCapture() {
77 engine.stop()
78 if hasTap {
79 engine.inputNode.removeTap(onBus: 0)
80 hasTap = false
81 }
82 continuation?.finish()
83 }
84}
85
86// AVAudioEngine invokes one tap serially. Only that tap touches the converter.
87final class AudioTap: @unchecked Sendable {
88 private let converter: AVAudioConverter
89 private let output: AVAudioFormat
90 private let continuation: AsyncThrowingStream<AnalyzerInput, Error>.Continuation
91 private let meter: (@Sendable (WaveformFrame) -> Void)?
92 private var waveform: MicrophoneWaveform
93
94 init(input: AVAudioFormat, output: AVAudioFormat,
95 continuation: AsyncThrowingStream<AnalyzerInput, Error>.Continuation,
96 meter: (@Sendable (WaveformFrame) -> Void)? = nil) throws {
97 guard let converter = AVAudioConverter(from: input, to: output) else {
98 throw VoxleyError.microphoneInput
99 }
100 self.converter = converter
101 self.output = output
102 self.continuation = continuation
103 self.meter = meter
104 waveform = MicrophoneWaveform(sampleRate: input.sampleRate)
105 }
106
107 var block: AVAudioNodeTapBlock {
108 { [self] input, time in convert(input, time: time) }
109 }
110
111 private func convert(_ input: AVAudioPCMBuffer, time: AVAudioTime) {
112 updateMeter(input, time: time)
113 let count = ceil(Double(input.frameLength) * output.sampleRate / input.format.sampleRate) + 16
114 guard let buffer = AVAudioPCMBuffer(pcmFormat: output, frameCapacity: AVAudioFrameCount(count)) else {
115 continuation.finish(throwing: VoxleyError.microphoneInput)
116 return
117 }
118 var error: NSError?
119 let feed = InputBuffer(input)
120 let status = converter.convert(to: buffer, error: &error) { _, flag in
121 feed.provide(flag)
122 }
123 if let error {
124 continuation.finish(throwing: error)
125 } else if status == .error {
126 continuation.finish(throwing: VoxleyError.microphoneInput)
127 } else if buffer.frameLength > 0,
128 case .dropped = continuation.yield(AnalyzerInput(buffer: buffer)) {
129 continuation.finish(throwing: VoxleyError.audioOverrun)
130 }
131 }
132
133 private func updateMeter(_ input: AVAudioPCMBuffer, time: AVAudioTime) {
134 guard let meter, let samples = input.floatChannelData?[0] else { return }
135 let bufferStart = time.isHostTimeValid
136 ? AVAudioTime.seconds(forHostTime: time.hostTime)
137 : WaveformFrame.hostTime - Double(input.frameLength) / input.format.sampleRate
138 if let frame = waveform.append(samples, count: Int(input.frameLength), stride: input.stride, bufferStart: bufferStart) {
139 meter(frame)
140 }
141 }
142}
143
144// The converter requests the input synchronously on the tap's call stack.
145private final class InputBuffer: @unchecked Sendable {
146 private var buffer: AVAudioPCMBuffer?
147
148 init(_ buffer: AVAudioPCMBuffer) { self.buffer = buffer }
149
150 func provide(_ status: UnsafeMutablePointer<AVAudioConverterInputStatus>) -> AVAudioPCMBuffer? {
151 let next = buffer
152 buffer = nil
153 status.pointee = next == nil ? .noDataNow : .haveData
154 return next
155 }
156}