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