feat(capture): capture Windows par GDI, écrans, tous les écrans, une fenêtre
CI / Formatting, tests and builds (push) Successful in 2m45s

Premier chemin de capture Windows (#8), celui qui marche partout, de
Windows 10 à Wine, sans GPU:
- chaque moniteur par BitBlt (couches comprises), en pixels physiques
  (conscience DPI par moniteur), et tous les écrans ensemble;
- une fenêtre par PrintWindow, lue même couverte; si l'image sort
  noire (application dessinée par le GPU, ou Wine), la fenêtre est lue
  là où elle s'affiche;
- le pointeur est dessiné dans l'image;
- une image inchangée est reconnue, et l'encodeur saute la répétition;
- une fenêtre réduite est listée grisée et garde sa dernière image.

Côté hôte: type de session Windows, chemin `gdi` (aussi par
RUSTSCREEN_CAPTURE), choix de source `windows`, vignettes dans la liste.

Vérifié sous Wine sur un Xvfb 1920 x 1080: l'écran puis la fenêtre du
Bloc-notes arrivent dans Chromium. Reste à mesurer sur une vraie
machine, et la duplication de bureau DXGI pour tenir le budget
processeur en 1080p60.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guillaume ASSIERandClaude Opus 5.5 committed 2026-10-30 20:57:54 +01:00
1 parent a358aaa262
commit 980e84ac84
18 files changed
+869 -15

No files matched your search

+4 -2
View File
@@ -171,7 +171,9 @@ cargo run --release -p rs-session --features pipewire,vaapi --bin rustscreen-cli
Windows se compile depuis Linux (#93): le shell `.#windows` fournit un rustc pour la cible
`x86_64-pc-windows-gnu`, mingw-w64 et une libvpx statique, et range sa cible sous `target/windows`.
Wine fait tourner le `.exe` et les tests, sans machine Windows (mais pas la capture réelle).
Wine fait tourner le `.exe` et les tests, sans machine Windows. La capture GDI (#8) s'y vérifie sur
un Xvfb **à la taille d'un moniteur que Wine annonce** (1920 × 1080): plus petit, X refuse de lire
la zone et l'image sort noire.
```bash
nix develop .#windows -c cargo clippy --workspace --all-targets -- -D warnings
@@ -197,7 +199,7 @@ make desktop-lint # biome, vitest, rustfmt et clippy de la coque
En debug, le binaire embarque `apps/desktop/dist` (feature `custom-protocol` par défaut);
`--no-default-features` charge le serveur Vite (`pnpm --dir apps/desktop dev`) à la place.
Le chemin se force avec `RUSTSCREEN_CAPTURE=portal|x11|synthetic`. Le test X11 réel se lance
Le chemin se force avec `RUSTSCREEN_CAPTURE=portal|x11|gdi|synthetic`. Le test X11 réel se lance
contre un serveur jetable: `Xephyr :5 & DISPLAY=:5 xeyes &` puis
`RUSTSCREEN_X11_TEST=:5 cargo test -p rs-capture x11 -- --ignored`. Pour plusieurs moniteurs,
lancer Xephyr avec `+extension RANDR` et en déclarer avec `xrandr --setmonitor` (voir le test).
Generated
+1
View File
@@ -2011,6 +2011,7 @@ dependencies = [
"rustix",
"thiserror",
"tracing",
"windows-sys 0.61.2",
"x11rb",
]
+6 -5
View File
@@ -1290,7 +1290,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -1689,7 +1689,7 @@ dependencies = [
"gobject-sys 0.22.9",
"libc",
"system-deps 9.0.1",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -3782,6 +3782,7 @@ dependencies = [
"rustix",
"thiserror 2.0.21",
"tracing",
"windows-sys 0.61.2",
"x11rb",
]
@@ -3942,7 +3943,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5007,7 +5008,7 @@ dependencies = [
"getrandom 0.3.4",
"once_cell",
"rustix",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5888,7 +5889,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
+1 -1
View File
@@ -4,7 +4,7 @@
* What the user chooses to share. The interface sends back the `choice` of a
* [`SourceOption`] as is.
*/
export type SourceChoice = { "type": "synthetic", width: number, height: number, } | { "type": "x11", id: string, } | { "type": "portal", virtual_display: boolean,
export type SourceChoice = { "type": "synthetic", width: number, height: number, } | { "type": "x11", id: string, } | { "type": "windows", id: string, } | { "type": "portal", virtual_display: boolean,
/**
* A window rather than a screen (#17), if the portal allows it.
*/
+2
View File
@@ -110,6 +110,8 @@ export function key(choice: SourceChoice): string {
switch (choice.type) {
case 'x11':
return `x11:${choice.id}`;
case 'windows':
return `windows:${choice.id}`;
case 'portal':
if (choice.virtual_display) return 'portal:virtual';
return choice.window ? 'portal:window' : 'portal:screen';
+11
View File
@@ -24,4 +24,15 @@ pipewire = { version = "0.10.1", optional = true, features = ["v0_3_44"] }
x11rb = { version = "0.14.0", features = ["shm", "composite", "randr"] }
rustix = { version = "1", features = ["fs", "mm", "shm"] }
# Windows (#8): GDI for every monitor and window, pointer included.
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = [
"Win32_Foundation",
"Win32_Graphics_Dwm",
"Win32_Graphics_Gdi",
"Win32_Storage_Xps",
"Win32_UI_HiDpi",
"Win32_UI_WindowsAndMessaging",
] }
[dev-dependencies]
+7 -1
View File
@@ -10,6 +10,7 @@
pub enum DisplaySession {
Wayland,
X11,
Windows,
Headless,
}
@@ -20,6 +21,8 @@ pub enum Backend {
Portal,
/// Direct X11, MIT-SHM when the server offers it.
X11,
/// Windows, through GDI (#8).
Gdi,
/// Generated test pattern, no screen.
Synthetic,
}
@@ -29,6 +32,7 @@ impl Backend {
match self {
Self::Portal => "portal",
Self::X11 => "x11",
Self::Gdi => "gdi",
Self::Synthetic => "synthetic",
}
}
@@ -36,7 +40,7 @@ impl Backend {
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum BackendChoiceError {
#[error("unknown RUSTSCREEN_CAPTURE={0}: expected portal, x11 or synthetic")]
#[error("unknown RUSTSCREEN_CAPTURE={0}: expected portal, x11, gdi or synthetic")]
Unknown(String),
#[error("no graphical session: nothing to capture (use --synthetic for a test pattern)")]
NoSession,
@@ -58,6 +62,7 @@ pub fn choose(
return match value.to_ascii_lowercase().as_str() {
"portail" | "portal" | "pipewire" | "wayland" => Ok(Backend::Portal),
"x11" | "xshm" => Ok(Backend::X11),
"gdi" | "windows" => Ok(Backend::Gdi),
"synthetique" | "synthétique" | "synthetic" => Ok(Backend::Synthetic),
_ => Err(BackendChoiceError::Unknown(value.to_string())),
};
@@ -68,6 +73,7 @@ pub fn choose(
// path.
DisplaySession::Wayland => Ok(Backend::Portal),
DisplaySession::X11 => Ok(Backend::X11),
DisplaySession::Windows => Ok(Backend::Gdi),
DisplaySession::Headless => Err(BackendChoiceError::NoSession),
}
}
+4 -2
View File
@@ -3,8 +3,8 @@
//! One [`ScreenCapturer`] interface, one implementation per system, and a
//! synthetic test pattern to test the rest of the pipeline without a screen.
//! On Linux: the portal and PipeWire for Wayland ([`pipewire`], `pipewire`
//! feature), X11 as a fallback ([`x11`]). The choice of path lives in
//! [`backend`].
//! feature), X11 as a fallback ([`x11`]). On Windows: GDI ([`windows`]). The
//! choice of path lives in [`backend`].
//!
//! Output: BGRA frames with a monotonic timestamp. Conversion to I420 and
//! encoding belong to `rs-codec`.
@@ -18,6 +18,8 @@ pub mod synthetic;
#[cfg(all(target_os = "linux", feature = "pipewire"))]
pub mod pipewire;
#[cfg(windows)]
pub mod windows;
#[cfg(target_os = "linux")]
pub mod x11;
+655
View File
@@ -0,0 +1,655 @@
//! Windows capture through GDI (#8): every monitor, all of them together, or
//! one window.
//!
//! GDI is the path that works everywhere, from Windows 10 to Wine, without a
//! GPU: `BitBlt` from the screen for a monitor, `PrintWindow` for a window,
//! which reads it even when another one covers it. The pointer is drawn into
//! the image, as the viewer must see where the presenter points. Desktop
//! Duplication (DXGI) is the faster path for a monitor, and comes on top of
//! this one.
//!
//! Window titles go to the interface, never to the log (ADR 0008).
use std::time::Instant;
use rs_proto::{SourceId, SourceInfo, SourceKind};
use windows_sys::Win32::Foundation::{HWND, LPARAM, POINT, RECT, TRUE};
use windows_sys::Win32::Graphics::Dwm::{DWMWA_CLOAKED, DwmGetWindowAttribute};
use windows_sys::Win32::Graphics::Gdi::{
BI_RGB, BITMAPINFO, BITMAPINFOHEADER, BitBlt, CAPTUREBLT, CreateCompatibleDC, CreateDIBSection,
DIB_RGB_COLORS, DeleteDC, DeleteObject, EnumDisplayMonitors, GdiFlush, GetDC, GetMonitorInfoW,
HBITMAP, HDC, HGDIOBJ, HMONITOR, MONITORINFO, MONITORINFOEXW, ReleaseDC, SRCCOPY, SelectObject,
};
use windows_sys::Win32::Storage::Xps::PrintWindow;
use windows_sys::Win32::UI::HiDpi::{
DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, SetProcessDpiAwarenessContext,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
CURSOR_SHOWING, CURSORINFO, DI_NORMAL, DrawIconEx, EnumWindows, GWL_EXSTYLE, GetCursorInfo,
GetIconInfo, GetSystemMetrics, GetWindowLongPtrW, GetWindowRect, GetWindowTextW,
GetWindowThreadProcessId, ICONINFO, IsIconic, IsWindow, IsWindowVisible, MONITORINFOF_PRIMARY,
PW_RENDERFULLCONTENT, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN,
SM_YVIRTUALSCREEN, WS_EX_TOOLWINDOW,
};
use crate::cadence::Cadence;
use crate::frame::{CaptureError, CapturedFrame};
use crate::pixels;
use crate::source::{ScreenCapturer, describe};
/// All monitors together, as one image.
pub const SCREEN: &str = "windows:screen";
/// A monitor, by its device name (`\\.\DISPLAY1`).
pub const MONITOR_PREFIX: &str = "windows:monitor:";
/// A window, by its handle in hexadecimal.
pub const WINDOW_PREFIX: &str = "windows:window:";
/// A handful of pixels is not an application.
const MIN_WINDOW_SIZE: u32 = 64;
/// A monitor as Windows describes it, in physical pixels.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Monitor {
pub device: String,
pub x: i32,
pub y: i32,
pub width: u32,
pub height: u32,
pub primary: bool,
}
#[derive(Debug, Clone, Copy)]
enum Target {
Screen,
Monitor,
Window(HWND),
}
pub struct GdiCapturer {
target: Option<Target>,
/// Device of the captured monitor: its rectangle is read again at each
/// frame, so a resolution change follows.
device: String,
surface: Option<Surface>,
cadence: Cadence,
sequence: u64,
previous: std::sync::Arc<Vec<u8>>,
fitted: Vec<u8>,
}
// The handles are only used from the capture thread that owns the capturer.
unsafe impl Send for GdiCapturer {}
impl GdiCapturer {
pub fn new(fps: u8) -> Self {
// Physical pixels: without this, a 150 % display is captured at two
// thirds of its size, then enlarged, and the text is blurry.
// SAFETY: no argument to get wrong; refused when already set.
unsafe { SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) };
Self {
target: None,
device: String::new(),
surface: None,
cadence: Cadence::new(fps),
sequence: 0,
previous: std::sync::Arc::new(Vec::new()),
fitted: Vec::new(),
}
}
/// The monitors, the primary one first.
pub fn monitors() -> Vec<Monitor> {
unsafe extern "system" fn collect(
monitor: HMONITOR,
_dc: HDC,
_rect: *mut RECT,
data: LPARAM,
) -> windows_sys::core::BOOL {
// SAFETY: `data` is the vector passed by `monitors`, alive during
// the enumeration.
let list = unsafe { &mut *(data as *mut Vec<Monitor>) };
let mut info = MONITORINFOEXW {
monitorInfo: MONITORINFO {
cbSize: std::mem::size_of::<MONITORINFOEXW>() as u32,
..Default::default()
},
..Default::default()
};
// SAFETY: `info` is an MONITORINFOEXW whose size is announced.
if unsafe { GetMonitorInfoW(monitor, (&raw mut info).cast()) } != 0 {
let r = info.monitorInfo.rcMonitor;
list.push(Monitor {
device: from_wide(&info.szDevice),
x: r.left,
y: r.top,
width: (r.right - r.left).max(0) as u32,
height: (r.bottom - r.top).max(0) as u32,
primary: info.monitorInfo.dwFlags & MONITORINFOF_PRIMARY != 0,
});
}
TRUE
}
let mut list: Vec<Monitor> = Vec::new();
// SAFETY: the callback only touches `list`, which outlives the call.
unsafe {
EnumDisplayMonitors(
std::ptr::null_mut(),
std::ptr::null(),
Some(collect),
(&raw mut list) as LPARAM,
)
};
list.sort_by_key(|m| (!m.primary, m.x, m.y));
list
}
/// The application windows: visible, titled, not a tool palette, not
/// cloaked (another virtual desktop, a suspended UWP app), not ours.
fn windows() -> Vec<HWND> {
unsafe extern "system" fn collect(window: HWND, data: LPARAM) -> windows_sys::core::BOOL {
// SAFETY: `data` is the vector passed by `windows`.
let list = unsafe { &mut *(data as *mut Vec<HWND>) };
if is_application(window) {
list.push(window);
}
TRUE
}
let mut list: Vec<HWND> = Vec::new();
// SAFETY: the callback only touches `list`, which outlives the call.
unsafe { EnumWindows(Some(collect), (&raw mut list) as LPARAM) };
list
}
/// The rectangle to read for the current target, in screen coordinates.
fn rectangle(&self, target: Target) -> Result<RECT, CaptureError> {
match target {
Target::Screen => Ok(virtual_screen()),
Target::Monitor => Self::monitors()
.into_iter()
.find(|m| m.device == self.device)
.map(|m| RECT {
left: m.x,
top: m.y,
right: m.x + m.width as i32,
bottom: m.y + m.height as i32,
})
.ok_or(CaptureError::SourceGone),
Target::Window(window) => window_rect(window),
}
}
}
impl ScreenCapturer for GdiCapturer {
fn sources(&mut self) -> Result<Vec<SourceInfo>, CaptureError> {
let monitors = Self::monitors();
let mut sources = Vec::new();
for m in &monitors {
let name = if m.primary {
format!("{} (primary)", m.device)
} else {
m.device.clone()
};
sources.push(describe(
format!("{MONITOR_PREFIX}{}", m.device),
SourceKind::Screen,
name,
m.width,
m.height,
true,
));
}
if monitors.len() > 1 {
let r = virtual_screen();
sources.push(describe(
SCREEN,
SourceKind::Screen,
"All screens",
(r.right - r.left) as u32,
(r.bottom - r.top) as u32,
true,
));
}
for window in Self::windows() {
let Ok(r) = window_rect(window) else {
continue;
};
let (w, h) = ((r.right - r.left) as u32, (r.bottom - r.top) as u32);
// SAFETY: `window` came from EnumWindows; a stale handle fails.
let minimized = unsafe { IsIconic(window) } != 0;
// Minimized windows report a tiny rectangle: listed anyway, so the
// user finds them and knows why they are not offered.
if !minimized && (w < MIN_WINDOW_SIZE || h < MIN_WINDOW_SIZE) {
continue;
}
sources.push(describe(
format!("{WINDOW_PREFIX}{:x}", window as usize),
SourceKind::Window,
title(window),
w,
h,
!minimized,
));
}
Ok(sources)
}
fn start(&mut self, source: &SourceId) -> Result<(), CaptureError> {
let target = if source.0 == SCREEN {
Target::Screen
} else if let Some(device) = source.0.strip_prefix(MONITOR_PREFIX) {
if !Self::monitors().iter().any(|m| m.device == device) {
return Err(CaptureError::SourceGone);
}
self.device = device.to_string();
Target::Monitor
} else if let Some(hex) = source.0.strip_prefix(WINDOW_PREFIX) {
let window =
usize::from_str_radix(hex, 16).map_err(|_| CaptureError::SourceGone)? as HWND;
// SAFETY: IsWindow accepts any value and says whether it is one.
if unsafe { IsWindow(window) } == 0 {
return Err(CaptureError::SourceGone);
}
// SAFETY: a valid window handle.
if unsafe { IsIconic(window) } != 0 {
return Err(CaptureError::Unavailable(
"the window is minimized: restore it to share it".into(),
));
}
Target::Window(window)
} else {
return Err(CaptureError::SourceGone);
};
self.target = Some(target);
self.surface = None;
self.previous = std::sync::Arc::new(Vec::new());
self.cadence.reset();
Ok(())
}
fn next_frame(&mut self) -> Result<CapturedFrame, CaptureError> {
let target = self
.target
.ok_or_else(|| CaptureError::Internal("capture not started".into()))?;
self.cadence.wait();
let minimized = match target {
Target::Window(window) => {
// SAFETY: IsWindow accepts any value.
if unsafe { IsWindow(window) } == 0 {
return Err(CaptureError::SourceGone);
}
// SAFETY: a valid window handle.
(unsafe { IsIconic(window) }) != 0
}
_ => false,
};
// Minimized, a window has nothing to show: viewers keep the last
// image rather than a black one.
if minimized && !self.previous.is_empty() {
return Ok(self.repeat());
}
let r = self.rectangle(target)?;
let (w, h) = ((r.right - r.left) as u32, (r.bottom - r.top) as u32);
if w == 0 || h == 0 {
return Err(CaptureError::Internal("zero-size source".into()));
}
if self
.surface
.as_ref()
.is_none_or(|s| (s.width, s.height) != (w, h))
{
self.surface = Some(Surface::new(w, h)?);
}
let surface = self.surface.as_mut().expect("just created");
match target {
Target::Window(window) => {
surface.print_window(window)?;
// Some applications draw on the GPU and leave PrintWindow a
// black image (and Wine always does): the window is then read
// where it shows on screen, as long as nothing covers it.
if surface.is_black() {
surface.copy_screen(r.left, r.top)?;
}
}
_ => surface.copy_screen(r.left, r.top)?,
}
surface.draw_cursor(r.left, r.top);
// The output follows the source (#16); only an odd dimension is
// trimmed by one pixel, which I420 refuses.
let output = pixels::even((w, h));
let bgra = if (w, h) == output {
surface.pixels().to_vec()
} else {
pixels::fit(
surface.pixels(),
w as usize,
h as usize,
(output.0 as usize, output.1 as usize),
&mut self.fitted,
);
self.fitted.clone()
};
// GDI cannot tell an unchanged screen: a comparison costs about a
// millisecond in 1080p, much less than encoding a repeat (#86).
let fresh = bgra != *self.previous;
let bgra = if fresh {
std::sync::Arc::new(bgra)
} else {
self.previous.clone()
};
self.previous = bgra.clone();
let frame = CapturedFrame {
width: output.0,
height: output.1,
bgra,
fresh,
captured_at: Instant::now(),
sequence: self.sequence,
};
self.sequence += 1;
Ok(frame)
}
fn stop(&mut self) {
self.target = None;
self.surface = None;
}
}
impl GdiCapturer {
/// The last image again, marked as not fresh.
fn repeat(&mut self) -> CapturedFrame {
let (width, height) = self
.surface
.as_ref()
.map(|s| pixels::even((s.width, s.height)))
.unwrap_or((0, 0));
let frame = CapturedFrame {
width,
height,
bgra: self.previous.clone(),
fresh: false,
captured_at: Instant::now(),
sequence: self.sequence,
};
self.sequence += 1;
frame
}
}
/// A memory device context and its top-down 32-bit DIB: GDI draws into it,
/// and its bits are the BGRA image.
struct Surface {
dc: HDC,
bitmap: HBITMAP,
previous: HGDIOBJ,
bits: *mut u8,
width: u32,
height: u32,
}
impl Surface {
fn new(width: u32, height: u32) -> Result<Self, CaptureError> {
let info = BITMAPINFO {
bmiHeader: BITMAPINFOHEADER {
biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
biWidth: width as i32,
// Negative: rows from top to bottom, as the encoder reads them.
biHeight: -(height as i32),
biPlanes: 1,
biBitCount: 32,
biCompression: BI_RGB,
..Default::default()
},
..Default::default()
};
// SAFETY: plain GDI object creation; every handle is checked, and
// freed by `Drop` or on the failure path.
unsafe {
let screen = GetDC(std::ptr::null_mut());
let dc = CreateCompatibleDC(screen);
ReleaseDC(std::ptr::null_mut(), screen);
if dc.is_null() {
return Err(gdi("CreateCompatibleDC"));
}
let mut bits = std::ptr::null_mut();
let bitmap = CreateDIBSection(
dc,
&info,
DIB_RGB_COLORS,
&mut bits,
std::ptr::null_mut(),
0,
);
if bitmap.is_null() || bits.is_null() {
DeleteDC(dc);
return Err(gdi("CreateDIBSection"));
}
let previous = SelectObject(dc, bitmap);
Ok(Self {
dc,
bitmap,
previous,
bits: bits.cast(),
width,
height,
})
}
}
fn copy_screen(&mut self, x: i32, y: i32) -> Result<(), CaptureError> {
// SAFETY: both device contexts are valid; the screen one is released.
let copied = unsafe {
let screen = GetDC(std::ptr::null_mut());
let copied = BitBlt(
self.dc,
0,
0,
self.width as i32,
self.height as i32,
screen,
x,
y,
// Layered windows (menus, tooltips) are in the image too.
SRCCOPY | CAPTUREBLT,
);
ReleaseDC(std::ptr::null_mut(), screen);
copied
};
if copied == 0 {
// The secure desktop (UAC, lock screen) refuses to be read.
return Err(CaptureError::Unavailable(
"Windows refuses to read the screen right now (locked session or elevation prompt)"
.into(),
));
}
Ok(())
}
fn print_window(&mut self, window: HWND) -> Result<(), CaptureError> {
// SAFETY: valid window and device context.
if unsafe { PrintWindow(window, self.dc, PW_RENDERFULLCONTENT) } == 0 {
return Err(CaptureError::Unavailable(
"Windows refuses to draw this window".into(),
));
}
Ok(())
}
/// Draws the pointer where it is, relative to the captured area.
fn draw_cursor(&mut self, left: i32, top: i32) {
let mut cursor = CURSORINFO {
cbSize: std::mem::size_of::<CURSORINFO>() as u32,
..Default::default()
};
// SAFETY: `cursor` announces its size; the icon bitmaps that
// GetIconInfo creates are deleted right after.
unsafe {
if GetCursorInfo(&mut cursor) == 0 || cursor.flags & CURSOR_SHOWING == 0 {
return;
}
let mut icon = ICONINFO::default();
let (hot_x, hot_y) = if GetIconInfo(cursor.hCursor, &mut icon) != 0 {
if !icon.hbmMask.is_null() {
DeleteObject(icon.hbmMask);
}
if !icon.hbmColor.is_null() {
DeleteObject(icon.hbmColor);
}
(icon.xHotspot as i32, icon.yHotspot as i32)
} else {
(0, 0)
};
let POINT { x, y } = cursor.ptScreenPos;
DrawIconEx(
self.dc,
x - left - hot_x,
y - top - hot_y,
cursor.hCursor,
0,
0,
0,
std::ptr::null_mut(),
DI_NORMAL,
);
}
}
/// Every pixel black: nothing was drawn.
fn is_black(&self) -> bool {
self.pixels()
.as_chunks::<4>()
.0
.iter()
.all(|p| p[..3] == [0, 0, 0])
}
fn pixels(&self) -> &[u8] {
// GDI batches its drawing: without a flush, the bits may not hold the
// last BitBlt yet.
// SAFETY: no argument.
unsafe { GdiFlush() };
let len = self.width as usize * self.height as usize * 4;
// SAFETY: the DIB holds width × height 32-bit pixels, alive with
// `self`, and GDI is done drawing when this is called.
unsafe { std::slice::from_raw_parts(self.bits, len) }
}
}
impl Drop for Surface {
fn drop(&mut self) {
// SAFETY: created by `Surface::new`, freed once.
unsafe {
SelectObject(self.dc, self.previous);
DeleteObject(self.bitmap);
DeleteDC(self.dc);
}
}
}
/// The rectangle covering every monitor.
fn virtual_screen() -> RECT {
// SAFETY: plain metrics.
unsafe {
let left = GetSystemMetrics(SM_XVIRTUALSCREEN);
let top = GetSystemMetrics(SM_YVIRTUALSCREEN);
RECT {
left,
top,
right: left + GetSystemMetrics(SM_CXVIRTUALSCREEN),
bottom: top + GetSystemMetrics(SM_CYVIRTUALSCREEN),
}
}
}
fn window_rect(window: HWND) -> Result<RECT, CaptureError> {
let mut r = RECT::default();
// SAFETY: `r` receives the rectangle; a stale handle fails.
if unsafe { GetWindowRect(window, &mut r) } == 0 {
return Err(CaptureError::SourceGone);
}
Ok(r)
}
fn is_application(window: HWND) -> bool {
// SAFETY: every call accepts a window handle from EnumWindows and fails
// cleanly if it went away in between.
unsafe {
if IsWindowVisible(window) == 0 {
return false;
}
let style = GetWindowLongPtrW(window, GWL_EXSTYLE) as u32;
if style & WS_EX_TOOLWINDOW != 0 {
return false;
}
let mut cloaked = 0u32;
let cloaked_read = DwmGetWindowAttribute(
window,
DWMWA_CLOAKED as u32,
(&raw mut cloaked).cast(),
std::mem::size_of::<u32>() as u32,
) >= 0;
if cloaked_read && cloaked != 0 {
return false;
}
let mut process = 0u32;
GetWindowThreadProcessId(window, &mut process);
if process == std::process::id() {
return false;
}
}
!title(window).is_empty()
}
fn title(window: HWND) -> String {
let mut buffer = [0u16; 256];
// SAFETY: the buffer length is passed.
let len = unsafe { GetWindowTextW(window, buffer.as_mut_ptr(), buffer.len() as i32) };
String::from_utf16_lossy(&buffer[..len.max(0) as usize])
}
fn from_wide(text: &[u16]) -> String {
let end = text.iter().position(|c| *c == 0).unwrap_or(text.len());
String::from_utf16_lossy(&text[..end])
}
fn gdi(call: &str) -> CaptureError {
CaptureError::Internal(format!("{call}: {}", std::io::Error::last_os_error()))
}
#[cfg(test)]
mod tests {
use super::*;
/// Needs a desktop: under Wine, an X server (`Xvfb :7 & DISPLAY=:7`).
#[test]
#[ignore = "needs a Windows desktop"]
fn the_primary_monitor_is_captured_with_its_size() {
let mut capturer = GdiCapturer::new(30);
let sources = capturer.sources().unwrap();
let first = sources.first().expect("no monitor");
assert_eq!(first.kind, SourceKind::Screen);
capturer.start(&first.id).unwrap();
let frame = capturer.next_frame().unwrap();
let (w, h) = pixels::even((first.width, first.height));
assert_eq!((frame.width, frame.height), (w, h));
assert_eq!(frame.bgra.len(), (w * h * 4) as usize);
// Not a black rectangle: a desktop has more than one colour.
let first_pixel = &frame.bgra[..4];
let varied = frame
.bgra
.as_chunks::<4>()
.0
.iter()
.any(|p| p[..3] != first_pixel[..3]);
assert!(varied, "uniform image, first pixel {first_pixel:?}");
}
#[test]
fn a_wide_string_stops_at_its_terminator() {
let text: Vec<u16> = r"\\.\DISPLAY1".encode_utf16().chain([0, 65, 66]).collect();
assert_eq!(from_wide(&text), r"\\.\DISPLAY1");
}
}
+10 -1
View File
@@ -13,6 +13,8 @@ use crate::portal::PortalInfo;
pub enum SessionType {
Wayland,
X11,
/// A Windows desktop (#8): GDI reads every monitor and window.
Windows,
/// Session without a display server: capture and virtual display impossible.
Headless,
}
@@ -63,7 +65,12 @@ pub struct Environment {
impl Environment {
/// Reads the real environment of the process.
pub fn detect() -> Self {
Self::from_vars(|name| std::env::var(name).ok())
let mut environment = Self::from_vars(|name| std::env::var(name).ok());
// A Windows session has none of these variables: the system says it.
if cfg!(windows) {
environment.session = SessionType::Windows;
}
environment
}
/// Injectable detection, for tests.
@@ -118,6 +125,8 @@ impl Environment {
match self.session {
SessionType::Headless => VirtualDisplayBackend::NotApplicable,
SessionType::X11 => VirtualDisplayBackend::Evdi,
// An IddCx driver would do it, and is an extension (ROADMAP).
SessionType::Windows => VirtualDisplayBackend::Unsupported,
SessionType::Wayland => {
if portal.is_some_and(PortalInfo::supports_virtual_display) {
VirtualDisplayBackend::PortalVirtual
+7 -2
View File
@@ -44,7 +44,7 @@ options:
--virtual virtual screen (desktop portal, GNOME 46 or KDE Plasma)
--pick-window Wayland: the desktop offers to pick a window
--list list capturable screens and windows, then exit
--x11-source ID X11: capture this source (identifier given by --list)
--x11-source ID X11 or Windows: capture this source (identifier given by --list)
-S, --synthetic generated test pattern rather than a screen
--test-portal ask the portal for a screen and print the stream obtained
-h, --help this help
@@ -167,6 +167,7 @@ fn choose(options: &Options, session: SessionType) -> Result<SourceChoice, Error
let display = match session {
SessionType::Wayland => DisplaySession::Wayland,
SessionType::X11 => DisplaySession::X11,
SessionType::Windows => DisplaySession::Windows,
SessionType::Headless => DisplaySession::Headless,
};
let forced = options
@@ -187,6 +188,10 @@ fn choose(options: &Options, session: SessionType) -> Result<SourceChoice, Error
.clone()
.unwrap_or_else(|| "x11:ecran".into()),
},
// No identifier: the primary monitor.
Backend::Gdi => SourceChoice::Windows {
id: options.x11_source.clone().unwrap_or_default(),
},
Backend::Portal => SourceChoice::Portal {
virtual_display: options.virtual_display,
window: options.pick_window,
@@ -392,7 +397,7 @@ fn list() -> Result<(), Error> {
};
for source in rs_session::sources::list(&environment, None, offer) {
let id = match &source.choice {
SourceChoice::X11 { id } => id.clone(),
SourceChoice::X11 { id } | SourceChoice::Windows { id } => id.clone(),
SourceChoice::Synthetic { .. } => "--synthetic".into(),
SourceChoice::Portal {
virtual_display: true,
+77
View File
@@ -57,6 +57,8 @@ pub enum StartCaptureError {
SourceNotFound(String),
#[error("X11 only exists on Linux")]
NoX11,
#[error("this source only exists on Windows")]
NoWindows,
#[error(
"this desktop's portal cannot create a virtual screen (no VIRTUAL type in \
AvailableSourceTypes): share an existing screen"
@@ -96,6 +98,7 @@ impl StartCaptureError {
Self::NoPipewire => Notice::new("no_pipewire", text),
Self::SourceNotFound(id) => Notice::new("source_not_found", text).with("id", id),
Self::NoX11 => Notice::new("no_x11", text),
Self::NoWindows => Notice::new("no_windows", text),
Self::NoVirtualDisplay => Notice::new("no_virtual_display", text),
Self::NoWindow => Notice::new("no_window", text),
Self::Task(e) => Notice::new("capture_failed", text).with("detail", e),
@@ -180,6 +183,7 @@ pub async fn start(
})
}
SourceChoice::X11 { id } => x11(id.clone(), settings, codec).await,
SourceChoice::Windows { id } => windows(id.clone(), settings, codec).await,
SourceChoice::Portal {
virtual_display,
window,
@@ -255,6 +259,79 @@ async fn x11(
Err(StartCaptureError::NoX11)
}
/// A Windows monitor or window through GDI (#8); an empty id is the primary
/// monitor.
#[cfg(windows)]
async fn windows(
id: String,
settings: &StreamSettings,
codec: Encoding,
) -> Result<StartedCapture, StartCaptureError> {
use rs_capture::windows::{GdiCapturer, MONITOR_PREFIX, SCREEN};
let settings = *settings;
tokio::task::spawn_blocking(move || {
let mut capturer = GdiCapturer::new(settings.max_fps);
let sources = capturer.sources()?;
let wanted = if id.is_empty() {
sources.first()
} else {
sources.iter().find(|s| s.id.0 == id)
}
.ok_or_else(|| StartCaptureError::SourceNotFound(id.clone()))?;
if !wanted.available {
return Err(StartCaptureError::Capture(
rs_capture::CaptureError::Unavailable(
"the window is minimized: restore it to share it".into(),
),
));
}
let size = rs_capture::pixels::even((wanted.width, wanted.height));
tracing::info!(
event = "gdi_capture",
kind = ?wanted.kind,
width = size.0,
height = size.1,
"Windows capture (GDI)"
);
let primary = GdiCapturer::monitors()
.into_iter()
.find(|m| m.primary)
.map(|m| m.device);
let label = match wanted.id.0.strip_prefix(MONITOR_PREFIX) {
Some(device) => Label::Monitor {
primary: primary.as_deref() == Some(device),
output: device.trim_start_matches(r"\\.\").to_string(),
},
None if wanted.id.0 == SCREEN => Label::AllScreens,
None => Label::Title {
text: wanted.name.clone(),
},
};
let source = SharedSource {
kind: wanted.kind,
name: wanted.name.clone(),
label,
backend: "gdi".into(),
width: size.0,
height: size.1,
};
let id = wanted.id.clone();
spawn_live(capturer, size, &settings, codec, &id, source)
})
.await
.map_err(|e| StartCaptureError::Task(e.to_string()))?
}
#[cfg(not(windows))]
async fn windows(
_: String,
_: &StreamSettings,
_: Encoding,
) -> Result<StartedCapture, StartCaptureError> {
Err(StartCaptureError::NoWindows)
}
/// Starts a capture and its encoder in the dedicated thread.
fn spawn_live<C>(
mut capturer: C,
+1
View File
@@ -1165,6 +1165,7 @@ fn capabilities(
session: match environment.session {
SessionType::Wayland => "wayland",
SessionType::X11 => "x11",
SessionType::Windows => "windows",
SessionType::Headless => "none",
}
.into(),
+73
View File
@@ -106,6 +106,7 @@ pub fn list(
}
}
SessionType::X11 => sources.extend(x11()),
SessionType::Windows => sources.extend(windows()),
SessionType::Headless => {}
}
if offer.test_pattern {
@@ -191,6 +192,72 @@ fn x11() -> Vec<SourceOption> {
Vec::new()
}
/// Every monitor, all of them together, then every window (#8), thumbnails
/// included: GDI reads them without asking.
#[cfg(windows)]
fn windows() -> Vec<SourceOption> {
use rs_capture::ScreenCapturer;
use rs_capture::windows::{GdiCapturer, MONITOR_PREFIX, SCREEN};
// High frame rate: each thumbnail waits for a frame, better make it quick.
let mut capture = GdiCapturer::new(60);
let Ok(sources) = capture.sources() else {
return Vec::new();
};
let primary = GdiCapturer::monitors()
.into_iter()
.find(|m| m.primary)
.map(|m| m.device);
sources
.into_iter()
.map(|source| {
let frame = source
.available
.then(|| {
capture
.start(&source.id)
.and_then(|()| capture.next_frame())
.ok()
})
.flatten();
let label = match source.id.0.strip_prefix(MONITOR_PREFIX) {
Some(device) => Label::Monitor {
output: display_name(device),
primary: primary.as_deref() == Some(device),
},
None if source.id.0 == SCREEN => Label::AllScreens,
None => Label::Title {
text: source.name.clone(),
},
};
SourceOption {
choice: SourceChoice::Windows {
id: source.id.0.clone(),
},
kind: source.kind,
name: source.name,
label,
width: source.width,
height: source.height,
thumbnail: frame.as_ref().and_then(thumbnail),
note: (!source.available).then_some(SourceNote::Minimized),
available: source.available,
}
})
.collect()
}
#[cfg(not(windows))]
fn windows() -> Vec<SourceOption> {
Vec::new()
}
/// `\\.\DISPLAY2` reads `DISPLAY2` in the interface.
#[cfg_attr(not(windows), allow(dead_code, reason = "used by the Windows listing"))]
fn display_name(device: &str) -> String {
device.trim_start_matches(r"\\.\").to_string()
}
/// Scales a frame down to a PNG thumbnail, as a `data:` URL. Box averaging:
/// nearest neighbour makes text unreadable and flickering.
pub fn thumbnail(frame: &CapturedFrame) -> Option<String> {
@@ -273,4 +340,10 @@ mod tests {
assert!(matches!(sources[0].choice, SourceChoice::Synthetic { .. }));
assert!(sources[0].thumbnail.is_some());
}
#[test]
fn a_windows_device_reads_without_its_prefix() {
assert_eq!(display_name(r"\\.\DISPLAY2"), "DISPLAY2");
assert_eq!(display_name("DISPLAY1"), "DISPLAY1");
}
}
+3
View File
@@ -33,6 +33,9 @@ pub enum SourceChoice {
Synthetic { width: u32, height: u32 },
/// An X11 screen, monitor or window, by identifier.
X11 { id: String },
/// A Windows monitor or window, by identifier (#8). Empty: the primary
/// monitor.
Windows { id: String },
/// The desktop portal (Wayland). The desktop shows its own picker: it is
/// the one that says which screen, or which window.
Portal {
+5 -1
View File
@@ -9,6 +9,7 @@ est un choix: il dit ce que voit l'utilisateur, pas seulement ce que fait le cod
| --- | --- | --- |
| X11 | chaque moniteur RandR (le principal en tête), puis « Tous les écrans », puis chaque fenêtre | oui |
| Wayland | « Un écran », et « Un second écran (virtuel) » si le portail l'annonce | non |
| Windows | chaque moniteur (le principal en tête), « Tous les écrans » s'il y en a plusieurs, puis chaque fenêtre (GDI, #8) | oui |
| toutes | la mire de test, si **Réglages → Débogage** la propose (#91) | oui |
La mire de test n'est plus proposée par défaut: c'est un outil de vérification, pas une source
@@ -38,7 +39,10 @@ survit à un débranchement suivi d'un rebranchement, pas l'indice.
bureau qui liste les fenêtres. Un bureau dont le portail ne l'annonce pas affiche l'entrée grisée
avec sa raison, **avant** le démarrage: on ne rend pas un écran entier à qui a demandé une
fenêtre.
- Windows: pas encore de capture, donc pas de critère vérifié. macOS: hors périmètre (#90).
- Windows (#8): `PrintWindow` lit une fenêtre même couverte. Quand elle rend une image noire
(application dessinée par le GPU, ou Wine), la fenêtre est lue là où elle s'affiche, tant que
rien ne la couvre. Une fenêtre réduite est listée mais grisée, et garde sa dernière image en
plein partage. Vérifié sous Wine seulement. macOS: hors périmètre (#90).
## Changement de résolution en cours de partage
+1
View File
@@ -297,6 +297,7 @@
"no_pipewire": "This build cannot capture under Wayland (no PipeWire support).",
"source_not_found": "Source {id} not found.",
"no_x11": "X11 capture only exists on Linux.",
"no_windows": "This source only exists on Windows.",
"no_virtual_display": "This desktop cannot create a virtual screen: share an existing screen.",
"no_window": "This desktop can only share an entire screen.",
"alias_invalid": "A device name is empty, too long or has control characters.",
+1
View File
@@ -297,6 +297,7 @@
"no_pipewire": "Cette version ne sait pas capturer sous Wayland (sans PipeWire).",
"source_not_found": "Source {id} introuvable.",
"no_x11": "La capture X11 n'existe que sous Linux.",
"no_windows": "Cette source n'existe que sous Windows.",
"no_virtual_display": "Ce bureau ne sait pas créer d'écran virtuel : partagez un écran existant.",
"no_window": "Ce bureau ne sait partager qu'un écran entier.",
"alias_invalid": "Un nom d'appareil est vide, trop long ou contient des caractères de contrôle.",