From 637629385a3357011a38d8ecde358bcc29c09201 Mon Sep 17 00:00:00 2001 From: Brian Hursey Date: Sat, 28 Nov 2026 04:04:44 +0000 Subject: [PATCH] Show camera profiles in every view and remember proof and DCP settings. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- README.md | 29 ++++-- server/imaging.mjs | 57 +++++++++++ server/index.mjs | 49 ++++++++- server/storage.mjs | 25 +++++ src/components/CompareView.tsx | 25 ++++- src/components/Develop.tsx | 20 ++++ src/components/Panels.tsx | 80 ++++++++++++++- src/components/PresetThumbs.tsx | 20 ++-- src/lib/dcpLibrary.test.ts | 58 +++++++++++ src/lib/dcpLibrary.ts | 127 +++++++++++++++++++++++ src/lib/editThumbs.ts | 6 +- src/lib/edits.ts | 6 +- src/lib/images.ts | 38 +++++++ src/lib/softProof.test.ts | 35 +++++++ src/lib/softProof.ts | 172 ++++++++++++++++++++++++++++++-- src/types.ts | 12 ++- 16 files changed, 720 insertions(+), 39 deletions(-) create mode 100644 src/lib/dcpLibrary.test.ts create mode 100644 src/lib/dcpLibrary.ts diff --git a/README.md b/README.md index 969a4da..da5632a 100644 --- a/README.md +++ b/README.md @@ -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 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 - 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/.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 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. @@ -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/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/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. @@ -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 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 - the sidecar is, i.e. the Develop canvas and exports; grid thumbnails and the compare - view grade the sRGB JPEG, which already has the body matrix baked in, so they do not - show a different camera profile. The sidecar costs about 25× the JPEG in disk, one download per photo at open time and + the sidecar is: the Develop canvas, exports, Compare and preset previews. The grid + uses a camera-native tile built on demand beside the sidecar (`previews/.t16.png`), + 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 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 @@ -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 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 - 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. 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 its colour with the background needs a brush pass. Soft 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 - a gamut approximation otherwise. The profile is session state rather than part of the - edit, and the print dialog still does its own colour management. Both LUT layouts are + a gamut approximation otherwise. The loaded profile is remembered on this device (a + 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 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 diff --git a/server/imaging.mjs b/server/imaging.mjs index 479e8f9..073f7b5 100644 --- a/server/imaging.mjs +++ b/server/imaging.mjs @@ -161,6 +161,63 @@ export function encodePng16(rgb16, width, height, matrix = null) { 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) { const sharp = await loadSharp(); if (!sharp) { diff --git a/server/index.mjs b/server/index.mjs index 51c8225..f691345 100644 --- a/server/index.mjs +++ b/server/index.mjs @@ -60,10 +60,12 @@ import { findProof, findProofThumb, findThumb, + findThumb16, isCustomRoot, originalTarget, removeAsset, removePreview16, + removeThumb16, setStorageRoot, storageBytes, storageRoot, @@ -72,6 +74,7 @@ import { writeProof, writeProofThumb, writeThumb, + writeThumb16, } from './storage.mjs'; import { decodeRaw, isRawName, rawSupport } from './raw.mjs'; import { @@ -84,7 +87,7 @@ import { purgeExpiredBridges, verifyBridgeToken, } from './bridge.mjs'; -import { jpegInfo, makeThumb, toJpegProxy } from './imaging.mjs'; +import { cameraThumb16, jpegInfo, makeThumb, toJpegProxy } from './imaging.mjs'; import { createZip } from './zip.mjs'; import { cancelPrune, @@ -1940,8 +1943,15 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => { const data = await fsp.readFile(target); const decoded = await decodeRaw(data); await writePreview(params.id, decoded.jpeg, decoded.ext); - if (decoded.preview16) await writePreview16(params.id, decoded.preview16.data); - else await removePreview16(params.id); + if (decoded.preview16) { + 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); return json(res, 201, { raw: true, @@ -1980,8 +1990,13 @@ route('POST', '/api/photos/:id/reprocess', async ({ req, res, params }) => { try { const decoded = await decodeRaw(await fsp.readFile(original)); await writePreview(params.id, decoded.jpeg, decoded.ext); - if (decoded.preview16) await writePreview16(params.id, decoded.preview16.data); - else await removePreview16(params.id); + if (decoded.preview16) { + 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); if (thumb) await writeThumb(params.id, thumb); // 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'); }); +/** + * 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 * stay untouched; galleries read this copy so clients see the developed image. diff --git a/server/storage.mjs b/server/storage.mjs index 3db4c5f..d0a8d4f 100644 --- a/server/storage.mjs +++ b/server/storage.mjs @@ -141,6 +141,30 @@ export async function removePreview16(id) { 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 * switching Amount back to a previous value reuses the file instead of spending @@ -234,6 +258,7 @@ export async function removeAsset(id) { findOriginal(id), findPreview(id), findPreview16(id), + findThumb16(id), findThumb(id), findProof(id), findProofThumb(id), diff --git a/src/components/CompareView.tsx b/src/components/CompareView.tsx index e2a93fb..8441f43 100644 --- a/src/components/CompareView.tsx +++ b/src/components/CompareView.tsx @@ -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(null); const rendererRef = useRef(null); const [bitmap, setBitmap] = useState(null); + const [hdr, setHdr] = useState(null); const [box, setBox] = useState({ w: 0, h: 0 }); const [lensCorrection, setLensCorrection] = useState(null); const [error, setError] = useState(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 (
onOpen(photo.id)}> diff --git a/src/components/Develop.tsx b/src/components/Develop.tsx index 48f4f6c..85c5cd3 100644 --- a/src/components/Develop.tsx +++ b/src/components/Develop.tsx @@ -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 }) => { diff --git a/src/components/Panels.tsx b/src/components/Panels.tsx index 9c7f069..1fc005b 100644 --- a/src/components/Panels.tsx +++ b/src/components/Panels.tsx @@ -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(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(() => 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({ )} )} + {matching.length > 0 && ( + + )} + {applied && ( + + )}

{!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({ + { setActiveProofCube(null); + void clearPersistedProofProfile(); setProfileError(null); onProofProfile?.(null); }} diff --git a/src/components/PresetThumbs.tsx b/src/components/PresetThumbs.tsx index a0b19ce..9e493f6 100644 --- a/src/components/PresetThumbs.tsx +++ b/src/components/PresetThumbs.tsx @@ -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 { const [thumbs, setThumbs] = useState>({}); @@ -23,6 +24,10 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record 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 = {}; 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 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 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(); + 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); + }); +}); diff --git a/src/lib/dcpLibrary.ts b/src/lib/dcpLibrary.ts new file mode 100644 index 0000000..ca8a54f --- /dev/null +++ b/src/lib/dcpLibrary.ts @@ -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; + +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; + 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)); +} diff --git a/src/lib/editThumbs.ts b/src/lib/editThumbs.ts index b840f9b..683b67d 100644 --- a/src/lib/editThumbs.ts +++ b/src/lib/editThumbs.ts @@ -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 { 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 { 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 }); diff --git a/src/lib/edits.ts b/src/lib/edits.ts index aac1c2e..62c054c 100644 --- a/src/lib/edits.ts +++ b/src/lib/edits.ts @@ -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 | 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), diff --git a/src/lib/images.ts b/src/lib/images.ts index fbbfa7a..f6a7775 100644 --- a/src/lib/images.ts +++ b/src/lib/images.ts @@ -141,7 +141,45 @@ export async function get16BitSource(photo: PhotoRecord): Promise(); + +/** + * 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 { + 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(); diff --git a/src/lib/softProof.test.ts b/src/lib/softProof.test.ts index ea9f584..2810475 100644 --- a/src/lib/softProof.test.ts +++ b/src/lib/softProof.test.ts @@ -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', diff --git a/src/lib/softProof.ts b/src/lib/softProof.ts index 39dbe7a..20fd8e0 100644 --- a/src/lib/softProof.ts +++ b/src/lib/softProof.ts @@ -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 = { + 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 | 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 { + 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 { + if (!activeBytes) return; + try { + const db = await openProofDb(); + const bytes = activeBytes.slice(); + const name = active?.name ?? 'ICC profile'; + await new Promise((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 { + try { + const db = await openProofDb(); + await new Promise((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 { + 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; + } +} diff --git a/src/types.ts b/src/types.ts index 38e5f05..be798c4 100644 --- a/src/types.ts +++ b/src/types.ts @@ -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.