geolith 0.2.1

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
Documentation
//! Windowed reader for tiled or stripped `GeoTIFFs`, including Cloud Optimized
//! `GeoTIFF` overviews.
//!
//! [`Dem`](crate::terrain::Dem) decodes a whole raster into memory, which
//! does not scale past a few gigapixels. [`Cog`] decodes only the internal
//! tiles or strips that a requested window touches, so memory follows the
//! window size instead of the file size.

use std::collections::{HashMap, VecDeque};
use std::fs::File;
use std::io::BufReader;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::error::{GeolithError, Result};
use tiff::decoder::{ChunkType, Decoder};
use tiff::tags::Tag;

use crate::terrain::crs::Crs;
use crate::terrain::dem::{
    GeoTransform, read_crs, read_geo_transform, read_nodata, to_f32_samples,
};

/// TIFF `NewSubfileType` tag.
const TAG_NEW_SUBFILE_TYPE: u16 = 254;

/// `NewSubfileType` bit for a reduced-resolution (overview) image.
const SUBFILE_REDUCED: u32 = 1;

/// `NewSubfileType` bit for a transparency mask.
const SUBFILE_MASK: u32 = 4;

/// Decoded chunks kept per reader; adjacent windows reuse them. A mosaic
/// keeps one idle reader per source, so this bounds idle memory to about
/// sources x 8 chunks.
const CHUNK_CACHE_LEN: usize = 8;

/// One resolution level: the full-resolution image or an overview.
#[derive(Debug, Clone, Copy)]
struct Level {
    /// Image file directory index inside the TIFF.
    ifd: usize,
    width: u32,
    height: u32,
    /// Internal tile or strip size; strips span the full width.
    chunk_width: u32,
    chunk_height: u32,
}

/// Decoded samples of one tile or strip.
#[derive(Debug, Clone)]
struct Chunk {
    values: Arc<[f32]>,
    /// Samples per row in `values`.
    stride: i64,
    /// Rows in `values`.
    rows: i64,
}

/// A `GeoTIFF` opened for windowed reads.
///
/// The decoder is not shareable between threads, so open one `Cog` per
/// thread; opening reads only the image directories.
pub struct Cog {
    path: PathBuf,
    decoder: Decoder<BufReader<File>>,
    /// Image directory the decoder points at.
    current_ifd: usize,
    /// Level 0 is full resolution, then overviews from largest to smallest.
    levels: Vec<Level>,
    transform: GeoTransform,
    crs: Crs,
    nodata: Option<f64>,
    /// Decoded chunks by `(level, chunk index)`, oldest first in `order`.
    cache: HashMap<(usize, u32), Chunk>,
    order: VecDeque<(usize, u32)>,
}

impl std::fmt::Debug for Cog {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Cog")
            .field("path", &self.path)
            .field("levels", &self.levels)
            .field("transform", &self.transform)
            .field("crs", &self.crs)
            .field("nodata", &self.nodata)
            .finish_non_exhaustive()
    }
}

