diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index d7f0869a40..632cfa3338 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -51,7 +51,7 @@ pub fn commands() -> Vec { .params(r#"{"layer"?: name|id, "crs": "EPSG:… or WKT; reinterpret native coordinates, without rewriting the source file"}"#), C::new("layer.loadAll", "Load All Features", "Layers", load_all).roles(&[]).effects(crate::policy::Effects::NONE).when(need_streamed).params(r#"{"layer"?: name|id}"#), C::new("layer.addUrl", "Add Data From URL", "Home › Add › Add Data", add_url).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (desktop and command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km)", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, + r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (desktop and command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km); a GeoTIFF in strips, which has no overviews, takes one strip and column in as many as that size holds", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, ), C::new("layer.addDownload", "Add Downloaded Data", "Home › Add", add_download).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files)) .params(r#"{"id": a download the app finished (Home › Add › Add Data › From URL), "url": its address, "name"?: text, "layer"?: text, "zoom"?: bool, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "service"?: bool (a service's features: their axes (when they came as GeoJSON) and paging are checked, and the address is kept as the layer's source), "bounds"?: [west, south, east, north] (with service: the layer's longitude/latitude bounds from its capabilities, which its axes are checked against; without bounds they are left as they come; ignored without service), "coverage"?: bool (a WCS coverage: a GeoTIFF, else the service's error, and its request kept as the layer's source), "coverageCrs"?: "EPSG:" (internal, with coverage: the system service.coverage's request asks it in (its coverageCrs), for an answer that doesn't say its own, when the address doesn't say it), "drawingInfo"?: object (internal, with service: an ArcGIS layer's drawingInfo from its description, which the layer is drawn with), "geolibreProject"?: bool (internal: downloaded project JSON), "geolibreLayer"?: {"token", "record"} (internal: reserved imported layer and its saved style), "geolibreZarr"?: bool (internal: an imported Zarr slice as GeoTIFF), "connection"?: "as layer.addUrl", "anonymous"?: bool (internal: preserves a plugin-origin download's anonymous reads), "request"?: number (internal: the download a plugin command left to the app, #1202), "window"?: {"bbox", "cellSize"?, "cog"?} (internal: what a cloud-optimised GeoTIFF's window the app read off the frame asked for, for a task to read it again, #1330)}"#), @@ -6715,9 +6715,10 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic:: ); (c0, c1, r0, r1) }; - let values = |l: &Level| { + // A level's window's values, taking every `step`-th column and row. + let values = |l: &Level, step: u32| { let (c0, c1, r0, r1) = window(l); - u64::from(c1 - c0).saturating_mul(u64::from(r1 - r0)).saturating_mul(layout.bands.max(1) as u64) + u64::from((c1 - c0).div_ceil(step)).saturating_mul(u64::from((r1 - r0).div_ceil(step))).saturating_mul(layout.bands.max(1) as u64) }; // The full image, or the coarsest overview whose cells are no larger than the size asked. A // size finer than the full image's cells reads the full image, and says so. @@ -6730,6 +6731,12 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic:: if c1 <= c0 || r1 <= r0 { return Err(named("the box is outside the file".into())); } + // A file in strips has no overviews to read coarser cells from: a cellSize coarser than the + // level's cells takes every n-th strip and column instead, as GDAL does (#2592). + let step = match cell { + Some(c) if layout.strips => (c * (1.0 + 1e-9) / size_of(lv)).floor().clamp(1.0, f64::from(u32::MAX)) as u32, + _ => 1, + }; // The sides of the box past the file's edges, which the window is cut at (snapping outwards // onto the pixels isn't a cut). let cut: Vec<&str> = { @@ -6747,10 +6754,17 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic:: .collect() }; let unit = if geographic { " m" } else { " (the file's units)" }; - if values(lv) > MAX_WINDOW_VALUES { - // The finest overview the window fits in, offered, never read unasked. - let take = match layout.levels.iter().skip(level).find(|l| values(l) <= MAX_WINDOW_VALUES) { - Some(l) => format!("take \"cellSize\": {} or more, or a smaller box", size_of(l).ceil()), + if values(lv, step) > MAX_WINDOW_VALUES { + // The finest overview the window fits in, offered, never read unasked; for a file in + // strips, the finest step. + let fitting = if layout.strips { + let least = (values(lv, 1) as f64 / MAX_WINDOW_VALUES as f64).sqrt() as u32; + (least.max(step + 1)..=c1.max(r1)).find(|s| values(lv, *s) <= MAX_WINDOW_VALUES).map(|s| size_of(lv) * f64::from(s)) + } else { + layout.levels.iter().skip(level).find(|l| values(l, 1) <= MAX_WINDOW_VALUES).map(size_of) + }; + let take = match fitting { + Some(size) => format!("take \"cellSize\": {} or more, or a smaller box", size.ceil()), None => "take a smaller box".into(), }; return Err(named(format!( @@ -6782,7 +6796,7 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic:: band_in_time(batch.first().copied().unwrap_or(0), count, started.elapsed(), WINDOW_WAIT).map_err(named)?; let wait = batch_wait(batch.len(), started.elapsed()); for (values, changed, past) in - cog::read_bands_counted_blocking(&info, url, level, batch, (c0, c1), (r0, r1), wait, stop).map_err(named)? + cog::read_bands_stepped_blocking(&info, url, level, batch, (c0, c1), (r0, r1), step, wait, stop).map_err(named)? { bands.push(values); rounded.push(changed); @@ -6790,19 +6804,21 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic:: } } let lt = layout.transform_of(lv); + // Each value a block of `step × step` cells, the last ones cut by the window's edge. + let (width, height) = ((c1 - c0).div_ceil(step), (r1 - r0).div_ceil(step)); let mut transform = rustgis_data::raster::GeoTransform { origin_x: lt.origin_x + f64::from(c0) * lt.pixel_width, origin_y: lt.origin_y + f64::from(r0) * lt.pixel_height, - ..lt + pixel_width: lt.pixel_width * f64::from(step), + pixel_height: lt.pixel_height * f64::from(step), }; if bottom_up { - let width = (c1 - c0) as usize; for band in &mut bands { - let rows: Vec = band.chunks(width.max(1)).rev().flatten().copied().collect(); + let rows: Vec = band.chunks((width as usize).max(1)).rev().flatten().copied().collect(); *band = rows; } - transform.origin_y = lt.origin_y + f64::from(r1) * lt.pixel_height; - transform.pixel_height = -lt.pixel_height; + transform.origin_y = lt.origin_y + (f64::from(r0) + f64::from(height) * f64::from(step)) * lt.pixel_height; + transform.pixel_height = -transform.pixel_height; } let color = match &layout.palette { Some(table) if bands.len() == 1 => rustgis_data::raster::ColorHint::Palette(table.clone()), @@ -6813,7 +6829,7 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic:: .then(|| format!("its colour table is left out: the window has {} bands, a palette has one", bands.len())); let name = asked.name.clone().unwrap_or_else(|| cog_name(url)); let mut r = - rustgis_data::raster::Raster::new(&name, c1 - c0, r1 - r0, bands, transform, layout.crs, layout.nodata, color, layout.data_type) + rustgis_data::raster::Raster::new(&name, width, height, bands, transform, layout.crs, layout.nodata, color, layout.data_type) .map_err(|e| named(e.to_string()))?; if rounded.iter().any(|n| *n > 0) { r.rounded = rounded; @@ -6830,9 +6846,10 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic:: if let Some(described) = &layout.described { r.apply_pam(described, rustgis_data::raster::pam::GDAL_METADATA); } - let size = size_of(lv); + let size = size_of(lv) * f64::from(step); let of = if level == 0 { "the full image".to_string() } else { format!("overview {level} of {}", layout.levels.len() - 1) }; - let read = format!("a {} × {} window of {of}, cells of {size:.1}{unit}, read by range from its address", r.width, r.height); + let every = if step > 1 { format!(" (one strip and column in {step})") } else { String::new() }; + let read = format!("a {} × {} window of {of}{every}, cells of {size:.1}{unit}, read by range from its address", r.width, r.height); let finer = finer.map(|c| format!("cellSize {c} is finer than the file's finest cells ({size:.1}{unit}): the full image is read")); let mut edges = Vec::new(); if !cut.is_empty() { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2ea7379f1c..332790a351 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -53856,6 +53856,35 @@ fn a_window_of_a_geotiff_in_strips_comes_in_as_a_raster() { assert_eq!((whole.width, whole.height), (300, 200)); } +/// A file in strips has no overviews: a cellSize coarser than its cells takes one strip and column +/// in so many (#2592), each value the middle cell of its block, the raster's cells that much +/// larger, and says so. +#[test] +fn a_cell_size_steps_over_the_strips_of_a_file_in_strips() { + // 300 × 200 cells of 0.01° (1,113.2 m) from 10° E, 46° N, a row a strip; cell (x, y) is + // 7 x − 3 y. + let (base, _) = serve_ranges(rustgis_data::raster::cog::example_strips(300, 200, 1)); + let mut s = world(); + let url = format!("{base}/cbers.tif"); + let mark = s.notice_mark(); + let r = + s.run("layer.addUrl", &json!({"url": url, "bbox": [10.505, 45.005, 11.005, 45.505], "cellSize": 4000, "name": "Coarse"})).unwrap(); + let at = |k: &str, i: usize| u32::try_from(r["window"][k][i].as_u64().unwrap()).unwrap(); + let (c0, c1, r0, r1) = (at("columns", 0), at("columns", 1), at("rows", 0), at("rows", 1)); + let w = s.map().layer_by_name("Coarse").and_then(|l| l.raster.as_ref()?.data.clone()).unwrap(); + assert_eq!((w.width, w.height), ((c1 - c0).div_ceil(3), (r1 - r0).div_ceil(3)), "one cell in 3: {r}"); + assert!((w.transform.pixel_width - 0.03).abs() < 1e-9 && (w.transform.pixel_height + 0.03).abs() < 1e-9); + assert!((w.transform.origin_x - (10.0 + 0.01 * f64::from(c0))).abs() < 1e-9); + assert!((w.transform.origin_y - (46.0 - 0.01 * f64::from(r0))).abs() < 1e-9); + for (x, y) in [(0, 0), (4, 7), (w.width - 2, w.height - 2)] { + let (cx, cy) = (i64::from(c0 + 3 * x + 1), i64::from(r0 + 3 * y + 1)); + assert_eq!(w.value(0, x.into(), y.into()), Some((7 * cx - 3 * cy) as f32), "value ({x}, {y})"); + } + assert!((r["window"]["cellSize"].as_f64().unwrap() - 3339.6).abs() < 0.1, "{r}"); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|n| n.contains("17 × 17 window of the full image (one strip and column in 3)")), "{said:?}"); +} + /// 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 43e5cda998..a1dab3aa7e 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -1819,14 +1819,35 @@ pub fn read_bands_counted_blocking( rows: (u32, u32), wait: Duration, stop: &std::sync::atomic::AtomicBool, +) -> Result, u64, u64)>, String> { + read_bands_stepped_blocking(info, url, level, bands, cols, rows, 1, wait, stop) +} + +/// [`read_bands_counted_blocking`] taking every `step`-th column and row of the window, in a +/// window of `⌈w / step⌉ × ⌈h / step⌉` values: each is the cell in the middle of its block of +/// `step × step` (nearest), or the last inside the file of a block the file's edge cuts. Only a +/// file in strips reads fewer bytes for it, the strips of the rows taken (#2592); a tiled file's +/// tiles are read whole, as its overviews are what make it cheap. +#[cfg(not(target_arch = "wasm32"))] +pub fn read_bands_stepped_blocking( + info: &Arc, + url: &str, + level: usize, + bands: &[usize], + cols: (u32, u32), + rows: (u32, u32), + step: u32, + wait: Duration, + stop: &std::sync::atomic::AtomicBool, ) -> Result, u64, u64)>, String> { let url = split(url).0.to_string(); let l = info.layout.levels.get(level).ok_or("no such overview")?; if bands.iter().any(|b| *b >= info.layout.bands.max(1)) { return Err(format!("the file has {} band(s)", info.layout.bands)); } + let step = step.max(1); // The window's size checked before its values are allocated: a caller's window, not the file. - let (w, h) = (cols.1.saturating_sub(cols.0) as usize, rows.1.saturating_sub(rows.0) as usize); + let (w, h) = (cols.1.saturating_sub(cols.0).div_ceil(step) as usize, rows.1.saturating_sub(rows.0).div_ceil(step) as usize); let n = (w as u64).saturating_mul(h as u64); if n > MAX_VALUES_READ { return Err(format!("a window of {w} × {h} values; one read takes {MAX_VALUES_READ} at most")); @@ -1842,7 +1863,8 @@ pub fn read_bands_counted_blocking( if x1 <= x0 || y1 <= y0 { return Ok(outs); } - let window = Window { x: (x0, x1), y: (y0, y1), from: (cols.0, rows.0), w, nodata: info.layout.nodata.map(|v| v as f32) }; + let nodata = info.layout.nodata.map(|v| v as f32); + let window = Window { x: (x0, x1), y: (y0, y1), from: (cols.0, rows.0), w, step, off: (step - 1) / 2, nodata }; if info.layout.strips { read_strips(info, &url, level, bands, &window, &mut outs, wait, stop)?; return Ok(outs); @@ -1878,25 +1900,45 @@ pub fn read_bands_counted_blocking( } /// Where a read's values go: the window's part inside the file (columns `x`, rows `y` of the -/// level's grid), its first column and row (`from`), its width, and the value that means none. +/// level's grid), its first column and row (`from`), its width (in values), the cells it steps +/// by and where in a step's block it takes one (`off`), and the value that means none. #[cfg(not(target_arch = "wasm32"))] struct Window { x: (u32, u32), y: (u32, u32), from: (u32, u32), w: usize, + step: u32, + off: u32, nodata: Option, } #[cfg(not(target_arch = "wasm32"))] impl Window { + /// The cell of the level's grid the window's value `i` takes along one axis: `from + i × step + /// + off`, or the last inside the file (before `end`) when the file's edge cuts its block. + fn cell(&self, from: u32, end: u32, i: u32) -> u32 { + from.saturating_add(i.saturating_mul(self.step)).saturating_add(self.off).min(end.saturating_sub(1)) + } + + /// The window's values along one axis whose cells ([`Window::cell`]) lie in `lo..hi`. + fn picks(&self, from: u32, end: u32, lo: u32, hi: u32) -> std::ops::Range { + let start = from.saturating_add(self.off); + let first = lo.saturating_sub(start).div_ceil(self.step); + let last = if hi >= end { end.saturating_sub(from).div_ceil(self.step) } else { hi.saturating_sub(start).div_ceil(self.step) }; + first..last.max(first) + } + /// Copies band `b` of a decoded chunk into `out` (values, rounded, overflowed): the chunk is a - /// tile `tw × th` whose first cell is (`tx0`, `ty0`), and only its cells in the window go. + /// tile `tw × th` whose first cell is (`tx0`, `ty0`), and only its cells the window takes go. fn copy(&self, chunk: &cog::Tile, b: usize, (tx0, ty0, tw, th): (u32, u32, u32, u32), out: &mut (Vec, u64, u64)) { let Some(values) = chunk.get(b) else { return }; let (out, rounded, overflowed) = out; - for py in ty0.max(self.y.0)..ty0.saturating_add(th).min(self.y.1) { - for px in tx0.max(self.x.0)..tx0.saturating_add(tw).min(self.x.1) { + let columns = self.picks(self.from.0, self.x.1, tx0.max(self.x.0), tx0.saturating_add(tw).min(self.x.1)); + for j in self.picks(self.from.1, self.y.1, ty0.max(self.y.0), ty0.saturating_add(th).min(self.y.1)) { + let py = self.cell(self.from.1, self.y.1, j); + for k in columns.clone() { + let px = self.cell(self.from.0, self.x.1, k); let i = (py - ty0) as usize * tw as usize + (px - tx0) as usize; let Some(&v) = values.get(i) else { continue }; // A marked value past `f32`'s range is infinite: left out as no value, and @@ -1906,7 +1948,7 @@ impl Window { } if v.is_finite() && Some(v) != self.nodata - && let Some(slot) = out.get_mut((py - self.from.1) as usize * self.w + (px - self.from.0) as usize) + && let Some(slot) = out.get_mut(j as usize * self.w + k as usize) { *slot = v; } @@ -1920,22 +1962,29 @@ impl Window { #[cfg(not(target_arch = "wasm32"))] const STRIP_RUN_BYTES: u64 = 4 << 20; +/// Strips this close in the file are read in one request, with the bytes between them: those a +/// window that steps over strips (`cellSize`) leaves out, when a request costs about as much as +/// reading them from a slow server (#2592). +#[cfg(not(target_arch = "wasm32"))] +const STRIP_GAP_BYTES: u64 = 256 << 10; + /// The requests of a window of a file in strips under way at once. #[cfg(not(target_arch = "wasm32"))] 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, of at most `max` bytes each 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). +/// 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). #[cfg(not(target_arch = "wasm32"))] -fn strip_runs(l: &Level, chunks: &[u32], max: u64) -> Vec> { +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)?)); let mut runs: Vec> = Vec::new(); let mut end = None::<(u64, u64)>; for (k, &c) in chunks.iter().enumerate() { let Some((at, len)) = place(c).filter(|p| p.1 > 0) else { continue }; match (runs.last_mut(), end) { - (Some(run), Some((first, next))) if run.end == k && next == at && at.saturating_add(len) - first <= max => { + (Some(run), Some((first, next))) if run.end == k && at >= next && at - next <= gap && at.saturating_add(len) - first <= max => { run.end = k + 1; end = Some((first, at.saturating_add(len))); } @@ -1948,8 +1997,9 @@ fn strip_runs(l: &Level, chunks: &[u32], max: u64) -> Vec runs } -/// [`read_bands_counted_blocking`] for a file in strips (#2592): the window's strips that follow -/// one another in the file are read in requests of up to [`STRIP_RUN_BYTES`], +/// [`read_bands_stepped_blocking`] for a file in strips (#2592): the strips of the rows the window +/// takes, those that follow one another in the file (or lie within [`STRIP_GAP_BYTES`]) read in +/// requests of up to [`STRIP_RUN_BYTES`], /// [`STRIP_RUNS_AT_ONCE`] under way at once, and each strip, decoded, is copied out to the /// window's columns. The strips aren't kept in the tile cache: no map tile draws them. The /// [`MAX_VALUE_TILES`] bound counts the requests, not the strips. @@ -1968,14 +2018,17 @@ fn read_strips( let th = l.tile_height.max(1); // Each chunk the window takes, with the bands it holds: (place in `outs`, place in the chunk). let mut wanted: BTreeMap> = BTreeMap::new(); - for strip in window.y.0 / th..=(window.y.1 - 1) / th { + let (from, end) = (window.from.1, window.y.1); + let mut strips: Vec = window.picks(from, end, window.y.0, end).map(|j| window.cell(from, end, j) / th).collect(); + strips.dedup(); + for strip in strips { for (i, &b) in bands.iter().enumerate() { let (c, at) = info.layout.chunk(l, strip, b).ok_or_else(|| format!("no band {} in strip {strip}", b + 1))?; wanted.entry(c).or_default().push((i, at)); } } let chunks: Vec = wanted.keys().copied().collect(); - let runs = strip_runs(l, &chunks, STRIP_RUN_BYTES); + let runs = strip_runs(l, &chunks, STRIP_RUN_BYTES, STRIP_GAP_BYTES); if runs.len() > MAX_VALUE_TILES { return Err(format!("{} reads of the file's strips for one read; at most {MAX_VALUE_TILES}: take a smaller area", runs.len())); } @@ -2146,8 +2199,57 @@ mod tests { // Strips 0–1 follow one another, 2 is empty, 3 lies apart, 4–6 pass 12 bytes together. let mut l = l.clone(); (l.offsets, l.counts) = (vec![100, 104, 0, 200, 300, 306, 312], vec![4, 4, 0, 6, 6, 6, 6]); - assert_eq!(super::strip_runs(&l, &[0, 1, 2, 3, 4, 5, 6], 12), vec![0..2, 3..4, 4..6, 6..7]); - assert_eq!(super::strip_runs(&l, &[3], 2), vec![0..1], "a strip larger than a run is read alone"); + assert_eq!(super::strip_runs(&l, &[0, 1, 2, 3, 4, 5, 6], 12, 0), vec![0..2, 3..4, 4..6, 6..7]); + assert_eq!(super::strip_runs(&l, &[3], 2, 0), vec![0..1], "a strip larger than a run is read alone"); + // Strip 3 lies 92 bytes past 1, and 4 lies 94 past 3: a gap of 92 joins the first two, 94 + // all; an empty strip still ends a run. + assert_eq!(super::strip_runs(&l, &[0, 1, 3, 4], 1000, 91), vec![0..2, 2..3, 3..4]); + assert_eq!(super::strip_runs(&l, &[0, 1, 3, 4], 1000, 92), vec![0..3, 3..4]); + assert_eq!(super::strip_runs(&l, &[0, 1, 2, 3, 4, 5, 6], 1000, 94), vec![0..2, 3..7]); + } + + /// A window read stepping over the file's cells takes the cell in the middle of each block, or + /// the last in the file of a block its edge cuts: a file in strips only the strips of those + /// rows, those close together in one request; a tiled file's tiles whole, the same cells. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_stepped_window_takes_a_cell_a_block() { + let _turn = crate::cache::turn(); + let never = std::sync::atomic::AtomicBool::new(false); + let file = Arc::new(cog::example_strips(300, 200, 1)); + let (bytes, asked) = serve_strips(file, Arc::new(AtomicU64::new(u64::MAX)), 0); + let url = "https://strips-cog.invalid/stepped.tif"; + let info = super::window_info_until(url, &never).unwrap(); + let (header, headers) = (bytes.load(Ordering::SeqCst), asked.load(Ordering::SeqCst)); + // Columns 10–49 and rows 20–60 in blocks of 4: 10 × 11 values, the last row's block cut + // to its first cell (row 60), the others taking their second (11, 15…; 21, 25…). + let wait = Duration::from_secs(120); + let mut read = super::read_bands_stepped_blocking(&info, url, 0, &[0], (10, 50), (20, 61), 4, wait, &never).unwrap(); + let values = read.pop().unwrap().0; + assert_eq!(values.len(), 10 * 11); + for (k, v) in values.iter().enumerate() { + let (x, y) = (11 + 4 * (k as i32 % 10), (21 + 4 * (k as i32 / 10)).min(60)); + assert_eq!(*v, (7 * x - 3 * y) as f32, "value {k}: cell ({x}, {y})"); + } + let l = &info.layout.levels[0]; + let span = l.offsets[60] + l.counts[60] - l.offsets[21]; + assert_eq!(bytes.load(Ordering::SeqCst) - header, span, "strips 21 to 60, the gaps between them read too"); + assert_eq!(asked.load(Ordering::SeqCst) - headers, 1, "in one request"); + super::forget_file(url); + let tiled = Arc::new(cog::example(512, 128)); + serve_strips(tiled, Arc::new(AtomicU64::new(u64::MAX)), 0); + let url = "https://tiled-cog.invalid/stepped.tif"; + let info = super::info_until(url, &never).unwrap(); + let full = super::read_values_blocking(&info, url, 0, 0, (3, 300), (5, 250)).unwrap(); + let mut read = super::read_bands_stepped_blocking(&info, url, 0, &[0], (3, 300), (5, 250), 5, wait, &never).unwrap(); + let stepped = read.pop().unwrap().0; + assert_eq!(stepped.len(), 60 * 49); + for (k, v) in stepped.iter().enumerate() { + let (x, y) = ((2 + 5 * (k % 60)).min(296), (2 + 5 * (k / 60)).min(244)); + assert_eq!(v.to_bits(), full[y * 297 + x].to_bits(), "value {k}"); + } + crate::cache::clear_fetcher(); + super::forget_file(url); } /// A read of strips stopped before it starts asks for none, and one whose address may reach