| 1 | //! `SFSpeechRecognizer`, recognizing on the device only. |
| 2 | |
| 3 | use std::{cell::RefCell, rc::Rc}; |
| 4 | |
| 5 | use anyhow::anyhow; |
| 6 | use block2::RcBlock; |
| 7 | use gpui::{App, SharedString, Task}; |
| 8 | use objc2::{AnyThread as _, rc::Retained, runtime::NSObjectProtocol as _, sel}; |
| 9 | use objc2_av_foundation::{AVAuthorizationStatus, AVCaptureDevice, AVMediaTypeAudio}; |
| 10 | use objc2_avf_audio::{AVAudioCommonFormat, AVAudioFormat, AVAudioPCMBuffer}; |
| 11 | use objc2_foundation::{NSBundle, NSError, NSLocale, NSString}; |
| 12 | use objc2_speech::{ |
| 13 | SFSpeechAudioBufferRecognitionRequest, SFSpeechRecognitionResult, SFSpeechRecognitionTask, |
| 14 | SFSpeechRecognizer, SFSpeechRecognizerAuthorizationStatus, |
| 15 | }; |
| 16 | use smol::channel::{Receiver, Sender, unbounded}; |
| 17 | |
| 18 | use crate::speech::{AudioFormat, RecognitionSession, SpeechError, SpeechRecognizer, SpeechSink}; |
| 19 | |
| 20 | /// Without this `Info.plist` key, asking for speech recognition access |
| 21 | /// terminates the process. |
| 22 | const USAGE_DESCRIPTION_KEY: &str = "NSSpeechRecognitionUsageDescription"; |
| 23 | |
| 24 | /// The error `SFSpeechRecognizer` reports when the audio held no speech. |
| 25 | const NO_SPEECH_DOMAIN: &str = "kAFAssistantErrorDomain"; |
| 26 | const NO_SPEECH_CODE: isize = 1110; |
| 27 | |
| 28 | pub(super) struct PlatformRecognizer { |
| 29 | /// `None` when the locale has no recognizer or the application cannot ask |
| 30 | /// for access. |
| 31 | recognizer: Option<Retained<SFSpeechRecognizer>>, |
| 32 | } |
| 33 | |
| 34 | impl PlatformRecognizer { |
| 35 | pub(super) fn new(locale: Option<SharedString>) -> Self { |
| 36 | if !has_usage_description() { |
| 37 | tracing::warn!( |
| 38 | "speech recognition is unavailable: the application's Info.plist has no \ |
| 39 | `{USAGE_DESCRIPTION_KEY}`, and asking for access without it terminates the process" |
| 40 | ); |
| 41 | return Self { recognizer: None }; |
| 42 | } |
| 43 | |
| 44 | let recognizer = match &locale { |
| 45 | Some(locale) => { |
| 46 | let locale = NSLocale::initWithLocaleIdentifier( |
| 47 | NSLocale::alloc(), |
| 48 | &NSString::from_str(locale), |
| 49 | ); |
| 50 | // SAFETY: `locale` is a valid `NSLocale`; the initializer returns |
| 51 | // nil for a locale without a recognizer. |
| 52 | unsafe { SFSpeechRecognizer::initWithLocale(SFSpeechRecognizer::alloc(), &locale) } |
| 53 | } |
| 54 | // SAFETY: plain initializer; returns nil if the system language has |
| 55 | // no recognizer. |
| 56 | None => unsafe { SFSpeechRecognizer::init(SFSpeechRecognizer::alloc()) }, |
| 57 | }; |
| 58 | if recognizer.is_none() { |
| 59 | tracing::warn!( |
| 60 | "speech recognition is unavailable: no recognizer for locale {}", |
| 61 | locale.as_deref().unwrap_or("of the system") |
| 62 | ); |
| 63 | } |
| 64 | |
| 65 | Self { recognizer } |
| 66 | } |
| 67 | |
| 68 | /// The recognizer, if it can recognize on the device. |
| 69 | fn on_device(&self) -> Option<&Retained<SFSpeechRecognizer>> { |
| 70 | self.recognizer |
| 71 | .as_ref() |
| 72 | // SAFETY: plain property reads on a valid recognizer. |
| 73 | .filter(|recognizer| unsafe { |
| 74 | recognizer.isAvailable() && recognizer.supportsOnDeviceRecognition() |
| 75 | }) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | impl SpeechRecognizer for PlatformRecognizer { |
| 80 | fn audio_format(&self) -> AudioFormat { |
| 81 | AudioFormat::default() |
| 82 | } |
| 83 | |
| 84 | fn is_available(&self, _: &App) -> bool { |
| 85 | self.on_device().is_some() && !is_speech_denied(speech_authorization()) |
| 86 | } |
| 87 | |
| 88 | fn start( |
| 89 | &self, |
| 90 | sink: SpeechSink, |
| 91 | cx: &mut App, |
| 92 | ) -> Result<Box<dyn RecognitionSession>, SpeechError> { |
| 93 | let recognizer = self.on_device().ok_or(SpeechError::Unsupported)?.clone(); |
| 94 | let authorization = speech_authorization(); |
| 95 | if is_speech_denied(authorization) { |
| 96 | return Err(SpeechError::PermissionDenied); |
| 97 | } |
| 98 | |
| 99 | let (events, rx) = unbounded(); |
| 100 | let mut recognition = Recognition::new(recognizer, sink, events.clone())?; |
| 101 | if authorization == SFSpeechRecognizerAuthorizationStatus::Authorized { |
| 102 | recognition.begin(cx); |
| 103 | } else { |
| 104 | request_authorization(events); |
| 105 | } |
| 106 | |
| 107 | let recognition = Rc::new(RefCell::new(recognition)); |
| 108 | let task = cx.spawn({ |
| 109 | let recognition = recognition.clone(); |
| 110 | async move |cx| run(recognition, rx, cx).await |
| 111 | }); |
| 112 | |
| 113 | Ok(Box::new(Session { |
| 114 | recognition, |
| 115 | _task: task, |
| 116 | })) |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | /// Whether the user or a policy denied this application the microphone. |
| 121 | /// |
| 122 | /// Capturing without access yields silence rather than an error on macOS, so |
| 123 | /// the [`Microphone`](crate::speech::Microphone) checks this first. |
| 124 | pub(in crate::speech) fn is_microphone_denied() -> bool { |
| 125 | // SAFETY: reading an immutable framework constant. |
| 126 | let Some(audio) = (unsafe { AVMediaTypeAudio }) else { |
| 127 | return false; |
| 128 | }; |
| 129 | // SAFETY: `audio` is one of the two media types the method accepts. |
| 130 | let status = unsafe { AVCaptureDevice::authorizationStatusForMediaType(audio) }; |
| 131 | status == AVAuthorizationStatus::Denied || status == AVAuthorizationStatus::Restricted |
| 132 | } |
| 133 | |
| 134 | fn has_usage_description() -> bool { |
| 135 | NSBundle::mainBundle() |
| 136 | .objectForInfoDictionaryKey(&NSString::from_str(USAGE_DESCRIPTION_KEY)) |
| 137 | .is_some() |
| 138 | } |
| 139 | |
| 140 | fn speech_authorization() -> SFSpeechRecognizerAuthorizationStatus { |
| 141 | // SAFETY: reading the status never prompts, so it is safe without the |
| 142 | // usage description. |
| 143 | unsafe { SFSpeechRecognizer::authorizationStatus() } |
| 144 | } |
| 145 | |
| 146 | fn is_speech_denied(status: SFSpeechRecognizerAuthorizationStatus) -> bool { |
| 147 | status == SFSpeechRecognizerAuthorizationStatus::Denied |
| 148 | || status == SFSpeechRecognizerAuthorizationStatus::Restricted |
| 149 | } |
| 150 | |
| 151 | /// Ask for speech recognition access; the answer arrives as an [`Event`]. |
| 152 | fn request_authorization(events: Sender<Event>) { |
| 153 | let handler = RcBlock::new(move |status: SFSpeechRecognizerAuthorizationStatus| { |
| 154 | _ = events.try_send(Event::Authorized( |
| 155 | status == SFSpeechRecognizerAuthorizationStatus::Authorized, |
| 156 | )); |
| 157 | }); |
| 158 | // SAFETY: only reached with the usage description present (see |
| 159 | // `PlatformRecognizer::new`); the block only sends on a channel, so it may |
| 160 | // run on any queue. |
| 161 | unsafe { SFSpeechRecognizer::requestAuthorization(&handler) }; |
| 162 | } |
| 163 | |
| 164 | /// What the framework reports, sent from its queues to the main thread. |
| 165 | enum Event { |
| 166 | Authorized(bool), |
| 167 | Result { |
| 168 | text: String, |
| 169 | is_final: bool, |
| 170 | /// The result ends an utterance, see [`Recognition::on_result`]. |
| 171 | ends_utterance: bool, |
| 172 | }, |
| 173 | Error { |
| 174 | domain: String, |
| 175 | code: isize, |
| 176 | message: String, |
| 177 | }, |
| 178 | } |
| 179 | |
| 180 | /// Deliver framework events to the recognition until it is done. |
| 181 | async fn run( |
| 182 | recognition: Rc<RefCell<Recognition>>, |
| 183 | events: Receiver<Event>, |
| 184 | cx: &mut gpui::AsyncApp, |
| 185 | ) { |
| 186 | while let Ok(event) = events.recv().await { |
| 187 | let done = cx.update(|cx| recognition.borrow_mut().on_event(event, cx)); |
| 188 | if done { |
| 189 | break; |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | struct Session { |
| 195 | recognition: Rc<RefCell<Recognition>>, |
| 196 | /// Dropping this stops delivering results. |
| 197 | _task: Task<()>, |
| 198 | } |
| 199 | |
| 200 | impl RecognitionSession for Session { |
| 201 | fn push_audio(&mut self, samples: &[i16], _: &mut App) { |
| 202 | self.recognition.borrow_mut().push_audio(samples); |
| 203 | } |
| 204 | |
| 205 | fn finish(&mut self, _: &mut App) { |
| 206 | self.recognition.borrow_mut().finish(); |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | impl Drop for Session { |
| 211 | fn drop(&mut self) { |
| 212 | if let Some(task) = &self.recognition.borrow().task { |
| 213 | // SAFETY: cancelling a valid task; it reports nothing we still read. |
| 214 | unsafe { task.cancel() }; |
| 215 | } |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | struct Recognition { |
| 220 | recognizer: Retained<SFSpeechRecognizer>, |
| 221 | request: Retained<SFSpeechAudioBufferRecognitionRequest>, |
| 222 | format: Retained<AVAudioFormat>, |
| 223 | /// `None` until access is granted. |
| 224 | task: Option<Retained<SFSpeechRecognitionTask>>, |
| 225 | sink: SpeechSink, |
| 226 | events: Sender<Event>, |
| 227 | /// Audio pushed before the task started. |
| 228 | pending: Vec<i16>, |
| 229 | finishing: bool, |
| 230 | done: bool, |
| 231 | /// The text of the last result that ended an utterance, until the next |
| 232 | /// result shows whether the recognizer carries it on. |
| 233 | utterance: Option<String>, |
| 234 | /// The current hypothesis, as the framework reported it. |
| 235 | hypothesis: String, |
| 236 | /// The last character committed as a phrase, to join the next one. |
| 237 | last_committed: Option<char>, |
| 238 | } |
| 239 | |
| 240 | impl Recognition { |
| 241 | fn new( |
| 242 | recognizer: Retained<SFSpeechRecognizer>, |
| 243 | sink: SpeechSink, |
| 244 | events: Sender<Event>, |
| 245 | ) -> Result<Self, SpeechError> { |
| 246 | let format = AudioFormat::default(); |
| 247 | // 16-bit mono is also the request's native format, so appended audio |
| 248 | // needs no conversion. |
| 249 | // SAFETY: a mono PCM format, which the initializer supports. |
| 250 | let format = unsafe { |
| 251 | AVAudioFormat::initWithCommonFormat_sampleRate_channels_interleaved( |
| 252 | AVAudioFormat::alloc(), |
| 253 | AVAudioCommonFormat::PCMFormatInt16, |
| 254 | format.sample_rate().into(), |
| 255 | format.channels().into(), |
| 256 | false, |
| 257 | ) |
| 258 | } |
| 259 | .ok_or_else(|| SpeechError::recognizer(anyhow!("cannot create the audio format")))?; |
| 260 | |
| 261 | // SAFETY: plain initializer and property setters on a fresh request. |
| 262 | let request = unsafe { |
| 263 | let request = SFSpeechAudioBufferRecognitionRequest::new(); |
| 264 | request.setShouldReportPartialResults(true); |
| 265 | // Never send audio to Apple's servers. |
| 266 | request.setRequiresOnDeviceRecognition(true); |
| 267 | // Punctuation needs macOS 13. |
| 268 | if request.respondsToSelector(sel!(setAddsPunctuation:)) { |
| 269 | request.setAddsPunctuation(true); |
| 270 | } |
| 271 | request |
| 272 | }; |
| 273 | |
| 274 | Ok(Self { |
| 275 | recognizer, |
| 276 | request, |
| 277 | format, |
| 278 | task: None, |
| 279 | sink, |
| 280 | events, |
| 281 | pending: Vec::new(), |
| 282 | finishing: false, |
| 283 | done: false, |
| 284 | utterance: None, |
| 285 | hypothesis: String::new(), |
| 286 | last_committed: None, |
| 287 | }) |
| 288 | } |
| 289 | |
| 290 | /// Start recognizing, once access is granted. |
| 291 | fn begin(&mut self, cx: &mut App) { |
| 292 | let events = self.events.clone(); |
| 293 | let handler = RcBlock::new( |
| 294 | move |result: *mut SFSpeechRecognitionResult, error: *mut NSError| { |
| 295 | // SAFETY: the framework passes nil or objects valid for the call. |
| 296 | let (result, error) = unsafe { (result.as_ref(), error.as_ref()) }; |
| 297 | if let Some(result) = result { |
| 298 | // SAFETY: plain property reads on a valid result. |
| 299 | let event = unsafe { |
| 300 | Event::Result { |
| 301 | text: result.bestTranscription().formattedString().to_string(), |
| 302 | is_final: result.isFinal(), |
| 303 | ends_utterance: result.speechRecognitionMetadata().is_some(), |
| 304 | } |
| 305 | }; |
| 306 | _ = events.try_send(event); |
| 307 | } |
| 308 | if let Some(error) = error { |
| 309 | _ = events.try_send(Event::Error { |
| 310 | domain: error.domain().to_string(), |
| 311 | code: error.code(), |
| 312 | message: error.localizedDescription().to_string(), |
| 313 | }); |
| 314 | } |
| 315 | }, |
| 316 | ); |
| 317 | // SAFETY: the request is an audio buffer request and the block only |
| 318 | // sends on a channel, so it may run on any queue. |
| 319 | let task = unsafe { |
| 320 | self.recognizer |
| 321 | .recognitionTaskWithRequest_resultHandler(&self.request, &handler) |
| 322 | }; |
| 323 | self.task = Some(task); |
| 324 | |
| 325 | let pending = std::mem::take(&mut self.pending); |
| 326 | self.append(&pending); |
| 327 | if self.finishing { |
| 328 | // SAFETY: ending the audio of a valid request. |
| 329 | unsafe { self.request.endAudio() }; |
| 330 | } |
| 331 | self.sink.ready(cx); |
| 332 | } |
| 333 | |
| 334 | fn push_audio(&mut self, samples: &[i16]) { |
| 335 | if self.done || self.finishing { |
| 336 | return; |
| 337 | } |
| 338 | if self.task.is_some() { |
| 339 | self.append(samples); |
| 340 | } else { |
| 341 | self.pending.extend_from_slice(samples); |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | fn finish(&mut self) { |
| 346 | if self.finishing { |
| 347 | return; |
| 348 | } |
| 349 | self.finishing = true; |
| 350 | if self.task.is_some() { |
| 351 | // SAFETY: ending the audio of a valid request. |
| 352 | unsafe { self.request.endAudio() }; |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | fn append(&self, samples: &[i16]) { |
| 357 | let Ok(frames) = u32::try_from(samples.len()) else { |
| 358 | return; |
| 359 | }; |
| 360 | if frames == 0 { |
| 361 | return; |
| 362 | } |
| 363 | // SAFETY: `format` is PCM, so the initializer only fails for sizes |
| 364 | // beyond `u32`. |
| 365 | let Some(buffer) = (unsafe { |
| 366 | AVAudioPCMBuffer::initWithPCMFormat_frameCapacity( |
| 367 | AVAudioPCMBuffer::alloc(), |
| 368 | &self.format, |
| 369 | frames, |
| 370 | ) |
| 371 | }) else { |
| 372 | return; |
| 373 | }; |
| 374 | // SAFETY: the format is 16-bit mono, so channel 0 holds `frames` |
| 375 | // writable samples, and `frames` is within the capacity. |
| 376 | unsafe { |
| 377 | let channel = (*buffer.int16ChannelData()).as_ptr(); |
| 378 | std::ptr::copy_nonoverlapping(samples.as_ptr(), channel, samples.len()); |
| 379 | buffer.setFrameLength(frames); |
| 380 | self.request.appendAudioPCMBuffer(&buffer); |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | /// Handle one framework event; returns whether the recognition is done. |
| 385 | fn on_event(&mut self, event: Event, cx: &mut App) -> bool { |
| 386 | if self.done { |
| 387 | return true; |
| 388 | } |
| 389 | match event { |
| 390 | Event::Authorized(true) => self.begin(cx), |
| 391 | Event::Authorized(false) => { |
| 392 | self.sink.error(SpeechError::PermissionDenied, cx); |
| 393 | self.done = true; |
| 394 | } |
| 395 | Event::Result { |
| 396 | text, |
| 397 | is_final, |
| 398 | ends_utterance, |
| 399 | } => self.on_result(text, is_final, ends_utterance, cx), |
| 400 | Event::Error { |
| 401 | domain, |
| 402 | code, |
| 403 | message, |
| 404 | } => { |
| 405 | if self.finishing && domain == NO_SPEECH_DOMAIN && code == NO_SPEECH_CODE { |
| 406 | // Stopping without (more) speech is a normal end. |
| 407 | let hypothesis = std::mem::take(&mut self.hypothesis); |
| 408 | self.commit(&hypothesis, cx); |
| 409 | self.sink.finish(cx); |
| 410 | } else { |
| 411 | self.sink.error( |
| 412 | SpeechError::recognizer(anyhow!("{message} ({domain} {code})")), |
| 413 | cx, |
| 414 | ); |
| 415 | } |
| 416 | self.done = true; |
| 417 | } |
| 418 | } |
| 419 | self.done |
| 420 | } |
| 421 | |
| 422 | /// Results carry the whole text of the request so far, except that some |
| 423 | /// macOS versions start over after a pause: the result that ends an |
| 424 | /// utterance has metadata, and the next one may no longer include its |
| 425 | /// text. Commit that utterance as a phrase only once it is dropped. |
| 426 | fn on_result(&mut self, text: String, is_final: bool, ends_utterance: bool, cx: &mut App) { |
| 427 | if let Some(utterance) = self.utterance.take() |
| 428 | && starts_over(&utterance, &text) |
| 429 | { |
| 430 | self.commit(&utterance, cx); |
| 431 | } |
| 432 | |
| 433 | if is_final { |
| 434 | self.hypothesis.clear(); |
| 435 | self.commit(&text, cx); |
| 436 | self.sink.finish(cx); |
| 437 | self.done = true; |
| 438 | return; |
| 439 | } |
| 440 | |
| 441 | if ends_utterance { |
| 442 | self.utterance = Some(text.clone()); |
| 443 | } |
| 444 | self.sink.hypothesis(self.joined(&text), cx); |
| 445 | self.hypothesis = text; |
| 446 | } |
| 447 | |
| 448 | fn commit(&mut self, text: &str, cx: &mut App) { |
| 449 | if text.is_empty() { |
| 450 | return; |
| 451 | } |
| 452 | let text = self.joined(text); |
| 453 | self.last_committed = text.chars().next_back(); |
| 454 | self.sink.phrase(text, cx); |
| 455 | } |
| 456 | |
| 457 | /// `text` with the separator it needs after the committed phrases. |
| 458 | fn joined(&self, text: &str) -> String { |
| 459 | match (self.last_committed, text.chars().next()) { |
| 460 | (Some(before), Some(after)) if needs_space(before, after) => format!(" {text}"), |
| 461 | _ => text.to_string(), |
| 462 | } |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | /// Whether `text`, the result after the one that ended `utterance`, starts a new |
| 467 | /// utterance instead of carrying `utterance` on. |
| 468 | /// |
| 469 | /// A result that carries it on may still revise its words, punctuation or case |
| 470 | /// ("Hello word" becomes "Hello world, how"), so an exact prefix is too strict; |
| 471 | /// a result that starts over shares almost nothing with it. Less than half of |
| 472 | /// `utterance` in common means it started over. |
| 473 | fn starts_over(utterance: &str, text: &str) -> bool { |
| 474 | let common = utterance |
| 475 | .chars() |
| 476 | .zip(text.chars()) |
| 477 | .take_while(|(a, b)| a == b) |
| 478 | .count(); |
| 479 | common * 2 < utterance.chars().count() |
| 480 | } |
| 481 | |
| 482 | /// Whether two phrases ending and starting with these characters need a space |
| 483 | /// between them. |
| 484 | fn needs_space(before: char, after: char) -> bool { |
| 485 | !before.is_whitespace() |
| 486 | && !after.is_whitespace() |
| 487 | && !matches!(after, ',' | '.' | '?' | '!' | ';' | ':' | ')') |
| 488 | && !is_unspaced_script(before) |
| 489 | && !is_unspaced_script(after) |
| 490 | } |
| 491 | |
| 492 | /// Characters of scripts written without spaces between words: Chinese, |
| 493 | /// Japanese and their punctuation. |
| 494 | fn is_unspaced_script(c: char) -> bool { |
| 495 | matches!(c, |
| 496 | '\u{3000}'..='\u{30FF}' |
| 497 | | '\u{3400}'..='\u{4DBF}' |
| 498 | | '\u{4E00}'..='\u{9FFF}' |
| 499 | | '\u{F900}'..='\u{FAFF}' |
| 500 | | '\u{FF00}'..='\u{FFEF}' |
| 501 | ) |
| 502 | } |
| 503 | |
| 504 | #[cfg(test)] |
| 505 | mod tests { |
| 506 | use super::*; |
| 507 | |
| 508 | #[test] |
| 509 | fn a_revised_utterance_carries_on() { |
| 510 | assert!(!starts_over("Hello word", "Hello world, how")); |
| 511 | assert!(!starts_over("Hello world", "Hello world. How are you")); |
| 512 | assert!(!starts_over("今天天气", "今天天气很好")); |
| 513 | } |
| 514 | |
| 515 | #[test] |
| 516 | fn a_reset_result_starts_over() { |
| 517 | assert!(starts_over("Hello world.", "How")); |
| 518 | assert!(starts_over("今天天气很好。", "明天")); |
| 519 | } |
| 520 | |
| 521 | #[test] |
| 522 | fn phrases_are_spaced_by_script() { |
| 523 | assert!(needs_space('.', 'H')); |
| 524 | assert!(!needs_space('d', ',')); |
| 525 | assert!(!needs_space('。', '明')); |
| 526 | assert!(!needs_space('好', 'O')); |
| 527 | } |
| 528 | } |