Skip to main content

copc_streaming/
header.rs

1//! LAS header + COPC info parsing.
2//!
3//! Uses the `las` crate for standard LAS/VLR parsing.
4//! Only the COPC info VLR (160 bytes) is parsed by us — it's COPC-specific.
5
6use std::io::Cursor;
7
8use byteorder::{LittleEndian, ReadBytesExt};
9use las::raw;
10use laz::LazVlr;
11
12use crate::error::CopcError;
13use crate::types::Aabb;
14
15/// Parsed COPC file header.
16///
17/// LAS-standard fields come from `las::Header`.
18/// COPC-specific fields are in `copc_info`.
19pub struct CopcHeader {
20    pub(crate) las_header: las::Header,
21    pub(crate) copc_info: CopcInfo,
22    pub(crate) laz_vlr: LazVlr,
23    pub(crate) evlr_offset: u64,
24    pub(crate) evlr_count: u32,
25}
26
27impl CopcHeader {
28    /// Full LAS header with transforms, bounds, point format, etc.
29    pub fn las_header(&self) -> &las::Header {
30        &self.las_header
31    }
32
33    /// COPC-specific info (octree center, halfsize, hierarchy location).
34    pub fn copc_info(&self) -> &CopcInfo {
35        &self.copc_info
36    }
37
38    /// LAZ decompression parameters.
39    pub fn laz_vlr(&self) -> &LazVlr {
40        &self.laz_vlr
41    }
42
43    /// File offset where EVLRs start.
44    pub fn evlr_offset(&self) -> u64 {
45        self.evlr_offset
46    }
47
48    /// Number of EVLRs.
49    pub fn evlr_count(&self) -> u32 {
50        self.evlr_count
51    }
52}
53
54/// COPC info VLR payload (160 bytes). This is COPC-specific — not part of the LAS standard.
55#[derive(Debug, Clone)]
56#[non_exhaustive]
57pub struct CopcInfo {
58    /// Centre of the root octree cube `[x, y, z]`.
59    pub center: [f64; 3],
60    /// Half the side length of the root octree cube.
61    pub halfsize: f64,
62    /// Spacing at the finest octree level.
63    pub spacing: f64,
64    /// File offset of the root hierarchy page.
65    pub root_hier_offset: u64,
66    /// Size of the root hierarchy page in bytes.
67    pub root_hier_size: u64,
68    /// Minimum GPS time across all points.
69    pub gpstime_minimum: f64,
70    /// Maximum GPS time across all points.
71    pub gpstime_maximum: f64,
72}
73
74impl CopcInfo {
75    /// Compute the root octree bounding box from center + halfsize.
76    pub fn root_bounds(&self) -> Aabb {
77        Aabb {
78            min: [
79                self.center[0] - self.halfsize,
80                self.center[1] - self.halfsize,
81                self.center[2] - self.halfsize,
82            ],
83            max: [
84                self.center[0] + self.halfsize,
85                self.center[1] + self.halfsize,
86                self.center[2] + self.halfsize,
87            ],
88        }
89    }
90
91    fn parse(data: &[u8]) -> Result<Self, CopcError> {
92        if data.len() < 160 {
93            return Err(CopcError::CopcInfoNotFound);
94        }
95        let mut r = Cursor::new(data);
96        let center_x = r.read_f64::<LittleEndian>()?;
97        let center_y = r.read_f64::<LittleEndian>()?;
98        let center_z = r.read_f64::<LittleEndian>()?;
99        let halfsize = r.read_f64::<LittleEndian>()?;
100        let spacing = r.read_f64::<LittleEndian>()?;
101        let root_hier_offset = r.read_u64::<LittleEndian>()?;
102        let root_hier_size = r.read_u64::<LittleEndian>()?;
103        let gpstime_minimum = r.read_f64::<LittleEndian>()?;
104        let gpstime_maximum = r.read_f64::<LittleEndian>()?;
105        Ok(CopcInfo {
106            center: [center_x, center_y, center_z],
107            halfsize,
108            spacing,
109            root_hier_offset,
110            root_hier_size,
111            gpstime_minimum,
112            gpstime_maximum,
113        })
114    }
115}
116
117/// Parse COPC header from a byte buffer.
118///
119/// The buffer must contain the LAS header and all VLRs (typically first ~64KB).
120pub(crate) fn parse_header(data: &[u8]) -> Result<CopcHeader, CopcError> {
121    let mut cursor = Cursor::new(data);
122
123    // Parse the raw LAS header
124    let raw_header = raw::Header::read_from(&mut cursor)?;
125
126    let evlr_offset = raw_header
127        .evlr
128        .as_ref()
129        .map_or(0, |e| e.start_of_first_evlr);
130    let evlr_count = raw_header.evlr.as_ref().map_or(0, |e| e.number_of_evlrs);
131    let number_of_vlrs = raw_header.number_of_variable_length_records;
132    let header_size = raw_header.header_size;
133
134    // Build the high-level header (for transforms, point format, etc.)
135    let mut builder = las::Builder::new(raw_header)?;
136
137    // Seek to VLR start and parse all VLRs
138    cursor.set_position(header_size as u64);
139
140    let mut copc_info = None;
141    let mut laz_vlr = None;
142
143    for _ in 0..number_of_vlrs {
144        let raw_vlr = raw::Vlr::read_from(&mut cursor, false)?;
145        let vlr = las::Vlr::new(raw_vlr);
146
147        match (vlr.user_id.as_str(), vlr.record_id) {
148            ("copc", 1) => {
149                copc_info = Some(CopcInfo::parse(&vlr.data)?);
150            }
151            ("laszip encoded", 22204) => {
152                laz_vlr = Some(LazVlr::read_from(vlr.data.as_slice())?);
153            }
154            _ => {}
155        }
156
157        builder.vlrs.push(vlr);
158    }
159
160    let las_header = builder.into_header()?;
161    let copc_info = copc_info.ok_or(CopcError::CopcInfoNotFound)?;
162    let laz_vlr = laz_vlr.ok_or(CopcError::LazVlrNotFound)?;
163
164    Ok(CopcHeader {
165        las_header,
166        copc_info,
167        laz_vlr,
168        evlr_offset,
169        evlr_count,
170    })
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    #[test]
178    fn test_copc_info_root_bounds() {
179        let info = CopcInfo {
180            center: [100.0, 200.0, 10.0],
181            halfsize: 50.0,
182            spacing: 1.0,
183            root_hier_offset: 0,
184            root_hier_size: 0,
185            gpstime_minimum: 0.0,
186            gpstime_maximum: 0.0,
187        };
188        let b = info.root_bounds();
189        assert_eq!(b.min, [50.0, 150.0, -40.0]);
190        assert_eq!(b.max, [150.0, 250.0, 60.0]);
191    }
192}