mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-15 23:12:15 +00:00
Format shared image codec crate
This commit is contained in:
52 files changed
+474
-197
No files matched your search
@@ -437,8 +437,9 @@ fn header(width: u32, height: u32, store: Store, levels: u32, top: usize) -> Res
|
||||
};
|
||||
// Uncompressed: the pitch of one row. Compressed: the whole top level (its "linear size").
|
||||
let (size_flag, pitch_or_size) = if store.is_block() { (DDSD_LINEARSIZE, Some(top)) } else { (DDSD_PITCH, store.row_bytes(width as usize)) };
|
||||
let pitch_or_size =
|
||||
pitch_or_size.and_then(|v| u32::try_from(v).ok()).ok_or_else(|| encode_err(format!("a {width}x{height} level is too large for a DDS header")))?;
|
||||
let pitch_or_size = pitch_or_size
|
||||
.and_then(|v| u32::try_from(v).ok())
|
||||
.ok_or_else(|| encode_err(format!("a {width}x{height} level is too large for a DDS header")))?;
|
||||
let mipmapped = levels > 1;
|
||||
put(4, 124);
|
||||
put(8, DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | size_flag | if mipmapped { DDSD_MIPMAPCOUNT } else { 0 });
|
||||
|
||||
@@ -252,7 +252,8 @@ fn least_squares(block: &Block, opaque: Mask, bytes: &[u8; 8]) -> Option<(u16, u
|
||||
/// between the extremes other than 0 and 255, plus exact 0 and 255) fits better.
|
||||
fn alpha_block(block: &Block, inside: Mask) -> [u8; 8] {
|
||||
let alphas = || block.iter().enumerate().filter(move |(t, _)| inside >> t & 1 != 0).map(|(_, texel)| texel[3]);
|
||||
let range = |values: &mut dyn Iterator<Item = u8>| values.fold(None, |r: Option<(u8, u8)>, a| Some(r.map_or((a, a), |(lo, hi)| (lo.min(a), hi.max(a)))));
|
||||
let range =
|
||||
|values: &mut dyn Iterator<Item = u8>| values.fold(None, |r: Option<(u8, u8)>, a| Some(r.map_or((a, a), |(lo, hi)| (lo.min(a), hi.max(a)))));
|
||||
let (lo, hi) = range(&mut alphas()).unwrap_or((0, 0));
|
||||
// Eight values need a0 > a1; equal ends fall to the six-value mode, which starts with a0 too.
|
||||
let eight = alpha_fit(block, inside, hi, lo);
|
||||
|
||||
@@ -53,7 +53,12 @@ fn read_exact<'a>(cur: &mut Cursor<&'a [u8]>, n: usize, what: &str) -> Result<&'
|
||||
|
||||
fn i32(cur: &mut Cursor<&[u8]>) -> Result<i32, CodecError> {
|
||||
let b = read_exact(cur, 4, "an i32")?;
|
||||
Ok(i32::from_le_bytes([b.first().copied().unwrap_or(0), b.get(1).copied().unwrap_or(0), b.get(2).copied().unwrap_or(0), b.get(3).copied().unwrap_or(0)]))
|
||||
Ok(i32::from_le_bytes([
|
||||
b.first().copied().unwrap_or(0),
|
||||
b.get(1).copied().unwrap_or(0),
|
||||
b.get(2).copied().unwrap_or(0),
|
||||
b.get(3).copied().unwrap_or(0),
|
||||
]))
|
||||
}
|
||||
|
||||
fn u64(cur: &mut Cursor<&[u8]>) -> Result<u64, CodecError> {
|
||||
@@ -125,7 +130,8 @@ fn reserve_up_to(out: &mut Vec<u8>, extra: usize, limit: usize, what: &str) -> R
|
||||
}
|
||||
if need > out.capacity() {
|
||||
let target = out.capacity().saturating_mul(2).max(need).min(limit);
|
||||
out.try_reserve_exact(target.saturating_sub(out.len())).map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {target} bytes for {what}")))?;
|
||||
out.try_reserve_exact(target.saturating_sub(out.len()))
|
||||
.map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {target} bytes for {what}")))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -344,30 +350,31 @@ pub(crate) fn decode_deep(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Res
|
||||
// Block coordinates → the block's pixel bounds and its slot. The per-pixel index is
|
||||
// built only after the chunk's declared payload sizes are validated below, so a
|
||||
// truncated or lying chunk cannot drive a large index allocation first.
|
||||
let (block_rows, block_cols, slot, row_w, scanline_row): (std::ops::Range<usize>, std::ops::Range<usize>, usize, usize, bool) = match &header.blocks {
|
||||
BlockDescription::ScanLines => {
|
||||
let y = i32(&mut cur)?;
|
||||
let row = match y.checked_sub(y0) {
|
||||
Some(d) if d >= 0 && (d as usize) < h => d as usize,
|
||||
_ => return Err(err(format!("scan line block y={y} is outside the data window"))),
|
||||
};
|
||||
(row..row + 1, 0..w, row, w, true)
|
||||
}
|
||||
BlockDescription::Tiles(_) => {
|
||||
let (tx, ty, lx, ly) = (i32(&mut cur)?, i32(&mut cur)?, i32(&mut cur)?, i32(&mut cur)?);
|
||||
if (lx, ly) != (0, 0) {
|
||||
return Err(err(format!("deep tile at level ({lx},{ly}); only level 0 exists in a single-level file")));
|
||||
let (block_rows, block_cols, slot, row_w, scanline_row): (std::ops::Range<usize>, std::ops::Range<usize>, usize, usize, bool) =
|
||||
match &header.blocks {
|
||||
BlockDescription::ScanLines => {
|
||||
let y = i32(&mut cur)?;
|
||||
let row = match y.checked_sub(y0) {
|
||||
Some(d) if d >= 0 && (d as usize) < h => d as usize,
|
||||
_ => return Err(err(format!("scan line block y={y} is outside the data window"))),
|
||||
};
|
||||
(row..row + 1, 0..w, row, w, true)
|
||||
}
|
||||
if tx < 0 || ty < 0 || (tx as usize) >= tiles_x || (ty as usize) * tile_h >= h {
|
||||
return Err(err(format!("tile ({tx},{ty}) is outside the data window")));
|
||||
BlockDescription::Tiles(_) => {
|
||||
let (tx, ty, lx, ly) = (i32(&mut cur)?, i32(&mut cur)?, i32(&mut cur)?, i32(&mut cur)?);
|
||||
if (lx, ly) != (0, 0) {
|
||||
return Err(err(format!("deep tile at level ({lx},{ly}); only level 0 exists in a single-level file")));
|
||||
}
|
||||
if tx < 0 || ty < 0 || (tx as usize) >= tiles_x || (ty as usize) * tile_h >= h {
|
||||
return Err(err(format!("tile ({tx},{ty}) is outside the data window")));
|
||||
}
|
||||
let (bx, by) = ((tx as usize) * tile_w, (ty as usize) * tile_h);
|
||||
let rows = (by + tile_h).min(h);
|
||||
let cols = (bx + tile_w).min(w);
|
||||
let slot = (ty as usize).saturating_mul(tiles_x) + tx as usize;
|
||||
(by..rows, bx..cols, slot, cols - bx, false)
|
||||
}
|
||||
let (bx, by) = ((tx as usize) * tile_w, (ty as usize) * tile_h);
|
||||
let rows = (by + tile_h).min(h);
|
||||
let cols = (bx + tile_w).min(w);
|
||||
let slot = (ty as usize).saturating_mul(tiles_x) + tx as usize;
|
||||
(by..rows, bx..cols, slot, cols - bx, false)
|
||||
}
|
||||
};
|
||||
};
|
||||
let block_len = block_rows.len().saturating_mul(block_cols.len());
|
||||
if seen.get(slot).copied().unwrap_or(true) {
|
||||
return Err(err(format!("two chunks cover block {slot}")));
|
||||
|
||||
@@ -254,7 +254,8 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result<Image, CodecError> {
|
||||
.get(pixel.start..pixel.start.checked_add(need).ok_or_else(|| CodecError::LimitExceeded("pixel data too large".into()))?)
|
||||
.ok_or_else(|| bad("pixel data is truncated"))?;
|
||||
let out_channels = layout.channels();
|
||||
let out_len = pixels.checked_mul(out_channels).and_then(|k| k.checked_mul(bytes_per)).ok_or_else(|| CodecError::LimitExceeded("image too large".into()))?;
|
||||
let out_len =
|
||||
pixels.checked_mul(out_channels).and_then(|k| k.checked_mul(bytes_per)).ok_or_else(|| CodecError::LimitExceeded("image too large".into()))?;
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(out_len).map_err(|_| CodecError::LimitExceeded("cannot allocate the image".into()))?;
|
||||
// Raw sample of channel `ch` at pixel `p`, honouring the planar configuration.
|
||||
@@ -367,7 +368,18 @@ mod tests {
|
||||
|
||||
/// A DICOM with the given transfer syntax UID and data-set encoding.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn synth(ts: &str, explicit: bool, big: bool, planar: u16, rows: u16, cols: u16, samples: u16, bits: u16, photometric: &str, pixels: &[u8]) -> Vec<u8> {
|
||||
fn synth(
|
||||
ts: &str,
|
||||
explicit: bool,
|
||||
big: bool,
|
||||
planar: u16,
|
||||
rows: u16,
|
||||
cols: u16,
|
||||
samples: u16,
|
||||
bits: u16,
|
||||
photometric: &str,
|
||||
pixels: &[u8],
|
||||
) -> Vec<u8> {
|
||||
let mut b = vec![0u8; 128];
|
||||
b.extend_from_slice(b"DICM");
|
||||
// One extra meta element before the syntax, so a reader that only looks at the last
|
||||
|
||||
@@ -382,7 +382,8 @@ pub(crate) fn decode_cineon(bytes: &[u8], limits: &Limits) -> Result<Image, Code
|
||||
}
|
||||
let o = Order::Big;
|
||||
let missing = |what: &str| err(format!("the header ends before {what}"));
|
||||
let image_offset = usize::try_from(o.u32(bytes, 4).ok_or_else(|| missing("the image data offset"))?).map_err(|_| err("image data offset out of range"))?;
|
||||
let image_offset =
|
||||
usize::try_from(o.u32(bytes, 4).ok_or_else(|| missing("the image data offset"))?).map_err(|_| err("image data offset out of range"))?;
|
||||
let channels = *bytes.get(193).ok_or_else(|| missing("the channel count"))?;
|
||||
let bits = *bytes.get(198).ok_or_else(|| missing("the bits per pixel"))?;
|
||||
if bits != 10 {
|
||||
@@ -442,8 +443,10 @@ pub(crate) fn encode_cineon(src: &Image, plan: Plan) -> Result<Vec<u8>, CodecErr
|
||||
return Err(enc("the image has the wrong number of samples".into()));
|
||||
}
|
||||
let data_len = line_bytes(per_line, 10, 1).and_then(|l| l.checked_mul(h as usize)).ok_or_else(|| enc("image too large".into()))?;
|
||||
let total =
|
||||
CINEON_HEADER_LEN.checked_add(data_len).and_then(|t| u32::try_from(t).ok()).ok_or_else(|| enc("image too large for a Cineon file (4 GiB)".into()))?;
|
||||
let total = CINEON_HEADER_LEN
|
||||
.checked_add(data_len)
|
||||
.and_then(|t| u32::try_from(t).ok())
|
||||
.ok_or_else(|| enc("image too large for a Cineon file (4 GiB)".into()))?;
|
||||
|
||||
let mut wr = Writer { h: vec![0; CINEON_HEADER_LEN] };
|
||||
// File information.
|
||||
@@ -731,8 +734,10 @@ mod tests {
|
||||
/// A minimal header for `w`×`h` with element 0 set; image data at 2048.
|
||||
fn header(o: Order, w: u32, h: u32, descriptor: u8, bits: u8, packing: u16) -> Vec<u8> {
|
||||
let mut b = vec![0u8; HEADER_LEN];
|
||||
let put32 = |b: &mut Vec<u8>, at: usize, v: u32| b[at..at + 4].copy_from_slice(&if o == Order::Big { v.to_be_bytes() } else { v.to_le_bytes() });
|
||||
let put16 = |b: &mut Vec<u8>, at: usize, v: u16| b[at..at + 2].copy_from_slice(&if o == Order::Big { v.to_be_bytes() } else { v.to_le_bytes() });
|
||||
let put32 =
|
||||
|b: &mut Vec<u8>, at: usize, v: u32| b[at..at + 4].copy_from_slice(&if o == Order::Big { v.to_be_bytes() } else { v.to_le_bytes() });
|
||||
let put16 =
|
||||
|b: &mut Vec<u8>, at: usize, v: u16| b[at..at + 2].copy_from_slice(&if o == Order::Big { v.to_be_bytes() } else { v.to_le_bytes() });
|
||||
b[..4].copy_from_slice(if o == Order::Big { b"SDPX" } else { b"XPDS" });
|
||||
put32(&mut b, 4, HEADER_LEN as u32);
|
||||
put32(&mut b, 28, INDUSTRY_LEN);
|
||||
|
||||
@@ -8,7 +8,8 @@ use std::io::Cursor;
|
||||
|
||||
use exr::meta::MetaData;
|
||||
use exr::prelude::{
|
||||
AnyChannel, AnyChannels, Blocks, Compression, Encoding, FlatSamples, Layer, LayerAttributes, LineOrder, ReadChannels, ReadLayers, WritableImage, read,
|
||||
AnyChannel, AnyChannels, Blocks, Compression, Encoding, FlatSamples, Layer, LayerAttributes, LineOrder, ReadChannels, ReadLayers, WritableImage,
|
||||
read,
|
||||
};
|
||||
use half::f16;
|
||||
|
||||
@@ -71,8 +72,10 @@ pub(crate) fn check_previews(b: &[u8]) -> Result<(), CodecError> {
|
||||
_ => return Ok(()),
|
||||
};
|
||||
if kind == b"preview" {
|
||||
let declared =
|
||||
u32_at(value).zip(u32_at(value + 4)).and_then(|(w, h)| u64::from(w).checked_mul(u64::from(h))?.checked_mul(4)).filter(|_| size >= 8);
|
||||
let declared = u32_at(value)
|
||||
.zip(u32_at(value + 4))
|
||||
.and_then(|(w, h)| u64::from(w).checked_mul(u64::from(h))?.checked_mul(4))
|
||||
.filter(|_| size >= 8);
|
||||
if declared.is_none_or(|n| n > (size - 8) as u64) {
|
||||
return Err(err("a preview attribute declares more pixels than it holds"));
|
||||
}
|
||||
@@ -201,7 +204,8 @@ fn layer_to_image(layer: &Layer<AnyChannels<FlatSamples>>) -> Result<Image, Code
|
||||
let (w, h) = (layer.size.0, layer.size.1);
|
||||
let channels = &layer.channel_data.list;
|
||||
let names: Vec<_> = channels.iter().map(|c| c.name.to_string()).collect();
|
||||
let (layout, selected) = exr_color_channels(names.iter().map(String::as_str)).ok_or_else(|| CodecError::unsupported(F, "no R/G/B or Y channels"))?;
|
||||
let (layout, selected) =
|
||||
exr_color_channels(names.iter().map(String::as_str)).ok_or_else(|| CodecError::unsupported(F, "no R/G/B or Y channels"))?;
|
||||
let color: Vec<_> = selected.iter().map(|i| channels.get(*i).ok_or_else(|| err("selected channel is missing"))).collect::<Result<_, _>>()?;
|
||||
let all_f16 = color.iter().all(|c| matches!(c.sample_data, FlatSamples::F16(_)));
|
||||
let sample = if all_f16 { SampleType::F16 } else { SampleType::F32 };
|
||||
@@ -273,7 +277,10 @@ pub(crate) fn probe(bytes: &[u8], limits: &Limits) -> Result<(u32, u32), CodecEr
|
||||
pub(crate) fn decode_part(bytes: &[u8], index: usize, limits: &Limits) -> Result<Image, CodecError> {
|
||||
let meta = read_meta(bytes, limits)?;
|
||||
if meta.requirements.has_deep_data {
|
||||
return Err(CodecError::unsupported(F, "this file has deep parts; the deep decoder composites those (mixing flat and deep parts is not supported)"));
|
||||
return Err(CodecError::unsupported(
|
||||
F,
|
||||
"this file has deep parts; the deep decoder composites those (mixing flat and deep parts is not supported)",
|
||||
));
|
||||
}
|
||||
if index >= meta.headers.len() {
|
||||
return Err(err(format!("part index {index} is out of range ({} parts)", meta.headers.len())));
|
||||
@@ -287,7 +294,10 @@ pub(crate) fn decode_part(bytes: &[u8], index: usize, limits: &Limits) -> Result
|
||||
pub(crate) fn decode_channels(bytes: &[u8], index: usize, names: &[&str], limits: &Limits) -> Result<Image, CodecError> {
|
||||
let meta = read_meta(bytes, limits)?;
|
||||
if meta.requirements.has_deep_data {
|
||||
return Err(CodecError::unsupported(F, "this file has deep parts; the deep decoder composites those (mixing flat and deep parts is not supported)"));
|
||||
return Err(CodecError::unsupported(
|
||||
F,
|
||||
"this file has deep parts; the deep decoder composites those (mixing flat and deep parts is not supported)",
|
||||
));
|
||||
}
|
||||
if index >= meta.headers.len() {
|
||||
return Err(err(format!("part index {index} is out of range ({} parts)", meta.headers.len())));
|
||||
|
||||
@@ -231,8 +231,10 @@ pub(crate) fn decode(bytes: &[u8], layer_name: &str, limits: &Limits) -> Result<
|
||||
// returned per-pixel vectors could exceed the caller's max_alloc budget.
|
||||
let ranks = layer.channels.len().saturating_mul(2);
|
||||
let pair_capacity = (ranks as u64).saturating_mul(std::mem::size_of::<(f32, f32)>() as u64);
|
||||
let per_pixel =
|
||||
(layer.channels.len().max(1) as u64).saturating_mul(16).saturating_add(std::mem::size_of::<Vec<(f32, f32)>>() as u64).saturating_add(pair_capacity);
|
||||
let per_pixel = (layer.channels.len().max(1) as u64)
|
||||
.saturating_mul(16)
|
||||
.saturating_add(std::mem::size_of::<Vec<(f32, f32)>>() as u64)
|
||||
.saturating_add(pair_capacity);
|
||||
limits.check_bytes(w32, h32, per_pixel)?;
|
||||
|
||||
let ex_layer = super::exr::read_layer(bytes, layer.part)?;
|
||||
|
||||
@@ -39,8 +39,8 @@ const MAX_HDUS: usize = 1000;
|
||||
/// Keywords that describe the data layout. They are written from the image, never copied from
|
||||
/// (or kept as) text metadata: after decoding they no longer describe the pixels.
|
||||
const STRUCTURAL: &[&str] = &[
|
||||
"SIMPLE", "BITPIX", "NAXIS", "EXTEND", "BZERO", "BSCALE", "BLANK", "END", "XTENSION", "PCOUNT", "GCOUNT", "ROWORDER", "CHECKSUM", "DATASUM", "DATAMIN",
|
||||
"DATAMAX", "ZIMAGE",
|
||||
"SIMPLE", "BITPIX", "NAXIS", "EXTEND", "BZERO", "BSCALE", "BLANK", "END", "XTENSION", "PCOUNT", "GCOUNT", "ROWORDER", "CHECKSUM", "DATASUM",
|
||||
"DATAMIN", "DATAMAX", "ZIMAGE",
|
||||
];
|
||||
|
||||
fn err(msg: impl std::fmt::Display) -> CodecError {
|
||||
@@ -192,7 +192,9 @@ fn axes(h: &Header) -> Result<Vec<u64>, CodecError> {
|
||||
if !(0..=999).contains(&n) {
|
||||
return Err(err(format!("invalid NAXIS {n}")));
|
||||
}
|
||||
(1..=n).map(|i| h.int(&format!("NAXIS{i}")).and_then(|v| u64::try_from(v).ok()).ok_or_else(|| err(format!("missing or negative NAXIS{i}")))).collect()
|
||||
(1..=n)
|
||||
.map(|i| h.int(&format!("NAXIS{i}")).and_then(|v| u64::try_from(v).ok()).ok_or_else(|| err(format!("missing or negative NAXIS{i}"))))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Bytes in the data unit (before padding to a block).
|
||||
@@ -433,7 +435,9 @@ fn ascii(s: &str) -> String {
|
||||
|
||||
/// A FITS literal (number or logical) that can be written unquoted.
|
||||
fn literal(v: &str) -> bool {
|
||||
v == "T" || v == "F" || (v.replace(['D', 'd'], "E").parse::<f64>().is_ok_and(|f| f.is_finite()) && v.bytes().all(|b| b"0123456789+-.EeDd".contains(&b)))
|
||||
v == "T"
|
||||
|| v == "F"
|
||||
|| (v.replace(['D', 'd'], "E").parse::<f64>().is_ok_and(|f| f.is_finite()) && v.bytes().all(|b| b"0123456789+-.EeDd".contains(&b)))
|
||||
}
|
||||
|
||||
fn quoted(v: &str, room: usize) -> String {
|
||||
|
||||
@@ -92,7 +92,10 @@ mod tests {
|
||||
let header = b"\0\0\0\x18ftypheic\0\0\0\0mif1heic";
|
||||
assert_eq!(crate::detect(header), Some(F), "still recognised");
|
||||
let r = crate::decode(header);
|
||||
assert!(matches!(&r, Err(CodecError::Unsupported { format: Format::Heif, reason }) if reason.contains("isn't included in this build")), "{r:?}");
|
||||
assert!(
|
||||
matches!(&r, Err(CodecError::Unsupported { format: Format::Heif, reason }) if reason.contains("isn't included in this build")),
|
||||
"{r:?}"
|
||||
);
|
||||
assert!(!crate::caps(F).read);
|
||||
}
|
||||
|
||||
@@ -109,9 +112,10 @@ mod tests {
|
||||
/// (`boxes.rs:130`, "slice index starts at 24 but ends at 16"). It must be an error, not a crash.
|
||||
#[cfg(feature = "heif")]
|
||||
const HEIC_RS_BOX_PANIC: [u8; 72] = [
|
||||
0x00, 0x00, 0x00, 0x24, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x69, 0x66, 0x31, 0x4d, 0x69, 0x50, 0x72, 0x6d,
|
||||
0x69, 0x61, 0x66, 0x4d, 0x69, 0x48, 0x42, 0x72, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x65, 0x74, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x10, 0x75, 0x75, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x03, 0x08, 0x08, 0x08, 0x00, 0x03, 0x01, 0x03, 0x70, 0x00, 0xa8, 0x00,
|
||||
0x00, 0x00, 0x00, 0x24, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x69, 0x66, 0x31, 0x4d, 0x69, 0x50,
|
||||
0x72, 0x6d, 0x69, 0x61, 0x66, 0x4d, 0x69, 0x48, 0x42, 0x72, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x65, 0x74, 0x61, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x75, 0x75, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x03, 0x08, 0x08, 0x08, 0x00, 0x03, 0x01, 0x03, 0x70,
|
||||
0x00, 0xa8, 0x00,
|
||||
];
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
|
||||
@@ -190,7 +190,8 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result<Image, CodecError> {
|
||||
for row in stored.chunks_mut(plane_row.max(1)).take(total_rows) {
|
||||
match h.compression {
|
||||
0 => {
|
||||
let src = body.get(cursor..cursor.checked_add(plane_row).ok_or_else(|| bad("BODY overflow"))?).ok_or_else(|| bad("truncated BODY data"))?;
|
||||
let src =
|
||||
body.get(cursor..cursor.checked_add(plane_row).ok_or_else(|| bad("BODY overflow"))?).ok_or_else(|| bad("truncated BODY data"))?;
|
||||
let n = row.len().min(src.len());
|
||||
row[..n].copy_from_slice(&src[..n]);
|
||||
cursor += plane_row;
|
||||
@@ -203,7 +204,8 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result<Image, CodecError> {
|
||||
}
|
||||
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(w.saturating_mul(hh).saturating_mul(layout.channels())).map_err(|_| CodecError::LimitExceeded("cannot allocate the image".into()))?;
|
||||
out.try_reserve_exact(w.saturating_mul(hh).saturating_mul(layout.channels()))
|
||||
.map_err(|_| CodecError::LimitExceeded("cannot allocate the image".into()))?;
|
||||
let planes = usize::from(h.planes);
|
||||
for y in 0..hh {
|
||||
for x in 0..w {
|
||||
@@ -215,7 +217,8 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result<Image, CodecError> {
|
||||
let c = if h.planes == DEEP_PLANES { [index as u8, (index >> 8) as u8, (index >> 16) as u8] } else { palette(index) };
|
||||
out.extend_from_slice(&c);
|
||||
if h.masking != 0 {
|
||||
let opaque = if h.masking == 1 { bit_at(&stored, (y * rows_planes + planes) * plane_row, x) } else { index != usize::from(h.transparent) };
|
||||
let opaque =
|
||||
if h.masking == 1 { bit_at(&stored, (y * rows_planes + planes) * plane_row, x) } else { index != usize::from(h.transparent) };
|
||||
out.push(if opaque { 255 } else { 0 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,7 +141,11 @@ pub(crate) fn encode(image: &Image, plan: Plan) -> Result<Vec<u8>, CodecError> {
|
||||
let options = ZuneOptions::new(width as usize, height as usize, space, depth);
|
||||
let mut output = Vec::new();
|
||||
JxlSimpleEncoder::new(image.data(), options).encode(&mut output).map_err(|e| CodecError::encode(F, e.to_string()))?;
|
||||
if depth == BitDepth::Sixteen && image.layout() == ChannelLayout::Rgba { correct_16_bit_alpha_header(&output, width, height) } else { Ok(output) }
|
||||
if depth == BitDepth::Sixteen && image.layout() == ChannelLayout::Rgba {
|
||||
correct_16_bit_alpha_header(&output, width, height)
|
||||
} else {
|
||||
Ok(output)
|
||||
}
|
||||
}))
|
||||
.unwrap_or_else(|_| Err(CodecError::encode(F, "the JPEG XL encoder failed")))
|
||||
}
|
||||
|
||||
@@ -355,7 +355,9 @@ impl<B: AsRef<[u8]>> PngDecodeRows<B> {
|
||||
let at = held.checked_mul(self.line).ok_or_else(|| err("image too large"))?;
|
||||
let end = at.checked_add(self.line).ok_or_else(|| err("image too large"))?;
|
||||
if self.buf.len() < end {
|
||||
self.buf.try_reserve_exact(end - self.buf.len()).map_err(|_| CodecError::LimitExceeded("cannot allocate a group of rows".into()))?;
|
||||
self.buf
|
||||
.try_reserve_exact(end - self.buf.len())
|
||||
.map_err(|_| CodecError::LimitExceeded("cannot allocate a group of rows".into()))?;
|
||||
self.buf.resize(end, 0);
|
||||
}
|
||||
let row = self.buf.get_mut(at..end).ok_or_else(|| err("invalid PNG row group"))?;
|
||||
@@ -990,7 +992,14 @@ fn inflate_text(mut p: PendingText, bytes: &[u8]) -> Result<TextBatch, CodecErro
|
||||
/// An uncompressed iTXt value is UTF-8 checked batch by batch before it is charged: an invalid
|
||||
/// value is dropped even when it is over the budget, as the previous whole-value check did.
|
||||
/// Its budget error is deferred until every byte has been seen and found valid.
|
||||
fn append_checked(out: &mut Vec<u8>, utf8: &mut Option<Utf8Check>, over: &mut bool, bytes: &[u8], latin1: bool, limit: usize) -> Result<bool, CodecError> {
|
||||
fn append_checked(
|
||||
out: &mut Vec<u8>,
|
||||
utf8: &mut Option<Utf8Check>,
|
||||
over: &mut bool,
|
||||
bytes: &[u8],
|
||||
latin1: bool,
|
||||
limit: usize,
|
||||
) -> Result<bool, CodecError> {
|
||||
if let Some(check) = utf8.as_mut()
|
||||
&& !check.feed(bytes)
|
||||
{
|
||||
@@ -1112,8 +1121,11 @@ fn start<W: Write>(
|
||||
&& x > 0.0
|
||||
&& y > 0.0
|
||||
{
|
||||
info.pixel_dims =
|
||||
Some(png::PixelDimensions { xppu: (x / METERS_PER_INCH).round() as u32, yppu: (y / METERS_PER_INCH).round() as u32, unit: png::Unit::Meter });
|
||||
info.pixel_dims = Some(png::PixelDimensions {
|
||||
xppu: (x / METERS_PER_INCH).round() as u32,
|
||||
yppu: (y / METERS_PER_INCH).round() as u32,
|
||||
unit: png::Unit::Meter,
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut encoder = png::Encoder::with_info(out, info).map_err(|e| CodecError::encode(F, e))?;
|
||||
@@ -1136,7 +1148,9 @@ fn start<W: Write>(
|
||||
res.map_err(|e| CodecError::encode(F, e))?;
|
||||
}
|
||||
if let Some(xmp) = &meta.xmp {
|
||||
encoder.add_itxt_chunk(XMP_KEYWORD.into(), crate::resolution::export_xmp(xmp, meta.dpi).into_owned()).map_err(|e| CodecError::encode(F, e))?;
|
||||
encoder
|
||||
.add_itxt_chunk(XMP_KEYWORD.into(), crate::resolution::export_xmp(xmp, meta.dpi).into_owned())
|
||||
.map_err(|e| CodecError::encode(F, e))?;
|
||||
}
|
||||
}
|
||||
let mut writer = encoder.write_header().map_err(|e| CodecError::encode(F, e))?;
|
||||
@@ -1195,7 +1209,18 @@ impl<W: Write> PngRows<W> {
|
||||
}
|
||||
let plan = crate::fidelity::plan(first, F, opts);
|
||||
let writer = start(out, (width, height), (plan.layout, plan.sample), first.icc.as_ref(), &first.meta, opts)?;
|
||||
Ok(Self { writer, plan, width, height, rows: 0, level: opts.png_compression, pending: Vec::new(), prev: Vec::new(), adler: 1, started: false })
|
||||
Ok(Self {
|
||||
writer,
|
||||
plan,
|
||||
width,
|
||||
height,
|
||||
rows: 0,
|
||||
level: opts.png_compression,
|
||||
pending: Vec::new(),
|
||||
prev: Vec::new(),
|
||||
adler: 1,
|
||||
started: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Encodes the next rows of the image: `band` is as wide as the image, in any layout and
|
||||
@@ -1235,7 +1260,8 @@ impl<W: Write> PngRows<W> {
|
||||
let parts = deflate_rows(rows, prev, stride, bpp, per_band, deflate_level(self.level), finish, encode_threads())
|
||||
.ok_or_else(|| CodecError::encode(F, "a band of rows could not be compressed"))?;
|
||||
let mut zlib = Vec::new();
|
||||
zlib.try_reserve_exact(parts.iter().map(|p| p.z.len()).sum::<usize>() + 6).map_err(|_| CodecError::encode(F, "not enough memory for PNG data"))?;
|
||||
zlib.try_reserve_exact(parts.iter().map(|p| p.z.len()).sum::<usize>() + 6)
|
||||
.map_err(|_| CodecError::encode(F, "not enough memory for PNG data"))?;
|
||||
if !self.started {
|
||||
zlib.extend_from_slice(&zlib_header(self.level));
|
||||
self.started = true;
|
||||
@@ -1266,7 +1292,8 @@ impl<W: Write> PngRows<W> {
|
||||
/// Build the zlib stream for an Adam7-interlaced image (filter type 0).
|
||||
fn adam7_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompression) -> Result<Vec<u8>, CodecError> {
|
||||
// (x0, y0, dx, dy) per pass.
|
||||
const PASSES: [(usize, usize, usize, usize); 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)];
|
||||
const PASSES: [(usize, usize, usize, usize); 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)];
|
||||
let mut raw = Vec::new();
|
||||
raw.try_reserve_exact(data.len() + h * 7).map_err(|_| CodecError::encode(F, "not enough memory for PNG rows"))?;
|
||||
for (x0, y0, dx, dy) in PASSES {
|
||||
@@ -1553,8 +1580,11 @@ pub fn encode_indexed(
|
||||
&& x > 0.0
|
||||
&& y > 0.0
|
||||
{
|
||||
info.pixel_dims =
|
||||
Some(png::PixelDimensions { xppu: (x / METERS_PER_INCH).round() as u32, yppu: (y / METERS_PER_INCH).round() as u32, unit: png::Unit::Meter });
|
||||
info.pixel_dims = Some(png::PixelDimensions {
|
||||
xppu: (x / METERS_PER_INCH).round() as u32,
|
||||
yppu: (y / METERS_PER_INCH).round() as u32,
|
||||
unit: png::Unit::Meter,
|
||||
});
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
{
|
||||
@@ -1880,7 +1910,8 @@ mod parallel_tests {
|
||||
for (layout, sample, ch, bytes) in [(ChannelLayout::Rgb, SampleType::U8, 3usize, 1usize), (ChannelLayout::Rgba, SampleType::U16, 4, 2)] {
|
||||
let (w, h) = (1531u32, 977u32);
|
||||
let n = w as usize * h as usize * ch * bytes;
|
||||
let px: Vec<u8> = (0..n).map(|i| ((i / 3) as u32).wrapping_mul(2_654_435_761).rotate_left(i as u32 % 7) as u8 / 3 + (i % 97) as u8).collect();
|
||||
let px: Vec<u8> =
|
||||
(0..n).map(|i| ((i / 3) as u32).wrapping_mul(2_654_435_761).rotate_left(i as u32 % 7) as u8 / 3 + (i % 97) as u8).collect();
|
||||
let img = Image::from_raw(w, h, layout, sample, px.clone()).unwrap();
|
||||
assert!(n >= PARALLEL_MIN_BYTES || sample == SampleType::U8);
|
||||
for level in [PngCompression::Fast, PngCompression::Default] {
|
||||
@@ -2088,7 +2119,8 @@ mod rows_tests {
|
||||
#[test]
|
||||
fn metadata_yields_do_not_finalize_the_pixels_again() {
|
||||
let text = "A".repeat(20_000);
|
||||
let img = image(8, 6, ChannelLayout::Rgb, SampleType::U8).with_meta(Metadata { text: vec![("Comment".into(), text.clone())], ..Default::default() });
|
||||
let img = image(8, 6, ChannelLayout::Rgb, SampleType::U8)
|
||||
.with_meta(Metadata { text: vec![("Comment".into(), text.clone())], ..Default::default() });
|
||||
let bytes = crate::encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let mut rows = PngDecodeRows::new(bytes.as_slice(), &Limits::default()).unwrap();
|
||||
let mut calls = 0;
|
||||
|
||||
@@ -338,7 +338,9 @@ pub(crate) fn encode(src: &Image, plan: Plan, _opts: &EncodeOptions) -> Result<V
|
||||
ChannelLayout::Cmyk => "CMYK",
|
||||
_ => "CMYK_ALPHA",
|
||||
};
|
||||
out.extend_from_slice(format!("P7\nWIDTH {w}\nHEIGHT {h}\nDEPTH {}\nMAXVAL {maxval}\nTUPLTYPE {t}\nENDHDR\n", l.channels()).as_bytes());
|
||||
out.extend_from_slice(
|
||||
format!("P7\nWIDTH {w}\nHEIGHT {h}\nDEPTH {}\nMAXVAL {maxval}\nTUPLTYPE {t}\nENDHDR\n", l.channels()).as_bytes(),
|
||||
);
|
||||
}
|
||||
}
|
||||
if sample == SampleType::U8 {
|
||||
|
||||
@@ -4,8 +4,8 @@ use super::bands::{Tally, convert_ab, decode_bands, extra_sample_indices, refill
|
||||
use super::tags::{F, TAG_IMAGE_SOURCE_DATA, TAG_PHOTOSHOP, TAG_XMP, TEXT_TAGS, photoshop_tags};
|
||||
use super::ycbcr::YCbCr;
|
||||
use super::{
|
||||
ChannelLayout, ChunkType, CodecError, DecodeWarning, Decoder, ExifDirs, File, Ifd, Image, Limits, Metadata, Read, SampleType, Seek, SeekFrom, Tag,
|
||||
camera_raw, err, ifd, io, map_err, tiff_exif,
|
||||
ChannelLayout, ChunkType, CodecError, DecodeWarning, Decoder, ExifDirs, File, Ifd, Image, Limits, Metadata, Read, SampleType, Seek, SeekFrom,
|
||||
Tag, camera_raw, err, ifd, io, map_err, tiff_exif,
|
||||
};
|
||||
|
||||
/// Decodes the page Photoshop would open: the first full-resolution directory.
|
||||
@@ -46,7 +46,10 @@ pub(crate) fn has_unretained_samples(bytes: &[u8], offset: u64) -> Result<bool,
|
||||
/// [`DecodeWarning::MorePages`] the page opens with when the file holds more.
|
||||
fn open_page(bytes: &[u8], page: Option<usize>) -> Result<(File<'_>, Ifd, Option<DecodeWarning>), CodecError> {
|
||||
if camera_raw(bytes) {
|
||||
return Err(CodecError::unsupported(F, "camera raw files (such as CR2, NEF, ARW or DNG) are not flat images; decode them with photocraft-raw"));
|
||||
return Err(CodecError::unsupported(
|
||||
F,
|
||||
"camera raw files (such as CR2, NEF, ARW or DNG) are not flat images; decode them with photocraft-raw",
|
||||
));
|
||||
}
|
||||
let file = File::parse(bytes).ok_or_else(|| err("not a TIFF or BigTIFF header"))?;
|
||||
let info = ifd::info_of(&file)?;
|
||||
@@ -262,7 +265,10 @@ fn scratch_bound(direct: bool, chunk_bytes: u64, band_rows: usize, h: u32, worke
|
||||
pub(crate) fn orientation(bytes: &[u8], page: Option<usize>) -> u16 {
|
||||
let Some(file) = File::parse(bytes) else { return 1 };
|
||||
let Ok(info) = ifd::info_of(&file) else { return 1 };
|
||||
page.or_else(|| info.default_page()).and_then(|i| info.pages.get(i)).and_then(|p| file.ifd(p.ifd_offset)).map_or(1, |d| ifd::orientation_of(&file, &d))
|
||||
page.or_else(|| info.default_page())
|
||||
.and_then(|i| info.pages.get(i))
|
||||
.and_then(|p| file.ifd(p.ifd_offset))
|
||||
.map_or(1, |d| ifd::orientation_of(&file, &d))
|
||||
}
|
||||
|
||||
/// The page's metadata; the ICC profile goes to `icc`.
|
||||
|
||||
@@ -111,7 +111,8 @@ macro_rules! write_extras {
|
||||
/// is an error, not an abort.
|
||||
pub(super) fn try_with_capacity<T>(len: usize) -> io::Result<Vec<T>> {
|
||||
let mut v = Vec::new();
|
||||
v.try_reserve_exact(len).map_err(|_| io::Error::new(io::ErrorKind::OutOfMemory, format!("cannot allocate {len} samples for the extra samples")))?;
|
||||
v.try_reserve_exact(len)
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::OutOfMemory, format!("cannot allocate {len} samples for the extra samples")))?;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
@@ -411,7 +412,8 @@ pub(super) fn half_size(img: &Image) -> Result<Image, CodecError> {
|
||||
let ch = layout.channels();
|
||||
let bps = sample.bytes();
|
||||
let src_row = (w as usize).checked_mul(ch).and_then(|n| n.checked_mul(bps)).ok_or_else(|| CodecError::encode(F, "image row size overflows"))?;
|
||||
let out_row = (nw as usize).checked_mul(ch).and_then(|n| n.checked_mul(bps)).ok_or_else(|| CodecError::encode(F, "pyramid row size overflows"))?;
|
||||
let out_row =
|
||||
(nw as usize).checked_mul(ch).and_then(|n| n.checked_mul(bps)).ok_or_else(|| CodecError::encode(F, "pyramid row size overflows"))?;
|
||||
let len = out_row.checked_mul(nh as usize).ok_or_else(|| CodecError::encode(F, "pyramid level size overflows"))?;
|
||||
if img.data().len() < src_row.saturating_mul(h as usize) {
|
||||
return Err(CodecError::encode(F, "image buffer is shorter than its dimensions"));
|
||||
|
||||
@@ -157,7 +157,8 @@ pub(crate) fn block(dirs: &ExifDirs) -> Vec<u8> {
|
||||
ifd0.push(pointer(TAG_GPS_IFD));
|
||||
}
|
||||
// Layout: header, then each directory followed by its out-of-line values.
|
||||
let size = |fs: &[Field]| 2 + 12 * fs.len() + 4 + fs.iter().filter(|f| f.value.len() > 4).map(|f| f.value.len().next_multiple_of(2)).sum::<usize>();
|
||||
let size =
|
||||
|fs: &[Field]| 2 + 12 * fs.len() + 4 + fs.iter().filter(|f| f.value.len() > 4).map(|f| f.value.len().next_multiple_of(2)).sum::<usize>();
|
||||
let at0 = 8;
|
||||
let at_exif = at0 + size(&ifd0);
|
||||
let at_gps = at_exif + if dirs.exif.is_empty() { 0 } else { size(&dirs.exif) };
|
||||
|
||||
@@ -327,7 +327,9 @@ fn to_dynamic(img: &Image) -> Result<DynamicImage, CodecError> {
|
||||
let bad = || CodecError::InvalidImage("buffer size mismatch".into());
|
||||
Ok(match (img.layout(), img.sample_type()) {
|
||||
(ChannelLayout::Gray, SampleType::U8) => DynamicImage::ImageLuma8(image::GrayImage::from_raw(w, h, img.data().to_vec()).ok_or_else(bad)?),
|
||||
(ChannelLayout::GrayA, SampleType::U8) => DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(w, h, img.data().to_vec()).ok_or_else(bad)?),
|
||||
(ChannelLayout::GrayA, SampleType::U8) => {
|
||||
DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(w, h, img.data().to_vec()).ok_or_else(bad)?)
|
||||
}
|
||||
(ChannelLayout::Rgb, SampleType::U8) => DynamicImage::ImageRgb8(image::RgbImage::from_raw(w, h, img.data().to_vec()).ok_or_else(bad)?),
|
||||
(ChannelLayout::Rgba, SampleType::U8) => DynamicImage::ImageRgba8(image::RgbaImage::from_raw(w, h, img.data().to_vec()).ok_or_else(bad)?),
|
||||
(ChannelLayout::Rgb, SampleType::F32) => {
|
||||
|
||||
@@ -20,9 +20,9 @@ mod transform;
|
||||
use bool_encoder::BoolEncoder;
|
||||
use predict::{Plane, SubEdges, predict_block, predict_sub};
|
||||
use tables::{
|
||||
AC_QLOOKUP, B_DC_PRED, B_HE_PRED, B_PRED, B_TM_PRED, B_VE_PRED, BMODE_TREE, CAT_BASE, COEFF_BANDS, COEFF_TREE, COEFF_UPDATE_PROBS, DC_PRED, DC_QLOOKUP,
|
||||
DCT_0, DCT_1, DCT_2, DCT_3, DCT_4, DCT_CAT1, DCT_CAT2, DCT_CAT3, DCT_CAT4, DCT_CAT5, DCT_CAT6, DCT_EOB, DEFAULT_COEFF_PROBS, H_PRED, KF_BMODE_PROBS,
|
||||
KF_UV_MODE_PROB, KF_YMODE_PROB, KF_YMODE_TREE, PCAT, TM_PRED, UV_MODE_TREE, V_PRED, ZIGZAG,
|
||||
AC_QLOOKUP, B_DC_PRED, B_HE_PRED, B_PRED, B_TM_PRED, B_VE_PRED, BMODE_TREE, CAT_BASE, COEFF_BANDS, COEFF_TREE, COEFF_UPDATE_PROBS, DC_PRED,
|
||||
DC_QLOOKUP, DCT_0, DCT_1, DCT_2, DCT_3, DCT_4, DCT_CAT1, DCT_CAT2, DCT_CAT3, DCT_CAT4, DCT_CAT5, DCT_CAT6, DCT_EOB, DEFAULT_COEFF_PROBS, H_PRED,
|
||||
KF_BMODE_PROBS, KF_UV_MODE_PROB, KF_YMODE_PROB, KF_YMODE_TREE, PCAT, TM_PRED, UV_MODE_TREE, V_PRED, ZIGZAG,
|
||||
};
|
||||
use transform::{fdct, fwht, idct, iwht};
|
||||
|
||||
|
||||
@@ -98,8 +98,14 @@ pub const COEFF_TREE: Tree = &[
|
||||
|
||||
/// Extra-bit probabilities of the six value categories (RFC 6386 §13.2), most significant bit
|
||||
/// first; the category bases are 5, 7, 11, 19, 35 and 67.
|
||||
pub const PCAT: [&[u8]; 6] =
|
||||
[&[159], &[165, 145], &[173, 148, 140], &[176, 155, 140, 135], &[180, 157, 141, 134, 130], &[254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129]];
|
||||
pub const PCAT: [&[u8]; 6] = [
|
||||
&[159],
|
||||
&[165, 145],
|
||||
&[173, 148, 140],
|
||||
&[176, 155, 140, 135],
|
||||
&[180, 157, 141, 134, 130],
|
||||
&[254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129],
|
||||
];
|
||||
pub const CAT_BASE: [i32; 6] = [5, 7, 11, 19, 35, 67];
|
||||
|
||||
/// Coefficient position → probability band (RFC 6386 §13.3).
|
||||
@@ -454,18 +460,18 @@ pub const COEFF_UPDATE_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [
|
||||
|
||||
/// DC dequantization factors by quantizer index (RFC 6386 §14.1).
|
||||
pub const DC_QLOOKUP: [i32; 128] = [
|
||||
4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
|
||||
37, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
|
||||
74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 122, 124,
|
||||
126, 128, 130, 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157,
|
||||
4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
|
||||
35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68,
|
||||
69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110,
|
||||
112, 114, 116, 118, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157,
|
||||
];
|
||||
|
||||
/// AC dequantization factors by quantizer index (RFC 6386 §14.1).
|
||||
pub const AC_QLOOKUP: [i32; 128] = [
|
||||
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
|
||||
44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104,
|
||||
106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197,
|
||||
201, 205, 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284,
|
||||
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
|
||||
42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96,
|
||||
98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173,
|
||||
177, 181, 185, 189, 193, 197, 201, 205, 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284,
|
||||
];
|
||||
|
||||
/// Key-frame sub-block mode probabilities `[above mode][left mode][tree node]` (RFC 6386 §11.5).
|
||||
|
||||
@@ -186,7 +186,8 @@ pub(crate) fn export_exif(img: &Image) -> Option<Vec<u8>> {
|
||||
pub(crate) fn keeps_dpi(img: &Image) -> bool {
|
||||
let bare_default = img.meta.exif.as_deref().is_none_or(<[u8]>::is_empty) && img.meta.dpi.is_none_or(is_default_ppi);
|
||||
// The XMP written beside it carries the resolution too, and readers look there first.
|
||||
let in_xmp = img.meta.xmp.as_deref().is_some_and(|x| crate::resolution::xmp_resolution(&crate::resolution::export_xmp(x, img.meta.dpi)).is_some());
|
||||
let in_xmp =
|
||||
img.meta.xmp.as_deref().is_some_and(|x| crate::resolution::xmp_resolution(&crate::resolution::export_xmp(x, img.meta.dpi)).is_some());
|
||||
bare_default || in_xmp || export_exif(img).is_some_and(|e| crate::resolution::exif_resolution(&e).is_some())
|
||||
}
|
||||
|
||||
|
||||
@@ -143,7 +143,8 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
}
|
||||
// The same channels the whole-file decoder shows, so both routes open the same image.
|
||||
let names: Vec<String> = list.iter().map(|c| c.name.to_string()).collect();
|
||||
let (layout, picked) = crate::image::exr_color_channels(names.iter().map(String::as_str)).ok_or_else(|| unsupported("no R/G/B or Y channels"))?;
|
||||
let (layout, picked) =
|
||||
crate::image::exr_color_channels(names.iter().map(String::as_str)).ok_or_else(|| unsupported("no R/G/B or Y channels"))?;
|
||||
let gray = matches!(layout, crate::ChannelLayout::Gray | crate::ChannelLayout::GrayA);
|
||||
let mut selected: Vec<Option<usize>> = picked.into_iter().map(Some).collect();
|
||||
if !matches!(layout, crate::ChannelLayout::GrayA | crate::ChannelLayout::Rgba) {
|
||||
@@ -241,8 +242,10 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
}
|
||||
self.source.read_exact(bytes).map_err(invalid)?;
|
||||
}
|
||||
let chunk =
|
||||
Chunk { layer_index: 0, compressed_block: CompressedBlock::ScanLine(CompressedScanLineBlock { y_coordinate: y, compressed_pixels_le: packed }) };
|
||||
let chunk = Chunk {
|
||||
layer_index: 0,
|
||||
compressed_block: CompressedBlock::ScanLine(CompressedScanLineBlock { y_coordinate: y, compressed_pixels_le: packed }),
|
||||
};
|
||||
let block = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| UncompressedBlock::decompress_chunk(chunk, &self.meta, false)))
|
||||
.map_err(|_| invalid("invalid EXR compression block"))?
|
||||
.map_err(invalid)?;
|
||||
|
||||
@@ -164,7 +164,9 @@ pub(crate) fn plan(image: &Image, format: Format, opts: &EncodeOptions) -> Plan
|
||||
match format {
|
||||
// PNM: integer data can use any layout (PAM); float goes to PFM
|
||||
// which only has gray and RGB.
|
||||
Format::Pnm if sample.is_float() => Plan { layout: pick_layout(layout, &[ChannelLayout::Gray, ChannelLayout::Rgb], false), sample: SampleType::F32 },
|
||||
Format::Pnm if sample.is_float() => {
|
||||
Plan { layout: pick_layout(layout, &[ChannelLayout::Gray, ChannelLayout::Rgb], false), sample: SampleType::F32 }
|
||||
}
|
||||
// DPX has no luma + alpha descriptor: gray with alpha is written as luma, alpha dropped.
|
||||
// The sample type follows the chosen bits (U8 for 8, U16 for 10, 12 and 16).
|
||||
Format::Dpx => Plan {
|
||||
|
||||
@@ -73,7 +73,10 @@ pub struct FormatCaps {
|
||||
/// Formats that are enabled but intentionally not symmetric, with the reason.
|
||||
/// The test-suite asserts that every other enabled format is read+write.
|
||||
pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[
|
||||
(Format::Xpm, "XPM is a legacy Unix icon interchange format. Reading existing XPM icons is supported; writing modern image assets should use PNG instead."),
|
||||
(
|
||||
Format::Xpm,
|
||||
"XPM is a legacy Unix icon interchange format. Reading existing XPM icons is supported; writing modern image assets should use PNG instead.",
|
||||
),
|
||||
(
|
||||
Format::Dicom,
|
||||
"DICOM single-frame images are imported for medical review; this crate has no DICOM writer, so save an imported frame as TIFF or PNG instead.",
|
||||
@@ -257,11 +260,23 @@ pub fn caps(format: Format) -> FormatCaps {
|
||||
lossy: false,
|
||||
};
|
||||
match format {
|
||||
Format::Png => {
|
||||
FormatCaps { depths: &[S::U8, S::U16], layouts: RGB_GRAY, icc: true, exif: true, xmp: true, dpi: true, text: true, animation: true, ..base }
|
||||
Format::Png => FormatCaps {
|
||||
depths: &[S::U8, S::U16],
|
||||
layouts: RGB_GRAY,
|
||||
icc: true,
|
||||
exif: true,
|
||||
xmp: true,
|
||||
dpi: true,
|
||||
text: true,
|
||||
animation: true,
|
||||
..base
|
||||
},
|
||||
Format::Jpeg => {
|
||||
FormatCaps { layouts: &[L::Gray, L::Rgb, L::Cmyk], alpha: false, icc: true, exif: true, xmp: true, dpi: true, lossy: true, ..base }
|
||||
}
|
||||
Format::Tiff => {
|
||||
FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: TIFF_LAYOUTS, icc: true, exif: true, xmp: true, dpi: true, text: true, ..base }
|
||||
}
|
||||
Format::Jpeg => FormatCaps { layouts: &[L::Gray, L::Rgb, L::Cmyk], alpha: false, icc: true, exif: true, xmp: true, dpi: true, lossy: true, ..base },
|
||||
Format::Tiff => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: TIFF_LAYOUTS, icc: true, exif: true, xmp: true, dpi: true, text: true, ..base },
|
||||
// Resolution travels in EXIF (WebP has no field of its own).
|
||||
Format::WebP => FormatCaps { icc: true, exif: true, xmp: true, dpi: true, animation: true, ..base },
|
||||
Format::Gif => FormatCaps { layouts: &[L::Rgba], animation: true, lossy: true, ..base },
|
||||
|
||||
@@ -97,7 +97,10 @@ impl ChannelLayout {
|
||||
|
||||
/// `true` if both layouts share a colour model (ignoring alpha).
|
||||
pub const fn same_model(self, other: Self) -> bool {
|
||||
(self.is_gray() && other.is_gray()) || (self.is_rgb() && other.is_rgb()) || (self.is_cmyk() && other.is_cmyk()) || (self.is_lab() && other.is_lab())
|
||||
(self.is_gray() && other.is_gray())
|
||||
|| (self.is_rgb() && other.is_rgb())
|
||||
|| (self.is_cmyk() && other.is_cmyk())
|
||||
|| (self.is_lab() && other.is_lab())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -521,7 +524,10 @@ impl Image {
|
||||
pub fn from_raw(width: u32, height: u32, layout: ChannelLayout, sample: SampleType, data: Vec<u8>) -> Result<Self, CodecError> {
|
||||
let expected = byte_len(width, height, layout, sample).ok_or_else(|| CodecError::InvalidImage("image size overflows usize".into()))?;
|
||||
if data.len() != expected {
|
||||
return Err(CodecError::InvalidImage(format!("buffer has {} bytes, expected {expected} for {width}x{height} {layout:?} {sample:?}", data.len())));
|
||||
return Err(CodecError::InvalidImage(format!(
|
||||
"buffer has {} bytes, expected {expected} for {width}x{height} {layout:?} {sample:?}",
|
||||
data.len()
|
||||
)));
|
||||
}
|
||||
Ok(Image { width, height, layout, sample, data, icc: None, cicp: None, meta: Metadata::default(), warnings: Vec::new() })
|
||||
}
|
||||
@@ -607,7 +613,8 @@ impl Image {
|
||||
|
||||
/// Copy samples out as `f16` (only when the sample type is `F16`).
|
||||
pub fn to_f16_samples(&self) -> Option<Vec<f16>> {
|
||||
(self.sample == SampleType::F16).then(|| self.data.as_chunks::<2>().0.iter().map(|c| f16::from_bits(u16::from_ne_bytes([c[0], c[1]]))).collect())
|
||||
(self.sample == SampleType::F16)
|
||||
.then(|| self.data.as_chunks::<2>().0.iter().map(|c| f16::from_bits(u16::from_ne_bytes([c[0], c[1]]))).collect())
|
||||
}
|
||||
|
||||
/// Copy samples out as `f32` (only when the sample type is `F32`).
|
||||
@@ -688,7 +695,11 @@ impl Image {
|
||||
/// [`Image::convert`], borrowing `self` when it already has that layout and sample type
|
||||
/// (encoders use it so a full-size image isn't copied for nothing).
|
||||
pub fn converted(&self, layout: ChannelLayout, sample: SampleType) -> std::borrow::Cow<'_, Image> {
|
||||
if layout == self.layout && sample == self.sample { std::borrow::Cow::Borrowed(self) } else { std::borrow::Cow::Owned(self.convert(layout, sample)) }
|
||||
if layout == self.layout && sample == self.sample {
|
||||
std::borrow::Cow::Borrowed(self)
|
||||
} else {
|
||||
std::borrow::Cow::Owned(self.convert(layout, sample))
|
||||
}
|
||||
}
|
||||
|
||||
/// Interleaved RGBA, 8 bits per sample.
|
||||
@@ -742,10 +753,21 @@ fn convert_data(data: &[u8], from: ChannelLayout, from_sample: SampleType, layou
|
||||
/// [`Image::convert`] on borrowed pixels: `rows` rows of `width` pixels in `from` (layout, sample
|
||||
/// type) become the same pixels in `to`, bit for bit what the image conversion gives. Lets a
|
||||
/// caller convert a band of a decoded image without copying it into an [`Image`] first.
|
||||
pub fn convert_samples(src: &[u8], width: u32, rows: u32, from: (ChannelLayout, SampleType), to: (ChannelLayout, SampleType)) -> Result<Vec<u8>, CodecError> {
|
||||
pub fn convert_samples(
|
||||
src: &[u8],
|
||||
width: u32,
|
||||
rows: u32,
|
||||
from: (ChannelLayout, SampleType),
|
||||
to: (ChannelLayout, SampleType),
|
||||
) -> Result<Vec<u8>, CodecError> {
|
||||
let expected = byte_len(width, rows, from.0, from.1).ok_or_else(|| CodecError::InvalidImage("image size overflows usize".into()))?;
|
||||
if src.len() != expected {
|
||||
return Err(CodecError::InvalidImage(format!("buffer has {} bytes, expected {expected} for {width}x{rows} {:?} {:?}", src.len(), from.0, from.1)));
|
||||
return Err(CodecError::InvalidImage(format!(
|
||||
"buffer has {} bytes, expected {expected} for {width}x{rows} {:?} {:?}",
|
||||
src.len(),
|
||||
from.0,
|
||||
from.1
|
||||
)));
|
||||
}
|
||||
Ok(convert_data(src, from.0, from.1, to.0, to.1))
|
||||
}
|
||||
@@ -919,7 +941,9 @@ mod tests {
|
||||
let got = convert_samples(img.data(), 5, 2, (ChannelLayout::Rgb, sample), (layout, to)).unwrap();
|
||||
assert_eq!(got, want.data(), "{sample:?} to {layout:?} {to:?}");
|
||||
}
|
||||
assert!(convert_samples(img.data().get(1..).unwrap_or_default(), 5, 2, (ChannelLayout::Rgb, sample), (ChannelLayout::Rgba, sample)).is_err());
|
||||
assert!(
|
||||
convert_samples(img.data().get(1..).unwrap_or_default(), 5, 2, (ChannelLayout::Rgb, sample), (ChannelLayout::Rgba, sample)).is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -933,9 +957,12 @@ mod tests {
|
||||
// Every U8 and every U16 value through every depth pair (alpha goes through the same per-sample conversion; covered by the layout test).
|
||||
let all8: Vec<u8> = (0..=255).collect();
|
||||
let all16: Vec<u16> = (0..=65535).collect();
|
||||
for (src, to) in
|
||||
[(SampleType::U8, SampleType::U8), (SampleType::U8, SampleType::U16), (SampleType::U16, SampleType::U8), (SampleType::U16, SampleType::U16)]
|
||||
{
|
||||
for (src, to) in [
|
||||
(SampleType::U8, SampleType::U8),
|
||||
(SampleType::U8, SampleType::U16),
|
||||
(SampleType::U16, SampleType::U8),
|
||||
(SampleType::U16, SampleType::U16),
|
||||
] {
|
||||
let img = if src == SampleType::U8 {
|
||||
Image::from_u8(256, 1, ChannelLayout::Gray, all8.clone()).unwrap()
|
||||
} else {
|
||||
|
||||
@@ -48,8 +48,8 @@ pub use crate::image::{
|
||||
MAX_EXTRA_SAMPLES, Metadata, SampleType, convert_samples,
|
||||
};
|
||||
pub use crate::options::{
|
||||
DdsCompression, DdsOptions, DecodeOptions, DpxBits, EncodeOptions, ExrCompression, JpegFormat, Limits, PngCompression, PngStereo, TIFF_PYRAMID_MIN,
|
||||
TiffCompression,
|
||||
DdsCompression, DdsOptions, DecodeOptions, DpxBits, EncodeOptions, ExrCompression, JpegFormat, Limits, PngCompression, PngStereo,
|
||||
TIFF_PYRAMID_MIN, TiffCompression,
|
||||
};
|
||||
pub use crate::orientation::{OrientSteps, exif_orientation, upright_exif, upright_xmp};
|
||||
pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_resolution, xmp_resolution};
|
||||
@@ -284,7 +284,10 @@ pub fn has_unretained_source_data(bytes: &[u8]) -> Result<bool, CodecError> {
|
||||
retained.and_then(|index| info.pages.get(index)).map_or(Ok(false), |page| tiff::has_unretained_samples(bytes, page.ifd_offset))
|
||||
}
|
||||
Some(Format::Ico) => {
|
||||
let count = bytes.get(4..6).and_then(|b| <[u8; 2]>::try_from(b).ok()).ok_or_else(|| CodecError::malformed(Format::Ico, "truncated image count"))?;
|
||||
let count = bytes
|
||||
.get(4..6)
|
||||
.and_then(|b| <[u8; 2]>::try_from(b).ok())
|
||||
.ok_or_else(|| CodecError::malformed(Format::Ico, "truncated image count"))?;
|
||||
Ok(u16::from_le_bytes(count) > 1)
|
||||
}
|
||||
Some(Format::Dds) => dds::has_additional_images(bytes),
|
||||
@@ -416,6 +419,8 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result<Vec
|
||||
Format::OpenExr => exr::encode(image, plan, opts),
|
||||
Format::Heif => Err(CodecError::unsupported(format, "encoding is not available in this build")),
|
||||
Format::Jxl => jxl::encode(image, plan),
|
||||
Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::encode(format, image, plan, opts),
|
||||
Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => {
|
||||
via_image::encode(format, image, plan, opts)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -177,8 +177,10 @@ pub fn upright_exif(exif: &[u8]) -> Cow<'_, [u8]> {
|
||||
let Some((order, first, count, entry_bytes, big_tiff)) = ifd0_entries(body) else {
|
||||
return Cow::Borrowed(exif);
|
||||
};
|
||||
let values: Vec<Value> =
|
||||
(0..count).filter_map(|i| first.checked_add(i.checked_mul(entry_bytes)?)).filter_map(|e| orientation_value(order, body, e, big_tiff)).collect();
|
||||
let values: Vec<Value> = (0..count)
|
||||
.filter_map(|i| first.checked_add(i.checked_mul(entry_bytes)?))
|
||||
.filter_map(|e| orientation_value(order, body, e, big_tiff))
|
||||
.collect();
|
||||
if values.iter().all(|v| v.read(order, body) == Some(1)) {
|
||||
return Cow::Borrowed(exif);
|
||||
}
|
||||
|
||||
@@ -40,8 +40,8 @@ const ANNEX_K_CHROMA: [u16; 64] = [
|
||||
/// The natural-order index of the k-th coefficient in zig-zag order (T.81 Figure A.6): DQT
|
||||
/// stores its 64 values in this order.
|
||||
const ZIGZAG: [usize; 64] = [
|
||||
0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29,
|
||||
22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
|
||||
0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43,
|
||||
36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
|
||||
];
|
||||
|
||||
/// One quantisation table from a DQT segment, in natural order, with its precision.
|
||||
@@ -129,7 +129,11 @@ fn read_dqt(mut seg: &[u8], tables: &mut [Option<Table>; 4]) {
|
||||
let Some(data) = rest.get(..n) else { return };
|
||||
let mut values = [0u16; 64];
|
||||
for (k, &natural) in ZIGZAG.iter().enumerate() {
|
||||
let v = if wide { data.get(2 * k..2 * k + 2).map_or(0, |p| u16::from_be_bytes([p[0], p[1]])) } else { data.get(k).map_or(0, |&p| u16::from(p)) };
|
||||
let v = if wide {
|
||||
data.get(2 * k..2 * k + 2).map_or(0, |p| u16::from_be_bytes([p[0], p[1]]))
|
||||
} else {
|
||||
data.get(k).map_or(0, |&p| u16::from(p))
|
||||
};
|
||||
if let Some(dst) = values.get_mut(natural) {
|
||||
*dst = v;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Writing DDS textures: every storage read back through the reader, the header fields, sizes
|
||||
//! that aren't a multiple of four, the mip chain, and the block-compression error on ramps.
|
||||
|
||||
use craft_image_codecs::{ChannelLayout, DdsCompression, DdsOptions, EncodeOptions, FidelityWarning, Format, Image, decode, encode, fidelity_warnings_with};
|
||||
use craft_image_codecs::{
|
||||
ChannelLayout, DdsCompression, DdsOptions, EncodeOptions, FidelityWarning, Format, Image, decode, encode, fidelity_warnings_with,
|
||||
};
|
||||
|
||||
const DDSD_PITCH: u32 = 0x8;
|
||||
const DDSD_MIPMAPCOUNT: u32 = 0x2_0000;
|
||||
@@ -65,7 +67,8 @@ fn max_colour_diff(a: &Image, b: &Image) -> u8 {
|
||||
|
||||
/// A 2D gradient: red across, green down and blue along the diagonal, opaque.
|
||||
fn gradient(w: u32, h: u32) -> Image {
|
||||
let data = (0..h).flat_map(|y| (0..w).flat_map(move |x| [(x * 4).min(255) as u8, (y * 4).min(255) as u8, ((x + y) * 2).min(255) as u8, 255])).collect();
|
||||
let data =
|
||||
(0..h).flat_map(|y| (0..w).flat_map(move |x| [(x * 4).min(255) as u8, (y * 4).min(255) as u8, ((x + y) * 2).min(255) as u8, 255])).collect();
|
||||
Image::from_u8(w, h, ChannelLayout::Rgba, data).unwrap()
|
||||
}
|
||||
|
||||
@@ -163,7 +166,9 @@ fn block_compressed_textures_round_trip_through_the_reader() {
|
||||
assert!(colour <= 24, "{compression:?} {w}x{h}: colour off by {colour}");
|
||||
let alpha = max_diff_channel(&img, &back, 3);
|
||||
match compression {
|
||||
DdsCompression::Bc1 => assert!(back.data().chunks(4).zip(img.data().chunks(4)).all(|(b, i)| b[3] == if i[3] < 128 { 0 } else { 255 })),
|
||||
DdsCompression::Bc1 => {
|
||||
assert!(back.data().chunks(4).zip(img.data().chunks(4)).all(|(b, i)| b[3] == if i[3] < 128 { 0 } else { 255 }))
|
||||
}
|
||||
_ => assert!(alpha <= 8, "{compression:?} {w}x{h}: alpha off by {alpha}"),
|
||||
}
|
||||
}
|
||||
@@ -201,7 +206,9 @@ fn block_compression_error_on_gradients_is_bounded() {
|
||||
assert!(plane_err <= 10, "{compression:?}: 2D gradient off by {plane_err}");
|
||||
assert!(p >= 38.0, "{compression:?}: 2D gradient PSNR {p:.1} dB");
|
||||
match compression {
|
||||
DdsCompression::Bc1 => assert!(line_back.data().chunks(4).zip(line.data().chunks(4)).all(|(b, i)| b[3] == if i[3] < 128 { 0 } else { 255 })),
|
||||
DdsCompression::Bc1 => {
|
||||
assert!(line_back.data().chunks(4).zip(line.data().chunks(4)).all(|(b, i)| b[3] == if i[3] < 128 { 0 } else { 255 }))
|
||||
}
|
||||
// Four bits: within half a step of 17.
|
||||
DdsCompression::Bc2 => assert!(alpha <= 8, "BC2 alpha off by {alpha}"),
|
||||
// Eight values across a block's few levels of alpha.
|
||||
|
||||
@@ -159,7 +159,8 @@ fn apng(frames: u32, sixteen: bool, separate_default: bool) -> Vec<u8> {
|
||||
}
|
||||
let mut w = enc.write_header().unwrap();
|
||||
for c in COLOURS.iter().cycle().take(images.max(1) as usize) {
|
||||
let px: Vec<u8> = if sixteen { c.iter().flat_map(|&v| [v, v]).collect::<Vec<u8>>().repeat((W * H) as usize) } else { c.repeat((W * H) as usize) };
|
||||
let px: Vec<u8> =
|
||||
if sixteen { c.iter().flat_map(|&v| [v, v]).collect::<Vec<u8>>().repeat((W * H) as usize) } else { c.repeat((W * H) as usize) };
|
||||
w.write_image_data(&px).unwrap();
|
||||
}
|
||||
w.finish().unwrap();
|
||||
|
||||
@@ -383,8 +383,9 @@ fn opaque_front_hides_back() {
|
||||
fn hdr_colour_is_kept_and_edge_tiles_match_scanlines() {
|
||||
let (w, h) = (7, 5);
|
||||
let counts: Vec<u32> = (0..w * h).map(|p| (p as u32 * 3) % 4).collect();
|
||||
let sample =
|
||||
|p: usize, ci: usize| -> Vec<f32> { (0..(p as u32 * 3) % 4).map(|k| [1.0, 0.25 * k as f32, 0.5, 2.0 + p as f32 / 8.0, 10.0 - k as f32][ci]).collect() };
|
||||
let sample = |p: usize, ci: usize| -> Vec<f32> {
|
||||
(0..(p as u32 * 3) % 4).map(|k| [1.0, 0.25 * k as f32, 0.5, 2.0 + p as f32 / 8.0, 10.0 - k as f32][ci]).collect()
|
||||
};
|
||||
for compression in [0u8, 1, 2] {
|
||||
let scan = rgba_flat(&gen_deep(w, h, &RGBAZ, compression, None, &counts, &sample));
|
||||
let tiled = rgba_flat(&gen_deep(w, h, &RGBAZ, compression, Some((3, 2)), &counts, &sample));
|
||||
@@ -482,7 +483,8 @@ fn tiles_match_scanlines() {
|
||||
/// Half-float channels come back as F16 samples with exact values.
|
||||
#[test]
|
||||
fn half_channels_round_trip() {
|
||||
let channels = [Chan { name: "A", ty: 1 }, Chan { name: "B", ty: 1 }, Chan { name: "G", ty: 1 }, Chan { name: "R", ty: 1 }, Chan { name: "Z", ty: 1 }];
|
||||
let channels =
|
||||
[Chan { name: "A", ty: 1 }, Chan { name: "B", ty: 1 }, Chan { name: "G", ty: 1 }, Chan { name: "R", ty: 1 }, Chan { name: "Z", ty: 1 }];
|
||||
let bytes = gen_deep(4, 4, &channels, 2, None, COUNTS_ONE, &|p, _ci| {
|
||||
let v = f16::from_f32(0.5).to_f32();
|
||||
vec![v * (p as f32 + 1.0) / 4.0]
|
||||
@@ -661,7 +663,11 @@ fn deep_tile_count_table_is_admitted_against_max_alloc() {
|
||||
// The table and its scratch copy are admitted together: 8 MiB.
|
||||
assert_eq!(decode_deep_exr(&big, &budget(2 * table)).expect("room for the table and its copy"), scan, "compression {compression}");
|
||||
let got = decode_deep_exr(&big, &budget(2 * table - 1));
|
||||
assert!(matches!(got, Err(CodecError::LimitExceeded(_))), "compression {compression}: one byte short gave {:?}", got.map(|d| d.total_samples()));
|
||||
assert!(
|
||||
matches!(got, Err(CodecError::LimitExceeded(_))),
|
||||
"compression {compression}: one byte short gave {:?}",
|
||||
got.map(|d| d.total_samples())
|
||||
);
|
||||
}
|
||||
// Ordinary tiles: full-size edge tables decode under the small budget, like clipped ones.
|
||||
let counts: Vec<u32> = (0..35).map(|p| (p * 3) % 4).collect();
|
||||
@@ -729,7 +735,8 @@ fn clipped_count_tables_include_scratch_in_the_budget() {
|
||||
let required = if compression == 0 { 256 } else { 512 };
|
||||
assert_eq!(decode_deep_exr(&bytes, &budget(required)).expect("table and any scratch fit exactly"), want, "{what}");
|
||||
assert!(matches!(decode_deep_exr(&bytes, &budget(required - 1)), Err(CodecError::LimitExceeded(_))), "{what}");
|
||||
let flat = craft_image_codecs::decode_with(&bytes, &craft_image_codecs::DecodeOptions { limits: budget(required - 1), ..Default::default() });
|
||||
let flat =
|
||||
craft_image_codecs::decode_with(&bytes, &craft_image_codecs::DecodeOptions { limits: budget(required - 1), ..Default::default() });
|
||||
assert!(matches!(flat, Err(CodecError::LimitExceeded(_))), "{what}");
|
||||
if compression == 0 {
|
||||
assert_eq!(decode_deep_exr(&bytes, &budget(511)).expect("raw table needs no scratch"), want, "{what}");
|
||||
@@ -802,9 +809,10 @@ type RealFile = (&'static str, u64, u64, &'static [(&'static str, &'static [u32]
|
||||
|
||||
#[cfg(feature = "corpus")]
|
||||
const MULTIVARIATE_IDS: &[u32] = &[
|
||||
127035619, 147085119, 319332210, 409096490, 523461226, 678492822, 683859976, 1058109025, 1193275200, 1503246798, 1552124883, 1613501244, 1672208113,
|
||||
1687665471, 1741895317, 1841370478, 1863854195, 1865183722, 2056745377, 2202049807, 2303547305, 2369798380, 2433329986, 2439705590, 2505186565, 2698909330,
|
||||
2862333315, 2898564507, 2979371527, 3007860936, 3182339638, 3236172513, 3497437340, 3626859046, 3656820528, 3693645783, 3739501011, 3936563811, 4048943790,
|
||||
127035619, 147085119, 319332210, 409096490, 523461226, 678492822, 683859976, 1058109025, 1193275200, 1503246798, 1552124883, 1613501244,
|
||||
1672208113, 1687665471, 1741895317, 1841370478, 1863854195, 1865183722, 2056745377, 2202049807, 2303547305, 2369798380, 2433329986, 2439705590,
|
||||
2505186565, 2698909330, 2862333315, 2898564507, 2979371527, 3007860936, 3182339638, 3236172513, 3497437340, 3626859046, 3656820528, 3693645783,
|
||||
3739501011, 3936563811, 4048943790,
|
||||
];
|
||||
|
||||
#[cfg(feature = "corpus")]
|
||||
@@ -813,7 +821,10 @@ const REAL_FILES: &[RealFile] = &[
|
||||
"11.deep.exr",
|
||||
6056,
|
||||
2,
|
||||
&[("id", &[523461226, 683859976, 1552124883, 2202049807, 2303547305, 2433329986, 2698909330, 3182339638, 3236172513, 3626859046, 3739501011])],
|
||||
&[(
|
||||
"id",
|
||||
&[523461226, 683859976, 1552124883, 2202049807, 2303547305, 2433329986, 2698909330, 3182339638, 3236172513, 3626859046, 3739501011],
|
||||
)],
|
||||
),
|
||||
(
|
||||
"42.deep.exr",
|
||||
|
||||
@@ -346,7 +346,10 @@ fn saving_sixteen_bits_at_ten_or_twelve_warns_with_the_stored_bits() {
|
||||
}
|
||||
assert_eq!(depth_warnings(&img, Format::Dpx, &opts(Some(DpxBits::Bits16))), []);
|
||||
assert_eq!(depth_warnings(&img, Format::Dpx, &opts(None)), []);
|
||||
assert_eq!(depth_warnings(&img, Format::Dpx, &opts(Some(DpxBits::Bits8))), [FidelityWarning::DepthReduced { from: SampleType::U16, to: SampleType::U8 }]);
|
||||
assert_eq!(
|
||||
depth_warnings(&img, Format::Dpx, &opts(Some(DpxBits::Bits8))),
|
||||
[FidelityWarning::DepthReduced { from: SampleType::U16, to: SampleType::U8 }]
|
||||
);
|
||||
assert_eq!(depth_warnings(&img, Format::Cineon, &EncodeOptions::default()), [FidelityWarning::BitsReduced { from: SampleType::U16, bits: 10 }]);
|
||||
}
|
||||
|
||||
@@ -360,7 +363,10 @@ fn a_frame_opened_at_ten_or_twelve_bits_saves_back_without_a_warning() {
|
||||
}
|
||||
// A 12-bit frame saved at 10 bits does lose its two low bits.
|
||||
let twelve = decode(&encode(&img, Format::Dpx, &opts(Some(DpxBits::Bits12))).unwrap()).unwrap();
|
||||
assert_eq!(depth_warnings(&twelve, Format::Dpx, &opts(Some(DpxBits::Bits10))), [FidelityWarning::BitsReduced { from: SampleType::U16, bits: 10 }]);
|
||||
assert_eq!(
|
||||
depth_warnings(&twelve, Format::Dpx, &opts(Some(DpxBits::Bits10))),
|
||||
[FidelityWarning::BitsReduced { from: SampleType::U16, bits: 10 }]
|
||||
);
|
||||
let cineon = decode(&cineon_bytes(3, 4, 2, &cineon_codes(24))).unwrap();
|
||||
assert_eq!(depth_warnings(&cineon, Format::Cineon, &EncodeOptions::default()), []);
|
||||
assert_eq!(depth_warnings(&cineon, Format::Dpx, &opts(Some(DpxBits::Bits10))), []);
|
||||
|
||||
@@ -4,11 +4,12 @@
|
||||
//! the manifest round trip and the per-pixel pairs. Malformed inputs must error or
|
||||
//! degrade, never panic.
|
||||
|
||||
use craft_image_codecs::{Limits, cryptomatte_id, cryptomatte_key, cryptomatte_layers, cryptomatte_preview_color, decode_cryptomatte};
|
||||
use exr::meta::attribute::{AttributeValue, Text};
|
||||
use exr::prelude::{
|
||||
AnyChannel, AnyChannels, Blocks, Compression, Encoding, FlatSamples, ImageAttributes, IntegerBounds, Layer, LayerAttributes, LineOrder, WritableImage,
|
||||
AnyChannel, AnyChannels, Blocks, Compression, Encoding, FlatSamples, ImageAttributes, IntegerBounds, Layer, LayerAttributes, LineOrder,
|
||||
WritableImage,
|
||||
};
|
||||
use craft_image_codecs::{Limits, cryptomatte_id, cryptomatte_key, cryptomatte_layers, cryptomatte_preview_color, decode_cryptomatte};
|
||||
|
||||
// -------------------------------------------------------------------------------------------
|
||||
// The official hash test vectors (cryptomatte_utilities_tests.py, CryptoHashing).
|
||||
@@ -77,7 +78,12 @@ fn cryptomatte_file(name: &str) -> Vec<u8> {
|
||||
let s1: Vec<f32> = (0..w * h).map(|p| if p % w == 0 { sphere } else { 0.0 }).collect();
|
||||
let s1c: Vec<f32> = (0..w * h).map(|p| if p % w == 0 { 0.25 } else { 0.0 }).collect();
|
||||
let mk = |n: String, v: Vec<f32>| AnyChannel::new(n.as_str(), FlatSamples::F32(v));
|
||||
let list = vec![mk(format!("{name}00.red"), s0), mk(format!("{name}00.green"), s0c), mk(format!("{name}01.red"), s1), mk(format!("{name}01.green"), s1c)];
|
||||
let list = vec![
|
||||
mk(format!("{name}00.red"), s0),
|
||||
mk(format!("{name}00.green"), s0c),
|
||||
mk(format!("{name}01.red"), s1),
|
||||
mk(format!("{name}01.green"), s1c),
|
||||
];
|
||||
let key = cryptomatte_key("CryptoAsset"); // attributes always use the canonical name
|
||||
let manifest = format!("{{\"cube\":\"{:08x}\",\"sphere\":\"{:08x}\"}}", cube.to_bits(), sphere.to_bits());
|
||||
let mut attrs = LayerAttributes::named(name);
|
||||
|
||||
@@ -3,14 +3,14 @@
|
||||
//! listing, the colour-ranked auto-pick and part-by-index decoding, and malformed
|
||||
//! inputs must error, never panic.
|
||||
|
||||
use exr::prelude::{
|
||||
AnyChannel, AnyChannels, Blocks, Compression, Encoding, FlatSamples, Image, ImageAttributes, IntegerBounds, Layer, LayerAttributes, LineOrder,
|
||||
WritableImage,
|
||||
};
|
||||
use craft_image_codecs::f16;
|
||||
use craft_image_codecs::{
|
||||
ChannelLayout, DecodeOptions, DecodeWarning, Format, Limits, SampleType, decode, decode_as_with, decode_exr_part, exr_info, probe_size,
|
||||
};
|
||||
use exr::prelude::{
|
||||
AnyChannel, AnyChannels, Blocks, Compression, Encoding, FlatSamples, Image, ImageAttributes, IntegerBounds, Layer, LayerAttributes, LineOrder,
|
||||
WritableImage,
|
||||
};
|
||||
|
||||
fn layer_f32(name: &str, comp: Compression, chans: &[(&str, Vec<f32>)]) -> Layer<AnyChannels<FlatSamples>> {
|
||||
let n = chans.iter().find(|(_, v)| !v.is_empty()).map_or(0, |(_, v)| v.len());
|
||||
@@ -49,7 +49,11 @@ fn aov_file() -> Vec<u8> {
|
||||
let diffuse: [Vec<f32>; 3] = std::array::from_fn(|c| (0..n).map(|_| [0.3, 0.6, 0.9][c]).collect());
|
||||
let layers = vec![
|
||||
layer_f32("Z", Compression::Uncompressed, &[("Z", z)]),
|
||||
layer_f32("beauty", Compression::ZIP1, &[("R", beauty[0].clone()), ("G", beauty[1].clone()), ("B", beauty[2].clone()), ("A", beauty[3].clone())]),
|
||||
layer_f32(
|
||||
"beauty",
|
||||
Compression::ZIP1,
|
||||
&[("R", beauty[0].clone()), ("G", beauty[1].clone()), ("B", beauty[2].clone()), ("A", beauty[3].clone())],
|
||||
),
|
||||
layer_f32("diffuse", Compression::RLE, &[("R", diffuse[0].clone()), ("G", diffuse[1].clone()), ("B", diffuse[2].clone())]),
|
||||
];
|
||||
write_image(layers)
|
||||
@@ -291,8 +295,15 @@ fn auto_pick_and_probe_skip_incoherent_rgb_parts() {
|
||||
|
||||
#[test]
|
||||
fn flat_decode_prefers_the_highest_ranked_complete_group() {
|
||||
let bytes =
|
||||
channel_group_file(&[("aaa.R", 9.0), ("aaa.G", 8.0), ("aaa.B", 7.0), ("beauty.R", 0.25), ("beauty.G", 0.5), ("beauty.B", 2.0), ("beauty.A", 0.75)]);
|
||||
let bytes = channel_group_file(&[
|
||||
("aaa.R", 9.0),
|
||||
("aaa.G", 8.0),
|
||||
("aaa.B", 7.0),
|
||||
("beauty.R", 0.25),
|
||||
("beauty.G", 0.5),
|
||||
("beauty.B", 2.0),
|
||||
("beauty.A", 0.75),
|
||||
]);
|
||||
assert_channel_group(&bytes, ChannelLayout::Rgba, &[0.25, 0.5, 2.0, 0.75]);
|
||||
let bytes = channel_group_file(&[("aaa.Y", 9.0), ("beauty.Y", 0.5), ("beauty.A", 0.75)]);
|
||||
assert_channel_group(&bytes, ChannelLayout::GrayA, &[0.5, 0.75]);
|
||||
|
||||
@@ -125,8 +125,12 @@ fn mixed_samples_and_offset_data_window_keep_coordinates_and_values() {
|
||||
.collect(),
|
||||
);
|
||||
let attributes = LayerAttributes { layer_position: exr::math::Vec2(-15, 40), ..Default::default() };
|
||||
let layer =
|
||||
Layer::new((31, 35), attributes, Encoding { compression: Compression::ZIP16, blocks: Blocks::ScanLines, line_order: LineOrder::Decreasing }, channels);
|
||||
let layer = Layer::new(
|
||||
(31, 35),
|
||||
attributes,
|
||||
Encoding { compression: Compression::ZIP16, blocks: Blocks::ScanLines, line_order: LineOrder::Decreasing },
|
||||
channels,
|
||||
);
|
||||
let mut bytes = Cursor::new(Vec::new());
|
||||
exr::image::Image::from_layer(layer).write().to_buffered(&mut bytes).unwrap();
|
||||
let mut decoder = Decoder::new(bytes, &|| false).unwrap();
|
||||
|
||||
@@ -92,8 +92,13 @@ fn icc_warning_suppressed_when_not_embedding() {
|
||||
#[test]
|
||||
fn exif_xmp_dpi_text_dropped_for_qoi() {
|
||||
let mut img = test_image(ChannelLayout::Rgb, SampleType::U8);
|
||||
img.meta =
|
||||
Metadata { exif: Some(sample_exif()), xmp: Some("x".into()), dpi: Some((72.0, 72.0)), text: vec![("a".into(), "b".into())], ..Default::default() };
|
||||
img.meta = Metadata {
|
||||
exif: Some(sample_exif()),
|
||||
xmp: Some("x".into()),
|
||||
dpi: Some((72.0, 72.0)),
|
||||
text: vec![("a".into(), "b".into())],
|
||||
..Default::default()
|
||||
};
|
||||
let w = warns(&img, Format::Qoi);
|
||||
for x in [W::ExifDropped, W::XmpDropped, W::DpiDropped, W::TextDropped] {
|
||||
assert!(w.contains(&x), "{x:?}");
|
||||
@@ -103,8 +108,13 @@ fn exif_xmp_dpi_text_dropped_for_qoi() {
|
||||
#[test]
|
||||
fn webp_drops_text_only() {
|
||||
let mut img = test_image(ChannelLayout::Rgb, SampleType::U8);
|
||||
img.meta =
|
||||
Metadata { exif: Some(sample_exif()), xmp: Some("x".into()), dpi: Some((72.0, 72.0)), text: vec![("a".into(), "b".into())], ..Default::default() };
|
||||
img.meta = Metadata {
|
||||
exif: Some(sample_exif()),
|
||||
xmp: Some("x".into()),
|
||||
dpi: Some((72.0, 72.0)),
|
||||
text: vec![("a".into(), "b".into())],
|
||||
..Default::default()
|
||||
};
|
||||
let w = warns(&img, Format::WebP);
|
||||
assert_eq!(w, vec![W::TextDropped]);
|
||||
}
|
||||
|
||||
@@ -393,7 +393,9 @@ fn pnm_header_alone_reserves_nothing_without_limits() {
|
||||
// 2⁶² bytes before finding the raster missing (an abort).
|
||||
let none = opts(Limits::none());
|
||||
let side = 1u32 << 31;
|
||||
for f in [format!("P1\n{side} {side}\n"), format!("P2\n{side} {side}\n255\n"), format!("P3\n{side} {side}\n255\n"), format!("P4\n{side} {side}\n")] {
|
||||
for f in
|
||||
[format!("P1\n{side} {side}\n"), format!("P2\n{side} {side}\n255\n"), format!("P3\n{side} {side}\n255\n"), format!("P4\n{side} {side}\n")]
|
||||
{
|
||||
assert!(decode_with(f.as_bytes(), &none).is_err(), "{f:?}");
|
||||
}
|
||||
}
|
||||
@@ -440,7 +442,8 @@ fn jpeg_bomb_header_rejected() {
|
||||
fn tiff_bomb_header_rejected() {
|
||||
// Minimal little-endian TIFF claiming 1_000_000 x 1_000_000 8-bit gray.
|
||||
let mut b = b"II*\0\x08\0\0\0".to_vec();
|
||||
let entries: [(u16, u16, u32, u32); 6] = [(256, 4, 1, 1_000_000), (257, 4, 1, 1_000_000), (258, 3, 1, 8), (262, 3, 1, 1), (273, 4, 1, 0), (279, 4, 1, 0)];
|
||||
let entries: [(u16, u16, u32, u32); 6] =
|
||||
[(256, 4, 1, 1_000_000), (257, 4, 1, 1_000_000), (258, 3, 1, 8), (262, 3, 1, 1), (273, 4, 1, 0), (279, 4, 1, 0)];
|
||||
b.extend_from_slice(&(entries.len() as u16).to_le_bytes());
|
||||
for (tag, ty, count, val) in entries {
|
||||
b.extend_from_slice(&tag.to_le_bytes());
|
||||
|
||||
@@ -177,7 +177,11 @@ fn jpeg_multi_segment_icc() {
|
||||
fn jpeg_with_oversized_metadata_still_encodes() {
|
||||
let ancestors: String = (0..3000).map(|i| format!("<rdf:li>xmp.did:{i:032x}</rdf:li>")).collect();
|
||||
let texts: String = (0..400)
|
||||
.map(|i| format!("<rdf:li rdf:parseType=\"Resource\"><ps:LayerName>Layer {i}</ps:LayerName><ps:LayerText>Words on layer {i}</ps:LayerText></rdf:li>"))
|
||||
.map(|i| {
|
||||
format!(
|
||||
"<rdf:li rdf:parseType=\"Resource\"><ps:LayerName>Layer {i}</ps:LayerName><ps:LayerText>Words on layer {i}</ps:LayerText></rdf:li>"
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let xmp = format!(
|
||||
"<?xpacket begin=\"\u{feff}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?><x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"\" xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\" xmlns:ps=\"http://example.com/ps/1.0/\" xmp:CreatorTool=\"synthetic\"><ps:DocumentAncestors>\n<rdf:Bag>{ancestors}</rdf:Bag></ps:DocumentAncestors><ps:TextLayers><rdf:Bag>{texts}</rdf:Bag></ps:TextLayers><ps:DocumentAncestorsNote/></rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end=\"w\"?>"
|
||||
@@ -218,7 +222,9 @@ fn embed_flags_disable_metadata() {
|
||||
assert!(back.icc.is_none(), "{f:?}");
|
||||
assert!(back.meta.exif.is_none() && back.meta.xmp.is_none(), "{f:?}");
|
||||
assert!(back.meta.text.is_empty(), "{f:?}");
|
||||
assert!(fidelity_warnings_with(&img, Format::Bmp, &opts).iter().all(|w| !matches!(w, FidelityWarning::IccDropped | FidelityWarning::ExifDropped)));
|
||||
assert!(
|
||||
fidelity_warnings_with(&img, Format::Bmp, &opts).iter().all(|w| !matches!(w, FidelityWarning::IccDropped | FidelityWarning::ExifDropped))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -322,7 +328,8 @@ fn webp_keeps_dpi_without_source_exif() {
|
||||
let back = decode(&encode(&img, Format::WebP, &EncodeOptions::default()).unwrap()).unwrap();
|
||||
assert!(back.meta.exif.is_some());
|
||||
// ...unless the XMP written beside it records the resolution, which readers look at first.
|
||||
img.meta.xmp = Some(r#"<x:xmpmeta><rdf:Description tiff:XResolution="300/1" tiff:YResolution="150/1" tiff:ResolutionUnit="2"/></x:xmpmeta>"#.into());
|
||||
img.meta.xmp =
|
||||
Some(r#"<x:xmpmeta><rdf:Description tiff:XResolution="300/1" tiff:YResolution="150/1" tiff:ResolutionUnit="2"/></x:xmpmeta>"#.into());
|
||||
assert!(!fidelity_warnings(&img, Format::WebP).contains(&FidelityWarning::DpiDropped));
|
||||
let back = decode(&encode(&img, Format::WebP, &EncodeOptions::default()).unwrap()).unwrap();
|
||||
let (x, y) = back.meta.dpi.expect("dpi from XMP");
|
||||
|
||||
@@ -364,7 +364,9 @@ fn jpeg_opens_upright_for_every_orientation() {
|
||||
|
||||
#[test]
|
||||
fn rgb_jpeg_with_dpi_swaps_resolution_on_a_quarter_turn() {
|
||||
let img = Image::from_u8(16, 8, ChannelLayout::Rgb, vec![128; 16 * 8 * 3]).unwrap().with_meta(Metadata { dpi: Some((300.0, 150.0)), ..Default::default() });
|
||||
let img = Image::from_u8(16, 8, ChannelLayout::Rgb, vec![128; 16 * 8 * 3])
|
||||
.unwrap()
|
||||
.with_meta(Metadata { dpi: Some((300.0, 150.0)), ..Default::default() });
|
||||
let jpeg = encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap();
|
||||
let back = decode(&jpeg_with_exif(&jpeg, &exif(6, false, false))).unwrap();
|
||||
assert_eq!(back.dimensions(), (8, 16));
|
||||
@@ -584,7 +586,11 @@ fn upright_exif_keeps_every_other_byte() {
|
||||
tail.extend_from_slice(&u32b(4));
|
||||
tail.extend_from_slice(b"0232");
|
||||
tail.extend_from_slice(&u32b(0));
|
||||
let e = ifd(big, &[(0x010F, 2, 12, u32b(make_at)), (0x0112, 3, 1, short(6, big)), (0x0131, 2, 4, *b"PC1\0"), (0x8769, 4, 1, u32b(sub_at))], &tail);
|
||||
let e = ifd(
|
||||
big,
|
||||
&[(0x010F, 2, 12, u32b(make_at)), (0x0112, 3, 1, short(6, big)), (0x0131, 2, 4, *b"PC1\0"), (0x8769, 4, 1, u32b(sub_at))],
|
||||
&tail,
|
||||
);
|
||||
let mut prefixed = b"Exif\0\0".to_vec();
|
||||
prefixed.extend_from_slice(&e);
|
||||
let fixed = upright_exif(&prefixed).into_owned();
|
||||
|
||||
@@ -112,7 +112,8 @@ fn rejects_truncated_and_overshooting_rle_without_panicking() {
|
||||
fn refuses_headers_that_exceed_allocation_budget() {
|
||||
let mut b = header(8, 3, 3000, 3000, 3000);
|
||||
// The default decoder rejects the allocation before reading any scanline.
|
||||
let opts = craft_image_codecs::DecodeOptions { limits: craft_image_codecs::Limits { max_alloc: 1024, ..Default::default() }, ..Default::default() };
|
||||
let opts =
|
||||
craft_image_codecs::DecodeOptions { limits: craft_image_codecs::Limits { max_alloc: 1024, ..Default::default() }, ..Default::default() };
|
||||
assert!(matches!(craft_image_codecs::decode_as_with(Format::Pcx, &b, &opts), Err(CodecError::LimitExceeded(_))));
|
||||
b[2] = 0;
|
||||
assert_eq!(detect(&b), None, "unsupported uncompressed encoding");
|
||||
|
||||
@@ -278,7 +278,8 @@ fn png_rows_take_one_call_per_row_and_report_progress() {
|
||||
|
||||
#[test]
|
||||
fn png_rows_share_their_bytes_without_copying_them() {
|
||||
let bytes = std::sync::Arc::new(encode(&synth(20, 20, ChannelLayout::Rgba, SampleType::U8, 3, 0.2), Format::Png, &EncodeOptions::default()).unwrap());
|
||||
let bytes =
|
||||
std::sync::Arc::new(encode(&synth(20, 20, ChannelLayout::Rgba, SampleType::U8, 3, 0.2), Format::Png, &EncodeOptions::default()).unwrap());
|
||||
let mut rows = PngDecodeRows::new(SharedBytes(bytes.clone()), &Limits::default()).unwrap();
|
||||
let img = rows.step(&mut || true).unwrap().unwrap();
|
||||
assert_eq!(img, decode(&bytes).unwrap());
|
||||
|
||||
@@ -280,7 +280,9 @@ fn truncated_metadata_never_panics_and_falls_back() {
|
||||
assert_eq!(photoshop_resolution(&r[..n]), None, "{n}");
|
||||
near(dpi_of(&jpeg_with(&[jfif(1, 72, 72), app13(&r[..n])])), 72.0);
|
||||
}
|
||||
for x in ["tiff:XResolution=", "tiff:XResolution=\"", "tiff:XResolution=\"\" tiff:YResolution=\"5/0\"", "<tiff:XResolution>", "</tiff:XResolution>9<"] {
|
||||
for x in
|
||||
["tiff:XResolution=", "tiff:XResolution=\"", "tiff:XResolution=\"\" tiff:YResolution=\"5/0\"", "<tiff:XResolution>", "</tiff:XResolution>9<"]
|
||||
{
|
||||
assert_eq!(xmp_resolution(x), None, "{x}");
|
||||
let _ = xmp_with_resolution(x, (1.0, 1.0));
|
||||
}
|
||||
@@ -375,7 +377,10 @@ fn xmp_resolution_is_rewritten() {
|
||||
r#"<rdf:Description tiff:XResolution="240/1" tiff:YResolution='240/1' tiff:ResolutionUnit="2" tiff:Make="X"/>"#
|
||||
);
|
||||
let elem = "<tiff:XResolution>300/1</tiff:XResolution><tiff:YResolution>300/1</tiff:YResolution>";
|
||||
assert_eq!(xmp_with_resolution(elem, (72.5, 72.5)), "<tiff:XResolution>72500/1000</tiff:XResolution><tiff:YResolution>72500/1000</tiff:YResolution>");
|
||||
assert_eq!(
|
||||
xmp_with_resolution(elem, (72.5, 72.5)),
|
||||
"<tiff:XResolution>72500/1000</tiff:XResolution><tiff:YResolution>72500/1000</tiff:YResolution>"
|
||||
);
|
||||
for same in [r#"tiff:XResolution="240" tiff:YResolution="240/1""#, "<x/>"] {
|
||||
assert!(matches!(xmp_with_resolution(same, (240.0, 240.0)), Cow::Borrowed(_)), "{same}");
|
||||
}
|
||||
|
||||
@@ -268,7 +268,8 @@ fn jpeg_format_options_round_trip() {
|
||||
let sof = |b: &[u8], m: u8| b.windows(2).any(|w| w == [0xFF, m]);
|
||||
for subsampled in [false, true] {
|
||||
let enc = |f| {
|
||||
encode(&img, Format::Jpeg, &EncodeOptions { jpeg_format: f, jpeg_chroma_subsampling: subsampled, jpeg_quality: 90, ..Default::default() }).unwrap()
|
||||
encode(&img, Format::Jpeg, &EncodeOptions { jpeg_format: f, jpeg_chroma_subsampling: subsampled, jpeg_quality: 90, ..Default::default() })
|
||||
.unwrap()
|
||||
};
|
||||
let (base, opt, prog) = (enc(JpegFormat::Baseline), enc(JpegFormat::Optimized), enc(JpegFormat::Progressive));
|
||||
// The scan layout only changes how the same quantized coefficients are stored, so every
|
||||
@@ -309,7 +310,8 @@ fn webp_lossy_request_is_a_lossy_file() {
|
||||
let back = decode(&bytes).unwrap();
|
||||
assert_eq!(back.dimensions(), img.dimensions());
|
||||
assert!(
|
||||
fidelity_warnings_with(&img, Format::WebP, &EncodeOptions { webp_lossless: false, ..Default::default() }).contains(&FidelityWarning::LossyCompression)
|
||||
fidelity_warnings_with(&img, Format::WebP, &EncodeOptions { webp_lossless: false, ..Default::default() })
|
||||
.contains(&FidelityWarning::LossyCompression)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -26,8 +26,8 @@ fn jpeg_quality_of_hand_built_tables() {
|
||||
// A minimal JPEG prefix: SOI, one DQT holding the Annex K luminance table (quality 50) in
|
||||
// zig-zag order, then SOS.
|
||||
let luma: [u8; 64] = [
|
||||
16, 11, 12, 14, 12, 10, 16, 14, 13, 14, 18, 17, 16, 19, 24, 40, 26, 24, 22, 22, 24, 49, 35, 37, 29, 40, 58, 51, 61, 60, 57, 51, 56, 55, 64, 72, 92, 78,
|
||||
64, 68, 87, 69, 55, 56, 80, 109, 81, 87, 95, 98, 103, 104, 103, 62, 77, 113, 121, 112, 100, 120, 92, 101, 103, 99,
|
||||
16, 11, 12, 14, 12, 10, 16, 14, 13, 14, 18, 17, 16, 19, 24, 40, 26, 24, 22, 22, 24, 49, 35, 37, 29, 40, 58, 51, 61, 60, 57, 51, 56, 55, 64,
|
||||
72, 92, 78, 64, 68, 87, 69, 55, 56, 80, 109, 81, 87, 95, 98, 103, 104, 103, 62, 77, 113, 121, 112, 100, 120, 92, 101, 103, 99,
|
||||
];
|
||||
let mut b = vec![0xFF, 0xD8, 0xFF, 0xDB, 0x00, 67, 0x00];
|
||||
b.extend_from_slice(&luma);
|
||||
|
||||
@@ -103,7 +103,11 @@ fn every_layout_matches_the_whole_image_decoder() {
|
||||
),
|
||||
(
|
||||
"palette 4-bit",
|
||||
strips(W, H, 4, 1, 3, rows, &noise((W as usize).div_ceil(2) * H as usize, 8)).tag(320, SHORT, &(0..48u64).map(|i| i * 1365).collect::<Vec<_>>()),
|
||||
strips(W, H, 4, 1, 3, rows, &noise((W as usize).div_ceil(2) * H as usize, 8)).tag(
|
||||
320,
|
||||
SHORT,
|
||||
&(0..48u64).map(|i| i * 1365).collect::<Vec<_>>(),
|
||||
),
|
||||
row(3, 1) * rows as usize,
|
||||
),
|
||||
("gray 1-bit", strips(W, H, 1, 1, 1, rows, &noise((W as usize).div_ceil(8) * H as usize, 9)), row(1, 1) * rows as usize),
|
||||
@@ -122,11 +126,9 @@ fn tiles_and_planar_data_match() {
|
||||
let (w, h) = (W as usize, H as usize);
|
||||
let px = noise(w * h * 3 * 2, 11);
|
||||
let tiled = |planar: bool| {
|
||||
let mut d = Dir { entries: base(W, H, 16, 3, 2), chunks: tile_split(&px, w, h, 3, 2, 16, 16, planar), tiled: true }.tag(322, SHORT, &[16]).tag(
|
||||
323,
|
||||
SHORT,
|
||||
&[16],
|
||||
);
|
||||
let mut d = Dir { entries: base(W, H, 16, 3, 2), chunks: tile_split(&px, w, h, 3, 2, 16, 16, planar), tiled: true }
|
||||
.tag(322, SHORT, &[16])
|
||||
.tag(323, SHORT, &[16]);
|
||||
if planar {
|
||||
d = d.tag(284, SHORT, &[2]);
|
||||
}
|
||||
@@ -135,7 +137,8 @@ fn tiles_and_planar_data_match() {
|
||||
let band = w * 3 * 2 * 16;
|
||||
assert_same(&build(true, false, &[tiled(false)], &[0]).bytes, band, "chunky tiles");
|
||||
assert_same(&build(true, true, &[tiled(true)], &[0]).bytes, band, "planar tiles, BigTIFF");
|
||||
let planar = Dir { entries: base(W, H, 16, 3, 2), chunks: planar_strips(&px, w, h, 3, 2, 5), tiled: false }.tag(278, LONG, &[5]).tag(284, SHORT, &[2]);
|
||||
let planar =
|
||||
Dir { entries: base(W, H, 16, 3, 2), chunks: planar_strips(&px, w, h, 3, 2, 5), tiled: false }.tag(278, LONG, &[5]).tag(284, SHORT, &[2]);
|
||||
assert_same(&build(true, false, &[planar], &[0]).bytes, w * 3 * 2 * 5, "planar strips");
|
||||
}
|
||||
|
||||
|
||||
@@ -78,9 +78,11 @@ fn time(name: &str, bytes: &[u8]) {
|
||||
fn decode_30mp() {
|
||||
let rgb = pixels(3);
|
||||
let img = Image::from_u8(W, H, ChannelLayout::Rgb, rgb.clone()).unwrap();
|
||||
for (name, c) in
|
||||
[("strips, none", TiffCompression::None), ("strips, LZW + predictor", TiffCompression::Lzw), ("strips, Deflate + predictor", TiffCompression::Deflate)]
|
||||
{
|
||||
for (name, c) in [
|
||||
("strips, none", TiffCompression::None),
|
||||
("strips, LZW + predictor", TiffCompression::Lzw),
|
||||
("strips, Deflate + predictor", TiffCompression::Deflate),
|
||||
] {
|
||||
let bytes = encode(&img, Format::Tiff, &EncodeOptions { tiff_compression: c, ..Default::default() }).unwrap();
|
||||
time(&format!("RGB 8 {name}"), &bytes);
|
||||
}
|
||||
|
||||
@@ -185,9 +185,18 @@ fn overlapping_tiff(entries: usize, count: u32) -> Vec<u8> {
|
||||
out.extend(42u16.to_le_bytes());
|
||||
out.extend(8u32.to_le_bytes());
|
||||
out.extend(10u16.to_le_bytes());
|
||||
for (tag, ty, value) in
|
||||
[(256, 3, 1), (257, 3, 1), (258, 3, 8), (259, 3, 1), (262, 3, 1), (273, 4, 0), (277, 3, 1), (278, 3, 1), (279, 4, 1), (34665, 4, at_exif as u32)]
|
||||
{
|
||||
for (tag, ty, value) in [
|
||||
(256, 3, 1),
|
||||
(257, 3, 1),
|
||||
(258, 3, 8),
|
||||
(259, 3, 1),
|
||||
(262, 3, 1),
|
||||
(273, 4, 0),
|
||||
(277, 3, 1),
|
||||
(278, 3, 1),
|
||||
(279, 4, 1),
|
||||
(34665, 4, at_exif as u32),
|
||||
] {
|
||||
out.extend(entry(tag, ty, 1, value));
|
||||
}
|
||||
out.extend(0u32.to_le_bytes());
|
||||
|
||||
@@ -338,7 +338,8 @@ fn alpha_after_an_unspecified_extra_sample_is_kept() {
|
||||
// The colour samples, then the second extra sample (the alpha).
|
||||
let want: Vec<u8> = want_all.chunks(spp * bps).flat_map(|p| [&p[..color * bps], &p[(color + 1) * bps..]].concat()).collect();
|
||||
for planar in [false, true] {
|
||||
let chunks = if planar { planar_strips(&file, w, h, spp, bps, 2) } else { file.chunks(w * spp * bps * 2).map(<[u8]>::to_vec).collect() };
|
||||
let chunks =
|
||||
if planar { planar_strips(&file, w, h, spp, bps, 2) } else { file.chunks(w * spp * bps * 2).map(<[u8]>::to_vec).collect() };
|
||||
let mut d = Dir { entries: base(w as u32, h as u32, bits, spp as u16, photometric), chunks, tiled: false }
|
||||
.tag(278, LONG, &[2])
|
||||
.tag(339, SHORT, &vec![u64::from(format); spp])
|
||||
@@ -509,7 +510,14 @@ fn every_ifd_and_subifd_is_listed_and_decodable() {
|
||||
use TiffPageKind::*;
|
||||
assert_eq!(
|
||||
summary,
|
||||
[(4, None, ReducedResolution), (9, None, Page), (3, Some(1), ReducedResolution), (2, Some(1), ReducedResolution), (9, None, Mask), (5, None, Page)]
|
||||
[
|
||||
(4, None, ReducedResolution),
|
||||
(9, None, Page),
|
||||
(3, Some(1), ReducedResolution),
|
||||
(2, Some(1), ReducedResolution),
|
||||
(9, None, Mask),
|
||||
(5, None, Page)
|
||||
]
|
||||
);
|
||||
assert_eq!(info.pages[1].ifd_offset, b.ifd_at[1]);
|
||||
assert_eq!((info.default_page(), info.page_count()), (Some(1), 2));
|
||||
|
||||
@@ -8,7 +8,8 @@ use craft_image_codecs::*;
|
||||
|
||||
fn with_tags(layout: ChannelLayout, sample: SampleType) -> Image {
|
||||
let mut img = synth(9, 7, layout, sample, 5, 0.3);
|
||||
img.meta.photoshop_resources = Some(b"8BIM\x03\xed\x00\x00\x00\x00\x00\x10\x00\x48\x00\x00\x00\x01\x00\x01\x00\x48\x00\x00\x00\x01\x00\x01".to_vec());
|
||||
img.meta.photoshop_resources =
|
||||
Some(b"8BIM\x03\xed\x00\x00\x00\x00\x00\x10\x00\x48\x00\x00\x00\x01\x00\x01\x00\x48\x00\x00\x00\x01\x00\x01".to_vec());
|
||||
let mut layers = b"Adobe Photoshop Document Data Block\0".to_vec();
|
||||
layers.extend_from_slice(b"MIB8ryaL");
|
||||
layers.extend_from_slice(&4u32.to_le_bytes());
|
||||
|
||||
@@ -51,8 +51,15 @@ fn off_by_default_and_none_for_small_images() {
|
||||
|
||||
#[test]
|
||||
fn every_depth_layout_and_compression() {
|
||||
let layouts =
|
||||
[ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb, ChannelLayout::Rgba, ChannelLayout::Cmyk, ChannelLayout::CmykA, ChannelLayout::Lab];
|
||||
let layouts = [
|
||||
ChannelLayout::Gray,
|
||||
ChannelLayout::GrayA,
|
||||
ChannelLayout::Rgb,
|
||||
ChannelLayout::Rgba,
|
||||
ChannelLayout::Cmyk,
|
||||
ChannelLayout::CmykA,
|
||||
ChannelLayout::Lab,
|
||||
];
|
||||
for layout in layouts {
|
||||
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
for compression in [TiffCompression::None, TiffCompression::Lzw, TiffCompression::Deflate, TiffCompression::PackBits] {
|
||||
@@ -100,7 +107,10 @@ fn first_level_pixel(layout: ChannelLayout, tile: [&[u8]; 4]) -> Vec<u8> {
|
||||
fn colour_is_weighted_by_alpha() {
|
||||
// One opaque pixel and three transparent ones of another colour: the level keeps the opaque
|
||||
// colour at a quarter alpha. Unweighted, the transparent colour would bleed in (pink, not red).
|
||||
assert_eq!(first_level_pixel(ChannelLayout::Rgba, [&[255, 0, 0, 255], &[255, 255, 255, 0], &[255, 255, 255, 0], &[255, 255, 255, 0]]), [255, 0, 0, 64]);
|
||||
assert_eq!(
|
||||
first_level_pixel(ChannelLayout::Rgba, [&[255, 0, 0, 255], &[255, 255, 255, 0], &[255, 255, 255, 0], &[255, 255, 255, 0]]),
|
||||
[255, 0, 0, 64]
|
||||
);
|
||||
// Gray and CMYK reach the same path with other channel counts.
|
||||
assert_eq!(first_level_pixel(ChannelLayout::GrayA, [&[40, 255], &[255, 0], &[255, 0], &[255, 0]]), [40, 64]);
|
||||
assert_eq!(first_level_pixel(ChannelLayout::CmykA, [&[200, 10, 30, 90, 255], &[0; 5], &[0; 5], &[0; 5]]), [200, 10, 30, 90, 64]);
|
||||
|
||||
@@ -141,11 +141,10 @@ fn sixteen_bit_ycbcr_bands_match_whole_decode_with_a_missing_last_strip() {
|
||||
let icc = sample_icc(512);
|
||||
for little in [true, false] {
|
||||
for missing in [false, true] {
|
||||
let dir = strips(w, h, 16, 3, 6, rows, &u16s(&samples, little)).tag(SUBSAMPLING, SHORT, &[1, 1]).tag(YCBCR_COEFFICIENTS, RATIONAL, &weights).bytes(
|
||||
ICC_PROFILE,
|
||||
UNDEFINED,
|
||||
&icc,
|
||||
);
|
||||
let dir = strips(w, h, 16, 3, 6, rows, &u16s(&samples, little))
|
||||
.tag(SUBSAMPLING, SHORT, &[1, 1])
|
||||
.tag(YCBCR_COEFFICIENTS, RATIONAL, &weights)
|
||||
.bytes(ICC_PROFILE, UNDEFINED, &icc);
|
||||
let mut file = build(little, false, &[dir], &[0]);
|
||||
if missing {
|
||||
let past = file.bytes.len() as u64 + 4096;
|
||||
@@ -222,7 +221,8 @@ fn tiled_jpeg_ycbcr_keeps_its_icc_profile() {
|
||||
assert_eq!((img.width(), img.height(), img.layout()), (w, h, ChannelLayout::Rgb));
|
||||
assert_eq!(img.icc.as_deref(), Some(icc.as_slice()), "the embedded profile is kept");
|
||||
// The oracle: each tile's stream decoded by an independent decoder, placed side by side.
|
||||
let tiles: Vec<Vec<u8>> = streams.iter().map(|s| image::load_from_memory_with_format(s, image::ImageFormat::Jpeg).unwrap().to_rgb8().into_raw()).collect();
|
||||
let tiles: Vec<Vec<u8>> =
|
||||
streams.iter().map(|s| image::load_from_memory_with_format(s, image::ImageFormat::Jpeg).unwrap().to_rgb8().into_raw()).collect();
|
||||
let row = (t * 3) as usize;
|
||||
let want: Vec<u8> = (0..t as usize).flat_map(|y| [&tiles[0][y * row..(y + 1) * row], &tiles[1][y * row..(y + 1) * row]].concat()).collect();
|
||||
let worst = rgb(&img).iter().zip(&want).map(|(g, o)| g.abs_diff(*o)).max().unwrap();
|
||||
@@ -248,11 +248,10 @@ fn planar_ycbcr_reads_as_rgb_in_both_byte_orders() {
|
||||
// The pixels of the default-conversion test, one plane per component.
|
||||
let px = [0u8, 128, 128, 255, 128, 128, 128, 128, 128, 76, 85, 255];
|
||||
for little in [true, false] {
|
||||
let dir = Dir { entries: base(4, 1, 8, 3, 6), chunks: planar_strips(&px, 4, 1, 3, 1, 1), tiled: false }.tag(278, LONG, &[1]).tag(284, SHORT, &[2]).tag(
|
||||
SUBSAMPLING,
|
||||
SHORT,
|
||||
&[1, 1],
|
||||
);
|
||||
let dir = Dir { entries: base(4, 1, 8, 3, 6), chunks: planar_strips(&px, 4, 1, 3, 1, 1), tiled: false }
|
||||
.tag(278, LONG, &[1])
|
||||
.tag(284, SHORT, &[2])
|
||||
.tag(SUBSAMPLING, SHORT, &[1, 1]);
|
||||
let img = decode(&build(little, false, &[dir], &[0]).bytes).unwrap();
|
||||
assert_eq!(rgb(&img), [0, 0, 0, 255, 255, 255, 128, 128, 128, 254, 0, 0], "little endian: {little}");
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! `decode_webp_frames`: every frame of an animated WebP, composited, with its duration (#1198).
|
||||
|
||||
use craft_image_codecs::{
|
||||
AnimationFrame, ChannelLayout, CodecError, DecodeOptions, DecodeWarning, EncodeOptions, Format, Image, Limits, decode, decode_webp_frames, encode,
|
||||
webp_is_animated,
|
||||
AnimationFrame, ChannelLayout, CodecError, DecodeOptions, DecodeWarning, EncodeOptions, Format, Image, Limits, decode, decode_webp_frames,
|
||||
encode, webp_is_animated,
|
||||
};
|
||||
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
|
||||
@@ -23,7 +23,8 @@ fn jpeg_xl_is_export_only_and_detects_both_signatures() {
|
||||
#[test]
|
||||
fn jpeg_xl_encoding_is_deterministic_and_converts_float_to_integer() {
|
||||
let input =
|
||||
Image::from_u8(3, 2, ChannelLayout::Rgba, vec![0, 255, 17, 127, 20, 40, 80, 255, 255, 0, 2, 0, 10, 20, 30, 64, 0, 0, 0, 1, 90, 80, 70, 128]).unwrap();
|
||||
Image::from_u8(3, 2, ChannelLayout::Rgba, vec![0, 255, 17, 127, 20, 40, 80, 255, 255, 0, 2, 0, 10, 20, 30, 64, 0, 0, 0, 1, 90, 80, 70, 128])
|
||||
.unwrap();
|
||||
let opts = EncodeOptions::default();
|
||||
let one = encode(&input, Format::Jxl, &opts).unwrap();
|
||||
let two = encode(&input, Format::Jxl, &opts).unwrap();
|
||||
|
||||
Reference in new issue
Block a user