Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 107 additions & 18 deletions crates/data/src/raster/cog.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! Cloud-optimised GeoTIFFs read in place: the layout of a tiled GeoTIFF (its images, their tile
//! grids and where each tile is) from the bytes read so far, and one tile at a time decoded from
//! its own bytes. Nothing here fetches: [`Sparse`] holds the byte ranges the caller has read, and a
//! read past them says which range is needed next (the tile cache fetches it, by HTTP range).
//! its own bytes. A GeoTIFF in strips is laid out the same way, each strip a tile as wide as the
//! image ([`Layout::strips`]). Nothing here fetches: [`Sparse`] holds the byte ranges the caller
//! has read, and a read past them says which range is needed next (the tile cache fetches it, by
//! HTTP range).
//!
//! Files are hostile input: image counts, tile counts and sizes are bounded, and a tile is decoded
//! with the same limits as a whole GeoTIFF.
Expand Down Expand Up @@ -147,9 +149,11 @@ impl Read for Sparse {
if buf.is_empty() || self.len.is_some_and(|len| self.pos >= len) {
return Ok(0);
}
let hit = self.chunks.range(..=self.pos).next_back().and_then(|(at, c)| {
// The part holding `pos`: the last one starting at or before it, or an earlier one reaching
// past it (a small file's header read whole holds an IFD written after the chunk read).
let hit = self.chunks.range(..=self.pos).rev().find_map(|(at, c)| {
let off = usize::try_from(self.pos - at).ok()?;
(off < c.len()).then(|| c.get(off..)).flatten()
c.get(off..).filter(|s| !s.is_empty())
});
match hit {
Some(src) => {
Expand Down Expand Up @@ -245,6 +249,10 @@ pub struct Layout {
pub lost: crate::loss::Notes,
/// Who holds the rights to the picture (its Copyright tag), as [`super::Raster::copyright`].
pub copyright: Option<String>,
/// The file is in strips, not tiles (#2592): each level's tiles are its strips, as wide as the
/// image and `RowsPerStrip` rows tall. A window is read from them in place; the map draws such
/// a file from it read whole, as before.
pub strips: bool,
}

impl Layout {
Expand Down Expand Up @@ -286,7 +294,7 @@ pub enum Parse {
Done(Box<Layout>),
/// These bytes (first, end) must be read first.
Need(u64, u64),
/// Not a tiled GeoTIFF RustGIS can read a tile at a time (strips, separate band planes…): read
/// Not a GeoTIFF RustGIS can read a tile at a time (a rotated image, strips too large…): read
/// it whole instead.
NotTiled(String),
}
Expand Down Expand Up @@ -324,7 +332,7 @@ fn take_tiles(allowance: &mut usize, n: usize) -> Result<()> {
Ok(())
}

/// The layout of a tiled GeoTIFF, from the bytes read so far.
/// The layout of a tiled GeoTIFF, or of one in strips, from the bytes read so far.
pub fn layout(bytes: &Sparse) -> Result<Parse> {
let r = bytes.reader();
let watch = r.clone();
Expand Down Expand Up @@ -478,6 +486,8 @@ fn read_layout(r: Sparse) -> Result<Parse> {
let mut skipped = 0usize;
// Transparency masks passed over.
let mut masks = 0usize;
// The full image is in strips: so are the levels read after it.
let mut strips = false;
loop {
let subfile = dec.find_tag_unsigned::<u32>(Tag::NewSubfileType).ok().flatten().unwrap_or(0);
// Transparency masks are skipped (a tile is read without its mask's), said, and count
Expand All @@ -490,14 +500,19 @@ fn read_layout(r: Sparse) -> Result<Parse> {
break;
}
} else {
let Some(tw) = dec.find_tag_unsigned::<u32>(Tag::TileWidth).ok().flatten() else {
if index == 0 {
return Ok(Parse::NotTiled("a GeoTIFF in strips is read whole".into()));
}
break;
};
let th = dec.find_tag_unsigned::<u32>(Tag::TileLength).ok().flatten().unwrap_or(tw);
let (w, h) = dec.dimensions().map_err(err)?;
let tiled = dec.find_tag_unsigned::<u32>(Tag::TileWidth).ok().flatten();
// A strip is a tile as wide as the image and `RowsPerStrip` rows tall (the whole image
// without the tag). A file in strips has its overviews in strips; a tiled file's image in
// strips ends the scan, as before.
if levels.is_empty() {
strips = tiled.is_none();
}
let (tw, th) = match tiled {
Some(tw) if !strips => (tw, dec.find_tag_unsigned::<u32>(Tag::TileLength).ok().flatten().unwrap_or(tw)),
None if strips => (w, dec.find_tag_unsigned::<u32>(Tag::RowsPerStrip).ok().flatten().unwrap_or(h).min(h)),
_ => break,
};
// An overview is smaller than the full image in both width and height, whatever the file's
// order: TIFF doesn't require the cloud-optimised largest-first order, and some
// writers store the smallest first (#1908). A level decodes as the full image does,
Expand Down Expand Up @@ -562,6 +577,11 @@ fn read_layout(r: Sparse) -> Result<Parse> {
let bytes = tile_bytes(tw, th, per_chunk, level_bits);
if bytes > MAX_TILE_BYTES as u64 {
let (mib, max) = (bytes.div_ceil(1 << 20), MAX_TILE_BYTES >> 20);
if strips {
return Ok(Parse::NotTiled(format!(
"strips of {th} rows take {mib} MiB each once read, more than the {max} MiB one may take: too large to read in place, so it is read whole"
)));
}
// Bands stored apart help only when one band's tile then fits.
let apart = per_chunk > 1 && tile_bytes(tw, th, 1, level_bits) <= MAX_TILE_BYTES as u64;
let of_bands = if per_chunk > 1 { format!(" of {per_chunk} interleaved bands") } else { String::new() };
Expand All @@ -577,8 +597,9 @@ fn read_layout(r: Sparse) -> Result<Parse> {
// Every band plane's tiles, when the bands are stored apart.
let n = (w.div_ceil(tw) as usize).saturating_mul(h.div_ceil(th) as usize).saturating_mul(planes);
take_tiles(&mut allowance, n)?;
let mut offsets = dec.find_tag_unsigned_vec::<u64>(Tag::TileOffsets).map_err(err)?.unwrap_or_default();
let mut counts = dec.find_tag_unsigned_vec::<u64>(Tag::TileByteCounts).map_err(err)?.unwrap_or_default();
let (at, len) = if strips { (Tag::StripOffsets, Tag::StripByteCounts) } else { (Tag::TileOffsets, Tag::TileByteCounts) };
let mut offsets = dec.find_tag_unsigned_vec::<u64>(at).map_err(err)?.unwrap_or_default();
let mut counts = dec.find_tag_unsigned_vec::<u64>(len).map_err(err)?.unwrap_or_default();
if offsets.len() < n || counts.len() < n {
return Err(err("the tile index is shorter than the image"));
}
Expand Down Expand Up @@ -645,6 +666,7 @@ fn read_layout(r: Sparse) -> Result<Parse> {
described,
lost,
copyright,
strips,
})))
}

Expand Down Expand Up @@ -766,6 +788,25 @@ pub fn example(size: u32, tile: u32) -> Vec<u8> {
example_with(&Example { size, tile, ..Example::default() })
}

/// A small GeoTIFF in strips, as the Brazil Data Cube writes its scenes (#2592): `width × height`
/// signed 16-bit cells, Deflate, `rows` rows a strip, no overviews, in longitude/latitude from
/// 10° E, 46° N in cells of 0.01°; cell (x, y) is `7 x − 3 y`.
#[doc(hidden)]
pub fn example_strips(width: u32, height: u32, rows: u32) -> Vec<u8> {
use tiff::encoder::{Compression, DeflateLevel, TiffEncoder, colortype};
let values: Vec<i16> = (0..height).flat_map(|y| (0..width).map(move |x| (7 * x as i32 - 3 * y as i32) as i16)).collect();
let mut out = std::io::Cursor::new(Vec::new());
let made = TiffEncoder::new(&mut out).map(|e| e.with_compression(Compression::Deflate(DeflateLevel::Balanced))).and_then(|mut enc| {
let mut img = enc.new_image::<colortype::GrayI16>(width, height)?;
img.encoder().write_tag(Tag::ModelPixelScaleTag, &[0.01f64, 0.01, 0.0][..])?;
img.encoder().write_tag(Tag::ModelTiepointTag, &[0.0f64, 0.0, 0.0, 10.0, 46.0, 0.0][..])?;
img.encoder().write_tag(Tag::GeoKeyDirectoryTag, &[1u16, 1, 0, 2, 1024, 0, 1, 2, 2048, 0, 1, 4326][..])?;
img.rows_per_strip(rows)?;
img.write_data(&values)
});
made.map(|()| out.into_inner()).unwrap_or_default()
}

/// What [`example_with`] writes.
#[doc(hidden)]
#[derive(Clone, Copy, Debug)]
Expand Down Expand Up @@ -1383,11 +1424,59 @@ pub(crate) mod tests {
assert!(said.iter().any(|x| x.contains("band and class names and wavelengths are left out")), "{said:?}");
}

/// A GeoTIFF in strips (#2592) is laid out as tiles as wide as the image and a strip's rows
/// tall: each decodes to its rows, the last strip's rows past the image NaN.
#[test]
fn strips_are_tiles_as_wide_as_the_image() {
let file = example_strips(37, 11, 4);
let Parse::Done(l) = layout(&Sparse::default().with(0, file.clone())).unwrap() else { panic!("not read in place") };
let full = &l.levels[0];
assert!(l.strips && !l.planar);
assert_eq!((l.levels.len(), full.width, full.height, full.tile_width, full.tile_height, full.tiles()), (1, 37, 11, 37, 4, 3));
assert_eq!((l.data_type, l.bands, l.transform.origin_x, l.transform.pixel_width), ("Int16", 1, 10.0, 0.01));
// The header read whole, as a small file's first read is: its IFD comes after the strips.
let header = Sparse::default().with(0, file.clone());
assert!(u32::from_le_bytes(file[4..8].try_into().unwrap()) as u64 > full.offsets[2]);
for strip in 0..3u32 {
let (at, n) = (full.offsets[strip as usize] as usize, full.counts[strip as usize] as usize);
let bands = decode_tile(&header, &l, 0, strip, file[at..at + n].to_vec()).unwrap();
for (i, v) in bands[0].iter().enumerate() {
let (x, y) = (i as u32 % 37, strip * 4 + i as u32 / 37);
if y < 11 {
assert_eq!(*v, (7 * x as i32 - 3 * y as i32) as f32, "cell ({x}, {y})");
} else {
assert!(v.is_nan(), "row {y} is past the image");
}
}
}
// A file RustGIS writes, in strips too, and one strip for the whole image.
let own = crate::raster::geotiff::tests_support::strip_tiff();
assert!(matches!(layout(&Sparse::default().with(0, own)).unwrap(), Parse::Done(l) if l.strips));
let one = example_strips(5, 3, 100);
assert!(matches!(layout(&Sparse::default().with(0, one)).unwrap(), Parse::Done(l) if l.levels[0].tile_height == 3));
}

/// Strips too large to decode one at a time are read whole, as before, and said so.
#[test]
fn strips_too_large_to_read_in_place_are_read_whole() {
let mut file = example_strips(16, 8, 8);
// The image made 1,048,576 rows tall, in one strip of them all: 64 MiB once read.
let ifd = u32::from_le_bytes(file[4..8].try_into().unwrap()) as usize;
let n = u16::from_le_bytes(file[ifd..ifd + 2].try_into().unwrap()) as usize;
for e in (0..n).map(|i| ifd + 2 + i * 12) {
let tag = u16::from_le_bytes(file[e..e + 2].try_into().unwrap());
if tag == 257 || tag == 278 {
assert_eq!(u16::from_le_bytes(file[e + 2..e + 4].try_into().unwrap()), 4, "tag {tag} is a LONG");
file[e + 8..e + 12].copy_from_slice(&(1u32 << 20).to_le_bytes());
}
}
let Parse::NotTiled(why) = layout(&Sparse::default().with(0, file)).unwrap() else { panic!("read in place") };
assert!(why.starts_with("strips of 1048576 rows take 64 MiB each") && why.contains("too large to read in place"), "{why}");
}

#[test]
fn strips_and_junk_are_refused() {
fn rotated_images_and_junk_are_refused() {
assert!(is_tiff(b"II*\0") && is_tiff(b"MM\0+") && !is_tiff(b"PK\x03\x04"));
let strips = crate::raster::geotiff::tests_support::strip_tiff();
assert!(matches!(layout(&Sparse::default().with(0, strips)).unwrap(), Parse::NotTiled(_)));
// A rotated image is read whole, and turned north-up then (issue #251).
let m = [30.0, 5.0, 0.0, 400_000.0, 3.0, -30.0, 0.0, 5_000_000.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0];
let rotated = crate::raster::geotiff::tests_support::matrix_tiff(m, false);
Expand Down
3 changes: 2 additions & 1 deletion crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6606,7 +6606,8 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic::
let cell = asked.cell;
// The five minutes count from the header's read.
let started = std::time::Instant::now();
let info = cog::info_until(url, stop).map_err(named)?;
// A file in strips too (#2592): a strip is a tile as wide as the image.
let info = cog::window_info_until(url, stop).map_err(named)?;
let layout = &info.layout;
let (pw, ph) = (layout.transform.pixel_width, layout.transform.pixel_height);
if !(pw.is_finite() && ph.is_finite() && pw != 0.0 && ph != 0.0) {
Expand Down
24 changes: 24 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53588,6 +53588,30 @@ fn a_bottom_up_cog_window_comes_in_north_up() {
assert_eq!(c.transform.origin_y, 45.0 + f64::from(c.height) / 1024.0);
}

/// `layer.addUrl` with `"bbox"` on a GeoTIFF in strips (#2592), as the Brazil Data Cube serves its
/// CBERS scenes: the window comes in, read by range, its values where they lie. Without a box the
/// file is downloaded whole, as before.
#[test]
fn a_window_of_a_geotiff_in_strips_comes_in_as_a_raster() {
// 300 × 200 cells of 0.01° from 10° E, 46° N, a row a strip; cell (x, y) is 7 x − 3 y.
let file = rustgis_data::raster::cog::example_strips(300, 200, 1);
let (base, _) = serve_ranges(file.clone());
let mut s = world();
let url = format!("{base}/cbers.tif");
let r = s.run("layer.addUrl", &json!({"url": url, "bbox": [10.505, 45.005, 11.005, 45.505], "name": "Strips"})).unwrap();
let (c0, r0) = (r["window"]["columns"][0].as_i64().unwrap(), r["window"]["rows"][0].as_i64().unwrap());
assert!((49..=51).contains(&c0) && (49..=51).contains(&r0), "{r}");
let w = s.map().layer_by_name("Strips").and_then(|l| l.raster.as_ref()?.data.clone()).unwrap();
assert!((50..=52).contains(&w.width) && (50..=52).contains(&w.height), "{} × {}", w.width, w.height);
assert_eq!(w.data_type, "Int16");
for (x, y) in [(0, 0), (10, 5), (i64::from(w.width) - 1, i64::from(w.height) - 1)] {
assert_eq!(w.value(0, x, y), Some((7 * (c0 + x) - 3 * (r0 + y)) as f32), "cell ({x}, {y})");
}
s.run("layer.addUrl", &json!({"url": url, "name": "Whole"})).unwrap();
let whole = s.map().layer_by_name("Whole").and_then(|l| l.raster.as_ref()?.data.clone()).unwrap();
assert_eq!((whole.width, whole.height), (300, 200));
}

/// A window read for a raster made from it (AlphaEarth's similarity and change, #1720) says what
/// its header left out, as `layer.addUrl` says it when it adds the window; a clean file, nothing.
#[test]
Expand Down
Loading
Loading