bwm 0.1.0

Image watermarking over borrowed RGB/RGBA buffers
Documentation
#![allow(clippy::needless_range_loop)]

#[derive(Clone, Copy, Debug)]
pub(crate) struct Haar8 {
    pub ll: [[f32; 4]; 4],
    pub hl: [[f32; 4]; 4],
    pub lh: [[f32; 4]; 4],
    pub hh: [[f32; 4]; 4],
}

pub(crate) fn forward_haar_8x8(tile: &[[f32; 8]; 8]) -> Haar8 {
    let mut out = Haar8 {
        ll: [[0.0; 4]; 4],
        hl: [[0.0; 4]; 4],
        lh: [[0.0; 4]; 4],
        hh: [[0.0; 4]; 4],
    };

    for by in 0..4 {
        for bx in 0..4 {
            let a = tile[by * 2][bx * 2];
            let b = tile[by * 2][bx * 2 + 1];
            let c = tile[by * 2 + 1][bx * 2];
            let d = tile[by * 2 + 1][bx * 2 + 1];

            out.ll[by][bx] = (a + b + c + d) * 0.5;
            out.hl[by][bx] = (a - b + c - d) * 0.5;
            out.lh[by][bx] = (a + b - c - d) * 0.5;
            out.hh[by][bx] = (a - b - c + d) * 0.5;
        }
    }

    out
}

pub(crate) fn inverse_haar_8x8(coeffs: &Haar8) -> [[f32; 8]; 8] {
    let mut tile = [[0.0; 8]; 8];

    for by in 0..4 {
        for bx in 0..4 {
            let ll = coeffs.ll[by][bx];
            let hl = coeffs.hl[by][bx];
            let lh = coeffs.lh[by][bx];
            let hh = coeffs.hh[by][bx];

            tile[by * 2][bx * 2] = (ll + hl + lh + hh) * 0.5;
            tile[by * 2][bx * 2 + 1] = (ll - hl + lh - hh) * 0.5;
            tile[by * 2 + 1][bx * 2] = (ll + hl - lh - hh) * 0.5;
            tile[by * 2 + 1][bx * 2 + 1] = (ll - hl - lh + hh) * 0.5;
        }
    }

    tile
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn haar_round_trips_tile() {
        let mut tile = [[0.0; 8]; 8];
        for y in 0..8 {
            for x in 0..8 {
                tile[y][x] = (y * 13 + x * 7) as f32;
            }
        }

        let coeffs = forward_haar_8x8(&tile);
        let recovered = inverse_haar_8x8(&coeffs);
        for y in 0..8 {
            for x in 0..8 {
                assert!((tile[y][x] - recovered[y][x]).abs() < 0.001);
            }
        }
    }
}