import type { Edits } from '../types'; import { clamp } from './curves'; interface Stats { mean: number; p05: number; p95: number; saturation: number; } async function analyze(thumb: string): Promise { const img = new Image(); img.src = thumb; await img.decode(); const w = 96; const h = Math.max(1, Math.round((img.height / img.width) * w)) || 96; const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; const ctx = canvas.getContext('2d'); if (!ctx) throw new Error('Canvas unavailable'); ctx.drawImage(img, 0, 0, w, h); const { data } = ctx.getImageData(0, 0, w, h); const hist = new Uint32Array(256); let total = 0; let lumaSum = 0; let satSum = 0; for (let i = 0; i < data.length; i += 4) { const r = data[i] / 255; const g = data[i + 1] / 255; const b = data[i + 2] / 255; const l = 0.2126 * r + 0.7152 * g + 0.0722 * b; hist[Math.round(l * 255)]++; lumaSum += l; satSum += Math.max(r, g, b) - Math.min(r, g, b); total++; } const percentile = (p: number) => { const target = total * p; let acc = 0; for (let i = 0; i < 256; i++) { acc += hist[i]; if (acc >= target) return i / 255; } return 1; }; return { mean: lumaSum / total, p05: percentile(0.05), p95: percentile(0.95), saturation: satSum / total, }; } /** Simple histogram based auto tone, in the spirit of Lightroom's Auto button. */ export async function computeAutoEdits(thumb: string): Promise> { try { const s = await analyze(thumb); const mean = clamp(s.mean, 0.03, 0.97); const exposure = clamp(Math.log2(0.46 / mean), -2, 2); return { exposure: Math.round(exposure * 100) / 100, contrast: s.p95 - s.p05 < 0.55 ? 18 : 10, highlights: s.p95 > 0.94 ? -32 : 4, shadows: s.p05 < 0.055 ? 32 : 4, whites: s.p95 > 0.96 ? -8 : 10, blacks: s.p05 < 0.03 ? 6 : -6, vibrance: s.saturation < 0.18 ? 18 : 8, }; } catch { return { contrast: 12, shadows: 12, highlights: -12, vibrance: 8 }; } }