| 1 | use ::png; |
| 2 | use super::*; |
| 3 | |
| 4 | #[inline(always)] |
| 5 | fn u16_be_to_u8_rounded(hi: u8, lo: u8) -> u8 { |
| 6 | ((u16::from_be_bytes([hi, lo]) as u32 + 128) / 257) as u8 |
| 7 | } |
| 8 | |
| 9 | const MAX_PNG_OUTPUT_BYTES: usize = 512 * 1024 * 1024; |
| 10 | |
| 11 | pub(super) enum PngDecodeOutcome { |
| 12 | Decoded(([u32; 2], Vec<u8>, bool)), |
| 13 | Fallback, |
| 14 | Reject, |
| 15 | } |
| 16 | |
| 17 | fn decode_png_rows<R: std::io::BufRead + std::io::Seek, F>( |
| 18 | reader: &mut png::Reader<R>, |
| 19 | line_size: usize, |
| 20 | out_len: usize, |
| 21 | row_out_bytes: usize, |
| 22 | mut convert_row: F, |
| 23 | ) -> Option<Vec<u8>> |
| 24 | where |
| 25 | F: FnMut(&[u8], &mut [u8]), |
| 26 | { |
| 27 | let mut rgba = Vec::new(); |
| 28 | rgba.try_reserve_exact(out_len).ok()?; |
| 29 | rgba.resize(out_len, 0); |
| 30 | let mut row_buf = Vec::new(); |
| 31 | row_buf.try_reserve_exact(line_size).ok()?; |
| 32 | row_buf.resize(line_size, 0); |
| 33 | for dst_row in rgba.chunks_exact_mut(row_out_bytes) { |
| 34 | reader.read_row(&mut row_buf).ok()??; |
| 35 | convert_row(&row_buf, dst_row); |
| 36 | } |
| 37 | Some(rgba) |
| 38 | } |
| 39 | |
| 40 | /// Fast direct PNG decoder matching `image::load_from_memory().into_rgba8()` bit-for-bit. |
| 41 | /// Returns `Fallback` for non-PNG, interlaced, animated, ICC-tagged, or unusual formats so the |
| 42 | /// caller falls back cleanly to `image::load_from_memory`, and `Reject` for corrupt or |
| 43 | /// oversized PNGs so callers fail immediately without double-decoding or OOM. |
| 44 | pub(super) fn decode_png_bytes(bytes: &[u8]) -> PngDecodeOutcome { |
| 45 | const PNG_SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10]; |
| 46 | if !bytes.starts_with(&PNG_SIGNATURE) { |
| 47 | return PngDecodeOutcome::Fallback; |
| 48 | } |
| 49 | |
| 50 | let mut decoder = png::Decoder::new_with_limits( |
| 51 | std::io::Cursor::new(bytes), |
| 52 | png::Limits { |
| 53 | bytes: MAX_PNG_OUTPUT_BYTES, |
| 54 | }, |
| 55 | ); |
| 56 | decoder.set_ignore_text_chunk(true); |
| 57 | decoder.set_transformations(png::Transformations::EXPAND); |
| 58 | |
| 59 | let Ok(mut reader) = decoder.read_info() else { |
| 60 | return PngDecodeOutcome::Reject; |
| 61 | }; |
| 62 | let info = reader.info(); |
| 63 | let (w, h) = info.size(); |
| 64 | if w == 0 || h == 0 { |
| 65 | return PngDecodeOutcome::Reject; |
| 66 | } |
| 67 | |
| 68 | let Some(pixel_count) = (w as usize).checked_mul(h as usize) else { |
| 69 | return PngDecodeOutcome::Reject; |
| 70 | }; |
| 71 | let Some(out_len) = pixel_count.checked_mul(4) else { |
| 72 | return PngDecodeOutcome::Reject; |
| 73 | }; |
| 74 | if out_len > MAX_PNG_OUTPUT_BYTES { |
| 75 | return PngDecodeOutcome::Reject; |
| 76 | } |
| 77 | |
| 78 | if info.interlaced |
| 79 | || info.icc_profile.is_some() |
| 80 | || info.animation_control.is_some() |
| 81 | || info.frame_control.is_some() |
| 82 | { |
| 83 | return PngDecodeOutcome::Fallback; |
| 84 | } |
| 85 | |
| 86 | let (color_type, bit_depth) = reader.output_color_type(); |
| 87 | let Some(row_out_bytes) = (w as usize).checked_mul(4) else { |
| 88 | return PngDecodeOutcome::Reject; |
| 89 | }; |
| 90 | let Some(line_size) = reader.output_line_size(w) else { |
| 91 | return PngDecodeOutcome::Reject; |
| 92 | }; |
| 93 | |
| 94 | match (color_type, bit_depth) { |
| 95 | (png::ColorType::Rgba, png::BitDepth::Eight) => { |
| 96 | let mut rgba = Vec::new(); |
| 97 | if rgba.try_reserve_exact(out_len).is_err() { |
| 98 | return PngDecodeOutcome::Reject; |
| 99 | } |
| 100 | rgba.resize(out_len, 0); |
| 101 | if reader.next_frame(&mut rgba).is_err() { |
| 102 | return PngDecodeOutcome::Reject; |
| 103 | } |
| 104 | PngDecodeOutcome::Decoded(([w, h], rgba, true)) |
| 105 | } |
| 106 | (png::ColorType::Rgb, png::BitDepth::Eight) => { |
| 107 | let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { |
| 108 | let (src_chunks, _) = src.as_chunks::<3>(); |
| 109 | let (dst_chunks, _) = dst.as_chunks_mut::<4>(); |
| 110 | for (&[r, g, b], dst_px) in src_chunks.iter().zip(dst_chunks) { |
| 111 | *dst_px = [r, g, b, 255]; |
| 112 | } |
| 113 | }) else { |
| 114 | return PngDecodeOutcome::Reject; |
| 115 | }; |
| 116 | PngDecodeOutcome::Decoded(([w, h], rgba, false)) |
| 117 | } |
| 118 | (png::ColorType::Grayscale, png::BitDepth::Eight) => { |
| 119 | let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { |
| 120 | let (dst_chunks, _) = dst.as_chunks_mut::<4>(); |
| 121 | for (&g, dst_px) in src.iter().zip(dst_chunks) { |
| 122 | *dst_px = [g, g, g, 255]; |
| 123 | } |
| 124 | }) else { |
| 125 | return PngDecodeOutcome::Reject; |
| 126 | }; |
| 127 | PngDecodeOutcome::Decoded(([w, h], rgba, false)) |
| 128 | } |
| 129 | (png::ColorType::GrayscaleAlpha, png::BitDepth::Eight) => { |
| 130 | let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { |
| 131 | let (src_chunks, _) = src.as_chunks::<2>(); |
| 132 | let (dst_chunks, _) = dst.as_chunks_mut::<4>(); |
| 133 | for (&[g, a], dst_px) in src_chunks.iter().zip(dst_chunks) { |
| 134 | *dst_px = [g, g, g, a]; |
| 135 | } |
| 136 | }) else { |
| 137 | return PngDecodeOutcome::Reject; |
| 138 | }; |
| 139 | PngDecodeOutcome::Decoded(([w, h], rgba, true)) |
| 140 | } |
| 141 | (png::ColorType::Rgba, png::BitDepth::Sixteen) => { |
| 142 | let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { |
| 143 | let (src_chunks, _) = src.as_chunks::<8>(); |
| 144 | let (dst_chunks, _) = dst.as_chunks_mut::<4>(); |
| 145 | for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) { |
| 146 | *dst_px = [ |
| 147 | u16_be_to_u8_rounded(s[0], s[1]), |
| 148 | u16_be_to_u8_rounded(s[2], s[3]), |
| 149 | u16_be_to_u8_rounded(s[4], s[5]), |
| 150 | u16_be_to_u8_rounded(s[6], s[7]), |
| 151 | ]; |
| 152 | } |
| 153 | }) else { |
| 154 | return PngDecodeOutcome::Reject; |
| 155 | }; |
| 156 | PngDecodeOutcome::Decoded(([w, h], rgba, true)) |
| 157 | } |
| 158 | (png::ColorType::Rgb, png::BitDepth::Sixteen) => { |
| 159 | let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { |
| 160 | let (src_chunks, _) = src.as_chunks::<6>(); |
| 161 | let (dst_chunks, _) = dst.as_chunks_mut::<4>(); |
| 162 | for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) { |
| 163 | *dst_px = [ |
| 164 | u16_be_to_u8_rounded(s[0], s[1]), |
| 165 | u16_be_to_u8_rounded(s[2], s[3]), |
| 166 | u16_be_to_u8_rounded(s[4], s[5]), |
| 167 | 255, |
| 168 | ]; |
| 169 | } |
| 170 | }) else { |
| 171 | return PngDecodeOutcome::Reject; |
| 172 | }; |
| 173 | PngDecodeOutcome::Decoded(([w, h], rgba, false)) |
| 174 | } |
| 175 | (png::ColorType::Grayscale, png::BitDepth::Sixteen) => { |
| 176 | let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { |
| 177 | let (src_chunks, _) = src.as_chunks::<2>(); |
| 178 | let (dst_chunks, _) = dst.as_chunks_mut::<4>(); |
| 179 | for (&[hi, lo], dst_px) in src_chunks.iter().zip(dst_chunks) { |
| 180 | let g = u16_be_to_u8_rounded(hi, lo); |
| 181 | *dst_px = [g, g, g, 255]; |
| 182 | } |
| 183 | }) else { |
| 184 | return PngDecodeOutcome::Reject; |
| 185 | }; |
| 186 | PngDecodeOutcome::Decoded(([w, h], rgba, false)) |
| 187 | } |
| 188 | (png::ColorType::GrayscaleAlpha, png::BitDepth::Sixteen) => { |
| 189 | let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| { |
| 190 | let (src_chunks, _) = src.as_chunks::<4>(); |
| 191 | let (dst_chunks, _) = dst.as_chunks_mut::<4>(); |
| 192 | for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) { |
| 193 | let g = u16_be_to_u8_rounded(s[0], s[1]); |
| 194 | *dst_px = [g, g, g, u16_be_to_u8_rounded(s[2], s[3])]; |
| 195 | } |
| 196 | }) else { |
| 197 | return PngDecodeOutcome::Reject; |
| 198 | }; |
| 199 | PngDecodeOutcome::Decoded(([w, h], rgba, true)) |
| 200 | } |
| 201 | _ => PngDecodeOutcome::Fallback, |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | pub(super) fn decode_raster_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> { |
| 206 | match decode_png_bytes(bytes) { |
| 207 | PngDecodeOutcome::Decoded(decoded) => return Some(decoded), |
| 208 | PngDecodeOutcome::Reject => return None, |
| 209 | PngDecodeOutcome::Fallback => {} |
| 210 | } |
| 211 | let dyn_img = image::load_from_memory(bytes).ok()?; |
| 212 | let has_alpha = dyn_img.color().has_alpha(); |
| 213 | let size = [dyn_img.width(), dyn_img.height()]; |
| 214 | let raw = dyn_img.into_rgba8().into_raw(); |
| 215 | Some((size, raw, has_alpha)) |
| 216 | } |
| 217 | |
| 218 | fn open_raster_rgba(path: &Path) -> Option<([u32; 2], Vec<u8>, bool)> { |
| 219 | if let Some(bytes) = virtual_bytes(path) { |
| 220 | return decode_raster_bytes(&bytes); |
| 221 | } |
| 222 | // Read file contents in one contiguous pass to avoid tiny buffered syscalls over SMB/network shares. |
| 223 | match std::fs::read(path) { |
| 224 | Ok(bytes) => return decode_raster_bytes(&bytes), |
| 225 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None, |
| 226 | Err(_) => {} |
| 227 | } |
| 228 | let dyn_img = image::open(path).ok()?; |
| 229 | let has_alpha = dyn_img.color().has_alpha(); |
| 230 | let size = [dyn_img.width(), dyn_img.height()]; |
| 231 | let raw = dyn_img.into_rgba8().into_raw(); |
| 232 | Some((size, raw, has_alpha)) |
| 233 | } |
| 234 | |
| 235 | pub(super) fn decode_raster_image( |
| 236 | path: &Path, |
| 237 | post_multiply: bool, |
| 238 | allow_parallel_premult: bool, |
| 239 | ) -> Option<DecodedImage> { |
| 240 | let (size, mut raw, has_alpha) = open_raster_rgba(path)?; |
| 241 | if post_multiply && has_alpha { |
| 242 | apply_post_multiply_rgba8_parallel(&mut raw, allow_parallel_premult); |
| 243 | } |
| 244 | Some(DecodedImage { |
| 245 | size, |
| 246 | rgba: Arc::new(raw), |
| 247 | rgba_f16: None, |
| 248 | rgba_f32: None, |
| 249 | z_f32: None, |
| 250 | }) |
| 251 | } |