Skip to content

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

9.5 KB
Raw Blame
//! An avatar's dominant colour, the way Discord's web client picks the
//! banner colour for a profile with no banner or accent colour: every 10th
//! pixel (skipping see-through and near-white ones), median-cut quantised to
//! 5 colours (the "quantize" / Color Thief MMCQ algorithm), then the colour of
//! the box with the largest pixel count × volume.

use std::collections::HashMap;
use std::sync::Mutex;

const SIGBITS: u32 = 5;
const RSHIFT: u32 = 8 - SIGBITS;
const MAX_ITERATIONS: usize = 1000;
const FRACT_BY_POPULATIONS: f64 = 0.75;

fn index(r: usize, g: usize, b: usize) -> usize {
    (r << (2 * SIGBITS)) + (g << SIGBITS) + b
}

#[derive(Clone, Debug)]
struct VBox {
    r1: usize,
    r2: usize,
    g1: usize,
    g2: usize,
    b1: usize,
    b2: usize,
    count: u64,
}

impl VBox {
    fn new(r1: usize, r2: usize, g1: usize, g2: usize, b1: usize, b2: usize, histo: &[u64]) -> Self {
        let mut v = VBox { r1, r2, g1, g2, b1, b2, count: 0 };
        v.count = v.recount(histo);
        v
    }

    fn recount(&self, histo: &[u64]) -> u64 {
        let mut n = 0;
        for r in self.r1..=self.r2 {
            for g in self.g1..=self.g2 {
                for b in self.b1..=self.b2 {
                    n += histo[index(r, g, b)];
                }
            }
        }
        n
    }

    fn volume(&self) -> u64 {
        ((self.r2 - self.r1 + 1) * (self.g2 - self.g1 + 1) * (self.b2 - self.b1 + 1)) as u64
    }

    fn avg(&self, histo: &[u64]) -> [u8; 3] {
        let mult = (1u64 << RSHIFT) as f64;
        let (mut tot, mut rs, mut gs, mut bs) = (0.0, 0.0, 0.0, 0.0);
        for r in self.r1..=self.r2 {
            for g in self.g1..=self.g2 {
                for b in self.b1..=self.b2 {
                    let h = histo[index(r, g, b)] as f64;
                    tot += h;
                    rs += h * (r as f64 + 0.5) * mult;
                    gs += h * (g as f64 + 0.5) * mult;
                    bs += h * (b as f64 + 0.5) * mult;
                }
            }
        }
        if tot > 0.0 {
            [(rs / tot) as u8, (gs / tot) as u8, (bs / tot) as u8]
        } else {
            let m = |a: usize, b: usize| (mult * (a + b + 1) as f64 / 2.0) as u8;
            [m(self.r1, self.r2), m(self.g1, self.g2), m(self.b1, self.b2)]
        }
    }
}

/// Split a box at the median of its widest side (quantize.js's medianCutApply).
fn median_cut(histo: &[u64], vbox: &VBox) -> Option<(VBox, Option<VBox>)> {
    if vbox.count == 0 {
        return None;
    }
    if vbox.count == 1 {
        return Some((vbox.clone(), None));
    }
    let rw = vbox.r2 - vbox.r1 + 1;
    let gw = vbox.g2 - vbox.g1 + 1;
    let bw = vbox.b2 - vbox.b1 + 1;
    let maxw = rw.max(gw).max(bw);
    // 0 = red, 1 = green, 2 = blue
    let axis = if maxw == rw { 0 } else if maxw == gw { 1 } else { 2 };
    let (lo, hi) = match axis {
        0 => (vbox.r1, vbox.r2),
        1 => (vbox.g1, vbox.g2),
        _ => (vbox.b1, vbox.b2),
    };
    let mut partial = vec![0u64; 1 << SIGBITS];
    let mut total = 0u64;
    for i in lo..=hi {
        let mut sum = 0;
        match axis {
            0 => {
                for g in vbox.g1..=vbox.g2 {
                    for b in vbox.b1..=vbox.b2 {
                        sum += histo[index(i, g, b)];
                    }
                }
            }
            1 => {
                for r in vbox.r1..=vbox.r2 {
                    for b in vbox.b1..=vbox.b2 {
                        sum += histo[index(r, i, b)];
                    }
                }
            }
            _ => {
                for r in vbox.r1..=vbox.r2 {
                    for g in vbox.g1..=vbox.g2 {
                        sum += histo[index(r, g, i)];
                    }
                }
            }
        }
        total += sum;
        partial[i] = total;
    }
    let lookahead = |i: usize| total - partial[i];
    for i in lo..=hi {
        if partial[i] as f64 > total as f64 / 2.0 {
            let left = i - lo;
            let right = hi - i;
            let mut d2 = if left <= right { (hi as i64 - 1).min((i as f64 + right as f64 / 2.0) as i64) } else { (lo as i64).max((i as f64 - 1.0 - left as f64 / 2.0) as i64) };
            d2 = d2.max(lo as i64);
            let mut d2 = d2 as usize;
            // Avoid empty boxes.
            while d2 < hi && partial[d2] == 0 {
                d2 += 1;
            }
            let mut count2 = lookahead(d2);
            while count2 == 0 && d2 > lo && partial[d2 - 1] != 0 {
                d2 -= 1;
                count2 = lookahead(d2);
            }
            let (mut a, mut b) = (vbox.clone(), vbox.clone());
            match axis {
                0 => {
                    a.r2 = d2;
                    b.r1 = d2 + 1;
                }
                1 => {
                    a.g2 = d2;
                    b.g1 = d2 + 1;
                }
                _ => {
                    a.b2 = d2;
                    b.b1 = d2 + 1;
                }
            }
            a.count = a.recount(histo);
            let b = if b.r1 <= b.r2 && b.g1 <= b.g2 && b.b1 <= b.b2 {
                b.count = b.recount(histo);
                Some(b)
            } else {
                None
            };
            return Some((a, b));
        }
    }
    None
}

