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