From 630a62096b17391ca626df97390c9a663dee645b Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 23:26:35 -0600 Subject: [PATCH 01/10] fix(data): a tile a sparse GeoTIFF leaves out holds 0, or its no-data value, as GDAL reads it GDAL writes a sparse file without the blocks whose cells are all its no-data value, or all 0 where it has none, and reads them back as that. They were read as no data whatever the file gave, losing real zeros, with a notice that said so. Read whole, in place, in a window of strips and in LERC files, they are now that value, and nothing is assumed or said. Part of #2761. --- crates/data/src/raster/cog.rs | 26 ++++------ crates/data/src/raster/geotiff.rs | 82 ++++++++++++++++++++----------- crates/data/src/raster/lerc.rs | 30 ++++++----- crates/engine/src/cmd/layer.rs | 1 - crates/engine/src/tests.rs | 9 ++-- crates/tiles/src/cog.rs | 61 +++++++++++++++++++++-- crates/tiles/src/cog/raster.rs | 2 - docs/user-guide/data-formats.md | 2 +- 8 files changed, 141 insertions(+), 72 deletions(-) diff --git a/crates/data/src/raster/cog.rs b/crates/data/src/raster/cog.rs index e06c7e1db0..f21d48b788 100644 --- a/crates/data/src/raster/cog.rs +++ b/crates/data/src/raster/cog.rs @@ -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 { - 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 { + 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. @@ -1163,20 +1162,15 @@ pub fn example_with(e: &Example) -> Vec { 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] diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 227beece52..8d1b9f744b 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -775,12 +775,6 @@ fn sample_bytes(dec: &mut Decoder) -> usize { (bits(dec) as usize).div_ceil(8).max(1) } -/// What a file says that gives no no-data value and leaves `absent` of an image's `chunks` out: -/// taking them as no data is an assumption (they read as 0 elsewhere). -pub(super) fn absent_note(absent: usize, chunks: usize) -> String { - format!("{absent} of its {chunks} tiles or strips aren't in the file, and it gives no no-data value: they are read as no data") -} - /// The type the current image's header gives its samples, as [`to_f32`] names them: an image with /// no chunk decoded (a sparse file's) has it too. fn declared_type(dec: &mut Decoder) -> &'static str { @@ -1370,6 +1364,8 @@ fn decimate( return Err(err(format!("a strip or tile of {cols} × {rows} pixels is too large to read ({} MB)", bytes >> 20))); } let mut bands = (0..nbands).map(|_| super::filled(ow, oh, f32::NAN)).collect::>>()?; + // What the chunks the file leaves out hold (a sparse file's), as GDAL writes and reads them. + let fill = super::lerc::nodata_tag(dec).map_or(0.0, |v| v as f32); // The chunks' places, read once and shared by the threads. let mut table = super::lerc::Table::default(); table.chunks(dec); @@ -1384,7 +1380,7 @@ fn decimate( let chunk_count = usize::try_from(examined).unwrap_or(usize::MAX); let threads = crate::threads::max().min(affordable.max(crate::threads::default_max())).min(chunk_count); if threads > 1 { - return decimate_parallel(chunks, bands, declared_type(dec), k, span, nodata, threads, open, image, limits, &table); + return decimate_parallel(chunks, bands, declared_type(dec), k, span, nodata, threads, open, image, limits, &table, fill); } } let _ = open; @@ -1394,8 +1390,10 @@ fn decimate( for p in 0..examined { crate::progress::check()?; if let Some((plane, index)) = chunks.nth(p, span, k).and_then(|i| chunks.wanted(i, k, span)) { - // One the file leaves out stays no-data. + // One the file leaves out holds its no-data value, or 0 (see [`absent_chunk`]). if table.absent(dec, index) { + let values = absent_chunk(&chunks, index, fill)?; + chunks.place(&mut bands, &values, None, &mut rounded, plane, index, k, span)?; crate::progress::step(1)?; continue; } @@ -1412,6 +1410,17 @@ fn decimate( Ok((bands, data_type, rounded)) } +/// The samples of chunk `c` (counting through every plane) where the file leaves it out (a sparse +/// file's: no offset, no bytes): each `fill`, the file's no-data value or 0, as GDAL writes a +/// sparse file without the blocks all that value and reads them back as it. As many as a chunk of +/// the image's own size decodes to ([`Chunks::place`] takes them so). +fn absent_chunk(chunks: &Chunks, c: u32, fill: f32) -> Result> { + let (_, _, cols, rows) = chunks.span(c % chunks.per_plane.max(1)); + let n = (cols as usize).checked_mul(rows as usize).and_then(|n| n.checked_mul(chunks.samples.max(1))); + let n = n.filter(|n| *n <= decoding_limit()).ok_or_else(|| err("a chunk is too large"))?; + Ok(vec![fill; n]) +} + /// [`decimate`] on `threads` threads, each with its own decoder taking the next chunk in turn. #[cfg(not(target_arch = "wasm32"))] fn decimate_parallel( @@ -1426,6 +1435,7 @@ fn decimate_parallel( image: usize, limits: Limits, table: &super::lerc::Table, + fill: f32, ) -> Result<(Vec>, &'static str, Vec)> { use std::sync::Mutex; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -1470,9 +1480,16 @@ fn decimate_parallel( } continue; }; - // One the file leaves out stays no-data. + // One the file leaves out holds its no-data value, or 0 (see [`absent_chunk`]). if table.absent(&mut dec, index) { - if let Err(e) = crate::progress::step(1) { + let placed = absent_chunk(&chunks, index, fill).and_then(|values| match out.lock() { + Ok(mut o) => { + let (bands, _, rounded) = &mut *o; + chunks.place(bands, &values, None, rounded, plane, index, k, span) + } + Err(_) => Err(err("a chunk couldn't be decoded")), + }); + if let Err(e) = placed.and_then(|()| crate::progress::step(1)) { return fail(e); } continue; @@ -2019,9 +2036,10 @@ fn read_image( // by [`super::lerc`] (#1818). let lerc = super::lerc::is_lerc(&mut dec); // 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. + // 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(); - let (chunk_count, absent) = super::lerc::Table::default().chunks(&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")); @@ -2110,9 +2128,6 @@ fn read_image( super::mask::Found::Unscanned(why) => mask_lost = Some(why), super::mask::Found::None => {} } - // Said for a whole image, not for each part read of it: the layer it is a part of said so. - let absent_said = - (absent > 0 && span.is_none() && geo.nodata.is_none() && sidecar_nodata.is_none()).then(|| absent_note(absent, chunk_count)); let mask_lost = mask_lost.map(|why| format!("its transparency mask isn't applied ({why}): masked pixels draw as stored")); // A scan keeps a stand-in transform, sized to the pixels read. if !geo.referenced { @@ -2126,7 +2141,6 @@ fn read_image( r.lost.extend(copyright_lost); r.lost.extend(table_lost); r.lost.extend(mask_lost); - r.lost.extend(absent_said); if let Some(p) = &described { r.apply_pam(p, super::pam::GDAL_METADATA); } @@ -2227,7 +2241,6 @@ fn read_image( r.lost.extend(turned); r.lost.extend(table_lost); r.lost.extend(mask_lost); - r.lost.extend(absent_said); if let Some(p) = &described { r.apply_pam(p, super::pam::GDAL_METADATA); } @@ -2768,6 +2781,7 @@ mod tests { 0, Limits::default(), &super::super::lerc::Table::default(), + 0.0, ) } else { decimate(&mut dec, 16, 16, 1, false, k, None, Uncounted::new(None, None), None) @@ -5545,10 +5559,11 @@ mod tests { assert!(!read(std::io::Cursor::new(&grey8(40, 16, &data, None)), "b").unwrap().white_is_zero); } - /// The chunks a sparse file leaves out are no-data read whole, with one thread or several, - /// whole or every k-th pixel, compressed or not, and the image keeps its type (#2761). + /// The chunks a sparse file leaves out hold 0, or the file's no-data value, read whole, with one + /// thread or several, whole or every k-th pixel, compressed or not, as GDAL reads them, and + /// the image keeps its type (#2761). #[test] - fn a_sparse_files_missing_chunks_are_no_data() { + fn a_sparse_files_missing_chunks_are_0_or_no_data() { // The byte counts of chunks `gone` set to 0, and their offsets. let sparse = |mut b: Vec, gone: &[usize]| { let at32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize; @@ -5568,21 +5583,28 @@ mod tests { let bytes = sparse(grey8(40, 16, &data, None), &[1, 3]); let r = read(std::io::Cursor::new(&bytes), "holes").unwrap(); assert_eq!(r.data_type, "UInt8"); - let said = "2 of its 4 tiles or strips aren't in the file, and it gives no no-data value: they are read as no data"; - assert!(r.lost.iter().any(|n| *n == said), "{:?}", r.lost); - let whole = read(std::io::Cursor::new(&grey8(40, 16, &data, None)), "whole").unwrap(); - assert!(whole.lost.is_empty(), "{:?}", whole.lost); - let declared = read_with_nodata(std::io::Cursor::new(&bytes), "declared", Some(255.0)).unwrap(); - assert!(!declared.lost.iter().any(|n| *n == said), "{:?}", declared.lost); + assert!(r.lost.is_empty(), "nothing is assumed: {:?}", r.lost); for y in 0..16i64 { for x in 0..40i64 { - let want = (y / 4 % 2 == 0).then(|| f32::from(data[(y * 40 + x) as usize])); - assert_eq!(r.value(0, x, y), want, "{x}, {y}"); + let want = if y / 4 % 2 == 0 { f32::from(data[(y * 40 + x) as usize]) } else { 0.0 }; + assert_eq!(r.value(0, x, y), Some(want), "{x}, {y}"); } } + // With a no-data value, they are no data. + let mut with_nodata = std::io::Cursor::new(Vec::new()); + { + use tiff::encoder::{TiffEncoder, colortype}; + let mut enc = TiffEncoder::new(&mut with_nodata).unwrap(); + let mut img = enc.new_image::(40, 16).unwrap(); + img.encoder().write_tag(Tag::Unknown(42113), "255").unwrap(); + img.rows_per_strip(4).unwrap(); + img.write_data(&data).unwrap(); + } + let r = read(std::io::Cursor::new(&sparse(with_nodata.into_inner(), &[3])), "nd").unwrap(); + assert_eq!((r.nodata, r.value(0, 0, 0), r.value(0, 39, 15)), (Some(255.0), Some(f32::from(data[0])), None)); // Every strip gone: all no-data, still bytes. let r = read(std::io::Cursor::new(&sparse(grey8(40, 16, &data, None), &[0, 1, 2, 3])), "none").unwrap(); - assert_eq!((r.data_type.as_str(), r.value(0, 0, 0)), ("UInt8", None)); + assert_eq!((r.data_type.as_str(), r.value(0, 0, 0)), ("UInt8", Some(0.0))); // No byte counts, but offsets: chunks some writers store uncompressed, read as they were. let mut bytes = grey8(40, 16, &data, None); let at32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize; @@ -5603,7 +5625,7 @@ mod tests { assert_eq!(i64::from(r.width), (1100 + k - 1) / k); for (x, y) in [(4, 4), (126, 126), (128, 0), (0, 128), (520, 130), (1098, 998)] { let tile = y / 128 * 9 + x / 128; - let want = (tile != 0 && tile != 13).then(|| pixel(x as u32, y as u32)); + let want = Some(if tile != 0 && tile != 13 { pixel(x as u32, y as u32) } else { 0.0 }); assert_eq!(r.value(0, x / k, y / k), want, "every {k}: {x}, {y}"); } } diff --git a/crates/data/src/raster/lerc.rs b/crates/data/src/raster/lerc.rs index 31aed4f615..c1067c141f 100644 --- a/crates/data/src/raster/lerc.rs +++ b/crates/data/src/raster/lerc.rs @@ -74,6 +74,15 @@ impl Table { } } +/// The no-data value the current image's GDAL_NODATA tag gives, if it gives a number. +pub(crate) fn nodata_tag(dec: &mut Decoder) -> Option { + 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::().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 { @@ -112,12 +121,7 @@ pub(crate) fn chunk(dec: &mut Decoder, index: u32, table: &mu && bps == 8 && format == 1 && dec.find_tag_unsigned_vec::(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::().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); @@ -140,12 +144,13 @@ pub(crate) fn chunk(dec: &mut Decoder, 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. 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: None }); } 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. @@ -626,7 +631,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(); @@ -639,8 +644,9 @@ mod tests { 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); + 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)); } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 1287f3d9e0..ed16461bea 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -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); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3de52c0685..ae3520d03e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -36260,7 +36260,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; @@ -36270,15 +36270,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. diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index ff56125d5d..91d1b5679a 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -1281,8 +1281,9 @@ fn get_tile_at( // it to land, then reads the tile again (#2814), so no old tile reaches its overview. let header = Arc::as_ptr(&info) as usize; let joins = |reach: crate::address::Reach, from: usize| reach == started_reach && (from == header || !is_local_file(&url)); - // A tile the file leaves out (GDAL's sparse files: no bytes) is empty: kept as any other, so - // a window over it is whole at once rather than asking for it at every draw. + // A tile the file leaves out (GDAL's sparse files: no bytes) holds 0, or no data where the file + // has a no-data value: kept as any other, so a window over it is whole at once rather than + // asking for it at every draw. if len == 0 { let key = (url.clone(), level, idx); let mut t = tiles().lock().unwrap_or_else(|e| e.into_inner()); @@ -1297,7 +1298,7 @@ fn get_tile_at( let empty = match t.used(&key, started_reach) { Some(b) => b, None => { - let b: Bands = Arc::new(vec![vec![f32::NAN; per_band]; nb].into()); + let b: Bands = Arc::new(vec![vec![info.layout.absent_value(); per_band]; nb].into()); // Kept only under the file's current header, as a decoded tile is (a local file // written again since is read again). let current = !is_local_file(&url) @@ -2032,7 +2033,7 @@ const STRIP_RUNS_AT_ONCE: usize = 8; /// The chunks of `chunks` (in the order of the file's index) split into runs whose bytes follow /// one another in the file, or with at most `gap` bytes between two, of at most `max` bytes each /// (gaps counted) unless a chunk alone is larger: each run (a range of places in `chunks`) is one -/// request. A chunk without bytes is in no run (no data). +/// request. A chunk without bytes is in no run (see [`cog::Layout::absent_value`]). #[cfg(not(target_arch = "wasm32"))] fn strip_runs(l: &Level, chunks: &[u32], max: u64, gap: u64) -> Vec> { let place = |c: u32| Some((*l.offsets.get(c as usize)?, *l.counts.get(c as usize)?)); @@ -2084,6 +2085,20 @@ fn read_strips( wanted.entry(c).or_default().push((i, at)); } } + // Those the file leaves out are in no run: 0, or no data where the file has a no-data value. + let left_out = |c: u32| l.offsets.get(c as usize) == Some(&0) && l.counts.get(c as usize) == Some(&0); + let fill = info.layout.absent_value(); + if !fill.is_nan() { + let blank: cog::Tile = vec![vec![fill; l.tile_width.max(1) as usize * th as usize]; info.layout.chunk_bands()].into(); + for (&c, places) in wanted.iter().filter(|(c, _)| left_out(**c)) { + let strip = c % l.tiles().max(1); + for &(i, b) in places { + if let Some(out) = outs.get_mut(i) { + window.copy(&blank, b, (0, strip.saturating_mul(th), l.tile_width.max(1), th), out); + } + } + } + } let chunks: Vec = wanted.keys().copied().collect(); let runs = strip_runs(l, &chunks, STRIP_RUN_BYTES, STRIP_GAP_BYTES); if runs.len() > MAX_VALUE_TILES { @@ -2228,6 +2243,41 @@ mod tests { super::forget_file(url); } + /// A strip the file leaves out (a sparse file's: no offset, no bytes) is read as 0 in a window, + /// the file giving no no-data value, as GDAL reads it, and isn't asked for (#2761). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_strip_a_sparse_file_leaves_out_is_0_in_a_window() { + let _turn = crate::cache::turn(); + let mut file = cog::example_strips(300, 200, 2); + // Strip 30 (rows 60 and 61) left out: its offset and byte count set to 0. + let at32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize; + assert_eq!(&file[..4], b"II*\0", "a little-endian classic TIFF"); + let ifd = at32(&file, 4); + for e in (0..u16::from_le_bytes([file[ifd], file[ifd + 1]]) as usize).map(|i| ifd + 2 + 12 * i) { + if [273u16, 279].contains(&u16::from_le_bytes([file[e], file[e + 1]])) { + let size = if file[e + 2] == 3 { 2 } else { 4 }; + let table = at32(&file, e + 8); + file[table + 30 * size..table + 31 * size].fill(0); + } + } + let (_, asked) = serve_strips(Arc::new(file), Arc::new(AtomicU64::new(u64::MAX)), 0); + let url = "https://sparse-strips.invalid/scene.tif"; + let never = std::sync::atomic::AtomicBool::new(false); + let info = super::window_info_until(url, &never).unwrap(); + assert_eq!(info.layout.nodata, None); + let before = asked.load(Ordering::SeqCst); + let values = super::read_values_blocking(&info, url, 0, 0, (40, 90), (51, 101)).unwrap(); + for (i, v) in values.iter().enumerate() { + let (x, y) = (40 + i as i32 % 50, 51 + i as i32 / 50); + let want = if (60..62).contains(&y) { 0.0 } else { (7 * x - 3 * y) as f32 }; + assert_eq!(*v, want, "cell ({x}, {y})"); + } + assert_eq!(asked.load(Ordering::SeqCst) - before, 2, "the strips before it and after it, not it"); + crate::cache::clear_fetcher(); + super::forget_file(url); + } + /// A window of more strips than the tiles one read takes ([`super::MAX_VALUE_TILES`]) is read /// in a few requests, one the fetch queue dropped asked for again; strips that don't follow /// one another, or past [`super::STRIP_RUN_BYTES`], are runs of their own, and empty ones @@ -3330,7 +3380,8 @@ mod tests { assert!(old_rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap().is_err()); let new = new_rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); if reader == Reach::Public { - assert!(new.unwrap().iter().flatten().all(|v| v.is_nan())); + // No no-data value: 0, as GDAL reads it. + assert!(new.unwrap().iter().flatten().all(|v| *v == 0.0)); } else { assert!(new.is_err()); } diff --git a/crates/tiles/src/cog/raster.rs b/crates/tiles/src/cog/raster.rs index cc6516cb84..3b418e234c 100644 --- a/crates/tiles/src/cog/raster.rs +++ b/crates/tiles/src/cog/raster.rs @@ -159,8 +159,6 @@ fn read_overview(info: Arc, url: String, done: Box Date: Wed, 2 Dec 2026 00:44:15 -0600 Subject: [PATCH 02/10] fix(data): a sparse GeoTIFF's missing chunk takes a sidecar's no-data value, and is black in a JPEG Read whole, a missing chunk holds the no-data value the .aux.xml sidecar gives too, as GDAL reads it, and a JPEG's is black once its YCbCr is turned into colours. A LERC chunk with no bytes is marked no data where the file has a no-data value, so a value its type can't hold isn't read as 0. A chunk's fill is bounded by its bytes. Part of #2761. --- crates/data/src/raster/geotiff.rs | 42 +++++++++++++++++++++---------- crates/data/src/raster/lerc.rs | 5 ++-- 2 files changed, 32 insertions(+), 15 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 8d1b9f744b..b2ba03470c 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1336,6 +1336,7 @@ fn decimate( k: u32, span: Option, nodata: Uncounted, + fill: &[f32], open: Option<(Opener<'_>, usize, Limits)>, ) -> Result<(Vec>, &'static str, Vec)> { crate::progress::check()?; @@ -1364,8 +1365,6 @@ fn decimate( return Err(err(format!("a strip or tile of {cols} × {rows} pixels is too large to read ({} MB)", bytes >> 20))); } let mut bands = (0..nbands).map(|_| super::filled(ow, oh, f32::NAN)).collect::>>()?; - // What the chunks the file leaves out hold (a sparse file's), as GDAL writes and reads them. - let fill = super::lerc::nodata_tag(dec).map_or(0.0, |v| v as f32); // The chunks' places, read once and shared by the threads. let mut table = super::lerc::Table::default(); table.chunks(dec); @@ -1411,14 +1410,17 @@ fn decimate( } /// The samples of chunk `c` (counting through every plane) where the file leaves it out (a sparse -/// file's: no offset, no bytes): each `fill`, the file's no-data value or 0, as GDAL writes a -/// sparse file without the blocks all that value and reads them back as it. As many as a chunk of -/// the image's own size decodes to ([`Chunks::place`] takes them so). -fn absent_chunk(chunks: &Chunks, c: u32, fill: f32) -> Result> { +/// file's: no offset, no bytes): `fill`'s, a pixel's samples in turn (or its one value for each), +/// the file's no-data value or 0, as GDAL writes a sparse file without the blocks all that value +/// and reads them back as it. As many as a chunk of the image's own size decodes to +/// ([`Chunks::place`] takes them so), held within [`decoding_limit`]'s bytes. +fn absent_chunk(chunks: &Chunks, c: u32, fill: &[f32]) -> Result> { let (_, _, cols, rows) = chunks.span(c % chunks.per_plane.max(1)); - let n = (cols as usize).checked_mul(rows as usize).and_then(|n| n.checked_mul(chunks.samples.max(1))); - let n = n.filter(|n| *n <= decoding_limit()).ok_or_else(|| err("a chunk is too large"))?; - Ok(vec![fill; n]) + let samples = chunks.samples.max(1); + let n = (cols as usize).checked_mul(rows as usize).and_then(|n| n.checked_mul(samples)); + let n = n.filter(|n| n.saturating_mul(4) <= decoding_limit()).ok_or_else(|| err("a chunk is too large"))?; + let each = |i: usize| if fill.len() == samples { fill.get(i % samples) } else { fill.first() }; + Ok((0..n).map(|i| each(i).copied().unwrap_or(0.0)).collect()) } /// [`decimate`] on `threads` threads, each with its own decoder taking the next chunk in turn. @@ -1435,7 +1437,7 @@ fn decimate_parallel( image: usize, limits: Limits, table: &super::lerc::Table, - fill: f32, + fill: &[f32], ) -> Result<(Vec>, &'static str, Vec)> { use std::sync::Mutex; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -2101,7 +2103,12 @@ fn read_image( let (iw, ih) = if decimate_by > 1 { (full_w, full_h) } else { (w, h) }; let open = open.map(|o| (o, image, limits)); // Already one vector per band. - decimate(&mut dec, iw, ih, nbands, planar, decimate_by, span, uncounted, open)? + // What the chunks the file leaves out (a sparse file's) hold, as GDAL reads them: the + // no-data value, the file's or its sidecar's, else 0. + // A JPEG's YCbCr is turned into colours after: its fill is that value's grey in YCbCr. + let fill = geo.nodata.or(sidecar_nodata).map_or(0.0, |v| v as f32); + let fill = if ycbcr && !planar { vec![fill, 128.0, 128.0] } else { vec![fill] }; + decimate(&mut dec, iw, ih, nbands, planar, decimate_by, span, uncounted, &fill, open)? }; let rounded = if rounded.iter().any(|n| *n > 0) { rounded } else { Vec::new() }; @@ -2781,10 +2788,10 @@ mod tests { 0, Limits::default(), &super::super::lerc::Table::default(), - 0.0, + &[0.0], ) } else { - decimate(&mut dec, 16, 16, 1, false, k, None, Uncounted::new(None, None), None) + decimate(&mut dec, 16, 16, 1, false, k, None, Uncounted::new(None, None), &[0.0], None) }; if let Some(after) = after { assert!(matches!(got, Err(DataError::Cancelled)), "parallel={parallel}, k={k}, after={after}: {got:?}"); @@ -5602,6 +5609,15 @@ mod tests { } let r = read(std::io::Cursor::new(&sparse(with_nodata.into_inner(), &[3])), "nd").unwrap(); assert_eq!((r.nodata, r.value(0, 0, 0), r.value(0, 39, 15)), (Some(255.0), Some(f32::from(data[0])), None)); + // A JPEG's missing strip is black once its YCbCr is turned into colours, not 0 in each. + let colors = [[200, 30, 30], [30, 160, 40], [20, 40, 220], [230, 230, 60]]; + let r = read(std::io::Cursor::new(&sparse(ycbcr_jpeg_tiff(&[(64, 64, 32)], colors, true), &[1])), "jpeg").unwrap(); + assert_eq!((0..3).map(|b| r.value(b, 10, 40)).collect::>(), [Some(0.0); 3]); + assert!((r.value(0, 10, 10).unwrap() - 200.0).abs() <= 4.0, "the strip there is read"); + // A no-data value its .aux.xml sidecar gives counts too: they hold it, which makes them no + // data once the sidecar is applied to the raster. + let r = read_with_nodata(std::io::Cursor::new(&sparse(grey8(40, 16, &data, None), &[3])), "sidecar", Some(5.0)).unwrap(); + assert_eq!((r.value(0, 0, 0), r.value(0, 39, 15)), (Some(f32::from(data[0])), Some(5.0))); // Every strip gone: all no-data, still bytes. let r = read(std::io::Cursor::new(&sparse(grey8(40, 16, &data, None), &[0, 1, 2, 3])), "none").unwrap(); assert_eq!((r.data_type.as_str(), r.value(0, 0, 0)), ("UInt8", Some(0.0))); diff --git a/crates/data/src/raster/lerc.rs b/crates/data/src/raster/lerc.rs index c1067c141f..4dab340541 100644 --- a/crates/data/src/raster/lerc.rs +++ b/crates/data/src/raster/lerc.rs @@ -145,12 +145,13 @@ pub(crate) fn chunk(dec: &mut Decoder, index: u32, table: &mu let (offset, count) = table.get(dec, tiled, index)?; if count == 0 { // 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. + // 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, nodata.unwrap_or(0.0)); } - return Ok(Chunk { samples: out, gaps: None }); + return Ok(Chunk { samples: out, gaps: nodata.map(|_| vec![true; n]) }); } 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. From 67872b1edb22bfcb7d7374e21dddd2356fe7783f Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 01:25:16 -0600 Subject: [PATCH 03/10] fix(data): a missing chunk of a JPEG with its bands stored apart takes its own band's fill Each plane's chunks take that plane's value, so a planar YCbCr JPEG's missing chunk is black too. Part of #2761. --- crates/data/src/raster/geotiff.rs | 35 ++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index b2ba03470c..7d7fb0f617 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1410,7 +1410,8 @@ fn decimate( } /// The samples of chunk `c` (counting through every plane) where the file leaves it out (a sparse -/// file's: no offset, no bytes): `fill`'s, a pixel's samples in turn (or its one value for each), +/// file's: no offset, no bytes): `fill`'s, a pixel's samples in turn, or the plane's where the +/// bands are stored apart (or its one value for each), /// the file's no-data value or 0, as GDAL writes a sparse file without the blocks all that value /// and reads them back as it. As many as a chunk of the image's own size decodes to /// ([`Chunks::place`] takes them so), held within [`decoding_limit`]'s bytes. @@ -1419,7 +1420,12 @@ fn absent_chunk(chunks: &Chunks, c: u32, fill: &[f32]) -> Result> { let samples = chunks.samples.max(1); let n = (cols as usize).checked_mul(rows as usize).and_then(|n| n.checked_mul(samples)); let n = n.filter(|n| n.saturating_mul(4) <= decoding_limit()).ok_or_else(|| err("a chunk is too large"))?; - let each = |i: usize| if fill.len() == samples { fill.get(i % samples) } else { fill.first() }; + let plane = (c / chunks.per_plane.max(1)) as usize; + let each = |i: usize| match fill.len() { + n if chunks.planar && n > 1 => fill.get(plane), + n if n == samples => fill.get(i % samples), + _ => fill.first(), + }; Ok((0..n).map(|i| each(i).copied().unwrap_or(0.0)).collect()) } @@ -2107,7 +2113,7 @@ fn read_image( // no-data value, the file's or its sidecar's, else 0. // A JPEG's YCbCr is turned into colours after: its fill is that value's grey in YCbCr. let fill = geo.nodata.or(sidecar_nodata).map_or(0.0, |v| v as f32); - let fill = if ycbcr && !planar { vec![fill, 128.0, 128.0] } else { vec![fill] }; + let fill = if ycbcr { vec![fill, 128.0, 128.0] } else { vec![fill] }; decimate(&mut dec, iw, ih, nbands, planar, decimate_by, span, uncounted, &fill, open)? }; let rounded = if rounded.iter().any(|n| *n > 0) { rounded } else { Vec::new() }; @@ -5566,6 +5572,29 @@ mod tests { assert!(!read(std::io::Cursor::new(&grey8(40, 16, &data, None)), "b").unwrap().white_is_zero); } + /// A missing chunk's samples are the fill's: a pixel's in turn where its bands are together, + /// the plane's where they are stored apart (a JPEG's YCbCr either way). + #[test] + fn a_missing_chunk_takes_each_band_its_fill() { + let chunks = |planar: bool| Chunks { + w: 2, + h: 2, + cw: 2, + ch: 2, + across: 1, + per_plane: 1, + planes: if planar { 3 } else { 1 }, + samples: if planar { 1 } else { 3 }, + planar, + }; + let ycbcr = [0.0, 128.0, 128.0]; + assert_eq!(absent_chunk(&chunks(false), 0, &ycbcr).unwrap(), [ycbcr; 4].concat()); + for plane in 0..3u32 { + assert_eq!(absent_chunk(&chunks(true), plane, &ycbcr).unwrap(), [ycbcr[plane as usize]; 4]); + } + assert_eq!(absent_chunk(&chunks(true), 1, &[7.0]).unwrap(), [7.0; 4]); + } + /// The chunks a sparse file leaves out hold 0, or the file's no-data value, read whole, with one /// thread or several, whole or every k-th pixel, compressed or not, as GDAL reads them, and /// the image keeps its type (#2761). From 9bdd00c7e73fd4460e107c6543f86cab645f1c9d Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 01:34:02 -0600 Subject: [PATCH 04/10] fix(data): a compressed chunk with no bytes is left out whatever its offset It can't be decoded from nothing, so it takes the same no-data value, a sidecar's included, as one with no offset. An uncompressed chunk still needs both at 0. Part of #2761. --- crates/data/src/raster/lerc.rs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/data/src/raster/lerc.rs b/crates/data/src/raster/lerc.rs index 4dab340541..46c79c0e9a 100644 --- a/crates/data/src/raster/lerc.rs +++ b/crates/data/src/raster/lerc.rs @@ -60,20 +60,29 @@ 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(&mut self, dec: &mut Decoder, 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) } /// How many chunks the decoder's current image has, and how many of them the file leaves out. pub(crate) fn chunks(&mut self, dec: &mut Decoder) -> (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(dec: &mut Decoder) -> bool { + dec.find_tag_unsigned::(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(dec: &mut Decoder) -> Option { dec.find_tag(Tag::Unknown(42113)) @@ -644,12 +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(); + 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))); } } From 138f45398c3842c5c886aeb2fbae68c9386e0a24 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 02:37:52 -0600 Subject: [PATCH 05/10] fix(data): a JPEG's missing chunk keeps a no-data value no byte holds A grey turned into colours keeps its luma unclamped, so a fill of -9999 stays no data instead of becoming a valid 0. The fill's room is reserved fallibly. --- crates/data/src/raster/geotiff.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 7d7fb0f617..f197655ed7 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -748,11 +748,16 @@ pub(crate) fn read_chunk( } /// 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. +/// JFIF (full-range) coefficients JPEG-in-TIFF files use. A grey (neutral chroma) is its luma in +/// each band, unclamped, so a missing chunk's no-data value outside 0 to 255 stays no data. pub(super) fn ycbcr_to_rgb(bands: &mut [Vec]) { let [y, cb, cr] = bands else { return }; for ((y, cb), cr) in y.iter_mut().zip(cb.iter_mut()).zip(cr.iter_mut()) { let (luma, blue, red) = (*y, *cb - 128.0, *cr - 128.0); + if blue == 0.0 && red == 0.0 { + (*cb, *cr) = (luma, luma); + continue; + } *y = (luma + 1.402 * red).round().clamp(0.0, 255.0); *cb = (luma - 0.344_136 * blue - 0.714_136 * red).round().clamp(0.0, 255.0); *cr = (luma + 1.772 * blue).round().clamp(0.0, 255.0); @@ -1426,7 +1431,9 @@ fn absent_chunk(chunks: &Chunks, c: u32, fill: &[f32]) -> Result> { n if n == samples => fill.get(i % samples), _ => fill.first(), }; - Ok((0..n).map(|i| each(i).copied().unwrap_or(0.0)).collect()) + let mut v = super::room(n, cols as usize, rows as usize)?; + v.extend((0..n).map(|i| each(i).copied().unwrap_or(0.0))); + Ok(v) } /// [`decimate`] on `threads` threads, each with its own decoder taking the next chunk in turn. @@ -5643,6 +5650,10 @@ mod tests { let r = read(std::io::Cursor::new(&sparse(ycbcr_jpeg_tiff(&[(64, 64, 32)], colors, true), &[1])), "jpeg").unwrap(); assert_eq!((0..3).map(|b| r.value(b, 10, 40)).collect::>(), [Some(0.0); 3]); assert!((r.value(0, 10, 10).unwrap() - 200.0).abs() <= 4.0, "the strip there is read"); + // A no-data value no byte can hold stays itself through the colours: no data, not 0. + let jpeg = sparse(ycbcr_jpeg_tiff(&[(64, 64, 32)], colors, true), &[1]); + let r = read_with_nodata(std::io::Cursor::new(&jpeg), "jpeg", Some(-9999.0)).unwrap(); + assert_eq!((0..3).map(|b| r.value(b, 10, 40)).collect::>(), [Some(-9999.0); 3]); // A no-data value its .aux.xml sidecar gives counts too: they hold it, which makes them no // data once the sidecar is applied to the raster. let r = read_with_nodata(std::io::Cursor::new(&sparse(grey8(40, 16, &data, None), &[3])), "sidecar", Some(5.0)).unwrap(); From 74d5d3e5c64271b75baa756187310ea46d106a49 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 03:32:20 -0600 Subject: [PATCH 06/10] fix(data): a sparse file's missing chunk is filled in place, not built The fill is written straight into the bands, so a missing chunk no larger than a present one that decodes can't fail the read, and no chunk-sized buffer is allocated for it. --- crates/data/src/raster/geotiff.rs | 87 ++++++++++++++++++------------- 1 file changed, 52 insertions(+), 35 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index f197655ed7..8f124ee934 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1304,6 +1304,48 @@ impl Chunks { } Ok(()) } + + /// The value band sample `b` of a pixel of `plane` takes where the file leaves its chunk out: + /// `fill`'s for the sample, or the plane's where the bands are stored apart (or its one value + /// for each). + fn fill_value(&self, fill: &[f32], plane: usize, b: usize) -> f32 { + let v = match fill.len() { + n if self.planar && n > 1 => fill.get(plane), + n if n == self.samples.max(1) => fill.get(b), + _ => fill.first(), + }; + v.copied().unwrap_or(0.0) + } + + /// Sets the pixels of chunk `c` of `plane` that [`Chunks::place`] would copy to each band's + /// fill (see [`Chunks::fill_value`]): a chunk the file leaves out (a sparse file's: no offset, + /// no bytes) holds the file's no-data value or 0, as GDAL writes a sparse file without the + /// blocks all that value and reads them back as it. Nothing the size of the chunk is held. + fn fill(&self, bands: &mut [Vec], fill: &[f32], plane: usize, c: u32, k: u32, span: Span) { + let c = c % self.per_plane.max(1); + let ow = span.width(); + let (x0, y0, cols, rows) = self.span(c); + let k = u64::from(k.max(1)); + let ((xs, xe), (ys, ye)) = (span.kept(span.cols, x0, cols, k), span.kept(span.rows, y0, rows, k)); + let (sc, sr) = (u64::from(span.cols.0), u64::from(span.rows.0)); + for b in 0..self.samples.max(1) { + let band = if self.planar { plane } else { b }; + let v = self.fill_value(fill, plane, b); + let Some(out) = bands.get_mut(band) else { continue }; + let mut y = ys; + while y < ye { + let row = (y / k - sr) as usize * ow; + let mut x = xs; + while x < xe { + if let Some(slot) = out.get_mut(row + (x / k - sc) as usize) { + *slot = v; + } + x += k; + } + y += k; + } + } + } } /// The most bytes the tiff crate decodes one chunk to, or a whole image to: the sample limit as @@ -1394,10 +1436,9 @@ fn decimate( for p in 0..examined { crate::progress::check()?; if let Some((plane, index)) = chunks.nth(p, span, k).and_then(|i| chunks.wanted(i, k, span)) { - // One the file leaves out holds its no-data value, or 0 (see [`absent_chunk`]). + // One the file leaves out holds its no-data value, or 0 (see [`Chunks::fill`]). if table.absent(dec, index) { - let values = absent_chunk(&chunks, index, fill)?; - chunks.place(&mut bands, &values, None, &mut rounded, plane, index, k, span)?; + chunks.fill(&mut bands, fill, plane, index, k, span); crate::progress::step(1)?; continue; } @@ -1414,28 +1455,6 @@ fn decimate( Ok((bands, data_type, rounded)) } -/// The samples of chunk `c` (counting through every plane) where the file leaves it out (a sparse -/// file's: no offset, no bytes): `fill`'s, a pixel's samples in turn, or the plane's where the -/// bands are stored apart (or its one value for each), -/// the file's no-data value or 0, as GDAL writes a sparse file without the blocks all that value -/// and reads them back as it. As many as a chunk of the image's own size decodes to -/// ([`Chunks::place`] takes them so), held within [`decoding_limit`]'s bytes. -fn absent_chunk(chunks: &Chunks, c: u32, fill: &[f32]) -> Result> { - let (_, _, cols, rows) = chunks.span(c % chunks.per_plane.max(1)); - let samples = chunks.samples.max(1); - let n = (cols as usize).checked_mul(rows as usize).and_then(|n| n.checked_mul(samples)); - let n = n.filter(|n| n.saturating_mul(4) <= decoding_limit()).ok_or_else(|| err("a chunk is too large"))?; - let plane = (c / chunks.per_plane.max(1)) as usize; - let each = |i: usize| match fill.len() { - n if chunks.planar && n > 1 => fill.get(plane), - n if n == samples => fill.get(i % samples), - _ => fill.first(), - }; - let mut v = super::room(n, cols as usize, rows as usize)?; - v.extend((0..n).map(|i| each(i).copied().unwrap_or(0.0))); - Ok(v) -} - /// [`decimate`] on `threads` threads, each with its own decoder taking the next chunk in turn. #[cfg(not(target_arch = "wasm32"))] fn decimate_parallel( @@ -1495,15 +1514,15 @@ fn decimate_parallel( } continue; }; - // One the file leaves out holds its no-data value, or 0 (see [`absent_chunk`]). + // One the file leaves out holds its no-data value, or 0 (see [`Chunks::fill`]). if table.absent(&mut dec, index) { - let placed = absent_chunk(&chunks, index, fill).and_then(|values| match out.lock() { + let placed = match out.lock() { Ok(mut o) => { - let (bands, _, rounded) = &mut *o; - chunks.place(bands, &values, None, rounded, plane, index, k, span) + chunks.fill(&mut o.0, fill, plane, index, k, span); + Ok(()) } Err(_) => Err(err("a chunk couldn't be decoded")), - }); + }; if let Err(e) = placed.and_then(|()| crate::progress::step(1)) { return fail(e); } @@ -5595,11 +5614,9 @@ mod tests { planar, }; let ycbcr = [0.0, 128.0, 128.0]; - assert_eq!(absent_chunk(&chunks(false), 0, &ycbcr).unwrap(), [ycbcr; 4].concat()); - for plane in 0..3u32 { - assert_eq!(absent_chunk(&chunks(true), plane, &ycbcr).unwrap(), [ycbcr[plane as usize]; 4]); - } - assert_eq!(absent_chunk(&chunks(true), 1, &[7.0]).unwrap(), [7.0; 4]); + assert_eq!((0..3).map(|b| chunks(false).fill_value(&ycbcr, 0, b)).collect::>(), ycbcr); + assert_eq!((0..3).map(|plane| chunks(true).fill_value(&ycbcr, plane, 0)).collect::>(), ycbcr); + assert_eq!(chunks(true).fill_value(&[7.0], 1, 0), 7.0); } /// The chunks a sparse file leaves out hold 0, or the file's no-data value, read whole, with one From dbf178b41a73afe7657524bc17efddd872f2ea8d Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 03:38:50 -0600 Subject: [PATCH 07/10] fix(tiles): a strip with no bytes is left out of a window as a tile is --- crates/data/src/raster/geotiff.rs | 4 ++-- crates/tiles/src/cog.rs | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 8f124ee934..450ae7395b 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1436,7 +1436,7 @@ fn decimate( for p in 0..examined { crate::progress::check()?; if let Some((plane, index)) = chunks.nth(p, span, k).and_then(|i| chunks.wanted(i, k, span)) { - // One the file leaves out holds its no-data value, or 0 (see [`Chunks::fill`]). + // A chunk the file leaves out holds its no-data value, or 0 (see [`Chunks::fill`]). if table.absent(dec, index) { chunks.fill(&mut bands, fill, plane, index, k, span); crate::progress::step(1)?; @@ -1514,7 +1514,7 @@ fn decimate_parallel( } continue; }; - // One the file leaves out holds its no-data value, or 0 (see [`Chunks::fill`]). + // A chunk the file leaves out holds its no-data value, or 0 (see [`Chunks::fill`]). if table.absent(&mut dec, index) { let placed = match out.lock() { Ok(mut o) => { diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index 91d1b5679a..0ba604502c 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -2085,8 +2085,9 @@ fn read_strips( wanted.entry(c).or_default().push((i, at)); } } - // Those the file leaves out are in no run: 0, or no data where the file has a no-data value. - let left_out = |c: u32| l.offsets.get(c as usize) == Some(&0) && l.counts.get(c as usize) == Some(&0); + // Those the file leaves out (no bytes, as a tile is) are in no run: 0, or no data where the + // file has a no-data value. + let left_out = |c: u32| l.counts.get(c as usize) == Some(&0); let fill = info.layout.absent_value(); if !fill.is_nan() { let blank: cog::Tile = vec![vec![fill; l.tile_width.max(1) as usize * th as usize]; info.layout.chunk_bands()].into(); From 53f37dd5ec47e5c446eee46ef35edcf9aa2e5fe4 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 04:17:06 -0600 Subject: [PATCH 08/10] perf(tiles): a strip window builds its blank strip only when one is left out --- crates/data/src/raster/geotiff.rs | 2 +- crates/tiles/src/cog.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 450ae7395b..3f68b78c55 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -2134,12 +2134,12 @@ fn read_image( } else { let (iw, ih) = if decimate_by > 1 { (full_w, full_h) } else { (w, h) }; let open = open.map(|o| (o, image, limits)); - // Already one vector per band. // What the chunks the file leaves out (a sparse file's) hold, as GDAL reads them: the // no-data value, the file's or its sidecar's, else 0. // A JPEG's YCbCr is turned into colours after: its fill is that value's grey in YCbCr. let fill = geo.nodata.or(sidecar_nodata).map_or(0.0, |v| v as f32); let fill = if ycbcr { vec![fill, 128.0, 128.0] } else { vec![fill] }; + // Already one vector per band. decimate(&mut dec, iw, ih, nbands, planar, decimate_by, span, uncounted, &fill, open)? }; let rounded = if rounded.iter().any(|n| *n > 0) { rounded } else { Vec::new() }; diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index 0ba604502c..d08c3ba21b 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -2089,7 +2089,7 @@ fn read_strips( // file has a no-data value. let left_out = |c: u32| l.counts.get(c as usize) == Some(&0); let fill = info.layout.absent_value(); - if !fill.is_nan() { + if !fill.is_nan() && wanted.keys().any(|&c| left_out(c)) { let blank: cog::Tile = vec![vec![fill; l.tile_width.max(1) as usize * th as usize]; info.layout.chunk_bands()].into(); for (&c, places) in wanted.iter().filter(|(c, _)| left_out(**c)) { let strip = c % l.tiles().max(1); From cc47fec289e0259a912c9e608734467275c0309a Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 04:59:32 -0600 Subject: [PATCH 09/10] test(data): a compressed chunk with no bytes but an offset is left out, as GDAL reads it --- crates/data/src/raster/geotiff.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 3f68b78c55..c0d74a01dd 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1318,8 +1318,8 @@ impl Chunks { } /// Sets the pixels of chunk `c` of `plane` that [`Chunks::place`] would copy to each band's - /// fill (see [`Chunks::fill_value`]): a chunk the file leaves out (a sparse file's: no offset, - /// no bytes) holds the file's no-data value or 0, as GDAL writes a sparse file without the + /// fill (see [`Chunks::fill_value`]): a chunk the file leaves out (a sparse file's: no bytes, + /// and no offset where it is uncompressed, see [`super::lerc::Table::absent`]) holds the file's no-data value or 0, as GDAL writes a sparse file without the /// blocks all that value and reads them back as it. Nothing the size of the chunk is held. fn fill(&self, bands: &mut [Vec], fill: &[f32], plane: usize, c: u32, k: u32, span: Span) { let c = c % self.per_plane.max(1); @@ -5624,13 +5624,14 @@ mod tests { /// the image keeps its type (#2761). #[test] fn a_sparse_files_missing_chunks_are_0_or_no_data() { - // The byte counts of chunks `gone` set to 0, and their offsets. - let sparse = |mut b: Vec, gone: &[usize]| { + // The byte counts of chunks `gone` set to 0, and their offsets unless `keep_offsets`. + let left_out = |mut b: Vec, gone: &[usize], keep_offsets: bool| { let at32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize; let ifd = at32(&b, 4); for i in 0..u16::from_le_bytes([b[ifd], b[ifd + 1]]) as usize { let e = ifd + 2 + 12 * i; - if [273, 279, 324, 325].contains(&u16::from_le_bytes([b[e], b[e + 1]])) { + let tags: &[u16] = if keep_offsets { &[279, 325] } else { &[273, 279, 324, 325] }; + if tags.contains(&u16::from_le_bytes([b[e], b[e + 1]])) { let size = if b[e + 2] == 3 { 2 } else { 4 }; let table = if at32(&b, e + 4) * size <= 4 { e + 8 } else { at32(&b, e + 8) }; gone.iter().for_each(|c| b[table + c * size..table + (c + 1) * size].fill(0)); @@ -5638,6 +5639,7 @@ mod tests { } b }; + let sparse = |b: Vec, gone: &[usize]| left_out(b, gone, false); // Strips of 4 rows, uncompressed: the second and the last one gone. let data: Vec = (0..40 * 16).map(|i| (i % 251 + 1) as u8).collect(); let bytes = sparse(grey8(40, 16, &data, None), &[1, 3]); @@ -5667,6 +5669,9 @@ mod tests { let r = read(std::io::Cursor::new(&sparse(ycbcr_jpeg_tiff(&[(64, 64, 32)], colors, true), &[1])), "jpeg").unwrap(); assert_eq!((0..3).map(|b| r.value(b, 10, 40)).collect::>(), [Some(0.0); 3]); assert!((r.value(0, 10, 10).unwrap() - 200.0).abs() <= 4.0, "the strip there is read"); + // A compressed chunk with no bytes is left out whatever its offset, as GDAL reads it. + let r = read(std::io::Cursor::new(&left_out(ycbcr_jpeg_tiff(&[(64, 64, 32)], colors, true), &[1], true)), "count").unwrap(); + assert_eq!((0..3).map(|b| r.value(b, 10, 40)).collect::>(), [Some(0.0); 3]); // A no-data value no byte can hold stays itself through the colours: no data, not 0. let jpeg = sparse(ycbcr_jpeg_tiff(&[(64, 64, 32)], colors, true), &[1]); let r = read_with_nodata(std::io::Cursor::new(&jpeg), "jpeg", Some(-9999.0)).unwrap(); From 4f1b204d7d7955a8cbbd9edddb3cc83258b6a403 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 05:18:23 -0600 Subject: [PATCH 10/10] fix(data): a sparse GeoTIFF's missing chunks take the no-data value of the bands it has Read again, as a type that rounds is, when the sidecar's no-data value for the raster's bands differs from that of all its records, so the fill and the declared value agree. A transparency mask's chunk with no bytes is masked whatever its offset, as GDAL reads it. --- crates/data/src/raster/mask.rs | 4 ++-- crates/data/src/raster/mod.rs | 36 +++++++++++++++++++++++++++------- 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/crates/data/src/raster/mask.rs b/crates/data/src/raster/mask.rs index 2d1f8d15b0..310efa9a3f 100644 --- a/crates/data/src/raster/mask.rs +++ b/crates/data/src/raster/mask.rs @@ -122,8 +122,8 @@ pub(super) fn read(dec: &mut Decoder, 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. diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 4978213af7..e5d3d69faf 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1570,15 +1570,13 @@ fn read_path_placing(path: &Path, world: bool) -> Result { // 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); @@ -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) }; @@ -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::(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#"79"#; + 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"), "