Skip to main content

spatialrust_io/pcd/
header.rs

1use std::io::{BufRead, Read};
2
3use crate::error::{pcd_format, pcd_parse, IoError};
4use crate::pcd::schema::PcdFieldSpec;
5
6/// PCD payload encoding.
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum PcdDataKind {
9    /// ASCII payload.
10    Ascii,
11    /// Binary little-endian payload.
12    Binary,
13    /// LZF-compressed binary payload.
14    BinaryCompressed,
15}
16
17/// Parsed PCD header.
18#[derive(Clone, Debug, PartialEq)]
19pub struct PcdHeader {
20    /// PCD version string.
21    pub version: String,
22    /// Field specifications.
23    pub fields: Vec<PcdFieldSpec>,
24    /// Cloud width.
25    pub width: usize,
26    /// Cloud height.
27    pub height: usize,
28    /// Viewpoint as seven float values.
29    pub viewpoint: [f32; 7],
30    /// Number of points.
31    pub points: usize,
32    /// Payload encoding.
33    pub data: PcdDataKind,
34}
35
36impl PcdHeader {
37    /// Returns the byte size of one point in binary PCD.
38    #[must_use]
39    pub fn point_step(&self) -> usize {
40        self.fields.iter().map(PcdFieldSpec::byte_size).sum()
41    }
42
43    /// Parses a PCD header from a buffered reader.
44    #[allow(unused_assignments)]
45    pub fn parse<R: BufRead>(reader: &mut R) -> Result<(Self, usize), IoError> {
46        let mut version = String::new();
47        let mut field_names = Vec::new();
48        let mut sizes = Vec::new();
49        let mut kinds = Vec::new();
50        let mut counts = Vec::new();
51        let mut width = 0usize;
52        let mut height = 0usize;
53        let mut viewpoint = [0.0_f32; 7];
54        let mut points = 0usize;
55        let mut points_declared = false;
56        let mut width_declared = false;
57        let mut height_declared = false;
58        let mut data: Option<PcdDataKind> = None;
59        let mut header_bytes = 0usize;
60
61        loop {
62            let mut line = String::new();
63            let read = reader.read_line(&mut line)?;
64            if read == 0 {
65                return Err(pcd_parse("unexpected EOF while reading PCD header"));
66            }
67            header_bytes += read;
68
69            let trimmed = line.trim();
70            if trimmed.is_empty() || trimmed.starts_with('#') {
71                continue;
72            }
73
74            if let Some(rest) = trimmed.strip_prefix("VERSION ") {
75                version = rest.trim().to_owned();
76                continue;
77            }
78            if let Some(rest) = trimmed.strip_prefix("FIELDS ") {
79                field_names = rest.split_whitespace().map(str::to_owned).collect();
80                continue;
81            }
82            if let Some(rest) = trimmed.strip_prefix("SIZE ") {
83                sizes = parse_usize_list(rest)?;
84                continue;
85            }
86            if let Some(rest) = trimmed.strip_prefix("TYPE ") {
87                kinds = parse_type_list(rest)?;
88                continue;
89            }
90            if let Some(rest) = trimmed.strip_prefix("COUNT ") {
91                counts = parse_usize_list(rest)?;
92                continue;
93            }
94            if let Some(rest) = trimmed.strip_prefix("WIDTH ") {
95                width_declared = true;
96                width = rest
97                    .trim()
98                    .parse()
99                    .map_err(|_| pcd_parse(format!("invalid WIDTH `{rest}`")))?;
100                continue;
101            }
102            if let Some(rest) = trimmed.strip_prefix("HEIGHT ") {
103                height_declared = true;
104                height = rest
105                    .trim()
106                    .parse()
107                    .map_err(|_| pcd_parse(format!("invalid HEIGHT `{rest}`")))?;
108                continue;
109            }
110            if let Some(rest) = trimmed.strip_prefix("VIEWPOINT ") {
111                let values = parse_f32_list(rest)?;
112                if values.len() != 7 {
113                    return Err(pcd_parse("VIEWPOINT must contain 7 values"));
114                }
115                viewpoint.copy_from_slice(&values);
116                continue;
117            }
118            if let Some(rest) = trimmed.strip_prefix("POINTS ") {
119                points_declared = true;
120                points = rest
121                    .trim()
122                    .parse()
123                    .map_err(|_| pcd_parse(format!("invalid POINTS `{rest}`")))?;
124                continue;
125            }
126            if let Some(rest) = trimmed.strip_prefix("DATA ") {
127                data = Some(match rest.trim().to_ascii_lowercase().as_str() {
128                    "ascii" => PcdDataKind::Ascii,
129                    "binary" => PcdDataKind::Binary,
130                    "binary_compressed" => PcdDataKind::BinaryCompressed,
131                    other => return Err(pcd_format(format!("unsupported DATA mode `{other}`"))),
132                });
133                break;
134            }
135
136            return Err(pcd_parse(format!("unexpected PCD header line `{trimmed}`")));
137        }
138
139        if version.is_empty() {
140            version = "0.7".to_owned();
141        }
142        if field_names.is_empty() {
143            return Err(pcd_parse("PCD header missing FIELDS"));
144        }
145        if sizes.len() != field_names.len()
146            || kinds.len() != field_names.len()
147            || counts.len() != field_names.len()
148        {
149            return Err(pcd_parse("FIELDS/SIZE/TYPE/COUNT length mismatch in PCD header"));
150        }
151
152        let fields: Vec<PcdFieldSpec> = field_names
153            .into_iter()
154            .zip(sizes)
155            .zip(kinds)
156            .zip(counts)
157            .map(|(((name, size), kind), count)| PcdFieldSpec { name, size, kind, count })
158            .collect();
159
160        let data_kind = data.ok_or_else(|| pcd_parse("PCD header missing DATA"))?;
161        let dimension_points = if width_declared && height_declared {
162            Some(
163                width
164                    .checked_mul(height)
165                    .ok_or_else(|| pcd_format("PCD WIDTH * HEIGHT overflow"))?,
166            )
167        } else {
168            None
169        };
170        if !points_declared {
171            points = dimension_points.unwrap_or(0);
172        }
173        let point_step = fields.iter().try_fold(0_usize, |total, field| {
174            if field.size == 0 || field.count == 0 {
175                return Err(pcd_format("PCD SIZE and COUNT must be positive"));
176            }
177            let bytes = field
178                .size
179                .checked_mul(field.count)
180                .ok_or_else(|| pcd_format("PCD field byte size overflow"))?;
181            total.checked_add(bytes).ok_or_else(|| pcd_format("PCD point byte size overflow"))
182        })?;
183        let payload_size = point_step
184            .checked_mul(points)
185            .ok_or_else(|| pcd_format("PCD payload byte size overflow"))?;
186        if payload_size > isize::MAX as usize {
187            return Err(pcd_format("PCD payload exceeds addressable allocation size"));
188        }
189        if let Some(dimension_points) = dimension_points {
190            if points_declared && points != dimension_points {
191                return Err(pcd_format(format!(
192                    "PCD POINTS {points} does not match WIDTH * HEIGHT {dimension_points}"
193                )));
194            }
195        }
196
197        Ok((
198            Self { version, fields, width, height, viewpoint, points, data: data_kind },
199            header_bytes,
200        ))
201    }
202}
203
204fn parse_usize_list(input: &str) -> Result<Vec<usize>, IoError> {
205    input
206        .split_whitespace()
207        .map(|value| {
208            value.parse().map_err(|_| pcd_parse(format!("invalid integer `{value}` in PCD header")))
209        })
210        .collect()
211}
212
213fn parse_f32_list(input: &str) -> Result<Vec<f32>, IoError> {
214    input
215        .split_whitespace()
216        .map(|value| {
217            value.parse().map_err(|_| pcd_parse(format!("invalid float `{value}` in PCD header")))
218        })
219        .collect()
220}
221
222fn parse_type_list(input: &str) -> Result<Vec<crate::pcd::schema::PcdType>, IoError> {
223    input
224        .split_whitespace()
225        .map(|value| match value {
226            "I" => Ok(crate::pcd::schema::PcdType::I),
227            "U" => Ok(crate::pcd::schema::PcdType::U),
228            "F" => Ok(crate::pcd::schema::PcdType::F),
229            _ => Err(pcd_parse(format!("invalid TYPE token `{value}`"))),
230        })
231        .collect()
232}
233
234/// Reads the remaining binary payload bytes after the header.
235pub fn read_binary_payload<R: Read>(reader: &mut R, byte_len: usize) -> Result<Vec<u8>, IoError> {
236    let mut data = vec![0_u8; byte_len];
237    reader.read_exact(&mut data)?;
238    Ok(data)
239}
240
241#[cfg(test)]
242mod tests {
243    use super::{PcdDataKind, PcdHeader};
244    use std::io::Cursor;
245
246    const SAMPLE_ASCII_HEADER: &str = "\
247# .PCD v0.7 - Point Cloud Data file format
248VERSION 0.7
249FIELDS x y z
250SIZE 4 4 4
251TYPE F F F
252COUNT 1 1 1
253WIDTH 2
254HEIGHT 1
255VIEWPOINT 0 0 0 1 0 0 0
256POINTS 2
257DATA ascii
258";
259
260    #[test]
261    fn parses_ascii_header() {
262        let mut reader = Cursor::new(SAMPLE_ASCII_HEADER);
263        let (header, _) = PcdHeader::parse(&mut reader).unwrap();
264        assert_eq!(header.points, 2);
265        assert_eq!(header.data, PcdDataKind::Ascii);
266        assert_eq!(header.fields.len(), 3);
267    }
268
269    #[test]
270    fn rejects_overflowing_and_zero_sized_headers() {
271        for (sizes, counts, width, height, points, message) in [
272            ("4 4 4".to_owned(), "1 1 1".to_owned(), usize::MAX, 2, 0, "WIDTH * HEIGHT"),
273            (format!("{} 4 4", usize::MAX), "2 1 1".to_owned(), 1, 1, 1, "field byte size"),
274            (format!("{} 4 4", usize::MAX), "1 1 1".to_owned(), 1, 1, 1, "point byte size"),
275            ("4 4 4".to_owned(), "1 1 1".to_owned(), 1, 1, usize::MAX, "payload byte size"),
276            (
277                "4 4 4".to_owned(),
278                "1 1 1".to_owned(),
279                1,
280                1,
281                isize::MAX as usize / 12 + 1,
282                "addressable",
283            ),
284            ("0 4 4".to_owned(), "1 1 1".to_owned(), 1, 1, 1, "positive"),
285            ("4 4 4".to_owned(), "0 1 1".to_owned(), 1, 1, 1, "positive"),
286        ] {
287            let input = format!("FIELDS x y z\nSIZE {sizes}\nTYPE F F F\nCOUNT {counts}\nWIDTH {width}\nHEIGHT {height}\nPOINTS {points}\nDATA binary\n");
288            let error = PcdHeader::parse(&mut Cursor::new(&input)).unwrap_err();
289            assert!(error.to_string().contains(message), "{error}");
290            // Public whole-cloud and streaming entry points reject before allocation.
291            assert!(crate::pcd::reader::read_pcd(&mut Cursor::new(&input)).is_err());
292            #[cfg(feature = "streaming")]
293            assert!(crate::pcd::reader::PcdChunkSource::new(
294                Cursor::new(&input),
295                spatialrust_records::StreamOptions::new(
296                    1,
297                    spatialrust_records::MemoryBudget::new(24).unwrap()
298                )
299                .unwrap(),
300                spatialrust_records::CancellationToken::default(),
301            )
302            .is_err());
303        }
304    }
305
306    #[test]
307    fn infers_missing_point_count_and_accepts_empty_clouds() {
308        let input = SAMPLE_ASCII_HEADER.replace("POINTS 2\n", "");
309        assert_eq!(PcdHeader::parse(&mut Cursor::new(input)).unwrap().0.points, 2);
310        let input =
311            SAMPLE_ASCII_HEADER.replace("WIDTH 2", "WIDTH 0").replace("POINTS 2", "POINTS 0");
312        assert_eq!(PcdHeader::parse(&mut Cursor::new(input)).unwrap().0.points, 0);
313    }
314
315    #[test]
316    fn rejects_explicit_point_count_inconsistent_with_dimensions() {
317        for points in [0, 1, 3] {
318            let input = SAMPLE_ASCII_HEADER.replace("POINTS 2", &format!("POINTS {points}"));
319            let error = PcdHeader::parse(&mut Cursor::new(&input)).unwrap_err();
320            assert!(error.to_string().contains("does not match WIDTH * HEIGHT"));
321            assert!(crate::pcd::reader::read_pcd(&mut Cursor::new(input)).is_err());
322        }
323        let input = SAMPLE_ASCII_HEADER.replace("WIDTH 2", "WIDTH 0");
324        assert!(PcdHeader::parse(&mut Cursor::new(input)).is_err());
325    }
326
327    #[test]
328    fn accepts_organized_and_point_count_only_headers() {
329        let input =
330            SAMPLE_ASCII_HEADER.replace("HEIGHT 1", "HEIGHT 3").replace("POINTS 2", "POINTS 6");
331        assert_eq!(PcdHeader::parse(&mut Cursor::new(input)).unwrap().0.points, 6);
332        let input = SAMPLE_ASCII_HEADER.replace("WIDTH 2\n", "").replace("HEIGHT 1\n", "");
333        assert_eq!(PcdHeader::parse(&mut Cursor::new(input)).unwrap().0.points, 2);
334    }
335}