legit-hashes 0.2.0

Versioned similarity hashes of images and text, and MinHash set signatures, with index keys for finding near matches
Documentation
//! Decoding PNG and JPEG files to luma or RGBA, with the `image` feature.

use std::io::Cursor;

use image::{DynamicImage, ImageReader, Limits};

use crate::{Error, LumaBuf, Result, RgbaBuf};

/// The widest or tallest file [`decode_luma_v1`] decodes: 16,384 pixels.
pub const DECODE_MAX_DIMENSION: u32 = 16_384;

/// The most memory the decoder may allocate for one file: 256 MiB.
pub const DECODE_MAX_ALLOC: u64 = 256 * 1024 * 1024;

/// The longest file [`decode_luma_v1`] reads: 64 MiB. The JPEG decoder copies its whole input
/// before it applies any other limit, so a longer file is refused before decoding starts.
pub const DECODE_MAX_INPUT: usize = 64 * 1024 * 1024;

/// Decode a PNG or JPEG file and convert it to luma with [`luma_v1`](crate::luma_v1).
///
/// The format is read from the bytes, not a file name. The file is decoded by the `image` crate,
/// converted to 8-bit RGB with its `to_rgb8`, then to luma with the v1 formula; alpha is ignored,
/// and an 8-bit greyscale file keeps its values. Orientation metadata isn't applied.
///
/// The limits bound what a hostile file can make the decoder allocate: the file may be at most
/// [`DECODE_MAX_INPUT`] bytes, a side at most [`DECODE_MAX_DIMENSION`] pixels, **and** the decoder
/// may allocate at most [`DECODE_MAX_ALLOC`] bytes. The last limit bounds the area too: the
/// decoded pixels must fit in it, so an 8-bit RGB file can have at most about 89 megapixels, such
/// as 11,000×8,000, even though 12,000×8,000 is within the side limit. A file over any limit is an
/// error before its pixels are read. To hash a larger image, decode it yourself and pass the RGB
/// to [`LumaBuf::from_rgb8_v1`] or the luma to [`Luma::new`](crate::Luma::new). The RGB copy and
/// the luma image come on top, at most four bytes for each pixel the limits allow.
///
/// Decoding isn't a validity check: a truncated JPEG may decode with its missing part filled in,
/// and hash without an error.
///
/// The hash definitions start from pixels. A PNG decodes to the same pixels everywhere, but a
/// JPEG decoder may round differently from another, or from a later version of itself, so a hash
/// of a JPEG file can move by a few bits when the `image` crate changes.
///
/// # Errors
///
/// Returns [`Error::Decode`] when the bytes aren't a PNG or JPEG file, are damaged, or are over
/// the limits.
pub fn decode_luma_v1(bytes: &[u8]) -> Result<LumaBuf> {
    let rgb = decode(bytes)?.into_rgb8();
    LumaBuf::from_rgb8_v1(rgb.width(), rgb.height(), rgb.as_raw())
}