impl Cog {
    /// Open a `GeoTIFF` and read its image directories.
    ///
    /// `crs_override` replaces the CRS from the `GeoKeyDirectory`, for files
    /// written without geokeys.
    ///
    /// # Errors
    ///
    /// Returns [`GeolithError::GeoTiff`] when the file cannot be decoded,
    /// lacks georeferencing or holds more than one sample per pixel, and
    /// [`GeolithError::Crs`] when the EPSG code is unsupported.
    pub fn open(path: &Path, crs_override: Option<Crs>) -> Result<Self> {
        let geotiff = |what: &str, e: &dyn std::fmt::Display| {
            GeolithError::GeoTiff(format!("{}: {what}: {e}", path.display()))
        };
        let file = File::open(path)?;
        let mut decoder = Decoder::new(BufReader::new(file))
            .map_err(|e| geotiff("open", &e))?
            .with_limits(tiff::decoder::Limits::unlimited());

        let transform = read_geo_transform(&mut decoder, path)?;
        let crs = match crs_override {
            Some(crs) => crs,
            None => read_crs(&mut decoder, path)?,
        };
        let nodata = read_nodata(&mut decoder);

        let mut levels = Vec::with_capacity(8);
        let mut ifd = 0;
        loop {
            let subfile = decoder
                .get_tag_u32(Tag::Unknown(TAG_NEW_SUBFILE_TYPE))
                .unwrap_or(0);
            let is_mask = subfile & SUBFILE_MASK != 0;
            let is_overview = subfile & SUBFILE_REDUCED != 0;
            if !is_mask && (ifd == 0 || is_overview) {
                levels.push(read_level(&mut decoder, ifd, path)?);
            }
            if !decoder.more_images() {
                break;
            }
            decoder
                .next_image()
                .map_err(|e| geotiff("next image", &e))?;
            ifd += 1;
        }
        levels.sort_by_key(|l| std::cmp::Reverse(l.width));

        Ok(Self {
            path: path.to_path_buf(),
            decoder,
            current_ifd: ifd,
            levels,
            transform,
            crs,
            nodata,
            cache: HashMap::with_capacity(CHUNK_CACHE_LEN),
            order: VecDeque::with_capacity(CHUNK_CACHE_LEN),
        })
    }

    /// Number of levels: 1 for full resolution plus one per overview.
    #[must_use]
    pub const fn levels(&self) -> usize {
        self.levels.len()
    }

    /// Width and height in pixels of `level`, or `None` past the last level.
    #[must_use]
    pub fn size(&self, level: usize) -> Option<(u32, u32)> {
        self.levels.get(level).map(|l| (l.width, l.height))
    }

    /// Pixel-to-projected transform of `level`, or `None` past the last level.
    ///
    /// An overview covers the same extent as level 0 with fewer, larger
    /// pixels, so its pixel size is scaled by the width and height ratios.
    #[must_use]
    pub fn geo_transform(&self, level: usize) -> Option<GeoTransform> {
        let full = self.levels.first()?;
        let l = self.levels.get(level)?;
        Some(GeoTransform {
            origin_x: self.transform.origin_x,
            origin_y: self.transform.origin_y,
            pixel_width: self.transform.pixel_width * f64::from(full.width) / f64::from(l.width),
            pixel_height: self.transform.pixel_height * f64::from(full.height)
                / f64::from(l.height),
        })
    }

    /// Coordinate reference system of the projected coordinates.
    #[must_use]
    pub const fn crs(&self) -> Crs {
        self.crs
    }

    /// Read a `width` x `height` window at pixel `(x0, y0)` of `level`.
    ///
    /// Samples come back row-major as `f32`. Nodata, NaN and pixels outside
    /// the raster are `NaN`, so a window may start at a negative offset or
    /// run past the edge. Only the chunks the window touches are decoded.
    ///
    /// # Errors
    ///
    /// Returns [`GeolithError::GeoTiff`] when `level` does not exist or a
    /// chunk cannot be decoded.
    pub fn read_window(
        &mut self,
        level: usize,
        x0: i64,
        y0: i64,
        width: u32,
        height: u32,
    ) -> Result<Vec<f32>> {
        let l = *self.levels.get(level).ok_or_else(|| {
            GeolithError::GeoTiff(format!(
                "{}: level {level} does not exist ({} levels)",
                self.path.display(),
                self.levels.len()
            ))
        })?;
        let (w, h) = (i64::from(width), i64::from(height));
        let mut out = vec![f32::NAN; width as usize * height as usize];

        // Window clipped to the raster.
        let left = x0.max(0);
        let top = y0.max(0);
        let right = (x0 + w).min(i64::from(l.width));
        let bottom = (y0 + h).min(i64::from(l.height));
        if left >= right || top >= bottom {
            return Ok(out);
        }

        let (cw, ch) = (i64::from(l.chunk_width), i64::from(l.chunk_height));
        let chunks_across = (i64::from(l.width) + cw - 1) / cw;
        for chunk_row in top / ch..=(bottom - 1) / ch {
            for chunk_col in left / cw..=(right - 1) / cw {
                let index = chunk_index(chunk_row, chunk_col, chunks_across).ok_or_else(|| {
                    GeolithError::GeoTiff(format!("{}: chunk index overflow", self.path.display()))
                })?;
                let chunk = self.chunk(level, &l, index)?;
                let (cx, cy) = (chunk_col * cw, chunk_row * ch);
                let stride = chunk.stride;
                for y in top.max(cy)..bottom.min(cy + chunk.rows) {
                    // Chunk columns come from `left` and `right`, so every
                    // chunk overlaps the window by at least one pixel.
                    let x_start = left.max(cx);
                    let x_end = right.min(cx + stride);
                    let src = ((y - cy) * stride + (x_start - cx)) as usize;
                    let dst = ((y - y0) * w + (x_start - x0)) as usize;
                    let n = (x_end - x_start) as usize;
                    out[dst..dst + n].copy_from_slice(&chunk.values[src..src + n]);
                }
            }
        }
        Ok(out)
    }

