Skip to content

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

58.4 KB
Raw Blame
//! Go Live: sharing your screen in a voice call, and watching other people's.
//!
//! Discord's flow (main gateway): op 18 STREAM_CREATE asks to stream, op 20
//! STREAM_WATCH asks to watch someone, op 19 STREAM_DELETE stops either. Discord
//! answers with STREAM_CREATE (the stream's `rtc_server_id` / `rtc_channel_id`)
//! and STREAM_SERVER_UPDATE (token, endpoint); with your call's voice session
//! those make a second voice connection that carries the video (the `voice`
//! crate's `start_stream` / `watch_stream`). STREAM_UPDATE lists viewers;
//! STREAM_DELETE ends it. Who is live comes from `self_stream` in voice states.

use crate::app::RustCord;
use crate::backend::Command;
use crate::style::{icon_font, overlay, Theme};
use discord::model::Id;
use eframe::egui::{self, pos2, vec2, Align2, Color32, CursorIcon, FontId, Frame, Margin, Order, Rect, RichText, Rounding, Sense, Stroke, Ui};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Segoe Fluent "screen" (share) and full-screen glyphs.
pub const SCREEN: &str = "\u{E7F4}";
pub const FULLSCREEN: &str = "\u{E740}";
pub const EXIT_FULLSCREEN: &str = "\u{E73F}";
/// Discord's LIVE red.
pub const LIVE_RED: Color32 = Color32::from_rgb(0xed, 0x42, 0x45);
/// How long Discord gets to set a stream up.
const SETUP_TIMEOUT: Duration = Duration::from_secs(25);
/// How many streams you can watch at once (each is its own video connection
/// and decoder, so RustCord keeps it to a few).
pub const MAX_WATCHING: usize = 4;

/// Stream generations (events of a stopped stream are ignored).
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)
}

/// "guild:<guild>:<channel>:<user>", or "call:<channel>:<user>" in a DM call.
pub fn stream_key(guild: Option<Id>, channel: Id, user: Id) -> String {
    match guild {
        Some(g) => format!("guild:{g}:{channel}:{user}"),
        None => format!("call:{channel}:{user}"),
    }
}

/// Discord's STREAM_DELETE reasons, said the way the official app says them.
fn delete_reason(reason: Option<&str>) -> Option<&'static str> {
    Some(match reason? {
        "stream_full" => "The stream is full.",
        "unauthorized" => "You don't have permission to stream here.",
        "user_requested" => return None,
        "stream_ended" => "The stream ended.",
        "user_moved" | "user_disconnected" => return None,
        _ => "The stream ended.",
    })
}

/// The second voice connection's credentials, as they arrive.
#[derive(Default)]
struct Setup {
    /// (rtc_server_id, rtc_channel_id) from STREAM_CREATE.
    rtc: Option<(u64, u64)>,
    /// (token, endpoint) from STREAM_SERVER_UPDATE.
    server: Option<(String, String)>,
    started: bool,
}

/// Your own Go Live.
pub struct GoLive {
    pub key: String,
    pub channel: Id,
    pub source: voice::ScreenSource,
    pub quality: voice::StreamQuality,
    pub audio: bool,
    setup: Setup,
    pub gen: u64,
    pub connected: bool,
    pub handle: Option<Arc<voice::StreamHandle>>,
    pub viewers: Vec<Id>,
    requested_at: Instant,
    /// Your own picture on your tile.
    pub preview: Option<egui::TextureHandle>,
    preview_seq: u64,
}

/// Someone's stream you're watching.
pub struct Watching {
    pub key: String,
    pub streamer: Id,
    pub channel: Id,
    setup: Setup,
    pub gen: u64,
    pub connected: bool,
    pub handle: Option<Arc<voice::WatchHandle>>,
    requested_at: Instant,
    pub frame: Option<egui::TextureHandle>,
    seq: u64,
    pub size: (u32, u32),
    pub volume: f32,
    pub fullscreen: bool,
    /// Who else is watching (STREAM_CREATE / STREAM_UPDATE `viewer_ids`).
    pub viewers: Vec<Id>,
}

/// Go Live bits of the UI that aren't a stream themselves.
#[derive(Default)]
pub struct GoLiveUi {
    /// The channel list's "Streaming Now" card: (streamer, voice channel,
    /// where, last frame the row or the card was hovered).
    pub card: Option<(Id, Id, egui::Pos2, u64)>,
    /// Stream preview pictures by stream key: (asked at, picture URL).
    pub previews: HashMap<String, (Instant, Option<String>)>,
    /// Watch this person once the call you're joining is up.
    pub pending_watch: Option<(Id, Id)>,
    /// The voice channel's text chat is open beside the call.
    pub chat_open: bool,
    /// The stream on the stage (clicked last), whose volume and full screen
    /// the call bar has; None: the first one.
    pub focused: Option<Id>,
    /// Discord's grid view: no stage, every tile the same size, the streams
    /// you watch playing in theirs.
    pub stream_grid: bool,
}

/// What happened to one stream on the stage this frame.
#[derive(Default)]
struct StreamCell {
    double_clicked: bool,
    close: bool,
    menu_at: Option<egui::Pos2>,
}

/// The "Screen Share" picker: monitors and windows with thumbnails, quality, audio.
pub struct SharePicker {
    sources: Option<Result<Vec<voice::ScreenSource>, String>>,
    rx: std::sync::mpsc::Receiver<PickerMsg>,
    thumbs: HashMap<String, egui::TextureHandle>,
    windows_tab: bool,
    selected: Option<String>,
    quality: voice::StreamQuality,
    audio: bool,
    opened: u64,
}

enum PickerMsg {
    Sources(Result<Vec<voice::ScreenSource>, String>),
    Thumb(String, voice::VideoFrame),
}

/// Copy a frame into a texture (a video frame is opaque, so straight RGBA is
/// already "premultiplied").
pub(crate) fn upload(ctx: &egui::Context, slot: &mut Option<egui::TextureHandle>, name: &str, f: &voice::VideoFrame) {
    let (w, h) = (f.width as usize, f.height as usize);
    if w == 0 || h == 0 || f.rgba.len() < w * h * 4 {
        return;
    }
    // Opaque RGBA bytes are already Color32's layout: one memcpy, not a
    // per-pixel conversion (a 1440p frame is 14.7 MB, many times a second).
    let pixels: Vec<Color32> = bytemuck::cast_slice::<u8, Color32>(&f.rgba[..w * h * 4]).to_vec();
    let img = egui::ColorImage { size: [w, h], pixels };
    match slot {
        Some(t) => t.set(img, egui::TextureOptions::LINEAR),
        None => *slot = Some(ctx.load_texture(name, img, egui::TextureOptions::LINEAR)),
    }
}

/// `inner` fitted into `outer` keeping its aspect ratio, centred.
fn fit(outer: Rect, w: f32, h: f32) -> Rect {
    let scale = (outer.width() / w.max(1.0)).min(outer.height() / h.max(1.0));
    Rect::from_center_size(outer.center(), vec2(w * scale, h * scale))
}

