1use std::io::Cursor;
4use std::sync::Arc;
5
6use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, RgbaImage};
7
8use crate::digest::Digest;
9use crate::error::{Result, VisionError};
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26#[non_exhaustive]
27pub struct DecodeLimits {
28 pub max_bytes: u64,
30 pub max_pixels: u64,
32}
33
34impl Default for DecodeLimits {
35 fn default() -> Self {
36 Self { max_bytes: 50 * 1024 * 1024, max_pixels: 50_000_000 }
37 }
38}
39
40impl DecodeLimits {
41 pub fn with_max_bytes(mut self, max_bytes: u64) -> Self {
43 self.max_bytes = max_bytes;
44 self
45 }
46
47 pub fn with_max_pixels(mut self, max_pixels: u64) -> Self {
49 self.max_pixels = max_pixels;
50 self
51 }
52}
53
54#[derive(Clone, PartialEq, Eq)]
56pub struct DecodedImage {
57 pixels: RgbaImage,
58}
59
60impl std::fmt::Debug for DecodedImage {
61 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62 f.debug_struct("DecodedImage")
63 .field("width", &self.width())
64 .field("height", &self.height())
65 .finish_non_exhaustive()
66 }
67}
68
69impl DecodedImage {
70 pub fn from_rgba(width: u32, height: u32, rgba: Vec<u8>) -> Result<Self> {
87 if width == 0 || height == 0 {
88 return Err(VisionError::InvalidInput(format!(
89 "a {width}x{height} image has no pixels"
90 )));
91 }
92 let expected = width as usize * height as usize * 4;
93 let actual = rgba.len();
94 let pixels = RgbaImage::from_raw(width, height, rgba).ok_or_else(|| {
95 VisionError::InvalidInput(format!(
96 "a {width}x{height} RGBA image needs {expected} bytes, got {actual}"
97 ))
98 })?;
99 Ok(Self { pixels })
100 }
101
102 pub fn filled(width: u32, height: u32, rgba: [u8; 4]) -> Self {
104 Self { pixels: RgbaImage::from_pixel(width.max(1), height.max(1), image::Rgba(rgba)) }
105 }
106
107 pub(crate) fn from_inner(pixels: RgbaImage) -> Self {
108 Self { pixels }
109 }
110
111 pub(crate) fn inner(&self) -> &RgbaImage {
112 &self.pixels
113 }
114
115 pub(crate) fn inner_mut(&mut self) -> &mut RgbaImage {
116 &mut self.pixels
117 }
118
119 pub fn width(&self) -> u32 {
121 self.pixels.width()
122 }
123
124 pub fn height(&self) -> u32 {
126 self.pixels.height()
127 }
128
129 pub fn size(&self) -> (u32, u32) {
131 self.pixels.dimensions()
132 }
133
134 pub fn rgba(&self) -> &[u8] {
136 self.pixels.as_raw()
137 }
138
139 pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
145 self.pixels.get_pixel(x, y).0
146 }
147
148 pub fn encode_png(&self) -> Result<Vec<u8>> {
154 let mut out = Cursor::new(Vec::new());
155 self.pixels
156 .write_to(&mut out, ImageFormat::Png)
157 .map_err(|e| VisionError::Decode(format!("PNG encoding failed: {e}")))?;
158 Ok(out.into_inner())
159 }
160
161 pub fn decode(bytes: &[u8], limits: &DecodeLimits) -> Result<(Self, &'static str)> {
170 let size = bytes.len() as u64;
171 if size > limits.max_bytes {
172 return Err(VisionError::TooManyBytes { limit: limits.max_bytes, actual: size });
173 }
174 let reader = || {
175 ImageReader::new(Cursor::new(bytes))
176 .with_guessed_format()
177 .map_err(|e| VisionError::Decode(e.to_string()))
178 };
179 let format = reader()?.format();
180 let mime = match format {
181 Some(ImageFormat::Png) => "image/png",
182 Some(ImageFormat::Jpeg) => "image/jpeg",
183 Some(ImageFormat::WebP) => "image/webp",
184 Some(ImageFormat::Gif) => "image/gif",
185 other => {
186 let detected = other.map_or_else(|| "unknown".to_string(), |f| format!("{f:?}"));
187 return Err(VisionError::UnsupportedFormat { detected });
188 }
189 };
190 let (width, height) =
191 reader()?.into_dimensions().map_err(|e| VisionError::Decode(e.to_string()))?;
192 let pixels = u64::from(width) * u64::from(height);
193 if pixels > limits.max_pixels {
194 return Err(VisionError::TooManyPixels { limit: limits.max_pixels, actual: pixels });
195 }
196 if pixels == 0 {
197 return Err(VisionError::Decode("the image declares no pixels".into()));
198 }
199 let mut reader = reader()?;
200 let mut caps = image::Limits::default();
201 caps.max_image_width = Some(width);
202 caps.max_image_height = Some(height);
203 caps.max_alloc = Some(pixels.saturating_mul(8).saturating_add(1 << 20));
204 reader.limits(caps);
205 let mut decoder = reader.into_decoder().map_err(|e| VisionError::Decode(e.to_string()))?;
206 let orientation =
207 decoder.orientation().unwrap_or(image::metadata::Orientation::NoTransforms);
208 let mut decoded =
209 DynamicImage::from_decoder(decoder).map_err(|e| VisionError::Decode(e.to_string()))?;
210 decoded.apply_orientation(orientation);
211 Ok((Self { pixels: decoded.into_rgba8() }, mime))
212 }
213}
214
215#[derive(Clone, Debug)]
231pub struct SourceImage {
232 digest: Digest,
233 mime_type: String,
234 pixels: Arc<DecodedImage>,
235}
236
237impl SourceImage {
238 pub fn decode(bytes: &[u8], limits: &DecodeLimits) -> Result<Self> {
244 let (pixels, mime) = DecodedImage::decode(bytes, limits)?;
245 Ok(Self {
246 digest: Digest::of(bytes),
247 mime_type: mime.to_string(),
248 pixels: Arc::new(pixels),
249 })
250 }
251
252 pub fn from_pixels(pixels: DecodedImage) -> Result<Self> {
258 let png = pixels.encode_png()?;
259 Ok(Self {
260 digest: Digest::of(&png),
261 mime_type: "image/png".into(),
262 pixels: Arc::new(pixels),
263 })
264 }
265
266 pub(crate) fn from_parts(digest: Digest, mime_type: String, pixels: Arc<DecodedImage>) -> Self {
267 Self { digest, mime_type, pixels }
268 }
269
270 pub fn digest(&self) -> Digest {
272 self.digest
273 }
274
275 pub fn mime_type(&self) -> &str {
277 &self.mime_type
278 }
279
280 pub fn pixels(&self) -> &DecodedImage {
282 &self.pixels
283 }
284
285 pub(crate) fn shared_pixels(&self) -> Arc<DecodedImage> {
286 Arc::clone(&self.pixels)
287 }
288
289 pub fn size(&self) -> (u32, u32) {
291 self.pixels.size()
292 }
293}
294
295#[cfg(test)]
296mod tests {
297 use super::*;
298
299 #[test]
300 fn caps_refuse_before_decoding() {
301 let png = DecodedImage::filled(100, 100, [1, 2, 3, 255]).encode_png().unwrap();
302 let err = DecodedImage::decode(&png, &DecodeLimits::default().with_max_pixels(9_999))
303 .unwrap_err();
304 assert!(matches!(err, VisionError::TooManyPixels { limit: 9_999, actual: 10_000 }));
305 let err =
306 DecodedImage::decode(&png, &DecodeLimits::default().with_max_bytes(10)).unwrap_err();
307 assert!(matches!(err, VisionError::TooManyBytes { limit: 10, .. }));
308 }
309
310 #[test]
311 fn unknown_formats_are_refused() {
312 let err = DecodedImage::decode(b"GIF89 is not this", &DecodeLimits::default()).unwrap_err();
313 assert!(matches!(err, VisionError::UnsupportedFormat { .. } | VisionError::Decode(_)));
314 let mut bmp = b"BM".to_vec();
315 bmp.extend_from_slice(&[0; 60]);
316 let err = DecodedImage::decode(&bmp, &DecodeLimits::default()).unwrap_err();
317 assert!(matches!(err, VisionError::UnsupportedFormat { .. }), "{err}");
318 }
319
320 #[test]
321 fn png_round_trips_and_encoding_is_stable() {
322 let image = DecodedImage::filled(3, 2, [10, 20, 30, 255]);
323 let a = image.encode_png().unwrap();
324 let (decoded, mime) = DecodedImage::decode(&a, &DecodeLimits::default()).unwrap();
325 assert_eq!(mime, "image/png");
326 assert_eq!(decoded, image);
327 assert_eq!(decoded.encode_png().unwrap(), a);
328 }
329}