Skip to content

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

48.3 KB
Raw Blame
//! Everything that moves: GIF embeds ("gifv" from Tenor, Klipy, Giphy… are
//! MP4 clips), GIF files, animated emoji, avatars and banners. Each is decoded
//! once in the background (MP4 by Windows' Media Foundation, GIF by the image
//! crate), scaled to display size, and served to egui as images under
//! `<url>#vframe=<n>`.
//!
//! All animations share one clock that redraws at most [`TICK_MS`] apart:
//! letting each GIF ask for redraws at its own frame times made the window
//! redraw 100+ times a second with a few on screen.

use eframe::egui::{
    self,
    load::{BytesPoll, ImageLoadResult, ImageLoader, ImagePoll, LoadError, SizeHint},
    ColorImage,
};
use std::collections::HashMap;
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};

const FRAME_TAG: &str = "#vframe=";
/// Frames are scaled down to what Discord shows at most (400×300).
const MAX_W: usize = 400;
const MAX_H: usize = 300;
/// Longer clips keep every n-th frame so memory stays bounded.
const MAX_FRAMES: usize = 150;
/// A thumbnail clip (see [`thumb_key`]) keeps at most this many: a picker
/// plays every tile in view at once.
const MAX_THUMB_FRAMES: usize = 75;
const THUMB_TAG: &str = "@thumb=";
const EFFECT_TAG: &str = "@effect=";
/// Largest size a profile effect layer is decoded to (Discord's are smaller).
const EFFECT_MAX: (usize, usize) = (640, 1100);

/// The key of profile effect layer `url`'s clip decoded for a card `w` px
/// wide (rounded up to 64 so cards of nearly the same size share it): the
/// layer is drawn as wide as the card, so pixels beyond that are never seen.
pub fn effect_key(url: &str, w: f32) -> String {
    let up = ((w.max(64.0) / 64.0).ceil() as usize * 64).min(EFFECT_MAX.0);
    format!("{url}#{EFFECT_TAG}{up}")
}

/// The key of `url`'s clip decoded for a tile `w`×`h` px (rounded up to 32 so
/// a slightly different layout reuses it), with fewer frames kept: a grid
/// of GIFs then costs what its tiles show, not 400×300 a clip.
pub fn thumb_key(url: &str, w: f32, h: f32) -> String {
    let up = |v: f32| ((v.max(32.0) / 32.0).ceil() as usize * 32).min(MAX_W.max(MAX_H));
    format!("{url}{THUMB_TAG}{}x{}", up(w), up(h))
}

/// (largest width, largest height, most frames) a GIF or MP4 clip is decoded to.
fn decode_limits(key: &str) -> (usize, usize, usize) {
    decode_limits_within(key, (MAX_W, MAX_H))
}

/// [`decode_limits`], with `normal` as the size limit when the key isn't a
/// thumbnail's.
fn decode_limits_within(key: &str, normal: (usize, usize)) -> (usize, usize, usize) {
    let fragment = key.rsplit('#').next().unwrap_or("");
    if let Some(w) = fragment.strip_prefix(EFFECT_TAG).and_then(|w| w.parse::<usize>().ok()) {
        // As wide as the card; the height follows the picture's shape.
        return (w.clamp(1, EFFECT_MAX.0), EFFECT_MAX.1, MAX_FRAMES);
    }
    let thumb = fragment.rsplit_once(THUMB_TAG).and_then(|(_, s)| s.split_once('x')).and_then(|(w, h)| Some((w.parse().ok()?, h.trim_end_matches('~').parse().ok()?)));
    match thumb {
        Some((w, h)) => (usize::min(w, MAX_W), usize::min(h, MAX_W), MAX_THUMB_FRAMES),
        None => (normal.0, normal.1, MAX_FRAMES),
    }
}

/// Whether `url`'s clip is decoded, decoding or released (asking for its
/// frames then starts nothing new).
pub fn known(url: &str) -> bool {
    LOADER.get().is_some_and(|l| l.clips.lock().is_ok_and(|c| c.contains_key(clip_key(url).as_ref())))
}
/// One shared animation clock: ~30 redraws a second at most.
const TICK_MS: u64 = 33;
/// A clip that hasn't played for this long (scrolled away, no longer hovered,
/// or RustCord isn't the focused window) gives its frames back and keeps only
/// the first, as its still. Its file is in the image cache (memory, then
/// disk), so playing it again costs a decode, not a download.
const IDLE: Duration = Duration::from_secs(10);

/// Decode jobs: (url, file bytes).
static JOBS: OnceLock<Mutex<Sender<(String, Arc<[u8]>)>>> = OnceLock::new();
static CTX: OnceLock<egui::Context> = OnceLock::new();

struct Clip {
    /// Frames kept as they are (GIF / APNG / WebP: they may be see-through).
    frames: Vec<Arc<ColorImage>>,
    /// Frames of a video clip, packed (see [`Packed`]); used when not empty.
    packed: Vec<Packed>,
    /// When each frame ends, in ms from the start (cumulative).
    ends_ms: Vec<u64>,
}

/// A frame stored the way video stores colour: full-size brightness, colour
/// at half size each way (YUV 4:2:0), 1.5 bytes a pixel instead of RGBA's 4,
/// plus a full-size alpha plane (2.5 bytes) when the frame is see-through.
/// GIF embeds are MP4 clips that already are 4:2:0, so nothing visible is
/// lost there; GIF and WebP files are packed the same way from
/// [`PACK_FROM_PX`] up (a 150-frame clip: ~20 MB instead of ~54 MB). Turned
/// back into RGBA only for the frame being drawn.
struct Packed {
    w: usize,
    h: usize,
    /// Y plane (w × h), then U and V (each ⌈w/2⌉ × ⌈h/2⌉), then alpha (w × h)
    /// for a see-through frame. Colour is premultiplied, as egui keeps it.
    data: Box<[u8]>,
}

/// Frames this big (pixels) and up are packed; smaller ones (emoji, small
/// avatars) stay RGBA: they cost little, and halving their colour would show.
const PACK_FROM_PX: usize = 128 * 128;

