import { DIST_MODEL, TCA_MODEL, getLensEntry, type DistortionSample, type LensEntry, type TcaSample, type VignettingSample, } from './lensDb'; import type { LensProfile, PhotoMeta } from '../types'; /** * Lens correction without Lensfun's runtime. * * The calibration data comes from the Lensfun database (see `lensDb.ts`); the * maths below is a port of the models it describes, evaluated in the same * normalised coordinate system so results match what the previous WebAssembly * build produced: * * norm = (36, 24) diagonal / crop / hypot(width + 1, height + 1) / focal * x = column * norm - centreX * * Distortion maps sample the original image for each corrected pixel, TCA maps * carry per-channel positions, and the vignetting map is a flat-field gain. */ export interface LensMap { data: Float32Array; width: number; height: number; } export interface LensCorrection { key: string; geometry: LensMap; /** RG offsets: red dx, red dy, blue dx, blue dy, normalized source units. */ tca?: LensMap; /** RGB vignetting gains. */ vignette?: LensMap; /** Centre zoom needed to hide transformed corners. */ scale: number; } const SENSOR_DIAGONAL = Math.hypot(36, 24); const DEFAULT_ASPECT = 3 / 2; const correctionCache = new Map(); function clampAspect(entry: LensEntry) { return entry.aspect > 0 ? entry.aspect : DEFAULT_ASPECT; } /** Lensfun rescales each coefficient by focal / half-diagonal, per model. */ function distortionScale(entry: LensEntry, realFocal: number) { const halfDiagonalMm = SENSOR_DIAGONAL / entry.crop / Math.hypot(clampAspect(entry), 1) / 2; return realFocal / halfDiagonalMm; } function vignettingScale(entry: LensEntry, focal: number) { const halfDiagonalMm = SENSOR_DIAGONAL / entry.crop / 2; return focal / halfDiagonalMm; } /* ------------------------------------------------------------- interpolation */ function pickDistortion(entry: LensEntry, focal: number): DistortionSample | null { const samples = entry.d; if (!samples.length) return null; return nearestByFocal(samples, focal); } function pickTca(entry: LensEntry, focal: number): TcaSample | null { const samples = entry.t; if (!samples.length) return null; return nearestByFocal(samples, focal); } /** * Linear in focal for a pair of samples that share a model; otherwise the * closest focal. Lensfun uses splines, but at the handful of focal lengths * these calibrations carry the difference is far below a pixel. */ function nearestByFocal(samples: T[], focal: number): T { if (samples.length === 1 || !focal) return samples[0]; if (focal <= samples[0][0]) return samples[0]; const last = samples[samples.length - 1]; if (focal >= last[0]) return last; let index = 0; while (index < samples.length - 1 && samples[index + 1][0] < focal) index += 1; const a = samples[index]; const b = samples[index + 1]; const span = b[0] - a[0]; if (!span) return a; const t = (focal - a[0]) / span; return a.map((value, i) => value + (b[i] - value) * t) as unknown as T; } /** Closest focal group, then closest aperture, then closest focus distance. */ function pickVignetting(entry: LensEntry, focal: number, aperture: number, distance: number): VignettingSample | null { const samples = entry.v; if (!samples.length) return null; const closest = (values: number[], target: number) => values.reduce((best, value) => (Math.abs(value - target) < Math.abs(best - target) ? value : best), values[0]); const focals = [...new Set(samples.map((sample) => sample[0]))]; const focalPick = focal ? closest(focals, focal) : focals[0]; let group = samples.filter((sample) => sample[0] === focalPick); if (!group.length) group = samples; const apertures = [...new Set(group.map((sample) => sample[1]))]; const aperturePick = aperture ? closest(apertures, aperture) : apertures[0]; group = group.filter((sample) => sample[1] === aperturePick); if (!group.length) group = samples; const distances = [...new Set(group.map((sample) => sample[2]))]; const distancePick = distance ? closest(distances, distance) : distances[0]; return group.find((sample) => sample[2] === distancePick) ?? group[0]; } /* ------------------------------------------------------------------ the maps */ type TcaTerms = | { model: 1; kr: number; kb: number } | { model: 0; r: [number, number, number]; b: [number, number, number] }; export interface MapOptions { width: number; height: number; focal: number; crop: number; aperture?: number; distance?: number; distortion: boolean; } export interface MapSet { width: number; height: number; /** 2 floats per point: source x/y in map pixels. */ geometry: Float32Array; /** 6 floats per point: red x/y, input x/y, blue x/y. */ tca?: Float32Array; /** 3 floats per point: the same gain for R, G and B. */ vignetting?: Float32Array; } export function computeMaps(entry: LensEntry, options: MapOptions): MapSet { const { width, height } = options; const crop = options.crop || entry.crop; const distortion = pickDistortion(entry, options.focal); const realFocal = (distortion && distortion[5]) || options.focal; const normScale = SENSOR_DIAGONAL / crop / Math.hypot(width, height) / realFocal || 1; const centreSize = Math.min(width - 1, height - 1); const centreX = ((width - 1) / 2 + (centreSize / 2) * entry.centerX) * normScale; const centreY = ((height - 1) / 2 + (centreSize / 2) * entry.centerY) * normScale; const scale = distortionScale(entry, realFocal); const dTerms = distortion && options.distortion ? { model: distortion[1], a: distortion[2], b: distortion[3], c: distortion[4], scaled: distortion[1] === DIST_MODEL.ptlens ? [distortion[2] * scale ** 3, distortion[3] * scale ** 2, distortion[4] * scale] : distortion[1] === DIST_MODEL.poly5 ? [0, distortion[3] * scale ** 2, distortion[4] * scale ** 4] : [0, distortion[3] * scale ** 2, 0], } : null; const tcaSample = options.distortion ? pickTca(entry, options.focal) : null; const tcaTerms: TcaTerms | null = tcaSample ? tcaSample[1] === TCA_MODEL.linear ? { model: 1, kr: tcaSample[2], kb: tcaSample[5] } : { model: 0, // r·(v + c·r + b·r²); c is scaled by focal, b by focal squared. r: [tcaSample[2] * scale ** 2, tcaSample[3] * scale, tcaSample[4]], b: [tcaSample[5] * scale ** 2, tcaSample[6] * scale, tcaSample[7]], } : null; const vignSample = pickVignetting(entry, options.focal, options.aperture ?? 0, options.distance ?? 1000); const vigScale = vignettingScale(entry, options.focal); const vigTerms = vignSample ? [ vignSample[3] * vigScale ** 2, vignSample[4] * vigScale ** 4, vignSample[5] * vigScale ** 6, ] : null; const geometry = new Float32Array(width * height * 2); const tca = tcaTerms ? new Float32Array(width * height * 6) : undefined; const vignetting = vigTerms ? new Float32Array(width * height * 3) : undefined; for (let row = 0; row < height; row++) { const v = row * normScale - centreY; for (let col = 0; col < width; col++) { const u = col * normScale - centreX; const radius2 = u * u + v * v; const at = row * width + col; let factor = 1; if (dTerms) { if (dTerms.model === DIST_MODEL.ptlens) { const r = Math.sqrt(radius2); factor = 1 + dTerms.scaled[0] * radius2 * r + dTerms.scaled[1] * radius2 + dTerms.scaled[2] * r; } else if (dTerms.model === DIST_MODEL.poly5) { factor = 1 + dTerms.scaled[1] * radius2 + dTerms.scaled[2] * radius2 * radius2; } else if (dTerms.model === DIST_MODEL.poly3) { factor = 1 + dTerms.scaled[1] * radius2; } } geometry[at * 2] = (u * factor + centreX) / normScale; geometry[at * 2 + 1] = (v * factor + centreY) / normScale; if (tca && tcaTerms) { const r = Math.sqrt(radius2); if (tcaTerms.model === 1) { tca[at * 6] = (u * tcaTerms.kr + centreX) / normScale; tca[at * 6 + 1] = (v * tcaTerms.kr + centreY) / normScale; tca[at * 6 + 4] = (u * tcaTerms.kb + centreX) / normScale; tca[at * 6 + 5] = (v * tcaTerms.kb + centreY) / normScale; } else { const red = tcaTerms.r[0] * radius2 + tcaTerms.r[1] * r + tcaTerms.r[2]; const blue = tcaTerms.b[0] * radius2 + tcaTerms.b[1] * r + tcaTerms.b[2]; tca[at * 6] = (u * red + centreX) / normScale; tca[at * 6 + 1] = (v * red + centreY) / normScale; tca[at * 6 + 4] = (u * blue + centreX) / normScale; tca[at * 6 + 5] = (v * blue + centreY) / normScale; } // Green keeps the input position; the renderer only needs red and blue. tca[at * 6 + 2] = col; tca[at * 6 + 3] = row; } if (vignetting && vigTerms) { const gain = 1 / (1 + vigTerms[0] * radius2 + vigTerms[1] * radius2 ** 2 + vigTerms[2] * radius2 ** 3); vignetting[at * 3] = gain; vignetting[at * 3 + 1] = gain; vignetting[at * 3 + 2] = gain; } } } return { width, height, geometry, tca, vignetting }; } /* --------------------------------------------------------------- assembling */ function bilinear(values: Float32Array, w: number, h: number, x: number, y: number, stride: number, offset: number) { const px = Math.max(0, Math.min(w - 1, x * (w - 1))); const py = Math.max(0, Math.min(h - 1, y * (h - 1))); const x0 = Math.floor(px); const y0 = Math.floor(py); const x1 = Math.min(w - 1, x0 + 1); const y1 = Math.min(h - 1, y0 + 1); const fx = px - x0; const fy = py - y0; const at = (xx: number, yy: number) => (yy * w + xx) * stride + offset; const a = values[at(x0, y0)]; const b = values[at(x1, y0)]; const c = values[at(x0, y1)]; const d = values[at(x1, y1)]; return (a * (1 - fx) + b * fx) * (1 - fy) + (c * (1 - fx) + d * fx) * fy; } export function autoScaleFor(geometry: LensMap): number { const sample = (x: number, y: number) => { const px = x * (geometry.width - 1); const py = y * (geometry.height - 1); const x0 = Math.max(0, Math.min(geometry.width - 1, Math.floor(px))); const y0 = Math.max(0, Math.min(geometry.height - 1, Math.floor(py))); const x1 = Math.min(geometry.width - 1, x0 + 1); const y1 = Math.min(geometry.height - 1, y0 + 1); const fx = px - x0; const fy = py - y0; const at = (xx: number, yy: number) => (yy * geometry.width + xx) * 4; const a = at(x0, y0); const b = at(x1, y0); const c = at(x0, y1); const d = at(x1, y1); return { x: (geometry.data[a] * (1 - fx) + geometry.data[b] * fx) * (1 - fy) + (geometry.data[c] * (1 - fx) + geometry.data[d] * fx) * fy, y: (geometry.data[a + 1] * (1 - fx) + geometry.data[b + 1] * fx) * (1 - fy) + (geometry.data[c + 1] * (1 - fx) + geometry.data[d + 1] * fx) * fy, }; }; const inside = (scale: number) => { for (let iy = 0; iy <= 24; iy++) { for (let ix = 0; ix <= 24; ix++) { const x = 0.5 + (ix / 24 - 0.5) / scale; const y = 0.5 + (iy / 24 - 0.5) / scale; const p = sample(x, y); if (p.x < 0.001 || p.y < 0.001 || p.x > 0.999 || p.y > 0.999) return false; } } return true; }; if (inside(1)) return 1; let lo = 1; let hi = 2.5; for (let i = 0; i < 12; i++) { const mid = (lo + hi) / 2; if (inside(mid)) hi = mid; else lo = mid; } return hi; } export async function buildLensCorrection( profile: LensProfile, photo: { width: number; height: number; meta: Pick }, ): Promise { const key = `${profile.maker}\u0000${profile.model}|${profile.crop}|${photo.width}x${photo.height}|${ photo.meta.focal ?? 0 }|${photo.meta.aperture ?? 0}|${profile.corrections.distortion ? 1 : 0}${ profile.corrections.tca ? 1 : 0 }${profile.corrections.vignetting ? 1 : 0}|${profile.distance ?? 1000}`; const cached = correctionCache.get(key); if (cached) return cached; const entry = await getLensEntry(profile); if (!entry) throw new Error('Lens profile not found in the database'); const focal = Number(photo.meta.focal) || 0; if (!focal) throw new Error('This photo has no focal length in its EXIF data'); const available = (entry.d.length ? 8 : 0) | (entry.t.length ? 1 : 0) | (entry.v.length ? 2 : 0); const useDistortion = profile.corrections.distortion && (available & 8) !== 0; const useTca = profile.corrections.tca && (available & 1) !== 0; const useVignetting = profile.corrections.vignetting && (available & 2) !== 0 && Number(photo.meta.aperture) > 0; const long = 640; const aspect = Math.max(0.1, photo.width / Math.max(1, photo.height)); const mapW = aspect >= 1 ? long : Math.max(8, Math.round(long * aspect)); const mapH = aspect >= 1 ? Math.max(8, Math.round(long / aspect)) : long; const maps = computeMaps(entry, { width: mapW, height: mapH, focal, crop: profile.crop, aperture: Number(photo.meta.aperture) || 1, distance: profile.distance ?? 1000, distortion: useDistortion, }); // Textures are RGBA32F so the renderer can use one upload path for all three // maps. Geometry and TCA only need the first channels, but keeping four // channels also means the texture is always fully specified. const geometry = new Float32Array(mapW * mapH * 4); for (let i = 0; i < mapW * mapH; i++) { if (useDistortion) { geometry[i * 4] = maps.geometry[i * 2] / Math.max(1, mapW - 1); geometry[i * 4 + 1] = maps.geometry[i * 2 + 1] / Math.max(1, mapH - 1); } else { geometry[i * 4] = (i % mapW) / Math.max(1, mapW - 1); geometry[i * 4 + 1] = Math.floor(i / mapW) / Math.max(1, mapH - 1); } geometry[i * 4 + 3] = 1; } const geometryMap: LensMap = { data: geometry, width: mapW, height: mapH }; let tca: LensMap | undefined; if (useTca && maps.tca) { tca = { data: new Float32Array(mapW * mapH * 4), width: mapW, height: mapH }; for (let i = 0; i < mapW * mapH; i++) { const x = (i % mapW) / Math.max(1, mapW - 1); const y = Math.floor(i / mapW) / Math.max(1, mapH - 1); const gx = useDistortion ? geometry[i * 4] : x; const gy = useDistortion ? geometry[i * 4 + 1] : y; const rx = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 0) / Math.max(1, mapW - 1); const ry = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 1) / Math.max(1, mapH - 1); const bx = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 4) / Math.max(1, mapW - 1); const by = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 5) / Math.max(1, mapH - 1); tca.data[i * 4] = rx - gx; tca.data[i * 4 + 1] = ry - gy; tca.data[i * 4 + 2] = bx - gx; tca.data[i * 4 + 3] = by - gy; } } let vignette: LensMap | undefined; if (useVignetting && maps.vignetting) { vignette = { data: new Float32Array(mapW * mapH * 4), width: mapW, height: mapH }; for (let i = 0; i < mapW * mapH; i++) { vignette.data[i * 4] = maps.vignetting[i * 3]; vignette.data[i * 4 + 1] = maps.vignetting[i * 3 + 1]; vignette.data[i * 4 + 2] = maps.vignetting[i * 3 + 2]; vignette.data[i * 4 + 3] = 1; } } const correction: LensCorrection = { key, geometry: geometryMap, tca, vignette, scale: useDistortion ? autoScaleFor(geometryMap) : 1, }; correctionCache.set(key, correction); return correction; } /* ------------------------------------------------------------- CPU map math */ export function sampleLensMap(map: LensMap, x: number, y: number): { x: number; y: number } { return { x: bilinear(map.data, map.width, map.height, x, y, 4, 0), y: bilinear(map.data, map.width, map.height, x, y, 4, 1), }; } export function correctLensPoint( correction: LensCorrection | null, x: number, y: number, ): { x: number; y: number } { if (!correction) return { x, y }; const sx = 0.5 + (x - 0.5) / Math.max(1e-5, correction.scale); const sy = 0.5 + (y - 0.5) / Math.max(1e-5, correction.scale); return sampleLensMap(correction.geometry, sx, sy); } export function uncorrectLensPoint( correction: LensCorrection | null, x: number, y: number, ): { x: number; y: number } { if (!correction) return { x, y }; let px = x; let py = y; for (let i = 0; i < 10; i++) { const mapped = correctLensPoint(correction, px, py); px += x - mapped.x; py += y - mapped.y; } return { x: px, y: py }; }