perf(drm): convert dma-buf frames straight into the recycled buffer

The DRM receive thread copied every converted frame out of libdrmtap's
context buffer into a recycled slot buffer: one full-frame memcpy per
frame, about 33 MB at 4K. drmtap_set_output_buffer, exported by every
libdrmtap 0.5.x, lets the conversion write into that buffer directly.

Same approach as #16808, reduced to the minimal change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JAxkkiaGp2k8okvs4MpCUq
This commit is contained in:
rustdeskandClaude Opus 5.5 committed 2026-11-09 17:09:15 +08:00
1 parent 95cca3f661
commit 2634e5e433
4 files changed
+163 -9

No files matched your search

+2
View File
@@ -2489,6 +2489,8 @@ jobs:
cargo test --locked -p scrap --features drm plane_rotation_tests
run_drm_tests "scrap drmtap_dl::tests" \
cargo test --locked -p scrap --features drm drmtap_dl::tests
run_drm_tests "scrap convert_into_tests" \
cargo test --locked -p scrap --features drm convert_into_tests
# Opt-in like drm, and this container already builds with it.
run_drm_tests "clipboard unix-file-copy-paste" \
cargo test --locked -p clipboard --features unix-file-copy-paste
+140
View File
@@ -170,6 +170,46 @@ impl RenderConverter {
Ok((data, w, h, pixfmt))
}
}
/// `convert()` straight into `buf`, saving the copy out of the context; `buf` ends up holding
/// exactly the frame, row stride `len / height`.
pub fn convert_into(
&mut self,
desc: &mut drmtap_dmabuf_desc,
received_fd: RawFd,
buf: &mut Vec<u8>,
) -> io::Result<(u32, u32, Pixfmt)> {
// The CPU deswizzle keeps the source pitch; every other path writes width * 4.
let need = (desc.pitches[0] as usize)
.max((desc.width as usize).saturating_mul(4))
.saturating_mul(desc.height as usize);
if need > MAX_FRAME_BYTES {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"drm: refusing a {}x{} dma-buf with pitch {}",
desc.width, desc.height, desc.pitches[0]
),
));
}
buf.resize(need, 0);
let (set_output, ctx) = (self.lib.set_output_buffer, self.ctx);
// SAFETY: `buf` is not touched until the destination is detached below. If libdrmtap
// refuses it, the frame lands in the context buffer and is copied out as before.
unsafe { set_output(ctx, buf.as_mut_ptr().cast(), buf.len()) };
let converted = self.convert(desc, received_fd);
// SAFETY: NULL only detaches the destination; libdrmtap never frees it.
unsafe { set_output(ctx, std::ptr::null_mut(), 0) };
let (data, w, h, fmt) = converted?;
if data.as_ptr() == buf.as_ptr() {
let len = data.len();
buf.truncate(len);
} else {
buf.clear();
buf.extend_from_slice(data);
}
Ok((w, h, fmt))
}
}
impl Drop for RenderConverter {
@@ -182,3 +222,103 @@ impl Drop for RenderConverter {
}
}
}
#[cfg(test)]
mod convert_into_tests {
use super::*;
use std::ffi::c_void;
struct Mock {
dst: *mut c_void,
given: *mut c_void,
own: Vec<u8>,
use_dst: bool,
}
unsafe extern "C" fn set_output(ctx: *mut drmtap_ctx, dst: *mut c_void, _: usize) -> i32 {
let mock = &mut *ctx.cast::<Mock>();
mock.dst = dst;
if !dst.is_null() {
mock.given = dst;
}
0
}
/// A 2x2 frame of 7s, written into the destination when `use_dst`, else into its own buffer.
unsafe extern "C" fn convert(
ctx: *mut drmtap_ctx,
_: *const drmtap_dmabuf_desc,
frame: *mut drmtap_frame_info,
) -> i32 {
let mock = &mut *ctx.cast::<Mock>();
let out: *mut u8 = if mock.use_dst && !mock.dst.is_null() {
mock.dst.cast()
} else {
mock.own.as_mut_ptr()
};
std::ptr::write_bytes(out, 7, 16);
(*frame).data = out.cast();
(*frame).width = 2;
(*frame).height = 2;
(*frame).stride = 8;
(*frame).format = DRM_FORMAT_XRGB8888;
0
}
fn convert_with(use_dst: bool, buf: &mut Vec<u8>) -> Box<Mock> {
unsafe extern "C" fn grab(_: *mut drmtap_ctx, _: *mut drmtap_frame_info) -> i32 {
-1
}
unsafe extern "C" fn release(_: *mut drmtap_ctx, _: *mut drmtap_frame_info) {}
unsafe extern "C" fn desc(
_: *mut drmtap_ctx,
_: *mut drmtap_dmabuf_desc,
_: *mut drmtap_frame_info,
) -> i32 {
-1
}
unsafe extern "C" fn rotation(_: *mut drmtap_ctx, _: *mut u32) -> i32 {
-1
}
let mut lib = DrmtapLib::fake(grab, release, desc, rotation);
lib.convert_dmabuf = convert;
lib.set_output_buffer = set_output;
let mock = Box::into_raw(Box::new(Mock {
dst: std::ptr::null_mut(),
given: std::ptr::null_mut(),
own: vec![0; 16],
use_dst,
}));
let mut conv = RenderConverter {
lib: Box::leak(Box::new(lib)),
ctx: mock.cast(),
};
let mut d = drmtap_dmabuf_desc {
width: 2,
height: 2,
pitches: [8, 0, 0, 0],
..Default::default()
};
let res = conv.convert_into(&mut d, -1, buf).unwrap();
assert!(matches!(res, (2, 2, Pixfmt::BGRA)));
drop(conv);
unsafe { Box::from_raw(mock) }
}
#[test]
fn converts_into_the_callers_buffer() {
let mut buf = vec![0; 64];
let allocation = buf.as_mut_ptr().cast::<c_void>();
let mock = convert_with(true, &mut buf);
assert_eq!(mock.given, allocation);
assert!(mock.dst.is_null());
assert_eq!(buf, [7; 16]);
}
#[test]
fn copies_a_frame_the_library_kept() {
let mut buf = Vec::new();
convert_with(false, &mut buf);
assert_eq!(buf, [7; 16]);
}
}
+14
View File
@@ -152,6 +152,8 @@ type FnPlaneRotation = unsafe extern "C" fn(*mut drmtap_ctx, *mut u32) -> c_int;
type FnCrtcRefresh = unsafe extern "C" fn(*mut drmtap_ctx, *mut u64, *mut u64) -> c_int;
type FnConvertDmabuf =
unsafe extern "C" fn(*mut drmtap_ctx, *const drmtap_dmabuf_desc, *mut drmtap_frame_info) -> c_int;
/// `drmtap_set_output_buffer`, exported by every 0.5.x.
type FnSetOutputBuffer = unsafe extern "C" fn(*mut drmtap_ctx, *mut c_void, usize) -> c_int;
/// The dlopen'd libdrmtap; the `Library` is kept alive for the process lifetime, so the raw fn pointers stay valid.
pub struct DrmtapLib {
@@ -171,6 +173,7 @@ pub struct DrmtapLib {
pub grab_desc: FnGrabDesc,
pub open_render: FnOpenRender,
pub convert_dmabuf: FnConvertDmabuf,
pub set_output_buffer: FnSetOutputBuffer,
pub render_node: Option<FnRenderNode>,
/// Optional: it only exists from libdrmtap 0.5.8. Absent means the library cannot say whether
/// the plane rotated the scanout, and the consumer keeps the pre-0.5.8 rule for that case.
@@ -212,6 +215,13 @@ impl DrmtapLib {
) -> c_int {
-1
}
unsafe extern "C" fn set_output_buffer(
_: *mut drmtap_ctx,
_: *mut c_void,
_: usize,
) -> c_int {
0
}
DrmtapLib {
_lib: hbb_common::libloading::os::unix::Library::this().into(),
open,
@@ -226,6 +236,7 @@ impl DrmtapLib {
grab_desc,
open_render,
convert_dmabuf,
set_output_buffer,
render_node: None,
plane_rotation: Some(plane_rotation),
crtc_refresh: None,
@@ -329,6 +340,8 @@ impl DrmtapLib {
let frame_release: FnFrameRelease = *lib.get(b"drmtap_frame_release").ok()?;
let get_cursor: FnGetCursor = *lib.get(b"drmtap_get_cursor").ok()?;
let cursor_release: FnCursorRelease = *lib.get(b"drmtap_cursor_release").ok()?;
let set_output_buffer: FnSetOutputBuffer =
*lib.get(b"drmtap_set_output_buffer").ok()?;
let grab: Option<FnGrabDesc> = lib.get(b"drmtap_grab_desc").ok().map(|s| *s);
let open_r: Option<FnOpenRender> = lib.get(b"drmtap_open_render").ok().map(|s| *s);
let conv: Option<FnConvertDmabuf> =
@@ -436,6 +449,7 @@ impl DrmtapLib {
grab_desc,
open_render,
convert_dmabuf,
set_output_buffer,
render_node,
plane_rotation,
crtc_refresh,
+7 -9
View File
@@ -900,19 +900,17 @@ async fn recv_thread(
hdr_eotf: desc.hdr_eotf,
hdr_max_nits: desc.hdr_max_nits,
};
match conv.convert(&mut ddesc, received_fd) {
Ok((data, w, h, fmt)) => {
// Borrowed from the render context, valid only until the next convert.
// Copy into a recycled buffer, and OUTSIDE the slot lock, so a
// multi-megabyte memcpy never holds the encoder off the slot.
let mut buf = shared.slot.lock().unwrap().take_free().unwrap_or_default();
buf.clear();
buf.extend_from_slice(data);
// Converted OUTSIDE the slot lock, so the encoder is never held off the slot.
let mut buf = shared.slot.lock().unwrap().take_free().unwrap_or_default();
match conv.convert_into(&mut ddesc, received_fd, &mut buf) {
Ok((w, h, fmt)) => {
let mut slot = shared.slot.lock().unwrap();
slot.publish(w as usize, h as usize, fmt, desc.plane_rotation, buf);
shared.cv.notify_one();
}
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {
shared.slot.lock().unwrap().recycle(buf);
}
Err(err) => {
drm_set_prefer_cpu(&our_key);
break format!("convert: {err}");