Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

38.1 KB
Raw Blame
//! Real device enumeration for the capture-target and device pickers.
//!
//! Everything here goes through the same crates the recorder uses
//! (`cap-camera`, `scap-targets`, and the Cap `cpal` fork) so the identities the
//! UI hands back — camera `device_id`, microphone name, `DisplayId`, `WindowId`
//! — are byte-identical to what `cap-recording` expects to be given. Nothing is
//! re-derived or prettified into a new identity space.

use cpal::traits::{DeviceTrait, HostTrait};
use scap_targets::{Display, DisplayId, Window, WindowId};

/// A camera, identified the way `cap-recording` identifies one.
#[derive(Debug, Clone, PartialEq)]
pub struct CameraOption {
    pub device_id: String,
    pub model_id: Option<cap_camera::ModelID>,
    pub label: String,
    /// Highest-resolution format the device advertises, shown as the row's
    /// subtitle. `None` when the device reports no formats.
    pub best_format: Option<CameraFormat>,
    pub formats: Vec<CameraFormat>,
}

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

impl CameraFormat {
    pub fn settings(self) -> cap_recording::feeds::camera::CameraDeviceSettings {
        cap_recording::feeds::camera::CameraDeviceSettings {
            width: Some(self.width),
            height: Some(self.height),
            frame_rate: Some(self.frame_rate),
        }
    }

    /// Matches the web UI: `1920×1080 @ 30fps`.
    pub fn describe(&self) -> String {
        format!(
            "{}×{} @ {}fps",
            self.width,
            self.height,
            self.frame_rate.round() as u32
        )
    }
}

/// A microphone. cpal has no stable id, so the name *is* the identity — which is
/// also exactly what `MicrophoneFeed::list()` keys its map on.
#[derive(Debug, Clone, PartialEq)]
pub struct MicrophoneOption {
    pub name: String,
    pub sample_rate: Option<u32>,
    pub channels: Option<u16>,
}