    /// Decoded samples of one chunk, from the cache or the file.
    fn chunk(&mut self, level: usize, l: &Level, index: u32) -> Result<Chunk> {
        if let Some(chunk) = self.cache.get(&(level, index)) {
            return Ok(chunk.clone());
        }
        if self.current_ifd != l.ifd {
            self.decoder.seek_to_image(l.ifd).map_err(|e| {
                GeolithError::GeoTiff(format!(
                    "{}: seek to image {}: {e}",
                    self.path.display(),
                    l.ifd
                ))
            })?;
            self.current_ifd = l.ifd;
        }
        let decoded = self.decoder.read_chunk(index).map_err(|e| {
            GeolithError::GeoTiff(format!("{}: read chunk {index}: {e}", self.path.display()))
        })?;
        let values = to_f32_samples(decoded, self.nodata, &self.path)?;
        // `read_chunk` cuts edge tiles to the pixels inside the raster.
        let (data_w, data_h) = self.decoder.chunk_data_dimensions(index);
        let chunk = Chunk {
            values: values.into(),
            stride: i64::from(data_w),
            rows: i64::from(data_h),
        };
        if self.order.len() == CHUNK_CACHE_LEN
            && let Some(oldest) = self.order.pop_front()
        {
            self.cache.remove(&oldest);
        }
        self.order.push_back((level, index));
        self.cache.insert((level, index), chunk.clone());
        Ok(chunk)
    }
}

/// Row-major index of the chunk at `(row, col)`, or `None` past `u32`.
fn chunk_index(row: i64, col: i64, across: i64) -> Option<u32> {
    u32::try_from(row * across + col).ok()
}

/// Describe the image directory the decoder points at.
fn read_level(decoder: &mut Decoder<BufReader<File>>, ifd: usize, path: &Path) -> Result<Level> {
    let geotiff = |what: &str, e: &dyn std::fmt::Display| {
        GeolithError::GeoTiff(format!("{}: {what}: {e}", path.display()))
    };
    let (width, height) = decoder
        .dimensions()
        .map_err(|e| geotiff("dimensions", &e))?;
    let samples = decoder.get_tag_u32(Tag::SamplesPerPixel).unwrap_or(1);
    if samples != 1 {
        return Err(GeolithError::GeoTiff(format!(
            "{}: {samples} samples per pixel; only single-band rasters are supported",
            path.display()
        )));
    }
    super::check_raster_size(path, std::fs::metadata(path)?.len(), width, height)?;
    let (chunk_width, chunk_height) = match decoder.get_chunk_type() {
        ChunkType::Tile => decoder.chunk_dimensions(),
        ChunkType::Strip => (width, decoder.chunk_dimensions().1),
    };
    super::check_chunk_size(path, chunk_width, chunk_height)?;
    Ok(Level {
        ifd,
        width,
        height,
        chunk_width,
        chunk_height,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn chunk_index_is_row_major_and_rejects_overflow() {
        assert_eq!(chunk_index(0, 0, 5), Some(0));
        assert_eq!(chunk_index(2, 3, 5), Some(13));
        assert_eq!(chunk_index(1 << 20, 0, 1 << 20), None, "2^40 is past u32");
    }
}