Skip to content

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

55.1 KB
Raw Blame
// Adapted from Serein (https://github.com/ViceVerse-cz/Serein) at commit a0e72cc,
// files `crates/discord-voice/src/screen.rs` and `crates/client-core/src/screen.rs`
// (`Settings`).
// 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: Windows only (macOS/Linux capture removed; other platforms report that
// sharing is unsupported); RustCord's quality presets and Discord-like bitrates; a
// downscaled (1280 wide), demand-driven preview instead of a full-size one; raw frame
// buffers recycled between capture and encoder; 5 s keyframe interval; statistics.
// Pacing, keyframe handling, bitrate adaptation and the encoder fallback follow Serein.
//! Explicitly selected, memory-only screen capture and H.264 encoding for Go Live.
use crate::{
    stats::{Counters, Engine},
    video_receive::{Publisher, VideoSink},
};
use std::sync::{
    Arc,
    atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering},
};

#[cfg(target_os = "windows")]
#[path = "screen/capture_windows.rs"]
mod capture;
#[cfg(target_os = "windows")]
#[path = "screen/camera_windows.rs"]
pub(crate) mod camera;
#[cfg(any(test, target_os = "windows"))]
#[path = "screen/convert.rs"]
mod convert;
#[cfg(target_os = "windows")]
#[path = "video_encode_windows.rs"]
mod hardware;

pub(crate) const MAX_RAW_BYTES: usize = 3840 * 2160 * 4;
pub(crate) const MAX_ENCODED_BYTES: usize = 2 * 1024 * 1024;
/// Widest local preview handed to the application: sharp on a large tile, yet a quarter of
/// a 1440p frame's pixels.
pub(crate) const PREVIEW_WIDTH: usize = 1280;
/// Seconds between periodic keyframes. Viewers that lose a picture or join late ask for
/// one (PLI); the periodic ones only bound recovery if such a request gets lost. Each IDR
/// costs many predicted frames' worth of bits, so they are kept rare (Serein used 2 s).
pub(crate) const KEYFRAME_SECONDS: u32 = 5;
/// The preview refreshes at most this often, and only while the application reads it.
const PREVIEW_INTERVAL: std::time::Duration = std::time::Duration::from_millis(66);
/// Longest system-audio chunk accepted from the OS: 100 ms of 48 kHz stereo.
pub(crate) const MAX_AUDIO_SAMPLES: usize = 4800 * 2;
pub(crate) const MAX_SHARE_WIDTH: u32 = 3840;
pub(crate) const MAX_SHARE_HEIGHT: u32 = 2160;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SourceId {
    Display(u64),
    Window(u64),
    /// RustCord: a webcam (see `screen/camera_windows.rs`).
    Camera(u64),
}
impl SourceId {
    pub fn encode(self) -> String {
        match self {
            Self::Display(id) => format!("display:{id}"),
            Self::Window(id) => format!("window:{id}"),
            Self::Camera(id) => format!("camera:{id}"),
        }
    }
    pub fn parse(text: &str) -> Option<Self> {
        let (kind, id) = text.split_once(':')?;
        let id = id.parse().ok().filter(|id| *id != 0)?;
        match kind {
            "display" => Some(Self::Display(id)),
            "window" => Some(Self::Window(id)),
            "camera" => Some(Self::Camera(id)),
            _ => None,
        }
    }
}

/// One shareable monitor or window as the platform reports it.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub(crate) struct NativeSource {
    pub id: SourceId,
    pub name: String,
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct Settings {
    pub source: SourceId,
    /// Encoded picture size; the source is scaled (letterboxed) into it.
    pub width: u32,
    pub height: u32,
    pub fps: u32,
    pub cursor: bool,
    /// Share system audio with the screen; call microphone settings are independent.
    pub audio: bool,
}
impl Settings {
    /// The encoded size for a source and a quality: at most `max_height` tall (0 keeps the
    /// source height), the source's aspect ratio, even dimensions, never above 4K.
    pub fn new(
        source: SourceId,
        (source_width, source_height): (u32, u32),
        quality: crate::StreamQuality,
        audio: bool,
    ) -> Result<Self, &'static str> {
        if source_width < 2 || source_height < 2 {
            return Err("Selected source dimensions are unavailable");
        }
        let (sw, sh) = (u64::from(source_width), u64::from(source_height));
        let mut height = if quality.max_height == 0 {
            sh
        } else {
            sh.min(u64::from(quality.max_height.max(2)))
        };
        let mut width = (sw * height + sh / 2) / sh;
        // Fit inside 3840x2160 (an ultrawide or 5K source at "source" quality).
        if width > u64::from(MAX_SHARE_WIDTH) {
            height = height * u64::from(MAX_SHARE_WIDTH) / width;
            width = u64::from(MAX_SHARE_WIDTH);
        }
        if height > u64::from(MAX_SHARE_HEIGHT) {
            width = width * u64::from(MAX_SHARE_HEIGHT) / height;
            height = u64::from(MAX_SHARE_HEIGHT);
        }
        let even = |value: u64| u32::try_from(value & !1).unwrap_or(0).max(2);
        let settings = Self {
            source,
            width: even(width),
            height: even(height),
            fps: match quality.fps {
                0..=22 => 15,
                23..=45 => 30,
                _ => 60,
            },
            cursor: true,
            audio,
        };
        if !settings.valid() {
            return Err("Screen sharing is unavailable for these settings");
        }
        Ok(settings)
    }

    pub fn valid(self) -> bool {
        !matches!(self.source, SourceId::Display(0) | SourceId::Window(0) | SourceId::Camera(0))
            && self.width >= 2
            && self.height >= 2
            && self.width <= MAX_SHARE_WIDTH
            && self.height <= MAX_SHARE_HEIGHT
            && self.width.is_multiple_of(2)
            && self.height.is_multiple_of(2)
            && matches!(self.fps, 15 | 30 | 60 | 90 | 120)
    }

    /// Discord-like targets. At 30 fps: 2.5 Mbit/s at 480p, 4 at 720p, 7 at 1080p, 10 at
    /// 1440p and 14 at 4K, interpolated by pixel count in between. Closer frames predict
    /// better, so 60 fps needs 1.5x (1080p60 10.5, 1440p60 15), not 2x; 15 fps 0.7x.
    /// Never above 20 Mbit/s (4K60).
    pub fn bit_rate(self) -> u32 {
        const POINTS: [(u64, u64); 5] = [
            (854 * 480, 2_500_000),
            (1280 * 720, 4_000_000),
            (1920 * 1080, 7_000_000),
            (2560 * 1440, 10_000_000),
            (3840 * 2160, 14_000_000),
        ];
        let pixels = u64::from(self.width) * u64::from(self.height);
        let (first_pixels, first_rate) = POINTS[0];
        let base = if pixels <= first_pixels {
            (first_rate * pixels / first_pixels).max(1_000_000)
        } else {
            POINTS
                .windows(2)
                .find(|pair| pixels <= pair[1].0)
                .map_or(POINTS[POINTS.len() - 1].1, |pair| {
                    let ((low, low_rate), (high, high_rate)) = (pair[0], pair[1]);
                    low_rate + (high_rate - low_rate) * (pixels - low) / (high - low)
                })
        };
        let scaled = match self.fps {
            0..=15 => base * 7 / 10,
            16..=30 => base,
            31..=60 => base * 3 / 2,
            61..=90 => base * 2,
            _ => base * 5 / 2,
        };
        u32::try_from(scaled.min(20_000_000)).unwrap_or(20_000_000)
    }
}

