// The footage moved and scaled so this clip's face sits in an effect's window; the value is {x, y, s}, origin top left. import { isNumber, type JsonObject, listOf, round } from "./json.js"; const FACE_SHARE = 0.5; /** Where the face's centre sits down the window, as a share of its height: a little above the middle, room for the chin. */ const FACE_DOWN = 0.45; const median = (values: number[]): number => { const sorted = [...values].sort((a, b) => a - b); return sorted[Math.floor(sorted.length / 2)] ?? 0; }; const numbers = (value: unknown, count: number): number[] | null => { const list = listOf(value as never).filter(isNumber); return list.length === count ? list : null; }; /** {x, y, s} framing the faces ([t, centre x, centre y, width] frame fractions) in the rule's box; null with no face. */ export function faceWindow( faces: number[][] | null, rule: JsonObject, aspect: number, ): JsonObject | null { const box = numbers(rule.box, 4); if (!box || !faces?.length) return null; const [x0, y0, x1, y1] = box as [number, number, number, number]; const [w, h] = (numbers(rule.frame, 2) ?? [1080, Math.round(1080 * aspect)]) as [number, number]; const cx = median(faces.map((f) => f[1] ?? 0)) * w; const cy = median(faces.map((f) => f[2] ?? 0)) * h; const wide = median(faces.map((f) => f[3] ?? 0)) * w; if (!(wide > 0)) return null; const boxW = x1 - x0; const boxH = y1 - y0; const s = Math.max((FACE_SHARE * boxW) / wide, boxW / w, boxH / h); const clamp = (v: number, lo: number, hi: number) => Math.min(Math.max(v, lo), hi); const x = clamp(x0 + boxW / 2 - s * cx, x1 - s * w, x0); const y = clamp(y0 + FACE_DOWN * boxH - s * cy, y1 - s * h, y0); return { x: round(x, 1), y: round(y, 1), s: round(s, 4) }; }