Skip to main content

geolith/terrain/
cog.rs

1//! Windowed reader for tiled or stripped `GeoTIFFs`, including Cloud Optimized
2//! `GeoTIFF` overviews.
3//!
4//! [`Dem`](crate::terrain::Dem) decodes a whole raster into memory, which
5//! does not scale past a few gigapixels. [`Cog`] decodes only the internal
6//! tiles or strips that a requested window touches, so memory follows the
7//! window size instead of the file size.
8
9use std::collections::{HashMap, VecDeque};
10use std::fs::File;
11use std::io::BufReader;
12use std::path::{Path, PathBuf};
13use std::sync::Arc;
14
15use crate::error::{GeolithError, Result};
16use tiff::decoder::{ChunkType, Decoder};
17use tiff::tags::Tag;
18
19use crate::terrain::crs::Crs;
20use crate::terrain::dem::{
21    GeoTransform, read_crs, read_geo_transform, read_nodata, to_f32_samples,
22};
23
24/// TIFF `NewSubfileType` tag.
25const TAG_NEW_SUBFILE_TYPE: u16 = 254;
26
27/// `NewSubfileType` bit for a reduced-resolution (overview) image.
28const SUBFILE_REDUCED: u32 = 1;
29
30/// `NewSubfileType` bit for a transparency mask.
31const SUBFILE_MASK: u32 = 4;
32
33/// Decoded chunks kept per reader; adjacent windows reuse them. A mosaic
34/// keeps one idle reader per source, so this bounds idle memory to about
35/// sources x 8 chunks.
36const CHUNK_CACHE_LEN: usize = 8;
37
38/// One resolution level: the full-resolution image or an overview.
39#[derive(Debug, Clone, Copy)]
40struct Level {
41    /// Image file directory index inside the TIFF.
42    ifd: usize,
43    width: u32,
44    height: u32,
45    /// Internal tile or strip size; strips span the full width.
46    chunk_width: u32,
47    chunk_height: u32,
48}
49
50/// Decoded samples of one tile or strip.
51#[derive(Debug, Clone)]
52struct Chunk {
53    values: Arc<[f32]>,
54    /// Samples per row in `values`.
55    stride: i64,
56    /// Rows in `values`.
57    rows: i64,
58}
59
60/// A `GeoTIFF` opened for windowed reads.
61///
62/// The decoder is not shareable between threads, so open one `Cog` per
63/// thread; opening reads only the image directories.
64pub struct Cog {
65    path: PathBuf,
66    decoder: Decoder<BufReader<File>>,
67    /// Image directory the decoder points at.
68    current_ifd: usize,
69    /// Level 0 is full resolution, then overviews from largest to smallest.
70    levels: Vec<Level>,
71    transform: GeoTransform,
72    crs: Crs,
73    nodata: Option<f64>,
74    /// Decoded chunks by `(level, chunk index)`, oldest first in `order`.
75    cache: HashMap<(usize, u32), Chunk>,
76    order: VecDeque<(usize, u32)>,
77}
78
79impl std::fmt::Debug for Cog {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        f.debug_struct("Cog")
82            .field("path", &self.path)
83            .field("levels", &self.levels)
84            .field("transform", &self.transform)
85            .field("crs", &self.crs)
86            .field("nodata", &self.nodata)
87            .finish_non_exhaustive()
88    }
89}
90
91impl Cog {
92    /// Open a `GeoTIFF` and read its image directories.
93    ///
94    /// `crs_override` replaces the CRS from the `GeoKeyDirectory`, for files
95    /// written without geokeys.
96    ///
97    /// # Errors
98    ///
99    /// Returns [`GeolithError::GeoTiff`] when the file cannot be decoded,
100    /// lacks georeferencing or holds more than one sample per pixel, and
101    /// [`GeolithError::Crs`] when the EPSG code is unsupported.
102    pub fn open(path: &Path, crs_override: Option<Crs>) -> Result<Self> {
103        let geotiff = |what: &str, e: &dyn std::fmt::Display| {
104            GeolithError::GeoTiff(format!("{}: {what}: {e}", path.display()))
105        };
106        let file = File::open(path)?;
107        let mut decoder = Decoder::new(BufReader::new(file))
108            .map_err(|e| geotiff("open", &e))?
109            .with_limits(tiff::decoder::Limits::unlimited());
110
111        let transform = read_geo_transform(&mut decoder, path)?;
112        let crs = match crs_override {
113            Some(crs) => crs,
114            None => read_crs(&mut decoder, path)?,
115        };
116        let nodata = read_nodata(&mut decoder);
117
118        let mut levels = Vec::with_capacity(8);
119        let mut ifd = 0;
120        loop {
121            let subfile = decoder
122                .get_tag_u32(Tag::Unknown(TAG_NEW_SUBFILE_TYPE))
123                .unwrap_or(0);
124            let is_mask = subfile & SUBFILE_MASK != 0;
125            let is_overview = subfile & SUBFILE_REDUCED != 0;
126            if !is_mask && (ifd == 0 || is_overview) {
127                levels.push(read_level(&mut decoder, ifd, path)?);
128            }
129            if !decoder.more_images() {
130                break;
131            }
132            decoder
133                .next_image()
134                .map_err(|e| geotiff("next image", &e))?;
135            ifd += 1;
136        }
137        levels.sort_by_key(|l| std::cmp::Reverse(l.width));
138
139        Ok(Self {
140            path: path.to_path_buf(),
141            decoder,
142            current_ifd: ifd,
143            levels,
144            transform,
145            crs,
146            nodata,
147            cache: HashMap::with_capacity(CHUNK_CACHE_LEN),
148            order: VecDeque::with_capacity(CHUNK_CACHE_LEN),
149        })
150    }
151
152    /// Number of levels: 1 for full resolution plus one per overview.
153    #[must_use]
154    pub const fn levels(&self) -> usize {
155        self.levels.len()
156    }
157
158    /// Width and height in pixels of `level`, or `None` past the last level.
159    #[must_use]
160    pub fn size(&self, level: usize) -> Option<(u32, u32)> {
161        self.levels.get(level).map(|l| (l.width, l.height))
162    }
163
164    /// Pixel-to-projected transform of `level`, or `None` past the last level.
165    ///
166    /// An overview covers the same extent as level 0 with fewer, larger
167    /// pixels, so its pixel size is scaled by the width and height ratios.
168    #[must_use]
169    pub fn geo_transform(&self, level: usize) -> Option<GeoTransform> {
170        let full = self.levels.first()?;
171        let l = self.levels.get(level)?;
172        Some(GeoTransform {
173            origin_x: self.transform.origin_x,
174            origin_y: self.transform.origin_y,
175            pixel_width: self.transform.pixel_width * f64::from(full.width) / f64::from(l.width),
176            pixel_height: self.transform.pixel_height * f64::from(full.height)
177                / f64::from(l.height),
178        })
179    }
180
181    /// Coordinate reference system of the projected coordinates.
182    #[must_use]
183    pub const fn crs(&self) -> Crs {
184        self.crs
185    }
186
187    /// Read a `width` x `height` window at pixel `(x0, y0)` of `level`.
188    ///
189    /// Samples come back row-major as `f32`. Nodata, NaN and pixels outside
190    /// the raster are `NaN`, so a window may start at a negative offset or
191    /// run past the edge. Only the chunks the window touches are decoded.
192    ///
193    /// # Errors
194    ///
195    /// Returns [`GeolithError::GeoTiff`] when `level` does not exist or a
196    /// chunk cannot be decoded.
197    pub fn read_window(
198        &mut self,
199        level: usize,
200        x0: i64,
201        y0: i64,
202        width: u32,
203        height: u32,
204    ) -> Result<Vec<f32>> {
205        let l = *self.levels.get(level).ok_or_else(|| {
206            GeolithError::GeoTiff(format!(
207                "{}: level {level} does not exist ({} levels)",
208                self.path.display(),
209                self.levels.len()
210            ))
211        })?;
212        let (w, h) = (i64::from(width), i64::from(height));
213        let mut out = vec![f32::NAN; width as usize * height as usize];
214
215        // Window clipped to the raster.
216        let left = x0.max(0);
217        let top = y0.max(0);
218        let right = (x0 + w).min(i64::from(l.width));
219        let bottom = (y0 + h).min(i64::from(l.height));
220        if left >= right || top >= bottom {
221            return Ok(out);
222        }
223
224        let (cw, ch) = (i64::from(l.chunk_width), i64::from(l.chunk_height));
225        let chunks_across = (i64::from(l.width) + cw - 1) / cw;
226        for chunk_row in top / ch..=(bottom - 1) / ch {
227            for chunk_col in left / cw..=(right - 1) / cw {
228                let index = chunk_index(chunk_row, chunk_col, chunks_across).ok_or_else(|| {
229                    GeolithError::GeoTiff(format!("{}: chunk index overflow", self.path.display()))
230                })?;
231                let chunk = self.chunk(level, &l, index)?;
232                let (cx, cy) = (chunk_col * cw, chunk_row * ch);
233                let stride = chunk.stride;
234                for y in top.max(cy)..bottom.min(cy + chunk.rows) {
235                    // Chunk columns come from `left` and `right`, so every
236                    // chunk overlaps the window by at least one pixel.
237                    let x_start = left.max(cx);
238                    let x_end = right.min(cx + stride);
239                    let src = ((y - cy) * stride + (x_start - cx)) as usize;
240                    let dst = ((y - y0) * w + (x_start - x0)) as usize;
241                    let n = (x_end - x_start) as usize;
242                    out[dst..dst + n].copy_from_slice(&chunk.values[src..src + n]);
243                }
244            }
245        }
246        Ok(out)
247    }
248
249    /// Decoded samples of one chunk, from the cache or the file.
250    fn chunk(&mut self, level: usize, l: &Level, index: u32) -> Result<Chunk> {
251        if let Some(chunk) = self.cache.get(&(level, index)) {
252            return Ok(chunk.clone());
253        }
254        if self.current_ifd != l.ifd {
255            self.decoder.seek_to_image(l.ifd).map_err(|e| {
256                GeolithError::GeoTiff(format!(
257                    "{}: seek to image {}: {e}",
258                    self.path.display(),
259                    l.ifd
260                ))
261            })?;
262            self.current_ifd = l.ifd;
263        }
264        let decoded = self.decoder.read_chunk(index).map_err(|e| {
265            GeolithError::GeoTiff(format!("{}: read chunk {index}: {e}", self.path.display()))
266        })?;
267        let values = to_f32_samples(decoded, self.nodata, &self.path)?;
268        // `read_chunk` cuts edge tiles to the pixels inside the raster.
269        let (data_w, data_h) = self.decoder.chunk_data_dimensions(index);
270        let chunk = Chunk {
271            values: values.into(),
272            stride: i64::from(data_w),
273            rows: i64::from(data_h),
274        };
275        if self.order.len() == CHUNK_CACHE_LEN
276            && let Some(oldest) = self.order.pop_front()
277        {
278            self.cache.remove(&oldest);
279        }
280        self.order.push_back((level, index));
281        self.cache.insert((level, index), chunk.clone());
282        Ok(chunk)
283    }
284}
285
286/// Row-major index of the chunk at `(row, col)`, or `None` past `u32`.
287fn chunk_index(row: i64, col: i64, across: i64) -> Option<u32> {
288    u32::try_from(row * across + col).ok()
289}
290
291/// Describe the image directory the decoder points at.
292fn read_level(decoder: &mut Decoder<BufReader<File>>, ifd: usize, path: &Path) -> Result<Level> {
293    let geotiff = |what: &str, e: &dyn std::fmt::Display| {
294        GeolithError::GeoTiff(format!("{}: {what}: {e}", path.display()))
295    };
296    let (width, height) = decoder
297        .dimensions()
298        .map_err(|e| geotiff("dimensions", &e))?;
299    let samples = decoder.get_tag_u32(Tag::SamplesPerPixel).unwrap_or(1);
300    if samples != 1 {
301        return Err(GeolithError::GeoTiff(format!(
302            "{}: {samples} samples per pixel; only single-band rasters are supported",
303            path.display()
304        )));
305    }
306    super::check_raster_size(path, std::fs::metadata(path)?.len(), width, height)?;
307    let (chunk_width, chunk_height) = match decoder.get_chunk_type() {
308        ChunkType::Tile => decoder.chunk_dimensions(),
309        ChunkType::Strip => (width, decoder.chunk_dimensions().1),
310    };
311    super::check_chunk_size(path, chunk_width, chunk_height)?;
312    Ok(Level {
313        ifd,
314        width,
315        height,
316        chunk_width,
317        chunk_height,
318    })
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324
325    #[test]
326    fn chunk_index_is_row_major_and_rejects_overflow() {
327        assert_eq!(chunk_index(0, 0, 5), Some(0));
328        assert_eq!(chunk_index(2, 3, 5), Some(13));
329        assert_eq!(chunk_index(1 << 20, 0, 1 << 20), None, "2^40 is past u32");
330    }
331}