pub(crate) struct RawFrame {
    pub width: u32,
    pub height: u32,
    pub stride: usize,
    pub data: Vec<u8>,
}

pub(crate) struct EncodedFrame {
    pub data: Vec<u8>,
    pub timestamp: u32,
    pub keyframe: bool,
}

#[derive(Debug)]
pub(crate) struct AudioChunk {
    pub samples: Vec<f32>,
    /// Capture generation; old buffers must not cross an encryption transition.
    pub epoch: u64,
}

/// The transport's side of one share.
pub(crate) struct Video {
    pub settings: Settings,
    pub frames: tokio::sync::mpsc::Receiver<EncodedFrame>,
    pub ready: Arc<AtomicBool>,
    pub keyframe: Arc<AtomicBool>,
    /// Transport feedback target in bits per second, bounded by the selected quality.
    pub bitrate: Arc<AtomicU32>,
    /// Interleaved 48 kHz stereo system audio, present only when the share requested it.
    pub audio: Option<tokio::sync::mpsc::Receiver<AudioChunk>>,
    pub audio_epoch: Arc<AtomicU64>,
    /// Why capture ended, set before `frames` closes.
    pub failure: Arc<std::sync::OnceLock<&'static str>>,
    /// The share's statistics, also written by the capture/encode worker.
    pub stats: Arc<Counters>,
}

/// Monitors first, then windows.
pub(crate) fn sources() -> Result<Vec<NativeSource>, &'static str> {
    #[cfg(target_os = "windows")]
    return capture::sources();
    #[cfg(not(target_os = "windows"))]
    Err("Screen sharing is available on Windows only")
}

/// One still of a source, at most `max_width` wide, as RGBA.
pub(crate) fn thumbnail(id: SourceId, max_width: usize) -> Option<(usize, usize, Vec<u8>)> {
    #[cfg(target_os = "windows")]
    {
        // A fresh thread gives WinRT its own apartment whatever the caller's thread uses.
        let frame = std::thread::Builder::new()
            .name("rustcord-thumbnail".into())
            .spawn(move || capture::thumbnail(id))
            .ok()?
            .join()
            .ok()??;
        let (width, height) = preview_size(frame.width as usize, frame.height as usize, max_width);
        let mut rgba = vec![0; width * height * 4];
        downscale_bgra(&frame, width, height, &mut rgba).ok()?;
        Some((width, height, rgba))
    }
    #[cfg(not(target_os = "windows"))]
    {
        let _ = (id, max_width);
        None
    }
}

/// The source's current native size.
pub(crate) fn source_size(id: SourceId) -> Result<(u32, u32), &'static str> {
    #[cfg(target_os = "windows")]
    return capture::source_size(id);
    #[cfg(not(target_os = "windows"))]
    {
        let _ = id;
        Err("Screen sharing is available on Windows only")
    }
}

/// The capture/encode worker of one share. Dropping it stops capture.
pub(crate) struct Worker {
    stop: Arc<AtomicBool>,
    ready: Arc<AtomicBool>,
}

impl Worker {
    /// Start capturing. Previews go to `preview` (whose wake tells the application), one
    /// each time `preview_wanted` is set, at most every 66 ms.
    pub fn start(
        settings: Settings,
        preview: VideoSink,
        preview_wanted: Arc<AtomicBool>,
    ) -> Result<(Self, Video), &'static str> {
        if !settings.valid() || !cfg!(target_os = "windows") {
            return Err("Screen sharing is unavailable for these settings or this platform");
        }
        let stop = Arc::new(AtomicBool::new(false));
        let ready = Arc::new(AtomicBool::new(false));
        let audio_epoch = Arc::new(AtomicU64::new(0));
        let keyframe = Arc::new(AtomicBool::new(true));
        let bitrate = Arc::new(AtomicU32::new(settings.bit_rate()));
        let failure = Arc::new(std::sync::OnceLock::new());
        let stats = preview.stats.clone();
        stats.set_size(settings.width as usize, settings.height as usize);
        // A few frames of slack absorbs send jitter without forcing keyframes on every hiccup.
        let (send, frames) = tokio::sync::mpsc::channel(3);
        let (audio_send, audio) = if settings.audio {
            let (send, receive) = tokio::sync::mpsc::channel(4);
            (Some(send), Some(receive))
        } else {
            (None, None)
        };
        let shared = Shared {
            settings,
            stop: stop.clone(),
            ready: ready.clone(),
            keyframe: keyframe.clone(),
            bitrate: bitrate.clone(),
            audio_epoch: audio_epoch.clone(),
            preview,
            preview_wanted,
        };
        let worker_failure = failure.clone();
        std::thread::Builder::new()
            .name("rustcord-screen".into())
            .spawn(move || {
                // The MFT event poll and capture pacing sleep 1 ms at a time.
                let _resolution = crate::timer::Resolution::acquire();
                let result = encode_loop(&shared, &send, audio_send);
                shared.ready.store(false, Ordering::Release);
                if let Err(reason) = result {
                    let _ = worker_failure.set(reason);
                }
                // Closing the frame queue tells the transport capture ended.
                drop(send);
            })
            .map_err(|_| "Could not start screen capture worker")?;
        Ok((
            Self {
                stop,
                ready: ready.clone(),
            },
            Video {
                settings,
                frames,
                ready,
                keyframe,
                bitrate,
                audio,
                audio_epoch,
                failure,
                stats,
            },
        ))
    }

    pub fn stop(&self) {
        self.ready.store(false, Ordering::Release);
        self.stop.store(true, Ordering::Release);
    }
}

impl Drop for Worker {
    fn drop(&mut self) {
        self.stop();
    }
}

/// The worker thread's view of the share.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
struct Shared {
    settings: Settings,
    stop: Arc<AtomicBool>,
    ready: Arc<AtomicBool>,
    keyframe: Arc<AtomicBool>,
    bitrate: Arc<AtomicU32>,
    audio_epoch: Arc<AtomicU64>,
    preview: VideoSink,
    preview_wanted: Arc<AtomicBool>,
}

#[cfg(not(target_os = "windows"))]
fn encode_loop(
    _shared: &Shared,
    _send: &tokio::sync::mpsc::Sender<EncodedFrame>,
    _audio: Option<tokio::sync::mpsc::Sender<AudioChunk>>,
) -> Result<(), &'static str> {
    Err("Screen sharing is available on Windows only")
}

