Skip to main content

lib_jsl_file_io/
ppm.rs

1//! Netpbm images: PBM (P1, P4), PGM (P2, P5) and PPM (P3, P6).
2//!
3//! The simplest lossless formats: a short text header (magic number, width, height and maximum
4//! value, with `#` comments) followed by the samples, as ASCII numbers (P1–P3) or raw bytes
5//! (P4–P6; 16-bit big-endian when the maximum exceeds 255). Bitmaps (PBM, where 1 is black) are
6//! read as 8-bit greyscale with black = 0 and white = 255. Writing produces binary PGM (one
7//! channel) or PPM (three channels).
8//!
9//! See the book entry [Image files](https://jwkunz.github.io/lib_jsl/book/foundations/images.html#netpbm).
10
11use crate::png::RasterImage;
12use lib_jsl_core::ErrorsJSL;
13use std::path::Path;
14
15fn corrupt(message: &'static str) -> ErrorsJSL {
16    ErrorsJSL::RuntimeError(message)
17}
18
19struct Cursor<'a> {
20    data: &'a [u8],
21    position: usize,
22}
23
24impl Cursor<'_> {
25    /// Skips whitespace and comments, then reads one whitespace-delimited token.
26    fn token(&mut self) -> Result<&[u8], ErrorsJSL> {
27        loop {
28            match self.data.get(self.position) {
29                Some(b'#') => {
30                    while self.data.get(self.position).is_some_and(|&c| c != b'\n') {
31                        self.position += 1;
32                    }
33                }
34                Some(c) if c.is_ascii_whitespace() => self.position += 1,
35                Some(_) => break,
36                None => return Err(corrupt("Netpbm data ended early.")),
37            }
38        }
39        let start = self.position;
40        while self.data.get(self.position).is_some_and(|c| !c.is_ascii_whitespace() && *c != b'#') {
41            self.position += 1;
42        }
43        Ok(&self.data[start..self.position])
44    }
45
46    fn number(&mut self) -> Result<usize, ErrorsJSL> {
47        std::str::from_utf8(self.token()?).ok().and_then(|t| t.parse().ok()).ok_or(corrupt("Bad number in Netpbm data."))
48    }
49}
50
51/// Decodes any Netpbm image (P1 to P6).
52pub fn ppm_decode(data: &[u8]) -> Result<RasterImage, ErrorsJSL> {
53    let mut cursor = Cursor { data, position: 0 };
54    let magic = cursor.token()?.to_vec();
55    let kind = match magic.as_slice() {
56        [b'P', k @ b'1'..=b'6'] => k - b'0',
57        _ => return Err(corrupt("Not a Netpbm image.")),
58    };
59    let (width, height) = (cursor.number()?, cursor.number()?);
60    let bitmap = kind == 1 || kind == 4;
61    let max = if bitmap { 1 } else { cursor.number()? };
62    if max == 0 || max > 65535 {
63        return Err(corrupt("The Netpbm maximum value must be 1 to 65535."));
64    }
65    let channels = if kind == 3 || kind == 6 { 3 } else { 1 };
66    // Every sample takes at least one bit of what remains (one character in the text formats), so
67    // a header promising more is rejected before anything is allocated.
68    let count = width.checked_mul(height).and_then(|n| n.checked_mul(channels)).ok_or(corrupt("The Netpbm image is too large."))?;
69    if count / 8 > data.len().saturating_sub(cursor.position) {
70        return Err(corrupt("Netpbm data ended early."));
71    }
72    let mut samples = Vec::with_capacity(count);
73    if kind <= 3 {
74        for _ in 0..count {
75            if kind == 1 {
76                // Bitmaps may pack digits without separators.
77                let digit = loop {
78                    match data.get(cursor.position) {
79                        Some(b'0') | Some(b'1') => break data[cursor.position],
80                        Some(b'#') => {
81                            cursor.token()?;
82                            cursor.position -= 1;
83                            continue;
84                        }
85                        Some(_) => cursor.position += 1,
86                        None => return Err(corrupt("Netpbm data ended early.")),
87                    }
88                };
89                cursor.position += 1;
90                samples.push(digit as usize - b'0' as usize);
91            } else {
92                samples.push(cursor.number()?);
93            }
94        }
95    } else {
96        cursor.position += 1; // the single whitespace after the header
97        let body = &data[cursor.position.min(data.len())..];
98        if kind == 4 {
99            let row_bytes = width.div_ceil(8);
100            if body.len() < row_bytes * height {
101                return Err(corrupt("Netpbm data ended early."));
102            }
103            for y in 0..height {
104                for x in 0..width {
105                    samples.push(((body[y * row_bytes + x / 8] >> (7 - x % 8)) & 1) as usize);
106                }
107            }
108        } else if max < 256 {
109            if body.len() < count {
110                return Err(corrupt("Netpbm data ended early."));
111            }
112            samples.extend(body[..count].iter().map(|&b| b as usize));
113        } else {
114            if body.len() < 2 * count {
115                return Err(corrupt("Netpbm data ended early."));
116            }
117            samples.extend((0..count).map(|i| u16::from_be_bytes([body[2 * i], body[2 * i + 1]]) as usize));
118        }
119    }
120    if samples.iter().any(|&s| s > max) {
121        return Err(corrupt("A Netpbm sample exceeds the maximum value."));
122    }
123    // Rescale to 8 bits (or keep 16-bit data at 16 bits); bitmaps map 1 (black) to 0.
124    let (depth, target) = if max > 255 { (16, 65535usize) } else { (8, 255usize) };
125    let values = samples
126        .into_iter()
127        .map(|s| if bitmap { (1 - s) as u16 * 255 } else { ((s * target + max / 2) / max) as u16 })
128        .collect();
129    RasterImage::new(width, height, channels, depth, values)
130}
131
132/// Encodes a one-channel image as binary PGM (P5) or a three-channel image as binary PPM (P6),
133/// with maximum value 255 or 65535 according to the bit depth.
134pub fn ppm_encode(image: &RasterImage) -> Result<Vec<u8>, ErrorsJSL> {
135    let magic = match image.channels {
136        1 => "P5",
137        3 => "P6",
138        _ => return Err(ErrorsJSL::InvalidInputRange("PGM/PPM need one or three channels (drop alpha first).")),
139    };
140    let max = if image.bit_depth == 16 { 65535 } else { 255 };
141    let mut out = format!("{magic}\n{} {}\n{max}\n", image.width, image.height).into_bytes();
142    if image.bit_depth == 16 {
143        out.extend(image.samples.iter().flat_map(|s| s.to_be_bytes()));
144    } else {
145        out.extend(image.samples.iter().map(|&s| s as u8));
146    }
147    Ok(out)
148}
149
150/// Reads a Netpbm file.
151pub fn read_ppm_file(path: impl AsRef<Path>) -> Result<RasterImage, ErrorsJSL> {
152    let data = std::fs::read(path).map_err(|_| ErrorsJSL::RuntimeError("Could not read the Netpbm file."))?;
153    ppm_decode(&data)
154}
155
156/// Writes a binary PGM or PPM file.
157pub fn write_ppm_file(path: impl AsRef<Path>, image: &RasterImage) -> Result<(), ErrorsJSL> {
158    std::fs::write(path, ppm_encode(image)?).map_err(|_| ErrorsJSL::RuntimeError("Could not write the Netpbm file."))
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164
165    #[test]
166    fn headers_promising_more_data_than_the_file_holds_are_errors() {
167        // These used to try to allocate hundreds of gigabytes and abort the process.
168        assert!(ppm_decode(b"P5\n200000 200000\n255\nabc").is_err());
169        assert!(ppm_decode(b"P2\n200000 200000\n255\n1 2 3").is_err());
170        assert!(ppm_decode(b"P6\n4294967296 4294967296\n255\n").is_err());
171    }
172
173    #[test]
174    fn reads_ascii_variants_with_comments() {
175        let ppm = b"P3\n# a comment\n2 1\n# another\n255\n255 0 0   0 128 255\n";
176        let image = ppm_decode(ppm).unwrap();
177        assert_eq!((image.width, image.height, image.channels), (2, 1, 3));
178        assert_eq!(image.samples, vec![255, 0, 0, 0, 128, 255]);
179        // Maximum 15 rescales to 8 bits.
180        let pgm = ppm_decode(b"P2 3 1 15 0 15 7").unwrap();
181        assert_eq!(pgm.samples, vec![0, 255, 119]);
182        // Bitmap digits may run together; 1 is black.
183        let pbm = ppm_decode(b"P1\n4 2\n0101\n1 1 0 0\n").unwrap();
184        assert_eq!(pbm.samples, vec![255, 0, 255, 0, 0, 0, 255, 255]);
185    }
186
187    #[test]
188    fn binary_round_trips_and_packed_bitmaps() {
189        let rgb = RasterImage::new(5, 3, 3, 8, (0..45).map(|i| (i * 5) as u16).collect()).unwrap();
190        assert_eq!(ppm_decode(&ppm_encode(&rgb).unwrap()).unwrap(), rgb);
191        let deep = RasterImage::new(4, 2, 1, 16, (0..8).map(|i| i * 9000).collect()).unwrap();
192        assert_eq!(ppm_decode(&ppm_encode(&deep).unwrap()).unwrap(), deep);
193        // P4: 10 pixels per row packed MSB first and padded to whole bytes.
194        let mut p4 = b"P4\n10 1\n".to_vec();
195        p4.extend([0b1010_0000, 0b0100_0000]);
196        assert_eq!(ppm_decode(&p4).unwrap().samples, vec![0, 255, 0, 255, 255, 255, 255, 255, 255, 0]);
197        assert!(ppm_decode(b"P6 2 2 255 abc").is_err() && ppm_decode(b"P7 1 1 1 0").is_err());
198        assert!(ppm_encode(&RasterImage::new(1, 1, 4, 8, vec![1, 2, 3, 4]).unwrap()).is_err());
199    }
200}