Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

9.2 KB
Raw Blame
use std::{
    fmt::{Debug, Display},
    ops::Deref,
    time::Duration,
};

#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "macos")]
use macos::*;

#[cfg(windows)]
mod windows;
#[cfg(windows)]
use windows::*;

#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "linux")]
pub use linux::*;

#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "specta", derive(specta::Type))]
pub struct CameraInfo {
    device_id: String,
    model_id: Option<ModelID>,
    display_name: String,
}

impl CameraInfo {
    pub fn device_id(&self) -> &str {
        &self.device_id
    }

    pub fn model_id(&self) -> Option<&ModelID> {
        self.model_id.as_ref()
    }

    pub fn display_name(&self) -> &str {
        &self.display_name
    }
}

pub fn list_cameras() -> impl Iterator<Item = CameraInfo> {
    list_cameras_impl()
}

#[cfg(windows)]
pub type NativeFormat = cap_camera_windows::VideoFormatInner;

#[derive(Debug, Clone)]
pub struct FormatInfo {
    width: u32,
    height: u32,
    frame_rate: f32,
}

impl FormatInfo {
    pub fn width(&self) -> u32 {
        self.width
    }

    pub fn height(&self) -> u32 {
        self.height
    }

    pub fn frame_rate(&self) -> f32 {
        (self.frame_rate * 100.0).round() / 100.0
    }
}

#[derive(Clone)]
pub struct Format {
    native: NativeFormat,
    info: FormatInfo,
    /// Captured when the format is enumerated: the native handle does not
    /// expose it uniformly across platforms (DirectShow formats lose it once
    /// the owning `VideoFormat` is dropped).
    pixel_format: Option<String>,
}

impl Format {
    pub fn native(&self) -> &NativeFormat {
        &self.native
    }

    /// The device's native pixel format for this capture format: a fourcc on
    /// macOS and Linux, the MediaFoundation/DirectShow subtype name on
    /// Windows. `None` where the platform does not report one.
    pub fn pixel_format_name(&self) -> Option<String> {
        self.pixel_format.clone()
    }
}

impl Deref for Format {
    type Target = FormatInfo;

    fn deref(&self) -> &Self::Target {
        &self.info
    }
}

impl Debug for Format {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Format")
            .field("info", &self.info)
            .field("native", {
                #[cfg(target_os = "macos")]
                {
                    &"AVFoundation"
                }
                #[cfg(windows)]
                {
                    use cap_camera_windows::VideoFormatInner;

                    match &self.native {
                        VideoFormatInner::DirectShow(_) => &"DirectShow",
                        VideoFormatInner::MediaFoundation(_) => &"MediaFoundation",
                    }
                }
                #[cfg(target_os = "linux")]
                {
                    &"Linux"
                }
            })
            .finish()
    }
}

/// A unique identifier for a camera device.
/// This is modelled after Chromium's  VideoCaptureDeviceDescriptor::model_id,
/// being a combination of the vendor ID and product ID.
#[derive(Debug, Clone, PartialEq)]
pub struct ModelID {
    vid: String,
    pid: String,
}

#[cfg_attr(feature = "specta", derive(specta::Type))]
#[cfg_attr(feature = "specta", specta(remote = ModelID))]
#[allow(dead_code)] // It's never constructed but it's a remote impl
struct ModelIDType(String);

#[cfg(feature = "serde")]
impl serde::Serialize for ModelID {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.collect_str(&format_args!("{}:{}", &self.vid, &self.pid))
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for ModelID {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Self::try_from(String::deserialize(deserializer)?)
            .map_err(|()| serde::de::Error::custom("camera model ID must contain a colon"))
    }
}

impl TryFrom<String> for ModelID {
    type Error = ();

    fn try_from(value: String) -> Result<Self, Self::Error> {
        let (vid, pid) = value.split_once(":").ok_or(())?;
        Ok(ModelID {
            vid: vid.to_string(),
            pid: pid.to_string(),
        })
    }
}

impl Display for ModelID {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", &self.vid, &self.pid)
    }
}

// Capture

