Integration: keep only the segment of a lossless-JPEG tile, test the sum through decode (#6041)

A compression-7 frame may declare up to four times its segment's samples
(ljpeg::decode is capped at 4x the tile), and read_plane returned the whole
frame, so each retained tile held up to 4x what retained_segment_bytes
charges it: tiles declared 256x256 holding 512x512 frames pass a 1 MiB
budget while keeping 2 MiB. The lossless-JPEG arm moves into
lossless_jpeg(), which now truncates to the segment's rows (all the scatter
reads) and releases the spare capacity.

The PR's test only called the helper; deleting the call in read_plane kept
it green. decode_charges_the_retained_tiles_together drives decode on an
18x18 CFA in four padded 16x16 LJ92 tiles: 1500 B -> LimitExceeded, 2048 B
-> Ok. lossless_jpeg_keeps_only_the_segment pins the truncation. The doc
comment now says the output plane is alive alongside the sum.

Co-authored-by: Muhammad Saad <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
committed 2026-10-22 21:09:26 +02:00
1 parent 810ddb9232
commit f40366f1a8
1 file changed
+69 -27
+69 -27
View File
@@ -294,31 +294,8 @@ pub(crate) fn read_plane(t: &Tiff, ifd: &Ifd, limits: &Limits, layout: JpegLayou
Ok(v)
}
34892 => lossy_jpeg(src, s, rows, samples, bits, tiled, limits),
// Compression 7 (lossless JPEG): the frame the entropy stream declares is capped
// by the budget, not only by the segment, and the `Quads` scatter buffer below
// comes out of the same budget. `max_alloc` counts bytes, a sample is two.
_ => {
let need = s.w * rows * samples;
let scatter = if layout == JpegLayout::Quads && samples == 1 { s.w.saturating_mul(s.h).saturating_mul(2) as u64 } else { 0 };
let budget = usize::try_from(limits.max_alloc.saturating_sub(scatter) / 2).unwrap_or(usize::MAX);
let geom = s.w.saturating_mul(s.h).saturating_mul(samples).saturating_mul(4);
let (f, v) = ljpeg::decode(src, geom.min(budget))?;
if v.len() < need {
return Err(RawError::malformed("lossless JPEG tile is smaller than its tile"));
}
if layout == JpegLayout::Quads && samples == 1 && f.components == 4 && f.width * 2 == s.w && f.height * 2 == s.h {
let mut tile = vec![0u16; s.w * s.h];
for (i, q) in v.as_chunks::<4>().0.iter().enumerate() {
let at = 2 * (i / f.width) * s.w + 2 * (i % f.width);
tile[at] = q[0];
tile[at + 1] = q[1];
tile[at + s.w] = q[2];
tile[at + s.w + 1] = q[3];
}
return Ok(tile);
}
Ok(v)
}
// Compression 7 (lossless JPEG).
_ => lossless_jpeg(src, s, rows, samples, layout, limits),
}
});
let mut data = vec![0u16; width * height * samples];
@@ -338,8 +315,8 @@ pub(crate) fn read_plane(t: &Tiff, ifd: &Ifd, limits: &Limits, layout: JpegLayou
/// Bytes of decoded samples the segments hold at once.
///
/// Each segment is charged against `limits` on its own just before it decodes, but every decoded
/// tile is retained until the scatter at the end of [`read_plane`], so the peak is their sum and
/// not the largest of them. A segment's geometry is declared independently of the image, so a
/// tile is retained until the scatter at the end of [`read_plane`], so what is alive at once is
/// their sum (plus the output plane the scatter fills), not the largest of them. A segment's geometry is declared independently of the image, so a
/// file can carry many segments that are each admissible and together are not (#4959). For a
/// well-formed file the segments tile the image, so their sum is about its own size, which
/// `limits.check` has already bounded.
@@ -401,6 +378,37 @@ pub(crate) fn segments(t: &Tiff, ifd: &Ifd, width: usize, height: usize) -> Resu
Ok(out)
}
/// Decodes one compression-7 (lossless JPEG) segment to the segment's own samples.
///
/// The frame the entropy stream declares is capped by the budget, not only by the segment, and
/// the `Quads` scatter buffer comes out of the same budget. `max_alloc` counts bytes, a sample is two.
fn lossless_jpeg(src: &[u8], s: &Segment, rows: usize, samples: usize, layout: JpegLayout, limits: &Limits) -> Result<Vec<u16>> {
let need = s.w * rows * samples;
let scatter = if layout == JpegLayout::Quads && samples == 1 { s.w.saturating_mul(s.h).saturating_mul(2) as u64 } else { 0 };
let budget = usize::try_from(limits.max_alloc.saturating_sub(scatter) / 2).unwrap_or(usize::MAX);
let geom = s.w.saturating_mul(s.h).saturating_mul(samples).saturating_mul(4);
let (f, mut v) = ljpeg::decode(src, geom.min(budget))?;
if v.len() < need {
return Err(RawError::malformed("lossless JPEG tile is smaller than its tile"));
}
if layout == JpegLayout::Quads && samples == 1 && f.components == 4 && f.width * 2 == s.w && f.height * 2 == s.h {
let mut tile = vec![0u16; s.w * s.h];
for (i, q) in v.as_chunks::<4>().0.iter().enumerate() {
let at = 2 * (i / f.width) * s.w + 2 * (i % f.width);
tile[at] = q[0];
tile[at + 1] = q[1];
tile[at + s.w] = q[2];
tile[at + s.w + 1] = q[3];
}
return Ok(tile);
}
// The frame may declare up to four times the segment's samples; the scatter reads only the
// segment's own rows, and the frame is retained until then, so keep just those (#4959).
v.truncate(need);
v.shrink_to_fit();
Ok(v)
}
/// Decodes one segment of a lossy DNG (Adobe DNG compression 34892): a complete baseline-DCT
/// JPEG stream (ITU-T T.81), 8 bits per sample, as DNG 1.4 defines it. A CFA segment is a
/// one-component (gray) JPEG; a 3-sample LinearRaw segment is a three-component one in YCbCr,
@@ -527,6 +535,40 @@ mod tests {
assert!(retained_segment_bytes(&normal, 1, &Limits::default()).is_ok());
}
/// #4959 end to end: the sum is charged in `read_plane`, not only by the helper. An 18x18
/// CFA in four padded 16x16 lossless-JPEG tiles: the image (648 B) and each tile (512 B) fit
/// a 1500 B budget, the four retained tiles (2048 B) do not.
#[test]
fn decode_charges_the_retained_tiles_together() {
use crate::testgen::{DngSpec, DngStorage, mosaic, scene};
let mut d = DngSpec::cfa(18, 18, mosaic(&scene(18, 18), 18, [0, 1, 1, 2], 64, 4000));
d.bits = 12;
d.white = 4000;
d.black = vec![64];
d.storage = DngStorage::Lj92Tiles { width: 16, height: 16 };
let b = d.build();
let tight = Limits { max_alloc: 1500, ..Limits::default() };
assert!(matches!(crate::decode(&b, &tight), Err(RawError::LimitExceeded(_))));
let exact = Limits { max_alloc: 2048, ..Limits::default() };
assert!(crate::decode(&b, &exact).is_ok(), "the padded tiles exactly at the budget still decode");
}
/// #4959: a lossless-JPEG frame may declare up to four times its segment's samples. The
/// segment is charged for its own size only, so it must keep only that until the scatter.
#[test]
fn lossless_jpeg_keeps_only_the_segment() {
let frame: Vec<u16> = (0..64 * 64).map(|i| (i % 4096) as u16).collect();
let src = crate::testgen::lj92_encode(&frame, 64, 64, 1, 12, 1, None);
let s = Segment { x: 0, y: 0, w: 32, h: 32, offset: 0, len: src.len() };
let v = lossless_jpeg(&src, &s, 32, 1, JpegLayout::Flat, &Limits::default()).unwrap();
assert_eq!(v.len(), 32 * 32, "only the segment's samples are retained");
assert!(v.capacity() < 64 * 64, "the frame's spare capacity is released");
assert_eq!(v[..32], frame[..32], "the first row is the frame's first row");
// An edge strip keeps only the rows inside the image.
let v = lossless_jpeg(&src, &s, 20, 1, JpegLayout::Flat, &Limits::default()).unwrap();
assert_eq!(v.len(), 32 * 20);
}
#[test]
fn bayer_patterns() {
for p in ["RGGB", "BGGR", "GRBG", "GBRG"] {