audio: play DualSense haptics from vibration audio ports #843

Manually merged
github merged 3 commits from gh-pr/843/head into gh-pr/843/base 2026-11-26 09:34:43 +00:00
Owner

@⁠Cosmo on GitHub · 2026-09-26 02:30 UTC · original
Cosmo:dualsense-audio-haptics → main · +588 −3 · 7 files · 3 commits · merged 2026-09-26 20:37 UTC

Summary

PS5 games drive the DualSense's two voice-coil actuators through an audio output port of type
vibration (sceAudioOutOpen type 10, AudioOut2 port type 6), one channel per actuator. These ports
had no device, so their samples were dropped and games that rely on audio haptics instead of
scePadSetVibration had no vibration at all.

Over USB, the DualSense is also a 4-channel USB audio device whose back channels feed the actuators.
This PR plays each vibration port's samples on those channels through SDL audio.

Changes

  • src/libs/padHaptics.{h,cpp} (new): finds the DualSense's audio device by name and requires 4
    channels, opens an SDL stream at the port's rate, converts each block (mono or stereo, s16 or float,
    port volume) to [0, 0, left, right] frames and queues them with about the same ~40 ms latency as
    the regular audio path. The playback rate is nudged by up to 3% to keep that queue level when the
    port is fed slightly off real time (a port without an SDL device is paced by a sleep timer, and the
    controller's USB audio clock differs from the main output's). The device is looked up every 2 s
    while the port plays, so the controller can be plugged in or out at any time; a device that fails
    to open is skipped until it is reconnected, and the reason haptics are unavailable is logged once.
  • src/libs/audio.cpp: vibration ports use that stream instead of dropping their samples. It never
    paces the port, so the existing pacing of AudioOutOutputs and AudioOut2 is unchanged. Queueing
    to it holds Audio::m_mutex (it never waits for pacing), so sceAudioOutClose on another thread
    cannot free the stream mid-queue.
  • src/libs/controller.{h,cpp}: remembers the last scePadSetVibration values. While haptic audio
    plays, a DualSense's rumble is held at 0 and restored 250 ms after the haptics fall silent. SDL's
    PS5 driver sets the "disable audio haptics" flag whenever rumble is non-zero
    (SDL_hidapi_ps5.c), which would mute the actuators.
  • tests/PadHapticsTests.cpp, CMakeLists.txt: pad_haptics test for the sample conversion,
    device-name matching and playback-rate correction, added to kyty_tests. The device handling
    itself needs a real controller and is not covered.

Limitations and side effects

  • USB only. Over Bluetooth the DualSense has no audio device; haptics there would need an
    undocumented HID output report, which is not implemented. Over Bluetooth nothing changes (legacy
    rumble as before).
  • The controller's speaker setup must have 4 channels (Windows: Quadraphonic). With a stereo setup
    the emulator plays nothing and logs why, since the OS would otherwise mix the actuator channels
    into the controller's speaker. SDL reads the channel count when the device appears, so after
    changing the setup the controller has to be reconnected.
  • The first DualSense audio device found is used, whichever controller is active. SDL cannot map a
    gamepad to its audio device yet (libsdl-org/SDL#9197). With an Xbox pad active and a DualSense
    plugged in by USB, the DualSense gets the haptics. Likewise, rumble is held off on the active
    controller whenever it is a DualSense, even if the haptics play on a different one.
  • While haptic audio plays, a DualSense's legacy rumble is suppressed; the controller cannot do both
    at once. A game that uses both at the same time loses the legacy rumble during haptics.
  • Haptics have the same ~40-50 ms latency as the sound.
  • scePadSetVibrationMode is still a stub; not needed for this.
  • Only tested on Windows. Linux and macOS use the same SDL code, but the device names and channel
    counts there are untested.

Testing

  • Windows 11, DualSense over USB (speaker setup 4 channels, 48 kHz), tested with Astro's Playroom.
  • pad_haptics and audio_out2_port pass; kyty_emulator and launcher build without warnings
    (clang-cl, Windows).

References

  • DualSense USB audio layout (channels 3 and 4 drive the actuators): DS5Windows documentation,
    dse-haptics,
    minimal WASAPI demo. Used for
    the channel layout only; no code was taken from them.
  • SDL3 sources in 3rdparty/SDL3 for how rumble and audio haptics interact.
  • SAxense (MPL-2.0) and
    dualsense-bt-haptics (MIT) were read for the
    Bluetooth protocol only. Nothing from them is in this PR.

AI use

Research, implementation and tests were done with Claude Code at my direction.
I reviewed the code, and tested it as described above.

**@⁠Cosmo** on GitHub · 2026-09-26 02:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/843) `Cosmo:dualsense-audio-haptics` → `main` · +588 −3 · 7 files · 3 commits · merged 2026-09-26 20:37 UTC ## Summary PS5 games drive the DualSense's two voice-coil actuators through an audio output port of type vibration (`sceAudioOutOpen` type 10, AudioOut2 port type 6), one channel per actuator. These ports had no device, so their samples were dropped and games that rely on audio haptics instead of `scePadSetVibration` had no vibration at all. Over USB, the DualSense is also a 4-channel USB audio device whose back channels feed the actuators. This PR plays each vibration port's samples on those channels through SDL audio. ## Changes - `src/libs/padHaptics.{h,cpp}` (new): finds the DualSense's audio device by name and requires 4 channels, opens an SDL stream at the port's rate, converts each block (mono or stereo, s16 or float, port volume) to `[0, 0, left, right]` frames and queues them with about the same ~40 ms latency as the regular audio path. The playback rate is nudged by up to 3% to keep that queue level when the port is fed slightly off real time (a port without an SDL device is paced by a sleep timer, and the controller's USB audio clock differs from the main output's). The device is looked up every 2 s while the port plays, so the controller can be plugged in or out at any time; a device that fails to open is skipped until it is reconnected, and the reason haptics are unavailable is logged once. - `src/libs/audio.cpp`: vibration ports use that stream instead of dropping their samples. It never paces the port, so the existing pacing of `AudioOutOutputs` and AudioOut2 is unchanged. Queueing to it holds `Audio::m_mutex` (it never waits for pacing), so `sceAudioOutClose` on another thread cannot free the stream mid-queue. - `src/libs/controller.{h,cpp}`: remembers the last `scePadSetVibration` values. While haptic audio plays, a DualSense's rumble is held at 0 and restored 250 ms after the haptics fall silent. SDL's PS5 driver sets the "disable audio haptics" flag whenever rumble is non-zero (`SDL_hidapi_ps5.c`), which would mute the actuators. - `tests/PadHapticsTests.cpp`, `CMakeLists.txt`: `pad_haptics` test for the sample conversion, device-name matching and playback-rate correction, added to `kyty_tests`. The device handling itself needs a real controller and is not covered. ## Limitations and side effects - USB only. Over Bluetooth the DualSense has no audio device; haptics there would need an undocumented HID output report, which is not implemented. Over Bluetooth nothing changes (legacy rumble as before). - The controller's speaker setup must have 4 channels (Windows: Quadraphonic). With a stereo setup the emulator plays nothing and logs why, since the OS would otherwise mix the actuator channels into the controller's speaker. SDL reads the channel count when the device appears, so after changing the setup the controller has to be reconnected. - The first DualSense audio device found is used, whichever controller is active. SDL cannot map a gamepad to its audio device yet (libsdl-org/SDL#9197). With an Xbox pad active and a DualSense plugged in by USB, the DualSense gets the haptics. Likewise, rumble is held off on the active controller whenever it is a DualSense, even if the haptics play on a different one. - While haptic audio plays, a DualSense's legacy rumble is suppressed; the controller cannot do both at once. A game that uses both at the same time loses the legacy rumble during haptics. - Haptics have the same ~40-50 ms latency as the sound. - `scePadSetVibrationMode` is still a stub; not needed for this. - Only tested on Windows. Linux and macOS use the same SDL code, but the device names and channel counts there are untested. ## Testing - Windows 11, DualSense over USB (speaker setup 4 channels, 48 kHz), tested with Astro's Playroom. - `pad_haptics` and `audio_out2_port` pass; `kyty_emulator` and `launcher` build without warnings (clang-cl, Windows). ## References - DualSense USB audio layout (channels 3 and 4 drive the actuators): DS5Windows documentation, [dse-haptics](https://github.com/iranran666/dse-haptics), [minimal WASAPI demo](https://gist.github.com/Ohjurot/b0c04dfbd25fb71bc0da50947d313d1b). Used for the channel layout only; no code was taken from them. - SDL3 sources in `3rdparty/SDL3` for how rumble and audio haptics interact. - [SAxense](https://github.com/egormanga/SAxense) (MPL-2.0) and [dualsense-bt-haptics](https://github.com/awalol/dualsense-bt-haptics) (MIT) were read for the Bluetooth protocol only. Nothing from them is in this PR. ## AI use Research, implementation and tests were done with Claude Code at my direction. I reviewed the code, and tested it as described above.
Games drive the DualSense's actuators through a vibration audio port, one channel per actuator.
These ports had no device, so their samples were dropped. Over USB the DualSense is a 4-channel
audio device whose back channels feed the actuators; play the port's samples there through SDL.