/// Split boxes (largest first by `key`) until there are `target` of them.
fn iterate(boxes: &mut Vec<VBox>, histo: &[u64], target: f64, key: fn(&VBox) -> u64) {
    let mut ncolors = boxes.len();
    let mut niters = 0;
    while niters < MAX_ITERATIONS {
        if ncolors as f64 >= target {
            return;
        }
        niters += 1;
        boxes.sort_by_key(key);
        let Some(vbox) = boxes.pop() else { return };
        if vbox.count == 0 {
            boxes.push(vbox);
            niters += 1;
            continue;
        }
        let Some((a, b)) = median_cut(histo, &vbox) else { return };
        boxes.push(a);
        if let Some(b) = b {
            boxes.push(b);
            ncolors += 1;
        }
    }
}

/// The colours of `pixels` (RGB), largest box first (quantize.js's palette()).
fn quantize(pixels: &[[u8; 3]], max_colors: usize) -> Vec<[u8; 3]> {
    if pixels.is_empty() || !(2..=256).contains(&max_colors) {
        return Vec::new();
    }
    let mut histo = vec![0u64; 1 << (3 * SIGBITS)];
    let (mut rmin, mut rmax, mut gmin, mut gmax, mut bmin, mut bmax) = (usize::MAX, 0, usize::MAX, 0, usize::MAX, 0);
    for p in pixels {
        let (r, g, b) = ((p[0] >> RSHIFT) as usize, (p[1] >> RSHIFT) as usize, (p[2] >> RSHIFT) as usize);
        histo[index(r, g, b)] += 1;
        rmin = rmin.min(r);
        rmax = rmax.max(r);
        gmin = gmin.min(g);
        gmax = gmax.max(g);
        bmin = bmin.min(b);
        bmax = bmax.max(b);
    }
    let mut boxes = vec![VBox::new(rmin, rmax, gmin, gmax, bmin, bmax, &histo)];
    iterate(&mut boxes, &histo, FRACT_BY_POPULATIONS * max_colors as f64, |v| v.count);
    iterate(&mut boxes, &histo, max_colors as f64, |v| v.count * v.volume());
    boxes.sort_by_key(|v| v.count * v.volume());
    boxes.iter().rev().map(|v| v.avg(&histo)).collect()
}

/// The dominant colour of an RGBA image (Discord's avatar palette, first colour).
pub fn dominant(rgba: &[u8], width: usize, height: usize) -> Option<[u8; 3]> {
    let total = width * height;
    let mut px = Vec::with_capacity(total / 10 + 1);
    let mut i = 0;
    while i < total {
        let o = i * 4;
        if o + 3 < rgba.len() {
            let (r, g, b, a) = (rgba[o], rgba[o + 1], rgba[o + 2], rgba[o + 3]);
            if a >= 125 && !(r > 250 && g > 250 && b > 250) {
                px.push([r, g, b]);
            }
        }
        i += 10;
    }
    quantize(&px, 5).first().copied()
}

/// Dominant colours of decoded avatars, by image address.
fn store() -> &'static Mutex<HashMap<String, [u8; 3]>> {
    static S: std::sync::OnceLock<Mutex<HashMap<String, [u8; 3]>>> = std::sync::OnceLock::new();
    S.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Is this an avatar (whose colour profiles may want)?
pub fn wants(uri: &str) -> bool {
    uri.contains("/avatars/") || uri.contains("/embed/avatars/")
}

pub fn remember(uri: &str, color: [u8; 3]) {
    if let Ok(mut s) = store().lock() {
        if s.len() > 512 {
            s.clear();
        }
        s.insert(uri.to_string(), color);
    }
}

pub fn get(uri: &str) -> Option<[u8; 3]> {
    store().lock().ok().and_then(|s| s.get(uri).copied())
}

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

    #[test]
    fn single_colour_image_is_that_colour() {
        let mut img = Vec::new();
        for _ in 0..(64 * 64) {
            img.extend_from_slice(&[149, 146, 153, 255]);
        }
        let c = dominant(&img, 64, 64).unwrap();
        // Quantised to 5 bits a channel: within one bucket of the input.
        assert!((c[0] as i32 - 149).abs() <= 8 && (c[1] as i32 - 146).abs() <= 8 && (c[2] as i32 - 153).abs() <= 8, "{c:?}");
    }

    #[test]
    fn biggest_area_wins() {
        // Three quarters dark red, a quarter blue: red-ish first.
        let mut img = Vec::new();
        for i in 0..(80 * 80) {
            img.extend_from_slice(if (i / 10) % 4 == 0 { &[20, 40, 220, 255] } else { &[150, 20, 20, 255] });
        }
        let c = dominant(&img, 80, 80).unwrap();
        assert!(c[0] > c[2], "{c:?}");
    }

    #[test]
    fn white_and_clear_pixels_are_skipped() {
        let mut img = Vec::new();
        for i in 0..(50 * 50) {
            img.extend_from_slice(if (i / 10) % 2 == 0 { &[255, 255, 255, 255] } else { &[10, 200, 10, 255] });
        }
        let c = dominant(&img, 50, 50).unwrap();
        assert!(c[1] > 150 && c[0] < 60, "{c:?}");
    }
}