legit-hashes 0.2.1

Versioned similarity hashes of images and text, and MinHash set signatures, with index keys for finding near matches
Documentation
//! 8-bit luma images: the input of every image hash, the v1 luma formula and the v1 downscale.

use std::fmt;

use crate::{Error, Result};

/// The largest width or height an image may have: 65,535 pixels.
pub const MAX_DIMENSION: u32 = 65_535;

/// Convert one RGB pixel to luma with the v1 formula.
///
/// `Y = (19595 * R + 38470 * G + 7471 * B + 32768) >> 16`: the ITU-R 601-2 weights in the integer
/// form Pillow's `convert("L")` uses. Grey stays grey: `R = G = B = v` gives `v`.
///
/// ```
/// assert_eq!(legit_hashes::luma_v1(255, 0, 0), 76);
/// assert_eq!(legit_hashes::luma_v1(200, 200, 200), 200);
/// ```
#[must_use]
pub const fn luma_v1(red: u8, green: u8, blue: u8) -> u8 {
    let weighted = 19_595 * red as u32 + 38_470 * green as u32 + 7_471 * blue as u32 + 32_768;
    // The weights sum to 65,536, so the shifted value is at most 255...
    (weighted >> 16) as u8
}

/// A borrowed 8-bit luma image: one byte a pixel, row by row from the top left.
///
/// Making one checks its size, so every image hash of a `Luma` succeeds.
///
/// ```
/// use legit_hashes::Luma;
///
/// let pixels = vec![128; 640 * 480];
/// let image = Luma::new(640, 480, &pixels)?;
/// assert_eq!(image.width(), 640);
/// # Ok::<(), legit_hashes::Error>(())
/// ```
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Luma<'a> {
    width: u32,
    height: u32,
    pixels: &'a [u8],
}

impl<'a> Luma<'a> {
    /// View `pixels` as a `width` × `height` luma image.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ZeroDimension`] or [`Error::DimensionTooLarge`] when a side isn't from 1
    /// to [`MAX_DIMENSION`], and [`Error::BufferLength`] when `pixels` isn't `width * height` long.
    pub fn new(width: u32, height: u32, pixels: &'a [u8]) -> Result<Self> {
        check_size(width, height, 1, pixels.len())?;
        Ok(Self { width, height, pixels })
    }

    /// The width in pixels.
    #[must_use]
    pub const fn width(&self) -> u32 {
        self.width
    }

    /// The height in pixels.
    #[must_use]
    pub const fn height(&self) -> u32 {
        self.height
    }

    /// The pixels, row by row from the top left.
    #[must_use]
    pub const fn pixels(&self) -> &'a [u8] {
        self.pixels
    }

    /// Resize the image to `width` × `height` with the v1 filter, an exact area average.
    ///
    /// Every image hash reduces its input with this filter and nothing else. It uses only integer
    /// arithmetic, so its output is the same on every platform.
    ///
    /// Put the source and the target on one integer grid, where a source pixel is `width` units
    /// wide and `height` units high, and a target pixel is `source width` units wide and
    /// `source height` units high. A source pixel's weight in a target pixel is the area of their
    /// overlap in those units, so each target pixel's weights sum to
    /// `T = source width * source height`. The target pixel is `(Σ weight * luma + T / 2) / T`,
    /// in integer division. The same size gives the same pixels, and enlarging follows from the
    /// same formula.
    ///
    /// ```
    /// use legit_hashes::Luma;
    ///
    /// // 3 pixels to 2: the middle one is split in half between the two...
    /// let resized = Luma::new(3, 1, &[0, 100, 255])?.downscale_v1(2, 1)?;
    /// assert_eq!(resized.pixels(), [33, 203]);
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::ZeroDimension`] or [`Error::DimensionTooLarge`] when a side of the target
    /// isn't from 1 to [`MAX_DIMENSION`].
    pub fn downscale_v1(&self, width: u32, height: u32) -> Result<LumaBuf> {
        check_dimensions(width, height)?;
        Ok(LumaBuf {
            width,
            height,
            pixels: downscale(*self, width, height),
        })
    }
}

impl fmt::Debug for Luma<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Luma")
            .field("width", &self.width)
            .field("height", &self.height)
            .finish_non_exhaustive()
    }
}

/// An owned 8-bit luma image, such as one converted from RGB. [`view`](Self::view) borrows it for
/// hashing.
///
/// ```
/// use legit_hashes::{LumaBuf, average_v1};
///
/// let rgb = [255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255];
/// let image = LumaBuf::from_rgb8_v1(2, 2, &rgb)?;
/// assert_eq!(image.pixels(), [76, 150, 29, 255]);
///
/// let hash = average_v1(image.view());
/// # Ok::<(), legit_hashes::Error>(())
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct LumaBuf {
    width: u32,
    height: u32,
    pixels: Vec<u8>,
}

