1use alloc::vec::Vec;
5
6use crate::Error;
7
8#[derive(Clone, Debug)]
9pub(crate) enum Pixels {
10 Jpeg { data: Vec<u8>, comps: u8, invert: bool, transform: Option<u8> },
13 Raw { colors: u8, data: Vec<u8> },
15}
16
17#[derive(Clone, Debug)]
20pub struct Image {
21 pub(crate) w: u32,
22 pub(crate) h: u32,
23 pub(crate) px: Pixels,
24 pub(crate) alpha: Option<Vec<u8>>,
25 pub(crate) interpolate: bool,
26}
27
28const MAX_SIDE: u32 = 1 << 16;
30
31fn check_size(w: u32, h: u32, n: usize, len: usize) -> Result<(), Error> {
32 if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE {
33 return Err(Error::Image("a side of 1 to 65536 pixels"));
34 }
35 if (w as usize).checked_mul(h as usize).and_then(|p| p.checked_mul(n)) != Some(len) {
36 return Err(Error::Image("pixel data of width x height x components bytes"));
37 }
38 Ok(())
39}
40
41impl Image {
42 pub fn jpeg(data: Vec<u8>) -> Result<Image, Error> {
45 let j = parse_jpeg(&data)?;
46 Ok(Image { w: j.w, h: j.h, px: Pixels::Jpeg { data, comps: j.comps, invert: j.invert, transform: j.transform }, alpha: None, interpolate: false })
47 }
48
49 pub fn gray(w: u32, h: u32, px: &[u8]) -> Result<Image, Error> {
51 check_size(w, h, 1, px.len())?;
52 Ok(Image { w, h, px: Pixels::Raw { colors: 1, data: px.to_vec() }, alpha: None, interpolate: false })
53 }
54
55 pub fn rgb(w: u32, h: u32, px: &[u8]) -> Result<Image, Error> {
57 check_size(w, h, 3, px.len())?;
58 Ok(Image::raw(w, h, px.to_vec(), None))
59 }
60
61 pub fn rgba(w: u32, h: u32, px: &[u8]) -> Result<Image, Error> {
63 check_size(w, h, 4, px.len())?;
64 let n = w as usize * h as usize;
65 let mut rgb = Vec::with_capacity(n * 3);
66 let mut alpha = Vec::with_capacity(n);
67 for p in px.chunks_exact(4) {
68 rgb.extend_from_slice(&p[..3]);
69 alpha.push(p[3]);
70 }
71 Ok(Image::raw(w, h, rgb, Some(alpha)))
72 }
73
74 pub fn from_surface(s: &gfx::Surface) -> Result<Image, Error> {
77 if s.w <= 0 || s.h <= 0 || s.stride < 0 {
78 return Err(Error::Image("an empty surface"));
79 }
80 let (w, h, stride) = (s.w as usize, s.h as usize, s.stride as usize);
81 let bpp = if s.fmt == gfx::FMT_A8 { 1 } else { 4 };
82 if stride < w * bpp || s.px.len() < stride * (h - 1) + w * bpp {
83 return Err(Error::Image("a surface smaller than its size"));
84 }
85 if s.fmt == gfx::FMT_A8 {
86 let mut g = Vec::with_capacity(w * h);
87 for y in 0..h {
88 g.extend_from_slice(&s.px[y * stride..y * stride + w]);
89 }
90 return Image::gray(w as u32, h as u32, &g);
91 }
92 let mut rgb = Vec::with_capacity(w * h * 3);
93 let mut alpha = Vec::with_capacity(w * h);
94 for y in 0..h {
95 for p in s.px[y * stride..y * stride + w * 4].chunks_exact(4) {
96 let a = if s.fmt == gfx::FMT_XRGB { 255 } else { p[3] };
98 let un = |c: u8| -> u8 {
99 if s.fmt != gfx::FMT_PARGB || a == 255 {
100 c
101 } else if a == 0 {
102 0
103 } else {
104 ((c as u32 * 255 + a as u32 / 2) / a as u32).min(255) as u8
105 }
106 };
107 rgb.extend_from_slice(&[un(p[2]), un(p[1]), un(p[0])]);
108 alpha.push(a);
109 }
110 }
111 check_size(w as u32, h as u32, 3, rgb.len())?;
112 Ok(Image::raw(w as u32, h as u32, rgb, Some(alpha)))
113 }
114
115 fn raw(w: u32, h: u32, rgb: Vec<u8>, alpha: Option<Vec<u8>>) -> Image {
117 let alpha = alpha.filter(|a| a.iter().any(|&v| v != 255));
118 let gray = rgb.chunks_exact(3).all(|p| p[0] == p[1] && p[1] == p[2]);
119 let px = if gray { Pixels::Raw { colors: 1, data: rgb.chunks_exact(3).map(|p| p[0]).collect() } } else { Pixels::Raw { colors: 3, data: rgb } };
120 Image { w, h, px, alpha, interpolate: false }
121 }
122
123 pub fn with_alpha(mut self, alpha: Vec<u8>) -> Result<Image, Error> {
125 check_size(self.w, self.h, 1, alpha.len())?;
126 self.alpha = if alpha.iter().all(|&v| v == 255) { None } else { Some(alpha) };
127 Ok(self)
128 }
129
130 pub fn interpolate(mut self, on: bool) -> Image {
132 self.interpolate = on;
133 self
134 }
135
136 pub fn size(&self) -> (u32, u32) {
138 (self.w, self.h)
139 }
140
141 pub fn is_jpeg(&self) -> bool {
142 matches!(self.px, Pixels::Jpeg { .. })
143 }
144
145 pub fn has_alpha(&self) -> bool {
146 self.alpha.is_some()
147 }
148}
149
150struct JpegInfo {
151 w: u32,
152 h: u32,
153 comps: u8,
154 invert: bool,
155 transform: Option<u8>,
156}
157
158fn parse_jpeg(d: &[u8]) -> Result<JpegInfo, Error> {
160 if d.len() < 4 || d[0] != 0xFF || d[1] != 0xD8 {
161 return Err(Error::Image("not a JPEG file"));
162 }
163 let mut i = 2;
164 let mut adobe: Option<u8> = None;
165 loop {
166 while i < d.len() && d[i] == 0xFF && d.get(i + 1) == Some(&0xFF) {
168 i += 1;
169 }
170 if i + 4 > d.len() || d[i] != 0xFF {
171 return Err(Error::Image("a JPEG file without a frame header"));
172 }
173 let m = d[i + 1];
174 if matches!(m, 0xD0..=0xD7 | 0x01) {
175 i += 2;
176 continue;
177 }
178 if m == 0xD9 || m == 0xDA {
179 return Err(Error::Image("a JPEG file without a frame header"));
180 }
181 let len = u16::from_be_bytes([d[i + 2], d[i + 3]]) as usize;
182 if len < 2 || i + 2 + len > d.len() {
183 return Err(Error::Image("a truncated JPEG segment"));
184 }
185 let seg = &d[i + 4..i + 2 + len];
186 match m {
187 0xEE if seg.len() >= 12 && &seg[..5] == b"Adobe" => adobe = Some(seg[11]),
188 0xC0..=0xC2 => {
189 if seg.len() < 6 {
190 return Err(Error::Image("a truncated JPEG frame header"));
191 }
192 if seg[0] != 8 {
193 return Err(Error::Unsupported("JPEG with other than 8 bits per sample"));
194 }
195 let h = u16::from_be_bytes([seg[1], seg[2]]) as u32;
196 let w = u16::from_be_bytes([seg[3], seg[4]]) as u32;
197 let comps = seg[5];
198 if w == 0 || h == 0 {
199 return Err(Error::Unsupported("JPEG whose height comes later (DNL)"));
200 }
201 if !matches!(comps, 1 | 3 | 4) {
202 return Err(Error::Unsupported("JPEG with other than 1, 3 or 4 components"));
203 }
204 if adobe.is_none() {
206 adobe = find_adobe(&d[i + 2 + len..]);
207 }
208 let transform = match (comps, adobe) {
209 (3, Some(0)) => Some(0),
210 (4, Some(t)) if t != 0 => Some(1),
211 _ => None,
212 };
213 return Ok(JpegInfo { w, h, comps, invert: comps == 4 && adobe.is_some(), transform });
214 }
215 0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF => {
216 return Err(Error::Unsupported("lossless, hierarchical or arithmetic-coded JPEG"));
217 }
218 _ => {}
219 }
220 i += 2 + len;
221 }
222}
223
224fn find_adobe(d: &[u8]) -> Option<u8> {
225 let mut i = 0;
226 while i + 4 <= d.len() && d[i] == 0xFF {
227 let m = d[i + 1];
228 if m == 0xDA || m == 0xD9 {
229 return None;
230 }
231 let len = u16::from_be_bytes([d[i + 2], d[i + 3]]) as usize;
232 if len < 2 || i + 2 + len > d.len() {
233 return None;
234 }
235 let seg = &d[i + 4..i + 2 + len];
236 if m == 0xEE && seg.len() >= 12 && &seg[..5] == b"Adobe" {
237 return Some(seg[11]);
238 }
239 i += 2 + len;
240 }
241 None
242}
243
244pub(crate) fn png_filter(data: &[u8], w: usize, bpp: usize) -> Vec<u8> {
247 let row = w * bpp;
248 let h = data.len().checked_div(row).unwrap_or(0);
249 let mut out = Vec::with_capacity(h * (row + 1));
250 let zero = alloc::vec![0u8; row];
251 let mut cand = [Vec::with_capacity(row), Vec::with_capacity(row), Vec::with_capacity(row), Vec::with_capacity(row), Vec::with_capacity(row)];
252 for y in 0..h {
253 let cur = &data[y * row..(y + 1) * row];
254 let up = if y > 0 { &data[(y - 1) * row..y * row] } else { &zero[..] };
255 for c in cand.iter_mut() {
256 c.clear();
257 }
258 for x in 0..row {
259 let a = if x >= bpp { cur[x - bpp] } else { 0 };
260 let b = up[x];
261 let c = if x >= bpp { up[x - bpp] } else { 0 };
262 let v = cur[x];
263 cand[0].push(v);
264 cand[1].push(v.wrapping_sub(a));
265 cand[2].push(v.wrapping_sub(b));
266 cand[3].push(v.wrapping_sub(((a as u16 + b as u16) / 2) as u8));
267 cand[4].push(v.wrapping_sub(paeth(a, b, c)));
268 }
269 let cost = |v: &Vec<u8>| v.iter().map(|&x| (x as i8).unsigned_abs() as u64).sum::<u64>();
270 let mut best = 0;
271 let mut best_cost = u64::MAX;
272 for (k, c) in cand.iter().enumerate() {
273 let s = cost(c);
274 if s < best_cost {
275 best = k;
276 best_cost = s;
277 }
278 }
279 out.push(best as u8);
280 out.extend_from_slice(&cand[best]);
281 }
282 out
283}
284
285fn paeth(a: u8, b: u8, c: u8) -> u8 {
286 let p = a as i16 + b as i16 - c as i16;
287 let pa = (p - a as i16).abs();
288 let pb = (p - b as i16).abs();
289 let pc = (p - c as i16).abs();
290 if pa <= pb && pa <= pc {
291 a
292 } else if pb <= pc {
293 b
294 } else {
295 c
296 }
297}