impl Packed {
    fn pack(img: &ColorImage) -> Self {
        let [w, h] = img.size;
        let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
        let alpha = img.pixels.iter().any(|p| p.a() < 255);
        let mut data = vec![0u8; w * h + 2 * cw * ch + if alpha { w * h } else { 0 }];
        let (ys, rest) = data.split_at_mut(w * h);
        let (us, rest) = rest.split_at_mut(cw * ch);
        let (vs, alphas) = rest.split_at_mut(cw * ch);
        for (y, px) in ys.iter_mut().zip(&img.pixels) {
            *y = ((77 * px.r() as u32 + 150 * px.g() as u32 + 29 * px.b() as u32) >> 8) as u8;
        }
        if alpha {
            for (a, px) in alphas.iter_mut().zip(&img.pixels) {
                *a = px.a();
            }
        }
        for cy in 0..ch {
            for cx in 0..cw {
                // Average the (up to) four pixels this colour sample covers.
                let (mut r, mut g, mut b, mut n) = (0i32, 0i32, 0i32, 0i32);
                for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
                    let (x, y) = (cx * 2 + dx, cy * 2 + dy);
                    if x < w && y < h {
                        let p = img.pixels[y * w + x];
                        r += p.r() as i32;
                        g += p.g() as i32;
                        b += p.b() as i32;
                        n += 1;
                    }
                }
                let (r, g, b) = (r / n, g / n, b / n);
                us[cy * cw + cx] = (((-43 * r - 85 * g + 128 * b) >> 8) + 128).clamp(0, 255) as u8;
                vs[cy * cw + cx] = (((128 * r - 107 * g - 21 * b) >> 8) + 128).clamp(0, 255) as u8;
            }
        }
        Self { w, h, data: data.into_boxed_slice() }
    }

    fn unpack(&self) -> ColorImage {
        let (w, h) = (self.w, self.h);
        let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
        let (ys, rest) = self.data.split_at(w * h);
        let (us, rest) = rest.split_at(cw * ch);
        let (vs, alphas) = rest.split_at(cw * ch);
        let mut pixels = Vec::with_capacity(w * h);
        for y in 0..h {
            let row = (y / 2) * cw;
            for x in 0..w {
                let l = ys[y * w + x] as i32;
                let u = us[row + x / 2] as i32 - 128;
                let v = vs[row + x / 2] as i32 - 128;
                let r = (l + ((359 * v) >> 8)).clamp(0, 255) as u8;
                let g = (l - ((88 * u + 183 * v) >> 8)).clamp(0, 255) as u8;
                let b = (l + ((454 * u) >> 8)).clamp(0, 255) as u8;
                pixels.push(match alphas.get(y * w + x) {
                    // (Premultiplied: colour never above its alpha.)
                    Some(&a) => egui::Color32::from_rgba_premultiplied(r.min(a), g.min(a), b.min(a), a),
                    None => egui::Color32::from_rgb(r, g, b),
                });
            }
        }
        ColorImage { size: [w, h], pixels }
    }
}

/// Frames as they come out of a decoder, each with how long it shows (ms):
/// big ones packed at once, so a long GIF never sits in memory as RGBA.
#[derive(Default)]
struct Collected {
    rgba: Vec<(Arc<ColorImage>, u64)>,
    packed: Vec<(Packed, u64)>,
}

impl Collected {
    fn push(&mut self, img: ColorImage, ms: u64) {
        if img.pixels.len() >= PACK_FROM_PX {
            self.packed.push((Packed::pack(&img), ms));
        } else {
            self.rgba.push((Arc::new(img), ms));
        }
    }

    fn len(&self) -> usize {
        self.rgba.len() + self.packed.len()
    }

    /// The clip, keeping every n-th frame so at most `max_frames` remain (a
    /// kept frame shows for as long as the frames it stands for).
    fn into_clip(self, max_frames: usize) -> Result<Clip, String> {
        let n = self.len();
        if n == 0 {
            return Err("no frames".into());
        }
        let keep_every = n.div_ceil(max_frames).max(1);
        let mut ends_ms = Vec::with_capacity(n.div_ceil(keep_every));
        let mut t = 0u64;
        let mut keep = |i: usize, ms: u64| {
            t += ms;
            if i % keep_every == keep_every - 1 || i == n - 1 {
                ends_ms.push(t);
            }
            i % keep_every == 0
        };
        let frames: Vec<Arc<ColorImage>> = self.rgba.into_iter().enumerate().filter_map(|(i, (f, ms))| keep(i, ms).then_some(f)).collect();
        let packed: Vec<Packed> = self.packed.into_iter().enumerate().filter_map(|(i, (f, ms))| keep(i, ms).then_some(f)).collect();
        Ok(Clip { frames, packed, ends_ms })
    }
}

impl Clip {
    fn len(&self) -> usize {
        if self.packed.is_empty() {
            self.frames.len()
        } else {
            self.packed.len()
        }
    }

    /// Frame `idx` (clamped), as pixels to draw.
    fn image(&self, idx: usize) -> Arc<ColorImage> {
        let idx = idx.min(self.len().saturating_sub(1));
        match self.packed.get(idx) {
            Some(p) => Arc::new(p.unpack()),
            None => self.frames[idx].clone(),
        }
    }

    fn byte_size(&self) -> usize {
        self.frames.iter().map(|f| f.pixels.len() * 4).sum::<usize>() + self.packed.iter().map(|p| p.data.len()).sum::<usize>()
    }

    /// This clip with only its first frame.
    fn still(&self) -> Clip {
        Clip { frames: vec![self.image(0)], packed: Vec::new(), ends_ms: vec![0] }
    }
}

enum State {
    Decoding,
    /// Decoded, and when it last played (see [`IDLE`]).
    Ready(Arc<Clip>, Instant),
    /// Its frames were released: the still, and whether the clip is wanted
    /// again and being decoded.
    Released(Arc<Clip>, bool),
    Failed(String),
}

#[derive(Default)]
pub struct VideoLoader {
    clips: Mutex<HashMap<String, State>>,
}

static LOADER: OnceLock<Arc<VideoLoader>> = OnceLock::new();

