SDL_hidapi_ps4.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2021 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.h"
  24. #include "SDL_events.h"
  25. #include "SDL_timer.h"
  26. #include "SDL_joystick.h"
  27. #include "SDL_gamecontroller.h"
  28. #include "../../SDL_hints_c.h"
  29. #include "../SDL_sysjoystick.h"
  30. #include "SDL_hidapijoystick_c.h"
  31. #include "SDL_hidapi_rumble.h"
  32. #ifdef SDL_JOYSTICK_HIDAPI_PS4
  33. /* Define this if you want to log all packets from the controller */
  34. /*#define DEBUG_PS4_PROTOCOL*/
  35. /* Define this if you want to log calibration data */
  36. /*#define DEBUG_PS4_CALIBRATION*/
  37. #define GYRO_RES_PER_DEGREE 1024.0f
  38. #define ACCEL_RES_PER_G 8192.0f
  39. #define BLUETOOTH_DISCONNECT_TIMEOUT_MS 500
  40. #define LOAD16(A, B) (Sint16)((Uint16)(A) | (((Uint16)(B)) << 8))
  41. typedef enum
  42. {
  43. k_EPS4ReportIdUsbState = 1,
  44. k_EPS4ReportIdUsbEffects = 5,
  45. k_EPS4ReportIdBluetoothState1 = 17,
  46. k_EPS4ReportIdBluetoothState2 = 18,
  47. k_EPS4ReportIdBluetoothState3 = 19,
  48. k_EPS4ReportIdBluetoothState4 = 20,
  49. k_EPS4ReportIdBluetoothState5 = 21,
  50. k_EPS4ReportIdBluetoothState6 = 22,
  51. k_EPS4ReportIdBluetoothState7 = 23,
  52. k_EPS4ReportIdBluetoothState8 = 24,
  53. k_EPS4ReportIdBluetoothState9 = 25,
  54. k_EPS4ReportIdBluetoothEffects = 17,
  55. k_EPS4ReportIdDisconnectMessage = 226,
  56. } EPS4ReportId;
  57. typedef enum
  58. {
  59. k_ePS4FeatureReportIdGyroCalibration_USB = 0x02,
  60. k_ePS4FeatureReportIdGyroCalibration_BT = 0x05,
  61. k_ePS4FeatureReportIdSerialNumber = 0x12,
  62. } EPS4FeatureReportID;
  63. typedef struct
  64. {
  65. Uint8 ucLeftJoystickX;
  66. Uint8 ucLeftJoystickY;
  67. Uint8 ucRightJoystickX;
  68. Uint8 ucRightJoystickY;
  69. Uint8 rgucButtonsHatAndCounter[ 3 ];
  70. Uint8 ucTriggerLeft;
  71. Uint8 ucTriggerRight;
  72. Uint8 _rgucPad0[ 3 ];
  73. Uint8 rgucGyroX[2];
  74. Uint8 rgucGyroY[2];
  75. Uint8 rgucGyroZ[2];
  76. Uint8 rgucAccelX[2];
  77. Uint8 rgucAccelY[2];
  78. Uint8 rgucAccelZ[2];
  79. Uint8 _rgucPad1[ 5 ];
  80. Uint8 ucBatteryLevel;
  81. Uint8 _rgucPad2[ 4 ];
  82. Uint8 ucTouchpadCounter1;
  83. Uint8 rgucTouchpadData1[ 3 ];
  84. Uint8 ucTouchpadCounter2;
  85. Uint8 rgucTouchpadData2[ 3 ];
  86. } PS4StatePacket_t;
  87. typedef struct
  88. {
  89. Uint8 ucRumbleRight;
  90. Uint8 ucRumbleLeft;
  91. Uint8 ucLedRed;
  92. Uint8 ucLedGreen;
  93. Uint8 ucLedBlue;
  94. Uint8 ucLedDelayOn;
  95. Uint8 ucLedDelayOff;
  96. Uint8 _rgucPad0[ 8 ];
  97. Uint8 ucVolumeLeft;
  98. Uint8 ucVolumeRight;
  99. Uint8 ucVolumeMic;
  100. Uint8 ucVolumeSpeaker;
  101. } DS4EffectsState_t;
  102. typedef struct {
  103. Sint16 bias;
  104. float sensitivity;
  105. } IMUCalibrationData;
  106. typedef struct {
  107. SDL_HIDAPI_Device *device;
  108. SDL_Joystick *joystick;
  109. SDL_bool is_dongle;
  110. SDL_bool is_bluetooth;
  111. SDL_bool official_controller;
  112. SDL_bool audio_supported;
  113. SDL_bool effects_supported;
  114. SDL_bool enhanced_mode;
  115. SDL_bool report_sensors;
  116. SDL_bool hardware_calibration;
  117. IMUCalibrationData calibration[6];
  118. Uint32 last_packet;
  119. int player_index;
  120. Uint8 rumble_left;
  121. Uint8 rumble_right;
  122. SDL_bool color_set;
  123. Uint8 led_red;
  124. Uint8 led_green;
  125. Uint8 led_blue;
  126. Uint8 volume;
  127. Uint32 last_volume_check;
  128. PS4StatePacket_t last_state;
  129. } SDL_DriverPS4_Context;
  130. static int HIDAPI_DriverPS4_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *effect, int size);
  131. static SDL_bool
  132. HIDAPI_DriverPS4_IsSupportedDevice(const char *name, SDL_GameControllerType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol)
  133. {
  134. return (type == SDL_CONTROLLER_TYPE_PS4) ? SDL_TRUE : SDL_FALSE;
  135. }
  136. static const char *
  137. HIDAPI_DriverPS4_GetDeviceName(Uint16 vendor_id, Uint16 product_id)
  138. {
  139. if (vendor_id == USB_VENDOR_SONY) {
  140. return "PS4 Controller";
  141. }
  142. return NULL;
  143. }
  144. static int ReadFeatureReport(SDL_hid_device *dev, Uint8 report_id, Uint8 *report, size_t length)
  145. {
  146. SDL_memset(report, 0, length);
  147. report[0] = report_id;
  148. return SDL_hid_get_feature_report(dev, report, length);
  149. }
  150. static SDL_bool HIDAPI_DriverPS4_CanRumble(Uint16 vendor_id, Uint16 product_id)
  151. {
  152. /* The Razer Panthera fight stick hangs when trying to rumble */
  153. if (vendor_id == USB_VENDOR_RAZER &&
  154. (product_id == USB_PRODUCT_RAZER_PANTHERA || product_id == USB_PRODUCT_RAZER_PANTHERA_EVO)) {
  155. return SDL_FALSE;
  156. }
  157. return SDL_TRUE;
  158. }
  159. static void
  160. SetLedsForPlayerIndex(DS4EffectsState_t *effects, int player_index)
  161. {
  162. /* This list is the same as what hid-sony.c uses in the Linux kernel.
  163. The first 4 values correspond to what the PS4 assigns.
  164. */
  165. static const Uint8 colors[7][3] = {
  166. { 0x00, 0x00, 0x40 }, /* Blue */
  167. { 0x40, 0x00, 0x00 }, /* Red */
  168. { 0x00, 0x40, 0x00 }, /* Green */
  169. { 0x20, 0x00, 0x20 }, /* Pink */
  170. { 0x02, 0x01, 0x00 }, /* Orange */
  171. { 0x00, 0x01, 0x01 }, /* Teal */
  172. { 0x01, 0x01, 0x01 } /* White */
  173. };
  174. if (player_index >= 0) {
  175. player_index %= SDL_arraysize(colors);
  176. } else {
  177. player_index = 0;
  178. }
  179. effects->ucLedRed = colors[player_index][0];
  180. effects->ucLedGreen = colors[player_index][1];
  181. effects->ucLedBlue = colors[player_index][2];
  182. }
  183. static SDL_bool
  184. HIDAPI_DriverPS4_InitDevice(SDL_HIDAPI_Device *device)
  185. {
  186. return HIDAPI_JoystickConnected(device, NULL);
  187. }
  188. static int
  189. HIDAPI_DriverPS4_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id)
  190. {
  191. return -1;
  192. }
  193. static void
  194. HIDAPI_DriverPS4_LoadCalibrationData(SDL_HIDAPI_Device *device)
  195. {
  196. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  197. int i, tries, size;
  198. SDL_bool have_data = SDL_FALSE;
  199. Uint8 data[USB_PACKET_LENGTH];
  200. if (!ctx->official_controller) {
  201. #ifdef DEBUG_PS4_CALIBRATION
  202. SDL_Log("Not an official controller, ignoring calibration\n");
  203. #endif
  204. return;
  205. }
  206. for( tries = 0; tries < 5; ++tries ) {
  207. /* For Bluetooth controllers, this report switches them into advanced report mode */
  208. size = ReadFeatureReport(device->dev, k_ePS4FeatureReportIdGyroCalibration_USB, data, sizeof(data));
  209. if (size < 35) {
  210. #ifdef DEBUG_PS4_CALIBRATION
  211. SDL_Log("Short read of calibration data: %d, ignoring calibration\n", size);
  212. #endif
  213. return;
  214. }
  215. if (ctx->is_bluetooth) {
  216. size = ReadFeatureReport(device->dev, k_ePS4FeatureReportIdGyroCalibration_BT, data, sizeof(data));
  217. if (size < 35) {
  218. #ifdef DEBUG_PS4_CALIBRATION
  219. SDL_Log("Short read of calibration data: %d, ignoring calibration\n", size);
  220. #endif
  221. return;
  222. }
  223. }
  224. /* In some cases this report returns all zeros. Usually immediately after connection with the PS4 Dongle */
  225. for (i = 0; i < size; ++i) {
  226. if (data[i]) {
  227. have_data = SDL_TRUE;
  228. break;
  229. }
  230. }
  231. if (have_data) {
  232. break;
  233. }
  234. SDL_Delay(2);
  235. }
  236. if (have_data) {
  237. Sint16 sGyroPitchBias, sGyroYawBias, sGyroRollBias;
  238. Sint16 sGyroPitchPlus, sGyroPitchMinus;
  239. Sint16 sGyroYawPlus, sGyroYawMinus;
  240. Sint16 sGyroRollPlus, sGyroRollMinus;
  241. Sint16 sGyroSpeedPlus, sGyroSpeedMinus;
  242. Sint16 sAccXPlus, sAccXMinus;
  243. Sint16 sAccYPlus, sAccYMinus;
  244. Sint16 sAccZPlus, sAccZMinus;
  245. float flNumerator;
  246. Sint16 sRange2g;
  247. #ifdef DEBUG_PS4_CALIBRATION
  248. HIDAPI_DumpPacket("PS4 calibration packet: size = %d", data, size);
  249. #endif
  250. sGyroPitchBias = LOAD16(data[1], data[2]);
  251. sGyroYawBias = LOAD16(data[3], data[4]);
  252. sGyroRollBias = LOAD16(data[5], data[6]);
  253. if (ctx->is_bluetooth || ctx->is_dongle) {
  254. sGyroPitchPlus = LOAD16(data[7], data[8]);
  255. sGyroYawPlus = LOAD16(data[9], data[10]);
  256. sGyroRollPlus = LOAD16(data[11], data[12]);
  257. sGyroPitchMinus = LOAD16(data[13], data[14]);
  258. sGyroYawMinus = LOAD16(data[15], data[16]);
  259. sGyroRollMinus = LOAD16(data[17], data[18]);
  260. } else {
  261. sGyroPitchPlus = LOAD16(data[7], data[8]);
  262. sGyroPitchMinus = LOAD16(data[9], data[10]);
  263. sGyroYawPlus = LOAD16(data[11], data[12]);
  264. sGyroYawMinus = LOAD16(data[13], data[14]);
  265. sGyroRollPlus = LOAD16(data[15], data[16]);
  266. sGyroRollMinus = LOAD16(data[17], data[18]);
  267. }
  268. sGyroSpeedPlus = LOAD16(data[19], data[20]);
  269. sGyroSpeedMinus = LOAD16(data[21], data[22]);
  270. sAccXPlus = LOAD16(data[23], data[24]);
  271. sAccXMinus = LOAD16(data[25], data[26]);
  272. sAccYPlus = LOAD16(data[27], data[28]);
  273. sAccYMinus = LOAD16(data[29], data[30]);
  274. sAccZPlus = LOAD16(data[31], data[32]);
  275. sAccZMinus = LOAD16(data[33], data[34]);
  276. flNumerator = (sGyroSpeedPlus + sGyroSpeedMinus) * GYRO_RES_PER_DEGREE;
  277. ctx->calibration[0].bias = sGyroPitchBias;
  278. ctx->calibration[0].sensitivity = flNumerator / (sGyroPitchPlus - sGyroPitchMinus);
  279. ctx->calibration[1].bias = sGyroYawBias;
  280. ctx->calibration[1].sensitivity = flNumerator / (sGyroYawPlus - sGyroYawMinus);
  281. ctx->calibration[2].bias = sGyroRollBias;
  282. ctx->calibration[2].sensitivity = flNumerator / (sGyroRollPlus - sGyroRollMinus);
  283. sRange2g = sAccXPlus - sAccXMinus;
  284. ctx->calibration[3].bias = sAccXPlus - sRange2g / 2;
  285. ctx->calibration[3].sensitivity = 2.0f * ACCEL_RES_PER_G / (float)sRange2g;
  286. sRange2g = sAccYPlus - sAccYMinus;
  287. ctx->calibration[4].bias = sAccYPlus - sRange2g / 2;
  288. ctx->calibration[4].sensitivity = 2.0f * ACCEL_RES_PER_G / (float)sRange2g;
  289. sRange2g = sAccZPlus - sAccZMinus;
  290. ctx->calibration[5].bias = sAccZPlus - sRange2g / 2;
  291. ctx->calibration[5].sensitivity = 2.0f * ACCEL_RES_PER_G / (float)sRange2g;
  292. ctx->hardware_calibration = SDL_TRUE;
  293. for (i = 0; i < 6; ++i) {
  294. float divisor = (i < 3 ? 64.0f : 1.0f);
  295. #ifdef DEBUG_PS4_CALIBRATION
  296. SDL_Log("calibration[%d] bias = %d, sensitivity = %f\n", i, ctx->calibration[i].bias, ctx->calibration[i].sensitivity);
  297. #endif
  298. /* Some controllers have a bad calibration */
  299. if ((SDL_abs(ctx->calibration[i].bias) > 1024) || (SDL_fabs(1.0f - ctx->calibration[i].sensitivity / divisor) > 0.5f)) {
  300. #ifdef DEBUG_PS4_CALIBRATION
  301. SDL_Log("invalid calibration, ignoring\n");
  302. #endif
  303. ctx->hardware_calibration = SDL_FALSE;
  304. }
  305. }
  306. } else {
  307. #ifdef DEBUG_PS4_CALIBRATION
  308. SDL_Log("Calibration data not available\n");
  309. #endif
  310. }
  311. }
  312. static float
  313. HIDAPI_DriverPS4_ApplyCalibrationData(SDL_DriverPS4_Context *ctx, int index, Sint16 value)
  314. {
  315. float result;
  316. if (ctx->hardware_calibration) {
  317. IMUCalibrationData *calibration = &ctx->calibration[index];
  318. result = (value - calibration->bias) * calibration->sensitivity;
  319. } else if (index < 3) {
  320. result = value * 64.f;
  321. } else {
  322. result = value;
  323. }
  324. /* Convert the raw data to the units expected by SDL */
  325. if (index < 3) {
  326. result = (result / GYRO_RES_PER_DEGREE) * (float)M_PI / 180.0f;
  327. } else {
  328. result = (result / ACCEL_RES_PER_G) * SDL_STANDARD_GRAVITY;
  329. }
  330. return result;
  331. }
  332. static int
  333. HIDAPI_DriverPS4_UpdateEffects(SDL_HIDAPI_Device *device)
  334. {
  335. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  336. DS4EffectsState_t effects;
  337. if (!ctx->enhanced_mode) {
  338. return SDL_Unsupported();
  339. }
  340. SDL_zero(effects);
  341. effects.ucRumbleLeft = ctx->rumble_left;
  342. effects.ucRumbleRight = ctx->rumble_right;
  343. /* Populate the LED state with the appropriate color from our lookup table */
  344. if (ctx->color_set) {
  345. effects.ucLedRed = ctx->led_red;
  346. effects.ucLedGreen = ctx->led_green;
  347. effects.ucLedBlue = ctx->led_blue;
  348. } else {
  349. SetLedsForPlayerIndex(&effects, ctx->player_index);
  350. }
  351. return HIDAPI_DriverPS4_SendJoystickEffect(device, ctx->joystick, &effects, sizeof(effects));
  352. }
  353. static void
  354. HIDAPI_DriverPS4_TickleBluetooth(SDL_HIDAPI_Device *device)
  355. {
  356. /* This is just a dummy packet that should have no effect, since we don't set the CRC */
  357. Uint8 data[78];
  358. SDL_zeroa(data);
  359. data[0] = k_EPS4ReportIdBluetoothEffects;
  360. data[1] = 0xC0; /* Magic value HID + CRC */
  361. SDL_HIDAPI_SendRumble(device, data, sizeof(data));
  362. }
  363. static void
  364. HIDAPI_DriverPS4_SetEnhancedMode(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  365. {
  366. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  367. if (!ctx->enhanced_mode) {
  368. ctx->enhanced_mode = SDL_TRUE;
  369. SDL_PrivateJoystickAddTouchpad(joystick, 2);
  370. SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_GYRO, 250.0f);
  371. SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_ACCEL, 250.0f);
  372. HIDAPI_DriverPS4_UpdateEffects(device);
  373. }
  374. }
  375. static void SDLCALL SDL_PS4RumbleHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
  376. {
  377. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)userdata;
  378. /* This is a one-way trip, you can't switch the controller back to simple report mode */
  379. if (SDL_GetStringBoolean(hint, SDL_FALSE)) {
  380. HIDAPI_DriverPS4_SetEnhancedMode(ctx->device, ctx->joystick);
  381. }
  382. }
  383. static void
  384. HIDAPI_DriverPS4_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index)
  385. {
  386. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  387. if (!ctx) {
  388. return;
  389. }
  390. ctx->player_index = player_index;
  391. /* This will set the new LED state based on the new player index */
  392. HIDAPI_DriverPS4_UpdateEffects(device);
  393. }
  394. static SDL_bool
  395. HIDAPI_DriverPS4_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  396. {
  397. SDL_DriverPS4_Context *ctx;
  398. SDL_bool enhanced_mode = SDL_FALSE;
  399. ctx = (SDL_DriverPS4_Context *)SDL_calloc(1, sizeof(*ctx));
  400. if (!ctx) {
  401. SDL_OutOfMemory();
  402. return SDL_FALSE;
  403. }
  404. ctx->device = device;
  405. ctx->joystick = joystick;
  406. ctx->last_packet = SDL_GetTicks();
  407. device->dev = SDL_hid_open_path(device->path, 0);
  408. if (!device->dev) {
  409. SDL_free(ctx);
  410. SDL_SetError("Couldn't open %s", device->path);
  411. return SDL_FALSE;
  412. }
  413. device->context = ctx;
  414. /* Check for type of connection */
  415. ctx->is_dongle = (device->vendor_id == USB_VENDOR_SONY && device->product_id == USB_PRODUCT_SONY_DS4_DONGLE);
  416. if (ctx->is_dongle) {
  417. ctx->is_bluetooth = SDL_FALSE;
  418. ctx->official_controller = SDL_TRUE;
  419. enhanced_mode = SDL_TRUE;
  420. } else if (device->vendor_id == USB_VENDOR_SONY) {
  421. Uint8 data[USB_PACKET_LENGTH];
  422. int size;
  423. /* This will fail if we're on Bluetooth */
  424. size = ReadFeatureReport(device->dev, k_ePS4FeatureReportIdSerialNumber, data, sizeof(data));
  425. if (size >= 7) {
  426. char serial[18];
  427. SDL_snprintf(serial, sizeof(serial), "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x",
  428. data[6], data[5], data[4], data[3], data[2], data[1]);
  429. joystick->serial = SDL_strdup(serial);
  430. ctx->is_bluetooth = SDL_FALSE;
  431. enhanced_mode = SDL_TRUE;
  432. } else {
  433. ctx->is_bluetooth = SDL_TRUE;
  434. /* Read a report to see if we're in enhanced mode */
  435. size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 16);
  436. #ifdef DEBUG_PS4_PROTOCOL
  437. if (size > 0) {
  438. HIDAPI_DumpPacket("PS4 first packet: size = %d", data, size);
  439. } else {
  440. SDL_Log("PS4 first packet: size = %d\n", size);
  441. }
  442. #endif
  443. if (size > 0 &&
  444. data[0] >= k_EPS4ReportIdBluetoothState1 &&
  445. data[0] <= k_EPS4ReportIdBluetoothState9) {
  446. enhanced_mode = SDL_TRUE;
  447. }
  448. }
  449. ctx->official_controller = SDL_TRUE;
  450. } else {
  451. /* Third party controllers appear to all be wired */
  452. ctx->is_bluetooth = SDL_FALSE;
  453. enhanced_mode = SDL_TRUE;
  454. }
  455. #ifdef DEBUG_PS4
  456. SDL_Log("PS4 dongle = %s, bluetooth = %s\n", ctx->is_dongle ? "TRUE" : "FALSE", ctx->is_bluetooth ? "TRUE" : "FALSE");
  457. #endif
  458. /* Check to see if audio is supported */
  459. if (device->vendor_id == USB_VENDOR_SONY &&
  460. (device->product_id == USB_PRODUCT_SONY_DS4_SLIM || device->product_id == USB_PRODUCT_SONY_DS4_DONGLE)) {
  461. ctx->audio_supported = SDL_TRUE;
  462. }
  463. if (HIDAPI_DriverPS4_CanRumble(device->vendor_id, device->product_id)) {
  464. ctx->effects_supported = SDL_TRUE;
  465. }
  466. if (!joystick->serial && device->serial && SDL_strlen(device->serial) == 12) {
  467. int i, j;
  468. char serial[18];
  469. j = -1;
  470. for (i = 0; i < 12; i += 2) {
  471. j += 1;
  472. SDL_memcpy(&serial[j], &device->serial[i], 2);
  473. j += 2;
  474. serial[j] = '-';
  475. }
  476. serial[j] = '\0';
  477. joystick->serial = SDL_strdup(serial);
  478. }
  479. /* Initialize player index (needed for setting LEDs) */
  480. ctx->player_index = SDL_JoystickGetPlayerIndex(joystick);
  481. /* Initialize the joystick capabilities
  482. *
  483. * We can't dynamically add the touchpad button, so always report it here
  484. */
  485. joystick->nbuttons = 16;
  486. joystick->naxes = SDL_CONTROLLER_AXIS_MAX;
  487. joystick->epowerlevel = ctx->is_bluetooth ? SDL_JOYSTICK_POWER_UNKNOWN : SDL_JOYSTICK_POWER_WIRED;
  488. if (enhanced_mode) {
  489. HIDAPI_DriverPS4_SetEnhancedMode(device, joystick);
  490. } else {
  491. SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE,
  492. SDL_PS4RumbleHintChanged, ctx);
  493. }
  494. return SDL_TRUE;
  495. }
  496. static int
  497. HIDAPI_DriverPS4_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble)
  498. {
  499. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  500. ctx->rumble_left = (low_frequency_rumble >> 8);
  501. ctx->rumble_right = (high_frequency_rumble >> 8);
  502. return HIDAPI_DriverPS4_UpdateEffects(device);
  503. }
  504. static int
  505. HIDAPI_DriverPS4_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble)
  506. {
  507. return SDL_Unsupported();
  508. }
  509. static Uint32
  510. HIDAPI_DriverPS4_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  511. {
  512. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  513. Uint32 result = 0;
  514. if (ctx->enhanced_mode && ctx->effects_supported) {
  515. result |= SDL_JOYCAP_LED | SDL_JOYCAP_RUMBLE;
  516. }
  517. return result;
  518. }
  519. static int
  520. HIDAPI_DriverPS4_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue)
  521. {
  522. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  523. ctx->color_set = SDL_TRUE;
  524. ctx->led_red = red;
  525. ctx->led_green = green;
  526. ctx->led_blue = blue;
  527. return HIDAPI_DriverPS4_UpdateEffects(device);
  528. }
  529. static int
  530. HIDAPI_DriverPS4_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *effect, int size)
  531. {
  532. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  533. Uint8 data[78];
  534. int report_size, offset;
  535. if (!ctx->effects_supported) {
  536. return SDL_Unsupported();
  537. }
  538. if (!ctx->enhanced_mode) {
  539. HIDAPI_DriverPS4_SetEnhancedMode(device, joystick);
  540. }
  541. SDL_zeroa(data);
  542. if (ctx->is_bluetooth) {
  543. data[0] = k_EPS4ReportIdBluetoothEffects;
  544. data[1] = 0xC0 | 0x04; /* Magic value HID + CRC, also sets interval to 4ms for samples */
  545. data[3] = 0x03; /* 0x1 is rumble, 0x2 is lightbar, 0x4 is the blink interval */
  546. report_size = 78;
  547. offset = 6;
  548. } else {
  549. data[0] = k_EPS4ReportIdUsbEffects;
  550. data[1] = 0x07; /* Magic value */
  551. report_size = 32;
  552. offset = 4;
  553. }
  554. SDL_memcpy(&data[offset], effect, SDL_min((sizeof(data) - offset), (size_t)size));
  555. if (ctx->is_bluetooth) {
  556. /* Bluetooth reports need a CRC at the end of the packet (at least on Linux) */
  557. Uint8 ubHdr = 0xA2; /* hidp header is part of the CRC calculation */
  558. Uint32 unCRC;
  559. unCRC = SDL_crc32(0, &ubHdr, 1);
  560. unCRC = SDL_crc32(unCRC, data, (size_t)(report_size - sizeof(unCRC)));
  561. SDL_memcpy(&data[report_size - sizeof(unCRC)], &unCRC, sizeof(unCRC));
  562. }
  563. if (SDL_HIDAPI_SendRumble(device, data, report_size) != report_size) {
  564. return SDL_SetError("Couldn't send rumble packet");
  565. }
  566. return 0;
  567. }
  568. static int
  569. HIDAPI_DriverPS4_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, SDL_bool enabled)
  570. {
  571. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  572. if (!ctx->enhanced_mode) {
  573. return SDL_Unsupported();
  574. }
  575. if (enabled) {
  576. HIDAPI_DriverPS4_LoadCalibrationData(device);
  577. }
  578. ctx->report_sensors = enabled;
  579. return 0;
  580. }
  581. static void
  582. HIDAPI_DriverPS4_HandleStatePacket(SDL_Joystick *joystick, SDL_hid_device *dev, SDL_DriverPS4_Context *ctx, PS4StatePacket_t *packet)
  583. {
  584. static const float TOUCHPAD_SCALEX = 1.0f / 1920;
  585. static const float TOUCHPAD_SCALEY = 1.0f / 920; /* This is noted as being 944 resolution, but 920 feels better */
  586. Sint16 axis;
  587. Uint8 touchpad_state;
  588. int touchpad_x, touchpad_y;
  589. if (ctx->last_state.rgucButtonsHatAndCounter[0] != packet->rgucButtonsHatAndCounter[0]) {
  590. {
  591. Uint8 data = (packet->rgucButtonsHatAndCounter[0] >> 4);
  592. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_X, (data & 0x01) ? SDL_PRESSED : SDL_RELEASED);
  593. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_A, (data & 0x02) ? SDL_PRESSED : SDL_RELEASED);
  594. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_B, (data & 0x04) ? SDL_PRESSED : SDL_RELEASED);
  595. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_Y, (data & 0x08) ? SDL_PRESSED : SDL_RELEASED);
  596. }
  597. {
  598. Uint8 data = (packet->rgucButtonsHatAndCounter[0] & 0x0F);
  599. SDL_bool dpad_up = SDL_FALSE;
  600. SDL_bool dpad_down = SDL_FALSE;
  601. SDL_bool dpad_left = SDL_FALSE;
  602. SDL_bool dpad_right = SDL_FALSE;
  603. switch (data) {
  604. case 0:
  605. dpad_up = SDL_TRUE;
  606. break;
  607. case 1:
  608. dpad_up = SDL_TRUE;
  609. dpad_right = SDL_TRUE;
  610. break;
  611. case 2:
  612. dpad_right = SDL_TRUE;
  613. break;
  614. case 3:
  615. dpad_right = SDL_TRUE;
  616. dpad_down = SDL_TRUE;
  617. break;
  618. case 4:
  619. dpad_down = SDL_TRUE;
  620. break;
  621. case 5:
  622. dpad_left = SDL_TRUE;
  623. dpad_down = SDL_TRUE;
  624. break;
  625. case 6:
  626. dpad_left = SDL_TRUE;
  627. break;
  628. case 7:
  629. dpad_up = SDL_TRUE;
  630. dpad_left = SDL_TRUE;
  631. break;
  632. default:
  633. break;
  634. }
  635. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_DOWN, dpad_down);
  636. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_UP, dpad_up);
  637. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT, dpad_right);
  638. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT, dpad_left);
  639. }
  640. }
  641. if (ctx->last_state.rgucButtonsHatAndCounter[1] != packet->rgucButtonsHatAndCounter[1]) {
  642. Uint8 data = packet->rgucButtonsHatAndCounter[1];
  643. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSHOULDER, (data & 0x01) ? SDL_PRESSED : SDL_RELEASED);
  644. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, (data & 0x02) ? SDL_PRESSED : SDL_RELEASED);
  645. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_BACK, (data & 0x10) ? SDL_PRESSED : SDL_RELEASED);
  646. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_START, (data & 0x20) ? SDL_PRESSED : SDL_RELEASED);
  647. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSTICK, (data & 0x40) ? SDL_PRESSED : SDL_RELEASED);
  648. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSTICK, (data & 0x80) ? SDL_PRESSED : SDL_RELEASED);
  649. }
  650. /* 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
  651. trigger is evaluated
  652. */
  653. if ((packet->rgucButtonsHatAndCounter[1] & 0x0C) != 0) {
  654. Uint8 data = packet->rgucButtonsHatAndCounter[1];
  655. packet->ucTriggerLeft = (data & 0x04) && packet->ucTriggerLeft == 0 ? 255 : packet->ucTriggerLeft;
  656. packet->ucTriggerRight = (data & 0x08) && packet->ucTriggerRight == 0 ? 255 : packet->ucTriggerRight;
  657. }
  658. if (ctx->last_state.rgucButtonsHatAndCounter[2] != packet->rgucButtonsHatAndCounter[2]) {
  659. Uint8 data = (packet->rgucButtonsHatAndCounter[2] & 0x03);
  660. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE, (data & 0x01) ? SDL_PRESSED : SDL_RELEASED);
  661. SDL_PrivateJoystickButton(joystick, 15, (data & 0x02) ? SDL_PRESSED : SDL_RELEASED);
  662. }
  663. axis = ((int)packet->ucTriggerLeft * 257) - 32768;
  664. SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, axis);
  665. axis = ((int)packet->ucTriggerRight * 257) - 32768;
  666. SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, axis);
  667. axis = ((int)packet->ucLeftJoystickX * 257) - 32768;
  668. SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTX, axis);
  669. axis = ((int)packet->ucLeftJoystickY * 257) - 32768;
  670. SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTY, axis);
  671. axis = ((int)packet->ucRightJoystickX * 257) - 32768;
  672. SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTX, axis);
  673. axis = ((int)packet->ucRightJoystickY * 257) - 32768;
  674. SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTY, axis);
  675. if (packet->ucBatteryLevel & 0x10) {
  676. joystick->epowerlevel = SDL_JOYSTICK_POWER_WIRED;
  677. } else {
  678. /* Battery level ranges from 0 to 10 */
  679. int level = (packet->ucBatteryLevel & 0xF);
  680. if (level == 0) {
  681. joystick->epowerlevel = SDL_JOYSTICK_POWER_EMPTY;
  682. } else if (level <= 2) {
  683. joystick->epowerlevel = SDL_JOYSTICK_POWER_LOW;
  684. } else if (level <= 7) {
  685. joystick->epowerlevel = SDL_JOYSTICK_POWER_MEDIUM;
  686. } else {
  687. joystick->epowerlevel = SDL_JOYSTICK_POWER_FULL;
  688. }
  689. }
  690. touchpad_state = ((packet->ucTouchpadCounter1 & 0x80) == 0) ? SDL_PRESSED : SDL_RELEASED;
  691. touchpad_x = packet->rgucTouchpadData1[0] | (((int)packet->rgucTouchpadData1[1] & 0x0F) << 8);
  692. touchpad_y = (packet->rgucTouchpadData1[1] >> 4) | ((int)packet->rgucTouchpadData1[2] << 4);
  693. SDL_PrivateJoystickTouchpad(joystick, 0, 0, touchpad_state, touchpad_x * TOUCHPAD_SCALEX, touchpad_y * TOUCHPAD_SCALEY, touchpad_state ? 1.0f : 0.0f);
  694. touchpad_state = ((packet->ucTouchpadCounter2 & 0x80) == 0) ? SDL_PRESSED : SDL_RELEASED;
  695. touchpad_x = packet->rgucTouchpadData2[0] | (((int)packet->rgucTouchpadData2[1] & 0x0F) << 8);
  696. touchpad_y = (packet->rgucTouchpadData2[1] >> 4) | ((int)packet->rgucTouchpadData2[2] << 4);
  697. SDL_PrivateJoystickTouchpad(joystick, 0, 1, touchpad_state, touchpad_x * TOUCHPAD_SCALEX, touchpad_y * TOUCHPAD_SCALEY, touchpad_state ? 1.0f : 0.0f);
  698. if (ctx->report_sensors) {
  699. float data[3];
  700. data[0] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 0, LOAD16(packet->rgucGyroX[0], packet->rgucGyroX[1]));
  701. data[1] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 1, LOAD16(packet->rgucGyroY[0], packet->rgucGyroY[1]));
  702. data[2] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 2, LOAD16(packet->rgucGyroZ[0], packet->rgucGyroZ[1]));
  703. SDL_PrivateJoystickSensor(joystick, SDL_SENSOR_GYRO, data, 3);
  704. data[0] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 3, LOAD16(packet->rgucAccelX[0], packet->rgucAccelX[1]));
  705. data[1] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 4, LOAD16(packet->rgucAccelY[0], packet->rgucAccelY[1]));
  706. data[2] = HIDAPI_DriverPS4_ApplyCalibrationData(ctx, 5, LOAD16(packet->rgucAccelZ[0], packet->rgucAccelZ[1]));
  707. SDL_PrivateJoystickSensor(joystick, SDL_SENSOR_ACCEL, data, 3);
  708. }
  709. SDL_memcpy(&ctx->last_state, packet, sizeof(ctx->last_state));
  710. }
  711. static SDL_bool
  712. HIDAPI_DriverPS4_UpdateDevice(SDL_HIDAPI_Device *device)
  713. {
  714. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  715. SDL_Joystick *joystick = NULL;
  716. Uint8 data[USB_PACKET_LENGTH*2];
  717. int size;
  718. int packet_count = 0;
  719. if (device->num_joysticks > 0) {
  720. joystick = SDL_JoystickFromInstanceID(device->joysticks[0]);
  721. }
  722. if (!joystick) {
  723. return SDL_FALSE;
  724. }
  725. while ((size = SDL_hid_read_timeout(device->dev, data, sizeof(data), 0)) > 0) {
  726. #ifdef DEBUG_PS4_PROTOCOL
  727. HIDAPI_DumpPacket("PS4 packet: size = %d", data, size);
  728. #endif
  729. ++packet_count;
  730. ctx->last_packet = SDL_GetTicks();
  731. switch (data[0]) {
  732. case k_EPS4ReportIdUsbState:
  733. HIDAPI_DriverPS4_HandleStatePacket(joystick, device->dev, ctx, (PS4StatePacket_t *)&data[1]);
  734. break;
  735. case k_EPS4ReportIdBluetoothState1:
  736. case k_EPS4ReportIdBluetoothState2:
  737. case k_EPS4ReportIdBluetoothState3:
  738. case k_EPS4ReportIdBluetoothState4:
  739. case k_EPS4ReportIdBluetoothState5:
  740. case k_EPS4ReportIdBluetoothState6:
  741. case k_EPS4ReportIdBluetoothState7:
  742. case k_EPS4ReportIdBluetoothState8:
  743. case k_EPS4ReportIdBluetoothState9:
  744. if (!ctx->enhanced_mode) {
  745. /* This is the extended report, we can enable effects now */
  746. HIDAPI_DriverPS4_SetEnhancedMode(device, joystick);
  747. }
  748. /* Bluetooth state packets have two additional bytes at the beginning, the first notes if HID is present */
  749. if (data[1] & 0x80) {
  750. HIDAPI_DriverPS4_HandleStatePacket(joystick, device->dev, ctx, (PS4StatePacket_t*)&data[3]);
  751. }
  752. break;
  753. default:
  754. #ifdef DEBUG_JOYSTICK
  755. SDL_Log("Unknown PS4 packet: 0x%.2x\n", data[0]);
  756. #endif
  757. break;
  758. }
  759. }
  760. if (ctx->is_bluetooth && packet_count == 0) {
  761. /* Check to see if it looks like the device disconnected */
  762. if (SDL_TICKS_PASSED(SDL_GetTicks(), ctx->last_packet + BLUETOOTH_DISCONNECT_TIMEOUT_MS)) {
  763. /* Send an empty output report to tickle the Bluetooth stack */
  764. HIDAPI_DriverPS4_TickleBluetooth(device);
  765. }
  766. }
  767. if (size < 0) {
  768. /* Read error, device is disconnected */
  769. HIDAPI_JoystickDisconnected(device, joystick->instance_id);
  770. }
  771. return (size >= 0);
  772. }
  773. static void
  774. HIDAPI_DriverPS4_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  775. {
  776. SDL_DriverPS4_Context *ctx = (SDL_DriverPS4_Context *)device->context;
  777. SDL_DelHintCallback(SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE,
  778. SDL_PS4RumbleHintChanged, ctx);
  779. SDL_LockMutex(device->dev_lock);
  780. {
  781. SDL_hid_close(device->dev);
  782. device->dev = NULL;
  783. SDL_free(device->context);
  784. device->context = NULL;
  785. }
  786. SDL_UnlockMutex(device->dev_lock);
  787. }
  788. static void
  789. HIDAPI_DriverPS4_FreeDevice(SDL_HIDAPI_Device *device)
  790. {
  791. }
  792. SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverPS4 =
  793. {
  794. SDL_HINT_JOYSTICK_HIDAPI_PS4,
  795. SDL_TRUE,
  796. SDL_TRUE,
  797. HIDAPI_DriverPS4_IsSupportedDevice,
  798. HIDAPI_DriverPS4_GetDeviceName,
  799. HIDAPI_DriverPS4_InitDevice,
  800. HIDAPI_DriverPS4_GetDevicePlayerIndex,
  801. HIDAPI_DriverPS4_SetDevicePlayerIndex,
  802. HIDAPI_DriverPS4_UpdateDevice,
  803. HIDAPI_DriverPS4_OpenJoystick,
  804. HIDAPI_DriverPS4_RumbleJoystick,
  805. HIDAPI_DriverPS4_RumbleJoystickTriggers,
  806. HIDAPI_DriverPS4_GetJoystickCapabilities,
  807. HIDAPI_DriverPS4_SetJoystickLED,
  808. HIDAPI_DriverPS4_SendJoystickEffect,
  809. HIDAPI_DriverPS4_SetJoystickSensorsEnabled,
  810. HIDAPI_DriverPS4_CloseJoystick,
  811. HIDAPI_DriverPS4_FreeDevice,
  812. };
  813. #endif /* SDL_JOYSTICK_HIDAPI_PS4 */
  814. #endif /* SDL_JOYSTICK_HIDAPI */
  815. /* vi: set ts=4 sw=4 expandtab: */