Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 10 additions & 16 deletions crates/data/src/raster/cog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,12 +270,11 @@ impl Layout {
}
}

/// What to say of the tiles or strips level `level` leaves out, when the file gives no no-data
/// value; kept apart from `lost`, as they are read alike in place and whole.
pub fn absent_said(&self, level: usize) -> Option<String> {
let l = self.levels.get(level).filter(|_| self.nodata.is_none())?;
let absent = l.offsets.iter().zip(&l.counts).filter(|chunk| *chunk == (&0, &0)).count();
(absent > 0).then(|| super::geotiff::absent_note(absent, l.offsets.len()))
/// What a tile or strip the file leaves out holds (a sparse file's: no offset, no bytes): its
/// no-data value, as decoded (NaN), or 0 where it gives none. GDAL writes a sparse file without
/// the blocks whose cells are all that value, and reads them back as it.
pub fn absent_value(&self) -> f32 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The notice is gone, and the reader now fills values the file doesn't store, with nothing said. Before, a sparse file with no no-data value was reported ("N of its M tiles or strips aren't in the file ... they are read as no data"). Now those tiles hold 0 and no notice is given. The PR says this is GDAL's behaviour and that "nothing is assumed", but AGENTS.md (Never silent) asks for a notice wherever a reader fills in values it does not have, with a count and a place. The tests only check the clean side (r.lost.is_empty()). Suggested: keep one notice per file with the count of left-out tiles or strips, and phrase it as "read as 0 (GDAL's sparse-file convention)" rather than "assumed". Test both ways, as the rule asks. If the maintainers decide GDAL parity is enough, the PR should say so under "Suggested AGENTS.md additions".

Category: agents-md

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's GDAL's rule rather than an assumption: GDAL writes a sparse file without the blocks that are all the no-data value, or all 0 where there is none, and reads them back as that (its GeoTIFF driver page, Sparse files). So the value read is what was written, and there's nothing to say. A file with a no-data value, from its tag or its sidecar, reads it as no data.

if self.nodata.is_some() { f32::NAN } else { 0.0 }
}

/// How many bands one chunk (a tile's bytes) holds: one when they are stored apart.
Expand Down Expand Up @@ -1163,20 +1162,15 @@ pub fn example_with(e: &Example) -> Vec<u8> {
pub(crate) mod tests {
use super::*;

/// What a sparse file leaves out is said level by level, and only without a no-data value.
/// What a sparse file leaves out is 0, or no data where the file has a no-data value.
#[test]
fn the_chunks_left_out_are_said_by_level() {
fn a_left_out_tile_is_0_or_no_data() {
let file = example_with(&Example { size: 256, tile: 64, sparse: true, ..Example::default() });
let Ok(Parse::Done(mut l)) = layout(&Sparse::default().with(0, file)) else { panic!("not a COG") };
assert!(l.absent_said(0).is_some_and(|s| s.starts_with("1 of its 16 tiles")), "{:?}", l.absent_said(0));
assert_eq!((l.absent_said(1), l.absent_said(9)), (None, None));
// An overview with a hole under a whole full image.
l.levels.swap(0, 1);
assert_eq!((l.absent_said(0), l.absent_said(1).is_some()), (None, true));
l.nodata = Some(0.0);
assert_eq!(l.absent_said(1), None);
assert_eq!(l.absent_value(), 0.0);
l.nodata = Some(7.0);
assert!(l.absent_value().is_nan());
}

/// ESA CCI Biomass's 1 km map (#2496): 18 bands interleaved in 512-pixel tiles, 4.7 million values
/// a tile, open; a tile past the limit says what it takes, the limit and what to do.
#[test]
Expand Down
172 changes: 136 additions & 36 deletions crates/data/src/raster/geotiff.rs

Large diffs are not rendered by default.

54 changes: 37 additions & 17 deletions crates/data/src/raster/lerc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,20 +60,38 @@ impl Table {
}

/// Whether the file leaves chunk `index` of the decoder's current image out (a sparse file's:
/// it has neither an offset nor bytes): all no-data, whatever the compression. A count of 0
/// alone doesn't say so: some writers leave the counts of uncompressed chunks out.
/// it has neither an offset nor bytes). A count of 0 alone says so of a compressed chunk, which
/// can't be decoded from nothing, but not of an uncompressed one: some writers leave the
/// counts of uncompressed chunks out.
pub(crate) fn absent<R: Read + Seek>(&mut self, dec: &mut Decoder<R>, index: u32) -> bool {
let tiled = dec.find_tag(Tag::TileWidth).ok().flatten().is_some();
matches!(self.get(dec, tiled, index), Ok((0, 0)))
let compressed = compressed(dec);
matches!(self.get(dec, tiled, index), Ok((offset, 0)) if offset == 0 || compressed)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This rule isn't only for LERC. Table::absent and Table::chunks are used by every by-chunk TIFF read: the serial and parallel paths of decimate (geotiff.rs around lines 1416 and 1440/1518) and the sparse check in read_image (geotiff.rs:2076). So before this change, a chunk was left out only when both its offset and its byte count were 0. Now, for any compression other than none (LZW, deflate, and so on), a chunk with a byte count of 0 is left out whatever its offset is.

That matters because a damaged index is now treated the same as GDAL's sparse convention. A compressed chunk whose offset is set but whose count is 0 used to go to the decoder, which can't decode zero bytes, so the read failed. Now it fills silently with 0 or no data, with no notice. The reply that this PR "keeps each reader's rule" is about the in-place readers. It doesn't cover this whole-file change, and no test covers a compressed chunk with a nonzero offset and a count of 0 (the sparse() test helper zeroes both fields).

Two possible fixes: limit the offset-or-compressed clause to LERC, where the author argued for it, or keep the offset-0 requirement for other compressions. Or, if GDAL parity is the goal, say so in the PR and add a test that such a chunk reads as 0 or no data. I haven't checked how GDAL's libtiff handles count-0 chunks with an offset, so my confidence that this is wrong is medium.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked against GDAL: a chunk with no bytes and an offset reads as 0 there, compressed (Deflate) and uncompressed alike, so for compressed chunks the widened rule is GDAL's. Uncompressed ones keep needing a 0 offset too, as some writers leave their counts out. cc47fec adds the test: a JPEG strip with its offset kept and no bytes reads black, like one left out entirely.

}

/// How many chunks the decoder's current image has, and how many of them the file leaves out.
pub(crate) fn chunks<R: Read + Seek>(&mut self, dec: &mut Decoder<R>) -> (usize, usize) {
self.absent(dec, 0);
(self.offsets.len(), self.offsets.iter().zip(self.counts.iter()).filter(|chunk| *chunk == (&0, &0)).count())
let compressed = compressed(dec);
let left_out = |(offset, count): (&u64, &u64)| *count == 0 && (*offset == 0 || compressed);
(self.offsets.len(), self.offsets.iter().zip(self.counts.iter()).filter(|chunk| left_out(*chunk)).count())
}
}

/// Whether the current image's chunks are compressed (a Compression other than 1, none).
fn compressed<R: Read + Seek>(dec: &mut Decoder<R>) -> bool {
dec.find_tag_unsigned::<u16>(Tag::Compression).ok().flatten().unwrap_or(1) != 1
}

/// The no-data value the current image's GDAL_NODATA tag gives, if it gives a number.
pub(crate) fn nodata_tag<R: Read + Seek>(dec: &mut Decoder<R>) -> Option<f64> {
dec.find_tag(Tag::Unknown(42113))
.ok()
.flatten()
.and_then(|v| v.into_string().ok())
.and_then(|s| s.trim_matches(char::from(0)).trim().parse::<f64>().ok())
}

/// A decoded chunk: its samples, cropped to the image as `Decoder::read_chunk` returns them, and
/// which of them the chunk's validity masks mark invalid (`None` when none is).
pub(crate) struct Chunk {
Expand Down Expand Up @@ -112,12 +130,7 @@ pub(crate) fn chunk<R: Read + Seek>(dec: &mut Decoder<R>, index: u32, table: &mu
&& bps == 8
&& format == 1
&& dec.find_tag_unsigned_vec::<u16>(Tag::ExtraSamples).ok().flatten().and_then(|v| v.last().copied()) == Some(2);
let nodata = dec
.find_tag(Tag::Unknown(42113))
.ok()
.flatten()
.and_then(|v| v.into_string().ok())
.and_then(|s| s.trim_matches(char::from(0)).trim().parse::<f64>().ok());
let nodata = nodata_tag(dec);

// Where the chunk is in its plane, and how much of it is image.
let across = w.div_ceil(cw);
Expand All @@ -140,12 +153,14 @@ pub(crate) fn chunk<R: Read + Seek>(dec: &mut Decoder<R>, index: u32, table: &mu
let expected = data_type(format, bps)?;
let (offset, count) = table.get(dec, tiled, index)?;
if count == 0 {
// A chunk with no bytes (a sparse file's): all no-data, as GDAL reads it.
// A chunk with no bytes (a sparse file's): its no-data value, or 0 where it has none, as
// GDAL writes and reads one. With one, every sample is marked no data too: a value the
// samples' type can't hold (NaN in bytes) would be read as one.
let mut out = empty(format, bps, n)?;
for _ in 0..n {
push(&mut out, None, fill);
push(&mut out, None, nodata.unwrap_or(0.0));
}
return Ok(Chunk { samples: out, gaps: Some(vec![true; n]) });
return Ok(Chunk { samples: out, gaps: nodata.map(|_| vec![true; n]) });
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
let count = usize::try_from(count).ok().filter(|n| *n <= MAX_CHUNK_BYTES).ok_or_else(|| err("a chunk is too large"))?;
// Read as far as the file goes, not allocated from the claim.
Expand Down Expand Up @@ -626,7 +641,7 @@ mod tests {
}

#[test]
fn a_chunk_with_no_bytes_is_no_data() {
fn a_chunk_with_no_bytes_is_0_where_the_file_gives_no_no_data_value() {
// The first tile's byte count set to 0, as a sparse file has it.
let path = format!("{}/tests/data/lerc/lerc_zstd_f64.tif", env!("CARGO_MANIFEST_DIR"));
let mut b = std::fs::read(path).unwrap();
Expand All @@ -638,11 +653,16 @@ mod tests {
let size = if u16_at(&b, counts + 2) == 3 { 2 } else { 4 };
let first = u32_at(&b, counts + 8);
b[first..first + size].fill(0);
let r = geotiff::read(Cursor::new(b), "sparse").unwrap();
assert_eq!(r.value(0, 0, 0), None);
assert_eq!(r.value(0, 15, 15), None);
let r = geotiff::read(Cursor::new(b.clone()), "sparse").unwrap();
assert_eq!(r.nodata, None);
assert_eq!(r.value(0, 0, 0), Some(0.0));
assert_eq!(r.value(0, 15, 15), Some(0.0));
assert_eq!(r.value(0, 16, 0), Some(4.0), "the next tile reads");
assert_eq!(r.value(0, 0, 16), Some(-24.0));
// Its offset kept, the count of 0 says it is left out of a LERC file: it takes a sidecar's
// no-data value as one left out with no offset does.
let r = geotiff::read_with_nodata(Cursor::new(b), "sidecar", Some(-9999.0)).unwrap();
assert_eq!((r.value(0, 0, 0), r.value(0, 16, 0)), (Some(-9999.0), Some(4.0)));
}
}

Expand Down
4 changes: 2 additions & 2 deletions crates/data/src/raster/mask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,8 @@ pub(super) fn read<R: Read + Seek>(dec: &mut Decoder<R>, index: usize, step: u32
continue;
}
let (Some(&offset), Some(&count)) = (offsets.get(c), counts.get(c)) else { continue };
// One a sparse file leaves out is all 0: masked, as `out` starts (#2761).
if (offset, count) == (0, 0) {
// One with no bytes (a sparse file leaves it out) is all 0: masked, as `out` starts (#2761).
if count == 0 {
continue;
}
// A tile holds every row, padded; a strip only the image's.
Expand Down
36 changes: 29 additions & 7 deletions crates/data/src/raster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1570,15 +1570,13 @@ fn read_path_placing(path: &Path, world: bool) -> Result<Raster> {
// left out of the rounded count: it left out the sidecar's no-data for all bands. When the two
// differ (a record for a band the raster lacks, or one only some bands give), the file is read
// again with the one applied (none, when the bands it has give none), so the rounded count
// leaves out just its pixels. Only an ASCII grid, a GRIB file, or a GeoTIFF of a type `f32` can
// round, is read again.
// leaves out just its pixels, and a sparse GeoTIFF's missing chunks hold it (#2761). Only an
// ASCII grid, a GRIB file or a GeoTIFF is read again.
let applied = pam.as_ref().map(|p| p.nodata_within(r.bands.len()));
if let Some(nd) = applied
&& nd != sidecar_nodata
&& r.nodata.is_none()
&& (matches!(ext.as_str(), "asc" | "grb" | "grib" | "grb2" | "grib2")
|| (matches!(ext.as_str(), "tif" | "tiff")
&& matches!(r.data_type.as_str(), "UInt32" | "Int32" | "UInt64" | "Int64" | "Float64")))
&& matches!(ext.as_str(), "asc" | "grb" | "grib" | "grb2" | "grib2" | "tif" | "tiff")
{
// The second read gives all the first did: the first goes before it, so two aren't held.
drop(r);
Expand Down Expand Up @@ -1717,12 +1715,11 @@ pub fn read_path_part(path: &Path, part: Part, max: usize, same_as: Option<&Rast
let Some(mut read) = geotiff::read_file_part(path, &name, sidecar_nodata, part, max, same_as)? else { return Ok(None) };
let r = &mut read.raster;
// As [`read_path_placing`]: read again with the no-data the bands it has give, so the
// rounded count leaves out just its pixels.
// rounded count leaves out just its pixels and missing chunks hold it.
let applied = pam.as_ref().map(|p| p.nodata_within(r.bands.len()));
if let Some(nd) = applied
&& nd != sidecar_nodata
&& r.nodata.is_none()
&& matches!(r.data_type.as_str(), "UInt32" | "Int32" | "UInt64" | "Int64" | "Float64")
{
drop(read);
let Some(again) = geotiff::read_file_part(path, &name, nd, part, max, same_as)? else { return Ok(None) };
Expand Down Expand Up @@ -2686,6 +2683,31 @@ pub(crate) mod tests {
std::fs::write(dir.join("grid.aux.xml"), xml).unwrap();
let g = read_path(&asc).unwrap();
assert_eq!((g.bands[0].name.as_str(), g.nodata, g.value(0, 1, 0)), ("Elevation", Some(-1.0), Some(0.0)));
// A sparse file's missing strip holds the no-data value of the bands it has, though the
// sidecar gives another for a band it lacks (#2761).
let mut sparse = std::io::Cursor::new(Vec::new());
{
use tiff::encoder::{TiffEncoder, colortype};
let mut enc = TiffEncoder::new(&mut sparse).unwrap();
let mut img = enc.new_image::<colortype::Gray8>(4, 4).unwrap();
img.rows_per_strip(2).unwrap();
img.write_data(&[1u8; 16]).unwrap();
}
let mut b = sparse.into_inner();
let at32 = |b: &[u8], at: usize| u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]) as usize;
let ifd = at32(&b, 4);
for e in (0..u16::from_le_bytes([b[ifd], b[ifd + 1]]) as usize).map(|i| ifd + 2 + 12 * i) {
if [273u16, 279].contains(&u16::from_le_bytes([b[e], b[e + 1]])) {
let table = at32(&b, e + 8);
b[table + 4..table + 8].fill(0);
}
}
let holes = dir.join("holes.tif");
std::fs::write(&holes, b).unwrap();
let two = r#"<PAMDataset><PAMRasterBand band="1"><NoDataValue>7</NoDataValue></PAMRasterBand><PAMRasterBand band="2"><NoDataValue>9</NoDataValue></PAMRasterBand></PAMDataset>"#;
std::fs::write(dir.join("holes.tif.aux.xml"), two).unwrap();
let back = read_path(&holes).unwrap();
assert_eq!((back.nodata, back.value(0, 0, 0), back.value(0, 0, 3)), (Some(7.0), Some(1.0), None));
// A broken sidecar is ignored.
std::fs::write(dir.join("dem.tif.aux.xml"), "<PAMDataset><PAMRasterBand").unwrap();
assert_eq!(read_path(&tif).unwrap().bands[0].name, "Band 1");
Expand Down
1 change: 0 additions & 1 deletion crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7000,7 +7000,6 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic::
}
// What the header holds but isn't read (a colour table, names): said when the layer is added.
r.lost.extend(layout.lost.iter().cloned());
r.lost.extend(layout.absent_said(level));
r.lost.extend(palette_lost);
if let Some(described) = &layout.described {
r.apply_pam(described, rustgis_data::raster::pam::GDAL_METADATA);
Expand Down
9 changes: 4 additions & 5 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36266,7 +36266,7 @@ fn a_generalised_relief_read_in_place_has_no_step_at_the_views_edges() {
/// is whole at once and asks for nothing more, and an export of the view over it is written rather
/// than refused after waiting for the tile.
#[test]
fn a_tile_a_sparse_file_leaves_out_is_empty_not_waited_for() {
fn a_tile_a_sparse_file_leaves_out_is_0_and_not_waited_for() {
use crate::render::rustgis_tiles::cog::raster::window;
use rustgis_data::raster::cog::{Example, example_with};
use std::sync::atomic::Ordering;
Expand All @@ -36276,15 +36276,14 @@ fn a_tile_a_sparse_file_leaves_out_is_empty_not_waited_for() {
// Its overview is level 1 (1024 pixels a side); level 0's first tile has no bytes.
let r = s.run("layer.addUrl", &json!({"url": url.clone(), "name": "Scene"})).unwrap();
assert_eq!(r["width"], 1024, "{r}");
// The file gives no no-data value, so reading the tile as no data is said (#2761).
let said = "1 of its 64 tiles or strips aren't in the file, and it gives no no-data value: they are read as no data";
assert!(s.notices_since(0).iter().any(|n| n.text.contains(said)), "{:?}", s.notices_since(0));
// Nothing is assumed of it: it is what GDAL reads (#2761).
assert!(!s.notices_since(0).iter().any(|n| n.text.contains("tiles or strips")), "{:?}", s.notices_since(0));
let before = sent.load(Ordering::Relaxed);
let gray = rustgis_data::raster::ColorHint::Gray;
for _ in 0..2 {
let w = window(&url, 0, (0, 64), (0, 64), &[0], gray.clone()).unwrap();
assert!(!w.pending, "an empty tile isn't waited for");
assert!(w.raster.unwrap().bands[0].data.iter().all(|v| v.is_nan()), "empty");
assert!(w.raster.unwrap().bands[0].data.iter().all(|v| *v == 0.0), "0, as the file gives no no-data value");
}
assert_eq!(sent.load(Ordering::Relaxed), before, "nothing is fetched for it");
// The view over it (the image's north-west corner), zoomed in past the overview: written.
Expand Down
Loading
Loading