From 56bd09db4078abb5e1bfc21346f6f5e45ac8f439 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 23:27:06 -0600 Subject: [PATCH 01/11] fix(data): GeoTIFFs of 1, 2 and 4 bits a sample open Their samples come from the decoder packed several to a byte, and weren't unpacked, so such a file failed with "couldn't read every band". They are unpacked a strip or tile at a time, so they open whole, on several threads, every k-th pixel and in place, either bit order. Scanned maps and documents and masks are often stored so. --- crates/data/src/raster/geotiff.rs | 196 ++++++++++++++++++++++++++++-- crates/data/src/raster/lzw.rs | 28 ++++- 2 files changed, 214 insertions(+), 10 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 227beece52..bc9bbc3d56 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -741,12 +741,59 @@ pub(crate) fn read_chunk( return Ok((c.samples, c.gaps)); } match dec.read_chunk(index) { - Ok(v) => Ok((v, None)), + Ok(v) => { + // Several samples a byte: unpacked, a byte each, the chunk's rows as wide as its data. + let row = chunk_columns(dec, index).saturating_mul(samples_in_chunk(dec)); + Ok((unpack_bits(dec, v, row)?, None)) + } Err(e) if lzw(dec) => super::lzw::chunk(dec, index).map(|v| (v, None)).map_err(|_| err(e)), Err(e) => Err(err(e)), } } +/// The columns chunk `index` (counting through every plane) of the current image holds: a strip's, +/// the image's width; a tile's, its width cut at the image's right edge, as the decoder gives them. +fn chunk_columns(dec: &mut Decoder, index: u32) -> usize { + let Ok((w, h)) = dec.dimensions() else { return 0 }; + let Some(tw) = dec.find_tag_unsigned::(Tag::TileWidth).ok().flatten().filter(|t| *t > 0) else { return w as usize }; + let th = dec.find_tag_unsigned::(Tag::TileLength).ok().flatten().filter(|t| *t > 0).unwrap_or(tw); + let across = w.div_ceil(tw).max(1); + let per_plane = across.saturating_mul(h.div_ceil(th)).max(1); + let x0 = u64::from((index % per_plane) % across) * u64::from(tw); + u64::from(tw).min(u64::from(w).saturating_sub(x0)) as usize +} + +/// Samples a pixel of one of the current image's chunks: one when its bands are stored apart. +fn samples_in_chunk(dec: &mut Decoder) -> usize { + if dec.find_tag_unsigned::(Tag::PlanarConfiguration).ok().flatten() == Some(2) { 1 } else { samples(dec) } +} + +/// Samples of fewer than 8 bits (1, 2 or 4), packed several to a byte in rows of `row` samples that +/// each start on a byte, as the decoder gives them: each in a byte of its own. Others are as they +/// are. A FillOrder of 2 (the first sample in a byte's lowest bits) is read as such. +fn unpack_bits(dec: &mut Decoder, buf: DecodingResult, row: usize) -> Result { + let bits = usize::from(bits(dec)); + let DecodingResult::U8(packed) = buf else { return Ok(buf) }; + if !matches!(bits, 1 | 2 | 4) || row == 0 { + return Ok(DecodingResult::U8(packed)); + } + let lsb_first = dec.find_tag_unsigned::(Tag::FillOrder).ok().flatten() == Some(2); + let row_bytes = (row * bits).div_ceil(8); + let rows = packed.len() / row_bytes; + let n = rows.checked_mul(row).filter(|n| *n <= decoding_limit()).ok_or_else(|| err("a strip or tile is too large to read"))?; + let mut out = Vec::new(); + out.try_reserve_exact(n).map_err(|_| err("a strip or tile is too large to read"))?; + let mask = (1u8 << bits) - 1; + for line in packed.chunks_exact(row_bytes) { + for i in 0..row { + let at = i * bits; + let byte = line.get(at / 8).map_or(0, |b| if lsb_first { b.reverse_bits() } else { *b }); + out.push((byte >> (8 - bits - at % 8)) & mask); + } + } + Ok(DecodingResult::U8(out)) +} + /// Turns a JPEG-compressed image's three YCbCr bands into red, green and blue in place, with the /// JFIF (full-range) coefficients JPEG-in-TIFF files use. pub(super) fn ycbcr_to_rgb(bands: &mut [Vec]) { @@ -2012,9 +2059,9 @@ fn read_image( if planar && nbands > 1 && tiled && !planar_tiles && decimate_by == 1 && padded { return Err(err("tiled bands stored apart at fewer than 8 bits a sample aren't supported")); } - // A large image, from a file, is read a chunk at a time on several threads (not one of - // fewer than 8 bits a sample, whose chunks pack several pixels to a byte). - let chunked = open.is_some() && n >= 1 << 20 && bits(&mut dec) >= 8; + // A large image, from a file, is read a chunk at a time on several threads ([`read_chunk`] + // unpacks samples of fewer than 8 bits). + let chunked = open.is_some() && n >= 1 << 20; // The decoder has no LERC codec: such an image is read a chunk at a time, every chunk decoded // by [`super::lerc`] (#1818). let lerc = super::lerc::is_lerc(&mut dec); @@ -2023,9 +2070,6 @@ fn read_image( let by_chunk = decimate_by > 1 || extra_samples || planar_tiles || chunked || lerc || span.is_some(); let (chunk_count, absent) = super::lerc::Table::default().chunks(&mut dec); let sparse = !by_chunk && absent > 0; - if absent > 0 && bits(&mut dec) < 8 { - return Err(err("a sparse file of fewer than 8 bits a sample isn't supported")); - } let whole = if by_chunk || sparse { None } else { @@ -2034,7 +2078,7 @@ fn read_image( Ok(_) => Some(buf), // An LZW image the decoder fails on is read a chunk at a time, the chunks it fails on // decoded by [`read_chunk`] (issue #350). - Err(_) if lzw(&mut dec) && bits(&mut dec) >= 8 => None, + Err(_) if lzw(&mut dec) => None, Err(e) => return Err(err(e)), } }; @@ -2051,6 +2095,9 @@ fn read_image( } } } + // Samples of fewer than 8 bits come packed, each row starting on a byte (a band's rows + // after another's, when they are stored apart). + let buf = unpack_bits(&mut dec, buf, ow as usize * if planar { 1 } else { nbands })?; let (values, dt) = to_f32(buf, (ow as usize, oh as usize))?; if values.len() < n.saturating_mul(nbands) { return Err(err("couldn't read every band")); @@ -5038,6 +5085,139 @@ mod tests { } } + /// A little-endian TIFF of one band of `bits` a sample (1, 2 or 4), `w` × `h`, uncompressed or (with + /// `lzw`) LZW-compressed: in + /// strips of `rows` rows, or in tiles of `tile` a side, each row of a chunk starting on a byte, + /// pixel (x, y) being `pixel(x, y)`; with `lsb_first`, FillOrder 2. + fn packed_tiff( + w: u32, + h: u32, + bits: u32, + (rows, tile): (u32, Option), + lsb_first: bool, + lzw: bool, + pixel: impl Fn(u32, u32) -> u8, + ) -> Vec { + let (cw, ch) = tile.map_or((w, rows), |t| (t, t)); + let (across, down) = (w.div_ceil(cw), h.div_ceil(ch)); + let mut out = vec![b'I', b'I', 42, 0, 0, 0, 0, 0]; + let (mut offsets, mut counts) = (Vec::new(), Vec::new()); + for c in 0..across * down { + let (x0, y0) = ((c % across) * cw, (c / across) * ch); + // A tile holds its padding; a strip only the image's rows, and its columns to the edge. + let (cols, lines) = if tile.is_some() { (cw, ch) } else { (w, ch.min(h - y0)) }; + let (start, mut raw) = (out.len(), Vec::new()); + for y in y0..y0 + lines { + let mut line = vec![0u8; (cols * bits).div_ceil(8) as usize]; + for x in 0..cols { + let v = if x0 + x < w && y < h { pixel(x0 + x, y) } else { 0 }; + let at = x * bits; + line[(at / 8) as usize] |= v << (8 - bits - at % 8); + } + if lsb_first { + line.iter_mut().for_each(|b| *b = b.reverse_bits()); + } + raw.extend(line); + } + if lzw { + raw = weezl::encode::Encoder::with_tiff_size_switch(weezl::BitOrder::Msb, 8).encode(&raw).unwrap(); + } + out.extend(raw); + offsets.push(start as u32); + counts.push((out.len() - start) as u32); + } + let shorts = |v: u16| v.to_le_bytes().to_vec(); + let longs = |v: &[u32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::>(); + let (at, count) = if tile.is_some() { (324u16, 325u16) } else { (273, 279) }; + let mut e: Vec<(u16, u16, u32, Vec)> = vec![ + (256, 4, 1, longs(&[w])), + (257, 4, 1, longs(&[h])), + (258, 3, 1, shorts(bits as u16)), + (259, 3, 1, shorts(if lzw { 5 } else { 1 })), + (262, 3, 1, shorts(1)), + (266, 3, 1, shorts(if lsb_first { 2 } else { 1 })), + (277, 3, 1, shorts(1)), + (284, 3, 1, shorts(1)), + ]; + match tile { + Some(t) => e.extend([(322, 4, 1, longs(&[t])), (323, 4, 1, longs(&[t]))]), + None => e.push((278, 4, 1, longs(&[rows]))), + } + e.push((at, 4, offsets.len() as u32, longs(&offsets))); + e.push((count, 4, counts.len() as u32, longs(&counts))); + e.sort_by_key(|x| x.0); + out.resize(out.len().next_multiple_of(2), 0); + let ifd = out.len(); + out[4..8].copy_from_slice(&(ifd as u32).to_le_bytes()); + let mut data_at = ifd + 2 + 12 * e.len() + 4; + let (mut table, mut data): (Vec, Vec) = (Vec::new(), Vec::new()); + for (tag, ty, n, bytes) in &e { + table.extend(tag.to_le_bytes()); + table.extend(ty.to_le_bytes()); + table.extend(n.to_le_bytes()); + if bytes.len() > 4 { + table.extend((data_at as u32).to_le_bytes()); + data_at += bytes.len(); + data.extend(bytes); + } else { + let mut b = bytes.clone(); + b.resize(4, 0); + table.extend(b); + } + } + out.extend((e.len() as u16).to_le_bytes()); + out.extend(table); + out.extend([0; 4]); + out.extend(data); + out + } + + /// Samples of 1, 2 and 4 bits are read, each a byte, in strips and tiles, either bit order, on + /// one thread or several, every pixel or every other, and a tile at a time in place. + #[test] + fn samples_of_fewer_than_8_bits_are_read() { + for bits in [1u32, 2, 4] { + let top = (1u32 << bits) - 1; + let pixel = move |x: u32, y: u32| ((x * 7 + y * 3) % (top + 1)) as u8; + for layout in [(5, None), (64, None), (1, Some(32))] { + for lsb_first in [false, true] { + // 37 columns: rows that don't end on a byte. + let bytes = packed_tiff(37, 21, bits, layout, lsb_first, false, pixel); + let r = read(std::io::Cursor::new(&bytes), "packed").unwrap(); + let at = format!("{bits} bits, {layout:?}, lsb first {lsb_first}"); + assert_eq!((r.width, r.height, r.data_type.as_str()), (37, 21, "UInt8"), "{at}"); + for (x, y) in [(0, 0), (1, 0), (8, 3), (36, 0), (36, 20), (17, 11)] { + assert_eq!(r.value(0, i64::from(x), i64::from(y)), Some(f32::from(pixel(x, y))), "{at}: {x}, {y}"); + } + } + } + // A million pixels, on several threads, then every other. + let big = packed_tiff(1100, 1000, bits, (16, None), false, false, pixel); + for (max, k) in [(usize::MAX, 1u32), (300_000, 2)] { + let r = read_threaded(&big, max).unwrap(); + for (x, y) in [(0, 0), (1099, 999), (513, 77)] { + let (x, y) = (x / k * k, y / k * k); + assert_eq!(r.value(0, i64::from(x / k), i64::from(y / k)), Some(f32::from(pixel(x, y))), "{bits} bits, every {k}"); + } + } + // A tile at a time, as a file read in place is. + let tiled = packed_tiff(37, 21, bits, (1, Some(16)), false, false, pixel); + let mut dec = Decoder::new(reader(std::io::Cursor::new(&tiled)).unwrap()).unwrap(); + let (chunk, _) = read_chunk(&mut dec, 2, &mut super::super::lerc::Table::default()).unwrap(); + let DecodingResult::U8(edge) = chunk else { panic!("not bytes") }; + assert_eq!((edge.len(), edge[0], edge[4]), (5 * 16, pixel(32, 0), pixel(36, 0)), "{bits} bits, the right edge tile"); + // LZW, by our decoder (which the decoder's failures fall back to) as by the crate's. + for lsb_first in [false, true] { + let packed = packed_tiff(37, 21, bits, (1, Some(16)), lsb_first, true, pixel); + let mut dec = Decoder::new(reader(std::io::Cursor::new(&packed)).unwrap()).unwrap(); + let DecodingResult::U8(ours) = super::super::lzw::chunk(&mut dec, 2).unwrap() else { panic!("not bytes") }; + assert_eq!(ours, edge, "{bits} bits, lsb first {lsb_first}"); + let r = read(std::io::Cursor::new(&packed), "lzw").unwrap(); + assert_eq!(r.value(0, 36, 20), Some(f32::from(pixel(36, 20))), "{bits} bits, lsb first {lsb_first}"); + } + } + } + #[test] fn padded_planar_tiles_below_8_bits_are_refused() { // They can't be read a tile at a time, and the decoder panics reading them whole. diff --git a/crates/data/src/raster/lzw.rs b/crates/data/src/raster/lzw.rs index b5cda20bd7..d0f0c20dda 100644 --- a/crates/data/src/raster/lzw.rs +++ b/crates/data/src/raster/lzw.rs @@ -36,7 +36,7 @@ pub(crate) fn chunk(dec: &mut Decoder, index: u32) -> Result< } let bits = dec.find_tag_unsigned_vec::(Tag::BitsPerSample).ok().flatten().unwrap_or_else(|| vec![1]); let bps = *bits.first().unwrap_or(&1); - if bits.iter().any(|b| *b != bps) || !matches!(bps, 8 | 16 | 32 | 64) { + if bits.iter().any(|b| *b != bps) || !matches!(bps, 1 | 2 | 4 | 8 | 16 | 32 | 64) { return Err(err(format!("{bps}-bit LZW samples aren't supported"))); } let format = dec.find_tag_unsigned_vec::(Tag::SampleFormat).ok().flatten().and_then(|v| v.first().copied()).unwrap_or(1); @@ -53,7 +53,12 @@ pub(crate) fn chunk(dec: &mut Decoder, index: u32) -> Result< let dw = if tiled { cw.min(w.saturating_sub(x0)) } else { w } as usize; let dh = ch.min(h.saturating_sub(y0)) as usize; let size = usize::from(bps / 8); - let row_bytes = (cw as usize).checked_mul(samples).and_then(|n| n.checked_mul(size)).ok_or_else(|| err("a chunk is too large"))?; + // Of fewer than 8 bits, a row's samples are packed and the row ends on a byte. + let row_bytes = (cw as usize) + .checked_mul(samples) + .and_then(|n| n.checked_mul(usize::from(bps))) + .map(|bits| bits.div_ceil(8)) + .ok_or_else(|| err("a chunk is too large"))?; // A tile holds every row, padded; a strip holds only the image's. let rows = if tiled { ch as usize } else { dh }; let need = row_bytes.checked_mul(rows).filter(|n| *n <= MAX_CHUNK_BYTES).ok_or_else(|| err("a chunk is too large"))?; @@ -79,6 +84,25 @@ pub(crate) fn chunk(dec: &mut Decoder, index: u32) -> Result< return Err(err("an LZW chunk is shorter than its strip or tile")); } + // Packed samples, unpacked a byte each (as `geotiff::read_chunk` unpacks the decoder's), the + // rows cut to the image's columns. No predictor applies to them. + if bps < 8 { + if predictor != 1 { + return Err(err(format!("predictor {predictor} isn't supported for {bps}-bit samples"))); + } + let lsb_first = tag(dec, Tag::FillOrder) == Some(2); + let (bits, mask) = (usize::from(bps), (1u8 << bps) - 1); + let mut out = Vec::with_capacity(dw * dh * samples); + for row in decoded.chunks(row_bytes).take(dh) { + for i in 0..dw * samples { + let at = i * bits; + let byte = row.get(at / 8).map_or(0, |b| if lsb_first { b.reverse_bits() } else { *b }); + out.push((byte >> (8 - bits - at % 8)) & mask); + } + } + return Ok(DecodingResult::U8(out)); + } + let little = matches!(dec.byte_order(), ByteOrder::LittleEndian); // Converted a row at a time: only a row is ever held as words. let mut out = empty(format, bps, dw * dh * samples)?; From d61d40c0a8aabc5f3c22c6853c1c21b8287edec6 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 00:53:45 -0600 Subject: [PATCH 02/11] fix(data): bound and check sub-byte unpacking, and refuse signed sub-byte samples The LZW fallback's unpacked chunk is bounded and reserved fallibly, a row's size is checked, a width that can't be read is an error, a missing BitsPerSample is 1 as TIFF has it, and signed samples of fewer than 8 bits are refused rather than read as unsigned. A sparse file of them opens. --- crates/data/src/raster/geotiff.rs | 27 ++++++++++++++++++++++++--- crates/data/src/raster/lzw.rs | 7 ++++++- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index bc9bbc3d56..c1f7bbc76d 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -772,13 +772,22 @@ fn samples_in_chunk(dec: &mut Decoder) -> usize { /// each start on a byte, as the decoder gives them: each in a byte of its own. Others are as they /// are. A FillOrder of 2 (the first sample in a byte's lowest bits) is read as such. fn unpack_bits(dec: &mut Decoder, buf: DecodingResult, row: usize) -> Result { - let bits = usize::from(bits(dec)); + // A missing BitsPerSample is 1, the TIFF default. + let bits = dec.find_tag_unsigned_vec::(Tag::BitsPerSample).ok().flatten().and_then(|v| v.into_iter().max()).unwrap_or(1); + let bits = usize::from(bits); let DecodingResult::U8(packed) = buf else { return Ok(buf) }; - if !matches!(bits, 1 | 2 | 4) || row == 0 { + if !matches!(bits, 1 | 2 | 4) { return Ok(DecodingResult::U8(packed)); } + if dec.find_tag_unsigned::(Tag::SampleFormat).ok().flatten() == Some(2) { + return Err(err(format!("signed samples of {bits} bits aren't supported"))); + } + // Packed samples taken a byte each would be wrong values, not some. + if row == 0 { + return Err(err("a strip or tile's width can't be read")); + } let lsb_first = dec.find_tag_unsigned::(Tag::FillOrder).ok().flatten() == Some(2); - let row_bytes = (row * bits).div_ceil(8); + let row_bytes = row.checked_mul(bits).map(|b| b.div_ceil(8)).ok_or_else(|| err("a strip or tile is too large to read"))?; let rows = packed.len() / row_bytes; let n = rows.checked_mul(row).filter(|n| *n <= decoding_limit()).ok_or_else(|| err("a strip or tile is too large to read"))?; let mut out = Vec::new(); @@ -5200,6 +5209,18 @@ mod tests { assert_eq!(r.value(0, i64::from(x / k), i64::from(y / k)), Some(f32::from(pixel(x, y))), "{bits} bits, every {k}"); } } + // A sparse file opens, its missing strip read as an 8-bit file's is. + let mut holes = packed_tiff(37, 21, bits, (5, None), false, false, pixel); + let at32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize; + let ifd = at32(&holes, 4); + for e in (0..u16::from_le_bytes([holes[ifd], holes[ifd + 1]]) as usize).map(|i| ifd + 2 + 12 * i) { + if [273u16, 279].contains(&u16::from_le_bytes([holes[e], holes[e + 1]])) { + let table = at32(&holes, e + 8); + holes[table + 4..table + 8].fill(0); + } + } + let r = read(std::io::Cursor::new(&holes), "holes").unwrap(); + assert_eq!((r.value(0, 3, 2), r.value(0, 3, 6)), (Some(f32::from(pixel(3, 2))), None), "{bits} bits, sparse"); // A tile at a time, as a file read in place is. let tiled = packed_tiff(37, 21, bits, (1, Some(16)), false, false, pixel); let mut dec = Decoder::new(reader(std::io::Cursor::new(&tiled)).unwrap()).unwrap(); diff --git a/crates/data/src/raster/lzw.rs b/crates/data/src/raster/lzw.rs index d0f0c20dda..260743019d 100644 --- a/crates/data/src/raster/lzw.rs +++ b/crates/data/src/raster/lzw.rs @@ -90,9 +90,14 @@ pub(crate) fn chunk(dec: &mut Decoder, index: u32) -> Result< if predictor != 1 { return Err(err(format!("predictor {predictor} isn't supported for {bps}-bit samples"))); } + if format == 2 { + return Err(err(format!("signed samples of {bps} bits aren't supported"))); + } let lsb_first = tag(dec, Tag::FillOrder) == Some(2); let (bits, mask) = (usize::from(bps), (1u8 << bps) - 1); - let mut out = Vec::with_capacity(dw * dh * samples); + let n = dw.checked_mul(dh).and_then(|n| n.checked_mul(samples)).filter(|n| *n <= MAX_CHUNK_BYTES); + let mut out = Vec::new(); + out.try_reserve_exact(n.ok_or_else(|| err("a chunk is too large"))?).map_err(|_| err("a chunk is too large"))?; for row in decoded.chunks(row_bytes).take(dh) { for i in 0..dw * samples { let at = i * bits; From 2b2e299ce2d1581ff1d865a62fcee3a0d18cfc60 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 01:41:12 -0600 Subject: [PATCH 03/11] fix(data): signed samples of fewer than 8 bits are refused before the decoder's are passed on The decoder gives them packed in signed bytes, which were returned as they were; the refusal now comes first. --- crates/data/src/raster/geotiff.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index c1f7bbc76d..987dc9612e 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -775,13 +775,14 @@ fn unpack_bits(dec: &mut Decoder, buf: DecodingResult, row: u // A missing BitsPerSample is 1, the TIFF default. let bits = dec.find_tag_unsigned_vec::(Tag::BitsPerSample).ok().flatten().and_then(|v| v.into_iter().max()).unwrap_or(1); let bits = usize::from(bits); - let DecodingResult::U8(packed) = buf else { return Ok(buf) }; if !matches!(bits, 1 | 2 | 4) { - return Ok(DecodingResult::U8(packed)); + return Ok(buf); } + // The decoder gives signed ones packed in `I8`s: refused, not read as either. if dec.find_tag_unsigned::(Tag::SampleFormat).ok().flatten() == Some(2) { return Err(err(format!("signed samples of {bits} bits aren't supported"))); } + let DecodingResult::U8(packed) = buf else { return Ok(buf) }; // Packed samples taken a byte each would be wrong values, not some. if row == 0 { return Err(err("a strip or tile's width can't be read")); @@ -5209,6 +5210,17 @@ mod tests { assert_eq!(r.value(0, i64::from(x / k), i64::from(y / k)), Some(f32::from(pixel(x, y))), "{bits} bits, every {k}"); } } + // Signed ones are refused (the FillOrder entry taken for a SampleFormat of 2). + let mut signed = packed_tiff(37, 21, bits, (5, None), false, false, pixel); + let ifd = u32::from_le_bytes(signed[4..8].try_into().unwrap()) as usize; + for e in (0..u16::from_le_bytes([signed[ifd], signed[ifd + 1]]) as usize).map(|i| ifd + 2 + 12 * i) { + if signed[e..e + 2] == 266u16.to_le_bytes() { + signed[e..e + 2].copy_from_slice(&339u16.to_le_bytes()); + signed[e + 8..e + 10].copy_from_slice(&2u16.to_le_bytes()); + } + } + let e = read(std::io::Cursor::new(&signed), "signed").unwrap_err(); + assert!(e.to_string().contains(&format!("signed samples of {bits} bits")), "{bits} bits: {e}"); // A sparse file opens, its missing strip read as an 8-bit file's is. let mut holes = packed_tiff(37, 21, bits, (5, None), false, false, pixel); let at32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize; From e863cd742ab9fec272d3fbce9454c98647721723 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 02:24:25 -0600 Subject: [PATCH 04/11] fix(data): tiled bands stored apart below 8 bits are read a tile at a time The refusal was skipped for a decimated read, so the same file was refused at full size and read at reduced size. Reading a tile at a time now unpacks the samples, so the refusal goes. The LZW fallback returns packed rows that read_chunk unpacks with the decoder's, keeps both errors, and only sub-byte chunks look up the chunk's width. --- crates/data/src/raster/geotiff.rs | 100 +++++++++++++++++++----------- crates/data/src/raster/lzw.rs | 19 ++---- 2 files changed, 69 insertions(+), 50 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 987dc9612e..7d63e4620f 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -740,15 +740,14 @@ pub(crate) fn read_chunk( let c = super::lerc::chunk(dec, index, table)?; return Ok((c.samples, c.gaps)); } - match dec.read_chunk(index) { - Ok(v) => { - // Several samples a byte: unpacked, a byte each, the chunk's rows as wide as its data. - let row = chunk_columns(dec, index).saturating_mul(samples_in_chunk(dec)); - Ok((unpack_bits(dec, v, row)?, None)) - } - Err(e) if lzw(dec) => super::lzw::chunk(dec, index).map(|v| (v, None)).map_err(|_| err(e)), - Err(e) => Err(err(e)), - } + let v = match dec.read_chunk(index) { + Ok(v) => v, + Err(e) if lzw(dec) => super::lzw::chunk(dec, index).map_err(|l| err(format!("{e}; {l}")))?, + Err(e) => return Err(err(e)), + }; + // Several samples a byte: unpacked, a byte each, the chunk's rows as wide as its data. + let row = |dec: &mut Decoder| chunk_columns(dec, index).saturating_mul(samples_in_chunk(dec)); + Ok((unpack_bits(dec, v, row)?, None)) } /// The columns chunk `index` (counting through every plane) of the current image holds: a strip's, @@ -771,7 +770,11 @@ fn samples_in_chunk(dec: &mut Decoder) -> usize { /// Samples of fewer than 8 bits (1, 2 or 4), packed several to a byte in rows of `row` samples that /// each start on a byte, as the decoder gives them: each in a byte of its own. Others are as they /// are. A FillOrder of 2 (the first sample in a byte's lowest bits) is read as such. -fn unpack_bits(dec: &mut Decoder, buf: DecodingResult, row: usize) -> Result { +fn unpack_bits( + dec: &mut Decoder, + buf: DecodingResult, + row: impl FnOnce(&mut Decoder) -> usize, +) -> Result { // A missing BitsPerSample is 1, the TIFF default. let bits = dec.find_tag_unsigned_vec::(Tag::BitsPerSample).ok().flatten().and_then(|v| v.into_iter().max()).unwrap_or(1); let bits = usize::from(bits); @@ -784,6 +787,7 @@ fn unpack_bits(dec: &mut Decoder, buf: DecodingResult, row: u } let DecodingResult::U8(packed) = buf else { return Ok(buf) }; // Packed samples taken a byte each would be wrong values, not some. + let row = row(dec); if row == 0 { return Err(err("a strip or tile's width can't be read")); } @@ -2056,19 +2060,12 @@ fn read_image( // Extra samples the decoder leaves out can make padded edge tiles spill into the next row // when read whole (issue #162). Read those tile by tile. An RGBI image the patched reader // shows as grey (see `Unpaletted`) keeps its fourth sample and doesn't need this. - let tile_rows = dec.find_tag_unsigned::(Tag::TileLength).ok().flatten(); let tiled = dec.find_tag_unsigned::(Tag::TileWidth).ok().flatten().is_some(); let extra_samples = !planar && samples(&mut dec) > nbands && tiled; // The decoder asserts (panics) on the padded bottom tiles of the later bands of a tiled image // whose bands are stored apart, read whole (issue #544): such an image is read a tile at a - // time, which can't be done below 8 bits a sample. - let planar_tiles = planar && nbands > 1 && tiled && bits(&mut dec) >= 8; - // `padded`: padding rows at the bottom. Right-edge padding is fine: the decoder places it by - // the tile's column, which is right in every band. - let padded = tile_rows.is_none_or(|t| t == 0 || h % t != 0); - if planar && nbands > 1 && tiled && !planar_tiles && decimate_by == 1 && padded { - return Err(err("tiled bands stored apart at fewer than 8 bits a sample aren't supported")); - } + // time ([`read_chunk`] unpacks samples of fewer than 8 bits). + let planar_tiles = planar && nbands > 1 && tiled; // A large image, from a file, is read a chunk at a time on several threads ([`read_chunk`] // unpacks samples of fewer than 8 bits). let chunked = open.is_some() && n >= 1 << 20; @@ -2107,7 +2104,7 @@ fn read_image( } // Samples of fewer than 8 bits come packed, each row starting on a byte (a band's rows // after another's, when they are stored apart). - let buf = unpack_bits(&mut dec, buf, ow as usize * if planar { 1 } else { nbands })?; + let buf = unpack_bits(&mut dec, buf, |_| ow as usize * if planar { 1 } else { nbands })?; let (values, dt) = to_f32(buf, (ow as usize, oh as usize))?; if values.len() < n.saturating_mul(nbands) { return Err(err("couldn't read every band")); @@ -5019,22 +5016,36 @@ mod tests { for b in 0..3 { for t in 0..across * down { offsets.push(out.len() as u32); - for p in 0..tw * th { - let (x, y) = ((t % across) * tw + p % tw, (t / across) * th + p / tw); - out.push(if x < w && y < h { pixel(b, x, y) } else { 0 }); + // Below 8 bits, a tile's rows are packed, the first sample in a byte's highest bits. + let row_bytes = (tw * u32::from(bits)).div_ceil(8); + for r in 0..th { + let mut row = vec![0u8; row_bytes as usize]; + for c in 0..tw { + let (x, y) = ((t % across) * tw + c, (t / across) * th + r); + let v = if x < w && y < h { pixel(b, x, y) } else { 0 }; + if bits >= 8 { + row[c as usize] = v; + } else { + let at = (c * u32::from(bits)) as usize; + row[at / 8] |= v << (8 - bits as usize - at % 8); + } + } + out.extend(row); } } } let shorts = |v: &[u16]| v.iter().flat_map(|x| x.to_le_bytes()).collect::>(); let longs = |v: &[u32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::>(); let doubles = |v: &[f64]| v.iter().flat_map(|x| x.to_le_bytes()).collect::>(); - let counts = vec![tw * th; offsets.len()]; + let counts = vec![(tw * u32::from(bits)).div_ceil(8) * th; offsets.len()]; let mut e: Vec<(u16, u16, u32, Vec)> = vec![ (256, 4, 1, longs(&[w])), (257, 4, 1, longs(&[h])), (258, 3, 3, shorts(&[bits; 3])), (259, 3, 1, shorts(&[1])), - (262, 3, 1, shorts(&[2])), + // Below 8 bits, grey and two extra bands, as GDAL writes them (the decoder has no RGB + // of fewer than 8 bits). + (262, 3, 1, shorts(&[if bits < 8 { 1 } else { 2 }])), (277, 3, 1, shorts(&[3])), (284, 3, 1, shorts(&[2])), (322, 4, 1, longs(&[tw])), @@ -5045,6 +5056,10 @@ mod tests { (33922, 12, 6, doubles(&[0.0, 0.0, 0.0, -8_300_000.0, -925_000.0, 0.0])), (34735, 3, 8, shorts(&[1, 1, 0, 1, 3072, 0, 1, 3857])), ]; + if bits < 8 { + e.push((338, 3, 2, shorts(&[0, 0]))); + e.sort_by_key(|t| t.0); + } let ifd_at = out.len() + out.len() % 2; out.resize(ifd_at, 0); let values_at = ifd_at + 2 + 12 * e.len() + 4; @@ -5243,7 +5258,8 @@ mod tests { for lsb_first in [false, true] { let packed = packed_tiff(37, 21, bits, (1, Some(16)), lsb_first, true, pixel); let mut dec = Decoder::new(reader(std::io::Cursor::new(&packed)).unwrap()).unwrap(); - let DecodingResult::U8(ours) = super::super::lzw::chunk(&mut dec, 2).unwrap() else { panic!("not bytes") }; + let packed_chunk = super::super::lzw::chunk(&mut dec, 2).unwrap(); + let DecodingResult::U8(ours) = unpack_bits(&mut dec, packed_chunk, |_| 5).unwrap() else { panic!("not bytes") }; assert_eq!(ours, edge, "{bits} bits, lsb first {lsb_first}"); let r = read(std::io::Cursor::new(&packed), "lzw").unwrap(); assert_eq!(r.value(0, 36, 20), Some(f32::from(pixel(36, 20))), "{bits} bits, lsb first {lsb_first}"); @@ -5252,16 +5268,28 @@ mod tests { } #[test] - fn padded_planar_tiles_below_8_bits_are_refused() { - // They can't be read a tile at a time, and the decoder panics reading them whole. - let bytes = planar_tiled(40, 24, (16, 16), 4, |_, _, _| 0); - let e = read(std::io::Cursor::new(&bytes), "planar").unwrap_err(); - assert!(e.to_string().contains("fewer than 8 bits"), "{e}"); - // Padded only on the right, they're left to the decoder (these samples are bytes, not - // nibbles, so whatever it makes of them). - let bytes = planar_tiled(40, 32, (16, 16), 4, |_, _, _| 0); - let read = read(std::io::Cursor::new(&bytes), "planar"); - assert!(read.as_ref().err().is_none_or(|e| !e.to_string().contains("fewer than 8 bits")), "{read:?}"); + fn tiled_bands_stored_apart_below_8_bits_are_read() { + // Padded at the bottom (which the decoder can't read whole, issue #544) and on the right + // only: read a tile at a time, every band's values are the file's. + for bits in [1u16, 2, 4] { + for (w, h) in [(40, 24), (40, 32)] { + let mask = (1u32 << bits) - 1; + let pixel = move |b: u32, x: u32, y: u32| ((b * 5 + x + 3 * y) & mask) as u8; + let r = read(std::io::Cursor::new(planar_tiled(w, h, (16, 16), bits, pixel)), "planar").unwrap(); + for b in 0..3 { + for y in 0..h { + for x in 0..w { + let want = Some(f32::from(pixel(b, x, y))); + assert_eq!( + r.value(b as usize, i64::from(x), i64::from(y)), + want, + "{bits} bits, {w}×{h}, band {b} at ({x}, {y})" + ); + } + } + } + } + } } #[test] diff --git a/crates/data/src/raster/lzw.rs b/crates/data/src/raster/lzw.rs index 260743019d..cef80c0f3f 100644 --- a/crates/data/src/raster/lzw.rs +++ b/crates/data/src/raster/lzw.rs @@ -84,26 +84,17 @@ pub(crate) fn chunk(dec: &mut Decoder, index: u32) -> Result< return Err(err("an LZW chunk is shorter than its strip or tile")); } - // Packed samples, unpacked a byte each (as `geotiff::read_chunk` unpacks the decoder's), the - // rows cut to the image's columns. No predictor applies to them. + // Packed samples, the rows cut to the image's columns and each ending on a byte, as the + // decoder gives them: `geotiff::read_chunk` unpacks them. No predictor applies to them. if bps < 8 { if predictor != 1 { return Err(err(format!("predictor {predictor} isn't supported for {bps}-bit samples"))); } - if format == 2 { - return Err(err(format!("signed samples of {bps} bits aren't supported"))); - } - let lsb_first = tag(dec, Tag::FillOrder) == Some(2); - let (bits, mask) = (usize::from(bps), (1u8 << bps) - 1); - let n = dw.checked_mul(dh).and_then(|n| n.checked_mul(samples)).filter(|n| *n <= MAX_CHUNK_BYTES); + let keep = dw.checked_mul(samples).and_then(|n| n.checked_mul(usize::from(bps))).map_or(row_bytes, |b| b.div_ceil(8)); let mut out = Vec::new(); - out.try_reserve_exact(n.ok_or_else(|| err("a chunk is too large"))?).map_err(|_| err("a chunk is too large"))?; + out.try_reserve_exact(keep.saturating_mul(dh)).map_err(|_| err("a chunk is too large"))?; for row in decoded.chunks(row_bytes).take(dh) { - for i in 0..dw * samples { - let at = i * bits; - let byte = row.get(at / 8).map_or(0, |b| if lsb_first { b.reverse_bits() } else { *b }); - out.push((byte >> (8 - bits - at % 8)) & mask); - } + out.extend_from_slice(row.get(..keep).unwrap_or(row)); } return Ok(DecodingResult::U8(out)); } From 86cd04f182d4f468b4f973055846470889f339c4 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 03:50:36 -0600 Subject: [PATCH 05/11] fix(data): sub-byte samples signed in any sample are refused, and sized unpacked A SampleFormat given for each sample is read whole, so a signed one is refused there too. A chunk of samples below 8 bits is sized at a byte a sample, as it is unpacked, before the bands are set aside. --- crates/data/src/raster/geotiff.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 7d63e4620f..9a55c5c6f7 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -782,7 +782,8 @@ fn unpack_bits( return Ok(buf); } // The decoder gives signed ones packed in `I8`s: refused, not read as either. - if dec.find_tag_unsigned::(Tag::SampleFormat).ok().flatten() == Some(2) { + let formats = dec.find_tag_unsigned_vec::(Tag::SampleFormat).ok().flatten().unwrap_or_default(); + if formats.contains(&2) { return Err(err(format!("signed samples of {bits} bits aren't supported"))); } let DecodingResult::U8(packed) = buf else { return Ok(buf) }; @@ -1417,7 +1418,8 @@ fn decimate( // tile's padding; LZW ones to the tiff crate, then to our reader, which keeps the padding too; // the rest to the tiff crate only, which holds a chunk cropped to the image. let sample_bits = bits(dec); - let (cropped, padded) = chunks.first_bytes(sample_bits); + // Samples of fewer than 8 bits are unpacked to a byte each: sized as such. + let (cropped, padded) = chunks.first_bytes(if matches!(sample_bits, 1 | 2 | 4) { 8 } else { sample_bits }); // The LZW reader takes 8- to 64-bit samples only. let lzw_reads = lzw(dec) && matches!(sample_bits, 8 | 16 | 32 | 64); let refused = if super::lerc::is_lerc(dec) { @@ -5290,6 +5292,18 @@ mod tests { } } } + // Signed, said for each sample (ExtraSamples' entry made a SampleFormat of [2, 2]): refused. + let mut signed = planar_tiled(40, 24, (16, 16), 4, |_, _, _| 0); + let at32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize; + let ifd = at32(&signed, 4); + for e in (0..u16::from_le_bytes([signed[ifd], signed[ifd + 1]]) as usize).map(|i| ifd + 2 + 12 * i) { + if signed[e..e + 2] == 338u16.to_le_bytes() { + signed[e..e + 2].copy_from_slice(&339u16.to_le_bytes()); + signed[e + 8..e + 12].copy_from_slice(&[2, 0, 2, 0]); + } + } + let e = read(std::io::Cursor::new(&signed), "signed").unwrap_err(); + assert!(e.to_string().contains("signed samples of 4 bits"), "{e}"); } #[test] From fb1b7c4010fe1f1089c2a9c734e94d59353b0ce3 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 04:31:27 -0600 Subject: [PATCH 06/11] fix(data): signed sub-byte samples are refused before a read, a missing BitsPerSample is 1 A sparse file may finish its read without decoding a chunk, so the signed refusal runs before it too. A missing BitsPerSample is the TIFF default of 1 everywhere, as the decoder reads it, and the size check before a read counts the LZW reader's sub-byte chunks. --- crates/data/src/raster/geotiff.rs | 39 ++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 9a55c5c6f7..8045cf1c9e 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -775,17 +775,11 @@ fn unpack_bits( buf: DecodingResult, row: impl FnOnce(&mut Decoder) -> usize, ) -> Result { - // A missing BitsPerSample is 1, the TIFF default. - let bits = dec.find_tag_unsigned_vec::(Tag::BitsPerSample).ok().flatten().and_then(|v| v.into_iter().max()).unwrap_or(1); - let bits = usize::from(bits); + let bits = usize::from(bits(dec)); if !matches!(bits, 1 | 2 | 4) { return Ok(buf); } - // The decoder gives signed ones packed in `I8`s: refused, not read as either. - let formats = dec.find_tag_unsigned_vec::(Tag::SampleFormat).ok().flatten().unwrap_or_default(); - if formats.contains(&2) { - return Err(err(format!("signed samples of {bits} bits aren't supported"))); - } + refuse_signed_sub_byte(dec)?; let DecodingResult::U8(packed) = buf else { return Ok(buf) }; // Packed samples taken a byte each would be wrong values, not some. let row = row(dec); @@ -809,6 +803,18 @@ fn unpack_bits( Ok(DecodingResult::U8(out)) } +/// Signed samples of fewer than 8 bits, in any sample, refused: the decoder gives them packed in +/// `I8`s, which aren't read as either. Said before a read too, which a sparse file may finish +/// without decoding a chunk. +fn refuse_signed_sub_byte(dec: &mut Decoder) -> Result<()> { + let bits = bits(dec); + let formats = dec.find_tag_unsigned_vec::(Tag::SampleFormat).ok().flatten().unwrap_or_default(); + if matches!(bits, 1 | 2 | 4) && formats.contains(&2) { + return Err(err(format!("signed samples of {bits} bits aren't supported"))); + } + Ok(()) +} + /// Turns a JPEG-compressed image's three YCbCr bands into red, green and blue in place, with the /// JFIF (full-range) coefficients JPEG-in-TIFF files use. pub(super) fn ycbcr_to_rgb(bands: &mut [Vec]) { @@ -829,7 +835,8 @@ pub(super) fn is_ycbcr_jpeg(dec: &mut Decoder) -> bool { /// Bits per sample of the current image (the most of any sample). fn bits(dec: &mut Decoder) -> u16 { - dec.find_tag_unsigned_vec::(Tag::BitsPerSample).ok().flatten().and_then(|v| v.into_iter().max()).unwrap_or(8) + // A missing BitsPerSample is 1, the TIFF default, as the decoder reads it. + dec.find_tag_unsigned_vec::(Tag::BitsPerSample).ok().flatten().and_then(|v| v.into_iter().max()).unwrap_or(1) } /// Bytes per sample of the current image (from its bits per sample). @@ -1417,11 +1424,12 @@ fn decimate( // by fuzzing, #1952). LERC chunks go to its reader only, which holds 8 bytes a sample with a // tile's padding; LZW ones to the tiff crate, then to our reader, which keeps the padding too; // the rest to the tiff crate only, which holds a chunk cropped to the image. + refuse_signed_sub_byte(dec)?; let sample_bits = bits(dec); // Samples of fewer than 8 bits are unpacked to a byte each: sized as such. let (cropped, padded) = chunks.first_bytes(if matches!(sample_bits, 1 | 2 | 4) { 8 } else { sample_bits }); - // The LZW reader takes 8- to 64-bit samples only. - let lzw_reads = lzw(dec) && matches!(sample_bits, 8 | 16 | 32 | 64); + // The LZW reader takes 1- to 64-bit samples, those below 8 unpacked by `read_chunk`. + let lzw_reads = lzw(dec) && matches!(sample_bits, 1 | 2 | 4 | 8 | 16 | 32 | 64); let refused = if super::lerc::is_lerc(dec) { let lerc = chunks.first_bytes(64).1; (lerc > super::lerc::MAX_CHUNK_BYTES as u64).then_some(((chunks.cw, chunks.ch), lerc)) @@ -5304,6 +5312,15 @@ mod tests { } let e = read(std::io::Cursor::new(&signed), "signed").unwrap_err(); assert!(e.to_string().contains("signed samples of 4 bits"), "{e}"); + // Every tile left out, with none to decode: refused all the same. + for e in (0..u16::from_le_bytes([signed[ifd], signed[ifd + 1]]) as usize).map(|i| ifd + 2 + 12 * i) { + if [324u16, 325].contains(&u16::from_le_bytes([signed[e], signed[e + 1]])) { + let (n, table) = (at32(&signed, e + 4), at32(&signed, e + 8)); + signed[table..table + 4 * n].fill(0); + } + } + let e = read(std::io::Cursor::new(&signed), "sparse signed").unwrap_err(); + assert!(e.to_string().contains("signed samples of 4 bits"), "{e}"); } #[test] From b64efcd88b359e927e3e74f30ff456ac064e0029 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 05:36:18 -0600 Subject: [PATCH 07/11] fix(data): compressed sub-byte samples with a FillOrder of 2 are refused, not misread A FillOrder of 2 reverses a compressed chunk's bytes, which the decoders don't undo; only uncompressed samples are read lowest bit first. Sub-byte samples in a type other than bytes are an error, a COG's missing BitsPerSample is 1 as the whole-file reader's is, and unpack_bits says it is one step without a Cancel check. --- crates/data/src/raster/cog.rs | 3 +- crates/data/src/raster/geotiff.rs | 57 ++++++++++++++++++++----------- 2 files changed, 40 insertions(+), 20 deletions(-) diff --git a/crates/data/src/raster/cog.rs b/crates/data/src/raster/cog.rs index e06c7e1db0..bb036375c1 100644 --- a/crates/data/src/raster/cog.rs +++ b/crates/data/src/raster/cog.rs @@ -396,7 +396,8 @@ fn read_layout(r: Sparse) -> Result { // Bands stored apart: each band of a tile is a chunk of its own. let planar = dec.find_tag_unsigned::(Tag::PlanarConfiguration).ok().flatten() == Some(2) && bands > 1; let (planes, per_chunk) = if planar { (bands, 1) } else { (1, bands) }; - let bits = dec.find_tag_unsigned_vec::(Tag::BitsPerSample).ok().flatten().and_then(|v| v.first().copied()).unwrap_or(8); + // A missing BitsPerSample is 1, the TIFF default, as the decoder reads it. + let bits = dec.find_tag_unsigned_vec::(Tag::BitsPerSample).ok().flatten().and_then(|v| v.first().copied()).unwrap_or(1); // One value a band (the first stands for all). let format = dec.find_tag_unsigned_vec::(Tag::SampleFormat).ok().flatten().and_then(|v| v.first().copied()).unwrap_or(1); let data_type = match (format, bits) { diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 8045cf1c9e..b5365b1582 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -769,7 +769,9 @@ fn samples_in_chunk(dec: &mut Decoder) -> usize { /// Samples of fewer than 8 bits (1, 2 or 4), packed several to a byte in rows of `row` samples that /// each start on a byte, as the decoder gives them: each in a byte of its own. Others are as they -/// are. A FillOrder of 2 (the first sample in a byte's lowest bits) is read as such. +/// are. A FillOrder of 2 (the first sample in a byte's lowest bits) is read as such. One step that +/// doesn't look at Cancel: a chunk's, whose caller looks between chunks, or a whole image's, of a +/// file small enough to be read whole. fn unpack_bits( dec: &mut Decoder, buf: DecodingResult, @@ -779,14 +781,17 @@ fn unpack_bits( if !matches!(bits, 1 | 2 | 4) { return Ok(buf); } - refuse_signed_sub_byte(dec)?; - let DecodingResult::U8(packed) = buf else { return Ok(buf) }; + refuse_sub_byte(dec)?; + let DecodingResult::U8(packed) = buf else { + return Err(err(format!("{bits}-bit samples came in a type this reader doesn't unpack"))); + }; // Packed samples taken a byte each would be wrong values, not some. let row = row(dec); if row == 0 { return Err(err("a strip or tile's width can't be read")); } - let lsb_first = dec.find_tag_unsigned::(Tag::FillOrder).ok().flatten() == Some(2); + // Only uncompressed samples come here with a FillOrder of 2 (see [`refuse_sub_byte`]). + let lsb_first = fill_order_2(dec); let row_bytes = row.checked_mul(bits).map(|b| b.div_ceil(8)).ok_or_else(|| err("a strip or tile is too large to read"))?; let rows = packed.len() / row_bytes; let n = rows.checked_mul(row).filter(|n| *n <= decoding_limit()).ok_or_else(|| err("a strip or tile is too large to read"))?; @@ -803,18 +808,30 @@ fn unpack_bits( Ok(DecodingResult::U8(out)) } -/// Signed samples of fewer than 8 bits, in any sample, refused: the decoder gives them packed in -/// `I8`s, which aren't read as either. Said before a read too, which a sparse file may finish -/// without decoding a chunk. -fn refuse_signed_sub_byte(dec: &mut Decoder) -> Result<()> { +/// Samples of fewer than 8 bits [`unpack_bits`] can't read, refused: signed ones, in any sample +/// (the decoder gives them packed in `I8`s, which aren't read as either), and compressed ones with +/// a FillOrder of 2, whose compressed bytes are reversed, which the decoders don't undo (GDAL +/// reads them). Said before a read too, which a sparse file may finish without decoding a chunk. +fn refuse_sub_byte(dec: &mut Decoder) -> Result<()> { let bits = bits(dec); + if !matches!(bits, 1 | 2 | 4) { + return Ok(()); + } let formats = dec.find_tag_unsigned_vec::(Tag::SampleFormat).ok().flatten().unwrap_or_default(); - if matches!(bits, 1 | 2 | 4) && formats.contains(&2) { + if formats.contains(&2) { return Err(err(format!("signed samples of {bits} bits aren't supported"))); } + if fill_order_2(dec) && dec.find_tag_unsigned::(Tag::Compression).ok().flatten().unwrap_or(1) != 1 { + return Err(err(format!("compressed {bits}-bit samples with a FillOrder of 2 aren't supported"))); + } Ok(()) } +/// Whether the current image's bits are in a byte lowest first (a FillOrder of 2). +fn fill_order_2(dec: &mut Decoder) -> bool { + dec.find_tag_unsigned::(Tag::FillOrder).ok().flatten() == Some(2) +} + /// Turns a JPEG-compressed image's three YCbCr bands into red, green and blue in place, with the /// JFIF (full-range) coefficients JPEG-in-TIFF files use. pub(super) fn ycbcr_to_rgb(bands: &mut [Vec]) { @@ -1424,7 +1441,7 @@ fn decimate( // by fuzzing, #1952). LERC chunks go to its reader only, which holds 8 bytes a sample with a // tile's padding; LZW ones to the tiff crate, then to our reader, which keeps the padding too; // the rest to the tiff crate only, which holds a chunk cropped to the image. - refuse_signed_sub_byte(dec)?; + refuse_sub_byte(dec)?; let sample_bits = bits(dec); // Samples of fewer than 8 bits are unpacked to a byte each: sized as such. let (cropped, padded) = chunks.first_bytes(if matches!(sample_bits, 1 | 2 | 4) { 8 } else { sample_bits }); @@ -2085,6 +2102,7 @@ fn read_image( // A sparse file's chunks aren't there to decode: the decoder fails on them, or reads another // part of the file. Read a chunk at a time, they are no-data (#2761), as they are in place. let by_chunk = decimate_by > 1 || extra_samples || planar_tiles || chunked || lerc || span.is_some(); + refuse_sub_byte(&mut dec)?; let (chunk_count, absent) = super::lerc::Table::default().chunks(&mut dec); let sparse = !by_chunk && absent > 0; let whole = if by_chunk || sparse { @@ -5265,15 +5283,16 @@ mod tests { let DecodingResult::U8(edge) = chunk else { panic!("not bytes") }; assert_eq!((edge.len(), edge[0], edge[4]), (5 * 16, pixel(32, 0), pixel(36, 0)), "{bits} bits, the right edge tile"); // LZW, by our decoder (which the decoder's failures fall back to) as by the crate's. - for lsb_first in [false, true] { - let packed = packed_tiff(37, 21, bits, (1, Some(16)), lsb_first, true, pixel); - let mut dec = Decoder::new(reader(std::io::Cursor::new(&packed)).unwrap()).unwrap(); - let packed_chunk = super::super::lzw::chunk(&mut dec, 2).unwrap(); - let DecodingResult::U8(ours) = unpack_bits(&mut dec, packed_chunk, |_| 5).unwrap() else { panic!("not bytes") }; - assert_eq!(ours, edge, "{bits} bits, lsb first {lsb_first}"); - let r = read(std::io::Cursor::new(&packed), "lzw").unwrap(); - assert_eq!(r.value(0, 36, 20), Some(f32::from(pixel(36, 20))), "{bits} bits, lsb first {lsb_first}"); - } + let packed = packed_tiff(37, 21, bits, (1, Some(16)), false, true, pixel); + let mut dec = Decoder::new(reader(std::io::Cursor::new(&packed)).unwrap()).unwrap(); + let packed_chunk = super::super::lzw::chunk(&mut dec, 2).unwrap(); + let DecodingResult::U8(ours) = unpack_bits(&mut dec, packed_chunk, |_| 5).unwrap() else { panic!("not bytes") }; + assert_eq!(ours, edge, "{bits} bits"); + let r = read(std::io::Cursor::new(&packed), "lzw").unwrap(); + assert_eq!(r.value(0, 36, 20), Some(f32::from(pixel(36, 20))), "{bits} bits"); + // Compressed with a FillOrder of 2: refused, not read with its compressed bytes reversed. + let e = read(std::io::Cursor::new(&packed_tiff(37, 21, bits, (1, Some(16)), true, true, pixel)), "lsb").unwrap_err(); + assert!(e.to_string().contains("FillOrder of 2"), "{bits} bits: {e}"); } } From 220c88e47e81fa0818b5c9ead15e53f756cc5adb Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 06:26:18 -0600 Subject: [PATCH 08/11] fix(data): sub-byte samples a reader can't unpack are refused before a chunk is decoded Floating-point samples of 1, 2 or 4 bits are refused, as signed ones are, and read_chunk refuses all of them before decoding, so a tile read in place says why. A GeoTIFF without BitsPerSample is read as 1 bit, whole and a tile at a time, and refused signed. --- crates/data/src/raster/geotiff.rs | 51 +++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index b5365b1582..399bdf7694 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -740,6 +740,8 @@ pub(crate) fn read_chunk( let c = super::lerc::chunk(dec, index, table)?; return Ok((c.samples, c.gaps)); } + // Refused before decoding, which may fail first with a less telling error (read in place). + refuse_sub_byte(dec)?; let v = match dec.read_chunk(index) { Ok(v) => v, Err(e) if lzw(dec) => super::lzw::chunk(dec, index).map_err(|l| err(format!("{e}; {l}")))?, @@ -809,7 +811,8 @@ fn unpack_bits( } /// Samples of fewer than 8 bits [`unpack_bits`] can't read, refused: signed ones, in any sample -/// (the decoder gives them packed in `I8`s, which aren't read as either), and compressed ones with +/// (the decoder gives them packed in `I8`s, which aren't read as either), floating-point ones +/// (which no float of so few bits is), and compressed ones with /// a FillOrder of 2, whose compressed bytes are reversed, which the decoders don't undo (GDAL /// reads them). Said before a read too, which a sparse file may finish without decoding a chunk. fn refuse_sub_byte(dec: &mut Decoder) -> Result<()> { @@ -821,6 +824,9 @@ fn refuse_sub_byte(dec: &mut Decoder) -> Result<()> { if formats.contains(&2) { return Err(err(format!("signed samples of {bits} bits aren't supported"))); } + if formats.contains(&3) { + return Err(err(format!("floating-point samples of {bits} bits aren't supported"))); + } if fill_order_2(dec) && dec.find_tag_unsigned::(Tag::Compression).ok().flatten().unwrap_or(1) != 1 { return Err(err(format!("compressed {bits}-bit samples with a FillOrder of 2 aren't supported"))); } @@ -5264,6 +5270,40 @@ mod tests { } let e = read(std::io::Cursor::new(&signed), "signed").unwrap_err(); assert!(e.to_string().contains(&format!("signed samples of {bits} bits")), "{bits} bits: {e}"); + // Floating-point ones too, LZW-compressed as well. + for lzw in [false, true] { + let mut float = packed_tiff(37, 21, bits, (5, None), false, lzw, pixel); + let ifd = u32::from_le_bytes(float[4..8].try_into().unwrap()) as usize; + for e in (0..u16::from_le_bytes([float[ifd], float[ifd + 1]]) as usize).map(|i| ifd + 2 + 12 * i) { + if float[e..e + 2] == 266u16.to_le_bytes() { + float[e..e + 2].copy_from_slice(&339u16.to_le_bytes()); + float[e + 8..e + 10].copy_from_slice(&3u16.to_le_bytes()); + } + } + let e = read(std::io::Cursor::new(&float), "float").unwrap_err(); + assert!(e.to_string().contains(&format!("floating-point samples of {bits} bits")), "{bits} bits, LZW {lzw}: {e}"); + } + // Without BitsPerSample, a sample is 1 bit, the TIFF default the decoder reads too: read + // as such whole and a tile at a time, and refused signed. + if bits == 1 { + let untagged = |b: &[u8]| { + let mut b = b.to_vec(); + let ifd = u32::from_le_bytes(b[4..8].try_into().unwrap()) as usize; + let n = u16::from_le_bytes([b[ifd], b[ifd + 1]]) as usize; + let e = (0..n).map(|i| ifd + 2 + 12 * i).find(|e| b[*e..*e + 2] == 258u16.to_le_bytes()).unwrap(); + b.copy_within(e + 12..ifd + 2 + 12 * n + 4, e); + b[ifd..ifd + 2].copy_from_slice(&((n - 1) as u16).to_le_bytes()); + b + }; + for layout in [(5, None), (1, Some(16))] { + let r = read(std::io::Cursor::new(untagged(&packed_tiff(37, 21, 1, layout, false, false, pixel))), "untagged").unwrap(); + for (x, y) in [(0, 0), (1, 0), (36, 20), (17, 11)] { + assert_eq!(r.value(0, i64::from(x), i64::from(y)), Some(f32::from(pixel(x, y))), "{layout:?}: {x}, {y}"); + } + } + let e = read(std::io::Cursor::new(untagged(&signed)), "untagged signed").unwrap_err(); + assert!(e.to_string().contains("signed samples of 1 bits"), "{e}"); + } // A sparse file opens, its missing strip read as an 8-bit file's is. let mut holes = packed_tiff(37, 21, bits, (5, None), false, false, pixel); let at32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize; @@ -5290,9 +5330,14 @@ mod tests { assert_eq!(ours, edge, "{bits} bits"); let r = read(std::io::Cursor::new(&packed), "lzw").unwrap(); assert_eq!(r.value(0, 36, 20), Some(f32::from(pixel(36, 20))), "{bits} bits"); - // Compressed with a FillOrder of 2: refused, not read with its compressed bytes reversed. - let e = read(std::io::Cursor::new(&packed_tiff(37, 21, bits, (1, Some(16)), true, true, pixel)), "lsb").unwrap_err(); + // Compressed with a FillOrder of 2: refused, not read with its compressed bytes reversed, + // whole and a tile at a time (as in place). + let lsb = packed_tiff(37, 21, bits, (1, Some(16)), true, true, pixel); + let e = read(std::io::Cursor::new(&lsb), "lsb").unwrap_err(); assert!(e.to_string().contains("FillOrder of 2"), "{bits} bits: {e}"); + let mut dec = Decoder::new(reader(std::io::Cursor::new(&lsb)).unwrap()).unwrap(); + let e = read_chunk(&mut dec, 2, &mut super::super::lerc::Table::default()).unwrap_err(); + assert!(e.to_string().contains("FillOrder of 2"), "{bits} bits, a tile: {e}"); } } From 6c307334353f5a312d5f7831e212a5b4be26cba1 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 07:17:48 -0600 Subject: [PATCH 09/11] fix(data): a sub-byte image's unreadable SampleFormat is an error, not unsigned Comments on the LZW reader's chunk size and its module say that it keeps only the image's columns below 8 bits, for read_chunk to unpack. --- crates/data/src/raster/geotiff.rs | 9 ++++++--- crates/data/src/raster/lzw.rs | 3 ++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index d4064c1feb..7ff7bc1fd0 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -820,7 +820,8 @@ fn refuse_sub_byte(dec: &mut Decoder) -> Result<()> { if !matches!(bits, 1 | 2 | 4) { return Ok(()); } - let formats = dec.find_tag_unsigned_vec::(Tag::SampleFormat).ok().flatten().unwrap_or_default(); + // A SampleFormat that can't be read is an error, not unsigned: it may say signed. + let formats = dec.find_tag_unsigned_vec::(Tag::SampleFormat).map_err(err)?.unwrap_or_default(); if formats.contains(&2) { return Err(err(format!("signed samples of {bits} bits aren't supported"))); } @@ -1228,7 +1229,8 @@ impl Chunks { /// The bytes the first chunk decodes to at `bits` a sample, each row padded to whole bytes: as /// the tiff crate holds it, cropped to the image, then with a tile's padding, as the LZW and - /// LERC readers hold it. The first chunk is the largest (only the last strip and the edge tiles are + /// LERC readers hold it (the LZW reader keeps only the image's columns below 8 bits a sample, + /// so for those the second is an upper bound). The first chunk is the largest (only the last strip and the edge tiles are /// smaller), and one always read, since it holds the image's first pixel. fn first_bytes(&self, bits: u16) -> (u64, u64) { let size = |cols: u32, rows: u32| { @@ -1487,7 +1489,8 @@ fn decimate( // A chunk larger than its decoder takes can't be read: said before the bands are set aside, // which can be gigabytes for a header claiming a vast image (a few hundred bytes of file, found // by fuzzing, #1952). LERC chunks go to its reader only, which holds 8 bytes a sample with a - // tile's padding; LZW ones to the tiff crate, then to our reader, which keeps the padding too; + // tile's padding; LZW ones to the tiff crate, then to our reader, which keeps the padding too + // (below 8 bits it keeps the image's columns only, so this is an upper bound for those); // the rest to the tiff crate only, which holds a chunk cropped to the image. refuse_sub_byte(dec)?; let sample_bits = bits(dec); diff --git a/crates/data/src/raster/lzw.rs b/crates/data/src/raster/lzw.rs index cef80c0f3f..7a244e8101 100644 --- a/crates/data/src/raster/lzw.rs +++ b/crates/data/src/raster/lzw.rs @@ -4,7 +4,8 @@ //! the input already used up ("no lzw end code found", issue #350). That depends on the data: //! about one tile in forty of an elevation model, none in another. GDAL reads such files without a //! complaint. A chunk the crate fails on is decoded whole here: LZW, then the byte order and the -//! predictor, as the crate would have. +//! predictor, as the crate would have. Samples of fewer than 8 bits come back packed, each row cut +//! to the image's columns, for `geotiff::read_chunk` to unpack. use std::io::{Read, Seek, SeekFrom}; From 6f7511b5ac3182ad9b939732c5b01ca249dbc456 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 07:25:03 -0600 Subject: [PATCH 10/11] fix(data): sub-byte LZW chunks are sized before a read, and a sub-byte alpha band is refused LZW chunks below 8 bits are held to the decoding limit before the bands are set aside, as other codecs' are, so unpack_bits no longer asks for the limit chunk by chunk. An alpha band of 1, 2 or 4 bits is refused rather than read as opacity out of 255. --- crates/data/src/raster/geotiff.rs | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 7ff7bc1fd0..57b9f49e18 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -796,7 +796,9 @@ fn unpack_bits( let lsb_first = fill_order_2(dec); let row_bytes = row.checked_mul(bits).map(|b| b.div_ceil(8)).ok_or_else(|| err("a strip or tile is too large to read"))?; let rows = packed.len() / row_bytes; - let n = rows.checked_mul(row).filter(|n| *n <= decoding_limit()).ok_or_else(|| err("a strip or tile is too large to read"))?; + // Every caller sizes such a chunk at a byte a sample or more before reading it (`decimate`'s + // check, the in-place reader's tile budget), so no limit is asked for here, chunk by chunk. + let n = rows.checked_mul(row).ok_or_else(|| err("a strip or tile is too large to read"))?; let mut out = Vec::new(); out.try_reserve_exact(n).map_err(|_| err("a strip or tile is too large to read"))?; let mask = (1u8 << bits) - 1; @@ -812,7 +814,8 @@ fn unpack_bits( /// Samples of fewer than 8 bits [`unpack_bits`] can't read, refused: signed ones, in any sample /// (the decoder gives them packed in `I8`s, which aren't read as either), floating-point ones -/// (which no float of so few bits is), and compressed ones with +/// (which no float of so few bits is), those with an alpha band (whose opacity would be read out +/// of 255, not of the samples' own range), and compressed ones with /// a FillOrder of 2, whose compressed bytes are reversed, which the decoders don't undo (GDAL /// reads them). Said before a read too, which a sparse file may finish without decoding a chunk. fn refuse_sub_byte(dec: &mut Decoder) -> Result<()> { @@ -828,6 +831,10 @@ fn refuse_sub_byte(dec: &mut Decoder) -> Result<()> { if formats.contains(&3) { return Err(err(format!("floating-point samples of {bits} bits aren't supported"))); } + let extra = dec.find_tag_unsigned_vec::(Tag::ExtraSamples).map_err(err)?.unwrap_or_default(); + if extra.iter().any(|e| matches!(e, 1 | 2)) { + return Err(err(format!("an alpha band of {bits} bits isn't supported"))); + } if fill_order_2(dec) && dec.find_tag_unsigned::(Tag::Compression).ok().flatten().unwrap_or(1) != 1 { return Err(err(format!("compressed {bits}-bit samples with a FillOrder of 2 aren't supported"))); } @@ -1496,8 +1503,9 @@ fn decimate( let sample_bits = bits(dec); // Samples of fewer than 8 bits are unpacked to a byte each: sized as such. let (cropped, padded) = chunks.first_bytes(if matches!(sample_bits, 1 | 2 | 4) { 8 } else { sample_bits }); - // The LZW reader takes 1- to 64-bit samples, those below 8 unpacked by `read_chunk`. - let lzw_reads = lzw(dec) && matches!(sample_bits, 1 | 2 | 4 | 8 | 16 | 32 | 64); + // The LZW reader's own allowance covers samples held as read; those below 8 bits are unpacked + // to a byte each, so they are held to the decoding limit as other codecs' are. + let lzw_reads = lzw(dec) && matches!(sample_bits, 8 | 16 | 32 | 64); let refused = if super::lerc::is_lerc(dec) { let lerc = chunks.first_bytes(64).1; (lerc > super::lerc::MAX_CHUNK_BYTES as u64).then_some(((chunks.cw, chunks.ch), lerc)) @@ -5432,6 +5440,16 @@ mod tests { } let e = read(std::io::Cursor::new(&signed), "signed").unwrap_err(); assert!(e.to_string().contains("signed samples of 4 bits"), "{e}"); + // With an alpha band: refused, not read as opacity out of 255. + let mut alpha = planar_tiled(40, 24, (16, 16), 4, |_, _, _| 0); + let ifd = at32(&alpha, 4); + for e in (0..u16::from_le_bytes([alpha[ifd], alpha[ifd + 1]]) as usize).map(|i| ifd + 2 + 12 * i) { + if alpha[e..e + 2] == 338u16.to_le_bytes() { + alpha[e + 8..e + 10].copy_from_slice(&2u16.to_le_bytes()); + } + } + let e = read(std::io::Cursor::new(&alpha), "alpha").unwrap_err(); + assert!(e.to_string().contains("alpha band of 4 bits"), "{e}"); // Every tile left out, with none to decode: refused all the same. for e in (0..u16::from_le_bytes([signed[ifd], signed[ifd + 1]]) as usize).map(|i| ifd + 2 + 12 * i) { if [324u16, 325].contains(&u16::from_le_bytes([signed[e], signed[e + 1]])) { From 42697e23be6eee90044c16b5c7b717c5b6e3e838 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 08:15:36 -0600 Subject: [PATCH 11/11] fix(data): a sub-byte image's unreadable FillOrder or Compression is an error, not its default --- crates/data/src/raster/geotiff.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 57b9f49e18..6bd8e258bb 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -835,7 +835,10 @@ fn refuse_sub_byte(dec: &mut Decoder) -> Result<()> { if extra.iter().any(|e| matches!(e, 1 | 2)) { return Err(err(format!("an alpha band of {bits} bits isn't supported"))); } - if fill_order_2(dec) && dec.find_tag_unsigned::(Tag::Compression).ok().flatten().unwrap_or(1) != 1 { + // Tags that can't be read are errors here, not their defaults: they may say otherwise. + let fill_order = dec.find_tag_unsigned::(Tag::FillOrder).map_err(err)?; + let compression = dec.find_tag_unsigned::(Tag::Compression).map_err(err)?.unwrap_or(1); + if fill_order == Some(2) && compression != 1 { return Err(err(format!("compressed {bits}-bit samples with a FillOrder of 2 aren't supported"))); } Ok(())