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,
};
const TAG_NEW_SUBFILE_TYPE: u16 = 254;
const SUBFILE_REDUCED: u32 = 1;
const SUBFILE_MASK: u32 = 4;
const CHUNK_CACHE_LEN: usize = 8;
#[derive(Debug, Clone, Copy)]
struct Level {
ifd: usize,
width: u32,
height: u32,
chunk_width: u32,
chunk_height: u32,
}
#[derive(Debug, Clone)]
struct Chunk {
values: Arc<[f32]>,
stride: i64,
rows: i64,
}
pub struct Cog {
path: PathBuf,
decoder: Decoder<BufReader<File>>,
current_ifd: usize,
levels: Vec<Level>,
transform: GeoTransform,
crs: Crs,
nodata: Option<f64>,
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 {
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),
})
}
#[must_use]
pub const fn levels(&self) -> usize {
self.levels.len()
}
#[must_use]
pub fn size(&self, level: usize) -> Option<(u32, u32)> {
self.levels.get(level).map(|l| (l.width, l.height))
}
#[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),
})
}
#[must_use]
pub const fn crs(&self) -> Crs {
self.crs
}
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];
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) {
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)
}
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)?;
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)
}
}
fn chunk_index(row: i64, col: i64, across: i64) -> Option<u32> {
u32::try_from(row * across + col).ok()
}
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()
)));
}
let (chunk_width, chunk_height) = match decoder.get_chunk_type() {
ChunkType::Tile => decoder.chunk_dimensions(),
ChunkType::Strip => (width, decoder.chunk_dimensions().1),
};
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");
}
}