Land camera-native raw profiles, real ICC soft proofing and 16-bit proxies.

Camera profiles, proofing tables and the half-float sidecar all have to agree
with the pixels the editor actually grades, so they land together with the
preset filter menu that was unusable while thumbnails streamed in.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
2026-11-28 03:59:55 +00:00
parent 6dfddffc14
commit 0c113e7a91
53 changed files with 9217 additions and 476 deletions
+98
View File
@@ -145,6 +145,21 @@ export function uploadOriginal(id: string, file: File | Blob, name: string): Pro
});
}
/** Re-decode a stored RAW with the server's current pipeline settings. */
export function reprocessRawPhoto(
id: string,
): Promise<{
width: number;
height: number;
engine?: 'libraw' | 'embedded';
note?: string | null;
previewVersion?: number;
previewUrl?: string;
thumbUrl?: string;
}> {
return request(`/api/photos/${encodeURIComponent(id)}/reprocess`, { method: 'POST' });
}
export function pushPhoto(photo: PhotoRecord): Promise<PhotoRecord> {
return request<{ photo: PhotoRecord }>(`/api/photos/${encodeURIComponent(photo.id)}`, {
method: 'PUT',
@@ -221,10 +236,26 @@ export interface ShareFeedback {
createdAt: number;
}
export interface ShareSettings {
passwordSet: boolean;
expiresAt: number | null;
watermark: string;
allowDownloads: boolean;
downloadCap: number;
downloadCount: number;
}
export interface ShareState {
token: string | null;
picks: { photoId: string; clientName: string }[];
feedback?: ShareFeedback[];
settings?: ShareSettings | null;
}
export interface GalleryStatus {
locked: boolean;
expiresAt: number | null;
allowDownloads: boolean;
}
export interface GalleryComment {
@@ -253,6 +284,8 @@ export interface GalleryPayload {
photographer: string;
photos: GalleryPhoto[];
picks: { total: number; clients: number };
downloads?: { allowed: boolean; remaining: number | null };
watermark?: string;
}
export function getShare(eventId: string): Promise<ShareState> {
@@ -274,6 +307,71 @@ export function galleryDownloadAllUrl(token: string, clientId: string): string {
return `/api/galleries/${encodeURIComponent(token)}/download-all?${query}`;
}
export interface ShareSettingsInput {
password?: string;
expiresAt?: number | null;
watermark?: string;
allowDownloads?: boolean;
downloadCap?: number;
}
export function saveShareSettings(
eventId: string,
input: ShareSettingsInput,
): Promise<ShareSettings> {
return request<{ settings: ShareSettings }>(
`/api/events/${encodeURIComponent(eventId)}/share/settings`,
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
},
).then((res) => res.settings);
}
/* ------------------------------------------------------------ tether api */
export interface TetherFile {
name: string;
size: number;
mtime: number;
}
export interface TetherState {
folder: string;
files: TetherFile[];
}
export function listTether(eventId: string): Promise<TetherState> {
return request<TetherState>(`/api/events/${encodeURIComponent(eventId)}/tether`);
}
export function tetherFileUrl(eventId: string, name: string): string {
const query = new URLSearchParams({ name });
return `/api/events/${encodeURIComponent(eventId)}/tether/file?${query}`;
}
export function removeTetherFile(eventId: string, name: string): Promise<void> {
const query = new URLSearchParams({ name });
return request(`/api/events/${encodeURIComponent(eventId)}/tether/file?${query}`, {
method: 'DELETE',
});
}
/** Public check for the link's lock and expiry, before loading the gallery. */
export function getGalleryStatus(token: string): Promise<GalleryStatus> {
return request<GalleryStatus>(`/api/galleries/${encodeURIComponent(token)}/status`);
}
/** Exchanges the gallery password for the unlock cookie the routes require. */
export function unlockGallery(token: string, password: string): Promise<void> {
return request(`/api/galleries/${encodeURIComponent(token)}/unlock`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }),
});
}
export function revokeShare(eventId: string): Promise<void> {
return request(`/api/events/${encodeURIComponent(eventId)}/share`, { method: 'DELETE' });
}
+67
View File
@@ -71,3 +71,70 @@ export async function computeAutoEdits(thumb: string): Promise<Partial<Edits>> {
return { contrast: 12, shadows: 12, highlights: -12, vibrance: 8 };
}
}
/**
* Grey-world auto white balance. It averages the unclipped midtones, then
* searches the two WB sliders for the multipliers that neutralise them. This is
* a starting point for mixed or unknown light, not a substitute for the
* eyedropper on a known neutral.
*/
export async function computeAutoWhiteBalance(
thumb: string,
): Promise<{ temp: number; tint: number }> {
try {
const img = new Image();
img.src = thumb;
await img.decode();
const w = 96;
const h = Math.max(1, Math.round((img.height / img.width) * w)) || 96;
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('Canvas unavailable');
ctx.drawImage(img, 0, 0, w, h);
const { data } = ctx.getImageData(0, 0, w, h);
let r = 0;
let g = 0;
let b = 0;
let count = 0;
for (let i = 0; i < data.length; i += 4) {
const rr = data[i];
const gg = data[i + 1];
const bb = data[i + 2];
const sum = rr + gg + bb;
// Clipped highlights and near-black pixels carry no reliable cast.
if (sum > 735 || sum < 24) continue;
r += rr;
g += gg;
b += bb;
count += 1;
}
if (!count) return { temp: 0, tint: 0 };
const ar = r / count / 255;
const ag = g / count / 255;
const ab = b / count / 255;
let best = { temp: 0, tint: 0, err: Number.POSITIVE_INFINITY };
for (let temp = -100; temp <= 100; temp += 4) {
for (let tint = -100; tint <= 100; tint += 4) {
const t = temp / 100;
const ti = tint / 100;
// Same channel multipliers the grade shader applies.
const mr = 1 + 0.3 * t + 0.06 * ti;
const mg = 1 - 0.16 * ti;
const mb = 1 - 0.26 * t + 0.06 * ti;
const rr = ar * mr;
const gg = ag * mg;
const bb = ab * mb;
const mean = (rr + gg + bb) / 3;
const err = (rr - mean) ** 2 + (gg - mean) ** 2 + (bb - mean) ** 2;
if (err < best.err) best = { temp, tint, err };
}
}
return { temp: best.temp, tint: best.tint };
} catch {
return { temp: 0, tint: 0 };
}
}
+92
View File
@@ -0,0 +1,92 @@
import { describe, expect, it } from 'vitest';
import { fillHoles, otsuThreshold, segmentMask } from './autoMask';
/** Flat grey background with a red block in the middle. */
function portrait(width = 64, height = 64): Uint8Array {
const data = new Uint8Array(width * height * 4);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const o = (y * width + x) * 4;
const inside = x > width * 0.3 && x < width * 0.7 && y > height * 0.25 && y < height * 0.85;
data[o] = inside ? 190 : 120;
data[o + 1] = inside ? 40 : 120;
data[o + 2] = inside ? 30 : 120;
data[o + 3] = 255;
}
}
return data;
}
describe('segmentation', () => {
it('selects the centred subject against a flat border', () => {
const width = 64;
const height = 64;
const mask = segmentMask(portrait(width, height), width, height, 'subject');
const at = (x: number, y: number) => mask[y * width + x];
expect(at(32, 32)).toBe(255);
expect(at(2, 32)).toBe(0);
expect(at(32, 2)).toBe(0);
let inside = 0;
let outside = 0;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const inSubject = x > width * 0.3 && x < width * 0.7 && y > height * 0.25 && y < height * 0.85;
if (inSubject && mask[y * width + x]) inside++;
if (!inSubject && mask[y * width + x]) outside++;
}
}
// Most of the subject is covered, and the flat wall mostly is not.
expect(inside / (width * height * 0.24)).toBeGreaterThan(0.6);
expect(outside).toBeLessThan(width * height * 0.2);
});
it('finds a blue sky above the horizon only', () => {
const width = 64;
const height = 64;
const data = new Uint8Array(width * height * 4);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const o = (y * width + x) * 4;
const sky = y < height / 2;
data[o] = sky ? 70 : 120;
data[o + 1] = sky ? 130 : 110;
data[o + 2] = sky ? 220 : 80;
data[o + 3] = 255;
}
}
const mask = segmentMask(data, width, height, 'sky');
expect(mask[10 * width + 32]).toBe(255);
expect(mask[55 * width + 32]).toBe(0);
});
it('inverts the subject for the background selection', () => {
const width = 64;
const height = 64;
const subject = segmentMask(portrait(width, height), width, height, 'subject');
const background = segmentMask(portrait(width, height), width, height, 'background');
expect(subject[32 * width + 32]).toBe(255);
expect(background[32 * width + 32]).toBe(0);
});
it('splits a bimodal score map', () => {
const values = new Float32Array(1000);
for (let i = 0; i < 500; i++) values[i] = 0.1;
for (let i = 500; i < 1000; i++) values[i] = 0.9;
const threshold = otsuThreshold(values);
expect(threshold).toBeGreaterThan(0.1);
expect(threshold).toBeLessThan(0.9);
});
it('fills an enclosed hole without spilling over the rim', () => {
const width = 9;
const height = 9;
const mask = new Uint8Array(width * height);
for (let y = 2; y < 7; y++) {
for (let x = 2; x < 7; x++) mask[y * width + x] = 255;
}
mask[4 * width + 4] = 0;
fillHoles(mask, width, height);
expect(mask[4 * width + 4]).toBe(255);
expect(mask[0]).toBe(0);
});
});
+236 -45
View File
@@ -6,15 +6,17 @@ export type AutoMaskKind = 'subject' | 'sky' | 'background';
* On-device mask estimation for the three selections that matter most in an
* event edit: the subject, the sky and the background around the subject.
*
* The estimator works from a downsampled preview. It combines distance from
* the border colour (the usual studio/event background) with a centre bias,
* saturation and a vertical sky prior. This is intentionally lightweight: it
* has no model download and produces a low-resolution raster that the normal
* mask pipeline feathers and scales. The output is editable like any brush
* mask, so a missed edge can be fixed without another model pass.
* The estimator works from a downsampled preview and is deliberately
* model-free: there is nothing to download and it runs in a few milliseconds.
* It builds a coarse colour histogram of the frame's border (the usual studio,
* venue or sky background), scores every pixel against that model plus a centre
* prior, splits the score map with an Otsu threshold, then keeps the connected
* regions that actually matter and fills interior holes. The result is a
* low-resolution raster the normal mask pipeline feathers and scales, and it is
* editable like any brush mask, so a missed edge can be fixed by hand.
*/
export async function buildAutoMask(bitmap: ImageBitmap, kind: AutoMaskKind): Promise<RasterMask> {
const width = Math.max(128, Math.min(320, Math.round(bitmap.width / 16)));
const width = Math.max(128, Math.min(384, Math.round(bitmap.width / 12)));
const height = Math.max(48, Math.round((width * bitmap.height) / Math.max(1, bitmap.width)));
const canvas = document.createElement('canvas');
canvas.width = width;
@@ -23,12 +25,26 @@ export async function buildAutoMask(bitmap: ImageBitmap, kind: AutoMaskKind): Pr
if (!ctx) throw new Error('Could not analyse the image for a mask');
ctx.drawImage(bitmap, 0, 0, width, height);
const image = ctx.getImageData(0, 0, width, height);
const data = image.data;
const count = width * height;
const mask = segmentMask(image.data, width, height, kind);
return { data: encodeBase64(mask), width, height };
}
const subject = new Float32Array(count);
const sky = new Float32Array(count);
const border = borderColor(data, width, height);
/**
* Pure segmentation step, exported so it can be exercised without a canvas.
* Returns one byte per pixel: 255 inside the selection, 0 outside.
*/
export function segmentMask(
data: Uint8ClampedArray | Uint8Array,
width: number,
height: number,
kind: AutoMaskKind,
): Uint8Array {
const count = width * height;
if (!count) return new Uint8Array(0);
const border = borderModel(data, width, height);
const score = new Float32Array(count);
const luma = new Float32Array(count);
for (let y = 0; y < height; y++) {
const ny = y / Math.max(1, height - 1);
@@ -38,55 +54,230 @@ export async function buildAutoMask(bitmap: ImageBitmap, kind: AutoMaskKind): Pr
const r = data[o] / 255;
const g = data[o + 1] / 255;
const b = data[o + 2] / 255;
const dist = Math.min(1, Math.sqrt((r - border[0]) ** 2 + (g - border[1]) ** 2 + (b - border[2]) ** 2) / 1.35);
const center = 1 - Math.min(1, Math.sqrt(((x / width - 0.5) * 1.7) ** 2 + ((y / height - 0.5) * 1.35) ** 2));
const value = 0.2126 * r + 0.7152 * g + 0.0722 * b;
luma[i] = value;
const maxc = Math.max(r, g, b);
const minc = Math.min(r, g, b);
const sat = maxc > 0.001 ? (maxc - minc) / maxc : 0;
const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
subject[i] = dist * 0.58 + center * 0.27 + sat * 0.1 + (1 - Math.abs(luma - 0.48)) * 0.05;
const blue = Math.max(0, b - (r + g) * 0.5);
sky[i] = blue * 2.5 + Math.max(0, luma - 0.4) * 0.5 + (1 - ny) * 0.28 - (1 - sat) * 0.08;
if (kind === 'sky') {
// Blue excess, brightness and height above the horizon. A foreground
// building keeps a hard edge, which the component pass protects.
const blue = Math.max(0, b - (r + g) * 0.5);
score[i] =
blue * 2.4 +
Math.max(0, value - 0.35) * 0.55 +
(1 - ny) * 0.42 -
sat * 0.18;
continue;
}
// Background probability from the border histogram, softened so a pixel
// next to a slightly different bin still reads as background.
const bg = border.probability(r, g, b);
const centre =
1 - Math.min(1, Math.sqrt(((x / width - 0.5) * 1.7) ** 2 + ((y / height - 0.5) * 1.35) ** 2));
const chroma = Math.min(
1,
Math.sqrt((r - border.mean[0]) ** 2 + (g - border.mean[1]) ** 2 + (b - border.mean[2]) ** 2) /
1.2,
);
// Skin and clothing usually sit near the centre and differ in chroma from
// a neutral wall; the histogram alone would eat a white shirt.
const subject = (1 - bg) * 0.46 + centre * 0.28 + chroma * 0.17 + sat * 0.09;
score[i] = kind === 'background' ? 1 - subject : subject;
}
}
const raw = kind === 'sky' ? sky : subject;
const sorted = [...raw].sort((a, b) => a - b);
const median = sorted[Math.floor(sorted.length * 0.5)] ?? 0;
const high = sorted[Math.floor(sorted.length * 0.82)] ?? 1;
const threshold = kind === 'sky' ? Math.max(0.35, median) : Math.max(0.36, median + (high - median) * 0.22);
const threshold = otsuThreshold(score);
const mask = new Uint8Array(count);
for (let i = 0; i < count; i++) {
const on = raw[i] >= threshold;
mask[i] = (kind === 'background' ? !on : on) ? 255 : 0;
}
smooth(mask, width, height);
smooth(mask, width, height);
for (let i = 0; i < count; i++) mask[i] = score[i] >= threshold ? 255 : 0;
return { data: encodeBase64(mask), width, height };
keepLargeRegions(mask, width, height);
if (kind !== 'background') fillHoles(mask, width, height);
smooth(mask, width, height);
smooth(mask, width, height);
return mask;
}
function borderColor(data: Uint8ClampedArray, width: number, height: number): [number, number, number] {
let r = 0;
let g = 0;
let b = 0;
interface BorderModel {
/** 4×4×4 RGB histogram of the frame's edge, normalised to the fullest bin. */
probability: (r: number, g: number, b: number) => number;
mean: [number, number, number];
}
function borderModel(
data: Uint8ClampedArray | Uint8Array,
width: number,
height: number,
): BorderModel {
const bins = new Float32Array(64);
let mr = 0;
let mg = 0;
let mb = 0;
let n = 0;
const add = (x: number, y: number) => {
const ring = Math.max(1, Math.round(Math.min(width, height) * 0.03));
const sample = (x: number, y: number) => {
const o = (y * width + x) * 4;
r += data[o];
g += data[o + 1];
b += data[o + 2];
n++;
const r = data[o];
const g = data[o + 1];
const b = data[o + 2];
bins[((r >> 6) << 4) | ((g >> 6) << 2) | (b >> 6)] += 1;
mr += r;
mg += g;
mb += b;
n += 1;
};
for (let y = 0; y < height; y++) {
const edgeRow = y < ring || y >= height - ring;
for (let x = 0; x < width; x++) {
if (edgeRow || x < ring || x >= width - ring) sample(x, y);
}
}
// Blur the histogram across neighbouring bins: real backgrounds are not
// quantised to 64 colours, and a hard lookup would call a wall foreground.
const soft = new Float32Array(64);
for (let r = 0; r < 4; r++) {
for (let g = 0; g < 4; g++) {
for (let b = 0; b < 4; b++) {
const index = (r << 4) | (g << 2) | b;
let total = 0;
for (let dr = -1; dr <= 1; dr++) {
for (let dg = -1; dg <= 1; dg++) {
for (let db = -1; db <= 1; db++) {
const rr = r + dr;
const gg = g + dg;
const bb = b + db;
if (rr < 0 || rr > 3 || gg < 0 || gg > 3 || bb < 0 || bb > 3) continue;
total += bins[(rr << 4) | (gg << 2) | bb] * (dr === 0 && dg === 0 && db === 0 ? 3 : 1);
}
}
}
soft[index] = total;
}
}
}
const max = soft.reduce((best, value) => Math.max(best, value), 0) || 1;
return {
probability: (r, g, b) => {
const value = soft[((Math.min(3, r * 4) | 0) << 4) | ((Math.min(3, g * 4) | 0) << 2) | (Math.min(3, b * 4) | 0)];
return Math.min(1, value / max);
},
mean: n ? [mr / n / 255, mg / n / 255, mb / n / 255] : [0.5, 0.5, 0.5],
};
}
/** Otsu split of the score histogram: adapts to flat and busy frames alike. */
export function otsuThreshold(values: Float32Array): number {
let min = Infinity;
let max = -Infinity;
for (let i = 0; i < values.length; i++) {
min = Math.min(min, values[i]);
max = Math.max(max, values[i]);
}
if (!Number.isFinite(min) || max - min < 1e-4) return max + 1;
const bins = 64;
const hist = new Float64Array(bins);
for (let i = 0; i < values.length; i++) {
const bin = Math.min(bins - 1, Math.floor(((values[i] - min) / (max - min)) * bins));
hist[bin] += 1;
}
const total = values.length;
let sum = 0;
for (let i = 0; i < bins; i++) sum += i * hist[i];
let sumB = 0;
let wB = 0;
let best = 0;
let bestVariance = -1;
for (let i = 0; i < bins; i++) {
wB += hist[i];
if (!wB) continue;
const wF = total - wB;
if (!wF) break;
sumB += i * hist[i];
const mB = sumB / wB;
const mF = (sum - sumB) / wF;
const variance = wB * wF * (mB - mF) ** 2;
if (variance > bestVariance) {
bestVariance = variance;
best = i;
}
}
// Otsu's split lies between bin `best` and the next: taking the upper edge
// puts the threshold above the lower mode rather than inside it.
return min + ((best + 1) / bins) * (max - min);
}
/** Drops specks: keeps every region at least a fifth of the largest one. */
export function keepLargeRegions(mask: Uint8Array, width: number, height: number) {
const labels = new Int32Array(mask.length).fill(-1);
const sizes: number[] = [];
const stack: number[] = [];
for (let start = 0; start < mask.length; start++) {
if (!mask[start] || labels[start] !== -1) continue;
const label = sizes.length;
let size = 0;
stack.push(start);
labels[start] = label;
while (stack.length) {
const index = stack.pop() as number;
size++;
const x = index % width;
const y = (index - x) / width;
const visit = (nx: number, ny: number) => {
if (nx < 0 || ny < 0 || nx >= width || ny >= height) return;
const next = ny * width + nx;
if (!mask[next] || labels[next] !== -1) return;
labels[next] = label;
stack.push(next);
};
visit(x - 1, y);
visit(x + 1, y);
visit(x, y - 1);
visit(x, y + 1);
}
sizes.push(size);
}
const largest = sizes.reduce((best, value) => Math.max(best, value), 0);
const min = largest * 0.2;
for (let i = 0; i < mask.length; i++) {
if (!mask[i]) continue;
const label = labels[i];
if (label >= 0 && sizes[label] < min) mask[i] = 0;
}
}
/** Fills enclosed background so a subject's face and clothes stay covered. */
export function fillHoles(mask: Uint8Array, width: number, height: number) {
const outside = new Uint8Array(mask.length);
const stack: number[] = [];
const push = (x: number, y: number) => {
if (x < 0 || y < 0 || x >= width || y >= height) return;
const index = y * width + x;
if (mask[index] || outside[index]) return;
outside[index] = 1;
stack.push(index);
};
for (let x = 0; x < width; x++) {
add(x, 0);
add(x, height - 1);
push(x, 0);
push(x, height - 1);
}
for (let y = 1; y < height - 1; y++) {
add(0, y);
add(width - 1, y);
for (let y = 0; y < height; y++) {
push(0, y);
push(width - 1, y);
}
while (stack.length) {
const index = stack.pop() as number;
const x = index % width;
const y = (index - x) / width;
push(x - 1, y);
push(x + 1, y);
push(x, y - 1);
push(x, y + 1);
}
for (let i = 0; i < mask.length; i++) {
if (!mask[i] && !outside[i]) mask[i] = 255;
}
return [r / n / 255, g / n / 255, b / n / 255];
}
function smooth(mask: Uint8Array, width: number, height: number) {
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest';
import { convertImageData, convertSrgbEncoded } from './colorSpace';
import { profileFor } from './icc';
describe('output colour spaces', () => {
it('leaves white unchanged in every space', () => {
for (const space of ['srgb', 'p3', 'adobe'] as const) {
const [r, g, b] = convertSrgbEncoded(1, 1, 1, space);
expect(r).toBeCloseTo(1, 3);
expect(g).toBeCloseTo(1, 3);
expect(b).toBeCloseTo(1, 3);
}
});
it('maps sRGB red into the wider P3 and Adobe gamuts', () => {
const p3 = convertSrgbEncoded(1, 0, 0, 'p3');
expect(p3[0]).toBeCloseTo(0.918, 2);
expect(p3[1]).toBeCloseTo(0.202, 1);
const adobe = convertSrgbEncoded(1, 0, 0, 'adobe');
expect(adobe[0]).toBeCloseTo(0.859, 2);
expect(adobe[1]).toBeCloseTo(0, 5);
});
it('preserves alpha while converting a byte buffer', () => {
const data = new Uint8ClampedArray([255, 0, 0, 128]);
convertImageData(data, 'p3');
expect(data[0]).toBeGreaterThan(220);
expect(data[1]).toBeGreaterThan(20);
expect(data[3]).toBe(128);
});
it('writes a profile whose description and curve match the space', () => {
const p3 = profileFor('p3');
expect(String.fromCharCode(...p3.subarray(36, 40))).toBe('acsp');
const adobe = profileFor('adobe');
const view = new DataView(adobe.buffer);
const count = view.getUint32(128, false);
let rtrc = -1;
for (let i = 0; i < count; i++) {
const at = 132 + i * 12;
if (String.fromCharCode(...adobe.subarray(at, at + 4)) === 'rTRC') {
rtrc = view.getUint32(at + 4, false);
}
}
expect(rtrc).toBeGreaterThan(0);
expect(view.getUint32(rtrc + 8, false)).toBe(1);
expect(view.getUint16(rtrc + 12, false)).toBe(563);
});
});
+103
View File
@@ -0,0 +1,103 @@
import type { OutputColorSpace } from './icc';
/**
* Output colour conversion.
*
* The renderer grades in sRGB. For a wider delivery space the encoded pixels
* are decoded to linear sRGB, converted with a 3x3 matrix, then encoded with
* the target transfer curve. The browser's canvas still holds 8 bits per
* channel, so this changes the gamut (and the ICC tag), not the bit depth.
*/
type Matrix = readonly [readonly [number, number, number], readonly [number, number, number], readonly [number, number, number]];
const SRGB_TO_P3: Matrix = [
[0.822592, 0.177508, 0.0],
[0.0331993, 0.966801, 0.0],
[0.0170826, 0.0723974, 0.91052],
];
const SRGB_TO_ADOBE: Matrix = [
[0.7151, 0.2849, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.04117, 0.95883],
];
export const COLOR_SPACE_OPTIONS: { value: OutputColorSpace; label: string }[] = [
{ value: 'srgb', label: 'sRGB' },
{ value: 'p3', label: 'Display P3' },
{ value: 'adobe', label: 'Adobe RGB (1998)' },
];
export function colorSpaceLabel(space: OutputColorSpace) {
return COLOR_SPACE_OPTIONS.find((option) => option.value === space)?.label ?? 'sRGB';
}
export function srgbToLinear(value: number): number {
const v = Math.min(1, Math.max(0, value));
return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
}
export function linearToSrgb(value: number): number {
const v = Math.max(0, value);
return v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;
}
function encode(value: number, space: OutputColorSpace): number {
if (space === 'adobe') return Math.max(0, Math.min(1, value ** (1 / 2.2)));
return Math.max(0, Math.min(1, linearToSrgb(value)));
}
function matrixFor(space: OutputColorSpace): Matrix | null {
if (space === 'p3') return SRGB_TO_P3;
if (space === 'adobe') return SRGB_TO_ADOBE;
return null;
}
/** Convert one sRGB-encoded triple (0-1) to the output space. */
export function convertSrgbEncoded(
r: number,
g: number,
b: number,
space: OutputColorSpace,
): [number, number, number] {
if (space === 'srgb') return [r, g, b];
const matrix = matrixFor(space);
if (!matrix) return [r, g, b];
const lr = srgbToLinear(r);
const lg = srgbToLinear(g);
const lb = srgbToLinear(b);
return [
encode(matrix[0][0] * lr + matrix[0][1] * lg + matrix[0][2] * lb, space),
encode(matrix[1][0] * lr + matrix[1][1] * lg + matrix[1][2] * lb, space),
encode(matrix[2][0] * lr + matrix[2][1] * lg + matrix[2][2] * lb, space),
];
}
/** Convert an RGBA byte buffer in place, preserving alpha. */
export function convertImageData(data: Uint8ClampedArray, space: OutputColorSpace) {
if (space === 'srgb') return data;
for (let i = 0; i < data.length; i += 4) {
const [r, g, b] = convertSrgbEncoded(data[i] / 255, data[i + 1] / 255, data[i + 2] / 255, space);
data[i] = Math.round(r * 255);
data[i + 1] = Math.round(g * 255);
data[i + 2] = Math.round(b * 255);
}
return data;
}
/**
* Convert the renderer's sRGB-encoded float pixels for a 16-bit TIFF. The
* renderer returns gamma-encoded values, so they go through the same decode /
* matrix / encode path as the 8-bit formats.
*/
export function convertFloatPixels(pixels: Float32Array, space: OutputColorSpace) {
if (space === 'srgb') return pixels;
for (let i = 0; i < pixels.length; i += 4) {
const [r, g, b] = convertSrgbEncoded(pixels[i], pixels[i + 1], pixels[i + 2], space);
pixels[i] = r;
pixels[i + 1] = g;
pixels[i + 2] = b;
}
return pixels;
}
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, it } from 'vitest';
import {
analyseGrey,
differenceHash,
greyFromPixels,
groupDuplicates,
hammingDistance,
laplacianVariance,
} from './cull';
function checkerboard(size: number): Uint8Array {
const grey = new Uint8Array(size * size);
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) grey[y * size + x] = (x + y) % 2 === 0 ? 255 : 0;
}
return grey;
}
describe('cull assist', () => {
it('scores a detailed frame above a flat one', () => {
const sharp = laplacianVariance(checkerboard(64), 64, 64);
const flat = laplacianVariance(new Uint8Array(64 * 64).fill(120), 64, 64);
expect(sharp).toBeGreaterThan(flat);
expect(analyseGrey(checkerboard(64), 64, 64).sharpness).toBeGreaterThan(
analyseGrey(new Uint8Array(64 * 64).fill(120), 64, 64).sharpness + 20,
);
});
it('hashes identical frames identically and reframes only a little', () => {
const base = differenceHash(checkerboard(64), 64, 64);
const same = differenceHash(checkerboard(64), 64, 64);
const shifted = differenceHash(checkerboard(32), 32, 32);
expect(base).toBe(same);
expect(hammingDistance(base, shifted)).toBeLessThan(20);
});
it('groups near-duplicates but keeps different frames apart', () => {
const items = [
{ id: 'a', hash: 'ffffffffffffffff' },
{ id: 'b', hash: 'fffffffffffffffe' },
{ id: 'c', hash: '0000000000000000' },
];
const groups = groupDuplicates(items);
expect(groups).toHaveLength(1);
expect(groups[0].map((item) => item.id)).toEqual(['a', 'b']);
});
it('reads luma from RGBA', () => {
const grey = greyFromPixels(new Uint8ClampedArray([255, 255, 255, 255, 0, 0, 0, 255]));
expect(grey[0]).toBe(255);
expect(grey[1]).toBe(0);
});
});
+157
View File
@@ -0,0 +1,157 @@
/**
* Cull assist.
*
* Two measurements decide most of a first pass through an event: is the frame
* actually in focus, and is it a near-duplicate of one already kept. Both are
* computed from the small thumbnail the browser already has, on-device, with
* no model download: a Laplacian variance for focus and a 64-bit difference
* hash for similarity.
*/
export interface CullStats {
/** 0–100, saturating score from the Laplacian variance. */
sharpness: number;
/** Mean luma, 0–255. */
mean: number;
/** Share of pixels at or near clipping, 0–1. */
clippedHigh: number;
clippedLow: number;
/** 64-bit difference hash as hex. */
hash: string;
}
export type SharpnessGrade = 'soft' | 'fair' | 'sharp';
/** RGBA pixels → luma plane (Rec. 709 weights). */
export function greyFromPixels(data: Uint8ClampedArray | Uint8Array): Uint8Array {
const count = Math.floor(data.length / 4);
const grey = new Uint8Array(count);
for (let i = 0; i < count; i++) {
const o = i * 4;
grey[i] = Math.round(0.2126 * data[o] + 0.7152 * data[o + 1] + 0.0722 * data[o + 2]);
}
return grey;
}
/** Variance of the 4-neighbour Laplacian: flat areas score low, edges high. */
export function laplacianVariance(grey: Uint8Array, width: number, height: number): number {
if (width < 3 || height < 3) return 0;
let sum = 0;
let sumSq = 0;
let count = 0;
for (let y = 1; y < height - 1; y++) {
for (let x = 1; x < width - 1; x++) {
const i = y * width + x;
const value = 4 * grey[i] - grey[i - 1] - grey[i + 1] - grey[i - width] - grey[i + width];
sum += value;
sumSq += value * value;
count++;
}
}
if (!count) return 0;
const mean = sum / count;
return Math.max(0, sumSq / count - mean * mean);
}
/** Nearest-neighbour resample, enough for a hash of a thumbnail. */
export function resampleGrey(
grey: Uint8Array,
width: number,
height: number,
cols: number,
rows: number,
): Float32Array {
const out = new Float32Array(cols * rows);
for (let y = 0; y < rows; y++) {
const sy = Math.min(height - 1, Math.floor(((y + 0.5) * height) / rows));
for (let x = 0; x < cols; x++) {
const sx = Math.min(width - 1, Math.floor(((x + 0.5) * width) / cols));
out[y * cols + x] = grey[sy * width + sx];
}
}
return out;
}
/**
* Difference hash: 9×8 samples, one bit per horizontal neighbour comparison.
* Identical framing hashes identically; a small reframe changes only a few bits.
*/
export function differenceHash(grey: Uint8Array, width: number, height: number): string {
const cols = 9;
const rows = 8;
const small = resampleGrey(grey, width, height, cols, rows);
let hex = '';
let bits = 0;
let value = 0;
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols - 1; x++) {
const on = small[y * cols + x] > small[y * cols + x + 1] ? 1 : 0;
value = (value << 1) | on;
bits++;
if (bits === 4) {
hex += value.toString(16);
value = 0;
bits = 0;
}
}
}
return hex;
}
export function analyseGrey(grey: Uint8Array, width: number, height: number): CullStats {
const count = Math.max(1, grey.length);
let total = 0;
let high = 0;
let low = 0;
for (let i = 0; i < grey.length; i++) {
const v = grey[i];
total += v;
if (v >= 250) high++;
if (v <= 4) low++;
}
const variance = laplacianVariance(grey, width, height);
return {
// Empirical saturation: a well-focused frame after downsampling lands
// around 40–70, a soft one under 15. The curve keeps the number readable
// without pretending to be a sharpness unit.
sharpness: Math.round(Math.min(100, (100 * variance) / (variance + 260))),
mean: total / count,
clippedHigh: high / count,
clippedLow: low / count,
hash: differenceHash(grey, width, height),
};
}
export function sharpnessGrade(sharpness: number): SharpnessGrade {
if (sharpness < 22) return 'soft';
if (sharpness < 38) return 'fair';
return 'sharp';
}
export function hammingDistance(a: string, b: string): number {
const length = Math.max(a.length, b.length);
let distance = 0;
for (let i = 0; i < length; i++) {
let x = parseInt(a[i] ?? '0', 16) ^ parseInt(b[i] ?? '0', 16);
while (x) {
distance += x & 1;
x >>= 1;
}
}
return distance;
}
/**
* Groups near-duplicates by hash distance. The first photo of each group is
* the one that hashed first; callers keep that ordering and can treat the rest
* as the alternatives.
*/
export function groupDuplicates<T extends { hash: string }>(items: T[], threshold = 9): T[][] {
const groups: T[][] = [];
for (const item of items) {
const group = groups.find((candidate) => hammingDistance(candidate[0].hash, item.hash) <= threshold);
if (group) group.push(item);
else groups.push([item]);
}
return groups.filter((group) => group.length > 1);
}
+145
View File
@@ -0,0 +1,145 @@
import { describe, expect, it } from 'vitest';
import { dcpRgbCam, parseDcp, rgbCamFromColorMatrix } from './dcp';
/**
* The camera matrix LibRaw reported for one of the repository's D700 raws, and
* the `rgb_cam` it rendered that same file with. The recipe has to land on the
* second from the first: that is the whole point of reading a DCP.
*/
const D700_CAM_XYZ = [
0.8139, -0.2171, -0.0663, -0.8747, 1.6541, 0.2295, -0.1925, 0.2008, 0.8093,
];
const D700_RGB_CAM = [
1.66943598, -0.4847292, -0.18470675, -0.00096075, 1.25268972, -0.25172901, 0.04713935,
-0.30006605, 1.25292671,
];
function maxDiff(a: number[], b: number[]) {
let diff = 0;
for (let i = 0; i < 9; i++) diff = Math.max(diff, Math.abs(a[i] - b[i]));
return diff;
}
interface DcpTag {
tag: number;
type: number;
values: number[] | string;
}
interface PlacedTag {
tag: number;
type: number;
count: number;
bytes: Uint8Array;
offset: number;
}
/** Big-endian TIFF-style tag table behind the 8-byte DCP header. */
function buildDcp(tags: DcpTag[]): Uint8Array {
const blobs = tags.map((entry): Omit<PlacedTag, 'offset'> => {
if (typeof entry.values === 'string') {
const text = new TextEncoder().encode(`${entry.values}\0`);
return { tag: entry.tag, type: entry.type, count: text.length, bytes: text };
}
const buffer = new Uint8Array(entry.values.length * 8);
const view = new DataView(buffer.buffer);
entry.values.forEach((value, index) => {
if (entry.type === 3) {
view.setUint16(index * 2, value, false);
} else {
// SRATIONAL: store with a fixed denominator of 10,000.
view.setInt32(index * 8, Math.round(value * 10000), false);
view.setInt32(index * 8 + 4, 10000, false);
}
});
const size = entry.type === 3 ? entry.values.length * 2 : entry.values.length * 8;
return { tag: entry.tag, type: entry.type, count: entry.values.length, bytes: buffer.subarray(0, size) };
});
let cursor = 8 + 2 + blobs.length * 12 + 4;
const layout: PlacedTag[] = blobs.map((blob) => {
const placed = { ...blob, offset: cursor };
cursor += (blob.bytes.length + 3) & ~3;
return placed;
});
const out = new Uint8Array(cursor);
const view = new DataView(out.buffer);
out.set(new TextEncoder().encode('DCP\0'), 0);
view.setUint32(4, 0x01000000, false);
view.setUint16(8, layout.length, false);
layout.forEach((entry, index) => {
const at = 10 + index * 12;
view.setUint16(at, entry.tag, false);
view.setUint16(at + 2, entry.type, false);
view.setUint32(at + 4, entry.count, false);
if (entry.bytes.length <= 4) {
out.set(entry.bytes, at + 8);
} else {
view.setUint32(at + 8, entry.offset, false);
out.set(entry.bytes, entry.offset);
}
});
return out;
}
describe('rgbCamFromColorMatrix', () => {
it('reproduces LibRaw rgb_cam from the body matrix', () => {
const matrix = rgbCamFromColorMatrix(D700_CAM_XYZ);
expect(matrix).not.toBeNull();
expect(maxDiff(matrix!, D700_RGB_CAM)).toBeLessThan(1e-4);
});
it('keeps white neutral by row-normalising before the inversion', () => {
const matrix = rgbCamFromColorMatrix(D700_CAM_XYZ)!;
for (let row = 0; row < 3; row++) {
const sum = matrix[row * 3] + matrix[row * 3 + 1] + matrix[row * 3 + 2];
expect(sum).toBeCloseTo(1, 5);
}
});
it('accepts rows and rejects a singular matrix', () => {
const rows = [
[0.8139, -0.2171, -0.0663],
[-0.8747, 1.6541, 0.2295],
[-0.1925, 0.2008, 0.8093],
];
expect(maxDiff(rgbCamFromColorMatrix(rows)!, D700_RGB_CAM)).toBeLessThan(1e-4);
expect(rgbCamFromColorMatrix([0, 0, 0, 0, 0, 0, 0, 0, 0])).toBeNull();
expect(rgbCamFromColorMatrix([1, 2, 3, 2, 4, 6, 3, 6, 9])).toBeNull();
});
});
describe('parseDcp', () => {
it('reads the colour matrices and the profile name', () => {
const bytes = buildDcp([
{ tag: 1, type: 2, values: 'Nikon D700' },
{ tag: 3, type: 2, values: 'Camera Standard' },
{ tag: 4, type: 10, values: D700_CAM_XYZ },
{ tag: 5, type: 10, values: [0.7, -0.1, -0.05, -0.8, 1.5, 0.2, -0.15, 0.15, 0.75] },
{ tag: 6, type: 3, values: [21] },
{ tag: 7, type: 3, values: [17] },
]);
const profile = parseDcp(bytes);
expect(profile).not.toBeNull();
expect(profile!.name).toBe('Camera Standard');
expect(profile!.camera).toBe('Nikon D700');
expect(profile!.illuminant1).toBe(21);
expect(profile!.illuminant2).toBe(17);
expect(profile!.colorMatrix1).toHaveLength(9);
expect(maxDiff(dcpRgbCam(profile!)!, D700_RGB_CAM)).toBeLessThan(1e-4);
});
it('falls back to the second illuminant when only that matrix exists', () => {
const bytes = buildDcp([{ tag: 5, type: 10, values: D700_CAM_XYZ }]);
const profile = parseDcp(bytes)!;
expect(profile.colorMatrix1).toBeNull();
expect(maxDiff(dcpRgbCam(profile)!, D700_RGB_CAM)).toBeLessThan(1e-4);
});
it('refuses a file that is not a DCP', () => {
expect(parseDcp(new Uint8Array(64))).toBeNull();
const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
expect(parseDcp(png)).toBeNull();
});
});
+255
View File
@@ -0,0 +1,255 @@
/**
* DCP camera profiles.
*
* A DCP's `ColorMatrix1` is the same thing LibRaw reads out of a raw file's
* maker notes: an XYZ-to-camera matrix. LibRaw turns it into the camera-to-sRGB
* `rgb_cam` matrix it renders with, and this module reproduces that conversion
* exactly, so a profile and the body's own matrix are interchangeable:
*
* rgb_cam = inverse(rowNormalise(ColorMatrix · xyz_rgb))
*
* `xyz_rgb` is the linear sRGB to XYZ matrix (D65). Row normalising before the
* inversion is what keeps a neutral from picking up a cast: it makes each camera
* channel sum to one over RGB, i.e. white maps to white. Validated against
* LibRaw's own `rgb_cam` for a D700 NEF and a 5D Mark II CR2 (max difference
* 2.2e-5 and 2.7e-5, which is float rounding inside LibRaw).
*
* The file format is a TIFF-style IFD behind an 8-byte header (`DCP\0` plus a
* version). Only the colour tags are read; tone curves are not applied here
* because the editor already has its own tone pipeline.
*/
/** Linear sRGB (D65) to XYZ, the matrix dcraw/libraw call `xyz_rgb`. */
const XYZ_RGB: number[] = [
0.412453, 0.35758, 0.180423, 0.212671, 0.71516, 0.072169, 0.019334, 0.119193, 0.950227,
];
type Matrix3 = [number, number, number, number, number, number, number, number, number];
export interface DcpProfile {
/** Human-readable profile name, when the file has one. */
name: string;
/** Camera model the profile was built for. */
camera: string;
/** XYZ-to-camera matrices under the two calibration illuminants. */
colorMatrix1: number[] | null;
colorMatrix2: number[] | null;
/** EXIF light-source codes (21 = D65, 17 = Standard Light A, ...). */
illuminant1: number | null;
illuminant2: number | null;
/** Every tag, for anything a caller needs beyond the colour matrices. */
tags: Map<number, { type: number; count: number; values: number[] | string }>;
}
const DCP_TAGS = {
camera: 0x0001,
name: 0x0003,
colorMatrix1: 0x0004,
colorMatrix2: 0x0005,
illuminant1: 0x0006,
illuminant2: 0x0007,
} as const;
/** Flattens either a flat 9-number list or three rows into one row-major array. */
export function flattenMatrix(value: number[] | number[][]): number[] | null {
if (Array.isArray(value) && Array.isArray(value[0])) {
const rows = value as number[][];
if (rows.length < 3) return null;
const flat = rows.slice(0, 3).flatMap((row) => row.slice(0, 3));
return flat.length === 9 && flat.every(Number.isFinite) ? flat : null;
}
const flat = (value as number[]).slice(0, 9);
return flat.length === 9 && flat.every(Number.isFinite) ? flat : null;
}
function multiply(a: number[], b: number[]): Matrix3 {
const out = new Array<number>(9).fill(0);
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 3; col++) {
let sum = 0;
for (let k = 0; k < 3; k++) sum += a[row * 3 + k] * b[k * 3 + col];
out[row * 3 + col] = sum;
}
}
return out as Matrix3;
}
function inverse(m: number[]): Matrix3 | null {
const [a, b, c, d, e, f, g, h, i] = m;
const A = e * i - f * h;
const B = -(d * i - f * g);
const C = d * h - e * g;
const det = a * A + b * B + c * C;
if (!Number.isFinite(det) || Math.abs(det) < 1e-12) return null;
return [
A / det,
(c * h - b * i) / det,
(b * f - c * e) / det,
B / det,
(a * i - c * g) / det,
(c * d - a * f) / det,
C / det,
(b * g - a * h) / det,
(a * e - b * d) / det,
];
}
function rowNormalise(m: number[]): number[] {
const out = [...m];
for (let row = 0; row < 3; row++) {
const sum = out[row * 3] + out[row * 3 + 1] + out[row * 3 + 2];
if (!Number.isFinite(sum) || Math.abs(sum) < 1e-9) continue;
for (let col = 0; col < 3; col++) out[row * 3 + col] /= sum;
}
return out;
}
/**
* Camera-to-sRGB matrix from an XYZ-to-camera `ColorMatrix`, the same recipe
* LibRaw uses for `rgb_cam`. Returns null for a singular matrix, which would
* make the camera profile unusable rather than merely odd.
*/
export function rgbCamFromColorMatrix(camXyz: number[] | number[][]): number[] | null {
const matrix = flattenMatrix(camXyz);
if (!matrix) return null;
const camRgb = multiply(matrix, XYZ_RGB);
return inverse(rowNormalise(camRgb));
}
/** The matrix a DCP should be rendered with, preferring the first illuminant. */
export function dcpRgbCam(profile: DcpProfile): number[] | null {
const source = profile.colorMatrix1 ?? profile.colorMatrix2;
if (!source) return null;
return rgbCamFromColorMatrix(source);
}
function readValues(
view: DataView,
type: number,
count: number,
offset: number,
): number[] {
const out: number[] = [];
const at = offset;
for (let i = 0; i < count; i++) {
switch (type) {
case 1:
case 7:
out.push(view.getUint8(at + i));
break;
case 3:
out.push(view.getUint16(at + i * 2, false));
break;
case 4:
case 13:
out.push(view.getUint32(at + i * 4, false));
break;
case 5:
out.push(view.getUint32(at + i * 8, false) / Math.max(1, view.getUint32(at + i * 8 + 4, false)));
break;
case 10:
out.push(view.getInt32(at + i * 8, false) / Math.max(1, Math.abs(view.getInt32(at + i * 8 + 4, false))));
break;
case 11:
out.push(view.getFloat32(at + i * 4, false));
break;
case 12:
out.push(view.getFloat64(at + i * 8, false));
break;
default:
break;
}
}
return out;
}
const TYPE_SIZE: Record<number, number> = {
1: 1,
2: 1,
3: 2,
4: 4,
5: 8,
6: 1,
7: 1,
8: 2,
9: 4,
10: 8,
11: 4,
12: 8,
13: 4,
};
function readAscii(view: DataView, count: number, offset: number): string {
let text = '';
for (let i = 0; i < count; i++) {
const code = view.getUint8(offset + i);
if (code === 0) break;
text += String.fromCharCode(code);
}
return text.trim();
}
function ifdFits(view: DataView, start: number): boolean {
if (start + 2 > view.byteLength) return false;
const count = view.getUint16(start, false);
if (count < 1 || count > 256) return false;
return start + 2 + count * 12 + 4 <= view.byteLength;
}
/**
* Parses the colour tags of a DCP file. Returns null when the header or the tag
* table does not look like a DCP at all, so a renamed JPEG cannot be installed
* as a profile by accident.
*/
export function parseDcp(bytes: Uint8Array): DcpProfile | null {
if (bytes.length < 16) return null;
if (String.fromCharCode(bytes[0], bytes[1], bytes[2], bytes[3]) !== 'DCP\0') return null;
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
// The IFD follows the 8-byte header; a couple of writers place it at 4. Probe
// both and take the one that is a plausible tag table.
const start = [8, 4].find((candidate) => ifdFits(view, candidate));
if (start === undefined) return null;
const count = view.getUint16(start, false);
const tags: DcpProfile['tags'] = new Map();
for (let index = 0; index < count; index++) {
const at = start + 2 + index * 12;
const tag = view.getUint16(at, false);
const type = view.getUint16(at + 2, false);
const size = view.getUint32(at + 4, false);
const unit = TYPE_SIZE[type];
if (!unit || size > 1_000_000) continue;
const total = size * unit;
const offset = total <= 4 ? at + 8 : view.getUint32(at + 8, false);
if (offset < 0 || offset + total > bytes.length) continue;
if (type === 2) {
tags.set(tag, { type, count: size, values: readAscii(view, size, offset) });
} else {
tags.set(tag, { type, count: size, values: readValues(view, type, size, offset) });
}
}
const matrix = (tag: number) => {
const entry = tags.get(tag);
return entry && Array.isArray(entry.values) ? flattenMatrix(entry.values) : null;
};
const text = (tag: number) => {
const entry = tags.get(tag);
return entry && typeof entry.values === 'string' ? entry.values : '';
};
const number = (tag: number) => {
const entry = tags.get(tag);
return entry && Array.isArray(entry.values) && entry.values.length ? entry.values[0] : null;
};
const camera = text(DCP_TAGS.camera);
return {
name: text(DCP_TAGS.name) || camera || 'Camera profile',
camera,
colorMatrix1: matrix(DCP_TAGS.colorMatrix1),
colorMatrix2: matrix(DCP_TAGS.colorMatrix2),
illuminant1: number(DCP_TAGS.illuminant1),
illuminant2: number(DCP_TAGS.illuminant2),
tags,
};
}
+3 -2
View File
@@ -30,7 +30,7 @@ export const EDIT_SECTIONS: EditSection[] = [
{
id: 'color',
label: 'Color',
hint: 'Curves, HSL, grading, black & white',
hint: 'Curves, HSL, grading, redscale, black & white',
defaultOn: true,
},
{
@@ -81,6 +81,7 @@ const GROUPS: Record<EditSectionId, (keyof Edits)[]> = {
light: [
'temp',
'tint',
'kelvin',
'exposure',
'recovery',
'contrast',
@@ -94,7 +95,7 @@ const GROUPS: Record<EditSectionId, (keyof Edits)[]> = {
'vibrance',
'saturation',
],
color: ['bw', 'bwFilter', 'bwFilterAmount', 'curve', 'parametric', 'hsl', 'grading'],
color: ['bw', 'bwFilter', 'bwFilterAmount', 'curve', 'levels', 'parametric', 'hsl', 'grading', 'redscale'],
detail: ['sharpen', 'noise', 'defringe'],
effects: ['vignette', 'grain', 'proof'],
geometry: ['geometry'],
+3 -1
View File
@@ -38,7 +38,9 @@ function versionOf(edits: Edits): number {
}
function keyOf(photo: PhotoRecord): string {
return `${photo.id}|${versionOf(photo.edits)}`;
// previewVersion changes when a RAW is re-decoded, so the old tile cannot be
// served from the cache even though the edit object is unchanged.
return `${photo.id}|${versionOf(photo.edits)}|${photo.previewVersion ?? 0}`;
}
let renderer: Renderer | null = null;
+70 -3
View File
@@ -96,11 +96,27 @@ export function thumbTransform(photo: PhotoRecord, boxAspect = 4 / 3): string {
/** The shader carries a fixed spot array; more than this would silently drop. */
export const MAX_HEAL_SPOTS = 24;
/** Four masks are packed into one RGBA texture. */
export const MAX_LOCAL_LAYERS = 4;
/** Eight masks are packed into two RGBA textures. */
export const MAX_LOCAL_LAYERS = 8;
export function defaultLocalAdjust(): LocalLayer['adjust'] {
return { exposure: 0, contrast: 0, highlights: 0, shadows: 0, temp: 0, tint: 0, saturation: 0 };
return {
exposure: 0,
contrast: 0,
highlights: 0,
shadows: 0,
whites: 0,
blacks: 0,
temp: 0,
tint: 0,
saturation: 0,
vibrance: 0,
hue: 0,
texture: 0,
clarity: 0,
dehaze: 0,
sharpen: 0,
};
}
export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLayer {
@@ -108,6 +124,7 @@ export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLaye
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
name: `Local ${index + 1}`,
kind,
mode: 'add',
inverted: false,
feather: 50,
brush: { strokes: [] },
@@ -146,6 +163,7 @@ export function defaultEdits(): Edits {
return {
temp: 0,
tint: 0,
kelvin: null,
exposure: 0,
recovery: 0,
contrast: 0,
@@ -158,6 +176,7 @@ export function defaultEdits(): Edits {
dehaze: 0,
vibrance: 0,
saturation: 0,
redscale: 0,
bw: false,
bwFilter: 'none',
bwFilterAmount: 100,
@@ -167,6 +186,7 @@ export function defaultEdits(): Edits {
green: identityCurve(),
blue: identityCurve(),
},
levels: { black: 0, white: 100, gamma: 1 },
parametric: { highlights: 0, lights: 0, darks: 0, blacks: 0 },
hsl: {
hue: HUE_BANDS.map(() => 0),
@@ -180,6 +200,7 @@ export function defaultEdits(): Edits {
},
sharpen: { amount: 0, radius: 1, detail: 25, mask: 0, lensSoftness: 0 },
proof: { enabled: false, paper: 'matte', blackPoint: 2, gamut: false },
cameraProfile: null,
noise: { luminance: 0, detail: 50, chroma: 0, chromaDetail: 50 },
aiDenoise: { amount: 100, key: null, model: 'guided' },
defringe: { purple: 0, green: 0 },
@@ -264,6 +285,8 @@ function localLayers(input: unknown): LocalLayer[] {
id: typeof layer.id === 'string' && layer.id ? layer.id : `local-${out.length}`,
name: typeof layer.name === 'string' && layer.name.trim() ? layer.name.slice(0, 40) : `Local ${out.length + 1}`,
kind,
mode:
layer.mode === 'subtract' || layer.mode === 'intersect' ? layer.mode : 'add',
inverted: !!layer.inverted,
feather: num(layer.feather, 50, 0, 100),
brush: { strokes: localStrokes(layer.brush?.strokes) },
@@ -293,9 +316,17 @@ function localLayers(input: unknown): LocalLayer[] {
contrast: num(adjust.contrast, 0, -100, 100),
highlights: num(adjust.highlights, 0, -100, 100),
shadows: num(adjust.shadows, 0, -100, 100),
whites: num(adjust.whites, 0, -100, 100),
blacks: num(adjust.blacks, 0, -100, 100),
temp: num(adjust.temp, 0, -100, 100),
tint: num(adjust.tint, 0, -100, 100),
saturation: num(adjust.saturation, 0, -100, 100),
vibrance: num(adjust.vibrance, 0, -100, 100),
hue: num(adjust.hue, 180, -180, 180),
texture: num(adjust.texture, 0, -100, 100),
clarity: num(adjust.clarity, 0, -100, 100),
dehaze: num(adjust.dehaze, 0, -100, 100),
sharpen: num(adjust.sharpen, 0, -100, 100),
},
});
}
@@ -338,10 +369,28 @@ function lensProfile(input: unknown): LensProfile | undefined {
};
}
/**
* Keeps a stored camera profile usable: a profile with a missing or non-finite
* matrix would black out the photo, so it is dropped instead.
*/
export function normalizeCameraProfile(value: unknown): Edits['cameraProfile'] {
if (!value || typeof value !== 'object') return null;
const raw = value as { name?: unknown; matrix?: unknown };
if (!Array.isArray(raw.matrix)) return null;
const matrix = raw.matrix.slice(0, 9).map(Number);
if (matrix.length !== 9 || !matrix.every(Number.isFinite)) return null;
const name =
typeof raw.name === 'string' && raw.name.trim()
? raw.name.trim().slice(0, 80)
: 'Camera profile';
return { name, matrix };
}
export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits {
const d = defaultEdits();
if (!input) return d;
const curve = (input.curve ?? {}) as Partial<Edits['curve']>;
const levels = (input.levels ?? {}) as Partial<Edits['levels']>;
const parametric = (input.parametric ?? {}) as Partial<Edits['parametric']>;
const grading = (input.grading ?? {}) as Partial<Edits['grading']>;
const sharpen = (input.sharpen ?? {}) as Partial<Edits['sharpen']>;
@@ -355,6 +404,7 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
return {
...d,
...input,
cameraProfile: normalizeCameraProfile(input.cameraProfile),
aiDenoise: {
amount: num(aiDenoise.amount, d.aiDenoise.amount, 0, 100),
key: typeof aiDenoise.key === 'string' && aiDenoise.key ? aiDenoise.key : null,
@@ -362,6 +412,10 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
},
temp: num(input.temp, 0, -100, 100),
tint: num(input.tint, 0, -100, 100),
kelvin:
typeof input.kelvin === 'number' && Number.isFinite(input.kelvin)
? clamp(input.kelvin, 1500, 15000)
: null,
exposure: num(input.exposure, 0, -5, 5),
recovery: num(input.recovery, 0, 0, 100),
contrast: num(input.contrast, 0, -100, 100),
@@ -374,6 +428,7 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
dehaze: num(input.dehaze, 0, -100, 100),
vibrance: num(input.vibrance, 0, -100, 100),
saturation: num(input.saturation, 0, -100, 100),
redscale: num(input.redscale, 0, 0, 100),
bw: !!input.bw,
bwFilter: BW_FILTERS.some((f) => f.id === input.bwFilter) ? (input.bwFilter as BwFilter) : 'none',
bwFilterAmount: num(input.bwFilterAmount, d.bwFilterAmount, 0, 100),
@@ -383,6 +438,14 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
green: sanitizeCurve(curve.green),
blue: sanitizeCurve(curve.blue),
},
levels: {
black: num(levels.black, 0, 0, 45),
white: Math.max(
num(levels.black, 0, 0, 45) + 5,
num(levels.white, 100, 55, 100),
),
gamma: num(levels.gamma, 1, 0.3, 3),
},
parametric: {
highlights: num(parametric.highlights, 0, -100, 100),
lights: num(parametric.lights, 0, -100, 100),
@@ -489,6 +552,10 @@ export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): Ph
decode: input.decode,
previewUrl: input.previewUrl,
thumbUrl: input.thumbUrl,
previewVersion:
typeof input.previewVersion === 'number' && Number.isFinite(input.previewVersion)
? input.previewVersion
: undefined,
proofAt: typeof input.proofAt === 'number' && Number.isFinite(input.proofAt) ? input.proofAt : undefined,
name: input.name ?? 'Untitled',
width: input.width ?? 0,
+44 -14
View File
@@ -1,11 +1,12 @@
import type { Edits, PhotoRecord } from '../types';
import { getBitmap } from './images';
import { get16BitSource, getBitmap } from './images';
import { normalizeEdits } from './edits';
import { buildLensCorrection } from './lensfun';
import { outputSize, Renderer } from '../gl/renderer';
import { getDenoisedBitmap } from './images';
import { createZipBlob, zipFileName } from './zip';
import { srgbProfile } from './icc';
import { profileFor, type OutputColorSpace } from './icc';
import { convertFloatPixels, convertImageData } from './colorSpace';
import { encodeTiff16 } from './tiff';
export type ExportFormat = 'jpeg' | 'png' | 'webp' | 'tiff16';
@@ -16,6 +17,8 @@ export type WatermarkPosition = 'br' | 'bl' | 'tr' | 'tl' | 'center';
export interface ExportOptions {
format: ExportFormat;
quality: number;
/** Delivery colour space; affects pixels and the embedded ICC profile. */
colorSpace: OutputColorSpace;
resize: ResizeMode;
longEdge: number;
percent: number;
@@ -46,6 +49,7 @@ export interface ExportRecipe {
export const DEFAULT_EXPORT: ExportOptions = {
format: 'jpeg',
quality: 92,
colorSpace: 'srgb',
resize: 'none',
longEdge: 3000,
percent: 100,
@@ -114,7 +118,12 @@ function targetSize(photo: PhotoRecord, edits: Edits, bitmap: ImageBitmap, opts:
};
}
export async function renderPhotoBlob(photo: PhotoRecord, opts: ExportOptions): Promise<Blob> {
export async function renderPhotoBlob(
photo: PhotoRecord,
opts: ExportOptions,
/** Reuse one WebGL renderer across a batch instead of one context per photo. */
sharedRenderer?: Renderer,
): Promise<Blob> {
const bitmap = await getBitmap(photo);
const base = normalizeEdits(photo.edits);
const edits = opts.outputSharpen > 0
@@ -125,12 +134,17 @@ export async function renderPhotoBlob(photo: PhotoRecord, opts: ExportOptions):
// Let the shader use its Catmull-Rom path when the crop is being enlarged,
// so an intentional 150–200% export does not turn into a bilinear blur.
const upscale = w > native.w * 1.05 || h > native.h * 1.05;
const canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
const renderer = new Renderer(canvas);
const canvas = sharedRenderer ? sharedRenderer.canvas : document.createElement('canvas');
if (!sharedRenderer) {
canvas.width = 1;
canvas.height = 1;
}
const renderer = sharedRenderer ?? new Renderer(canvas);
try {
renderer.setImage(bitmap);
// The sidecar is what makes a 16-bit TIFF export genuinely 16-bit rather
// than a 65,536-code container around 256 real levels.
const hdr = await get16BitSource(photo).catch(() => null);
renderer.setImage(bitmap, hdr);
// Forgetting this is how denoise silently goes missing from exports: the
// preview and the file would be graded from different pixels.
if (edits.aiDenoise.key) {
@@ -141,26 +155,28 @@ export async function renderPhotoBlob(photo: PhotoRecord, opts: ExportOptions):
? await buildLensCorrection(edits.lens, { width: bitmap.width, height: bitmap.height, meta: photo.meta })
: null;
const space: OutputColorSpace = opts.colorSpace ?? 'srgb';
if (opts.format === 'tiff16') {
if (opts.watermark.enabled && opts.watermark.text.trim()) {
throw new Error('Watermarking is not available for 16-bit TIFF exports');
}
const pixels = renderer.render(edits, { width: w, height: h, lens, upscale, floatOut: true });
let pixels = renderer.render(edits, { width: w, height: h, lens, upscale, floatOut: true });
if (!pixels) throw new Error('Could not read the 16-bit render');
pixels = convertFloatPixels(pixels, space);
return encodeTiff16({
width: w,
height: h,
pixels,
icc: opts.embedProfile ? srgbProfile() : null,
icc: opts.embedProfile ? profileFor(space) : null,
});
}
renderer.render(edits, { width: w, height: h, lens, upscale });
renderer.finishGpu();
let output = canvas;
let output = space === 'srgb' ? canvas : convertCanvas(canvas, space);
if (opts.watermark.enabled && opts.watermark.text.trim()) {
output = paintWatermark(canvas, photo, opts);
output = paintWatermark(output, photo, opts);
}
const mime = MIME[opts.format];
let blob = await new Promise<Blob | null>((resolve) =>
@@ -171,15 +187,29 @@ export async function renderPhotoBlob(photo: PhotoRecord, opts: ExportOptions):
blob = await embedJpegMetadata(
blob,
opts.metadata ? buildXmp(photo) : '',
opts.embedProfile ? srgbProfile() : null,
opts.embedProfile ? profileFor(space) : null,
);
}
return blob;
} finally {
renderer.dispose();
// A caller-owned renderer outlives the photo, so it is theirs to dispose.
if (!sharedRenderer) renderer.dispose();
}
}
function convertCanvas(source: HTMLCanvasElement, space: OutputColorSpace) {
const canvas = document.createElement('canvas');
canvas.width = source.width;
canvas.height = source.height;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) return source;
ctx.drawImage(source, 0, 0);
const image = ctx.getImageData(0, 0, canvas.width, canvas.height);
convertImageData(image.data, space);
ctx.putImageData(image, 0, 0);
return canvas;
}
function paintWatermark(source: HTMLCanvasElement, photo: PhotoRecord, opts: ExportOptions) {
const canvas = document.createElement('canvas');
canvas.width = source.width;
+84 -18
View File
@@ -1,13 +1,54 @@
/**
* A small, self-contained ICC v2 sRGB display profile.
* Self-contained ICC v2 display profiles, generated rather than shipped as
* binary assets.
*
* It is generated rather than shipped as a binary so the export pipeline can
* tag sRGB files without adding a third-party profile asset. The matrix and
* gamma describe the standard sRGB primaries; the browser already converted
* the working pixels into sRGB when it decoded the source image.
* sRGB, Display P3 and Adobe RGB (1998) are all RGB display spaces, so one
* builder covers them: only the primaries, transfer curve and description
* change. The primaries are the D50-adapted values an ICC profile expects; the
* pixels themselves are converted by `colorSpace.ts` before encoding.
*/
let cached: Uint8Array | null = null;
export type OutputColorSpace = 'srgb' | 'p3' | 'adobe';
interface SpaceDefinition {
description: string;
/** D50-adapted XYZ of the red, green and blue primaries. */
primaries: [[number, number, number], [number, number, number], [number, number, number]];
/** sRGB piecewise curve, or a straight display gamma. */
transfer: 'srgb' | number;
}
const SPACES: Record<OutputColorSpace, SpaceDefinition> = {
srgb: {
description: 'sRGB IEC61966-2.1 (Luminary)',
primaries: [
[0.4360747, 0.2225045, 0.0139322],
[0.3850649, 0.7168786, 0.0971045],
[0.1430804, 0.0606169, 0.7141733],
],
transfer: 'srgb',
},
p3: {
description: 'Display P3 (Luminary)',
primaries: [
[0.5151188, 0.2411894, -0.0010657],
[0.2919771, 0.6922441, 0.0418837],
[0.1571035, 0.0665752, 0.7845088],
],
transfer: 'srgb',
},
adobe: {
description: 'Adobe RGB (1998) (Luminary)',
primaries: [
[0.6097559, 0.3111242, 0.0194811],
[0.2052401, 0.625656, 0.0608899],
[0.1493582, 0.0632197, 0.7446702],
],
transfer: 2.2,
},
};
const cache = new Map<OutputColorSpace, Uint8Array>();
function be32(out: DataView, offset: number, value: number) {
out.setUint32(offset, value >>> 0, false);
@@ -39,7 +80,7 @@ function xyzTag(x: number, y: number, z: number) {
return data;
}
function curveTag() {
function srgbCurveTag() {
// ICC v2 curveType with the piecewise sRGB transfer function sampled at
// 1024 points. A gamma-2.2 shortcut is close, but this is exact to the
// standard (within 16-bit quantisation) and still readable by old CMMs.
@@ -59,6 +100,16 @@ function curveTag() {
return data;
}
function gammaCurveTag(gamma: number) {
// A one-entry curveType stores the gamma as u8Fixed8; 2.2 -> 563.
const data = new Uint8Array(14);
const view = new DataView(data.buffer);
data.set(ascii('curv'), 0);
be32(view, 8, 1);
be16(view, 12, Math.round(gamma * 256));
return data;
}
function descTag(text: string) {
const value = new TextEncoder().encode(text);
const size = pad4(12 + value.length + 1 + 4 + 4);
@@ -83,20 +134,24 @@ function textTag(text: string) {
return data;
}
export function srgbProfile(): Uint8Array {
if (cached) return cached;
function buildProfile(space: OutputColorSpace): Uint8Array {
const definition = SPACES[space];
const curve =
definition.transfer === 'srgb' ? srgbCurveTag() : gammaCurveTag(definition.transfer);
const [r, g, b] = definition.primaries;
// sRGB primaries adapted to the D50 profile connection space.
const tags: { sig: string; data: Uint8Array }[] = [
{ sig: 'desc', data: descTag('sRGB IEC61966-2.1 (Luminary)') },
{ sig: 'desc', data: descTag(definition.description) },
{ sig: 'cprt', data: textTag('No copyright, use freely') },
{ sig: 'wtpt', data: xyzTag(0.9642, 1.0, 0.8249) },
{ sig: 'rXYZ', data: xyzTag(0.4360747, 0.2225045, 0.0139322) },
{ sig: 'gXYZ', data: xyzTag(0.3850649, 0.7168786, 0.0971045) },
{ sig: 'bXYZ', data: xyzTag(0.1430804, 0.0606169, 0.7141733) },
{ sig: 'rTRC', data: curveTag() },
{ sig: 'gTRC', data: curveTag() },
{ sig: 'bTRC', data: curveTag() },
{ sig: 'rXYZ', data: xyzTag(r[0], r[1], r[2]) },
{ sig: 'gXYZ', data: xyzTag(g[0], g[1], g[2]) },
{ sig: 'bXYZ', data: xyzTag(b[0], b[1], b[2]) },
// All three channels share the transfer function; the writer copies the
// bytes at each tag's own offset.
{ sig: 'rTRC', data: curve },
{ sig: 'gTRC', data: curve },
{ sig: 'bTRC', data: curve },
];
const tableSize = 4 + tags.length * 12;
@@ -147,6 +202,17 @@ export function srgbProfile(): Uint8Array {
data.set(tag.data, tag.at);
});
cached = data;
return data;
}
export function profileFor(space: OutputColorSpace): Uint8Array {
const hit = cache.get(space);
if (hit) return hit;
const profile = buildProfile(space);
cache.set(space, profile);
return profile;
}
export function srgbProfile(): Uint8Array {
return profileFor('srgb');
}
+49
View File
@@ -1,5 +1,6 @@
import type { PhotoRecord } from '../types';
import { getAsset, putAsset } from './db';
import { parsePreview16, type Preview16 } from './preview16';
const CACHE_LIMIT = 6;
const cache = new Map<string, ImageBitmap>();
@@ -93,11 +94,59 @@ export function evictBitmap(photoId: string) {
bmp.close();
}
const hdrCache = new Map<string, Preview16 | null>();
/** Version stamp from the preview URL, so a reprocess invalidates the sidecar too. */
function preview16Url(photo: PhotoRecord): string {
const base = `/api/photos/${encodeURIComponent(photo.id)}/preview16`;
const query = (photo.previewUrl ?? '').split('?')[1];
return query ? `${base}?${query}` : base;
}
/**
* The 16-bit samples behind a raw proxy, or null when there are none.
*
* Null is normal, not an error: photos imported before the sidecar existed,
* non-raw files and oversized fetches all end up grading the JPEG. Only a 404
* is remembered, so a dropped connection is retried on the next look.
*/
export async function get16BitSource(photo: PhotoRecord): Promise<Preview16 | null> {
if (!photo.raw) return null;
const hit = hdrCache.get(photo.id);
if (hit !== undefined) return hit;
let parsed: Preview16 | null = null;
let missing = false;
try {
const res = await fetch(preview16Url(photo), { credentials: 'same-origin' });
if (!res.ok) {
missing = true;
} else {
parsed = await parsePreview16(await res.arrayBuffer());
missing = parsed === null;
}
} catch {
return null;
}
if (parsed) {
hdrCache.set(photo.id, parsed);
// Each sidecar is up to ~100 MB of typed array, so only the last two stay.
while (hdrCache.size > 2) {
const first = hdrCache.keys().next();
if (first.done) break;
hdrCache.delete(first.value);
}
} else if (missing) {
hdrCache.set(photo.id, null);
}
return parsed;
}
export function clearBitmapCache() {
for (const bmp of cache.values()) bmp.close();
cache.clear();
for (const bmp of denoisedCache.values()) bmp.close();
denoisedCache.clear();
hdrCache.clear();
}
const denoisedCache = new Map<string, ImageBitmap>();
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, it } from 'vitest';
import { buildCurveLUT } from '../gl/renderer';
import { defaultEdits } from './edits';
describe('input levels', () => {
it('is an identity LUT by default', () => {
const lut = buildCurveLUT(defaultEdits());
for (const i of [0, 1, 32, 128, 255]) {
expect(lut[i * 4]).toBeCloseTo(i, 0);
}
});
it('maps the chosen black and white points to the ends of the range', () => {
const edits = defaultEdits();
edits.levels = { black: 20, white: 80, gamma: 1 };
const lut = buildCurveLUT(edits);
expect(lut[Math.round(0.2 * 255) * 4]).toBe(0);
expect(lut[Math.round(0.8 * 255) * 4]).toBe(255);
expect(lut[128 * 4]).toBeGreaterThan(125);
expect(lut[128 * 4]).toBeLessThan(131);
});
it('applies gamma before the curve', () => {
const edits = defaultEdits();
edits.levels = { black: 0, white: 100, gamma: 2 };
const lut = buildCurveLUT(edits);
// sqrt(0.25) = 0.5
expect(lut[64 * 4]).toBeGreaterThan(125);
expect(lut[64 * 4]).toBeLessThan(131);
});
});
+54
View File
@@ -0,0 +1,54 @@
import { describe, expect, it } from 'vitest';
import { applyFilmVariant, FILM_PRESETS, PRESETS, PRESET_CATEGORIES } from './presets';
import { normalizeEdits } from './edits';
describe('preset library', () => {
it('ships an extensive, uniquely identified catalogue', () => {
expect(FILM_PRESETS.length).toBeGreaterThanOrEqual(120);
expect(PRESETS.length).toBeGreaterThanOrEqual(160);
const ids = PRESETS.map((preset) => preset.id);
expect(new Set(ids).size).toBe(ids.length);
});
it('documents every film stock and files it under a real category', () => {
const categories = PRESET_CATEGORIES.map((category) => category.id);
for (const preset of FILM_PRESETS) {
expect(preset.film, preset.id).toBeDefined();
expect(preset.film?.speed, preset.id).toBeGreaterThan(0);
expect(preset.film?.process, preset.id).toBeTruthy();
expect(preset.description, preset.id).toBeTruthy();
expect(categories, preset.id).toContain(preset.category);
}
});
it('keeps every look inside the edits schema', () => {
for (const preset of PRESETS) {
const normalized = normalizeEdits(preset.edits);
for (const key of Object.keys(preset.edits) as (keyof typeof preset.edits)[]) {
expect(normalized[key], `${preset.id}.${String(key)}`).toEqual(preset.edits[key]);
}
}
});
it('ships a research-based redscale set', () => {
const redscale = PRESETS.filter((preset) => preset.category === 'Redscale');
expect(redscale.length).toBeGreaterThanOrEqual(8);
for (const preset of redscale) {
expect(preset.film, preset.id).toBeDefined();
expect(preset.description?.toLowerCase(), preset.id).toMatch(/redscal|revers|backwards|through the base/);
// White balance alone cannot produce the look; the film-response control
// has to carry it.
expect(preset.edits.redscale, preset.id).toBeGreaterThanOrEqual(60);
}
// Clear-base slide film is the one redscale case that needs no compensation.
expect(redscale.some((preset) => preset.film?.process === 'E-6')).toBe(true);
});
it('derives push/pull variants for film stocks only', () => {
const stock = FILM_PRESETS[0];
expect(applyFilmVariant(stock, 'push').id).toBe(`${stock.id}::push`);
const look = PRESETS.find((preset) => !preset.film);
expect(look).toBeDefined();
expect(applyFilmVariant(look!, 'push')).toBe(look);
});
});
+1869 -53
View File
File diff suppressed because it is too large Load Diff
+191
View File
@@ -0,0 +1,191 @@
import { describe, expect, it } from 'vitest';
import { halfBits, parsePreview16 } from './preview16';
/**
* A stored-block zlib stream: valid deflate without a dependency, which is all
* the parser needs to prove it reads a real PNG byte stream rather than a mock.
*/
function zlibStored(data: Uint8Array): Uint8Array {
const blocks = Math.max(1, Math.ceil(data.length / 65535));
const out = new Uint8Array(2 + data.length + blocks * 5 + 4);
out[0] = 0x78;
out[1] = 0x01;
let at = 2;
for (let b = 0; b < blocks; b++) {
const start = b * 65535;
const len = Math.min(65535, data.length - start);
out[at++] = b === blocks - 1 ? 1 : 0;
out[at++] = len & 0xff;
out[at++] = (len >> 8) & 0xff;
out[at++] = ~len & 0xff;
out[at++] = (~len >> 8) & 0xff;
out.set(data.subarray(start, start + len), at);
at += len;
}
let a = 1;
let c = 0;
for (const byte of data) {
a = (a + byte) % 65521;
c = (c + a) % 65521;
}
out[at++] = (c >> 8) & 0xff;
out[at++] = c & 0xff;
out[at++] = (a >> 8) & 0xff;
out[at++] = a & 0xff;
return out;
}
const CRC_TABLE = (() => {
const table = new Int32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[n] = c;
}
return table;
})();
function crc32(bytes: Uint8Array): number {
let c = 0xffffffff;
for (const byte of bytes) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
function concat(parts: Uint8Array[]): Uint8Array {
const total = parts.reduce((n, p) => n + p.length, 0);
const out = new Uint8Array(total);
let at = 0;
for (const part of parts) {
out.set(part, at);
at += part.length;
}
return out;
}
/** Mirror of the server encoder: 16-bit RGB, Sub-filtered rows. */
function encodePng16(
samples: number[][],
width: number,
height: number,
text?: string,
): ArrayBuffer {
const stride = width * 6;
const raw = new Uint8Array((stride + 1) * height);
const row = new Uint8Array(stride);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const [r, g, b] = samples[y * width + x];
row[x * 6] = (r >> 8) & 0xff;
row[x * 6 + 1] = r & 0xff;
row[x * 6 + 2] = (g >> 8) & 0xff;
row[x * 6 + 3] = g & 0xff;
row[x * 6 + 4] = (b >> 8) & 0xff;
row[x * 6 + 5] = b & 0xff;
}
const base = y * (stride + 1);
raw[base] = 1; // Sub
for (let i = 0; i < stride; i++) raw[base + 1 + i] = (row[i] - (i >= 6 ? row[i - 6] : 0)) & 0xff;
}
const ihdr = new Uint8Array(13);
ihdr[0] = (width >>> 24) & 0xff;
ihdr[1] = (width >>> 16) & 0xff;
ihdr[2] = (width >>> 8) & 0xff;
ihdr[3] = width & 0xff;
ihdr[4] = (height >>> 24) & 0xff;
ihdr[5] = (height >>> 16) & 0xff;
ihdr[6] = (height >>> 8) & 0xff;
ihdr[7] = height & 0xff;
ihdr[8] = 16;
ihdr[9] = 2;
const chunk = (type: string, data: Uint8Array) => {
const head = new Uint8Array(8 + data.length + 4);
head[0] = (data.length >>> 24) & 0xff;
head[1] = (data.length >>> 16) & 0xff;
head[2] = (data.length >>> 8) & 0xff;
head[3] = data.length & 0xff;
for (let i = 0; i < 4; i++) head[4 + i] = type.charCodeAt(i);
head.set(data, 8);
const crc = crc32(concat([head.subarray(4, 8), data]));
head[8 + data.length] = (crc >>> 24) & 0xff;
head[9 + data.length] = (crc >>> 16) & 0xff;
head[10 + data.length] = (crc >>> 8) & 0xff;
head[11 + data.length] = crc & 0xff;
return head;
};
const png = concat([
new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
chunk('IHDR', ihdr),
...(text ? [chunk('tEXt', new TextEncoder().encode(text))] : []),
chunk('IDAT', zlibStored(raw)),
chunk('IEND', new Uint8Array(0)),
]);
const copy = new Uint8Array(png.length);
copy.set(png);
return copy.buffer;
}
describe('halfBits', () => {
it('matches the reference encodings', () => {
expect(halfBits(0)).toBe(0);
expect(halfBits(1)).toBe(0x3c00);
expect(halfBits(0.5)).toBe(0x3800);
expect(halfBits(0.25)).toBe(0x3400);
expect(halfBits(2)).toBe(0x3c00);
});
});
describe('parsePreview16', () => {
it('reads 16-bit samples back as half-float RGBA', async () => {
const samples = [
[0, 32768, 65535],
[65535, 0, 32768],
];
const parsed = await parsePreview16(encodePng16(samples, 2, 1));
expect(parsed).not.toBeNull();
expect(parsed!.width).toBe(2);
expect(parsed!.height).toBe(1);
expect(Array.from(parsed!.rgba.slice(0, 4))).toEqual([0, 0x3800, 0x3c00, 0x3c00]);
expect(Array.from(parsed!.rgba.slice(4, 8))).toEqual([0x3c00, 0, 0x3800, 0x3c00]);
});
it('flips the rows so upload needs no UNPACK_FLIP_Y', async () => {
const parsed = await parsePreview16(
encodePng16(
[
[65535, 65535, 65535],
[0, 0, 0],
],
1,
2,
),
);
expect(parsed).not.toBeNull();
// Row 0 of the returned buffer is the last image row.
expect(parsed!.rgba[0]).toBe(0);
expect(parsed!.rgba[4]).toBe(0x3c00);
});
it('reads the camera matrix out of the sidecar text chunk', async () => {
const matrix = [1.66943598, -0.4847292, -0.18470675, -0.00096075, 1.25268972, -0.25172901, 0.04713935, -0.30006605, 1.25292671];
const parsed = await parsePreview16(
encodePng16([[1000, 2000, 3000]], 1, 1, `rgbCam\0${matrix.join(',')}`),
);
expect(parsed).not.toBeNull();
expect(parsed!.rgbCam).toHaveLength(9);
expect(parsed!.rgbCam![0]).toBeCloseTo(matrix[0], 6);
expect(parsed!.rgbCam![8]).toBeCloseTo(matrix[8], 6);
});
it('leaves rgbCam undefined for canister sRGB sidecars', async () => {
const parsed = await parsePreview16(encodePng16([[1, 2, 3]], 1, 1));
expect(parsed).not.toBeNull();
expect(parsed!.rgbCam).toBeUndefined();
});
it('rejects 8-bit or non-PNG input instead of guessing', async () => {
const eight = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
expect(await parsePreview16(eight.buffer)).toBeNull();
expect(await parsePreview16(new Uint8Array(64).buffer)).toBeNull();
});
});
+210
View File
@@ -0,0 +1,210 @@
/**
* Client half of the 16-bit raw proxy.
*
* The server keeps the samples LibRaw decoded in a 16-bit PNG next to the JPEG
* proxy. Decoding that PNG here and uploading it as a half-float texture is what
* lets a heavy grade work from 65,536 levels per channel instead of 256: the
* JPEG proxy is still what ordinary imports and thumbnails use, so this is
* always optional.
*
* The parser only accepts what the encoder writes (16-bit, non-interlaced,
* RGB or RGBA) and returns the samples as half-float RGBA with the rows already
* flipped, because `UNPACK_FLIP_Y_WEBGL` is ignored for ArrayBufferView uploads.
*/
export interface Preview16 {
width: number;
height: number;
/** RGBA half-float, rows bottom-up, ready for `texImage2D` without a flip. */
rgba: Uint16Array;
/**
* Camera-to-sRGB matrix, row major, when the samples are camera native.
* Absent on older sidecars, which already hold sRGB.
*/
rgbCam?: number[];
}
const scratchFloat = new Float32Array(1);
const scratchBits = new Uint32Array(scratchFloat.buffer);
/** IEEE-754 half representation of a unit value; 1 -> 0x3c00. */
export function halfBits(value: number): number {
if (!(value > 0)) return value < 0 ? 0x8000 : 0;
if (value >= 1) return 0x3c00;
scratchFloat[0] = value;
const bits = scratchBits[0];
const exponent = ((bits >>> 23) & 0xff) - (127 - 15);
const mantissa = bits & 0x7fffff;
if (exponent <= 0) {
// Subnormal half: shift the implicit bit down and round to nearest.
if (exponent < -10) return 0;
const shift = 14 - exponent;
const full = mantissa | 0x800000;
return (full >>> shift) + ((full >>> (shift - 1)) & 1);
}
let half = (exponent << 10) | (mantissa >>> 13);
const rest = mantissa & 0x1fff;
if (rest > 0x1000 || (rest === 0x1000 && (half & 1) === 1)) half += 1;
return half;
}
let unitTable: Uint16Array | null = null;
/** 65,536-entry lookup so converting a 12-megapixel sidecar stays a table read. */
function halfTable(): Uint16Array {
if (!unitTable) {
const table = new Uint16Array(65536);
for (let i = 0; i < 65536; i++) table[i] = halfBits(i / 65535);
unitTable = table;
}
return unitTable;
}
function paeth(a: number, b: number, c: number): number {
const p = a + b - c;
const pa = Math.abs(p - a);
const pb = Math.abs(p - b);
const pc = Math.abs(p - c);
if (pa <= pb && pa <= pc) return a;
return pb <= pc ? b : c;
}
/** Reverses the PNG row filters in place; PNG filters are byte-oriented. */
function unfilter(data: Uint8Array, width: number, height: number, bpp: number): boolean {
const stride = width * bpp;
if (data.length < (stride + 1) * height) return false;
for (let y = 0; y < height; y++) {
const base = y * (stride + 1);
const filter = data[base];
const row = base + 1;
const prev = row - (stride + 1);
if (filter === 0) continue;
if (filter === 1) {
for (let i = bpp; i < stride; i++) data[row + i] = (data[row + i] + data[row + i - bpp]) & 0xff;
} else if (filter === 2) {
if (y === 0) continue;
for (let i = 0; i < stride; i++) data[row + i] = (data[row + i] + data[prev + i]) & 0xff;
} else if (filter === 3) {
for (let i = 0; i < stride; i++) {
const left = i >= bpp ? data[row + i - bpp] : 0;
const up = y > 0 ? data[prev + i] : 0;
data[row + i] = (data[row + i] + ((left + up) >> 1)) & 0xff;
}
} else if (filter === 4) {
for (let i = 0; i < stride; i++) {
const left = i >= bpp ? data[row + i - bpp] : 0;
const up = y > 0 ? data[prev + i] : 0;
const upLeft = y > 0 && i >= bpp ? data[prev + i - bpp] : 0;
data[row + i] = (data[row + i] + paeth(left, up, upLeft)) & 0xff;
}
} else {
return false;
}
}
return true;
}
async function inflate(data: Uint8Array): Promise<Uint8Array | null> {
try {
// Copy into a plain ArrayBuffer: Blob parts cannot take a view whose buffer
// might be a SharedArrayBuffer.
const copy = new Uint8Array(data.byteLength);
copy.set(data);
const stream = new Blob([copy.buffer]).stream().pipeThrough(new DecompressionStream('deflate'));
return new Uint8Array(await new Response(stream).arrayBuffer());
} catch {
return null;
}
}
/**
* Parses a 16-bit RGB(A) PNG into half-float RGBA. Returns null for anything the
* encoder would not have produced, so a corrupt or unexpectedly large sidecar
* simply leaves the editor on the JPEG proxy.
*/
export async function parsePreview16(buffer: ArrayBuffer): Promise<Preview16 | null> {
const bytes = new Uint8Array(buffer);
if (bytes.length < 33) return null;
if (bytes[0] !== 0x89 || bytes[1] !== 0x50 || bytes[2] !== 0x4e || bytes[3] !== 0x47) return null;
const view = new DataView(buffer);
let at = 8;
let width = 0;
let height = 0;
let depth = 0;
let colorType = 0;
let interlace = 0;
let sawHeader = false;
let rgbCam: number[] | undefined;
const parts: Uint8Array[] = [];
let total = 0;
while (at + 12 <= bytes.length) {
const length = view.getUint32(at);
if (at + 12 + length > bytes.length) return null;
const type = String.fromCharCode(bytes[at + 4], bytes[at + 5], bytes[at + 6], bytes[at + 7]);
const data = bytes.subarray(at + 8, at + 8 + length);
if (type === 'IHDR') {
if (length < 13) return null;
width = view.getUint32(at + 8);
height = view.getUint32(at + 12);
depth = bytes[at + 16];
colorType = bytes[at + 17];
interlace = bytes[at + 20];
sawHeader = true;
} else if (type === 'IDAT') {
parts.push(data);
total += data.length;
} else if (type === 'tEXt') {
// Self-describing sidecars: the camera matrix is written next to the
// pixels, so a sidecar and the matrix that converts it never split.
const zero = data.indexOf(0);
if (zero > 0) {
const keyword = String.fromCharCode(...data.subarray(0, zero));
if (keyword === 'rgbCam') {
const text = String.fromCharCode(...data.subarray(zero + 1));
const values = text.split(',').map(Number);
if (values.length === 9 && values.every((value) => Number.isFinite(value))) {
rgbCam = values;
}
}
}
} else if (type === 'IEND') {
break;
}
at += 12 + length;
}
if (!sawHeader || !width || !height) return null;
if (depth !== 16 || interlace !== 0) return null;
const channels = colorType === 2 ? 3 : colorType === 6 ? 4 : 0;
if (!channels || total === 0) return null;
const idat = new Uint8Array(total);
let offset = 0;
for (const part of parts) {
idat.set(part, offset);
offset += part.length;
}
const raw = await inflate(idat);
if (!raw) return null;
const bpp = channels * 2;
const stride = width * bpp;
if (raw.length < (stride + 1) * height) return null;
if (!unfilter(raw, width, height, bpp)) return null;
const table = halfTable();
const rgba = new Uint16Array(width * height * 4);
const opaque = table[65535];
let out = 0;
for (let y = height - 1; y >= 0; y--) {
// Bottom-up: the texture upload cannot flip an ArrayBufferView.
let src = y * (stride + 1) + 1;
for (let x = 0; x < width; x++) {
rgba[out++] = table[(raw[src] << 8) | raw[src + 1]];
rgba[out++] = table[(raw[src + 2] << 8) | raw[src + 3]];
rgba[out++] = table[(raw[src + 4] << 8) | raw[src + 5]];
rgba[out++] = opaque;
src += bpp;
}
}
return { width, height, rgba, ...(rgbCam ? { rgbCam } : {}) };
}
+340
View File
@@ -0,0 +1,340 @@
import { describe, expect, it } from 'vitest';
import {
buildProofCube,
getActiveProofCube,
loadProofProfile,
parseIcc,
setActiveProofCube,
} from './softProof';
const ascii = (text: string) => new TextEncoder().encode(text);
const clamp = (value: number) => Math.min(1, Math.max(0, value));
/**
* A lut16Type element. `map` turns normalised device values into PCS values, so
* a test can describe the printer's response directly instead of hand-writing
* CLUT entries.
*/
function mft2({
inChannels = 3,
outChannels = 3,
grid = 2,
entries = 256,
counted = false,
map,
}: {
inChannels?: number;
outChannels?: number;
grid?: number;
/** Samples per input/output table: v4 `mft2` allows more than 256. */
entries?: number;
/** Write the entry counts at offsets 48/50, as real paper profiles do. */
counted?: boolean;
map: (inputs: number[]) => number[];
}): Uint8Array {
const corners = grid ** inChannels;
const header = counted ? 52 : 48;
const size =
header + inChannels * entries * 2 + corners * outChannels * 2 + outChannels * entries * 2;
const data = new Uint8Array(size);
const view = new DataView(data.buffer);
data.set(ascii('mft2'), 0);
view.setUint8(8, inChannels);
view.setUint8(9, outChannels);
view.setUint8(10, grid);
if (counted) {
view.setUint16(48, entries, false);
view.setUint16(50, entries, false);
}
let at = header;
for (let channel = 0; channel < inChannels; channel++) {
for (let i = 0; i < entries; i++) {
view.setUint16(at, Math.round((i / (entries - 1)) * 65535), false);
at += 2;
}
}
for (let index = 0; index < corners; index++) {
const inputs = new Array<number>(inChannels).fill(0);
let rest = index;
for (let channel = inChannels - 1; channel >= 0; channel--) {
inputs[channel] = (rest % grid) / (grid - 1);
rest = Math.floor(rest / grid);
}
const out = map(inputs);
for (let channel = 0; channel < outChannels; channel++) {
view.setUint16(at, Math.round(clamp(out[channel]) * 65535), false);
at += 2;
}
}
for (let channel = 0; channel < outChannels; channel++) {
for (let i = 0; i < entries; i++) {
view.setUint16(at, Math.round((i / (entries - 1)) * 65535), false);
at += 2;
}
}
return data;
}
/** A minimal lutAtoBType whose curves, matrix and CLUT are all absent. */
function mabIdentity(inChannels = 3, outChannels = 3): Uint8Array {
const data = new Uint8Array(32);
data.set(ascii('mAB '), 0);
new DataView(data.buffer).setUint8(8, inChannels);
new DataView(data.buffer).setUint8(9, outChannels);
return data;
}
/**
* A v4 lutAtoBType with identity A curves and a two-point identity CLUT. The
* CLUT sits after a five-byte header (grid, precision, three reserved bytes),
* which is easy to misread and silently garbles every v4 printer profile.
*/
function mabWithClut(): Uint8Array {
const grid = 2;
const corners = grid ** 3;
const curveBytes = 12 * 3; // three empty (identity) curves
const aAt = 32;
const clutAt = aAt + curveBytes;
const clutData = clutAt + 5;
const size = (clutData + corners * 3 + 3) & ~3;
const data = new Uint8Array(size);
const view = new DataView(data.buffer);
data.set(ascii('mAB '), 0);
view.setUint8(8, 3);
view.setUint8(9, 3);
view.setUint32(28, aAt, false);
view.setUint32(24, clutAt, false);
for (let c = 0; c < 3; c++) data.set(ascii('curv'), aAt + c * 12);
view.setUint8(clutAt, grid);
view.setUint8(clutAt + 1, 1); // 8-bit CLUT entries
for (let index = 0; index < corners; index++) {
const values = new Array<number>(3).fill(0);
let rest = index;
for (let c = 2; c >= 0; c--) {
values[c] = rest % grid;
rest = Math.floor(rest / grid);
}
for (let c = 0; c < 3; c++) view.setUint8(clutData + index * 3 + c, values[c] * 255);
}
return data;
}
function descTag(text: string): Uint8Array {
const body = ascii(`${text}\0`);
const size = (12 + body.length + 3) & ~3;
const data = new Uint8Array(size);
const view = new DataView(data.buffer);
data.set(ascii('desc'), 0);
view.setUint32(8, body.length, false);
data.set(body, 12);
return data;
}
function buildIcc({
name,
colourSpace = 'RGB ',
pcs = 'Lab ',
a2b,
b2a,
}: {
name: string;
colourSpace?: string;
pcs?: string;
a2b: Uint8Array;
b2a: Uint8Array;
}): Uint8Array {
const tags: { signature: string; bytes: Uint8Array }[] = [
{ signature: 'desc', bytes: descTag(name) },
{ signature: 'A2B0', bytes: a2b },
{ signature: 'B2A0', bytes: b2a },
];
let cursor = 128 + 4 + tags.length * 12;
const placed = tags.map((tag) => {
const at = cursor;
cursor += (tag.bytes.length + 3) & ~3;
return { ...tag, at };
});
const out = new Uint8Array(cursor);
const view = new DataView(out.buffer);
view.setUint32(0, out.length, false);
out.set(ascii('prtr'), 12);
out.set(ascii(colourSpace), 16);
out.set(ascii(pcs), 20);
out.set(ascii('acsp'), 36);
view.setUint32(128, placed.length, false);
placed.forEach((tag, index) => {
const at = 132 + index * 12;
out.set(ascii(tag.signature), at);
view.setUint32(at + 4, tag.at, false);
view.setUint32(at + 8, tag.bytes.length, false);
out.set(tag.bytes, tag.at);
});
return out;
}
/** One node of the proof cube; grid coordinates are sRGB encoded values. */
function cubeAt(cube: { size: number; data: Float32Array }, r: number, g: number, b: number) {
const n = cube.size;
const at = ((b * n + g) * n + r) * 4;
return Array.from(cube.data.subarray(at, at + 4));
}
const identity = (values: number[]) => values;
describe('parseIcc', () => {
it('reads the description, class, PCS and both tables', () => {
const profile = parseIcc(
buildIcc({ name: 'Matte Proof', a2b: mft2({ map: identity }), b2a: mft2({ map: identity }) }),
);
expect(profile).not.toBeNull();
expect(profile!.name).toBe('Matte Proof');
expect(profile!.profileClass).toBe('prtr');
expect(profile!.pcs).toBe('Lab ');
expect(profile!.a2b).not.toBeNull();
expect(profile!.b2a).not.toBeNull();
});
it('reads the counted v4 lut16 tables real paper profiles use', () => {
// MOAB/Epson and the Artifex press profile both declare 4096-entry input
// tables at offsets 48/50 while claiming a v2 version. Treating them as the
// fixed 256-entry v2 layout puts the CLUT in the middle of the input curve.
const profile = parseIcc(
buildIcc({
name: 'Counted paper',
a2b: mft2({ map: identity, entries: 4096, counted: true }),
b2a: mft2({ map: identity, entries: 4096, counted: true }),
}),
);
expect(profile).not.toBeNull();
expect(profile!.a2b).not.toBeNull();
const cube = buildProofCube(profile!, 9);
const mid = cubeAt(cube, 4, 4, 4);
expect(mid[0]).toBeCloseTo(0.5, 2);
expect(mid[0]).toBeCloseTo(mid[2], 2);
});
it('reads a v4 mAB table as well as v2 lut16', () => {
const profile = parseIcc(
buildIcc({ name: 'V4', a2b: mabIdentity(), b2a: mabIdentity() }),
);
expect(profile).not.toBeNull();
expect(profile!.a2b).not.toBeNull();
expect(profile!.b2a).not.toBeNull();
});
it('reads the CLUT of a v4 mAB table at the right offset', () => {
const profile = parseIcc(buildIcc({ name: 'mAB cube', a2b: mabWithClut(), b2a: mabWithClut() }))!;
expect(profile.a2b).not.toBeNull();
const cube = buildProofCube(profile, 9);
const mid = cubeAt(cube, 4, 4, 4);
expect(mid[0]).toBeCloseTo(0.5, 2);
expect(mid[1]).toBeCloseTo(0.5, 2);
expect(mid[2]).toBeCloseTo(0.5, 2);
});
it('refuses data without an ICC signature', () => {
expect(parseIcc(new Uint8Array(200))).toBeNull();
expect(parseIcc(new Uint8Array(4))).toBeNull();
});
});
describe('buildProofCube', () => {
it('is an identity for a profile whose printer reproduces everything', () => {
const profile = parseIcc(
buildIcc({ name: 'Identity', a2b: mft2({ map: identity }), b2a: mft2({ map: identity }) }),
)!;
const cube = buildProofCube(profile, 9);
expect(cube.size).toBe(9);
const mid = cubeAt(cube, 4, 4, 4);
expect(mid[0]).toBeCloseTo(0.5, 2);
expect(mid[1]).toBeCloseTo(0.5, 2);
expect(mid[2]).toBeCloseTo(0.5, 2);
expect(mid[3]).toBe(0);
const colour = cubeAt(cube, 7, 3, 2);
expect(colour[0]).toBeGreaterThan(colour[1]);
expect(colour[1]).toBeGreaterThan(colour[2]);
});
it('shows a printer that cannot reach the top of the tonescale', () => {
// The printed lightness is 80% of the requested one, so a mid grey comes
// back darker: that is the simulation the finish pass displays.
const profile = parseIcc(
buildIcc({
name: 'Dim',
a2b: mft2({ map: ([lightness, a, b]) => [lightness * 0.8, a, b] }),
b2a: mft2({ map: identity }),
}),
)!;
const cube = buildProofCube(profile, 9);
const mid = cubeAt(cube, 4, 4, 4);
expect(mid[0]).toBeLessThan(0.47);
expect(mid[0]).toBeGreaterThan(0.3);
});
it('flags the colours a printer cannot reproduce', () => {
const profile = parseIcc(
buildIcc({
name: 'Clip',
// The printer renders everything 10 % darker than asked, so bright
// colours come back with a large round-trip error while shadows stay
// within the 2.5 ΔE band.
a2b: mft2({ map: ([lightness, a, b]) => [lightness * 0.9, a, b] }),
b2a: mft2({ map: identity }),
}),
)!;
const cube = buildProofCube(profile, 9);
// A bright patch cannot be reproduced, so its round-trip error exceeds the
// gamut threshold without relying on a pinned endpoint.
expect(cubeAt(cube, 8, 8, 8)[3]).toBe(1);
// A dark patch stays inside.
expect(cubeAt(cube, 1, 1, 1)[3]).toBe(0);
// Raising the threshold past the error clears the warning.
const loose = buildProofCube(profile, 9, Infinity);
expect(cubeAt(loose, 8, 8, 8)[3]).toBe(0);
});
it('treats a CMYK printer profile as four channels in, three out', () => {
const profile = parseIcc(
buildIcc({
name: 'CMYK',
colourSpace: 'CMYK',
a2b: mft2({ inChannels: 4, outChannels: 3, grid: 2, map: ([c, m, y, k]) => [1 - c - k, 1 - m - k, 1 - y - k] }),
b2a: mft2({ inChannels: 3, outChannels: 4, grid: 2, map: ([r, g, b]) => [1 - r, 1 - g, 1 - b, 0] }),
}),
)!;
const cube = buildProofCube(profile, 9);
const mid = cubeAt(cube, 4, 4, 4);
expect(mid[0]).toBeGreaterThan(0);
expect(mid[0]).toBeLessThan(1);
});
it('refuses a profile without a round trip', () => {
const bytes = buildIcc({
name: 'Half',
a2b: mft2({ map: identity }),
b2a: mft2({ map: identity }),
});
const profile = parseIcc(bytes)!;
expect(() => buildProofCube({ ...profile, a2b: null }, 5)).toThrow();
});
});
describe('active proof profile', () => {
it('remembers the cube the export path needs', () => {
const bytes = buildIcc({
name: 'Session',
a2b: mft2({ map: identity }),
b2a: mft2({ map: identity }),
});
setActiveProofCube(null);
expect(getActiveProofCube()).toBeNull();
const cube = loadProofProfile(bytes, 5);
expect(cube.name).toBe('Session');
expect(getActiveProofCube()).toBe(cube);
setActiveProofCube(null);
});
it('rejects a file that is not a profile', () => {
expect(() => loadProofProfile(new Uint8Array(300))).toThrow(/not an ICC profile/);
});
});
+586
View File
@@ -0,0 +1,586 @@
/**
* Real ICC soft proofing.
*
* A printer profile describes two directions between its device values and the
* Profile Connection Space: `A2B0` (device -> PCS) and `B2A0` (PCS -> device).
* Simulating the print means going through both: the display colour is turned
* into PCS, pushed into the printer's ink space, and pulled back out. Colours
* the printer cannot hit come back changed, and that difference is exactly what
* the soft proof shows. Saturated colours are also flagged, so the gamut warning
* reflects the profile instead of a saturation guess.
*
* The round trip is baked into a 3D cube that maps sRGB to sRGB, which the
* renderer samples with one texture fetch per pixel. Values are kept in the
* sRGB encoding the finish pass already works in.
*
* Both the v2 (`lut8Type`/`lut16Type`) and v4 (`lutAtoBType`/`lutBtoAType`)
* table layouts are read, because printer profiles ship in both.
*/
const D50_WHITE = [0.9642, 1, 0.8249] as const;
/** Linear sRGB (D50 adapted) to XYZ, matching the primaries in `icc.ts`. */
const RGB_TO_XYZ = [
0.4360747, 0.3850649, 0.1430804, 0.2225045, 0.7168786, 0.0606169, 0.0139322, 0.0971045,
0.7141733,
];
/** XYZ (D50) to linear sRGB. */
const XYZ_TO_RGB = [
3.1338561, -1.6168667, -0.4906146, -0.9787684, 1.9161415, 0.033454, 0.0719453, -0.2289914,
1.4052427,
];
export type Pcs = 'Lab ' | 'XYZ ';
interface Curve {
/** Sampled curve in 0-1, or null for a plain gamma. */
table: Float32Array | null;
/** ICC gamma curve (u8Fixed8), used when there is no table. */
gamma: number;
}
interface Clut {
inChannels: number;
outChannels: number;
grid: number;
data: Float32Array;
}
/** One step of a LUT, in the order the profile specifies. */
type Stage =
| { kind: 'curves'; curves: Curve[] }
| { kind: 'matrix'; matrix: number[] }
| { kind: 'clut'; clut: Clut };
interface IccTransform {
inChannels: number;
outChannels: number;
stages: Stage[];
}
export interface IccProfile {
name: string;
/** Profile class signature: 'prtr', 'mntr', 'scnr', ... */
profileClass: string;
colourSpace: string;
pcs: Pcs;
a2b: IccTransform | null;
b2a: IccTransform | null;
}
export interface SoftProofCube {
/** Edge length of the cube, e.g. 33. */
size: number;
/** RGBA: sRGB out in RGB, gamut flag in A. */
data: Float32Array;
name: string;
}
/* ------------------------------------------------------------------ helpers */
const clamp01 = (value: number) => (value <= 0 ? 0 : value >= 1 ? 1 : value);
function srgbToLinear(value: number): number {
const v = clamp01(value);
return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
}
function linearToSrgb(value: number): number {
const v = value <= 0 ? 0 : value;
return v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;
}
function multiply3(m: number[], v: number[]): number[] {
return [
m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
m[6] * v[0] + m[7] * v[1] + m[8] * v[2],
];
}
function xyzToLab(xyz: number[]): [number, number, number] {
const f = (t: number) => (t > 0.008856 ? Math.cbrt(t) : 7.787 * t + 16 / 116);
const xr = f(xyz[0] / D50_WHITE[0]);
const yr = f(xyz[1] / D50_WHITE[1]);
const zr = f(xyz[2] / D50_WHITE[2]);
return [116 * yr - 16, 500 * (xr - yr), 200 * (yr - zr)];
}
function labToXyz(lab: number[]): [number, number, number] {
const fy = (lab[0] + 16) / 116;
const fx = fy + lab[1] / 500;
const fz = fy - lab[2] / 200;
const inv = (t: number) => (t ** 3 > 0.008856 ? t ** 3 : (t - 16 / 116) / 7.787);
return [inv(fx) * D50_WHITE[0], inv(fy) * D50_WHITE[1], inv(fz) * D50_WHITE[2]];
}
/** PCS values as the 0-1 fractions a LUT is indexed with. */
function encodePcs(pcs: Pcs, lab: number[], xyz: number[]): number[] {
if (pcs === 'Lab ') {
return [clamp01(lab[0] / 100), clamp01((lab[1] + 128) / 255), clamp01((lab[2] + 128) / 255)];
}
return [clamp01(xyz[0] / 1.99997), clamp01(xyz[1] / 1.99997), clamp01(xyz[2] / 1.99997)];
}
function decodePcs(pcs: Pcs, values: number[]): { lab: number[]; xyz: number[] } {
if (pcs === 'Lab ') {
const lab = [values[0] * 100, values[1] * 255 - 128, values[2] * 255 - 128];
return { lab, xyz: labToXyz(lab) };
}
const xyz = [values[0] * 1.99997, values[1] * 1.99997, values[2] * 1.99997];
return { lab: xyzToLab(xyz), xyz };
}
function curveAt(curve: Curve, value: number): number {
const v = clamp01(value);
if (curve.table) {
const last = curve.table.length - 1;
if (last <= 0) return v;
const at = v * last;
const index = Math.floor(at);
const frac = at - index;
const a = curve.table[Math.min(last, index)];
const b = curve.table[Math.min(last, index + 1)];
return a + (b - a) * frac;
}
return v ** curve.gamma;
}
/** Multilinear interpolation, first input channel varying slowest. */
function sampleClut(clut: Clut, values: number[]): number[] {
const { inChannels, outChannels, grid, data } = clut;
const lo: number[] = [];
const hi: number[] = [];
const frac: number[] = [];
for (let channel = 0; channel < inChannels; channel++) {
const at = clamp01(values[channel]) * (grid - 1);
const base = Math.min(grid - 1, Math.floor(at));
lo.push(base);
hi.push(Math.min(grid - 1, base + 1));
frac.push(at - base);
}
const out = new Array<number>(outChannels).fill(0);
const corners = 1 << inChannels;
for (let corner = 0; corner < corners; corner++) {
let weight = 1;
let offset = 0;
for (let channel = 0; channel < inChannels; channel++) {
const high = (corner >> channel) & 1;
weight *= high ? frac[channel] : 1 - frac[channel];
offset = offset * grid + (high ? hi[channel] : lo[channel]);
}
if (weight === 0) continue;
for (let channel = 0; channel < outChannels; channel++) {
out[channel] += weight * data[offset * outChannels + channel];
}
}
for (let channel = 0; channel < outChannels; channel++) out[channel] = clamp01(out[channel]);
return out;
}
function evaluate(transform: IccTransform, input: number[]): number[] {
let values = input;
for (const stage of transform.stages) {
if (stage.kind === 'curves') {
values = values.map((value, index) => curveAt(stage.curves[index], value));
} else if (stage.kind === 'matrix') {
values = multiply3(stage.matrix, values).map(clamp01);
} else {
values = sampleClut(stage.clut, values);
}
}
return values;
}
/* ------------------------------------------------------------------ parsing */
const identityCurve = (): Curve => ({ table: null, gamma: 1 });
const curves = (count: number): Curve[] => Array.from({ length: count }, identityCurve);
function readS15(view: DataView, at: number): number {
return view.getInt32(at, false) / 65536;
}
function parseMatrix(view: DataView, at: number): number[] | null {
const values: number[] = [];
for (let i = 0; i < 9; i++) values.push(readS15(view, at + i * 4));
// An all-zero matrix is how a profile says "no matrix".
return values.some((value) => Math.abs(value) > 1e-6) ? values : null;
}
function readTable(
view: DataView,
cursor: number,
count: number,
entries: number,
wide: boolean,
limit: number,
): { curves: Curve[]; cursor: number } | null {
const entry = wide ? 2 : 1;
const scale = wide ? 65535 : 255;
if (cursor + count * entries * entry > limit) return null;
const table = Array.from({ length: count }, identityCurve);
let at = cursor;
for (let channel = 0; channel < count; channel++) {
const samples = new Float32Array(entries);
for (let i = 0; i < entries; i++) {
samples[i] = (wide ? view.getUint16(at, false) : view.getUint8(at)) / scale;
at += entry;
}
table[channel] = { table: samples, gamma: 1 };
}
return { curves: table, cursor: at };
}
/**
* lut8Type / lut16Type: input tables, a matrix for three-channel spaces, a CLUT,
* then output tables.
*
* `lut16Type` has two layouts in the wild. ICC v4 stores the input and output
* table entry counts at offsets 48 and 50, so tables can hold 4096 samples;
* v2 fixed both at 256 with the tables starting at 48. Real vendor paper
* profiles (MOAB/Epson, Artifex CMYK) are v2-versioned but use the counted
* layout, so both are measured against the tag size and the layout that fills
* the tag is taken.
*/
function parseMft(view: DataView, at: number, size: number, wide: boolean): IccTransform | null {
if (size < (wide ? 52 : 48)) return null;
const inChannels = view.getUint8(at + 8);
const outChannels = view.getUint8(at + 9);
const grid = view.getUint8(at + 10);
if (!inChannels || !outChannels || grid < 2) return null;
if (inChannels > 15 || outChannels > 15) return null;
const matrix = inChannels === 3 ? parseMatrix(view, at + 12) : null;
const entry = wide ? 2 : 1;
const scale = wide ? 65535 : 255;
const total = grid ** inChannels * outChannels;
if (!Number.isFinite(total) || total > 16_000_000) return null;
const limit = at + size;
let start = at + 48;
let inEntries = 256;
let outEntries = 256;
if (wide) {
// A counted layout only counts when its tables fit; on a legacy profile the
// first two table samples land here and the computed size overruns the tag.
const countedIn = view.getUint16(at + 48, false);
const countedOut = view.getUint16(at + 50, false);
const countedTotal =
52 + inChannels * countedIn * entry + total * entry + outChannels * countedOut * entry;
if (
countedIn >= 2 &&
countedIn <= 4096 &&
countedOut >= 2 &&
countedOut <= 4096 &&
countedTotal <= size &&
size - countedTotal <= 32
) {
start = at + 52;
inEntries = countedIn;
outEntries = countedOut;
} else {
const legacyTotal =
48 + inChannels * 256 * entry + total * entry + outChannels * 256 * entry;
if (legacyTotal > size) return null;
}
}
const input = readTable(view, start, inChannels, inEntries, wide, limit);
if (!input) return null;
let cursor = input.cursor;
if (cursor + total * entry > limit) return null;
const data = new Float32Array(total);
for (let i = 0; i < total; i++) {
data[i] = (wide ? view.getUint16(cursor, false) : view.getUint8(cursor)) / scale;
cursor += entry;
}
const output = readTable(view, cursor, outChannels, outEntries, wide, limit);
if (!output) return null;
const stages: Stage[] = [{ kind: 'curves', curves: input.curves }];
if (matrix) stages.push({ kind: 'matrix', matrix });
stages.push({ kind: 'clut', clut: { inChannels, outChannels, grid, data } });
stages.push({ kind: 'curves', curves: output.curves });
return { inChannels, outChannels, stages };
}
/** A sequence of `curv` elements, one per channel, each 4-byte aligned. */
function parseCurveSet(
view: DataView,
base: number,
offset: number,
count: number,
limit: number,
): Curve[] | null {
if (!offset) return curves(count);
let at = base + offset;
const out: Curve[] = [];
for (let channel = 0; channel < count; channel++) {
if (at + 12 > limit) return null;
const type = String.fromCharCode(
view.getUint8(at),
view.getUint8(at + 1),
view.getUint8(at + 2),
view.getUint8(at + 3),
);
if (type !== 'curv') return null;
const entries = view.getUint32(at + 8, false);
if (entries === 0) {
out.push(identityCurve());
at += 12;
} else if (entries === 1) {
out.push({ table: null, gamma: view.getUint16(at + 12, false) / 256 });
at += 14;
} else {
if (entries > 4096 || at + 12 + entries * 2 > limit) return null;
const table = new Float32Array(entries);
for (let i = 0; i < entries; i++) {
table[i] = view.getUint16(at + 12 + i * 2, false) / 65535;
}
out.push({ table, gamma: 1 });
at += 12 + entries * 2;
}
at = (at + 3) & ~3;
}
return out;
}
/**
* lutAtoBType / lutBtoAType: A curves, CLUT, M curves, matrix and B curves, in
* the order the direction calls for.
*/
function parseMab(
view: DataView,
at: number,
size: number,
towardsPcs: boolean,
): IccTransform | null {
if (size < 32) return null;
const inChannels = view.getUint8(at + 8);
const outChannels = view.getUint8(at + 9);
if (!inChannels || !outChannels || inChannels > 15 || outChannels > 15) return null;
const bCurvesAt = view.getUint32(at + 12, false);
const matrixAt = view.getUint32(at + 16, false);
const mCurvesAt = view.getUint32(at + 20, false);
const clutAt = view.getUint32(at + 24, false);
const aCurvesAt = view.getUint32(at + 28, false);
const limit = at + size;
const matrix = matrixAt ? parseMatrix(view, at + matrixAt) : null;
const a = parseCurveSet(view, at, aCurvesAt, inChannels, limit);
const b = parseCurveSet(view, at, bCurvesAt, outChannels, limit);
const m = parseCurveSet(view, at, mCurvesAt, outChannels, limit);
if (!a || !b || !m) return null;
let clut: Clut | null = null;
if (clutAt) {
const points = view.getUint8(at + clutAt);
const precision = view.getUint8(at + clutAt + 1);
if (!points || points < 2) return null;
const entry = precision === 2 ? 2 : 1;
const scale = precision === 2 ? 65535 : 255;
const total = points ** inChannels * outChannels;
// Grid point, precision and three reserved bytes, then the data.
const cursor = at + clutAt + 5;
if (cursor + total * entry > limit) return null;
const data = new Float32Array(total);
for (let i = 0; i < total; i++) {
data[i] =
(entry === 2 ? view.getUint16(cursor + i * 2, false) : view.getUint8(cursor + i)) / scale;
}
clut = { inChannels, outChannels, grid: points, data };
}
const stages: Stage[] = [];
if (towardsPcs) {
stages.push({ kind: 'curves', curves: a });
if (clut) stages.push({ kind: 'clut', clut });
stages.push({ kind: 'curves', curves: m });
if (matrix) stages.push({ kind: 'matrix', matrix });
stages.push({ kind: 'curves', curves: b });
} else {
stages.push({ kind: 'curves', curves: b });
if (matrix) stages.push({ kind: 'matrix', matrix });
stages.push({ kind: 'curves', curves: m });
if (clut) stages.push({ kind: 'clut', clut });
stages.push({ kind: 'curves', curves: a });
}
return { inChannels, outChannels, stages };
}
function parseDescription(view: DataView, at: number, size: number): string {
if (!at || size < 12) return '';
const type = String.fromCharCode(
view.getUint8(at),
view.getUint8(at + 1),
view.getUint8(at + 2),
view.getUint8(at + 3),
);
if (type === 'desc') {
const length = view.getUint32(at + 8, false);
let text = '';
for (let i = 0; i < Math.min(length, 255, size - 12); i++) {
const code = view.getUint8(at + 12 + i);
if (!code) break;
text += String.fromCharCode(code);
}
return text.trim();
}
if (type === 'mluc') {
// Multi-localized text: the first record, whose string is UTF-16BE.
const records = view.getUint32(at + 8, false);
if (!records) return '';
const length = view.getUint32(at + 20, false);
const offset = view.getUint32(at + 24, false);
let text = '';
for (let i = 0; i + 1 < length && offset + i + 1 < size; i += 2) {
const code = view.getUint16(at + offset + i, false);
if (!code) break;
text += String.fromCharCode(code);
}
return text.trim();
}
return '';
}
/**
* Reads an ICC profile's colour tags. Returns null when the header or the tag
* table is not an ICC profile, so a renamed JPEG cannot become a proof profile.
*/
export function parseIcc(bytes: Uint8Array): IccProfile | null {
if (bytes.length < 132) return null;
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
if (String.fromCharCode(...bytes.subarray(36, 40)) !== 'acsp') return null;
const declared = view.getUint32(0, false);
if (declared > bytes.length) return null;
const ascii = (at: number) => String.fromCharCode(...bytes.subarray(at, at + 4)).trim();
const colourSpace = ascii(16);
const pcs = ascii(20) === 'Lab' ? 'Lab ' : 'XYZ ';
const count = view.getUint32(128, false);
if (!count || 132 + count * 12 > bytes.length) return null;
const tags = new Map<string, { at: number; size: number }>();
for (let index = 0; index < count; index++) {
const entry = 132 + index * 12;
const signature = String.fromCharCode(...bytes.subarray(entry, entry + 4));
const at = view.getUint32(entry + 4, false);
const size = view.getUint32(entry + 8, false);
if (at >= bytes.length || at + size > bytes.length) continue;
tags.set(signature, { at, size });
}
const transform = (signature: string, towardsPcs: boolean): IccTransform | null => {
const tag = tags.get(signature);
if (!tag) return null;
const type = String.fromCharCode(...bytes.subarray(tag.at, tag.at + 4));
if (type === 'mft1') return parseMft(view, tag.at, tag.size, false);
if (type === 'mft2') return parseMft(view, tag.at, tag.size, true);
if (type === 'mAB ') return parseMab(view, tag.at, tag.size, towardsPcs);
if (type === 'mBA ') return parseMab(view, tag.at, tag.size, !towardsPcs);
return null;
};
const description = tags.get('desc');
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),
};
}
/* --------------------------------------------------------------- proof cube */
/**
* Round-trip Lab error above which a colour is called out of gamut. Pinned ink
* values are always flagged; this catches colours the profile bends without
* hitting an endpoint. Measured against real paper and press profiles: see the
* soft-proof notes in the README.
*/
export const GAMUT_DELTA = 2.5;
/**
* Bakes the profile's device round trip into an sRGB cube.
*
* `size` is the cube edge; 33 keeps a smooth ramp (the renderer interpolates
* between nodes) without a noticeable upload. Throws when the profile is missing
* the tables the round trip needs, because silently showing the paper
* approximation instead would misrepresent what was loaded.
*/
export function buildProofCube(
profile: IccProfile,
size = 33,
gamutDelta = GAMUT_DELTA,
): SoftProofCube {
if (!profile.a2b || !profile.b2a) {
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 data = new Float32Array(edge * edge * edge * 4);
let at = 0;
const scale = edge - 1;
for (let b = 0; b < edge; b++) {
for (let g = 0; g < edge; g++) {
for (let r = 0; r < edge; r++) {
const linear = [
srgbToLinear(r / scale),
srgbToLinear(g / scale),
srgbToLinear(b / scale),
];
const xyz = multiply3(RGB_TO_XYZ, linear);
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 back = decodePcs(profile.pcs, printed);
const rgb = multiply3(XYZ_TO_RGB, back.xyz);
data[at++] = clamp01(linearToSrgb(rgb[0]));
data[at++] = clamp01(linearToSrgb(rgb[1]));
data[at++] = clamp01(linearToSrgb(rgb[2]));
const delta = Math.hypot(
lab[0] - back.lab[0],
lab[1] - back.lab[1],
lab[2] - back.lab[2],
);
// Pinned device values are not a gamut signal on their own: white and
// black sit at 0/1 on every paper. An out-of-gamut colour shows up as a
// large round-trip error instead, because the profile clamps it.
data[at++] = delta > gamutDelta ? 1 : 0;
}
}
}
return { size: edge, data, name: profile.name };
}
/* ----------------------------------------------------- active proof profile */
/**
* The profile loaded for this session. The renderer is handed the cube, and the
* export path reads it here so a file rendered while the profile is loaded
* matches the canvas. An edit only stores whether proofing is on; the table is
* a megabyte and does not belong in a photo record.
*/
let active: SoftProofCube | null = null;
export function setActiveProofCube(cube: SoftProofCube | null) {
active = cube;
}
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 {
const profile = parseIcc(bytes);
if (!profile) throw new Error('That file is not an ICC profile');
const cube = buildProofCube(profile, size);
setActiveProofCube(cube);
return cube;
}
+35
View File
@@ -0,0 +1,35 @@
import { describe, expect, it } from 'vitest';
import { kelvinGains, wbGainFor, WB_REFERENCE_KELVIN } from './whiteBalance';
describe('absolute white balance', () => {
it('is neutral at the daylight reference', () => {
const gain = kelvinGains(WB_REFERENCE_KELVIN);
expect(gain[0]).toBeCloseTo(1, 2);
expect(gain[1]).toBeCloseTo(1, 2);
expect(gain[2]).toBeCloseTo(1, 2);
});
it('warms a tungsten scene by lifting blue and pulling red', () => {
const gain = kelvinGains(3200);
expect(gain[2]).toBeGreaterThan(1.4);
expect(gain[0]).toBeLessThan(1);
expect(gain[1]).toBeCloseTo(1, 2);
});
it('cools a high-temperature scene by lifting red', () => {
const gain = kelvinGains(9000);
expect(gain[0]).toBeGreaterThan(1);
expect(gain[2]).toBeLessThan(1);
});
it('keeps the relative sliders neutral at zero and normalises luminance', () => {
const neutral = wbGainFor(0, 0, null);
expect(neutral[0]).toBeCloseTo(1, 5);
expect(neutral[1]).toBeCloseTo(1, 5);
expect(neutral[2]).toBeCloseTo(1, 5);
for (const gain of [wbGainFor(40, 20, null), wbGainFor(0, 0, 3200)]) {
const luma = 0.2126 * gain[0] + 0.7152 * gain[1] + 0.0722 * gain[2];
expect(luma).toBeCloseTo(1, 4);
}
});
});
+84
View File
@@ -24,6 +24,90 @@ function toLinear(v: number): number {
const clampRange = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
/** Reference illuminant for the absolute Kelvin control; daylight-balanced. */
export const WB_REFERENCE_KELVIN = 5500;
/** CIE 1931 chromaticity of a black body at `kelvin` (Kim et al. approximation). */
export function planckianXy(kelvin: number): { x: number; y: number } {
const t = clampRange(kelvin, 1667, 25000);
const x =
t <= 4000
? -0.2661239e9 / (t * t * t) -
0.2343589e6 / (t * t) +
0.8776956e3 / t +
0.17991
: -3.0258469e9 / (t * t * t) +
2.1070379e6 / (t * t) +
0.2226347e3 / t +
0.24039;
let y: number;
if (t <= 2222) {
y = -1.1063814 * x ** 3 - 1.3481102 * x ** 2 + 2.18555832 * x - 0.20219683;
} else if (t <= 4000) {
y = -0.9549476 * x ** 3 - 1.37418593 * x ** 2 + 2.09137015 * x - 0.16748867;
} else {
y = 3.081758 * x ** 3 - 5.8733867 * x ** 2 + 3.75112997 * x - 0.37001483;
}
// Guard the fit at the extremes; outside the Planckian locus it can drift.
if (!Number.isFinite(y) || y <= 0.001) y = Math.max(0.001, 2 / (x * 1000 + 2));
return { x, y };
}
/* sRGB primaries, D65 white. */
const XYZ_TO_LINEAR_SRGB: readonly (readonly [number, number, number])[] = [
[3.2404542, -1.5371385, -0.4985314],
[-0.969266, 1.8760108, 0.041556],
[0.0556434, -0.2040259, 1.0572252],
];
function whiteForKelvin(kelvin: number): [number, number, number] {
const { x, y } = planckianXy(kelvin);
const X = x / y;
const Y = 1;
const Z = (1 - x - y) / y;
return [
XYZ_TO_LINEAR_SRGB[0][0] * X + XYZ_TO_LINEAR_SRGB[0][1] * Y + XYZ_TO_LINEAR_SRGB[0][2] * Z,
XYZ_TO_LINEAR_SRGB[1][0] * X + XYZ_TO_LINEAR_SRGB[1][1] * Y + XYZ_TO_LINEAR_SRGB[1][2] * Z,
XYZ_TO_LINEAR_SRGB[2][0] * X + XYZ_TO_LINEAR_SRGB[2][1] * Y + XYZ_TO_LINEAR_SRGB[2][2] * Z,
].map((v) => Math.max(1e-4, v)) as [number, number, number];
}
/**
* Linear-light channel gains that treat the scene as lit at `kelvin` and render
* it neutral, relative to the 5500 K daylight balance of the proxy. A lower
* Kelvin warms the picture (as if correcting tungsten), a higher one cools it.
* Green is normalised to 1 so the control changes colour, not exposure.
*/
export function kelvinGains(kelvin: number): [number, number, number] {
const ref = whiteForKelvin(WB_REFERENCE_KELVIN);
const white = whiteForKelvin(kelvin);
const g = ref[1] / white[1];
return [ref[0] / white[0] / g, 1, ref[2] / white[2] / g].map((v) =>
Number.isFinite(v) ? Math.max(0.05, v) : 1,
) as [number, number, number];
}
/** The gain the grade shader applies for the current white-balance controls. */
export function wbGainFor(
temp: number,
tint: number,
kelvin: number | null,
): [number, number, number] {
const t = temp / 100;
const ti = tint / 100;
let gain: [number, number, number] = kelvin
? kelvinGains(kelvin)
: [1 + 0.3 * t, 1, 1 - 0.26 * t];
gain = [
gain[0] * (1 + 0.06 * ti),
gain[1] * (1 - 0.16 * ti),
gain[2] * (1 + 0.06 * ti),
];
const l = 0.2126 * gain[0] + 0.7152 * gain[1] + 0.0722 * gain[2];
const norm = Math.max(0.05, l);
return gain.map((v) => v / norm) as [number, number, number];
}
/**
* Temperature and tint that make a sampled source colour neutral.
* `sample` is the untouched (sRGB-encoded) source pixel, 0–1 per channel.
+61
View File
@@ -0,0 +1,61 @@
import { describe, expect, it } from 'vitest';
import { defaultEdits, normalizeEdits } from './edits';
import { editsToXmp, xmpFileName, xmpToEdits } from './xmp';
describe('xmp sidecars', () => {
it('round-trips every develop field exactly', () => {
const edits = defaultEdits();
edits.exposure = 0.65;
edits.temp = -14;
edits.kelvin = 4200;
edits.contrast = 22;
edits.parametric.darks = -17;
edits.hsl.hue[3] = 12;
edits.grain.roughness = 71;
edits.local = [
{
...defaultEdits().local[0],
kind: 'linear',
linear: { x1: 0.1, y1: 0.2, x2: 0.8, y2: 0.9 },
},
];
const xml = editsToXmp(edits);
const back = xmpToEdits(xml, defaultEdits());
expect(back.source).toBe('luminary');
// Sanitising on the way in is allowed; it must not change any value.
expect(back.edits).toEqual(normalizeEdits(edits));
});
it('reads crs fields written by Lightroom', () => {
const xml = `<?xpacket begin=""?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:Exposure2012="1.25" crs:Contrast2012="-18" crs:Clarity2012="34" crs:GrainAmount="40" crs:ConvertToGrayscale="True"/></rdf:RDF></x:xmpmeta>`;
const base = defaultEdits();
base.saturation = 9;
const result = xmpToEdits(xml, base);
expect(result.source).toBe('lightroom');
expect(result.edits.exposure).toBe(1.25);
expect(result.edits.contrast).toBe(-18);
expect(result.edits.clarity).toBe(34);
expect(result.edits.grain.amount).toBe(40);
expect(result.edits.bw).toBe(true);
// Fields the sidecar does not mention keep the photo's own settings.
expect(result.edits.saturation).toBe(9);
});
it('reads an absolute Kelvin temperature written by Lightroom', () => {
const xml = `<?xpacket begin=""?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:Temperature="3800" crs:Tint="12" crs:Exposure2012="0.4"/></rdf:RDF></x:xmpmeta>`;
const result = xmpToEdits(xml, defaultEdits());
expect(result.edits.kelvin).toBe(3800);
expect(result.edits.tint).toBe(12);
expect(result.applied).toContain('Temperature');
});
it('rejects a file that is not a sidecar', () => {
expect(() => xmpToEdits('<html></html>', defaultEdits())).toThrow(/not an XMP/);
});
it('names the sidecar after the photo', () => {
expect(xmpFileName('DSC0123.ARW')).toBe('DSC0123.xmp');
expect(xmpFileName('no-extension')).toBe('no-extension.xmp');
});
});
+237
View File
@@ -0,0 +1,237 @@
import type { Edits, PhotoRecord } from '../types';
import { normalizeEdits } from './edits';
/**
* Lightroom-compatible XMP sidecars.
*
* The crs: attributes are the shared vocabulary, so a sidecar written here
* carries the grade into Lightroom and one written by Lightroom opens here.
* Lightroom has no slot for everything Luminary can do (film curves, HSL,
* local layers, denoise), so the full edit is also written to a private
* `lum:Settings` attribute as base64 JSON. Import prefers that attribute when
* it is present and falls back to reading the crs: fields otherwise, which
* keeps round trips exact without making the file useless elsewhere.
*/
const LUM_NS = 'https://luminary.app/xmp/1.0';
/** crs field, direction: our edits use the same -100…100 scale. */
const CRS_FIELDS: [string, (edits: Edits) => number][] = [
['Exposure2012', (e) => e.exposure],
['Contrast2012', (e) => e.contrast],
['Highlights2012', (e) => e.highlights],
['Shadows2012', (e) => e.shadows],
['Whites2012', (e) => e.whites],
['Blacks2012', (e) => e.blacks],
['Texture', (e) => e.texture],
['Clarity2012', (e) => e.clarity],
['Dehaze', (e) => e.dehaze],
['Vibrance', (e) => e.vibrance],
['Saturation', (e) => e.saturation],
['ParametricHighlights', (e) => e.parametric.highlights],
['ParametricLights', (e) => e.parametric.lights],
['ParametricDarks', (e) => e.parametric.darks],
['ParametricBlacks', (e) => e.parametric.blacks],
['PostCropVignetteAmount', (e) => e.vignette.amount],
['GrainAmount', (e) => e.grain.amount],
];
const CRS_TO_EDIT: Record<string, (edits: Edits, value: number) => void> = {
Exposure2012: (e, v) => (e.exposure = v),
Contrast2012: (e, v) => (e.contrast = v),
Highlights2012: (e, v) => (e.highlights = v),
Shadows2012: (e, v) => (e.shadows = v),
Whites2012: (e, v) => (e.whites = v),
Blacks2012: (e, v) => (e.blacks = v),
Texture: (e, v) => (e.texture = v),
Clarity2012: (e, v) => (e.clarity = v),
Dehaze: (e, v) => (e.dehaze = v),
Vibrance: (e, v) => (e.vibrance = v),
Saturation: (e, v) => (e.saturation = v),
ParametricHighlights: (e, v) => (e.parametric.highlights = v),
ParametricLights: (e, v) => (e.parametric.lights = v),
ParametricDarks: (e, v) => (e.parametric.darks = v),
ParametricBlacks: (e, v) => (e.parametric.blacks = v),
PostCropVignetteAmount: (e, v) => (e.vignette.amount = v),
GrainAmount: (e, v) => (e.grain.amount = v),
ConvertToGrayscale: (e, v) => (e.bw = v >= 0.5 || v === 1),
};
export interface XmpImport {
edits: Edits;
/** How the settings were read: exact Luminary payload or crs fallback. */
source: 'luminary' | 'lightroom';
/** crs fields the sidecar set, for the toast. */
applied: string[];
}
function escapeXml(value: string) {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function unescapeXml(value: string) {
return value
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&');
}
function base64Encode(text: string) {
const bytes = new TextEncoder().encode(text);
let binary = '';
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary);
}
function base64Decode(value: string) {
const binary = atob(value);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return new TextDecoder().decode(bytes);
}
function num(value: number) {
return Number.isFinite(value) ? String(Math.round(value * 1000) / 1000) : '0';
}
/** Sidecar name for a photo: "DSC0123.ARW" → "DSC0123.xmp". */
export function xmpFileName(name: string) {
return `${name.replace(/\.[^.]+$/, '') || 'photo'}.xmp`;
}
export function editsToXmp(edits: Edits, photo?: Pick<PhotoRecord, 'name' | 'meta'>): string {
const normalized = normalizeEdits(edits);
const attrs = CRS_FIELDS.map(
([name, read]) => `crs:${name}="${num(read(normalized))}"`,
);
attrs.push(`crs:ConvertToGrayscale="${normalized.bw ? 'True' : 'False'}"`);
if (normalized.kelvin != null) attrs.push(`crs:Temperature="${Math.round(normalized.kelvin)}"`);
attrs.push(`lum:Settings="${escapeXml(base64Encode(JSON.stringify(normalized)))}"`);
const label = photo ? escapeXml(photo.name) : 'Luminary edit';
return [
'<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?>',
'<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Luminary">',
' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">',
` <rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmlns:lum="${LUM_NS}"`,
' crs:Version="15.0" crs:ProcessVersion="15.4" crs:HasSettings="True"',
` ${attrs.join('\n ')}>`,
` <dc:title xmlns:dc="http://purl.org/dc/elements/1.1/"><rdf:Alt><rdf:li xml:lang="x-default">${label}</rdf:li></rdf:Alt></dc:title>`,
' </rdf:Description>',
' </rdf:RDF>',
'</x:xmpmeta>',
'<?xpacket end="w"?>',
].join('\n');
}
function attributes(xml: string) {
const out = new Map<string, string>();
const pattern = /([A-Za-z][\w:.-]*)\s*=\s*"([^"]*)"/g;
let match: RegExpExecArray | null;
while ((match = pattern.exec(xml))) {
// Later duplicates lose: rdf:about="" repeats on every nested node.
if (!out.has(match[1])) out.set(match[1], unescapeXml(match[2]));
}
return out;
}
/**
* Reads settings from a sidecar. `base` supplies every field the file does not
* mention, so importing a Lightroom crop-free sidecar keeps the photo's mask
* layers, crop and lens profile instead of resetting them.
*/
export function xmpToEdits(xml: string, base: Edits): XmpImport {
if (!/<x:xmpmeta|<rdf:RDF/i.test(xml)) {
throw new Error('That file is not an XMP sidecar');
}
const attrs = attributes(xml);
const exact = attrs.get('lum:Settings');
if (exact) {
try {
const parsed = JSON.parse(base64Decode(exact)) as Partial<Edits>;
return {
edits: normalizeEdits({ ...base, ...parsed }),
source: 'luminary',
applied: ['Luminary settings'],
};
} catch {
// A damaged private payload still leaves the crs: fields to read.
}
}
const next = normalizeEdits(base);
const applied: string[] = [];
for (const [name, apply] of Object.entries(CRS_TO_EDIT)) {
const raw = attrs.get(`crs:${name}`);
if (raw === undefined) continue;
const value = name === 'ConvertToGrayscale'
? raw === 'True' || raw === 'true' || raw === '1'
? 1
: 0
: Number(raw);
if (!Number.isFinite(value)) continue;
apply(next, value);
applied.push(name);
}
const temperature = attrs.get('crs:Temperature');
const tint = attrs.get('crs:Tint');
if (temperature !== undefined) {
const kelvin = Number(temperature);
// Lightroom's Temperature is absolute Kelvin; the absolute control here is
// defined against a 5500 K daylight reference, so the value transfers
// directly and the panel shows the same number.
if (Number.isFinite(kelvin) && kelvin >= 1500 && kelvin <= 15000) {
next.kelvin = kelvin;
applied.push('Temperature');
}
}
if (tint !== undefined) {
const value = Number(tint);
if (Number.isFinite(value)) {
next.tint = Math.max(-100, Math.min(100, value));
applied.push('Tint');
}
}
if (!applied.length) throw new Error('No develop settings found in that sidecar');
return { edits: normalizeEdits(next), source: 'lightroom', applied };
}
/** Opens the OS picker and returns the sidecar text, or null when cancelled. */
export function readXmpFile(): Promise<string | null> {
return new Promise((resolve, reject) => {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.xmp,application/rdf+xml,text/xml,application/xml';
input.onchange = () => {
const file = input.files?.[0];
if (!file) {
resolve(null);
return;
}
file.text().then(resolve, reject);
};
input.click();
});
}
/**
* Sidecars named after the file next to the original, the way Lightroom writes
* them, plus the download helper used by the library action.
*/
export function downloadXmp(photo: PhotoRecord) {
const blob = new Blob([editsToXmp(photo.edits, photo)], { type: 'application/rdf+xml' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = xmpFileName(photo.name);
document.body.appendChild(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 4000);
}