impl LumaBuf {
    /// Take `pixels` as a `width` × `height` luma image.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ZeroDimension`] or [`Error::DimensionTooLarge`] when a side isn't from 1
    /// to [`MAX_DIMENSION`], and [`Error::BufferLength`] when `pixels` isn't `width * height` long.
    pub fn new(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self> {
        check_size(width, height, 1, pixels.len())?;
        Ok(Self { width, height, pixels })
    }

    /// Convert a `width` × `height` RGB image, three bytes a pixel, with [`luma_v1`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::ZeroDimension`] or [`Error::DimensionTooLarge`] when a side isn't from 1
    /// to [`MAX_DIMENSION`], and [`Error::BufferLength`] when `rgb` isn't `width * height * 3`
    /// long.
    pub fn from_rgb8_v1(width: u32, height: u32, rgb: &[u8]) -> Result<Self> {
        Self::from_channels(width, height, rgb, 3)
    }

    /// Convert a `width` × `height` RGBA image, four bytes a pixel, with [`luma_v1`]. Alpha is
    /// ignored: a transparent pixel counts as its colour.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ZeroDimension`] or [`Error::DimensionTooLarge`] when a side isn't from 1
    /// to [`MAX_DIMENSION`], and [`Error::BufferLength`] when `rgba` isn't `width * height * 4`
    /// long.
    pub fn from_rgba8_v1(width: u32, height: u32, rgba: &[u8]) -> Result<Self> {
        Self::from_channels(width, height, rgba, 4)
    }

    fn from_channels(width: u32, height: u32, samples: &[u8], channels: usize) -> Result<Self> {
        check_size(width, height, channels, samples.len())?;
        let pixels = samples
            .chunks_exact(channels)
            .map(|pixel| luma_v1(pixel[0], pixel[1], pixel[2]))
            .collect();
        Ok(Self { width, height, pixels })
    }

    /// Borrow the image for hashing.
    #[must_use]
    pub fn view(&self) -> Luma<'_> {
        Luma {
            width: self.width,
            height: self.height,
            pixels: &self.pixels,
        }
    }

    /// The width in pixels.
    #[must_use]
    pub const fn width(&self) -> u32 {
        self.width
    }

    /// The height in pixels.
    #[must_use]
    pub const fn height(&self) -> u32 {
        self.height
    }

    /// The pixels, row by row from the top left.
    #[must_use]
    pub fn pixels(&self) -> &[u8] {
        &self.pixels
    }

    /// Take the pixels out.
    #[must_use]
    pub fn into_pixels(self) -> Vec<u8> {
        self.pixels
    }
}

impl fmt::Debug for LumaBuf {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("LumaBuf")
            .field("width", &self.width)
            .field("height", &self.height)
            .finish_non_exhaustive()
    }
}