pub fn install(ctx: &egui::Context) {
    let loader = LOADER.get_or_init(|| Arc::new(VideoLoader::default())).clone();
    let _ = CTX.set(ctx.clone());
    // Two decode threads for all animations (not a thread per GIF).
    let (tx, rx) = std::sync::mpsc::channel::<(String, Arc<[u8]>)>();
    let rx = Arc::new(Mutex::new(rx));
    for i in 0..2 {
        let (rx, ctx) = (rx.clone(), ctx.clone());
        let _ = std::thread::Builder::new().name(format!("rustcord-anim-{i}")).spawn(move || loop {
            let job = rx.lock().ok().and_then(|r| r.recv().ok());
            let Some((key, bytes)) = job else { return };
            let file = key.clone();
            let result = if bytes.iter().find(|b| !b.is_ascii_whitespace()) == Some(&b'{') {
                // Lottie (Discord's own stickers): JSON drawn frame by frame.
                decode_lottie(&bytes, &key)
            } else if bytes.starts_with(b"GIF8") {
                decode_gif(&bytes, decode_limits(&key))
            } else if bytes.starts_with(b"\x89PNG") {
                // Avatar decorations and profile effects: animated PNG (APNG).
                decode_apng(&bytes, decode_limits_within(&key, EFFECT_MAX))
            } else if bytes.len() > 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
                decode_webp(&bytes, decode_limits_within(&key, EFFECT_MAX))
            } else {
                decode_mp4(&bytes, decode_limits(&key))
            };
            let state = match result {
                Ok(clip) => {
                    let size = clip.frames.first().map(|f| f.size).or_else(|| clip.packed.first().map(|p| [p.w, p.h])).unwrap_or_default();
                    log::debug!("anim: {} decoded, {} frames at {}x{}, {} KB", crate::net_images::log_url(&key), clip.len(), size[0], size[1], clip.byte_size() / 1024);
                    State::Ready(Arc::new(clip), Instant::now())
                }
                Err(e) => {
                    log::debug!("animation decode failed for {}: {e}", crate::net_images::log_url(&key));
                    State::Failed(e)
                }
            };
            if let Some(l) = LOADER.get() {
                if let Ok(mut c) = l.clips.lock() {
                    // Only if not forgotten meanwhile.
                    if matches!(c.get(&key), Some(State::Decoding | State::Released(_, true))) {
                        c.insert(key, state);
                    }
                }
            }
            drop(bytes);
            // The clip is decoded: its file isn't needed in memory any more.
            crate::net_images::forget_file(clip_source(&file));
            crate::diagnostics::release_this_threads_memory();
            ctx.request_repaint();
        });
    }
    let _ = JOBS.set(Mutex::new(tx));
    ctx.add_image_loader(loader);
}

/// The name a clip goes by in here and in its frame URIs. egui plays GIFs by
/// itself: any image whose URI ends in ".gif" or has ".gif#" in it gets
/// "#<frame>" added and goes to egui_extras' GIF loader, which decodes the
/// whole file on the UI thread, keeps every frame at full size, and wakes the
/// window at each GIF's own pace. RustCord's frame URI of a GIF file with no query
/// ("x.gif#vframe=12") looked like that: egui then decoded the whole GIF once
/// per frame *number* (hundreds of MB for a few GIFs, a stall each time) and
/// redrew ~100 times a second. So a clip's key never looks like a GIF to
/// egui: an empty query goes after a final ".gif" ("x.gif" → "x.gif?",
/// "x.gif#anim" → "x.gif?#anim"). [`clip_source`] undoes it for loading.
pub fn clip_key(url: &str) -> std::borrow::Cow<'_, str> {
    use std::borrow::Cow;
    if !url.ends_with(".gif") && !url.contains(".gif#") {
        return Cow::Borrowed(url);
    }
    let (path, fragment) = match url.split_once('#') {
        Some((p, f)) => (p, Some(f)),
        None => (url, None),
    };
    let mut key = String::with_capacity(url.len() + 2);
    key.push_str(path);
    if path.ends_with(".gif") {
        key.push(if path.contains('?') { '&' } else { '?' });
    }
    if let Some(f) = fragment {
        // (Fragments are RustCord's, never sent: anything will do there.)
        key.push('#');
        key.push_str(&f.replace(".gif#", ".gif~#"));
        if f.ends_with(".gif") {
            key.push('~');
        }
    }
    Cow::Owned(key)
}

/// Where a clip's file is: its key without what [`clip_key`] added (a file
/// already in memory, `bytes://…`, is only found under its exact name).
fn clip_source(key: &str) -> &str {
    let path = key.split('#').next().unwrap_or(key);
    if path.ends_with(".gif?") || path.ends_with(".gif&") {
        &path[..path.len() - 1]
    } else {
        path
    }
}

/// The clip could not be decoded (a codec Windows doesn't have, a broken file).
pub fn failed(url: &str) -> bool {
    let Some(loader) = LOADER.get() else { return false };
    loader.clips.lock().is_ok_and(|c| matches!(c.get(clip_key(url).as_ref()), Some(State::Failed(_))))
}

/// [`current_frame`] with the app's context (for code without one at hand).
pub fn frame_uri(url: &str, playing: bool) -> Option<String> {
    current_frame(CTX.get()?, url, playing)
}

/// `x.mp4#vframe=3` → (`x.mp4`, 3).
pub fn split_frame_uri(uri: &str) -> Option<(&str, usize)> {
    let (base, n) = uri.rsplit_once(FRAME_TAG)?;
    Some((base, n.parse().ok()?))
}

/// URI of the frame of `url` to draw right now, once the clip is decoded
/// (None until then: show the still thumbnail). Starts the download and
/// decode on first call, and schedules the next redraw while playing.
pub fn current_frame(ctx: &egui::Context, url: &str, playing: bool) -> Option<String> {
    frame_of(ctx, url, playing, None)
}

/// [`current_frame`] for a clip on a clock of its own (a profile effect's
/// layer): the frame `at_ms` into it, going round again when `looped` and
/// staying on its last frame when not.
pub fn frame_at(ctx: &egui::Context, url: &str, at_ms: u64, looped: bool) -> Option<String> {
    frame_of(ctx, url, true, Some((at_ms, looped)))
}

