Skip to main content

webpkit_cli/format/
ppm.rs

1//! Netpbm binary PPM (`P6`, RGB) and PAM (`P7`, RGBA) I/O — dependency-free, for
2//! `cwebp` PPM/PAM inputs and `dwebp -ppm`/`-pam` outputs.
3
4use webpkit::lossless::{Dimensions, Image, Metadata, PixelLayout};
5
6use crate::{error::CliError, format::to_rgba8};
7
8/// Decode a binary PPM (`P6`) or PAM (`P7`) image into an RGBA8 [`Image`].
9///
10/// # Errors
11///
12/// [`CliError::Format`] if the header or body is malformed or uses an
13/// unsupported feature (only 8-bit `MAXVAL 255` is supported).
14pub fn read(bytes: &[u8]) -> Result<Image, CliError> {
15    if bytes.starts_with(b"P6") {
16        read_ppm(bytes)
17    } else if bytes.starts_with(b"P7") {
18        read_pam(bytes)
19    } else {
20        Err(CliError::Format(
21            "not a binary PPM/PAM (P6/P7) file".to_owned(),
22        ))
23    }
24}
25
26/// Encode an [`Image`] as a binary PPM (`P6`, RGB; alpha dropped).
27#[must_use]
28pub fn write_ppm(image: &Image) -> Vec<u8> {
29    let rgba = to_rgba8(image);
30    let mut out = format!("P6\n{} {}\n255\n", image.width(), image.height()).into_bytes();
31    out.reserve(rgba.len() / 4 * 3);
32    for px in rgba.chunks_exact(4) {
33        out.extend_from_slice(&px[..3]);
34    }
35    out
36}
37
38/// Encode an [`Image`] as a binary PAM (`P7`, RGBA).
39#[must_use]
40pub fn write_pam(image: &Image) -> Vec<u8> {
41    let rgba = to_rgba8(image);
42    let header = format!(
43        "P7\nWIDTH {}\nHEIGHT {}\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n",
44        image.width(),
45        image.height(),
46    );
47    let mut out = header.into_bytes();
48    out.extend_from_slice(&rgba);
49    out
50}
51
52fn read_ppm(bytes: &[u8]) -> Result<Image, CliError> {
53    let mut pos = 2;
54    let width = next_uint(bytes, &mut pos)?;
55    let height = next_uint(bytes, &mut pos)?;
56    let maxval = next_uint(bytes, &mut pos)?;
57    require_maxval_255(maxval)?;
58    // A single whitespace byte separates the header from the pixel data.
59    pos += 1;
60    let data = bytes.get(pos..).unwrap_or(&[]);
61    let rgba = pack_rgba(data, width, height, 3)?;
62    finish(width, height, rgba)
63}
64
65fn read_pam(bytes: &[u8]) -> Result<Image, CliError> {
66    let end = find(bytes, b"ENDHDR").ok_or_else(|| bad("PAM header missing ENDHDR"))?;
67    let header = core::str::from_utf8(&bytes[..end]).map_err(|_| bad("PAM header is not UTF-8"))?;
68    let (mut width, mut height, mut depth, mut maxval) = (None, None, None, None);
69    for line in header.lines() {
70        let mut it = line.split_ascii_whitespace();
71        match (it.next(), it.next()) {
72            (Some("WIDTH"), Some(v)) => width = Some(parse_uint(v)?),
73            (Some("HEIGHT"), Some(v)) => height = Some(parse_uint(v)?),
74            (Some("DEPTH"), Some(v)) => depth = Some(parse_uint(v)?),
75            (Some("MAXVAL"), Some(v)) => maxval = Some(parse_uint(v)?),
76            _ => {},
77        }
78    }
79    let width = width.ok_or_else(|| bad("PAM header missing WIDTH"))?;
80    let height = height.ok_or_else(|| bad("PAM header missing HEIGHT"))?;
81    let depth = depth.ok_or_else(|| bad("PAM header missing DEPTH"))?;
82    require_maxval_255(maxval.ok_or_else(|| bad("PAM header missing MAXVAL"))?)?;
83    if depth != 3 && depth != 4 {
84        return Err(bad("PAM DEPTH must be 3 (RGB) or 4 (RGBA)"));
85    }
86    // Data begins after "ENDHDR" and its trailing newline.
87    let data = bytes.get(end + "ENDHDR".len() + 1..).unwrap_or(&[]);
88    let rgba = pack_rgba(data, width, height, depth as usize)?;
89    finish(width, height, rgba)
90}
91
92/// Pack `channels`-per-pixel 8-bit data (3=RGB, 4=RGBA) into RGBA8.
93fn pack_rgba(data: &[u8], width: u32, height: u32, channels: usize) -> Result<Vec<u8>, CliError> {
94    let pixels = width as usize * height as usize;
95    let expected = pixels * channels;
96    if data.len() < expected {
97        return Err(CliError::Format(format!(
98            "netpbm body is {} bytes but {width}x{height} at depth {channels} needs {expected}",
99            data.len(),
100        )));
101    }
102    let mut rgba = Vec::with_capacity(pixels * 4);
103    for px in data[..expected].chunks_exact(channels) {
104        match channels {
105            3 => rgba.extend_from_slice(&[px[0], px[1], px[2], 0xff]),
106            _ => rgba.extend_from_slice(&[px[0], px[1], px[2], px[3]]),
107        }
108    }
109    Ok(rgba)
110}
111
112fn finish(width: u32, height: u32, rgba: Vec<u8>) -> Result<Image, CliError> {
113    let dims = Dimensions::new(width, height)?;
114    let has_alpha = rgba.chunks_exact(4).any(|px| px[3] != 0xff);
115    Ok(Image::from_parts(
116        dims,
117        PixelLayout::Rgba8,
118        rgba,
119        has_alpha,
120        Metadata::none(),
121    ))
122}
123
124/// Read the next unsigned integer, skipping ASCII whitespace and `#` comments,
125/// leaving `pos` at the first byte after the digits.
126fn next_uint(bytes: &[u8], pos: &mut usize) -> Result<u32, CliError> {
127    while let Some(&b) = bytes.get(*pos) {
128        if b == b'#' {
129            while let Some(&c) = bytes.get(*pos) {
130                *pos += 1;
131                if c == b'\n' {
132                    break;
133                }
134            }
135        } else if b.is_ascii_whitespace() {
136            *pos += 1;
137        } else {
138            break;
139        }
140    }
141    let start = *pos;
142    let mut value: u64 = 0;
143    while let Some(&b) = bytes.get(*pos) {
144        if b.is_ascii_digit() {
145            value = value * 10 + u64::from(b - b'0');
146            if value > u64::from(u32::MAX) {
147                return Err(bad("netpbm integer out of range"));
148            }
149            *pos += 1;
150        } else {
151            break;
152        }
153    }
154    if *pos == start {
155        return Err(bad("expected an integer in the netpbm header"));
156    }
157    u32::try_from(value).map_err(|_| bad("netpbm integer out of range"))
158}
159
160fn parse_uint(text: &str) -> Result<u32, CliError> {
161    text.parse()
162        .map_err(|_| bad("invalid integer in PAM header"))
163}
164
165fn require_maxval_255(maxval: u32) -> Result<(), CliError> {
166    if maxval == 255 {
167        Ok(())
168    } else {
169        Err(bad("only 8-bit netpbm (MAXVAL 255) is supported"))
170    }
171}
172
173fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
174    haystack
175        .windows(needle.len())
176        .position(|window| window == needle)
177}
178
179fn bad(message: &str) -> CliError {
180    CliError::Format(message.to_owned())
181}