fix(input): stop controller rumble when the game that started it is gone (#2614)

* fix(input): stop controller rumble when the game that started it is gone

A crashed game never sends the stop for a held rumble, so the keepalive re-armed it every 1.5 s until the session ended. A held effect now stops on the next keepalive once the process that sent it or the Steam game it started in has exited. The fake controller also stops its rumble when it's closed or the playing effect is erased, like the kernel does.

* test: read the test's own pid from /proc/self

* fix(input): track who plays rumble on each slot, check the game when a hold starts

The process that plays an effect now owns it, and only the handle currently playing on a slot sends the stop when it closes or erases its effect. A held effect records whether a game is running when it starts, and keeps checking that its sender still exists even when its start time couldn't be read.

* fix(input): only cache a running game, not its absence

A new hold claimed right after a no-game result reused it, so a game that started within the cache window was never watched.

* fix(input): treat a vanished sender of our own user as gone

Guest processes run as the app's user, so the app can always see them in /proc. If one is missing at the first lookup it already exited; only senders of another user (root-spawned guests) are left unchecked.

* fix(input): a stop only ends rumble the same process started

The fake controller's playing-handle tracking is per process, so another process closing or erasing its older effect still sent a slot-wide stop. The app now ignores a stop whose sender isn't the one behind the slot's current effect; stops from an unknown sender work as before.

---------

Co-authored-by: Tapuuk <177422350+Tapuuk@users.noreply.github.com>
This commit is contained in:
TapuukandTapuuk authored and GitHub committed 2026-11-14 23:56:08 -05:00
1 parent 6f7d7f827f
commit fdf3d98c36
4 files changed
+407 -20

No files matched your search

+37 -13
View File
@@ -157,6 +157,8 @@ struct FakeController {
bool closed = false;
bool needs_keyframe = true;
bool mouse = false;
int playing_ff = -1;
pid_t owner = getpid();
~FakeController() {
if (ring) munmap(ring, mapping_size);
@@ -411,22 +413,49 @@ __attribute__((visibility("hidden"))) static void send_ff_effect(const struct ff
send_vibration(effect.u.periodic.magnitude, effect.u.periodic.magnitude, duration, slot);
}
static std::unordered_map<int, const FakeController *> &ff_players() {
static auto *players = new std::unordered_map<int, const FakeController *>();
return *players;
}
__attribute__((visibility("hidden"))) static void ff_played(FakeController &controller, int id) {
controller.playing_ff = id;
controller.owner = getpid();
ff_players()[controller.slot] = &controller;
}
__attribute__((visibility("hidden"))) static bool ff_release(FakeController &controller) {
auto player = ff_players().find(controller.slot);
bool current = player != ff_players().end() && player->second == &controller;
if (current) ff_players().erase(player);
controller.playing_ff = -1;
return current;
}
__attribute__((visibility("hidden"))) static void
check_ff_event(const struct input_event *ev, uint16_t slot) {
check_ff_event(const struct input_event *ev, FakeController &controller) {
if (ev->type != EV_FF)
return;
uint16_t slot = static_cast<uint16_t>(controller.slot);
int id = ev->code;
if (ev->value > 0) {
auto it = ff_effects().find(id);
if (it == ff_effects().end())
return;
send_ff_effect(it->second, slot);
ff_played(controller, id);
} else {
send_vibration(0, 0, 0, slot);
ff_release(controller);
}
}
__attribute__((visibility("hidden"))) static void stop_ff(FakeController &controller) {
bool playing = controller.playing_ff >= 0 && controller.owner == getpid();
if (ff_release(controller) && playing) send_vibration(0, 0, 0, static_cast<uint16_t>(controller.slot));
}
__attribute__((visibility("hidden"))) char *
from_real_to_fake_path(const char *pathname) {
const char *event = strrchr(pathname, '/') + 1;
@@ -3657,10 +3686,12 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
effect->id = next_ff_id++;
ff_effects()[effect->id] = *effect;
send_ff_effect(*effect, static_cast<uint16_t>(event_number));
ff_played(*controller->second, effect->id);
return 0;
} else if (type == 0x45 && number == 0x81) {
int id = (intptr_t)argp;
ff_effects().erase(id);
if (controller->second->playing_ff == id) stop_ff(*controller->second);
return 0;
} else if (type == 0x45 && number == 0x84) {
int max_effects = 16;
@@ -3740,6 +3771,7 @@ EXPORT int close(int fd) {
if (controller != controller_map().end()) {
Logger::log("Removing controller, fd %d event %s\n", controller->first,
controller->second->event ? controller->second->event : "(unknown)");
stop_ff(*controller->second);
controller->second->closed = true;
controller_map().erase(fd);
}
@@ -3937,12 +3969,8 @@ EXPORT ssize_t write(int fd, const void *buf, size_t count) {
return -1;
}
const struct input_event *ev = nullptr;
uint16_t slot = static_cast<uint16_t>(controller->second->slot);
if (count == sizeof(struct input_event)) {
ev = static_cast<const struct input_event *>(buf);
check_ff_event(ev, slot);
}
if (count == sizeof(struct input_event))
check_ff_event(static_cast<const struct input_event *>(buf), *controller->second);
return static_cast<ssize_t>(count);
}
@@ -3982,14 +4010,10 @@ EXPORT ssize_t writev(int fd, const struct iovec *iov, int iovcnt) {
return -1;
}
uint16_t slot = static_cast<uint16_t>(controller->second->slot);
ssize_t total = 0;
for (int i = 0; i < iovcnt; i++) {
if (iov[i].iov_len == sizeof(struct input_event)) {
const struct input_event *ev =
static_cast<const struct input_event *>(iov[i].iov_base);
check_ff_event(ev, slot);
}
if (iov[i].iov_len == sizeof(struct input_event))
check_ff_event(static_cast<const struct input_event *>(iov[i].iov_base), *controller->second);
total += static_cast<ssize_t>(iov[i].iov_len);
}
return total;
@@ -19,6 +19,7 @@ import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.JoyCon
import com.droiddeck.launcher.input.PadBridge
import java.io.DataInputStream
import java.io.File
import kotlin.math.max
class RumbleComponent : SessionPart() {
@@ -39,6 +40,10 @@ class RumbleComponent : SessionPart() {
internal var controllerMotors: (Int) -> Motors? = ::lookupController
internal var motorLooper: Looper? = null
internal var processStart: (Int) -> String? = ::readProcessStart
internal var gameRunning: () -> Boolean = { SteamGameProcess.running() }
private var gameCheckedAt = Long.MIN_VALUE
private var gameLastSeen = false
@Synchronized private fun refreshEnabled() {
enabled = app()?.let { ControllerPrefs.rumbleEnabled(it) } == true
@@ -66,7 +71,9 @@ class RumbleComponent : SessionPart() {
try {
val bytes = ByteArray(8)
DataInputStream(client.inputStream).readFully(bytes)
buzz(u16(bytes, 0), u16(bytes, 2), u16(bytes, 4), u16(bytes, 6))
val peer = runCatching { client.peerCredentials }.getOrNull()
buzz(u16(bytes, 0), u16(bytes, 2), u16(bytes, 4), u16(bytes, 6), peer?.pid ?: 0,
peer?.uid == android.os.Process.myUid())
} catch (e: Exception) {
} finally {
try { client.close() } catch (e: Exception) { }
@@ -94,7 +101,9 @@ class RumbleComponent : SessionPart() {
private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) {
private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) = buzz(strong, weak, ms, slot, 0, false)
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int, sender: Int, ownUser: Boolean) {
if (!enabled || quiet) return
val target = target(slot)
val previous = playing[slot]
@@ -105,10 +114,19 @@ class RumbleComponent : SessionPart() {
target?.let { Log.i(TAG, "rumble: slot $slot playing on ${it.name}") }
}
if (target == null) return
if ((strong == 0 && weak == 0) || ms == 0) { target.cancel(); forget(slot); return }
if ((strong == 0 && weak == 0) || ms == 0) {
val from = effects[slot]?.from ?: 0
if (sender > 0 && from > 0 && from != sender) return
target.cancel()
forget(slot)
return
}
val handler = handler ?: return
val effect = effects.getOrPut(slot) { Effect(slot) }
val held = effect.hold
effect.want(strong, weak, ms)
effect.from = sender
if (effect.hold && (!held || effect.owner != sender)) effect.claim(sender, ownUser)
val now = SystemClock.uptimeMillis()
if (effect.playing(now)) return
handler.removeCallbacks(effect)
@@ -116,19 +134,37 @@ class RumbleComponent : SessionPart() {
if (wait > 0) handler.postDelayed(effect, wait) else play(effect)
}
@Synchronized private fun play(effect: Effect) {
@Synchronized private fun play(effect: Effect, keepalive: Boolean = false) {
val target = playing[effect.slot]
if (target == null || effects[effect.slot] !== effect) return
if (keepalive && effect.hold && effect.armed) effect.orphaned()?.let { why ->
Log.i(TAG, "rumble: slot ${effect.slot} stopped, $why")
target.cancel()
forget(effect.slot)
return
}
val duration = if (effect.hold) HOLD_EFFECT_MS else effect.ms.toLong().coerceIn(1L, 5000L)
try {
target.play(effect.strong, effect.weak, duration)
effect.played(SystemClock.uptimeMillis(), duration)
if (effect.hold) handler?.postDelayed(effect, KEEPALIVE_MS)
if (effect.hold) {
effect.armed = true
handler?.postDelayed(effect, KEEPALIVE_MS)
}
} catch (e: Exception) {
Log.w(TAG, "rumble: ${target.name}: $e")
}
}
private fun gameRecently(): Boolean {
val now = SystemClock.uptimeMillis()
if (!gameLastSeen || now - gameCheckedAt >= GAME_CHECK_MS) {
gameLastSeen = gameRunning()
gameCheckedAt = now
}
return gameLastSeen
}
private fun forget(slot: Int) {
effects.remove(slot)?.let { handler?.removeCallbacks(it) }
}
@@ -170,8 +206,32 @@ class RumbleComponent : SessionPart() {
private var playedWeak = 0
private var playedMs = 0
private var until = 0L
var owner = 0
var from = 0
private var ownerSeen = false
private var ownerStart: String? = null
private var duringGame = false
var armed = false
val hold get() = ms == HOLD_MS
fun claim(sender: Int, ownUser: Boolean) {
owner = sender
val start = if (sender > 0) processStart(sender) else null
ownerSeen = sender > 0 && (start != null || ownUser)
ownerStart = start?.takeIf { it != UNKNOWN_START }
duringGame = gameRecently()
armed = false
}
fun orphaned(): String? {
if (ownerSeen) {
val start = processStart(owner)
if (start == null || (ownerStart != null && start != UNKNOWN_START && start != ownerStart))
return "process $owner that started it is gone"
}
return if (duringGame && !gameRunning()) "the game it started in has exited" else null
}
fun want(strong: Int, weak: Int, ms: Int) { this.strong = strong; this.weak = weak; this.ms = ms }
fun playing(now: Long) = playedMs != 0 && playedStrong == strong && playedWeak == weak && playedMs == ms &&
@@ -185,7 +245,7 @@ class RumbleComponent : SessionPart() {
until = now + duration
}
override fun run() = play(this)
override fun run() = play(this, keepalive = true)
}
internal interface Motors {
@@ -256,6 +316,7 @@ class RumbleComponent : SessionPart() {
const val HOLD_MS = 0xFFFF
const val HOLD_EFFECT_MS = 2000L
const val KEEPALIVE_MS = 1500L
const val GAME_CHECK_MS = 1000L
private fun oneShot(vibrator: Vibrator, strength: Int, ms: Long): VibrationEffect {
val amplitude = if (vibrator.hasAmplitudeControl()) (strength * 255L / 65535L).toInt().coerceIn(1, 255)
@@ -263,6 +324,13 @@ class RumbleComponent : SessionPart() {
return VibrationEffect.createOneShot(ms, amplitude)
}
const val UNKNOWN_START = "?"
internal fun readProcessStart(pid: Int): String? = runCatching {
val stat = File("/proc/$pid/stat").readText()
stat.substring(stat.lastIndexOf(')') + 2).split(' ')[19]
}.getOrElse { if (File("/proc/$pid").exists()) UNKNOWN_START else null }
private fun lookupController(id: Int): Motors? {
val device = InputDevice.getDevice(id) ?: return null
val name = "\"${device.name}\""
@@ -36,7 +36,12 @@ class RumbleComponentTest {
vibrator = if (Build.VERSION.SDK_INT >= 31) context.getSystemService(VibratorManager::class.java).defaultVibrator
else context.getSystemService(Vibrator::class.java)
shadowOf(vibrator).setHasVibrator(true)
rumble = RumbleComponent().also { it.motorLooper = Looper.getMainLooper(); it.attach(context); it.start() }
rumble = RumbleComponent().also {
it.motorLooper = Looper.getMainLooper()
it.gameRunning = { false }
it.attach(context)
it.start()
}
}
@After fun stopListener() { rumble.stop() }
@@ -115,6 +120,143 @@ class RumbleComponentTest {
assertFalse(pad.vibrating)
}
@Test fun aHeldEffectStopsWhenTheProcessThatStartedItIsGone() {
val pad = FakeMotors()
var alive = true
rumble.controllerMotors = { pad }
rumble.processStart = { pid -> if (pid == SENDER && alive) "1234" else null }
rumble.gameRunning = { false }
activeController(PAD_ID)
effectFrom(SENDER, ms = RumbleComponent.HOLD_MS)
idle(RumbleComponent.KEEPALIVE_MS * 2 + 100)
assertTrue(pad.vibrating)
alive = false
idle(RumbleComponent.KEEPALIVE_MS * 2 + 100)
assertFalse("a crashed game's rumble kept going", pad.vibrating)
val played = pad.played.size
idle(RumbleComponent.KEEPALIVE_MS * 4)
assertEquals("the keepalive restarted the motors", played, pad.played.size)
}
@Test fun aHeldEffectStopsWhenTheGameItStartedInExits() {
val pad = FakeMotors()
var game = true
rumble.controllerMotors = { pad }
rumble.processStart = { "1234" }
rumble.gameRunning = { game }
activeController(PAD_ID)
effectFrom(SENDER, ms = RumbleComponent.HOLD_MS)
idle(RumbleComponent.KEEPALIVE_MS * 2 + 100)
assertTrue(pad.vibrating)
game = false
idle(RumbleComponent.KEEPALIVE_MS + 100)
assertFalse("rumble outlived the game", pad.vibrating)
game = true
effectFrom(SENDER, ms = RumbleComponent.HOLD_MS)
assertTrue("the next game's rumble was dropped", pad.vibrating)
}
@Test fun aProcessStartTimeIsReadForALiveProcessOnly() {
val self = java.io.File("/proc/self").canonicalFile.name.toInt()
val start = RumbleComponent.readProcessStart(self)
assertNotNull(start)
assertNotEquals(RumbleComponent.UNKNOWN_START, start)
assertEquals("the start time changed for the same process", start, RumbleComponent.readProcessStart(self))
assertNull(RumbleComponent.readProcessStart(Int.MAX_VALUE))
}
@Test fun aGameThatExitsBeforeTheFirstKeepaliveStillStopsItsRumble() {
val pad = FakeMotors()
var game = true
rumble.controllerMotors = { pad }
rumble.processStart = { "1234" }
rumble.gameRunning = { game }
activeController(PAD_ID)
effectFrom(SENDER, ms = RumbleComponent.HOLD_MS)
game = false
idle(RumbleComponent.KEEPALIVE_MS + 100)
assertFalse("rumble outlived a game that exited right away", pad.vibrating)
}
@Test fun aGameStartingRightAfterAnotherHoldIsStillWatched() {
val pad = FakeMotors()
var game = false
rumble.controllerMotors = { pad }
rumble.processStart = { "1234" }
rumble.gameRunning = { game }
activeController(PAD_ID)
effectFrom(SENDER, ms = RumbleComponent.HOLD_MS)
effectFrom(SENDER, strong = 0, weak = 0)
game = true
idle(RumbleComponent.MIN_GAP_MS)
effectFrom(SENDER, ms = RumbleComponent.HOLD_MS)
assertTrue(pad.vibrating)
game = false
idle(RumbleComponent.KEEPALIVE_MS + 100)
assertFalse("a stale no-game result left the hold unwatched", pad.vibrating)
}
@Test fun anotherProcessClosingItsOlderRumbleLeavesTheNewerOneOnTheSlot() {
val pad = FakeMotors()
rumble.controllerMotors = { pad }
rumble.processStart = { "1234" }
activeController(PAD_ID)
effectFrom(SENDER, ms = RumbleComponent.HOLD_MS)
idle(RumbleComponent.MIN_GAP_MS)
effectFrom(OTHER_SENDER, strong = 30000, ms = RumbleComponent.HOLD_MS)
effectFrom(SENDER, strong = 0, weak = 0)
assertTrue("an older process's stop cancelled newer rumble", pad.vibrating)
effectFrom(OTHER_SENDER, strong = 0, weak = 0)
assertFalse(pad.vibrating)
}
@Test fun aSenderOfOurOwnUserThatExitedBeforeItsFirstLookupStopsItsRumble() {
val pad = FakeMotors()
rumble.controllerMotors = { pad }
rumble.processStart = { null }
activeController(PAD_ID)
effectFrom(SENDER, ms = RumbleComponent.HOLD_MS, ownUser = true)
assertTrue(pad.vibrating)
idle(RumbleComponent.KEEPALIVE_MS + 100)
assertFalse("rumble outlived a sender that was already gone", pad.vibrating)
}
@Test fun anUnseenSenderOfAnotherUserKeepsItsRumble() {
val pad = FakeMotors()
rumble.controllerMotors = { pad }
rumble.processStart = { null }
activeController(PAD_ID)
effectFrom(SENDER, ms = RumbleComponent.HOLD_MS, ownUser = false)
idle(RumbleComponent.KEEPALIVE_MS * 3 + 100)
assertTrue("a sender the app can't see lost its rumble", pad.vibrating)
}
@Test fun aSenderFirstReadAsUnknownStillStopsItsRumbleWhenItExits() {
val pad = FakeMotors()
var start: String? = RumbleComponent.UNKNOWN_START
rumble.controllerMotors = { pad }
rumble.processStart = { start }
activeController(PAD_ID)
effectFrom(SENDER, ms = RumbleComponent.HOLD_MS)
idle(RumbleComponent.KEEPALIVE_MS * 2 + 100)
assertTrue(pad.vibrating)
start = null
idle(RumbleComponent.KEEPALIVE_MS + 100)
assertFalse("rumble outlived its sender", pad.vibrating)
}
@Test fun anUnreadableButLiveProcessKeepsItsRumble() {
val pad = FakeMotors()
var start: String? = "1234"
rumble.controllerMotors = { pad }
rumble.processStart = { start }
activeController(PAD_ID)
effectFrom(SENDER, ms = RumbleComponent.HOLD_MS)
start = RumbleComponent.UNKNOWN_START
idle(RumbleComponent.KEEPALIVE_MS * 3 + 100)
assertTrue("a passing /proc read error cut the rumble", pad.vibrating)
}
@Test fun quietingStopsAHeldEffectAndDropsEffectsUntilLifted() {
val pad = FakeMotors()
rumble.controllerMotors = { pad }
@@ -280,6 +422,12 @@ class RumbleComponentTest {
.apply { isAccessible = true }.invoke(rumble, strong, weak, ms, slot)
}
private fun effectFrom(sender: Int, strong: Int = 40000, weak: Int = 20000, slot: Int = 0, ms: Int = 5000, ownUser: Boolean = false) {
val int = Int::class.javaPrimitiveType
RumbleComponent::class.java.getDeclaredMethod("buzz", int, int, int, int, int, Boolean::class.javaPrimitiveType)
.apply { isAccessible = true }.invoke(rumble, strong, weak, ms, slot, sender, ownUser)
}
private fun idle(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(java.time.Duration.ofMillis(ms))
private class FakeMotors : RumbleComponent.Motors {
@@ -293,6 +441,8 @@ class RumbleComponentTest {
private companion object {
const val PAD_ID = 7
const val SECOND_PAD_ID = 8
const val SENDER = 4242
const val OTHER_SENDER = 4343
}
@Implements(LocalServerSocket::class)