surtgis-core 0.14.8

Core types and traits for SurtGis geospatial library
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! Native GeoTIFF reading/writing (without GDAL dependency)
//!
//! Uses the `tiff` crate for basic TIFF I/O.
//! For full GeoTIFF support (projections, advanced types), enable the `gdal` feature.

use crate::error::{Error, Result};
use crate::raster::{GeoTransform, Raster, RasterElement};
use std::fs::File;
use std::io::Cursor;
use std::path::Path;
use tiff::decoder::{Decoder, DecodingResult, Limits};
use tiff::encoder::colortype::{ColorType, Gray32Float, RGB32Float, RGBA32Float};
use tiff::encoder::compression::DeflateLevel;
use tiff::encoder::{Compression, TiffEncoder};
use tiff::tags::Tag;

/// Options for writing GeoTIFF files
#[derive(Debug, Clone)]
pub struct GeoTiffOptions {
    /// Compression (not fully supported in native mode)
    pub compression: String,
}

impl Default for GeoTiffOptions {
    fn default() -> Self {
        Self {
            compression: "NONE".to_string(),
        }
    }
}

/// Read a GeoTIFF file into a Raster
///
/// Native reader with limited GeoTIFF metadata support.
/// For full support, enable the `gdal` feature.
pub fn read_geotiff<T, P>(path: P, band: Option<usize>) -> Result<Raster<T>>
where
    T: RasterElement,
    P: AsRef<Path>,
{
    let file = File::open(path.as_ref())?;
    decode_geotiff(file, band)
}

/// Read a GeoTIFF from an in-memory buffer into a Raster
///
/// Same as `read_geotiff` but operates on a byte slice instead of a file path.
/// Useful for WASM environments where filesystem access is not available.
pub fn read_geotiff_from_buffer<T>(data: &[u8], band: Option<usize>) -> Result<Raster<T>>
where
    T: RasterElement,
{
    let cursor = Cursor::new(data);
    decode_geotiff(cursor, band)
}

/// Internal: decode a GeoTIFF from any `Read + Seek` source
fn decode_geotiff<T, R>(reader: R, _band: Option<usize>) -> Result<Raster<T>>
where
    T: RasterElement,
    R: std::io::Read + std::io::Seek,
{
    let mut decoder = Decoder::new(reader)
        .map_err(|e| Error::Other(format!("TIFF decode error: {}", e)))?
        .with_limits(Limits::unlimited());

    let (width, height) = decoder
        .dimensions()
        .map_err(|e| Error::Other(format!("Cannot read dimensions: {}", e)))?;

    let rows = height as usize;
    let cols = width as usize;

    // Read image data
    let result = decoder
        .read_image()
        .map_err(|e| Error::Other(format!("Cannot read image data: {}", e)))?;

    let data: Vec<T> = match result {
        DecodingResult::F32(buf) => buf
            .iter()
            .map(|&v| num_traits::cast(v).unwrap_or(T::default_nodata()))
            .collect(),
        DecodingResult::F64(buf) => buf
            .iter()
            .map(|&v| num_traits::cast(v).unwrap_or(T::default_nodata()))
            .collect(),
        DecodingResult::U8(buf) => buf
            .iter()
            .map(|&v| num_traits::cast(v).unwrap_or(T::default_nodata()))
            .collect(),
        DecodingResult::U16(buf) => buf
            .iter()
            .map(|&v| num_traits::cast(v).unwrap_or(T::default_nodata()))
            .collect(),
        DecodingResult::U32(buf) => buf
            .iter()
            .map(|&v| num_traits::cast(v).unwrap_or(T::default_nodata()))
            .collect(),
        DecodingResult::I8(buf) => buf
            .iter()
            .map(|&v| num_traits::cast(v).unwrap_or(T::default_nodata()))
            .collect(),
        DecodingResult::I16(buf) => buf
            .iter()
            .map(|&v| num_traits::cast(v).unwrap_or(T::default_nodata()))
            .collect(),
        DecodingResult::I32(buf) => buf
            .iter()
            .map(|&v| num_traits::cast(v).unwrap_or(T::default_nodata()))
            .collect(),
        _ => {
            return Err(Error::UnsupportedDataType(
                "Unsupported TIFF pixel format".to_string(),
            ));
        }
    };

    if data.len() != rows * cols {
        return Err(Error::InvalidDimensions {
            width: cols,
            height: rows,
        });
    }

    let mut raster = Raster::from_vec(data, rows, cols)?;

    // Try to read GeoTIFF tags (ModelTiepointTag + ModelPixelScaleTag)
    if let Ok(transform) = read_geotransform(&mut decoder) {
        raster.set_transform(transform);
    }

    // Try to read CRS from GeoKeyDirectory (tag 34735)
    if let Some(crs) = read_crs(&mut decoder) {
        raster.set_crs(Some(crs));
    }

    // Read GDAL_NODATA tag (42113) — ASCII string with nodata value
    if let Some(nodata_f64) = read_nodata(&mut decoder) {
        if let Some(nd) = num_traits::cast::<f64, T>(nodata_f64) {
            raster.set_nodata(Some(nd));
            // For float types, replace nodata values with NaN so that
            // all algorithms (which check .is_nan()) handle them correctly.
            if T::is_float() {
                let nan_val = T::default_nodata(); // NaN for floats
                for val in raster.data_mut().iter_mut() {
                    if val.is_nodata(Some(nd)) {
                        *val = nan_val;
                    }
                }
            }
        }
    }

    Ok(raster)
}

