diff --git a/crates/data/src/raster/cog.rs b/crates/data/src/raster/cog.rs index f21d48b788..ecec29aed3 100644 --- a/crates/data/src/raster/cog.rs +++ b/crates/data/src/raster/cog.rs @@ -395,7 +395,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 c0d74a01dd..6bd8e258bb 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -740,11 +740,113 @@ 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) => Ok((v, None)), - Err(e) if lzw(dec) => super::lzw::chunk(dec, index).map(|v| (v, None)).map_err(|_| err(e)), - Err(e) => Err(err(e)), + // 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}")))?, + 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, +/// 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. 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, + row: impl FnOnce(&mut Decoder) -> usize, +) -> Result { + let bits = usize::from(bits(dec)); + if !matches!(bits, 1 | 2 | 4) { + 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")); + } + // 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; + // 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; + 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)) +} + +/// 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), 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<()> { + let bits = bits(dec); + if !matches!(bits, 1 | 2 | 4) { + return Ok(()); + } + // 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"))); + } + 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"))); + } + // 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(()) +} + +/// 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 @@ -772,7 +874,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). @@ -1136,7 +1239,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| { @@ -1395,11 +1499,15 @@ 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); - let (cropped, padded) = chunks.first_bytes(sample_bits); - // The LZW reader takes 8- to 64-bit samples only. + // 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'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; @@ -2050,22 +2158,15 @@ 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")); - } - // 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; + // 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; // 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); @@ -2073,11 +2174,9 @@ fn read_image( // part of the file. Read a chunk at a time, they hold the file's no-data value, or 0, as they // do in place and as GDAL reads them. let by_chunk = decimate_by > 1 || extra_samples || planar_tiles || chunked || lerc || span.is_some(); + refuse_sub_byte(&mut dec)?; let (_, 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 { @@ -2086,7 +2185,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)), } }; @@ -2103,6 +2202,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")); @@ -5015,22 +5117,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])), @@ -5041,6 +5157,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; @@ -5091,17 +5211,257 @@ 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}"); + } + } + // 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}"); + // 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 0 as an 8-bit file's is (#2761). + 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))), Some(0.0)), "{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(); + 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. + 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, + // 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}"); + } + } + #[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})" + ); + } + } + } + } + } + // 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}"); + // 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]])) { + 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] diff --git a/crates/data/src/raster/lzw.rs b/crates/data/src/raster/lzw.rs index b5cda20bd7..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}; @@ -36,7 +37,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 +54,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 +85,21 @@ 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, 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"))); + } + 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(keep.saturating_mul(dh)).map_err(|_| err("a chunk is too large"))?; + for row in decoded.chunks(row_bytes).take(dh) { + out.extend_from_slice(row.get(..keep).unwrap_or(row)); + } + 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)?;