bwm 0.1.0

Image watermarking over borrowed RGB/RGBA buffers
Documentation
use crate::{color, embed, payload, prng, ImageBufferRef, WatermarkConfig, WatermarkError};

pub fn extract_text(
    image: ImageBufferRef<'_>,
    config: &WatermarkConfig,
) -> Result<String, WatermarkError> {
    let decoded = extract_payload_inner(image, config)?;
    if decoded.kind != payload::TYPE_TEXT_UTF8 {
        return Err(WatermarkError::DecodeError(
            "watermark payload is not UTF-8 text".to_string(),
        ));
    }

    String::from_utf8(decoded.bytes)
        .map_err(|err| WatermarkError::DecodeError(format!("invalid UTF-8 payload: {err}")))
}

pub fn extract_payload(
    image: ImageBufferRef<'_>,
    config: &WatermarkConfig,
) -> Result<Vec<u8>, WatermarkError> {
    Ok(extract_payload_inner(image, config)?.bytes)
}

fn extract_payload_inner(
    image: ImageBufferRef<'_>,
    config: &WatermarkConfig,
) -> Result<payload::DecodedPayload, WatermarkError> {
    color::validate_image(image)?;
    config.validate()?;

    let tile_count = embed::tile_count(image);
    let repetition_factor = config.robustness.repetitions();
    let usable_bits = tile_count / repetition_factor;
    let usable_bytes = usable_bits / 8;

    if usable_bytes < payload::HEADER_LEN {
        return Err(WatermarkError::NoWatermarkFound);
    }

    let schedule = prng::KeySchedule::derive(&config.key);
    let positions = prng::shuffled_indices(tile_count, &schedule.placement, b"tile-order-v1");
    let mut encoded = vec![0u8; usable_bytes];

    for bit_index in 0..(usable_bytes * 8) {
        let base = bit_index * repetition_factor;
        let mut ones = 0usize;
        for repetition in 0..repetition_factor {
            let tile_index = positions[base + repetition];
            if embed::read_bit_from_tile(image.data, image, tile_index) {
                ones += 1;
            }
        }

        if ones * 2 >= repetition_factor {
            payload::set_byte_bit(&mut encoded, bit_index, true);
        }
    }

    payload::decode_frame(&encoded, &config.key)
}