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:
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { get16BitSource, getBitmap } from '../lib/images';
|
||||
import type { Preview16 } from '../lib/preview16';
|
||||
import { rotatedBounds, Renderer } from '../gl/renderer';
|
||||
import { buildLensCorrection, type LensCorrection } from '../lib/lensfun';
|
||||
import { buildLensCorrection, type LensCorrection } from '../lib/lensEngine';
|
||||
import type { PhotoRecord } from '../types';
|
||||
|
||||
interface Props {
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
correctLensPoint,
|
||||
uncorrectLensPoint,
|
||||
type LensCorrection,
|
||||
} from '../lib/lensfun';
|
||||
} from '../lib/lensEngine';
|
||||
import {
|
||||
frameToSource,
|
||||
rotatedBounds,
|
||||
|
||||
@@ -37,7 +37,7 @@ import {
|
||||
type SavedCameraProfile,
|
||||
} from '../lib/dcpLibrary';
|
||||
import { usePresetThumbs } from './PresetThumbs';
|
||||
import { availableFor, findLensForMeta, searchLens, type LensSearchResult } from '../lib/lensfun';
|
||||
import { availableFor, findLensForMeta, searchLens, type LensSearchResult } from '../lib/lensDb';
|
||||
import {
|
||||
getCameraLensDefault,
|
||||
removeCameraLensDefault,
|
||||
@@ -1905,8 +1905,9 @@ export function OpticsPanel({
|
||||
};
|
||||
}, [profile]);
|
||||
|
||||
const applyProfile = (result: Pick<LensSearchResult, 'maker' | 'model' | 'crop'>) => {
|
||||
const applyProfile = (result: Pick<LensSearchResult, 'id' | 'maker' | 'model' | 'crop'>) => {
|
||||
const next: LensProfile = {
|
||||
id: result.id,
|
||||
maker: result.maker,
|
||||
model: result.model,
|
||||
crop: result.crop,
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import type { LensCorrection } from '../lib/lensfun';
|
||||
import type { LensCorrection } from '../lib/lensEngine';
|
||||
import type { Preview16 } from '../lib/preview16';
|
||||
import type { Edits, GeometryEdits } from '../types';
|
||||
import { buildSampler, clamp01 } from '../lib/curves';
|
||||
|
||||
Vendored
-83
@@ -1,83 +0,0 @@
|
||||
/**
|
||||
* The published package's `types` entry points at a file that is not shipped in
|
||||
* 0.1.3, so declare the small surface we use here.
|
||||
*/
|
||||
declare module '@neoanaloglabkk/lensfun-wasm' {
|
||||
export interface LensfunInitOptions {
|
||||
moduleFactory?: (options?: Record<string, unknown>) => Promise<unknown>;
|
||||
moduleJsUrl?: string;
|
||||
wasmUrl?: string;
|
||||
dataUrl?: string;
|
||||
dbPath?: string;
|
||||
autoInitDb?: boolean;
|
||||
locateFile?: (path: string, prefix: string) => string;
|
||||
}
|
||||
|
||||
export interface LensMatch {
|
||||
handle: number;
|
||||
maker: string;
|
||||
model: string;
|
||||
score: number;
|
||||
minFocal: number;
|
||||
maxFocal: number;
|
||||
minAperture: number;
|
||||
maxAperture: number;
|
||||
cropFactor: number;
|
||||
}
|
||||
|
||||
export interface CameraMatch {
|
||||
maker: string;
|
||||
model: string;
|
||||
variant: string;
|
||||
mount: string;
|
||||
cropFactor: number;
|
||||
score: number;
|
||||
}
|
||||
|
||||
export interface SearchLensesInput {
|
||||
lensMaker?: string;
|
||||
lensModel: string;
|
||||
cameraMaker?: string;
|
||||
cameraModel?: string;
|
||||
searchFlags?: number;
|
||||
}
|
||||
|
||||
export interface SearchCamerasInput {
|
||||
maker?: string;
|
||||
model?: string;
|
||||
searchFlags?: number;
|
||||
}
|
||||
|
||||
export interface CorrectionInput {
|
||||
lensHandle: number;
|
||||
width: number;
|
||||
height: number;
|
||||
focal: number;
|
||||
crop: number;
|
||||
step?: number;
|
||||
reverse?: boolean;
|
||||
includeTca?: boolean;
|
||||
includeVignetting?: boolean;
|
||||
aperture?: number;
|
||||
distance?: number;
|
||||
}
|
||||
|
||||
export interface CorrectionMaps {
|
||||
gridWidth: number;
|
||||
gridHeight: number;
|
||||
step: number;
|
||||
geometry: Float32Array;
|
||||
tca?: Float32Array;
|
||||
vignetting?: Float32Array;
|
||||
}
|
||||
|
||||
export interface LensfunClient {
|
||||
dispose(): void;
|
||||
searchLenses(input: SearchLensesInput): LensMatch[];
|
||||
searchCameras(input: SearchCamerasInput): CameraMatch[];
|
||||
getAvailableModifications(lensHandle: number, crop: number): number;
|
||||
buildCorrectionMaps(input: CorrectionInput): CorrectionMaps;
|
||||
}
|
||||
|
||||
export function createLensfun(options?: LensfunInitOptions): Promise<LensfunClient>;
|
||||
}
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import type { Edits, PhotoRecord } from '../types';
|
||||
import { get16BitSource, getBitmap } from './images';
|
||||
import { normalizeEdits } from './edits';
|
||||
import { buildLensCorrection } from './lensfun';
|
||||
import { buildLensCorrection } from './lensEngine';
|
||||
import { outputSize, Renderer } from '../gl/renderer';
|
||||
import { getDenoisedBitmap } from './images';
|
||||
import { createZipBlob, zipFileName } from './zip';
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { availableFor, findCamera, findLensForMeta, searchLens, type LensDatabase } from './lensDb';
|
||||
import { fixtureLenses } from './lensEngine.fixture';
|
||||
import type { LensProfile } from '../types';
|
||||
|
||||
/**
|
||||
* A miniature database: enough to exercise matching (brand, focal length, exact
|
||||
* model), the mount tie-break and the availability flags without downloading
|
||||
* the real 1.7 MB file.
|
||||
*/
|
||||
const database: LensDatabase = {
|
||||
source: { project: 'lensfun', commit: 'test', licence: 'CC BY-SA 3.0', note: '' },
|
||||
models: { distortion: ['poly3', 'poly5', 'ptlens', 'linear', 'acm'], tca: ['poly3', 'linear', 'acm'] },
|
||||
mounts: ['Nikon F AF', 'Canon EF', 'Canon EF-M'],
|
||||
cameras: [
|
||||
{ maker: 'Nikon Corporation', model: 'Nikon D700', mount: 'Nikon F AF', crop: 1 },
|
||||
{ maker: 'Canon', model: 'Canon EOS R5', mount: 'Canon EF', crop: 1 },
|
||||
],
|
||||
lenses: [
|
||||
...fixtureLenses,
|
||||
{
|
||||
id: 'canon-ef-50mm-f1-8',
|
||||
maker: 'Canon',
|
||||
model: 'Canon EF 50mm f/1.8 STM',
|
||||
crop: 1,
|
||||
mounts: ['Canon EF'],
|
||||
aspect: 0,
|
||||
centerX: 0,
|
||||
centerY: 0,
|
||||
d: [[50, 0, 0, -0.01, 0, 0]],
|
||||
t: [],
|
||||
v: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
beforeAll(() => {
|
||||
vi.stubGlobal('fetch', async () => new Response(JSON.stringify(database), { status: 200 }));
|
||||
});
|
||||
|
||||
describe('lens search', () => {
|
||||
it('finds a maker the way people type it', async () => {
|
||||
const results = await searchLens('tamron');
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
expect(results.every((result) => result.maker === 'Tamron')).toBe(true);
|
||||
});
|
||||
|
||||
it('finds a lens by focal length alone', async () => {
|
||||
const results = await searchLens('28-75');
|
||||
expect(results[0]?.model).toContain('28-75');
|
||||
});
|
||||
|
||||
it('matches an EXIF lens name to a profile', async () => {
|
||||
const match = await findLensForMeta({
|
||||
camera: 'NIKON CORPORATION NIKON D700',
|
||||
lens: 'Tamron SP AF 28-75mm f/2.8 XR Di LD Aspherical (IF) Macro',
|
||||
});
|
||||
expect(match?.maker).toBe('Tamron');
|
||||
});
|
||||
|
||||
it('returns nothing for a name that is not in the database', async () => {
|
||||
expect(await searchLens('zzzz nonexistent lens')).toEqual([]);
|
||||
expect(await searchLens('')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('camera lookup', () => {
|
||||
it('reads the mount and crop factor from an EXIF body name', async () => {
|
||||
const camera = await findCamera('NIKON CORPORATION NIKON D700');
|
||||
expect(camera).toMatchObject({ mount: 'Nikon F AF', cropFactor: 1 });
|
||||
});
|
||||
|
||||
it('keeps lenses filed under another mount findable', async () => {
|
||||
// The Canon EF 50mm is not a Nikon F lens, but a search must not hide it.
|
||||
const results = await searchLens('canon ef 50mm', { camera: 'NIKON CORPORATION NIKON D700' });
|
||||
expect(results.some((result) => result.model.includes('50mm'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('availability', () => {
|
||||
it('reports which corrections a profile supports', async () => {
|
||||
const [tamron] = fixtureLenses;
|
||||
const profile: LensProfile = {
|
||||
maker: tamron.maker,
|
||||
model: tamron.model,
|
||||
crop: tamron.crop,
|
||||
corrections: { distortion: true, tca: true, vignetting: true },
|
||||
};
|
||||
// Distortion, TCA and vignetting all have calibration samples.
|
||||
expect(await availableFor(profile)).toBe(11);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { autoScaleFor, computeMaps, type LensCorrection, type LensMap } from './lensEngine';
|
||||
import { fixtureLenses, referenceCases } from './lensEngine.fixture';
|
||||
|
||||
const GRID = { width: 64, height: 43 };
|
||||
|
||||
function mapsFor(model: string, focal: number, aperture: number) {
|
||||
const entry = fixtureLenses.find((lens) => lens.model === model);
|
||||
expect(entry, model).toBeTruthy();
|
||||
return computeMaps(entry!, {
|
||||
...GRID,
|
||||
focal,
|
||||
crop: entry!.crop,
|
||||
aperture,
|
||||
distance: 1000,
|
||||
distortion: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference values were captured from the Lensfun WebAssembly build this
|
||||
* engine replaced, at 25 points of a 64x43 grid. Matching them proves the ported
|
||||
* models (PanoTools and poly3 distortion, poly3 TCA, pa vignetting) agree with
|
||||
* what the editor used to render.
|
||||
*/
|
||||
describe('lens engine matches the reference implementation', () => {
|
||||
for (const testCase of referenceCases) {
|
||||
it(`corrects ${testCase.model} the same way`, () => {
|
||||
const maps = mapsFor(testCase.model, testCase.focal, testCase.aperture);
|
||||
for (const point of testCase.points) {
|
||||
const index = point.y * GRID.width + point.x;
|
||||
const where = `${testCase.key} at ${point.x},${point.y}`;
|
||||
expect(maps.geometry[index * 2], `${where} x`).toBeCloseTo(point.g[0], 3);
|
||||
expect(maps.geometry[index * 2 + 1], `${where} y`).toBeCloseTo(point.g[1], 3);
|
||||
if (point.t && maps.tca) {
|
||||
expect(maps.tca[index * 6], `${where} red x`).toBeCloseTo(point.t[0], 3);
|
||||
expect(maps.tca[index * 6 + 1], `${where} red y`).toBeCloseTo(point.t[1], 3);
|
||||
expect(maps.tca[index * 6 + 4], `${where} blue x`).toBeCloseTo(point.t[2], 3);
|
||||
expect(maps.tca[index * 6 + 5], `${where} blue y`).toBeCloseTo(point.t[3], 3);
|
||||
}
|
||||
if (point.v != null && maps.vignetting) {
|
||||
expect(maps.vignetting[index * 3], `${where} gain`).toBeCloseTo(point.v, 3);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe('lens engine basics', () => {
|
||||
it('leaves coordinates untouched when the calibration has no distortion', () => {
|
||||
const entry = { ...fixtureLenses[0], d: [] };
|
||||
const maps = computeMaps(entry, { ...GRID, focal: 50, crop: entry.crop, distortion: true });
|
||||
for (const [x, y] of [
|
||||
[0, 0],
|
||||
[31, 21],
|
||||
[63, 42],
|
||||
]) {
|
||||
const index = y * GRID.width + x;
|
||||
expect(maps.geometry[index * 2]).toBeCloseTo(x, 3);
|
||||
expect(maps.geometry[index * 2 + 1]).toBeCloseTo(y, 3);
|
||||
}
|
||||
});
|
||||
|
||||
it('only emits the maps the calibration and the toggles ask for', () => {
|
||||
const entry = fixtureLenses[0];
|
||||
const plain = computeMaps(entry, { ...GRID, focal: 50, crop: entry.crop, distortion: false });
|
||||
expect(plain.tca).toBeUndefined();
|
||||
|
||||
const cooled = computeMaps(entry, { ...GRID, focal: 28, crop: entry.crop, aperture: 2.8, distortion: true });
|
||||
expect(cooled.tca?.length).toBe(GRID.width * GRID.height * 6);
|
||||
expect(cooled.vignetting?.length).toBe(GRID.width * GRID.height * 3);
|
||||
// Flat-field gains brighten the corners of a vignetted lens.
|
||||
expect(cooled.vignetting![0]).toBeGreaterThan(cooled.vignetting![(21 * GRID.width + 31) * 3]);
|
||||
});
|
||||
|
||||
it('scales up when the correction samples outside the frame', () => {
|
||||
const geometry: LensMap = {
|
||||
width: 3,
|
||||
height: 3,
|
||||
// Every sample points slightly outside the image.
|
||||
data: new Float32Array(3 * 3 * 4),
|
||||
};
|
||||
for (let i = 0; i < 3 * 3; i++) {
|
||||
geometry.data[i * 4] = -0.1;
|
||||
geometry.data[i * 4 + 1] = -0.1;
|
||||
geometry.data[i * 4 + 3] = 1;
|
||||
}
|
||||
const correction: LensCorrection = { key: 'test', geometry, scale: 1 };
|
||||
expect(autoScaleFor(correction.geometry)).toBeGreaterThan(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,448 @@
|
||||
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<string, LensCorrection>();
|
||||
|
||||
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<T extends number[]>(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<PhotoMeta, 'focal' | 'aperture'> },
|
||||
): Promise<LensCorrection> {
|
||||
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 };
|
||||
}
|
||||
@@ -1,479 +0,0 @@
|
||||
import type {
|
||||
CameraMatch,
|
||||
CorrectionMaps,
|
||||
LensMatch,
|
||||
LensfunClient,
|
||||
} from '@neoanaloglabkk/lensfun-wasm';
|
||||
import { lensMatchScore, lensSearchVariants } from './lensNames';
|
||||
import type { LensProfile, PhotoMeta } from '../types';
|
||||
|
||||
/**
|
||||
* Lensfun is loaded on demand from public/lensfun. The database and the
|
||||
* WebAssembly wrapper are third-party assets; see public/lensfun/NOTICE.md.
|
||||
*/
|
||||
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 FLAG_TCA = 1;
|
||||
const FLAG_VIGNETTING = 2;
|
||||
const FLAG_DISTORTION = 8;
|
||||
|
||||
let clientPromise: Promise<LensfunClient> | null = null;
|
||||
let client: LensfunClient | null = null;
|
||||
const handleCache = new Map<string, LensMatch>();
|
||||
const cameraCache = new Map<string, CameraMatch | null>();
|
||||
const correctionCache = new Map<string, LensCorrection>();
|
||||
|
||||
async function loadCoreFactory(): Promise<(options?: Record<string, unknown>) => Promise<unknown>> {
|
||||
const response = await fetch('/lensfun/lensfun-core.js');
|
||||
if (!response.ok) throw new Error('Could not load the Lensfun runtime');
|
||||
let source = await response.text();
|
||||
// The 0.1.3 Emscripten build keeps the float heap view in a closure and the
|
||||
// wrapper reads it from `module.HEAPF32`, so expose it after every memory
|
||||
// resize. The asset itself is untouched on disk.
|
||||
if (!source.includes('Module["HEAPF32"]')) {
|
||||
const marker = 'HEAPF32=new Float32Array(b)';
|
||||
if (!source.includes(marker)) throw new Error('Unexpected Lensfun runtime layout');
|
||||
source = source.replace(marker, `${marker};Module["HEAPF32"]=HEAPF32;`);
|
||||
}
|
||||
const scriptUrl = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.src = scriptUrl;
|
||||
script.onload = () => {
|
||||
script.remove();
|
||||
resolve();
|
||||
};
|
||||
script.onerror = () => {
|
||||
script.remove();
|
||||
reject(new Error('Could not start the Lensfun runtime'));
|
||||
};
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
} finally {
|
||||
URL.revokeObjectURL(scriptUrl);
|
||||
}
|
||||
const factory = (globalThis as Record<string, unknown>).createLensfunCoreModule;
|
||||
if (typeof factory !== 'function') throw new Error('Lensfun runtime did not initialize');
|
||||
return factory as (options?: Record<string, unknown>) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export async function getLensfun(): Promise<LensfunClient> {
|
||||
if (client) return client;
|
||||
if (!clientPromise) {
|
||||
clientPromise = import('@neoanaloglabkk/lensfun-wasm')
|
||||
.then(async ({ createLensfun }) => {
|
||||
const moduleFactory = await loadCoreFactory();
|
||||
return createLensfun({
|
||||
moduleFactory,
|
||||
wasmUrl: '/lensfun/lensfun-core.wasm',
|
||||
dataUrl: '/lensfun/lensfun-core.data',
|
||||
});
|
||||
})
|
||||
.then((instance) => {
|
||||
client = instance;
|
||||
return instance;
|
||||
})
|
||||
.catch((err) => {
|
||||
clientPromise = null;
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
return clientPromise;
|
||||
}
|
||||
|
||||
export function profileKey(profile: LensProfile) {
|
||||
return `${profile.maker}\u0000${profile.model}`;
|
||||
}
|
||||
|
||||
export interface LensSearchResult {
|
||||
maker: string;
|
||||
model: string;
|
||||
crop: number;
|
||||
score: number;
|
||||
available: number;
|
||||
}
|
||||
|
||||
function toResult(match: LensMatch, available = 0): LensSearchResult {
|
||||
return {
|
||||
maker: match.maker,
|
||||
model: match.model,
|
||||
crop: match.cropFactor,
|
||||
score: match.score,
|
||||
available,
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchLens(
|
||||
query: string,
|
||||
meta?: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||
): Promise<LensSearchResult[]> {
|
||||
const variants = lensSearchVariants(query);
|
||||
if (!variants.length) return [];
|
||||
const lf = await getLensfun();
|
||||
const camera = cameraParts(meta?.camera);
|
||||
const cameraFields = {
|
||||
...(camera.maker ? { cameraMaker: camera.maker } : {}),
|
||||
...(camera.model ? { cameraModel: camera.model } : {}),
|
||||
};
|
||||
const byName = new Map<string, LensMatch>();
|
||||
for (const variant of variants) {
|
||||
let matches: LensMatch[] = [];
|
||||
try {
|
||||
matches = lf.searchLenses({ lensModel: variant, ...cameraFields });
|
||||
} catch {
|
||||
matches = [];
|
||||
}
|
||||
if (!matches.length) {
|
||||
try {
|
||||
matches = lf.searchLenses({ lensModel: variant });
|
||||
} catch {
|
||||
matches = [];
|
||||
}
|
||||
}
|
||||
for (const match of matches) {
|
||||
const key = `${match.maker}\u0000${match.model}`;
|
||||
if (!byName.has(key)) byName.set(key, match);
|
||||
}
|
||||
}
|
||||
const crop = (await findCamera(meta?.camera))?.cropFactor || 1;
|
||||
return [...byName.values()].slice(0, 20).map((match) => {
|
||||
handleCache.set(`${match.maker}\u0000${match.model}`, match);
|
||||
return toResult(match, lf.getAvailableModifications(match.handle, crop));
|
||||
});
|
||||
}
|
||||
|
||||
export async function findLensForMeta(
|
||||
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||
): Promise<LensSearchResult | null> {
|
||||
if (!meta.lens) return null;
|
||||
const results = await searchLens(meta.lens, meta);
|
||||
if (!results.length) return null;
|
||||
let best = results[0];
|
||||
let score = lensMatchScore(meta.lens, best.model);
|
||||
for (const candidate of results.slice(1)) {
|
||||
const next = lensMatchScore(meta.lens, candidate.model);
|
||||
if (next > score) {
|
||||
best = candidate;
|
||||
score = next;
|
||||
}
|
||||
}
|
||||
return score > 0 ? best : null;
|
||||
}
|
||||
|
||||
export async function resolveLens(profile: LensProfile): Promise<LensMatch | null> {
|
||||
const key = profileKey(profile);
|
||||
const cached = handleCache.get(key);
|
||||
if (cached) return cached;
|
||||
const lf = await getLensfun();
|
||||
const cam = cameraParts(profile.cameraModel);
|
||||
const cameraFields = {
|
||||
...(profile.cameraMaker || cam.maker ? { cameraMaker: profile.cameraMaker ?? cam.maker } : {}),
|
||||
...(profile.cameraModel || cam.model ? { cameraModel: cam.model ?? profile.cameraModel } : {}),
|
||||
};
|
||||
const tokens = profile.model.split(/\s+/).filter(Boolean);
|
||||
const focal = tokens.find((token) => /^\d+(?:\.\d+)?mm$/i.test(token));
|
||||
const aperture = tokens.find((token) => /^f\/\d+(?:\.\d+)?[a-z]*$/i.test(token));
|
||||
const shortened = tokens
|
||||
.filter((token) => !/^(af|af-s|af-i|ai|ai-s|ais|d|g|ed|vr|if|asp|ld|dx|fx)$/i.test(token))
|
||||
.join(' ');
|
||||
const queries: { lensMaker?: string; lensModel: string; cameraMaker?: string; cameraModel?: string }[] = [
|
||||
{ ...cameraFields, lensMaker: profile.maker, lensModel: profile.model },
|
||||
{ ...cameraFields, lensModel: profile.model },
|
||||
{ ...cameraFields, lensModel: shortened },
|
||||
...(focal
|
||||
? [{ ...cameraFields, lensModel: [tokens[0], focal, aperture].filter(Boolean).join(' ') }]
|
||||
: []),
|
||||
];
|
||||
const attempts: LensMatch[] = [];
|
||||
for (const query of queries) {
|
||||
try {
|
||||
const found = lf.searchLenses(query);
|
||||
if (found.length) {
|
||||
attempts.push(...found);
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
/* try the next, looser query */
|
||||
}
|
||||
}
|
||||
const exact =
|
||||
attempts.find(
|
||||
(match) =>
|
||||
match.maker.toLowerCase() === profile.maker.toLowerCase() &&
|
||||
match.model.toLowerCase() === profile.model.toLowerCase(),
|
||||
) ?? attempts[0];
|
||||
if (exact) handleCache.set(key, exact);
|
||||
return exact ?? null;
|
||||
}
|
||||
|
||||
export async function availableFor(profile: LensProfile): Promise<number> {
|
||||
const match = await resolveLens(profile);
|
||||
if (!match) return 0;
|
||||
const lf = await getLensfun();
|
||||
return lf.getAvailableModifications(match.handle, profile.crop);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- camera search */
|
||||
|
||||
function cameraParts(camera?: string): { maker?: string; model?: string } {
|
||||
if (!camera) return {};
|
||||
const cleaned = camera.replace(/\s+/g, ' ').trim();
|
||||
const lower = cleaned.toLowerCase();
|
||||
const makerNames = [
|
||||
'Nikon Corporation',
|
||||
'Canon',
|
||||
'Sony',
|
||||
'FUJIFILM',
|
||||
'Olympus',
|
||||
'Panasonic',
|
||||
'PENTAX',
|
||||
'Sigma',
|
||||
'Tamron',
|
||||
'Leica',
|
||||
'Hasselblad',
|
||||
'Samsung',
|
||||
'Ricoh',
|
||||
];
|
||||
const maker = makerNames.find((name) => lower.startsWith(name.toLowerCase()));
|
||||
if (maker) {
|
||||
return { maker, model: cleaned.slice(maker.length).trim() || cleaned };
|
||||
}
|
||||
const [first, ...rest] = cleaned.split(' ');
|
||||
return rest.length ? { maker: first, model: rest.join(' ') } : { model: cleaned };
|
||||
}
|
||||
|
||||
export async function findCamera(camera?: string): Promise<CameraMatch | null> {
|
||||
if (!camera) return null;
|
||||
const cached = cameraCache.get(camera);
|
||||
if (cached !== undefined) return cached;
|
||||
const lf = await getLensfun();
|
||||
const parts = cameraParts(camera);
|
||||
let found: CameraMatch[] = [];
|
||||
try {
|
||||
found = lf.searchCameras({ ...parts, searchFlags: 1 });
|
||||
} catch {
|
||||
found = [];
|
||||
}
|
||||
if (!found.length) {
|
||||
try {
|
||||
found = lf.searchCameras({ model: camera, searchFlags: 1 });
|
||||
} catch {
|
||||
found = [];
|
||||
}
|
||||
}
|
||||
const best = found[0] ?? null;
|
||||
cameraCache.set(camera, best);
|
||||
return best;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- correction maps */
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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 async function buildLensCorrection(
|
||||
profile: LensProfile,
|
||||
photo: { width: number; height: number; meta: Pick<PhotoMeta, 'focal' | 'aperture'> },
|
||||
): Promise<LensCorrection> {
|
||||
const key = `${profileKey(profile)}|${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 match = await resolveLens(profile);
|
||||
if (!match) throw new Error('Lens profile not found in the Lensfun database');
|
||||
const focal = Number(photo.meta.focal) || 0;
|
||||
if (!focal) throw new Error('This photo has no focal length in its EXIF data');
|
||||
const lf = await getLensfun();
|
||||
const available = lf.getAvailableModifications(match.handle, profile.crop);
|
||||
const useDistortion =
|
||||
profile.corrections.distortion && (available & FLAG_DISTORTION) !== 0;
|
||||
const useTca = profile.corrections.tca && (available & FLAG_TCA) !== 0;
|
||||
const useVignetting =
|
||||
profile.corrections.vignetting &&
|
||||
(available & FLAG_VIGNETTING) !== 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: CorrectionMaps = lf.buildCorrectionMaps({
|
||||
lensHandle: match.handle,
|
||||
width: mapW,
|
||||
height: mapH,
|
||||
focal,
|
||||
crop: profile.crop,
|
||||
step: 1,
|
||||
includeTca: useTca,
|
||||
includeVignetting: useVignetting,
|
||||
aperture: Number(photo.meta.aperture) || 1,
|
||||
distance: profile.distance ?? 1000,
|
||||
});
|
||||
|
||||
// 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 };
|
||||
}
|
||||
+3
-1
@@ -115,7 +115,9 @@ export interface LensCorrections {
|
||||
}
|
||||
|
||||
export interface LensProfile {
|
||||
/** Lensfun maker/model and the sensor crop used for calibration. */
|
||||
/** Profile id in the bundled lens database, when it came from a search. */
|
||||
id?: string;
|
||||
/** Maker/model and the sensor crop used for calibration. */
|
||||
maker: string;
|
||||
model: string;
|
||||
crop: number;
|
||||
|
||||
Reference in New Issue
Block a user