1 // Copyright 2013 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.
5 #include "content/browser/gamepad/xbox_data_fetcher_mac.h"
11 #include <CoreFoundation/CoreFoundation.h>
12 #include <IOKit/IOCFPlugIn.h>
13 #include <IOKit/IOKitLib.h>
14 #include <IOKit/usb/IOUSBLib.h>
15 #include <IOKit/usb/USB.h>
17 #include "base/logging.h"
18 #include "base/mac/foundation_util.h"
21 const int kVendorMicrosoft = 0x045e;
22 const int kProduct360Controller = 0x028e;
24 const int kReadEndpoint = 1;
25 const int kControlEndpoint = 2;
28 STATUS_MESSAGE_BUTTONS = 0,
29 STATUS_MESSAGE_LED = 1,
31 // Apparently this message tells you if the rumble pack is disabled in the
32 // controller. If the rumble pack is disabled, vibration control messages
34 STATUS_MESSAGE_RUMBLE = 3,
38 CONTROL_MESSAGE_SET_RUMBLE = 0,
39 CONTROL_MESSAGE_SET_LED = 1,
51 bool stick_left_click : 1;
52 bool stick_right_click : 1;
55 bool bumper_right : 1;
57 bool dummy1 : 1; // Always 0.
78 COMPILE_ASSERT(sizeof(ButtonData) == 0x12, xbox_button_data_wrong_size);
81 // http://msdn.microsoft.com/en-us/library/windows/desktop/ee417001(v=vs.85).aspx#dead_zone
82 const int16 kLeftThumbDeadzone = 7849;
83 const int16 kRightThumbDeadzone = 8689;
84 const uint8 kTriggerDeadzone = 30;
86 void NormalizeAxis(int16 x,
94 // Determine how far the stick is pushed.
95 float real_magnitude = std::sqrt(x_val * x_val + y_val * y_val);
97 // Check if the controller is outside a circular dead zone.
98 if (real_magnitude > deadzone) {
99 // Clip the magnitude at its expected maximum value.
100 float magnitude = std::min(32767.0f, real_magnitude);
102 // Adjust magnitude relative to the end of the dead zone.
103 magnitude -= deadzone;
105 // Normalize the magnitude with respect to its expected range giving a
106 // magnitude value of 0.0 to 1.0
107 float ratio = (magnitude / (32767 - deadzone)) / real_magnitude;
109 // Y is negated because xbox controllers have an opposite sign from
110 // the 'standard controller' recommendations.
111 *x_out = x_val * ratio;
112 *y_out = -y_val * ratio;
114 // If the controller is in the deadzone zero out the magnitude.
115 *x_out = *y_out = 0.0f;
119 float NormalizeTrigger(uint8 value) {
120 return value < kTriggerDeadzone ? 0 :
121 static_cast<float>(value - kTriggerDeadzone) /
122 (std::numeric_limits<uint8>::max() - kTriggerDeadzone);
125 void NormalizeButtonData(const ButtonData& data,
126 XboxController::Data* normalized_data) {
127 normalized_data->buttons[0] = data.a;
128 normalized_data->buttons[1] = data.b;
129 normalized_data->buttons[2] = data.x;
130 normalized_data->buttons[3] = data.y;
131 normalized_data->buttons[4] = data.bumper_left;
132 normalized_data->buttons[5] = data.bumper_right;
133 normalized_data->buttons[6] = data.back;
134 normalized_data->buttons[7] = data.start;
135 normalized_data->buttons[8] = data.stick_left_click;
136 normalized_data->buttons[9] = data.stick_right_click;
137 normalized_data->buttons[10] = data.dpad_up;
138 normalized_data->buttons[11] = data.dpad_down;
139 normalized_data->buttons[12] = data.dpad_left;
140 normalized_data->buttons[13] = data.dpad_right;
141 normalized_data->buttons[14] = data.guide;
142 normalized_data->triggers[0] = NormalizeTrigger(data.trigger_left);
143 normalized_data->triggers[1] = NormalizeTrigger(data.trigger_right);
144 NormalizeAxis(data.stick_left_x,
147 &normalized_data->axes[0],
148 &normalized_data->axes[1]);
149 NormalizeAxis(data.stick_right_x,
152 &normalized_data->axes[2],
153 &normalized_data->axes[3]);
158 XboxController::XboxController(Delegate* delegate)
161 device_is_open_(false),
162 interface_is_open_(false),
163 read_buffer_size_(0),
164 led_pattern_(LED_NUM_PATTERNS),
166 delegate_(delegate) {
169 XboxController::~XboxController() {
171 CFRunLoopSourceInvalidate(source_);
172 if (interface_ && interface_is_open_)
173 (*interface_)->USBInterfaceClose(interface_);
174 if (device_ && device_is_open_)
175 (*device_)->USBDeviceClose(device_);
178 bool XboxController::OpenDevice(io_service_t service) {
179 IOCFPlugInInterface **plugin;
180 SInt32 score; // Unused, but required for IOCreatePlugInInterfaceForService.
182 IOCreatePlugInInterfaceForService(service,
183 kIOUSBDeviceUserClientTypeID,
184 kIOCFPlugInInterfaceID,
187 if (kr != KERN_SUCCESS)
189 base::mac::ScopedIOPluginInterface<IOCFPlugInInterface> plugin_ref(plugin);
192 (*plugin)->QueryInterface(plugin,
193 CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID320),
195 if (!SUCCEEDED(res) || !device_)
199 kr = (*device_)->GetDeviceVendor(device_, &vendor_id);
200 if (kr != KERN_SUCCESS)
203 kr = (*device_)->GetDeviceProduct(device_, &product_id);
204 if (kr != KERN_SUCCESS)
206 if (vendor_id != kVendorMicrosoft || product_id != kProduct360Controller)
209 // Open the device and configure it.
210 kr = (*device_)->USBDeviceOpen(device_);
211 if (kr != KERN_SUCCESS)
213 device_is_open_ = true;
215 // Xbox controllers have one configuration option which has configuration
216 // value 1. Try to set it and fail if it couldn't be configured.
217 IOUSBConfigurationDescriptorPtr config_desc;
218 kr = (*device_)->GetConfigurationDescriptorPtr(device_, 0, &config_desc);
219 if (kr != KERN_SUCCESS)
221 kr = (*device_)->SetConfiguration(device_, config_desc->bConfigurationValue);
222 if (kr != KERN_SUCCESS)
225 // The device has 4 interfaces. They are as follows:
227 // - Endpoint 1 (in) : Controller events, including button presses.
228 // - Endpoint 2 (out): Rumble pack and LED control
229 // Protocol 2 has a single endpoint to read from a connected ChatPad device.
230 // Protocol 3 is used by a connected headset device.
231 // The device also has an interface on subclass 253, protocol 10 with no
232 // endpoints. It is unused.
234 // We don't currently support the ChatPad or headset, so protocol 1 is the
235 // only protocol we care about.
237 // For more detail, see
238 // https://github.com/Grumbel/xboxdrv/blob/master/PROTOCOL
239 IOUSBFindInterfaceRequest request;
240 request.bInterfaceClass = 255;
241 request.bInterfaceSubClass = 93;
242 request.bInterfaceProtocol = 1;
243 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
245 kr = (*device_)->CreateInterfaceIterator(device_, &request, &iter);
246 if (kr != KERN_SUCCESS)
248 base::mac::ScopedIOObject<io_iterator_t> iter_ref(iter);
250 // There should be exactly one USB interface which matches the requested
252 io_service_t usb_interface = IOIteratorNext(iter);
256 // We need to make an InterfaceInterface to communicate with the device
257 // endpoint. This is the same process as earlier: first make a
258 // PluginInterface from the io_service then make the InterfaceInterface from
260 IOCFPlugInInterface **plugin_interface;
261 kr = IOCreatePlugInInterfaceForService(usb_interface,
262 kIOUSBInterfaceUserClientTypeID,
263 kIOCFPlugInInterfaceID,
266 if (kr != KERN_SUCCESS || !plugin_interface)
268 base::mac::ScopedIOPluginInterface<IOCFPlugInInterface> interface_ref(
271 // Release the USB interface, and any subsequent interfaces returned by the
272 // iterator. (There shouldn't be any, but in case a future device does
273 // contain more interfaces, this will serve to avoid memory leaks.)
275 IOObjectRelease(usb_interface);
276 } while ((usb_interface = IOIteratorNext(iter)));
278 // Actually create the interface.
279 res = (*plugin_interface)->QueryInterface(
281 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID300),
282 (LPVOID *)&interface_);
284 if (!SUCCEEDED(res) || !interface_)
287 // Actually open the interface.
288 kr = (*interface_)->USBInterfaceOpen(interface_);
289 if (kr != KERN_SUCCESS)
291 interface_is_open_ = true;
293 CFRunLoopSourceRef source_ref;
294 kr = (*interface_)->CreateInterfaceAsyncEventSource(interface_, &source_ref);
295 if (kr != KERN_SUCCESS || !source_ref)
297 source_.reset(source_ref);
298 CFRunLoopAddSource(CFRunLoopGetCurrent(), source_, kCFRunLoopDefaultMode);
300 // The interface should have two pipes. Pipe 1 with direction kUSBIn and pipe
301 // 2 with direction kUSBOut. Both pipes should have type kUSBInterrupt.
303 kr = (*interface_)->GetNumEndpoints(interface_, &num_endpoints);
304 if (kr != KERN_SUCCESS || num_endpoints < 2)
307 for (int i = 1; i <= 2; i++) {
311 uint16 max_packet_size;
314 kr = (*interface_)->GetPipeProperties(interface_,
321 if (kr != KERN_SUCCESS || transfer_type != kUSBInterrupt)
323 if (i == kReadEndpoint) {
324 if (direction != kUSBIn)
326 if (max_packet_size > 32)
328 read_buffer_.reset(new uint8[max_packet_size]);
329 read_buffer_size_ = max_packet_size;
331 } else if (i == kControlEndpoint) {
332 if (direction != kUSBOut)
337 // The location ID is unique per controller, and can be used to track
338 // controllers through reconnections (though if a controller is detached from
339 // one USB hub and attached to another, the location ID will change).
340 kr = (*device_)->GetLocationID(device_, &location_id_);
341 if (kr != KERN_SUCCESS)
347 void XboxController::SetLEDPattern(LEDPattern pattern) {
348 led_pattern_ = pattern;
349 const UInt8 length = 3;
351 // This buffer will be released in WriteComplete when WritePipeAsync
353 UInt8* buffer = new UInt8[length];
354 buffer[0] = static_cast<UInt8>(CONTROL_MESSAGE_SET_LED);
356 buffer[2] = static_cast<UInt8>(pattern);
357 kern_return_t kr = (*interface_)->WritePipeAsync(interface_,
363 if (kr != KERN_SUCCESS) {
370 int XboxController::GetVendorId() const {
371 return kVendorMicrosoft;
374 int XboxController::GetProductId() const {
375 return kProduct360Controller;
378 void XboxController::WriteComplete(void* context, IOReturn result, void* arg0) {
379 UInt8* buffer = static_cast<UInt8*>(context);
382 // Ignoring any errors sending data, because they will usually only occur
383 // when the device is disconnected, in which case it really doesn't matter if
384 // the data got to the controller or not.
385 if (result != kIOReturnSuccess)
389 void XboxController::GotData(void* context, IOReturn result, void* arg0) {
390 size_t bytes_read = reinterpret_cast<size_t>(arg0);
391 XboxController* controller = static_cast<XboxController*>(context);
393 if (result != kIOReturnSuccess) {
394 // This will happen if the device was disconnected. The gamepad has
395 // probably been destroyed by a meteorite.
396 controller->IOError();
400 controller->ProcessPacket(bytes_read);
402 // Queue up another read.
403 controller->QueueRead();
406 void XboxController::ProcessPacket(size_t length) {
407 if (length < 2) return;
408 DCHECK(length <= read_buffer_size_);
409 if (length > read_buffer_size_) {
413 uint8* buffer = read_buffer_.get();
415 if (buffer[1] != length)
416 // Length in packet doesn't match length reported by USB.
419 uint8 type = buffer[0];
423 case STATUS_MESSAGE_BUTTONS: {
424 if (length != sizeof(ButtonData))
426 ButtonData* data = reinterpret_cast<ButtonData*>(buffer);
427 Data normalized_data;
428 NormalizeButtonData(*data, &normalized_data);
429 delegate_->XboxControllerGotData(this, normalized_data);
432 case STATUS_MESSAGE_LED:
435 // The controller sends one of these messages every time the LED pattern
436 // is set, as well as once when it is plugged in.
437 if (led_pattern_ == LED_NUM_PATTERNS && buffer[0] < LED_NUM_PATTERNS)
438 led_pattern_ = static_cast<LEDPattern>(buffer[0]);
441 // Unknown packet: ignore!
446 void XboxController::QueueRead() {
447 kern_return_t kr = (*interface_)->ReadPipeAsync(interface_,
453 if (kr != KERN_SUCCESS)
457 void XboxController::IOError() {
458 delegate_->XboxControllerError(this);
461 //-----------------------------------------------------------------------------
463 XboxDataFetcher::XboxDataFetcher(Delegate* delegate)
464 : delegate_(delegate),
470 XboxDataFetcher::~XboxDataFetcher() {
471 while (!controllers_.empty()) {
472 RemoveController(*controllers_.begin());
474 UnregisterFromNotifications();
477 void XboxDataFetcher::DeviceAdded(void* context, io_iterator_t iterator) {
479 XboxDataFetcher* fetcher = static_cast<XboxDataFetcher*>(context);
481 while ((ref = IOIteratorNext(iterator))) {
482 base::mac::ScopedIOObject<io_service_t> scoped_ref(ref);
483 XboxController* controller = new XboxController(fetcher);
484 if (controller->OpenDevice(ref)) {
485 fetcher->AddController(controller);
492 void XboxDataFetcher::DeviceRemoved(void* context, io_iterator_t iterator) {
494 XboxDataFetcher* fetcher = static_cast<XboxDataFetcher*>(context);
496 while ((ref = IOIteratorNext(iterator))) {
497 base::mac::ScopedIOObject<io_service_t> scoped_ref(ref);
498 base::ScopedCFTypeRef<CFNumberRef> number(
499 base::mac::CFCastStrict<CFNumberRef>(
500 IORegistryEntryCreateCFProperty(ref,
501 CFSTR(kUSBDevicePropertyLocationID),
504 UInt32 location_id = 0;
505 CFNumberGetValue(number, kCFNumberSInt32Type, &location_id);
506 fetcher->RemoveControllerByLocationID(location_id);
510 bool XboxDataFetcher::RegisterForNotifications() {
513 base::ScopedCFTypeRef<CFNumberRef> vendor_cf(CFNumberCreate(
514 kCFAllocatorDefault, kCFNumberSInt32Type, &kVendorMicrosoft));
515 base::ScopedCFTypeRef<CFNumberRef> product_cf(CFNumberCreate(
516 kCFAllocatorDefault, kCFNumberSInt32Type, &kProduct360Controller));
517 base::ScopedCFTypeRef<CFMutableDictionaryRef> matching_dict(
518 IOServiceMatching(kIOUSBDeviceClassName));
521 CFDictionarySetValue(matching_dict, CFSTR(kUSBVendorID), vendor_cf);
522 CFDictionarySetValue(matching_dict, CFSTR(kUSBProductID), product_cf);
523 port_ = IONotificationPortCreate(kIOMasterPortDefault);
526 source_ = IONotificationPortGetRunLoopSource(port_);
529 CFRunLoopAddSource(CFRunLoopGetCurrent(), source_, kCFRunLoopDefaultMode);
533 // IOServiceAddMatchingNotification() releases the dictionary when it's done.
534 // Retain it before each call to IOServiceAddMatchingNotification to keep
536 CFRetain(matching_dict);
537 io_iterator_t device_added_iter;
539 ret = IOServiceAddMatchingNotification(port_,
540 kIOFirstMatchNotification,
545 device_added_iter_.reset(device_added_iter);
546 if (ret != kIOReturnSuccess) {
547 LOG(ERROR) << "Error listening for Xbox controller add events: " << ret;
550 DeviceAdded(this, device_added_iter_.get());
552 CFRetain(matching_dict);
553 io_iterator_t device_removed_iter;
554 ret = IOServiceAddMatchingNotification(port_,
555 kIOTerminatedNotification,
559 &device_removed_iter);
560 device_removed_iter_.reset(device_removed_iter);
561 if (ret != kIOReturnSuccess) {
562 LOG(ERROR) << "Error listening for Xbox controller remove events: " << ret;
565 DeviceRemoved(this, device_removed_iter_.get());
569 void XboxDataFetcher::UnregisterFromNotifications() {
574 CFRunLoopSourceInvalidate(source_);
576 IONotificationPortDestroy(port_);
580 XboxController* XboxDataFetcher::ControllerForLocation(UInt32 location_id) {
581 for (std::set<XboxController*>::iterator i = controllers_.begin();
582 i != controllers_.end();
584 if ((*i)->location_id() == location_id)
590 void XboxDataFetcher::AddController(XboxController* controller) {
591 DCHECK(!ControllerForLocation(controller->location_id()))
592 << "Controller with location ID " << controller->location_id()
593 << " already exists in the set of controllers.";
594 controllers_.insert(controller);
595 delegate_->XboxDeviceAdd(controller);
598 void XboxDataFetcher::RemoveController(XboxController* controller) {
599 delegate_->XboxDeviceRemove(controller);
600 controllers_.erase(controller);
604 void XboxDataFetcher::RemoveControllerByLocationID(uint32 location_id) {
605 XboxController* controller = NULL;
606 for (std::set<XboxController*>::iterator i = controllers_.begin();
607 i != controllers_.end();
609 if ((*i)->location_id() == location_id) {
615 RemoveController(controller);
618 void XboxDataFetcher::XboxControllerGotData(XboxController* controller,
619 const XboxController::Data& data) {
620 delegate_->XboxValueChanged(controller, data);
623 void XboxDataFetcher::XboxControllerError(XboxController* controller) {
624 RemoveController(controller);