#[cfg(target_os = "windows")]
fn encode_loop(
    shared: &Shared,
    send: &tokio::sync::mpsc::Sender<EncodedFrame>,
    audio: Option<tokio::sync::mpsc::Sender<AudioChunk>>,
) -> Result<(), &'static str> {
    use std::sync::mpsc;
    use std::time::{Duration, Instant};
    let Shared {
        settings,
        stop,
        ready,
        keyframe,
        bitrate,
        audio_epoch,
        preview,
        preview_wanted,
    } = shared;
    let settings = *settings;
    if stop.load(Ordering::Acquire) || send.is_closed() {
        return Ok(());
    }
    let origin = Instant::now();
    let (raw_send, raw) = mpsc::sync_channel(1);
    let (recycle_send, recycle) = mpsc::sync_channel::<Vec<u8>>(2);
    let capture_stop = Arc::new(AtomicBool::new(false));
    let raw_pending = Arc::new(AtomicBool::new(false));
    // (Kept alive for the loop: dropping either stops its capture.)
    let (_camera, _native) = match settings.source {
        SourceId::Camera(id) => (
            Some(camera::Camera::start(
                id,
                (settings.width, settings.height),
                camera::Outputs {
                    frames: raw_send,
                    recycle,
                    stop: capture_stop.clone(),
                    pending: raw_pending.clone(),
                    cancel: stop.clone(),
                },
            )?),
            None,
        ),
        _ => (
            None,
            Some(capture::Capture::start(
                settings,
                capture::Outputs {
                    frames: raw_send,
                    recycle,
                    audio,
                    stop: capture_stop.clone(),
                    ready: ready.clone(),
                    audio_epoch: audio_epoch.clone(),
                    pending: raw_pending.clone(),
                    cancel: stop.clone(),
                },
            )?),
        ),
    };
    let mut encoding: Option<ScreenEncoder> = None;
    let mut first_frame_deadline = Some(Instant::now() + Duration::from_secs(15));
    let mut next_frame = Instant::now();
    let mut latest_frame: Option<RawFrame> = None;
    let mut publisher = Publisher::new(preview.clone());
    let mut last_preview: Option<Instant> = None;

    while !stop.load(Ordering::Acquire) && !send.is_closed() {
        if capture_stop.load(Ordering::Acquire) {
            return Err(if matches!(settings.source, SourceId::Camera(_)) {
                "The camera stopped; it may have been unplugged"
            } else {
                "The selected screen or window stopped sharing"
            });
        }
        let frame = match raw.recv_timeout(Duration::from_millis(100)) {
            Ok(frame) => {
                raw_pending.store(false, Ordering::Release);
                Some(frame)
            }
            Err(_) if stop.load(Ordering::Acquire) || send.is_closed() => break,
            Err(mpsc::RecvTimeoutError::Timeout)
                if first_frame_deadline.is_none_or(|deadline| Instant::now() < deadline) =>
            {
                None
            }
            Err(_) => {
                return Err(
                    "No screen frames received; check the selected source and screen recording permission",
                );
            }
        };
        if stop.load(Ordering::Acquire) || send.is_closed() {
            break;
        }
        let now = Instant::now();
        if let Some(frame) = &frame {
            first_frame_deadline = None;
            if last_preview.is_none_or(|at| now.duration_since(at) >= PREVIEW_INTERVAL)
                && preview_wanted.swap(false, Ordering::AcqRel)
            {
                last_preview = Some(now);
                let (width, height) =
                    preview_size(frame.width as usize, frame.height as usize, PREVIEW_WIDTH);
                let mut result = Ok(());
                publisher.publish(width, height, |out| {
                    result = downscale_bgra(frame, width, height, out);
                })?;
                result?;
            }
        }
        let previous = latest_frame.take();
        let encode = retain_screen_frame(
            &mut latest_frame,
            previous,
            frame,
            ready.load(Ordering::Acquire),
            keyframe.load(Ordering::Acquire),
            &recycle_send,
        )?;
        // Local capture remains available while alone; only secure media is encoded or queued.
        if !ready.load(Ordering::Acquire) {
            encoding = None;
            keyframe.store(true, Ordering::Release);
            continue;
        }
        if !encode {
            continue;
        }
        // Pace on an accumulating schedule with a little tolerance: capture timing jitter must
        // not skip every other frame, and a stalled encoder resumes from now instead of bursting.
        let interval = Duration::from_secs_f64(1.0 / f64::from(settings.fps));
        if now + Duration::from_millis(2) < next_frame {
            continue;
        }
        next_frame = (next_frame + interval).max(now + interval / 2);
        // Drop before encoding while the transport is behind, so the encoder never references
        // a picture the receiver did not get.
        if send.capacity() == 0 {
            preview.stats.dropped(1);
            continue;
        }
        let target = bitrate
            .load(Ordering::Acquire)
            .clamp(250_000, settings.bit_rate());
        if encoding.is_none() {
            encoding = Some(ScreenEncoder::new(settings, target)?);
        }
        let encoder = encoding.as_mut().expect("secure screen encoder");
        if encoder.set_bitrate(target)? {
            keyframe.store(true, Ordering::Release);
        }
        // Retain one current source snapshot, never encoded media, for a viewer's keyframe
        // request on an unchanged desktop.
        let force_keyframe = keyframe.swap(false, Ordering::AcqRel);
        let (data, is_keyframe) = encoder.encode(
            latest_frame.as_ref().expect("latest screen frame"),
            force_keyframe,
        )?;
        preview.stats.set_engine(encoder.engine());
        if force_keyframe && (data.is_empty() || !is_keyframe) {
            keyframe.store(true, Ordering::Release);
        }
        if data.is_empty() {
            preview.stats.dropped(1);
            continue;
        }
        if !ready.load(Ordering::Acquire) || stop.load(Ordering::Acquire) {
            continue;
        }
        let frame = EncodedFrame {
            data,
            timestamp: (origin.elapsed().as_micros() * 90 / 1000) as u32,
            keyframe: is_keyframe,
        };
        if send.try_send(frame).is_err() {
            preview.stats.dropped(1);
            keyframe.store(true, Ordering::Release);
        }
    }
    capture_stop.store(true, Ordering::Release);
    Ok(())
}

/// Keep the newest captured picture (returning the replaced buffer to capture) and decide
/// whether to encode now: fresh pictures always, the retained one for a keyframe request.
fn retain_screen_frame(
    latest: &mut Option<RawFrame>,
    previous: Option<RawFrame>,
    frame: Option<RawFrame>,
    ready: bool,
    keyframe: bool,
    recycle: &std::sync::mpsc::SyncSender<Vec<u8>>,
) -> Result<bool, &'static str> {
    let fresh = frame.is_some();
    match frame {
        Some(frame) => {
            if let Err(error) = validate_frame(&frame) {
                *latest = previous;
                return Err(error);
            }
            if let Some(previous) = previous {
                let _ = recycle.try_send(previous.data);
            }
            *latest = Some(frame);
        }
        None => *latest = previous,
    }
    Ok(ready && latest.is_some() && (fresh || keyframe))
}

