gc_adapter.cpp 19 KB

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