From 7bceff22ca718dc2fd4a08953183606336c87c20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 13:01:10 +0300 Subject: [PATCH] feat(image): PNG decoding and the still-image API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ec-image decodes stills for the engine's placed-picture path. This first stage is the shared API — format guessing from content, a Pixels buffer in the file's own colour form, parsed-but-unapplied metadata, and pixel limits checked before any buffer is sized from a header — plus the PNG decoder over ec-inflate. Every colour type at every legal bit depth, all five filter types, Adam7 interlace, palette and colour-key transparency, gamma and sRGB exposed, ancillary chunks skipped by length, and every chunk CRC verified: a PNG that fails its own checksum is refused rather than decoded into a picture nobody can tell is wrong. scripts/gen-still-fixtures.sh generates the seeded corpus the later stages measure against; the fixtures themselves stay out of the repository. --- Cargo.toml | 1 + crates/ec-image/Cargo.toml | 17 + crates/ec-image/src/lib.rs | 424 ++++++++++++++++++++++++ crates/ec-image/src/png.rs | 588 ++++++++++++++++++++++++++++++++++ scripts/gen-still-fixtures.sh | 104 ++++++ 5 files changed, 1134 insertions(+) create mode 100644 crates/ec-image/Cargo.toml create mode 100644 crates/ec-image/src/lib.rs create mode 100644 crates/ec-image/src/png.rs create mode 100755 scripts/gen-still-fixtures.sh diff --git a/Cargo.toml b/Cargo.toml index d17fe754..5f29fb79 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ ec-core = { path = "crates/ec-core", version = "0.1.0" } ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" } ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" } ec-h265-syntax = { path = "crates/ec-h265-syntax", version = "0.1.0" } +ec-image = { path = "crates/ec-image", version = "0.1.0" } ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" } ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" } ec-mp3 = { path = "crates/ec-mp3", version = "0.1.0" } diff --git a/crates/ec-image/Cargo.toml b/crates/ec-image/Cargo.toml new file mode 100644 index 00000000..6222bfcb --- /dev/null +++ b/crates/ec-image/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "ec-image" +description = "Still-image decoding: PNG, JPEG and WebP." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core = { workspace = true } +ec-inflate = { workspace = true } + +[dev-dependencies] +# The incumbent, as a differential oracle only: every test decodes the same +# bytes both ways and compares pixels. Running it is the point; nothing is +# copied from it. +image = "0.25.10" diff --git a/crates/ec-image/src/lib.rs b/crates/ec-image/src/lib.rs new file mode 100644 index 00000000..53fa12f2 --- /dev/null +++ b/crates/ec-image/src/lib.rs @@ -0,0 +1,424 @@ +//! Still-image decoding: PNG, JPEG and WebP. +//! +//! One entry point — [`decode`] over bytes, [`open`] over a path — guesses the +//! format from the leading bytes and hands back an [`Image`]: dimensions, a +//! [`Pixels`] buffer in the file's own colour form, and the [`Metadata`] the +//! file declared about it (gamma, sRGB intent, EXIF orientation). +//! +//! Contracts worth knowing before implementing against this crate: +//! +//! - Metadata is *parsed and exposed, never applied*. A JPEG that says it was +//! shot sideways decodes to the pixels as stored, with +//! [`Metadata::orientation`] set; a PNG's gamma is reported, not rendered. +//! Rotating or gamma-correcting behind the caller's back would make a +//! round-trip through this crate lossy in a way no caller asked for. +//! - Sample depth survives: a 16-bit PNG decodes to a 16-bit [`Pixels`] +//! variant. [`Image::to_rgb8`] and friends convert on demand. +//! - Refusals are [`ec_core::Error::Unsupported`] naming *what* and *why* — +//! an animated WebP and a CMYK JPEG each say so rather than producing a +//! plausible-looking wrong picture. +//! - Truncated or corrupt input is an error, never a panic and never an +//! unbounded allocation: [`Limits`] bounds pixel count before any buffer is +//! sized from header fields. +//! +//! No async, no unsafe, no external dependencies beyond the family's own +//! [`ec_core`] and [`ec_inflate`]. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] +// Coefficient positions, macroblock columns and prediction samples are indices +// in every specification these decoders implement; iterating them by index is +// what keeps the code readable against the text it comes from. +#![allow(clippy::needless_range_loop)] + +pub mod png; + +use ec_core::{PixelFormat, Plane, VideoFrame}; + +// The family's error taxonomy is this crate's too, and a caller that has to +// name a decode failure needs it in scope. +pub use ec_core::{Error, Result}; + +/// The formats this crate decodes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ImageFormat { + /// Portable Network Graphics (W3C PNG, RFC 2083). + Png, + /// JFIF/EXIF JPEG (ITU-T T.81 baseline and progressive). + Jpeg, + /// WebP: a RIFF container over VP8 (lossy) or VP8L (lossless). + WebP, +} + +impl ImageFormat { + /// The format whose signature `data` starts with, if any. + /// + /// This is what `with_guessed_format` means: content, not file extension. + pub fn guess(data: &[u8]) -> Option { + if data.starts_with(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) { + Some(ImageFormat::Png) + } else if data.starts_with(&[0xff, 0xd8, 0xff]) { + Some(ImageFormat::Jpeg) + } else if data.len() >= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP" { + Some(ImageFormat::WebP) + } else { + None + } + } + + /// The usual lowercase extension, for diagnostics. + pub fn extension(&self) -> &'static str { + match self { + ImageFormat::Png => "png", + ImageFormat::Jpeg => "jpg", + ImageFormat::WebP => "webp", + } + } +} + +/// Bounds applied before any buffer is sized from a header field. +/// +/// A three-byte dimension field can ask for a 68-gigapixel allocation; this is +/// the trust boundary that says no first. The default admits everything the +/// formats themselves can express up to 2^28 pixels — comfortably past 8K +/// (33 Mpx) and far below what would exhaust a desktop. +#[derive(Debug, Clone, Copy)] +pub struct Limits { + /// Largest `width * height` accepted. + pub max_pixels: u64, + /// Largest single decompressed buffer accepted, in bytes. + pub max_alloc: usize, +} + +impl Default for Limits { + fn default() -> Self { + Limits { + max_pixels: 1 << 28, + max_alloc: 1 << 32, + } + } +} + +impl Limits { + /// Check a header's dimensions before they size anything. + pub fn check(&self, width: u32, height: u32) -> Result<()> { + if width == 0 || height == 0 { + return Err(Error::corrupt(format!("{width}x{height} image"))); + } + let pixels = u64::from(width) * u64::from(height); + if pixels > self.max_pixels { + return Err(Error::unsupported( + format!("{width}x{height} image"), + format!("{pixels} pixels is past the {} limit", self.max_pixels), + )); + } + Ok(()) + } +} + +/// What a file said about its own pixels, parsed but not applied. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct Metadata { + /// PNG `gAMA`: the gamma the file was authored at. + pub gamma: Option, + /// PNG `sRGB`: rendering intent 0..=3, meaning the file is sRGB. + pub srgb_intent: Option, + /// EXIF orientation tag 1..=8, from a JPEG APP1 or a WebP `EXIF` chunk. + /// + /// Exposed, never applied — the same choice the incumbent `image` crate + /// makes, so a caller swapping between them sees the same pixels. + pub orientation: Option, +} + +/// A decoded image's samples, in the file's own colour form. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Pixels { + /// 8-bit grayscale. + L8(Vec), + /// 8-bit grayscale + alpha. + La8(Vec), + /// 8-bit R,G,B. + Rgb8(Vec), + /// 8-bit R,G,B,A. + Rgba8(Vec), + /// 16-bit grayscale. + L16(Vec), + /// 16-bit grayscale + alpha. + La16(Vec), + /// 16-bit R,G,B. + Rgb16(Vec), + /// 16-bit R,G,B,A. + Rgba16(Vec), +} + +impl Pixels { + /// Samples per pixel. + pub fn channels(&self) -> usize { + match self { + Pixels::L8(_) | Pixels::L16(_) => 1, + Pixels::La8(_) | Pixels::La16(_) => 2, + Pixels::Rgb8(_) | Pixels::Rgb16(_) => 3, + Pixels::Rgba8(_) | Pixels::Rgba16(_) => 4, + } + } + + /// Bits per sample: 8 or 16. + pub fn bit_depth(&self) -> u8 { + match self { + Pixels::L8(_) | Pixels::La8(_) | Pixels::Rgb8(_) | Pixels::Rgba8(_) => 8, + _ => 16, + } + } + + /// True when the samples carry an alpha channel. + pub fn has_alpha(&self) -> bool { + matches!( + self, + Pixels::La8(_) | Pixels::Rgba8(_) | Pixels::La16(_) | Pixels::Rgba16(_) + ) + } +} + +/// A decoded still image. +#[derive(Debug, Clone, PartialEq)] +pub struct Image { + /// Width in pixels. + pub width: u32, + /// Height in pixels. + pub height: u32, + /// The samples. + pub pixels: Pixels, + /// What the file declared about them. + pub meta: Metadata, +} + +/// Rounding-correct 16-bit sample down to 8 bits: `round(v * 255 / 65535)`. +fn narrow(v: u16) -> u8 { + ((u32::from(v) + 128) / 257) as u8 +} + +/// 8-bit sample widened to 16: `v * 65535 / 255`, exact. +fn widen(v: u8) -> u16 { + u16::from(v) * 257 +} + +impl Image { + /// `(width, height)`. + pub fn dimensions(&self) -> (u32, u32) { + (self.width, self.height) + } + + /// Packed 8-bit R,G,B, dropping any alpha channel. + pub fn to_rgb8(&self) -> Vec { + let n = (self.width as usize) * (self.height as usize); + let mut out = Vec::with_capacity(n * 3); + match &self.pixels { + Pixels::L8(d) => d.iter().for_each(|&l| out.extend_from_slice(&[l, l, l])), + Pixels::La8(d) => d + .chunks_exact(2) + .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0]])), + Pixels::Rgb8(d) => out.extend_from_slice(d), + Pixels::Rgba8(d) => d + .chunks_exact(4) + .for_each(|p| out.extend_from_slice(&p[..3])), + Pixels::L16(d) => d.iter().for_each(|&l| { + let l = narrow(l); + out.extend_from_slice(&[l, l, l]); + }), + Pixels::La16(d) => d.chunks_exact(2).for_each(|p| { + let l = narrow(p[0]); + out.extend_from_slice(&[l, l, l]); + }), + Pixels::Rgb16(d) => d.iter().for_each(|&s| out.push(narrow(s))), + Pixels::Rgba16(d) => d + .chunks_exact(4) + .for_each(|p| out.extend(p[..3].iter().map(|&s| narrow(s)))), + } + out + } + + /// Packed 8-bit R,G,B,A; opaque where the source had no alpha. + pub fn to_rgba8(&self) -> Vec { + let n = (self.width as usize) * (self.height as usize); + let mut out = Vec::with_capacity(n * 4); + match &self.pixels { + Pixels::L8(d) => d + .iter() + .for_each(|&l| out.extend_from_slice(&[l, l, l, 255])), + Pixels::La8(d) => d + .chunks_exact(2) + .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0], p[1]])), + Pixels::Rgb8(d) => d + .chunks_exact(3) + .for_each(|p| out.extend_from_slice(&[p[0], p[1], p[2], 255])), + Pixels::Rgba8(d) => out.extend_from_slice(d), + Pixels::L16(d) => d.iter().for_each(|&l| { + let l = narrow(l); + out.extend_from_slice(&[l, l, l, 255]); + }), + Pixels::La16(d) => d.chunks_exact(2).for_each(|p| { + let l = narrow(p[0]); + out.extend_from_slice(&[l, l, l, narrow(p[1])]); + }), + Pixels::Rgb16(d) => d.chunks_exact(3).for_each(|p| { + out.extend_from_slice(&[narrow(p[0]), narrow(p[1]), narrow(p[2]), 255]); + }), + Pixels::Rgba16(d) => d.iter().for_each(|&s| out.push(narrow(s))), + } + out + } + + /// Packed 16-bit R,G,B — 8-bit sources widened exactly (`v * 257`). + pub fn to_rgb16(&self) -> Vec { + match &self.pixels { + Pixels::Rgb16(d) => d.clone(), + Pixels::Rgba16(d) => d.chunks_exact(4).flat_map(|p| p[..3].to_vec()).collect(), + Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l]).collect(), + Pixels::La16(d) => d.chunks_exact(2).flat_map(|p| [p[0], p[0], p[0]]).collect(), + _ => self.to_rgb8().into_iter().map(widen).collect(), + } + } + + /// Packed 16-bit R,G,B,A; opaque where the source had no alpha. + pub fn to_rgba16(&self) -> Vec { + match &self.pixels { + Pixels::Rgba16(d) => d.clone(), + Pixels::Rgb16(d) => d + .chunks_exact(3) + .flat_map(|p| [p[0], p[1], p[2], u16::MAX]) + .collect(), + Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l, u16::MAX]).collect(), + Pixels::La16(d) => d + .chunks_exact(2) + .flat_map(|p| [p[0], p[0], p[0], p[1]]) + .collect(), + _ => self.to_rgba8().into_iter().map(widen).collect(), + } + } + + /// The image as an [`ec_core::VideoFrame`], packed RGB8 or RGBA8. + /// + /// The natural bridge for a caller that composes stills and decoded video + /// in one pipeline: alpha survives when the file had it, rather than being + /// silently dropped on the way to a frame. + pub fn to_video_frame(&self) -> Result { + let (format, data) = if self.pixels.has_alpha() { + (PixelFormat::Rgba8, self.to_rgba8()) + } else { + (PixelFormat::Rgb8, self.to_rgb8()) + }; + let stride = (self.width as usize) * if self.pixels.has_alpha() { 4 } else { 3 }; + VideoFrame::try_new( + format, + self.width, + self.height, + vec![Plane::new(data, stride)], + ) + } +} + +/// Dimensions and format from a header alone — the whole file is not decoded. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Info { + /// Which format the bytes are in. + pub format: ImageFormat, + /// Width in pixels. + pub width: u32, + /// Height in pixels. + pub height: u32, +} + +/// Decode `data`, guessing the format from its leading bytes. +pub fn decode(data: &[u8]) -> Result { + decode_with_limits(data, Limits::default()) +} + +/// [`decode`] with caller-chosen [`Limits`]. +pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result { + match ImageFormat::guess(data) { + Some(ImageFormat::Png) => png::decode(data, limits), + Some(ImageFormat::Jpeg) => Err(Error::unsupported( + "JPEG", + "the JPEG decoder is the next stage of this crate", + )), + Some(ImageFormat::WebP) => Err(Error::unsupported( + "WebP", + "the WebP decoder is a later stage of this crate", + )), + None => Err(Error::unsupported( + "image", + "no PNG, JPEG or WebP signature at the start of the data", + )), + } +} + +/// Dimensions from the header alone, without decoding the pixels. +pub fn info(data: &[u8]) -> Result { + match ImageFormat::guess(data) { + Some(ImageFormat::Png) => png::info(data), + Some(ImageFormat::Jpeg) => Err(Error::unsupported( + "JPEG", + "the JPEG decoder is the next stage of this crate", + )), + Some(ImageFormat::WebP) => Err(Error::unsupported( + "WebP", + "the WebP decoder is a later stage of this crate", + )), + None => Err(Error::unsupported( + "image", + "no PNG, JPEG or WebP signature at the start of the data", + )), + } +} + +/// Read and decode the file at `path`. +pub fn open(path: impl AsRef) -> Result { + let data = std::fs::read(path).map_err(Error::Io)?; + decode(&data) +} + +/// Read the file at `path` and report its header dimensions. +pub fn open_info(path: impl AsRef) -> Result { + let data = std::fs::read(path).map_err(Error::Io)?; + info(&data) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn guess_reads_signatures_not_extensions() { + assert_eq!( + ImageFormat::guess(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0]), + Some(ImageFormat::Png) + ); + assert_eq!( + ImageFormat::guess(&[0xff, 0xd8, 0xff, 0xe0]), + Some(ImageFormat::Jpeg) + ); + let mut webp = b"RIFF\0\0\0\0WEBPVP8 ".to_vec(); + webp.push(0); + assert_eq!(ImageFormat::guess(&webp), Some(ImageFormat::WebP)); + assert_eq!(ImageFormat::guess(b"RIFF\0\0\0\0WAVEfmt "), None); + assert_eq!(ImageFormat::guess(b""), None); + } + + #[test] + fn sample_conversion_round_trips_through_eight_bits() { + for v in 0..=255u8 { + assert_eq!(narrow(widen(v)), v, "{v}"); + } + assert_eq!(narrow(0), 0); + assert_eq!(narrow(u16::MAX), 255); + assert_eq!(narrow(32768), 128); + } + + #[test] + fn limits_refuse_before_allocating() { + let limits = Limits::default(); + assert!(limits.check(1920, 1080).is_ok()); + assert!(limits.check(0, 10).is_err()); + assert!(limits.check(100_000, 100_000).is_err()); + } +} diff --git a/crates/ec-image/src/png.rs b/crates/ec-image/src/png.rs new file mode 100644 index 00000000..8c25f76d --- /dev/null +++ b/crates/ec-image/src/png.rs @@ -0,0 +1,588 @@ +//! PNG decoding (W3C PNG / RFC 2083) over [`ec_inflate`]. +//! +//! Every critical chunk is honoured: `IHDR`, `PLTE`, `tRNS`, all five filter +//! types, all five colour types at every legal bit depth (1/2/4/8/16) and both +//! interlace methods. `gAMA` and `sRGB` are parsed into [`Metadata`]; other +//! ancillary chunks are skipped by length, which is what "safe to ignore" +//! means in a format whose chunk list keeps growing. +//! +//! Every chunk's CRC is verified. A PNG that fails its own checksum is +//! [`Error::Corrupt`], because the alternative — decoding it anyway — turns a +//! detectable bit flip into a picture nobody can tell is wrong. + +use crate::{Image, ImageFormat, Info, Limits, Metadata, Pixels}; +use ec_core::{Error, Result}; + +const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]; + +/// Adam7: `(x_start, y_start, x_step, y_step)` per pass. +const ADAM7: [(u32, u32, u32, u32); 7] = [ + (0, 0, 8, 8), + (4, 0, 8, 8), + (0, 4, 4, 8), + (2, 0, 4, 4), + (0, 2, 2, 4), + (1, 0, 2, 2), + (0, 1, 1, 2), +]; + +/// IHDR, the only chunk that must come first. +#[derive(Debug, Clone, Copy)] +struct Header { + width: u32, + height: u32, + depth: u8, + color_type: u8, + interlaced: bool, +} + +impl Header { + /// Samples per pixel for the colour type (palette indices count as one). + fn channels(&self) -> usize { + match self.color_type { + 0 | 3 => 1, + 2 => 3, + 4 => 2, + _ => 4, + } + } + + /// Bytes in one unfiltered scanline of `width` pixels. + fn row_bytes(&self, width: u32) -> usize { + let bits = (width as usize) * self.channels() * (self.depth as usize); + bits.div_ceil(8) + } + + /// Filter unit: bytes per pixel, rounded up, at least one. + fn filter_step(&self) -> usize { + ((self.channels() * self.depth as usize) / 8).max(1) + } +} + +/// CRC-32 (IEEE) as PNG specifies it, table built at compile time. +const CRC_TABLE: [u32; 256] = { + let mut table = [0u32; 256]; + let mut n = 0; + while n < 256 { + let mut c = n as u32; + let mut k = 0; + while k < 8 { + c = if c & 1 != 0 { + 0xedb8_8320 ^ (c >> 1) + } else { + c >> 1 + }; + k += 1; + } + table[n] = c; + n += 1; + } + table +}; + +fn crc32(data: &[u8]) -> u32 { + let mut c = 0xffff_ffffu32; + for &b in data { + c = CRC_TABLE[((c ^ u32::from(b)) & 0xff) as usize] ^ (c >> 8); + } + c ^ 0xffff_ffff +} + +fn be32(data: &[u8]) -> u32 { + u32::from_be_bytes([data[0], data[1], data[2], data[3]]) +} + +/// One chunk: type, payload, and the offset the next chunk starts at. +struct Chunk<'a> { + kind: [u8; 4], + data: &'a [u8], + next: usize, +} + +/// Read the chunk at `at`, verifying its CRC. +fn chunk(data: &[u8], at: usize) -> Result> { + let head = data + .get(at..at + 8) + .ok_or_else(|| Error::corrupt("PNG: truncated chunk header"))?; + let len = be32(head) as usize; + let kind = [head[4], head[5], head[6], head[7]]; + // The length field is 31-bit by spec; a bigger one is a corrupt file, not + // a reason to try to address past the buffer. + if len > 0x7fff_ffff { + return Err(Error::corrupt(format!("PNG: chunk length {len}"))); + } + let body = data + .get(at + 8..at + 8 + len) + .ok_or_else(|| Error::corrupt("PNG: truncated chunk data"))?; + let crc = data + .get(at + 8 + len..at + 12 + len) + .ok_or_else(|| Error::corrupt("PNG: truncated chunk CRC"))?; + let want = be32(crc); + let got = crc32(&data[at + 4..at + 8 + len]); + if want != got { + return Err(Error::corrupt(format!( + "PNG: {} chunk CRC {got:#010x}, file says {want:#010x}", + String::from_utf8_lossy(&kind) + ))); + } + Ok(Chunk { + kind, + data: body, + next: at + 12 + len, + }) +} + +fn header(data: &[u8]) -> Result
{ + if !data.starts_with(&SIGNATURE) { + return Err(Error::corrupt("PNG: bad signature")); + } + let ihdr = chunk(data, 8)?; + if &ihdr.kind != b"IHDR" || ihdr.data.len() != 13 { + return Err(Error::corrupt("PNG: first chunk is not a 13-byte IHDR")); + } + let d = ihdr.data; + let header = Header { + width: be32(d), + height: be32(&d[4..]), + depth: d[8], + color_type: d[9], + interlaced: d[12] == 1, + }; + let depths: &[u8] = match header.color_type { + 0 => &[1, 2, 4, 8, 16], + 3 => &[1, 2, 4, 8], + 2 | 4 | 6 => &[8, 16], + other => { + return Err(Error::corrupt(format!("PNG: colour type {other}"))); + } + }; + if !depths.contains(&header.depth) { + return Err(Error::corrupt(format!( + "PNG: bit depth {} with colour type {}", + header.depth, header.color_type + ))); + } + if d[10] != 0 { + return Err(Error::corrupt(format!("PNG: compression method {}", d[10]))); + } + if d[11] != 0 { + return Err(Error::corrupt(format!("PNG: filter method {}", d[11]))); + } + if d[12] > 1 { + return Err(Error::corrupt(format!("PNG: interlace method {}", d[12]))); + } + Ok(header) +} + +/// Dimensions from IHDR alone. +pub fn info(data: &[u8]) -> Result { + let h = header(data)?; + Ok(Info { + format: ImageFormat::Png, + width: h.width, + height: h.height, + }) +} + +/// Decode a PNG. +pub fn decode(data: &[u8], limits: Limits) -> Result { + let hdr = header(data)?; + limits.check(hdr.width, hdr.height)?; + + let mut palette: Vec<[u8; 3]> = Vec::new(); + let mut trns: Option> = None; + let mut meta = Metadata::default(); + let mut idat: Vec = Vec::new(); + let mut at = chunk(data, 8)?.next; + let mut saw_end = false; + while !saw_end { + let c = chunk(data, at)?; + at = c.next; + match &c.kind { + b"PLTE" => { + if c.data.len() % 3 != 0 || c.data.len() > 256 * 3 { + return Err(Error::corrupt(format!( + "PNG: PLTE of {} bytes", + c.data.len() + ))); + } + palette = c.data.chunks_exact(3).map(|p| [p[0], p[1], p[2]]).collect(); + } + b"tRNS" => trns = Some(c.data.to_vec()), + b"gAMA" if c.data.len() == 4 => { + meta.gamma = Some(f64::from(be32(c.data)) / 100_000.0); + } + b"sRGB" if c.data.len() == 1 => meta.srgb_intent = Some(c.data[0]), + b"IDAT" => idat.extend_from_slice(c.data), + b"IEND" => saw_end = true, + // Anything else is skipped by its own length: unknown ancillary + // chunks are exactly what the chunk layout exists to survive. + _ => {} + } + } + if idat.is_empty() { + return Err(Error::corrupt("PNG: no IDAT data")); + } + if hdr.color_type == 3 && palette.is_empty() { + return Err(Error::corrupt("PNG: palette image without a PLTE chunk")); + } + + // Exactly how many bytes the passes need; a stream claiming more is + // truncated by the limit rather than believed. + let expected: usize = passes(&hdr) + .iter() + .map(|&(w, h)| { + if w == 0 || h == 0 { + 0 + } else { + (h as usize) * (hdr.row_bytes(w) + 1) + } + }) + .sum(); + if expected > limits.max_alloc { + return Err(Error::unsupported( + "PNG", + format!("{expected} bytes of pixel data is past the allocation limit"), + )); + } + let raw = ec_inflate::inflate_zlib(&idat, expected).map_err(Error::from)?; + if raw.len() < expected { + return Err(Error::corrupt(format!( + "PNG: {} bytes of scanlines, {expected} needed", + raw.len() + ))); + } + + // Samples are carried at 16 bits internally whatever the file's depth, so + // one expansion path serves every colour type; the narrowing back to 8 + // happens once, at the end. + let channels_out = out_channels(&hdr, &trns); + let mut out = vec![0u16; (hdr.width as usize) * (hdr.height as usize) * channels_out]; + let mut offset = 0; + for (pass, &(pw, ph)) in passes(&hdr).iter().enumerate() { + if pw == 0 || ph == 0 { + continue; + } + let row_bytes = hdr.row_bytes(pw); + let step = hdr.filter_step(); + let mut previous = vec![0u8; row_bytes]; + let mut current = vec![0u8; row_bytes]; + let (x0, y0, dx, dy) = if hdr.interlaced { + ADAM7[pass] + } else { + (0, 0, 1, 1) + }; + for row in 0..ph { + let start = offset + (row as usize) * (row_bytes + 1); + let filter = raw[start]; + current.copy_from_slice(&raw[start + 1..start + 1 + row_bytes]); + unfilter(filter, step, &previous, &mut current)?; + let y = y0 + row * dy; + expand_row( + ¤t, + pw, + &hdr, + &palette, + trns.as_deref(), + channels_out, + |px, sample| { + let x = x0 + px * dx; + let base = ((y as usize) * (hdr.width as usize) + x as usize) * channels_out; + out[base..base + channels_out].copy_from_slice(sample); + }, + )?; + std::mem::swap(&mut previous, &mut current); + } + offset += (ph as usize) * (row_bytes + 1); + } + + let pixels = if hdr.depth == 16 { + match channels_out { + 1 => Pixels::L16(out), + 2 => Pixels::La16(out), + 3 => Pixels::Rgb16(out), + _ => Pixels::Rgba16(out), + } + } else { + let bytes: Vec = out.into_iter().map(|s| s as u8).collect(); + match channels_out { + 1 => Pixels::L8(bytes), + 2 => Pixels::La8(bytes), + 3 => Pixels::Rgb8(bytes), + _ => Pixels::Rgba8(bytes), + } + }; + Ok(Image { + width: hdr.width, + height: hdr.height, + pixels, + meta, + }) +} + +/// Channels the decoded image ends up with: a palette becomes RGB(A), and a +/// `tRNS` chunk adds the alpha channel the colour type lacks. +fn out_channels(hdr: &Header, trns: &Option>) -> usize { + match hdr.color_type { + 0 => 1 + usize::from(trns.is_some()), + 2 => 3 + usize::from(trns.is_some()), + 3 => 3 + usize::from(trns.is_some()), + 4 => 2, + _ => 4, + } +} + +/// `(width, height)` of each pass — one entry for a non-interlaced image. +fn passes(hdr: &Header) -> Vec<(u32, u32)> { + if !hdr.interlaced { + return vec![(hdr.width, hdr.height)]; + } + ADAM7 + .iter() + .map(|&(x0, y0, dx, dy)| { + ( + hdr.width.saturating_sub(x0).div_ceil(dx), + hdr.height.saturating_sub(y0).div_ceil(dy), + ) + }) + .collect() +} + +/// Reverse one scanline's filter in place. +fn unfilter(filter: u8, step: usize, prev: &[u8], row: &mut [u8]) -> Result<()> { + match filter { + 0 => {} + 1 => { + for i in step..row.len() { + row[i] = row[i].wrapping_add(row[i - step]); + } + } + 2 => { + for i in 0..row.len() { + row[i] = row[i].wrapping_add(prev[i]); + } + } + 3 => { + for i in 0..row.len() { + let left = if i >= step { + u16::from(row[i - step]) + } else { + 0 + }; + let up = u16::from(prev[i]); + row[i] = row[i].wrapping_add(((left + up) / 2) as u8); + } + } + 4 => { + for i in 0..row.len() { + let (a, c) = if i >= step { + (i32::from(row[i - step]), i32::from(prev[i - step])) + } else { + (0, 0) + }; + let b = i32::from(prev[i]); + let p = a + b - c; + let (pa, pb, pc) = ((p - a).abs(), (p - b).abs(), (p - c).abs()); + let pred = if pa <= pb && pa <= pc { + a + } else if pb <= pc { + b + } else { + c + }; + row[i] = row[i].wrapping_add(pred as u8); + } + } + other => return Err(Error::corrupt(format!("PNG: filter type {other}"))), + } + Ok(()) +} + +/// Pull one pixel's raw samples out of a packed scanline. +fn raw_sample(row: &[u8], depth: u8, index: usize) -> u16 { + match depth { + 16 => u16::from_be_bytes([row[index * 2], row[index * 2 + 1]]), + 8 => u16::from(row[index]), + _ => { + let per_byte = 8 / depth as usize; + let byte = row[index / per_byte]; + let shift = 8 - depth as usize * (index % per_byte + 1); + u16::from((byte >> shift) & ((1u16 << depth) - 1) as u8) + } + } +} + +/// Expand one unfiltered scanline into per-pixel output samples. +/// +/// `emit` places pixel `px` of this pass; interlacing is entirely the caller's +/// business, which keeps one expansion path serving both layouts. +fn expand_row( + row: &[u8], + width: u32, + hdr: &Header, + palette: &[[u8; 3]], + trns: Option<&[u8]>, + channels_out: usize, + mut emit: impl FnMut(u32, &[u16]), +) -> Result<()> { + // Sub-8-bit greyscale is scaled to the full range, so a 1-bit "1" is white + // rather than a nearly black 1/255. + let max = ((1u32 << hdr.depth) - 1) as u16; + let scale = |v: u16| -> u16 { + if hdr.depth == 16 || hdr.depth == 8 { + v + } else { + ((u32::from(v) * 255) / u32::from(max)) as u16 + } + }; + let mut sample = [0u16; 4]; + for px in 0..width { + let base = (px as usize) * hdr.channels(); + match hdr.color_type { + 0 => { + let g = raw_sample(row, hdr.depth, base); + sample[0] = scale(g); + if channels_out == 2 { + let key = trns + .and_then(|t| t.get(..2)) + .map(|t| u16::from_be_bytes([t[0], t[1]])); + sample[1] = if Some(g) == key { + 0 + } else { + max_for(hdr.depth) + }; + } + } + 2 => { + for c in 0..3 { + sample[c] = raw_sample(row, hdr.depth, base + c); + } + if channels_out == 4 { + let key = trns.and_then(|t| t.get(..6)).map(|t| { + [ + u16::from_be_bytes([t[0], t[1]]), + u16::from_be_bytes([t[2], t[3]]), + u16::from_be_bytes([t[4], t[5]]), + ] + }); + sample[3] = if key == Some([sample[0], sample[1], sample[2]]) { + 0 + } else { + max_for(hdr.depth) + }; + } + } + 3 => { + let index = raw_sample(row, hdr.depth, base) as usize; + let entry = palette.get(index).ok_or_else(|| { + Error::corrupt(format!( + "PNG: palette index {index} in a {}-entry PLTE", + palette.len() + )) + })?; + sample[0] = u16::from(entry[0]); + sample[1] = u16::from(entry[1]); + sample[2] = u16::from(entry[2]); + if channels_out == 4 { + sample[3] = u16::from(trns.and_then(|t| t.get(index)).copied().unwrap_or(255)); + } + } + 4 => { + sample[0] = raw_sample(row, hdr.depth, base); + sample[1] = raw_sample(row, hdr.depth, base + 1); + } + _ => { + for c in 0..4 { + sample[c] = raw_sample(row, hdr.depth, base + c); + } + } + } + emit(px, &sample[..channels_out]); + } + Ok(()) +} + +/// Fully opaque, at the depth the output carries. +fn max_for(depth: u8) -> u16 { + if depth == 16 { u16::MAX } else { 255 } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn crc_matches_the_known_iend_value() { + // IEND is a fixed, empty chunk; its CRC is the same in every PNG ever + // written, which makes it the one checksum worth pinning by hand. + assert_eq!(crc32(b"IEND"), 0xae42_6082); + } + + #[test] + fn paeth_prefers_the_nearest_predictor() { + let prev = [10u8, 200]; + let mut row = [0u8, 0]; + unfilter(4, 1, &prev, &mut row).unwrap(); + assert_eq!(row, [10, 200]); + } + + #[test] + fn adam7_pass_sizes_cover_every_pixel() { + for (w, h) in [(1u32, 1u32), (7, 5), (16, 16), (33, 17)] { + let hdr = Header { + width: w, + height: h, + depth: 8, + color_type: 2, + interlaced: true, + }; + let total: u32 = passes(&hdr).iter().map(|&(pw, ph)| pw * ph).sum(); + assert_eq!(total, w * h, "{w}x{h}"); + } + } + + /// A 1x1 white 8-bit greyscale PNG, built here rather than checked in: the + /// zlib payload is a single stored DEFLATE block, so no encoder is needed. + fn tiny_png() -> Vec { + fn push_chunk(out: &mut Vec, kind: &[u8; 4], body: &[u8]) { + out.extend_from_slice(&(body.len() as u32).to_be_bytes()); + let start = out.len(); + out.extend_from_slice(kind); + out.extend_from_slice(body); + let crc = crc32(&out[start..]); + out.extend_from_slice(&crc.to_be_bytes()); + } + let scanline = [0u8, 0xff]; // filter None, one white sample + let mut zlib = vec![0x78, 0x01, 0x01, 0x02, 0x00, 0xfd, 0xff]; + zlib.extend_from_slice(&scanline); + let (mut a, mut b) = (1u32, 0u32); + for &byte in &scanline { + a = (a + u32::from(byte)) % 65521; + b = (b + a) % 65521; + } + zlib.extend_from_slice(&((b << 16) | a).to_be_bytes()); + + let mut png = SIGNATURE.to_vec(); + let mut ihdr = Vec::new(); + ihdr.extend_from_slice(&1u32.to_be_bytes()); + ihdr.extend_from_slice(&1u32.to_be_bytes()); + ihdr.extend_from_slice(&[8, 0, 0, 0, 0]); + push_chunk(&mut png, b"IHDR", &ihdr); + push_chunk(&mut png, b"IDAT", &zlib); + push_chunk(&mut png, b"IEND", &[]); + png + } + + #[test] + fn a_one_pixel_png_decodes_and_a_bad_crc_does_not() { + let png = tiny_png(); + let img = decode(&png, Limits::default()).expect("the hand-built PNG"); + assert_eq!(img.dimensions(), (1, 1)); + assert_eq!(img.pixels, Pixels::L8(vec![255])); + + let mut broken = png.clone(); + let last = broken.len() - 1; + broken[last] ^= 0xff; + assert!(decode(&broken, Limits::default()).is_err(), "bad IEND CRC"); + } +} diff --git a/scripts/gen-still-fixtures.sh b/scripts/gen-still-fixtures.sh new file mode 100755 index 00000000..b14370e9 --- /dev/null +++ b/scripts/gen-still-fixtures.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# Still-image fixtures for ec-image's differential tests: every PNG colour +# type and bit depth, both JPEG processes at each chroma layout, and both WebP +# bitstreams with and without alpha. +# +# The corpus is generated rather than committed, so the repository stays free +# of binaries and every machine can rebuild it: ImageMagick writes the PNG and +# JPEG variants, ffmpeg the WebP ones. +set -euo pipefail + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +out="$root/fixtures/stills" +mkdir -p "$out" + +need() { + command -v "$1" >/dev/null || { echo "missing: $1" >&2; exit 1; } +} +need magick +need ffmpeg + +# Source pictures: one with smooth and hard content at even dimensions, one at +# odd dimensions (chroma subsampling and Adam7 both round there), and one with +# a real alpha channel. +# Seeded, so the corpus is byte-identical on every machine and a differential +# bar measured today still means the same thing tomorrow. +magick -seed 1234 -size 320x240 plasma:fractal -blur 0x1 \ + -fill white -stroke black -draw "rectangle 20,20 80,60" \ + -draw "line 0,239 319,0" "$out/source.png" +magick "$out/source.png" -resize 61x47! "$out/source-odd.png" +magick "$out/source.png" -alpha set -channel A \ + -fx "i/w" +channel "$out/source-alpha.png" + +# --- PNG: every colour type, every bit depth, both interlace methods -------- +magick "$out/source.png" -define png:color-type=2 -depth 8 "$out/rgb8.png" +magick "$out/source-alpha.png" -define png:color-type=6 -depth 8 "$out/rgba8.png" +magick "$out/source.png" -colorspace Gray -define png:color-type=0 -depth 8 "$out/gray8.png" +magick "$out/source-alpha.png" -colorspace Gray -define png:color-type=4 -depth 8 "$out/graya8.png" +magick "$out/source.png" -define png:color-type=2 -depth 16 "$out/rgb16.png" +magick "$out/source-alpha.png" -define png:color-type=6 -depth 16 "$out/rgba16.png" +magick "$out/source.png" -colorspace Gray -define png:color-type=0 -depth 16 "$out/gray16.png" +magick "$out/source.png" -colors 256 -define png:color-type=3 "$out/palette8.png" +magick "$out/source.png" -colors 16 -define png:color-type=3 -define png:bit-depth=4 "$out/palette4.png" +magick "$out/source.png" -colors 3 -define png:color-type=3 -define png:bit-depth=2 "$out/palette2.png" +magick "$out/source.png" -monochrome -define png:color-type=3 -define png:bit-depth=1 "$out/palette1.png" +magick "$out/source.png" -colorspace Gray -depth 4 -define png:color-type=0 -define png:bit-depth=4 "$out/gray4.png" +magick "$out/source.png" -colorspace Gray -depth 2 -define png:color-type=0 -define png:bit-depth=2 "$out/gray2.png" +magick "$out/source.png" -colorspace Gray -threshold 50% -define png:color-type=0 -define png:bit-depth=1 "$out/gray1.png" +magick "$out/source.png" -interlace PNG -define png:color-type=2 "$out/interlaced-rgb8.png" +magick "$out/source-alpha.png" -interlace PNG -define png:color-type=6 -depth 16 "$out/interlaced-rgba16.png" +magick "$out/source.png" -colors 64 -interlace PNG -define png:color-type=3 "$out/interlaced-palette.png" +magick "$out/source-odd.png" -define png:color-type=2 "$out/odd-rgb8.png" +magick "$out/source-odd.png" -interlace PNG -define png:color-type=2 "$out/odd-interlaced.png" +# Palette with a transparent entry, and a colour-keyed truecolour image. +magick "$out/source-alpha.png" -colors 32 PNG8:"$out/trns-palette.png" +magick "$out/source.png" -define png:color-type=2 -transparent white "$out/trns-rgb.png" || true +magick "$out/source.png" -colorspace Gray -depth 8 -transparent black \ + -define png:color-type=0 "$out/trns-gray.png" || true + +# --- JPEG: both processes, every chroma layout, restarts, EXIF ------------- +magick "$out/source.png" -quality 90 -sampling-factor 1x1 "$out/baseline-444.jpg" +magick "$out/source.png" -quality 90 -sampling-factor 2x1 "$out/baseline-422.jpg" +magick "$out/source.png" -quality 90 -sampling-factor 2x2 "$out/baseline-420.jpg" +magick "$out/source.png" -quality 50 -sampling-factor 2x2 "$out/baseline-420-q50.jpg" +magick "$out/source.png" -quality 90 -sampling-factor 2x2 -interlace JPEG "$out/progressive-420.jpg" +magick "$out/source.png" -quality 90 -sampling-factor 1x1 -interlace JPEG "$out/progressive-444.jpg" +magick "$out/source.png" -colorspace Gray -quality 90 "$out/gray.jpg" +magick "$out/source.png" -quality 90 -sampling-factor 2x2 \ + -define jpeg:restart-interval=4 "$out/restart-420.jpg" +magick "$out/source-odd.png" -quality 90 -sampling-factor 2x2 "$out/odd-420.jpg" +magick "$out/source-odd.png" -quality 90 -sampling-factor 2x1 "$out/odd-422.jpg" + +# --- WebP: lossy and lossless, with and without alpha ---------------------- +ffmpeg -loglevel error -y -i "$out/source.png" -c:v libwebp -lossless 0 -quality 80 \ + "$out/lossy.webp" +ffmpeg -loglevel error -y -i "$out/source.png" -c:v libwebp -lossless 0 -quality 40 \ + "$out/lossy-q40.webp" +ffmpeg -loglevel error -y -i "$out/source.png" -c:v libwebp -lossless 1 "$out/lossless.webp" +ffmpeg -loglevel error -y -i "$out/source-alpha.png" -c:v libwebp -lossless 1 \ + "$out/lossless-alpha.webp" +ffmpeg -loglevel error -y -i "$out/source-alpha.png" -c:v libwebp -lossless 0 -quality 80 \ + "$out/lossy-alpha.webp" +ffmpeg -loglevel error -y -i "$out/source-odd.png" -c:v libwebp -lossless 0 -quality 80 \ + "$out/odd-lossy.webp" +ffmpeg -loglevel error -y -i "$out/source-odd.png" -c:v libwebp -lossless 1 "$out/odd-lossless.webp" +# A palette-friendly picture, so the lossless colour-indexing transform is +# exercised rather than only the predictor one. +magick "$out/source.png" -colors 8 "$out/source-flat.png" +ffmpeg -loglevel error -y -i "$out/source-flat.png" -c:v libwebp -lossless 1 \ + "$out/lossless-palette.webp" +# An animation, which the decoder must refuse by name rather than decode. +# ffmpeg's libwebp_anim silently writes a single still here, so ImageMagick +# writes this one: its output really does carry ANIM/ANMF chunks. +magick -delay 10 "$out/source.png" "$out/source-flat.png" "$out/source-odd.png" \ + -loop 0 "$out/animated.webp" + +# Small versions of each format, for the fuzz sweep: ten thousand mutations +# per format is only affordable on a picture that decodes in microseconds. +magick "$out/source.png" -resize 32x24! "$out/tiny.png" +magick "$out/tiny.png" -quality 80 -sampling-factor 2x2 "$out/tiny.jpg" +ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 0 -quality 75 \ + "$out/tiny-lossy.webp" +ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 1 "$out/tiny-lossless.webp" + +echo "wrote $(ls "$out" | wc -l) files to $out"