Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

21.3 KB
Raw Blame
// Adapted from Serein (https://github.com/ViceVerse-cz/Serein) at commit a0e72cc,
// file `crates/discord-voice/src/screen/capture_windows.rs`.
// Copyright (c) 2026 Serein contributors. Licensed under MIT OR Apache-2.0; RustCord's
// modifications are under the same terms. See crates/voice/NOTICE.md.
//
// RustCord changes: RustCord's source list (cloaked and desktop windows skipped), frame
// buffers recycled from the encoder, one-frame thumbnails, a failed system-audio loopback
// no longer ends the share, the pointer is drawn into frames instead of by Windows.
//! Windows Graphics Capture of one monitor or window (via `windows-capture`).
use super::{AudioChunk, NativeSource, RawFrame, Settings, SourceId};
use std::sync::{
    Arc, OnceLock,
    atomic::{AtomicBool, AtomicU64, Ordering},
    mpsc::{Receiver, SyncSender},
};
use std::time::{Duration, Instant};
use windows_capture::{
    capture::{CaptureControl, Context, GraphicsCaptureApiHandler},
    frame::Frame,
    graphics_capture_api::{GraphicsCaptureApi, InternalCaptureControl},
    monitor::Monitor,
    settings::{
        ColorFormat, CursorCaptureSettings, DirtyRegionSettings, DrawBorderSettings,
        MinimumUpdateIntervalSettings, SecondaryWindowSettings, Settings as NativeSettings,
    },
    window::Window,
};

#[path = "audio_windows.rs"]
mod audio;
#[path = "cursor_windows.rs"]
mod cursor;

const MAX_SOURCES: usize = 64;
const MAX_NAME_BYTES: usize = 256;
const MAX_SOURCE_WIDTH: u32 = 7680;
const MAX_SOURCE_HEIGHT: u32 = 4320;
const MAX_FRAME_WIDTH: u32 = 3840;
const MAX_FRAME_HEIGHT: u32 = 2160;
const MAX_RAW_BYTES: usize = MAX_FRAME_WIDTH as usize * MAX_FRAME_HEIGHT as usize * 4;

fn bounded_name(mut name: String) -> String {
    if name.len() > MAX_NAME_BYTES {
        let mut end = MAX_NAME_BYTES;
        while !name.is_char_boundary(end) {
            end -= 1;
        }
        name.truncate(end);
        name.shrink_to_fit();
    }
    name
}

fn monitor_id(monitor: &Monitor) -> u64 {
    u64::try_from(monitor.as_raw_hmonitor() as usize).unwrap_or(0)
}

fn window_id(window: &Window) -> u64 {
    u64::try_from(window.as_raw_hwnd() as usize).unwrap_or(0)
}

/// Suspended Store apps and other cloaked windows are "visible" but never drawn.
#[allow(unsafe_code)]
fn cloaked(window: &Window) -> bool {
    use windows::Win32::{
        Foundation::HWND,
        Graphics::Dwm::{DWMWA_CLOAKED, DwmGetWindowAttribute},
    };
    let mut cloaked = 0u32;
    // SAFETY: DWM writes at most `size_of::<u32>()` bytes into the local it is given; an
    // invalid (already destroyed) window handle only returns an error.
    let result = unsafe {
        DwmGetWindowAttribute(
            HWND(window.as_raw_hwnd()),
            DWMWA_CLOAKED,
            (&raw mut cloaked).cast(),
            size_of::<u32>() as u32,
        )
    };
    result.is_ok() && cloaked != 0
}

fn window_size(window: &Window) -> Option<(u32, u32)> {
    let (Ok(width), Ok(height)) = (window.width(), window.height()) else {
        return None;
    };
    u32::try_from(width).ok().zip(u32::try_from(height).ok())
}

