Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[rust] Add bounded streaming PNG decoding

laurenspriem0fe837873460
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 5b7bc5c631..c97d1165bb 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2621,6 +2621,8 @@ dependencies = [
"jxl-oxide",
"kamadak-exif",
"moxcms",
+ "png 0.18.1",
+ "tempfile",
"thiserror 2.0.18",
"tiff 0.10.3",
]
diff --git a/rust/crates/image/Cargo.toml b/rust/crates/image/Cargo.toml
index 4259206052..0e9f510a19 100644
--- a/rust/crates/image/Cargo.toml
+++ b/rust/crates/image/Cargo.toml
@@ -11,8 +11,12 @@ image.workspace = true
jxl-oxide = { version = "0.12.6", features = ["image"] }
kamadak-exif = "0.6.1"
moxcms = { version = "0.8.1", features = ["in_place"] }
+png = "0.18.1"
thiserror.workspace = true
tiff = "0.10.3"
+[dev-dependencies]
+tempfile.workspace = true
+
[lints]
workspace = true
diff --git a/rust/crates/image/README.md b/rust/crates/image/README.md
new file mode 100644
index 0000000000..6ec76ec148
--- /dev/null
+++ b/rust/crates/image/README.md
@@ -0,0 +1,42 @@
+# ente-image
+
+`decode_bounded` accepts a path or borrowed bytes and a nonzero maximum side length:
+
+```rust
+use ente_image::{ImageInput, decode_bounded};
+
+let decoded = decode_bounded(ImageInput::Path("photo.png"), 6000)?;
+let decoded = decode_bounded(ImageInput::Bytes(&encoded_bytes), 6000)?;
+```
+
+The result contains `image`, an RGB8 `DecodedImage`, and `original_dimensions`.
+Both sets of dimensions include EXIF orientation. Output preserves aspect ratio
+with integer rounding, never upscales, and fits within the requested maximum side.
+Existing decode functions and callers are unchanged.
+
+PNG is detected from its signature and decoded row by row through the `png`
+crate. Pixels are converted using the existing ICC-to-sRGB handling and reduced
+with an area average before applying orientation. Palette, transparency,
+grayscale, 16-bit samples, and Adam7 interlacing are supported. Alpha is discarded,
+matching the existing RGB decoder. APNG returns its default image.
+
+Non-interlaced PNG needs the reduced RGB output and a few source/target rows.
+Adam7 additionally needs a floating-point accumulator at the reduced dimensions
+(12 bytes per output pixel). Neither path allocates a full-resolution pixel
+image when reducing. Source row width and buffer sizes are checked before decode:
+the conservative row allowance is 4 MiB, the PNG decoder allowance is 32 MiB,
+and the estimated working-buffer allowance is 512 MiB. Oversized requests return
+`ImageError::TooLarge`; a large Adam7 output can exceed this allowance even when
+its side length is permitted. These are allocation guards, not a process-wide
+RSS limit; caller-owned encoded bytes and color-management allocations also use
+memory. Decode time still depends on the source image size.
+
+Other formats use the existing decoder followed by a resize. Their output is
+bounded, but their full-resolution decode memory is not bounded by `max_side`.
+PNG failures are returned directly without retrying a full-image decode.
+
+Run the optional large-input regression with:
+
+```sh
+cargo test --release -p ente-image streams_200_megapixels -- --ignored
+```
diff --git a/rust/crates/image/src/bounded.rs b/rust/crates/image/src/bounded.rs
new file mode 100644
index 0000000000..4e2f216a3c
--- /dev/null
+++ b/rust/crates/image/src/bounded.rs
@@ -0,0 +1,87 @@
+use std::{
+ fs::File,
+ io::{BufRead, BufReader, Cursor},
+};
+
+use image::{DynamicImage, imageops::FilterType};
+
+use crate::{
+ DecodedImage, Dimensions, ImageError, ImageResult,
+ decode::{decode_image_from_bytes, decode_image_from_path},
+};
+
+pub enum ImageInput<'a> {
+ Path(&'a str),
+ Bytes(&'a [u8]),
+}
+
+#[derive(Clone, Debug)]
+pub struct BoundedDecodedImage {
+ pub image: DecodedImage,
+ pub original_dimensions: Dimensions,
+}
+
+pub fn decode_bounded(input: ImageInput<'_>, max_side: u32) -> ImageResult<BoundedDecodedImage> {
+ if max_side == 0 {
+ return Err(ImageError::Postprocess(
+ "maximum side must be greater than zero".into(),
+ ));
+ }
+ let decoded = match input {
+ ImageInput::Path(path) => {
+ let file = File::open(path).map_err(|error| {
+ ImageError::Decode(format!("failed to open image file '{path}': {error}"))
+ })?;
+ let mut reader = BufReader::new(file);
+ let header = reader
+ .fill_buf()
+ .map_err(|error| ImageError::Decode(error.to_string()))?;
+ if header.starts_with(crate::png::SIGNATURE) {
+ return crate::png::decode(reader, max_side);
+ }
+ decode_image_from_path(path)?
+ }
+ ImageInput::Bytes(bytes) => {
+ if bytes.starts_with(crate::png::SIGNATURE) {
+ return crate::png::decode(Cursor::new(bytes), max_side);
+ }
+ decode_image_from_bytes(bytes)?
+ }
+ };
+ let original_dimensions = decoded.dimensions.clone();
+ let dimensions = target_dimensions(&original_dimensions, max_side);
+ if dimensions == original_dimensions {
+ return Ok(BoundedDecodedImage {
+ image: decoded,
+ original_dimensions,
+ });
+ }
+ let source = image::RgbImage::from_raw(
+ original_dimensions.width,
+ original_dimensions.height,
+ decoded.rgb,
+ )
+ .ok_or_else(|| ImageError::Postprocess("invalid decoded RGB buffer".into()))?;
+ let resized = DynamicImage::ImageRgb8(source)
+ .resize_exact(dimensions.width, dimensions.height, FilterType::Triangle)
+ .into_rgb8();
+ Ok(BoundedDecodedImage {
+ image: DecodedImage {
+ dimensions,
+ rgb: resized.into_raw(),
+ },
+ original_dimensions,
+ })
+}
+
+pub(crate) fn target_dimensions(source: &Dimensions, max_side: u32) -> Dimensions {
+ let longest = source.width.max(source.height);
+ if longest <= max_side {
+ return source.clone();
+ }
+ let scale = |side| ((u64::from(side) * u64::from(max_side)) / u64::from(longest)).max(1) as u32;
+ Dimensions {
+ width: scale(source.width),
+ height: scale(source.height),
+ }
+}
diff --git a/rust/crates/image/src/color_management.rs b/rust/crates/image/src/color_management.rs
index ad6fd85e62..217fdb2eb0 100644
--- a/rust/crates/image/src/color_management.rs
+++ b/rust/crates/image/src/color_management.rs
@@ -1,7 +1,8 @@
use image::{DynamicImage, ImageBuffer, Pixel};
use moxcms::{
ColorProfile, DataColorSpace, InPlaceTransformExecutor, Layout, ToneReprCurve,
- TransferCharacteristics, TransformOptions, Xyzd,
+ TransferCharacteristics, Transform8BitExecutor, Transform16BitExecutor, TransformF32Executor,
+ TransformOptions, Xyzd,
};
use std::{
collections::VecDeque,
@@ -16,6 +17,49 @@ const ICC_PROFILE_CACHE_CAPACITY: usize = 8;
const MAX_CACHEABLE_ICC_PROFILE_BYTES: usize = 4 * 1024 * 1024;
type U8Transform = Arc<dyn InPlaceTransformExecutor<u8> + Send + Sync>;
+type TransformCache<T> = Vec<(Layout, Result<Arc<T>, String>)>;
+
+#[derive(Default)]
+struct IccTransforms {
+ u8_in_place: TransformCache<dyn InPlaceTransformExecutor<u8> + Send + Sync>,
+ u8_out_of_place: TransformCache<Transform8BitExecutor>,
+ u16: TransformCache<Transform16BitExecutor>,
+ f32: TransformCache<TransformF32Executor>,
+}
+
+pub(crate) struct IccConverter<'a> {
+ source_profile: Option<Arc<ColorProfile>>,
+ encoded_profile: &'a [u8],
+ transforms: IccTransforms,
+}
+
+impl<'a> IccConverter<'a> {
+ pub(crate) fn new(icc_profile: Option<&'a [u8]>) -> Self {
+ Self {
+ source_profile: conversion_profile(icc_profile),
+ encoded_profile: icc_profile.unwrap_or_default(),
+ transforms: IccTransforms::default(),
+ }
+ }
+
+ pub(crate) fn apply(&mut self, image: DynamicImage) -> DynamicImage {
+ let Some(source_profile) = &self.source_profile else {
+ return image;
+ };
+ match apply_profile_to_image(
+ image,
+ source_profile,
+ self.encoded_profile,
+ &mut self.transforms,
+ ) {
+ Ok(image) => image,
+ Err((image, err)) => {
+ eprintln!("[ml][decode] failed to convert embedded ICC profile to sRGB: {err}");
+ image
+ }
+ }
+ }
+}
struct CachedIccProfile {
encoded: Arc<[u8]>,
@@ -27,85 +71,124 @@ pub(crate) fn apply_icc_profile_to_srgb(
image: DynamicImage,
icc_profile: Option<&[u8]>,
) -> DynamicImage {
- let Some(icc_profile) = icc_profile.filter(|profile| !profile.is_empty()) else {
- return image;
- };
+ IccConverter::new(icc_profile).apply(image)
+}
+
+fn conversion_profile(icc_profile: Option<&[u8]>) -> Option<Arc<ColorProfile>> {
+ let icc_profile = icc_profile.filter(|profile| !profile.is_empty())?;
let source_profile = match cached_color_profile(icc_profile) {
Ok(profile) => profile,
Err(err) => {
eprintln!("[ml][decode] failed to parse embedded ICC profile: {err}");
- return image;
+ return None;
}
};
if profile_is_effectively_srgb(&source_profile) {
- return image;
+ return None;
}
if profile_uses_hdr_transfer(&source_profile) {
eprintln!(
"[ml][decode] embedded ICC profile uses PQ/HLG transfer; skipping ICC transform because tone mapping is not implemented"
);
- return image;
+ return None;
}
- match apply_profile_to_image(image, &source_profile, icc_profile) {
- Ok(image) => image,
- Err((image, err)) => {
- eprintln!("[ml][decode] failed to convert embedded ICC profile to sRGB: {err}");
- image
- }
- }
+ Some(source_profile)
}
fn apply_profile_to_image(
image: DynamicImage,
source_profile: &ColorProfile,
encoded_profile: &[u8],
+ transforms: &mut IccTransforms,
) -> Result<DynamicImage, (DynamicImage, String)> {
use DynamicImage::*;
use Layout::{Gray, GrayAlpha, Rgb, Rgba};
match image {
- ImageLuma8(buffer) => {
- transform_buffer(buffer, source_profile, encoded_profile, Gray, ImageLuma8)
- }
+ ImageLuma8(buffer) => transform_buffer(
+ buffer,
+ source_profile,
+ encoded_profile,
+ transforms,
+ Gray,
+ ImageLuma8,
+ ),
ImageLumaA8(buffer) => transform_buffer(
buffer,
source_profile,
encoded_profile,
+ transforms,
GrayAlpha,
ImageLumaA8,
),
- ImageRgb8(buffer) => {
- transform_buffer(buffer, source_profile, encoded_profile, Rgb, ImageRgb8)
- }
- ImageRgba8(buffer) => {
- transform_buffer(buffer, source_profile, encoded_profile, Rgba, ImageRgba8)
- }
- ImageLuma16(buffer) => {
- transform_buffer(buffer, source_profile, encoded_profile, Gray, ImageLuma16)
- }
+ ImageRgb8(buffer) => transform_buffer(
+ buffer,
+ source_profile,
+ encoded_profile,
+ transforms,
+ Rgb,
+ ImageRgb8,
+ ),
+ ImageRgba8(buffer) => transform_buffer(
+ buffer,
+ source_profile,
+ encoded_profile,
+ transforms,
+ Rgba,
+ ImageRgba8,
+ ),
+ ImageLuma16(buffer) => transform_buffer(
+ buffer,
+ source_profile,
+ encoded_profile,
+ transforms,
+ Gray,
+ ImageLuma16,
+ ),
ImageLumaA16(buffer) => transform_buffer(
buffer,
source_profile,
encoded_profile,
+ transforms,
GrayAlpha,
ImageLumaA16,
),
- ImageRgb16(buffer) => {
- transform_buffer(buffer, source_profile, encoded_profile, Rgb, ImageRgb16)
- }
- ImageRgba16(buffer) => {
- transform_buffer(buffer, source_profile, encoded_profile, Rgba, ImageRgba16)
- }
- ImageRgb32F(buffer) => {
- transform_buffer(buffer, source_profile, encoded_profile, Rgb, ImageRgb32F)
- }
- ImageRgba32F(buffer) => {
- transform_buffer(buffer, source_profile, encoded_profile, Rgba, ImageRgba32F)
- }
+ ImageRgb16(buffer) => transform_buffer(
+ buffer,
+ source_profile,
+ encoded_profile,
+ transforms,
+ Rgb,
+ ImageRgb16,
+ ),
+ ImageRgba16(buffer) => transform_buffer(
+ buffer,
+ source_profile,
+ encoded_profile,
+ transforms,
+ Rgba,
+ ImageRgba16,
+ ),
+ ImageRgb32F(buffer) => transform_buffer(
+ buffer,
+ source_profile,
+ encoded_profile,
+ transforms,
+ Rgb,
+ ImageRgb32F,
+ ),
+ ImageRgba32F(buffer) => transform_buffer(
+ buffer,
+ source_profile,
+ encoded_profile,
+ transforms,
+ Rgba,
+ ImageRgba32F,
+ ),
other => Ok(other),
}
}
@@ -114,6 +197,7 @@ fn transform_buffer<P>(
mut buffer: ImageBuffer<P, Vec<P::Subpixel>>,
source_profile: &ColorProfile,
encoded_profile: &[u8],
+ transforms: &mut IccTransforms,
layout: Layout,
into_dynamic: fn(ImageBuffer<P, Vec<P::Subpixel>>) -> DynamicImage,
) -> Result<DynamicImage, (DynamicImage, String)>
@@ -122,7 +206,13 @@ where
P::Subpixel: TransformSubpixel,
{
let (width, height) = buffer.dimensions();
- match P::Subpixel::transform_to_srgb(buffer.as_mut(), source_profile, encoded_profile, layout) {
+ match P::Subpixel::transform_to_srgb(
+ buffer.as_mut(),
+ source_profile,
+ encoded_profile,
+ transforms,
+ layout,
+ ) {
#[expect(
clippy::expect_used,
reason = "Color transforms preserve the source buffer length and dimensions"
@@ -141,6 +231,7 @@ trait TransformSubpixel: Copy {
pixels: &mut [Self],
source_profile: &ColorProfile,
encoded_profile: &[u8],
+ transforms: &mut IccTransforms,
layout: Layout,
) -> Result<Option<Vec<Self>>, String>;
}
@@ -150,22 +241,36 @@ impl TransformSubpixel for u8 {
pixels: &mut [Self],
source_profile: &ColorProfile,
encoded_profile: &[u8],
+ transforms: &mut IccTransforms,
layout: Layout,
) -> Result<Option<Vec<Self>>, String> {
// ICC gives A2B LUTs precedence, but moxcms executes them only out of
// place. Fall back to matrix/TRC without a default Perceptual LUT.
if profile_has_device_to_pcs_lut(source_profile)
- && let Ok(transformed) = transform_u8_out_of_place(pixels, source_profile, layout)
+ && let Ok(transformed) = transform_u8_out_of_place(
+ pixels,
+ source_profile,
+ &mut transforms.u8_out_of_place,
+ layout,
+ )
{
return Ok(Some(transformed));
}
- if let Ok(transform) = cached_u8_transform(encoded_profile, source_profile, layout) {
+ if let Ok(transform) = prepared_transform(&mut transforms.u8_in_place, layout, || {
+ cached_u8_transform(encoded_profile, source_profile, layout)
+ }) {
transform.transform(pixels).map_err(|err| err.to_string())?;
return Ok(None);
}
- transform_u8_out_of_place(pixels, source_profile, layout).map(Some)
+ transform_u8_out_of_place(
+ pixels,
+ source_profile,
+ &mut transforms.u8_out_of_place,
+ layout,
+ )
+ .map(Some)
}
}
@@ -174,12 +279,15 @@ impl TransformSubpixel for u16 {
pixels: &mut [Self],
source_profile: &ColorProfile,
_encoded_profile: &[u8],
+ transforms: &mut IccTransforms,
layout: Layout,
) -> Result<Option<Vec<Self>>, String> {
let target_profile = target_profile_for_layout(layout);
- let transform = source_profile
- .create_transform_16bit(layout, target_profile, layout, transform_options())
- .map_err(|err| err.to_string())?;
+ let transform = prepared_transform(&mut transforms.u16, layout, || {
+ source_profile
+ .create_transform_16bit(layout, target_profile, layout, transform_options())
+ .map_err(|err| err.to_string())
+ })?;
let mut transformed = vec![0; pixels.len()];
transform
.transform(pixels, &mut transformed)
@@ -193,12 +301,15 @@ impl TransformSubpixel for f32 {
pixels: &mut [Self],
source_profile: &ColorProfile,
_encoded_profile: &[u8],
+ transforms: &mut IccTransforms,
layout: Layout,
) -> Result<Option<Vec<Self>>, String> {
let target_profile = target_profile_for_layout(layout);
- let transform = source_profile
- .create_transform_f32(layout, target_profile, layout, transform_options())
- .map_err(|err| err.to_string())?;
+ let transform = prepared_transform(&mut transforms.f32, layout, || {
+ source_profile
+ .create_transform_f32(layout, target_profile, layout, transform_options())
+ .map_err(|err| err.to_string())
+ })?;
let mut transformed = vec![0.0; pixels.len()];
transform
.transform(pixels, &mut transformed)
@@ -207,6 +318,22 @@ impl TransformSubpixel for f32 {
}
}
+fn prepared_transform<T: ?Sized>(
+ cache: &mut TransformCache<T>,
+ layout: Layout,
+ create: impl FnOnce() -> Result<Arc<T>, String>,
+) -> Result<Arc<T>, String> {
+ if let Some((_, transform)) = cache
+ .iter()
+ .find(|(cached_layout, _)| *cached_layout == layout)
+ {
+ return transform.clone();
+ }
+ let transform = create();
+ cache.push((layout, transform.clone()));
+ transform
+}
+
fn cached_color_profile(encoded: &[u8]) -> Result<Arc<ColorProfile>, String> {
if !profile_is_cacheable(encoded) {
return ColorProfile::new_from_slice(encoded)
@@ -306,12 +433,15 @@ fn cache_u8_transform(encoded: &[u8], layout: Layout, transform: U8Transform) ->
fn transform_u8_out_of_place(
pixels: &[u8],
source_profile: &ColorProfile,
+ transforms: &mut TransformCache<Transform8BitExecutor>,
layout: Layout,
) -> Result<Vec<u8>, String> {
let target_profile = target_profile_for_layout(layout);
- let transform = source_profile
- .create_transform_8bit(layout, target_profile, layout, transform_options())
- .map_err(|err| err.to_string())?;
+ let transform = prepared_transform(transforms, layout, || {
+ source_profile
+ .create_transform_8bit(layout, target_profile, layout, transform_options())
+ .map_err(|err| err.to_string())
+ })?;
let mut transformed = vec![0; pixels.len()];
transform
.transform(pixels, &mut transformed)
@@ -494,7 +624,7 @@ mod tests {
TransformOptions, Vector3d,
};
- use super::{apply_icc_profile_to_srgb, profile_is_effectively_srgb};
+ use super::{IccConverter, apply_icc_profile_to_srgb, profile_is_effectively_srgb};
fn identity_a_to_b_lut() -> LutWarehouse {
let identity_curve = || ToneReprCurve::Lut(vec![0, u16::MAX]);
@@ -520,6 +650,53 @@ mod tests {
profile
}
+ #[test]
+ fn reused_converter_preserves_lut_precedence_and_matrix_fallback() {
+ let mut matrix_and_lut = ColorProfile::new_display_p3();
+ matrix_and_lut.lut_a_to_b_perceptual = Some(identity_a_to_b_lut());
+ let mut unusable_lut = ColorProfile::new_display_p3();
+ unusable_lut.lut_a_to_b_colorimetric = Some(identity_a_to_b_lut());
+ for profile in [matrix_and_lut, unusable_lut, lut_based_rgb_profile()] {
+ let icc = profile.encode().unwrap();
+ let parsed = ColorProfile::new_from_slice(&icc).unwrap();
+ let mut converter = IccConverter::new(Some(&icc));
+ for width in [1, 9, 3, 20, 1] {
+ for layout in [Layout::Rgb, Layout::Rgba] {
+ let channels = if layout == Layout::Rgb { 3 } else { 4 };
+ let pixels = (0..width * channels)
+ .map(|i| (i * 71) as u8)
+ .collect::<Vec<_>>();
+ let mut expected = pixels.clone();
+ if let Ok(transform) = parsed.create_transform_8bit(
+ layout,
+ &ColorProfile::new_srgb(),
+ layout,
+ TransformOptions::default(),
+ ) {
+ transform.transform(&pixels, &mut expected).unwrap();
+ } else {
+ parsed
+ .create_in_place_transform_8bit(
+ layout,
+ &ColorProfile::new_srgb(),
+ TransformOptions::default(),
+ )
+ .unwrap()
+ .transform(&mut expected)
+ .unwrap();
+ }
+ let image = if layout == Layout::Rgb {
+ DynamicImage::ImageRgb8(ImageBuffer::from_raw(width, 1, pixels).unwrap())
+ } else {
+ DynamicImage::ImageRgba8(ImageBuffer::from_raw(width, 1, pixels).unwrap())
+ };
+ let actual = converter.apply(image);
+ assert_eq!(actual.as_bytes(), expected);
+ }
+ }
+ }
+ }
+
#[test]
fn detects_generated_srgb_profile() {
let srgb = ColorProfile::new_srgb();
diff --git a/rust/crates/image/src/lib.rs b/rust/crates/image/src/lib.rs
index 97178fafb2..34dbc37e30 100644
--- a/rust/crates/image/src/lib.rs
+++ b/rust/crates/image/src/lib.rs
@@ -1,8 +1,11 @@
+mod bounded;
mod color_management;
pub mod decode;
pub mod error;
pub mod image_compression;
+mod png;
pub mod types;
+pub use bounded::{BoundedDecodedImage, ImageInput, decode_bounded};
pub use error::{ImageError, ImageResult};
pub use types::{DecodedImage, Dimensions};
diff --git a/rust/crates/image/src/png.rs b/rust/crates/image/src/png.rs
new file mode 100644
index 0000000000..0632b714a3
--- /dev/null
+++ b/rust/crates/image/src/png.rs
@@ -0,0 +1,811 @@
+use std::io::{BufRead, Seek};
+
+use image::{DynamicImage, ImageBuffer, metadata::Orientation};
+
+use crate::{
+ BoundedDecodedImage, DecodedImage, Dimensions, ImageError, ImageResult,
+ bounded::target_dimensions, color_management::IccConverter,
+};
+
+pub(crate) const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
+const DECODER_BYTES: usize = 32 * 1024 * 1024;
+const MAX_ROW_BYTES: u64 = 4 * 1024 * 1024;
+const MAX_BUFFER_BYTES: u64 = 512 * 1024 * 1024;
+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),
+];
+
+pub(crate) fn decode<R: BufRead + Seek>(
+ input: R,
+ max_side: u32,
+) -> ImageResult<BoundedDecodedImage> {
+ let mut decoder = ::png::Decoder::new_with_limits(
+ input,
+ ::png::Limits {
+ bytes: DECODER_BYTES,
+ },
+ );
+ decoder.set_ignore_text_chunk(true);
+ decoder.set_transformations(::png::Transformations::EXPAND);
+ let header = decoder.read_header_info().map_err(png_error)?;
+ let source = Dimensions {
+ width: header.width,
+ height: header.height,
+ };
+ let interlaced = header.interlaced;
+ let row_bytes = u64::from(source.width) * 8;
+ if row_bytes > MAX_ROW_BYTES {
+ return Err(too_large());
+ }
+ let target = target_dimensions(&source, max_side);
+ let mut output = Downsampler::new(source.clone(), target.clone(), interlaced, row_bytes)?;
+ let mut reader = decoder.read_info().map_err(png_error)?;
+ let profile = reader.info().icc_profile.clone();
+ let mut converter = IccConverter::new(profile.as_deref());
+ let orientation = reader
+ .info()
+ .exif_metadata
+ .as_deref()
+ .and_then(Orientation::from_exif_chunk)
+ .unwrap_or(Orientation::NoTransforms);
+ let (color, depth) = reader.output_color_type();
+ let plain = [(0, 0, 1, 1)];
+ let passes = if interlaced { &ADAM7[..] } else { &plain[..] };
+ for &(left, top, step_x, step_y) in passes {
+ if left >= source.width || top >= source.height {
+ continue;
+ }
+ let width = (source.width - left).div_ceil(step_x);
+ for y in (top..source.height).step_by(step_y as usize) {
+ let row = reader
+ .next_interlaced_row()
+ .map_err(png_error)?
+ .ok_or_else(|| {
+ ImageError::Decode("PNG ended before all rows were decoded".into())
+ })?;
+ let rgb = row_rgb(row.data(), width, color, depth, &mut converter)?;
+ output.push_row(&rgb, left, y, step_x);
+ }
+ output.finish_pass();
+ }
+ if reader.next_interlaced_row().map_err(png_error)?.is_some() {
+ return Err(ImageError::Decode("PNG contains unexpected rows".into()));
+ }
+ reader.finish().map_err(png_error)?;
+ let rgb = output.finish();
+ let buffer = image::RgbImage::from_raw(target.width, target.height, rgb)
+ .ok_or_else(|| ImageError::Postprocess("invalid bounded PNG buffer".into()))?;
+ let mut image = DynamicImage::ImageRgb8(buffer);
+ image.apply_orientation(orientation);
+ let image = image.into_rgb8();
+ let original_dimensions = match orientation {
+ Orientation::Rotate90
+ | Orientation::Rotate270
+ | Orientation::Rotate90FlipH
+ | Orientation::Rotate270FlipH => Dimensions {
+ width: source.height,
+ height: source.width,
+ },
+ _ => source,
+ };
+ Ok(BoundedDecodedImage {
+ image: DecodedImage {
+ dimensions: Dimensions {
+ width: image.width(),
+ height: image.height(),
+ },
+ rgb: image.into_raw(),
+ },
+ original_dimensions,
+ })
+}
+
+fn row_rgb(
+ bytes: &[u8],
+ width: u32,
+ color: ::png::ColorType,
+ depth: ::png::BitDepth,
+ converter: &mut IccConverter<'_>,
+) -> ImageResult<Vec<u8>> {
+ let invalid = || ImageError::Decode("invalid PNG row layout".into());
+ let image = match depth {
+ ::png::BitDepth::Eight => {
+ let data = bytes.to_vec();
+ match color {
+ ::png::ColorType::Grayscale => DynamicImage::ImageLuma8(
+ ImageBuffer::from_raw(width, 1, data).ok_or_else(invalid)?,
+ ),
+ ::png::ColorType::GrayscaleAlpha => DynamicImage::ImageLumaA8(
+ ImageBuffer::from_raw(width, 1, data).ok_or_else(invalid)?,
+ ),
+ ::png::ColorType::Rgb => DynamicImage::ImageRgb8(
+ ImageBuffer::from_raw(width, 1, data).ok_or_else(invalid)?,
+ ),
+ ::png::ColorType::Rgba => DynamicImage::ImageRgba8(
+ ImageBuffer::from_raw(width, 1, data).ok_or_else(invalid)?,
+ ),
+ _ => return Err(invalid()),
+ }
+ }
+ ::png::BitDepth::Sixteen => {
+ let data = bytes
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .map(|sample| u16::from_be_bytes([sample[0], sample[1]]))
+ .collect::<Vec<_>>();
+ match color {
+ ::png::ColorType::Grayscale => DynamicImage::ImageLuma16(
+ ImageBuffer::from_raw(width, 1, data).ok_or_else(invalid)?,
+ ),
+ ::png::ColorType::GrayscaleAlpha => DynamicImage::ImageLumaA16(
+ ImageBuffer::from_raw(width, 1, data).ok_or_else(invalid)?,
+ ),
+ ::png::ColorType::Rgb => DynamicImage::ImageRgb16(
+ ImageBuffer::from_raw(width, 1, data).ok_or_else(invalid)?,
+ ),
+ ::png::ColorType::Rgba => DynamicImage::ImageRgba16(
+ ImageBuffer::from_raw(width, 1, data).ok_or_else(invalid)?,
+ ),
+ _ => return Err(invalid()),
+ }
+ }
+ _ => return Err(invalid()),
+ };
+ Ok(converter.apply(image).into_rgb8().into_raw())
+}
+
+struct Downsampler {
+ source: Dimensions,
+ target: Dimensions,
+ rgb: Vec<u8>,
+ sums: Vec<[f64; 3]>,
+ interlaced_sums: Vec<[f32; 3]>,
+ row_sums: Vec<[f64; 3]>,
+ interlaced: bool,
+ completed_rows: u32,
+}
+
+impl Downsampler {
+ fn new(
+ source: Dimensions,
+ target: Dimensions,
+ interlaced: bool,
+ row_bytes: u64,
+ ) -> ImageResult<Self> {
+ let pixels = u64::from(target.width) * u64::from(target.height);
+ let sum_rows = if source == target {
+ 0
+ } else {
+ target.height.min(2)
+ };
+ let sum_pixels = u64::from(target.width) * u64::from(sum_rows);
+ let interlaced_pixels = if interlaced && sum_rows > 0 {
+ pixels
+ } else {
+ 0
+ };
+ let sum_bytes = interlaced_pixels
+ .checked_mul(12)
+ .and_then(|size| size.checked_add(sum_pixels * 24))
+ .ok_or_else(too_large)?;
+ let required = pixels
+ .checked_mul(6)
+ .and_then(|size| size.checked_add(sum_bytes))
+ .and_then(|size| {
+ size.checked_add(
+ row_bytes * 4 + DECODER_BYTES as u64 + u64::from(target.width) * 24,
+ )
+ })
+ .ok_or_else(too_large)?;
+ if required > MAX_BUFFER_BYTES {
+ return Err(too_large());
+ }
+ let row_sums = zeroed(if sum_rows == 0 {
+ 0
+ } else {
+ target.width as usize
+ })?;
+ Ok(Self {
+ source,
+ target,
+ rgb: zeroed((pixels * 3) as usize)?,
+ sums: zeroed(sum_pixels as usize)?,
+ interlaced_sums: zeroed(interlaced_pixels as usize)?,
+ row_sums,
+ interlaced,
+ completed_rows: 0,
+ })
+ }
+
+ fn push_row(&mut self, rgb: &[u8], left: u32, y: u32, step_x: u32) {
+ if self.sums.is_empty() {
+ for (index, pixel) in rgb.as_chunks::<3>().0.iter().enumerate() {
+ let x = left as usize + index * step_x as usize;
+ let offset = (y as usize * self.target.width as usize + x) * 3;
+ self.rgb[offset..offset + 3].copy_from_slice(pixel);
+ }
+ return;
+ }
+ self.finish_rows(
+ (u64::from(y) * u64::from(self.target.height) / u64::from(self.source.height)) as u32,
+ );
+ let ys = contributions(y, self.source.height, self.target.height);
+ self.row_sums.fill([0.0; 3]);
+ for (index, pixel) in rgb.as_chunks::<3>().0.iter().enumerate() {
+ let x = left + index as u32 * step_x;
+ for (dest_x, weight_x) in contributions(x, self.source.width, self.target.width) {
+ if weight_x == 0.0 {
+ continue;
+ }
+ for (channel, &value) in pixel.iter().enumerate() {
+ self.row_sums[dest_x as usize][channel] += f64::from(value) * weight_x;
+ }
+ }
+ }
+ for (dest_y, weight_y) in ys {
+ if weight_y == 0.0 {
+ continue;
+ }
+ let row = dest_y % 2;
+ for dest_x in 0..self.target.width {
+ let sum = &mut self.sums[(row * self.target.width + dest_x) as usize];
+ for (channel, value) in sum.iter_mut().enumerate() {
+ *value += self.row_sums[dest_x as usize][channel] * weight_y;
+ }
+ }
+ }
+ let complete = ((u64::from(y) + 1) * u64::from(self.target.height)
+ / u64::from(self.source.height)) as u32;
+ self.finish_rows(complete);
+ }
+
+ fn finish_rows(&mut self, complete: u32) {
+ while self.completed_rows < complete {
+ self.finish_row(self.completed_rows);
+ self.completed_rows += 1;
+ }
+ }
+
+ fn finish_row(&mut self, y: u32) {
+ let row = y % 2;
+ for x in 0..self.target.width {
+ let sum = &mut self.sums[(row * self.target.width + x) as usize];
+ let index = (y * self.target.width + x) as usize;
+ for (channel, &value) in sum.iter().enumerate() {
+ if self.interlaced {
+ self.interlaced_sums[index][channel] += value as f32;
+ } else {
+ self.rgb[index * 3 + channel] = value.round().clamp(0.0, 255.0) as u8;
+ }
+ }
+ *sum = [0.0; 3];
+ }
+ }
+
+ fn finish_pass(&mut self) {
+ if !self.sums.is_empty() {
+ self.finish_rows(self.target.height);
+ self.completed_rows = 0;
+ }
+ }
+
+ fn finish(mut self) -> Vec<u8> {
+ for (pixel, sum) in self
+ .rgb
+ .as_chunks_mut::<3>()
+ .0
+ .iter_mut()
+ .zip(self.interlaced_sums)
+ {
+ for (channel, value) in sum.into_iter().enumerate() {
+ pixel[channel] = value.round().clamp(0.0, 255.0) as u8;
+ }
+ }
+ self.rgb
+ }
+}
+
+fn contributions(position: u32, source: u32, target: u32) -> [(u32, f64); 2] {
+ let start = u64::from(position) * u64::from(target);
+ let end = start + u64::from(target);
+ let first = start / u64::from(source);
+ let boundary = (first + 1) * u64::from(source);
+ let first_weight = (end.min(boundary) - start) as f64 / source as f64;
+ let second_weight = end.saturating_sub(boundary) as f64 / source as f64;
+ [
+ (first as u32, first_weight),
+ (first as u32 + 1, second_weight),
+ ]
+}
+
+fn zeroed<T: Default + Clone>(length: usize) -> ImageResult<Vec<T>> {
+ let mut buffer = Vec::new();
+ buffer.try_reserve_exact(length).map_err(|_| too_large())?;
+ buffer.resize(length, T::default());
+ Ok(buffer)
+}
+
+fn too_large() -> ImageError {
+ image::ImageError::Limits(image::error::LimitError::from_kind(
+ image::error::LimitErrorKind::InsufficientMemory,
+ ))
+ .into()
+}
+
+fn png_error(error: ::png::DecodingError) -> ImageError {
+ if matches!(error, ::png::DecodingError::LimitsExceeded) {
+ too_large()
+ } else {
+ ImageError::Decode(error.to_string())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::{
+ borrow::Cow,
+ fs::File,
+ io::Write,
+ time::{Duration, Instant},
+ };
+
+ use super::*;
+ use crate::{ImageInput, decode::decode_image_from_bytes, decode_bounded};
+
+ fn fixture(info: ::png::Info<'_>, pixels: &[u8]) -> Vec<u8> {
+ let mut bytes = Vec::new();
+ let interlaced = info.interlaced;
+ let width = info.width;
+ let height = info.height;
+ let pixel_bytes = info.color_type.samples()
+ * if info.bit_depth == ::png::BitDepth::Sixteen {
+ 2
+ } else {
+ 1
+ };
+ let mut writer = ::png::Encoder::with_info(&mut bytes, info)
+ .unwrap()
+ .write_header()
+ .unwrap();
+ if interlaced {
+ let mut filtered = Vec::new();
+ for (left, top, step_x, step_y) in ADAM7 {
+ if left >= width || top >= height {
+ continue;
+ }
+ for y in (top..height).step_by(step_y as usize) {
+ filtered.push(0);
+ for x in (left..width).step_by(step_x as usize) {
+ let offset = (y * width + x) as usize * pixel_bytes;
+ filtered.extend_from_slice(&pixels[offset..offset + pixel_bytes]);
+ }
+ }
+ }
+ let mut compressed = vec![0x78, 0x01];
+ let mut blocks = filtered.chunks(u16::MAX as usize).peekable();
+ while let Some(block) = blocks.next() {
+ let length = u16::try_from(block.len()).unwrap();
+ compressed.push(u8::from(blocks.peek().is_none()));
+ compressed.extend_from_slice(&length.to_le_bytes());
+ compressed.extend_from_slice(&(!length).to_le_bytes());
+ compressed.extend_from_slice(block);
+ }
+ let (mut a, mut b) = (1u32, 0u32);
+ for byte in filtered {
+ a = (a + u32::from(byte)) % 65521;
+ b = (b + a) % 65521;
+ }
+ compressed.extend_from_slice(&((b << 16) | a).to_be_bytes());
+ writer.write_chunk(::png::chunk::IDAT, &compressed).unwrap();
+ } else {
+ writer.write_image_data(pixels).unwrap();
+ }
+ writer.finish().unwrap();
+ bytes
+ }
+
+ fn rgb_info(width: u32, height: u32, interlaced: bool) -> ::png::Info<'static> {
+ let mut info = ::png::Info::with_size(width, height);
+ info.color_type = ::png::ColorType::Rgb;
+ info.bit_depth = ::png::BitDepth::Eight;
+ info.interlaced = interlaced;
+ info
+ }
+
+ fn area_reference(pixels: &[u8], width: u32, height: u32, target: &Dimensions) -> Vec<u8> {
+ let mut result = Vec::new();
+ for y in 0..target.height {
+ for x in 0..target.width {
+ let x0 = x as f64 * width as f64 / target.width as f64;
+ let x1 = (x + 1) as f64 * width as f64 / target.width as f64;
+ let y0 = y as f64 * height as f64 / target.height as f64;
+ let y1 = (y + 1) as f64 * height as f64 / target.height as f64;
+ let mut sums = [0.0f64; 3];
+ for sy in y0.floor() as u32..y1.ceil() as u32 {
+ for sx in x0.floor() as u32..x1.ceil() as u32 {
+ let weight = (x1.min((sx + 1) as f64) - x0.max(sx as f64))
+ * (y1.min((sy + 1) as f64) - y0.max(sy as f64));
+ for channel in 0..3 {
+ sums[channel] +=
+ f64::from(pixels[((sy * width + sx) * 3) as usize + channel])
+ * weight;
+ }
+ }
+ }
+ for sum in sums {
+ result.push((sum / ((x1 - x0) * (y1 - y0))).round() as u8);
+ }
+ }
+ }
+ result
+ }
+
+ #[test]
+ fn streamed_rows_match_area_reference_including_adam7_and_thin_images() {
+ for (width, height) in [(1, 19), (19, 1), (2, 3), (13, 17), (31, 23)] {
+ let pixels = (0..width * height * 3)
+ .map(|i| ((i * 37 + 11) % 256) as u8)
+ .collect::<Vec<_>>();
+ for interlaced in [false, true] {
+ let bytes = fixture(rgb_info(width, height, interlaced), &pixels);
+ assert_eq!(decode_image_from_bytes(&bytes).unwrap().rgb, pixels);
+ for max_side in [1, 2, 7, 13, 40] {
+ let decoded = decode_bounded(ImageInput::Bytes(&bytes), max_side).unwrap();
+ let reference =
+ area_reference(&pixels, width, height, &decoded.image.dimensions);
+ assert_eq!(decoded.original_dimensions, Dimensions { width, height });
+ assert!(
+ decoded
+ .image
+ .dimensions
+ .width
+ .max(decoded.image.dimensions.height)
+ <= max_side
+ );
+ for (actual, expected) in decoded.image.rgb.iter().zip(reference) {
+ assert!(
+ actual.abs_diff(expected) <= 1,
+ "{width}x{height}, max {max_side}, interlaced {interlaced}: {actual} != {expected}"
+ );
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn extreme_downsampling_preserves_constant_colors() {
+ let source = Dimensions {
+ width: 1,
+ height: 1_000_000,
+ };
+ for interlaced in [false, true] {
+ let mut output = Downsampler::new(
+ source.clone(),
+ Dimensions {
+ width: 1,
+ height: 1,
+ },
+ interlaced,
+ 8,
+ )
+ .unwrap();
+ let plain = [(0, 0, 1, 1)];
+ let passes = if interlaced { &ADAM7[..] } else { &plain[..] };
+ for &(left, top, step_x, step_y) in passes {
+ if left >= source.width {
+ continue;
+ }
+ for y in (top..source.height).step_by(step_y as usize) {
+ output.push_row(&[128, 127, 254], left, y, step_x);
+ }
+ output.finish_pass();
+ }
+ assert_eq!(output.finish(), [128, 127, 254]);
+ }
+ }
+
+ #[test]
+ fn apng_returns_the_default_image() {
+ let mut bytes = Vec::new();
+ let mut encoder = ::png::Encoder::new(&mut bytes, 4, 2);
+ encoder.set_color(::png::ColorType::Rgb);
+ encoder.set_animated(2, 0).unwrap();
+ let mut writer = encoder.write_header().unwrap();
+ writer.write_image_data(&[80; 4 * 2 * 3]).unwrap();
+ writer.write_image_data(&[120; 4 * 2 * 3]).unwrap();
+ writer.finish().unwrap();
+ let output = decode_bounded(ImageInput::Bytes(&bytes), 2).unwrap();
+ assert_eq!(output.image.rgb, [80; 2 * 3]);
+ }
+
+ #[test]
+ fn color_types_depths_and_icc_match_existing_decoder_before_downsampling() {
+ for color in [
+ ::png::ColorType::Grayscale,
+ ::png::ColorType::GrayscaleAlpha,
+ ::png::ColorType::Rgb,
+ ::png::ColorType::Rgba,
+ ] {
+ for depth in [::png::BitDepth::Eight, ::png::BitDepth::Sixteen] {
+ for interlaced in [false, true] {
+ let mut info = rgb_info(9, 7, interlaced);
+ info.color_type = color;
+ info.bit_depth = depth;
+ let profile = if matches!(
+ color,
+ ::png::ColorType::Grayscale | ::png::ColorType::GrayscaleAlpha
+ ) {
+ moxcms::ColorProfile::new_gray_with_gamma(1.8)
+ } else {
+ moxcms::ColorProfile::new_display_p3()
+ };
+ info.icc_profile = Some(Cow::Owned(profile.encode().unwrap()));
+ let count = 9
+ * 7
+ * color.samples()
+ * if depth == ::png::BitDepth::Sixteen {
+ 2
+ } else {
+ 1
+ };
+ let pixels = (0..count)
+ .map(|i| ((i * 71) % 256) as u8)
+ .collect::<Vec<_>>();
+ let bytes = fixture(info, &pixels);
+ let full = decode_image_from_bytes(&bytes).unwrap();
+ for max_side in [4, 6000] {
+ let bounded = decode_bounded(ImageInput::Bytes(&bytes), max_side).unwrap();
+ if max_side == 6000 {
+ assert_eq!(bounded.image.rgb, full.rgb);
+ } else {
+ let expected =
+ area_reference(&full.rgb, 9, 7, &bounded.image.dimensions);
+ assert_eq!(bounded.image.rgb.len(), expected.len());
+ for (actual, expected) in bounded.image.rgb.iter().zip(expected) {
+ assert!(
+ actual.abs_diff(expected) <= 1,
+ "{color:?} {depth:?} {interlaced}: {actual} != {expected}"
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn streamed_rows_preserve_pixels_for_ignored_icc_profiles() {
+ let mut pq = moxcms::ColorProfile::new_display_p3_pq();
+ pq.cicp = None;
+ let mut hlg = moxcms::ColorProfile::new_bt2020_hlg();
+ hlg.cicp = None;
+ let pixels = (0..9 * 7 * 3).map(|i| (i * 71) as u8).collect::<Vec<_>>();
+ for profile in [
+ None,
+ Some(b"invalid ICC profile".to_vec()),
+ Some(moxcms::ColorProfile::new_srgb().encode().unwrap()),
+ Some(pq.encode().unwrap()),
+ Some(hlg.encode().unwrap()),
+ ] {
+ for interlaced in [false, true] {
+ let mut info = rgb_info(9, 7, interlaced);
+ info.icc_profile = profile.clone().map(Cow::Owned);
+ let bytes = fixture(info, &pixels);
+ for max_side in [4, 6000] {
+ let bounded = decode_bounded(ImageInput::Bytes(&bytes), max_side).unwrap();
+ let expected = area_reference(&pixels, 9, 7, &bounded.image.dimensions);
+ assert_eq!(bounded.image.rgb.len(), expected.len());
+ for (actual, expected) in bounded.image.rgb.iter().zip(expected) {
+ assert!(actual.abs_diff(expected) <= 1);
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn expands_packed_palette_transparency_and_grayscale() {
+ for color in [::png::ColorType::Indexed, ::png::ColorType::Grayscale] {
+ let mut info = rgb_info(8, 1, false);
+ info.color_type = color;
+ info.bit_depth = ::png::BitDepth::One;
+ if color == ::png::ColorType::Indexed {
+ info.palette = Some(Cow::Owned(vec![200, 20, 10, 10, 40, 220]));
+ info.trns = Some(Cow::Owned(vec![0, 255]));
+ }
+ let bytes = fixture(info, &[0b10101010]);
+ let full = decode_image_from_bytes(&bytes).unwrap();
+ let bounded = decode_bounded(ImageInput::Bytes(&bytes), 4).unwrap();
+ assert_eq!(
+ bounded.image.rgb,
+ area_reference(&full.rgb, 8, 1, &bounded.image.dimensions)
+ );
+ }
+ }
+
+ #[test]
+ fn applies_all_exif_orientations_after_downsampling() {
+ let pixels = (0..8 * 4 * 3).map(|i| (i * 7) as u8).collect::<Vec<_>>();
+ for orientation in 1..=8 {
+ let mut info = rgb_info(8, 4, true);
+ let mut exif = b"II\x2a\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0".to_vec();
+ exif.extend_from_slice(&[orientation, 0, 0, 0, 0, 0, 0, 0]);
+ info.exif_metadata = Some(Cow::Owned(exif));
+ let bytes = fixture(info, &pixels);
+ let full = decode_image_from_bytes(&bytes).unwrap();
+ let bounded = decode_bounded(ImageInput::Bytes(&bytes), 4).unwrap();
+ assert_eq!(bounded.original_dimensions, full.dimensions);
+ let expected = area_reference(
+ &full.rgb,
+ full.dimensions.width,
+ full.dimensions.height,
+ &bounded.image.dimensions,
+ );
+ assert_eq!(bounded.image.rgb, expected);
+ }
+ }
+
+ #[test]
+ fn path_sniffs_content_and_matches_bytes() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("image.jpg");
+ let bytes = fixture(rgb_info(11, 5, true), &[70; 11 * 5 * 3]);
+ std::fs::write(&path, &bytes).unwrap();
+ let from_path = decode_bounded(ImageInput::Path(path.to_str().unwrap()), 6).unwrap();
+ let from_bytes = decode_bounded(ImageInput::Bytes(&bytes), 6).unwrap();
+ assert_eq!(from_path.image.rgb, from_bytes.image.rgb);
+ assert_eq!(from_path.image.dimensions, from_bytes.image.dimensions);
+ }
+
+ #[test]
+ fn invalid_and_truncated_pngs_fail_without_fallback() {
+ let bytes = fixture(rgb_info(8, 4, false), &[80; 8 * 4 * 3]);
+ for length in [8, 20, bytes.len() / 2, bytes.len() - 1] {
+ assert!(
+ decode_bounded(ImageInput::Bytes(&bytes[..length]), 4).is_err(),
+ "length {length}"
+ );
+ }
+ let mut corrupt = bytes.clone();
+ let idat = corrupt
+ .windows(4)
+ .position(|window| window == b"IDAT")
+ .unwrap();
+ corrupt[idat + 6] ^= 0x55;
+ assert!(decode_bounded(ImageInput::Bytes(&corrupt), 4).is_err());
+ assert!(decode_bounded(ImageInput::Bytes(&bytes), 0).is_err());
+ }
+
+ #[test]
+ fn oversized_source_rows_and_output_buffers_are_rejected() {
+ let mut bytes = Vec::new();
+ let info = rgb_info(MAX_ROW_BYTES as u32 / 8 + 1, 1, false);
+ ::png::Encoder::with_info(&mut bytes, info)
+ .unwrap()
+ .write_header()
+ .unwrap()
+ .finish()
+ .unwrap();
+ assert!(matches!(
+ decode_bounded(ImageInput::Bytes(&bytes), 6000),
+ Err(ImageError::TooLarge(_))
+ ));
+ assert!(matches!(
+ Downsampler::new(
+ Dimensions {
+ width: 100_000,
+ height: 100_000
+ },
+ Dimensions {
+ width: 100_000,
+ height: 100_000
+ },
+ false,
+ 0
+ ),
+ Err(ImageError::TooLarge(_))
+ ));
+ }
+
+ #[test]
+ fn jpeg_fallback_caps_output_and_keeps_original_dimensions() {
+ let bytes = crate::image_compression::encode_rgb(
+ &[100; 12 * 8 * 3],
+ 12,
+ 8,
+ crate::image_compression::EncodedImageFormat::Jpeg { quality: 90 },
+ )
+ .unwrap();
+ let output = decode_bounded(ImageInput::Bytes(&bytes), 6).unwrap();
+ assert_eq!(
+ output.original_dimensions,
+ Dimensions {
+ width: 12,
+ height: 8
+ }
+ );
+ assert_eq!(
+ output.image.dimensions,
+ Dimensions {
+ width: 6,
+ height: 4
+ }
+ );
+ }
+
+ #[test]
+ #[ignore = "ICC streaming performance regression; run in release mode"]
+ fn profiled_png_decode_avoids_per_row_setup_cost() {
+ let pixels = (0..256 * 1024 * 6)
+ .map(|index| ((index * 71) % 256) as u8)
+ .collect::<Vec<_>>();
+ for interlaced in [false, true] {
+ let mut info = rgb_info(256, 1024, interlaced);
+ info.bit_depth = ::png::BitDepth::Sixteen;
+ info.icc_profile = Some(Cow::Owned(
+ moxcms::ColorProfile::new_display_p3().encode().unwrap(),
+ ));
+ let bytes = fixture(info, &pixels);
+ let start = Instant::now();
+ let full = decode_image_from_bytes(&bytes).unwrap();
+ let full_time = start.elapsed();
+ for max_side in [1024, 128] {
+ let start = Instant::now();
+ let bounded = decode_bounded(ImageInput::Bytes(&bytes), max_side).unwrap();
+ let bounded_time = start.elapsed();
+ if max_side == 1024 {
+ assert_eq!(bounded.image.rgb, full.rgb);
+ } else {
+ let expected = area_reference(&full.rgb, 256, 1024, &bounded.image.dimensions);
+ assert_eq!(bounded.image.rgb.len(), expected.len());
+ for (actual, expected) in bounded.image.rgb.iter().zip(expected) {
+ assert!(actual.abs_diff(expected) <= 1);
+ }
+ }
+ println!(
+ "interlaced {interlaced}, max_side {max_side}: bounded {bounded_time:?}, full {full_time:?}"
+ );
+ assert!(
+ bounded_time <= (full_time * 20).max(Duration::from_millis(100)),
+ "bounded decode took {bounded_time:?}, full decode took {full_time:?}"
+ );
+ }
+ }
+ }
+
+ #[test]
+ #[ignore = "200 MP streaming memory regression; run in release mode"]
+ fn streams_200_megapixels() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("large.png");
+ let mut encoder = ::png::Encoder::new(File::create(&path).unwrap(), 20_000, 10_000);
+ encoder.set_color(::png::ColorType::Rgb);
+ encoder.set_depth(::png::BitDepth::Eight);
+ let mut writer = encoder.write_header().unwrap();
+ let mut stream = writer.stream_writer().unwrap();
+ let row = vec![128u8; 20_000 * 3];
+ for _ in 0..10_000 {
+ stream.write_all(&row).unwrap();
+ }
+ stream.finish().unwrap();
+ writer.finish().unwrap();
+ let output = decode_bounded(ImageInput::Path(path.to_str().unwrap()), 6000).unwrap();
+ assert_eq!(
+ output.image.dimensions,
+ Dimensions {
+ width: 6000,
+ height: 3000
+ }
+ );
+ assert!(output.image.rgb.iter().all(|&value| value == 128));
+ }
+}