The device is looked up while the port plays, so the controller can be connected at any time. The
queue keeps about the latency of the regular audio path, with the playback rate nudged by up to 3%
when the port is fed off real time.

While haptic audio plays, hold a DualSense's rumble at zero: SDL disables audio haptics whenever
rumble is non-zero.

Add pad_haptics tests for the sample conversion, device-name matching and rate correction.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:34:42 +00:00
github manually merged commit 275ef643fd into gh-pr/843/base 2026-11-26 09:34:43 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 02:38 UTC · original · edited 2026-09-26 12:43 UTC

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The change adds DualSense audio haptics with audio-device discovery, sample conversion, playback queue management, and coordination with controller rumble. Vibration-port audio now routes through the haptics module, and controller code supplies the active controller ID and delegates supported rumble requests. A new test executable covers playback, discovery, failure handling, queue limits, rumble timing, and cleanup. CTest registers the executable and includes it in the aggregate test target.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Feature

Merge Risk: 🔵 Low · up to 275ef

Switching controllers can make the previous pad vibrate again. The impact is localized, but the rumble-state fix should be made before merging.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 275ef

Vibration audio can now reach a connected controller, but the selected audio device is not tied to the active controller. Controller shutdown also does not immediately close the haptic audio stream. Exposure appears limited to local connected devices; the behavior warrants review before relying on controller ownership to contain output.

Retained concerns

  • Medium · security · inferred: Haptic samples can be routed to a name-matching DualSense audio device that is not the active gamepad, while rumble control targets the active gamepad.
  • Medium · security · inferred: Controller shutdown resets rumble state but does not terminate an already-open haptic audio stream or clear its queued samples. Output termination remains dependent on audio-port cleanup or a subsequent queue transition.
Security review details

Security Blast Radius

  • inferred — The new sink exposes guest-supplied vibration samples to a local matching playback device. No reviewed path establishes remote, cross-tenant, credential, or infrastructure exposure.

Security Findings and Attack Paths

  • inferred — When multiple matching devices are available, vibration-port samples can reach the first enumerated audio device rather than the active controller's device.
  • inferred — After controller release, queued haptic audio need not be stopped by Shutdown itself. Whether a removed device independently stops playback is not established by the reviewed source.

Trust Boundaries and Controls

  • observed — The new physical-output path is restricted to vibration ports, checks for a PS5 gamepad, checks the playback format, applies port volume, and uses only the first two guest channels for actuator output.

Resilience and Maintainability Implications

  • observed — Device rechecks and non-PS5 queue handling can close a stream during later queue activity; they do not provide immediate stream invalidation when controller ownership changes.

Hardening Proposals

  • proposed — Bind the selected audio endpoint to the active physical gamepad, and invalidate or close controller-owned haptic playback on disconnect and shutdown without waiting for another audio submission.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.94% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 63 functions across 8 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: routing audio from vibration ports to DualSense haptics.
