Replace the Lensfun WebAssembly runtime with our own lens engine.

The wrapper's wasm, its 5 MB data blob and the runtime chunk were fragile to
serve (CSP, MIME, cache) and pulled an LGPL runtime into the bundle just for
calibration data. The Lensfun XML is now converted at build time into
public/lens-db/profiles.json, and search, matching and the correction maths live
in src/lib/lensDb.ts and src/lib/lensEngine.ts. Maps are pinned against output
captured from the previous implementation, so results are unchanged.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
2026-11-28 05:17:02 +00:00
parent 637629385a
commit 16456c3c69
29 changed files with 1277 additions and 66564 deletions
+251
View File
@@ -0,0 +1,251 @@
import type { LensProfile, PhotoMeta } from '../types';
/**
* Lens profiles are built from the Lensfun project's calibration database
* (CC BY-SA 3.0, © Lensfun contributors) by `scripts/build-lens-db.mjs`. Only
* the measurements come from there; searching, matching and the correction
* maths are ours, so the editor ships no WebAssembly runtime and no database
* parser.
*
* The file is fetched the first time the Optics panel, a stored profile or a
* lens-corrected export needs it, and then kept in memory.
*/
/** [focal, model, a, b, c, realFocal] — a·r³ + b·r² + c·r + 1; 0 = nominal focal */
export type DistortionSample = [number, number, number, number, number, number];
/** [focal, model, br, cr, vr, bb, cb, vb] — r·(v + c·r + b·r²) per channel */
export type TcaSample = [number, number, number, number, number, number, number, number];
/** [focal, aperture, distance, k1, k2, k3] */
export type VignettingSample = [number, number, number, number, number, number];
export const DIST_MODEL = { poly3: 0, poly5: 1, ptlens: 2, linear: 3, acm: 4 } as const;
export const TCA_MODEL = { poly3: 0, linear: 1, acm: 2 } as const;
export interface LensEntry {
id: string;
maker: string;
model: string;
/** Crop factor the calibration was measured at. */
crop: number;
mounts: string[];
/** Calibration sensor aspect ratio, 0 when the database does not say. */
aspect: number;
centerX: number;
centerY: number;
d: DistortionSample[];
t: TcaSample[];
v: VignettingSample[];
}
export interface CameraEntry {
maker: string;
model: string;
mount: string;
crop: number;
}
export interface LensDatabase {
source: { project: string; commit: string; licence: string; note: string };
models: { distortion: string[]; tca: string[] };
mounts: string[];
cameras: CameraEntry[];
lenses: LensEntry[];
}
export interface CameraMatch {
maker: string;
model: string;
mount: string;
cropFactor: number;
score: number;
}
export interface LensSearchResult {
id: string;
maker: string;
model: string;
crop: number;
score: number;
/** Bit mask of the corrections the calibration supports. */
available: number;
}
export const FLAG_TCA = 1;
export const FLAG_VIGNETTING = 2;
export const FLAG_DISTORTION = 8;
let databasePromise: Promise<LensDatabase> | null = null;
export function loadLensDatabase(): Promise<LensDatabase> {
if (!databasePromise) {
databasePromise = fetch('/lens-db/profiles.json')
.then((response) => {
if (!response.ok) throw new Error(`The lens database could not be loaded (${response.status})`);
return response.json() as Promise<LensDatabase>;
})
.catch((err) => {
databasePromise = null;
throw err;
});
}
return databasePromise;
}
/** Available corrections for a profile, matching the flags the renderer uses. */
export function availableFlags(entry: LensEntry): number {
return (
(entry.d.length ? FLAG_DISTORTION : 0) |
(entry.t.length ? FLAG_TCA : 0) |
(entry.v.length ? FLAG_VIGNETTING : 0)
);
}
export function toResult(entry: LensEntry, score = 0): LensSearchResult {
return {
id: entry.id,
maker: entry.maker,
model: entry.model,
crop: entry.crop,
score,
available: availableFlags(entry),
};
}
/* ------------------------------------------------------------------ matching */
/** Lowercase word tokens, with units folded so "28-75mm" meets "28-75". */
function tokens(value: string): string[] {
return value
.toLowerCase()
.replace(/[^a-z0-9]+/g, ' ')
.trim()
.split(' ')
.filter(Boolean)
.map((token) => token.replace(/mm$/, '').replace(/^f(?=\d)/, ''));
}
function coverage(query: string[], target: Set<string>): number {
if (!query.length) return 0;
let hit = 0;
for (const token of query) if (target.has(token)) hit += 1;
return hit / query.length;
}
/**
* 3 for an exact model, otherwise the fraction of query words the entry covers,
* with a small bonus when every word matches. Both maker and model count, so
* "tamron" finds Tamron glass without needing the focal length.
*/
function scoreEntry(entry: LensEntry, variants: string[]): number {
const target = new Set([...tokens(entry.maker), ...tokens(entry.model)]);
const maker = tokens(entry.maker);
const model = tokens(entry.model);
let best = 0;
for (const variant of variants) {
const query = tokens(variant);
if (!query.length) continue;
const name = [...maker, ...model].join(' ');
if (query.join(' ') === name || query.join(' ') === model.join(' ')) return 3;
const hit = coverage(query, target);
best = Math.max(best, hit >= 1 ? 1.25 : hit);
}
return best;
}
/** Variants of the query worth matching: as typed, plus unit-normalised forms. */
function queryVariants(query: string): string[] {
const raw = query.trim();
if (raw.length < 2) return [];
const compact = raw.replace(/(\d)\s*mm\b/gi, '$1mm').replace(/\s+/g, ' ');
return [...new Set([raw, compact, compact.replace(/\s+/g, '')])].filter((text) => text.length >= 2);
}
/* ------------------------------------------------------------------- queries */
export async function searchLens(
query: string,
meta?: Pick<PhotoMeta, 'camera' | 'lens'>,
): Promise<LensSearchResult[]> {
const variants = queryVariants(query);
if (!variants.length) return [];
const db = await loadLensDatabase();
const camera = await findCamera(meta?.camera);
const mount = camera?.mount ?? '';
const scored: { entry: LensEntry; score: number }[] = [];
for (const entry of db.lenses) {
const score = scoreEntry(entry, variants);
if (score < 0.5) continue;
// A mount the camera actually uses is a tie-break, never a filter: a
// profile that is in the database but filed under another mount must still
// be findable.
const fits = mount && entry.mounts.includes(mount) ? 0.3 : 0;
scored.push({ entry, score: score + fits });
}
scored.sort((a, b) => b.score - a.score || a.entry.model.length - b.entry.model.length);
return scored.slice(0, 20).map(({ entry, score }) => toResult(entry, Math.min(3, score)));
}
export async function findLensForMeta(
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
): Promise<LensSearchResult | null> {
if (!meta.lens) return null;
const results = await searchLens(meta.lens, meta);
return results.find((result) => result.score >= 0.75) ?? results[0] ?? null;
}
const cameraCache = new Map<string, CameraMatch | null>();
export async function findCamera(camera?: string): Promise<CameraMatch | null> {
if (!camera) return null;
const cached = cameraCache.get(camera);
if (cached !== undefined) return cached;
const db = await loadLensDatabase();
const query = tokens(camera);
let best: CameraMatch | null = null;
let bestScore = 0;
for (const entry of db.cameras) {
const target = new Set([...tokens(entry.maker), ...tokens(entry.model)]);
// Ignore the maker prefix the EXIF repeats, e.g. "NIKON CORPORATION".
const model = tokens(entry.model);
const score = Math.max(coverage(query, target), coverage(model, target) * 0.9);
if (score > bestScore) {
bestScore = score;
best = {
maker: entry.maker,
model: entry.model,
mount: entry.mount,
cropFactor: entry.crop,
score,
};
}
}
const match = bestScore >= 0.6 ? best : null;
cameraCache.set(camera, match);
return match;
}
/** Exact entry for a stored profile, falling back to the closest name match. */
export async function getLensEntry(profile: LensProfile): Promise<LensEntry | null> {
const db = await loadLensDatabase();
if (profile.id) {
const byId = db.lenses.find((entry) => entry.id === profile.id);
if (byId) return byId;
}
const maker = profile.maker.trim().toLowerCase();
const model = profile.model.trim().toLowerCase();
const exact = db.lenses.find(
(entry) => entry.maker.toLowerCase() === maker && entry.model.toLowerCase() === model,
);
if (exact) return exact;
const sameModel = db.lenses.filter((entry) => entry.model.toLowerCase() === model);
if (sameModel.length === 1) return sameModel[0];
const scored = db.lenses
.map((entry) => ({ entry, score: scoreEntry(entry, [profile.model, `${profile.maker} ${profile.model}`]) }))
.sort((a, b) => b.score - a.score);
return scored[0] && scored[0].score >= 0.5 ? scored[0].entry : null;
}
export async function availableFor(profile: LensProfile): Promise<number> {
const entry = await getLensEntry(profile);
return entry ? availableFlags(entry) : 0;
}