summaryrefslogtreecommitdiff
path: root/src/input_common/drivers/gc_adapter.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/input_common/drivers/gc_adapter.cpp')
-rw-r--r--src/input_common/drivers/gc_adapter.cpp483
1 files changed, 483 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..6721ba4f7
--- /dev/null
+++ b/src/input_common/drivers/gc_adapter.cpp
@@ -0,0 +1,483 @@
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(const std::string input_engine_) : InputEngine(input_engine_) {
73 if (usb_adapter_handle) {
74 return;
75 }
76 LOG_INFO(Input, "GC Adapter 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, "GC Adapter 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, "GC adapter 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] = {};
154 pads[port].type = pad_type;
155}
156
157void GCAdapter::UpdateStateButtons(std::size_t port, [[maybe_unused]] u8 b1,
158 [[maybe_unused]] u8 b2) {
159 if (port >= pads.size()) {
160 return;
161 }
162
163 static constexpr std::array<PadButton, 8> b1_buttons{
164 PadButton::ButtonA, PadButton::ButtonB, PadButton::ButtonX, PadButton::ButtonY,
165 PadButton::ButtonLeft, PadButton::ButtonRight, PadButton::ButtonDown, PadButton::ButtonUp,
166 };
167
168 static constexpr std::array<PadButton, 4> b2_buttons{
169 PadButton::ButtonStart,
170 PadButton::TriggerZ,
171 PadButton::TriggerR,
172 PadButton::TriggerL,
173 };
174
175 for (std::size_t i = 0; i < b1_buttons.size(); ++i) {
176 const bool button_status = (b1 & (1U << i)) != 0;
177 const int button = static_cast<int>(b1_buttons[i]);
178 SetButton(pads[port].identifier, button, button_status);
179 }
180
181 for (std::size_t j = 0; j < b2_buttons.size(); ++j) {
182 const bool button_status = (b2 & (1U << j)) != 0;
183 const int button = static_cast<int>(b2_buttons[j]);
184 SetButton(pads[port].identifier, button, button_status);
185 }
186}
187
188void GCAdapter::UpdateStateAxes(std::size_t port, const AdapterPayload& adapter_payload) {
189 if (port >= pads.size()) {
190 return;
191 }
192
193 const std::size_t offset = 1 + (9 * port);
194 static constexpr std::array<PadAxes, 6> axes{
195 PadAxes::StickX, PadAxes::StickY, PadAxes::SubstickX,
196 PadAxes::SubstickY, PadAxes::TriggerLeft, PadAxes::TriggerRight,
197 };
198
199 for (const PadAxes axis : axes) {
200 const auto index = static_cast<std::size_t>(axis);
201 const u8 axis_value = adapter_payload[offset + 3 + index];
202 if (pads[port].reset_origin_counter <= 18) {
203 if (pads[port].axis_origin[index] != axis_value) {
204 pads[port].reset_origin_counter = 0;
205 }
206 pads[port].axis_origin[index] = axis_value;
207 pads[port].reset_origin_counter++;
208 }
209 const f32 axis_status = (axis_value - pads[port].axis_origin[index]) / 110.0f;
210 SetAxis(pads[port].identifier, static_cast<int>(index), axis_status);
211 }
212}
213
214void GCAdapter::AdapterScanThread(std::stop_token stop_token) {
215 Common::SetCurrentThreadName("yuzu:input:ScanGCAdapter");
216 usb_adapter_handle = nullptr;
217 pads = {};
218 while (!stop_token.stop_requested() && !Setup()) {
219 std::this_thread::sleep_for(std::chrono::seconds(2));
220 }
221}
222
223bool GCAdapter::Setup() {
224 constexpr u16 nintendo_vid = 0x057e;
225 constexpr u16 gc_adapter_pid = 0x0337;
226 usb_adapter_handle =
227 std::make_unique<LibUSBDeviceHandle>(libusb_ctx->get(), nintendo_vid, gc_adapter_pid);
228 if (!usb_adapter_handle->get()) {
229 return false;
230 }
231 if (!CheckDeviceAccess()) {
232 usb_adapter_handle = nullptr;
233 return false;
234 }
235
236 libusb_device* const device = libusb_get_device(usb_adapter_handle->get());
237
238 LOG_INFO(Input, "GC adapter is now connected");
239 // GC Adapter found and accessible, registering it
240 if (GetGCEndpoint(device)) {
241 rumble_enabled = true;
242 input_error_counter = 0;
243 output_error_counter = 0;
244
245 std::size_t port = 0;
246 for (GCController& pad : pads) {
247 pad.identifier = {
248 .guid = Common::UUID{""},
249 .port = port++,
250 .pad = 0,
251 };
252 PreSetController(pad.identifier);
253 }
254
255 adapter_input_thread =
256 std::jthread([this](std::stop_token stop_token) { AdapterInputThread(stop_token); });
257 return true;
258 }
259 return false;
260}
261
262bool GCAdapter::CheckDeviceAccess() {
263 // This fixes payload problems from offbrand GCAdapters
264 const s32 control_transfer_error =
265 libusb_control_transfer(usb_adapter_handle->get(), 0x21, 11, 0x0001, 0, nullptr, 0, 1000);
266 if (control_transfer_error < 0) {
267 LOG_ERROR(Input, "libusb_control_transfer failed with error= {}", control_transfer_error);
268 }
269
270 s32 kernel_driver_error = libusb_kernel_driver_active(usb_adapter_handle->get(), 0);
271 if (kernel_driver_error == 1) {
272 kernel_driver_error = libusb_detach_kernel_driver(usb_adapter_handle->get(), 0);
273 if (kernel_driver_error != 0 && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) {
274 LOG_ERROR(Input, "libusb_detach_kernel_driver failed with error = {}",
275 kernel_driver_error);
276 }
277 }
278
279 if (kernel_driver_error && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) {
280 usb_adapter_handle = nullptr;
281 return false;
282 }
283
284 const int interface_claim_error = libusb_claim_interface(usb_adapter_handle->get(), 0);
285 if (interface_claim_error) {
286 LOG_ERROR(Input, "libusb_claim_interface failed with error = {}", interface_claim_error);
287 usb_adapter_handle = nullptr;
288 return false;
289 }
290
291 return true;
292}
293
294bool GCAdapter::GetGCEndpoint(libusb_device* device) {
295 libusb_config_descriptor* config = nullptr;
296 const int config_descriptor_return = libusb_get_config_descriptor(device, 0, &config);
297 if (config_descriptor_return != LIBUSB_SUCCESS) {
298 LOG_ERROR(Input, "libusb_get_config_descriptor failed with error = {}",
299 config_descriptor_return);
300 return false;
301 }
302
303 for (u8 ic = 0; ic < config->bNumInterfaces; ic++) {
304 const libusb_interface* interfaceContainer = &config->interface[ic];
305 for (int i = 0; i < interfaceContainer->num_altsetting; i++) {
306 const libusb_interface_descriptor* interface = &interfaceContainer->altsetting[i];
307 for (u8 e = 0; e < interface->bNumEndpoints; e++) {
308 const libusb_endpoint_descriptor* endpoint = &interface->endpoint[e];
309 if ((endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) != 0) {
310 input_endpoint = endpoint->bEndpointAddress;
311 } else {
312 output_endpoint = endpoint->bEndpointAddress;
313 }
314 }
315 }
316 }
317 // This transfer seems to be responsible for clearing the state of the adapter
318 // Used to clear the "busy" state of when the device is unexpectedly unplugged
319 unsigned char clear_payload = 0x13;
320 libusb_interrupt_transfer(usb_adapter_handle->get(), output_endpoint, &clear_payload,
321 sizeof(clear_payload), nullptr, 16);
322 return true;
323}
324
325bool GCAdapter::SetRumble(const PadIdentifier& identifier, const Input::VibrationStatus vibration) {
326 const auto mean_amplitude = (vibration.low_amplitude + vibration.high_amplitude) * 0.5f;
327 const auto processed_amplitude =
328 static_cast<u8>((mean_amplitude + std::pow(mean_amplitude, 0.3f)) * 0.5f * 0x8);
329
330 pads[identifier.port].rumble_amplitude = processed_amplitude;
331 return rumble_enabled;
332}
333
334void GCAdapter::UpdateVibrations() {
335 // Use 8 states to keep the switching between on/off fast enough for
336 // a human to feel different vibration strenght
337 // More states == more rumble strengths == slower update time
338 constexpr u8 vibration_states = 8;
339
340 vibration_counter = (vibration_counter + 1) % vibration_states;
341
342 for (GCController& pad : pads) {
343 const bool vibrate = pad.rumble_amplitude > vibration_counter;
344 vibration_changed |= vibrate != pad.enable_vibration;
345 pad.enable_vibration = vibrate;
346 }
347 SendVibrations();
348}
349
350void GCAdapter::SendVibrations() {
351 if (!rumble_enabled || !vibration_changed) {
352 return;
353 }
354 s32 size{};
355 constexpr u8 rumble_command = 0x11;
356 const u8 p1 = pads[0].enable_vibration;
357 const u8 p2 = pads[1].enable_vibration;
358 const u8 p3 = pads[2].enable_vibration;
359 const u8 p4 = pads[3].enable_vibration;
360 std::array<u8, 5> payload = {rumble_command, p1, p2, p3, p4};
361 const int err =
362 libusb_interrupt_transfer(usb_adapter_handle->get(), output_endpoint, payload.data(),
363 static_cast<s32>(payload.size()), &size, 16);
364 if (err) {
365 LOG_DEBUG(Input, "Adapter libusb write failed: {}", libusb_error_name(err));
366 if (output_error_counter++ > 5) {
367 LOG_ERROR(Input, "GC adapter output timeout, Rumble disabled");
368 rumble_enabled = false;
369 }
370 return;
371 }
372 output_error_counter = 0;
373 vibration_changed = false;
374}
375
376bool GCAdapter::DeviceConnected(std::size_t port) const {
377 return pads[port].type != ControllerTypes::None;
378}
379
380void GCAdapter::Reset() {
381 adapter_scan_thread = {};
382 adapter_input_thread = {};
383 usb_adapter_handle = nullptr;
384 pads = {};
385 libusb_ctx = nullptr;
386}
387
388std::vector<Common::ParamPackage> GCAdapter::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 const std::string name = fmt::format("Gamecube Controller {}", port + 1);
395 devices.emplace_back(Common::ParamPackage{
396 {"engine", "gcpad"},
397 {"display", std::move(name)},
398 {"port", std::to_string(port)},
399 });
400 }
401 return devices;
402}
403
404ButtonMapping GCAdapter::GetButtonMappingForDevice(const Common::ParamPackage& params) {
405 // This list is missing ZL/ZR since those are not considered buttons.
406 // We will add those afterwards
407 // This list also excludes any button that can't be really mapped
408 static constexpr std::array<std::pair<Settings::NativeButton::Values, PadButton>, 12>
409 switch_to_gcadapter_button = {
410 std::pair{Settings::NativeButton::A, PadButton::ButtonA},
411 {Settings::NativeButton::B, PadButton::ButtonB},
412 {Settings::NativeButton::X, PadButton::ButtonX},
413 {Settings::NativeButton::Y, PadButton::ButtonY},
414 {Settings::NativeButton::Plus, PadButton::ButtonStart},
415 {Settings::NativeButton::DLeft, PadButton::ButtonLeft},
416 {Settings::NativeButton::DUp, PadButton::ButtonUp},
417 {Settings::NativeButton::DRight, PadButton::ButtonRight},
418 {Settings::NativeButton::DDown, PadButton::ButtonDown},
419 {Settings::NativeButton::SL, PadButton::TriggerL},
420 {Settings::NativeButton::SR, PadButton::TriggerR},
421 {Settings::NativeButton::R, PadButton::TriggerZ},
422 };
423 if (!params.Has("port")) {
424 return {};
425 }
426
427 ButtonMapping mapping{};
428 for (const auto& [switch_button, gcadapter_button] : switch_to_gcadapter_button) {
429 Common::ParamPackage button_params({{"engine", "gcpad"}});
430 button_params.Set("port", params.Get("port", 0));
431 button_params.Set("button", static_cast<int>(gcadapter_button));
432 mapping.insert_or_assign(switch_button, std::move(button_params));
433 }
434
435 // Add the missing bindings for ZL/ZR
436 static constexpr std::array<std::tuple<Settings::NativeButton::Values, PadButton, PadAxes>, 2>
437 switch_to_gcadapter_axis = {
438 std::tuple{Settings::NativeButton::ZL, PadButton::TriggerL, PadAxes::TriggerLeft},
439 {Settings::NativeButton::ZR, PadButton::TriggerR, PadAxes::TriggerRight},
440 };
441 for (const auto& [switch_button, gcadapter_buton, gcadapter_axis] : switch_to_gcadapter_axis) {
442 Common::ParamPackage button_params({{"engine", "gcpad"}});
443 button_params.Set("port", params.Get("port", 0));
444 button_params.Set("button", static_cast<s32>(gcadapter_buton));
445 button_params.Set("axis", static_cast<s32>(gcadapter_axis));
446 button_params.Set("threshold", 0.5f);
447 button_params.Set("range", 1.9f);
448 button_params.Set("direction", "+");
449 mapping.insert_or_assign(switch_button, std::move(button_params));
450 }
451 return mapping;
452}
453
454AnalogMapping GCAdapter::GetAnalogMappingForDevice(const Common::ParamPackage& params) {
455 if (!params.Has("port")) {
456 return {};
457 }
458
459 AnalogMapping mapping = {};
460 Common::ParamPackage left_analog_params;
461 left_analog_params.Set("engine", "gcpad");
462 left_analog_params.Set("port", params.Get("port", 0));
463 left_analog_params.Set("axis_x", static_cast<int>(PadAxes::StickX));
464 left_analog_params.Set("axis_y", static_cast<int>(PadAxes::StickY));
465 mapping.insert_or_assign(Settings::NativeAnalog::LStick, std::move(left_analog_params));
466 Common::ParamPackage right_analog_params;
467 right_analog_params.Set("engine", "gcpad");
468 right_analog_params.Set("port", params.Get("port", 0));
469 right_analog_params.Set("axis_x", static_cast<int>(PadAxes::SubstickX));
470 right_analog_params.Set("axis_y", static_cast<int>(PadAxes::SubstickY));
471 mapping.insert_or_assign(Settings::NativeAnalog::RStick, std::move(right_analog_params));
472 return mapping;
473}
474
475std::string GCAdapter::GetUIName(const Common::ParamPackage& params) const {
476 if (params.Has("button")) {
477 return fmt::format("Button {}", params.Get("button", 0));
478 }
479
480 return "Bad GC Adapter";
481}
482
483} // namespace InputCommon