xbox_controller_mac.mm 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. // Copyright 2017 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "device/gamepad/xbox_controller_mac.h"
  5. #include <algorithm>
  6. #include <cmath>
  7. #include <limits>
  8. #include <CoreFoundation/CoreFoundation.h>
  9. #include <IOKit/IOCFPlugIn.h>
  10. #include <IOKit/IOKitLib.h>
  11. #include <IOKit/IOMessage.h>
  12. #include <IOKit/usb/IOUSBLib.h>
  13. #include <IOKit/usb/USB.h>
  14. #include "base/bind.h"
  15. #include "base/callback_helpers.h"
  16. #include "base/check_op.h"
  17. #include "base/cxx17_backports.h"
  18. #include "base/location.h"
  19. #include "base/mac/foundation_util.h"
  20. #include "base/mac/scoped_ioobject.h"
  21. #include "base/task/sequenced_task_runner.h"
  22. #include "base/threading/thread_task_runner_handle.h"
  23. #include "device/gamepad/gamepad_uma.h"
  24. namespace device {
  25. namespace {
  26. const int kXbox360ReadEndpoint = 1;
  27. const int kXbox360ControlEndpoint = 2;
  28. const int kXboxOneReadEndpoint = 2;
  29. const int kXboxOneControlEndpoint = 1;
  30. const double kXboxOneMaxEffectDurationMillis = 2500; // 2.5 seconds
  31. const size_t kXbox360HeaderBytes = 2;
  32. const size_t kXboxOneHeaderBytes = 4;
  33. enum {
  34. STATUS_MESSAGE_BUTTONS = 0,
  35. STATUS_MESSAGE_LED = 1,
  36. // Apparently this message tells you if the rumble pack is disabled in the
  37. // controller. If the rumble pack is disabled, vibration control messages
  38. // have no effect.
  39. STATUS_MESSAGE_RUMBLE = 3,
  40. };
  41. enum {
  42. XBOX_ONE_STATUS_MESSAGE_BUTTONS = 0x20,
  43. XBOX_ONE_STATUS_MESSAGE_GUIDE = 0x07
  44. };
  45. enum {
  46. CONTROL_MESSAGE_SET_RUMBLE = 0,
  47. CONTROL_MESSAGE_SET_LED = 1,
  48. };
  49. #pragma pack(push, 1)
  50. struct Xbox360ButtonData {
  51. bool dpad_up : 1;
  52. bool dpad_down : 1;
  53. bool dpad_left : 1;
  54. bool dpad_right : 1;
  55. bool start : 1;
  56. bool back : 1;
  57. bool stick_left_click : 1;
  58. bool stick_right_click : 1;
  59. bool bumper_left : 1;
  60. bool bumper_right : 1;
  61. bool guide : 1;
  62. bool dummy1 : 1; // Always 0.
  63. bool a : 1;
  64. bool b : 1;
  65. bool x : 1;
  66. bool y : 1;
  67. uint8_t trigger_left;
  68. uint8_t trigger_right;
  69. int16_t stick_left_x;
  70. int16_t stick_left_y;
  71. int16_t stick_right_x;
  72. int16_t stick_right_y;
  73. // Always 0.
  74. uint32_t dummy2;
  75. uint16_t dummy3;
  76. };
  77. struct Xbox360RumbleData {
  78. uint8_t command;
  79. uint8_t size;
  80. uint8_t dummy1;
  81. uint8_t big;
  82. uint8_t little;
  83. uint8_t dummy2[3];
  84. };
  85. struct XboxOneButtonData {
  86. bool sync : 1;
  87. bool dummy1 : 1; // Always 0.
  88. bool start : 1;
  89. bool back : 1;
  90. bool a : 1;
  91. bool b : 1;
  92. bool x : 1;
  93. bool y : 1;
  94. bool dpad_up : 1;
  95. bool dpad_down : 1;
  96. bool dpad_left : 1;
  97. bool dpad_right : 1;
  98. bool bumper_left : 1;
  99. bool bumper_right : 1;
  100. bool stick_left_click : 1;
  101. bool stick_right_click : 1;
  102. uint16_t trigger_left;
  103. uint16_t trigger_right;
  104. int16_t stick_left_x;
  105. int16_t stick_left_y;
  106. int16_t stick_right_x;
  107. int16_t stick_right_y;
  108. };
  109. struct XboxSeriesXOldFirmwareButtonData {
  110. XboxOneButtonData xbox_one_data;
  111. bool share : 1;
  112. uint8_t padding : 7;
  113. };
  114. // Accurate for firmware version 5.5.2641.
  115. struct XboxSeriesXButtonData {
  116. XboxOneButtonData xbox_one_data;
  117. uint8_t padding[4];
  118. bool share : 1;
  119. uint8_t padding2 : 7;
  120. };
  121. struct XboxOneGuideData {
  122. uint8_t down;
  123. uint8_t dummy1;
  124. };
  125. struct XboxOneRumbleData {
  126. uint8_t command;
  127. uint8_t dummy1;
  128. uint8_t counter;
  129. uint8_t size;
  130. uint8_t mode;
  131. uint8_t rumble_mask;
  132. uint8_t trigger_left;
  133. uint8_t trigger_right;
  134. uint8_t strong_magnitude;
  135. uint8_t weak_magnitude;
  136. uint8_t duration;
  137. uint8_t period;
  138. uint8_t extra;
  139. };
  140. #pragma pack(pop)
  141. static_assert(sizeof(Xbox360ButtonData) == 18, "Xbox360ButtonData wrong size");
  142. static_assert(sizeof(Xbox360RumbleData) == 8, "Xbox360RumbleData wrong size");
  143. static_assert(sizeof(XboxOneButtonData) == 14, "XboxOneButtonData wrong size");
  144. static_assert(sizeof(XboxOneGuideData) == 2, "XboxOneGuideData wrong size");
  145. static_assert(sizeof(XboxOneRumbleData) == 13, "XboxOneRumbleData wrong size");
  146. static_assert(sizeof(XboxSeriesXOldFirmwareButtonData) == 15,
  147. "XboxSeriesXOldFirmwareButtonData wrong size");
  148. static_assert(sizeof(XboxSeriesXButtonData) == 19,
  149. "XboxSeriesXButtonData wrong size");
  150. // Report lengths for the input reports that carry gamepad button and axis data
  151. // on special Xbox One devices. These devices support input remapping and
  152. // include both the mapped and unmapped data in the input report, along with
  153. // additional data specific to the device. This driver only uses the mapped
  154. // data, which is at the beginning of the report and has the same structure as
  155. // the standard XboxOneButtonData report.
  156. const size_t kXboxOneEliteButtonDataBytes = 29;
  157. const size_t kXboxOneElite2ButtonDataBytes = 34;
  158. const size_t kXboxAdaptiveButtonDataBytes = 50;
  159. const size_t kXboxSeriesXOldFirmwareButtonDataBytes = 40;
  160. const size_t kXboxSeriesXButtonDataBytes = 44;
  161. // From MSDN:
  162. // http://msdn.microsoft.com/en-us/library/windows/desktop/ee417001(v=vs.85).aspx#dead_zone
  163. const int16_t kLeftThumbDeadzone = 7849;
  164. const int16_t kRightThumbDeadzone = 8689;
  165. const uint8_t kXbox360TriggerDeadzone = 30;
  166. const uint16_t kXboxOneTriggerMax = 1023;
  167. const uint16_t kXboxOneTriggerDeadzone = 120;
  168. void NormalizeAxis(int16_t x,
  169. int16_t y,
  170. int16_t deadzone,
  171. float* x_out,
  172. float* y_out) {
  173. float x_val = x;
  174. float y_val = y;
  175. // Determine how far the stick is pushed.
  176. float real_magnitude = std::sqrt(x_val * x_val + y_val * y_val);
  177. // Check if the controller is outside a circular dead zone.
  178. if (real_magnitude > deadzone) {
  179. // Clip the magnitude at its expected maximum value.
  180. float magnitude = std::min(32767.0f, real_magnitude);
  181. // Adjust magnitude relative to the end of the dead zone.
  182. magnitude -= deadzone;
  183. // Normalize the magnitude with respect to its expected range giving a
  184. // magnitude value of 0.0 to 1.0
  185. float ratio = (magnitude / (32767 - deadzone)) / real_magnitude;
  186. // Y is negated because xbox controllers have an opposite sign from
  187. // the 'standard controller' recommendations.
  188. *x_out = x_val * ratio;
  189. *y_out = -y_val * ratio;
  190. } else {
  191. // If the controller is in the deadzone zero out the magnitude.
  192. *x_out = *y_out = 0.0f;
  193. }
  194. }
  195. float NormalizeTrigger(uint8_t value) {
  196. return value < kXbox360TriggerDeadzone
  197. ? 0
  198. : static_cast<float>(value - kXbox360TriggerDeadzone) /
  199. (std::numeric_limits<uint8_t>::max() -
  200. kXbox360TriggerDeadzone);
  201. }
  202. float NormalizeXboxOneTrigger(uint16_t value) {
  203. return value < kXboxOneTriggerDeadzone
  204. ? 0
  205. : static_cast<float>(value - kXboxOneTriggerDeadzone) /
  206. (kXboxOneTriggerMax - kXboxOneTriggerDeadzone);
  207. }
  208. void NormalizeXbox360ButtonData(const Xbox360ButtonData& data,
  209. XboxControllerMac::Data* normalized_data) {
  210. normalized_data->buttons[0] = data.a;
  211. normalized_data->buttons[1] = data.b;
  212. normalized_data->buttons[2] = data.x;
  213. normalized_data->buttons[3] = data.y;
  214. normalized_data->buttons[4] = data.bumper_left;
  215. normalized_data->buttons[5] = data.bumper_right;
  216. normalized_data->buttons[6] = data.back;
  217. normalized_data->buttons[7] = data.start;
  218. normalized_data->buttons[8] = data.stick_left_click;
  219. normalized_data->buttons[9] = data.stick_right_click;
  220. normalized_data->buttons[10] = data.dpad_up;
  221. normalized_data->buttons[11] = data.dpad_down;
  222. normalized_data->buttons[12] = data.dpad_left;
  223. normalized_data->buttons[13] = data.dpad_right;
  224. normalized_data->buttons[14] = data.guide;
  225. normalized_data->triggers[0] = NormalizeTrigger(data.trigger_left);
  226. normalized_data->triggers[1] = NormalizeTrigger(data.trigger_right);
  227. NormalizeAxis(data.stick_left_x, data.stick_left_y, kLeftThumbDeadzone,
  228. &normalized_data->axes[0], &normalized_data->axes[1]);
  229. NormalizeAxis(data.stick_right_x, data.stick_right_y, kRightThumbDeadzone,
  230. &normalized_data->axes[2], &normalized_data->axes[3]);
  231. }
  232. void NormalizeXboxOneButtonData(const XboxOneButtonData& data,
  233. XboxControllerMac::Data* normalized_data) {
  234. normalized_data->buttons[0] = data.a;
  235. normalized_data->buttons[1] = data.b;
  236. normalized_data->buttons[2] = data.x;
  237. normalized_data->buttons[3] = data.y;
  238. normalized_data->buttons[4] = data.bumper_left;
  239. normalized_data->buttons[5] = data.bumper_right;
  240. normalized_data->buttons[6] = data.back;
  241. normalized_data->buttons[7] = data.start;
  242. normalized_data->buttons[8] = data.stick_left_click;
  243. normalized_data->buttons[9] = data.stick_right_click;
  244. normalized_data->buttons[10] = data.dpad_up;
  245. normalized_data->buttons[11] = data.dpad_down;
  246. normalized_data->buttons[12] = data.dpad_left;
  247. normalized_data->buttons[13] = data.dpad_right;
  248. normalized_data->triggers[0] = NormalizeXboxOneTrigger(data.trigger_left);
  249. normalized_data->triggers[1] = NormalizeXboxOneTrigger(data.trigger_right);
  250. NormalizeAxis(data.stick_left_x, data.stick_left_y, kLeftThumbDeadzone,
  251. &normalized_data->axes[0], &normalized_data->axes[1]);
  252. NormalizeAxis(data.stick_right_x, data.stick_right_y, kRightThumbDeadzone,
  253. &normalized_data->axes[2], &normalized_data->axes[3]);
  254. }
  255. std::string GetDeviceName(io_service_t service) {
  256. io_name_t device_name;
  257. kern_return_t kr = IORegistryEntryGetName(service, device_name);
  258. if (kr != KERN_SUCCESS)
  259. return "Unknown Gamepad";
  260. return std::string(device_name);
  261. }
  262. } // namespace
  263. XboxControllerMac::XboxControllerMac(Delegate* delegate)
  264. : delegate_(delegate) {}
  265. XboxControllerMac::~XboxControllerMac() = default;
  266. void XboxControllerMac::DoShutdown() {
  267. if (source_)
  268. CFRunLoopSourceInvalidate(source_);
  269. source_.reset();
  270. if (interface_ && interface_is_open_)
  271. (*interface_)->USBInterfaceClose(interface_);
  272. interface_.reset();
  273. if (device_ && device_is_open_)
  274. (*device_)->USBDeviceClose(device_);
  275. device_.reset();
  276. }
  277. double XboxControllerMac::GetMaxEffectDurationMillis() {
  278. // The Xbox One controller rumble packet specifies a duration for the rumble
  279. // effect with a maximum length of about 3 seconds.
  280. return kXboxOneMaxEffectDurationMillis;
  281. }
  282. void XboxControllerMac::SetVibration(mojom::GamepadEffectParametersPtr params) {
  283. if (!SupportsVibration())
  284. return;
  285. // Clamp magnitudes to [0,1]
  286. double strong_magnitude =
  287. base::clamp<double>(params->strong_magnitude, 0.0, 1.0);
  288. double weak_magnitude = base::clamp<double>(params->weak_magnitude, 0.0, 1.0);
  289. if (xinput_type_ == kXInputTypeXbox360) {
  290. WriteXbox360Rumble(static_cast<uint8_t>(strong_magnitude * 255.0),
  291. static_cast<uint8_t>(weak_magnitude * 255.0));
  292. } else if (xinput_type_ == kXInputTypeXboxOne) {
  293. WriteXboxOneRumble(static_cast<uint8_t>(strong_magnitude * 255.0),
  294. static_cast<uint8_t>(weak_magnitude * 255.0));
  295. }
  296. }
  297. XboxControllerMac::OpenDeviceResult XboxControllerMac::OpenDevice(
  298. io_service_t service) {
  299. IOCFPlugInInterface** plugin;
  300. SInt32 score; // Unused, but required for IOCreatePlugInInterfaceForService.
  301. kern_return_t kr = IOCreatePlugInInterfaceForService(
  302. service, kIOUSBDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &plugin,
  303. &score);
  304. if (kr != KERN_SUCCESS)
  305. return OPEN_FAILED;
  306. base::mac::ScopedIOPluginInterface<IOCFPlugInInterface> plugin_ref(plugin);
  307. HRESULT res = (*plugin)->QueryInterface(
  308. plugin, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID320),
  309. (LPVOID*)&device_);
  310. if (!SUCCEEDED(res) || !device_)
  311. return OPEN_FAILED;
  312. kr = (*device_)->GetDeviceVendor(device_, &vendor_id_);
  313. if (kr != KERN_SUCCESS)
  314. return OPEN_FAILED;
  315. kr = (*device_)->GetDeviceProduct(device_, &product_id_);
  316. if (kr != KERN_SUCCESS)
  317. return OPEN_FAILED;
  318. // Record a connected XInput gamepad. Non-XInput devices are recorded
  319. // elsewhere.
  320. xinput_type_ = GamepadIdList::Get().GetXInputType(vendor_id_, product_id_);
  321. DCHECK_NE(xinput_type_, kXInputTypeNone);
  322. gamepad_id_ = GamepadIdList::Get().GetGamepadId(base::StringPiece(),
  323. vendor_id_, product_id_);
  324. RecordConnectedGamepad(gamepad_id_);
  325. // Get the product name. Use hard-coded strings for older devices to avoid
  326. // breaking applications that expect these strings. New devices should use
  327. // the product name reported by the device.
  328. switch (gamepad_id_) {
  329. case GamepadId::kMicrosoftProduct028e: // Xbox 360
  330. product_name_ = "Xbox 360 Controller";
  331. break;
  332. case GamepadId::kMicrosoftProduct02d1: // Xbox One
  333. case GamepadId::kMicrosoftProduct02dd: // Xbox One, 2015 firmware
  334. case GamepadId::kMicrosoftProduct02e3: // Xbox One Elite
  335. case GamepadId::kMicrosoftProduct0b00: // Xbox One Elite v2
  336. case GamepadId::kMicrosoftProduct02ea: // Xbox One S
  337. case GamepadId::kMicrosoftProduct0b0a: // Xbox Adaptive
  338. product_name_ = "Xbox One Controller";
  339. break;
  340. case GamepadId::kMicrosoftProduct0b12: // Xbox Series X
  341. product_name_ = "Xbox Series X Controller";
  342. break;
  343. default:
  344. product_name_ = GetDeviceName(service);
  345. break;
  346. }
  347. IOUSBFindInterfaceRequest request;
  348. switch (xinput_type_) {
  349. case kXInputTypeXbox360:
  350. read_endpoint_ = kXbox360ReadEndpoint;
  351. control_endpoint_ = kXbox360ControlEndpoint;
  352. request.bInterfaceClass = 255;
  353. request.bInterfaceSubClass = 93;
  354. request.bInterfaceProtocol = 1;
  355. request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
  356. break;
  357. case kXInputTypeXboxOne:
  358. read_endpoint_ = kXboxOneReadEndpoint;
  359. control_endpoint_ = kXboxOneControlEndpoint;
  360. request.bInterfaceClass = 255;
  361. request.bInterfaceSubClass = 71;
  362. request.bInterfaceProtocol = 208;
  363. request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
  364. break;
  365. default:
  366. return OPEN_FAILED;
  367. }
  368. // Open the device and configure it.
  369. kr = (*device_)->USBDeviceOpen(device_);
  370. if (kr == kIOReturnExclusiveAccess) {
  371. // USBDeviceOpen may fail with kIOReturnExclusiveAccess if the device has
  372. // already been opened by another process. Usually this is temporary and
  373. // the device will soon become available. Signal to the data fetcher that
  374. // it should retry.
  375. return OPEN_FAILED_EXCLUSIVE_ACCESS;
  376. } else if (kr != KERN_SUCCESS) {
  377. return OPEN_FAILED;
  378. }
  379. device_is_open_ = true;
  380. // Xbox controllers have one configuration option which has configuration
  381. // value 1. Try to set it and fail if it couldn't be configured.
  382. IOUSBConfigurationDescriptorPtr config_desc;
  383. kr = (*device_)->GetConfigurationDescriptorPtr(device_, 0, &config_desc);
  384. if (kr != KERN_SUCCESS)
  385. return OPEN_FAILED;
  386. kr = (*device_)->SetConfiguration(device_, config_desc->bConfigurationValue);
  387. if (kr != KERN_SUCCESS)
  388. return OPEN_FAILED;
  389. // The device has 4 interfaces. They are as follows:
  390. // Protocol 1:
  391. // - Endpoint 1 (in) : Controller events, including button presses.
  392. // - Endpoint 2 (out): Rumble pack and LED control
  393. // Protocol 2 has a single endpoint to read from a connected ChatPad device.
  394. // Protocol 3 is used by a connected headset device.
  395. // The device also has an interface on subclass 253, protocol 10 with no
  396. // endpoints. It is unused.
  397. //
  398. // We don't currently support the ChatPad or headset, so protocol 1 is the
  399. // only protocol we care about.
  400. //
  401. // For more detail, see
  402. // https://github.com/Grumbel/xboxdrv/blob/master/PROTOCOL
  403. io_iterator_t iter;
  404. kr = (*device_)->CreateInterfaceIterator(device_, &request, &iter);
  405. if (kr != KERN_SUCCESS)
  406. return OPEN_FAILED;
  407. base::mac::ScopedIOObject<io_iterator_t> iter_ref(iter);
  408. // There should be exactly one USB interface which matches the requested
  409. // settings.
  410. io_service_t usb_interface = IOIteratorNext(iter);
  411. if (!usb_interface)
  412. return OPEN_FAILED;
  413. // We need to make an InterfaceInterface to communicate with the device
  414. // endpoint. This is the same process as earlier: first make a
  415. // PluginInterface from the io_service then make the InterfaceInterface from
  416. // that.
  417. IOCFPlugInInterface** plugin_interface;
  418. kr = IOCreatePlugInInterfaceForService(
  419. usb_interface, kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID,
  420. &plugin_interface, &score);
  421. if (kr != KERN_SUCCESS || !plugin_interface)
  422. return OPEN_FAILED;
  423. base::mac::ScopedIOPluginInterface<IOCFPlugInInterface> interface_ref(
  424. plugin_interface);
  425. // Release the USB interface, and any subsequent interfaces returned by the
  426. // iterator. (There shouldn't be any, but in case a future device does
  427. // contain more interfaces, this will serve to avoid memory leaks.)
  428. do {
  429. IOObjectRelease(usb_interface);
  430. } while ((usb_interface = IOIteratorNext(iter)));
  431. // Actually create the interface.
  432. res = (*plugin_interface)
  433. ->QueryInterface(plugin_interface,
  434. CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID300),
  435. (LPVOID*)&interface_);
  436. if (!SUCCEEDED(res) || !interface_)
  437. return OPEN_FAILED;
  438. // Actually open the interface.
  439. kr = (*interface_)->USBInterfaceOpen(interface_);
  440. if (kr != KERN_SUCCESS)
  441. return OPEN_FAILED;
  442. interface_is_open_ = true;
  443. CFRunLoopSourceRef source_ref;
  444. kr = (*interface_)->CreateInterfaceAsyncEventSource(interface_, &source_ref);
  445. if (kr != KERN_SUCCESS || !source_ref)
  446. return OPEN_FAILED;
  447. source_.reset(source_ref);
  448. CFRunLoopAddSource(CFRunLoopGetCurrent(), source_, kCFRunLoopDefaultMode);
  449. // The interface should have two pipes. Pipe 1 with direction kUSBIn and pipe
  450. // 2 with direction kUSBOut. Both pipes should have type kUSBInterrupt.
  451. uint8_t num_endpoints;
  452. kr = (*interface_)->GetNumEndpoints(interface_, &num_endpoints);
  453. if (kr != KERN_SUCCESS || num_endpoints < 2)
  454. return OPEN_FAILED;
  455. for (int i = 1; i <= 2; i++) {
  456. uint8_t direction;
  457. uint8_t number;
  458. uint8_t transfer_type;
  459. uint16_t max_packet_size;
  460. uint8_t interval;
  461. kr = (*interface_)
  462. ->GetPipeProperties(interface_, i, &direction, &number,
  463. &transfer_type, &max_packet_size, &interval);
  464. if (kr != KERN_SUCCESS || transfer_type != kUSBInterrupt)
  465. return OPEN_FAILED;
  466. if (i == read_endpoint_) {
  467. if (direction != kUSBIn)
  468. return OPEN_FAILED;
  469. read_buffer_.reset(new uint8_t[max_packet_size]);
  470. read_buffer_size_ = max_packet_size;
  471. if (!QueueRead())
  472. return OPEN_FAILED;
  473. } else if (i == control_endpoint_) {
  474. if (direction != kUSBOut)
  475. return OPEN_FAILED;
  476. // Xbox One controllers require an initialization packet.
  477. if (xinput_type_ == kXInputTypeXboxOne && !WriteXboxOneInit())
  478. return OPEN_FAILED;
  479. }
  480. }
  481. // The location ID is unique per controller, and can be used to track
  482. // controllers through reconnections (though if a controller is detached from
  483. // one USB hub and attached to another, the location ID will change).
  484. kr = (*device_)->GetLocationID(device_, &location_id_);
  485. if (kr != KERN_SUCCESS)
  486. return OPEN_FAILED;
  487. return OPEN_SUCCEEDED;
  488. }
  489. void XboxControllerMac::SetLEDPattern(LEDPattern pattern) {
  490. led_pattern_ = pattern;
  491. const UInt8 length = 3;
  492. // This buffer will be released in WriteComplete when WritePipeAsync
  493. // finishes.
  494. UInt8* buffer = new UInt8[length];
  495. buffer[0] = static_cast<UInt8>(CONTROL_MESSAGE_SET_LED);
  496. buffer[1] = length;
  497. buffer[2] = static_cast<UInt8>(pattern);
  498. kern_return_t kr =
  499. (*interface_)
  500. ->WritePipeAsync(interface_, control_endpoint_, buffer,
  501. (UInt32)length, WriteComplete, buffer);
  502. if (kr != KERN_SUCCESS) {
  503. DLOG(ERROR) << "Write error: Failed to send Xbox 360 LED command.";
  504. delete[] buffer;
  505. }
  506. }
  507. bool XboxControllerMac::SupportsVibration() const {
  508. // The Xbox Adaptive Controller has no vibration actuators.
  509. return gamepad_id_ != GamepadId::kMicrosoftProduct0b0a;
  510. }
  511. // static
  512. void XboxControllerMac::WriteComplete(void* context,
  513. IOReturn result,
  514. void* arg0) {
  515. UInt8* buffer = static_cast<UInt8*>(context);
  516. delete[] buffer;
  517. // Ignoring any errors sending data, because they will usually only occur
  518. // when the device is disconnected, in which case it really doesn't matter if
  519. // the data got to the controller or not.
  520. if (result != kIOReturnSuccess)
  521. return;
  522. }
  523. // static
  524. void XboxControllerMac::GotData(void* context, IOReturn result, void* arg0) {
  525. size_t bytes_read = reinterpret_cast<size_t>(arg0);
  526. XboxControllerMac* controller = static_cast<XboxControllerMac*>(context);
  527. if (result != kIOReturnSuccess) {
  528. // This will happen if the device was disconnected. The gamepad has
  529. // probably been destroyed by a meteorite.
  530. DLOG(ERROR) << "Read error: Failed to read from the device.";
  531. controller->IOError();
  532. return;
  533. }
  534. auto xinput_type = controller->xinput_type();
  535. if (xinput_type == kXInputTypeXbox360)
  536. controller->ProcessXbox360Packet(bytes_read);
  537. else if (xinput_type == kXInputTypeXboxOne)
  538. controller->ProcessXboxOnePacket(bytes_read);
  539. // Queue up another read.
  540. if (!controller->QueueRead())
  541. controller->IOError();
  542. }
  543. void XboxControllerMac::ProcessXbox360Packet(size_t length) {
  544. if (length < kXbox360HeaderBytes)
  545. return;
  546. DCHECK_LE(length, read_buffer_size_);
  547. if (length > read_buffer_size_)
  548. return;
  549. uint8_t* buffer = read_buffer_.get();
  550. if (buffer[1] != length)
  551. // Length in packet doesn't match length reported by USB.
  552. return;
  553. uint8_t type = buffer[0];
  554. buffer += kXbox360HeaderBytes;
  555. length -= kXbox360HeaderBytes;
  556. switch (type) {
  557. case STATUS_MESSAGE_BUTTONS: {
  558. if (length != sizeof(Xbox360ButtonData))
  559. return;
  560. Xbox360ButtonData* data = reinterpret_cast<Xbox360ButtonData*>(buffer);
  561. Data normalized_data;
  562. NormalizeXbox360ButtonData(*data, &normalized_data);
  563. if (delegate_)
  564. delegate_->XboxControllerGotData(this, normalized_data);
  565. break;
  566. }
  567. case STATUS_MESSAGE_LED:
  568. if (length != 3)
  569. return;
  570. // The controller sends one of these messages every time the LED pattern
  571. // is set, as well as once when it is plugged in.
  572. if (led_pattern_ == LED_NUM_PATTERNS && buffer[0] < LED_NUM_PATTERNS)
  573. led_pattern_ = static_cast<LEDPattern>(buffer[0]);
  574. break;
  575. default:
  576. // Unknown packet: ignore!
  577. break;
  578. }
  579. }
  580. void XboxControllerMac::ProcessXboxOnePacket(size_t length) {
  581. if (length < kXboxOneHeaderBytes)
  582. return;
  583. DCHECK_LE(length, read_buffer_size_);
  584. if (length > read_buffer_size_)
  585. return;
  586. uint8_t* buffer = read_buffer_.get();
  587. uint8_t type = buffer[0];
  588. bool needs_ack = (buffer[1] == 0x30);
  589. uint8_t sequence_number = buffer[2];
  590. buffer += kXboxOneHeaderBytes;
  591. length -= kXboxOneHeaderBytes;
  592. switch (type) {
  593. case XBOX_ONE_STATUS_MESSAGE_BUTTONS: {
  594. if (length != sizeof(XboxOneButtonData) &&
  595. length != kXboxOneEliteButtonDataBytes &&
  596. length != kXboxOneElite2ButtonDataBytes &&
  597. length != kXboxAdaptiveButtonDataBytes &&
  598. length != kXboxSeriesXOldFirmwareButtonDataBytes &&
  599. length != kXboxSeriesXButtonDataBytes) {
  600. return;
  601. }
  602. Data normalized_data;
  603. if (gamepad_id_ == GamepadId::kMicrosoftProduct0b12) {
  604. // Xbox Series X received a firmware update that modified the input
  605. // report. Distinguish the old and new reports by size.
  606. if (length == kXboxSeriesXOldFirmwareButtonDataBytes) {
  607. XboxSeriesXOldFirmwareButtonData* data =
  608. reinterpret_cast<XboxSeriesXOldFirmwareButtonData*>(buffer);
  609. NormalizeXboxOneButtonData(data->xbox_one_data, &normalized_data);
  610. normalized_data.buttons[14] = data->share;
  611. } else if (length == kXboxSeriesXButtonDataBytes) {
  612. XboxSeriesXButtonData* data =
  613. reinterpret_cast<XboxSeriesXButtonData*>(buffer);
  614. NormalizeXboxOneButtonData(data->xbox_one_data, &normalized_data);
  615. normalized_data.buttons[14] = data->share;
  616. }
  617. } else {
  618. XboxOneButtonData* data = reinterpret_cast<XboxOneButtonData*>(buffer);
  619. NormalizeXboxOneButtonData(*data, &normalized_data);
  620. }
  621. if (delegate_)
  622. delegate_->XboxControllerGotData(this, normalized_data);
  623. break;
  624. }
  625. case XBOX_ONE_STATUS_MESSAGE_GUIDE: {
  626. if (length != sizeof(XboxOneGuideData))
  627. return;
  628. XboxOneGuideData* data = reinterpret_cast<XboxOneGuideData*>(buffer);
  629. delegate_->XboxControllerGotGuideData(this, data->down);
  630. // The Xbox One S controller requires these reports to be acked.
  631. if (needs_ack)
  632. WriteXboxOneAckGuide(sequence_number);
  633. break;
  634. }
  635. default:
  636. // Unknown packet: ignore!
  637. break;
  638. }
  639. }
  640. bool XboxControllerMac::QueueRead() {
  641. kern_return_t kr =
  642. (*interface_)
  643. ->ReadPipeAsync(interface_, read_endpoint_, read_buffer_.get(),
  644. read_buffer_size_, GotData, this);
  645. if (kr != KERN_SUCCESS)
  646. DLOG(ERROR) << "Read error: Failed to queue next read.";
  647. return kr == KERN_SUCCESS;
  648. }
  649. void XboxControllerMac::IOError() {
  650. // Ignore errors that occur while the controller is being shut down.
  651. if (delegate_ && !IsShuttingDown())
  652. delegate_->XboxControllerError(this);
  653. }
  654. void XboxControllerMac::WriteXbox360Rumble(uint8_t strong_magnitude,
  655. uint8_t weak_magnitude) {
  656. const UInt8 length = sizeof(Xbox360RumbleData);
  657. // This buffer will be released in WriteComplete when WritePipeAsync
  658. // finishes.
  659. UInt8* buffer = new UInt8[length];
  660. Xbox360RumbleData* rumble_data = reinterpret_cast<Xbox360RumbleData*>(buffer);
  661. memset(buffer, 0, length);
  662. rumble_data->command = 0x00; // Rumble
  663. rumble_data->size = length;
  664. // Set rumble intensities.
  665. rumble_data->big = strong_magnitude;
  666. rumble_data->little = weak_magnitude;
  667. kern_return_t kr =
  668. (*interface_)
  669. ->WritePipeAsync(interface_, control_endpoint_, buffer,
  670. (UInt32)length, WriteComplete, buffer);
  671. if (kr != KERN_SUCCESS) {
  672. DLOG(ERROR) << "Write error: Failed to send Xbox 360 rumble command.";
  673. delete[] buffer;
  674. }
  675. }
  676. bool XboxControllerMac::WriteXboxOneInit() {
  677. const UInt8 length = 5;
  678. // This buffer will be released in WriteComplete when WritePipeAsync
  679. // finishes.
  680. UInt8* buffer = new UInt8[length];
  681. buffer[0] = 0x05;
  682. buffer[1] = 0x20;
  683. buffer[2] = 0x00;
  684. buffer[3] = 0x01;
  685. buffer[4] = 0x00;
  686. kern_return_t kr =
  687. (*interface_)
  688. ->WritePipeAsync(interface_, control_endpoint_, buffer,
  689. (UInt32)length, WriteComplete, buffer);
  690. if (kr != KERN_SUCCESS) {
  691. DLOG(ERROR)
  692. << "Write error: Failed to send Xbox One initialization packet.";
  693. delete[] buffer;
  694. return false;
  695. }
  696. return true;
  697. }
  698. void XboxControllerMac::WriteXboxOneRumble(uint8_t strong_magnitude,
  699. uint8_t weak_magnitude) {
  700. const UInt8 length = sizeof(XboxOneRumbleData);
  701. // This buffer will be released in WriteComplete when WritePipeAsync
  702. // finishes.
  703. UInt8* buffer = new UInt8[length];
  704. XboxOneRumbleData* rumble_data = reinterpret_cast<XboxOneRumbleData*>(buffer);
  705. rumble_data->command = 0x09;
  706. rumble_data->dummy1 = 0x00;
  707. rumble_data->counter = counter_++;
  708. rumble_data->size = 0x09;
  709. rumble_data->mode = 0x00;
  710. rumble_data->rumble_mask = 0x0f;
  711. rumble_data->duration = 0xff;
  712. rumble_data->period = 0x00;
  713. rumble_data->extra = 0x00;
  714. // Set rumble intensities.
  715. rumble_data->trigger_left = 0x00;
  716. rumble_data->trigger_right = 0x00;
  717. rumble_data->strong_magnitude = strong_magnitude;
  718. rumble_data->weak_magnitude = weak_magnitude;
  719. kern_return_t kr =
  720. (*interface_)
  721. ->WritePipeAsync(interface_, control_endpoint_, buffer,
  722. (UInt32)length, WriteComplete, buffer);
  723. if (kr != KERN_SUCCESS) {
  724. DLOG(ERROR) << "Write error: Failed to send Xbox One rumble command.";
  725. delete[] buffer;
  726. }
  727. }
  728. // Ack the guide report. The contents of the ack report are modeled after
  729. // xpad's xboxone_ack_mode_report. See the mode_report_ack buffer defined in
  730. // this commit:
  731. // https://github.com/torvalds/linux/commit/57b8443d3e5bd046a519ff714ca31c64c7f04309
  732. void XboxControllerMac::WriteXboxOneAckGuide(uint8_t sequence_number) {
  733. const UInt8 length = 13;
  734. UInt8* buffer = new UInt8[length];
  735. buffer[0] = 0x01;
  736. buffer[1] = 0x20;
  737. buffer[2] = sequence_number;
  738. buffer[3] = 0x09;
  739. buffer[4] = 0x00;
  740. buffer[5] = 0x07;
  741. buffer[6] = 0x20;
  742. buffer[7] = 0x02;
  743. buffer[8] = 0x00;
  744. buffer[9] = 0x00;
  745. buffer[10] = 0x00;
  746. buffer[11] = 0x00;
  747. buffer[12] = 0x00;
  748. kern_return_t kr =
  749. (*interface_)
  750. ->WritePipeAsync(interface_, control_endpoint_, buffer,
  751. (UInt32)length, WriteComplete, buffer);
  752. if (kr != KERN_SUCCESS) {
  753. DLOG(ERROR) << "Write error: Failed to send Xbox One mode report reply.";
  754. delete[] buffer;
  755. }
  756. }
  757. base::WeakPtr<AbstractHapticGamepad> XboxControllerMac::GetWeakPtr() {
  758. return weak_factory_.GetWeakPtr();
  759. }
  760. } // namespace device