fn frame_of(ctx: &egui::Context, url: &str, playing: bool, own_clock: Option<(u64, bool)>) -> Option<String> {
    let loader = LOADER.get()?;
    let key = clip_key(url);
    let url = key.as_ref();
    // Look up, then let go of the lock before asking egui to load anything
    // (the load comes back into this loader and takes the lock itself).
    let state = loader.clips.lock().ok()?.get_mut(url).map(|s| match s {
        State::Ready(c, played) => {
            if playing {
                *played = Instant::now();
            }
            Some((c.clone(), false))
        }
        State::Released(c, decoding) => Some((c.clone(), playing && !*decoding)),
        _ => None,
    });
    let clip = match state {
        Some(Some((c, redecode))) => {
            // Its frames were released and it plays again: decode it again
            // (the still shows until then).
            if redecode {
                loader.redecode(ctx, url);
            }
            c
        }
        Some(None) => return None,
        None => {
            // Not playing (the window isn't focused, animations are off, the
            // pointer isn't on it): the caller shows its still. Nothing is
            // downloaded or decoded for a clip until it is actually to play;
            // decoding every clip in view just to throw the frames away ten
            // seconds later was most of a channel's start-up memory.
            if !playing {
                return None;
            }
            // Kick off: asking for frame 0 fetches the file and starts decoding.
            let _ = ctx.try_load_image(&format!("{url}{FRAME_TAG}0"), SizeHint::default());
            return None;
        }
    };
    let total = *clip.ends_ms.last()?;
    if !playing || clip.len() < 2 || total == 0 {
        return Some(format!("{url}{FRAME_TAG}0"));
    }
    let t = (ctx.input(|i| i.time) * 1000.0) as u64;
    let now = match own_clock {
        Some((at, true)) => at % total,
        // Played through: its last frame, and nothing more to wake for.
        Some((at, false)) if at >= total => return Some(format!("{url}{FRAME_TAG}{}", clip.len() - 1)),
        Some((at, false)) => at,
        None => t % total,
    };
    let idx = clip.ends_ms.partition_point(|&end| end <= now).min(clip.len() - 1);
    // The shared clock: the next redraw this clip needs, moved onto a global
    // 33 ms grid so every animation on screen asks for the *same* moment —
    // any number of them then costs ≤ 30 redraws a second.
    let due = t + clip.ends_ms[idx].saturating_sub(now);
    let mut tick = due.div_ceil(TICK_MS) * TICK_MS;
    if tick < t + TICK_MS / 3 {
        tick += TICK_MS; // woke a little early: don't add an extra frame
    }
    // egui wakes one predicted frame *before* any delay it's given (to not
    // overshoot); without adding it back, 33 ms became ~17 ms (60 fps).
    let early = ctx.input(|i| i.predicted_dt).max(0.0) as f64;
    ctx.request_repaint_after(std::time::Duration::from_secs_f64((tick - t) as f64 / 1000.0 + early));
    Some(format!("{url}{FRAME_TAG}{idx}"))
}

/// Release the frames of clips that haven't played for [`IDLE`] (called
/// every few seconds by the texture cache's sweep).
pub fn release_idle() {
    let Some(loader) = LOADER.get() else { return };
    let Ok(mut clips) = loader.clips.lock() else { return };
    for state in clips.values_mut() {
        if let State::Ready(clip, played) = state {
            if clip.len() > 1 && played.elapsed() >= IDLE {
                *state = State::Released(Arc::new(clip.still()), false);
            }
        }
    }
}

impl VideoLoader {
    /// Decode a released clip again. Its file may have to come back from
    /// disk first: then this is simply tried again on the next frame.
    fn redecode(&self, ctx: &egui::Context, url: &str) {
        let Ok(BytesPoll::Ready { bytes, .. }) = ctx.try_load_bytes(clip_source(url)) else { return };
        let Ok(mut clips) = self.clips.lock() else { return };
        let Some(State::Released(_, decoding)) = clips.get_mut(url) else { return };
        if *decoding {
            return;
        }
        let bytes: Arc<[u8]> = Arc::from(&bytes[..]);
        *decoding = JOBS.get().and_then(|j| j.lock().ok()).is_some_and(|tx| tx.send((url.to_string(), bytes)).is_ok());
    }
}

impl ImageLoader for VideoLoader {
    fn id(&self) -> &str {
        egui::generate_loader_id!(VideoLoader)
    }

    fn load(&self, ctx: &egui::Context, uri: &str, _: SizeHint) -> ImageLoadResult {
        let Some((base, idx)) = split_frame_uri(uri) else { return Err(LoadError::NotSupported) };
        {
            let clips = self.clips.lock().map_err(|_| LoadError::Loading("poisoned".into()))?;
            match clips.get(base) {
                Some(State::Ready(c, _) | State::Released(c, _)) => {
                    return Ok(ImagePoll::Ready { image: c.image(idx) });
                }
                Some(State::Decoding) => return Ok(ImagePoll::Pending { size: None }),
                Some(State::Failed(e)) => return Err(LoadError::Loading(e.clone())),
                None => {}
            }
        }
        match ctx.try_load_bytes(clip_source(base)) {
            Ok(BytesPoll::Pending { .. }) => Ok(ImagePoll::Pending { size: None }),
            Ok(BytesPoll::Ready { bytes, .. }) => {
                let bytes: Arc<[u8]> = Arc::from(&bytes[..]);
                if let Ok(mut c) = self.clips.lock() {
                    c.insert(base.to_string(), State::Decoding);
                }
                let sent = JOBS.get().and_then(|j| j.lock().ok()).map(|tx| tx.send((base.to_string(), bytes)).is_ok()).unwrap_or(false);
                if !sent {
                    return Err(LoadError::Loading("animation decoder not running".into()));
                }
                Ok(ImagePoll::Pending { size: None })
            }
            Err(e) => Err(e),
        }
    }

    fn forget(&self, uri: &str) {
        let base = split_frame_uri(uri).map(|(b, _)| b).unwrap_or(uri);
        if let Ok(mut c) = self.clips.lock() {
            c.remove(clip_key(base).as_ref());
        }
    }

    fn forget_all(&self) {
        if let Ok(mut c) = self.clips.lock() {
            c.clear();
        }
    }

    fn byte_size(&self) -> usize {
        self.clips
            .lock()
            .map(|c| {
                c.values()
                    .map(|s| match s {
                        State::Ready(clip, _) | State::Released(clip, _) => clip.byte_size(),
                        _ => 0,
                    })
                    .sum()
            })
            .unwrap_or(0)
    }
}

/// MP4 → frames scaled to fit `limits` (see [`decode_limits`]), with their
/// timing (GIF clips).
#[cfg(windows)]
fn decode_mp4(bytes: &[u8], (max_w, max_h, max_frames): (usize, usize, usize)) -> Result<Clip, String> {
    let mut frames: Vec<(i64, Packed)> = Vec::new();
    mp4_frames(bytes, &|w, h, px| scale_within(w, h, px, max_w, max_h), &mut |ts, img| {
        frames.push((ts, Packed::pack(&img)));
        frames.len() < max_frames * 3
    })?;
    clip_from_frames(frames, max_frames)
}

/// Decode an MP4 with Windows' own decoder (Media Foundation: every H.264
/// profile, B-frames, GPU-assisted), handing each frame (timestamp in 100 ns,
/// image made by `scale`) to `on_frame` until it returns false.
#[cfg(windows)]
pub fn mp4_frames(bytes: &[u8], scale: &dyn Fn(usize, usize, Vec<u8>) -> ColorImage, on_frame: &mut dyn FnMut(i64, ColorImage) -> bool) -> Result<(), String> {
    mp4_frames_ctl(MediaSrc::Bytes(bytes), scale, &mut || None, &mut |_| {}, on_frame)
}

