diff --git a/libs/scrap/src/common/drm_reader.rs b/libs/scrap/src/common/drm_reader.rs index a269ffe89..296059905 100644 --- a/libs/scrap/src/common/drm_reader.rs +++ b/libs/scrap/src/common/drm_reader.rs @@ -36,6 +36,9 @@ pub struct CursorSnapshot { /// so the consumer must re-guess on the upright one. pub hot_measured: bool, pub colors: Vec, + /// Cursor plane position (CRTC_X/CRTC_Y), in this reader's scanout pixels. + pub x: i32, + pub y: i32, } /// Fold everything that makes a cursor a DIFFERENT cursor into its id. @@ -639,6 +642,8 @@ impl DrmReader { hoty: 0, hot_measured: false, colors: vec![0, 0, 0, 0], + x: 0, + y: 0, }) } else if !c.pixels.is_null() && c.width > 0 @@ -691,6 +696,8 @@ impl DrmReader { hoty, hot_measured, colors, + x: c.x, + y: c.y, }) } else { None diff --git a/src/ipc.rs b/src/ipc.rs index cc894b287..0887485a5 100644 --- a/src/ipc.rs +++ b/src/ipc.rs @@ -540,7 +540,14 @@ pub enum Data { /// Service -> client: a frame header; the packed BGRA pixels follow via `send_raw()`. /// CPU-fallback path (no render node, or no transferable dma-buf): pixels cross the wire. #[cfg(all(target_os = "linux", feature = "drm"))] - DrmFrame { width: u32, height: u32 }, + DrmFrame { + width: u32, + height: u32, + /// See `DmabufDesc::cursor_pos`: the cursor plane position read right after this frame, + /// or `None` when the cursor is hidden, the read failed or the producer predates the field. + #[serde(default)] + cursor_pos: Option<(i32, i32)>, + }, /// Service -> client: a zero-copy dma-buf frame descriptor. The scanout fd is NOT a field; when /// `desc.has_fd` it rides an SCM_RIGHTS ancillary message on the same `DrmConn::send_msg`, and /// there is NO trailing `send_raw()` body. The unprivileged `--server` imports the fd and does @@ -2369,4 +2376,29 @@ mod test { other => panic!("expected DrmCursor, got {other:?}"), } } + + /// A frame header from a producer that predates the cursor plane position reads as `None`; + /// a producer that sends one is read back exactly. A pin, not a gate: the consumer only ever + /// measures against `Some`. + #[cfg(all(target_os = "linux", feature = "drm"))] + #[test] + fn a_drm_frame_without_a_cursor_position_reads_as_none() { + let legacy = r#"{"t":"DrmFrame","c":{"width":8,"height":8}}"#; + match serde_json::from_str::(legacy).expect("legacy DrmFrame must deserialize") { + Data::DrmFrame { + width, + height, + cursor_pos, + } => { + assert_eq!((width, height), (8, 8)); + assert_eq!(cursor_pos, None); + } + other => panic!("expected DrmFrame, got {other:?}"), + } + let modern = r#"{"t":"DrmFrame","c":{"width":8,"height":8,"cursor_pos":[3,4]}}"#; + match serde_json::from_str::(modern).expect("modern DrmFrame must deserialize") { + Data::DrmFrame { cursor_pos, .. } => assert_eq!(cursor_pos, Some((3, 4))), + other => panic!("expected DrmFrame, got {other:?}"), + } + } } diff --git a/src/ipc/drm.rs b/src/ipc/drm.rs index f0b5dcecb..a6963aed6 100644 --- a/src/ipc/drm.rs +++ b/src/ipc/drm.rs @@ -45,6 +45,13 @@ pub struct DmabufDesc { pub hdr_max_nits: u32, /// True: the fd rides this message's SCM_RIGHTS cmsg. False: import-once cache hit for `fb_id`. pub has_fd: bool, + /// Cursor plane position read right after this frame was grabbed, in scanout pixels of the + /// display this stream shows, so a few ms newer than the frame. `None` means the cursor is + /// hidden, the read failed or was rejected, or the producer predates this field. It rides + /// the frame instead of a stream of its own so it cannot queue and cannot backpressure the + /// capture worker; the consumer only acts on a position that held still for several frames. + #[serde(default)] + pub cursor_pos: Option<(i32, i32)>, } pub(crate) fn drm_ipc_path() -> String { @@ -100,6 +107,9 @@ enum DrmProducerMsg { width: u32, height: u32, data: Bytes, + /// See `DmabufDesc::cursor_pos`. The dmabuf path carries it inside the descriptor; this + /// one has no descriptor, so it travels beside the pixels. + cursor_pos: Option<(i32, i32)>, }, Cursor { id: u64, @@ -112,6 +122,105 @@ enum DrmProducerMsg { }, } +/// Put this tick's cursor plane position on the frame it was read next to. The hidden sentinel +/// carries no position; a shape message is left alone. +fn stamp_cursor_pos(msg: &mut DrmProducerMsg, c: Option<&scrap::drm_reader::CursorSnapshot>) { + let pos = c.and_then(|c| (c.id != scrap::drm_reader::HIDDEN_CURSOR_ID).then_some((c.x, c.y))); + match msg { + DrmProducerMsg::Frame { desc, .. } => desc.cursor_pos = pos, + DrmProducerMsg::FrameCpu { cursor_pos, .. } => *cursor_pos = pos, + DrmProducerMsg::Displays(_) | DrmProducerMsg::Cursor { .. } => {} + } +} + +#[cfg(test)] +mod cursor_pos_tests { + use super::*; + + fn desc() -> DmabufDesc { + DmabufDesc { + buffer_id: 0, + width: 4, + height: 4, + format: 0, + modifier: 0, + fb_id: 0, + num_planes: 1, + offsets: [0; 4], + pitches: [16, 0, 0, 0], + hdr_eotf: 0, + hdr_max_nits: 0, + has_fd: false, + cursor_pos: None, + } + } + + fn snapshot(id: u64) -> scrap::drm_reader::CursorSnapshot { + scrap::drm_reader::CursorSnapshot { + id, + width: 2, + height: 2, + hotx: 0, + hoty: 0, + hot_measured: false, + colors: vec![0; 16], + x: 10, + y: 20, + } + } + + #[test] + fn the_plane_position_rides_both_frame_kinds_and_a_hidden_cursor_rides_as_none() { + let visible = snapshot(7); + let hidden = snapshot(scrap::drm_reader::HIDDEN_CURSOR_ID); + + let mut frame = DrmProducerMsg::Frame { desc: desc(), fd: None }; + stamp_cursor_pos(&mut frame, Some(&visible)); + assert!(matches!(&frame, DrmProducerMsg::Frame { desc, .. } if desc.cursor_pos == Some((10, 20)))); + stamp_cursor_pos(&mut frame, Some(&hidden)); + assert!(matches!(&frame, DrmProducerMsg::Frame { desc, .. } if desc.cursor_pos.is_none())); + + let mut cpu = DrmProducerMsg::FrameCpu { + width: 4, + height: 4, + data: Bytes::new(), + cursor_pos: None, + }; + stamp_cursor_pos(&mut cpu, Some(&visible)); + assert!(matches!(&cpu, DrmProducerMsg::FrameCpu { cursor_pos: Some((10, 20)), .. })); + stamp_cursor_pos(&mut cpu, None); + assert!(matches!(&cpu, DrmProducerMsg::FrameCpu { cursor_pos: None, .. })); + + let mut shape = DrmProducerMsg::Cursor { + id: 7, + width: 2, + height: 2, + hotx: 1, + hoty: 1, + hot_measured: false, + colors: vec![0; 16], + }; + stamp_cursor_pos(&mut shape, Some(&visible)); + assert!(matches!(&shape, DrmProducerMsg::Cursor { hotx: 1, hoty: 1, .. })); + } + + // A producer that predates the field: the descriptor arrives without it and reads as None. + #[test] + fn a_descriptor_without_a_cursor_position_reads_as_none() { + let mut v = serde_json::to_value(desc()).unwrap(); + v.as_object_mut().unwrap().remove("cursor_pos").expect("the field is serialized"); + let d: DmabufDesc = serde_json::from_value(v).expect("a legacy descriptor must deserialize"); + assert_eq!(d.cursor_pos, None); + let d: DmabufDesc = serde_json::from_value(serde_json::to_value(DmabufDesc { + cursor_pos: Some((3, 4)), + ..desc() + }) + .unwrap()) + .unwrap(); + assert_eq!(d.cursor_pos, Some((3, 4))); + } +} + struct DrmStopGuard(std::sync::Arc); impl Drop for DrmStopGuard { fn drop(&mut self) { @@ -960,8 +1069,17 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> { width, height, data, + cursor_pos, }) => { - conn.send_msg(&Data::DrmFrame { width, height }, None).await?; + conn.send_msg( + &Data::DrmFrame { + width, + height, + cursor_pos, + }, + None, + ) + .await?; conn.send_raw(data).await?; credit -= 1; // one frame in flight until the consumer acks it } @@ -1030,7 +1148,7 @@ fn drm_capture_worker( let mut stalled: u32 = 0; let mut logged_first = false; while !stop.load(Ordering::Relaxed) { - let grabbed: Option> = if frames_gated.load(Ordering::Relaxed) + let mut grabbed: Option> = if frames_gated.load(Ordering::Relaxed) { // `stalled` is left untouched because the device is healthy -- the task bounds this // state itself (CREDIT_STALL) since our watchdog cannot advance. @@ -1051,6 +1169,7 @@ fn drm_capture_worker( hdr_eotf: d.hdr_eotf, hdr_max_nits: d.hdr_max_nits, has_fd: true, // every exported frame carries its fd; see the send below + cursor_pos: None, // stamped below, from the one cursor read of this tick }, fd: Some(fd), }), @@ -1062,10 +1181,22 @@ fn drm_capture_worker( width: w as u32, height: h as u32, data: Bytes::copy_from_slice(buf), + cursor_pos: None, }), Err(err) => Err(err), }) }; + // ONE cursor read per tick, and none on a stalled or failed grab: the plane position rides + // the frame it was read next to, and the shape ships when it changes. The position is a + // few ms newer than the frame; the consumer only measures a plane that held still for + // several frames, so that skew never reaches a measurement. + let cursor = match &grabbed { + Some(Err(_)) => None, + _ => reader.cursor(), + }; + if let Some(Ok(msg)) = grabbed.as_mut() { + stamp_cursor_pos(msg, cursor.as_ref()); + } match grabbed { None => {} Some(Ok(msg)) => { @@ -1108,7 +1239,7 @@ fn drm_capture_worker( } // Ship the cursor shape only when it changes (id is a content hash or the hidden sentinel). - if let Some(c) = reader.cursor() { + if let Some(c) = cursor { if c.id != last_cursor_id { last_cursor_id = c.id; if frame_tx @@ -1538,7 +1669,14 @@ mod drm_conn_tests { let (a, b) = tokio::net::UnixStream::pair().unwrap(); let mut tx = DrmConn::new(a); let mut rx = DrmConn::new(b); - tx.send_msg(&Data::DrmFrame { width: 1920, height: 1080 }, None) + tx.send_msg( + &Data::DrmFrame { + width: 1920, + height: 1080, + cursor_pos: None, + }, + None, + ) .await .unwrap(); let (data, fd) = rx.recv_msg().await.unwrap(); @@ -1546,7 +1684,8 @@ mod drm_conn_tests { data, Data::DrmFrame { width: 1920, - height: 1080 + height: 1080, + cursor_pos: None } )); assert!(fd.is_none(), "no fd was sent, none must be reported"); @@ -1558,7 +1697,14 @@ mod drm_conn_tests { let mut tx = DrmConn::new(a); let mut rx = DrmConn::new(b); let (rd, wr) = pipe(); - tx.send_msg(&Data::DrmFrame { width: 4, height: 4 }, Some(rd.as_fd())) + tx.send_msg( + &Data::DrmFrame { + width: 4, + height: 4, + cursor_pos: None, + }, + Some(rd.as_fd()), + ) .await .unwrap(); let (_data, fd) = rx.recv_msg().await.unwrap(); @@ -1672,6 +1818,7 @@ mod drm_conn_tests { let payload = serde_json::to_vec(&Data::DrmFrame { width: 8, height: 8, + cursor_pos: None, }) .unwrap(); let prefix = (payload.len() as u32).to_be_bytes(); @@ -1683,7 +1830,8 @@ mod drm_conn_tests { data, Data::DrmFrame { width: 8, - height: 8 + height: 8, + cursor_pos: None } )); let kept = fd.expect("the first surplus fd must be kept"); diff --git a/src/server/drm_capturer.rs b/src/server/drm_capturer.rs index dfcb2f490..4dabec01a 100644 --- a/src/server/drm_capturer.rs +++ b/src/server/drm_capturer.rs @@ -725,7 +725,11 @@ async fn recv_thread( break format!("frame ack: {err}"); } } - Data::DrmFrame { width, height } => { + Data::DrmFrame { + width, + height, + cursor_pos: _, + } => { // `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 {