Skip to content

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

16.5 KB
Raw Blame
// RustCord: webcam capture, a third capture source beside monitors and windows.
//! A camera read through Media Foundation's source reader as top-down BGRA pictures, fed
//! into the same queue as the screen capture so the encoder, preview and pacing are shared.
// FFI: the Media Foundation calls are unsafe, each block states what it relies on.
#![allow(unsafe_code)]

use super::RawFrame;
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
    mpsc::{Receiver, SyncSender},
};
use windows::{
    Win32::{
        Media::MediaFoundation::*,
        System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoTaskMemFree, CoUninitialize},
    },
    core::{GUID, Interface, PWSTR},
};

const UNAVAILABLE: &str = "Cameras are unavailable on this computer";
const OPEN_FAILED: &str = "The camera could not be opened; another app may be using it";
const NOT_FOUND: &str = "The selected camera is not connected";
const READ_FAILED: &str = "The camera stopped sending pictures";
const STREAM: u32 = MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32;

/// A connected camera. `id` is derived from the device's system path, so it stays the
/// same across restarts and replugging into the same port.
pub(crate) struct Device {
    pub id: u64,
    pub name: String,
}

/// COM and Media Foundation for the current thread.
struct Runtime;
impl Runtime {
    fn open() -> Result<Self, &'static str> {
        // SAFETY: Balanced in Drop on the same thread; every caller is a thread RustCord owns.
        unsafe {
            CoInitializeEx(None, COINIT_MULTITHREADED)
                .ok()
                .map_err(|_| UNAVAILABLE)?;
            if MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET).is_err() {
                CoUninitialize();
                return Err(UNAVAILABLE);
            }
        }
        Ok(Self)
    }
}
impl Drop for Runtime {
    fn drop(&mut self) {
        // SAFETY: Balanced with Runtime::open on the same thread.
        unsafe {
            let _ = MFShutdown();
            CoUninitialize();
        }
    }
}

fn id_of(link: &str) -> u64 {
    // FNV-1a; never zero (zero is "no source").
    link.bytes()
        .fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| {
            (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
        })
        .max(1)
}

/// # Safety
/// Media Foundation must be started on this thread.
unsafe fn text(activate: &IMFActivate, key: &GUID) -> Option<String> {
    let mut value = PWSTR::null();
    let mut length = 0u32;
    // SAFETY: Out pointers are valid; the string is freed below.
    unsafe {
        activate
            .GetAllocatedString(key, &mut value, &mut length)
            .ok()?;
        let text = value.to_string().ok();
        CoTaskMemFree(Some(value.0.cast()));
        text
    }
}

/// # Safety
/// Media Foundation must be started on this thread.
unsafe fn activates() -> Result<Vec<(IMFActivate, Device)>, &'static str> {
    // SAFETY: Plain Media Foundation enumeration; the returned array is freed below.
    unsafe {
        let mut attributes = None;
        MFCreateAttributes(&mut attributes, 1).map_err(|_| UNAVAILABLE)?;
        let attributes = attributes.ok_or(UNAVAILABLE)?;
        attributes
            .SetGUID(
                &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
                &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID,
            )
            .map_err(|_| UNAVAILABLE)?;
        let mut list: *mut Option<IMFActivate> = std::ptr::null_mut();
        let mut count = 0u32;
        MFEnumDeviceSources(&attributes, &mut list, &mut count).map_err(|_| UNAVAILABLE)?;
        let mut out = Vec::new();
        if !list.is_null() {
            for slot in std::slice::from_raw_parts_mut(list, count.min(64) as usize) {
                let Some(activate) = slot.take() else { continue };
                let name = text(&activate, &MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME)
                    .unwrap_or_else(|| "Camera".into());
                let link = text(
                    &activate,
                    &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK,
                )
                .unwrap_or_else(|| name.clone());
                out.push((
                    activate,
                    Device {
                        id: id_of(&link),
                        name,
                    },
                ));
            }
            CoTaskMemFree(Some(list.cast()));
        }
        Ok(out)
    }
}

