Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

feat(input): USB controllers as their own players (Xbox, XInput)

Rafael Abud Ferreira17703bfcceb8
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 3fcbf60..1373b9d 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -171,6 +171,7 @@ if(XCLOUD_PS5)
src/media/hw_decoder_ps5.cpp
src/input/controller_ps5.cpp
src/input/kbm_ps5.cpp
+ src/input/pad_usb_ps5.cpp
src/media/audio_out_ps5.cpp
src/media/audio_in_ps5.cpp
)
diff --git a/cmake/platform.cmake b/cmake/platform.cmake
index e5f5277..9865859 100644
--- a/cmake/platform.cmake
+++ b/cmake/platform.cmake
@@ -24,9 +24,8 @@ if(NOT XC_PLATFORM STREQUAL "ps5" AND NOT XC_PLATFORM STREQUAL "ps4")
target_compile_definitions(xc_platform INTERFACE XC_PLATFORM_DESKTOP=1)
endif()
# PS4 behaviours the shared code needs to know about (it may not name the platform):
-# XC_NO_UHID_PADS: no /dev/uhid* USB pads (pads come through libScePad).
# XC_HWDEC_NO_SOFTWARE_FALLBACK: a failing hardware decoder recovers by itself; FFmpeg
# cannot decode the stream in time on this CPU, so it is never switched to.
if(XC_PLATFORM STREQUAL "ps4")
- target_compile_definitions(xc_platform INTERFACE XC_NO_UHID_PADS=1 XC_HWDEC_NO_SOFTWARE_FALLBACK=1)
+ target_compile_definitions(xc_platform INTERFACE XC_HWDEC_NO_SOFTWARE_FALLBACK=1)
endif()
diff --git a/src/app/app_core.cpp b/src/app/app_core.cpp
index c6a1c9e..4b2c771 100644
--- a/src/app/app_core.cpp
+++ b/src/app/app_core.cpp
@@ -917,9 +917,25 @@ bool Core::frame() {
if (virtualGamepadState(0, vpad0, vconn0) && vconn0) {
input::mergePads(pad, vpad0);
}
+ // USB pads (pad_usb.h): every one drives the menus; in a game, those
+ // playing as player 1 join pad 0 (the others: stream_screen.cpp), but
+ // the one whose in-game menu is up.
+ const bool streaming = g_ui->screen() == ui::Screen::Streaming;
+ const int usbMenuOwner = streaming ? streamScreen->menuUsbOwner() : -1;
+ input::ControllerState player1 = pad;
input::ControllerState usbPad;
- if (input::pollUsbPad(usbPad)) {
- input::mergePads(pad, usbPad);
+ if (input::pollUsbPadsFor(0, usbPad, usbMenuOwner)) input::mergePads(player1, usbPad);
+ if (input::pollUsbPad(usbPad)) input::mergePads(pad, usbPad);
+ for (const input::UsbPadEvent& e : input::takeUsbPadEvents()) {
+ if (e.kind == input::UsbPadEvent::Kind::MenuButton) {
+ if (streaming) streamScreen->usbMenuButton(e.slot);
+ continue;
+ }
+ const std::string who = std::to_string(e.player + 1) + " (" + e.name + ")";
+ const bool gone = e.kind == input::UsbPadEvent::Kind::Disconnected;
+ platform::notify(ui::trf(gone ? ui::Str::PadDisconnected : ui::Str::PadConnected, who),
+ "usb controller " + std::to_string(e.player + 1) + (gone ? " disconnected" : " connected"));
+ padsCheckedAt = 0; // the players' row at once
}
// USB keyboard: the app's screens (and its menu in a game) as with the
// controller; in a game otherwise, its keys and the mouse go to the game.
@@ -1106,13 +1122,19 @@ bool Core::frame() {
for (int i = 0; i < input::kMaxPads; ++i) {
bool padConn = input::padConnected(i);
std::string padName = input::padUserName(i);
+ // A USB pad playing as this player: connected too, by its name
+ // when it is the only pad there.
+ const std::string usbName = input::usbPadNameFor(i);
+ if (!usbName.empty() && !padConn) padName = usbName;
+ const bool usbConn = !usbName.empty();
bool vpadConn = false;
input::ControllerState vpadSt{};
virtualGamepadState(i, vpadSt, vpadConn);
uint64_t now = platform::nowMs();
- uint64_t padT = padConn ? input::padActiveAt(i) : 0;
+ uint64_t padT = std::max(padConn ? input::padActiveAt(i) : 0, input::usbPadActiveAt(i));
+ padConn = padConn || usbConn;
uint64_t kbT = (kbmConnected && i == kbPlayer) ? keyboardActiveAt : 0;
uint64_t vpadActive = virtualGamepadActiveAt(i);
uint64_t phoneT = (vpadConn && (now >= vpadActive) && (now - vpadActive < 15000)) ? vpadActive : 0;
@@ -1149,6 +1171,8 @@ bool Core::frame() {
streamScreen->setCaps(caps);
}
+ // The in-game menu a USB controller opened: that controller alone moves in it.
+ if (usbMenuOwner >= 0) input::pollUsbPadSlot(usbMenuOwner, pad);
ui::NavInput nav;
nav.up = up.update(pad.dpadUp || pad.leftStickY < -0.6f, now);
nav.down = down.update(pad.dpadDown || pad.leftStickY > 0.6f, now);
@@ -1222,7 +1246,7 @@ bool Core::frame() {
prev = pad;
autoplayNav(nav, menuCombo, now);
if (g_ui->screen() == ui::Screen::Streaming) {
- streamScreen->update(pad, nav, menuCombo);
+ streamScreen->update(player1, nav, menuCombo);
display::idleWait(4); // ~250 Hz input (the PS5 sleeps 4 ms; matching DualSense native 250 Hz rate)
display::pump(); // the desktop shows the newest video frame here
return true;
diff --git a/src/app/autoplay.cpp b/src/app/autoplay.cpp
index 81e65a3..239132d 100644
--- a/src/app/autoplay.cpp
+++ b/src/app/autoplay.cpp
@@ -1703,6 +1703,38 @@ void autoplayScreens(const ui::Canvas& canvas, uint64_t now) {
ppm += static_cast<char>((p >> 16) & 0xFF);
}
platform::writeFileAtomic(platform::dataDir() + "/stream_menu_muted.ppm", ppm);
+ ++step;
+ } else if (step == 2 && now - since > 6000) {
+ // Opened by a USB controller playing as player 2: its Player row
+ // (selected), the pad's name under its slot.
+ ui::StreamMenu menu(g_ui->fonts());
+ menu.setUsbOwner(1);
+ menu.open(0, false, 1, 1, 0, false, true, false, 2, 15, false, 0.3f, false);
+ ui::NavInput down;
+ down.down = true;
+ menu.handle(down);
+ ui::StreamInfo info;
+ info.region = "Brazil South";
+ info.rttMs = 15;
+ info.fps = 60.0;
+ info.mbps = 20.0;
+ info.width = 1920;
+ info.height = 1080;
+ ui::PadSlots pads{};
+ pads[0].connected = true;
+ pads[0].name = "RafaelNGP";
+ pads[1].connected = true;
+ pads[1].name = "8BitDo Ultimate wireless Controller for PC";
+ menu.setPads(pads);
+ ui::Canvas menuCanvas = menu.renderMenu(info);
+ std::string ppm = "P6\n" + std::to_string(menuCanvas.width()) + " " + std::to_string(menuCanvas.height()) + "\n255\n";
+ for (size_t i = 0; i < static_cast<size_t>(menuCanvas.width() * menuCanvas.height()); ++i) {
+ uint32_t p = menuCanvas.data()[i];
+ ppm += static_cast<char>(p & 0xFF);
+ ppm += static_cast<char>((p >> 8) & 0xFF);
+ ppm += static_cast<char>((p >> 16) & 0xFF);
+ }
+ platform::writeFileAtomic(platform::dataDir() + "/stream_menu_usb.ppm", ppm);
g_autoplay.streamMenuTest = false;
XC_LOGI("AUTOPLAY END: stream menu test");
++step;
diff --git a/src/app/stream_screen.cpp b/src/app/stream_screen.cpp
index ed548f6..e22827b 100644
--- a/src/app/stream_screen.cpp
+++ b/src/app/stream_screen.cpp
@@ -250,6 +250,8 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b
// A new stream, or a new session after a reconnection: the
// other controllers are announced again.
for (bool& a : padAttached_) a = false;
+ for (bool& a : padUsbOnly_) a = false;
+ menuUsbOwner_ = pendingUsbMenu_ = -1;
playerReconnects_ = g_player ? g_player->reconnects() : 0;
}
if (g_player != overlayPlayer_) { // a new stream
@@ -333,9 +335,20 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b
}
prevL3R3_ = l3r3;
- // OPTIONS + TOUCHPAD opens the menu (and closes it again).
+ // OPTIONS + TOUCHPAD opens the menu (and closes it again); so does a
+ // USB controller's Xbox / Home button, for that controller.
+ const int usbMenu = pendingUsbMenu_;
+ pendingUsbMenu_ = -1;
+ if (menu_.isOpen() && menuUsbOwner_ >= 0 && input::usbPadPlayer(menuUsbOwner_) < 0) {
+ menu_.close(); // its controller went away
+ overlaySeq_ = 0;
+ }
bool wasOpen = menu_.isOpen();
- if (!wasOpen && (menuCombo || swipeMenu_) && g_keyboardFor.empty()) {
+ if (!wasOpen && (menuCombo || swipeMenu_ || usbMenu >= 0) && g_keyboardFor.empty()) {
+ menuUsbOwner_ = menuCombo || swipeMenu_ ? -1 : usbMenu;
+ menu_.setUsbOwner(menuUsbOwner_ >= 0 ? input::usbPadPlayer(menuUsbOwner_) : -1);
+ if (menuUsbOwner_ >= 0)
+ XC_LOGI("menu_: opened by usb pad %d (player %d)", menuUsbOwner_, menu_.usbOwnerPlayer() + 1);
swipeMenu_ = false;
menu_.setCircleConfirms(circleConfirms_);
bool allow1440;
@@ -357,7 +370,7 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b
menu_.open(streamResolution_, showStats_, sharpness_, deband_, upscaler_, g_playingHome, allow1440,
hasCustomProfile_, triggerStrength_, deadzone_, circleConfirms_, micLvl, micMuted, padVol);
overlaySeq_ = 0;
- } else if (wasOpen && (menuCombo || swipeMenu_)) {
+ } else if (wasOpen && (menuCombo || swipeMenu_ || (usbMenu >= 0 && usbMenu == menuUsbOwner_))) {
// The same gesture or key closes it again.
swipeMenu_ = false;
menu_.close();
@@ -366,11 +379,18 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b
} else if (wasOpen) {
switch (menu_.handle(nav)) {
case ui::MenuAction::Leave: g_cancel = true; break;
- case ui::MenuAction::XboxButton:
- // A short press, once the menu is gone: the Xbox guide opens.
- g_xboxButtonUntil = platform::nowMs() + 250;
+ case ui::MenuAction::XboxButton: {
+ // A short press, once the menu is gone: the Xbox guide opens,
+ // for the player whose controller opened the menu.
+ const int player = menuUsbOwner_ >= 0 ? std::max(input::usbPadPlayer(menuUsbOwner_), 0) : 0;
+ if (player > 0) xboxUntil_[player] = platform::nowMs() + 250;
+ else g_xboxButtonUntil = platform::nowMs() + 250;
g_player->requestKeyframe();
- XC_LOGI("menu_: Xbox button");
+ XC_LOGI("menu_: Xbox button (player %d)", player + 1);
+ break;
+ }
+ case ui::MenuAction::Player:
+ input::setUsbPadPlayer(menuUsbOwner_, menu_.usbOwnerPlayer());
break;
case ui::MenuAction::PadSpeakerVolume: {
int vol = menu_.padSpeakerVolume();
@@ -570,6 +590,12 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b
}
overlaySeq_ = 0;
}
+ // Closed: the USB controllers wait for their buttons to be let go
+ // (the one that closed it would press them in the game).
+ if (wasOpen && !menu_.isOpen()) {
+ input::usbPadsWaitRelease();
+ menuUsbOwner_ = -1;
+ }
input::KbmInput touchKbm;
bool touchDrag = false;
if (mouseKeyboard_ && touchpadMouse_ && !menu_.isOpen() && g_keyboardFor.empty() && !menuCombo) {
@@ -615,7 +641,8 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b
// and the buttons that closed them until they are let go.
bool held = pad.dpadUp || pad.dpadDown || pad.dpadLeft || pad.dpadRight || pad.btnA || pad.btnB ||
pad.btnX || pad.btnY || pad.btnOptions || pad.btnTouchpad;
- if (menu_.isOpen() || !g_keyboardFor.empty()) padReleased_ = false;
+ // A menu a USB controller opened is that controller's: player 1 plays on.
+ if ((menu_.isOpen() && menuUsbOwner_ < 0) || !g_keyboardFor.empty()) padReleased_ = false;
else if (!held) padReleased_ = true;
if (!padReleased_ || menuCombo) sent = input::ControllerState{};
else if (!menu_.isOpen() && !touchDrag) {
@@ -669,14 +696,6 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b
g_xboxButtonUntil = platform::nowMs() + 250;
}
}
- input::ControllerState usbPad;
- if (input::pollUsbPad(usbPad)) {
- input::mergePads(sent, usbPad);
- if (usbPad.btnNexus) {
- sent.btnNexus = true;
- g_xboxButtonUntil = platform::nowMs() + 250;
- }
- }
}
if (platform::nowMs() < g_xboxButtonUntil) sent.btnNexus = true;
g_player->sendInput(sent);
@@ -730,6 +749,7 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b
for (int i = 1; i < input::kMaxPads; ++i) {
input::ControllerState other;
bool on = input::pollPad(i, other);
+ const bool padOn = on;
input::ControllerState vpad;
bool vconn = false;
if (virtualGamepadState(i, vpad, vconn) && vconn) {
@@ -740,9 +760,22 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b
on = true;
}
}
+ // USB pads playing as this player (pad_usb.h); theirs goes to the
+ // app's menu while it is open.
+ input::ControllerState usb;
+ const bool usbOn = input::pollUsbPadsFor(i, usb, menuUsbOwner());
+ if (usbOn && menu_.isOpen() && menuUsbOwner_ < 0) usb = input::ControllerState{};
+ if (usbOn) {
+ if (on) input::mergePads(other, usb);
+ else other = usb;
+ on = true;
+ }
+ // A USB pad alone: the app told of it as it came (app_core.cpp).
+ const bool usbOnly = usbOn && !padOn && !vconn;
if (on) other = input::applyPadMap(other, padMap_); // the same map as player 1's (the keys keep theirs)
if (on && i == kbSlot) input::mergePads(other, kbPad_); // the keyboard plays with this player's pad
if (on != padAttached_[i]) {
+ const bool quiet = on ? usbOnly : padUsbOnly_[i];
padAttached_[i] = on;
g_player->setPadConnected(i, on);
std::string who = std::to_string(i + 1);
@@ -750,10 +783,13 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b
if (!name.empty()) who += " (" + name + ")";
else if (vconn && !input::padConnected(i)) who += " (Web Gamepad)";
// The PS5 user's name on the TV, not in the log.
- platform::notify(ui::trf(on ? ui::Str::PadConnected : ui::Str::PadDisconnected, who),
- std::string("controller ") + std::to_string(i + 1) +
- (on ? " connected" : " disconnected"));
+ if (!quiet)
+ platform::notify(ui::trf(on ? ui::Str::PadConnected : ui::Str::PadDisconnected, who),
+ std::string("controller ") + std::to_string(i + 1) +
+ (on ? " connected" : " disconnected"));
}
+ padUsbOnly_[i] = on && usbOnly;
+ if (on && platform::nowMs() < xboxUntil_[i]) other.btnNexus = true;
if (on) g_player->sendInput(other, i);
}
// The window holds the mouse while the keyboard and mouse go to the
@@ -851,6 +887,8 @@ void StreamScreen::idle() {
if (wasStreaming_) {
wasStreaming_ = false;
for (bool& a : padAttached_) a = false;
+ for (bool& a : padUsbOnly_) a = false;
+ menuUsbOwner_ = pendingUsbMenu_ = -1;
overlayPlayer_ = nullptr;
std::lock_guard<std::mutex> lock(g_settingsMutex);
input::setDeadzone(g_settings.deadzoneLeft / 100.0f, g_settings.deadzoneRight / 100.0f);
diff --git a/src/app/stream_screen.h b/src/app/stream_screen.h
index d585c82..c94cbf1 100644
--- a/src/app/stream_screen.h
+++ b/src/app/stream_screen.h
@@ -38,6 +38,12 @@ public:
// is closed (update() sends them).
void setKbm(input::KbmInput kbm) { kbm_ = std::move(kbm); }
bool menuOpen() const;
+ // A USB controller's Xbox / Home button (input/pad_usb.h): the in-game
+ // menu for that controller, or closed again by it. While it is up, that
+ // controller alone moves in it (menuUsbOwner(): its slot, -1 when the
+ // menu is closed or player 1's) and the other players keep playing.
+ void usbMenuButton(int slot) { pendingUsbMenu_ = slot; }
+ int menuUsbOwner() const { return menu_.isOpen() ? menuUsbOwner_ : -1; }
// The hints changed device (keyboard / controller): the overlay again.
void redrawMenu();
// What the display and the pads can do: the game menu hides the rest.
@@ -73,6 +79,9 @@ private:
int upscaler_ = 0; // as Settings::upscaler
bool padReleased_ = true;
bool padAttached_[input::kMaxPads] = {}; // controllers 1..3 announced to the stream
+ bool padUsbOnly_[input::kMaxPads] = {}; // ...by a USB pad alone (told of by app_core.cpp)
+ int menuUsbOwner_ = -1, pendingUsbMenu_ = -1; // usbMenuButton()
+ uint64_t xboxUntil_[input::kMaxPads] = {}; // players 2..4: the menu's Xbox button pressed for them
uint32_t playerReconnects_ = 0;
uint32_t overlaySeq_ = 0; // g_infoSeq + 1 when drawn; 0 = redraw
bool hasCustomProfile_ = false;
diff --git a/src/input/controller.h b/src/input/controller.h
index b73d155..c345ea0 100644
--- a/src/input/controller.h
+++ b/src/input/controller.h
@@ -91,6 +91,10 @@ void setTriggerRumble(uint8_t left, uint8_t right, uint32_t durationMs, int pad
// Each stick's own dead zone (0..1 of the travel): a drifting stick can
// have a bigger one.
void setDeadzone(float left, float right);
+// A pad read some other way (USB, pad_usb.h) as the DualSense's are: the
+// dead zones above on its sticks (rawLeftX... kept) and the Circle / Cross
+// swap below.
+void applyPadSettings(ControllerState& s);
// Circle reported as Cross (Xbox A) and Cross as Circle, everywhere.
void setCircleConfirms(bool on);
bool circleConfirms();
diff --git a/src/input/controller_common.cpp b/src/input/controller_common.cpp
index cf7b921..0df6188 100644
--- a/src/input/controller_common.cpp
+++ b/src/input/controller_common.cpp
@@ -254,6 +254,14 @@ void setDeadzone(float left, float right) {
g_deadzone[1] = std::clamp(right, 0.0f, 0.5f);
}
+void applyPadSettings(ControllerState& s) {
+ if (g_circleConfirms) std::swap(s.btnA, s.btnB);
+ s.leftStickX = s.rawLeftX, s.leftStickY = s.rawLeftY;
+ s.rightStickX = s.rawRightX, s.rightStickY = s.rawRightY;
+ radialDeadzone(s.leftStickX, s.leftStickY, g_deadzone[0].load(std::memory_order_relaxed));
+ radialDeadzone(s.rightStickX, s.rightStickY, g_deadzone[1].load(std::memory_order_relaxed));
+}
+
bool pollPad(int index, ControllerState& out) {
out = {};
if (index < 0 || index >= kMaxPads || !backend::padOpen(index)) return false;
diff --git a/src/input/controller_ps5.cpp b/src/input/controller_ps5.cpp
index 41ba860..8a938ae 100644
--- a/src/input/controller_ps5.cpp
+++ b/src/input/controller_ps5.cpp
@@ -7,6 +7,7 @@
#include "input/controller.h"
#include "input/controller_backend.h"
#include "input/input_ext.h"
+#include "input/pad_usb.h"
#include "util/log.h"
#include <algorithm>
@@ -292,6 +293,7 @@ bool init() {
}
if (!openPad(0, uid)) return false;
refreshPads();
+ usbPadsStart(); // Xbox / XInput pads on USB, as pad 0 too (pad_usb.h)
return true;
}
@@ -322,6 +324,7 @@ void refreshPads() {
}
void shutdown() {
+ usbPadsStop();
for (int i = 0; i < kMaxPads; ++i) closePad(i);
}
diff --git a/src/input/pad_usb.cpp b/src/input/pad_usb.cpp
index 3ca58c0..0d6123b 100644
--- a/src/input/pad_usb.cpp
+++ b/src/input/pad_usb.cpp
@@ -1,509 +1,342 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 RafaelNGP
-// USB HID driver for 8BitDo Ultimate 2.4G wireless adapter on PS5 /dev/uhid* in D-Input mode.
+// USB pads (pad_usb.h): their reports parsed, and their state kept for
+// pollUsbPad(). The report layouts are those of the Linux xpad driver and
+// OmniPad CE (usb_controllers.c).
#include "input/pad_usb.h"
+
+#include "input/keyboard_nav.h"
#include "platform/platform.h"
#include "util/log.h"
#include <algorithm>
#include <array>
-#include <cmath>
-#include <cstring>
#include <mutex>
-#include <vector>
-
-// XC_NO_UHID_PADS (PS4): pads come through the system there, and /dev/uhid* does not
-// exist (the scan only cost an open() per node every 2 s).
-#if (defined(__unix__) || defined(__linux__) || defined(__APPLE__) || defined(__posix)) && !defined(XC_NO_UHID_PADS)
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-#define XC_HAS_UHID_POSIX 1
-#else
-#define XC_HAS_UHID_POSIX 0
-#endif
-
-#include "input/keyboard_nav.h"
namespace xc::input {
namespace {
-std::mutex g_usbPadMutex;
-bool g_initialized = false;
-ControllerState g_lastUsbState{};
-uint64_t g_lastPacketMs = 0;
-std::array<ControllerState, 8> g_slotStates{};
-std::array<uint64_t, 8> g_slotPacketMs{};
-
-std::vector<uint8_t> g_testReport;
-bool g_hasTestReport = false;
-std::array<std::vector<uint8_t>, 8> g_slotTestReports;
-std::array<bool, 8> g_hasSlotTestReport{};
-
-#if XC_HAS_UHID_POSIX
-std::array<int, 8> g_uhidFds = {-1, -1, -1, -1, -1, -1, -1, -1};
-uint64_t g_lastScanMs = 0;
-
-void scanUhidDevices() {
- uint64_t now = platform::nowMs();
- if (now - g_lastScanMs < 2000) {
- return;
- }
- g_lastScanMs = now;
-
- // Check existing fds and scan for unopened nodes
- for (int i = 0; i < 8; ++i) {
- if (g_uhidFds[i] >= 0) {
- struct stat st{};
- if (fstat(g_uhidFds[i], &st) < 0) {
- close(g_uhidFds[i]);
- g_uhidFds[i] = -1;
- g_slotStates[i] = ControllerState{};
- g_slotPacketMs[i] = 0;
- }
- }
- if (g_uhidFds[i] < 0) {
- char path[32];
- std::snprintf(path, sizeof(path), "/dev/uhid%d", i);
- int fd = open(path, O_RDONLY | O_NONBLOCK);
- if (fd >= 0) {
- XC_LOGI("usb pad: opened %s (fd %d)", path, fd);
- g_uhidFds[i] = fd;
- g_slotStates[i] = ControllerState{};
- g_slotPacketMs[i] = 0;
+int16_t le16(const uint8_t* p) { return static_cast<int16_t>(p[0] | (p[1] << 8)); }
+
+float stick(int16_t v) { return std::clamp(static_cast<float>(v) / 32767.0f, -1.0f, 1.0f); }
+
+// XInput and GIP sticks have +y up; ControllerState has +y down.
+void setSticks(ControllerState& s, const uint8_t* p) {
+ s.rawLeftX = s.leftStickX = stick(le16(p));
+ s.rawLeftY = s.leftStickY = -stick(le16(p + 2));
+ s.rawRightX = s.rightStickX = stick(le16(p + 4));
+ s.rawRightY = s.rightStickY = -stick(le16(p + 6));
+}
+
+struct Slot {
+ bool attached = false;
+ std::string name;
+ ControllerState state; // as read; connected once its first input came
+ int player = -1; // -1: given one at the next poll
+ uint64_t order = 0; // when it came, for the players' order
+ // The Xbox / Home button held: LB / RB move the pad to another player;
+ // let go without them, it asks for the in-game menu. It never reaches
+ // the game itself (the menu has an Xbox button item).
+ bool guideHeld = false, comboUsed = false;
+ bool waitRelease = false; // out of the game until every button is let go
+ uint64_t activeAt = 0;
+};
+
+std::mutex g_mutex;
+std::array<Slot, kMaxUsbPads> g_slots;
+std::vector<UsbPadEvent> g_events;
+uint64_t g_attachCount = 0;
+
+// The players for the pads that came since the last poll, in their order.
+void assignPlayers() {
+ for (;;) {
+ Slot* next = nullptr;
+ for (Slot& s : g_slots)
+ if (s.attached && s.player < 0 && (!next || s.order < next->order)) next = &s;
+ if (!next) return;
+ next->player = 0; // all taken: the first player
+ for (int p = 0; p < kMaxPads; ++p) {
+ bool taken = padConnected(p);
+ for (const Slot& o : g_slots) taken |= o.attached && o.player == p && &o != next;
+ if (!taken) {
+ next->player = p;
+ break;
}
}
+ XC_LOGI("usb pad: %s plays as player %d", next->name.c_str(), next->player + 1);
+ g_events.push_back({UsbPadEvent::Kind::Connected, next->player, next->name, static_cast<int>(next - g_slots.data())});
}
}
-#endif
-} // namespace
+// A pad's state for the game and the menus: the settings applied, LB / RB
+// held back while the Xbox button is down, the Xbox button itself never.
+ControllerState shown(const Slot& slot) {
+ ControllerState s = slot.state;
+ applyPadSettings(s);
+ if (slot.guideHeld) s.btnL1 = s.btnR1 = false;
+ s.btnNexus = false;
+ return s;
+}
-bool parse8BitDoDInputReport(const uint8_t* data, size_t len, ControllerState& out) {
- if (!data || len < 16) {
- return false;
- }
+void movePlayer(Slot& s, int slot, int player) {
+ s.player = player;
+ XC_LOGI("usb pad %d: %s moved to player %d", slot, s.name.c_str(), player + 1);
+ g_events.push_back({UsbPadEvent::Kind::Moved, player, s.name, slot});
+}
+// `player` -1: every pad (the menus, so a pad waiting for its buttons to be
+// let go too); otherwise those playing as it, but `except`.
+bool pollWhere(int player, int except, ControllerState& out) {
out = ControllerState{};
- out.connected = true;
-
- // Analog sticks: 0..255 (128 center) -> [-1.0 .. 1.0]
- out.rawLeftX = std::clamp((static_cast<float>(data[0]) - 128.0f) / 128.0f, -1.0f, 1.0f);
- out.rawLeftY = std::clamp((static_cast<float>(data[1]) - 128.0f) / 128.0f, -1.0f, 1.0f);
- out.rawRightX = std::clamp((static_cast<float>(data[2]) - 128.0f) / 128.0f, -1.0f, 1.0f);
- out.rawRightY = std::clamp((static_cast<float>(data[3]) - 128.0f) / 128.0f, -1.0f, 1.0f);
-
- out.leftStickX = std::abs(out.rawLeftX) < 0.05f ? 0.0f : out.rawLeftX;
- out.leftStickY = std::abs(out.rawLeftY) < 0.05f ? 0.0f : out.rawLeftY;
- out.rightStickX = std::abs(out.rawRightX) < 0.05f ? 0.0f : out.rawRightX;
- out.rightStickY = std::abs(out.rawRightY) < 0.05f ? 0.0f : out.rawRightY;
-
- // Triggers L2/R2: 0..255 -> [0.0 .. 1.0]
- out.triggerL2 = std::clamp(static_cast<float>(data[4]) / 255.0f, 0.0f, 1.0f);
- out.triggerR2 = std::clamp(static_cast<float>(data[5]) / 255.0f, 0.0f, 1.0f);
-
- // D-Pad: data[6] (Hat switch: 0..7 directions, 8 / 0x0F = neutral)
- uint8_t hat = data[6] & 0x0F;
- if (hat <= 7) {
- out.dpadUp = (hat == 7 || hat == 0 || hat == 1);
- out.dpadRight = (hat == 1 || hat == 2 || hat == 3);
- out.dpadDown = (hat == 3 || hat == 4 || hat == 5);
- out.dpadLeft = (hat == 5 || hat == 6 || hat == 7);
- } else {
- out.dpadUp = false;
- out.dpadRight = false;
- out.dpadDown = false;
- out.dpadLeft = false;
+ bool any = false;
+ std::lock_guard<std::mutex> lock(g_mutex);
+ assignPlayers();
+ for (size_t i = 0; i < g_slots.size(); ++i) {
+ const Slot& slot = g_slots[i];
+ if (!slot.attached || !slot.state.connected) continue;
+ if (player >= 0 && (slot.player != player || slot.waitRelease || static_cast<int>(i) == except)) continue;
+ ControllerState s = shown(slot);
+ if (any) mergePads(out, s);
+ else out = s;
+ any = true;
}
+ return any;
+}
- // Action buttons: data[7]
- out.btnA = (data[7] & 0x01) != 0;
- out.btnB = (data[7] & 0x02) != 0;
- out.btnX = (data[7] & 0x04) != 0;
- out.btnY = (data[7] & 0x08) != 0;
- out.btnL1 = (data[7] & 0x10) != 0;
- out.btnR1 = (data[7] & 0x20) != 0;
- if ((data[7] & 0x40) != 0) out.triggerL2 = 1.0f;
- if ((data[7] & 0x80) != 0) out.triggerR2 = 1.0f;
-
- // System buttons: data[8]
- out.btnTouchpad = (data[8] & 0x01) != 0; // Select / View
- out.btnOptions = (data[8] & 0x02) != 0; // Start / Menu
- out.btnNexus = (data[8] & 0x04) != 0; // Home / Xbox Guide
- out.btnL3 = (data[8] & 0x08) != 0;
- out.btnR3 = (data[8] & 0x10) != 0;
+} // namespace
- return true;
+UsbPadProtocol usbPadProtocolFor(uint8_t ifaceClass, uint8_t ifaceSubclass, uint8_t ifaceProtocol) {
+ if (ifaceClass != 0xFF) return UsbPadProtocol::None;
+ if (ifaceSubclass == 0x5D && ifaceProtocol == 0x01) return UsbPadProtocol::XInput;
+ if (ifaceSubclass == 0x47 && ifaceProtocol == 0xD0) return UsbPadProtocol::Gip;
+ return UsbPadProtocol::None;
}
-bool parseXbox360Report(const uint8_t* data, size_t len, ControllerState& out) {
- if (!data || len < 12) return false;
-
- size_t off = 0;
- if (len >= 20 && data[0] == 0x00 && data[1] == 0x14) {
- off = 2;
- } else if (len >= 18 && data[0] == 0x00 && data[3] == 0x14) {
- off = 4;
- } else if (len >= 14 && data[0] == 0x00 && (data[1] == 0x14 || data[1] == 0x00)) {
- off = 2;
+UsbPadInterface findUsbPadInterface(const uint8_t* d, size_t len) {
+ UsbPadInterface pad;
+ bool inPad = false; // the endpoints that follow are the pad interface's
+ for (size_t off = 0; d && off + 2 <= len; off += d[off]) {
+ const size_t l = d[off];
+ if (l < 2 || off + l > len) break;
+ if (d[off + 1] == 0x04 && l >= 9) { // an interface
+ if (inPad && pad.epIn) return pad;
+ pad = {usbPadProtocolFor(d[off + 5], d[off + 6], d[off + 7]), d[off + 2], 0, 0};
+ inPad = pad.protocol != UsbPadProtocol::None && d[off + 3] == 0;
+ } else if (d[off + 1] == 0x05 && l >= 7 && inPad && (d[off + 3] & 0x03) == 0x03) { // an interrupt endpoint
+ const uint8_t addr = d[off + 2];
+ uint8_t& ep = (addr & 0x80) ? pad.epIn : pad.epOut;
+ if (!ep) ep = addr;
+ }
}
+ return inPad && pad.epIn ? pad : UsbPadInterface{};
+}
- if (len < off + 12) return false;
-
- out = ControllerState{};
- out.connected = true;
-
- uint8_t b1 = data[off];
- out.dpadUp = (b1 & 0x01) != 0;
- out.dpadDown = (b1 & 0x02) != 0;
- out.dpadLeft = (b1 & 0x04) != 0;
- out.dpadRight = (b1 & 0x08) != 0;
- out.btnOptions = (b1 & 0x10) != 0; // Start
- out.btnTouchpad = (b1 & 0x20) != 0; // Back / View
- out.btnL3 = (b1 & 0x40) != 0;
- out.btnR3 = (b1 & 0x80) != 0;
-
- uint8_t b2 = data[off + 1];
- out.btnL1 = (b2 & 0x01) != 0;
- out.btnR1 = (b2 & 0x02) != 0;
- out.btnNexus = (b2 & 0x04) != 0; // Guide
- out.btnA = (b2 & 0x10) != 0;
- out.btnB = (b2 & 0x20) != 0;
- out.btnX = (b2 & 0x40) != 0;
- out.btnY = (b2 & 0x80) != 0;
-
- out.triggerL2 = std::clamp(static_cast<float>(data[off + 2]) / 255.0f, 0.0f, 1.0f);
- out.triggerR2 = std::clamp(static_cast<float>(data[off + 3]) / 255.0f, 0.0f, 1.0f);
-
- int16_t lx = static_cast<int16_t>(data[off + 4] | (data[off + 5] << 8));
- int16_t ly = static_cast<int16_t>(data[off + 6] | (data[off + 7] << 8));
- int16_t rx = static_cast<int16_t>(data[off + 8] | (data[off + 9] << 8));
- int16_t ry = static_cast<int16_t>(data[off + 10] | (data[off + 11] << 8));
-
- out.rawLeftX = std::clamp(static_cast<float>(lx) / 32768.0f, -1.0f, 1.0f);
- out.rawLeftY = std::clamp(-static_cast<float>(ly) / 32768.0f, -1.0f, 1.0f);
- out.rawRightX = std::clamp(static_cast<float>(rx) / 32768.0f, -1.0f, 1.0f);
- out.rawRightY = std::clamp(-static_cast<float>(ry) / 32768.0f, -1.0f, 1.0f);
-
- out.leftStickX = std::abs(out.rawLeftX) < 0.05f ? 0.0f : out.rawLeftX;
- out.leftStickY = std::abs(out.rawLeftY) < 0.05f ? 0.0f : out.rawLeftY;
- out.rightStickX = std::abs(out.rawRightX) < 0.05f ? 0.0f : out.rawRightX;
- out.rightStickY = std::abs(out.rawRightY) < 0.05f ? 0.0f : out.rawRightY;
+std::vector<std::array<uint8_t, 13>> gipAcksFor(const uint8_t* data, size_t len) {
+ std::vector<std::array<uint8_t, 13>> acks;
+ for (size_t off = 0; data && off + 4 <= len;) {
+ const uint8_t* m = data + off;
+ const size_t payload = m[3];
+ if ((m[3] & 0x80) || payload < 2 || payload > 60 || off + 4 + payload > len) break;
+ off += 4 + payload;
+ if (!(m[1] & 0x10)) continue;
+ const auto client = static_cast<uint8_t>((m[1] & 0x0f) | 0x20);
+ acks.push_back({0x01, client, m[2], 0x09, 0x00, m[0], client, static_cast<uint8_t>(payload), 0, 0, 0, 0, 0});
+ }
+ return acks;
+}
+// 00 14 | buttons (16 bits) | LT | RT | LX LY RX RY (16 bits each) | ...
+// Clones fill the length byte in their own way; the type and the size
+// tell an input report from the LED (01), rumble (03) and status ones.
+bool parseXInputReport(const uint8_t* data, size_t len, ControllerState& s) {
+ if (!data || len < 14 || data[0] != 0x00) return false;
+ const unsigned b = static_cast<unsigned>(data[2] | (data[3] << 8));
+ s.dpadUp = b & 0x0001;
+ s.dpadDown = b & 0x0002;
+ s.dpadLeft = b & 0x0004;
+ s.dpadRight = b & 0x0008;
+ s.btnOptions = b & 0x0010; // Start (Menu)
+ s.btnTouchpad = b & 0x0020; // Back (View)
+ s.btnL3 = b & 0x0040;
+ s.btnR3 = b & 0x0080;
+ s.btnL1 = b & 0x0100;
+ s.btnR1 = b & 0x0200;
+ s.btnNexus = b & 0x0400; // Guide
+ s.btnA = b & 0x1000;
+ s.btnB = b & 0x2000;
+ s.btnX = b & 0x4000;
+ s.btnY = b & 0x8000;
+ s.triggerL2 = static_cast<float>(data[4]) / 255.0f;
+ s.triggerR2 = static_cast<float>(data[5]) / 255.0f;
+ setSticks(s, data + 6);
+ s.connected = true;
return true;
}
-bool parseXboxOneReport(const uint8_t* data, size_t len, ControllerState& out) {
- if (!data || len < 18) return false;
-
- // Standard GIP report starts with 0x20
- size_t off = 0;
- if (data[0] == 0x20) {
- off = 4;
- }
- if (len < off + 14) return false;
-
- out = ControllerState{};
- out.connected = true;
-
- uint8_t b1 = data[off];
- out.btnOptions = (b1 & 0x04) != 0; // Menu
- out.btnTouchpad = (b1 & 0x08) != 0; // View
- out.btnA = (b1 & 0x10) != 0;
- out.btnB = (b1 & 0x20) != 0;
- out.btnX = (b1 & 0x40) != 0;
- out.btnY = (b1 & 0x80) != 0;
-
- uint8_t b2 = data[off + 1];
- out.dpadUp = (b2 & 0x01) != 0;
- out.dpadDown = (b2 & 0x02) != 0;
- out.dpadLeft = (b2 & 0x04) != 0;
- out.dpadRight = (b2 & 0x08) != 0;
- out.btnL1 = (b2 & 0x10) != 0;
- out.btnR1 = (b2 & 0x20) != 0;
- out.btnL3 = (b2 & 0x40) != 0;
- out.btnR3 = (b2 & 0x80) != 0;
-
- uint16_t trigL = static_cast<uint16_t>(data[off + 2] | (data[off + 3] << 8));
- uint16_t trigR = static_cast<uint16_t>(data[off + 4] | (data[off + 5] << 8));
- out.triggerL2 = std::clamp(static_cast<float>(trigL) / 1023.0f, 0.0f, 1.0f);
- out.triggerR2 = std::clamp(static_cast<float>(trigR) / 1023.0f, 0.0f, 1.0f);
-
- int16_t lx = static_cast<int16_t>(data[off + 6] | (data[off + 7] << 8));
- int16_t ly = static_cast<int16_t>(data[off + 8] | (data[off + 9] << 8));
- int16_t rx = static_cast<int16_t>(data[off + 10] | (data[off + 11] << 8));
- int16_t ry = static_cast<int16_t>(data[off + 12] | (data[off + 13] << 8));
-
- out.rawLeftX = std::clamp(static_cast<float>(lx) / 32768.0f, -1.0f, 1.0f);
- out.rawLeftY = std::clamp(-static_cast<float>(ly) / 32768.0f, -1.0f, 1.0f);
- out.rawRightX = std::clamp(static_cast<float>(rx) / 32768.0f, -1.0f, 1.0f);
- out.rawRightY = std::clamp(-static_cast<float>(ry) / 32768.0f, -1.0f, 1.0f);
-
- out.leftStickX = std::abs(out.rawLeftX) < 0.05f ? 0.0f : out.rawLeftX;
- out.leftStickY = std::abs(out.rawLeftY) < 0.05f ? 0.0f : out.rawLeftY;
- out.rightStickX = std::abs(out.rawRightX) < 0.05f ? 0.0f : out.rawRightX;
- out.rightStickY = std::abs(out.rawRightY) < 0.05f ? 0.0f : out.rawRightY;
-
- if (len >= off + 15 && (data[off + 14] & 0x01)) {
- out.btnNexus = true;
+// A GIP message: command | options | sequence | payload length | payload.
+// 0x20, the input: buttons (16 bits) | LT RT (0..1023) | LX LY RX RY. The
+// Xbox button comes by itself, in a 0x07 message (bit 0 of its payload).
+bool parseGipReport(const uint8_t* data, size_t len, ControllerState& s) {
+ if (!data || len < 5) return false;
+ if (data[0] == 0x07) {
+ s.btnNexus = data[4] & 0x01;
+ s.connected = true;
+ return true;
}
-
+ if (data[0] != 0x20 || len < 18) return false;
+ const unsigned b = static_cast<unsigned>(data[4] | (data[5] << 8));
+ s.btnOptions = b & 0x0004; // Menu
+ s.btnTouchpad = b & 0x0008; // View
+ s.btnA = b & 0x0010;
+ s.btnB = b & 0x0020;
+ s.btnX = b & 0x0040;
+ s.btnY = b & 0x0080;
+ s.dpadUp = b & 0x0100;
+ s.dpadDown = b & 0x0200;
+ s.dpadLeft = b & 0x0400;
+ s.dpadRight = b & 0x0800;
+ s.btnL1 = b & 0x1000;
+ s.btnR1 = b & 0x2000;
+ s.btnL3 = b & 0x4000;
+ s.btnR3 = b & 0x8000;
+ s.triggerL2 = std::min(static_cast<float>(static_cast<uint16_t>(le16(data + 6))) / 1023.0f, 1.0f);
+ s.triggerR2 = std::min(static_cast<float>(static_cast<uint16_t>(le16(data + 8))) / 1023.0f, 1.0f);
+ setSticks(s, data + 10);
+ s.connected = true;
return true;
}
-bool parseDualShock4Report(const uint8_t* data, size_t len, ControllerState& out) {
- if (!data || len < 10) return false;
+bool parseUsbPadReport(UsbPadProtocol protocol, const uint8_t* data, size_t len, ControllerState& state) {
+ switch (protocol) {
+ case UsbPadProtocol::XInput: return parseXInputReport(data, len, state);
+ case UsbPadProtocol::Gip: return parseGipReport(data, len, state);
+ case UsbPadProtocol::None: break;
+ }
+ return false;
+}
- size_t off = (data[0] == 0x01) ? 1 : 0;
- if (len < off + 9) return false;
+void usbPadAttached(int slot, const std::string& name) {
+ if (slot < 0 || slot >= kMaxUsbPads) return;
+ std::lock_guard<std::mutex> lock(g_mutex);
+ g_slots[slot] = Slot{};
+ g_slots[slot].attached = true;
+ g_slots[slot].name = name;
+ g_slots[slot].order = ++g_attachCount;
+ XC_LOGI("usb pad %d: %s connected", slot, name.c_str());
+}
- out = ControllerState{};
- out.connected = true;
-
- out.rawLeftX = std::clamp((static_cast<float>(data[off]) - 128.0f) / 128.0f, -1.0f, 1.0f);
- out.rawLeftY = std::clamp((static_cast<float>(data[off + 1]) - 128.0f) / 128.0f, -1.0f, 1.0f);
- out.rawRightX = std::clamp((static_cast<float>(data[off + 2]) - 128.0f) / 128.0f, -1.0f, 1.0f);
- out.rawRightY = std::clamp((static_cast<float>(data[off + 3]) - 128.0f) / 128.0f, -1.0f, 1.0f);
-
- out.leftStickX = std::abs(out.rawLeftX) < 0.05f ? 0.0f : out.rawLeftX;
- out.leftStickY = std::abs(out.rawLeftY) < 0.05f ? 0.0f : out.rawLeftY;
- out.rightStickX = std::abs(out.rawRightX) < 0.05f ? 0.0f : out.rawRightX;
- out.rightStickY = std::abs(out.rawRightY) < 0.05f ? 0.0f : out.rawRightY;
-
- uint8_t hatAndButtons = data[off + 4];
- uint8_t hat = hatAndButtons & 0x0F;
- if (hat <= 7) {
- out.dpadUp = (hat == 7 || hat == 0 || hat == 1);
- out.dpadRight = (hat == 1 || hat == 2 || hat == 3);
- out.dpadDown = (hat == 3 || hat == 4 || hat == 5);
- out.dpadLeft = (hat == 5 || hat == 6 || hat == 7);
- }
- out.btnX = (hatAndButtons & 0x10) != 0; // Square -> Xbox X
- out.btnA = (hatAndButtons & 0x20) != 0; // Cross -> Xbox A
- out.btnB = (hatAndButtons & 0x40) != 0; // Circle -> Xbox B
- out.btnY = (hatAndButtons & 0x80) != 0; // Triangle -> Xbox Y
-
- uint8_t b2 = data[off + 5];
- out.btnL1 = (b2 & 0x01) != 0;
- out.btnR1 = (b2 & 0x02) != 0;
- out.btnTouchpad = (b2 & 0x10) != 0; // Share
- out.btnOptions = (b2 & 0x20) != 0; // Options
- out.btnL3 = (b2 & 0x40) != 0;
- out.btnR3 = (b2 & 0x80) != 0;
-
- if (len >= off + 7) {
- uint8_t b3 = data[off + 6];
- out.btnNexus = (b3 & 0x01) != 0; // PS Button
- if (b3 & 0x02) out.btnTouchpad = true; // Touchpad click
+void usbPadState(int slot, const ControllerState& in) {
+ if (slot < 0 || slot >= kMaxUsbPads) return;
+ std::lock_guard<std::mutex> lock(g_mutex);
+ Slot& s = g_slots[slot];
+ if (!s.attached) return;
+ if (in.btnNexus && !s.guideHeld) s.guideHeld = true, s.comboUsed = false;
+ if (s.guideHeld) {
+ const int step = in.btnR1 && !s.state.btnR1 ? 1 : in.btnL1 && !s.state.btnL1 ? -1 : 0;
+ if (step && s.player >= 0) {
+ movePlayer(s, slot, (s.player + step + kMaxPads) % kMaxPads);
+ s.comboUsed = true;
+ }
+ if (!in.btnNexus) {
+ s.guideHeld = false;
+ if (!s.comboUsed && s.player >= 0) g_events.push_back({UsbPadEvent::Kind::MenuButton, s.player, s.name, slot});
+ }
}
+ s.state = in;
+ s.state.connected = true;
+ ControllerState used = in;
+ applyPadSettings(used);
+ const bool pressed = inUse(used) || in.btnNexus;
+ if (pressed) s.activeAt = platform::nowMs();
+ else s.waitRelease = false;
+}
- if (len >= off + 9) {
- out.triggerL2 = std::clamp(static_cast<float>(data[off + 7]) / 255.0f, 0.0f, 1.0f);
- out.triggerR2 = std::clamp(static_cast<float>(data[off + 8]) / 255.0f, 0.0f, 1.0f);
- } else {
- if (b2 & 0x04) out.triggerL2 = 1.0f;
- if (b2 & 0x08) out.triggerR2 = 1.0f;
+void usbPadDetached(int slot) {
+ if (slot < 0 || slot >= kMaxUsbPads) return;
+ std::lock_guard<std::mutex> lock(g_mutex);
+ Slot& s = g_slots[slot];
+ if (s.attached) {
+ XC_LOGI("usb pad %d: %s disconnected", slot, s.name.c_str());
+ if (s.player >= 0) g_events.push_back({UsbPadEvent::Kind::Disconnected, s.player, s.name, slot});
}
-
- return true;
+ s = Slot{};
}
-bool parseGenericArcadeReport(const uint8_t* data, size_t len, ControllerState& out) {
- if (!data || len < 6) return false;
-
- out = ControllerState{};
- out.connected = true;
-
- out.rawLeftX = std::clamp((static_cast<float>(data[0]) - 128.0f) / 128.0f, -1.0f, 1.0f);
- out.rawLeftY = std::clamp((static_cast<float>(data[1]) - 128.0f) / 128.0f, -1.0f, 1.0f);
- out.leftStickX = std::abs(out.rawLeftX) < 0.05f ? 0.0f : out.rawLeftX;
- out.leftStickY = std::abs(out.rawLeftY) < 0.05f ? 0.0f : out.rawLeftY;
-
- // In arcade sticks, direction stick is often mapped to Hat switch or D-Pad
- if (out.rawLeftY < -0.5f) out.dpadUp = true;
- if (out.rawLeftY > 0.5f) out.dpadDown = true;
- if (out.rawLeftX < -0.5f) out.dpadLeft = true;
- if (out.rawLeftX > 0.5f) out.dpadRight = true;
-
- // Action buttons (1-8): data[4]
- uint8_t b4 = data[4];
- out.btnA = (b4 & 0x01) != 0;
- out.btnB = (b4 & 0x02) != 0;
- out.btnX = (b4 & 0x04) != 0;
- out.btnY = (b4 & 0x08) != 0;
- out.btnL1 = (b4 & 0x10) != 0;
- out.btnR1 = (b4 & 0x20) != 0;
- if (b4 & 0x40) out.triggerL2 = 1.0f;
- if (b4 & 0x80) out.triggerR2 = 1.0f;
-
- uint8_t b5 = data[5];
- if ((b5 & 0x01) != 0) out.btnTouchpad = true; // Select / View
- if ((b5 & 0x02) != 0) out.btnOptions = true; // Start / Menu
- if ((b5 & 0x04) != 0) out.btnL3 = true;
- if ((b5 & 0x08) != 0) out.btnR3 = true;
- if ((b5 & 0x10) != 0) out.btnNexus = true; // Home
-
- return true;
+int usbPadPlayer(int slot) {
+ if (slot < 0 || slot >= kMaxUsbPads) return -1;
+ std::lock_guard<std::mutex> lock(g_mutex);
+ return g_slots[slot].attached ? g_slots[slot].player : -1;
}
-bool parseUsbPadReport(const uint8_t* data, size_t len, ControllerState& out) {
- if (!data || len == 0) return false;
-
- if (data[0] == 0x20 && len >= 18) {
- return parseXboxOneReport(data, len, out);
- }
- if (data[0] == 0x00 && len >= 14 && (data[1] == 0x14 || (len >= 18 && data[3] == 0x14))) {
- return parseXbox360Report(data, len, out);
- }
- if (data[0] == 0x01 && len >= 10 && ((data[5] & 0x0F) <= 8)) {
- return parseDualShock4Report(data, len, out);
- }
- if (len >= 16 && (data[6] & 0x0F) <= 8) {
- return parse8BitDoDInputReport(data, len, out);
- }
- if (len >= 6) {
- return parseGenericArcadeReport(data, len, out);
- }
- return false;
+std::vector<UsbPadEvent> takeUsbPadEvents() {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ std::vector<UsbPadEvent> events;
+ events.swap(g_events);
+ return events;
}
-void padUsbInjectReportForTesting(const uint8_t* data, size_t len) {
- padUsbInjectSlotReportForTesting(0, data, len);
-}
+bool pollUsbPad(ControllerState& out) { return pollWhere(-1, -1, out); }
-void padUsbInjectSlotReportForTesting(int slot, const uint8_t* data, size_t len) {
- std::lock_guard<std::mutex> lock(g_usbPadMutex);
- if (slot < 0 || slot >= 8) return;
- if (!data || len == 0) {
- g_hasSlotTestReport[slot] = false;
- g_slotTestReports[slot].clear();
- g_slotStates[slot] = ControllerState{};
- g_slotPacketMs[slot] = 0;
- return;
- }
- g_slotTestReports[slot].assign(data, data + len);
- g_hasSlotTestReport[slot] = true;
- ControllerState s{};
- if (parseUsbPadReport(data, len, s)) {
- s.connected = true;
- g_slotStates[slot] = s;
- g_slotPacketMs[slot] = platform::nowMs();
+bool pollUsbPadsFor(int player, ControllerState& out, int except) {
+ if (player < 0 || player >= kMaxPads) {
+ out = ControllerState{};
+ return false;
}
+ return pollWhere(player, except, out);
}
-bool padUsbInit() {
- std::lock_guard<std::mutex> lock(g_usbPadMutex);
- if (g_initialized) return true;
- g_initialized = true;
-#if XC_HAS_UHID_POSIX
- scanUhidDevices();
-#endif
+bool pollUsbPadSlot(int slot, ControllerState& out) {
+ out = ControllerState{};
+ if (slot < 0 || slot >= kMaxUsbPads) return false;
+ std::lock_guard<std::mutex> lock(g_mutex);
+ const Slot& s = g_slots[slot];
+ if (!s.attached || !s.state.connected) return false;
+ out = shown(s);
return true;
}
-void padUsbShutdown() {
- std::lock_guard<std::mutex> lock(g_usbPadMutex);
-#if XC_HAS_UHID_POSIX
- for (int& fd : g_uhidFds) {
- if (fd >= 0) {
- close(fd);
- fd = -1;
- }
- }
-#endif
- g_initialized = false;
- g_lastUsbState = ControllerState{};
- g_hasTestReport = false;
- g_testReport.clear();
- g_slotStates.fill(ControllerState{});
- g_slotPacketMs.fill(0);
- g_hasSlotTestReport.fill(false);
- for (auto& r : g_slotTestReports) r.clear();
+void setUsbPadPlayer(int slot, int player) {
+ if (slot < 0 || slot >= kMaxUsbPads || player < 0 || player >= kMaxPads) return;
+ std::lock_guard<std::mutex> lock(g_mutex);
+ Slot& s = g_slots[slot];
+ if (s.attached && s.player >= 0 && s.player != player) movePlayer(s, slot, player);
}
-bool pollUsbPad(ControllerState& out) {
- std::lock_guard<std::mutex> lock(g_usbPadMutex);
-
- bool anyTestSlot = false;
- for (int i = 0; i < 8; ++i) {
- if (g_hasSlotTestReport[i]) {
- anyTestSlot = true;
- break;
- }
- }
- if (anyTestSlot) {
- ControllerState merged{};
- bool hasActive = false;
- uint64_t now = platform::nowMs();
- for (int i = 0; i < 8; ++i) {
- if (g_hasSlotTestReport[i] && g_slotStates[i].connected) {
- mergePads(merged, g_slotStates[i]);
- hasActive = true;
- }
- }
- if (hasActive) {
- merged.connected = true;
- g_lastUsbState = merged;
- g_lastPacketMs = now;
- out = merged;
- return true;
- }
- return false;
+void usbPadsWaitRelease() {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ for (Slot& s : g_slots) {
+ if (!s.attached) continue;
+ ControllerState used = s.state;
+ applyPadSettings(used);
+ s.waitRelease = inUse(used) || s.state.btnNexus;
}
+}
-#if XC_HAS_UHID_POSIX
- if (!g_initialized) {
- g_initialized = true;
- }
- scanUhidDevices();
-
- uint8_t buffer[64];
- bool gotAny = false;
- uint64_t now = platform::nowMs();
-
- for (int i = 0; i < 8; ++i) {
- int fd = g_uhidFds[i];
- if (fd < 0) continue;
- ssize_t n = read(fd, buffer, sizeof(buffer));
- if (n >= 6) {
- ControllerState s{};
- if (parseUsbPadReport(buffer, static_cast<size_t>(n), s)) {
- g_slotStates[i] = s;
- g_slotPacketMs[i] = now;
- gotAny = true;
- }
- } else if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK)) {
- close(fd);
- g_uhidFds[i] = -1;
- g_slotStates[i] = ControllerState{};
- g_slotPacketMs[i] = 0;
- }
- }
+std::string usbPadName(int slot) {
+ if (slot < 0 || slot >= kMaxUsbPads) return {};
+ std::lock_guard<std::mutex> lock(g_mutex);
+ return g_slots[slot].attached ? g_slots[slot].name : std::string();
+}
- ControllerState merged{};
- bool hasActive = false;
- for (int i = 0; i < 8; ++i) {
- if (g_slotPacketMs[i] > 0 && (now - g_slotPacketMs[i] < 500) && g_slotStates[i].connected) {
- mergePads(merged, g_slotStates[i]);
- hasActive = true;
- }
- }
+int usbPadCount() {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ return static_cast<int>(std::count_if(g_slots.begin(), g_slots.end(), [](const Slot& s) { return s.attached; }));
+}
- if (gotAny || hasActive) {
- merged.connected = true;
- g_lastUsbState = merged;
- g_lastPacketMs = now;
- out = merged;
- return true;
- }
-#endif
+std::string usbPadNameFor(int player) {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ for (const Slot& s : g_slots)
+ if (s.attached && s.player == player && player >= 0) return s.name;
+ return {};
+}
- out = ControllerState{};
- return false;
+uint64_t usbPadActiveAt(int player) {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ uint64_t at = 0;
+ for (const Slot& s : g_slots)
+ if (s.attached && s.player == player && player >= 0) at = std::max(at, s.activeAt);
+ return at;
}
} // namespace xc::input
diff --git a/src/input/pad_usb.h b/src/input/pad_usb.h
index 1716ec6..72f76cd 100644
--- a/src/input/pad_usb.h
+++ b/src/input/pad_usb.h
@@ -1,58 +1,101 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 RafaelNGP
-// USB HID gamepad driver for third-party wireless controllers on PS5 (such as 8BitDo Ultimate 2.4G dongle)
-// via /dev/uhid* bypassing Sony's libScePad whitelist.
+// Controllers the PS5 itself does not take (Xbox One / Series pads on a
+// cable, 8BitDo and other XInput pads and their 2.4G dongles), read by the
+// app straight from USB. Every one drives the app's menus; in a game each
+// plays as a player of its own (usbPadPlayer).
+//
+// The reports are parsed here, on every platform (the tests feed them);
+// reading them off USB is the platform's (pad_usb_ps5.cpp: /dev/ugen,
+// after OmniPad CE, github.com/jpemendonca/OmniPad-CE, GPL-3.0). Elsewhere
+// there is no transport and no USB pad.
#pragma once
#include "input/controller.h"
+#include <array>
#include <cstddef>
#include <cstdint>
+#include <string>
+#include <vector>
namespace xc::input {
-constexpr uint16_t k8BitDoVid = 0x2DC8;
-constexpr uint16_t k8BitDoUltimate24GPid = 0x3106;
-
-constexpr uint16_t kXbox360WiredVid = 0x045E;
-constexpr uint16_t kXbox360WiredPid = 0x028E;
-constexpr uint16_t kXbox360WirelessVid = 0x045E;
-constexpr uint16_t kXbox360WirelessPid1 = 0x0719;
-constexpr uint16_t kXbox360WirelessPid2 = 0x0291;
-
-constexpr uint16_t kXboxOneVid = 0x045E;
-constexpr uint16_t kXboxOnePid1 = 0x02D1;
-constexpr uint16_t kXboxOnePid2 = 0x02DD;
-constexpr uint16_t kXboxSeriesPid = 0x0B12;
-
-constexpr uint16_t kDualShock4Vid = 0x054C;
-constexpr uint16_t kDualShock4Pid1 = 0x05C4;
-constexpr uint16_t kDualShock4Pid2 = 0x09CC;
-
-bool padUsbInit();
-void padUsbShutdown();
+// What a pad speaks, from its USB interface (class 0xFF):
+// XInput: subclass 0x5D, protocol 0x01 (Xbox 360 and its clones: 8BitDo,
+// GameSir, Machenike... in their PC mode);
+// GIP: subclass 0x47, protocol 0xD0 (Xbox One and Series pads).
+enum class UsbPadProtocol { None, XInput, Gip };
+UsbPadProtocol usbPadProtocolFor(uint8_t ifaceClass, uint8_t ifaceSubclass, uint8_t ifaceProtocol);
+
+// The pad's interface in a configuration descriptor (as USB_GET_FULL_DESC
+// gives it): the first XInput / GIP one (alternate setting 0) and its
+// interrupt endpoints. protocol None when the device has none.
+struct UsbPadInterface {
+ UsbPadProtocol protocol = UsbPadProtocol::None;
+ uint8_t number = 0;
+ uint8_t epIn = 0, epOut = 0; // endpoint addresses (epIn has bit 7); 0: none
+};
+UsbPadInterface findUsbPadInterface(const uint8_t* configDesc, size_t len);
+
+// GIP: the acknowledgements (13 bytes each) a report asks for, one per
+// message in it with the ACK option (0x10); the pad repeats them otherwise.
+std::vector<std::array<uint8_t, 13>> gipAcksFor(const uint8_t* data, size_t len);
+
+// One report into `state`, as read: sticks -1..1 (+y down) with no dead
+// zone, triggers 0..1. `state` comes in with the pad's last state: a
+// report that carries only some of the buttons (GIP's Xbox button) leaves
+// the rest as they were. False for a report that is not input (LED,
+// rumble and status reports, GIP's announce / keep-alive...).
+bool parseXInputReport(const uint8_t* data, size_t len, ControllerState& state);
+bool parseGipReport(const uint8_t* data, size_t len, ControllerState& state);
+bool parseUsbPadReport(UsbPadProtocol protocol, const uint8_t* data, size_t len, ControllerState& state);
+
+// The transport tells the shared code about each pad (slot 0..kMaxUsbPads-1).
+constexpr int kMaxUsbPads = 4;
+void usbPadAttached(int slot, const std::string& name);
+void usbPadState(int slot, const ControllerState& state);
+void usbPadDetached(int slot);
+
+// Players (0..kMaxPads-1). A pad takes the first free one as it connects,
+// in the order they come (free: no DualSense connected there and no other
+// USB pad on it), from the first pollUsbPad() after it came. Holding its
+// Xbox / Home button, LB and RB move it to the player before / after; the
+// button alone (let go without them) asks for the in-game menu, for that
+// pad (UsbPadEvent::MenuButton). It never reaches the game itself, and
+// LB / RB do not while it is held.
+int usbPadPlayer(int slot); // -1: no pad, or not given a player yet
+void setUsbPadPlayer(int slot, int player); // the in-game menu's choice
+std::string usbPadName(int slot);
+
+// What the app acts on, oldest first: notifications, and the in-game menu.
+struct UsbPadEvent {
+ enum class Kind { Connected, Moved, Disconnected, MenuButton } kind = Kind::Connected;
+ int player = 0;
+ std::string name;
+ int slot = -1;
+};
+std::vector<UsbPadEvent> takeUsbPadEvents();
+
+// The USB pads connected, added up, with the dead zones and the Circle /
+// Cross swap applied as on the DualSense: every one (the menus), those
+// playing as `player` but `except` (a slot whose pad has the in-game
+// menu), or the one in `slot`. False (and `out` cleared) when there is none.
bool pollUsbPad(ControllerState& out);
-
-// Parses raw 16-byte D-Input report from 8BitDo Ultimate 2.4G USB RF adapter
-bool parse8BitDoDInputReport(const uint8_t* data, size_t len, ControllerState& out);
-
-// Parses Xbox 360 USB wired / wireless receiver reports (X-Input 14..20+ bytes)
-bool parseXbox360Report(const uint8_t* data, size_t len, ControllerState& out);
-
-// Parses Xbox One / Series USB reports (GIP 0x20 packets)
-bool parseXboxOneReport(const uint8_t* data, size_t len, ControllerState& out);
-
-// Parses DualShock 4 USB reports (64 bytes report 0x01)
-bool parseDualShock4Report(const uint8_t* data, size_t len, ControllerState& out);
-
-// Parses Generic Standard HID 14/16-button fightsticks and arcade sticks
-bool parseGenericArcadeReport(const uint8_t* data, size_t len, ControllerState& out);
-
-// Auto-detects device type and parses any supported USB HID report
-bool parseUsbPadReport(const uint8_t* data, size_t len, ControllerState& out);
-
-// Test helper to inject reports in unit tests
-void padUsbInjectReportForTesting(const uint8_t* data, size_t len);
-void padUsbInjectSlotReportForTesting(int slot, const uint8_t* data, size_t len);
+bool pollUsbPadsFor(int player, ControllerState& out, int except = -1);
+bool pollUsbPadSlot(int slot, ControllerState& out);
+int usbPadCount();
+// After the in-game menu closes: each pad stays out of the game until its
+// buttons are let go (the one that closed the menu would press it there).
+void usbPadsWaitRelease();
+// The name of the first USB pad playing as `player` (empty: none), and
+// when one of them was last used (ms; 0: never).
+std::string usbPadNameFor(int player);
+uint64_t usbPadActiveAt(int player);
+
+// PS5: starts and stops looking for USB pads (pad_usb_ps5.cpp; called by
+// controller_ps5.cpp). Not defined on the other platforms.
+void usbPadsStart();
+void usbPadsStop();
} // namespace xc::input
diff --git a/src/input/pad_usb_ps5.cpp b/src/input/pad_usb_ps5.cpp
new file mode 100644
index 0000000..ad8e80d
--- /dev/null
+++ b/src/input/pad_usb_ps5.cpp
@@ -0,0 +1,517 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// USB pads on the PS5 (pad_usb.h). The console has no driver for an Xbox
+// or XInput pad: the FreeBSD kernel leaves it to ugen, whose control node
+// (/dev/ugenB.A) is open to every process. Each pad gets a thread that
+// keeps one interrupt IN transfer queued through the USB_FS ioctls, as
+// OmniPad CE does (usb_hotplug.c, github.com/jpemendonca/OmniPad-CE,
+// GPL-3.0); the wake-up packets each kind of pad wants come from there too.
+// A thread looks for pads plugged in and unplugged every 1.5 s.
+#include "input/pad_usb.h"
+#include "util/log.h"
+
+#include <dev/usb/usb_ioctl.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <sys/select.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <atomic>
+#include <chrono>
+#include <cstring>
+#include <memory>
+#include <mutex>
+#include <set>
+#include <string>
+#include <thread>
+#include <utility>
+#include <vector>
+
+namespace xc::input {
+
+namespace {
+
+constexpr int kUsbErrNormal = 0; // USB_ERR_NORMAL_COMPLETION (dev/usb/usbdi.h)
+constexpr int kUsbErrShortXfer = 21; // USB_ERR_SHORT_XFER
+constexpr uint16_t kShortXferOk = 0x0004; // USB_SHORT_XFER_OK (usbdi.h): a reply shorter than asked is fine
+constexpr uint16_t kMediaTekVid = 0x0e8d; // the console's own Bluetooth radio: never touched
+constexpr int kInIndex = 0, kOutIndex = 1;
+
+struct Device {
+ std::string path;
+ int fd = -1;
+ int slot = -1;
+ uint16_t vid = 0, pid = 0;
+ std::string name;
+ UsbPadInterface iface;
+ bool hasOut = false;
+ usb_fs_endpoint eps[2]{};
+ void* frames[2]{};
+ uint32_t lengths[2]{};
+ uint8_t rx[64]{}, tx[64]{};
+ bool inPending = false, inDone = false, clearStall = false;
+ std::atomic<bool> stop{false}, dead{false}, attached{false}, failed{false};
+ std::thread thread;
+};
+
+std::mutex g_mutex; // g_devices, g_ignored
+std::vector<std::unique_ptr<Device>> g_devices;
+std::set<std::pair<std::string, ino_t>> g_ignored; // not a pad, or it failed: until it is plugged again
+std::thread g_scanner;
+std::atomic<bool> g_running{false};
+
+const char* protocolName(UsbPadProtocol p) {
+ return p == UsbPadProtocol::Gip ? "GIP" : p == UsbPadProtocol::XInput ? "XInput" : "none";
+}
+
+std::string hex(const uint8_t* p, int n) {
+ std::string s;
+ char b[4];
+ for (int i = 0; i < n && i < 24; ++i) std::snprintf(b, sizeof b, "%02x ", p[i]), s += b;
+ return s;
+}
+
+int controlRequest(int fd, uint8_t type, uint8_t request, uint16_t value, uint16_t index, void* data, uint16_t len) {
+ usb_ctl_request r{};
+ r.ucr_data = data;
+ r.ucr_flags = kShortXferOk;
+ r.ucr_request.bmRequestType = type;
+ r.ucr_request.bRequest = request;
+ USETW(r.ucr_request.wValue, value);
+ USETW(r.ucr_request.wIndex, index);
+ USETW(r.ucr_request.wLength, len);
+ return ioctl(fd, USB_DO_REQUEST, &r) == 0 ? 0 : errno;
+}
+
+// The product's name from its string descriptor (UTF-16, ASCII kept).
+std::string productName(int fd, uint8_t index) {
+ if (!index) return {};
+ uint8_t raw[256] = {};
+ usb_gen_descriptor gd{};
+ gd.ugd_data = raw;
+ gd.ugd_maxlen = sizeof raw;
+ gd.ugd_string_index = index;
+ gd.ugd_lang_id = 0x0409;
+ if (ioctl(fd, USB_GET_STRING_DESC, &gd) != 0) return {};
+ std::string s;
+ const size_t n = std::min<size_t>({gd.ugd_actlen, raw[0], sizeof raw});
+ for (size_t i = 2; i + 1 < n; i += 2)
+ if (raw[i + 1] == 0 && raw[i] >= 0x20 && raw[i] < 0x7f) s += static_cast<char>(raw[i]);
+ return s;
+}
+
+// A device that is no pad of ours: its interfaces in the log (class,
+// subclass, protocol and endpoints) and, for a HID one that is no boot
+// keyboard / mouse, its report descriptor (a read-only request), to tell
+// what another pad needs.
+void logInterfaces(int fd, const std::string& path, const uint8_t* d, size_t len) {
+ std::string line;
+ for (size_t off = 0; off + 2 <= len; off += d[off]) {
+ const size_t l = d[off];
+ if (l < 2 || off + l > len) break;
+ char b[64];
+ if (d[off + 1] == 0x04 && l >= 9) {
+ std::snprintf(b, sizeof b, " | if %u alt %u: %02x/%02x/%02x", d[off + 2], d[off + 3], d[off + 5], d[off + 6],
+ d[off + 7]);
+ line += b;
+ } else if (d[off + 1] == 0x05 && l >= 7) {
+ std::snprintf(b, sizeof b, " ep %02x/%u", d[off + 2], d[off + 3] & 3);
+ line += b;
+ }
+ }
+ XC_LOGI("usb pad: %s: interfaces%s", path.c_str(), line.c_str());
+ uint8_t iface = 0, sub = 0xff;
+ bool hid = false;
+ for (size_t off = 0; off + 2 <= len; off += d[off]) {
+ const size_t l = d[off];
+ if (l < 2 || off + l > len) break;
+ if (d[off + 1] == 0x04 && l >= 9) iface = d[off + 2], hid = d[off + 5] == 0x03, sub = d[off + 6];
+ if (d[off + 1] != 0x21 || l < 9 || !hid || sub != 0x00) continue; // a HID descriptor, no boot device
+ const uint16_t size = static_cast<uint16_t>(d[off + 7] | (d[off + 8] << 8));
+ uint8_t report[512] = {};
+ const uint16_t want = std::min<uint16_t>(size, sizeof report);
+ int err = controlRequest(fd, 0x81, 0x06, 0x2200, iface, report, want);
+ if (err) {
+ XC_LOGI("usb pad: %s: if %u report descriptor: errno %d", path.c_str(), iface, err);
+ continue;
+ }
+ for (int at = 0; at < want; at += 24)
+ XC_LOGI("usb pad: %s: if %u report descriptor @%d: %s", path.c_str(), iface, at,
+ hex(report + at, std::min(24, want - at)).c_str());
+ }
+}
+
+bool setupTransfers(Device& d) {
+ int config = 0;
+ if (ioctl(d.fd, USB_GET_CONFIG, &config) == 0 && (config & 0xff) == 0xff) {
+ config = 0;
+ if (ioctl(d.fd, USB_SET_CONFIG, &config) != 0) XC_LOGW("usb pad: %s: set config: errno %d", d.path.c_str(), errno);
+ }
+ usb_fs_init init{};
+ init.pEndpoints = d.eps;
+ init.ep_index_max = 2;
+ if (ioctl(d.fd, USB_FS_INIT, &init) != 0) {
+ XC_LOGW("usb pad: %s: USB_FS_INIT: errno %d (%s)", d.path.c_str(), errno, std::strerror(errno));
+ return false;
+ }
+ usb_fs_open op{};
+ op.max_bufsize = sizeof d.rx;
+ op.max_frames = 1;
+ op.ep_index = kInIndex;
+ op.ep_no = d.iface.epIn;
+ if (ioctl(d.fd, USB_FS_OPEN, &op) != 0) {
+ int err = errno;
+ char driver[64] = {};
+ usb_gen_descriptor gd{};
+ gd.ugd_data = driver;
+ gd.ugd_maxlen = sizeof driver - 1;
+ gd.ugd_iface_index = d.iface.number;
+ bool claimed = ioctl(d.fd, USB_GET_IFACE_DRIVER, &gd) == 0;
+ XC_LOGW("usb pad: %s: opening IN 0x%02x: errno %d (%s)%s%s", d.path.c_str(), d.iface.epIn, err, std::strerror(err),
+ claimed ? ", interface held by the driver " : "", claimed ? driver : "");
+ return false;
+ }
+ if (d.iface.epOut) {
+ op = {};
+ op.max_bufsize = sizeof d.tx;
+ op.max_frames = 1;
+ op.ep_index = kOutIndex;
+ op.ep_no = d.iface.epOut;
+ d.hasOut = ioctl(d.fd, USB_FS_OPEN, &op) == 0;
+ if (!d.hasOut) XC_LOGW("usb pad: %s: opening OUT 0x%02x: errno %d", d.path.c_str(), d.iface.epOut, errno);
+ }
+ for (int i : {kInIndex, kOutIndex}) {
+ d.frames[i] = i == kInIndex ? d.rx : d.tx;
+ d.lengths[i] = sizeof d.rx;
+ d.eps[i].ppBuffer = &d.frames[i];
+ d.eps[i].pLength = &d.lengths[i];
+ d.eps[i].nFrames = 1;
+ d.eps[i].flags = USB_FS_FLAG_SINGLE_SHORT_OK;
+ }
+ return true;
+}
+
+// One report off the IN endpoint: its size, 0 when none came within
+// `waitMs`, -1 on an error. The transfer stays queued between calls (no
+// kernel timeout): a pad that reports only on change (the 8BitDo dongle)
+// would lose a press landing between a timed-out transfer and the next.
+int receive(Device& d, uint8_t* out, int waitMs) {
+ usb_fs_endpoint& ep = d.eps[kInIndex];
+ if (!d.inPending) {
+ d.lengths[kInIndex] = sizeof d.rx;
+ ep.timeout = 0;
+ ep.flags = USB_FS_FLAG_SINGLE_SHORT_OK | (d.clearStall ? USB_FS_FLAG_CLEAR_STALL : 0);
+ d.clearStall = false;
+ usb_fs_start start{};
+ start.ep_index = kInIndex;
+ if (ioctl(d.fd, USB_FS_START, &start) != 0 && errno != EBUSY) return -1;
+ d.inPending = true;
+ }
+ for (int spins = waitMs / 4 + 1; spins > 0; --spins) {
+ bool done = d.inDone;
+ if (!done) {
+ usb_fs_complete complete{};
+ if (ioctl(d.fd, USB_FS_COMPLETE, &complete) == 0) {
+ if (complete.ep_index != kInIndex) continue; // an OUT transfer that ended late
+ done = true;
+ } else if (errno != EBUSY && errno != EAGAIN && errno != ETIMEDOUT) {
+ return -1;
+ }
+ }
+ if (done) {
+ d.inDone = d.inPending = false;
+ if (ep.status != kUsbErrNormal && ep.status != kUsbErrShortXfer) {
+ d.clearStall = true;
+ return -1;
+ }
+ const int n = static_cast<int>(std::min<uint32_t>(d.lengths[kInIndex], sizeof d.rx));
+ std::memcpy(out, d.rx, static_cast<size_t>(n));
+ return n;
+ }
+ fd_set rset;
+ FD_ZERO(&rset);
+ FD_SET(d.fd, &rset);
+ timeval wait{0, 4000};
+ select(d.fd + 1, &rset, nullptr, nullptr, &wait);
+ }
+ return 0;
+}
+
+// One packet out the OUT endpoint; false when it was not sent.
+bool send(Device& d, const uint8_t* data, size_t len, int timeoutMs = 80) {
+ if (!d.hasOut) return false;
+ usb_fs_endpoint& ep = d.eps[kOutIndex];
+ len = std::min(len, sizeof d.tx);
+ std::memcpy(d.tx, data, len);
+ d.lengths[kOutIndex] = static_cast<uint32_t>(len);
+ ep.timeout = static_cast<uint16_t>(timeoutMs);
+ usb_fs_start start{};
+ start.ep_index = kOutIndex;
+ if (ioctl(d.fd, USB_FS_START, &start) != 0 && errno != EBUSY) return false;
+ for (int spins = timeoutMs / 4 + 1; spins > 0; --spins) {
+ usb_fs_complete complete{};
+ if (ioctl(d.fd, USB_FS_COMPLETE, &complete) == 0) {
+ if (complete.ep_index == kInIndex) { // the queued IN transfer: the next receive() takes it
+ d.inDone = true;
+ continue;
+ }
+ return ep.status == kUsbErrNormal || ep.status == kUsbErrShortXfer;
+ }
+ if (errno != EBUSY && errno != EAGAIN) return false;
+ std::this_thread::sleep_for(std::chrono::milliseconds(4));
+ }
+ return false;
+}
+
+// What each kind of pad waits for before it reports.
+void wakeUp(Device& d) {
+ if (d.iface.protocol == UsbPadProtocol::Gip) {
+ // Power on, the "S" init and the Xbox button's light.
+ static const uint8_t powerOn[] = {0x05, 0x20, 0x00, 0x01, 0x00};
+ static const uint8_t sInit[] = {0x05, 0x20, 0x00, 0x0f, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x55, 0x53, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+ static const uint8_t ledOn[] = {0x0a, 0x20, 0x00, 0x03, 0x00, 0x01, 0x14};
+ bool a = send(d, powerOn, sizeof powerOn);
+ std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ bool b = send(d, sInit, sizeof sInit);
+ std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ bool c = send(d, ledOn, sizeof ledOn);
+ XC_LOGI("usb pad %d: GIP power on %s, init %s, light %s", d.slot, a ? "ok" : "failed", b ? "ok" : "failed",
+ c ? "ok" : "failed");
+ } else {
+ // The player 1 light, which XInput hosts set as a pad connects: the
+ // 8BitDo Ultimate dongle stays silent without it and drops off USB
+ // after ~10 s.
+ static const uint8_t led[] = {0x01, 0x03, 0x02};
+ bool ok = send(d, led, sizeof led);
+ XC_LOGI("usb pad %d: XInput light %s", d.slot, ok ? "sent" : "not sent");
+ }
+}
+
+unsigned buttonBits(const ControllerState& s) {
+ const bool b[] = {s.btnA, s.btnB, s.btnX, s.btnY, s.dpadUp, s.dpadDown, s.dpadLeft, s.dpadRight,
+ s.btnL1, s.btnR1, s.btnL3, s.btnR3, s.btnOptions, s.btnTouchpad, s.btnNexus,
+ s.triggerL2 > 0.5f, s.triggerR2 > 0.5f};
+ unsigned bits = 0;
+ for (size_t i = 0; i < sizeof b; ++i) bits |= b[i] ? 1u << i : 0;
+ return bits;
+}
+
+std::string buttonNames(unsigned bits) {
+ static const char* names[] = {"A", "B", "X", "Y", "Up", "Down", "Left", "Right", "LB",
+ "RB", "LS", "RS", "Menu", "View", "Xbox", "LT", "RT"};
+ std::string s;
+ for (size_t i = 0; i < sizeof names / sizeof *names; ++i)
+ if (bits & (1u << i)) s += s.empty() ? names[i] : std::string(" ") + names[i];
+ return s.empty() ? "none" : s;
+}
+
+void readLoop(Device* d) {
+ // The XInput wake-up through the control endpoint some 2.4G dongles
+ // want (OmniPad CE's handshake), before the transfers start.
+ if (d->iface.protocol == UsbPadProtocol::XInput) {
+ uint8_t buf[32];
+ int r1 = controlRequest(d->fd, 0xc1, 0x01, 0x0100, d->iface.number, buf, 20);
+ std::this_thread::sleep_for(std::chrono::milliseconds(20));
+ uint8_t led[] = {0x01, 0x03, 0x02};
+ int r2 = controlRequest(d->fd, 0x21, 0x09, 0x0200, d->iface.number, led, sizeof led);
+ XC_LOGI("usb pad: %s: XInput wake-up requests: errno %d, %d", d->path.c_str(), r1, r2);
+ }
+ if (!setupTransfers(*d)) {
+ d->failed = true;
+ d->dead = true;
+ return;
+ }
+ XC_LOGI("usb pad %d: %s (%04x:%04x, %s, IN 0x%02x, OUT 0x%02x%s) on %s", d->slot, d->name.c_str(), d->vid, d->pid,
+ protocolName(d->iface.protocol), d->iface.epIn, d->iface.epOut, d->hasOut ? "" : " not opened",
+ d->path.c_str());
+ usbPadAttached(d->slot, d->name);
+ d->attached = true;
+ wakeUp(*d);
+
+ ControllerState state;
+ uint8_t buf[64];
+ int errors = 0, shown = 0, changesLogged = 0, lightPlayer = -1;
+ unsigned buttons = 0;
+ auto lastOther = std::chrono::steady_clock::time_point{};
+ while (!d->stop) {
+ // XInput pads show their player on their four lights (01 03 06..09).
+ if (const int player = usbPadPlayer(d->slot);
+ d->iface.protocol == UsbPadProtocol::XInput && player >= 0 && player != lightPlayer) {
+ const uint8_t led[] = {0x01, 0x03, static_cast<uint8_t>(0x06 + player)};
+ send(*d, led, sizeof led, 40);
+ lightPlayer = player;
+ }
+ const int n = receive(*d, buf, 20);
+ if (n < 0) {
+ if (++errors >= 50) {
+ XC_LOGW("usb pad %d: %d errors in a row (errno %d): closed", d->slot, errors, errno);
+ break;
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds(4));
+ continue;
+ }
+ if (n == 0) continue;
+ errors = 0;
+ if (d->iface.protocol == UsbPadProtocol::Gip)
+ for (const auto& ack : gipAcksFor(buf, static_cast<size_t>(n))) send(*d, ack.data(), ack.size(), 40);
+ if (shown < 6) XC_LOGI("usb pad %d: report %d: %d bytes: %s", d->slot, ++shown, n, hex(buf, n).c_str());
+ if (parseUsbPadReport(d->iface.protocol, buf, static_cast<size_t>(n), state)) {
+ usbPadState(d->slot, state);
+ // The first presses, to check the buttons from the log.
+ const unsigned now = buttonBits(state);
+ if (now != buttons && changesLogged < 80) {
+ ++changesLogged;
+ XC_LOGI("usb pad %d: buttons %s, sticks %.2f,%.2f %.2f,%.2f, triggers %.2f %.2f", d->slot,
+ buttonNames(now).c_str(), state.rawLeftX, state.rawLeftY, state.rawRightX, state.rawRightY,
+ state.triggerL2, state.triggerR2);
+ }
+ buttons = now;
+ } else if (std::chrono::steady_clock::now() - lastOther > std::chrono::seconds(5)) {
+ lastOther = std::chrono::steady_clock::now();
+ XC_LOGD("usb pad %d: other report, %d bytes: %s", d->slot, n, hex(buf, n).c_str());
+ }
+ }
+ usb_fs_uninit uninit{};
+ ioctl(d->fd, USB_FS_UNINIT, &uninit);
+ d->dead = true;
+}
+
+void closeDevice(Device& d) {
+ d.stop = true;
+ if (d.thread.joinable()) d.thread.join();
+ if (d.attached) usbPadDetached(d.slot);
+ if (d.fd >= 0) close(d.fd);
+ d.fd = -1;
+}
+
+int freeSlot() {
+ for (int s = 0; s < kMaxUsbPads; ++s) {
+ bool used = false;
+ for (const auto& d : g_devices) used |= d->slot == s;
+ if (!used) return s;
+ }
+ return -1;
+}
+
+// A device seen for the first time: a pad gets a slot and its thread;
+// anything else is left alone until it is plugged in again.
+void probe(const std::string& path, ino_t ino) {
+ const auto key = std::make_pair(path, ino);
+ int fd = open(path.c_str(), O_RDWR | O_NONBLOCK);
+ if (fd < 0) {
+ XC_LOGW("usb pad: %s: open: errno %d (%s)", path.c_str(), errno, std::strerror(errno));
+ g_ignored.insert(key);
+ return;
+ }
+ usb_device_descriptor dd{};
+ if (ioctl(fd, USB_GET_DEVICE_DESC, &dd) != 0) {
+ XC_LOGW("usb pad: %s: device descriptor: errno %d", path.c_str(), errno);
+ close(fd);
+ g_ignored.insert(key);
+ return;
+ }
+ const uint16_t vid = UGETW(dd.idVendor), pid = UGETW(dd.idProduct);
+ UsbPadInterface iface;
+ uint8_t config[1024] = {};
+ size_t configLen = 0;
+ // Not the console's radios (class E0, or MediaTek's), not a hub.
+ const bool other = vid == kMediaTekVid || dd.bDeviceClass == 0x09 || dd.bDeviceClass == 0xe0;
+ if (!other) {
+ usb_gen_descriptor gd{};
+ gd.ugd_data = config;
+ gd.ugd_maxlen = sizeof config;
+ if (ioctl(fd, USB_GET_FULL_DESC, &gd) == 0) {
+ configLen = std::min<size_t>(gd.ugd_actlen, sizeof config);
+ iface = findUsbPadInterface(config, configLen);
+ }
+ }
+ if (iface.protocol == UsbPadProtocol::None) {
+ XC_LOGI("usb pad: %s: %04x:%04x (class %02x) is not an Xbox / XInput pad", path.c_str(), vid, pid,
+ dd.bDeviceClass);
+ if (!other && configLen) logInterfaces(fd, path, config, configLen);
+ close(fd);
+ g_ignored.insert(key);
+ return;
+ }
+ const int slot = freeSlot();
+ if (slot < 0) {
+ close(fd); // tried again on the next scan, once a pad leaves
+ return;
+ }
+ auto d = std::make_unique<Device>();
+ d->path = path;
+ d->fd = fd;
+ d->slot = slot;
+ d->vid = vid;
+ d->pid = pid;
+ d->iface = iface;
+ d->name = productName(fd, dd.iProduct);
+ if (d->name.empty()) d->name = protocolName(iface.protocol) + std::string(" pad");
+ d->thread = std::thread(readLoop, d.get());
+ g_devices.push_back(std::move(d));
+}
+
+void scan() {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ // Gone (unplugged, or its thread gave up): closed.
+ for (auto it = g_devices.begin(); it != g_devices.end();) {
+ Device& d = **it;
+ struct stat st {};
+ if (d.dead || stat(d.path.c_str(), &st) != 0) {
+ if (d.failed) {
+ if (stat(d.path.c_str(), &st) == 0) g_ignored.insert({d.path, st.st_ino});
+ XC_LOGW("usb pad: %s left alone until it is plugged in again", d.path.c_str());
+ }
+ closeDevice(d);
+ it = g_devices.erase(it);
+ } else {
+ ++it;
+ }
+ }
+ for (auto it = g_ignored.begin(); it != g_ignored.end();) {
+ struct stat st {};
+ if (stat(it->first.c_str(), &st) != 0 || st.st_ino != it->second) it = g_ignored.erase(it);
+ else ++it;
+ }
+ // New ones. Address 1 of each bus is its root hub.
+ for (int bus = 0; bus < 8; ++bus) {
+ for (int addr = 2; addr < 32; ++addr) {
+ char path[32];
+ std::snprintf(path, sizeof path, "/dev/ugen%d.%d", bus, addr);
+ struct stat st {};
+ if (stat(path, &st) != 0) continue;
+ bool known = g_ignored.count({path, st.st_ino}) != 0;
+ for (const auto& d : g_devices) known |= d->path == path;
+ if (!known) probe(path, st.st_ino);
+ }
+ }
+}
+
+void scanLoop() {
+ while (g_running) {
+ scan();
+ for (int i = 0; i < 15 && g_running; ++i) std::this_thread::sleep_for(std::chrono::milliseconds(100));
+ }
+ std::lock_guard<std::mutex> lock(g_mutex);
+ for (auto& d : g_devices) closeDevice(*d);
+ g_devices.clear();
+ g_ignored.clear();
+}
+
+} // namespace
+
+void usbPadsStart() {
+ if (g_running.exchange(true)) return;
+ XC_LOGI("usb pad: looking for Xbox / XInput pads on /dev/ugen*");
+ g_scanner = std::thread(scanLoop);
+}
+
+void usbPadsStop() {
+ if (!g_running.exchange(false)) return;
+ if (g_scanner.joinable()) g_scanner.join();
+}
+
+} // namespace xc::input
diff --git a/src/ui/i18n/strings_de.inc b/src/ui/i18n/strings_de.inc
index 4e364b1..2e6d6ce 100644
--- a/src/ui/i18n/strings_de.inc
+++ b/src/ui/i18n/strings_de.inc
@@ -415,4 +415,5 @@ constexpr Column kGerman = {
"In Warteschlange (geschätzte Wartezeit: %s • wartet seit %s)", // InQueueEstimated
"Um kostenlose Spiele außer Fortnite ohne Game Pass zu streamen, aktivieren Sie 'Preview-Funktionen' in den App-Einstellungen und auf xbox.com/play.", // F2pPreviewRequiredDesc
"Dieses Konto muss 'Preview-Funktionen' im Profil auf xbox.com/play aktivieren, um werbefinanziertes Free-to-Play-Streaming freizuschalten.", // F2pPreviewAccountNeededDesc
+ "Spieler", // MenuPlayer
};
diff --git a/src/ui/i18n/strings_en.inc b/src/ui/i18n/strings_en.inc
index ac7e29d..4400d01 100644
--- a/src/ui/i18n/strings_en.inc
+++ b/src/ui/i18n/strings_en.inc
@@ -415,4 +415,5 @@ constexpr Column kEnglish = {
"In queue (estimated wait: %s • waiting for %s)", // InQueueEstimated
"To stream free-to-play games beyond Fortnite without Game Pass, enable 'Preview Features' in app Settings and on xbox.com/play.", // F2pPreviewRequiredDesc
"This account needs to enable 'Preview Features' in its profile on xbox.com/play to unlock ad-supported free-to-play streaming.", // F2pPreviewAccountNeededDesc
+ "Player", // MenuPlayer
};
diff --git a/src/ui/i18n/strings_es.inc b/src/ui/i18n/strings_es.inc
index f96002e..8ea70d6 100644
--- a/src/ui/i18n/strings_es.inc
+++ b/src/ui/i18n/strings_es.inc
@@ -415,4 +415,5 @@ constexpr Column kSpanish = {
"En cola (tiempo estimado: %s • esperando desde hace %s)", // InQueueEstimated
"Para transmitir juegos gratuitos además de Fortnite en cuentas sin Game Pass, activa 'Funciones Preview' en Ajustes y en xbox.com/play.", // F2pPreviewRequiredDesc
"Esta cuenta necesita habilitar 'Funciones Preview' en su perfil en xbox.com/play para desbloquear el streaming con anuncios de juegos gratuitos.", // F2pPreviewAccountNeededDesc
+ "Jugador", // MenuPlayer
};
diff --git a/src/ui/i18n/strings_fr.inc b/src/ui/i18n/strings_fr.inc
index d988ae0..8e56225 100644
--- a/src/ui/i18n/strings_fr.inc
+++ b/src/ui/i18n/strings_fr.inc
@@ -415,4 +415,5 @@ constexpr Column kFrench = {
"En file d'attente (temps estimé : %s • attente depuis %s)", // InQueueEstimated
"Pour jouer aux jeux gratuits autres que Fortnite sans Game Pass, activez les 'Fonctionnalités Preview' dans les Paramètres et sur xbox.com/play.", // F2pPreviewRequiredDesc
"Ce compte doit activer les 'Fonctionnalités Preview' sur son profil sur xbox.com/play pour débloquer le streaming gratuit avec publicités.", // F2pPreviewAccountNeededDesc
+ "Joueur", // MenuPlayer
};
diff --git a/src/ui/i18n/strings_it.inc b/src/ui/i18n/strings_it.inc
index 3b53f8b..d48b4ca 100644
--- a/src/ui/i18n/strings_it.inc
+++ b/src/ui/i18n/strings_it.inc
@@ -415,4 +415,5 @@ constexpr Column kItalian = {
"In coda (tempo stimato: %s • in attesa da %s)", // InQueueEstimated
"Per giocare a titoli gratuiti oltre a Fortnite senza Game Pass, abilita 'Funzionalità Preview' nelle Impostazioni e su xbox.com/play.", // F2pPreviewRequiredDesc
"Questo account deve abilitare le 'Funzionalità Preview' nel profilo su xbox.com/play per sbloccare lo streaming gratuito supportato da annunci.", // F2pPreviewAccountNeededDesc
+ "Giocatore", // MenuPlayer
};
diff --git a/src/ui/i18n/strings_pt_br.inc b/src/ui/i18n/strings_pt_br.inc
index eefcf56..7adf595 100644
--- a/src/ui/i18n/strings_pt_br.inc
+++ b/src/ui/i18n/strings_pt_br.inc
@@ -415,4 +415,5 @@ constexpr Column kPortugueseBR = {
"Na fila (tempo estimado: %s • aguardando há %s)", // InQueueEstimated
"Para transmitir jogos gratuitos além de Fortnite em contas sem Game Pass, ative os 'Recursos Preview' nas Configurações do app e no site xbox.com/play.", // F2pPreviewRequiredDesc
"Esta conta precisa habilitar os 'Recursos Preview' no perfil em xbox.com/play para liberar o streaming com anúncios de jogos gratuitos.", // F2pPreviewAccountNeededDesc
+ "Jogador", // MenuPlayer
};
diff --git a/src/ui/stream_menu.cpp b/src/ui/stream_menu.cpp
index e8c2fcf..4609e08 100644
--- a/src/ui/stream_menu.cpp
+++ b/src/ui/stream_menu.cpp
@@ -43,6 +43,7 @@ bool StreamMenu::itemShown(int item) const {
case GyroLevelItem: return caps_.gyro;
case PadSpeakerVolumeItem: return caps_.triggerRumble || caps_.adaptiveTriggers;
case TouchpadShortcutsItem: return caps_.touchpad;
+ case PlayerItem: return usbOwnerPlayer_ >= 0;
default: return true;
}
}
@@ -159,6 +160,10 @@ MenuAction StreamMenu::handle(const NavInput& in) {
// Up / down over the items shown (the Xbox button always is).
if (in.up) do selected_ = (selected_ + ItemCount - 1) % ItemCount; while (!itemShown(selected_));
if (in.down) do selected_ = (selected_ + 1) % ItemCount; while (!itemShown(selected_));
+ if (selected_ == PlayerItem && (in.left || in.right || in.accept)) {
+ usbOwnerPlayer_ = (usbOwnerPlayer_ + (in.left ? 3 : 1)) % 4;
+ return MenuAction::Player;
+ }
if (selected_ == Profile && (in.left || in.right || in.accept)) {
hasCustomProfile_ = !hasCustomProfile_;
return MenuAction::ProfileToggle;
@@ -389,6 +394,7 @@ Canvas StreamMenu::renderMenu(const StreamInfo& info) const {
Color fg = sel ? kDark : kWhite;
int ty = fonts_.semibold.centeredY(row.y, row.h, kPx);
const char* label = i == XboxButton ? tr(Str::MenuXboxButton)
+ : i == PlayerItem ? tr(Str::MenuPlayer)
: i == Profile ? tr(Str::Profile)
: i == Stats ? tr(Str::MenuStats)
: i == Sharpness ? tr(Str::MenuSharpness)
@@ -406,6 +412,10 @@ Canvas StreamMenu::renderMenu(const StreamInfo& info) const {
: tr(Str::MenuLeave);
fonts_.semibold.draw(c, label, row.x + 16, ty, kPx, fg);
std::string value;
+ if (i == PlayerItem) {
+ value = std::to_string(usbOwnerPlayer_ + 1);
+ if (sel) value = "< " + value + " >";
+ }
if (i == Profile) {
value = tr(hasCustomProfile_ ? Str::ProfileCustom : Str::ProfileDefault);
if (sel) value = "< " + value + " >";
diff --git a/src/ui/stream_menu.h b/src/ui/stream_menu.h
index 43f8301..8152bbc 100644
--- a/src/ui/stream_menu.h
+++ b/src/ui/stream_menu.h
@@ -45,7 +45,7 @@ enum StatsIndicator : uint32_t {
enum class MenuAction {
None, Close, Leave, Resolution, Stats, Sharpness, Deband, Upscaler, XboxButton,
ProfileToggle, Triggers, Deadzone, ConfirmButton, MicToggle, Gyro, PadSpeakerVolume,
- TouchpadShortcuts
+ TouchpadShortcuts, Player
};
class StreamMenu {
@@ -110,6 +110,11 @@ public:
bool hasCustomProfile);
// The controllers in use, under the connection.
void setPads(const PadSlots& pads) { pads_ = pads; }
+ // Opened by a USB controller (input/pad_usb.h): the player it plays as
+ // (0..3), which its Player item changes (MenuAction::Player); -1 when
+ // the menu is player 1's own (no such item).
+ void setUsbOwner(int player) { usbOwnerPlayer_ = player; }
+ int usbOwnerPlayer() const { return usbOwnerPlayer_; }
// What the display and the pads can do (UiCaps, all by default as on
// the PS5): the upscaler, sharpness and block smoothing need the
// display's; trigger vibration and gyro aiming a pad with them; the
@@ -126,6 +131,7 @@ public:
private:
enum Item {
XboxButton,
+ PlayerItem,
Profile,
Stats,
Upscaler,
@@ -169,6 +175,7 @@ private:
float micLevel_ = 0.0f;
int padSpeakerVolume_ = 100;
PadSlots pads_{};
+ int usbOwnerPlayer_ = -1;
mutable std::vector<float> frametimes_;
};
diff --git a/src/ui/strings.h b/src/ui/strings.h
index fb212a6..163ece5 100644
--- a/src/ui/strings.h
+++ b/src/ui/strings.h
@@ -424,6 +424,7 @@ enum class Str {
InQueueEstimated,
F2pPreviewRequiredDesc,
F2pPreviewAccountNeededDesc,
+ MenuPlayer, // game menu, a USB controller's: the player it plays as
Count
};
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index 38c2fd8..8248a91 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -4006,97 +4006,232 @@ static void testVoiceRouting() {
CHECK(st.voiceRouting == 0);
}
-static void testUsbPad8BitDo() {
- input::ControllerState state{};
-
- // Null and undersized buffers
- CHECK(!input::parse8BitDoDInputReport(nullptr, 0, state));
- uint8_t shortBuf[10] = {0};
- CHECK(!input::parse8BitDoDInputReport(shortBuf, sizeof(shortBuf), state));
-
- // Centered sticks, neutral hat, no buttons
- uint8_t neutralReport[16] = {
- 128, 128, 128, 128, // Left X, Y, Right X, Y (center)
- 0, 0, // L2, R2 trigger
- 0x08, // Hat neutral (0x08 > 7, no bitmask)
- 0x00, // Action buttons
- 0x00, // System buttons
- 0, 0, 0, 0, 0, 0, 0 // Reserved / telemetry
- };
- CHECK(input::parse8BitDoDInputReport(neutralReport, sizeof(neutralReport), state));
- CHECK(state.connected == true);
- CHECK(std::abs(state.leftStickX) < 0.001f);
- CHECK(std::abs(state.leftStickY) < 0.001f);
- CHECK(std::abs(state.rightStickX) < 0.001f);
- CHECK(std::abs(state.rightStickY) < 0.001f);
- CHECK(state.triggerL2 == 0.0f);
- CHECK(state.triggerR2 == 0.0f);
- CHECK(!state.btnA && !state.btnB && !state.btnX && !state.btnY);
- CHECK(!state.dpadUp && !state.dpadDown && !state.dpadLeft && !state.dpadRight);
-
- // Deflected sticks & triggers
- uint8_t motionReport[16] = {
- 255, 0, 0, 255, // Left stick right/up, Right stick left/down
- 255, 128, // L2 fully pressed, R2 half
- 0x08,
- 0x00,
- 0x00,
- 0, 0, 0, 0, 0, 0, 0
- };
- CHECK(input::parse8BitDoDInputReport(motionReport, sizeof(motionReport), state));
- CHECK(state.leftStickX > 0.95f);
- CHECK(state.leftStickY < -0.95f);
- CHECK(state.rightStickX < -0.95f);
- CHECK(state.rightStickY > 0.95f);
- CHECK(state.triggerL2 == 1.0f);
- CHECK(std::abs(state.triggerR2 - (128.0f / 255.0f)) < 0.02f);
-
- // Action buttons (data[7])
- uint8_t btnReport[16] = {
- 128, 128, 128, 128,
- 0, 0,
- 0x08,
- 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20, // A, B, X, Y, L1, R1
- 0x00,
- 0, 0, 0, 0, 0, 0, 0
+static void testUsbPadReports() {
+ using input::ControllerState;
+ auto near = [](float a, float b) { return std::abs(a - b) < 0.01f; };
+
+ // XInput (Xbox 360 layout; 8BitDo Ultimate 2.4G in PC mode): A + LB +
+ // Up + Start, LT half, RT full, left stick right and up.
+ const uint8_t xin[20] = {0x00, 0x14, 0x11, 0x11, 128, 255, 0xff, 0x7f, 0xff, 0x7f, 0, 0, 0x00, 0x80};
+ ControllerState s;
+ CHECK(input::parseXInputReport(xin, sizeof xin, s));
+ CHECK(s.connected && s.btnA && s.btnL1 && s.dpadUp && s.btnOptions);
+ CHECK(!s.btnB && !s.btnX && !s.btnY && !s.btnR1 && !s.dpadDown && !s.btnTouchpad && !s.btnNexus);
+ CHECK(near(s.triggerL2, 0.5f) && near(s.triggerR2, 1.0f));
+ CHECK(near(s.rawLeftX, 1.0f) && near(s.rawLeftY, -1.0f)); // +y is down
+ CHECK(near(s.rawRightX, 0.0f) && near(s.rawRightY, 1.0f)); // RY -32768: all the way down
+ const uint8_t xinGuide[20] = {0x00, 0x14, 0x20, 0x04}; // Back + Guide
+ CHECK(input::parseXInputReport(xinGuide, sizeof xinGuide, s));
+ CHECK(s.btnTouchpad && s.btnNexus && !s.btnA && !s.btnOptions);
+ // Not input: the LED and rumble status reports.
+ const uint8_t xinLed[3] = {0x01, 0x03, 0x02}, xinRumble[3] = {0x03, 0x03, 0x00};
+ CHECK(!input::parseXInputReport(xinLed, sizeof xinLed, s));
+ CHECK(!input::parseXInputReport(xinRumble, sizeof xinRumble, s));
+
+ // GIP (Xbox One / Series): B + Y + View + Right + RB + RS, LT 1023,
+ // RT 0, right stick left.
+ const uint8_t gip[18] = {0x20, 0x00, 0x05, 0x0e, 0xa8, 0xa8, 0xff, 0x03, 0x00, 0x00,
+ 0, 0, 0, 0, 0x00, 0x80, 0, 0};
+ s = {};
+ CHECK(input::parseGipReport(gip, sizeof gip, s));
+ CHECK(s.btnB && s.btnY && s.btnTouchpad && s.dpadRight && s.btnR1 && s.btnR3);
+ CHECK(!s.btnA && !s.btnX && !s.btnOptions && !s.dpadLeft && !s.btnL1 && !s.btnL3 && !s.btnNexus);
+ CHECK(near(s.triggerL2, 1.0f) && near(s.triggerR2, 0.0f));
+ CHECK(near(s.rawRightX, -1.0f) && near(s.rawLeftX, 0.0f));
+ // The Xbox button comes by itself and keeps the other buttons.
+ const uint8_t guideDown[6] = {0x07, 0x30, 0x01, 0x02, 0x01, 0x5b}, guideUp[6] = {0x07, 0x30, 0x02, 0x02, 0x00, 0x5b};
+ CHECK(input::parseGipReport(guideDown, sizeof guideDown, s));
+ CHECK(s.btnNexus && s.btnB && s.btnY);
+ CHECK(input::parseGipReport(guideUp, sizeof guideUp, s));
+ CHECK(!s.btnNexus && s.btnB);
+ // Its announce and keep-alive messages are not input.
+ const uint8_t announce[8] = {0x02, 0x20, 0x01, 0x1c, 0x7e, 0xed, 0x8b, 0x11}, keepAlive[6] = {0x03, 0x20, 0x01, 0x04, 0x80, 0x00};
+ CHECK(!input::parseGipReport(announce, sizeof announce, s));
+ CHECK(!input::parseGipReport(keepAlive, sizeof keepAlive, s));
+ CHECK(input::parseUsbPadReport(input::UsbPadProtocol::Gip, gip, sizeof gip, s));
+ CHECK(!input::parseUsbPadReport(input::UsbPadProtocol::None, gip, sizeof gip, s));
+
+ // GIP acknowledgements: the Xbox button's message asks for one.
+ auto acks = input::gipAcksFor(guideDown, sizeof guideDown);
+ CHECK(acks.size() == 1);
+ const std::array<uint8_t, 13> ack = {0x01, 0x20, 0x01, 0x09, 0x00, 0x07, 0x20, 0x02, 0, 0, 0, 0, 0};
+ CHECK(!acks.empty() && acks[0] == ack);
+ CHECK(input::gipAcksFor(gip, sizeof gip).empty()); // input is not acknowledged
+}
+
+static void testUsbPadDescriptors() {
+ // An Xbox Series pad's configuration (045e:0b12): GIP interface 0
+ // (OUT 0x02, IN 0x82), then the audio interface with its alternates.
+ const uint8_t series[] = {
+ 0x09, 0x02, 0x77, 0x00, 0x03, 0x01, 0x00, 0xa0, 0xfa, // configuration
+ 0x09, 0x04, 0x00, 0x00, 0x02, 0xff, 0x47, 0xd0, 0x00, // interface 0: GIP
+ 0x07, 0x05, 0x02, 0x03, 0x40, 0x00, 0x04, // OUT 0x02 interrupt
+ 0x07, 0x05, 0x82, 0x03, 0x40, 0x00, 0x04, // IN 0x82 interrupt
+ 0x09, 0x04, 0x01, 0x00, 0x00, 0xff, 0x47, 0xd0, 0x00, // interface 1, no endpoints
+ 0x09, 0x04, 0x01, 0x01, 0x02, 0xff, 0x47, 0xd0, 0x00, // its alternate 1: isochronous
+ 0x07, 0x05, 0x03, 0x01, 0xe4, 0x00, 0x01,
+ 0x07, 0x05, 0x83, 0x01, 0x40, 0x00, 0x01,
};
- CHECK(input::parse8BitDoDInputReport(btnReport, sizeof(btnReport), state));
- CHECK(state.btnA && state.btnB && state.btnX && state.btnY && state.btnL1 && state.btnR1);
-
- // D-Pad Hat Switch (0 = Up, 2 = Right, 4 = Down, 6 = Left)
- uint8_t dpadReports[4][16] = {
- {128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Up
- {128, 128, 128, 128, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Right
- {128, 128, 128, 128, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Down
- {128, 128, 128, 128, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0} // Left
+ input::UsbPadInterface i = input::findUsbPadInterface(series, sizeof series);
+ CHECK(i.protocol == input::UsbPadProtocol::Gip && i.number == 0 && i.epIn == 0x82 && i.epOut == 0x02);
+
+ // An XInput pad (8BitDo Ultimate, 2dc8:3106): interface 0 FF/5D/01
+ // (IN 0x81, OUT 0x01) after a vendor interface the code must skip.
+ const uint8_t xinput[] = {
+ 0x09, 0x02, 0x40, 0x00, 0x02, 0x01, 0x00, 0xa0, 0xfa,
+ 0x09, 0x04, 0x00, 0x00, 0x00, 0xff, 0xfd, 0x13, 0x00, // security interface: not a pad
+ 0x09, 0x04, 0x01, 0x00, 0x02, 0xff, 0x5d, 0x01, 0x00, // interface 1: XInput
+ 0x11, 0x21, 0x10, 0x01, 0x01, 0x25, 0x81, 0x14, 0x03, 0x03, 0x03, 0x04, 0x13, 0x02, 0x08, 0x03, 0x03,
+ 0x07, 0x05, 0x81, 0x03, 0x20, 0x00, 0x01,
+ 0x07, 0x05, 0x01, 0x03, 0x20, 0x00, 0x08,
};
- CHECK(input::parse8BitDoDInputReport(dpadReports[0], 16, state) && state.dpadUp && !state.dpadDown);
- CHECK(input::parse8BitDoDInputReport(dpadReports[1], 16, state) && state.dpadRight && !state.dpadLeft);
- CHECK(input::parse8BitDoDInputReport(dpadReports[2], 16, state) && state.dpadDown && !state.dpadUp);
- CHECK(input::parse8BitDoDInputReport(dpadReports[3], 16, state) && state.dpadLeft && !state.dpadRight);
-
- // System buttons (data[8])
- uint8_t sysReport[16] = {
- 128, 128, 128, 128,
- 0, 0,
- 0x08,
- 0x00,
- 0x01 | 0x02 | 0x04 | 0x08 | 0x10, // Touchpad/Select, Options/Start, Nexus/Home, L3, R3
- 0, 0, 0, 0, 0, 0, 0
+ i = input::findUsbPadInterface(xinput, sizeof xinput);
+ CHECK(i.protocol == input::UsbPadProtocol::XInput && i.number == 1 && i.epIn == 0x81 && i.epOut == 0x01);
+
+ // A keyboard (HID, class 3): no pad. A truncated descriptor: none either.
+ const uint8_t keyboard[] = {
+ 0x09, 0x02, 0x22, 0x00, 0x01, 0x01, 0x00, 0xa0, 0x32,
+ 0x09, 0x04, 0x00, 0x00, 0x01, 0x03, 0x01, 0x01, 0x00,
+ 0x07, 0x05, 0x81, 0x03, 0x08, 0x00, 0x0a,
};
- CHECK(input::parse8BitDoDInputReport(sysReport, sizeof(sysReport), state));
- CHECK(state.btnTouchpad && state.btnOptions && state.btnNexus && state.btnL3 && state.btnR3);
-
- // Test injection & polling API
- input::padUsbInit();
- input::padUsbInjectReportForTesting(sysReport, sizeof(sysReport));
- input::ControllerState polled{};
- CHECK(input::pollUsbPad(polled));
- CHECK(polled.btnNexus == true);
- CHECK(polled.btnL3 == true);
-
- input::padUsbInjectReportForTesting(nullptr, 0);
- input::padUsbShutdown();
+ CHECK(input::findUsbPadInterface(keyboard, sizeof keyboard).protocol == input::UsbPadProtocol::None);
+ CHECK(input::findUsbPadInterface(series, 20).protocol == input::UsbPadProtocol::None);
+ CHECK(input::findUsbPadInterface(nullptr, 0).protocol == input::UsbPadProtocol::None);
+ CHECK(input::usbPadProtocolFor(0x03, 0x00, 0x00) == input::UsbPadProtocol::None);
+}
+
+static void testUsbPadSlots() {
+ using input::UsbPadEvent;
+ input::ControllerState out;
+ input::takeUsbPadEvents();
+ CHECK(!input::pollUsbPad(out) && !out.connected && input::usbPadCount() == 0);
+ // Each pad a player of its own, in the order they came (no DualSense here).
+ input::usbPadAttached(1, "Xbox Wireless Controller");
+ input::usbPadAttached(0, "8BitDo Ultimate");
+ CHECK(input::usbPadCount() == 2 && input::usbPadPlayer(1) == -1);
+ CHECK(!input::pollUsbPad(out)); // no input from either yet; the players given
+ CHECK(input::usbPadPlayer(1) == 0 && input::usbPadPlayer(0) == 1);
+ auto events = input::takeUsbPadEvents();
+ CHECK(events.size() == 2 && events[0].kind == UsbPadEvent::Kind::Connected && events[0].player == 0 &&
+ events[0].name == "Xbox Wireless Controller" && events[1].player == 1);
+ CHECK(input::usbPadNameFor(0) == "Xbox Wireless Controller" && input::usbPadNameFor(1) == "8BitDo Ultimate");
+ CHECK(input::usbPadNameFor(2).empty() && input::usbPadActiveAt(0) == 0);
+
+ input::ControllerState xbox, bitdo;
+ xbox.btnA = true;
+ xbox.rawLeftX = 0.05f; // the left stick inside the dead zone, the right one pushed
+ xbox.rawRightY = 0.9f;
+ bitdo.dpadRight = true;
+ bitdo.triggerR2 = 0.7f;
+ input::usbPadState(1, xbox);
+ input::usbPadState(0, bitdo);
+ CHECK(input::usbPadActiveAt(0) > 0 && input::usbPadActiveAt(1) > 0);
+ // The menus: both. The game: each its own player.
+ CHECK(input::pollUsbPad(out) && out.btnA && out.dpadRight && std::abs(out.triggerR2 - 0.7f) < 0.01f);
+ CHECK(input::pollUsbPadsFor(0, out) && out.btnA && !out.dpadRight);
+ CHECK(out.leftStickX == 0.0f && out.rawLeftX > 0.04f && out.rightStickY > 0.8f);
+ CHECK(input::pollUsbPadsFor(1, out) && out.dpadRight && !out.btnA);
+ CHECK(!input::pollUsbPadsFor(2, out) && !input::pollUsbPadsFor(-1, out) && !input::pollUsbPadsFor(9, out));
+ // Circle confirms: the Xbox B button becomes A as the DualSense's Circle does.
+ input::setCircleConfirms(true);
+ CHECK(input::pollUsbPadsFor(0, out) && !out.btnA && out.btnB);
+ input::setCircleConfirms(false);
+
+ // Xbox / Home + RB: the 8BitDo to player 3; LB / RB and the Xbox
+ // button do not reach the game meanwhile.
+ bitdo = {};
+ bitdo.btnNexus = true;
+ input::usbPadState(0, bitdo);
+ CHECK(input::pollUsbPadsFor(1, out) && !out.btnNexus);
+ bitdo.btnR1 = true;
+ input::usbPadState(0, bitdo);
+ CHECK(input::usbPadPlayer(0) == 2 && !input::pollUsbPadsFor(1, out));
+ CHECK(input::pollUsbPadsFor(2, out) && !out.btnR1 && !out.btnNexus);
+ bitdo.btnR1 = false;
+ input::usbPadState(0, bitdo);
+ bitdo.btnR1 = true; // again: player 4
+ input::usbPadState(0, bitdo);
+ CHECK(input::usbPadPlayer(0) == 3);
+ bitdo = {};
+ input::usbPadState(0, bitdo); // let go after a move: no menu
+ bitdo.btnNexus = true, bitdo.btnL1 = true; // Xbox + LB: back to player 3
+ input::usbPadState(0, bitdo);
+ CHECK(input::usbPadPlayer(0) == 2);
+ bitdo = {};
+ input::usbPadState(0, bitdo);
+ events = input::takeUsbPadEvents();
+ CHECK(events.size() == 3 && events[0].kind == UsbPadEvent::Kind::Moved && events[0].player == 2 &&
+ events[0].slot == 0 && events[1].player == 3 && events[2].player == 2);
+ // From player 1, LB goes round to player 4, and RB back.
+ xbox = {};
+ xbox.btnNexus = true;
+ input::usbPadState(1, xbox);
+ xbox.btnL1 = true;
+ input::usbPadState(1, xbox);
+ CHECK(input::usbPadPlayer(1) == 3);
+ xbox.btnL1 = false;
+ input::usbPadState(1, xbox);
+ xbox.btnR1 = true;
+ input::usbPadState(1, xbox);
+ CHECK(input::usbPadPlayer(1) == 0);
+ xbox = {};
+ input::usbPadState(1, xbox);
+ input::takeUsbPadEvents();
+ // The Xbox button alone: the in-game menu, for that pad, once let go.
+ xbox.btnNexus = true;
+ input::usbPadState(1, xbox);
+ CHECK(input::takeUsbPadEvents().empty());
+ xbox.btnNexus = false;
+ input::usbPadState(1, xbox);
+ events = input::takeUsbPadEvents();
+ CHECK(events.size() == 1 && events[0].kind == UsbPadEvent::Kind::MenuButton && events[0].slot == 1 &&
+ events[0].player == 0);
+ // Menu (Start) goes straight through, with View too.
+ xbox.btnOptions = true;
+ input::usbPadState(1, xbox);
+ CHECK(input::pollUsbPadsFor(0, out) && out.btnOptions);
+ xbox = {};
+ input::usbPadState(1, xbox);
+
+ // The menu's owner: out of its player's input, read by itself.
+ xbox.btnA = true;
+ input::usbPadState(1, xbox);
+ CHECK(!input::pollUsbPadsFor(0, out, 1));
+ CHECK(input::pollUsbPadSlot(1, out) && out.btnA && !input::pollUsbPadSlot(3, out) && !input::pollUsbPadSlot(-1, out));
+ // The menu closed with A held: out of the game until let go (the menus still see it).
+ input::usbPadsWaitRelease();
+ CHECK(!input::pollUsbPadsFor(0, out) && input::pollUsbPad(out) && out.btnA);
+ xbox.btnA = false;
+ input::usbPadState(1, xbox);
+ CHECK(input::pollUsbPadsFor(0, out) && !out.btnA);
+ // The menu's Player item.
+ input::setUsbPadPlayer(1, 2);
+ CHECK(input::usbPadPlayer(1) == 2 && input::usbPadName(1) == "Xbox Wireless Controller");
+ input::setUsbPadPlayer(1, 7); // out of range: kept
+ CHECK(input::usbPadPlayer(1) == 2);
+ input::setUsbPadPlayer(1, 0);
+ events = input::takeUsbPadEvents();
+ CHECK(events.size() == 2 && events[0].kind == UsbPadEvent::Kind::Moved && events[0].player == 2 &&
+ events[1].player == 0);
+
+ // A pad that reports only on change keeps its state.
+ bitdo.btnY = true;
+ input::usbPadState(0, bitdo);
+ CHECK(input::pollUsbPadsFor(2, out) && out.btnY);
+ CHECK(input::pollUsbPadsFor(2, out) && out.btnY);
+ input::usbPadDetached(1);
+ events = input::takeUsbPadEvents();
+ CHECK(events.size() == 1 && events[0].kind == UsbPadEvent::Kind::Disconnected && events[0].player == 0);
+ // Gone: its player is free for the next one.
+ input::usbPadAttached(1, "Xbox Wireless Controller");
+ CHECK(!input::pollUsbPadsFor(0, out) && input::usbPadPlayer(1) == 0);
+ input::usbPadDetached(0);
+ input::usbPadDetached(1);
+ input::takeUsbPadEvents();
+ CHECK(!input::pollUsbPad(out) && input::usbPadCount() == 0);
+ input::usbPadState(2, bitdo); // a slot that was never attached
+ CHECK(!input::pollUsbPad(out) && input::usbPadPlayer(2) == -1);
+ input::usbPadState(9, bitdo); // out of range: ignored
}
static void testDesktopMouseNav() {
@@ -4345,143 +4480,6 @@ static void testWebSocketRFC6455() {
CHECK(std::abs(csW3c.rightStickY - 0.8f) < 0.01f);
}
-static void testExpandedUsbControllers() {
- // 1. Xbox 360 controller report decoding (14 bytes)
- uint8_t x360[14] = {
- 0x00, 0x14,
- 0x11, // A (0x10) | DPAD_UP (0x01)
- 0x12, // Start (0x10) | RB (0x02)
- 128, // LT (50%)
- 255, // RT (100%)
- 0x00, 0x40, // LX = +16384 (~0.5)
- 0x00, 0xC0, // LY = -16384 (-0.5 raw -> +0.5 normalised)
- 0x00, 0x00, 0x00, 0x00
- };
- input::ControllerState cs360{};
- CHECK(input::parseXbox360Report(x360, sizeof(x360), cs360));
- CHECK(cs360.btnA == true);
- CHECK(cs360.dpadUp == true);
- CHECK(cs360.btnOptions == true);
- CHECK(cs360.btnR1 == true);
- CHECK(std::abs(cs360.triggerL2 - 0.5019f) < 0.01f);
- CHECK(std::abs(cs360.triggerR2 - 1.0f) < 0.01f);
- CHECK(std::abs(cs360.leftStickX - 0.5f) < 0.02f);
- CHECK(std::abs(cs360.leftStickY - 0.5f) < 0.02f);
-
- // 2. Xbox One / Series controller report decoding (18 bytes min, 0x20 header)
- uint8_t xone[18] = {
- 0x20, 0x00, 0x01, 0x0c,
- 0x50, // A (0x10) | X (0x40)
- 0x01, // D-pad Up
- 0x00, 0x02, // LT = 512 (~0.5)
- 0xFF, 0x03, // RT = 1023 (1.0)
- 0x00, 0x40, // LX = +16384 (0.5)
- 0x00, 0x80, // LY = -32768 (1.0)
- 0x00, 0x00, 0x00, 0x00
- };
- input::ControllerState csOne{};
- CHECK(input::parseXboxOneReport(xone, sizeof(xone), csOne));
- CHECK(csOne.btnA == true);
- CHECK(csOne.btnX == true);
- CHECK(csOne.btnB == false);
- CHECK(csOne.dpadUp == true);
- CHECK(std::abs(csOne.triggerL2 - 0.5f) < 0.02f);
- CHECK(std::abs(csOne.triggerR2 - 1.0f) < 0.01f);
- CHECK(std::abs(csOne.leftStickX - 0.5f) < 0.02f);
- CHECK(std::abs(csOne.leftStickY - 1.0f) < 0.02f);
-
- // 3. DualShock 4 controller report decoding (10 bytes min)
- uint8_t ds4[10] = {
- 0x01,
- 255, // LX full right (+1.0)
- 0, // LY full up (-1.0 -> inverted is -1.0)
- 128, 128,
- 0x20 | 0x02, // Cross (Xbox A) | D-pad East (Right)
- 0x02 | 0x20, // R1 (RB) | Options (Menu)
- 0x00,
- 0, 255 // RT = 1.0
- };
- input::ControllerState csDs4{};
- CHECK(input::parseDualShock4Report(ds4, sizeof(ds4), csDs4));
- CHECK(csDs4.btnA == true);
- CHECK(csDs4.dpadRight == true);
- CHECK(csDs4.btnR1 == true);
- CHECK(csDs4.btnOptions == true);
- CHECK(std::abs(csDs4.triggerR2 - 1.0f) < 0.01f);
- CHECK(std::abs(csDs4.leftStickX - 1.0f) < 0.02f);
-
- // 4. Generic Arcade Stick (6 bytes min)
- uint8_t arcade[6] = {
- 0, // Left
- 128, // Center Y
- 128, 128,
- 0x01 | 0x04, // Button 1 (A) | Button 3 (X)
- 0x01 // Button 9 (Select/View)
- };
- input::ControllerState csArcade{};
- CHECK(input::parseGenericArcadeReport(arcade, sizeof(arcade), csArcade));
- CHECK(csArcade.btnA == true);
- CHECK(csArcade.btnX == true);
- CHECK(csArcade.btnTouchpad == true);
- CHECK(csArcade.dpadLeft == true);
-
- // 5. parseUsbPadReport auto-detection
- input::ControllerState csAuto{};
- CHECK(input::parseUsbPadReport(x360, sizeof(x360), csAuto));
- CHECK(csAuto.btnA == true);
- CHECK(csAuto.btnR1 == true);
-
- CHECK(input::parseUsbPadReport(xone, sizeof(xone), csAuto));
- CHECK(csAuto.btnA == true);
- CHECK(csAuto.btnX == true);
-
- CHECK(input::parseUsbPadReport(ds4, sizeof(ds4), csAuto));
- // 6. Wireless receiver on non-zero slot (slot 1)
- uint8_t x360WirelessSlot1[18] = {
- 0x00, 0x01, 0x00, 0x14,
- 0x01, // b1: D-pad Up (0x01)
- 0x12, // b2: A (0x10) | RB (0x02)
- 0, 255, // LT=0, RT=255
- 0x00, 0x40, // LX = +16384 (0.5)
- 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
- };
- input::ControllerState csWireless{};
- CHECK(input::parseXbox360Report(x360WirelessSlot1, sizeof(x360WirelessSlot1), csWireless));
- CHECK(csWireless.dpadUp == true);
- CHECK(csWireless.btnA == true);
- CHECK(csWireless.btnR1 == true);
- CHECK(std::abs(csWireless.triggerR2 - 1.0f) < 0.01f);
- CHECK(input::parseUsbPadReport(x360WirelessSlot1, sizeof(x360WirelessSlot1), csWireless));
- CHECK(csWireless.dpadUp == true);
- CHECK(csWireless.btnA == true);
-
- // 7. Multi-slot simultaneous UHID injection & merging (Xbox 360 on slot 0 + DS4 on slot 1)
- input::padUsbInit();
- input::padUsbInjectSlotReportForTesting(0, x360, sizeof(x360));
- input::padUsbInjectSlotReportForTesting(1, ds4, sizeof(ds4));
-
- input::ControllerState mergedSlots{};
- CHECK(input::pollUsbPad(mergedSlots));
- CHECK(mergedSlots.connected);
- CHECK(mergedSlots.btnA == true); // From slot 0 (x360) and slot 1 (ds4)
- CHECK(mergedSlots.btnR1 == true); // From slot 0 & slot 1
- CHECK(mergedSlots.dpadUp == true); // From slot 0
- CHECK(mergedSlots.dpadRight == true); // From slot 1
- CHECK(std::abs(mergedSlots.leftStickX - 1.0f) < 0.02f); // Further(0.5, 1.0) -> 1.0
- CHECK(std::abs(mergedSlots.triggerR2 - 1.0f) < 0.01f);
-
- // Unplug slot 0 -> slot 1 remains active
- input::padUsbInjectSlotReportForTesting(0, nullptr, 0);
- input::ControllerState slot1Only{};
- CHECK(input::pollUsbPad(slot1Only));
- CHECK(slot1Only.connected);
- CHECK(slot1Only.dpadUp == false); // Slot 0 gone
- CHECK(slot1Only.dpadRight == true); // Slot 1 still present
- CHECK(slot1Only.btnR1 == true);
-
- input::padUsbShutdown();
-}
static void testAudioToHaptics() {
media::AudioToHaptics filter;
@@ -7055,10 +7053,11 @@ int main() {
testWebStreamingAndGamepad();
testWebSettingsAndStreamMenu();
testVoiceRouting();
- testUsbPad8BitDo();
+ testUsbPadReports();
+ testUsbPadDescriptors();
+ testUsbPadSlots();
testDesktopMouseNav();
testWebSocketRFC6455();
- testExpandedUsbControllers();
testAudioToHaptics();
testLibraryOfflineCache();
testTouchpadShortcutsAndSlots();