Skip to content

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

53.3 KB
Raw Blame
// RustCord voice: a Discord voice client adapted from Serein
// (https://github.com/ViceVerse-cz/Serein, commit a0e72cc, `crates/discord-voice` and the
// call glue in `apps/desktop/src/voice.rs`, `screen.rs`, `watch.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.
//! Discord voice and Go Live for RustCord.
//!
//! The main gateway (opcode 4, `VOICE_STATE_UPDATE`, `VOICE_SERVER_UPDATE`, and for Go Live
//! opcodes 18/19/20 with `STREAM_CREATE`/`STREAM_SERVER_UPDATE`/`STREAM_DELETE`) stays with the
//! application; this crate owns the separate voice WebSockets (v8), UDP transport with
//! `aead_xchacha20_poly1305_rtpsize`, the DAVE end-to-end encryption groups (via `davey`),
//! Opus and the microphone/speakers (via `cpal`: the system defaults, or the devices,
//! volumes and noise suppression set with [`set_audio_settings`]), and for Go Live the
//! screen capture (Windows Graphics Capture), H.264 encoding (Media Foundation, OpenH264
//! fallback) and decoding (Media Foundation with DXVA hardware acceleration, OpenH264
//! fallback). Media Foundation runs on the crate's own threads, which initialize COM
//! themselves: the application needs no COM setup.
//!
//! ```no_run
//! # fn demo(rt: tokio::runtime::Handle) {
//! let call = voice::VoiceHandle::connect(
//!     voice::VoiceConfig {
//!         user_id: 1,
//!         session_id: "session_id from your VOICE_STATE_UPDATE".into(),
//!         token: "token from VOICE_SERVER_UPDATE".into(),
//!         endpoint: "c-ams05-1a2b3c4d.discord.media:443".into(),
//!         server_id: 2, // guild_id, or the channel id for DM calls
//!         channel_id: 3,
//!     },
//!     rt,
//!     |event| println!("{event:?}"),
//! );
//! call.set_self_mute(true);
//! call.disconnect();
//! # }
//! ```
mod activity;
mod agc;
mod audio;
mod ogg_opus;
mod capture;
mod crypto;
mod echo;
mod health;
mod jitter;
mod mic;
mod mixer;
mod presentation;
mod screen;
mod settings;
mod stats;
mod stream;
mod stream_audio_receive;
mod stream_mix;
mod stream_playout;
mod stream_sync;
#[cfg(test)]
mod test_mls;
mod timer;
mod transport;
mod transport_feedback;
mod video;
mod video_codec;
#[cfg(target_os = "windows")]
mod video_decode_windows;
mod video_feedback;
mod video_playout;
mod video_receive;
mod video_rgba;
mod video_sps;
// Exercise the exact vendored HPKE SHAKE adapter (see vendor/hpke-rs/SEREIN-PATCH.md).
#[cfg(test)]
#[path = "../vendor/hpke-rs/src/serein_sha3.rs"]
#[rustfmt::skip]
mod hpke_sha3;

use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicU16, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, Weak, mpsc};
use tokio::sync::{oneshot, watch};
use transport::{Controls, Credentials, Status};
use zeroize::Zeroizing;

pub use audio::call_input_level_db;
pub use ogg_opus::decode_ogg_opus;
pub(crate) use presentation::{PlaybackFrame, Presentation};
pub use settings::{
    AudioDevice, AudioDevices, AudioSettings, MicTest, audio_devices, audio_settings,
    set_audio_settings, set_push_to_talk, set_video_hardware_acceleration,
};

/// The browser user agent voice sockets open with (the app's, set once at
/// startup), so they open the way the web client's do: with it and
/// discord.com as their origin.
pub fn set_user_agent(user_agent: String) {
    let _ = transport::USER_AGENT.set(user_agent);
}

/// Microphone level (dBFS) above which audio is sent and you show as speaking.
pub const SPEAKING_THRESHOLD_DB: f32 = audio::SEND_THRESHOLD_DB as f32;

/// One 20 ms mono 48 kHz PCM frame.
pub(crate) type Frame = [f32; 960];

/// Voice credentials for one call, collected from the main gateway.
#[derive(Clone)]
pub struct VoiceConfig {
    /// Your own user ID.
    pub user_id: u64,
    /// `session_id` of the main gateway's `VOICE_STATE_UPDATE` for your account.
    pub session_id: String,
    /// `token` of `VOICE_SERVER_UPDATE`.
    pub token: String,
    /// `endpoint` of `VOICE_SERVER_UPDATE` (`host:port`; a scheme or missing port is fine).
    pub endpoint: String,
    /// The guild ID, or the channel ID for DM/group DM calls.
    pub server_id: u64,
    /// The voice channel ID (also the DAVE group ID).
    pub channel_id: u64,
}
impl fmt::Debug for VoiceConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VoiceConfig")
            .field("user_id", &self.user_id)
            .field("session_id", &"[REDACTED]")
            .field("token", &"[REDACTED]")
            .field("endpoint", &self.endpoint)
            .field("server_id", &self.server_id)
            .field("channel_id", &self.channel_id)
            .finish()
    }
}

/// Events of one call, delivered from background threads.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum VoiceEvent {
    /// Joined and end-to-end encrypted (DAVE); audio flows. Sent once per connection. When
    /// you are alone in the channel this comes as soon as the empty group is set up; audio
    /// starts flowing when somebody joins.
    Connected,
    /// Someone (including you) started or stopped producing audible sound.
    Speaking { user_id: u64, speaking: bool },
    /// A user connected to the voice server (opcode 11), including those already present
    /// when you join. Never your own ID.
    UserJoined(u64),
    /// A previously announced user disconnected (opcode 13).
    UserLeft(u64),
    /// Voice gateway heartbeat round trip in milliseconds.
    Ping(u32),
    /// Where connecting stands, for the log and the status line: "connecting" (opening the
    /// voice WebSocket), "discovering" (UDP address discovery), "securing" (transport key
    /// received, DAVE group negotiation), "waiting for a peer" (secured, alone in the
    /// channel). Each is sent when that phase begins.
    Progress(&'static str),
    /// The call ended. `None` after `disconnect()`/drop; otherwise why it failed. Always the
    /// last event. Speaking users get `Speaking { speaking: false }` before it.
    Disconnected { reason: Option<String> },
}