/// Where a video comes from: bytes already in memory (short GIF clips), or
/// an address Media Foundation reads itself — an https URL (streamed, with
/// range requests for seeking) or a file path. A player uses the latter so
/// the file is never held in RustCord's memory.
#[derive(Clone, Copy)]
pub enum MediaSrc<'a> {
    Bytes(&'a [u8]),
    Url(&'a str),
}

#[cfg(windows)]
unsafe fn open_reader(src: MediaSrc, attrs: Option<&windows::Win32::Media::MediaFoundation::IMFAttributes>) -> Result<windows::Win32::Media::MediaFoundation::IMFSourceReader, String> {
    use windows::Win32::Media::MediaFoundation::*;
    use windows::Win32::UI::Shell::SHCreateMemStream;
    let e = |e: windows::core::Error| e.message().to_string();
    match src {
        MediaSrc::Bytes(bytes) => {
            let stream = SHCreateMemStream(Some(bytes)).ok_or("couldn't wrap the video in memory")?;
            let bs = MFCreateMFByteStreamOnStream(&stream).map_err(e)?;
            MFCreateSourceReaderFromByteStream(&bs, attrs).map_err(e)
        }
        MediaSrc::Url(url) => MFCreateSourceReaderFromURL(&windows::core::HSTRING::from(url), attrs).map_err(e),
    }
}

/// [`mp4_frames`] for a player: `seek` is asked before every frame for a
/// position to jump to (100 ns; decoding resumes at the key frame before it),
/// and `on_duration` is told the clip's length once, when it is known.
#[cfg(windows)]
pub fn mp4_frames_ctl(
    src: MediaSrc,
    scale: &dyn Fn(usize, usize, Vec<u8>) -> ColorImage,
    seek: &mut dyn FnMut() -> Option<i64>,
    on_duration: &mut dyn FnMut(i64),
    on_frame: &mut dyn FnMut(i64, ColorImage) -> bool,
) -> Result<(), String> {
    use windows::Win32::Media::MediaFoundation::*;
    use windows::Win32::System::Com::{CoInitializeEx, COINIT_MULTITHREADED};
    let e = |e: windows::core::Error| e.message().to_string();
    unsafe {
        let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
        MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET).map_err(e)?;
        let result = (|| -> Result<(), String> {
            let mut attrs: Option<IMFAttributes> = None;
            MFCreateAttributes(&mut attrs, 2).map_err(e)?;
            let attrs = attrs.ok_or("no attributes")?;
            // Let the reader convert whatever the decoder outputs to RGB32.
            attrs.SetUINT32(&MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING, 1).map_err(e)?;
            let reader = open_reader(src, Some(&attrs))?;
            let stream_ix = MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32;
            // Only pictures here: the sound has its own reader.
            let _ = reader.SetStreamSelection(MF_SOURCE_READER_ALL_STREAMS.0 as u32, false);
            let _ = reader.SetStreamSelection(stream_ix, true);
            let want = MFCreateMediaType().map_err(e)?;
            want.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video).map_err(e)?;
            want.SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_RGB32).map_err(e)?;
            reader.SetCurrentMediaType(stream_ix, None, &want).map_err(e)?;
            // Frame layout: (width, height, stride, visible x, y, w, h). The
            // decoder may change it after the first frame (it learns the real,
            // padded size), so it's re-read whenever the reader says so.
            let format = |reader: &IMFSourceReader| -> Result<(usize, usize, i32, usize, usize, usize, usize), String> {
                let got = reader.GetCurrentMediaType(stream_ix).map_err(e)?;
                let size = got.GetUINT64(&MF_MT_FRAME_SIZE).map_err(e)?;
                let (w, h) = ((size >> 32) as usize, (size & 0xffff_ffff) as usize);
                if w == 0 || h == 0 {
                    return Err("video has no size".into());
                }
                // Negative stride: rows are stored bottom-up.
                let stride = got.GetUINT32(&MF_MT_DEFAULT_STRIDE).map(|s| s as i32).unwrap_or((w * 4) as i32);
                // Decoders pad frames (e.g. to multiples of 16); the visible part
                // is the "minimum display aperture": {x, y, width, height}.
                let mut blob = [0u8; 16];
                let (ax, ay, aw, ah) = match got.GetBlob(&MF_MT_MINIMUM_DISPLAY_APERTURE, &mut blob, None) {
                    Ok(()) => {
                        let ox = i16::from_le_bytes([blob[2], blob[3]]).max(0) as usize;
                        let oy = i16::from_le_bytes([blob[6], blob[7]]).max(0) as usize;
                        let cw = i32::from_le_bytes([blob[8], blob[9], blob[10], blob[11]]).max(0) as usize;
                        let ch = i32::from_le_bytes([blob[12], blob[13], blob[14], blob[15]]).max(0) as usize;
                        if cw > 0 && ch > 0 && ox + cw <= w && oy + ch <= h {
                            (ox, oy, cw, ch)
                        } else {
                            (0, 0, w, h)
                        }
                    }
                    Err(_) => (0, 0, w, h),
                };
                Ok((w, h, stride, ax, ay, aw, ah))
            };
            let (mut w, mut h, mut stride, mut ax, mut ay, mut aw, mut ah) = format(&reader)?;
            if let Ok(pv) = reader.GetPresentationAttribute(MF_SOURCE_READER_MEDIASOURCE.0 as u32, &MF_PD_DURATION) {
                if let Ok(d) = u64::try_from(&pv) {
                    on_duration(d as i64);
                }
            }

            loop {
                if let Some(pos) = seek() {
                    let at = windows::core::PROPVARIANT::from(pos.max(0));
                    reader.SetCurrentPosition(&windows::core::GUID::zeroed(), &at).map_err(e)?;
                }
                let mut flags = 0u32;
                let mut ts = 0i64;
                let mut sample: Option<IMFSample> = None;
                reader.ReadSample(stream_ix, 0, None, Some(&mut flags), Some(&mut ts), Some(&mut sample)).map_err(e)?;
                if flags & MF_SOURCE_READERF_ENDOFSTREAM.0 as u32 != 0 {
                    break;
                }
                if flags & MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED.0 as u32 != 0 {
                    (w, h, stride, ax, ay, aw, ah) = format(&reader)?;
                }
                let Some(sample) = sample else { continue };
                // The decoder's own buffer keeps its 2-D layout (a contiguous
                // copy doesn't); fall back to the copy only if needed.
                let buf = match sample.GetBufferByIndex(0) {
                    Ok(b) => b,
                    Err(_) => sample.ConvertToContiguousBuffer().map_err(e)?,
                };
                let mut rgba = vec![0u8; aw * ah * 4];
                // BGRX row `y` (top-down) → RustCord's RGBA row.
                let mut put_row = |y: usize, src: &[u8]| {
                    for x in 0..aw.min(src.len() / 4) {
                        let (s, d) = (x * 4, (y * aw + x) * 4);
                        rgba[d] = src[s + 2];
                        rgba[d + 1] = src[s + 1];
                        rgba[d + 2] = src[s];
                        rgba[d + 3] = 255;
                    }
                };
                // The real row pitch comes from the 2-D buffer; padded rows are
                // why a wrong guess shows up as diagonal stripes.
                if let Ok(b2) = windows::core::Interface::cast::<IMF2DBuffer>(&buf) {
                    let mut scan0 = std::ptr::null_mut::<u8>();
                    let mut pitch = 0i32;
                    b2.Lock2D(&mut scan0, &mut pitch).map_err(e)?;
                    for y in 0..ah {
                        let row = scan0.offset((ay + y) as isize * pitch as isize).add(ax * 4);
                        put_row(y, std::slice::from_raw_parts(row, aw * 4));
                    }
                    let _ = b2.Unlock2D();
                } else {
                    let mut ptr = std::ptr::null_mut::<u8>();
                    let mut len = 0u32;
                    buf.Lock(&mut ptr, None, Some(&mut len)).map_err(e)?;
                    let data = std::slice::from_raw_parts(ptr, len as usize);
                    // Pitch: the media type's stride, else from the buffer size.
                    let row = if stride.unsigned_abs() as usize >= w * 4 { stride.unsigned_abs() as usize } else { (len as usize / h).max(w * 4) };
                    for y in 0..ah {
                        let sy = ay + y;
                        let src_y = if stride < 0 { h - 1 - sy } else { sy };
                        let start = (src_y * row + ax * 4).min(data.len());
                        put_row(y, &data[start..(start + aw * 4).min(data.len())]);
                    }
                    let _ = buf.Unlock();
                }
                if !on_frame(ts, scale(aw, ah, rgba)) {
                    break;
                }
            }
            Ok(())
        })();
        let _ = MFShutdown();
        result
    }
}

