gc_adapter.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 "input_common/gcadapter/gc_adapter.h"
  9. namespace GCAdapter {
  10. /// Used to loop through and assign button in poller
  11. constexpr std::array<PadButton, 12> PadButtonArray{
  12. PadButton::PAD_BUTTON_LEFT, PadButton::PAD_BUTTON_RIGHT, PadButton::PAD_BUTTON_DOWN,
  13. PadButton::PAD_BUTTON_UP, PadButton::PAD_TRIGGER_Z, PadButton::PAD_TRIGGER_R,
  14. PadButton::PAD_TRIGGER_L, PadButton::PAD_BUTTON_A, PadButton::PAD_BUTTON_B,
  15. PadButton::PAD_BUTTON_X, PadButton::PAD_BUTTON_Y, PadButton::PAD_BUTTON_START,
  16. };
  17. Adapter::Adapter() {
  18. if (usb_adapter_handle != nullptr) {
  19. return;
  20. }
  21. LOG_INFO(Input, "GC Adapter Initialization started");
  22. current_status = NO_ADAPTER_DETECTED;
  23. get_origin.fill(true);
  24. const int init_res = libusb_init(&libusb_ctx);
  25. if (init_res == LIBUSB_SUCCESS) {
  26. StartScanThread();
  27. } else {
  28. LOG_ERROR(Input, "libusb could not be initialized. failed with error = {}", init_res);
  29. }
  30. }
  31. GCPadStatus Adapter::GetPadStatus(std::size_t port, const std::array<u8, 37>& adapter_payload) {
  32. GCPadStatus pad = {};
  33. ControllerTypes type = ControllerTypes(adapter_payload[1 + (9 * port)] >> 4);
  34. adapter_controllers_status[port] = type;
  35. static constexpr std::array<PadButton, 8> b1_buttons{
  36. PadButton::PAD_BUTTON_A, PadButton::PAD_BUTTON_B, PadButton::PAD_BUTTON_X,
  37. PadButton::PAD_BUTTON_Y, PadButton::PAD_BUTTON_LEFT, PadButton::PAD_BUTTON_RIGHT,
  38. PadButton::PAD_BUTTON_DOWN, PadButton::PAD_BUTTON_UP,
  39. };
  40. static constexpr std::array<PadButton, 4> b2_buttons{
  41. PadButton::PAD_BUTTON_START,
  42. PadButton::PAD_TRIGGER_Z,
  43. PadButton::PAD_TRIGGER_R,
  44. PadButton::PAD_TRIGGER_L,
  45. };
  46. if (adapter_controllers_status[port] == ControllerTypes::None && !get_origin[port]) {
  47. // Controller may have been disconnected, recalibrate if reconnected.
  48. get_origin[port] = true;
  49. }
  50. if (adapter_controllers_status[port] != ControllerTypes::None) {
  51. const u8 b1 = adapter_payload[1 + (9 * port) + 1];
  52. const u8 b2 = adapter_payload[1 + (9 * port) + 2];
  53. for (std::size_t i = 0; i < b1_buttons.size(); ++i) {
  54. if ((b1 & (1U << i)) != 0) {
  55. pad.button |= static_cast<u16>(b1_buttons[i]);
  56. }
  57. }
  58. for (std::size_t j = 0; j < b2_buttons.size(); ++j) {
  59. if ((b2 & (1U << j)) != 0) {
  60. pad.button |= static_cast<u16>(b2_buttons[j]);
  61. }
  62. }
  63. pad.stick_x = adapter_payload[1 + (9 * port) + 3];
  64. pad.stick_y = adapter_payload[1 + (9 * port) + 4];
  65. pad.substick_x = adapter_payload[1 + (9 * port) + 5];
  66. pad.substick_y = adapter_payload[1 + (9 * port) + 6];
  67. pad.trigger_left = adapter_payload[1 + (9 * port) + 7];
  68. pad.trigger_right = adapter_payload[1 + (9 * port) + 8];
  69. if (get_origin[port]) {
  70. origin_status[port].stick_x = pad.stick_x;
  71. origin_status[port].stick_y = pad.stick_y;
  72. origin_status[port].substick_x = pad.substick_x;
  73. origin_status[port].substick_y = pad.substick_y;
  74. origin_status[port].trigger_left = pad.trigger_left;
  75. origin_status[port].trigger_right = pad.trigger_right;
  76. get_origin[port] = false;
  77. }
  78. }
  79. return pad;
  80. }
  81. void Adapter::PadToState(const GCPadStatus& pad, GCState& state) {
  82. for (const auto& button : PadButtonArray) {
  83. const u16 button_value = static_cast<u16>(button);
  84. state.buttons.insert_or_assign(button_value, pad.button & button_value);
  85. }
  86. state.axes.insert_or_assign(static_cast<u8>(PadAxes::StickX), pad.stick_x);
  87. state.axes.insert_or_assign(static_cast<u8>(PadAxes::StickY), pad.stick_y);
  88. state.axes.insert_or_assign(static_cast<u8>(PadAxes::SubstickX), pad.substick_x);
  89. state.axes.insert_or_assign(static_cast<u8>(PadAxes::SubstickY), pad.substick_y);
  90. state.axes.insert_or_assign(static_cast<u8>(PadAxes::TriggerLeft), pad.trigger_left);
  91. state.axes.insert_or_assign(static_cast<u8>(PadAxes::TriggerRight), pad.trigger_right);
  92. }
  93. void Adapter::Read() {
  94. LOG_DEBUG(Input, "GC Adapter Read() thread started");
  95. int payload_size_in, payload_size_copy;
  96. std::array<u8, 37> adapter_payload;
  97. std::array<u8, 37> adapter_payload_copy;
  98. std::array<GCPadStatus, 4> pads;
  99. while (adapter_thread_running) {
  100. libusb_interrupt_transfer(usb_adapter_handle, input_endpoint, adapter_payload.data(),
  101. sizeof(adapter_payload), &payload_size_in, 16);
  102. payload_size_copy = 0;
  103. // this mutex might be redundant?
  104. {
  105. std::lock_guard<std::mutex> lk(s_mutex);
  106. std::copy(std::begin(adapter_payload), std::end(adapter_payload),
  107. std::begin(adapter_payload_copy));
  108. payload_size_copy = payload_size_in;
  109. }
  110. if (payload_size_copy != sizeof(adapter_payload_copy) ||
  111. adapter_payload_copy[0] != LIBUSB_DT_HID) {
  112. LOG_ERROR(Input, "error reading payload (size: {}, type: {:02x})", payload_size_copy,
  113. adapter_payload_copy[0]);
  114. adapter_thread_running = false; // error reading from adapter, stop reading.
  115. break;
  116. }
  117. for (std::size_t port = 0; port < pads.size(); ++port) {
  118. pads[port] = GetPadStatus(port, adapter_payload_copy);
  119. if (DeviceConnected(port) && configuring) {
  120. if (pads[port].button != 0) {
  121. pad_queue[port].Push(pads[port]);
  122. }
  123. // Accounting for a threshold here because of some controller variance
  124. if (pads[port].stick_x > origin_status[port].stick_x + pads[port].THRESHOLD ||
  125. pads[port].stick_x < origin_status[port].stick_x - pads[port].THRESHOLD) {
  126. pads[port].axis = GCAdapter::PadAxes::StickX;
  127. pads[port].axis_value = pads[port].stick_x;
  128. pad_queue[port].Push(pads[port]);
  129. }
  130. if (pads[port].stick_y > origin_status[port].stick_y + pads[port].THRESHOLD ||
  131. pads[port].stick_y < origin_status[port].stick_y - pads[port].THRESHOLD) {
  132. pads[port].axis = GCAdapter::PadAxes::StickY;
  133. pads[port].axis_value = pads[port].stick_y;
  134. pad_queue[port].Push(pads[port]);
  135. }
  136. if (pads[port].substick_x > origin_status[port].substick_x + pads[port].THRESHOLD ||
  137. pads[port].substick_x < origin_status[port].substick_x - pads[port].THRESHOLD) {
  138. pads[port].axis = GCAdapter::PadAxes::SubstickX;
  139. pads[port].axis_value = pads[port].substick_x;
  140. pad_queue[port].Push(pads[port]);
  141. }
  142. if (pads[port].substick_y > origin_status[port].substick_y + pads[port].THRESHOLD ||
  143. pads[port].substick_y < origin_status[port].substick_y - pads[port].THRESHOLD) {
  144. pads[port].axis = GCAdapter::PadAxes::SubstickY;
  145. pads[port].axis_value = pads[port].substick_y;
  146. pad_queue[port].Push(pads[port]);
  147. }
  148. if (pads[port].trigger_left > pads[port].TRIGGER_THRESHOLD) {
  149. pads[port].axis = GCAdapter::PadAxes::TriggerLeft;
  150. pads[port].axis_value = pads[port].trigger_left;
  151. pad_queue[port].Push(pads[port]);
  152. }
  153. if (pads[port].trigger_right > pads[port].TRIGGER_THRESHOLD) {
  154. pads[port].axis = GCAdapter::PadAxes::TriggerRight;
  155. pads[port].axis_value = pads[port].trigger_right;
  156. pad_queue[port].Push(pads[port]);
  157. }
  158. }
  159. PadToState(pads[port], state[port]);
  160. }
  161. std::this_thread::yield();
  162. }
  163. }
  164. void Adapter::ScanThreadFunc() {
  165. LOG_INFO(Input, "GC Adapter scanning thread started");
  166. while (detect_thread_running) {
  167. if (usb_adapter_handle == nullptr) {
  168. std::lock_guard<std::mutex> lk(initialization_mutex);
  169. Setup();
  170. }
  171. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  172. }
  173. }
  174. void Adapter::StartScanThread() {
  175. if (detect_thread_running) {
  176. return;
  177. }
  178. if (!libusb_ctx) {
  179. return;
  180. }
  181. detect_thread_running = true;
  182. detect_thread = std::thread(&Adapter::ScanThreadFunc, this);
  183. }
  184. void Adapter::StopScanThread() {
  185. detect_thread_running = false;
  186. detect_thread.join();
  187. }
  188. void Adapter::Setup() {
  189. // Reset the error status in case the adapter gets unplugged
  190. if (current_status < 0) {
  191. current_status = NO_ADAPTER_DETECTED;
  192. }
  193. adapter_controllers_status.fill(ControllerTypes::None);
  194. // pointer to list of connected usb devices
  195. libusb_device** devices{};
  196. // populate the list of devices, get the count
  197. const ssize_t device_count = libusb_get_device_list(libusb_ctx, &devices);
  198. if (device_count < 0) {
  199. LOG_ERROR(Input, "libusb_get_device_list failed with error: {}", device_count);
  200. detect_thread_running = false; // Stop the loop constantly checking for gc adapter
  201. // TODO: For hotplug+gc adapter checkbox implementation, revert this.
  202. return;
  203. }
  204. if (devices != nullptr) {
  205. for (std::size_t index = 0; index < static_cast<std::size_t>(device_count); ++index) {
  206. if (CheckDeviceAccess(devices[index])) {
  207. // GC Adapter found and accessible, registering it
  208. GetGCEndpoint(devices[index]);
  209. break;
  210. }
  211. }
  212. libusb_free_device_list(devices, 1);
  213. }
  214. // Break out of the ScanThreadFunc() loop that is constantly looking for the device
  215. // Assumes user has GC adapter plugged in before launch to use the adapter
  216. detect_thread_running = false;
  217. }
  218. bool Adapter::CheckDeviceAccess(libusb_device* device) {
  219. libusb_device_descriptor desc;
  220. const int get_descriptor_error = libusb_get_device_descriptor(device, &desc);
  221. if (get_descriptor_error) {
  222. // could not acquire the descriptor, no point in trying to use it.
  223. LOG_ERROR(Input, "libusb_get_device_descriptor failed with error: {}",
  224. get_descriptor_error);
  225. return false;
  226. }
  227. if (desc.idVendor != 0x057e || desc.idProduct != 0x0337) {
  228. // This isn't the device we are looking for.
  229. return false;
  230. }
  231. const int open_error = libusb_open(device, &usb_adapter_handle);
  232. if (open_error == LIBUSB_ERROR_ACCESS) {
  233. LOG_ERROR(Input, "Yuzu can not gain access to this device: ID {:04X}:{:04X}.",
  234. desc.idVendor, desc.idProduct);
  235. return false;
  236. }
  237. if (open_error) {
  238. LOG_ERROR(Input, "libusb_open failed to open device with error = {}", open_error);
  239. return false;
  240. }
  241. int kernel_driver_error = libusb_kernel_driver_active(usb_adapter_handle, 0);
  242. if (kernel_driver_error == 1) {
  243. kernel_driver_error = libusb_detach_kernel_driver(usb_adapter_handle, 0);
  244. if (kernel_driver_error != 0 && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) {
  245. LOG_ERROR(Input, "libusb_detach_kernel_driver failed with error = {}",
  246. kernel_driver_error);
  247. }
  248. }
  249. if (kernel_driver_error && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) {
  250. libusb_close(usb_adapter_handle);
  251. usb_adapter_handle = nullptr;
  252. return false;
  253. }
  254. const int interface_claim_error = libusb_claim_interface(usb_adapter_handle, 0);
  255. if (interface_claim_error) {
  256. LOG_ERROR(Input, "libusb_claim_interface failed with error = {}", interface_claim_error);
  257. libusb_close(usb_adapter_handle);
  258. usb_adapter_handle = nullptr;
  259. return false;
  260. }
  261. return true;
  262. }
  263. void Adapter::GetGCEndpoint(libusb_device* device) {
  264. libusb_config_descriptor* config = nullptr;
  265. const int config_descriptor_return = libusb_get_config_descriptor(device, 0, &config);
  266. if (config_descriptor_return != LIBUSB_SUCCESS) {
  267. LOG_ERROR(Input, "libusb_get_config_descriptor failed with error = {}",
  268. config_descriptor_return);
  269. return;
  270. }
  271. for (u8 ic = 0; ic < config->bNumInterfaces; ic++) {
  272. const libusb_interface* interfaceContainer = &config->interface[ic];
  273. for (int i = 0; i < interfaceContainer->num_altsetting; i++) {
  274. const libusb_interface_descriptor* interface = &interfaceContainer->altsetting[i];
  275. for (u8 e = 0; e < interface->bNumEndpoints; e++) {
  276. const libusb_endpoint_descriptor* endpoint = &interface->endpoint[e];
  277. if (endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) {
  278. input_endpoint = endpoint->bEndpointAddress;
  279. } else {
  280. output_endpoint = endpoint->bEndpointAddress;
  281. }
  282. }
  283. }
  284. }
  285. // This transfer seems to be responsible for clearing the state of the adapter
  286. // Used to clear the "busy" state of when the device is unexpectedly unplugged
  287. unsigned char clear_payload = 0x13;
  288. libusb_interrupt_transfer(usb_adapter_handle, output_endpoint, &clear_payload,
  289. sizeof(clear_payload), nullptr, 16);
  290. adapter_thread_running = true;
  291. current_status = ADAPTER_DETECTED;
  292. adapter_input_thread = std::thread([=] { Read(); }); // Read input
  293. }
  294. Adapter::~Adapter() {
  295. StopScanThread();
  296. Reset();
  297. }
  298. void Adapter::Reset() {
  299. std::unique_lock<std::mutex> lock(initialization_mutex, std::defer_lock);
  300. if (!lock.try_lock()) {
  301. return;
  302. }
  303. if (current_status != ADAPTER_DETECTED) {
  304. return;
  305. }
  306. if (adapter_thread_running) {
  307. adapter_thread_running = false;
  308. }
  309. adapter_input_thread.join();
  310. adapter_controllers_status.fill(ControllerTypes::None);
  311. get_origin.fill(true);
  312. current_status = NO_ADAPTER_DETECTED;
  313. if (usb_adapter_handle) {
  314. libusb_release_interface(usb_adapter_handle, 1);
  315. libusb_close(usb_adapter_handle);
  316. usb_adapter_handle = nullptr;
  317. }
  318. if (libusb_ctx) {
  319. libusb_exit(libusb_ctx);
  320. }
  321. }
  322. bool Adapter::DeviceConnected(std::size_t port) {
  323. return adapter_controllers_status[port] != ControllerTypes::None;
  324. }
  325. void Adapter::ResetDeviceType(std::size_t port) {
  326. adapter_controllers_status[port] = ControllerTypes::None;
  327. }
  328. void Adapter::BeginConfiguration() {
  329. get_origin.fill(true);
  330. for (auto& pq : pad_queue) {
  331. pq.Clear();
  332. }
  333. configuring = true;
  334. }
  335. void Adapter::EndConfiguration() {
  336. for (auto& pq : pad_queue) {
  337. pq.Clear();
  338. }
  339. configuring = false;
  340. }
  341. std::array<Common::SPSCQueue<GCPadStatus>, 4>& Adapter::GetPadQueue() {
  342. return pad_queue;
  343. }
  344. const std::array<Common::SPSCQueue<GCPadStatus>, 4>& Adapter::GetPadQueue() const {
  345. return pad_queue;
  346. }
  347. std::array<GCState, 4>& Adapter::GetPadState() {
  348. return state;
  349. }
  350. const std::array<GCState, 4>& Adapter::GetPadState() const {
  351. return state;
  352. }
  353. int Adapter::GetOriginValue(int port, int axis) const {
  354. const auto& status = origin_status[port];
  355. switch (static_cast<PadAxes>(axis)) {
  356. case PadAxes::StickX:
  357. return status.stick_x;
  358. case PadAxes::StickY:
  359. return status.stick_y;
  360. case PadAxes::SubstickX:
  361. return status.substick_x;
  362. case PadAxes::SubstickY:
  363. return status.substick_y;
  364. case PadAxes::TriggerLeft:
  365. return status.trigger_left;
  366. case PadAxes::TriggerRight:
  367. return status.trigger_right;
  368. default:
  369. return 0;
  370. }
  371. }
  372. } // namespace GCAdapter