Skip to main content

webpkit_cli/
codec.rs

1//! Thin glue over the codec public API, shared by every binary.
2//!
3//! Both decode and encode route through the umbrella `webpkit` crate: [`decode`]
4//! inspects the container and handles **either** VP8L (lossless) or VP8 (lossy)
5//! input, and a single [`EncodeMode`] selects the encoder.
6
7use webpkit::{DecodeOptions, Effort, Encoder, Image, Metadata, PixelLayout};
8
9use crate::error::CliError;
10
11/// Which codec (and its knobs) [`encode`] should use.
12///
13/// The three shared binaries build this once from their own flag grammar and hand
14/// it to [`encode`], so the lossless/lossy fork lives in exactly one place.
15#[derive(Debug, Clone, Copy)]
16pub enum EncodeMode {
17    /// Lossless VP8L at the given effort [`Effort`].
18    Lossless(Effort),
19    /// Lossy VP8 at the given quality (`0..=100`) and effort [`Effort`].
20    Lossy {
21        /// Encode quality, higher = larger and closer to the source.
22        quality: u8,
23        /// Encoder effort tier.
24        method: Effort,
25    },
26}
27
28/// Decode any still WebP file — lossless (`VP8L`) or lossy (`VP8 `) — into an
29/// [`Image`] with the requested output `layout`, dispatching on the container.
30///
31/// # Errors
32///
33/// [`CliError::Codec`] if the input is not a decodable still WebP image.
34pub fn decode(bytes: &[u8], layout: PixelLayout) -> Result<Image, CliError> {
35    let options = DecodeOptions::default().layout(layout);
36    Ok(webpkit::decode_with(bytes, &options)?)
37}
38
39/// Encode an [`Image`] into a complete WebP file — lossless or lossy per `mode` —
40/// embedding exactly the given `metadata` (an empty [`Metadata`] yields a bare
41/// `VP8L`/`VP8 ` file).
42///
43/// Uses the bare-[`ImageRef`](webpkit::ImageRef) [`Encoder::encode_ref`] path so
44/// the CLI's per-field `-metadata` selection is honored precisely (the encoder's
45/// metadata is embedded verbatim, with no policy-based inheritance from the image).
46///
47/// # Errors
48///
49/// [`CliError::Codec`] if the image is invalid (out-of-range dimensions or a
50/// buffer-length mismatch).
51pub fn encode(image: &Image, mode: EncodeMode, metadata: Metadata) -> Result<Vec<u8>, CliError> {
52    let bytes = match mode {
53        EncodeMode::Lossless(effort) => Encoder::lossless()
54            .effort(effort)
55            .metadata(metadata)
56            .encode_ref(image.as_image_ref())?,
57        EncodeMode::Lossy { quality, method } => Encoder::lossy()
58            .quality(quality)
59            .effort(method)
60            .metadata(metadata)
61            .encode_ref(image.as_image_ref())?,
62    };
63    Ok(bytes)
64}