gc_adapter.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. 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. Adapter::Adapter() {
  56. if (usb_adapter_handle) {
  57. return;
  58. }
  59. LOG_INFO(Input, "GC Adapter 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. Adapter::~Adapter() {
  70. Reset();
  71. }
  72. void Adapter::AdapterInputThread(std::stop_token stop_token) {
  73. LOG_DEBUG(Input, "GC Adapter input thread started");
  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 Adapter::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, "GC adapter 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 Adapter::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. if (configuring) {
  118. UpdateYuzuSettings(port);
  119. }
  120. }
  121. }
  122. }
  123. void Adapter::UpdatePadType(std::size_t port, ControllerTypes pad_type) {
  124. if (pads[port].type == pad_type) {
  125. return;
  126. }
  127. // Device changed reset device and set new type
  128. pads[port] = {};
  129. pads[port].type = pad_type;
  130. }
  131. void Adapter::UpdateStateButtons(std::size_t port, u8 b1, u8 b2) {
  132. if (port >= pads.size()) {
  133. return;
  134. }
  135. static constexpr std::array<PadButton, 8> b1_buttons{
  136. PadButton::ButtonA, PadButton::ButtonB, PadButton::ButtonX, PadButton::ButtonY,
  137. PadButton::ButtonLeft, PadButton::ButtonRight, PadButton::ButtonDown, PadButton::ButtonUp,
  138. };
  139. static constexpr std::array<PadButton, 4> b2_buttons{
  140. PadButton::ButtonStart,
  141. PadButton::TriggerZ,
  142. PadButton::TriggerR,
  143. PadButton::TriggerL,
  144. };
  145. pads[port].buttons = 0;
  146. for (std::size_t i = 0; i < b1_buttons.size(); ++i) {
  147. if ((b1 & (1U << i)) != 0) {
  148. pads[port].buttons =
  149. static_cast<u16>(pads[port].buttons | static_cast<u16>(b1_buttons[i]));
  150. pads[port].last_button = b1_buttons[i];
  151. }
  152. }
  153. for (std::size_t j = 0; j < b2_buttons.size(); ++j) {
  154. if ((b2 & (1U << j)) != 0) {
  155. pads[port].buttons =
  156. static_cast<u16>(pads[port].buttons | static_cast<u16>(b2_buttons[j]));
  157. pads[port].last_button = b2_buttons[j];
  158. }
  159. }
  160. }
  161. void Adapter::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. pads[port].axis_values[index] =
  181. static_cast<s16>(axis_value - pads[port].axis_origin[index]);
  182. }
  183. }
  184. void Adapter::UpdateYuzuSettings(std::size_t port) {
  185. if (port >= pads.size()) {
  186. return;
  187. }
  188. constexpr u8 axis_threshold = 50;
  189. GCPadStatus pad_status = {.port = port};
  190. if (pads[port].buttons != 0) {
  191. pad_status.button = pads[port].last_button;
  192. pad_queue.Push(pad_status);
  193. }
  194. // Accounting for a threshold here to ensure an intentional press
  195. for (std::size_t i = 0; i < pads[port].axis_values.size(); ++i) {
  196. const s16 value = pads[port].axis_values[i];
  197. if (value > axis_threshold || value < -axis_threshold) {
  198. pad_status.axis = static_cast<PadAxes>(i);
  199. pad_status.axis_value = value;
  200. pad_status.axis_threshold = axis_threshold;
  201. pad_queue.Push(pad_status);
  202. }
  203. }
  204. }
  205. void Adapter::UpdateVibrations() {
  206. // Use 8 states to keep the switching between on/off fast enough for
  207. // a human to not notice the difference between switching from on/off
  208. // More states = more rumble strengths = slower update time
  209. constexpr u8 vibration_states = 8;
  210. vibration_counter = (vibration_counter + 1) % vibration_states;
  211. for (GCController& pad : pads) {
  212. const bool vibrate = pad.rumble_amplitude > vibration_counter;
  213. vibration_changed |= vibrate != pad.enable_vibration;
  214. pad.enable_vibration = vibrate;
  215. }
  216. SendVibrations();
  217. }
  218. void Adapter::SendVibrations() {
  219. if (!rumble_enabled || !vibration_changed) {
  220. return;
  221. }
  222. s32 size{};
  223. constexpr u8 rumble_command = 0x11;
  224. const u8 p1 = pads[0].enable_vibration;
  225. const u8 p2 = pads[1].enable_vibration;
  226. const u8 p3 = pads[2].enable_vibration;
  227. const u8 p4 = pads[3].enable_vibration;
  228. std::array<u8, 5> payload = {rumble_command, p1, p2, p3, p4};
  229. const int err =
  230. libusb_interrupt_transfer(usb_adapter_handle->get(), output_endpoint, payload.data(),
  231. static_cast<s32>(payload.size()), &size, 16);
  232. if (err) {
  233. LOG_DEBUG(Input, "Adapter libusb write failed: {}", libusb_error_name(err));
  234. if (output_error_counter++ > 5) {
  235. LOG_ERROR(Input, "GC adapter output timeout, Rumble disabled");
  236. rumble_enabled = false;
  237. }
  238. return;
  239. }
  240. output_error_counter = 0;
  241. vibration_changed = false;
  242. }
  243. bool Adapter::RumblePlay(std::size_t port, u8 amplitude) {
  244. pads[port].rumble_amplitude = amplitude;
  245. return rumble_enabled;
  246. }
  247. void Adapter::AdapterScanThread(std::stop_token stop_token) {
  248. usb_adapter_handle = nullptr;
  249. pads = {};
  250. while (!stop_token.stop_requested() && !Setup()) {
  251. std::this_thread::sleep_for(std::chrono::seconds(2));
  252. }
  253. }
  254. bool Adapter::Setup() {
  255. constexpr u16 nintendo_vid = 0x057e;
  256. constexpr u16 gc_adapter_pid = 0x0337;
  257. usb_adapter_handle =
  258. std::make_unique<LibUSBDeviceHandle>(libusb_ctx->get(), nintendo_vid, gc_adapter_pid);
  259. if (!usb_adapter_handle->get()) {
  260. return false;
  261. }
  262. if (!CheckDeviceAccess()) {
  263. usb_adapter_handle = nullptr;
  264. return false;
  265. }
  266. libusb_device* const device = libusb_get_device(usb_adapter_handle->get());
  267. LOG_INFO(Input, "GC adapter is now connected");
  268. // GC Adapter found and accessible, registering it
  269. if (GetGCEndpoint(device)) {
  270. rumble_enabled = true;
  271. input_error_counter = 0;
  272. output_error_counter = 0;
  273. adapter_input_thread =
  274. std::jthread([this](std::stop_token stop_token) { AdapterInputThread(stop_token); });
  275. return true;
  276. }
  277. return false;
  278. }
  279. bool Adapter::CheckDeviceAccess() {
  280. // This fixes payload problems from offbrand GCAdapters
  281. const s32 control_transfer_error =
  282. libusb_control_transfer(usb_adapter_handle->get(), 0x21, 11, 0x0001, 0, nullptr, 0, 1000);
  283. if (control_transfer_error < 0) {
  284. LOG_ERROR(Input, "libusb_control_transfer failed with error= {}", control_transfer_error);
  285. }
  286. s32 kernel_driver_error = libusb_kernel_driver_active(usb_adapter_handle->get(), 0);
  287. if (kernel_driver_error == 1) {
  288. kernel_driver_error = libusb_detach_kernel_driver(usb_adapter_handle->get(), 0);
  289. if (kernel_driver_error != 0 && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) {
  290. LOG_ERROR(Input, "libusb_detach_kernel_driver failed with error = {}",
  291. kernel_driver_error);
  292. }
  293. }
  294. if (kernel_driver_error && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) {
  295. usb_adapter_handle = nullptr;
  296. return false;
  297. }
  298. const int interface_claim_error = libusb_claim_interface(usb_adapter_handle->get(), 0);
  299. if (interface_claim_error) {
  300. LOG_ERROR(Input, "libusb_claim_interface failed with error = {}", interface_claim_error);
  301. usb_adapter_handle = nullptr;
  302. return false;
  303. }
  304. return true;
  305. }
  306. bool Adapter::GetGCEndpoint(libusb_device* device) {
  307. libusb_config_descriptor* config = nullptr;
  308. const int config_descriptor_return = libusb_get_config_descriptor(device, 0, &config);
  309. if (config_descriptor_return != LIBUSB_SUCCESS) {
  310. LOG_ERROR(Input, "libusb_get_config_descriptor failed with error = {}",
  311. config_descriptor_return);
  312. return false;
  313. }
  314. for (u8 ic = 0; ic < config->bNumInterfaces; ic++) {
  315. const libusb_interface* interfaceContainer = &config->interface[ic];
  316. for (int i = 0; i < interfaceContainer->num_altsetting; i++) {
  317. const libusb_interface_descriptor* interface = &interfaceContainer->altsetting[i];
  318. for (u8 e = 0; e < interface->bNumEndpoints; e++) {
  319. const libusb_endpoint_descriptor* endpoint = &interface->endpoint[e];
  320. if ((endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) != 0) {
  321. input_endpoint = endpoint->bEndpointAddress;
  322. } else {
  323. output_endpoint = endpoint->bEndpointAddress;
  324. }
  325. }
  326. }
  327. }
  328. // This transfer seems to be responsible for clearing the state of the adapter
  329. // Used to clear the "busy" state of when the device is unexpectedly unplugged
  330. unsigned char clear_payload = 0x13;
  331. libusb_interrupt_transfer(usb_adapter_handle->get(), output_endpoint, &clear_payload,
  332. sizeof(clear_payload), nullptr, 16);
  333. return true;
  334. }
  335. void Adapter::Reset() {
  336. adapter_scan_thread = {};
  337. adapter_input_thread = {};
  338. usb_adapter_handle = nullptr;
  339. pads = {};
  340. libusb_ctx = nullptr;
  341. }
  342. std::vector<Common::ParamPackage> Adapter::GetInputDevices() const {
  343. std::vector<Common::ParamPackage> devices;
  344. for (std::size_t port = 0; port < pads.size(); ++port) {
  345. if (!DeviceConnected(port)) {
  346. continue;
  347. }
  348. std::string name = fmt::format("Gamecube Controller {}", port + 1);
  349. devices.emplace_back(Common::ParamPackage{
  350. {"class", "gcpad"},
  351. {"display", std::move(name)},
  352. {"port", std::to_string(port)},
  353. });
  354. }
  355. return devices;
  356. }
  357. InputCommon::ButtonMapping Adapter::GetButtonMappingForDevice(
  358. const Common::ParamPackage& params) const {
  359. // This list is missing ZL/ZR since those are not considered buttons.
  360. // We will add those afterwards
  361. // This list also excludes any button that can't be really mapped
  362. static constexpr std::array<std::pair<Settings::NativeButton::Values, PadButton>, 12>
  363. switch_to_gcadapter_button = {
  364. std::pair{Settings::NativeButton::A, PadButton::ButtonA},
  365. {Settings::NativeButton::B, PadButton::ButtonB},
  366. {Settings::NativeButton::X, PadButton::ButtonX},
  367. {Settings::NativeButton::Y, PadButton::ButtonY},
  368. {Settings::NativeButton::Plus, PadButton::ButtonStart},
  369. {Settings::NativeButton::DLeft, PadButton::ButtonLeft},
  370. {Settings::NativeButton::DUp, PadButton::ButtonUp},
  371. {Settings::NativeButton::DRight, PadButton::ButtonRight},
  372. {Settings::NativeButton::DDown, PadButton::ButtonDown},
  373. {Settings::NativeButton::SL, PadButton::TriggerL},
  374. {Settings::NativeButton::SR, PadButton::TriggerR},
  375. {Settings::NativeButton::R, PadButton::TriggerZ},
  376. };
  377. if (!params.Has("port")) {
  378. return {};
  379. }
  380. InputCommon::ButtonMapping mapping{};
  381. for (const auto& [switch_button, gcadapter_button] : switch_to_gcadapter_button) {
  382. Common::ParamPackage button_params({{"engine", "gcpad"}});
  383. button_params.Set("port", params.Get("port", 0));
  384. button_params.Set("button", static_cast<int>(gcadapter_button));
  385. mapping.insert_or_assign(switch_button, std::move(button_params));
  386. }
  387. // Add the missing bindings for ZL/ZR
  388. static constexpr std::array<std::pair<Settings::NativeButton::Values, PadAxes>, 2>
  389. switch_to_gcadapter_axis = {
  390. std::pair{Settings::NativeButton::ZL, PadAxes::TriggerLeft},
  391. {Settings::NativeButton::ZR, PadAxes::TriggerRight},
  392. };
  393. for (const auto& [switch_button, gcadapter_axis] : switch_to_gcadapter_axis) {
  394. Common::ParamPackage button_params({{"engine", "gcpad"}});
  395. button_params.Set("port", params.Get("port", 0));
  396. button_params.Set("button", static_cast<s32>(PadButton::Stick));
  397. button_params.Set("axis", static_cast<s32>(gcadapter_axis));
  398. button_params.Set("threshold", 0.5f);
  399. button_params.Set("direction", "+");
  400. mapping.insert_or_assign(switch_button, std::move(button_params));
  401. }
  402. return mapping;
  403. }
  404. InputCommon::AnalogMapping Adapter::GetAnalogMappingForDevice(
  405. const Common::ParamPackage& params) const {
  406. if (!params.Has("port")) {
  407. return {};
  408. }
  409. InputCommon::AnalogMapping mapping = {};
  410. Common::ParamPackage left_analog_params;
  411. left_analog_params.Set("engine", "gcpad");
  412. left_analog_params.Set("port", params.Get("port", 0));
  413. left_analog_params.Set("axis_x", static_cast<int>(PadAxes::StickX));
  414. left_analog_params.Set("axis_y", static_cast<int>(PadAxes::StickY));
  415. mapping.insert_or_assign(Settings::NativeAnalog::LStick, std::move(left_analog_params));
  416. Common::ParamPackage right_analog_params;
  417. right_analog_params.Set("engine", "gcpad");
  418. right_analog_params.Set("port", params.Get("port", 0));
  419. right_analog_params.Set("axis_x", static_cast<int>(PadAxes::SubstickX));
  420. right_analog_params.Set("axis_y", static_cast<int>(PadAxes::SubstickY));
  421. mapping.insert_or_assign(Settings::NativeAnalog::RStick, std::move(right_analog_params));
  422. return mapping;
  423. }
  424. bool Adapter::DeviceConnected(std::size_t port) const {
  425. return pads[port].type != ControllerTypes::None;
  426. }
  427. void Adapter::BeginConfiguration() {
  428. pad_queue.Clear();
  429. configuring = true;
  430. }
  431. void Adapter::EndConfiguration() {
  432. pad_queue.Clear();
  433. configuring = false;
  434. }
  435. Common::SPSCQueue<GCPadStatus>& Adapter::GetPadQueue() {
  436. return pad_queue;
  437. }
  438. const Common::SPSCQueue<GCPadStatus>& Adapter::GetPadQueue() const {
  439. return pad_queue;
  440. }
  441. GCController& Adapter::GetPadState(std::size_t port) {
  442. return pads.at(port);
  443. }
  444. const GCController& Adapter::GetPadState(std::size_t port) const {
  445. return pads.at(port);
  446. }
  447. } // namespace GCAdapter