From 853566c0788735057602c3dfbaf9e0861dc0064d Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 29 Nov 2026 07:44:17 -0300 Subject: [PATCH] feat(data): read a window of a GeoTIFF in strips in place (#2592, part 1) A GeoTIFF in strips (the Brazil Data Cube's CBERS and Amazonia scenes) is laid out as tiles as wide as the image and RowsPerStrip rows tall, from its strip offsets and byte counts, so a window (layer.addUrl with bbox) reads only its rows' strips by range. Strips too large to decode one at a time are still read whole, and say so. Drawing such a file in place stays refused as before, so the map draws it from the file downloaded whole. A small file's header read whole now also serves a chunk's reads past the chunk read after it (its IFD written after the strips). Part of #2592. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/cog.rs | 125 ++++++++++++++++++++++++++++----- crates/engine/src/cmd/layer.rs | 3 +- crates/engine/src/tests.rs | 24 +++++++ crates/tiles/src/cog.rs | 76 +++++++++++++++++++- 4 files changed, 206 insertions(+), 22 deletions(-) diff --git a/crates/data/src/raster/cog.rs b/crates/data/src/raster/cog.rs index 5f312f1d52..5d5970e3b3 100644 --- a/crates/data/src/raster/cog.rs +++ b/crates/data/src/raster/cog.rs @@ -1,7 +1,9 @@ //! Cloud-optimised GeoTIFFs read in place: the layout of a tiled GeoTIFF (its images, their tile //! grids and where each tile is) from the bytes read so far, and one tile at a time decoded from -//! its own bytes. Nothing here fetches: [`Sparse`] holds the byte ranges the caller has read, and a -//! read past them says which range is needed next (the tile cache fetches it, by HTTP range). +//! its own bytes. A GeoTIFF in strips is laid out the same way, each strip a tile as wide as the +//! image ([`Layout::strips`]). Nothing here fetches: [`Sparse`] holds the byte ranges the caller +//! has read, and a read past them says which range is needed next (the tile cache fetches it, by +//! HTTP range). //! //! Files are hostile input: image counts, tile counts and sizes are bounded, and a tile is decoded //! with the same limits as a whole GeoTIFF. @@ -147,9 +149,11 @@ impl Read for Sparse { if buf.is_empty() || self.len.is_some_and(|len| self.pos >= len) { return Ok(0); } - let hit = self.chunks.range(..=self.pos).next_back().and_then(|(at, c)| { + // The part holding `pos`: the last one starting at or before it, or an earlier one reaching + // past it (a small file's header read whole holds an IFD written after the chunk read). + let hit = self.chunks.range(..=self.pos).rev().find_map(|(at, c)| { let off = usize::try_from(self.pos - at).ok()?; - (off < c.len()).then(|| c.get(off..)).flatten() + c.get(off..).filter(|s| !s.is_empty()) }); match hit { Some(src) => { @@ -245,6 +249,10 @@ pub struct Layout { pub lost: crate::loss::Notes, /// Who holds the rights to the picture (its Copyright tag), as [`super::Raster::copyright`]. pub copyright: Option, + /// The file is in strips, not tiles (#2592): each level's tiles are its strips, as wide as the + /// image and `RowsPerStrip` rows tall. A window is read from them in place; the map draws such + /// a file from it read whole, as before. + pub strips: bool, } impl Layout { @@ -286,7 +294,7 @@ pub enum Parse { Done(Box), /// These bytes (first, end) must be read first. Need(u64, u64), - /// Not a tiled GeoTIFF RustGIS can read a tile at a time (strips, separate band planes…): read + /// Not a GeoTIFF RustGIS can read a tile at a time (a rotated image, strips too large…): read /// it whole instead. NotTiled(String), } @@ -324,7 +332,7 @@ fn take_tiles(allowance: &mut usize, n: usize) -> Result<()> { Ok(()) } -/// The layout of a tiled GeoTIFF, from the bytes read so far. +/// The layout of a tiled GeoTIFF, or of one in strips, from the bytes read so far. pub fn layout(bytes: &Sparse) -> Result { let r = bytes.reader(); let watch = r.clone(); @@ -478,6 +486,8 @@ fn read_layout(r: Sparse) -> Result { let mut skipped = 0usize; // Transparency masks passed over. let mut masks = 0usize; + // The full image is in strips: so are the levels read after it. + let mut strips = false; loop { let subfile = dec.find_tag_unsigned::(Tag::NewSubfileType).ok().flatten().unwrap_or(0); // Transparency masks are skipped (a tile is read without its mask's), said, and count @@ -490,14 +500,19 @@ fn read_layout(r: Sparse) -> Result { break; } } else { - let Some(tw) = dec.find_tag_unsigned::(Tag::TileWidth).ok().flatten() else { - if index == 0 { - return Ok(Parse::NotTiled("a GeoTIFF in strips is read whole".into())); - } - break; - }; - let th = dec.find_tag_unsigned::(Tag::TileLength).ok().flatten().unwrap_or(tw); let (w, h) = dec.dimensions().map_err(err)?; + let tiled = dec.find_tag_unsigned::(Tag::TileWidth).ok().flatten(); + // A strip is a tile as wide as the image and `RowsPerStrip` rows tall (the whole image + // without the tag). A file in strips has its overviews in strips; a tiled file's image in + // strips ends the scan, as before. + if levels.is_empty() { + strips = tiled.is_none(); + } + let (tw, th) = match tiled { + Some(tw) if !strips => (tw, dec.find_tag_unsigned::(Tag::TileLength).ok().flatten().unwrap_or(tw)), + None if strips => (w, dec.find_tag_unsigned::(Tag::RowsPerStrip).ok().flatten().unwrap_or(h).min(h)), + _ => break, + }; // An overview is smaller than the full image in both width and height, whatever the file's // order: TIFF doesn't require the cloud-optimised largest-first order, and some // writers store the smallest first (#1908). A level decodes as the full image does, @@ -562,6 +577,11 @@ fn read_layout(r: Sparse) -> Result { let bytes = tile_bytes(tw, th, per_chunk, level_bits); if bytes > MAX_TILE_BYTES as u64 { let (mib, max) = (bytes.div_ceil(1 << 20), MAX_TILE_BYTES >> 20); + if strips { + return Ok(Parse::NotTiled(format!( + "strips of {th} rows take {mib} MiB each once read, more than the {max} MiB one may take: too large to read in place, so it is read whole" + ))); + } // Bands stored apart help only when one band's tile then fits. let apart = per_chunk > 1 && tile_bytes(tw, th, 1, level_bits) <= MAX_TILE_BYTES as u64; let of_bands = if per_chunk > 1 { format!(" of {per_chunk} interleaved bands") } else { String::new() }; @@ -577,8 +597,9 @@ fn read_layout(r: Sparse) -> Result { // Every band plane's tiles, when the bands are stored apart. let n = (w.div_ceil(tw) as usize).saturating_mul(h.div_ceil(th) as usize).saturating_mul(planes); take_tiles(&mut allowance, n)?; - let mut offsets = dec.find_tag_unsigned_vec::(Tag::TileOffsets).map_err(err)?.unwrap_or_default(); - let mut counts = dec.find_tag_unsigned_vec::(Tag::TileByteCounts).map_err(err)?.unwrap_or_default(); + let (at, len) = if strips { (Tag::StripOffsets, Tag::StripByteCounts) } else { (Tag::TileOffsets, Tag::TileByteCounts) }; + let mut offsets = dec.find_tag_unsigned_vec::(at).map_err(err)?.unwrap_or_default(); + let mut counts = dec.find_tag_unsigned_vec::(len).map_err(err)?.unwrap_or_default(); if offsets.len() < n || counts.len() < n { return Err(err("the tile index is shorter than the image")); } @@ -645,6 +666,7 @@ fn read_layout(r: Sparse) -> Result { described, lost, copyright, + strips, }))) } @@ -766,6 +788,25 @@ pub fn example(size: u32, tile: u32) -> Vec { example_with(&Example { size, tile, ..Example::default() }) } +/// A small GeoTIFF in strips, as the Brazil Data Cube writes its scenes (#2592): `width × height` +/// signed 16-bit cells, Deflate, `rows` rows a strip, no overviews, in longitude/latitude from +/// 10° E, 46° N in cells of 0.01°; cell (x, y) is `7 x − 3 y`. +#[doc(hidden)] +pub fn example_strips(width: u32, height: u32, rows: u32) -> Vec { + use tiff::encoder::{Compression, DeflateLevel, TiffEncoder, colortype}; + let values: Vec = (0..height).flat_map(|y| (0..width).map(move |x| (7 * x as i32 - 3 * y as i32) as i16)).collect(); + let mut out = std::io::Cursor::new(Vec::new()); + let made = TiffEncoder::new(&mut out).map(|e| e.with_compression(Compression::Deflate(DeflateLevel::Balanced))).and_then(|mut enc| { + let mut img = enc.new_image::(width, height)?; + img.encoder().write_tag(Tag::ModelPixelScaleTag, &[0.01f64, 0.01, 0.0][..])?; + img.encoder().write_tag(Tag::ModelTiepointTag, &[0.0f64, 0.0, 0.0, 10.0, 46.0, 0.0][..])?; + img.encoder().write_tag(Tag::GeoKeyDirectoryTag, &[1u16, 1, 0, 2, 1024, 0, 1, 2, 2048, 0, 1, 4326][..])?; + img.rows_per_strip(rows)?; + img.write_data(&values) + }); + made.map(|()| out.into_inner()).unwrap_or_default() +} + /// What [`example_with`] writes. #[doc(hidden)] #[derive(Clone, Copy, Debug)] @@ -1383,11 +1424,59 @@ pub(crate) mod tests { assert!(said.iter().any(|x| x.contains("band and class names and wavelengths are left out")), "{said:?}"); } + /// A GeoTIFF in strips (#2592) is laid out as tiles as wide as the image and a strip's rows + /// tall: each decodes to its rows, the last strip's rows past the image NaN. + #[test] + fn strips_are_tiles_as_wide_as_the_image() { + let file = example_strips(37, 11, 4); + let Parse::Done(l) = layout(&Sparse::default().with(0, file.clone())).unwrap() else { panic!("not read in place") }; + let full = &l.levels[0]; + assert!(l.strips && !l.planar); + assert_eq!((l.levels.len(), full.width, full.height, full.tile_width, full.tile_height, full.tiles()), (1, 37, 11, 37, 4, 3)); + assert_eq!((l.data_type, l.bands, l.transform.origin_x, l.transform.pixel_width), ("Int16", 1, 10.0, 0.01)); + // The header read whole, as a small file's first read is: its IFD comes after the strips. + let header = Sparse::default().with(0, file.clone()); + assert!(u32::from_le_bytes(file[4..8].try_into().unwrap()) as u64 > full.offsets[2]); + for strip in 0..3u32 { + let (at, n) = (full.offsets[strip as usize] as usize, full.counts[strip as usize] as usize); + let bands = decode_tile(&header, &l, 0, strip, file[at..at + n].to_vec()).unwrap(); + for (i, v) in bands[0].iter().enumerate() { + let (x, y) = (i as u32 % 37, strip * 4 + i as u32 / 37); + if y < 11 { + assert_eq!(*v, (7 * x as i32 - 3 * y as i32) as f32, "cell ({x}, {y})"); + } else { + assert!(v.is_nan(), "row {y} is past the image"); + } + } + } + // A file RustGIS writes, in strips too, and one strip for the whole image. + let own = crate::raster::geotiff::tests_support::strip_tiff(); + assert!(matches!(layout(&Sparse::default().with(0, own)).unwrap(), Parse::Done(l) if l.strips)); + let one = example_strips(5, 3, 100); + assert!(matches!(layout(&Sparse::default().with(0, one)).unwrap(), Parse::Done(l) if l.levels[0].tile_height == 3)); + } + + /// Strips too large to decode one at a time are read whole, as before, and said so. + #[test] + fn strips_too_large_to_read_in_place_are_read_whole() { + let mut file = example_strips(16, 8, 8); + // The image made 1,048,576 rows tall, in one strip of them all: 64 MiB once read. + let ifd = u32::from_le_bytes(file[4..8].try_into().unwrap()) as usize; + let n = u16::from_le_bytes(file[ifd..ifd + 2].try_into().unwrap()) as usize; + for e in (0..n).map(|i| ifd + 2 + i * 12) { + let tag = u16::from_le_bytes(file[e..e + 2].try_into().unwrap()); + if tag == 257 || tag == 278 { + assert_eq!(u16::from_le_bytes(file[e + 2..e + 4].try_into().unwrap()), 4, "tag {tag} is a LONG"); + file[e + 8..e + 12].copy_from_slice(&(1u32 << 20).to_le_bytes()); + } + } + let Parse::NotTiled(why) = layout(&Sparse::default().with(0, file)).unwrap() else { panic!("read in place") }; + assert!(why.starts_with("strips of 1048576 rows take 64 MiB each") && why.contains("too large to read in place"), "{why}"); + } + #[test] - fn strips_and_junk_are_refused() { + fn rotated_images_and_junk_are_refused() { assert!(is_tiff(b"II*\0") && is_tiff(b"MM\0+") && !is_tiff(b"PK\x03\x04")); - let strips = crate::raster::geotiff::tests_support::strip_tiff(); - assert!(matches!(layout(&Sparse::default().with(0, strips)).unwrap(), Parse::NotTiled(_))); // A rotated image is read whole, and turned north-up then (issue #251). let m = [30.0, 5.0, 0.0, 400_000.0, 3.0, -30.0, 0.0, 5_000_000.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]; let rotated = crate::raster::geotiff::tests_support::matrix_tiff(m, false); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index a670435610..a53146e4fc 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -6606,7 +6606,8 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic:: let cell = asked.cell; // The five minutes count from the header's read. let started = std::time::Instant::now(); - let info = cog::info_until(url, stop).map_err(named)?; + // A file in strips too (#2592): a strip is a tile as wide as the image. + let info = cog::window_info_until(url, stop).map_err(named)?; let layout = &info.layout; let (pw, ph) = (layout.transform.pixel_width, layout.transform.pixel_height); if !(pw.is_finite() && ph.is_finite() && pw != 0.0 && ph != 0.0) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ebca733592..e4ebb12bb0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -53588,6 +53588,30 @@ fn a_bottom_up_cog_window_comes_in_north_up() { assert_eq!(c.transform.origin_y, 45.0 + f64::from(c.height) / 1024.0); } +/// `layer.addUrl` with `"bbox"` on a GeoTIFF in strips (#2592), as the Brazil Data Cube serves its +/// CBERS scenes: the window comes in, read by range, its values where they lie. Without a box the +/// file is downloaded whole, as before. +#[test] +fn a_window_of_a_geotiff_in_strips_comes_in_as_a_raster() { + // 300 × 200 cells of 0.01° from 10° E, 46° N, a row a strip; cell (x, y) is 7 x − 3 y. + let file = rustgis_data::raster::cog::example_strips(300, 200, 1); + let (base, _) = serve_ranges(file.clone()); + let mut s = world(); + let url = format!("{base}/cbers.tif"); + let r = s.run("layer.addUrl", &json!({"url": url, "bbox": [10.505, 45.005, 11.005, 45.505], "name": "Strips"})).unwrap(); + let (c0, r0) = (r["window"]["columns"][0].as_i64().unwrap(), r["window"]["rows"][0].as_i64().unwrap()); + assert!((49..=51).contains(&c0) && (49..=51).contains(&r0), "{r}"); + let w = s.map().layer_by_name("Strips").and_then(|l| l.raster.as_ref()?.data.clone()).unwrap(); + assert!((50..=52).contains(&w.width) && (50..=52).contains(&w.height), "{} × {}", w.width, w.height); + assert_eq!(w.data_type, "Int16"); + for (x, y) in [(0, 0), (10, 5), (i64::from(w.width) - 1, i64::from(w.height) - 1)] { + assert_eq!(w.value(0, x, y), Some((7 * (c0 + x) - 3 * (r0 + y)) as f32), "cell ({x}, {y})"); + } + s.run("layer.addUrl", &json!({"url": url, "name": "Whole"})).unwrap(); + let whole = s.map().layer_by_name("Whole").and_then(|l| l.raster.as_ref()?.data.clone()).unwrap(); + assert_eq!((whole.width, whole.height), (300, 200)); +} + /// A window read for a raster made from it (AlphaEarth's similarity and change, #1720) says what /// its header left out, as `layer.addUrl` says it when it adds the window; a clean file, nothing. #[test] diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index 6376bf0ecf..ff15444680 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -380,7 +380,7 @@ pub fn info(url: &str) -> Result>, String> { { let i = infos().lock().unwrap_or_else(|e| e.into_inner()); match i.get(url) { - Some(State::Ready(info, reach)) if *reach <= crate::cache::ceiling_for(url) => return Ok(Some(info.clone())), + Some(State::Ready(info, reach)) if *reach <= crate::cache::ceiling_for(url) => return drawn(info.clone()).map(Some), Some(State::Loading(..)) => return Ok(None), Some(State::Failed(e, at, reach)) if *reach == crate::cache::ceiling_for(url) => { // Not read again until its wait is over: the map draws again then. @@ -405,7 +405,7 @@ pub fn info_landed(url: &str) -> Option> { crate::logins::check(url).ok()?; let url = split(url).0; match infos().lock().unwrap_or_else(|e| e.into_inner()).get(url) { - Some(State::Ready(info, reach)) if *reach <= crate::cache::ceiling_for(url) => Some(info.clone()), + Some(State::Ready(info, reach)) if *reach <= crate::cache::ceiling_for(url) => drawn(info.clone()).ok(), _ => None, } } @@ -444,10 +444,23 @@ fn forget_if_rewritten(url: &str) { } /// Shares parsed headers and loading waiters, retaining retry delays only for resource failures. +/// A file in strips is refused, as one the map draws from it read whole ([`drawn`]). fn with_info(url: &str, then: Box, String>) + Send>) { + with_any_info(url, Box::new(move |r| then(r.and_then(drawn)))); +} + +/// [`with_info`], a file in strips too: for a window read from its strips ([`window_info_until`]). +fn with_any_info(url: &str, then: Box, String>) + Send>) { with_info_at(url, crate::cache::ceiling_for(url), then); } +/// A file's header, for the map to draw it in place: a file in strips (#2592), whose strips are +/// read for a window only (it has no overviews to draw from), is refused as before, so the map +/// draws it from the file read whole. +fn drawn(info: Arc) -> Result, String> { + if info.layout.strips { Err(format!("{NOT_COG}: a GeoTIFF in strips is read whole")) } else { Ok(info) } +} + /// Retains a waiter's original ceiling when another reader's in-flight load must finish first. fn with_info_at(url: &str, ceiling: crate::address::Reach, then: Box, String>) + Send>) { let then = caller_callback(then); @@ -1694,10 +1707,28 @@ pub fn info_blocking(url: &str) -> Result, String> { /// [`STOPPED`]. #[cfg(not(target_arch = "wasm32"))] pub fn info_until(url: &str, stop: &std::sync::atomic::AtomicBool) -> Result, String> { + info_until_then(url, stop, false) +} + +/// [`info_until`] for a window: a file in strips too (#2592), whose strips +/// [`read_bands_counted_blocking`] reads as tiles. +#[cfg(not(target_arch = "wasm32"))] +pub fn window_info_until(url: &str, stop: &std::sync::atomic::AtomicBool) -> Result, String> { + info_until_then(url, stop, true) +} + +/// [`info_until`], a file in strips too when `strips`. +#[cfg(not(target_arch = "wasm32"))] +fn info_until_then(url: &str, stop: &std::sync::atomic::AtomicBool, strips: bool) -> Result, String> { let url = split(url).0; ask_again_if_dropped(url); let (tx, rx) = std::sync::mpsc::channel(); - with_info(url, Box::new(move |r| tx.send(r).unwrap_or_default())); + let then: Box, String>) + Send> = Box::new(move |r| tx.send(r).unwrap_or_default()); + if strips { + with_any_info(url, then) + } else { + with_info(url, then) + } wait_until(&rx, Duration::from_secs(120), stop).map_err(|stopped| stopped_or(stopped, url, "no answer in two minutes"))? } @@ -1861,6 +1892,45 @@ pub fn read_bands_counted_blocking( #[cfg(test)] mod tests { + /// A window of a GeoTIFF in strips (#2592) is read by range, a strip a tile, only its rows' + /// strips; the map doesn't draw the file in place (it is read whole for that, as before). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_window_of_a_geotiff_in_strips_reads_its_rows_by_range() { + let _turn = crate::cache::turn(); + let file = Arc::new(cog::example_strips(300, 200, 2)); + let (bytes, served) = (Arc::new(std::sync::atomic::AtomicU64::new(0)), file.clone()); + let counted = bytes.clone(); + crate::cache::set_fetcher(move |url, done| { + let (a, b) = crate::cache::split_range(&url).1.unwrap(); + let range = served.get(a as usize..((b + 1) as usize).min(served.len())).unwrap_or_default().to_vec(); + counted.fetch_add(range.len() as u64, std::sync::atomic::Ordering::SeqCst); + done(Ok(range)); + }); + let url = "https://strips-cog.invalid/scene.tif"; + let never = std::sync::atomic::AtomicBool::new(false); + let e = super::info_until(url, &never).err().unwrap_or_default(); + assert_eq!(e, format!("{NOT_COG}: a GeoTIFF in strips is read whole")); + assert_eq!(super::probe_blocking(url), Ok(false), "drawn from the file read whole"); + let info = super::window_info_until(url, &never).unwrap(); + assert!(info.layout.strips && info.layout.levels[0].tiles() == 100, "a strip a tile"); + assert!(super::info(url).is_err_and(|e| e.contains(NOT_COG)) && super::info_landed(url).is_none(), "not drawn in place"); + let header = bytes.load(std::sync::atomic::Ordering::SeqCst); + // Columns 40–89 and rows 51–100: the 26 strips of rows 50–101. + let values = super::read_values_blocking(&info, url, 0, 0, (40, 90), (51, 101)).unwrap(); + assert_eq!(values.len(), 50 * 50); + for (i, v) in values.iter().enumerate() { + let (x, y) = (40 + i as i32 % 50, 51 + i as i32 / 50); + assert_eq!(*v, (7 * x - 3 * y) as f32, "cell ({x}, {y})"); + } + let full = &info.layout.levels[0]; + let strips: u64 = full.counts[25..51].iter().sum(); + assert_eq!(bytes.load(std::sync::atomic::Ordering::SeqCst) - header, strips, "only the window's strips are read"); + assert!(strips < file.len() as u64 / 3); + crate::cache::clear_fetcher(); + super::forget_file(url); + } + /// Two callers share cached bytes, but a joining callback never borrows the loader's /// lifetime. Both metadata-to-overview and tile-to-next-tile run the real range reader; /// a retired loader also leaves no successful header or raw tile for later callers.