caprs 0.1.1

Image-based click, slide, drag and rotate CAPTCHA generation and verification
Documentation
use std::ops::RangeInclusive;

use image::imageops::{self, FilterType};
use image::{Rgba, RgbaImage};
use rand::Rng;
use rand::seq::IndexedRandom;

use crate::{CaptchaError, Size};

const MAX_PIXELS: u64 = 4_194_304;
const MAX_SIDE: u32 = 4096;
pub(crate) const TRANSPARENT: Rgba<u8> = Rgba([0, 0, 0, 0]);

pub(crate) fn check_size(size: Size, field: &'static str) -> Result<(), CaptchaError> {
    if !(1..=MAX_SIDE).contains(&size.width)
        || !(1..=MAX_SIDE).contains(&size.height)
        || u64::from(size.width) * u64::from(size.height) > MAX_PIXELS
    {
        return Err(CaptchaError::invalid(
            field,
            "dimensions must be in 1..=4096 and contain at most 4194304 pixels",
        ));
    }
    Ok(())
}

pub(crate) fn check_range(
    range: &RangeInclusive<u32>,
    limits: RangeInclusive<u32>,
    field: &'static str,
) -> Result<(), CaptchaError> {
    if range.is_empty() || !limits.contains(range.start()) || !limits.contains(range.end()) {
        return Err(CaptchaError::invalid(
            field,
            "range is empty or outside the allowed bounds",
        ));
    }
    Ok(())
}

pub(crate) fn check_image(image: &RgbaImage, field: &'static str) -> Result<(), CaptchaError> {
    if image.width() == 0 || image.height() == 0 {
        return Err(CaptchaError::invalid(field, "image has an empty dimension"));
    }
    Ok(())
}

pub(crate) fn check_angles(
    angles: &[RangeInclusive<i16>],
    span: RangeInclusive<i16>,
) -> Result<(), CaptchaError> {
    if angles.iter().any(|angle| {
        angle.is_empty() || !span.contains(angle.start()) || !span.contains(angle.end())
    }) {
        return Err(CaptchaError::invalid(
            "angles",
            "range is empty or outside the allowed bounds",
        ));
    }
    Ok(())
}

pub(crate) fn angle(angles: &[RangeInclusive<i16>], rng: &mut impl Rng) -> i16 {
    angles
        .choose(rng)
        .map_or(0, |range| rng.random_range(range.clone()))
}

pub(crate) fn crop_background(source: &RgbaImage, size: Size, rng: &mut impl Rng) -> RgbaImage {
    let width = source.width().min(size.width);
    let height = source.height().min(size.height);
    let x = rng.random_range(0..=source.width() - width);
    let y = rng.random_range(0..=source.height() - height);
    let cropped = imageops::crop_imm(source, x, y, width, height).to_image();
    scale(cropped, size.width, size.height)
}

pub(crate) fn scale(mut source: RgbaImage, width: u32, height: u32) -> RgbaImage {
    if source.dimensions() == (width, height) {
        return source;
    }

    // Filtering premultiplied pixels keeps transparent edge colors out of the result.
    for pixel in source.pixels_mut() {
        let alpha = u16::from(pixel[3]);
        for channel in &mut pixel.0[..3] {
            *channel = ((u16::from(*channel) * alpha + 127) / 255) as u8;
        }
    }
    let mut scaled = imageops::resize(&source, width, height, FilterType::Triangle);
    for pixel in scaled.pixels_mut().filter(|pixel| pixel[3] != 0) {
        let alpha = u16::from(pixel[3]);
        for channel in &mut pixel.0[..3] {
            *channel = ((u16::from(*channel) * 255 + alpha / 2) / alpha).min(255) as u8;
        }
    }
    scaled
}