#[derive(thiserror::Error, Debug)]
pub enum StartCapturingError {
    #[cfg(windows)]
    #[error("GetDevicesFailed/{0}")]
    GetDevicesFailed(#[from] cap_camera_windows::GetDevicesError),
    #[error("Device not found")]
    DeviceNotFound,
    #[cfg(windows)]
    #[error("{0}")]
    Inner(#[from] cap_camera_windows::StartCapturingError),
    #[cfg(target_os = "macos")]
    #[error("{0}")]
    Native(#[from] AVFoundationError),
    #[cfg(windows)]
    #[error("{0}")]
    Native(windows_core::Error),
    #[cfg(target_os = "linux")]
    #[error("{0}")]
    Native(String),
}

/// How the capture session negotiates pixel format and device format.
/// Only affects macOS; other platforms ignore it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CaptureMode {
    /// Pin the device's active format and request its native pixel format from
    /// the output, avoiding conversion overhead.
    #[default]
    Native,
    /// Leave format and pixel-format negotiation entirely to the OS capture
    /// stack, like a stock AVFoundation app. Costs a conversion but works with
    /// devices that stall when the native format is forced.
    Compatibility,
}

#[cfg(not(target_os = "linux"))]
#[derive(Debug)]
pub struct CapturedFrame {
    native: NativeCapturedFrame,
    // pub reference_time: Instant,
    pub timestamp: Duration,
    // pub capture_begin_time: Option<Instant>,
}

#[cfg(target_os = "linux")]
#[derive(Debug)]
pub struct CapturedFrame<'a> {
    native: NativeCapturedFrame<'a>,
    // pub reference_time: Instant,
    pub timestamp: Duration,
    // pub capture_begin_time: Option<Instant>,
}

#[cfg(not(target_os = "linux"))]
impl CapturedFrame {
    pub fn native(&self) -> &NativeCapturedFrame {
        &self.native
    }
}

#[cfg(target_os = "linux")]
impl<'a> CapturedFrame<'a> {
    pub fn native(&self) -> &NativeCapturedFrame<'a> {
        &self.native
    }
}

impl CameraInfo {
    pub fn formats(&self) -> Option<Vec<Format>> {
        self.formats_impl()
    }

    #[cfg(not(target_os = "linux"))]
    pub fn start_capturing(
        &self,
        format: Format,
        callback: impl FnMut(CapturedFrame) + Send + 'static,
    ) -> Result<CaptureHandle, StartCapturingError> {
        self.start_capturing_with_mode(format, CaptureMode::default(), callback)
    }

    #[cfg(target_os = "linux")]
    pub fn start_capturing(
        &self,
        format: Format,
        callback: impl for<'a> FnMut(CapturedFrame<'a>) + Send + 'static,
    ) -> Result<CaptureHandle, StartCapturingError> {
        self.start_capturing_with_mode(format, CaptureMode::default(), callback)
    }

    #[cfg(not(target_os = "linux"))]
    #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
    pub fn start_capturing_with_mode(
        &self,
        format: Format,
        mode: CaptureMode,
        callback: impl FnMut(CapturedFrame) + Send + 'static,
    ) -> Result<CaptureHandle, StartCapturingError> {
        Ok(CaptureHandle {
            #[cfg(target_os = "macos")]
            native: Some(start_capturing_impl(
                self,
                format,
                mode,
                Box::new(callback),
            )?),
            #[cfg(windows)]
            native: Some(start_capturing_impl(self, format, Box::new(callback))?),
        })
    }

    #[cfg(target_os = "linux")]
    pub fn start_capturing_with_mode(
        &self,
        format: Format,
        _mode: CaptureMode,
        callback: impl for<'a> FnMut(CapturedFrame<'a>) + Send + 'static,
    ) -> Result<CaptureHandle, StartCapturingError> {
        Ok(CaptureHandle {
            native: Some(start_capturing_impl(self, format, Box::new(callback))?),
        })
    }
}

#[must_use = "must be held for the duration of the recording"]
pub struct CaptureHandle {
    native: Option<NativeCaptureHandle>,
}

impl CaptureHandle {
    pub fn stop_capturing(mut self) -> Result<(), String> {
        if let Some(feed) = self.native.take() {
            feed.stop_capturing()?;
        }
        Ok(())
    }
}

impl Drop for CaptureHandle {
    fn drop(&mut self) {
        if let Some(feed) = self.native.take() {
            feed.stop_capturing().ok();
        }
    }
}

#[cfg(all(test, feature = "serde"))]
mod model_id_tests {
    use super::ModelID;
    use serde::{Deserialize, de::value::StrDeserializer};

    #[test]
    fn reads_saved_model_id() {
        let input = StrDeserializer::<serde::de::value::Error>::new("046d:08e5");
        assert_eq!(
            ModelID::deserialize(input).unwrap().to_string(),
            "046d:08e5"
        );
    }

    #[test]
    fn malformed_model_id_returns_an_error() {
        for value in ["", "missing-separator"] {
            let input = StrDeserializer::<serde::de::value::Error>::new(value);
            assert!(ModelID::deserialize(input).is_err());
        }
    }
}