1use std::io::Cursor;
9
10pub const FRAME: u8 = 1;
12const JPEG_QUALITY: u8 = 70;
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub struct Rect {
18 pub x: u16,
19 pub y: u16,
20 pub w: u16,
21 pub h: u16,
22}
23
24impl Rect {
25 pub fn whole(w: u16, h: u16) -> Self {
27 Self { x: 0, y: 0, w, h }
28 }
29
30 pub fn clipped(x: i16, y: i16, w: u16, h: u16, screen_w: u16, screen_h: u16) -> Option<Self> {
32 let (x0, y0) = (i32::from(x).max(0), i32::from(y).max(0));
33 let (x1, y1) = ((i32::from(x) + i32::from(w)).min(i32::from(screen_w)), (i32::from(y) + i32::from(h)).min(i32::from(screen_h)));
34 if x1 <= x0 || y1 <= y0 {
35 return None;
36 }
37 Some(Self { x: x0 as u16, y: y0 as u16, w: (x1 - x0) as u16, h: (y1 - y0) as u16 })
38 }
39
40 pub fn union(self, other: Self) -> Self {
42 let (x0, y0) = (self.x.min(other.x), self.y.min(other.y));
43 let (x1, y1) = ((self.x + self.w).max(other.x + other.w), (self.y + self.h).max(other.y + other.h));
44 Self { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }
45 }
46}
47
48pub struct Picture {
51 w: usize,
52 h: usize,
53 px: Vec<u8>,
54}
55
56impl Picture {
57 pub fn new(w: u16, h: u16) -> Self {
58 Self { w: usize::from(w), h: usize::from(h), px: vec![0; usize::from(w) * usize::from(h) * 4] }
59 }
60
61 pub fn pixels(&self) -> &[u8] {
63 &self.px
64 }
65
66 pub fn update(&mut self, at: Rect, part: &[u8]) -> bool {
69 let (x, y, w, h) = (usize::from(at.x), usize::from(at.y), usize::from(at.w), usize::from(at.h));
70 if x + w > self.w || y + h > self.h || part.len() < w * h * 4 {
71 return false;
72 }
73 let mut changed = false;
74 for row in 0..h {
75 let (from, to) = (row * w * 4, ((y + row) * self.w + x) * 4);
76 let (new, old) = (&part[from..from + w * 4], &mut self.px[to..to + w * 4]);
77 if new != old {
78 old.copy_from_slice(new);
79 changed = true;
80 }
81 }
82 changed
83 }
84}
85
86pub fn frame_message(bgrx: &[u8], w: u32, h: u32) -> Result<Vec<u8>, String> {
89 let pixels = (w as usize) * (h as usize);
90 if bgrx.len() < pixels * 4 {
91 return Err(format!("the screen came back with {} bytes, not {}", bgrx.len(), pixels * 4));
92 }
93 let mut rgb = Vec::with_capacity(pixels * 3);
94 for p in bgrx[..pixels * 4].chunks_exact(4) {
95 rgb.extend_from_slice(&[p[2], p[1], p[0]]);
96 }
97 let mut out = Cursor::new(vec![FRAME]);
98 out.set_position(1);
99 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, JPEG_QUALITY)
100 .encode(&rgb, w, h, image::ExtendedColorType::Rgb8)
101 .map_err(|e| format!("a frame could not be made: {e}"))?;
102 Ok(out.into_inner())
103}
104
105#[cfg(test)]
106mod tests {
107 use super::*;
108
109 fn screen(w: u32, h: u32, bgrx: [u8; 4]) -> Vec<u8> {
110 bgrx.iter().copied().cycle().take((w * h * 4) as usize).collect()
111 }
112
113 #[test]
114 fn a_part_that_is_the_same_is_no_change_and_one_that_differs_is_written_in() {
115 let mut p = Picture::new(4, 4);
116 let all = Rect::whole(4, 4);
117 assert!(p.update(all, &screen(4, 4, [0, 0, 255, 0])), "the first read of a coloured screen is a change from the blank picture");
118 assert!(!p.update(all, &screen(4, 4, [0, 0, 255, 0])), "the same screen is not a change");
119 let part = Rect { x: 1, y: 2, w: 2, h: 1 };
120 assert!(p.update(part, &screen(2, 1, [0, 255, 0, 0])));
121 assert!(!p.update(part, &screen(2, 1, [0, 255, 0, 0])));
122 let px = p.pixels();
123 let at = |x: usize, y: usize| &px[(y * 4 + x) * 4..(y * 4 + x) * 4 + 3];
124 assert_eq!(at(1, 2), [0, 255, 0], "the part is written where it was read");
125 assert_eq!(at(2, 2), [0, 255, 0]);
126 assert_eq!(at(0, 2), [0, 0, 255], "what is around it is untouched");
127 assert_eq!(at(3, 2), [0, 0, 255]);
128 assert_eq!(at(1, 1), [0, 0, 255]);
129 }
130
131 #[test]
132 fn a_part_that_does_not_fit_or_came_back_short_is_ignored() {
133 let mut p = Picture::new(4, 4);
134 assert!(!p.update(Rect { x: 3, y: 3, w: 2, h: 2 }, &screen(2, 2, [1, 2, 3, 0])), "off the screen");
135 assert!(!p.update(Rect::whole(4, 4), &[1, 2, 3]), "short");
136 assert!(p.pixels().iter().all(|b| *b == 0));
137 }
138
139 #[test]
140 fn damage_is_cut_to_the_screen_and_joined_into_one_rectangle() {
141 assert_eq!(Rect::clipped(-5, -5, 10, 10, 100, 80), Some(Rect { x: 0, y: 0, w: 5, h: 5 }));
142 assert_eq!(Rect::clipped(90, 70, 50, 50, 100, 80), Some(Rect { x: 90, y: 70, w: 10, h: 10 }));
143 assert_eq!(Rect::clipped(100, 0, 10, 10, 100, 80), None, "right of the screen");
144 assert_eq!(Rect::clipped(0, 0, 0, 10, 100, 80), None, "empty");
145 let a = Rect { x: 10, y: 10, w: 5, h: 5 };
146 let b = Rect { x: 30, y: 2, w: 4, h: 4 };
147 assert_eq!(a.union(b), Rect { x: 10, y: 2, w: 24, h: 13 });
148 assert_eq!(a.union(a), a);
149 }
150
151 #[test]
152 fn a_frame_is_the_kind_byte_and_a_jpeg_of_the_right_colour_and_size() {
153 let m = frame_message(&screen(16, 8, [0, 0, 255, 0]), 16, 8).unwrap();
155 assert_eq!(m[0], FRAME);
156 let img = image::load_from_memory_with_format(&m[1..], image::ImageFormat::Jpeg).unwrap().to_rgb8();
157 assert_eq!((img.width(), img.height()), (16, 8));
158 let p = img.get_pixel(8, 4);
159 assert!(p[0] > 200 && p[1] < 60 && p[2] < 60, "{p:?} is not red");
160 }
161
162 #[test]
163 fn a_short_screen_is_refused_in_words() {
164 let e = frame_message(&[0; 10], 4, 4).unwrap_err();
165 assert!(e.contains("not 64"), "{e}");
166 }
167}