/// Attempt to read CRS EPSG code from GeoKeyDirectory tag
fn read_crs<R: std::io::Read + std::io::Seek>(decoder: &mut Decoder<R>) -> Option<crate::crs::CRS> {
    let geokeys = decoder.get_tag_u16_vec(Tag::Unknown(34735)).ok()?;
    if geokeys.len() < 4 {
        return None;
    }
    let num_keys = geokeys[3] as usize;
    for i in 0..num_keys {
        let base = 4 + i * 4;
        if base + 3 >= geokeys.len() {
            break;
        }
        let key_id = geokeys[base];
        let value = geokeys[base + 3];
        // ProjectedCSTypeGeoKey (3072) or GeographicTypeGeoKey (2048)
        if (key_id == 3072 || key_id == 2048) && value > 0 {
            return Some(crate::crs::CRS::from_epsg(value as u32));
        }
    }
    None
}

/// Attempt to read GeoTransform from TIFF tags
fn read_geotransform<R: std::io::Read + std::io::Seek>(
    decoder: &mut Decoder<R>,
) -> Result<GeoTransform> {
    // ModelPixelScaleTag = 33550
    // ModelTiepointTag = 33922
    // ModelTransformationTag = 34264 (alternative)

    // Try ModelPixelScaleTag + ModelTiepointTag first
    let scale_tag = Tag::Unknown(33550);
    let tiepoint_tag = Tag::Unknown(33922);

    let scale = decoder
        .get_tag_f64_vec(scale_tag)
        .map_err(|_| Error::Other("No pixel scale tag".into()))?;

    let tiepoint = decoder
        .get_tag_f64_vec(tiepoint_tag)
        .map_err(|_| Error::Other("No tiepoint tag".into()))?;

    if scale.len() >= 2 && tiepoint.len() >= 6 {
        // tiepoint: [I, J, K, X, Y, Z]
        // scale: [ScaleX, ScaleY, ScaleZ]
        let origin_x = tiepoint[3] - tiepoint[0] * scale[0];
        let origin_y = tiepoint[4] + tiepoint[1] * scale[1];
        let pixel_width = scale[0];
        let pixel_height = -scale[1]; // Negative for north-up

        return Ok(GeoTransform::new(
            origin_x,
            origin_y,
            pixel_width,
            pixel_height,
        ));
    }

    Err(Error::Other("Cannot determine geotransform".into()))
}

/// Read GDAL_NODATA tag (42113) — stored as ASCII string, parsed to f64.
fn read_nodata<R: std::io::Read + std::io::Seek>(decoder: &mut Decoder<R>) -> Option<f64> {
    let s = decoder.get_tag_ascii_string(Tag::Unknown(42113)).ok()?;
    s.trim().trim_end_matches('\0').parse::<f64>().ok()
}

