legit-hashes 0.2.0

Versioned similarity hashes of images and text, and MinHash set signatures, with index keys for finding near matches
Documentation
//! `blockhash-v1`, the block mean value hash.

use crate::{Algorithm, Hash, Rgba};

/// Blocks a side: 16 × 16 blocks, one bit each.
const GRID: usize = 16;

/// Blocks in a band of four rows, thresholded against their own median.
const BAND: usize = GRID * GRID / 4;

/// What a fully transparent pixel counts as: white, `255 + 255 + 255`.
const TRANSPARENT: u64 = 765;

/// Hash an image with `blockhash-v1`, the block mean value hash.
///
/// The definition, frozen, is the "precise" method of [blockhash](https://github.com/commonsmachinery/blockhash)
/// at 16 blocks a side, as its Python port, [blockhash-python](https://github.com/commonsmachinery/blockhash-python)
/// at commit `f28b741a1f6bfff25763ae42dc2190051079998c`, computes it: `blockhash(image, 16)`. That
/// implements the method of Bian Yang, Fan Gu and Xiamu Niu. Given the same RGBA pixels, this
/// function gives the bits blockhash-python gives. The image isn't resized first.
///
/// 1. A pixel's value is `R + G + B`, from 0 to 765; a pixel with alpha 0 counts as 765, white,
///    whatever its colour. Any other alpha is ignored.
/// 2. Cut the image into 16 × 16 blocks, each `width / 16` pixels wide and `height / 16` high,
///    which needn't be whole numbers. Along a side of `n` pixels, pixel `p`, counting from 0, goes
///    to the blocks this way:
///    - When 16 divides `n`, all of it goes to block `16p / n`, in integer division.
///    - Otherwise, let `r = (p + 1) mod (n / 16)`, and `f` its fractional part. When `r` is at
///      least 1, or `p` is the last pixel, all of it goes to block `⌊16p / n⌋`. Otherwise `1 - f`
///      of it goes to block `⌊16p / n⌋` and `f` to block `⌈16p / n⌉`.
///
///    A pixel's share of a block is its share along the width times its share along the height.
///    On a side of 16 pixels or more this is the area of the pixel that lies in the block. On a
///    shorter side, where a block is narrower than a pixel, it isn't: some blocks get nothing.
/// 3. A block's value is the sum of the values of its pixels, each times its share.
/// 4. Split the 256 blocks, taken row by row, into four bands of four rows. In each band, let `m`
///    be the median of its 64 block values, the mean of the two middle ones, and
///    `half = width · height · 1.5`, the value of a block of pixels whose channels are all 128.
///    A block's bit is set when its value `v` is above `m`, or when `|v - m| < 1` and `m > half`.
///    So blocks equal to a median at or below mid-grey stay clear, and those equal to a brighter
///    median are set, which keeps a mostly black or mostly white image from hashing to all zeros.
/// 5. The bits run in block order, row by row from the top left, the first in the most significant
///    bit of the first byte, as blockhash prints them.
///
/// The reference computes the shares in `f64`. Each share is a multiple of 1/16 along each side,
/// so each product of a value and two shares is a multiple of 1/256 below 1,024, and every sum and
/// median it forms stays below `2^53 / 256`: `f64` holds them all exactly. This function computes
/// the same quantities times 256, in `u64`, so its comparisons are the reference's, ties included,
/// and every platform computes the same hash.
///
/// Each band has exactly 32 of its 64 bits set when its block values are distinct and no value
/// other than one above the median lies within 1 of it. A band of equal values is all clear or all
/// set; a flat image hashes to all zeros unless it's brighter than mid-grey.
///
/// The C blockhash agrees except at a tie: it sums in `f32`, and for a size 16 doesn't divide it
/// truncates the block area to an integer before it computes `half`.
///
/// ```
/// use legit_hashes::{Algorithm, Rgba, RgbaBuf, blockhash_v1};
///
/// // A white square on black, 16 pixels a side in the middle of 32: the bits of the middle
/// // eight blocks of the middle eight rows are set...
/// let rgb: Vec<u8> = (0..32 * 32)
///     .flat_map(|i| if (8..24).contains(&(i % 32)) && (8..24).contains(&(i / 32)) { [255; 3] } else { [0; 3] })
///     .collect();
/// let hash = blockhash_v1(RgbaBuf::from_rgb8(32, 32, &rgb)?.view());
/// assert_eq!(hash.algorithm(), Algorithm::BlockhashV1);
/// let middle = "0ff0".repeat(8);
/// assert_eq!(hash.to_hex(), format!("{}{middle}{}", "0".repeat(16), "0".repeat(16)));
///
/// // ...and transparent pixels count as white.
/// let clear = blockhash_v1(Rgba::new(16, 16, &[0; 16 * 16 * 4])?);
/// assert_eq!(clear.to_hex(), "f".repeat(64));
/// # Ok::<(), legit_hashes::Error>(())
/// ```
#[must_use]
pub fn blockhash_v1(image: Rgba<'_>) -> Hash {
    let width = image.width() as usize;
    let columns = shares(width);
    let rows = shares(image.height() as usize);
    // Each block's value times 256: shares in sixteenths along each side...
    let mut blocks = [0_u64; GRID * GRID];
    for (row, top_bottom) in image.pixels().chunks_exact(width * 4).zip(&rows) {
        let (pixels, _) = row.as_chunks::<4>();
        for (&[red, green, blue, alpha], left_right) in pixels.iter().zip(&columns) {
            let value = if alpha == 0 {
                TRANSPARENT
            } else {
                u64::from(red) + u64::from(green) + u64::from(blue)
            };
            for (block_row, row_share) in [
                (top_bottom.first, top_bottom.first_share),
                (top_bottom.second, top_bottom.second_share),
            ] {
                for (block_column, column_share) in [
                    (left_right.first, left_right.first_share),
                    (left_right.second, left_right.second_share),
                ] {
                    blocks[block_row * GRID + block_column] += value * row_share * column_share;
                }
            }
        }
    }
    // `half` times 512, the scale of the sum of two block values...
    let twice_half = 768 * u64::from(image.width()) * u64::from(image.height());
    let mut bytes = [0; 32];
    for (band_index, band) in blocks.as_chunks::<BAND>().0.iter().enumerate() {
        let mut sorted = *band;
        sorted.sort_unstable();
        // Twice the median, times 256...
        let twice_median = sorted[BAND / 2 - 1] + sorted[BAND / 2];
        for (index, &block) in band.iter().enumerate() {
            let twice = 2 * block;
            let set = twice > twice_median || (twice.abs_diff(twice_median) < 512 && twice_median > twice_half);
            if set {
                let bit = band_index * BAND + index;
                bytes[bit / 8] |= 0x80 >> (bit % 8);
            }
        }
    }
    Hash::from_wide(Algorithm::BlockhashV1, bytes)
}

/// Where one pixel along a side goes: its share of each of two blocks, in sixteenths. Both blocks
/// are the same when the pixel lies within one.
#[derive(Debug, Clone, Copy)]
struct Share {
    first: usize,
    second: usize,
    first_share: u64,
    second_share: u64,
}

/// Step 2 for each pixel along a side of `side` pixels.
fn shares(side: usize) -> Vec<Share> {
    (0..side)
        .map(|p| {
            let first = GRID * p / side;
            if side.is_multiple_of(GRID) {
                return Share {
                    first,
                    second: first,
                    first_share: 16,
                    second_share: 0,
                };
            }
            // `(p + 1) mod (side / 16)`, in sixteenths: its whole part and its fraction...
            let remainder = (GRID * (p + 1)) % side;
            let (whole, fraction) = (remainder / 16, remainder % 16);
            let second = if whole > 0 || p + 1 == side {
                first
            } else {
                (GRID * p).div_ceil(side)
            };
            Share {
                first,
                second,
                first_share: 16 - fraction as u64,
                second_share: fraction as u64,
            }
        })
        .collect()
}