wbgeotiff 0.1.2

Shared GeoTIFF / BigTIFF / COG read-write engine for Whitebox crates
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
//! Compression and decompression implementations.
//!
//! Supported codecs:
//! - **None** – raw bytes (no-op)
//! - **JPEG** – lossy JPEG (8-bit grayscale/RGB chunks)
//! - **WebP** – lossy WebP (8-bit RGB/RGBA chunks)
//! - **JPEG-XL** – lossy/lossless JPEG-XL (8-bit gray/RGB/RGBA chunks)
//! - **LZW** – via the `weezl` crate (TIFF variant with MSB-first bit order)
//! - **Deflate/ZIP** – via the `flate2` crate
//! - **PackBits** – pure-Rust implementation
//!
//! Each codec exposes `compress(input) -> Result<Vec<u8>>` and
//! `decompress(input, expected_len) -> Result<Vec<u8>>` functions.

#![allow(dead_code)]

use super::error::{GeoTiffError, Result};
use super::tags::Compression;
use std::io::Cursor;

// ── Public dispatch ──────────────────────────────────────────────────────────

/// Compress `input` bytes using the given codec.
pub fn compress(codec: Compression, input: &[u8]) -> Result<Vec<u8>> {
    match codec {
        Compression::None => Ok(input.to_vec()),
        Compression::Lzw => lzw::compress(input),
        Compression::Deflate => deflate::compress(input),
        Compression::PackBits => packbits::compress(input),
        other => Err(GeoTiffError::UnsupportedCompression(other.tag_value())),
    }
}

/// Compress with WebP for one strip/tile chunk.
pub fn compress_webp(
    input: &[u8],
    width: u32,
    height: u32,
    samples_per_pixel: usize,
    quality: f32,
) -> Result<Vec<u8>> {
    use webp_rust::{encode_lossless, encode_lossy, ImageBuffer};

    let encoded = match samples_per_pixel {
        3 => {
            let mut rgba = Vec::with_capacity(input.len() / 3 * 4);
            for px in input.chunks_exact(3) {
                rgba.extend_from_slice(px);
                rgba.push(255);
            }
            let image = ImageBuffer {
                width: width as usize,
                height: height as usize,
                rgba,
            };
            encode_lossy(&image, 0, quality.clamp(0.0, 100.0).round() as usize, None).map_err(
                |e| GeoTiffError::CompressionError {
                    codec: "WebP",
                    message: format!("{e}"),
                },
            )?
        }
        4 => {
            let image = ImageBuffer {
                width: width as usize,
                height: height as usize,
                rgba: input.to_vec(),
            };
            let has_alpha = input.chunks_exact(4).any(|px| px[3] != 255);
            if has_alpha {
                encode_lossless(&image, 2, None).map_err(|e| GeoTiffError::CompressionError {
                    codec: "WebP",
                    message: format!("{e}"),
                })?
            } else {
                encode_lossy(&image, 0, quality.clamp(0.0, 100.0).round() as usize, None)
                    .map_err(|e| GeoTiffError::CompressionError {
                        codec: "WebP",
                        message: format!("{e}"),
                    })?
            }
        }
        _ => {
            return Err(GeoTiffError::CompressionError {
                codec: "WebP",
                message: format!("unsupported samples_per_pixel={}, expected 3 (RGB) or 4 (RGBA)", samples_per_pixel),
            })
        }
    };

    Ok(encoded)
}

/// Decompress one WebP strip/tile chunk.
pub fn decompress_webp(input: &[u8], expected_len: usize) -> Result<Vec<u8>> {
    let img = webp_rust::decode(input).map_err(|e| GeoTiffError::CompressionError {
        codec: "WebP",
        message: format!("{e}"),
    })?;

    let decoded = img.rgba;
    if expected_len == 0 {
        return Ok(decoded);
    }

    if decoded.len() == expected_len {
        return Ok(decoded);
    }

    let pixel_count = img.width * img.height;
    if pixel_count > 0 && decoded.len() == pixel_count * 3 {
        if expected_len == pixel_count * 3 {
            return Ok(decoded);
        }
        if expected_len == pixel_count * 4 {
            let mut out = Vec::with_capacity(expected_len);
            for px in decoded.chunks_exact(3) {
                out.extend_from_slice(px);
                out.push(255);
            }
            return Ok(out);
        }
        if expected_len == pixel_count {
            let mut out = Vec::with_capacity(expected_len);
            for px in decoded.chunks_exact(3) {
                out.push(px[0]);
            }
            return Ok(out);
        }
    }

    if pixel_count > 0 && decoded.len() == pixel_count * 4 {
        if expected_len == pixel_count * 4 {
            return Ok(decoded);
        }
        if expected_len == pixel_count * 3 {
            let mut out = Vec::with_capacity(expected_len);
            for px in decoded.chunks_exact(4) {
                out.extend_from_slice(&px[..3]);
            }
            return Ok(out);
        }
        if expected_len == pixel_count {
            let mut out = Vec::with_capacity(expected_len);
            for px in decoded.chunks_exact(4) {
                out.push(px[0]);
            }
            return Ok(out);
        }
    }

    Err(GeoTiffError::CompressionError {
        codec: "WebP",
        message: format!(
            "decoded length mismatch: got {}, expected {}",
            decoded.len(),
            expected_len
        ),
    })
}

/// Compress with JPEG for one strip/tile chunk.
pub fn compress_jpeg(
    input: &[u8],
    width: u16,
    height: u16,
    samples_per_pixel: usize,
    quality: u8,
) -> Result<Vec<u8>> {
    use jpeg_encoder::{ColorType, Encoder};

    let color = match samples_per_pixel {
        1 => ColorType::Luma,
        3 => ColorType::Rgb,
        _ => {
            return Err(GeoTiffError::CompressionError {
                codec: "JPEG",
                message: format!("unsupported samples_per_pixel={}, expected 1 or 3", samples_per_pixel),
            })
        }
    };

    let mut out = Vec::new();
    let enc = Encoder::new(&mut out, quality);
    enc.encode(input, width, height, color)
        .map_err(|e| GeoTiffError::CompressionError {
            codec: "JPEG",
            message: e.to_string(),
        })?;
    Ok(out)
}

/// Compress with JPEG-XL for one strip/tile chunk.
pub fn compress_jpegxl(
    input: &[u8],
    width: u32,
    height: u32,
    samples_per_pixel: usize,
    quality: u8,
) -> Result<Vec<u8>> {
    use zune_core::bit_depth::BitDepth;
    use zune_core::colorspace::ColorSpace;
    use zune_core::options::EncoderOptions;
    use zune_jpegxl::JxlSimpleEncoder;

    let pixel_count = (width as usize)
        .checked_mul(height as usize)
        .ok_or_else(|| GeoTiffError::CompressionError {
            codec: "JPEG-XL",
            message: "image dimensions overflow".into(),
        })?;

    let (color_space, expected_len) = match samples_per_pixel {
        1 => (ColorSpace::Luma, pixel_count),
        3 => (ColorSpace::RGB, pixel_count * 3),
        4 => (ColorSpace::RGBA, pixel_count * 4),
        _ => {
            return Err(GeoTiffError::CompressionError {
                codec: "JPEG-XL",
                message: format!(
                    "unsupported samples_per_pixel={}, expected 1, 3, or 4",
                    samples_per_pixel
                ),
            })
        }
    };

    if input.len() != expected_len {
        return Err(GeoTiffError::CompressionError {
            codec: "JPEG-XL",
            message: format!("invalid input length {}, expected {}", input.len(), expected_len),
        });
    }

    let effort = ((quality as u16 * 9 + 99) / 100) as u8;
    let options = EncoderOptions::new(width as usize, height as usize, color_space, BitDepth::Eight)
        .set_quality(quality.clamp(1, 100))
        .set_effort(effort.clamp(1, 9));
    let encoder = JxlSimpleEncoder::new(input, options);
    let mut out = Vec::new();
    encoder
        .encode(&mut out)
        .map_err(|e| GeoTiffError::CompressionError {
            codec: "JPEG-XL",
            message: format!("{e:?}"),
        })?;
    Ok(out)
}

/// Decompress one JPEG-XL strip/tile chunk.
pub fn decompress_jpegxl(input: &[u8], expected_len: usize) -> Result<Vec<u8>> {
    use jxl_oxide::JxlImage;

    let image = JxlImage::builder()
        .read(Cursor::new(input))
        .map_err(|e| GeoTiffError::CompressionError {
            codec: "JPEG-XL",
            message: format!("{e:?}"),
        })?;

    let render = image.render_frame(0).map_err(|e| GeoTiffError::CompressionError {
        codec: "JPEG-XL",
        message: format!("{e:?}"),
    })?;
    let fb = render.image_all_channels();
    let pixel_count = fb.width().saturating_mul(fb.height());
    let channels = fb.channels();
    let src = fb.buf();

    if pixel_count == 0 || src.len() != pixel_count * channels {
        return Err(GeoTiffError::CompressionError {
            codec: "JPEG-XL",
            message: format!(
                "decoded framebuffer mismatch: samples={}, expected {}",
                src.len(),
                pixel_count * channels
            ),
        });
    }

    let mut rgba = Vec::with_capacity(pixel_count * 4);
    for i in 0..pixel_count {
        let base = i * channels;
        let c0 = src[base].round().clamp(0.0, 255.0) as u8;
        let c1 = if channels > 1 {
            src[base + 1].round().clamp(0.0, 255.0) as u8
        } else {
            c0
        };
        let c2 = if channels > 2 {
            src[base + 2].round().clamp(0.0, 255.0) as u8
        } else {
            c0
        };
        let a = if channels > 3 {
            src[base + 3].round().clamp(0.0, 255.0) as u8
        } else {
            255
        };
        rgba.extend_from_slice(&[c0, c1, c2, a]);
    }

    if expected_len == 0 || expected_len == rgba.len() {
        return Ok(rgba);
    }

    if expected_len == pixel_count * 3 {
        let mut out = Vec::with_capacity(expected_len);
        for px in rgba.chunks_exact(4) {
            out.extend_from_slice(&px[..3]);
        }
        return Ok(out);
    }

    if expected_len == pixel_count {
        let mut out = Vec::with_capacity(expected_len);
        for px in rgba.chunks_exact(4) {
            out.push(px[0]);
        }
        return Ok(out);
    }

    Err(GeoTiffError::CompressionError {
        codec: "JPEG-XL",
        message: format!(
            "decoded length mismatch: got {}, expected {}",
            rgba.len(),
            expected_len
        ),
    })
}

/// Decompress one JPEG strip/tile chunk.
pub fn decompress_jpeg(input: &[u8], expected_len: usize) -> Result<Vec<u8>> {
    use jpeg_decoder::Decoder;

    let mut decoder = Decoder::new(Cursor::new(input));
    let mut output = decoder
        .decode()
        .map_err(|e| GeoTiffError::CompressionError {
            codec: "JPEG",
            message: e.to_string(),
        })?;

    if expected_len > 0 {
        if output.len() < expected_len {
            return Err(GeoTiffError::CompressionError {
                codec: "JPEG",
                message: format!(
                    "decoded chunk shorter than expected: {} < {}",
                    output.len(),
                    expected_len
                ),
            });
        }
        if output.len() > expected_len {
            output.truncate(expected_len);
        }
    }

    Ok(output)
}

/// Decompress `input` bytes using the given codec.
///
/// `expected_len` is used as a hint for buffer pre-allocation and, for
/// PackBits, as a stopping criterion.
pub fn decompress(codec: Compression, input: &[u8], expected_len: usize) -> Result<Vec<u8>> {
    match codec {
        Compression::None => Ok(input.to_vec()),
        Compression::Lzw => lzw::decompress(input, expected_len),
        Compression::Deflate => deflate::decompress(input, expected_len),
        Compression::PackBits => packbits::decompress(input, expected_len),
        Compression::Jpeg | Compression::OldJpeg => decompress_jpeg(input, expected_len),
        Compression::WebP => decompress_webp(input, expected_len),
        Compression::JpegXl => decompress_jpegxl(input, expected_len),
        other => Err(GeoTiffError::UnsupportedCompression(other.tag_value())),
    }
}

// ── LZW ──────────────────────────────────────────────────────────────────────

mod lzw {
    use super::*;
    use weezl::BitOrder;

    /// TIFF uses MSB-first bit order and a 8-bit minimum code size.
    const BIT_ORDER: BitOrder = BitOrder::Msb;
    const MIN_CODE_SIZE: u8 = 8;

    /// Compress bytes with TIFF PackBits run-length encoding.
    pub fn compress(input: &[u8]) -> Result<Vec<u8>> {
        let mut encoder = weezl::encode::Encoder::with_tiff_size_switch(BIT_ORDER, MIN_CODE_SIZE);

        encoder.encode(input).map_err(|e| GeoTiffError::CompressionError {
                codec: "LZW",
                message: e.to_string(),
            })
    }

    /// Decompress PackBits bytes, stopping when `expected_len` output bytes are produced.
    pub fn decompress(input: &[u8], expected_len: usize) -> Result<Vec<u8>> {
        let mut decoder = weezl::decode::Decoder::with_tiff_size_switch(BIT_ORDER, MIN_CODE_SIZE);

        let mut output = decoder.decode(input).map_err(|e| GeoTiffError::CompressionError {
                codec: "LZW",
                message: e.to_string(),
            })?;
        if expected_len > 0 && output.len() > expected_len {
            output.truncate(expected_len);
        }
        Ok(output)
    }
}

// ── Deflate ───────────────────────────────────────────────────────────────────

mod deflate {
    use super::*;
    use flate2::{read::ZlibDecoder, write::ZlibEncoder, Compression as FlateLevel};
    use std::io::{Read, Write};

    pub fn compress(input: &[u8]) -> Result<Vec<u8>> {
        let mut encoder = ZlibEncoder::new(Vec::new(), FlateLevel::default());
        encoder.write_all(input).map_err(|e| GeoTiffError::CompressionError {
            codec: "Deflate",
            message: e.to_string(),
        })?;
        encoder.finish().map_err(|e| GeoTiffError::CompressionError {
            codec: "Deflate",
            message: e.to_string(),
        })
    }

    pub fn decompress(input: &[u8], expected_len: usize) -> Result<Vec<u8>> {
        let mut decoder = ZlibDecoder::new(input);
        let mut output = Vec::with_capacity(expected_len);
        decoder.read_to_end(&mut output).map_err(|e| GeoTiffError::CompressionError {
            codec: "Deflate",
            message: e.to_string(),
        })?;
        Ok(output)
    }
}

// ── PackBits ──────────────────────────────────────────────────────────────────

pub mod packbits {
    //! Pure-Rust PackBits (Apple/TIFF run-length encoding) codec.
    //!
    //! Format:
    //! - `n` in `[0, 127]`  → copy the next `n + 1` literal bytes.
    //! - `n` in `[-127, -1]` → repeat the next byte `1 - n` times.
    //! - `n == -128 (0x80)` → no-op (skip).

    use super::*;

    /// Compress a byte slice using PackBits run-length encoding.
    pub fn compress(input: &[u8]) -> Result<Vec<u8>> {
        let mut output = Vec::with_capacity(input.len() + input.len() / 128 + 1);
        let mut i = 0;

        while i < input.len() {
            // Check for a run
            let run_len = {
                let mut len = 1usize;
                while len < 128 && i + len < input.len() && input[i + len] == input[i] {
                    len += 1;
                }
                len
            };

            if run_len >= 2 {
                // Encode run
                output.push((1i8.wrapping_sub(run_len as i8)) as u8);
                output.push(input[i]);
                i += run_len;
            } else {
                // Gather literal bytes (stop before a run of ≥ 2)
                let lit_start = i;
                i += 1;
                while i < input.len() && i - lit_start < 128 {
                    let run = {
                        let mut len = 1usize;
                        while len < 3 && i + len < input.len() && input[i + len] == input[i] {
                            len += 1;
                        }
                        len
                    };
                    if run >= 2 {
                        break;
                    }
                    i += 1;
                }
                let lit_bytes = &input[lit_start..i];
                output.push((lit_bytes.len() - 1) as u8);
                output.extend_from_slice(lit_bytes);
            }
        }

        Ok(output)
    }

    /// Decompress PackBits-encoded bytes, using `expected_len` as output-size bound.
    pub fn decompress(input: &[u8], expected_len: usize) -> Result<Vec<u8>> {
        let mut output = Vec::with_capacity(expected_len);
        let mut i = 0;

        while i < input.len() && output.len() < expected_len {
            let header = input[i] as i8;
            i += 1;

            if header == -128 {
                // No-op
                continue;
            } else if header >= 0 {
                // Literal run: copy (header + 1) bytes
                let count = header as usize + 1;
                if i + count > input.len() {
                    return Err(GeoTiffError::CompressionError {
                        codec: "PackBits",
                        message: format!(
                            "Literal run extends beyond input (need {} bytes at offset {})",
                            count, i
                        ),
                    });
                }
                output.extend_from_slice(&input[i..i + count]);
                i += count;
            } else {
                // Replicate run: repeat next byte (1 - header) times
                let count = (1i32 - header as i32) as usize;
                if i >= input.len() {
                    return Err(GeoTiffError::CompressionError {
                        codec: "PackBits",
                        message: "Replicate run at end of input".into(),
                    });
                }
                let byte = input[i];
                i += 1;
                for _ in 0..count {
                    output.push(byte);
                }
            }
        }

        Ok(output)
    }

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

        #[test]
        fn roundtrip_literal() {
            let data: Vec<u8> = (0..200u8).collect();
            let compressed = compress(&data).unwrap();
            let decompressed = decompress(&compressed, data.len()).unwrap();
            assert_eq!(data, decompressed);
        }

        #[test]
        fn roundtrip_run() {
            let data = vec![0xAAu8; 256];
            let compressed = compress(&data).unwrap();
            // A run of 256 should compress to ~4 bytes
            assert!(compressed.len() < 20, "compressed len = {}", compressed.len());
            let decompressed = decompress(&compressed, data.len()).unwrap();
            assert_eq!(data, decompressed);
        }

        #[test]
        fn roundtrip_mixed() {
            let mut data = vec![42u8; 50];
            data.extend_from_slice(b"Hello, World!");
            data.extend(vec![7u8; 100]);
            let compressed = compress(&data).unwrap();
            let decompressed = decompress(&compressed, data.len()).unwrap();
            assert_eq!(data, decompressed);
        }
    }
}

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

    fn test_roundtrip(codec: Compression, data: &[u8]) {
        let compressed = compress(codec, data).unwrap();
        let decompressed = decompress(codec, &compressed, data.len()).unwrap();
        assert_eq!(data, decompressed.as_slice(), "roundtrip failed for {:?}", codec);
    }

    #[test]
    fn none_roundtrip() {
        test_roundtrip(Compression::None, b"Hello, GeoTIFF!");
    }

    #[test]
    fn packbits_roundtrip() {
        let data: Vec<u8> = (0..=255u8).cycle().take(1024).collect();
        test_roundtrip(Compression::PackBits, &data);
    }

    #[test]
    fn lzw_roundtrip() {
        let data: Vec<u8> = (0..=255u8).cycle().take(4096).collect();
        test_roundtrip(Compression::Lzw, &data);
    }

    #[test]
    fn deflate_roundtrip() {
        let data: Vec<u8> = (0..=255u8).cycle().take(4096).collect();
        test_roundtrip(Compression::Deflate, &data);
    }
}