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