//! Still-image decoding: PNG, JPEG, WebP, GIF, BMP and TIFF. //! //! 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 bmp; pub mod gif; pub mod jpeg; pub mod png; pub mod tiff; mod upsample; pub mod gif_encode; pub mod png_encode; pub mod transform; pub mod webp; mod exif; mod probe; pub use probe::{probe, probe_reader, PROBE_LIMIT}; 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, /// GIF, still or animated (GIF87a and GIF89a). Gif, /// Windows BMP (device-independent bitmap). Bmp, /// TIFF, the tag-directory format. Tiff, } 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 if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") { Some(ImageFormat::Gif) } else if is_bmp(data) { Some(ImageFormat::Bmp) } else if data.starts_with(b"II\x2a\x00") || data.starts_with(b"MM\x00\x2a") || data.starts_with(b"II\x2b\x00") || data.starts_with(b"MM\x00\x2b") { // 42 is classic TIFF and 43 is BigTIFF; the second is recognised // here so that the decoder can refuse it by name rather than // leaving the file unidentified. Some(ImageFormat::Tiff) } 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", ImageFormat::Gif => "gif", ImageFormat::Bmp => "bmp", ImageFormat::Tiff => "tiff", } } } /// Whether `data` opens like a BMP. /// /// "BM" is two bytes, which half the files on a disk could start with by /// accident, so the guess also asks the file header to agree with itself: the /// declared info-header length must be one the format defines, and the pixel /// data must start after the headers. fn is_bmp(data: &[u8]) -> bool { if !data.starts_with(b"BM") || data.len() < 18 { return false; } let u32_at = |at: usize| u32::from_le_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]); let offset = u32_at(10) as usize; let info_size = u32_at(14) as usize; matches!(info_size, 12 | 16 | 40 | 52 | 56 | 64 | 108 | 124) && offset >= 14 + info_size } /// The default decode budget for one buffer, in bytes: 512 MiB, the same default the `image` /// crate applies. [`decode`] and [`decode_animation`] refuse any picture whose decoded output /// (width x height x bytes per pixel) is larger; [`decode_with_limits`] lets a caller raise it. pub const DEFAULT_MAX_ALLOC: usize = 512 << 20; /// 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 refuses a decoded picture past [`DEFAULT_MAX_ALLOC`] bytes. #[derive(Debug, Clone, Copy)] pub struct Limits { /// Largest `width * height` accepted. pub max_pixels: u64, /// Largest single decompressed buffer accepted, in bytes. The decoded picture /// is the buffer that matters most; see [`Limits::check_output`]. pub max_alloc: usize, /// Largest total bytes accepted across every frame of one decode call. /// /// A single frame can pass [`Limits::check_bytes`] on its own and still /// be a bomb once a frame or segment count multiplies it — GIF and WebP /// both composite onto a full canvas per frame, and a stripped or tiled /// TIFF decompresses many segments per call, so a file whose parts each /// look small on their own can still retain gigabytes nothing ever /// checked one buffer at a time. [`AllocBudget`] enforces this across a /// decode call. pub max_total_alloc: usize, } impl Default for Limits { fn default() -> Self { Limits { max_pixels: 1 << 28, max_alloc: DEFAULT_MAX_ALLOC, max_total_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(()) } /// Check a decoded picture, `width * height * bytes_per_pixel`, before anything is sized /// from it. A refusal names the dimensions and the budget, and comes before any pixel work. pub fn check_output(&self, width: u32, height: u32, bytes_per_pixel: usize) -> Result { self.check(width, height)?; let what = format!("{width}x{height} image"); let bytes = (width as usize) .checked_mul(height as usize) .and_then(|p| p.checked_mul(bytes_per_pixel)) .ok_or_else(|| Error::corrupt(format!("{what}: size overflows usize")))?; if bytes > self.max_alloc { return Err(Error::unsupported( what, format!( "{bytes} bytes of decoded pixels past the {} byte budget \ (512 MiB by default; decode_with_limits raises it)", self.max_alloc ), )); } Ok(bytes) } /// Check a byte count computed from header-declared fields (a frame's or /// strip's `width * height * bpp`, a palette size, a chunk length) before it /// sizes a single allocation. `what` names the buffer for the error. pub fn check_bytes(&self, what: &str, bytes: Option) -> Result { let bytes = bytes.ok_or_else(|| Error::corrupt(format!("{what}: size overflows usize")))?; if bytes > self.max_alloc { return Err(Error::unsupported( what.to_string(), format!("{bytes} bytes past the {} allocation limit", self.max_alloc), )); } Ok(bytes) } } /// Accumulates bytes spent across every frame or segment of one decode call /// and refuses once the running total crosses [`Limits::max_total_alloc`] — /// the guard for `frame_count x canvas` or `segment_count x segment_size`, /// which [`Limits::check_bytes`] alone never sees since it only ever looks /// at one buffer at a time. #[derive(Debug, Default)] pub struct AllocBudget(usize); impl AllocBudget { /// Spend `bytes` from the budget, refusing once the running total passes /// `limits.max_total_alloc`. pub fn spend(&mut self, limits: &Limits, what: &str, bytes: usize) -> Result<()> { self.0 = self .0 .checked_add(bytes) .ok_or_else(|| Error::corrupt(format!("{what}: total size overflows usize")))?; if self.0 > limits.max_total_alloc { return Err(Error::unsupported( what.to_string(), format!( "{} total decoded bytes past the {} limit", self.0, limits.max_total_alloc ), )); } 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, a PNG `eXIf` 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 } 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 .as_chunks::<2>().0.iter() .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 .as_chunks::<4>().0.iter() .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.as_chunks::<2>().0.iter().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 .as_chunks::<4>().0.iter() .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 .as_chunks::<2>().0.iter() .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0], p[1]])), Pixels::Rgb8(d) => d .as_chunks::<3>().0.iter() .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.as_chunks::<2>().0.iter().for_each(|p| { let l = narrow(p[0]); out.extend_from_slice(&[l, l, l, narrow(p[1])]); }), Pixels::Rgb16(d) => d.as_chunks::<3>().0.iter().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 } /// 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, /// EXIF orientation 1..=8 (1 when the file carries none). Reported, not applied. pub orientation: u8, } fn format_of(data: &[u8]) -> Result { ImageFormat::guess(data).ok_or_else(|| { Error::unsupported( "image", "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data", ) }) } /// 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 format_of(data)? { ImageFormat::Png => png::decode(data, limits), ImageFormat::Jpeg => jpeg::decode(data, limits), ImageFormat::WebP => webp::decode(data, limits), ImageFormat::Gif => gif::decode(data, limits), ImageFormat::Bmp => bmp::decode(data, limits), ImageFormat::Tiff => tiff::decode(data, limits), } } /// Format, dimensions and EXIF orientation from the header alone, without /// decoding the pixels. /// /// The whole of `data` is read as header. To look at a bounded prefix or a /// stream instead, use [`probe`] or [`probe_reader`]. pub fn info(data: &[u8]) -> Result { match format_of(data)? { ImageFormat::Png => png::info(data), ImageFormat::Jpeg => jpeg::info(data), ImageFormat::WebP => webp::info(data), ImageFormat::Gif => gif::info(data), ImageFormat::Bmp => bmp::info(data), ImageFormat::Tiff => tiff::info(data), } } /// One picture of an animation, already composited onto the canvas. /// /// A frame is the whole canvas, not the sub-rectangle the file stored, because /// every consumer of an animation draws whole pictures. #[derive(Debug, Clone, PartialEq)] pub struct AnimationFrame { /// The canvas at this point in the animation. pub image: Image, /// How long the frame is shown, in `delay_num / delay_den` seconds. pub delay_num: u32, /// The denominator of that delay; GIF counts hundredths of a second. pub delay_den: u32, } /// Every frame of an animation, composited. /// /// A format that cannot animate -- and a single-picture file in one that can /// -- returns exactly one frame, with a zero delay, so a caller that wants /// frames never needs to know which format it holds. pub fn decode_animation(data: &[u8]) -> Result> { decode_animation_with_limits(data, Limits::default()) } /// [`decode_animation`] with caller-chosen [`Limits`]. /// /// The limits bound every frame and the whole composite, so a caller with a /// tighter memory budget than the default can lower them here. pub fn decode_animation_with_limits(data: &[u8], limits: Limits) -> Result> { match format_of(data)? { ImageFormat::Gif => gif::decode_animation(data, limits), ImageFormat::WebP if webp::is_animated(data) => webp::decode_frames(data, limits), _ => Ok(vec![AnimationFrame { image: decode_with_limits(data, limits)?, delay_num: 0, delay_den: 100, }]), } } /// 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) } #[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(u16::from(v) * 257), 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()); } #[test] fn check_output_names_the_picture_and_refuses_past_the_budget() { let limits = Limits::default(); assert_eq!(limits.max_alloc, 512 << 20); assert!(limits.check_output(12000, 12000, 3).is_ok()); let err = limits.check_output(12000, 12000, 4).expect_err("576 MB is past 512 MiB"); let text = format!("{err}"); assert!(text.contains("12000x12000"), "{text}"); assert!(text.contains("536870912"), "{text}"); } #[test] fn check_bytes_refuses_past_max_alloc_before_a_frame_size_carries_it() { let limits = Limits::default(); assert!(limits.check_bytes("test", Some(1024)).is_ok()); assert!(limits.check_bytes("test", Some(limits.max_alloc + 1)).is_err()); assert!(limits.check_bytes("test", None).is_err()); } #[test] fn alloc_budget_refuses_once_repeated_spends_cross_the_total() { // The class this guards: no single spend is ever over budget on its // own, but a canvas cloned once per animation frame is. let limits = Limits::default(); let mut budget = AllocBudget::default(); let per_frame = limits.max_total_alloc / 4; for i in 0..4 { assert!( budget.spend(&limits, "frame", per_frame).is_ok(), "frame {i} alone is within budget" ); } assert!( budget.spend(&limits, "frame", per_frame).is_err(), "a fifth frame the same size crosses the total" ); } }