geolith-dataset-builder 0.2.2

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! `geolith dataset inspect`: the layout of a raster and whether each read
//! path decodes it.
//!
//! The layout comes from the TIFF tags, read here with the `tiff` decoder
//! (`terrain::Cog` keeps them private). The read paths are the two the
//! dataset engine uses: [`Dem::open`] for a whole band and [`Cog`] for
//! windows.

use std::path::Path;

use anyhow::Context as _;
use serde::{Deserialize, Serialize};
use tiff::decoder::Decoder;
use tiff::tags::Tag;

use crate::cli::InspectArgs;
use geolith::terrain::{Cog, Crs, Dem};

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

/// GDAL nodata tag (ASCII).
const TAG_GDAL_NODATA: u16 = 42113;

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

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

/// Largest whole band, in bytes of `f32` samples, that `Dem::open` is tried
/// on.
const DEM_OPEN_MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024;

/// The limit printed for a tiled LZW file the chunk path cannot decode.
pub const TILED_LZW_LIMIT: &str =
    "tiled LZW does not decode in the chunk path (image-rs/image-tiff#395)";

/// What `inspect` found in one raster.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Report {
    /// Sample type, e.g. `uint8`, `int16`, `float32`.
    pub data_type: String,
    /// `GDAL_NODATA` tag text, null when the tag is absent, `error: …` when it
    /// is present but not ASCII text.
    pub nodata: Option<String>,
    /// `none`, `lzw`, `deflate`, `zstd`, `jpeg`, `packbits` or `other(<n>)`.
    pub compression: String,
    /// TIFF predictor: 1 none, 2 horizontal, 3 floating point.
    pub predictor: u16,
    /// `tiled <w>x<h>` or `stripped <rows> rows`.
    pub layout: String,
    /// Overviews of the full-resolution image.
    pub overviews: Overviews,
    /// `EPSG:<code>` of the grid, or null when it cannot be read.
    pub crs: Option<String>,
    /// Full-resolution size.
    pub size: Size,
    /// `ok`, `error: …` or `skipped: whole-band read needs <n> GB`.
    pub dem_open: String,
    /// `ok` or `error: …`: one chunk-sized window at the top-left of every
    /// level through `terrain::Cog`.
    pub cog_read: String,
    /// A known decoder limit that explains a failed read, if any.
    pub known_limit: Option<String>,
    /// The `gdal_translate` command that re-encodes the file into one the
    /// chunk path reads, if a known limit applies.
    pub reencode_command: Option<String>,
}

/// Overviews of a raster.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Overviews {
    /// Number of overviews.
    pub count: usize,
    /// Each overview's `<w>x<h>`, largest first.
    pub sizes: Vec<String>,
}

/// Width and height in pixels.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Size {
    /// Pixels across.
    pub width: u32,
    /// Pixels down.
    pub height: u32,
}

/// Tags of one image directory.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Ifd {
    /// Index of the directory in the file.
    pub index: usize,
    pub width: u32,
    pub height: u32,
    pub compression: u16,
    pub predictor: u16,
    pub sample_format: u16,
    pub bits_per_sample: u16,
    pub tiled: bool,
    /// Tile width, or the image width for strips.
    pub chunk_width: u32,
    /// Tile height, or `RowsPerStrip` (the image height when absent).
    pub chunk_height: u32,
    pub subfile: u32,
}

impl Ifd {
    /// Whether the directory is a resolution level: the first image or a
    /// reduced-resolution one, never a mask.
    const fn is_level(&self) -> bool {
        self.subfile & SUBFILE_MASK == 0 && (self.index == 0 || self.subfile & SUBFILE_REDUCED != 0)
    }
}

