diff --git a/crates/data/src/raster/cog.rs b/crates/data/src/raster/cog.rs index 95a2400e60..6dedc6c524 100644 --- a/crates/data/src/raster/cog.rs +++ b/crates/data/src/raster/cog.rs @@ -28,7 +28,7 @@ const MAX_TILES: usize = 4 << 20; const MAX_TOTAL_TILES: usize = 8 << 20; /// The largest tile, in bytes once read: each value as the `f32` it is kept as, a 64-bit one as /// the 8 bytes it is decoded to before that. -const MAX_TILE_BYTES: usize = 32 << 20; +pub(crate) const MAX_TILE_BYTES: usize = 32 << 20; /// The most bytes held from a file's header (its IFDs and their tag arrays). pub const MAX_HEADER: u64 = 32 << 20; diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index db641e15c1..bf8414a9d1 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -526,10 +526,12 @@ fn entries(r: &Raster, plan: &Plan, lv: &Level, first: bool, geo: &GeoKeys, big: e.push(long(323, TILE)); e.push(table(324, lv.tiles(), big, false)); e.push(table(325, lv.tiles(), big, true)); - if plan.alpha.is_some() { - e.push(shorts(338, &[2])); - } else if plan.rgb && spp == 4 { - e.push(shorts(338, &[0])); + // Samples past the colour or grey ones: alpha, or nothing said of them (an RGB and + // near-infrared image's fourth, a stream's further bands). + let base = if plan.rgb { 3 } else { 1 }; + if spp > base { + let extra: Vec = (base..spp).map(|i| if plan.alpha == Some(i) { 2 } else { 0 }).collect(); + e.push(shorts(338, &extra)); } e.push(shorts(339, &vec![format; spp])); if first { @@ -1087,43 +1089,55 @@ pub fn write_staged(r: &Raster, band: usize, path: &Path) -> Result<(CogInfo, cr Ok((info, staged)) } -/// A tiled GeoTIFF of one band of 32-bit floats written a row of tiles at a time, for a raster -/// made in pieces too large to hold whole (#2865). The caller gives the full image's rows, top to -/// bottom, in as many calls as it likes ([`TileStream::put`]); each full row of tiles is -/// compressed and written as it is complete, and the rows of the overviews are made from it as -/// they go, each level averaging two by two the pixels of the one before (the pixels with a value -/// among the four, as [`write_to`] averages, but from the level before rather than the full -/// image). Its layout is a tiled GeoTIFF's, every level's directory first: not a cloud-optimised -/// one, whose tiles go smallest level first, but one this computer's reader reads in place. +/// A tiled GeoTIFF of 32-bit floats, one band or several, written a row of tiles at a time, for a +/// raster made in pieces too large to hold whole (#2865). The caller gives the full image's rows, +/// top to bottom, in as many calls as it likes ([`TileStream::put`], [`TileStream::put_bands`]); +/// each full row of tiles is compressed and written as it is complete, and the rows of the +/// overviews are made from it as they go, each level averaging two by two the pixels of the one +/// before (the pixels with a value among the four, as [`write_to`] averages, but from the level +/// before rather than the full image, and each band by itself). Its layout is a tiled GeoTIFF's, +/// every level's directory first: not a cloud-optimised one, whose tiles go smallest level first, +/// but one this computer's reader reads in place. /// /// Memory: at most two rows of tiles of each level wait to be written, about -/// `width × TILE × 4 × 2 × 4 / 3` bytes, and a few compressed tiles a thread. +/// `width × TILE × 4 × 2 × 4 / 3` bytes a band, and a few compressed tiles a thread. pub struct TileStream<'a, W: Write + Seek> { out: &'a mut W, levels: Vec, - /// Each level's rows given and not yet written as a row of tiles, its width each. - pending: Vec>, + /// What the file holds: its bands, their type, colour and alpha. + plan: Plan, + /// Each level's rows given and not yet written as a row of tiles, a band each, its width each. + pending: Vec>>, /// How many rows of each level have been given. given: Vec, places: Vec>, patches: Vec, big: bool, pos: u64, - /// The value of a pixel with none, written for pixels past the image's edge too. + /// The value of a pixel with none as the file holds it, written for pixels past the image's + /// edge too. nodata: f32, + /// The value of a pixel with none as it is given (the template's), which the overviews are + /// made with: the file's, unless alpha says which pixels have one ([`Holding`]). + given_nodata: f32, + /// The alpha band, which says which pixels have a value, and the value it is opaque at (an + /// integer template's, which a float file holds divided by it, opaque at 1, as [`write_to`] + /// writes it). + alpha_scale: Option<(usize, f32)>, /// Whole numbers 1 to 255 written as bytes, 0 for no value ([`Samples::Hillshade`]); floats /// otherwise. bytes: bool, /// Classes, whose overviews take a pixel ([`Samples::Classes`]). classes: bool, - /// The level kept as it is written ([`TileStream::keeping`]), and its rows so far. - kept: Option<(usize, Vec)>, - /// What the kept level is made into: the template's name, place and no-data. + /// The level kept as it is written ([`TileStream::keeping`]), and its rows so far, a band each. + kept: Option<(usize, Vec>)>, + /// What the kept level is made into: the template's name, bands' names, place, colour and + /// no-data. template: Raster, } -/// What a [`TileStream`]'s band holds, which decides how it is stored and how its overviews are -/// made. +/// What a [`TileStream`]'s bands hold, which decides how they are stored and how their overviews +/// are made. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Samples { /// Measures, as 32-bit floats; an overview pixel is the mean of the four it covers. @@ -1132,16 +1146,18 @@ pub enum Samples { /// four it covers, never an average no class has, as [`write_to`] makes a classes' overview. Classes, /// A hillshade's whole numbers 1 to 255, as bytes with 0 for no value; averaged, which never - /// gives 0 (no value) from pixels that have one. + /// gives 0 (no value) from pixels that have one. One band only. Hillshade, } impl<'a, W: Write + Seek> TileStream<'a, W> { /// A stream of a `width` × `height` raster of `samples` into `out` (which must be empty: - /// offsets are from its start), placed, named and with the no-data value of `template` (its - /// first band's name, its transform's corner and pixel size, its system and rights holder; - /// its own pixels and size aren't written). A template without a no-data value marks pixels - /// with none NaN; a hillshade's no-data is 0. + /// offsets are from its start), placed, named and with the no-data value of `template`, and + /// with as many bands as it has (their names, its colour: red, green and blue for an RGB + /// template of three or four bands, the fourth alpha when it says so; grey and alpha; else + /// grey, further bands saying nothing of what they are), its transform's corner and pixel + /// size, its system and rights holder; its own pixels and size aren't written. A template + /// without a no-data value marks pixels with none NaN; a hillshade's no-data is 0. pub fn new(template: &Raster, width: u32, height: u32, samples: Samples, out: &'a mut W) -> Result> { template.require_coordinates().map_err(err)?; let gt = template.transform; @@ -1151,11 +1167,34 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { if width == 0 || height == 0 { return Err(err("the raster has no pixels to write")); } + let n = template.bands.len().max(1); let bytes = samples == Samples::Hillshade; if bytes && template.nodata != Some(0.0) { return Err(err("a hillshade's pixels with no value are 0")); } - let plan = stream_plan(bytes, template.nodata); + if bytes && n > 1 { + return Err(err("a hillshade has one band")); + } + // A class overview picks a pixel band by band, which for several bands could pick one + // pixel's colour and another's alpha. + if samples == Samples::Classes && n > 1 { + return Err(err("classes are written one band at a time")); + } + if n > Self::most_bands() { + return Err(err(format!( + "its {n} bands make tiles of {} MB, more than a reader takes: at most {} bands are written a row of tiles at a time", + (n as u64 * u64::from(TILE) * u64::from(TILE) * 4) >> 20, + Self::most_bands() + ))); + } + let plan = stream_plan(bytes, template.nodata, n, &template.color); + // With alpha, alpha says which pixels have a value, as [`write_to`] writes it: no no-data + // value is written, a pixel with none is see-through, its colours what they are (a black + // one stays black), and an integer template's alpha is held on a float's scale, opaque + // at 1. Further bands mark a value with none NaN. + let opaque = super::alpha_max(&template.data_type); + let alpha_scale = plan.alpha.filter(|_| !bytes).map(|a| (a, opaque)); + let file_nodata = if alpha_scale.is_some() { None } else { template.nodata }; let geo = geo_keys(template)?; let mut levels = vec![Level::new(width, height, 1)]; while let Some(last) = levels.last().filter(|l| l.w.max(l.h) > TILE) { @@ -1167,7 +1206,7 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { } let tiles: usize = levels.iter().map(Level::tiles).sum(); // The worst a file can come to, as [`write_to`] reckons it. - let raw = (tiles as u64).saturating_mul(u64::from(TILE) * u64::from(TILE) * if bytes { 1 } else { 4 }); + let raw = (tiles as u64).saturating_mul(u64::from(TILE) * u64::from(TILE) * if bytes { 1 } else { 4 }).saturating_mul(n as u64); let worst = raw.saturating_add(raw / 512).saturating_add(tiles as u64 * 64).saturating_add(1 << 20); let big = worst >= u64::from(u32::MAX); // A header past what a reader takes at a file's start couldn't be read in place: its @@ -1179,7 +1218,8 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { table_bytes >> 20 ))); } - let nodata = template.nodata.map_or(f32::NAN, |d| d as f32); + let given_nodata = template.nodata.map_or(f32::NAN, |d| d as f32); + let nodata = file_nodata.map_or(f32::NAN, |d| d as f32); let ifds: Vec> = levels .iter() .enumerate() @@ -1187,9 +1227,11 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { let mut e = entries(template, &plan, lv, i == 0, &geo, big); if i == 0 { // What marks a pixel with none: the template's value, else NaN (its own - // pixels, which `entries` looks at, aren't the stream's). + // pixels, which `entries` looks at, aren't the stream's); with alpha, alpha. e.retain(|e| e.tag != 42113); - e.push(ascii(42113, &template.nodata.map_or_else(|| "nan".to_string(), |d| d.to_string()))); + if alpha_scale.is_none() { + e.push(ascii(42113, &file_nodata.map_or_else(|| "nan".to_string(), |d| d.to_string()))); + } } e }) @@ -1204,17 +1246,20 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { } out.seek(SeekFrom::Start(0)).map_err(err)?; out.write_all(&head.bytes).map_err(err)?; - let n = levels.len(); + let count = levels.len(); Ok(TileStream { out, pos: head.bytes.len() as u64, places: levels.iter().map(|l| Vec::with_capacity(l.tiles())).collect(), levels, - pending: vec![Vec::new(); n], - given: vec![0; n], + plan, + pending: vec![vec![Vec::new(); n]; count], + given: vec![0; count], patches: head.patches, big, nodata, + given_nodata, + alpha_scale, bytes, classes: samples == Samples::Classes, kept: None, @@ -1222,58 +1267,102 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { }) } - /// Keeps, as it is written, the finest level whose tiles hold at most `samples` pixels, their - /// padding counted (the coarsest when none does), which [`TileStream::finish`] gives as a - /// raster: an overview of the file to hold, the one a layer reading the file in place picks - /// with the same budget, without reading it back. + /// How many bands it writes. + fn bands(&self) -> usize { + self.plan.bands.len() + } + + /// The most bands a stream writes: their samples interleaved in a tile within what a reader + /// decodes of one (`cog::MAX_TILE_BYTES`). + pub fn most_bands() -> usize { + super::cog::MAX_TILE_BYTES / (TILE as usize * TILE as usize * 4) + } + + /// The level [`TileStream::keeping`] keeps of `levels` with `samples`: the finest whose tiles + /// hold at most that many samples of `bands` bands, padding counted, else the coarsest. + fn kept_level(levels: &[Level], bands: usize, samples: usize) -> usize { + let tile = TILE as usize * TILE as usize * bands.max(1); + levels.iter().position(|l| l.tiles().saturating_mul(tile) <= samples).unwrap_or(levels.len().saturating_sub(1)) + } + + /// How a pixel's value of a band is held in the file ([`Holding`]). + fn holding(&self) -> Holding { + Holding { given: self.given_nodata, nodata: self.nodata, alpha: self.alpha_scale } + } + + /// Keeps, as it is written, the finest level whose tiles hold at most `samples` samples, every + /// band's and their padding counted (the coarsest when none does), which + /// [`TileStream::finish`] gives as a raster: an overview of the file to hold, the one a layer + /// reading the file in place picks with the same budget, without reading it back. pub fn keeping(mut self, samples: usize) -> TileStream<'a, W> { - let tile = TILE as usize * TILE as usize; - let fits = self.levels.iter().position(|l| l.tiles().saturating_mul(tile) <= samples); - let level = fits.unwrap_or(self.levels.len().saturating_sub(1)); - self.kept = Some((level, Vec::new())); + let level = Self::kept_level(&self.levels, self.bands(), samples); + self.kept = Some((level, vec![Vec::new(); self.bands()])); self } - /// The most bytes a stream of a `width` × `height` image holds at once, keeping an overview of - /// at most `kept` samples ([`TileStream::keeping`]), given its rows a row of tiles at a time: - /// each level's rows waiting for their row of tiles (none at the full size, which is written - /// from the rows given; less than a row of tiles of each level after it, and the rows made - /// for it), the tiles' tables, the overview kept, and the tiles being compressed. - pub fn peak(width: u32, height: u32, kept: usize) -> u64 { - let row = u64::from(width).saturating_mul(u64::from(TILE)).saturating_mul(4); + /// The most bytes a stream of a `width` × `height` image of `bands` bands holds at once, + /// keeping an overview of at most `kept` samples ([`TileStream::keeping`]), given its rows a + /// row of tiles at a time: each level's rows waiting for their row of tiles (none at the full + /// size, which is written from the rows given; less than a row of tiles of each level after + /// it, and the rows made for it), the tiles' tables, the overview kept, and the tiles being + /// compressed. + pub fn peak(width: u32, height: u32, bands: usize, kept: usize) -> u64 { + let bands = bands.max(1) as u64; + let row = u64::from(width).saturating_mul(u64::from(TILE)).saturating_mul(4).saturating_mul(bands); // The tiles of every level, each with an offset and a count of 8 bytes, held three times // as the header is laid out, and once more where each tile went. - let (mut tiles, (mut w, mut h)) = (0u64, (width, height)); + let (mut levels, (mut w, mut h)) = (Vec::new(), (width, height)); loop { - tiles = tiles.saturating_add(u64::from(w.div_ceil(TILE)).saturating_mul(u64::from(h.div_ceil(TILE)))); - if w.max(h) <= TILE { + levels.push(Level::new(w, h, 1)); + if w.max(h) <= TILE || levels.len() >= MAX_LEVELS { break; } (w, h) = (w.div_ceil(2), h.div_ceil(2)); } + let tiles = levels.iter().map(|l| l.tiles() as u64).fold(0u64, u64::saturating_add); + // The level kept, as many samples as it has (the coarsest can pass `kept`). + let kept = levels + .get(Self::kept_level(&levels, bands as usize, kept)) + .map_or(0, |l| (l.w as u64).saturating_mul(u64::from(l.h)).saturating_mul(bands)); // Rows waiting at each level after the first: at most a row of tiles of that level and the // half-size rows just made for it, each level half as wide as the one before, so two // full-width rows hold them all. - let levels = row.saturating_mul(2); + let rows = row.saturating_mul(2); let tables = tiles.saturating_mul(64); - let compressing = (crate::threads::max() as u64).saturating_mul(u64::from(TILE) * u64::from(TILE) * 4 * (2 + AHEAD as u64)); - levels.saturating_add(tables).saturating_add((kept as u64).saturating_mul(4)).saturating_add(compressing) + let tile = (u64::from(TILE) * u64::from(TILE) * 4).saturating_mul(bands); + // No more tiles are made at once than a row of them has. + let workers = (crate::threads::max() as u64).min(u64::from(width.div_ceil(TILE)).max(1)); + let compressing = workers.saturating_mul(tile.saturating_mul(2 + AHEAD as u64)); + rows.saturating_add(tables).saturating_add(kept.saturating_mul(4)).saturating_add(compressing) } - /// The full image's next rows, whole rows of its width, top to bottom: each row of tiles they - /// complete is written, and its overviews' rows made. More rows than the image has are an error. + /// The full image's next rows of its one band, whole rows of its width, top to bottom: each + /// row of tiles they complete is written, and its overviews' rows made. More rows than the + /// image has are an error, as is a stream of several bands. pub fn put(&mut self, rows: &[f32]) -> Result<()> { - self.put_level(0, rows) + if self.bands() != 1 { + return Err(err(format!("a stream of {} bands is given them all at once (put_bands)", self.bands()))); + } + self.put_level(0, &[rows]) } - /// [`TileStream::put`] at level `i`. - fn put_level(&mut self, i: usize, rows: &[f32]) -> Result<()> { + /// [`TileStream::put`] of every band: the same rows of each, in the bands' order. + pub fn put_bands(&mut self, bands: &[&[f32]]) -> Result<()> { + self.put_level(0, bands) + } + + /// [`TileStream::put_bands`] at level `i`. + fn put_level(&mut self, i: usize, rows: &[&[f32]]) -> Result<()> { let Some(lv) = self.levels.get(i) else { return Ok(()) }; let w = lv.w as usize; - if !rows.len().is_multiple_of(w) { + let len = rows.first().map_or(0, |r| r.len()); + if rows.len() != self.bands() || rows.iter().any(|r| r.len() != len) { + return Err(err(format!("the same rows of each of its {} bands must be given", self.bands()))); + } + if !len.is_multiple_of(w) { return Err(err("rows must be whole rows of the image's width")); } - let count = (rows.len() / w) as u64; + let count = (len / w) as u64; let given = self.given.get(i).copied().unwrap_or(0).saturating_add(count); if given > u64::from(lv.h) { return Err(err(format!("more than the image's {} rows were given", lv.h))); @@ -1282,71 +1371,87 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { *g = given; } if let Some((_, kept)) = self.kept.as_mut().filter(|(level, _)| *level == i) { - kept.try_reserve(rows.len()).map_err(|_| err("too little memory for the overview kept"))?; - kept.extend_from_slice(rows); + // Set aside whole at its first rows, as planned ([`TileStream::peak`]), not grown. + let whole = w.saturating_mul(lv.h as usize); + for (k, r) in kept.iter_mut().zip(rows) { + k.try_reserve_exact(whole.max(k.len() + r.len()) - k.len()).map_err(|_| err("too little memory for the overview kept"))?; + k.extend_from_slice(r); + } } let tile_rows = TILE as usize * w; // Taken while its rows are written, which give the next level its own. let mut pending = self.pending.get_mut(i).map(std::mem::take).unwrap_or_default(); - let mut rest = rows; - let room = |n: usize, pending: &mut Vec| { - pending.try_reserve(n).map_err(|_| err("too little memory for the rows of a level waiting to be written")) + pending.resize_with(rows.len(), Vec::new); + let held = |pending: &[Vec]| pending.first().map_or(0, Vec::len); + let add = |pending: &mut [Vec], from: usize, to: usize| -> Result<()> { + for (p, r) in pending.iter_mut().zip(rows) { + let part = r.get(from..to).unwrap_or_default(); + p.try_reserve(part.len()).map_err(|_| err("too little memory for the rows of a level waiting to be written"))?; + p.extend_from_slice(part); + } + Ok(()) }; + let mut at = 0; // A row of tiles begun: finished from the rows given, and written. - if !pending.is_empty() { - let (head, after) = rest.split_at(tile_rows.saturating_sub(pending.len()).min(rest.len())); - room(head.len(), &mut pending)?; - pending.extend_from_slice(head); - rest = after; - if pending.len() == tile_rows { - self.write_row(i, &pending)?; - pending.clear(); + if held(&pending) > 0 { + let to = tile_rows.saturating_sub(held(&pending)).min(len); + add(&mut pending, 0, to)?; + at = to; + if held(&pending) == tile_rows { + let row: Vec<&[f32]> = pending.iter().map(Vec::as_slice).collect(); + self.write_row(i, &row)?; + pending.iter_mut().for_each(Vec::clear); } } // Whole rows of tiles are written from the rows given, not copied first. - while pending.is_empty() && rest.len() >= tile_rows { - let (row, after) = rest.split_at(tile_rows); - self.write_row(i, row)?; - rest = after; + while held(&pending) == 0 && len - at >= tile_rows { + let row: Vec<&[f32]> = rows.iter().map(|r| r.get(at..at + tile_rows).unwrap_or_default()).collect(); + self.write_row(i, &row)?; + at += tile_rows; } - room(rest.len(), &mut pending)?; - pending.extend_from_slice(rest); + add(&mut pending, at, len)?; if let Some(p) = self.pending.get_mut(i) { *p = pending; } Ok(()) } - /// Writes `rows` (at most [`TILE`] of level `i`'s rows, the last row of tiles when fewer) as - /// the level's next row of tiles, then gives the next level their average two by two. - fn write_row(&mut self, i: usize, rows: &[f32]) -> Result<()> { + /// Writes `rows` (at most [`TILE`] of level `i`'s rows of each band, the last row of tiles + /// when fewer) as the level's next row of tiles, then gives the next level their average two + /// by two. + fn write_row(&mut self, i: usize, rows: &[&[f32]]) -> Result<()> { let Some(lv) = self.levels.get(i) else { return Ok(()) }; let (w, across) = (lv.w as usize, lv.across as usize); - let (t, nodata, bytes) = (TILE as usize, self.nodata, self.bytes); - let plan = stream_plan(bytes, Some(f64::from(nodata))); + let (t, given, bytes, spp, holding) = (TILE as usize, self.given_nodata, self.bytes, self.bands(), self.holding()); + // The full image's values, or a classes' overview's, which picks a pixel: a value with + // none there is one. + let full = i == 0 || self.classes; let size = if bytes { 1 } else { 4 }; - let line = t * size; + let line = t * spp * size; + let (sample, predictor) = (self.plan.sample, predictor(&self.plan)); let make = |scratch: &mut Vec, tx: usize| -> Result> { - let mut raw = Vec::with_capacity(t * t * size); + let mut raw = Vec::with_capacity(t * t * spp * size); for y in 0..t { for x in 0..t { let col = tx * t + x; - let v = if col < w { rows.get(y * w + col).copied().unwrap_or(nodata) } else { nodata }; - let v = if v.is_nan() { nodata } else { v }; - if bytes { - raw.push(v.round().clamp(0.0, 255.0) as u8); - } else { - raw.extend_from_slice(&v.to_le_bytes()); + for (b, band) in rows.iter().enumerate() { + let v = if col < w { band.get(y * w + col).copied().unwrap_or(given) } else { given }; + let v = holding.of(b, v, full); + if bytes { + raw.push(v.round().clamp(0.0, 255.0) as u8); + } else { + raw.extend_from_slice(&v.to_le_bytes()); + } } } } - predict_rows(&mut raw, line, 1, plan.sample, predictor(&plan), scratch); + predict_rows(&mut raw, line, spp, sample, predictor, scratch); Ok(miniz_oxide::deflate::compress_to_vec_zlib(&raw, DEFLATE_FAST)) }; let (big, out, pos, places) = (self.big, &mut *self.out, &mut self.pos, &mut self.places); // The run's progress counts the caller's pieces, not these tiles. crate::progress::without_counting(|| { - in_order(across, t * t * size, err, Vec::new, make, |_, zipped| { + in_order(across, t * t * spp * size, err, Vec::new, make, |_, zipped| { if !big && *pos + zipped.len() as u64 > u64::from(u32::MAX) { return Err(err("the file is too large for classic TIFF")); } @@ -1359,9 +1464,27 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { }) })?; // The next level's rows: each the average of two of these (the last alone when they are - // odd), two pixels across at a time. + // odd), two pixels across at a time, each band by itself. if i + 1 < self.levels.len() { - let half = if self.classes { pick_rows(rows, w, nodata) } else { average_rows(rows, w, nodata) }; + // Colours before an alpha band weighted by it; the rest by themselves. + let alpha = self.alpha_scale.and_then(|(a, _)| rows.get(a).copied().map(|r| (a, r))); + let half: Vec> = rows + .iter() + .enumerate() + .map(|(b, r)| match alpha { + _ if self.classes => pick_rows(r, w, given), + Some((a, ar)) if b < a => average_by_alpha(r, ar, w, given, if i == 0 { given } else { f32::NAN }), + // A see-through pixel's alpha is 0, which an overview's averages in. + Some((a, _)) if b == a => { + // Only the full image's alpha can be given without a value: an overview's + // is a mean of alphas, whatever it comes to. + let seen: Vec = r.iter().map(|v| if v.is_nan() || (i == 0 && *v == given) { 0.0 } else { *v }).collect(); + average_rows(&seen, w, f32::NAN) + } + _ => average_rows(r, w, given), + }) + .collect(); + let half: Vec<&[f32]> = half.iter().map(Vec::as_slice).collect(); self.put_level(i + 1, &half)?; } Ok(()) @@ -1376,8 +1499,9 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { } for i in 0..self.levels.len() { let rest = self.pending.get_mut(i).map(std::mem::take).unwrap_or_default(); - if !rest.is_empty() { - self.write_row(i, &rest)?; + if rest.first().is_some_and(|r| !r.is_empty()) { + let row: Vec<&[f32]> = rest.iter().map(Vec::as_slice).collect(); + self.write_row(i, &row)?; } } for (lv, p) in self.levels.iter().zip(&self.places) { @@ -1387,6 +1511,7 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { } fill_tables(self.out, &self.patches, &self.places, self.big, self.pos, err)?; let info = CogInfo { big: self.big, levels: self.levels.iter().map(|l| (l.w, l.h)).collect(), bytes: self.pos }; + let holding = self.holding(); let (Some((level, data)), Some(full)) = (self.kept, self.levels.first()) else { return Ok((info, None)) }; let Some(lv) = self.levels.get(level) else { return Ok((info, None)) }; let t = &self.template; @@ -1394,34 +1519,133 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { let (sx, sy) = (f64::from(full.w) / f64::from(lv.w.max(1)), f64::from(full.h) / f64::from(lv.h.max(1))); let gt = super::GeoTransform { pixel_width: t.transform.pixel_width * sx, pixel_height: t.transform.pixel_height * sy, ..t.transform }; - // As the file holds it: bytes rounded as they were written. - let (data, kind) = match self.bytes { - true => (data.into_iter().map(|v| if v.is_nan() { self.nodata } else { v.round().clamp(0.0, 255.0) }).collect(), "UInt8"), + // As the file holds it: bytes rounded as they were written, an integer template's alpha + // on a float's scale, no-data as the file says it. + let mut data = data; + for (b, band) in data.iter_mut().enumerate() { + band.iter_mut().for_each(|v| *v = holding.of(b, *v, level == 0 || self.classes)); + } + let (data, kind): (Vec>, _) = match self.bytes { + true => (data.into_iter().map(|b| b.into_iter().map(|v| v.round().clamp(0.0, 255.0)).collect()).collect(), "UInt8"), false => (data, "Float32"), }; - let mut r = Raster::new(t.name.clone(), lv.w, lv.h, vec![data], gt, t.crs, t.nodata, ColorHint::Gray, kind)?; + let nodata = (self.alpha_scale.is_none() && !self.nodata.is_nan()).then_some(f64::from(self.nodata)).and(t.nodata); + // Its colour as the file says it: red, green and blue, grey and alpha, else grey. + let color = match (&t.color, self.plan.rgb) { + (ColorHint::Rgb { .. }, true) => ColorHint::Rgb { alpha: self.plan.alpha.is_some() }, + (ColorHint::GrayAlpha, false) if self.plan.alpha.is_some() => ColorHint::GrayAlpha, + _ => ColorHint::Gray, + }; + let mut r = Raster::new(t.name.clone(), lv.w, lv.h, data, gt, t.crs, nodata, color, kind)?; if level > 0 { r.overview = Some((full.w, full.h)); } - if let (Some(b), Some(tb)) = (r.bands.first_mut(), t.bands.first()) { + for (b, tb) in r.bands.iter_mut().zip(&t.bands) { b.name.clone_from(&tb.name); + b.wavelength = tb.wavelength; } Ok((info, Some(r))) } } -/// What a [`TileStream`] writes: one band of 32-bit floats, or with `bytes` of bytes whose -/// no-data value is `nodata`, averaged in its overviews. -fn stream_plan(bytes: bool, nodata: Option) -> Plan { +/// What a [`TileStream`] writes: `n` bands of 32-bit floats, or with `bytes` one band of bytes +/// whose no-data value is `nodata`, averaged in its overviews; red, green and blue first for an +/// RGB `color` of three bands or more (the fourth alpha when it says so), grey and alpha first for +/// grey and alpha, else grey, the further bands nothing in particular. +fn stream_plan(bytes: bool, nodata: Option, n: usize, color: &ColorHint) -> Plan { let (sample, nodata_int) = match bytes { true => (Sample::Byte, nodata.filter(|d| (0.0..=255.0).contains(d)).map(|d| d as u16)), false => (Sample::Float, None), }; - Plan { bands: vec![0], sample, rgb: false, alpha: None, nodata_int, palette: None, categorical: false } + let (rgb, alpha) = match color { + ColorHint::Rgb { alpha } if n >= 3 => (true, (*alpha && n >= 4).then_some(3)), + ColorHint::GrayAlpha if n >= 2 => (false, Some(1)), + _ => (false, None), + }; + Plan { bands: (0..n).collect(), sample, rgb, alpha, nodata_int, palette: None, categorical: false } +} + +/// How a [`TileStream`] holds a pixel's value in its file: `given` (the template's no-data, or +/// NaN) and NaN as `nodata`, the file's. With `alpha` (its band, and the value it is opaque at), +/// alpha says which pixels have a value instead: its own values divided by that value, 0 (see +/// through) for a pixel with none; the colour bands before it as they are, a black one black; +/// further bands NaN for a value with none. +#[derive(Clone, Copy)] +struct Holding { + given: f32, + nodata: f32, + alpha: Option<(usize, f32)>, +} + +impl Holding { + /// Band `b`'s value `v` as the file holds it, of the full image when `full`: an overview's + /// alpha is a mean of alphas, a pixel with none already 0, whatever value it comes to. + fn of(&self, b: usize, v: f32, full: bool) -> f32 { + let none = v.is_nan() || v == self.given; + match self.alpha { + None if none => self.nodata, + None => v, + Some((a, _)) if b == a && (v.is_nan() || (full && none)) => 0.0, + Some((a, opaque)) if b == a => v / opaque, + Some((a, _)) if b < a => v, + Some(_) if none => f32::NAN, + Some(_) => v, + } + } +} + +/// `rows` of `w` pixels of a colour band made half the size each way as [`average_rows`] makes +/// them, each pixel weighted by `alpha`'s (the same rows of the alpha band, `alpha_none` marking +/// one with none, which counts for nothing), so see-through pixels don't darken an overview's +/// colours; the plain mean where all four are see-through. +fn average_by_alpha(rows: &[f32], alpha: &[f32], w: usize, nodata: f32, alpha_none: f32) -> Vec { + let h = rows.len() / w.max(1); + let (hw, hh) = (w.div_ceil(2), h.div_ceil(2)); + let valid = |v: f32| v.is_finite() && v != alpha_none; + let mut out = Vec::with_capacity(hw * hh); + for y in 0..hh { + for x in 0..hw { + let (mut sum, mut weight) = (0.0f64, 0.0f64); + for (dy, dx) in [(0, 0), (0, 1), (1, 0), (1, 1)] { + let (yy, xx) = (2 * y + dy, 2 * x + dx); + if yy < h + && xx < w + && let (Some(&v), Some(&a)) = (rows.get(yy * w + xx), alpha.get(yy * w + xx)) + // Alpha says whether a colour has a value: a black one is black. + && v.is_finite() + && valid(a) + && a > 0.0 + { + sum += f64::from(v) * f64::from(a); + weight += f64::from(a); + } + } + if weight > 0.0 { + out.push((sum / weight) as f32); + continue; + } + // All four see-through: the plain mean of those with a value, as [`average_rows`]. + let (mut plain, mut n) = (0.0f64, 0u32); + for (dy, dx) in [(0, 0), (0, 1), (1, 0), (1, 1)] { + let (yy, xx) = (2 * y + dy, 2 * x + dx); + if yy < h + && xx < w + && let Some(&v) = rows.get(yy * w + xx) + && v.is_finite() + && v != nodata + { + plain += f64::from(v); + n += 1; + } + } + out.push(if n > 0 { (plain / f64::from(n)) as f32 } else { nodata }); + } + } + out } /// `rows` of `w` pixels made half the size each way, for classes: each pixel the first of the up to -/// four it covers that has a value (not NaN, nor `nodata`), row by row, else `nodata`: always a +/// four it covers that has a finite value (not `nodata`), row by row, else `nodata`: always a /// class one of them is, never one between them. fn pick_rows(rows: &[f32], w: usize, nodata: f32) -> Vec { let h = rows.len() / w.max(1); @@ -1442,7 +1666,7 @@ fn pick_rows(rows: &[f32], w: usize, nodata: f32) -> Vec { } /// `rows` of `w` pixels made half the size each way: each pixel the mean of the up to four it -/// covers that have a value (not NaN, nor `nodata`), else `nodata`; an odd last row or column +/// covers that have a finite value (not `nodata`), else `nodata`; an odd last row or column /// covers itself alone. fn average_rows(rows: &[f32], w: usize, nodata: f32) -> Vec { let h = rows.len() / w.max(1); @@ -1587,6 +1811,137 @@ mod tests { assert!(stream.finish().is_err()); } + /// A stream of several bands (#2865): an RGB template's three are written as red, green and + /// blue, five plain ones as grey with four more, each read back pixel for pixel, with its + /// name, the colour it was given, and its overviews averaged band by band; the overview kept + /// holds every band. Bands given unevenly are an error. + #[test] + fn a_streamed_raster_of_several_bands_reads_back_band_by_band() { + let (w, h) = (700u32, 600u32); + let value = |b: usize, x: u32, y: u32| { + if (x * 7 + y * 3 + b as u32).is_multiple_of(89) { f32::NAN } else { (x as f32) * 0.5 - (y as f32) * 0.25 + b as f32 * 100.0 } + }; + for (n, color) in [ + (3usize, ColorHint::Rgb { alpha: false }), + (5, ColorHint::Gray), + (5, ColorHint::Rgb { alpha: false }), + (3, ColorHint::GrayAlpha), + ] { + let bands: Vec> = (0..n).map(|b| (0..h).flat_map(|y| (0..w).map(move |x| value(b, x, y))).collect()).collect(); + let mut template = utm(1, 1, vec![vec![0.0]; n], color.clone(), "Float32", Some(-9999.0)); + template.bands.iter_mut().enumerate().for_each(|(b, band)| { + band.name = format!("band {b}"); + band.wavelength = Some(500.0 + b as f64); + }); + let mut out = Cursor::new(Vec::new()); + let mut stream = TileStream::new(&template, w, h, Samples::Floats, &mut out).unwrap().keeping(1 << 20); + assert!(stream.put(&bands[0][..w as usize]).is_err(), "one band of {n}"); + let mut at = 0usize; + for rows in [3usize, 509, 88] { + let m = rows * w as usize; + let rows: Vec<&[f32]> = bands.iter().map(|b| &b[at..at + m]).collect(); + stream.put_bands(&rows).unwrap(); + at += m; + } + let (info, kept) = stream.finish().unwrap(); + assert_eq!(info.levels, vec![(700, 600), (350, 300)], "{n} bands"); + let bytes = out.into_inner(); + let back = geotiff::read(Cursor::new(&bytes), "back").unwrap(); + // With alpha (grey and alpha), alpha says which pixels have a value, so no no-data + // value is written and the pixels are as the alpha test below has them. + let alpha = color == ColorHint::GrayAlpha; + assert_eq!( + (back.width, back.height, back.nodata, back.band_count(), &back.color), + (w, h, (!alpha).then_some(-9999.0), n, &color), + "{n} bands" + ); + for (b, band) in back.bands.iter().enumerate() { + assert_eq!(band.name, format!("band {b}")); + for y in (0..h).filter(|_| !alpha) { + for x in 0..w { + let want = value(b, x, y); + assert_eq!(back.value(b, i64::from(x), i64::from(y)), (!want.is_nan()).then_some(want), "band {b} {x},{y}"); + } + } + } + let level = geotiff::read_limited(geotiff::reader(Cursor::new(&bytes)).unwrap(), "o", 350 * 300 * n, None).unwrap(); + let kept = kept.unwrap(); + assert_eq!((level.width, level.height, kept.width, kept.height, kept.band_count()), (350, 300, 350, 300, n)); + for (b, data) in bands.iter().enumerate().filter(|_| !alpha) { + let filled: Vec = data.iter().map(|v| if v.is_nan() { -9999.0 } else { *v }).collect(); + let want = average_rows(&filled, w as usize, -9999.0); + assert_eq!(level.bands[b].data, want, "{n} bands: band {b}'s overview"); + assert_eq!(kept.bands[b].data, want, "{n} bands: band {b} kept"); + } + assert_eq!(kept.color, color); + assert!( + kept.bands.iter().enumerate().all(|(b, band)| band.wavelength == Some(500.0 + b as f64)), + "{n} bands: wavelengths kept" + ); + // The in-place reader finds every band and the colour too. + let Ok(crate::raster::cog::Parse::Done(layout)) = + crate::raster::cog::layout(&crate::raster::cog::Sparse::default().with(0, bytes)) + else { + panic!("not a tiled GeoTIFF the reader reads in place"); + }; + assert_eq!((layout.bands, &layout.color, layout.levels.len()), (n, &color, 2), "{n} bands in place"); + } + // With alpha, alpha says which pixels have a value: no no-data value is written, an + // integer template's alpha is held on a float's scale, opaque at 1, a black pixel's colour + // (the template's no-data, 0) stays black, a pixel with none is see-through, and an + // overview's colours are weighted by alpha, a see-through pixel's counting for nothing. + let (w, h) = (600u32, 600u32); + let mut rgba = utm(1, 1, vec![vec![0.0]; 4], ColorHint::Rgb { alpha: true }, "UInt8", Some(0.0)); + rgba.bands.iter_mut().for_each(|b| b.name = String::new()); + let mut out = Cursor::new(Vec::new()); + let mut stream = TileStream::new(&rgba, w, h, Samples::Floats, &mut out).unwrap().keeping(1 << 20); + let px = (w * h) as usize; + let (mut red, mut colour, mut alpha) = (vec![50.0f32; px], vec![50.0f32; px], vec![255.0f32; px]); + alpha[0] = 128.0; + red[1] = 0.0; + let at = |x: usize, y: usize| y * w as usize + x; + for x in [2, 3] { + (red[at(x, 2)], colour[at(x, 2)]) = (200.0, 200.0); + (red[at(x, 3)], colour[at(x, 3)], alpha[at(x, 3)]) = (0.0, 0.0, 0.0); + } + stream.put_bands(&[&red, &colour, &colour, &alpha]).unwrap(); + let (_, kept) = stream.finish().unwrap(); + let back = geotiff::read(Cursor::new(out.into_inner()), "back").unwrap(); + assert_eq!((&back.color, back.nodata), (&ColorHint::Rgb { alpha: true }, None)); + assert_eq!((back.value(3, 1, 0), back.value(3, 0, 0), back.value(0, 1, 0)), (Some(1.0), Some(128.0 / 255.0), Some(0.0))); + let kept = kept.unwrap(); + assert_eq!((kept.width, kept.nodata, &kept.color), (300, None, &ColorHint::Rgb { alpha: true })); + let one = |b: usize, x: usize, y: usize| kept.bands[b].data[y * 300 + x]; + let corner = ((128.0f64 + 3.0 * 255.0) / 4.0) as f32 / 255.0; + let red_corner = ((50.0 * 128.0 + 50.0 * 255.0 * 2.0) / (128.0 + 255.0 * 3.0)) as f32; + assert_eq!((one(3, 0, 0), one(0, 0, 0), one(3, 2, 0)), (corner, red_corner, 1.0)); + assert_eq!((one(0, 1, 1), one(3, 1, 1)), (200.0, 0.5), "see-through pixels darken nothing and halve alpha"); + // An overview's alpha is a mean of alphas, kept whatever it comes to: one of 64 and 192 is + // 128, the template's no-data value here, and still half see-through. + let mut rgba = utm(1, 1, vec![vec![0.0]; 4], ColorHint::Rgb { alpha: true }, "UInt8", Some(128.0)); + rgba.bands.iter_mut().for_each(|b| b.name = String::new()); + let mut out = Cursor::new(Vec::new()); + let mut stream = TileStream::new(&rgba, w, h, Samples::Floats, &mut out).unwrap().keeping(1 << 20); + let checker: Vec = (0..px).map(|i| if (i % w as usize + i / w as usize).is_multiple_of(2) { 64.0 } else { 192.0 }).collect(); + let colour = vec![50.0f32; px]; + stream.put_bands(&[&colour, &colour, &colour, &checker]).unwrap(); + let (_, kept) = stream.finish().unwrap(); + let bytes = out.into_inner(); + let level = geotiff::read_limited(geotiff::reader(Cursor::new(&bytes)).unwrap(), "o", 300 * 300 * 4, None).unwrap(); + assert_eq!(level.width, 300); + assert!(level.bands[3].data.iter().all(|a| *a == 128.0 / 255.0), "the file's overview"); + assert!(kept.unwrap().bands[3].data.iter().all(|a| *a == 128.0 / 255.0), "the overview kept"); + // More bands than a reader decodes a tile of are refused; the plan counts the overview + // kept, the coarsest level when none fits. + let many = utm(1, 1, vec![vec![0.0]; TileStream::>>::most_bands() + 1], ColorHint::Gray, "Float32", None); + assert!(TileStream::new(&many, 10, 10, Samples::Floats, &mut Cursor::new(Vec::new())).is_err()); + let peak = |kept: usize| TileStream::>>::peak(2048, 2048, 32, kept); + assert_eq!(peak(0), peak(512 * 512 * 32), "the 512 × 512 level kept either way"); + // A hillshade is one band. + let shade = utm(1, 1, vec![vec![0.0]; 2], ColorHint::Gray, "UInt8", Some(0.0)); + assert!(TileStream::new(&shade, 10, 10, Samples::Hillshade, &mut Cursor::new(Vec::new())).is_err()); + } + /// 3000 × 2000 colour pixels: red rises across, green down, blue is a checker of 2 × 2 blocks. fn big_rgb() -> Raster { let (w, h) = (3000u32, 2000u32); diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index d39ba90360..14ec9e0968 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1016,6 +1016,17 @@ impl Span { } } +/// The columns and rows of a chunk (a tile, or a strip of the image's width) of the full image of +/// the GeoTIFF at `path`, as its tags give them; `None` when it can't be read. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn chunk_size(path: &std::path::Path) -> Option<(u32, u32)> { + let file = std::io::BufReader::new(std::fs::File::open(path).ok()?); + let mut dec = Decoder::new(reader(file).ok()?).ok()?.with_limits(Limits::default()); + let (w, h) = dec.dimensions().ok()?; + let c = Chunks::new(&mut dec, w, h, 1, false); + Some((c.cw, c.ch)) +} + /// How an image is cut into chunks (strips or tiles), and how they're laid out. #[derive(Clone, Copy)] struct Chunks { diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 33905bf3fa..49232a0828 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1513,6 +1513,13 @@ pub struct PartRead { pub full: (u32, u32), } +/// The columns and rows of a tile of the GeoTIFF at `path` (a strip's: the image's width), which a +/// part read decodes whole ([`read_path_part`]); `None` when they can't be read. +#[cfg(not(target_arch = "wasm32"))] +pub fn chunk_size(path: &Path) -> Option<(u32, u32)> { + geotiff::chunk_size(path) +} + /// `part` of the GeoTIFF at `path`, as [`read_path`] reads the file but holding only that part, /// at the finest level whose part fits `max` samples: the full image when it does, read from the /// strips or tiles that hold it alone. The `.aux.xml` beside it is applied as it is to the whole diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 2b3ea8d9a8..273c4ad11d 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1573,23 +1573,15 @@ pub(crate) fn supervised_work(s: &Session, p: &Value) -> Result 1 && !super::in_blocks::affordable(row.saturating_mul(u64::from(strip)).saturating_mul(2)) { - strip /= 2; - } - // From the start of the row of tiles the window begins in (a block's rows, which a - // file's tiles of 256 or 512 rows divide), so no row of tiles is read for two strips; - // the rows above the window are visited by no polygon. - let top = under.start / bh * bh; + // Within what the computer can give, and what a part read reads at full size. + let fits = |rows: u32| { + super::in_blocks::affordable(row.saturating_mul(u64::from(rows)).saturating_mul(2)) && reading.part_fits(width, rows) + }; + let (top, strip) = training_strips(under.start, reading.chunk().map(|c| c.1), fits); reading .each_block((cols.start, cols.end), (top, under.end), (width, strip), |_, _, read| { means.add(&read.raster, read.at, &read.grid.0).map_err(String::from) @@ -1867,25 +1859,42 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result resample_in_blocks(&reading, k, out), - // Short of it since then: the file read as before. - false => resample_whole(&r, factor, out), + return Ok(Box::new(move || { + // Blocks of whole tiles where the part reader reads them at full size and + // the computer can give them now, else of the factor alone; the memory + // planned for is the blocks read. + let fits = |cols: u32, rows: u32| reading.part_fits(cols, rows); + let blocks = [resample_block(k, reading.chunk(), fits), resample_block(k, None, fits)]; + let block = blocks + .into_iter() + .find(|b| fits(b.0, b.1) && super::in_blocks::affordable(resample_need(w, h, bands, held, *b, k))); + match block { + Some(block) => resample_in_blocks(&reading, k, out, folder, block), + // Short of it since then: the file read as before. + None => resample_whole(&r, factor, out), + } })); } } @@ -1895,13 +1904,57 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result u32 { + uint(p, "factor").unwrap_or(2).clamp(2, 64) as u32 +} + +/// What a resample `w` × `h` of `bands` bands made a block at a time holds, planned before it is +/// set aside. `held`: its bands and its file, and for several bands the copy of them interleaved +/// that the file is made from (one band is written from itself). Written: a row of blocks of the +/// result (blocks of `block` of the file, `k` times the result's), and its file's levels' rows as +/// they are written, with the tables of its tiles and the overview kept. Either way, a block of the +/// file as it is read: its samples, and its tiles as decoded, about as many again. +#[cfg(not(target_arch = "wasm32"))] +fn resample_need(w: u32, h: u32, bands: usize, held: bool, block: (u32, u32), k: u32) -> u64 { + // 4 bytes a sample, twice: as held, and as its tiles are decoded. + let input = u64::from(block.0).saturating_mul(u64::from(block.1)).saturating_mul(bands as u64).saturating_mul(4 * 2); + if held { + let copies = if bands > 1 { 3 } else { 2 }; + return u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bands as u64).saturating_mul(4 * copies).saturating_add(input); + } + let rows = block.1 / k.max(1); + let row = u64::from(w).saturating_mul(u64::from(rows)).saturating_mul(bands as u64).saturating_mul(4); + super::in_blocks::stream_peak(w, h, bands).saturating_add(row).saturating_add(input) +} + +/// The columns and rows of the blocks a resample by `k` reads of a file whose tiles are `chunk`: +/// whole multiples of `k` near [`super::in_blocks::BLOCK`]'s size, and of the tiles too where a +/// common multiple stays within four blocks' columns or rows, so that no tile is decoded for two +/// blocks, and `fits` says the part reader reads a block that size at full size +/// ([`super::in_blocks::Reading::part_fits`]). #[cfg(not(target_arch = "wasm32"))] -fn resample_need(w: u32, h: u32, bands: usize) -> u64 { - let copies = if bands > 1 { 3 } else { 2 }; - u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bands as u64).saturating_mul(4 * copies) +fn resample_block(k: u32, chunk: Option<(u32, u32)>, fits: impl Fn(u32, u32) -> bool) -> (u32, u32) { + let k = k.max(1); + let side = |block: u32, tile: Option| { + let plain = (block / k).max(1) * k; + let Some(tile) = tile.filter(|t| *t > 0) else { return plain }; + let gcd = |mut a: u64, mut b: u64| { + while b != 0 { + (a, b) = (b, a % b); + } + a + }; + let lcm = u64::from(k) / gcd(u64::from(k), u64::from(tile)) * u64::from(tile); + match u32::try_from(lcm) { + Ok(lcm) if lcm <= block.saturating_mul(4) => (block / lcm).max(1) * lcm, + _ => plain, + } + }; + let (bw, bh) = super::in_blocks::BLOCK; + let (aligned, plain) = ((side(bw, chunk.map(|c| c.0)), side(bh, chunk.map(|c| c.1))), (side(bw, None), side(bh, None))); + // Whole tiles each way the part reader reads at full size, else one way, else neither. + [aligned, (aligned.0, plain.1), (plain.0, aligned.1)].into_iter().find(|(c, r)| fits(*c, *r)).unwrap_or(plain) } /// A resample by `factor` of `r` read whole (the finest level of a file read in place that @@ -1913,10 +1966,8 @@ fn resample_whole(r: &super::workflows::Input, factor: u32, out: String) -> Resu // Each output pixel is the mean of the valid pixels it covers; one covering none // takes the result's no-data value (the raster's, else the one cells with no value // take). - let empty = r.nodata.map_or(NODATA, |d| d as f32); - let bands = r - .bands - .iter() + let (empty, alpha) = (resample_empty(&r), alpha_band(&r)); + let bands = (0..r.band_count()) .map(|b| { // A cell reads its k × k block; the cells are counted and cancellable. let cost = (k * k) as usize; @@ -1927,20 +1978,11 @@ fn resample_whole(r: &super::workflows::Input, factor: u32, out: String) -> Resu || (), |_, i| { let (row, col) = ((i / w as usize) as u32, (i % w as usize) as u32); - let (mut sum, mut n) = (0.0f64, 0u32); - for dy in 0..k { - for dx in 0..k { - let (x, y) = (col * k + dx, row * k + dy); - if x >= r.width || y >= r.height { - continue; - } - if let Some(v) = b.data.get((y * r.width + x) as usize).copied().filter(|v| r.is_valid(*v)) { - sum += v as f64; - n += 1; - } - } - } - if n > 0 { (sum / n as f64) as f32 } else { empty } + let cells = (0..k) + .flat_map(|dy| (0..k).map(move |dx| (col * k + dx, row * k + dy))) + .filter(|(x, y)| *x < r.width && *y < r.height) + .map(|(x, y)| (y * r.width + x) as usize); + resample_mean(&r, b, alpha, cells, empty) }, ) }) @@ -1957,7 +1999,34 @@ fn resample_whole(r: &super::workflows::Input, factor: u32, out: String) -> Resu }); // The blocks average values rounded when the file was read, some or all of them. out.keep_rounded_mark(&r); - super::workflows::made(out, None) + let notes: Vec = resample_palette_note(&r, &r.name).into_iter().collect(); + let then: super::workflows::Then = Box::new(move |s: &mut Session, _: &mut Value| { + for note in notes { + s.notify(note, false); + } + }); + super::workflows::made_then(out, None, Some(then)) +} + +/// What a resample `out` of `source` written to a file says it leaves out: with alpha, the file +/// says which pixels have a value by alpha, not by the no-data value `source` has, which a held +/// resample keeps (`cogwrite::TileStream`). +#[cfg(not(target_arch = "wasm32"))] +fn alpha_nodata_note(source: &Raster, out: &str) -> Option { + let alpha = match source.color { + ColorHint::Rgb { alpha } => alpha && source.band_count() >= 4, + ColorHint::GrayAlpha => source.band_count() >= 2, + _ => false, + }; + let d = source.nodata.filter(|_| alpha)?; + Some(format!("{out}: its no-data value {d} isn't written to its file: alpha says which of its pixels have a value")) +} + +/// What a resample of `r` (layer `layer`) says it leaves out: a palette's colour table, whose +/// indexes it averages as grey values (a mean of indexes is no colour of the table). +fn resample_palette_note(r: &Raster, layer: &str) -> Option { + matches!(r.color, ColorHint::Palette(_)) + .then(|| format!("{layer}: its colour table isn't kept: its colour indexes are resampled as grey values")) } /// A resample by `k` of a large file read in place, made a block at a time from the file at its @@ -1967,102 +2036,224 @@ fn resample_whole(r: &super::workflows::Input, factor: u32, out: String) -> Resu /// output pixel spans two. Its memory ([`resample_need`]) is planned by the caller, which reads /// the file as before when the computer can't give it. #[cfg(not(target_arch = "wasm32"))] -fn resample_in_blocks(reading: &super::in_blocks::Reading, k: u32, out: String) -> Result { +fn resample_in_blocks( + reading: &super::in_blocks::Reading, + k: u32, + out: String, + folder: Option, + size: (u32, u32), +) -> Result { let (fw, fh) = reading.full(); let (w, h) = ((fw / k).max(1), (fh / k).max(1)); - let (bw, bh) = super::in_blocks::BLOCK; - let size = ((bw / k).max(1) * k, (bh / k).max(1) * k); - let need = resample_need(w, h, reading.held().band_count()); + let need = resample_need(w, h, reading.held().band_count(), folder.is_none(), size, k); let _held = rustgis_data::memory::Holding::of(need); - let mut bands: Vec> = Vec::new(); - let mut first: Option = None; - let mut marks: Vec = Vec::new(); - let rounded = reading.each_block((0, w * k), (0, h * k), size, |cols, rows, read| { - let r = &read.raster; - let (ax, ay) = read.at; - // A pixel with no value takes the result's no-data value, as a whole raster's resample. - let empty = r.nodata.map_or(NODATA, |d| d as f32); - if bands.is_empty() { - bands = (0..r.band_count()).map(|_| rasterops::new_band(w as usize, h as usize, empty)).collect::>()?; - marks = vec![false; r.band_count()]; + let note = |rounded: u64| { + let mut notes = super::gp::tiled_read_notes(&[super::gp::ReadNote::rounded(reading.layer(), rounded)], "its"); + notes.extend(resample_palette_note(reading.held(), reading.layer())); + notes + }; + let Some(folder) = folder else { + let mut res: Vec> = Vec::new(); + let mut first: Option = None; + let mut marks: Vec = Vec::new(); + let rounded = reading.each_block((0, w * k), (0, h * k), size, |cols, rows, read| { + let r = &read.raster; + if res.is_empty() { + res = (0..r.band_count()) + .map(|_| rasterops::new_band(w as usize, h as usize, resample_empty(r))) + .collect::>()?; + marks = vec![false; r.band_count()]; + } + marks.iter_mut().enumerate().for_each(|(b, m)| *m |= r.band_rounded(b)); + let (ox0, oy0) = (cols.0 / k, rows.0 / k); + for (means, dst) in block_means(read, k, cols, rows)?.iter().zip(res.iter_mut()) { + let ow = ((cols.1 - cols.0) / k) as usize; + for (row, line) in means.chunks(ow.max(1)).enumerate() { + let at = (oy0 as usize + row) * w as usize + ox0 as usize; + let d = dst + .get_mut(at..at + line.len()) + .ok_or_else(|| format!("{}: a block's means don't fit the result", reading.layer()))?; + d.copy_from_slice(line); + } + } + if first.is_none() { + first = Some(resampled_as(read, k, &out)?); + } + Ok(()) + })?; + let t = first.ok_or_else(|| format!("{}: it has no pixels", reading.layer()))?; + let mut res = + Raster::new(out, w, h, res, t.transform, t.crs, t.nodata, t.color.clone(), t.data_type.clone()).map_err(|e| e.to_string())?; + res.bands.iter_mut().zip(&t.bands).for_each(|(o, i)| { + o.name.clone_from(&i.name); + o.wavelength = i.wavelength; + }); + // The blocks average values rounded when the file was read, some or all of them. + res.rounded = Vec::new(); + res.rounded_some = if marks.contains(&true) { marks } else { Vec::new() }; + let notes = note(rounded); + let then: super::workflows::Then = Box::new(move |s: &mut Session, _: &mut Value| { + for note in notes { + s.notify(note, false); + } + }); + return super::workflows::made_then(res, None, Some(then)); + }; + // Too large to hold: written a row of blocks at a time to the results folder, read in place. + let (oh, row_len) = (size.1 / k, w as usize * (size.1 / k) as usize); + let (dest, staged, (overview, rounded)) = super::in_blocks::write_new(&folder, &out, |sink| { + let (mut sink, mut stream, mut row) = (Some(sink), None, Vec::new()); + let mut marks: Vec = Vec::new(); + let rounded = reading + .each_block((0, w * k), (0, h * k), size, |cols, rows, read| { + marks.resize(read.raster.band_count(), false); + marks.iter_mut().enumerate().for_each(|(b, m)| *m |= read.raster.band_rounded(b)); + if stream.is_none() { + // Placed, named and coloured as a resample held is, its bands floats. + let t = resampled_as(read, k, &out)?; + let sink = sink.take().ok_or("the result's file was started twice")?; + stream = Some(super::in_blocks::stream(&t, w, h, raster::cogwrite::Samples::Floats, sink)?); + let empty = resample_empty(&read.raster); + row = (0..t.band_count()).map(|_| rasterops::new_band(w as usize, oh as usize, empty)).collect::>()?; + } + let ox0 = (cols.0 / k) as usize; + let ow = ((cols.1 - cols.0) / k) as usize; + for (means, dst) in block_means(read, k, cols, rows)?.iter().zip(row.iter_mut()) { + for (y, line) in means.chunks(ow.max(1)).enumerate() { + let at = y * w as usize + ox0; + let d = dst + .get_mut(at..at + line.len()) + .ok_or_else(|| format!("{}: a block's means don't fit the result", reading.layer()))?; + d.copy_from_slice(line); + } + } + // A row of blocks done: its rows of the result written. + if cols.1 == w * k { + let n = ((rows.1 - rows.0) / k) as usize * w as usize; + let rows: Vec<&[f32]> = row.iter().map(|b| b.get(..n.min(row_len)).unwrap_or_default()).collect(); + stream + .as_mut() + .map_or(Ok(()), |s: &mut raster::cogwrite::TileStream<_>| s.put_bands(&rows).map_err(|e| e.to_string()))?; + } + Ok(()) + }) + // A Cancel stays one, as on the path that holds its result. + .map_err(rustgis_data::DataError::of_conversion)?; + let stream = stream.ok_or_else(|| rustgis_data::DataError::Format(format!("{}: it has no pixels", reading.layer())))?; + let (_, mut overview) = stream.finish()?; + // The blocks average values rounded when the file was read, some or all of them, as a + // held resample says of its bands. + if let Some(o) = overview.as_mut().filter(|_| marks.contains(&true)) { + o.rounded = Vec::new(); + o.rounded_some = marks; } - marks.iter_mut().enumerate().for_each(|(b, m)| *m |= r.band_rounded(b)); - // This block's output pixels: columns and rows of the output. - let (ox0, ox1, oy0, oy1) = (cols.0 / k, cols.1 / k, rows.0 / k, rows.1 / k); - let ow = (ox1 - ox0) as usize; - for (band, dst) in r.bands.iter().zip(bands.iter_mut()) { - let means = rasterops::per_index( + Ok((overview, rounded)) + })?; + let made = format!("resampled by {k} from {} at its full {fw} × {fh}", reading.layer()); + let mut notes = note(rounded); + let source = reading.held(); + notes.extend(alpha_nodata_note(source, &out)); + let mut made = super::in_blocks::file_layer(out, &dest, staged, overview, &made, notes)?; + // A byte colour image's resample is drawn on its 0 to 255, as one held is, not stretched as + // the floats its file holds would be. + if source.data_type == "UInt8" && matches!(source.color, ColorHint::Rgb { .. }) && source.band_count() >= 3 { + made.layer_mut().style.stretch = rustgis_map::Stretch::Custom { min: 0.0, max: 255.0, bands: None }; + } + Ok(made) +} + +/// The means of a block of a resample by `k` (`read`, holding columns `cols` and rows `rows` of +/// the full image, whole multiples of `k`), a band each: each output pixel the mean of the valid +/// pixels of the `k` × `k` it covers, row by row, as a whole raster's resample makes it, and one +/// covering none the result's no-data value ([`resample_empty`]). +#[cfg(not(target_arch = "wasm32"))] +fn block_means(read: &rustgis_data::raster::PartRead, k: u32, cols: (u32, u32), rows: (u32, u32)) -> Result>, String> { + let r = &read.raster; + let (empty, alpha) = (resample_empty(r), alpha_band(r)); + let (ax, ay) = read.at; + let (ox0, ox1, oy0, oy1) = (cols.0 / k, cols.1 / k, rows.0 / k, rows.1 / k); + let ow = (ox1 - ox0) as usize; + (0..r.band_count()) + .map(|b| { + rasterops::per_index( ow * (oy1 - oy0) as usize, ow, (k * k) as usize, || (), |_, i| { let (ox, oy) = (ox0 + (i % ow.max(1)) as u32, oy0 + (i / ow.max(1)) as u32); - let (mut sum, mut n) = (0.0f64, 0u32); - for dy in 0..k { - for dx in 0..k { - let (x, y) = (ox * k + dx - ax, oy * k + dy - ay); - if let Some(v) = band.data.get((y * r.width + x) as usize).copied().filter(|v| r.is_valid(*v)) { - sum += f64::from(v); - n += 1; - } - } - } - if n > 0 { (sum / f64::from(n)) as f32 } else { empty } + let cells = (0..k).flat_map(|dy| (0..k).map(move |dx| ((oy * k + dy - ay) * r.width + (ox * k + dx - ax)) as usize)); + resample_mean(r, b, alpha, cells, empty) }, - )?; - for (row, line) in means.chunks(ow.max(1)).enumerate() { - let at = (oy0 as usize + row) * w as usize + ox0 as usize; - let d = - dst.get_mut(at..at + line.len()).ok_or_else(|| format!("{}: a block's means don't fit the result", reading.layer()))?; - d.copy_from_slice(line); - } - } - if first.is_none() { - // Its bands, place and kind, as a whole read gives them. - let mut meta = Raster::new( - r.name.clone(), - 1, - 1, - vec![vec![0.0]; r.band_count()], - read.grid.0, - r.crs, - r.nodata, - r.color.clone(), - r.data_type.clone(), ) - .map_err(|e| e.to_string())?; - meta.bands.iter_mut().zip(&r.bands).for_each(|(o, i)| { - o.name.clone_from(&i.name); - o.wavelength = i.wavelength; - }); - first = Some(meta); + }) + .collect() +} + +/// The band of `r` that says which of its pixels have a value: an RGB raster's fourth when it +/// says it is alpha, grey and alpha's second. +fn alpha_band(r: &Raster) -> Option { + match r.color { + ColorHint::Rgb { alpha: true } if r.band_count() >= 4 => Some(3), + ColorHint::GrayAlpha if r.band_count() >= 2 => Some(1), + _ => None, + } +} + +/// One resampled pixel of band `b` of `r`, from its pixels at `cells` (indexes into a band's +/// values): the mean of those with a value, `empty` for none. With `alpha`, which says which +/// pixels have a value, alpha's own mean counts a pixel with none as see-through (0), and the +/// colours before it are weighted by alpha, so a see-through pixel counts for nothing and a black +/// one is black (the plain mean where all are see-through). +fn resample_mean(r: &Raster, b: usize, alpha: Option, cells: impl Iterator + Clone, empty: f32) -> f32 { + let value = |band: usize, i: usize| r.bands.get(band).and_then(|x| x.data.get(i)).copied(); + let mean = |(sum, n): (f64, u32)| if n > 0 { (sum / f64::from(n)) as f32 } else { empty }; + let plain = + || mean(cells.clone().filter_map(|i| value(b, i).filter(|v| r.is_valid(*v))).fold((0.0, 0), |(s, n), v| (s + f64::from(v), n + 1))); + match alpha { + Some(a) if b == a => mean( + cells + .clone() + .filter_map(|i| value(b, i).map(|v| if r.is_valid(v) { v } else { 0.0 })) + .fold((0.0, 0), |(s, n), v| (s + f64::from(v), n + 1)), + ), + Some(a) if b < a => { + let (sum, weight) = + cells.clone().fold((0.0f64, 0.0f64), |(s, w), i| match (value(b, i), value(a, i).filter(|v| r.is_valid(*v))) { + (Some(v), Some(al)) if v.is_finite() && al > 0.0 => (s + f64::from(v) * f64::from(al), w + f64::from(al)), + _ => (s, w), + }); + if weight > 0.0 { (sum / weight) as f32 } else { plain() } } - Ok(()) - })?; - let meta = first.ok_or_else(|| format!("{}: it has no pixels", reading.layer()))?; - let gt = GeoTransform { - pixel_width: meta.transform.pixel_width * f64::from(k), - pixel_height: meta.transform.pixel_height * f64::from(k), - ..meta.transform - }; - let nodata = meta.nodata.or(Some(NODATA as f64)); - let color = if matches!(meta.color, ColorHint::Palette(_)) { ColorHint::Gray } else { meta.color.clone() }; - let mut res = Raster::new(out, w, h, bands, gt, meta.crs, nodata, color, meta.data_type.clone()).map_err(|e| e.to_string())?; - res.bands.iter_mut().zip(&meta.bands).for_each(|(o, i)| { + _ => plain(), + } +} + +/// The value a resampled pixel covering no pixel of `r` with a value takes: the result's no-data +/// value, `r`'s, else the one cells with no value take. +fn resample_empty(r: &Raster) -> f32 { + r.nodata.map_or(NODATA, |d| d as f32) +} + +/// A raster of one pixel of each band of a resample by `k` of the file `read` is a part of, +/// called `out`: placed on the resample's grid (the file's, `k` times coarser), with its system, +/// no-data value (the file's, else the one cells with no value take), colour (grey for a palette's +/// indexes, which a mean isn't), type and bands' names and wavelengths, as a whole raster's +/// resample makes them. +#[cfg(not(target_arch = "wasm32"))] +fn resampled_as(read: &rustgis_data::raster::PartRead, k: u32, out: &str) -> Result { + let r = &read.raster; + let grid = read.grid.0; + let gt = GeoTransform { pixel_width: grid.pixel_width * f64::from(k), pixel_height: grid.pixel_height * f64::from(k), ..grid }; + let nodata = r.nodata.or(Some(NODATA as f64)); + let color = if matches!(r.color, ColorHint::Palette(_)) { ColorHint::Gray } else { r.color.clone() }; + let mut t = Raster::new(out.to_string(), 1, 1, vec![vec![0.0]; r.band_count()], gt, r.crs, nodata, color, r.data_type.clone()) + .map_err(|e| e.to_string())?; + t.bands.iter_mut().zip(&r.bands).for_each(|(o, i)| { o.name.clone_from(&i.name); o.wavelength = i.wavelength; }); - // The blocks average values rounded when the file was read, some or all of them. - res.rounded = Vec::new(); - res.rounded_some = if marks.contains(&true) { marks } else { Vec::new() }; - let notes = super::gp::tiled_read_notes(&[super::gp::ReadNote::rounded(reading.layer(), rounded)], "its"); - let then: super::workflows::Then = Box::new(move |s: &mut Session, _: &mut Value| { - for note in notes { - s.notify(note, false); - } - }); - super::workflows::made_then(res, None, Some(then)) + Ok(t) } /// The pixel window of `r` covering extent `e`'s edges (columns, rows); an error when it can't be @@ -2449,6 +2640,27 @@ fn edge_pixels_on(r: &Raster, gt: &GeoTransform, bounds: Extent, e: &Extent) -> }) } +/// Where the strips of rows a training read takes begin, and how many rows each holds, for a +/// window whose first row is `start` in a file whose tiles have `tile` rows (`None`: a block's): +/// from the start of the row of tiles the window begins in, whole rows of tiles at a time (as many +/// as make a block's rows, for tiles or strips shorter than that), so each is decoded once, where +/// `fits` says the computer can give a strip that tall (the part read and its +/// tiles as decoded, about twice the strip); half as many, and again, where it can't. A strip of +/// fewer rows than a tile decodes its row of tiles once for each strip in it: a window as wide as +/// the mosaic of #2761 (83517 columns, 3 bands) needs 513 MB at once for strips of 512 rows. The +/// rows above the window are in no polygon's window. +#[cfg(not(target_arch = "wasm32"))] +fn training_strips(start: u32, tile: Option, fits: impl Fn(u32) -> bool) -> (u32, u32) { + let tile = tile.filter(|t| *t > 0).unwrap_or(super::in_blocks::BLOCK.1); + // Rows of tiles at least a block's rows, so a file in strips of a row or a few isn't read a + // strip at a time. + let mut strip = tile.saturating_mul((super::in_blocks::BLOCK.1 / tile).max(1)); + while strip > 1 && !fits(strip) { + strip /= 2; + } + (start / tile * tile, strip) +} + /// The training polygons of `ds`, each with its class (field `fi`'s value), in the layer's /// order: a polygon of several parts is a polygon each. Cancel is looked at as they are gathered. fn training_polygons(ds: &rustgis_data::Dataset, fi: usize) -> Result>)>, String> { @@ -3275,3 +3487,92 @@ fn pixel_window_tells_a_miss_from_a_place_it_cant_take() { let e = pixel_window(&r, &Extent::new(-170.0, -10.0, 10.0, 10.0)).unwrap_err(); assert!(e.contains("coordinate system can't place the polygon's edge"), "{e}"); } + +/// A resample's blocks are whole multiples of its factor, and of the file's tiles where a common +/// multiple stays within four blocks, so no tile is decoded for two blocks; strips as tall as the +/// image, or a factor with no small common multiple, keep blocks of the factor alone. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_resample_reads_blocks_of_whole_tiles() { + let (bw, bh) = super::in_blocks::BLOCK; + for (k, chunk) in [ + (2u32, Some((256u32, 256u32))), + (3, Some((256, 256))), + (5, Some((512, 512))), + (3, Some((100_000, 16))), + (3, None), + (61, Some((256, 256))), + ] { + let (cols, rows) = resample_block(k, chunk, |_, _| true); + assert!(cols % k == 0 && rows % k == 0, "{k} {chunk:?}: {cols} × {rows}"); + let lcm = |t: u32| (1..=t).map(|i| i * k).find(|m| m % t == 0).unwrap_or(0); + match chunk { + Some((tw, th)) => { + assert_eq!(cols % tw == 0, lcm(tw) <= 4 * bw, "{k} {chunk:?}: {cols} columns"); + assert_eq!(rows % th == 0, lcm(th) <= 4 * bh, "{k} {chunk:?}: {rows} rows"); + } + None => assert_eq!((cols, rows), ((bw / k) * k, (bh / k) * k)), + } + } + // Blocks the part reader can't read at full size give way to blocks of the factor alone, one + // way or both. + let plain = ((bw / 3) * 3, (bh / 3) * 3); + assert_eq!(resample_block(3, Some((256, 256)), |c, r| c <= plain.0 && r <= plain.1), plain); + assert_eq!(resample_block(3, Some((256, 256)), |c, _| c <= plain.0), (plain.0, 768)); +} + +/// A training read's strips start on a row of the file's own tiles and hold one, so a file of +/// 1024-row tiles has each decoded once; where a strip that tall isn't given, they hold half as +/// many rows, and again. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn training_strips_follow_the_files_tiles() { + assert_eq!(training_strips(1500, Some(1024), |_| true), (1024, 1024)); + assert_eq!(training_strips(1500, Some(256), |_| true), (1280, 512)); + // A file in strips of one row is read a block's rows at a time, not a row. + assert_eq!(training_strips(1500, Some(1), |_| true), (1500, super::in_blocks::BLOCK.1)); + assert_eq!(training_strips(1500, Some(1024), |rows| rows <= 300), (1024, 256)); + let block = super::in_blocks::BLOCK.1; + assert_eq!(training_strips(1500, None, |_| true), (1500 / block * block, block)); + assert_eq!(training_strips(7, Some(1024), |_| false), (0, 1)); +} + +/// A resample written to a file of an image with alpha and a no-data value says the value isn't +/// written, as alpha says which pixels have one; nothing for an image without alpha or no-data. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_written_resample_with_alpha_says_its_no_data_value_goes() { + let gt = GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 0.001, pixel_height: -0.001 }; + let image = |bands: usize, color: ColorHint, nodata: Option| { + Raster::new("image", 2, 2, vec![vec![1.0; 4]; bands], gt, Crs::LonLat, nodata, color, "UInt8").unwrap() + }; + let note = alpha_nodata_note(&image(4, ColorHint::Rgb { alpha: true }, Some(0.0)), "out"); + assert!(note.is_some_and(|n| n.contains("no-data value 0 isn't written"))); + assert!(alpha_nodata_note(&image(2, ColorHint::GrayAlpha, Some(5.0)), "out").is_some()); + assert!(alpha_nodata_note(&image(4, ColorHint::Rgb { alpha: true }, None), "out").is_none()); + assert!(alpha_nodata_note(&image(3, ColorHint::Rgb { alpha: false }, Some(0.0)), "out").is_none()); +} + +/// A resampled pixel of an image with alpha and a no-data value: alpha's mean counts a +/// see-through pixel as 0, so half see-through stays half; the colours are weighted by alpha, a +/// see-through one counting for nothing and a black one black; without alpha, the mean of the +/// pixels with a value, as before. +#[test] +fn a_resampled_pixel_with_alpha_is_weighted_by_it() { + let gt = GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 0.001, pixel_height: -0.001 }; + let red = vec![200.0, 200.0, 0.0, 0.0]; + let grey = vec![0.0, 100.0, 7.0, 7.0]; + let alpha = vec![255.0, 255.0, 0.0, 0.0]; + let r = + Raster::new("rgba", 4, 1, vec![red.clone(), grey, red, alpha], gt, Crs::LonLat, Some(0.0), ColorHint::Rgb { alpha: true }, "UInt8") + .unwrap(); + let a = alpha_band(&r); + assert_eq!(a, Some(3)); + let all = || 0..4usize; + assert_eq!(resample_mean(&r, 3, a, all(), -1.0), 127.5, "half see-through"); + assert_eq!(resample_mean(&r, 0, a, all(), -1.0), 200.0, "see-through black counts for nothing"); + assert_eq!(resample_mean(&r, 1, a, all(), -1.0), 50.0, "an opaque black is black"); + assert_eq!(resample_mean(&r, 1, a, 2..4, -1.0), 7.0, "all see-through: the plain mean"); + let grey = Raster::new("grey", 4, 1, vec![vec![0.0, 4.0, 8.0, 0.0]], gt, Crs::LonLat, Some(0.0), ColorHint::Gray, "UInt8").unwrap(); + assert_eq!(resample_mean(&grey, 0, alpha_band(&grey), all(), -1.0), 6.0, "no alpha: no-data left out"); +} diff --git a/crates/engine/src/cmd/in_blocks.rs b/crates/engine/src/cmd/in_blocks.rs index 0cb7cb9722..b254554922 100644 --- a/crates/engine/src/cmd/in_blocks.rs +++ b/crates/engine/src/cmd/in_blocks.rs @@ -176,13 +176,43 @@ fn written(full: (u32, u32)) -> bool { /// Whether command `id` with `params` writes its result to a file in the results folder: a /// command that works in blocks ([`in_blocks`]) over a layer too large to read whole, whose -/// result is too large to hold. The permission check adds that it writes files. +/// result is too large to hold, or a resample of such a layer whose result is ([`holds`]) and +/// can be written ([`streams`]). The permission check adds that it writes files. It doesn't ask +/// whether the memory or a results folder is there now. When either isn't, the run reads the file +/// as before, and the check has asked for more than the run needed. pub(crate) fn writes_file(context: &impl super::InputSource, id: &str, params: &Value) -> bool { - if !in_blocks(id, params) { + let resample = id == "raster.process" && params.get("operation").and_then(Value::as_str) == Some("resample"); + if !in_blocks(id, params) && !resample { return false; } let Some(name) = params.get("layer").and_then(Value::as_str) else { return false }; - Input::of(context, name).ok().as_ref().and_then(too_large).is_some_and(written) + let Some((full, bands)) = Input::of(context, name).ok().and_then(|i| Some((too_large(&i)?, i.held().band_count()))) else { + return false; + }; + match resample { + true => !holds(resample_samples(full, super::imagery::resample_factor(params), bands)) && streams(bands), + false => written(full), + } +} + +/// Whether a result of `bands` bands can be written a row of tiles at a time +/// ([`cogwrite::TileStream::most_bands`]). +pub(crate) fn streams(bands: usize) -> bool { + bands <= cogwrite::TileStream::>>::most_bands() +} + +/// A resample by `factor` of a raster `full` in size: the factor used (never coarser than the +/// raster itself), and the result's columns and rows, its trailing ones short of a full block +/// left out. +pub(crate) fn resample_size(full: (u32, u32), factor: u32) -> (u32, u32, u32) { + let k = factor.min(full.0.min(full.1)).max(1); + (k, (full.0 / k).max(1), (full.1 / k).max(1)) +} + +/// The samples of a resample by `factor` of a raster `full` in size, of `bands` bands. +pub(crate) fn resample_samples(full: (u32, u32), factor: u32, bands: usize) -> u64 { + let (_, w, h) = resample_size(full, factor); + u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bands as u64) } /// The plan to make `out` from `input` a block at a time, when `input` is a layer read in place @@ -199,7 +229,7 @@ pub(crate) fn plan(s: &Session, input: &Input, out: &str) -> Result Some(folder(s).ok_or("this computer gives RustGIS no folder to write the result to: save the project first")?), + true => Some(results_folder(s)?), false => None, }; Ok(Some(Blocks { @@ -271,6 +301,22 @@ impl Reading { self.full } + /// Whether a part of `cols` × `rows` of the file is read at its full size: its samples, every + /// band's, within what a part read takes ([`rustgis_data::raster::max_samples`]), a 64-bit + /// sample counted twice, as it is decoded at its size before it is held as a float. + pub(crate) fn part_fits(&self, cols: u32, rows: u32) -> bool { + let held = self.input.held(); + let wide: u64 = if matches!(held.data_type.as_str(), "Float64" | "Int64" | "UInt64") { 2 } else { 1 }; + let samples = u64::from(cols).saturating_mul(u64::from(rows)).saturating_mul(held.band_count().max(1) as u64).saturating_mul(wide); + samples <= rustgis_data::raster::max_samples() as u64 + } + + /// The columns and rows of its file's tiles (a strip's: the image's width), which a block + /// read decodes whole; `None` when they can't be read. + pub(crate) fn chunk(&self) -> Option<(u32, u32)> { + rustgis_data::raster::chunk_size(Path::new(&self.path)) + } + /// The input layer's name. pub(crate) fn layer(&self) -> &str { &self.layer @@ -417,7 +463,7 @@ impl Blocks { // The row of blocks made, and the file's levels' rows waiting to be written (less // than a row each way, two at most at the full size, half that at the next level…), // the tables of its tiles, and the overview kept. - Some(_) => cogwrite::TileStream::>>::peak(fw, fh, OVERVIEW_SAMPLES).saturating_add(row_bytes), + Some(_) => stream_peak(fw, fh, 1).saturating_add(row_bytes), None => u64::from(fw).saturating_mul(u64::from(fh)).saturating_mul(4).saturating_add(row_bytes), }; // Within what any run of rasters plans for ([`rustgis_data::raster::max_samples`]), @@ -466,96 +512,128 @@ impl Blocks { }); return super::workflows::made_then(r, None, Some(then)); }; - // A folder this run makes goes again with a result never added, while nothing else is in - // it; one already there stays, whatever is in it. - let mut made_folder = make_folder(&folder)?; - let (mut taken, mut i, mut remade) = (None, 1u32, 0); - while i < 10_000 { - let stem = stem(&out); - let dest = folder.join(if i == 1 { format!("{stem}.tif") } else { format!("{stem} {i}.tif") }); - // The file's name is reserved before it is written: two runs never take the same one. - let wrote = rustgis_data::io::stage_streamed_new(&dest, made_folder.then_some(folder.as_path()), |w| { - let (mut sink, mut stream) = (Some(w), None); - let (_, _, rounded) = blocks - .each_row(&cells, halo, |_, rows, (grid, crs)| { - count(rows); - // Placed on the file's full grid, as a read of all of it places it. - if stream.is_none() { - let t = Raster::new( - out.clone(), - 1, - 1, - vec![vec![nodata]], - grid, - crs, - Some(f64::from(nodata)), - ColorHint::Gray, - kind, - ) - .map_err(|e| e.to_string())?; - let t = named(t); - let w = sink.take().ok_or("the result's file was started twice")?; - stream = Some( - cogwrite::TileStream::new(&t, fw, fh, shape.samples(), w) - .map_err(|e| e.to_string())? - .keeping(OVERVIEW_SAMPLES), - ); - } - stream.as_mut().map_or(Ok(()), |s: &mut cogwrite::TileStream<_>| s.put(rows).map_err(|e| e.to_string())) - }) - // A Cancel stays one, as on the path that holds its result. - .map_err(rustgis_data::DataError::of_conversion)?; - let (info, overview) = - stream.ok_or_else(|| rustgis_data::DataError::Format(format!("{layer}: it has no pixels")))?.finish()?; - Ok::<_, rustgis_data::DataError>((info, overview, rounded)) - }); - match wrote { - Err(rustgis_data::DataError::Io(e)) if e.kind() == std::io::ErrorKind::AlreadyExists => i += 1, - // Another run's result, never added, took the folder it made with it meanwhile: - // made again (this run's now, if it makes it), the same name tried again. - Err(rustgis_data::DataError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound && !folder.exists() && remade < 8 => { - made_folder = make_folder(&folder)?; - remade += 1; - } - Err(e) => { - if made_folder { - let _ = std::fs::remove_dir(&folder); + let (dest, staged, (info, overview, rounded)) = write_new(&folder, &out, |w| { + let (mut sink, mut stream) = (Some(w), None); + let (_, _, rounded) = blocks + .each_row(&cells, halo, |_, rows, (grid, crs)| { + count(rows); + // Placed on the file's full grid, as a read of all of it places it. + if stream.is_none() { + let t = + Raster::new(out.clone(), 1, 1, vec![vec![nodata]], grid, crs, Some(f64::from(nodata)), ColorHint::Gray, kind) + .map_err(|e| e.to_string())?; + let t = named(t); + let w = sink.take().ok_or("the result's file was started twice")?; + stream = Some(self::stream(&t, fw, fh, shape.samples(), w)?); } - return Err(match e { - rustgis_data::DataError::Cancelled => e.to_string(), - e => format!("{}: {e}", dest.display()), - }); - } - Ok(w) => { - taken = Some((dest, w)); - break; - } - } - } - let (dest, (staged, (info, overview, rounded))) = - taken.ok_or_else(|| format!("{}: every name for {out} is taken", folder.display()))?; + stream.as_mut().map_or(Ok(()), |s: &mut cogwrite::TileStream<_>| s.put(rows).map_err(|e| e.to_string())) + }) + // A Cancel stays one, as on the path that holds its result. + .map_err(rustgis_data::DataError::of_conversion)?; + let (info, overview) = stream.ok_or_else(|| rustgis_data::DataError::Format(format!("{layer}: it has no pixels")))?.finish()?; + Ok((info, overview, rounded)) + })?; // Refused, its file goes with it. overflowed()?; - rustgis_data::progress::check().map_err(|e| e.to_string())?; - // The layer holds an overview of the file, as one added from it would. - let overview = overview.ok_or("the result's overview wasn't kept")?; - let file = dest.display().to_string(); - let rl = rustgis_map::RasterLayer::tiled_file(overview, file.clone()); let (w, h) = info.levels.first().copied().unwrap_or_default(); - let mut notes = vec![format!( - "{out}: made a block at a time from {layer} at its full {w} × {h}, and written to {file}, where the layer reads it from" - )]; - notes.extend(super::gp::tiled_read_notes(&[note(rounded)], "its")); - let then: super::workflows::Then = Box::new(move |s: &mut Session, v: &mut Value| { - for note in notes { - s.notify(note, false); + let made = format!("made a block at a time from {layer} at its full {w} × {h}"); + file_layer(out, &dest, staged, overview, &made, super::gp::tiled_read_notes(&[note(rounded)], "its")) + } +} + +/// A stream of a raster `w` × `h` in size, of `template`'s bands, place and no-data, into `out`, +/// keeping the overview the layer that reads its file holds ([`OVERVIEW_SAMPLES`]). +pub(crate) fn stream<'a, W: std::io::Write + std::io::Seek>( + template: &Raster, + w: u32, + h: u32, + samples: cogwrite::Samples, + out: &'a mut W, +) -> Result, String> { + Ok(cogwrite::TileStream::new(template, w, h, samples, out).map_err(|e| e.to_string())?.keeping(OVERVIEW_SAMPLES)) +} + +/// The most bytes a [`stream`] of a raster `w` × `h` of `bands` bands holds at once, given its +/// rows a row of tiles at a time. +pub(crate) fn stream_peak(w: u32, h: u32, bands: usize) -> u64 { + cogwrite::TileStream::>>::peak(w, h, bands, OVERVIEW_SAMPLES) +} + +/// The project's results folder for a result too large to hold ([`folder`]), or an error saying +/// to save the project first when the computer gives none. +pub(crate) fn results_folder(s: &Session) -> Result { + folder(s).ok_or_else(|| "this computer gives RustGIS no folder to write the result to: save the project first".to_string()) +} + +/// Writes a result called `out` to a new file in `folder` (made when it isn't there), under the +/// first of its names not taken (`out.tif`, `out 2.tif`, …): the name is reserved before `write` +/// writes it, so two runs never take the same one, and the file is staged beside its place, +/// put there as the layer is added ([`file_layer`]). A run cancelled, failed or never added +/// leaves no file behind, nor the folder when this made it (not the folders around it, the +/// project's own when it is saved) while nothing else is in it (one another run wrote into too can +/// stay, empty, once both their results are gone). +pub(crate) fn write_new( + folder: &Path, + out: &str, + mut write: impl FnMut(&mut std::io::BufWriter) -> Result, +) -> Result<(PathBuf, rustgis_data::io::StagedWrite, T), String> { + // A folder this run makes goes again with a result never added, while nothing else is in + // it; one already there stays, whatever is in it. + let mut made_folder = make_folder(folder)?; + let (mut i, mut remade) = (1u32, 0); + while i < 10_000 { + let stem = stem(out); + let dest = folder.join(if i == 1 { format!("{stem}.tif") } else { format!("{stem} {i}.tif") }); + match rustgis_data::io::stage_streamed_new(&dest, made_folder.then_some(folder), &mut write) { + Err(rustgis_data::DataError::Io(e)) if e.kind() == std::io::ErrorKind::AlreadyExists => i += 1, + // Another run's result, never added, took the folder it made with it meanwhile: + // made again (this run's now, if it makes it), the same name tried again. + Err(rustgis_data::DataError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound && !folder.exists() && remade < 8 => { + made_folder = make_folder(folder)?; + remade += 1; } - if let Some(o) = v.as_object_mut() { - o.insert("path".into(), Value::String(file)); + Err(e) => { + if made_folder { + let _ = std::fs::remove_dir(folder); + } + return Err(match e { + rustgis_data::DataError::Cancelled => e.to_string(), + e => format!("{}: {e}", dest.display()), + }); } - }); - Ok(super::workflows::made_layer(out, rl, None, Some(then)).committing(staged, Vec::new())) + Ok((staged, value)) => return Ok((dest, staged, value)), + } } + Err(format!("{}: every name for {out} is taken", folder.display())) +} + +/// The layer `out` reading its file `dest` in place, holding `overview` of it, the file staged +/// to be put there as it is added: says it was `made` (how) and written there, then `notes`, and +/// its answer gives the file's `path`. +pub(crate) fn file_layer( + out: String, + dest: &Path, + staged: rustgis_data::io::StagedWrite, + overview: Option, + made: &str, + notes: Vec, +) -> Result { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + // The layer holds an overview of the file, as one added from it would. + let overview = overview.ok_or("the result's overview wasn't kept")?; + let file = dest.display().to_string(); + let rl = rustgis_map::RasterLayer::tiled_file(overview, file.clone()); + let mut said = vec![format!("{out}: {made}, and written to {file}, where the layer reads it from")]; + said.extend(notes); + let then: super::workflows::Then = Box::new(move |s: &mut Session, v: &mut Value| { + for note in said { + s.notify(note, false); + } + if let Some(o) = v.as_object_mut() { + o.insert("path".into(), Value::String(file)); + } + }); + Ok(super::workflows::made_layer(out, rl, None, Some(then)).committing(staged, Vec::new())) } /// A file read a block at a time ([`Source::each_row`]): the layer's input, name and file, and diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs index 083384ca36..ad8dd5c036 100644 --- a/crates/engine/src/tests/tiled_files.rs +++ b/crates/engine/src/tests/tiled_files.rs @@ -651,9 +651,10 @@ fn raster_functions_and_resamples_run_a_block_at_a_time() { let want = raster(&whole, "out").data.clone().unwrap(); let said_whole: Vec = said(&whole, mark).into_iter().filter(|n| n.contains("matches no")).collect(); assert_eq!(said_whole.is_empty(), p["function"] != "remap", "{command}: a range of the remap is empty, and said"); - // Held, then (one band past the limit) written, a block at a time. + // Held, then (one band past the limit, or for a resample its three bands) written, a block + // at a time. let resample = *command == "raster.process"; - for (past, written) in [(1_000_000, false), (900_000, !resample)] { + for (past, written) in [(1_000_000, false), (if resample { 300_000 } else { 900_000 }, true)] { let why = format!("{command} {p}, written {written}"); let (_held, _blocks) = (HeldWhole::at(1_000_000), BlocksPast::at(past)); let mut s = Session::new(Project::default()); @@ -661,6 +662,13 @@ fn raster_functions_and_resamples_run_a_block_at_a_time() { open(&mut s); assert!(raster(&s, "checks").tiled); let (before, mark) = (reads(), s.notice_mark()); + // The Assistant asks before a run that writes a file, and only then. + let scope = crate::policy::Scope::assistant(8, std::sync::Arc::new(Live)); + match s.review(&scope, &crate::policy::Call::command(command, p.clone())) { + crate::policy::Outcome::NeedsApproval(_) => assert!(written, "{why}: the Assistant asks only before a file is written"), + crate::policy::Outcome::Allowed => assert!(!written, "{why}: the Assistant asks before a file is written"), + crate::policy::Outcome::Refused(e) => panic!("{why}: refused: {e}"), + } let got = s.run(command, p).unwrap(); assert_eq!(reads(), before, "{why}: the file isn't read whole"); let rl = raster(&s, "out"); @@ -670,12 +678,27 @@ fn raster_functions_and_resamples_run_a_block_at_a_time() { } else { rl.data.as_deref().unwrap().clone() }; + // A resample's file holds its means as floats. + let kind = if resample && written { "Float32" } else { want.data_type.as_str() }; assert_eq!( - (got_raster.width, got_raster.height, got_raster.transform, got_raster.nodata, got_raster.data_type.as_str()), - (want.width, want.height, want.transform, want.nodata, want.data_type.as_str()), + ( + got_raster.width, + got_raster.height, + got_raster.transform, + got_raster.nodata, + got_raster.data_type.as_str(), + &got_raster.color + ), + (want.width, want.height, want.transform, want.nodata, kind, &want.color), "{why}" ); assert_eq!(got_raster.bands.len(), want.bands.len(), "{why}: its bands"); + // A written resample of bytes is drawn on their 0 to 255, as the held one is, and of an + // image without alpha says nothing of a no-data value. + if resample && written { + assert!(!said(&s, mark).iter().any(|n| n.contains("isn't written to its file")), "{why}"); + assert_eq!(raster(&s, "out").style.stretch, rustgis_map::Stretch::Custom { min: 0.0, max: 255.0, bands: None }, "{why}"); + } for (g, w) in got_raster.bands.iter().zip(&want.bands) { assert!(g.data == w.data, "{why}: band {} is the whole raster's", w.name); assert_eq!(g.name, w.name, "{why}"); @@ -781,9 +804,37 @@ fn a_resampled_pixel_with_no_value_takes_the_no_data_value() { let mut s = Session::new(Project::default()); s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); assert_eq!(raster(&s, "gaps").tiled, in_blocks); + let mark = s.notice_mark(); s.run("raster.process", &p).unwrap(); let out = raster(&s, "out").data.clone().unwrap(); assert_eq!((out.width, out.nodata), (N / 2, Some(-9999.0)), "in blocks {in_blocks}"); assert_eq!(out.bands[0].data[..2], [-9999.0, 6.0], "in blocks {in_blocks}"); + assert!(!said(&s, mark).iter().any(|n| n.contains("colour table")), "in blocks {in_blocks}: no palette, nothing said"); + } +} + +/// A palette raster's resample says its colour table isn't kept (its indexes are averaged as grey +/// values), whether the file is held whole or read a block at a time. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_resampled_palette_says_its_colours_go() { + let d = dir("resample-palette"); + const N: u32 = 600; + let band: Vec = (0..N * N).map(|i| (i % 4) as f32).collect(); + let gt = GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 0.001, pixel_height: -0.001 }; + let colours = (0..256u32).map(|i| [i as u8, 0, 255 - i as u8, 255]).collect(); + let r = Raster::new("classes", N, N, vec![band], gt, Crs::LonLat, None, ColorHint::Palette(colours), "UInt8").unwrap(); + let path = d.join("classes.tif"); + rustgis_data::raster::cogwrite::write_file(&r, 0, &path).unwrap(); + let p = json!({"layer": "classes", "operation": "resample", "factor": 2, "name": "out"}); + for in_blocks in [false, true] { + let (_held, _blocks) = (HeldWhole::at(if in_blocks { 1000 } else { 1_000_000 }), BlocksPast::at(100_000)); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + assert_eq!(raster(&s, "classes").tiled, in_blocks); + let mark = s.notice_mark(); + s.run("raster.process", &p).unwrap(); + let notes: Vec = said(&s, mark).into_iter().filter(|n| n.contains("colour table isn't kept")).collect(); + assert_eq!(notes.len(), 1, "in blocks {in_blocks}: {notes:?}"); } } diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 8ebb98ccd5..b1d9d0e186 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1691,14 +1691,15 @@ at the file's full resolution when that part fits. **Indices**, **Raster Functio NDVI, remap, threshold, slope, aspect and hillshade, those over a cell's neighbours reading each block with the cells around it), the **Function Editor** with those steps, and **Classification Tools** (each class's mean summed from the rows of the file under the training polygons, as -from the whole raster) work a block of tiles at a time at the file's full resolution. A result -of up to 120 million pixels is held, as any other; a larger one is written to a tiled GeoTIFF in +from the whole raster) work a block of tiles at a time at the file's full resolution, as does +**Process**'s resample. A result of up to 120 million pixels is held, as any other (a +resample's, 120 million values of all its bands); a larger one is written to a tiled GeoTIFF in the project's results folder beside it (`Survey.rgis.data` for `Survey.rgis`), or in RustGIS's own folder for a project not saved yet, and the new layer reads it in place; a notice says where -it is. **Process**'s resample is made from the file a block at a time when its result fits. A -chain that remaps or thresholds after a step over neighbours, or has a slope in percent before -its last step, the other commands, and a larger resample read the finest level of the file they -can hold, and say which. +it is. A resample's file holds its means as 32-bit floats, every band. A chain that remaps or +thresholds after a step over neighbours, or has a slope in percent before its last step, a +resample the computer can't give the memory for, one of more than 32 bands too large to hold, +and the other commands read the finest level of the file they can hold, and say which. The web app opens a picked or dropped file of up to 256 MB whole. A larger GeoTIFF is read a part at a time instead: its header, then only the tiles of the overview it opens from. A