/// Discord's red "LIVE" pill; returns its width.
pub fn paint_live(p: &egui::Painter, left_center: egui::Pos2, size: f32) -> f32 {
    let font = FontId::new(size, egui::FontFamily::Name(crate::style::BOLD.into()));
    let g = p.layout_no_wrap("LIVE".into(), font, Color32::WHITE);
    let r = Rect::from_min_size(pos2(left_center.x, left_center.y - g.size().y / 2.0 - 2.0), g.size() + vec2(10.0, 4.0));
    p.rect_filled(r, 4.0, LIVE_RED);
    p.galley(r.min + vec2(5.0, 2.0), g, Color32::WHITE);
    r.width()
}

impl RustCord {
    // ---- your stream ------------------------------------------------------------

    /// The call you're in can be shared from (connected, not already live).
    pub fn can_go_live(&self) -> bool {
        self.voice.as_ref().is_some_and(|v| v.connected) && self.go_live.is_none()
    }

    pub fn open_share_picker(&mut self) {
        if !self.can_go_live() {
            return;
        }
        let (tx, rx) = std::sync::mpsc::channel();
        let ctx = self.ctx.clone();
        // Listing windows and grabbing a still of each takes a moment: off the UI thread.
        let _ = std::thread::Builder::new().name("rustcord-share-sources".into()).spawn(move || {
            let sources = voice::screen_sources();
            let list = sources.clone().unwrap_or_default();
            let _ = tx.send(PickerMsg::Sources(sources));
            ctx.request_repaint();
            for s in list {
                if let Some(f) = voice::screen_thumbnail(&s, 320) {
                    if tx.send(PickerMsg::Thumb(s.id.clone(), f)).is_err() {
                        return;
                    }
                    ctx.request_repaint();
                }
            }
        });
        self.share_picker = Some(SharePicker {
            sources: None,
            rx,
            thumbs: HashMap::new(),
            windows_tab: false,
            selected: None,
            // Discord's defaults: 1080p60 with Nitro, 720p30 without.
            quality: if self.store.me.as_ref().and_then(|u| u.premium_type).is_some_and(|p| p > 0) {
                voice::StreamQuality { max_height: 1080, fps: 60 }
            } else {
                voice::StreamQuality { max_height: 720, fps: 30 }
            },
            audio: true,
            opened: self.ctx.cumulative_pass_nr(),
        });
    }

    /// Op 18: ask Discord for a stream in the call you're in.
    fn start_go_live(&mut self, source: voice::ScreenSource, quality: voice::StreamQuality, audio: bool) {
        let Some(me) = self.store.me_id() else { return };
        let Some((guild, channel)) = self.voice.as_ref().filter(|v| v.connected).map(|v| (v.guild, v.channel)) else {
            self.toast("Join a voice channel to stream.", true);
            return;
        };
        let key = stream_key(guild, channel, me);
        log::info!("go live: requesting {key}");
        self.backend.send(Command::StreamCreate { guild, channel });
        self.go_live = Some(GoLive {
            key,
            channel,
            source,
            quality,
            audio,
            setup: Setup::default(),
            gen: next_gen(),
            connected: false,
            handle: None,
            viewers: Vec::new(),
            requested_at: Instant::now(),
            preview: None,
            preview_seq: 0,
        });
    }

    pub fn stop_go_live(&mut self) {
        let Some(g) = self.go_live.take() else { return };
        log::info!("go live: stopping {}", g.key);
        if let Some(h) = &g.handle {
            h.stop();
        }
        self.backend.send(Command::StreamDelete(g.key));
    }

    // ---- watching ---------------------------------------------------------------

    /// The stream that gets the big stage, the call bar's volume and full screen:
    /// the one picked last (or the first one, once that ends).
    pub fn focused_watch(&self) -> Option<&Watching> {
        let focused = self.golive_ui.focused;
        self.watching.iter().find(|w| Some(w.streamer) == focused).or(self.watching.first())
    }

    /// Op 20: watch `streamer`'s stream in the call you're in. Discord's rule:
    /// with two or more others live in the call it plays beside the streams
    /// already open (up to `MAX_WATCHING`) and the view stays as it is;
    /// otherwise it takes their place, on the stage. Already watching it:
    /// put it on the stage.
    pub fn watch_stream(&mut self, streamer: Id) {
        let Some((guild, channel)) = self.voice.as_ref().filter(|v| v.connected).map(|v| (v.guild, v.channel)) else {
            self.toast("Join the voice channel to watch.", true);
            return;
        };
        if self.watching.iter().any(|w| w.streamer == streamer) {
            self.focus_stream(Some(streamer));
            return;
        }
        let me = self.store.me_id();
        let live = self.store.voice.get(&channel).map_or(0, |users| {
            users.iter().filter(|u| Some(**u) != me && self.store.voice_flags.get(*u).is_some_and(|f| f.streaming)).count()
        });
        let multiple = live >= 2;
        // Streams of a call you've left go first; one stream replaces another.
        let stop: Vec<Id> = self.watching.iter().filter(|w| !multiple || w.channel != channel).map(|w| w.streamer).collect();
        for s in stop {
            self.stop_watch(s);
        }
        if self.watching.len() >= MAX_WATCHING {
            self.toast(format!("You can watch up to {MAX_WATCHING} streams at once. Stop one first."), true);
            return;
        }
        let key = stream_key(guild, channel, streamer);
        log::info!("watch: requesting {key}");
        self.backend.send(Command::StreamWatch(key.clone()));
        self.watching.push(Watching {
            key,
            streamer,
            channel,
            setup: Setup::default(),
            gen: next_gen(),
            connected: false,
            handle: None,
            requested_at: Instant::now(),
            frame: None,
            seq: 0,
            size: (16, 9),
            volume: self.voice_ui.prefs.stream_volumes.get(&streamer.0).map_or(1.0, |v| v / 100.0),
            fullscreen: false,
            viewers: Vec::new(),
        });
        if !multiple {
            self.focus_stream(Some(streamer));
        } else if self.watching.len() == 1 {
            // The first of several: it plays in its tile, in the grid.
            self.focus_stream(None);
        }
    }

