Skip to main content

webpkit_cli/format/
raw.rs

1//! Raw row-major pixel I/O (the codec's native currency).
2
3use webpkit::lossless::{Dimensions, Image, Metadata, PixelLayout};
4
5use crate::error::CliError;
6
7/// Dimensions and byte order for interpreting a raw pixel buffer.
8#[derive(Debug, Clone, Copy)]
9pub struct RawParams {
10    /// Image width in pixels.
11    pub width: u32,
12    /// Image height in pixels.
13    pub height: u32,
14    /// Byte order of each 4-byte pixel.
15    pub layout: PixelLayout,
16}
17
18/// Interpret `bytes` as raw row-major pixels per `params`.
19///
20/// # Errors
21///
22/// [`CliError::RawConfig`] if the buffer length does not equal
23/// `width * height * 4`, or [`CliError::Codec`] for out-of-range dimensions.
24pub fn read(bytes: &[u8], params: RawParams) -> Result<Image, CliError> {
25    let dims = Dimensions::new(params.width, params.height)?;
26    let expected = params.width as usize * params.height as usize * 4;
27    if bytes.len() != expected {
28        return Err(CliError::RawConfig(format!(
29            "raw input is {} bytes but {}x{} needs {expected}",
30            bytes.len(),
31            params.width,
32            params.height,
33        )));
34    }
35    let alpha_offset = match params.layout {
36        PixelLayout::Argb8 => 0,
37        PixelLayout::Rgba8 | PixelLayout::Bgra8 => 3,
38    };
39    let has_alpha = bytes.chunks_exact(4).any(|px| px[alpha_offset] != 0xff);
40    Ok(Image::from_parts(
41        dims,
42        params.layout,
43        bytes.to_vec(),
44        has_alpha,
45        Metadata::none(),
46    ))
47}