fn on_thread<T: Send + 'static>(
    name: &str,
    work: impl FnOnce() -> Result<T, &'static str> + Send + 'static,
) -> Result<T, &'static str> {
    // A thread RustCord owns has its own COM apartment whatever the caller's thread uses.
    std::thread::Builder::new()
        .name(name.into())
        .spawn(work)
        .map_err(|_| UNAVAILABLE)?
        .join()
        .map_err(|_| UNAVAILABLE)?
}

/// Connected cameras (blocking, tens of milliseconds).
pub(crate) fn devices() -> Result<Vec<Device>, &'static str> {
    on_thread("rustcord-cameras", || {
        let _runtime = Runtime::open()?;
        // SAFETY: Media Foundation runs on this thread for the call.
        Ok(unsafe { activates() }?.into_iter().map(|(_, device)| device).collect())
    })
}

/// The media source of an open camera: shut down when dropped (a source reader made from
/// a source leaves that to its creator), which frees the device for other apps.
struct Source(IMFMediaSource);
impl Drop for Source {
    fn drop(&mut self) {
        // SAFETY: The source is live; shutting down twice is harmless.
        unsafe {
            let _ = self.0.Shutdown();
        }
    }
}

/// (Fields drop in order: the reader first, then its source.)
struct Reader {
    reader: IMFSourceReader,
    _source: Source,
}

fn frame_size(kind: &IMFMediaType) -> Option<(u32, u32)> {
    // SAFETY: Reading an attribute of a live media type.
    let packed = unsafe { kind.GetUINT64(&MF_MT_FRAME_SIZE) }.ok()?;
    let (width, height) = ((packed >> 32) as u32, packed as u32);
    (width >= 2 && height >= 2 && width <= 3840 && height <= 2160).then_some((width, height))
}

/// Open the camera for reading BGRA at the format closest to `want` (width, height):
/// the largest one not above it, at 24 pictures a second or more where the camera has one.
///
/// # Safety
/// Media Foundation must be started on this thread.
unsafe fn open(id: u64, want: (u32, u32)) -> Result<(Reader, u32, u32), &'static str> {
    // SAFETY: Media Foundation calls on objects created here.
    unsafe {
        let (activate, _) = activates()?
            .into_iter()
            .find(|(_, device)| device.id == id)
            .ok_or(NOT_FOUND)?;
        let source: IMFMediaSource = activate.ActivateObject().map_err(|_| OPEN_FAILED)?;
        // (From here on, dropping `source` releases the camera.)
        let source = Source(source);
        let mut attributes = None;
        MFCreateAttributes(&mut attributes, 1).map_err(|_| OPEN_FAILED)?;
        let attributes = attributes.ok_or(OPEN_FAILED)?;
        // Colour conversion (and MJPEG decoding) to the BGRA RustCord asks for below.
        attributes
            .SetUINT32(&MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING, 1)
            .map_err(|_| OPEN_FAILED)?;
        let reader = MFCreateSourceReaderFromMediaSource(&source.0, &attributes)
            .map_err(|_| OPEN_FAILED)?;
        let mut best: Option<(IMFMediaType, i64)> = None;
        for index in 0..256 {
            let Ok(kind) = reader.GetNativeMediaType(STREAM, index) else { break };
            let Some((width, height)) = frame_size(&kind) else { continue };
            let rate = kind.GetUINT64(&MF_MT_FRAME_RATE).unwrap_or(0);
            let fps = (rate >> 32) as f64 / f64::from((rate as u32).max(1));
            let pixels = i64::from(width) * i64::from(height);
            let fits = width <= want.0 && height <= want.1;
            // Formats that fit rank by size; larger ones rank below every fitting one,
            // smallest first. A slow format loses to any normal one of its group.
            let mut score = if fits { pixels } else { -pixels };
            if fps < 23.5 {
                score -= 1 << 40;
            }
            if !fits {
                score -= 1 << 36;
            }
            if best.as_ref().is_none_or(|(_, top)| score > *top) {
                best = Some((kind, score));
            }
        }
        let (native, _) = best.ok_or(OPEN_FAILED)?;
        let size = frame_size(&native).ok_or(OPEN_FAILED)?;
        reader
            .SetCurrentMediaType(STREAM, None, &native)
            .map_err(|_| OPEN_FAILED)?;
        let output = MFCreateMediaType().map_err(|_| OPEN_FAILED)?;
        output
            .SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video)
            .map_err(|_| OPEN_FAILED)?;
        output
            .SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_RGB32)
            .map_err(|_| OPEN_FAILED)?;
        output
            .SetUINT64(&MF_MT_FRAME_SIZE, u64::from(size.0) << 32 | u64::from(size.1))
            .map_err(|_| OPEN_FAILED)?;
        reader
            .SetCurrentMediaType(STREAM, None, &output)
            .map_err(|_| OPEN_FAILED)?;
        let current = reader.GetCurrentMediaType(STREAM).map_err(|_| OPEN_FAILED)?;
        let (width, height) = frame_size(&current).ok_or(OPEN_FAILED)?;
        Ok((Reader { reader, _source: source }, width, height))
    }
}