type Callback = Arc<dyn Fn(VoiceEvent) + Send + Sync>;

/// Serializes one handle's events and guarantees that the final batch (ending with
/// `Disconnected`) is the last thing the application sees, even if a media thread is
/// still winding down.
struct Events<E> {
    closed: Mutex<bool>,
    callback: Box<dyn Fn(E) + Send + Sync>,
}
impl<E> Events<E> {
    fn new(callback: impl Fn(E) + Send + Sync + 'static) -> Arc<Self> {
        Arc::new(Self {
            closed: Mutex::new(false),
            callback: Box::new(callback),
        })
    }
    fn lock(&self) -> std::sync::MutexGuard<'_, bool> {
        self.closed
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }
    fn emit(&self, event: E) {
        let closed = self.lock();
        if !*closed {
            (self.callback)(event);
        }
    }
    /// Deliver the final events; later `emit`s are dropped.
    fn finish(&self, events: impl IntoIterator<Item = E>) {
        let mut closed = self.lock();
        if !*closed {
            *closed = true;
            for event in events {
                (self.callback)(event);
            }
        }
    }
}

/// A running voice connection. Dropping it disconnects.
pub struct VoiceHandle {
    shared: Arc<Shared>,
}

struct Shared {
    /// Dropping the sender stops the media loop.
    controls: Mutex<Option<watch::Sender<Controls>>>,
    audio: Mutex<Option<audio::Audio>>,
    /// The first fatal local failure (audio devices), reported as the disconnect reason.
    failure: OnceLock<&'static str>,
    /// This call's ephemeral DAVE signing identity; its Go Live streams reuse it.
    identity: Arc<crypto::Identity>,
    /// Watched streams' audio, mixed into the call's speakers.
    streams: Arc<stream_mix::StreamMix>,
    /// Camera on (a source) / off (`None`) requests for the media loop.
    camera: Mutex<mpsc::Sender<Option<screen::Video>>>,
    /// Other people's cameras.
    feeds: Arc<CameraFeeds>,
}
impl Shared {
    fn lock_controls(&self) -> std::sync::MutexGuard<'_, Option<watch::Sender<Controls>>> {
        self.controls
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }
    fn lock_audio(&self) -> std::sync::MutexGuard<'_, Option<audio::Audio>> {
        self.audio
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }
    /// Apply a control change to the media loop and the device gates together.
    fn update(&self, change: impl FnOnce(&mut Controls)) {
        let controls = self.lock_controls();
        let Some(sender) = controls.as_ref() else {
            return;
        };
        sender.send_modify(change);
        let current = *sender.borrow();
        if let Some(audio) = self.lock_audio().as_ref() {
            audio.set_controls(current.muted, current.deafened);
        }
    }
    fn set_media_ready(&self, ready: bool) {
        if let Some(audio) = self.lock_audio().as_ref() {
            audio.set_ready(ready);
        }
    }
    /// Stop the media loop and close the devices. Idempotent.
    fn stop(&self) {
        drop(self.lock_controls().take());
        drop(self.lock_audio().take());
    }
    fn running(&self) -> bool {
        self.lock_controls().is_some()
    }
}

impl VoiceHandle {
    /// Connect to the voice server and start audio. Everything runs on background threads
    /// (a dedicated media thread plus a supervising task on `rt`); this returns at once.
    /// Failures, including an invalid endpoint, arrive as `VoiceEvent::Disconnected`.
    pub fn connect(
        cfg: VoiceConfig,
        rt: tokio::runtime::Handle,
        on_event: impl Fn(VoiceEvent) + Send + Sync + 'static,
    ) -> VoiceHandle {
        let url = transport::endpoint(&cfg.endpoint);
        Self::start(cfg, url, &rt, Arc::new(on_event))
    }

    /// Stop sending (the media loop sends trailing silence and `speaking: 0`).
    pub fn set_self_mute(&self, mute: bool) {
        self.shared.update(|controls| controls.muted = mute);
    }

    /// Stop playback; while deafened nothing is sent either. Undeafening restores the
    /// previous mute state.
    pub fn set_self_deaf(&self, deaf: bool) {
        self.shared.update(|controls| controls.deafened = deaf);
    }

    /// Per-user playback volume, `0.0..=2.0` (1.0 is unchanged). Non-finite values are ignored.
    pub fn set_user_volume(&self, user_id: u64, volume: f32) {
        if user_id == 0 || !volume.is_finite() {
            return;
        }
        let percent = (volume.clamp(0.0, 2.0) * 100.0).round() as u16;
        self.shared
            .update(|controls| set_volume(&mut controls.user_volumes, user_id, percent));
    }

    /// Outgoing voice bitrate in bit/s: the voice channel's `bitrate`, which Discord clients
    /// encode at (capped by the server's boost level). Clamped to 8 000..=384 000.
    pub fn set_bitrate(&self, bitrate: u32) {
        let bitrate = i32::try_from(bitrate).unwrap_or(i32::MAX);
        let bitrate = bitrate.clamp(*transport::OPUS_BITRATES.start(), *transport::OPUS_BITRATES.end());
        self.shared.update(|controls| controls.bitrate = bitrate);
    }

    /// Leave the voice connection and close the audio devices. Idempotent; also on drop.
    /// `Disconnected { reason: None }` follows unless the call had already failed.
    /// The main-gateway leave (opcode 4 with `channel_id: null`) is the caller's job.
    /// Streams started from this call keep running until they are stopped themselves.
    pub fn disconnect(&self) {
        self.shared.stop();
    }

