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