/// Check both sides are from 1 to [`MAX_DIMENSION`].
fn check_dimensions(width: u32, height: u32) -> Result<()> {
    if width == 0 || height == 0 {
        return Err(Error::ZeroDimension { width, height });
    }
    // The area check only matters on a 32-bit target, where a buffer can't be that long...
    if width > MAX_DIMENSION || height > MAX_DIMENSION || u64::from(width) * u64::from(height) > isize::MAX as u64 {
        return Err(Error::DimensionTooLarge { width, height });
    }
    Ok(())
}

/// Check the sides, and that `actual` bytes is `channels` bytes for each pixel.
pub(crate) fn check_size(width: u32, height: u32, channels: usize, actual: usize) -> Result<()> {
    check_dimensions(width, height)?;
    // On a 32-bit target the product can overflow; no slice is that long, so the lengths differ...
    let expected = (width as usize)
        .checked_mul(height as usize)
        .and_then(|pixels| pixels.checked_mul(channels))
        .unwrap_or(usize::MAX);
    if actual != expected {
        return Err(Error::BufferLength { expected, actual });
    }
    Ok(())
}

/// The v1 exact area average, for a target whose sides are already checked.
pub(crate) fn downscale(image: Luma<'_>, width: u32, height: u32) -> Vec<u8> {
    if (image.width, image.height) == (width, height) {
        return image.pixels.to_vec();
    }
    let columns = axis_weights(image.width, width);
    let rows = axis_weights(image.height, height);
    let source_width = image.width as usize;
    let pixel = |x: usize, y: usize| u64::from(image.pixels[y * source_width + x]);
    let total = u64::from(image.width) * u64::from(image.height);
    // A weighted mean of bytes rounds to at most 255...
    let round = |sum: u64| ((sum + total / 2) / total) as u8;

    // Integer sums are exact, so summing across or down first gives the same result. Take the
    // order with fewer partial sums, so a long, thin image enlarged the other way stays cheap...
    if u64::from(image.height) * u64::from(width) <= u64::from(height) * u64::from(image.width) {
        let across: Vec<Vec<u64>> = (0..image.height as usize)
            .map(|y| {
                columns
                    .iter()
                    .map(|cell| cell.iter().map(|&(x, weight)| weight * pixel(x, y)).sum())
                    .collect()
            })
            .collect();
        rows.iter()
            .flat_map(|cell| {
                let across = &across;
                (0..width as usize).map(move |column| cell.iter().map(|&(y, weight)| weight * across[y][column]).sum())
            })
            .map(round)
            .collect()
    } else {
        let down: Vec<Vec<u64>> = rows
            .iter()
            .map(|cell| {
                (0..source_width)
                    .map(|x| cell.iter().map(|&(y, weight)| weight * pixel(x, y)).sum())
                    .collect()
            })
            .collect();
        down.iter()
            .flat_map(|row| {
                columns
                    .iter()
                    .map(move |cell| cell.iter().map(|&(x, weight)| weight * row[x]).sum())
            })
            .map(round)
            .collect()
    }
}

/// For each target position on one axis, the source positions it overlaps and the overlap length.
///
/// A source position spans `target` units and a target position `source` units, so both cover
/// `source * target` units in all.
fn axis_weights(source: u32, target: u32) -> Vec<Vec<(usize, u64)>> {
    let (source, target) = (u64::from(source), u64::from(target));
    (0..target)
        .map(|index| {
            let start = index * source;
            let end = start + source;
            (start / target..=(end - 1) / target)
                .map(|position| {
                    let overlap = end.min((position + 1) * target) - start.max(position * target);
                    (position as usize, overlap)
                })
                .collect()
        })
        .collect()
}

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

    #[test]
    fn the_weights_of_each_target_position_cover_one_source_length() {
        for source in 1..40 {
            for target in 1..40 {
                for weights in axis_weights(source, target) {
                    assert_eq!(
                        weights.iter().map(|&(_, weight)| weight).sum::<u64>(),
                        u64::from(source)
                    );
                    assert!(weights.iter().all(|&(_, weight)| weight > 0));
                }
            }
        }
    }
}