gc_adapter.cpp 17 KB

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