diff --git a/Cargo.lock b/Cargo.lock index 324bc0bdf..cb2a50ac1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -560,6 +560,7 @@ dependencies = [ "serde_json", "toml", "windows", + "windows-core", "windows-sys 0.61.2", ] diff --git a/README.md b/README.md index bdb207620..311618398 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,7 @@ XCL works only on unpacked game files you already own. It does not download, dec | **XGameRuntime** | ✅ | the GDK thunk protocol real titles use, laid out from a table of all 396 GDK runtime functions; offline XUser, XGameSave, persistent local storage, XPackage, XGame (title id), XSystem – the title sees an Xbox Series X / S; task queues, async, networking and dialogs through the PC's XGameRuntime | the game's libHttpClient initialises; users, saves and storage through the real call path; slot layout cross-checked against the game's own thunks | | **Input** | ✅ | GameInput: one gamepad – the PC's XInput controller or a PlayStation controller, and keyboard and mouse as a gamepad (see [Controls](#controls)) | unit tests; an Xbox controller in Minecraft; a DualShock 4 (USB) | | **Audio** | ✅ | XAudio2 → system XAudio2.9 (PCM / float voices; Opus 0x704F decoded via `MSOpusDecoder.dll`; XMA1 / XMA2 decoded in pure Rust) | unit + end-to-end tests | +| **Spatial audio fallback** | ✅ | Titles can submit spatial audio to a silent render endpoint when Windows has no active playback device (#695) | synthetic client exercises endpoint discovery, stream timing and audio buffers | ### Graphics diff --git a/crates/xcl/Cargo.toml b/crates/xcl/Cargo.toml index c3b23a1b8..bc2230574 100644 --- a/crates/xcl/Cargo.toml +++ b/crates/xcl/Cargo.toml @@ -19,6 +19,7 @@ retour = "0.3" serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "1" +windows-core = "0.62" [dependencies.windows] version = "0.62" @@ -35,8 +36,11 @@ features = [ "Win32_Media_MediaFoundation", "Win32_Security", "Win32_System_Com", + "Win32_System_Com_StructuredStorage", "Win32_System_LibraryLoader", "Win32_System_Threading", + "Win32_System_Variant", + "Win32_UI_Shell_PropertiesSystem", "Win32_UI_WindowsAndMessaging", ] diff --git a/crates/xcl/src/hle/mod.rs b/crates/xcl/src/hle/mod.rs index abea3ae4e..53608bede 100644 --- a/crates/xcl/src/hle/mod.rs +++ b/crates/xcl/src/hle/mod.rs @@ -24,6 +24,7 @@ pub mod mfplat; pub mod netoff; pub mod opus; pub mod playstation; +mod spatial_audio; pub mod user; pub mod xaudio2; pub mod xma2; @@ -97,6 +98,7 @@ pub const MINUSERX: &str = "minuserx.dll"; pub const ACPHAL: &str = "acphal.dll"; /// controllers (`GameInputCreate`) pub const GAMEINPUT: &str = "gameinput.dll"; +const SPATIAL_AUDIO: &str = "xcl-spatial-audio.dll"; fn build(config: &Config) -> Registry { let mut modules = vec![ @@ -111,6 +113,7 @@ fn build(config: &Config) -> Registry { HleModule::new(XG, xg::exports(), &[]), HleModule::new(ACPHAL, acphal::exports(), &[]), HleModule::new(GAMEINPUT, gameinput::exports(), &[]), + HleModule::new(SPATIAL_AUDIO, spatial_audio::exports(), &[SELF]), ]; let offline = netoff::enabled(); if offline { @@ -155,6 +158,10 @@ fn build(config: &Config) -> Registry { ] { routes.push((p.into(), Route::Hle(k))); } + let audio = idx(SPATIAL_AUDIO); + for p in ["ole32.dll", "combase.dll"] { + routes.push((p.into(), Route::Hle(audio))); + } let x = idx(XGAMERUNTIME); for p in ["xgameruntime.dll", "xgameruntime*.dll", "xgameplatform.dll"] { routes.push((p.into(), Route::Hle(x))); diff --git a/crates/xcl/src/hle/spatial_audio.rs b/crates/xcl/src/hle/spatial_audio.rs new file mode 100644 index 000000000..c57479df0 --- /dev/null +++ b/crates/xcl/src/hle/spatial_audio.rs @@ -0,0 +1,362 @@ +//! Guest-only spatial audio fallback for hosts without an active render endpoint (#695). + +use std::cell::UnsafeCell; +use std::ffi::c_void; +use std::mem::size_of; +use std::ptr::null_mut; + +use windows::core::{GUID, HRESULT, Interface, PCWSTR, PWSTR, Ref, Result, implement, w}; +use windows::Win32::Foundation::{ + E_INVALIDARG, E_NOINTERFACE, E_OUTOFMEMORY, E_POINTER, ERROR_NOT_FOUND, PROPERTYKEY, +}; +use windows::Win32::Media::Audio::*; +use windows::Win32::System::Com::StructuredStorage::PROPVARIANT; +use windows::Win32::System::Com::{CLSCTX, CoTaskMemAlloc, STGM}; +use windows::Win32::System::Variant::{VT_BLOB, VT_LPWSTR}; +use windows::Win32::UI::Shell::PropertiesSystem::{IPropertyStore, PSCreateMemoryPropertyStore}; + +mod stream; +#[cfg(test)] +mod tests; + +use stream::{FRAMES_PER_BUFFER, MAX_DYNAMIC_OBJECTS, SilentStream}; + +const ENDPOINT_ID: PCWSTR = w!("{0.0.0.00000000}.{A6CC38B1-1B18-4C4A-8ECC-739984D91271}"); +const FRIENDLY_NAME: PCWSTR = w!("XCL Silent Spatial Audio"); +const FRIENDLY_NAME_KEY: PROPERTYKEY = PROPERTYKEY { + fmtid: GUID::from_u128(0xa45c254e_df1c_4efd_8020_67d146a850e0), + pid: 14, +}; +const NO_ENDPOINT: HRESULT = HRESULT::from_win32(ERROR_NOT_FOUND.0); + +pub(super) fn exports() -> Vec<(&'static str, usize)> { + crate::hle_exports![CoCreateInstance] +} + +#[allow(non_snake_case)] // Windows export name +unsafe extern "system" fn CoCreateInstance( + clsid: *const GUID, + outer: *mut c_void, + context: u32, + iid: *const GUID, + out: *mut *mut c_void, +) -> HRESULT { + let hr = HRESULT(unsafe { + windows_sys::Win32::System::Com::CoCreateInstance( + clsid.cast(), outer, context, iid.cast(), out, + ) + }); + if hr.is_ok() + && outer.is_null() + && unsafe { clsid.as_ref() } == Some(&MMDeviceEnumerator) + && unsafe { iid.as_ref() } == Some(&IMMDeviceEnumerator::IID) + && !out.is_null() + && !unsafe { *out }.is_null() + { + // Take ownership of the reference returned by Windows and transfer it (or + // the replacement) back to the guest with the same COM ownership rules. + let native = unsafe { IMMDeviceEnumerator::from_raw(*out) }; + unsafe { out.write(with_silent_endpoint(native).into_raw()) }; + } + hr +} + +fn no_active_render_device(native: &IMMDeviceEnumerator) -> bool { + matches!( + unsafe { native.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE) } + .and_then(|devices| unsafe { devices.GetCount() }), + Ok(0) + ) +} + +fn with_silent_endpoint(native: IMMDeviceEnumerator) -> IMMDeviceEnumerator { + if no_active_render_device(&native) { + SilentDeviceEnumerator { native, silent: SilentDevice.into() }.into() + } else { + native + } +} + +#[implement(IMMDeviceEnumerator)] +struct SilentDeviceEnumerator { + native: IMMDeviceEnumerator, + silent: IMMDevice, +} + +impl IMMDeviceEnumerator_Impl for SilentDeviceEnumerator_Impl { + fn EnumAudioEndpoints(&self, flow: EDataFlow, state: DEVICE_STATE) -> Result { + let native = unsafe { self.native.EnumAudioEndpoints(flow, state) }?; + if (flow != eRender && flow != eAll) || state.0 & DEVICE_STATE_ACTIVE.0 == 0 { + return Ok(native); + } + let count = unsafe { native.GetCount() }?; + let can_add_silent = if flow == eRender && state == DEVICE_STATE_ACTIVE { + count == 0 + } else { + no_active_render_device(&self.native) + }; + if can_add_silent { + Ok(SilentDeviceCollection { native, native_count: count, silent: self.silent.clone() }.into()) + } else { + Ok(native) + } + } + + fn GetDefaultAudioEndpoint(&self, flow: EDataFlow, role: ERole) -> Result { + match unsafe { self.native.GetDefaultAudioEndpoint(flow, role) } { + Err(err) if flow == eRender && err.code() == NO_ENDPOINT + && no_active_render_device(&self.native) => Ok(self.silent.clone()), + result => result, + } + } + + fn GetDevice(&self, id: &PCWSTR) -> Result { + if !id.is_null() && unsafe { id.as_wide() == ENDPOINT_ID.as_wide() } { + return Ok(self.silent.clone()); + } + unsafe { self.native.GetDevice(*id) } + } + + fn RegisterEndpointNotificationCallback(&self, client: Ref) -> Result<()> { + unsafe { self.native.RegisterEndpointNotificationCallback(client.ok()?) } + } + + fn UnregisterEndpointNotificationCallback(&self, client: Ref) -> Result<()> { + unsafe { self.native.UnregisterEndpointNotificationCallback(client.ok()?) } + } +} + +#[implement(IMMDeviceCollection)] +struct SilentDeviceCollection { + native: IMMDeviceCollection, + native_count: u32, + silent: IMMDevice, +} + +impl IMMDeviceCollection_Impl for SilentDeviceCollection_Impl { + fn GetCount(&self) -> Result { + Ok(self.native_count + 1) + } + + fn Item(&self, index: u32) -> Result { + if index == self.native_count { + return Ok(self.silent.clone()); + } + unsafe { self.native.Item(index) } + } +} + +#[implement(IMMDevice, IMMEndpoint)] +struct SilentDevice; + +impl IMMDevice_Impl for SilentDevice_Impl { + fn Activate( + &self, iid: *const GUID, _context: CLSCTX, _params: *const PROPVARIANT, out: *mut *mut c_void, + ) -> Result<()> { + let out = unsafe { out.as_mut() }.ok_or(E_POINTER)?; + *out = null_mut(); + if unsafe { iid.as_ref() }.ok_or(E_POINTER)? != &ISpatialAudioClient::IID { + return Err(E_NOINTERFACE.into()); + } + let client: ISpatialAudioClient = SilentSpatialClient.into(); + *out = client.into_raw(); + crate::xlog_info!("spatial audio: using XCL's silent renderer"); + Ok(()) + } + + fn OpenPropertyStore(&self, _access: STGM) -> Result { + // The property store is transient. The guest can query the endpoint's name. + unsafe { + let mut raw = null_mut(); + PSCreateMemoryPropertyStore(&IPropertyStore::IID, &mut raw)?; + let store = IPropertyStore::from_raw(raw); + let mut value = PROPVARIANT::default(); + let string = copy_com_string(FRIENDLY_NAME)?; + let inner = &mut *value.Anonymous.Anonymous; + inner.vt = VT_LPWSTR; + inner.Anonymous.pwszVal = string; + store.SetValue(&FRIENDLY_NAME_KEY, &value)?; + Ok(store) + } + } + + fn GetId(&self) -> Result { + copy_com_string(ENDPOINT_ID) + } + + fn GetState(&self) -> Result { + Ok(DEVICE_STATE_ACTIVE) + } +} + +impl IMMEndpoint_Impl for SilentDevice_Impl { + fn GetDataFlow(&self) -> Result { + Ok(eRender) + } +} + +fn copy_com_string(string: PCWSTR) -> Result { + // Both callers pass static, nul-terminated strings. The guest owns the copy. + let words = unsafe { string.as_wide() }.len() + 1; + let dest = unsafe { CoTaskMemAlloc(words * size_of::()) }.cast::(); + if dest.is_null() { + return Err(E_OUTOFMEMORY.into()); + } + unsafe { string.0.copy_to_nonoverlapping(dest, words) }; + Ok(PWSTR(dest)) +} + +const SAMPLE_RATE: u32 = 48_000; +const SAMPLE_BYTES: u16 = size_of::() as u16; +const WAVE_FORMAT_IEEE_FLOAT: u16 = 3; +const WAVE_FORMAT_EXTENSIBLE: u16 = 0xfffe; +const IEEE_FLOAT_SUBFORMAT: GUID = GUID::from_u128(0x00000003_0000_0010_8000_00aa00389b71); +const FLOAT_FORMAT: WAVEFORMATEX = WAVEFORMATEX { + wFormatTag: WAVE_FORMAT_IEEE_FLOAT, + nChannels: 1, + nSamplesPerSec: SAMPLE_RATE, + nAvgBytesPerSec: SAMPLE_RATE * SAMPLE_BYTES as u32, + nBlockAlign: SAMPLE_BYTES, + wBitsPerSample: SAMPLE_BYTES * 8, + cbSize: 0, +}; + +#[implement(IAudioFormatEnumerator)] +struct SilentAudioFormat(UnsafeCell); + +impl IAudioFormatEnumerator_Impl for SilentAudioFormat_Impl { + fn GetCount(&self) -> Result { + Ok(1) + } + + fn GetFormat(&self, index: u32) -> Result<*mut WAVEFORMATEX> { + if index != 0 { + return Err(E_INVALIDARG.into()); + } + // The enumerator owns the format for as long as the guest keeps it alive. + Ok(self.0.get()) + } +} + +const STATIC_SPEAKERS: [(AudioObjectType, [f32; 3]); 12] = [ + (AudioObjectType_FrontLeft, [-1.0, 0.0, -1.0]), + (AudioObjectType_FrontRight, [1.0, 0.0, -1.0]), + (AudioObjectType_FrontCenter, [0.0, 0.0, -1.0]), + (AudioObjectType_LowFrequency, [0.0, 0.0, -1.0]), + (AudioObjectType_SideLeft, [-1.0, 0.0, 0.0]), + (AudioObjectType_SideRight, [1.0, 0.0, 0.0]), + (AudioObjectType_BackLeft, [-1.0, 0.0, 1.0]), + (AudioObjectType_BackRight, [1.0, 0.0, 1.0]), + (AudioObjectType_TopFrontLeft, [-1.0, 1.0, -1.0]), + (AudioObjectType_TopFrontRight, [1.0, 1.0, -1.0]), + (AudioObjectType_TopBackLeft, [-1.0, 1.0, 1.0]), + (AudioObjectType_TopBackRight, [1.0, 1.0, 1.0]), +]; + +#[implement(ISpatialAudioClient)] +struct SilentSpatialClient; + +impl ISpatialAudioClient_Impl for SilentSpatialClient_Impl { + fn GetStaticObjectPosition( + &self, kind: AudioObjectType, x: *mut f32, y: *mut f32, z: *mut f32, + ) -> Result<()> { + if x.is_null() || y.is_null() || z.is_null() { + return Err(E_POINTER.into()); + } + let (_, position) = STATIC_SPEAKERS.iter().find(|(speaker, _)| *speaker == kind) + .ok_or(SPTLAUDCLNT_E_STATIC_OBJECT_NOT_AVAILABLE)?; + unsafe { + x.write(position[0]); + y.write(position[1]); + z.write(position[2]); + } + Ok(()) + } + + fn GetNativeStaticObjectTypeMask(&self) -> Result { + Ok(AudioObjectType(STATIC_SPEAKERS.iter().fold(0, |mask, (kind, _)| mask | kind.0))) + } + + fn GetMaxDynamicObjectCount(&self) -> Result { + Ok(MAX_DYNAMIC_OBJECTS) + } + + fn GetSupportedAudioObjectFormatEnumerator(&self) -> Result { + Ok(SilentAudioFormat(UnsafeCell::new(FLOAT_FORMAT)).into()) + } + + fn GetMaxFrameCount(&self, format: *const WAVEFORMATEX) -> Result { + self.IsAudioObjectFormatSupported(format)?; + Ok(FRAMES_PER_BUFFER) + } + + fn IsAudioObjectFormatSupported(&self, format: *const WAVEFORMATEX) -> Result<()> { + let wave = unsafe { format.as_ref() }.ok_or(E_POINTER)?; + if wave.nChannels != FLOAT_FORMAT.nChannels + || wave.nSamplesPerSec != FLOAT_FORMAT.nSamplesPerSec + || wave.nAvgBytesPerSec != FLOAT_FORMAT.nAvgBytesPerSec + || wave.nBlockAlign != FLOAT_FORMAT.nBlockAlign + || wave.wBitsPerSample != FLOAT_FORMAT.wBitsPerSample + { + return Err(AUDCLNT_E_UNSUPPORTED_FORMAT.into()); + } + match wave.wFormatTag { + WAVE_FORMAT_IEEE_FLOAT => Ok(()), + WAVE_FORMAT_EXTENSIBLE + if usize::from(wave.cbSize) >= size_of::() - size_of::() => + { + let extended = unsafe { format.cast::().read_unaligned() }; + let subformat = extended.SubFormat; + if subformat == IEEE_FLOAT_SUBFORMAT + && unsafe { extended.Samples.wValidBitsPerSample } == FLOAT_FORMAT.wBitsPerSample + { + Ok(()) + } else { + Err(AUDCLNT_E_UNSUPPORTED_FORMAT.into()) + } + } + _ => Err(AUDCLNT_E_UNSUPPORTED_FORMAT.into()), + } + } + + fn IsSpatialAudioStreamAvailable(&self, iid: *const GUID, _params: *const PROPVARIANT) -> Result<()> { + let iid = unsafe { iid.as_ref() }.ok_or(E_POINTER)?; + if iid != &ISpatialAudioObjectRenderStream::IID { + return Err(SPTLAUDCLNT_E_STREAM_NOT_AVAILABLE.into()); + } + Ok(()) + } + + fn ActivateSpatialAudioStream( + &self, params: *const PROPVARIANT, iid: *const GUID, out: *mut *mut c_void, + ) -> Result<()> { + let out = unsafe { out.as_mut() }.ok_or(E_POINTER)?; + *out = null_mut(); + self.IsSpatialAudioStreamAvailable(iid, params)?; + let params = unsafe { params.as_ref() }.ok_or(E_POINTER)?; + let variant = unsafe { &*params.Anonymous.Anonymous }; + if variant.vt != VT_BLOB { + return Err(E_INVALIDARG.into()); + } + let blob = unsafe { variant.Anonymous.blob }; + let data = blob.pBlobData.cast::(); + if blob.cbSize as usize != size_of::() + || data.is_null() + { + return Err(E_INVALIDARG.into()); + } + let params = unsafe { &*data }; + self.IsAudioObjectFormatSupported(params.ObjectFormat)?; + if params.MinDynamicObjectCount > params.MaxDynamicObjectCount + || params.MaxDynamicObjectCount > MAX_DYNAMIC_OBJECTS + { + return Err(E_INVALIDARG.into()); + } + if params.StaticObjectTypeMask.0 & !self.GetNativeStaticObjectTypeMask()?.0 != 0 { + return Err(SPTLAUDCLNT_E_STATIC_OBJECT_NOT_AVAILABLE.into()); + } + let stream: ISpatialAudioObjectRenderStream = SilentStream::new(params)?.into(); + *out = stream.into_raw(); + Ok(()) + } +} diff --git a/crates/xcl/src/hle/spatial_audio/stream.rs b/crates/xcl/src/hle/spatial_audio/stream.rs new file mode 100644 index 000000000..1e15da5fd --- /dev/null +++ b/crates/xcl/src/hle/spatial_audio/stream.rs @@ -0,0 +1,342 @@ +//! Timing and disposable mix buffers for the silent spatial renderer. + +use std::cell::UnsafeCell; +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::size_of; +use std::ptr::{null, null_mut}; +use std::sync::{Arc, Mutex, Weak}; + +use windows::core::{BOOL, Error, GUID, Result, implement}; +use windows::Win32::Foundation::{E_INVALIDARG, E_NOINTERFACE, E_POINTER}; +use windows::Win32::Media::Audio::*; +use windows_sys::Win32::Foundation::{ + CloseHandle, DUPLICATE_SAME_ACCESS, DuplicateHandle, FILETIME, HANDLE, +}; +use windows_sys::Win32::System::Threading::{ + CloseThreadpoolTimer, CreateThreadpoolTimer, GetCurrentProcess, PTP_CALLBACK_INSTANCE, + PTP_TIMER, ResetEvent, SetEvent, SetThreadpoolTimer, WaitForThreadpoolTimerCallbacks, +}; + +const PERIOD_MS: u32 = 10; +pub(super) const FRAMES_PER_BUFFER: u32 = super::SAMPLE_RATE * PERIOD_MS / 1000; +pub(super) const MAX_DYNAMIC_OBJECTS: u32 = 128; +type Buffer = [f32; FRAMES_PER_BUFFER as usize]; + +struct BufferClock { + event: HANDLE, + timer: PTP_TIMER, +} + +unsafe extern "system" fn signal_buffer( + _instance: PTP_CALLBACK_INSTANCE, event: *mut c_void, _timer: PTP_TIMER, +) { + // The timer owns the duplicate until cancellation has drained every callback. + unsafe { SetEvent(event) }; +} + +impl BufferClock { + fn new(event: HANDLE) -> Result { + if event.is_null() { + return Err(E_INVALIDARG.into()); + } + let mut duplicate = null_mut(); + unsafe { + let process = GetCurrentProcess(); + if DuplicateHandle(process, event, process, &mut duplicate, 0, 0, DUPLICATE_SAME_ACCESS) == 0 { + return Err(Error::from_thread()); + } + let timer = CreateThreadpoolTimer(Some(signal_buffer), duplicate, null()); + if timer == 0 { + let err = Error::from_thread(); + CloseHandle(duplicate); + return Err(err); + } + Ok(Self { event: duplicate, timer }) + } + } + + fn start(&self) { + // Negative FILETIME values are relative. Request the first buffer immediately. + let due = FILETIME { dwLowDateTime: u32::MAX, dwHighDateTime: u32::MAX }; + unsafe { SetThreadpoolTimer(self.timer, &due, PERIOD_MS, 0) }; + } + + fn cancel(&self) { + unsafe { + SetThreadpoolTimer(self.timer, null(), 0, 0); + WaitForThreadpoolTimerCallbacks(self.timer, 1); + } + } + + fn stop(&self) { + self.cancel(); + unsafe { ResetEvent(self.event) }; + } +} + +impl Drop for BufferClock { + fn drop(&mut self) { + self.cancel(); + unsafe { + CloseThreadpoolTimer(self.timer); + CloseHandle(self.event); + } + } +} + +#[derive(Default, PartialEq, Eq)] +enum Phase { + #[default] + Stopped, + Ready, + Updating, +} + +struct ObjectState { + kind: AudioObjectType, + buffer: BufferState, +} + +#[derive(PartialEq, Eq)] +enum BufferState { + New, + Written(u64), + Ending, + Inactive, +} + +#[derive(Default)] +struct StreamState { + phase: Phase, + pass: u64, + next_object: u64, + objects: HashMap, +} + +impl StreamState { + fn dynamic_slots_left(&self, max: u32) -> u32 { + max - self.objects.values().filter(|object| object.kind == AudioObjectType_Dynamic).count() as u32 + } + + fn updating(&self) -> Result<()> { + if self.phase != Phase::Updating { + return Err(SPTLAUDCLNT_E_OUT_OF_ORDER.into()); + } + Ok(()) + } + + fn updating_object(&mut self, id: u64) -> Result<&mut ObjectState> { + self.updating()?; + self.objects.get_mut(&id) + .filter(|object| object.buffer != BufferState::Inactive) + .ok_or_else(|| SPTLAUDCLNT_E_RESOURCES_INVALIDATED.into()) + } +} + +#[implement(ISpatialAudioObjectRenderStream)] +pub(super) struct SilentStream { + clock: BufferClock, + state: Arc>, + static_mask: AudioObjectType, + max_dynamic: u32, +} + +impl SilentStream { + pub(super) fn new(params: &SpatialAudioObjectRenderStreamActivationParams) -> Result { + // Dynamic capacity is fixed, so a capacity-change notification is never needed. + Ok(Self { + clock: BufferClock::new(params.EventHandle.0)?, + state: Arc::new(Mutex::new(StreamState::default())), + static_mask: params.StaticObjectTypeMask, + max_dynamic: params.MaxDynamicObjectCount, + }) + } +} + +impl ISpatialAudioObjectRenderStreamBase_Impl for SilentStream_Impl { + fn GetAvailableDynamicObjectCount(&self) -> Result { + Ok(self.state.lock().unwrap().dynamic_slots_left(self.max_dynamic)) + } + + fn GetService(&self, _iid: *const GUID, service: *mut *mut c_void) -> Result<()> { + let service = unsafe { service.as_mut() }.ok_or(E_POINTER)?; + *service = null_mut(); + Err(E_NOINTERFACE.into()) + } + + fn Start(&self) -> Result<()> { + let mut state = self.state.lock().unwrap(); + if state.phase != Phase::Stopped { + return Err(SPTLAUDCLNT_E_STREAM_NOT_STOPPED.into()); + } + state.phase = Phase::Ready; + self.clock.start(); + Ok(()) + } + + fn Stop(&self) -> Result<()> { + let mut state = self.state.lock().unwrap(); + if state.phase != Phase::Stopped { + self.clock.stop(); + state.phase = Phase::Stopped; + } + Ok(()) + } + + fn Reset(&self) -> Result<()> { + let mut state = self.state.lock().unwrap(); + if state.phase != Phase::Stopped { + return Err(SPTLAUDCLNT_E_STREAM_NOT_STOPPED.into()); + } + state.objects.clear(); + Ok(()) + } + + fn BeginUpdatingAudioObjects(&self, available: *mut u32, frames: *mut u32) -> Result<()> { + if available.is_null() || frames.is_null() { + return Err(E_POINTER.into()); + } + let mut state = self.state.lock().unwrap(); + if state.phase != Phase::Ready { + return Err(SPTLAUDCLNT_E_OUT_OF_ORDER.into()); + } + state.phase = Phase::Updating; + state.pass = state.pass.wrapping_add(1); + unsafe { + available.write(state.dynamic_slots_left(self.max_dynamic)); + frames.write(FRAMES_PER_BUFFER); + } + Ok(()) + } + + fn EndUpdatingAudioObjects(&self) -> Result<()> { + let mut state = self.state.lock().unwrap(); + state.updating()?; + let pass = state.pass; + // An object that starts writing must write in every pass. After it ends, + // its slot remains reserved until the guest releases the COM object. + for object in state.objects.values_mut() { + if object.buffer == BufferState::Ending + || matches!(object.buffer, BufferState::Written(last) if last != pass) + { + object.buffer = BufferState::Inactive; + } + } + state.phase = Phase::Ready; + Ok(()) + } +} + +impl ISpatialAudioObjectRenderStream_Impl for SilentStream_Impl { + fn ActivateSpatialAudioObject(&self, kind: AudioObjectType) -> Result { + let mut state = self.state.lock().unwrap(); + if kind == AudioObjectType_Dynamic { + if state.dynamic_slots_left(self.max_dynamic) == 0 { + return Err(SPTLAUDCLNT_E_NO_MORE_OBJECTS.into()); + } + } else { + if kind != AudioObjectType_None + && (kind.0.count_ones() != 1 || kind.0 & self.static_mask.0 == 0) + { + return Err(SPTLAUDCLNT_E_STATIC_OBJECT_NOT_AVAILABLE.into()); + } + if state.objects.values().any(|object| object.kind == kind) { + return Err(SPTLAUDCLNT_E_OBJECT_ALREADY_ACTIVE.into()); + } + } + let id = state.next_object; + state.next_object += 1; + state.objects.insert(id, ObjectState { kind, buffer: BufferState::New }); + Ok(SilentObject { + kind, + id, + state: Arc::downgrade(&self.state), + buffer: UnsafeCell::new([0.0; FRAMES_PER_BUFFER as usize]), + }.into()) + } +} + +#[implement(ISpatialAudioObject)] +struct SilentObject { + kind: AudioObjectType, + id: u64, + state: Weak>, + buffer: UnsafeCell, +} + +impl SilentObject { + fn stream(&self) -> Result>> { + self.state.upgrade().ok_or_else(|| SPTLAUDCLNT_E_RESOURCES_INVALIDATED.into()) + } + + fn check_active(&self) -> Result<()> { + let state = self.stream()?; + let state = state.lock().unwrap(); + if !state.objects.get(&self.id).is_some_and(|object| object.buffer != BufferState::Inactive) { + return Err(SPTLAUDCLNT_E_RESOURCES_INVALIDATED.into()); + } + Ok(()) + } +} + +impl Drop for SilentObject { + fn drop(&mut self) { + if let Some(state) = self.state.upgrade() { + state.lock().unwrap().objects.remove(&self.id); + } + } +} + +impl ISpatialAudioObjectBase_Impl for SilentObject_Impl { + fn GetBuffer(&self, buffer: *mut *mut u8, bytes: *mut u32) -> Result<()> { + if buffer.is_null() || bytes.is_null() { + return Err(E_POINTER.into()); + } + let state = self.stream()?; + let mut state = state.lock().unwrap(); + let pass = state.pass; + let object = state.updating_object(self.id)?; + if object.buffer != BufferState::Ending { + object.buffer = BufferState::Written(pass); + } + // The guest fills this scratch buffer before ending the pass. The renderer + // only tracks its lifetime, since there is no host device to play it. + unsafe { + buffer.write(self.buffer.get().cast()); + bytes.write(size_of::() as u32); + } + Ok(()) + } + + fn SetEndOfStream(&self, frames: u32) -> Result<()> { + if frames > FRAMES_PER_BUFFER { + return Err(E_INVALIDARG.into()); + } + let state = self.stream()?; + let mut state = state.lock().unwrap(); + state.updating_object(self.id)?.buffer = BufferState::Ending; + Ok(()) + } + + fn IsActive(&self) -> Result { + Ok(self.check_active().is_ok().into()) + } + + fn GetAudioObjectType(&self) -> Result { + Ok(self.kind) + } +} + +impl ISpatialAudioObject_Impl for SilentObject_Impl { + fn SetPosition(&self, _x: f32, _y: f32, _z: f32) -> Result<()> { + if self.kind != AudioObjectType_Dynamic { + return Err(SPTLAUDCLNT_E_PROPERTY_NOT_SUPPORTED.into()); + } + self.check_active() + } + + fn SetVolume(&self, _volume: f32) -> Result<()> { + self.check_active() + } +} diff --git a/crates/xcl/src/hle/spatial_audio/tests.rs b/crates/xcl/src/hle/spatial_audio/tests.rs new file mode 100644 index 000000000..469f201a6 --- /dev/null +++ b/crates/xcl/src/hle/spatial_audio/tests.rs @@ -0,0 +1,261 @@ +use std::mem::ManuallyDrop; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use windows::Win32::Foundation::{CloseHandle, E_FAIL, HANDLE, WAIT_OBJECT_0, WAIT_TIMEOUT}; +use windows::Win32::System::Com::{BLOB, CLSCTX_INPROC_SERVER, CoTaskMemFree, STGM_READ}; +use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + +use super::*; +use crate::pe::ImportName; +use crate::resolver::{self, Source}; + +#[implement(IMMDeviceEnumerator)] +struct HostDevices { + render_active: Arc, + fail_render_query: bool, + capture: IMMDevice, + render: IMMDevice, +} + +impl IMMDeviceEnumerator_Impl for HostDevices_Impl { + fn EnumAudioEndpoints(&self, flow: EDataFlow, state: DEVICE_STATE) -> Result { + if flow == eRender && self.fail_render_query { + return Err(E_FAIL.into()); + } + let mut devices = Vec::new(); + if state.0 & DEVICE_STATE_ACTIVE.0 != 0 { + if flow == eCapture || flow == eAll { + devices.push(self.capture.clone()); + } + if (flow == eRender || flow == eAll) && self.render_active.load(Ordering::Relaxed) { + devices.push(self.render.clone()); + } + } + Ok(HostCollection(devices).into()) + } + + fn GetDefaultAudioEndpoint(&self, flow: EDataFlow, _role: ERole) -> Result { + if flow == eCapture { + return Ok(self.capture.clone()); + } + if flow == eRender && self.render_active.load(Ordering::Relaxed) { + return Ok(self.render.clone()); + } + Err(NO_ENDPOINT.into()) + } + + fn GetDevice(&self, _id: &PCWSTR) -> Result { + Err(NO_ENDPOINT.into()) + } + + fn RegisterEndpointNotificationCallback(&self, _client: Ref) -> Result<()> { + Ok(()) + } + + fn UnregisterEndpointNotificationCallback(&self, _client: Ref) -> Result<()> { + Ok(()) + } +} + +#[implement(IMMDeviceCollection)] +struct HostCollection(Vec); + +impl IMMDeviceCollection_Impl for HostCollection_Impl { + fn GetCount(&self) -> Result { + Ok(self.0.len() as u32) + } + + fn Item(&self, index: u32) -> Result { + self.0.get(index as usize).cloned().ok_or_else(|| E_INVALIDARG.into()) + } +} + +fn host_devices(active: &Arc, fail_render_query: bool) -> IMMDeviceEnumerator { + HostDevices { + render_active: active.clone(), + fail_render_query, + capture: SilentDevice.into(), + render: SilentDevice.into(), + }.into() +} + +#[test] +fn routes_guest_com_activation_through_the_fallback() { + let activation = ImportName::Name { hint: 0, name: "CoCreateInstance".into() }; + let uninitialize = ImportName::Name { hint: 0, name: "CoUninitialize".into() }; + for dll in ["ole32.dll", "combase.dll"] { + assert_eq!(resolver::classify(dll, &activation), Source::Hle(super::super::SPATIAL_AUDIO.into())); + let module = resolver::load_library(dll).expect("native COM module"); + assert_eq!(resolver::get_proc_address(module, &activation), Some(CoCreateInstance as *const () as usize)); + assert_eq!(resolver::get_proc_address(module, &uninitialize), resolver::system_proc_in(module, &uninitialize)); + } + assert_eq!( + resolver::classify("api-ms-win-core-com-l1-1-0.dll", &activation), + Source::HleOther(super::super::SPATIAL_AUDIO.into()), + ); +} + +#[test] +fn exposes_the_silent_endpoint_only_when_windows_reports_no_render_device() { + let active = Arc::new(AtomicBool::new(false)); + let host = host_devices(&active, false); + let wrapped = with_silent_endpoint(host.clone()); + assert_ne!(wrapped.as_raw(), host.as_raw()); + + unsafe { + let silent = wrapped.GetDefaultAudioEndpoint(eRender, eConsole).unwrap(); + let capture = host.GetDefaultAudioEndpoint(eCapture, eConsole).unwrap(); + let reported_capture = wrapped.GetDefaultAudioEndpoint(eCapture, eConsole).unwrap(); + assert_eq!(reported_capture.as_raw(), capture.as_raw()); + assert_eq!(silent.GetState().unwrap(), DEVICE_STATE_ACTIVE); + assert_eq!(silent.cast::().unwrap().GetDataFlow().unwrap(), eRender); + + let id = silent.GetId().unwrap(); + let selected = wrapped.GetDevice(PCWSTR(id.0)); + CoTaskMemFree(Some(id.0.cast())); + assert_eq!(selected.unwrap().as_raw(), silent.as_raw()); + let devices = wrapped.EnumAudioEndpoints(eAll, DEVICE_STATE_ACTIVE).unwrap(); + assert_eq!(devices.GetCount().unwrap(), 2); + assert_eq!(devices.Item(0).unwrap().as_raw(), capture.as_raw()); + assert_eq!(devices.Item(1).unwrap().as_raw(), silent.as_raw()); + let disabled = wrapped.EnumAudioEndpoints(eRender, DEVICE_STATE_DISABLED).unwrap(); + assert_eq!(disabled.GetCount().unwrap(), 0); + + let store = silent.OpenPropertyStore(STGM_READ).unwrap(); + let name = store.GetValue(&FRIENDLY_NAME_KEY).unwrap(); + let value = &*name.Anonymous.Anonymous; + assert_eq!(value.vt, VT_LPWSTR); + assert_eq!(value.Anonymous.pwszVal.as_wide(), FRIENDLY_NAME.as_wide()); + + active.store(true, Ordering::Relaxed); + let native = host.GetDefaultAudioEndpoint(eRender, eConsole).unwrap(); + assert_eq!(wrapped.GetDefaultAudioEndpoint(eRender, eConsole).unwrap().as_raw(), native.as_raw()); + assert_eq!(wrapped.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE).unwrap().GetCount().unwrap(), 1); + assert_eq!(with_silent_endpoint(host.clone()).as_raw(), host.as_raw()); + } + + let host = host_devices(&active, true); + assert_eq!(with_silent_endpoint(host.clone()).as_raw(), host.as_raw()); +} + +struct TestEvent(HANDLE); + +impl TestEvent { + fn new() -> Self { + Self(unsafe { CreateEventW(None, false, false, PCWSTR::null()) }.unwrap()) + } + + fn wait_for_buffer(&self) { + assert_eq!(unsafe { WaitForSingleObject(self.0, 2_000) }, WAIT_OBJECT_0); + } +} + +impl Drop for TestEvent { + fn drop(&mut self) { + let _ = unsafe { CloseHandle(self.0) }; + } +} + +fn activate_stream( + client: &ISpatialAudioClient, params: &SpatialAudioObjectRenderStreamActivationParams, +) -> Result { + // The BLOB borrows the caller's params. PROPVARIANT's Drop would free them. + let mut blob = ManuallyDrop::new(PROPVARIANT::default()); + unsafe { + let variant = &mut *blob.Anonymous.Anonymous; + variant.vt = VT_BLOB; + variant.Anonymous.blob = BLOB { + cbSize: size_of::() as u32, + pBlobData: std::ptr::from_ref(params).cast_mut().cast(), + }; + client.ActivateSpatialAudioStream(&*blob) + } +} + +#[test] +fn renders_repeated_silent_buffers_and_stops_signaling() { + let event = TestEvent::new(); + let host = host_devices(&Arc::new(AtomicBool::new(false)), false); + let wrapped = with_silent_endpoint(host); + unsafe { + let device = wrapped.GetDefaultAudioEndpoint(eRender, eConsole).unwrap(); + let client: ISpatialAudioClient = device.Activate(CLSCTX_INPROC_SERVER, None).unwrap(); + let formats = client.GetSupportedAudioObjectFormatEnumerator().unwrap(); + assert_eq!(formats.GetCount().unwrap(), 1); + let format = formats.GetFormat(0).unwrap(); + assert_eq!(client.GetMaxFrameCount(format).unwrap(), 480); + let extended = WAVEFORMATEXTENSIBLE { + Format: WAVEFORMATEX { + wFormatTag: WAVE_FORMAT_EXTENSIBLE, + cbSize: (size_of::() - size_of::()) as u16, + ..FLOAT_FORMAT + }, + Samples: WAVEFORMATEXTENSIBLE_0 { wValidBitsPerSample: FLOAT_FORMAT.wBitsPerSample }, + dwChannelMask: 0x4, // SPEAKER_FRONT_CENTER + SubFormat: IEEE_FLOAT_SUBFORMAT, + }; + assert_eq!(client.GetMaxFrameCount(&raw const extended.Format).unwrap(), 480); + assert_ne!(client.GetNativeStaticObjectTypeMask().unwrap().0 & AudioObjectType_FrontLeft.0, 0); + let mut params = SpatialAudioObjectRenderStreamActivationParams { + ObjectFormat: format, + StaticObjectTypeMask: AudioObjectType_FrontLeft, + MinDynamicObjectCount: 1, + MaxDynamicObjectCount: 1, + Category: AudioCategory_GameEffects, + EventHandle: event.0, + ..Default::default() + }; + let stream = activate_stream(&client, ¶ms).unwrap(); + params.MinDynamicObjectCount = 2; + assert_eq!(activate_stream(&client, ¶ms).unwrap_err().code(), E_INVALIDARG); + let dynamic = stream.ActivateSpatialAudioObject(AudioObjectType_Dynamic).unwrap(); + assert_eq!( + stream.ActivateSpatialAudioObject(AudioObjectType_Dynamic).unwrap_err().code(), + SPTLAUDCLNT_E_NO_MORE_OBJECTS, + ); + let front = stream.ActivateSpatialAudioObject(AudioObjectType_FrontLeft).unwrap(); + assert_eq!( + stream.ActivateSpatialAudioObject(AudioObjectType_FrontRight).unwrap_err().code(), + SPTLAUDCLNT_E_STATIC_OBJECT_NOT_AVAILABLE, + ); + assert_eq!(stream.GetAvailableDynamicObjectCount().unwrap(), 0); + + stream.Start().unwrap(); + assert_eq!(stream.Start().unwrap_err().code(), SPTLAUDCLNT_E_STREAM_NOT_STOPPED); + for pass in 0..4 { + event.wait_for_buffer(); + let (mut available, mut frames) = (u32::MAX, 0); + stream.BeginUpdatingAudioObjects(&mut available, &mut frames).unwrap(); + assert_eq!((available, frames), (0, 480)); + assert_eq!( + stream.BeginUpdatingAudioObjects(&mut available, &mut frames).unwrap_err().code(), + SPTLAUDCLNT_E_OUT_OF_ORDER, + ); + for object in [&dynamic, &front] { + let (mut data, mut bytes) = (null_mut(), 0); + object.GetBuffer(&mut data, &mut bytes).unwrap(); + assert_eq!(bytes, frames * SAMPLE_BYTES as u32); + data.cast::().write(0.5); + data.cast::().add(frames as usize - 1).write(-0.5); + } + if pass == 3 { + dynamic.SetEndOfStream(frames).unwrap(); + } + stream.EndUpdatingAudioObjects().unwrap(); + } + assert!(!dynamic.IsActive().unwrap().as_bool()); + assert!(front.IsActive().unwrap().as_bool()); + assert_eq!(stream.GetAvailableDynamicObjectCount().unwrap(), 0); + drop(dynamic); + assert_eq!(stream.GetAvailableDynamicObjectCount().unwrap(), 1); + stream.Stop().unwrap(); + assert_eq!(WaitForSingleObject(event.0, 35), WAIT_TIMEOUT); + stream.Reset().unwrap(); + assert!(!front.IsActive().unwrap().as_bool()); + + stream.Start().unwrap(); + event.wait_for_buffer(); + stream.Stop().unwrap(); + } +}