Show camera profiles in every view and remember proof and DCP settings.

A profile chosen for a raw only changed Develop and exports, so the grid,
Compare and preset previews could disagree with the file. They now grade
camera-native samples, while the proof profile persists with a rendering
intent and DCP matrices can be reused per camera body.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
2026-11-28 04:04:44 +00:00
parent 0c113e7a91
commit 637629385a
16 changed files with 720 additions and 39 deletions
+22 -3
View File
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from 'react';
import { getBitmap } from '../lib/images';
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 type { PhotoRecord } from '../types';
@@ -15,6 +16,7 @@ function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: strin
const boxRef = useRef<HTMLDivElement>(null);
const rendererRef = useRef<Renderer | null>(null);
const [bitmap, setBitmap] = useState<ImageBitmap | null>(null);
const [hdr, setHdr] = useState<Preview16 | null>(null);
const [box, setBox] = useState({ w: 0, h: 0 });
const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -29,6 +31,23 @@ function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: strin
};
}, [photo]);
// Compare renders the full proxy, so the matching 16-bit sidecar is what lets
// a per-photo camera profile show here exactly as it does in Develop. Without
// a profile the JPEG already carries the body matrix, so skip the big fetch.
useEffect(() => {
let alive = true;
if (!photo.edits.cameraProfile) {
setHdr(null);
return;
}
get16BitSource(photo)
.then((next) => alive && setHdr(next))
.catch(() => alive && setHdr(null));
return () => {
alive = false;
};
}, [photo]);
useEffect(() => {
let alive = true;
if (!photo.edits.lens || !bitmap) {
@@ -98,14 +117,14 @@ function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: strin
lens: lensCorrection,
};
try {
renderer.setImage(bitmap);
renderer.setImage(bitmap, hdr);
renderer.render(photo.edits, opts);
} catch (err) {
setError(err instanceof Error ? err.message : 'Rendering failed');
}
});
return () => cancelAnimationFrame(raf);
}, [bitmap, box, photo, lensCorrection]);
}, [bitmap, box, photo, lensCorrection, hdr]);
return (
<figure className="compare-tile" onDoubleClick={() => onOpen(photo.id)}>
+20
View File
@@ -8,6 +8,7 @@ import {
} from '../lib/edits';
import { subscribeClipPreview } from '../lib/clipPreview';
import { get16BitSource, getBitmap, getDenoisedBitmap } from '../lib/images';
import { rebuildProofCube, restoreProofProfile } from '../lib/softProof';
import type { Preview16 } from '../lib/preview16';
import { useMediaQuery } from '../lib/useMediaQuery';
import { usePersistentState } from '../lib/usePersistentState';
@@ -627,6 +628,25 @@ export default function Develop({
return () => cancelAnimationFrame(raf);
}, [bitmap, drawPreview]);
// The printer profile lives outside the edit record, so restoring it and
// following an intent change are handled here rather than by the proof panel.
useEffect(() => {
let alive = true;
void restoreProofProfile(edits.proof.intent).then((cube) => {
if (alive && cube) setProofProfile(cube.name);
});
return () => {
alive = false;
};
// Restore once; intent changes are picked up by the effect below.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
const cube = rebuildProofCube(edits.proof.intent);
if (cube) setProofProfile(cube.name);
}, [edits.proof.intent]);
/* ------------------------------------------------------------ zoom & pan */
const applyZoom = useCallback((rawPct: number | 'fit', point?: { x: number; y: number }) => {
+77 -3
View File
@@ -21,8 +21,21 @@ import { getBitmap } from '../lib/images';
import { grainSampleWindow, rotatedBounds, Renderer } from '../gl/renderer';
import { applyFilmVariant, FILM_VARIANTS, PRESET_CATEGORIES, type FilmVariant } from '../lib/presets';
import { usePersistentState } from '../lib/usePersistentState';
import { loadProofProfile, setActiveProofCube, type SoftProofCube } from '../lib/softProof';
import {
clearPersistedProofProfile,
loadProofProfile,
persistProofProfile,
setActiveProofCube,
type SoftProofCube,
} from '../lib/softProof';
import { dcpRgbCam, parseDcp } from '../lib/dcp';
import {
loadSavedCameraProfiles,
removeCameraProfile,
saveCameraProfile,
savedProfilesForCamera,
type SavedCameraProfile,
} from '../lib/dcpLibrary';
import { usePresetThumbs } from './PresetThumbs';
import { availableFor, findLensForMeta, searchLens, type LensSearchResult } from '../lib/lensfun';
import {
@@ -2178,6 +2191,12 @@ export function CameraProfilePanel({
}: PanelSetProps & { cameraNative?: boolean }) {
const [error, setError] = useState<string | null>(null);
const profile = edits.cameraProfile;
const camera = photo.meta?.camera ?? '';
// Saved per camera body: the matrix describes the sensor, so every frame from
// the same body can reuse it without opening the .dcp file again.
const [saved, setSaved] = useState<SavedCameraProfile[]>(() => loadSavedCameraProfiles());
const matching = useMemo(() => savedProfilesForCamera(saved, camera), [saved, camera]);
const applied = matching.find((entry) => entry.name === profile?.name);
const load = async (file: File) => {
if (!cameraNative) return;
@@ -2188,6 +2207,7 @@ export function CameraProfilePanel({
if (!matrix) throw new Error('This profile has no usable colour matrix');
setError(null);
set({ cameraProfile: { name: parsed.name, matrix } }, 'Camera profile');
setSaved(saveCameraProfile({ name: parsed.name, camera: camera || parsed.camera, matrix }));
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not read that profile');
}
@@ -2219,7 +2239,7 @@ export function CameraProfilePanel({
className="btn ghost small"
onClick={() => {
setError(null);
set({ cameraProfile: null }, 'Body camera profile');
set({ cameraProfile: null }, 'Body camera matrix');
}}
>
Use body matrix
@@ -2227,6 +2247,38 @@ export function CameraProfilePanel({
)}
</div>
)}
{matching.length > 0 && (
<label className="field">
<span>Saved for this camera</span>
<select
value=""
onChange={(e) => {
const entry = matching.find((item) => item.id === e.target.value);
if (!entry) return;
setError(null);
set({ cameraProfile: { name: entry.name, matrix: entry.matrix } }, 'Camera profile');
}}
>
<option value="">Choose a saved profile…</option>
{matching.map((entry) => (
<option key={entry.id} value={entry.id}>
{entry.name}
</option>
))}
</select>
</label>
)}
{applied && (
<button
className="btn ghost small"
onClick={() => {
setSaved(removeCameraProfile(applied.id));
setError(null);
}}
>
Forget saved {applied.name}
</button>
)}
<p className="muted small panel-hint">
{!cameraNative
? 'This proxy was decoded straight to sRGB, so there are no camera samples to profile. Reprocess the RAW to enable camera profiles.'
@@ -2254,7 +2306,10 @@ export function ProofPanel({
const loadProfile = async (file: File) => {
try {
const cube = loadProofProfile(new Uint8Array(await file.arrayBuffer()));
const bytes = new Uint8Array(await file.arrayBuffer());
const cube = loadProofProfile(bytes, 33, proof.intent);
// Persisting is best-effort: the cube is live even when IndexedDB is not.
void persistProofProfile();
setProfileError(null);
onProofProfile?.(cube);
} catch (err) {
@@ -2293,6 +2348,24 @@ export function ProofPanel({
<option value="newsprint">Newsprint</option>
</select>
</label>
<label className="field">
<span>Rendering intent</span>
<select
value={proof.intent}
onChange={(e) =>
set(
{ proof: { ...proof, intent: e.target.value as typeof proof.intent } },
'Rendering intent',
)
}
disabled={!proof.enabled}
title="Which printer table pair the proof uses. Relative colorimetric is what most print shops expect; saturation is often absent from paper profiles and falls back to perceptual."
>
<option value="perceptual">Perceptual</option>
<option value="relative">Relative colorimetric</option>
<option value="saturation">Saturation</option>
</select>
</label>
<Slider
label="Paper black"
min={0}
@@ -2324,6 +2397,7 @@ export function ProofPanel({
className="btn ghost small"
onClick={() => {
setActiveProofCube(null);
void clearPersistedProofProfile();
setProfileError(null);
onProofProfile?.(null);
}}
+13 -7
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
import { normalizeEdits } from '../lib/edits';
import { getBitmap } from '../lib/images';
import { get16BitSource, getBitmap } from '../lib/images';
import { Renderer, rotatedBounds } from '../gl/renderer';
import type { PhotoRecord, Preset } from '../types';
@@ -14,7 +14,8 @@ const CACHE_LIMIT = 900;
const THUMB_EDGE = 200;
/** The crop is part of the key so a turn, straighten or flip refreshes the tiles. */
const keyOf = (photoId: string, presetId: string, crop: string) => `${photoId}|${presetId}|${crop}`;
const keyOf = (photoId: string, presetId: string, crop: string, source: string) =>
`${photoId}|${presetId}|${crop}|${source}`;
export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> {
const [thumbs, setThumbs] = useState<Record<string, string>>({});
@@ -23,6 +24,10 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
const presetKey = presets.map((p) => p.id).join('|');
const crop = photo.edits.crop;
const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(',');
// The preset previews keep the photo's camera profile, so a reprocess or a
// different profile has to invalidate tiles the same way a crop does.
const profile = photo.edits.cameraProfile;
const sourceKey = `${photo.previewVersion ?? 0}|${profile ? profile.matrix.join(',') : ''}`;
useEffect(() => {
let alive = true;
@@ -31,7 +36,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
const known: Record<string, string> = {};
for (const preset of presets) {
const hit = cache.get(keyOf(photo.id, preset.id, cropKey));
const hit = cache.get(keyOf(photo.id, preset.id, cropKey, sourceKey));
if (hit) known[preset.id] = hit;
}
setThumbs(known);
@@ -43,6 +48,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
try {
const bitmap = await getBitmap(photo);
if (!alive) return;
const hdr = profile ? await get16BitSource(photo).catch(() => null) : null;
renderer = new Renderer(canvas);
// Every tile shows the photo as it is framed now, so a turned photo's
// presets are turned too.
@@ -52,18 +58,18 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
const scale = THUMB_EDGE / Math.max(cropW, cropH);
const width = Math.max(1, Math.round(cropW * scale));
const height = Math.max(1, Math.round(cropH * scale));
renderer.setImage(bitmap);
renderer.setImage(bitmap, hdr);
for (const preset of pending) {
if (!alive) break;
try {
renderer.render({ ...normalizeEdits(preset.edits), crop }, {
renderer.render({ ...normalizeEdits(preset.edits), crop, cameraProfile: profile }, {
width,
height,
upscale: Math.max(width / cropW, height / cropH) > 1.05,
});
const url = canvas.toDataURL('image/jpeg', 0.72);
cache.set(keyOf(photo.id, preset.id, cropKey), url);
cache.set(keyOf(photo.id, preset.id, cropKey, sourceKey), url);
setThumbs((prev) => ({ ...prev, [preset.id]: url }));
} catch {
// One bad preset must not stop the rest of the grid.
@@ -85,7 +91,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
renderer?.dispose();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [photo.id, presetKey, cropKey]);
}, [photo.id, presetKey, cropKey, sourceKey]);
return thumbs;
}
+58
View File
@@ -0,0 +1,58 @@
import { describe, expect, it } from 'vitest';
import {
loadSavedCameraProfiles,
removeCameraProfile,
saveCameraProfile,
savedProfilesForCamera,
type ProfileStore,
} from './dcpLibrary';
function memoryStore(): ProfileStore {
const data = new Map<string, string>();
return {
getItem: (key) => data.get(key) ?? null,
setItem: (key, value) => {
data.set(key, value);
},
};
}
const matrix = [0.4, 0.3, 0.3, 0.2, 0.7, 0.1, 0.01, 0.09, 0.9];
describe('camera profile library', () => {
it('keeps a profile and finds it by camera body', () => {
const store = memoryStore();
saveCameraProfile({ name: 'Studio DCP', camera: 'Nikon D700', matrix }, store);
const saved = loadSavedCameraProfiles(store);
expect(saved).toHaveLength(1);
expect(saved[0].matrix).toEqual(matrix);
expect(savedProfilesForCamera(saved, 'NIKON CORPORATION D700')).toHaveLength(1);
expect(savedProfilesForCamera(saved, 'Canon EOS 5D')).toHaveLength(0);
});
it('replaces the same name for the same body instead of duplicating it', () => {
const store = memoryStore();
saveCameraProfile({ name: 'Studio', camera: 'Nikon D700', matrix }, store);
const next = saveCameraProfile(
{ name: 'Studio', camera: 'nikon d700', matrix: matrix.map((value) => value * 0.9) },
store,
);
expect(next).toHaveLength(1);
expect(next[0].matrix[0]).toBeCloseTo(0.36, 6);
});
it('forgets a profile and tolerates corrupt storage', () => {
const store = memoryStore();
const saved = saveCameraProfile({ name: 'Studio', camera: 'Nikon D700', matrix }, store);
expect(removeCameraProfile(saved[0].id, store)).toHaveLength(0);
store.setItem('lumenroom.cameraProfiles', JSON.stringify([{ id: 'x', name: 'bad', matrix: [1] }]));
expect(loadSavedCameraProfiles(store)).toHaveLength(0);
});
it('refuses a matrix that is not nine finite numbers', () => {
const store = memoryStore();
const saved = saveCameraProfile({ name: 'Bad', camera: 'Nikon D700', matrix: [1, 2, 3] }, store);
expect(saved).toHaveLength(0);
});
});
+127
View File
@@ -0,0 +1,127 @@
/**
* Per-camera DCP profile library.
*
* A DCP's colour matrix describes the sensor, not the frame, so every raw from
* the same body can use the same derived matrix. The library keeps those
* matrices in localStorage (name, camera and nine numbers — never the file) so
* switching photos does not mean opening a file dialog again. Each edit still
* stores its own copy of the matrix, so a photo stays self-contained and the
* library is only a shortcut for filling it in.
*/
import { cameraKey } from './lensNames';
export interface SavedCameraProfile {
id: string;
name: string;
camera: string;
matrix: number[];
savedAt: number;
}
const STORAGE_KEY = 'lumenroom.cameraProfiles';
/** Enough for a shelf of bodies without letting a stray write grow unbounded. */
const LIMIT = 32;
/** The slice of Storage the library needs; injectable so it is testable. */
export type ProfileStore = Pick<Storage, 'getItem' | 'setItem'>;
function defaultStore(): ProfileStore | null {
try {
return globalThis.localStorage ?? null;
} catch {
return null;
}
}
function validMatrix(value: unknown): value is number[] {
return (
Array.isArray(value) &&
value.length === 9 &&
value.every((entry) => typeof entry === 'number' && Number.isFinite(entry))
);
}
/** Reads the library, dropping anything that no longer looks like a matrix. */
export function loadSavedCameraProfiles(store: ProfileStore | null = defaultStore()): SavedCameraProfile[] {
if (!store) return [];
try {
const raw = store.getItem(STORAGE_KEY);
if (!raw) return [];
const parsed: unknown = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
return parsed.flatMap((entry) => {
if (!entry || typeof entry !== 'object') return [];
const { id, name, camera, matrix, savedAt } = entry as Record<string, unknown>;
if (typeof id !== 'string' || typeof name !== 'string' || typeof camera !== 'string') return [];
if (!validMatrix(matrix)) return [];
return [
{
id,
name,
camera,
matrix: [...matrix],
savedAt: typeof savedAt === 'number' && Number.isFinite(savedAt) ? savedAt : 0,
},
];
});
} catch {
return [];
}
}
function persist(entries: SavedCameraProfile[], store: ProfileStore | null) {
if (!store) return;
try {
store.setItem(STORAGE_KEY, JSON.stringify(entries));
} catch {
/* Quota or private mode: the edit still has the matrix it was given. */
}
}
/**
* Adds or replaces a profile for the same camera and name. Returns the library
* as saved so a panel can update without re-reading storage.
*/
export function saveCameraProfile(
entry: { name: string; camera: string; matrix: number[] },
store: ProfileStore | null = defaultStore(),
): SavedCameraProfile[] {
const saved = loadSavedCameraProfiles(store);
if (!entry.name.trim() || !validMatrix(entry.matrix)) return saved;
const camera = entry.camera.trim() || 'Unknown camera';
const id = `${cameraKey(camera) || 'camera'}|${entry.name.trim()}`.toLowerCase();
const next: SavedCameraProfile[] = [
{
id,
name: entry.name.trim(),
camera,
matrix: [...entry.matrix],
savedAt: Date.now(),
},
...saved.filter((profile) => profile.id !== id),
].slice(0, LIMIT);
persist(next, store);
return next;
}
export function removeCameraProfile(
id: string,
store: ProfileStore | null = defaultStore(),
): SavedCameraProfile[] {
const next = loadSavedCameraProfiles(store).filter((profile) => profile.id !== id);
persist(next, store);
return next;
}
/** Profiles that belong to this body, most recently saved first. */
export function savedProfilesForCamera(
profiles: SavedCameraProfile[],
camera?: string,
): SavedCameraProfile[] {
const key = cameraKey(camera);
if (!key) return [];
return profiles
.filter((profile) => cameraKey(profile.camera) === key)
.sort((left, right) => right.savedAt - left.savedAt || left.name.localeCompare(right.name));
}
+5 -1
View File
@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';
import type { Edits, PhotoRecord } from '../types';
import { isEdited } from './edits';
import { Renderer, rotatedBounds } from '../gl/renderer';
import { getCameraThumb } from './images';
/**
* Thumbnails of edited photos.
@@ -77,6 +78,9 @@ async function renderThumb(photo: PhotoRecord): Promise<string | null> {
const bitmap = await loadThumb(photo);
if (!bitmap) return null;
try {
// Only a profile override can differ from the JPEG: without one the thumb
// already has the body matrix baked in and the extra fetch is wasted.
const cameraThumb = photo.edits.cameraProfile ? await getCameraThumb(photo) : null;
const crop = photo.edits.crop;
const frame = rotatedBounds(bitmap.width, bitmap.height, crop.angle, crop.quarter);
const cropW = Math.max(1, frame.w * crop.w);
@@ -84,7 +88,7 @@ async function renderThumb(photo: PhotoRecord): Promise<string | null> {
const scale = Math.min(2, RENDER_EDGE / Math.max(cropW, cropH));
const width = Math.max(16, Math.round(cropW * scale));
const height = Math.max(16, Math.round(cropH * scale));
r.setImage(bitmap);
r.setImage(bitmap, cameraThumb);
// `lens: null` clears the previous photo's calibration maps: this renderer
// is shared, and a stale map would warp the next thumbnail.
r.render(photo.edits, { width, height, lens: null, upscale: scale > 1.02 });
+5 -1
View File
@@ -199,7 +199,7 @@ export function defaultEdits(): Edits {
balance: 0,
},
sharpen: { amount: 0, radius: 1, detail: 25, mask: 0, lensSoftness: 0 },
proof: { enabled: false, paper: 'matte', blackPoint: 2, gamut: false },
proof: { enabled: false, paper: 'matte', blackPoint: 2, gamut: false, intent: 'perceptual' },
cameraProfile: null,
noise: { luminance: 0, detail: 50, chroma: 0, chromaDetail: 50 },
aiDenoise: { amount: 100, key: null, model: 'guided' },
@@ -480,6 +480,10 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
paper: input.proof?.paper === 'gloss' || input.proof?.paper === 'newsprint' ? input.proof.paper : 'matte',
blackPoint: num(input.proof?.blackPoint, 2, 0, 20),
gamut: !!input.proof?.gamut,
intent:
input.proof?.intent === 'relative' || input.proof?.intent === 'saturation'
? input.proof.intent
: 'perceptual',
},
noise: {
luminance: num(noise.luminance, 0, 0, 100),
+38
View File
@@ -141,7 +141,45 @@ export async function get16BitSource(photo: PhotoRecord): Promise<Preview16 | nu
return parsed;
}
const cameraThumbCache = new Map<string, Preview16 | null>();
/**
* Camera-native grid thumbnail for a raw, or null when the server has none.
*
* The grid otherwise renders the sRGB JPEG, whose body matrix is already baked
* in, so a loaded DCP profile would only show in Develop. This is the sidecar
* resized to the JPEG thumbnail's dimensions, small enough to fetch per tile;
* null (a normal state for older imports) falls back to the JPEG.
*/
export async function getCameraThumb(photo: PhotoRecord): Promise<Preview16 | null> {
if (!photo.raw) return null;
const key = `${photo.id}|${photo.previewVersion ?? 0}`;
const hit = cameraThumbCache.get(key);
if (hit !== undefined) return hit;
try {
const res = await fetch(`/api/photos/${encodeURIComponent(photo.id)}/thumb16`, {
credentials: 'same-origin',
});
if (!res.ok) {
cameraThumbCache.set(key, null);
return null;
}
const parsed = await parsePreview16(await res.arrayBuffer());
cameraThumbCache.set(key, parsed);
while (cameraThumbCache.size > 12) {
const first = cameraThumbCache.keys().next();
if (first.done) break;
cameraThumbCache.delete(first.value);
}
return parsed;
} catch {
// A dropped connection is retried on the next tile, not cached as missing.
return null;
}
}
export function clearBitmapCache() {
cameraThumbCache.clear();
for (const bmp of cache.values()) bmp.close();
cache.clear();
for (const bmp of denoisedCache.values()) bmp.close();
+35
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
buildProofCube,
GAMUT_DELTA,
getActiveProofCube,
loadProofProfile,
parseIcc,
@@ -136,17 +137,21 @@ function buildIcc({
pcs = 'Lab ',
a2b,
b2a,
extra = [],
}: {
name: string;
colourSpace?: string;
pcs?: string;
a2b: Uint8Array;
b2a: Uint8Array;
/** Additional intent tables, e.g. A2B1/B2A1 for relative colorimetric. */
extra?: { signature: string; bytes: Uint8Array }[];
}): Uint8Array {
const tags: { signature: string; bytes: Uint8Array }[] = [
{ signature: 'desc', bytes: descTag(name) },
{ signature: 'A2B0', bytes: a2b },
{ signature: 'B2A0', bytes: b2a },
...extra,
];
let cursor = 128 + 4 + tags.length * 12;
const placed = tags.map((tag) => {
@@ -308,6 +313,36 @@ describe('buildProofCube', () => {
expect(mid[0]).toBeLessThan(1);
});
it('builds the round trip from the requested rendering intent', () => {
const identityTable = () => mft2({ map: identity });
// Relative colorimetric darkens what the printer returns, so its cube must
// differ from the perceptual one built from the primary tables.
const profile = parseIcc(
buildIcc({
name: 'Two intents',
a2b: identityTable(),
b2a: identityTable(),
extra: [
{ signature: 'A2B1', bytes: mft2({ map: ([lightness, a, b]) => [lightness * 0.6, a, b] }) },
{ signature: 'B2A1', bytes: identityTable() },
],
}),
)!;
expect(profile.a2bIntents[1]).not.toBeNull();
const perceptual = cubeAt(buildProofCube(profile, 9), 4, 4, 4)[0];
const relative = cubeAt(buildProofCube(profile, 9, GAMUT_DELTA, 'relative'), 4, 4, 4)[0];
expect(perceptual).toBeCloseTo(0.5, 2);
expect(relative).toBeLessThan(perceptual - 0.05);
});
it('falls back to the perceptual pair when an intent has no tables', () => {
const profile = parseIcc(
buildIcc({ name: 'One intent', a2b: mft2({ map: identity }), b2a: mft2({ map: identity }) }),
)!;
const saturation = buildProofCube(profile, 5, GAMUT_DELTA, 'saturation');
expect(cubeAt(saturation, 2, 2, 2)[0]).toBeCloseTo(0.5, 2);
});
it('refuses a profile without a round trip', () => {
const bytes = buildIcc({
name: 'Half',
+162 -10
View File
@@ -17,6 +17,8 @@
* table layouts are read, because printer profiles ship in both.
*/
import type { ProofIntent } from '../types';
const D50_WHITE = [0.9642, 1, 0.8249] as const;
/** Linear sRGB (D50 adapted) to XYZ, matching the primaries in `icc.ts`. */
@@ -67,6 +69,10 @@ export interface IccProfile {
pcs: Pcs;
a2b: IccTransform | null;
b2a: IccTransform | null;
/** Device→PCS tables by intent: perceptual, relative colorimetric, saturation. */
a2bIntents: (IccTransform | null)[];
/** PCS→device tables by intent, in the same order. */
b2aIntents: (IccTransform | null)[];
}
export interface SoftProofCube {
@@ -482,15 +488,20 @@ export function parseIcc(bytes: Uint8Array): IccProfile | null {
};
const description = tags.get('desc');
const a2bIntents = [transform('A2B0', true), transform('A2B1', true), transform('A2B2', true)];
const b2aIntents = [transform('B2A0', false), transform('B2A1', false), transform('B2A2', false)];
return {
name: (description && parseDescription(view, description.at, description.size)) || 'ICC profile',
profileClass: ascii(12),
colourSpace,
pcs,
// Perceptual first, then relative colorimetric: a printer profile often
// ships one and not the other.
a2b: transform('A2B0', true) ?? transform('A2B1', true),
b2a: transform('B2A0', false) ?? transform('B2A1', false),
// ships one and not the other. The full table set is kept as well, so the
// proof can be rebuilt for a different rendering intent.
a2b: a2bIntents[0] ?? a2bIntents[1],
b2a: b2aIntents[0] ?? b2aIntents[1],
a2bIntents,
b2aIntents,
};
}
@@ -512,12 +523,40 @@ export const GAMUT_DELTA = 2.5;
* the tables the round trip needs, because silently showing the paper
* approximation instead would misrepresent what was loaded.
*/
const INTENT_SLOT: Record<ProofIntent, number> = {
perceptual: 0,
relative: 1,
saturation: 2,
};
/**
* The table pair for an intent. Perceptual uses the primary pair, which is what
* a profile that only ships one set provides and what hand-built profiles in
* tests carry. Other intents need both of their own tables; falling back to the
* perceptual pair keeps a profile that omits saturation usable (many output
* profiles do) instead of refusing to proof at all.
*/
function tablesForIntent(
profile: IccProfile,
intent: ProofIntent,
): { a2b: IccTransform; b2a: IccTransform } | null {
if (INTENT_SLOT[intent] === 0) {
return profile.a2b && profile.b2a ? { a2b: profile.a2b, b2a: profile.b2a } : null;
}
const slot = INTENT_SLOT[intent];
const a2b = profile.a2bIntents?.[slot] ?? profile.a2b;
const b2a = profile.b2aIntents?.[slot] ?? profile.b2a;
return a2b && b2a ? { a2b, b2a } : null;
}
export function buildProofCube(
profile: IccProfile,
size = 33,
gamutDelta = GAMUT_DELTA,
intent: ProofIntent = 'perceptual',
): SoftProofCube {
if (!profile.a2b || !profile.b2a) {
const tables = tablesForIntent(profile, intent);
if (!tables) {
throw new Error('This profile has no A2B/B2A tables, so it cannot be soft proofed');
}
const edge = Math.max(2, Math.min(65, Math.round(size)));
@@ -536,8 +575,8 @@ export function buildProofCube(
const lab = xyzToLab(xyz);
const pcs = encodePcs(profile.pcs, lab, xyz);
// Into the printer, then back out: what the paper can actually show.
const device = evaluate(profile.b2a, pcs);
const printed = evaluate(profile.a2b, device);
const device = evaluate(tables.b2a, pcs);
const printed = evaluate(tables.a2b, device);
const back = decodePcs(profile.pcs, printed);
const rgb = multiply3(XYZ_TO_RGB, back.xyz);
data[at++] = clamp01(linearToSrgb(rgb[0]));
@@ -567,20 +606,133 @@ export function buildProofCube(
* a megabyte and does not belong in a photo record.
*/
let active: SoftProofCube | null = null;
/**
* The bytes behind the active cube. Kept so changing the rendering intent can
* rebuild the table without asking for the file again, and so the profile can
* be restored in the next session.
*/
let activeBytes: Uint8Array | null = null;
/** Clears the active profile; the bytes go too, so an intent change cannot
* silently re-install a profile the user switched off. */
export function setActiveProofCube(cube: SoftProofCube | null) {
active = cube;
if (!cube) activeBytes = null;
}
export function getActiveProofCube(): SoftProofCube | null {
return active;
}
/** Parses a .icc/.icm file and makes it the session's proof profile. */
export function loadProofProfile(bytes: Uint8Array, size = 33): SoftProofCube {
function activate(bytes: Uint8Array, size: number, intent: ProofIntent): SoftProofCube {
const profile = parseIcc(bytes);
if (!profile) throw new Error('That file is not an ICC profile');
const cube = buildProofCube(profile, size);
setActiveProofCube(cube);
const cube = buildProofCube(profile, size, GAMUT_DELTA, intent);
activeBytes = bytes.slice();
active = cube;
return cube;
}
/** Parses a .icc/.icm file and makes it the active proof profile. */
export function loadProofProfile(
bytes: Uint8Array,
size = 33,
intent: ProofIntent = 'perceptual',
): SoftProofCube {
return activate(bytes, size, intent);
}
/**
* Rebuilds the active profile for a different intent. Returns null when no
* profile is loaded, so the caller can leave the paper simulation alone.
*/
export function rebuildProofCube(intent: ProofIntent, size = 33): SoftProofCube | null {
if (!activeBytes) return null;
try {
return activate(activeBytes, size, intent);
} catch {
return null;
}
}
/* ------------------------------------------------- persisted proof profile */
const PROOF_DB = 'lumenroom.proof';
const PROOF_STORE = 'profile';
const PROOF_KEY = 'active';
let proofDb: Promise<IDBDatabase> | null = null;
/**
* A one-store database for the loaded printer profile. It is separate from the
* catalogue so a server-backed workspace can remember the profile on this
* device without writing a megabyte into a photo record or the SQLite catalog.
*/
function openProofDb(): Promise<IDBDatabase> {
if (proofDb) return proofDb;
proofDb = new Promise((resolve, reject) => {
if (typeof indexedDB === 'undefined') {
reject(new Error('IndexedDB is unavailable'));
return;
}
const req = indexedDB.open(PROOF_DB, 1);
req.onupgradeneeded = () => {
if (!req.result.objectStoreNames.contains(PROOF_STORE)) {
req.result.createObjectStore(PROOF_STORE);
}
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error ?? new Error('Unable to open the proof profile store'));
});
return proofDb;
}
/** Remembers the active profile for the next session; failures are harmless. */
export async function persistProofProfile(): Promise<void> {
if (!activeBytes) return;
try {
const db = await openProofDb();
const bytes = activeBytes.slice();
const name = active?.name ?? 'ICC profile';
await new Promise<void>((resolve, reject) => {
const tx = db.transaction(PROOF_STORE, 'readwrite');
tx.objectStore(PROOF_STORE).put({ name, bytes }, PROOF_KEY);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error ?? new Error('Could not save the proof profile'));
});
} catch {
/* Private mode or no IndexedDB: the profile still lasts for this session. */
}
}
export async function clearPersistedProofProfile(): Promise<void> {
try {
const db = await openProofDb();
await new Promise<void>((resolve, reject) => {
const tx = db.transaction(PROOF_STORE, 'readwrite');
tx.objectStore(PROOF_STORE).delete(PROOF_KEY);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error ?? new Error('Could not clear the proof profile'));
});
} catch {
/* nothing persisted to clear */
}
}
/** Loads the profile saved by a previous session and rebuilds its cube. */
export async function restoreProofProfile(
intent: ProofIntent = 'perceptual',
): Promise<SoftProofCube | null> {
try {
const db = await openProofDb();
const stored = await new Promise<{ bytes?: Uint8Array } | undefined>((resolve, reject) => {
const req = db.transaction(PROOF_STORE, 'readonly').objectStore(PROOF_STORE).get(PROOF_KEY);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
if (!stored?.bytes) return null;
return activate(stored.bytes, 33, intent);
} catch {
return null;
}
}
+11 -1
View File
@@ -138,6 +138,9 @@ export interface GeometryEdits {
scale: number;
}
/** ICC rendering intents the soft proof can build its round trip from. */
export type ProofIntent = 'perceptual' | 'relative' | 'saturation';
export interface Edits {
/** relative warm/cool offset, used when `kelvin` is null */
temp: number;
@@ -185,7 +188,14 @@ export interface Edits {
/** lensSoftness compensates for edge softness, 0–100 */
sharpen: { amount: number; radius: number; detail: number; mask: number; lensSoftness: number };
/** paper/output simulation for soft proofing */
proof: { enabled: boolean; paper: 'matte' | 'gloss' | 'newsprint'; blackPoint: number; gamut: boolean };
proof: {
enabled: boolean;
paper: 'matte' | 'gloss' | 'newsprint';
blackPoint: number;
gamut: boolean;
/** Which ICC table pair the printer round trip is built from. */
intent: ProofIntent;
};
/**
* Camera profile override for a raw file, as the camera-to-sRGB matrix derived
* from a DCP's ColorMatrix. Null renders with the matrix the body supplied.