From be8c2620e5e849e24dd73f7f3723e7ef19fe4ada Mon Sep 17 00:00:00 2001 From: chrg6 Date: Mon, 9 Nov 2026 23:51:58 -0500 Subject: [PATCH] Run the gamepad update on a thread of its own, so a controller that comes or goes no longer stalls the game. When a device came or went, SDL's gamepad update first found every device again, 100 ms and more, on the game's polling thread with the input lock held: a controller disconnecting gave five frames of 120 to 240 ms in a row, with the game's other pollers queued on the lock. The pad thread now makes SDL's initialisation and every update. A poll asks for an update and waits at most 2 ms for it; an ordinary one is done in microseconds and the poll reads fresh state as before, and during a device search the poll goes on with the state it read last. Rumble, the motion samples and the menu's stick reading skip a beat then instead of waiting. --probe-input checks it on a virtual gamepad, with an update made to take 300 ms. Co-Authored-By: Claude Fable 5.2 --- runtime/host.h | 1 + runtime/input.c | 222 +++++++++++++++++++++++++++++++++++++++++++----- runtime/main.c | 4 +- 3 files changed, 204 insertions(+), 23 deletions(-) diff --git a/runtime/host.h b/runtime/host.h index 0d1feb45..2ccedb96 100644 --- a/runtime/host.h +++ b/runtime/host.h @@ -371,6 +371,7 @@ int probe_shader(void); // gfx_shader.c int probe_census_dir(char *dir, size_t n); // gfx_shader_probe.c: build//shaders for the probes int probe_vkmem(void), probe_vkexec(void), probe_astc(void); // tex_probe.c, vk_exec_probe.c, astc_probe.c int probe_zstd(void); // ov_zstd.c +int probe_input(void); // input.c int probe_movie(void); // movie_probe.c: host VP9 movie::Decoder on one RomFS movie int vk_pipeline_prepare_shaders(void); // vk_pipeline.c: --prepare-shaders (tools/prepare_shaders.py) int vk_pipeline_warm_shaders(void); // vk_pipeline.c: --warm-shaders (tools/build_game.py) diff --git a/runtime/input.c b/runtime/input.c index 3eac713a..26244cd6 100644 --- a/runtime/input.c +++ b/runtime/input.c @@ -395,6 +395,102 @@ static float stick_dead_get(int s) { } // One gamepad stick through the dead zone; SDL's Y grows downwards, the Switch's upwards. +// ---- SDL's gamepad update on a thread of its own +// SDL_UpdateGamepads reads the controllers, and when a device came or went it first finds every device again, 100 ms +// and more inside the system's input libraries. It ran on the game's polling thread with the input lock held: a +// controller that disconnected (a wireless one going to sleep, a cable pulled) gave a burst of 120 to 240 ms frames, +// one per device notification, with the game's other pollers queued on the lock. +// The pad thread (up_main) makes SDL's initialisation and every update. A poll asks for an update and waits for it, +// UP_WAIT_NS at most (sdl_enter): an ordinary update is done in microseconds and the poll reads fresh state, as before; +// one that runs into the device search is not, and the poll goes on with what it read last. sdl_lock is held around +// every SDL gamepad call: by the pad thread for an update, by everyone else through sdl_enter or a try +// (plat_mutex_trylock), never by waiting, so no thread of the game stands behind the device search. +#define UP_WAIT_NS 2000000ull // how long a poll waits for its update +#define UP_FRESH_NS 500000ull // polls this soon after an update share it (the game reads several pads in a row) +static PlatMutex sdl_lock = PLAT_MUTEX_INIT; +static PlatMutex up_lock = PLAT_MUTEX_INIT; // guards the fields below +static PlatCond up_go = PLAT_COND_INIT, up_done = PLAT_COND_INIT; +static int up_started, up_inited, up_init_ok, up_want, up_busy; +static uint64_t up_gen, up_at, up_t0; // updates finished; when the last one finished; when the running one began +static uint64_t up_stale; // polls that went on without an update +static volatile uint64_t up_test_ns; // --probe-input: the next update takes this long, as a device search does + +static void up_main(void *arg) { + (void)arg; + // SDL drops gamepad presses while it thinks the program is in the background, and it judges that from windows of + // its own: the Win32 window (gfx_window_win.c) is not one, and keyboard focus is gated here (ikb_foreground) + SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1"); + int ok = SDL_Init(SDL_INIT_GAMEPAD); + if (!ok) rt_log("input: SDL gamepad init failed (%s), keyboard only", SDL_GetError()); + plat_mutex_lock(&up_lock); + up_inited = 1, up_init_ok = ok; + plat_cond_broadcast(&up_done); + while (ok) { + while (!up_want) plat_cond_wait(&up_go, &up_lock); + up_want = 0, up_busy = 1, up_t0 = plat_now_ns(); + plat_mutex_unlock(&up_lock); + plat_mutex_lock(&sdl_lock); + uint64_t slow = __atomic_exchange_n(&up_test_ns, 0, __ATOMIC_RELAXED); + if (slow) plat_wait_ns(slow); + SDL_UpdateGamepads(); +#ifdef _WIN32 + // The Windows window is our own (gfx_window_win.c), so nothing reads SDL's event queue, yet every axis and + // button change of a gamepad is queued there: at SDL's cap (about 65,000 events, several MB) each further one + // fails and sets SDL's error text. The state the getters read does not come from the queue. + SDL_FlushEvents(SDL_EVENT_FIRST, SDL_EVENT_LAST); +#endif + plat_mutex_unlock(&sdl_lock); + plat_mutex_lock(&up_lock); + uint64_t took = plat_now_ns() - up_t0; + up_busy = 0, up_gen++, up_at = plat_now_ns(); + plat_cond_broadcast(&up_done); + static int logged; + if (took >= 20000000ull && logged++ < 16) + rt_log("input: the gamepad update took %.0f ms (devices found again after one came or went); %llu polls so far " + "went on with their last state instead of waiting", took / 1e6, (unsigned long long)up_stale); + } + plat_mutex_unlock(&up_lock); +} + +// Under lock: starts the pad thread and waits for SDL's initialisation on it. 1 when SDL's gamepads can be used. +static int sdl_start(void) { + plat_mutex_lock(&up_lock); + if (!up_started) { + up_started = 1; + if (!plat_thread_spawn(up_main, NULL, "pads", 0)) rt_fatal("input: cannot start the gamepad thread"); + } + while (!up_inited) plat_cond_wait(&up_done, &up_lock); + int ok = up_init_ok; + plat_mutex_unlock(&up_lock); + return ok; +} + +// Under lock: brings SDL's gamepad state up to date and takes sdl_lock for the caller's SDL calls. 1 with it held +// (sdl_leave gives it back); 0 when the update is not done within UP_WAIT_NS, and then nothing of SDL may be called. +static int sdl_enter(void) { + plat_mutex_lock(&up_lock); + uint64_t now = plat_now_ns(); + int ok = 1; + if (up_busy && now - up_t0 >= UP_WAIT_NS) { + ok = 0; // the device search: the first poll waited for it, the ones after it do not + } else if (up_busy || now - up_at >= UP_FRESH_NS) { + uint64_t next = up_gen + 1; + if (!up_busy) up_want = 1, plat_cond_signal(&up_go); + while (up_gen < next) { + uint64_t el = plat_now_ns() - now; + if (el >= UP_WAIT_NS) break; + plat_cond_wait_ns(&up_done, &up_lock, UP_WAIT_NS - el); + } + ok = up_gen >= next; + } + if (!ok) up_stale++; + plat_mutex_unlock(&up_lock); + if (ok && !plat_mutex_trylock(&sdl_lock)) ok = 0; // the next update began already, for another poller + return ok; +} + +static void sdl_leave(void) { plat_mutex_unlock(&sdl_lock); } + static void stick(SDL_GamepadAxis ax, SDL_GamepadAxis ay, float dead, int32_t out[2]) { input_pad_stick(SDL_GetGamepadAxis(pad, ax), -(int32_t)SDL_GetGamepadAxis(pad, ay), dead, out); } @@ -577,14 +673,12 @@ static void start(void) { binds_refresh(); const char *e = cfg_get("NX2NAVI_INPUT"); if (e && !strcmp(e, "none")) { state = -1; rt_log("input: disabled (NX2NAVI_INPUT=none)"); return; } - // SDL drops gamepad presses while it thinks the program is in the background, and it judges that from windows of - // its own: the Win32 window (gfx_window_win.c) is not one, and keyboard focus is gated here (ikb_foreground) - SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1"); - if (!SDL_Init(SDL_INIT_GAMEPAD)) { state = -1; rt_log("input: SDL gamepad init failed (%s), keyboard only", SDL_GetError()); } - else state = 1; - if (state == 1) test_pad_attach(); + state = sdl_start() ? 1 : -1; // SDL's initialisation, on the pad thread (up_main) if (state == 1) { + plat_mutex_lock(&sdl_lock); // the pad thread updates only when asked, and nobody has asked yet + test_pad_attach(); scan_pads(); + plat_mutex_unlock(&sdl_lock); if (!pad) rt_log("input: no gamepad (keyboard only until one is connected)"); } if (state == -1) state = 2; // keyboard only @@ -620,18 +714,12 @@ static int32_t shake_stick(int held) { return (now - from) / SHAKE_SIDE_NS % 2 ? STICK_MAX : -STICK_MAX; } -// Under lock, state 1: the open gamepad's inputs by position (pd[PAD_*] != 0 held); 0 without a connected gamepad. +// Under lock and inside sdl_enter (the gamepads' state is up to date), state 1: the open gamepad's inputs by position +// (pd[PAD_*] != 0 held); 0 without a connected gamepad. static int pad_physical(uint8_t pd[PAD_COUNT]) { test_pad_tick(); // every RESCAN_MS, not only without a gamepad: a second controller, or one that wakes up after the start, is found if (plat_now_ns() / 1000000u >= next_scan) { next_scan = plat_now_ns() / 1000000u + RESCAN_MS; scan_pads(); } - SDL_UpdateGamepads(); -#ifdef _WIN32 - // The Windows window is our own (gfx_window_win.c), so nothing reads SDL's event queue, yet every axis and button - // change of a gamepad is queued there: at SDL's cap (about 65,000 events, several MB) each further one fails and - // sets SDL's error text. The state the calls below read does not come from the queue. - SDL_FlushEvents(SDL_EVENT_FIRST, SDL_EVENT_LAST); -#endif pad_follow(); if (!pad || !SDL_GamepadConnected(pad)) return 0; for (int p = PAD_SOUTH; p < PAD_ZL; p++) pd[p] = SDL_GetGamepadButton(pad, pad_sdl[p]); @@ -717,7 +805,26 @@ static int ds3_primary(uint8_t pd[PAD_COUNT], int32_t raw[4], int sdl_pad) { } #endif +static int pad_read_now(uint64_t *b, int32_t sl[2], int32_t sr[2]); + +// Under lock, state 1: the gamepad's buttons (ORed into *b) and sticks; 0 without one. While SDL is finding devices +// again (sdl_enter) the answer is the last one read: what was held stays held for those moments. static int pad_read(uint64_t *b, int32_t sl[2], int32_t sr[2]) { + static uint64_t last_b; + static int32_t last_sl[2], last_sr[2]; + static int last_ok; + if (sdl_enter()) { + uint64_t pb = 0; + int32_t l[2] = {0, 0}, r[2] = {0, 0}; + last_ok = pad_read_now(&pb, l, r); + sdl_leave(); + last_b = pb, last_sl[0] = l[0], last_sl[1] = l[1], last_sr[0] = r[0], last_sr[1] = r[1]; + } + if (last_ok) *b |= last_b, sl[0] = last_sl[0], sl[1] = last_sl[1], sr[0] = last_sr[0], sr[1] = last_sr[1]; + return last_ok; +} + +static int pad_read_now(uint64_t *b, int32_t sl[2], int32_t sr[2]) { uint8_t pd[PAD_COUNT] = {0}; #ifdef _WIN32 int sdl = pad_physical(pd); @@ -749,22 +856,25 @@ int input_pad_stick_percent(double pct[2]) { int ok = 0; pct[0] = pct[1] = 0; plat_mutex_lock(&lock); + int in = state == 1 && plat_mutex_trylock(&sdl_lock); // not while SDL updates: this reading is skipped then + int sdl_pad = in && pad && SDL_GamepadConnected(pad); #ifdef _WIN32 uint8_t dd[PAD_COUNT]; int32_t raw[4]; - if (state == 1 && ds3_primary(dd, raw, pad && SDL_GamepadConnected(pad))) { + if (state == 1 && ds3_primary(dd, raw, sdl_pad)) { pct[0] = input_stick_percent(raw[0], raw[1]); pct[1] = input_stick_percent(raw[2], raw[3]); ok = 1; } else #endif - if (state == 1 && pad && SDL_GamepadConnected(pad)) { // the game's poll keeps the state fresh (SDL_UpdateGamepads) + if (sdl_pad) { // the game's poll keeps the state fresh (sdl_enter) pct[0] = input_stick_percent(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFTX), SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFTY)); pct[1] = input_stick_percent(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHTX), SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHTY)); ok = 1; } + if (in) sdl_leave(); plat_mutex_unlock(&lock); return ok; } @@ -954,7 +1064,7 @@ int input_capture(int reset, int *id) { int esc = fg && ikb_escape(); plat_mutex_lock(&lock); if (!state) start(); - if (state == 1) pad_physical(p); + if (state == 1 && sdl_enter()) pad_physical(p), sdl_leave(); #ifdef _WIN32 if (state == 1) { // a DualShock 3 the reader has: its presses can be bound too uint8_t dd[PAD_COUNT]; @@ -988,9 +1098,10 @@ int input_rumble(uint16_t low, uint16_t high, uint32_t ms) { static unsigned seen; if (triggers < 0 || seen != cfg_version()) seen = cfg_version(), triggers = input_rumble_triggers_enabled(); plat_mutex_lock(&lock); - if (state == 1 && pad && pad_rumble) { + if (state == 1 && pad && pad_rumble && plat_mutex_trylock(&sdl_lock)) { // one skipped while SDL updates ok = SDL_RumbleGamepad(pad, low, high, ms); if (triggers) SDL_RumbleGamepadTriggers(pad, high, high, ms); // unsupported pads return false: ignored + sdl_leave(); } #ifdef _WIN32 if (state == 1 && ds3_rumble(low, high, ms)) ok = 1; // no-op unless the DualShock 3 reader has a controller @@ -1054,10 +1165,10 @@ static void motion_main(void *arg) { float a[3], g[3]; int have = 0; plat_mutex_lock(&lock); - if (pad && SDL_GamepadConnected(pad)) { - SDL_UpdateGamepads(); - have = sensors_ready() && SDL_GetGamepadSensorData(pad, SDL_SENSOR_ACCEL, a, 3) && - SDL_GetGamepadSensorData(pad, SDL_SENSOR_GYRO, g, 3); + if (pad && sdl_enter()) { // no sample while SDL finds devices again + have = SDL_GamepadConnected(pad) && sensors_ready() && + SDL_GetGamepadSensorData(pad, SDL_SENSOR_ACCEL, a, 3) && SDL_GetGamepadSensorData(pad, SDL_SENSOR_GYRO, g, 3); + sdl_leave(); } plat_mutex_unlock(&lock); if (!have || !input_motion_enabled()) continue; @@ -1080,3 +1191,70 @@ void input_motion_start(void) { } plat_mutex_unlock(&lock); } + +// --probe-input: the gamepad path on SDL's virtual test gamepad (NX2NAVI_TEST_PAD). The pad thread comes up, a poll +// reads the gamepad, polls are quick, and while an update takes as long as a device search (up_test_ns) the polls go on +// with their last state instead of waiting for it. Needs no game files and no controller. +int probe_input(void) { + int fails = 0; + cfg_setenv("NX2NAVI_TEST_PAD", "20000,-12000,0,0"); + uint64_t b = 0; + int32_t lx = 0, ly = 0; + uint64_t t0 = plat_now_ns(); + int ok = input_pad_read(&b, &lx, &ly); + printf("input: first poll %.1f ms (SDL comes up on the pad thread), gamepad %s\n", (plat_now_ns() - t0) / 1e6, + ok ? "read" : "not read"); + if (!ok) fails++, printf("FAIL: no gamepad was read, with the test gamepad attached\n"); + plat_mutex_lock(&lock); + const char *nm = pad && plat_mutex_trylock(&sdl_lock) ? SDL_GetGamepadName(pad) : NULL; + int test = nm && strstr(nm, "test gamepad"); + if (nm) sdl_leave(); + plat_mutex_unlock(&lock); + if (test && (lx < 8000 || ly == 0)) fails++, printf("FAIL: the test gamepad's left stick read %d,%d\n", lx, ly); + if (!test) printf("input: another gamepad is the primary one; the stick values are not checked\n"); + // ordinary polls: each asks the pad thread for an update unless one is fresh + uint64_t worst = 0, sum = 0; + enum { N = 400 }; + for (int i = 0; i < N; i++) { + plat_wait_ns(700000); // past UP_FRESH_NS: every poll asks + uint64_t p0 = plat_now_ns(); + int32_t x, y; + ok = input_pad_read(&b, &x, &y); + uint64_t d = plat_now_ns() - p0; + sum += d; + if (d > worst) worst = d; + if (!ok || (test && x != lx)) { fails++, printf("FAIL: poll %d read %d (stick %d, was %d)\n", i, ok, x, lx); break; } + } + printf("input: %d polls, each with its own update: %.0f us on average, %.0f us the longest\n", N, sum / 1e3 / N, worst / 1e3); + if (worst > UP_WAIT_NS + 3000000) fails++, printf("FAIL: a poll took %.1f ms\n", worst / 1e6); + uint64_t stale0 = up_stale; + // an update that takes 300 ms: the first poll waits UP_WAIT_NS for it, the others not at all, and all get the stick + __atomic_store_n(&up_test_ns, 300000000ull, __ATOMIC_RELAXED); + plat_wait_ns(700000); + uint64_t s0 = plat_now_ns(), first = 0, rest = 0; + int n = 0; + while (plat_now_ns() - s0 < 250000000ull) { + uint64_t p0 = plat_now_ns(); + int32_t x, y; + ok = input_pad_read(&b, &x, &y); + uint64_t d = plat_now_ns() - p0; + if (!n) first = d; + else if (d > rest) rest = d; + n++; + if (!ok || (test && x != lx)) { fails++, printf("FAIL: a poll during the long update read %d (stick %d, was %d)\n", ok, x, lx); break; } + plat_wait_ns(1000000); + } + printf("input: during a 300 ms update: %d polls, the first %.1f ms, the longest after it %.0f us, %llu went on with " + "the last state\n", n, first / 1e6, rest / 1e3, (unsigned long long)(up_stale - stale0)); + if (first > UP_WAIT_NS + 3000000 || rest > 1500000 || up_stale - stale0 < (uint64_t)n - 1) + fails++, printf("FAIL: polls waited for the long update\n"); + plat_wait_ns(120000000); // the long update ends: polls are fresh again + uint64_t g0 = up_gen; + ok = input_pad_read(&b, &lx, &ly); + if (!ok || up_gen == g0) fails++, printf("FAIL: no update after the long one\n"); + double pct[2]; + input_pad_stick_percent(pct); + input_rumble(1000, 1000, 10); + printf("probe-input: %s\n", fails ? "FAILED" : "passed"); + return fails != 0; +} diff --git a/runtime/main.c b/runtime/main.c index e5935374..2786b0a5 100644 --- a/runtime/main.c +++ b/runtime/main.c @@ -22,6 +22,7 @@ // --probe-nvn, --probe-nvn-tex, --probe-window, --probe-shader, --probe-vkmem, --probe-vkexec graphics probes // --probe-astc the compute ASTC decoder against astc_decode_ldr; needs no game files // --probe-zstd host zstd streams (ov_zstd.c) on frames made here; needs no game files +// --probe-input gamepad polls on a virtual gamepad, also while SDL's update takes long; needs no game files // --probe-movie host VP9 movie::Decoder on one RomFS movie; skips without game data // --boot run the game to the first NVN call // --seconds S run the game (implies --boot's start-up) until the world clock (game time since the loaded @@ -493,7 +494,7 @@ static int usage(const char *argv0) { fprintf(stderr, "usage: %s [--exefs DIR] [--romfs DIR] [--profile DIR] [--audio-device VALUE] [--monitor VALUE] [--list-audio-devices | --list-monitors | --selftest | --probe-loader | " "--probe-cfg | --probe-dpi | --probe-mods | --probe-kernel | --probe-ipc | --probe-services | --probe-fs | --probe-gfx-abi | " "--probe-nvn | --probe-nvn-tex | --probe-window | --probe-shader | --probe-vkmem | " - "--probe-vkexec | --probe-astc | --probe-zstd | --probe-movie | --probe-crash-call | --probe-crash-null | --probe-discord | " + "--probe-vkexec | --probe-astc | --probe-zstd | --probe-input | --probe-movie | --probe-crash-call | --probe-crash-null | --probe-discord | " "--prepare-shaders | --warm-shaders | --boot |--seconds S [--shot PNG]]\n", argv0); return 2; } @@ -630,6 +631,7 @@ int main(int argc, char **argv) { if (!strcmp(mode, "--probe-vkexec")) return probe_vkexec(); if (!strcmp(mode, "--probe-astc")) return probe_astc(); if (!strcmp(mode, "--probe-zstd")) return probe_zstd(); + if (!strcmp(mode, "--probe-input")) return probe_input(); if (!strcmp(mode, "--probe-vkdevice")) return probe_vkdevice(); if (!strcmp(mode, "--probe-movie")) return probe_movie(); if (!strcmp(mode, "--prepare-shaders")) return vk_pipeline_prepare_shaders();