Skip to main content

pltrs_codec/
raster.rs

1//! Decoded images as Pillow presents them: the JPEG, TIFF and GIF decoders
2//! all produce a [`Raster`] whose [`Pixels`] variant is the Pillow image
3//! mode the same file opens in, holding the same values. [`Raster::to_rgba8`]
4//! is Pillow's `convert("RGBA")`.
5
6/// The most pixels a decoded image may have. Pillow refuses larger images
7/// as decompression bombs (twice `PIL.Image.MAX_IMAGE_PIXELS`).
8pub const MAX_PIXELS: u64 = 178_956_970;
9
10/// The colours of an indexed image, with at most one transparent entry.
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct Palette {
13    colors: Vec<[u8; 3]>,
14    transparent: Option<u8>,
15}
16
17impl Palette {
18    /// A palette of at most 256 `colors` (later entries are dropped);
19    /// `transparent` is the index drawn fully transparent, if any.
20    pub fn new(mut colors: Vec<[u8; 3]>, transparent: Option<u8>) -> Self {
21        colors.truncate(256);
22        Self {
23            colors,
24            transparent,
25        }
26    }
27
28    /// The colours, in index order.
29    pub fn colors(&self) -> &[[u8; 3]] {
30        &self.colors
31    }
32
33    /// The transparent index, if any.
34    pub fn transparent(&self) -> Option<u8> {
35        self.transparent
36    }
37
38    /// The RGBA colour of `index` as Pillow's palettes give it: indices
39    /// past the colours are opaque black, the transparent index has alpha
40    /// 0 and every other entry is opaque.
41    pub fn rgba(&self, index: u8) -> [u8; 4] {
42        let [r, g, b] = self
43            .colors
44            .get(usize::from(index))
45            .copied()
46            .unwrap_or_default();
47        let alpha = if self.transparent == Some(index) {
48            0
49        } else {
50            255
51        };
52        [r, g, b, alpha]
53    }
54}
55
56/// The pixels of a decoded image, row by row, in one of Pillow's modes.
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub enum Pixels {
59    /// Mode `1`: bilevel pixels, each 0 (black) or 255 (white).
60    Bilevel(Vec<u8>),
61    /// Mode `L`: 8-bit grey levels.
62    Gray(Vec<u8>),
63    /// Mode `I;16`: 16-bit grey levels.
64    Gray16(Vec<u16>),
65    /// Mode `LA`: 8-bit grey levels with alpha.
66    GrayAlpha(Vec<[u8; 2]>),
67    /// Mode `RGB`: 8-bit colours.
68    Rgb(Vec<[u8; 3]>),
69    /// Mode `RGBA`: 8-bit colours with straight (not premultiplied) alpha.
70    Rgba(Vec<[u8; 4]>),
71    /// Mode `CMYK`: 8-bit ink amounts, 255 being full ink.
72    Cmyk(Vec<[u8; 4]>),
73    /// Mode `P`: palette indices.
74    Indexed {
75        /// The colours the indices refer to.
76        palette: Palette,
77        /// One index per pixel.
78        indices: Vec<u8>,
79    },
80    /// Mode `PA`: palette indices with alpha.
81    IndexedAlpha {
82        /// The colours the indices refer to.
83        palette: Palette,
84        /// An index and an alpha per pixel.
85        pixels: Vec<[u8; 2]>,
86    },
87}
88
89impl Pixels {
90    /// The number of pixels held.
91    pub fn len(&self) -> usize {
92        match self {
93            Self::Bilevel(v) | Self::Gray(v) => v.len(),
94            Self::Gray16(v) => v.len(),
95            Self::GrayAlpha(v) => v.len(),
96            Self::Rgb(v) => v.len(),
97            Self::Rgba(v) | Self::Cmyk(v) => v.len(),
98            Self::Indexed { indices, .. } => indices.len(),
99            Self::IndexedAlpha { pixels, .. } => pixels.len(),
100        }
101    }
102
103    /// Returns `true` when no pixels are held.
104    pub fn is_empty(&self) -> bool {
105        self.len() == 0
106    }
107
108    /// Every pixel as Pillow's `convert("RGBA")` gives it.
109    pub fn to_rgba8(&self) -> Vec<[u8; 4]> {
110        let gray = |v: u8| [v, v, v, 255];
111        match self {
112            Self::Bilevel(v) => v
113                .iter()
114                .map(|&v| gray(if v == 0 { 0 } else { 255 }))
115                .collect(),
116            Self::Gray(v) => v.iter().map(|&v| gray(v)).collect(),
117            Self::Gray16(v) => v
118                .iter()
119                .map(|&v| gray(u8::try_from(v).unwrap_or(u8::MAX)))
120                .collect(),
121            Self::GrayAlpha(v) => v.iter().map(|&[l, a]| [l, l, l, a]).collect(),
122            Self::Rgb(v) => v.iter().map(|&[r, g, b]| [r, g, b, 255]).collect(),
123            Self::Rgba(v) => v.clone(),
124            Self::Cmyk(v) => v.iter().map(|&cmyk| cmyk_to_rgba(cmyk)).collect(),
125            Self::Indexed { palette, indices } => {
126                indices.iter().map(|&i| palette.rgba(i)).collect()
127            }
128            Self::IndexedAlpha { palette, pixels } => pixels
129                .iter()
130                .map(|&[i, a]| {
131                    let [r, g, b, _] = palette.rgba(i);
132                    [r, g, b, a]
133                })
134                .collect(),
135        }
136    }
137}
138
139/// Pillow's `cmyk2rgb`: each channel is `(255 − k) · (1 − ink / 255)`,
140/// rounded with its divide-by-255 shortcut.
141fn cmyk_to_rgba([c, m, y, k]: [u8; 4]) -> [u8; 4] {
142    let remaining = 255 - u32::from(k);
143    let channel = |ink: u8| {
144        let product = u32::from(ink) * remaining + 128;
145        let scaled = ((product >> 8) + product) >> 8;
146        u8::try_from(remaining - scaled).expect("at most the remaining 255 - k")
147    };
148    [channel(c), channel(m), channel(y), 255]
149}
150
151/// A decoded image: its size and its pixels in a Pillow mode.
152#[derive(Clone, Debug, PartialEq, Eq)]
153pub struct Raster {
154    width: u32,
155    height: u32,
156    pixels: Pixels,
157}
158
159impl Raster {
160    /// An image of `width × height` pixels; `pixels` holds exactly that
161    /// many.
162    pub(crate) fn new(width: u32, height: u32, pixels: Pixels) -> Self {
163        debug_assert_eq!(
164            pixels.len() as u64,
165            u64::from(width) * u64::from(height),
166            "the pixels fill the image"
167        );
168        Self {
169            width,
170            height,
171            pixels,
172        }
173    }
174
175    /// The width in pixels.
176    pub fn width(&self) -> u32 {
177        self.width
178    }
179
180    /// The height in pixels.
181    pub fn height(&self) -> u32 {
182        self.height
183    }
184
185    /// The pixels, row by row.
186    pub fn pixels(&self) -> &Pixels {
187        &self.pixels
188    }
189
190    /// Takes the pixels.
191    pub fn into_pixels(self) -> Pixels {
192        self.pixels
193    }
194
195    /// Every pixel as Pillow's `convert("RGBA")` gives it.
196    pub fn to_rgba8(&self) -> Vec<[u8; 4]> {
197        self.pixels.to_rgba8()
198    }
199}
200
201/// Whether a `width × height` image is small enough to decode: at most
202/// [`MAX_PIXELS`] pixels and, as each pixel costs at least `1 / per_byte`
203/// bytes of a valid file, at most `per_byte × input_len` pixels. Checking
204/// before allocating keeps a forged header from claiming gigabytes.
205pub(crate) fn fits(width: u32, height: u32, input_len: usize, per_byte: u64) -> bool {
206    let pixels = u64::from(width) * u64::from(height);
207    let input = u64::try_from(input_len).unwrap_or(u64::MAX);
208    pixels <= MAX_PIXELS && pixels <= input.saturating_mul(per_byte)
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    #[test]
216    fn palettes_fill_missing_entries_with_opaque_black() {
217        let palette = Palette::new(vec![[1, 2, 3], [4, 5, 6]], Some(1));
218        assert_eq!(palette.rgba(0), [1, 2, 3, 255]);
219        assert_eq!(palette.rgba(1), [4, 5, 6, 0]);
220        assert_eq!(palette.rgba(9), [0, 0, 0, 255]);
221        let transparent_past_end = Palette::new(vec![[1, 2, 3]], Some(200));
222        assert_eq!(transparent_past_end.rgba(200), [0, 0, 0, 0]);
223        assert_eq!(Palette::new(vec![[0; 3]; 300], None).colors().len(), 256);
224    }
225
226    #[test]
227    fn conversions_follow_pillow() {
228        assert_eq!(
229            Pixels::Bilevel(vec![0, 255]).to_rgba8(),
230            [[0, 0, 0, 255], [255; 4]]
231        );
232        assert_eq!(
233            Pixels::Gray16(vec![7, 300]).to_rgba8(),
234            [[7, 7, 7, 255], [255; 4]]
235        );
236        assert_eq!(Pixels::GrayAlpha(vec![[9, 3]]).to_rgba8(), [[9, 9, 9, 3]]);
237        let palette = Palette::new(vec![[10, 20, 30]], None);
238        assert_eq!(
239            Pixels::IndexedAlpha {
240                palette,
241                pixels: vec![[0, 77]]
242            }
243            .to_rgba8(),
244            [[10, 20, 30, 77]]
245        );
246    }
247
248    #[test]
249    fn cmyk_converts_like_pillow() {
250        assert_eq!(cmyk_to_rgba([0, 0, 0, 0]), [255, 255, 255, 255]);
251        assert_eq!(cmyk_to_rgba([255, 0, 0, 0]), [0, 255, 255, 255]);
252        assert_eq!(cmyk_to_rgba([0, 0, 0, 255]), [0, 0, 0, 255]);
253        // nk = 155, 100 · 155 / 255 ≈ 60.8 rounds to 61: 155 − 61.
254        assert_eq!(cmyk_to_rgba([100, 0, 0, 100])[0], 94);
255    }
256
257    #[test]
258    fn size_limits() {
259        assert!(fits(10, 10, 1, 100));
260        assert!(!fits(10, 11, 1, 100));
261        assert!(!fits(65_535, 65_535, usize::MAX, u64::MAX));
262    }
263}