1use 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#[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#[derive(Debug, clap::Args)]
35struct GlobalArgs {
36 #[arg(short, long, global = true, action = clap::ArgAction::Count)]
38 verbose: u8,
39 #[arg(short, long, global = true, conflicts_with = "verbose")]
41 quiet: bool,
42}
43
44#[derive(Debug, Subcommand)]
45enum Command {
46 Decode(DecodeArgs),
48 Encode(EncodeArgs),
50 Convert(ConvertArgs),
52 Info(InfoArgs),
54}
55
56#[derive(Debug, clap::Args)]
58struct ConvertArgs {
59 #[arg(required = true)]
61 inputs: Vec<PathBuf>,
62 #[arg(short, long)]
64 output: Option<PathBuf>,
65 #[arg(short, long, value_enum, default_value_t)]
67 method: Method,
68 #[arg(long)]
70 lossy: bool,
71 #[arg(long)]
73 quality: Option<u8>,
74 #[arg(long)]
76 optimize: bool,
77 #[arg(short, long)]
79 recursive: bool,
80 #[arg(long, value_enum, value_delimiter = ',')]
82 metadata: Vec<MetadataField>,
83}
84
85#[derive(Debug, clap::Args)]
87struct InfoArgs {
88 #[arg(default_value = "-")]
90 input: PathBuf,
91}
92
93#[derive(Debug, Clone, Copy, Default, clap::ValueEnum)]
95enum FrameSelection {
96 #[default]
98 First,
99 All,
101}
102
103#[derive(Debug, clap::Args)]
105struct DecodeArgs {
106 #[arg(default_value = "-")]
108 input: PathBuf,
109 #[arg(short, long)]
111 output: PathBuf,
112 #[arg(long, value_enum)]
114 format: Option<OutputFormat>,
115 #[arg(long, value_enum, default_value_t)]
117 layout: Layout,
118 #[arg(long, value_enum)]
120 frames: Option<FrameSelection>,
121 #[arg(long, conflicts_with = "frames")]
123 frame: Option<u32>,
124 #[arg(long, value_enum, value_delimiter = ',')]
126 metadata: Vec<MetadataField>,
127}
128
129#[derive(Debug, clap::Args)]
131struct EncodeArgs {
132 #[arg(default_value = "-")]
134 input: PathBuf,
135 #[arg(short, long)]
137 output: PathBuf,
138 #[arg(long, value_enum)]
140 input_format: Option<InputFormat>,
141 #[arg(long)]
143 width: Option<u32>,
144 #[arg(long)]
146 height: Option<u32>,
147 #[arg(long, value_enum, default_value_t)]
149 layout: Layout,
150 #[arg(short, long, value_enum, default_value_t)]
152 method: Method,
153 #[arg(long)]
155 lossy: bool,
156 #[arg(long)]
158 quality: Option<u8>,
159 #[arg(long, value_enum, value_delimiter = ',')]
161 metadata: Vec<MetadataField>,
162}
163
164fn 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#[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 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
267fn is_animated(bytes: &[u8]) -> Result<bool, CliError> {
270 Ok(webpkit::is_animated(bytes)?)
271}
272
273fn 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
331fn 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
376fn 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
405fn 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
423fn 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
445fn 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}