gc_adapter.cpp 17 KB

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