/// A video's sound, decoded by Media Foundation (every AAC flavour, MP3,
/// AC-3…) as it is needed: `on_format` gets (channels, sample rate) once,
/// then `on_chunk` each block of interleaved samples until it returns false.
/// `seek` is asked before every block for a position to jump to (100 ns);
/// at the end it is polled until it gives one (a replay) or `on_chunk`
/// (called with an empty block) says stop. `Ok(false)`: no audio track.
#[cfg(windows)]
pub fn mp4_audio_stream(
    src: MediaSrc,
    seek: &mut dyn FnMut() -> Option<i64>,
    on_format: &mut dyn FnMut(u16, u32),
    on_chunk: &mut dyn FnMut(Vec<f32>) -> bool,
) -> Result<bool, String> {
    use windows::Win32::Media::MediaFoundation::*;
    use windows::Win32::System::Com::{CoInitializeEx, COINIT_MULTITHREADED};
    let e = |e: windows::core::Error| e.message().to_string();
    unsafe {
        let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
        MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET).map_err(e)?;
        let result = (|| -> Result<bool, String> {
            let reader = open_reader(src, None)?;
            let ix = MF_SOURCE_READER_FIRST_AUDIO_STREAM.0 as u32;
            // Only the sound: don't decode pictures along the way.
            let _ = reader.SetStreamSelection(MF_SOURCE_READER_ALL_STREAMS.0 as u32, false);
            if reader.SetStreamSelection(ix, true).is_err() {
                return Ok(false);
            }
            let want = MFCreateMediaType().map_err(e)?;
            want.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Audio).map_err(e)?;
            want.SetGUID(&MF_MT_SUBTYPE, &MFAudioFormat_PCM).map_err(e)?;
            want.SetUINT32(&MF_MT_AUDIO_BITS_PER_SAMPLE, 16).map_err(e)?;
            if reader.SetCurrentMediaType(ix, None, &want).is_err() {
                return Ok(false);
            }
            let got = reader.GetCurrentMediaType(ix).map_err(e)?;
            let channels = got.GetUINT32(&MF_MT_AUDIO_NUM_CHANNELS).map_err(e)?;
            let rate = got.GetUINT32(&MF_MT_AUDIO_SAMPLES_PER_SECOND).map_err(e)?;
            if got.GetUINT32(&MF_MT_AUDIO_BITS_PER_SAMPLE).unwrap_or(16) != 16 || channels == 0 || rate == 0 {
                return Err("unexpected audio format".into());
            }
            on_format(channels as u16, rate);
            let mut ended = false;
            loop {
                if let Some(pos) = seek() {
                    let at = windows::core::PROPVARIANT::from(pos.max(0));
                    reader.SetCurrentPosition(&windows::core::GUID::zeroed(), &at).map_err(e)?;
                    ended = false;
                }
                if ended {
                    // Wait for a replay (or to be told to stop).
                    if !on_chunk(Vec::new()) {
                        return Ok(true);
                    }
                    std::thread::sleep(std::time::Duration::from_millis(30));
                    continue;
                }
                let mut flags = 0u32;
                let mut sample: Option<IMFSample> = None;
                reader.ReadSample(ix, 0, None, Some(&mut flags), None, Some(&mut sample)).map_err(e)?;
                if flags & MF_SOURCE_READERF_ENDOFSTREAM.0 as u32 != 0 {
                    ended = true;
                    continue;
                }
                let Some(sample) = sample else { continue };
                let buf = sample.ConvertToContiguousBuffer().map_err(e)?;
                let mut ptr = std::ptr::null_mut::<u8>();
                let mut len = 0u32;
                buf.Lock(&mut ptr, None, Some(&mut len)).map_err(e)?;
                let data = std::slice::from_raw_parts(ptr, len as usize);
                let pcm: Vec<f32> = data.chunks_exact(2).map(|b| i16::from_le_bytes([b[0], b[1]]) as f32 / 32768.0).collect();
                let _ = buf.Unlock();
                if !on_chunk(pcm) {
                    return Ok(true);
                }
            }
        })();
        let _ = MFShutdown();
        result
    }
}