/// Screen encoder preferring the Media Foundation hardware H.264 encoder and falling back
/// to OpenH264 when it is unavailable or fails mid-stream.
#[cfg(target_os = "windows")]
struct ScreenEncoder {
    software: Option<openh264::encoder::Encoder>,
    /// Reused I420 picture for OpenH264.
    i420: Vec<u8>,
    hardware: Option<hardware::Encoder>,
    settings: Settings,
    bitrate: u32,
    /// The previous picture was dropped after encoding: the next one must be a keyframe.
    restart: bool,
}

#[cfg(target_os = "windows")]
impl ScreenEncoder {
    fn new(settings: Settings, bitrate: u32) -> Result<Self, &'static str> {
        let config = hardware::Config {
            width: settings.width,
            height: settings.height,
            fps: settings.fps,
            bit_rate: bitrate,
            max_bytes: MAX_ENCODED_BYTES,
            keyframe_interval: settings.fps * KEYFRAME_SECONDS,
        };
        let hardware = crate::settings::video_hardware_acceleration()
            .then(|| hardware::Encoder::new(config).ok())
            .flatten();
        let software = if hardware.is_none() {
            Some(encoder(settings, bitrate)?)
        } else {
            None
        };
        Ok(Self {
            software,
            i420: Vec::new(),
            hardware,
            settings,
            bitrate,
            restart: false,
        })
    }

    fn set_bitrate(&mut self, bitrate: u32) -> Result<bool, &'static str> {
        if self.bitrate == bitrate {
            return Ok(false);
        }
        if self
            .hardware
            .as_mut()
            .is_some_and(|encoder| encoder.set_bitrate(bitrate).is_ok())
        {
            self.bitrate = bitrate;
            return Ok(false);
        }
        if self.hardware.is_none() {
            // OpenH264 exposes no safe runtime bitrate setter, and a restart costs an IDR:
            // follow only large moves so gradual recovery cannot cause a keyframe per second.
            if !software_rate_change(self.bitrate, bitrate) {
                return Ok(false);
            }
            self.software = Some(encoder(self.settings, bitrate)?);
            self.bitrate = bitrate;
        } else {
            // Reopen native encoders that refuse a live rate change at the target rate.
            // Release scarce hardware sessions before requesting their replacement.
            self.hardware = None;
            *self = Self::new(self.settings, bitrate)?;
        }
        Ok(true)
    }

    fn engine(&self) -> Engine {
        if self.hardware.is_some() {
            Engine::MediaFoundationHardware
        } else {
            Engine::OpenH264
        }
    }

    fn encode(
        &mut self,
        frame: &RawFrame,
        force_keyframe: bool,
    ) -> Result<(Vec<u8>, bool), &'static str> {
        let (width, height) = (self.settings.width as usize, self.settings.height as usize);
        let force_keyframe = force_keyframe || self.restart;
        let mut software_force = force_keyframe;
        if let Some(hardware) = self.hardware.as_mut() {
            let encoded = hardware.encode_with(width * height * 3 / 2, force_keyframe, |picture| {
                convert::bgra_to_yuv420(frame, width, height, convert::Chroma::Interleaved, picture)
            });
            match encoded {
                Ok(encoded) => {
                    self.restart = false;
                    return Ok(encoded);
                }
                // One picture over the transport limit is dropped, not a broken encoder.
                // Later pictures would reference it, so the next one is a keyframe.
                Err(hardware::OVERSIZED) => {
                    self.restart = true;
                    return Ok((Vec::new(), false));
                }
                Err(_) => {}
            }
            // The viewer must restart from a keyframe once the software encoder takes over.
            self.hardware = None;
            self.software = Some(encoder(self.settings, self.bitrate)?);
            software_force = true;
        }
        self.i420.resize(width * height * 3 / 2, 0);
        convert::bgra_to_yuv420(
            frame,
            width,
            height,
            convert::Chroma::Planar,
            &mut self.i420,
        )?;
        let (y, chroma) = self.i420.split_at(width * height);
        let (u, v) = chroma.split_at(width * height / 4);
        encode_yuv(
            self.software.as_mut().expect("software screen encoder"),
            &openh264::formats::YUVSlices::new(
                (y, u, v),
                (width, height),
                (width, width / 2, width / 2),
            ),
            software_force,
        )
    }
}

/// Whether a software encoder should restart for a new transport target.
pub(crate) fn software_rate_change(current: u32, target: u32) -> bool {
    // Always honor congestion cuts of at least 15%; grow in 25% steps.
    u64::from(target) * 100 <= u64::from(current) * 85
        || u64::from(target) * 100 >= u64::from(current) * 125
}

#[cfg(test)]
pub(crate) fn i420_to_nv12(
    y: &[u8],
    u: &[u8],
    v: &[u8],
    output: &mut [u8],
) -> Result<(), &'static str> {
    if u.len() != v.len() || y.len() != u.len() * 4 || output.len() != y.len() + u.len() + v.len() {
        return Err("Invalid screen encoder color planes");
    }
    output[..y.len()].copy_from_slice(y);
    for (pair, (&u, &v)) in output[y.len()..]
        .as_chunks_mut::<2>()
        .0
        .iter_mut()
        .zip(u.iter().zip(v))
    {
        pair.copy_from_slice(&[u, v]);
    }
    Ok(())
}

pub(crate) fn encoder(
    settings: Settings,
    bitrate: u32,
) -> Result<openh264::encoder::Encoder, &'static str> {
    use openh264::{
        OpenH264API,
        encoder::{
            BitRate, Complexity, Encoder, EncoderConfig, FrameRate, IntraFramePeriod,
            RateControlMode, UsageType,
        },
    };
    let config = EncoderConfig::new()
        .bitrate(BitRate::from_bps(
            bitrate.clamp(250_000, settings.bit_rate()),
        ))
        .max_frame_rate(FrameRate::from_hz(settings.fps as f32))
        .usage_type(UsageType::ScreenContentRealTime)
        .rate_control_mode(RateControlMode::Bitrate)
        .complexity(Complexity::Low)
        .num_threads(encoder_threads())
        .intra_frame_period(IntraFramePeriod::from_num_frames(
            settings.fps * KEYFRAME_SECONDS,
        ));
    Encoder::with_api_config(OpenH264API::from_source(), config)
        .map_err(|_| "Screen video encoder is unavailable")
}

fn encoder_threads() -> u16 {
    std::thread::available_parallelism().map_or(2, |count| count.get().clamp(2, 8) as u16)
}