/// Monitors first, then visible titled windows, as Windows enumerates them.
pub(crate) fn sources() -> Result<Vec<NativeSource>, &'static str> {
    let mut sources = Vec::with_capacity(16);
    for monitor in Monitor::enumerate().map_err(|_| "Displays could not be enumerated")? {
        let (Ok(width), Ok(height)) = (monitor.width(), monitor.height()) else {
            continue;
        };
        if width == 0 || height == 0 || width > MAX_SOURCE_WIDTH || height > MAX_SOURCE_HEIGHT {
            continue;
        }
        let name = monitor
            .name()
            .or_else(|_| monitor.device_string())
            .unwrap_or_else(|_| "Display".to_owned());
        sources.push(NativeSource {
            id: SourceId::Display(monitor_id(&monitor)),
            name: bounded_name(name),
        });
        if sources.len() == MAX_SOURCES {
            return Ok(sources);
        }
    }

    for window in Window::enumerate().map_err(|_| "Windows could not be enumerated")? {
        let Ok(title) = window.title() else {
            continue;
        };
        let Some((width, height)) = window_size(&window) else {
            continue;
        };
        if title.trim().is_empty()
            // The desktop itself (Explorer's shell window) is not an application window.
            || title == "Program Manager"
            || width == 0
            || height == 0
            || width > MAX_SOURCE_WIDTH
            || height > MAX_SOURCE_HEIGHT
            || cloaked(&window)
        {
            continue;
        }
        sources.push(NativeSource {
            id: SourceId::Window(window_id(&window)),
            name: bounded_name(title),
        });
        if sources.len() == MAX_SOURCES {
            break;
        }
    }
    Ok(sources)
}

/// The current native size of a source, or why it cannot be shared.
pub(crate) fn source_size(id: SourceId) -> Result<(u32, u32), &'static str> {
    let size = match id {
        SourceId::Display(id) => {
            let monitor = find_monitor(id)?;
            monitor.width().ok().zip(monitor.height().ok())
        }
        SourceId::Window(id) => window_size(&find_window(id)?),
        SourceId::Camera(_) => None,
    };
    size.filter(|&(width, height)| width > 0 && height > 0)
        .ok_or("Selected source dimensions are unavailable")
}

fn find_monitor(id: u64) -> Result<Monitor, &'static str> {
    Monitor::enumerate()
        .map_err(|_| "Displays could not be enumerated")?
        .into_iter()
        .find(|monitor| monitor_id(monitor) == id)
        .ok_or("Selected display is no longer available")
}

fn find_window(id: u64) -> Result<Window, &'static str> {
    Window::enumerate()
        .map_err(|_| "Windows could not be enumerated")?
        .into_iter()
        .find(|window| window_id(window) == id)
        .ok_or("Selected window is no longer available")
}

struct Flags {
    frames: SyncSender<RawFrame>,
    /// Buffers the encoder no longer needs, reused instead of allocating per frame.
    recycle: Option<Receiver<Vec<u8>>>,
    stop: Arc<AtomicBool>,
    pending: Arc<AtomicBool>,
    next_frame: Instant,
    interval: Duration,
    /// Thumbnails stop after their first frame.
    once: bool,
    /// Draws the mouse pointer into frames, where Windows does not.
    pointer: Option<cursor::Pointer>,
}

struct Handler(Flags);

impl GraphicsCaptureApiHandler for Handler {
    type Flags = Flags;
    type Error = &'static str;

    fn new(context: Context<Self::Flags>) -> Result<Self, Self::Error> {
        Ok(Self(context.flags))
    }

    fn on_frame_arrived(
        &mut self,
        frame: &mut Frame,
        control: InternalCaptureControl,
    ) -> Result<(), Self::Error> {
        if self.0.stop.load(Ordering::Acquire) {
            control.stop();
            return Ok(());
        }
        let now = Instant::now();
        if now + Duration::from_millis(2) < self.0.next_frame
            || self.0.pending.swap(true, Ordering::AcqRel)
        {
            return Ok(());
        }
        self.0.next_frame = (self.0.next_frame + self.0.interval).max(now + self.0.interval / 2);
        let (width, height) = (frame.width(), frame.height());
        let Some(row_bytes) = (width as usize).checked_mul(4) else {
            self.0.stop.store(true, Ordering::Release);
            control.stop();
            return Err("Captured frame dimensions are invalid");
        };
        let Some(data_len) = row_bytes.checked_mul(height as usize) else {
            self.0.stop.store(true, Ordering::Release);
            control.stop();
            return Err("Captured frame dimensions are invalid");
        };
        if width == 0
            || height == 0
            || width > MAX_FRAME_WIDTH
            || height > MAX_FRAME_HEIGHT
            || data_len > MAX_RAW_BYTES
        {
            self.0.stop.store(true, Ordering::Release);
            control.stop();
            return Err("Captured frame exceeds the 4K limit");
        }
        let mut buffer = frame.buffer().map_err(|_| {
            self.0.stop.store(true, Ordering::Release);
            "Captured frame could not be read"
        })?;
        let stride = buffer.row_pitch() as usize;
        let Some(source_len) = stride.checked_mul(height as usize) else {
            self.0.stop.store(true, Ordering::Release);
            return Err("Captured frame stride is invalid");
        };
        if stride < row_bytes || source_len > MAX_RAW_BYTES {
            self.0.stop.store(true, Ordering::Release);
            return Err("Captured frame stride exceeds the 4K limit");
        }
        let source = buffer.as_raw_buffer();
        if source.len() < source_len {
            self.0.stop.store(true, Ordering::Release);
            return Err("Captured frame buffer is incomplete");
        }
        let mut data = self
            .0
            .recycle
            .as_ref()
            .and_then(|recycle| recycle.try_recv().ok())
            .unwrap_or_default();
        data.clear();
        data.reserve_exact(data_len);
        for row in source[..source_len].chunks_exact(stride) {
            data.extend_from_slice(&row[..row_bytes]);
        }
        if let Some(pointer) = &mut self.0.pointer {
            pointer.draw(&mut data, width, height);
        }
        if self
            .0
            .frames
            .try_send(RawFrame {
                width,
                height,
                stride: row_bytes,
                data,
            })
            .is_err()
        {
            self.0.pending.store(false, Ordering::Release);
        }
        if self.0.once {
            control.stop();
        }
        Ok(())
    }

