// A difference hash of a frame's tiny grey thumbnail (release 30, lane P): // the cheap test of "the same picture as the last one" that lets a static // lobby or break screen cost one read. Pure. // // The thumbnail is (w+1)×h grey bytes, row-major, as ffmpeg writes // `scale=:,format=gray` rawvideo: each bit says whether a pixel is // brighter than its right-hand neighbour, so the hash survives a change of // overall brightness and of compression noise, and a picture that moves does // not. export const THUMB_W = 17; export const THUMB_H = 16; export const THUMB_BYTES = THUMB_W * THUMB_H; /** The dHash (hex, `(w-1)·h` bits) of one `w`×`h` grey thumbnail. */ export function dHash(px: Uint8Array | Buffer, w = THUMB_W, h = THUMB_H): string { if (px.length < w * h) throw new Error(`a ${w}×${h} thumbnail is ${w * h} bytes, not ${px.length}`); const bits: number[] = []; for (let r = 0; r < h; r++) for (let c = 0; c < w - 1; c++) bits.push(px[r * w + c] > px[r * w + c + 1] ? 1 : 0); while (bits.length % 4) bits.push(0); let hex = ""; for (let i = 0; i < bits.length; i += 4) hex += ((bits[i] << 3) | (bits[i + 1] << 2) | (bits[i + 2] << 1) | bits[i + 3]).toString(16); return hex; } const POP = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]; /** Bits two hashes of one length differ by; Infinity when they cannot be compared. */ export function hamming(a: string, b: string): number { if (!a || a.length !== b.length) return Infinity; let d = 0; for (let i = 0; i < a.length; i++) { const x = parseInt(a[i], 16) ^ parseInt(b[i], 16); if (Number.isNaN(x)) return Infinity; d += POP[x]; } return d; } /** Split ffmpeg's rawvideo stream of thumbnails into one hash per frame. */ export function hashesOf(raw: Buffer | Uint8Array, w = THUMB_W, h = THUMB_H): string[] { const n = Math.floor(raw.length / (w * h)); const out: string[] = []; for (let i = 0; i < n; i++) out.push(dHash(raw.subarray(i * w * h, (i + 1) * w * h), w, h)); return out; } /** * Which frames a model must read: a frame is a duplicate of the last frame * READ when their hashes differ by at most `maxBits`, and a duplicate run is * read again every `rereadEvery` frames. Answers, per frame in order, null (read * it) or the index of the frame it duplicates. */ export function duplicatesOf(hashes: readonly string[], o: { maxBits: number; rereadEvery: number }): (number | null)[] { const out: (number | null)[] = []; let lastRead = -1; let run = 0; for (let i = 0; i < hashes.length; i++) { const dup = lastRead >= 0 && hamming(hashes[i], hashes[lastRead]) <= o.maxBits; if (dup && (o.rereadEvery <= 0 || run + 1 < o.rereadEvery)) { out.push(lastRead); run++; } else { out.push(null); lastRead = i; run = 0; } } return out; }