rosier 0.3.0

A fast picture and video viewer for large folders
//! The frosted strip behind the floating controls.
//!
//! gpui cannot blur what is behind an element, so rosier makes the blur
//! itself: the bottom part of each frame is shrunk and box-blurred into a
//! tiny image, which the UI stretches back under the glass pill. Shrinking
//! first makes the blur nearly free (a 1080p frame becomes ~240x30 pixels).

use crate::turbo::Bgra;

/// Fraction of the frame height, from the bottom, that the strip covers.
pub const STRIP: f32 = 0.24;
const SHRINK: u32 = 8;
const RADIUS: i32 = 2;

/// Returns a blurred copy of the bottom `STRIP` of `frame`, shrunk by 8.
pub fn strip(frame: &Bgra) -> Bgra {
    let (w, h) = (frame.width.max(1), frame.height.max(1));
    let y0 = ((h as f32) * (1.0 - STRIP)) as u32;
    let sh = h - y0;
    let (ow, oh) = (w.div_ceil(SHRINK).max(1), sh.div_ceil(SHRINK).max(1));
    // Box-average SHRINKxSHRINK blocks. The result is blurred twice more,
    // so every other pixel of every other row is plenty: a quarter of the
    // reads, which matters at 60 frames a second in 4K.
    let mut small = vec![0u32; (ow * oh * 4) as usize];
    let mut count = vec![0u32; (ow * oh) as usize];
    for y in (y0..h).step_by(2) {
        let oy = ((y - y0) / SHRINK) as usize;
        let row = &frame.pixels[(y * w * 4) as usize..((y + 1) * w * 4) as usize];
        let sums = &mut small[oy * ow as usize * 4..(oy + 1) * ow as usize * 4];
        let counts = &mut count[oy * ow as usize..(oy + 1) * ow as usize];
        for ((block, sum), n) in row.chunks(SHRINK as usize * 4).zip(sums.as_chunks_mut::<4>().0).zip(counts) {
            for p in block.as_chunks::<4>().0.iter().step_by(2) {
                sum[0] += p[0] as u32;
                sum[1] += p[1] as u32;
                sum[2] += p[2] as u32;
                *n += 1;
            }
        }
    }
    let mut px: Vec<u8> = vec![255; (ow * oh * 4) as usize];
    for o in 0..(ow * oh) as usize {
        let n = count[o].max(1);
        for c in 0..3 {
            px[o * 4 + c] = (small[o * 4 + c] / n) as u8;
        }
    }
    // Two separable box-blur passes on the small image.
    for _ in 0..2 {
        blur_axis(&mut px, ow, oh, true);
        blur_axis(&mut px, ow, oh, false);
    }
    Bgra { width: ow, height: oh, pixels: px }
}

/// Cuts the part of a blurred strip that sits under the controls.
///
/// `region` is [x0, y0, x1, y1]: x as fractions of the media width, y as
/// fractions of the strip height. Above or below the strip repeats its edge
/// rows; left or right of the media is black, like the letterbox there.
/// The result is drawn at the controls' exact size with rounded corners, so
/// nothing square peeks out from behind them.
pub fn crop(src: &Bgra, region: [f32; 4]) -> Bgra {
    let (sw, sh) = (src.width.max(1) as f32, src.height.max(1) as f32);
    let [x0, y0, x1, y1] = region;
    let ow = (((x1 - x0) * sw).ceil() as u32).clamp(1, 512);
    let oh = (((y1 - y0) * sh).ceil() as u32).clamp(1, 128);
    let mut px = Vec::with_capacity((ow * oh * 4) as usize);
    for oy in 0..oh {
        let fy = y0 + (y1 - y0) * (oy as f32 + 0.5) / oh as f32;
        let sy = ((fy * sh) as i64).clamp(0, src.height as i64 - 1) as u32;
        for ox in 0..ow {
            let fx = x0 + (x1 - x0) * (ox as f32 + 0.5) / ow as f32;
            if !(0.0..1.0).contains(&fx) {
                // Beside the media is the black letterbox.
                px.extend_from_slice(&[0, 0, 0, 255]);
                continue;
            }
            let sx = ((fx * sw) as i64).clamp(0, src.width as i64 - 1) as u32;
            let i = ((sy * src.width + sx) * 4) as usize;
            px.extend_from_slice(&src.pixels[i..i + 4]);
        }
    }
    Bgra { width: ow, height: oh, pixels: px }
}

/// A heavily blurred, tiny version of a whole image, stretched behind the
/// app as an ambient backdrop so the glass panels pick up the mood of what
/// is selected.
pub fn ambient(b: &Bgra) -> Bgra {
    let small = crate::thumb::fit(b.clone(), 24).unwrap_or_else(|_| b.clone());
    let mut px = small.pixels;
    for _ in 0..3 {
        blur_axis(&mut px, small.width, small.height, true);
        blur_axis(&mut px, small.width, small.height, false);
    }
    Bgra { width: small.width, height: small.height, pixels: px }
}

fn blur_axis(px: &mut [u8], w: u32, h: u32, horizontal: bool) {
    let src = px.to_vec();
    let (w, h) = (w as i32, h as i32);
    for y in 0..h {
        for x in 0..w {
            let mut acc = [0u32; 3];
            let mut n = 0;
            for d in -RADIUS..=RADIUS {
                let (sx, sy) = if horizontal { ((x + d).clamp(0, w - 1), y) } else { (x, (y + d).clamp(0, h - 1)) };
                let i = ((sy * w + sx) * 4) as usize;
                for c in 0..3 {
                    acc[c] += src[i + c] as u32;
                }
                n += 1;
            }
            let o = ((y * w + x) * 4) as usize;
            for c in 0..3 {
                px[o + c] = (acc[c] / n) as u8;
            }
        }
    }
}

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

    #[test]
    fn strip_is_small_and_averages_colors() {
        let (w, h) = (640u32, 360u32);
        let mut pixels = vec![0u8; (w * h * 4) as usize];
        for p in pixels.as_chunks_mut::<4>().0 {
            p.copy_from_slice(&[10, 20, 30, 255]);
        }
        let s = strip(&Bgra { width: w, height: h, pixels });
        assert_eq!(s.width, 80);
        assert!(s.height >= 10 && s.height <= 12);
        assert_eq!(&s.pixels[..4], &[10, 20, 30, 255]);
    }

    #[test]
    fn crop_clamps_outside_the_strip() {
        // 4x1 strip: black, black, white, white.
        let src = Bgra { width: 4, height: 1, pixels: [[0u8; 4], [0; 4], [255; 4], [255; 4]].concat() };
        let c = crop(&src, [-0.5, -1.0, 1.5, 2.0]);
        assert!(c.width >= 4 && c.height >= 1);
        let at = |x: usize| c.pixels[x * 4];
        // Outside the media on both sides: black letterbox.
        assert_eq!(at(0), 0);
        assert_eq!(at(c.width as usize - 1), 0);
        // Inside: the strip's own colors, white on the right half.
        assert_eq!(at(c.width as usize * 5 / 8), 255);
    }

    #[test]
    fn tiny_frames_do_not_panic() {
        let s = strip(&Bgra { width: 1, height: 1, pixels: vec![1, 2, 3, 255] });
        assert_eq!((s.width, s.height), (1, 1));
    }
}