From 80adfd358907ecc8ba23fbb7718ce00ce219fe5a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 17 Jul 2026 11:20:07 +0100 Subject: [PATCH] Add loss-tolerant HID edge assist --- crates/muninn-daemon/src/main.rs | 27 ++++ .../examples/xinput_edge_observer.rs | 127 ++++++++++++++++++ crates/sleipnir-daemon/src/main.rs | 4 +- vendor/cultnet-rs/src/rudp.rs | 12 ++ 4 files changed, 169 insertions(+), 1 deletion(-) create mode 100644 crates/sleipnir-daemon/examples/xinput_edge_observer.rs diff --git a/crates/muninn-daemon/src/main.rs b/crates/muninn-daemon/src/main.rs index e50ddde..021989f 100644 --- a/crates/muninn-daemon/src/main.rs +++ b/crates/muninn-daemon/src/main.rs @@ -5737,6 +5737,7 @@ struct ActiveHidControllerRudpSource { pending_edges: VecDeque, edge_buttons: Vec, last_edge_sent: Option<(u64, u64)>, + last_edge_assist_at: Option, joystick_axes: [i16; 16], joystick_buttons: [bool; 32], latest_report: Option, @@ -5754,6 +5755,8 @@ struct ActiveHidControllerRudpSource { const MUNINN_HID_MAX_PENDING_EDGES: usize = 256; const MUNINN_HID_MAX_NEW_EDGES_PER_TURN: usize = 16; +const MUNINN_HID_EDGE_ASSIST_INTERVAL: Duration = Duration::from_millis(4); +const MUNINN_HID_MAX_ASSIST_EDGES_PER_TURN: usize = 4; fn active_hid_controller_rudp_source(source: MoveStateSource) -> ActiveHidControllerRudpSource { let epoch = timestamp_ns().unwrap_or_default().max(0) as u64; @@ -5771,6 +5774,7 @@ fn active_hid_controller_rudp_source(source: MoveStateSource) -> ActiveHidContro pending_edges: VecDeque::new(), edge_buttons: Vec::new(), last_edge_sent: None, + last_edge_assist_at: None, joystick_axes: [0; 16], joystick_buttons: [false; 32], latest_report: None, @@ -5847,6 +5851,7 @@ fn capture_button_edges(active: &mut ActiveHidControllerRudpSource, buttons: &[S active.next_edge_sequence = 1; active.pending_edges.clear(); active.last_edge_sent = None; + active.last_edge_assist_at = None; } } @@ -6117,8 +6122,30 @@ fn run_hid_controller_rudp_ingress( // semantic cursor owns ordering. Application ACKs only // retire history; they never gate the next edge. source.last_edge_sent = Some((edge.epoch, edge.edge_sequence)); + source.last_edge_assist_at = Some(Instant::now()); } } + if !source.pending_edges.is_empty() + && source + .last_edge_assist_at + .is_some_and(|sent_at| sent_at.elapsed() >= MUNINN_HID_EDGE_ASSIST_INTERVAL) + { + let assist_edges = source + .pending_edges + .iter() + .take(MUNINN_HID_MAX_ASSIST_EDGES_PER_TURN) + .cloned() + .collect::>(); + for edge in assist_edges { + if let Err(error) = + transport.send("hid.edge.assist", serde_json::to_vec(&edge)?) + { + eprintln!("Muninn HID edge assist warning: {error:#}"); + break; + } + } + source.last_edge_assist_at = Some(Instant::now()); + } sent_frames = sent_frames.saturating_add(1); last_sent_at = Some(Instant::now()); last_stale_log_at = None; diff --git a/crates/sleipnir-daemon/examples/xinput_edge_observer.rs b/crates/sleipnir-daemon/examples/xinput_edge_observer.rs new file mode 100644 index 0000000..860b03a --- /dev/null +++ b/crates/sleipnir-daemon/examples/xinput_edge_observer.rs @@ -0,0 +1,127 @@ +#[cfg(windows)] +fn main() -> anyhow::Result<()> { + use anyhow::Context; + use std::{ + env, fs, thread, + time::{Duration, Instant}, + }; + + #[repr(C)] + #[derive(Clone, Copy, Default)] + struct XInputGamepad { + buttons: u16, + left_trigger: u8, + right_trigger: u8, + thumb_lx: i16, + thumb_ly: i16, + thumb_rx: i16, + thumb_ry: i16, + } + + #[repr(C)] + #[derive(Clone, Copy, Default)] + struct XInputState { + packet_number: u32, + gamepad: XInputGamepad, + } + + #[link(name = "xinput")] + unsafe extern "system" { + fn XInputGetState(user_index: u32, state: *mut XInputState) -> u32; + } + + #[link(name = "winmm")] + unsafe extern "system" { + fn timeBeginPeriod(period_ms: u32) -> u32; + fn timeEndPeriod(period_ms: u32) -> u32; + } + + struct TimerResolution; + impl Drop for TimerResolution { + fn drop(&mut self) { + unsafe { + let _ = timeEndPeriod(1); + } + } + } + + let index = env::args().nth(1).and_then(|v| v.parse().ok()).unwrap_or(0); + let duration_seconds = env::args() + .nth(2) + .and_then(|v| v.parse().ok()) + .unwrap_or(30); + let output = env::args() + .nth(3) + .context("usage: xinput_edge_observer INDEX SECONDS OUTPUT")?; + unsafe { + let _ = timeBeginPeriod(1); + } + let _timer_resolution = TimerResolution; + + let started = Instant::now(); + let deadline = started + Duration::from_secs(duration_seconds); + let mut next_sample = started; + let mut last_sample = started; + let mut max_sample_gap = Duration::ZERO; + let mut connected_samples = 0_u64; + let mut presses = 0_u64; + let mut releases = 0_u64; + let mut seen = false; + let mut last_pressed = false; + let mut press_started = None; + let mut durations_ms = Vec::new(); + + while Instant::now() < deadline { + let now = Instant::now(); + max_sample_gap = max_sample_gap.max(now.saturating_duration_since(last_sample)); + last_sample = now; + let mut state = XInputState::default(); + if unsafe { XInputGetState(index, &mut state) } == 0 { + connected_samples += 1; + let pressed = state.gamepad.buttons & 0x1000 != 0; + if seen && pressed && !last_pressed { + presses += 1; + press_started = Some(now); + } + if seen && !pressed && last_pressed { + releases += 1; + if let Some(pressed_at) = press_started.take() { + durations_ms + .push(now.saturating_duration_since(pressed_at).as_secs_f64() * 1000.0); + } + } + last_pressed = pressed; + seen = true; + } + next_sample += Duration::from_millis(1); + let now = Instant::now(); + if next_sample > now + Duration::from_micros(250) { + thread::sleep(next_sample - now - Duration::from_micros(250)); + } + while Instant::now() < next_sample { + std::hint::spin_loop(); + } + if Instant::now().saturating_duration_since(next_sample) > Duration::from_millis(5) { + next_sample = Instant::now(); + } + } + + let durations = durations_ms + .iter() + .map(|v| format!("{v:.3}")) + .collect::>() + .join(","); + let result = format!( + "presses={presses} releases={releases} connected_samples={connected_samples} final_pressed={last_pressed} max_sample_gap_us={} durations_ms={durations}\n", + max_sample_gap.as_micros() + ); + fs::write(&output, &result).with_context(|| format!("writing {output}"))?; + print!("{result}"); + Ok(()) +} + +#[cfg(not(windows))] +fn main() { + eprintln!("xinput_edge_observer is Windows-only"); + std::process::exit(2); +} diff --git a/crates/sleipnir-daemon/src/main.rs b/crates/sleipnir-daemon/src/main.rs index b1b54b8..26edacf 100644 --- a/crates/sleipnir-daemon/src/main.rs +++ b/crates/sleipnir-daemon/src/main.rs @@ -2691,7 +2691,9 @@ fn receive_rudp_records(stream: &mut ActiveRudpStream, trace: bool) -> Result { + Ok(Some(frame)) + if frame.channel_id == "hid.edge" || frame.channel_id == "hid.edge.assist" => + { empty_polls = 0; let edge = decode_button_edge(&frame.payload) .ok_or_else(|| anyhow!("decoding Sleipnir HID button edge"))?; diff --git a/vendor/cultnet-rs/src/rudp.rs b/vendor/cultnet-rs/src/rudp.rs index 1998a06..f4bcd27 100644 --- a/vendor/cultnet-rs/src/rudp.rs +++ b/vendor/cultnet-rs/src/rudp.rs @@ -1514,6 +1514,12 @@ fn channel_send_options(channel_id: &str, now_ms: u64) -> CultNetRudpSendOptions sequenced: false, now_ms, }, + "hid.edge.assist" => CultNetRudpSendOptions { + reliable: false, + ordered: false, + sequenced: false, + now_ms, + }, "latest" => CultNetRudpSendOptions { reliable: false, ordered: false, @@ -1569,6 +1575,12 @@ mod socket_transport_tests { "{channel} uses application sequence and must not head-of-line block behind latest state" ); } + let assist = channel_send_options("hid.edge.assist", 7); + assert!( + !assist.reliable, + "edge assist must never accumulate retransmission debt" + ); + assert!(!assist.ordered && !assist.sequenced); let latest = channel_send_options("latest", 7); assert!(!latest.reliable); assert!(latest.sequenced);