1use serde::{Deserialize, Deserializer, Serialize};
2
3use crate::{ErrorCode, PixelDimensions, Result, VisionError};
4
5#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, schemars::JsonSchema)]
7pub struct PixelRect {
8 x: u32,
9 y: u32,
10 width: u32,
11 height: u32,
12}
13
14impl PixelRect {
15 pub fn new(x: u32, y: u32, width: u32, height: u32) -> Result<Self> {
16 if width == 0 || height == 0 {
17 return Err(VisionError::new(
18 ErrorCode::InvalidRegion,
19 "pixel rectangle dimensions must be non-zero",
20 ));
21 }
22 let rect = Self {
23 x,
24 y,
25 width,
26 height,
27 };
28 rect.right_exclusive()?;
29 rect.bottom_exclusive()?;
30 Ok(rect)
31 }
32
33 pub const fn x(self) -> u32 {
34 self.x
35 }
36
37 pub const fn y(self) -> u32 {
38 self.y
39 }
40
41 pub const fn width(self) -> u32 {
42 self.width
43 }
44
45 pub const fn height(self) -> u32 {
46 self.height
47 }
48
49 pub fn right_exclusive(self) -> Result<u32> {
50 self.x.checked_add(self.width).ok_or_else(|| {
51 VisionError::new(
52 ErrorCode::InvalidRegion,
53 "pixel rectangle exceeds the coordinate space",
54 )
55 })
56 }
57
58 pub fn bottom_exclusive(self) -> Result<u32> {
59 self.y.checked_add(self.height).ok_or_else(|| {
60 VisionError::new(
61 ErrorCode::InvalidRegion,
62 "pixel rectangle exceeds the coordinate space",
63 )
64 })
65 }
66
67 pub fn fits_within(self, dimensions: PixelDimensions) -> bool {
68 self.right_exclusive()
69 .is_ok_and(|right| right <= dimensions.width())
70 && self
71 .bottom_exclusive()
72 .is_ok_and(|bottom| bottom <= dimensions.height())
73 }
74}
75
76impl<'de> Deserialize<'de> for PixelRect {
77 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
78 where
79 D: Deserializer<'de>,
80 {
81 #[derive(Deserialize)]
82 #[serde(deny_unknown_fields)]
83 struct Wire {
84 x: u32,
85 y: u32,
86 width: u32,
87 height: u32,
88 }
89 let wire = Wire::deserialize(deserializer)?;
90 Self::new(wire.x, wire.y, wire.width, wire.height).map_err(serde::de::Error::custom)
91 }
92}
93
94#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, schemars::JsonSchema)]
96pub struct FrameRegion {
97 rect: PixelRect,
98}
99
100impl FrameRegion {
101 pub fn new(rect: PixelRect, frame_dimensions: PixelDimensions) -> Result<Self> {
102 if !rect.fits_within(frame_dimensions) {
103 return Err(VisionError::new(
104 ErrorCode::InvalidRegion,
105 "frame region lies outside the source-frame dimensions",
106 ));
107 }
108 Ok(Self { rect })
109 }
110
111 pub const fn rect(self) -> PixelRect {
112 self.rect
113 }
114}
115
116impl<'de> Deserialize<'de> for FrameRegion {
117 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
118 where
119 D: Deserializer<'de>,
120 {
121 #[derive(Deserialize)]
122 #[serde(deny_unknown_fields)]
123 struct Wire {
124 rect: PixelRect,
125 }
126 let wire = Wire::deserialize(deserializer)?;
127 Ok(Self { rect: wire.rect })
130 }
131}
132
133#[derive(Clone, Debug, Eq, PartialEq, Serialize, schemars::JsonSchema)]
135pub struct BinaryMask {
136 dimensions: PixelDimensions,
137 bits: Box<[u8]>,
138}
139
140impl BinaryMask {
141 pub fn new(dimensions: PixelDimensions, bits: impl Into<Box<[u8]>>) -> Result<Self> {
142 let bits = bits.into();
143 let pixel_count = dimensions.pixel_count()?;
144 let expected_len = pixel_count.checked_add(7).ok_or_else(|| {
145 VisionError::new(ErrorCode::InvalidMask, "mask dimensions are too large")
146 })? / 8;
147 if bits.len() != expected_len {
148 return Err(VisionError::new(
149 ErrorCode::InvalidMask,
150 "mask byte length does not match its dimensions",
151 ));
152 }
153 let padding = expected_len * 8 - pixel_count;
154 if padding > 0 {
155 let padding_mask = (1_u8 << padding) - 1;
156 if bits.last().is_some_and(|byte| byte & padding_mask != 0) {
157 return Err(VisionError::new(
158 ErrorCode::InvalidMask,
159 "unused trailing mask bits must be zero",
160 ));
161 }
162 }
163 Ok(Self { dimensions, bits })
164 }
165
166 pub const fn dimensions(&self) -> PixelDimensions {
167 self.dimensions
168 }
169
170 pub fn bits(&self) -> &[u8] {
171 &self.bits
172 }
173
174 pub(crate) fn row_bits(&self, y: u32) -> Option<(&[u8], u8)> {
175 if y >= self.dimensions.height() {
176 return None;
177 }
178 let width = usize::try_from(self.dimensions.width()).ok()?;
179 let start_bit = usize::try_from(y).ok()?.checked_mul(width)?;
180 let start_byte = start_bit / 8;
181 let bit_offset = u8::try_from(start_bit % 8).ok()?;
182 let byte_count = (usize::from(bit_offset) + width).checked_add(7)? / 8;
183 Some((&self.bits[start_byte..start_byte + byte_count], bit_offset))
184 }
185
186 pub fn includes(&self, x: u32, y: u32) -> Option<bool> {
187 if x >= self.dimensions.width() || y >= self.dimensions.height() {
188 return None;
189 }
190 let index = usize::try_from(y).ok()? * usize::try_from(self.dimensions.width()).ok()?
191 + usize::try_from(x).ok()?;
192 let byte = self.bits[index / 8];
193 Some(byte & (0x80 >> (index % 8)) != 0)
194 }
195
196 pub fn bounds(&self) -> Result<Option<PixelRect>> {
201 let mut left = self.dimensions.width();
202 let mut top = self.dimensions.height();
203 let mut right = 0_u32;
204 let mut bottom = 0_u32;
205 let mut selected = false;
206 for y in 0..self.dimensions.height() {
207 for x in 0..self.dimensions.width() {
208 if self.includes(x, y) == Some(true) {
209 selected = true;
210 left = left.min(x);
211 top = top.min(y);
212 right = right.max(x.checked_add(1).ok_or_else(|| {
213 VisionError::new(ErrorCode::InvalidMask, "mask bounds overflow")
214 })?);
215 bottom = bottom.max(y.checked_add(1).ok_or_else(|| {
216 VisionError::new(ErrorCode::InvalidMask, "mask bounds overflow")
217 })?);
218 }
219 }
220 }
221 if !selected {
222 return Ok(None);
223 }
224 Ok(Some(PixelRect::new(left, top, right - left, bottom - top)?))
225 }
226}
227
228impl<'de> Deserialize<'de> for BinaryMask {
229 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
230 where
231 D: Deserializer<'de>,
232 {
233 #[derive(Deserialize)]
234 #[serde(deny_unknown_fields)]
235 struct Wire {
236 dimensions: PixelDimensions,
237 bits: Box<[u8]>,
238 }
239 let wire = Wire::deserialize(deserializer)?;
240 Self::new(wire.dimensions, wire.bits).map_err(serde::de::Error::custom)
241 }
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 #[test]
249 fn validates_checked_geometry_and_mask_padding() {
250 let dimensions = PixelDimensions::new(3, 3).unwrap();
251 assert!(PixelRect::new(u32::MAX, 0, 1, 1).is_err());
252 assert!(FrameRegion::new(PixelRect::new(2, 2, 2, 1).unwrap(), dimensions).is_err());
253 assert_eq!(
254 BinaryMask::new(dimensions, [0xff, 0x01]).unwrap_err().code,
255 ErrorCode::InvalidMask
256 );
257 let mask = BinaryMask::new(dimensions, [0x80, 0x00]).unwrap();
258 assert_eq!(mask.includes(0, 0), Some(true));
259 assert_eq!(mask.includes(1, 0), Some(false));
260 assert_eq!(mask.includes(3, 0), None);
261 assert_eq!(
262 mask.bounds().unwrap(),
263 Some(PixelRect::new(0, 0, 1, 1).unwrap())
264 );
265 assert_eq!(
266 BinaryMask::new(dimensions, [0x00, 0x00])
267 .unwrap()
268 .bounds()
269 .unwrap(),
270 None
271 );
272 }
273}