    fn start(
        cfg: VoiceConfig,
        url: Result<String, &'static str>,
        rt: &tokio::runtime::Handle,
        on_event: Callback,
    ) -> VoiceHandle {
        // Sixteen frames (320 ms) each way: a media thread that wakes late (a game using
        // every core) catches up from these queues instead of losing speech.
        let (capture_send, capture) = mpsc::sync_channel(audio::QUEUE);
        let (playback, playback_receive) = mpsc::sync_channel(audio::QUEUE);
        let (controls, control_receive) = watch::channel(Controls::default());
        let (camera_send, camera_receive) = mpsc::channel();
        let shared = Arc::new_cyclic(|weak: &Weak<Shared>| {
            let weak = weak.clone();
            let audio = audio::Audio::start(capture_send, playback_receive, move |error| {
                if let Some(shared) = weak.upgrade() {
                    let _ = shared.failure.set(error);
                    shared.stop();
                }
            });
            let failure = OnceLock::new();
            let audio = audio.map_err(|error| failure.set(error)).ok();
            Shared {
                controls: Mutex::new(audio.is_some().then_some(controls)),
                audio: Mutex::new(audio),
                failure,
                identity: crypto::Identity::generate(),
                streams: Arc::default(),
                camera: Mutex::new(camera_send),
                feeds: Arc::default(),
            }
        });
        let credentials = Credentials {
            user: cfg.user_id,
            server: cfg.server_id,
            channel: cfg.channel_id,
            session: Zeroizing::new(cfg.session_id),
            token: Zeroizing::new(cfg.token),
        };
        let events = Events::new(move |event| on_event(event));
        let speaking: Arc<Mutex<Vec<u64>>> = Arc::default();
        let media_shared = shared.clone();
        let media_events = events.clone();
        let media_speaking = speaking.clone();
        let supervisor = shared.clone();
        let identity = shared.identity.clone();
        let streams = shared.streams.clone();
        let feeds = shared.feeds.clone();
        rt.spawn(async move {
            let result = match url {
                Ok(url) if media_shared.failure.get().is_none() => {
                    timer::isolated("rustcord-voice", move || async move {
                        let connected = std::cell::Cell::new(false);
                        // Stop promptly even while connecting or resuming.
                        let mut stop = control_receive.clone();
                        let call = transport::run(
                            credentials,
                            url,
                            capture,
                            playback,
                            control_receive,
                            move |status| {
                                forward(
                                    status,
                                    &media_shared,
                                    &media_events,
                                    &media_speaking,
                                    &connected,
                                )
                            },
                            identity,
                            streams,
                            camera_receive,
                            feeds,
                            false,
                        );
                        tokio::select! {
                            result = call => result,
                            () = transport::stopped(&mut stop) => Ok(()),
                        }
                    })
                    .await
                }
                Ok(_) => Ok(()),
                Err(error) => Err(error),
            };
            supervisor.stop();
            let reason = supervisor.failure.get().copied().or(result.err());
            let still_speaking = std::mem::take(
                &mut *speaking
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner),
            );
            events.finish(
                still_speaking
                    .into_iter()
                    .map(|user_id| VoiceEvent::Speaking {
                        user_id,
                        speaking: false,
                    })
                    .chain([VoiceEvent::Disconnected {
                        reason: reason.map(String::from),
                    }]),
            );
        });
        VoiceHandle { shared }
    }
}
impl Drop for VoiceHandle {
    fn drop(&mut self) {
        self.disconnect();
    }
}

/// Map media-loop progress to device readiness and application events.
fn forward(
    status: Status,
    shared: &Shared,
    events: &Events<VoiceEvent>,
    speaking: &Mutex<Vec<u64>>,
    connected: &std::cell::Cell<bool>,
) {
    match status {
        // Devices open (and capture may leave) only once DAVE secured the call, as in Serein.
        Status::Ready | Status::WaitingForPeer => {
            shared.set_media_ready(true);
            if status == Status::WaitingForPeer {
                events.emit(VoiceEvent::Progress("waiting for a peer"));
            }
            if !connected.replace(true) {
                events.emit(VoiceEvent::Connected);
            }
        }
        Status::Connecting | Status::Discovering | Status::Securing => {
            shared.set_media_ready(false);
            events.emit(VoiceEvent::Progress(match status {
                Status::Connecting => "connecting",
                Status::Discovering => "discovering",
                _ => "securing",
            }));
        }
        Status::Speaking { user, speaking: on } => {
            let mut users = speaking
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            users.retain(|known| *known != user);
            if on {
                users.push(user);
            }
            drop(users);
            events.emit(VoiceEvent::Speaking {
                user_id: user,
                speaking: on,
            });
        }
        Status::UserJoined(user) => events.emit(VoiceEvent::UserJoined(user)),
        Status::UserLeft(user) => events.emit(VoiceEvent::UserLeft(user)),
        Status::Ping(ms) => events.emit(VoiceEvent::Ping(ms)),
        Status::RemoteAudio => {}
    }
}

/// Store a playback percentage; 100% frees the slot. At most 64 users are tracked.
fn set_volume(volumes: &mut [(u64, u16); 64], user: u64, percent: u16) {
    if let Some(slot) = volumes.iter_mut().find(|(id, _)| *id == user) {
        *slot = if percent == 100 {
            (0, 100)
        } else {
            (user, percent)
        };
    } else if percent != 100
        && let Some(slot) = volumes.iter_mut().find(|(id, _)| *id == 0)
    {
        *slot = (user, percent);
    }
}

// ---- Camera --------------------------------------------------------------------------

/// A connected webcam.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CameraDevice {
    /// Opaque: `camera:<id>`, stable across restarts.
    pub id: String,
    pub name: String,
}

/// Connected cameras (blocking, tens of milliseconds; call it off the UI thread).
/// Windows only; elsewhere the list is empty.
pub fn cameras() -> Vec<CameraDevice> {
    #[cfg(target_os = "windows")]
    {
        screen::camera::devices()
            .unwrap_or_default()
            .into_iter()
            .map(|device| CameraDevice { id: screen::SourceId::Camera(device.id).encode(), name: device.name })
            .collect()
    }
    #[cfg(not(target_os = "windows"))]
    Vec::new()
}

