Cotton code
216 lines · 8.4 KB · RustRaw
//! What the core sees in one photo: a small grey picture the phone hands it,//! at whatever size the phone had **without the network**.//!//! An iPhone with Optimise Storage keeps a small picture of every photo and//! the original in iCloud; Apple does not document which sizes stay local//! (RESEARCH.md §1). So the core never asks for a size it might not get: it//! takes what came and says how far it can trust it ([`Level`])://!//! | Level | Longest side handed | What the core can say |//! |---|---|---|//! | `Full`  | ≥ 256 px | looks alike, sharp or blurred, dark, everything |//! | `Small` | 32–255 px | looks alike and dark; **not** sharp or blurred (a small picture hides blur) |//! | `None`  | nothing, or < 32 px | nothing: the photo is counted as "only in iCloud" and asked for again on Wi-Fi |//!//! Every measure is taken on the core's own reduction of the picture (fixed//! sizes, fixed grey weights), so an iPhone and an Android phone that hand the//! same photo get the same numbers: the difference hash is the portable match//! key's third part. What a platform adds (Vision's feature print and quality,//! ML Kit's labels) rides along in [`PlatformLook`] and is used when present.use serde::{Deserialize, Serialize};/// A grey picture, one byte a pixel, row by row.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Grey {    pub width: u32,    pub height: u32,    pub pixels: Vec<u8>,}impl Grey {    /// From RGBA8 (what both platforms' bitmaps give), with the core's own    /// weights (BT.601 luma), so the grey is the same on every phone.    pub fn from_rgba(width: u32, height: u32, rgba: &[u8]) -> Option<Grey> {        let n = width as usize * height as usize;        if rgba.len() != n * 4 {            return None;        }        let pixels = rgba.chunks_exact(4).map(|p| ((299 * p[0] as u32 + 587 * p[1] as u32 + 114 * p[2] as u32 + 500) / 1000) as u8).collect();        Some(Grey { width, height, pixels })    }    pub fn new(width: u32, height: u32, pixels: Vec<u8>) -> Option<Grey> {        (pixels.len() == width as usize * height as usize).then_some(Grey { width, height, pixels })    }    fn longest(&self) -> u32 {        self.width.max(self.height)    }}/// How far the core can trust what it saw.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum Level {    None,    Small,    Full,}pub const FULL_FROM: u32 = 256;pub const SMALL_FROM: u32 = 32;/// What a platform adds when it has it (Vision on the iPhone, ML Kit and the/// shared model on Android). All optional: the core works without any.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]pub struct PlatformLook {    /// Vision's feature print (or Android's), with its revision: prints of    /// different revisions are never compared. The phone's index never keeps    /// it (the coordinator, 27 Nov 2026): it stays in the shell's own store,    /// and the core groups by its own print and difference hash.    #[serde(default)]    pub print: Option<Print>,    /// Vision aesthetics overall score, −1 to 1.    #[serde(default)]    pub aesthetics: Option<f32>,    /// Vision `isUtility`: a receipt, a screenshot, a document.    #[serde(default)]    pub utility: Option<bool>,    /// A document's edges were found.    #[serde(default)]    pub document: Option<bool>,    /// Characters of text read, when the phone read any.    #[serde(default)]    pub text_chars: Option<u32>,    /// Faces found, and the best face capture quality (0–1).    #[serde(default)]    pub faces: u32,    #[serde(default)]    pub face_quality: Option<f32>,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Print {    pub revision: String,    pub values: Vec<f32>,}/// The core's measures of one photo.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Look {    pub level: Level,    /// 64-bit difference hash of a 9×8 reduction (portable).    pub dhash: u64,    /// The core's own small print: an 8×8 reduction, mean taken away, scaled    /// to unit length and stored as 64 signed bytes (portable).    pub print: Vec<i8>,    /// Sharpness (variance of the Laplacian on a 128 px reduction, 0–1 grey);    /// only at `Full`.    pub sharp: Option<f32>,    /// Mean brightness, 0–1.    pub brightness: f32,    /// Share of pixels darker than 8%.    pub dark_share: f32,    #[serde(default)]    pub platform: PlatformLook,}impl Look {    /// A photo the phone had no picture of: counted, never grouped.    pub fn none(platform: PlatformLook) -> Look {        Look { level: Level::None, dhash: 0, print: Vec::new(), sharp: None, brightness: 0.0, dark_share: 0.0, platform }    }}/// Look at what the phone handed over. `None` for the picture means the phone/// had none without the network.pub fn analyse(grey: Option<&Grey>, platform: PlatformLook) -> Look {    let Some(g) = grey.filter(|g| g.longest() >= SMALL_FROM && g.width >= 9 && g.height >= 8) else {        return Look::none(platform);    };    let level = if g.longest() >= FULL_FROM { Level::Full } else { Level::Small };    let unit: Vec<f32> = g.pixels.iter().map(|&p| p as f32 / 255.0).collect();    let (w, h) = (g.width as usize, g.height as usize);    let d = reduce(&unit, w, h, 9, 8);    let mut dhash = 0u64;    for y in 0..8 {        for x in 0..8 {            dhash = (dhash << 1) | (d[y * 9 + x] > d[y * 9 + x + 1]) as u64;        }    }    let p = reduce(&unit, w, h, 8, 8);    let mean = p.iter().sum::<f32>() / 64.0;    let centred: Vec<f32> = p.iter().map(|v| v - mean).collect();    let norm = centred.iter().map(|v| v * v).sum::<f32>().sqrt();    let print = if norm < 1e-4 { vec![0i8; 64] } else { centred.iter().map(|v| ((v / norm) * 127.0).round().clamp(-127.0, 127.0) as i8).collect() };    let brightness = unit.iter().sum::<f32>() / unit.len() as f32;    let dark_share = unit.iter().filter(|&&v| v < 0.08).count() as f32 / unit.len() as f32;    let sharp = (level == Level::Full).then(|| {        let scale = 128.0 / g.longest() as f32;        let (rw, rh) = (((w as f32 * scale).round() as usize).max(3), ((h as f32 * scale).round() as usize).max(3));        let r = reduce(&unit, w, h, rw, rh);        laplacian_variance(&r, rw, rh)    });    Look { level, dhash, print, sharp, brightness, dark_share, platform }}/// Box reduction of a `w×h` picture to `rw×rh`.fn reduce(a: &[f32], w: usize, h: usize, rw: usize, rh: usize) -> Vec<f32> {    let mut out = vec![0f32; rw * rh];    for y in 0..rh {        let (y0, y1) = (y * h / rh, ((y + 1) * h / rh).max(y * h / rh + 1).min(h));        for x in 0..rw {            let (x0, x1) = (x * w / rw, ((x + 1) * w / rw).max(x * w / rw + 1).min(w));            let mut s = 0.0;            for yy in y0..y1 {                for xx in x0..x1 {                    s += a[yy * w + xx];                }            }            out[y * rw + x] = s / ((x1 - x0) * (y1 - y0)) as f32;        }    }    out}fn laplacian_variance(a: &[f32], w: usize, h: usize) -> f32 {    let mut vals = Vec::with_capacity(w * h);    for y in 1..h - 1 {        for x in 1..w - 1 {            vals.push(4.0 * a[y * w + x] - a[y * w + x - 1] - a[y * w + x + 1] - a[(y - 1) * w + x] - a[(y + 1) * w + x]);        }    }    if vals.is_empty() {        return 0.0;    }    let m = vals.iter().sum::<f32>() / vals.len() as f32;    vals.iter().map(|v| (v - m).powi(2)).sum::<f32>() / vals.len() as f32}/// Distance between two core prints: 0 the same, 2 opposite (unit vectors).pub fn print_distance(a: &[i8], b: &[i8]) -> f32 {    if a.len() != 64 || b.len() != 64 {        return f32::INFINITY;    }    let s: f32 = a.iter().zip(b).map(|(x, y)| ((*x as f32 - *y as f32) / 127.0).powi(2)).sum();    s.sqrt()}/// Bits that differ between two difference hashes.pub fn hamming(a: u64, b: u64) -> u32 {    (a ^ b).count_ones()}/// The portable key that names one photo on every phone of his: the second it/// was taken, its pixel size and the core's difference hash. Two phones (an/// iPhone and an Android, or a phone and the Mac) that hold the same photo/// make the same key without sending the photo anywhere.pub fn match_key(taken_at_ms: i64, width: u32, height: u32, look: &Look) -> Option<String> {    (look.level != Level::None).then(|| format!("{}:{}x{}:{:016x}", taken_at_ms.div_euclid(1000), width, height, look.dhash))}