use std::{path::PathBuf, process::ExitCode};
use clap::{Parser, Subcommand};
use crate::{
bulk,
cli::{Layout, Method},
codec::{self, EncodeMode},
error::CliError,
format::{self, InputFormat, OutputFormat, raw::RawParams},
io::{Sink, Source},
metadata::{MetadataField, Selection},
report::{self, Reporter},
};
#[derive(Debug, Parser)]
#[command(name = "webp", version, about, long_about = None)]
struct Cli {
#[command(flatten)]
global: GlobalArgs,
#[command(subcommand)]
command: Command,
}
#[derive(Debug, clap::Args)]
struct GlobalArgs {
#[arg(short, long, global = true, action = clap::ArgAction::Count)]
verbose: u8,
#[arg(short, long, global = true, conflicts_with = "verbose")]
quiet: bool,
}
#[derive(Debug, Subcommand)]
enum Command {
Decode(DecodeArgs),
Encode(EncodeArgs),
Convert(ConvertArgs),
Info(InfoArgs),
}
#[derive(Debug, clap::Args)]
struct ConvertArgs {
#[arg(required = true)]
inputs: Vec<PathBuf>,
#[arg(short, long)]
output: Option<PathBuf>,
#[arg(short, long, value_enum, default_value_t)]
method: Method,
#[arg(long)]
lossy: bool,
#[arg(long)]
quality: Option<u8>,
#[arg(long)]
optimize: bool,
#[arg(short, long)]
recursive: bool,
#[arg(long, value_enum, value_delimiter = ',')]
metadata: Vec<MetadataField>,
}
#[derive(Debug, clap::Args)]
struct InfoArgs {
#[arg(default_value = "-")]
input: PathBuf,
}
#[derive(Debug, Clone, Copy, Default, clap::ValueEnum)]
enum FrameSelection {
#[default]
First,
All,
}
#[derive(Debug, clap::Args)]
struct DecodeArgs {
#[arg(default_value = "-")]
input: PathBuf,
#[arg(short, long)]
output: PathBuf,
#[arg(long, value_enum)]
format: Option<OutputFormat>,
#[arg(long, value_enum, default_value_t)]
layout: Layout,
#[arg(long, value_enum)]
frames: Option<FrameSelection>,
#[arg(long, conflicts_with = "frames")]
frame: Option<u32>,
#[arg(long, value_enum, value_delimiter = ',')]
metadata: Vec<MetadataField>,
}
#[derive(Debug, clap::Args)]
struct EncodeArgs {
#[arg(default_value = "-")]
input: PathBuf,
#[arg(short, long)]
output: PathBuf,
#[arg(long, value_enum)]
input_format: Option<InputFormat>,
#[arg(long)]
width: Option<u32>,
#[arg(long)]
height: Option<u32>,
#[arg(long, value_enum, default_value_t)]
layout: Layout,
#[arg(short, long, value_enum, default_value_t)]
method: Method,
#[arg(long)]
lossy: bool,
#[arg(long)]
quality: Option<u8>,
#[arg(long, value_enum, value_delimiter = ',')]
metadata: Vec<MetadataField>,
}
fn encode_mode(lossy: bool, quality: Option<u8>, method: Method) -> EncodeMode {
if lossy || quality.is_some() {
EncodeMode::Lossy {
quality: quality.unwrap_or(75),
method: method.into(),
}
} else {
EncodeMode::Lossless(method.into())
}
}
#[must_use]
pub fn main() -> ExitCode {
let cli = Cli::parse();
let reporter = Reporter::new(cli.global.verbose, cli.global.quiet);
match run(&cli.command, &reporter) {
Ok(()) => ExitCode::SUCCESS,
Err(err) => {
crate::report::error(&err);
err.exit_code()
},
}
}
fn run(command: &Command, reporter: &Reporter) -> Result<(), CliError> {
match command {
Command::Decode(args) => decode(args, reporter),
Command::Encode(args) => encode(args, reporter),
Command::Convert(args) => convert(args, reporter),
Command::Info(args) => info(args),
}
}
fn convert(args: &ConvertArgs, reporter: &Reporter) -> Result<(), CliError> {
let options = bulk::Options {
mode: encode_mode(args.lossy, args.quality, args.method),
metadata: Selection::from_fields(&args.metadata),
optimize: args.optimize,
recursive: args.recursive,
output_dir: args.output.clone(),
};
let outcome = bulk::convert(&args.inputs, &options)?;
for (ok, text) in &outcome.lines {
if *ok {
reporter.detail(text);
} else {
report::warn(text);
}
}
reporter.status(&format!(
"converted {} file(s), {} -> {} bytes{}",
outcome.converted,
outcome.total_in,
outcome.total_out,
if outcome.failed > 0 {
format!(" ({} failed)", outcome.failed)
} else {
String::new()
},
));
if outcome.failed > 0 {
return Err(CliError::Format(format!(
"{} file(s) failed to convert",
outcome.failed
)));
}
Ok(())
}
fn decode(args: &DecodeArgs, reporter: &Reporter) -> Result<(), CliError> {
let source = Source::from_arg(&args.input);
let sink = Sink::from_arg(&args.output);
let bytes = source.read()?;
let format = OutputFormat::resolve(args.format, sink.extension().as_deref());
reporter.detail(&format!("decoding {} -> {format:?}", source.label()));
let layout = if format == OutputFormat::Raw {
args.layout.into()
} else {
webpkit::lossless::PixelLayout::Rgba8
};
if is_animated(&bytes)? {
return decode_animation(args, &bytes, format, &sink, reporter);
}
let image = codec::decode(&bytes, layout)?;
let metadata = Selection::from_fields(&args.metadata).apply(image.metadata());
let out = format::write_image(&image, format, &metadata)?;
sink.write(&out)?;
reporter.status(&format!(
"decoded {} -> {} ({}x{}, {} bytes)",
source.label(),
sink.label(),
image.width(),
image.height(),
out.len(),
));
Ok(())
}
fn is_animated(bytes: &[u8]) -> Result<bool, CliError> {
Ok(webpkit::is_animated(bytes)?)
}
fn decode_animation(
args: &DecodeArgs,
bytes: &[u8],
format: OutputFormat,
sink: &Sink,
reporter: &Reporter,
) -> Result<(), CliError> {
let frames = webpkit::decode_frames(bytes)?;
let images: Vec<webpkit::lossless::Image> = frames
.composited()
.map(|frame| frame.map(webpkit::lossless::CompositedFrame::into_image))
.collect::<Result<_, _>>()?;
if images.is_empty() {
return Err(CliError::Format("animation has no frames".to_owned()));
}
let no_meta = webpkit::lossless::Metadata::none();
if let Some(index) = args.frame {
let image = images
.get(index as usize)
.ok_or_else(|| CliError::Usage(format!("frame {index} is out of range")))?;
let out = format::write_image(image, format, &no_meta)?;
sink.write(&out)?;
reporter.status(&format!("decoded frame {index} -> {}", sink.label()));
return Ok(());
}
match args.frames.unwrap_or_default() {
FrameSelection::First => {
let out = format::write_image(&images[0], format, &no_meta)?;
sink.write(&out)?;
reporter.status(&format!("decoded first frame -> {}", sink.label()));
},
FrameSelection::All => {
let base = match sink {
Sink::File(path) => path.clone(),
Sink::Stdout => {
return Err(CliError::Usage(
"`--frames all` needs a file output, not stdout".to_owned(),
));
},
};
for (index, image) in images.iter().enumerate() {
let path = numbered_path(&base, index);
let out = format::write_image(image, format, &no_meta)?;
Sink::File(path).write(&out)?;
}
reporter.status(&format!(
"decoded {} frames -> {}",
images.len(),
base.display()
));
},
}
Ok(())
}
fn numbered_path(base: &std::path::Path, index: usize) -> PathBuf {
let stem = base
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let numbered = format!("{stem}-{index:03}");
match base.extension() {
Some(ext) => base.with_file_name(numbered).with_extension(ext),
None => base.with_file_name(numbered),
}
}
fn encode(args: &EncodeArgs, reporter: &Reporter) -> Result<(), CliError> {
let source = Source::from_arg(&args.input);
let sink = Sink::from_arg(&args.output);
let bytes = source.read()?;
let format = InputFormat::resolve(args.input_format, source.extension().as_deref(), &bytes);
reporter.detail(&format!("encoding {format:?} {}", source.label()));
let raw = match (args.width, args.height) {
(Some(width), Some(height)) => Some(RawParams {
width,
height,
layout: args.layout.into(),
}),
_ => None,
};
let image = format::read_image(&bytes, format, raw)?;
let metadata = Selection::from_fields(&args.metadata).apply(image.metadata());
let mode = encode_mode(args.lossy, args.quality, args.method);
let webp = codec::encode(&image, mode, metadata)?;
sink.write(&webp)?;
reporter.status(&format!(
"encoded {} -> {} ({}x{}, {} bytes, {})",
source.label(),
sink.label(),
image.width(),
image.height(),
webp.len(),
ratio(bytes.len(), webp.len()),
));
Ok(())
}
fn ratio(input_len: usize, output_len: usize) -> String {
if input_len == 0 {
return "n/a".to_owned();
}
let permille = output_len as u128 * 1000 / input_len as u128;
format!("{}.{}%", permille / 10, permille % 10)
}
#[allow(
clippy::print_stdout,
reason = "info prints its report to stdout by design"
)]
fn info(args: &InfoArgs) -> Result<(), CliError> {
let source = Source::from_arg(&args.input);
let bytes = source.read()?;
let mut lines = vec![format!("File: {}", source.label())];
if is_animated(&bytes)? {
lines.extend(animation_lines(&bytes)?);
} else {
let image = webpkit::decode(&bytes)?;
lines.extend(still_lines(&bytes, &image));
}
for line in &lines {
println!("{line}");
}
Ok(())
}
fn still_lines(bytes: &[u8], image: &webpkit::lossless::Image) -> Vec<String> {
let format = if bytes.windows(4).any(|w| w == b"VP8L") {
"WebP VP8L (lossless)"
} else if bytes.windows(4).any(|w| w == b"VP8 ") {
"WebP VP8 (lossy)"
} else {
"WebP"
};
vec![
format!("Format: {format}"),
format!("Dimensions: {}x{}", image.width(), image.height()),
format!("Alpha: {}", yes_no(image.has_alpha())),
format!("Metadata: {}", metadata_summary(image.metadata())),
]
}
fn animation_lines(bytes: &[u8]) -> Result<Vec<String>, CliError> {
let frames = webpkit::decode_frames(bytes)?;
let anim = frames.anim_info();
let loops = if anim.loop_count == 0 {
"forever".to_owned()
} else {
format!("{} time(s)", anim.loop_count)
};
let count = frames.composited().count();
Ok(vec![
"Format: WebP animation".to_owned(),
format!(
"Canvas: {}x{}",
anim.canvas.width(),
anim.canvas.height()
),
format!("Loop: {loops}"),
format!("Frames: {count}"),
])
}
fn metadata_summary(metadata: &webpkit::lossless::Metadata) -> String {
let mut parts = Vec::new();
if metadata.icc_profile.is_some() {
parts.push("ICC");
}
if metadata.exif.is_some() {
parts.push("Exif");
}
if metadata.xmp.is_some() {
parts.push("XMP");
}
if parts.is_empty() {
"none".to_owned()
} else {
parts.join(", ")
}
}
const fn yes_no(value: bool) -> &'static str {
if value { "yes" } else { "no" }
}