bwm 0.1.0

Image watermarking over borrowed RGB/RGBA buffers
Documentation
use crate::error::WatermarkError;

#[derive(Clone, Debug, PartialEq)]
pub struct WatermarkConfig {
    pub key: WatermarkKey,
    pub strength: WatermarkStrength,
    pub robustness: RobustnessProfile,
    pub color_mode: ColorMode,
    pub threads: ThreadConfig,
}

impl WatermarkConfig {
    pub fn new(key: WatermarkKey) -> Self {
        Self {
            key,
            strength: WatermarkStrength::Medium,
            robustness: RobustnessProfile::Balanced,
            color_mode: ColorMode::LumaOnly,
            threads: ThreadConfig::Single,
        }
    }

    pub(crate) fn validate(&self) -> Result<(), WatermarkError> {
        if matches!(self.color_mode, ColorMode::YuvChannels) {
            return Err(WatermarkError::InvalidConfig(
                "YuvChannels is reserved for a future multi-channel encoder".to_string(),
            ));
        }

        if matches!(self.threads, ThreadConfig::Fixed(0)) {
            return Err(WatermarkError::InvalidConfig(
                "ThreadConfig::Fixed must be greater than zero".to_string(),
            ));
        }

        if let WatermarkStrength::Custom { d1, d2 } = self.strength {
            if !d1.is_finite() || d1 <= 0.0 {
                return Err(WatermarkError::InvalidConfig(
                    "WatermarkStrength::Custom.d1 must be finite and positive".to_string(),
                ));
            }

            if let Some(d2) = d2 {
                if !d2.is_finite() || d2 <= 0.0 {
                    return Err(WatermarkError::InvalidConfig(
                        "WatermarkStrength::Custom.d2 must be finite and positive".to_string(),
                    ));
                }
            }
        }

        Ok(())
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct WatermarkKey {
    pub bytes: [u8; 32],
}

impl WatermarkKey {
    pub fn from_bytes(bytes: [u8; 32]) -> Self {
        Self { bytes }
    }

    pub fn from_hex(hex: &str) -> Result<Self, WatermarkError> {
        let hex = hex.trim();
        if hex.len() != 64 {
            return Err(WatermarkError::InvalidConfig(
                "watermark key hex must contain exactly 64 characters".to_string(),
            ));
        }

        let mut bytes = [0u8; 32];
        for (index, chunk) in hex.as_bytes().chunks_exact(2).enumerate() {
            let hi = decode_hex_nibble(chunk[0])?;
            let lo = decode_hex_nibble(chunk[1])?;
            bytes[index] = (hi << 4) | lo;
        }

        Ok(Self { bytes })
    }
}

fn decode_hex_nibble(byte: u8) -> Result<u8, WatermarkError> {
    match byte {
        b'0'..=b'9' => Ok(byte - b'0'),
        b'a'..=b'f' => Ok(byte - b'a' + 10),
        b'A'..=b'F' => Ok(byte - b'A' + 10),
        _ => Err(WatermarkError::InvalidConfig(
            "watermark key hex contains a non-hex character".to_string(),
        )),
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WatermarkStrength {
    Low,
    Medium,
    High,
    Custom { d1: f32, d2: Option<f32> },
}

impl WatermarkStrength {
    pub(crate) fn coefficient_margin(self) -> f32 {
        match self {
            Self::Low => 18.0,
            Self::Medium => 30.0,
            Self::High => 46.0,
            Self::Custom { d1, .. } => d1,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RobustnessProfile {
    Fast,
    Balanced,
    Robust,
}

impl RobustnessProfile {
    pub(crate) fn repetitions(self) -> usize {
        match self {
            Self::Fast => 1,
            Self::Balanced => 3,
            Self::Robust => 75,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColorMode {
    LumaOnly,
    YuvChannels,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ThreadConfig {
    Auto,
    Single,
    Fixed(usize),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PixelFormat {
    Rgb8,
    Rgba8,
}

impl PixelFormat {
    pub(crate) fn channels(self) -> usize {
        match self {
            Self::Rgb8 => 3,
            Self::Rgba8 => 4,
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub struct ImageBufferRef<'a> {
    pub data: &'a [u8],
    pub width: u32,
    pub height: u32,
    pub stride: usize,
    pub pixel_format: PixelFormat,
}

impl<'a> ImageBufferRef<'a> {
    pub fn new(
        data: &'a [u8],
        width: u32,
        height: u32,
        stride: usize,
        pixel_format: PixelFormat,
    ) -> Self {
        Self {
            data,
            width,
            height,
            stride,
            pixel_format,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WatermarkedImage {
    pub data: Vec<u8>,
    pub width: u32,
    pub height: u32,
    pub stride: usize,
    pub pixel_format: PixelFormat,
}

impl WatermarkedImage {
    pub fn as_ref(&self) -> ImageBufferRef<'_> {
        ImageBufferRef {
            data: &self.data,
            width: self.width,
            height: self.height,
            stride: self.stride,
            pixel_format: self.pixel_format,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CapacityInfo {
    pub width: u32,
    pub height: u32,
    pub tile_count: usize,
    pub repetition_factor: usize,
    pub usable_bits: usize,
    pub frame_overhead_bytes: usize,
    pub max_payload_bytes: usize,
}