mirror of
https://github.com/lobomfz/VIctory-xmem.git
synced 2026-12-06 05:48:38 +00:00
loader: the PS5 build's haptics on a DualSense's actuators (VICTORY_DUALSENSE)
Sounds for the pad's actuators carry effect route 7, which both builds' mixers send to the PadHaptics mix group (0x144de7250 on this build). The PS5 build hands that stereo submix to its pad's haptics port; the Xbox build makes the same group but gives it no output, so it reaches no speaker. With VICTORY_DUALSENSE=1, a hook in front of the mixer's per-group output step (0x144e59960, once per 256-sample frame on the mixer thread) copies the PadHaptics group's two channels into a ring, and a thread plays them through WASAPI in shared mode on channels 3 and 4 (the actuators) of the controller's 4-channel USB audio endpoint; channels 1 and 2 (its speaker) stay silent. Gain defaults to +8 dB (VICTORY_HAPTICS_GAIN_DB); the title's audio settings give +14 dB on PC with a PS5 controller, which clips the loudest events. VICTORY_HAPTICS_LOG=1 logs the group's state and levels. Rumble keeps its own path and stacks with the haptics, as on the PS5 build. Wired (USB) only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1
Cargo.lock
generated
1
Cargo.lock
generated
@ -819,6 +819,7 @@ dependencies = [
|
||||
"tracing",
|
||||
"victory-core",
|
||||
"victory-pe",
|
||||
"windows",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
|
||||
@ -359,6 +359,9 @@ pub fn run(
|
||||
let size = image.info().size_of_image as usize;
|
||||
// SAFETY: the image stays mapped and nothing of it has run yet.
|
||||
unsafe { victory_loader::pad_effects::apply_asked(image.base(), size) };
|
||||
// The PadHaptics submix on the DualSense's actuators (VICTORY_DUALSENSE).
|
||||
// SAFETY: as above.
|
||||
unsafe { victory_loader::haptics::apply_asked(image.base(), size) };
|
||||
}
|
||||
if !execute {
|
||||
println!("not executing (pass --execute to start the title)");
|
||||
|
||||
@ -27,6 +27,14 @@ windows-sys = { workspace = true, features = [
|
||||
"Win32_System_Performance",
|
||||
"Win32_System_Threading",
|
||||
] }
|
||||
# WASAPI for the DualSense haptics.
|
||||
windows = { workspace = true, features = [
|
||||
"Win32_Media_Audio",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_Com_StructuredStorage",
|
||||
"Win32_System_Variant",
|
||||
"Win32_UI_Shell_PropertiesSystem",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
603
crates/victory-loader/src/haptics.rs
Normal file
603
crates/victory-loader/src/haptics.rs
Normal file
@ -0,0 +1,603 @@
|
||||
//! DualSense haptics (`VICTORY_DUALSENSE=1`): the PS5 build's haptic sounds,
|
||||
//! played on the controller's actuators.
|
||||
//!
|
||||
//! Sounds meant for the pad's actuators carry effect route 7, which both
|
||||
//! builds' mixers send to the `PadHaptics` mix group. A mix group is one of
|
||||
//! the title's software submixes: per channel, a buffer of 256 floats each
|
||||
//! mixer frame (pointers at group+0x670, channel count at group+0x7d0). The
|
||||
//! PS5 build hands that stereo submix to its pad's haptics port; the Xbox
|
||||
//! build makes the same group but gives it no output (no sends, nothing at
|
||||
//! group+0x7b0), so it reaches no speaker.
|
||||
//!
|
||||
//! A hook in front of the mixer's per-group output step (`0x144e59960`, run
|
||||
//! on the title's mixer thread once per frame for each live group) copies
|
||||
//! that group's two channels into a ring; a thread of ours plays the ring on
|
||||
//! channels 3 and 4 (the actuators) of the controller's 4-channel USB audio
|
||||
//! endpoint, "Speakers (DualSense Wireless Controller)", through WASAPI in
|
||||
//! shared mode. Channels 1 and 2 (the pad's speaker) stay silent. When the
|
||||
//! group has nothing to play the title skips it, and the endpoint plays
|
||||
//! silence.
|
||||
//!
|
||||
//! Gain: the title's audio settings give haptics +14 dB on PC with a PS5
|
||||
//! controller (`Haptics_PC_With_PS5_Controller_Gain`, our case: Windows
|
||||
//! audio to the controller) and +20 dB on the PS5 (`Haptics_PS5_Gain`); the
|
||||
//! Xbox build applies neither. The default is +8 dB: in play the group peaks
|
||||
//! around -5 dBFS, so +14 clips the loudest events, and +8 felt right on a
|
||||
//! wired pad. `VICTORY_HAPTICS_GAIN_DB` overrides it. `VICTORY_HAPTICS_LOG=1`
|
||||
//! logs the group's state once and the levels and frame counts every few
|
||||
//! seconds.
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
|
||||
|
||||
/// The mixer's per-group output step (title offset) and its first 17 bytes
|
||||
/// (`push rsi; push rdi; push rbx; sub rsp, 0xa0; mov rsi, [rcx+0x7b0]`, all
|
||||
/// position independent).
|
||||
const OUTPUT_STEP: usize = 0x4e5_9960;
|
||||
const OUTPUT_PROLOGUE: [u8; 17] = [
|
||||
0x56, 0x57, 0x53, 0x48, 0x81, 0xec, 0xa0, 0x00, 0x00, 0x00, 0x48, 0x8b, 0xb1, 0xb0, 0x07, 0x00,
|
||||
0x00,
|
||||
];
|
||||
/// The mix group manager (a pointer, title offset) and the `PadHaptics`
|
||||
/// group's index (u16, a field of the audio engine object at 0x14aa31d00).
|
||||
const MANAGER: usize = 0xa92_4088;
|
||||
const PAD_HAPTICS_ID: usize = 0xaa3_6944;
|
||||
/// In the manager: group count (u32) and the groups (pointer).
|
||||
const GROUP_COUNT: usize = 0x14;
|
||||
const GROUPS: usize = 0x18;
|
||||
const GROUP_SIZE: usize = 0x820;
|
||||
/// In a group: channel buffer pointers, channel count, output object,
|
||||
/// output (send) count.
|
||||
const GROUP_BUFFERS: usize = 0x670;
|
||||
const GROUP_CHANNELS: usize = 0x7d0;
|
||||
const GROUP_OUTPUT: usize = 0x7b0;
|
||||
const GROUP_SENDS: usize = 0x7cc;
|
||||
|
||||
/// Samples per channel in a mixer frame.
|
||||
const FRAME: usize = 256;
|
||||
/// The mixer's and the controller's rate.
|
||||
const RATE: u32 = 48_000;
|
||||
/// Ring capacity in stereo frames (~85 ms); older audio is dropped beyond it.
|
||||
const RING: usize = 4096;
|
||||
/// Most frames kept waiting for the player (~43 ms).
|
||||
const BACKLOG: usize = 2048;
|
||||
const DEFAULT_GAIN_DB: f32 = 8.0;
|
||||
|
||||
static IMAGE: AtomicUsize = AtomicUsize::new(0);
|
||||
static TRAMPOLINE: AtomicUsize = AtomicUsize::new(0);
|
||||
static LOG: AtomicBool = AtomicBool::new(false);
|
||||
static DESCRIBED: AtomicBool = AtomicBool::new(false);
|
||||
/// Linear gain, as f32 bits.
|
||||
static GAIN: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// Stereo frames from the mixer to the player.
|
||||
struct Ring {
|
||||
data: Box<[[f32; 2]]>,
|
||||
start: usize,
|
||||
len: usize,
|
||||
/// For the log: mixer frames seen, frames dropped, peak before gain.
|
||||
frames: u64,
|
||||
dropped: u64,
|
||||
peak: f32,
|
||||
}
|
||||
|
||||
impl Ring {
|
||||
fn new(capacity: usize) -> Self {
|
||||
Self {
|
||||
data: vec![[0.0; 2]; capacity].into_boxed_slice(),
|
||||
start: 0,
|
||||
len: 0,
|
||||
frames: 0,
|
||||
dropped: 0,
|
||||
peak: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, left: &[f32], right: &[f32]) {
|
||||
let cap = self.data.len();
|
||||
for (&l, &r) in left.iter().zip(right) {
|
||||
if self.len == cap {
|
||||
self.start = (self.start + 1) % cap;
|
||||
self.len -= 1;
|
||||
self.dropped += 1;
|
||||
}
|
||||
self.data[(self.start + self.len) % cap] = [l, r];
|
||||
self.len += 1;
|
||||
self.peak = self.peak.max(l.abs()).max(r.abs());
|
||||
}
|
||||
self.frames += 1;
|
||||
}
|
||||
|
||||
/// Takes up to `out.len()` frames; returns how many.
|
||||
fn pop_into(&mut self, out: &mut [[f32; 2]]) -> usize {
|
||||
let n = out.len().min(self.len);
|
||||
let cap = self.data.len();
|
||||
for (i, o) in out[..n].iter_mut().enumerate() {
|
||||
*o = self.data[(self.start + i) % cap];
|
||||
}
|
||||
self.start = (self.start + n) % cap;
|
||||
self.len -= n;
|
||||
n
|
||||
}
|
||||
|
||||
/// Drops the oldest frames beyond `max`, so latency stays bounded when
|
||||
/// the mixer runs a little faster than the controller.
|
||||
fn trim(&mut self, max: usize) {
|
||||
if self.len > max {
|
||||
let extra = self.len - max;
|
||||
self.start = (self.start + extra) % self.data.len();
|
||||
self.len = max;
|
||||
self.dropped += extra as u64;
|
||||
}
|
||||
}
|
||||
|
||||
fn clear(&mut self) {
|
||||
self.start = 0;
|
||||
self.len = 0;
|
||||
}
|
||||
}
|
||||
|
||||
static RING_STATE: Mutex<Option<Ring>> = Mutex::new(None);
|
||||
|
||||
fn lock() -> std::sync::MutexGuard<'static, Option<Ring>> {
|
||||
RING_STATE.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Writes `frames` (stereo, before gain) into `out`, an interleaved buffer of
|
||||
/// `channels` channels, on channels 3 and 4; every other channel is zero.
|
||||
fn interleave(frames: &[[f32; 2]], gain: f32, channels: usize, out: &mut [f32]) {
|
||||
out.fill(0.0);
|
||||
if channels < 4 {
|
||||
return;
|
||||
}
|
||||
for (frame, o) in frames.iter().zip(out.chunks_exact_mut(channels)) {
|
||||
o[2] = (frame[0] * gain).clamp(-1.0, 1.0);
|
||||
o[3] = (frame[1] * gain).clamp(-1.0, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn gain_from_env() -> f32 {
|
||||
let db = std::env::var("VICTORY_HAPTICS_GAIN_DB")
|
||||
.ok()
|
||||
.and_then(|v| v.trim().parse::<f32>().ok())
|
||||
.filter(|db| db.is_finite())
|
||||
.unwrap_or(DEFAULT_GAIN_DB);
|
||||
10f32.powf(db / 20.0)
|
||||
}
|
||||
|
||||
/// The `PadHaptics` group, once the title has made it.
|
||||
///
|
||||
/// # Safety
|
||||
/// The title's image is mapped at `base`.
|
||||
unsafe fn pad_haptics_group(base: usize) -> Option<usize> {
|
||||
// SAFETY: globals of the mapped image; the manager and its groups are the
|
||||
// title's, alive while its mixer runs.
|
||||
unsafe {
|
||||
let manager = std::ptr::read_volatile((base + MANAGER) as *const usize);
|
||||
if manager == 0 {
|
||||
return None;
|
||||
}
|
||||
let id = std::ptr::read_volatile((base + PAD_HAPTICS_ID) as *const u16);
|
||||
let count = std::ptr::read_volatile((manager + GROUP_COUNT) as *const u32);
|
||||
let groups = std::ptr::read_volatile((manager + GROUPS) as *const usize);
|
||||
(id != 0xffff && u32::from(id) < count && groups != 0)
|
||||
.then(|| groups + usize::from(id) * GROUP_SIZE)
|
||||
}
|
||||
}
|
||||
|
||||
/// In front of the mixer's per-group output step.
|
||||
unsafe extern "system" fn output_step(group: usize) {
|
||||
let base = IMAGE.load(Ordering::Relaxed);
|
||||
// SAFETY: the title's group, on its mixer thread, after the frame's mix and effects.
|
||||
unsafe {
|
||||
if pad_haptics_group(base) == Some(group) {
|
||||
take(group);
|
||||
}
|
||||
let original = TRAMPOLINE.load(Ordering::Relaxed);
|
||||
std::mem::transmute::<usize, unsafe extern "system" fn(usize)>(original)(group);
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies the group's frame into the ring.
|
||||
///
|
||||
/// # Safety
|
||||
/// `group` is the title's `PadHaptics` group, during its output step.
|
||||
unsafe fn take(group: usize) {
|
||||
// SAFETY: fields of the title's group; its buffers hold FRAME floats each.
|
||||
unsafe {
|
||||
let channels = std::ptr::read_volatile((group + GROUP_CHANNELS) as *const u32) as usize;
|
||||
let buffers = (group + GROUP_BUFFERS) as *const *const f32;
|
||||
if LOG.load(Ordering::Relaxed) && !DESCRIBED.swap(true, Ordering::Relaxed) {
|
||||
tracing::info!(
|
||||
group = format_args!("{group:#x}"),
|
||||
channels,
|
||||
output = format_args!(
|
||||
"{:#x}",
|
||||
std::ptr::read_volatile((group + GROUP_OUTPUT) as *const usize)
|
||||
),
|
||||
sends = std::ptr::read_volatile((group + GROUP_SENDS) as *const u32),
|
||||
"haptics: first PadHaptics frame"
|
||||
);
|
||||
}
|
||||
if channels == 0 {
|
||||
return;
|
||||
}
|
||||
let left = *buffers;
|
||||
let right = if channels >= 2 { *buffers.add(1) } else { left };
|
||||
if left.is_null() || right.is_null() {
|
||||
return;
|
||||
}
|
||||
let left = std::slice::from_raw_parts(left, FRAME);
|
||||
let right = std::slice::from_raw_parts(right, FRAME);
|
||||
if let Some(ring) = lock().as_mut() {
|
||||
ring.push(left, right);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts the hook in front of the mixer's output step and starts the player,
|
||||
/// when `VICTORY_DUALSENSE` asks for it.
|
||||
///
|
||||
/// # Safety
|
||||
/// The image of `size` bytes at `base` stays mapped and nothing of it runs yet.
|
||||
#[cfg(windows)]
|
||||
pub unsafe fn apply_asked(base: usize, size: usize) {
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, VirtualAlloc, VirtualProtect,
|
||||
};
|
||||
let on = |name: &str| std::env::var_os(name).is_some_and(|v| v == "1");
|
||||
if !on("VICTORY_DUALSENSE") {
|
||||
return;
|
||||
}
|
||||
LOG.store(on("VICTORY_HAPTICS_LOG"), Ordering::Relaxed);
|
||||
if OUTPUT_STEP + OUTPUT_PROLOGUE.len() > size {
|
||||
return;
|
||||
}
|
||||
let at = base + OUTPUT_STEP;
|
||||
// SAFETY: inside the mapped image (checked above); nothing runs yet.
|
||||
let found = unsafe { std::slice::from_raw_parts(at as *const u8, OUTPUT_PROLOGUE.len()) };
|
||||
if found != OUTPUT_PROLOGUE {
|
||||
tracing::warn!(
|
||||
"haptics: not hooked, the mixer's output step is not the expected code (another build?)"
|
||||
);
|
||||
return;
|
||||
}
|
||||
let jump = |to: usize| -> [u8; 14] {
|
||||
let mut j = [0xff, 0x25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
|
||||
j[6..].copy_from_slice(&(to as u64).to_le_bytes());
|
||||
j
|
||||
};
|
||||
// SAFETY: a fresh page of our own for the trampoline.
|
||||
let trampoline = unsafe {
|
||||
VirtualAlloc(
|
||||
std::ptr::null(),
|
||||
64,
|
||||
MEM_COMMIT | MEM_RESERVE,
|
||||
PAGE_EXECUTE_READWRITE,
|
||||
)
|
||||
}
|
||||
.cast::<u8>();
|
||||
if trampoline.is_null() {
|
||||
return;
|
||||
}
|
||||
// SAFETY: our page: the displaced prologue, then a jump back after it.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(OUTPUT_PROLOGUE.as_ptr(), trampoline, OUTPUT_PROLOGUE.len());
|
||||
let back = jump(at + OUTPUT_PROLOGUE.len());
|
||||
std::ptr::copy_nonoverlapping(
|
||||
back.as_ptr(),
|
||||
trampoline.add(OUTPUT_PROLOGUE.len()),
|
||||
back.len(),
|
||||
);
|
||||
}
|
||||
*lock() = Some(Ring::new(RING));
|
||||
GAIN.store(gain_from_env().to_bits(), Ordering::Relaxed);
|
||||
TRAMPOLINE.store(trampoline as usize, Ordering::Relaxed);
|
||||
IMAGE.store(base, Ordering::Relaxed);
|
||||
let mut patch = [0x90u8; OUTPUT_PROLOGUE.len()];
|
||||
patch[..14].copy_from_slice(&jump(
|
||||
output_step as unsafe extern "system" fn(usize) as usize,
|
||||
));
|
||||
let mut old = 0;
|
||||
// SAFETY: the title's function head (checked above), made writable for the write and put back.
|
||||
unsafe {
|
||||
if VirtualProtect(
|
||||
at as *const _,
|
||||
patch.len(),
|
||||
PAGE_EXECUTE_READWRITE,
|
||||
&mut old,
|
||||
) == 0
|
||||
{
|
||||
tracing::warn!("haptics: not hooked, the mixer's code would not become writable");
|
||||
return;
|
||||
}
|
||||
std::ptr::copy_nonoverlapping(patch.as_ptr(), at as *mut u8, patch.len());
|
||||
VirtualProtect(at as *const _, patch.len(), old, &mut old);
|
||||
}
|
||||
if let Err(e) = std::thread::Builder::new()
|
||||
.name("victory-haptics".into())
|
||||
.spawn(player::run)
|
||||
{
|
||||
tracing::warn!(error = %e, "haptics: the player thread did not start");
|
||||
return;
|
||||
}
|
||||
tracing::info!(
|
||||
gain_db = format_args!(
|
||||
"{:.1}",
|
||||
20.0 * f32::from_bits(GAIN.load(Ordering::Relaxed)).log10()
|
||||
),
|
||||
log = LOG.load(Ordering::Relaxed),
|
||||
"haptics: the PadHaptics submix goes to the DualSense's actuators (VICTORY_DUALSENSE, VICTORY_HAPTICS_GAIN_DB, VICTORY_HAPTICS_LOG)"
|
||||
);
|
||||
}
|
||||
|
||||
/// Plays the ring on the controller's audio endpoint.
|
||||
#[cfg(windows)]
|
||||
mod player {
|
||||
use super::{BACKLOG, GAIN, LOG, RATE, interleave, lock};
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use windows::Win32::Foundation::PROPERTYKEY;
|
||||
use windows::Win32::Media::Audio::{
|
||||
AUDCLNT_SHAREMODE_SHARED, DEVICE_STATE_ACTIVE, IAudioClient, IAudioRenderClient, IMMDevice,
|
||||
IMMDeviceEnumerator, MMDeviceEnumerator, eRender,
|
||||
};
|
||||
use windows::Win32::System::Com::StructuredStorage::PropVariantClear;
|
||||
use windows::Win32::System::Com::{
|
||||
CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoTaskMemFree,
|
||||
STGM_READ,
|
||||
};
|
||||
use windows::Win32::System::Variant::VT_LPWSTR;
|
||||
use windows::core::GUID;
|
||||
|
||||
/// `PKEY_Device_FriendlyName`.
|
||||
const FRIENDLY_NAME: PROPERTYKEY = PROPERTYKEY {
|
||||
fmtid: GUID::from_u128(0xa45c254e_df1c_4efd_8020_67d146a850e0),
|
||||
pid: 14,
|
||||
};
|
||||
/// Buffer asked of WASAPI and how full we keep it (100 ns units / frames).
|
||||
const BUFFER_HNS: i64 = 400_000;
|
||||
const TARGET_FRAMES: u32 = RATE / 1000 * 25;
|
||||
/// `WAVE_FORMAT_IEEE_FLOAT` and `WAVE_FORMAT_EXTENSIBLE`.
|
||||
const FLOAT_TAG: u16 = 3;
|
||||
const EXTENSIBLE_TAG: u16 = 0xfffe;
|
||||
/// `KSDATAFORMAT_SUBTYPE_IEEE_FLOAT`.
|
||||
const FLOAT_SUBTYPE: GUID = GUID::from_u128(0x00000003_0000_0010_8000_00aa00389b71);
|
||||
|
||||
pub fn run() {
|
||||
// SAFETY: COM on this thread of ours.
|
||||
if let Err(e) = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.ok() {
|
||||
tracing::warn!(error = %e, "haptics: no COM; not played");
|
||||
return;
|
||||
}
|
||||
let mut announced = false;
|
||||
loop {
|
||||
// SAFETY: COM calls with parameters built here.
|
||||
match unsafe { find() } {
|
||||
Ok(Some((device, name))) => {
|
||||
announced = false;
|
||||
// SAFETY: as above.
|
||||
if let Err(e) = unsafe { play(&device, &name) } {
|
||||
tracing::warn!(error = %e, "haptics: playback stopped; looking for the controller again");
|
||||
}
|
||||
}
|
||||
Ok(None) if !announced => {
|
||||
tracing::warn!(
|
||||
"haptics: no 4-channel DualSense audio endpoint (connect it by USB); looking again every few seconds"
|
||||
);
|
||||
announced = true;
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::warn!(error = %e, "haptics: could not list audio endpoints"),
|
||||
}
|
||||
if let Some(ring) = lock().as_mut() {
|
||||
ring.clear();
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(3));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an endpoint name is the controller's.
|
||||
pub(super) fn is_dualsense(name: &str) -> bool {
|
||||
name.contains("DualSense") || name.contains("Wireless Controller")
|
||||
}
|
||||
|
||||
/// The controller's endpoint: a render endpoint by its name, with 4 channels.
|
||||
unsafe fn find() -> windows::core::Result<Option<(IMMDevice, String)>> {
|
||||
// SAFETY: COM calls with parameters built here; the property and the
|
||||
// mix format are read, then freed.
|
||||
unsafe {
|
||||
let devices: IMMDeviceEnumerator =
|
||||
CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL)?;
|
||||
let list = devices.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE)?;
|
||||
for i in 0..list.GetCount()? {
|
||||
let device = list.Item(i)?;
|
||||
let Ok(store) = device.OpenPropertyStore(STGM_READ) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(mut value) = store.GetValue(&FRIENDLY_NAME) else {
|
||||
continue;
|
||||
};
|
||||
let inner = &value.Anonymous.Anonymous;
|
||||
let name = if inner.vt == VT_LPWSTR && !inner.Anonymous.pwszVal.is_null() {
|
||||
inner.Anonymous.pwszVal.to_string().unwrap_or_default()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let _ = PropVariantClear(&mut value);
|
||||
if !is_dualsense(&name) {
|
||||
continue;
|
||||
}
|
||||
let client: IAudioClient = device.Activate(CLSCTX_ALL, None)?;
|
||||
let format = client.GetMixFormat()?;
|
||||
let channels = (*format).nChannels;
|
||||
CoTaskMemFree(Some(format as *const _));
|
||||
if channels == 4 {
|
||||
return Ok(Some((device, name)));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn play(device: &IMMDevice, name: &str) -> windows::core::Result<()> {
|
||||
// SAFETY: COM calls with parameters built here; the render buffer is
|
||||
// written only between `GetBuffer` and `ReleaseBuffer`.
|
||||
unsafe {
|
||||
let client: IAudioClient = device.Activate(CLSCTX_ALL, None)?;
|
||||
let format = client.GetMixFormat()?;
|
||||
let f = *format;
|
||||
let float = f.wFormatTag == FLOAT_TAG
|
||||
|| (f.wFormatTag == EXTENSIBLE_TAG && f.cbSize >= 22 && {
|
||||
// WAVEFORMATEXTENSIBLE: SubFormat after the 18-byte header and 6 more bytes.
|
||||
let sub = (format as *const u8)
|
||||
.add(24)
|
||||
.cast::<GUID>()
|
||||
.read_unaligned();
|
||||
sub == FLOAT_SUBTYPE
|
||||
});
|
||||
let channels = usize::from(f.nChannels);
|
||||
let rate = f.nSamplesPerSec;
|
||||
let bits = f.wBitsPerSample;
|
||||
let result =
|
||||
client.Initialize(AUDCLNT_SHAREMODE_SHARED, 0, BUFFER_HNS, 0, format, None);
|
||||
CoTaskMemFree(Some(format as *const _));
|
||||
result?;
|
||||
if !(float && bits == 32 || !float && bits == 16) {
|
||||
tracing::warn!(
|
||||
bits,
|
||||
float,
|
||||
"haptics: the controller's mix format is not 32-bit float or 16-bit; not played"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if rate != RATE {
|
||||
tracing::warn!(
|
||||
rate,
|
||||
"haptics: the controller's rate is not 48 kHz; haptics will play off pitch"
|
||||
);
|
||||
}
|
||||
let size = client.GetBufferSize()?;
|
||||
let render: IAudioRenderClient = client.GetService()?;
|
||||
client.Start()?;
|
||||
tracing::info!(
|
||||
name,
|
||||
channels,
|
||||
rate,
|
||||
bits,
|
||||
buffer = size,
|
||||
"haptics: playing on the controller's channels 3 and 4"
|
||||
);
|
||||
let target = TARGET_FRAMES.min(size);
|
||||
let mut frames = vec![[0f32; 2]; size as usize];
|
||||
let mut mixed = vec![0f32; size as usize * channels];
|
||||
let mut logged = Instant::now();
|
||||
let (mut played, mut starved) = (0u64, 0u64);
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_millis(3));
|
||||
let padding = client.GetCurrentPadding()?;
|
||||
if padding >= target {
|
||||
continue;
|
||||
}
|
||||
let want = (target - padding) as usize;
|
||||
let (got, stats) = {
|
||||
let mut guard = lock();
|
||||
let Some(ring) = guard.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
ring.trim(BACKLOG);
|
||||
let got = ring.pop_into(&mut frames[..want]);
|
||||
let stats = (ring.frames, ring.dropped, ring.peak);
|
||||
if LOG.load(Ordering::Relaxed) && logged.elapsed() >= Duration::from_secs(5) {
|
||||
ring.frames = 0;
|
||||
ring.dropped = 0;
|
||||
ring.peak = 0.0;
|
||||
}
|
||||
(got, stats)
|
||||
};
|
||||
// Nothing to play: let the endpoint run dry (it plays silence)
|
||||
// rather than add latency ahead of the next haptic sound.
|
||||
if got > 0 {
|
||||
let data = render.GetBuffer(got as u32)?;
|
||||
let gain = f32::from_bits(GAIN.load(Ordering::Relaxed));
|
||||
let out = &mut mixed[..got * channels];
|
||||
interleave(&frames[..got], gain, channels, out);
|
||||
if float {
|
||||
std::ptr::copy_nonoverlapping(out.as_ptr(), data.cast::<f32>(), out.len());
|
||||
} else {
|
||||
let data = std::slice::from_raw_parts_mut(data.cast::<i16>(), out.len());
|
||||
for (d, &s) in data.iter_mut().zip(out.iter()) {
|
||||
*d = (s * 32767.0) as i16;
|
||||
}
|
||||
}
|
||||
render.ReleaseBuffer(got as u32, 0)?;
|
||||
played += got as u64;
|
||||
} else if padding == 0 {
|
||||
starved += 1;
|
||||
}
|
||||
if LOG.load(Ordering::Relaxed) && logged.elapsed() >= Duration::from_secs(5) {
|
||||
let secs = logged.elapsed().as_secs_f32();
|
||||
tracing::info!(
|
||||
mixer_frames_per_s = stats.0 as f32 / secs,
|
||||
dropped = stats.1,
|
||||
peak_db = 20.0 * stats.2.max(1e-9).log10(),
|
||||
played_per_s = played as f32 / secs,
|
||||
starved,
|
||||
"haptics: levels"
|
||||
);
|
||||
logged = Instant::now();
|
||||
played = 0;
|
||||
starved = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ring_keeps_order_and_drops_oldest() {
|
||||
let mut r = Ring::new(4);
|
||||
r.push(&[1.0, 2.0, 3.0], &[-1.0, -2.0, -3.0]);
|
||||
r.push(&[4.0, 5.0], &[-4.0, -5.0]);
|
||||
assert_eq!(r.dropped, 1);
|
||||
assert_eq!(r.frames, 2);
|
||||
assert_eq!(r.peak, 5.0);
|
||||
let mut out = [[0.0; 2]; 8];
|
||||
assert_eq!(r.pop_into(&mut out), 4);
|
||||
assert_eq!(
|
||||
out[..4],
|
||||
[[2.0, -2.0], [3.0, -3.0], [4.0, -4.0], [5.0, -5.0]]
|
||||
);
|
||||
assert_eq!(r.pop_into(&mut out), 0);
|
||||
r.push(&[1.0, 2.0, 3.0], &[0.0; 3]);
|
||||
r.trim(1);
|
||||
assert_eq!(r.pop_into(&mut out), 1);
|
||||
assert_eq!(out[0], [3.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interleaves_on_channels_3_and_4() {
|
||||
let mut out = [9.0f32; 8];
|
||||
interleave(&[[0.1, -0.2], [0.5, 0.9]], 2.0, 4, &mut out);
|
||||
assert_eq!(out, [0.0, 0.0, 0.2, -0.4, 0.0, 0.0, 1.0, 1.0]);
|
||||
// Fewer than 4 channels: nothing is played.
|
||||
let mut out = [9.0f32; 4];
|
||||
interleave(&[[0.1, 0.2], [0.3, 0.4]], 1.0, 2, &mut out);
|
||||
assert_eq!(out, [0.0; 4]);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn endpoint_names() {
|
||||
assert!(player::is_dualsense(
|
||||
"Speakers (DualSense Wireless Controller)"
|
||||
));
|
||||
assert!(player::is_dualsense("Speakers (Wireless Controller)"));
|
||||
assert!(!player::is_dualsense("Speakers (Realtek(R) Audio)"));
|
||||
}
|
||||
}
|
||||
@ -29,6 +29,7 @@ pub mod descriptor_sites;
|
||||
pub mod detail;
|
||||
pub mod dualsense;
|
||||
pub mod frame_rate;
|
||||
pub mod haptics;
|
||||
pub mod keyboard_events;
|
||||
pub mod pad_effects;
|
||||
pub mod prepare;
|
||||
|
||||
Reference in New Issue
Block a user