mode_xinput.cpp 14 KB

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