SDL_hidapi_ps4.c 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. /* This driver supports both simplified reports and the extended input reports enabled by Steam.
  19. Code and logic contributed by Valve Corporation under the SDL zlib license.
  20. */
  21. #include "SDL_internal.h"
  22. #ifdef SDL_JOYSTICK_HIDAPI
  23. #include "../../SDL_hints_c.h"
  24. #include "../SDL_sysjoystick.h"
  25. #include "SDL_hidapijoystick_c.h"
  26. #include "SDL_hidapi_rumble.h"
  27. #ifdef SDL_JOYSTICK_HIDAPI_PS4
  28. // Define this if you want to log all packets from the controller
  29. #if 0
  30. #define DEBUG_PS4_PROTOCOL
  31. #endif
  32. // Define this if you want to log calibration data
  33. #if 0
  34. #define DEBUG_PS4_CALIBRATION
  35. #endif
  36. #define BLUETOOTH_DISCONNECT_TIMEOUT_MS 500
  37. #define LOAD16(A, B) (Sint16)((Uint16)(A) | (((Uint16)(B)) << 8))
  38. #define LOAD32(A, B, C, D) ((((Uint32)(A)) << 0) | \
  39. (((Uint32)(B)) << 8) | \
  40. (((Uint32)(C)) << 16) | \
  41. (((Uint32)(D)) << 24))
  42. enum
  43. {
  44. SDL_GAMEPAD_BUTTON_PS4_TOUCHPAD = 11
  45. };
  46. typedef enum
  47. {
  48. k_EPS4ReportIdUsbState = 1,
  49. k_EPS4ReportIdUsbEffects = 5,
  50. k_EPS4ReportIdBluetoothState1 = 17,
  51. k_EPS4ReportIdBluetoothState2 = 18,
  52. k_EPS4ReportIdBluetoothState3 = 19,
  53. k_EPS4ReportIdBluetoothState4 = 20,
  54. k_EPS4ReportIdBluetoothState5 = 21,
  55. k_EPS4ReportIdBluetoothState6 = 22,
  56. k_EPS4ReportIdBluetoothState7 = 23,
  57. k_EPS4ReportIdBluetoothState8 = 24,
  58. k_EPS4ReportIdBluetoothState9 = 25,
  59. k_EPS4ReportIdBluetoothEffects = 17,
  60. k_EPS4ReportIdDisconnectMessage = 226,
  61. } EPS4ReportId;
  62. typedef enum
  63. {
  64. k_ePS4FeatureReportIdGyroCalibration_USB = 0x02,
  65. k_ePS4FeatureReportIdCapabilities = 0x03,
  66. k_ePS4FeatureReportIdGyroCalibration_BT = 0x05,
  67. k_ePS4FeatureReportIdSerialNumber = 0x12,
  68. } EPS4FeatureReportID;
  69. typedef struct
  70. {
  71. Uint8 ucLeftJoystickX;
  72. Uint8 ucLeftJoystickY;
  73. Uint8 ucRightJoystickX;
  74. Uint8 ucRightJoystickY;
  75. Uint8 rgucButtonsHatAndCounter[3];
  76. Uint8 ucTriggerLeft;
  77. Uint8 ucTriggerRight;
  78. Uint8 rgucTimestamp[2];
  79. Uint8 _rgucPad0[1];
  80. Uint8 rgucGyroX[2];
  81. Uint8 rgucGyroY[2];
  82. Uint8 rgucGyroZ[2];
  83. Uint8 rgucAccelX[2];
  84. Uint8 rgucAccelY[2];
  85. Uint8 rgucAccelZ[2];
  86. Uint8 _rgucPad1[5];
  87. Uint8 ucBatteryLevel;
  88. Uint8 _rgucPad2[4];
  89. Uint8 ucTouchpadCounter1;
  90. Uint8 rgucTouchpadData1[3];
  91. Uint8 ucTouchpadCounter2;
  92. Uint8 rgucTouchpadData2[3];
  93. } PS4StatePacket_t;
  94. typedef struct
  95. {
  96. Uint8 ucRumbleRight;
  97. Uint8 ucRumbleLeft;
  98. Uint8 ucLedRed;
  99. Uint8 ucLedGreen;
  100. Uint8 ucLedBlue;
  101. Uint8 ucLedDelayOn;
  102. Uint8 ucLedDelayOff;
  103. Uint8 _rgucPad0[8];
  104. Uint8 ucVolumeLeft;
  105. Uint8 ucVolumeRight;
  106. Uint8 ucVolumeMic;
  107. Uint8 ucVolumeSpeaker;
  108. } DS4EffectsState_t;
  109. typedef struct
  110. {
  111. Sint16 bias;
  112. float scale;
  113. } IMUCalibrationData;
  114. /* Rumble hint mode:
  115. * default: enhanced features are available if the controller is using enhanced reports
  116. * "0": enhanced features are never used
  117. * "1": enhanced features are always used
  118. * "auto": enhanced features are advertised to the application, but SDL doesn't touch the controller state unless the application explicitly requests it.
  119. */
  120. typedef enum
  121. {
  122. PS4_RUMBLE_HINT_DEFAULT,
  123. PS4_RUMBLE_HINT_OFF,
  124. PS4_RUMBLE_HINT_ON,
  125. PS4_RUMBLE_HINT_AUTO
  126. } SDL_PS4_RumbleHintMode;
  127. typedef struct
  128. {
  129. SDL_HIDAPI_Device *device;
  130. SDL_Joystick *joystick;
  131. bool is_dongle;
  132. bool is_nacon_dongle;
  133. bool official_controller;
  134. bool sensors_supported;
  135. bool lightbar_supported;
  136. bool vibration_supported;
  137. bool touchpad_supported;
  138. bool effects_supported;
  139. SDL_PS4_RumbleHintMode rumble_hint;
  140. bool enhanced_reports;
  141. bool enhanced_mode;
  142. bool enhanced_mode_available;
  143. Uint8 report_interval;
  144. bool report_sensors;
  145. bool report_touchpad;
  146. bool report_battery;
  147. bool hardware_calibration;
  148. IMUCalibrationData calibration[6];
  149. Uint64 last_packet;
  150. int player_index;
  151. Uint8 rumble_left;
  152. Uint8 rumble_right;
  153. bool color_set;
  154. Uint8 led_red;
  155. Uint8 led_green;
  156. Uint8 led_blue;
  157. Uint16 gyro_numerator;
  158. Uint16 gyro_denominator;
  159. Uint16 accel_numerator;
  160. Uint16 accel_denominator;
  161. Uint64 sensor_ticks;
  162. Uint16 last_tick;
  163. Uint16 valid_crc_packets; // wrapping counter
  164. PS4StatePacket_t last_state;
  165. } SDL_DriverPS4_Context;
  166. static bool HIDAPI_DriverPS4_InternalSendJoystickEffect(SDL_DriverPS4_Context *ctx, const void *effect, int size, bool application_usage);
  167. static void HIDAPI_DriverPS4_RegisterHints(SDL_HintCallback callback, void *userdata)
  168. {
  169. SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS4, callback, userdata);
  170. }
  171. static void HIDAPI_DriverPS4_UnregisterHints(SDL_HintCallback callback, void *userdata)
  172. {
  173. SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS4, callback, userdata);
  174. }
  175. static bool HIDAPI_DriverPS4_IsEnabled(void)
  176. {
  177. return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_PS4, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT));
  178. }
  179. static int ReadFeatureReport(SDL_hid_device *dev, Uint8 report_id, Uint8 *report, size_t length)
  180. {
  181. SDL_memset(report, 0, length);
  182. report[0] = report_id;
  183. return SDL_hid_get_feature_report(dev, report, length);
  184. }
  185. static bool HIDAPI_DriverPS4_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol)
  186. {
  187. Uint8 data[USB_PACKET_LENGTH];
  188. int size;
  189. if (type == SDL_GAMEPAD_TYPE_PS4) {
  190. return true;
  191. }
  192. if (HIDAPI_SupportsPlaystationDetection(vendor_id, product_id)) {
  193. if (device && device->dev) {
  194. size = ReadFeatureReport(device->dev, k_ePS4FeatureReportIdCapabilities, data, sizeof(data));
  195. if (size == 48 && data[2] == 0x27) {
  196. // Supported third party controller
  197. return true;
  198. } else {
  199. return false;
  200. }
  201. } else {
  202. // Might be supported by this driver, enumerate and find out
  203. return true;
  204. }
  205. }
  206. return false;
  207. }
  208. static void SetLedsForPlayerIndex(DS4EffectsState_t *effects, int player_index)
  209. {
  210. /* This list is the same as what hid-sony.c uses in the Linux kernel.
  211. The first 4 values correspond to what the PS4 assigns.
  212. */
  213. static const Uint8 colors[7][3] = {
  214. { 0x00, 0x00, 0x40 }, // Blue
  215. { 0x40, 0x00, 0x00 }, // Red
  216. { 0x00, 0x40, 0x00 }, // Green
  217. { 0x20, 0x00, 0x20 }, // Pink
  218. { 0x02, 0x01, 0x00 }, // Orange
  219. { 0x00, 0x01, 0x01 }, // Teal
  220. { 0x01, 0x01, 0x01 } // White
  221. };
  222. if (player_index >= 0) {
  223. player_index %= SDL_arraysize(colors);
  224. } else {
  225. player_index = 0;
  226. }
  227. effects->ucLedRed = colors[player_index][0];
  228. effects->ucLedGreen = colors[player_index][1];
  229. effects->ucLedBlue = colors[player_index][2];
  230. }
  231. static bool ReadWiredSerial(SDL_HIDAPI_Device *device, char *serial, size_t serial_size)
  232. {
  233. Uint8 data[USB_PACKET_LENGTH];
  234. int size;
  235. size = ReadFeatureReport(device->dev, k_ePS4FeatureReportIdSerialNumber, data, sizeof(data));
  236. if (size >= 7 && (data[1] || data[2] || data[3] || data[4] || data[5] || data[6])) {
  237. (void)SDL_snprintf(serial, serial_size, "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x",
  238. data[6], data[5], data[4], data[3], data[2], data[1]);
  239. return true;
  240. }
  241. return false;
  242. }
  243. static bool HIDAPI_DriverPS4_InitDevice(SDL_HIDAPI_Device *device)
  244. {
  245. SDL_DriverPS4_Context *ctx;
  246. Uint8 data[USB_PACKET_LENGTH];
  247. int size;
  248. char serial[18];
  249. SDL_JoystickType joystick_type = SDL_JOYSTICK_TYPE_GAMEPAD;
  250. ctx = (SDL_DriverPS4_Context *)SDL_calloc(1, sizeof(*ctx));
  251. if (!ctx) {
  252. return false;
  253. }
  254. ctx->device = device;
  255. ctx->gyro_numerator = 1;
  256. ctx->gyro_denominator = 16;
  257. ctx->accel_numerator = 1;
  258. ctx->accel_denominator = 8192;
  259. device->context = ctx;
  260. if (device->serial && SDL_strlen(device->serial) == 12) {
  261. int i, j;
  262. j = -1;
  263. for (i = 0; i < 12; i += 2) {
  264. j += 1;
  265. SDL_memcpy(&serial[j], &device->serial[i], 2);
  266. j += 2;
  267. serial[j] = '-';
  268. }
  269. serial[j] = '\0';
  270. } else {
  271. serial[0] = '\0';
  272. }
  273. // Check for type of connection
  274. ctx->is_dongle = (device->vendor_id == USB_VENDOR_SONY && device->product_id == USB_PRODUCT_SONY_DS4_DONGLE);
  275. if (ctx->is_dongle) {
  276. ReadWiredSerial(device, serial, sizeof(serial));
  277. ctx->enhanced_reports = true;
  278. } else if (device->vendor_id == USB_VENDOR_SONY && device->product_id == USB_PRODUCT_SONY_DS4_STRIKEPAD) {
  279. ctx->enhanced_reports = true;
  280. } else if (device->vendor_id == USB_VENDOR_SONY) {
  281. if (device->is_bluetooth) {
  282. // Read a report to see if we're in enhanced mode
  283. size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 16);
  284. #ifdef DEBUG_PS4_PROTOCOL
  285. if (size > 0) {
  286. HIDAPI_DumpPacket("PS4 first packet: size = %d", data, size);
  287. } else {
  288. SDL_Log("PS4 first packet: size = %d\n", size);
  289. }
  290. #endif
  291. if (size > 0 &&
  292. data[0] >= k_EPS4ReportIdBluetoothState1 &&
  293. data[0] <= k_EPS4ReportIdBluetoothState9) {
  294. ctx->enhanced_reports = true;
  295. }
  296. } else {
  297. ReadWiredSerial(device, serial, sizeof(serial));
  298. ctx->enhanced_reports = true;
  299. }
  300. } else {
  301. // Third party controllers appear to all be wired
  302. ctx->enhanced_reports = true;
  303. }
  304. if (device->vendor_id == USB_VENDOR_SONY) {
  305. ctx->official_controller = true;
  306. ctx->sensors_supported = true;
  307. ctx->lightbar_supported = true;
  308. ctx->vibration_supported = true;
  309. ctx->touchpad_supported = true;
  310. } else {
  311. // Third party controller capability request
  312. size = ReadFeatureReport(device->dev, k_ePS4FeatureReportIdCapabilities, data, sizeof(data));
  313. // Get the device capabilities
  314. if (size == 48 && data[2] == 0x27) {
  315. Uint8 capabilities = data[4];
  316. Uint8 device_type = data[5];
  317. Uint16 gyro_numerator = LOAD16(data[10], data[11]);
  318. Uint16 gyro_denominator = LOAD16(data[12], data[13]);
  319. Uint16 accel_numerator = LOAD16(data[14], data[15]);
  320. Uint16 accel_denominator = LOAD16(data[16], data[17]);
  321. #ifdef DEBUG_PS4_PROTOCOL
  322. HIDAPI_DumpPacket("PS4 capabilities: size = %d", data, size);
  323. #endif
  324. if (capabilities & 0x02) {
  325. ctx->sensors_supported = true;
  326. }
  327. if (capabilities & 0x04) {
  328. ctx->lightbar_supported = true;
  329. }
  330. if (capabilities & 0x08) {
  331. ctx->vibration_supported = true;
  332. }
  333. if (capabilities & 0x40) {
  334. ctx->touchpad_supported = true;
  335. }
  336. switch (device_type) {
  337. case 0x00:
  338. joystick_type = SDL_JOYSTICK_TYPE_GAMEPAD;
  339. break;
  340. case 0x01:
  341. joystick_type = SDL_JOYSTICK_TYPE_GUITAR;
  342. break;
  343. case 0x02:
  344. joystick_type = SDL_JOYSTICK_TYPE_DRUM_KIT;
  345. break;
  346. case 0x04:
  347. joystick_type = SDL_JOYSTICK_TYPE_DANCE_PAD;
  348. break;
  349. case 0x06:
  350. joystick_type = SDL_JOYSTICK_TYPE_WHEEL;
  351. break;
  352. case 0x07:
  353. joystick_type = SDL_JOYSTICK_TYPE_ARCADE_STICK;
  354. break;
  355. case 0x08:
  356. joystick_type = SDL_JOYSTICK_TYPE_FLIGHT_STICK;
  357. break;
  358. default:
  359. joystick_type = SDL_JOYSTICK_TYPE_UNKNOWN;
  360. break;
  361. }
  362. if (gyro_numerator && gyro_denominator) {
  363. ctx->gyro_numerator = gyro_numerator;
  364. ctx->gyro_denominator = gyro_denominator;
  365. }
  366. if (accel_numerator && accel_denominator) {
  367. ctx->accel_numerator = accel_numerator;
  368. ctx->accel_denominator = accel_denominator;
  369. }
  370. } else if (device->vendor_id == USB_VENDOR_RAZER) {
  371. // The Razer Raiju doesn't respond to the detection protocol, but has a touchpad and vibration
  372. ctx->vibration_supported = true;
  373. ctx->touchpad_supported = true;
  374. }
  375. }
  376. ctx->effects_supported = (ctx->lightbar_supported || ctx->vibration_supported);
  377. if (device->vendor_id == USB_VENDOR_NACON_ALT &&
  378. device->product_id == USB_PRODUCT_NACON_REVOLUTION_5_PRO_PS4_WIRELESS) {
  379. ctx->is_nacon_dongle = true;
  380. }
  381. if (device->vendor_id == USB_VENDOR_PDP &&
  382. (device->product_id == USB_PRODUCT_VICTRIX_FS_PRO ||
  383. device->product_id == USB_PRODUCT_VICTRIX_FS_PRO_V2)) {
  384. /* The Victrix FS Pro V2 reports that it has lightbar support,
  385. * but it doesn't respond to the effects packet, and will hang
  386. * on reboot if we send it.
  387. */
  388. ctx->effects_supported = false;
  389. }
  390. device->joystick_type = joystick_type;
  391. device->type = SDL_GAMEPAD_TYPE_PS4;
  392. if (ctx->official_controller) {
  393. HIDAPI_SetDeviceName(device, "PS4 Controller");
  394. }
  395. HIDAPI_SetDeviceSerial(device, serial);
  396. // Prefer the USB device over the Bluetooth device
  397. if (device->is_bluetooth) {
  398. if (HIDAPI_HasConnectedUSBDevice(device->serial)) {
  399. return true;
  400. }
  401. } else {
  402. HIDAPI_DisconnectBluetoothDevice(device->serial);
  403. }
  404. if ((ctx->is_dongle || ctx->is_nacon_dongle) && serial[0] == '\0') {
  405. // Not yet connected
  406. return true;
  407. }
  408. return HIDAPI_JoystickConnected(device, NULL);
  409. }
  410. static int HIDAPI_DriverPS4_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id)
  411. {
  412. return -1;
  413. }
  414. static bool HIDAPI_DriverPS4_LoadOfficialCalibrationData(SDL_HIDAPI_Device *device)
  415. {
  416. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  417. int i, tries, size;
  418. bool have_data = false;
  419. Uint8 data[USB_PACKET_LENGTH];
  420. if (!ctx->official_controller) {
  421. #ifdef DEBUG_PS4_CALIBRATION
  422. SDL_Log("Not an official controller, ignoring calibration\n");
  423. #endif
  424. return false;
  425. }
  426. for (tries = 0; tries < 5; ++tries) {
  427. // For Bluetooth controllers, this report switches them into advanced report mode
  428. size = ReadFeatureReport(device->dev, k_ePS4FeatureReportIdGyroCalibration_USB, data, sizeof(data));
  429. if (size < 35) {
  430. #ifdef DEBUG_PS4_CALIBRATION
  431. SDL_Log("Short read of calibration data: %d, ignoring calibration\n", size);
  432. #endif
  433. return false;
  434. }
  435. if (device->is_bluetooth) {
  436. size = ReadFeatureReport(device->dev, k_ePS4FeatureReportIdGyroCalibration_BT, data, sizeof(data));
  437. if (size < 35) {
  438. #ifdef DEBUG_PS4_CALIBRATION
  439. SDL_Log("Short read of calibration data: %d, ignoring calibration\n", size);
  440. #endif
  441. return false;
  442. }
  443. }
  444. // In some cases this report returns all zeros. Usually immediately after connection with the PS4 Dongle
  445. for (i = 0; i < size; ++i) {
  446. if (data[i]) {
  447. have_data = true;
  448. break;
  449. }
  450. }
  451. if (have_data) {
  452. break;
  453. }
  454. SDL_Delay(2);
  455. }
  456. if (have_data) {
  457. Sint16 sGyroPitchBias, sGyroYawBias, sGyroRollBias;
  458. Sint16 sGyroPitchPlus, sGyroPitchMinus;
  459. Sint16 sGyroYawPlus, sGyroYawMinus;
  460. Sint16 sGyroRollPlus, sGyroRollMinus;
  461. Sint16 sGyroSpeedPlus, sGyroSpeedMinus;
  462. Sint16 sAccXPlus, sAccXMinus;
  463. Sint16 sAccYPlus, sAccYMinus;
  464. Sint16 sAccZPlus, sAccZMinus;
  465. float flNumerator;
  466. float flDenominator;
  467. Sint16 sRange2g;
  468. #ifdef DEBUG_PS4_CALIBRATION
  469. HIDAPI_DumpPacket("PS4 calibration packet: size = %d", data, size);
  470. #endif
  471. sGyroPitchBias = LOAD16(data[1], data[2]);
  472. sGyroYawBias = LOAD16(data[3], data[4]);
  473. sGyroRollBias = LOAD16(data[5], data[6]);
  474. if (device->is_bluetooth || ctx->is_dongle) {
  475. sGyroPitchPlus = LOAD16(data[7], data[8]);
  476. sGyroYawPlus = LOAD16(data[9], data[10]);
  477. sGyroRollPlus = LOAD16(data[11], data[12]);
  478. sGyroPitchMinus = LOAD16(data[13], data[14]);
  479. sGyroYawMinus = LOAD16(data[15], data[16]);
  480. sGyroRollMinus = LOAD16(data[17], data[18]);
  481. } else {
  482. sGyroPitchPlus = LOAD16(data[7], data[8]);
  483. sGyroPitchMinus = LOAD16(data[9], data[10]);
  484. sGyroYawPlus = LOAD16(data[11], data[12]);
  485. sGyroYawMinus = LOAD16(data[13], data[14]);
  486. sGyroRollPlus = LOAD16(data[15], data[16]);
  487. sGyroRollMinus = LOAD16(data[17], data[18]);
  488. }
  489. sGyroSpeedPlus = LOAD16(data[19], data[20]);
  490. sGyroSpeedMinus = LOAD16(data[21], data[22]);
  491. sAccXPlus = LOAD16(data[23], data[24]);
  492. sAccXMinus = LOAD16(data[25], data[26]);
  493. sAccYPlus = LOAD16(data[27], data[28]);
  494. sAccYMinus = LOAD16(data[29], data[30]);
  495. sAccZPlus = LOAD16(data[31], data[32]);
  496. sAccZMinus = LOAD16(data[33], data[34]);
  497. flNumerator = (float)(sGyroSpeedPlus + sGyroSpeedMinus) * ctx->gyro_denominator / ctx->gyro_numerator;
  498. flDenominator = (float)(SDL_abs(sGyroPitchPlus - sGyroPitchBias) + SDL_abs(sGyroPitchMinus - sGyroPitchBias));
  499. if (flDenominator != 0.0f) {
  500. ctx->calibration[0].bias = sGyroPitchBias;
  501. ctx->calibration[0].scale = flNumerator / flDenominator;
  502. }
  503. flDenominator = (float)(SDL_abs(sGyroYawPlus - sGyroYawBias) + SDL_abs(sGyroYawMinus - sGyroYawBias));
  504. if (flDenominator != 0.0f) {
  505. ctx->calibration[1].bias = sGyroYawBias;
  506. ctx->calibration[1].scale = flNumerator / flDenominator;
  507. }
  508. flDenominator = (float)(SDL_abs(sGyroRollPlus - sGyroRollBias) + SDL_abs(sGyroRollMinus - sGyroRollBias));
  509. if (flDenominator != 0.0f) {
  510. ctx->calibration[2].bias = sGyroRollBias;
  511. ctx->calibration[2].scale = flNumerator / flDenominator;
  512. }
  513. sRange2g = sAccXPlus - sAccXMinus;
  514. ctx->calibration[3].bias = sAccXPlus - sRange2g / 2;
  515. ctx->calibration[3].scale = (2.0f * ctx->accel_denominator / ctx->accel_numerator) / sRange2g;
  516. sRange2g = sAccYPlus - sAccYMinus;
  517. ctx->calibration[4].bias = sAccYPlus - sRange2g / 2;
  518. ctx->calibration[4].scale = (2.0f * ctx->accel_denominator / ctx->accel_numerator) / sRange2g;
  519. sRange2g = sAccZPlus - sAccZMinus;
  520. ctx->calibration[5].bias = sAccZPlus - sRange2g / 2;
  521. ctx->calibration[5].scale = (2.0f * ctx->accel_denominator / ctx->accel_numerator) / sRange2g;
  522. ctx->hardware_calibration = true;
  523. for (i = 0; i < 6; ++i) {
  524. #ifdef DEBUG_PS4_CALIBRATION
  525. SDL_Log("calibration[%d] bias = %d, sensitivity = %f\n", i, ctx->calibration[i].bias, ctx->calibration[i].scale);
  526. #endif
  527. // Some controllers have a bad calibration
  528. if (SDL_abs(ctx->calibration[i].bias) > 1024 || SDL_fabsf(1.0f - ctx->calibration[i].scale) > 0.5f) {
  529. #ifdef DEBUG_PS4_CALIBRATION
  530. SDL_Log("invalid calibration, ignoring\n");
  531. #endif
  532. ctx->hardware_calibration = false;
  533. }
  534. }
  535. } else {
  536. #ifdef DEBUG_PS4_CALIBRATION
  537. SDL_Log("Calibration data not available\n");
  538. #endif
  539. }
  540. return ctx->hardware_calibration;
  541. }
  542. static void HIDAPI_DriverPS4_LoadCalibrationData(SDL_HIDAPI_Device *device)
  543. {
  544. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  545. int i;
  546. if (!HIDAPI_DriverPS4_LoadOfficialCalibrationData(device)) {
  547. for (i = 0; i < SDL_arraysize(ctx->calibration); ++i) {
  548. ctx->calibration[i].bias = 0;
  549. ctx->calibration[i].scale = 1.0f;
  550. }
  551. }
  552. // Scale the raw data to the units expected by SDL
  553. for (i = 0; i < SDL_arraysize(ctx->calibration); ++i) {
  554. double scale = ctx->calibration[i].scale;
  555. if (i < 3) {
  556. scale *= ((double)ctx->gyro_numerator / ctx->gyro_denominator) * SDL_PI_D / 180.0;
  557. if (device->vendor_id == USB_VENDOR_SONY &&
  558. device->product_id == USB_PRODUCT_SONY_DS4_STRIKEPAD) {
  559. // The Armor-X Pro seems to only deliver half the rotation it should
  560. scale *= 2.0;
  561. }
  562. } else {
  563. scale *= ((double)ctx->accel_numerator / ctx->accel_denominator) * SDL_STANDARD_GRAVITY;
  564. if (device->vendor_id == USB_VENDOR_SONY &&
  565. device->product_id == USB_PRODUCT_SONY_DS4_STRIKEPAD) {
  566. /* The Armor-X Pro seems to only deliver half the acceleration it should,
  567. * and in the opposite direction on all axes */
  568. scale *= -2.0;
  569. }
  570. }
  571. ctx->calibration[i].scale = (float)scale;
  572. }
  573. }
  574. static float HIDAPI_DriverPS4_ApplyCalibrationData(SDL_DriverPS4_Context *ctx, int index, Sint16 value)
  575. {
  576. IMUCalibrationData *calibration = &ctx->calibration[index];
  577. return ((float)value - calibration->bias) * calibration->scale;
  578. }
  579. static bool HIDAPI_DriverPS4_UpdateEffects(SDL_DriverPS4_Context *ctx, bool application_usage)
  580. {
  581. DS4EffectsState_t effects;
  582. SDL_zero(effects);
  583. if (ctx->vibration_supported) {
  584. effects.ucRumbleLeft = ctx->rumble_left;
  585. effects.ucRumbleRight = ctx->rumble_right;
  586. }
  587. if (ctx->lightbar_supported) {
  588. // Populate the LED state with the appropriate color from our lookup table
  589. if (ctx->color_set) {
  590. effects.ucLedRed = ctx->led_red;
  591. effects.ucLedGreen = ctx->led_green;
  592. effects.ucLedBlue = ctx->led_blue;
  593. } else {
  594. SetLedsForPlayerIndex(&effects, ctx->player_index);
  595. }
  596. }
  597. return HIDAPI_DriverPS4_InternalSendJoystickEffect(ctx, &effects, sizeof(effects), application_usage);
  598. }
  599. static void HIDAPI_DriverPS4_TickleBluetooth(SDL_HIDAPI_Device *device)
  600. {
  601. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  602. if (ctx->enhanced_reports) {
  603. // This is just a dummy packet that should have no effect, since we don't set the CRC
  604. Uint8 data[78];
  605. SDL_zeroa(data);
  606. data[0] = k_EPS4ReportIdBluetoothEffects;
  607. data[1] = 0xC0; // Magic value HID + CRC
  608. if (SDL_HIDAPI_LockRumble()) {
  609. SDL_HIDAPI_SendRumbleAndUnlock(device, data, sizeof(data));
  610. }
  611. } else {
  612. #if 0 /* The 8BitDo Zero 2 has perfect emulation of a PS4 controllers, except it
  613. * only sends reports when the state changes, so we can't disconnect here.
  614. */
  615. // We can't even send an invalid effects packet, or it will put the controller in enhanced mode
  616. if (device->num_joysticks > 0) {
  617. HIDAPI_JoystickDisconnected(device, device->joysticks[0]);
  618. }
  619. #endif
  620. }
  621. }
  622. static void HIDAPI_DriverPS4_SetEnhancedModeAvailable(SDL_DriverPS4_Context *ctx)
  623. {
  624. ctx->enhanced_mode_available = true;
  625. if (ctx->touchpad_supported) {
  626. SDL_PrivateJoystickAddTouchpad(ctx->joystick, 2);
  627. ctx->report_touchpad = true;
  628. }
  629. if (ctx->sensors_supported) {
  630. SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_GYRO, (float)(1000 / ctx->report_interval));
  631. SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_ACCEL, (float)(1000 / ctx->report_interval));
  632. }
  633. if (ctx->official_controller) {
  634. ctx->report_battery = true;
  635. }
  636. HIDAPI_UpdateDeviceProperties(ctx->device);
  637. }
  638. static void HIDAPI_DriverPS4_SetEnhancedMode(SDL_DriverPS4_Context *ctx)
  639. {
  640. if (!ctx->enhanced_mode_available) {
  641. HIDAPI_DriverPS4_SetEnhancedModeAvailable(ctx);
  642. }
  643. if (!ctx->enhanced_mode) {
  644. ctx->enhanced_mode = true;
  645. // Switch into enhanced report mode
  646. HIDAPI_DriverPS4_UpdateEffects(ctx, false);
  647. }
  648. }
  649. static void HIDAPI_DriverPS4_SetRumbleHintMode(SDL_DriverPS4_Context *ctx, SDL_PS4_RumbleHintMode rumble_hint)
  650. {
  651. switch (rumble_hint) {
  652. case PS4_RUMBLE_HINT_DEFAULT:
  653. if (ctx->enhanced_reports) {
  654. HIDAPI_DriverPS4_SetEnhancedMode(ctx);
  655. }
  656. break;
  657. case PS4_RUMBLE_HINT_OFF:
  658. // Nothing to do, enhanced mode is a one-way ticket
  659. break;
  660. case PS4_RUMBLE_HINT_ON:
  661. HIDAPI_DriverPS4_SetEnhancedMode(ctx);
  662. break;
  663. case PS4_RUMBLE_HINT_AUTO:
  664. HIDAPI_DriverPS4_SetEnhancedModeAvailable(ctx);
  665. break;
  666. }
  667. ctx->rumble_hint = rumble_hint;
  668. }
  669. static void HIDAPI_DriverPS4_UpdateEnhancedModeOnEnhancedReport(SDL_DriverPS4_Context *ctx)
  670. {
  671. ctx->enhanced_reports = true;
  672. if (ctx->rumble_hint == PS4_RUMBLE_HINT_DEFAULT) {
  673. HIDAPI_DriverPS4_SetRumbleHintMode(ctx, PS4_RUMBLE_HINT_ON);
  674. }
  675. }
  676. static void HIDAPI_DriverPS4_UpdateEnhancedModeOnApplicationUsage(SDL_DriverPS4_Context *ctx)
  677. {
  678. if (ctx->rumble_hint == PS4_RUMBLE_HINT_AUTO) {
  679. HIDAPI_DriverPS4_SetRumbleHintMode(ctx, PS4_RUMBLE_HINT_ON);
  680. }
  681. }
  682. static void SDLCALL SDL_PS4RumbleHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
  683. {
  684. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)userdata;
  685. if (!hint) {
  686. HIDAPI_DriverPS4_SetRumbleHintMode(ctx, PS4_RUMBLE_HINT_DEFAULT);
  687. } else if (SDL_strcasecmp(hint, "auto") == 0) {
  688. HIDAPI_DriverPS4_SetRumbleHintMode(ctx, PS4_RUMBLE_HINT_AUTO);
  689. } else if (SDL_GetStringBoolean(hint, false)) {
  690. HIDAPI_DriverPS4_SetRumbleHintMode(ctx, PS4_RUMBLE_HINT_ON);
  691. } else {
  692. HIDAPI_DriverPS4_SetRumbleHintMode(ctx, PS4_RUMBLE_HINT_OFF);
  693. }
  694. }
  695. static void SDLCALL SDL_PS4ReportIntervalHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
  696. {
  697. const int DEFAULT_REPORT_INTERVAL = 4;
  698. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)userdata;
  699. int new_report_interval = DEFAULT_REPORT_INTERVAL;
  700. if (hint) {
  701. int report_interval = SDL_atoi(hint);
  702. switch (report_interval) {
  703. case 1:
  704. case 2:
  705. case 4:
  706. // Valid values
  707. new_report_interval = report_interval;
  708. break;
  709. default:
  710. break;
  711. }
  712. }
  713. if (new_report_interval != ctx->report_interval) {
  714. ctx->report_interval = (Uint8)new_report_interval;
  715. HIDAPI_DriverPS4_UpdateEffects(ctx, false);
  716. SDL_LockJoysticks();
  717. SDL_PrivateJoystickSensorRate(ctx->joystick, SDL_SENSOR_GYRO, (float)(1000 / ctx->report_interval));
  718. SDL_PrivateJoystickSensorRate(ctx->joystick, SDL_SENSOR_ACCEL, (float)(1000 / ctx->report_interval));
  719. SDL_UnlockJoysticks();
  720. }
  721. }
  722. static void HIDAPI_DriverPS4_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index)
  723. {
  724. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  725. if (!ctx->joystick) {
  726. return;
  727. }
  728. ctx->player_index = player_index;
  729. // This will set the new LED state based on the new player index
  730. // SDL automatically calls this, so it doesn't count as an application action to enable enhanced mode
  731. HIDAPI_DriverPS4_UpdateEffects(ctx, false);
  732. }
  733. static bool HIDAPI_DriverPS4_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  734. {
  735. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  736. SDL_AssertJoysticksLocked();
  737. ctx->joystick = joystick;
  738. ctx->last_packet = SDL_GetTicks();
  739. ctx->report_sensors = false;
  740. ctx->report_touchpad = false;
  741. ctx->rumble_left = 0;
  742. ctx->rumble_right = 0;
  743. ctx->color_set = false;
  744. SDL_zero(ctx->last_state);
  745. // Initialize player index (needed for setting LEDs)
  746. ctx->player_index = SDL_GetJoystickPlayerIndex(joystick);
  747. // Initialize the joystick capabilities
  748. joystick->nbuttons = 11;
  749. if (ctx->touchpad_supported) {
  750. joystick->nbuttons += 1;
  751. }
  752. joystick->naxes = SDL_GAMEPAD_AXIS_MAX;
  753. joystick->nhats = 1;
  754. SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS4_REPORT_INTERVAL,
  755. SDL_PS4ReportIntervalHintChanged, ctx);
  756. SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE,
  757. SDL_PS4RumbleHintChanged, ctx);
  758. return true;
  759. }
  760. static bool HIDAPI_DriverPS4_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble)
  761. {
  762. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  763. if (!ctx->vibration_supported) {
  764. return SDL_Unsupported();
  765. }
  766. ctx->rumble_left = (low_frequency_rumble >> 8);
  767. ctx->rumble_right = (high_frequency_rumble >> 8);
  768. return HIDAPI_DriverPS4_UpdateEffects(ctx, true);
  769. }
  770. static bool HIDAPI_DriverPS4_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble)
  771. {
  772. return SDL_Unsupported();
  773. }
  774. static Uint32 HIDAPI_DriverPS4_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  775. {
  776. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  777. Uint32 result = 0;
  778. if (ctx->enhanced_mode_available) {
  779. if (ctx->lightbar_supported) {
  780. result |= SDL_JOYSTICK_CAP_RGB_LED;
  781. }
  782. if (ctx->vibration_supported) {
  783. result |= SDL_JOYSTICK_CAP_RUMBLE;
  784. }
  785. }
  786. return result;
  787. }
  788. static bool HIDAPI_DriverPS4_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue)
  789. {
  790. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  791. if (!ctx->lightbar_supported) {
  792. return SDL_Unsupported();
  793. }
  794. ctx->color_set = true;
  795. ctx->led_red = red;
  796. ctx->led_green = green;
  797. ctx->led_blue = blue;
  798. return HIDAPI_DriverPS4_UpdateEffects(ctx, true);
  799. }
  800. static bool HIDAPI_DriverPS4_InternalSendJoystickEffect(SDL_DriverPS4_Context *ctx, const void *effect, int size, bool application_usage)
  801. {
  802. Uint8 data[78];
  803. int report_size, offset;
  804. if (!ctx->effects_supported) {
  805. // We shouldn't be sending packets to this controller
  806. return SDL_Unsupported();
  807. }
  808. if (!ctx->enhanced_mode) {
  809. if (application_usage) {
  810. HIDAPI_DriverPS4_UpdateEnhancedModeOnApplicationUsage(ctx);
  811. }
  812. if (!ctx->enhanced_mode) {
  813. // We're not in enhanced mode, effects aren't allowed
  814. return SDL_Unsupported();
  815. }
  816. }
  817. SDL_zeroa(data);
  818. if (ctx->device->is_bluetooth && ctx->official_controller) {
  819. data[0] = k_EPS4ReportIdBluetoothEffects;
  820. data[1] = 0xC0 | ctx->report_interval; // Magic value HID + CRC, also sets update interval
  821. data[3] = 0x03; // 0x1 is rumble, 0x2 is lightbar, 0x4 is the blink interval
  822. report_size = 78;
  823. offset = 6;
  824. } else {
  825. data[0] = k_EPS4ReportIdUsbEffects;
  826. data[1] = 0x07; // Magic value
  827. report_size = 32;
  828. offset = 4;
  829. }
  830. SDL_memcpy(&data[offset], effect, SDL_min((sizeof(data) - offset), (size_t)size));
  831. if (ctx->device->is_bluetooth) {
  832. // Bluetooth reports need a CRC at the end of the packet (at least on Linux)
  833. Uint8 ubHdr = 0xA2; // hidp header is part of the CRC calculation
  834. Uint32 unCRC;
  835. unCRC = SDL_crc32(0, &ubHdr, 1);
  836. unCRC = SDL_crc32(unCRC, data, (size_t)(report_size - sizeof(unCRC)));
  837. SDL_memcpy(&data[report_size - sizeof(unCRC)], &unCRC, sizeof(unCRC));
  838. }
  839. if (SDL_HIDAPI_SendRumble(ctx->device, data, report_size) != report_size) {
  840. return SDL_SetError("Couldn't send rumble packet");
  841. }
  842. return true;
  843. }
  844. static bool HIDAPI_DriverPS4_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *effect, int size)
  845. {
  846. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  847. return HIDAPI_DriverPS4_InternalSendJoystickEffect(ctx, effect, size, true);
  848. }
  849. static bool HIDAPI_DriverPS4_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled)
  850. {
  851. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  852. HIDAPI_DriverPS4_UpdateEnhancedModeOnApplicationUsage(ctx);
  853. if (!ctx->sensors_supported || (enabled && !ctx->enhanced_mode)) {
  854. return SDL_Unsupported();
  855. }
  856. if (enabled) {
  857. HIDAPI_DriverPS4_LoadCalibrationData(device);
  858. }
  859. ctx->report_sensors = enabled;
  860. return true;
  861. }
  862. static void HIDAPI_DriverPS4_HandleStatePacket(SDL_Joystick *joystick, SDL_hid_device *dev, SDL_DriverPS4_Context *ctx, PS4StatePacket_t *packet, int size)
  863. {
  864. static const float TOUCHPAD_SCALEX = 1.0f / 1920;
  865. static const float TOUCHPAD_SCALEY = 1.0f / 920; // This is noted as being 944 resolution, but 920 feels better
  866. Sint16 axis;
  867. bool touchpad_down;
  868. int touchpad_x, touchpad_y;
  869. Uint64 timestamp = SDL_GetTicksNS();
  870. if (ctx->last_state.rgucButtonsHatAndCounter[0] != packet->rgucButtonsHatAndCounter[0]) {
  871. {
  872. Uint8 data = (packet->rgucButtonsHatAndCounter[0] >> 4);
  873. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_WEST, ((data & 0x01) != 0));
  874. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SOUTH, ((data & 0x02) != 0));
  875. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_EAST, ((data & 0x04) != 0));
  876. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_NORTH, ((data & 0x08) != 0));
  877. }
  878. {
  879. Uint8 hat;
  880. Uint8 data = (packet->rgucButtonsHatAndCounter[0] & 0x0F);
  881. switch (data) {
  882. case 0:
  883. hat = SDL_HAT_UP;
  884. break;
  885. case 1:
  886. hat = SDL_HAT_RIGHTUP;
  887. break;
  888. case 2:
  889. hat = SDL_HAT_RIGHT;
  890. break;
  891. case 3:
  892. hat = SDL_HAT_RIGHTDOWN;
  893. break;
  894. case 4:
  895. hat = SDL_HAT_DOWN;
  896. break;
  897. case 5:
  898. hat = SDL_HAT_LEFTDOWN;
  899. break;
  900. case 6:
  901. hat = SDL_HAT_LEFT;
  902. break;
  903. case 7:
  904. hat = SDL_HAT_LEFTUP;
  905. break;
  906. default:
  907. hat = SDL_HAT_CENTERED;
  908. break;
  909. }
  910. SDL_SendJoystickHat(timestamp, joystick, 0, hat);
  911. }
  912. }
  913. if (ctx->last_state.rgucButtonsHatAndCounter[1] != packet->rgucButtonsHatAndCounter[1]) {
  914. Uint8 data = packet->rgucButtonsHatAndCounter[1];
  915. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x01) != 0));
  916. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x02) != 0));
  917. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data & 0x10) != 0));
  918. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x20) != 0));
  919. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x40) != 0));
  920. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data & 0x80) != 0));
  921. }
  922. /* Some fightsticks, ex: Victrix FS Pro will only this these digital trigger bits and not the analog values so this needs to run whenever the
  923. trigger is evaluated
  924. */
  925. if (packet->rgucButtonsHatAndCounter[1] & 0x0C) {
  926. Uint8 data = packet->rgucButtonsHatAndCounter[1];
  927. packet->ucTriggerLeft = (data & 0x04) && packet->ucTriggerLeft == 0 ? 255 : packet->ucTriggerLeft;
  928. packet->ucTriggerRight = (data & 0x08) && packet->ucTriggerRight == 0 ? 255 : packet->ucTriggerRight;
  929. }
  930. if (ctx->last_state.rgucButtonsHatAndCounter[2] != packet->rgucButtonsHatAndCounter[2]) {
  931. Uint8 data = (packet->rgucButtonsHatAndCounter[2] & 0x03);
  932. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x01) != 0));
  933. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_PS4_TOUCHPAD, ((data & 0x02) != 0));
  934. }
  935. axis = ((int)packet->ucTriggerLeft * 257) - 32768;
  936. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis);
  937. axis = ((int)packet->ucTriggerRight * 257) - 32768;
  938. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis);
  939. axis = ((int)packet->ucLeftJoystickX * 257) - 32768;
  940. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis);
  941. axis = ((int)packet->ucLeftJoystickY * 257) - 32768;
  942. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis);
  943. axis = ((int)packet->ucRightJoystickX * 257) - 32768;
  944. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis);
  945. axis = ((int)packet->ucRightJoystickY * 257) - 32768;
  946. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis);
  947. if (size > 9 && ctx->report_battery && ctx->enhanced_reports) {
  948. SDL_PowerState state;
  949. int percent;
  950. Uint8 level = (packet->ucBatteryLevel & 0x0F);
  951. if (packet->ucBatteryLevel & 0x10) {
  952. if (level <= 10) {
  953. state = SDL_POWERSTATE_CHARGING;
  954. percent = SDL_min(level * 10 + 5, 100);
  955. } else if (level == 11) {
  956. state = SDL_POWERSTATE_CHARGED;
  957. percent = 100;
  958. } else {
  959. state = SDL_POWERSTATE_UNKNOWN;
  960. percent = 0;
  961. }
  962. } else {
  963. state = SDL_POWERSTATE_ON_BATTERY;
  964. percent = SDL_min(level * 10 + 5, 100);
  965. }
  966. SDL_SendJoystickPowerInfo(joystick, state, percent);
  967. }
  968. if (size > 9 && ctx->report_touchpad && ctx->enhanced_reports) {
  969. touchpad_down = ((packet->ucTouchpadCounter1 & 0x80) == 0);
  970. touchpad_x = packet->rgucTouchpadData1[0] | (((int)packet->rgucTouchpadData1[1] & 0x0F) << 8);
  971. touchpad_y = (packet->rgucTouchpadData1[1] >> 4) | ((int)packet->rgucTouchpadData1[2] << 4);
  972. SDL_SendJoystickTouchpad(timestamp, joystick, 0, 0, touchpad_down, touchpad_x * TOUCHPAD_SCALEX, touchpad_y * TOUCHPAD_SCALEY, touchpad_down ? 1.0f : 0.0f);
  973. touchpad_down = ((packet->ucTouchpadCounter2 & 0x80) == 0);
  974. touchpad_x = packet->rgucTouchpadData2[0] | (((int)packet->rgucTouchpadData2[1] & 0x0F) << 8);
  975. touchpad_y = (packet->rgucTouchpadData2[1] >> 4) | ((int)packet->rgucTouchpadData2[2] << 4);
  976. SDL_SendJoystickTouchpad(timestamp, joystick, 0, 1, touchpad_down, touchpad_x * TOUCHPAD_SCALEX, touchpad_y * TOUCHPAD_SCALEY, touchpad_down ? 1.0f : 0.0f);
  977. }
  978. if (size > 9 && ctx->report_sensors) {
  979. Uint16 tick;
  980. Uint16 delta;
  981. Uint64 sensor_timestamp;
  982. float data[3];
  983. tick = LOAD16(packet->rgucTimestamp[0], packet->rgucTimestamp[1]);
  984. if (ctx->last_tick < tick) {
  985. delta = (tick - ctx->last_tick);
  986. } else {
  987. delta = (SDL_MAX_UINT16 - ctx->last_tick + tick + 1);
  988. }
  989. ctx->sensor_ticks += delta;
  990. ctx->last_tick = tick;
  991. // Sensor timestamp is in 5.33us units
  992. sensor_timestamp = (ctx->sensor_ticks * SDL_NS_PER_US * 16) / 3;
  993. data[0] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 0, LOAD16(packet->rgucGyroX[0], packet->rgucGyroX[1]));
  994. data[1] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 1, LOAD16(packet->rgucGyroY[0], packet->rgucGyroY[1]));
  995. data[2] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 2, LOAD16(packet->rgucGyroZ[0], packet->rgucGyroZ[1]));
  996. SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_GYRO, sensor_timestamp, data, 3);
  997. data[0] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 3, LOAD16(packet->rgucAccelX[0], packet->rgucAccelX[1]));
  998. data[1] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 4, LOAD16(packet->rgucAccelY[0], packet->rgucAccelY[1]));
  999. data[2] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 5, LOAD16(packet->rgucAccelZ[0], packet->rgucAccelZ[1]));
  1000. SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_ACCEL, sensor_timestamp, data, 3);
  1001. }
  1002. SDL_memcpy(&ctx->last_state, packet, sizeof(ctx->last_state));
  1003. }
  1004. static bool VerifyCRC(Uint8 *data, int size)
  1005. {
  1006. Uint8 ubHdr = 0xA1; // hidp header is part of the CRC calculation
  1007. Uint32 unCRC, unPacketCRC;
  1008. Uint8 *packetCRC = data + size - sizeof(unPacketCRC);
  1009. unCRC = SDL_crc32(0, &ubHdr, 1);
  1010. unCRC = SDL_crc32(unCRC, data, (size_t)(size - sizeof(unCRC)));
  1011. unPacketCRC = LOAD32(packetCRC[0],
  1012. packetCRC[1],
  1013. packetCRC[2],
  1014. packetCRC[3]);
  1015. return (unCRC == unPacketCRC);
  1016. }
  1017. static bool HIDAPI_DriverPS4_IsPacketValid(SDL_DriverPS4_Context *ctx, Uint8 *data, int size)
  1018. {
  1019. switch (data[0]) {
  1020. case k_EPS4ReportIdUsbState:
  1021. if (size == 10) {
  1022. // This is non-enhanced mode, this packet is fine
  1023. return true;
  1024. }
  1025. if (ctx->is_nacon_dongle && size >= (1 + sizeof(PS4StatePacket_t))) {
  1026. // The report timestamp doesn't change when the controller isn't connected
  1027. PS4StatePacket_t *packet = (PS4StatePacket_t *)&data[1];
  1028. if (SDL_memcmp(packet->rgucTimestamp, ctx->last_state.rgucTimestamp, sizeof(packet->rgucTimestamp)) == 0) {
  1029. return false;
  1030. }
  1031. if (ctx->last_state.rgucAccelX[0] == 0 && ctx->last_state.rgucAccelX[1] == 0 &&
  1032. ctx->last_state.rgucAccelY[0] == 0 && ctx->last_state.rgucAccelY[1] == 0 &&
  1033. ctx->last_state.rgucAccelZ[0] == 0 && ctx->last_state.rgucAccelZ[1] == 0) {
  1034. // We don't have any state to compare yet, go ahead and copy it
  1035. SDL_memcpy(&ctx->last_state, &data[1], sizeof(PS4StatePacket_t));
  1036. return false;
  1037. }
  1038. }
  1039. /* In the case of a DS4 USB dongle, bit[2] of byte 31 indicates if a DS4 is actually connected (indicated by '0').
  1040. * For non-dongle, this bit is always 0 (connected).
  1041. * This is usually the ID over USB, but the DS4v2 that started shipping with the PS4 Slim will also send this
  1042. * packet over BT with a size of 128
  1043. */
  1044. if (size >= 64 && !(data[31] & 0x04)) {
  1045. return true;
  1046. }
  1047. break;
  1048. case k_EPS4ReportIdBluetoothState1:
  1049. case k_EPS4ReportIdBluetoothState2:
  1050. case k_EPS4ReportIdBluetoothState3:
  1051. case k_EPS4ReportIdBluetoothState4:
  1052. case k_EPS4ReportIdBluetoothState5:
  1053. case k_EPS4ReportIdBluetoothState6:
  1054. case k_EPS4ReportIdBluetoothState7:
  1055. case k_EPS4ReportIdBluetoothState8:
  1056. case k_EPS4ReportIdBluetoothState9:
  1057. // Bluetooth state packets have two additional bytes at the beginning, the first notes if HID data is present
  1058. if (size >= 78 && (data[1] & 0x80)) {
  1059. if (VerifyCRC(data, 78)) {
  1060. ++ctx->valid_crc_packets;
  1061. } else {
  1062. if (ctx->valid_crc_packets > 0) {
  1063. --ctx->valid_crc_packets;
  1064. }
  1065. if (ctx->valid_crc_packets >= 3) {
  1066. // We're generally getting valid CRC, but failed one
  1067. return false;
  1068. }
  1069. }
  1070. return true;
  1071. }
  1072. break;
  1073. default:
  1074. break;
  1075. }
  1076. return false;
  1077. }
  1078. static bool HIDAPI_DriverPS4_UpdateDevice(SDL_HIDAPI_Device *device)
  1079. {
  1080. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  1081. SDL_Joystick *joystick = NULL;
  1082. Uint8 data[USB_PACKET_LENGTH * 2];
  1083. int size;
  1084. int packet_count = 0;
  1085. Uint64 now = SDL_GetTicks();
  1086. if (device->num_joysticks > 0) {
  1087. joystick = SDL_GetJoystickFromID(device->joysticks[0]);
  1088. }
  1089. while ((size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) {
  1090. #ifdef DEBUG_PS4_PROTOCOL
  1091. HIDAPI_DumpPacket("PS4 packet: size = %d", data, size);
  1092. #endif
  1093. if (!HIDAPI_DriverPS4_IsPacketValid(ctx, data, size)) {
  1094. continue;
  1095. }
  1096. ++packet_count;
  1097. ctx->last_packet = now;
  1098. if (!joystick) {
  1099. continue;
  1100. }
  1101. switch (data[0]) {
  1102. case k_EPS4ReportIdUsbState:
  1103. HIDAPI_DriverPS4_HandleStatePacket(joystick, device->dev, ctx, (PS4StatePacket_t *)&data[1], size - 1);
  1104. break;
  1105. case k_EPS4ReportIdBluetoothState1:
  1106. case k_EPS4ReportIdBluetoothState2:
  1107. case k_EPS4ReportIdBluetoothState3:
  1108. case k_EPS4ReportIdBluetoothState4:
  1109. case k_EPS4ReportIdBluetoothState5:
  1110. case k_EPS4ReportIdBluetoothState6:
  1111. case k_EPS4ReportIdBluetoothState7:
  1112. case k_EPS4ReportIdBluetoothState8:
  1113. case k_EPS4ReportIdBluetoothState9:
  1114. // This is the extended report, we can enable effects now in default mode
  1115. HIDAPI_DriverPS4_UpdateEnhancedModeOnEnhancedReport(ctx);
  1116. // Bluetooth state packets have two additional bytes at the beginning, the first notes if HID is present
  1117. HIDAPI_DriverPS4_HandleStatePacket(joystick, device->dev, ctx, (PS4StatePacket_t *)&data[3], size - 3);
  1118. break;
  1119. default:
  1120. #ifdef DEBUG_JOYSTICK
  1121. SDL_Log("Unknown PS4 packet: 0x%.2x\n", data[0]);
  1122. #endif
  1123. break;
  1124. }
  1125. }
  1126. if (device->is_bluetooth) {
  1127. if (packet_count == 0) {
  1128. // Check to see if it looks like the device disconnected
  1129. if (now >= (ctx->last_packet + BLUETOOTH_DISCONNECT_TIMEOUT_MS)) {
  1130. // Send an empty output report to tickle the Bluetooth stack
  1131. HIDAPI_DriverPS4_TickleBluetooth(device);
  1132. }
  1133. } else {
  1134. // Reconnect the Bluetooth device once the USB device is gone
  1135. if (device->num_joysticks == 0 &&
  1136. !HIDAPI_HasConnectedUSBDevice(device->serial)) {
  1137. HIDAPI_JoystickConnected(device, NULL);
  1138. }
  1139. }
  1140. }
  1141. if (ctx->is_dongle || ctx->is_nacon_dongle) {
  1142. if (packet_count == 0) {
  1143. if (device->num_joysticks > 0) {
  1144. // Check to see if it looks like the device disconnected
  1145. if (now >= (ctx->last_packet + BLUETOOTH_DISCONNECT_TIMEOUT_MS)) {
  1146. HIDAPI_JoystickDisconnected(device, device->joysticks[0]);
  1147. }
  1148. }
  1149. } else {
  1150. if (device->num_joysticks == 0) {
  1151. char serial[18];
  1152. size = ReadFeatureReport(device->dev, k_ePS4FeatureReportIdSerialNumber, data, sizeof(data));
  1153. if (size >= 7 && (data[1] || data[2] || data[3] || data[4] || data[5] || data[6])) {
  1154. (void)SDL_snprintf(serial, sizeof(serial), "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x",
  1155. data[6], data[5], data[4], data[3], data[2], data[1]);
  1156. HIDAPI_SetDeviceSerial(device, serial);
  1157. }
  1158. HIDAPI_JoystickConnected(device, NULL);
  1159. }
  1160. }
  1161. }
  1162. if (packet_count == 0 && size < 0 && device->num_joysticks > 0) {
  1163. // Read error, device is disconnected
  1164. HIDAPI_JoystickDisconnected(device, device->joysticks[0]);
  1165. }
  1166. return (size >= 0);
  1167. }
  1168. static void HIDAPI_DriverPS4_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  1169. {
  1170. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  1171. SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS4_REPORT_INTERVAL,
  1172. SDL_PS4ReportIntervalHintChanged, ctx);
  1173. SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE,
  1174. SDL_PS4RumbleHintChanged, ctx);
  1175. ctx->joystick = NULL;
  1176. }
  1177. static void HIDAPI_DriverPS4_FreeDevice(SDL_HIDAPI_Device *device)
  1178. {
  1179. }
  1180. SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverPS4 = {
  1181. SDL_HINT_JOYSTICK_HIDAPI_PS4,
  1182. true,
  1183. HIDAPI_DriverPS4_RegisterHints,
  1184. HIDAPI_DriverPS4_UnregisterHints,
  1185. HIDAPI_DriverPS4_IsEnabled,
  1186. HIDAPI_DriverPS4_IsSupportedDevice,
  1187. HIDAPI_DriverPS4_InitDevice,
  1188. HIDAPI_DriverPS4_GetDevicePlayerIndex,
  1189. HIDAPI_DriverPS4_SetDevicePlayerIndex,
  1190. HIDAPI_DriverPS4_UpdateDevice,
  1191. HIDAPI_DriverPS4_OpenJoystick,
  1192. HIDAPI_DriverPS4_RumbleJoystick,
  1193. HIDAPI_DriverPS4_RumbleJoystickTriggers,
  1194. HIDAPI_DriverPS4_GetJoystickCapabilities,
  1195. HIDAPI_DriverPS4_SetJoystickLED,
  1196. HIDAPI_DriverPS4_SendJoystickEffect,
  1197. HIDAPI_DriverPS4_SetJoystickSensorsEnabled,
  1198. HIDAPI_DriverPS4_CloseJoystick,
  1199. HIDAPI_DriverPS4_FreeDevice,
  1200. };
  1201. #endif // SDL_JOYSTICK_HIDAPI_PS4
  1202. #endif // SDL_JOYSTICK_HIDAPI