Skip to main content

oa/vision/
screen_capture.rs

1//! Screen capture sessions producing runtime-owned video frames.
2//!
3//! Donor: `source/cpp/include/oa/vision/screenCapture.h` and
4//! `source/cpp/lib/oa/vision/capture/screenCapture.cpp`.
5//!
6//! Donor mapped-memory route, with portal consent and nonblocking PipeWire
7//! polling on the Runtime-owning thread. Returned textures own their pixels;
8//! producer buffers are copied and released before `poll` returns. DMA-BUF
9//! import remains separate, unimplemented qualification work.
10
11#[cfg(all(target_os = "linux", feature = "pipewire"))]
12mod pipewire;
13#[cfg(all(target_os = "linux", feature = "pipewire"))]
14mod portal;
15
16#[cfg(all(target_os = "linux", feature = "pipewire"))]
17use crate::runtime::RuntimeHandle;
18use crate::video::VideoFrame;
19#[cfg(all(target_os = "linux", feature = "pipewire"))]
20use crate::video::{VideoColorInfo, VideoColorMatrix, VideoColorRange, VideoFrameTiming};
21pub use crate::vision::types::ScreenCaptureConfig;
22#[cfg(all(target_os = "linux", feature = "pipewire"))]
23use crate::{DType, Matrix};
24use crate::{Error, Result, Runtime};
25
26/// Whether the capture targets whatever the compositor offers, an entire
27/// monitor, or an individual window.
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
29pub enum ScreenCaptureTarget {
30	/// Let the compositor present its own monitor-or-window picker.
31	#[default]
32	MonitorOrWindow,
33	/// Capture an entire monitor.
34	Monitor,
35	/// Capture an individual window.
36	Window,
37}
38
39/// Whether captured frames composite the cursor into the image.
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
41pub enum ScreenCaptureCursor {
42	/// Frames never contain the cursor.
43	Hidden,
44	/// Frames contain the cursor wherever the compositor draws it.
45	#[default]
46	Embedded,
47}
48
49impl Default for ScreenCaptureConfig {
50	fn default() -> Self {
51		Self {
52			target: ScreenCaptureTarget::MonitorOrWindow,
53			cursor: ScreenCaptureCursor::Embedded,
54			preferred_width: 1920,
55			preferred_height: 1080,
56			preferred_fps: 30,
57			ring_frames: 4,
58		}
59	}
60}
61
62/// Portal-approved screen or window capture producing owned RGBA8 frames.
63///
64/// `open` may show the desktop picker. `poll` is nonblocking and never retains
65/// a PipeWire producer slot after returning. Drop releases host resources only;
66/// `close` explicitly disconnects the stream and reports a disconnect failure.
67pub struct ScreenCapture {
68	#[cfg(all(target_os = "linux", feature = "pipewire"))]
69	runtime: RuntimeHandle,
70	#[cfg(all(target_os = "linux", feature = "pipewire"))]
71	fps: u32,
72	width: u32,
73	height: u32,
74	#[cfg(all(target_os = "linux", feature = "pipewire"))]
75	backend: Option<pipewire::Backend>,
76}
77
78impl ScreenCapture {
79	/// Whether this platform has the portal adapter and a session bus.
80	/// This does not request permission or guarantee that a portal service or
81	/// a selected source is available. Actual admission happens in `open`.
82	#[must_use]
83	pub fn is_supported() -> bool {
84		#[cfg(all(target_os = "linux", feature = "pipewire"))]
85		{
86			std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_some() && portal::Portal::is_supported()
87		}
88		#[cfg(not(all(target_os = "linux", feature = "pipewire")))]
89		{
90			false
91		}
92	}
93
94	/// Request desktop consent and open one selected screen/window stream.
95	///
96	/// # Errors
97	/// Rejects invalid extent, FPS or ring hints, missing platform support,
98	/// cancelled/denied permission, and portal/PipeWire setup failures.
99	pub fn open(runtime: &Runtime, config: &ScreenCaptureConfig) -> Result<Self> {
100		if config.preferred_width == 0
101			|| config.preferred_height == 0
102			|| config.preferred_width > 16384
103			|| config.preferred_height > 16384
104		{
105			return Err(Error::invalid_argument(
106				"screen capture preferred extent must be in 1..=16384",
107			));
108		}
109		if config.preferred_fps == 0 || config.preferred_fps > 240 {
110			return Err(Error::invalid_argument(
111				"screen capture preferred frame rate must be in 1..=240",
112			));
113		}
114		if config.ring_frames == 0 || config.ring_frames > 64 {
115			return Err(Error::invalid_argument(
116				"screen capture ring depth must be in 1..=64",
117			));
118		}
119		if !Self::is_supported() {
120			return Err(Error::missing_capability(
121				"screen capture requires Linux, libportal and a desktop session bus",
122			));
123		}
124		#[cfg(all(target_os = "linux", feature = "pipewire"))]
125		{
126			Ok(Self {
127				runtime: runtime.handle().clone(),
128				fps: config.preferred_fps,
129				width: 0,
130				height: 0,
131				backend: Some(pipewire::Backend::open(config)?),
132			})
133		}
134		#[cfg(not(all(target_os = "linux", feature = "pipewire")))]
135		{
136			let _ = runtime;
137			Err(Error::missing_capability(
138				"screen capture requires the Linux portal/PipeWire adapter",
139			))
140		}
141	}
142
143	/// Poll once without waiting; return only a new caller-owned RGBA8 frame.
144	///
145	/// # Errors
146	/// Reports closed/revoked streams, malformed frames or texture allocation.
147	pub fn poll(&mut self) -> Result<Option<VideoFrame>> {
148		#[cfg(all(target_os = "linux", feature = "pipewire"))]
149		{
150			let backend = self
151				.backend
152				.as_mut()
153				.ok_or_else(|| Error::failed_precondition("ScreenCapture is closed"))?;
154			let Some(frame) = backend.poll()? else {
155				return Ok(None);
156			};
157			let width = frame.width as usize;
158			let height = frame.height as usize;
159			let data = Matrix::allocate(
160				&self.runtime,
161				vec![height, width, 4],
162				frame.rgba.len(),
163				DType::U8,
164			)?;
165			data.write_values(&frame.rgba)?;
166			let texture = crate::render::texture_from_matrix(data, width, height)?;
167			self.width = frame.width;
168			self.height = frame.height;
169			crate::video::from_texture(
170				&texture,
171				VideoFrameTiming::new_from_microseconds(frame.pts, 1_000_000 / u64::from(self.fps)),
172				VideoColorInfo::new(VideoColorMatrix::Bt709, VideoColorRange::Full),
173			)
174			.map(Some)
175		}
176		#[cfg(not(all(target_os = "linux", feature = "pipewire")))]
177		{
178			Err(Error::failed_precondition("ScreenCapture is closed"))
179		}
180	}
181
182	/// Explicitly disconnect and release the portal grant. Idempotent.
183	/// # Errors
184	/// Reports a PipeWire disconnect failure after releasing the session.
185	pub fn close(&mut self) -> Result<()> {
186		#[cfg(all(target_os = "linux", feature = "pipewire"))]
187		if let Some(backend) = self.backend.take() {
188			return backend.close();
189		}
190		Ok(())
191	}
192	/// Whether PipeWire currently reports a streaming source.
193	#[must_use]
194	pub fn is_streaming(&self) -> bool {
195		#[cfg(all(target_os = "linux", feature = "pipewire"))]
196		{
197			self
198				.backend
199				.as_ref()
200				.is_some_and(pipewire::Backend::is_streaming)
201		}
202		#[cfg(not(all(target_os = "linux", feature = "pipewire")))]
203		{
204			false
205		}
206	}
207	/// Latest delivered frame width; zero before the first frame.
208	pub const fn width(&self) -> u32 {
209		self.width
210	}
211	/// Latest delivered frame height; zero before the first frame.
212	pub const fn height(&self) -> u32 {
213		self.height
214	}
215}