/// Other people's cameras in one call: the newest picture of each (H.264 decoded with
/// Media Foundation, DXVA where available, else OpenH264; at most 2560 wide).
#[derive(Default)]
pub struct CameraFeeds {
    sinks: Mutex<std::collections::HashMap<u64, video_receive::VideoSink>>,
    wake: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
}
impl CameraFeeds {
    /// Called (from any thread) whenever a new picture is ready. Set it right after
    /// connecting: cameras that appeared earlier don't use it.
    pub fn set_wake(&self, wake: impl Fn() + Send + Sync + 'static) {
        *self.wake.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::new(wake));
    }
    /// The newest picture of `user`'s camera (cheap: a shared picture); `None` while
    /// their camera is off or nothing has been decoded yet.
    pub fn latest(&self, user: u64) -> Option<VideoFrame> {
        let sink = self.sinks.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&user).cloned()?;
        sink.latest()
    }
    /// Who has a camera on right now.
    pub fn users(&self) -> Vec<u64> {
        self.sinks.lock().unwrap_or_else(std::sync::PoisonError::into_inner).keys().copied().collect()
    }
    pub(crate) fn add(&self, user: u64) -> video_receive::VideoSink {
        let wake = self.wake.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
        let sink = video_receive::Output::new(move || {
            if let Some(wake) = &wake {
                wake();
            }
        });
        self.sinks.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(user, sink.clone());
        sink
    }
    pub(crate) fn remove(&self, user: u64) {
        self.sinks.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&user);
    }
}

impl VoiceHandle {
    /// Other people's cameras in this call.
    pub fn camera_feeds(&self) -> Arc<CameraFeeds> {
        self.shared.feeds.clone()
    }
}

/// An open camera: capturing, with a local preview. Dropping it closes the camera.
/// On its own it only previews (the settings' camera test); [`VoiceHandle::set_camera`]
/// sends it to the call.
pub struct Camera {
    /// Capture and encoding; dropping it stops them.
    _worker: screen::Worker,
    preview: video_receive::VideoSink,
    preview_wanted: Arc<AtomicBool>,
    /// The call's side, until a call takes it.
    video: Mutex<Option<screen::Video>>,
}
impl Camera {
    /// Open `device` (an id from [`cameras`]) at up to 720p, 30 pictures a second.
    /// Blocking (opening a camera takes up to a second): call it off the UI thread.
    /// `wake` is called (from any thread) when a new preview picture is ready.
    pub fn open(device: &str, wake: impl Fn() + Send + Sync + 'static) -> Result<Camera, String> {
        #[cfg(target_os = "windows")]
        {
            let source = screen::SourceId::parse(device).ok_or("Unknown camera")?;
            let screen::SourceId::Camera(id) = source else { return Err("Unknown camera".into()) };
            let size = screen::camera::size(id, (1280, 720))?;
            let quality = StreamQuality { max_height: 720, fps: 30 };
            let mut settings = screen::Settings::new(source, size, quality, false)?;
            settings.cursor = false;
            let preview = video_receive::Output::new(wake);
            let preview_wanted = Arc::new(AtomicBool::new(true));
            let (worker, video) = screen::Worker::start(settings, preview.clone(), preview_wanted.clone())?;
            Ok(Camera { _worker: worker, preview, preview_wanted, video: Mutex::new(Some(video)) })
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = (device, wake);
            Err("Cameras are available on Windows only".into())
        }
    }
    /// The latest picture (cheap: a shared picture), at most 15 new ones per second and
    /// only while this is being read.
    pub fn preview(&self) -> Option<VideoFrame> {
        self.preview_wanted.store(true, Ordering::Release);
        self.preview.latest()
    }
    /// What is being sent: size, pictures per second, bitrate, encoder.
    pub fn stats(&self) -> StreamStats {
        self.preview.stats.snapshot()
    }
}

impl VoiceHandle {
    /// Send `camera` to the call (H.264, end-to-end encrypted like the audio), or stop
    /// sending with `None`. A camera can be sent to one call, once: to turn it back on,
    /// open it again. Main-gateway opcode 4 with `self_video` is the caller's job.
    /// Returns false when that camera was already used or the call has ended.
    pub fn set_camera(&self, camera: Option<&Camera>) -> bool {
        let video = match camera {
            Some(camera) => {
                let taken = camera.video.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take();
                let Some(video) = taken else { return false };
                Some(video)
            }
            None => None,
        };
        self.shared.running()
            && self.shared.camera.lock().unwrap_or_else(std::sync::PoisonError::into_inner).send(video).is_ok()
    }
}

// ---- Go Live -------------------------------------------------------------------------

/// Credentials for one Go Live connection, from the main gateway:
/// STREAM_CREATE (`rtc_server_id`, `rtc_channel_id`) + STREAM_SERVER_UPDATE (`token`,
/// `endpoint`), plus your own voice `session_id` (from your VOICE_STATE_UPDATE).
#[derive(Clone)]
pub struct StreamConfig {
    pub user_id: u64,
    pub session_id: String,
    pub token: String,
    /// STREAM_SERVER_UPDATE `endpoint` (validated like the voice endpoint: `*.discord.media`).
    pub endpoint: String,
    /// STREAM_CREATE `rtc_server_id`: the Identify `server_id`. The stream's DAVE group is
    /// `rtc_server_id - 1` (Serein's mapping, see `stream::dave_group`).
    pub rtc_server_id: u64,
    /// STREAM_CREATE `rtc_channel_id` (else `rtc_server_id`). Informational: Serein's tested
    /// mapping derives the DAVE group from `rtc_server_id`, so this is not sent anywhere.
    pub rtc_channel_id: u64,
}
impl fmt::Debug for StreamConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StreamConfig")
            .field("user_id", &self.user_id)
            .field("session_id", &"[REDACTED]")
            .field("token", &"[REDACTED]")
            .field("endpoint", &self.endpoint)
            .field("rtc_server_id", &self.rtc_server_id)
            .field("rtc_channel_id", &self.rtc_channel_id)
            .finish()
    }
}

/// A monitor or window that can be shared.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ScreenSource {
    /// Opaque: `display:<handle>` or `window:<handle>`.
    pub id: String,
    pub name: String,
    pub is_window: bool,
}

/// Monitors first, then windows (blocking, a few ms; call it off the UI thread).
/// Windows only; elsewhere this returns an error.
pub fn screen_sources() -> Result<Vec<ScreenSource>, String> {
    let sources = screen::sources().map_err(String::from)?;
    Ok(sources
        .into_iter()
        .map(|source| ScreenSource {
            id: source.id.encode(),
            name: source.name,
            is_window: matches!(source.id, screen::SourceId::Window(_)),
        })
        .collect())
}