fn encode_yuv(
    encoder: &mut openh264::encoder::Encoder,
    yuv: &impl openh264::formats::YUVSource,
    force_keyframe: bool,
) -> Result<(Vec<u8>, bool), &'static str> {
    if force_keyframe {
        encoder.force_intra_frame();
    }
    let encoded = encoder
        .encode(yuv)
        .map_err(|_| "Screen video encoding failed")?;
    let is_keyframe = matches!(encoded.frame_type(), openh264::encoder::FrameType::IDR);
    let mut encoded_len = 0usize;
    for layer_index in 0..encoded.num_layers() {
        let layer = encoded
            .layer(layer_index)
            .ok_or("Screen video encoder returned an invalid layer")?;
        for nal_index in 0..layer.nal_count() {
            encoded_len = encoded_len
                .checked_add(
                    layer
                        .nal_unit(nal_index)
                        .ok_or("Screen video encoder returned an invalid NAL")?
                        .len(),
                )
                .filter(|length| *length <= MAX_ENCODED_BYTES)
                .ok_or("Encoded screen frame exceeds the sharing limit; choose a lower quality")?;
        }
    }
    let mut data = Vec::with_capacity(encoded_len);
    encoded.write_vec(&mut data);
    Ok((data, is_keyframe))
}

fn validate_frame(frame: &RawFrame) -> Result<(usize, usize), &'static str> {
    let row_bytes = (frame.width as usize)
        .checked_mul(4)
        .ok_or("Screen capture returned an unsupported frame size")?;
    let required = frame
        .stride
        .checked_mul(frame.height as usize)
        .ok_or("Screen capture returned an unsupported frame size")?;
    if frame.width == 0
        || frame.height == 0
        || frame.width > 3840
        || frame.height > 2160
        || frame.data.len() > MAX_RAW_BYTES
        || frame.stride < row_bytes
        || required > frame.data.len()
    {
        return Err("Screen capture returned an unsupported frame size");
    }

    Ok((row_bytes, required))
}

/// A preview size at most `max_width` wide with the source's aspect ratio.
pub(crate) fn preview_size(width: usize, height: usize, max_width: usize) -> (usize, usize) {
    let max_width = max_width.max(1);
    if width <= max_width {
        return (width.max(1), height.max(1));
    }
    (max_width, ((height * max_width + width / 2) / width).max(1))
}

