Skip to main content

unityrs_texture/write/
source.rs

1// Ported from Pillow 9.5.0 (MIT-CMU): src/libImaging/Convert.c and src/PIL/Image.py's convert. See LICENSE-PILLOW.
2// Copyright (c) 1997-2005 by Secret Labs AB.
3// Copyright (c) 1995-1997 by Fredrik Lundh.
4//! Borrowed Pillow pixel storage, including modes outside the PNG image model.
5use super::WriteError;
6use std::sync::Arc;
7use unityrs_core::limits::{Meter, MeteredVec};
8use unityrs_imageio::{Image, Mode};
9
10/// A Pillow image's `tobytes()` storage. Integer/float modes use native byte
11/// order, `1` uses MSB-first bits with each row rounded up to a byte. Palette
12/// entries are RGBA, permitting palette alpha and PA's separate alpha band.
13#[derive(Clone, Copy, Debug)]
14pub struct Source<'a> {
15    width: u32,
16    height: u32,
17    mode: &'a str,
18    bytes: &'a [u8],
19    palette: Option<&'a [[u8; 4]; 256]>,
20    auxiliary: Option<&'a [u8]>,
21}
22const _: () = crate::send_sync::<Source<'static>>();
23impl<'a> Source<'a> {
24    /// Validate the complete storage before any allocation or pixel access.
25    pub fn new(
26        width: u32,
27        height: u32,
28        mode: &'a str,
29        bytes: &'a [u8],
30        palette: Option<&'a [[u8; 4]; 256]>,
31    ) -> Result<Self, WriteError> {
32        let channels = match mode {
33            "1" | "L" | "P" => 1,
34            "LA" | "La" | "PA" | "I;16" | "I;16L" | "I;16B" | "I;16N" | "BGR;15" | "BGR;16" => 2,
35            "RGB" | "LAB" | "HSV" | "YCbCr" | "BGR;24" => 3,
36            "RGBA" | "RGBX" | "RGBa" | "CMYK" | "I" | "F" => 4,
37            _ => return Err(WriteError::Unsupported("image mode")),
38        };
39        let row = if mode == "1" {
40            u64::from(width).div_ceil(8)
41        } else {
42            u64::from(width) * channels
43        };
44        let len = row
45            .checked_mul(u64::from(height))
46            .ok_or(WriteError::Invalid("image size"))?;
47        if len != bytes.len() as u64 {
48            return Err(WriteError::Invalid("pixel length"));
49        }
50        if width > i32::MAX as u32
51            || height > i32::MAX as u32
52            || u64::from(width) * u64::from(height) > crate::MAX_PIXELS
53        {
54            return Err(WriteError::Invalid("image dimensions exceed bounds"));
55        }
56        Ok(Self {
57            width,
58            height,
59            mode,
60            bytes,
61            palette,
62            auxiliary: None,
63        })
64    }
65    /// Preserve Pillow's otherwise unexported fourth storage byte of `RGB` or
66    /// `LAB`. `frombytes` initializes it to 255; `Image.new` initializes it to
67    /// zero. Raw RGBA packing and `ImageCms` copy it. Other modes ignore it.
68    pub fn with_auxiliary(mut self, bytes: &'a [u8]) -> Result<Self, WriteError> {
69        if bytes.len() as u64 != u64::from(self.width) * u64::from(self.height) {
70            return Err(WriteError::Invalid("auxiliary band length"));
71        }
72        self.auxiliary = Some(bytes);
73        Ok(self)
74    }
75    pub(super) const fn auxiliary(&self) -> Option<&'a [u8]> {
76        self.auxiliary
77    }
78    /// Image width.
79    #[must_use]
80    pub const fn width(&self) -> u32 {
81        self.width
82    }
83    /// Image height.
84    #[must_use]
85    pub const fn height(&self) -> u32 {
86        self.height
87    }
88    /// Pillow's mode name.
89    #[must_use]
90    pub const fn mode(&self) -> &str {
91        self.mode
92    }
93
94    pub(super) fn check_convertible(&self) -> Result<(), WriteError> {
95        if matches!(self.mode, "BGR;15" | "BGR;16" | "BGR;24" | "La") {
96            return Err(WriteError::Unsupported(
97                "Pillow cannot convert image mode to RGBA",
98            ));
99        }
100        Ok(())
101    }
102    pub(super) fn prepare(
103        &self,
104        channels: usize,
105        alpha: bool,
106        meter: &Arc<Meter>,
107    ) -> Result<Prepared, WriteError> {
108        self.check_convertible()?;
109        let direct = if alpha {
110            matches!(self.mode, "RGBA" | "LAB")
111        } else if channels == 4 {
112            matches!(self.mode, "RGB" | "RGBA")
113        } else {
114            matches!(self.mode, "RGB" | "RGBX" | "RGBA")
115        };
116        let lab_alpha = alpha && self.mode == "LAB";
117        let mode = if lab_alpha || (direct && self.mode != "RGBA" && !alpha) {
118            Mode::Rgb
119        } else {
120            Mode::Rgba
121        };
122        let len = self.width as usize * self.height as usize * mode.channels();
123        meter.count_decode(len as u64)?;
124        let mut bytes = MeteredVec::with_capacity(meter, len)?;
125        for n in 0..self.width as usize * self.height as usize {
126            if lab_alpha {
127                let p = self
128                    .bytes
129                    .get(n * 3..n * 3 + 3)
130                    .ok_or(WriteError::Invalid("LAB pixel"))?;
131                for (i, &b) in p.iter().enumerate() {
132                    bytes.push(if i == 0 { b } else { b ^ 128 })?;
133                }
134            } else {
135                let rgba = self.rgba(n)?;
136                bytes.extend_from_slice(
137                    rgba.get(..mode.channels())
138                        .ok_or(WriteError::Invalid("converted pixel"))?,
139                )?;
140            }
141        }
142        Ok(Prepared {
143            width: self.width,
144            height: self.height,
145            mode,
146            bytes,
147            alpha_band: if lab_alpha { 1 } else { 3 },
148        })
149    }
150
151    fn rgba(&self, n: usize) -> Result<[u8; 4], WriteError> {
152        let stride = match self.mode {
153            "L" | "P" | "1" => 1,
154            "LA" | "PA" | "I;16" | "I;16L" | "I;16B" | "I;16N" => 2,
155            "RGB" | "YCbCr" | "HSV" | "LAB" => 3,
156            _ => 4,
157        };
158        let pixel = self.bytes.get(n * stride..n * stride + stride);
159        let byte = |i| pixel.and_then(|p| p.get(i)).copied().unwrap_or(0);
160        let grey = |v| [v, v, v, 255];
161        Ok(match self.mode {
162            "1" => {
163                let x = n % self.width as usize;
164                let y = n / self.width as usize;
165                let value = self
166                    .bytes
167                    .get(y * (self.width as usize).div_ceil(8) + x / 8)
168                    .copied()
169                    .unwrap_or(0);
170                grey(if value & (128 >> (x % 8)) == 0 {
171                    0
172                } else {
173                    255
174                })
175            }
176            "L" => grey(byte(0)),
177            "LA" => [byte(0), byte(0), byte(0), byte(1)],
178            "P" | "PA" => {
179                let mut color = self.palette.map_or_else(
180                    || grey(byte(0)),
181                    |p| p.get(usize::from(byte(0))).copied().unwrap_or([0; 4]),
182                );
183                if self.mode == "PA" {
184                    color[3] = byte(1);
185                }
186                color
187            }
188            "RGB" | "RGBX" => [byte(0), byte(1), byte(2), 255],
189            "RGBA" => [byte(0), byte(1), byte(2), byte(3)],
190            "RGBa" => {
191                let a = u32::from(byte(3));
192                let unpremultiply = |c| {
193                    if a == 0 || a == 255 {
194                        c
195                    } else {
196                        u8::try_from((u32::from(c) * 255 / a).min(255)).unwrap_or(255)
197                    }
198                };
199                [
200                    unpremultiply(byte(0)),
201                    unpremultiply(byte(1)),
202                    unpremultiply(byte(2)),
203                    byte(3),
204                ]
205            }
206            "CMYK" => {
207                let k = 255 - u32::from(byte(3));
208                let convert = |c| {
209                    let t = u32::from(c) * k + 128;
210                    u8::try_from(k - ((t + (t >> 8)) >> 8)).unwrap_or(0)
211                };
212                [convert(byte(0)), convert(byte(1)), convert(byte(2)), 255]
213            }
214            "I" => grey(
215                u8::try_from(
216                    i32::from_ne_bytes([byte(0), byte(1), byte(2), byte(3)]).clamp(0, 255),
217                )
218                .unwrap_or(0),
219            ),
220            "F" => {
221                let v = f32::from_ne_bytes([byte(0), byte(1), byte(2), byte(3)]);
222                grey(float_byte(v))
223            }
224            "I;16" | "I;16L" | "I;16B" | "I;16N" => {
225                let raw = [byte(0), byte(1)];
226                let v = match self.mode {
227                    "I;16B" => u16::from_be_bytes(raw),
228                    "I;16N" => u16::from_ne_bytes(raw),
229                    _ => u16::from_le_bytes(raw),
230                };
231                grey(u8::try_from(v).unwrap_or(255))
232            }
233            "HSV" => hsv(byte(0), byte(1), byte(2)),
234            "YCbCr" => super::ycbcr::convert(byte(0), byte(1), byte(2)),
235            "LAB" => {
236                let mut color = super::lab::convert(byte(0), byte(1), byte(2));
237                color[3] = self
238                    .auxiliary
239                    .and_then(|b| b.get(n))
240                    .copied()
241                    .unwrap_or(255);
242                color
243            }
244            _ => return Err(WriteError::Unsupported("image mode conversion")),
245        })
246    }
247}
248
249#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
250fn float_byte(v: f32) -> u8 {
251    v.clamp(0.0, 255.0) as u8
252}
253// C promotes expressions containing double literals, then assigns f/fs as floats.
254#[allow(
255    clippy::cast_possible_truncation,
256    clippy::cast_sign_loss,
257    clippy::many_single_char_names
258)]
259fn hsv(h: u8, s: u8, v: u8) -> [u8; 4] {
260    if s == 0 {
261        return [v, v, v, 255];
262    }
263    let sector = f64::from(h) * 6.0 / 255.0;
264    let i = sector.floor() as u32;
265    let f = (sector - f64::from(i)) as f32;
266    let fs = (f64::from(s) / 255.0) as f32;
267    let p = (f64::from(v) * (1.0 - f64::from(fs))).round() as u8;
268    let q = (f64::from(v) * (1.0 - f64::from(fs * f))).round() as u8;
269    let t = (f64::from(v) * (1.0 - f64::from(fs) * (1.0 - f64::from(f)))).round() as u8;
270    let [r, g, b] = match i % 6 {
271        0 => [v, t, p],
272        1 => [q, v, p],
273        2 => [p, v, t],
274        3 => [p, q, v],
275        4 => [t, p, v],
276        _ => [v, p, q],
277    };
278    [r, g, b, 255]
279}
280pub(super) struct Prepared {
281    width: u32,
282    height: u32,
283    pub mode: Mode,
284    bytes: MeteredVec<u8>,
285    pub alpha_band: usize,
286}
287impl Prepared {
288    pub fn image(&self) -> Result<Image<'_>, WriteError> {
289        Image::new(self.width, self.height, self.mode, self.bytes.as_slice())
290            .map_err(|_| WriteError::Invalid("prepared image"))
291    }
292}