summaryrefslogtreecommitdiff
path: root/src/input_common/drivers/gc_adapter.cpp
diff options
context:
space:
mode:
authorGravatar Feng Chen2021-12-18 13:57:14 +0800
committerGravatar GitHub2021-12-18 13:57:14 +0800
commite49184e6069a9d791d2df3c1958f5c4b1187e124 (patch)
treeb776caf722e0be0e680f67b0ad0842628162ef1c /src/input_common/drivers/gc_adapter.cpp
parentImplement convert legacy to generic (diff)
parentMerge pull request #7570 from ameerj/favorites-expanded (diff)
downloadyuzu-e49184e6069a9d791d2df3c1958f5c4b1187e124.tar.gz
yuzu-e49184e6069a9d791d2df3c1958f5c4b1187e124.tar.xz
yuzu-e49184e6069a9d791d2df3c1958f5c4b1187e124.zip
Merge branch 'yuzu-emu:master' into convert_legacy
Diffstat (limited to 'src/input_common/drivers/gc_adapter.cpp')
-rw-r--r--src/input_common/drivers/gc_adapter.cpp527
1 files changed, 527 insertions, 0 deletions
diff --git a/src/input_common/drivers/gc_adapter.cpp b/src/input_common/drivers/gc_adapter.cpp
new file mode 100644
index 000000000..7ab4540a8
--- /dev/null
+++ b/src/input_common/drivers/gc_adapter.cpp
@@ -0,0 +1,527 @@
1// Copyright 2014 Dolphin Emulator Project
2// Licensed under GPLv2+
3// Refer to the license.txt file included.
4
5#include <fmt/format.h>
6#include <libusb.h>
7
8#include "common/logging/log.h"
9#include "common/param_package.h"
10#include "common/settings_input.h"
11#include "common/thread.h"
12#include "input_common/drivers/gc_adapter.h"
13
14namespace InputCommon {
15
16class LibUSBContext {
17public:
18 explicit LibUSBContext() {
19 init_result = libusb_init(&ctx);
20 }
21
22 ~LibUSBContext() {
23 libusb_exit(ctx);
24 }
25
26 LibUSBContext& operator=(const LibUSBContext&) = delete;
27 LibUSBContext(const LibUSBContext&) = delete;
28
29 LibUSBContext& operator=(LibUSBContext&&) noexcept = delete;
30 LibUSBContext(LibUSBContext&&) noexcept = delete;
31
32 [[nodiscard]] int InitResult() const noexcept {
33 return init_result;
34 }
35
36 [[nodiscard]] libusb_context* get() noexcept {
37 return ctx;
38 }
39
40private:
41 libusb_context* ctx;
42 int init_result{};
43};
44
45class LibUSBDeviceHandle {
46public:
47 explicit LibUSBDeviceHandle(libusb_context* ctx, uint16_t vid, uint16_t pid) noexcept {
48 handle = libusb_open_device_with_vid_pid(ctx, vid, pid);
49 }
50
51 ~LibUSBDeviceHandle() noexcept {
52 if (handle) {
53 libusb_release_interface(handle, 1);
54 libusb_close(handle);
55 }
56 }
57
58 LibUSBDeviceHandle& operator=(const LibUSBDeviceHandle&) = delete;
59 LibUSBDeviceHandle(const LibUSBDeviceHandle&) = delete;
60
61 LibUSBDeviceHandle& operator=(LibUSBDeviceHandle&&) noexcept = delete;
62 LibUSBDeviceHandle(LibUSBDeviceHandle&&) noexcept = delete;
63
64 [[nodiscard]] libusb_device_handle* get() noexcept {
65 return handle;
66 }
67
68private:
69 libusb_device_handle* handle{};
70};
71
72GCAdapter::GCAdapter(std::string input_engine_) : InputEngine(std::move(input_engine_)) {
73 if (usb_adapter_handle) {
74 return;
75 }
76 LOG_DEBUG(Input, "Initialization started");
77
78 libusb_ctx = std::make_unique<LibUSBContext>();
79 const int init_res = libusb_ctx->InitResult();
80 if (init_res == LIBUSB_SUCCESS) {
81 adapter_scan_thread =
82 std::jthread([this](std::stop_token stop_token) { AdapterScanThread(stop_token); });
83 } else {
84 LOG_ERROR(Input, "libusb could not be initialized. failed with error = {}", init_res);
85 }
86}
87
88GCAdapter::~GCAdapter() {
89 Reset();
90}
91
92void GCAdapter::AdapterInputThread(std::stop_token stop_token) {
93 LOG_DEBUG(Input, "Input thread started");
94 Common::SetCurrentThreadName("yuzu:input:GCAdapter");
95 s32 payload_size{};
96 AdapterPayload adapter_payload{};
97
98 adapter_scan_thread = {};
99
100 while (!stop_token.stop_requested()) {
101 libusb_interrupt_transfer(usb_adapter_handle->get(), input_endpoint, adapter_payload.data(),
102 static_cast<s32>(adapter_payload.size()), &payload_size, 16);
103 if (IsPayloadCorrect(adapter_payload, payload_size)) {
104 UpdateControllers(adapter_payload);
105 UpdateVibrations();
106 }
107 std::this_thread::yield();
108 }
109
110 if (restart_scan_thread) {
111 adapter_scan_thread =
112 std::jthread([this](std::stop_token token) { AdapterScanThread(token); });
113 restart_scan_thread = false;
114 }
115}
116
117bool GCAdapter::IsPayloadCorrect(const AdapterPayload& adapter_payload, s32 payload_size) {
118 if (payload_size != static_cast<s32>(adapter_payload.size()) ||
119 adapter_payload[0] != LIBUSB_DT_HID) {
120 LOG_DEBUG(Input, "Error reading payload (size: {}, type: {:02x})", payload_size,
121 adapter_payload[0]);
122 if (input_error_counter++ > 20) {
123 LOG_ERROR(Input, "Timeout, Is the adapter connected?");
124 adapter_input_thread.request_stop();
125 restart_scan_thread = true;
126 }
127 return false;
128 }
129
130 input_error_counter = 0;
131 return true;
132}
133
134void GCAdapter::UpdateControllers(const AdapterPayload& adapter_payload) {
135 for (std::size_t port = 0; port < pads.size(); ++port) {
136 const std::size_t offset = 1 + (9 * port);
137 const auto type = static_cast<ControllerTypes>(adapter_payload[offset] >> 4);
138 UpdatePadType(port, type);
139 if (DeviceConnected(port)) {
140 const u8 b1 = adapter_payload[offset + 1];
141 const u8 b2 = adapter_payload[offset + 2];
142 UpdateStateButtons(port, b1, b2);
143 UpdateStateAxes(port, adapter_payload);
144 }
145 }
146}
147
148void GCAdapter::UpdatePadType(std::size_t port, ControllerTypes pad_type) {
149 if (pads[port].type == pad_type) {
150 return;
151 }
152 // Device changed reset device and set new type
153 pads[port].axis_origin = {};
154 pads[port].reset_origin_counter = {};
155 pads[port].enable_vibration = {};
156 pads[port].rumble_amplitude = {};
157 pads[port].type = pad_type;
158}
159
160void GCAdapter::UpdateStateButtons(std::size_t port, [[maybe_unused]] u8 b1,
161 [[maybe_unused]] u8 b2) {
162 if (port >= pads.size()) {
163 return;
164 }
165
166 static constexpr std::array<PadButton, 8> b1_buttons{
167 PadButton::ButtonA, PadButton::ButtonB, PadButton::ButtonX, PadButton::ButtonY,
168 PadButton::ButtonLeft, PadButton::ButtonRight, PadButton::ButtonDown, PadButton::ButtonUp,
169 };
170
171 static constexpr std::array<PadButton, 4> b2_buttons{
172 PadButton::ButtonStart,
173 PadButton::TriggerZ,
174 PadButton::TriggerR,
175 PadButton::TriggerL,
176 };
177
178 for (std::size_t i = 0; i < b1_buttons.size(); ++i) {
179 const bool button_status = (b1 & (1U << i)) != 0;
180 const int button = static_cast<int>(b1_buttons[i]);
181 SetButton(pads[port].identifier, button, button_status);
182 }
183
184 for (std::size_t j = 0; j < b2_buttons.size(); ++j) {
185 const bool button_status = (b2 & (1U << j)) != 0;
186 const int button = static_cast<int>(b2_buttons[j]);
187 SetButton(pads[port].identifier, button, button_status);
188 }
189}
190
191void GCAdapter::UpdateStateAxes(std::size_t port, const AdapterPayload& adapter_payload) {
192 if (port >= pads.size()) {
193 return;
194 }
195
196 const std::size_t offset = 1 + (9 * port);
197 static constexpr std::array<PadAxes, 6> axes{
198 PadAxes::StickX, PadAxes::StickY, PadAxes::SubstickX,
199 PadAxes::SubstickY, PadAxes::TriggerLeft, PadAxes::TriggerRight,
200 };
201
202 for (const PadAxes axis : axes) {
203 const auto index = static_cast<std::size_t>(axis);
204 const u8 axis_value = adapter_payload[offset + 3 + index];
205 if (pads[port].reset_origin_counter <= 18) {
206 if (pads[port].axis_origin[index] != axis_value) {
207 pads[port].reset_origin_counter = 0;
208 }
209 pads[port].axis_origin[index] = axis_value;
210 pads[port].reset_origin_counter++;
211 }
212 const f32 axis_status = (axis_value - pads[port].axis_origin[index]) / 100.0f;
213 SetAxis(pads[port].identifier, static_cast<int>(index), axis_status);
214 }
215}
216
217void GCAdapter::AdapterScanThread(std::stop_token stop_token) {
218 Common::SetCurrentThreadName("yuzu:input:ScanGCAdapter");
219 usb_adapter_handle = nullptr;
220 pads = {};
221 while (!stop_token.stop_requested() && !Setup()) {
222 std::this_thread::sleep_for(std::chrono::seconds(2));
223 }
224}
225
226bool GCAdapter::Setup() {
227 constexpr u16 nintendo_vid = 0x057e;
228 constexpr u16 gc_adapter_pid = 0x0337;
229 usb_adapter_handle =
230 std::make_unique<LibUSBDeviceHandle>(libusb_ctx->get(), nintendo_vid, gc_adapter_pid);
231 if (!usb_adapter_handle->get()) {
232 return false;
233 }
234 if (!CheckDeviceAccess()) {
235 usb_adapter_handle = nullptr;
236 return false;
237 }
238
239 libusb_device* const device = libusb_get_device(usb_adapter_handle->get());
240
241 LOG_INFO(Input, "GC adapter is now connected");
242 // GC Adapter found and accessible, registering it
243 if (GetGCEndpoint(device)) {
244 rumble_enabled = true;
245 input_error_counter = 0;
246 output_error_counter = 0;
247
248 std::size_t port = 0;
249 for (GCController& pad : pads) {
250 pad.identifier = {
251 .guid = Common::UUID{Common::INVALID_UUID},
252 .port = port++,
253 .pad = 0,
254 };
255 PreSetController(pad.identifier);
256 }
257
258 adapter_input_thread =
259 std::jthread([this](std::stop_token stop_token) { AdapterInputThread(stop_token); });
260 return true;
261 }
262 return false;
263}
264
265bool GCAdapter::CheckDeviceAccess() {
266 s32 kernel_driver_error = libusb_kernel_driver_active(usb_adapter_handle->get(), 0);
267 if (kernel_driver_error == 1) {
268 kernel_driver_error = libusb_detach_kernel_driver(usb_adapter_handle->get(), 0);
269 if (kernel_driver_error != 0 && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) {
270 LOG_ERROR(Input, "libusb_detach_kernel_driver failed with error = {}",
271 kernel_driver_error);
272 }
273 }
274
275 if (kernel_driver_error && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) {
276 usb_adapter_handle = nullptr;
277 return false;
278 }
279
280 const int interface_claim_error = libusb_claim_interface(usb_adapter_handle->get(), 0);
281 if (interface_claim_error) {
282 LOG_ERROR(Input, "libusb_claim_interface failed with error = {}", interface_claim_error);
283 usb_adapter_handle = nullptr;
284 return false;
285 }
286
287 // This fixes payload problems from offbrand GCAdapters
288 const s32 control_transfer_error =
289 libusb_control_transfer(usb_adapter_handle->get(), 0x21, 11, 0x0001, 0, nullptr, 0, 1000);
290 if (control_transfer_error < 0) {
291 LOG_ERROR(Input, "libusb_control_transfer failed with error= {}", control_transfer_error);
292 }
293
294 return true;
295}
296
297bool GCAdapter::GetGCEndpoint(libusb_device* device) {
298 libusb_config_descriptor* config = nullptr;
299 const int config_descriptor_return = libusb_get_config_descriptor(device, 0, &config);
300 if (config_descriptor_return != LIBUSB_SUCCESS) {
301 LOG_ERROR(Input, "libusb_get_config_descriptor failed with error = {}",
302 config_descriptor_return);
303 return false;
304 }
305
306 for (u8 ic = 0; ic < config->bNumInterfaces; ic++) {
307 const libusb_interface* interfaceContainer = &config->interface[ic];
308 for (int i = 0; i < interfaceContainer->num_altsetting; i++) {
309 const libusb_interface_descriptor* interface = &interfaceContainer->altsetting[i];
310 for (u8 e = 0; e < interface->bNumEndpoints; e++) {
311 const libusb_endpoint_descriptor* endpoint = &interface->endpoint[e];
312 if ((endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) != 0) {
313 input_endpoint = endpoint->bEndpointAddress;
314 } else {
315 output_endpoint = endpoint->bEndpointAddress;
316 }
317 }
318 }
319 }
320 // This transfer seems to be responsible for clearing the state of the adapter
321 // Used to clear the "busy" state of when the device is unexpectedly unplugged
322 unsigned char clear_payload = 0x13;
323 libusb_interrupt_transfer(usb_adapter_handle->get(), output_endpoint, &clear_payload,
324 sizeof(clear_payload), nullptr, 16);
325 return true;
326}
327
328Common::Input::VibrationError GCAdapter::SetRumble(
329 const PadIdentifier& identifier, const Common::Input::VibrationStatus& vibration) {
330 const auto mean_amplitude = (vibration.low_amplitude + vibration.high_amplitude) * 0.5f;
331 const auto processed_amplitude =
332 static_cast<u8>((mean_amplitude + std::pow(mean_amplitude, 0.3f)) * 0.5f * 0x8);
333
334 pads[identifier.port].rumble_amplitude = processed_amplitude;
335
336 if (!rumble_enabled) {
337 return Common::Input::VibrationError::Disabled;
338 }
339 return Common::Input::VibrationError::None;
340}
341
342void GCAdapter::UpdateVibrations() {
343 // Use 8 states to keep the switching between on/off fast enough for
344 // a human to feel different vibration strenght
345 // More states == more rumble strengths == slower update time
346 constexpr u8 vibration_states = 8;
347
348 vibration_counter = (vibration_counter + 1) % vibration_states;
349
350 for (GCController& pad : pads) {
351 const bool vibrate = pad.rumble_amplitude > vibration_counter;
352 vibration_changed |= vibrate != pad.enable_vibration;
353 pad.enable_vibration = vibrate;
354 }
355 SendVibrations();
356}
357
358void GCAdapter::SendVibrations() {
359 if (!rumble_enabled || !vibration_changed) {
360 return;
361 }
362 s32 size{};
363 constexpr u8 rumble_command = 0x11;
364 const u8 p1 = pads[0].enable_vibration;
365 const u8 p2 = pads[1].enable_vibration;
366 const u8 p3 = pads[2].enable_vibration;
367 const u8 p4 = pads[3].enable_vibration;
368 std::array<u8, 5> payload = {rumble_command, p1, p2, p3, p4};
369 const int err =
370 libusb_interrupt_transfer(usb_adapter_handle->get(), output_endpoint, payload.data(),
371 static_cast<s32>(payload.size()), &size, 16);
372 if (err) {
373 LOG_DEBUG(Input, "Libusb write failed: {}", libusb_error_name(err));
374 if (output_error_counter++ > 5) {
375 LOG_ERROR(Input, "Output timeout, Rumble disabled");
376 rumble_enabled = false;
377 }
378 return;
379 }
380 output_error_counter = 0;
381 vibration_changed = false;
382}
383
384bool GCAdapter::DeviceConnected(std::size_t port) const {
385 return pads[port].type != ControllerTypes::None;
386}
387
388void GCAdapter::Reset() {
389 adapter_scan_thread = {};
390 adapter_input_thread = {};
391 usb_adapter_handle = nullptr;
392 pads = {};
393 libusb_ctx = nullptr;
394}
395
396std::vector<Common::ParamPackage> GCAdapter::GetInputDevices() const {
397 std::vector<Common::ParamPackage> devices;
398 for (std::size_t port = 0; port < pads.size(); ++port) {
399 if (!DeviceConnected(port)) {
400 continue;
401 }
402 Common::ParamPackage identifier{};
403 identifier.Set("engine", GetEngineName());
404 identifier.Set("display", fmt::format("Gamecube Controller {}", port + 1));
405 identifier.Set("port", static_cast<int>(port));
406 devices.emplace_back(identifier);
407 }
408 return devices;
409}
410
411ButtonMapping GCAdapter::GetButtonMappingForDevice(const Common::ParamPackage& params) {
412 // This list is missing ZL/ZR since those are not considered buttons.
413 // We will add those afterwards
414 // This list also excludes any button that can't be really mapped
415 static constexpr std::array<std::pair<Settings::NativeButton::Values, PadButton>, 12>
416 switch_to_gcadapter_button = {
417 std::pair{Settings::NativeButton::A, PadButton::ButtonA},
418 {Settings::NativeButton::B, PadButton::ButtonB},
419 {Settings::NativeButton::X, PadButton::ButtonX},
420 {Settings::NativeButton::Y, PadButton::ButtonY},
421 {Settings::NativeButton::Plus, PadButton::ButtonStart},
422 {Settings::NativeButton::DLeft, PadButton::ButtonLeft},
423 {Settings::NativeButton::DUp, PadButton::ButtonUp},
424 {Settings::NativeButton::DRight, PadButton::ButtonRight},
425 {Settings::NativeButton::DDown, PadButton::ButtonDown},
426 {Settings::NativeButton::SL, PadButton::TriggerL},
427 {Settings::NativeButton::SR, PadButton::TriggerR},
428 {Settings::NativeButton::R, PadButton::TriggerZ},
429 };
430 if (!params.Has("port")) {
431 return {};
432 }
433
434 ButtonMapping mapping{};
435 for (const auto& [switch_button, gcadapter_button] : switch_to_gcadapter_button) {
436 Common::ParamPackage button_params{};
437 button_params.Set("engine", GetEngineName());
438 button_params.Set("port", params.Get("port", 0));
439 button_params.Set("button", static_cast<int>(gcadapter_button));
440 mapping.insert_or_assign(switch_button, std::move(button_params));
441 }
442
443 // Add the missing bindings for ZL/ZR
444 static constexpr std::array<std::tuple<Settings::NativeButton::Values, PadButton, PadAxes>, 2>
445 switch_to_gcadapter_axis = {
446 std::tuple{Settings::NativeButton::ZL, PadButton::TriggerL, PadAxes::TriggerLeft},
447 {Settings::NativeButton::ZR, PadButton::TriggerR, PadAxes::TriggerRight},
448 };
449 for (const auto& [switch_button, gcadapter_buton, gcadapter_axis] : switch_to_gcadapter_axis) {
450 Common::ParamPackage button_params{};
451 button_params.Set("engine", GetEngineName());
452 button_params.Set("port", params.Get("port", 0));
453 button_params.Set("button", static_cast<s32>(gcadapter_buton));
454 button_params.Set("axis", static_cast<s32>(gcadapter_axis));
455 button_params.Set("threshold", 0.5f);
456 button_params.Set("range", 1.9f);
457 button_params.Set("direction", "+");
458 mapping.insert_or_assign(switch_button, std::move(button_params));
459 }
460 return mapping;
461}
462
463AnalogMapping GCAdapter::GetAnalogMappingForDevice(const Common::ParamPackage& params) {
464 if (!params.Has("port")) {
465 return {};
466 }
467
468 AnalogMapping mapping = {};
469 Common::ParamPackage left_analog_params;
470 left_analog_params.Set("engine", GetEngineName());
471 left_analog_params.Set("port", params.Get("port", 0));
472 left_analog_params.Set("axis_x", static_cast<int>(PadAxes::StickX));
473 left_analog_params.Set("axis_y", static_cast<int>(PadAxes::StickY));
474 mapping.insert_or_assign(Settings::NativeAnalog::LStick, std::move(left_analog_params));
475 Common::ParamPackage right_analog_params;
476 right_analog_params.Set("engine", GetEngineName());
477 right_analog_params.Set("port", params.Get("port", 0));
478 right_analog_params.Set("axis_x", static_cast<int>(PadAxes::SubstickX));
479 right_analog_params.Set("axis_y", static_cast<int>(PadAxes::SubstickY));
480 mapping.insert_or_assign(Settings::NativeAnalog::RStick, std::move(right_analog_params));
481 return mapping;
482}
483
484Common::Input::ButtonNames GCAdapter::GetUIButtonName(const Common::ParamPackage& params) const {
485 PadButton button = static_cast<PadButton>(params.Get("button", 0));
486 switch (button) {
487 case PadButton::ButtonLeft:
488 return Common::Input::ButtonNames::ButtonLeft;
489 case PadButton::ButtonRight:
490 return Common::Input::ButtonNames::ButtonRight;
491 case PadButton::ButtonDown:
492 return Common::Input::ButtonNames::ButtonDown;
493 case PadButton::ButtonUp:
494 return Common::Input::ButtonNames::ButtonUp;
495 case PadButton::TriggerZ:
496 return Common::Input::ButtonNames::TriggerZ;
497 case PadButton::TriggerR:
498 return Common::Input::ButtonNames::TriggerR;
499 case PadButton::TriggerL:
500 return Common::Input::ButtonNames::TriggerL;
501 case PadButton::ButtonA:
502 return Common::Input::ButtonNames::ButtonA;
503 case PadButton::ButtonB:
504 return Common::Input::ButtonNames::ButtonB;
505 case PadButton::ButtonX:
506 return Common::Input::ButtonNames::ButtonX;
507 case PadButton::ButtonY:
508 return Common::Input::ButtonNames::ButtonY;
509 case PadButton::ButtonStart:
510 return Common::Input::ButtonNames::ButtonStart;
511 default:
512 return Common::Input::ButtonNames::Undefined;
513 }
514}
515
516Common::Input::ButtonNames GCAdapter::GetUIName(const Common::ParamPackage& params) const {
517 if (params.Has("button")) {
518 return GetUIButtonName(params);
519 }
520 if (params.Has("axis")) {
521 return Common::Input::ButtonNames::Value;
522 }
523
524 return Common::Input::ButtonNames::Invalid;
525}
526
527} // namespace InputCommon