Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

Input on SDL3: gamepads, keyboard and mouse, and the shell's hooks

Rafael Abud Ferreiradb5a1e738b57
diff --git a/CMakeLists.txt b/CMakeLists.txt
index b81a51f..5d2f5de 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -39,6 +39,7 @@ add_library(xcloud_core STATIC
src/input/kbm_map.cpp
src/input/key_map.cpp
src/input/keyboard_nav.cpp
+ src/input/sdl_mapping.cpp
src/xcloud/social.cpp
src/platform/posix_common.cpp
src/input/gyro.cpp
@@ -179,3 +180,25 @@ else()
target_link_libraries(xcloud-tests PRIVATE xcloud_stream xcloud_media xcloud_ui xcloud_backends_null xc_ffmpeg datachannel-static)
add_test(NAME unit COMMAND xcloud-tests)
endif()
+
+# --- Desktop input and sound on SDL3 (controllers, keyboard / mouse, audio) ---
+# The SDL backends of controller.h, kbm.h, input_ext.h, audio_out.h and
+# audio_in.h, for the desktop app in place of the null ones (controller_null,
+# kbm_null, audio_*_null: not both). Only where SDL3 is found and the desktop
+# app is wanted: xcloud-cli, xcloud-tests and psbox-headless stay SDL-free.
+if(NOT XCLOUD_PS5 AND (NOT DEFINED XCLOUD_DESKTOP_APP OR XCLOUD_DESKTOP_APP))
+ if(NOT TARGET SDL3::SDL3)
+ find_package(SDL3 CONFIG QUIET)
+ endif()
+ if(TARGET SDL3::SDL3)
+ add_library(xcloud_backends_sdl_io OBJECT
+ src/input/sdl_input.cpp
+ src/input/controller_sdl.cpp
+ src/input/kbm_sdl.cpp
+ )
+ target_link_libraries(xcloud_backends_sdl_io PUBLIC xcloud_core xcloud_media SDL3::SDL3)
+ if(NOT MSVC)
+ target_compile_options(xcloud_backends_sdl_io PRIVATE -Wall -Wextra -Wno-unused-parameter)
+ endif()
+ endif()
+endif()
diff --git a/src/input/controller_sdl.cpp b/src/input/controller_sdl.cpp
new file mode 100644
index 0000000..702658e
--- /dev/null
+++ b/src/input/controller_sdl.cpp
@@ -0,0 +1,340 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// SDL3 gamepads on the desktop (controller.h): each one plugged in takes the
+// first free slot, is read, and is sent the effects the shared code
+// (controller_common.cpp) works out: rumble, the triggers (an Xbox pad's
+// trigger motors, or the DualSense's effects through SDL_SendGamepadEffect),
+// the light bar. Gyro aiming and the touchpad where the pad has them.
+// The gamepads come and go with the shell's events (sdl_input.cpp).
+#include "input/controller.h"
+#include "input/controller_backend.h"
+#include "input/input_ext.h"
+#include "input/sdl_backend.h"
+#include "input/sdl_mapping.h"
+#include "util/log.h"
+
+#include <SDL3/SDL.h>
+
+#include <algorithm>
+#include <mutex>
+#include <string>
+
+namespace xc::input {
+
+namespace {
+
+// SDL's longest rumble (SDL_MAX_RUMBLE_DURATION_MS): what "until changed"
+// becomes. A duration keeps SDL re-sending the rumble to the pads that let
+// it fade on their own; the shared code stops it when its time is up.
+constexpr uint32_t kRumbleForever = 0xFFFF;
+
+struct Slot {
+ SDL_Gamepad* pad = nullptr;
+ SDL_JoystickID id = 0;
+ PadCaps caps;
+ bool triggerMotors = false; // SDL can drive its triggers' motors (an Xbox pad)
+ bool accel = false; // its accelerometer is on (gyro aiming's "up")
+ std::string name;
+};
+// The pads are opened, closed and read on the main thread (the shell's
+// events and coreFrame); g_mutex keeps the caps and names whole for the
+// UI's questions.
+Slot g_slots[kMaxPads];
+std::mutex g_mutex;
+bool g_initedGamepads = false; // SDL's gamepad subsystem started here (not by the shell)
+
+uint32_t sdlDuration(uint32_t ms) { return ms ? std::min(ms, kRumbleForever) : kRumbleForever; }
+
+PadKind kindOf(SDL_GamepadType type) {
+ switch (type) {
+ case SDL_GAMEPAD_TYPE_PS5: return PadKind::DualSense;
+ case SDL_GAMEPAD_TYPE_PS4: return PadKind::DualShock4;
+ case SDL_GAMEPAD_TYPE_XBOX360:
+ case SDL_GAMEPAD_TYPE_XBOXONE: return PadKind::Xbox;
+ case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO:
+ case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT:
+ case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT:
+ case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_PAIR: return PadKind::Switch;
+ default: return PadKind::Generic;
+ }
+}
+
+const char* kindName(PadKind kind) {
+ switch (kind) {
+ case PadKind::DualSense: return "DualSense";
+ case PadKind::DualShock4: return "DualShock 4";
+ case PadKind::Xbox: return "Xbox";
+ case PadKind::Switch: return "Switch";
+ case PadKind::Generic: return "generic";
+ default: return "none";
+ }
+}
+
+void openPad(SDL_JoystickID id) {
+ for (const Slot& s : g_slots)
+ if (s.pad && s.id == id) return; // the first scan and its ADDED event
+ int slot = -1;
+ for (int i = 0; i < kMaxPads && slot < 0; ++i)
+ if (!g_slots[i].pad) slot = i;
+ if (slot < 0) {
+ const char* name = SDL_GetGamepadNameForID(id);
+ XC_LOGI("gamepad %s: no free slot (%d in use)", name ? name : "?", kMaxPads);
+ return;
+ }
+ SDL_Gamepad* gp = SDL_OpenGamepad(id);
+ if (!gp) {
+ XC_LOGW("SDL_OpenGamepad(%u): %s", static_cast<unsigned>(id), SDL_GetError());
+ return;
+ }
+ SDL_SetGamepadPlayerIndex(gp, slot); // the pad's own player lights
+ SDL_PropertiesID props = SDL_GetGamepadProperties(gp);
+ Slot s;
+ s.pad = gp;
+ s.id = id;
+ s.caps.kind = kindOf(SDL_GetGamepadType(gp));
+ s.caps.rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, false);
+ s.caps.lightBar = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_RGB_LED_BOOLEAN, false);
+ // The DualSense's trigger effects go through SDL's own driver for it
+ // (HIDAPI), the one that also drives its light bar; Linux's evdev
+ // fallback has neither. A refused effect turns them off too.
+ s.caps.adaptiveTriggers = s.caps.kind == PadKind::DualSense && s.caps.lightBar;
+ s.triggerMotors = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN, false);
+ s.caps.triggerRumble = s.caps.adaptiveTriggers || s.triggerMotors;
+ s.caps.gyro = SDL_GamepadHasSensor(gp, SDL_SENSOR_GYRO) && SDL_SetGamepadSensorEnabled(gp, SDL_SENSOR_GYRO, true);
+ s.accel = SDL_GamepadHasSensor(gp, SDL_SENSOR_ACCEL) && SDL_SetGamepadSensorEnabled(gp, SDL_SENSOR_ACCEL, true);
+ s.caps.touchpad = SDL_GetNumGamepadTouchpads(gp) > 0;
+ const char* name = SDL_GetGamepadName(gp);
+ s.name = name ? name : "";
+ {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ g_slots[slot] = s;
+ }
+ slotOpened(slot);
+ if (s.caps.lightBar) { // the player's colour, as the PS5 shows it
+ uint8_t c[3];
+ playerLightColour(slot, c);
+ SDL_SetGamepadLED(gp, c[0], c[1], c[2]);
+ }
+ XC_LOGI("pad %d opened: %s (%s; rumble %d, trigger rumble %d, adaptive triggers %d, light bar %d, gyro %d, accel %d, "
+ "touchpad %d)",
+ slot, s.name.c_str(), kindName(s.caps.kind), s.caps.rumble, s.caps.triggerRumble, s.caps.adaptiveTriggers,
+ s.caps.lightBar, s.caps.gyro, s.accel, s.caps.touchpad);
+}
+
+void closePad(int slot) {
+ Slot& s = g_slots[slot];
+ if (!s.pad) return;
+ if (SDL_GamepadConnected(s.pad)) { // still there (the app closing): its effects stopped
+ if (s.caps.rumble) SDL_RumbleGamepad(s.pad, 0, 0, 0);
+ if (s.caps.adaptiveTriggers) {
+ uint8_t off[kDs5EffectsSize];
+ ds5TriggerEffects(TriggerCommand{}, TriggerCommand{}, off);
+ SDL_SendGamepadEffect(s.pad, off, sizeof off);
+ } else if (s.triggerMotors) {
+ SDL_RumbleGamepadTriggers(s.pad, 0, 0, 0);
+ }
+ }
+ slotClosed(slot);
+ SDL_CloseGamepad(s.pad);
+ XC_LOGI("pad %d closed (%s)", slot, s.name.c_str());
+ std::lock_guard<std::mutex> lock(g_mutex);
+ s = {};
+}
+
+} // namespace
+
+namespace backend {
+
+bool padOpen(int slot) { return g_slots[slot].pad != nullptr; }
+
+bool readPad(int slot, RawPad& out) {
+ const Slot& s = g_slots[slot];
+ SDL_Gamepad* gp = s.pad;
+ if (!SDL_GamepadConnected(gp)) return false;
+ auto button = [gp](SDL_GamepadButton b) { return SDL_GetGamepadButton(gp, b); };
+ out.dpadUp = button(SDL_GAMEPAD_BUTTON_DPAD_UP);
+ out.dpadDown = button(SDL_GAMEPAD_BUTTON_DPAD_DOWN);
+ out.dpadLeft = button(SDL_GAMEPAD_BUTTON_DPAD_LEFT);
+ out.dpadRight = button(SDL_GAMEPAD_BUTTON_DPAD_RIGHT);
+ // By position, whatever is printed on them (Cross / A at the bottom).
+ out.btnA = button(SDL_GAMEPAD_BUTTON_SOUTH);
+ out.btnB = button(SDL_GAMEPAD_BUTTON_EAST);
+ out.btnX = button(SDL_GAMEPAD_BUTTON_WEST);
+ out.btnY = button(SDL_GAMEPAD_BUTTON_NORTH);
+ out.btnL1 = button(SDL_GAMEPAD_BUTTON_LEFT_SHOULDER);
+ out.btnR1 = button(SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER);
+ out.btnL3 = button(SDL_GAMEPAD_BUTTON_LEFT_STICK);
+ out.btnR3 = button(SDL_GAMEPAD_BUTTON_RIGHT_STICK);
+ out.btnOptions = button(SDL_GAMEPAD_BUTTON_START);
+ // View: an Xbox pad's View (Back), or the DualSense's touchpad click as on the PS5.
+ out.btnTouchpad = button(SDL_GAMEPAD_BUTTON_BACK) || button(SDL_GAMEPAD_BUTTON_TOUCHPAD);
+ // The desktop leaves the guide / PS button to the app: the Xbox button.
+ out.btnNexus = button(SDL_GAMEPAD_BUTTON_GUIDE);
+
+ out.leftX = sdlStickAxis(SDL_GetGamepadAxis(gp, SDL_GAMEPAD_AXIS_LEFTX));
+ out.leftY = sdlStickAxis(SDL_GetGamepadAxis(gp, SDL_GAMEPAD_AXIS_LEFTY));
+ out.rightX = sdlStickAxis(SDL_GetGamepadAxis(gp, SDL_GAMEPAD_AXIS_RIGHTX));
+ out.rightY = sdlStickAxis(SDL_GetGamepadAxis(gp, SDL_GAMEPAD_AXIS_RIGHTY));
+ out.l2 = sdlTriggerAxis(SDL_GetGamepadAxis(gp, SDL_GAMEPAD_AXIS_LEFT_TRIGGER));
+ out.r2 = sdlTriggerAxis(SDL_GetGamepadAxis(gp, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER));
+
+ // rad/s, x pitch, y yaw, z roll (scePad's convention); the "gyro:" log
+ // lines show the signs on a real pad.
+ if (s.caps.gyro) SDL_GetGamepadSensorData(gp, SDL_SENSOR_GYRO, out.gyro, 3);
+ if (s.accel) {
+ float ms2[3] = {0, 0, 0};
+ if (SDL_GetGamepadSensorData(gp, SDL_SENSOR_ACCEL, ms2, 3)) {
+ sdlAccelToG(ms2, out.accel);
+ out.hasAccel = true;
+ }
+ }
+
+ if (s.caps.touchpad) {
+ bool down = false;
+ float x = 0, y = 0, pressure = 0;
+ if (SDL_GetGamepadTouchpadFinger(gp, 0, 0, &down, &x, &y, &pressure) && down) {
+ out.touching = true; // SDL gives 0..1 from the top left already
+ out.touchX = std::clamp(x, 0.0f, 1.0f);
+ out.touchY = std::clamp(y, 0.0f, 1.0f);
+ }
+ }
+ return true;
+}
+
+void setMotors(int slot, uint8_t large, uint8_t small, uint32_t durationMs) {
+ const Slot& s = g_slots[slot];
+ if (!s.caps.rumble) return;
+ bool ok = SDL_RumbleGamepad(s.pad, static_cast<uint16_t>(large * 257), static_cast<uint16_t>(small * 257),
+ sdlDuration(durationMs));
+ static int logged = 0; // the first, and a few failures
+ if (logged == 0 || (!ok && logged < 6))
+ XC_LOGI("SDL_RumbleGamepad(%u, %u, %u ms): %s", large, small, durationMs, ok ? "ok" : SDL_GetError()), ++logged;
+}
+
+TriggerStyle triggerStyle(int slot) {
+ const Slot& s = g_slots[slot];
+ if (s.caps.adaptiveTriggers) return TriggerStyle::Adaptive;
+ return s.triggerMotors ? TriggerStyle::Motors : TriggerStyle::None;
+}
+
+int setTriggerEffects(int slot, const TriggerCommand command[2]) {
+ Slot& s = g_slots[slot];
+ uint8_t packet[kDs5EffectsSize];
+ ds5TriggerEffects(command[0], command[1], packet);
+ if (SDL_SendGamepadEffect(s.pad, packet, sizeof packet)) return 0;
+ // No effects through this pad's driver (Linux's evdev, without access to
+ // its hidraw node): plain triggers from now on, and Settings hides them.
+ static bool logged = false;
+ if (!logged) XC_LOGW("pad %d: trigger effects refused (%s): no adaptive triggers", slot, SDL_GetError());
+ logged = true;
+ std::lock_guard<std::mutex> lock(g_mutex);
+ s.caps.adaptiveTriggers = false;
+ s.caps.triggerRumble = s.triggerMotors;
+ return -1;
+}
+
+void setTriggerMotors(int slot, uint8_t left, uint8_t right, uint32_t durationMs) {
+ const Slot& s = g_slots[slot];
+ bool ok = SDL_RumbleGamepadTriggers(s.pad, static_cast<uint16_t>(left * 257), static_cast<uint16_t>(right * 257),
+ sdlDuration(durationMs));
+ static int logged = 0;
+ if (logged == 0 || (!ok && logged < 6))
+ XC_LOGI("SDL_RumbleGamepadTriggers(%u, %u, %u ms): %s", left, right, durationMs, ok ? "ok" : SDL_GetError()), ++logged;
+}
+
+void setLight(int slot, uint8_t r, uint8_t g, uint8_t b) {
+ const Slot& s = g_slots[slot];
+ if (!s.caps.lightBar) return;
+ bool ok = SDL_SetGamepadLED(s.pad, r, g, b);
+ static int logged = 0;
+ if (logged == 0 || (!ok && logged < 6)) XC_LOGI("SDL_SetGamepadLED(%u, %u, %u): %s", r, g, b, ok ? "ok" : SDL_GetError()), ++logged;
+}
+
+void resetLight(int slot) {
+ const Slot& s = g_slots[slot];
+ if (!s.caps.lightBar) return;
+ uint8_t c[3];
+ playerLightColour(slot, c);
+ SDL_SetGamepadLED(s.pad, c[0], c[1], c[2]);
+}
+
+} // namespace backend
+
+void padSdlInit() {
+ if (!SDL_WasInit(SDL_INIT_GAMEPAD)) {
+ if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) {
+ XC_LOGE("SDL gamepads: %s", SDL_GetError());
+ return;
+ }
+ g_initedGamepads = true;
+ }
+ int count = 0;
+ SDL_JoystickID* ids = SDL_GetGamepads(&count);
+ for (int i = 0; ids && i < count; ++i) openPad(ids[i]);
+ SDL_free(ids);
+ XC_LOGI("controllers: %d gamepad(s) found", count);
+}
+
+void padSdlEvent(const SDL_Event& event) {
+ if (event.type == SDL_EVENT_GAMEPAD_ADDED) {
+ openPad(event.gdevice.which);
+ } else if (event.type == SDL_EVENT_GAMEPAD_REMOVED) {
+ for (int i = 0; i < kMaxPads; ++i)
+ if (g_slots[i].pad && g_slots[i].id == event.gdevice.which) closePad(i);
+ }
+}
+
+void padSdlShutdown() {
+ shutdown();
+ if (g_initedGamepads) SDL_QuitSubSystem(SDL_INIT_GAMEPAD);
+ g_initedGamepads = false;
+}
+
+bool init() { return true; } // the pads come with sdlInputInit() and the window's events
+
+void shutdown() {
+ for (int i = 0; i < kMaxPads; ++i) closePad(i);
+}
+
+bool poll(ControllerState& out) {
+ for (int i = 0; i < kMaxPads; ++i)
+ if (g_slots[i].pad) return pollPad(i, out);
+ out = {};
+ return false;
+}
+
+void refreshPads() {} // pads plugged in or out arrive as events
+
+std::string padUserName(int) { return {}; }
+
+std::string padDeviceName(int index) {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ return index >= 0 && index < kMaxPads && g_slots[index].pad ? g_slots[index].name : std::string();
+}
+
+int32_t padUserId(int) { return -1; }
+
+void setEmbeddedMicActive(bool, int) {} // no such weakening outside the console
+
+PadCaps padCaps(int index) {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ return index >= 0 && index < kMaxPads && g_slots[index].pad ? g_slots[index].caps : PadCaps{};
+}
+
+PadCaps anyPadCaps() {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ PadCaps any;
+ for (const Slot& s : g_slots) {
+ if (!s.pad) continue;
+ if (any.kind == PadKind::None) any.kind = s.caps.kind; // the first pad's kind
+ any.rumble |= s.caps.rumble;
+ any.triggerRumble |= s.caps.triggerRumble;
+ any.adaptiveTriggers |= s.caps.adaptiveTriggers;
+ any.lightBar |= s.caps.lightBar;
+ any.gyro |= s.caps.gyro;
+ any.touchpad |= s.caps.touchpad;
+ }
+ return any;
+}
+
+} // namespace xc::input
diff --git a/src/input/kbm_sdl.cpp b/src/input/kbm_sdl.cpp
new file mode 100644
index 0000000..b20c7d0
--- /dev/null
+++ b/src/input/kbm_sdl.cpp
@@ -0,0 +1,215 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// The keyboard and mouse on the desktop (kbm.h), from the window's SDL3
+// events (sdl_input.cpp). Keys come out as Windows virtual-key codes, as the
+// PS5's keyboard does (SDL's scancodes are the same USB HID usages); the
+// mouse's movement counts only while the window holds it (kbmSetCaptured:
+// in a game), its buttons and wheel while the window has the focus.
+#include "input/input_ext.h"
+#include "input/kbm.h"
+#include "input/sdl_backend.h"
+#include "input/sdl_mapping.h"
+#include "util/log.h"
+
+#include <SDL3/SDL.h>
+
+#include <algorithm>
+#include <mutex>
+#include <vector>
+
+namespace xc::input {
+
+namespace {
+
+// Events and polls are on the main thread; the lock keeps them whole if a
+// shell ever pumps elsewhere. SDL is never called with it held.
+std::mutex g_mutex;
+SDL_Window* g_window = nullptr;
+bool g_captureWanted = false, g_focused = true, g_captured = false;
+bool g_down[SDL_SCANCODE_COUNT] = {}; // keys held (scancodes)
+std::vector<int> g_pressed; // scancodes that went down since the last poll
+std::vector<uint8_t> g_tapped; // keys that went down and up since the last poll
+float g_dx = 0, g_dy = 0; // movement while held, what isn't a whole step yet kept
+int32_t g_wheel = 0; // notches, + away from the user (as Windows counts them)
+uint32_t g_sdlButtons = 0; // SDL's mask, held now
+uint32_t g_sdlClicked = 0; // went down since the last poll (a click between two polls still counts)
+// What the last poll reported.
+std::vector<uint8_t> g_held;
+uint8_t g_buttons = 0;
+
+// Holds or lets go of the mouse: held while a game wants it and the window
+// has the focus.
+void applyCapture() {
+ SDL_Window* window;
+ bool hold;
+ {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ hold = g_captureWanted && g_focused && g_window;
+ if (hold == g_captured) return;
+ g_captured = hold;
+ if (!hold) g_dx = g_dy = 0; // what moved before letting go isn't the game's
+ window = g_window;
+ }
+ if (!window) return;
+ if (SDL_SetWindowRelativeMouseMode(window, hold))
+ XC_LOGI("mouse %s", hold ? "held by the window" : "let go");
+ else
+ XC_LOGW("SDL_SetWindowRelativeMouseMode(%d): %s", hold, SDL_GetError());
+}
+
+bool ourWindow(const SDL_Event& e) {
+ SDL_Window* window;
+ {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ window = g_window;
+ }
+ return !window || e.window.windowID == SDL_GetWindowID(window);
+}
+
+} // namespace
+
+void kbmSdlInit(SDL_Window* window) {
+ bool focused = !window || (SDL_GetWindowFlags(window) & SDL_WINDOW_INPUT_FOCUS) != 0;
+ std::lock_guard<std::mutex> lock(g_mutex);
+ g_window = window;
+ g_focused = focused;
+}
+
+void kbmSdlEvent(const SDL_Event& e) {
+ switch (e.type) {
+ case SDL_EVENT_KEY_DOWN:
+ case SDL_EVENT_KEY_UP: {
+ if (e.key.repeat) break;
+ int sc = e.key.scancode;
+ if (sc <= SDL_SCANCODE_UNKNOWN || sc >= SDL_SCANCODE_COUNT) break;
+ std::lock_guard<std::mutex> lock(g_mutex);
+ if (e.key.down) {
+ if (!g_down[sc]) g_pressed.push_back(sc);
+ g_down[sc] = true;
+ } else {
+ bool quick = g_down[sc] && std::find(g_pressed.begin(), g_pressed.end(), sc) != g_pressed.end();
+ if (uint8_t vk = scancodeToVk(sc); quick && vk) g_tapped.push_back(vk);
+ g_down[sc] = false;
+ }
+ break;
+ }
+ case SDL_EVENT_MOUSE_MOTION: {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ if (g_captured) {
+ g_dx += e.motion.xrel;
+ g_dy += e.motion.yrel;
+ }
+ break;
+ }
+ case SDL_EVENT_MOUSE_BUTTON_DOWN:
+ case SDL_EVENT_MOUSE_BUTTON_UP: {
+ if (e.button.button < SDL_BUTTON_LEFT || e.button.button > SDL_BUTTON_X2) break;
+ uint32_t bit = SDL_BUTTON_MASK(e.button.button);
+ std::lock_guard<std::mutex> lock(g_mutex);
+ if (e.button.down) {
+ g_sdlButtons |= bit;
+ g_sdlClicked |= bit;
+ } else {
+ g_sdlButtons &= ~bit;
+ }
+ break;
+ }
+ case SDL_EVENT_MOUSE_WHEEL: {
+ int32_t notches = e.wheel.integer_y;
+ if (e.wheel.direction == SDL_MOUSEWHEEL_FLIPPED) notches = -notches;
+ std::lock_guard<std::mutex> lock(g_mutex);
+ g_wheel += notches;
+ break;
+ }
+ case SDL_EVENT_WINDOW_FOCUS_GAINED:
+ case SDL_EVENT_WINDOW_FOCUS_LOST: {
+ if (!ourWindow(e)) break;
+ bool focused = e.type == SDL_EVENT_WINDOW_FOCUS_GAINED;
+ {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ g_focused = focused;
+ if (!focused) { // nothing stays held for the game behind another window
+ std::fill(std::begin(g_down), std::end(g_down), false);
+ g_sdlButtons = 0;
+ }
+ }
+ applyCapture();
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+void kbmSdlShutdown() {
+ kbmSetCaptured(false);
+ std::lock_guard<std::mutex> lock(g_mutex);
+ g_window = nullptr;
+}
+
+bool kbmInit(int32_t) {
+ XC_LOGI("keyboard: %s, mouse: %s (SDL)", SDL_HasKeyboard() ? "found" : "none yet", SDL_HasMouse() ? "found" : "none yet");
+ return true;
+}
+
+KbmInput kbmPoll() {
+ KbmInput out;
+ out.keyboard = SDL_HasKeyboard();
+ out.mouse = SDL_HasMouse();
+ std::lock_guard<std::mutex> lock(g_mutex);
+
+ // The keys held now; what went down or up since the last poll is the
+ // difference, as the PS5's keyboard records give it.
+ std::vector<uint8_t> held;
+ for (int sc = 0; sc < SDL_SCANCODE_COUNT; ++sc)
+ if (g_down[sc])
+ if (uint8_t vk = scancodeToVk(sc)) held.push_back(vk);
+ std::sort(held.begin(), held.end());
+ held.erase(std::unique(held.begin(), held.end()), held.end());
+ for (uint8_t vk : g_held)
+ if (!std::binary_search(held.begin(), held.end(), vk)) out.keys.push_back({vk, false});
+ for (uint8_t vk : held)
+ if (!std::binary_search(g_held.begin(), g_held.end(), vk)) out.keys.push_back({vk, true});
+ // Down and up again between two polls (a quick tap while a frame took
+ // long): both, so it isn't lost.
+ for (uint8_t vk : g_tapped)
+ if (!std::binary_search(held.begin(), held.end(), vk) && !std::binary_search(g_held.begin(), g_held.end(), vk)) {
+ out.keys.push_back({vk, true});
+ out.keys.push_back({vk, false});
+ }
+ g_tapped.clear();
+ g_pressed.clear();
+ g_held.swap(held);
+ out.held = g_held;
+ static int logged = 0; // the first few, to check a keyboard works (not what is typed after)
+ for (const auto& k : out.keys)
+ if (logged < 10) XC_LOGI("keyboard: key 0x%02x %s (%d)", k.vk, k.pressed ? "down" : "up", ++logged);
+
+ // The mouse: whole steps of the movement (the rest kept for the next
+ // poll), the wheel, the buttons (a click since the last poll shows once).
+ out.dx = static_cast<int32_t>(g_dx);
+ out.dy = static_cast<int32_t>(g_dy);
+ g_dx -= static_cast<float>(out.dx);
+ g_dy -= static_cast<float>(out.dy);
+ out.wheel = g_wheel;
+ g_wheel = 0;
+ uint8_t buttons = sdlMouseButtons(g_sdlButtons | g_sdlClicked);
+ g_sdlClicked = 0;
+ out.buttons = buttons;
+ out.moved = out.dx || out.dy || out.wheel || buttons != g_buttons;
+ static int movesLogged = 0;
+ if (out.moved && movesLogged < 10)
+ XC_LOGI("mouse: %d,%d wheel %d buttons 0x%02x (%d)", out.dx, out.dy, out.wheel, buttons, ++movesLogged);
+ g_buttons = buttons;
+ return out;
+}
+
+void kbmSetCaptured(bool captured) {
+ {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ g_captureWanted = captured;
+ }
+ applyCapture();
+}
+
+} // namespace xc::input
diff --git a/src/input/sdl_backend.h b/src/input/sdl_backend.h
new file mode 100644
index 0000000..1d68889
--- /dev/null
+++ b/src/input/sdl_backend.h
@@ -0,0 +1,28 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// Between sdl_input.cpp (input_ext.h's SDL3 hooks, called by the shell) and
+// the SDL backends it hands the window's events to: the gamepads
+// (controller_sdl.cpp) and the keyboard and mouse (kbm_sdl.cpp). Main
+// thread, as SDL's event loop.
+#pragma once
+
+union SDL_Event;
+struct SDL_Window;
+
+namespace xc::input {
+
+// Starts SDL's gamepads (unless the shell did) and opens those plugged in.
+void padSdlInit();
+// SDL_EVENT_GAMEPAD_ADDED / REMOVED.
+void padSdlEvent(const SDL_Event& event);
+// Closes the pads (their effects stopped).
+void padSdlShutdown();
+
+// The window whose events come in and which holds the mouse.
+void kbmSdlInit(SDL_Window* window);
+// Keys, mouse movement / buttons / wheel, the window's focus.
+void kbmSdlEvent(const SDL_Event& event);
+// Lets the mouse go.
+void kbmSdlShutdown();
+
+} // namespace xc::input
diff --git a/src/input/sdl_input.cpp b/src/input/sdl_input.cpp
new file mode 100644
index 0000000..eb20093
--- /dev/null
+++ b/src/input/sdl_input.cpp
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// The desktop's input hooks (input_ext.h): the shell owns the window and
+// SDL's event loop and hands each event over; the gamepads go to
+// controller_sdl.cpp, keys, the mouse and the window's focus to kbm_sdl.cpp.
+#include "input/input_ext.h"
+#include "input/sdl_backend.h"
+
+#include <SDL3/SDL.h>
+
+namespace xc::input {
+
+void sdlInputInit(SDL_Window* window) {
+ padSdlInit();
+ kbmSdlInit(window);
+}
+
+void sdlInputEvent(const SDL_Event& event) {
+ switch (event.type) {
+ case SDL_EVENT_GAMEPAD_ADDED:
+ case SDL_EVENT_GAMEPAD_REMOVED:
+ padSdlEvent(event);
+ break;
+ case SDL_EVENT_KEY_DOWN:
+ case SDL_EVENT_KEY_UP:
+ case SDL_EVENT_MOUSE_MOTION:
+ case SDL_EVENT_MOUSE_BUTTON_DOWN:
+ case SDL_EVENT_MOUSE_BUTTON_UP:
+ case SDL_EVENT_MOUSE_WHEEL:
+ case SDL_EVENT_WINDOW_FOCUS_GAINED:
+ case SDL_EVENT_WINDOW_FOCUS_LOST:
+ kbmSdlEvent(event);
+ break;
+ default:
+ break;
+ }
+}
+
+void sdlInputShutdown() {
+ kbmSdlShutdown();
+ padSdlShutdown();
+}
+
+} // namespace xc::input
diff --git a/src/input/sdl_mapping.cpp b/src/input/sdl_mapping.cpp
new file mode 100644
index 0000000..65c914a
--- /dev/null
+++ b/src/input/sdl_mapping.cpp
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+#include "input/sdl_mapping.h"
+
+#include "input/kbm.h"
+
+#include <algorithm>
+#include <cstring>
+
+namespace xc::input {
+
+float sdlStickAxis(int16_t v) { return std::clamp(v / 32767.0f, -1.0f, 1.0f); }
+float sdlTriggerAxis(int16_t v) { return std::clamp(v / 32767.0f, 0.0f, 1.0f); }
+
+void sdlAccelToG(const float ms2[3], float g[3]) {
+ for (int i = 0; i < 3; ++i) g[i] = ms2[i] / kStandardGravity;
+}
+
+uint8_t scancodeToVk(int scancode) {
+ if (scancode >= 224 && scancode <= 231) return modifierVk(scancode - 224);
+ if (scancode < 0 || scancode > 0xFF) return 0;
+ return hidToVk(static_cast<uint16_t>(scancode));
+}
+
+uint8_t sdlMouseButtons(uint32_t m) {
+ return static_cast<uint8_t>((m & 1u ? 1 : 0) | (m & 4u ? 2 : 0) | (m & 2u ? 4 : 0) | (m & 8u ? 8 : 0) | (m & 16u ? 16 : 0));
+}
+
+void playerLightColour(int slot, uint8_t rgb[3]) {
+ static constexpr uint8_t kColours[4][3] = {{0, 112, 220}, {220, 50, 50}, {40, 170, 80}, {225, 90, 175}};
+ const uint8_t* c = kColours[std::clamp(slot, 0, 3)];
+ std::copy(c, c + 3, rgb);
+}
+
+void ds5TriggerBlock(const TriggerCommand& c, uint8_t out[kDs5TriggerBlock]) {
+ std::memset(out, 0, kDs5TriggerBlock);
+ out[0] = 0x05; // off
+ // Zones `position`..9 each at `level` (1..8, 3 bits as level - 1).
+ auto zones = [&](uint8_t type, int position, int level) {
+ uint16_t active = 0;
+ uint32_t levels = 0;
+ for (int i = std::clamp(position, 0, 9); i < 10; ++i) {
+ active |= static_cast<uint16_t>(1u << i);
+ levels |= static_cast<uint32_t>((level - 1) & 7) << (3 * i);
+ }
+ out[0] = type;
+ out[1] = static_cast<uint8_t>(active);
+ out[2] = static_cast<uint8_t>(active >> 8);
+ for (int b = 0; b < 4; ++b) out[3 + b] = static_cast<uint8_t>(levels >> (8 * b));
+ };
+ if (c.mode == 1 && c.data[1]) {
+ zones(0x21, c.data[0], std::min<int>(c.data[1], 8)); // feedback: resistance from `position` on
+ } else if (c.mode == 3 && c.data[1] && c.data[2]) {
+ zones(0x26, c.data[0], std::min<int>(c.data[1], 8)); // vibration
+ out[9] = c.data[2];
+ }
+}
+
+void ds5TriggerEffects(const TriggerCommand& left, const TriggerCommand& right, uint8_t out[kDs5EffectsSize]) {
+ std::memset(out, 0, kDs5EffectsSize);
+ out[0] = 0x04 | 0x08;
+ ds5TriggerBlock(right, out + kDs5RightTrigger);
+ ds5TriggerBlock(left, out + kDs5LeftTrigger);
+}
+
+} // namespace xc::input
diff --git a/src/input/sdl_mapping.h b/src/input/sdl_mapping.h
new file mode 100644
index 0000000..8b652fe
--- /dev/null
+++ b/src/input/sdl_mapping.h
@@ -0,0 +1,52 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// What the desktop's SDL3 input backends (controller_sdl.cpp, kbm_sdl.cpp)
+// work out, kept free of SDL so the tests check it: SDL's numbers are
+// fixed by its ABI and written out here.
+#pragma once
+
+#include "input/tuning.h"
+
+#include <cstddef>
+#include <cstdint>
+
+namespace xc::input {
+
+// A stick axis (SDL: -32768..32767, +y down) -> -1..1.
+float sdlStickAxis(int16_t v);
+// A trigger (SDL: 0..32767) -> 0..1.
+float sdlTriggerAxis(int16_t v);
+// The accelerometer: SDL reads m/s^2, gyro aiming takes g.
+constexpr float kStandardGravity = 9.80665f; // SDL_STANDARD_GRAVITY
+void sdlAccelToG(const float ms2[3], float g[3]);
+
+// SDL_Scancode values are USB HID usages (keyboard page): the key's
+// Windows virtual-key code (kbm.h), the modifiers (224..231: left ctrl,
+// shift, alt, GUI, then the right ones) as the PS5's modifier bits; 0 for
+// none.
+uint8_t scancodeToVk(int scancode);
+
+// SDL's mouse button mask (left 1, middle 2, right 4, X1 8, X2 16) -> the
+// app's and the wire's (kbm.h: 1 left, 2 right, 4 middle, 8 back, 16 forward).
+uint8_t sdlMouseButtons(uint32_t sdlMask);
+
+// The light bar of player `slot` (0..3) while the app sets none: the
+// player's colour (ui::playerColor: blue, red, green, pink).
+void playerLightColour(int slot, uint8_t rgb[3]);
+
+// The DualSense's effects packet for SDL_SendGamepadEffect (its output
+// report from the enable bits on, as SDL's DS5EffectsState_t): only the two
+// triggers' effects enabled (byte 0: 0x04 right, 0x08 left), the right one's
+// 11-byte block at byte 10, the left one's at 21; rumble and lights left as
+// they are.
+constexpr size_t kDs5EffectsSize = 47;
+constexpr size_t kDs5RightTrigger = 10, kDs5LeftTrigger = 21, kDs5TriggerBlock = 11;
+// One trigger's block for a command (tuning.h): mode 0 -> off (0x05);
+// 1, feedback -> 0x21, the zones from its position to 9 as a 16-bit mask
+// and 3 bits of (strength - 1) per zone; 3, vibration -> 0x26, the zones,
+// (amplitude - 1) per zone, the frequency in byte 9. A zero strength,
+// amplitude or frequency is off too.
+void ds5TriggerBlock(const TriggerCommand& c, uint8_t out[kDs5TriggerBlock]);
+void ds5TriggerEffects(const TriggerCommand& left, const TriggerCommand& right, uint8_t out[kDs5EffectsSize]);
+
+} // namespace xc::input