    /// Takes watch `i` off the list and closes its connection (without telling Discord).
    fn drop_watch(&mut self, i: usize) -> Watching {
        let w = self.watching.remove(i);
        if let Some(h) = &w.handle {
            h.stop();
        }
        if w.fullscreen {
            self.ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(false));
        }
        if self.golive_ui.focused == Some(w.streamer) {
            self.golive_ui.focused = None;
        }
        w
    }

    /// Stop watching `streamer`'s stream; the others keep going.
    pub fn stop_watch(&mut self, streamer: Id) {
        let Some(i) = self.watching.iter().position(|w| w.streamer == streamer) else { return };
        let w = self.drop_watch(i);
        log::info!("watch: stopping {}", w.key);
        self.backend.send(Command::StreamDelete(w.key));
    }

    /// Stop watching every stream.
    pub fn stop_watching(&mut self) {
        let all: Vec<Id> = self.watching.iter().map(|w| w.streamer).collect();
        for s in all {
            self.stop_watch(s);
        }
    }

    /// Leaving or losing the call ends them all.
    pub fn end_streams(&mut self) {
        self.stop_go_live();
        self.stop_watching();
        self.share_picker = None;
    }

    // ---- gateway ------------------------------------------------------------------

    /// STREAM_CREATE / STREAM_SERVER_UPDATE / STREAM_UPDATE / STREAM_DELETE.
    pub fn stream_dispatch(&mut self, name: &str, d: &Value) {
        let Some(key) = d["stream_key"].as_str() else { return };
        let mine = self.go_live.as_ref().is_some_and(|g| g.key == key);
        let watched = self.watching.iter().position(|w| w.key == key);
        if !mine && watched.is_none() {
            return;
        }
        match name {
            "STREAM_CREATE" => {
                let id = |k: &str| d[k].as_str().and_then(|s| s.parse::<u64>().ok());
                let Some(server) = id("rtc_server_id") else { return };
                let rtc = (server, id("rtc_channel_id").unwrap_or(server));
                if mine {
                    if let Some(g) = self.go_live.as_mut() {
                        g.setup.rtc = Some(rtc);
                        g.viewers = ids(&d["viewer_ids"]);
                    }
                    // Unpause it (the official app does this right after creating).
                    self.backend.send(Command::StreamSetPaused { key: key.to_string(), paused: false });
                } else if let Some(i) = watched {
                    let w = &mut self.watching[i];
                    w.setup.rtc = Some(rtc);
                    w.viewers = ids(&d["viewer_ids"]);
                }
            }
            "STREAM_SERVER_UPDATE" => {
                // A null endpoint means "wait for the next one".
                let (Some(token), Some(endpoint)) = (d["token"].as_str(), d["endpoint"].as_str()) else { return };
                let server = Some((token.to_string(), endpoint.to_string()));
                if mine {
                    if let Some(g) = self.go_live.as_mut() {
                        g.setup.server = server;
                        g.setup.started = false;
                    }
                } else if let Some(i) = watched {
                    let w = &mut self.watching[i];
                    w.setup.server = server;
                    w.setup.started = false;
                }
            }
            "STREAM_UPDATE" => {
                // Discord's "viewer joined / left" sounds, for streams of up to 25 viewers.
                let mut change = None;
                let mut note = |before: usize, after: usize| {
                    if before != after && before.max(after) <= 25 {
                        change = Some(after > before);
                    }
                };
                if let Some(g) = self.go_live.as_mut().filter(|_| mine) {
                    let before = g.viewers.len();
                    g.viewers = ids(&d["viewer_ids"]);
                    if g.connected {
                        note(before, g.viewers.len());
                    }
                }
                if let Some(i) = watched {
                    let w = &mut self.watching[i];
                    let before = w.viewers.len();
                    w.viewers = ids(&d["viewer_ids"]);
                    if w.connected {
                        note(before, w.viewers.len());
                    }
                }
                if let Some(joined) = change {
                    self.voice_cue(if joined { crate::audio::Cue::StreamUserJoined } else { crate::audio::Cue::StreamUserLeft });
                }
            }
            "STREAM_DELETE" => {
                let why = delete_reason(d["reason"].as_str());
                if mine {
                    if let Some(g) = self.go_live.take() {
                        if let Some(h) = &g.handle {
                            h.stop();
                        }
                    }
                    if let Some(w) = why {
                        self.toast(format!("Your stream ended: {w}"), true);
                    }
                } else if let Some(i) = watched {
                    self.drop_watch(i);
                    self.toast(why.unwrap_or("The stream ended."), false);
                }
                return;
            }
            _ => return,
        }
        self.maybe_connect_streams();
    }

    /// Both halves of a stream's credentials are in: open its connection.
    fn maybe_connect_streams(&mut self) {
        let Some(user) = self.store.me_id() else { return };
        let Some(session_id) = self.voice.as_ref().and_then(|v| v.session_id.clone()) else { return };
        let cfg = |s: &Setup| -> Option<voice::StreamConfig> {
            let (rtc_server_id, rtc_channel_id) = s.rtc?;
            let (token, endpoint) = s.server.clone()?;
            Some(voice::StreamConfig { user_id: user.0, session_id: session_id.clone(), token, endpoint, rtc_server_id, rtc_channel_id })
        };
        if let Some(g) = self.go_live.as_mut().filter(|g| !g.setup.started) {
            if let Some(c) = cfg(&g.setup) {
                g.setup.started = true;
                g.gen = next_gen();
                if let Some(h) = g.handle.take() {
                    h.stop();
                }
                log::info!("go live: connecting (stream {})", g.gen);
                self.backend.send(Command::GoLiveConnect { gen: g.gen, cfg: c, source: g.source.clone(), quality: g.quality, audio: g.audio });
            }
        }
        for w in self.watching.iter_mut().filter(|w| !w.setup.started) {
            if let Some(c) = cfg(&w.setup) {
                w.setup.started = true;
                w.gen = next_gen();
                if let Some(h) = w.handle.take() {
                    h.stop();
                }
                log::info!("watch: connecting (stream {})", w.gen);
                self.backend.send(Command::WatchConnect { gen: w.gen, cfg: c });
            }
        }
    }

    /// The backend started a stream connection: keep its handle.
    pub fn on_stream_handle(&mut self, gen: u64, own: Option<Arc<voice::StreamHandle>>, watch: Option<Arc<voice::WatchHandle>>) {
        match (own, watch) {
            (Some(h), _) => match self.go_live.as_mut().filter(|g| g.gen == gen) {
                Some(g) => g.handle = Some(h),
                None => h.stop(),
            },
            (_, Some(h)) => match self.watching.iter_mut().find(|w| w.gen == gen) {
                Some(w) => {
                    h.set_volume(w.volume);
                    w.handle = Some(h);
                }
                None => h.stop(),
            },
            _ => {}
        }
    }

    pub fn on_stream_event(&mut self, gen: u64, e: voice::StreamEvent) {
        let mine = self.go_live.as_ref().is_some_and(|g| g.gen == gen);
        let watched = self.watching.iter().find(|w| w.gen == gen).map(|w| w.streamer);
        match e {
            voice::StreamEvent::Connected => {
                if let Some(g) = self.go_live.as_mut().filter(|_| mine) {
                    log::info!("go live: live (stream {gen})");
                    g.connected = true;
                }
                if let Some(w) = self.watching.iter_mut().find(|w| w.gen == gen) {
                    log::info!("watch: connected (stream {gen})");
                    w.connected = true;
                }
            }
            voice::StreamEvent::Ping(_) => {}
            voice::StreamEvent::Disconnected { reason } => {
                log::info!("stream {gen} ended: {reason:?}");
                let Some(r) = reason else { return };
                if mine {
                    self.stop_go_live();
                    self.toast(format!("Your stream stopped: {r}"), true);
                } else if let Some(streamer) = watched {
                    self.stop_watch(streamer);
                    self.toast(format!("Stopped watching: {r}"), true);
                }
            }
        }
    }

    /// Setup timeouts and new video frames; cheap, every frame.
    pub fn streams_tick(&mut self) {
        let now = Instant::now();
        if self.go_live.as_ref().is_some_and(|g| !g.connected && now >= g.requested_at + SETUP_TIMEOUT) {
            self.stop_go_live();
            self.toast("Discord didn't set up the stream in time. Try again.", true);
        }
        let late: Vec<Id> = self.watching.iter().filter(|w| !w.connected && now >= w.requested_at + SETUP_TIMEOUT).map(|w| w.streamer).collect();
        if !late.is_empty() {
            for s in late {
                self.stop_watch(s);
            }
            self.toast("Couldn't connect to the stream. Try again.", true);
        }
        // The call went away: so do its streams.
        if self.voice.is_none() && (self.go_live.is_some() || !self.watching.is_empty()) {
            self.end_streams();
        }
        // "Watch Stream" from the channel list joined the call first: now watch.
        if let Some((streamer, channel)) = self.golive_ui.pending_watch {
            match self.voice.as_ref() {
                Some(v) if v.channel == channel && v.connected => {
                    self.golive_ui.pending_watch = None;
                    self.watch_stream(streamer);
                }
                Some(v) if v.channel == channel => self.ctx.request_repaint_after(Duration::from_millis(250)),
                _ => self.golive_ui.pending_watch = None,
            }
        }
        if self.go_live.is_some() || !self.watching.is_empty() {
            self.ctx.request_repaint_after(Duration::from_millis(500));
            // Every 10 s: what's flowing (for diagnosing quality reports).
            static LAST: std::sync::Mutex<Option<Instant>> = std::sync::Mutex::new(None);
            let due = LAST.lock().map(|mut l| {
                let due = l.is_none_or(|t| t.elapsed() >= Duration::from_secs(10));
                if due {
                    *l = Some(Instant::now());
                }
                due
            });
            if due.unwrap_or(false) {
                let fmt = |s: &voice::StreamStats| {
                    format!("{} {}x{} {:.0}fps {}kbps via {} (dropped {}, keyframe requests {})", s.codec, s.width, s.height, s.fps, s.bitrate_kbps, s.engine, s.dropped, s.keyframe_requests)
                };
                for w in &self.watching {
                    if let Some(h) = &w.handle {
                        log::info!("watch stats ({}): {}", w.streamer, fmt(&h.stats()));
                    }
                }
                if let Some(h) = self.go_live.as_ref().and_then(|g| g.handle.as_ref()) {
                    log::info!("go live stats: {}", fmt(&h.stats()));
                }
            }
        }
    }

    /// Fresh pixels for the textures that are on screen.
    fn refresh_frames(&mut self, ctx: &egui::Context) {
        for w in self.watching.iter_mut() {
            if let Some(f) = w.handle.as_ref().and_then(|h| h.latest_frame()).filter(|f| f.seq != w.seq) {
                w.seq = f.seq;
                w.size = (f.width, f.height);
                upload(ctx, &mut w.frame, &format!("go-live-watch-{}", w.streamer), &f);
            }
        }
        if let Some(g) = self.go_live.as_mut() {
            if let Some(f) = g.handle.as_ref().and_then(|h| h.preview()).filter(|f| f.seq != g.preview_seq) {
                g.preview_seq = f.seq;
                upload(ctx, &mut g.preview, "go-live-preview", &f);
            }
        }
    }

    // ---- UI ---------------------------------------------------------------------------

    /// Your picture on your own tile while you're live (else None).
    pub fn own_stream_texture(&mut self, ctx: &egui::Context) -> Option<egui::TextureHandle> {
        self.refresh_frames(ctx);
        self.go_live.as_ref().and_then(|g| g.preview.clone())
    }

    /// "1440p 60FPS" for a stream's stats (what Discord's badge says).
    pub fn quality_label(stats: &voice::StreamStats) -> Option<String> {
        if stats.height == 0 {
            return None;
        }
        let p = quality_tier(stats.width, stats.height);
        let fps = quality_fps(stats.fps);
        Some(if fps > 0 { format!("{p}p {fps}FPS") } else { format!("{p}p") })
    }

    /// The focused stream's stats (zeros until it's up).
    pub fn watching_stats(&self) -> voice::StreamStats {
        self.focused_watch().and_then(|w| w.handle.as_ref()).map(|h| h.stats()).unwrap_or_default()
    }

    /// Put a stream you watch on the stage (clicking its tile, as in Discord),
    /// or `None`: Discord's grid view.
    pub fn focus_stream(&mut self, streamer: Option<Id>) {
        self.golive_ui.stream_grid = streamer.is_none();
        if streamer.is_some() {
            self.golive_ui.focused = streamer;
        }
    }

    /// The stream on the stage, above a strip of the call's tiles, where the
    /// other streams you watch play in their tiles (see `call_tiles`). In the
    /// grid view there is no stage. Hovering the stream shows Discord's
    /// "Stream Info" (codec, resolution, FPS); double-click for full screen.
    /// Returns the rect left for the tiles.
    pub fn watching_stage(&mut self, ui: &mut Ui, t: &Theme, area: Rect) -> Rect {
        let ctx = ui.ctx().clone();
        self.refresh_frames(&ctx);
        if self.golive_ui.stream_grid {
            return area;
        }
        let Some(focused) = self.focused_watch().map(|w| w.streamer) else { return area };
        let strip = 118.0_f32.min(area.height() * 0.24);
        let stage = Rect::from_min_max(area.min, pos2(area.right(), area.bottom() - strip - 12.0));
        let cell = self.paint_stream(ui, t, stage, focused, self.watching.len() > 1);
        if cell.double_clicked {
            self.toggle_watch_fullscreen(focused);
        }
        if cell.close {
            self.stop_watch(focused);
        }
        if let Some(at) = cell.menu_at {
            self.toggle_voice_menu(crate::ui::voice_menu::VoiceMenuKind::Stream(focused), Rect::from_min_size(at, vec2(1.0, 1.0)));
        }
        Rect::from_min_max(pos2(area.left(), area.bottom() - strip), area.max)
    }

    /// One watched stream in `rect`: its picture (or how far it got), Stream Info
    /// on hover when there's room, and with several streams its name and a
    /// close button.
    fn paint_stream(&mut self, ui: &mut Ui, t: &Theme, rect: Rect, streamer: Id, several: bool) -> StreamCell {
        let ctx = ui.ctx().clone();
        let mut out = StreamCell::default();
        let Some(w) = self.watching.iter().find(|w| w.streamer == streamer) else { return out };
        let (connected, size, tex, channel) = (w.connected, w.size, w.frame.clone(), w.channel);
        let stats = w.handle.as_ref().map(|h| h.stats()).unwrap_or_default();
        let resp = ui.interact(rect, egui::Id::new(("watch_video", streamer.0)), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
        let hovered = ui.rect_contains_pointer(rect);
        let p = ui.painter_at(rect.expand(3.0));
        p.rect_filled(rect, 12.0, Color32::BLACK);
        let video = fit(rect, size.0 as f32, size.1 as f32);
        let small = rect.width() < 320.0;
        match &tex {
            Some(tex) => {
                // Drawn at its own size when it fits (1:1 pixels are sharpest).
                egui::Image::new((tex.id(), video.size())).rounding(Rounding::same(8.0)).paint_at(ui, video);
            }
            None => {
                let text = if connected { "Waiting for the first frame…" } else { "Connecting to the stream…" };
                let (icon, font) = if small { (20.0, 12.0) } else { (30.0, 14.0) };
                p.text(rect.center() - vec2(0.0, icon * 0.5), Align2::CENTER_CENTER, SCREEN, icon_font(icon), t.text_muted);
                p.text(rect.center() + vec2(0.0, font * 1.6), Align2::CENTER_CENTER, text, FontId::proportional(font), t.text_muted);
                ctx.request_repaint_after(Duration::from_millis(250));
            }
        }
        let bold = |size: f32| FontId::new(size, egui::FontFamily::Name(crate::style::BOLD.into()));
        // Stream Info, top-left, while the pointer is on it.
        if hovered && tex.is_some() && !small {
            let rows = [
                ("Video Codec:", if stats.codec.is_empty() { "H264".to_string() } else { stats.codec.to_string() }),
                ("Resolution:", if stats.width > 0 { format!("{} x {}", stats.width, stats.height) } else { format!("{} x {}", size.0, size.1) }),
                ("FPS:", if stats.fps > 0.0 { format!("{:.0}", stats.fps) } else { "–".into() }),
            ];
            let mut extra: Vec<(&str, String)> = Vec::new();
            if stats.bitrate_kbps > 0 {
                extra.push(("Bitrate:", format!("{:.1} Mbps", stats.bitrate_kbps as f32 / 1000.0)));
            }
            if !stats.engine.is_empty() {
                extra.push(("Decoder:", stats.engine.to_string()));
            }
            let lines = 1 + rows.len() + extra.len();
            let card = Rect::from_min_size(rect.min + vec2(12.0, 12.0), vec2(210.0, 12.0 + 19.0 * lines as f32));
            p.rect_filled(card, 8.0, Color32::from_black_alpha(185));
            p.text(card.min + vec2(10.0, 8.0), Align2::LEFT_TOP, "Stream Info", bold(13.0), Color32::WHITE);
            for (i, (k, v)) in rows.iter().map(|(k, v)| (*k, v.clone())).chain(extra.into_iter()).enumerate() {
                let y = card.top() + 8.0 + 19.0 * (i + 1) as f32;
                p.text(pos2(card.left() + 10.0, y), Align2::LEFT_TOP, k, FontId::proportional(12.5), crate::style::rgba(255, 255, 255, 200));
                p.text(pos2(card.right() - 10.0, y), Align2::RIGHT_TOP, v, bold(13.0), Color32::WHITE);
            }
            // Keep the numbers fresh while it's shown.
            ctx.request_repaint_after(Duration::from_millis(500));
        }
        if several {
            // Whose stream it is, bottom-left.
            let gid = self.store.channels.get(&channel).and_then(|c| c.guild_id);
            let name = self.store.nick_in(gid, Some(channel), streamer).or_else(|| self.store.users.get(&streamer).map(|u| u.display_name().to_string())).unwrap_or_default();
            let g = p.layout_no_wrap(name, bold(12.5), Color32::WHITE);
            let label = Rect::from_min_size(pos2(rect.left() + 8.0, rect.bottom() - 8.0 - 22.0), vec2(g.size().x + 16.0, 22.0));
            p.rect_filled(label, 6.0, Color32::from_black_alpha(170));
            p.galley(pos2(label.left() + 8.0, label.center().y - g.size().y / 2.0), g, Color32::WHITE);
            // Stop watching this one, top-right, while the pointer is on it.
            if hovered {
                let b = Rect::from_min_size(pos2(rect.right() - 8.0 - 28.0, rect.top() + 8.0), vec2(28.0, 28.0));
                let r = ui.interact(b, egui::Id::new(("watch_close", streamer.0)), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
                p.rect_filled(b, 8.0, if r.hovered() { LIVE_RED } else { Color32::from_black_alpha(170) });
                p.text(b.center(), Align2::CENTER_CENTER, crate::style::icon::CLOSE, icon_font(12.0), Color32::WHITE);
                out.close = r.on_hover_text("Stop Watching").clicked();
            }
        }
        // Double-click the picture: full screen, like Discord. Right-click: the stream's menu.
        out.double_clicked = resp.double_clicked();
        if resp.secondary_clicked() {
            out.menu_at = Some(resp.interact_pointer_pos().unwrap_or(rect.center()));
        }
        out
    }

    /// Full screen for `streamer`'s stream (or back); only one stream at a time.
    pub fn toggle_watch_fullscreen(&mut self, streamer: Id) {
        let mut on = false;
        for w in self.watching.iter_mut() {
            w.fullscreen = w.streamer == streamer && !w.fullscreen;
            on |= w.fullscreen;
        }
        if on {
            self.golive_ui.focused = Some(streamer);
        }
        self.ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(on));
    }

    /// `streamer`'s stream volume (0–2), applied at once; remembered for that
    /// streamer and saved when `save` (the slider let go).
    pub fn set_watch_volume(&mut self, streamer: Id, v: f32, save: bool) {
        let Some(w) = self.watching.iter_mut().find(|w| w.streamer == streamer) else { return };
        w.volume = v.clamp(0.0, 2.0);
        if let Some(h) = &w.handle {
            h.set_volume(w.volume);
        }
        let percent = w.volume * 100.0;
        let volumes = &mut self.voice_ui.prefs.stream_volumes;
        if (percent - 100.0).abs() < 0.5 {
            volumes.remove(&streamer.0);
        } else {
            volumes.insert(streamer.0, percent);
        }
        if save {
            self.voice_ui.changed();
        }
    }

    /// The volume of `streamer`'s stream in percent, while you watch it.
    pub fn watched_stream_volume(&self, streamer: Id) -> Option<f32> {
        self.watching.iter().find(|w| w.streamer == streamer).map(|w| w.volume * 100.0)
    }

    /// Whether `streamer`'s stream is the one shown full screen.
    pub fn watch_is_fullscreen(&self, streamer: Id) -> bool {
        self.watching.iter().any(|w| w.streamer == streamer && w.fullscreen)
    }

    /// Full screen: the picture over everything, Esc (or double-click) to leave.
    pub fn watching_fullscreen_ui(&mut self, ctx: &egui::Context) {
        let Some(w) = self.watching.iter().find(|w| w.fullscreen) else { return };
        let streamer = w.streamer;
        self.refresh_frames(ctx);
        let Some(w) = self.watching.iter().find(|w| w.streamer == streamer) else { return };
        let (tex, size) = (w.frame.clone(), w.size);
        let screen = ctx.screen_rect();
        // Esc closes an open menu first.
        let menu_open = self.voice_menu_open(crate::ui::voice_menu::VoiceMenuKind::Stream(streamer));
        let mut leave = !menu_open && ctx.input(|i| i.key_pressed(egui::Key::Escape));
        let mut menu_at = None;
        egui::Area::new(egui::Id::new("watch_fullscreen")).order(Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
            let (r, resp) = ui.allocate_exact_size(screen.size(), Sense::click());
            ui.painter().rect_filled(r, 0.0, Color32::BLACK);
            if let Some(tex) = &tex {
                let video = fit(r, size.0 as f32, size.1 as f32);
                egui::Image::new((tex.id(), video.size())).paint_at(ui, video);
            }
            if ui.rect_contains_pointer(r) {
                ui.painter().text(pos2(r.right() - 20.0, r.top() + 20.0), Align2::RIGHT_TOP, "Esc to exit full screen", FontId::proportional(13.0), crate::style::rgba(255, 255, 255, 140));
            }
            leave |= resp.double_clicked();
            if resp.secondary_clicked() {
                menu_at = resp.interact_pointer_pos();
            }
        });
        if let Some(at) = menu_at {
            self.toggle_voice_menu(crate::ui::voice_menu::VoiceMenuKind::Stream(streamer), Rect::from_min_size(at, vec2(1.0, 1.0)));
        }
        if leave {
            for w in self.watching.iter_mut() {
                w.fullscreen = false;
            }
            ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(false));
        }
    }

    /// The picture Discord shows for a live stream (refreshed every minute while
    /// something shows it): `GET /streams/<key>/preview` → `{ "url": … }`.
    pub fn stream_preview(&mut self, key: &str) -> Option<String> {
        let tag = format!("stream_preview:{key}");
        if let Some(r) = self.api_take(&tag) {
            let url = r.ok().and_then(|v| v["url"].as_str().map(String::from));
            let at = self.golive_ui.previews.get(key).map(|(at, _)| *at).unwrap_or_else(Instant::now);
            let keep = url.or_else(|| self.golive_ui.previews.get(key).and_then(|(_, u)| u.clone()));
            self.golive_ui.previews.insert(key.to_string(), (at, keep));
        }
        let stale = self.golive_ui.previews.get(key).is_none_or(|(at, _)| at.elapsed() > Duration::from_secs(60));
        if stale && !self.api_busy(&tag) {
            let old = self.golive_ui.previews.get(key).and_then(|(_, u)| u.clone());
            self.golive_ui.previews.insert(key.to_string(), (Instant::now(), old));
            let version = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0);
            self.api(&tag, reqwest::Method::GET, format!("/streams/{key}/preview?version={version}"), None);
        }
        self.golive_ui.previews.get(key).and_then(|(_, u)| u.clone())
    }

    /// What `user` is doing, for stream cards and the stream header:
    /// (verb, name, picture, started at ms).
    pub fn stream_activity(&self, user: Id) -> Option<(&'static str, String, Option<String>, Option<u64>)> {
        let p = self.store.presences.get(&user)?;
        let a = p.activities.iter().find(|a| a.kind != 4)?;
        let verb = match a.kind {
            1 => "Streaming",
            2 => "Listening to",
            3 => "Watching",
            5 => "Competing in",
            _ => "Playing",
        };
        let icon = a.large_image_url().or_else(|| a.application_id.and_then(|id| self.apps.get(&id)).and_then(|app| app.icon_url()));
        if let (None, Some(app)) = (&icon, a.application_id) {
            if !self.apps.contains_key(&app) {
                self.apps_wanted.borrow_mut().insert(app);
            }
        }
        Some((verb, a.name.clone(), icon, a.timestamps.as_ref().and_then(|t| t.start)))
    }

    /// "Watch Stream" from the channel list: joins the call first if needed.
    pub fn watch_from_list(&mut self, streamer: Id, channel: Id) {
        if self.voice.as_ref().is_some_and(|v| v.channel == channel && v.connected) {
            self.watch_stream(streamer);
        } else {
            if self.voice.as_ref().is_none_or(|v| v.channel != channel) {
                self.join_voice(channel);
            }
            self.golive_ui.pending_watch = Some((streamer, channel));
        }
        self.open_call_view_for(channel);
    }

    fn open_call_view_for(&mut self, channel: Id) {
        let guild = self.store.channels.get(&channel).and_then(|c| c.guild_id);
        self.current_guild = guild;
        self.select_channel(Some(channel));
    }

    /// The channel list's "Streaming Now" card for a hovered streamer: the
    /// stream's picture, what they're doing, and Watch Stream. Stays while the
    /// pointer is on the row or the card.
    pub fn stream_card_ui(&mut self, ctx: &egui::Context) {
        let Some((streamer, channel, at, seen)) = self.golive_ui.card else { return };
        let frame = ctx.cumulative_pass_nr();
        if frame > seen + 2 {
            self.golive_ui.card = None;
            return;
        }
        let t = self.theme.clone();
        let guild = self.store.channels.get(&channel).and_then(|c| c.guild_id);
        let key = stream_key(guild, channel, streamer);
        let preview = self.stream_preview(&key);
        let activity = self.stream_activity(streamer);
        let watching = self.watching.iter().any(|w| w.streamer == streamer);
        let mut watch = false;
        let area = egui::Area::new(egui::Id::new("stream_card")).order(Order::Foreground).fixed_pos(at).constrain(true).show(ctx, |ui| {
            Frame::none()
                .fill(t.bg_floating)
                .rounding(12.0)
                .stroke(Stroke::new(1.0_f32, t.border_subtle))
                .shadow(egui::epaint::Shadow { offset: vec2(0.0, 8.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(140) })
                .inner_margin(Margin::same(12.0))
                .show(ui, |ui| {
                    ui.set_width(256.0);
                    ui.horizontal(|ui| {
                        ui.label(RichText::new("Streaming Now").font(FontId::new(13.0, egui::FontFamily::Name(crate::style::BOLD.into()))).color(t.header_secondary));
                        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                            let (r, _) = ui.allocate_exact_size(vec2(40.0, 18.0), Sense::hover());
                            paint_live(ui.painter(), r.left_center(), 11.0);
                        });
                    });
                    ui.add_space(8.0);
                    let (pic, _) = ui.allocate_exact_size(vec2(256.0, 144.0), Sense::hover());
                    ui.painter().rect_filled(pic, 8.0, Color32::BLACK);
                    match &preview {
                        Some(u) => egui::Image::new(u.as_str()).rounding(Rounding::same(8.0)).paint_at(ui, pic),
                        None => {
                            ui.painter().text(pic.center(), Align2::CENTER_CENTER, SCREEN, icon_font(28.0), t.text_muted);
                        }
                    }
                    if let Some((verb, name, icon, start)) = &activity {
                        ui.add_space(10.0);
                        ui.horizontal(|ui| {
                            ui.spacing_mut().item_spacing.x = 10.0;
                            let (r, _) = ui.allocate_exact_size(vec2(36.0, 36.0), Sense::hover());
                            match icon {
                                Some(u) => egui::Image::new(u.as_str()).rounding(Rounding::same(8.0)).paint_at(ui, r),
                                None => {
                                    ui.painter().rect_filled(r, 8.0, overlay(0.16));
                                    ui.painter().text(r.center(), Align2::CENTER_CENTER, crate::style::icon::GAME, icon_font(17.0), t.interactive_normal);
                                }
                            }
                            ui.vertical(|ui| {
                                ui.spacing_mut().item_spacing.y = 1.0;
                                ui.add(egui::Label::new(RichText::new(name).font(FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into()))).color(t.header_primary)).truncate());
                                let sub = match start {
                                    Some(s) => {
                                        let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
                                        let secs = now.saturating_sub(*s) / 1000;
                                        ui.ctx().request_repaint_after(Duration::from_secs(1));
                                        format!("{} {}:{:02}:{:02}", crate::style::icon::GAME, secs / 3600, secs / 60 % 60, secs % 60)
                                    }
                                    None => verb.to_string(),
                                };
                                ui.label(RichText::new(sub).font(icon_font(12.5)).color(crate::voice_call::VOICE_GREEN));
                            });
                        });
                    }
                    ui.add_space(10.0);
                    let label = if watching { "Watching Stream" } else { "Watch Stream" };
                    let b = ui.add_enabled(
                        !watching,
                        egui::Button::new(RichText::new(format!("{SCREEN}  {label}")).font(icon_font(14.0)).color(Color32::WHITE))
                            .fill(if watching { overlay(0.12) } else { t.accent })
                            .rounding(8.0)
                            .min_size(vec2(256.0, 36.0)),
                    );
                    watch = b.clicked();
                });
        });
        if area.response.hovered() || ctx.input(|i| i.pointer.hover_pos()).is_some_and(|p| area.response.rect.contains(p)) {
            if let Some(c) = self.golive_ui.card.as_mut() {
                c.3 = frame;
            }
        }
        if watch {
            self.golive_ui.card = None;
            self.watch_from_list(streamer, channel);
        }
    }

    /// Discord's "Screen Share" window: Screens / Applications with a still of
    /// each, then Resolution, Frame Rate, "Share audio" and Go Live.
    pub fn share_picker_ui(&mut self, ctx: &egui::Context) {
        let t = self.theme.clone();
        let Some(pk) = self.share_picker.as_mut() else { return };
        while let Ok(msg) = pk.rx.try_recv() {
            match msg {
                PickerMsg::Sources(s) => {
                    // Start on Screens; preselect the first one.
                    if let Ok(list) = &s {
                        pk.selected = list.iter().find(|s| !s.is_window).or(list.first()).map(|s| s.id.clone());
                    }
                    pk.sources = Some(s);
                }
                PickerMsg::Thumb(id, f) => {
                    let mut slot = None;
                    upload(ctx, &mut slot, &format!("share-thumb-{id}"), &f);
                    if let Some(tex) = slot {
                        pk.thumbs.insert(id, tex);
                    }
                }
            }
        }
        let screen = ctx.screen_rect();
        let mut close = ctx.input(|i| i.key_pressed(egui::Key::Escape));
        let mut go: Option<(voice::ScreenSource, voice::StreamQuality, bool)> = None;
        egui::Area::new(egui::Id::new("share_picker_dim")).order(Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
            let (r, resp) = ui.allocate_exact_size(screen.size(), Sense::click());
            ui.painter().rect_filled(r, 0.0, Color32::from_black_alpha(160));
            close |= resp.clicked() && ctx.cumulative_pass_nr() > pk.opened + 1;
        });
        egui::Area::new(egui::Id::new("share_picker")).order(Order::Foreground).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)).show(ctx, |ui| {
            ui.ctx().move_to_top(ui.layer_id());
            Frame::none()
                .fill(t.bg_floating)
                .rounding(12.0)
                .stroke(Stroke::new(1.0_f32, t.border_subtle))
                .shadow(egui::epaint::Shadow { offset: vec2(0.0, 10.0), blur: 30.0, spread: 0.0, color: Color32::from_black_alpha(150) })
                .inner_margin(Margin::same(20.0))
                .show(ui, |ui| {
                    ui.set_width(620.0);
                    ui.horizontal(|ui| {
                        ui.label(RichText::new("Screen Share").font(FontId::new(20.0, egui::FontFamily::Name(crate::style::BOLD.into()))).color(t.header_primary));
                        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                            let (x, r) = ui.allocate_exact_size(vec2(28.0, 28.0), Sense::click());
                            let r = r.on_hover_cursor(egui::CursorIcon::PointingHand);
                            if r.hovered() {
                                ui.painter().rect_filled(x, 6.0, overlay(0.16));
                            }
                            ui.painter().text(x.center(), Align2::CENTER_CENTER, crate::style::icon::CLOSE, icon_font(12.0), t.interactive_normal);
                            close |= r.clicked();
                        });
                    });
                    ui.add_space(12.0);
                    // Tabs.
                    ui.horizontal(|ui| {
                        ui.spacing_mut().item_spacing.x = 8.0;
                        for (windows, label) in [(false, "Screens"), (true, "Applications")] {
                            let on = pk.windows_tab == windows;
                            let g = ui.painter().layout_no_wrap(label.into(), FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into())), Color32::PLACEHOLDER);
                            let (r, resp) = ui.allocate_exact_size(g.size() + vec2(24.0, 12.0), Sense::click());
                            if on || resp.hovered() {
                                ui.painter().rect_filled(r, 8.0, overlay(if on { 0.16 } else { 0.08 }));
                            }
                            ui.painter().galley(r.min + vec2(12.0, 6.0), g, if on { t.header_primary } else { t.interactive_normal });
                            if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                                pk.windows_tab = windows;
                            }
                        }
                    });
                    ui.add_space(10.0);
                    // Sources.
                    egui::ScrollArea::vertical().max_height(300.0).auto_shrink([false, true]).show(ui, |ui| match &pk.sources {
                        None => {
                            ui.add_space(40.0);
                            ui.vertical_centered(|ui| ui.spinner());
                            ui.add_space(40.0);
                        }
                        Some(Err(e)) => {
                            ui.add_space(20.0);
                            ui.label(RichText::new(format!("Screen sharing isn't available: {e}")).size(14.0).color(t.text_muted));
                            ui.add_space(20.0);
                        }
                        Some(Ok(list)) => {
                            let shown: Vec<&voice::ScreenSource> = list.iter().filter(|s| s.is_window == pk.windows_tab).collect();
                            if shown.is_empty() {
                                ui.add_space(20.0);
                                ui.label(RichText::new("Nothing to share here.").size(14.0).color(t.text_muted));
                            }
                            ui.horizontal_wrapped(|ui| {
                                ui.spacing_mut().item_spacing = vec2(12.0, 12.0);
                                for s in shown {
                                    let (cell, resp) = ui.allocate_exact_size(vec2(190.0, 136.0), Sense::click());
                                    let selected = pk.selected.as_deref() == Some(s.id.as_str());
                                    let thumb = Rect::from_min_size(cell.min, vec2(190.0, 107.0));
                                    ui.painter().rect_filled(thumb, 8.0, Color32::BLACK);
                                    match pk.thumbs.get(&s.id) {
                                        Some(tex) => {
                                            let sz = tex.size_vec2();
                                            let r = fit(thumb.shrink(2.0), sz.x, sz.y);
                                            egui::Image::new((tex.id(), r.size())).rounding(Rounding::same(6.0)).paint_at(ui, r);
                                        }
                                        None => {
                                            ui.painter().text(thumb.center(), Align2::CENTER_CENTER, SCREEN, icon_font(26.0), t.text_muted);
                                        }
                                    }
                                    let edge = if selected { Stroke::new(2.0_f32, t.accent) } else if resp.hovered() { Stroke::new(1.0_f32, overlay(0.4)) } else { Stroke::new(1.0_f32, overlay(0.12)) };
                                    ui.painter().rect_stroke(thumb, 8.0, edge);
                                    let mut job = egui::text::LayoutJob::simple_singleline(s.name.clone(), FontId::proportional(13.0), t.text_normal);
                                    job.wrap = egui::text::TextWrapping::truncate_at_width(cell.width());
                                    let g = ui.painter().layout_job(job);
                                    ui.painter().galley(pos2(cell.left(), thumb.bottom() + 8.0), g, if selected { t.header_primary } else { t.text_normal });
                                    if resp.on_hover_cursor(CursorIcon::PointingHand).on_hover_text(&s.name).clicked() {
                                        pk.selected = Some(s.id.clone());
                                    }
                                }
                            });
                        }
                    });
                    ui.add_space(14.0);
                    ui.painter().hline(ui.max_rect().x_range(), ui.cursor().top(), Stroke::new(1.0_f32, t.border_subtle));
                    ui.add_space(14.0);
                    // Quality and audio.
                    let chip = |ui: &mut Ui, label: &str, on: bool| -> bool {
                        let g = ui.painter().layout_no_wrap(label.into(), FontId::new(13.0, egui::FontFamily::Name(crate::style::BOLD.into())), Color32::PLACEHOLDER);
                        let (r, resp) = ui.allocate_exact_size(g.size() + vec2(22.0, 12.0), Sense::click());
                        ui.painter().rect(r, 16.0, if on { t.accent } else { overlay(if resp.hovered() { 0.16 } else { 0.08 }) }, Stroke::NONE);
                        ui.painter().galley(r.min + vec2(11.0, 6.0), g, if on { Color32::WHITE } else { t.text_normal });
                        resp.on_hover_cursor(CursorIcon::PointingHand).clicked()
                    };
                    ui.horizontal(|ui| {
                        ui.spacing_mut().item_spacing.x = 8.0;
                        ui.label(RichText::new("RESOLUTION").size(11.5).strong().color(t.header_secondary));
                        ui.add_space(6.0);
                        for (h, label) in [(720u32, "720p"), (1080, "1080p"), (1440, "1440p"), (0, "Source")] {
                            if chip(ui, label, pk.quality.max_height == h) {
                                pk.quality.max_height = h;
                            }
                        }
                        ui.add_space(18.0);
                        ui.label(RichText::new("FRAME RATE").size(11.5).strong().color(t.header_secondary));
                        ui.add_space(6.0);
                        for fps in [15u32, 30, 60] {
                            if chip(ui, &format!("{fps} FPS"), pk.quality.fps == fps) {
                                pk.quality.fps = fps;
                            }
                        }
                    });
                    ui.add_space(12.0);
                    ui.horizontal(|ui| {
                        crate::ui::toggle_switch(ui, &mut pk.audio, &t);
                        ui.label(RichText::new("Share audio").size(14.0).color(t.text_normal));
                    });
                    ui.add_space(16.0);
                    ui.horizontal(|ui| {
                        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                            let chosen = pk.selected.as_ref().and_then(|id| pk.sources.as_ref()?.as_ref().ok()?.iter().find(|s| &s.id == id).cloned());
                            let enabled = chosen.is_some();
                            let b = ui.add_enabled(
                                enabled,
                                egui::Button::new(RichText::new("Go Live").font(FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into()))).color(Color32::WHITE))
                                    .fill(t.accent)
                                    .rounding(8.0)
                                    .min_size(vec2(110.0, 38.0)),
                            );
                            if b.clicked() {
                                if let Some(s) = chosen {
                                    go = Some((s, pk.quality, pk.audio));
                                }
                            }
                            if ui.add(egui::Button::new(RichText::new("Cancel").size(14.0).color(t.header_primary)).frame(false)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                                close = true;
                            }
                        });
                    });
                });
        });
        if let Some((s, q, a)) = go {
            self.share_picker = None;
            self.start_go_live(s, q, a);
        } else if close {
            self.share_picker = None;
        }
    }
}

