Skip to content
rustdesk-orgPublic
forked from fxd0h/libdrmtap

About

DRM/KMS screen capture library for Linux — embeddable, multi-GPU, privilege-managed

Resources

Contributing

Security policy

Stars

8 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

🔍 libdrmtap

A zero-dependency C library for DRM/KMS framebuffer capture on Linux

License: MIT crates.io Built with AI PRs Welcome

Capture any Linux display — no Wayland, no PipeWire, no user prompts.


The Problem

Screen capture on modern Linux is a mess:

  • Wayland prevents unprivileged screen capture by design
  • PipeWire/xdg-desktop-portal require user interaction every time
  • Login screens (GDM, SDDM) can't be captured at all — no compositor running
  • RustDesk, Sunshine, and others have fought this for 4+ years with no clean solution
  • No embeddable C library exists for direct framebuffer capture

The Solution

libdrmtap goes below the compositor — directly to the kernel's DRM/KMS subsystem — to capture the framebuffer without any user interaction, compositor cooperation, or display server dependency.

#include <drmtap.h>

int main() {
    drmtap_ctx *ctx = drmtap_open(NULL);  // auto-detect GPU
    
    drmtap_frame_info frame;
    drmtap_grab_mapped(ctx, &frame);      // capture screen → linear 8-bit pixels
    
    // frame.data = linear pixels, 4 bytes each, laid out as frame.format
    // (XRGB8888 once converted; a linear 8-bit scanout keeps its own order)
    // frame.width, frame.height, frame.stride
    
    drmtap_frame_release(ctx, &frame);
    drmtap_close(ctx);
}

Rust

[dependencies]
libdrmtap = "0.6"

This pulls in libdrmtap-sys, which embeds and statically compiles the C sources (and the privilege helper). No system libdrmtap install, no meson install, no pkg-config to find a shared library.

use libdrmtap::DrmTap;

let mut tap = DrmTap::open(None)?;
let frame = tap.grab_mapped()?;
println!("{}x{} pixels captured", frame.width(), frame.height());

Since 0.5.7 the split path is reachable from Rust too: grab_desc() returns the frame plus a DmabufDesc carrying the plane layout and HDR state, and the frame hands out its DMA-BUF as a BorrowedFd (or an owned dup via try_clone_fd()). The descriptor deliberately carries no file descriptor, so it is safe to serialize and the fd travels out of band, exactly as the C header prescribes. Needs Rust 1.66. That is the single-buffer split: the multi-plane packet API (drmtap_grab_packet() / drmtap_convert_packet()) has no safe Rust API yet and is reachable only through the raw libdrmtap-sys FFI.

Features

Feature Status
VMs (virtio_gpu, Parallels, QEMU) ✅ Verified
Multi-monitor (per-CRTC) ✅ Implemented
Multi-GPU (enumerate every card + bind convert to the exporting GPU) ✅ Implemented
Split capture (privileged export + unprivileged convert) ✅ Implemented
Multi-plane scanout: windows on overlay/underlay planes (0.6.0) ✅ Verified on i915 with KWin 6.8.2, overlay and underlay; composed on the GPU
Zero-copy DMA-BUF output (V3) ✅ Implemented
Mapped RGBA output ✅ Verified
Continuous capture (polling loop) ✅ Verified
Cursor capture (position + pixels) ✅ Verified on bare metal (amdgpu, i915) and on a para-virtualized driver (needs 0.5.4 there — see Known Limitations). Hotspot provenance (drmtap_cursor_hotspot_valid(), 0.5.6) verified in all three of its states: absent on i915, present on virtio-gpu, unavailable through a pre-0.5.6 helper
Exact CRTC refresh as a fraction (drmtap_crtc_refresh(), 0.5.9) ✅ Verified on i915 (60/1, 6750000/112463 for 1280x1024 at 60.02 Hz, 131375/4382 for 3840x2160 at 29.98 Hz; -ENODATA on a disabled pipe)
Plane rotation (drmtap_plane_rotation(), 0.5.8) ✅ Verified on i915 (mutter rotates 180 in hardware: rotate-180), on amdgpu with KWin (software rotation: rotate-0, scanout upside down) and on appletbdrm (no property: -ENOTSUP)
Privileged helper (setcap, no root) ✅ Verified
Security hardening (cap drop + seccomp) ✅ Implemented
EGL/GLES2 GPU-universal detiling ✅ Implemented (primary, all GPUs)
Intel (i915/xe) X/Y-tiled deswizzle ✅ CPU fallback
AMD (amdgpu) deswizzle ⛔ EGL only — no CPU decoder, fails closed
Nvidia (nvidia-drm) blocklinear deswizzle ⛔ EGL only — there is no CPU decoder; the CPU path returns -ENOTSUP (0.5.3)
HDR10 → SDR tone-map (AR30/XR30/AB30/XB30, XR48/AR48/XB48/AB48) ✅ Implemented (P010 not yet)
Frame differencing (dirty rects) ✅ Implemented
Thread-safe (one drmtap_ctx per thread) ✅ By design
Coexists with NoMachine/Sunshine ✅ By design
Rust bindings (crates.io) ✅ Published
MIT License ✅

