Skip to main content

qrcode_barcode_scanner/
input.rs

1//! Image input layer — borrowed inputs, anti-DoS limits, BT.601 luma.
2//!
3//! Every scan starts here: an [`ImageInput`] is validated against [`Limits`]
4//! and normalized into the internal owned luma buffer the engines consume.
5//! EXIF orientation is NOT applied in v0.3 (open item — decoders are
6//! rotation-tolerant; only corner coordinates are affected).
7
8use crate::error::{Result, ScanError};
9
10/// Borrowed image input for a scan.
11#[derive(Debug, Clone, Copy)]
12#[non_exhaustive]
13pub enum ImageInput<'a> {
14    /// Encoded image bytes — PNG, JPEG, WebP or GIF.
15    Encoded(&'a [u8]),
16    /// Raw 8-bit RGBA pixels, row-major (browser `ImageData.data` shape).
17    Rgba8 {
18        /// Pixel bytes, `width * height * 4` long.
19        data: &'a [u8],
20        /// Width in pixels.
21        width: u32,
22        /// Height in pixels.
23        height: u32,
24    },
25    /// Raw 8-bit grayscale pixels, row-major.
26    Luma8 {
27        /// Pixel bytes, `width * height` long.
28        data: &'a [u8],
29        /// Width in pixels.
30        width: u32,
31        /// Height in pixels.
32        height: u32,
33    },
34}
35
36impl<'a> ImageInput<'a> {
37    /// Input from encoded image bytes (PNG/JPEG/WebP/GIF).
38    #[must_use]
39    pub fn encoded(bytes: &'a [u8]) -> Self {
40        Self::Encoded(bytes)
41    }
42
43    /// Input from raw RGBA8 pixels (e.g. a camera frame's `ImageData`).
44    #[must_use]
45    pub fn rgba8(data: &'a [u8], width: u32, height: u32) -> Self {
46        Self::Rgba8 {
47            data,
48            width,
49            height,
50        }
51    }
52
53    /// Input from raw grayscale pixels.
54    #[must_use]
55    pub fn luma8(data: &'a [u8], width: u32, height: u32) -> Self {
56        Self::Luma8 {
57            data,
58            width,
59            height,
60        }
61    }
62}
63
64/// Anti-DoS bounds applied to every input before any pixel work.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct Limits {
67    /// Maximum width or height in pixels.
68    pub max_dimension: u32,
69    /// Maximum total pixel count.
70    pub max_pixels: u64,
71}
72
73impl Default for Limits {
74    fn default() -> Self {
75        Self {
76            max_dimension: 10_000,
77            max_pixels: 64_000_000,
78        }
79    }
80}
81
82impl Limits {
83    /// Refuse limits no input can pass (`QRS-006`): a zero `max_dimension`
84    /// or `max_pixels` would turn every scan into `QRS-002`/`QRS-003`.
85    ///
86    /// # Errors
87    /// `QRS-006` naming the zero limit.
88    pub fn validate(&self) -> Result<()> {
89        if self.max_dimension == 0 {
90            return Err(ScanError::invalid_option(
91                "max_dimension",
92                "0 pixels; the smallest is 1",
93            ));
94        }
95        if self.max_pixels == 0 {
96            return Err(ScanError::invalid_option(
97                "max_pixels",
98                "0 pixels; the smallest is 1",
99            ));
100        }
101        Ok(())
102    }
103}
104
105/// Internal owned grayscale image — the only shape engines consume.
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub(crate) struct LumaImage {
108    data: Vec<u8>,
109    width: u32,
110    height: u32,
111}
112
113impl LumaImage {
114    pub(crate) fn new(data: Vec<u8>, width: u32, height: u32) -> Self {
115        debug_assert_eq!(data.len() as u64, u64::from(width) * u64::from(height));
116        Self {
117            data,
118            width,
119            height,
120        }
121    }
122
123    pub(crate) fn width(&self) -> u32 {
124        self.width
125    }
126
127    pub(crate) fn height(&self) -> u32 {
128        self.height
129    }
130
131    pub(crate) fn data(&self) -> &[u8] {
132        &self.data
133    }
134}
135
136/// Validate dimensions against limits. Zero dimensions are invalid input.
137pub(crate) fn validate_dims(width: u32, height: u32, limits: &Limits) -> Result<u64> {
138    if width == 0 || height == 0 {
139        return Err(ScanError::InvalidImage {
140            details: format!("zero dimension: {width}x{height}"),
141        });
142    }
143    if width > limits.max_dimension || height > limits.max_dimension {
144        return Err(ScanError::DimensionsExceeded {
145            width,
146            height,
147            max_dimension: limits.max_dimension,
148        });
149    }
150    let pixels = u64::from(width) * u64::from(height);
151    if pixels > limits.max_pixels {
152        return Err(ScanError::PixelOverflow {
153            width,
154            height,
155            max_pixels: limits.max_pixels,
156        });
157    }
158    Ok(pixels)
159}
160
161/// Check a raw buffer length against the expected byte count.
162pub(crate) fn validate_buffer(got: usize, expected: u64) -> Result<usize> {
163    let expected_usize = usize::try_from(expected).map_err(|_| ScanError::PixelOverflow {
164        width: 0,
165        height: 0,
166        max_pixels: expected,
167    })?;
168    if got != expected_usize {
169        return Err(ScanError::BufferMismatch {
170            got,
171            expected: expected_usize,
172        });
173    }
174    Ok(expected_usize)
175}
176
177/// BT.601 integer luma: `y = (299r + 587g + 114b + 500) / 1000`.
178pub(crate) fn bt601(r: u8, g: u8, b: u8) -> u8 {
179    let y = (299 * u32::from(r) + 587 * u32::from(g) + 114 * u32::from(b) + 500) / 1000;
180    // 0..=255 by construction: max = (299+587+114)*255/1000 = 255
181    u8::try_from(y).unwrap_or(u8::MAX)
182}
183
184#[cfg(test)]
185mod tests {
186    // Tests assert via unwrap by design — the workspace deny targets src paths.
187    #![allow(clippy::unwrap_used, clippy::expect_used)]
188
189    use super::*;
190    use crate::ScanError;
191
192    /// The historical seam: input validation is exercised through the
193    /// crate's single decode point (`transform::normalize`).
194    fn decode_to_luma(input: &ImageInput<'_>, limits: &Limits) -> crate::Result<LumaImage> {
195        crate::transform::normalize(input, limits).map(|planes| planes.luma)
196    }
197
198    fn png_bytes(width: u32, height: u32) -> Vec<u8> {
199        let img = image::DynamicImage::ImageLuma8(image::ImageBuffer::new(width, height));
200        let mut buf = Vec::new();
201        img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
202            .unwrap();
203        buf
204    }
205
206    #[test]
207    fn encoded_garbage_is_invalid_image() {
208        let err = decode_to_luma(
209            &ImageInput::encoded(b"definitely not an image"),
210            &Limits::default(),
211        )
212        .unwrap_err();
213        assert!(matches!(err, ScanError::InvalidImage { .. }), "{err}");
214        assert_eq!(err.code(), "QRS-001");
215    }
216
217    #[test]
218    fn encoded_oversize_rejected_before_full_decode() {
219        let bytes = png_bytes(2_001, 1);
220        let limits = Limits {
221            max_dimension: 2_000,
222            ..Limits::default()
223        };
224        let err = decode_to_luma(&ImageInput::encoded(&bytes), &limits).unwrap_err();
225        assert!(
226            matches!(
227                err,
228                ScanError::DimensionsExceeded {
229                    width: 2_001,
230                    height: 1,
231                    max_dimension: 2_000
232                }
233            ),
234            "{err}"
235        );
236    }
237
238    #[test]
239    fn raw_oversize_dimension_rejected() {
240        let data = vec![0u8; 4];
241        let err =
242            decode_to_luma(&ImageInput::rgba8(&data, 10_001, 1), &Limits::default()).unwrap_err();
243        assert_eq!(err.code(), "QRS-002");
244    }
245
246    #[test]
247    fn pixel_cap_applies_before_buffer_check() {
248        // 9000x9000 = 81MP > default 64MP cap — buffer length is irrelevant here.
249        let err =
250            decode_to_luma(&ImageInput::luma8(&[], 9_000, 9_000), &Limits::default()).unwrap_err();
251        assert!(
252            matches!(
253                err,
254                ScanError::PixelOverflow {
255                    max_pixels: 64_000_000,
256                    ..
257                }
258            ),
259            "{err}"
260        );
261    }
262
263    #[test]
264    fn rgba8_buffer_mismatch_reports_expected_len() {
265        let data = vec![0u8; 11];
266        let err = decode_to_luma(&ImageInput::rgba8(&data, 2, 2), &Limits::default()).unwrap_err();
267        assert!(
268            matches!(
269                err,
270                ScanError::BufferMismatch {
271                    got: 11,
272                    expected: 16
273                }
274            ),
275            "{err}"
276        );
277    }
278
279    #[test]
280    fn luma8_buffer_mismatch_reports_expected_len() {
281        let data = vec![0u8; 3];
282        let err = decode_to_luma(&ImageInput::luma8(&data, 2, 2), &Limits::default()).unwrap_err();
283        assert!(
284            matches!(
285                err,
286                ScanError::BufferMismatch {
287                    got: 3,
288                    expected: 4
289                }
290            ),
291            "{err}"
292        );
293    }
294
295    #[test]
296    fn rgba8_converts_with_bt601_integer_coefficients() {
297        // red · white · black · green
298        let data: Vec<u8> = vec![
299            255, 0, 0, 255, //
300            255, 255, 255, 255, //
301            0, 0, 0, 255, //
302            0, 255, 0, 255,
303        ];
304        let luma = decode_to_luma(&ImageInput::rgba8(&data, 4, 1), &Limits::default()).unwrap();
305        assert_eq!(luma.width(), 4);
306        assert_eq!(luma.height(), 1);
307        // y = (299r + 587g + 114b + 500) / 1000
308        assert_eq!(luma.data(), &[76, 255, 0, 150]);
309    }
310
311    #[test]
312    fn luma8_is_passthrough() {
313        let data: Vec<u8> = vec![7, 42, 99, 200, 13, 0];
314        let luma = decode_to_luma(&ImageInput::luma8(&data, 3, 2), &Limits::default()).unwrap();
315        assert_eq!(luma.data(), data.as_slice());
316        assert_eq!((luma.width(), luma.height()), (3, 2));
317    }
318
319    #[test]
320    fn encoded_png_roundtrip_decodes_with_correct_dims() {
321        let bytes = png_bytes(31, 17);
322        let luma = decode_to_luma(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
323        assert_eq!((luma.width(), luma.height()), (31, 17));
324        assert_eq!(luma.data().len(), 31 * 17);
325    }
326
327    #[test]
328    fn zero_dimension_is_invalid() {
329        let err = decode_to_luma(&ImageInput::luma8(&[], 0, 4), &Limits::default()).unwrap_err();
330        assert_eq!(err.code(), "QRS-001");
331    }
332
333    /// Every limit admits its exact value: a side of `max_dimension`, either
334    /// way round, and an image of exactly `max_pixels` pass; one more is
335    /// refused, naming the limit it broke.
336    #[test]
337    fn limits_admit_their_exact_values() {
338        let limits = Limits {
339            max_dimension: 100,
340            max_pixels: 5_000,
341        };
342        assert_eq!(validate_dims(100, 1, &limits).unwrap(), 100);
343        assert_eq!(validate_dims(1, 100, &limits).unwrap(), 100);
344        assert_eq!(validate_dims(50, 100, &limits).unwrap(), 5_000);
345        assert!(matches!(
346            validate_dims(101, 1, &limits),
347            Err(ScanError::DimensionsExceeded {
348                width: 101,
349                height: 1,
350                max_dimension: 100
351            })
352        ));
353        assert!(matches!(
354            validate_dims(1, 101, &limits),
355            Err(ScanError::DimensionsExceeded {
356                width: 1,
357                height: 101,
358                max_dimension: 100
359            })
360        ));
361        assert!(matches!(
362            validate_dims(51, 100, &limits),
363            Err(ScanError::PixelOverflow {
364                width: 51,
365                height: 100,
366                max_pixels: 5_000
367            })
368        ));
369    }
370}