    fn on_closed(&mut self) -> Result<(), Self::Error> {
        self.0.stop.store(true, Ordering::Release);
        Ok(())
    }
}

pub(crate) struct Capture {
    control: Option<CaptureControl<Handler, &'static str>>,
    audio: Option<audio::Audio>,
}

/// What one capture session needs besides its settings.
pub(crate) struct Outputs {
    pub frames: SyncSender<RawFrame>,
    pub recycle: Receiver<Vec<u8>>,
    pub audio: Option<tokio::sync::mpsc::Sender<AudioChunk>>,
    /// Set by capture when the source closes or fails.
    pub stop: Arc<AtomicBool>,
    /// Secure stream media (gates system audio).
    pub ready: Arc<AtomicBool>,
    pub audio_epoch: Arc<AtomicU64>,
    /// A frame the encoder has not taken yet; capture skips frames meanwhile.
    pub pending: Arc<AtomicBool>,
    /// The worker's cancellation: a stopped share gives up a pending consent wait.
    pub cancel: Arc<AtomicBool>,
}

impl Capture {
    pub(crate) fn start(settings: Settings, outputs: Outputs) -> Result<Self, &'static str> {
        if settings.width == 0
            || settings.height == 0
            || settings.width > MAX_FRAME_WIDTH
            || settings.height > MAX_FRAME_HEIGHT
            || settings.fps == 0
        {
            return Err("Invalid screen capture settings");
        }
        let Outputs {
            frames,
            recycle,
            audio,
            stop,
            ready,
            audio_epoch,
            pending,
            cancel,
        } = outputs;
        let flags = Flags {
            frames,
            recycle: Some(recycle),
            stop,
            pending,
            next_frame: Instant::now(),
            interval: Duration::from_secs_f64(1.0 / f64::from(settings.fps)),
            once: false,
            pointer: None,
        };
        let control = match settings.source {
            SourceId::Display(id) => start_item(find_monitor(id)?, settings.cursor, flags, &cancel),
            SourceId::Window(id) => start_item(find_window(id)?, settings.cursor, flags, &cancel),
            SourceId::Camera(_) => Err("A camera is not a screen source"),
        }?;
        // System audio is best effort: without it (older Windows, no output device) the
        // video share continues and the transport sends no soundshare packets.
        let audio = audio.and_then(|send| audio::Audio::start(send, ready, audio_epoch).ok());
        Ok(Capture {
            control: Some(control),
            audio,
        })
    }
}

trait Item:
    TryInto<windows_capture::settings::GraphicsCaptureItemType> + Send + Copy + 'static
{
    fn dimensions(&self) -> Option<(u32, u32)>;
    /// Converts the source once, so Windows can answer with its permission decision.
    fn probe(&self) -> Result<(), &'static str>;
    fn pointer_target(&self) -> cursor::Target;
}

impl Item for Monitor {
    fn dimensions(&self) -> Option<(u32, u32)> {
        self.width().ok().zip(self.height().ok())
    }
    fn probe(&self) -> Result<(), &'static str> {
        <Monitor as TryInto<windows_capture::settings::GraphicsCaptureItemType>>::try_into(*self)
            .map(|_| ())
            .map_err(|error| capture_refusal(error.code().0 as u32))
    }
    fn pointer_target(&self) -> cursor::Target {
        cursor::Target::Display(windows::Win32::Graphics::Gdi::HMONITOR(self.as_raw_hmonitor()))
    }
}