/// A looping clip from decoded frames (at most `max_frames` kept).
#[cfg(windows)]
fn clip_from_frames(frames: Vec<(i64, Packed)>, max_frames: usize) -> Result<Clip, String> {
    {
        {
            if frames.is_empty() {
                return Err("no frames decoded".into());
            }
            // Timing from timestamps (100 ns units); keep at most `max_frames`.
            let keep_every = frames.len().div_ceil(max_frames).max(1);
            let last_gap = if frames.len() > 1 { frames[frames.len() - 1].0 - frames[frames.len() - 2].0 } else { 1_000_000 };
            let end_ts = frames.last().map(|f| f.0 + last_gap.max(100_000)).unwrap_or(0);
            let mut ends_ms = Vec::new();
            let start = frames[0].0;
            let stamps: Vec<i64> = frames.iter().map(|f| f.0).collect();
            let total = frames.len();
            let kept: Vec<usize> = (0..total).step_by(keep_every).collect();
            for (k, _) in kept.iter().enumerate() {
                let next_ts = kept.get(k + 1).map(|&j| stamps[j]).unwrap_or(end_ts);
                ends_ms.push(((next_ts - start).max(0) / 10_000) as u64);
            }
            let out: Vec<Packed> = frames.into_iter().step_by(keep_every).map(|f| f.1).collect();
            // Strictly increasing ends (some clips repeat timestamps).
            let mut prev = 0;
            for end in ends_ms.iter_mut() {
                *end = (*end).max(prev + 10);
                prev = *end;
            }
            let (w, h) = out.first().map_or((0, 0), |p| (p.w, p.h));
            log::debug!("gifv: {total} frames decoded, {} kept at {w}x{h} ({} KB), {} ms long", out.len(), out.iter().map(|p| p.data.len()).sum::<usize>() / 1024, ends_ms.last().copied().unwrap_or(0));
            Ok(Clip { frames: Vec::new(), packed: out, ends_ms })
        }
    }
}

#[cfg(not(windows))]
fn decode_mp4(_bytes: &[u8], _limits: (usize, usize, usize)) -> Result<Clip, String> {
    Err("video decoding is only available on Windows".into())
}

/// GIF file → frames scaled to fit `limits` (see [`decode_limits`]), with
/// their timing.
fn decode_gif(bytes: &[u8], (max_w, max_h, max_frames): (usize, usize, usize)) -> Result<Clip, String> {
    use image::AnimationDecoder;
    let decoder = image::codecs::gif::GifDecoder::new(std::io::Cursor::new(bytes)).map_err(|e| e.to_string())?;
    let mut out = Collected::default();
    for f in decoder.into_frames().take(max_frames * 3) {
        let f = f.map_err(|e| e.to_string())?;
        let (num, den) = f.delay().numer_denom_ms();
        // Browsers (and Discord) treat tiny GIF delays as 100 ms.
        let ms = if den == 0 { 100 } else { (num / den.max(1)) as u64 };
        let ms = if ms <= 10 { 100 } else { ms };
        let buf = f.into_buffer();
        let (w, h) = (buf.width() as usize, buf.height() as usize);
        out.push(scale_within(w, h, buf.into_raw(), max_w, max_h), ms);
    }
    out.into_clip(max_frames)
}

/// Frames from an `AnimationDecoder` (APNG, animated WebP), at full size up to
/// the limits (decorations and profile effects are small already), with timing.
fn decode_frames(frames: image::Frames<'_>, (max_w, max_h, max_frames): (usize, usize, usize)) -> Result<Clip, String> {
    let mut out = Collected::default();
    for f in frames.take(max_frames * 3) {
        let f = f.map_err(|e| e.to_string())?;
        let (num, den) = f.delay().numer_denom_ms();
        let ms = if den == 0 { 40 } else { (num / den.max(1)) as u64 };
        let ms = ms.max(16);
        let buf = f.into_buffer();
        let (w, h) = (buf.width() as usize, buf.height() as usize);
        out.push(scale_within(w, h, buf.into_raw(), max_w, max_h), ms);
    }
    out.into_clip(max_frames)
}

/// The clip key of a Lottie sticker drawn `size` px square: `still` keys
/// draw only the first frame (stickers that aren't playing).
pub fn lottie_key(url: &str, size: u32, still: bool) -> String {
    format!("{url}#lottie={size}{}", if still { ",still" } else { "" })
}

/// Lottie JSON → frames (at most 30 a second) `size` px square, as the key
/// asks (see [`lottie_key`]).
fn decode_lottie(bytes: &[u8], key: &str) -> Result<Clip, String> {
    let opts = key.rsplit_once("#lottie=").map(|(_, o)| o).unwrap_or("160");
    let (size, still) = match opts.split_once(',') {
        Some((n, rest)) => (n, rest == "still"),
        None => (opts, false),
    };
    let size: u32 = size.parse().unwrap_or(160).clamp(16, 512);
    let anim = crate::lottie::Animation::parse(bytes)?;
    let to_image = |px: tiny_skia::Pixmap| ColorImage::from_rgba_premultiplied([px.width() as usize, px.height() as usize], px.data());
    if still {
        let px = anim.render(anim.ip, size).ok_or("could not draw the sticker")?;
        return Ok(Clip { frames: vec![Arc::new(to_image(px))], packed: Vec::new(), ends_ms: vec![0] });
    }
    // 60 fps files are drawn at 30: every second frame.
    let step = (anim.fr / 30.0).max(1.0);
    let count = (((anim.op - anim.ip) / step).ceil() as usize).clamp(1, MAX_FRAMES);
    let (mut frames, mut ends_ms) = (Vec::with_capacity(count), Vec::with_capacity(count));
    for k in 0..count {
        let px = anim.render(anim.ip + k as f64 * step, size).ok_or("could not draw the sticker")?;
        frames.push(Arc::new(to_image(px)));
        ends_ms.push((((k + 1) as f64 * step / anim.fr) * 1000.0).round() as u64);
    }
    Ok(Clip { frames, packed: Vec::new(), ends_ms })
}

/// Animated PNG. A plain PNG comes out as a one-frame clip.
fn decode_apng(bytes: &[u8], limits: (usize, usize, usize)) -> Result<Clip, String> {
    use image::AnimationDecoder;
    let decoder = image::codecs::png::PngDecoder::new(std::io::Cursor::new(bytes)).map_err(|e| e.to_string())?;
    if !decoder.is_apng().map_err(|e| e.to_string())? {
        let img = crate::net_images::decode_limited(bytes).map_err(|e| e.to_string())?.to_rgba8();
        let (w, h) = (img.width() as usize, img.height() as usize);
        return Ok(Clip { frames: vec![Arc::new(scale_within(w, h, img.into_raw(), limits.0, limits.1))], packed: Vec::new(), ends_ms: vec![1000] });
    }
    decode_frames(decoder.apng().map_err(|e| e.to_string())?.into_frames(), limits)
}