/// Scale a BGRA capture into RGBA (opaque), averaging a 2x2 tap footprint per pixel, in
/// parallel row bands (a 1280-wide preview of a 1440p capture is ~1M pixels).
pub(crate) fn downscale_bgra(
    frame: &RawFrame,
    width: usize,
    height: usize,
    out: &mut [u8],
) -> Result<(), &'static str> {
    validate_frame(frame)?;
    if width == 0 || height == 0 || out.len() != width * height * 4 {
        return Err("Invalid screen preview size");
    }
    let (source_width, source_height) = (frame.width as usize, frame.height as usize);
    // Half a destination pixel apart, so a 4:1 reduction still averages spread-out samples.
    let step_x = (source_width / width / 2).min(source_width - 1);
    let step_y = (source_height / height / 2).min(source_height - 1);
    crate::video_rgba::for_each_band(out, width * 4, width * height, |first, rows| {
        for (index, line) in rows.chunks_exact_mut(width * 4).enumerate() {
            let y = first + index;
            let top = (y * source_height / height).min(source_height - 1);
            let bottom = (top + step_y).min(source_height - 1);
            let (top, bottom) = (
                &frame.data[top * frame.stride..],
                &frame.data[bottom * frame.stride..],
            );
            for (x, pixel) in line.chunks_exact_mut(4).enumerate() {
                let left = (x * source_width / width).min(source_width - 1);
                let right = (left + step_x).min(source_width - 1);
                let (left, right) = (left * 4, right * 4);
                for (channel, byte) in [2usize, 1, 0].into_iter().enumerate() {
                    let sum = u16::from(top[left + byte])
                        + u16::from(top[right + byte])
                        + u16::from(bottom[left + byte])
                        + u16::from(bottom[right + byte]);
                    pixel[channel] = ((sum + 2) / 4) as u8;
                }
                pixel[3] = 255;
            }
        }
    });
    Ok(())
}

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

    fn quality(max_height: u32, fps: u32) -> crate::StreamQuality {
        crate::StreamQuality { max_height, fps }
    }

    #[test]
    fn quality_presets_keep_aspect_ratio_even_sizes_and_serein_bitrates() {
        let source = SourceId::Display(7);
        let hd = Settings::new(source, (1920, 1080), quality(720, 30), false).unwrap();
        assert_eq!((hd.width, hd.height, hd.fps), (1280, 720, 30));
        assert_eq!(hd.bit_rate(), 4_000_000);
        let full = Settings::new(source, (2560, 1440), quality(1080, 60), true).unwrap();
        assert_eq!((full.width, full.height, full.fps), (1920, 1080, 60));
        assert_eq!(full.bit_rate(), 10_500_000);
        // Discord-like targets across the presets, 1440p included.
        let qhd = Settings::new(source, (2560, 1440), quality(1440, 60), false).unwrap();
        assert_eq!((qhd.width, qhd.height, qhd.bit_rate()), (2560, 1440, 15_000_000));
        let qhd30 = Settings::new(source, (3840, 2160), quality(1440, 30), false).unwrap();
        assert_eq!((qhd30.width, qhd30.height, qhd30.bit_rate()), (2560, 1440, 10_000_000));
        for (size, fps, expected) in [
            ((1920, 1080), 30, 7_000_000),
            ((1280, 720), 60, 6_000_000),
            ((1280, 720), 15, 2_800_000),
            ((3840, 2160), 30, 14_000_000),
            ((3840, 2160), 60, 20_000_000),
            ((640, 360), 30, 1_405_152),
            ((320, 180), 30, 1_000_000),
        ] {
            let settings = Settings::new(source, size, quality(0, fps), false).unwrap();
            assert_eq!(settings.bit_rate(), expected, "{size:?}@{fps}");
        }
        // Monotonic in size between the anchor points.
        let mid = Settings::new(source, (2240, 1260), quality(0, 30), false).unwrap();
        assert!((7_000_001..10_000_000).contains(&mid.bit_rate()));
        let ultrawide = Settings::new(source, (3440, 1440), quality(720, 15), false).unwrap();
        assert_eq!(
            (ultrawide.width, ultrawide.height, ultrawide.fps),
            (1720, 720, 15)
        );
        // A small window is never upscaled; odd sizes become even.
        let window =
            Settings::new(SourceId::Window(9), (801, 601), quality(1080, 30), false).unwrap();
        assert_eq!((window.width, window.height), (800, 600));
        // "Source" keeps the native size, capped at 4K.
        let native = Settings::new(source, (5120, 2880), quality(0, 30), false).unwrap();
        assert_eq!((native.width, native.height), (3840, 2160));
        let super_wide = Settings::new(source, (7680, 2160), quality(0, 30), false).unwrap();
        assert_eq!((super_wide.width, super_wide.height), (3840, 1080));
        assert!(Settings::new(source, (1, 1), quality(720, 30), false).is_err());
        assert!(Settings::new(SourceId::Window(0), (1280, 720), quality(720, 30), false).is_err());
    }

    #[test]
    fn source_ids_round_trip_and_reject_garbage() {
        for id in [SourceId::Display(42), SourceId::Window(u64::MAX)] {
            assert_eq!(SourceId::parse(&id.encode()), Some(id));
        }
        for bad in ["", "display", "display:", "display:0", "window:x", "tab:3"] {
            assert_eq!(SourceId::parse(bad), None, "{bad}");
        }
    }

    #[test]
    fn idle_screen_keyframe_uses_latest_snapshot_only_when_ready() {
        let frame = |value| RawFrame {
            width: 2,
            height: 2,
            stride: 8,
            data: vec![value; 16],
        };
        let (recycle, returned) = std::sync::mpsc::sync_channel(2);
        let mut latest = None;
        let step = |latest: &mut Option<RawFrame>, frame, ready, keyframe| {
            let previous = latest.take();
            retain_screen_frame(latest, previous, frame, ready, keyframe, &recycle)
        };
        assert!(!step(&mut latest, None, true, true).unwrap());
        assert!(step(&mut latest, Some(frame(1)), true, false).unwrap());
        assert!(!step(&mut latest, None, true, false).unwrap());
        assert!(step(&mut latest, None, true, true).unwrap());
        // A security pause keeps tracking the source without encoding. Its newest snapshot
        // can be freshly encoded after readiness, even if no further capture event arrives.
        assert!(!step(&mut latest, Some(frame(2)), false, true).unwrap());
        assert_eq!(
            returned.try_recv().unwrap(),
            vec![1; 16],
            "replaced buffer reused"
        );
        assert!(!step(&mut latest, None, false, true).unwrap());
        assert!(step(&mut latest, None, true, true).unwrap());
        assert_eq!(latest.as_ref().unwrap().data, vec![2; 16]);
        let mut oversized = frame(3);
        oversized.width = 3841;
        assert!(step(&mut latest, Some(oversized), true, true).is_err());
        assert_eq!(latest.unwrap().data, vec![2; 16]);
    }

    #[test]
    fn preview_is_bounded_and_converts_padded_bgra() {
        let frame = RawFrame {
            width: 1,
            height: 2,
            stride: 8,
            data: vec![1, 2, 3, 0, 9, 9, 9, 9, 4, 5, 6, 0, 9, 9, 9, 9],
        };
        let mut out = [0; 8];
        downscale_bgra(&frame, 1, 2, &mut out).unwrap();
        assert_eq!(out, [3, 2, 1, 255, 6, 5, 4, 255]);
        assert_eq!(preview_size(3840, 2160, 640), (640, 360));
        assert_eq!(preview_size(320, 200, 640), (320, 200));
        assert_eq!(preview_size(2560, 1440, PREVIEW_WIDTH), (1280, 720));
        // A 4:1 reduction averages its taps.
        let wide = RawFrame {
            width: 4,
            height: 1,
            stride: 16,
            data: vec![0, 0, 0, 0, 0, 0, 0, 0, 200, 200, 200, 0, 200, 200, 200, 0],
        };
        let mut out = [0; 4];
        downscale_bgra(&wide, 1, 1, &mut out).unwrap();
        assert_eq!(out, [100, 100, 100, 255]);
        assert!(
            downscale_bgra(
                &RawFrame {
                    width: 2,
                    height: 2,
                    stride: 4,
                    data: vec![0; 8],
                },
                1,
                1,
                &mut out
            )
            .is_err()
        );
    }

    #[test]
    fn synthetic_frame_encodes_a_bounded_keyframe() {
        let settings =
            Settings::new(SourceId::Display(1), (1280, 720), quality(720, 30), false).unwrap();
        let frame = RawFrame {
            width: 64,
            height: 36,
            stride: 64 * 4 + 12,
            data: vec![255; (64 * 4 + 12) * 36],
        };
        let mut encoder = encoder(settings, settings.bit_rate()).unwrap();
        let (width, height) = (1280, 720);
        let mut i420 = vec![0; width * height * 3 / 2];
        convert::bgra_to_yuv420(&frame, width, height, convert::Chroma::Planar, &mut i420).unwrap();
        let (y, chroma) = i420.split_at(width * height);
        let (u, v) = chroma.split_at(width * height / 4);
        let (encoded, keyframe) = encode_yuv(
            &mut encoder,
            &openh264::formats::YUVSlices::new(
                (y, u, v),
                (width, height),
                (width, width / 2, width / 2),
            ),
            true,
        )
        .unwrap();
        assert!(keyframe);
        assert!(!encoded.is_empty() && encoded.len() <= MAX_ENCODED_BYTES);
        assert!(crate::video_codec::is_keyframe(&encoded));
        assert!(software_rate_change(4_000_000, 3_400_000));
        assert!(!software_rate_change(4_000_000, 3_500_000));
        assert!(software_rate_change(4_000_000, 5_000_000));
    }

    #[test]
    fn interleaves_i420_chroma_for_windows_nv12() {
        let mut nv12 = [0; 12];
        i420_to_nv12(&[1, 2, 3, 4, 5, 6, 7, 8], &[9, 10], &[11, 12], &mut nv12).unwrap();
        assert_eq!(nv12, [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 10, 12]);
        assert!(i420_to_nv12(&[0; 4], &[0; 2], &[0; 2], &mut [0; 8]).is_err());
    }

    /// The real encoder path (Media Foundation where the GPU offers it, else OpenH264) on a
    /// synthetic picture: no capture, window or network.
    #[cfg(target_os = "windows")]
    #[test]
    fn screen_encoder_produces_bounded_h264_keyframes_on_request() {
        let settings =
            Settings::new(SourceId::Display(1), (1920, 1080), quality(720, 30), false).unwrap();
        let mut encoder = ScreenEncoder::new(settings, settings.bit_rate()).unwrap();
        eprintln!(
            "Media Foundation hardware encoder: {}",
            encoder.hardware.is_some()
        );
        let mut data = vec![0u8; 1920 * 4 * 1080];
        for (index, pixel) in data.chunks_exact_mut(4).enumerate() {
            pixel.copy_from_slice(&[(index % 251) as u8, (index / 1920 % 255) as u8, 90, 255]);
        }
        let frame = RawFrame {
            width: 1920,
            height: 1080,
            stride: 1920 * 4,
            data,
        };
        let mut keyframes = 0;
        for index in 0..6 {
            let (encoded, keyframe) = encoder.encode(&frame, index == 0 || index == 4).unwrap();
            if encoded.is_empty() {
                continue;
            }
            assert!(encoded.len() <= MAX_ENCODED_BYTES);
            assert_eq!(keyframe, crate::video_codec::is_keyframe(&encoded));
            if keyframe {
                keyframes += 1;
                assert!(crate::video_codec::has_parameter_sets(&encoded));
                // The SPS rewrite DAVE relies on accepts what this encoder produces, and the
                // viewer's decoder reads it at the stream size.
                let normalized = crate::video_sps::normalize(&encoded).unwrap();
                let mut decoder = openh264::decoder::Decoder::new().unwrap();
                let picture = decoder.decode(&normalized).unwrap().unwrap();
                use openh264::formats::YUVSource;
                assert_eq!(picture.dimensions(), (1280, 720));
            }
        }
        assert!(keyframes >= 1, "a requested keyframe never arrived");
        // A large bitrate change is applied (hardware live, software by restarting).
        encoder.set_bitrate(1_000_000).unwrap();
        assert!(!encoder.encode(&frame, true).unwrap().0.is_empty() || encoder.hardware.is_some());
    }

    /// Synthetic 1440p screen content: a scrolling page of glyph-like 1-px detail, a
    /// playing "video" tile and a moving window, so both intra and inter coding work hard.
    #[cfg(target_os = "windows")]
    fn draw_screen(data: &mut [u8], width: usize, height: usize, index: usize) {
        let hash = |mut value: u32| {
            value ^= value >> 16;
            value = value.wrapping_mul(0x7feb_352d);
            value ^= value >> 15;
            value = value.wrapping_mul(0x846c_a68b);
            value ^ (value >> 16)
        };
        let scroll = index * 3;
        let window = (200 + index * 9 % 900, 900 + index * 5 % 300);
        for (y, row) in data.chunks_exact_mut(width * 4).take(height).enumerate() {
            for (x, pixel) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() {
                let mut bgr = [240u8, 240, 240];
                if (60..1700).contains(&x) && (60..1380).contains(&y) {
                    // Text: 8x16 cells, 7x12 glyphs, ~1/6 spaces, stable as it scrolls.
                    let doc = (y - 60 + scroll) as u32;
                    let (line, cell_y) = (doc / 16, doc % 16);
                    let (column, cell_x) = ((x - 60) as u32 / 8, (x - 60) as u32 % 8);
                    let glyph = hash(line * 4099 + column);
                    if cell_y < 12
                        && cell_x < 7
                        && glyph % 6 != 0
                        && hash(glyph ^ (cell_y * 8 + cell_x)) & 3 == 0
                    {
                        bgr = [30, 30, 30];
                    }
                } else if (1800..2440).contains(&x) && (120..480).contains(&y) {
                    // A video tile: smooth moving colour.
                    let t = index as u32 * 4;
                    bgr = [
                        ((x as u32 + t) % 256) as u8,
                        ((y as u32 * 2 + t) % 256) as u8,
                        (((x + y) as u32 + t * 2) % 256) as u8,
                    ];
                }
                if (window.0..window.0 + 600).contains(&x) && (window.1..window.1 + 340).contains(&y)
                {
                    bgr = if y < window.1 + 30 { [200, 120, 40] } else { [250, 250, 250] };
                }
                *pixel = [bgr[0], bgr[1], bgr[2], 255];
            }
        }
    }

    /// Serein's (pre-change) scalar I420 downscale to 1920 wide, kept here as the baseline.
    #[cfg(target_os = "windows")]
    fn old_scale_i420(
        planes: &crate::video_rgba::Planes<'_>,
        (width, height): (usize, usize),
        out: &mut [u8],
    ) {
        let crate::video_rgba::Chroma::Planar {
            u, v, u_stride, v_stride,
        } = &planes.chroma
        else {
            panic!("OpenH264 pictures are I420");
        };
        let (source_width, source_height) = (planes.width, planes.height);
        let columns: Vec<usize> =
            (0..width).map(|x| (x * source_width / width).min(source_width - 1)).collect();
        for (row, line) in out.chunks_exact_mut(width * 4).take(height).enumerate() {
            let sy = (row * source_height / height).min(source_height - 1);
            let sy2 = (sy + 1).min(source_height - 1);
            let (top, bottom) = (&planes.y[sy * planes.y_stride..], &planes.y[sy2 * planes.y_stride..]);
            let (u_row, v_row) = (&u[(sy / 2) * u_stride..], &v[(sy / 2) * v_stride..]);
            for (pixel, &sx) in line.chunks_exact_mut(4).zip(columns.iter()) {
                let sx2 = (sx + 1).min(source_width - 1);
                let luma = (u16::from(top[sx])
                    + u16::from(top[sx2])
                    + u16::from(bottom[sx])
                    + u16::from(bottom[sx2])
                    + 2)
                    / 4;
                let [r, g, b] = crate::video_rgba::rgb(luma as u8, u_row[sx / 2], v_row[sx / 2]);
                pixel.copy_from_slice(&[r, g, b, 255]);
            }
        }
    }

    /// Go Live 1440p60 benchmark (run by hand, in release):
    /// `cargo test -p voice --lib --release -- --ignored --nocapture go_live_1440p`
    /// Encodes synthetic screen content with the real share encoder, then decodes the
    /// stream with each decoder and converts it for display, reporting ms per frame.
    #[cfg(target_os = "windows")]
    #[test]
    #[ignore]
    fn go_live_1440p_encode_decode_benchmark() {
        use crate::video_rgba::{Planes, to_rgba};
        use std::time::{Duration, Instant};
        const FRAMES: usize = 120;
        let (width, height) = (2560usize, 1440usize);
        let settings =
            Settings::new(SourceId::Display(1), (2560, 1440), quality(1440, 60), false).unwrap();
        let mut frame = RawFrame {
            width: 2560,
            height: 1440,
            stride: width * 4,
            data: vec![0; width * height * 4],
        };
        // Sender side: capture-format conversion, preview, encoding.
        let mut encoder = ScreenEncoder::new(settings, settings.bit_rate()).unwrap();
        eprintln!(
            "encoder: {} at {} kbit/s, {}x{}@{}",
            encoder.engine().name(),
            settings.bit_rate() / 1000,
            settings.width,
            settings.height,
            settings.fps
        );
        let mut stream = Vec::new();
        let (mut encode_time, mut nv12_time, mut preview_time) =
            (Duration::ZERO, Duration::ZERO, Duration::ZERO);
        let mut nv12 = vec![0; width * height * 3 / 2];
        let (preview_width, preview_height) = preview_size(width, height, PREVIEW_WIDTH);
        let mut preview = vec![0; preview_width * preview_height * 4];
        for index in 0..FRAMES {
            draw_screen(&mut frame.data, width, height, index);
            let started = Instant::now();
            convert::bgra_to_yuv420(&frame, width, height, convert::Chroma::Interleaved, &mut nv12)
                .unwrap();
            nv12_time += started.elapsed();
            let started = Instant::now();
            downscale_bgra(&frame, preview_width, preview_height, &mut preview).unwrap();
            preview_time += started.elapsed();
            let started = Instant::now();
            let (data, keyframe) = encoder.encode(&frame, index == 0).unwrap();
            encode_time += started.elapsed();
            if !data.is_empty() {
                stream.push((data, keyframe));
            }
        }
        let bytes: usize = stream.iter().map(|(data, _)| data.len()).sum();
        eprintln!(
            "sender: BGRA->NV12 {:.2} ms, 1280 preview {:.2} ms, encode (incl. NV12) {:.2} ms per frame; {} pictures, keyframe {} kB, average {:.1} Mbit/s at 60 fps",
            nv12_time.as_secs_f64() * 1000.0 / FRAMES as f64,
            preview_time.as_secs_f64() * 1000.0 / FRAMES as f64,
            encode_time.as_secs_f64() * 1000.0 / FRAMES as f64,
            stream.len(),
            stream[0].0.len() / 1000,
            bytes as f64 * 8.0 * 60.0 / stream.len() as f64 / 1e6
        );
        assert!(stream[0].1, "the first picture is a keyframe");

        type Deliver<'a> = dyn FnMut(&Planes<'_>) -> Result<(), &'static str> + 'a;
        type Decode<'a> =
            dyn FnMut(&[u8], bool, &mut Deliver<'_>) -> Result<(), &'static str> + 'a;
        /// Decode the whole stream; conversion runs inside the decoder's callback. Returns
        /// the last picture's full-size RGBA for a cross-decoder comparison.
        fn run(
            name: &str,
            stream: &[(Vec<u8>, bool)],
            old_conversion: bool,
            decode: &mut Decode<'_>,
        ) -> Vec<u8> {
            let mut columns = Vec::new();
            let mut out = Vec::new();
            let mut last = Vec::new();
            let mut totals = Vec::new();
            let mut conversions = Vec::new();
            for (index, (data, keyframe)) in stream.iter().enumerate() {
                let mut converting = Duration::ZERO;
                let started = Instant::now();
                decode(data, *keyframe, &mut |planes| {
                    let begun = Instant::now();
                    let size = if old_conversion {
                        (1920, 1080)
                    } else {
                        crate::video_receive::output_size(planes.width, planes.height)
                    };
                    out.resize(size.0 * size.1 * 4, 0);
                    if old_conversion {
                        old_scale_i420(planes, size, &mut out);
                    } else {
                        to_rgba(planes, size.0, size.1, &mut columns, &mut out)?;
                    }
                    converting += begun.elapsed();
                    if index + 1 == stream.len() {
                        last.resize(planes.width * planes.height * 4, 0);
                        to_rgba(planes, planes.width, planes.height, &mut columns, &mut last)?;
                    }
                    Ok(())
                })
                .unwrap();
                if index > 0 {
                    // The first (keyframe + setup) picture is reported apart.
                    totals.push(started.elapsed());
                    conversions.push(converting);
                } else {
                    eprintln!(
                        "  {name}: first picture {:.1} ms",
                        started.elapsed().as_secs_f64() * 1000.0
                    );
                }
            }
            let ms = |value: &Duration| value.as_secs_f64() * 1000.0;
            let mut sorted: Vec<f64> = totals.iter().map(ms).collect();
            sorted.sort_by(f64::total_cmp);
            let mean = sorted.iter().sum::<f64>() / sorted.len() as f64;
            let p95 = sorted[(sorted.len() * 95 / 100).min(sorted.len() - 1)];
            let convert = conversions.iter().map(ms).sum::<f64>() / conversions.len() as f64;
            eprintln!(
                "{name}: {mean:.2} ms per 1440p frame (p95 {p95:.2}) = decode {:.2} + convert {convert:.2}",
                mean - convert
            );
            last
        }
        fn openh264_decode(
            decoder: &mut openh264::decoder::Decoder,
            data: &[u8],
            deliver: &mut Deliver<'_>,
        ) -> Result<(), &'static str> {
            use openh264::formats::YUVSource;
            match decoder.decode(data).map_err(|_| "OpenH264 failed")? {
                Some(picture) => {
                    let (width, height) = picture.dimensions();
                    let (y_stride, u_stride, v_stride) = picture.strides();
                    deliver(&Planes {
                        width,
                        height,
                        y: picture.y(),
                        y_stride,
                        chroma: crate::video_rgba::Chroma::Planar {
                            u: picture.u(),
                            v: picture.v(),
                            u_stride,
                            v_stride,
                        },
                    })
                }
                None => Ok(()),
            }
        }

        let mut openh264 = openh264::decoder::Decoder::new().unwrap();
        let reference = run(
            "before: OpenH264 + scalar downscale to 1920x1080",
            &stream,
            true,
            &mut |data, _, deliver| openh264_decode(&mut openh264, data, deliver),
        );
        let mut openh264 = openh264::decoder::Decoder::new().unwrap();
        run(
            "fallback: OpenH264 + parallel 2560x1440 RGBA",
            &stream,
            false,
            &mut |data, _, deliver| openh264_decode(&mut openh264, data, deliver),
        );
        for hardware in [false, true] {
            let mut decoder = crate::video_decode_windows::Decoder::new(hardware).unwrap();
            let name = if hardware {
                "after: Media Foundation DXVA + parallel 2560x1440 RGBA"
            } else {
                "after: Media Foundation software + parallel 2560x1440 RGBA"
            };
            let last = run(name, &stream, false, &mut |data, keyframe, deliver| {
                decoder.decode(data, keyframe, deliver)
            });
            eprintln!(
                "  (DXVA set up: {}, pictures from the GPU: {}, staging read-back: {})",
                decoder.accelerated(),
                decoder.hardware_output(),
                decoder.staged()
            );
            // H.264 decoding is exact: every decoder must reproduce OpenH264's picture.
            let differing = last.iter().zip(&reference).filter(|(a, b)| a != b).count();
            eprintln!("  last picture differs from OpenH264's in {differing} bytes");
            assert_eq!(last.len(), reference.len());
            assert!(differing * 1000 < last.len(), "{differing} bytes differ");
        }
    }

    /// Enumeration only (no capture): names are bounded and IDs round-trip.
    #[cfg(target_os = "windows")]
    #[test]
    fn source_enumeration_lists_parseable_ids() {
        let listed = sources().unwrap();
        for source in &listed {
            assert!(source.name.len() <= 256);
            assert_eq!(SourceId::parse(&source.id.encode()), Some(source.id));
        }
        let displays = listed
            .iter()
            .take_while(|source| matches!(source.id, SourceId::Display(_)))
            .count();
        assert!(
            listed[displays..]
                .iter()
                .all(|source| matches!(source.id, SourceId::Window(_))),
            "monitors come first"
        );
    }
}