diff --git a/crates/capri-perception/src/imaging.rs b/crates/capri-perception/src/imaging.rs new file mode 100644 index 0000000..9e9ef31 --- /dev/null +++ b/crates/capri-perception/src/imaging.rs @@ -0,0 +1,237 @@ +//! Frames, PNG bounds, 64x36 change signatures and the all-monitor mosaic. +use anyhow::{bail, ensure, Result}; +use image::{imageops, ImageEncoder, Rgb, RgbImage}; + +/// Desktop rectangle in compositor (logical) pixels. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct Rect { + pub x: i32, + pub y: i32, + pub width: u32, + pub height: u32, +} + +impl Rect { + pub fn contains(&self, x: i32, y: i32) -> bool { + x >= self.x && y >= self.y && x < self.x + self.width as i32 && y < self.y + self.height as i32 + } +} + +pub const SAMPLE_W: u32 = 64; +pub const SAMPLE_H: u32 = 36; +pub type Signature = Vec; + +/// Scales down (never up) to fit `max_w` x `max_h`, like Capri's `min(1, 1280/w, 720/h)` with rounding. +pub fn fit(image: &RgbImage, max_w: u32, max_h: u32) -> RgbImage { + let (w, h) = image.dimensions(); + let factor = (max_w as f64 / w as f64).min(max_h as f64 / h as f64).min(1.0); + if factor >= 1.0 { + return image.clone(); + } + let nw = ((w as f64 * factor).round() as u32).max(1); + let nh = ((h as f64 * factor).round() as u32).max(1); + imageops::resize(image, nw, nh, imageops::FilterType::Triangle) +} + +pub fn encode_png(image: &RgbImage) -> Result> { + let mut out = Vec::new(); + image::codecs::png::PngEncoder::new(&mut out).write_image(image.as_raw(), image.width(), image.height(), image::ExtendedColorType::Rgb8)?; + Ok(out) +} + +/// PNG signature + IHDR bounds check before any decode (`snapshotBytes` / `screenshotDimensions`). +pub fn png_dimensions(png: &[u8], max_bytes: usize, max_w: u32, max_h: u32) -> Result<(u32, u32)> { + ensure!(png.len() >= 33 && png.len() <= max_bytes, "Invalid snapshot image"); + ensure!(png.starts_with(&[137, 80, 78, 71, 13, 10, 26, 10]) && &png[12..16] == b"IHDR", "Snapshot must be PNG"); + let w = u32::from_be_bytes(png[16..20].try_into().unwrap()); + let h = u32::from_be_bytes(png[20..24].try_into().unwrap()); + ensure!(w >= 1 && h >= 1 && w <= max_w && h <= max_h && (w as u64 * h as u64) <= 40_000_000, "Snapshot dimensions exceed limits"); + Ok((w, h)) +} + +/// Snapshot/observation frames: 33 B..3 MiB, at most 1280x720, and decodable. +pub fn valid_snapshot(png: &[u8]) -> Result<()> { + png_dimensions(png, 3 << 20, 1280, 720)?; + image::load_from_memory_with_format(png, image::ImageFormat::Png).map_err(|_| anyhow::anyhow!("Snapshot could not be decoded"))?; + Ok(()) +} + +/// 64x36 luminance sample, `round(0.299 R + 0.587 G + 0.114 B)`. +pub fn signature(image: &RgbImage) -> Signature { + let small = imageops::resize(image, SAMPLE_W, SAMPLE_H, imageops::FilterType::Triangle); + small.pixels().map(|p| (0.299 * p[0] as f64 + 0.587 * p[1] as f64 + 0.114 * p[2] as f64).round() as u8).collect() +} + +/// Mean absolute difference >= 3.5 % (no previous sample = changed). +pub fn changed(previous: Option<&[u8]>, current: &[u8]) -> bool { + let Some(previous) = previous else { return true }; + if previous.len() != current.len() { + return true; + } + let diff: u64 = previous.iter().zip(current).map(|(a, b)| a.abs_diff(*b) as u64).sum(); + diff as f64 / (current.len() as f64 * 255.0) >= 0.035 +} + +/// Pixel layouts KWin ScreenShot2 returns (QImage::Format numbers). +pub fn decode_raw(format: u32, width: u32, height: u32, stride: u32, data: &[u8]) -> Result { + ensure!(width > 0 && height > 0 && width <= 16384 && height <= 16384, "Capture geometry exceeds limits"); + ensure!(stride >= width * 4 && data.len() as u64 >= stride as u64 * height as u64, "Capture buffer is incomplete"); + let bgra = match format { + 4..=6 => true, // (A)RGB32 little-endian: B,G,R,A + 16..=18 => false, // RGBX/RGBA8888: R,G,B,A + _ => bail!("Unsupported capture pixel format"), + }; + let premultiplied = format == 6 || format == 18; + let mut out = RgbImage::new(width, height); + for y in 0..height { + let row = &data[(y * stride) as usize..]; + for x in 0..width { + let p = &row[(x * 4) as usize..(x * 4 + 4) as usize]; + let (r, g, b) = if bgra { (p[2], p[1], p[0]) } else { (p[0], p[1], p[2]) }; + let a = p[3]; + let un = |c: u8| if premultiplied && a > 0 && a < 255 { ((c as u32 * 255) / a as u32).min(255) as u8 } else { c }; + out.put_pixel(x, y, Rgb([un(r), un(g), un(b)])); + } + } + Ok(out) +} + +/// X11 ZPixmap, 32 bits per pixel, little-endian BGRX. +pub fn decode_bgrx(width: u32, height: u32, data: &[u8]) -> Result { + decode_raw(4, width, height, width * 4, data) +} + +const GUTTER: u32 = 8; +const CAPTION: u32 = 28; + +/// Grid geometry of the mosaic: (columns, rows, cell width, max image height). +pub fn mosaic_layout(n: usize) -> (u32, u32, u32, u32) { + let columns = (n as f64).sqrt().ceil() as u32; + let rows = (n as u32).div_ceil(columns); + let cell = (1280 - GUTTER * (columns + 1)) / columns; + let max_h = (720 - GUTTER * (rows + 1)) / rows - CAPTION; + (columns, rows, cell, max_h) +} + +/// All-monitor mosaic: tiles in layout order with `Monitor N` captions, width 1280, height <= 720. +pub fn mosaic(tiles: &[RgbImage]) -> Result { + ensure!((2..=8).contains(&tiles.len()), "Monitor capture is unavailable"); + let (columns, _, cell, max_h) = mosaic_layout(tiles.len()); + let scaled: Vec = tiles + .iter() + .map(|t| { + let f = (cell as f64 / t.width() as f64).min(max_h as f64 / t.height() as f64).min(1.0); + let (w, h) = (((t.width() as f64 * f).floor() as u32).max(1), ((t.height() as f64 * f).floor() as u32).max(1)); + if (w, h) == t.dimensions() { t.clone() } else { imageops::resize(t, w, h, imageops::FilterType::Triangle) } + }) + .collect(); + let rows: Vec<&[RgbImage]> = scaled.chunks(columns as usize).collect(); + let height = GUTTER + rows.iter().map(|r| r.iter().map(|t| t.height()).max().unwrap_or(0) + CAPTION + GUTTER).sum::(); + let mut canvas = RgbImage::from_pixel(1280, height.min(720), Rgb([0x11, 0x18, 0x27])); + let mut y = GUTTER; + for (r, row) in rows.iter().enumerate() { + let row_h = row.iter().map(|t| t.height()).max().unwrap_or(0); + for (c, tile) in row.iter().enumerate() { + let x = GUTTER + c as u32 * (cell + GUTTER); + imageops::replace(&mut canvas, &RgbImage::from_pixel(cell, CAPTION, Rgb([0x24, 0x32, 0x44])), x as i64, y as i64); + caption(&mut canvas, x + 8, y + (CAPTION - 14) / 2, &format!("Monitor {}", r * columns as usize + c + 1)); + imageops::replace(&mut canvas, tile, (x + (cell - tile.width()) / 2) as i64, (y + CAPTION) as i64); + } + y += row_h + CAPTION + GUTTER; + } + Ok(canvas) +} + +// TODO: 5x7 bitmap glyphs only cover "Monitor N" (layout constants match Capri, not the font); use egui's font if captions get localized. +fn glyph(c: char) -> [u8; 7] { + match c { + 'M' => [0x11, 0x1B, 0x15, 0x15, 0x11, 0x11, 0x11], + 'o' => [0, 0, 0x0E, 0x11, 0x11, 0x11, 0x0E], + 'n' => [0, 0, 0x16, 0x19, 0x11, 0x11, 0x11], + 'i' => [0x04, 0, 0x0C, 0x04, 0x04, 0x04, 0x0E], + 't' => [0x08, 0x08, 0x1C, 0x08, 0x08, 0x09, 0x06], + 'r' => [0, 0, 0x16, 0x19, 0x10, 0x10, 0x10], + '0' => [0x0E, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0E], + '1' => [0x04, 0x0C, 0x04, 0x04, 0x04, 0x04, 0x0E], + '2' => [0x0E, 0x11, 0x01, 0x02, 0x04, 0x08, 0x1F], + '3' => [0x1F, 0x02, 0x04, 0x02, 0x01, 0x11, 0x0E], + '4' => [0x02, 0x06, 0x0A, 0x12, 0x1F, 0x02, 0x02], + '5' => [0x1F, 0x10, 0x1E, 0x01, 0x01, 0x11, 0x0E], + '6' => [0x06, 0x08, 0x10, 0x1E, 0x11, 0x11, 0x0E], + '7' => [0x1F, 0x01, 0x02, 0x04, 0x08, 0x08, 0x08], + '8' => [0x0E, 0x11, 0x11, 0x0E, 0x11, 0x11, 0x0E], + '9' => [0x0E, 0x11, 0x11, 0x0F, 0x01, 0x02, 0x0C], + _ => [0; 7], + } +} + +fn caption(canvas: &mut RgbImage, x: u32, y: u32, text: &str) { + for (i, c) in text.chars().enumerate() { + for (row, bits) in glyph(c).iter().enumerate() { + for col in 0..5u32 { + if bits & (0x10 >> col) != 0 { + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let (px, py) = (x + i as u32 * 12 + col * 2 + dx, y + row as u32 * 2 + dy); + if px < canvas.width() && py < canvas.height() { + canvas.put_pixel(px, py, Rgb([255, 255, 255])); + } + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fit_and_png_bounds() { + let img = RgbImage::from_pixel(2560, 1440, Rgb([10, 20, 30])); + let small = fit(&img, 1280, 720); + assert_eq!(small.dimensions(), (1280, 720)); + let png = encode_png(&small).unwrap(); + valid_snapshot(&png).unwrap(); + assert!(valid_snapshot(&encode_png(&img).unwrap()).is_err()); + assert!(png_dimensions(b"not a png at all, not a png at all", 1 << 20, 10, 10).is_err()); + } + + #[test] + fn change_detection() { + let a = signature(&RgbImage::from_pixel(640, 360, Rgb([100, 100, 100]))); + let mut blink = RgbImage::from_pixel(640, 360, Rgb([100, 100, 100])); + for y in 0..10 { + blink.put_pixel(5, y, Rgb([255, 255, 255])); // a cursor blink + } + assert_eq!(a.len(), 2304); + assert!(!changed(Some(&a), &signature(&blink))); + assert!(changed(Some(&a), &signature(&RgbImage::from_pixel(640, 360, Rgb([200, 200, 200]))))); + assert!(changed(None, &a)); + } + + #[test] + fn raw_formats_with_stride() { + // 2x1, stride 12: BGRA then padding. + let data = [3, 2, 1, 255, 6, 5, 4, 255, 0, 0, 0, 0]; + let img = decode_raw(5, 2, 1, 12, &data).unwrap(); + assert_eq!(img.get_pixel(0, 0), &Rgb([1, 2, 3])); + let img = decode_raw(17, 2, 1, 12, &data).unwrap(); + assert_eq!(img.get_pixel(1, 0), &Rgb([6, 5, 4])); + let pm = decode_raw(18, 1, 1, 4, &[64, 0, 0, 128]).unwrap(); + assert_eq!(pm.get_pixel(0, 0)[0], 127); + assert!(decode_raw(99, 1, 1, 4, &[0; 4]).is_err()); + assert!(decode_raw(4, 2, 2, 8, &[0; 8]).is_err(), "short buffer"); + } + + #[test] + fn mosaic_geometry() { + assert_eq!(mosaic_layout(2), (2, 1, 628, 676)); + assert_eq!(mosaic_layout(5), (3, 2, 416, 320)); + let tiles = vec![RgbImage::new(1280, 800), RgbImage::new(1280, 720), RgbImage::new(800, 600)]; + let m = mosaic(&tiles).unwrap(); + assert_eq!(m.width(), 1280); + assert!(m.height() <= 720); + assert!(mosaic(&tiles[..1]).is_err()); + } +}