Skip to main content

moq_video/capture/
mod.rs

1//! Surface capture. [`Config`] is shared; the implementation is per-platform and
2//! per-source:
3//! - macOS camera -> AVFoundation, screen -> ScreenCaptureKit, both yielding
4//!   zero-copy `CVPixelBuffer` surfaces straight to VideoToolbox.
5//! - Linux camera -> native V4L2 (YUYV / MJPEG -> CPU I420), or a PipeWire
6//!   camera node (`pipewire` feature), X11 display and window -> X11, and a
7//!   system-picked screen or window -> xdg-desktop-portal + PipeWire (`pipewire`
8//!   feature).
9//! - Windows camera -> native Media Foundation (`IMFSourceReader`), display and
10//!   window -> Windows.Graphics.Capture (GPU NV12, Windows 10 2004 or newer).
11//!
12//! [`encode::publish_capture`](crate::encode::publish_capture) consumes [`Config`].
13
14use std::sync::Arc;
15
16use crate::{Error, Frame, FrameRate, Output};
17
18mod channel;
19use channel::FrameChannel;
20
21/// Type-erased keep-alive for a capture backend, dropped to release the device.
22///
23/// `Send` off macOS (the backend is a pump-thread guard: an `Arc` stop flag plus
24/// a `JoinHandle`), which keeps [`publish_capture`](crate::encode::publish_capture)
25/// `Send` so a server can `tokio::spawn` it. On macOS the backend is the objc
26/// `AVCaptureSession` (plus its delegate), which is `!Send`, so that platform's
27/// capture future is `!Send` too.
28#[cfg(not(target_os = "macos"))]
29type Keepalive = Box<dyn std::any::Any + Send>;
30#[cfg(target_os = "macos")]
31type Keepalive = Box<dyn std::any::Any>;
32
33#[cfg(target_os = "macos")]
34mod avfoundation;
35#[cfg(target_os = "macos")]
36mod screencapture;
37#[cfg(target_os = "macos")]
38mod surface;
39
40// Native V4L2 camera capture on Linux.
41#[cfg(target_os = "linux")]
42mod v4l2;
43// The mode choice V4L2 and PipeWire cameras share.
44#[cfg(target_os = "linux")]
45mod mode;
46// Native X11 display and window capture, including the portal fallback.
47#[cfg(target_os = "linux")]
48mod x11;
49
50// Portal + PipeWire screen capture and PipeWire camera capture on Linux.
51#[cfg(all(target_os = "linux", feature = "pipewire"))]
52mod pipewire;
53
54/// System-picked screen or window selection and its restore grant.
55#[cfg(any(all(target_os = "linux", feature = "pipewire"), test))]
56pub mod portal;
57
58// Native Media Foundation camera capture on Windows.
59#[cfg(target_os = "windows")]
60mod mediafoundation;
61
62// The WGC notification state and selector tests also run on headless hosts.
63#[cfg(any(target_os = "windows", test))]
64mod wgc;
65
66// Blocking-device -> async-channel bridge used by V4L2 / Media Foundation.
67#[cfg(any(target_os = "linux", target_os = "windows"))]
68mod pump;
69
70// Geometry debounce shared by the X11 and Windows window backends. The state
71// machine is platform independent, so it is also built under `cfg(test)` to
72// keep its tests running on every host.
73#[cfg(any(target_os = "linux", target_os = "windows", test))]
74mod settle;
75
76/// What to capture, selected by a native identifier or the system picker.
77///
78/// The identifiers come from [`cameras`], [`displays`], [`windows`], and
79/// [`apps`]; each listed item's `source()` builds the matching variant.
80#[derive(Clone, Debug, PartialEq, Eq)]
81#[non_exhaustive]
82pub enum Source {
83	/// A camera / webcam. `None` opens the default camera.
84	///
85	/// The identifiers from [`cameras`] are an AVFoundation `uniqueID` on macOS,
86	/// a Media Foundation symbolic link on Windows, and on Linux a `/dev/videoN`
87	/// path or, with the `pipewire` feature, a `pipewire:<node name>` id. Bare
88	/// numeric indices remain accepted on Linux and Windows.
89	///
90	/// With the `pipewire` feature, Linux lists a webcam that a PipeWire node
91	/// fronts by the node's id, since PipeWire shares the camera with other
92	/// clients while a V4L2 open holds it exclusively. Only devices no node
93	/// fronts list as `/dev/videoN`. `pipewire` alone opens the listed camera
94	/// with the highest session priority, which the session manager treats as
95	/// default.
96	///
97	/// The id picks the backend: a `/dev/videoN` path always opens V4L2, listed
98	/// or not, so an id saved from an earlier listing keeps working, and a
99	/// `pipewire` id always opens PipeWire.
100	///
101	/// With the `pipewire` feature, `None` opens PipeWire's default camera when
102	/// PipeWire lists a camera, and `/dev/video0` otherwise, such as on a host
103	/// without a PipeWire session. Inside a sandbox (Flatpak or Snap) it always
104	/// goes through the camera portal. Without the feature, `None` opens
105	/// `/dev/video0`.
106	Camera(Option<String>),
107
108	/// A whole display. [`DisplaySelection::default`] opens the main display.
109	///
110	/// The id is the opaque value [`displays`] reports. Linux supports X11
111	/// displays only, including XWayland's `x11:` ids; on Wayland the main
112	/// display and any other id are refused, so ask the system picker with
113	/// [`Source::Portal`] instead.
114	Display(DisplaySelection),
115
116	/// A single window, by the id [`windows`] reports. Supported on macOS,
117	/// Windows, and X11.
118	Window(String),
119
120	/// Every window belonging to one application, by the id [`apps`] reports
121	/// (a bundle identifier). Windows that open later are included. macOS only.
122	App(String),
123
124	/// A screen or window chosen through the Linux system picker.
125	///
126	/// Clone the selection to reopen the same source, as an on-demand capture
127	/// does for each viewer; create a new one to ask for a different source.
128	/// Restoration depends on compositor support.
129	#[cfg(all(target_os = "linux", feature = "pipewire"))]
130	Portal(portal::Selection),
131}
132
133/// The default camera, matching the historical `Config::default()`.
134impl Default for Source {
135	fn default() -> Self {
136		Self::Camera(None)
137	}
138}
139
140impl Source {
141	/// A short human-readable name for the source, used in logs and as the
142	/// captured device label.
143	///
144	/// ScreenCaptureKit and WGC serve multiple source kinds, so they name the
145	/// source from the config. The other backends label a stream
146	/// with the device they resolved (`/dev/video0`, a Media Foundation friendly
147	/// name), which the config doesn't know.
148	#[cfg(any(target_os = "macos", target_os = "windows", test))]
149	pub(crate) fn label(&self) -> String {
150		match self {
151			Self::Camera(None) => "camera".to_string(),
152			Self::Camera(Some(id)) => format!("camera:{id}"),
153			Self::Display(selection) => match &selection.id {
154				None => "display".to_string(),
155				Some(id) => format!("display:{}", id.strip_prefix("display:").unwrap_or(id)),
156			},
157			Self::Window(id) => format!("window:{}", id.strip_prefix("window:").unwrap_or(id)),
158			Self::App(id) => format!("app:{id}"),
159			#[cfg(all(target_os = "linux", feature = "pipewire"))]
160			Self::Portal(selection) => format!("portal:{:?}", selection.kind()),
161		}
162	}
163}
164
165/// Which display [`Source::Display`] captures.
166///
167/// `#[non_exhaustive]`: build it with [`DisplaySelection::new`] or
168/// [`DisplaySelection::default`], so a capture option can join it without
169/// breaking callers.
170#[derive(Clone, Debug, Default, PartialEq, Eq)]
171#[non_exhaustive]
172pub struct DisplaySelection {
173	/// The opaque id [`displays`] reports. `None` selects the main display.
174	pub id: Option<String>,
175}
176
177impl DisplaySelection {
178	/// Select the display with this id, as [`displays`] reports it.
179	pub fn new(id: impl Into<String>) -> Self {
180		Self { id: Some(id.into()) }
181	}
182}
183
184/// A camera reported by [`cameras`].
185#[derive(Clone, Debug)]
186#[non_exhaustive]
187pub struct Camera {
188	/// Opaque identifier: pass to [`Source::Camera`].
189	pub id: String,
190	/// Human-readable name, e.g. "FaceTime HD Camera".
191	pub name: String,
192}
193
194impl Camera {
195	/// The [`Source`] that captures this camera.
196	pub fn source(&self) -> Source {
197		Source::Camera(Some(self.id.clone()))
198	}
199}
200
201/// A capture mode a source reports: one frame size and its exact frame rates.
202#[derive(Clone, Debug, PartialEq, Eq)]
203#[non_exhaustive]
204pub struct Mode {
205	/// Frame width in pixels.
206	pub width: u32,
207	/// Frame height in pixels.
208	pub height: u32,
209	/// The exact frame rates offered at this size, highest first.
210	///
211	/// Empty when the driver describes a continuous range instead of listing
212	/// rates, or cannot enumerate intervals for this size.
213	pub framerates: Vec<FrameRate>,
214}
215
216impl Mode {
217	/// The highest rate this mode offers, or `None` when the driver listed none.
218	pub fn max_framerate(&self) -> Option<FrameRate> {
219		self.framerates.first().copied()
220	}
221}
222
223/// A display reported by [`displays`].
224#[derive(Clone, Debug)]
225#[non_exhaustive]
226pub struct Display {
227	/// Opaque identifier: pass to [`Source::Display`].
228	pub id: String,
229	/// Human-readable name, e.g. "Display 1".
230	pub name: String,
231	/// Width in the platform's desktop coordinate space: points on macOS and
232	/// desktop pixels on Windows and X11.
233	pub width: u32,
234	/// Height in the platform's desktop coordinate space: points on macOS and
235	/// desktop pixels on Windows and X11.
236	pub height: u32,
237}
238
239impl Display {
240	/// The [`Source`] that captures this display.
241	pub fn source(&self) -> Source {
242		Source::Display(DisplaySelection::new(self.id.clone()))
243	}
244}
245
246/// A window reported by [`windows`].
247#[derive(Clone, Debug)]
248#[non_exhaustive]
249pub struct Window {
250	/// Opaque identifier: pass to [`Source::Window`].
251	pub id: String,
252	/// The window title, empty if it has none.
253	pub title: String,
254	/// The name of the application owning the window.
255	pub app: String,
256	/// Width in platform window coordinates: points on macOS and pixels on
257	/// Windows and X11.
258	pub width: u32,
259	/// Height in platform window coordinates: points on macOS and pixels on
260	/// Windows and X11.
261	pub height: u32,
262}
263
264impl Window {
265	/// The [`Source`] that captures this window.
266	pub fn source(&self) -> Source {
267		Source::Window(self.id.clone())
268	}
269}
270
271/// An application reported by [`apps`].
272#[derive(Clone, Debug)]
273#[non_exhaustive]
274pub struct App {
275	/// Bundle identifier: pass to [`Source::App`].
276	pub id: String,
277	/// Human-readable name, e.g. "Safari".
278	pub name: String,
279}
280
281impl App {
282	/// The [`Source`] that captures every window of this application.
283	pub fn source(&self) -> Source {
284		Source::App(self.id.clone())
285	}
286}
287
288/// Capture configuration. All fields are hints; the backend picks the closest
289/// supported mode.
290///
291/// `#[non_exhaustive]`: construct via [`Config::default`] and set fields, so
292/// new options can be added without breaking callers.
293#[derive(Clone, Debug)]
294#[non_exhaustive]
295pub struct Config {
296	/// What to capture.
297	pub source: Source,
298	/// Preferred output width in pixels.
299	pub width: Option<u32>,
300	/// Preferred output height in pixels.
301	pub height: Option<u32>,
302	/// Preferred exact frame rate.
303	pub framerate: Option<FrameRate>,
304	/// What happens to the mouse cursor. Screen/window/app sources only;
305	/// ignored by cameras. Defaults to [`Cursor::Drawn`].
306	pub cursor: Cursor,
307	/// Where captured pixels live. Defaults to [`Output::Native`]: whatever the
308	/// platform captures into, a GPU surface or CPU pixels.
309	pub output: Output,
310}
311
312impl Default for Config {
313	fn default() -> Self {
314		Self {
315			source: Source::default(),
316			width: None,
317			height: None,
318			framerate: None,
319			cursor: Cursor::default(),
320			output: Output::Native,
321		}
322	}
323}
324
325/// What a screen, window, or app capture does with the mouse cursor.
326#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
327#[non_exhaustive]
328pub enum Cursor {
329	/// Drawn into each frame where it sits.
330	#[default]
331	Drawn,
332	/// Left out of the frames.
333	Hidden,
334}
335
336impl Cursor {
337	/// Whether the platform should draw the cursor into the frame.
338	pub(crate) fn drawn(self) -> bool {
339		match self {
340			Self::Drawn => true,
341			Self::Hidden => false,
342		}
343	}
344}
345
346/// A live, async frame source opened via [`open`].
347///
348/// Every backend delivers frames through the same latest-frame channel, so the
349/// consumer just `read().await`s regardless of platform. Dropping the stream
350/// releases the device (stops the macOS `AVCaptureSession`, joins the V4L2 /
351/// Media Foundation pump thread). That is the whole point: because `read` is a
352/// real await, cancelling the capture future drops this and the camera turns off
353/// promptly, with no blocking task left pinned to the runtime.
354pub struct Stream {
355	chan: Arc<FrameChannel>,
356	width: u32,
357	height: u32,
358	framerate: Option<FrameRate>,
359	color: Option<crate::Color>,
360	label: String,
361	/// [`Config::output`], applied to each frame as it is read.
362	output: Output,
363	/// First frame captured during [`open`] (some backends learn their geometry
364	/// only from a frame); returned by the first [`read`](Self::read).
365	pending: Option<Frame>,
366	/// Keeps the backend alive and releases it on drop. Type-erased because it
367	/// differs per platform (objc session + delegate, or pump-thread guard).
368	_backend: Keepalive,
369}
370
371impl Stream {
372	/// Build a stream from a backend's channel, geometry, and keep-alive guard.
373	fn new(
374		chan: Arc<FrameChannel>,
375		width: u32,
376		height: u32,
377		framerate: Option<FrameRate>,
378		label: String,
379		pending: Option<Frame>,
380		backend: Keepalive,
381	) -> Self {
382		let color = pending.as_ref().and_then(|frame| frame.surface.color());
383		Self {
384			chan,
385			width,
386			height,
387			framerate,
388			color,
389			label,
390			output: Output::Native,
391			pending,
392			_backend: backend,
393		}
394	}
395
396	/// Await the next frame, or `None` once the source ends.
397	///
398	/// `None` is recoverable: the source stopped for a benign reason (it
399	/// resized, the compositor renegotiated the format, the device went idle)
400	/// and reopening is expected to work. An `Err` is terminal for this
401	/// selection: the source is gone or was refused.
402	///
403	/// Dropping this future cancels only the pending read. Dropping the stream
404	/// releases the capture source.
405	pub async fn read(&mut self) -> Result<Option<Frame>, Error> {
406		let frame = match self.pending.take() {
407			Some(frame) => frame,
408			None => match self.chan.recv().await? {
409				Some(frame) => frame,
410				None => return Ok(None),
411			},
412		};
413		let surface = self.output.convert(frame.surface)?;
414		Ok(Some(Frame::new(frame.timestamp, surface)))
415	}
416
417	/// How many captured frames no [`read`](Self::read) returned, because a newer one replaced
418	/// them while the reader was busy.
419	pub(crate) fn skipped(&self) -> u64 {
420		self.chan.skipped()
421	}
422
423	/// Width of the captured frames in pixels.
424	pub fn width(&self) -> u32 {
425		self.width
426	}
427
428	/// Height of the captured frames in pixels.
429	pub fn height(&self) -> u32 {
430		self.height
431	}
432
433	/// The negotiated frame rate, or `None` if the source doesn't report one.
434	pub fn framerate(&self) -> Option<FrameRate> {
435		self.framerate
436	}
437
438	/// The first frame's declared color space, when its capture backend knows it.
439	pub fn color(&self) -> Option<crate::Color> {
440		self.color
441	}
442
443	/// Human-readable label for the selected capture source.
444	pub fn label(&self) -> &str {
445		&self.label
446	}
447
448	/// Current time in this stream's private capture timeline.
449	pub(crate) fn now(&self) -> moq_net::Timestamp {
450		self.chan.now()
451	}
452}
453
454/// A test-driven capture device: fixtures push frames at explicit acquisition
455/// instants or device timestamps, standing in for a camera behind a [`Stream`].
456#[cfg(all(test, feature = "openh264"))]
457pub(crate) struct Synthetic {
458	chan: Arc<FrameChannel>,
459}
460
461#[cfg(all(test, feature = "openh264"))]
462impl Synthetic {
463	/// Open a synthetic device with the given geometry, returning it and the stream reading it.
464	pub(crate) fn open(size: crate::Size, framerate: FrameRate) -> (Self, Stream) {
465		let chan = FrameChannel::new();
466		let stream = Stream::new(
467			chan.clone(),
468			size.width,
469			size.height,
470			Some(framerate),
471			"synthetic".to_string(),
472			None,
473			Box::new(()),
474		);
475		(Self { chan }, stream)
476	}
477
478	/// Deliver a frame acquired at `captured`.
479	pub(crate) fn push_at(&self, surface: crate::frame::Surface, captured: kio::clock::Instant) {
480		self.chan.push_at(surface, captured);
481	}
482
483	/// Deliver a frame stamped on the device's own timeline, like V4L2 and Media Foundation.
484	pub(crate) fn push_native(&self, surface: crate::frame::Surface, source: moq_net::Timestamp) {
485		self.chan.push_native(surface, source);
486	}
487
488	/// Whether the stream read the last frame delivered.
489	pub(crate) fn taken(&self) -> bool {
490		self.chan.taken()
491	}
492
493	/// End the stream, as a device that stops delivering does.
494	pub(crate) fn close(&self) {
495		self.chan.close();
496	}
497
498	/// Whether the stream reading this device was dropped, as a closed camera is.
499	pub(crate) fn released(&self) -> bool {
500		Arc::strong_count(&self.chan) == 1
501	}
502}
503
504/// Open the capture source described by `config`.
505pub async fn open(config: &Config) -> Result<Stream, Error> {
506	let mut stream = open_source(config).await?;
507	stream.output = config.output;
508	Ok(stream)
509}
510
511async fn open_source(config: &Config) -> Result<Stream, Error> {
512	match &config.source {
513		Source::Camera(device) => {
514			let _ = device;
515			#[cfg(target_os = "macos")]
516			{
517				avfoundation::open(config, device.as_deref()).await
518			}
519			#[cfg(target_os = "linux")]
520			{
521				match LinuxCamera::select(device.as_deref(), sandboxed()) {
522					LinuxCamera::V4l2(device) => v4l2::open(config, device).await,
523					LinuxCamera::Default => {
524						#[cfg(feature = "pipewire")]
525						if pipewire::camera::present().await {
526							return pipewire::camera::open(config, None).await;
527						}
528						v4l2::open(config, None).await
529					}
530					#[cfg(feature = "pipewire")]
531					LinuxCamera::PipeWire(node) => pipewire::camera::open(config, node).await,
532					#[cfg(not(feature = "pipewire"))]
533					LinuxCamera::PipeWire(_) => Err(Error::Unsupported(
534						"PipeWire camera capture without the `pipewire` feature".to_string(),
535					)),
536				}
537			}
538			#[cfg(target_os = "windows")]
539			{
540				mediafoundation::open(config, device.as_deref()).await
541			}
542			#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
543			{
544				Err(Error::Unsupported("camera capture".to_string()))
545			}
546		}
547		Source::Display(selection) => {
548			let _ = selection;
549			#[cfg(target_os = "macos")]
550			{
551				screencapture::open_display(config, selection.id.as_deref()).await
552			}
553			#[cfg(target_os = "windows")]
554			{
555				wgc::open(config).await
556			}
557			#[cfg(target_os = "linux")]
558			{
559				x11::open_display(config, selection.id.as_deref()).await
560			}
561			#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
562			{
563				Err(Error::Unsupported("screen capture".to_string()))
564			}
565		}
566		Source::Window(id) => {
567			let _ = id;
568			#[cfg(target_os = "macos")]
569			{
570				screencapture::open_window(config, id).await
571			}
572			#[cfg(target_os = "linux")]
573			{
574				x11::open_window(config, id).await
575			}
576			#[cfg(target_os = "windows")]
577			{
578				wgc::open(config).await
579			}
580			#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
581			{
582				Err(Error::Unsupported("window capture".to_string()))
583			}
584		}
585		#[cfg(all(target_os = "linux", feature = "pipewire"))]
586		Source::Portal(selection) => pipewire::open(config, selection).await,
587		Source::App(id) => {
588			let _ = id;
589			#[cfg(target_os = "macos")]
590			{
591				screencapture::open_app(config, id).await
592			}
593			#[cfg(not(target_os = "macos"))]
594			{
595				Err(Error::Unsupported("application capture".to_string()))
596			}
597		}
598	}
599}
600
601/// List the available cameras and the identifiers [`Source::Camera`] accepts.
602///
603/// On Linux, V4L2 lists only devices offering YUYV or MJPEG. With the `pipewire`
604/// feature, PipeWire camera nodes come first, and a V4L2 device that a listed
605/// node fronts is listed only as that node, since PipeWire shares the device
606/// with other clients while a V4L2 open holds it exclusively. V4L2 devices no
607/// node fronts remain visible. A session without PipeWire, or one whose daemon
608/// does not answer, lists V4L2 alone. Inside a sandbox the PipeWire nodes come
609/// through the camera portal, which may ask the user for camera access.
610pub async fn cameras() -> Result<Vec<Camera>, Error> {
611	#[cfg(target_os = "macos")]
612	{
613		avfoundation::cameras()
614	}
615	#[cfg(target_os = "linux")]
616	{
617		let cameras = blocking(v4l2::cameras).await?;
618		#[cfg(feature = "pipewire")]
619		let cameras = pipewire::camera::cameras(cameras).await?;
620		Ok(cameras)
621	}
622	#[cfg(target_os = "windows")]
623	{
624		blocking(mediafoundation::cameras).await
625	}
626	#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
627	{
628		Err(Error::Unsupported("listing cameras".to_string()))
629	}
630}
631
632/// List the modes a camera reports, largest size first.
633///
634/// `camera` selects the device exactly as [`Source::Camera`] does. Only the
635/// formats this crate can convert are enumerated, so the modes that come back
636/// are ones [`open`] could negotiate rather than everything the driver
637/// advertises.
638///
639/// Linux only (V4L2, and PipeWire cameras with the `pipewire` feature); other
640/// platforms return [`Error::Unsupported`].
641/// Rates are exact device reports and [`Config::framerate`] accepts the same type.
642/// Both Linux backends prefer the closest geometry, then the accepted rate
643/// nearest that request, then the cheaper conversion format.
644///
645/// An empty list is not a failure: it means the driver enumerated nothing this
646/// crate can convert.
647pub async fn camera_modes(camera: Option<&str>) -> Result<Vec<Mode>, Error> {
648	let _ = camera;
649	#[cfg(target_os = "linux")]
650	{
651		match LinuxCamera::select(camera, sandboxed()) {
652			LinuxCamera::V4l2(camera) => {
653				let camera = camera.map(str::to_string);
654				blocking(move || v4l2::modes(camera.as_deref())).await
655			}
656			LinuxCamera::Default => {
657				#[cfg(feature = "pipewire")]
658				if pipewire::camera::present().await {
659					return pipewire::camera::modes(None).await;
660				}
661				blocking(|| v4l2::modes(None)).await
662			}
663			#[cfg(feature = "pipewire")]
664			LinuxCamera::PipeWire(node) => pipewire::camera::modes(node).await,
665			#[cfg(not(feature = "pipewire"))]
666			LinuxCamera::PipeWire(_) => Err(Error::Unsupported(
667				"PipeWire camera modes without the `pipewire` feature".to_string(),
668			)),
669		}
670	}
671	#[cfg(not(target_os = "linux"))]
672	{
673		Err(Error::Unsupported("listing camera modes".to_string()))
674	}
675}
676
677/// List the available displays and the identifiers [`Source::Display`] accepts.
678///
679/// On Wayland the xdg-desktop-portal picker owns display selection, so there is
680/// no portal list or stable identifier to expose. When XWayland is available,
681/// its native displays are listed with stable X11 ids.
682pub async fn displays() -> Result<Vec<Display>, Error> {
683	#[cfg(target_os = "macos")]
684	{
685		screencapture::displays().await
686	}
687	#[cfg(target_os = "windows")]
688	{
689		blocking(wgc::displays).await
690	}
691	#[cfg(target_os = "linux")]
692	{
693		blocking(x11::displays).await
694	}
695	#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
696	{
697		Err(Error::Unsupported("listing displays".to_string()))
698	}
699}
700
701/// List the on-screen windows.
702pub async fn windows() -> Result<Vec<Window>, Error> {
703	#[cfg(target_os = "macos")]
704	{
705		screencapture::windows().await
706	}
707	#[cfg(target_os = "linux")]
708	{
709		blocking(x11::windows).await
710	}
711	#[cfg(target_os = "windows")]
712	{
713		blocking(wgc::windows).await
714	}
715	#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
716	{
717		Err(Error::Unsupported("listing windows".to_string()))
718	}
719}
720
721/// List the applications with at least one on-screen window. macOS only.
722pub async fn apps() -> Result<Vec<App>, Error> {
723	#[cfg(target_os = "macos")]
724	{
725		screencapture::apps().await
726	}
727	#[cfg(not(target_os = "macos"))]
728	{
729		Err(Error::Unsupported("listing applications".to_string()))
730	}
731}
732
733/// The id prefix of a PipeWire camera, and on its own the default one.
734#[cfg(any(target_os = "linux", test))]
735const PIPEWIRE: &str = "pipewire";
736
737/// The Linux backend a [`Source::Camera`] selector names.
738#[cfg(any(target_os = "linux", test))]
739#[derive(Debug, PartialEq, Eq)]
740enum LinuxCamera<'a> {
741	/// No camera named, outside a sandbox: PipeWire's default camera when the
742	/// `pipewire` feature is on and PipeWire lists a camera, else `/dev/video0`.
743	Default,
744	/// A V4L2 device, by path or index. `None` opens `/dev/video0`.
745	V4l2(Option<&'a str>),
746	/// A PipeWire camera, by `node.name`. `None` picks the listed camera with
747	/// the highest session priority, the one the session manager links by
748	/// default.
749	PipeWire(Option<&'a str>),
750}
751
752#[cfg(any(target_os = "linux", test))]
753impl<'a> LinuxCamera<'a> {
754	/// Parse a camera selector. A sandbox has no V4L2 devices to open by
755	/// default, so its default camera is PipeWire's, reached through the portal.
756	fn select(selector: Option<&'a str>, sandboxed: bool) -> Self {
757		match selector {
758			None if sandboxed => Self::PipeWire(None),
759			None => Self::Default,
760			Some(PIPEWIRE) => Self::PipeWire(None),
761			Some(selector) => match selector.strip_prefix(PIPEWIRE).and_then(|rest| rest.strip_prefix(':')) {
762				Some(name) => Self::PipeWire(Some(name)),
763				None => Self::V4l2(Some(selector)),
764			},
765		}
766	}
767}
768
769/// Whether this process runs in a Flatpak or Snap sandbox. Without the
770/// `pipewire` feature there is no portal to use, so it never matters.
771#[cfg(target_os = "linux")]
772fn sandboxed() -> bool {
773	#[cfg(feature = "pipewire")]
774	{
775		ashpd::is_sandboxed()
776	}
777	#[cfg(not(feature = "pipewire"))]
778	{
779		false
780	}
781}
782
783/// Run synchronous platform enumeration off the async runtime's worker threads.
784#[cfg(any(target_os = "linux", target_os = "windows"))]
785async fn blocking<T, F>(f: F) -> Result<T, Error>
786where
787	F: FnOnce() -> Result<T, Error> + Send + 'static,
788	T: Send + 'static,
789{
790	tokio::task::spawn_blocking(f)
791		.await
792		.map_err(|err| Error::codec(anyhow::anyhow!("capture enumeration thread failed: {err}")))?
793}
794
795#[cfg(test)]
796mod tests {
797	use super::*;
798
799	#[test]
800	fn source_labels_add_the_source_kind() {
801		assert_eq!(Source::Camera(None).label(), "camera");
802		assert_eq!(Source::Camera(Some("camera-id".into())).label(), "camera:camera-id");
803		assert_eq!(Source::Display(DisplaySelection::default()).label(), "display");
804		assert_eq!(Source::Display(DisplaySelection::new("0")).label(), "display:0");
805		assert_eq!(Source::Window("123".into()).label(), "window:123");
806		assert_eq!(Source::App("com.example.app".into()).label(), "app:com.example.app");
807	}
808
809	#[test]
810	fn source_labels_preserve_prefixed_display_ids() {
811		assert_eq!(Source::Display(DisplaySelection::new("display:0")).label(), "display:0");
812	}
813
814	#[test]
815	fn source_labels_preserve_prefixed_window_ids() {
816		assert_eq!(Source::Window("window:123".into()).label(), "window:123");
817	}
818
819	#[test]
820	fn camera_selectors_name_their_backend() {
821		assert_eq!(LinuxCamera::select(None, false), LinuxCamera::Default);
822		assert_eq!(LinuxCamera::select(None, true), LinuxCamera::PipeWire(None));
823		for sandboxed in [false, true] {
824			assert_eq!(
825				LinuxCamera::select(Some("/dev/video2"), sandboxed),
826				LinuxCamera::V4l2(Some("/dev/video2"))
827			);
828			assert_eq!(LinuxCamera::select(Some("1"), sandboxed), LinuxCamera::V4l2(Some("1")));
829			assert_eq!(
830				LinuxCamera::select(Some("pipewire"), sandboxed),
831				LinuxCamera::PipeWire(None)
832			);
833			assert_eq!(
834				LinuxCamera::select(Some("pipewire:v4l2_input.pci-0000_00_14.0-usb-0_4_1.0"), sandboxed),
835				LinuxCamera::PipeWire(Some("v4l2_input.pci-0000_00_14.0-usb-0_4_1.0"))
836			);
837		}
838		// Only the whole prefix selects PipeWire; anything else is a device path.
839		assert_eq!(
840			LinuxCamera::select(Some("pipewired"), false),
841			LinuxCamera::V4l2(Some("pipewired"))
842		);
843	}
844}