/// Read the tags of the directory the decoder points at.
fn read_ifd<R: std::io::Read + std::io::Seek>(
    decoder: &mut Decoder<R>,
    index: usize,
) -> anyhow::Result<Ifd> {
    let (width, height) = decoder.dimensions()?;
    let first = |values: Option<Vec<u16>>, default: u16| {
        values.and_then(|v| v.first().copied()).unwrap_or(default)
    };
    let compression = decoder.find_tag_unsigned(Tag::Compression)?.unwrap_or(1);
    let predictor = decoder.find_tag_unsigned(Tag::Predictor)?.unwrap_or(1);
    let sample_format = first(decoder.find_tag_unsigned_vec(Tag::SampleFormat)?, 1);
    let bits_per_sample = first(decoder.find_tag_unsigned_vec(Tag::BitsPerSample)?, 1);
    let tile_width: Option<u32> = decoder.find_tag_unsigned(Tag::TileWidth)?;
    let tile_length: Option<u32> = decoder.find_tag_unsigned(Tag::TileLength)?;
    let (tiled, chunk_width, chunk_height) = match (tile_width, tile_length) {
        (Some(w), Some(h)) => (true, w, h),
        _ => {
            let rows = decoder
                .find_tag_unsigned(Tag::RowsPerStrip)?
                .unwrap_or(height);
            (false, width, rows)
        }
    };
    let subfile = decoder
        .find_tag_unsigned(Tag::Unknown(TAG_NEW_SUBFILE_TYPE))?
        .unwrap_or(0);
    Ok(Ifd {
        index,
        width,
        height,
        compression,
        predictor,
        sample_format,
        bits_per_sample,
        tiled,
        chunk_width,
        chunk_height,
        subfile,
    })
}

/// The report text of a `GDAL_NODATA` lookup: `None` only when the tag is
/// absent, `error: …` when it is present but not readable as text.
fn nodata_text(tag: tiff::TiffResult<Option<tiff::decoder::ifd::Value>>) -> Option<String> {
    match tag.and_then(|value| value.map(|v| v.into_string()).transpose()) {
        Ok(None) => None,
        Ok(Some(raw)) => Some(raw.trim_end_matches('\0').trim().to_owned()),
        Err(e) => Some(format!("error: GDAL_NODATA tag: {e}")),
    }
}

/// Every image directory of `path`, in file order, and the GDAL nodata text
/// of the first.
fn read_ifds(path: &Path) -> anyhow::Result<(Vec<Ifd>, Option<String>)> {
    let file = std::fs::File::open(path).with_context(|| format!("reading {}", path.display()))?;
    let mut decoder = Decoder::new(std::io::BufReader::new(file))
        .with_context(|| format!("reading {}", path.display()))?;
    let nodata = nodata_text(decoder.find_tag(Tag::Unknown(TAG_GDAL_NODATA)));
    let mut ifds = Vec::with_capacity(8);
    loop {
        let ifd = read_ifd(&mut decoder, ifds.len())
            .with_context(|| format!("{}: image directory {}", path.display(), ifds.len()))?;
        ifds.push(ifd);
        if !decoder.more_images() {
            break;
        }
        decoder
            .next_image()
            .with_context(|| format!("{}: image directory {}", path.display(), ifds.len()))?;
    }
    Ok((ifds, nodata))
}

/// The resolution levels of `path`, full resolution first, then overviews
/// from largest to smallest (the order of `terrain::Cog` levels).
///
/// # Errors
///
/// Fails, naming the file, when its directories cannot be read.
pub(crate) fn levels(path: &Path) -> anyhow::Result<Vec<Ifd>> {
    let (ifds, _) = read_ifds(path)?;
    Ok(sorted_levels(&ifds))
}

/// The levels among `ifds`, widest first.
fn sorted_levels(ifds: &[Ifd]) -> Vec<Ifd> {
    let mut levels: Vec<Ifd> = ifds.iter().copied().filter(Ifd::is_level).collect();
    levels.sort_by_key(|l| std::cmp::Reverse(l.width));
    levels
}

/// Name of a TIFF sample type, e.g. `uint8` or `float32`.
#[must_use]
fn data_type(sample_format: u16, bits: u16) -> String {
    match sample_format {
        1 => format!("uint{bits}"),
        2 => format!("int{bits}"),
        3 => format!("float{bits}"),
        other => format!("other(sample format {other}, {bits} bits)"),
    }
}

/// Name of a TIFF compression code.
#[must_use]
fn compression_name(code: u16) -> String {
    match code {
        1 => "none".to_owned(),
        5 => "lzw".to_owned(),
        8 | 32946 => "deflate".to_owned(),
        50000 => "zstd".to_owned(),
        7 => "jpeg".to_owned(),
        32773 => "packbits".to_owned(),
        other => format!("other({other})"),
    }
}

/// The skip text when a whole-band read of `width` x `height` `f32` samples
/// is over 2 GiB, else `None` (the read is tried).
#[must_use]
pub fn dem_open_skip(width: u32, height: u32) -> Option<String> {
    let bytes = u64::from(width) * u64::from(height) * 4;
    (bytes > DEM_OPEN_MAX_BYTES).then(|| {
        format!(
            "skipped: whole-band read needs {:.1} GB",
            bytes as f64 / 1e9
        )
    })
}

/// The command that re-encodes `path` as a DEFLATE COG beside it.
#[must_use]
fn reencode_command(path: &Path) -> String {
    let stem = path
        .file_stem()
        .map_or_else(String::new, |s| s.to_string_lossy().into_owned());
    let out = path.with_file_name(format!("{stem}.deflate.tif"));
    format!(
        "gdal_translate -of COG -co COMPRESS=DEFLATE -co PREDICTOR=2 -co BLOCKSIZE=512 \
         -co OVERVIEWS=AUTO {} {}",
        path.display(),
        out.display()
    )
}

/// Where the windowed read failed.
#[derive(Debug)]
enum CogFailure {
    /// Opening the file or matching its levels, before any chunk.
    Open(anyhow::Error),
    /// Decoding a window.
    Read(anyhow::Error),
}

/// Whether the tiled-LZW limit explains the outcome: LZW, tiled, and a
/// window failed to decode (a failed open, e.g. a missing CRS, is not it).
#[must_use]
fn tiled_lzw_limit_applies(compression: &str, tiled: bool, failure: Option<&CogFailure>) -> bool {
    compression == "lzw" && tiled && matches!(failure, Some(CogFailure::Read(_)))
}

/// The known limit that explains a failed window read of a file with
/// `compression`, if any: tiled LZW. ZSTD has none: the `tiff` crate is built
/// with its `zstd` feature, so a CDSE NDVI COG decodes like any DEFLATE one.
#[must_use]
fn known_limit(
    compression: &str,
    tiled: bool,
    failure: Option<&CogFailure>,
) -> Option<&'static str> {
    if tiled_lzw_limit_applies(compression, tiled, failure) {
        Some(TILED_LZW_LIMIT)
    } else {
        None
    }
}

/// Read one chunk-sized window at the top-left of every level.
fn cog_read(path: &Path, crs: Option<Crs>, levels: &[Ifd]) -> Result<(), CogFailure> {
    let mut cog = Cog::open(path, crs).map_err(|e| CogFailure::Open(e.into()))?;
    if cog.levels() != levels.len() {
        return Err(CogFailure::Open(anyhow::anyhow!(
            "the reader sees {} levels, the tags {}",
            cog.levels(),
            levels.len()
        )));
    }
    for (level, ifd) in levels.iter().enumerate() {
        let width = ifd.chunk_width.min(ifd.width);
        let height = ifd.chunk_height.min(ifd.height);
        cog.read_window(level, 0, 0, width, height).map_err(|e| {
            CogFailure::Read(anyhow::Error::from(e).context(format!("level {level}")))
        })?;
    }
    Ok(())
}

/// `ok` or `error: <cause chain>`.
fn outcome(result: Result<(), &anyhow::Error>) -> String {
    match result {
        Ok(()) => "ok".to_owned(),
        Err(e) => format!("error: {e:#}"),
    }
}

/// Inspect the raster at `path`: its layout from the TIFF tags, then a
/// whole-band read (when it fits in 2 GiB) and a windowed read of every
/// level. `crs` overrides the file's CRS, as in the dataset config.
///
/// # Errors
///
/// Fails, naming the file, when the TIFF directories cannot be read. A
/// failed read path is reported in the [`Report`], not as an error.
pub fn inspect(path: &Path, crs: Option<Crs>) -> anyhow::Result<Report> {
    let (ifds, nodata) = read_ifds(path)?;
    let levels = sorted_levels(&ifds);
    let full = *levels
        .first()
        .with_context(|| format!("{}: no full-resolution image", path.display()))?;

    let layout = if full.tiled {
        format!("tiled {}x{}", full.chunk_width, full.chunk_height)
    } else {
        format!("stripped {} rows", full.chunk_height.min(full.height))
    };
    let sizes: Vec<String> = levels
        .iter()
        .skip(1)
        .map(|l| format!("{}x{}", l.width, l.height))
        .collect();

    let crs_name = match crs {
        Some(c) => Some(c),
        None => Cog::open(path, None).ok().map(|c| c.crs()),
    }
    .map(|c| format!("EPSG:{}", c.epsg()));

    let dem_open =
        dem_open_skip(full.width, full.height).unwrap_or_else(|| match Dem::open(path, crs) {
            Ok(_) => outcome(Ok(())),
            Err(e) => outcome(Err(&e.into())),
        });
    let failure = cog_read(path, crs, &levels).err();
    let cog_read = outcome(match &failure {
        None => Ok(()),
        Some(CogFailure::Open(e) | CogFailure::Read(e)) => Err(e),
    });

    let compression = compression_name(full.compression);
    let limit = known_limit(&compression, full.tiled, failure.as_ref());

    Ok(Report {
        data_type: data_type(full.sample_format, full.bits_per_sample),
        nodata,
        compression,
        predictor: full.predictor,
        layout,
        overviews: Overviews {
            count: sizes.len(),
            sizes,
        },
        crs: crs_name,
        size: Size {
            width: full.width,
            height: full.height,
        },
        dem_open,
        cog_read,
        known_limit: limit.map(str::to_owned),
        reencode_command: limit.map(|_| reencode_command(path)),
    })
}

/// The human-readable lines of `report`.
#[must_use]
fn lines(report: &Report) -> Vec<String> {
    let or_none = |v: &Option<String>| v.clone().unwrap_or_else(|| "none".to_owned());
    let mut out = Vec::with_capacity(12);
    out.push(format!("data type:   {}", report.data_type));
    out.push(format!("nodata:      {}", or_none(&report.nodata)));
    out.push(format!("compression: {}", report.compression));
    out.push(format!("predictor:   {}", report.predictor));
    out.push(format!("layout:      {}", report.layout));
    out.push(format!(
        "overviews:   {}{}",
        report.overviews.count,
        if report.overviews.sizes.is_empty() {
            String::new()
        } else {
            format!(" ({})", report.overviews.sizes.join(", "))
        }
    ));
    out.push(format!("crs:         {}", or_none(&report.crs)));
    out.push(format!(
        "size:        {}x{}",
        report.size.width, report.size.height
    ));
    out.push(format!("dem open:    {}", report.dem_open));
    out.push(format!("cog read:    {}", report.cog_read));
    if let Some(limit) = &report.known_limit {
        out.push(format!("known limit: {limit}"));
    }
    if let Some(command) = &report.reencode_command {
        out.push(format!("re-encode:   {command}"));
    }
    out
}

/// Run `geolith dataset inspect`: print the report as lines, then its JSON
/// on the last line.
///
/// # Errors
///
/// Fails on an unsupported `--crs-epsg` or when the file cannot be read.
pub fn run(args: &InspectArgs) -> anyhow::Result<()> {
    let crs = args
        .crs_epsg
        .map(|code| Crs::from_epsg(code).with_context(|| format!("--crs-epsg {code}")))
        .transpose()?;
    let report = inspect(&args.file, crs)?;
    for line in lines(&report) {
        println!("{line}");
    }
    println!("{}", serde_json::to_string(&report)?);
    Ok(())
}

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

    fn fixture(name: &str) -> PathBuf {
        Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/inspect")
            .join(name)
    }

    // Expected values come from `gdalinfo` of each fixture (README.md).

    #[test]
    fn inspect_reads_a_deflate_tiled_uint8() {
        let report = inspect(&fixture("u8-deflate-tiled.tif"), None).expect("inspect");
        assert_eq!(report.data_type, "uint8");
        assert_eq!(report.nodata.as_deref(), Some("255"));
        assert_eq!(report.compression, "deflate");
        assert_eq!(
            report.predictor, 1,
            "the COG was written without a predictor"
        );
        assert_eq!(report.layout, "tiled 32x32");
        assert_eq!(
            report.overviews,
            Overviews {
                count: 1,
                sizes: vec!["32x32".to_owned()],
            }
        );
        assert_eq!(report.crs.as_deref(), Some("EPSG:4326"));
        assert_eq!(
            report.size,
            Size {
                width: 64,
                height: 64,
            }
        );
        assert_eq!(report.dem_open, "ok");
        assert_eq!(report.cog_read, "ok");
        assert_eq!(report.known_limit, None);
        assert_eq!(report.reencode_command, None);
    }

    #[test]
    fn inspect_explains_tiled_lzw() {
        let path = fixture("u8-lzw-tiled.tif");
        let report = inspect(&path, None).expect("inspect");
        assert_eq!(report.compression, "lzw");
        assert_eq!(report.layout, "tiled 32x32");
        assert_eq!(report.overviews.count, 0);
        // Observed with tiff 0.11.3: the chunk path decodes this file.
        assert_eq!(report.cog_read, "ok");
        assert_eq!(report.dem_open, "ok");
        assert_eq!(report.known_limit, None);
        assert_eq!(report.reencode_command, None);
    }

    #[test]
    fn inspect_reads_a_stripped_float32_lzw() {
        let report = inspect(&fixture("f32-lzw-stripped.tif"), None).expect("inspect");
        assert_eq!(report.data_type, "float32");
        assert_eq!(report.nodata.as_deref(), Some("-9999"));
        assert_eq!(report.compression, "lzw");
        assert_eq!(report.layout, "stripped 16 rows");
        assert_eq!(report.overviews.count, 0);
        assert!(report.overviews.sizes.is_empty());
        assert_eq!(report.crs.as_deref(), Some("EPSG:4326"));
        assert_eq!(report.dem_open, "ok");
        assert_eq!(report.cog_read, "ok");
        assert_eq!(report.known_limit, None, "strips are not the tiled limit");
        assert_eq!(report.reencode_command, None);
    }

    #[test]
    fn the_lzw_limit_applies_only_to_a_failed_tiled_lzw_read() {
        let read = CogFailure::Read(anyhow::anyhow!("read chunk 0"));
        let open = CogFailure::Open(anyhow::anyhow!("missing GeoKeyDirectory"));
        assert!(tiled_lzw_limit_applies("lzw", true, Some(&read)));
        assert!(!tiled_lzw_limit_applies("lzw", true, None));
        assert!(!tiled_lzw_limit_applies("lzw", true, Some(&open)), "open");
        assert!(
            !tiled_lzw_limit_applies("lzw", false, Some(&read)),
            "strips"
        );
        assert!(!tiled_lzw_limit_applies("deflate", true, Some(&read)));
    }

    #[test]
    fn a_failed_zstd_read_names_no_limit() {
        // ZSTD decodes: the `tiff` crate is built with its `zstd` feature, so
        // a failed read of a ZSTD file is an error like any other.
        let read = CogFailure::Read(anyhow::anyhow!("read chunk 7642: truncated"));
        assert_eq!(known_limit("zstd", true, Some(&read)), None);
        assert_eq!(known_limit("zstd", false, Some(&read)), None);
        assert_eq!(known_limit("lzw", true, Some(&read)), Some(TILED_LZW_LIMIT));
        assert_eq!(known_limit("deflate", true, Some(&read)), None);
    }

    #[test]
    fn the_reencode_command_writes_a_deflate_cog_beside_the_input() {
        assert_eq!(
            reencode_command(Path::new("/data/ndvi/c_gls_NDVI300.tiff")),
            "gdal_translate -of COG -co COMPRESS=DEFLATE -co PREDICTOR=2 -co BLOCKSIZE=512 \
             -co OVERVIEWS=AUTO /data/ndvi/c_gls_NDVI300.tiff /data/ndvi/c_gls_NDVI300.deflate.tif"
        );
    }

    /// A 2 x 2 strip TIFF whose `GDAL_NODATA` tag is `nodata`.
    fn write_tiff_with_nodata(path: &Path, nodata: Option<&[u16]>) {
        let file = std::fs::File::create(path).expect("create");
        let mut encoder = tiff::encoder::TiffEncoder::new(file).expect("encoder");
        let mut image = encoder
            .new_image::<tiff::encoder::colortype::Gray8>(2, 2)
            .expect("image");
        if let Some(values) = nodata {
            image
                .encoder()
                .write_tag(Tag::Unknown(TAG_GDAL_NODATA), values)
                .expect("tag");
        }
        image.write_data(&[1, 2, 3, 4]).expect("data");
    }

    #[test]
    fn a_malformed_nodata_tag_is_an_error_and_an_absent_one_is_null() {
        let dir = tempfile::tempdir().expect("tempdir");
        let short = dir.path().join("short.tif");
        // GDAL writes GDAL_NODATA as ASCII; a SHORT value is malformed.
        write_tiff_with_nodata(&short, Some(&[255]));
        let (_, nodata) = read_ifds(&short).expect("tags");
        let text = nodata.expect("a present tag is reported");
        assert!(text.starts_with("error: GDAL_NODATA tag: "), "{text}");

        let absent = dir.path().join("absent.tif");
        write_tiff_with_nodata(&absent, None);
        assert_eq!(read_ifds(&absent).expect("tags").1, None);
    }

    /// The printed re-encode command, run with local GDAL, gives a file
    /// that `inspect` reads as DEFLATE.
    #[test]
    #[ignore = "needs local GDAL (gdal_translate)"]
    fn the_reencode_command_runs_with_gdal() {
        let gdal = std::process::Command::new("gdal_translate")
            .arg("--version")
            .output();
        if !gdal.is_ok_and(|o| o.status.success()) {
            eprintln!("skipped: gdal_translate is not installed");
            return;
        }
        let dir = tempfile::tempdir().expect("tempdir");
        let input = dir.path().join("u8-lzw-tiled.tif");
        std::fs::copy(fixture("u8-lzw-tiled.tif"), &input).expect("copy fixture");
        let command = reencode_command(&input);
        let mut words = command.split(' ');
        let program = words.next().expect("program");
        let status = std::process::Command::new(program)
            .args(words)
            .status()
            .expect("run gdal_translate");
        assert!(status.success(), "{command}");
        let report =
            inspect(&dir.path().join("u8-lzw-tiled.deflate.tif"), None).expect("inspect output");
        assert_eq!(report.compression, "deflate");
        assert_eq!(report.predictor, 2);
        assert_eq!(report.cog_read, "ok");
    }

    #[test]
    fn inspect_skips_dem_open_on_huge_rasters() {
        // The NDVI grid: 120960 x 47040 x 4 bytes = 22,756,646,400 bytes.
        assert_eq!(
            dem_open_skip(120_960, 47_040).as_deref(),
            Some("skipped: whole-band read needs 22.8 GB")
        );
        // 2 GiB exactly (32768 x 16384 x 4) is still tried; one row more is not.
        assert_eq!(dem_open_skip(32_768, 16_384), None);
        assert_eq!(
            dem_open_skip(32_768, 16_385).as_deref(),
            Some("skipped: whole-band read needs 2.1 GB")
        );
        assert_eq!(dem_open_skip(64, 64), None);
    }
}