/// The size the camera will deliver when asked for `want` (blocking: opens the camera
/// briefly).
pub(crate) fn size(id: u64, want: (u32, u32)) -> Result<(u32, u32), &'static str> {
    on_thread("rustcord-camera-probe", move || {
        let _runtime = Runtime::open()?;
        // SAFETY: Media Foundation runs on this thread for the call.
        let (_reader, width, height) = unsafe { open(id, want) }?;
        Ok((width, height))
    })
}

/// Copy one sample into `data` as top-down, opaque BGRA rows of `width * 4` bytes.
///
/// # Safety
/// Media Foundation must be started on this thread.
unsafe fn copy(sample: &IMFSample, width: usize, height: usize, data: &mut Vec<u8>) -> bool {
    let row = width * 4;
    data.resize(row * height, 0);
    // SAFETY: Every row read stays inside the locked buffer (checked against its length,
    // or given by the 2D lock's own pitch for `height` rows).
    unsafe {
        let Ok(buffer) = sample.ConvertToContiguousBuffer() else { return false };
        // A picture smaller than the size this reader was opened at (the
        // camera changed format) has fewer rows than are copied below.
        if buffer.GetCurrentLength().map_or(true, |length| (length as usize) < row * height) {
            return false;
        }
        if let Ok(planar) = buffer.cast::<IMF2DBuffer>() {
            let mut first: *mut u8 = std::ptr::null_mut();
            let mut pitch = 0i32;
            if planar.Lock2D(&mut first, &mut pitch).is_ok() {
                let usable = !first.is_null() && pitch.unsigned_abs() as usize >= row;
                if usable {
                    for y in 0..height {
                        // (A negative pitch is a bottom-up picture: `first` is still its top row.)
                        let source = first.offset(y as isize * pitch as isize);
                        std::ptr::copy_nonoverlapping(source, data.as_mut_ptr().add(y * row), row);
                    }
                }
                let _ = planar.Unlock2D();
                if usable {
                    opaque(data);
                }
                return usable;
            }
        }
        let mut bytes: *mut u8 = std::ptr::null_mut();
        let mut length = 0u32;
        if buffer.Lock(&mut bytes, None, Some(&mut length)).is_err() {
            return false;
        }
        let usable = !bytes.is_null() && length as usize >= row * height;
        if usable {
            std::ptr::copy_nonoverlapping(bytes, data.as_mut_ptr(), row * height);
        }
        let _ = buffer.Unlock();
        if usable {
            opaque(data);
        }
        usable
    }
}

/// RGB32 leaves the fourth byte undefined; the preview treats it as alpha.
fn opaque(data: &mut [u8]) {
    for pixel in data.chunks_exact_mut(4) {
        pixel[3] = 255;
    }
}