/// A small still of a source for the picker, at most `max_width` wide (blocking: it starts
/// a capture session for one frame, up to half a second). `None` if the source is gone,
/// minimized, protected or unsupported.
pub fn screen_thumbnail(source: &ScreenSource, max_width: u32) -> Option<VideoFrame> {
    static SEQ: AtomicU64 = AtomicU64::new(0);
    let id = screen::SourceId::parse(&source.id)?;
    let (width, height, rgba) = screen::thumbnail(id, max_width.max(1) as usize)?;
    Some(VideoFrame {
        width: u32::try_from(width).ok()?,
        height: u32::try_from(height).ok()?,
        rgba: Arc::new(rgba),
        seq: SEQ.fetch_add(1, Ordering::Relaxed) + 1,
    })
}

/// Go Live picture quality. Discord's defaults without Nitro are 720p at 30 fps.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StreamQuality {
    /// 720, 1080, 1440, or 0 for the source resolution (at most 3840x2160). Never upscaled.
    pub max_height: u32,
    /// 15, 30 or 60 (other values round to the nearest of these).
    pub fps: u32,
}
impl Default for StreamQuality {
    fn default() -> Self {
        Self {
            max_height: 720,
            fps: 30,
        }
    }
}

/// One decoded or captured RGBA8 frame (unpremultiplied, row-major, `width * height * 4`
/// bytes). Cloning is cheap; the pixels are shared.
#[derive(Clone)]
pub struct VideoFrame {
    pub width: u32,
    pub height: u32,
    pub rgba: Arc<Vec<u8>>,
    /// Increases with every new frame.
    pub seq: u64,
}
impl fmt::Debug for VideoFrame {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VideoFrame")
            .field("width", &self.width)
            .field("height", &self.height)
            .field("seq", &self.seq)
            .finish_non_exhaustive()
    }
}

/// What a Go Live stream is doing right now, for a "Stream Info" overlay or a quality badge.
/// Read with [`WatchHandle::stats`] or [`StreamHandle::stats`]; cheap enough to call every
/// frame (rates are computed on demand from lock-free counters).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StreamStats {
    /// "H264" (what's being received / sent).
    pub codec: &'static str,
    /// Size of the stream as sent (before any display downscale); 0 until known.
    pub width: u32,
    pub height: u32,
    /// Frames per second actually decoded (watching) or encoded+sent (streaming), averaged over ~1 s.
    pub fps: f32,
    /// Receive / send video bitrate, kbit/s, ~1 s average.
    pub bitrate_kbps: u32,
    /// "Media Foundation (hardware)", "Media Foundation", "OpenH264" — whatever is decoding/encoding.
    pub engine: &'static str,
    /// Frames dropped / keyframes requested since start (diagnostics).
    pub dropped: u64,
    pub keyframe_requests: u64,
}

/// Events of one Go Live connection, delivered from background threads.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StreamEvent {
    /// Joined the stream server and encrypted; media flows (for a stream nobody watches yet:
    /// ready, video starts when the first viewer joins).
    Connected,
    /// Stream gateway heartbeat round trip (ms).
    Ping(u32),
    /// Ended. `None` after stop()/drop; otherwise a short user-facing reason. Always last.
    Disconnected { reason: Option<String> },
}

/// Stop signal shared by stream and watch handles.
struct Stopper {
    stop: Mutex<Option<oneshot::Sender<()>>>,
    stopping: AtomicBool,
}
impl Stopper {
    fn new() -> (Self, oneshot::Receiver<()>) {
        let (send, receive) = oneshot::channel();
        (
            Self {
                stop: Mutex::new(Some(send)),
                stopping: AtomicBool::new(false),
            },
            receive,
        )
    }
    fn stop(&self) {
        self.stopping.store(true, Ordering::Release);
        drop(
            self.stop
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .take(),
        );
    }
    fn stopping(&self) -> bool {
        self.stopping.load(Ordering::Acquire)
    }
}

/// Map stream progress to application events.
fn forward_stream(
    status: stream::StreamStatus,
    events: &Events<StreamEvent>,
    connected: &AtomicBool,
) {
    match status {
        stream::StreamStatus::Ready | stream::StreamStatus::WaitingForPeer => {
            if !connected.swap(true, Ordering::AcqRel) {
                events.emit(StreamEvent::Connected);
            }
        }
        stream::StreamStatus::Ping(ms) => events.emit(StreamEvent::Ping(ms)),
        stream::StreamStatus::Connecting
        | stream::StreamStatus::Discovering
        | stream::StreamStatus::Securing => {}
    }
}

/// Your running Go Live. Dropping it stops the share.
pub struct StreamHandle {
    inner: Arc<StreamInner>,
}
struct StreamInner {
    stopper: Stopper,
    /// Capture and encoding; dropping it stops them.
    worker: Mutex<Option<screen::Worker>>,
    preview: video_receive::VideoSink,
    preview_wanted: Arc<AtomicBool>,
}
impl StreamInner {
    fn stop_worker(&self) {
        drop(
            self.worker
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .take(),
        );
    }
}
impl StreamHandle {
    /// Stop sharing. Idempotent; also on drop. `Disconnected { reason: None }` follows unless
    /// the stream had already ended. Gateway opcode 19 (Stream Delete) is the caller's job.
    pub fn stop(&self) {
        self.inner.stopper.stop();
        self.inner.stop_worker();
    }
    /// The latest captured frame, downscaled to at most 1280 wide (cheap: a shared picture).
    /// Previews are rendered only while this is being read, at most 15 per second.
    pub fn preview(&self) -> Option<VideoFrame> {
        self.inner.preview_wanted.store(true, Ordering::Release);
        self.inner.preview.latest()
    }
    /// What is being sent: the encoded size, frames encoded and sent per second, the send
    /// bitrate, the encoder ("Media Foundation (hardware)" or "OpenH264"), frames dropped
    /// before sending and keyframes viewers requested. Zeros until capture starts.
    pub fn stats(&self) -> StreamStats {
        self.inner.preview.stats.snapshot()
    }
}
impl Drop for StreamHandle {
    fn drop(&mut self) {
        self.stop();
    }
}