fn decode_webp(bytes: &[u8], limits: (usize, usize, usize)) -> Result<Clip, String> {
    use image::AnimationDecoder;
    let decoder = image::codecs::webp::WebPDecoder::new(std::io::Cursor::new(bytes)).map_err(|e| e.to_string())?;
    decode_frames(decoder.into_frames(), limits)
}

fn scale_within(w: usize, h: usize, rgba: Vec<u8>, max_w: usize, max_h: usize) -> ColorImage {
    let scale = (max_w as f32 / w as f32).min(max_h as f32 / h as f32);
    if scale >= 1.0 {
        return ColorImage::from_rgba_unmultiplied([w, h], &rgba);
    }
    let (nw, nh) = (((w as f32 * scale) as u32).max(1), ((h as f32 * scale) as u32).max(1));
    match image::RgbaImage::from_raw(w as u32, h as u32, rgba) {
        Some(img) => {
            let small = image::imageops::resize(&img, nw, nh, image::imageops::FilterType::Triangle);
            ColorImage::from_rgba_unmultiplied([nw as usize, nh as usize], small.as_raw())
        }
        None => ColorImage::new([1, 1], egui::Color32::TRANSPARENT),
    }
}

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

    #[test]
    fn see_through_frames_keep_their_alpha() {
        let (w, h) = (6usize, 4usize);
        let pixels: Vec<egui::Color32> = (0..w * h).map(|i| if i % 3 == 0 { egui::Color32::TRANSPARENT } else { egui::Color32::from_rgb(200, 40, 40) }).collect();
        let back = Packed::pack(&ColorImage { size: [w, h], pixels: pixels.clone() }).unpack();
        for (a, b) in pixels.iter().zip(&back.pixels) {
            assert_eq!(a.a(), b.a());
            // (Premultiplied: a clear pixel has no colour left.)
            assert!(b.r() <= b.a() && b.g() <= b.a() && b.b() <= b.a());
        }
        // A long clip keeps at most the frames asked for, and its full length.
        let mut c = Collected::default();
        for _ in 0..10 {
            c.push(ColorImage::new([4, 4], egui::Color32::RED), 100);
        }
        let clip = c.into_clip(4).unwrap();
        assert_eq!((clip.len(), clip.ends_ms.last().copied()), (4, Some(1000)));
    }

    #[test]
    fn packed_frames_round_trip_closely() {
        // A smooth gradient (odd size, to cover the edge samples).
        let (w, h) = (9usize, 7usize);
        let pixels: Vec<egui::Color32> = (0..w * h).map(|i| (i % w, i / w)).map(|(x, y)| egui::Color32::from_rgb((x * 6) as u8, 200 - (y * 6) as u8, 40 + (x + y) as u8)).collect();
        let img = ColorImage { size: [w, h], pixels };
        let packed = Packed::pack(&img);
        assert_eq!(packed.data.len(), w * h + 2 * 5 * 4);
        let back = packed.unpack();
        assert_eq!(back.size, [w, h]);
        for (a, b) in img.pixels.iter().zip(&back.pixels) {
            for (x, y) in [(a.r(), b.r()), (a.g(), b.g()), (a.b(), b.b())] {
                assert!((x as i32 - y as i32).abs() <= 12, "{a:?} vs {b:?}");
            }
        }
        // Grey stays grey.
        let grey = ColorImage { size: [2, 2], pixels: vec![egui::Color32::from_gray(128); 4] };
        let back = Packed::pack(&grey).unpack();
        assert!(back.pixels.iter().all(|p| (p.r() as i32 - 128).abs() <= 2 && p.r() == p.g() && p.g() == p.b()));
    }

    /// egui 0.29's own test for "this is a GIF, I'll play it" (`is_gif_uri`).
    fn egui_plays(uri: &str) -> bool {
        uri.ends_with(".gif") || uri.contains(".gif#")
    }

    #[test]
    fn frame_uris_never_look_like_gifs_to_egui() {
        for url in [
            "https://a/x.gif",
            "https://a/x.gif#anim",
            "https://a/x.gif?size=96",
            "https://a/x.gif?size=96#anim",
            "https://a/p?u=x.gif",
            "https://a/x.png#.gif",
            "https://a/x.png#a.gif#b",
            "bytes://upload/1/x.gif",
            "https://a/x.mp4",
        ] {
            let key = clip_key(url);
            let frame = format!("{key}{FRAME_TAG}12");
            assert!(!egui_plays(&frame), "{frame}");
            assert_eq!(split_frame_uri(&frame), Some((key.as_ref(), 12)), "{url}");
            // A key is its own key, and its file is the address it came from.
            assert_eq!(clip_key(&key), key, "{url}");
            assert_eq!(clip_source(&key), url.split('#').next().unwrap(), "{url}");
        }
        // Nothing is touched that didn't need it.
        assert!(matches!(clip_key("https://a/x.gif?size=96"), std::borrow::Cow::Borrowed(_)));
        assert!(matches!(clip_key("https://a/x.mp4#anim"), std::borrow::Cow::Borrowed(_)));
    }

    #[test]
    fn effect_layers_decode_at_card_size() {
        let url = "https://cdn.discordapp.com/assets/collectibles/effect.png";
        // Rounded up to 64 px, never past the usual limit.
        let key = effect_key(url, 300.0);
        assert_eq!(key, format!("{url}#{EFFECT_TAG}320"));
        assert_eq!(effect_key(url, 290.0), key);
        assert_eq!(decode_limits_within(&key, EFFECT_MAX), (320, EFFECT_MAX.1, MAX_FRAMES));
        assert_eq!(decode_limits_within(&effect_key(url, 4000.0), EFFECT_MAX).0, EFFECT_MAX.0);
        assert_eq!(decode_limits_within(&effect_key(url, 0.0), EFFECT_MAX).0, 64);
        // A layer without the tag (avatar decorations) keeps the usual limits.
        assert_eq!(decode_limits_within(url, EFFECT_MAX), (EFFECT_MAX.0, EFFECT_MAX.1, MAX_FRAMES));
        // The file is still the layer's own address, and frames find their clip.
        assert_eq!(clip_key(&key), key);
        assert_eq!(clip_source(&key), url);
        let frame = format!("{key}{FRAME_TAG}12");
        assert_eq!(split_frame_uri(&frame), Some((key.as_str(), 12)));
    }
}