use core::fmt;
use crate::geometry::{Rect, Size};
use crate::units::{Logical, Physical, ScaleFactor};
#[derive(Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "RawFrame"))]
pub struct Frame {
rgba: Vec<u8>,
size: Physical<Size<u32>>,
scale: ScaleFactor,
}
impl Frame {
pub fn new(
rgba: Vec<u8>,
size: Physical<Size<u32>>,
scale: ScaleFactor,
) -> Result<Frame, FrameError> {
let expected = byte_length(size.get());
if expected != Some(rgba.len()) {
return Err(FrameError::LengthMismatch {
size: size.get(),
expected,
found: rgba.len(),
});
}
Ok(Frame { rgba, size, scale })
}
#[must_use]
pub fn rgba(&self) -> &[u8] {
&self.rgba
}
#[must_use]
pub fn into_rgba(self) -> Vec<u8> {
self.rgba
}
#[must_use]
pub fn size(&self) -> Physical<Size<u32>> {
self.size
}
#[must_use]
pub fn logical_size(&self) -> Logical<Size<f32>> {
self.size.to_logical(self.scale)
}
#[must_use]
pub fn scale(&self) -> ScaleFactor {
self.scale
}
#[must_use]
pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
let size = self.size.get();
if x >= size.width || y >= size.height {
return None;
}
let start = (usize::try_from(y).ok()? * usize::try_from(size.width).ok()?
+ usize::try_from(x).ok()?)
* 4;
let bytes = self.rgba.get(start..start + 4)?;
bytes.try_into().ok()
}
pub fn crop(&self, region: Logical<Rect>) -> Result<Frame, FrameError> {
let rect = region.get();
let finite = [rect.x, rect.y, rect.width, rect.height]
.iter()
.all(|value| value.is_finite());
if !finite || rect.width < 0.0 || rect.height < 0.0 {
return Err(FrameError::InvalidRegion { region: rect });
}
let size = self.size.get();
let scale = self.scale.get();
let clamp = |value: f32, limit: u32| value.clamp(0.0, limit as f32) as u32;
let left = clamp((rect.x * scale).floor(), size.width);
let top = clamp((rect.y * scale).floor(), size.height);
let right = clamp(((rect.x + rect.width) * scale).ceil(), size.width);
let bottom = clamp(((rect.y + rect.height) * scale).ceil(), size.height);
if right <= left || bottom <= top {
return Err(FrameError::EmptyCrop { region: rect });
}
let width = usize::try_from(size.width).map_err(|_| FrameError::TooLarge)?;
let (left, top, right, bottom) = (
usize::try_from(left).map_err(|_| FrameError::TooLarge)?,
usize::try_from(top).map_err(|_| FrameError::TooLarge)?,
usize::try_from(right).map_err(|_| FrameError::TooLarge)?,
usize::try_from(bottom).map_err(|_| FrameError::TooLarge)?,
);
let mut rgba = Vec::with_capacity((right - left) * (bottom - top) * 4);
for row in top..bottom {
let start = (row * width + left) * 4;
let end = (row * width + right) * 4;
let bytes = self.rgba.get(start..end).ok_or(FrameError::TooLarge)?;
rgba.extend_from_slice(bytes);
}
let cropped = Size::new(
u32::try_from(right - left).map_err(|_| FrameError::TooLarge)?,
u32::try_from(bottom - top).map_err(|_| FrameError::TooLarge)?,
);
Frame::new(rgba, Physical::new(cropped), self.scale)
}
}
impl fmt::Debug for Frame {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let size = self.size.get();
f.debug_struct("Frame")
.field("width", &size.width)
.field("height", &size.height)
.field("scale", &self.scale)
.finish_non_exhaustive()
}
}
fn byte_length(size: Size<u32>) -> Option<usize> {
usize::try_from(size.width)
.ok()?
.checked_mul(usize::try_from(size.height).ok()?)?
.checked_mul(4)
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum FrameError {
LengthMismatch {
size: Size<u32>,
expected: Option<usize>,
found: usize,
},
InvalidRegion {
region: Rect,
},
EmptyCrop {
region: Rect,
},
TooLarge,
}
impl fmt::Display for FrameError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FrameError::LengthMismatch {
size,
expected: Some(expected),
found,
} => write!(
f,
"a {}x{} frame needs {expected} bytes of RGBA, but {found} were given",
size.width, size.height
),
FrameError::LengthMismatch {
size,
expected: None,
..
} => write!(
f,
"a {}x{} frame is too large to hold in memory",
size.width, size.height
),
FrameError::InvalidRegion { region } => write!(
f,
"crop region {region:?} has a negative or non-finite part"
),
FrameError::EmptyCrop { region } => {
write!(f, "crop region {region:?} covers no pixel of the frame")
}
FrameError::TooLarge => f.write_str("the frame is too large to address"),
}
}
}
impl std::error::Error for FrameError {}
#[cfg(feature = "serde")]
#[derive(serde::Deserialize)]
struct RawFrame {
rgba: Vec<u8>,
size: Physical<Size<u32>>,
scale: ScaleFactor,
}
#[cfg(feature = "serde")]
impl TryFrom<RawFrame> for Frame {
type Error = FrameError;
fn try_from(raw: RawFrame) -> Result<Self, FrameError> {
Frame::new(raw.rgba, raw.size, raw.scale)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geometry::Point;
fn gradient(width: u32, height: u32, scale: ScaleFactor) -> Result<Frame, FrameError> {
let mut rgba = Vec::new();
for y in 0..height {
for x in 0..width {
rgba.extend_from_slice(&[x as u8, y as u8, 0, 255]);
}
}
Frame::new(rgba, Physical::new(Size::new(width, height)), scale)
}
fn region(x: f32, y: f32, width: f32, height: f32) -> Logical<Rect> {
Logical(Rect::new(Point::new(x, y), Size::new(width, height)))
}
#[test]
fn new_checks_the_length() {
let size = Physical::new(Size::new(2, 2));
assert!(Frame::new(vec![0; 16], size, ScaleFactor::ONE).is_ok());
let error = Frame::new(vec![0; 15], size, ScaleFactor::ONE).err();
assert_eq!(
error,
Some(FrameError::LengthMismatch {
size: Size::new(2, 2),
expected: Some(16),
found: 15
})
);
assert_eq!(
error.map(|e| e.to_string()).as_deref(),
Some("a 2x2 frame needs 16 bytes of RGBA, but 15 were given")
);
}
#[test]
fn accessors() -> Result<(), FrameError> {
let frame = gradient(4, 2, ScaleFactor::TWO)?;
assert_eq!(frame.size(), Physical::new(Size::new(4, 2)));
assert_eq!(frame.logical_size(), Logical(Size::new(2.0, 1.0)));
assert_eq!(frame.scale(), ScaleFactor::TWO);
assert_eq!(frame.rgba().len(), 32);
assert_eq!(frame.pixel(3, 1), Some([3, 1, 0, 255]));
assert_eq!(frame.pixel(4, 0), None);
assert_eq!(frame.pixel(0, 2), None);
assert_eq!(
format!("{frame:?}"),
"Frame { width: 4, height: 2, scale: ScaleFactor(2.0), .. }"
);
assert_eq!(frame.into_rgba().len(), 32);
Ok(())
}
#[test]
fn crop_uses_logical_pixels() -> Result<(), FrameError> {
let frame = gradient(8, 8, ScaleFactor::TWO)?;
let cropped = frame.crop(region(1.0, 2.0, 1.0, 1.0))?;
assert_eq!(cropped.size(), Physical::new(Size::new(2, 2)));
assert_eq!(cropped.scale(), ScaleFactor::TWO);
assert_eq!(cropped.pixel(0, 0), Some([2, 4, 0, 255]));
assert_eq!(cropped.pixel(1, 1), Some([3, 5, 0, 255]));
Ok(())
}
#[test]
fn crop_widens_to_whole_pixels_and_clips_to_the_frame() -> Result<(), FrameError> {
let frame = gradient(4, 4, ScaleFactor::ONE)?;
let widened = frame.crop(region(0.5, 0.5, 1.0, 1.0))?;
assert_eq!(widened.size(), Physical::new(Size::new(2, 2)));
assert_eq!(widened.pixel(0, 0), Some([0, 0, 0, 255]));
let clipped = frame.crop(region(-2.0, 3.0, 10.0, 10.0))?;
assert_eq!(clipped.size(), Physical::new(Size::new(4, 1)));
assert_eq!(clipped.pixel(0, 0), Some([0, 3, 0, 255]));
Ok(())
}
#[test]
fn crop_refuses_bad_and_empty_regions() -> Result<(), FrameError> {
let frame = gradient(4, 4, ScaleFactor::ONE)?;
assert!(matches!(
frame.crop(region(f32::NAN, 0.0, 1.0, 1.0)),
Err(FrameError::InvalidRegion { .. })
));
assert!(matches!(
frame.crop(region(0.0, 0.0, -1.0, 1.0)),
Err(FrameError::InvalidRegion { .. })
));
assert!(matches!(
frame.crop(region(10.0, 10.0, 1.0, 1.0)),
Err(FrameError::EmptyCrop { .. })
));
assert!(matches!(
frame.crop(region(1.0, 1.0, 0.0, 1.0)),
Err(FrameError::EmptyCrop { .. })
));
Ok(())
}
#[test]
fn error_messages() {
let too_big = FrameError::LengthMismatch {
size: Size::new(u32::MAX, u32::MAX),
expected: None,
found: 0,
};
assert!(too_big.to_string().contains("too large"));
assert!(
FrameError::EmptyCrop { region: Rect::ZERO }
.to_string()
.contains("covers no pixel")
);
assert!(
FrameError::InvalidRegion { region: Rect::ZERO }
.to_string()
.contains("non-finite")
);
assert_eq!(
FrameError::TooLarge.to_string(),
"the frame is too large to address"
);
}
#[cfg(feature = "serde")]
#[test]
fn deserialising_checks_the_length() -> Result<(), Box<dyn std::error::Error>> {
let frame = gradient(2, 1, ScaleFactor::ONE)?;
let json = serde_json::to_string(&frame)?;
assert_eq!(serde_json::from_str::<Frame>(&json)?, frame);
let bad = r#"{"rgba":[0,0,0],"size":{"width":1,"height":1},"scale":1.0}"#;
assert!(serde_json::from_str::<Frame>(bad).is_err());
Ok(())
}
}