diff --git a/crates/data/src/raster/cog.rs b/crates/data/src/raster/cog.rs index 5d5970e3b3..f2e715f1b6 100644 --- a/crates/data/src/raster/cog.rs +++ b/crates/data/src/raster/cog.rs @@ -793,14 +793,32 @@ pub fn example(size: u32, tile: u32) -> Vec { /// 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 { + example_strips_in(width, height, rows, None) +} + +/// [`example_strips`] in UTM zone 23 south (EPSG:32723) from easting 200,000 m, northing +/// 7,750,000 m (about 47.8° W, 20.3° S, 3° west of the zone's meridian), in cells of 30 m: its +/// rows lie at an angle to the map's, as a CBERS scene's do. +#[doc(hidden)] +pub fn example_strips_utm(width: u32, height: u32, rows: u32) -> Vec { + example_strips_in(width, height, rows, Some(32723)) +} + +/// [`example_strips`], in longitude/latitude, or in the UTM zone `utm` names. +fn example_strips_in(width: u32, height: u32, rows: u32, utm: Option) -> 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 (cell, corner) = if utm.is_some() { (30.0, (200_000.0, 7_750_000.0)) } else { (0.01, (10.0, 46.0)) }; + let keys = match utm { + Some(code) => vec![1u16, 1, 0, 2, 1024, 0, 1, 1, 3072, 0, 1, code], + None => vec![1u16, 1, 0, 2, 1024, 0, 1, 2, 2048, 0, 1, 4326], + }; 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.encoder().write_tag(Tag::ModelPixelScaleTag, &[cell, cell, 0.0][..])?; + img.encoder().write_tag(Tag::ModelTiepointTag, &[0.0f64, 0.0, 0.0, corner.0, corner.1, 0.0][..])?; + img.encoder().write_tag(Tag::GeoKeyDirectoryTag, &keys[..])?; img.rows_per_strip(rows)?; img.write_data(&values) }); @@ -859,6 +877,8 @@ pub struct Example { pub rounded_down: bool, /// Geographic without an EPSG code (no GeographicTypeGeoKey): read as WGS 84, said. pub no_epsg: bool, + /// In strips of `tile` rows as wide as the image (#2592), no overviews. + pub strips: bool, } impl Default for Example { @@ -884,6 +904,7 @@ impl Default for Example { wavelengths: false, rounded_down: false, no_epsg: false, + strips: false, } } } @@ -896,7 +917,7 @@ pub fn example_with(e: &Example) -> Vec { let planes = if e.planar { nb } else { 1 }; let per_chunk = nb / planes; let mut sizes = vec![size]; - while !e.no_overviews && *sizes.last().unwrap_or(&tile) > tile { + while !e.no_overviews && !e.strips && *sizes.last().unwrap_or(&tile) > tile { let last = *sizes.last().unwrap_or(&tile); sizes.push(if e.rounded_down { last / 2 } else { last.div_ceil(2) }); } @@ -913,13 +934,16 @@ pub fn example_with(e: &Example) -> Vec { .map(|&s| { let k = size / s; let n = s.div_ceil(tile); + // A strip is `tile` rows as wide as the image (the last one what is left). + let (count, cw) = if e.strips { (n, s) } else { (n * n, tile) }; let mut chunks = Vec::new(); for plane in 0..planes { - for i in 0..n * n { - let (tx, ty) = (i % n, i / n); - let mut c = Vec::with_capacity((tile * tile * per_chunk) as usize); - for p in 0..tile * tile { - let (x, y) = (tx * tile + p % tile, ty * tile + p / tile); + for i in 0..count { + let (tx, ty) = if e.strips { (0, i) } else { (i % n, i / n) }; + let ch = if e.strips { tile.min(s - i * tile) } else { tile }; + let mut c = Vec::with_capacity((cw * ch * per_chunk) as usize); + for p in 0..cw * ch { + let (x, y) = (tx * cw + p % cw, ty * tile + p / cw); for b in 0..per_chunk { let band = if e.planar { plane } else { b }; let v = if x < s && y < s { value(x * k, y * k, band) } else { 0 }; @@ -964,7 +988,7 @@ pub fn example_with(e: &Example) -> Vec { }; let mut ifds: Vec> = Vec::new(); for (i, &s) in sizes.iter().enumerate() { - let n = (s.div_ceil(tile) * s.div_ceil(tile) * planes) as usize; + let n = (if e.strips { s.div_ceil(tile) } else { s.div_ceil(tile) * s.div_ceil(tile) } * planes) as usize; let tagged_huge = e.huge || (e.huge_overviews && i > 0); let mut t = vec![ (254u16, V::L(vec![if i == 0 { 0 } else { 1 }])), @@ -987,11 +1011,13 @@ pub fn example_with(e: &Example) -> Vec { (262, V::S(vec![if e.classes && !(e.stray && i == 0) { 3 } else { e.photometric }])), (277, V::S(vec![nb as u16])), (284, V::S(vec![if e.planar { 2 } else { 1 }])), - (322, V::L(vec![tile])), - (323, V::L(vec![tile])), - (324, V::L(vec![0; n])), - (325, V::L(images.get(i).map_or(vec![chunk_len; n], |c| c.iter().map(|c| c.len() as u32).collect()))), ]; + let counts = V::L(images.get(i).map_or(vec![chunk_len; n], |c| c.iter().map(|c| c.len() as u32).collect())); + if e.strips { + t.extend([(273, V::L(vec![0; n])), (278, V::L(vec![tile])), (279, counts)]); + } else { + t.extend([(322, V::L(vec![tile])), (323, V::L(vec![tile])), (324, V::L(vec![0; n])), (325, counts)]); + } // The samples past the colour ones (three of an RGB image, else one): the first alpha // when asked, the others undefined. let colours = if e.photometric == 2 { 3 } else { 1 }; @@ -1065,7 +1091,7 @@ pub fn example_with(e: &Example) -> Vec { out.extend_from_slice(&header_len.to_le_bytes()); for (lvl, t) in ifds.iter_mut().enumerate() { for (tag, v) in t.iter_mut() { - if *tag == 324 + if (*tag == 324 || *tag == 273) && let V::L(offs) = v { for (j, o) in offs.iter_mut().enumerate() { diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 02e4f06e21..8263ccc264 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -5508,7 +5508,12 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { // and anything that doesn't answer as one is downloaded whole, as before. let unnamed = !tiff && is_unnamed_url(url); if (tiff || unnamed) && !scan && !super::b(p, "whole").unwrap_or(false) { - let cog = match crate::render::rustgis_tiles::cog::probe_blocking(url) { + // A data cube's file is asked for as one: a GeoTIFF in strips is drawn in place then + // (#2592), where a single one is downloaded whole. + let (_, mut look) = crate::render::rustgis_tiles::cog::split(url); + look.cube |= super::b(p, "cube") == Some(true); + let asked = crate::render::rustgis_tiles::cog::with_look(url, &look); + let cog = match crate::render::rustgis_tiles::cog::probe_blocking(&asked) { Ok(cog) => cog, Err(_) if unnamed => false, Err(e) => return Err(named(e)), diff --git a/crates/engine/src/cmd/stac.rs b/crates/engine/src/cmd/stac.rs index ded3c22717..5a60a50b3d 100644 --- a/crates/engine/src/cmd/stac.rs +++ b/crates/engine/src/cmd/stac.rs @@ -1000,6 +1000,15 @@ pub fn stac_cube(s: &mut Session, p: &Value) -> Result { } else { (level, 1) }; + // The cells read, said when they aren't the size asked (the overview nearest it, or a whole + // number of a file in strips' cells): the cube is that much finer or coarser. + if let Some(size) = size { + let got = lt.pixel_width.abs(); + if (got - size).abs() > size * 1e-6 { + let show = |v: f64| format!("{v:.9}").trim_end_matches('0').trim_end_matches('.').to_string(); + s.notify(format!("cellSize {} is read as {}: the files' cells nearest it", show(size), show(got)), false); + } + } let read_tile_rows = layout.levels.get(read).map_or(1, |l| l.tile_height).div_ceil(factor).max(1); // The area, in the files' coordinates: the box's edges, each at 32 points, as a curved grid // (MODIS's sinusoidal) bends them. A point the system refuses (one it can't bring back, @@ -1772,7 +1781,17 @@ fn add_cube(s: &mut Session, p: &Value) -> CmdResult { m.layers.retain(|l| layers_before.contains(&l.id)); }; for (tile, by_day) in &tiles { - let urls: Vec<(f64, String)> = by_day.iter().map(|(d, u)| (*d as f64 * 86_400_000.0, format!("{u}{look}"))).collect(); + // Each date's file keeps the cube's look, and says it is a data cube's: the map draws + // it in place in strips too (#2592), at every date the slider shows. + let urls: Vec<(f64, String)> = by_day + .iter() + .map(|(d, u)| { + let file = format!("{u}{look}"); + let mut cube = crate::render::rustgis_tiles::cog::split(&file).1; + cube.cube = true; + (*d as f64 * 86_400_000.0, crate::render::rustgis_tiles::cog::with_look(&file, &cube)) + }) + .collect(); let Some((_, first)) = urls.first() else { continue }; let name = if many { format!("{base} {tile}") } else { base.clone() }; let r = match super::layer::add_url(s, &json!({"url": first, "name": name, "cube": true, "connection": p.get("connection")})) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0383d19d11..22ab2b44b7 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -34002,7 +34002,12 @@ fn a_static_collection_by_date_as_a_data_cube() { assert!(!said.iter().any(|t| t.contains("left out, as their codes")), "codes read whole leave nothing out: {said:?}"); let tile = &s.map().tiles[0]; assert_eq!(tile.time_urls.len(), 2); - assert!(tile.time_urls[0].1.ends_with("/2024-01.tiff#range=0,100"), "the range through je:rasters' slope: {}", tile.time_urls[0].1); + // The range through je:rasters' slope, and a data cube's file (drawn in place in strips too). + assert!( + tile.time_urls[0].1.ends_with("/2024-01.tiff#range=0,100&cube=1"), + "the range through je:rasters' slope: {}", + tile.time_urls[0].1 + ); // A document missing: its date is left out, and said. let mut gap = Session::new(Project::default()); let mark = gap.notice_mark(); @@ -34049,6 +34054,21 @@ fn a_static_collection_by_date_as_a_data_cube() { assert!(e.contains("1 item(s) left out, as their codes for a failed retrieval"), "{e}"); } +/// A GeoTIFF in strips too large to read in place (#2592): one strip of 1,048,576 rows, 64 MiB +/// once read, which even a data cube's file is refused for, as one that isn't cloud-optimised. +fn strips_too_large() -> Vec { + let mut file = rustgis_data::raster::cog::example_strips(16, 8, 8); + 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) { + // ImageLength and RowsPerStrip, both LONG. + if matches!(u16::from_le_bytes(file[e..e + 2].try_into().unwrap()), 257 | 278) { + file[e + 8..e + 12].copy_from_slice(&(1u32 << 20).to_le_bytes()); + } + } + file +} + /// A STAC collection's band as a data cube on the time slider (#559), from a local API: a tile /// layer per grid tile, each a file per date; the slider on over their dates; a fixed range in the /// band's own units, through its scale; a tile with no date in the window drawn as nothing. @@ -34122,7 +34142,7 @@ fn a_stac_data_cube_on_the_time_slider() { // A file per date (the first item of a tile and day), the range in stored values (0.9 / 0.0001). assert_eq!(t1.time_urls.len(), 2); assert_eq!(t2.time_urls.len(), 1); - assert!(t1.time_urls.iter().all(|(_, u)| u.ends_with("#range=0,9000")), "{:?}", t1.time_urls); + assert!(t1.time_urls.iter().all(|(_, u)| u.ends_with("#range=0,9000&cube=1")), "{:?}", t1.time_urls); assert!(t2.time_urls[0].1.contains("/b1.tif")); // The slider: on, over the two dates; at the first, both tiles draw. assert_eq!(s.run("time.info", &Value::Null).unwrap()["steps"], 2); @@ -34153,22 +34173,10 @@ fn a_stac_data_cube_on_the_time_slider() { ] { assert!(s.run("stac.addCube", &bad).is_err(), "{bad}"); } - // A file read whole (a GeoTIFF that isn't cloud-optimised) can't follow the slider: the cube - // is refused, and what it added is taken back, the view its first tile framed included. - let gt = rustgis_data::raster::GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 0.5, pixel_height: -0.5 }; - let plain = rustgis_data::raster::Raster::new( - "p", - 2, - 2, - vec![vec![1.0; 4]], - gt, - rustgis_data::raster::Crs::LonLat, - None, - rustgis_data::raster::ColorHint::Gray, - "Float32", - ) - .unwrap(); - let (file, _) = serve_ranges(rustgis_data::raster::geotiff::write(&plain, 0).unwrap()); + // A file read whole (a GeoTIFF that can't be read in place, even as a data cube's) can't + // follow the slider: the cube is refused, and what it added is taken back, the view its first + // tile framed included. + let (file, _) = serve_ranges(strips_too_large()); let one = format!( r#"{{"type": "Feature", "id": "p1", "collection": "cube", "bbox": [10, 45, 11, 46], "geometry": null, "properties": {{"datetime": "2024-01-01T00:00:00Z", "bdc:tiles": ["P"]}}, "assets": {{"NDVI": {{"href": "{file}/p.tif"}}}}}}"# @@ -34184,7 +34192,8 @@ fn a_stac_data_cube_on_the_time_slider() { &json!({"url": format!("{plain_api}/v1"), "collection": "cube", "asset": "ndvi", "bbox": [10, 45, 11, 46], "start": "2024-01-01", "end": "2024-01-31"}), ) .unwrap_err(); - assert!(e.contains("not a cloud-optimised"), "{e}"); + // Downloaded whole as such a file is, it can't be read (its strips are past the bytes). + assert!(e.contains("/p.tif"), "{e}"); assert_eq!((s.map().tiles.len(), s.map().layers.len()), (tiles, layers)); // The view tile A framed and the slider are put back too. assert_eq!(s.map().camera, camera); @@ -34252,7 +34261,7 @@ fn a_stac_data_cube_from_a_plugin_command_in_the_app() { assert!(s.take_url_requests().is_empty(), "a cube's files are read in place, not left to the app to download"); let t1 = s.map().tiles.iter().find(|t| t.name.ends_with("T1")).unwrap(); assert_eq!(t1.time_urls.len(), 2); - assert!(t1.time_urls.iter().all(|(_, u)| u.ends_with("#range=0,9000")), "{:?}", t1.time_urls); + assert!(t1.time_urls.iter().all(|(_, u)| u.ends_with("#range=0,9000&cube=1")), "{:?}", t1.time_urls); assert_eq!(s.map().tiles.iter().filter(|t| !t.time_urls.is_empty()).count(), 2); assert_eq!(s.run("time.info", &Value::Null).unwrap()["steps"], 2); s.run("time.goTo", &json!({"step": 1})).unwrap(); @@ -34285,14 +34294,9 @@ fn a_stac_data_cube_from_a_plugin_command_in_the_app() { assert!(e.contains("left to the app to download") && !e.contains("not a cloud-optimised"), "{e}"); assert_eq!((s.map().tiles.len(), s.map().layers.len()), (tiles, layers)); assert!(s.take_url_requests().is_empty(), "the failed command's request is taken back with it"); - // A file that isn't cloud-optimised is added all the same (its header isn't read on the + // A file that can't be read in place is added all the same (its header isn't read on the // frame); its header's read fails, and the map drawing it says why, as for any tile layer. - let gt = rustgis_data::raster::GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 0.5, pixel_height: -0.5 }; - let crs = rustgis_data::raster::Crs::LonLat; - let plain = - rustgis_data::raster::Raster::new("p", 2, 2, vec![vec![1.0; 4]], gt, crs, None, rustgis_data::raster::ColorHint::Gray, "Float32") - .unwrap(); - let (stripped, _) = serve_ranges(rustgis_data::raster::geotiff::write(&plain, 0).unwrap()); + let (stripped, _) = serve_ranges(strips_too_large()); let one = item("p1", "P", "2024-01-01", "p1.tif").replace(&format!("{cog}/"), &format!("{stripped}/")); let stripped_api = serve_routes(vec![("/v1/search", format!(r#"{{"type": "FeatureCollection", "features": [{one}]}}"#))], 2); let mut flat = Session::new(Project::default()); @@ -34421,6 +34425,7 @@ fn an_entry_without_a_range_takes_one_from_its_files() { assert_eq!(r["rangeFrom"], "sample"); let look = format!("#range={},{}", range[0] / 0.0001, range[1] / 0.0001); let tile = &s.map().tiles[0]; + let look = format!("{look}&cube=1"); assert!(tile.time_urls.len() == 2 && tile.time_urls.iter().all(|(_, u)| u.ends_with(&look)), "{:?} {look}", tile.time_urls); assert_eq!(tile.attribution, "JAXA, A test dataset"); assert_eq!( @@ -34434,7 +34439,7 @@ fn an_entry_without_a_range_takes_one_from_its_files() { // A range given takes its place, as for any entry. let mut t = Session::new(Project::default()); let r = crate::cmd::cube_catalog::open_entry(&mut t, &entry, &json!({"bbox": [10, 45, 11, 46], "range": [0, 0.01]})).unwrap(); - assert!(r.get("rangeFrom").is_none() && t.map().tiles[0].time_urls.iter().all(|(_, u)| u.ends_with("#range=0,100")), "{r}"); + assert!(r.get("rangeFrom").is_none() && t.map().tiles[0].time_urls.iter().all(|(_, u)| u.ends_with("#range=0,100&cube=1")), "{r}"); // Other text is refused, naming "auto", before anything is read. assert!( t.run("stac.addCube", &json!({"url": entry.url, "collection": "cube", "asset": "B1", "range": "wide"})) @@ -34635,7 +34640,7 @@ fn a_catalog_entry_opens_as_its_command_would() { .unwrap(); let urls = |s: &Session| s.map().tiles.iter().map(|t| t.time_urls.clone()).collect::>(); assert_eq!(urls(&by_entry), urls(&typed), "the same files, the entry's range in stored values"); - assert!(urls(&by_entry)[0].iter().all(|(_, u)| u.ends_with("#range=0,9000"))); + assert!(urls(&by_entry)[0].iter().all(|(_, u)| u.ends_with("#range=0,9000&cube=1"))); // As one step: undone, the cube goes. by_entry.run("edit.undo", &Value::Null).unwrap(); assert!(by_entry.map().tiles.is_empty()); @@ -34644,7 +34649,7 @@ fn a_catalog_entry_opens_as_its_command_would() { crate::cmd::cube_catalog::open_entry(&mut by_entry, &entry, &json!({"bbox": [10, 45, 11, 46], "range": [0, 0.5], "name": "NDVI"})) .unwrap(); assert_eq!(r["layers"], 1); - assert!(by_entry.map().tiles[0].time_urls.iter().all(|(_, u)| u.ends_with("#range=0,5000"))); + assert!(by_entry.map().tiles[0].time_urls.iter().all(|(_, u)| u.ends_with("#range=0,5000&cube=1"))); assert_eq!(by_entry.map().tiles[0].name, "NDVI"); // Refused before anything is added: an area the entry has no data in, a period outside its // dates, one end of the period alone. diff --git a/crates/engine/src/tests/cube_strips.rs b/crates/engine/src/tests/cube_strips.rs index 9883528d41..2f3df82e81 100644 --- a/crates/engine/src/tests/cube_strips.rs +++ b/crates/engine/src/tests/cube_strips.rs @@ -4,10 +4,10 @@ use super::*; /// Two dates of a 300 × 200 file of 0.01° cells from 10° E, 46° N, a row a strip, cell (x, y) -/// 7 x − 3 y: the API's address. -fn collection() -> String { +/// 7 x − 3 y: the API's address, and the files' requests (a path and its range, empty when whole). +fn collection() -> (String, std::sync::Arc>>) { let file = rustgis_data::raster::cog::example_strips(300, 200, 1); - let (files, _) = serve_ranged_files(vec![("/a.tif".into(), file.clone()), ("/b.tif".into(), file)]); + let (files, asked) = serve_ranged_files(vec![("/a.tif".into(), file.clone()), ("/b.tif".into(), file)]); let features: Vec = [("a", "2026-04-02"), ("b", "2026-05-04")] .iter() .map(|(id, d)| { @@ -19,7 +19,7 @@ fn collection() -> String { }) .collect(); let search = format!(r#"{{"type": "FeatureCollection", "features": [{}]}}"#, features.join(",")); - format!("{}/v1", serve_routes(vec![("/v1/search", search)], 64)) + (format!("{}/v1", serve_routes(vec![("/v1/search", search)], 64)), asked) } /// The first raster `cube.reduce` adds for `p`. @@ -35,7 +35,7 @@ fn reduce(s: &mut Session, p: &Value) -> std::sync::Arc = asked.lock().unwrap().iter().filter(|(_, range)| range.is_empty()).cloned().collect(); + assert!(whole.is_empty(), "downloaded whole: {whole:?}"); +} + +/// A cube's cellSize read at another size, the nearest whole number of a file in strips' cells, +/// says so (AGENTS.md, Never silent); one that is a whole number of them says nothing. +#[test] +fn a_cubes_cell_size_read_at_another_size_says_so() { + let (api, _) = collection(); + let mut s = Session::new(Project::default()); + let mut said = |size: f64| { + let p = json!({"url": api, "collection": "wpm", "asset": "BAND0", "bbox": [10.5, 45.0, 10.8, 45.3], "start": "2026-04-01", + "end": "2026-05-31", "stat": "mean", "cellSize": size, "resampling": "average"}); + let mark = s.notice_mark(); + reduce(&mut s, &p); + s.notices_since(mark).iter().map(|n| n.text.clone()).collect::>() + }; + let even = said(0.03); + assert!(!even.iter().any(|n| n.contains("is read as")), "{even:?}"); + let rounded = said(0.025); + assert!(rounded.iter().any(|n| n.contains("cellSize 0.025 is read as 0.03")), "{rounded:?}"); +} diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index a1dab3aa7e..131b149008 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -43,6 +43,8 @@ const MAX_ROUNDS: usize = 12; const MAX_AT: u64 = u64::MAX >> 1; /// The most COG tiles one map tile may need (past that, a coarser overview is read). const MAX_PER_TILE: usize = 16; +/// The most strips of a GeoTIFF in strips one map tile takes (#2592): two a row of its pixels. +const MAX_STRIPS_PER_TILE: usize = 2 * SIZE as usize; /// The most tiles of the coarsest overview read for the stretch. const MAX_STATS_TILES: usize = 16; /// Decoded tiles kept, in samples. @@ -373,14 +375,14 @@ fn forget_file_in(t: &mut Tiles, url: &str) { pub fn info(url: &str) -> Result>, String> { crate::cache::check_still(&crate::cache::current_still())?; crate::logins::check(url).map_err(str::to_string)?; - let url = split(url).0; + let (url, look) = split(url); // A local file written again since its header was read is read again (as with `with_info`). #[cfg(not(target_arch = "wasm32"))] forget_if_rewritten(url); { 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 drawn(info.clone()).map(Some), + Some(State::Ready(info, reach)) if *reach <= crate::cache::ceiling_for(url) => return drawn(info.clone(), look.cube).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. @@ -403,9 +405,9 @@ pub fn info(url: &str) -> Result>, String> { pub fn info_landed(url: &str) -> Option> { crate::cache::check_still(&crate::cache::current_still()).ok()?; crate::logins::check(url).ok()?; - let url = split(url).0; + let (url, look) = split(url); match infos().lock().unwrap_or_else(|e| e.into_inner()).get(url) { - Some(State::Ready(info, reach)) if *reach <= crate::cache::ceiling_for(url) => drawn(info.clone()).ok(), + Some(State::Ready(info, reach)) if *reach <= crate::cache::ceiling_for(url) => drawn(info.clone(), look.cube).ok(), _ => None, } } @@ -446,7 +448,12 @@ 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_drawn_info(url, false, then); +} + +/// [`with_info`], a file in strips too when it is a data cube's (`cube`, [`drawn`]). +fn with_drawn_info(url: &str, cube: bool, then: Box, String>) + Send>) { + with_any_info(url, Box::new(move |r| then(r.and_then(|info| drawn(info, cube))))); } /// [`with_info`], a file in strips too: for a window read from its strips ([`window_info_until`]). @@ -454,11 +461,12 @@ fn with_any_info(url: &str, then: Box, String>) + Se 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) } +/// A file's header, for the map to draw it in place. A file in strips (#2592) is drawn in place +/// when it is a data cube's (`cube`: a scene a date, too large to download for each, such as the +/// Brazil Data Cube's), a map tile from the strips of its rows; any other is refused as before, so +/// the map draws it from the file read whole. +fn drawn(info: Arc, cube: bool) -> Result, String> { + if info.layout.strips && !cube { 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. @@ -912,8 +920,17 @@ fn with_stretch(info: Arc, file: String, look: Look, then: StretchThen) { let colour = info.colour(&look); let coarsest = stats_level(&info.layout.levels); let n = info.layout.levels.get(coarsest).map(|l| l.tiles() as usize).unwrap_or(0); - // Too many tiles to read for it: the values' full range for the type. - if n == 0 || n > MAX_STATS_TILES { + // A file in strips (a data cube's, #2592): strips spread down the image, each the image's + // width, as many as a stretch reads tiles and half the tiles' budget holds (the bound a map + // tile's strips keep, see `draw`); none when not even one fits. + // A strip's values read, every band of it read when they are stored apart. + let bands = if info.layout.planar { info.shown_from(colour.clone()).len().max(1) } else { info.layout.chunk_bands() }; + let per = info.layout.levels.get(coarsest).map_or(0, |l| l.tile_width as usize * l.tile_height as usize * bands); + let take = if info.layout.strips { n.min(MAX_STATS_TILES).min(BUDGET / 2 / per.max(1)) } else { n.min(MAX_STATS_TILES) }; + let tiles: Vec = + if info.layout.strips { (0..take).map(|k| (k * n / take.max(1)) as u32).collect() } else { (0..take as u32).collect() }; + // Too many tiles to read for it, or strips too large: the values' full range for the type. + if take == 0 || (n > MAX_STATS_TILES && !info.layout.strips) { let s = vec![type_range(&info.layout, look.aef); colour.len()]; keep_stretch(&info, (colour, look.aef), s.clone()); then(Ok(s)); @@ -934,7 +951,6 @@ fn with_stretch(info: Arc, file: String, look: Look, then: StretchThen) { } reading.insert(key.clone(), vec![then]); } - let tiles: Vec = (0..n as u32).collect(); let i = info.clone(); let shown_bands = colour.len(); let key_aef = look.aef; @@ -1376,8 +1392,9 @@ pub(crate) fn fetch(url: &str, done: Done) { let (file, look) = split(&archive); let file = file.to_string(); let f = file.clone(); - with_info( + with_drawn_info( &file, + look.cube, Box::new(move |info| match info { Ok(info) => { let i = info.clone(); @@ -1397,8 +1414,11 @@ pub(crate) fn fetch(url: &str, done: Done) { ); } -/// Where each pixel of a map tile falls in the file, at a level: (tile, sample) or none. -fn locate(info: &Info, level: usize, native: &[Option]) -> Vec> { +/// Where each pixel of a map tile falls in the file, at a level: (tile, sample) or none. Its row is +/// the middle one of its block of `rows` (1: its own), so a map tile far coarser than a file in +/// strips takes one strip in `rows`, not one a pixel where the file's rows lie at an angle to the +/// map's (#2592). +fn locate(info: &Info, level: usize, native: &[Option], rows: u32) -> Vec> { let Some(l) = info.layout.levels.get(level) else { return vec![None; native.len()] }; let t = info.layout.transform_of(l); let (tw, th) = (l.tile_width.max(1), l.tile_height.max(1)); @@ -1412,12 +1432,18 @@ fn locate(info: &Info, level: usize, native: &[Option]) -> Vec u32 { + if rows > 1 { (py / rows * rows).saturating_add(rows / 2).min(height.saturating_sub(1)) } else { py } +} + fn draw(info: Arc, url: String, look: &Look, stretch: &[(f32, f32)], z: u8, x: u32, y: u32, done: Done) { let n = (1u64 << z) as f64; let size = 2.0 * HALF / n; @@ -1472,12 +1498,18 @@ fn draw(info: Arc, url: String, look: &Look, stretch: &[(f32, f32)], z: u8 .find(|(_, l)| info.layout.transform_of(l).pixel_width.abs() <= target * 1.25) .map(|(i, _)| i) .unwrap_or(0); + // A file in strips (a data cube's, #2592): about a strip a row of the map tile's pixels, + // whatever its scale, as a strip is the image's width. + let (most, cap) = if info.layout.strips { (MAX_STRIPS_PER_TILE, MAX_STRIPS_PER_TILE) } else { (MAX_PER_TILE, MAX_PER_TILE * 4) }; let (spots, wanted) = loop { - let spots = locate(&info, level, &native); + // A file in strips: the rows a map tile's pixel spans at this level, one strip of them read. + let cell = levels.get(level).map_or(0.0, |l| info.layout.transform_of(l).pixel_height.abs()); + let rows = if info.layout.strips && cell > 0.0 { (target / cell).floor().clamp(1.0, f64::from(u32::MAX)) as u32 } else { 1 }; + let spots = locate(&info, level, &native, rows); let mut wanted: Vec = spots.iter().flatten().map(|(t, _)| *t).collect(); wanted.sort_unstable(); wanted.dedup(); - if wanted.len() <= MAX_PER_TILE || level + 1 >= levels.len() { + if wanted.len() <= most || level + 1 >= levels.len() { break (spots, wanted); } level += 1; @@ -1486,13 +1518,21 @@ fn draw(info: Arc, url: String, look: &Look, stretch: &[(f32, f32)], z: u8 done(Ok(Vec::new())); return; } - if wanted.len() > MAX_PER_TILE * 4 { + if wanted.len() > cap { done(Err("too many GeoTIFF tiles for one map tile".into())); return; } let colour = info.colour(look); let colours = colour.len(); let shown = info.shown_from(colour); + // The strips kept for one map tile within half the tiles' budget, so the next one's fit too: + // each strip's values read, every band shown when they are stored apart. + let bands = if info.layout.planar { shown.len().max(1) } else { info.layout.chunk_bands() }; + let per = levels.get(level).map_or(0, |l| l.tile_width as usize * l.tile_height as usize * bands); + if info.layout.strips && wanted.len().saturating_mul(per) > BUDGET / 2 { + done(Err(format!("{} strips of {per} values for one map tile: too wide to draw in place", wanted.len()))); + return; + } let pen = Pen { rgb: colours >= 3, // The alpha band where it is among those shown: after the colours, or one of them. @@ -1660,10 +1700,10 @@ pub fn forget_dropped(url: &str) { /// line): `Ok(false)` for any other file, read whole instead. #[cfg(not(target_arch = "wasm32"))] pub fn probe_blocking(url: &str) -> Result { - let url = split(url).0; + let (url, look) = split(url); ask_again_if_dropped(url); let (tx, rx) = std::sync::mpsc::channel(); - with_info(url, Box::new(move |r| tx.send(r.map(|_| ())).unwrap_or_default())); + with_drawn_info(url, look.cube, Box::new(move |r| tx.send(r.map(|_| ())).unwrap_or_default())); match rx.recv_timeout(std::time::Duration::from_secs(60)) { Ok(Ok(())) => Ok(true), Ok(Err(e)) if read_whole(&e) => Ok(false), @@ -1675,10 +1715,11 @@ pub fn probe_blocking(url: &str) -> Result { /// Whether the file at `url` is a cloud-optimised GeoTIFF, off the frame (the app): `then` gets /// `Ok(false)` for any other file, read whole instead. pub fn probe(url: &str, then: Box) + Send>) { - let url = split(url).0; + let (url, look) = split(url); ask_again_if_dropped(url); - with_info( + with_drawn_info( url, + look.cube, Box::new(move |r| { then(match r { Ok(_) => Ok(true), @@ -1720,15 +1761,12 @@ pub fn window_info_until(url: &str, stop: &std::sync::atomic::AtomicBool) -> Res /// [`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; + let (url, look) = split(url); ask_again_if_dropped(url); let (tx, rx) = std::sync::mpsc::channel(); 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) - } + // A data cube's file in strips is drawn in place too ([`drawn`]). + with_drawn_info(url, strips || look.cube, then); wait_until(&rx, Duration::from_secs(120), stop).map_err(|stopped| stopped_or(stopped, url, "no answer in two minutes"))? } @@ -2252,6 +2290,139 @@ mod tests { super::forget_file(url); } + /// A data cube's GeoTIFF in strips (#2592) is drawn in place: a map tile from the strips of + /// its rows, read by range and kept, its stretch from strips spread down the image. Any other + /// address of it is refused, as a file the map reads whole. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_data_cubes_geotiff_in_strips_is_drawn_from_its_strips() { + let _turn = crate::cache::turn(); + let file = Arc::new(cog::example_strips(300, 200, 1)); + let (bytes, _) = serve_strips(file.clone(), Arc::new(AtomicU64::new(u64::MAX)), 0); + let url = "https://strips-cog.invalid/cube.tif"; + let cube = format!("{url}#cube=1"); + assert_eq!(super::probe_blocking(url), Ok(false), "a single file is read whole"); + assert_eq!(super::probe_blocking(&cube), Ok(true), "a cube's is drawn in place"); + // Map tile 6/33/23 (5.6° to 11.3° E, 41° to 45.1° N) over the file's south-west. + let tile = |address: &str| { + let (tx, rx) = std::sync::mpsc::channel(); + super::fetch(&format!("cog:6/33/23@{address}"), Box::new(move |r| tx.send(r).unwrap_or_default())); + rx.recv_timeout(Duration::from_secs(20)).unwrap() + }; + assert!(tile(url).is_err_and(|e| e.contains(NOT_COG)), "not drawn as a single file"); + let before = bytes.load(Ordering::SeqCst); + assert!(!tile(&cube).unwrap().is_empty(), "drawn"); + let read = bytes.load(Ordering::SeqCst) - before; + assert!(read > 0 && read < file.len() as u64 * 2 / 3, "{read} bytes of {}", file.len()); + let kept = bytes.load(Ordering::SeqCst); + assert!(!tile(&cube).unwrap().is_empty()); + assert_eq!(bytes.load(Ordering::SeqCst), kept, "drawn again from the strips kept"); + // The values run from −597 to 2093: not the type's full range. + let info = super::info(&cube).unwrap().unwrap(); + let stretch = info.stretch.lock().unwrap().values().next().cloned().unwrap(); + assert!(stretch[0].0 > -1000.0 && stretch[0].1 < 2200.0, "{stretch:?}"); + crate::cache::clear_fetcher(); + super::forget_file(url); + } + + /// A data cube's scene in strips in UTM, its rows at an angle to the map's, drawn by a map tile + /// far coarser than its cells (#2592): the tile takes one strip in so many, not a strip a + /// pixel, so it stays within the strips a map tile reads. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_map_tile_far_coarser_than_a_scene_in_strips_takes_one_strip_in_so_many() { + let _turn = crate::cache::turn(); + // 2,000 × 2,000 cells of 30 m, a row a strip: 60 km a side. + let file = Arc::new(cog::example_strips_utm(2000, 2000, 1)); + serve_strips(file, Arc::new(AtomicU64::new(u64::MAX)), 0); + let cube = "https://strips-cog.invalid/utm.tif#cube=1"; + let info = super::window_info_until(cube, &std::sync::atomic::AtomicBool::new(false)).unwrap(); + // The zoom-7 map tile (about 300 km a side, 39 rows a pixel) holding the scene's middle. + let [w, s, e, n] = info.bounds; + let (lon, lat) = ((w + e) / 2.0, ((s + n) / 2.0).to_radians()); + let x = ((lon + 180.0) / 360.0 * 128.0) as u32; + let y = ((1.0 - (lat.tan() + 1.0 / lat.cos()).ln() / std::f64::consts::PI) / 2.0 * 128.0) as u32; + let (tx, rx) = std::sync::mpsc::channel(); + super::fetch(&format!("cog:7/{x}/{y}@{cube}"), Box::new(move |r| tx.send(r).unwrap_or_default())); + let drawn = rx.recv_timeout(Duration::from_secs(60)).unwrap(); + assert!(drawn.as_ref().is_ok_and(|t| !t.is_empty()), "drawn at zoom 7 ({x}, {y}): {:?}", drawn.err()); + crate::cache::clear_fetcher(); + super::forget_file(cube); + } + + /// The stretch of a data cube's file in wide, tall strips (#2592) reads only as many strips as + /// half the tiles' budget holds, the bound a map tile's strips keep, not 16 whatever their size. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_stretch_of_large_strips_reads_what_half_the_budget_holds() { + let _turn = crate::cache::turn(); + // 16 strips of 2,560 × 1,024 cells: 2.6 million values each, 42 million in all. + let file = Arc::new(cog::example_strips(2560, 16 * 1024, 1024)); + let (_, asked) = serve_strips(file, Arc::new(AtomicU64::new(u64::MAX)), 0); + let cube = "https://strips-cog.invalid/wide.tif#cube=1"; + let info = super::window_info_until(cube, &std::sync::atomic::AtomicBool::new(false)).unwrap(); + let before = asked.load(Ordering::SeqCst); + let (tx, rx) = std::sync::mpsc::channel(); + super::with_stretch(info, split(cube).0.into(), Look::default(), Box::new(move |r| tx.send(r).unwrap_or_default())); + assert!(rx.recv_timeout(Duration::from_secs(120)).unwrap().is_ok()); + let (read, fit) = (asked.load(Ordering::SeqCst) - before, BUDGET / 2 / (2560 * 1024)); + assert!(read as usize <= fit, "{read} strips read for the stretch; half the budget holds {fit}"); + crate::cache::clear_fetcher(); + super::forget_file(cube); + } + + /// A data cube's file in strips whose bands are stored apart (planar) is bounded by every band + /// it reads, not one: its stretch reads no more strips of its three than half the tiles' + /// budget holds, and a map tile whose strips of the three pass it is refused (#2592). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_bounds_of_a_planar_file_in_strips_count_every_band_read() { + let _turn = crate::cache::turn(); + // 4,096 × 4,096 signed bytes in three planes, strips of 256 rows: 16 a band, 1 million + // values each. + let example = cog::Example { + size: 4096, + tile: 256, + bands: 3, + planar: true, + photometric: 2, + int8: true, + strips: true, + ..cog::Example::default() + }; + let file = Arc::new(cog::example_with(&example)); + let (_, asked) = serve_strips(file, Arc::new(AtomicU64::new(u64::MAX)), 0); + let cube = "https://strips-cog.invalid/planar.tif#cube=1"; + let info = super::window_info_until(cube, &std::sync::atomic::AtomicBool::new(false)).unwrap(); + assert!(info.layout.strips && info.layout.planar && info.layout.levels[0].tiles() == 16); + let before = asked.load(Ordering::SeqCst); + let (tx, rx) = std::sync::mpsc::channel(); + super::with_stretch(info.clone(), split(cube).0.into(), Look::default(), Box::new(move |r| tx.send(r).unwrap_or_default())); + assert!(rx.recv_timeout(Duration::from_secs(120)).unwrap().is_ok()); + let read = (asked.load(Ordering::SeqCst) - before) as usize * 4096 * 256; + assert!(read <= BUDGET / 2, "the stretch read {read} values; half the budget is {}", BUDGET / 2); + // The zoom-6 map tile over the whole image: its 16 strips of three bands, 50 million values. + let [w, s, e, n] = info.bounds; + let (lon, lat) = ((w + e) / 2.0, ((s + n) / 2.0).to_radians()); + let x = ((lon + 180.0) / 360.0 * 64.0) as u32; + let y = ((1.0 - (lat.tan() + 1.0 / lat.cos()).ln() / std::f64::consts::PI) / 2.0 * 64.0) as u32; + let (tx, rx) = std::sync::mpsc::channel(); + super::fetch(&format!("cog:6/{x}/{y}@{cube}"), Box::new(move |r| tx.send(r).unwrap_or_default())); + let drawn = rx.recv_timeout(Duration::from_secs(120)).unwrap(); + assert!(drawn.as_ref().is_err_and(|e| e.contains("too wide to draw in place")), "{:?}", drawn.map(|t| t.len())); + crate::cache::clear_fetcher(); + super::forget_file(cube); + } + + /// A row's block (`locate`, #2592): its middle row, within the file, a block as large as a + /// malformed file's height allows included. + #[test] + fn a_rows_block_is_its_middle_row_within_the_file() { + assert_eq!((super::block_row(7, 1, 10), super::block_row(7, 4, 10), super::block_row(9, 4, 10)), (7, 6, 9)); + // The block from 3,000,000,000: its middle (4,500,000,000) is past `u32`, so the file's last row. + assert_eq!(super::block_row(u32::MAX - 1, 3_000_000_000, u32::MAX), u32::MAX - 1); + } + /// A read of strips stopped before it starts asks for none, and one whose address may reach /// less once its strips are under way fails with [`super::REACH_CHANGED`], as a tile does. #[cfg(not(target_arch = "wasm32"))]