From 690d3b27a59c15b7d02590ea5d7a70e7fab3db7e Mon Sep 17 00:00:00 2001 From: Mariano Abad Date: Wed, 23 Sep 2026 22:20:00 -0300 Subject: [PATCH] drm: measure the cursor hotspot and confirm it before publishing On a driver without HOTSPOT_X/Y the wire carries infer_hotspot's guess, which the bitmap cannot get right for a shape whose click point the theme put where the alpha does not mark it. This process injects the tip and the plane origin rides every frame: once both are still, tip - origin is the hotspot. Only a guessed shape is measured. The first measurement is a candidate and changes nothing visible. A second measurement confirms it only from another stable plane position and another peer sample, and then the retained candidate is the one value that reaches the cache, the served hotspot, the id remix and the delivery. Near what is served, nothing changes, even when the value is also near the wire, so a correction a few px from the wire does not flap; near the wire otherwise, the wire is served and the cached correction is dropped. A stable position is measured at most once, a layout generation change stops measurement once the display service's poll has seen it, and the cache is read only behind the context gate, so a correction measured upright never reaches a rotated output. Each of these gates has a test that goes red with the check removed or altered (file restored byte for byte afterwards): publish the first measurement -> retained candidate, same sample, still plane, local nudge same sample confirms -> same sample never confirms, local nudge confirm with the new value -> retained candidate, near wire, in band drop the near-wire arm -> near wire serves the wire drop the in-band arm -> in band changes nothing visible drop the re-store after clear-on-cap -> in band stays cached measure a kernel-measured hotspot -> never calibrated at the origin read the cache without a context -> not served without a context drop the once-per-position flag -> still plane measured once drop the transform gate -> context only for an upright output swap phys and extent -> the arithmetic, the scaled context drop the clear-on-cap -> cache bounded drop the partial-snapshot gate -> context only for an identity match drop the generation check -> closed intervals compare the wire before the served -> in band with both keeps the served correction --- .github/workflows/flutter-build.yml | 4 + src/server/drm_capturer.rs | 693 +++++++++++++++++++++++++++- 2 files changed, 693 insertions(+), 4 deletions(-) diff --git a/.github/workflows/flutter-build.yml b/.github/workflows/flutter-build.yml index cac2d770d..083502239 100644 --- a/.github/workflows/flutter-build.yml +++ b/.github/workflows/flutter-build.yml @@ -2080,6 +2080,10 @@ jobs: cargo test --locked --lib --features drm drm_capturer_tests run_drm_tests "rustdesk ipc::test" \ cargo test --locked --lib --features drm ipc::test + run_drm_tests "rustdesk cursor_pos_tests" \ + cargo test --locked --lib --features drm cursor_pos_tests + run_drm_tests "rustdesk peer_abs_sample_tests" \ + cargo test --locked --lib --features drm peer_abs_sample_tests run_drm_tests "scrap hotspot_provenance_tests" \ cargo test --locked -p scrap --features drm hotspot_provenance_tests run_drm_tests "scrap hotspot_guess_tests" \ diff --git a/src/server/drm_capturer.rs b/src/server/drm_capturer.rs index 585fe6a4c..69164f9d9 100644 --- a/src/server/drm_capturer.rs +++ b/src/server/drm_capturer.rs @@ -661,6 +661,8 @@ async fn recv_thread( // A cursor that arrived before new() stored the session transform, held for replay. Only the // newest matters; the 200 ms recv timeout guarantees this is retried even on an idle wire. let mut pending_cursor: Option<(u64, u32, u32, i32, i32, bool, Vec)> = None; + // The shape being measured, or None: hidden, kernel-measured, or no context for this stream. + let mut cal: Option = None; let end_reason = loop { if stop.load(Ordering::SeqCst) { break "stopped".to_owned(); @@ -669,8 +671,9 @@ async fn recv_thread( let t = shared.cursor_transform.load(std::sync::atomic::Ordering::Acquire); if t != TRANSFORM_PENDING { if let Some((id, width, height, hotx, hoty, hot_measured, raw)) = pending_cursor.take() { - deliver_drm_cursor( - display, cursor_epoch, id, width, height, hotx, hoty, hot_measured, raw, t, + let ctx = *shared.cal_context.lock().unwrap(); + cal = on_cursor_shape( + display, cursor_epoch, ctx, id, width, height, hotx, hoty, hot_measured, raw, t, ); } } @@ -682,6 +685,17 @@ async fn recv_thread( }; match msg { Data::DrmFrameDmabuf(desc) => { + if cal.is_some() { + on_cursor_plane( + &mut cal, + desc.cursor_pos, + super::input_service::last_peer_abs_sample, + super::display_service::wayland_layout_drifted(), + scrap::wayland::display::wayland_snapshot_generation(), + display, + cursor_epoch, + ); + } let conv = match converter.as_mut() { Some(c) => c, None => break "no DRM render node; cannot convert dma-buf frame".to_owned(), @@ -740,8 +754,19 @@ async fn recv_thread( Data::DrmFrame { width, height, - cursor_pos: _, + cursor_pos, } => { + if cal.is_some() { + on_cursor_plane( + &mut cal, + cursor_pos, + super::input_service::last_peer_abs_sample, + super::display_service::wayland_layout_drifted(), + scrap::wayland::display::wayland_snapshot_generation(), + display, + cursor_epoch, + ); + } // `frame()` hands this to PixelBuffer::new, which derives the stride as // `data.len() / height`: height==0 would DIVIDE BY ZERO. if width == 0 || height == 0 { @@ -798,12 +823,15 @@ async fn recv_thread( } let t = shared.cursor_transform.load(std::sync::atomic::Ordering::Acquire); if t == TRANSFORM_PENDING { + cal = None; pending_cursor = Some((id, width, height, hotx, hoty, hot_measured, raw)); } else { pending_cursor = None; - deliver_drm_cursor( + let ctx = *shared.cal_context.lock().unwrap(); + cal = on_cursor_shape( display, cursor_epoch, + ctx, id, width, height, @@ -910,12 +938,31 @@ pub struct DrmCursorData { pub colors: Vec, } + // The kernel only exposes a cursor hotspot on DRIVER_CURSOR_HOTSPOT drivers (VMs); on bare metal // the wire carries `infer_hotspot`'s guess, which the bitmap alone cannot get right for a shape // whose click point the theme put where the alpha does not mark it. But // `plane_origin = pointer_tip - hotspot`, this process injects the tip itself, and the plane // position rides every frame: once both sit still, the difference IS the hotspot. +type Pos = (i32, i32); +type Hotspot = (i32, i32); + +/// The plane must hold one position this many consecutive frames, not counting the frame that +/// first reported it, before a measurement is taken ... +const CURSOR_CAL_STABLE_TICKS: u32 = 3; +/// ... and a position still for longer than this is not measured any more: the peer point that +/// would be subtracted is that much staler. +const CURSOR_CAL_WINDOW_TICKS: u32 = 33; +/// Two measurements this close agree; a correction this close to what is drawn is jitter. The +/// peer coordinate is quantized to logical px, so at a fractional scale a measurement wobbles by +/// ceil(scale) physical px between positions. +const CURSOR_CAL_TOLERANCE: i32 = 2; +/// The last absolute peer move must be at least this old (the compositor consumed it) ... +const CURSOR_CAL_MIN_INPUT_AGE_MS: u64 = 150; +/// ... and at most this old: a local user may have moved the pointer since. +const CURSOR_CAL_MAX_INPUT_AGE_MS: u64 = 10_000; + /// The calibration geometry of one stream, resolved once when the capturer is built, from the /// wayland snapshot the frame transform comes from. Immutable for the session; a layout change /// bumps the snapshot generation, which stops measurement, and rebuilds the capturer. @@ -964,6 +1011,285 @@ fn calibration_context( }) } +/// Pure geometry. The injected point is in the logical layout (`logical_rects_of`: a lone output +/// at its oriented physical size, several outputs at their logical sizes) and the plane origin is +/// in this CRTC's scanout px, so the point is required to fall inside this output's rect (else +/// the pointer is on another monitor and that stream measures), scaled into scanout space, and +/// only then is the plane subtracted. An answer outside the bitmap is a race, an edge clip or a +/// local user having moved the pointer, not a hotspot. +fn measure_hotspot( + ctx: &CalContext, + injected: Pos, + plane: Pos, + cursor_size: (i32, i32), +) -> Option { + let (ax, ay, aw, ah) = ctx.rect; + let (px, py) = ctx.physical_size; + let (ix, iy) = injected; + if ix < ax || ix >= ax + aw || iy < ay || iy >= ay + ah { + return None; + } + let tipx = ((ix - ax) as f64 * px as f64 / aw as f64).round() as i32; + let tipy = ((iy - ay) as f64 * py as f64 / ah as f64).round() as i32; + let h = (tipx - plane.0, tipy - plane.1); + if h.0 < 0 || h.1 < 0 || h.0 >= cursor_size.0 || h.1 >= cursor_size.1 { + return None; + } + Some(h) +} + +/// What one stream knows about the shape it is currently showing. +struct CursorCal { + /// The wire id: what the cache is keyed by, and what a corrected id is remixed from. + id: u64, + width: u32, + height: u32, + /// Kept so a confirmed measurement can re-deliver the same pixels under the new hotspot. + raw: Vec, + ctx: CalContext, + /// What the producer reported. + wire_hot: Hotspot, + /// What the client is being served: the cache's confirmed value, else the wire's. + current_hot: Hotspot, + /// An unconfirmed measurement, with the peer sample it was taken against. + candidate: Option<(Hotspot, u64)>, + plane: Option, + stable_ticks: u32, + measured_this_position: bool, +} + +/// Only a hotspot the producer guessed is measured; kernel truth is never overridden. A producer +/// that predates the provenance field arrives as measured (`legacy_hot_measured`), so it is never +/// measured over either. +fn calibratable(id: u64, hot_measured: bool) -> bool { + id != scrap::drm_reader::HIDDEN_CURSOR_ID && !hot_measured +} + +/// One frame reported where the plane is. +fn update_plane_stability(c: &mut CursorCal, p: Pos) { + if c.plane != Some(p) { + c.plane = Some(p); + c.stable_ticks = 0; + c.measured_this_position = false; + return; + } + c.stable_ticks = c.stable_ticks.saturating_add(1); +} + +/// Each stable plane position yields at most one measurement, and only inside the window. +fn settled_unmeasured(c: &CursorCal) -> bool { + !c.measured_this_position + && (CURSOR_CAL_STABLE_TICKS..=CURSOR_CAL_WINDOW_TICKS).contains(&c.stable_ticks) +} + +/// The peer sample a measurement may subtract from, or none: the layout must not have moved +/// since the context was built (the remap flag is a secondary guard for the window in which the +/// promotion is still owed), the sample must have been mapped against that same layout, and it +/// must be old enough to have been consumed and young enough to still describe the pointer. +/// The generation and the flag are both advanced by the display service's layout poll, so a +/// monitor moved mid-session is seen up to one check interval late; a measurement inside that +/// window is bounded by the bitmap and replaced by the next confirmed pair. +fn usable_sample( + ctx: &CalContext, + s: Option, + drifted: bool, + current_gen: u64, +) -> Option<(Pos, u64)> { + if drifted || current_gen != ctx.built_gen { + return None; + } + let s = s?; + if s.gen != ctx.built_gen { + return None; + } + if !(CURSOR_CAL_MIN_INPUT_AGE_MS..=CURSOR_CAL_MAX_INPUT_AGE_MS).contains(&s.age_ms) { + return None; + } + Some((s.pos, s.seq)) +} + +fn near(a: Hotspot, b: Hotspot) -> bool { + (a.0 - b.0).abs() <= CURSOR_CAL_TOLERANCE && (a.1 - b.1).abs() <= CURSOR_CAL_TOLERANCE +} + +/// The confirmation policy. `Some` only when a second measurement agrees with the candidate, +/// and then it IS the candidate, never the second raw value. Two measurements against the same +/// peer sample are not independent: the plane moved and the peer did not, which is what a local +/// hand on the mouse looks like, so they never confirm each other. +fn observe_measurement(c: &mut CursorCal, m: Hotspot, seq: u64) -> Option { + match c.candidate { + Some((_, kseq)) if kseq == seq => None, + Some((k, _)) if near(k, m) => { + c.candidate = None; + Some(k) + } + _ => { + c.candidate = Some((m, seq)); + None + } + } +} + +/// Both decisions are taken on the one accepted value. What is served is compared first: near +/// it, nothing visible changes and the served value stays cached. That includes a value that is +/// also near the wire, which a correction 3 or 4 px from the wire makes possible, and comparing +/// the wire first there would flap the served hotspot and the id on every confirmation. Near the +/// wire otherwise, the producer's guess was right: the wire value is served and a correction +/// cached earlier for this shape is dropped. Otherwise the accepted value is cached and served. +fn apply_confirmed_hotspot(c: &mut CursorCal, accepted: Hotspot, display: i32, cursor_epoch: u64) { + if near(accepted, c.current_hot) { + if c.current_hot == c.wire_hot { + // The wire is served and was right: nothing of ours stays cached for this shape. + forget_cursor_cal(c.id); + } else if cached_cursor_cal(c.id) != Some(c.current_hot) { + store_cursor_cal(c.id, c.current_hot); + } + return; + } + let target = if near(accepted, c.wire_hot) { + forget_cursor_cal(c.id); + c.wire_hot + } else { + store_cursor_cal(c.id, accepted); + accepted + }; + debug_assert_ne!(target, c.current_hot, "not near the served value, so a change"); + c.current_hot = target; + let id = if target == c.wire_hot { + c.id + } else { + remix_cursor_id(c.id, target.0, target.1) + }; + log::info!( + "drm: cursor hotspot for display {display}: confirmed {target:?} (wire {:?}); serving it", + c.wire_hot + ); + deliver_drm_cursor( + display, + cursor_epoch, + id, + c.width, + c.height, + target.0, + target.1, + false, + c.raw.clone(), + 0, + ); +} + +/// Confirmed hotspots per wire cursor id, so a shape the compositor reuses (arrow, beam, arrow) +/// is served right from its first frame. Bounded by wholesale clearing; ids churn on theme or +/// size changes and re-measuring is cheap. Read in one place, behind the context gate. +static CURSOR_CAL_CACHE: Mutex> = Mutex::new(BTreeMap::new()); +const CURSOR_CAL_CACHE_CAP: usize = 64; + +fn store_cursor_cal(wire_id: u64, h: Hotspot) { + let mut cache = CURSOR_CAL_CACHE.lock().unwrap(); + if cache.len() >= CURSOR_CAL_CACHE_CAP && !cache.contains_key(&wire_id) { + cache.clear(); + } + cache.insert(wire_id, h); +} +fn forget_cursor_cal(wire_id: u64) { + CURSOR_CAL_CACHE.lock().unwrap().remove(&wire_id); +} +fn cached_cursor_cal(wire_id: u64) -> Option { + CURSOR_CAL_CACHE.lock().unwrap().get(&wire_id).copied() +} + +/// Mixes the hotspot into the wire id on top of the reader's fold, so `run_cursor` sees the +/// corrected shape as a change and caches it under its own key; the id a peer sees is the content +/// hash made in input_service, which covers the hotspot by itself. A collision is as unlikely as +/// between any two 64-bit ids and would serve one cached bitmap for another until the next change. +fn remix_cursor_id(wire_id: u64, hotx: i32, hoty: i32) -> u64 { + let mut id = wire_id ^ 0x9e37_79b9_7f4a_7c15; + for v in [hotx as u32 as u64, hoty as u32 as u64] { + id ^= v; + id = id.wrapping_mul(1099511628211); + } + id +} + +/// A shape arrived. Publish it as the producer sent it, or under a confirmed correction the +/// cache holds for it, and start measuring it when there is a context and it is a guess. The +/// cache is consulted here and nowhere else, so without a context a correction measured on an +/// upright output can never reach a rotated one. +#[allow(clippy::too_many_arguments)] +fn on_cursor_shape( + display: i32, + cursor_epoch: u64, + ctx: Option, + id: u64, + width: u32, + height: u32, + hotx: i32, + hoty: i32, + hot_measured: bool, + raw: Vec, + t: i32, +) -> Option { + let cal = ctx.filter(|_| calibratable(id, hot_measured)).map(|ctx| { + debug_assert_eq!(t, 0, "a calibration context implies an upright output"); + let wire_hot = (hotx, hoty); + CursorCal { + id, + width, + height, + raw: raw.clone(), + ctx, + wire_hot, + current_hot: cached_cursor_cal(id).unwrap_or(wire_hot), + candidate: None, + plane: None, + stable_ticks: 0, + measured_this_position: false, + } + }); + let (pid, hx, hy) = match &cal { + Some(c) if c.current_hot != c.wire_hot => ( + remix_cursor_id(id, c.current_hot.0, c.current_hot.1), + c.current_hot.0, + c.current_hot.1, + ), + _ => (id, hotx, hoty), + }; + deliver_drm_cursor(display, cursor_epoch, pid, width, height, hx, hy, hot_measured, raw, t); + cal +} + +/// A frame reported where the plane is. The sample is read only once the plane has settled, so +/// most frames cost one comparison and no lock. +fn on_cursor_plane( + cal: &mut Option, + pos: Option, + sample: impl FnOnce() -> Option, + drifted: bool, + current_gen: u64, + display: i32, + cursor_epoch: u64, +) { + let (Some(c), Some(p)) = (cal.as_mut(), pos) else { + return; + }; + update_plane_stability(c, p); + if !settled_unmeasured(c) { + return; + } + let Some((injected, seq)) = usable_sample(&c.ctx, sample(), drifted, current_gen) else { + return; + }; + c.measured_this_position = true; + let Some(m) = measure_hotspot(&c.ctx, injected, p, (c.width as i32, c.height as i32)) else { + return; + }; + let Some(accepted) = observe_measurement(c, m, seq) else { + log::debug!("drm: cursor hotspot for display {display}: measured {m:?} (sample {seq}), waiting for a second one"); + return; + }; + apply_confirmed_hotspot(c, accepted, display, cursor_epoch); +} + static DRM_CURSOR: Mutex> = Mutex::new(BTreeMap::new()); // Monotonic per-stream tag: a rebuilt stream reuses the display index, so a torn-down stream drops // its entry ONLY if the epoch still matches. @@ -2594,6 +2920,193 @@ mod drm_capturer_tests { assert!(matches!(c.frame(Duration::from_millis(50)), Ok(_))); } + // ---- cursor hotspot calibration ---- + // The cache and DRM_CURSOR are process-wide and libtest runs tests concurrently: every test + // below has its own display id (9_700..9_799) and its own shape id, and the ones that read + // the cache back hold this lock, because one of them clears it. + static CACHE_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + const CAL_GEN: u64 = 7; + fn ctx1() -> CalContext { + CalContext { + rect: (0, 0, 1920, 1080), + physical_size: (1920, 1080), + built_gen: CAL_GEN, + } + } + fn peer(pos: Pos, seq: u64) -> crate::server::input_service::PeerAbsSample { + crate::server::input_service::PeerAbsSample { + pos, + age_ms: 400, + seq, + gen: CAL_GEN, + } + } + /// A guessed shape arriving on a stream with a context, as the receive loop registers it. + fn arrive(display: i32, epoch: u64, shape: u64, wire: Hotspot) -> Option { + on_cursor_shape( + display, + epoch, + Some(ctx1()), + shape, + 64, + 64, + wire.0, + wire.1, + false, + vec![0; 64 * 64 * 4], + 0, + ) + } + /// One stable plane position against one sample: the first frame reports the move, the + /// next STABLE frames settle it, and the last one measures. + fn settle( + cal: &mut Option, + plane: Pos, + sample: Option, + display: i32, + epoch: u64, + ) { + for _ in 0..=CURSOR_CAL_STABLE_TICKS { + on_cursor_plane(cal, Some(plane), || sample, false, CAL_GEN, display, epoch); + } + } + fn served(display: i32) -> (u64, i32, i32) { + let map = DRM_CURSOR.lock().unwrap(); + let (_, c) = map.get(&display).expect("a shape was published for this display"); + (c.id, c.hotx, c.hoty) + } + fn plain(shape: u64) -> u64 { + fold_cursor_id(shape, 0) + } + fn corrected(shape: u64, h: Hotspot) -> u64 { + fold_cursor_id(remix_cursor_id(shape, h.0, h.1), 0) + } + + // Two stable positions against two samples: the first measurement is a candidate and changes + // nothing visible; the second, 1 px away, confirms it, and everything that follows uses the + // retained candidate, not the second sample. Mutations caught: publishing the first + // measurement, confirming with the new value, dropping the seq check. + #[test] + fn a_confirming_measurement_publishes_the_retained_candidate_not_the_new_sample() { + let _serial = CACHE_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner()); + let (d, e, shape) = (9_700, next_cursor_epoch(), 0x7a00); + forget_cursor_cal(shape); + let mut cal = arrive(d, e, shape, (4, 4)); + assert_eq!(served(d), (plain(shape), 4, 4)); + // (500,300) - (488,288) = (12,12): the candidate. + settle(&mut cal, (488, 288), Some(peer((500, 300), 1)), d, e); + assert_eq!(cal.as_ref().unwrap().candidate, Some(((12, 12), 1))); + assert_eq!(cal.as_ref().unwrap().current_hot, (4, 4)); + assert_eq!(served(d), (plain(shape), 4, 4), "unconfirmed: nothing visible changes"); + assert_eq!(cached_cursor_cal(shape), None); + // (600,400) - (587,388) = (13,12): confirms (12,12). + settle(&mut cal, (587, 388), Some(peer((600, 400), 2)), d, e); + let c = cal.as_ref().unwrap(); + assert_eq!(c.candidate, None); + assert_eq!(c.current_hot, (12, 12)); + assert_eq!(cached_cursor_cal(shape), Some((12, 12))); + assert_eq!(served(d), (corrected(shape, (12, 12)), 12, 12)); + forget_cursor_cal(shape); + } + + // The confirmed value is within tolerance of the wire: the producer's guess was right, the + // wire value is served under the plain id, and the stale cached correction goes. + #[test] + fn a_confirmed_value_near_the_wire_serves_the_wire_and_drops_the_cached_correction() { + let _serial = CACHE_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner()); + let (d, e, shape) = (9_701, next_cursor_epoch(), 0x7a01); + store_cursor_cal(shape, (30, 4)); + let mut cal = arrive(d, e, shape, (10, 10)); + assert_eq!(served(d), (corrected(shape, (30, 4)), 30, 4), "seeded from the cache"); + // (12,10) then (14,10): confirms (12,10), which is 2 px from the wire. + settle(&mut cal, (488, 290), Some(peer((500, 300), 1)), d, e); + settle(&mut cal, (586, 390), Some(peer((600, 400), 2)), d, e); + assert_eq!(cached_cursor_cal(shape), None, "the wire was right: the correction goes"); + assert_eq!(cal.as_ref().unwrap().current_hot, (10, 10)); + assert_eq!(served(d), (plain(shape), 10, 10)); + } + + // The confirmed value is within tolerance of what is already served: nothing visible + // changes, and the served value is cached again if a clear-on-cap took it out meanwhile. + #[test] + fn a_confirmed_value_in_band_with_the_served_one_changes_nothing_and_stays_cached() { + let _serial = CACHE_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner()); + let (d, e, shape) = (9_702, next_cursor_epoch(), 0x7a02); + store_cursor_cal(shape, (12, 12)); + let mut cal = arrive(d, e, shape, (4, 4)); + let before = served(d); + assert_eq!(before, (corrected(shape, (12, 12)), 12, 12)); + CURSOR_CAL_CACHE.lock().unwrap().clear(); + // (13,12) then (15,12): confirms (13,12), 1 px from what is served. + settle(&mut cal, (488, 288), Some(peer((501, 300), 1)), d, e); + settle(&mut cal, (587, 388), Some(peer((602, 400), 2)), d, e); + assert_eq!(served(d), before, "in band: nothing visible changes"); + assert_eq!(cal.as_ref().unwrap().current_hot, (12, 12)); + assert_eq!(cached_cursor_cal(shape), Some((12, 12)), "the served value is cached again"); + forget_cursor_cal(shape); + } + + // Review of rustdesk#16122 (pre-push, 23-sep): a served correction 3 px from the wire and a + // confirmed value in band with BOTH. The served value wins, or every confirmation in that + // band would flap the hotspot and the id. A value in band with the wire only still goes + // back to the wire. Mutation caught: comparing the wire before the served value. + #[test] + fn a_confirmed_value_in_band_with_both_keeps_the_served_correction() { + let _serial = CACHE_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner()); + let (d, e, shape) = (9_706, next_cursor_epoch(), 0x7a06); + store_cursor_cal(shape, (13, 10)); + let mut cal = arrive(d, e, shape, (10, 10)); + let before = served(d); + assert_eq!(before, (corrected(shape, (13, 10)), 13, 10)); + // (12,10) then (14,10): confirms (12,10), 2 px from the wire AND 1 px from the served. + settle(&mut cal, (488, 290), Some(peer((500, 300), 1)), d, e); + settle(&mut cal, (586, 390), Some(peer((600, 400), 2)), d, e); + assert_eq!(served(d), before, "in band with the served value: it stays"); + assert_eq!(cal.as_ref().unwrap().current_hot, (13, 10)); + assert_eq!(cached_cursor_cal(shape), Some((13, 10))); + // (10,10) twice: in band with the wire only, so the wire is served again. + settle(&mut cal, (490, 290), Some(peer((500, 300), 3)), d, e); + settle(&mut cal, (590, 390), Some(peer((600, 400), 4)), d, e); + assert_eq!(served(d), (plain(shape), 10, 10)); + assert_eq!(cached_cursor_cal(shape), None); + } + + #[test] + fn a_disagreeing_measurement_replaces_the_candidate_and_the_same_sample_never_confirms() { + let mut c = arrive(9_703, next_cursor_epoch(), 0x7a03, (4, 4)).unwrap(); + assert_eq!(observe_measurement(&mut c, (12, 12), 1), None); + assert_eq!(c.candidate, Some(((12, 12), 1))); + assert_eq!(observe_measurement(&mut c, (30, 4), 2), None, "disagreement replaces"); + assert_eq!(c.candidate, Some(((30, 4), 2))); + assert_eq!(observe_measurement(&mut c, (31, 4), 3), Some((30, 4)), "the retained one"); + assert_eq!(c.candidate, None); + assert_eq!(observe_measurement(&mut c, (12, 12), 4), None); + assert_eq!(observe_measurement(&mut c, (12, 12), 4), None, "same sample: not independent"); + assert_eq!(c.candidate, Some(((12, 12), 4))); + } + + // The local hand on the mouse (review of rustdesk#16122): the remote peer stops, a local user + // nudges the pointer, the plane settles somewhere new, and the only sample on hand is the + // stale remote one. However many times the plane settles, the same sample never confirms. + #[test] + fn a_plane_move_without_a_new_peer_sample_never_confirms() { + let (d, e, shape) = (9_705, next_cursor_epoch(), 0x7a05); + forget_cursor_cal(shape); + let mut cal = arrive(d, e, shape, (4, 4)); + let before = served(d); + let stale = Some(peer((500, 300), 1)); + settle(&mut cal, (493, 288), stale, d, e); // (7,12) + assert_eq!(cal.as_ref().unwrap().candidate, Some(((7, 12), 1))); + settle(&mut cal, (494, 288), stale, d, e); // (6,12), same sample + assert_eq!(cal.as_ref().unwrap().candidate, Some(((7, 12), 1))); + settle(&mut cal, (400, 400), stale, d, e); // away: out of the bitmap + settle(&mut cal, (493, 288), stale, d, e); // back: (7,12) again, same sample + assert_eq!(cal.as_ref().unwrap().candidate, Some(((7, 12), 1))); + assert_eq!(served(d), before); + assert_eq!(cached_cursor_cal(shape), None); + } + #[test] fn a_calibration_context_exists_only_for_an_identity_matched_upright_output() { let one = |t: i32| { @@ -2656,6 +3169,178 @@ mod drm_capturer_tests { calibration_context(&two, 1, &wl, 7).map(|c| (c.rect, c.physical_size)), Ok(((1920, 0, 2560, 1440), (2560, 1440))) ); + // Chained and scaled: the T2 panel, 2880x1800 scanning out a 1986x1241 logical rect. + let panel = [ + drm_display("eDP-1", 2880, 1800), + drm_display("DP-6", 1920, 1080), + ]; + let mut p = wl_display("eDP-1", 0, 0, 2880, 1800); + p.logical_size = Some((1986, 1241)); + let wl = scrap::wayland::display::Displays { + primary: 0, + displays: vec![p, wl_display("DP-6", 1986, 0, 1920, 1080)], + }; + let ctx = calibration_context(&panel, 0, &wl, 7).unwrap(); + assert_eq!(ctx.rect, (0, 0, 1986, 1241)); + assert_eq!(measure_hotspot(&ctx, (1643, 577), (2357, 814), (128, 128)), Some((26, 23))); + } + + // The cache is read behind the context gate only: without a context a correction measured + // upright is never served, which is what a rotated output relies on. + #[test] + fn a_cached_correction_is_not_served_without_a_context() { + let _serial = CACHE_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner()); + let (d, e, shape) = (9_706, next_cursor_epoch(), 0x7a06); + store_cursor_cal(shape, (20, 20)); + let raw = vec![0; 64 * 64 * 4]; + let cal = on_cursor_shape(d, e, None, shape, 64, 64, 4, 4, false, raw.clone(), 0); + assert!(cal.is_none()); + assert_eq!(served(d), (plain(shape), 4, 4), "no context, no cache read"); + let cal = on_cursor_shape(d, e, Some(ctx1()), shape, 64, 64, 4, 4, false, raw, 0); + assert!(cal.is_some(), "control: with a context the same arrival is served corrected"); + assert_eq!(served(d), (corrected(shape, (20, 20)), 20, 20)); + forget_cursor_cal(shape); + } + + #[test] + fn a_kernel_measured_hotspot_is_never_calibrated_even_at_the_origin() { + let (d, e, shape) = (9_707, next_cursor_epoch(), 0x7a07); + let raw = vec![0; 64 * 64 * 4]; + let kernel = on_cursor_shape(d, e, Some(ctx1()), shape, 64, 64, 0, 0, true, raw.clone(), 0); + assert!(kernel.is_none()); + assert_eq!(served(d), (plain(shape), 0, 0)); + let guess = on_cursor_shape(d, e, Some(ctx1()), shape, 64, 64, 0, 0, false, raw, 0); + assert!(guess.is_some(), "control: a guess at the origin is measured"); + assert!(!calibratable(scrap::drm_reader::HIDDEN_CURSOR_ID, false)); + } + + // Each stable position yields at most one measurement: a fresh sample arriving while the + // plane is still does not get a second one, so it cannot confirm the first. + #[test] + fn a_still_plane_is_measured_once() { + let (d, e, shape) = (9_708, next_cursor_epoch(), 0x7a08); + forget_cursor_cal(shape); + let mut cal = arrive(d, e, shape, (4, 4)); + let before = served(d); + settle(&mut cal, (488, 288), Some(peer((500, 300), 1)), d, e); + assert_eq!(cal.as_ref().unwrap().candidate, Some(((12, 12), 1))); + for _ in 0..CURSOR_CAL_WINDOW_TICKS { + let fresh = Some(peer((500, 300), 2)); + on_cursor_plane(&mut cal, Some((488, 288)), || fresh, false, CAL_GEN, d, e); + } + assert_eq!(cal.as_ref().unwrap().candidate, Some(((12, 12), 1))); + assert_eq!(served(d), before); + assert_eq!(cached_cursor_cal(shape), None); + } + + #[test] + fn the_settle_window_and_the_sample_gates_are_closed_intervals() { + let mut c = arrive(9_709, next_cursor_epoch(), 0x7a09, (4, 4)).unwrap(); + for (ticks, ok) in [ + (CURSOR_CAL_STABLE_TICKS - 1, false), + (CURSOR_CAL_STABLE_TICKS, true), + (CURSOR_CAL_WINDOW_TICKS, true), + (CURSOR_CAL_WINDOW_TICKS + 1, false), + ] { + c.stable_ticks = ticks; + c.measured_this_position = false; + assert_eq!(settled_unmeasured(&c), ok, "stable_ticks {ticks}"); + } + c.stable_ticks = CURSOR_CAL_STABLE_TICKS; + c.measured_this_position = true; + assert!(!settled_unmeasured(&c)); + let ctx = ctx1(); + let s = |age: u64, gen: u64| { + Some(crate::server::input_service::PeerAbsSample { + pos: (1, 1), + age_ms: age, + seq: 9, + gen, + }) + }; + let min = CURSOR_CAL_MIN_INPUT_AGE_MS; + let max = CURSOR_CAL_MAX_INPUT_AGE_MS; + assert_eq!(usable_sample(&ctx, s(min, CAL_GEN), false, CAL_GEN), Some(((1, 1), 9))); + assert_eq!(usable_sample(&ctx, s(max, CAL_GEN), false, CAL_GEN), Some(((1, 1), 9))); + assert_eq!(usable_sample(&ctx, s(min - 1, CAL_GEN), false, CAL_GEN), None); + assert_eq!(usable_sample(&ctx, s(max + 1, CAL_GEN), false, CAL_GEN), None); + assert_eq!(usable_sample(&ctx, None, false, CAL_GEN), None); + assert_eq!(usable_sample(&ctx, s(400, CAL_GEN), true, CAL_GEN), None, "drift"); + assert_eq!(usable_sample(&ctx, s(400, CAL_GEN), false, CAL_GEN + 1), None, "layout moved"); + assert_eq!(usable_sample(&ctx, s(400, CAL_GEN - 1), false, CAL_GEN), None, "old sample"); + } + + #[test] + fn a_settle_lands_one_sample_later_than_the_constant_reads() { + let mut c = arrive(9_710, next_cursor_epoch(), 0x7a10, (4, 4)).unwrap(); + for _ in 0..=CURSOR_CAL_STABLE_TICKS { + update_plane_stability(&mut c, (10, 20)); + } + assert_eq!(c.stable_ticks, CURSOR_CAL_STABLE_TICKS); + c.measured_this_position = true; + update_plane_stability(&mut c, (11, 20)); + assert_eq!( + (c.plane, c.stable_ticks, c.measured_this_position), + (Some((11, 20)), 0, false) + ); + } + + #[test] + fn the_measurement_is_the_injected_tip_in_scanout_space_minus_the_plane() { + let ctx = ctx1(); + assert_eq!(measure_hotspot(&ctx, (500, 300), (488, 288), (32, 32)), Some((12, 12))); + // The T2 reading that found the space mismatch: 2880x1800 advertised as 1986x1241. + let scaled = CalContext { + rect: (0, 0, 1986, 1241), + physical_size: (2880, 1800), + built_gen: CAL_GEN, + }; + assert_eq!(measure_hotspot(&scaled, (1643, 577), (2357, 814), (128, 128)), Some((26, 23))); + // The pointer is on another monitor: that stream measures, not this one. + let right = CalContext { + rect: (1920, 0, 1920, 1080), + ..ctx + }; + assert_eq!(measure_hotspot(&right, (500, 300), (488, 288), (32, 32)), None); + // Outside the bitmap: far away, and the plane ahead of the tip. + assert_eq!(measure_hotspot(&ctx, (900, 300), (488, 288), (32, 32)), None); + assert_eq!(measure_hotspot(&ctx, (480, 300), (488, 288), (32, 32)), None); + } + + #[test] + fn a_corrected_id_differs_from_the_wire_id_and_is_deterministic() { + let wire = 0xabcdef0123456789u64; + let a = remix_cursor_id(wire, 12, 12); + assert_ne!(a, wire); + assert_eq!(a, remix_cursor_id(wire, 12, 12)); + assert_ne!(a, remix_cursor_id(wire, 13, 12)); + } + + #[test] + fn the_calibration_cache_is_bounded() { + let _serial = CACHE_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner()); + for i in 0..(CURSOR_CAL_CACHE_CAP as u64 * 2) { + store_cursor_cal(0x1_0000 + i, (1, 1)); + } + assert!(CURSOR_CAL_CACHE.lock().unwrap().len() <= CURSOR_CAL_CACHE_CAP); + CURSOR_CAL_CACHE.lock().unwrap().clear(); + } + + // A held frame can carry the previous shape's plane position after a new shape arrived: + // a fresh CursorCal starts with no plane, so its first position always counts as a move. + #[test] + fn the_first_position_after_a_shape_never_counts_as_settled() { + let (d, e, shape) = (9_711, next_cursor_epoch(), 0x7a11); + let mut cal = arrive(d, e, shape, (4, 4)); + on_cursor_plane(&mut cal, None, || None, false, CAL_GEN, d, e); + assert_eq!(cal.as_ref().unwrap().plane, None, "no position, no state change"); + for _ in 0..CURSOR_CAL_STABLE_TICKS { + let s = Some(peer((500, 300), 1)); + on_cursor_plane(&mut cal, Some((488, 288)), || s, false, CAL_GEN, d, e); + } + let c = cal.as_ref().unwrap(); + assert_eq!(c.stable_ticks, CURSOR_CAL_STABLE_TICKS - 1); + assert_eq!(c.candidate, None); } fn drm_display(name: &str, w: u32, h: u32) -> DrmDisplayInfo {