Skip to main content

icedwright_types/
frame.rs

1//! [`Frame`], a rendered image: RGBA bytes at physical pixels.
2//!
3//! PNG encoding lives with the snapshot code in `icedwright`, so this crate needs no encoder.
4
5use core::fmt;
6
7use crate::geometry::{Rect, Size};
8use crate::units::{Logical, Physical, ScaleFactor};
9
10/// A rendered image, four bytes per pixel (red, green, blue, alpha), row by row from the top.
11///
12/// The fields are private so the byte length always matches the size.
13#[derive(Clone, PartialEq)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15#[cfg_attr(feature = "serde", serde(try_from = "RawFrame"))]
16pub struct Frame {
17    rgba: Vec<u8>,
18    size: Physical<Size<u32>>,
19    scale: ScaleFactor,
20}
21
22impl Frame {
23    /// A frame from its pixels. Fails unless `rgba` holds exactly `width * height * 4` bytes.
24    pub fn new(
25        rgba: Vec<u8>,
26        size: Physical<Size<u32>>,
27        scale: ScaleFactor,
28    ) -> Result<Frame, FrameError> {
29        let expected = byte_length(size.get());
30        if expected != Some(rgba.len()) {
31            return Err(FrameError::LengthMismatch {
32                size: size.get(),
33                expected,
34                found: rgba.len(),
35            });
36        }
37        Ok(Frame { rgba, size, scale })
38    }
39
40    /// The pixels.
41    #[must_use]
42    pub fn rgba(&self) -> &[u8] {
43        &self.rgba
44    }
45
46    /// The pixels, taking ownership.
47    #[must_use]
48    pub fn into_rgba(self) -> Vec<u8> {
49        self.rgba
50    }
51
52    /// The size in physical pixels.
53    #[must_use]
54    pub fn size(&self) -> Physical<Size<u32>> {
55        self.size
56    }
57
58    /// The size in logical pixels.
59    #[must_use]
60    pub fn logical_size(&self) -> Logical<Size<f32>> {
61        self.size.to_logical(self.scale)
62    }
63
64    /// The scale factor the frame was rendered at.
65    #[must_use]
66    pub fn scale(&self) -> ScaleFactor {
67        self.scale
68    }
69
70    /// The pixel at physical `x`, `y`, or `None` outside the frame.
71    #[must_use]
72    pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
73        let size = self.size.get();
74        if x >= size.width || y >= size.height {
75            return None;
76        }
77        let start = (usize::try_from(y).ok()? * usize::try_from(size.width).ok()?
78            + usize::try_from(x).ok()?)
79            * 4;
80        let bytes = self.rgba.get(start..start + 4)?;
81        bytes.try_into().ok()
82    }
83
84    /// The part of the frame under `region`, given in logical pixels.
85    ///
86    /// Edges are widened to whole physical pixels and the region is clipped to the frame, so
87    /// a partly visible element crops to the part inside it.
88    pub fn crop(&self, region: Logical<Rect>) -> Result<Frame, FrameError> {
89        let rect = region.get();
90        let finite = [rect.x, rect.y, rect.width, rect.height]
91            .iter()
92            .all(|value| value.is_finite());
93        if !finite || rect.width < 0.0 || rect.height < 0.0 {
94            return Err(FrameError::InvalidRegion { region: rect });
95        }
96        let size = self.size.get();
97        let scale = self.scale.get();
98        let clamp = |value: f32, limit: u32| value.clamp(0.0, limit as f32) as u32;
99        let left = clamp((rect.x * scale).floor(), size.width);
100        let top = clamp((rect.y * scale).floor(), size.height);
101        let right = clamp(((rect.x + rect.width) * scale).ceil(), size.width);
102        let bottom = clamp(((rect.y + rect.height) * scale).ceil(), size.height);
103        if right <= left || bottom <= top {
104            return Err(FrameError::EmptyCrop { region: rect });
105        }
106
107        let width = usize::try_from(size.width).map_err(|_| FrameError::TooLarge)?;
108        let (left, top, right, bottom) = (
109            usize::try_from(left).map_err(|_| FrameError::TooLarge)?,
110            usize::try_from(top).map_err(|_| FrameError::TooLarge)?,
111            usize::try_from(right).map_err(|_| FrameError::TooLarge)?,
112            usize::try_from(bottom).map_err(|_| FrameError::TooLarge)?,
113        );
114        let mut rgba = Vec::with_capacity((right - left) * (bottom - top) * 4);
115        for row in top..bottom {
116            let start = (row * width + left) * 4;
117            let end = (row * width + right) * 4;
118            let bytes = self.rgba.get(start..end).ok_or(FrameError::TooLarge)?;
119            rgba.extend_from_slice(bytes);
120        }
121        let cropped = Size::new(
122            u32::try_from(right - left).map_err(|_| FrameError::TooLarge)?,
123            u32::try_from(bottom - top).map_err(|_| FrameError::TooLarge)?,
124        );
125        Frame::new(rgba, Physical::new(cropped), self.scale)
126    }
127}
128
129/// Prints the size and scale rather than every byte.
130impl fmt::Debug for Frame {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        let size = self.size.get();
133        f.debug_struct("Frame")
134            .field("width", &size.width)
135            .field("height", &size.height)
136            .field("scale", &self.scale)
137            .finish_non_exhaustive()
138    }
139}
140
141fn byte_length(size: Size<u32>) -> Option<usize> {
142    usize::try_from(size.width)
143        .ok()?
144        .checked_mul(usize::try_from(size.height).ok()?)?
145        .checked_mul(4)
146}
147
148/// Why a [`Frame`] could not be made or cropped.
149#[derive(Debug, Clone, PartialEq)]
150#[non_exhaustive]
151pub enum FrameError {
152    /// The byte buffer does not match the size.
153    LengthMismatch {
154        /// The size given.
155        size: Size<u32>,
156        /// `width * height * 4`, or `None` if that overflows.
157        expected: Option<usize>,
158        /// The number of bytes given.
159        found: usize,
160    },
161    /// A crop region with a negative or non-finite part.
162    InvalidRegion {
163        /// The region asked for, in logical pixels.
164        region: Rect,
165    },
166    /// A crop region that covers no pixel of the frame.
167    EmptyCrop {
168        /// The region asked for, in logical pixels.
169        region: Rect,
170    },
171    /// The frame is too large to address on this platform.
172    TooLarge,
173}
174
175impl fmt::Display for FrameError {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        match self {
178            FrameError::LengthMismatch {
179                size,
180                expected: Some(expected),
181                found,
182            } => write!(
183                f,
184                "a {}x{} frame needs {expected} bytes of RGBA, but {found} were given",
185                size.width, size.height
186            ),
187            FrameError::LengthMismatch {
188                size,
189                expected: None,
190                ..
191            } => write!(
192                f,
193                "a {}x{} frame is too large to hold in memory",
194                size.width, size.height
195            ),
196            FrameError::InvalidRegion { region } => write!(
197                f,
198                "crop region {region:?} has a negative or non-finite part"
199            ),
200            FrameError::EmptyCrop { region } => {
201                write!(f, "crop region {region:?} covers no pixel of the frame")
202            }
203            FrameError::TooLarge => f.write_str("the frame is too large to address"),
204        }
205    }
206}
207
208impl std::error::Error for FrameError {}
209
210#[cfg(feature = "serde")]
211#[derive(serde::Deserialize)]
212struct RawFrame {
213    rgba: Vec<u8>,
214    size: Physical<Size<u32>>,
215    scale: ScaleFactor,
216}
217
218#[cfg(feature = "serde")]
219impl TryFrom<RawFrame> for Frame {
220    type Error = FrameError;
221
222    fn try_from(raw: RawFrame) -> Result<Self, FrameError> {
223        Frame::new(raw.rgba, raw.size, raw.scale)
224    }
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230    use crate::geometry::Point;
231
232    /// A frame whose every pixel is `[x, y, 0, 255]`.
233    fn gradient(width: u32, height: u32, scale: ScaleFactor) -> Result<Frame, FrameError> {
234        let mut rgba = Vec::new();
235        for y in 0..height {
236            for x in 0..width {
237                rgba.extend_from_slice(&[x as u8, y as u8, 0, 255]);
238            }
239        }
240        Frame::new(rgba, Physical::new(Size::new(width, height)), scale)
241    }
242
243    fn region(x: f32, y: f32, width: f32, height: f32) -> Logical<Rect> {
244        Logical(Rect::new(Point::new(x, y), Size::new(width, height)))
245    }
246
247    #[test]
248    fn new_checks_the_length() {
249        let size = Physical::new(Size::new(2, 2));
250        assert!(Frame::new(vec![0; 16], size, ScaleFactor::ONE).is_ok());
251        let error = Frame::new(vec![0; 15], size, ScaleFactor::ONE).err();
252        assert_eq!(
253            error,
254            Some(FrameError::LengthMismatch {
255                size: Size::new(2, 2),
256                expected: Some(16),
257                found: 15
258            })
259        );
260        assert_eq!(
261            error.map(|e| e.to_string()).as_deref(),
262            Some("a 2x2 frame needs 16 bytes of RGBA, but 15 were given")
263        );
264    }
265
266    #[test]
267    fn accessors() -> Result<(), FrameError> {
268        let frame = gradient(4, 2, ScaleFactor::TWO)?;
269        assert_eq!(frame.size(), Physical::new(Size::new(4, 2)));
270        assert_eq!(frame.logical_size(), Logical(Size::new(2.0, 1.0)));
271        assert_eq!(frame.scale(), ScaleFactor::TWO);
272        assert_eq!(frame.rgba().len(), 32);
273        assert_eq!(frame.pixel(3, 1), Some([3, 1, 0, 255]));
274        assert_eq!(frame.pixel(4, 0), None);
275        assert_eq!(frame.pixel(0, 2), None);
276        assert_eq!(
277            format!("{frame:?}"),
278            "Frame { width: 4, height: 2, scale: ScaleFactor(2.0), .. }"
279        );
280        assert_eq!(frame.into_rgba().len(), 32);
281        Ok(())
282    }
283
284    #[test]
285    fn crop_uses_logical_pixels() -> Result<(), FrameError> {
286        let frame = gradient(8, 8, ScaleFactor::TWO)?;
287        let cropped = frame.crop(region(1.0, 2.0, 1.0, 1.0))?;
288        assert_eq!(cropped.size(), Physical::new(Size::new(2, 2)));
289        assert_eq!(cropped.scale(), ScaleFactor::TWO);
290        assert_eq!(cropped.pixel(0, 0), Some([2, 4, 0, 255]));
291        assert_eq!(cropped.pixel(1, 1), Some([3, 5, 0, 255]));
292        Ok(())
293    }
294
295    #[test]
296    fn crop_widens_to_whole_pixels_and_clips_to_the_frame() -> Result<(), FrameError> {
297        let frame = gradient(4, 4, ScaleFactor::ONE)?;
298        let widened = frame.crop(region(0.5, 0.5, 1.0, 1.0))?;
299        assert_eq!(widened.size(), Physical::new(Size::new(2, 2)));
300        assert_eq!(widened.pixel(0, 0), Some([0, 0, 0, 255]));
301        let clipped = frame.crop(region(-2.0, 3.0, 10.0, 10.0))?;
302        assert_eq!(clipped.size(), Physical::new(Size::new(4, 1)));
303        assert_eq!(clipped.pixel(0, 0), Some([0, 3, 0, 255]));
304        Ok(())
305    }
306
307    #[test]
308    fn crop_refuses_bad_and_empty_regions() -> Result<(), FrameError> {
309        let frame = gradient(4, 4, ScaleFactor::ONE)?;
310        assert!(matches!(
311            frame.crop(region(f32::NAN, 0.0, 1.0, 1.0)),
312            Err(FrameError::InvalidRegion { .. })
313        ));
314        assert!(matches!(
315            frame.crop(region(0.0, 0.0, -1.0, 1.0)),
316            Err(FrameError::InvalidRegion { .. })
317        ));
318        assert!(matches!(
319            frame.crop(region(10.0, 10.0, 1.0, 1.0)),
320            Err(FrameError::EmptyCrop { .. })
321        ));
322        assert!(matches!(
323            frame.crop(region(1.0, 1.0, 0.0, 1.0)),
324            Err(FrameError::EmptyCrop { .. })
325        ));
326        Ok(())
327    }
328
329    #[test]
330    fn error_messages() {
331        let too_big = FrameError::LengthMismatch {
332            size: Size::new(u32::MAX, u32::MAX),
333            expected: None,
334            found: 0,
335        };
336        assert!(too_big.to_string().contains("too large"));
337        assert!(
338            FrameError::EmptyCrop { region: Rect::ZERO }
339                .to_string()
340                .contains("covers no pixel")
341        );
342        assert!(
343            FrameError::InvalidRegion { region: Rect::ZERO }
344                .to_string()
345                .contains("non-finite")
346        );
347        assert_eq!(
348            FrameError::TooLarge.to_string(),
349            "the frame is too large to address"
350        );
351    }
352
353    #[cfg(feature = "serde")]
354    #[test]
355    fn deserialising_checks_the_length() -> Result<(), Box<dyn std::error::Error>> {
356        let frame = gradient(2, 1, ScaleFactor::ONE)?;
357        let json = serde_json::to_string(&frame)?;
358        assert_eq!(serde_json::from_str::<Frame>(&json)?, frame);
359        let bad = r#"{"rgba":[0,0,0],"size":{"width":1,"height":1},"scale":1.0}"#;
360        assert!(serde_json::from_str::<Frame>(bad).is_err());
361        Ok(())
362    }
363}