GameInput: a player for the DualSense's haptic actuators over USB audio #705

Open
MrCheese5 wants to merge 3 commits from upstream-pr/710 into main
MrCheese5 commented 2026-11-24 03:59:13 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by MrCheese5 on 2026-11-24T03:59:13Z.


Stacked on #552 and #709; only the top commit belongs here.

Over USB the DualSense is also a 4-channel audio output, and its channels 3 and 4 drive the two voice-coil actuators. dualsense_haptics finds that output by name with WASAPI (shared mode) and plays from a thread of its own. The title's big motor becomes a 100 Hz tone, mostly on the left, and the small motor a 230 Hz tone, mostly on the right. The amplitudes glide over 10 ms so level changes do not click, and the speaker channels stay silent. start() refuses an output with fewer than 4 channels, so the caller can keep compatible rumble.

Nothing starts it yet; #731 does. The windows crate gets three features for the device property store: Win32_System_Com_StructuredStorage, Win32_System_Variant and Win32_UI_Shell_PropertiesSystem. No new crates.

What is in it

  • crates/xcl/src/hle/dualsense_haptics.rs: the synthesiser and the WASAPI player, with tests of the synthesiser (only the actuator channels play, the cross-mix, the glide, each tone's frequency by zero crossings)
  • crates/xcl/Cargo.toml: the three features
  • crates/xcl/src/hle/mod.rs: the module

Tested

  • RTX 4090 (driver 621.14), i9-14900K, Windows 11 26200, Rust stable-x86_64-pc-windows-msvc, debug tests, release smoke runs
  • cargo test -p xcl --lib dualsense_haptics: 2 passed
  • cargo test --workspace -- --test-threads=1: 698 passed, 0 failed, 41 ignored; SKIPPED: gpu_geometry_wave32_prefix_count_over_a_mask (no wave64), gpu_wave32_program_in_wave64_hardware (no wave64)
  • Single-threaded on purpose: with --test-threads=4, GPU tests on this machine hang or lose the device tonight on main too (bdab194 and 91f9a5e; bdab194 had passed with 4 threads earlier the same night, and the driver logs GPU errors). Single-threaded, main 91f9a5e passes (cargo test -p xcl --lib -- --test-threads=1: 647 passed, 0 failed).
  • With #731 on top, on a USB DualSense (054c:0ce6): the player found the controller's output in 4 channels at 48 kHz, started, and stopped at shutdown.

Regression run
Both runs use a fresh data root of their own. The title is not driven by a controller during the run, so this shows that nothing else changes, not the new path.

xcl-smoke v1
commit: 91f9a5e9f03156ea82dc55a18f7704862da7a5db
gpu: NVIDIA GeForce RTX 4090
title: Xbox
seconds: 60
exit: 0x0
frames shown: 811 (PresentX 811)
presents per 2 s (last 3): 37 34 36
device removals: 0
crashes: 0
peak commit: 15536 MB
xcl-smoke v1
commit: 4eebfdca13fe91e94f0892435242854f96d7c001
gpu: NVIDIA GeForce RTX 4090
title: Xbox
seconds: 60
exit: 0x0
frames shown: 827 (PresentX 827)
presents per 2 s (last 3): 36 37 36
device removals: 0
crashes: 0
peak commit: 15563 MB

Not tested

  • Whether the actuators feel right: nobody held the controller during the run.
  • An output that is not in 4 channels was not tried, so the refusal path is untested on hardware.
  • Nothing starts the player in this PR on its own.
  • AMD and other NVIDIA GPUs (the change has no GPU code).

AI use

  • Claude Code with Claude Opus 5.5: wrote the code, the tests and this description; the hardware checks above are runs on the machine named under Tested.

🤖 Generated with Claude Code

<!-- greyfinch-sync:ivall/xcl:issue:5465811191 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/710). Originally posted by [MrCheese5](https://github.com/MrCheese5) on 2026-11-24T03:59:13Z. --- Stacked on #552 and #709; only the top commit belongs here. Over USB the DualSense is also a 4-channel audio output, and its channels 3 and 4 drive the two voice-coil actuators. `dualsense_haptics` finds that output by name with WASAPI (shared mode) and plays from a thread of its own. The title's big motor becomes a 100 Hz tone, mostly on the left, and the small motor a 230 Hz tone, mostly on the right. The amplitudes glide over 10 ms so level changes do not click, and the speaker channels stay silent. `start()` refuses an output with fewer than 4 channels, so the caller can keep compatible rumble. Nothing starts it yet; #731 does. The `windows` crate gets three features for the device property store: `Win32_System_Com_StructuredStorage`, `Win32_System_Variant` and `Win32_UI_Shell_PropertiesSystem`. No new crates. **What is in it** - `crates/xcl/src/hle/dualsense_haptics.rs`: the synthesiser and the WASAPI player, with tests of the synthesiser (only the actuator channels play, the cross-mix, the glide, each tone's frequency by zero crossings) - `crates/xcl/Cargo.toml`: the three features - `crates/xcl/src/hle/mod.rs`: the module **Tested** - RTX 4090 (driver 621.14), i9-14900K, Windows 11 26200, Rust stable-x86_64-pc-windows-msvc, debug tests, release smoke runs - `cargo test -p xcl --lib dualsense_haptics`: 2 passed - `cargo test --workspace -- --test-threads=1`: 698 passed, 0 failed, 41 ignored; SKIPPED: `gpu_geometry_wave32_prefix_count_over_a_mask` (no wave64), `gpu_wave32_program_in_wave64_hardware` (no wave64) - Single-threaded on purpose: with `--test-threads=4`, GPU tests on this machine hang or lose the device tonight on `main` too (bdab194 and 91f9a5e; bdab194 had passed with 4 threads earlier the same night, and the driver logs GPU errors). Single-threaded, `main` 91f9a5e passes (`cargo test -p xcl --lib -- --test-threads=1`: 647 passed, 0 failed). - With #731 on top, on a USB DualSense (054c:0ce6): the player found the controller's output in 4 channels at 48 kHz, started, and stopped at shutdown. **Regression run** Both runs use a fresh data root of their own. The title is not driven by a controller during the run, so this shows that nothing else changes, not the new path. ``` xcl-smoke v1 commit: 91f9a5e9f03156ea82dc55a18f7704862da7a5db gpu: NVIDIA GeForce RTX 4090 title: Xbox seconds: 60 exit: 0x0 frames shown: 811 (PresentX 811) presents per 2 s (last 3): 37 34 36 device removals: 0 crashes: 0 peak commit: 15536 MB ``` ``` xcl-smoke v1 commit: 4eebfdca13fe91e94f0892435242854f96d7c001 gpu: NVIDIA GeForce RTX 4090 title: Xbox seconds: 60 exit: 0x0 frames shown: 827 (PresentX 827) presents per 2 s (last 3): 36 37 36 device removals: 0 crashes: 0 peak commit: 15563 MB ``` **Not tested** - Whether the actuators feel right: nobody held the controller during the run. - An output that is not in 4 channels was not tried, so the refusal path is untested on hardware. - Nothing starts the player in this PR on its own. - AMD and other NVIDIA GPUs (the change has no GPU code). **AI use** - Claude Code with Claude Opus 5.5: wrote the code, the tests and this description; the hardware checks above are runs on the machine named under **Tested**. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
futurepro62 commented 2026-11-24 07:06:21 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by futurepro62 on 2026-11-24T04:46:55Z.


Tested exact head 4eebfdc (on its base 91f9a5e).

Tested

  • NVIDIA GeForce RTX 5070 Ti 16 GB (Blackwell, 32-lane waves only, mesh shaders), driver 616.64, Ryzen 7 9800X3D, Windows 11 Home 26300, Rust 1.100.0 MSVC, debug, D3D12 debug layer installed.
  • cargo build --workspace, then XCL_REQUIRE_GPU=mesh cargo test --workspace -- --test-threads=4: 698 passed, 0 failed, 41 ignored. SKIPPED (no wave64): gpu_geometry_wave32_prefix_count_over_a_mask, gpu_wave32_program_in_wave64_hardware.

Not tested

  • A DualSense or its haptics (none connected here), a retail title or scripts/smoke.ps1 (no title on this machine), AMD, a release build.

AI use

  • Claude Code (Claude Opus 5.5) ran the tests and wrote this report. I checked it before posting.
<!-- greyfinch-sync:ivall/xcl:comment:7122333233 --> Imported from [ivall/xcl](https://github.com/ivall/xcl/pull/710#issuecomment-7122333233). Originally posted by [futurepro62](https://github.com/futurepro62) on 2026-11-24T04:46:55Z. --- Tested exact head `4eebfdc` (on its base `91f9a5e`). **Tested** - NVIDIA GeForce RTX 5070 Ti 16 GB (Blackwell, 32-lane waves only, mesh shaders), driver 616.64, Ryzen 7 9800X3D, Windows 11 Home 26300, Rust 1.100.0 MSVC, debug, D3D12 debug layer installed. - `cargo build --workspace`, then `XCL_REQUIRE_GPU=mesh cargo test --workspace -- --test-threads=4`: **698 passed, 0 failed, 41 ignored**. SKIPPED (no wave64): `gpu_geometry_wave32_prefix_count_over_a_mask`, `gpu_wave32_program_in_wave64_hardware`. **Not tested** - A DualSense or its haptics (none connected here), a retail title or `scripts/smoke.ps1` (no title on this machine), AMD, a release build. **AI use** - Claude Code (Claude Opus 5.5) ran the tests and wrote this report. I checked it before posting.
MesshM commented 2026-11-24 07:06:26 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by MesshM on 2026-11-24T05:00:50Z.


Test run of 4eebfdca13fe91e94f0892435242854f96d7c001 on AMD RDNA4. I merged it onto current main 64b3f35 locally (clean merge), so the tree tested includes the stack under it (#552, #709).

Tested

  • AMD Radeon RX 9060 XT 16 GB (RDNA4), driver 32.0.32029.2010; Ryzen 7 5700X, 64 GB RAM, Windows 11 Pro build 26200, Rust 1.100.0 stable-x86_64-pc-windows-msvc, debug
  • cargo build --workspace + cargo test --workspace -- --test-threads=4 on the merge: 707 passed, 0 failed, 41 ignored, exit code 0; xcl lib tests 666 passed, 0 failed, 21 ignored
  • 0 SKIPPED; the dualsense_haptics tests pass (no DualSense attached, so no WASAPI output was opened).

Review: I reviewed the top commit only, as the description asks.

Not tested: no retail title or regression run (I have no unpacked game), no XCL_SAMPLE_* tests, release build; the PR's head on its old base was not run, only its merge onto main.

Run and review by Claude Code (Claude Opus 5.5) on this machine; the review points were checked against the code.

<!-- greyfinch-sync:ivall/xcl:comment:7122542508 --> Imported from [ivall/xcl](https://github.com/ivall/xcl/pull/710#issuecomment-7122542508). Originally posted by [MesshM](https://github.com/MesshM) on 2026-11-24T05:00:50Z. --- Test run of `4eebfdca13fe91e94f0892435242854f96d7c001` on AMD RDNA4. I merged it onto current `main` `64b3f35` locally (clean merge), so the tree tested includes the stack under it (#552, #709). **Tested** - AMD Radeon RX 9060 XT 16 GB (RDNA4), driver 32.0.32029.2010; Ryzen 7 5700X, 64 GB RAM, Windows 11 Pro build 26200, Rust 1.100.0 `stable-x86_64-pc-windows-msvc`, debug - `cargo build --workspace` + `cargo test --workspace -- --test-threads=4` on the merge: **707 passed, 0 failed, 41 ignored**, exit code 0; `xcl` lib tests 666 passed, 0 failed, 21 ignored - **0 `SKIPPED`**; the `dualsense_haptics` tests pass (no DualSense attached, so no WASAPI output was opened). **Review:** I reviewed the top commit only, as the description asks. **Not tested:** no retail title or regression run (I have no unpacked game), no `XCL_SAMPLE_*` tests, release build; the PR's head on its old base was not run, only its merge onto `main`. Run and review by Claude Code (Claude Opus 5.5) on this machine; the review points were checked against the code.
JJAutoCompare commented 2026-11-25 07:05:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by JJAutoCompare on 2026-11-25T06:18:29Z.


Empirical test report (4eebfdca)

Hardware / environment

  • PR #710 head 4eebfdca13fe91e94f0892435242854f96d7c001, checked out detached on STOR-WINLAB.
  • Windows 11 Enterprise Evaluation, x64, build 26200 (10.0.26200). AMD Ryzen 7 3800X, with 6 cores and 12 logical processors visible to Windows.
  • Rust 1.100.0 (0ef1bc386), target x86_64-pc-windows-msvc. DXC 1.9.2609.5 (01b62ad47). Cargo test profile unoptimized, with debug info and incremental compilation disabled.
  • The focused run used XCL_ADAPTER=NONE_CPU_ONLY and RUST_TEST_NOCAPTURE=1. The build and all three runs were outside Invoke-ArcTest.ps1, with no Arc GPU mutex held.

Commands and results

Command Exit Passed / failed / ignored / skipped
cargo test --workspace --no-run 0 Compile only
cargo test -p xcl --lib hle::dualsense_haptics::tests:: 0 2 / 0 / 0 / 0
cargo test -p xcl --lib hle::dualsense_report::tests:: 0 2 / 0 / 0 / 0
cargo test -p xcl --lib hle::playstation::tests:: 0 2 / 0 / 0 / 0

The total was 6 passed, 0 failed, 0 ignored, and 0 case-sensitive SKIPPED lines. Each focused invocation filtered out 677 tests. The build emitted a deprecation warning for Atomic::fetch_update in XGameRuntime.

Observed behavior

  • The synthesizer left the speaker channels silent and drove the actuator channels in memory. The tests also checked the amplitude ramp, stereo silence, and the 230 Hz tone by counting zero crossings.
  • The report tests verified trigger-effect encoding and USB output layout. The HID tests checked DualShock 4 and DualSense input parsing and controller identification from sample HID paths.
  • None of the six tests opened an audio endpoint. No audio-device skips were reported.

Not tested

Physical DualSense USB audio hardware, Windows audio endpoint discovery and playback, the full GPU workspace suite, and game smoke runs.

AI use

Verified with T3 Code / Codex (gpt-6.2-sol, reasoningEffort: high). Coordinator #2 (T3 Code / Antigravity, gemini-4-neon) verified counts against pr710-focused.log and published.

<!-- greyfinch-sync:ivall/xcl:comment:7154656017 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/710#issuecomment-7154656017). Originally posted by [JJAutoCompare](https://github.com/JJAutoCompare) on 2026-11-25T06:18:29Z. --- ### Empirical test report (4eebfdca) **Hardware / environment** - PR #710 head `4eebfdca13fe91e94f0892435242854f96d7c001`, checked out detached on STOR-WINLAB. - Windows 11 Enterprise Evaluation, x64, build 26200 (10.0.26200). AMD Ryzen 7 3800X, with 6 cores and 12 logical processors visible to Windows. - Rust 1.100.0 (0ef1bc386), target `x86_64-pc-windows-msvc`. DXC 1.9.2609.5 (01b62ad47). Cargo test profile unoptimized, with debug info and incremental compilation disabled. - The focused run used `XCL_ADAPTER=NONE_CPU_ONLY` and `RUST_TEST_NOCAPTURE=1`. The build and all three runs were outside `Invoke-ArcTest.ps1`, with no Arc GPU mutex held. **Commands and results** | Command | Exit | Passed / failed / ignored / skipped | | --- | ---: | --- | | `cargo test --workspace --no-run` | 0 | Compile only | | `cargo test -p xcl --lib hle::dualsense_haptics::tests::` | 0 | 2 / 0 / 0 / 0 | | `cargo test -p xcl --lib hle::dualsense_report::tests::` | 0 | 2 / 0 / 0 / 0 | | `cargo test -p xcl --lib hle::playstation::tests::` | 0 | 2 / 0 / 0 / 0 | The total was 6 passed, 0 failed, 0 ignored, and 0 case-sensitive `SKIPPED ` lines. Each focused invocation filtered out 677 tests. The build emitted a deprecation warning for `Atomic::fetch_update` in XGameRuntime. **Observed behavior** - The synthesizer left the speaker channels silent and drove the actuator channels in memory. The tests also checked the amplitude ramp, stereo silence, and the 230 Hz tone by counting zero crossings. - The report tests verified trigger-effect encoding and USB output layout. The HID tests checked DualShock 4 and DualSense input parsing and controller identification from sample HID paths. - None of the six tests opened an audio endpoint. No audio-device skips were reported. **Not tested** Physical DualSense USB audio hardware, Windows audio endpoint discovery and playback, the full GPU workspace suite, and game smoke runs. **AI use** Verified with T3 Code / Codex (gpt-6.2-sol, reasoningEffort: high). Coordinator #2 (T3 Code / Antigravity, gemini-4-neon) verified counts against pr710-focused.log and published.
DavidM1911 commented 2026-11-25 12:06:30 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by DavidM1911 on 2026-11-25T11:54:23Z.


Verification on RTX 3060 Ti (Windows 11), branch merged with current main:

  • cargo test -p xcl --lib: all passed, 0 failed, ~26 ignored. (Intermittent single-test flake / 0xc0000005 abort under parallel scheduling — tracked in #1978; clean on single-threaded rerun.)

Thanks!

<!-- greyfinch-sync:ivall/xcl:comment:7161661334 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/710#issuecomment-7161661334). Originally posted by [DavidM1911](https://github.com/DavidM1911) on 2026-11-25T11:54:23Z. --- Verification on RTX 3060 Ti (Windows 11), branch merged with current `main`: - `cargo test -p xcl --lib`: all passed, 0 failed, ~26 ignored. (Intermittent single-test flake / 0xc0000005 abort under parallel scheduling — tracked in #1978; clean on single-threaded rerun.) Thanks!
gut0to commented 2026-11-26 16:55:32 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by gut0to on 2026-11-26T16:55:32Z.

Code review location: crates/xcl/src/hle/dualsense_haptics.rs; line 144

@@ -0,0 +1,229 @@
+//! DualSense haptics from the title's rumble. Over USB the controller is also a 4-channel
+//! audio output whose channels 3 and 4 drive the left and right voice-coil actuators; a
+//! thread plays waveforms made from the two rumble levels there (the big, slow motor as a
+//! low tone mostly on the left, the small, fast one as a higher tone mostly on the right).
+//! Channels 1 and 2 (the speaker and headset jack) stay silent.
+//!
+//! It needs the controller's audio output in 4 channels (Windows' sound settings: the
+//! controller's speaker configuration "Quadraphonic"); otherwise `start` fails and the
+//! caller keeps compatible rumble.
+
+use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+/// the left (big) motor's tone and the right (small) one's, Hz
+const LOW_HZ: f32 = 100.0;
+const HIGH_HZ: f32 = 230.0;
+/// how much of each motor reaches the other side's actuator
+const CROSS: f32 = 0.25;
+
+/// A phase-continuous two-tone generator whose amplitudes glide to their targets (no clicks
+/// when the title changes the levels).
+#[derive(Default, Clone, Debug)]
+pub struct Synth {
+    phase_lo: f32,
+    phase_hi: f32,
+    amp_lo: f32,
+    amp_hi: f32,
+}
+
+impl Synth {
+    /// `frames` frames of `channels` interleaved samples at `rate` Hz into `out`; the actuators
+    /// are channels 2 and 3 (0-based), the others get silence.
+    pub fn fill(&mut self, out: &mut [f32], channels: usize, rate: f32, low: f32, high: f32) {
+        let frames = out.len() / channels.max(1);
+        let (low, high) = (low.clamp(0.0, 1.0), high.clamp(0.0, 1.0));
+        // glide over about 10 ms
+        let k = (1.0 / (0.010 * rate)).min(1.0);
+        let tau = std::f32::consts::TAU;
+        for f in 0..frames {
+            self.amp_lo += (low - self.amp_lo) * k;
+            self.amp_hi += (high - self.amp_hi) * k;
+            self.phase_lo = (self.phase_lo + tau * LOW_HZ / rate) % tau;
+            self.phase_hi = (self.phase_hi + tau * HIGH_HZ / rate) % tau;
+            let lo = self.amp_lo * self.phase_lo.sin();
+            let hi = self.amp_hi * self.phase_hi.sin();
+            let frame = &mut out[f * channels..(f + 1) * channels];
+            frame.fill(0.0);
+            if channels >= 4 {
+                frame[2] = ((1.0 - CROSS) * lo + CROSS * hi).clamp(-1.0, 1.0);
+                frame[3] = ((1.0 - CROSS) * hi + CROSS * lo).clamp(-1.0, 1.0);
+            }
+        }
+    }
+}
+
+/// the levels the thread plays (f32 bits)
+static LOW: AtomicU32 = AtomicU32::new(0);
+static HIGH: AtomicU32 = AtomicU32::new(0);
+static RUNNING: AtomicBool = AtomicBool::new(false);
+static STOP: AtomicBool = AtomicBool::new(false);
+
+/// Sets what the actuators play (0..1).
+pub fn set(low: f32, high: f32) {
+    LOW.store(low.to_bits(), Ordering::Relaxed);
+    HIGH.store(high.to_bits(), Ordering::Relaxed);
+}
+
+/// Whether the haptics thread is playing.
+pub fn running() -> bool {
+    RUNNING.load(Ordering::Acquire)
+}
+
+/// Stops the thread (it notices within a buffer).
+pub fn stop() {
+    set(0.0, 0.0);
+    STOP.store(true, Ordering::Release);
+}
+
+/// Starts playing on the audio output whose name contains `name`; waits until it plays or
+/// fails (true: playing).
+pub fn start(name: &str) -> bool {
+    if running() {
+        return true;
+    }
+    static STARTING: OnceLock<std::sync::Mutex<()>> = OnceLock::new();
+    let _g = STARTING.get_or_init(Default::default).lock().unwrap();
+    if running() {
+        return true;
+    }
+    STOP.store(false, Ordering::Release);
+    let (tx, rx) = std::sync::mpsc::channel();
+    let name = name.to_string();
+    let spawned = std::thread::Builder::new().name("xcl-dualsense-haptics".into()).spawn(move || {
+        crate::eh::arm_current_thread();
+        // SAFETY: COM and WASAPI calls on this thread's own objects
+        if let Err(e) = unsafe { play(&name, &tx) } {
+            let _ = tx.send(Err(e));
+        }
+        RUNNING.store(false, Ordering::Release);
+    });
+    if spawned.is_err() {
+        return false;
+    }
+    match rx.recv_timeout(Duration::from_secs(3)) {
+        Ok(Ok(())) => true,
+        Ok(Err(e)) => {
+            crate::xlog_info!("GameInput: DualSense haptics not available ({e}); compatible rumble instead");
+            false
+        }
+        Err(_) => false,
+    }
+}
+
+unsafe fn play(name: &str, ready: &std::sync::mpsc::Sender<Result<(), String>>) -> Result<(), String> {
+    use windows::Win32::Media::Audio::*;
+    use windows::Win32::System::Com::StructuredStorage::PropVariantToStringAlloc;
+    use windows::Win32::System::Com::*;
+
+    let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
+    let e: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(|e| e.to_string())?;
+    let all = e.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE).map_err(|e| e.to_string())?;
+    // PKEY_Device_FriendlyName
+    let key = windows::Win32::Foundation::PROPERTYKEY { fmtid: windows::core::GUID::from_u128(0xa45c254e_df1c_4efd_8020_67d146a850e0), pid: 14 };
+    let want = name.to_ascii_lowercase();
+    let mut found = None;
+    for i in 0..all.GetCount().unwrap_or(0) {
+        let Ok(d) = all.Item(i) else { continue };
+        let Ok(props) = d.OpenPropertyStore(STGM_READ) else { continue };
+        let Ok(v) = props.GetValue(&key) else { continue };
+        let Ok(s) = PropVariantToStringAlloc(&v) else { continue };
+        let n = s.to_string().unwrap_or_default();
+        CoTaskMemFree(Some(s.0 as *const _));
+        if n.to_ascii_lowercase().contains(&want) {
+            found = Some((d, n));
+            break;
+        }
+    }
+    let (dev, devname) = found.ok_or_else(|| format!("no audio output named like {name:?}: the controller is not on USB, or its audio is off"))?;
+    let client: IAudioClient = dev.Activate(CLSCTX_ALL, None).map_err(|e| e.to_string())?;
+    let fmt = client.GetMixFormat().map_err(|e| e.to_string())?;
+    let (channels, rate, bits) = ((*fmt).nChannels as usize, (*fmt).nSamplesPerSec as f32, (*fmt).wBitsPerSample);
+    // float (WAVE_FORMAT_IEEE_FLOAT, or EXTENSIBLE with 32 bits: the shared-mode mix format is float)
+    let float = (*fmt).wFormatTag == 3 || ((*fmt).wFormatTag == 0xFFFE && bits == 32);

Could this check inspect WAVEFORMATEXTENSIBLE.SubFormat instead of treating every 32-bit extensible format as float? Extensible formats can be either PCM or IEEE float; with a 32-bit PCM mix format, this branch selects the float render path and copies f32 bit patterns into an integer PCM stream. Please accept only the supported PCM/float subformats and add a focused format-selection test. AI-assisted review: I checked this against the Windows format definition, but I did not run tests.

<!-- greyfinch-sync:ivall/xcl:review-comment:4711379832 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/710#discussion_r4711379832). Originally posted by [gut0to](https://github.com/gut0to) on 2026-11-26T16:55:32Z. **Code review location:** `crates/xcl/src/hle/dualsense_haptics.rs`; line 144 ~~~~diff @@ -0,0 +1,229 @@ +//! DualSense haptics from the title's rumble. Over USB the controller is also a 4-channel +//! audio output whose channels 3 and 4 drive the left and right voice-coil actuators; a +//! thread plays waveforms made from the two rumble levels there (the big, slow motor as a +//! low tone mostly on the left, the small, fast one as a higher tone mostly on the right). +//! Channels 1 and 2 (the speaker and headset jack) stay silent. +//! +//! It needs the controller's audio output in 4 channels (Windows' sound settings: the +//! controller's speaker configuration "Quadraphonic"); otherwise `start` fails and the +//! caller keeps compatible rumble. + +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::OnceLock; +use std::time::Duration; + +/// the left (big) motor's tone and the right (small) one's, Hz +const LOW_HZ: f32 = 100.0; +const HIGH_HZ: f32 = 230.0; +/// how much of each motor reaches the other side's actuator +const CROSS: f32 = 0.25; + +/// A phase-continuous two-tone generator whose amplitudes glide to their targets (no clicks +/// when the title changes the levels). +#[derive(Default, Clone, Debug)] +pub struct Synth { + phase_lo: f32, + phase_hi: f32, + amp_lo: f32, + amp_hi: f32, +} + +impl Synth { + /// `frames` frames of `channels` interleaved samples at `rate` Hz into `out`; the actuators + /// are channels 2 and 3 (0-based), the others get silence. + pub fn fill(&mut self, out: &mut [f32], channels: usize, rate: f32, low: f32, high: f32) { + let frames = out.len() / channels.max(1); + let (low, high) = (low.clamp(0.0, 1.0), high.clamp(0.0, 1.0)); + // glide over about 10 ms + let k = (1.0 / (0.010 * rate)).min(1.0); + let tau = std::f32::consts::TAU; + for f in 0..frames { + self.amp_lo += (low - self.amp_lo) * k; + self.amp_hi += (high - self.amp_hi) * k; + self.phase_lo = (self.phase_lo + tau * LOW_HZ / rate) % tau; + self.phase_hi = (self.phase_hi + tau * HIGH_HZ / rate) % tau; + let lo = self.amp_lo * self.phase_lo.sin(); + let hi = self.amp_hi * self.phase_hi.sin(); + let frame = &mut out[f * channels..(f + 1) * channels]; + frame.fill(0.0); + if channels >= 4 { + frame[2] = ((1.0 - CROSS) * lo + CROSS * hi).clamp(-1.0, 1.0); + frame[3] = ((1.0 - CROSS) * hi + CROSS * lo).clamp(-1.0, 1.0); + } + } + } +} + +/// the levels the thread plays (f32 bits) +static LOW: AtomicU32 = AtomicU32::new(0); +static HIGH: AtomicU32 = AtomicU32::new(0); +static RUNNING: AtomicBool = AtomicBool::new(false); +static STOP: AtomicBool = AtomicBool::new(false); + +/// Sets what the actuators play (0..1). +pub fn set(low: f32, high: f32) { + LOW.store(low.to_bits(), Ordering::Relaxed); + HIGH.store(high.to_bits(), Ordering::Relaxed); +} + +/// Whether the haptics thread is playing. +pub fn running() -> bool { + RUNNING.load(Ordering::Acquire) +} + +/// Stops the thread (it notices within a buffer). +pub fn stop() { + set(0.0, 0.0); + STOP.store(true, Ordering::Release); +} + +/// Starts playing on the audio output whose name contains `name`; waits until it plays or +/// fails (true: playing). +pub fn start(name: &str) -> bool { + if running() { + return true; + } + static STARTING: OnceLock<std::sync::Mutex<()>> = OnceLock::new(); + let _g = STARTING.get_or_init(Default::default).lock().unwrap(); + if running() { + return true; + } + STOP.store(false, Ordering::Release); + let (tx, rx) = std::sync::mpsc::channel(); + let name = name.to_string(); + let spawned = std::thread::Builder::new().name("xcl-dualsense-haptics".into()).spawn(move || { + crate::eh::arm_current_thread(); + // SAFETY: COM and WASAPI calls on this thread's own objects + if let Err(e) = unsafe { play(&name, &tx) } { + let _ = tx.send(Err(e)); + } + RUNNING.store(false, Ordering::Release); + }); + if spawned.is_err() { + return false; + } + match rx.recv_timeout(Duration::from_secs(3)) { + Ok(Ok(())) => true, + Ok(Err(e)) => { + crate::xlog_info!("GameInput: DualSense haptics not available ({e}); compatible rumble instead"); + false + } + Err(_) => false, + } +} + +unsafe fn play(name: &str, ready: &std::sync::mpsc::Sender<Result<(), String>>) -> Result<(), String> { + use windows::Win32::Media::Audio::*; + use windows::Win32::System::Com::StructuredStorage::PropVariantToStringAlloc; + use windows::Win32::System::Com::*; + + let _ = CoInitializeEx(None, COINIT_MULTITHREADED); + let e: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(|e| e.to_string())?; + let all = e.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE).map_err(|e| e.to_string())?; + // PKEY_Device_FriendlyName + let key = windows::Win32::Foundation::PROPERTYKEY { fmtid: windows::core::GUID::from_u128(0xa45c254e_df1c_4efd_8020_67d146a850e0), pid: 14 }; + let want = name.to_ascii_lowercase(); + let mut found = None; + for i in 0..all.GetCount().unwrap_or(0) { + let Ok(d) = all.Item(i) else { continue }; + let Ok(props) = d.OpenPropertyStore(STGM_READ) else { continue }; + let Ok(v) = props.GetValue(&key) else { continue }; + let Ok(s) = PropVariantToStringAlloc(&v) else { continue }; + let n = s.to_string().unwrap_or_default(); + CoTaskMemFree(Some(s.0 as *const _)); + if n.to_ascii_lowercase().contains(&want) { + found = Some((d, n)); + break; + } + } + let (dev, devname) = found.ok_or_else(|| format!("no audio output named like {name:?}: the controller is not on USB, or its audio is off"))?; + let client: IAudioClient = dev.Activate(CLSCTX_ALL, None).map_err(|e| e.to_string())?; + let fmt = client.GetMixFormat().map_err(|e| e.to_string())?; + let (channels, rate, bits) = ((*fmt).nChannels as usize, (*fmt).nSamplesPerSec as f32, (*fmt).wBitsPerSample); + // float (WAVE_FORMAT_IEEE_FLOAT, or EXTENSIBLE with 32 bits: the shared-mode mix format is float) + let float = (*fmt).wFormatTag == 3 || ((*fmt).wFormatTag == 0xFFFE && bits == 32); ~~~~ --- Could this check inspect `WAVEFORMATEXTENSIBLE.SubFormat` instead of treating every 32-bit extensible format as float? Extensible formats can be either PCM or IEEE float; with a 32-bit PCM mix format, this branch selects the float render path and copies f32 bit patterns into an integer PCM stream. Please accept only the supported PCM/float subformats and add a focused format-selection test. AI-assisted review: I checked this against the Windows format definition, but I did not run tests.
Foniass commented 2026-12-01 03:59:36 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T03:59:36Z.


Triage (#1607) – head 4eebfdc

Stacked on #552 (merged) and #709; only 4eebfdc belongs here, and #715 / #731 build on it. No other open or merged PR plays haptics on the DualSense's USB audio channels.
Minor, in dualsense_haptics.rs:start: when the thread takes longer than 3 s to answer, start returns false (the caller keeps compatible rumble) but the thread keeps going and may start playing too; and start right after stop returns true while the old thread is still exiting, so nothing plays. Nothing calls it yet.
Recommendation: keep open.

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.

<!-- greyfinch-sync:ivall/xcl:comment:7300267632 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/710#issuecomment-7300267632). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T03:59:36Z. --- **Triage (#1607)** – head 4eebfdc Stacked on #552 (merged) and #709; only 4eebfdc belongs here, and #715 / #731 build on it. No other open or merged PR plays haptics on the DualSense's USB audio channels. Minor, in `dualsense_haptics.rs:start`: when the thread takes longer than 3 s to answer, `start` returns false (the caller keeps compatible rumble) but the thread keeps going and may start playing too; and `start` right after `stop` returns true while the old thread is still exiting, so nothing plays. Nothing calls it yet. Recommendation: keep open. AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/710:upstream-pr/710'
git switch 'upstream-pr/710'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/710'
git switch 'upstream-pr/710'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/710'
git switch 'upstream-pr/710'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/710'
git switch 'main'
git merge --squash 'upstream-pr/710'
git switch 'main'
git merge --ff-only 'upstream-pr/710'
git switch 'main'
git merge 'upstream-pr/710'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
xcl-dev/xcl!705
No description provided.