crates/format/image/src/pixel.rs 4.4 KiB 137 lines Raw
1 //! One image, the three formats that the engine carries, and a rectangle of2 //! it.3 //!4 //! A frame keeps its bytes in one buffer, in rows with no padding. A tile is a5 //! view of a rectangle, copied into its own frame so that a plugin can send it6 //! without the rest of the image.7 8 use crate::ImageError;9 10 /// The pixel layouts that a plugin may return.11 ///12 /// Three formats cover the engine: colour, colour with alpha, and grey. A13 /// fourth would need a converter, which this crate does not have.14 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]15 pub enum Format {16     /// Three bytes per pixel.17     Rgb8,18     /// Four bytes per pixel.19     Rgba8,20     /// One byte per pixel.21     Gray8,22 }23 24 impl Format {25     /// Bytes per pixel. The length of `pixels` is a multiple of this.26     pub const fn channels(self) -> u8 {27         match self {28             Format::Rgb8 => 3,29             Format::Rgba8 => 4,30             Format::Gray8 => 1,31         }32     }33 34     /// Bits per pixel, which is what the png header carries.35     pub const fn bits(self) -> u8 {36         self.channels() * 837     }38 }39 40 /// One image: a format, a width, a height, and the bytes of the pixels.41 ///42 /// Rows are packed with no padding, so `stride` is `width * channels`.43 pub struct Frame {44     pub format: Format,45     pub width: u32,46     pub height: u32,47     pub pixels: Vec<u8>,48 }49 50 impl Frame {51     /// A frame whose bytes match its size.52     ///53     /// The length check catches a caller that computed a buffer for one size54     /// and then changed the header.55     pub fn new(56         format: Format,57         width: u32,58         height: u32,59         pixels: Vec<u8>,60     ) -> Result<Frame, ImageError> {61         if width == 0 || height == 0 {62             return Err(ImageError::Empty);63         }64         let want = expected_len(format, width, height).ok_or(ImageError::Size)?;65         if pixels.len() != want {66             return Err(ImageError::Size);67         }68         Ok(Frame {69             format,70             width,71             height,72             pixels,73         })74     }75 76     /// Bytes in one row. A tile copies rows with this step.77     pub fn stride(&self) -> usize {78         // A u32 width times at most four channels fits usize on a 64-bit79         // target. The cast is the same on a 32-bit target only for widths that80         // fit the buffer, which `new` already checked.81         self.width as usize * usize::from(self.format.channels())82     }83 84     /// The bytes of one pixel, or `None` when the point is outside the frame.85     pub fn pixel(&self, x: u32, y: u32) -> Option<&[u8]> {86         if x >= self.width || y >= self.height {87             return None;88         }89         let channels = usize::from(self.format.channels());90         let offset = (y as usize)91             .checked_mul(self.stride())?92             .checked_add((x as usize).checked_mul(channels)?)?;93         self.pixels.get(offset..offset.checked_add(channels)?)94     }95 96     /// The rectangle `tile` as a frame of its own.97     ///98     /// A tile that leaves the frame is `None`. A caller that sends a part of99     /// an image must not receive invented bytes.100     pub fn tile(&self, tile: Tile) -> Option<Frame> {101         let right = tile.x.checked_add(tile.w)?;102         let bottom = tile.y.checked_add(tile.h)?;103         if tile.w == 0 || tile.h == 0 || right > self.width || bottom > self.height {104             return None;105         }106         let channels = usize::from(self.format.channels());107         let row_bytes = (tile.w as usize).checked_mul(channels)?;108         let stride = self.stride();109         let mut pixels = Vec::with_capacity(row_bytes.checked_mul(tile.h as usize)?);110         for row in 0..tile.h {111             let start = ((tile.y + row) as usize)112                 .checked_mul(stride)?113                 .checked_add((tile.x as usize).checked_mul(channels)?)?;114             let end = start.checked_add(row_bytes)?;115             pixels.extend_from_slice(self.pixels.get(start..end)?);116         }117         Frame::new(self.format, tile.w, tile.h, pixels).ok()118     }119 }120 121 /// A rectangle of a frame. Half-open: `x..x+w`, `y..y+h`.122 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]123 pub struct Tile {124     pub x: u32,125     pub y: u32,126     pub w: u32,127     pub h: u32,128 }129 130 /// The byte length of a frame, or `None` when the product overflows.131 pub(crate) fn expected_len(format: Format, width: u32, height: u32) -> Option<usize> {132     let channels = usize::from(format.channels());133     usize::try_from(width)134         .ok()?135         .checked_mul(usize::try_from(height).ok()?)?136         .checked_mul(channels)137 }