impl Item for Window {
    fn dimensions(&self) -> Option<(u32, u32)> {
        window_size(self)
    }
    fn probe(&self) -> Result<(), &'static str> {
        <Window as TryInto<windows_capture::settings::GraphicsCaptureItemType>>::try_into(*self)
            .map(|_| ())
            .map_err(|error| capture_refusal(error.code().0 as u32))
    }
    fn pointer_target(&self) -> cursor::Target {
        cursor::Target::Window(windows::Win32::Foundation::HWND(self.as_raw_hwnd()))
    }
}

fn start_item<T: Item>(
    item: T,
    cursor: bool,
    mut flags: Flags,
    cancel: &AtomicBool,
) -> Result<CaptureControl<Handler, &'static str>, &'static str> {
    let Some((width, height)) = item.dimensions() else {
        return Err("Selected source dimensions are unavailable");
    };
    if width == 0 || height == 0 || width > MAX_SOURCE_WIDTH || height > MAX_SOURCE_HEIGHT {
        return Err("Selected source exceeds the capture limit");
    }
    // Windows 11 keeps a per-application consent; an application that never asks is denied and
    // the Settings page lists no request. Asking here shows the system prompt once.
    request_access(cancel)?;
    // The item conversion can still refuse the source (a protected window, for example).
    item.probe()?;
    // Windows' own pointer is missing from games that present through independent flip, so
    // the pointer is drawn into frames instead. Windows before the cursor setting always draw
    // it themselves, and a second pointer would cancel out the inverting text cursor.
    let cursor = if !GraphicsCaptureApi::is_cursor_settings_supported().unwrap_or(false) {
        CursorCaptureSettings::Default
    } else {
        flags.pointer = cursor.then(|| cursor::Pointer::new(item.pointer_target()));
        CursorCaptureSettings::WithoutCursor
    };
    // An unset interval lets Windows batch pointer-only updates away from the frame rate.
    let minimum_update =
        if GraphicsCaptureApi::is_minimum_update_interval_supported().unwrap_or(false) {
            MinimumUpdateIntervalSettings::Custom(Duration::from_millis(1))
        } else {
            MinimumUpdateIntervalSettings::Default
        };
    let native = NativeSettings::new(
        item,
        cursor,
        // Hide the border where supported; older Windows must keep the system default.
        if GraphicsCaptureApi::is_border_settings_supported().unwrap_or(false) {
            DrawBorderSettings::WithoutBorder
        } else {
            DrawBorderSettings::Default
        },
        SecondaryWindowSettings::Default,
        minimum_update,
        DirtyRegionSettings::Default,
        ColorFormat::Bgra8,
        flags,
    );
    Handler::start_free_threaded(native).map_err(|error| start_failure(&error))
}

/// One still of a source: its first captured frame, within half a second.
pub(crate) fn thumbnail(id: SourceId) -> Option<RawFrame> {
    let (send, frames) = std::sync::mpsc::sync_channel(1);
    let stop = Arc::new(AtomicBool::new(false));
    let flags = Flags {
        frames: send,
        recycle: None,
        stop: stop.clone(),
        pending: Arc::new(AtomicBool::new(false)),
        next_frame: Instant::now(),
        interval: Duration::from_millis(1),
        once: true,
        pointer: None,
    };
    let cancel = AtomicBool::new(false);
    let control = match id {
        SourceId::Display(id) => start_item(find_monitor(id).ok()?, false, flags, &cancel),
        SourceId::Window(id) => start_item(find_window(id).ok()?, false, flags, &cancel),
        SourceId::Camera(_) => return None,
    }
    .ok()?;
    let frame = frames.recv_timeout(Duration::from_millis(500)).ok();
    stop.store(true, Ordering::Release);
    let _ = control.stop();
    frame
}

impl Drop for Capture {
    fn drop(&mut self) {
        self.audio.take();
        if let Some(control) = self.control.take() {
            let _ = control.stop();
        }
    }
}

