Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1385)

Side by Side Diff: content/browser/gamepad/xbox_data_fetcher_mac.cc

Issue 14328036: Implement support for USB Xbox360 controllers without a driver on Mac. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: . Created 7 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(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 "content/browser/gamepad/xbox_data_fetcher_mac.h"
6
7 #include <CoreFoundation/CoreFoundation.h>
8 #include <IOKit/IOKitLib.h>
9 #include <IOKit/IOCFPlugIn.h>
Avi (use Gerrit) 2013/04/22 21:00:51 alphabetize
jeremya 2013/04/23 04:38:25 Done.
10 #include <IOKit/usb/IOUSBLib.h>
11 #include <IOKit/usb/USB.h>
12
13 #include "base/logging.h"
14 #include "base/mac/scoped_cftyperef.h"
15
16 namespace {
17 const int32 kVendorMicrosoft = 0x045e;
18 const int32 kProduct360Controller = 0x028e;
19
20 const int kReadEndpoint = 1;
21 const int kControlEndpoint = 2;
22
23 #pragma pack(push, 1)
24 struct ButtonData {
25 bool dpad_up : 1;
26 bool dpad_down : 1;
27 bool dpad_left : 1;
28 bool dpad_right : 1;
29
30 bool start : 1;
31 bool back : 1;
32 bool stick_left_click : 1;
33 bool stick_right_click : 1;
34
35 bool bumper_left : 1;
36 bool bumper_right : 1;
37 bool guide : 1;
38 bool dummy1 : 1; // Always 0.
39
40 bool a : 1;
41 bool b : 1;
42 bool x : 1;
43 bool y : 1;
44
45 uint8 trigger_left;
46 uint8 trigger_right;
47
48 int16 stick_left_x;
49 int16 stick_left_y;
50 int16 stick_right_x;
51 int16 stick_right_y;
52
53 // Always 0.
54 uint32 dummy2;
55 uint16 dummy3;
56 };
57 #pragma pack(pop)
58
59 COMPILE_ASSERT(sizeof(ButtonData) == 0x12, xbox_button_data_wrong_size);
60
61 enum {
62 CONTROL_MESSAGE_SET_RUMBLE = 0,
63 CONTROL_MESSAGE_SET_LED = 1,
64 };
65
66 // From MSDN:
67 // http://msdn.microsoft.com/en-us/library/windows/desktop/ee417001(v=vs.85).asp x#dead_zone
68 const int16 kLeftThumbDeadzone = 7849;
69 const int16 kRightThumbDeadzone = 8689;
70 const uint8 kTriggerDeadzone = 30;
71
72 void NormalizeAxis(int16 x,
73 int16 y,
74 int16 deadzone,
75 float* x_out,
76 float* y_out) {
77 float x_val = (float)x;
78 float y_val = (float)y;
79
80 // Determine how far the stick is pushed.
81 float real_magnitude = sqrtf(x_val * x_val + y_val * y_val);
82
83 // Check if the controller is outside a circular dead zone.
84 if (real_magnitude > deadzone) {
85 // Clip the magnitude at its expected maximum value.
86 float magnitude = real_magnitude > 32767 ? 32767 : real_magnitude;
87
88 // Adjust magnitude relative to the end of the dead zone.
89 magnitude -= deadzone;
90
91 // Normalize the magnitude with respect to its expected range giving a
92 // magnitude value of 0.0 to 1.0
93 float ratio = (magnitude / (32767 - deadzone)) / real_magnitude;
94
95 // Y is negated because xbox controllers have an opposite sign from
96 // the 'standard controller' recommendations.
97 *x_out = x_val * ratio;
98 *y_out = -y_val * ratio;
99 } else {
100 // If the controller is in the deadzone zero out the magnitude.
101 *x_out = *y_out = 0.0f;
102 }
103 }
104
105 static float NormalizeTrigger(uint8 value) {
106 return value < kTriggerDeadzone ? 0 :
107 (float)(value - kTriggerDeadzone) / (kuint8max - kTriggerDeadzone);
108 }
109
110 void NormalizeButtonData(const ButtonData& data,
111 XboxController::Data* normalized_data) {
112 normalized_data->buttons[0] = data.a ? 1.f : 0.f;
113 normalized_data->buttons[1] = data.b ? 1.f : 0.f;
114 normalized_data->buttons[2] = data.x ? 1.f : 0.f;
115 normalized_data->buttons[3] = data.y ? 1.f : 0.f;
116 normalized_data->buttons[4] = data.bumper_left ? 1.f : 0.f;
117 normalized_data->buttons[5] = data.bumper_right ? 1.f : 0.f;
118 normalized_data->buttons[6] = NormalizeTrigger(data.trigger_left);
119 normalized_data->buttons[7] = NormalizeTrigger(data.trigger_right);
120 normalized_data->buttons[8] = data.back ? 1.f : 0.f;
121 normalized_data->buttons[9] = data.start ? 1.f : 0.f;
122 normalized_data->buttons[10] = data.stick_left_click ? 1.f : 0.f;
123 normalized_data->buttons[11] = data.stick_right_click ? 1.f : 0.f;
124 normalized_data->buttons[12] = data.dpad_up ? 1.f : 0.f;
125 normalized_data->buttons[13] = data.dpad_down ? 1.f : 0.f;
126 normalized_data->buttons[14] = data.dpad_left ? 1.f : 0.f;
127 normalized_data->buttons[15] = data.dpad_right ? 1.f : 0.f;
128 normalized_data->buttons[16] = data.guide ? 1.f : 0.f;
129 NormalizeAxis(data.stick_left_x,
130 data.stick_left_y,
131 kLeftThumbDeadzone,
132 &normalized_data->axes[0],
133 &normalized_data->axes[1]);
134 NormalizeAxis(data.stick_right_x,
135 data.stick_right_y,
136 kRightThumbDeadzone,
137 &normalized_data->axes[2],
138 &normalized_data->axes[3]);
139 }
140 } // namespace
141
142 XboxController::XboxController(Delegate* delegate)
143 : device_(NULL),
144 interface_(NULL),
145 device_is_open_(false),
146 interface_is_open_(false),
147 source_(NULL),
148 read_buffer_size_(0),
149 led_pattern_(LED_NUM_PATTERNS),
150 location_id_(0),
151 delegate_(delegate) {
152 }
153
154 XboxController::~XboxController() {
155 if (source_)
156 CFRunLoopSourceInvalidate(source_);
157 if (interface_) {
158 if (interface_is_open_)
159 (*interface_)->USBInterfaceClose(interface_);
160 (*interface_)->Release(interface_);
161 }
162 if (device_) {
163 if (device_is_open_)
164 (*device_)->USBDeviceClose(device_);
165 (*device_)->Release(device_);
166 }
167 }
168
169 bool XboxController::OpenDevice(io_service_t service) {
170 kern_return_t kr;
171 HRESULT res;
172
173 IOCFPlugInInterface **plugin;
174 SInt32 score; // Unused, but required for IOCreatePlugInInterfaceForService.
175 kr = IOCreatePlugInInterfaceForService(service,
176 kIOUSBDeviceUserClientTypeID,
177 kIOCFPlugInInterfaceID,
178 &plugin,
179 &score);
180 IOObjectRelease(service);
Avi (use Gerrit) 2013/04/22 21:00:51 If you're consuming the service, you may want to n
jeremya 2013/04/23 04:38:25 Oops, looks like this was actually being double-re
181 service = 0;
182 if (kr != KERN_SUCCESS)
183 return false;
184
185 // Use IOUSBDeviceStruct320 for support on MacOS 10.6.
Avi (use Gerrit) 2013/04/22 21:00:51 I don't understand your comment here. "For support
jeremya 2013/04/23 04:38:25 There are various versions of the IOUSBDeviceStruc
186 res = (*plugin)->QueryInterface(
187 plugin,
188 CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID320),
189 (LPVOID *)&device_);
190 (*plugin)->Release(plugin);
191 plugin = NULL;
192 if (res || !device_)
193 return false;
194
195 // Open the device and configure it.
196 kr = (*device_)->USBDeviceOpen(device_);
197 if (kr != KERN_SUCCESS)
198 return false;
199 device_is_open_ = true;
200
201 // Xbox controllers have one configuration option which has configuration
202 // value 1. Try to set it and fail out if it couldn't be configured.
203 IOUSBConfigurationDescriptorPtr config_desc;
204 kr = (*device_)->GetConfigurationDescriptorPtr(device_, 0, &config_desc);
205 if (kr != KERN_SUCCESS)
206 return false;
207 kr = (*device_)->SetConfiguration(device_, config_desc->bConfigurationValue);
208 if (kr != KERN_SUCCESS)
209 return false;
210
211 // The device has 4 interfaces. They are as follows:
212 // Protocol 1:
213 // - Endpoint 1 (in) : Controller events, including button presses.
214 // - Endpoint 2 (out): Rumble pack and LED control
215 // Protocol 2 has a single endpoint to read from a connected ChatPad device.
216 // Protocol 3 is used by a connected headset device.
217 // The device also has an interface on subclass 253, protocol 10 with no
218 // endpoints. It is unused.
219 //
220 // We don't currently support the ChatPad or headset, so protocol 1 is the
221 // only protocol we care about.
222 //
223 // For more detail, see https://github.com/Grumbel/xboxdrv/blob/master/PROTOCO L
224 IOUSBFindInterfaceRequest request;
225 request.bInterfaceClass = 255;
226 request.bInterfaceSubClass = 93;
227 request.bInterfaceProtocol = 1;
228 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
229 io_iterator_t iter;
230 kr = (*device_)->CreateInterfaceIterator(device_, &request, &iter);
231 if (kr != KERN_SUCCESS)
232 return false;
233
234 // There should be exactly one usb interface which matches the requested
235 // settings.
236 io_service_t usb_interface = IOIteratorNext(iter);
237 if (!usb_interface)
238 return false;
239
240 // We need to make an InterfaceInterface to communicate with the device
241 // endpoint. This is the same process as earlier: first make a
242 // PluginInterface from the io_service then make the InterfaceInterface from
243 // that.
244 IOCFPlugInInterface **plugin_interface;
245 kr = IOCreatePlugInInterfaceForService(usb_interface,
246 kIOUSBInterfaceUserClientTypeID,
247 kIOCFPlugInInterfaceID,
248 &plugin_interface,
249 &score);
250 if (kr != KERN_SUCCESS || !plugin_interface)
251 return false;
252
253 // Release the usb interface, and any subsequent interfaces returned by the
254 // iterator. (There shouldn't be any, but in case a future device does
255 // contain more interfaces, this will serve to avoid memory leaks.)
256 do {
257 IOObjectRelease(usb_interface);
258 } while ((usb_interface = IOIteratorNext(iter)));
259
260 // Actually create the interface.
261 kr = (*plugin_interface)->QueryInterface(
262 plugin_interface,
263 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID300),
264 (LPVOID *)&interface_);
265
266 (*plugin_interface)->Release(plugin_interface);
267
268 if (kr != KERN_SUCCESS || !interface_)
269 return false;
270
271 // Actually open the interface.
272 kr = (*interface_)->USBInterfaceOpen(interface_);
273 if (kr != KERN_SUCCESS)
274 return false;
275 interface_is_open_ = true;
276
277 kr = (*interface_)->CreateInterfaceAsyncEventSource(interface_, &source_);
278 if (kr != KERN_SUCCESS || !source_)
279 return false;
280 CFRunLoopAddSource(CFRunLoopGetMain(), source_, kCFRunLoopDefaultMode);
281 // The CFRunLoop retains the source.
282 CFRelease(source_);
283
284 // The interface should have two pipes. Pipe 1 with direction kUSBIn and pipe
285 // 2 with direction kUSBOut. Both pipes should have type kUSBInterrupt.
286 uint8 num_endpoints;
287 kr = (*interface_)->GetNumEndpoints(interface_, &num_endpoints);
288 if (kr != KERN_SUCCESS || num_endpoints < 2)
289 return false;
290
291 for (int i = 1; i <= num_endpoints; i++) {
292 uint8 direction;
293 uint8 number;
294 uint8 transfer_type;
295 uint16 max_packet_size;
296 uint8 interval;
297
298 kr = (*interface_)->GetPipeProperties(interface_,
299 i,
300 &direction,
301 &number,
302 &transfer_type,
303 &max_packet_size,
304 &interval);
305 if (kr != KERN_SUCCESS || transfer_type != kUSBInterrupt)
306 return false;
307 if (i == kReadEndpoint) {
308 if (direction != kUSBIn)
309 return false;
310 if (max_packet_size > 32)
311 return false;
312 read_buffer_.reset(new uint8[max_packet_size]);
313 read_buffer_size_ = max_packet_size;
314 QueueRead();
315 } else if (i == kControlEndpoint) {
316 if (direction != kUSBOut)
317 return false;
318 }
319 }
320
321 // If its useful, the deviceId can be used to track controllers through
322 // reconnections.
323 kr = (*device_)->GetLocationID(device_, &location_id_);
324 if (kr != KERN_SUCCESS)
325 return false;
326
327 return true;
328 }
329
330 void XboxController::SetLEDPattern(LEDPattern pattern) {
331 led_pattern_ = pattern;
332 const UInt8 length = 3;
333 UInt8* buffer = new UInt8[length];
334 buffer[0] = (UInt8)CONTROL_MESSAGE_SET_LED;
335 buffer[1] = length;
336 buffer[2] = (UInt8)pattern;
337 kern_return_t kr = (*interface_)->WritePipeAsync(interface_,
338 kControlEndpoint,
339 buffer,
340 (UInt32)length,
341 WriteComplete,
342 buffer);
343 if (kr != KERN_SUCCESS) {
344 IOError();
345 return;
346 }
347 }
348
349 void XboxController::WriteComplete(void* context, IOReturn result, void* arg0) {
350 // Ignoring any errors sending data, because they will usually only occur
351 // when the device is disconnected, in which case it really doesn't matter if
352 // the data got to the controller or not.
353 if (result != KERN_SUCCESS)
354 return;
355
356 UInt8* buffer = (UInt8*)context;
357 delete[] buffer;
358 }
359
360 void XboxController::GotData(void* context, IOReturn result, void* arg0) {
361 uint32 bytesRead = (uint32)arg0;
362 XboxController* controller = static_cast<XboxController*>(context);
363
364 if (result != kIOReturnSuccess) {
365 // This will happen if the device was disconnected. The gamepad has
366 // probably been destroyed by a meteorite.
367 controller->IOError();
368 return;
369 }
370
371 controller->ProcessPacket(bytesRead);
372
373 // Queue up another read.
374 controller->QueueRead();
375 }
376
377 void XboxController::ProcessPacket(uint32 length) {
378 if (length < 3) return;
379 DCHECK(length <= read_buffer_size_);
380 if (length > read_buffer_size_) {
381 IOError();
382 return;
383 }
384 uint8* buffer = read_buffer_.get();
385
386 if (buffer[1] != length)
387 // Length in packet doesn't match length reported by USB.
388 return;
389
390 uint8 type = buffer[0];
391 buffer += 2;
392 length -= 2;
393 switch (type) {
394 case STATUS_MESSAGE_BUTTONS: {
395 if (length != sizeof(ButtonData))
396 return;
397 ButtonData data;
398 memcpy(&data, buffer, sizeof(data));
399 Data normalized_data;
400 NormalizeButtonData(data, &normalized_data);
401 delegate_->XboxControllerGotData(this, normalized_data);
402 break;
403 }
404 case STATUS_MESSAGE_LED:
405 // The controller sends one of these messages every time the LED pattern
406 // is set, as well as once when it is plugged in.
407 if (led_pattern_ == LED_NUM_PATTERNS && buffer[0] < LED_NUM_PATTERNS)
408 led_pattern_ = (LEDPattern)buffer[0];
409 break;
410 default:
411 // Unknown packet: ignore!
412 break;
413 }
414 }
415
416 void XboxController::QueueRead() {
417 kern_return_t kr = (*interface_)->ReadPipeAsync(interface_,
418 kReadEndpoint,
419 read_buffer_.get(),
420 read_buffer_size_,
421 GotData,
422 this);
423 if (kr != KERN_SUCCESS)
424 IOError();
425 }
426
427 void XboxController::IOError() {
428 delegate_->XboxControllerError(this);
429 }
430
431 //-----------------------------------------------------------------------------
432
433 XboxDataFetcher::XboxDataFetcher(Delegate* delegate)
434 : delegate_(delegate),
435 listening_(false),
436 port_(NULL),
437 source_(NULL),
438 device_added_iter_(0),
439 device_removed_iter_(0) {
440 }
441
442 XboxDataFetcher::~XboxDataFetcher() {
443 while (!controllers_.empty()) {
444 RemoveController(*controllers_.begin());
445 }
446 UnregisterFromNotifications();
447 }
448
449 void XboxDataFetcher::DeviceAdded(void* context, io_iterator_t iterator) {
450 DCHECK(context);
451 XboxDataFetcher* fetcher = static_cast<XboxDataFetcher*>(context);
452 io_service_t ref;
453 while ((ref = IOIteratorNext(iterator))) {
454 XboxController* controller = new XboxController(fetcher);
455 if (controller->OpenDevice(ref)) {
456 fetcher->AddController(controller);
457 } else {
458 delete controller;
459 }
460 IOObjectRelease(ref);
Avi (use Gerrit) 2013/04/22 21:00:51 Huh? I thought OpenDevice consumed the ref... bas
jeremya 2013/04/23 04:38:25 Right you are :) I added the releasing afterwards,
461 }
462 }
463
464 void XboxDataFetcher::DeviceRemoved(void* context, io_iterator_t iterator) {
465 DCHECK(context);
466 XboxDataFetcher* fetcher = static_cast<XboxDataFetcher*>(context);
467 io_service_t ref;
468 while ((ref = IOIteratorNext(iterator))) {
469 base::mac::ScopedCFTypeRef<CFNumberRef> number(
470 (CFNumberRef)IORegistryEntryCreateCFProperty(
471 ref,
472 CFSTR(kUSBDevicePropertyLocationID),
473 kCFAllocatorDefault,
474 kNilOptions));
475 UInt32 location_id = 0;
476 CFNumberGetValue(number, kCFNumberSInt32Type, &location_id);
477 fetcher->RemoveControllerByLocationID(location_id);
478 IOObjectRelease(ref);
Avi (use Gerrit) 2013/04/22 21:00:51 ScopedIOObject
jeremya 2013/04/23 04:38:25 Done.
479 }
480 }
481
482 void XboxDataFetcher::RegisterForNotifications() {
483 if (listening_)
484 return;
485 base::mac::ScopedCFTypeRef<CFNumberRef> vendor_cf(
486 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type,
487 &kVendorMicrosoft));
488 base::mac::ScopedCFTypeRef<CFNumberRef> product_cf(
489 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type,
490 &kProduct360Controller));
491 base::mac::ScopedCFTypeRef<CFMutableDictionaryRef> matching_dict(
492 IOServiceMatching(kIOUSBDeviceClassName));
493 if (!matching_dict)
494 return;
495 CFDictionarySetValue(matching_dict, CFSTR(kUSBVendorID), vendor_cf);
496 CFDictionarySetValue(matching_dict, CFSTR(kUSBProductID), product_cf);
497 port_ = IONotificationPortCreate(kIOMasterPortDefault);
498 if (!port_)
499 return;
500 source_ = IONotificationPortGetRunLoopSource(port_);
501 if (!source_)
502 return;
503 CFRunLoopAddSource(CFRunLoopGetMain(), source_, kCFRunLoopDefaultMode);
504 CFRelease(source_);
505
506 listening_ = true;
507
508 IOReturn ret;
509
510 // IOServiceAddMatchingNotification() releases the dictionary when it's done.
511 // Retain it before each call to IOServiceAddMatchingNotification to keep
512 // things balanced.
513 CFRetain(matching_dict);
514 ret = IOServiceAddMatchingNotification(port_,
515 kIOFirstMatchNotification,
516 matching_dict,
517 DeviceAdded,
518 this,
519 &device_added_iter_);
520 if (ret != kIOReturnSuccess) {
521 LOG(ERROR) << "Error listening for Xbox controller add events: " << ret;
522 return;
523 }
524 DeviceAdded(this, device_added_iter_);
525
526 CFRetain(matching_dict);
527 ret = IOServiceAddMatchingNotification(port_,
528 kIOTerminatedNotification,
529 matching_dict,
530 DeviceRemoved,
531 this,
532 &device_removed_iter_);
533 if (ret != kIOReturnSuccess) {
534 LOG(ERROR) << "Error listening for Xbox controller remove events: " << ret;
535 return;
536 }
537 DeviceRemoved(this, device_removed_iter_);
538 }
539
540 void XboxDataFetcher::UnregisterFromNotifications() {
541 if (!listening_)
542 return;
543 listening_ = false;
544 if (source_)
545 CFRunLoopSourceInvalidate(source_);
546 source_ = NULL;
547 if (port_)
548 IONotificationPortDestroy(port_);
549 port_ = NULL;
550 if (device_added_iter_)
551 IOObjectRelease(device_added_iter_);
552 device_added_iter_ = 0;
553 if (device_removed_iter_)
554 IOObjectRelease(device_removed_iter_);
555 device_removed_iter_ = 0;
556 }
557
558 void XboxDataFetcher::AddController(XboxController* controller) {
559 controllers_.insert(controller);
560 delegate_->XboxDeviceAdd(controller);
561 }
562
563 void XboxDataFetcher::RemoveController(XboxController* controller) {
564 controllers_.erase(controller);
565 delegate_->XboxDeviceRemove(controller);
566 delete controller;
567 }
568
569 void XboxDataFetcher::RemoveControllerByLocationID(uint32 location_id) {
570 XboxController* controller = NULL;
571 for (std::set<XboxController*>::iterator i = controllers_.begin();
572 i != controllers_.end();
573 ++i) {
574 if ((*i)->location_id() == location_id) {
575 controller = *i;
576 break;
577 }
578 }
579 if (controller)
580 RemoveController(controller);
581 }
582
583 void XboxDataFetcher::XboxControllerGotData(XboxController* controller,
584 const XboxController::Data& data) {
585 delegate_->XboxValueChanged(controller, data);
586 }
587
588 void XboxDataFetcher::XboxControllerError(XboxController* controller) {
589 RemoveController(controller);
590 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698