Files
luminary/scripts/build-lens-db.mjs
T
bhursey 16456c3c69 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>
2026-11-28 05:17:02 +00:00

309 lines
10 KiB
JavaScript

#!/usr/bin/env node
/**
* Builds the lens profile database the editor ships.
*
* The calibration measurements come from the Lensfun project's database
* (CC BY-SA 3.0, © Lensfun contributors); this script only converts the XML
* into the compact form `src/lib/lensDb.ts` reads, so the app no longer needs
* the Lensfun WebAssembly runtime. Data, not code: the maths lives in
* `src/lib/lensEngine.ts`.
*
* Usage:
* node scripts/build-lens-db.mjs --db <lensfun/data/db> [--out <file>]
*
* `--db` is a checkout of https://github.com/lensfun/lensfun at the pinned commit
* recorded in `public/lens-db/NOTICE.md`; only its `data/db/*.xml` files are read.
* The generated file is committed, so a normal build does not need the checkout.
*/
import { readFileSync, writeFileSync, readdirSync, mkdirSync, existsSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
const DIST_MODELS = ['poly3', 'poly5', 'ptlens', 'linear', 'acm'];
const TCA_MODELS = ['poly3', 'linear', 'acm'];
const args = process.argv.slice(2);
const argValue = (name, fallback) => {
const at = args.indexOf(name);
return at >= 0 && args[at + 1] ? args[at + 1] : fallback;
};
const DB_DIR = argValue('--db', '');
const OUT = resolve(argValue('--out', 'public/lens-db/profiles.json'));
/* ------------------------------------------------------------------ parsing */
/** Rounds to six decimals and drops trailing zeros, to keep the file small. */
function round(n) {
return Number.isFinite(n) ? Math.round(n * 1e6) / 1e6 : 0;
}
function num(value) {
if (value == null || value === '') return 0;
return round(Number(value));
}
/** "3:2" or "1.5" as a number, 0 when absent so the engine can use the image. */
function aspectRatio(value) {
if (!value) return 0;
const parts = value.split(':').map(Number);
if (parts.length === 2 && parts[0] > 0 && parts[1] > 0) return round(parts[0] / parts[1]);
return num(value);
}
const TAG = /<(\/?)([a-zA-Z0-9_:.-]+)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
const ATTR = /([a-zA-Z0-9_:.-]+)\s*=\s*("([^"]*)"|'([^']*)')/g;
function attributes(source) {
const out = {};
for (const match of source.matchAll(ATTR)) {
out[match[1]] = decode(match[3] ?? match[4] ?? '');
}
return out;
}
/**
* Minimal XML reader for the Lensfun schema: elements, attributes and text.
* Comments and the doctype are skipped; nothing here needs namespaces,
* entities beyond the five predefined ones, or CDATA.
*/
function parseXml(source) {
// Comments carry prose (and markup examples) that must not reach the tag
// scanner, or they unbalance the element stack.
const xml = source.replace(/<!--[\s\S]*?-->/g, '');
const root = { name: '#root', attrs: {}, children: [], text: '' };
const stack = [root];
let cursor = 0;
TAG.lastIndex = 0;
for (let match = TAG.exec(xml); match; match = TAG.exec(xml)) {
const [whole, closing, name, rawAttrs, selfClosing] = match;
const between = xml.slice(cursor, match.index);
cursor = match.index + whole.length;
if (between.trim()) stack[stack.length - 1].text += decode(between.trim());
if (closing) {
if (stack.length > 1) stack.pop();
continue;
}
const node = { name, attrs: attributes(rawAttrs), children: [], text: '' };
stack[stack.length - 1].children.push(node);
if (!selfClosing) stack.push(node);
}
return root;
}
function decode(text) {
return text
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&amp;/g, '&');
}
const kids = (node, name) => node.children.filter((child) => child.name === name);
const kid = (node, name) => kids(node, name)[0];
const text = (node) => (node ? node.text.trim() : '');
/** Picks the untagged value, falling back to English. */
function localized(node, name) {
const all = kids(node, name);
if (!all.length) return '';
const plain = all.find((entry) => !entry.attrs.lang);
if (plain) return text(plain);
const english = all.find((entry) => entry.attrs.lang === 'en' || entry.attrs.lang === 'en_US');
return text(english ?? all[0]);
}
/* --------------------------------------------------------------- conversion */
function convertFile(xml, db) {
const doc = parseXml(xml);
const root = kid(doc, 'lensdatabase');
if (!root) return;
for (const mount of kids(root, 'mount')) {
const name = text(kid(mount, 'name'));
if (name) db.mounts.add(name);
}
for (const camera of kids(root, 'camera')) {
const maker = localized(camera, 'maker');
const model = localized(camera, 'model');
if (!maker || !model) continue;
db.cameras.push({ maker, model, mount: text(kid(camera, 'mount')), crop: num(text(kid(camera, 'cropfactor'))) || 1 });
}
for (const lens of kids(root, 'lens')) {
const maker = localized(lens, 'maker');
const model = localized(lens, 'model');
if (!maker || !model) continue;
const record = {
maker,
model,
crop: num(text(kid(lens, 'cropfactor'))) || 1,
mounts: kids(lens, 'mount').map((entry) => text(entry)).filter(Boolean),
aspect: aspectRatio(text(kid(lens, 'aspect-ratio'))),
centerX: num(text(kid(lens, 'center-x'))),
centerY: num(text(kid(lens, 'center-y'))),
d: [],
t: [],
v: [],
};
const calibration = kid(lens, 'calibration');
if (calibration) {
for (const entry of kids(calibration, 'distortion')) {
const terms = distortionTerms(entry);
if (!terms) continue;
// A few calibrations were measured at a focal length other than the
// nominal one; Lensfun scales by the ratio, so keep it (0 = same focal).
record.d.push([
num(entry.attrs.focal),
terms.model,
...terms.terms,
num(entry.attrs['real-focal']),
]);
}
for (const entry of kids(calibration, 'tca')) {
const terms = tcaTerms(entry);
if (!terms) continue;
record.t.push([num(entry.attrs.focal), terms.model, ...terms.terms]);
}
for (const entry of kids(calibration, 'vignetting')) {
const model = entry.attrs.model;
if (model !== 'pa' && model !== 'acm') continue;
record.v.push([
num(entry.attrs.focal),
num(entry.attrs.aperture),
num(entry.attrs.distance),
num(entry.attrs.k1),
num(entry.attrs.k2),
num(entry.attrs.k3),
]);
}
}
db.stats.lenses += 1;
if (record.d.length || record.t.length || record.v.length) db.lenses.push(record);
else db.stats.withoutCalibration += 1;
}
}
/**
* Lensfun stores poly3 as `k1`, polygon (poly5) as `k1`/`k2`, and PanoTools as
* `a`/`b`/`c`. Everything is normalised to the `a·r³ + b·r² + c·r + 1` form the
* engine evaluates, with the PanoTools `d = 1 - a - b - c` factor divided out
* the way Lensfun does so the focal length is preserved.
*/
function distortionTerms(entry) {
const attrs = entry.attrs;
switch (attrs.model) {
case 'poly3': {
const k1 = num(attrs.k1);
const d = 1 - k1;
return { model: DIST_MODELS.indexOf('poly3'), terms: [0, round(k1 / d ** 3), 0] };
}
case 'poly5':
return { model: DIST_MODELS.indexOf('poly5'), terms: [0, num(attrs.k1), num(attrs.k2)] };
case 'ptlens': {
const a = num(attrs.a);
const b = num(attrs.b);
const c = num(attrs.c);
const d = 1 - a - b - c;
return {
model: DIST_MODELS.indexOf('ptlens'),
terms: [round(a / d ** 4), round(b / d ** 3), round(c / d ** 2)],
};
}
case 'linear':
return { model: DIST_MODELS.indexOf('linear'), terms: [0, 0, 0] };
default:
return null;
}
}
function tcaTerms(entry) {
const attrs = entry.attrs;
if (attrs.model === 'poly3') {
// Stored per channel as [br, cr, vr] / [bb, cb, vb], matching the term
// order the engine evaluates: r_d = r * (v + c*r + b*r^2).
return {
model: TCA_MODELS.indexOf('poly3'),
terms: [num(attrs.br), num(attrs.cr), num(attrs.vr || 1), num(attrs.bb), num(attrs.cb), num(attrs.vb || 1)],
};
}
if (attrs.model === 'linear') {
return { model: TCA_MODELS.indexOf('linear'), terms: [num(attrs.kr || 1), num(attrs.kb || 1)] };
}
return null;
}
/* --------------------------------------------------------------------- main */
function loadXmlFiles() {
if (!DB_DIR) {
throw new Error(
'pass --db <path to lensfun/data/db>; the profiles are committed, so this is only ' +
'needed when refreshing them',
);
}
const dir = resolve(DB_DIR);
if (!existsSync(dir)) throw new Error(`database directory not found: ${dir}`);
return readdirSync(dir)
.filter((name) => name.endsWith('.xml'))
.sort()
.map((name) => readFileSync(join(dir, name), 'utf8'));
}
const db = { mounts: new Set(), cameras: [], lenses: [], stats: { lenses: 0, withoutCalibration: 0 } };
for (const xml of loadXmlFiles()) {
try {
convertFile(xml, db);
} catch (err) {
console.warn(`skipped a database file: ${err.message}`);
}
}
const slug = (value) =>
value
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
const seen = new Map();
const lenses = db.lenses.map((lens) => {
const base = `${slug(lens.maker)}-${slug(lens.model)}`;
const count = (seen.get(base) ?? 0) + 1;
seen.set(base, count);
return {
id: count === 1 ? base : `${base}-${count}`,
maker: lens.maker,
model: lens.model,
crop: lens.crop,
mounts: lens.mounts,
aspect: lens.aspect,
centerX: lens.centerX,
centerY: lens.centerY,
d: lens.d.sort((a, b) => a[0] - b[0]),
t: lens.t.sort((a, b) => a[0] - b[0]),
v: lens.v.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]),
};
});
const payload = {
source: {
project: 'lensfun',
commit: '655a9c4e3e53c25bc04843c853e7e7a0121359e7',
licence: 'CC BY-SA 3.0 Unported',
note: 'Calibration data only; the correction maths is Luminary\u2019s own.',
},
models: { distortion: DIST_MODELS, tca: TCA_MODELS },
mounts: [...db.mounts].sort(),
cameras: db.cameras.sort((a, b) => a.maker.localeCompare(b.maker) || a.model.localeCompare(b.model)),
lenses,
};
mkdirSync(dirname(OUT), { recursive: true });
writeFileSync(OUT, `${JSON.stringify(payload)}\n`);
console.log(
`wrote ${OUT}: ${lenses.length} lenses with calibration (${db.stats.withoutCalibration} of ` +
`${db.stats.lenses} entries have none), ${payload.cameras.length} cameras, ` +
`${lenses.reduce((n, lens) => n + lens.v.length, 0)} vignetting samples`,
);