impl MicrophoneOption {
    /// Matches the web UI: `48kHz Stereo`.
    pub fn describe(&self) -> Option<String> {
        let sample_rate = self.sample_rate?;
        let khz = sample_rate as f32 / 1000.;
        let layout = match self.channels {
            Some(1) => "Mono".to_string(),
            Some(2) => "Stereo".to_string(),
            Some(n) => format!("{n}ch"),
            None => return Some(format!("{khz}kHz")),
        };
        Some(format!("{khz}kHz {layout}"))
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct DisplayOption {
    pub id: DisplayId,
    pub label: String,
    pub refresh_rate: f64,
}

impl DisplayOption {
    /// `formatRefreshRate`: `60 Hz`, or nothing when the display does not
    /// report one.
    pub fn describe_refresh_rate(&self) -> Option<String> {
        (self.refresh_rate > 0.).then(|| format!("{} Hz", self.refresh_rate.round() as u32))
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct WindowOption {
    pub id: WindowId,
    /// The window's own title.
    pub label: String,
    /// Owning application, shown as the secondary line.
    pub app: String,
    pub size: Option<(u32, u32)>,
    /// Display-relative logical origin. Nothing renders it -- it is here
    /// because `createWindowSignature` (`new-main/index.tsx:376-398`) joins
    /// `position.x`/`position.y` into the signature the thumbnail refresh
    /// compares, so a window that is dragged without being resized has to
    /// invalidate its thumbnail. See `target_thumbnails::window_signature`.
    pub position: Option<(f64, f64)>,
    pub refresh_rate: Option<f64>,
}

impl WindowOption {
    /// The card's third line. The Tauri card joins resolution and refresh rate
    /// with `@` when it has both and falls back to whichever it has:
    /// `1920×1080 @ 60 Hz`. Note the multiplication sign, not a letter x.
    pub fn describe_metadata(&self) -> Option<String> {
        let resolution = self
            .size
            .filter(|(width, height)| *width > 0 && *height > 0)
            .map(|(width, height)| format!("{width}×{height}"));
        let refresh = self
            .refresh_rate
            .filter(|rate| *rate > 0.)
            .map(|rate| format!("{} Hz", rate.round() as u32));

        match (resolution, refresh) {
            (Some(resolution), Some(refresh)) => Some(format!("{resolution} @ {refresh}")),
            (Some(only), None) | (None, Some(only)) => Some(only),
            (None, None) => None,
        }
    }

    /// Whether two entries draw the same card. `position` only feeds the
    /// thumbnail signature, so a window that moved still draws the same card.
    pub fn same_card(&self, other: &Self) -> bool {
        let Self {
            id,
            label,
            app,
            size,
            position: _,
            refresh_rate,
        } = self;
        *id == other.id
            && *label == other.label
            && *app == other.app
            && *size == other.size
            && *refresh_rate == other.refresh_rate
    }
}

#[derive(Debug, Clone, Default, PartialEq)]
pub struct DeviceSnapshot {
    pub cameras: Vec<CameraOption>,
    pub microphones: Vec<MicrophoneOption>,
    pub displays: Vec<DisplayOption>,
    pub windows: Vec<WindowOption>,
}

impl DeviceSnapshot {
    /// Store a fresh display list. Returns whether any card changed.
    pub fn install_displays(&mut self, displays: Vec<DisplayOption>) -> bool {
        if self.displays == displays {
            return false;
        }
        self.displays = displays;
        true
    }

    /// Store a fresh window list. Returns whether any card changed. The list is
    /// stored either way so the thumbnail signature sees moved windows.
    pub fn install_windows(&mut self, windows: Vec<WindowOption>) -> bool {
        let changed = self.windows.len() != windows.len()
            || self
                .windows
                .iter()
                .zip(&windows)
                .any(|(current, next)| !current.same_card(next));
        self.windows = windows;
        changed
    }

    pub fn update_camera_formats(
        &mut self,
        queried: &CameraOption,
        formats: Vec<CameraFormat>,
    ) -> bool {
        let Some(camera) = self
            .cameras
            .iter_mut()
            .find(|camera| camera.same_device(queried))
        else {
            return false;
        };
        camera.best_format = formats.first().copied();
        camera.formats = formats;
        true
    }

    /// Enumerate everything. This blocks — AVFoundation camera discovery and the
    /// window-server queries are both slow enough to drop frames — so callers
    /// should run it on the background executor, never inside `render`.
    pub fn enumerate() -> Self {
        Self {
            cameras: list_cameras(),
            microphones: list_microphone_names(),
            displays: list_displays(),
            windows: list_windows(),
        }
    }
}

#[derive(Clone, Default)]
pub struct InputEnumerationGate(std::sync::Arc<std::sync::atomic::AtomicBool>);

pub struct InputEnumerationPermit(std::sync::Arc<std::sync::atomic::AtomicBool>);

impl InputEnumerationGate {
    pub fn try_enter(&self) -> Option<InputEnumerationPermit> {
        self.0
            .compare_exchange(
                false,
                true,
                std::sync::atomic::Ordering::AcqRel,
                std::sync::atomic::Ordering::Acquire,
            )
            .ok()
            .map(|_| InputEnumerationPermit(self.0.clone()))
    }
}

impl Drop for InputEnumerationPermit {
    fn drop(&mut self) {
        self.0.store(false, std::sync::atomic::Ordering::Release);
    }
}

pub enum InputSnapshot {
    Cameras(Vec<CameraOption>),
    Microphones(Vec<MicrophoneOption>),
}

impl InputSnapshot {
    pub fn cameras(previous: &[CameraOption]) -> Self {
        Self::Cameras(list_cameras_with_previous(previous))
    }

    pub fn microphones() -> Self {
        Self::Microphones(list_microphones())
    }

    pub fn install(self, snapshot: &mut DeviceSnapshot) -> bool {
        match self {
            Self::Cameras(mut cameras) => {
                for camera in &mut cameras {
                    if camera.formats.is_empty()
                        && let Some(current) = snapshot.cameras.iter().find(|current| {
                            current.same_device(camera) && !current.formats.is_empty()
                        })
                    {
                        camera.best_format = current.best_format;
                        camera.formats = current.formats.clone();
                    }
                }
                if snapshot.cameras == cameras {
                    return false;
                }
                snapshot.cameras = cameras;
            }
            Self::Microphones(microphones) if snapshot.microphones != microphones => {
                snapshot.microphones = microphones;
            }
            _ => return false,
        }
        true
    }
}

#[cfg(test)]
mod target_list_tests {
    use super::*;
    use std::str::FromStr;

    fn window(id: &str, label: &str) -> WindowOption {
        WindowOption {
            id: WindowId::from_str(id).unwrap(),
            label: label.into(),
            app: "Cap".into(),
            size: Some((1920, 1080)),
            position: Some((0., 0.)),
            refresh_rate: Some(60.),
        }
    }

    fn display(id: &str, label: &str) -> DisplayOption {
        DisplayOption {
            id: DisplayId::from_str(id).unwrap(),
            label: label.into(),
            refresh_rate: 60.,
        }
    }

    #[test]
    fn unchanged_display_list_does_not_repaint() {
        let list = vec![display("1", "Built-in"), display("2", "Studio Display")];
        let mut snapshot = DeviceSnapshot::default();
        assert!(snapshot.install_displays(list.clone()));
        assert!(!snapshot.install_displays(list.clone()));
        assert_eq!(snapshot.displays, list);
    }

    #[test]
    fn display_changes_repaint() {
        let list = vec![display("1", "Built-in"), display("2", "Studio Display")];
        let mut renamed = list.clone();
        renamed[1].label = "Sidecar".into();
        let mut slower = list.clone();
        slower[0].refresh_rate = 30.;
        let reordered = vec![list[1].clone(), list[0].clone()];
        for next in [
            renamed,
            slower,
            reordered,
            vec![list[0].clone()],
            Vec::new(),
        ] {
            let mut snapshot = DeviceSnapshot {
                displays: list.clone(),
                ..Default::default()
            };
            assert!(snapshot.install_displays(next.clone()));
            assert_eq!(snapshot.displays, next);
        }
    }

    #[test]
    fn unchanged_window_list_does_not_repaint() {
        let list = vec![window("1", "Main"), window("2", "Editor")];
        let mut snapshot = DeviceSnapshot::default();
        assert!(snapshot.install_windows(list.clone()));
        assert!(!snapshot.install_windows(list.clone()));
        assert_eq!(snapshot.windows, list);
    }

    #[test]
    fn moved_window_is_stored_without_a_repaint() {
        let list = vec![window("1", "Main"), window("2", "Editor")];
        let mut moved = list.clone();
        moved[1].position = Some((240., 96.));
        let mut snapshot = DeviceSnapshot {
            windows: list,
            ..Default::default()
        };
        assert!(!snapshot.install_windows(moved.clone()));
        assert_eq!(snapshot.windows, moved);
    }

    #[test]
    fn window_card_changes_repaint() {
        let list = vec![window("1", "Main"), window("2", "Editor")];
        let mut renamed = list.clone();
        renamed[0].label = "Untitled".into();
        let mut other_app = list.clone();
        other_app[1].app = "Finder".into();
        let mut resized = list.clone();
        resized[0].size = Some((1280, 720));
        let mut sizeless = list.clone();
        sizeless[0].size = None;
        let mut slower = list.clone();
        slower[1].refresh_rate = Some(30.);
        let reordered = vec![list[1].clone(), list[0].clone()];
        let mut opened = list.clone();
        opened.push(window("3", "Settings"));
        for next in [
            renamed,
            other_app,
            resized,
            sizeless,
            slower,
            reordered,
            opened,
            vec![list[0].clone()],
            Vec::new(),
        ] {
            let mut snapshot = DeviceSnapshot {
                windows: list.clone(),
                ..Default::default()
            };
            assert!(snapshot.install_windows(next.clone()));
            assert_eq!(snapshot.windows, next);
        }
    }
}

#[cfg(test)]
mod input_enumeration_tests {
    use super::*;

    #[test]
    fn cancelled_refresh_keeps_its_permit_until_enumeration_finishes() {
        let gate = InputEnumerationGate::default();
        let pending = gate.try_enter().expect("first refresh");
        assert!(gate.clone().try_enter().is_none());
        drop(pending);
        assert!(gate.try_enter().is_some());
    }

    #[test]
    fn enumeration_unwind_releases_the_gate() {
        let gate = InputEnumerationGate::default();
        let worker_gate = gate.clone();
        let result = std::panic::catch_unwind(move || {
            let _permit = worker_gate.try_enter().expect("first refresh");
            panic!("enumeration fixture");
        });
        assert!(result.is_err());
        assert!(gate.try_enter().is_some());
    }

    #[test]
    fn camera_refresh_preserves_other_device_lists() {
        let microphone = MicrophoneOption {
            name: "Selected microphone".into(),
            sample_rate: Some(48_000),
            channels: Some(2),
        };
        let mut snapshot = DeviceSnapshot {
            microphones: vec![microphone.clone()],
            ..Default::default()
        };
        let camera = CameraOption {
            device_id: "new-camera".into(),
            model_id: None,
            label: "Connected camera".into(),
            best_format: None,
            formats: Vec::new(),
        };
        assert!(InputSnapshot::Cameras(vec![camera.clone()]).install(&mut snapshot));
        assert_eq!(snapshot.cameras, vec![camera.clone()]);
        assert_eq!(snapshot.microphones, vec![microphone]);
        assert!(!InputSnapshot::Cameras(vec![camera.clone()]).install(&mut snapshot));
        assert!(InputSnapshot::Microphones(Vec::new()).install(&mut snapshot));
        assert_eq!(snapshot.cameras, vec![camera]);
    }
    fn camera_fixture(id: &str) -> CameraOption {
        CameraOption {
            device_id: id.into(),
            model_id: None,
            label: "Camera".into(),
            best_format: None,
            formats: Vec::new(),
        }
    }

    fn formats_fixture() -> Vec<CameraFormat> {
        vec![CameraFormat {
            width: 1920,
            height: 1080,
            frame_rate: 30.0,
        }]
    }

    #[test]
    fn completed_query_updates_matching_camera_capabilities() {
        let queried = camera_fixture("camera-a");
        let mut snapshot = DeviceSnapshot {
            cameras: vec![queried.clone()],
            ..Default::default()
        };
        assert!(snapshot.update_camera_formats(&queried, formats_fixture()));
        assert_eq!(snapshot.cameras[0].formats, formats_fixture());
        assert_eq!(
            snapshot.cameras[0].best_format,
            formats_fixture().first().copied()
        );
    }

    #[test]
    fn completed_query_cannot_overwrite_replacement_camera_capabilities() {
        let queried = camera_fixture("camera-a");
        let mut changed_id = queried.clone();
        changed_id.device_id = "camera-b".into();
        let mut changed_model = queried.clone();
        changed_model.model_id =
            Some(cap_camera::ModelID::try_from("046d:08e5".to_string()).unwrap());
        let mut changed_label = queried.clone();
        changed_label.label = "Replacement camera".into();
        for replacement in [changed_id, changed_model, changed_label] {
            let mut snapshot = DeviceSnapshot {
                cameras: vec![replacement.clone()],
                ..Default::default()
            };
            assert!(!snapshot.update_camera_formats(&queried, formats_fixture()));
            assert_eq!(snapshot.cameras, vec![replacement]);
        }
    }

    #[test]
    fn completed_query_cannot_restore_disconnected_camera() {
        let mut snapshot = DeviceSnapshot::default();
        assert!(!snapshot.update_camera_formats(&camera_fixture("camera-a"), formats_fixture()));
        assert!(snapshot.cameras.is_empty());
    }

    #[test]
    fn repeated_camera_refresh_does_not_reopen_unchanged_devices() {
        let mut previous = vec![camera_fixture("camera-a").with_formats(&[], formats_fixture)];
        for _ in 0..1000 {
            let refreshed = camera_fixture("camera-a").with_formats(&previous, || {
                panic!("unchanged camera must not reopen its driver")
            });
            assert_eq!(refreshed, previous[0]);
            previous = vec![refreshed];
        }
    }

    #[test]
    fn new_camera_does_not_inherit_another_devices_formats() {
        let previous = vec![camera_fixture("camera-a").with_formats(&[], formats_fixture)];
        let mut probes = 0;
        let refreshed = camera_fixture("camera-b").with_formats(&previous, || {
            probes += 1;
            Vec::new()
        });
        assert_eq!(probes, 1);
        assert!(refreshed.formats.is_empty());
        assert!(refreshed.best_format.is_none());
    }

    #[test]
    fn reconnect_refreshes_formats_after_camera_disappears() {
        let connected = camera_fixture("camera-a").with_formats(&[], formats_fixture);
        let after_disconnect = Vec::new();
        let changed_format = CameraFormat {
            width: 1280,
            height: 720,
            frame_rate: 60.0,
        };
        let reconnected =
            camera_fixture("camera-a").with_formats(&after_disconnect, || vec![changed_format]);
        assert_ne!(reconnected.formats, connected.formats);
        assert_eq!(reconnected.best_format, Some(changed_format));
    }

    #[test]
    fn renamed_camera_refreshes_capabilities() {
        let previous = vec![camera_fixture("camera-a").with_formats(&[], formats_fixture)];
        let mut camera = camera_fixture("camera-a");
        camera.label = "Reconfigured virtual camera".into();
        let mut probes = 0;
        camera.with_formats(&previous, || {
            probes += 1;
            Vec::new()
        });
        assert_eq!(probes, 1);
    }
    #[test]
    fn failed_probe_is_not_retried_by_background_refresh() {
        let previous = vec![camera_fixture("camera-a").with_formats(&[], Vec::new)];
        let refreshed = camera_fixture("camera-a").with_formats(&previous, || {
            panic!("background refresh must not retry a native probe")
        });
        assert!(refreshed.formats.is_empty());
    }

    #[test]
    fn late_refresh_does_not_erase_successful_explicit_retry() {
        let refreshed = vec![camera_fixture("camera-a")];
        let mut snapshot = DeviceSnapshot {
            cameras: vec![camera_fixture("camera-a").with_formats(&[], formats_fixture)],
            ..Default::default()
        };
        assert!(!InputSnapshot::Cameras(refreshed).install(&mut snapshot));
        assert_eq!(snapshot.cameras[0].formats, formats_fixture());
    }

    #[test]
    fn changed_device_does_not_inherit_previous_capabilities() {
        let mut changed = camera_fixture("camera-a");
        changed.label = "Changed virtual camera".into();
        let mut snapshot = DeviceSnapshot {
            cameras: vec![camera_fixture("camera-a").with_formats(&[], formats_fixture)],
            ..Default::default()
        };
        assert!(InputSnapshot::Cameras(vec![changed]).install(&mut snapshot));
        assert!(snapshot.cameras[0].formats.is_empty());
    }
}

/// Just the capture targets.
///
/// The Tauri app keeps these on their own queries (`listScreens` /
/// `listWindows` in `utils/queries.ts:29-52`), separate from the device query,
/// precisely so the window list can be re-read every few seconds while a
/// picker is open without paying for another AVFoundation camera scan. The
/// split exists here for the same reason: `DeviceSnapshot::enumerate` is the
/// once-at-launch call, this is the one the picker's refresh loop runs.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TargetSnapshot {
    pub displays: Vec<DisplayOption>,
    pub windows: Vec<WindowOption>,
}

impl TargetSnapshot {
    /// Blocking window-server queries, same rule as `DeviceSnapshot::enumerate`:
    /// background executor or a tokio worker, never `render`.
    pub fn enumerate() -> Self {
        Self {
            displays: list_displays(),
            windows: list_windows(),
        }
    }
}

fn list_cameras() -> Vec<CameraOption> {
    list_cameras_with_previous(&[])
}

fn list_cameras_with_previous(previous: &[CameraOption]) -> Vec<CameraOption> {
    cap_camera::list_cameras()
        .map(|camera| {
            CameraOption {
                device_id: camera.device_id().to_string(),
                model_id: camera.model_id().cloned(),
                label: camera.display_name().to_string(),
                best_format: None,
                formats: Vec::new(),
            }
            .with_formats(previous, || {
                camera
                    .formats()
                    .unwrap_or_default()
                    .into_iter()
                    .map(|format| CameraFormat {
                        width: format.width(),
                        height: format.height(),
                        frame_rate: format.frame_rate(),
                    })
                    .collect()
            })
        })
        .collect()
}

impl CameraOption {
    fn same_device(&self, other: &Self) -> bool {
        self.device_id == other.device_id
            && self.model_id == other.model_id
            && self.label == other.label
    }

    fn with_formats(
        mut self,
        previous: &[Self],
        load_formats: impl FnOnce() -> Vec<CameraFormat>,
    ) -> Self {
        // Windows format probing opens native camera sources; polling an unchanged
        // device must reuse metadata rather than repeatedly activating its driver.
        if let Some(previous) = previous.iter().find(|previous| previous.same_device(&self)) {
            self.best_format = previous.best_format;
            self.formats = previous.formats.clone();
            return self;
        }

        let mut formats = load_formats();
        let mut seen = std::collections::HashSet::new();
        formats.retain(|format| {
            seen.insert((
                format.width,
                format.height,
                format.frame_rate.round() as u32,
            ))
        });
        formats.sort_by(|a, b| {
            (u64::from(b.width) * u64::from(b.height))
                .cmp(&(u64::from(a.width) * u64::from(a.height)))
                .then(b.frame_rate.total_cmp(&a.frame_rate))
        });
        self.best_format = formats.first().copied();
        self.formats = formats;
        self
    }
}

pub fn camera_formats(device_id: &str) -> Result<Vec<CameraFormat>, String> {
    let camera = cap_camera::list_cameras()
        .find(|camera| camera.device_id() == device_id)
        .ok_or_else(|| "Camera is no longer available. Reconnect it and try again.".to_string())?;
    let formats = camera.formats().ok_or_else(|| {
        "Could not read camera formats. Check camera access and try again.".to_string()
    })?;
    if formats.is_empty() {
        return Err(
            "No camera formats are available. Check camera access and try again.".to_string(),
        );
    }
    Ok(CameraOption {
        device_id: camera.device_id().to_string(),
        model_id: camera.model_id().cloned(),
        label: camera.display_name().to_string(),
        best_format: None,
        formats: Vec::new(),
    }
    .with_formats(&[], || {
        formats
            .into_iter()
            .map(|format| CameraFormat {
                width: format.width(),
                height: format.height(),
                frame_rate: format.frame_rate(),
            })
            .collect()
    })
    .formats)
}

fn list_microphone_names() -> Vec<MicrophoneOption> {
    cap_recording::feeds::microphone::MicrophoneFeed::list_names()
        .into_iter()
        .map(|name| MicrophoneOption {
            name,
            sample_rate: None,
            channels: None,
        })
        .collect()
}

fn list_microphones() -> Vec<MicrophoneOption> {
    // CPAL's configuration lookup opens an input AudioUnit and can prompt for consent.
    #[cfg(target_os = "macos")]
    if !crate::permissions::check_raw_preflight().is_some_and(|permissions| {
        permissions.microphone == crate::permissions::MediaAuthorization::Authorized
    }) {
        return list_microphone_names();
    }

    let host = cpal::default_host();
    let mut mics: Vec<MicrophoneOption> = Vec::new();

    let mut push = |device: cpal::Device| {
        let Ok(name) = device.name() else { return };
        if mics.iter().any(|mic| mic.name == name) {
            return;
        }

        // `default_input_config` is the config the device would actually be
        // opened with, which is what the row should describe.
        let config = device.default_input_config().ok();
        mics.push(MicrophoneOption {
            name,
            sample_rate: config.as_ref().map(|config| config.sample_rate().0),
            channels: config.as_ref().map(|config| config.channels()),
        });
    };

    if let Some(device) = host.default_input_device() {
        push(device);
    }

    match host.input_devices() {
        Ok(devices) => {
            for device in devices {
                push(device);
            }
        }
        Err(error) => {
            tracing::error!("could not access audio input devices: {error}");
        }
    }

    mics
}

pub fn microphone_formats(
    name: &str,
) -> Result<Vec<cap_recording::feeds::microphone::MicrophoneDeviceSettings>, String> {
    let devices = cap_recording::feeds::microphone::MicrophoneFeed::list();
    let (device, _) = devices
        .get(name)
        .ok_or_else(|| format!("Microphone '{name}' is no longer available"))?;
    let configs = device
        .supported_input_configs()
        .map_err(|error| format!("Could not read microphone formats: {error}"))?;
    let mut formats = std::collections::BTreeSet::new();
    for config in configs {
        if cap_media_info::ffmpeg_sample_format_for(config.sample_format()).is_none() {
            continue;
        }
        for sample_rate in [
            config.min_sample_rate().0,
            44_100,
            48_000,
            96_000,
            config.max_sample_rate().0,
        ] {
            if (config.min_sample_rate().0..=config.max_sample_rate().0).contains(&sample_rate) {
                formats.insert((sample_rate, config.channels()));
            }
        }
    }
    Ok(formats
        .into_iter()
        .rev()
        .map(
            |(sample_rate, channels)| cap_recording::feeds::microphone::MicrophoneDeviceSettings {
                sample_rate: Some(sample_rate),
                channels: Some(channels),
            },
        )
        .collect())
}

/// `Window::get_topmost_at_cursor`, minus this process's own windows: the
/// same level-≤5 filter and descending-level (stable, so front-to-back within
/// a level) pick, transcribed from `scap-targets/src/platform/macos.rs`, with
/// an owner-pid skip added. The overlay's hover highlight and the
/// window-screenshot hotkey fall *through* a cap window to whatever sits
/// beneath it -- the Tauri poll gets the same effect from
/// `should_skip_window` (`target_select_overlay.rs:186-196`).
#[cfg(target_os = "macos")]
pub fn topmost_foreign_window_at_cursor() -> Option<Window> {
    let own_pid = std::process::id() as i32;
    let mut candidates = Window::list_containing_cursor()
        .into_iter()
        .filter_map(|window| {
            let level = window.raw_handle().level()?;
            if level > 5 {
                return None;
            }
            if window.raw_handle().owner_pid() == Some(own_pid) {
                return None;
            }
            Some((window, level))
        })
        .collect::<Vec<_>>();
    candidates.sort_by_key(|(_, level)| std::cmp::Reverse(*level));
    candidates.into_iter().next().map(|(window, _)| window)
}

#[cfg(target_os = "linux")]
pub fn topmost_foreign_window_at_cursor() -> Option<Window> {
    match scap_targets::WindowImpl::topmost_x11_snapshot_at_cursor() {
        Some(found) => found.map(|snapshot| snapshot.window),
        None => Window::get_topmost_at_cursor(),
    }
}

#[cfg(not(any(target_os = "macos", target_os = "linux")))]
pub fn topmost_foreign_window_at_cursor() -> Option<Window> {
    Window::get_topmost_at_cursor()
}

pub fn list_displays() -> Vec<DisplayOption> {
    list_display_targets()
        .into_iter()
        .map(|(option, _)| option)
        .collect()
}

/// The same enumeration, keeping the `scap-targets` handle alongside each row.
///
/// `collect_displays_with_thumbnails` (`src-tauri/src/thumbnails/mod.rs:88-105`)
/// iterates `list_displays()`'s `(CaptureDisplay, Display)` pairs so the
/// capture and the row it fills come from one pass. Re-deriving the handle from
/// the id later would mean a second full `Display::list()` per target.
pub fn list_display_targets() -> Vec<(DisplayOption, Display)> {
    Display::list()
        .into_iter()
        .map(|display| {
            let id = display.id();
            let label = display.name().unwrap_or_else(|| format!("Display {}", id));
            (
                DisplayOption {
                    id,
                    label,
                    refresh_rate: display.refresh_rate(),
                },
                display,
            )
        })
        .collect()
}

pub fn list_windows() -> Vec<WindowOption> {
    list_window_targets()
        .into_iter()
        .map(|(option, _)| option)
        .collect()
}

/// The same enumeration, keeping the `scap-targets` handle alongside each row —
/// the window twin of `list_display_targets`, for
/// `collect_windows_with_thumbnails` (`thumbnails/mod.rs:107-137`), which needs
/// the handle for both the ScreenCaptureKit filter and `Window::app_icon()`.
pub fn list_window_targets() -> Vec<(WindowOption, Window)> {
    list_window_targets_inner(
        #[cfg(target_os = "windows")]
        &mut scap_targets::platform::WindowListCache::default(),
    )
}

pub(crate) fn list_window_targets_inner(
    #[cfg(target_os = "windows")] cache: &mut scap_targets::platform::WindowListCache,
) -> Vec<(WindowOption, Window)> {
    #[cfg(target_os = "linux")]
    if let Some(targets) = linux_window_targets_from_snapshot() {
        return targets;
    }

    #[cfg(target_os = "windows")]
    let windows = cache.list();
    #[cfg(not(target_os = "windows"))]
    let windows = Window::list();

    windows
        .into_iter()
        .filter_map(|window| {
            #[cfg(target_os = "windows")]
            if !cache.is_valid(&window) || !cache.is_on_screen(&window) {
                return None;
            }

            let label = window.name().filter(|name| !name.trim().is_empty())?;
            #[cfg(target_os = "windows")]
            let app = cache.owner_name(&window)?;
            #[cfg(not(target_os = "windows"))]
            let app = window.owner_name()?;

            if app == "Window Server" {
                return None;
            }

            // Our own windows never belong in the picker: the recording flow
            // excludes them from the capture filter anyway
            // (`app_windows::begin_recording`), so offering one as a target
            // records a hole. Matched by owner pid rather than title or
            // bundle id -- the dev binary is unbundled, and most of our
            // windows carry no CG title at all.
            #[cfg(target_os = "macos")]
            if window.raw_handle().owner_pid() == Some(std::process::id() as i32) {
                return None;
            }

            #[cfg(target_os = "macos")]
            {
                let level = window.raw_handle().level();
                let bundle_identifier = window.raw_handle().bundle_identifier();
                let is_accessory_application = matches!(level, Some(level) if level > 0)
                    && window.raw_handle().is_accessory_application();
                if !cap_recording::sources::screen_capture::is_listable_macos_window(
                    level,
                    &app,
                    bundle_identifier.as_deref(),
                    false,
                    is_accessory_application,
                ) {
                    return None;
                }
            }

            Some((
                WindowOption {
                    id: window.id(),
                    label,
                    app,
                    size: window
                        .logical_size()
                        .map(|size| (size.width() as u32, size.height() as u32)),
                    position: window
                        .display_relative_logical_bounds()
                        .map(|bounds| (bounds.position().x(), bounds.position().y())),
                    refresh_rate: window.display().map(|display| display.refresh_rate()),
                },
                window,
            ))
        })
        .collect()
}

#[cfg(target_os = "linux")]
fn linux_window_targets_from_snapshot() -> Option<Vec<(WindowOption, Window)>> {
    let snapshots = scap_targets::WindowImpl::list_x11_snapshots()?;
    Some(
        snapshots
            .into_iter()
            .filter_map(|snapshot| {
                let size = snapshot.logical_size();
                let position = snapshot.display_relative_origin();
                let refresh_rate = snapshot.refresh_rate();
                let id = snapshot.window.id();
                if snapshot.name.trim().is_empty() {
                    return None;
                }
                let app = snapshot.owner_name?;
                if app == "Window Server" {
                    return None;
                }
                // As on macOS: recording one of our own windows records a
                // window the recording hides.
                if snapshot.owner_pid == Some(std::process::id()) {
                    return None;
                }
                Some((
                    WindowOption {
                        id,
                        label: snapshot.name,
                        app,
                        size: Some((size.width() as u32, size.height() as u32)),
                        position,
                        refresh_rate: Some(refresh_rate),
                    },
                    snapshot.window,
                ))
            })
            .collect(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Smoke test for the real enumeration path. Displays are the only thing we
    /// can assert on unconditionally — a machine running this test has at least
    /// one screen, but it may genuinely have no camera and no microphone, and on
    /// a fresh machine the TCC prompt for camera access has not been answered
    /// yet. The rest is printed for eyeballing with `--nocapture`.
    #[test]
    fn enumerates_real_devices() {
        let snapshot = DeviceSnapshot::enumerate();

        println!("cameras ({}):", snapshot.cameras.len());
        for camera in &snapshot.cameras {
            println!(
                "  {} [{}] {}",
                camera.label,
                camera.device_id,
                camera
                    .best_format
                    .map(|format| format.describe())
                    .unwrap_or_else(|| "<no formats>".into())
            );
        }
        println!("microphones ({}):", snapshot.microphones.len());
        for mic in &snapshot.microphones {
            println!(
                "  {} {}",
                mic.name,
                mic.describe().unwrap_or_else(|| "<no config>".into())
            );
        }
        println!("displays ({}):", snapshot.displays.len());
        for display in &snapshot.displays {
            println!("  {} [{}]", display.label, display.id);
        }
        println!("windows ({}):", snapshot.windows.len());
        for window in snapshot.windows.iter().take(10) {
            println!("  {} — {} [{}]", window.app, window.label, window.id);
        }

        assert!(
            !snapshot.displays.is_empty(),
            "expected at least one display"
        );
        assert!(
            snapshot.windows.iter().all(|w| !w.label.trim().is_empty()),
            "untitled windows should have been filtered out"
        );
    }

    /// The thumbnail sweep enumerates through the `*_targets` pairs so it can
    /// keep the `scap-targets` handle, while the picker's cheap poll goes
    /// through the plain lists. If those two ever diverged the cards and their
    /// thumbnails would be describing different windows.
    #[test]
    fn paired_listings_agree_with_the_plain_ones() {
        let displays = list_displays();
        let paired: Vec<_> = list_display_targets()
            .into_iter()
            .map(|(option, _)| option)
            .collect();
        assert_eq!(displays.len(), paired.len());
        assert_eq!(
            displays
                .iter()
                .map(|d| d.id.to_string())
                .collect::<Vec<_>>(),
            paired.iter().map(|d| d.id.to_string()).collect::<Vec<_>>(),
        );

        // Window lists race real window-server state between the two calls, so
        // only the shape is assertable: both go through `list_window_targets`,
        // and every row must carry the position the refresh signature needs.
        let windows = list_window_targets();
        assert!(
            windows
                .iter()
                .all(|(option, handle)| option.id == handle.id()),
            "each row must be paired with its own handle"
        );
        assert!(
            windows.iter().any(|(option, _)| option.position.is_some()) || windows.is_empty(),
            "display-relative bounds should resolve for at least one window"
        );
    }

    #[test]
    fn target_snapshot_is_the_display_and_window_half_of_a_device_snapshot() {
        let targets = TargetSnapshot::enumerate();
        assert!(
            !targets.displays.is_empty(),
            "expected at least one display"
        );
    }
}