Repository navigation
fix(data): read the chunks a sparse GeoTIFF leaves out as no-data #3549
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
a0ee537
ce2845b
5a97f5b
9ea0ca5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -769,6 +769,31 @@ fn sample_bytes<R: Read + Seek>(dec: &mut Decoder<R>) -> 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 { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Category: agents-md
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Kept as a plain notice. It has its count, is said once a layer, and reaches |
||
| 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<R: Read + Seek>(dec: &mut Decoder<R>) -> &'static str { | ||
| let format = dec.find_tag_unsigned_vec::<u16>(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<R: Read + Seek>(dec: &mut Decoder<R>) -> usize { | ||
| dec.find_tag_unsigned::<u16>(Tag::SamplesPerPixel).ok().flatten().unwrap_or(1).max(1) as usize | ||
| } | ||
|
|
@@ -1324,6 +1349,9 @@ fn decimate<R: Read + Seek>( | |
| 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::<Result<Vec<_>>>()?; | ||
| // 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<R: Read + Seek>( | |
| 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. | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Question on the "never silent" rule. A hole in a sparse file now reads as no-data with no notice. The PR body says that for a file with no declared no-data value, uncompressed strips that read as 0 before now read as no-data, a visible change in the values. AGENTS.md asks a reader that changes what it shows for part of the data to say what, how much and where, with one notice per kind and a count. A notice such as "N chunks the file leaves out read as no-data" from Category: agents-md
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Agreed where the file gives no no-data value, as no data is then an assumption. ce2845b says how many chunks, once for a whole read. A file that gives a no-data value says nothing, and both are tested. |
||
| 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,13 +1396,15 @@ fn decimate<R: Read + Seek>( | |
| fn decimate_parallel( | ||
| chunks: Chunks, | ||
| bands: Vec<Vec<f32>>, | ||
| data_type: &'static str, | ||
| k: u32, | ||
| span: Span, | ||
| nodata: Uncounted, | ||
| threads: usize, | ||
| open: Opener<'_>, | ||
| image: usize, | ||
| limits: Limits, | ||
| table: &super::lerc::Table, | ||
| ) -> Result<(Vec<Vec<f32>>, &'static str, Vec<u64>)> { | ||
| 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<Option<DataError>> = 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; | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| 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,13 +2735,15 @@ mod tests { | |
| decimate_parallel( | ||
| chunks, | ||
| vec![vec![f32::NAN; (side * side) as usize]], | ||
| "UInt8", | ||
| k, | ||
| Span::whole(side, side), | ||
| Uncounted::new(None, None), | ||
| 2, | ||
| &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<u8>, 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<u8> = (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 | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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<R: Read + Seek>(dec: &mut Decoder<R>) -> 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<u64>, | ||
| counts: Vec<u64>, | ||
| offsets: Arc<Vec<u64>>, | ||
| counts: Arc<Vec<u64>>, | ||
| } | ||
|
|
||
| impl Table { | ||
|
|
@@ -49,14 +50,28 @@ impl Table { | |
| fn get<R: Read + Seek>(&mut self, dec: &mut Decoder<R>, 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::<u64>(offsets).ok().flatten().unwrap_or_default(); | ||
| self.counts = dec.find_tag_unsigned_vec::<u64>(counts).ok().flatten().unwrap_or_default(); | ||
| self.offsets = Arc::new(dec.find_tag_unsigned_vec::<u64>(offsets).ok().flatten().unwrap_or_default()); | ||
| self.counts = Arc::new(dec.find_tag_unsigned_vec::<u64>(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<R: Read + Seek>(&mut self, dec: &mut Decoder<R>, index: u32) -> bool { | ||
| let tiled = dec.find_tag(Tag::TileWidth).ok().flatten().is_some(); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Memory, not in the budget: Category: performance
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in ce2845b: the table is read once before the threads start and shared by them. Its size is in the PR description. |
||
| 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<R: Read + Seek>(&mut self, dec: &mut Decoder<R>) -> (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 | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
absent_saidonly looks at the TIFF's own no-data tag (self.nodata), but a COG's.aux.xmlsidecar can declare one. The COG read paths apply that sidecar afterwards:apply_pam(mod.rs:1070-1071) fillsr.nodatafrompam.nodata_within(bands)when the raster has none. So for a COG with a sidecar no-data value, the left-out tiles already read as no data, yetabsent_saidstill adds "they are read as no data … it gives no no-data value". That notice is false. The GeoTIFF path gets this right:read_imagecheckssidecar_nodata(geotiff.rs:2093). The COG twin does not, and it is reached byread_overview(tiles/cog/raster.rs:159) andread_window_raster(layer.rs:6960).Suggested fix: apply the same test
apply_pamuses, inLayout::absent_said:The test
the_chunks_left_out_are_said_by_levelshould get a case with a sidecar no-data value that expectsNone, as the GeoTIFF testa_sparse_files_missing_chunks_are_no_dataalready does withread_with_nodata(…, Some(255.0)).Confidence: high on the mismatch (read from source); the user-visible effect is a wrong notice, not wrong pixels.
Category: bug
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Checked:
describedisn't a sidecar here. It is the TIFF's own GDAL_METADATA tag (parse_gdal_metadata), which sets descriptions and wavelengths and never a no-data value; only the.aux.xmlparser sets one. A local file with an.aux.xmlbeside it isn't read in place (tiled_in_place,cmd/raster.rs), and no sidecar is read for an address, so the in-place and window readers have no declared value to contradict: they apply none to the pixels either. Reading sidecars in place is a later step of #2761, and this check goes with it. No change here.