⚠️ Testing status: every entry below is a machine someone captured from, and it says whose. A tester confirmation is one host on one day, not a support matrix.

Verified here:

  • Intel Meteor Lake-P (i915, Core Ultra 7 155H) — multiple displays up to 3840x2160, 4_TILED_MTL_RC_CCS_CC scanout detiled through EGL.
  • AMD RX560 (Polaris/gfx8) — 2880x1800 eDP-1, tiled XR30, EGL detile.
  • NVIDIA Jetson Orin Nano (nvidia-drm, aarch64, Wayland).
  • virtio_gpu (QEMU/Parallels VMs), V3 zero-copy path.

Confirmed by outside testers, on their hardware and not ours:

  • AMD RX Vega 64 (gfx9), X11, modifier 0x200000004801a01, unprivileged via the helper — GK-Gaming, 2026-07-29 (#26, #36).
  • Intel Raptor Lake with a hybrid NVIDIA GPU (ThinkBook 16p G5 IRX, Ubuntu 26.04, GNOME Wayland, eDP-1, Y_TILED_GEN12_RC_CCS_CC) — huzhifeng, 2026-08-07 (#45).

Whichever GPU you have, most of this depends on the EGL detile backend. The CPU path on its own still handles linear scanouts and the plain tilings (Intel X/Y/Yf-tiled), but a compressed scanout, or any tiled layout it has no deswizzler for, fails closed — it returns an error rather than passing the raw bytes off as linear pixels. Current Intel and AMD desktops scan out exactly those. The egl Meson feature defaults to auto, which silently builds the CPU-only stub when the headers are missing, so configure with -Degl=enabled to fail at configure time instead — that is what #45 turned out to be.

Multi-GPU render-node selection is verified on the Jetson Orin's two DRM devices (tegra/renderD128 with no connectors + nvidia-drm/renderD129 driving the display): the converter now binds renderD129, the node that exported the scanout. Multi-card, multi-VENDOR hosts with more than one display-driving GPU are now verified on an Apple T2 MacBook Pro: three DRM cards — appletbdrm (the Touch Bar strip), i915 (no connected output) and amdgpu (the panel) — where two different vendors are each scanning out a display at once, and each was captured from its own card. That machine also covers two cases nothing else here does:

  • A display-only card with NO render node. appletbdrm exposes an active CRTC and no renderD*, so a consumer cannot be told which GPU exported the scanout and must not guess: importing it on the wrong device can corrupt the image silently. Such a frame takes the CPU path instead.
  • A scanout framebuffer PADDED wider than the mode. That card drives a 60x2170 mode out of a 64x2170 framebuffer (256-byte pitch), and those four columns are alignment padding that is never scanned out. A grab reports the width the CRTC scans out, not the framebuffer's, so a consumer that enumerated the mode is not handed an image wider than the display it asked for. Worth knowing if you compare a frame's geometry against a display list. If you test on real hardware, please report results.

ℹ️ virgl note: Plain virtio-gpu is captured with a direct linear map. A host-rendered virgl (3D) scanout cannot be read by the guest CPU (it comes out black, and TRANSFER_FROM_HOST does not bring it back); it is captured via GPU-side EGL readback on the guest. Solved technically; production integration is in progress (#15).

HDR10 capture is tone-mapped to SDR. When the connector advertises an HDR scanout (HDR_OUTPUT_METADATA, PQ), libdrmtap applies the real transfer — PQ (SMPTE ST 2084) decode, BT.2020 → BT.709 gamut, a highlight-preserving tone-map, sRGB — and returns correct 8-bit SDR, instead of the washed-out top-8-of-10-bits result. This matches what consumers like RustDesk expect (their pipeline is 8-bit SDR; on other platforms the OS/compositor tone-maps before they see it — on DRM we do it). Covers AR30/XR30/AB30/XB30 (10-bit) and XR48/AR48/XB48/AB48 (16-bit), in both the CPU and the EGL (tiled) paths. P010 (10-bit YUV, used for overlay-video planes rather than the primary desktop scanout) is not handled.

FP16 half-float scanouts (XRGB16161616F and its BGR/alpha siblings) are reduced to 8-bit sRGB when the scanout is linear — linear-light decode through the sRGB OETF, not HDR tone-mapped (values above 1.0 clip to white).

Quick Start

Requirements

The tiled/compressed framebuffer path (Intel/AMD/Nvidia modifiers) uses the DRM GETFB2 ioctl, which mainline added in Linux 5.7. Ubuntu 20.04 (5.4) has it backported; 22.04 (5.15), 24.04 (6.8) and newer have it. Linear framebuffers (virtio-gpu and similar VMs) work on older kernels.

Build

# Dependencies: meson, gcc, libdrm-dev
sudo apt install meson gcc libdrm-dev pkg-config

# For EGL GPU-universal detiling:
sudo apt install libegl-dev libgles2-mesa-dev

# For the privileged helper. Without these, `helper=auto` builds the library
# ALONE and says so only in the configure log, and the setcap step further down
# then fails on a binary that was never built.
sudo apt install libseccomp-dev libcap-dev

# Build. Neither option is optional in practice, and both are passed as
# `=enabled` for the same reason: on `auto` a missing dependency is a message in
# the configure log rather than an error. Without -Degl you get a stub that
# fails on the first real scanout; without -Dhelper you get no binary for
# unprivileged capture. Pass them and a missing dependency stops the build.
git clone https://github.com/fxd0h/libdrmtap.git
cd libdrmtap
meson setup build -Degl=enabled -Dhelper=enabled
meson compile -C build

# If you do NOT want the helper at all - device access arranged by udev rules,
# membership of video/render, or seat management - build without it instead.
# That leaves no fork/exec path in the library, not merely no binary, and a
# caller that cannot read the scanout itself then gets -EACCES naming what is
# missing rather than a fallback:
meson setup build-nohelper -Degl=enabled -Dhelper=disabled
meson compile -C build-nohelper

Install

sudo meson install -C build

Install the directory you configured above. For the helper-disabled build:

sudo meson install -C build-nohelper

Set up privileged helper (for capture without root)

A Meson install already places the helper at mode 0750, owner root:root, so it is never world-executable out of the box. What is left to you is the group. A file capability applies to every user who can exec the binary, so cap_sys_admin+ep on a helper that anyone can run lets any local user read the DRM scanout (login screen, lock screen, other users' sessions). Chown it to a trusted capture group FIRST, keep the mode at 0750, and apply the capability LAST. The SO_PEERCRED check inside the helper is defense-in-depth, not an access-control boundary; the file mode is. This mirrors the procedure in SECURITY.md.

# Restrict execution to a trusted group, THEN grant the capability.
sudo groupadd -f drmtap-capture
sudo chown root:drmtap-capture /usr/local/libexec/drmtap-helper
sudo chmod 0750               /usr/local/libexec/drmtap-helper
sudo setcap cap_sys_admin+ep  /usr/local/libexec/drmtap-helper
# Add each user who is allowed to capture to the group:
sudo usermod -aG drmtap-capture "$USER"

Take a screenshot

# With sudo (direct capture):
sudo ./build/screenshot > screenshot.ppm

# Without sudo (via helper — after setcap above):
./build/screenshot > screenshot.ppm

Examples

All of them are built with the library (build/<name>):

Example What it shows
screenshot.c One frame to a PPM file with drmtap_grab_mapped(). Several planes are composed for you.
stream.c Continuous capture at a target frame rate.
split_capture.c The privilege split with one buffer: drmtap_grab_desc() in a privileged process, the DMA-BUF fd over a unix socket, drmtap_convert_dmabuf() in an unprivileged one.
packet_capture.c The same split for a screen of several planes (0.6.0): drmtap_grab_packet() / drmtap_convert_packet(), the consumer only forwards bytes and fds. Starts with the drmtap_abi() check.
vnc_server.c A VNC server with mouse and keyboard (needs libvncserver).

VNC server demo (full remote desktop)

The included VNC server example captures the screen and serves it over VNC with mouse and keyboard input:

# Build with libvncserver (optional dependency)
meson setup build -Degl=enabled && meson compile -C build

# Run (needs root for uinput access)
sudo ./build/vnc_server

# Connect from any VNC client:
#   vnc://YOUR_IP:5900  (password: drmtap)

RustDesk integration

libdrmtap is upstream in RustDesk: rustdesk/rustdesk#15420 was merged on 2026-08-06 and ships in the rustdesk-unattended-wayland build. The integration adds a drm backend to scrap that dlopens libdrmtap.so.0 at runtime: it does not link libdrmtap at build time and does not depend on the libdrmtap-sys crate, whose build.rs would statically compile the whole C tree and a privileged helper. Loading the shared object by soname is what lets a missing or too-old .so degrade to the existing PipeWire path instead of breaking the build.

A self-contained example of the crate-based backend, which does link libdrmtap-sys statically, lives in contrib/integrations/rustdesk/. Tested and verified on Ubuntu 24.04 with cargo build (zero errors).

ABI level

The release version and the ABI are counted separately. drmtap_abi(&current, &oldest) gives the range of ABI levels the loaded library serves, and DRMTAP_ABI_LEVEL is the level of the header a consumer was built with. A consumer accepts the library when oldest <= DRMTAP_ABI_LEVEL <= current and enables features by level: level 1 is the 0.5.x API (a library without drmtap_abi is level 1), level 2 (0.6.0) adds the packet API. A consumer that dlopen()s the library can therefore accept a newer minor without an update, as long as the level range still covers it. The level is the library's own claim, not an integrity check: load it from a trusted absolute path.

0.6.0 serves level 1 too (oldest = 1) because no 0.5 struct or signature changed and the 0.5 calls changed only within what 0.5 documented. On a screen of several planes a level-1 caller sees: drmtap_grab_desc() returning -EAGAIN and then the covering plane (an underlay), drmtap_grab() returning composed pixels with no fd, and a composed frame's fb_id that is not a content key. A caller that handles errors and a -1 fd as 0.5 documented keeps working.

Run tests

# Unit tests (no hardware needed)
meson test -C build --suite unit

# Integration tests (need a DRM device; CONTRIBUTING.md has which card they open
# and when the capture test really grabs)
meson test -C build --suite integration

Environment variables

Variable Effect
DRM_DEVICE DRM node to open (e.g. /dev/dri/card0). Ignored for privileged callers (root, or a setuid, setgid or file-capability binary) — a privileged capture service uses its configured device_path or the KMS auto-scan, so the environment cannot redirect which device it opens. Honored only for unprivileged runs.
DRMTAP_DEBUG Set to 1 for verbose debug logging on stderr.
DRMTAP_NO_EGL Set to 1 to force the CPU deswizzle/convert path (skip EGL/GLES).
DRMTAP_NO_IMAGE_CACHE Set to 1 to re-import the EGLImage every frame (disable the import-once cache).
DRMTAP_SKIP_UNCHANGED Set to 1 to skip the GPU readback when the screen has not changed. After the EGL convert has rendered the frame on the GPU, a shader hashes the converted image in 32x32 blocks; when no block changed, the readback is skipped and the previous output buffer is returned as it was (same pointer, same pixels). Applies to the EGL path of drmtap_grab_mapped(), drmtap_grab_mapped_fast() and drmtap_convert_dmabuf(), for frames of 1920x1080 or more (below that the readback is already cheaper than the hash). Needs OpenGL ES 3; without it the normal path runs. While it is on, treat frame->data as read-only: the next unchanged frame returns the buffer as it is. A buffer set with drmtap_set_output_buffer() is never skipped. Off by default.
DRMTAP_FORCE_MMAP_FAIL Test hook — set to 1 to force the fast-path CPU mmap to fail so the EGL-detile fallback runs.

A setuid, setgid or file-capability binary ignores all of these: the library reads them with secure_getenv().

The privilege model is described in SECURITY.md.

Skipping unchanged frames

A capture loop on a still screen reads back the same image over and over. With DRMTAP_SKIP_UNCHANGED=1 the library hashes each converted frame on the GPU and skips the readback when nothing changed (details in the table above). Set the variable before the first grab; nothing else in the loop changes:

setenv("DRMTAP_SKIP_UNCHANGED", "1", 1);   /* before the first grab on this thread */
drmtap_ctx *ctx = drmtap_open(NULL);
for (;;) {
    drmtap_frame_info f;
    if (drmtap_grab_mapped(ctx, &f) == 0) {
        send_frame(f.data, f.width, f.height, f.stride);   /* read only: never write to f.data */
        drmtap_frame_release(ctx, &f);
    }
}

From the shell, DRMTAP_SKIP_UNCHANGED=1 DRMTAP_DEBUG=1 ./build/stream prints egl: unchanged, skipped for each skipped frame.

Performance

CPU cost of the capture loop, measured as a share of one core (approximate; on Ubuntu 24.04). The library figure is the full grab + detile loop in the consuming process; the helper figure is the privileged drmtap-helper process.

Environment Resolution Capture CPU (1 core) Helper CPU Path
Intel Meteor Lake (i915) dual 3840×2160 @ 60 ~16% ~0.4% V3 zero-copy, EGL CCS detile
NVIDIA Jetson Orin Nano (nvidia-drm) 1920×1080 ~11% ~0.4% V3 zero-copy, EGL detile
Plain virtio-gpu VM typical desktop ~1.2% ~0.7% V3 zero-copy, direct linear map

Plain virtio dropped from ~14% on the old V2 copy path to ~1.2% once V3 stopped copying full frames across the socket.

With DRMTAP_SKIP_UNCHANGED=1 a still screen costs less: on Intel Meteor Lake a 3840x2160 frame went from about 4.8 ms to 1.3 ms of CPU, 1920x1080 from 2.2 ms to 1.0 ms. A screen that changes every frame pays the hash on top of the convert (about 1.5 ms more wall time per 1080p frame on the same machine).

How it works:

  • V3 zero-copy (default) — the privileged helper exports the active scanout as a DMA-BUF and passes the fd back over a socketpair via SCM_RIGHTS. No full-frame copy crosses the socket.
  • V2 copy (fallback) — when DMA-BUF export is not possible, the helper dumb-maps the framebuffer and copies the pixels over the socket.
  • GPU EGL readback — tiled/compressed scanouts (Intel CCS, AMD, Nvidia block-linear, vendor modifiers) and host-rendered virgl buffers are imported as an EGLImage and read back linear with glReadPixels. Plain linear framebuffers are mapped directly with no detile.
  • Zero-copy DMA-BUF output — consumers that take the DMA-BUF output can import the buffer directly (e.g. as an EGLImage or Vulkan texture) and skip the readback entirely.

Why Not Use Existing Tools?

Every existing project is either a complete application, a plugin, or PipeWire-based. None is an embeddable C library for DRM/KMS capture.

Project Embeddable lib? DRM/KMS? Privilege helper? Multi-GPU? Multi-monitor?
FFmpeg kmsgrab ❌ Needs FFmpeg (40MB+) ✅ ❌ Root on binary ✅ ✅
gpu-screen-recorder ❌ CLI tool ✅ Partial ✅ gsr-kms-server ✅ ✅
kmsvnc ❌ VNC server ✅ ❌ Needs root ⚠️ Partial ✅
obs-kmsgrab ❌ OBS plugin ✅ ✅ pkexec ❌ First GPU only ❌
Sunshine ❌ Built-in ✅ ❌ setcap on binary ✅ ✅
ReFrame ❌ VNC server ✅ ✅ Split process ✅ ✅
libdrmtap ✅ C library ✅ ✅ Hardened ✅ ✅

libdrmtap is the only project that is simultaneously: an embeddable C library, uses DRM/KMS direct capture, includes a hardened privilege helper, supports multiple GPUs, and handles multiple monitors — all under the MIT license.

Architecture

┌─────────────────────────────────────────────────┐
│              YOUR APPLICATION                   │
│      (RustDesk, Sunshine, VNC, custom)          │
├─────────────────────────────────────────────────┤
│              libdrmtap.h                        │
│          Public API — 32 functions              │
├─────────────────────────────────────────────────┤
│                                                 │
│  ┌────────────┐  ┌─────────┐  ┌──────────────┐  │
│  │ enumerate  │  │  grab   │  │ pixel_convert│  │
│  │ Planes     │  │ GetFB2  │  │ Deswizzle    │  │
│  │ CRTCs      │  │ Prime   │  │ Format cvt   │  │
│  │ Connectors │  │ Layers  │  │ Compose (EGL)│  │
│  │            │  │ Packet  │  │ Diff frames  │  │
│  └────────────┘  └─────────┘  └──────────────┘  │
│                                                 │
│  ┌────────────┐  ┌────────────────────────────┐ │
│  │ gpu_backend│  │ privilege_helper           │ │
│  │ EGL: all   │  │ Auto-spawn drmtap-helper   │ │
│  │ (primary)  │  │ DMA-BUF fd via SCM_RIGHTS  │ │
│  │ CPU detile │  │ V3 zero-copy / V2 copy     │ │
│  │ (fallback) │  │ cap_drop + seccomp         │ │
│  │ VM: linear │  │ Transparent to user        │ │
│  └────────────┘  └────────────────────────────┘ │
├─────────────────────────────────────────────────┤
│           libdrm / kernel DRM/KMS               │
└─────────────────────────────────────────────────┘

GPU Detiling Strategy

libdrmtap uses a dual-path approach for GPU-tiled framebuffers:

  1. EGL path (primary) — Imports DMA-BUF as EGLImage with modifier metadata, renders via GL_TEXTURE_EXTERNAL_OES. The GPU driver handles its own tiling transparently. One code path for ALL GPUs. Based on ReFrame.
  2. CPU path (fallback) — Per-GPU deswizzle when EGL is unavailable (headless servers, no GPU rendering).
  3. Linear path — VMs and linear framebuffers need no conversion.

Scope — What libdrmtap Does (and Doesn't)

✅ We do ❌ We don't
Capture framebuffer pixels (RGBA / DMA-BUF) Encode or compress frames
Handle GPU tiling → linear conversion Transport frames over network
Manage permissions transparently Inject keyboard/mouse input
Support Intel, AMD, Nvidia, VMs Replace Wayland's screen sharing protocols
Provide cursor position + shape Implement a VNC/RDP server
Enumerate displays and monitors across multiple GPUs
Detect changed regions (dirty rects)

Wayland positioning: For interactive desktop sharing where user consent matters, use Wayland protocols (ext-image-capture-source-v1, PipeWire). For unattended system-level capture (servers, kiosks, CI, remote management, login screens), use libdrmtap. We complement Wayland — we don't compete with it.

Known Limitations

  • Cursor hotspot on bare-metal drivers. The cursor hotspot (the click point inside the image, e.g. an arrow's tip or an I-beam's centre) is only exposed by the DRM cursor plane on para-virtualized drivers (virtio-gpu, vmwgfx, qxl, vboxvideo), via the HOTSPOT_X/HOTSPOT_Y plane properties. On bare-metal drivers (i915, amdgpu, nvidia) those properties do not exist at all — measured on amdgpu and on i915 with a found/not-found flag and CRTC_X as the positive control — so drmtap_cursor_info.hot_x/hot_y come back 0 there. Since 0.5.6 a consumer can tell that 0 apart from a hotspot the driver really published at the corner: drmtap_cursor_hotspot_valid() answers from the sample in hand (Cursor::hotspot_from_driver() in Rust). Testing hot_x != 0 || hot_y != 0 instead is wrong in both directions - it overrides a real (0, 0) with a guess, and it would trust a hotspot no driver published.

    The cursor image and position are unaffected: drmtap_cursor_info.x/y is the cursor plane's CRTC_X/CRTC_Y, and it tracks the pointer live on bare metal whichever ioctl the compositor drives it with. Measured on amdgpu under KWin, and on i915 under Mutter, where moving the pointer by 100 logical px moved CRTC_X by 266 physical px on that scaled output, monotonically over three samples. (While the pointer is idle a compositor may leave the plane unbound — CRTC_ID and FB_ID read 0 and the coordinates go stale — which libdrmtap reports as a hidden cursor, not as a position.)

    That live position is what makes the hotspot recoverable, and it is why there are two ways out on bare metal rather than one:

    • Measure it, if the consumer injects the pointer itself (remote desktop, test automation). It knows where it put the pointer, the plane sits at that point minus the hotspot, so once both settle hotspot = injected_position - plane_position — mind the coordinate spaces, the plane is in the CRTC's physical pixels while an injected point is usually in the compositor's logical layout. RustDesk does this in rustdesk/rustdesk#16122.
    • Approximate it from the image (top-left of an arrow's bounding box, centre of a tall/narrow I-beam) when there is no injected pointer to compare against. Fine for an arrow, and off by roughly half the glyph for a wide centre-hotspot shape: on a horizontal resize arrow the bounding-box guess gave (4,16) where the real hotspot was (26,23), i.e. 19 px out horizontally.

    Those same hotspot properties are why, since kernel 6.6, a para-virtualized driver (virtio-gpu, vmwgfx, qxl, vboxvideo) hides its cursor plane entirely from a client that has enabled DRM_CLIENT_CAP_ATOMIC and has not also enabled DRM_CLIENT_CAP_CURSOR_PLANE_HOTSPOT: the second cap is how a client declares it honors them. libdrmtap needs the atomic cap to read a connector's CRTC_ID, so it enables both (since 0.5.4 — before it, the cursor read found no plane on those drivers and reported the cursor hidden forever). The hotspot cap is refused with EOPNOTSUPP on bare metal, which is harmless and is also a cheap way to tell the two kinds of driver apart.

  • Multi-plane scanout needs the packet API in a split, and EGL to compose. A compositor can scan a window out of its own plane, above the desktop (an overlay) or below a desktop with a transparent hole (an underlay). KWin 6.8 does this on Intel when one output is enabled (rustdesk/rustdesk#17187). Since 0.6.0 drmtap_grab(), drmtap_grab_mapped() and drmtap_grab_mapped_fast() compose such a frame the way the display does, and drmtap_grab_packet() + drmtap_convert_packet() carry it across a process boundary. What is left:

    • drmtap_grab_desc() describes one buffer. When the primary plane covers the screen it returns it as before, without the window on the overlay. On an underlay it returns -EAGAIN (no frame, keep the last one) for 2 seconds, then the topmost plane that covers the screen (the desktop, with the window showing as its transparent hole) until the underlay ends. With KWin 6.8.2 the underlay lasted 1.1 to 1.4 s while a window opened. One lit plane stretched to the screen, or smaller than it, is that buffer at its own size here (a 40x40 plane gives a 40x40 descriptor): one buffer cannot scale or place. drmtap_grab() does the same for such a plane (its contract is an fd).
    • One lit plane that is not the screen as it is (stretched to it, or smaller than it) is composed to the screen size like several planes since 0.6.1, by drmtap_grab_mapped(), drmtap_grab_mapped_fast() and drmtap_convert_packet(). Before, the frame was the size of the buffer. When it cannot be composed, those calls return its buffer at its own size, as before, said once in the debug log; only a caller buffer too small for the screen-sized frame fails, with -ENOSPC. This plane does not have to cover the screen.
    • A composed frame is in screen orientation (drmtap_plane_rotation() answers ROTATE_0 for it), and its fb_id is the primary plane's, not a content key.
    • Composing needs the EGL backend. Without it (-Degl=disabled, no libEGL, or a setuid or file-capability process) the CPU composes only linear 8-bit RGB planes with no rotation.
    • When a frame of several planes cannot be composed (no EGL and a plane the CPU cannot read, an import the driver refuses, more than four lit planes, a drmtap-helper older than 0.6.0) it is captured from one plane, said once in the debug log: the primary plane when it covers the screen (windows on other planes are missing), or, when the primary is a window under the desktop (an underlay), the topmost plane that covers the screen (the desktop, the window shows as its transparent hole). If no plane covers the screen there is no frame: the call returns its error with a message. What each call then returns: drmtap_grab(), drmtap_grab_mapped() and drmtap_grab_mapped_fast() that plane's buffer at its own size; drmtap_grab_packet() with more than four lit planes a one-layer packet of it; drmtap_convert_packet() that layer at its buffer size, unrotated, with its rotation answered by drmtap_plane_rotation() on the converting context. Through the helper the covering plane of an underlay needs CMD_GRAB_LAYERS, so with a helper older than 0.6.0, or more than four lit planes, those calls return -EAGAIN for as long as the underlay lasts.
    • Up to four planes per frame. HDR (PQ) comes from the connector and applies to every plane, there is no per-plane colour pipeline here. Plane rotation and YUV planes follow the kernel definitions and are tested on the GPU with synthetic buffers, but no compositor here put one on screen (KWin used rotate-0 RGB planes, and decoded NV12/P010 video stayed composited).
    • A split capture of several planes needs 0.6.0 on both ends: a 0.5 converter cannot read a packet (use drmtap_grab_desc() there). The rotation of a converted frame is the converting context's answer, after each convert.
    • Multi-plane capture was measured on Intel (i915) with KWin 6.8.2 only; amdgpu, nvidia, mutter and wlroots overlay use are not measured.
  • No cursor on drivers without a cursor plane. libdrmtap reads the cursor from a DRM_PLANE_TYPE_CURSOR plane. A driver that registers its CRTCs with drm_crtc_init() exposes only a primary plane and sets the cursor through the legacy cursor ioctl, which has no read-back, so there is no cursor to capture. The known case is radeon, the driver for older Radeon GPUs (an integrated CAICOS was reported in rustdesk discussion #10016). On GNOME the workaround is to make mutter draw the cursor into the frame: add MUTTER_DEBUG_DISABLE_HW_CURSORS=1 to /etc/environment and reboot (restarting gdm alone is not enough, the old environment stays in systemd --user). Measured on mutter 46 with virtio-gpu: the cursor plane goes unused and the cursor shows up in the captured frame. Not tested on radeon.

Why This Exists

This project was born from a real frustration: trying to get remote desktop working on Ubuntu Wayland. After RustDesk broke packages, Sunshine failed on KMS, and every solution required "just switch to X11" — we decided to solve it at the root.

We researched every existing project on GitHub, analyzed 25+ real-world issues, studied the source code of kmsvnc, gpu-screen-recorder, FFmpeg kmsgrab, ReFrame, and kms-screenshot. All findings are documented in docs/research/.

Read the full research: 9 documents covering the landscape, Wayland capture problems, DRM/KMS internals, permissions, GPU differences, API design, GitHub issues analysis, potential adopters, and the ReFrame EGL analysis.

🤖 Built with AI Agents

This project is proudly developed with the assistance of AI coding agents. We don't hide it — we celebrate it.

The entire research phase — analyzing codebases, reading GitHub issues, studying kernel APIs, designing the architecture — was conducted as a collaboration between a human developer and AI agents. This includes:

  • Antigravity by Google DeepMind — agentic AI coding assistant
  • Gemini by Google DeepMind — powering research and analysis
  • Claude by Anthropic — powering code generation and reasoning

We believe AI agents are a force multiplier for open source. A single developer with AI assistance can produce research and code that would traditionally require a team. This project is proof of that thesis.

Agent-written code is held to the same bar as any other contribution: every PR is reviewed by CodeRabbit, scanned by CodeQL and cppcheck, and validated under ASan/UBSan in CI — and the privileged helper survived a serious security audit during RustDesk upstreaming. The hardening was praised, not waved through. AI speeds up the work; it does not lower the standard.

See docs/AI_DEVELOPMENT.md for our full AI development philosophy, and AGENTS.md for the working agreement we hand to coding agents.

Documentation

Document Description
00_landscape.md GitHub landscape — 11 projects analyzed
01_wayland_capture_problem.md Wayland capture problem — why every project struggles
02_drm_kms_mechanism.md DRM/KMS capture mechanism deep dive
03_permissions.md Permissions model & helper binary
04_gpu_and_testing.md GPU differences & vkms testing
05_api_and_architecture.md API design & architecture
06_github_issues_analysis.md Analysis of 25+ real GitHub issues
07_potential_adopters.md Integration targets — 243K+ ⭐ of potential adopters
08_reframe_egl_analysis.md ReFrame analysis — EGL GPU-universal detiling

Contributing

We welcome contributions of all kinds! Whether you're fixing a bug, adding GPU support, improving docs, or just reporting an issue — you're helping solve a real problem for the Linux desktop community.

See CONTRIBUTING.md for guidelines.

Areas where we especially need help:

  • 🐧 Testing on real hardware (Intel, AMD, Nvidia, Raspberry Pi) — validating EGL detiling and CPU fallback paths
  • 🔧 Login screen capture testing — GDM/SDDM/LightDM on various distros
  • 📖 Documentation and examples — tutorials, man pages
  • 🌐 Integration patches — RustDesk, Sunshine, and other remote desktop projects

License

MIT License — Use it anywhere, in anything.

We chose MIT specifically so projects like RustDesk (AGPLv3), Sunshine, and proprietary software can all integrate libdrmtap without license conflicts.


libdrmtap — Framebuffer capture for the Linux kernel, no compositor required.

Built with ❤️, frustration, and AI agents.

About

DRM/KMS screen capture library for Linux — embeddable, multi-GPU, privilege-managed

Resources

Contributing

Security policy

Stars

8 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages