Skip to content

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

66.3 KB
Raw Blame
//! Voice channels: joining (op 4), collecting the two halves of the voice
//! credentials (your own VOICE_STATE_UPDATE's session and VOICE_SERVER_UPDATE's
//! token / endpoint), running the call through the `voice` crate, the
//! "Voice Connected" panel above the user panel (with its connection stats),
//! and the Voice & Video preferences. The call view is in `ui/call.rs`.

use crate::app::RustCord;
use crate::backend::Command;
use crate::style::{icon_font, rgba, Theme};
use crate::ui::SizedOffScreen;
use discord::model::Id;
use eframe::egui::{self, pos2, vec2, Align2, Color32, FontId, Frame, Margin, Order, Rect, RichText, Sense, Stroke, Ui};
use serde_json::Value;
use std::collections::{HashSet, VecDeque};
use std::time::{Duration, Instant};

/// Ping samples kept for the stats graph: five minutes at the voice heartbeat's 5 s.
const PING_HISTORY: usize = 60;
/// What the stats graph spans.
const GRAPH_WINDOW: Duration = Duration::from_secs(300);
/// Discord's "connected" green (also the speaking ring).
pub const VOICE_GREEN: Color32 = Color32::from_rgb(0x23, 0xa5, 0x5a);
const VOICE_YELLOW: Color32 = Color32::from_rgb(0xf0, 0xb2, 0x32);
const VOICE_RED: Color32 = Color32::from_rgb(0xf2, 0x3f, 0x43);
/// Segoe Fluent Icons used by the voice UI.
pub const SIGNAL: &str = "\u{EC3B}";
pub const HANG_UP: &str = "\u{E778}";
pub const WAVEFORM: &str = "\u{F61F}";
pub const LOCK: &str = "\u{E72E}";

/// Joining: how long Discord gets to give you a working call.
const JOIN_TIMEOUT: Duration = Duration::from_secs(20);
/// Waits before each automatic rejoin after a call dropped (like Discord's client).
const REJOIN_BACKOFF: [Duration; 5] =
    [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(4), Duration::from_secs(8), Duration::from_secs(15)];
/// How long a rejoin waits for Discord to confirm you left before joining anyway.
const LEAVE_WAIT: Duration = Duration::from_secs(3);
/// A call that stayed up this long starts its next drop from the first attempt again.
const STABLE_AFTER: Duration = Duration::from_secs(30);

/// Call generations: each `VoiceConnect` gets a new one and its events carry it, so the
/// last call's late "disconnected" (after a channel switch or a voice server move) can't
/// end the new one.
fn next_gen() -> u64 {
    static GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
    GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}

/// An automatic rejoin in progress: leave (op 4 with no channel), wait for Discord to
/// confirm (it ignores a join for a channel it thinks you're in), then join again.
pub struct Rejoin {
    /// When to send the leave.
    pub due: Instant,
    /// When the leave went out.
    pub left_at: Option<Instant>,
    pub departed: bool,
    pub why: String,
}

/// A DM / group DM call as Discord announced it (CALL_CREATE / CALL_UPDATE).
pub struct DmCall {
    /// Who is still being rung.
    pub ringing: Vec<Id>,
}

pub struct VoiceSession {
    pub guild: Option<Id>,
    pub channel: Id,
    /// Generation of the running call (see `next_gen`).
    pub gen: u64,
    /// When RustCord last asked to join (op 4), for the join timeout.
    pub joined_at: Instant,
    /// Rejoins since the call last stayed up for `STABLE_AFTER`.
    pub attempt: usize,
    pub rejoin: Option<Rejoin>,
    /// A leave RustCord sent itself (rejoin): its "left the channel" update isn't the end.
    pub leave_pending: bool,
    /// When the current connection came up (the call timer keeps `connected_at`).
    pub up_since: Option<Instant>,
    pub session_id: Option<String>,
    /// (token, endpoint) from VOICE_SERVER_UPDATE.
    pub server: Option<(String, String)>,
    /// The call is running on the voice server.
    pub started: bool,
    pub connected: bool,
    pub ping: Option<u32>,
    /// Who is talking right now (user ids).
    pub speaking: HashSet<u64>,
    /// Voice gateway heartbeat round trips (`VoiceEvent::Ping`), oldest first.
    pub pings: VecDeque<(Instant, u32)>,
    /// The connection stats popover is open.
    pub stats_open: bool,
    /// When the call connected (the call view's timer).
    pub connected_at: Option<Instant>,
    /// Where connecting stands (`VoiceEvent::Progress`), shown while not connected.
    pub phase: &'static str,
    /// The main gateway session this call was joined under. A READY for a *new* session
    /// takes the voice session with it (rejoin); the READY of the session RustCord joined
    /// under (joining right after connecting) does not.
    pub gateway_session: Option<String>,
    /// The outgoing bitrate last handed to the call (`voice_bitrate`).
    pub bitrate_sent: Option<u32>,
}

/// The most a voice channel's bitrate counts for at each server boost level, in bit/s
/// (Discord: 96 kbit/s unboosted, 128 / 256 / 384 at levels 1-3; VIP servers 384).
fn bitrate_limit(premium_tier: u8, vip: bool) -> u32 {
    match premium_tier {
        _ if vip => 384_000,
        0 => 96_000,
        1 => 128_000,
        2 => 256_000,
        _ => 384_000,
    }
}

/// Signal colour for a ping, like Discord's: green, yellow from 150 ms, red from 300 ms.
pub fn ping_color(ms: Option<u32>) -> Color32 {
    match ms {
        Some(ms) if ms >= 300 => VOICE_RED,
        Some(ms) if ms >= 150 => VOICE_YELLOW,
        _ => VOICE_GREEN,
    }
}

/// Disconnect reasons that come back identically on every attempt, so an automatic rejoin
/// only costs time: the channel runs without DAVE end-to-end encryption (RustCord joins
/// only encrypted calls), Discord refused the credentials, or the endpoint was unusable.
fn permanent_failure(reason: &str) -> bool {
    reason.contains("encryption was not negotiated")
        || reason.contains("encryption downgrade")
        || reason.contains("Unsupported DAVE protocol version")
        || reason.contains("(4004)")
        || reason.contains("(4001)")
        || reason.contains("(4002)")
        || reason.contains("(4012)")
        || reason.contains("(4016)")
        || reason.contains("(4017)")
        || reason.contains("(4020)")
        || reason.contains("Invalid Discord voice endpoint")
        || reason.contains("outside Discord media")
        || reason.contains("transport encryption is unavailable")
}

/// A permanent failure, said the way a person reads it.
fn explain_failure(reason: &str) -> String {
    if reason.contains("encryption was not negotiated") || reason.contains("encryption downgrade") {
        "this channel isn't running end-to-end encryption (someone in it, often a bot, doesn't support it). RustCord only joins encrypted calls.".into()
    } else {
        reason.to_string()
    }
}

/// "c-lhr09-6118dde8.discord.media:443" → "c-lhr09-6118dde8" (the name Discord shows).
fn endpoint_name(endpoint: &str) -> String {
    let host = endpoint.trim().trim_start_matches("wss://");
    let host = host.split([':', '/']).next().unwrap_or(host);
    host.strip_suffix(".discord.media").unwrap_or(host).to_string()
}

/// Voice & Video choices, saved in `<config>/voice.json` (per device, like Discord's).
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct VoicePrefs {
    /// Chosen microphone (`voice::AudioDevice::id`); `None` follows Windows' default.
    pub input_device: Option<String>,
    /// Its name, shown while it's unplugged.
    pub input_name: Option<String>,
    pub output_device: Option<String>,
    pub output_name: Option<String>,
    /// Microphone volume, 0–100 %.
    pub input_volume: f32,
    /// Speaker volume, 0–200 %.
    pub output_volume: f32,
    /// Input profile: Voice Isolation (noise suppression) or Studio (none).
    pub voice_isolation: bool,
    /// Input Profile → Custom's "Automatic Gain Control"; the other profiles decide it
    /// (on with Voice Isolation, off in Studio), as in Discord.
    pub automatic_gain_control: bool,
    /// Input Profile → Custom's "Echo Cancellation"; the other profiles decide it (on with
    /// Voice Isolation, off in Studio), as in Discord.
    pub echo_cancellation: bool,
    /// "Listen to Microphone": hear your own microphone while a call captures it.
    pub listen_to_mic: bool,
    /// Input sensitivity: the level (dBFS, -70 to 0) above which your microphone is sent.
    pub input_sensitivity: f32,
    /// Chimes on mute, deafen, join and leave (Discord's "Sounds").
    pub sounds: bool,
    /// "User Volume" per person (0–200 %), like Discord's right-click slider.
    pub user_volumes: std::collections::HashMap<u64, f32>,
    /// "Stream Volume" per streamer (0–200 %), kept for their next stream like Discord's.
    pub stream_volumes: std::collections::HashMap<u64, f32>,
    /// People muted for you only (Discord's local "Mute").
    pub local_mutes: HashSet<u64>,
    /// Call view "Show Non-Video Participants".
    pub show_non_video: bool,
    /// Soundboard Volume (0–100 %): how loud sounds play for you.
    pub soundboard_volume: f32,
    /// How often you played each sound (the picker's "Frequently Used").
    pub sound_uses: std::collections::HashMap<u64, u32>,
    /// Input mode: Push to Talk (send only while `ptt_key` is held) instead of
    /// voice activity. The key is a Windows virtual-key code (0: not set yet).
    pub push_to_talk: bool,
    pub ptt_key: u32,
    /// Input Profile → Custom: the processing switches are yours to set.
    pub custom_profile: bool,
    /// Chosen camera (`voice::CameraDevice::id`) and its name; `None`: the first one.
    pub camera_device: Option<String>,
    pub camera_device_name: Option<String>,
    /// Show your picture and ask before the camera is turned on.
    pub always_preview_video: bool,
    /// "Video Hardware Acceleration": streams and cameras encoded and decoded on the GPU.
    pub video_hardware_acceleration: bool,
}

impl Default for VoicePrefs {
    fn default() -> Self {
        // Voice Isolation is Discord's default input profile too.
        Self {
            input_device: None,
            input_name: None,
            output_device: None,
            output_name: None,
            input_volume: 100.0,
            output_volume: 100.0,
            voice_isolation: true,
            automatic_gain_control: true,
            echo_cancellation: true,
            listen_to_mic: false,
            input_sensitivity: voice::SPEAKING_THRESHOLD_DB,
            sounds: true,
            user_volumes: Default::default(),
            stream_volumes: Default::default(),
            local_mutes: Default::default(),
            show_non_video: true,
            soundboard_volume: 100.0,
            sound_uses: Default::default(),
            push_to_talk: false,
            ptt_key: 0,
            custom_profile: false,
            camera_device: None,
            camera_device_name: None,
            always_preview_video: false,
            video_hardware_acceleration: true,
        }
    }
}

impl VoicePrefs {
    fn audio(&self) -> voice::AudioSettings {
        voice::AudioSettings {
            input_device: self.input_device.clone(),
            output_device: self.output_device.clone(),
            input_volume: self.input_volume / 100.0,
            output_volume: self.output_volume / 100.0,
            voice_isolation: self.voice_isolation,
            echo_cancellation: if self.custom_profile { self.echo_cancellation } else { self.voice_isolation },
            automatic_gain_control: if self.custom_profile { self.automatic_gain_control } else { self.voice_isolation },
            listen_to_mic: self.listen_to_mic,
            input_sensitivity_db: self.input_sensitivity,
        }
    }
}

/// One row of a device picker.
pub struct DeviceChoice {
    /// `None`: System Default.
    pub id: Option<String>,
    pub name: Option<String>,
    pub label: String,
    pub selected: bool,
}

/// Voice state outside a call: the preferences, the device list, the mic
/// test and the call view's device menu.
pub struct VoiceUi {
    pub prefs: VoicePrefs,
    /// Microphones and speakers, listed in the background.
    pub devices: Option<voice::AudioDevices>,
    listed_at: Option<Instant>,
    listing: Option<std::sync::mpsc::Receiver<voice::AudioDevices>>,
    pub mic_test: Option<voice::MicTest>,
    /// The mic test meter as drawn (dBFS; falls back smoothly).
    pub meter: f32,
    /// The open voice menu (mic / headphone chevrons, call bar, someone's right-click).
    pub menu: Option<crate::ui::voice_menu::VoiceMenu>,
    /// Frame the call view's control bar was last drawn (its menus close with it).
    pub menu_drawn: u64,
}

impl VoiceUi {
    fn path() -> Option<std::path::PathBuf> {
        directories::ProjectDirs::from("dev", "RustCord", "RustCord").map(|d| d.config_dir().join("voice.json"))
    }

    /// Saved preferences, applied to the voice engine at once.
    pub fn load() -> Self {
        let prefs = Self::path().and_then(|p| std::fs::read_to_string(p).ok()).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
        let ui = Self { prefs, devices: None, listed_at: None, listing: None, mic_test: None, meter: -100.0, menu: None, menu_drawn: 0 };
        ui.apply();
        ui
    }

    /// Hand the preferences to running and future calls (cheap; fine while dragging).
    pub fn apply(&self) {
        voice::set_audio_settings(&self.prefs.audio());
        voice::set_video_hardware_acceleration(self.prefs.video_hardware_acceleration);
        // (Push to Talk without a key yet would mute you for good: voice activity until one is set.)
        crate::hotkey::set_push_to_talk((self.prefs.push_to_talk && self.prefs.ptt_key != 0).then_some(self.prefs.ptt_key));
    }

    /// Apply and save.
    pub fn changed(&self) {
        self.apply();
        let Some(path) = Self::path() else { return };
        if let Some(dir) = path.parent() {
            let _ = std::fs::create_dir_all(dir);
        }
        if let Ok(s) = serde_json::to_string_pretty(&self.prefs) {
            let _ = std::fs::write(path, s);
        }
    }

    /// Keep the device list fresh while something shows it: listed in the
    /// background, again every few seconds (devices come and go).
    pub fn want_devices(&mut self, ctx: &egui::Context) {
        if let Some(rx) = &self.listing {
            match rx.try_recv() {
                Ok(list) => {
                    self.devices = Some(list);
                    self.listing = None;
                }
                Err(std::sync::mpsc::TryRecvError::Empty) => return,
                Err(std::sync::mpsc::TryRecvError::Disconnected) => self.listing = None,
            }
        }
        if self.listed_at.is_some_and(|at| at.elapsed() < Duration::from_secs(5)) {
            return;
        }
        self.listed_at = Some(Instant::now());
        let (tx, rx) = std::sync::mpsc::channel();
        let ctx = ctx.clone();
        let spawned = std::thread::Builder::new().name("rustcord-audio-devices".into()).spawn(move || {
            let _ = tx.send(voice::audio_devices());
            ctx.request_repaint();
        });
        if spawned.is_ok() {
            self.listing = Some(rx);
        }
    }

    /// The picker's current text: "System Default – Speakers (FxSound)" or the device.
    pub fn device_label(&self, input: bool) -> String {
        let (id, name) = if input { (&self.prefs.input_device, &self.prefs.input_name) } else { (&self.prefs.output_device, &self.prefs.output_name) };
        let list = self.devices.as_ref();
        match id {
            None => match list.and_then(|d| if input { d.default_input.clone() } else { d.default_output.clone() }) {
                Some(default) => format!("System Default – {default}"),
                None => "System Default".into(),
            },
            Some(id) => {
                let devices = list.map(|d| if input { &d.inputs } else { &d.outputs });
                match devices.and_then(|l| l.iter().find(|d| d.id == *id)) {
                    Some(d) => d.name.clone(),
                    None if list.is_some() => format!("{} (disconnected)", name.as_deref().unwrap_or("Unknown device")),
                    None => name.clone().unwrap_or_else(|| "Unknown device".into()),
                }
            }
        }
    }

    /// Rows for a microphone / speaker picker: System Default, then each device.
    pub fn device_choices(&self, input: bool) -> Vec<DeviceChoice> {
        let current = if input { &self.prefs.input_device } else { &self.prefs.output_device };
        let default_name = self.devices.as_ref().and_then(|d| if input { d.default_input.clone() } else { d.default_output.clone() });
        let mut out = vec![DeviceChoice {
            id: None,
            name: None,
            label: default_name.map_or_else(|| "System Default".into(), |n| format!("System Default – {n}")),
            selected: current.is_none(),
        }];
        if let Some(d) = &self.devices {
            for dev in if input { &d.inputs } else { &d.outputs } {
                out.push(DeviceChoice { id: Some(dev.id.clone()), name: Some(dev.name.clone()), label: dev.name.clone(), selected: current.as_deref() == Some(dev.id.as_str()) });
            }
        }
        // A chosen device that's unplugged stays listed (and selected).
        if let Some(id) = current.as_ref().filter(|id| !out.iter().any(|c| c.id.as_ref() == Some(*id))) {
            out.push(DeviceChoice { id: Some(id.clone()), name: None, label: self.device_label(input), selected: true });
        }
        out
    }

    /// Pick a microphone / speaker (`None`: System Default); applied to a running call.
    pub fn choose_device(&mut self, input: bool, id: Option<String>, name: Option<String>) {
        let (slot, label) = if input { (&mut self.prefs.input_device, &mut self.prefs.input_name) } else { (&mut self.prefs.output_device, &mut self.prefs.output_name) };
        if *slot == id {
            return;
        }
        *slot = id;
        if name.is_some() || slot.is_none() {
            *label = name;
        }
        self.changed();
    }

    pub fn set_voice_isolation(&mut self, on: bool) {
        if self.prefs.voice_isolation != on {
            self.prefs.voice_isolation = on;
            self.changed();
        }
    }

    pub fn set_sounds(&mut self, on: bool) {
        if self.prefs.sounds != on {
            self.prefs.sounds = on;
            self.changed();
        }
    }

    /// Someone's "User Volume" (percent, 100 unless changed).
    pub fn user_volume(&self, user: Id) -> f32 {
        self.prefs.user_volumes.get(&user.0).copied().unwrap_or(100.0)
    }

    pub fn locally_muted(&self, user: Id) -> bool {
        self.prefs.local_mutes.contains(&user.0)
    }

    /// What the call plays them at (0.0–2.0): their volume, or 0 while muted for you.
    pub fn playback_gain(&self, user: Id) -> f32 {
        if self.locally_muted(user) {
            0.0
        } else {
            self.user_volume(user) / 100.0
        }
    }
}

impl RustCord {
    /// The bitrate to send at in `channel`: its own setting, capped by its server's boost
    /// level, 64 kbit/s where it has none (DM calls).
    fn voice_bitrate(&self, guild: Option<Id>, channel: Id) -> u32 {
        let wanted = self.store.channels.get(&channel).and_then(|c| c.bitrate).unwrap_or(64_000);
        let limit = guild.and_then(|g| self.store.guilds.get(&g)).map_or(u32::MAX, |g| {
            let vip = g.guild.features.as_ref().is_some_and(|f| f.iter().any(|f| f == "VIP_REGIONS"));
            bitrate_limit(g.guild.premium_tier.unwrap_or(0), vip)
        });
        wanted.min(limit).max(8_000)
    }

    /// Discord's voice cue for `cue`, if sounds are on.
    pub fn voice_cue(&mut self, cue: crate::audio::Cue) {
        if self.voice_ui.prefs.sounds && self.prefs.sounds_allowed() && !self.prefs.muted_cues.iter().any(|c| c == cue.name()) {
            self.audio.cue(cue, self.voice_ui.prefs.output_volume / 100.0);
        }
    }

    /// CALL_CREATE / CALL_UPDATE / CALL_DELETE: a call in one of your DMs.
    pub fn call_dispatch(&mut self, name: &str, d: &Value) {
        let Some(channel) = Id::from_value(&d["channel_id"]) else { return };
        if name == "CALL_DELETE" {
            log::info!("call: the call in {channel} ended");
            self.calls.remove(&channel);
            self.dismissed_calls.remove(&channel);
            return;
        }
        // Who is already in it (CALL_CREATE carries their voice states).
        for state in d["voice_states"].as_array().into_iter().flatten() {
            self.store.voice_state_update(state);
        }
        let ringing: Vec<Id> = d["ringing"].as_array().into_iter().flatten().filter_map(Id::from_value).collect();
        let me = self.store.me_id();
        log::info!("call: {name} in {channel}, ringing {} ({})", ringing.len(), if me.is_some_and(|m| ringing.contains(&m)) { "including you" } else { "not you" });
        self.calls.insert(channel, DmCall { ringing });
    }

    /// The DM header's video call button: the call, with the camera on once
    /// you're connected (Windows only, where RustCord has a camera).
    pub fn start_dm_video_call(&mut self, channel: Id) {
        let already_in = self.voice.as_ref().is_some_and(|v| v.channel == channel);
        self.start_dm_call(channel);
        if self.demo {
            return;
        }
        if already_in {
            if self.camera.on.is_none() && !self.camera.pending {
                self.toggle_camera();
            }
        } else {
            self.camera_when_connected = Some(channel);
        }
    }

    /// The DM header's call button: start the call (Discord rings the others once your
    /// side is up), or join / show the one that's running.
    pub fn start_dm_call(&mut self, channel: Id) {
        if self.voice.as_ref().is_some_and(|v| v.channel == channel) {
            self.open_call_view();
            return;
        }
        if self.demo {
            self.toast("Voice needs a real account (this is the demo).", true);
            return;
        }
        let running = self.calls.contains_key(&channel) || self.store.voice.get(&channel).is_some_and(|l| !l.is_empty());
        self.dismissed_calls.remove(&channel);
        if running {
            self.join_voice(channel);
            return;
        }
        // As Discord's client does: ask whether the DM can be rung, then join and ring.
        log::info!("call: asking Discord whether {channel} can be rung");
        self.call_check = Some(channel);
        self.api("call-check", reqwest::Method::GET, format!("/channels/{channel}/call"), None);
    }

    /// Someone is calling: the DM whose call rings you (not one you're in or dismissed).
    pub fn incoming_call(&self) -> Option<Id> {
        let me = self.store.me_id()?;
        let in_voice = self.voice.as_ref().map(|v| v.channel);
        self.calls
            .iter()
            .filter(|(channel, call)| call.ringing.contains(&me) && in_voice != Some(**channel) && !self.dismissed_calls.contains(*channel))
            .map(|(channel, _)| *channel)
            .min()
    }

    /// Answer the call in `channel`.
    pub fn accept_call(&mut self, channel: Id) {
        self.dismissed_calls.remove(&channel);
        self.join_voice(channel);
        self.open_call_view();
    }

    /// Decline: Discord stops ringing this account (the call itself goes on).
    pub fn decline_call(&mut self, channel: Id) {
        log::info!("call: declining the call in {channel}");
        self.dismissed_calls.insert(channel);
        if crate::diagnostics::dev_var_os("RUSTCORD_DEV_CALL").is_some() {
            return;
        }
        self.api("call-stop-ringing", reqwest::Method::POST, format!("/channels/{channel}/call/stop-ringing"), Some(serde_json::json!({})));
    }

    /// A DM shows its call area: a call is running there, or you're in voice there.
    pub fn dm_call_visible(&self, channel: Id) -> bool {
        self.calls.contains_key(&channel) || self.voice.as_ref().is_some_and(|v| v.channel == channel) || self.store.voice.get(&channel).is_some_and(|l| !l.is_empty())
    }

    /// Rings the others once a call you started is connected, and keeps Discord's looping
    /// call sounds going: "ringing" while someone calls you, "calling" while you wait alone
    /// in a call that still rings somebody. Cheap; runs every frame.
    pub fn calls_tick(&mut self) {
        // Developer aid for screenshots: RUSTCORD_DEV_CALL=incoming | outgoing pretends
        // the open DM has a call that rings you / the other person. Nothing is sent.
        if let (Ok(kind), Some(channel), Some(me)) = (crate::diagnostics::dev_var("RUSTCORD_DEV_CALL"), self.current_channel.filter(|_| self.current_guild.is_none()), self.store.me_id()) {
            if !self.calls.contains_key(&channel) && !self.dismissed_calls.contains(&channel) {
                let other = self.store.channels.get(&channel).and_then(|c| c.recipients.first().map(|u| u.id));
                let ringing = if kind == "incoming" { vec![me] } else { other.into_iter().collect() };
                self.calls.insert(channel, DmCall { ringing });
            }
        }
        if let Some(channel) = self.ring_when_connected {
            match self.voice.as_ref() {
                Some(v) if v.channel == channel && v.connected => {
                    self.ring_when_connected = None;
                    log::info!("call: ringing the others in {channel}");
                    self.api("call-ring", reqwest::Method::POST, format!("/channels/{channel}/call/ring"), Some(serde_json::json!({ "recipients": null })));
                }
                Some(v) if v.channel == channel => {}
                _ => self.ring_when_connected = None,
            }
        }
        if let Some(channel) = self.camera_when_connected {
            match self.voice.as_ref() {
                Some(v) if v.channel == channel && v.connected => {
                    self.camera_when_connected = None;
                    if self.camera.on.is_none() && !self.camera.pending {
                        self.toggle_camera();
                    }
                }
                Some(v) if v.channel == channel => {}
                _ => self.camera_when_connected = None,
            }
        }
        if let Some(answer) = self.api_take("call-check") {
            if let Some(channel) = self.call_check.take() {
                match answer {
                    Ok(v) => {
                        let ringable = v["ringable"].as_bool().unwrap_or(false);
                        log::info!("call: {channel} ringable: {ringable}");
                        self.join_voice(channel);
                        if ringable {
                            self.ring_when_connected = Some(channel);
                        }
                    }
                    Err(e) => {
                        log::warn!("call: Discord refused the call in {channel}: {e}");
                        self.toast(format!("You can't call this person: {e}"), true);
                    }
                }
            }
        }
        if let Some(Err(e)) = self.api_take("call-ring") {
            log::warn!("call: ringing failed: {e}");
            self.toast(format!("Couldn't ring: {e}"), true);
        }
        if let Some(Err(e)) = self.api_take("call-stop-ringing") {
            log::warn!("call: declining failed: {e}");
        }
        let calling = self.voice.as_ref().is_some_and(|v| {
            v.guild.is_none() && self.calls.get(&v.channel).is_some_and(|c| !c.ringing.is_empty()) && self.store.voice.get(&v.channel).map_or(0, Vec::len) < 2
        });
        let ring = if !self.voice_ui.prefs.sounds {
            None
        } else if self.incoming_call().is_some() {
            Some(crate::audio::Cue::Ringing)
        } else if calling {
            Some(crate::audio::Cue::Calling)
        } else {
            None
        };
        // (The screenshot aid stays silent: it must not ring into a real call.)
        let ring = ring.filter(|_| crate::diagnostics::dev_var_os("RUSTCORD_DEV_CALL").is_none());
        // Notifications → Sounds: Incoming Ring, and the switch for all sounds.
        let ring = ring.filter(|c| self.prefs.sounds_allowed() && (*c != crate::audio::Cue::Ringing || self.prefs.sound_ring) && !self.prefs.muted_cues.iter().any(|m| m == c.name()));
        self.audio.set_ring(ring, self.voice_ui.prefs.output_volume / 100.0);
    }

    /// Every five seconds while online: what Spotify is playing goes into your
    /// presence ("Listening to Spotify"), like Discord's own client does for a
    /// connected Spotify account. Off with "Share your detected activities".
    pub fn spotify_tick(&mut self) {
        if self.demo || self.conn != crate::app::ConnState::Online || self.spotify_at.is_some_and(|at| at.elapsed() < Duration::from_secs(5)) {
            return;
        }
        let Some(user) = self.store.me_id() else { return };
        self.spotify_at = Some(Instant::now());
        let share = self.discord_setting("show_current_game", true);
        let fresh = std::mem::take(&mut self.spotify_fresh);
        self.backend.send(Command::SpotifyPoll { share, user, fresh });
    }

    /// Put the games' Rich Presence in your presence, unless "Share your detected
    /// activities with others" is off. Only sends when something changed.
    pub fn sync_rpc_presence(&mut self) {
        let share = self.discord_setting("show_current_game", true);
        let now: Vec<(String, serde_json::Value)> = if share { self.rpc_activities.values().cloned().collect() } else { Vec::new() };
        if self.rpc_sent.as_ref() == Some(&now) {
            return;
        }
        // Nothing to clear on a fresh session.
        if self.rpc_sent.is_none() && now.is_empty() {
            self.rpc_sent = Some(now);
            return;
        }
        self.rpc_sent = Some(now.clone());
        self.backend.send(Command::RpcActivities(now));
    }

    /// Set someone's "User Volume" (percent); applied to the call at once, saved on `save`.
    pub fn set_user_volume(&mut self, user: Id, percent: f32, save: bool) {
        let percent = percent.clamp(0.0, 200.0);
        if (percent - 100.0).abs() < 0.5 {
            self.voice_ui.prefs.user_volumes.remove(&user.0);
        } else {
            self.voice_ui.prefs.user_volumes.insert(user.0, percent);
        }
        self.backend.send(Command::VoiceUserVolume { user, volume: self.voice_ui.playback_gain(user) });
        if save {
            self.voice_ui.changed();
        }
    }

    /// Discord's local "Mute": you stop hearing them; nobody else is affected.
    pub fn toggle_local_mute(&mut self, user: Id) {
        if !self.voice_ui.prefs.local_mutes.remove(&user.0) {
            self.voice_ui.prefs.local_mutes.insert(user.0);
        }
        self.backend.send(Command::VoiceUserVolume { user, volume: self.voice_ui.playback_gain(user) });
        self.voice_ui.changed();
    }

    /// Join (or switch to) a voice channel. Clicking the channel you're
    /// already in opens the call view.
    pub fn join_voice(&mut self, channel: Id) {
        // The screenshot aid never touches the account's real voice connection.
        if crate::diagnostics::dev_var_os("RUSTCORD_DEV_CALL").is_some() {
            log::info!("voice: RUSTCORD_DEV_CALL is set; not joining {channel}");
            return;
        }
        if self.demo {
            self.toast("Voice needs a real account (this is the demo).", true);
            return;
        }
        let guild = self.store.channels.get(&channel).and_then(|c| c.guild_id);
        if self.voice.as_ref().is_some_and(|v| v.channel == channel) {
            self.open_call_view();
            return;
        }
        if self.voice.is_some() {
            self.backend.send(Command::VoiceDisconnect);
        }
        self.voice = Some(VoiceSession {
            guild,
            channel,
            gen: next_gen(),
            joined_at: Instant::now(),
            attempt: 0,
            rejoin: None,
            leave_pending: false,
            up_since: None,
            session_id: None,
            server: None,
            started: false,
            connected: false,
            ping: None,
            speaking: HashSet::new(),
            pings: VecDeque::with_capacity(PING_HISTORY),
            stats_open: false,
            connected_at: None,
            phase: "",
            gateway_session: self.store.session_id.clone(),
            bitrate_sent: None,
        });
        // The call's server sends its voice changes one by one from here on,
        // whichever server is open.
        if let Some(guild) = guild {
            self.backend.send(Command::SubscribeGuild(guild));
        }
        // Saved per-person volumes and local mutes ride along with every call.
        let people: HashSet<u64> = self.voice_ui.prefs.user_volumes.keys().chain(self.voice_ui.prefs.local_mutes.iter()).copied().collect();
        for user in people {
            self.backend.send(Command::VoiceUserVolume { user: Id(user), volume: self.voice_ui.playback_gain(Id(user)) });
        }
        log::info!("voice: joining channel {channel} (mute {} deaf {})", self.self_mute, self.self_deaf);
        self.backend.send(Command::VoiceState { guild, channel: Some(channel), mute: self.self_mute, deaf: self.self_deaf });
    }

    /// Show the call you're in: the voice channel's page (a DM call shows the DM).
    pub fn open_call_view(&mut self) {
        let Some((guild, channel)) = self.voice.as_ref().map(|v| (v.guild, v.channel)) else { return };
        self.current_guild = guild;
        self.select_channel(Some(channel));
    }

    pub fn leave_voice(&mut self) {
        self.ring_when_connected = None;
        self.camera_when_connected = None;
        self.end_streams();
        let Some(v) = self.voice.take() else { return };
        log::info!("voice: leaving channel {}", v.channel);
        self.voice_cue(crate::audio::Cue::Leave);
        self.backend.send(Command::VoiceDisconnect);
        self.backend.send(Command::VoiceState { guild: v.guild, channel: None, mute: self.self_mute, deaf: self.self_deaf });
    }

    /// Mute / deafen changed in the user panel.
    pub fn voice_mute_changed(&mut self) {
        if self.voice.is_some() {
            // Deafening mutes too, as in Discord's own voice states.
            log::info!("voice: self mute {} deaf {}", self.self_mute || self.self_deaf, self.self_deaf);
            self.backend.send(Command::VoiceSelfState { mute: self.self_mute || self.self_deaf, deaf: self.self_deaf });
        }
    }

    /// The mic button (user panel, call view): unmuting while deafened
    /// undeafens too, like Discord.
    pub fn toggle_self_mute(&mut self) {
        if self.self_deaf {
            self.self_deaf = false;
            self.self_mute = false;
            self.voice_cue(crate::audio::Cue::Undeafen);
        } else {
            self.self_mute = !self.self_mute;
            self.voice_cue(if self.self_mute { crate::audio::Cue::Mute } else { crate::audio::Cue::Unmute });
        }
        self.voice_mute_changed();
    }

    pub fn toggle_self_deaf(&mut self) {
        self.self_deaf = !self.self_deaf;
        self.voice_cue(if self.self_deaf { crate::audio::Cue::Deafen } else { crate::audio::Cue::Undeafen });
        self.voice_mute_changed();
    }

    /// VOICE_STATE_UPDATE / VOICE_SERVER_UPDATE: your side of the call.
    pub fn voice_dispatch(&mut self, name: &str, d: &Value) {
        let me = self.store.me_id();
        let my_session = self.store.session_id.clone();
        let mut moved = false;
        let Some(v) = self.voice.as_mut() else { return };
        match name {
            "VOICE_STATE_UPDATE" if Id::from_value(&d["user_id"]) == me => {
                // Another of your devices (the official app on your phone…) has its own
                // voice state: only this session's is about this call.
                let session = d["session_id"].as_str();
                let other_device = matches!((session, my_session.as_deref()), (Some(s), Some(mine)) if s != mine);
                if other_device {
                    if Id::from_value(&d["channel_id"]).is_some() && v.connected {
                        // Joined voice elsewhere: Discord moves the call there (like the official app).
                        log::info!("voice: joined on another device; leaving here");
                        self.backend.send(Command::VoiceDisconnect);
                        self.voice = None;
                        self.toast("You joined voice on another device.", false);
                    }
                    return;
                }
                match Id::from_value(&d["channel_id"]) {
                    // RustCord's own leave during a rejoin: not the end of the call.
                    None if v.leave_pending => {
                        v.leave_pending = false;
                        if let Some(r) = v.rejoin.as_mut() {
                            r.departed = true;
                        }
                        return;
                    }
                    // Moved / disconnected by a moderator, or left elsewhere.
                    None => {
                        self.backend.send(Command::VoiceDisconnect);
                        self.voice = None;
                        return;
                    }
                    Some(c) => {
                        // Moved to another channel by someone: Discord's "moved" sound.
                        moved = v.connected && v.channel != c;
                        v.channel = c;
                        if let Some(s) = d["session_id"].as_str() {
                            if v.session_id.is_none() {
                                log::info!("voice: own voice state after {} ms", v.joined_at.elapsed().as_millis());
                            }
                            v.session_id = Some(s.to_string());
                        }
                    }
                }
            }
            "VOICE_SERVER_UPDATE" => {
                let ours = Id::from_value(&d["guild_id"]).map_or(v.guild.is_none(), |g| Some(g) == v.guild);
                if !ours {
                    return;
                }
                // A null endpoint means "wait for the next one".
                if let (Some(token), Some(endpoint)) = (d["token"].as_str(), d["endpoint"].as_str()) {
                    log::info!("voice: voice server {} after {} ms", endpoint_name(endpoint), v.joined_at.elapsed().as_millis());
                    v.server = Some((token.to_string(), endpoint.to_string()));
                    v.started = false;
                } else {
                    log::info!("voice: voice server update without an endpoint (waiting for the next one)");
                }
            }
            _ => return,
        }
        if moved {
            self.voice_cue(crate::audio::Cue::UserMoved);
        }
        self.maybe_start_call();
    }

    fn maybe_start_call(&mut self) {
        let Some(user) = self.store.me_id() else { return };
        let Some(v) = self.voice.as_mut() else { return };
        if v.started {
            return;
        }
        if v.rejoin.is_some() {
            return;
        }
        let (Some(session_id), Some((token, endpoint))) = (v.session_id.clone(), v.server.clone()) else { return };
        v.started = true;
        v.connected = false;
        // The join timeout counts from this connection attempt (a voice server move
        // mid-call starts a new one).
        v.joined_at = Instant::now();
        // A new generation: the call it replaces (voice server move) ends quietly.
        v.gen = next_gen();
        let server = v.guild.unwrap_or(v.channel);
        log::info!("voice: connecting to {} (call {}, {} ms after the join)", endpoint_name(&endpoint), v.gen, v.joined_at.elapsed().as_millis());
        self.backend.send(Command::VoiceConnect { gen: v.gen, user, session_id, token, endpoint, server, channel: v.channel });
    }

    /// The call dropped (or never came up): rejoin automatically, waiting a little longer
    /// each time; after `REJOIN_BACKOFF.len()` tries in a row, give up and say why.
    fn schedule_rejoin(&mut self, why: String) {
        let Some(v) = self.voice.as_mut() else { return };
        if v.attempt >= REJOIN_BACKOFF.len() {
            log::warn!("voice: giving up after {} rejoins: {why}", v.attempt);
            self.toast(format!("Couldn't reconnect to voice: {why}"), true);
            self.leave_voice();
            return;
        }
        let wait = REJOIN_BACKOFF[v.attempt];
        v.attempt += 1;
        let streaming = self.go_live.is_some() || !self.watching.is_empty();
        let Some(v) = self.voice.as_mut() else { return };
        log::info!("voice: rejoin {} in {:?}: {why}", v.attempt, wait);
        // Stop the old call; its late events belong to an old generation.
        v.gen = next_gen();
        v.started = false;
        v.connected = false;
        v.session_id = None;
        v.server = None;
        v.speaking.clear();
        v.rejoin = Some(Rejoin { due: Instant::now() + wait, left_at: None, departed: false, why });
        self.backend.send(Command::VoiceDisconnect);
        // Streams ride on the call: they end with it (rejoin, then share again).
        if streaming {
            self.end_streams();
            self.toast("Voice reconnecting: the stream stopped.", false);
        }
    }

    /// A new gateway session (READY after the old one expired) took the voice
    /// session with it: rejoin the channel you were in.
    pub fn voice_after_ready(&mut self) {
        // Already in voice from another device (or an earlier session)?
        if let Some(me) = self.store.me_id() {
            if let Some((ch, _)) = self.store.voice.iter().find(|(_, users)| users.contains(&me)) {
                log::info!("voice: this account is in voice elsewhere (channel {ch})");
            }
        }
        let same_session = self.voice.as_ref().is_some_and(|v| v.gateway_session.is_some() && v.gateway_session == self.store.session_id);
        if same_session {
            // The READY of the session the join was sent on: the voice state stands.
            return;
        }
        if self.voice.as_ref().is_some_and(|v| v.rejoin.is_none()) {
            if let Some(v) = self.voice.as_mut() {
                // Not a failure of the call itself: don't spend the backoff on it.
                v.attempt = v.attempt.saturating_sub(1);
                v.gateway_session = self.store.session_id.clone();
            }
            self.schedule_rejoin("the connection to Discord was renewed".into());
        }
    }

    /// Drives rejoins and the join timeout; cheap, runs every frame.
    pub fn voice_tick(&mut self) {
        let now = Instant::now();
        // Send at the channel's bitrate, as Discord clients do; it can change mid-call.
        if let Some(v) = self.voice.as_ref() {
            let bitrate = self.voice_bitrate(v.guild, v.channel);
            if v.bitrate_sent != Some(bitrate) {
                self.backend.send(Command::VoiceBitrate(bitrate));
                if let Some(v) = self.voice.as_mut() {
                    v.bitrate_sent = Some(bitrate);
                }
            }
        }
        let mut wake: Option<Duration> = None;
        let mut timed_out = false;
        if let Some(v) = self.voice.as_mut() {
            if let Some(r) = v.rejoin.as_mut() {
                match r.left_at {
                    None if now >= r.due => {
                        r.left_at = Some(now);
                        v.leave_pending = true;
                        self.backend.send(Command::VoiceState { guild: v.guild, channel: None, mute: self.self_mute, deaf: self.self_deaf });
                        wake = Some(Duration::from_millis(200));
                    }
                    None => wake = Some(r.due - now),
                    Some(at) if r.departed || now >= at + LEAVE_WAIT => {
                        log::info!("voice: rejoining ({})", r.why);
                        v.rejoin = None;
                        v.joined_at = now;
                        self.backend.send(Command::VoiceState { guild: v.guild, channel: Some(v.channel), mute: self.self_mute, deaf: self.self_deaf });
                        wake = Some(Duration::from_millis(500));
                    }
                    Some(_) => wake = Some(Duration::from_millis(200)),
                }
            } else if !v.connected {
                if now >= v.joined_at + JOIN_TIMEOUT {
                    timed_out = true;
                } else {
                    wake = Some(v.joined_at + JOIN_TIMEOUT - now);
                }
            } else if v.attempt > 0 && v.up_since.is_some_and(|at| now >= at + STABLE_AFTER) {
                v.attempt = 0;
            }
        }
        if timed_out {
            let why = match self.voice.as_ref() {
                Some(v) if v.session_id.is_none() => "Discord didn't answer the join (no permission, or the channel is full?)",
                Some(v) if v.server.is_none() => "Discord didn't assign a voice server",
                _ => "the voice server didn't answer",
            };
            self.schedule_rejoin(why.to_string());
            wake = Some(Duration::from_millis(500));
        }
        if let Some(w) = wake {
            self.ctx.request_repaint_after(w.max(Duration::from_millis(16)));
        }
    }

    pub fn on_voice_event(&mut self, gen: u64, e: voice::VoiceEvent) {
        let Some(v) = self.voice.as_mut() else { return };
        // A call RustCord already replaced or stopped.
        if gen != v.gen {
            return;
        }
        match e {
            voice::VoiceEvent::Connected => {
                log::info!("voice: connected (call {gen}) {} ms after the join", v.joined_at.elapsed().as_millis());
                v.connected = true;
                let first = v.connected_at.is_none();
                v.connected_at.get_or_insert_with(Instant::now);
                v.up_since = Some(Instant::now());
                if first {
                    self.voice_cue(crate::audio::Cue::Join);
                }
            }
            voice::VoiceEvent::Speaking { user_id, speaking } => {
                if speaking {
                    v.speaking.insert(user_id);
                } else {
                    v.speaking.remove(&user_id);
                }
            }
            voice::VoiceEvent::Ping(ms) => {
                v.ping = Some(ms);
                if v.pings.len() >= PING_HISTORY {
                    v.pings.pop_front();
                }
                v.pings.push_back((Instant::now(), ms));
            }
            voice::VoiceEvent::Progress(phase) => {
                log::info!("voice: {phase} (call {gen}, {} ms after the join)", v.joined_at.elapsed().as_millis());
                v.phase = phase;
            }
            // Others coming and going, once you're in (the roster at join time is silent).
            // (Discord stays quiet in channels of more than 25 people.)
            voice::VoiceEvent::UserJoined(_) | voice::VoiceEvent::UserLeft(_) if v.connected => {
                let people = self.store.voice.get(&v.channel).map_or(0, Vec::len);
                if people <= 25 {
                    self.voice_cue(if matches!(e, voice::VoiceEvent::UserJoined(_)) { crate::audio::Cue::UserJoin } else { crate::audio::Cue::UserLeave });
                }
            }
            voice::VoiceEvent::UserJoined(_) | voice::VoiceEvent::UserLeft(_) => {}
            voice::VoiceEvent::Disconnected { reason } => {
                log::info!("voice: disconnected ({reason:?}, call {gen})");
                match reason {
                    // RustCord stopped it itself.
                    None => {}
                    // Discord ended this device's call on purpose (moved to another device,
                    // disconnected by a moderator, channel deleted): don't fight it.
                    Some(r) if r.contains("disconnected this device") => {
                        let channel = v.channel;
                        self.voice = None;
                        self.voice_cue(crate::audio::Cue::Leave);
                        self.toast(format!("Voice disconnected: {r}"), true);
                        let guild = self.store.channels.get(&channel).and_then(|c| c.guild_id);
                        self.backend.send(Command::VoiceState { guild, channel: None, mute: self.self_mute, deaf: self.self_deaf });
                    }
                    // A failure that a rejoin can't fix (the channel can't be joined the way
                    // RustCord joins calls): say so at once instead of retrying for a minute.
                    Some(r) if permanent_failure(&r) => {
                        log::warn!("voice: not retrying: {r}");
                        self.toast(format!("Couldn't join voice: {}", explain_failure(&r)), true);
                        self.leave_voice();
                    }
                    // Everything else (server restart, timeouts, network change…): rejoin.
                    Some(r) => self.schedule_rejoin(r),
                }
            }
        }
    }

    /// Is `user` talking in the call you're in?
    pub fn is_speaking(&self, user: Id) -> bool {
        self.voice.as_ref().is_some_and(|v| v.speaking.contains(&user.0))
    }

    /// Discord's "Voice Connected" box: status (hover for the ping, click for
    /// the connection stats), channel / server (click for the call view),
    /// voice isolation and disconnect. Returns true if it drew something.
    pub fn voice_panel(&mut self, ui: &mut Ui, t: &Theme) -> bool {
        let Some(v) = self.voice.as_ref() else { return false };
        let (connected, ping, stats_open) = (v.connected, v.ping, v.stats_open);
        let rejoining = v.rejoin.is_some() || v.attempt > 0 && !connected;
        let channel = self.store.channels.get(&v.channel).map(crate::store::Store::channel_label).unwrap_or_default();
        // Discord: "channel / server", and for a DM call just "@name".
        let place_line = match v.guild.and_then(|g| self.store.guilds.get(&g)) {
            Some(g) => format!("{channel} / {}", g.guild.name),
            None => format!("@{channel}"),
        };
        let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), Sense::hover());
        let phase = v.phase;
        let (label, color) = if connected {
            ("Voice Connected", ping_color(ping))
        } else if rejoining {
            ("Reconnecting…", VOICE_YELLOW)
        } else if phase == "securing" {
            ("Securing…", VOICE_YELLOW)
        } else {
            ("RTC Connecting…", VOICE_YELLOW)
        };
        let bold = FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into()));
        let label_w = ui.painter().layout_no_wrap(label.into(), bold.clone(), color).size().x;
        let status = Rect::from_min_size(pos2(rect.left(), rect.top() + 1.0), vec2(label_w + 30.0, 22.0));
        let sresp = ui.interact(status, egui::Id::new("voice_status"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
        if sresp.hovered() || stats_open {
            ui.painter().rect_filled(status, 4.0, t.bg_hover);
        }
        ui.painter().text(pos2(status.left() + 12.0, status.center().y), Align2::CENTER_CENTER, SIGNAL, icon_font(13.0), color);
        ui.painter().text(pos2(status.left() + 24.0, status.center().y), Align2::LEFT_CENTER, label, bold, color);
        let tip = match ping {
            Some(ms) => format!("{ms} ms"),
            None => "Measuring ping…".into(),
        };
        let sresp = if stats_open { sresp } else { sresp.on_hover_text(tip) };
        let toggle_stats = sresp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
        // Channel / server: opens the call view.
        let line = Rect::from_min_max(pos2(rect.left(), rect.top() + 24.0), pos2(rect.right() - 76.0, rect.bottom()));
        let lresp = ui.interact(line, egui::Id::new("voice_channel_line"), Sense::click());
        let fg = if lresp.hovered() { t.interactive_hover } else { t.text_muted };
        let p = ui.painter_at(line);
        let text = p.text(pos2(line.left() + 6.0, line.center().y), Align2::LEFT_CENTER, place_line, FontId::proportional(12.5), fg);
        if lresp.hovered() {
            p.hline(text.x_range(), text.bottom() - 1.0, Stroke::new(1.0_f32, fg));
        }
        let open_view = lresp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text("Open the call").clicked();
        // Voice isolation, then hang up.
        let iso_on = self.voice_ui.prefs.voice_isolation;
        let iso = Rect::from_center_size(pos2(rect.right() - 52.0, rect.center().y), vec2(32.0, 32.0));
        let iresp = ui.interact(iso, egui::Id::new("voice_isolation_toggle"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
        if iresp.hovered() {
            ui.painter().rect_filled(iso, 6.0, t.bg_hover);
        }
        let ic = if iresp.hovered() { t.header_primary } else { t.interactive_normal };
        ui.painter().text(iso.center(), Align2::CENTER_CENTER, WAVEFORM, icon_font(16.0), ic);
        if !iso_on {
            ui.painter().line_segment([iso.center() + vec2(-8.0, -8.0), iso.center() + vec2(8.0, 8.0)], Stroke::new(2.0_f32, ic));
        }
        let tip = if iso_on { "Voice Isolation: on (click for Studio, no processing)" } else { "Voice Isolation: off (click to cut background noise)" };
        if iresp.on_hover_text(tip).clicked() {
            self.voice_ui.set_voice_isolation(!iso_on);
        }
        let hang = Rect::from_center_size(pos2(rect.right() - 18.0, rect.center().y), vec2(32.0, 32.0));
        let resp = ui.interact(hang, egui::Id::new("voice_hangup"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
        if resp.hovered() {
            ui.painter().rect_filled(hang, 6.0, t.bg_hover);
        }
        ui.painter().text(hang.center(), Align2::CENTER_CENTER, HANG_UP, icon_font(17.0), if resp.hovered() { t.header_primary } else { t.interactive_normal });
        if resp.on_hover_text("Disconnect").clicked() {
            self.leave_voice();
            return true;
        }
        // Discord's row of call buttons under it: camera, Share Your Screen and the
        // Soundboard (Activities aren't in RustCord, so they aren't shown).
        ui.add_space(4.0);
        let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::hover());
        let w = (row.width() - 16.0) / 3.0;
        let cam = Rect::from_min_size(row.min, vec2(w, 32.0));
        let cr = ui.interact(cam, egui::Id::new("voice_panel_camera"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
        let cam_on = self.camera.on.is_some();
        let cam_ready = self.voice.as_ref().is_some_and(|v| v.connected);
        let fill = if cam_on { VOICE_GREEN } else { crate::ui::soundboard::button_fill(self.camera.pending, cr.hovered(), t) };
        ui.painter().rect_filled(cam, 8.0, fill);
        ui.painter().rect_stroke(cam, 8.0, Stroke::new(1.0_f32, rgba(151, 151, 159, 10)));
        let fg = if cam_on { Color32::WHITE } else if cam_ready { t.header_primary } else { t.text_muted };
        ui.painter().text(cam.center(), Align2::CENTER_CENTER, crate::camera::CAMERA, icon_font(18.0), fg);
        let tip = if cam_on { "Turn Off Camera" } else if self.camera.pending { "Starting your camera…" } else if cam_ready { "Turn On Camera" } else { "Turn On Camera (once you're connected)" };
        let camera_clicked = cr.on_hover_text(tip).clicked() && cam_ready;
        let live = self.go_live.is_some();
        let can_share = live || self.can_go_live();
        let share = Rect::from_min_size(pos2(cam.right() + 8.0, row.top()), vec2(w, 32.0));
        let sr = ui.interact(share, egui::Id::new("voice_panel_share"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
        let fill = if live { crate::golive::LIVE_RED } else { crate::ui::soundboard::button_fill(false, sr.hovered(), t) };
        ui.painter().rect_filled(share, 8.0, fill);
        ui.painter().rect_stroke(share, 8.0, Stroke::new(1.0_f32, rgba(151, 151, 159, 10)));
        let fg = if live { Color32::WHITE } else if can_share { t.header_primary } else { t.text_muted };
        ui.painter().text(share.center(), Align2::CENTER_CENTER, crate::golive::SCREEN, icon_font(18.0), fg);
        let tip = if live { "Stop Streaming" } else if can_share { "Share Your Screen" } else { "Share Your Screen (once you're connected)" };
        let share_clicked = sr.on_hover_text(tip).clicked();
        let sb = Rect::from_min_size(pos2(share.right() + 8.0, row.top()), vec2(w, 32.0));
        let br = ui.interact(sb, egui::Id::new("voice_panel_soundboard"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
        let sb_open = self.soundboard_open();
        ui.painter().rect_filled(sb, 8.0, crate::ui::soundboard::button_fill(sb_open, br.hovered(), t));
        ui.painter().rect_stroke(sb, 8.0, Stroke::new(1.0_f32, rgba(151, 151, 159, 10)));
        ui.painter().text(sb.center(), Align2::CENTER_CENTER, crate::ui::soundboard::SOUNDBOARD, icon_font(18.0), t.header_primary);
        self.soundboard_anchor(sb);
        if br.on_hover_text("Open Soundboard").clicked() {
            self.toggle_soundboard(sb);
        }
        if share_clicked {
            if live {
                self.stop_go_live();
            } else {
                self.open_share_picker();
            }
        }
        if camera_clicked {
            self.toggle_camera();
        }
        if open_view {
            self.open_call_view();
        }
        if let Some(v) = self.voice.as_mut() {
            if toggle_stats {
                v.stats_open = !v.stats_open;
            }
            if v.stats_open {
                self.voice_stats_popover(ui.ctx(), t, rect, status);
            }
        }
        true
    }

    /// Discord's connection stats (click "Voice Connected"): ping over the last
    /// minutes, the voice server, average / last ping and the encryption.
    fn voice_stats_popover(&mut self, ctx: &egui::Context, t: &Theme, panel: Rect, status: Rect) {
        let Some(v) = self.voice.as_ref() else { return };
        let pings: Vec<(Instant, u32)> = v.pings.iter().copied().collect();
        let server = v.server.as_ref().map(|(_, e)| endpoint_name(e)).filter(|s| !s.is_empty());
        let (connected, last) = (v.connected, v.ping);
        let average = (!pings.is_empty()).then(|| pings.iter().map(|(_, ms)| u64::from(*ms)).sum::<u64>() / pings.len() as u64);
        let area = egui::Area::new(egui::Id::new("voice_stats"))
            .order(Order::Foreground)
            .pivot(Align2::LEFT_BOTTOM)
            .fixed_pos(pos2(panel.left() - 6.0, panel.top() - 14.0))
            .sized_off_screen(ctx)
            .show(ctx, |ui| {
                Frame::none()
                    .fill(t.bg_floating)
                    .rounding(10.0)
                    .stroke(Stroke::new(1.0_f32, t.border_subtle))
                    .shadow(egui::epaint::Shadow { offset: vec2(0.0, 6.0), blur: 20.0, spread: 0.0, color: Color32::from_black_alpha(120) })
                    .inner_margin(Margin::same(12.0))
                    .show(ui, |ui| {
                        ui.set_width(276.0);
                        ui.spacing_mut().item_spacing.y = 2.0;
                        ping_graph(ui, t, &pings);
                        ui.add_space(10.0);
                        let title = server.unwrap_or_else(|| "Voice server".into());
                        ui.label(RichText::new(title).font(FontId::new(15.0, egui::FontFamily::Name(crate::style::BOLD.into()))).color(t.header_primary));
                        ui.add_space(2.0);
                        let ms = |v: Option<u64>| v.map_or_else(|| "–".to_string(), |v| format!("{v} ms"));
                        for (name, value) in [("Average ping", ms(average)), ("Last ping", ms(last.map(u64::from)))] {
                            ui.horizontal(|ui| {
                                ui.spacing_mut().item_spacing.x = 4.0;
                                ui.label(RichText::new(format!("{name}:")).size(13.0).color(t.text_muted));
                                ui.label(RichText::new(value).size(13.0).color(t.text_normal));
                            });
                        }
                        ui.add_space(6.0);
                        ui.add(egui::Label::new(RichText::new("You may notice delayed audio at 250 ms or higher. If it doesn't settle, disconnect and join again.").size(12.0).color(t.text_muted)).wrap());
                        ui.add_space(8.0);
                        let y = ui.cursor().top();
                        ui.painter().hline(ui.max_rect().x_range(), y, Stroke::new(1.0_f32, t.border_subtle));
                        ui.add_space(8.0);
                        let (glyph_color, title, sub) = if connected {
                            (VOICE_GREEN, "Secure Connection", "End-to-end encrypted (DAVE): only people in the call can hear it.")
                        } else {
                            (t.text_muted, "Securing connection…", "Setting up end-to-end encryption (DAVE).")
                        };
                        ui.horizontal(|ui| {
                            ui.spacing_mut().item_spacing.x = 6.0;
                            ui.label(RichText::new(LOCK).font(icon_font(13.0)).color(glyph_color));
                            ui.label(RichText::new(title).size(13.0).color(glyph_color));
                        });
                        ui.add(egui::Label::new(RichText::new(sub).size(12.0).color(t.text_muted)).wrap());
                    });
            });
        // Click elsewhere or Escape closes it (the status line toggles it itself).
        let outside = ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !area.response.rect.contains(p) && !status.contains(p)));
        if outside || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
            if let Some(v) = self.voice.as_mut() {
                v.stats_open = false;
            }
        }
    }
}

/// Ping over the last five minutes: a green line with a soft fill, ms on the
/// right, clock times underneath.
fn ping_graph(ui: &mut Ui, t: &Theme, pings: &[(Instant, u32)]) {
    let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 104.0), Sense::hover());
    let p = ui.painter_at(rect);
    p.rect_filled(rect, 8.0, t.bg_tertiary);
    let plot = Rect::from_min_max(rect.min + vec2(10.0, 10.0), rect.max - vec2(30.0, 22.0));
    let small = FontId::proportional(10.5);
    let peak = pings.iter().map(|(_, ms)| *ms).max().unwrap_or(0);
    // A round top: 20, 40, 60, 80, 100, 150, 200, 300, 400, 500, 1000…
    let top = [20u32, 40, 60, 80, 100, 150, 200, 300, 400, 500, 1000, 2000, 5000].into_iter().find(|v| *v >= peak).unwrap_or(peak.max(1));
    for (frac, value) in [(0.0, 0), (0.5, top / 2), (1.0, top)] {
        let y = plot.bottom() - frac * plot.height();
        p.hline(plot.x_range(), y, Stroke::new(1.0_f32, t.border_subtle));
        p.text(pos2(rect.right() - 8.0, y), Align2::RIGHT_CENTER, value.to_string(), small.clone(), t.text_muted);
    }
    let now = Instant::now();
    let window = GRAPH_WINDOW.as_secs_f32();
    let x_at = |ago: f32| plot.right() - ago / window * plot.width();
    // Every other whole minute under the graph, in the app's clock format.
    let wall = chrono::Local::now();
    let into_minute = f32::from(chrono::Timelike::second(&wall) as u8);
    for k in 0..5 {
        let ago = into_minute + 60.0 * k as f32;
        let x = x_at(ago);
        if x < plot.left() + 20.0 {
            break;
        }
        let at = wall - chrono::Duration::seconds(ago as i64);
        if chrono::Timelike::minute(&at) % 2 != 0 || x > plot.right() - 16.0 {
            continue;
        }
        let label = at.format(crate::ui::time_fmt()).to_string();
        let label = label.strip_prefix('0').unwrap_or(&label);
        p.text(pos2(x, plot.bottom() + 11.0), Align2::CENTER_CENTER, label, small.clone(), t.text_muted);
    }
    let points: Vec<egui::Pos2> = pings
        .iter()
        .map(|(at, ms)| (now.saturating_duration_since(*at).as_secs_f32(), *ms))
        .filter(|(ago, _)| *ago <= window)
        .map(|(ago, ms)| pos2(x_at(ago), plot.bottom() - (ms as f32 / top as f32).min(1.0) * plot.height()))
        .collect();
    match points.len() {
        0 => {
            p.text(plot.center(), Align2::CENTER_CENTER, "Measuring…", FontId::proportional(12.0), t.text_muted);
        }
        1 => {
            p.circle_filled(points[0], 3.0, VOICE_GREEN);
        }
        _ => {
            // Soft fill under the line (fades towards the baseline).
            let mut mesh = egui::Mesh::default();
            let (high, low) = (rgba(0x23, 0xa5, 0x5a, 70), rgba(0x23, 0xa5, 0x5a, 0));
            for pt in &points {
                mesh.colored_vertex(*pt, high);
                mesh.colored_vertex(pos2(pt.x, plot.bottom()), low);
            }
            for i in 0..points.len() as u32 - 1 {
                let k = i * 2;
                mesh.add_triangle(k, k + 1, k + 2);
                mesh.add_triangle(k + 1, k + 2, k + 3);
            }
            p.add(egui::Shape::mesh(mesh));
            p.add(egui::Shape::line(points.clone(), Stroke::new(2.0_f32, VOICE_GREEN)));
            if let Some(last) = points.last() {
                p.circle_filled(*last, 3.0, VOICE_GREEN);
            }
        }
    }
}

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

    #[test]
    fn endpoint_names_match_discords() {
        assert_eq!(endpoint_name("c-lhr09-6118dde8.discord.media:443"), "c-lhr09-6118dde8");
        assert_eq!(endpoint_name("wss://rotterdam1234.discord.media"), "rotterdam1234");
        assert_eq!(ping_color(Some(23)), VOICE_GREEN);
        assert_eq!(ping_color(Some(400)), VOICE_RED);
    }

    #[test]
    fn only_deterministic_failures_skip_the_rejoin() {
        assert!(permanent_failure("Required DAVE version 1 encryption was not negotiated"));
        assert!(permanent_failure("Discord requested a voice encryption downgrade; call stopped"));
        assert!(permanent_failure("Discord voice authentication failed; the voice token is invalid (4004)"));
        assert!(!permanent_failure("Voice connection timed out"));
        assert!(!permanent_failure("Discord voice session timed out; rejoin the call (4009)"));
        assert!(!permanent_failure("Discord voice connection closed; rejoin the call"));
        assert!(explain_failure("Required DAVE version 1 encryption was not negotiated").contains("end-to-end"));
        assert_eq!(explain_failure("Voice UDP send failed"), "Voice UDP send failed");
    }

    #[test]
    fn prefs_survive_missing_fields_and_map_to_gains() {
        let p: VoicePrefs = serde_json::from_str(r#"{"output_volume": 150}"#).unwrap();
        assert!(p.voice_isolation && p.input_device.is_none() && p.sounds);
        let a = p.audio();
        assert_eq!((a.input_volume, a.output_volume), (1.0, 1.5));
        // Echo Cancellation: on with Voice Isolation (the default), off in Studio, and
        // Custom's own switch.
        assert!(a.echo_cancellation);
        let studio = VoicePrefs { voice_isolation: false, ..p.clone() };
        assert!(!studio.audio().echo_cancellation);
        let custom = VoicePrefs { custom_profile: true, voice_isolation: false, echo_cancellation: true, ..p };
        assert!(custom.audio().echo_cancellation);
    }
}