Description check ✅ Passed The description directly explains the DualSense haptics implementation, audio routing, rumble coordination, tests, limitations, and reported validation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 7.94% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 63 functions across 8 files. (1 skipped: 1 unsupported.)


Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 02:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/843#issuecomment-5842436522) · edited 2026-09-26 12:43 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/843"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The change adds DualSense audio haptics with audio-device discovery, sample conversion, playback queue management, and coordination with controller rumble. Vibration-port audio now routes through the haptics module, and controller code supplies the active controller ID and delegates supported rumble requests. A new test executable covers playback, discovery, failure handling, queue limits, rumble timing, and cleanup. CTest registers the executable and includes it in the aggregate test target. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"275ef643fde82aeccc7edf377ed68a92a2791fc5" --> **Change:** Feature <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🔵 Low_ · up to `275ef` <!-- final_review_risk_coverage:{"sourceCommitId":"275ef643fde82aeccc7edf377ed68a92a2791fc5","coveredCommitId":"275ef643fde82aeccc7edf377ed68a92a2791fc5","kind":"reviewed"} --> Switching controllers can make the previous pad vibrate again. The impact is localized, but the rumble-state fix should be made before merging. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🟡 Moderate_ · up to `275ef` Vibration audio can now reach a connected controller, but the selected audio device is not tied to the active controller. Controller shutdown also does not immediately close the haptic audio stream. Exposure appears limited to local connected devices; the behavior warrants review before relying on controller ownership to contain output. **Retained concerns** - **Medium · security · inferred:** Haptic samples can be routed to a name-matching DualSense audio device that is not the active gamepad, while rumble control targets the active gamepad. - **Medium · security · inferred:** Controller shutdown resets rumble state but does not terminate an already-open haptic audio stream or clear its queued samples. Output termination remains dependent on audio-port cleanup or a subsequent queue transition. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The new sink exposes guest-supplied vibration samples to a local matching playback device. No reviewed path establishes remote, cross-tenant, credential, or infrastructure exposure. **Security Findings and Attack Paths** - _inferred_ — When multiple matching devices are available, vibration-port samples can reach the first enumerated audio device rather than the active controller's device. - _inferred_ — After controller release, queued haptic audio need not be stopped by Shutdown itself. Whether a removed device independently stops playback is not established by the reviewed source. **Trust Boundaries and Controls** - _observed_ — The new physical-output path is restricted to vibration ports, checks for a PS5 gamepad, checks the playback format, applies port volume, and uses only the first two guest channels for actuator output. **Resilience and Maintainability Implications** - _observed_ — Device rechecks and non-PS5 queue handling can close a stream during later queue activity; they do not provide immediate stream invalidation when controller ownership changes. **Hardening Proposals** - _proposed_ — Bind the selected audio endpoint to the active physical gamepad, and invalidate or close controller-owned haptic playback on disconnect and shutdown without waiting for another audio submission. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 7.94% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 63 functions across 8 files. (1 skipped: 1… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly and concisely summarizes the main change: routing audio from vibration ports to DualSense haptics. | | Description check | ✅ Passed | The description directly explains the DualSense haptics implementation, audio routing, rumble coordination, tests, limitations, and reported validation. | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | </details> <details> <summary>Full details: Docstring Coverage</summary> **Explanation** Docstring coverage is 7.94% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 63 functions across 8 files. (1 skipped: 1 unsupported.) </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 02:38 UTC · original
On src/libs/padHaptics.cpp line 304 (outdated):