/// Decode a PNG or JPEG file to 8-bit RGBA, the input of `pdq-v1` and `blockhash-v1`.
///
/// The format is read from the bytes, not a file name, and the file is decoded by the `image`
/// crate within the limits [`decode_luma_v1`] states; the RGBA copy comes on top, four bytes a
/// pixel. Orientation metadata isn't applied. The conversion to RGBA, frozen:
///
/// - RGB: each pixel keeps its colour and gets alpha 255.
/// - RGBA: kept as it is, alpha included. A palette file's transparency becomes its alpha.
/// - Greyscale: a level `v` becomes `(v, v, v)`, with the file's alpha, or 255 without one.
/// - 16-bit samples, alpha included, narrow to 8 bits as `(s + 128) / 257` in integer division,
///   the nearest 8-bit value.
///
/// Alpha is kept, not applied: a transparent pixel keeps the colour it's stored with, often black.
/// `blockhash-v1` counts a pixel with alpha 0 as white, and `pdq-v1` ignores alpha, as Meta's
/// reference does with the RGB it's given, so a transparent area hashes as whatever colour the
/// file stores there. Composite the image onto a background first if that matters.
///
/// The hash definitions start from pixels. A PNG decodes to the same pixels everywhere, but a
/// JPEG decoder may round differently from another, or from a later version of itself, so a hash
/// of a JPEG file can move by a few bits when the `image` crate changes, or from the hash another
/// program computes from its own decoding.
///
/// ```no_run
/// use legit_hashes::{blockhash_v1, decode_rgba_v1, pdq_v1};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let image = decode_rgba_v1(&std::fs::read("upload.png")?)?;
/// let pdq = pdq_v1(image.view());
/// let block = blockhash_v1(image.view());
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns [`Error::Decode`] when the bytes aren't a PNG or JPEG file, are damaged, or are over
/// the limits.
pub fn decode_rgba_v1(bytes: &[u8]) -> Result<RgbaBuf> {
    let image = decode(bytes)?;
    let (width, height) = (image.width(), image.height());
    let pixels: Vec<u8> = match image {
        DynamicImage::ImageRgba8(image) => image.into_raw(),
        DynamicImage::ImageRgb8(image) => expand(&image.into_raw(), 3, |&[r, g, b, ..]| [r, g, b, u8::MAX]),
        DynamicImage::ImageLuma8(image) => expand(&image.into_raw(), 1, |&[v, ..]| [v, v, v, u8::MAX]),
        DynamicImage::ImageLumaA8(image) => expand(&image.into_raw(), 2, |&[v, a, ..]| [v, v, v, a]),
        DynamicImage::ImageRgba16(image) => image.into_raw().into_iter().map(narrow).collect(),
        DynamicImage::ImageRgb16(image) => expand_wide(&image.into_raw(), 3, |&[r, g, b, ..]| [r, g, b, u8::MAX]),
        DynamicImage::ImageLuma16(image) => expand_wide(&image.into_raw(), 1, |&[v, ..]| [v, v, v, u8::MAX]),
        DynamicImage::ImageLumaA16(image) => expand_wide(&image.into_raw(), 2, |&[v, a, ..]| [v, v, v, a]),
        other => {
            return Err(Error::Decode(format!(
                "the file's `{:?}` samples aren't 8 or 16-bit integers",
                other.color()
            )));
        }
    };
    RgbaBuf::new(width, height, pixels)
}

/// Each pixel of `channels` 8-bit samples as RGBA. `pixel` reads the first `channels` of four.
fn expand(samples: &[u8], channels: usize, pixel: impl Fn(&[u8; 4]) -> [u8; 4]) -> Vec<u8> {
    samples
        .chunks_exact(channels)
        .flat_map(|chunk| {
            let mut padded = [0; 4];
            padded[..channels].copy_from_slice(chunk);
            pixel(&padded)
        })
        .collect()
}

/// Each pixel of `channels` 16-bit samples as 8-bit RGBA, each sample narrowed first.
fn expand_wide(samples: &[u16], channels: usize, pixel: impl Fn(&[u8; 4]) -> [u8; 4]) -> Vec<u8> {
    let narrowed: Vec<u8> = samples.iter().copied().map(narrow).collect();
    expand(&narrowed, channels, pixel)
}

/// A 16-bit sample as the nearest 8-bit one: `(s + 128) / 257`.
fn narrow(sample: u16) -> u8 {
    // At most (65,535 + 128) / 257 = 255...
    ((u32::from(sample) + 128) / 257) as u8
}

/// Decode a PNG or JPEG file within the limits.
fn decode(bytes: &[u8]) -> Result<DynamicImage> {
    if bytes.len() > DECODE_MAX_INPUT {
        return Err(Error::Decode(format!(
            "the file is `{}` bytes; at most `{DECODE_MAX_INPUT}` are read",
            bytes.len()
        )));
    }
    let mut reader = ImageReader::new(Cursor::new(bytes))
        .with_guessed_format()
        .map_err(|error| Error::Decode(error.to_string()))?;
    let mut limits = Limits::default();
    limits.max_image_width = Some(DECODE_MAX_DIMENSION);
    limits.max_image_height = Some(DECODE_MAX_DIMENSION);
    limits.max_alloc = Some(DECODE_MAX_ALLOC);
    reader.limits(limits);
    reader.decode().map_err(|error| Error::Decode(error.to_string()))
}