/// Write a Raster to a GeoTIFF file
///
/// Native writer with limited GeoTIFF metadata support.
/// Writes as 32-bit float. For full support, enable the `gdal` feature.
pub fn write_geotiff<T, P>(
    raster: &Raster<T>,
    path: P,
    options: Option<GeoTiffOptions>,
) -> Result<()>
where
    T: RasterElement,
    P: AsRef<Path>,
{
    let compress = options
        .as_ref()
        .map(|o| o.compression.to_lowercase() != "none")
        .unwrap_or(false);

    // Write to temp file first, then atomic rename to prevent corrupt partial files
    let final_path = path.as_ref();
    let tmp_path = final_path.with_extension("tmp");
    let file = File::create(&tmp_path)?;
    encode_geotiff(raster, file, compress)?;
    std::fs::rename(&tmp_path, final_path)?;
    Ok(())
}

/// Write a Raster to an in-memory GeoTIFF buffer
///
/// Same as `write_geotiff` but returns a `Vec<u8>` instead of writing to a file.
/// Useful for WASM environments where filesystem access is not available.
pub fn write_geotiff_to_buffer<T>(
    raster: &Raster<T>,
    options: Option<GeoTiffOptions>,
) -> Result<Vec<u8>>
where
    T: RasterElement,
{
    let compress = options
        .as_ref()
        .map(|o| o.compression.to_lowercase() != "none")
        .unwrap_or(false);
    let mut buf = Vec::new();
    encode_geotiff(raster, Cursor::new(&mut buf), compress)?;
    Ok(buf)
}

/// Internal: encode a Raster as GeoTIFF into any `Write + Seek` sink
fn encode_geotiff<T, W>(raster: &Raster<T>, writer: W, compress: bool) -> Result<()>
where
    T: RasterElement,
    W: std::io::Write + std::io::Seek,
{
    let compression = if compress {
        Compression::Deflate(DeflateLevel::Balanced)
    } else {
        Compression::Uncompressed
    };

    let mut encoder = TiffEncoder::new(writer)
        .map_err(|e| Error::Other(format!("TIFF encoder error: {}", e)))?
        .with_compression(compression);

    let (rows, cols) = raster.shape();

    // Convert data to f32
    let data: Vec<f32> = raster
        .data()
        .iter()
        .map(|&v| num_traits::cast(v).unwrap_or(f32::NAN))
        .collect();

    let mut image = encoder
        .new_image::<Gray32Float>(cols as u32, rows as u32)
        .map_err(|e| Error::Other(format!("Cannot create TIFF image: {}", e)))?;

    // Write GeoTIFF tags
    let gt = raster.transform();

    // ModelPixelScaleTag
    let scale = vec![gt.pixel_width, gt.pixel_height.abs(), 0.0];
    image
        .encoder()
        .write_tag(Tag::Unknown(33550), scale.as_slice())
        .map_err(|e| Error::Other(format!("Cannot write scale tag: {}", e)))?;

    // ModelTiepointTag
    let tiepoint = vec![0.0, 0.0, 0.0, gt.origin_x, gt.origin_y, 0.0];
    image
        .encoder()
        .write_tag(Tag::Unknown(33922), tiepoint.as_slice())
        .map_err(|e| Error::Other(format!("Cannot write tiepoint tag: {}", e)))?;

    // GeoKeyDirectoryTag (34735) — embed actual CRS from raster metadata.
    // GeoKey structure: [KeyDirectoryVersion, KeyRevision, MinorRevision, NumberOfKeys,
    //                    KeyID, TIFFTagLocation, Count, Value_Offset, ...]
    let geokeys: Vec<u16> = if let Some(crs) = raster.crs() {
        if let Some(epsg) = crs.epsg() {
            if epsg == 4326 {
                // Geographic CRS (WGS84)
                vec![
                    1,
                    1,
                    0,
                    3, // Version 1.1.0, 3 keys
                    1024,
                    0,
                    1,
                    2, // GTModelTypeGeoKey = ModelTypeGeographic
                    1025,
                    0,
                    1,
                    1, // GTRasterTypeGeoKey = RasterPixelIsArea
                    2048,
                    0,
                    1,
                    epsg as u16, // GeographicTypeGeoKey = EPSG code
                ]
            } else {
                // Projected CRS (e.g., UTM zones EPSG:326xx/327xx)
                vec![
                    1,
                    1,
                    0,
                    3, // Version 1.1.0, 3 keys
                    1024,
                    0,
                    1,
                    1, // GTModelTypeGeoKey = ModelTypeProjected
                    1025,
                    0,
                    1,
                    1, // GTRasterTypeGeoKey = RasterPixelIsArea
                    3072,
                    0,
                    1,
                    epsg as u16, // ProjectedCSTypeGeoKey = EPSG code
                ]
            }
        } else {
            // CRS without EPSG code — write generic projected
            vec![
                1, 1, 0, 2, 1024, 0, 1, 1, // ModelTypeProjected
                1025, 0, 1, 1, // RasterPixelIsArea
            ]
        }
    } else {
        // No CRS — write generic projected (backward compatible)
        vec![1, 1, 0, 2, 1024, 0, 1, 1, 1025, 0, 1, 1]
    };
    image
        .encoder()
        .write_tag(Tag::Unknown(34735), geokeys.as_slice())
        .map_err(|e| Error::Other(format!("Cannot write geokey tag: {}", e)))?;

    // GDAL_NODATA tag (42113) — write as ASCII string
    if let Some(nd) = raster.nodata() {
        if let Some(nd_f64) = nd.to_f64() {
            let nodata_str = if nd_f64.is_nan() {
                "nan\0".to_string()
            } else {
                format!("{}\0", nd_f64)
            };
            image
                .encoder()
                .write_tag(Tag::Unknown(42113), nodata_str.as_bytes())
                .map_err(|e| Error::Other(format!("Cannot write nodata tag: {}", e)))?;
        }
    }

    image
        .write_data(&data)
        .map_err(|e| Error::Other(format!("Cannot write image data: {}", e)))?;

    Ok(())
}

/// Write a stack of single-band rasters as a multi-band GeoTIFF.
///
/// Supports 1, 3 or 4 bands (`Gray32Float`, `RGB32Float`,
/// `RGBA32Float`). All band rasters must share the same shape and
/// geotransform. GeoTIFF metadata (CRS, transform, nodata) is
/// inherited from `bands[0]`. Per-band values are cast to `f32`.
///
/// For arbitrary `N > 4`, enable the `gdal` feature and use
/// `gdal_io::write_geotiff_multiband`.
pub fn write_geotiff_multiband<T, P>(
    bands: &[&Raster<T>],
    path: P,
    options: Option<GeoTiffOptions>,
) -> Result<()>
where
    T: RasterElement,
    P: AsRef<Path>,
{
    if bands.is_empty() {
        return Err(Error::Other("stack needs at least one band".into()));
    }
    let (rows, cols) = bands[0].shape();
    for b in bands.iter().skip(1) {
        if b.shape() != (rows, cols) {
            return Err(Error::Other(
                "stack bands must share shape".into(),
            ));
        }
    }
    let n_bands = bands.len();
    if !matches!(n_bands, 1 | 3 | 4) {
        return Err(Error::Other(format!(
            "native stack supports 1, 3 or 4 bands; got {} (use --features gdal for N>4)",
            n_bands
        )));
    }

    let compress = options
        .as_ref()
        .map(|o| o.compression.to_lowercase() != "none")
        .unwrap_or(false);

    let final_path = path.as_ref();
    let tmp_path = final_path.with_extension("tmp");
    let file = File::create(&tmp_path)?;

    // Build the interleaved (chunky) buffer expected by the tiff
    // crate for pixel-interleaved multi-sample images:
    //   [s0_px0, s1_px0, ..., sK_px0,
    //    s0_px1, s1_px1, ..., sK_px1, ...]
    let n_px = rows * cols;
    let mut interleaved: Vec<f32> = vec![0.0; n_px * n_bands];
    for (b, raster) in bands.iter().enumerate() {
        for (i, &v) in raster.data().iter().enumerate() {
            let f: f32 = num_traits::cast(v).unwrap_or(f32::NAN);
            interleaved[i * n_bands + b] = f;
        }
    }

    match n_bands {
        1 => encode_multiband_image::<Gray32Float, _>(file, bands[0], &interleaved, compress)?,
        3 => encode_multiband_image::<RGB32Float, _>(file, bands[0], &interleaved, compress)?,
        4 => encode_multiband_image::<RGBA32Float, _>(file, bands[0], &interleaved, compress)?,
        _ => unreachable!(),
    }
    std::fs::rename(&tmp_path, final_path)?;
    Ok(())
}

/// Generic multi-band writer parameterised over the tiff
/// `ColorType` so the same GeoTIFF-tag plumbing serves Gray /
/// RGB / RGBA. `meta` provides geotransform, CRS and nodata;
/// `interleaved` is the chunky f32 buffer.
fn encode_multiband_image<CT, W>(
    writer: W,
    meta: &Raster<impl RasterElement>,
    interleaved: &[f32],
    compress: bool,
) -> Result<()>
where
    CT: ColorType<Inner = f32>,
    W: std::io::Write + std::io::Seek,
{
    let compression = if compress {
        Compression::Deflate(DeflateLevel::Balanced)
    } else {
        Compression::Uncompressed
    };
    let mut encoder = TiffEncoder::new(writer)
        .map_err(|e| Error::Other(format!("TIFF encoder error: {}", e)))?
        .with_compression(compression);

    let (rows, cols) = meta.shape();
    let mut image = encoder
        .new_image::<CT>(cols as u32, rows as u32)
        .map_err(|e| Error::Other(format!("Cannot create TIFF image: {}", e)))?;

    let gt = meta.transform();
    let scale = vec![gt.pixel_width, gt.pixel_height.abs(), 0.0];
    image
        .encoder()
        .write_tag(Tag::Unknown(33550), scale.as_slice())
        .map_err(|e| Error::Other(format!("Cannot write scale tag: {}", e)))?;
    let tiepoint = vec![0.0, 0.0, 0.0, gt.origin_x, gt.origin_y, 0.0];
    image
        .encoder()
        .write_tag(Tag::Unknown(33922), tiepoint.as_slice())
        .map_err(|e| Error::Other(format!("Cannot write tiepoint tag: {}", e)))?;

    let geokeys: Vec<u16> = if let Some(crs) = meta.crs() {
        if let Some(epsg) = crs.epsg() {
            if epsg == 4326 {
                vec![1, 1, 0, 3, 1024, 0, 1, 2, 1025, 0, 1, 1, 2048, 0, 1, epsg as u16]
            } else {
                vec![1, 1, 0, 3, 1024, 0, 1, 1, 1025, 0, 1, 1, 3072, 0, 1, epsg as u16]
            }
        } else {
            vec![1, 1, 0, 2, 1024, 0, 1, 1, 1025, 0, 1, 1]
        }
    } else {
        vec![1, 1, 0, 2, 1024, 0, 1, 1, 1025, 0, 1, 1]
    };
    image
        .encoder()
        .write_tag(Tag::Unknown(34735), geokeys.as_slice())
        .map_err(|e| Error::Other(format!("Cannot write geokey tag: {}", e)))?;

    if let Some(nd) = meta.nodata()
        && let Some(nd_f64) = nd.to_f64()
    {
        let nodata_str = if nd_f64.is_nan() {
            "nan\0".to_string()
        } else {
            format!("{}\0", nd_f64)
        };
        image
            .encoder()
            .write_tag(Tag::Unknown(42113), nodata_str.as_bytes())
            .map_err(|e| Error::Other(format!("Cannot write nodata tag: {}", e)))?;
    }

    image
        .write_data(interleaved)
        .map_err(|e| Error::Other(format!("Cannot write image data: {}", e)))?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::raster::Raster;
    use tempfile::TempDir;

    fn ramp_band(rows: usize, cols: usize, base: f64) -> Raster<f64> {
        let mut r = Raster::new(rows, cols);
        r.set_transform(GeoTransform::new(0.0, rows as f64, 1.0, -1.0));
        for row in 0..rows {
            for col in 0..cols {
                r.set(row, col, base + (row + col) as f64).unwrap();
            }
        }
        r
    }

    #[test]
    fn multiband_rgb_roundtrip() {
        // Write three single-band rasters as an RGB stack, read it
        // back, verify per-band values match.
        let r0 = ramp_band(10, 12, 0.0);
        let r1 = ramp_band(10, 12, 100.0);
        let r2 = ramp_band(10, 12, 200.0);
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("rgb.tif");
        write_geotiff_multiband::<f64, _>(&[&r0, &r1, &r2], &path, None).unwrap();

        // Roundtrip read: the native reader returns band 1 only. We
        // verify the file is a valid 3-band TIFF by reopening with
        // the tiff crate directly and inspecting BitsPerSample.
        let file = File::open(&path).unwrap();
        let mut dec = Decoder::new(file).unwrap();
        let bps = dec
            .get_tag(Tag::Unknown(258)) // BitsPerSample
            .unwrap();
        // 3 samples × 32 bits.
        match bps {
            tiff::decoder::ifd::Value::List(list) => {
                assert_eq!(list.len(), 3, "expected 3 samples per pixel");
            }
            _ => panic!("BitsPerSample not a list"),
        }
        let spp = dec.get_tag_u32(Tag::Unknown(277)).unwrap(); // SamplesPerPixel
        assert_eq!(spp, 3);
    }

    #[test]
    fn multiband_rgba_writes_four_samples() {
        let r0 = ramp_band(8, 8, 0.0);
        let r1 = ramp_band(8, 8, 1.0);
        let r2 = ramp_band(8, 8, 2.0);
        let r3 = ramp_band(8, 8, 3.0);
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("rgba.tif");
        write_geotiff_multiband::<f64, _>(&[&r0, &r1, &r2, &r3], &path, None).unwrap();
        let file = File::open(&path).unwrap();
        let mut dec = Decoder::new(file).unwrap();
        let spp = dec.get_tag_u32(Tag::Unknown(277)).unwrap();
        assert_eq!(spp, 4);
    }

    #[test]
    fn multiband_rejects_unsupported_band_count() {
        let r0 = ramp_band(4, 4, 0.0);
        let r1 = ramp_band(4, 4, 1.0);
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("two_bands.tif");
        let err = write_geotiff_multiband::<f64, _>(&[&r0, &r1], &path, None).unwrap_err();
        let msg = format!("{}", err);
        assert!(msg.contains("1, 3 or 4"), "got: {}", msg);
    }

    #[test]
    fn multiband_rejects_mismatched_shapes() {
        let r0 = ramp_band(4, 4, 0.0);
        let r1 = ramp_band(4, 5, 0.0);
        let r2 = ramp_band(4, 4, 0.0);
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("bad.tif");
        let err = write_geotiff_multiband::<f64, _>(&[&r0, &r1, &r2], &path, None).unwrap_err();
        let msg = format!("{}", err);
        assert!(msg.contains("share shape"), "got: {}", msg);
    }

    #[test]
    fn multiband_preserves_crs_and_transform() {
        // `read_geotiff` is single-band only; we inspect the GeoTIFF
        // tags directly with the tiff decoder to verify the multiband
        // writer emits the same scale / tiepoint / geokey payload.
        use crate::crs::CRS;
        let mut r0 = ramp_band(6, 6, 0.0);
        let mut r1 = ramp_band(6, 6, 1.0);
        let mut r2 = ramp_band(6, 6, 2.0);
        // GeoTransform::new(origin_x, origin_y, pixel_width, pixel_height).
        let gt = GeoTransform::new(100000.0, 6300000.0, 10.0, -10.0);
        let crs = CRS::from_epsg(32719);
        for r in [&mut r0, &mut r1, &mut r2] {
            r.set_transform(gt.clone());
            r.set_crs(Some(crs.clone()));
        }
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("crs_check.tif");
        write_geotiff_multiband::<f64, _>(&[&r0, &r1, &r2], &path, None).unwrap();

        let file = File::open(&path).unwrap();
        let mut dec = Decoder::new(file).unwrap();
        // ModelPixelScaleTag (33550) -> [pix_w, pix_h.abs(), 0].
        let scale = dec.get_tag_f64_vec(Tag::Unknown(33550)).unwrap();
        assert!((scale[0] - 10.0).abs() < 1e-9);
        assert!((scale[1] - 10.0).abs() < 1e-9);
        // ModelTiepointTag (33922) -> [0,0,0, ox, oy, 0].
        let tp = dec.get_tag_f64_vec(Tag::Unknown(33922)).unwrap();
        assert!((tp[3] - 100000.0).abs() < 1e-6);
        assert!((tp[4] - 6300000.0).abs() < 1e-6);
        // GeoKeyDirectory (34735) -> embeds EPSG:32719 under ProjectedCSTypeGeoKey (3072).
        let gk = dec.get_tag_u32_vec(Tag::Unknown(34735)).unwrap();
        assert!(
            gk.windows(2).any(|w| w[0] == 3072 && w[1] == 0)
                && gk.contains(&32719),
            "EPSG:32719 missing from GeoKeyDirectory: {:?}",
            gk
        );
    }
}