BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / speech / system / winrt.rs

winrt.rs

winrt.rs 14.9 KiB Download Raw
1//! The Windows recognizer: continuous dictation with
2//! `Windows.Media.SpeechRecognition`.
3//!
4//! The WinRT recognizer captures from the default microphone itself and has no
5//! way to consume audio from elsewhere, so the pushed PCM is ignored; the
6//! [`Microphone`](crate::speech::Microphone) keeps capturing alongside it only
7//! to drive the waveform, which WASAPI's shared mode allows.
8//!
9//! The speech objects are agile, so they are called from the main thread, an
10//! STA that GPUI initializes with `OleInitialize`, without further apartment
11//! setup. Their completions and events arrive on WinRT threads, which only
12//! forward them over a channel to a foreground task that reports to the sink.
13
14use anyhow::anyhow;
15use gpui::{App, AsyncApp, SharedString, Task};
16use smol::channel::{Receiver, Sender, bounded, unbounded};
17use windows::{
18 Foundation::{
19 AsyncActionCompletedHandler, AsyncOperationCompletedHandler, EventRegistrationToken,
20 IAsyncAction, IAsyncOperation, TypedEventHandler,
21 },
22 Globalization::Language,
23 Media::SpeechRecognition::{
24 SpeechContinuousRecognitionCompletedEventArgs,
25 SpeechContinuousRecognitionResultGeneratedEventArgs, SpeechContinuousRecognitionSession,
26 SpeechRecognitionConfidence, SpeechRecognitionHypothesisGeneratedEventArgs,
27 SpeechRecognitionResult, SpeechRecognitionResultStatus, SpeechRecognitionScenario,
28 SpeechRecognitionTopicConstraint, SpeechRecognizer as WinSpeechRecognizer,
29 },
30 Win32::Foundation::E_ACCESSDENIED,
31 core::{HRESULT, HSTRING, RuntimeType},
32};
33
34use crate::speech::{AudioFormat, RecognitionSession, SpeechError, SpeechRecognizer, SpeechSink};
35
36/// `SPERR_SPEECH_PRIVACY_POLICY_NOT_ACCEPTED`: "Online speech recognition" is
37/// turned off in the privacy settings, which dictation requires.
38const PRIVACY_POLICY_NOT_ACCEPTED: HRESULT = HRESULT(0x80045509_u32 as i32);
39/// `MF_E_NO_CAPTURE_DEVICES_AVAILABLE`.
40const NO_CAPTURE_DEVICES: HRESULT = HRESULT(0xC00DABE0_u32 as i32);
41
42pub(super) struct PlatformRecognizer {
43 /// The dictation language, or `None` when the requested one is malformed or
44 /// has no speech pack installed.
45 language: Option<Language>,
46 separator: &'static str,
47}
48
49impl PlatformRecognizer {
50 pub(super) fn new(locale: Option<SharedString>) -> Self {
51 let language = supported_language(locale.as_deref())
52 .inspect_err(|error| log::warn!("speech: no dictation language: {error:#}"))
53 .ok()
54 .flatten();
55 let separator = language
56 .as_ref()
57 .and_then(|language| language.LanguageTag().ok())
58 .map_or(" ", |tag| phrase_separator(&tag.to_string_lossy()));
59 Self {
60 language,
61 separator,
62 }
63 }
64}
65
66impl SpeechRecognizer for PlatformRecognizer {
67 fn audio_format(&self) -> AudioFormat {
68 AudioFormat::default()
69 }
70
71 fn is_available(&self, _: &App) -> bool {
72 self.language.is_some()
73 }
74
75 fn start(
76 &self,
77 sink: SpeechSink,
78 cx: &mut App,
79 ) -> Result<Box<dyn RecognitionSession>, SpeechError> {
80 let Some(language) = &self.language else {
81 return Err(SpeechError::Unsupported);
82 };
83
84 let recognizer = WinSpeechRecognizer::Create(language).map_err(speech_error)?;
85 let continuous = recognizer
86 .ContinuousRecognitionSession()
87 .map_err(speech_error)?;
88 let (messages, rx) = unbounded();
89 let mut session = Session {
90 recognizer: recognizer.clone(),
91 continuous: continuous.clone(),
92 hypothesis_token: None,
93 result_token: None,
94 completed_token: None,
95 messages: messages.clone(),
96 _task: None,
97 };
98
99 let constraint = SpeechRecognitionTopicConstraint::Create(
100 SpeechRecognitionScenario::Dictation,
101 &HSTRING::from("dictation"),
102 )
103 .map_err(speech_error)?;
104 recognizer
105 .Constraints()
106 .and_then(|constraints| constraints.Append(&constraint))
107 .map_err(speech_error)?;
108
109 session.hypothesis_token = Some(
110 recognizer
111 .HypothesisGenerated(&TypedEventHandler::new({
112 let messages = messages.clone();
113 move |_, args: &Option<SpeechRecognitionHypothesisGeneratedEventArgs>| {
114 if let Some(args) = args {
115 let text = args.Hypothesis()?.Text()?;
116 _ = messages.try_send(Message::Hypothesis(text));
117 }
118 Ok(())
119 }
120 }))
121 .map_err(speech_error)?,
122 );
123 session.result_token = Some(
124 continuous
125 .ResultGenerated(&TypedEventHandler::new({
126 let messages = messages.clone();
127 move |_, args: &Option<SpeechContinuousRecognitionResultGeneratedEventArgs>| {
128 if let Some(args) = args {
129 _ = messages.try_send(Message::Result(args.Result()?));
130 }
131 Ok(())
132 }
133 }))
134 .map_err(speech_error)?,
135 );
136 session.completed_token = Some(
137 continuous
138 .Completed(&TypedEventHandler::new({
139 let messages = messages.clone();
140 move |_, args: &Option<SpeechContinuousRecognitionCompletedEventArgs>| {
141 if let Some(args) = args {
142 _ = messages.try_send(Message::Completed(args.Status()?));
143 }
144 Ok(())
145 }
146 }))
147 .map_err(speech_error)?,
148 );
149
150 let separator = self.separator;
151 session._task = Some(cx.spawn(async move |cx| {
152 let result = dictate(&recognizer, &continuous, rx, &sink, separator, cx).await;
153 if let Err(error) = result {
154 cx.update(|cx| sink.error(error, cx));
155 }
156 }));
157 Ok(Box::new(session))
158 }
159}
160
161/// What the WinRT threads and [`Session::finish`] tell the dictation task.
162enum Message {
163 Hypothesis(HSTRING),
164 Result(SpeechRecognitionResult),
165 Completed(SpeechRecognitionResultStatus),
166 /// The user stopped talking.
167 Finish,
168}
169
170struct Session {
171 recognizer: WinSpeechRecognizer,
172 continuous: SpeechContinuousRecognitionSession,
173 hypothesis_token: Option<EventRegistrationToken>,
174 result_token: Option<EventRegistrationToken>,
175 completed_token: Option<EventRegistrationToken>,
176 messages: Sender<Message>,
177 _task: Option<Task<()>>,
178}
179
180impl RecognitionSession for Session {
181 /// Ignored: the WinRT recognizer captures from the microphone itself.
182 fn push_audio(&mut self, _: &[i16], _: &mut App) {}
183
184 fn finish(&mut self, _: &mut App) {
185 // Queued behind the start, so finishing while connecting stops the
186 // session as soon as it runs.
187 _ = self.messages.try_send(Message::Finish);
188 }
189}
190
191impl Drop for Session {
192 fn drop(&mut self) {
193 if let Some(token) = self.hypothesis_token.take() {
194 _ = self.recognizer.RemoveHypothesisGenerated(token);
195 }
196 if let Some(token) = self.result_token.take() {
197 _ = self.continuous.RemoveResultGenerated(token);
198 }
199 if let Some(token) = self.completed_token.take() {
200 _ = self.continuous.RemoveCompleted(token);
201 }
202
203 // Close the recognizer once the cancellation lands, or right away when
204 // there is nothing to cancel.
205 let recognizer = self.recognizer.clone();
206 let closed = self.continuous.CancelAsync().and_then(|action| {
207 action.SetCompleted(&AsyncActionCompletedHandler::new(move |_, _| {
208 _ = recognizer.Close();
209 Ok(())
210 }))
211 });
212 if closed.is_err() {
213 _ = self.recognizer.Close();
214 }
215 }
216}
217
218/// Compile the dictation constraint, start the continuous session and report
219/// its results to `sink` until it completes.
220async fn dictate(
221 recognizer: &WinSpeechRecognizer,
222 continuous: &SpeechContinuousRecognitionSession,
223 messages: Receiver<Message>,
224 sink: &SpeechSink,
225 separator: &'static str,
226 cx: &mut AsyncApp,
227) -> Result<(), SpeechError> {
228 let compilation = operation(recognizer.CompileConstraintsAsync().map_err(speech_error)?)
229 .await
230 .map_err(speech_error)?;
231 let status = compilation.Status().map_err(speech_error)?;
232 if status != SpeechRecognitionResultStatus::Success {
233 return Err(status_error(status));
234 }
235 action(continuous.StartAsync().map_err(speech_error)?)
236 .await
237 .map_err(speech_error)?;
238 cx.update(|cx| sink.ready(cx));
239
240 let mut separator_due = false;
241 while let Ok(message) = messages.recv().await {
242 match message {
243 Message::Hypothesis(text) => {
244 let text = joined(separator_due, separator, &text);
245 cx.update(|cx| sink.hypothesis(text, cx));
246 }
247 Message::Result(result) => {
248 let Some(text) = phrase_text(&result) else {
249 continue;
250 };
251 let text = joined(separator_due, separator, &text);
252 separator_due = true;
253 cx.update(|cx| sink.phrase(text, cx));
254 }
255 Message::Completed(status) => {
256 return match status {
257 // Stopped, cancelled, or ended by the silence timeout.
258 SpeechRecognitionResultStatus::Success
259 | SpeechRecognitionResultStatus::UserCanceled
260 | SpeechRecognitionResultStatus::TimeoutExceeded => {
261 cx.update(|cx| sink.finish(cx));
262 Ok(())
263 }
264 status => Err(status_error(status)),
265 };
266 }
267 // Stopping flushes the last phrase, then completes the session.
268 Message::Finish => {
269 let stopped = match continuous.StopAsync() {
270 Ok(stop) => action(stop).await,
271 Err(error) => Err(error),
272 };
273 // The session may have ended by itself, e.g. after the silence
274 // timeout, with its `Completed` still queued behind this; stopping
275 // it then fails, and that queued event ends the session instead.
276 if let Err(error) = stopped {
277 log::debug!("speech: stopping dictation failed: {error}");
278 }
279 }
280 }
281 }
282 Ok(())
283}
284
285/// The text of a recognized phrase, unless it was rejected or empty.
286fn phrase_text(result: &SpeechRecognitionResult) -> Option<HSTRING> {
287 if result.Status().ok()? != SpeechRecognitionResultStatus::Success
288 || result.Confidence().ok()? == SpeechRecognitionConfidence::Rejected
289 {
290 return None;
291 }
292 Some(result.Text().ok()?).filter(|text| !text.is_empty())
293}
294
295/// `text` preceded by `separator` once a phrase has been committed.
296fn joined(separator_due: bool, separator: &str, text: &HSTRING) -> SharedString {
297 let text = text.to_string_lossy();
298 if separator_due {
299 format!("{separator}{text}").into()
300 } else {
301 text.into()
302 }
303}
304
305/// What goes between two phrases, which dictation returns without surrounding
306/// whitespace: a space, except in languages written without spaces between
307/// words (Chinese, Japanese, Thai, Lao, Khmer, Burmese).
308fn phrase_separator(tag: &str) -> &'static str {
309 let primary = tag.split('-').next().unwrap_or_default();
310 let unspaced = ["zh", "yue", "ja", "th", "lo", "km", "my"];
311 if unspaced
312 .iter()
313 .any(|lang| primary.eq_ignore_ascii_case(lang))
314 {
315 ""
316 } else {
317 " "
318 }
319}
320
321/// The language to dictate `locale` (or, without one, the system's speech
322/// language) in, if a speech pack supports it.
323///
324/// A bare language such as `en` falls back to the first supported region.
325fn supported_language(locale: Option<&str>) -> windows::core::Result<Option<Language>> {
326 let requested = match locale {
327 Some(locale) => {
328 let tag = HSTRING::from(locale);
329 if !Language::IsWellFormed(&tag)? {
330 return Ok(None);
331 }
332 Language::CreateLanguage(&tag)?
333 }
334 None => WinSpeechRecognizer::SystemSpeechLanguage()?,
335 };
336 let requested = requested.LanguageTag()?.to_string_lossy();
337 let region_prefix = format!("{requested}-");
338
339 let mut fallback = None;
340 for language in WinSpeechRecognizer::SupportedTopicLanguages()? {
341 let tag = language.LanguageTag()?.to_string_lossy();
342 if tag.eq_ignore_ascii_case(&requested) {
343 return Ok(Some(language));
344 }
345 if fallback.is_none()
346 && tag.len() > region_prefix.len()
347 && tag[..region_prefix.len()].eq_ignore_ascii_case(&region_prefix)
348 {
349 fallback = Some(language);
350 }
351 }
352 Ok(fallback)
353}
354
355/// Await `operation` without blocking: its completion handler, which runs on a
356/// WinRT thread, only wakes this future.
357async fn operation<T: RuntimeType + 'static>(
358 operation: IAsyncOperation<T>,
359) -> windows::core::Result<T> {
360 let (done, wait) = bounded(1);
361 operation.SetCompleted(&AsyncOperationCompletedHandler::new(move |_, _| {
362 _ = done.try_send(());
363 Ok(())
364 }))?;
365 _ = wait.recv().await;
366 operation.GetResults()
367}
368
369/// Await `action` like [`operation`].
370async fn action(action: IAsyncAction) -> windows::core::Result<()> {
371 let (done, wait) = bounded(1);
372 action.SetCompleted(&AsyncActionCompletedHandler::new(move |_, _| {
373 _ = done.try_send(());
374 Ok(())
375 }))?;
376 _ = wait.recv().await;
377 action.GetResults()
378}
379
380fn speech_error(error: windows::core::Error) -> SpeechError {
381 match error.code() {
382 E_ACCESSDENIED => SpeechError::PermissionDenied,
383 NO_CAPTURE_DEVICES => SpeechError::NoInputDevice,
384 PRIVACY_POLICY_NOT_ACCEPTED => SpeechError::recognizer(anyhow!(
385 "Online speech recognition is turned off; turn it on in Settings > \
386 Privacy & security > Speech"
387 )),
388 _ => SpeechError::recognizer(error),
389 }
390}
391
392fn status_error(status: SpeechRecognitionResultStatus) -> SpeechError {
393 match status {
394 SpeechRecognitionResultStatus::TopicLanguageNotSupported => SpeechError::Unsupported,
395 SpeechRecognitionResultStatus::MicrophoneUnavailable => SpeechError::NoInputDevice,
396 SpeechRecognitionResultStatus::NetworkFailure => {
397 SpeechError::recognizer(anyhow!("could not reach the online speech service"))
398 }
399 SpeechRecognitionResultStatus::AudioQualityFailure => {
400 SpeechError::recognizer(anyhow!("the audio was too poor to recognize"))
401 }
402 status => SpeechError::recognizer(anyhow!("recognition ended with status {}", status.0)),
403 }
404}