/// Someone's Go Live you watch. Dropping it stops watching.
pub struct WatchHandle {
    inner: Arc<WatchInner>,
}
struct WatchInner {
    stopper: Stopper,
    output: video_receive::VideoSink,
    /// Stream audio playback percentage, 0..=200.
    volume: Arc<AtomicU16>,
}
impl WatchHandle {
    /// The newest decoded frame (a cheap shared picture), at most 2560 wide: 1440p is
    /// delivered 1:1, wider streams (4K, ultrawide) are downscaled.
    pub fn latest_frame(&self) -> Option<VideoFrame> {
        self.inner.output.latest()
    }
    /// What is being received: the stream's size as sent, frames decoded per second, the
    /// receive bitrate, the decoder ("Media Foundation (hardware)", "Media Foundation" or
    /// "OpenH264"), frames dropped and keyframes requested from the sender.
    pub fn stats(&self) -> StreamStats {
        self.inner.output.stats.snapshot()
    }
    /// Stream audio volume, `0.0..=2.0` (1.0 is unchanged). Non-finite values are ignored.
    pub fn set_volume(&self, volume: f32) {
        if volume.is_finite() {
            let percent = (volume.clamp(0.0, 2.0) * 100.0).round() as u16;
            self.inner.volume.store(percent, Ordering::Relaxed);
        }
    }
    /// Stop watching. Idempotent; also on drop. `Disconnected { reason: None }` follows
    /// unless the watch had already ended. Gateway opcode 19 for the stream key is the
    /// caller's job.
    pub fn stop(&self) {
        self.inner.stopper.stop();
    }
}
impl Drop for WatchHandle {
    fn drop(&mut self) {
        self.stop();
    }
}

impl VoiceHandle {
    /// Go Live: capture `source`, encode H.264 (Media Foundation hardware encoder, OpenH264
    /// fallback) and send it on a second voice connection that shares this call's DAVE
    /// identity. `with_audio` also sends what this computer plays, except RustCord itself
    /// (process loopback: Windows 11 or Server 2022, build 20348+; on older Windows the
    /// share continues without audio). `wake` is called (from any thread) when a new preview frame
    /// is ready. Returns at once; failures arrive as `StreamEvent::Disconnected`.
    #[allow(clippy::too_many_arguments)] // The documented public API.
    pub fn start_stream(
        &self,
        cfg: StreamConfig,
        source: ScreenSource,
        quality: StreamQuality,
        with_audio: bool,
        rt: tokio::runtime::Handle,
        wake: impl Fn() + Send + Sync + 'static,
        on_event: impl Fn(StreamEvent) + Send + Sync + 'static,
    ) -> StreamHandle {
        let events = Events::new(on_event);
        let (stopper, mut stop) = Stopper::new();
        let preview = video_receive::Output::new(wake);
        let preview_wanted = Arc::new(AtomicBool::new(true));
        let inner = Arc::new(StreamInner {
            stopper,
            worker: Mutex::new(None),
            preview: preview.clone(),
            preview_wanted: preview_wanted.clone(),
        });
        let supervisor = inner.clone();
        let identity = self.shared.identity.clone();
        rt.spawn(async move {
            let work = async {
                let url = transport::endpoint(&cfg.endpoint)?;
                let id = screen::SourceId::parse(&source.id).ok_or("Unknown screen source")?;
                // Source lookup and capture start enumerate windows: keep them off the runtime.
                let (worker, video) = tokio::task::spawn_blocking(move || {
                    let size = screen::source_size(id)?;
                    let settings = screen::Settings::new(id, size, quality, with_audio)?;
                    screen::Worker::start(settings, preview, preview_wanted)
                })
                .await
                .map_err(|_| "Screen capture worker could not start")??;
                {
                    let mut slot = supervisor
                        .worker
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    if supervisor.stopper.stopping() {
                        return Ok(());
                    }
                    *slot = Some(worker);
                }
                let credentials = stream::StreamCredentials {
                    user: cfg.user_id,
                    server: cfg.rtc_server_id,
                    session: Zeroizing::new(cfg.session_id),
                    token: Zeroizing::new(cfg.token),
                };
                let emitter = events.clone();
                timer::isolated("rustcord-stream", move || async move {
                    let connected = AtomicBool::new(false);
                    stream::run_stream(
                        credentials,
                        identity,
                        Some(video),
                        None,
                        None,
                        move |status| forward_stream(status, &emitter, &connected),
                        url,
                        false,
                    )
                    .await
                })
                .await
            };
            let result = tokio::select! {
                result = work => result,
                _ = &mut stop => Ok(()),
            };
            supervisor.stop_worker();
            let reason = if supervisor.stopper.stopping() {
                None
            } else {
                result.err()
            };
            events.finish([StreamEvent::Disconnected {
                reason: reason.map(String::from),
            }]);
        });
        StreamHandle { inner }
    }

    /// Watch someone's Go Live: decode H.264 (Media Foundation with DXVA where available,
    /// else its software decoder, else OpenH264) to RGBA (at most 2560 wide) and play the
    /// stream's audio through this call's speakers (while the call runs and is not
    /// deafened). `wake` is called (from any thread) on every new frame. Returns at once;
    /// failures arrive as `StreamEvent::Disconnected`.
    pub fn watch_stream(
        &self,
        cfg: StreamConfig,
        rt: tokio::runtime::Handle,
        wake: impl Fn() + Send + Sync + 'static,
        on_event: impl Fn(StreamEvent) + Send + Sync + 'static,
    ) -> WatchHandle {
        let url = transport::endpoint(&cfg.endpoint);
        self.watch_at(cfg, url, &rt, wake, on_event)
    }

