diff --git a/Cargo.lock b/Cargo.lock index 5f8e14abc..d6bbf30d9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1286,6 +1286,7 @@ dependencies = [ name = "horizon-dualsense" version = "0.1.0" dependencies = [ + "cpal", "hidapi", "log", ] diff --git a/crates/horizon-client/src/game/pad.rs b/crates/horizon-client/src/game/pad.rs index fdff9abdb..53aab1884 100644 --- a/crates/horizon-client/src/game/pad.rs +++ b/crates/horizon-client/src/game/pad.rs @@ -59,6 +59,9 @@ pub(super) struct Pads { /// Its own output over HID (rumble here; gilrs only reads it), started once this window /// has the pad in hand; dropped, it releases the pad. output: Option, + /// Its HD haptics, on USB: looked for once each time the output opens. + haptics: Option, + haptics_tried: bool, /// What it was last told to show. shown: Option, } @@ -219,6 +222,7 @@ impl Game<'_> { if self.pad.dualsense && self.pad.in_use && self.focused && self.pad.output.is_none() { self.pad.output = Some(horizon_dualsense::Link::start()); } + self.pad_haptics(); self.pad_show(); // Damage from any source, here or on a server; nothing counts on // the title screen. @@ -506,8 +510,28 @@ impl Game<'_> { } } + /// Open the pad's haptics once its output is open over USB (its audio device is there + /// only then); close them when it goes. Opt-in with `HORIZON_DUALSENSE_HAPTICS=1` until + /// they are proven on a pad (docs/controllers.md); never for games without sound (tests). + fn pad_haptics(&mut self) { + let usb = self.pad.output.as_ref().and_then(|o| o.open()) + == Some(horizon_dualsense::Transport::Usb); + if !usb { + self.pad.haptics = None; + self.pad.haptics_tried = false; + } else if !self.pad.haptics_tried { + self.pad.haptics_tried = true; + if std::env::var_os("HORIZON_DUALSENSE_HAPTICS").is_some_and(|v| v == "1") + && std::env::var_os("HORIZON_NO_AUDIO").is_none() + { + self.pad.haptics = horizon_dualsense::haptics::Haptics::open(); + } + } + } + /// Release the DualSense's output (the game is quitting). pub(super) fn pad_close_output(&mut self) { + self.pad.haptics = None; self.pad.output = None; } @@ -525,9 +549,28 @@ impl Game<'_> { }; self.pad.last_rumble = Some((rumble.name(), pulse)); let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + if let Some(haptics) = self + .pad + .haptics + .as_ref() + .filter(|_| self.pad_output().is_some()) + { + let steps = rumble.shape().into_iter().map(|step| { + ( + step.strong, + step.weak, + Duration::from_millis(u64::from(step.millis)), + ) + }); + haptics.play(&steps.collect::>()); + return; + } if let Some(output) = self.pad_output() { - let length = Duration::from_millis(u64::from(pulse.millis)); - output.rumble(vec![([level(pulse.strong), level(pulse.weak)], length)]); + let steps = rumble.shape().into_iter().map(|step| { + let length = Duration::from_millis(u64::from(step.millis)); + ([level(step.strong), level(step.weak)], length) + }); + output.rumble(steps.collect()); return; } let (Some(gilrs), Some(id)) = (self.pad.gilrs.as_mut(), self.pad.active) else { diff --git a/crates/horizon-client/src/gamepad.rs b/crates/horizon-client/src/gamepad.rs index 0649b6bef..c1be6a90b 100644 --- a/crates/horizon-client/src/gamepad.rs +++ b/crates/horizon-client/src/gamepad.rs @@ -950,6 +950,38 @@ impl Rumble { }), } } + + /// The pulse shaped, for a pad that plays steps (a DualSense): a hit starts at full + /// strength and dies away, an explosion rolls on, a totem swells; a broken block is a tick. + pub fn shape(self) -> Vec { + let Some(p) = self.pulse() else { + return Vec::new(); + }; + let step = |level: f32, millis: u32| Pulse { + strong: p.strong * level, + weak: p.weak * level, + millis, + }; + match self { + Rumble::BlockBroken => vec![Pulse { millis: 35, ..p }], + Rumble::Hurt(_) => { + let tail = p.millis.saturating_sub(50) / 2; + vec![step(1.0, 50), step(0.55, tail), step(0.25, tail)] + } + Rumble::Explosion { .. } => vec![ + step(1.0, 80), + step(0.6, 150), + step(0.35, 150), + step(0.15, 150), + ], + Rumble::Totem => vec![ + step(0.4, 100), + step(0.7, 100), + step(1.0, 200), + step(0.5, 100), + ], + } + } } /// What a trigger feels like on a DualSense, from what its action is doing (docs/controllers.md @@ -1394,6 +1426,26 @@ mod tests { None ); assert_eq!(Rumble::BlockBroken.pulse().unwrap().strong, 0.0); + // Shapes open at the pulse's strength and fade; nothing for what isn't felt. + for rumble in [ + Rumble::Hurt(4.0), + Rumble::Explosion { + distance: 2.0, + radius: 4.0, + }, + ] { + let (pulse, shape) = (rumble.pulse().unwrap(), rumble.shape()); + assert_eq!(shape[0].strong, pulse.strong); + assert!(shape.windows(2).all(|w| w[1].strong < w[0].strong)); + } + let hurt: u32 = Rumble::Hurt(4.0).shape().iter().map(|s| s.millis).sum(); + assert!(hurt.abs_diff(Rumble::Hurt(4.0).pulse().unwrap().millis) <= 1); + assert_eq!( + Rumble::Totem.shape().iter().map(|s| s.millis).sum::(), + 500 + ); + assert_eq!(Rumble::BlockBroken.shape()[0].millis, 35); + assert!(Rumble::Hurt(0.0).shape().is_empty()); } #[test] diff --git a/crates/horizon-dualsense/Cargo.toml b/crates/horizon-dualsense/Cargo.toml index 8e26f2e59..fe05b4f59 100644 --- a/crates/horizon-dualsense/Cargo.toml +++ b/crates/horizon-dualsense/Cargo.toml @@ -11,6 +11,8 @@ description = "The DualSense's output over HID: rumble, adaptive triggers, light # IOKit on macOS (opened shared, so gilrs keeps reading the pad), the HID API on Windows. hidapi = { version = "2.6.7", default-features = false, features = ["linux-static-hidraw", "macos-shared-device"] } log = "0.4" +# HD haptics through the pad's own audio device (USB). +cpal = "0.16" [lints] workspace = true diff --git a/crates/horizon-dualsense/src/haptics.rs b/crates/horizon-dualsense/src/haptics.rs new file mode 100644 index 000000000..6aa9d5ab8 --- /dev/null +++ b/crates/horizon-dualsense/src/haptics.rs @@ -0,0 +1,149 @@ +//! HD haptics: on USB the DualSense is also a four-channel 48 kHz audio device, whose channels 3 +//! and 4 drive the left and right voice-coil actuators (1 and 2 are its speaker and headset). +//! Vibrations are synthesized as waveforms on those two channels; the first two stay silent. +//! Over Bluetooth there is no audio device, and the motors' emulation is used instead. +use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; +use std::collections::VecDeque; +use std::f32::consts::TAU; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +const RATE: u32 = 48_000; +/// The frequencies the heavy and light parts of a vibration play at. +pub const HEAVY_HZ: f32 = 80.0; +pub const LIGHT_HZ: f32 = 200.0; +/// Fades between steps, so a level change doesn't click. +const RAMP: f32 = 0.004; + +/// The pad's audio output, playing the queued samples (left, right actuator). +pub struct Haptics { + queue: Arc>>, + _stream: cpal::Stream, +} + +impl Haptics { + /// The DualSense's audio device, if one is there with its four channels (USB). + pub fn open() -> Option { + let host = cpal::default_host(); + let device = host.output_devices().ok()?.find(is_dualsense)?; + let config = cpal::StreamConfig { + channels: 4, + sample_rate: cpal::SampleRate(RATE), + buffer_size: cpal::BufferSize::Default, + }; + let queue = Arc::new(Mutex::new(VecDeque::new())); + let source = queue.clone(); + let stream = device + .build_output_stream( + &config, + move |data: &mut [f32], _| { + let mut queue = source.lock().unwrap_or_else(|e| e.into_inner()); + for frame in data.chunks_mut(4) { + let [left, right] = queue.pop_front().unwrap_or_default(); + frame.copy_from_slice(&[0.0, 0.0, left, right]); + } + }, + |e| log::debug!("DualSense haptics: {e}"), + None, + ) + .map_err(|e| log::info!("Horizon: DualSense haptics unavailable: {e}")) + .ok()?; + stream.play().ok()?; + log::info!("DualSense HD haptics through its audio device"); + Some(Haptics { + queue, + _stream: stream, + }) + } + + /// Play a vibration (heavy and light levels, 0..1, each for a while), replacing the one + /// playing. + pub fn play(&self, steps: &[(f32, f32, Duration)]) { + let samples = waveform(steps); + let mut queue = self.queue.lock().unwrap_or_else(|e| e.into_inner()); + queue.clear(); + queue.extend(samples.into_iter().map(|v| [v, v])); + } + + /// Stop at once. + pub fn stop(&self) { + self.queue.lock().unwrap_or_else(|e| e.into_inner()).clear(); + } +} + +fn is_dualsense(device: &cpal::Device) -> bool { + device.name().is_ok_and(|n| is_dualsense_name(&n)) + && device.supported_output_configs().is_ok_and(|mut configs| { + configs.any(|c| { + c.channels() >= 4 + && c.min_sample_rate().0 <= RATE + && c.max_sample_rate().0 >= RATE + && c.sample_format() == cpal::SampleFormat::F32 + }) + }) +} + +/// "DualSense Wireless Controller" on macOS; on Windows the endpoint is often just "Speakers +/// (Wireless Controller)" (DS5Windows' and dse-haptics' setup notes), a name the DualShock 4's +/// two-channel headset output shares, which the four channels rule out; ALSA names the card +/// "Controller". +fn is_dualsense_name(name: &str) -> bool { + name.contains("DualSense") + || name.contains("Wireless Controller") + || name.contains("CARD=Controller") +} + +/// The samples of a vibration: the heavy and light tones at each step's levels, with short +/// ramps between steps and to silence at the end. +pub fn waveform(steps: &[(f32, f32, Duration)]) -> Vec { + let ramp = (RAMP * RATE as f32) as usize; + let mut out = Vec::new(); + let mut level = [0.0f32; 2]; + let mut t = 0usize; + for &(heavy, light, length) in steps.iter().chain(&[(0.0, 0.0, Duration::ZERO)]) { + let target = [heavy.clamp(0.0, 1.0), light.clamp(0.0, 1.0)]; + let from = level; + let n = (length.as_secs_f32() * RATE as f32) as usize; + for i in 0..n.max(ramp) { + let k = (i as f32 / ramp as f32).min(1.0); + level = [0, 1].map(|j| from[j] + (target[j] - from[j]) * k); + let time = t as f32 / RATE as f32; + let v = + level[0] * (TAU * HEAVY_HZ * time).sin() + level[1] * (TAU * LIGHT_HZ * time).sin(); + out.push(v.clamp(-1.0, 1.0)); + t += 1; + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn device_names() { + assert!(is_dualsense_name("DualSense Wireless Controller")); + assert!(is_dualsense_name("Speakers (Wireless Controller)")); + assert!(is_dualsense_name( + "Speakers (2- DualSense Wireless Controller)" + )); + assert!(is_dualsense_name("plughw:CARD=Controller,DEV=0")); + assert!(!is_dualsense_name("MacBook Pro Speakers")); + assert!(!is_dualsense_name("hw:CARD=PCH,DEV=0")); + } + + #[test] + fn waveform_follows_the_steps() { + let w = waveform(&[(1.0, 0.0, Duration::from_millis(100))]); + // The step, then the ramp down. + assert_eq!(w.len(), 4800 + 192); + // Starts silent, reaches full strength, ends silent. + assert_eq!(w[0], 0.0); + let peak = w[1000..4800].iter().fold(0.0f32, |m, v| m.max(v.abs())); + assert!(peak > 0.99, "{peak}"); + assert!(w.last().unwrap().abs() < 0.01); + assert!(w.iter().all(|v| v.abs() <= 1.0)); + assert!(waveform(&[]).iter().all(|v| *v == 0.0)); + } +} diff --git a/crates/horizon-dualsense/src/lib.rs b/crates/horizon-dualsense/src/lib.rs index f7e70e756..227fba6b0 100644 --- a/crates/horizon-dualsense/src/lib.rs +++ b/crates/horizon-dualsense/src/lib.rs @@ -7,6 +7,7 @@ //! and as report 0x31 over Bluetooth, where a sequence tag leads it and a CRC-32 (seeded with //! the byte 0xA2) closes it. pub mod device; +pub mod haptics; pub mod trigger; pub use device::{Link, Transport}; diff --git a/docs/controllers.md b/docs/controllers.md index a33403938..095914a02 100644 --- a/docs/controllers.md +++ b/docs/controllers.md @@ -248,7 +248,7 @@ sensitivity, slower while scoping with a spyglass. Vibration (on by default, off in the options): taking damage (stronger with the damage), a block broken, an explosion nearby (scaled by distance), a totem of undying. Short, low-intensity pulses, as on Bedrock. A DualSense gets them -through its own output report (below), on every OS. Other pads go through +shaped, through its own output report (below), on every OS. Other pads go through gilrs force feedback: Linux (evdev force feedback, including Steam Input's virtual pad) and Windows support it; macOS gilrs has no force feedback, so it is silently skipped there. @@ -393,6 +393,49 @@ documents (none of it measured on Horizon's pad yet): get a finer, faster grit, harder ones a slower, heavier chug, never above 5 of 8, since the attack trigger is held for seconds. +### Vibration shapes and HD haptics + +Each event plays a short shape rather than one flat block: a hit opens at +full strength for 50 ms and dies away in two steps, an explosion rolls on for +half a second, a totem swells, a broken block is a 35 ms tick. Over HID they +drive the motors' emulation (the compatible-vibration bytes). Measured on the +pad, that emulation has inertia: after a full-strength step it takes about +half a second to settle, so short shapes blur. + +The DualSense has no motors, but two voice-coil actuators, and on USB it is +also a four-channel 48 kHz audio device whose channels 3 and 4 drive them +(1 and 2 are its speaker and headset). Played there as waveforms (an 80 Hz +tone for the heavy part, 200 Hz for the light one, 4 ms ramps between steps, +channels 1 and 2 silent), the same shapes come out crisp. Per OS: + +| | USB | Bluetooth | +|---|---|---| +| macOS | the pad lists as a 4-channel CoreAudio output ("DualSense Wireless Controller", seen on the Mac mini by dualsense-1); cpal opens it by name | no audio device | +| Linux | snd-usb-audio exposes the card "Controller" with 4 channels; cpal opens it through ALSA (`plughw:CARD=Controller`), which fails while PipeWire or PulseAudio holds the card, as desktops do: then the motors' emulation stays | no audio device | +| Windows | a WASAPI endpoint named "Wireless Controller" (or "DualSense Wireless Controller"), stereo until its speaker setup is set to Quadraphonic in the Sound control panel (`mmsys.cpl`, Configure); until then Horizon finds no 4-channel output and keeps the motors | no audio device | + +The audio haptics play only while the pad is out of its rumble emulation: +any report with the rumble flags (flags 0, bits 0 and 1) silences them until +a report without them (SDL: "Leaving emulated rumble bits off will restore +audio haptics"; nondebug/dualsense and +[dse-haptics](https://github.com/iranran666/dse-haptics) arm them with an +all-zero report 0x02). While HD haptics are open the motors stay at zero, so +every report Horizon sends, starting with the one at opening, keeps them +armed; that first report also clears the attenuation a PS5 may have left. +The frame layout `[0, 0, left, right]` at 48 kHz is the one +[KytyPS5 #843](https://github.com/KytyPS5/KytyPS5/pull/843) plays on +Windows. + +Over Bluetooth the haptics travel as 8-bit 3 kHz samples in vendor output +report 0x32, reverse-engineered by +[SAxense](https://github.com/egormanga/SAxense) and since used by DSX 3.2 +and [dualsense-bt-haptics](https://github.com/awalol/dualsense-bt-haptics); +it needs Bluetooth output, which only Linux gets (see above), and isn't +done: there the motors' emulation is used. HD haptics are opt-in for now +(`HORIZON_DUALSENSE_HAPTICS=1`) until they are confirmed on a real pad; +games started for tests (`HORIZON_NO_AUDIO`) never open them, and the pad's +audio device is only ever opened by name, never the system's default output. + Byte layout from public references, read for facts; no code is copied from them (the kernel and dualsensectl are GPL): @@ -404,6 +447,7 @@ them (the kernel and dualsensectl are GPL): | Nielk1's [TriggerEffectGenerator](https://gist.github.com/Nielk1/6d54cc2c00d2201ccb8c2720ad7538db/f73a299fdc52f43be84d39e62734192ad82bb393) (MIT) | rev. `f73a299` | the trigger modes (official 0x05, 0x21, 0x25, 0x26) and their zone packing | | [pydualsense](https://github.com/flok/pydualsense/blob/01445f5ed6ba/pydualsense/pydualsense.py) (MIT) | `01445f5` | sets the attenuation flag with 0 on every report | | [nondebug/dualsense](https://github.com/nondebug/dualsense) | `b87450e` | an all-zero report 0x02 leaves rumble emulation for the audio haptics | +| [KytyPS5 #843](https://github.com/KytyPS5/KytyPS5/pull/843), [dse-haptics](https://github.com/iranran666/dse-haptics), [SAxense](https://github.com/egormanga/SAxense) | read 2026-10-15 | the 4-channel layout, the Windows and Linux device names and setup, the Bluetooth haptics report | Verified on hardware (USB, dualsense-1, Mac mini): the motors with the V2 flags (the IMU shook, and settled after a stop that then still sent the