bwm 0.1.0

Image watermarking over borrowed RGB/RGBA buffers
Documentation
use std::{env, fs::File, io::BufWriter, path::PathBuf, process};

use bwm::{
    capacity, embed_text, extract_text, ColorMode, ImageBufferRef, PixelFormat, RobustnessProfile,
    ThreadConfig, WatermarkConfig, WatermarkKey, WatermarkStrength,
};
use image::{codecs::jpeg::JpegEncoder, imageops, ImageReader, RgbImage};

fn main() {
    if let Err(err) = run() {
        eprintln!("bwm: {err}");
        process::exit(1);
    }
}

fn run() -> Result<(), String> {
    let mut args = env::args().skip(1);
    let command = args.next().ok_or_else(usage)?;
    let options = Options::parse(args.collect())?;

    match command.as_str() {
        "embed" => {
            let config = options.config()?;
            let input = options
                .input
                .ok_or_else(|| "--input is required".to_string())?;
            let output = options
                .output
                .ok_or_else(|| "--output is required".to_string())?;
            let text = options
                .text
                .ok_or_else(|| "--text is required".to_string())?;

            let image = load_rgb8(&input)?;
            let image_ref = ImageBufferRef::new(
                image.data.as_raw(),
                image.width,
                image.height,
                (image.width as usize) * 3,
                PixelFormat::Rgb8,
            );
            let info = capacity(image_ref, &config).map_err(|err| err.to_string())?;
            if text.len() > info.max_payload_bytes {
                return Err(format!(
                    "payload is {} bytes, but robust capacity is {} bytes",
                    text.len(),
                    info.max_payload_bytes
                ));
            }

            let watermarked =
                embed_text(image_ref, &text, &config).map_err(|err| err.to_string())?;
            save_rgb8_jpeg(
                &output,
                watermarked.width,
                watermarked.height,
                &watermarked.data,
                options.quality,
            )?;
        }
        "extract" => {
            let config = options.config()?;
            let input = options
                .input
                .ok_or_else(|| "--input is required".to_string())?;
            let image = load_rgb8(&input)?;
            let text = extract_from_rgb_with_orientation_fallback(&image.data, &config)?;
            print!("{text}");
        }
        "capacity" => {
            let config = options.config()?;
            let input = options
                .input
                .ok_or_else(|| "--input is required".to_string())?;
            let image = load_rgb8(&input)?;
            let image_ref = ImageBufferRef::new(
                image.data.as_raw(),
                image.width,
                image.height,
                (image.width as usize) * 3,
                PixelFormat::Rgb8,
            );
            let info = capacity(image_ref, &config).map_err(|err| err.to_string())?;
            println!("tiles: {}", info.tile_count);
            println!("repetition_factor: {}", info.repetition_factor);
            println!("max_payload_bytes: {}", info.max_payload_bytes);
        }
        _ => return Err(usage()),
    }

    Ok(())
}

fn extract_from_rgb_with_orientation_fallback(
    image: &RgbImage,
    config: &WatermarkConfig,
) -> Result<String, String> {
    if let Ok(text) = extract_from_rgb(image, config) {
        return Ok(text);
    }

    let rotated_180 = imageops::rotate180(image);
    if let Ok(text) = extract_from_rgb(&rotated_180, config) {
        return Ok(text);
    }

    let rotated_90 = imageops::rotate90(image);
    if let Ok(text) = extract_from_rgb(&rotated_90, config) {
        return Ok(text);
    }

    let rotated_270 = imageops::rotate270(image);
    extract_from_rgb(&rotated_270, config).map_err(|err| err.to_string())
}

fn extract_from_rgb(
    image: &RgbImage,
    config: &WatermarkConfig,
) -> Result<String, bwm::WatermarkError> {
    let (width, height) = image.dimensions();
    let image_ref = ImageBufferRef::new(
        image.as_raw(),
        width,
        height,
        (width as usize) * 3,
        PixelFormat::Rgb8,
    );
    extract_text(image_ref, config)
}

#[derive(Debug)]
struct Options {
    input: Option<PathBuf>,
    output: Option<PathBuf>,
    key: Option<WatermarkKey>,
    text: Option<String>,
    strength: WatermarkStrength,
    robustness: RobustnessProfile,
    quality: u8,
}