    fn watch_at(
        &self,
        cfg: StreamConfig,
        url: Result<String, &'static str>,
        rt: &tokio::runtime::Handle,
        wake: impl Fn() + Send + Sync + 'static,
        on_event: impl Fn(StreamEvent) + Send + Sync + 'static,
    ) -> WatchHandle {
        let events = Events::new(on_event);
        let (stopper, mut stop) = Stopper::new();
        let output = video_receive::Output::new(wake);
        let volume = Arc::new(AtomicU16::new(100));
        let inner = Arc::new(WatchInner {
            stopper,
            output: output.clone(),
            volume: volume.clone(),
        });
        let supervisor = inner.clone();
        let identity = self.shared.identity.clone();
        // Stream audio plays only through a running call.
        let (audio, registration) = if self.shared.running() {
            let (send, registration) = self.shared.streams.register(volume);
            (Some(send), Some(registration))
        } else {
            (None, None)
        };
        rt.spawn(async move {
            let work = async {
                let url = url?;
                let credentials = stream::StreamCredentials {
                    user: cfg.user_id,
                    server: cfg.rtc_server_id,
                    session: Zeroizing::new(cfg.session_id),
                    token: Zeroizing::new(cfg.token),
                };
                let emitter = events.clone();
                timer::isolated("rustcord-watch", move || async move {
                    let connected = AtomicBool::new(false);
                    stream::run_stream(
                        credentials,
                        identity,
                        None,
                        Some(output),
                        audio,
                        move |status| forward_stream(status, &emitter, &connected),
                        url,
                        false,
                    )
                    .await
                })
                .await
            };
            let result = tokio::select! {
                result = work => result,
                _ = &mut stop => Ok(()),
            };
            drop(registration);
            let reason = if supervisor.stopper.stopping() {
                None
            } else {
                result.err()
            };
            events.finish([StreamEvent::Disconnected {
                reason: reason.map(String::from),
            }]);
        });
        WatchHandle { inner }
    }
}

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

    fn config(endpoint: &str) -> VoiceConfig {
        VoiceConfig {
            user_id: 1,
            session_id: "synthetic-session".into(),
            token: "synthetic-token".into(),
            endpoint: endpoint.into(),
            server_id: 30,
            channel_id: 3,
        }
    }
    fn stream_config(endpoint: &str) -> StreamConfig {
        StreamConfig {
            user_id: 1,
            session_id: "synthetic-session".into(),
            token: "synthetic-token".into(),
            endpoint: endpoint.into(),
            rtc_server_id: 31,
            rtc_channel_id: 30,
        }
    }
    fn collector<E: Send + 'static>() -> (Arc<dyn Fn(E) + Send + Sync>, mpsc::Receiver<E>) {
        let (send, receive) = mpsc::channel();
        let send = Mutex::new(send);
        (
            Arc::new(move |event| {
                let _ = send.lock().unwrap().send(event);
            }),
            receive,
        )
    }
    /// The next event that isn't connecting progress.
    fn next_outcome(events: &mpsc::Receiver<VoiceEvent>, wait: Duration) -> VoiceEvent {
        loop {
            match events.recv_timeout(wait).unwrap() {
                VoiceEvent::Progress(_) => continue,
                event => return event,
            }
        }
    }
    fn runtime() -> tokio::runtime::Runtime {
        tokio::runtime::Builder::new_multi_thread()
            .worker_threads(1)
            .enable_all()
            .build()
            .unwrap()
    }
    /// A handle without devices or network, for API tests.
    fn idle_handle() -> (VoiceHandle, watch::Receiver<Controls>) {
        let (sender, receiver) = watch::channel(Controls::default());
        let shared = Shared {
            controls: Mutex::new(Some(sender)),
            audio: Mutex::new(None),
            failure: OnceLock::new(),
            identity: crypto::Identity::generate(),
            streams: Arc::default(),
            camera: Mutex::new(mpsc::channel().0),
            feeds: Arc::default(),
        };
        (
            VoiceHandle {
                shared: Arc::new(shared),
            },
            receiver,
        )
    }

    #[test]
    fn invalid_endpoint_reports_disconnected_without_network() {
        let runtime = runtime();
        for endpoint in ["127.0.0.1:9", "", "evil.example.com:443"] {
            let (callback, events) = collector();
            let handle =
                VoiceHandle::connect(config(endpoint), runtime.handle().clone(), move |event| {
                    callback(event)
                });
            let event = events.recv_timeout(Duration::from_secs(10)).unwrap();
            assert!(
                matches!(&event, VoiceEvent::Disconnected { reason: Some(_) }),
                "{endpoint}: {event:?}"
            );
            // Controls after the end are harmless no-ops; disconnect is idempotent.
            handle.set_self_mute(true);
            handle.set_self_deaf(true);
            handle.set_user_volume(5, 0.5);
            handle.disconnect();
            handle.disconnect();
            drop(handle);
            assert!(events.recv_timeout(Duration::from_millis(200)).is_err());
        }
    }

    #[test]
    fn unreachable_voice_server_ends_with_disconnected() {
        let runtime = runtime();
        let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = closed.local_addr().unwrap();
        drop(closed);
        let (callback, events) = collector();
        let handle = VoiceHandle::start(
            config("unused"),
            Ok(format!("ws://{address}")),
            runtime.handle(),
            callback,
        );
        assert_eq!(
            next_outcome(&events, Duration::from_secs(20)),
            VoiceEvent::Disconnected {
                reason: Some("Voice connection failed".into())
            }
        );
        drop(handle);
        assert!(events.recv_timeout(Duration::from_millis(200)).is_err());
    }

    #[test]
    fn disconnect_while_connecting_is_clean_and_reported_once() {
        let runtime = runtime();
        // A server that accepts TCP but never completes the WebSocket handshake.
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let (callback, events) = collector();
        let handle = VoiceHandle::start(
            config("unused"),
            Ok(format!("ws://{address}")),
            runtime.handle(),
            callback,
        );
        let _socket = listener.accept().unwrap();
        handle.disconnect();
        assert_eq!(
            next_outcome(&events, Duration::from_secs(10)),
            VoiceEvent::Disconnected { reason: None }
        );
        handle.disconnect();
        drop(handle);
        assert!(events.recv_timeout(Duration::from_millis(200)).is_err());
    }

    #[test]
    fn dropping_the_handle_disconnects() {
        let runtime = runtime();
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let (callback, events) = collector();
        let handle = VoiceHandle::start(
            config("unused"),
            Ok(format!("ws://{address}")),
            runtime.handle(),
            callback,
        );
        let _socket = listener.accept().unwrap();
        drop(handle);
        assert_eq!(
            next_outcome(&events, Duration::from_secs(10)),
            VoiceEvent::Disconnected { reason: None }
        );
    }

    #[test]
    fn bitrate_follows_the_channel_within_discords_range() {
        let (handle, receiver) = idle_handle();
        assert_eq!(receiver.borrow().bitrate, 64_000);
        handle.set_bitrate(96_000);
        assert_eq!(receiver.borrow().bitrate, 96_000);
        handle.set_bitrate(1_000_000);
        assert_eq!(receiver.borrow().bitrate, 384_000);
        handle.set_bitrate(0);
        assert_eq!(receiver.borrow().bitrate, 8_000);
        handle.disconnect();
    }

    #[test]
    fn user_volumes_are_clamped_and_slots_reused() {
        let mut volumes = [(0, 100); 64];
        set_volume(&mut volumes, 7, 50);
        assert_eq!(volumes[0], (7, 50));
        set_volume(&mut volumes, 7, 200);
        assert_eq!(volumes[0], (7, 200));
        set_volume(&mut volumes, 7, 100);
        assert_eq!(volumes[0], (0, 100));
        for user in 1..=70 {
            set_volume(&mut volumes, user, 10);
        }
        assert_eq!(volumes.iter().filter(|(id, _)| *id != 0).count(), 64);
        // The handle converts 0.0..=2.0 to percentages, clamping out-of-range values.
        let (handle, receiver) = idle_handle();
        handle.set_user_volume(9, 3.5);
        handle.set_user_volume(10, -1.0);
        handle.set_user_volume(11, 0.256);
        handle.set_user_volume(12, f32::NAN);
        handle.set_self_mute(true);
        let controls = *receiver.borrow();
        assert!(controls.user_volumes.contains(&(9, 200)));
        assert!(controls.user_volumes.contains(&(10, 0)));
        assert!(controls.user_volumes.contains(&(11, 26)));
        assert!(!controls.user_volumes.iter().any(|(id, _)| *id == 12));
        assert!(controls.muted && !controls.deafened);
        handle.set_self_deaf(true);
        assert!(receiver.borrow().deafened);
        handle.disconnect();
        assert!(
            receiver.has_changed().is_err(),
            "disconnect drops the control sender"
        );
    }

    #[test]
    fn handle_and_config_are_thread_safe_and_redacted() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<VoiceHandle>();
        assert_send_sync::<VoiceConfig>();
        assert_send_sync::<StreamHandle>();
        assert_send_sync::<WatchHandle>();
        assert_send_sync::<StreamConfig>();
        assert_send_sync::<VideoFrame>();
        assert_send_sync::<StreamStats>();
        let debug = format!("{:?}", config("c-1.discord.media"));
        assert!(!debug.contains("synthetic-token") && !debug.contains("synthetic-session"));
        let debug = format!("{:?}", stream_config("c-1.discord.media"));
        assert!(!debug.contains("synthetic-token") && !debug.contains("synthetic-session"));
        assert!(debug.contains("rtc_server_id: 31"));
    }

    #[test]
    fn events_after_the_final_batch_are_dropped() {
        let (callback, events) = collector::<u32>();
        let emitter = Events::new(move |event| callback(event));
        emitter.emit(1);
        emitter.finish([2, 3]);
        emitter.emit(4);
        emitter.finish([5]);
        assert_eq!(events.try_iter().collect::<Vec<_>>(), [1, 2, 3]);
    }

    #[test]
    fn streams_with_invalid_settings_end_with_a_reason_and_stop_cleanly() {
        let runtime = runtime();
        let (handle, _controls) = idle_handle();
        let source = ScreenSource {
            id: "display:1".into(),
            name: "Display".into(),
            is_window: false,
        };
        for (endpoint, source) in [
            ("127.0.0.1:9", source.clone()),
            (
                "c-1.discord.media",
                ScreenSource {
                    id: "nonsense".into(),
                    ..source
                },
            ),
        ] {
            let (callback, events) = collector();
            let stream = handle.start_stream(
                stream_config(endpoint),
                source,
                StreamQuality::default(),
                false,
                runtime.handle().clone(),
                || {},
                move |event| callback(event),
            );
            let event = events.recv_timeout(Duration::from_secs(10)).unwrap();
            assert!(
                matches!(&event, StreamEvent::Disconnected { reason: Some(_) }),
                "{endpoint}: {event:?}"
            );
            assert!(stream.preview().is_none());
            let stats = stream.stats();
            assert_eq!(
                (stats.codec, stats.width, stats.fps, stats.bitrate_kbps, stats.engine),
                ("H264", 0, 0.0, 0, "")
            );
            stream.stop();
            stream.stop();
            drop(stream);
            assert!(events.recv_timeout(Duration::from_millis(200)).is_err());
        }
        // A watch of an invalid endpoint fails the same way; volume changes are harmless.
        let (callback, events) = collector();
        let watch = handle.watch_stream(
            stream_config("evil.example.com:443"),
            runtime.handle().clone(),
            || {},
            move |event| callback(event),
        );
        watch.set_volume(1.5);
        watch.set_volume(f32::NAN);
        assert_eq!(watch.inner.volume.load(Ordering::Relaxed), 150);
        assert!(matches!(
            events.recv_timeout(Duration::from_secs(10)).unwrap(),
            StreamEvent::Disconnected { reason: Some(_) }
        ));
        assert!(watch.latest_frame().is_none());
        assert_eq!(watch.stats().keyframe_requests, 0);
        drop(watch);
        assert!(events.recv_timeout(Duration::from_millis(200)).is_err());
        // The watch's audio input left the call's mix with it.
        assert!(handle.shared.streams.mix(None, true, false).is_none());
    }

    #[test]
    fn stopping_a_watch_while_connecting_reports_none_once() {
        let runtime = runtime();
        let (handle, _controls) = idle_handle();
        let (callback, events) = collector();
        // A server that accepts TCP but never completes the WebSocket handshake.
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let watch = handle.watch_at(
            stream_config("unused"),
            Ok(format!("ws://{address}")),
            runtime.handle(),
            || {},
            move |event| callback(event),
        );
        let _socket = listener.accept().unwrap();
        watch.stop();
        assert_eq!(
            events.recv_timeout(Duration::from_secs(10)).unwrap(),
            StreamEvent::Disconnected { reason: None }
        );
        drop(watch);
        assert!(events.recv_timeout(Duration::from_millis(200)).is_err());
    }

    #[test]
    fn unknown_sources_have_no_thumbnail() {
        let source = ScreenSource {
            id: "window:1".into(),
            name: "gone".into(),
            is_window: true,
        };
        assert!(screen_thumbnail(&source, 160).is_none());
        let garbage = ScreenSource {
            id: "garbage".into(),
            ..source
        };
        assert!(screen_thumbnail(&garbage, 160).is_none());
    }
}