diff --git a/app/src/main/cpp/fakeinput_steam.cpp b/app/src/main/cpp/fakeinput_steam.cpp index 8941abda20..300d6be6e2 100644 --- a/app/src/main/cpp/fakeinput_steam.cpp +++ b/app/src/main/cpp/fakeinput_steam.cpp @@ -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 &ff_players() { + static auto *players = new std::unordered_map(); + 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(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(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(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(controller->second->slot); - if (count == sizeof(struct input_event)) { - ev = static_cast(buf); - check_ff_event(ev, slot); - } + if (count == sizeof(struct input_event)) + check_ff_event(static_cast(buf), *controller->second); return static_cast(count); } @@ -3982,14 +4010,10 @@ EXPORT ssize_t writev(int fd, const struct iovec *iov, int iovcnt) { return -1; } - uint16_t slot = static_cast(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(iov[i].iov_base); - check_ff_event(ev, slot); - } + if (iov[i].iov_len == sizeof(struct input_event)) + check_ff_event(static_cast(iov[i].iov_base), *controller->second); total += static_cast(iov[i].iov_len); } return total; diff --git a/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt b/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt index 39d99bfa6c..677d16511d 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt @@ -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}\"" diff --git a/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt index 78741888d3..c1f71bef54 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt @@ -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) diff --git a/tools/tests/test_fakeinput_rumble_stop.py b/tools/tests/test_fakeinput_rumble_stop.py new file mode 100644 index 0000000000..fd88503413 --- /dev/null +++ b/tools/tests/test_fakeinput_rumble_stop.py @@ -0,0 +1,145 @@ +import os +from pathlib import Path +import shutil +import socket +import struct +import subprocess +import sys +import tempfile +import unittest + +SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp" +RING_MAGIC = 0x46494252 +DESCRIPTION_MAGIC = 0x46495544 +HEADER = 64 +EVENT = 24 +CAPACITY = 4096 +DESCRIPTION = 1824 + +GAME = r""" +#include +#include +#include +#include +#include +#include + +static int rumble(int fd, unsigned short strong) { + struct ff_effect effect; + memset(&effect, 0, sizeof(effect)); + effect.id = -1; + effect.type = FF_RUMBLE; + effect.u.rumble.strong_magnitude = strong; + effect.u.rumble.weak_magnitude = 20000; + if (ioctl(fd, EVIOCSFF, &effect) < 0) return -1; + struct input_event play; + memset(&play, 0, sizeof(play)); + play.type = EV_FF; + play.code = effect.id; + play.value = 1; + if (write(fd, &play, sizeof(play)) != sizeof(play)) return -1; + return effect.id; +} + +int main(int argc, char **argv) { + int fd = open("/dev/input/event16", O_RDWR | O_NONBLOCK); + if (fd < 0) return 1; + if (argv[1][0] == 'p') { + int other = open("/dev/input/event16", O_RDWR | O_NONBLOCK); + if (other < 0 || rumble(fd, 40000) < 0 || rumble(other, 30000) < 0) return 2; + close(fd); + return 0; + } + if (argv[1][0] == 'k') { + pid_t child = fork(); + if (child == 0) { + if (rumble(fd, 40000) < 0) _exit(2); + close(fd); + _exit(0); + } + int status = 0; + waitpid(child, &status, 0); + return WEXITSTATUS(status); + } + struct ff_effect effect; + effect.id = rumble(fd, 40000); + if (effect.id < 0) return 2; + if (argv[1][0] == 'e') ioctl(fd, EVIOCRMFF, effect.id); + else if (argv[1][0] == 'c') close(fd); + else if (argv[1][0] == 'f') { + pid_t child = fork(); + if (child == 0) { + close(fd); + _exit(0); + } + waitpid(child, NULL, 0); + } + return 0; +} +""" + + +@unittest.skipUnless(sys.platform == "linux" and shutil.which("g++") and shutil.which("gcc"), "needs Linux, gcc and g++") +class FakeinputRumbleStopTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = Path(tempfile.mkdtemp()) + cls.addClassCleanup(shutil.rmtree, cls.tmp, True) + cls.library = cls.tmp / "libfakeinput.so" + subprocess.run(["g++", "-shared", "-fPIC", "-O2", "-Wno-attributes", "-pthread", "-std=c++17", + "-static-libstdc++", "-static-libgcc", "-Wl,--exclude-libs,ALL", "-o", str(cls.library), + str(SOURCE), "-ldl"], check=True) + cls.game = cls.tmp / "game" + (cls.tmp / "game.c").write_text(GAME) + subprocess.run(["gcc", "-o", str(cls.game), str(cls.tmp / "game.c")], check=True) + cls.hooks = cls.tmp / "hooks" + cls.hooks.mkdir() + (cls.hooks / "event16").touch() + ring = bytearray(HEADER + CAPACITY * EVENT + DESCRIPTION) + struct.pack_into("