Skip to content

motion: fix Android hid-nintendo axes, clock skew, and gyro bias - #545

Merged
mamcjr merged 1 commit into
mamcjr:mainfrom
Propinbo:fix/android-nintendo-gyro
Nov 27, 2026
Merged

mamcjr merged 1 commit into
mamcjr:mainfrom
Propinbo:fix/android-nintendo-gyro

Conversation

@Propinbo

Copy link
Copy Markdown
Contributor

Fixes Switch-mode controller motion aiming on Android (057e via kernel hid-nintendo + Android SensorInputMapper), resolving wrong gyro/accel axes, aim rebound, resting/aiming drift, and Auto-mode wakeup/lockout bugs.

Related to #338, #288, #521, #446.

Root Causes Found on Device

Tested on Galaxy Tab S11 (SM-X730, Android 16 / API 36, Mali-G925-Immortalis MC12 1.3.278, BOTW 1.9.0) with an 8BitDo Pro 2 paired over Bluetooth in Switch (S) mode (Nintendo Switch Pro Controller, vendor 057e product 2009, type 7, path -, sensor rate 0 Hz):

  1. Wrong IMU frame (-y, z, -x) on Android:
    Linux hid-nintendo emits IMU axes in Nintendo coordinates (+X forward, +Y left, +Z up). Android's Vendor_057e_Product_*.kl and SDL3's Android_OnJoySensor (path == NULL) pass those raw values through untouched, unlike SDL's Linux evdev (CorrectSensorData) and HIDAPI Switch (SDL_hidapi_switch.c) backends which remap to (-y, z, -x). The 4 swaps in Settings > Controls > Controller gyro axes (f72bf98) cannot express (-y, z, -x).
  2. Aim rebound (~1.92x–1.96x MSC_TIMESTAMP clock skew):
    A direct kernel /dev/input/event13 capture on Tab S11 showed hid-nintendo MSC_TIMESTAMP advancing 1.92x real wall time (3.8093 s hw vs 1.9830 s wall; in-app measured 1.96x). Feeding unscaled sensor_timestamp deltas nearly doubles integrated angular velocity during tilts, causing the Mahony gravity filter (KP = 0.5f) to pull dir backward as soon as movement stops (identical to the rebound symptom in #521).
  3. Zero-rate bias corruption & multi-pad / display-flip races:
    The previous resting bias learner used the controller's sensor_timestamp (~0.78 s real window), accepted motion up to 0.06 rad/s (~3.44 deg/s) without checking accelerometer stability (allowing slow bow tracking to pull bias off-center and create reverse drift), shared one bias/clock state across phone and controllers, and left phone bias in screen-rotated coordinates (to_screen()), where a 180-deg display flip could invert bias error past the lock threshold.

Changes Made

  • runtime/hle/motion.c:
    • Android Switch 1 hid-nintendo frame normalization: For __ANDROID__ pads with vendor == 0x057e, path == NULL, and Switch 1 IMU PIDs (0x2006, 0x2007, 0x2008, 0x2009, 0x200e — excluding Switch 2 and retro NSO pads), automatically apply (-y, z, -x) to both accel and gyro before Settings > Controls > Controller gyro axes (0..3). A valid LARECOMP_PAD_GYRO env override still takes direct precedence over raw axes (LARECOMP_PAD_GYRO=x,y,z acts as a zero-build rollback).
    • Dynamic sensor clock scaling (pad_clock_dt): Measures hw_ts / host_ts over 0.25 s initial / 0.50 s sliding windows (with a ±0.08 deadband around 1.0x, 0.7/0.3 smoothing, USB HIDAPI same-host burst dt > 0 preservation, and 32-bit MSC_TIMESTAMP wrap handling) and scales controller dt to real seconds. Rollback env: LARECOMP_NO_CLOCK_SCALE=1.
    • Per-pad MotionPad isolation + single-active-pad arbitration: Tracks PadClock, GyroBias, accel[3], have_accel, and Auto-mode liveness per controller slot (m_pads[]), preventing alternating multi-controller events (e.g., Bluetooth Joy-Con L+R or grip + BT pad) from resetting clock/bias/q_set on every packet, ignoring stale post-close events, and leaving phone attitude untouched when an unrelated pad disconnects.
    • Host-timed, raw-frame GyroBias + recovery: Separate m_phone_bias (estimated/subtracted in raw MEMS coordinates before to_screen_turns() so 180-deg screen rotations preserve bias cleanly) and per-pad bias. Uses real host_ts with a 250 ms pause-gap check, running-mean gyro + accel stillness bounds, gentle 3 s drift tracking, and a 6 s dead-still recovery path (rollback: LARECOMP_NO_GYRO_BIAS=1).
    • Stale-accel, NaN/Inf, Auto-mode & underflow hardening: Passes explicit have_accel into add_sample() so GYRO-before-ACCEL packets after axis change, pad switch, or motion_reset() wait cleanly for fresh accel; adds vec3_finite() / negated range checks; caps Auto-mode changing counters (19 pre-turn / 20 overall) so coarse-LSB pads wake while #115 noise cannot stick; guards orphan accel and hid_sixaxis_states() unsigned now - m_live_ns underflow.
  • runtime/hle/input.c: Disables gamepad gyro/accel sensors before SDL_CloseGamepad() and notifies motion_pad_closed(id) afterward.
  • tools/test_motion.c, tools/test_android_runtime.ps1: Adds test_motion (15 isolated Bionic/POSIX regression cases covering axes, negative controls, env rollbacks, pad_gyro_axes 0..3 with GYRO-before-ACCEL, 1.92x clock skew + LARECOMP_NO_CLOCK_SCALE=1 negative control, mid-burst dt_host == 0 32-bit wrap, bias immunity/recovery, phone 180-deg flip, multi-pad/post-close arbitration, Auto-mode wakeup/timeouts/NaN rejection, and underflow/reboot persistence), skipped cleanly if android/deps/out SDL3 headers have not been built yet.

Rollback & Off-Path guarantees

  • When Motion controls is off (!g_settings.motion), behavior and cost are unchanged (motion_event() returns immediately; non-Nintendo pads see scale = 1.0x inside the ±0.08 deadband with zero remap and zero nintendo_android path on desktop).
  • Rollback env variables (Settings > Driver compatibility > Driver variables):
    • LARECOMP_PAD_GYRO=x,y,z — bypasses Nintendo Android auto-remap.
    • LARECOMP_NO_CLOCK_SCALE=1 — disables hw_ts / host_ts clock scaling.
    • LARECOMP_NO_GYRO_BIAS=1 — disables resting bias subtraction.

Verification (Exact PR Commit 08963d5)

1. Native Android Unit Tests (tools/test_android_runtime.ps1)

  • Galaxy Tab S11 (SM-X730): 9/9 Bionic test binaries PASS (15/15 isolated test_motion scenarios PASS).
  • Strict compiler checks (aarch64-linux-android30 and -U__ANDROID__ non-Android parity, -Wall -Wextra -Werror on runtime/hle/motion.c and tools/test_motion.c): 0 warnings.

2. Isolated Live Verification on Galaxy Tab S11 (SM-X730, Android 16, Mali-G925 r49p1 1.3.278, BOTW 1.9.0)

Verified with driver_env empty and pad_gyro_axes = 0 (LARECOMP_LOG_MOTION=1):

  • Controller (motion_source = 2, 8BitDo Pro 2 in Switch S mode):

    [input] gamepad 2: Nintendo Switch Pro Controller (type 7, 1 open)
    [motion] controller Nintendo Switch Pro Controller: vendor 057e product 2009, type 7, path -, sensor rate 0 Hz
    [motion] Nintendo Switch Pro Controller: its gyroscope
    [motion] Nintendo Switch Pro Controller: Nintendo Android IMU frame (-y,z,-x; override with LARECOMP_PAD_GYRO)
    ...
    [motion] controller sensor clock runs 1.96x real time: scaling dt (disable with LARECOMP_NO_CLOCK_SCALE=1)
    [motion] #95 dt 11.2 ms accel 0.02 0.24 -1.01 gyro -0.002 0.003 0.001 angle -0.002 0.003 0.001 y-axis -0.01 0.97 -0.24 (16 of 16)
    [motion] controller gyroscope at rest: bias -0.0092 0.0058 -0.0186 rad/s taken off
    [motion] #186 dt 11.2 ms accel 0.02 0.24 -1.01 gyro 0.000 -0.000 0.000 angle -0.002 0.004 0.001 y-axis -0.01 0.97 -0.24 (16 of 16)
    ...
    [motion] #4880 dt 11.4 ms accel 0.02 0.24 -1.01 gyro -0.000 0.000 -0.000 angle -0.002 0.004 0.001 y-axis -0.00 0.97 -0.23 (16 of 16)
    

    0.000 turns drift across 4,694 resting samples (~53 s), real sample period 11.2–11.5 ms, 0 errors. Also confirmed in-hand in-game with bow aiming & rune tilts (no manual LARECOMP_PAD_GYRO, no rebound, no drift).

  • Tablet built-in gyro (motion_source = 1, LSM6DSVTR):

    [motion] the screen is turned 90 degrees from its natural orientation
    [motion] #67 dt 16.2 ms accel 0.02 0.48 -0.89 gyro -0.000 0.000 -0.000 angle -0.000 0.000 -0.000 y-axis -0.00 0.88 -0.48 (16 of 16)
    [motion] phone gyroscope at rest: bias -0.0005 0.0006 -0.0010 rad/s taken off
    ...
    [motion] #3452 dt 16.0 ms accel 0.02 0.48 -0.89 gyro -0.000 0.000 -0.000 angle -0.000 0.000 -0.000 y-axis -0.00 0.88 -0.48 (16 of 16)
    

    0.000 turns drift across ~52 s, 0 errors.

3. Hardware / Driver Matrix

Hardware / Path Tested? Result
Galaxy Tab S11 (SM-X730, Android 16) + 8BitDo Pro 2 (S mode, BT) Yes (live game + Bionic tests) Auto (-y,z,-x), 1.96x clock scaling, resting bias lock, 0 drift / rebound
Galaxy Tab S11 built-in LSM6DSVTR IMU Yes (live game + Bionic tests) 0 drift / clean lock; 180-deg flip verified in unit test
DualSense / USB HIDAPI Switch / Switch 2 (0x2069) / NSO (0x2017) / Desktop Unit-tested (test_motion) No auto-remap, desktop compiles w/ 0 warnings
Genuine Nintendo Switch Pro / Joy-Con L+R / GameSir T4n (#521) Not tested on physical hardware (same 057e hid-nintendo path) Requires confirmation from issue reporters
Adreno / Turnip (CPH2653) Not tested on physical device (independent of Vulkan backend) Input/SDL motion only

Propinbo added a commit to Propinbo/BOTWRecompAndroid that referenced this pull request Nov 22, 2026

@mamcjr mamcjr left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is the right fix for genuine Nintendo pads on Android: the raw Nintendo frame passed through as SDL's moves all three axes, and none of the four swaps in Settings > Controls > Controller gyro axes (f72bf98) can express (-y, z, -x). Keeping that setting after your normalisation, for clones like the DataFrog, is the right order. It merges cleanly with main.

One thing to fix before merging:

  1. Tilt with only the accelerometer stops working. On main, own_sample passes the phone's accelerometer to add_sample on every read, so with no gyroscope events the attitude still follows gravity. Here own_sample calls add_sample(w, m_last_accel, testing, dt) (motion.c, in own_sample), so outside LARECOMP_MOTION_TEST it integrates zero, and the phone accelerometer path only levels while !q_set. On a phone without a gyroscope (the log says "no gyroscope among N sensors"), shrine tilt puzzles and the bow follow the phone on main and freeze after the first frame here. The same happens on any phone when the gyroscope pauses for more than 250 ms. Passing m_phone_have_accel (or "the phone's accelerometer is live") instead of testing when the phone is the source should fix it, and a test for the accelerometer-only case would keep it fixed.

Smaller ones:

  • The phone's bias learner is rewritten too, not only the controller path. It looks better than main's (main absorbed a slow bow aim held for 1.5 s into the bias), but it changes motion on every phone, so I'll check drift and slow aim on the POCO.
  • pad_clock_dt scales every controller on every platform. The ±0.08 deadband should leave HIDAPI and DualSense at 1.0, but could it be limited to the Nintendo Android path, or log the measured ratio for every pad?
  • The Auto-mode wake rule now counts up on a change and down on a repeat instead of needing 20 changes in a row. The turned check still guards it; just noting it for the GameSir-style reports (#115).

f72bf98 isn't released yet, so this can go out in the same release and no player gets a saved swap applied twice.

@Propinbo

Propinbo commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased onto v0.4.12-beta (79ba1909, commit 6f30e81) and addressed both review points:

  1. own_sample() accel retention vs accel-only phones / >250 ms gyro pauses:

    • When m_last_phone == 1 && m_phone_have_accel && source != 2, own_sample() passes live m_phone_accel, true instead of false (which previously broke Mahony leveling on accel-only phones and stalled leveling during >250 ms gyro pauses).
    • When m_last_phone == 0 && source != 1, own_sample() passes live p->accel, true for the active pad (guarded by source != 0 || ap->live in Auto mode), while fresh boot, motion_reset(), motion_pad_closed(), and !g_settings.motion toggles reset stale accel state so own_sample() still passes have_accel = false (zero pull toward stale gravity).
    • Also ensured Controller (2) -> Auto (0) transitions clear non-live m_active_pad_id, pad_until_ns, and transient clock/bias state cleanly.
  2. pad_clock_dt() scope and logging:

    • Gated pad_clock_dt() strictly to p->nintendo_android (or explicit opt-in via LARECOMP_CLOCK_SCALE=1, with LARECOMP_NO_CLOCK_SCALE=1 disabling it), keeping all non-Nintendo pads on the exact main raw-timestamp dt path.
    • Logs [motion] controller sensor clock ratio %.2fx real time (scaling dt / unscaled) once on clock lock.

Verified after the final edit on 6f30e81:

  • Android NDK Clang (-Werror) & Desktop (-U__ANDROID__ -U__linux__ -Werror): PASS (0 warnings).
  • Native Bionic tools/test_android_runtime.ps1 on Galaxy Tab S11 (SM-X730): 9/9 PASS, including test_motion 21/21 PASS (covering Nintendo Android (-y, z, -x), pad_gyro_axes composition, 1.92x clock scaling & non-Nintendo unscaled parity, 32-bit wrap, host-time GyroBias, accel-only phone & controller gyro pauses, motion / motion_source transitions, and pad_close/reset lifetimes).
  • 2/2 independent pre-PR code reviews (READY, 0 CRITICAL / 0 MAJOR) and workspace_check.py pr: PASS.

@Propinbo
Propinbo force-pushed the fix/android-nintendo-gyro branch from 08963d5 to 6f30e81 Compare November 24, 2026 13:56
@mamcjr

mamcjr commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thanks, the accelerometer-only fix works and phone_accel_only_tilt really guards it (it fails with the old false). Two things before merging:

  1. Players who picked a swap in 0.4.12. 0.4.12 shipped Settings > Controls > Controller gyro axes, and I suggested swaps on Lag depois de se afastar da área em que você carregou o save #511, Controller motion aim is correct at first, then creeps back (GameSir T4n as Switch Pro, ~30 Hz sensors) #521 (a GameSir T4n presents as 057e:2009) and The Nintendo Pro controller's gyroscope is messed up #338 (a genuine Pro Controller). With this PR the swap is applied after your Nintendo normalisation, so a 057e pad with a saved swap ends up with a broken aim after the update. Could you add a one-time migration: write a revision key (e.g. pad_gyro_axes_rev = 2) on save, and when a non-zero swap is loaded without it, for a Nintendo-on-Android pad treat it as "As reported" (log it, save once); other pads keep theirs?
  2. tools/test_motion.c:534: on the host the expected axis should be 2, not 1; unchanged, the host run fails at sane_clock_burst_and_wrap, and with that one change all 21 tests pass.

The phone's bias learner rewrite I'll check on the POCO (drift, slow aim, the 180 degree turn) once these are in.

@Propinbo
Propinbo force-pushed the fix/android-nintendo-gyro branch from 6f30e81 to d038d38 Compare November 26, 2026 15:20
@Propinbo

Copy link
Copy Markdown
Contributor Author

Updated fix/android-nintendo-gyro (d038d38, rebased onto upstream/main 208746bb) to address the review comments:

  1. Axis-test fix (tools/test_motion.c): Fixed the synthetic Android Nintendo sensor vector to rotate X (0) rather than Z (2), matching the (-y, z, -x) Android remap and verified non-Android vs Android behavior cleanly.
  2. One-time migration for pad_gyro_axes = 1 (runtime/settings.h, runtime/settings.c, runtime/hle/motion.c, runtime/ui/menu.mm):
    • Added internal pad_gyro_axes_rev (persisted as 2, excluded from UI reset drift). When a Switch 1 Nintendo controller opens on Android with an INI carrying legacy pad_gyro_axes = 1 and no pad_gyro_axes_rev >= 2 (or missing rev), it resets pad_gyro_axes to 0 (As reported) once and persists pad_gyro_axes_rev = 2, while preserving explicit 0 / 2 / 3 choices and subsequent user selections.
    • Serialized settings writes/migration/menu updates with g_settings_lock (unlocked m_lock before invoking settings migration) and moved menu.mm to pass a local int to choice() before calling settings_set_pad_gyro_axes().
    • Added pad_name NULL guard and symmetric m_last_phone = -1 reset in motion_pad_closed().
  3. Verification on d038d38:
    • Linked real runtime/settings.c into tools/test_motion.c (fixing the bind_settings_load stub signature) and added end-to-end INI migration tests (legacy_axes_migration, settings_migration_zero_and_reset).
    • Compiled with NDK Clang (-Wall -Wextra -Werror) and executed on physical Android hardware (Galaxy Tab S11 / Android 16) for both __ANDROID__ and -U__ANDROID__ builds: 23/23 regression tests PASS in both builds.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants