Skip to main content

lerc/
lib.rs

1//! Pure Rust implementation of the LERC (Limited Error Raster Compression) format.
2//!
3//! Supports encoding and decoding of raster images with configurable lossy or lossless
4//! compression. Compatible with ESRI's LERC2 format specification.
5
6#![cfg_attr(not(feature = "std"), no_std)]
7#![allow(
8    clippy::cast_possible_truncation,
9    clippy::cast_possible_wrap,
10    clippy::cast_sign_loss,
11    clippy::cast_precision_loss,
12    clippy::cast_lossless
13)]
14
15extern crate alloc;
16
17/// Error types for LERC encoding and decoding.
18pub mod error;
19/// Pixel data types and the `Sample` trait for type-safe encoding/decoding.
20pub mod types;
21
22/// Validity bitmask for tracking valid/invalid pixels.
23pub mod bitmask;
24pub(crate) mod bitstuffer;
25/// Fletcher-32 checksum used by the LERC2 format.
26#[allow(dead_code)]
27pub mod checksum;
28#[allow(dead_code)]
29pub(crate) mod header;
30#[allow(dead_code)]
31pub(crate) mod huffman;
32pub(crate) mod rle;
33
34pub(crate) mod decode;
35pub(crate) mod encode;
36#[allow(dead_code)]
37pub(crate) mod fpl;
38pub(crate) mod lerc1;
39#[allow(dead_code)]
40pub(crate) mod tiles;
41
42pub use error::{LercError, Result};
43pub use types::{DataType, Sample};
44
45use alloc::vec;
46use alloc::vec::Vec;
47
48use bitmask::BitMask;
49
50/// Controls the precision/error tolerance for LERC encoding.
51///
52/// `Lossless` preserves exact values. `Tolerance(x)` allows decoded values
53/// to differ from originals by at most +/-x.
54#[derive(Debug, Clone, Copy, PartialEq, Default)]
55pub enum Precision<T> {
56    /// Lossless compression. Exact round-trip for all pixel values.
57    #[default]
58    Lossless,
59    /// Lossy compression. Decoded values are within the given tolerance of originals.
60    Tolerance(T),
61}
62
63/// Metadata returned from a decode-into operation (no owned pixel data).
64#[derive(Debug, Clone)]
65pub struct DecodeResult {
66    /// Image width in pixels.
67    pub width: u32,
68    /// Image height in pixels.
69    pub height: u32,
70    /// Number of values per pixel (depth slices).
71    pub depth: u32,
72    /// Number of bands in the image.
73    pub bands: u32,
74    /// Pixel data type of the decoded blob.
75    pub data_type: DataType,
76    /// Per-band validity masks indicating which pixels are valid.
77    pub valid_masks: Vec<BitMask>,
78    /// NoData sentinel value, if the blob uses NoData encoding.
79    pub no_data_value: Option<f64>,
80}
81
82/// Header metadata extracted from a LERC blob without decoding pixel data.
83#[derive(Debug, Clone, Default)]
84pub struct LercInfo {
85    /// LERC format version number.
86    pub version: i32,
87    /// Image width in pixels.
88    pub width: u32,
89    /// Image height in pixels.
90    pub height: u32,
91    /// Number of values per pixel (depth slices).
92    pub depth: u32,
93    /// Number of bands in the image.
94    pub bands: u32,
95    /// Pixel data type stored in the blob.
96    pub data_type: DataType,
97    /// Number of valid (non-masked) pixels.
98    pub valid_pixels: u32,
99    /// Maximum error tolerance used during encoding.
100    pub tolerance: f64,
101    /// Minimum pixel value across all valid pixels.
102    pub min_value: f64,
103    /// Maximum pixel value across all valid pixels.
104    pub max_value: f64,
105    /// Total size of the LERC blob in bytes.
106    pub blob_size: u32,
107    /// The original NoData value, if the blob uses NoData encoding (v6+, depth > 1).
108    pub no_data_value: Option<f64>,
109}
110
111/// A decoded raster image with pixel data and validity masks.
112#[derive(Debug, Clone)]
113pub struct Image {
114    /// Image width in pixels.
115    pub width: u32,
116    /// Image height in pixels.
117    pub height: u32,
118    /// Number of values per pixel (depth slices).
119    pub depth: u32,
120    /// Number of bands in the image.
121    pub bands: u32,
122    /// Pixel data type.
123    pub data_type: DataType,
124    /// Per-band validity masks indicating which pixels are valid.
125    pub valid_masks: Vec<BitMask>,
126    /// Pixel sample data stored as a typed vector.
127    pub data: SampleData,
128    /// The original NoData value, if any. When set during encoding with depth > 1,
129    /// pixels matching this value in invalid depth slices are encoded with a sentinel.
130    /// On decode, the sentinel is remapped back to this value.
131    pub no_data_value: Option<f64>,
132}
133
134impl Default for Image {
135    fn default() -> Self {
136        Self {
137            width: 0,
138            height: 0,
139            depth: 1,
140            bands: 1,
141            data_type: DataType::Byte,
142            valid_masks: Vec::new(),
143            data: SampleData::U8(Vec::new()),
144            no_data_value: None,
145        }
146    }
147}
148
149/// Type-erased pixel data container, one variant per supported data type.
150#[derive(Debug, Clone)]
151pub enum SampleData {
152    /// Signed 8-bit integer pixel data.
153    I8(Vec<i8>),
154    /// Unsigned 8-bit integer pixel data.
155    U8(Vec<u8>),
156    /// Signed 16-bit integer pixel data.
157    I16(Vec<i16>),
158    /// Unsigned 16-bit integer pixel data.
159    U16(Vec<u16>),
160    /// Signed 32-bit integer pixel data.
161    I32(Vec<i32>),
162    /// Unsigned 32-bit integer pixel data.
163    U32(Vec<u32>),
164    /// 32-bit floating-point pixel data.
165    F32(Vec<f32>),
166    /// 64-bit floating-point pixel data.
167    F64(Vec<f64>),
168}
169
170/// Read header metadata from a LERC blob without decoding pixel data.
171pub fn decode_info(data: &[u8]) -> Result<LercInfo> {
172    decode::decode_info(data)
173}
174
175/// Decode a LERC blob, returning the image with pixel data and validity masks.
176pub fn decode(data: &[u8]) -> Result<Image> {
177    decode::decode(data)
178}
179
180/// Encode an image into a LERC blob with the given precision.
181///
182/// This entry point clones the image's pixel buffer when called via the
183/// owning `Image` path. To avoid that clone, see [`encode_borrowed`], which
184/// takes a borrowed `&[T]` and image-shape parameters directly.
185pub fn encode(image: &Image, precision: Precision<f64>) -> Result<Vec<u8>> {
186    let max_z_error = match precision {
187        Precision::Lossless => {
188            if image.data_type.is_integer() {
189                0.5
190            } else {
191                0.0
192            }
193        }
194        Precision::Tolerance(val) => val,
195    };
196    encode::encode(image, max_z_error)
197}
198
199/// Zero-copy multi-band encode entry point.
200///
201/// Encodes a raster image directly from a borrowed pixel slice, avoiding the
202/// buffer clone forced by the [`Image`]-based [`encode`] API. The pixel type
203/// `T` determines the LERC data type automatically via [`Sample`]; tolerances
204/// are expressed in `f64` regardless of `T` to keep the API boundary uniform.
205///
206/// # Data layout
207///
208/// `data` is band-major: outermost is `band`, then row-major within each band,
209/// then `depth` slices interleaved per pixel. Concretely, the value for band
210/// `b`, row `r`, column `c`, depth `d` is at index
211/// `b * (width * height * depth) + (r * width + c) * depth + d`.
212///
213/// `data.len()` must equal `width * height * depth * bands`.
214///
215/// # Validity masks
216///
217/// `masks.len()` must equal `bands`, with one [`BitMask`] per band (each
218/// having `num_pixels() == width * height`). For fully valid bands, pass
219/// [`BitMask::all_valid(width as usize * height as usize)`](BitMask::all_valid).
220///
221/// # Errors
222///
223/// Returns [`LercError::InvalidData`] if the data length, the number of
224/// masks, or any mask's pixel count does not match the declared shape.
225///
226/// # Examples
227///
228/// ```
229/// use lerc::{Precision, encode_borrowed};
230/// use lerc::bitmask::BitMask;
231///
232/// let width = 4u32;
233/// let height = 3u32;
234/// let pixels: Vec<f32> = (0..12).map(|i| i as f32).collect();
235/// let masks = [BitMask::all_valid((width * height) as usize)];
236/// let blob = encode_borrowed::<f32>(
237///     width, height, 1, 1,
238///     &pixels,
239///     &masks,
240///     None,
241///     Precision::Lossless,
242/// ).expect("encode failed");
243/// assert!(!blob.is_empty());
244/// ```
245#[allow(clippy::too_many_arguments)]
246pub fn encode_borrowed<T: Sample>(
247    width: u32,
248    height: u32,
249    depth: u32,
250    bands: u32,
251    data: &[T],
252    masks: &[BitMask],
253    no_data_value: Option<f64>,
254    precision: Precision<f64>,
255) -> Result<Vec<u8>> {
256    let pixels_per_band = (width as usize) * (height as usize);
257    let expected = pixels_per_band * (depth as usize) * (bands as usize);
258    if data.len() != expected {
259        return Err(LercError::InvalidData(alloc::format!(
260            "data length {} does not match width*height*depth*bands {expected}",
261            data.len()
262        )));
263    }
264    if masks.len() != bands as usize {
265        return Err(LercError::InvalidData(alloc::format!(
266            "masks length {} does not match bands {}",
267            masks.len(),
268            bands
269        )));
270    }
271    for (i, mask) in masks.iter().enumerate() {
272        if mask.num_pixels() != pixels_per_band {
273            return Err(LercError::InvalidData(alloc::format!(
274                "mask[{i}] pixel count {} does not match width*height {pixels_per_band}",
275                mask.num_pixels()
276            )));
277        }
278    }
279    let max_z_error: f64 = match precision {
280        Precision::Lossless => {
281            if T::is_integer() {
282                0.5
283            } else {
284                0.0
285            }
286        }
287        Precision::Tolerance(val) => val,
288    };
289    encode::encode_borrowed_typed(
290        width,
291        height,
292        depth,
293        bands,
294        data,
295        masks,
296        no_data_value,
297        max_z_error,
298    )
299}
300
301// ---------------------------------------------------------------------------
302// Typed convenience encode/decode helpers
303// ---------------------------------------------------------------------------
304
305/// Encode a single-band image with all pixels valid.
306///
307/// The pixel type `T` determines the LERC data type automatically via `Sample`.
308/// Returns an error if `data.len() != width * height`.
309///
310/// This helper internally clones `data` into an owned `Image`. For zero-copy
311/// encoding, including multi-band layouts, see [`encode_borrowed`].
312pub fn encode_slice<T: Sample>(
313    width: u32,
314    height: u32,
315    data: &[T],
316    precision: Precision<T>,
317) -> Result<Vec<u8>> {
318    let expected = (width as usize) * (height as usize);
319    if data.len() != expected {
320        return Err(LercError::InvalidData(alloc::format!(
321            "data length {} does not match width*height {expected}",
322            data.len()
323        )));
324    }
325    let max_z_error: f64 = match precision {
326        Precision::Lossless => {
327            if T::is_integer() {
328                0.5
329            } else {
330                0.0
331            }
332        }
333        Precision::Tolerance(val) => val.to_f64(),
334    };
335    let image = Image {
336        width,
337        height,
338        depth: 1,
339        bands: 1,
340        data_type: T::DATA_TYPE,
341        valid_masks: vec![BitMask::all_valid(expected)],
342        data: T::into_lerc_data(data.to_vec()),
343        no_data_value: None,
344    };
345    encode::encode(&image, max_z_error)
346}
347
348/// Encode a single-band image with a validity mask.
349///
350/// The pixel type `T` determines the LERC data type automatically via `Sample`.
351/// Returns an error if `data.len() != width * height` or if the mask size does not match.
352///
353/// This helper internally clones `data` into an owned `Image`. For zero-copy
354/// encoding, including multi-band layouts, see [`encode_borrowed`].
355pub fn encode_slice_masked<T: Sample>(
356    width: u32,
357    height: u32,
358    data: &[T],
359    mask: &BitMask,
360    precision: Precision<T>,
361) -> Result<Vec<u8>> {
362    let expected = (width as usize) * (height as usize);
363    if data.len() != expected {
364        return Err(LercError::InvalidData(alloc::format!(
365            "data length {} does not match width*height {expected}",
366            data.len()
367        )));
368    }
369    if mask.num_pixels() != expected {
370        return Err(LercError::InvalidData(alloc::format!(
371            "mask pixel count {} does not match width*height {expected}",
372            mask.num_pixels()
373        )));
374    }
375    let max_z_error: f64 = match precision {
376        Precision::Lossless => {
377            if T::is_integer() {
378                0.5
379            } else {
380                0.0
381            }
382        }
383        Precision::Tolerance(val) => val.to_f64(),
384    };
385    let image = Image {
386        width,
387        height,
388        depth: 1,
389        bands: 1,
390        data_type: T::DATA_TYPE,
391        valid_masks: vec![mask.clone()],
392        data: T::into_lerc_data(data.to_vec()),
393        no_data_value: None,
394    };
395    encode::encode(&image, max_z_error)
396}
397
398/// Decode a single-band, single-depth LERC blob, returning typed pixel data,
399/// the validity mask, width, and height.
400///
401/// The pixel type `T` must match the blob's data type. Returns an error on type
402/// mismatch or if the blob contains multiple bands or depths (use [`decode`] for
403/// multi-band/multi-depth blobs to get full shape and per-band masks).
404pub fn decode_slice<T: Sample>(blob: &[u8]) -> Result<(Vec<T>, BitMask, u32, u32)> {
405    let image = decode::decode(blob)?;
406    if image.bands > 1 {
407        return Err(LercError::InvalidData(alloc::format!(
408            "decode_slice requires single-band data, got {} bands (use decode() instead)",
409            image.bands
410        )));
411    }
412    if image.depth > 1 {
413        return Err(LercError::InvalidData(alloc::format!(
414            "decode_slice requires single-depth data, got depth={} (use decode() instead)",
415            image.depth
416        )));
417    }
418    let w = image.width;
419    let h = image.height;
420    let pixels = T::try_from_lerc_data(image.data).map_err(|_| {
421        LercError::InvalidData(alloc::format!(
422            "expected {:?} data but blob contains {:?}",
423            T::DATA_TYPE,
424            image.data_type
425        ))
426    })?;
427    let mask = image
428        .valid_masks
429        .into_iter()
430        .next()
431        .unwrap_or_else(|| BitMask::all_valid((w as usize) * (h as usize)));
432    Ok((pixels, mask, w, h))
433}
434
435// ---------------------------------------------------------------------------
436// Typed accessor methods on Image
437// ---------------------------------------------------------------------------
438
439impl Image {
440    /// Try to borrow the pixel data as `&[T]`.
441    ///
442    /// Returns `None` if the image's data type does not match `T`.
443    pub fn as_typed<T: Sample>(&self) -> Option<&[T]> {
444        T::try_ref_lerc_data(&self.data)
445    }
446
447    /// Return the validity mask for the first band, or `None` if no masks are present.
448    pub fn mask(&self) -> Option<&BitMask> {
449        self.valid_masks.first()
450    }
451
452    /// Get the pixel value at `(row, col)` for single-band, single-depth images.
453    ///
454    /// Returns `None` if the data type does not match `T`, if `bands > 1` or
455    /// `depth > 1`, or if the coordinates are out of bounds.
456    pub fn pixel<T: Sample>(&self, row: u32, col: u32) -> Option<T> {
457        if self.bands != 1 || self.depth != 1 {
458            return None;
459        }
460        if row >= self.height || col >= self.width {
461            return None;
462        }
463        let data = self.as_typed::<T>()?;
464        let idx = row as usize * self.width as usize + col as usize;
465        Some(data[idx])
466    }
467
468    /// Iterate over valid pixels as `(row, col, value)` tuples.
469    ///
470    /// Only works for single-band, single-depth images. Returns `None` if the data
471    /// type does not match `T` or if `bands > 1` or `depth > 1`.
472    /// The iterator respects the validity mask, skipping invalid pixels.
473    pub fn valid_pixels<'a, T: Sample + 'a>(
474        &'a self,
475    ) -> Option<impl Iterator<Item = (u32, u32, T)> + 'a> {
476        if self.bands != 1 || self.depth != 1 {
477            return None;
478        }
479        let data = self.as_typed::<T>()?;
480        let width = self.width;
481        let mask = self.valid_masks.first();
482        Some(data.iter().enumerate().filter_map(move |(idx, &val)| {
483            let is_valid = match mask {
484                Some(m) => m.is_valid(idx),
485                None => true,
486            };
487            if is_valid {
488                let row = (idx / width as usize) as u32;
489                let col = (idx % width as usize) as u32;
490                Some((row, col, val))
491            } else {
492                None
493            }
494        }))
495    }
496
497    /// Get dimensions as `(width, height)`.
498    pub fn dimensions(&self) -> (u32, u32) {
499        (self.width, self.height)
500    }
501
502    /// Total number of pixels (`width * height`).
503    pub fn num_pixels(&self) -> usize {
504        self.width as usize * self.height as usize
505    }
506
507    /// Check if all pixels in the first band are valid.
508    ///
509    /// Returns `true` if there is no mask (all pixels are implicitly valid),
510    /// if the first band's mask is [`BitMask::AllValid`] (O(1)), or if an
511    /// explicit mask happens to have every bit set (O(n) popcount fallback).
512    pub fn all_valid(&self) -> bool {
513        match self.valid_masks.first() {
514            Some(m) => m.is_all_valid(),
515            None => true,
516        }
517    }
518
519    /// Create a single-band, all-valid `Image` from a typed pixel vector
520    /// and dimensions.
521    ///
522    /// Returns an error if `data.len() != width * height`.
523    pub fn from_pixels<T: Sample>(width: u32, height: u32, data: Vec<T>) -> Result<Self> {
524        let expected = width as usize * height as usize;
525        if data.len() != expected {
526            return Err(LercError::InvalidData(alloc::format!(
527                "data length {} does not match width*height {expected}",
528                data.len()
529            )));
530        }
531        Ok(Self {
532            width,
533            height,
534            depth: 1,
535            bands: 1,
536            data_type: T::DATA_TYPE,
537            valid_masks: vec![BitMask::all_valid(expected)],
538            data: T::into_lerc_data(data),
539            no_data_value: None,
540        })
541    }
542}
543
544// ---------------------------------------------------------------------------
545// Zero-copy decode-into API
546// ---------------------------------------------------------------------------
547
548/// Decode a LERC blob into a pre-allocated buffer, returning metadata.
549///
550/// The type `T` must match the blob's data type (e.g., `f32` for `DataType::Float`).
551/// The buffer must have at least `width * height * n_depth * n_bands` elements.
552///
553/// Returns `LercError::TypeMismatch` if `T` does not match the blob's data type.
554/// Returns `LercError::OutputBufferTooSmall` if the buffer is too small.
555pub fn decode_into<T: Sample>(data: &[u8], output: &mut [T]) -> Result<DecodeResult> {
556    decode::decode_into(data, output)
557}
558
559/// Decode a LERC blob into a pre-allocated buffer, filling invalid pixels with
560/// a caller-supplied sentinel value.
561///
562/// This is a convenience layer over [`decode_into`]: it performs the same decode
563/// (so the same constraints on type and buffer size apply), then walks each
564/// band's validity mask and writes `nodata` into every position that the mask
565/// reports as invalid. For pixels with `depth > 1`, all `depth` slices of an
566/// invalid pixel receive the sentinel.
567///
568/// The returned [`DecodeResult`] still carries `valid_masks`, so callers that
569/// want both the sentinel-filled buffer and the masks (e.g. to distinguish
570/// genuine sentinel-valued pixels from mask-driven fills) have access to both.
571///
572/// Bands whose mask is [`BitMask::AllValid`] are skipped entirely — no writes
573/// occur for those bands.
574pub fn decode_into_with_nodata<T: Sample>(
575    data: &[u8],
576    output: &mut [T],
577    nodata: T,
578) -> Result<DecodeResult> {
579    let result = decode::decode_into(data, output)?;
580
581    let n_cols = result.width as usize;
582    let n_rows = result.height as usize;
583    let n_depth = result.depth as usize;
584    let band_size = n_rows * n_cols * n_depth;
585
586    for (band_idx, mask) in result.valid_masks.iter().enumerate() {
587        if mask.is_all_valid() {
588            continue;
589        }
590        let band_offset = band_idx * band_size;
591        for i in 0..n_rows {
592            let row_start = band_offset + i * n_cols * n_depth;
593            for j in 0..n_cols {
594                let k = i * n_cols + j;
595                if !mask.is_valid(k) {
596                    let base = row_start + j * n_depth;
597                    for m in 0..n_depth {
598                        output[base + m] = nodata;
599                    }
600                }
601            }
602        }
603    }
604
605    Ok(result)
606}