PNG decoding and the still-image API
Browse files at this commit7bceff22ca718dc2fd4a08953183606336c87c20Parent: 9a848b4- feat
- PNG decoding and the still-image API
5 changed files +1134 -0
- Cargo.toml +1 -0
- crates/ec-image/Cargo.toml +17 -0
- crates/ec-image/src/lib.rs +424 -0
- crates/ec-image/src/png.rs +588 -0
- scripts/gen-still-fixtures.sh +104 -0
Cargo.tomlmodified+1 -0
| @@ -15,6 +15,7 @@ ec-core = { path = "crates/ec-core", version = "0.1.0" } | ||
| 15 | 15 | ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" } |
| 16 | 16 | ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" } |
| 17 | 17 | ec-h265-syntax = { path = "crates/ec-h265-syntax", version = "0.1.0" } |
| 18 | +ec-image = { path = "crates/ec-image", version = "0.1.0" } | |
| 18 | 19 | ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" } |
| 19 | 20 | ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" } |
| 20 | 21 | ec-mp3 = { path = "crates/ec-mp3", version = "0.1.0" } |
crates/ec-image/Cargo.tomladded+17 -0
| @@ -0,0 +1,17 @@ | ||
| 1 | +[package] | |
| 2 | +name = "ec-image" | |
| 3 | +description = "Still-image decoding: PNG, JPEG and WebP." | |
| 4 | +version.workspace = true | |
| 5 | +edition.workspace = true | |
| 6 | +license.workspace = true | |
| 7 | +authors.workspace = true | |
| 8 | + | |
| 9 | +[dependencies] | |
| 10 | +ec-core = { workspace = true } | |
| 11 | +ec-inflate = { workspace = true } | |
| 12 | + | |
| 13 | +[dev-dependencies] | |
| 14 | +# The incumbent, as a differential oracle only: every test decodes the same | |
| 15 | +# bytes both ways and compares pixels. Running it is the point; nothing is | |
| 16 | +# copied from it. | |
| 17 | +image = "0.25.10" |
crates/ec-image/src/lib.rsadded+424 -0
| @@ -0,0 +1,424 @@ | ||
| 1 | +//! Still-image decoding: PNG, JPEG and WebP. | |
| 2 | +//! | |
| 3 | +//! One entry point — [`decode`] over bytes, [`open`] over a path — guesses the | |
| 4 | +//! format from the leading bytes and hands back an [`Image`]: dimensions, a | |
| 5 | +//! [`Pixels`] buffer in the file's own colour form, and the [`Metadata`] the | |
| 6 | +//! file declared about it (gamma, sRGB intent, EXIF orientation). | |
| 7 | +//! | |
| 8 | +//! Contracts worth knowing before implementing against this crate: | |
| 9 | +//! | |
| 10 | +//! - Metadata is *parsed and exposed, never applied*. A JPEG that says it was | |
| 11 | +//! shot sideways decodes to the pixels as stored, with | |
| 12 | +//! [`Metadata::orientation`] set; a PNG's gamma is reported, not rendered. | |
| 13 | +//! Rotating or gamma-correcting behind the caller's back would make a | |
| 14 | +//! round-trip through this crate lossy in a way no caller asked for. | |
| 15 | +//! - Sample depth survives: a 16-bit PNG decodes to a 16-bit [`Pixels`] | |
| 16 | +//! variant. [`Image::to_rgb8`] and friends convert on demand. | |
| 17 | +//! - Refusals are [`ec_core::Error::Unsupported`] naming *what* and *why* — | |
| 18 | +//! an animated WebP and a CMYK JPEG each say so rather than producing a | |
| 19 | +//! plausible-looking wrong picture. | |
| 20 | +//! - Truncated or corrupt input is an error, never a panic and never an | |
| 21 | +//! unbounded allocation: [`Limits`] bounds pixel count before any buffer is | |
| 22 | +//! sized from header fields. | |
| 23 | +//! | |
| 24 | +//! No async, no unsafe, no external dependencies beyond the family's own | |
| 25 | +//! [`ec_core`] and [`ec_inflate`]. | |
| 26 | + | |
| 27 | +#![forbid(unsafe_code)] | |
| 28 | +#![warn(missing_docs)] | |
| 29 | +// Coefficient positions, macroblock columns and prediction samples are indices | |
| 30 | +// in every specification these decoders implement; iterating them by index is | |
| 31 | +// what keeps the code readable against the text it comes from. | |
| 32 | +#![allow(clippy::needless_range_loop)] | |
| 33 | + | |
| 34 | +pub mod png; | |
| 35 | + | |
| 36 | +use ec_core::{PixelFormat, Plane, VideoFrame}; | |
| 37 | + | |
| 38 | +// The family's error taxonomy is this crate's too, and a caller that has to | |
| 39 | +// name a decode failure needs it in scope. | |
| 40 | +pub use ec_core::{Error, Result}; | |
| 41 | + | |
| 42 | +/// The formats this crate decodes. | |
| 43 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 44 | +pub enum ImageFormat { | |
| 45 | + /// Portable Network Graphics (W3C PNG, RFC 2083). | |
| 46 | + Png, | |
| 47 | + /// JFIF/EXIF JPEG (ITU-T T.81 baseline and progressive). | |
| 48 | + Jpeg, | |
| 49 | + /// WebP: a RIFF container over VP8 (lossy) or VP8L (lossless). | |
| 50 | + WebP, | |
| 51 | +} | |
| 52 | + | |
| 53 | +impl ImageFormat { | |
| 54 | + /// The format whose signature `data` starts with, if any. | |
| 55 | + /// | |
| 56 | + /// This is what `with_guessed_format` means: content, not file extension. | |
| 57 | + pub fn guess(data: &[u8]) -> Option<ImageFormat> { | |
| 58 | + if data.starts_with(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) { | |
| 59 | + Some(ImageFormat::Png) | |
| 60 | + } else if data.starts_with(&[0xff, 0xd8, 0xff]) { | |
| 61 | + Some(ImageFormat::Jpeg) | |
| 62 | + } else if data.len() >= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP" { | |
| 63 | + Some(ImageFormat::WebP) | |
| 64 | + } else { | |
| 65 | + None | |
| 66 | + } | |
| 67 | + } | |
| 68 | + | |
| 69 | + /// The usual lowercase extension, for diagnostics. | |
| 70 | + pub fn extension(&self) -> &'static str { | |
| 71 | + match self { | |
| 72 | + ImageFormat::Png => "png", | |
| 73 | + ImageFormat::Jpeg => "jpg", | |
| 74 | + ImageFormat::WebP => "webp", | |
| 75 | + } | |
| 76 | + } | |
| 77 | +} | |
| 78 | + | |
| 79 | +/// Bounds applied before any buffer is sized from a header field. | |
| 80 | +/// | |
| 81 | +/// A three-byte dimension field can ask for a 68-gigapixel allocation; this is | |
| 82 | +/// the trust boundary that says no first. The default admits everything the | |
| 83 | +/// formats themselves can express up to 2^28 pixels — comfortably past 8K | |
| 84 | +/// (33 Mpx) and far below what would exhaust a desktop. | |
| 85 | +#[derive(Debug, Clone, Copy)] | |
| 86 | +pub struct Limits { | |
| 87 | + /// Largest `width * height` accepted. | |
| 88 | + pub max_pixels: u64, | |
| 89 | + /// Largest single decompressed buffer accepted, in bytes. | |
| 90 | + pub max_alloc: usize, | |
| 91 | +} | |
| 92 | + | |
| 93 | +impl Default for Limits { | |
| 94 | + fn default() -> Self { | |
| 95 | + Limits { | |
| 96 | + max_pixels: 1 << 28, | |
| 97 | + max_alloc: 1 << 32, | |
| 98 | + } | |
| 99 | + } | |
| 100 | +} | |
| 101 | + | |
| 102 | +impl Limits { | |
| 103 | + /// Check a header's dimensions before they size anything. | |
| 104 | + pub fn check(&self, width: u32, height: u32) -> Result<()> { | |
| 105 | + if width == 0 || height == 0 { | |
| 106 | + return Err(Error::corrupt(format!("{width}x{height} image"))); | |
| 107 | + } | |
| 108 | + let pixels = u64::from(width) * u64::from(height); | |
| 109 | + if pixels > self.max_pixels { | |
| 110 | + return Err(Error::unsupported( | |
| 111 | + format!("{width}x{height} image"), | |
| 112 | + format!("{pixels} pixels is past the {} limit", self.max_pixels), | |
| 113 | + )); | |
| 114 | + } | |
| 115 | + Ok(()) | |
| 116 | + } | |
| 117 | +} | |
| 118 | + | |
| 119 | +/// What a file said about its own pixels, parsed but not applied. | |
| 120 | +#[derive(Debug, Clone, Copy, Default, PartialEq)] | |
| 121 | +pub struct Metadata { | |
| 122 | + /// PNG `gAMA`: the gamma the file was authored at. | |
| 123 | + pub gamma: Option<f64>, | |
| 124 | + /// PNG `sRGB`: rendering intent 0..=3, meaning the file is sRGB. | |
| 125 | + pub srgb_intent: Option<u8>, | |
| 126 | + /// EXIF orientation tag 1..=8, from a JPEG APP1 or a WebP `EXIF` chunk. | |
| 127 | + /// | |
| 128 | + /// Exposed, never applied — the same choice the incumbent `image` crate | |
| 129 | + /// makes, so a caller swapping between them sees the same pixels. | |
| 130 | + pub orientation: Option<u8>, | |
| 131 | +} | |
| 132 | + | |
| 133 | +/// A decoded image's samples, in the file's own colour form. | |
| 134 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 135 | +pub enum Pixels { | |
| 136 | + /// 8-bit grayscale. | |
| 137 | + L8(Vec<u8>), | |
| 138 | + /// 8-bit grayscale + alpha. | |
| 139 | + La8(Vec<u8>), | |
| 140 | + /// 8-bit R,G,B. | |
| 141 | + Rgb8(Vec<u8>), | |
| 142 | + /// 8-bit R,G,B,A. | |
| 143 | + Rgba8(Vec<u8>), | |
| 144 | + /// 16-bit grayscale. | |
| 145 | + L16(Vec<u16>), | |
| 146 | + /// 16-bit grayscale + alpha. | |
| 147 | + La16(Vec<u16>), | |
| 148 | + /// 16-bit R,G,B. | |
| 149 | + Rgb16(Vec<u16>), | |
| 150 | + /// 16-bit R,G,B,A. | |
| 151 | + Rgba16(Vec<u16>), | |
| 152 | +} | |
| 153 | + | |
| 154 | +impl Pixels { | |
| 155 | + /// Samples per pixel. | |
| 156 | + pub fn channels(&self) -> usize { | |
| 157 | + match self { | |
| 158 | + Pixels::L8(_) | Pixels::L16(_) => 1, | |
| 159 | + Pixels::La8(_) | Pixels::La16(_) => 2, | |
| 160 | + Pixels::Rgb8(_) | Pixels::Rgb16(_) => 3, | |
| 161 | + Pixels::Rgba8(_) | Pixels::Rgba16(_) => 4, | |
| 162 | + } | |
| 163 | + } | |
| 164 | + | |
| 165 | + /// Bits per sample: 8 or 16. | |
| 166 | + pub fn bit_depth(&self) -> u8 { | |
| 167 | + match self { | |
| 168 | + Pixels::L8(_) | Pixels::La8(_) | Pixels::Rgb8(_) | Pixels::Rgba8(_) => 8, | |
| 169 | + _ => 16, | |
| 170 | + } | |
| 171 | + } | |
| 172 | + | |
| 173 | + /// True when the samples carry an alpha channel. | |
| 174 | + pub fn has_alpha(&self) -> bool { | |
| 175 | + matches!( | |
| 176 | + self, | |
| 177 | + Pixels::La8(_) | Pixels::Rgba8(_) | Pixels::La16(_) | Pixels::Rgba16(_) | |
| 178 | + ) | |
| 179 | + } | |
| 180 | +} | |
| 181 | + | |
| 182 | +/// A decoded still image. | |
| 183 | +#[derive(Debug, Clone, PartialEq)] | |
| 184 | +pub struct Image { | |
| 185 | + /// Width in pixels. | |
| 186 | + pub width: u32, | |
| 187 | + /// Height in pixels. | |
| 188 | + pub height: u32, | |
| 189 | + /// The samples. | |
| 190 | + pub pixels: Pixels, | |
| 191 | + /// What the file declared about them. | |
| 192 | + pub meta: Metadata, | |
| 193 | +} | |
| 194 | + | |
| 195 | +/// Rounding-correct 16-bit sample down to 8 bits: `round(v * 255 / 65535)`. | |
| 196 | +fn narrow(v: u16) -> u8 { | |
| 197 | + ((u32::from(v) + 128) / 257) as u8 | |
| 198 | +} | |
| 199 | + | |
| 200 | +/// 8-bit sample widened to 16: `v * 65535 / 255`, exact. | |
| 201 | +fn widen(v: u8) -> u16 { | |
| 202 | + u16::from(v) * 257 | |
| 203 | +} | |
| 204 | + | |
| 205 | +impl Image { | |
| 206 | + /// `(width, height)`. | |
| 207 | + pub fn dimensions(&self) -> (u32, u32) { | |
| 208 | + (self.width, self.height) | |
| 209 | + } | |
| 210 | + | |
| 211 | + /// Packed 8-bit R,G,B, dropping any alpha channel. | |
| 212 | + pub fn to_rgb8(&self) -> Vec<u8> { | |
| 213 | + let n = (self.width as usize) * (self.height as usize); | |
| 214 | + let mut out = Vec::with_capacity(n * 3); | |
| 215 | + match &self.pixels { | |
| 216 | + Pixels::L8(d) => d.iter().for_each(|&l| out.extend_from_slice(&[l, l, l])), | |
| 217 | + Pixels::La8(d) => d | |
| 218 | + .chunks_exact(2) | |
| 219 | + .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0]])), | |
| 220 | + Pixels::Rgb8(d) => out.extend_from_slice(d), | |
| 221 | + Pixels::Rgba8(d) => d | |
| 222 | + .chunks_exact(4) | |
| 223 | + .for_each(|p| out.extend_from_slice(&p[..3])), | |
| 224 | + Pixels::L16(d) => d.iter().for_each(|&l| { | |
| 225 | + let l = narrow(l); | |
| 226 | + out.extend_from_slice(&[l, l, l]); | |
| 227 | + }), | |
| 228 | + Pixels::La16(d) => d.chunks_exact(2).for_each(|p| { | |
| 229 | + let l = narrow(p[0]); | |
| 230 | + out.extend_from_slice(&[l, l, l]); | |
| 231 | + }), | |
| 232 | + Pixels::Rgb16(d) => d.iter().for_each(|&s| out.push(narrow(s))), | |
| 233 | + Pixels::Rgba16(d) => d | |
| 234 | + .chunks_exact(4) | |
| 235 | + .for_each(|p| out.extend(p[..3].iter().map(|&s| narrow(s)))), | |
| 236 | + } | |
| 237 | + out | |
| 238 | + } | |
| 239 | + | |
| 240 | + /// Packed 8-bit R,G,B,A; opaque where the source had no alpha. | |
| 241 | + pub fn to_rgba8(&self) -> Vec<u8> { | |
| 242 | + let n = (self.width as usize) * (self.height as usize); | |
| 243 | + let mut out = Vec::with_capacity(n * 4); | |
| 244 | + match &self.pixels { | |
| 245 | + Pixels::L8(d) => d | |
| 246 | + .iter() | |
| 247 | + .for_each(|&l| out.extend_from_slice(&[l, l, l, 255])), | |
| 248 | + Pixels::La8(d) => d | |
| 249 | + .chunks_exact(2) | |
| 250 | + .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0], p[1]])), | |
| 251 | + Pixels::Rgb8(d) => d | |
| 252 | + .chunks_exact(3) | |
| 253 | + .for_each(|p| out.extend_from_slice(&[p[0], p[1], p[2], 255])), | |
| 254 | + Pixels::Rgba8(d) => out.extend_from_slice(d), | |
| 255 | + Pixels::L16(d) => d.iter().for_each(|&l| { | |
| 256 | + let l = narrow(l); | |
| 257 | + out.extend_from_slice(&[l, l, l, 255]); | |
| 258 | + }), | |
| 259 | + Pixels::La16(d) => d.chunks_exact(2).for_each(|p| { | |
| 260 | + let l = narrow(p[0]); | |
| 261 | + out.extend_from_slice(&[l, l, l, narrow(p[1])]); | |
| 262 | + }), | |
| 263 | + Pixels::Rgb16(d) => d.chunks_exact(3).for_each(|p| { | |
| 264 | + out.extend_from_slice(&[narrow(p[0]), narrow(p[1]), narrow(p[2]), 255]); | |
| 265 | + }), | |
| 266 | + Pixels::Rgba16(d) => d.iter().for_each(|&s| out.push(narrow(s))), | |
| 267 | + } | |
| 268 | + out | |
| 269 | + } | |
| 270 | + | |
| 271 | + /// Packed 16-bit R,G,B — 8-bit sources widened exactly (`v * 257`). | |
| 272 | + pub fn to_rgb16(&self) -> Vec<u16> { | |
| 273 | + match &self.pixels { | |
| 274 | + Pixels::Rgb16(d) => d.clone(), | |
| 275 | + Pixels::Rgba16(d) => d.chunks_exact(4).flat_map(|p| p[..3].to_vec()).collect(), | |
| 276 | + Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l]).collect(), | |
| 277 | + Pixels::La16(d) => d.chunks_exact(2).flat_map(|p| [p[0], p[0], p[0]]).collect(), | |
| 278 | + _ => self.to_rgb8().into_iter().map(widen).collect(), | |
| 279 | + } | |
| 280 | + } | |
| 281 | + | |
| 282 | + /// Packed 16-bit R,G,B,A; opaque where the source had no alpha. | |
| 283 | + pub fn to_rgba16(&self) -> Vec<u16> { | |
| 284 | + match &self.pixels { | |
| 285 | + Pixels::Rgba16(d) => d.clone(), | |
| 286 | + Pixels::Rgb16(d) => d | |
| 287 | + .chunks_exact(3) | |
| 288 | + .flat_map(|p| [p[0], p[1], p[2], u16::MAX]) | |
| 289 | + .collect(), | |
| 290 | + Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l, u16::MAX]).collect(), | |
| 291 | + Pixels::La16(d) => d | |
| 292 | + .chunks_exact(2) | |
| 293 | + .flat_map(|p| [p[0], p[0], p[0], p[1]]) | |
| 294 | + .collect(), | |
| 295 | + _ => self.to_rgba8().into_iter().map(widen).collect(), | |
| 296 | + } | |
| 297 | + } | |
| 298 | + | |
| 299 | + /// The image as an [`ec_core::VideoFrame`], packed RGB8 or RGBA8. | |
| 300 | + /// | |
| 301 | + /// The natural bridge for a caller that composes stills and decoded video | |
| 302 | + /// in one pipeline: alpha survives when the file had it, rather than being | |
| 303 | + /// silently dropped on the way to a frame. | |
| 304 | + pub fn to_video_frame(&self) -> Result<VideoFrame> { | |
| 305 | + let (format, data) = if self.pixels.has_alpha() { | |
| 306 | + (PixelFormat::Rgba8, self.to_rgba8()) | |
| 307 | + } else { | |
| 308 | + (PixelFormat::Rgb8, self.to_rgb8()) | |
| 309 | + }; | |
| 310 | + let stride = (self.width as usize) * if self.pixels.has_alpha() { 4 } else { 3 }; | |
| 311 | + VideoFrame::try_new( | |
| 312 | + format, | |
| 313 | + self.width, | |
| 314 | + self.height, | |
| 315 | + vec![Plane::new(data, stride)], | |
| 316 | + ) | |
| 317 | + } | |
| 318 | +} | |
| 319 | + | |
| 320 | +/// Dimensions and format from a header alone — the whole file is not decoded. | |
| 321 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 322 | +pub struct Info { | |
| 323 | + /// Which format the bytes are in. | |
| 324 | + pub format: ImageFormat, | |
| 325 | + /// Width in pixels. | |
| 326 | + pub width: u32, | |
| 327 | + /// Height in pixels. | |
| 328 | + pub height: u32, | |
| 329 | +} | |
| 330 | + | |
| 331 | +/// Decode `data`, guessing the format from its leading bytes. | |
| 332 | +pub fn decode(data: &[u8]) -> Result<Image> { | |
| 333 | + decode_with_limits(data, Limits::default()) | |
| 334 | +} | |
| 335 | + | |
| 336 | +/// [`decode`] with caller-chosen [`Limits`]. | |
| 337 | +pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result<Image> { | |
| 338 | + match ImageFormat::guess(data) { | |
| 339 | + Some(ImageFormat::Png) => png::decode(data, limits), | |
| 340 | + Some(ImageFormat::Jpeg) => Err(Error::unsupported( | |
| 341 | + "JPEG", | |
| 342 | + "the JPEG decoder is the next stage of this crate", | |
| 343 | + )), | |
| 344 | + Some(ImageFormat::WebP) => Err(Error::unsupported( | |
| 345 | + "WebP", | |
| 346 | + "the WebP decoder is a later stage of this crate", | |
| 347 | + )), | |
| 348 | + None => Err(Error::unsupported( | |
| 349 | + "image", | |
| 350 | + "no PNG, JPEG or WebP signature at the start of the data", | |
| 351 | + )), | |
| 352 | + } | |
| 353 | +} | |
| 354 | + | |
| 355 | +/// Dimensions from the header alone, without decoding the pixels. | |
| 356 | +pub fn info(data: &[u8]) -> Result<Info> { | |
| 357 | + match ImageFormat::guess(data) { | |
| 358 | + Some(ImageFormat::Png) => png::info(data), | |
| 359 | + Some(ImageFormat::Jpeg) => Err(Error::unsupported( | |
| 360 | + "JPEG", | |
| 361 | + "the JPEG decoder is the next stage of this crate", | |
| 362 | + )), | |
| 363 | + Some(ImageFormat::WebP) => Err(Error::unsupported( | |
| 364 | + "WebP", | |
| 365 | + "the WebP decoder is a later stage of this crate", | |
| 366 | + )), | |
| 367 | + None => Err(Error::unsupported( | |
| 368 | + "image", | |
| 369 | + "no PNG, JPEG or WebP signature at the start of the data", | |
| 370 | + )), | |
| 371 | + } | |
| 372 | +} | |
| 373 | + | |
| 374 | +/// Read and decode the file at `path`. | |
| 375 | +pub fn open(path: impl AsRef<std::path::Path>) -> Result<Image> { | |
| 376 | + let data = std::fs::read(path).map_err(Error::Io)?; | |
| 377 | + decode(&data) | |
| 378 | +} | |
| 379 | + | |
| 380 | +/// Read the file at `path` and report its header dimensions. | |
| 381 | +pub fn open_info(path: impl AsRef<std::path::Path>) -> Result<Info> { | |
| 382 | + let data = std::fs::read(path).map_err(Error::Io)?; | |
| 383 | + info(&data) | |
| 384 | +} | |
| 385 | + | |
| 386 | +#[cfg(test)] | |
| 387 | +mod tests { | |
| 388 | + use super::*; | |
| 389 | + | |
| 390 | + #[test] | |
| 391 | + fn guess_reads_signatures_not_extensions() { | |
| 392 | + assert_eq!( | |
| 393 | + ImageFormat::guess(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0]), | |
| 394 | + Some(ImageFormat::Png) | |
| 395 | + ); | |
| 396 | + assert_eq!( | |
| 397 | + ImageFormat::guess(&[0xff, 0xd8, 0xff, 0xe0]), | |
| 398 | + Some(ImageFormat::Jpeg) | |
| 399 | + ); | |
| 400 | + let mut webp = b"RIFF\0\0\0\0WEBPVP8 ".to_vec(); | |
| 401 | + webp.push(0); | |
| 402 | + assert_eq!(ImageFormat::guess(&webp), Some(ImageFormat::WebP)); | |
| 403 | + assert_eq!(ImageFormat::guess(b"RIFF\0\0\0\0WAVEfmt "), None); | |
| 404 | + assert_eq!(ImageFormat::guess(b""), None); | |
| 405 | + } | |
| 406 | + | |
| 407 | + #[test] | |
| 408 | + fn sample_conversion_round_trips_through_eight_bits() { | |
| 409 | + for v in 0..=255u8 { | |
| 410 | + assert_eq!(narrow(widen(v)), v, "{v}"); | |
| 411 | + } | |
| 412 | + assert_eq!(narrow(0), 0); | |
| 413 | + assert_eq!(narrow(u16::MAX), 255); | |
| 414 | + assert_eq!(narrow(32768), 128); | |
| 415 | + } | |
| 416 | + | |
| 417 | + #[test] | |
| 418 | + fn limits_refuse_before_allocating() { | |
| 419 | + let limits = Limits::default(); | |
| 420 | + assert!(limits.check(1920, 1080).is_ok()); | |
| 421 | + assert!(limits.check(0, 10).is_err()); | |
| 422 | + assert!(limits.check(100_000, 100_000).is_err()); | |
| 423 | + } | |
| 424 | +} |
crates/ec-image/src/png.rsadded+588 -0
| @@ -0,0 +1,588 @@ | ||
| 1 | +//! PNG decoding (W3C PNG / RFC 2083) over [`ec_inflate`]. | |
| 2 | +//! | |
| 3 | +//! Every critical chunk is honoured: `IHDR`, `PLTE`, `tRNS`, all five filter | |
| 4 | +//! types, all five colour types at every legal bit depth (1/2/4/8/16) and both | |
| 5 | +//! interlace methods. `gAMA` and `sRGB` are parsed into [`Metadata`]; other | |
| 6 | +//! ancillary chunks are skipped by length, which is what "safe to ignore" | |
| 7 | +//! means in a format whose chunk list keeps growing. | |
| 8 | +//! | |
| 9 | +//! Every chunk's CRC is verified. A PNG that fails its own checksum is | |
| 10 | +//! [`Error::Corrupt`], because the alternative — decoding it anyway — turns a | |
| 11 | +//! detectable bit flip into a picture nobody can tell is wrong. | |
| 12 | + | |
| 13 | +use crate::{Image, ImageFormat, Info, Limits, Metadata, Pixels}; | |
| 14 | +use ec_core::{Error, Result}; | |
| 15 | + | |
| 16 | +const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]; | |
| 17 | + | |
| 18 | +/// Adam7: `(x_start, y_start, x_step, y_step)` per pass. | |
| 19 | +const ADAM7: [(u32, u32, u32, u32); 7] = [ | |
| 20 | + (0, 0, 8, 8), | |
| 21 | + (4, 0, 8, 8), | |
| 22 | + (0, 4, 4, 8), | |
| 23 | + (2, 0, 4, 4), | |
| 24 | + (0, 2, 2, 4), | |
| 25 | + (1, 0, 2, 2), | |
| 26 | + (0, 1, 1, 2), | |
| 27 | +]; | |
| 28 | + | |
| 29 | +/// IHDR, the only chunk that must come first. | |
| 30 | +#[derive(Debug, Clone, Copy)] | |
| 31 | +struct Header { | |
| 32 | + width: u32, | |
| 33 | + height: u32, | |
| 34 | + depth: u8, | |
| 35 | + color_type: u8, | |
| 36 | + interlaced: bool, | |
| 37 | +} | |
| 38 | + | |
| 39 | +impl Header { | |
| 40 | + /// Samples per pixel for the colour type (palette indices count as one). | |
| 41 | + fn channels(&self) -> usize { | |
| 42 | + match self.color_type { | |
| 43 | + 0 | 3 => 1, | |
| 44 | + 2 => 3, | |
| 45 | + 4 => 2, | |
| 46 | + _ => 4, | |
| 47 | + } | |
| 48 | + } | |
| 49 | + | |
| 50 | + /// Bytes in one unfiltered scanline of `width` pixels. | |
| 51 | + fn row_bytes(&self, width: u32) -> usize { | |
| 52 | + let bits = (width as usize) * self.channels() * (self.depth as usize); | |
| 53 | + bits.div_ceil(8) | |
| 54 | + } | |
| 55 | + | |
| 56 | + /// Filter unit: bytes per pixel, rounded up, at least one. | |
| 57 | + fn filter_step(&self) -> usize { | |
| 58 | + ((self.channels() * self.depth as usize) / 8).max(1) | |
| 59 | + } | |
| 60 | +} | |
| 61 | + | |
| 62 | +/// CRC-32 (IEEE) as PNG specifies it, table built at compile time. | |
| 63 | +const CRC_TABLE: [u32; 256] = { | |
| 64 | + let mut table = [0u32; 256]; | |
| 65 | + let mut n = 0; | |
| 66 | + while n < 256 { | |
| 67 | + let mut c = n as u32; | |
| 68 | + let mut k = 0; | |
| 69 | + while k < 8 { | |
| 70 | + c = if c & 1 != 0 { | |
| 71 | + 0xedb8_8320 ^ (c >> 1) | |
| 72 | + } else { | |
| 73 | + c >> 1 | |
| 74 | + }; | |
| 75 | + k += 1; | |
| 76 | + } | |
| 77 | + table[n] = c; | |
| 78 | + n += 1; | |
| 79 | + } | |
| 80 | + table | |
| 81 | +}; | |
| 82 | + | |
| 83 | +fn crc32(data: &[u8]) -> u32 { | |
| 84 | + let mut c = 0xffff_ffffu32; | |
| 85 | + for &b in data { | |
| 86 | + c = CRC_TABLE[((c ^ u32::from(b)) & 0xff) as usize] ^ (c >> 8); | |
| 87 | + } | |
| 88 | + c ^ 0xffff_ffff | |
| 89 | +} | |
| 90 | + | |
| 91 | +fn be32(data: &[u8]) -> u32 { | |
| 92 | + u32::from_be_bytes([data[0], data[1], data[2], data[3]]) | |
| 93 | +} | |
| 94 | + | |
| 95 | +/// One chunk: type, payload, and the offset the next chunk starts at. | |
| 96 | +struct Chunk<'a> { | |
| 97 | + kind: [u8; 4], | |
| 98 | + data: &'a [u8], | |
| 99 | + next: usize, | |
| 100 | +} | |
| 101 | + | |
| 102 | +/// Read the chunk at `at`, verifying its CRC. | |
| 103 | +fn chunk(data: &[u8], at: usize) -> Result<Chunk<'_>> { | |
| 104 | + let head = data | |
| 105 | + .get(at..at + 8) | |
| 106 | + .ok_or_else(|| Error::corrupt("PNG: truncated chunk header"))?; | |
| 107 | + let len = be32(head) as usize; | |
| 108 | + let kind = [head[4], head[5], head[6], head[7]]; | |
| 109 | + // The length field is 31-bit by spec; a bigger one is a corrupt file, not | |
| 110 | + // a reason to try to address past the buffer. | |
| 111 | + if len > 0x7fff_ffff { | |
| 112 | + return Err(Error::corrupt(format!("PNG: chunk length {len}"))); | |
| 113 | + } | |
| 114 | + let body = data | |
| 115 | + .get(at + 8..at + 8 + len) | |
| 116 | + .ok_or_else(|| Error::corrupt("PNG: truncated chunk data"))?; | |
| 117 | + let crc = data | |
| 118 | + .get(at + 8 + len..at + 12 + len) | |
| 119 | + .ok_or_else(|| Error::corrupt("PNG: truncated chunk CRC"))?; | |
| 120 | + let want = be32(crc); | |
| 121 | + let got = crc32(&data[at + 4..at + 8 + len]); | |
| 122 | + if want != got { | |
| 123 | + return Err(Error::corrupt(format!( | |
| 124 | + "PNG: {} chunk CRC {got:#010x}, file says {want:#010x}", | |
| 125 | + String::from_utf8_lossy(&kind) | |
| 126 | + ))); | |
| 127 | + } | |
| 128 | + Ok(Chunk { | |
| 129 | + kind, | |
| 130 | + data: body, | |
| 131 | + next: at + 12 + len, | |
| 132 | + }) | |
| 133 | +} | |
| 134 | + | |
| 135 | +fn header(data: &[u8]) -> Result<Header> { | |
| 136 | + if !data.starts_with(&SIGNATURE) { | |
| 137 | + return Err(Error::corrupt("PNG: bad signature")); | |
| 138 | + } | |
| 139 | + let ihdr = chunk(data, 8)?; | |
| 140 | + if &ihdr.kind != b"IHDR" || ihdr.data.len() != 13 { | |
| 141 | + return Err(Error::corrupt("PNG: first chunk is not a 13-byte IHDR")); | |
| 142 | + } | |
| 143 | + let d = ihdr.data; | |
| 144 | + let header = Header { | |
| 145 | + width: be32(d), | |
| 146 | + height: be32(&d[4..]), | |
| 147 | + depth: d[8], | |
| 148 | + color_type: d[9], | |
| 149 | + interlaced: d[12] == 1, | |
| 150 | + }; | |
| 151 | + let depths: &[u8] = match header.color_type { | |
| 152 | + 0 => &[1, 2, 4, 8, 16], | |
| 153 | + 3 => &[1, 2, 4, 8], | |
| 154 | + 2 | 4 | 6 => &[8, 16], | |
| 155 | + other => { | |
| 156 | + return Err(Error::corrupt(format!("PNG: colour type {other}"))); | |
| 157 | + } | |
| 158 | + }; | |
| 159 | + if !depths.contains(&header.depth) { | |
| 160 | + return Err(Error::corrupt(format!( | |
| 161 | + "PNG: bit depth {} with colour type {}", | |
| 162 | + header.depth, header.color_type | |
| 163 | + ))); | |
| 164 | + } | |
| 165 | + if d[10] != 0 { | |
| 166 | + return Err(Error::corrupt(format!("PNG: compression method {}", d[10]))); | |
| 167 | + } | |
| 168 | + if d[11] != 0 { | |
| 169 | + return Err(Error::corrupt(format!("PNG: filter method {}", d[11]))); | |
| 170 | + } | |
| 171 | + if d[12] > 1 { | |
| 172 | + return Err(Error::corrupt(format!("PNG: interlace method {}", d[12]))); | |
| 173 | + } | |
| 174 | + Ok(header) | |
| 175 | +} | |
| 176 | + | |
| 177 | +/// Dimensions from IHDR alone. | |
| 178 | +pub fn info(data: &[u8]) -> Result<Info> { | |
| 179 | + let h = header(data)?; | |
| 180 | + Ok(Info { | |
| 181 | + format: ImageFormat::Png, | |
| 182 | + width: h.width, | |
| 183 | + height: h.height, | |
| 184 | + }) | |
| 185 | +} | |
| 186 | + | |
| 187 | +/// Decode a PNG. | |
| 188 | +pub fn decode(data: &[u8], limits: Limits) -> Result<Image> { | |
| 189 | + let hdr = header(data)?; | |
| 190 | + limits.check(hdr.width, hdr.height)?; | |
| 191 | + | |
| 192 | + let mut palette: Vec<[u8; 3]> = Vec::new(); | |
| 193 | + let mut trns: Option<Vec<u8>> = None; | |
| 194 | + let mut meta = Metadata::default(); | |
| 195 | + let mut idat: Vec<u8> = Vec::new(); | |
| 196 | + let mut at = chunk(data, 8)?.next; | |
| 197 | + let mut saw_end = false; | |
| 198 | + while !saw_end { | |
| 199 | + let c = chunk(data, at)?; | |
| 200 | + at = c.next; | |
| 201 | + match &c.kind { | |
| 202 | + b"PLTE" => { | |
| 203 | + if c.data.len() % 3 != 0 || c.data.len() > 256 * 3 { | |
| 204 | + return Err(Error::corrupt(format!( | |
| 205 | + "PNG: PLTE of {} bytes", | |
| 206 | + c.data.len() | |
| 207 | + ))); | |
| 208 | + } | |
| 209 | + palette = c.data.chunks_exact(3).map(|p| [p[0], p[1], p[2]]).collect(); | |
| 210 | + } | |
| 211 | + b"tRNS" => trns = Some(c.data.to_vec()), | |
| 212 | + b"gAMA" if c.data.len() == 4 => { | |
| 213 | + meta.gamma = Some(f64::from(be32(c.data)) / 100_000.0); | |
| 214 | + } | |
| 215 | + b"sRGB" if c.data.len() == 1 => meta.srgb_intent = Some(c.data[0]), | |
| 216 | + b"IDAT" => idat.extend_from_slice(c.data), | |
| 217 | + b"IEND" => saw_end = true, | |
| 218 | + // Anything else is skipped by its own length: unknown ancillary | |
| 219 | + // chunks are exactly what the chunk layout exists to survive. | |
| 220 | + _ => {} | |
| 221 | + } | |
| 222 | + } | |
| 223 | + if idat.is_empty() { | |
| 224 | + return Err(Error::corrupt("PNG: no IDAT data")); | |
| 225 | + } | |
| 226 | + if hdr.color_type == 3 && palette.is_empty() { | |
| 227 | + return Err(Error::corrupt("PNG: palette image without a PLTE chunk")); | |
| 228 | + } | |
| 229 | + | |
| 230 | + // Exactly how many bytes the passes need; a stream claiming more is | |
| 231 | + // truncated by the limit rather than believed. | |
| 232 | + let expected: usize = passes(&hdr) | |
| 233 | + .iter() | |
| 234 | + .map(|&(w, h)| { | |
| 235 | + if w == 0 || h == 0 { | |
| 236 | + 0 | |
| 237 | + } else { | |
| 238 | + (h as usize) * (hdr.row_bytes(w) + 1) | |
| 239 | + } | |
| 240 | + }) | |
| 241 | + .sum(); | |
| 242 | + if expected > limits.max_alloc { | |
| 243 | + return Err(Error::unsupported( | |
| 244 | + "PNG", | |
| 245 | + format!("{expected} bytes of pixel data is past the allocation limit"), | |
| 246 | + )); | |
| 247 | + } | |
| 248 | + let raw = ec_inflate::inflate_zlib(&idat, expected).map_err(Error::from)?; | |
| 249 | + if raw.len() < expected { | |
| 250 | + return Err(Error::corrupt(format!( | |
| 251 | + "PNG: {} bytes of scanlines, {expected} needed", | |
| 252 | + raw.len() | |
| 253 | + ))); | |
| 254 | + } | |
| 255 | + | |
| 256 | + // Samples are carried at 16 bits internally whatever the file's depth, so | |
| 257 | + // one expansion path serves every colour type; the narrowing back to 8 | |
| 258 | + // happens once, at the end. | |
| 259 | + let channels_out = out_channels(&hdr, &trns); | |
| 260 | + let mut out = vec![0u16; (hdr.width as usize) * (hdr.height as usize) * channels_out]; | |
| 261 | + let mut offset = 0; | |
| 262 | + for (pass, &(pw, ph)) in passes(&hdr).iter().enumerate() { | |
| 263 | + if pw == 0 || ph == 0 { | |
| 264 | + continue; | |
| 265 | + } | |
| 266 | + let row_bytes = hdr.row_bytes(pw); | |
| 267 | + let step = hdr.filter_step(); | |
| 268 | + let mut previous = vec![0u8; row_bytes]; | |
| 269 | + let mut current = vec![0u8; row_bytes]; | |
| 270 | + let (x0, y0, dx, dy) = if hdr.interlaced { | |
| 271 | + ADAM7[pass] | |
| 272 | + } else { | |
| 273 | + (0, 0, 1, 1) | |
| 274 | + }; | |
| 275 | + for row in 0..ph { | |
| 276 | + let start = offset + (row as usize) * (row_bytes + 1); | |
| 277 | + let filter = raw[start]; | |
| 278 | + current.copy_from_slice(&raw[start + 1..start + 1 + row_bytes]); | |
| 279 | + unfilter(filter, step, &previous, &mut current)?; | |
| 280 | + let y = y0 + row * dy; | |
| 281 | + expand_row( | |
| 282 | + ¤t, | |
| 283 | + pw, | |
| 284 | + &hdr, | |
| 285 | + &palette, | |
| 286 | + trns.as_deref(), | |
| 287 | + channels_out, | |
| 288 | + |px, sample| { | |
| 289 | + let x = x0 + px * dx; | |
| 290 | + let base = ((y as usize) * (hdr.width as usize) + x as usize) * channels_out; | |
| 291 | + out[base..base + channels_out].copy_from_slice(sample); | |
| 292 | + }, | |
| 293 | + )?; | |
| 294 | + std::mem::swap(&mut previous, &mut current); | |
| 295 | + } | |
| 296 | + offset += (ph as usize) * (row_bytes + 1); | |
| 297 | + } | |
| 298 | + | |
| 299 | + let pixels = if hdr.depth == 16 { | |
| 300 | + match channels_out { | |
| 301 | + 1 => Pixels::L16(out), | |
| 302 | + 2 => Pixels::La16(out), | |
| 303 | + 3 => Pixels::Rgb16(out), | |
| 304 | + _ => Pixels::Rgba16(out), | |
| 305 | + } | |
| 306 | + } else { | |
| 307 | + let bytes: Vec<u8> = out.into_iter().map(|s| s as u8).collect(); | |
| 308 | + match channels_out { | |
| 309 | + 1 => Pixels::L8(bytes), | |
| 310 | + 2 => Pixels::La8(bytes), | |
| 311 | + 3 => Pixels::Rgb8(bytes), | |
| 312 | + _ => Pixels::Rgba8(bytes), | |
| 313 | + } | |
| 314 | + }; | |
| 315 | + Ok(Image { | |
| 316 | + width: hdr.width, | |
| 317 | + height: hdr.height, | |
| 318 | + pixels, | |
| 319 | + meta, | |
| 320 | + }) | |
| 321 | +} | |
| 322 | + | |
| 323 | +/// Channels the decoded image ends up with: a palette becomes RGB(A), and a | |
| 324 | +/// `tRNS` chunk adds the alpha channel the colour type lacks. | |
| 325 | +fn out_channels(hdr: &Header, trns: &Option<Vec<u8>>) -> usize { | |
| 326 | + match hdr.color_type { | |
| 327 | + 0 => 1 + usize::from(trns.is_some()), | |
| 328 | + 2 => 3 + usize::from(trns.is_some()), | |
| 329 | + 3 => 3 + usize::from(trns.is_some()), | |
| 330 | + 4 => 2, | |
| 331 | + _ => 4, | |
| 332 | + } | |
| 333 | +} | |
| 334 | + | |
| 335 | +/// `(width, height)` of each pass — one entry for a non-interlaced image. | |
| 336 | +fn passes(hdr: &Header) -> Vec<(u32, u32)> { | |
| 337 | + if !hdr.interlaced { | |
| 338 | + return vec![(hdr.width, hdr.height)]; | |
| 339 | + } | |
| 340 | + ADAM7 | |
| 341 | + .iter() | |
| 342 | + .map(|&(x0, y0, dx, dy)| { | |
| 343 | + ( | |
| 344 | + hdr.width.saturating_sub(x0).div_ceil(dx), | |
| 345 | + hdr.height.saturating_sub(y0).div_ceil(dy), | |
| 346 | + ) | |
| 347 | + }) | |
| 348 | + .collect() | |
| 349 | +} | |
| 350 | + | |
| 351 | +/// Reverse one scanline's filter in place. | |
| 352 | +fn unfilter(filter: u8, step: usize, prev: &[u8], row: &mut [u8]) -> Result<()> { | |
| 353 | + match filter { | |
| 354 | + 0 => {} | |
| 355 | + 1 => { | |
| 356 | + for i in step..row.len() { | |
| 357 | + row[i] = row[i].wrapping_add(row[i - step]); | |
| 358 | + } | |
| 359 | + } | |
| 360 | + 2 => { | |
| 361 | + for i in 0..row.len() { | |
| 362 | + row[i] = row[i].wrapping_add(prev[i]); | |
| 363 | + } | |
| 364 | + } | |
| 365 | + 3 => { | |
| 366 | + for i in 0..row.len() { | |
| 367 | + let left = if i >= step { | |
| 368 | + u16::from(row[i - step]) | |
| 369 | + } else { | |
| 370 | + 0 | |
| 371 | + }; | |
| 372 | + let up = u16::from(prev[i]); | |
| 373 | + row[i] = row[i].wrapping_add(((left + up) / 2) as u8); | |
| 374 | + } | |
| 375 | + } | |
| 376 | + 4 => { | |
| 377 | + for i in 0..row.len() { | |
| 378 | + let (a, c) = if i >= step { | |
| 379 | + (i32::from(row[i - step]), i32::from(prev[i - step])) | |
| 380 | + } else { | |
| 381 | + (0, 0) | |
| 382 | + }; | |
| 383 | + let b = i32::from(prev[i]); | |
| 384 | + let p = a + b - c; | |
| 385 | + let (pa, pb, pc) = ((p - a).abs(), (p - b).abs(), (p - c).abs()); | |
| 386 | + let pred = if pa <= pb && pa <= pc { | |
| 387 | + a | |
| 388 | + } else if pb <= pc { | |
| 389 | + b | |
| 390 | + } else { | |
| 391 | + c | |
| 392 | + }; | |
| 393 | + row[i] = row[i].wrapping_add(pred as u8); | |
| 394 | + } | |
| 395 | + } | |
| 396 | + other => return Err(Error::corrupt(format!("PNG: filter type {other}"))), | |
| 397 | + } | |
| 398 | + Ok(()) | |
| 399 | +} | |
| 400 | + | |
| 401 | +/// Pull one pixel's raw samples out of a packed scanline. | |
| 402 | +fn raw_sample(row: &[u8], depth: u8, index: usize) -> u16 { | |
| 403 | + match depth { | |
| 404 | + 16 => u16::from_be_bytes([row[index * 2], row[index * 2 + 1]]), | |
| 405 | + 8 => u16::from(row[index]), | |
| 406 | + _ => { | |
| 407 | + let per_byte = 8 / depth as usize; | |
| 408 | + let byte = row[index / per_byte]; | |
| 409 | + let shift = 8 - depth as usize * (index % per_byte + 1); | |
| 410 | + u16::from((byte >> shift) & ((1u16 << depth) - 1) as u8) | |
| 411 | + } | |
| 412 | + } | |
| 413 | +} | |
| 414 | + | |
| 415 | +/// Expand one unfiltered scanline into per-pixel output samples. | |
| 416 | +/// | |
| 417 | +/// `emit` places pixel `px` of this pass; interlacing is entirely the caller's | |
| 418 | +/// business, which keeps one expansion path serving both layouts. | |
| 419 | +fn expand_row( | |
| 420 | + row: &[u8], | |
| 421 | + width: u32, | |
| 422 | + hdr: &Header, | |
| 423 | + palette: &[[u8; 3]], | |
| 424 | + trns: Option<&[u8]>, | |
| 425 | + channels_out: usize, | |
| 426 | + mut emit: impl FnMut(u32, &[u16]), | |
| 427 | +) -> Result<()> { | |
| 428 | + // Sub-8-bit greyscale is scaled to the full range, so a 1-bit "1" is white | |
| 429 | + // rather than a nearly black 1/255. | |
| 430 | + let max = ((1u32 << hdr.depth) - 1) as u16; | |
| 431 | + let scale = |v: u16| -> u16 { | |
| 432 | + if hdr.depth == 16 || hdr.depth == 8 { | |
| 433 | + v | |
| 434 | + } else { | |
| 435 | + ((u32::from(v) * 255) / u32::from(max)) as u16 | |
| 436 | + } | |
| 437 | + }; | |
| 438 | + let mut sample = [0u16; 4]; | |
| 439 | + for px in 0..width { | |
| 440 | + let base = (px as usize) * hdr.channels(); | |
| 441 | + match hdr.color_type { | |
| 442 | + 0 => { | |
| 443 | + let g = raw_sample(row, hdr.depth, base); | |
| 444 | + sample[0] = scale(g); | |
| 445 | + if channels_out == 2 { | |
| 446 | + let key = trns | |
| 447 | + .and_then(|t| t.get(..2)) | |
| 448 | + .map(|t| u16::from_be_bytes([t[0], t[1]])); | |
| 449 | + sample[1] = if Some(g) == key { | |
| 450 | + 0 | |
| 451 | + } else { | |
| 452 | + max_for(hdr.depth) | |
| 453 | + }; | |
| 454 | + } | |
| 455 | + } | |
| 456 | + 2 => { | |
| 457 | + for c in 0..3 { | |
| 458 | + sample[c] = raw_sample(row, hdr.depth, base + c); | |
| 459 | + } | |
| 460 | + if channels_out == 4 { | |
| 461 | + let key = trns.and_then(|t| t.get(..6)).map(|t| { | |
| 462 | + [ | |
| 463 | + u16::from_be_bytes([t[0], t[1]]), | |
| 464 | + u16::from_be_bytes([t[2], t[3]]), | |
| 465 | + u16::from_be_bytes([t[4], t[5]]), | |
| 466 | + ] | |
| 467 | + }); | |
| 468 | + sample[3] = if key == Some([sample[0], sample[1], sample[2]]) { | |
| 469 | + 0 | |
| 470 | + } else { | |
| 471 | + max_for(hdr.depth) | |
| 472 | + }; | |
| 473 | + } | |
| 474 | + } | |
| 475 | + 3 => { | |
| 476 | + let index = raw_sample(row, hdr.depth, base) as usize; | |
| 477 | + let entry = palette.get(index).ok_or_else(|| { | |
| 478 | + Error::corrupt(format!( | |
| 479 | + "PNG: palette index {index} in a {}-entry PLTE", | |
| 480 | + palette.len() | |
| 481 | + )) | |
| 482 | + })?; | |
| 483 | + sample[0] = u16::from(entry[0]); | |
| 484 | + sample[1] = u16::from(entry[1]); | |
| 485 | + sample[2] = u16::from(entry[2]); | |
| 486 | + if channels_out == 4 { | |
| 487 | + sample[3] = u16::from(trns.and_then(|t| t.get(index)).copied().unwrap_or(255)); | |
| 488 | + } | |
| 489 | + } | |
| 490 | + 4 => { | |
| 491 | + sample[0] = raw_sample(row, hdr.depth, base); | |
| 492 | + sample[1] = raw_sample(row, hdr.depth, base + 1); | |
| 493 | + } | |
| 494 | + _ => { | |
| 495 | + for c in 0..4 { | |
| 496 | + sample[c] = raw_sample(row, hdr.depth, base + c); | |
| 497 | + } | |
| 498 | + } | |
| 499 | + } | |
| 500 | + emit(px, &sample[..channels_out]); | |
| 501 | + } | |
| 502 | + Ok(()) | |
| 503 | +} | |
| 504 | + | |
| 505 | +/// Fully opaque, at the depth the output carries. | |
| 506 | +fn max_for(depth: u8) -> u16 { | |
| 507 | + if depth == 16 { u16::MAX } else { 255 } | |
| 508 | +} | |
| 509 | + | |
| 510 | +#[cfg(test)] | |
| 511 | +mod tests { | |
| 512 | + use super::*; | |
| 513 | + | |
| 514 | + #[test] | |
| 515 | + fn crc_matches_the_known_iend_value() { | |
| 516 | + // IEND is a fixed, empty chunk; its CRC is the same in every PNG ever | |
| 517 | + // written, which makes it the one checksum worth pinning by hand. | |
| 518 | + assert_eq!(crc32(b"IEND"), 0xae42_6082); | |
| 519 | + } | |
| 520 | + | |
| 521 | + #[test] | |
| 522 | + fn paeth_prefers_the_nearest_predictor() { | |
| 523 | + let prev = [10u8, 200]; | |
| 524 | + let mut row = [0u8, 0]; | |
| 525 | + unfilter(4, 1, &prev, &mut row).unwrap(); | |
| 526 | + assert_eq!(row, [10, 200]); | |
| 527 | + } | |
| 528 | + | |
| 529 | + #[test] | |
| 530 | + fn adam7_pass_sizes_cover_every_pixel() { | |
| 531 | + for (w, h) in [(1u32, 1u32), (7, 5), (16, 16), (33, 17)] { | |
| 532 | + let hdr = Header { | |
| 533 | + width: w, | |
| 534 | + height: h, | |
| 535 | + depth: 8, | |
| 536 | + color_type: 2, | |
| 537 | + interlaced: true, | |
| 538 | + }; | |
| 539 | + let total: u32 = passes(&hdr).iter().map(|&(pw, ph)| pw * ph).sum(); | |
| 540 | + assert_eq!(total, w * h, "{w}x{h}"); | |
| 541 | + } | |
| 542 | + } | |
| 543 | + | |
| 544 | + /// A 1x1 white 8-bit greyscale PNG, built here rather than checked in: the | |
| 545 | + /// zlib payload is a single stored DEFLATE block, so no encoder is needed. | |
| 546 | + fn tiny_png() -> Vec<u8> { | |
| 547 | + fn push_chunk(out: &mut Vec<u8>, kind: &[u8; 4], body: &[u8]) { | |
| 548 | + out.extend_from_slice(&(body.len() as u32).to_be_bytes()); | |
| 549 | + let start = out.len(); | |
| 550 | + out.extend_from_slice(kind); | |
| 551 | + out.extend_from_slice(body); | |
| 552 | + let crc = crc32(&out[start..]); | |
| 553 | + out.extend_from_slice(&crc.to_be_bytes()); | |
| 554 | + } | |
| 555 | + let scanline = [0u8, 0xff]; // filter None, one white sample | |
| 556 | + let mut zlib = vec![0x78, 0x01, 0x01, 0x02, 0x00, 0xfd, 0xff]; | |
| 557 | + zlib.extend_from_slice(&scanline); | |
| 558 | + let (mut a, mut b) = (1u32, 0u32); | |
| 559 | + for &byte in &scanline { | |
| 560 | + a = (a + u32::from(byte)) % 65521; | |
| 561 | + b = (b + a) % 65521; | |
| 562 | + } | |
| 563 | + zlib.extend_from_slice(&((b << 16) | a).to_be_bytes()); | |
| 564 | + | |
| 565 | + let mut png = SIGNATURE.to_vec(); | |
| 566 | + let mut ihdr = Vec::new(); | |
| 567 | + ihdr.extend_from_slice(&1u32.to_be_bytes()); | |
| 568 | + ihdr.extend_from_slice(&1u32.to_be_bytes()); | |
| 569 | + ihdr.extend_from_slice(&[8, 0, 0, 0, 0]); | |
| 570 | + push_chunk(&mut png, b"IHDR", &ihdr); | |
| 571 | + push_chunk(&mut png, b"IDAT", &zlib); | |
| 572 | + push_chunk(&mut png, b"IEND", &[]); | |
| 573 | + png | |
| 574 | + } | |
| 575 | + | |
| 576 | + #[test] | |
| 577 | + fn a_one_pixel_png_decodes_and_a_bad_crc_does_not() { | |
| 578 | + let png = tiny_png(); | |
| 579 | + let img = decode(&png, Limits::default()).expect("the hand-built PNG"); | |
| 580 | + assert_eq!(img.dimensions(), (1, 1)); | |
| 581 | + assert_eq!(img.pixels, Pixels::L8(vec![255])); | |
| 582 | + | |
| 583 | + let mut broken = png.clone(); | |
| 584 | + let last = broken.len() - 1; | |
| 585 | + broken[last] ^= 0xff; | |
| 586 | + assert!(decode(&broken, Limits::default()).is_err(), "bad IEND CRC"); | |
| 587 | + } | |
| 588 | +} |
scripts/gen-still-fixtures.shadded+104 -0
| @@ -0,0 +1,104 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# Still-image fixtures for ec-image's differential tests: every PNG colour | |
| 3 | +# type and bit depth, both JPEG processes at each chroma layout, and both WebP | |
| 4 | +# bitstreams with and without alpha. | |
| 5 | +# | |
| 6 | +# The corpus is generated rather than committed, so the repository stays free | |
| 7 | +# of binaries and every machine can rebuild it: ImageMagick writes the PNG and | |
| 8 | +# JPEG variants, ffmpeg the WebP ones. | |
| 9 | +set -euo pipefail | |
| 10 | + | |
| 11 | +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" | |
| 12 | +out="$root/fixtures/stills" | |
| 13 | +mkdir -p "$out" | |
| 14 | + | |
| 15 | +need() { | |
| 16 | + command -v "$1" >/dev/null || { echo "missing: $1" >&2; exit 1; } | |
| 17 | +} | |
| 18 | +need magick | |
| 19 | +need ffmpeg | |
| 20 | + | |
| 21 | +# Source pictures: one with smooth and hard content at even dimensions, one at | |
| 22 | +# odd dimensions (chroma subsampling and Adam7 both round there), and one with | |
| 23 | +# a real alpha channel. | |
| 24 | +# Seeded, so the corpus is byte-identical on every machine and a differential | |
| 25 | +# bar measured today still means the same thing tomorrow. | |
| 26 | +magick -seed 1234 -size 320x240 plasma:fractal -blur 0x1 \ | |
| 27 | + -fill white -stroke black -draw "rectangle 20,20 80,60" \ | |
| 28 | + -draw "line 0,239 319,0" "$out/source.png" | |
| 29 | +magick "$out/source.png" -resize 61x47! "$out/source-odd.png" | |
| 30 | +magick "$out/source.png" -alpha set -channel A \ | |
| 31 | + -fx "i/w" +channel "$out/source-alpha.png" | |
| 32 | + | |
| 33 | +# --- PNG: every colour type, every bit depth, both interlace methods -------- | |
| 34 | +magick "$out/source.png" -define png:color-type=2 -depth 8 "$out/rgb8.png" | |
| 35 | +magick "$out/source-alpha.png" -define png:color-type=6 -depth 8 "$out/rgba8.png" | |
| 36 | +magick "$out/source.png" -colorspace Gray -define png:color-type=0 -depth 8 "$out/gray8.png" | |
| 37 | +magick "$out/source-alpha.png" -colorspace Gray -define png:color-type=4 -depth 8 "$out/graya8.png" | |
| 38 | +magick "$out/source.png" -define png:color-type=2 -depth 16 "$out/rgb16.png" | |
| 39 | +magick "$out/source-alpha.png" -define png:color-type=6 -depth 16 "$out/rgba16.png" | |
| 40 | +magick "$out/source.png" -colorspace Gray -define png:color-type=0 -depth 16 "$out/gray16.png" | |
| 41 | +magick "$out/source.png" -colors 256 -define png:color-type=3 "$out/palette8.png" | |
| 42 | +magick "$out/source.png" -colors 16 -define png:color-type=3 -define png:bit-depth=4 "$out/palette4.png" | |
| 43 | +magick "$out/source.png" -colors 3 -define png:color-type=3 -define png:bit-depth=2 "$out/palette2.png" | |
| 44 | +magick "$out/source.png" -monochrome -define png:color-type=3 -define png:bit-depth=1 "$out/palette1.png" | |
| 45 | +magick "$out/source.png" -colorspace Gray -depth 4 -define png:color-type=0 -define png:bit-depth=4 "$out/gray4.png" | |
| 46 | +magick "$out/source.png" -colorspace Gray -depth 2 -define png:color-type=0 -define png:bit-depth=2 "$out/gray2.png" | |
| 47 | +magick "$out/source.png" -colorspace Gray -threshold 50% -define png:color-type=0 -define png:bit-depth=1 "$out/gray1.png" | |
| 48 | +magick "$out/source.png" -interlace PNG -define png:color-type=2 "$out/interlaced-rgb8.png" | |
| 49 | +magick "$out/source-alpha.png" -interlace PNG -define png:color-type=6 -depth 16 "$out/interlaced-rgba16.png" | |
| 50 | +magick "$out/source.png" -colors 64 -interlace PNG -define png:color-type=3 "$out/interlaced-palette.png" | |
| 51 | +magick "$out/source-odd.png" -define png:color-type=2 "$out/odd-rgb8.png" | |
| 52 | +magick "$out/source-odd.png" -interlace PNG -define png:color-type=2 "$out/odd-interlaced.png" | |
| 53 | +# Palette with a transparent entry, and a colour-keyed truecolour image. | |
| 54 | +magick "$out/source-alpha.png" -colors 32 PNG8:"$out/trns-palette.png" | |
| 55 | +magick "$out/source.png" -define png:color-type=2 -transparent white "$out/trns-rgb.png" || true | |
| 56 | +magick "$out/source.png" -colorspace Gray -depth 8 -transparent black \ | |
| 57 | + -define png:color-type=0 "$out/trns-gray.png" || true | |
| 58 | + | |
| 59 | +# --- JPEG: both processes, every chroma layout, restarts, EXIF ------------- | |
| 60 | +magick "$out/source.png" -quality 90 -sampling-factor 1x1 "$out/baseline-444.jpg" | |
| 61 | +magick "$out/source.png" -quality 90 -sampling-factor 2x1 "$out/baseline-422.jpg" | |
| 62 | +magick "$out/source.png" -quality 90 -sampling-factor 2x2 "$out/baseline-420.jpg" | |
| 63 | +magick "$out/source.png" -quality 50 -sampling-factor 2x2 "$out/baseline-420-q50.jpg" | |
| 64 | +magick "$out/source.png" -quality 90 -sampling-factor 2x2 -interlace JPEG "$out/progressive-420.jpg" | |
| 65 | +magick "$out/source.png" -quality 90 -sampling-factor 1x1 -interlace JPEG "$out/progressive-444.jpg" | |
| 66 | +magick "$out/source.png" -colorspace Gray -quality 90 "$out/gray.jpg" | |
| 67 | +magick "$out/source.png" -quality 90 -sampling-factor 2x2 \ | |
| 68 | + -define jpeg:restart-interval=4 "$out/restart-420.jpg" | |
| 69 | +magick "$out/source-odd.png" -quality 90 -sampling-factor 2x2 "$out/odd-420.jpg" | |
| 70 | +magick "$out/source-odd.png" -quality 90 -sampling-factor 2x1 "$out/odd-422.jpg" | |
| 71 | + | |
| 72 | +# --- WebP: lossy and lossless, with and without alpha ---------------------- | |
| 73 | +ffmpeg -loglevel error -y -i "$out/source.png" -c:v libwebp -lossless 0 -quality 80 \ | |
| 74 | + "$out/lossy.webp" | |
| 75 | +ffmpeg -loglevel error -y -i "$out/source.png" -c:v libwebp -lossless 0 -quality 40 \ | |
| 76 | + "$out/lossy-q40.webp" | |
| 77 | +ffmpeg -loglevel error -y -i "$out/source.png" -c:v libwebp -lossless 1 "$out/lossless.webp" | |
| 78 | +ffmpeg -loglevel error -y -i "$out/source-alpha.png" -c:v libwebp -lossless 1 \ | |
| 79 | + "$out/lossless-alpha.webp" | |
| 80 | +ffmpeg -loglevel error -y -i "$out/source-alpha.png" -c:v libwebp -lossless 0 -quality 80 \ | |
| 81 | + "$out/lossy-alpha.webp" | |
| 82 | +ffmpeg -loglevel error -y -i "$out/source-odd.png" -c:v libwebp -lossless 0 -quality 80 \ | |
| 83 | + "$out/odd-lossy.webp" | |
| 84 | +ffmpeg -loglevel error -y -i "$out/source-odd.png" -c:v libwebp -lossless 1 "$out/odd-lossless.webp" | |
| 85 | +# A palette-friendly picture, so the lossless colour-indexing transform is | |
| 86 | +# exercised rather than only the predictor one. | |
| 87 | +magick "$out/source.png" -colors 8 "$out/source-flat.png" | |
| 88 | +ffmpeg -loglevel error -y -i "$out/source-flat.png" -c:v libwebp -lossless 1 \ | |
| 89 | + "$out/lossless-palette.webp" | |
| 90 | +# An animation, which the decoder must refuse by name rather than decode. | |
| 91 | +# ffmpeg's libwebp_anim silently writes a single still here, so ImageMagick | |
| 92 | +# writes this one: its output really does carry ANIM/ANMF chunks. | |
| 93 | +magick -delay 10 "$out/source.png" "$out/source-flat.png" "$out/source-odd.png" \ | |
| 94 | + -loop 0 "$out/animated.webp" | |
| 95 | + | |
| 96 | +# Small versions of each format, for the fuzz sweep: ten thousand mutations | |
| 97 | +# per format is only affordable on a picture that decodes in microseconds. | |
| 98 | +magick "$out/source.png" -resize 32x24! "$out/tiny.png" | |
| 99 | +magick "$out/tiny.png" -quality 80 -sampling-factor 2x2 "$out/tiny.jpg" | |
| 100 | +ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 0 -quality 75 \ | |
| 101 | + "$out/tiny-lossy.webp" | |
| 102 | +ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 1 "$out/tiny-lossless.webp" | |
| 103 | + | |
| 104 | +echo "wrote $(ls "$out" | wc -l) files to $out" |