OLD | NEW |
| (Empty) |
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. | |
4 | |
5 #include "device/gamepad/xbox_data_fetcher_mac.h" | |
6 | |
7 #include <algorithm> | |
8 #include <cmath> | |
9 #include <limits> | |
10 | |
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> | |
16 | |
17 #include "base/logging.h" | |
18 #include "base/mac/foundation_util.h" | |
19 | |
20 namespace { | |
21 const int kVendorMicrosoft = 0x045e; | |
22 const int kProductXbox360Controller = 0x028e; | |
23 const int kProductXboxOneController = 0x02d1; | |
24 | |
25 const int kXbox360ReadEndpoint = 1; | |
26 const int kXbox360ControlEndpoint = 2; | |
27 | |
28 const int kXboxOneReadEndpoint = 2; | |
29 const int kXboxOneControlEndpoint = 1; | |
30 | |
31 enum { | |
32 STATUS_MESSAGE_BUTTONS = 0, | |
33 STATUS_MESSAGE_LED = 1, | |
34 | |
35 // Apparently this message tells you if the rumble pack is disabled in the | |
36 // controller. If the rumble pack is disabled, vibration control messages | |
37 // have no effect. | |
38 STATUS_MESSAGE_RUMBLE = 3, | |
39 }; | |
40 | |
41 enum { | |
42 XBOX_ONE_STATUS_MESSAGE_BUTTONS = 0x20, | |
43 }; | |
44 | |
45 enum { | |
46 CONTROL_MESSAGE_SET_RUMBLE = 0, | |
47 CONTROL_MESSAGE_SET_LED = 1, | |
48 }; | |
49 | |
50 #pragma pack(push, 1) | |
51 struct Xbox360ButtonData { | |
52 bool dpad_up : 1; | |
53 bool dpad_down : 1; | |
54 bool dpad_left : 1; | |
55 bool dpad_right : 1; | |
56 | |
57 bool start : 1; | |
58 bool back : 1; | |
59 bool stick_left_click : 1; | |
60 bool stick_right_click : 1; | |
61 | |
62 bool bumper_left : 1; | |
63 bool bumper_right : 1; | |
64 bool guide : 1; | |
65 bool dummy1 : 1; // Always 0. | |
66 | |
67 bool a : 1; | |
68 bool b : 1; | |
69 bool x : 1; | |
70 bool y : 1; | |
71 | |
72 uint8_t trigger_left; | |
73 uint8_t trigger_right; | |
74 | |
75 int16_t stick_left_x; | |
76 int16_t stick_left_y; | |
77 int16_t stick_right_x; | |
78 int16_t stick_right_y; | |
79 | |
80 // Always 0. | |
81 uint32_t dummy2; | |
82 uint16_t dummy3; | |
83 }; | |
84 | |
85 struct XboxOneButtonData { | |
86 bool sync : 1; | |
87 bool dummy1 : 1; // Always 0. | |
88 bool start : 1; | |
89 bool back : 1; | |
90 | |
91 bool a : 1; | |
92 bool b : 1; | |
93 bool x : 1; | |
94 bool y : 1; | |
95 | |
96 bool dpad_up : 1; | |
97 bool dpad_down : 1; | |
98 bool dpad_left : 1; | |
99 bool dpad_right : 1; | |
100 | |
101 bool bumper_left : 1; | |
102 bool bumper_right : 1; | |
103 bool stick_left_click : 1; | |
104 bool stick_right_click : 1; | |
105 | |
106 uint16_t trigger_left; | |
107 uint16_t trigger_right; | |
108 | |
109 int16_t stick_left_x; | |
110 int16_t stick_left_y; | |
111 int16_t stick_right_x; | |
112 int16_t stick_right_y; | |
113 }; | |
114 #pragma pack(pop) | |
115 | |
116 static_assert(sizeof(Xbox360ButtonData) == 18, "xbox button data wrong size"); | |
117 static_assert(sizeof(XboxOneButtonData) == 14, "xbox button data wrong size"); | |
118 | |
119 // From MSDN: | |
120 // http://msdn.microsoft.com/en-us/library/windows/desktop/ee417001(v=vs.85).asp
x#dead_zone | |
121 const int16_t kLeftThumbDeadzone = 7849; | |
122 const int16_t kRightThumbDeadzone = 8689; | |
123 const uint8_t kXbox360TriggerDeadzone = 30; | |
124 const uint16_t kXboxOneTriggerMax = 1023; | |
125 const uint16_t kXboxOneTriggerDeadzone = 120; | |
126 | |
127 void NormalizeAxis(int16_t x, | |
128 int16_t y, | |
129 int16_t deadzone, | |
130 float* x_out, | |
131 float* y_out) { | |
132 float x_val = x; | |
133 float y_val = y; | |
134 | |
135 // Determine how far the stick is pushed. | |
136 float real_magnitude = std::sqrt(x_val * x_val + y_val * y_val); | |
137 | |
138 // Check if the controller is outside a circular dead zone. | |
139 if (real_magnitude > deadzone) { | |
140 // Clip the magnitude at its expected maximum value. | |
141 float magnitude = std::min(32767.0f, real_magnitude); | |
142 | |
143 // Adjust magnitude relative to the end of the dead zone. | |
144 magnitude -= deadzone; | |
145 | |
146 // Normalize the magnitude with respect to its expected range giving a | |
147 // magnitude value of 0.0 to 1.0 | |
148 float ratio = (magnitude / (32767 - deadzone)) / real_magnitude; | |
149 | |
150 // Y is negated because xbox controllers have an opposite sign from | |
151 // the 'standard controller' recommendations. | |
152 *x_out = x_val * ratio; | |
153 *y_out = -y_val * ratio; | |
154 } else { | |
155 // If the controller is in the deadzone zero out the magnitude. | |
156 *x_out = *y_out = 0.0f; | |
157 } | |
158 } | |
159 | |
160 float NormalizeTrigger(uint8_t value) { | |
161 return value < kXbox360TriggerDeadzone | |
162 ? 0 | |
163 : static_cast<float>(value - kXbox360TriggerDeadzone) / | |
164 (std::numeric_limits<uint8_t>::max() - | |
165 kXbox360TriggerDeadzone); | |
166 } | |
167 | |
168 float NormalizeXboxOneTrigger(uint16_t value) { | |
169 return value < kXboxOneTriggerDeadzone | |
170 ? 0 | |
171 : static_cast<float>(value - kXboxOneTriggerDeadzone) / | |
172 (kXboxOneTriggerMax - kXboxOneTriggerDeadzone); | |
173 } | |
174 | |
175 void NormalizeXbox360ButtonData(const Xbox360ButtonData& data, | |
176 XboxController::Data* normalized_data) { | |
177 normalized_data->buttons[0] = data.a; | |
178 normalized_data->buttons[1] = data.b; | |
179 normalized_data->buttons[2] = data.x; | |
180 normalized_data->buttons[3] = data.y; | |
181 normalized_data->buttons[4] = data.bumper_left; | |
182 normalized_data->buttons[5] = data.bumper_right; | |
183 normalized_data->buttons[6] = data.back; | |
184 normalized_data->buttons[7] = data.start; | |
185 normalized_data->buttons[8] = data.stick_left_click; | |
186 normalized_data->buttons[9] = data.stick_right_click; | |
187 normalized_data->buttons[10] = data.dpad_up; | |
188 normalized_data->buttons[11] = data.dpad_down; | |
189 normalized_data->buttons[12] = data.dpad_left; | |
190 normalized_data->buttons[13] = data.dpad_right; | |
191 normalized_data->buttons[14] = data.guide; | |
192 normalized_data->triggers[0] = NormalizeTrigger(data.trigger_left); | |
193 normalized_data->triggers[1] = NormalizeTrigger(data.trigger_right); | |
194 NormalizeAxis(data.stick_left_x, data.stick_left_y, kLeftThumbDeadzone, | |
195 &normalized_data->axes[0], &normalized_data->axes[1]); | |
196 NormalizeAxis(data.stick_right_x, data.stick_right_y, kRightThumbDeadzone, | |
197 &normalized_data->axes[2], &normalized_data->axes[3]); | |
198 } | |
199 | |
200 void NormalizeXboxOneButtonData(const XboxOneButtonData& data, | |
201 XboxController::Data* normalized_data) { | |
202 normalized_data->buttons[0] = data.a; | |
203 normalized_data->buttons[1] = data.b; | |
204 normalized_data->buttons[2] = data.x; | |
205 normalized_data->buttons[3] = data.y; | |
206 normalized_data->buttons[4] = data.bumper_left; | |
207 normalized_data->buttons[5] = data.bumper_right; | |
208 normalized_data->buttons[6] = data.back; | |
209 normalized_data->buttons[7] = data.start; | |
210 normalized_data->buttons[8] = data.stick_left_click; | |
211 normalized_data->buttons[9] = data.stick_right_click; | |
212 normalized_data->buttons[10] = data.dpad_up; | |
213 normalized_data->buttons[11] = data.dpad_down; | |
214 normalized_data->buttons[12] = data.dpad_left; | |
215 normalized_data->buttons[13] = data.dpad_right; | |
216 normalized_data->buttons[14] = data.sync; | |
217 normalized_data->triggers[0] = NormalizeXboxOneTrigger(data.trigger_left); | |
218 normalized_data->triggers[1] = NormalizeXboxOneTrigger(data.trigger_right); | |
219 NormalizeAxis(data.stick_left_x, data.stick_left_y, kLeftThumbDeadzone, | |
220 &normalized_data->axes[0], &normalized_data->axes[1]); | |
221 NormalizeAxis(data.stick_right_x, data.stick_right_y, kRightThumbDeadzone, | |
222 &normalized_data->axes[2], &normalized_data->axes[3]); | |
223 } | |
224 | |
225 } // namespace | |
226 | |
227 XboxController::XboxController(Delegate* delegate) | |
228 : device_(NULL), | |
229 interface_(NULL), | |
230 device_is_open_(false), | |
231 interface_is_open_(false), | |
232 read_buffer_size_(0), | |
233 led_pattern_(LED_NUM_PATTERNS), | |
234 location_id_(0), | |
235 delegate_(delegate), | |
236 controller_type_(UNKNOWN_CONTROLLER), | |
237 read_endpoint_(0), | |
238 control_endpoint_(0) {} | |
239 | |
240 XboxController::~XboxController() { | |
241 if (source_) | |
242 CFRunLoopSourceInvalidate(source_); | |
243 if (interface_ && interface_is_open_) | |
244 (*interface_)->USBInterfaceClose(interface_); | |
245 if (device_ && device_is_open_) | |
246 (*device_)->USBDeviceClose(device_); | |
247 } | |
248 | |
249 bool XboxController::OpenDevice(io_service_t service) { | |
250 IOCFPlugInInterface** plugin; | |
251 SInt32 score; // Unused, but required for IOCreatePlugInInterfaceForService. | |
252 kern_return_t kr = IOCreatePlugInInterfaceForService( | |
253 service, kIOUSBDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &plugin, | |
254 &score); | |
255 if (kr != KERN_SUCCESS) | |
256 return false; | |
257 base::mac::ScopedIOPluginInterface<IOCFPlugInInterface> plugin_ref(plugin); | |
258 | |
259 HRESULT res = (*plugin)->QueryInterface( | |
260 plugin, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID320), | |
261 (LPVOID*)&device_); | |
262 if (!SUCCEEDED(res) || !device_) | |
263 return false; | |
264 | |
265 UInt16 vendor_id; | |
266 kr = (*device_)->GetDeviceVendor(device_, &vendor_id); | |
267 if (kr != KERN_SUCCESS || vendor_id != kVendorMicrosoft) | |
268 return false; | |
269 | |
270 UInt16 product_id; | |
271 kr = (*device_)->GetDeviceProduct(device_, &product_id); | |
272 if (kr != KERN_SUCCESS) | |
273 return false; | |
274 | |
275 IOUSBFindInterfaceRequest request; | |
276 switch (product_id) { | |
277 case kProductXbox360Controller: | |
278 controller_type_ = XBOX_360_CONTROLLER; | |
279 read_endpoint_ = kXbox360ReadEndpoint; | |
280 control_endpoint_ = kXbox360ControlEndpoint; | |
281 request.bInterfaceClass = 255; | |
282 request.bInterfaceSubClass = 93; | |
283 request.bInterfaceProtocol = 1; | |
284 request.bAlternateSetting = kIOUSBFindInterfaceDontCare; | |
285 break; | |
286 case kProductXboxOneController: | |
287 controller_type_ = XBOX_ONE_CONTROLLER; | |
288 read_endpoint_ = kXboxOneReadEndpoint; | |
289 control_endpoint_ = kXboxOneControlEndpoint; | |
290 request.bInterfaceClass = 255; | |
291 request.bInterfaceSubClass = 71; | |
292 request.bInterfaceProtocol = 208; | |
293 request.bAlternateSetting = kIOUSBFindInterfaceDontCare; | |
294 break; | |
295 default: | |
296 return false; | |
297 } | |
298 | |
299 // Open the device and configure it. | |
300 kr = (*device_)->USBDeviceOpen(device_); | |
301 if (kr != KERN_SUCCESS) | |
302 return false; | |
303 device_is_open_ = true; | |
304 | |
305 // Xbox controllers have one configuration option which has configuration | |
306 // value 1. Try to set it and fail if it couldn't be configured. | |
307 IOUSBConfigurationDescriptorPtr config_desc; | |
308 kr = (*device_)->GetConfigurationDescriptorPtr(device_, 0, &config_desc); | |
309 if (kr != KERN_SUCCESS) | |
310 return false; | |
311 kr = (*device_)->SetConfiguration(device_, config_desc->bConfigurationValue); | |
312 if (kr != KERN_SUCCESS) | |
313 return false; | |
314 | |
315 // The device has 4 interfaces. They are as follows: | |
316 // Protocol 1: | |
317 // - Endpoint 1 (in) : Controller events, including button presses. | |
318 // - Endpoint 2 (out): Rumble pack and LED control | |
319 // Protocol 2 has a single endpoint to read from a connected ChatPad device. | |
320 // Protocol 3 is used by a connected headset device. | |
321 // The device also has an interface on subclass 253, protocol 10 with no | |
322 // endpoints. It is unused. | |
323 // | |
324 // We don't currently support the ChatPad or headset, so protocol 1 is the | |
325 // only protocol we care about. | |
326 // | |
327 // For more detail, see | |
328 // https://github.com/Grumbel/xboxdrv/blob/master/PROTOCOL | |
329 io_iterator_t iter; | |
330 kr = (*device_)->CreateInterfaceIterator(device_, &request, &iter); | |
331 if (kr != KERN_SUCCESS) | |
332 return false; | |
333 base::mac::ScopedIOObject<io_iterator_t> iter_ref(iter); | |
334 | |
335 // There should be exactly one USB interface which matches the requested | |
336 // settings. | |
337 io_service_t usb_interface = IOIteratorNext(iter); | |
338 if (!usb_interface) | |
339 return false; | |
340 | |
341 // We need to make an InterfaceInterface to communicate with the device | |
342 // endpoint. This is the same process as earlier: first make a | |
343 // PluginInterface from the io_service then make the InterfaceInterface from | |
344 // that. | |
345 IOCFPlugInInterface** plugin_interface; | |
346 kr = IOCreatePlugInInterfaceForService( | |
347 usb_interface, kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID, | |
348 &plugin_interface, &score); | |
349 if (kr != KERN_SUCCESS || !plugin_interface) | |
350 return false; | |
351 base::mac::ScopedIOPluginInterface<IOCFPlugInInterface> interface_ref( | |
352 plugin_interface); | |
353 | |
354 // Release the USB interface, and any subsequent interfaces returned by the | |
355 // iterator. (There shouldn't be any, but in case a future device does | |
356 // contain more interfaces, this will serve to avoid memory leaks.) | |
357 do { | |
358 IOObjectRelease(usb_interface); | |
359 } while ((usb_interface = IOIteratorNext(iter))); | |
360 | |
361 // Actually create the interface. | |
362 res = (*plugin_interface) | |
363 ->QueryInterface(plugin_interface, | |
364 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID300), | |
365 (LPVOID*)&interface_); | |
366 | |
367 if (!SUCCEEDED(res) || !interface_) | |
368 return false; | |
369 | |
370 // Actually open the interface. | |
371 kr = (*interface_)->USBInterfaceOpen(interface_); | |
372 if (kr != KERN_SUCCESS) | |
373 return false; | |
374 interface_is_open_ = true; | |
375 | |
376 CFRunLoopSourceRef source_ref; | |
377 kr = (*interface_)->CreateInterfaceAsyncEventSource(interface_, &source_ref); | |
378 if (kr != KERN_SUCCESS || !source_ref) | |
379 return false; | |
380 source_.reset(source_ref); | |
381 CFRunLoopAddSource(CFRunLoopGetCurrent(), source_, kCFRunLoopDefaultMode); | |
382 | |
383 // The interface should have two pipes. Pipe 1 with direction kUSBIn and pipe | |
384 // 2 with direction kUSBOut. Both pipes should have type kUSBInterrupt. | |
385 uint8_t num_endpoints; | |
386 kr = (*interface_)->GetNumEndpoints(interface_, &num_endpoints); | |
387 if (kr != KERN_SUCCESS || num_endpoints < 2) | |
388 return false; | |
389 | |
390 for (int i = 1; i <= 2; i++) { | |
391 uint8_t direction; | |
392 uint8_t number; | |
393 uint8_t transfer_type; | |
394 uint16_t max_packet_size; | |
395 uint8_t interval; | |
396 | |
397 kr = (*interface_) | |
398 ->GetPipeProperties(interface_, i, &direction, &number, | |
399 &transfer_type, &max_packet_size, &interval); | |
400 if (kr != KERN_SUCCESS || transfer_type != kUSBInterrupt) { | |
401 return false; | |
402 } | |
403 if (i == read_endpoint_) { | |
404 if (direction != kUSBIn) | |
405 return false; | |
406 read_buffer_.reset(new uint8_t[max_packet_size]); | |
407 read_buffer_size_ = max_packet_size; | |
408 QueueRead(); | |
409 } else if (i == control_endpoint_) { | |
410 if (direction != kUSBOut) | |
411 return false; | |
412 if (controller_type_ == XBOX_ONE_CONTROLLER) | |
413 WriteXboxOneInit(); | |
414 } | |
415 } | |
416 | |
417 // The location ID is unique per controller, and can be used to track | |
418 // controllers through reconnections (though if a controller is detached from | |
419 // one USB hub and attached to another, the location ID will change). | |
420 kr = (*device_)->GetLocationID(device_, &location_id_); | |
421 if (kr != KERN_SUCCESS) | |
422 return false; | |
423 | |
424 return true; | |
425 } | |
426 | |
427 void XboxController::SetLEDPattern(LEDPattern pattern) { | |
428 led_pattern_ = pattern; | |
429 const UInt8 length = 3; | |
430 | |
431 // This buffer will be released in WriteComplete when WritePipeAsync | |
432 // finishes. | |
433 UInt8* buffer = new UInt8[length]; | |
434 buffer[0] = static_cast<UInt8>(CONTROL_MESSAGE_SET_LED); | |
435 buffer[1] = length; | |
436 buffer[2] = static_cast<UInt8>(pattern); | |
437 kern_return_t kr = | |
438 (*interface_) | |
439 ->WritePipeAsync(interface_, control_endpoint_, buffer, | |
440 (UInt32)length, WriteComplete, buffer); | |
441 if (kr != KERN_SUCCESS) { | |
442 delete[] buffer; | |
443 IOError(); | |
444 return; | |
445 } | |
446 } | |
447 | |
448 int XboxController::GetVendorId() const { | |
449 return kVendorMicrosoft; | |
450 } | |
451 | |
452 int XboxController::GetProductId() const { | |
453 if (controller_type_ == XBOX_360_CONTROLLER) | |
454 return kProductXbox360Controller; | |
455 else | |
456 return kProductXboxOneController; | |
457 } | |
458 | |
459 XboxController::ControllerType XboxController::GetControllerType() const { | |
460 return controller_type_; | |
461 } | |
462 | |
463 void XboxController::WriteComplete(void* context, IOReturn result, void* arg0) { | |
464 UInt8* buffer = static_cast<UInt8*>(context); | |
465 delete[] buffer; | |
466 | |
467 // Ignoring any errors sending data, because they will usually only occur | |
468 // when the device is disconnected, in which case it really doesn't matter if | |
469 // the data got to the controller or not. | |
470 if (result != kIOReturnSuccess) | |
471 return; | |
472 } | |
473 | |
474 void XboxController::GotData(void* context, IOReturn result, void* arg0) { | |
475 size_t bytes_read = reinterpret_cast<size_t>(arg0); | |
476 XboxController* controller = static_cast<XboxController*>(context); | |
477 | |
478 if (result != kIOReturnSuccess) { | |
479 // This will happen if the device was disconnected. The gamepad has | |
480 // probably been destroyed by a meteorite. | |
481 controller->IOError(); | |
482 return; | |
483 } | |
484 | |
485 if (controller->GetControllerType() == XBOX_360_CONTROLLER) | |
486 controller->ProcessXbox360Packet(bytes_read); | |
487 else | |
488 controller->ProcessXboxOnePacket(bytes_read); | |
489 | |
490 // Queue up another read. | |
491 controller->QueueRead(); | |
492 } | |
493 | |
494 void XboxController::ProcessXbox360Packet(size_t length) { | |
495 if (length < 2) | |
496 return; | |
497 DCHECK(length <= read_buffer_size_); | |
498 if (length > read_buffer_size_) { | |
499 IOError(); | |
500 return; | |
501 } | |
502 uint8_t* buffer = read_buffer_.get(); | |
503 | |
504 if (buffer[1] != length) | |
505 // Length in packet doesn't match length reported by USB. | |
506 return; | |
507 | |
508 uint8_t type = buffer[0]; | |
509 buffer += 2; | |
510 length -= 2; | |
511 switch (type) { | |
512 case STATUS_MESSAGE_BUTTONS: { | |
513 if (length != sizeof(Xbox360ButtonData)) | |
514 return; | |
515 Xbox360ButtonData* data = reinterpret_cast<Xbox360ButtonData*>(buffer); | |
516 Data normalized_data; | |
517 NormalizeXbox360ButtonData(*data, &normalized_data); | |
518 delegate_->XboxControllerGotData(this, normalized_data); | |
519 break; | |
520 } | |
521 case STATUS_MESSAGE_LED: | |
522 if (length != 3) | |
523 return; | |
524 // The controller sends one of these messages every time the LED pattern | |
525 // is set, as well as once when it is plugged in. | |
526 if (led_pattern_ == LED_NUM_PATTERNS && buffer[0] < LED_NUM_PATTERNS) | |
527 led_pattern_ = static_cast<LEDPattern>(buffer[0]); | |
528 break; | |
529 default: | |
530 // Unknown packet: ignore! | |
531 break; | |
532 } | |
533 } | |
534 | |
535 void XboxController::ProcessXboxOnePacket(size_t length) { | |
536 if (length < 2) | |
537 return; | |
538 DCHECK(length <= read_buffer_size_); | |
539 if (length > read_buffer_size_) { | |
540 IOError(); | |
541 return; | |
542 } | |
543 uint8_t* buffer = read_buffer_.get(); | |
544 | |
545 uint8_t type = buffer[0]; | |
546 buffer += 4; | |
547 length -= 4; | |
548 switch (type) { | |
549 case XBOX_ONE_STATUS_MESSAGE_BUTTONS: { | |
550 if (length != sizeof(XboxOneButtonData)) | |
551 return; | |
552 XboxOneButtonData* data = reinterpret_cast<XboxOneButtonData*>(buffer); | |
553 Data normalized_data; | |
554 NormalizeXboxOneButtonData(*data, &normalized_data); | |
555 delegate_->XboxControllerGotData(this, normalized_data); | |
556 break; | |
557 } | |
558 default: | |
559 // Unknown packet: ignore! | |
560 break; | |
561 } | |
562 } | |
563 | |
564 void XboxController::QueueRead() { | |
565 kern_return_t kr = | |
566 (*interface_) | |
567 ->ReadPipeAsync(interface_, read_endpoint_, read_buffer_.get(), | |
568 read_buffer_size_, GotData, this); | |
569 if (kr != KERN_SUCCESS) | |
570 IOError(); | |
571 } | |
572 | |
573 void XboxController::IOError() { | |
574 delegate_->XboxControllerError(this); | |
575 } | |
576 | |
577 void XboxController::WriteXboxOneInit() { | |
578 const UInt8 length = 2; | |
579 | |
580 // This buffer will be released in WriteComplete when WritePipeAsync | |
581 // finishes. | |
582 UInt8* buffer = new UInt8[length]; | |
583 buffer[0] = 0x05; | |
584 buffer[1] = 0x20; | |
585 kern_return_t kr = | |
586 (*interface_) | |
587 ->WritePipeAsync(interface_, control_endpoint_, buffer, | |
588 (UInt32)length, WriteComplete, buffer); | |
589 if (kr != KERN_SUCCESS) { | |
590 delete[] buffer; | |
591 IOError(); | |
592 return; | |
593 } | |
594 } | |
595 | |
596 //----------------------------------------------------------------------------- | |
597 | |
598 XboxDataFetcher::XboxDataFetcher(Delegate* delegate) | |
599 : delegate_(delegate), listening_(false), source_(NULL), port_(NULL) {} | |
600 | |
601 XboxDataFetcher::~XboxDataFetcher() { | |
602 while (!controllers_.empty()) { | |
603 RemoveController(*controllers_.begin()); | |
604 } | |
605 UnregisterFromNotifications(); | |
606 } | |
607 | |
608 void XboxDataFetcher::DeviceAdded(void* context, io_iterator_t iterator) { | |
609 DCHECK(context); | |
610 XboxDataFetcher* fetcher = static_cast<XboxDataFetcher*>(context); | |
611 io_service_t ref; | |
612 while ((ref = IOIteratorNext(iterator))) { | |
613 base::mac::ScopedIOObject<io_service_t> scoped_ref(ref); | |
614 XboxController* controller = new XboxController(fetcher); | |
615 if (controller->OpenDevice(ref)) { | |
616 fetcher->AddController(controller); | |
617 } else { | |
618 delete controller; | |
619 } | |
620 } | |
621 } | |
622 | |
623 void XboxDataFetcher::DeviceRemoved(void* context, io_iterator_t iterator) { | |
624 DCHECK(context); | |
625 XboxDataFetcher* fetcher = static_cast<XboxDataFetcher*>(context); | |
626 io_service_t ref; | |
627 while ((ref = IOIteratorNext(iterator))) { | |
628 base::mac::ScopedIOObject<io_service_t> scoped_ref(ref); | |
629 base::ScopedCFTypeRef<CFNumberRef> number( | |
630 base::mac::CFCastStrict<CFNumberRef>(IORegistryEntryCreateCFProperty( | |
631 ref, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, | |
632 kNilOptions))); | |
633 UInt32 location_id = 0; | |
634 CFNumberGetValue(number, kCFNumberSInt32Type, &location_id); | |
635 fetcher->RemoveControllerByLocationID(location_id); | |
636 } | |
637 } | |
638 | |
639 bool XboxDataFetcher::RegisterForNotifications() { | |
640 if (listening_) | |
641 return true; | |
642 port_ = IONotificationPortCreate(kIOMasterPortDefault); | |
643 if (!port_) | |
644 return false; | |
645 source_ = IONotificationPortGetRunLoopSource(port_); | |
646 if (!source_) | |
647 return false; | |
648 CFRunLoopAddSource(CFRunLoopGetCurrent(), source_, kCFRunLoopDefaultMode); | |
649 | |
650 listening_ = true; | |
651 | |
652 if (!RegisterForDeviceNotifications( | |
653 kVendorMicrosoft, kProductXboxOneController, | |
654 &xbox_one_device_added_iter_, &xbox_one_device_removed_iter_)) | |
655 return false; | |
656 | |
657 if (!RegisterForDeviceNotifications( | |
658 kVendorMicrosoft, kProductXbox360Controller, | |
659 &xbox_360_device_added_iter_, &xbox_360_device_removed_iter_)) | |
660 return false; | |
661 | |
662 return true; | |
663 } | |
664 | |
665 bool XboxDataFetcher::RegisterForDeviceNotifications( | |
666 int vendor_id, | |
667 int product_id, | |
668 base::mac::ScopedIOObject<io_iterator_t>* added_iter, | |
669 base::mac::ScopedIOObject<io_iterator_t>* removed_iter) { | |
670 base::ScopedCFTypeRef<CFNumberRef> vendor_cf( | |
671 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &vendor_id)); | |
672 base::ScopedCFTypeRef<CFNumberRef> product_cf( | |
673 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &product_id)); | |
674 base::ScopedCFTypeRef<CFMutableDictionaryRef> matching_dict( | |
675 IOServiceMatching(kIOUSBDeviceClassName)); | |
676 if (!matching_dict) | |
677 return false; | |
678 CFDictionarySetValue(matching_dict, CFSTR(kUSBVendorID), vendor_cf); | |
679 CFDictionarySetValue(matching_dict, CFSTR(kUSBProductID), product_cf); | |
680 | |
681 // IOServiceAddMatchingNotification() releases the dictionary when it's done. | |
682 // Retain it before each call to IOServiceAddMatchingNotification to keep | |
683 // things balanced. | |
684 CFRetain(matching_dict); | |
685 io_iterator_t device_added_iter; | |
686 IOReturn ret; | |
687 ret = IOServiceAddMatchingNotification(port_, kIOFirstMatchNotification, | |
688 matching_dict, DeviceAdded, this, | |
689 &device_added_iter); | |
690 added_iter->reset(device_added_iter); | |
691 if (ret != kIOReturnSuccess) { | |
692 LOG(ERROR) << "Error listening for Xbox controller add events: " << ret; | |
693 return false; | |
694 } | |
695 DeviceAdded(this, added_iter->get()); | |
696 | |
697 CFRetain(matching_dict); | |
698 io_iterator_t device_removed_iter; | |
699 ret = IOServiceAddMatchingNotification(port_, kIOTerminatedNotification, | |
700 matching_dict, DeviceRemoved, this, | |
701 &device_removed_iter); | |
702 removed_iter->reset(device_removed_iter); | |
703 if (ret != kIOReturnSuccess) { | |
704 LOG(ERROR) << "Error listening for Xbox controller remove events: " << ret; | |
705 return false; | |
706 } | |
707 DeviceRemoved(this, removed_iter->get()); | |
708 return true; | |
709 } | |
710 | |
711 void XboxDataFetcher::UnregisterFromNotifications() { | |
712 if (!listening_) | |
713 return; | |
714 listening_ = false; | |
715 if (source_) | |
716 CFRunLoopSourceInvalidate(source_); | |
717 if (port_) | |
718 IONotificationPortDestroy(port_); | |
719 port_ = NULL; | |
720 } | |
721 | |
722 XboxController* XboxDataFetcher::ControllerForLocation(UInt32 location_id) { | |
723 for (std::set<XboxController*>::iterator i = controllers_.begin(); | |
724 i != controllers_.end(); ++i) { | |
725 if ((*i)->location_id() == location_id) | |
726 return *i; | |
727 } | |
728 return NULL; | |
729 } | |
730 | |
731 void XboxDataFetcher::AddController(XboxController* controller) { | |
732 DCHECK(!ControllerForLocation(controller->location_id())) | |
733 << "Controller with location ID " << controller->location_id() | |
734 << " already exists in the set of controllers."; | |
735 controllers_.insert(controller); | |
736 delegate_->XboxDeviceAdd(controller); | |
737 } | |
738 | |
739 void XboxDataFetcher::RemoveController(XboxController* controller) { | |
740 delegate_->XboxDeviceRemove(controller); | |
741 controllers_.erase(controller); | |
742 delete controller; | |
743 } | |
744 | |
745 void XboxDataFetcher::RemoveControllerByLocationID(uint32_t location_id) { | |
746 XboxController* controller = NULL; | |
747 for (std::set<XboxController*>::iterator i = controllers_.begin(); | |
748 i != controllers_.end(); ++i) { | |
749 if ((*i)->location_id() == location_id) { | |
750 controller = *i; | |
751 break; | |
752 } | |
753 } | |
754 if (controller) | |
755 RemoveController(controller); | |
756 } | |
757 | |
758 void XboxDataFetcher::XboxControllerGotData(XboxController* controller, | |
759 const XboxController::Data& data) { | |
760 delegate_->XboxValueChanged(controller, data); | |
761 } | |
762 | |
763 void XboxDataFetcher::XboxControllerError(XboxController* controller) { | |
764 RemoveController(controller); | |
765 } | |
OLD | NEW |