1use std::sync::Arc;
15
16use crate::{Error, Frame, FrameRate, Output};
17
18mod channel;
19use channel::FrameChannel;
20
21#[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#[cfg(target_os = "linux")]
42mod v4l2;
43#[cfg(target_os = "linux")]
45mod mode;
46#[cfg(target_os = "linux")]
48mod x11;
49
50#[cfg(all(target_os = "linux", feature = "pipewire"))]
52mod pipewire;
53
54#[cfg(any(all(target_os = "linux", feature = "pipewire"), test))]
56pub mod portal;
57
58#[cfg(target_os = "windows")]
60mod mediafoundation;
61
62#[cfg(any(target_os = "windows", test))]
64mod wgc;
65
66#[cfg(any(target_os = "linux", target_os = "windows"))]
68mod pump;
69
70#[cfg(any(target_os = "linux", target_os = "windows", test))]
74mod settle;
75
76#[derive(Clone, Debug, PartialEq, Eq)]
81#[non_exhaustive]
82pub enum Source {
83 Camera(Option<String>),
107
108 Display(DisplaySelection),
115
116 Window(String),
119
120 App(String),
123
124 #[cfg(all(target_os = "linux", feature = "pipewire"))]
130 Portal(portal::Selection),
131}
132
133impl Default for Source {
135 fn default() -> Self {
136 Self::Camera(None)
137 }
138}
139
140impl Source {
141 #[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#[derive(Clone, Debug, Default, PartialEq, Eq)]
171#[non_exhaustive]
172pub struct DisplaySelection {
173 pub id: Option<String>,
175}
176
177impl DisplaySelection {
178 pub fn new(id: impl Into<String>) -> Self {
180 Self { id: Some(id.into()) }
181 }
182}
183
184#[derive(Clone, Debug)]
186#[non_exhaustive]
187pub struct Camera {
188 pub id: String,
190 pub name: String,
192}
193
194impl Camera {
195 pub fn source(&self) -> Source {
197 Source::Camera(Some(self.id.clone()))
198 }
199}
200
201#[derive(Clone, Debug, PartialEq, Eq)]
203#[non_exhaustive]
204pub struct Mode {
205 pub width: u32,
207 pub height: u32,
209 pub framerates: Vec<FrameRate>,
214}
215
216impl Mode {
217 pub fn max_framerate(&self) -> Option<FrameRate> {
219 self.framerates.first().copied()
220 }
221}
222
223#[derive(Clone, Debug)]
225#[non_exhaustive]
226pub struct Display {
227 pub id: String,
229 pub name: String,
231 pub width: u32,
234 pub height: u32,
237}
238
239impl Display {
240 pub fn source(&self) -> Source {
242 Source::Display(DisplaySelection::new(self.id.clone()))
243 }
244}
245
246#[derive(Clone, Debug)]
248#[non_exhaustive]
249pub struct Window {
250 pub id: String,
252 pub title: String,
254 pub app: String,
256 pub width: u32,
259 pub height: u32,
262}
263
264impl Window {
265 pub fn source(&self) -> Source {
267 Source::Window(self.id.clone())
268 }
269}
270
271#[derive(Clone, Debug)]
273#[non_exhaustive]
274pub struct App {
275 pub id: String,
277 pub name: String,
279}
280
281impl App {
282 pub fn source(&self) -> Source {
284 Source::App(self.id.clone())
285 }
286}
287
288#[derive(Clone, Debug)]
294#[non_exhaustive]
295pub struct Config {
296 pub source: Source,
298 pub width: Option<u32>,
300 pub height: Option<u32>,
302 pub framerate: Option<FrameRate>,
304 pub cursor: Cursor,
307 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
327#[non_exhaustive]
328pub enum Cursor {
329 #[default]
331 Drawn,
332 Hidden,
334}
335
336impl Cursor {
337 pub(crate) fn drawn(self) -> bool {
339 match self {
340 Self::Drawn => true,
341 Self::Hidden => false,
342 }
343 }
344}
345
346pub 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 output: Output,
363 pending: Option<Frame>,
366 _backend: Keepalive,
369}
370
371impl Stream {
372 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 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 pub(crate) fn skipped(&self) -> u64 {
420 self.chan.skipped()
421 }
422
423 pub fn width(&self) -> u32 {
425 self.width
426 }
427
428 pub fn height(&self) -> u32 {
430 self.height
431 }
432
433 pub fn framerate(&self) -> Option<FrameRate> {
435 self.framerate
436 }
437
438 pub fn color(&self) -> Option<crate::Color> {
440 self.color
441 }
442
443 pub fn label(&self) -> &str {
445 &self.label
446 }
447
448 pub(crate) fn now(&self) -> moq_net::Timestamp {
450 self.chan.now()
451 }
452}
453
454#[cfg(all(test, feature = "openh264"))]
457pub(crate) struct Synthetic {
458 chan: Arc<FrameChannel>,
459}
460
461#[cfg(all(test, feature = "openh264"))]
462impl Synthetic {
463 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 pub(crate) fn push_at(&self, surface: crate::frame::Surface, captured: kio::clock::Instant) {
480 self.chan.push_at(surface, captured);
481 }
482
483 pub(crate) fn push_native(&self, surface: crate::frame::Surface, source: moq_net::Timestamp) {
485 self.chan.push_native(surface, source);
486 }
487
488 pub(crate) fn taken(&self) -> bool {
490 self.chan.taken()
491 }
492
493 pub(crate) fn close(&self) {
495 self.chan.close();
496 }
497
498 pub(crate) fn released(&self) -> bool {
500 Arc::strong_count(&self.chan) == 1
501 }
502}
503
504pub 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
601pub 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
632pub 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
677pub 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
701pub 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
721pub 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#[cfg(any(target_os = "linux", test))]
735const PIPEWIRE: &str = "pipewire";
736
737#[cfg(any(target_os = "linux", test))]
739#[derive(Debug, PartialEq, Eq)]
740enum LinuxCamera<'a> {
741 Default,
744 V4l2(Option<&'a str>),
746 PipeWire(Option<&'a str>),
750}
751
752#[cfg(any(target_os = "linux", test))]
753impl<'a> LinuxCamera<'a> {
754 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#[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#[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 assert_eq!(
840 LinuxCamera::select(Some("pipewired"), false),
841 LinuxCamera::V4l2(Some("pipewired"))
842 );
843 }
844}