gc_adapter.cpp 20 KB

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