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
+21 -8
View File
@@ -835,7 +835,10 @@ The browser cannot demosaic camera raw, so the server does it during upload:
texture and applies `rgb_cam` in the grade shader, so the grade has 65,536 levels per texture and applies `rgb_cam` in the grade shader, so the grade has 65,536 levels per
channel instead of 256. A photo without a sidecar — one imported before this existed, channel instead of 256. A photo without a sidecar — one imported before this existed,
a non-raw file, or a build with `LUMINARY_16BIT=0` — simply grades the JPEG, so a non-raw file, or a build with `LUMINARY_16BIT=0` — simply grades the JPEG, so
nothing breaks either way. nothing breaks either way. The grid and Compare read the same samples: on first
request the server writes a camera-native tile the size of the JPEG thumbnail at
`previews/<id>.t16.png`, and Compare loads the full sidecar, so a loaded DCP profile
shows in every view of the photo. Preset previews do the same.
3. If LibRaw cannot open the file, the largest JPEG embedded in the container is 3. If LibRaw cannot open the file, the largest JPEG embedded in the container is
extracted and normalised instead. The grid marks such photos `RAW` and the Info panel extracted and normalised instead. The grid marks such photos `RAW` and the Info panel
reports which engine produced the proxy, so exotic or very new cameras still import. reports which engine produced the proxy, so exotic or very new cameras still import.
@@ -970,7 +973,8 @@ Conventions worth knowing before changing code:
| `src/lib/editSections.test.ts` | Selective settings copy and the ISO-aware auto-noise curve | | `src/lib/editSections.test.ts` | Selective settings copy and the ISO-aware auto-noise curve |
| `src/lib/preview16.test.ts` | 16-bit PNG proxy parsing, row flip, half-float encoding and the camera matrix chunk | | `src/lib/preview16.test.ts` | 16-bit PNG proxy parsing, row flip, half-float encoding and the camera matrix chunk |
| `src/lib/dcp.test.ts` | DCP tag parsing and the camera matrix recipe against LibRaw's own values | | `src/lib/dcp.test.ts` | DCP tag parsing and the camera matrix recipe against LibRaw's own values |
| `src/lib/softProof.test.ts` | ICC parsing (including counted lut16 tables), the printer round trip, gamut threshold and CMYK profiles | | `src/lib/softProof.test.ts` | ICC parsing (including counted lut16 tables), the printer round trip, gamut threshold, rendering-intent selection and CMYK profiles |
| `src/lib/dcpLibrary.test.ts` | Per-camera DCP library: validation, replacement, forgetting and camera matching |
There are no server integration tests; the API is exercised through the UI. There are no server integration tests; the API is exercised through the UI.
@@ -1009,9 +1013,11 @@ There are no server integration tests; the API is exercised through the UI.
present, which is what keeps a heavy shadow lift or a 3200 K white balance from present, which is what keeps a heavy shadow lift or a 3200 K white balance from
posterising an 8-bit source; the JPEG and everything derived from it (thumbnails, posterising an 8-bit source; the JPEG and everything derived from it (thumbnails,
denoise renders, proofs) stay 8-bit. A per-photo DCP profile is applied wherever denoise renders, proofs) stay 8-bit. A per-photo DCP profile is applied wherever
the sidecar is, i.e. the Develop canvas and exports; grid thumbnails and the compare the sidecar is: the Develop canvas, exports, Compare and preset previews. The grid
view grade the sRGB JPEG, which already has the body matrix baked in, so they do not uses a camera-native tile built on demand beside the sidecar (`previews/<id>.t16.png`),
show a different camera profile. The sidecar costs about 25× the JPEG in disk, one download per photo at open time and so a profile does not cost a 50 MB fetch per card; a photo that predates the tile or
was imported with `LUMINARY_16BIT=0` falls back to the JPEG, which already has the
body matrix baked in. The sidecar costs about 25× the JPEG in disk, one download per photo at open time and
one extra texture in GPU memory (about 8 bytes per pixel), so `LUMINARY_16BIT=0` turns one extra texture in GPU memory (about 8 bytes per pixel), so `LUMINARY_16BIT=0` turns
it off for libraries that would rather have the space. Either way the 16-bit TIFF export writes 65,536 it off for libraries that would rather have the space. Either way the 16-bit TIFF export writes 65,536
samples per channel from the `RGBA16F` render target, so its precision is only more samples per channel from the `RGBA16F` render target, so its precision is only more
@@ -1022,15 +1028,22 @@ There are no server integration tests; the API is exercised through the UI.
matrix pair. Raw decode uses the camera's own matrix; a DCP `ColorMatrix` reproduces matrix pair. Raw decode uses the camera's own matrix; a DCP `ColorMatrix` reproduces
it exactly (`src/lib/dcp.ts` parses the file and derives the matrix), and **Develop → it exactly (`src/lib/dcp.ts` parses the file and derives the matrix), and **Develop →
Camera profile** loads a `.dcp` per photo, storing the derived 9-number matrix in Camera profile** loads a `.dcp` per photo, storing the derived 9-number matrix in
the edit so it follows presets, snapshots and XMP. The picker is available only on the edit so it follows presets, snapshots and XMP. A loaded matrix is also remembered
per camera body in a local profile library (`src/lib/dcpLibrary.ts`), so the next
frame from that body needs one menu pick instead of another file dialog; the edit
keeps its own copy, so the library is only a shortcut. The picker is available only on
camera-native sidecars; an older sRGB proxy needs a RAW reprocess first. camera-native sidecars; an older sRGB proxy needs a RAW reprocess first.
Auto masks are an on-device colour-model segmentation (border histogram, Otsu split, Auto masks are an on-device colour-model segmentation (border histogram, Otsu split,
connected components), not a trained segmentation network, so a subject that shares connected components), not a trained segmentation network, so a subject that shares
its colour with the background needs a brush pass. Soft its colour with the background needs a brush pass. Soft
proofing applies a printer profile's real A2B/B2A tables when one is loaded proofing applies a printer profile's real A2B/B2A tables when one is loaded
(**Soft proofing → Load ICC profile**), and falls back to paper white, black point and (**Soft proofing → Load ICC profile**), and falls back to paper white, black point and
a gamut approximation otherwise. The profile is session state rather than part of the a gamut approximation otherwise. The loaded profile is remembered on this device (a
edit, and the print dialog still does its own colour management. Both LUT layouts are small IndexedDB store, not the photo record or the catalog) and the edit stores the
rendering intent — perceptual, relative colorimetric or saturation — so a proof
survives reloads and follows the photo. A profile without tables for the chosen intent
falls back to its perceptual pair. The print dialog still does its own colour
management. Both LUT layouts are
read: v2 `lut16` with fixed 256-entry tables and the counted v4 layout that MOAB/Epson read: v2 `lut16` with fixed 256-entry tables and the counted v4 layout that MOAB/Epson
paper profiles and Ghostscript's press profiles actually use (4096 entries, counts at paper profiles and Ghostscript's press profiles actually use (4096 entries, counts at
offsets 48/50). Against LittleCMS on a MOAB/Epson ET-8550 profile the cube agrees to a offsets 48/50). Against LittleCMS on a MOAB/Epson ET-8550 profile the cube agrees to a
+57
View File
@@ -161,6 +161,63 @@ export function encodePng16(rgb16, width, height, matrix = null) {
chunk('IEND', Buffer.alloc(0)), chunk('IEND', Buffer.alloc(0)),
]); ]);
} }
/** The camera matrix carried in a 16-bit sidecar's `rgbCam` tEXt chunk. */
export function png16Matrix(png) {
const needle = Buffer.from('rgbCam\0', 'latin1');
const at = png.indexOf(needle);
if (at < 0) return null;
const start = at + needle.length;
// The text runs to the end of the tEXt chunk, and the chunk's CRC is binary
// and may contain a NUL. Stop at the first byte that cannot be part of the
// comma-separated number list instead of searching for a terminator.
let end = start;
while (end < png.length) {
const code = png[end];
const numeric =
(code >= 0x30 && code <= 0x39) || // 0-9
code === 0x2e || // .
code === 0x2c || // ,
code === 0x2d || // -
code === 0x2b || // +
code === 0x65 || // e
code === 0x45; // E
if (!numeric) break;
end++;
}
const values = png.toString('latin1', start, end).split(',').map(Number);
return values.length === 9 && values.every(Number.isFinite) ? values : null;
}
/**
* A camera-native grid thumbnail, resized from the 16-bit sidecar with sharp's
* 16-bit path. The grid normally renders the sRGB JPEG, whose body matrix is
* already baked in; this gives the client camera samples small enough to fetch
* per tile, so a per-photo DCP profile shows everywhere the photo does. The
* `rgbCam` tag is rewritten so the client still knows how to convert them.
*/
export async function cameraThumb16(png16, width, height, matrix = null) {
const sharp = await loadSharp();
if (!sharp || width < 1 || height < 1) return null;
try {
const { data, info } = await sharp(png16)
.resize({ width, height, fit: 'fill' })
.raw({ depth: 'ushort' })
.toBuffer({ resolveWithObject: true });
if (info.channels !== 3 || info.depth !== 'ushort') return null;
// Copy through a fresh buffer: a raw output offset is not guaranteed to be
// 16-bit aligned, and Uint16Array refuses an odd byteOffset.
const samples = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
return encodePng16(
new Uint16Array(samples),
info.width,
info.height,
matrix ?? png16Matrix(png16),
);
} catch {
return null;
}
}
export async function encodeRgb(rgb, width, height, quality = 92, maxEdge = 0) { export async function encodeRgb(rgb, width, height, quality = 92, maxEdge = 0) {
const sharp = await loadSharp(); const sharp = await loadSharp();
if (!sharp) { if (!sharp) {
+44 -5
View File
@@ -60,10 +60,12 @@ import {
findProof, findProof,
findProofThumb, findProofThumb,
findThumb, findThumb,
findThumb16,
isCustomRoot, isCustomRoot,
originalTarget, originalTarget,
removeAsset, removeAsset,
removePreview16, removePreview16,
removeThumb16,
setStorageRoot, setStorageRoot,
storageBytes, storageBytes,
storageRoot, storageRoot,
@@ -72,6 +74,7 @@ import {
writeProof, writeProof,
writeProofThumb, writeProofThumb,
writeThumb, writeThumb,
writeThumb16,
} from './storage.mjs'; } from './storage.mjs';
import { decodeRaw, isRawName, rawSupport } from './raw.mjs'; import { decodeRaw, isRawName, rawSupport } from './raw.mjs';
import { import {
@@ -84,7 +87,7 @@ import {
purgeExpiredBridges, purgeExpiredBridges,
verifyBridgeToken, verifyBridgeToken,
} from './bridge.mjs'; } from './bridge.mjs';
import { jpegInfo, makeThumb, toJpegProxy } from './imaging.mjs'; import { cameraThumb16, jpegInfo, makeThumb, toJpegProxy } from './imaging.mjs';
import { createZip } from './zip.mjs'; import { createZip } from './zip.mjs';
import { import {
cancelPrune, cancelPrune,
@@ -1940,8 +1943,15 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
const data = await fsp.readFile(target); const data = await fsp.readFile(target);
const decoded = await decodeRaw(data); const decoded = await decodeRaw(data);
await writePreview(params.id, decoded.jpeg, decoded.ext); await writePreview(params.id, decoded.jpeg, decoded.ext);
if (decoded.preview16) await writePreview16(params.id, decoded.preview16.data); if (decoded.preview16) {
else await removePreview16(params.id); await writePreview16(params.id, decoded.preview16.data);
// The thumbnail may not exist yet; drop any camera-native tile so the
// first grid view rebuilds it from the new pixels.
await removeThumb16(params.id);
} else {
await removePreview16(params.id);
await removeThumb16(params.id);
}
const info = await jpegInfo(decoded.jpeg); const info = await jpegInfo(decoded.jpeg);
return json(res, 201, { return json(res, 201, {
raw: true, raw: true,
@@ -1980,8 +1990,13 @@ route('POST', '/api/photos/:id/reprocess', async ({ req, res, params }) => {
try { try {
const decoded = await decodeRaw(await fsp.readFile(original)); const decoded = await decodeRaw(await fsp.readFile(original));
await writePreview(params.id, decoded.jpeg, decoded.ext); await writePreview(params.id, decoded.jpeg, decoded.ext);
if (decoded.preview16) await writePreview16(params.id, decoded.preview16.data); if (decoded.preview16) {
else await removePreview16(params.id); await writePreview16(params.id, decoded.preview16.data);
await removeThumb16(params.id);
} else {
await removePreview16(params.id);
await removeThumb16(params.id);
}
const thumb = await makeThumb(decoded.jpeg, 560); const thumb = await makeThumb(decoded.jpeg, 560);
if (thumb) await writeThumb(params.id, thumb); if (thumb) await writeThumb(params.id, thumb);
// The old denoised renders were made from the previous proxy. // The old denoised renders were made from the previous proxy.
@@ -2023,6 +2038,30 @@ route('GET', '/api/photos/:id/thumb', async ({ req, res, params }) => {
return sendBuffer(res, data, 'image/jpeg'); return sendBuffer(res, data, 'image/jpeg');
}); });
/**
* Camera-native version of the grid thumbnail, built on first request from the
* 16-bit sidecar and the JPEG thumbnail so the two have identical dimensions.
* Without this the grid can only show the camera profile's effect in Develop.
*/
route('GET', '/api/photos/:id/thumb16', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found');
let file = findThumb16(params.id);
if (!file) {
const sidecar = findPreview16(params.id);
const thumb = findThumb(params.id);
if (sidecar && thumb) {
const info = await jpegInfo(await fsp.readFile(thumb));
if (info?.width && info?.height) {
const png = await cameraThumb16(await fsp.readFile(sidecar), info.width, info.height);
if (png) file = await writeThumb16(params.id, png);
}
}
}
return sendFile(req, res, file, 'image/png');
});
/** /**
* Store a rendered proof for an edited photo. The editable proxy and original * Store a rendered proof for an edited photo. The editable proxy and original
* stay untouched; galleries read this copy so clients see the developed image. * stay untouched; galleries read this copy so clients see the developed image.
+25
View File
@@ -141,6 +141,30 @@ export async function removePreview16(id) {
if (found) await fsp.rm(found, { force: true }); if (found) await fsp.rm(found, { force: true });
} }
/**
* Camera-native grid thumbnail: the sidecar's samples at the JPEG thumbnail's
* size, so the grid can honour a per-photo camera profile without downloading
* the full sidecar. Lives beside the sidecar and is regenerated on demand.
*/
export async function writeThumb16(id, data) {
ensureDirs();
const target = path.join(storageRoot(), 'previews', `${safeId(id)}.t16.png`);
await fsp.writeFile(target, data);
return target;
}
export function findThumb16(id) {
const safe = lookupId(id);
if (!safe) return null;
const p = path.join(dirs().previews, `${safe}.t16.png`);
return fs.existsSync(p) ? p : null;
}
export async function removeThumb16(id) {
const found = findThumb16(id);
if (found) await fsp.rm(found, { force: true });
}
/** /**
* Denoised proxies, keyed by the hash of the parameters that produced them, so * Denoised proxies, keyed by the hash of the parameters that produced them, so
* switching Amount back to a previous value reuses the file instead of spending * switching Amount back to a previous value reuses the file instead of spending
@@ -234,6 +258,7 @@ export async function removeAsset(id) {
findOriginal(id), findOriginal(id),
findPreview(id), findPreview(id),
findPreview16(id), findPreview16(id),
findThumb16(id),
findThumb(id), findThumb(id),
findProof(id), findProof(id),
findProofThumb(id), findProofThumb(id),
+22 -3
View File
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from 'react'; 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 { rotatedBounds, Renderer } from '../gl/renderer';
import { buildLensCorrection, type LensCorrection } from '../lib/lensfun'; import { buildLensCorrection, type LensCorrection } from '../lib/lensfun';
import type { PhotoRecord } from '../types'; import type { PhotoRecord } from '../types';
@@ -15,6 +16,7 @@ function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: strin
const boxRef = useRef<HTMLDivElement>(null); const boxRef = useRef<HTMLDivElement>(null);
const rendererRef = useRef<Renderer | null>(null); const rendererRef = useRef<Renderer | null>(null);
const [bitmap, setBitmap] = useState<ImageBitmap | 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 [box, setBox] = useState({ w: 0, h: 0 });
const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null); const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@@ -29,6 +31,23 @@ function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: strin
}; };
}, [photo]); }, [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(() => { useEffect(() => {
let alive = true; let alive = true;
if (!photo.edits.lens || !bitmap) { if (!photo.edits.lens || !bitmap) {
@@ -98,14 +117,14 @@ function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: strin
lens: lensCorrection, lens: lensCorrection,
}; };
try { try {
renderer.setImage(bitmap); renderer.setImage(bitmap, hdr);
renderer.render(photo.edits, opts); renderer.render(photo.edits, opts);
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : 'Rendering failed'); setError(err instanceof Error ? err.message : 'Rendering failed');
} }
}); });
return () => cancelAnimationFrame(raf); return () => cancelAnimationFrame(raf);
}, [bitmap, box, photo, lensCorrection]); }, [bitmap, box, photo, lensCorrection, hdr]);
return ( return (
<figure className="compare-tile" onDoubleClick={() => onOpen(photo.id)}> <figure className="compare-tile" onDoubleClick={() => onOpen(photo.id)}>
+20
View File
@@ -8,6 +8,7 @@ import {
} from '../lib/edits'; } from '../lib/edits';
import { subscribeClipPreview } from '../lib/clipPreview'; import { subscribeClipPreview } from '../lib/clipPreview';
import { get16BitSource, getBitmap, getDenoisedBitmap } from '../lib/images'; import { get16BitSource, getBitmap, getDenoisedBitmap } from '../lib/images';
import { rebuildProofCube, restoreProofProfile } from '../lib/softProof';
import type { Preview16 } from '../lib/preview16'; import type { Preview16 } from '../lib/preview16';
import { useMediaQuery } from '../lib/useMediaQuery'; import { useMediaQuery } from '../lib/useMediaQuery';
import { usePersistentState } from '../lib/usePersistentState'; import { usePersistentState } from '../lib/usePersistentState';
@@ -627,6 +628,25 @@ export default function Develop({
return () => cancelAnimationFrame(raf); return () => cancelAnimationFrame(raf);
}, [bitmap, drawPreview]); }, [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 */ /* ------------------------------------------------------------ zoom & pan */
const applyZoom = useCallback((rawPct: number | 'fit', point?: { x: number; y: number }) => { 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 { grainSampleWindow, rotatedBounds, Renderer } from '../gl/renderer';
import { applyFilmVariant, FILM_VARIANTS, PRESET_CATEGORIES, type FilmVariant } from '../lib/presets'; import { applyFilmVariant, FILM_VARIANTS, PRESET_CATEGORIES, type FilmVariant } from '../lib/presets';
import { usePersistentState } from '../lib/usePersistentState'; 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 { dcpRgbCam, parseDcp } from '../lib/dcp';
import {
loadSavedCameraProfiles,
removeCameraProfile,
saveCameraProfile,
savedProfilesForCamera,
type SavedCameraProfile,
} from '../lib/dcpLibrary';
import { usePresetThumbs } from './PresetThumbs'; import { usePresetThumbs } from './PresetThumbs';
import { availableFor, findLensForMeta, searchLens, type LensSearchResult } from '../lib/lensfun'; import { availableFor, findLensForMeta, searchLens, type LensSearchResult } from '../lib/lensfun';
import { import {
@@ -2178,6 +2191,12 @@ export function CameraProfilePanel({
}: PanelSetProps & { cameraNative?: boolean }) { }: PanelSetProps & { cameraNative?: boolean }) {
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const profile = edits.cameraProfile; 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) => { const load = async (file: File) => {
if (!cameraNative) return; if (!cameraNative) return;
@@ -2188,6 +2207,7 @@ export function CameraProfilePanel({
if (!matrix) throw new Error('This profile has no usable colour matrix'); if (!matrix) throw new Error('This profile has no usable colour matrix');
setError(null); setError(null);
set({ cameraProfile: { name: parsed.name, matrix } }, 'Camera profile'); set({ cameraProfile: { name: parsed.name, matrix } }, 'Camera profile');
setSaved(saveCameraProfile({ name: parsed.name, camera: camera || parsed.camera, matrix }));
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : 'Could not read that profile'); setError(err instanceof Error ? err.message : 'Could not read that profile');
} }
@@ -2219,7 +2239,7 @@ export function CameraProfilePanel({
className="btn ghost small" className="btn ghost small"
onClick={() => { onClick={() => {
setError(null); setError(null);
set({ cameraProfile: null }, 'Body camera profile'); set({ cameraProfile: null }, 'Body camera matrix');
}} }}
> >
Use body matrix Use body matrix
@@ -2227,6 +2247,38 @@ export function CameraProfilePanel({
)} )}
</div> </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"> <p className="muted small panel-hint">
{!cameraNative {!cameraNative
? 'This proxy was decoded straight to sRGB, so there are no camera samples to profile. Reprocess the RAW to enable camera profiles.' ? '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) => { const loadProfile = async (file: File) => {
try { 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); setProfileError(null);
onProofProfile?.(cube); onProofProfile?.(cube);
} catch (err) { } catch (err) {
@@ -2293,6 +2348,24 @@ export function ProofPanel({
<option value="newsprint">Newsprint</option> <option value="newsprint">Newsprint</option>
</select> </select>
</label> </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 <Slider
label="Paper black" label="Paper black"
min={0} min={0}
@@ -2324,6 +2397,7 @@ export function ProofPanel({
className="btn ghost small" className="btn ghost small"
onClick={() => { onClick={() => {
setActiveProofCube(null); setActiveProofCube(null);
void clearPersistedProofProfile();
setProfileError(null); setProfileError(null);
onProofProfile?.(null); onProofProfile?.(null);
}} }}
+13 -7
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { normalizeEdits } from '../lib/edits'; import { normalizeEdits } from '../lib/edits';
import { getBitmap } from '../lib/images'; import { get16BitSource, getBitmap } from '../lib/images';
import { Renderer, rotatedBounds } from '../gl/renderer'; import { Renderer, rotatedBounds } from '../gl/renderer';
import type { PhotoRecord, Preset } from '../types'; import type { PhotoRecord, Preset } from '../types';
@@ -14,7 +14,8 @@ const CACHE_LIMIT = 900;
const THUMB_EDGE = 200; const THUMB_EDGE = 200;
/** The crop is part of the key so a turn, straighten or flip refreshes the tiles. */ /** 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> { export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> {
const [thumbs, setThumbs] = useState<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 presetKey = presets.map((p) => p.id).join('|');
const crop = photo.edits.crop; const crop = photo.edits.crop;
const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(','); 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(() => { useEffect(() => {
let alive = true; let alive = true;
@@ -31,7 +36,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
const known: Record<string, string> = {}; const known: Record<string, string> = {};
for (const preset of presets) { 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; if (hit) known[preset.id] = hit;
} }
setThumbs(known); setThumbs(known);
@@ -43,6 +48,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
try { try {
const bitmap = await getBitmap(photo); const bitmap = await getBitmap(photo);
if (!alive) return; if (!alive) return;
const hdr = profile ? await get16BitSource(photo).catch(() => null) : null;
renderer = new Renderer(canvas); renderer = new Renderer(canvas);
// Every tile shows the photo as it is framed now, so a turned photo's // Every tile shows the photo as it is framed now, so a turned photo's
// presets are turned too. // 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 scale = THUMB_EDGE / Math.max(cropW, cropH);
const width = Math.max(1, Math.round(cropW * scale)); const width = Math.max(1, Math.round(cropW * scale));
const height = Math.max(1, Math.round(cropH * scale)); const height = Math.max(1, Math.round(cropH * scale));
renderer.setImage(bitmap); renderer.setImage(bitmap, hdr);
for (const preset of pending) { for (const preset of pending) {
if (!alive) break; if (!alive) break;
try { try {
renderer.render({ ...normalizeEdits(preset.edits), crop }, { renderer.render({ ...normalizeEdits(preset.edits), crop, cameraProfile: profile }, {
width, width,
height, height,
upscale: Math.max(width / cropW, height / cropH) > 1.05, upscale: Math.max(width / cropW, height / cropH) > 1.05,
}); });
const url = canvas.toDataURL('image/jpeg', 0.72); 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 })); setThumbs((prev) => ({ ...prev, [preset.id]: url }));
} catch { } catch {
// One bad preset must not stop the rest of the grid. // 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(); renderer?.dispose();
}; };
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [photo.id, presetKey, cropKey]); }, [photo.id, presetKey, cropKey, sourceKey]);
return thumbs; 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 type { Edits, PhotoRecord } from '../types';
import { isEdited } from './edits'; import { isEdited } from './edits';
import { Renderer, rotatedBounds } from '../gl/renderer'; import { Renderer, rotatedBounds } from '../gl/renderer';
import { getCameraThumb } from './images';
/** /**
* Thumbnails of edited photos. * Thumbnails of edited photos.
@@ -77,6 +78,9 @@ async function renderThumb(photo: PhotoRecord): Promise<string | null> {
const bitmap = await loadThumb(photo); const bitmap = await loadThumb(photo);
if (!bitmap) return null; if (!bitmap) return null;
try { 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 crop = photo.edits.crop;
const frame = rotatedBounds(bitmap.width, bitmap.height, crop.angle, crop.quarter); const frame = rotatedBounds(bitmap.width, bitmap.height, crop.angle, crop.quarter);
const cropW = Math.max(1, frame.w * crop.w); 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 scale = Math.min(2, RENDER_EDGE / Math.max(cropW, cropH));
const width = Math.max(16, Math.round(cropW * scale)); const width = Math.max(16, Math.round(cropW * scale));
const height = Math.max(16, Math.round(cropH * 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 // `lens: null` clears the previous photo's calibration maps: this renderer
// is shared, and a stale map would warp the next thumbnail. // is shared, and a stale map would warp the next thumbnail.
r.render(photo.edits, { width, height, lens: null, upscale: scale > 1.02 }); 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, balance: 0,
}, },
sharpen: { amount: 0, radius: 1, detail: 25, mask: 0, lensSoftness: 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, cameraProfile: null,
noise: { luminance: 0, detail: 50, chroma: 0, chromaDetail: 50 }, noise: { luminance: 0, detail: 50, chroma: 0, chromaDetail: 50 },
aiDenoise: { amount: 100, key: null, model: 'guided' }, 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', paper: input.proof?.paper === 'gloss' || input.proof?.paper === 'newsprint' ? input.proof.paper : 'matte',
blackPoint: num(input.proof?.blackPoint, 2, 0, 20), blackPoint: num(input.proof?.blackPoint, 2, 0, 20),
gamut: !!input.proof?.gamut, gamut: !!input.proof?.gamut,
intent:
input.proof?.intent === 'relative' || input.proof?.intent === 'saturation'
? input.proof.intent
: 'perceptual',
}, },
noise: { noise: {
luminance: num(noise.luminance, 0, 0, 100), 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; 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() { export function clearBitmapCache() {
cameraThumbCache.clear();
for (const bmp of cache.values()) bmp.close(); for (const bmp of cache.values()) bmp.close();
cache.clear(); cache.clear();
for (const bmp of denoisedCache.values()) bmp.close(); for (const bmp of denoisedCache.values()) bmp.close();
+35
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { import {
buildProofCube, buildProofCube,
GAMUT_DELTA,
getActiveProofCube, getActiveProofCube,
loadProofProfile, loadProofProfile,
parseIcc, parseIcc,
@@ -136,17 +137,21 @@ function buildIcc({
pcs = 'Lab ', pcs = 'Lab ',
a2b, a2b,
b2a, b2a,
extra = [],
}: { }: {
name: string; name: string;
colourSpace?: string; colourSpace?: string;
pcs?: string; pcs?: string;
a2b: Uint8Array; a2b: Uint8Array;
b2a: Uint8Array; b2a: Uint8Array;
/** Additional intent tables, e.g. A2B1/B2A1 for relative colorimetric. */
extra?: { signature: string; bytes: Uint8Array }[];
}): Uint8Array { }): Uint8Array {
const tags: { signature: string; bytes: Uint8Array }[] = [ const tags: { signature: string; bytes: Uint8Array }[] = [
{ signature: 'desc', bytes: descTag(name) }, { signature: 'desc', bytes: descTag(name) },
{ signature: 'A2B0', bytes: a2b }, { signature: 'A2B0', bytes: a2b },
{ signature: 'B2A0', bytes: b2a }, { signature: 'B2A0', bytes: b2a },
...extra,
]; ];
let cursor = 128 + 4 + tags.length * 12; let cursor = 128 + 4 + tags.length * 12;
const placed = tags.map((tag) => { const placed = tags.map((tag) => {
@@ -308,6 +313,36 @@ describe('buildProofCube', () => {
expect(mid[0]).toBeLessThan(1); 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', () => { it('refuses a profile without a round trip', () => {
const bytes = buildIcc({ const bytes = buildIcc({
name: 'Half', name: 'Half',
+162 -10
View File
@@ -17,6 +17,8 @@
* table layouts are read, because printer profiles ship in both. * 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; const D50_WHITE = [0.9642, 1, 0.8249] as const;
/** Linear sRGB (D50 adapted) to XYZ, matching the primaries in `icc.ts`. */ /** Linear sRGB (D50 adapted) to XYZ, matching the primaries in `icc.ts`. */
@@ -67,6 +69,10 @@ export interface IccProfile {
pcs: Pcs; pcs: Pcs;
a2b: IccTransform | null; a2b: IccTransform | null;
b2a: 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 { export interface SoftProofCube {
@@ -482,15 +488,20 @@ export function parseIcc(bytes: Uint8Array): IccProfile | null {
}; };
const description = tags.get('desc'); 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 { return {
name: (description && parseDescription(view, description.at, description.size)) || 'ICC profile', name: (description && parseDescription(view, description.at, description.size)) || 'ICC profile',
profileClass: ascii(12), profileClass: ascii(12),
colourSpace, colourSpace,
pcs, pcs,
// Perceptual first, then relative colorimetric: a printer profile often // Perceptual first, then relative colorimetric: a printer profile often
// ships one and not the other. // ships one and not the other. The full table set is kept as well, so the
a2b: transform('A2B0', true) ?? transform('A2B1', true), // proof can be rebuilt for a different rendering intent.
b2a: transform('B2A0', false) ?? transform('B2A1', false), 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 * the tables the round trip needs, because silently showing the paper
* approximation instead would misrepresent what was loaded. * 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( export function buildProofCube(
profile: IccProfile, profile: IccProfile,
size = 33, size = 33,
gamutDelta = GAMUT_DELTA, gamutDelta = GAMUT_DELTA,
intent: ProofIntent = 'perceptual',
): SoftProofCube { ): 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'); 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))); const edge = Math.max(2, Math.min(65, Math.round(size)));
@@ -536,8 +575,8 @@ export function buildProofCube(
const lab = xyzToLab(xyz); const lab = xyzToLab(xyz);
const pcs = encodePcs(profile.pcs, lab, xyz); const pcs = encodePcs(profile.pcs, lab, xyz);
// Into the printer, then back out: what the paper can actually show. // Into the printer, then back out: what the paper can actually show.
const device = evaluate(profile.b2a, pcs); const device = evaluate(tables.b2a, pcs);
const printed = evaluate(profile.a2b, device); const printed = evaluate(tables.a2b, device);
const back = decodePcs(profile.pcs, printed); const back = decodePcs(profile.pcs, printed);
const rgb = multiply3(XYZ_TO_RGB, back.xyz); const rgb = multiply3(XYZ_TO_RGB, back.xyz);
data[at++] = clamp01(linearToSrgb(rgb[0])); data[at++] = clamp01(linearToSrgb(rgb[0]));
@@ -567,20 +606,133 @@ export function buildProofCube(
* a megabyte and does not belong in a photo record. * a megabyte and does not belong in a photo record.
*/ */
let active: SoftProofCube | null = null; 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) { export function setActiveProofCube(cube: SoftProofCube | null) {
active = cube; active = cube;
if (!cube) activeBytes = null;
} }
export function getActiveProofCube(): SoftProofCube | null { export function getActiveProofCube(): SoftProofCube | null {
return active; return active;
} }
/** Parses a .icc/.icm file and makes it the session's proof profile. */ function activate(bytes: Uint8Array, size: number, intent: ProofIntent): SoftProofCube {
export function loadProofProfile(bytes: Uint8Array, size = 33): SoftProofCube {
const profile = parseIcc(bytes); const profile = parseIcc(bytes);
if (!profile) throw new Error('That file is not an ICC profile'); if (!profile) throw new Error('That file is not an ICC profile');
const cube = buildProofCube(profile, size); const cube = buildProofCube(profile, size, GAMUT_DELTA, intent);
setActiveProofCube(cube); activeBytes = bytes.slice();
active = cube;
return 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; scale: number;
} }
/** ICC rendering intents the soft proof can build its round trip from. */
export type ProofIntent = 'perceptual' | 'relative' | 'saturation';
export interface Edits { export interface Edits {
/** relative warm/cool offset, used when `kelvin` is null */ /** relative warm/cool offset, used when `kelvin` is null */
temp: number; temp: number;
@@ -185,7 +188,14 @@ export interface Edits {
/** lensSoftness compensates for edge softness, 0–100 */ /** lensSoftness compensates for edge softness, 0–100 */
sharpen: { amount: number; radius: number; detail: number; mask: number; lensSoftness: number }; sharpen: { amount: number; radius: number; detail: number; mask: number; lensSoftness: number };
/** paper/output simulation for soft proofing */ /** 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 * 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. * from a DCP's ColorMatrix. Null renders with the matrix the body supplied.