/// A running camera. Dropping it stops reading and releases the device.
pub(crate) struct Camera {
    halt: Arc<AtomicBool>,
}
impl Drop for Camera {
    fn drop(&mut self) {
        self.halt.store(true, Ordering::Release);
    }
}

pub(crate) struct Outputs {
    pub frames: SyncSender<RawFrame>,
    pub recycle: Receiver<Vec<u8>>,
    /// Set when the camera fails or is unplugged.
    pub stop: Arc<AtomicBool>,
    /// A picture the encoder has not taken yet; newer ones are skipped meanwhile.
    pub pending: Arc<AtomicBool>,
    /// The worker's cancellation.
    pub cancel: Arc<AtomicBool>,
}

impl Camera {
    /// Open the camera and start reading. Returns once it is open (or failed to).
    pub(crate) fn start(id: u64, want: (u32, u32), outputs: Outputs) -> Result<Self, &'static str> {
        let halt = Arc::new(AtomicBool::new(false));
        let stopping = halt.clone();
        let (opened_send, opened) = std::sync::mpsc::sync_channel::<Result<(), &'static str>>(1);
        std::thread::Builder::new()
            .name("rustcord-camera".into())
            .spawn(move || {
                let runtime = Runtime::open();
                // SAFETY: Media Foundation runs on this thread until the end of the closure.
                let reader = runtime.as_ref().map_err(|e| *e).and_then(|_| unsafe { open(id, want) });
                let (reader, width, height) = match reader {
                    Ok(reader) => {
                        let _ = opened_send.send(Ok(()));
                        reader
                    }
                    Err(error) => {
                        let _ = opened_send.send(Err(error));
                        return;
                    }
                };
                let Outputs { frames, recycle, stop, pending, cancel } = outputs;
                let mut failures = 0u8;
                while !stopping.load(Ordering::Acquire) && !cancel.load(Ordering::Acquire) {
                    let mut flags = 0u32;
                    let mut sample: Option<IMFSample> = None;
                    // SAFETY: Out pointers are valid for the call; it blocks until the next picture.
                    let read = unsafe { reader.reader.ReadSample(STREAM, 0, None, Some(&mut flags), None, Some(&mut sample)) };
                    let ended = flags & (MF_SOURCE_READERF_ERROR.0 as u32 | MF_SOURCE_READERF_ENDOFSTREAM.0 as u32) != 0;
                    if read.is_err() || ended {
                        failures += 1;
                        if ended || failures >= 3 {
                            log::warn!("voice camera: {READ_FAILED}");
                            stop.store(true, Ordering::Release);
                            break;
                        }
                        continue;
                    }
                    failures = 0;
                    // The camera switched to another format (a virtual camera
                    // does, mid-stream): its pictures no longer have the size
                    // this reader was opened at.
                    if flags & (MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED.0 as u32 | MF_SOURCE_READERF_NATIVEMEDIATYPECHANGED.0 as u32) != 0 {
                        log::warn!("voice camera: the camera changed its format; stopping");
                        stop.store(true, Ordering::Release);
                        break;
                    }
                    let Some(sample) = sample else { continue };
                    if pending.swap(true, Ordering::AcqRel) {
                        continue;
                    }
                    let mut data = recycle.try_recv().unwrap_or_default();
                    // SAFETY: Media Foundation runs on this thread.
                    if !unsafe { copy(&sample, width as usize, height as usize, &mut data) } {
                        pending.store(false, Ordering::Release);
                        continue;
                    }
                    let frame = RawFrame { width, height, stride: width as usize * 4, data };
                    match frames.try_send(frame) {
                        Ok(()) => {}
                        Err(std::sync::mpsc::TrySendError::Full(_)) => pending.store(false, Ordering::Release),
                        Err(std::sync::mpsc::TrySendError::Disconnected(_)) => break,
                    }
                }
                drop(reader);
                drop(runtime);
            })
            .map_err(|_| UNAVAILABLE)?;
        opened
            .recv_timeout(std::time::Duration::from_secs(10))
            .map_err(|_| OPEN_FAILED)??;
        Ok(Self { halt })
    }
}