Skip to main content

webpkit_cli/
format.rs

1//! Image-file encodings the CLI reads and writes: PNG, netpbm (PPM/PAM), raw.
2//!
3//! The codec itself only speaks raw RGBA/ARGB/BGRA, so this layer is what makes
4//! the tools accept `.png` inputs and emit `.png` outputs.
5
6pub mod png;
7pub mod ppm;
8pub mod raw;
9
10use clap::ValueEnum;
11use webpkit::lossless::{Image, Metadata, PixelLayout};
12
13use crate::{error::CliError, format::raw::RawParams};
14
15/// An image encoding the CLI can read as encoder input.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
17pub enum InputFormat {
18    /// PNG (any color type; normalized to RGBA8).
19    Png,
20    /// Netpbm binary PPM (`P6`, RGB).
21    Ppm,
22    /// Netpbm binary PAM (`P7`, RGBA).
23    Pam,
24    /// Raw row-major pixels; requires `--width`/`--height`/`--layout`.
25    Raw,
26}
27
28/// An image encoding the CLI can write as decoder output.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
30pub enum OutputFormat {
31    /// PNG, RGBA8.
32    Png,
33    /// Netpbm binary PPM (`P6`, RGB; alpha dropped).
34    Ppm,
35    /// Netpbm binary PAM (`P7`, RGBA).
36    Pam,
37    /// Raw row-major pixels in the requested `--layout`.
38    Raw,
39}
40
41impl InputFormat {
42    /// Resolve the input format: an explicit choice wins, else the file
43    /// extension, else the leading magic bytes, else [`InputFormat::Raw`].
44    #[must_use]
45    pub fn resolve(explicit: Option<Self>, extension: Option<&str>, bytes: &[u8]) -> Self {
46        explicit
47            .or_else(|| extension.and_then(Self::from_extension))
48            .or_else(|| Self::sniff(bytes))
49            .unwrap_or(Self::Raw)
50    }
51
52    fn from_extension(ext: &str) -> Option<Self> {
53        match ext {
54            "png" => Some(Self::Png),
55            "ppm" => Some(Self::Ppm),
56            "pam" => Some(Self::Pam),
57            "raw" | "rgba" | "argb" | "bgra" => Some(Self::Raw),
58            _ => None,
59        }
60    }
61
62    fn sniff(bytes: &[u8]) -> Option<Self> {
63        if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
64            Some(Self::Png)
65        } else if bytes.starts_with(b"P6") {
66            Some(Self::Ppm)
67        } else if bytes.starts_with(b"P7") {
68            Some(Self::Pam)
69        } else {
70            None
71        }
72    }
73}
74
75impl OutputFormat {
76    /// Resolve the output format: an explicit choice wins, else the `-o`
77    /// extension, else [`OutputFormat::Png`] (the dwebp default).
78    #[must_use]
79    pub fn resolve(explicit: Option<Self>, extension: Option<&str>) -> Self {
80        explicit
81            .or_else(|| extension.and_then(Self::from_extension))
82            .unwrap_or(Self::Png)
83    }
84
85    fn from_extension(ext: &str) -> Option<Self> {
86        match ext {
87            "png" => Some(Self::Png),
88            "ppm" => Some(Self::Ppm),
89            "pam" => Some(Self::Pam),
90            "raw" | "rgba" | "argb" | "bgra" => Some(Self::Raw),
91            _ => None,
92        }
93    }
94}
95
96/// Decode `bytes` in the given `format` into an [`Image`].
97///
98/// `raw` supplies the dimensions/layout required by [`InputFormat::Raw`].
99///
100/// # Errors
101///
102/// [`CliError::Format`] if a PNG/netpbm stream is malformed, or
103/// [`CliError::RawConfig`] if raw parameters are missing or inconsistent.
104pub fn read_image(
105    bytes: &[u8],
106    format: InputFormat,
107    raw: Option<RawParams>,
108) -> Result<Image, CliError> {
109    match format {
110        InputFormat::Png => png::read(bytes),
111        InputFormat::Ppm | InputFormat::Pam => ppm::read(bytes),
112        InputFormat::Raw => {
113            let params = raw.ok_or_else(|| {
114                CliError::RawConfig(
115                    "raw input requires --width and --height (or use a PNG/PPM/PAM file)"
116                        .to_owned(),
117                )
118            })?;
119            raw::read(bytes, params)
120        },
121    }
122}
123
124/// Encode an [`Image`] into the given output `format`, returning file bytes.
125///
126/// `metadata` is embedded only by formats that support it (PNG); netpbm and raw
127/// ignore it.
128///
129/// # Errors
130///
131/// [`CliError::Format`] if PNG encoding fails.
132pub fn write_image(
133    image: &Image,
134    format: OutputFormat,
135    metadata: &Metadata,
136) -> Result<Vec<u8>, CliError> {
137    match format {
138        OutputFormat::Png => png::write(image, metadata),
139        OutputFormat::Ppm => Ok(ppm::write_ppm(image)),
140        OutputFormat::Pam => Ok(ppm::write_pam(image)),
141        OutputFormat::Raw => Ok(image.as_bytes().to_vec()),
142    }
143}
144
145/// Return an image's pixels as RGBA8, reordering from its stored layout.
146#[must_use]
147pub fn to_rgba8(image: &Image) -> Vec<u8> {
148    let src = image.as_bytes();
149    match image.layout() {
150        PixelLayout::Rgba8 => src.to_vec(),
151        PixelLayout::Argb8 => reorder(src, [1, 2, 3, 0]),
152        PixelLayout::Bgra8 => reorder(src, [2, 1, 0, 3]),
153    }
154}
155
156/// Reorder 4-byte pixels by picking source indices `order` into RGBA slots.
157fn reorder(src: &[u8], order: [usize; 4]) -> Vec<u8> {
158    let mut out = Vec::with_capacity(src.len());
159    for px in src.chunks_exact(4) {
160        out.extend_from_slice(&[px[order[0]], px[order[1]], px[order[2]], px[order[3]]]);
161    }
162    out
163}