Skip to main content

webpkit_cli/cli/
brand.rs

1//! The `webp` brand tool: `encode` / `decode` / `convert` / `info`.
2//!
3//! It works over PNG, netpbm, and raw pixels with smart format detection and
4//! metadata-preserving defaults, decodes animations frame-by-frame, and shares
5//! the codec, format, I/O, and reporting layers with the `cwebp` / `dwebp`
6//! drop-ins.
7
8use std::{path::PathBuf, process::ExitCode};
9
10use clap::{Parser, Subcommand};
11
12use crate::{
13    bulk,
14    cli::{Layout, Method},
15    codec::{self, EncodeMode},
16    error::CliError,
17    format::{self, InputFormat, OutputFormat, raw::RawParams},
18    io::{Sink, Source},
19    metadata::{MetadataField, Selection},
20    report::{self, Reporter},
21};
22
23/// Encode, decode, and inspect WebP VP8L (lossless) images.
24#[derive(Debug, Parser)]
25#[command(name = "webp", version, about, long_about = None)]
26struct Cli {
27    #[command(flatten)]
28    global: GlobalArgs,
29    #[command(subcommand)]
30    command: Command,
31}
32
33/// Flags available to every subcommand.
34#[derive(Debug, clap::Args)]
35struct GlobalArgs {
36    /// Print per-stage detail on stderr.
37    #[arg(short, long, global = true, action = clap::ArgAction::Count)]
38    verbose: u8,
39    /// Suppress all non-error output.
40    #[arg(short, long, global = true, conflicts_with = "verbose")]
41    quiet: bool,
42}
43
44#[derive(Debug, Subcommand)]
45enum Command {
46    /// Decode a WebP VP8L file to PNG (default), PPM/PAM, or raw pixels.
47    Decode(DecodeArgs),
48    /// Encode a PNG/PPM/PAM/raw image into a WebP file (lossless, or --lossy).
49    Encode(EncodeArgs),
50    /// Batch-convert many images (or directories) to WebP, in parallel.
51    Convert(ConvertArgs),
52    /// Print a summary of a WebP file (size, alpha, metadata, animation).
53    Info(InfoArgs),
54}
55
56/// Arguments for `webp convert`.
57#[derive(Debug, clap::Args)]
58struct ConvertArgs {
59    /// Input images and/or directories (PNG/PPM/PAM).
60    #[arg(required = true)]
61    inputs: Vec<PathBuf>,
62    /// Output directory (created outputs are `<stem>.webp`); default: beside input.
63    #[arg(short, long)]
64    output: Option<PathBuf>,
65    /// Encoder effort (ignored with --optimize).
66    #[arg(short, long, value_enum, default_value_t)]
67    method: Method,
68    /// Encode lossily (VP8) instead of losslessly (VP8L).
69    #[arg(long)]
70    lossy: bool,
71    /// Lossy quality 0-100 (higher = larger, closer to source); selects --lossy.
72    #[arg(long)]
73    quality: Option<u8>,
74    /// Try every lossless effort level and keep the smallest output.
75    #[arg(long)]
76    optimize: bool,
77    /// Recurse into subdirectories.
78    #[arg(short, long)]
79    recursive: bool,
80    /// Metadata to embed: all,none,icc,exif,xmp (default: all).
81    #[arg(long, value_enum, value_delimiter = ',')]
82    metadata: Vec<MetadataField>,
83}
84
85/// Arguments for `webp info`.
86#[derive(Debug, clap::Args)]
87struct InfoArgs {
88    /// Input `.webp` file; `-` (the default) reads stdin.
89    #[arg(default_value = "-")]
90    input: PathBuf,
91}
92
93/// Which frames of an animation to emit.
94#[derive(Debug, Clone, Copy, Default, clap::ValueEnum)]
95enum FrameSelection {
96    /// Only the first composited frame (the default).
97    #[default]
98    First,
99    /// Every composited frame, numbered `<stem>-000.<ext>`, ...
100    All,
101}
102
103/// Arguments for `webp decode`.
104#[derive(Debug, clap::Args)]
105struct DecodeArgs {
106    /// Input `.webp` file; `-` (the default) reads stdin.
107    #[arg(default_value = "-")]
108    input: PathBuf,
109    /// Output path; `-` writes stdout.
110    #[arg(short, long)]
111    output: PathBuf,
112    /// Output format; defaults to the `-o` extension, else PNG.
113    #[arg(long, value_enum)]
114    format: Option<OutputFormat>,
115    /// Byte order for raw output only.
116    #[arg(long, value_enum, default_value_t)]
117    layout: Layout,
118    /// For animations: which frames to emit.
119    #[arg(long, value_enum)]
120    frames: Option<FrameSelection>,
121    /// For animations: emit only this 0-based frame.
122    #[arg(long, conflicts_with = "frames")]
123    frame: Option<u32>,
124    /// Metadata to carry into the output: all,none,icc,exif,xmp (default: all).
125    #[arg(long, value_enum, value_delimiter = ',')]
126    metadata: Vec<MetadataField>,
127}
128
129/// Arguments for `webp encode`.
130#[derive(Debug, clap::Args)]
131struct EncodeArgs {
132    /// Input image (PNG/PPM/PAM/raw); `-` (the default) reads stdin.
133    #[arg(default_value = "-")]
134    input: PathBuf,
135    /// Output `.webp` file; `-` writes stdout.
136    #[arg(short, long)]
137    output: PathBuf,
138    /// Input format; defaults to the extension, else the magic bytes, else raw.
139    #[arg(long, value_enum)]
140    input_format: Option<InputFormat>,
141    /// Raw-input width in pixels (required for raw input).
142    #[arg(long)]
143    width: Option<u32>,
144    /// Raw-input height in pixels (required for raw input).
145    #[arg(long)]
146    height: Option<u32>,
147    /// Byte order for raw input only.
148    #[arg(long, value_enum, default_value_t)]
149    layout: Layout,
150    /// Encoder effort.
151    #[arg(short, long, value_enum, default_value_t)]
152    method: Method,
153    /// Encode lossily (VP8) instead of losslessly (VP8L).
154    #[arg(long)]
155    lossy: bool,
156    /// Lossy quality 0-100 (higher = larger, closer to source); selects --lossy.
157    #[arg(long)]
158    quality: Option<u8>,
159    /// Metadata to embed: all,none,icc,exif,xmp (default: all — kinder than cwebp).
160    #[arg(long, value_enum, value_delimiter = ',')]
161    metadata: Vec<MetadataField>,
162}
163
164/// Build the [`EncodeMode`] from the shared effort/quality flags: `--lossy`, or an
165/// explicit `--quality`, selects lossy (VP8) output; otherwise lossless (VP8L).
166fn encode_mode(lossy: bool, quality: Option<u8>, method: Method) -> EncodeMode {
167    if lossy || quality.is_some() {
168        EncodeMode::Lossy {
169            quality: quality.unwrap_or(75),
170            method: method.into(),
171        }
172    } else {
173        EncodeMode::Lossless(method.into())
174    }
175}
176
177/// Parse arguments, run the requested command, and return a process exit code.
178#[must_use]
179pub fn main() -> ExitCode {
180    let cli = Cli::parse();
181    let reporter = Reporter::new(cli.global.verbose, cli.global.quiet);
182    match run(&cli.command, &reporter) {
183        Ok(()) => ExitCode::SUCCESS,
184        Err(err) => {
185            crate::report::error(&err);
186            err.exit_code()
187        },
188    }
189}
190
191fn run(command: &Command, reporter: &Reporter) -> Result<(), CliError> {
192    match command {
193        Command::Decode(args) => decode(args, reporter),
194        Command::Encode(args) => encode(args, reporter),
195        Command::Convert(args) => convert(args, reporter),
196        Command::Info(args) => info(args),
197    }
198}
199
200fn convert(args: &ConvertArgs, reporter: &Reporter) -> Result<(), CliError> {
201    let options = bulk::Options {
202        mode: encode_mode(args.lossy, args.quality, args.method),
203        metadata: Selection::from_fields(&args.metadata),
204        optimize: args.optimize,
205        recursive: args.recursive,
206        output_dir: args.output.clone(),
207    };
208    let outcome = bulk::convert(&args.inputs, &options)?;
209    for (ok, text) in &outcome.lines {
210        if *ok {
211            reporter.detail(text);
212        } else {
213            report::warn(text);
214        }
215    }
216    reporter.status(&format!(
217        "converted {} file(s), {} -> {} bytes{}",
218        outcome.converted,
219        outcome.total_in,
220        outcome.total_out,
221        if outcome.failed > 0 {
222            format!(" ({} failed)", outcome.failed)
223        } else {
224            String::new()
225        },
226    ));
227    if outcome.failed > 0 {
228        return Err(CliError::Format(format!(
229            "{} file(s) failed to convert",
230            outcome.failed
231        )));
232    }
233    Ok(())
234}
235
236fn decode(args: &DecodeArgs, reporter: &Reporter) -> Result<(), CliError> {
237    let source = Source::from_arg(&args.input);
238    let sink = Sink::from_arg(&args.output);
239    let bytes = source.read()?;
240    let format = OutputFormat::resolve(args.format, sink.extension().as_deref());
241    reporter.detail(&format!("decoding {} -> {format:?}", source.label()));
242
243    // Image formats are always RGBA8; only raw honors the requested layout.
244    let layout = if format == OutputFormat::Raw {
245        args.layout.into()
246    } else {
247        webpkit::lossless::PixelLayout::Rgba8
248    };
249    if is_animated(&bytes)? {
250        return decode_animation(args, &bytes, format, &sink, reporter);
251    }
252    let image = codec::decode(&bytes, layout)?;
253    let metadata = Selection::from_fields(&args.metadata).apply(image.metadata());
254    let out = format::write_image(&image, format, &metadata)?;
255    sink.write(&out)?;
256    reporter.status(&format!(
257        "decoded {} -> {} ({}x{}, {} bytes)",
258        source.label(),
259        sink.label(),
260        image.width(),
261        image.height(),
262        out.len(),
263    ));
264    Ok(())
265}
266
267/// Whether the WebP file is animated (an `ANIM` container). Codec-agnostic — works
268/// for a lossy file the same as a lossless one, so `webp decode`/`info` handle both.
269fn is_animated(bytes: &[u8]) -> Result<bool, CliError> {
270    Ok(webpkit::is_animated(bytes)?)
271}
272
273/// Decode an animation, honoring `--frame` / `--frames`.
274fn decode_animation(
275    args: &DecodeArgs,
276    bytes: &[u8],
277    format: OutputFormat,
278    sink: &Sink,
279    reporter: &Reporter,
280) -> Result<(), CliError> {
281    let frames = webpkit::decode_frames(bytes)?;
282    let images: Vec<webpkit::lossless::Image> = frames
283        .composited()
284        .map(|frame| frame.map(webpkit::lossless::CompositedFrame::into_image))
285        .collect::<Result<_, _>>()?;
286    if images.is_empty() {
287        return Err(CliError::Format("animation has no frames".to_owned()));
288    }
289    let no_meta = webpkit::lossless::Metadata::none();
290
291    if let Some(index) = args.frame {
292        let image = images
293            .get(index as usize)
294            .ok_or_else(|| CliError::Usage(format!("frame {index} is out of range")))?;
295        let out = format::write_image(image, format, &no_meta)?;
296        sink.write(&out)?;
297        reporter.status(&format!("decoded frame {index} -> {}", sink.label()));
298        return Ok(());
299    }
300
301    match args.frames.unwrap_or_default() {
302        FrameSelection::First => {
303            let out = format::write_image(&images[0], format, &no_meta)?;
304            sink.write(&out)?;
305            reporter.status(&format!("decoded first frame -> {}", sink.label()));
306        },
307        FrameSelection::All => {
308            let base = match sink {
309                Sink::File(path) => path.clone(),
310                Sink::Stdout => {
311                    return Err(CliError::Usage(
312                        "`--frames all` needs a file output, not stdout".to_owned(),
313                    ));
314                },
315            };
316            for (index, image) in images.iter().enumerate() {
317                let path = numbered_path(&base, index);
318                let out = format::write_image(image, format, &no_meta)?;
319                Sink::File(path).write(&out)?;
320            }
321            reporter.status(&format!(
322                "decoded {} frames -> {}",
323                images.len(),
324                base.display()
325            ));
326        },
327    }
328    Ok(())
329}
330
331/// Insert a zero-padded frame index before the extension: `out.png` → `out-000.png`.
332fn numbered_path(base: &std::path::Path, index: usize) -> PathBuf {
333    let stem = base
334        .file_stem()
335        .map(|s| s.to_string_lossy().into_owned())
336        .unwrap_or_default();
337    let numbered = format!("{stem}-{index:03}");
338    match base.extension() {
339        Some(ext) => base.with_file_name(numbered).with_extension(ext),
340        None => base.with_file_name(numbered),
341    }
342}
343
344fn encode(args: &EncodeArgs, reporter: &Reporter) -> Result<(), CliError> {
345    let source = Source::from_arg(&args.input);
346    let sink = Sink::from_arg(&args.output);
347    let bytes = source.read()?;
348    let format = InputFormat::resolve(args.input_format, source.extension().as_deref(), &bytes);
349    reporter.detail(&format!("encoding {format:?} {}", source.label()));
350
351    let raw = match (args.width, args.height) {
352        (Some(width), Some(height)) => Some(RawParams {
353            width,
354            height,
355            layout: args.layout.into(),
356        }),
357        _ => None,
358    };
359    let image = format::read_image(&bytes, format, raw)?;
360    let metadata = Selection::from_fields(&args.metadata).apply(image.metadata());
361    let mode = encode_mode(args.lossy, args.quality, args.method);
362    let webp = codec::encode(&image, mode, metadata)?;
363    sink.write(&webp)?;
364    reporter.status(&format!(
365        "encoded {} -> {} ({}x{}, {} bytes, {})",
366        source.label(),
367        sink.label(),
368        image.width(),
369        image.height(),
370        webp.len(),
371        ratio(bytes.len(), webp.len()),
372    ));
373    Ok(())
374}
375
376/// Format the output-to-input size ratio as a percentage string, e.g. `41.2%`.
377fn ratio(input_len: usize, output_len: usize) -> String {
378    if input_len == 0 {
379        return "n/a".to_owned();
380    }
381    let permille = output_len as u128 * 1000 / input_len as u128;
382    format!("{}.{}%", permille / 10, permille % 10)
383}
384
385#[allow(
386    clippy::print_stdout,
387    reason = "info prints its report to stdout by design"
388)]
389fn info(args: &InfoArgs) -> Result<(), CliError> {
390    let source = Source::from_arg(&args.input);
391    let bytes = source.read()?;
392    let mut lines = vec![format!("File:       {}", source.label())];
393    if is_animated(&bytes)? {
394        lines.extend(animation_lines(&bytes)?);
395    } else {
396        let image = webpkit::decode(&bytes)?;
397        lines.extend(still_lines(&bytes, &image));
398    }
399    for line in &lines {
400        println!("{line}");
401    }
402    Ok(())
403}
404
405/// Summary lines for a still image, labeling the codec from the container's
406/// image chunk (`VP8L` lossless vs `VP8 ` lossy).
407fn still_lines(bytes: &[u8], image: &webpkit::lossless::Image) -> Vec<String> {
408    let format = if bytes.windows(4).any(|w| w == b"VP8L") {
409        "WebP VP8L (lossless)"
410    } else if bytes.windows(4).any(|w| w == b"VP8 ") {
411        "WebP VP8 (lossy)"
412    } else {
413        "WebP"
414    };
415    vec![
416        format!("Format:     {format}"),
417        format!("Dimensions: {}x{}", image.width(), image.height()),
418        format!("Alpha:      {}", yes_no(image.has_alpha())),
419        format!("Metadata:   {}", metadata_summary(image.metadata())),
420    ]
421}
422
423/// Summary lines for an animation.
424fn animation_lines(bytes: &[u8]) -> Result<Vec<String>, CliError> {
425    let frames = webpkit::decode_frames(bytes)?;
426    let anim = frames.anim_info();
427    let loops = if anim.loop_count == 0 {
428        "forever".to_owned()
429    } else {
430        format!("{} time(s)", anim.loop_count)
431    };
432    let count = frames.composited().count();
433    Ok(vec![
434        "Format:     WebP animation".to_owned(),
435        format!(
436            "Canvas:     {}x{}",
437            anim.canvas.width(),
438            anim.canvas.height()
439        ),
440        format!("Loop:       {loops}"),
441        format!("Frames:     {count}"),
442    ])
443}
444
445/// Comma-list the metadata kinds present, or `none`.
446fn metadata_summary(metadata: &webpkit::lossless::Metadata) -> String {
447    let mut parts = Vec::new();
448    if metadata.icc_profile.is_some() {
449        parts.push("ICC");
450    }
451    if metadata.exif.is_some() {
452        parts.push("Exif");
453    }
454    if metadata.xmp.is_some() {
455        parts.push("XMP");
456    }
457    if parts.is_empty() {
458        "none".to_owned()
459    } else {
460        parts.join(", ")
461    }
462}
463
464const fn yes_no(value: bool) -> &'static str {
465    if value { "yes" } else { "no" }
466}