/// `E_ACCESSDENIED`; Windows 11's "Screenshots and screen recording" privacy setting returns it.
const ACCESS_DENIED: u32 = 0x8007_0005;
/// Windows 11 blocks programmatic capture for applications the owner has not allowed.
const DENIED: &str = "Windows blocked screen capture for this app; allow it in Settings, Privacy & security, Screenshots and screen recording";
/// How often a pending consent wait checks whether the share was cancelled.
const CONSENT_POLL: Duration = Duration::from_millis(50);

/// Asks Windows for the programmatic capture consent this application needs.
///
/// The consent is per application: an application that never asks is denied outright and the
/// Settings page lists no request. The call shows the system prompt once; the wait stays
/// cancellable so a share stopped while the prompt is open releases the worker at once.
/// A granted consent is remembered for the process, so thumbnails do not ask again.
fn request_access(stop: &AtomicBool) -> Result<(), &'static str> {
    use windows::Graphics::Capture::{GraphicsCaptureAccess, GraphicsCaptureAccessKind};
    use windows::Security::Authorization::AppCapabilityAccess::AppCapabilityAccessStatus;
    use windows_future::AsyncStatus;
    static ALLOWED: OnceLock<()> = OnceLock::new();
    if ALLOWED.get().is_some() {
        return Ok(());
    }
    // SAFETY: WinRT activation needs an initialized apartment on this worker thread. Only the
    // consent call below decides the outcome, so an already-initialized mode is harmless.
    #[allow(unsafe_code)]
    unsafe {
        let _ = windows::Win32::System::WinRT::RoInitialize(
            windows::Win32::System::WinRT::RO_INIT_MULTITHREADED,
        );
    }
    let Ok(operation) =
        GraphicsCaptureAccess::RequestAccessAsync(GraphicsCaptureAccessKind::Programmatic)
    else {
        // Builds without the consent API report their decision through the capture item instead.
        let _ = ALLOWED.set(());
        return Ok(());
    };
    while operation.Status() == Ok(AsyncStatus::Started) {
        if stop.load(Ordering::Acquire) {
            return Err("Screen sharing was cancelled");
        }
        std::thread::sleep(CONSENT_POLL);
    }
    match operation.GetResults() {
        Ok(status) if status == AppCapabilityAccessStatus::Allowed => {
            let _ = ALLOWED.set(());
            Ok(())
        }
        // A decision the owner made is the only answer this call can be trusted with: an
        // unpackaged executable reports NotDeclaredByApp even where capture is already allowed,
        // and that decision still belongs to the capture item.
        Ok(status)
            if status == AppCapabilityAccessStatus::DeniedByUser
                || status == AppCapabilityAccessStatus::DeniedBySystem =>
        {
            Err(DENIED)
        }
        _ => Ok(()),
    }
}

/// The item conversion is the first place Windows reports the privacy decision.
fn capture_refusal(code: u32) -> &'static str {
    if code == ACCESS_DENIED {
        DENIED
    } else {
        "Screen capture could not be started"
    }
}

fn start_failure(
    error: &windows_capture::capture::GraphicsCaptureApiError<&'static str>,
) -> &'static str {
    use windows_capture::{capture::GraphicsCaptureApiError as Error, graphics_capture_api};
    match error {
        Error::GraphicsCaptureApiError(graphics_capture_api::Error::WindowsError(windows))
            if windows.code().0 as u32 == ACCESS_DENIED =>
        {
            DENIED
        }
        Error::DirectXError(_) => "The graphics driver could not start screen capture",
        Error::FailedToInitWinRT
        | Error::FailedToCreateDispatcherQueueController
        | Error::FailedToShutdownDispatcherQueue
        | Error::FailedToSetDispatcherQueueCompletedHandler
        | Error::FailedToRunMessageLoop
        | Error::FailedToStartCaptureThread
        | Error::FailedToJoinThread => "Windows could not start its screen-capture service",
        Error::ItemConvertFailed => "The selected screen or window cannot be captured",
        Error::GraphicsCaptureApiError(graphics_capture_api::Error::Unsupported) => {
            "Windows Graphics Capture is unavailable on this Windows build"
        }
        Error::GraphicsCaptureApiError(_) => "Windows refused to start screen capture",
        Error::NewHandlerError(_) | Error::FrameHandlerError(_) => {
            "Screen capture could not be started"
        }
    }
}

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

    #[test]
    fn source_names_end_on_utf8_boundaries() {
        let name = bounded_name(format!("{}é", "a".repeat(MAX_NAME_BYTES - 1)));
        assert_eq!(name.len(), MAX_NAME_BYTES - 1);
    }
}