@@ -0,0 +1,306 @@
+#include "libs/padHaptics.h"
+
+#include "common/logging/log.h"
+#include "common/threads.h"
+#include "libs/controller.h"
+
+#include <SDL3/SDL.h>
+#include <algorithm>
+#include <atomic>
+#include <cmath>
+#include <string>
+#include <vector>
+
+namespace Libs::Audio::PadHaptics {
+
+namespace {
+
+// A DualSense's USB audio channels in SDL's quad order: its speaker, then its two actuators.
+constexpr uint32_t DEVICE_CHANNELS = 4;
+constexpr uint32_t LEFT_ACTUATOR   = 2;
+constexpr uint32_t RIGHT_ACTUATOR  = 3;
+constexpr int      FRAME_BYTES     = static_cast<int>(DEVICE_CHANNELS * sizeof(float));
+
+constexpr float VOLUME_UNITY = 32768.0f;
+constexpr float S16_SCALE    = 1.0f / 32768.0f;
+
+constexpr Uint64 DEVICE_CHECK_MS = 2000;           // Hot-plug polling interval.
+constexpr float  SILENCE_LEVEL   = 1.0f / 1024.0f; // About -60 dBFS.
+// Rumble comes back this long after the haptics fall silent, not in every short pause.
+constexpr Uint64 STOP_MS = 250;
+// About what Audio::QueueSdlAudio keeps queued, so haptics and sound have similar latency.
+constexpr uint32_t LATENCY_MS = 40;
+// Playback runs up to 3% slow or fast to hold the queue near LATENCY_MS when the port is fed off
+// real time (a port without a device paces on a sleep timer; two devices have two clocks).
+constexpr float RATE_CORRECTION = 0.03f;
+
+Common::Mutex g_playing_mutex;
+int           g_playing_streams = 0;
+// Why haptics are unavailable is logged once, until they play again.
+std::atomic_bool g_logged_unavailable {false};
+
+} // namespace
+
+struct Stream {
+	uint32_t           freq          = 0;
+	SDL_AudioDeviceID  device        = 0;
+	SDL_AudioDeviceID  failed_device = 0; // Skipped until reconnected, which gives it a new ID.
+	SDL_AudioStream*   sdl           = nullptr;
+	float              ratio         = 1.0f;
+	Uint64             next_check    = 0;
+	Uint64             last_sound    = 0;
+	bool               playing       = false;
+	std::vector<float> converted;
+	std::vector<float> silence;
+};
+
+float ToControllerFrames(const void* data, uint32_t frames, uint32_t channels, bool is_float,
+                         const int* volume, float* out) {
+	const uint32_t right_channel = (channels > 1 ? 1 : 0);
+	const float    left_gain     = static_cast<float>(volume[0]) / VOLUME_UNITY;
+	const float    right_gain    = static_cast<float>(volume[right_channel]) / VOLUME_UNITY;
+
+	float peak = 0.0f;
+	for (uint32_t frame = 0; frame < frames; frame++) {
+		const size_t src_index = static_cast<size_t>(frame) * channels;
+		float        left      = 0.0f;
+		float        right     = 0.0f;
+		if (is_float) {
+			const auto* src = static_cast<const float*>(data) + src_index;
+			left            = src[0];
+			right           = src[right_channel];
+		} else {
+			const auto* src = static_cast<const int16_t*>(data) + src_index;
+			left            = static_cast<float>(src[0]) * S16_SCALE;
+			right           = static_cast<float>(src[right_channel]) * S16_SCALE;
+		}
+		left *= left_gain;
+		right *= right_gain;
+
+		float* dst = out + static_cast<size_t>(frame) * DEVICE_CHANNELS;
+		std::fill_n(dst, DEVICE_CHANNELS, 0.0f);
+		dst[LEFT_ACTUATOR]  = left;
+		dst[RIGHT_ACTUATOR] = right;
+		peak                = std::max({peak, std::fabs(left), std::fabs(right)});
+	}
+	return peak;
+}
+
+bool IsControllerName(const char* name) {
+	// Hosts decorate the name, e.g. "Speakers (DualSense Wireless Controller)" on Windows.
+	return name != nullptr && SDL_strcasestr(name, "DualSense") != nullptr;
+}
+
+float PlaybackRatio(int queued_bytes, int target_bytes) {
+	if (queued_bytes < target_bytes / 2) {
+		return 1.0f - RATE_CORRECTION;
+	}
+	if (queued_bytes > target_bytes + target_bytes / 2) {
+		return 1.0f + RATE_CORRECTION;
+	}
+	return 1.0f;
+}
+
+// The controller holds a DualSense's rumble off while any port plays.
+static void SetPlaying(Stream* stream, bool playing) {
+	if (stream->playing == playing) {
+		return;
+	}
+	stream->playing = playing;
+
+	Common::LockGuard lock(g_playing_mutex);
+	const bool        was_playing = g_playing_streams > 0;
+	g_playing_streams += (playing ? 1 : -1);
+	if (was_playing != (g_playing_streams > 0)) {
+		Controller::SetAudioHapticsPlaying(g_playing_streams > 0);
+	}
+}
+
+static bool DevicePresent(SDL_AudioDeviceID device) {
+	int                count   = 0;
+	SDL_AudioDeviceID* devices = SDL_GetAudioPlaybackDevices(&count);
+	const bool         present =
+	    devices != nullptr && std::find(devices, devices + count, device) != devices + count;
+	SDL_free(devices);
+	return present;
+}
+
+// The first DualSense with the actuators' channels, or 0.
+static SDL_AudioDeviceID FindDevice(const Stream* stream) {
+	int                count   = 0;
+	SDL_AudioDeviceID* devices = SDL_GetAudioPlaybackDevices(&count);
+	SDL_AudioDeviceID  found   = 0;
+	std::string        too_few_channels;
+	int                too_few_channels_num = 0;
+	for (int i = 0; i < count && found == 0; i++) {
+		const char* name = SDL_GetAudioDeviceName(devices[i]);
+		if (devices[i] == stream->failed_device || !IsControllerName(name)) {
+			continue;
+		}
+		SDL_AudioSpec spec {};
+		if (!SDL_GetAudioDeviceFormat(devices[i], &spec, nullptr)) {
+			continue;
+		}
+		if (spec.channels >= static_cast<int>(DEVICE_CHANNELS)) {
+			found = devices[i];
+		} else if (too_few_channels.empty()) {
+			too_few_channels     = name;
+			too_few_channels_num = spec.channels;
+		}
+	}
+	SDL_free(devices);
+
+	if (found == 0 && !g_logged_unavailable.exchange(true)) {
+		if (!too_few_channels.empty()) {
+			// A stereo device would play the actuators' channels on the controller's speaker. SDL
+			// reads the channel count when the device appears.
+			LOGF("PadHaptics: '%s' has %d channels, the actuators need %u; switch the device to a "
+			     "4-channel (quadraphonic) speaker setup, then reconnect the controller\n",
+			     too_few_channels.c_str(), too_few_channels_num, DEVICE_CHANNELS);
+		} else {
+			LOGF("PadHaptics: no DualSense audio device; haptics need the controller connected by "
+			     "USB\n");
+		}
+	}
+	return found;
+}
+
+static void CloseDevice(Stream* stream) {
+	if (stream->sdl != nullptr) {
+		SDL_DestroyAudioStream(stream->sdl);
+	}
+	stream->sdl    = nullptr;
+	stream->device = 0;
+}
+
+static void FailDevice(Stream* stream, SDL_AudioDeviceID device, const char* call) {
+	if (!g_logged_unavailable.exchange(true)) {
+		LOGF("PadHaptics: %s failed: %s\n", call, SDL_GetError());
+	}
+	CloseDevice(stream);
+	stream->failed_device = device;
+}
+
+static void OpenDevice(Stream* stream, SDL_AudioDeviceID device) {
+	SDL_AudioSpec spec {};
+	spec.freq     = static_cast<int>(stream->freq);
+	spec.format   = SDL_AUDIO_F32;
+	spec.channels = static_cast<int>(DEVICE_CHANNELS);
+
+	stream->sdl = SDL_OpenAudioDeviceStream(device, &spec, nullptr, nullptr);
+	if (stream->sdl == nullptr) {
+		FailDevice(stream, device, "SDL_OpenAudioDeviceStream");
+		return;
+	}
+	if (!SDL_ResumeAudioStreamDevice(stream->sdl)) {
+		FailDevice(stream, device, "SDL_ResumeAudioStreamDevice");
+		return;
+	}
+
+	stream->device = device;
+	stream->ratio  = 1.0f;
+	g_logged_unavailable.store(false);
+	const char* name = SDL_GetAudioDeviceName(device);
+	LOGF("PadHaptics: playing on '%s' (%u Hz)\n", name != nullptr ? name : "?", stream->freq);
+}
+
+static void CheckDevice(Stream* stream) {
+	if (stream->sdl != nullptr) {
+		if (DevicePresent(stream->device)) {
+			return;
+		}
+		LOGF("PadHaptics: the DualSense audio device is gone\n");
+		CloseDevice(stream);
+	}
+	if (stream->failed_device != 0 && !DevicePresent(stream->failed_device)) {
+		stream->failed_device = 0;
+	}
+	if (const auto device = FindDevice(stream); device != 0) {
+		OpenDevice(stream, device);
+	}
+}
+
+static bool PutConverted(Stream* stream, uint32_t frames) {
+	const int latency_bytes = static_cast<int>(stream->freq * LATENCY_MS / 1000) * FRAME_BYTES;
+	const int block_bytes   = static_cast<int>(frames) * FRAME_BYTES;
+
+	int queued = SDL_GetAudioStreamQueued(stream->sdl);
+	// A backlog after a stall is dropped rather than played late.
+	if (queued > 2 * latency_bytes) {
+		SDL_ClearAudioStream(stream->sdl);
+		queued = 0;
+	}
+	// Starting, or after an underrun: silence first, up to the target latency.
+	if (queued <= 0 && latency_bytes > block_bytes) {
+		queued = latency_bytes - block_bytes;
+		stream->silence.assign(static_cast<size_t>(queued) / sizeof(float), 0.0f);
+		if (!SDL_PutAudioStreamData(stream->sdl, stream->silence.data(), queued)) {
+			return false;
+		}
+	}
+
+	const float ratio = PlaybackRatio(queued + block_bytes, latency_bytes);
+	if (ratio != stream->ratio && SDL_SetAudioStreamFrequencyRatio(stream->sdl, ratio)) {
+		stream->ratio = ratio;
+	}
+	return SDL_PutAudioStreamData(stream->sdl, stream->converted.data(), block_bytes);
+}
+
+Stream* Open(uint32_t freq) {
+	if (freq == 0) {
+		return nullptr;
+	}
+	if (!SDL_InitSubSystem(SDL_INIT_AUDIO)) {
+		LOGF("PadHaptics: SDL audio init failed: %s\n", SDL_GetError());
+		return nullptr;
+	}
+
+	auto* stream = new Stream;
+	stream->freq = freq;
+	return stream;
+}
+
+void Close(Stream* stream) {
+	if (stream == nullptr) {
+		return;
+	}
+
+	SetPlaying(stream, false);
+	CloseDevice(stream);
+	delete stream;
+	SDL_QuitSubSystem(SDL_INIT_AUDIO);
+}
+
+void Queue(Stream* stream, const void* data, uint32_t frames, uint32_t channels, bool is_float,
+           const int* volume) {
+	if (stream == nullptr || data == nullptr || volume == nullptr || frames == 0 || channels == 0) {
+		return;
+	}
+
+	const Uint64 now = SDL_GetTicks();
+	if (now >= stream->next_check) {
+		stream->next_check = now + DEVICE_CHECK_MS;
+		CheckDevice(stream);
+	}
+	if (stream->sdl == nullptr) {
+		SetPlaying(stream, false);
+		return;
+	}
+
+	stream->converted.resize(static_cast<size_t>(frames) * DEVICE_CHANNELS);
+	const float peak =
+	    ToControllerFrames(data, frames, channels, is_float, volume, stream->converted.data());
+	if (peak > SILENCE_LEVEL) {
+		stream->last_sound = now;
+		SetPlaying(stream, true);
+	} else if (now - stream->last_sound >= STOP_MS) {
+		SetPlaying(stream, false);
+	}
+
+	if (!PutConverted(stream, frames)) {
+		SetPlaying(stream, false);
+		FailDevice(stream, stream->device, "SDL_PutAudioStreamData");
+	}
+}

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '100,126p;263,306p' src/libs/padHaptics.cpp
sed -n '530,610p' src/libs/audio.cpp
rg -n 'AudioOutOutputs|AudioOutOutput|AudioOutClose|SetPlaying|SetAudioHapticsPlaying' src/libs/audio.cpp src/libs/padHaptics.cpp src/libs/controller.cpp

Repository: KytyPS5/KytyPS5

Length of output: 6761


🏁 Script executed:

#!/bin/bash
printf '%s\n' '--- audio lifecycle and output entrypoints ---'
sed -n '390,475p;500,575p;810,970p' src/libs/audio.cpp
printf '%s\n' '--- vibration and haptics references ---'
rg -n -C 5 'AUDIO_OUT_PORT_TYPE_VIBRATION|PadHaptics::(Open|Close|Queue)|haptics|AudioOutOpen|AudioOutClose|AudioOutOutput' src/libs/audio.cpp
printf '%s\n' '--- controller rumble state ---'
sed -n '530,590p;690,730p' src/libs/controller.cpp
printf '%s\n' '--- haptics initialization and constants ---'
sed -n '1,140p;240,275p' src/libs/padHaptics.cpp

Repository: KytyPS5/KytyPS5

Length of output: 24868


🏁 Script executed:

sed -n '390,475p;500,575p;810,970p' src/libs/audio.cpp; rg -n -C 5 'AUDIO_OUT_PORT_TYPE_VIBRATION|PadHaptics::(Open|Close|Queue)|haptics|AudioOutOpen|AudioOutClose|AudioOutOutput' src/libs/audio.cpp; sed -n '530,590p;690,730p' src/libs/controller.cpp; sed -n '1,140p;240,275p' src/libs/padHaptics.cpp

Repository: KytyPS5/KytyPS5

Length of output: 24703


Clear idle haptics when output stops.

PadHaptics::Queue checks STOP_MS only when AudioOutOutputs or AudioOutOutput submits another block. An open vibration port does not receive periodic queue calls, and AudioOutClose is the only separate path that calls PadHaptics::Close. Therefore, a non-silent block can leave stream->playing set until the port closes. Controller::ApplyRumble then keeps both rumble motors at zero while m_audio_haptics remains true. Add an independently synchronized idle timeout for each Stream, or an equivalent port-stop transition, that calls SetPlaying(stream, false) after 250 ms without output.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 02:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/843#discussion_r4109906835) On `src/libs/padHaptics.cpp` line 304 (outdated): ```diff @@ -0,0 +1,306 @@ +#include "libs/padHaptics.h" + +#include "common/logging/log.h" +#include "common/threads.h" +#include "libs/controller.h" + +#include <SDL3/SDL.h> +#include <algorithm> +#include <atomic> +#include <cmath> +#include <string> +#include <vector> + +namespace Libs::Audio::PadHaptics { + +namespace { + +// A DualSense's USB audio channels in SDL's quad order: its speaker, then its two actuators. +constexpr uint32_t DEVICE_CHANNELS = 4; +constexpr uint32_t LEFT_ACTUATOR = 2; +constexpr uint32_t RIGHT_ACTUATOR = 3; +constexpr int FRAME_BYTES = static_cast<int>(DEVICE_CHANNELS * sizeof(float)); + +constexpr float VOLUME_UNITY = 32768.0f; +constexpr float S16_SCALE = 1.0f / 32768.0f; + +constexpr Uint64 DEVICE_CHECK_MS = 2000; // Hot-plug polling interval. +constexpr float SILENCE_LEVEL = 1.0f / 1024.0f; // About -60 dBFS. +// Rumble comes back this long after the haptics fall silent, not in every short pause. +constexpr Uint64 STOP_MS = 250; +// About what Audio::QueueSdlAudio keeps queued, so haptics and sound have similar latency. +constexpr uint32_t LATENCY_MS = 40; +// Playback runs up to 3% slow or fast to hold the queue near LATENCY_MS when the port is fed off +// real time (a port without a device paces on a sleep timer; two devices have two clocks). +constexpr float RATE_CORRECTION = 0.03f; + +Common::Mutex g_playing_mutex; +int g_playing_streams = 0; +// Why haptics are unavailable is logged once, until they play again. +std::atomic_bool g_logged_unavailable {false}; + +} // namespace + +struct Stream { + uint32_t freq = 0; + SDL_AudioDeviceID device = 0; + SDL_AudioDeviceID failed_device = 0; // Skipped until reconnected, which gives it a new ID. + SDL_AudioStream* sdl = nullptr; + float ratio = 1.0f; + Uint64 next_check = 0; + Uint64 last_sound = 0; + bool playing = false; + std::vector<float> converted; + std::vector<float> silence; +}; + +float ToControllerFrames(const void* data, uint32_t frames, uint32_t channels, bool is_float, + const int* volume, float* out) { + const uint32_t right_channel = (channels > 1 ? 1 : 0); + const float left_gain = static_cast<float>(volume[0]) / VOLUME_UNITY; + const float right_gain = static_cast<float>(volume[right_channel]) / VOLUME_UNITY; + + float peak = 0.0f; + for (uint32_t frame = 0; frame < frames; frame++) { + const size_t src_index = static_cast<size_t>(frame) * channels; + float left = 0.0f; + float right = 0.0f; + if (is_float) { + const auto* src = static_cast<const float*>(data) + src_index; + left = src[0]; + right = src[right_channel]; + } else { + const auto* src = static_cast<const int16_t*>(data) + src_index; + left = static_cast<float>(src[0]) * S16_SCALE; + right = static_cast<float>(src[right_channel]) * S16_SCALE; + } + left *= left_gain; + right *= right_gain; + + float* dst = out + static_cast<size_t>(frame) * DEVICE_CHANNELS; + std::fill_n(dst, DEVICE_CHANNELS, 0.0f); + dst[LEFT_ACTUATOR] = left; + dst[RIGHT_ACTUATOR] = right; + peak = std::max({peak, std::fabs(left), std::fabs(right)}); + } + return peak; +} + +bool IsControllerName(const char* name) { + // Hosts decorate the name, e.g. "Speakers (DualSense Wireless Controller)" on Windows. + return name != nullptr && SDL_strcasestr(name, "DualSense") != nullptr; +} + +float PlaybackRatio(int queued_bytes, int target_bytes) { + if (queued_bytes < target_bytes / 2) { + return 1.0f - RATE_CORRECTION; + } + if (queued_bytes > target_bytes + target_bytes / 2) { + return 1.0f + RATE_CORRECTION; + } + return 1.0f; +} + +// The controller holds a DualSense's rumble off while any port plays. +static void SetPlaying(Stream* stream, bool playing) { + if (stream->playing == playing) { + return; + } + stream->playing = playing; + + Common::LockGuard lock(g_playing_mutex); + const bool was_playing = g_playing_streams > 0; + g_playing_streams += (playing ? 1 : -1); + if (was_playing != (g_playing_streams > 0)) { + Controller::SetAudioHapticsPlaying(g_playing_streams > 0); + } +} + +static bool DevicePresent(SDL_AudioDeviceID device) { + int count = 0; + SDL_AudioDeviceID* devices = SDL_GetAudioPlaybackDevices(&count); + const bool present = + devices != nullptr && std::find(devices, devices + count, device) != devices + count; + SDL_free(devices); + return present; +} + +// The first DualSense with the actuators' channels, or 0. +static SDL_AudioDeviceID FindDevice(const Stream* stream) { + int count = 0; + SDL_AudioDeviceID* devices = SDL_GetAudioPlaybackDevices(&count); + SDL_AudioDeviceID found = 0; + std::string too_few_channels; + int too_few_channels_num = 0; + for (int i = 0; i < count && found == 0; i++) { + const char* name = SDL_GetAudioDeviceName(devices[i]); + if (devices[i] == stream->failed_device || !IsControllerName(name)) { + continue; + } + SDL_AudioSpec spec {}; + if (!SDL_GetAudioDeviceFormat(devices[i], &spec, nullptr)) { + continue; + } + if (spec.channels >= static_cast<int>(DEVICE_CHANNELS)) { + found = devices[i]; + } else if (too_few_channels.empty()) { + too_few_channels = name; + too_few_channels_num = spec.channels; + } + } + SDL_free(devices); + + if (found == 0 && !g_logged_unavailable.exchange(true)) { + if (!too_few_channels.empty()) { + // A stereo device would play the actuators' channels on the controller's speaker. SDL + // reads the channel count when the device appears. + LOGF("PadHaptics: '%s' has %d channels, the actuators need %u; switch the device to a " + "4-channel (quadraphonic) speaker setup, then reconnect the controller\n", + too_few_channels.c_str(), too_few_channels_num, DEVICE_CHANNELS); + } else { + LOGF("PadHaptics: no DualSense audio device; haptics need the controller connected by " + "USB\n"); + } + } + return found; +} + +static void CloseDevice(Stream* stream) { + if (stream->sdl != nullptr) { + SDL_DestroyAudioStream(stream->sdl); + } + stream->sdl = nullptr; + stream->device = 0; +} + +static void FailDevice(Stream* stream, SDL_AudioDeviceID device, const char* call) { + if (!g_logged_unavailable.exchange(true)) { + LOGF("PadHaptics: %s failed: %s\n", call, SDL_GetError()); + } + CloseDevice(stream); + stream->failed_device = device; +} + +static void OpenDevice(Stream* stream, SDL_AudioDeviceID device) { + SDL_AudioSpec spec {}; + spec.freq = static_cast<int>(stream->freq); + spec.format = SDL_AUDIO_F32; + spec.channels = static_cast<int>(DEVICE_CHANNELS); + + stream->sdl = SDL_OpenAudioDeviceStream(device, &spec, nullptr, nullptr); + if (stream->sdl == nullptr) { + FailDevice(stream, device, "SDL_OpenAudioDeviceStream"); + return; + } + if (!SDL_ResumeAudioStreamDevice(stream->sdl)) { + FailDevice(stream, device, "SDL_ResumeAudioStreamDevice"); + return; + } + + stream->device = device; + stream->ratio = 1.0f; + g_logged_unavailable.store(false); + const char* name = SDL_GetAudioDeviceName(device); + LOGF("PadHaptics: playing on '%s' (%u Hz)\n", name != nullptr ? name : "?", stream->freq); +} + +static void CheckDevice(Stream* stream) { + if (stream->sdl != nullptr) { + if (DevicePresent(stream->device)) { + return; + } + LOGF("PadHaptics: the DualSense audio device is gone\n"); + CloseDevice(stream); + } + if (stream->failed_device != 0 && !DevicePresent(stream->failed_device)) { + stream->failed_device = 0; + } + if (const auto device = FindDevice(stream); device != 0) { + OpenDevice(stream, device); + } +} + +static bool PutConverted(Stream* stream, uint32_t frames) { + const int latency_bytes = static_cast<int>(stream->freq * LATENCY_MS / 1000) * FRAME_BYTES; + const int block_bytes = static_cast<int>(frames) * FRAME_BYTES; + + int queued = SDL_GetAudioStreamQueued(stream->sdl); + // A backlog after a stall is dropped rather than played late. + if (queued > 2 * latency_bytes) { + SDL_ClearAudioStream(stream->sdl); + queued = 0; + } + // Starting, or after an underrun: silence first, up to the target latency. + if (queued <= 0 && latency_bytes > block_bytes) { + queued = latency_bytes - block_bytes; + stream->silence.assign(static_cast<size_t>(queued) / sizeof(float), 0.0f); + if (!SDL_PutAudioStreamData(stream->sdl, stream->silence.data(), queued)) { + return false; + } + } + + const float ratio = PlaybackRatio(queued + block_bytes, latency_bytes); + if (ratio != stream->ratio && SDL_SetAudioStreamFrequencyRatio(stream->sdl, ratio)) { + stream->ratio = ratio; + } + return SDL_PutAudioStreamData(stream->sdl, stream->converted.data(), block_bytes); +} + +Stream* Open(uint32_t freq) { + if (freq == 0) { + return nullptr; + } + if (!SDL_InitSubSystem(SDL_INIT_AUDIO)) { + LOGF("PadHaptics: SDL audio init failed: %s\n", SDL_GetError()); + return nullptr; + } + + auto* stream = new Stream; + stream->freq = freq; + return stream; +} + +void Close(Stream* stream) { + if (stream == nullptr) { + return; + } + + SetPlaying(stream, false); + CloseDevice(stream); + delete stream; + SDL_QuitSubSystem(SDL_INIT_AUDIO); +} + +void Queue(Stream* stream, const void* data, uint32_t frames, uint32_t channels, bool is_float, + const int* volume) { + if (stream == nullptr || data == nullptr || volume == nullptr || frames == 0 || channels == 0) { + return; + } + + const Uint64 now = SDL_GetTicks(); + if (now >= stream->next_check) { + stream->next_check = now + DEVICE_CHECK_MS; + CheckDevice(stream); + } + if (stream->sdl == nullptr) { + SetPlaying(stream, false); + return; + } + + stream->converted.resize(static_cast<size_t>(frames) * DEVICE_CHANNELS); + const float peak = + ToControllerFrames(data, frames, channels, is_float, volume, stream->converted.data()); + if (peak > SILENCE_LEVEL) { + stream->last_sound = now; + SetPlaying(stream, true); + } else if (now - stream->last_sound >= STOP_MS) { + SetPlaying(stream, false); + } + + if (!PutConverted(stream, frames)) { + SetPlaying(stream, false); + FailDevice(stream, stream->device, "SDL_PutAudioStreamData"); + } +} ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '100,126p;263,306p' src/libs/padHaptics.cpp sed -n '530,610p' src/libs/audio.cpp rg -n 'AudioOutOutputs|AudioOutOutput|AudioOutClose|SetPlaying|SetAudioHapticsPlaying' src/libs/audio.cpp src/libs/padHaptics.cpp src/libs/controller.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 6761 --- 🏁 Script executed: ```bash #!/bin/bash printf '%s\n' '--- audio lifecycle and output entrypoints ---' sed -n '390,475p;500,575p;810,970p' src/libs/audio.cpp printf '%s\n' '--- vibration and haptics references ---' rg -n -C 5 'AUDIO_OUT_PORT_TYPE_VIBRATION|PadHaptics::(Open|Close|Queue)|haptics|AudioOutOpen|AudioOutClose|AudioOutOutput' src/libs/audio.cpp printf '%s\n' '--- controller rumble state ---' sed -n '530,590p;690,730p' src/libs/controller.cpp printf '%s\n' '--- haptics initialization and constants ---' sed -n '1,140p;240,275p' src/libs/padHaptics.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 24868 --- 🏁 Script executed: ```bash sed -n '390,475p;500,575p;810,970p' src/libs/audio.cpp; rg -n -C 5 'AUDIO_OUT_PORT_TYPE_VIBRATION|PadHaptics::(Open|Close|Queue)|haptics|AudioOutOpen|AudioOutClose|AudioOutOutput' src/libs/audio.cpp; sed -n '530,590p;690,730p' src/libs/controller.cpp; sed -n '1,140p;240,275p' src/libs/padHaptics.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 24703 --- </details> **Clear idle haptics when output stops.** `PadHaptics::Queue` checks `STOP_MS` only when `AudioOutOutputs` or `AudioOutOutput` submits another block. An open vibration port does not receive periodic queue calls, and `AudioOutClose` is the only separate path that calls `PadHaptics::Close`. Therefore, a non-silent block can leave `stream->playing` set until the port closes. `Controller::ApplyRumble` then keeps both rumble motors at zero while `m_audio_haptics` remains true. Add an independently synchronized idle timeout for each `Stream`, or an equivalent port-stop transition, that calls `SetPlaying(stream, false)` after 250 ms without output. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:70e5494ccd8f1ac997eb2505 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 02:38 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: e08d46c0-e4ae-4e8a-8298-4ef7eaef8289

📥 Commits

Reviewing files that changed from the base of the PR and between fd2e15ee73 and d007592878.

📒 Files selected for processing (7)
  • CMakeLists.txt
  • src/libs/audio.cpp
  • src/libs/controller.cpp
  • src/libs/controller.h
  • src/libs/padHaptics.cpp
  • src/libs/padHaptics.h
  • tests/PadHapticsTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 02:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/843#pullrequestreview-5324237466) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `e08d46c0-e4ae-4e8a-8298-4ef7eaef8289` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between fd2e15ee737ea9a671619246129bc2aae7e0bfda and d007592878d6f4ba275ba8521f231e61944967f2. </details> <details> <summary>📒 Files selected for processing (7)</summary> * `CMakeLists.txt` * `src/libs/audio.cpp` * `src/libs/controller.cpp` * `src/libs/controller.h` * `src/libs/padHaptics.cpp` * `src/libs/padHaptics.h` * `tests/PadHapticsTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠Nmzik on GitHub · 2026-09-26 12:36 UTC · original

@⁠Cosmo please retest. Implementation is simplified

**@⁠Nmzik** on GitHub · 2026-09-26 12:36 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/843#issuecomment-5846323914) @⁠Cosmo please retest. Implementation is simplified
@ -0,0 +48,4 @@
g_large_motor = g_small_motor = 0;
g_rumble_until = 0;
}
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 12:43 UTC · original

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Stop the old controller's rumble when you switch controllers.

