Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/raw/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,5 @@ proptest = { workspace = true }
zune-jpegxl = { workspace = true }
# Pinned CC0 corpus identities; not a product dependency.
sha2 = { version = "0.10", default-features = false, features = ["std"] }
# Peak-heap regression tests (tests/sr2_heap.rs); not a product dependency.
# Peak-heap regression tests (tests/sr2_heap.rs, tests/erf_preview_heap.rs); not a product dependency.
dhat = { workspace = true }
120 changes: 109 additions & 11 deletions crates/raw/src/tiffraw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,12 @@ fn decode_chunk(data: &[u8], info: &ImageInfo, c: &Chunk, order: ByteOrder, pack
Ok(ChunkPx::U16(v))
}
comp::LOSSY_JPEG => {
// lossy DNG: each chunk is a baseline (DCT) JPEG of 8-bit samples
let (px, jw, jh, jc) = lossy_jpeg(src, cpp)?;
// lossy DNG: each chunk is a baseline (DCT) JPEG of 8-bit samples, its frame no larger than the nominal
// chunk rounded up to whole 16-pixel MCUs (a last strip may be coded at the full RowsPerStrip); these
// edge caps also bound its pixel count
let nominal_h = ch.max(info.chunk_size().1.min(info.height) as usize);
let max = (cw.div_ceil(16).saturating_mul(16), nominal_h.div_ceil(16).saturating_mul(16));
let (px, jw, jh, jc) = lossy_jpeg(src, cpp, max, usize::MAX)?;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let mut v = vec![0u16; n];
for y in 0..ch.min(jh) {
for x in 0..cw.min(jw) {
Expand Down Expand Up @@ -228,17 +232,26 @@ fn jxl_chunk_check(src: &[u8], cw: usize, ch: usize, vw: usize, vh: usize, cpp:
jxl_chunk(src, cw, ch, vw, vh, cpp, bits, float).map(|_| ())
}

/// Decode one baseline JPEG chunk to 8-bit samples: (samples, width, height, channels).
pub(crate) fn lossy_jpeg(src: &[u8], cpp: usize) -> Result<(Vec<u8>, usize, usize, usize)> {
/// Decode one baseline JPEG chunk to 8-bit samples: (samples, width, height, channels). A frame wider or taller than
/// `max` (width, height) or of more than `max_px` pixels is refused from its header, before the output it declares
/// is allocated (issue #2560).
pub(crate) fn lossy_jpeg(src: &[u8], cpp: usize, max: (usize, usize), max_px: usize) -> Result<(Vec<u8>, usize, usize, usize)> {
use zune_core::bytestream::ZCursor;
use zune_core::colorspace::ColorSpace;
use zune_core::options::DecoderOptions;
let corrupt = |e: zune_jpeg::errors::DecodeErrors| RawError::Corrupt(format!("lossy JPEG tile: {e}"));
let cs = if cpp == 1 { ColorSpace::Luma } else { ColorSpace::RGB };
// zune's own limits stay open so that an oversized frame is a `Limit` from the check below, not a format error
let opts = DecoderOptions::default().set_max_width(1 << 16).set_max_height(1 << 16).set_strict_mode(false).jpeg_set_out_colorspace(cs);
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(src), opts);
let px = d.decode().map_err(|e| RawError::Corrupt(format!("lossy JPEG tile: {e}")))?;
d.decode_headers().map_err(corrupt)?;
let info = d.info().ok_or_else(|| RawError::Corrupt("lossy JPEG tile without a header".into()))?;
let (w, h) = (info.width as usize, info.height as usize);
// `output_buffer_size` is `None` when w·h·channels overflows `usize` (wasm32), which `decode` would unwrap
if w > max.0 || h > max.1 || w.checked_mul(h).is_none_or(|p| p > max_px) || d.output_buffer_size().is_none() {
return Err(RawError::Limit("lossy JPEG frame larger than expected"));
}
let px = d.decode().map_err(corrupt)?;
let c = if cpp == 1 { 1 } else { 3 };
if w == 0 || h == 0 || px.len() < w * h * c {
return Err(RawError::Corrupt("lossy JPEG tile: short output".into()));
Expand Down Expand Up @@ -342,17 +355,28 @@ mod lossy_tests {
use super::*;
use lightcraft_tiff::image::Layout;

/// A `w`×`h` baseline JPEG: red `shade`, a green ramp across, blue 200.
fn rgb_jpeg(w: usize, h: usize, shade: u8) -> Vec<u8> {
let px: Vec<u8> = (0..w * h).flat_map(|i| [shade, (i % w * 15) as u8, 200]).collect();
let mut out = Vec::new();
jpeg_encoder::Encoder::new(&mut out, 100).encode(&px, w as u16, h as u16, jpeg_encoder::ColorType::Rgb).unwrap();
out
}

/// `jpeg` with its SOF0 header declaring a `w`×`h` frame; the coded data stays as it was.
fn with_frame_size(mut jpeg: Vec<u8>, w: u16, h: u16) -> Vec<u8> {
let sof = jpeg.windows(2).position(|m| m == [0xFF, 0xC0]).unwrap();
jpeg[sof + 5..sof + 7].copy_from_slice(&h.to_be_bytes());
jpeg[sof + 7..sof + 9].copy_from_slice(&w.to_be_bytes());
jpeg
}

/// A lossy-DNG-style image: two 16×8 tiles, each a baseline JPEG, the right one cut short
/// by the image edge.
#[test]
fn lossy_jpeg_tiles_decode() {
let (tw, th) = (16usize, 8usize);
let tile = |shade: u8| {
let px: Vec<u8> = (0..tw * th).flat_map(|i| [shade, (i % tw * 15) as u8, 200]).collect();
let mut out = Vec::new();
jpeg_encoder::Encoder::new(&mut out, 100).encode(&px, tw as u16, th as u16, jpeg_encoder::ColorType::Rgb).unwrap();
out
};
let tile = |shade: u8| rgb_jpeg(tw, th, shade);
let (a, b) = (tile(40), tile(220));
let mut file = vec![0u8; 8];
let oa = file.len() as u64;
Expand Down Expand Up @@ -382,6 +406,80 @@ mod lossy_tests {
assert!((px(10, 5)[1] as i32 - 150).abs() <= 6, "green ramp: {:?}", px(10, 5));
}

/// A 16×8 lossy tile whose JPEG header declares a 4096×4096 frame is refused from that header, before the frame
/// is allocated and decoded (issue #2560); the same tile with its own header decodes.
#[test]
fn lossy_tile_declaring_more_than_its_tile_is_refused_from_its_header() {
let info = |len: usize| ImageInfo {
width: 16,
height: 8,
bits_per_sample: vec![8, 8, 8],
samples_per_pixel: 3,
compression: comp::LOSSY_JPEG,
photometric: 34892,
planar: 1,
predictor: 1,
sample_format: 1,
new_subfile_type: 0,
layout: Layout::Tiles { tile_width: 16, tile_height: 8 },
offsets: vec![0],
byte_counts: vec![len as u64],
};
let tile = rgb_jpeg(16, 8, 40);
assert!(read_image(&tile, &info(tile.len()), ByteOrder::Little, Packing::Msb).is_ok());
let huge = with_frame_size(tile, 4096, 4096);
let r = read_image(&huge, &info(huge.len()), ByteOrder::Little, Packing::Msb);
assert!(matches!(r, Err(RawError::Limit(_))), "{:?}", r.map(|_| ()));
}

/// A 16×40 lossy image in strips of 32 rows whose last strip is coded at the full 32 rows, past the image's
/// bottom edge, still decodes; a last strip whose header declares more rows than RowsPerStrip is refused.
#[test]
fn lossy_last_strip_coded_at_its_full_rows_per_strip_decodes() {
let info = |a: usize, b: usize| ImageInfo {
width: 16,
height: 40,
bits_per_sample: vec![8, 8, 8],
samples_per_pixel: 3,
compression: comp::LOSSY_JPEG,
photometric: 34892,
planar: 1,
predictor: 1,
sample_format: 1,
new_subfile_type: 0,
layout: Layout::Strips { rows_per_strip: 32 },
offsets: vec![0, a as u64],
byte_counts: vec![a as u64, b as u64],
};
let (a, b) = (rgb_jpeg(16, 32, 40), rgb_jpeg(16, 32, 220));
let file = [a.as_slice(), b.as_slice()].concat();
let RawData::U16(v) = read_image(&file, &info(a.len(), b.len()), ByteOrder::Little, Packing::Msb).unwrap() else { panic!("integer samples") };
assert_eq!(v.len(), 16 * 40 * 3);
let red = |x: usize, y: usize| v[(y * 16 + x) * 3] as i32;
assert!((red(3, 20) - 40).abs() <= 3 && (red(3, 36) - 220).abs() <= 3, "{} {}", red(3, 20), red(3, 36));
let tall = with_frame_size(b, 16, 4096);
let file = [a.as_slice(), tall.as_slice()].concat();
let r = read_image(&file, &info(a.len(), tall.len()), ByteOrder::Little, Packing::Msb);
assert!(matches!(r, Err(RawError::Limit(_))), "{:?}", r.map(|_| ()));
}

/// A frame past either edge cap or the pixel cap is refused before it is decoded, up to the 65535×65535 a JPEG
/// header can declare (about 12.9 GB of RGB output), under a tile's caps and under the embedded preview's.
#[test]
fn lossy_jpeg_frame_past_its_caps_is_refused() {
let limit = |r: Result<(Vec<u8>, usize, usize, usize)>| matches!(r, Err(RawError::Limit(_)));
let preview = (u16::MAX as usize, u16::MAX as usize);
let jpeg = rgb_jpeg(16, 8, 40);
let (px, w, h, c) = lossy_jpeg(&jpeg, 3, (16, 16), 256).unwrap();
assert_eq!((px.len(), w, h, c), (16 * 8 * 3, 16, 8, 3));
assert!(limit(lossy_jpeg(&jpeg, 3, (8, 16), 256)), "wider than the tile");
assert!(limit(lossy_jpeg(&jpeg, 3, (16, 4), 256)), "taller than the tile");
assert!(limit(lossy_jpeg(&jpeg, 3, (16, 16), 64)), "more pixels than allowed");
let huge = with_frame_size(jpeg, u16::MAX, u16::MAX);
assert!(limit(lossy_jpeg(&huge, 3, (16, 16), 256)));
assert!(limit(lossy_jpeg(&huge, 3, preview, crate::wb_estimate::MAX_PREVIEW_PIXELS)));
}

fn strip_info(compression: u16, offsets: Vec<u64>, byte_counts: Vec<u64>) -> ImageInfo {
ImageInfo {
width: 4,
Expand Down
5 changes: 3 additions & 2 deletions crates/raw/src/wb_estimate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const NEUTRAL_SPREAD: u8 = 12;
/// At least this many neutral preview pixels are needed.
const MIN_NEUTRAL: usize = 64;
/// Previews larger than this (pixels) are not decoded for the estimate.
const MAX_PREVIEW_PIXELS: usize = 1 << 24;
pub(crate) const MAX_PREVIEW_PIXELS: usize = 1 << 24;

/// The raw frame the estimate looks at.
pub(crate) struct Frame<'a> {
Expand Down Expand Up @@ -66,7 +66,8 @@ fn median(v: &mut [f64]) -> Option<f64> {

fn from_preview(bytes: &[u8], f: &Frame) -> Option<[f32; 3]> {
let jpeg = crate::preview::embedded_preview(bytes)?;
let (px, pw, ph, ch) = crate::tiffraw::lossy_jpeg(&jpeg, 3).ok()?;
// a preview over the cap is refused from its JPEG header, before it is decoded (issue #2560)
let (px, pw, ph, ch) = crate::tiffraw::lossy_jpeg(&jpeg, 3, (u16::MAX as usize, u16::MAX as usize), MAX_PREVIEW_PIXELS).ok()?;
if ch != 3 {
return None;
}
Expand Down
70 changes: 70 additions & 0 deletions crates/raw/tests/erf_preview_heap.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
//! Peak heap of measuring an Epson ERF's white balance from its embedded preview (`crates/raw/src/wb_estimate.rs`),
//! measured with dhat's testing mode. The header probe of every ERF decodes that preview, so a JPEG whose frame
//! header claims far more pixels than the measurement reads must be refused from that header, before the frame it
//! declares is allocated (issue #2560). One test per binary (dhat's profiler is global).

use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags as t};

#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;

/// A 16 × 8 baseline JPEG whose SOF0 header declares a `w` × `h` frame; the coded data stays that of 16 × 8.
fn jpeg_claiming(w: u16, h: u16) -> Vec<u8> {
let px: Vec<u8> = (0..16 * 8).flat_map(|i| [120u8, (i % 16 * 15) as u8, 200]).collect();
let mut jpeg = Vec::new();
jpeg_encoder::Encoder::new(&mut jpeg, 90).encode(&px, 16, 8, jpeg_encoder::ColorType::Rgb).unwrap();
let sof = jpeg.windows(2).position(|m| m == [0xFF, 0xC0]).unwrap();
jpeg[sof + 5..sof + 7].copy_from_slice(&h.to_be_bytes());
jpeg[sof + 7..sof + 9].copy_from_slice(&w.to_be_bytes());
jpeg
}

/// A 20 × 6 Epson ERF (a `BLOCKS16` CFA sub-IFD, as `vendor::erf` reads it) followed by `preview`, stored the way
/// Epson stores it: its first byte as `ee`, found by the structural scan in `preview::scan_for_jpeg`.
fn erf_with_preview(preview: &[u8]) -> Vec<u8> {
let (w, h) = (20u32, 6u32);
let px: Vec<u16> = (0..w * h).map(|i| (i * 37 % 4096) as u16).collect();
// ten 12-bit samples MSB first in 15 bytes, then a pad byte
let mut blocks = Vec::new();
for g in px.chunks(10) {
for p in g.chunks(2) {
let (a, b) = (p[0], p[1]);
blocks.extend_from_slice(&[(a >> 4) as u8, ((a & 15) << 4) as u8 | (b >> 8) as u8, b as u8]);
}
blocks.push(0);
}
let mut raw = IfdBuilder::new();
raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0]));
raw.set(t::IMAGE_WIDTH, Value::Long(vec![w]));
raw.set(t::IMAGE_LENGTH, Value::Long(vec![h]));
raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![12]));
raw.set(t::COMPRESSION, Value::Short(vec![32769]));
raw.set(t::PHOTOMETRIC, Value::Short(vec![t::photometric::CFA]));
raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2]));
raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2]));
raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![blocks] });
let mut ifd0 = IfdBuilder::new();
ifd0.set(t::MAKE, Value::Ascii("SEIKO EPSON CORP.".into()));
ifd0.set(t::MODEL, Value::Ascii("R-D1".into()));
ifd0.add_sub_ifd(raw);
let mut file = TiffWriter::new(ByteOrder::Big, false).write(&[ifd0]).unwrap();
let at = file.len();
file.extend_from_slice(preview);
file[at] = 0xee;
file
}