/// The "p" number Discord's badge shows for a picture: the standard tier (360, 480, 720,
/// 1080, 1440, 2160) its height is within 5 % of, so a 1920x1072 cropped window or a
/// decoder's 1088-row surface still reads as "1080p"; other heights show as they are.
/// Judged by height only: an ultrawide 2560x1080 share is "1080p", as Discord has it.
pub fn quality_tier(_width: u32, height: u32) -> u32 {
    [360u32, 480, 720, 1080, 1440, 2160].into_iter().find(|tier| height.abs_diff(*tier) * 20 <= *tier).unwrap_or(height)
}

/// Frame rates read as the standard rates when they're within a frame or two of them:
/// a 60 fps stream decoded at 58-59 fps is "60FPS", like Discord shows it.
pub fn quality_fps(fps: f32) -> u32 {
    let rounded = fps.round() as u32;
    [15u32, 24, 30, 60].into_iter().find(|rate| rounded.abs_diff(*rate) <= 2).unwrap_or(rounded)
}

fn ids(v: &Value) -> Vec<Id> {
    v.as_array().into_iter().flatten().filter_map(|x| x.as_str().and_then(|s| s.parse().ok()).map(Id)).collect()
}

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

    #[test]
    fn quality_badges_read_like_discords() {
        assert_eq!(quality_tier(2560, 1440), 1440);
        assert_eq!(quality_tier(2560, 1417), 1440, "a cropped 1440p window");
        assert_eq!(quality_tier(1920, 1088), 1080, "a decoder's padded surface");
        assert_eq!(quality_tier(2560, 1080), 1080, "ultrawide is judged by height");
        assert_eq!(quality_tier(1280, 720), 720);
        assert_eq!(quality_tier(1000, 900), 900, "odd sizes show their own height");
        assert_eq!(quality_fps(59.4), 60);
        assert_eq!(quality_fps(29.6), 30);
        assert_eq!(quality_fps(45.0), 45);
        let stats = voice::StreamStats { codec: "H264", width: 2560, height: 1440, fps: 58.7, ..Default::default() };
        assert_eq!(RustCord::quality_label(&stats).as_deref(), Some("1440p 60FPS"));
        assert!(RustCord::quality_label(&voice::StreamStats::default()).is_none());
    }
}