From 22c9206d10e2a829c943891033796ee6dd5eadfe Mon Sep 17 00:00:00 2001 From: AliceWood <36452359+AliceWood@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:05:17 +0300 Subject: [PATCH 1/2] hle: synthesize text and SSML with installed Windows voices --- Cargo.lock | 1 + README.md | 2 +- crates/xtp-hle/Cargo.toml | 10 +- crates/xtp-hle/src/modules/speech.rs | 246 ++++++++++++++---- crates/xtp-hle/src/modules/speech/narrator.rs | 100 +++++++ 5 files changed, 305 insertions(+), 54 deletions(-) create mode 100644 crates/xtp-hle/src/modules/speech/narrator.rs diff --git a/Cargo.lock b/Cargo.lock index f9eac25d..a4cd9106 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -874,6 +874,7 @@ dependencies = [ "xtp-gpu", "xtp-loader", "xtp-pe", + "xtp-testkit", ] [[package]] diff --git a/README.md b/README.md index 6e47c101..3caac100 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ What each part does today and what it still needs: | Subsystem | Today | Needs | |-----------|-------|-------| | Loader | Runs the title's executable and its DLLs in our process; crash reports name the faulting code and are kept in `crashes.log` | – | -| Runtime services | One signed-in offline user, licences, packages, saves that survive a kill at any step, text entry dialog | Speech is silent; the dialog and relaunch are untested live | +| Runtime services | One signed-in offline user, licences, packages, saves that survive a kill at any step, text entry dialog, text and SSML narration with installed Windows voices | Narration returns an empty WAVE when no voice is installed. The dialog and relaunch are untested live | | Network | Offline by design: the title cannot reach the network | – | | Files and streaming | Archives and streamed data read, zlib and BCPack decoded in parallel | Loading is limited by writes into title memory | | Input | XInput pads with trigger rumble, keyboard, keyboard and mouse as a pad (keys by place, mouse as the right stick) | Trigger rumble and the mouse are untested in play | diff --git a/crates/xtp-hle/Cargo.toml b/crates/xtp-hle/Cargo.toml index 328758dd..6f2422db 100644 --- a/crates/xtp-hle/Cargo.toml +++ b/crates/xtp-hle/Cargo.toml @@ -34,14 +34,18 @@ windows-sys = { workspace = true, features = [ "Win32_UI_Input_XboxController", "Win32_UI_WindowsAndMessaging", ] } -# Trigger motors (`modules::gameinput::triggers`) and Windows accessibility -# settings (`modules::speech::captions`). Diagnostics adds `modules::audio::capture`. -windows = { workspace = true, features = ["Gaming_Input", "Media_ClosedCaptioning", "UI_ViewManagement"] } +# Trigger motors, accessibility settings and in-memory speech synthesis. +windows = { workspace = true, features = [ + "Gaming_Input", "Media_ClosedCaptioning", "UI_ViewManagement", + "Media_Core", "Media_MediaProperties", "Media_SpeechSynthesis", + "Media_Transcoding", "Storage_Streams", "Win32_Foundation", +] } # `#[implement]` names it. windows-core = { workspace = true, optional = true } [dev-dependencies] tempfile.workspace = true +xtp-testkit.workspace = true [features] # Debugging switches (scripted keys and the like). diff --git a/crates/xtp-hle/src/modules/speech.rs b/crates/xtp-hle/src/modules/speech.rs index 89b8a63c..16808051 100644 --- a/crates/xtp-hle/src/modules/speech.rs +++ b/crates/xtp-hle/src/modules/speech.rs @@ -1,16 +1,14 @@ //! Accessibility covers caption preferences, high contrast and speech synthesis. -//! No voice is installed here. Each stream is a valid, empty WAVE file, so -//! narration is silent. -// shortcut: silent speech. The host's engine (SAPI through COM, or WinRT -// speech synthesis) needs COM bindings this crate has only in diagnostics -// builds, plus voice enumeration and SSML the title sends (slot 0xa8); the -// title then plays the empty stream and goes on. +//! Synthesized speech streams own their WAVE data until the title closes them. #![allow(clippy::not_unsafe_ptr_arg_deref)] mod captions; +#[cfg(windows)] +mod narrator; use std::ffi::{c_char, c_void}; +use super::xasync::{E_INVALIDARG, E_NOT_SUFFICIENT_BUFFER}; use super::xgameruntime::{ Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, }; @@ -39,60 +37,126 @@ pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)]; const SILENCE: [u8; 44] = *b"RIFF\x24\0\0\0WAVEfmt \x10\0\0\0\x01\0\x01\0\x80\x3e\0\0\0\x7d\0\0\x02\0\x10\0data\0\0\0\0"; -/// Synthesizers and streams hold nothing, so their handles are fixed -/// addresses and closing them is free. -static SYNTHESIZER: u8 = 0; -static STREAM: u8 = 0; - type This = *const Object; -/// No voice is installed, so the callback never runs. +enum Synthesizer { + Silent, + #[cfg(windows)] + Windows(windows::Media::SpeechSynthesis::SpeechSynthesizer), +} + +#[repr(C)] +struct VoiceInfo { + description: *const c_char, + display_name: *const c_char, + gender: u32, + id: *const c_char, + language: *const c_char, +} + +type VoiceCallback = extern "system" fn(&VoiceInfo, *mut c_void) -> bool; + extern "system" fn enumerate_voices( _: This, _context: *mut c_void, - _callback: *const c_void, + callback: Option, ) -> HRESULT { + let Some(_callback) = callback else { + return E_INVALIDARG; + }; + #[cfg(windows)] + if let Err(e) = narrator::enumerate(_context, _callback) { + return e.code().0; + } S_OK } -extern "system" fn create(_: This, out: *mut *const u8) -> HRESULT { - put(out, &raw const SYNTHESIZER) -} -extern "system" fn close(_: This, _: *const u8) -> HRESULT { +extern "system" fn create(_: This, out: Option<&mut *mut Synthesizer>) -> HRESULT { + let Some(out) = out else { return E_INVALIDARG }; + *out = std::ptr::null_mut(); + #[cfg(windows)] + let synth = match narrator::open() { + Ok(Some(engine)) => Synthesizer::Windows(engine), + Ok(None) => Synthesizer::Silent, + Err(e) => return e.code().0, + }; + #[cfg(not(windows))] + let synth = Synthesizer::Silent; + *out = Box::into_raw(Box::new(synth)); S_OK } -extern "system" fn set_default_voice(_: This, _: *const u8) -> HRESULT { +extern "system" fn close(_: This, handle: *mut T) -> HRESULT { + if !handle.is_null() { + // SAFETY: create and create_stream each hand a Box to the title, closed once after use. + drop(unsafe { Box::from_raw(handle) }); + } S_OK } -extern "system" fn set_custom_voice(_: This, _: *const u8, _voice: *const c_char) -> HRESULT { - S_OK +fn set_voice(synth: Option<&Synthesizer>, _id: Option<&str>) -> HRESULT { + match synth { + None => E_INVALIDARG, + Some(Synthesizer::Silent) => S_OK, + #[cfg(windows)] + Some(Synthesizer::Windows(engine)) => { + narrator::set_voice(engine, _id).map_or_else(|e| e.code().0, |()| S_OK) + } + } +} +extern "system" fn set_default_voice(_: This, synth: Option<&Synthesizer>) -> HRESULT { + set_voice(synth, None) } -extern "system" fn create_stream( +extern "system" fn set_custom_voice( _: This, - _: *const u8, + synth: Option<&Synthesizer>, + id: *const c_char, +) -> HRESULT { + let Some(id) = text(id) else { + return E_INVALIDARG; + }; + set_voice(synth, Some(&id)) +} +extern "system" fn create_stream( + _: This, + synth: Option<&Synthesizer>, words: *const c_char, - out: *mut *const u8, + out: Option<&mut *mut Vec>, ) -> HRESULT { - tracing::debug!(text = text(words).unwrap_or_default(), "speech (silent)"); - put(out, &raw const STREAM) + let Some(out) = out else { return E_INVALIDARG }; + *out = std::ptr::null_mut(); + let (Some(synth), Some(_words)) = (synth, text(words)) else { + return E_INVALIDARG; + }; + let wav = match synth { + Synthesizer::Silent => SILENCE.to_vec(), + #[cfg(windows)] + Synthesizer::Windows(engine) => match narrator::render(engine, &_words, SSML) { + Ok(wav) => wav, + Err(e) => return e.code().0, + }, + }; + *out = Box::into_raw(Box::new(wav)); + S_OK } -extern "system" fn stream_size(_: This, _: *const u8, out: *mut usize) -> HRESULT { - put(out, SILENCE.len()) +extern "system" fn stream_size(_: This, stream: Option<&Vec>, out: *mut usize) -> HRESULT { + stream.map_or(E_INVALIDARG, |wav| put(out, wav.len())) } extern "system" fn stream_data( _: This, - _: *const u8, + stream: Option<&Vec>, size: usize, buffer: *mut u8, used: *mut usize, ) -> HRESULT { - if buffer.is_null() || size < SILENCE.len() { - return super::xasync::E_NOT_SUFFICIENT_BUFFER; + let Some(wav) = stream else { + return E_INVALIDARG; + }; + if buffer.is_null() || size < wav.len() { + return E_NOT_SUFFICIENT_BUFFER; } // SAFETY: the buffer holds `size` bytes, checked above. - unsafe { buffer.copy_from_nonoverlapping(SILENCE.as_ptr(), SILENCE.len()) }; + unsafe { buffer.copy_from_nonoverlapping(wav.as_ptr(), wav.len()) }; if !used.is_null() { // SAFETY: checked non-null. - unsafe { used.write(SILENCE.len()) }; + unsafe { used.write(wav.len()) }; } S_OK } @@ -108,46 +172,128 @@ static VTABLE: Methods<22> = Methods([ missing::<7> as *const (), // 0x38 enumerate_voices as *const (), // 0x40 create as *const (), // 0x48 - close as *const (), // 0x50 + close:: as *const (), // 0x50 set_default_voice as *const (), // 0x58 set_custom_voice as *const (), // 0x60 - create_stream as *const (), // 0x68 from text - close as *const (), // 0x70 a stream + create_stream:: as *const (), // 0x68 from text + close::> as *const (), // 0x70 a stream stream_size as *const (), // 0x78 stream_data as *const (), // 0x80 missing::<17> as *const (), // 0x88 speech to text missing::<18> as *const (), // 0x90 missing::<19> as *const (), // 0x98 missing::<20> as *const (), // 0xa0 - create_stream as *const (), // 0xa8 from SSML + create_stream:: as *const (), // 0xa8 from SSML ]); #[cfg(test)] mod tests { use super::*; use crate::modules::xgameruntime::method; + use std::ffi::CStr; - #[test] - fn streams_are_empty_wave_files() { + type Stream = + extern "system" fn(This, &Synthesizer, *const c_char, *mut *mut Vec) -> HRESULT; + + fn wave(synth: &Synthesizer, slot: usize, words: &CStr) -> Vec { let this: This = &OBJECT; - type Create = extern "system" fn(This, *mut *const u8) -> HRESULT; - type Stream = extern "system" fn(This, *const u8, *const c_char, *mut *const u8) -> HRESULT; - type Size = extern "system" fn(This, *const u8, *mut usize) -> HRESULT; - type Data = extern "system" fn(This, *const u8, usize, *mut u8, *mut usize) -> HRESULT; - let (mut synth, mut stream, mut size) = (std::ptr::null(), std::ptr::null(), 0); - assert_eq!(method::(&OBJECT, 0x48)(this, &mut synth), S_OK); - let say = method::(&OBJECT, 0x68); - assert_eq!(say(this, synth, c"Hello".as_ptr(), &mut stream), S_OK); + type Size = extern "system" fn(This, *mut Vec, *mut usize) -> HRESULT; + type Data = extern "system" fn(This, *mut Vec, usize, *mut u8, *mut usize) -> HRESULT; + let (mut stream, mut size) = (std::ptr::null_mut(), 0); + assert_eq!( + method::(&OBJECT, slot)(this, synth, words.as_ptr(), &mut stream), + S_OK + ); assert_eq!(method::(&OBJECT, 0x78)(this, stream, &mut size), S_OK); let mut wav = vec![0u8; size]; let mut used = 0; let data = method::(&OBJECT, 0x80); + assert_eq!( + data(this, stream, size - 1, wav.as_mut_ptr(), &mut used), + E_NOT_SUFFICIENT_BUFFER + ); assert_eq!(data(this, stream, size, wav.as_mut_ptr(), &mut used), S_OK); + assert_eq!(used, size); + type Close = extern "system" fn(This, *mut Vec) -> HRESULT; + assert_eq!(method::(&OBJECT, 0x70)(this, stream), S_OK); + wav + } + + #[test] + fn no_voice_returns_the_empty_wave_for_text_and_ssml() { + for slot in [0x68, 0xa8] { + assert_eq!(wave(&Synthesizer::Silent, slot, c"test"), SILENCE); + } + } + + #[cfg(windows)] + #[test] + fn installed_voice_speaks_text_and_ssml() { + use std::ffi::CString; + // Stop after the first voice. The title can keep a copy of its ID. + extern "system" fn first(info: &VoiceInfo, context: *mut c_void) -> bool { + // SAFETY: context points to the test's output; the voice strings live through this call. + unsafe { + *context.cast::>() = Some(( + CStr::from_ptr(info.id).to_owned(), + CStr::from_ptr(info.language).to_string_lossy().into_owned(), + )); + } + false + } + let mut voice: Option<(CString, String)> = None; assert_eq!( - (&wav[..4], &wav[8..16], &wav[36..40]), - (&b"RIFF"[..], &b"WAVEfmt "[..], &b"data"[..]) + enumerate_voices(&OBJECT, (&raw mut voice).cast(), Some(first)), + S_OK + ); + let mut handle = std::ptr::null_mut(); + assert_eq!(create(&OBJECT, Some(&mut handle)), S_OK); + // SAFETY: create returned a live handle which this test owns until close. + let synth = unsafe { &*handle }; + let Some((id, language)) = voice else { + assert_eq!(wave(synth, 0x68, c"test"), SILENCE); + assert_eq!(close(&OBJECT, handle), S_OK); + xtp_testkit::skip("no-voice"); + return; + }; + assert_eq!(set_custom_voice(&OBJECT, Some(synth), id.as_ptr()), S_OK); + assert_eq!( + set_custom_voice(&OBJECT, Some(synth), c"missing-test-voice".as_ptr()), + E_INVALIDARG + ); + let ssml = CString::new(format!(r#"test"#)).unwrap(); + let spoken_ssml = wave(synth, 0xa8, &ssml); + let mut invalid = std::ptr::null_mut(); + assert_ne!( + method::(&OBJECT, 0xa8)(&OBJECT, synth, c"".as_ptr(), &mut invalid), + S_OK ); - assert_eq!(u32::from_le_bytes(wav[24..28].try_into().unwrap()), 16_000); - assert_eq!(used, 44); + assert!(invalid.is_null()); + assert_eq!(set_default_voice(&OBJECT, Some(synth)), S_OK); + let spoken_text = wave(synth, 0x68, c"test"); + assert_eq!(close(&OBJECT, handle), S_OK); + for wav in [spoken_text, spoken_ssml] { + let size = |bytes: &[u8]| u32::from_le_bytes(bytes.try_into().unwrap()) as usize; + assert_eq!(&wav[..4], b"RIFF"); + assert_eq!(size(&wav[4..8]) + 8, wav.len()); + assert_eq!(&wav[8..12], b"WAVE"); + let mut chunks = &wav[12..]; + let (mut format, mut samples) = (None, None); + while !chunks.is_empty() { + let len = size(&chunks[4..8]); + let payload = &chunks[8..8 + len]; + match &chunks[..4] { + b"fmt " => format = Some(payload), + b"data" => samples = Some(payload), + _ => (), + } + chunks = &chunks[8 + len + (len % 2)..]; + } + let fmt = format.unwrap(); + assert_eq!(size(&fmt[4..8]), 48_000); + assert_eq!(u16::from_le_bytes(fmt[2..4].try_into().unwrap()), 1); + assert_eq!(u16::from_le_bytes(fmt[14..16].try_into().unwrap()), 16); + assert!(samples.unwrap().iter().any(|&byte| byte != 0)); + } } } diff --git a/crates/xtp-hle/src/modules/speech/narrator.rs b/crates/xtp-hle/src/modules/speech/narrator.rs new file mode 100644 index 00000000..d6cc5cd8 --- /dev/null +++ b/crates/xtp-hle/src/modules/speech/narrator.rs @@ -0,0 +1,100 @@ +//! Windows voices and in-memory conversion to the title's 48 kHz WAVE format. + +use std::ffi::{CString, c_void}; +use windows::Media::MediaProperties::{ + AudioEncodingProperties, AudioEncodingQuality, MediaEncodingProfile, +}; +use windows::Media::SpeechSynthesis::{SpeechSynthesizer, VoiceGender, VoiceInformation}; +use windows::Media::Transcoding::MediaTranscoder; +use windows::Storage::Streams::{DataReader, InMemoryRandomAccessStream}; +use windows::Win32::Foundation::{E_BOUNDS, E_FAIL, E_INVALIDARG}; +use windows::core::{HSTRING, Result}; + +use super::{VoiceCallback, VoiceInfo}; + +fn installed_voices() -> Result> { + // On hosts without the speech service even opening the catalog can fail. + let voices = match SpeechSynthesizer::AllVoices() { + Ok(voices) => voices, + Err(error) => { + tracing::debug!(%error, "Windows speech voices unavailable"); + return Ok(Vec::new()); + } + }; + (0..voices.Size()?) + .map(|index| voices.GetAt(index)) + .collect() +} + +pub(super) fn open() -> Result> { + if installed_voices()?.is_empty() { + return Ok(None); + } + SpeechSynthesizer::new().map(Some) +} + +pub(super) fn enumerate(context: *mut c_void, callback: VoiceCallback) -> Result<()> { + let string = |s: HSTRING| CString::new(s.to_string()).map_err(|_| E_INVALIDARG); + for voice in installed_voices()? { + let description = string(voice.Description()?)?; + let name = string(voice.DisplayName()?)?; + let id = string(voice.Id()?)?; + let language = string(voice.Language()?)?; + let info = VoiceInfo { + description: description.as_ptr(), + display_name: name.as_ptr(), + gender: u32::from(voice.Gender()? == VoiceGender::Male), + id: id.as_ptr(), + language: language.as_ptr(), + }; + if !callback(&info, context) { + break; + } + } + Ok(()) +} + +pub(super) fn set_voice(engine: &SpeechSynthesizer, id: Option<&str>) -> Result<()> { + let Some(id) = id else { + return engine.SetVoice(&SpeechSynthesizer::DefaultVoice()?); + }; + for voice in installed_voices()? { + if voice.Id()? == id { + return engine.SetVoice(&voice); + } + } + Err(E_INVALIDARG.into()) +} + +pub(super) fn render(engine: &SpeechSynthesizer, words: &str, ssml: bool) -> Result> { + let words = HSTRING::from(words); + let speech = if ssml { + engine.SynthesizeSsmlToStreamAsync(&words)? + } else { + engine.SynthesizeTextToStreamAsync(&words)? + } + .join()?; + + let wave = InMemoryRandomAccessStream::new()?; + let profile = MediaEncodingProfile::CreateWav(AudioEncodingQuality::Auto)?; + profile.SetAudio(&AudioEncodingProperties::CreatePcm(48_000, 1, 16)?)?; + let transcoder = MediaTranscoder::new()?; + transcoder.SetAlwaysReencode(true)?; + let prepared = transcoder + .PrepareStreamTranscodeAsync(&speech, &wave, &profile)? + .join()?; + if !prepared.CanTranscode()? { + tracing::warn!(reason = ?prepared.FailureReason()?, "cannot convert speech to WAVE"); + return Err(E_FAIL.into()); + } + prepared.TranscodeAsync()?.join()?; + + let size = u32::try_from(wave.Size()?).map_err(|_| E_BOUNDS)?; + let reader = DataReader::CreateDataReader(&wave.GetInputStreamAt(0)?)?; + if reader.LoadAsync(size)?.join()? != size { + return Err(E_FAIL.into()); + } + let mut bytes = vec![0; size as usize]; + reader.ReadBytes(&mut bytes)?; + Ok(bytes) +} From c9ae4cf6210d2242213a68e4b028e7a06590127a Mon Sep 17 00:00:00 2001 From: AliceWood <36452359+AliceWood@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:35:11 +0300 Subject: [PATCH 2/2] hle: preserve silent narration when Windows speech fails --- README.md | 2 +- crates/xtp-hle/Cargo.toml | 2 +- crates/xtp-hle/src/modules/speech.rs | 34 ++++++++- crates/xtp-hle/src/modules/speech/narrator.rs | 75 +++++++++++++++++-- docs/analysis/hle.md | 14 ++-- 5 files changed, 106 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 3caac100..38b270d6 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ What each part does today and what it still needs: | Subsystem | Today | Needs | |-----------|-------|-------| | Loader | Runs the title's executable and its DLLs in our process; crash reports name the faulting code and are kept in `crashes.log` | – | -| Runtime services | One signed-in offline user, licences, packages, saves that survive a kill at any step, text entry dialog, text and SSML narration with installed Windows voices | Narration returns an empty WAVE when no voice is installed. The dialog and relaunch are untested live | +| Runtime services | One signed-in offline user, licences, packages, saves that survive a kill at any step, text entry dialog, text and SSML narration with installed Windows voices | Narration returns an empty WAVE for blank text or when Windows cannot produce audio. The dialog and relaunch are untested live | | Network | Offline by design: the title cannot reach the network | – | | Files and streaming | Archives and streamed data read, zlib and BCPack decoded in parallel | Loading is limited by writes into title memory | | Input | XInput pads with trigger rumble, keyboard, keyboard and mouse as a pad (keys by place, mouse as the right stick) | Trigger rumble and the mouse are untested in play | diff --git a/crates/xtp-hle/Cargo.toml b/crates/xtp-hle/Cargo.toml index 6f2422db..5fd30a2c 100644 --- a/crates/xtp-hle/Cargo.toml +++ b/crates/xtp-hle/Cargo.toml @@ -38,7 +38,7 @@ windows-sys = { workspace = true, features = [ windows = { workspace = true, features = [ "Gaming_Input", "Media_ClosedCaptioning", "UI_ViewManagement", "Media_Core", "Media_MediaProperties", "Media_SpeechSynthesis", - "Media_Transcoding", "Storage_Streams", "Win32_Foundation", + "Data_Xml_Dom", "Media_Transcoding", "Storage_Streams", "Win32_Foundation", ] } # `#[implement]` names it. windows-core = { workspace = true, optional = true } diff --git a/crates/xtp-hle/src/modules/speech.rs b/crates/xtp-hle/src/modules/speech.rs index 16808051..9d15eb94 100644 --- a/crates/xtp-hle/src/modules/speech.rs +++ b/crates/xtp-hle/src/modules/speech.rs @@ -38,6 +38,7 @@ const SILENCE: [u8; 44] = *b"RIFF\x24\0\0\0WAVEfmt \x10\0\0\0\x01\0\x01\0\x80\x3e\0\0\0\x7d\0\0\x02\0\x10\0data\0\0\0\0"; type This = *const Object; +const STREAM_NOT_FOUND: HRESULT = 0x8007_0490_u32 as i32; // HRESULT_FROM_WIN32(ERROR_NOT_FOUND) enum Synthesizer { Silent, @@ -77,7 +78,10 @@ extern "system" fn create(_: This, out: Option<&mut *mut Synthesizer>) -> HRESUL let synth = match narrator::open() { Ok(Some(engine)) => Synthesizer::Windows(engine), Ok(None) => Synthesizer::Silent, - Err(e) => return e.code().0, + Err(error) => { + tracing::warn!(%error, "could not open Windows speech synthesizer; using silence"); + Synthesizer::Silent + } }; #[cfg(not(windows))] let synth = Synthesizer::Silent; @@ -137,7 +141,7 @@ extern "system" fn create_stream( S_OK } extern "system" fn stream_size(_: This, stream: Option<&Vec>, out: *mut usize) -> HRESULT { - stream.map_or(E_INVALIDARG, |wav| put(out, wav.len())) + stream.map_or(STREAM_NOT_FOUND, |wav| put(out, wav.len())) } extern "system" fn stream_data( _: This, @@ -147,7 +151,7 @@ extern "system" fn stream_data( used: *mut usize, ) -> HRESULT { let Some(wav) = stream else { - return E_INVALIDARG; + return STREAM_NOT_FOUND; }; if buffer.is_null() || size < wav.len() { return E_NOT_SUFFICIENT_BUFFER; @@ -226,6 +230,15 @@ mod tests { } } + #[test] + fn null_stream_is_not_found() { + assert_eq!(stream_size(&OBJECT, None, &mut 0), STREAM_NOT_FOUND); + assert_eq!( + stream_data(&OBJECT, None, 0, std::ptr::null_mut(), std::ptr::null_mut()), + STREAM_NOT_FOUND + ); + } + #[cfg(windows)] #[test] fn installed_voice_speaks_text_and_ssml() { @@ -250,6 +263,9 @@ mod tests { assert_eq!(create(&OBJECT, Some(&mut handle)), S_OK); // SAFETY: create returned a live handle which this test owns until close. let synth = unsafe { &*handle }; + for blank in [c"", c" \t\r\n"] { + assert_eq!(wave(synth, 0x68, blank), SILENCE); + } let Some((id, language)) = voice else { assert_eq!(wave(synth, 0x68, c"test"), SILENCE); assert_eq!(close(&OBJECT, handle), S_OK); @@ -261,7 +277,7 @@ mod tests { set_custom_voice(&OBJECT, Some(synth), c"missing-test-voice".as_ptr()), E_INVALIDARG ); - let ssml = CString::new(format!(r#"test"#)).unwrap(); + let ssml = CString::new(format!(r#""#)).unwrap(); let spoken_ssml = wave(synth, 0xa8, &ssml); let mut invalid = std::ptr::null_mut(); assert_ne!( @@ -271,6 +287,13 @@ mod tests { assert!(invalid.is_null()); assert_eq!(set_default_voice(&OBJECT, Some(synth)), S_OK); let spoken_text = wave(synth, 0x68, c"test"); + // Simulate losing the host service after the title has acquired its handle. + let Synthesizer::Windows(engine) = synth else { + panic!("expected a Windows voice") + }; + engine.Close().unwrap(); + assert_eq!(wave(synth, 0x68, c"test"), SILENCE); + assert_eq!(wave(synth, 0xa8, &ssml), SILENCE); assert_eq!(close(&OBJECT, handle), S_OK); for wav in [spoken_text, spoken_ssml] { let size = |bytes: &[u8]| u32::from_le_bytes(bytes.try_into().unwrap()) as usize; @@ -290,7 +313,10 @@ mod tests { chunks = &chunks[8 + len + (len % 2)..]; } let fmt = format.unwrap(); + assert_eq!(u16::from_le_bytes(fmt[0..2].try_into().unwrap()), 1); // PCM assert_eq!(size(&fmt[4..8]), 48_000); + assert_eq!(size(&fmt[8..12]), 96_000); + assert_eq!(u16::from_le_bytes(fmt[12..14].try_into().unwrap()), 2); assert_eq!(u16::from_le_bytes(fmt[2..4].try_into().unwrap()), 1); assert_eq!(u16::from_le_bytes(fmt[14..16].try_into().unwrap()), 16); assert!(samples.unwrap().iter().any(|&byte| byte != 0)); diff --git a/crates/xtp-hle/src/modules/speech/narrator.rs b/crates/xtp-hle/src/modules/speech/narrator.rs index d6cc5cd8..b19579bb 100644 --- a/crates/xtp-hle/src/modules/speech/narrator.rs +++ b/crates/xtp-hle/src/modules/speech/narrator.rs @@ -1,23 +1,29 @@ //! Windows voices and in-memory conversion to the title's 48 kHz WAVE format. use std::ffi::{CString, c_void}; +use windows::Data::Xml::Dom::{XmlDocument, XmlLoadSettings}; use windows::Media::MediaProperties::{ AudioEncodingProperties, AudioEncodingQuality, MediaEncodingProfile, }; -use windows::Media::SpeechSynthesis::{SpeechSynthesizer, VoiceGender, VoiceInformation}; +use windows::Media::SpeechSynthesis::{ + SpeechSynthesisStream, SpeechSynthesizer, VoiceGender, VoiceInformation, +}; use windows::Media::Transcoding::MediaTranscoder; use windows::Storage::Streams::{DataReader, InMemoryRandomAccessStream}; use windows::Win32::Foundation::{E_BOUNDS, E_FAIL, E_INVALIDARG}; -use windows::core::{HSTRING, Result}; +use windows::core::{HRESULT, HSTRING, Result, h}; + +use super::{SILENCE, VoiceCallback, VoiceInfo}; -use super::{VoiceCallback, VoiceInfo}; +// WinRT reports malformed SSML as a FormatException. +const COR_E_FORMAT: HRESULT = HRESULT(0x8013_1537_u32 as i32); fn installed_voices() -> Result> { // On hosts without the speech service even opening the catalog can fail. let voices = match SpeechSynthesizer::AllVoices() { Ok(voices) => voices, Err(error) => { - tracing::debug!(%error, "Windows speech voices unavailable"); + tracing::warn!(%error, "Windows speech voices unavailable"); return Ok(Vec::new()); } }; @@ -67,14 +73,54 @@ pub(super) fn set_voice(engine: &SpeechSynthesizer, id: Option<&str>) -> Result< } pub(super) fn render(engine: &SpeechSynthesizer, words: &str, ssml: bool) -> Result> { + if !ssml && words.trim().is_empty() { + return Ok(SILENCE.to_vec()); + } let words = HSTRING::from(words); let speech = if ssml { - engine.SynthesizeSsmlToStreamAsync(&words)? + offline_ssml(words).and_then(|markup| engine.SynthesizeSsmlToStreamAsync(&markup)) } else { - engine.SynthesizeTextToStreamAsync(&words)? + engine.SynthesizeTextToStreamAsync(&words) + } + .and_then(|op| op.join()); + match speech { + Err(error) if ssml && error.code() == COR_E_FORMAT => Err(error), + result => Ok(result.and_then(to_wave).unwrap_or_else(|error| { + tracing::warn!(%error, "could not render Windows speech; using silence"); + SILENCE.to_vec() + })), + } +} + +/// Use the audio element's fallback content. The host receives no audio source to load. +fn offline_ssml(words: HSTRING) -> Result { + let doc = XmlDocument::new()?; + let settings = XmlLoadSettings::new()?; + settings.SetProhibitDtd(true)?; + settings.SetResolveExternals(false)?; + settings.SetElementContentWhiteSpace(true)?; + doc.LoadXmlWithSettings(&words, &settings) + .map_err(|_| COR_E_FORMAT)?; + let nodes = doc.SelectNodes(h!("//*[local-name()='audio']"))?; + let count = nodes.Length()?; + if count == 0 { + return Ok(words); } - .join()?; + // Unwrap nested audio first. A desc child describes the recording and is + // not part of the fallback narration. + for index in (0..count).rev() { + let audio = nodes.Item(index)?; + let parent = audio.ParentNode()?; + let fallback = audio.SelectNodes(h!("node()[local-name() != 'desc']"))?; + for i in 0..fallback.Length()? { + parent.InsertBefore(&fallback.Item(i)?, &audio)?; + } + parent.RemoveChild(&audio)?; + } + doc.GetXml() +} +fn to_wave(speech: SpeechSynthesisStream) -> Result> { let wave = InMemoryRandomAccessStream::new()?; let profile = MediaEncodingProfile::CreateWav(AudioEncodingQuality::Auto)?; profile.SetAudio(&AudioEncodingProperties::CreatePcm(48_000, 1, 16)?)?; @@ -98,3 +144,18 @@ pub(super) fn render(engine: &SpeechSynthesizer, words: &str, ssml: bool) -> Res reader.ReadBytes(&mut bytes)?; Ok(bytes) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn audio_references_keep_only_the_fallback_in_document_order() { + let markup = h!( + "one recordingtwo four" + ); + let result = offline_ssml(markup.clone()).unwrap().to_string(); + assert!(result.contains("one two three four"), "{result}"); + assert!(!result.contains(".wav") && !result.contains("recording")); + } +} diff --git a/docs/analysis/hle.md b/docs/analysis/hle.md index 42ea91f0..e27e3217 100644 --- a/docs/analysis/hle.md +++ b/docs/analysis/hle.md @@ -174,7 +174,7 @@ Legend: ✔ implemented and tested, ◐ partial, ✘ missing, — not needed. | XNetworking: stack up, reaches nothing | ✔ | ✔ real hints, CryptoAPI certificate checks | 1 / 7 | Keep XTP (offline by design) | | XGameUi: profile card, text entry (host dialog) | ✔ | → PC runtime | 1 / — | Keep XTP | | XGameUi message and error dialogs | ✘ | → PC runtime | — / — | **New work** (R5) | -| Speech synthesis | ◐ valid empty WAVE | → PC runtime | 1 / — | **New work** (R6) | +| Speech synthesis | ✔ Windows voices, text and SSML to 48 kHz PCM | → PC runtime | 4 / — | Done (R6) | | Closed captions, high contrast | ✔ Windows settings and title override | ✔ `accessibility.rs` | 5 / 3 | Done (R7) | | XError callback and options | ✘ class absent | ✔ | — / — | After xcl, if the title asks (R9) | | Relaunch (`XLaunchNewGame`), restart on crash | ◐ relaunch untested live | ✔ both | 4 (lifecycle) / — | Verify (R10) | @@ -395,15 +395,13 @@ shows the title calls them. defaults when the host has no setting; set-enabled is read back. - **Depends on:** — -### R6. Speech synthesis through the host — M +### R6. Speech synthesis through the host — M (done) - **Goal:** narration speaks: voices enumerated from the host's speech synthesizer, text and SSML streams rendered to 48 kHz WAVE in memory. -- **Files:** `crates/xtp-hle/src/modules/speech.rs`, `crates/xtp-hle/Cargo.toml` - (WinRT speech or SAPI features). +- **Files:** `crates/xtp-hle/src/modules/speech.rs` and `speech/narrator.rs`. - **xcl ref:** none (xcl forwards speech to the PC runtime). New work. -- **Acceptance:** Windows test: a stream for "test" is a valid WAVE file - with non-zero length; with no voice installed the current empty-stream - behaviour remains. +- **Acceptance:** Windows tests check PCM output for text and SSML, and the + empty WAVE for blank text, an unavailable voice, or a failed host engine. - **Depends on:** — ### I3. Trigger rumble — M @@ -513,7 +511,7 @@ shows the title calls them. | 10 | R5 message/error dialogs | M | (R1) | | 11 | R10 relaunch, restart on crash | S | — | | 12 | R7 closed captions, high contrast (done) | S | — | -| 13 | R6 speech synthesis | M | — | +| 13 | R6 speech synthesis (done) | M | — | | 14 | I3 trigger rumble | M | — | | 15 | K1 commit measurement | S | — | | 16 | K2 lazy commit | M | K1 |