garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /media/src/picture.rs

raw

//! Pictures shown on a screen: whether a file is one (by its first bytes,
//! never its name), decoded by Wil (`jeroen/wil`: PNG, JPEG, GIF, WebP),
//! and fitted into the box it is shown in as the window's pixels.

use alloc::vec::Vec;

pub use wil_core::{Error, Format};
use wil_core::{Image, Limits};

/// The largest picture file opened, in bytes: a phone camera's photo is a
/// fraction of it.
pub const FILE_MAX: u64 = 64 << 20;

/// The most pixels a picture may have: 50 megapixels, 200 MB decoded. A
/// file that claims more is refused before anything is allocated for it.
const PIXELS_MAX: usize = 50_000_000;

/// The format of a picture whose file starts with `head`, if it is one
/// Pinnacle shows.
pub fn sniff(head: &[u8]) -> Option<Format> {
    Format::sniff(head)
}

/// A decoded picture, and the last fitting of it drawn.
pub struct Picture {
    image: Image,
    fitted: Option<Fitted>,
}

/// A picture fitted into a box: where in the box (centred), its size, and
/// its pixels as 0x00RRGGBB, transparency blended over the background.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Fitted {
    /// The box it was fitted into, and the background blended over.
    room: (u32, u32, u32),
    pub x: u32,
    pub y: u32,
    pub width: u32,
    pub height: u32,
    pub pixels: Vec<u32>,
}

impl Picture {
    /// The picture in `data`, a whole file.
    pub fn decode(data: &[u8]) -> Result<Picture, Error> {
        let limits = Limits {
            max_pixels: PIXELS_MAX,
            ..Limits::default()
        };
        Ok(Picture {
            image: wil_core::image::decode_with(data, &limits)?,
            fitted: None,
        })
    }

    pub fn width(&self) -> u32 {
        self.image.width
    }

    pub fn height(&self) -> u32 {
        self.image.height
    }

    /// The picture as large as fits in `width` × `height` with its shape
    /// kept, never larger than it is, centred; kept until the box or the
    /// background changes.
    pub fn fit(&mut self, width: u32, height: u32, background: u32) -> &Fitted {
        let room = (width, height, background);
        if self.fitted.as_ref().is_none_or(|f| f.room != room) {
            let image = self.image.fit(width.max(1), height.max(1));
            self.fitted = Some(Fitted {
                room,
                x: width.saturating_sub(image.width) / 2,
                y: height.saturating_sub(image.height) / 2,
                width: image.width,
                height: image.height,
                pixels: over(&image, background),
            });
        }
        self.fitted.as_ref().expect("fitted above")
    }
}

/// `image`'s pixels as 0x00RRGGBB, each blended by its alpha over
/// `background`.
fn over(image: &Image, background: u32) -> Vec<u32> {
    let mix = |c: u8, b: u32, a: u32| (u32::from(c) * a + b * (255 - a) + 127) / 255;
    let (br, bg, bb) = (background >> 16 & 0xff, background >> 8 & 0xff, background & 0xff);
    image
        .pixels
        .as_chunks::<4>()
        .0
        .iter()
        .map(|p| {
            let a = u32::from(p[3]);
            mix(p[0], br, a) << 16 | mix(p[1], bg, a) << 8 | mix(p[2], bb, a)
        })
        .collect()
}