pub(crate) fn scale_fit(source: RgbaImage, width: u32, height: u32) -> RgbaImage {
    let ratio = (f64::from(width) / f64::from(source.width()))
        .min(f64::from(height) / f64::from(source.height()))
        .min(1.0);
    let width = (f64::from(source.width()) * ratio).floor().max(1.0) as u32;
    let height = (f64::from(source.height()) * ratio).floor().max(1.0) as u32;
    scale(source, width, height)
}

pub(crate) fn opacity(image: &mut RgbaImage, amount: u8) {
    if amount != u8::MAX {
        for pixel in image.pixels_mut() {
            pixel[3] = multiply_alpha(pixel[3], amount);
        }
    }
}

pub(crate) fn multiply_alpha(left: u8, right: u8) -> u8 {
    ((u16::from(left) * u16::from(right) + 127) / 255) as u8
}

pub(crate) fn tint(image: &mut RgbaImage, color: Rgba<u8>) {
    let [red, green, blue, alpha] = color.0;
    for pixel in image.pixels_mut() {
        *pixel = Rgba([red, green, blue, multiply_alpha(pixel[3], alpha)]);
    }
}

pub(crate) fn rotate(source: RgbaImage, degrees: i16, size: Size) -> RgbaImage {
    if degrees.rem_euclid(360) == 0 && source.dimensions() == (size.width, size.height) {
        return source;
    }

    let (sin, cos) = f64::from(degrees).to_radians().sin_cos();
    let source_x = (f64::from(source.width()) - 1.0) / 2.0;
    let source_y = (f64::from(source.height()) - 1.0) / 2.0;
    let center_x = (f64::from(size.width) - 1.0) / 2.0;
    let center_y = (f64::from(size.height) - 1.0) / 2.0;

    // Map destination centers back to the source so each output pixel gets one sample.
    RgbaImage::from_fn(size.width, size.height, |x, y| {
        let x = f64::from(x) - center_x;
        let y = f64::from(y) - center_y;
        sample(
            &source,
            source_x + cos * x + sin * y,
            source_y - sin * x + cos * y,
        )
    })
}

pub(crate) fn rotate_fit(source: RgbaImage, degrees: i16) -> RgbaImage {
    let (sin, cos) = f64::from(degrees).to_radians().sin_cos();
    let w = f64::from(source.width());
    let h = f64::from(source.height());
    let width = (w * cos.abs() + h * sin.abs()).ceil() as u32;
    let height = (w * sin.abs() + h * cos.abs()).ceil() as u32;
    rotate(source, degrees, Size::new(width, height))
}

pub(crate) fn sample(source: &RgbaImage, x: f64, y: f64) -> Rgba<u8> {
    let left = x.floor() as i32;
    let top = y.floor() as i32;
    let dx = x - f64::from(left);
    let dy = y - f64::from(top);
    let mut alpha = 0.0;
    let mut rgb = [0.0; 3];

    for (y, wy) in [(top, 1.0 - dy), (top + 1, dy)] {
        for (x, wx) in [(left, 1.0 - dx), (left + 1, dx)] {
            if let Some(pixel) = source.get_pixel_checked(x as u32, y as u32) {
                let weight = wx * wy * f64::from(pixel[3]);
                alpha += weight;
                for (sum, channel) in rgb.iter_mut().zip(pixel.0) {
                    *sum += weight * f64::from(channel);
                }
            }
        }
    }
    if alpha < 0.5 {
        return TRANSPARENT;
    }
    let [red, green, blue] = rgb.map(|sum| (sum / alpha).round() as u8);
    Rgba([red, green, blue, alpha.round() as u8])
}

pub(crate) fn circle(image: &mut RgbaImage) {
    let center = f64::from(image.width()) / 2.0;
    for (x, y, pixel) in image.enumerate_pixels_mut() {
        let dx = f64::from(x) + 0.5 - center;
        let dy = f64::from(y) + 0.5 - center;
        let coverage = (center + 0.5 - dx.hypot(dy)).clamp(0.0, 1.0);
        pixel[3] = multiply_alpha(pixel[3], (coverage * 255.0).round() as u8);
    }
}