GCAdapter.cpp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. // Copyright 2014 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "InputCommon/GCAdapter.h"
  4. #ifndef ANDROID
  5. #define GCADAPTER_USE_LIBUSB_IMPLEMENTATION true
  6. #define GCADAPTER_USE_ANDROID_IMPLEMENTATION false
  7. #else
  8. #define GCADAPTER_USE_LIBUSB_IMPLEMENTATION false
  9. #define GCADAPTER_USE_ANDROID_IMPLEMENTATION true
  10. #endif
  11. #include <algorithm>
  12. #include <array>
  13. #include <mutex>
  14. #include <optional>
  15. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  16. #include <libusb.h>
  17. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  18. #include <jni.h>
  19. #endif
  20. #include "Common/BitUtils.h"
  21. #include "Common/Config/Config.h"
  22. #include "Common/Event.h"
  23. #include "Common/Flag.h"
  24. #include "Common/Logging/Log.h"
  25. #include "Common/Thread.h"
  26. #include "Core/Config/MainSettings.h"
  27. #include "Core/Core.h"
  28. #include "Core/CoreTiming.h"
  29. #include "Core/HW/SI/SI.h"
  30. #include "Core/HW/SI/SI_Device.h"
  31. #include "Core/HW/SystemTimers.h"
  32. #include "Core/System.h"
  33. #include "InputCommon/GCPadStatus.h"
  34. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  35. #include "Common/ScopeGuard.h"
  36. #include "Core/LibusbUtils.h"
  37. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  38. #include "jni/AndroidCommon/IDCache.h"
  39. #endif
  40. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  41. #if defined(LIBUSB_API_VERSION)
  42. #define LIBUSB_API_VERSION_EXIST 1
  43. #else
  44. #define LIBUSB_API_VERSION_EXIST 0
  45. #endif
  46. #define LIBUSB_API_VERSION_ATLEAST(v) (LIBUSB_API_VERSION_EXIST && LIBUSB_API_VERSION >= (v))
  47. #define LIBUSB_API_HAS_HOTPLUG LIBUSB_API_VERSION_ATLEAST(0x01000102)
  48. #endif
  49. namespace GCAdapter
  50. {
  51. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  52. constexpr unsigned int USB_TIMEOUT_MS = 100;
  53. static bool CheckDeviceAccess(libusb_device* device);
  54. static void AddGCAdapter(libusb_device* device);
  55. static void ResetRumbleLockNeeded();
  56. #endif
  57. enum class CalledFromReadThread
  58. {
  59. No,
  60. Yes,
  61. };
  62. static void Reset(CalledFromReadThread called_from_read_thread);
  63. static void Setup();
  64. static void ProcessInputPayload(const u8* data, std::size_t size);
  65. static void ReadThreadFunc();
  66. static void WriteThreadFunc();
  67. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  68. enum class AdapterStatus
  69. {
  70. NotDetected,
  71. Detected,
  72. Error,
  73. };
  74. static std::atomic<AdapterStatus> s_status = AdapterStatus::NotDetected;
  75. static std::atomic<libusb_error> s_adapter_error = LIBUSB_SUCCESS;
  76. static libusb_device_handle* s_handle = nullptr;
  77. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  78. // Java classes
  79. static jclass s_adapter_class;
  80. static bool s_detected = false;
  81. static int s_fd = 0;
  82. #endif
  83. enum class ControllerType : u8
  84. {
  85. None = 0,
  86. Wired = 1,
  87. Wireless = 2,
  88. };
  89. static std::array<u8, SerialInterface::MAX_SI_CHANNELS> s_controller_rumble;
  90. constexpr size_t CONTROLLER_INPUT_PAYLOAD_EXPECTED_SIZE = 37;
  91. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  92. constexpr size_t CONTROLLER_OUTPUT_INIT_PAYLOAD_SIZE = 1;
  93. #endif
  94. constexpr size_t CONTROLLER_OUTPUT_RUMBLE_PAYLOAD_SIZE = 5;
  95. struct PortState
  96. {
  97. GCPadStatus origin = {};
  98. GCPadStatus status = {};
  99. ControllerType controller_type = ControllerType::None;
  100. bool is_new_connection = false;
  101. };
  102. // Only access with s_mutex held!
  103. static std::array<PortState, SerialInterface::MAX_SI_CHANNELS> s_port_states;
  104. static std::array<u8, CONTROLLER_OUTPUT_RUMBLE_PAYLOAD_SIZE> s_controller_write_payload;
  105. static std::atomic<int> s_controller_write_payload_size{0};
  106. static std::thread s_read_adapter_thread;
  107. static Common::Flag s_read_adapter_thread_running;
  108. static Common::Flag s_read_adapter_thread_needs_joining;
  109. static std::thread s_write_adapter_thread;
  110. static Common::Flag s_write_adapter_thread_running;
  111. static Common::Event s_write_happened;
  112. static std::mutex s_read_mutex;
  113. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  114. static std::mutex s_init_mutex;
  115. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  116. static std::mutex s_write_mutex;
  117. #endif
  118. static std::thread s_adapter_detect_thread;
  119. static Common::Flag s_adapter_detect_thread_running;
  120. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  121. static Common::Event s_hotplug_event;
  122. static std::function<void(void)> s_detect_callback;
  123. #if defined(__FreeBSD__) && __FreeBSD__ >= 11
  124. static bool s_libusb_hotplug_enabled = true;
  125. #else
  126. static bool s_libusb_hotplug_enabled = false;
  127. #endif
  128. #if LIBUSB_API_HAS_HOTPLUG
  129. static libusb_hotplug_callback_handle s_hotplug_handle;
  130. #endif
  131. static std::unique_ptr<LibusbUtils::Context> s_libusb_context;
  132. static u8 s_endpoint_in = 0;
  133. static u8 s_endpoint_out = 0;
  134. #endif
  135. static u64 s_last_init = 0;
  136. static std::optional<Config::ConfigChangedCallbackID> s_config_callback_id = std::nullopt;
  137. static bool s_is_adapter_wanted = false;
  138. static std::array<bool, SerialInterface::MAX_SI_CHANNELS> s_config_rumble_enabled{};
  139. static void ReadThreadFunc()
  140. {
  141. Common::SetCurrentThreadName("GCAdapter Read Thread");
  142. NOTICE_LOG_FMT(CONTROLLERINTERFACE, "GCAdapter read thread started");
  143. #if GCADAPTER_USE_ANDROID_IMPLEMENTATION
  144. bool first_read = true;
  145. JNIEnv* const env = IDCache::GetEnvForThread();
  146. const jfieldID payload_field = env->GetStaticFieldID(s_adapter_class, "controller_payload", "[B");
  147. jobject payload_object = env->GetStaticObjectField(s_adapter_class, payload_field);
  148. auto* const java_controller_payload = reinterpret_cast<jbyteArray*>(&payload_object);
  149. // Get function pointers
  150. const jmethodID getfd_func = env->GetStaticMethodID(s_adapter_class, "GetFD", "()I");
  151. const jmethodID input_func = env->GetStaticMethodID(s_adapter_class, "Input", "()I");
  152. const jmethodID openadapter_func = env->GetStaticMethodID(s_adapter_class, "OpenAdapter", "()Z");
  153. const bool connected = env->CallStaticBooleanMethod(s_adapter_class, openadapter_func);
  154. if (!connected)
  155. {
  156. s_fd = 0;
  157. s_detected = false;
  158. NOTICE_LOG_FMT(CONTROLLERINTERFACE, "GC Adapter failed to open!");
  159. return;
  160. }
  161. #endif
  162. s_write_adapter_thread_running.Set(true);
  163. s_write_adapter_thread = std::thread(WriteThreadFunc);
  164. // Reset rumble once on initial reading
  165. ResetRumble();
  166. while (s_read_adapter_thread_running.IsSet())
  167. {
  168. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  169. std::array<u8, CONTROLLER_INPUT_PAYLOAD_EXPECTED_SIZE> input_buffer;
  170. int payload_size = 0;
  171. int error = libusb_interrupt_transfer(s_handle, s_endpoint_in, input_buffer.data(),
  172. int(input_buffer.size()), &payload_size, USB_TIMEOUT_MS);
  173. if (error != LIBUSB_SUCCESS)
  174. {
  175. ERROR_LOG_FMT(CONTROLLERINTERFACE, "Read: libusb_interrupt_transfer failed: {}",
  176. LibusbUtils::ErrorWrap(error));
  177. }
  178. if (error == LIBUSB_ERROR_IO)
  179. {
  180. // s_read_adapter_thread_running is cleared by the joiner, not the stopper.
  181. // Reset the device, which may trigger a replug.
  182. error = libusb_reset_device(s_handle);
  183. ERROR_LOG_FMT(CONTROLLERINTERFACE, "Read: libusb_reset_device: {}",
  184. LibusbUtils::ErrorWrap(error));
  185. // If error is nonzero, try fixing it next loop iteration. We can't easily return
  186. // and cleanup program state without getting another thread to call Reset().
  187. }
  188. ProcessInputPayload(input_buffer.data(), payload_size);
  189. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  190. const int payload_size = env->CallStaticIntMethod(s_adapter_class, input_func);
  191. jbyte* const java_data = env->GetByteArrayElements(*java_controller_payload, nullptr);
  192. ProcessInputPayload(reinterpret_cast<const u8*>(java_data), payload_size);
  193. env->ReleaseByteArrayElements(*java_controller_payload, java_data, 0);
  194. if (first_read)
  195. {
  196. first_read = false;
  197. s_fd = env->CallStaticIntMethod(s_adapter_class, getfd_func);
  198. }
  199. #endif
  200. Common::YieldCPU();
  201. }
  202. // Terminate the write thread on leaving
  203. if (s_write_adapter_thread_running.TestAndClear())
  204. {
  205. s_controller_write_payload_size.store(0);
  206. // Kick the waiting event
  207. s_write_happened.Set();
  208. s_write_adapter_thread.join();
  209. }
  210. #if GCADAPTER_USE_ANDROID_IMPLEMENTATION
  211. s_fd = 0;
  212. s_detected = false;
  213. #endif
  214. NOTICE_LOG_FMT(CONTROLLERINTERFACE, "GCAdapter read thread stopped");
  215. }
  216. static void WriteThreadFunc()
  217. {
  218. Common::SetCurrentThreadName("GCAdapter Write Thread");
  219. NOTICE_LOG_FMT(CONTROLLERINTERFACE, "GCAdapter write thread started");
  220. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  221. int size = 0;
  222. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  223. JNIEnv* const env = IDCache::GetEnvForThread();
  224. const jmethodID output_func = env->GetStaticMethodID(s_adapter_class, "Output", "([B)I");
  225. #endif
  226. while (s_write_adapter_thread_running.IsSet())
  227. {
  228. s_write_happened.Wait();
  229. const int write_size = s_controller_write_payload_size.load();
  230. if (write_size)
  231. {
  232. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  233. const int error =
  234. libusb_interrupt_transfer(s_handle, s_endpoint_out, s_controller_write_payload.data(),
  235. write_size, &size, USB_TIMEOUT_MS);
  236. if (error != LIBUSB_SUCCESS)
  237. {
  238. ERROR_LOG_FMT(CONTROLLERINTERFACE, "Write: libusb_interrupt_transfer failed: {}",
  239. LibusbUtils::ErrorWrap(error));
  240. }
  241. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  242. const jbyteArray jrumble_array = env->NewByteArray(CONTROLLER_OUTPUT_RUMBLE_PAYLOAD_SIZE);
  243. jbyte* const jrumble = env->GetByteArrayElements(jrumble_array, nullptr);
  244. {
  245. std::lock_guard lk(s_write_mutex);
  246. memcpy(jrumble, s_controller_write_payload.data(), write_size);
  247. }
  248. env->ReleaseByteArrayElements(jrumble_array, jrumble, 0);
  249. env->CallStaticIntMethod(s_adapter_class, output_func, jrumble_array);
  250. #endif
  251. }
  252. Common::YieldCPU();
  253. }
  254. NOTICE_LOG_FMT(CONTROLLERINTERFACE, "GCAdapter write thread stopped");
  255. }
  256. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  257. #if LIBUSB_API_HAS_HOTPLUG
  258. static int HotplugCallback(libusb_context* ctx, libusb_device* dev, libusb_hotplug_event event,
  259. void* user_data)
  260. {
  261. if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED)
  262. {
  263. if (s_handle == nullptr)
  264. s_hotplug_event.Set();
  265. }
  266. else if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT)
  267. {
  268. if (s_handle != nullptr && libusb_get_device(s_handle) == dev)
  269. Reset(CalledFromReadThread::No);
  270. // Reset a potential error status now that the adapter is unplugged
  271. if (s_status == AdapterStatus::Error)
  272. {
  273. s_status = AdapterStatus::NotDetected;
  274. if (s_detect_callback != nullptr)
  275. s_detect_callback();
  276. }
  277. }
  278. return 0;
  279. }
  280. #endif
  281. #endif
  282. static void ScanThreadFunc()
  283. {
  284. Common::SetCurrentThreadName("GC Adapter Scanning Thread");
  285. NOTICE_LOG_FMT(CONTROLLERINTERFACE, "GC Adapter scanning thread started");
  286. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  287. #if LIBUSB_API_HAS_HOTPLUG
  288. #ifndef __FreeBSD__
  289. s_libusb_hotplug_enabled = libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) != 0;
  290. #endif
  291. if (s_libusb_hotplug_enabled)
  292. {
  293. const int error = libusb_hotplug_register_callback(
  294. *s_libusb_context,
  295. (libusb_hotplug_event)(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |
  296. LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT),
  297. LIBUSB_HOTPLUG_ENUMERATE, 0x057e, 0x0337, LIBUSB_HOTPLUG_MATCH_ANY, HotplugCallback,
  298. nullptr, &s_hotplug_handle);
  299. if (error == LIBUSB_SUCCESS)
  300. {
  301. NOTICE_LOG_FMT(CONTROLLERINTERFACE, "Using libUSB hotplug detection");
  302. }
  303. else
  304. {
  305. s_libusb_hotplug_enabled = false;
  306. ERROR_LOG_FMT(CONTROLLERINTERFACE, "Failed to add libUSB hotplug detection callback: {}",
  307. LibusbUtils::ErrorWrap(error));
  308. }
  309. }
  310. #endif
  311. while (s_adapter_detect_thread_running.IsSet())
  312. {
  313. if (s_handle == nullptr)
  314. {
  315. std::lock_guard lk(s_init_mutex);
  316. Setup();
  317. }
  318. if (s_libusb_hotplug_enabled)
  319. s_hotplug_event.Wait();
  320. else
  321. Common::SleepCurrentThread(500);
  322. }
  323. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  324. JNIEnv* const env = IDCache::GetEnvForThread();
  325. const jmethodID queryadapter_func =
  326. env->GetStaticMethodID(s_adapter_class, "QueryAdapter", "()Z");
  327. while (s_adapter_detect_thread_running.IsSet())
  328. {
  329. if (!s_detected && UseAdapter() &&
  330. env->CallStaticBooleanMethod(s_adapter_class, queryadapter_func))
  331. Setup();
  332. Common::SleepCurrentThread(1000);
  333. }
  334. #endif
  335. NOTICE_LOG_FMT(CONTROLLERINTERFACE, "GC Adapter scanning thread stopped");
  336. }
  337. void SetAdapterCallback(std::function<void(void)> func)
  338. {
  339. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  340. s_detect_callback = func;
  341. #endif
  342. }
  343. static void RefreshConfig()
  344. {
  345. s_is_adapter_wanted = false;
  346. for (int i = 0; i < SerialInterface::MAX_SI_CHANNELS; ++i)
  347. {
  348. s_is_adapter_wanted |= Config::Get(Config::GetInfoForSIDevice(i)) ==
  349. SerialInterface::SIDevices::SIDEVICE_WIIU_ADAPTER;
  350. s_config_rumble_enabled[i] = Config::Get(Config::GetInfoForAdapterRumble(i));
  351. }
  352. }
  353. void Init()
  354. {
  355. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  356. if (s_handle != nullptr)
  357. return;
  358. s_libusb_context = std::make_unique<LibusbUtils::Context>();
  359. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  360. if (s_fd)
  361. return;
  362. #endif
  363. auto& system = Core::System::GetInstance();
  364. if (const Core::State state = Core::GetState(system);
  365. state != Core::State::Uninitialized && state != Core::State::Starting)
  366. {
  367. auto& core_timing = system.GetCoreTiming();
  368. if ((core_timing.GetTicks() - s_last_init) < system.GetSystemTimers().GetTicksPerSecond())
  369. return;
  370. s_last_init = core_timing.GetTicks();
  371. }
  372. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  373. s_status = AdapterStatus::NotDetected;
  374. s_adapter_error = LIBUSB_SUCCESS;
  375. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  376. JNIEnv* const env = IDCache::GetEnvForThread();
  377. const jclass adapter_class = env->FindClass("org/dolphinemu/dolphinemu/utils/Java_GCAdapter");
  378. s_adapter_class = reinterpret_cast<jclass>(env->NewGlobalRef(adapter_class));
  379. #endif
  380. if (!s_config_callback_id)
  381. s_config_callback_id = Config::AddConfigChangedCallback(RefreshConfig);
  382. RefreshConfig();
  383. if (UseAdapter())
  384. StartScanThread();
  385. }
  386. void StartScanThread()
  387. {
  388. if (s_adapter_detect_thread_running.IsSet())
  389. return;
  390. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  391. if (!s_libusb_context->IsValid())
  392. return;
  393. #endif
  394. s_adapter_detect_thread_running.Set(true);
  395. s_adapter_detect_thread = std::thread(ScanThreadFunc);
  396. }
  397. void StopScanThread()
  398. {
  399. if (s_adapter_detect_thread_running.TestAndClear())
  400. {
  401. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  402. s_hotplug_event.Set();
  403. #endif
  404. s_adapter_detect_thread.join();
  405. }
  406. }
  407. static void Setup()
  408. {
  409. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  410. const AdapterStatus prev_status = s_status;
  411. // Reset the error status in case the adapter gets unplugged
  412. if (s_status == AdapterStatus::Error)
  413. s_status = AdapterStatus::NotDetected;
  414. s_port_states.fill({});
  415. s_controller_rumble.fill(0);
  416. const int ret = s_libusb_context->GetDeviceList([](libusb_device* device) {
  417. if (CheckDeviceAccess(device))
  418. {
  419. // Only connect to a single adapter in case the user has multiple connected
  420. AddGCAdapter(device);
  421. return false;
  422. }
  423. return true;
  424. });
  425. if (ret != LIBUSB_SUCCESS)
  426. WARN_LOG_FMT(CONTROLLERINTERFACE, "Failed to get device list: {}", LibusbUtils::ErrorWrap(ret));
  427. if (s_status != AdapterStatus::Detected && prev_status != s_status &&
  428. s_detect_callback != nullptr)
  429. s_detect_callback();
  430. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  431. s_fd = 0;
  432. s_detected = true;
  433. // Make sure the thread isn't in the middle of shutting down while starting a new one
  434. if (s_read_adapter_thread_needs_joining.TestAndClear() ||
  435. s_read_adapter_thread_running.TestAndClear())
  436. {
  437. s_read_adapter_thread.join();
  438. }
  439. s_read_adapter_thread_running.Set(true);
  440. s_read_adapter_thread = std::thread(ReadThreadFunc);
  441. #endif
  442. }
  443. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  444. static bool CheckDeviceAccess(libusb_device* device)
  445. {
  446. libusb_device_descriptor desc;
  447. int ret = libusb_get_device_descriptor(device, &desc);
  448. if (ret != LIBUSB_SUCCESS)
  449. {
  450. // could not acquire the descriptor, no point in trying to use it.
  451. ERROR_LOG_FMT(CONTROLLERINTERFACE, "libusb_get_device_descriptor failed: {}",
  452. LibusbUtils::ErrorWrap(ret));
  453. return false;
  454. }
  455. if (desc.idVendor != 0x057e || desc.idProduct != 0x0337)
  456. {
  457. // This isn’t the device we are looking for.
  458. return false;
  459. }
  460. NOTICE_LOG_FMT(CONTROLLERINTERFACE, "Found GC Adapter with Vendor: {:X} Product: {:X} Devnum: {}",
  461. desc.idVendor, desc.idProduct, 1);
  462. // In case of failure, capture the libusb error code into the adapter status
  463. Common::ScopeGuard status_guard([&ret] {
  464. s_adapter_error = static_cast<libusb_error>(ret);
  465. s_status = AdapterStatus::Error;
  466. });
  467. const u8 bus = libusb_get_bus_number(device);
  468. const u8 port = libusb_get_device_address(device);
  469. ret = libusb_open(device, &s_handle);
  470. if (ret != LIBUSB_SUCCESS)
  471. {
  472. if (ret == LIBUSB_ERROR_ACCESS)
  473. {
  474. ERROR_LOG_FMT(CONTROLLERINTERFACE,
  475. "Dolphin does not have access to this device: Bus {:03d} Device {:03d}: ID "
  476. "{:04X}:{:04X}.",
  477. bus, port, desc.idVendor, desc.idProduct);
  478. }
  479. ERROR_LOG_FMT(CONTROLLERINTERFACE, "libusb_open failed to open device: {}",
  480. LibusbUtils::ErrorWrap(ret));
  481. return false;
  482. }
  483. bool detach_failed = false;
  484. ret = libusb_kernel_driver_active(s_handle, 0);
  485. if (ret == 1) // 1: kernel driver is active
  486. {
  487. // On macos detaching would fail without root or entitlement.
  488. // We assume user is using GCAdapterDriver and therefore don't want to detach anything
  489. #if !defined(__APPLE__)
  490. ret = libusb_detach_kernel_driver(s_handle, 0);
  491. detach_failed =
  492. ret < LIBUSB_SUCCESS && ret != LIBUSB_ERROR_NOT_FOUND && ret != LIBUSB_ERROR_NOT_SUPPORTED;
  493. #endif
  494. if (detach_failed)
  495. {
  496. ERROR_LOG_FMT(CONTROLLERINTERFACE, "libusb_detach_kernel_driver failed: {}",
  497. LibusbUtils::ErrorWrap(ret));
  498. }
  499. }
  500. else if (ret != 0) // 0: kernel driver is not active, but otherwise no error.
  501. {
  502. // Neither 0 nor 1 means an error occured.
  503. ERROR_LOG_FMT(CONTROLLERINTERFACE, "libusb_kernel_driver_active failed: {}",
  504. LibusbUtils::ErrorWrap(ret));
  505. }
  506. // This call makes Nyko-brand (and perhaps other) adapters work.
  507. // However it returns LIBUSB_ERROR_PIPE with Mayflash adapters.
  508. const int transfer = libusb_control_transfer(s_handle, 0x21, 11, 0x0001, 0, nullptr, 0, 1000);
  509. if (transfer < LIBUSB_SUCCESS)
  510. {
  511. WARN_LOG_FMT(CONTROLLERINTERFACE, "libusb_control_transfer failed: {}",
  512. LibusbUtils::ErrorWrap(transfer));
  513. }
  514. // this split is needed so that we don't avoid claiming the interface when
  515. // detaching the kernel driver is successful
  516. if (detach_failed)
  517. {
  518. libusb_close(s_handle);
  519. s_handle = nullptr;
  520. return false;
  521. }
  522. ret = libusb_claim_interface(s_handle, 0);
  523. if (ret != LIBUSB_SUCCESS)
  524. {
  525. ERROR_LOG_FMT(CONTROLLERINTERFACE, "libusb_claim_interface failed: {}",
  526. LibusbUtils::ErrorWrap(ret));
  527. libusb_close(s_handle);
  528. s_handle = nullptr;
  529. return false;
  530. }
  531. // Updating the adapter status will be done in AddGCAdapter
  532. status_guard.Dismiss();
  533. return true;
  534. }
  535. static void AddGCAdapter(libusb_device* device)
  536. {
  537. auto [error, config] = LibusbUtils::MakeConfigDescriptor(device);
  538. if (error != LIBUSB_SUCCESS)
  539. {
  540. WARN_LOG_FMT(CONTROLLERINTERFACE, "libusb_get_config_descriptor failed: {}",
  541. LibusbUtils::ErrorWrap(error));
  542. }
  543. for (u8 ic = 0; ic < config->bNumInterfaces; ic++)
  544. {
  545. const libusb_interface* interfaceContainer = &config->interface[ic];
  546. for (int i = 0; i < interfaceContainer->num_altsetting; i++)
  547. {
  548. const libusb_interface_descriptor* interface = &interfaceContainer->altsetting[i];
  549. for (u8 e = 0; e < interface->bNumEndpoints; e++)
  550. {
  551. const libusb_endpoint_descriptor* endpoint = &interface->endpoint[e];
  552. if (endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN)
  553. s_endpoint_in = endpoint->bEndpointAddress;
  554. else
  555. s_endpoint_out = endpoint->bEndpointAddress;
  556. }
  557. }
  558. }
  559. config.reset();
  560. int size = 0;
  561. std::array<u8, CONTROLLER_OUTPUT_INIT_PAYLOAD_SIZE> payload = {0x13};
  562. error = libusb_interrupt_transfer(s_handle, s_endpoint_out, payload.data(),
  563. CONTROLLER_OUTPUT_INIT_PAYLOAD_SIZE, &size, USB_TIMEOUT_MS);
  564. if (error != LIBUSB_SUCCESS)
  565. {
  566. WARN_LOG_FMT(CONTROLLERINTERFACE, "AddGCAdapter: libusb_interrupt_transfer failed: {}",
  567. LibusbUtils::ErrorWrap(error));
  568. }
  569. s_read_adapter_thread_running.Set(true);
  570. s_read_adapter_thread = std::thread(ReadThreadFunc);
  571. s_status = AdapterStatus::Detected;
  572. if (s_detect_callback != nullptr)
  573. s_detect_callback();
  574. ResetRumbleLockNeeded();
  575. }
  576. #endif
  577. void Shutdown()
  578. {
  579. StopScanThread();
  580. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  581. #if LIBUSB_API_HAS_HOTPLUG
  582. if (s_libusb_context && s_libusb_context->IsValid() && s_libusb_hotplug_enabled)
  583. libusb_hotplug_deregister_callback(*s_libusb_context, s_hotplug_handle);
  584. #endif
  585. #endif
  586. Reset(CalledFromReadThread::No);
  587. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  588. s_libusb_context.reset();
  589. s_status = AdapterStatus::NotDetected;
  590. #endif
  591. if (s_config_callback_id)
  592. {
  593. Config::RemoveConfigChangedCallback(*s_config_callback_id);
  594. s_config_callback_id = std::nullopt;
  595. }
  596. }
  597. static void Reset(CalledFromReadThread called_from_read_thread)
  598. {
  599. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  600. std::unique_lock lock(s_init_mutex, std::defer_lock);
  601. if (!lock.try_lock())
  602. return;
  603. if (s_status != AdapterStatus::Detected)
  604. return;
  605. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  606. if (!s_detected)
  607. return;
  608. #endif
  609. if (called_from_read_thread == CalledFromReadThread::No)
  610. {
  611. if (s_read_adapter_thread_running.TestAndClear())
  612. s_read_adapter_thread.join();
  613. }
  614. else
  615. {
  616. s_read_adapter_thread_needs_joining.Set();
  617. s_read_adapter_thread_running.Clear();
  618. }
  619. // The read thread will close the write thread
  620. s_port_states.fill({});
  621. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  622. s_status = AdapterStatus::NotDetected;
  623. if (s_handle)
  624. {
  625. const int error = libusb_release_interface(s_handle, 0);
  626. if (error != LIBUSB_SUCCESS)
  627. {
  628. WARN_LOG_FMT(CONTROLLERINTERFACE, "libusb_release_interface failed: {}",
  629. LibusbUtils::ErrorWrap(error));
  630. }
  631. libusb_close(s_handle);
  632. s_handle = nullptr;
  633. }
  634. if (s_detect_callback != nullptr)
  635. s_detect_callback();
  636. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  637. s_detected = false;
  638. s_fd = 0;
  639. #endif
  640. NOTICE_LOG_FMT(CONTROLLERINTERFACE, "GC Adapter detached");
  641. }
  642. GCPadStatus Input(int chan)
  643. {
  644. if (!UseAdapter())
  645. return {};
  646. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  647. if (s_handle == nullptr || s_status != AdapterStatus::Detected)
  648. return {};
  649. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  650. if (!s_detected || !s_fd)
  651. return {};
  652. #endif
  653. std::lock_guard lk(s_read_mutex);
  654. auto& pad_state = s_port_states[chan];
  655. // Return the "origin" state for the first input on a new connection.
  656. if (pad_state.is_new_connection)
  657. {
  658. pad_state.is_new_connection = false;
  659. return pad_state.origin;
  660. }
  661. return pad_state.status;
  662. }
  663. // Get ControllerType from first byte in input payload.
  664. static ControllerType IdentifyControllerType(u8 data)
  665. {
  666. if (Common::ExtractBit<4>(data))
  667. return ControllerType::Wired;
  668. if (Common::ExtractBit<5>(data))
  669. return ControllerType::Wireless;
  670. return ControllerType::None;
  671. }
  672. void ProcessInputPayload(const u8* data, std::size_t size)
  673. {
  674. if (size != CONTROLLER_INPUT_PAYLOAD_EXPECTED_SIZE
  675. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  676. || data[0] != LIBUSB_DT_HID
  677. #endif
  678. )
  679. {
  680. // This can occur for a few frames on initialization.
  681. ERROR_LOG_FMT(CONTROLLERINTERFACE, "error reading payload (size: {}, type: {:02x})", size,
  682. data[0]);
  683. #if GCADAPTER_USE_ANDROID_IMPLEMENTATION
  684. Reset(CalledFromReadThread::Yes);
  685. #endif
  686. }
  687. else
  688. {
  689. std::lock_guard lk(s_read_mutex);
  690. for (int chan = 0; chan != SerialInterface::MAX_SI_CHANNELS; ++chan)
  691. {
  692. const u8* const channel_data = &data[1 + (9 * chan)];
  693. const auto type = IdentifyControllerType(channel_data[0]);
  694. auto& pad_state = s_port_states[chan];
  695. GCPadStatus pad = {};
  696. if (type != ControllerType::None)
  697. {
  698. const u8 b1 = channel_data[1];
  699. const u8 b2 = channel_data[2];
  700. if (Common::ExtractBit<0>(b1))
  701. pad.button |= PAD_BUTTON_A;
  702. if (Common::ExtractBit<1>(b1))
  703. pad.button |= PAD_BUTTON_B;
  704. if (Common::ExtractBit<2>(b1))
  705. pad.button |= PAD_BUTTON_X;
  706. if (Common::ExtractBit<3>(b1))
  707. pad.button |= PAD_BUTTON_Y;
  708. if (Common::ExtractBit<4>(b1))
  709. pad.button |= PAD_BUTTON_LEFT;
  710. if (Common::ExtractBit<5>(b1))
  711. pad.button |= PAD_BUTTON_RIGHT;
  712. if (Common::ExtractBit<6>(b1))
  713. pad.button |= PAD_BUTTON_DOWN;
  714. if (Common::ExtractBit<7>(b1))
  715. pad.button |= PAD_BUTTON_UP;
  716. if (Common::ExtractBit<0>(b2))
  717. pad.button |= PAD_BUTTON_START;
  718. if (Common::ExtractBit<1>(b2))
  719. pad.button |= PAD_TRIGGER_Z;
  720. if (Common::ExtractBit<2>(b2))
  721. pad.button |= PAD_TRIGGER_R;
  722. if (Common::ExtractBit<3>(b2))
  723. pad.button |= PAD_TRIGGER_L;
  724. pad.stickX = channel_data[3];
  725. pad.stickY = channel_data[4];
  726. pad.substickX = channel_data[5];
  727. pad.substickY = channel_data[6];
  728. pad.triggerLeft = channel_data[7];
  729. pad.triggerRight = channel_data[8];
  730. }
  731. else if (!Core::WantsDeterminism())
  732. {
  733. // This is a hack to prevent a desync due to SI devices
  734. // being different and returning different values.
  735. // The corresponding code in DeviceGCAdapter has the same check
  736. pad.button = PAD_ERR_STATUS;
  737. }
  738. if (type != ControllerType::None && pad_state.controller_type == ControllerType::None)
  739. {
  740. NOTICE_LOG_FMT(CONTROLLERINTERFACE, "New device connected to Port {} of Type: {:02x}",
  741. chan + 1, channel_data[0]);
  742. pad.button |= PAD_GET_ORIGIN;
  743. pad_state.origin = pad;
  744. pad_state.is_new_connection = true;
  745. }
  746. pad_state.controller_type = type;
  747. pad_state.status = pad;
  748. }
  749. }
  750. }
  751. bool DeviceConnected(int chan)
  752. {
  753. std::lock_guard lk(s_read_mutex);
  754. return s_port_states[chan].controller_type != ControllerType::None;
  755. }
  756. void ResetDeviceType(int chan)
  757. {
  758. std::lock_guard lk(s_read_mutex);
  759. s_port_states[chan].controller_type = ControllerType::None;
  760. }
  761. bool UseAdapter()
  762. {
  763. return s_is_adapter_wanted;
  764. }
  765. void ResetRumble()
  766. {
  767. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  768. std::unique_lock lock(s_init_mutex, std::defer_lock);
  769. if (!lock.try_lock())
  770. return;
  771. ResetRumbleLockNeeded();
  772. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  773. std::array<u8, CONTROLLER_OUTPUT_RUMBLE_PAYLOAD_SIZE> rumble = {0x11, 0, 0, 0, 0};
  774. {
  775. std::lock_guard lk(s_write_mutex);
  776. s_controller_write_payload = rumble;
  777. s_controller_write_payload_size.store(CONTROLLER_OUTPUT_RUMBLE_PAYLOAD_SIZE);
  778. }
  779. s_write_happened.Set();
  780. #endif
  781. }
  782. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  783. // Needs to be called when s_init_mutex is locked in order to avoid
  784. // being called while the libusb state is being reset
  785. static void ResetRumbleLockNeeded()
  786. {
  787. if (!UseAdapter() || (s_handle == nullptr || s_status != AdapterStatus::Detected))
  788. {
  789. return;
  790. }
  791. s_controller_rumble.fill(0);
  792. std::array<u8, CONTROLLER_OUTPUT_RUMBLE_PAYLOAD_SIZE> rumble = {
  793. 0x11, s_controller_rumble[0], s_controller_rumble[1], s_controller_rumble[2],
  794. s_controller_rumble[3]};
  795. int size = 0;
  796. const int error =
  797. libusb_interrupt_transfer(s_handle, s_endpoint_out, rumble.data(),
  798. CONTROLLER_OUTPUT_RUMBLE_PAYLOAD_SIZE, &size, USB_TIMEOUT_MS);
  799. if (error != LIBUSB_SUCCESS)
  800. {
  801. WARN_LOG_FMT(CONTROLLERINTERFACE, "ResetRumbleLockNeeded: libusb_interrupt_transfer failed: {}",
  802. LibusbUtils::ErrorWrap(error));
  803. }
  804. INFO_LOG_FMT(CONTROLLERINTERFACE, "Rumble state reset");
  805. }
  806. #endif
  807. void Output(int chan, u8 rumble_command)
  808. {
  809. if (!UseAdapter() || !s_config_rumble_enabled[chan])
  810. return;
  811. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  812. if (s_handle == nullptr)
  813. return;
  814. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  815. if (!s_detected || !s_fd)
  816. return;
  817. #endif
  818. // Skip over rumble commands if it has not changed or the controller is wireless
  819. if (rumble_command != s_controller_rumble[chan] &&
  820. s_port_states[chan].controller_type != ControllerType::Wireless)
  821. {
  822. s_controller_rumble[chan] = rumble_command;
  823. std::array<u8, CONTROLLER_OUTPUT_RUMBLE_PAYLOAD_SIZE> rumble = {
  824. 0x11, s_controller_rumble[0], s_controller_rumble[1], s_controller_rumble[2],
  825. s_controller_rumble[3]};
  826. {
  827. #if GCADAPTER_USE_ANDROID_IMPLEMENTATION
  828. std::lock_guard lk(s_write_mutex);
  829. #endif
  830. s_controller_write_payload = rumble;
  831. s_controller_write_payload_size.store(CONTROLLER_OUTPUT_RUMBLE_PAYLOAD_SIZE);
  832. }
  833. s_write_happened.Set();
  834. }
  835. }
  836. bool IsDetected(const char** error_message)
  837. {
  838. #if GCADAPTER_USE_LIBUSB_IMPLEMENTATION
  839. if (s_status != AdapterStatus::Error)
  840. {
  841. if (error_message)
  842. *error_message = nullptr;
  843. return s_status == AdapterStatus::Detected;
  844. }
  845. if (error_message)
  846. *error_message = libusb_strerror(s_adapter_error.load());
  847. return false;
  848. #elif GCADAPTER_USE_ANDROID_IMPLEMENTATION
  849. return s_detected;
  850. #endif
  851. }
  852. } // namespace GCAdapter