1use std::{ffi::OsString, path::PathBuf, process::ExitCode};
7
8use webpkit::lossless::{Image, PixelLayout};
9
10use crate::{
11 codec,
12 error::CliError,
13 format::{self, OutputFormat},
14 io::{Sink, Source},
15 report::Reporter,
16};
17
18#[must_use]
20pub fn main() -> ExitCode {
21 let args: Vec<OsString> = std::env::args_os().skip(1).collect();
22 match run(&args) {
23 Ok(()) => ExitCode::SUCCESS,
24 Err(err) => {
25 crate::report::error(&err);
26 err.exit_code()
27 },
28 }
29}
30
31#[derive(Default)]
33struct Config {
34 input: Option<PathBuf>,
35 output: Option<PathBuf>,
36 format: Option<OutputFormat>,
37 flip: bool,
38 alpha: bool,
39 verbose: u8,
40 quiet: bool,
41}
42
43fn run(args: &[OsString]) -> Result<(), CliError> {
44 let config = match parse(args)? {
45 Parsed::Run(config) => config,
46 Parsed::Handled => return Ok(()),
47 };
48 let reporter = Reporter::new(config.verbose, config.quiet);
49 let input = config
50 .input
51 .ok_or_else(|| CliError::Usage("no input file (use `-` for stdin)".to_owned()))?;
52 let output = config
53 .output
54 .ok_or_else(|| CliError::Usage("no output file (use `-o <file>`, or `-o -`)".to_owned()))?;
55
56 let source = Source::from_arg(&input);
57 let sink = Sink::from_arg(&output);
58 let bytes = source.read()?;
59 let mut image = codec::decode(&bytes, PixelLayout::Rgba8)?;
60 if config.alpha {
61 image = alpha_as_gray(&image);
62 }
63 if config.flip {
64 image = flip_vertically(&image);
65 }
66 let format = OutputFormat::resolve(config.format, sink.extension().as_deref());
67 let out = format::write_image(&image, format, image.metadata())?;
68 sink.write(&out)?;
69 reporter.status(&format!(
70 "{} -> {} ({}x{}, {} bytes)",
71 source.label(),
72 sink.label(),
73 image.width(),
74 image.height(),
75 out.len(),
76 ));
77 Ok(())
78}
79
80enum Parsed {
81 Run(Box<Config>),
82 Handled,
83}
84
85fn parse(args: &[OsString]) -> Result<Parsed, CliError> {
86 let mut config = Config::default();
87 let mut index = 0;
88 while index < args.len() {
89 let token = args[index].to_string_lossy().into_owned();
90 match token.as_str() {
91 "-h" | "-help" | "--help" => {
92 print_help();
93 return Ok(Parsed::Handled);
94 },
95 "-version" | "--version" => {
96 print_version();
97 return Ok(Parsed::Handled);
98 },
99 "-o" => {
100 index += 1;
101 let value = args
102 .get(index)
103 .ok_or_else(|| CliError::Usage("`-o` needs a value".to_owned()))?;
104 config.output = Some(PathBuf::from(value));
105 },
106 "-png" => config.format = Some(OutputFormat::Png),
107 "-ppm" => config.format = Some(OutputFormat::Ppm),
108 "-pam" => config.format = Some(OutputFormat::Pam),
109 "-flip" => config.flip = true,
110 "-alpha" => config.alpha = true,
111 "-quiet" => config.quiet = true,
112 "-v" => config.verbose = config.verbose.saturating_add(1),
113 "-nofancy" | "-nofilter" | "-nodither" | "-alpha_dither" | "-mt" | "-incremental"
115 | "-noasm" => {},
116 "-dither" => {
117 index += 1; },
119 "-yuv" | "-pgm" => {
120 return Err(CliError::Usage(format!(
121 "`{token}` needs a lossy RGB→YUV conversion; use -png/-ppm/-pam"
122 )));
123 },
124 "-bmp" | "-tiff" => {
125 return Err(CliError::Usage(format!(
126 "`{token}` output is not supported; use -png, -ppm, or -pam"
127 )));
128 },
129 "-crop" | "-resize" | "-scale" => {
130 return Err(CliError::Usage(format!("`{token}` is not supported yet")));
131 },
132 "--" => {
133 index += 1;
134 if index < args.len() {
135 config.input = Some(PathBuf::from(&args[index]));
136 }
137 },
138 other if other.starts_with('-') && other.len() > 1 => {
139 return Err(CliError::Usage(format!("unknown option `{other}`")));
140 },
141 _ => config.input = Some(PathBuf::from(&args[index])),
142 }
143 index += 1;
144 }
145 Ok(Parsed::Run(Box::new(config)))
146}
147
148fn alpha_as_gray(image: &Image) -> Image {
151 let mut pixels = image.as_bytes().to_vec();
152 for px in pixels.chunks_exact_mut(4) {
153 let a = px[3];
154 px[0] = a;
155 px[1] = a;
156 px[2] = a;
157 px[3] = 0xff;
158 }
159 Image::from_parts(
160 image.dimensions(),
161 PixelLayout::Rgba8,
162 pixels,
163 false,
164 image.metadata().clone(),
165 )
166}
167
168fn flip_vertically(image: &Image) -> Image {
170 let width = image.width() as usize;
171 let row = width * 4;
172 let mut pixels = Vec::with_capacity(image.as_bytes().len());
173 for chunk in image.as_bytes().chunks_exact(row).rev() {
174 pixels.extend_from_slice(chunk);
175 }
176 Image::from_parts(
177 image.dimensions(),
178 PixelLayout::Rgba8,
179 pixels,
180 image.has_alpha(),
181 image.metadata().clone(),
182 )
183}
184
185#[allow(
186 clippy::print_stdout,
187 reason = "help/version print to stdout by CLI convention"
188)]
189fn print_help() {
190 println!(
191 "dwebp (webpkit) — decode WebP VP8L (lossless) to PNG/PPM/PAM\n\n\
192 Usage: dwebp [options] <input.webp> -o <output>\n\n\
193 Options:\n\
194 \x20 -o <file> output file (`-` for stdout)\n\
195 \x20 -png PNG output (default)\n\
196 \x20 -ppm / -pam netpbm output\n\
197 \x20 -flip flip vertically\n\
198 \x20 -alpha output the alpha plane as grayscale\n\
199 \x20 -quiet / -v quieter / more verbose\n\
200 \x20 -version print version\n"
201 );
202}
203
204#[allow(
205 clippy::print_stdout,
206 reason = "help/version print to stdout by CLI convention"
207)]
208fn print_version() {
209 println!("dwebp (webpkit) {}", env!("CARGO_PKG_VERSION"));
210}