Skip to content

armgit / ente

Public Imported from GitHub
0

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

[rust] Stream HEIC grid images in bounded decoding (#14343)

laurens-pilotc2c7cab2d9de
diff --git a/rust/crates/image/src/bounded.rs b/rust/crates/image/src/bounded.rs
index 02492305cb..44a42c6dca 100644
--- a/rust/crates/image/src/bounded.rs
+++ b/rust/crates/image/src/bounded.rs
@@ -1,26 +1,51 @@
use std::{
fs::File,
- io::{BufRead, BufReader, Cursor},
+ io::{BufRead, BufReader, Cursor, Seek},
};
use crate::{DecodedImage, Dimensions, ImageError, ImageResult};
+const MAX_SIDE: u32 = 6000;
+
pub enum ImageInput<'a> {
Path(&'a str),
Bytes(&'a [u8]),
}
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct BoundedDecodeOptions {
+ pub max_side: u32,
+ pub max_memory_bytes: u64,
+}
+
+impl Default for BoundedDecodeOptions {
+ fn default() -> Self {
+ Self {
+ max_side: MAX_SIDE,
+ max_memory_bytes: 512 * 1024 * 1024,
+ }
+ }
+}
+
#[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(),
- ));
+enum Format {
+ Png,
+ Heif,
+}
+
+pub fn decode_bounded(
+ input: ImageInput<'_>,
+ options: BoundedDecodeOptions,
+) -> ImageResult<BoundedDecodedImage> {
+ if !(1..=MAX_SIDE).contains(&options.max_side) {
+ return Err(ImageError::Postprocess(format!(
+ "maximum side must be between 1 and {MAX_SIDE}"
+ )));
}
match input {
ImageInput::Path(path) => {
@@ -31,19 +56,64 @@ pub fn decode_bounded(input: ImageInput<'_>, max_side: u32) -> ImageResult<Bound
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);
- }
- }
- ImageInput::Bytes(bytes) => {
- if bytes.starts_with(crate::png::SIGNATURE) {
- return crate::png::decode(Cursor::new(bytes), max_side);
- }
+ decode_format(sniff(header), reader, input, options)
}
+ ImageInput::Bytes(bytes) => decode_format(sniff(bytes), Cursor::new(bytes), input, options),
+ }
+}
+
+fn sniff(header: &[u8]) -> Option<Format> {
+ if header.starts_with(crate::png::SIGNATURE) {
+ Some(Format::Png)
+ } else if has_heif_brand(header) {
+ Some(Format::Heif)
+ } else {
+ None
+ }
+}
+
+fn has_heif_brand(header: &[u8]) -> bool {
+ let Some((size, rest)) = header.split_first_chunk::<4>() else {
+ return false;
+ };
+ let Some((kind, rest)) = rest.split_first_chunk::<4>() else {
+ return false;
+ };
+ if kind != b"ftyp" {
+ return false;
+ }
+ let (box_size, header_size, brands) = if *size == [0, 0, 0, 1] {
+ let Some((large_size, brands)) = rest.split_first_chunk::<8>() else {
+ return false;
+ };
+ (u64::from_be_bytes(*large_size), 16, brands)
+ } else {
+ (u64::from(u32::from_be_bytes(*size)), 8, rest)
+ };
+ let length = usize::try_from(box_size.saturating_sub(header_size))
+ .unwrap_or(usize::MAX)
+ .min(brands.len());
+ brands[..length]
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .enumerate()
+ .any(|(index, brand)| index != 1 && matches!(brand, b"heic" | b"heix" | b"mif1"))
+}
+
+fn decode_format<R: BufRead + Seek>(
+ format: Option<Format>,
+ reader: R,
+ input: ImageInput<'_>,
+ options: BoundedDecodeOptions,
+) -> ImageResult<BoundedDecodedImage> {
+ match format {
+ Some(Format::Png) => crate::png::decode(reader, options),
+ Some(Format::Heif) => crate::heif::decode(input, options),
+ None => Err(ImageError::Decode(
+ "unsupported format for bounded decoding: only PNG and HEIC are supported".into(),
+ )),
}
- Err(ImageError::Decode(
- "unsupported format for bounded decoding: only PNG is currently supported".into(),
- ))
}
pub(crate) fn target_dimensions(source: &Dimensions, max_side: u32) -> Dimensions {
@@ -58,23 +128,47 @@ pub(crate) fn target_dimensions(source: &Dimensions, max_side: u32) -> Dimension
}
}
+pub(crate) fn too_large() -> ImageError {
+ image::ImageError::Limits(image::error::LimitError::from_kind(
+ image::error::LimitErrorKind::InsufficientMemory,
+ ))
+ .into()
+}
+
#[cfg(test)]
-mod tests {
+pub(crate) mod tests {
use super::*;
use crate::{
decode::decode_image_from_bytes,
image_compression::{EncodedImageFormat, encode_rgb},
};
+ pub(crate) fn options(max_side: u32) -> BoundedDecodeOptions {
+ BoundedDecodeOptions {
+ max_side,
+ ..BoundedDecodeOptions::default()
+ }
+ }
+
+ fn encode(format: EncodedImageFormat) -> Vec<u8> {
+ encode_rgb(&[100; 12 * 8 * 3], 12, 8, format).unwrap()
+ }
+
#[test]
- fn rejects_non_png_from_bytes_and_paths_without_affecting_existing_decode() {
- let jpeg = encode_rgb(
- &[100; 12 * 8 * 3],
- 12,
- 8,
- EncodedImageFormat::Jpeg { quality: 90 },
- )
- .unwrap();
+ fn rejects_max_side_outside_supported_range() {
+ let png = encode(EncodedImageFormat::Png);
+ assert!(decode_bounded(ImageInput::Bytes(&png), options(MAX_SIDE)).is_ok());
+ for max_side in [0, MAX_SIDE + 1] {
+ assert!(matches!(
+ decode_bounded(ImageInput::Bytes(&png), options(max_side)),
+ Err(ImageError::Postprocess(_))
+ ));
+ }
+ }
+
+ #[test]
+ fn rejects_unsupported_formats_from_bytes_and_paths_without_affecting_existing_decode() {
+ let jpeg = encode(EncodedImageFormat::Jpeg { quality: 90 });
assert_eq!(
decode_image_from_bytes(&jpeg).unwrap().dimensions,
Dimensions {
@@ -86,7 +180,9 @@ mod tests {
let path = directory.path().join("image.png");
for bytes in [
jpeg.as_slice(),
- b"\0\0\0\x18ftypheic\0\0\0\0",
+ b"GIF89a\x01\0\x01\0\0\0\0;",
+ b"\0\0\0\x14ftypisom\0\0\0\0isom",
+ b"\0\0\0\x10ftypisomheic",
b"not an image",
b"",
] {
@@ -96,10 +192,24 @@ mod tests {
ImageInput::Path(path.to_str().unwrap()),
] {
assert!(matches!(
- decode_bounded(input, 6000),
+ decode_bounded(input, options(MAX_SIDE)),
Err(ImageError::Decode(message)) if message.contains("unsupported format")
));
}
}
}
+
+ #[test]
+ fn heif_brands_route_to_the_heif_decoder() {
+ for bytes in [
+ &b"\0\0\0\x18ftypheic\0\0\0\0mif1heic"[..],
+ b"\0\0\0\x18ftypmiaf\0\0\0\0mif1heic",
+ b"\0\0\0\x01ftyp\0\0\0\0\0\0\0\x18heic\0\0\0\0",
+ ] {
+ assert!(matches!(
+ decode_bounded(ImageInput::Bytes(bytes), options(MAX_SIDE)),
+ Err(ImageError::Decode(message)) if !message.contains("unsupported format")
+ ));
+ }
+ }
}
diff --git a/rust/crates/image/src/heif.rs b/rust/crates/image/src/heif.rs
new file mode 100644
index 0000000000..53e5266275
--- /dev/null
+++ b/rust/crates/image/src/heif.rs
@@ -0,0 +1,163 @@
+use std::path::Path;
+
+use ente_heic::{BoundedDecodeError, BoundedInput};
+
+use crate::{
+ BoundedDecodeOptions, BoundedDecodedImage, DecodedImage, Dimensions, ImageError, ImageInput,
+ ImageResult, bounded::too_large,
+};
+
+pub(crate) fn decode(
+ input: ImageInput<'_>,
+ options: BoundedDecodeOptions,
+) -> ImageResult<BoundedDecodedImage> {
+ let source = match input {
+ ImageInput::Path(path) => BoundedInput::Path(Path::new(path)),
+ ImageInput::Bytes(bytes) => BoundedInput::Bytes(bytes),
+ };
+ let heic_options = ente_heic::BoundedDecodeOptions {
+ max_side: options.max_side,
+ max_memory_bytes: usize::try_from(options.max_memory_bytes).unwrap_or(usize::MAX),
+ };
+ match ente_heic::decode_bounded(source, heic_options) {
+ Ok(decoded) => Ok(BoundedDecodedImage {
+ image: DecodedImage {
+ dimensions: Dimensions {
+ width: decoded.image.width,
+ height: decoded.image.height,
+ },
+ rgb: decoded.image.pixels,
+ },
+ original_dimensions: Dimensions {
+ width: decoded.original_dimensions.0,
+ height: decoded.original_dimensions.1,
+ },
+ }),
+ Err(
+ BoundedDecodeError::LimitExceeded(_)
+ | BoundedDecodeError::MemoryBudgetExceeded { .. }
+ | BoundedDecodeError::AllocationFailed,
+ ) => Err(too_large()),
+ Err(error @ BoundedDecodeError::InvalidOptions(_)) => {
+ Err(ImageError::Postprocess(error.to_string()))
+ }
+ Err(
+ error @ (BoundedDecodeError::Io(_)
+ | BoundedDecodeError::Unsupported(_)
+ | BoundedDecodeError::Malformed(_)
+ | BoundedDecodeError::Decode(_)),
+ ) => Err(ImageError::Decode(error.to_string())),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::path::PathBuf;
+
+ use super::*;
+ use crate::{
+ bounded::{target_dimensions, tests::options},
+ decode::decode_image_from_path,
+ decode_bounded,
+ resample::tests::area_reference,
+ };
+
+ const GRID_FIXTURES: [&str; 3] = [
+ "IMG_0983.HEIC",
+ "IMG_0682_pano.HEIC",
+ "IMG_8606_rotate_90_cw_contains_text.HEIC",
+ ];
+
+ const NON_GRID_FIXTURES: [&str; 3] = [
+ "1718_rotate_90_cw.HEIC",
+ "7765_horizontal_normal.HEIC",
+ "7949_mirror_horizontal_rotate_270_cw.HEIC",
+ ];
+
+ fn fixtures_dir() -> Option<PathBuf> {
+ if let Some(path) = std::env::var_os("ENTE_TEST_FIXTURES_DIR") {
+ return Some(PathBuf::from(path));
+ }
+ let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
+ let repo_root = manifest_dir.parent()?.parent()?.parent()?;
+ Some(repo_root.parent()?.join("test-fixtures"))
+ }
+
+ fn heic_fixtures_dir() -> Option<PathBuf> {
+ fixtures_dir()
+ .map(|path| path.join("media/heic/v1/files"))
+ .filter(|path| path.exists())
+ }
+
+ #[test]
+ fn memory_budget_failures_are_too_large() {
+ let bytes = b"\0\0\0\x18ftypheic\0\0\0\0mif1heic\0\0\0\x0cmeta\0\0\0\0";
+ assert!(matches!(
+ decode_bounded(
+ ImageInput::Bytes(bytes),
+ BoundedDecodeOptions {
+ max_memory_bytes: 64 * 1024,
+ ..BoundedDecodeOptions::default()
+ }
+ ),
+ Err(ImageError::TooLarge(_))
+ ));
+ assert!(matches!(
+ decode_bounded(ImageInput::Bytes(bytes), BoundedDecodeOptions::default()),
+ Err(ImageError::Decode(_))
+ ));
+ }
+
+ #[test]
+ fn non_grid_heic_fixtures_are_rejected_when_present() {
+ let Some(directory) = heic_fixtures_dir() else {
+ eprintln!("Skipping: external HEIC fixtures not present");
+ return;
+ };
+ for name in NON_GRID_FIXTURES {
+ let path = directory.join(name);
+ assert!(
+ matches!(
+ decode_bounded(ImageInput::Path(path.to_str().unwrap()), options(6000)),
+ Err(ImageError::Decode(_))
+ ),
+ "{name}"
+ );
+ }
+ }
+
+ #[test]
+ fn grid_heic_fixtures_match_the_full_decoder_when_present() {
+ let Some(directory) = heic_fixtures_dir() else {
+ eprintln!("Skipping: external HEIC fixtures not present");
+ return;
+ };
+ for name in GRID_FIXTURES {
+ let path = directory.join(name);
+ let path = path.to_str().unwrap();
+ let full = decode_image_from_path(path).unwrap();
+ for max_side in [6000, 97] {
+ let bounded = decode_bounded(ImageInput::Path(path), options(max_side)).unwrap();
+ assert_eq!(bounded.original_dimensions, full.dimensions, "{name}");
+ assert_eq!(
+ bounded.image.dimensions,
+ target_dimensions(&full.dimensions, max_side),
+ "{name}"
+ );
+ let expected = area_reference(
+ &full.rgb,
+ full.dimensions.width,
+ full.dimensions.height,
+ &bounded.image.dimensions,
+ );
+ assert_eq!(bounded.image.rgb.len(), expected.len(), "{name}");
+ for (actual, expected) in bounded.image.rgb.iter().zip(expected) {
+ assert!(
+ actual.abs_diff(expected) <= 1,
+ "{name}, max {max_side}: {actual} != {expected}"
+ );
+ }
+ }
+ }
+ }
+}
diff --git a/rust/crates/image/src/lib.rs b/rust/crates/image/src/lib.rs
index 34dbc37e30..ceef8f0ab5 100644
--- a/rust/crates/image/src/lib.rs
+++ b/rust/crates/image/src/lib.rs
@@ -2,10 +2,12 @@ mod bounded;
mod color_management;
pub mod decode;
pub mod error;
+mod heif;
pub mod image_compression;
mod png;
+mod resample;
pub mod types;
-pub use bounded::{BoundedDecodedImage, ImageInput, decode_bounded};
+pub use bounded::{BoundedDecodeOptions, 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
index 9438c9fbe2..b21b6a932b 100644
--- a/rust/crates/image/src/png.rs
+++ b/rust/crates/image/src/png.rs
@@ -3,8 +3,10 @@ use std::io::{BufRead, Seek};
use image::{DynamicImage, ImageBuffer, metadata::Orientation};
use crate::{
- BoundedDecodedImage, DecodedImage, Dimensions, ImageError, ImageResult,
- bounded::target_dimensions, color_management::IccConverter,
+ BoundedDecodeOptions, BoundedDecodedImage, DecodedImage, Dimensions, ImageError, ImageResult,
+ bounded::{target_dimensions, too_large},
+ color_management::IccConverter,
+ resample::Downsampler,
};
pub(crate) const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
@@ -12,8 +14,7 @@ const DECODER_BYTES: usize = 32 * 1024 * 1024;
const MAX_ROW_BYTES: u64 = 4 * 1024 * 1024;
const MAX_SOURCE_HEIGHT: u32 = 512 * 1024;
const MAX_SOURCE_PIXELS: u64 = 256_000_000;
-const MAX_BUFFER_BYTES: u64 = 512 * 1024 * 1024;
-const ADAM7: [(u32, u32, u32, u32); 7] = [
+pub(crate) const ADAM7: [(u32, u32, u32, u32); 7] = [
(0, 0, 8, 8),
(4, 0, 8, 8),
(0, 4, 4, 8),
@@ -25,7 +26,7 @@ const ADAM7: [(u32, u32, u32, u32); 7] = [
pub(crate) fn decode<R: BufRead + Seek>(
input: R,
- max_side: u32,
+ options: BoundedDecodeOptions,
) -> ImageResult<BoundedDecodedImage> {
let mut decoder = ::png::Decoder::new_with_limits(
input,
@@ -48,8 +49,15 @@ pub(crate) fn decode<R: BufRead + Seek>(
{
return Err(too_large());
}
- let target = target_dimensions(&source, max_side);
- let mut output = Downsampler::new(source.clone(), target.clone(), interlaced, row_bytes)?;
+ let target = target_dimensions(&source, options.max_side);
+ let oriented_copy = u64::from(target.width) * u64::from(target.height) * 3;
+ let required = Downsampler::bytes(&source, &target, interlaced)
+ .saturating_add(oriented_copy)
+ .saturating_add(row_bytes * 4 + DECODER_BYTES as u64);
+ if required > options.max_memory_bytes {
+ return Err(too_large());
+ }
+ let mut output = Downsampler::new(source.clone(), target.clone(), interlaced)?;
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());
@@ -166,184 +174,6 @@ fn row_rgb(
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()
@@ -362,7 +192,10 @@ mod tests {
};
use super::*;
- use crate::{ImageInput, decode::decode_image_from_bytes, decode_bounded};
+ use crate::{
+ ImageInput, bounded::tests::options, decode::decode_image_from_bytes, decode_bounded,
+ resample::tests::area_reference,
+ };
fn fixture(info: ::png::Info<'_>, pixels: &[u8]) -> Vec<u8> {
let mut bytes = Vec::new();
@@ -416,6 +249,17 @@ mod tests {
bytes
}
+ fn header_only(width: u32, height: u32, interlaced: bool) -> Vec<u8> {
+ let mut bytes = Vec::new();
+ ::png::Encoder::with_info(&mut bytes, rgb_info(width, height, interlaced))
+ .unwrap()
+ .write_header()
+ .unwrap()
+ .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;
@@ -424,34 +268,6 @@ mod tests {
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)] {
@@ -462,7 +278,8 @@ mod tests {
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 decoded =
+ decode_bounded(ImageInput::Bytes(&bytes), options(max_side)).unwrap();
let reference =
area_reference(&pixels, width, height, &decoded.image.dimensions);
assert_eq!(decoded.original_dimensions, Dimensions { width, height });
@@ -485,38 +302,6 @@ mod tests {
}
}
- #[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();
@@ -527,7 +312,7 @@ mod tests {
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();
+ let output = decode_bounded(ImageInput::Bytes(&bytes), options(2)).unwrap();
assert_eq!(output.image.rgb, [80; 2 * 3]);
}
@@ -567,7 +352,8 @@ mod tests {
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();
+ let bounded =
+ decode_bounded(ImageInput::Bytes(&bytes), options(max_side)).unwrap();
if max_side == 6000 {
assert_eq!(bounded.image.rgb, full.rgb);
} else {
@@ -611,7 +397,8 @@ mod tests {
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 bounded =
+ decode_bounded(ImageInput::Bytes(&bytes), options(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) {
@@ -634,7 +421,7 @@ mod tests {
}
let bytes = fixture(info, &[0b10101010]);
let full = decode_image_from_bytes(&bytes).unwrap();
- let bounded = decode_bounded(ImageInput::Bytes(&bytes), 4).unwrap();
+ let bounded = decode_bounded(ImageInput::Bytes(&bytes), options(4)).unwrap();
assert_eq!(
bounded.image.rgb,
area_reference(&full.rgb, 8, 1, &bounded.image.dimensions)
@@ -652,7 +439,7 @@ mod tests {
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();
+ let bounded = decode_bounded(ImageInput::Bytes(&bytes), options(4)).unwrap();
assert_eq!(bounded.original_dimensions, full.dimensions);
let expected = area_reference(
&full.rgb,
@@ -670,8 +457,9 @@ mod tests {
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();
+ let from_path =
+ decode_bounded(ImageInput::Path(path.to_str().unwrap()), options(6)).unwrap();
+ let from_bytes = decode_bounded(ImageInput::Bytes(&bytes), options(6)).unwrap();
assert_eq!(from_path.image.rgb, from_bytes.image.rgb);
assert_eq!(from_path.image.dimensions, from_bytes.image.dimensions);
}
@@ -681,7 +469,7 @@ mod tests {
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(),
+ decode_bounded(ImageInput::Bytes(&bytes[..length]), options(4)).is_err(),
"length {length}"
);
}
@@ -691,8 +479,8 @@ mod tests {
.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());
+ assert!(decode_bounded(ImageInput::Bytes(&corrupt), options(4)).is_err());
+ assert!(decode_bounded(ImageInput::Bytes(&bytes), options(0)).is_err());
}
#[test]
@@ -706,24 +494,31 @@ mod tests {
.finish()
.unwrap();
assert!(matches!(
- decode_bounded(ImageInput::Bytes(&bytes), 6000),
+ decode_bounded(ImageInput::Bytes(&bytes), options(6000)),
+ Err(ImageError::TooLarge(_))
+ ));
+ assert!(matches!(
+ decode_bounded(
+ ImageInput::Bytes(&header_only(8000, 8000, true)),
+ BoundedDecodeOptions::default()
+ ),
Err(ImageError::TooLarge(_))
));
+ let plain = header_only(8000, 8000, false);
assert!(matches!(
- Downsampler::new(
- Dimensions {
- width: 100_000,
- height: 100_000
- },
- Dimensions {
- width: 100_000,
- height: 100_000
- },
- false,
- 0
+ decode_bounded(
+ ImageInput::Bytes(&plain),
+ BoundedDecodeOptions {
+ max_memory_bytes: 64 * 1024 * 1024,
+ ..BoundedDecodeOptions::default()
+ }
),
Err(ImageError::TooLarge(_))
));
+ assert!(matches!(
+ decode_bounded(ImageInput::Bytes(&plain), BoundedDecodeOptions::default()),
+ Err(ImageError::Decode(_))
+ ));
}
#[test]
@@ -749,7 +544,7 @@ mod tests {
ImageInput::Bytes(&bytes),
ImageInput::Path(path.to_str().unwrap()),
] {
- let result = decode_bounded(input, 1);
+ let result = decode_bounded(input, options(1));
assert!(
matches!(result, Err(ImageError::TooLarge(_))),
"{width}x{height}, interlaced {interlaced}: {result:?}"
@@ -770,7 +565,7 @@ mod tests {
.unwrap()
.finish()
.unwrap();
- let result = decode_bounded(ImageInput::Bytes(&bytes), 1);
+ let result = decode_bounded(ImageInput::Bytes(&bytes), options(1));
assert!(
matches!(result, Err(ImageError::Decode(_))),
"{width}x{height}, interlaced {interlaced}: {result:?}"
@@ -797,7 +592,7 @@ mod tests {
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 = decode_bounded(ImageInput::Bytes(&bytes), options(max_side)).unwrap();
let bounded_time = start.elapsed();
if max_side == 1024 {
assert_eq!(bounded.image.rgb, full.rgb);
@@ -835,7 +630,8 @@ mod tests {
}
stream.finish().unwrap();
writer.finish().unwrap();
- let output = decode_bounded(ImageInput::Path(path.to_str().unwrap()), 6000).unwrap();
+ let output =
+ decode_bounded(ImageInput::Path(path.to_str().unwrap()), options(6000)).unwrap();
assert_eq!(
output.image.dimensions,
Dimensions {
diff --git a/rust/crates/image/src/resample.rs b/rust/crates/image/src/resample.rs
new file mode 100644
index 0000000000..40dbd7c069
--- /dev/null
+++ b/rust/crates/image/src/resample.rs
@@ -0,0 +1,254 @@
+use crate::{Dimensions, ImageResult, bounded::too_large};
+
+pub(crate) 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,
+}
+
+struct BufferLengths {
+ rgb: u64,
+ sums: u64,
+ interlaced_sums: u64,
+ row_sums: u64,
+}
+
+impl BufferLengths {
+ fn new(source: &Dimensions, target: &Dimensions, interlaced: bool) -> Self {
+ let pixels = u64::from(target.width) * u64::from(target.height);
+ let sum_rows = if source == target {
+ 0
+ } else {
+ target.height.min(2)
+ };
+ Self {
+ rgb: pixels.saturating_mul(3),
+ sums: u64::from(target.width) * u64::from(sum_rows),
+ interlaced_sums: if interlaced && sum_rows > 0 {
+ pixels
+ } else {
+ 0
+ },
+ row_sums: if sum_rows == 0 {
+ 0
+ } else {
+ u64::from(target.width)
+ },
+ }
+ }
+}
+
+impl Downsampler {
+ pub(crate) fn bytes(source: &Dimensions, target: &Dimensions, interlaced: bool) -> u64 {
+ let lengths = BufferLengths::new(source, target, interlaced);
+ lengths
+ .rgb
+ .saturating_add(lengths.sums.saturating_mul(24))
+ .saturating_add(lengths.interlaced_sums.saturating_mul(12))
+ .saturating_add(lengths.row_sums.saturating_mul(24))
+ }
+
+ pub(crate) fn new(
+ source: Dimensions,
+ target: Dimensions,
+ interlaced: bool,
+ ) -> ImageResult<Self> {
+ let lengths = BufferLengths::new(&source, &target, interlaced);
+ Ok(Self {
+ rgb: zeroed(lengths.rgb)?,
+ sums: zeroed(lengths.sums)?,
+ interlaced_sums: zeroed(lengths.interlaced_sums)?,
+ row_sums: zeroed(lengths.row_sums)?,
+ source,
+ target,
+ interlaced,
+ completed_rows: 0,
+ })
+ }
+
+ pub(crate) 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];
+ }
+ }
+
+ pub(crate) fn finish_pass(&mut self) {
+ if !self.sums.is_empty() {
+ self.finish_rows(self.target.height);
+ self.completed_rows = 0;
+ }
+ }
+
+ pub(crate) 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: u64) -> ImageResult<Vec<T>> {
+ let length = usize::try_from(length).map_err(|_| too_large())?;
+ let mut buffer = Vec::new();
+ buffer.try_reserve_exact(length).map_err(|_| too_large())?;
+ buffer.resize(length, T::default());
+ Ok(buffer)
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+ use super::*;
+
+ pub(crate) 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 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,
+ )
+ .unwrap();
+ let plain = [(0, 0, 1, 1)];
+ let passes = if interlaced {
+ &crate::png::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]);
+ }
+ }
+}