diff --git a/crates/data/src/raster/cog.rs b/crates/data/src/raster/cog.rs index bed6e247ce..68e01f9fef 100644 --- a/crates/data/src/raster/cog.rs +++ b/crates/data/src/raster/cog.rs @@ -268,6 +268,14 @@ impl Layout { } } + /// What to say of the tiles or strips level `level` leaves out, when the file gives no no-data + /// value; kept apart from `lost`, as they are read alike in place and whole. + pub fn absent_said(&self, level: usize) -> Option { + let l = self.levels.get(level).filter(|_| self.nodata.is_none())?; + let absent = l.offsets.iter().zip(&l.counts).filter(|chunk| *chunk == (&0, &0)).count(); + (absent > 0).then(|| super::geotiff::absent_note(absent, l.offsets.len())) + } + /// How many bands one chunk (a tile's bytes) holds: one when they are stored apart. pub fn chunk_bands(&self) -> usize { if self.planar { 1 } else { self.bands.max(1) } @@ -1142,6 +1150,21 @@ pub fn example_with(e: &Example) -> Vec { #[cfg(test)] pub(crate) mod tests { use super::*; + + /// What a sparse file leaves out is said level by level, and only without a no-data value. + #[test] + fn the_chunks_left_out_are_said_by_level() { + let file = example_with(&Example { size: 256, tile: 64, sparse: true, ..Example::default() }); + let Ok(Parse::Done(mut l)) = layout(&Sparse::default().with(0, file)) else { panic!("not a COG") }; + assert!(l.absent_said(0).is_some_and(|s| s.starts_with("1 of its 16 tiles")), "{:?}", l.absent_said(0)); + assert_eq!((l.absent_said(1), l.absent_said(9)), (None, None)); + // An overview with a hole under a whole full image. + l.levels.swap(0, 1); + assert_eq!((l.absent_said(0), l.absent_said(1).is_some()), (None, true)); + l.nodata = Some(0.0); + assert_eq!(l.absent_said(1), None); + } + /// ESA CCI Biomass's 1 km map (#2496): 18 bands interleaved in 512-pixel tiles, 4.7 million values /// a tile, open; a tile past the limit says what it takes, the limit and what to do. #[test] diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 9b9e5c1333..18f333448b 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -769,6 +769,31 @@ fn sample_bytes(dec: &mut Decoder) -> usize { (bits(dec) as usize).div_ceil(8).max(1) } +/// What a file says that gives no no-data value and leaves `absent` of an image's `chunks` out: +/// taking them as no data is an assumption (they read as 0 elsewhere). +pub(super) fn absent_note(absent: usize, chunks: usize) -> String { + format!("{absent} of its {chunks} tiles or strips aren't in the file, and it gives no no-data value: they are read as no data") +} + +/// The type the current image's header gives its samples, as [`to_f32`] names them: an image with +/// no chunk decoded (a sparse file's) has it too. +fn declared_type(dec: &mut Decoder) -> &'static str { + let format = dec.find_tag_unsigned_vec::(Tag::SampleFormat).ok().flatten().and_then(|v| v.first().copied()).unwrap_or(1); + match (format, bits(dec)) { + (3, 64) => "Float64", + (3, 16) => "Float16", + (3, _) => "Float32", + (2, ..=8) => "Int8", + (2, ..=16) => "Int16", + (2, ..=32) => "Int32", + (2, _) => "Int64", + (_, ..=8) => "UInt8", + (_, ..=16) => "UInt16", + (_, ..=32) => "UInt32", + _ => "UInt64", + } +} + fn samples(dec: &mut Decoder) -> usize { dec.find_tag_unsigned::(Tag::SamplesPerPixel).ok().flatten().unwrap_or(1).max(1) as usize } @@ -1324,6 +1349,9 @@ fn decimate( return Err(err(format!("a strip or tile of {cols} × {rows} pixels is too large to read ({} MB)", bytes >> 20))); } let mut bands = (0..nbands).map(|_| super::filled(ow, oh, f32::NAN)).collect::>>()?; + // The chunks' places, read once and shared by the threads. + let mut table = super::lerc::Table::default(); + table.chunks(dec); #[cfg(not(target_arch = "wasm32"))] if let Some((open, image, limits)) = open && examined >= PARALLEL_CHUNKS @@ -1335,17 +1363,21 @@ fn decimate( let chunk_count = usize::try_from(examined).unwrap_or(usize::MAX); let threads = crate::threads::max().min(affordable.max(crate::threads::default_max())).min(chunk_count); if threads > 1 { - return decimate_parallel(chunks, bands, k, span, nodata, threads, open, image, limits); + return decimate_parallel(chunks, bands, declared_type(dec), k, span, nodata, threads, open, image, limits, &table); } } let _ = open; crate::progress::begin(usize::try_from(examined).unwrap_or(usize::MAX)); - let mut data_type = "Float32"; + let mut data_type = declared_type(dec); let mut rounded = vec![0u64; nbands]; - let mut table = super::lerc::Table::default(); for p in 0..examined { crate::progress::check()?; if let Some((plane, index)) = chunks.nth(p, span, k).and_then(|i| chunks.wanted(i, k, span)) { + // One the file leaves out stays no-data. + if table.absent(dec, index) { + crate::progress::step(1)?; + continue; + } let (buf, gaps) = read_chunk(dec, index, &mut table)?; let changed = rounded_bits(&buf, nodata); let (mut values, dt) = to_f32(buf, (ow, oh))?; @@ -1364,6 +1396,7 @@ fn decimate( fn decimate_parallel( chunks: Chunks, bands: Vec>, + data_type: &'static str, k: u32, span: Span, nodata: Uncounted, @@ -1371,6 +1404,7 @@ fn decimate_parallel( open: Opener<'_>, image: usize, limits: Limits, + table: &super::lerc::Table, ) -> Result<(Vec>, &'static str, Vec)> { use std::sync::Mutex; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -1383,7 +1417,7 @@ fn decimate_parallel( let failed = AtomicBool::new(false); let failure: Mutex> = Mutex::new(None); let rounded = vec![0u64; bands.len()]; - let out = Mutex::new((bands, "Float32", rounded)); + let out = Mutex::new((bands, data_type, rounded)); let fail = |e: DataError| { failed.store(true, Ordering::Relaxed); if let Ok(mut f) = failure.lock() { @@ -1400,7 +1434,7 @@ fn decimate_parallel( Ok(d) => d, Err(e) => return fail(e), }; - let mut table = super::lerc::Table::default(); + let mut table = table.clone(); while !failed.load(Ordering::Relaxed) { if let Err(e) = crate::progress::check() { return fail(e); @@ -1415,6 +1449,13 @@ fn decimate_parallel( } continue; }; + // One the file leaves out stays no-data. + if table.absent(&mut dec, index) { + if let Err(e) = crate::progress::step(1) { + return fail(e); + } + continue; + } match read_chunk(&mut dec, index, &mut table) { Ok((buf, gaps)) => { let changed = rounded_bits(&buf, nodata); @@ -1955,7 +1996,15 @@ fn read_image( // The decoder has no LERC codec: such an image is read a chunk at a time, every chunk decoded // by [`super::lerc`] (#1818). let lerc = super::lerc::is_lerc(&mut dec); - let whole = if decimate_by > 1 || extra_samples || planar_tiles || chunked || lerc || span.is_some() { + // A sparse file's chunks aren't there to decode: the decoder fails on them, or reads another + // part of the file. Read a chunk at a time, they are no-data (#2761), as they are in place. + let by_chunk = decimate_by > 1 || extra_samples || planar_tiles || chunked || lerc || span.is_some(); + let (chunk_count, absent) = super::lerc::Table::default().chunks(&mut dec); + let sparse = !by_chunk && absent > 0; + if absent > 0 && bits(&mut dec) < 8 { + return Err(err("a sparse file of fewer than 8 bits a sample isn't supported")); + } + let whole = if by_chunk || sparse { None } else { let mut buf = DecodingResult::U8(Vec::new()); @@ -2039,6 +2088,9 @@ fn read_image( super::mask::Found::Unscanned(why) => mask_lost = Some(why), super::mask::Found::None => {} } + // Said for a whole image, not for each part read of it: the layer it is a part of said so. + let absent_said = + (absent > 0 && span.is_none() && geo.nodata.is_none() && sidecar_nodata.is_none()).then(|| absent_note(absent, chunk_count)); let mask_lost = mask_lost.map(|why| format!("its transparency mask isn't applied ({why}): masked pixels draw as stored")); // A scan keeps a stand-in transform, sized to the pixels read. if !geo.referenced { @@ -2051,6 +2103,7 @@ fn read_image( r.lost.extend(copyright_lost); r.lost.extend(table_lost); r.lost.extend(mask_lost); + r.lost.extend(absent_said); if let Some(p) = &described { r.apply_pam(p, super::pam::GDAL_METADATA); } @@ -2150,6 +2203,7 @@ fn read_image( r.lost.extend(turned); r.lost.extend(table_lost); r.lost.extend(mask_lost); + r.lost.extend(absent_said); if let Some(p) = &described { r.apply_pam(p, super::pam::GDAL_METADATA); } @@ -2681,6 +2735,7 @@ mod tests { decimate_parallel( chunks, vec![vec![f32::NAN; (side * side) as usize]], + "UInt8", k, Span::whole(side, side), Uncounted::new(None, None), @@ -2688,6 +2743,7 @@ mod tests { &open, 0, Limits::default(), + &super::super::lerc::Table::default(), ) } else { decimate(&mut dec, 16, 16, 1, false, k, None, Uncounted::new(None, None), None) @@ -5394,6 +5450,70 @@ mod tests { out } + /// The chunks a sparse file leaves out are no-data read whole, with one thread or several, + /// whole or every k-th pixel, compressed or not, and the image keeps its type (#2761). + #[test] + fn a_sparse_files_missing_chunks_are_no_data() { + // The byte counts of chunks `gone` set to 0, and their offsets. + let sparse = |mut b: Vec, gone: &[usize]| { + let at32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize; + let ifd = at32(&b, 4); + for i in 0..u16::from_le_bytes([b[ifd], b[ifd + 1]]) as usize { + let e = ifd + 2 + 12 * i; + if [273, 279, 324, 325].contains(&u16::from_le_bytes([b[e], b[e + 1]])) { + let size = if b[e + 2] == 3 { 2 } else { 4 }; + let table = if at32(&b, e + 4) * size <= 4 { e + 8 } else { at32(&b, e + 8) }; + gone.iter().for_each(|c| b[table + c * size..table + (c + 1) * size].fill(0)); + } + } + b + }; + // Strips of 4 rows, uncompressed: the second and the last one gone. + let data: Vec = (0..40 * 16).map(|i| (i % 251 + 1) as u8).collect(); + let bytes = sparse(grey8(40, 16, &data, None), &[1, 3]); + let r = read(std::io::Cursor::new(&bytes), "holes").unwrap(); + assert_eq!(r.data_type, "UInt8"); + let said = "2 of its 4 tiles or strips aren't in the file, and it gives no no-data value: they are read as no data"; + assert!(r.lost.iter().any(|n| *n == said), "{:?}", r.lost); + let whole = read(std::io::Cursor::new(&grey8(40, 16, &data, None)), "whole").unwrap(); + assert!(whole.lost.is_empty(), "{:?}", whole.lost); + let declared = read_with_nodata(std::io::Cursor::new(&bytes), "declared", Some(255.0)).unwrap(); + assert!(!declared.lost.iter().any(|n| *n == said), "{:?}", declared.lost); + for y in 0..16i64 { + for x in 0..40i64 { + let want = (y / 4 % 2 == 0).then(|| f32::from(data[(y * 40 + x) as usize])); + assert_eq!(r.value(0, x, y), want, "{x}, {y}"); + } + } + // Every strip gone: all no-data, still bytes. + let r = read(std::io::Cursor::new(&sparse(grey8(40, 16, &data, None), &[0, 1, 2, 3])), "none").unwrap(); + assert_eq!((r.data_type.as_str(), r.value(0, 0, 0)), ("UInt8", None)); + // No byte counts, but offsets: chunks some writers store uncompressed, read as they were. + let mut bytes = grey8(40, 16, &data, None); + let at32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize; + let ifd = at32(&bytes, 4); + for e in (0..u16::from_le_bytes([bytes[ifd], bytes[ifd + 1]]) as usize).map(|i| ifd + 2 + 12 * i) { + if bytes[e..e + 2] == 279u16.to_le_bytes() { + let (table, size) = (at32(&bytes, e + 8), if bytes[e + 2] == 3 { 2 } else { 4 }); + bytes[table..table + 4 * size].fill(0); + } + } + let r = read(std::io::Cursor::new(&bytes), "uncounted").unwrap(); + assert_eq!(r.value(0, 3, 5), Some(f32::from(data[5 * 40 + 3]))); + // LZW tiles, on several threads, then every other pixel. + let pixel = |x: u32, y: u32| (x * 3 + y) as f32; + let bytes = sparse(lzw_tiled(1100, 1000, 128, 1, pixel), &[0, 13]); + for (max, k) in [(usize::MAX, 1i64), (300_000, 2)] { + let r = read_threaded(&bytes, max).unwrap(); + assert_eq!(i64::from(r.width), (1100 + k - 1) / k); + for (x, y) in [(4, 4), (126, 126), (128, 0), (0, 128), (520, 130), (1098, 998)] { + let tile = y / 128 * 9 + x / 128; + let want = (tile != 0 && tile != 13).then(|| pixel(x as u32, y as u32)); + assert_eq!(r.value(0, x / k, y / k), want, "every {k}: {x}, {y}"); + } + } + } + #[test] fn ycbcr_jpeg_is_shown_as_rgb() { // Issue #692: the tiff crate leaves JPEG-compressed YCbCr as it is, which drew a COG with diff --git a/crates/data/src/raster/lerc.rs b/crates/data/src/raster/lerc.rs index 159527c824..31aed4f615 100644 --- a/crates/data/src/raster/lerc.rs +++ b/crates/data/src/raster/lerc.rs @@ -14,6 +14,7 @@ //! no-data. A blob must hold samples of the image's own type: another type is an error, not a cast. use std::io::{Read, Seek, SeekFrom}; +use std::sync::Arc; use tiff::decoder::{Decoder, DecodingResult}; use tiff::tags::Tag; @@ -37,10 +38,10 @@ pub(crate) fn is_lerc(dec: &mut Decoder) -> bool { /// Where an image's chunks are in the file: its offsets and byte counts, read once for every chunk /// of the image a reader decodes (the `tiff` crate keeps its own copy private). -#[derive(Default)] +#[derive(Clone, Default)] pub(crate) struct Table { - offsets: Vec, - counts: Vec, + offsets: Arc>, + counts: Arc>, } impl Table { @@ -49,14 +50,28 @@ impl Table { fn get(&mut self, dec: &mut Decoder, tiled: bool, index: u32) -> Result<(u64, u64)> { if self.offsets.is_empty() { let (offsets, counts) = if tiled { (Tag::TileOffsets, Tag::TileByteCounts) } else { (Tag::StripOffsets, Tag::StripByteCounts) }; - self.offsets = dec.find_tag_unsigned_vec::(offsets).ok().flatten().unwrap_or_default(); - self.counts = dec.find_tag_unsigned_vec::(counts).ok().flatten().unwrap_or_default(); + self.offsets = Arc::new(dec.find_tag_unsigned_vec::(offsets).ok().flatten().unwrap_or_default()); + self.counts = Arc::new(dec.find_tag_unsigned_vec::(counts).ok().flatten().unwrap_or_default()); } match (self.offsets.get(index as usize), self.counts.get(index as usize)) { (Some(o), Some(c)) => Ok((*o, *c)), _ => Err(err("no such chunk")), } } + + /// Whether the file leaves chunk `index` of the decoder's current image out (a sparse file's: + /// it has neither an offset nor bytes): all no-data, whatever the compression. A count of 0 + /// alone doesn't say so: some writers leave the counts of uncompressed chunks out. + pub(crate) fn absent(&mut self, dec: &mut Decoder, index: u32) -> bool { + let tiled = dec.find_tag(Tag::TileWidth).ok().flatten().is_some(); + matches!(self.get(dec, tiled, index), Ok((0, 0))) + } + + /// How many chunks the decoder's current image has, and how many of them the file leaves out. + pub(crate) fn chunks(&mut self, dec: &mut Decoder) -> (usize, usize) { + self.absent(dec, 0); + (self.offsets.len(), self.offsets.iter().zip(self.counts.iter()).filter(|chunk| *chunk == (&0, &0)).count()) + } } /// A decoded chunk: its samples, cropped to the image as `Decoder::read_chunk` returns them, and diff --git a/crates/data/src/raster/mask.rs b/crates/data/src/raster/mask.rs index 5b15aee4ee..2d1f8d15b0 100644 --- a/crates/data/src/raster/mask.rs +++ b/crates/data/src/raster/mask.rs @@ -121,11 +121,15 @@ pub(super) fn read(dec: &mut Decoder, index: usize, step: u32 if tile.first(step, span).is_none() { continue; } + let (Some(&offset), Some(&count)) = (offsets.get(c), counts.get(c)) else { continue }; + // One a sparse file leaves out is all 0: masked, as `out` starts (#2761). + if (offset, count) == (0, 0) { + continue; + } // A tile holds every row, padded; a strip only the image's. let rows = if tiled { ch as u64 } else { tile.dh } as usize; let need = row_bytes.checked_mul(rows).filter(|n| *n <= MAX_CHUNK_BYTES).ok_or_else(|| err("a transparency mask's chunk is too large"))?; - let (Some(&offset), Some(&count)) = (offsets.get(c), counts.get(c)) else { continue }; let count = usize::try_from(count).ok().filter(|n| *n <= MAX_CHUNK_BYTES).ok_or_else(|| err("a transparency mask's chunk is too large"))?; // Read as far as the file goes, not allocated from the claim. @@ -229,7 +233,8 @@ mod tests { let mut out = vec![b'I', b'I', 42, 0, 0, 0, 0, 0]; let (mut offsets, mut counts) = (Vec::new(), Vec::new()); for s in strips { - offsets.push(out.len() as u32); + // An empty strip is one a sparse file leaves out. + offsets.push(if s.is_empty() { 0 } else { out.len() as u32 }); counts.push(s.len() as u32); out.extend(s); } @@ -274,6 +279,20 @@ mod tests { .collect() } + /// The strips a sparse file leaves out are masked; the others are read (#2761). + #[test] + fn a_sparse_masks_missing_strips_are_masked() { + let mut strips = rows(); + strips[2].clear(); + strips[6].clear(); + let mut dec = Decoder::new(std::io::Cursor::new(striped(10, 7, 1, 1, &strips))).expect("decoder"); + let all = read(&mut dec, 0, 1, None).expect("mask"); + for (i, on) in all.iter().enumerate() { + let (x, y) = (i % 10, i / 10); + assert_eq!(*on, (x + y) % 2 == 0 && y != 2 && y != 6, "{x}, {y}"); + } + } + fn check(bytes: Vec) { let mut dec = Decoder::new(std::io::Cursor::new(bytes)).expect("decoder"); assert!(matches!(find(&mut dec, 0, (10, 7)), Found::At(0))); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 2e0256d0e8..07b48408fa 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -6957,6 +6957,7 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic:: } // What the header holds but isn't read (a colour table, names): said when the layer is added. r.lost.extend(layout.lost.iter().cloned()); + r.lost.extend(layout.absent_said(level)); r.lost.extend(palette_lost); if let Some(described) = &layout.described { r.apply_pam(described, rustgis_data::raster::pam::GDAL_METADATA); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1dacd58ac3..afbcf9ce01 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -36038,6 +36038,9 @@ fn a_tile_a_sparse_file_leaves_out_is_empty_not_waited_for() { // Its overview is level 1 (1024 pixels a side); level 0's first tile has no bytes. let r = s.run("layer.addUrl", &json!({"url": url.clone(), "name": "Scene"})).unwrap(); assert_eq!(r["width"], 1024, "{r}"); + // The file gives no no-data value, so reading the tile as no data is said (#2761). + let said = "1 of its 64 tiles or strips aren't in the file, and it gives no no-data value: they are read as no data"; + assert!(s.notices_since(0).iter().any(|n| n.text.contains(said)), "{:?}", s.notices_since(0)); let before = sent.load(Ordering::Relaxed); let gray = rustgis_data::raster::ColorHint::Gray; for _ in 0..2 { diff --git a/crates/tiles/src/cog/raster.rs b/crates/tiles/src/cog/raster.rs index 73d34dbd1e..c67d4337b5 100644 --- a/crates/tiles/src/cog/raster.rs +++ b/crates/tiles/src/cog/raster.rs @@ -155,6 +155,8 @@ fn read_overview(info: Arc, url: String, done: Box