SelectController sets g_haptics_until = 0 and then calls ApplyRumble() for the old g_controller. It does not clear g_rumble_until first. If the old pad had a rumble in progress, muted is false, and ApplyRumble() sends the old g_large_motor/g_small_motor values again for the remaining time. This can be up to about 65 s.

Here is how it happens:

  1. The game sets rumble on pad A.
  2. Haptic audio then mutes that rumble.
  3. The active controller changes to pad B.
  4. Pad A starts vibrating again, even though the game now uses pad B.

Shutdown() does not have this problem, because it sets g_rumble_until = 0 before it calls SelectController(-1).

🐛 Proposed fix
 	if (g_controller != controller) {
-		g_haptics_until = 0;
+		g_haptics_until = 0;
+		g_rumble_until  = 0;
 		ApplyRumble();
 		g_controller  = controller;
 		g_large_motor = g_small_motor = 0;
-		g_rumble_until                = 0;
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

void SelectController(int controller) {
	if (g_controller != controller) {
		g_haptics_until = 0;
		g_rumble_until  = 0;
		ApplyRumble();
		g_controller  = controller;
		g_large_motor = g_small_motor = 0;
	}
}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 12:43 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/843#discussion_r4111400244) _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **Stop the old controller's rumble when you switch controllers.** `SelectController` sets `g_haptics_until = 0` and then calls `ApplyRumble()` for the old `g_controller`. It does not clear `g_rumble_until` first. If the old pad had a rumble in progress, `muted` is false, and `ApplyRumble()` sends the old `g_large_motor`/`g_small_motor` values again for the remaining time. This can be up to about 65 s. Here is how it happens: 1. The game sets rumble on pad A. 2. Haptic audio then mutes that rumble. 3. The active controller changes to pad B. 4. Pad A starts vibrating again, even though the game now uses pad B. `Shutdown()` does not have this problem, because it sets `g_rumble_until = 0` before it calls `SelectController(-1)`. <details> <summary>🐛 Proposed fix</summary> ```diff if (g_controller != controller) { - g_haptics_until = 0; + g_haptics_until = 0; + g_rumble_until = 0; ApplyRumble(); g_controller = controller; g_large_motor = g_small_motor = 0; - g_rumble_until = 0; } ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion void SelectController(int controller) { if (g_controller != controller) { g_haptics_until = 0; g_rumble_until = 0; ApplyRumble(); g_controller = controller; g_large_motor = g_small_motor = 0; } } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:8f149806c6a1796d49dc934b --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 12:43 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 8a3aa63f-d166-440c-95ef-259640269f27

📥 Commits

Reviewing files that changed from the base of the PR and between d007592878 and 275ef643fd.

📒 Files selected for processing (7)
  • CMakeLists.txt
  • src/libs/audio.cpp
  • src/libs/controller.cpp
  • src/libs/controller.h
  • src/libs/dualSenseHaptics.cpp
  • src/libs/dualSenseHaptics.h
  • tests/PadHapticsTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 12:43 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/843#pullrequestreview-5325940733) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `8a3aa63f-d166-440c-95ef-259640269f27` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between d007592878d6f4ba275ba8521f231e61944967f2 and 275ef643fde82aeccc7edf377ed68a92a2791fc5. </details> <details> <summary>📒 Files selected for processing (7)</summary> * `CMakeLists.txt` * `src/libs/audio.cpp` * `src/libs/controller.cpp` * `src/libs/controller.h` * `src/libs/dualSenseHaptics.cpp` * `src/libs/dualSenseHaptics.h` * `tests/PadHapticsTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠Cosmo on GitHub · 2026-09-26 20:36 UTC · original

@⁠Cosmo please retest. Implementation is simplified

thanks and done -- works great!

**@⁠Cosmo** on GitHub · 2026-09-26 20:36 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/843#issuecomment-5849672500) > @⁠Cosmo please retest. Implementation is simplified thanks and done -- works great!
Author
Owner

@⁠Rool-IO on GitHub · 2026-09-27 00:07 UTC · original

If I may, the Controller Speaker FX are still missing

**@⁠Rool-IO** on GitHub · 2026-09-27 00:07 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/843#issuecomment-5851138707) If I may, the Controller Speaker FX are still missing
Author
Owner

@⁠Cosmo on GitHub · 2026-09-27 07:32 UTC · original

Exactly! Thanks for pointing it out.
The DualSense makes sound in two ways. This PR drives the haptic actuators, which are voice coils, so you can hear them a little too (noticeable in Astro's Playroom for example).
The controller speaker is separate: Games send it their own audio stream, and it needs an extra command before it plays anything. That's not in this PR - I'm adding it in a follow-up once finished testing.

**@⁠Cosmo** on GitHub · 2026-09-27 07:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/843#issuecomment-5853835648) Exactly! Thanks for pointing it out. The DualSense makes sound in two ways. This PR drives the haptic actuators, which are voice coils, so you can hear them a little too (noticeable in Astro's Playroom for example). The controller speaker is separate: Games send it their own audio stream, and it needs an extra command before it plays anything. That's not in this PR - I'm adding it in a follow-up once finished testing.
Author
Owner

@⁠Rool-IO on GitHub · 2026-09-27 09:01 UTC · original

Felt like mentioning it since Haptics & Speaker FX are always together in Astro (be it playroom or the full game).
Looking forward to this.

**@⁠Rool-IO** on GitHub · 2026-09-27 09:01 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/843#issuecomment-5854452485) Felt like mentioning it since Haptics & Speaker FX are always together in Astro (be it playroom or the full game). Looking forward to this.
This discussion has been locked. Commenting is limited to contributors.
No description provided.