mode_xinput.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. // mode_xinput.cpp -- Xbox 360 wired (XInput) personality (MODE_XBOX): one XInput gamepad per bonded controller.
  2. //
  3. // Real Xbox 360 pads are NOT HID: they use a vendor interface (class 0xFF / sub 0x5D / proto 0x01) carrying a
  4. // 20-byte XInput report. A custom TinyUSB class driver serves that interface plus a second boot-mouse interface
  5. // for the right trackpad. Host binds by VID/PID (045E:028E) + the FF/5D/01 interface. The OUT endpoint carries
  6. // rumble, relayed to the controller as a haptic by task().
  7. //
  8. // Multi-controller: one XInput interface per CONNECTED controller (dynamic mount -- see usb_mount.h; the device
  9. // re-enumerates without rebooting as controllers connect/disconnect). The single class driver routes xfer/open
  10. // callbacks by endpoint address into the per-bond-slot state; xi_open claims slots in connection order. The
  11. // right-pad mouse is a single shared interface (only bond slot 0's right-pad drives it).
  12. #include "mode_xinput.h"
  13. #include "triton.h"
  14. #include "gamepad_util.h"
  15. #include "config.h"
  16. #include "haptics.h"
  17. #include "bonds.h"
  18. #include "usb_mount.h"
  19. #include <Adafruit_TinyUSB.h>
  20. #include <Arduino.h>
  21. #include <string.h>
  22. // custom class-driver API for the XInput interface
  23. extern "C" {
  24. #include "device/usbd_pvt.h"
  25. }
  26. XboxController g_xboxCtl;
  27. // XInput button bits
  28. enum {
  29. XB_DUP = 0x0001,
  30. XB_DDOWN = 0x0002,
  31. XB_DLEFT = 0x0004,
  32. XB_DRIGHT = 0x0008,
  33. XB_START = 0x0010,
  34. XB_BACK = 0x0020,
  35. XB_L3 = 0x0040,
  36. XB_R3 = 0x0080,
  37. XB_LB = 0x0100,
  38. XB_RB = 0x0200,
  39. XB_GUIDE = 0x0400,
  40. XB_A = 0x1000,
  41. XB_B = 0x2000,
  42. XB_X = 0x4000,
  43. XB_Y = 0x8000
  44. };
  45. // ===================== XInput custom TinyUSB class driver =====================
  46. // Custom class driver + an Adafruit_USBD_Interface subclass emitting the interface + 0x21-blob + 2 endpoints.
  47. // Per-slot state lives in g_xiSlot[]: each XInput interface gets one. The class driver dispatches open/xfer
  48. // by endpoint address; xinputSend() targets a specific slot's IN endpoint.
  49. #define XINPUT_DESC_LEN \
  50. (9 + 17 + 7 + 7) // interface(9)+vendor0x21(17)+IN ep(7)+OUT ep(7) = 40
  51. // per-slot state. `inUse` is set in xi_open from the USB ISR and read in xinputSend from the loop -- mark
  52. // volatile so the loop doesn't observe a stale 0 across a freshly-attached interface.
  53. struct XiSlot {
  54. uint8_t itf, epIn, epOut;
  55. uint8_t inBuf[32], outBuf[32];
  56. volatile uint16_t rumbleLow,
  57. rumbleHigh; // last host rumble values, x 257
  58. volatile unsigned long
  59. rumbleMs; // millis of last OUT packet (stuck-rumble watchdog)
  60. volatile bool inUse;
  61. };
  62. static XiSlot g_xiSlot[NSLOT];
  63. // Dynamic mount: xi_open is called once per XInput interface in descriptor order; this counts them so the
  64. // u-th interface claims the u-th connected controller (g_usbToBond[u]). Reset on every (re)enumeration.
  65. static uint8_t g_xiOpenU = 0;
  66. // release a held rumble if no OUT packet refreshes it for this long (covers a lost stop)
  67. #define RUMBLE_STUCK_MS 2500u
  68. static void xi_init(void)
  69. {
  70. for (int s = 0; s < NSLOT; s++)
  71. g_xiSlot[s].inUse = false;
  72. }
  73. static bool xi_deinit(void)
  74. {
  75. return true;
  76. }
  77. static void xi_reset(uint8_t rhport)
  78. {
  79. (void)rhport;
  80. g_xiOpenU = 0; // restart per-interface claim ordering for this enumeration
  81. for (int s = 0; s < NSLOT; s++) {
  82. g_xiSlot[s].itf = 0;
  83. g_xiSlot[s].epIn = g_xiSlot[s].epOut = 0;
  84. g_xiSlot[s].inUse = false;
  85. }
  86. }
  87. // TinyUSB calls xi_open once per XInput interface in the config descriptor. Claim the first free BONDED
  88. // slot so the xiSlot index matches the bond-slot index (begin() registers them in ascending bond-slot order).
  89. // Fallback to any free slot when there are no bonds (fresh device).
  90. static uint16_t xi_open(uint8_t rhport, tusb_desc_interface_t const *itf,
  91. uint16_t max_len)
  92. {
  93. if (!(itf->bInterfaceClass == 0xFF && itf->bInterfaceSubClass == 0x5D &&
  94. itf->bInterfaceProtocol == 0x01))
  95. return 0;
  96. // The u-th XInput interface in the descriptor serves the u-th connected controller. g_xiSlot is keyed by
  97. // BOND slot so onReport45(bond)/rumble route straight through; only connected bonds get an interface.
  98. uint8_t u = g_xiOpenU++;
  99. int slot = (u < g_usbMountCount) ? g_usbToBond[u] : -1;
  100. if (slot < 0) { // fallback (e.g. map not built): first free slot
  101. for (int s = 0; s < NSLOT; s++)
  102. if (!g_xiSlot[s].inUse) {
  103. slot = s;
  104. break;
  105. }
  106. }
  107. if (slot < 0 || slot >= NSLOT || g_xiSlot[slot].inUse)
  108. return 0;
  109. XiSlot &S = g_xiSlot[slot];
  110. S.itf = itf->bInterfaceNumber;
  111. uint8_t const *p = (uint8_t const *)itf;
  112. uint8_t const *end = p + max_len;
  113. uint16_t used = itf->bLength;
  114. p += itf->bLength;
  115. uint8_t opened = 0;
  116. while (p < end && opened < itf->bNumEndpoints) {
  117. uint8_t blen = p[0], btype = p[1];
  118. if (btype == TUSB_DESC_ENDPOINT) {
  119. tusb_desc_endpoint_t const *ep =
  120. (tusb_desc_endpoint_t const *)p;
  121. usbd_edpt_open(rhport, ep);
  122. if (tu_edpt_dir(ep->bEndpointAddress) == TUSB_DIR_IN)
  123. S.epIn = ep->bEndpointAddress;
  124. else
  125. S.epOut = ep->bEndpointAddress;
  126. opened++;
  127. }
  128. used += blen;
  129. p += blen;
  130. }
  131. S.inUse = true;
  132. // arm OUT (rumble/LED)
  133. if (S.epOut)
  134. usbd_edpt_xfer(rhport, S.epOut, S.outBuf, sizeof S.outBuf);
  135. return used;
  136. }
  137. static bool xi_ctrl(uint8_t rhport, uint8_t stage,
  138. tusb_control_request_t const *req)
  139. {
  140. (void)rhport;
  141. (void)req;
  142. return stage != CONTROL_STAGE_SETUP;
  143. }
  144. // Route an endpoint xfer callback to the slot that owns that endpoint.
  145. static bool xi_xfer(uint8_t rhport, uint8_t ep, xfer_result_t res, uint32_t n)
  146. {
  147. (void)res;
  148. for (int s = 0; s < NSLOT; s++) {
  149. XiSlot &S = g_xiSlot[s];
  150. if (!S.inUse)
  151. continue;
  152. if (ep == S.epOut) {
  153. // XInput rumble packet: [00][08][00][bigMotor][smallMotor][00][00][00]; LED pkt is [01][03][led]
  154. if (n >= 5 && S.outBuf[0] == 0x00 &&
  155. S.outBuf[1] == 0x08) {
  156. uint8_t big = S.outBuf[3], sml = S.outBuf[4];
  157. uint16_t lo = (uint16_t)big * 257u;
  158. uint16_t hi = (uint16_t)sml * 257u;
  159. S.rumbleLow = lo;
  160. S.rumbleHigh = hi;
  161. S.rumbleMs = millis();
  162. hapticSteamRumble(lo, hi, (uint8_t)s);
  163. }
  164. usbd_edpt_xfer(rhport, S.epOut, S.outBuf,
  165. sizeof S.outBuf);
  166. return true;
  167. }
  168. }
  169. return true;
  170. }
  171. static const usbd_class_driver_t g_xiDriver = {
  172. #if CFG_TUSB_DEBUG >= 2
  173. .name = "XINPUT",
  174. #endif
  175. .init = xi_init,
  176. .deinit = xi_deinit,
  177. .reset = xi_reset,
  178. .open = xi_open,
  179. .control_xfer_cb = xi_ctrl,
  180. .xfer_cb = xi_xfer,
  181. .sof = NULL
  182. };
  183. extern "C" const usbd_class_driver_t *usbd_app_driver_get_cb(uint8_t *count)
  184. {
  185. *count = 1;
  186. return &g_xiDriver;
  187. }
  188. class Adafruit_USBD_XInput : public Adafruit_USBD_Interface {
  189. public:
  190. uint16_t getInterfaceDescriptor(uint8_t, uint8_t *buf,
  191. uint16_t bufsize) override
  192. {
  193. if (!buf)
  194. return XINPUT_DESC_LEN;
  195. if (bufsize < XINPUT_DESC_LEN)
  196. return 0;
  197. uint8_t itfnum = TinyUSBDevice.allocInterface(1);
  198. uint8_t epin = TinyUSBDevice.allocEndpoint(TUSB_DIR_IN),
  199. epout = TinyUSBDevice.allocEndpoint(TUSB_DIR_OUT);
  200. const uint8_t t[XINPUT_DESC_LEN] = {
  201. 9, TUSB_DESC_INTERFACE, itfnum, 0x00, 0x02, 0xFF, 0x5D,
  202. 0x01, _strid, 0x11, 0x21, 0x00, 0x01, 0x01, 0x25, epin,
  203. 0x14, 0x00, 0x00, 0x00, 0x00, 0x13, epout, 0x08, 0x00,
  204. 0x00, 7, TUSB_DESC_ENDPOINT, epin, TUSB_XFER_INTERRUPT,
  205. U16_TO_U8S_LE(0x20),
  206. // bInterval 1ms (1000Hz) so the RF rate is the only limit
  207. 1, 7, TUSB_DESC_ENDPOINT, epout, TUSB_XFER_INTERRUPT,
  208. U16_TO_U8S_LE(0x20), 8
  209. };
  210. memcpy(buf, t, XINPUT_DESC_LEN);
  211. return XINPUT_DESC_LEN;
  212. }
  213. bool begin()
  214. {
  215. return TinyUSBDevice.addInterface(*this);
  216. }
  217. };
  218. // NSLOT instances: each registers its own XInput interface (own itfnum + IN/OUT ep pair) during begin().
  219. // begin() in XboxController::begin() runs in order 0..NSLOT-1, so xi_open's first-free assignment lines up.
  220. static Adafruit_USBD_XInput g_xinput[NSLOT];
  221. static void xinputSend(uint8_t slot, uint16_t buttons, uint8_t lt, uint8_t rt,
  222. int16_t lx, int16_t ly, int16_t rx, int16_t ry)
  223. {
  224. if (slot >= NSLOT || !g_xiSlot[slot].inUse)
  225. return;
  226. XiSlot &S = g_xiSlot[slot];
  227. if (!tud_mounted() || S.epIn == 0 || usbd_edpt_busy(0, S.epIn))
  228. return;
  229. uint8_t *r = S.inBuf;
  230. r[0] = 0x00;
  231. r[1] = 0x14;
  232. r[2] = buttons & 0xFF;
  233. r[3] = buttons >> 8;
  234. r[4] = lt;
  235. r[5] = rt;
  236. r[6] = lx & 0xFF;
  237. r[7] = lx >> 8;
  238. r[8] = ly & 0xFF;
  239. r[9] = ly >> 8;
  240. r[10] = rx & 0xFF;
  241. r[11] = rx >> 8;
  242. r[12] = ry & 0xFF;
  243. r[13] = ry >> 8;
  244. memset(r + 14, 0, 6);
  245. if (usbd_edpt_claim(0, S.epIn)) {
  246. if (!usbd_edpt_xfer(0, S.epIn, r, 20))
  247. usbd_edpt_release(0, S.epIn);
  248. }
  249. }
  250. // ===================== right-pad mouse interface =====================
  251. static const uint8_t MOUSE_HID_DESC[] = { TUD_HID_REPORT_DESC_MOUSE() };
  252. static Adafruit_USBD_HID
  253. g_mouse; // Xbox-mode mouse interface (right trackpad, slot 0 only)
  254. // ===================== report 0x45 -> XInput + mouse =====================
  255. // button code (g_back[], g_abSwap targets) -> legacy XInput bit. 0=none 1=A 2=B 3=X 4=Y 5=LB 6=RB 7=L3 8=R3 9=Back 10=Start 11=Guide 12=Dup 13=Ddown 14=Dleft 15=Dright
  256. static uint16_t codeToXB(uint8_t c)
  257. {
  258. switch (c) {
  259. case 1:
  260. return XB_A;
  261. case 2:
  262. return XB_B;
  263. case 3:
  264. return XB_X;
  265. case 4:
  266. return XB_Y;
  267. case 5:
  268. return XB_LB;
  269. case 6:
  270. return XB_RB;
  271. case 7:
  272. return XB_L3;
  273. case 8:
  274. return XB_R3;
  275. case 9:
  276. return XB_BACK;
  277. case 10:
  278. return XB_START;
  279. case 11:
  280. return XB_GUIDE;
  281. case 12:
  282. return XB_DUP;
  283. case 13:
  284. return XB_DDOWN;
  285. case 14:
  286. return XB_DLEFT;
  287. case 15:
  288. return XB_DRIGHT;
  289. default:
  290. return 0;
  291. }
  292. }
  293. static void rfXboxGamepad(uint8_t slot, const uint8_t *r)
  294. {
  295. uint32_t b = btnsOf(r);
  296. if (g_qamMap && (b & TB_QAM)) {
  297. b &= ~(uint32_t)TB_QAM;
  298. b |= tritonFromCode(g_qamMap);
  299. }
  300. uint16_t btn = 0;
  301. if (b & TB_DUP)
  302. btn |= XB_DUP;
  303. if (b & TB_DDN)
  304. btn |= XB_DDOWN;
  305. if (b & TB_DLF)
  306. btn |= XB_DLEFT;
  307. if (b & TB_DRT)
  308. btn |= XB_DRIGHT;
  309. if (b & TB_VIEW)
  310. btn |= XB_START;
  311. if (b & TB_MENU)
  312. btn |= XB_BACK;
  313. if (b & TB_STEAM)
  314. btn |= XB_GUIDE;
  315. if (b & TB_LB)
  316. btn |= XB_LB;
  317. if (b & TB_RB)
  318. btn |= XB_RB;
  319. if (b & TB_L3)
  320. btn |= XB_L3;
  321. if (b & TB_R3)
  322. btn |= XB_R3;
  323. // face buttons, with optional A/B + X/Y swap (Nintendo layout)
  324. uint16_t fA = g_abSwap ? XB_B : XB_A, fB = g_abSwap ? XB_A : XB_B,
  325. fX = g_abSwap ? XB_Y : XB_X, fY = g_abSwap ? XB_X : XB_Y;
  326. if (b & TB_A)
  327. btn |= fA;
  328. if (b & TB_B)
  329. btn |= fB;
  330. if (b & TB_X)
  331. btn |= fX;
  332. if (b & TB_Y)
  333. btn |= fY;
  334. // back paddles -> configurable mapping (default L4->LB, R4->RB, L5->L3, R5->R3)
  335. if (b & TB_L4)
  336. btn |= codeToXB(g_back[0]);
  337. if (b & TB_R4)
  338. btn |= codeToXB(g_back[1]);
  339. if (b & TB_L5)
  340. btn |= codeToXB(g_back[2]);
  341. if (b & TB_R5)
  342. btn |= codeToXB(g_back[3]);
  343. uint8_t lt = trigU8(u16off(r, 4)),
  344. rt = trigU8(u16off(
  345. r, 6)); // triggers u16 (half-scale) -> full-range u8
  346. // Trigger remaps (codes 19=LT, 20=RT): XInput triggers are analog bytes, not buttons, so a back paddle /
  347. // QAM mapped to a trigger pulls it full. QAM arrives as TB_L2/TB_R2 (folded into b via tritonFromCode);
  348. // back paddles are matched by their configured code.
  349. if (b & TB_L2)
  350. lt = 0xFF;
  351. if (b & TB_R2)
  352. rt = 0xFF;
  353. const uint8_t bc[4] = { g_back[0], g_back[1], g_back[2], g_back[3] };
  354. const uint32_t bm[4] = { TB_L4, TB_R4, TB_L5, TB_R5 };
  355. for (int i = 0; i < 4; i++) {
  356. if (!(b & bm[i]))
  357. continue;
  358. if (bc[i] == 19)
  359. lt = 0xFF;
  360. else if (bc[i] == 20)
  361. rt = 0xFF;
  362. }
  363. xinputSend(slot, btn, lt, rt, (int16_t)s16off(r, 8),
  364. (int16_t)s16off(r, 10), // L stick X/Y
  365. (int16_t)s16off(r, 12),
  366. (int16_t)s16off(r, 14)); // R stick X/Y
  367. }
  368. // Right pad -> mouse on a second HID-mouse interface alongside the XInput gamepad. Same glide model as Lizard's
  369. // right pad; RPad click = left button, LPad click = right. SINGLE shared mouse: the desktop can only consume
  370. // one mouse. Slot 0's right-pad drives it; other slots' right-pad input is intentionally ignored here.
  371. static void rfXboxMouse(const uint8_t *r)
  372. {
  373. uint32_t b = btnsOf(r);
  374. static int prx = 0, pry = 0;
  375. static bool prt = false;
  376. static float vx = 0, vy = 0, rmx = 0, rmy = 0;
  377. static uint8_t pmb = 0;
  378. bool rtouch = b & TB_RPADT;
  379. int rx = s16off(r, 22), ry = s16off(r, 24);
  380. if (rtouch) {
  381. if (prt) {
  382. vx += (rx - prx);
  383. vy += (ry - pry);
  384. }
  385. prx = rx;
  386. pry = ry;
  387. }
  388. prt = rtouch;
  389. float mxf = vx / (float)(g_mDiv * 10) + rmx,
  390. myf = -(vy / (float)(g_mDiv * 10)) +
  391. rmy; // Y inverted for screen coords
  392. int dx = (int)mxf, dy = (int)myf;
  393. rmx = mxf - dx;
  394. rmy = myf - dy; // sub-pixel carry
  395. if (dx > 127)
  396. dx = 127;
  397. if (dx < -127)
  398. dx = -127;
  399. if (dy > 127)
  400. dy = 127;
  401. if (dy < -127)
  402. dy = -127;
  403. float f = g_mFric / 100.0f;
  404. vx *= f;
  405. vy *= f;
  406. if (vx > -1 && vx < 1)
  407. vx = 0;
  408. if (vy > -1 && vy < 1)
  409. vy = 0; // friction = glide/decay
  410. uint8_t mb = ((b & TB_RPADC) ? 1 : 0) |
  411. ((b & TB_LPADC) ?
  412. 2 :
  413. 0); // RPad click = left, LPad click = right
  414. if (dx || dy || mb != pmb) {
  415. pmb = mb;
  416. hid_mouse_report_t m;
  417. m.buttons = mb;
  418. m.x = (int8_t)dx;
  419. m.y = (int8_t)dy;
  420. m.wheel = 0;
  421. m.pan = 0;
  422. if (g_mouse.ready())
  423. g_mouse.sendReport(0, &m, sizeof m);
  424. }
  425. }
  426. // ===================== IController =====================
  427. // Dynamic-mount mode: begin() is unused (setup() calls beginPool()+usbReenumerate instead).
  428. void XboxController::begin()
  429. {
  430. }
  431. // XInput slot interfaces are a custom (non-HID) class, so they don't draw on the CFG_TUD_HID budget (only the
  432. // wake mouse + right-pad mouse do). Slots are limited by NSLOT / USB endpoints, not HID instances.
  433. uint8_t XboxController::maxSlots() const
  434. {
  435. return (uint8_t)NSLOT;
  436. }
  437. void XboxController::usbIdentity()
  438. {
  439. // 045E:028E -> Windows xusb / SDL / Linux xpad all bind it
  440. USBDevice.setID(0x045E, 0x028E);
  441. USBDevice.setDeviceVersion(0x0120);
  442. USBDevice.setManufacturerDescriptor("Microsoft");
  443. USBDevice.setProductDescriptor("Controller");
  444. }
  445. void XboxController::beginPool()
  446. {
  447. // Lock the right-pad mouse HID instance (wake mouse was begun first by setup -> this is HID instance 1).
  448. g_mouse.setStringDescriptor("OpenPuck Mouse");
  449. g_mouse.setBootProtocol(HID_ITF_PROTOCOL_MOUSE);
  450. g_mouse.setReportDescriptor(MOUSE_HID_DESC, sizeof MOUSE_HID_DESC);
  451. g_mouse.setPollInterval(1);
  452. g_mouse.begin();
  453. for (int s = 0; s < NSLOT; s++)
  454. g_xinput[s].setStringDescriptor("Controller");
  455. }
  456. void XboxController::mountSlots(uint8_t k)
  457. {
  458. // Right-pad mouse first (fixed HID), then one XInput interface per connected controller (claimed in
  459. // order by xi_open). The wake mouse + WebUSB are added around this by usbReenumerate.
  460. USBDevice.addInterface(g_mouse);
  461. for (uint8_t u = 0; u < k; u++)
  462. USBDevice.addInterface(g_xinput[u]);
  463. }
  464. void XboxController::onReport45(int slot, const uint8_t *rep, bool fresh,
  465. uint8_t bodyTlen)
  466. {
  467. (void)fresh;
  468. (void)bodyTlen;
  469. if (slot < 0 || slot >= NSLOT)
  470. return;
  471. rfXboxGamepad((uint8_t)slot, rep);
  472. // Shared desktop mouse: slot 0's right-pad only. Other slots' right-pad is still part of the
  473. // per-slot XInput (TB_RPADT in the gamepad report is unused today but kept for forward-compat).
  474. if (slot == 0)
  475. rfXboxMouse(rep);
  476. }
  477. // Lost-stop watchdog per slot: Steam/Triton rumble is latched, so force a zero report if the host stops
  478. // refreshing on a particular XInput. The haptics.cpp global watchdog fires too, but it skips while the slot
  479. // is in the post-reconnect block -- this catches a host that kept streaming while we were blocked.
  480. void XboxController::task()
  481. {
  482. for (int s = 0; s < NSLOT; s++) {
  483. if (!g_xiSlot[s].inUse)
  484. continue;
  485. if ((g_xiSlot[s].rumbleLow || g_xiSlot[s].rumbleHigh) &&
  486. millis() - g_xiSlot[s].rumbleMs > RUMBLE_STUCK_MS) {
  487. g_xiSlot[s].rumbleLow = g_xiSlot[s].rumbleHigh = 0;
  488. hapticSteamRumble(0, 0, (uint8_t)s);
  489. }
  490. }
  491. }