#[test]
fn erf_preview_claiming_a_huge_frame_costs_no_memory_sized_by_it() {
// 8192 × 8192: 192 MiB of RGB if it were decoded, four times the pixels the measurement reads
let preview = jpeg_claiming(8192, 8192);
let file = erf_with_preview(&preview);
assert_eq!(lightcraft_raw::embedded_preview(&file), Some(preview), "the scan finds the preview");
let _profiler = dhat::Profiler::builder().testing().build();
let info = lightcraft_raw::probe_info(&file).unwrap();
let peak = dhat::HeapStats::get().max_bytes;
// the preview is not used; the white balance still comes from the mosaic (grey world)
assert!(info.wb_multipliers.is_some(), "no white balance");
eprintln!("peak heap {peak} bytes probing a {} byte file", file.len());
assert!(peak < 2 << 20, "peak heap {peak} bytes probing a {} byte file", file.len());
}
9 changes: 9 additions & 0 deletions docs/whats-new.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# What's new in LightCraft

## 2026-10-22

### Reliability
- A damaged or crafted lossy DNG, Epson ERF or Mamiya MEF can no longer make LightCraft set aside gigabytes of memory
(or crash it on the web) for a JPEG whose header claims a far larger picture than it holds (issue #2560). Each JPEG in
a lossy DNG may be no larger than the tile or strip it fills, and the embedded preview used to measure white balance
no larger than 16 megapixels, the most that measurement uses; both are checked from the JPEG header before anything is
decoded.

## 2026-10-21

### Sharper resampling in HDR and panorama merges
Expand Down
Loading