impl Options {
    fn parse(args: Vec<String>) -> Result<Self, String> {
        let mut options = Self {
            input: None,
            output: None,
            key: None,
            text: None,
            strength: WatermarkStrength::High,
            robustness: RobustnessProfile::Robust,
            quality: 100,
        };

        let mut args = args.into_iter();
        while let Some(arg) = args.next() {
            match arg.as_str() {
                "--input" => options.input = Some(next_path(&mut args, "--input")?),
                "--output" => options.output = Some(next_path(&mut args, "--output")?),
                "--key" => {
                    let key = next_value(&mut args, "--key")?;
                    options.key =
                        Some(WatermarkKey::from_hex(&key).map_err(|err| err.to_string())?);
                }
                "--text" => options.text = Some(next_value(&mut args, "--text")?),
                "--strength" => {
                    let value = next_value(&mut args, "--strength")?;
                    options.strength = parse_strength(&value)?;
                }
                "--robustness" => {
                    let value = next_value(&mut args, "--robustness")?;
                    options.robustness = parse_robustness(&value)?;
                }
                "--quality" => {
                    let value = next_value(&mut args, "--quality")?;
                    let quality = value
                        .parse::<u8>()
                        .map_err(|_| "--quality must be an integer from 1 to 100".to_string())?;
                    if !(1..=100).contains(&quality) {
                        return Err("--quality must be from 1 to 100".to_string());
                    }
                    options.quality = quality;
                }
                "--help" | "-h" => return Err(usage()),
                unknown => return Err(format!("unknown argument: {unknown}\n{}", usage())),
            }
        }

        Ok(options)
    }

    fn config(&self) -> Result<WatermarkConfig, String> {
        Ok(WatermarkConfig {
            key: self.key.ok_or_else(|| "--key is required".to_string())?,
            strength: self.strength,
            robustness: self.robustness,
            color_mode: ColorMode::LumaOnly,
            threads: ThreadConfig::Single,
        })
    }
}

#[derive(Debug)]
struct LoadedRgb {
    data: image::RgbImage,
    width: u32,
    height: u32,
}

fn load_rgb8(path: &PathBuf) -> Result<LoadedRgb, String> {
    let image = ImageReader::open(path)
        .map_err(|err| format!("failed to open {}: {err}", path.display()))?
        .decode()
        .map_err(|err| format!("failed to decode {}: {err}", path.display()))?
        .to_rgb8();
    let (width, height) = image.dimensions();
    Ok(LoadedRgb {
        data: image,
        width,
        height,
    })
}

fn save_rgb8_jpeg(
    path: &PathBuf,
    width: u32,
    height: u32,
    data: &[u8],
    quality: u8,
) -> Result<(), String> {
    let file =
        File::create(path).map_err(|err| format!("failed to create {}: {err}", path.display()))?;
    let mut writer = BufWriter::new(file);
    let mut encoder = JpegEncoder::new_with_quality(&mut writer, quality);
    encoder
        .encode(data, width, height, image::ExtendedColorType::Rgb8)
        .map_err(|err| format!("failed to encode {}: {err}", path.display()))
}

fn next_value(args: &mut impl Iterator<Item = String>, name: &str) -> Result<String, String> {
    args.next()
        .ok_or_else(|| format!("{name} requires a value"))
}

fn next_path(args: &mut impl Iterator<Item = String>, name: &str) -> Result<PathBuf, String> {
    Ok(PathBuf::from(next_value(args, name)?))
}

fn parse_strength(value: &str) -> Result<WatermarkStrength, String> {
    match value {
        "low" => Ok(WatermarkStrength::Low),
        "medium" => Ok(WatermarkStrength::Medium),
        "high" => Ok(WatermarkStrength::High),
        _ => Err("--strength must be low, medium, or high".to_string()),
    }
}

fn parse_robustness(value: &str) -> Result<RobustnessProfile, String> {
    match value {
        "fast" => Ok(RobustnessProfile::Fast),
        "balanced" => Ok(RobustnessProfile::Balanced),
        "robust" => Ok(RobustnessProfile::Robust),
        _ => Err("--robustness must be fast, balanced, or robust".to_string()),
    }
}

fn usage() -> String {
    "usage:
  bwm embed --key <64-hex> --text <text> --input <in.jpg> --output <out.jpg> [--quality 100]
  bwm extract --key <64-hex> --input <watermarked.jpg>
  bwm capacity --key <64-hex> --input <in.jpg>"
        .to_string()
}