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
5 changes: 5 additions & 0 deletions crates/data/src/raster/file_revision.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@ impl super::Raster {
original.check_metadata(&metadata)
}

/// Whether this raster's pixels came from the file at `revision`, as it was then.
pub(crate) fn is_from(&self, revision: &FileRevision) -> bool {
matches!(&self.source_file, Some(Ok(original)) if original == revision)
}

/// Checks fresh metadata from this open handle against the original source.
/// This does not verify that the live path still names the handle; check_original_file does.
pub fn check_original_handle(&self, file: &std::fs::File) -> std::result::Result<(), String> {
Expand Down
472 changes: 395 additions & 77 deletions crates/data/src/raster/geotiff.rs

Large diffs are not rendered by default.

72 changes: 42 additions & 30 deletions crates/data/src/raster/mask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::io::{Read, Seek, SeekFrom};
use tiff::decoder::Decoder;
use tiff::tags::Tag;

use super::geotiff::Span;
use crate::{DataError, Result};

/// Most bytes in a chunk, compressed or decoded.
Expand Down Expand Up @@ -68,9 +69,9 @@ pub(super) fn find<R: Read + Seek>(dec: &mut Decoder<R>, image: usize, size: (u3
}

/// Which pixels of the mask image at `index` are opaque, for every `step`-th pixel of it across and
/// down (row by row, `ceil(width / step)` × `ceil(height / step)` of them). A mask that can't be
/// read is an error saying why.
pub(super) fn read<R: Read + Seek>(dec: &mut Decoder<R>, index: usize, step: u32) -> Result<Vec<bool>> {
/// down (row by row, `ceil(width / step)` × `ceil(height / step)` of them), or of those `span`
/// keeps of them. A mask that can't be read is an error saying why.
pub(super) fn read<R: Read + Seek>(dec: &mut Decoder<R>, index: usize, step: u32, span: Option<Span>) -> Result<Vec<bool>> {
dec.seek_to_image(index).map_err(err)?;
let (w, h) = dec.dimensions().map_err(err)?;
// An absent tag is its default; one that can't be read is an error, not a default.
Expand Down Expand Up @@ -107,16 +108,17 @@ pub(super) fn read<R: Read + Seek>(dec: &mut Decoder<R>, index: usize, step: u32
.filter(|n| offsets.len() >= *n && counts.len() >= *n)
.ok_or_else(|| err("a transparency mask's chunk index is shorter than its image"))?;
let row_bytes = (cw as usize).div_ceil(8);
let (ow, oh) = (w.div_ceil(step) as usize, h.div_ceil(step) as usize);
let span = span.unwrap_or_else(|| Span::whole(w.div_ceil(step), h.div_ceil(step)));
let (ow, oh) = (span.width(), span.height());
let mut out = super::filled(ow, oh, false)?;
let step = u64::from(step);
for c in 0..n {
crate::progress::check()?;
let (x0, y0) = ((c as u64 % across) * u64::from(cw), (c as u64 / across) * u64::from(ch));
let tile =
Tile { x0, y0, dw: u64::from(cw).min(u64::from(w).saturating_sub(x0)), dh: u64::from(ch).min(u64::from(h).saturating_sub(y0)) };
// No sampled pixel inside the chunk: skipped.
if tile.first(step).is_none() {
// No sampled pixel of the span inside the chunk: skipped.
if tile.first(step, span).is_none() {
continue;
}
// A tile holds every row, padded; a strip only the image's.
Expand Down Expand Up @@ -144,7 +146,7 @@ pub(super) fn read<R: Read + Seek>(dec: &mut Decoder<R>, index: usize, step: u32
if (decoded.len() as u64) < (row_bytes as u64).saturating_mul(tile.dh) {
return Err(err("a transparency mask's chunk is shorter than its image"));
}
tile.sample(&mut out, ow, step, &decoded, row_bytes, lsb_first);
tile.sample(&mut out, span, step, &decoded, row_bytes, lsb_first);
}
Ok(out)
}
Expand All @@ -160,32 +162,34 @@ struct Tile {
}

impl Tile {
/// The first sampled column and row at or after the chunk's corner, if the chunk holds any
/// sampled pixel (every `step`-th column and row from the image's corner).
fn first(self, step: u64) -> Option<(u64, u64)> {
let (sx, sy) = (self.x0.div_ceil(step) * step, self.y0.div_ceil(step) * step);
(sx < self.x0 + self.dw && sy < self.y0 + self.dh).then_some((sx, sy))
/// The sampled columns and rows (half-open) of the chunk that `span` keeps, if it holds any
/// (every `step`-th column and row from the image's corner).
fn first(self, step: u64, span: Span) -> Option<((u64, u64), (u64, u64))> {
let (xs, ys) = (span.kept(span.cols, self.x0, self.dw, step), span.kept(span.rows, self.y0, self.dh, step));
(xs.0 < xs.1 && ys.0 < ys.1).then_some((xs, ys))
}

/// Puts the chunk's sampled pixels into `out`, `ow` to a row: `decoded` is its rows of
/// `row_bytes` bytes, a pixel a bit, the first of a byte its high bit unless `lsb_first`.
fn sample(self, out: &mut [bool], ow: usize, step: u64, decoded: &[u8], row_bytes: usize, lsb_first: bool) {
let Some((sx, sy)) = self.first(step) else { return };
/// Puts the chunk's sampled pixels that `span` keeps into `out`, the span's width to a row:
/// `decoded` is its rows of `row_bytes` bytes, a pixel a bit, the first of a byte its high bit
/// unless `lsb_first`.
fn sample(self, out: &mut [bool], span: Span, step: u64, decoded: &[u8], row_bytes: usize, lsb_first: bool) {
let Some(((sx, ex), (sy, ey))) = self.first(step, span) else { return };
let (ow, sc, sr) = (span.width(), u64::from(span.cols.0), u64::from(span.rows.0));
let by = usize::try_from(step).unwrap_or(usize::MAX);
for y in (sy..self.y0 + self.dh).step_by(by) {
for y in (sy..ey).step_by(by) {
let row = usize::try_from(y - self.y0)
.ok()
.and_then(|r| r.checked_mul(row_bytes))
.and_then(|at| decoded.get(at..))
.unwrap_or_default();
for x in (sx..self.x0 + self.dw).step_by(by) {
for x in (sx..ex).step_by(by) {
let (bx, bit) = (usize::try_from((x - self.x0) / 8).unwrap_or(usize::MAX), (x - self.x0) % 8);
let Some(byte) = row.get(bx) else { continue };
let on = if lsb_first { byte >> bit & 1 } else { byte >> (7 - bit) & 1 } == 1;
let at = usize::try_from(y / step)
let at = usize::try_from(y / step - sr)
.ok()
.and_then(|r| r.checked_mul(ow))
.and_then(|at| at.checked_add(usize::try_from(x / step).ok()?));
.and_then(|at| at.checked_add(usize::try_from(x / step - sc).ok()?));
if let Some(slot) = at.and_then(|at| out.get_mut(at)) {
*slot = on;
}
Expand Down Expand Up @@ -273,15 +277,22 @@ mod tests {
fn check(bytes: Vec<u8>) {
let mut dec = Decoder::new(std::io::Cursor::new(bytes)).expect("decoder");
assert!(matches!(find(&mut dec, 0, (10, 7)), Found::At(0)));
let all = read(&mut dec, 0, 1).expect("mask");
let all = read(&mut dec, 0, 1, None).expect("mask");
assert_eq!(all.len(), 70);
assert!(all.iter().enumerate().all(|(i, on)| *on == ((i % 10 + i / 10) % 2 == 0)));
// Every third pixel, from the corner.
let some = read(&mut dec, 0, 3).expect("sampled mask");
let some = read(&mut dec, 0, 3, None).expect("sampled mask");
assert_eq!(some.len(), 4 * 3);
for (i, on) in some.iter().enumerate() {
assert_eq!(*on, ((i % 4 * 3 + i / 4 * 3) % 2) == 0, "{i}");
}
// A part of it, columns 3 to 8 and rows 2 to 6, alone; and of every other pixel.
for (step, span) in [(1, Span { cols: (3, 8), rows: (2, 6) }), (2, Span { cols: (1, 4), rows: (1, 4) })] {
let part = read(&mut dec, 0, step, Some(span)).expect("a part of the mask");
let want: Vec<bool> =
(span.rows.0..span.rows.1).flat_map(|y| (span.cols.0..span.cols.1).map(move |x| (x * step + y * step) % 2 == 0)).collect();
assert_eq!(part, want, "every {step}th, {span:?}");
}
}

#[test]
Expand Down Expand Up @@ -311,14 +322,14 @@ mod tests {
fn a_short_or_missing_chunk_is_an_error_not_a_panic() {
let rows = rows();
let mut dec = Decoder::new(std::io::Cursor::new(striped(10, 7, 7, 1, &[rows[..5].concat()]))).expect("decoder");
assert!(read(&mut dec, 0, 1).is_err());
assert!(read(&mut dec, 0, 1, None).is_err());
}

/// A packbits run that lacks its value byte is a short chunk, not eight transparent pixels.
#[test]
fn a_packbits_run_without_its_byte_is_a_short_chunk() {
let mut dec = Decoder::new(std::io::Cursor::new(striped(8, 8, 8, 32773, &[vec![0xF9]]))).expect("decoder");
assert!(read(&mut dec, 0, 1).is_err());
assert!(read(&mut dec, 0, 1, None).is_err());
}

/// A damaged image directory chain is said, not taken for a file without a mask.
Expand All @@ -339,23 +350,24 @@ mod tests {
#[test]
fn tiles_of_an_image_as_wide_as_u32_holds_are_sampled_and_the_walk_ends() {
let step = 1u64 << 20;
let span = Span::whole(4096, 4096);
let last = Tile { x0: 4095 << 20, y0: 0, dw: (1 << 20) - 1, dh: 1 };
assert_eq!(last.first(step), Some((4095 << 20, 0)));
assert_eq!(last.first(step, span), Some(((4095 << 20, (1 << 32) - 1), (0, 1))));
for lsb_first in [false, true] {
let mut row = vec![0u8; 1 << 17];
row[0] = if lsb_first { 0x01 } else { 0x80 };
let mut out = vec![false; 4096];
last.sample(&mut out, 4096, step, &row, row.len(), lsb_first);
last.sample(&mut out, Span::whole(4096, 1), step, &row, row.len(), lsb_first);
assert_eq!(out.iter().filter(|on| **on).count(), 1, "lsb_first {lsb_first}");
assert!(out[4095], "lsb_first {lsb_first}");
}
// Three pixels from 4,294,967,292: the next multiple of 2^20 is 2^32, past them.
let end = Tile { x0: u64::from(u32::MAX) - 3, y0: 0, dw: 3, dh: 1 };
assert_eq!(end.first(step), None);
assert_eq!(end.first(step, span), None);
let tall = Tile { x0: 0, y0: u64::from(u32::MAX) - 3, dw: 1, dh: 3 };
assert_eq!(tall.first(step), None);
assert_eq!(tall.first(step, span), None);
let mut out = vec![false; 4];
end.sample(&mut out, 4, step, &[0xff], 1, false);
end.sample(&mut out, Span::whole(4, 1), step, &[0xff], 1, false);
assert_eq!(out, [false; 4]);
}

Expand All @@ -364,7 +376,7 @@ mod tests {
#[test]
fn a_mask_too_large_to_hold_is_an_error() {
let mut dec = Decoder::new(std::io::Cursor::new(striped(u32::MAX, u32::MAX, u32::MAX, 1, &[vec![0]]))).expect("decoder");
let e = read(&mut dec, 0, 1).unwrap_err().to_string();
let e = read(&mut dec, 0, 1, None).unwrap_err().to_string();
assert!(e.contains("not enough memory"), "{e}");
}
}
105 changes: 103 additions & 2 deletions crates/data/src/raster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -715,7 +715,8 @@ pub struct Raster {
/// The original local GeoTIFF's revision or capture failure, retained with these pixels and never serialized.
#[cfg(not(target_arch = "wasm32"))]
source_file: Option<std::result::Result<file_revision::FileRevision, String>>,
/// Whether the pixels come from a reduced-resolution overview.
/// Whether the pixels come from a reduced-resolution overview: the size, in the file's pixels,
/// of what was read (the file's, or a part's, [`read_path_part`]).
pub overview: Option<(u32, u32)>,
/// With `overview`, whether the pixels are every `step`-th of the file's, from its top-left
/// corner (a picture too large to read whole): each then spans exactly `step` of its pixels,
Expand Down Expand Up @@ -1109,7 +1110,8 @@ impl Raster {

/// How many of the file's pixels one pixel read spans, across and down: exactly `step` for
/// every `step`-th pixel, an overview's size over the file's, else 1. (`overview` stays the
/// file's own size, which `step` needn't divide, so a reader at a step goes by `step`.)
/// size of what was read in the file's pixels, the file's or a part's, which `step` needn't
/// divide, so a reader at a step goes by `step`.)
pub fn file_pixels(&self) -> (f64, f64) {
if self.step > 1 {
return (f64::from(self.step), f64::from(self.step));
Expand Down Expand Up @@ -1425,6 +1427,105 @@ fn read_path_placing(path: &Path, world: bool) -> Result<Raster> {
Ok(r)
}

/// Part of a raster file's image: its left, top, right and bottom edges as fractions of the
/// image's width and height from its top-left corner, 0 to 1. Every level of a file (its full
/// image and its overviews) covers the same ground, so a part is the same ground at each.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Part {
left: f64,
top: f64,
right: f64,
bottom: f64,
}

impl Part {
/// The part between these edges, each cut to the image; `None` when they aren't numbers or
/// leave nothing of it.
pub fn new(left: f64, top: f64, right: f64, bottom: f64) -> Option<Part> {
let [left, top, right, bottom] = [left, top, right, bottom].map(|v| v.clamp(0.0, 1.0));
([left, top, right, bottom].iter().all(|v| v.is_finite()) && left < right && top < bottom).then_some(Part {
left,
top,
right,
bottom,
})
}

/// The columns and rows of a grid `w` × `h` the part covers, out to whole pixels: one at
/// least, of a grid that has any. The image spans `extent` of the grid's pixels each way:
/// its size, or for every k-th pixel of it its size over k, which the grid's last pixel
/// passes when k doesn't divide it.
fn span(self, (w, h): (u32, u32), extent: (f64, f64)) -> geotiff::Span {
let edges = |a: f64, b: f64, n: u32, units: f64| {
let start = ((a * units).floor() as u32).min(n.saturating_sub(1));
(start, ((b * units).ceil() as u32).min(n).max(start.saturating_add(1).min(n)))
};
geotiff::Span { cols: edges(self.left, self.right, w, extent.0), rows: edges(self.top, self.bottom, h, extent.1) }
}
}

/// A part of a raster file read ([`read_path_part`]): its pixels, and where they lie in the grid
/// they were read from, so a window found on that grid ([`GeoTransform::to_pixel`]) is placed on
/// the part in whole pixels, without rounding again.
pub struct PartRead {
pub raster: Raster,
/// The part's first column and row in the grid read.
pub at: (u32, u32),
/// The grid read (the full image, an overview, or every k-th pixel of it), whole: its
/// transform, columns and rows, as a read of all of it places them.
pub grid: (GeoTransform, u32, u32),
/// That grid's longitude/latitude bounds, as [`Raster::extent`] finds a raster's: every k-th
/// pixel's grid can pass the image's edge.
pub bounds: Extent,
/// The file's full image, its columns and rows (the raster's `overview` is the part's).
pub full: (u32, u32),
}

/// `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
/// file. `Ok(None)` when the file isn't read so: not a GeoTIFF, one with a world file beside it,
/// one [`geotiff`] can't read by part (rotated, skewed or without coordinates), or, with
/// `same_as`, no longer the revision of the file that raster was read from, which the part was
/// found on. Read the whole file then. A part read at a coarser level says it with `overview`,
/// the part's size in the file's pixels.
#[cfg(not(target_arch = "wasm32"))]
pub fn read_path_part(path: &Path, part: Part, max: usize, same_as: Option<&Raster>) -> Result<Option<PartRead>> {
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
if !matches!(ext.as_str(), "tif" | "tiff") {
return Ok(None);
}
if !std::fs::metadata(path)?.is_file() {
return Err(DataError::Format(format!("{} is not a regular file", path.display())));
}
// A world file is compared with the file's whole grid as it is read: read whole.
if world::beside(path).is_some() {
return Ok(None);
}
let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("raster").to_string();
let pam = pam::read(path);
let sidecar_nodata = pam.as_ref().and_then(pam::Pam::nodata);
let Some(mut read) = geotiff::read_file_part(path, &name, sidecar_nodata, part, max, same_as)? else { return Ok(None) };
let r = &mut read.raster;
// As [`read_path_placing`]: read again with the no-data the bands it has give, so the
// rounded count leaves out just its pixels.
let applied = pam.as_ref().map(|p| p.nodata_within(r.bands.len()));
if let Some(nd) = applied
&& nd != sidecar_nodata
&& r.nodata.is_none()
&& matches!(r.data_type.as_str(), "UInt32" | "Int32" | "UInt64" | "Int64" | "Float64")
{
drop(read);
let Some(again) = geotiff::read_file_part(path, &name, nd, part, max, same_as)? else { return Ok(None) };
read = again;
}
if let Some(p) = &pam {
read.raster.apply_pam(p, pam::SIDECAR);
}
read.raster.source = Some(path.display().to_string());
Ok(Some(read))
}

/// A picture at `path` with the world file beside it applied (#2075). A scan is placed by it, in
/// the coordinate system of the `.prj` beside it. Whatever goes wrong (no `.prj`, one that can't
/// be used, a world file that can't be read, or one that places it nowhere it can be drawn), the
Expand Down
Loading
Loading