Skip to main content

adk_vision/media/
decode.rs

1//! Decoding under limits, and decoded pixels.
2
3use 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/// Caps checked before an image is decoded.
12///
13/// The byte cap is checked against the encoded size and the pixel cap against the size the
14/// header declares, both before any pixel buffer is allocated; the decoder then runs with
15/// the declared dimensions as hard limits.
16///
17/// # Example
18///
19/// ```
20/// use adk_vision::DecodeLimits;
21///
22/// let limits = DecodeLimits::default().with_max_pixels(4_000_000);
23/// assert_eq!(limits.max_pixels, 4_000_000);
24/// ```
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26#[non_exhaustive]
27pub struct DecodeLimits {
28    /// Largest encoded image in bytes. Default 50 MiB.
29    pub max_bytes: u64,
30    /// Largest image in pixels. Default 50 million.
31    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    /// Sets the byte cap.
42    pub fn with_max_bytes(mut self, max_bytes: u64) -> Self {
43        self.max_bytes = max_bytes;
44        self
45    }
46
47    /// Sets the pixel cap.
48    pub fn with_max_pixels(mut self, max_pixels: u64) -> Self {
49        self.max_pixels = max_pixels;
50        self
51    }
52}
53
54/// Decoded RGBA8 pixels, row-major, EXIF orientation already applied.
55#[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    /// Pixels from a row-major RGBA8 buffer.
71    ///
72    /// # Errors
73    ///
74    /// Returns [`VisionError::InvalidInput`] when the buffer is not `width × height × 4`
75    /// bytes, or either side is zero.
76    ///
77    /// # Example
78    ///
79    /// ```
80    /// use adk_vision::DecodedImage;
81    ///
82    /// let white = DecodedImage::from_rgba(2, 1, vec![255; 8]).unwrap();
83    /// assert_eq!(white.pixel(1, 0), [255, 255, 255, 255]);
84    /// assert!(DecodedImage::from_rgba(2, 2, vec![0; 3]).is_err());
85    /// ```
86    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    /// A `width × height` image filled with one colour.
103    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    /// Width in pixels.
120    pub fn width(&self) -> u32 {
121        self.pixels.width()
122    }
123
124    /// Height in pixels.
125    pub fn height(&self) -> u32 {
126        self.pixels.height()
127    }
128
129    /// `(width, height)`.
130    pub fn size(&self) -> (u32, u32) {
131        self.pixels.dimensions()
132    }
133
134    /// The row-major RGBA8 bytes.
135    pub fn rgba(&self) -> &[u8] {
136        self.pixels.as_raw()
137    }
138
139    /// One pixel's RGBA value.
140    ///
141    /// # Panics
142    ///
143    /// Panics when `(x, y)` is outside the image.
144    pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
145        self.pixels.get_pixel(x, y).0
146    }
147
148    /// Encodes the pixels as PNG. The same pixels always encode to the same bytes.
149    ///
150    /// # Errors
151    ///
152    /// Returns [`VisionError::Decode`] when the encoder fails.
153    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    /// Decodes an encoded image under `limits`, applying its EXIF orientation once. Returns
162    /// the pixels and the MIME type of the format.
163    ///
164    /// # Errors
165    ///
166    /// [`VisionError::TooManyBytes`] or [`VisionError::TooManyPixels`] before any pixel
167    /// buffer is allocated; [`VisionError::UnsupportedFormat`] for anything other than PNG,
168    /// JPEG, WebP or GIF; [`VisionError::Decode`] for a corrupt image.
169    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/// A source image on the device: its pixels and the digest of the bytes they came from.
216///
217/// Source images never leave the machine as such; a backend sees one only through the
218/// runtime, as a `SentImage` or, for a remote backend, a `ReleasedImage`.
219///
220/// # Example
221///
222/// ```
223/// use adk_vision::{DecodeLimits, DecodedImage, SourceImage};
224///
225/// let png = DecodedImage::filled(4, 3, [0, 0, 0, 255]).encode_png().unwrap();
226/// let source = SourceImage::decode(&png, &DecodeLimits::default()).unwrap();
227/// assert_eq!(source.size(), (4, 3));
228/// assert_eq!(source.mime_type(), "image/png");
229/// ```
230#[derive(Clone, Debug)]
231pub struct SourceImage {
232    digest: Digest,
233    mime_type: String,
234    pixels: Arc<DecodedImage>,
235}
236
237impl SourceImage {
238    /// Decodes encoded bytes; the digest is the bytes' SHA-256.
239    ///
240    /// # Errors
241    ///
242    /// As [`DecodedImage::decode`].
243    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    /// A source image from pixels; the digest is that of their PNG encoding.
253    ///
254    /// # Errors
255    ///
256    /// As [`DecodedImage::encode_png`].
257    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    /// The digest of the image's encoded bytes.
271    pub fn digest(&self) -> Digest {
272        self.digest
273    }
274
275    /// The MIME type of the encoded bytes.
276    pub fn mime_type(&self) -> &str {
277        &self.mime_type
278    }
279
280    /// The pixels.
281    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    /// `(width, height)`.
290    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}