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
+121 -26
View File
@@ -62,16 +62,22 @@ changing the current filters.
**Develop.** A WebGL2 multi-pass pipeline (`src/gl/renderer.ts`), per photo,
non-destructive:
- white balance, exposure, contrast, highlights/shadows/whites/blacks
- texture, clarity, dehaze, vibrance, saturation, black & white mix
- RGB and per-channel tone curves
- 8-band HSL colour mixer, split toning / colour grading
- white balance as a relative Temp/Tint offset or an absolute Kelvin value with a
5500 K daylight reference, exposure, contrast, and hue-preserving
highlights/shadows/whites/blacks
- per-channel highlight recovery, texture, clarity, per-pixel dehaze, vibrance,
saturation, black & white mix
- input levels (black point, white point, midtone gamma), RGB and per-channel tone
curves
- 8-band HSL colour mixer evaluated in OkLCh (hue and chroma changes keep their
perceived lightness), split toning / colour grading
- sharpening, luminance noise reduction
- vignette, grain
- crop with nine aspect ratios, straighten, 90° rotation, flips
- local adjustments (up to four layers): brush, linear gradient and radial masks with
feather, invert, luminance/hue/saturation ranges, and per-layer exposure, contrast,
highlights, shadows, temperature, tint and saturation. Masks follow crops, zoom,
- local adjustments (up to eight layers): brush, linear gradient and radial masks
with feather, invert, luminance/hue/saturation ranges, and per-layer exposure,
contrast, highlights, shadows, whites, blacks, temperature, tint, saturation,
vibrance, hue, texture, clarity, dehaze and sharpening. Masks follow crops, zoom,
healing and lens correction; Copy mask / Paste mask move one layer between photos
- full Lensfun profiles: distortion, transverse chromatic aberration and vignetting
from the official database, with manual lens search, "Match EXIF lens"
@@ -87,8 +93,8 @@ non-destructive:
- histogram, built-in and saved presets, history with undo/redo, selective
copy/paste and batch sync, named snapshots, virtual copies, before/after (**\**)
- on-device auto subject, sky and background masks (no model download), an
ISO/camera-aware noise starting point, edge-aware lens-softness compensation, and an
approximate paper soft-proof preview
ISO/camera-aware noise starting point, edge-aware lens-softness compensation, and soft
proofing through a loaded printer ICC profile (or a paper simulation when none is)
- HDR merge with alignment, horizontal panorama stitching and focus stacking; each
result is added to the catalog as a new editable photo
- browser print layouts (A4, Letter, 5×7) rendered through the develop pipeline
@@ -97,7 +103,9 @@ non-destructive:
Clients need no account: they see that event's live photos, heart favourites, leave
per-photo comments, mark a photo approved or needing changes, and download proofs
individually or as one ZIP. Feedback shows up on the library grid and in the "Client
picks", "Approved" and "Changes" filters. Revoking a link drops its picks and feedback.
picks", "Approved" and "Changes" filters. Each link can carry a password, a closing
date, a download cap or downloads switched off, and a watermark that is rendered into
newly published proofs. Revoking a link drops its picks, feedback and access settings.
**Team accounts.** The first signup becomes the admin. Admins create single-use invite
links (`/join/<token>`) with an optional email lock and 1–30 day expiry, copy them from
@@ -111,6 +119,22 @@ quota, schedule a 24-hour cleanup of the oldest content, send a warning immediat
cancel a scheduled cleanup. Cleanups stop at a target percentage of the quota instead
of deleting the whole original plan.
**Tethering.** Watch a folder on the server for an event: the editor polls it, pulls
each new JPEG/TIFF/WebP/raw, imports it through the normal path (raw decode, metadata,
cloud mirroring) and only then removes the file from the folder. Point a capture app or
a transfer folder at `<data>/tether/<event>`; nothing is lost if the tab closes.
**Cull assist.** Run a focus and duplicate pass over the selection from the command
palette. Every frame is scored from its own thumbnail with a Laplacian variance, and
near-duplicates are grouped by 64-bit difference hash, so the sharpest frame of a
burst can be kept and the alternatives flagged in one action. Nothing is rated or
rejected without confirmation.
**Sidecars.** Export the selected photos' develop settings as Lightroom-style `.xmp`
sidecars (crs: attributes plus a private payload for the rest of the grade) and import
a sidecar back onto a photo. Importing keeps the crop, masks and lens profile for every
field the file does not mention.
**Catalog workflow.** Editable title, caption, creator, copyright and keyword chips
with a keyword library and reusable metadata presets. Save the current filters and sort
order as a smart collection. Virtual copies share the master file but keep independent
@@ -118,9 +142,10 @@ edits; named snapshots preserve alternative looks.
**Export and print.** JPEG, PNG, WebP or uncompressed 16-bit TIFF; quality; resize by
long edge or percent; filename template (`{name}`, `{date}`, `{time}`, `{index}`); saved
export recipes; output sharpening; watermark; XMP metadata embedded in JPEGs; an
embedded sRGB ICC profile; batch export as one ZIP or separate files. Full-resolution
export runs through the same renderer as the screen preview.
export recipes; output sharpening; watermark; XMP metadata embedded in JPEGs; sRGB,
Display P3 or Adobe RGB output with a matching generated ICC profile (JPEG/TIFF); batch
export as one ZIP or separate files. Full-resolution export runs through the same
renderer as the screen preview.
**Administration.** Users, roles, invites, catalog backup/restore, per-account quotas,
email settings and a storage relocation tool are all in one panel.
@@ -204,6 +229,7 @@ storage, while quotas are stored per account in the database.
| `LUMINARY_INVITE` | *(empty)* | Shared registration code for teammates; personal invite links work without it |
| `LUMINARY_MAX_UPLOAD` | `314572800` (300 MB) | Largest accepted upload, in bytes |
| `LUMINARY_RAW_EDGE` | `6000` | Long edge of the editable JPEG proxy made from a raw |
| `LUMINARY_16BIT` | `1` | Also keep the decoded samples as a 16-bit PNG beside the raw proxy; `0` saves the disk and download it costs, at the price of grading an 8-bit source |
| `LUMINARY_RAW_WORKERS` | `min(4, cores−1)` | Concurrent LibRaw decoders; each holds a worker and a few hundred MB |
| `LUMINARY_RAW_IDLE_MS` | `90000` | Idle decoders are disposed after this to release memory |
| `LUMINARY_DENOISE_WORKERS` | `min(4, cores−1)` | Concurrent detail-denoise jobs (read directly from the environment) |
@@ -427,9 +453,14 @@ Data directory
| `src/lib/import.ts` | File ingest, EXIF read, preview/thumb creation, upload scheduling |
| `src/lib/export.ts` | Renderer-driven export, recipes, watermark, filenames, ZIP |
| `src/lib/tiff.ts`, `icc.ts` | Dependency-free 16-bit TIFF writer and sRGB profile |
| `src/lib/preview16.ts` | 16-bit raw-proxy PNG parser, camera matrix and half-float conversion for the RGBA16F source texture |
| `src/lib/softProof.ts` | ICC parsing (lut8/lut16/mAB), printer A2B/B2A round trip and the 3D proof cube |
| `src/lib/dcp.ts` | DCP tag reader and the camera-to-sRGB matrix recipe |
| `src/lib/lensfun.ts`, `lensNames.ts`, `lensDefaults.ts` | Lensfun client, EXIF matching, saved defaults |
| `src/lib/merge.ts` | HDR / panorama / focus-stack composition |
| `src/lib/autoMask.ts`, `noiseProfile.ts` | On-device masks and ISO-aware noise starting points |
| `src/lib/xmp.ts` | Lightroom-compatible XMP sidecar reader/writer |
| `src/lib/cull.ts` | Focus scoring and duplicate hashing for cull assist |
| `src/lib/curves.ts`, `whiteBalance.ts`, `clipPreview.ts`, `presets.ts` | Curve sampling, WB maths, clipping display, presets |
| `docs/user-guide/` | Source of the in-app user guide (`guide.html`), also shipped as PDF |
@@ -510,6 +541,12 @@ routes are public and are gated only by the share token.
| --- | --- | --- | --- |
| GET | `/api/sync` | session | Everything the workspace needs: user, events, photos, presets, proof summary |
| GET | `/api/proofs` | session | Client pick/comment/review summary for the owner's events |
| PUT | `/api/events/:id/share/settings` | owner | Password, expiry, watermark, download switch and cap for the proofing link |
| GET | `/api/galleries/:token/status` | public | Whether the link is locked, its expiry and whether downloads are allowed |
| POST | `/api/galleries/:token/unlock` | public | Exchange the gallery password for a link-scoped unlock cookie |
| GET | `/api/events/:id/tether` | owner | Watch-folder path and the frames waiting in it |
| GET | `/api/events/:id/tether/file?name=` | owner | Stream one waiting frame to the editor |
| DELETE | `/api/events/:id/tether/file?name=` | owner | Remove a frame after it imported |
| PUT | `/api/presets` | session | Replace the stored preset library |
| PUT | `/api/events/:id` | owner | Upsert an event record |
| DELETE | `/api/events/:id` | owner | Delete an event (photos are handled separately) |
@@ -783,9 +820,22 @@ for album assets inline first, retries with `withoutAssets=false`, and falls bac
The browser cannot demosaic camera raw, so the server does it during upload:
1. The original file is stored byte-for-byte in `originals/` with its real extension.
2. LibRaw (`libraw-wasm`) opens it in a pooled worker with camera white balance, sRGB
output and the container's orientation, then `sharp` encodes an editable JPEG proxy
at `LUMINARY_RAW_EDGE` (6000 px by default).
2. LibRaw (`libraw-wasm`) opens it in a pooled worker with camera white balance and the
container's orientation and returns the frame **before** any output colourspace
(`outputColor: 0`). The camera-to-sRGB step is then the body's own `rgb_cam` matrix,
applied in `server/color.mjs` — the same 3×3 matrix the editor applies to the sidecar,
so changing the camera profile is a matrix swap rather than a second decode. One
white point is chosen for the frame from the matrixed pixels (99th percentile, the
clipping policy LibRaw's auto-bright targets) and baked into both outputs; LibRaw's
own auto-bright measures each output path separately and would leave the JPEG a third
of a stop away from the sidecar. `sharp` encodes the editable JPEG proxy at
`LUMINARY_RAW_EDGE` (6000 px by default). The same decode also writes a 16-bit PNG of
the camera samples beside it (`previews/<id>.p16.png`, roughly 25× the JPEG) with the
matrix in a `tEXt` chunk: the editor inflates that sidecar into an `RGBA16F` source
texture and applies `rgb_cam` in the grade shader, so the grade has 65,536 levels per
channel instead of 256. A photo without a sidecar — one imported before this existed,
a non-raw file, or a build with `LUMINARY_16BIT=0` — simply grades the JPEG, so
nothing breaks either way.
3. If LibRaw cannot open the file, the largest JPEG embedded in the container is
extracted and normalised instead. The grid marks such photos `RAW` and the Info panel
reports which engine produced the proxy, so exotic or very new cameras still import.
@@ -796,6 +846,17 @@ Formats: CR2/CR3/CRW, NEF/NRW, ARW/SRF/SR2, ORF, RW2/RWL/RAW, RAF, PEF, DNG, SRW
FFF, IIQ, X3F, ERF, K25/KDC, DCR, MOS, MRW, MEF, SRAW. Content sniffing checks the
container signature before wasting a decode attempt.
**Camera-native conversion, measured.** `rgb_cam` is applied to the sRGB-decoded camera
samples; `outputColor: 0` output is sRGB-encoded, not linear (a power curve fits it
1.8 ΔE worse). Against LibRaw's sRGB + auto-bright output on this repository's test
raws, the new proxy sits at mean ΔE 0.3–2.4 on normally exposed frames with the same
~1 % highlight clipping, and 5.5 on one very dark frame where the two auto-bright
policies disagree most — one shared white point cannot match a per-path heuristic
exactly. Applying the sidecar's matrix in the shader reproduces the server-encoded
proxy to within one 8-bit code, so the two outputs cannot drift apart. Deriving the
same matrix from a DCP `ColorMatrix1` — `inverse(rowNormalise(ColorMatrix · xyz_rgb))`
— matches LibRaw's `rgb_cam` to 2.2e-5 on a D700 NEF and 2.7e-5 on a 5D Mark II CR2.
**Parallel import.** Decoding runs in a bounded pool of LibRaw workers (default
`min(4, cores−1)`, `LUMINARY_RAW_WORKERS`), and the browser uploads several files at a
time. Each instance owns one worker thread; extra jobs queue. Idle instances are
@@ -897,7 +958,7 @@ Conventions worth knowing before changing code:
### Tests
`npm test` runs six Vitest files, all pure-logic:
`npm test` runs the pure-logic Vitest suite:
| File | Covers |
| --- | --- |
@@ -907,6 +968,9 @@ Conventions worth knowing before changing code:
| `src/lib/lensNames.test.ts` | EXIF lens-name normalisation, search variants and match scoring |
| `src/lib/lensDefaults.test.ts` | Camera + lens default selection and rejection rules |
| `src/lib/editSections.test.ts` | Selective settings copy and the ISO-aware auto-noise curve |
| `src/lib/preview16.test.ts` | 16-bit PNG proxy parsing, row flip, half-float encoding and the camera matrix chunk |
| `src/lib/dcp.test.ts` | DCP tag parsing and the camera matrix recipe against LibRaw's own values |
| `src/lib/softProof.test.ts` | ICC parsing (including counted lut16 tables), the printer round trip, gamut threshold and CMYK profiles |
There are no server integration tests; the API is exercised through the UI.
@@ -931,20 +995,51 @@ There are no server integration tests; the API is exercised through the UI.
## Limitations
- **Not a cloud service.** No hosted deployment, no tethered capture, no sync client
beyond one browser tab's whole-record push. The last writer wins per photo; it is
- **Not a cloud service.** No hosted deployment and no camera driver: tethering is a
server drop folder, not a PTP/USB connection. No sync client beyond one browser tab's
whole-record push. The last writer wins per photo; it is
designed for a handful of people, not concurrent batch workflows.
- **Per-account catalogs.** Workspaces are private to their owner; there is no shared
library between two members. Collaboration happens through client proofing links and
the admin overview.
- **Proxy-bounded raw.** Raw editing works on the demosaiced JPEG proxy (6000 px
default), not the sensor mosaic; export size is bounded by the proxy.
- **Approximate tools.** Temperature/tint are relative to the as-shot white balance.
Auto masks are an on-device saliency/colour estimate, not a segmentation model. Soft
proofing approximates paper white, black point and print gamut but does not apply a
printer ICC profile; use the browser print dialog for final ICC handling. The
- **Proxy-bounded raw.** Raw editing works on the demosaiced proxy (6000 px default),
not the sensor mosaic; export size is bounded by the proxy. Raw imports keep two
files: the JPEG proxy every browser can decode, and a 16-bit PNG sidecar of the same
pixels. The editor grades the sidecar as a half-float source texture when it is
present, which is what keeps a heavy shadow lift or a 3200 K white balance from
posterising an 8-bit source; the JPEG and everything derived from it (thumbnails,
denoise renders, proofs) stay 8-bit. A per-photo DCP profile is applied wherever
the sidecar is, i.e. the Develop canvas and exports; grid thumbnails and the compare
view grade the sRGB JPEG, which already has the body matrix baked in, so they do not
show a different camera profile. The sidecar costs about 25× the JPEG in disk, one download per photo at open time and
one extra texture in GPU memory (about 8 bytes per pixel), so `LUMINARY_16BIT=0` turns
it off for libraries that would rather have the space. Either way the 16-bit TIFF export writes 65,536
samples per channel from the `RGBA16F` render target, so its precision is only more
than the source's when the sidecar was available; it never invents detail the decode
did not produce.
- **Approximate tools.** The relative Temp/Tint sliders and the absolute Kelvin
control are display-space gains; they are not a camera-specific white-balance
matrix pair. Raw decode uses the camera's own matrix; a DCP `ColorMatrix` reproduces
it exactly (`src/lib/dcp.ts` parses the file and derives the matrix), and **Develop →
Camera profile** loads a `.dcp` per photo, storing the derived 9-number matrix in
the edit so it follows presets, snapshots and XMP. The picker is available only on
camera-native sidecars; an older sRGB proxy needs a RAW reprocess first.
Auto masks are an on-device colour-model segmentation (border histogram, Otsu split,
connected components), not a trained segmentation network, so a subject that shares
its colour with the background needs a brush pass. Soft
proofing applies a printer profile's real A2B/B2A tables when one is loaded
(**Soft proofing → Load ICC profile**), and falls back to paper white, black point and
a gamut approximation otherwise. The profile is session state rather than part of the
edit, and the print dialog still does its own colour management. Both LUT layouts are
read: v2 `lut16` with fixed 256-entry tables and the counted v4 layout that MOAB/Epson
paper profiles and Ghostscript's press profiles actually use (4096 entries, counts at
offsets 48/50). Against LittleCMS on a MOAB/Epson ET-8550 profile the cube agrees to a
mean 0.97 and p95 3 of 255 per channel. The gamut warning uses a ΔE76 round-trip
threshold of 2.5 with no endpoint rule: on the repository's photos that flags 6–8 % of
pixels, the 90th percentile round trip is 1.5 ΔE, and the neutral ramp stays clean. The
auto-noise profile is an ISO/camera heuristic over the existing sliders, not a
calibrated sensor model.
calibrated sensor model, and sharpening is multi-scale unsharp masking rather than
deconvolution.
- **Merge scope.** HDR, panorama and focus stacking are translation-aligned and aimed at
bracketed, stacked or horizontal sequences, not handheld multi-row composites. They
compose at a reduced working edge (2600 px).
+144
View File
@@ -0,0 +1,144 @@
/**
* Camera-native colour conversion for the raw pipeline.
*
* LibRaw can hand back the demosaiced frame before it applies any output
* colourspace (`outputColor: 0`). Those samples are the camera's own RGB,
* white-balanced and gamma encoded, which is what a camera profile needs: the
* camera-to-sRGB step becomes a matrix the editor can swap out without
* decoding the raw again.
*
* One white point is chosen for the whole frame from the *converted* pixels, so
* the JPEG proxy and the 16-bit sidecar share an exposure. LibRaw's own
* auto-bright is deliberately off: it measures each output path separately,
* which leaves the two outputs a third of a stop apart.
*/
export function srgbToLinear(value) {
const v = value <= 0 ? 0 : value >= 1 ? 1 : value;
return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
}
export function linearToSrgb(value) {
const v = value <= 0 ? 0 : value >= 1 ? 1 : value;
return v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;
}
let decodeTable = null;
let encodeTable = null;
/** 16-bit sample -> linear light, for the camera's own gamma encoding. */
function linearTable() {
if (!decodeTable) {
decodeTable = new Float32Array(65536);
for (let i = 0; i < 65536; i++) decodeTable[i] = srgbToLinear(i / 65535);
}
return decodeTable;
}
/** Linear light (indexed as a 16-bit fraction) -> 8-bit sRGB. */
function encodedTable() {
if (!encodeTable) {
encodeTable = new Uint8Array(65536);
for (let i = 0; i < 65536; i++) {
encodeTable[i] = Math.round(linearToSrgb(i / 65535) * 255);
}
}
return encodeTable;
}
/** Flattens the metadata's 4x4 `rgb_cam` into the 3x3 camera -> sRGB matrix. */
export function readRgbCam(meta) {
const raw = meta?.color_data?.rgb_cam;
if (!Array.isArray(raw) || raw.length < 3) return null;
const matrix = [];
for (let row = 0; row < 3; row++) {
const values = raw[row];
if (!Array.isArray(values) || values.length < 3) return null;
for (let col = 0; col < 3; col++) {
const value = Number(values[col]);
if (!Number.isFinite(value)) return null;
matrix.push(value);
}
}
// A zero matrix would render the whole frame black; that is a metadata
// failure, not a look, so fall back to LibRaw's own conversion.
if (matrix.every((value) => Math.abs(value) < 1e-6)) return null;
return matrix;
}
/**
* Converts a camera-native 16-bit frame into the two buffers the editor needs,
* in place:
*
* - `rgb8` the sRGB proxy the JPEG is encoded from
* - `rgb16` the camera samples, white-point scaled, still camera native
*
* Returns the white point gain that was applied. The gain is baked into both
* buffers, so the client only has to apply the camera matrix; keeping it out of
* the sidecar would mean shipping a second 16-bit table for no benefit.
*/
export function cameraToProxy(rgb16, rgb8, matrix) {
const linear = linearTable();
const encode = encodedTable();
const count = Math.floor(rgb16.length / 3);
const m = matrix ?? [1, 0, 0, 0, 1, 0, 0, 0, 1];
// Pass 1: where does the fastest channel sit? Choosing the white point after
// the matrix keeps highlight clipping at about the same 1% LibRaw targets,
// instead of clipping whatever the matrix pushes past 1 on top of that.
const hist = new Uint32Array(65536);
for (let i = 0; i < count; i++) {
const s = i * 3;
const r = linear[rgb16[s]];
const g = linear[rgb16[s + 1]];
const b = linear[rgb16[s + 2]];
const max = Math.max(
m[0] * r + m[1] * g + m[2] * b,
m[3] * r + m[4] * g + m[5] * b,
m[6] * r + m[7] * g + m[8] * b,
);
const bin = max <= 0 ? 0 : max >= 1 ? 65535 : Math.round(max * 65535);
hist[bin]++;
}
let seen = 0;
let p99 = 65535;
const target = count * 0.99;
for (let i = 0; i < 65536; i++) {
seen += hist[i];
if (seen >= target) {
p99 = i;
break;
}
}
// Cap the gain: a nearly black frame is a real photograph, not a reason to
// multiply read noise by fifty.
const gain = Math.min(48, Math.max(0.25, 65535 / Math.max(1, p99)));
// Camera samples stay gamma encoded, so a shadow lift still has 16 bits of
// encoded detail to work from rather than 16 bits of linear light.
const camera = new Uint16Array(65536);
for (let i = 0; i < 65536; i++) {
camera[i] = Math.round(linearToSrgb(linear[i] * gain) * 65535);
}
// Pass 2: write both buffers.
for (let i = 0; i < count; i++) {
const s = i * 3;
const r = linear[rgb16[s]] * gain;
const g = linear[rgb16[s + 1]] * gain;
const b = linear[rgb16[s + 2]] * gain;
rgb8[s] = encode[clampIndex(m[0] * r + m[1] * g + m[2] * b)];
rgb8[s + 1] = encode[clampIndex(m[3] * r + m[4] * g + m[5] * b)];
rgb8[s + 2] = encode[clampIndex(m[6] * r + m[7] * g + m[8] * b)];
rgb16[s] = camera[rgb16[s]];
rgb16[s + 1] = camera[rgb16[s + 1]];
rgb16[s + 2] = camera[rgb16[s + 2]];
}
return gain;
}
function clampIndex(value) {
if (!(value > 0)) return 0;
if (value >= 1) return 65535;
return Math.round(value * 65535);
}
+7
View File
@@ -75,6 +75,13 @@ export const SMTP_FROM = setting('SMTP_FROM', SMTP_USER);
/** Long edge used for the editable proxy of raw files. */
export const RAW_PREVIEW_EDGE = Number(setting('RAW_EDGE', '6000'));
/**
* Also store the 16-bit samples LibRaw decoded as a sidecar next to the JPEG
* proxy. It costs roughly 25x the JPEG in disk and download, but it is the only
* way the editor can grade from more than 256 levels per channel.
*/
export const RAW_16BIT = setting('16BIT', '1') !== '0';
export const SESSION_DAYS = 30;
/** How many raws decode at once. One core is left for the HTTP server. */
+77
View File
@@ -89,6 +89,18 @@ db.exec(`
CREATE INDEX IF NOT EXISTS gallery_reviews_token ON gallery_reviews(token);
CREATE TABLE IF NOT EXISTS gallery_settings (
token TEXT PRIMARY KEY,
password_hash TEXT NOT NULL DEFAULT '',
password_salt TEXT NOT NULL DEFAULT '',
expires_at INTEGER,
watermark TEXT NOT NULL DEFAULT '',
allow_downloads INTEGER NOT NULL DEFAULT 1,
download_cap INTEGER NOT NULL DEFAULT 0,
download_count INTEGER NOT NULL DEFAULT 0,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS invites (
token TEXT PRIMARY KEY,
email TEXT NOT NULL DEFAULT '',
@@ -607,6 +619,71 @@ export function picksByOwner(ownerId) {
}));
}
const gallerySettingsStmt = db.prepare('SELECT * FROM gallery_settings WHERE token = ?');
const upsertGallerySettings = db.prepare(`
INSERT INTO gallery_settings
(token, password_hash, password_salt, expires_at, watermark, allow_downloads, download_cap, download_count, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(token) DO UPDATE SET
password_hash = excluded.password_hash,
password_salt = excluded.password_salt,
expires_at = excluded.expires_at,
watermark = excluded.watermark,
allow_downloads = excluded.allow_downloads,
download_cap = excluded.download_cap,
updated_at = excluded.updated_at
`);
const deleteGallerySettings = db.prepare('DELETE FROM gallery_settings WHERE token = ?');
const bumpGalleryDownload = db.prepare(
'UPDATE gallery_settings SET download_count = download_count + 1 WHERE token = ?',
);
const readGalleryDownloads = db.prepare(
'SELECT download_count FROM gallery_settings WHERE token = ?',
);
/** Access rules for a public proofing link; defaults when none were saved. */
export function gallerySettingsFor(token) {
const row = gallerySettingsStmt.get(token);
return {
passwordHash: row?.password_hash ?? '',
passwordSalt: row?.password_salt ?? '',
expiresAt: row?.expires_at ?? null,
watermark: row?.watermark ?? '',
allowDownloads: row ? Boolean(row.allow_downloads) : true,
downloadCap: row?.download_cap ?? 0,
downloadCount: row?.download_count ?? 0,
};
}
/**
* The download counter is deliberately preserved across settings edits: an
* owner tightening or loosening a cap must not hand out a fresh allowance.
*/
export function saveGallerySettings(token, settings) {
upsertGallerySettings.run(
token,
settings.passwordHash ?? '',
settings.passwordSalt ?? '',
settings.expiresAt ?? null,
settings.watermark ?? '',
settings.allowDownloads === false ? 0 : 1,
Math.max(0, Math.round(settings.downloadCap ?? 0)),
0,
Date.now(),
);
return gallerySettingsFor(token);
}
export function clearGallerySettings(token) {
deleteGallerySettings.run(token);
}
/** Counts a gallery download and reports the new total, or 0 when uncapped. */
export function noteGalleryDownload(token) {
bumpGalleryDownload.run(token);
return readGalleryDownloads.get(token)?.download_count ?? 0;
}
export function galleryPick(token, photoId, clientId, clientName, picked) {
if (!picked) {
q.deletePick.run(token, photoId, clientId);
+93 -1
View File
@@ -68,7 +68,99 @@ export function encodePng(rgb, width, height) {
]);
}
/** Encode an interleaved RGB byte buffer as JPEG (sharp) or PNG (fallback). */
/**
* Box-average a 16-bit RGB image down to the proxy size. sharp's raw pipeline
* does not round-trip 16-bit samples faithfully, and this keeps the sidecar
* pixel-aligned with the JPEG that was encoded by a different library.
*/
export function resizeRgb16(rgb16, width, height, tw, th) {
if (width === tw && height === th) return rgb16;
const out = new Uint16Array(tw * th * 3);
const fx = width / tw;
const fy = height / th;
for (let y = 0; y < th; y++) {
const y0 = Math.floor(y * fy);
const y1 = Math.min(height, Math.max(y0 + 1, Math.ceil((y + 1) * fy)));
for (let x = 0; x < tw; x++) {
const x0 = Math.floor(x * fx);
const x1 = Math.min(width, Math.max(x0 + 1, Math.ceil((x + 1) * fx)));
let r = 0;
let g = 0;
let b = 0;
let n = 0;
for (let sy = y0; sy < y1; sy++) {
let at = (sy * width + x0) * 3;
for (let sx = x0; sx < x1; sx++) {
r += rgb16[at];
g += rgb16[at + 1];
b += rgb16[at + 2];
at += 3;
n += 1;
}
}
const d = (y * tw + x) * 3;
out[d] = Math.round(r / n);
out[d + 1] = Math.round(g / n);
out[d + 2] = Math.round(b / n);
}
}
return out;
}
/**
* 16-bit RGB PNG (colour type 2, no interlacing, Sub-filtered rows). The editor
* inflates this in the browser and uploads it as a half-float texture, so it has
* to be a standard PNG rather than a private container. Sub filtering subtracts
* each byte from the pixel six bytes to its left, which compresses photographic
* rows far better than storing the samples raw.
*
* `matrix` is the camera-to-sRGB matrix (9 numbers, row major). It is written to
* a tEXt chunk because the sidecar holds camera-native samples: without it the
* client would have to guess the conversion, and a self-describing sidecar also
* keeps working for imports that predate a catalogue migration.
*/
export function encodePng16(rgb16, width, height, matrix = null) {
const stride = width * 6;
const raw = Buffer.alloc((stride + 1) * height);
const row = Buffer.alloc(stride);
for (let y = 0; y < height; y++) {
let at = y * width * 3;
for (let i = 0; i < stride; i += 2) {
row.writeUInt16BE(rgb16[at++] & 0xffff, i);
}
const base = y * (stride + 1);
raw[base] = 1;
for (let i = 0; i < stride; i++) {
raw[base + 1 + i] = (row[i] - (i >= 6 ? row[i - 6] : 0)) & 0xff;
}
}
const idat = zlib.deflateSync(raw, { level: 6 });
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(width, 0);
ihdr.writeUInt32BE(height, 4);
ihdr[8] = 16;
ihdr[9] = 2;
ihdr[10] = 0;
ihdr[11] = 0;
ihdr[12] = 0;
return Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
chunk('IHDR', ihdr),
...(matrix && matrix.length === 9
? [
chunk(
'tEXt',
Buffer.from(
`rgbCam\0${matrix.map((value) => Number(value).toFixed(8)).join(',')}`,
'latin1',
),
),
]
: []),
chunk('IDAT', idat),
chunk('IEND', Buffer.alloc(0)),
]);
}
export async function encodeRgb(rgb, width, height, quality = 92, maxEdge = 0) {
const sharp = await loadSharp();
if (!sharp) {
+334 -16
View File
@@ -56,16 +56,19 @@ import {
defaultRoot,
findOriginal,
findPreview,
findPreview16,
findProof,
findProofThumb,
findThumb,
isCustomRoot,
originalTarget,
removeAsset,
removePreview16,
setStorageRoot,
storageBytes,
storageRoot,
writePreview,
writePreview16,
writeProof,
writeProofThumb,
writeThumb,
@@ -238,6 +241,77 @@ function normalizePhotoMime(value, name = '') {
return PHOTO_MIME_BY_EXT[ext] ?? 'application/octet-stream';
}
import {
gallerySettingsFor,
saveGallerySettings,
clearGallerySettings,
noteGalleryDownload,
} from './db.mjs';
/** Passwords are hashed per link with a random salt, so a database dump is not a key. */
function hashGalleryPassword(password, salt) {
return crypto.scryptSync(password, salt, 32).toString('hex');
}
/* Unlocked galleries live in memory: a restart asks for the password again. */
const galleryUnlocks = new Map();
const GALLERY_UNLOCK_MS = 12 * 3600 * 1000;
const galleryCookie = (token) => `lumg_${token}`;
/**
* One check for every public gallery route: revoked link, expiry, password.
* A locked gallery is a 401 so the page can show the password prompt instead
* of claiming the shoot is gone.
*/
function galleryGate(req, token) {
const shared = eventByShareToken(token);
if (!shared) {
return { ok: false, status: 404, message: 'This proofing gallery is no longer available' };
}
const settings = gallerySettingsFor(token);
if (settings.expiresAt && Date.now() > settings.expiresAt) {
return { ok: false, status: 410, message: 'This proofing gallery has expired' };
}
if (settings.passwordHash) {
const cookie = parseCookies(req)[galleryCookie(token)];
const entry = galleryUnlocks.get(token);
const valid =
cookie && entry && entry.key === cookie && entry.expires > Date.now()
? true
: false;
if (!valid) {
return {
ok: false,
status: 401,
message: 'This gallery is password protected',
locked: true,
};
}
}
return { ok: true, shared, settings };
}
/** Writes the refusal and returns true when the caller must stop. */
function galleryDenied(req, res, token) {
const gate = galleryGate(req, token);
if (gate.ok) return false;
error(res, gate.status, gate.message);
return true;
}
/** Refuses a download when the link turned downloads off or used its allowance. */
function galleryDownloadDenied(res, token, settings) {
if (!settings.allowDownloads) {
error(res, 403, 'Downloads are disabled for this gallery');
return true;
}
if (settings.downloadCap > 0 && settings.downloadCount >= settings.downloadCap) {
error(res, 403, 'This gallery has reached its download limit');
return true;
}
return false;
}
function parseCookies(req) {
const out = {};
for (const part of String(req.headers.cookie ?? '').split(';')) {
@@ -1315,6 +1389,103 @@ route('GET', '/api/events/:id/share', async ({ req, res, params }) => {
.map((p) => ({ photoId: p.photoId, clientName: p.clientName }))
: [],
feedback,
settings: token
? (() => {
const saved = gallerySettingsFor(token);
return {
passwordSet: Boolean(saved.passwordHash),
expiresAt: saved.expiresAt,
watermark: saved.watermark,
allowDownloads: saved.allowDownloads,
downloadCap: saved.downloadCap,
downloadCount: saved.downloadCount,
};
})()
: null,
});
});
/** Owner-side security settings for the proofing link. */
route('PUT', '/api/events/:id/share/settings', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event');
const token = shareTokenFor(params.id);
if (!token) return error(res, 404, 'This event has no proofing link yet');
const body = await readJson(req, 64 * 1024);
const current = gallerySettingsFor(token);
let passwordHash = current.passwordHash;
let passwordSalt = current.passwordSalt;
if (typeof body.password === 'string') {
const password = body.password.trim();
if (password === '') {
passwordHash = '';
passwordSalt = '';
} else if (password.length < 4) {
return error(res, 400, 'Use at least 4 characters for the gallery password');
} else {
passwordSalt = crypto.randomBytes(12).toString('hex');
passwordHash = hashGalleryPassword(password, passwordSalt);
}
}
const saved = saveGallerySettings(token, {
passwordHash,
passwordSalt,
expiresAt:
typeof body.expiresAt === 'number' && body.expiresAt > 0 ? body.expiresAt : null,
watermark: String(body.watermark ?? '').trim().slice(0, 80),
allowDownloads: body.allowDownloads !== false,
downloadCap: Number.isFinite(Number(body.downloadCap))
? Math.max(0, Math.min(100000, Math.round(Number(body.downloadCap))))
: current.downloadCap,
});
json(res, 200, {
settings: {
passwordSet: Boolean(saved.passwordHash),
expiresAt: saved.expiresAt,
watermark: saved.watermark,
allowDownloads: saved.allowDownloads,
downloadCap: saved.downloadCap,
downloadCount: saved.downloadCount,
},
});
});
/** Public unlock: exchanges the gallery password for a cookie scoped to the link. */
route('POST', '/api/galleries/:token/unlock', async ({ req, res, params }) => {
if (!allowGalleryWrite(req, params.token)) {
return error(res, 429, 'Too many attempts. Try again shortly.', { 'Retry-After': '60' });
}
const gate = galleryGate(req, params.token);
if (!gate.ok && gate.status === 410) return error(res, 410, gate.message);
if (!gate.ok && !gate.locked) return error(res, gate.status, gate.message);
const settings = gallerySettingsFor(params.token);
if (!settings.passwordHash) return json(res, 200, { ok: true });
const body = await readJson(req, 16 * 1024);
const password = String(body.password ?? '');
const attempt = Buffer.from(hashGalleryPassword(password, settings.passwordSalt), 'hex');
const expected = Buffer.from(settings.passwordHash, 'hex');
const ok =
attempt.length === expected.length && crypto.timingSafeEqual(attempt, expected);
if (!ok) return error(res, 403, 'That password does not open this gallery');
const key = crypto.randomBytes(24).toString('base64url');
galleryUnlocks.set(params.token, { key, expires: Date.now() + GALLERY_UNLOCK_MS });
res.setHeader(
'Set-Cookie',
`${galleryCookie(params.token)}=${encodeURIComponent(key)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${GALLERY_UNLOCK_MS / 1000}`,
);
json(res, 200, { ok: true });
});
/** Public: is this link locked or past its expiry? Used before the gallery loads. */
route('GET', '/api/galleries/:token/status', async ({ req, res, params }) => {
const gate = galleryGate(req, params.token);
if (!gate.ok && !gate.locked) return error(res, gate.status, gate.message);
const settings = gate.ok ? gate.settings : gallerySettingsFor(params.token);
json(res, 200, {
locked: !gate.ok,
expiresAt: settings.expiresAt,
allowDownloads: settings.allowDownloads,
});
});
@@ -1334,14 +1505,20 @@ route('DELETE', '/api/events/:id/share', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event');
const token = shareTokenFor(params.id);
setShareToken(params.id, null);
if (token) {
clearGallerySettings(token);
galleryUnlocks.delete(token);
}
json(res, 200, { ok: true });
});
/** Public gallery payload: no session, only the shared event and its photos. */
route('GET', '/api/galleries/:token', async ({ res, params, url }) => {
const shared = eventByShareToken(params.token);
if (!shared) return error(res, 404, 'This proofing gallery is no longer available');
route('GET', '/api/galleries/:token', async ({ req, res, params, url }) => {
const gate = galleryGate(req, params.token);
if (!gate.ok) return error(res, gate.status, gate.message);
const shared = gate.shared;
const clientId = String(url.searchParams.get('client') ?? '').slice(0, 64);
const picks = picksForToken(params.token).filter((p) => p.picked);
const counts = new Map();
@@ -1395,16 +1572,26 @@ route('GET', '/api/galleries/:token', async ({ res, params, url }) => {
photographer: 'Luminary',
photos,
picks: { total: picks.length, clients: new Set(picks.map((p) => p.clientId)).size },
downloads: {
allowed: gate.settings.allowDownloads,
remaining:
gate.settings.downloadCap > 0
? Math.max(0, gate.settings.downloadCap - gate.settings.downloadCount)
: null,
},
watermark: gate.settings.watermark,
});
});
route('GET', '/api/galleries/:token/photos/:id/thumb', async ({ req, res, params }) => {
if (galleryDenied(req, res, params.token)) return;
if (!galleryPhoto(params.token, params.id)) return error(res, 404, 'Not found');
const file = findProofThumb(params.id) ?? (await findThumb(params.id));
return sendFile(req, res, file, 'image/jpeg', 'private, max-age=3600');
});
route('GET', '/api/galleries/:token/photos/:id/preview', async ({ req, res, params }) => {
if (galleryDenied(req, res, params.token)) return;
const hit = galleryPhoto(params.token, params.id);
if (!hit) return error(res, 404, 'Not found');
const proof = findProof(params.id);
@@ -1423,6 +1610,9 @@ route('GET', '/api/galleries/:token/photos/:id/preview', async ({ req, res, para
/** Client download of the edited proof, named like the delivered file. */
route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, params }) => {
const gate = galleryGate(req, params.token);
if (!gate.ok) return error(res, gate.status, gate.message);
if (galleryDownloadDenied(res, params.token, gate.settings)) return;
const hit = galleryPhoto(params.token, params.id);
if (!hit) return error(res, 404, 'Not found');
const proof = findProof(params.id);
@@ -1430,6 +1620,7 @@ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, par
const originalName = String(hit.photo.name || 'photo.jpg');
const safe = (proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName).replace(/["\\/:*?<>|]+/g, '-');
const mime = proof ? 'image/jpeg' : normalizePhotoMime(hit.photo.mime, hit.photo.name);
noteGalleryDownload(params.token);
return sendFile(req, res, file, mime, 'private, max-age=3600', {
'Content-Disposition': `attachment; filename="${safe}"`,
});
@@ -1437,8 +1628,10 @@ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, par
/** Download the client's favourites as one ZIP. */
route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, url }) => {
const shared = eventByShareToken(params.token);
if (!shared) return error(res, 404, 'This proofing gallery is no longer available');
const gate = galleryGate(req, params.token);
if (!gate.ok) return error(res, gate.status, gate.message);
if (galleryDownloadDenied(res, params.token, gate.settings)) return;
const shared = gate.shared;
const clientId = String(url.searchParams.get('client') ?? '').slice(0, 64);
const picks = picksForToken(params.token).filter(
(pick) => pick.picked && (!clientId || pick.clientId === clientId),
@@ -1487,6 +1680,7 @@ route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, ur
if (!entries.length) return error(res, 404, 'There are no downloadable favourites yet');
const archive = createZip(entries);
noteGalleryDownload(params.token);
const eventName = String(shared.event.name || 'proofing')
.replace(/[^a-z0-9._ -]+/gi, '-')
.trim() || 'proofing';
@@ -1502,13 +1696,80 @@ route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, ur
}
});
/* ---------------------------------------------------------------- tether */
/**
* Tethering is a drop folder, not a camera driver: the owner (or a synced
* tethering app) writes frames into one directory per event, and the open
* editor pulls and imports them. Files are removed from the folder only after
* the client confirms the import, so a dropped connection never loses a frame.
*/
const TETHER_EXT = new Set([
'jpg', 'jpeg', 'png', 'tif', 'tiff', 'webp',
'dng', 'cr2', 'cr3', 'nef', 'arw', 'orf', 'rw2', 'raf', 'pef', 'srw',
]);
function tetherFolder(eventId) {
const safe = String(eventId).replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 64) || 'event';
return { safe, dir: path.join(DATA_DIR, 'tether', safe) };
}
/** A bare file name in the drop folder; anything with a path is refused. */
function tetherFileName(raw) {
const name = path.basename(String(raw ?? ''));
if (!name || name !== String(raw ?? '')) return null;
const ext = name.split('.').pop()?.toLowerCase() ?? '';
return TETHER_EXT.has(ext) ? name : null;
}
route('GET', '/api/events/:id/tether', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event');
const folder = tetherFolder(params.id);
await fsp.mkdir(folder.dir, { recursive: true });
const names = await fsp.readdir(folder.dir).catch(() => []);
const files = [];
for (const name of names) {
if (!tetherFileName(name)) continue;
const stat = await fsp.stat(path.join(folder.dir, name)).catch(() => null);
if (!stat?.isFile()) continue;
files.push({ name, size: stat.size, mtime: stat.mtimeMs });
}
files.sort((a, b) => a.mtime - b.mtime);
json(res, 200, { folder: folder.dir, files });
});
route('GET', '/api/events/:id/tether/file', async ({ req, res, params, url }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event');
const name = tetherFileName(url.searchParams.get('name'));
if (!name) return error(res, 400, 'No such file');
const file = path.join(tetherFolder(params.id).dir, name);
const stat = await fsp.stat(file).catch(() => null);
if (!stat?.isFile()) return error(res, 404, 'No such file');
const mime = normalizePhotoMime('', name);
return sendFile(req, res, file, mime, 'no-store', {
'Content-Disposition': `attachment; filename="${name}"`,
});
});
route('DELETE', '/api/events/:id/tether/file', async ({ req, res, params, url }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event');
const name = tetherFileName(url.searchParams.get('name'));
if (!name) return error(res, 400, 'No such file');
await fsp.unlink(path.join(tetherFolder(params.id).dir, name)).catch(() => undefined);
json(res, 200, { ok: true });
});
route('POST', '/api/galleries/:token/comments', async ({ req, res, params }) => {
if (!allowGalleryWrite(req, params.token)) {
return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' });
}
if (!eventByShareToken(params.token)) {
return error(res, 404, 'This proofing gallery is no longer available');
}
if (galleryDenied(req, res, params.token)) return;
const body = await readJson(req, 32 * 1024);
const hit = galleryPhoto(params.token, String(body.photoId ?? ''));
if (!hit) return error(res, 404, 'No such photo');
@@ -1532,9 +1793,7 @@ route('POST', '/api/galleries/:token/reviews', async ({ req, res, params }) => {
if (!allowGalleryWrite(req, params.token)) {
return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' });
}
if (!eventByShareToken(params.token)) {
return error(res, 404, 'This proofing gallery is no longer available');
}
if (galleryDenied(req, res, params.token)) return;
const body = await readJson(req, 16 * 1024);
const hit = galleryPhoto(params.token, String(body.photoId ?? ''));
if (!hit) return error(res, 404, 'No such photo');
@@ -1555,9 +1814,7 @@ route('POST', '/api/galleries/:token/picks', async ({ req, res, params }) => {
if (!allowGalleryWrite(req, params.token)) {
return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' });
}
if (!eventByShareToken(params.token)) {
return error(res, 404, 'This proofing gallery is no longer available');
}
if (galleryDenied(req, res, params.token)) return;
const body = await readJson(req, 32 * 1024);
const hit = galleryPhoto(params.token, String(body.photoId ?? ''));
if (!hit) return error(res, 404, 'No such photo');
@@ -1683,6 +1940,8 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
const data = await fsp.readFile(target);
const decoded = await decodeRaw(data);
await writePreview(params.id, decoded.jpeg, decoded.ext);
if (decoded.preview16) await writePreview16(params.id, decoded.preview16.data);
else await removePreview16(params.id);
const info = await jpegInfo(decoded.jpeg);
return json(res, 201, {
raw: true,
@@ -1705,6 +1964,49 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
return json(res, 201, { raw: false, mime, size });
});
/**
* Re-decode a stored RAW with the current pipeline settings. The original is
* never touched; only the editable proxy, its thumbnail and the cached denoise
* renders are replaced, so existing edits keep working on fresh pixels.
*/
route('POST', '/api/photos/:id/reprocess', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo');
const photo = getPhoto(params.id);
if (!photo?.raw) return error(res, 400, 'Only RAW imports can be reprocessed');
const original = findOriginal(params.id);
if (!original) return error(res, 404, 'The RAW original is missing from storage');
try {
const decoded = await decodeRaw(await fsp.readFile(original));
await writePreview(params.id, decoded.jpeg, decoded.ext);
if (decoded.preview16) await writePreview16(params.id, decoded.preview16.data);
else await removePreview16(params.id);
const thumb = await makeThumb(decoded.jpeg, 560);
if (thumb) await writeThumb(params.id, thumb);
// The old denoised renders were made from the previous proxy.
clearDenoised(params.id);
const info = await jpegInfo(decoded.jpeg);
const width = info?.width || decoded.width || photo.width;
const height = info?.height || decoded.height || photo.height;
// Stamp the record so cached previews and thumbnails are fetched again.
const previewVersion = Date.now();
// Pass the owner explicitly: savePhoto defaults to '' and would orphan the row.
savePhoto({ ...photo, width, height, mime: 'image/jpeg', previewVersion }, Date.now(), user.id);
json(res, 200, {
width,
height,
engine: decoded.engine,
note: decoded.note ?? null,
previewVersion,
previewUrl: `/api/photos/${params.id}/preview?v=${previewVersion}`,
thumbUrl: `/api/photos/${params.id}/thumb?v=${previewVersion}`,
});
} catch (err) {
return error(res, 422, err instanceof Error ? err.message : 'Could not reprocess this RAW file');
}
});
route('GET', '/api/photos/:id/thumb', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
@@ -1784,6 +2086,18 @@ route('GET', '/api/photos/:id/preview', async ({ req, res, params }) => {
return sendFile(req, res, findOriginal(params.id), 'application/octet-stream');
});
/**
* The 16-bit half of a raw proxy. The editor inflates it and uploads it as a
* half-float source texture so a heavy grade keeps its precision; the JPEG at
* `/preview` stays the fallback when this file is absent or too large to fetch.
*/
route('GET', '/api/photos/:id/preview16', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found');
return sendFile(req, res, findPreview16(params.id), 'image/png');
});
route('POST', '/api/photos/:id/denoise', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
@@ -1892,8 +2206,12 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
await writeThumb(params.id, thumb.data);
delete record.thumb;
}
const versionQuery =
typeof record.previewVersion === 'number' && Number.isFinite(record.previewVersion)
? `?v=${record.previewVersion}`
: '';
if (record.raw) {
record.previewUrl = `/api/photos/${params.id}/preview`;
record.previewUrl = `/api/photos/${params.id}/preview${versionQuery}`;
const preview = findPreview(params.id);
if (!preview) {
const original = findOriginal(params.id);
@@ -1905,7 +2223,7 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
}
record.thumbUrl = record.proofAt
? `/api/photos/${params.id}/thumb?proof=${record.proofAt}`
: `/api/photos/${params.id}/thumb`;
: `/api/photos/${params.id}/thumb${versionQuery}`;
savePhoto(record, Date.now(), user.id);
json(res, 200, { photo: record });
});
+93 -19
View File
@@ -1,5 +1,6 @@
import { RAW_PREVIEW_EDGE } from './config.mjs';
import { encodeRgb, jpegInfo, loadSharp, toJpegProxy } from './imaging.mjs';
import { RAW_16BIT, RAW_PREVIEW_EDGE } from './config.mjs';
import { cameraToProxy, readRgbCam } from './color.mjs';
import { encodePng16, encodeRgb, jpegInfo, loadSharp, resizeRgb16, toJpegProxy } from './imaging.mjs';
import { loadLibRaw, rawPool } from './libraw-pool.mjs';
/** Every raw container the pipeline will attempt, grouped by vendor family. */
@@ -57,12 +58,25 @@ export async function rawEngine() {
}
const DECODE_SETTINGS = {
outputBps: 8,
// Decode at 16 bits and let LibRaw blend reconstructed highlights instead of
// clipping them; the 8-bit proxy is downsampled after the rolloff, so a
// recovered sky keeps gradation instead of a flat white patch.
outputBps: 16,
useCameraWb: true,
outputColor: 1, // sRGB
// Camera-native, not sRGB: the camera-to-output matrix is applied here in JS
// (see color.mjs) and again by the editor on the 16-bit sidecar. That makes
// the conversion one swappable matrix instead of a fixed choice inside
// LibRaw, which is what a camera profile needs.
outputColor: 0,
userQual: 3,
highlight: 0,
noAutoBright: false,
highlight: 2,
// One white point for the frame, chosen after the matrix. LibRaw's per-path
// auto-bright measures each output colourspace separately, so the JPEG and
// the camera-native sidecar would disagree by up to half a stop.
noAutoBright: true,
// Always use the camera's own colour matrix. The default only does so when
// white balance is applied, which leaves some bodies on the generic matrix.
useCameraMatrix: 3,
// Use the orientation stored in the raw container: phone and DSLR files often
// record the shot rotated (EXIF 6/8), and demosaicing without it produces a
// sideways proxy that no later step can fix without losing the original axes.
@@ -70,7 +84,13 @@ const DECODE_SETTINGS = {
useFujiRotate: -1,
};
/** Turns one LibRaw `imageData()` result into an interleaved RGB buffer. */
/**
* Turns one LibRaw `imageData()` result into an interleaved RGB buffer.
*
* The 8-bit copy is what the JPEG proxy is encoded from. The 16-bit copy keeps
* every sample LibRaw produced so the editor can upload a half-float source
* texture; without it, a heavy shadow lift is applied to 256 levels per channel.
*/
function toRgb(img) {
if (!img || !img.width || !img.height || !img.data) throw new Error('LibRaw returned no pixels');
const width = Number(img.width);
@@ -79,19 +99,36 @@ function toRgb(img) {
const bits = Number(img.bits ?? 8);
const src = img.data;
const pixelCount = width * height;
const needed = pixelCount * colors * (bits > 8 ? 2 : 1);
if (src.length < needed) {
throw new Error(`LibRaw buffer too small (${src.length} bytes for ${width}×${height}×${colors})`);
const needed = pixelCount * colors;
// libraw-wasm hands back samples, not bytes: with outputBps 16 the buffer is a
// Uint16Array already. Older builds returned the raw 16-bit bytes, so accept
// both shapes instead of assuming one and rejecting every 16-bit decode.
const wide =
bits > 8 && !(src instanceof Uint16Array)
? new Uint16Array(src.buffer, src.byteOffset, Math.floor(src.byteLength / 2))
: src;
if (wide.length < needed) {
throw new Error(
`LibRaw buffer too small (${wide.length} samples for ${width}×${height}×${colors})`,
);
}
const rgb = Buffer.alloc(pixelCount * 3);
let rgb16 = null;
if (bits > 8) {
const view = new Uint16Array(src.buffer, src.byteOffset, Math.floor(src.byteLength / 2));
const view = wide instanceof Uint16Array ? wide : src;
rgb16 = new Uint16Array(pixelCount * 3);
for (let i = 0; i < pixelCount; i++) {
const s = i * colors;
rgb[i * 3] = view[s] >> 8;
rgb[i * 3 + 1] = view[s + 1] >> 8;
rgb[i * 3 + 2] = view[s + 2] >> 8;
const r = view[s];
const g = view[s + 1];
const b = view[s + 2];
rgb[i * 3] = r >> 8;
rgb[i * 3 + 1] = g >> 8;
rgb[i * 3 + 2] = b >> 8;
rgb16[i * 3] = r;
rgb16[i * 3 + 1] = g;
rgb16[i * 3 + 2] = b;
}
} else {
for (let i = 0; i < pixelCount; i++) {
@@ -101,20 +138,29 @@ function toRgb(img) {
rgb[i * 3 + 2] = src[s + 2];
}
}
return { rgb, width, height };
return { rgb, rgb16, width, height };
}
/**
* Full demosaic through a pooled LibRaw worker. `open()` only unpacks the file;
* the pixels come from `imageData()`, which rejects when the camera is unsupported.
*
* `cameraNative` asks for the frame before LibRaw's output matrix, plus the
* matrix metadata. A body LibRaw has no matrix for falls back to the plain sRGB
* decode, which is the same result the pipeline produced before.
*/
async function demosaic(buffer) {
async function demosaic(buffer, cameraNative = true) {
if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed');
return rawPool.use(async (lib) => {
// LibRaw transfers the buffer to its worker, which detaches it here. Hand it
// a copy so the caller's bytes survive for the embedded-preview fallback.
await lib.open(Buffer.from(buffer), DECODE_SETTINGS);
return toRgb(await lib.imageData());
await lib.open(
Buffer.from(buffer),
cameraNative ? DECODE_SETTINGS : { ...DECODE_SETTINGS, outputColor: 1, noAutoBright: false },
);
const image = toRgb(await lib.imageData());
const rgbCam = cameraNative ? readRgbCam(await lib.metadata(true)) : null;
return { ...image, rgbCam };
});
}
@@ -163,10 +209,38 @@ export async function decodeRaw(buffer) {
let librawError = null;
if (looksLikeRaw(buffer)) {
try {
const { rgb, width, height } = await demosaic(buffer);
let frame = await demosaic(buffer, true);
// No usable matrix (an odd body or older engine): decode the familiar sRGB
// way instead of shipping camera samples nobody can convert.
if (!frame.rgbCam || !frame.rgb16) frame = await demosaic(buffer, false);
const { width, height, rgbCam } = frame;
// Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and
// `rgb16` the camera-native sidecar, sharing one white point.
if (rgbCam && frame.rgb16) cameraToProxy(frame.rgb16, frame.rgb, rgbCam);
const { rgb } = frame;
const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE);
// The sidecar must match the JPEG pixel for pixel: the editor swaps the
// two textures at the same uv, so a size disagreement would misalign the
// whole grade. It is optional -- encoding failures leave the JPEG path.
let preview16 = null;
if (frame.rgb16 && RAW_16BIT) {
try {
const scaled = resizeRgb16(frame.rgb16, width, height, encoded.width, encoded.height);
preview16 = {
// The matrix travels with the samples so the editor knows how to
// turn camera RGB into sRGB without a second metadata fetch.
data: encodePng16(scaled, encoded.width, encoded.height, rgbCam),
width: encoded.width,
height: encoded.height,
rgbCam,
};
} catch {
preview16 = null;
}
}
return {
jpeg: encoded.data,
preview16,
width: encoded.width,
height: encoded.height,
engine: 'libraw',
+25
View File
@@ -117,6 +117,30 @@ export function findPreview(id) {
return null;
}
/**
* The 16-bit sidecar for a raw proxy: the samples LibRaw decoded, before the
* JPEG quantised them. Its name keeps a second extension so `findPreview` keeps
* returning the JPEG for browsers and for photos imported before this existed.
*/
export async function writePreview16(id, data) {
ensureDirs();
const target = path.join(storageRoot(), 'previews', `${safeId(id)}.p16.png`);
await fsp.writeFile(target, data);
return target;
}
export function findPreview16(id) {
const safe = lookupId(id);
if (!safe) return null;
const p = path.join(dirs().previews, `${safe}.p16.png`);
return fs.existsSync(p) ? p : null;
}
export async function removePreview16(id) {
const found = findPreview16(id);
if (found) await fsp.rm(found, { force: true });
}
/**
* Denoised proxies, keyed by the hash of the parameters that produced them, so
* switching Amount back to a previous value reuses the file instead of spending
@@ -209,6 +233,7 @@ export async function removeAsset(id) {
const files = [
findOriginal(id),
findPreview(id),
findPreview16(id),
findThumb(id),
findProof(id),
findProofThumb(id),
+361 -2
View File
@@ -15,6 +15,12 @@ import MergeModal from './components/MergeModal';
import PasteSettingsModal from './components/PasteSettingsModal';
import PrintModal from './components/PrintModal';
import ShareModal from './components/ShareModal';
import RawReprocessModal, {
type RawReprocessFailure,
type RawReprocessJob,
} from './components/RawReprocessModal';
import CullAssistModal from './components/CullAssistModal';
import TetherPanel from './components/TetherPanel';
import Shortcuts from './components/Shortcuts';
import Stars, { ColorSwatches, FlagButtons } from './components/Stars';
import TopBar from './components/TopBar';
@@ -37,6 +43,7 @@ import {
pushImmichPhoto,
pushPhoto,
register as apiRegister,
reprocessRawPhoto,
uploadOriginal,
} from './lib/api';
import type { Health, ImmichStatus, ProofSummary, QuotaState, SessionUser } from './lib/api';
@@ -58,8 +65,9 @@ import { COLOR_LABELS, defaultEdits, isEdited, normalizePhoto } from './lib/edit
import { applyEditSections, type EditSectionId } from './lib/editSections';
import type { MergeResult } from './lib/merge';
import { evictBitmap } from './lib/images';
import { uid } from './lib/import';
import { importFiles, uid } from './lib/import';
import { PRESETS } from './lib/presets';
import { downloadXmp, readXmpFile, xmpToEdits } from './lib/xmp';
import type {
Edits,
EventRecord,
@@ -185,6 +193,12 @@ export default function App() {
const [exportOptions, setExportOptions] = useState<ExportOptions>(DEFAULT_EXPORT);
const [exportRecipes, setExportRecipes] = useState<ExportRecipe[]>([]);
const [mergeOpen, setMergeOpen] = useState(false);
const [rawJob, setRawJob] = useState<RawReprocessJob | null>(null);
const [cullOpen, setCullOpen] = useState(false);
const [tetherEventId, setTetherEventId] = useState<string | null>(null);
const rawBusyRef = useRef(false);
const rawCancelRef = useRef(false);
const rawBusy = Boolean(rawJob?.running);
const [printOpen, setPrintOpen] = useState(false);
const saveTimers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
@@ -363,6 +377,151 @@ export default function App() {
[queueSave],
);
/**
* Re-decode selected RAW files on the server, then refresh the cached proxy so
* the grid and Develop pick up the new pixels without a reload. Existing edits
* are kept; only width, height and the decode engine change on the record.
*/
const reprocessRawPhotos = useCallback(
async (ids: string[], options: { eventName?: string } = {}) => {
if (rawBusyRef.current) {
setToast('A RAW reprocess is already running');
return;
}
const targets = photosRef.current.filter(
(photo) => ids.includes(photo.id) && photo.raw && !photo.deletedAt,
);
if (!targets.length) {
setToast('Select RAW photos to reprocess');
return;
}
if (!userRef.current) {
setToast('Sign in to the server to reprocess RAW files');
return;
}
rawBusyRef.current = true;
rawCancelRef.current = false;
const failures: RawReprocessFailure[] = [];
let attempts = 0;
setRawJob({
running: true,
done: 0,
total: targets.length,
current: targets[0].name,
eventName: options.eventName,
failures: [],
});
try {
for (let index = 0; index < targets.length; index += 1) {
if (rawCancelRef.current) break;
const photo = targets[index];
setRawJob((prev) =>
prev ? { ...prev, done: index, current: photo.name, failures: failures.slice() } : prev,
);
try {
const result = await reprocessRawPhoto(photo.id);
const res = await fetch(
`/api/photos/${encodeURIComponent(photo.id)}/preview?v=${Date.now()}`,
{ credentials: 'same-origin' },
);
if (!res.ok) throw new Error('The new preview could not be read');
const blob = await res.blob();
// Replace the cached proxy, then drop the decoded bitmap so the next
// render fetches the new pixels instead of the old ones.
await putAsset(photo.id, blob);
evictBitmap(photo.id);
const version = result.previewVersion ?? Date.now();
updatePhoto(photo.id, {
width: result.width || photo.width,
height: result.height || photo.height,
decode: result.engine ?? photo.decode,
previewVersion: version,
// The stored files keep their names; the query is only a cache buster.
previewUrl:
result.previewUrl ??
`/api/photos/${encodeURIComponent(photo.id)}/preview?v=${version}`,
thumbUrl:
result.thumbUrl ??
`/api/photos/${encodeURIComponent(photo.id)}/thumb?v=${version}`,
});
attempts += 1;
} catch (err) {
failures.push({
name: photo.name,
error: err instanceof Error ? err.message : 'could not be reprocessed',
});
}
setRawJob((prev) =>
prev
? { ...prev, done: index + 1, failures: failures.slice() }
: prev,
);
}
} finally {
rawBusyRef.current = false;
setRawJob((prev) =>
prev
? {
...prev,
running: false,
done: attempts,
failures: failures.slice(),
cancelled: rawCancelRef.current,
}
: prev,
);
}
const succeeded = attempts - failures.length;
const parts = [
`Reprocessed ${succeeded} of ${targets.length} RAW${targets.length === 1 ? '' : 's'}`,
];
if (failures.length) parts.push(`${failures.length} failed`);
if (rawCancelRef.current) parts.push('cancelled');
setToast(parts.join(' · '));
},
[updatePhoto],
);
/** Reprocess every RAW file in one event, with a confirmation that names it. */
const reprocessEventRaws = useCallback(
(id: string) => {
const event = eventsRef.current.find((item) => item.id === id);
if (!event) return;
const raws = photosRef.current.filter(
(photo) => photo.eventId === id && photo.raw && !photo.deletedAt,
);
if (!raws.length) {
setToast('This event has no RAW photos');
return;
}
if (!userRef.current) {
setToast('Sign in to the server to reprocess RAW files');
return;
}
if (rawBusyRef.current) {
setToast('A RAW reprocess is already running');
return;
}
const ok = window.confirm(
`Re-decode ${raws.length} RAW file${raws.length === 1 ? '' : 's'} in “${event.name}”? ` +
'Existing edits and crops are kept.',
);
if (!ok) return;
void reprocessRawPhotos(raws.map((photo) => photo.id), { eventName: event.name });
},
[reprocessRawPhotos],
);
/** Auto-sync in Develop: merge the same patch into every selected photo. */
const updatePhotoEdits = useCallback(
(ids: string[], patch: Partial<Edits>, historyLabel?: string) => {
for (const id of ids) {
updatePhoto(id, (p) => ({ edits: { ...p.edits, ...patch } }), historyLabel);
}
},
[updatePhoto],
);
const bulkUpdate = useCallback(
(ids: string[], patch: Partial<PhotoRecord>) => {
if (!ids.length) return;
@@ -868,7 +1027,9 @@ export default function App() {
const savePreset = useCallback(
(name: string, edits: Edits) => {
const { crop: _crop, ...withoutCrop } = edits;
// Crop and the camera profile are properties of this photo, not a look:
// copying either onto another body would be wrong.
const { crop: _crop, cameraProfile: _cameraProfile, ...withoutCrop } = edits;
const preset: Preset = {
id: uid(),
name,
@@ -887,6 +1048,19 @@ export default function App() {
[customPresets],
);
const deletePreset = useCallback(
(id: string) => {
const next = customPresets.filter((preset) => preset.id !== id);
setCustomPresets(next);
setKV('customPresets', next).catch((err) => console.error(err));
if (userRef.current) {
import('./lib/api').then(({ pushPresets }) => pushPresets(next).catch(() => undefined));
}
setToast('Preset deleted');
},
[customPresets],
);
/* ------------------------------------------------------------- reordering */
const reorderPhotos = useCallback(
@@ -1477,6 +1651,40 @@ export default function App() {
setToast(message);
}, []);
/**
* Manual publish for an event that has no Immich gallery yet: create the
* album, link it to the event, then push originals and current edits.
*/
const publishEventToImmich = useCallback(
async (targetEventId: string) => {
const event = eventsRef.current.find((item) => item.id === targetEventId);
if (!event) return;
if (!immichStatusRef.current?.enabled) {
setToast('Turn on Immich in the Immich sync panel first');
return;
}
if (event.immich) {
await syncEventGallery(targetEventId);
return;
}
try {
await createImmichGalleryForEvent(targetEventId);
} catch (err) {
setToast(err instanceof Error ? err.message : 'Could not create the Immich gallery');
return;
}
const count = photosRef.current.filter(
(photo) => photo.eventId === targetEventId && !photo.deletedAt,
).length;
if (!count) {
setToast(`Immich gallery created for ${event.name} — import photos to fill it`);
return;
}
await syncEventGallery(targetEventId);
},
[createImmichGalleryForEvent, syncEventGallery],
);
const openImmichAsset = useCallback((photo: PhotoRecord) => {
const status = immichStatusRef.current;
if (!status?.url || !photo.immich) return;
@@ -1854,7 +2062,94 @@ export default function App() {
? 'Unsorted'
: events.find((e) => e.id === eventId)?.name ?? 'All photos';
const tetherImport = useCallback(
async (files: File[]) => {
if (!tetherEventId) return 0;
const result = await importFiles(
files,
tetherEventId,
[],
undefined,
cloudUser ? { uploadOriginal, push: pushPhoto } : null,
);
if (result.photos.length) {
const tagged = result.photos.map((photo) =>
cloudUser ? { ...photo, workspace: cloudUser.id } : photo,
);
setPhotos((prev) => [...tagged, ...prev]);
}
return result.photos.length;
},
[cloudUser, tetherEventId],
);
const importSidecar = useCallback(async () => {
if (selected.length !== 1) {
setToast('Select exactly one photo to import a sidecar into');
return;
}
const target = photos.find((photo) => photo.id === selected[0]);
if (!target) return;
try {
const xml = await readXmpFile();
if (!xml) return;
const result = xmpToEdits(xml, target.edits);
updatePhoto(target.id, { edits: result.edits }, 'Import XMP sidecar');
setToast(
result.source === 'luminary'
? 'Imported Luminary settings from the sidecar'
: `Imported ${result.applied.length} Lightroom setting${result.applied.length === 1 ? '' : 's'}`,
);
} catch (err) {
setToast(err instanceof Error ? err.message : 'Could not import the sidecar');
}
}, [photos, selected, updatePhoto]);
const paletteActions = [
{
id: 'xmp-export',
label: 'Export XMP sidecar for the selection',
hint: 'Sidecar',
run: () => {
const chosen = photos.filter((photo) => selected.includes(photo.id));
if (!chosen.length) {
setToast('Select photos to export sidecars for');
return;
}
for (const photo of chosen) downloadXmp(photo);
setToast(`Exported ${chosen.length} sidecar${chosen.length === 1 ? '' : 's'}`);
},
},
{
id: 'xmp-import',
label: 'Import XMP sidecar into the selected photo',
hint: 'Sidecar',
run: () => void importSidecar(),
},
{
id: 'tether',
label: 'Tether this event from a watch folder',
hint: 'Capture',
run: () => {
if (eventId === 'all' || eventId === 'unsorted') {
setToast('Open an event to tether into it');
return;
}
setTetherEventId(eventId);
},
},
{
id: 'cull-assist',
label: 'Cull assist for the selection',
hint: 'Focus',
run: () => {
if (!selected.length) {
setToast('Select photos to cull');
return;
}
setCullOpen(true);
},
},
{
id: 'import',
label: 'Import photos',
@@ -1889,6 +2184,29 @@ export default function App() {
run: () => setFilters(EMPTY_FILTERS),
},
{ id: 'shortcuts', label: 'Show keyboard shortcuts', hint: '?', run: () => setHelpOpen(true) },
...(cloudUser &&
eventId !== 'all' &&
eventId !== 'unsorted' &&
photos.some((photo) => photo.eventId === eventId && photo.raw && !photo.deletedAt)
? [
{
id: 'reprocess-event-raws',
label: 'Reprocess all RAW photos in this event',
hint: 'RAW',
run: () => reprocessEventRaws(eventId),
},
]
: []),
...(cloudUser && immichStatus?.enabled && eventId !== 'all' && eventId !== 'unsorted'
? [
{
id: 'immich-publish',
label: 'Publish this event to Immich',
hint: 'Immich',
run: () => void publishEventToImmich(eventId),
},
]
: []),
...(cloudUser && eventId !== 'all' && eventId !== 'unsorted'
? [{ id: 'share', label: 'Open client proofing', hint: 'Share', run: () => setShareEventId(eventId) }]
: []),
@@ -2010,6 +2328,9 @@ export default function App() {
await createEvent(name, { immichGallery });
}}
onSyncGallery={syncEventGallery}
onPublishGallery={publishEventToImmich}
canReprocessRaw={Boolean(cloudUser)}
onReprocessEvent={reprocessEventRaws}
onRename={renameEvent}
onDelete={removeEvent}
onReorderEvents={reorderEvents}
@@ -2117,6 +2438,12 @@ export default function App() {
: undefined
}
immichBusy={Boolean(immichProgress)}
onReprocessRaw={
cloudUser && selected.some((id) => photos.find((photo) => photo.id === id)?.raw)
? () => void reprocessRawPhotos(selected)
: undefined
}
reprocessBusy={rawBusy}
onDelete={() => (trashOpen ? void removePhotos(selected) : trashPhotos(selected))}
onExport={openExport}
onCompare={() => setCompareOpen(true)}
@@ -2154,6 +2481,7 @@ export default function App() {
onSelect={setActiveId}
onExit={() => setView('grid')}
onUpdate={updatePhoto}
onUpdateEdits={updatePhotoEdits}
clipboard={clipboard}
onCopy={copySettings}
onCopyOf={copySettingsOf}
@@ -2170,6 +2498,7 @@ export default function App() {
}
presets={[...PRESETS, ...customPresets]}
onSavePreset={savePreset}
onDeletePreset={deletePreset}
onDelete={() => trashPhotos([activePhoto.id])}
onVirtualCopy={() => void createVirtualCopy(activePhoto.id, true)}
metadataPresets={metadataPresets}
@@ -2489,6 +2818,36 @@ export default function App() {
</div>
)}
{tetherEventId && (
<TetherPanel
event={{
id: tetherEventId,
name: events.find((e) => e.id === tetherEventId)?.name ?? 'this event',
}}
onImport={tetherImport}
onClose={() => setTetherEventId(null)}
/>
)}
{cullOpen && (
<CullAssistModal
photos={photos.filter((photo) => selected.includes(photo.id))}
onReject={(ids) => bulkUpdate(ids, { flag: 'reject' })}
onClose={() => setCullOpen(false)}
/>
)}
{rawJob && (
<RawReprocessModal
job={rawJob}
onCancel={() => {
rawCancelRef.current = true;
setRawJob((prev) => (prev ? { ...prev, cancelled: true } : prev));
}}
onClose={() => setRawJob(null)}
/>
)}
{toast && (
<div className="toast">
<span>{toast}</span>
+248
View File
@@ -0,0 +1,248 @@
import { useEffect, useMemo, useState } from 'react';
import { analyseGrey, greyFromPixels, groupDuplicates, sharpnessGrade } from '../lib/cull';
import type { CullStats } from '../lib/cull';
import type { PhotoRecord } from '../types';
interface Row {
photo: PhotoRecord;
stats: CullStats | null;
error?: string;
}
interface Props {
photos: PhotoRecord[];
onReject: (ids: string[]) => void;
onClose: () => void;
}
const THUMB_EDGE = 96;
async function statsFor(photo: PhotoRecord): Promise<CullStats> {
const src = photo.thumbUrl ?? photo.thumb;
const image = new Image();
image.decoding = 'async';
await new Promise<void>((resolve, reject) => {
image.onload = () => resolve();
image.onerror = () => reject(new Error('Could not read the thumbnail'));
image.src = src;
});
const width = THUMB_EDGE;
const height = Math.max(24, Math.round((width * image.naturalHeight) / Math.max(1, image.naturalWidth)));
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) throw new Error('Could not analyse the thumbnail');
ctx.drawImage(image, 0, 0, width, height);
return analyseGrey(greyFromPixels(ctx.getImageData(0, 0, width, height).data), width, height);
}
/**
* Focus and duplicate pass over a selection, run on the thumbnails the grid
* already loaded. It never edits or rates anything by itself: the owner sees
* the scores and chooses what to reject.
*/
export default function CullAssistModal({ photos, onReject, onClose }: Props) {
const [rows, setRows] = useState<Row[]>([]);
const [done, setDone] = useState(0);
const [running, setRunning] = useState(true);
const [current, setCurrent] = useState('');
const [threshold, setThreshold] = useState(22);
useEffect(() => {
let cancelled = false;
const next: Row[] = photos.map((photo) => ({ photo, stats: null }));
setRows(next.map((row) => ({ ...row })));
setDone(0);
setRunning(true);
void (async () => {
for (let i = 0; i < next.length; i++) {
if (cancelled) return;
setCurrent(next[i].photo.name);
try {
next[i] = { ...next[i], stats: await statsFor(next[i].photo) };
} catch (err) {
next[i] = {
...next[i],
error: err instanceof Error ? err.message : 'Analysis failed',
};
}
if (cancelled) return;
setRows(next.map((row) => ({ ...row })));
setDone(i + 1);
}
if (!cancelled) {
setRunning(false);
setCurrent('');
}
})();
return () => {
cancelled = true;
};
}, [photos]);
const analysed = rows.filter((row) => row.stats);
const soft = analysed.filter((row) => (row.stats?.sharpness ?? 100) < threshold);
const duplicates = useMemo(
() =>
groupDuplicates(
analysed.map((row) => ({ ...row, hash: row.stats?.hash ?? '' })),
9,
),
[analysed],
);
const duplicateRejects = useMemo(() => {
const ids: string[] = [];
for (const group of duplicates) {
// Keep the sharpest frame of the burst; everything close to it is the
// alternative the photographer would otherwise have to compare by eye.
const sorted = [...group].sort(
(a, b) => (b.stats?.sharpness ?? 0) - (a.stats?.sharpness ?? 0),
);
for (const row of sorted.slice(1)) ids.push(row.photo.id);
}
return ids;
}, [duplicates]);
const pct = photos.length ? Math.round((done / photos.length) * 100) : 0;
return (
<div
className="modal-backdrop"
onPointerDown={(e) => e.target === e.currentTarget && !running && onClose()}
>
<div className="modal raw-modal cull-modal" role="dialog" aria-modal="true" aria-label="Cull assist">
<header className="modal-head">
<div>
<h2>Cull assist</h2>
<p className="muted small">
Focus and duplicate checks on {photos.length} photo{photos.length === 1 ? '' : 's'}.
Nothing is rated or rejected without your say-so.
</p>
</div>
{!running && (
<button className="icon-btn" onClick={onClose} title="Close">
×
</button>
)}
</header>
<div className="modal-body">
{running && (
<>
<div className="progress-bar">
<div className="progress-fill" style={{ width: `${pct}%` }} />
</div>
<p className="muted small">
{done} of {photos.length}
{current ? ` · ${current}` : '…'}
</p>
</>
)}
{!running && (
<>
<div className="cull-summary">
<div>
<strong>{soft.length}</strong>
<span>soft under {threshold}</span>
</div>
<div>
<strong>{duplicates.length}</strong>
<span>duplicate set{duplicates.length === 1 ? '' : 's'}</span>
</div>
<div>
<strong>{analysed.length}</strong>
<span>analysed</span>
</div>
</div>
<label className="cull-threshold">
<span>Soft threshold</span>
<input
type="range"
min={5}
max={55}
value={threshold}
onChange={(e) => setThreshold(Number(e.target.value))}
/>
<span className="muted small">{threshold}</span>
</label>
<ul className="cull-list">
{[...analysed]
.sort((a, b) => (a.stats?.sharpness ?? 0) - (b.stats?.sharpness ?? 0))
.slice(0, 60)
.map((row) => {
const stats = row.stats as CullStats;
const grade = sharpnessGrade(stats.sharpness);
return (
<li key={row.photo.id}>
<span className="cull-name" title={row.photo.name}>
{row.photo.name}
</span>
<span className={`cull-grade ${grade}`}>{grade}</span>
<span className="cull-score">{stats.sharpness}</span>
<span className="muted small">
{stats.clippedHigh > 0.08
? 'highlights clipped'
: stats.clippedLow > 0.12
? 'crushed shadows'
: stats.mean < 30
? 'very dark'
: ''}
</span>
</li>
);
})}
</ul>
{analysed.length > 60 && (
<p className="muted small">Showing the 60 softest frames.</p>
)}
</>
)}
</div>
<footer className="modal-foot">
<span className="muted small">
Scores come from the thumbnails, so treat them as a first pass.
</span>
{running ? (
<button className="btn ghost" onClick={onClose}>
Hide
</button>
) : (
<>
<button
className="btn ghost small"
disabled={!duplicateRejects.length}
onClick={() => {
onReject(duplicateRejects);
onClose();
}}
>
Reject {duplicateRejects.length} duplicate alternative
{duplicateRejects.length === 1 ? '' : 's'}
</button>
<button
className="btn ghost small danger"
disabled={!soft.length}
onClick={() => {
onReject(soft.map((row) => row.photo.id));
onClose();
}}
>
Reject {soft.length} soft
</button>
<button className="btn primary" onClick={onClose}>
Done
</button>
</>
)}
</footer>
</div>
</div>
);
}
+71 -3
View File
@@ -2,16 +2,33 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { buildSampler, clamp01 } from '../lib/curves';
import type { CurvePoint } from '../types';
export type ParametricKey = 'highlights' | 'lights' | 'darks' | 'blacks';
interface Props {
points: CurvePoint[];
onChange: (points: CurvePoint[]) => void;
color: string;
/** Region tone shaper values, shown as draggable dots on the curve. */
parametric?: Record<ParametricKey, number>;
onParametric?: (key: ParametricKey, value: number) => void;
}
export default function CurveEditor({ points, onChange, color }: Props) {
/** Lightroom-scale zones: the four regions share the diagonal evenly. */
const ZONES: { key: ParametricKey; label: string; x: number }[] = [
{ key: 'highlights', label: 'Highlights', x: 0.875 },
{ key: 'lights', label: 'Lights', x: 0.625 },
{ key: 'darks', label: 'Darks', x: 0.375 },
{ key: 'blacks', label: 'Blacks', x: 0.125 },
];
/** Full slider travel moves a zone dot a quarter of the graph. */
const ZONE_TRAVEL = 0.18;
export default function CurveEditor({ points, onChange, color, parametric, onParametric }: Props) {
const svgRef = useRef<SVGSVGElement>(null);
const pointsRef = useRef(points);
const [drag, setDrag] = useState<number | null>(null);
const [paramDrag, setParamDrag] = useState<ParametricKey | null>(null);
const [hover, setHover] = useState<number | null>(null);
useEffect(() => {
@@ -42,6 +59,12 @@ export default function CurveEditor({ points, onChange, color }: Props) {
const handleDown = (e: React.PointerEvent<SVGSVGElement>) => {
e.preventDefault();
const paramAttr = (e.target as Element).getAttribute('data-param');
if (paramAttr && parametric && onParametric) {
setParamDrag(paramAttr as ParametricKey);
e.currentTarget.setPointerCapture(e.pointerId);
return;
}
const idxAttr = (e.target as Element).getAttribute('data-idx');
let idx: number;
if (idxAttr !== null) {
@@ -57,6 +80,15 @@ export default function CurveEditor({ points, onChange, color }: Props) {
};
const handleMove = (e: React.PointerEvent<SVGSVGElement>) => {
if (paramDrag && parametric && onParametric) {
const zone = ZONES.find((item) => item.key === paramDrag);
if (!zone) return;
const p = toNorm(e.clientX, e.clientY);
const base = sampler(zone.x);
const value = ((p.y - base) / ZONE_TRAVEL) * 100;
onParametric(paramDrag, Math.round(Math.max(-100, Math.min(100, value))));
return;
}
if (drag === null) return;
const pts = pointsRef.current;
const idx = drag;
@@ -68,7 +100,10 @@ export default function CurveEditor({ points, onChange, color }: Props) {
onChange(next);
};
const handleUp = () => setDrag(null);
const handleUp = () => {
setDrag(null);
setParamDrag(null);
};
const removePoint = (idx: number) => {
const pts = pointsRef.current;
@@ -101,6 +136,37 @@ export default function CurveEditor({ points, onChange, color }: Props) {
</g>
))}
<line x1="0" y1="100" x2="100" y2="0" className="curve-diag" />
{parametric &&
onParametric &&
ZONES.map((zone) => {
const value = parametric[zone.key] ?? 0;
const y = clamp01(sampler(zone.x) + (value / 100) * ZONE_TRAVEL);
return (
<g key={zone.key} style={{ cursor: 'ns-resize' }}>
<line
x1={zone.x * 100}
y1="0"
x2={zone.x * 100}
y2="100"
stroke="rgba(255,255,255,0.12)"
strokeDasharray="2 3"
vectorEffect="non-scaling-stroke"
/>
<circle
data-param={zone.key}
cx={zone.x * 100}
cy={(1 - y) * 100}
r={paramDrag === zone.key ? 3.2 : 2.3}
fill="#141416"
stroke="#f0c86a"
strokeWidth="1.4"
vectorEffect="non-scaling-stroke"
>
<title>{`${zone.label}: ${value > 0 ? '+' : ''}${value}`}</title>
</circle>
</g>
);
})}
<path d={path} fill="none" stroke={color} strokeWidth="1.6" vectorEffect="non-scaling-stroke" />
{points.map((p, i) => (
<circle
@@ -116,7 +182,9 @@ export default function CurveEditor({ points, onChange, color }: Props) {
/>
))}
</svg>
<div className="curve-hint">Click to add a point · drag to shape · double-click a point to remove</div>
<div className="curve-hint">
Click to add a point · drag to shape · drag the four gold dots for highlights, lights, darks and blacks
</div>
</div>
);
}
+147 -37
View File
@@ -7,7 +7,8 @@ import {
MAX_LOCAL_LAYERS,
} from '../lib/edits';
import { subscribeClipPreview } from '../lib/clipPreview';
import { getBitmap, getDenoisedBitmap } from '../lib/images';
import { get16BitSource, getBitmap, getDenoisedBitmap } from '../lib/images';
import type { Preview16 } from '../lib/preview16';
import { useMediaQuery } from '../lib/useMediaQuery';
import { usePersistentState } from '../lib/usePersistentState';
import { solveWhiteBalance } from '../lib/whiteBalance';
@@ -59,6 +60,7 @@ import {
OpticsPanel,
PresetsPanel,
ProofPanel,
CameraProfilePanel,
SnapshotsPanel,
} from './Panels';
import Stars, { ColorSwatches, FlagButtons } from './Stars';
@@ -121,6 +123,8 @@ interface Props {
onSelect: (id: string) => void;
onExit: () => void;
onUpdate: (id: string, patch: Partial<PhotoRecord>, historyLabel?: string) => void;
/** Auto-sync: merge a patch into several photos' own edits at once. */
onUpdateEdits?: (ids: string[], patch: Partial<Edits>, historyLabel?: string) => void;
clipboard: Edits | null;
onCopy: () => void;
/** Copy settings from a named filmstrip photo instead of the canvas photo. */
@@ -138,6 +142,7 @@ interface Props {
onOpenImmich?: () => void;
presets: Preset[];
onSavePreset: (name: string, edits: Edits) => void;
onDeletePreset: (id: string) => void;
onDelete: () => void;
onVirtualCopy: () => void;
metadataPresets: MetadataPreset[];
@@ -156,6 +161,7 @@ export default function Develop({
onSelect,
onExit,
onUpdate,
onUpdateEdits,
clipboard,
onCopy,
onCopyOf,
@@ -170,6 +176,7 @@ export default function Develop({
onOpenImmich,
presets,
onSavePreset,
onDeletePreset,
onDelete,
onVirtualCopy,
metadataPresets,
@@ -189,7 +196,10 @@ export default function Develop({
const panRef = useRef<{ x: number; y: number; cx: number; cy: number } | null>(null);
const [bitmap, setBitmap] = useState<ImageBitmap | null>(null);
const [hdrSource, setHdrSource] = useState<Preview16 | null>(null);
const [denoisedBitmap, setDenoisedBitmap] = useState<ImageBitmap | null>(null);
/** Name of the printer ICC profile loaded for this session, if any. */
const [proofProfile, setProofProfile] = useState<string | null>(null);
const [stage, setStage] = useState({ w: 0, h: 0 });
const [cropMode, setCropMode] = useState(false);
const [cropDrag, setCropDrag] = useState(false);
@@ -214,6 +224,7 @@ export default function Develop({
const [filmSel, setFilmSel] = useState<string[]>([photo.id]);
const [filmAnchor, setFilmAnchor] = useState(photo.id);
const [showOriginal, setShowOriginal] = useState(false);
const [autoSync, setAutoSync] = usePersistentState('develop.autosync', false);
const [histVersion, setHistVersion] = useState(0);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
@@ -232,6 +243,7 @@ export default function Develop({
ids?: string[];
} | null>(null);
const [healMode, setHealMode] = useState(false);
const [rangePicking, setRangePicking] = useState(false);
const [brushPx, setBrushPx] = useState(56);
const [healFeather, setHealFeather] = useState(50);
const [healSelected, setHealSelected] = useState<number | null>(null);
@@ -340,9 +352,17 @@ export default function Develop({
const setEdits = useCallback(
(patch: Partial<Edits>, label: string) => {
// Auto-sync applies only the changed controls to the rest of the
// filmstrip, so each photo keeps its own untouched settings, crop and
// masks. The canvas photo is always updated last so the preview follows
// the slider that was actually moved.
if (autoSync && filmSel.length > 1 && onUpdateEdits) {
const others = filmSel.filter((id) => id !== photo.id);
if (others.length) onUpdateEdits(others, patch, label);
}
onUpdate(photo.id, { edits: { ...photo.edits, ...patch } }, label);
},
[onUpdate, photo.id, photo.edits],
[autoSync, filmSel, onUpdate, onUpdateEdits, photo.id, photo.edits],
);
useEffect(() => {
@@ -399,6 +419,14 @@ export default function Develop({
useEffect(() => {
let alive = true;
setLoading(true);
// The 16-bit sidecar is optional and can be tens of megabytes, so it loads
// behind the JPEG and simply swaps the source texture when it lands.
setHdrSource(null);
get16BitSource(photo)
.then((hdr) => {
if (alive) setHdrSource(hdr);
})
.catch(() => undefined);
getBitmap(photo)
.then((bmp) => {
if (!alive) return;
@@ -508,22 +536,14 @@ export default function Develop({
let cssH = Math.max(40, Math.round(contentH * fitScale));
if (zoomFactor > 1.0001) {
// The visible window keeps the stage's aspect, so the canvas is stage sized
// and the shader maps it onto a sub-rect of the frame. Cost stays constant
// no matter how far you zoom, and detail comes from the source bitmap.
const vw = Math.min(1, availW / (fitScale * zoomFactor) / frame.w);
const vh = Math.min(1, availH / (fitScale * zoomFactor) / frame.h);
const cx =
vw >= content.w
? content.x + content.w / 2
: clampNum(zoom.cx, content.x + vw / 2, content.x + content.w - vw / 2);
const cy =
vh >= content.h
? content.y + content.h / 2
: clampNum(zoom.cy, content.y + vh / 2, content.y + content.h - vh / 2);
// The canvas keeps the photo's fit-sized box while zooming and the window
// shrinks inside the crop at the same aspect. Growing the canvas to the
// stage's shape instead stretched any photo whose aspect differed from it.
const vw = content.w / zoomFactor;
const vh = content.h / zoomFactor;
const cx = clampNum(zoom.cx, content.x + vw / 2, content.x + content.w - vw / 2);
const cy = clampNum(zoom.cy, content.y + vh / 2, content.y + content.h - vh / 2);
view = { x: cx - vw / 2, y: cy - vh / 2, w: vw, h: vh };
cssW = Math.round(availW);
cssH = Math.round(availH);
}
const dpr = Math.min(window.devicePixelRatio || 1, 2);
@@ -555,7 +575,7 @@ export default function Develop({
);
try {
renderer.setImage(bitmap);
renderer.setImage(bitmap, hdrSource);
// "Show original" must show the untouched source, not the cleaned proxy.
renderer.setDenoised(showOriginal ? null : denoisedBitmap, activeEdits.aiDenoise.amount / 100);
renderer.render(activeEdits, {
@@ -583,6 +603,7 @@ export default function Develop({
}
}, [
bitmap,
hdrSource,
denoisedBitmap,
edits,
cropMode,
@@ -595,6 +616,9 @@ export default function Develop({
lensCorrection,
lensSplit,
lensSplitAt,
// Loading or clearing a printer profile changes the finish pass, and the
// cube lives outside the edit record, so the redraw is keyed on it here.
proofProfile,
]);
useEffect(() => {
@@ -634,11 +658,11 @@ export default function Develop({
}
}
const vw = geo.availW / (geo.fitScale * zNext) / geo.frameW;
const vh = geo.availH / (geo.fitScale * zNext) / geo.frameH;
const c = geo.content;
cx = vw >= c.w ? c.x + c.w / 2 : clampNum(cx, c.x + vw / 2, c.x + c.w - vw / 2);
cy = vh >= c.h ? c.y + c.h / 2 : clampNum(cy, c.y + vh / 2, c.y + c.h - vh / 2);
const vw = c.w / zNext;
const vh = c.h / zNext;
cx = clampNum(cx, c.x + vw / 2, c.x + c.w - vw / 2);
cy = clampNum(cy, c.y + vh / 2, c.y + c.h - vh / 2);
setZoom({ pct: next, cx, cy });
}, []);
@@ -653,16 +677,10 @@ export default function Develop({
const pct = zoom.pct === 'fit' ? 100 : zoom.pct;
const z = Math.max(1, pct / geo.fitPct);
const c = geo.content;
const vw = Math.min(c.w, geo.availW / (geo.fitScale * z) / geo.frameW);
const vh = Math.min(c.h, geo.availH / (geo.fitScale * z) / geo.frameH);
const cx =
vw >= c.w
? c.x + c.w / 2
: clampNum(fx, c.x + vw / 2, c.x + c.w - vw / 2);
const cy =
vh >= c.h
? c.y + c.h / 2
: clampNum(fy, c.y + vh / 2, c.y + c.h - vh / 2);
const vw = c.w / z;
const vh = c.h / z;
const cx = clampNum(fx, c.x + vw / 2, c.x + c.w - vw / 2);
const cy = clampNum(fy, c.y + vh / 2, c.y + c.h - vh / 2);
setZoom({ pct, cx, cy });
},
[zoom.pct],
@@ -717,7 +735,7 @@ export default function Develop({
}, [cropMode, applyZoom, healMode, localMode, activeLocal]);
const beginPan = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (picking || cropMode || healMode || localMode || !zoomed || e.button !== 0) return;
if (picking || rangePicking || cropMode || healMode || localMode || !zoomed || e.button !== 0) return;
const geo = geoRef.current;
panRef.current = {
x: e.clientX,
@@ -1007,6 +1025,58 @@ export default function Develop({
[autoMaskBusy, bitmap, commitLocal, edits.local, photo],
);
/**
* Colour-range sampler: read the untouched source colour under the pointer and
* shape the active mask's range around its hue, saturation and luma. The same
* source colour the mask range compares against, so the result lines up even
* under a heavy grade.
*/
const pickRangeColour = (e: React.MouseEvent<HTMLCanvasElement>) => {
if (!rangePicking || !activeLocal) return;
const canvas = canvasRef.current;
const renderer = rendererRef.current;
if (!canvas || !renderer) return;
const rect = canvas.getBoundingClientRect();
if (!rect.width || !rect.height) return;
const geo = geoRef.current;
const sample = renderer.pickSource(edits, {
nx: clampNum((e.clientX - rect.left) / rect.width, 0, 1),
ny: clampNum((e.clientY - rect.top) / rect.height, 0, 1),
view: geo.zoomFactor > 1.0001 ? geo.view : undefined,
upscale: Math.min(window.devicePixelRatio || 1, 2) * geo.fitScale * geo.zoomFactor > 1.1,
});
setRangePicking(false);
if (!sample) return;
const [r, g, b] = sample;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const delta = max - min;
let hue = 0;
if (delta > 1e-6) {
if (max === r) hue = ((g - b) / delta) % 6;
else if (max === g) hue = (b - r) / delta + 2;
else hue = (r - g) / delta + 4;
hue = (hue * 60 + 360) % 360;
}
const sat = max > 0 ? delta / max : 0;
const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
patchLocal(
activeLocal.id,
{
range: {
...activeLocal.range,
enabled: true,
hue: Math.round(hue),
hueRange: 40,
satMin: Math.round(Math.max(0, sat * 100 - 25)),
lumaMin: Math.round(Math.max(0, luma * 100 - 14)),
lumaMax: Math.round(Math.min(100, luma * 100 + 14)),
},
},
'Sample mask colour',
);
};
const deleteLocalLayer = useCallback(
(id: string) => {
commitLocal((edits.local ?? []).filter((layer) => layer.id !== id), 'Delete local adjustment');
@@ -1381,7 +1451,15 @@ export default function Develop({
const next: Edits =
preset.id === 'original'
? { ...defaultEdits(), crop: photo.edits.crop }
: { ...photo.edits, ...preset.edits, crop: photo.edits.crop };
: {
...photo.edits,
...preset.edits,
crop: photo.edits.crop,
// The camera profile belongs to the body that produced the raw.
cameraProfile: photo.edits.cameraProfile,
// A strong film response must not leak into the next look.
redscale: preset.edits.redscale ?? 0,
};
onUpdate(photo.id, { edits: next }, `Preset: ${preset.name}`);
},
[onUpdate, photo.id, photo.edits],
@@ -1433,6 +1511,13 @@ export default function Develop({
onPasteLayer={pasteLocalLayer}
canPaste={Boolean(localClipboard)}
onAutoMask={(kind) => void addAutoMask(kind)}
onSampleRange={() => {
setRangePicking(true);
setLocalMode(false);
setHealMode(false);
setPicking(false);
setCropMode(false);
}}
autoBusy={autoMaskBusy}
/>
<EffectsPanel edits={edits} photo={photo} set={setEdits} grainFreeze={cropDrag} />
@@ -1445,7 +1530,19 @@ export default function Develop({
lensSplit={lensSplit}
onLensSplit={setLensSplit}
/>
<ProofPanel edits={edits} photo={photo} set={setEdits} />
<CameraProfilePanel
edits={edits}
photo={photo}
set={setEdits}
cameraNative={Boolean(hdrSource?.rgbCam)}
/>
<ProofPanel
edits={edits}
photo={photo}
set={setEdits}
proofProfile={proofProfile}
onProofProfile={(cube) => setProofProfile(cube?.name ?? null)}
/>
{includeMetadata && (
<MetadataPanel
photo={photo}
@@ -1597,6 +1694,18 @@ export default function Develop({
>
Before / After
</button>
<button
className={`btn ghost small ${autoSync ? 'on' : ''}`}
onClick={() => setAutoSync((v) => !v)}
aria-pressed={autoSync}
title={
autoSync
? 'Auto-sync on: every adjustment applies to all selected filmstrip photos'
: 'Auto-sync: apply adjustments to every selected filmstrip photo'
}
>
Auto-sync{autoSync && filmSel.length > 1 ? ` (${filmSel.length})` : ''}
</button>
<button className={`btn ghost small ${cropMode ? 'on' : ''}`} onClick={() => setCropMode((v) => !v)} title="Crop & straighten (C)">
Crop
</button>
@@ -1731,6 +1840,7 @@ export default function Develop({
photo={photo}
onApply={applyPreset}
onSave={(name) => onSavePreset(name, photo.edits)}
onDelete={onDeletePreset}
/>
<SnapshotsPanel
snapshots={photo.snapshots ?? []}
@@ -1766,8 +1876,8 @@ export default function Develop({
<div className="canvas-wrap">
<canvas
ref={canvasRef}
className={`preview ${zoomed ? 'zoomed' : ''} ${picking ? 'picking' : ''} ${healMode ? 'healing' : ''} ${localMode ? 'masking' : ''}`}
onClick={pickWhiteBalance}
className={`preview ${zoomed ? 'zoomed' : ''} ${picking || rangePicking ? 'picking' : ''} ${healMode ? 'healing' : ''} ${localMode ? 'masking' : ''}`}
onClick={(e) => (rangePicking ? pickRangeColour(e) : pickWhiteBalance(e))}
onPointerDown={(e) => {
if (localMode) startLocalMask(e);
else if (healMode) startHeal(e);
+8 -2
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react';
import { memo, useEffect, useRef, useState } from 'react';
import { thumbTransform } from '../lib/edits';
import { useEditedThumb } from '../lib/editThumbs';
import type { PhotoRecord } from '../types';
@@ -19,7 +19,7 @@ interface Props {
* server/import thumbnail and the CSS orientation transform. Rendering starts
* only when the tile is close to the viewport.
*/
export default function EditedImage({
function EditedImage({
photo,
boxAspect = 4 / 3,
alt,
@@ -62,3 +62,9 @@ export default function EditedImage({
/>
);
}
/**
* Memoised: a selection change on the library re-renders the whole grid, and a
* picture whose photo, size and props did not change has no work to redo.
*/
export default memo(EditedImage);
+35 -4
View File
@@ -22,6 +22,10 @@ interface Props {
onRename: (id: string, name: string) => void;
onDelete: (id: string) => void;
onSyncGallery?: (id: string) => void;
onPublishGallery?: (id: string) => void;
/** Server-backed account, so RAW originals can be re-decoded. */
canReprocessRaw?: boolean;
onReprocessEvent?: (id: string) => void;
onReorderEvents: (dragId: string, targetId: string) => void;
onDropPhotos: (ids: string[], eventId: string) => void;
trashOpen: boolean;
@@ -46,6 +50,9 @@ export default function EventSidebar({
onRename,
onDelete,
onSyncGallery,
onPublishGallery,
canReprocessRaw = false,
onReprocessEvent,
onReorderEvents,
onDropPhotos,
trashOpen,
@@ -63,6 +70,7 @@ export default function EventSidebar({
const [dropTarget, setDropTarget] = useState<string | null>(null);
const counts = new Map<string, number>();
const rawCounts = new Map<string, number>();
let unsorted = 0;
for (const p of photos) {
if (!p.eventId) {
@@ -70,6 +78,7 @@ export default function EventSidebar({
continue;
}
counts.set(p.eventId, (counts.get(p.eventId) ?? 0) + 1);
if (p.raw) rawCounts.set(p.eventId, (rawCounts.get(p.eventId) ?? 0) + 1);
}
const submit = async () => {
@@ -250,15 +259,37 @@ export default function EventSidebar({
<span className="event-count">{counts.get(event.id) ?? 0}</span>
</button>
<div className="event-tools">
{immichEnabled && event.immich && onSyncGallery && (
{canReprocessRaw && onReprocessEvent && (rawCounts.get(event.id) ?? 0) > 0 && (
<button
className="icon-btn"
title="Push edits and originals to this event's Immich gallery"
onClick={() => onSyncGallery(event.id)}
title={`Reprocess ${rawCounts.get(event.id)} RAW file${
rawCounts.get(event.id) === 1 ? '' : 's'
} in this event`}
onClick={() => onReprocessEvent(event.id)}
>
☁
⟲
</button>
)}
{immichEnabled &&
(event.immich
? onSyncGallery && (
<button
className="icon-btn"
title="Publish new photos and edits to this event's Immich gallery"
onClick={() => onSyncGallery(event.id)}
>
☁
</button>
)
: onPublishGallery && (
<button
className="icon-btn"
title="Create an Immich gallery for this event and publish its photos"
onClick={() => onPublishGallery(event.id)}
>
☁+
</button>
))}
<button
className="icon-btn"
title="Rename event"
+21 -1
View File
@@ -5,6 +5,8 @@ import Slider from './Slider';
import { getBitmap } from '../lib/images';
import { frameToSource, grainCellPx, grainSampleWindow, outputSize, rotatedBounds, Renderer } from '../gl/renderer';
import type { PhotoRecord } from '../types';
import { COLOR_SPACE_OPTIONS } from '../lib/colorSpace';
import type { OutputColorSpace } from '../lib/icc';
interface Props {
photos: PhotoRecord[];
@@ -280,8 +282,12 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
value={opts.format}
onChange={(e) => {
const format = e.target.value as ExportFormat;
const wide = format === 'jpeg' || format === 'tiff16';
patch({
format,
// PNG/WebP output can carry converted pixels but no ICC tag, so
// keep those formats in the tagged sRGB default.
...(wide ? {} : { colorSpace: 'srgb' as OutputColorSpace }),
// Watermarking needs an 8-bit canvas pass; keep the option off
// rather than silently downgrading the 16-bit file.
...(format === 'tiff16' ? { watermark: { ...opts.watermark, enabled: false } } : {}),
@@ -435,6 +441,20 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
<div className="subhead">
<span>Output</span>
</div>
<label className="field">
<span>Colour space</span>
<select
value={opts.colorSpace ?? 'srgb'}
onChange={(e) => patch({ colorSpace: e.target.value as OutputColorSpace })}
disabled={busy || (opts.format !== 'jpeg' && opts.format !== 'tiff16')}
>
{COLOR_SPACE_OPTIONS.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</label>
<Slider
label="Output sharpening"
min={0}
@@ -460,7 +480,7 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
onChange={(e) => patch({ embedProfile: e.target.checked })}
disabled={opts.format === 'webp' || opts.format === 'png'}
/>
Embed sRGB profile (JPEG/TIFF)
Embed {COLOR_SPACE_OPTIONS.find((option) => option.value === (opts.colorSpace ?? 'srgb'))?.label ?? 'sRGB'} profile (JPEG/TIFF)
</label>
<div className="subhead">
+2 -2
View File
@@ -291,8 +291,8 @@ export default function ImmichPanel({ onClose, onChanged, onToast }: Props) {
</label>
<p className="muted small">
Nothing is uploaded while you edit. Press the ☁ button on an event to push
its edited photos and any originals Immich has not seen yet.
Nothing is uploaded while you edit. Press ☁+ on an event to create its Immich
gallery and publish it, or ☁ to push new photos and edits to an existing one.
</p>
<label className="check-row">
+15
View File
@@ -24,6 +24,9 @@ interface Props {
onStack: () => void;
onVirtualCopy: () => void;
onMerge: () => void;
/** Re-decode the selected RAW files with the server's current pipeline. */
onReprocessRaw?: () => void;
reprocessBusy?: boolean;
onPrint: () => void;
stacks: Map<string, { count: number; expanded: boolean }>;
onToggleStack: (id: string) => void;
@@ -62,6 +65,8 @@ export default function LibraryGrid({
onStack,
onVirtualCopy,
onMerge,
onReprocessRaw,
reprocessBusy = false,
onPrint,
stacks,
onToggleStack,
@@ -282,6 +287,16 @@ export default function LibraryGrid({
<button className="btn ghost small" onClick={onMerge} disabled={selected.length < 2}>
Merge
</button>
{onReprocessRaw && (
<button
className="btn ghost small"
onClick={onReprocessRaw}
disabled={reprocessBusy}
title="Re-decode the selected RAW files with the current pipeline settings"
>
{reprocessBusy ? 'Reprocessing…' : 'Reprocess RAW'}
</button>
)}
{onSendToImmich && (
<button
className="btn ghost small"
+641 -70
View File
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve } from '../lib/edits';
import { computeAutoEdits } from '../lib/auto';
import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve, MAX_LOCAL_LAYERS } from '../lib/edits';
import { computeAutoEdits, computeAutoWhiteBalance } from '../lib/auto';
import { autoNoiseFor } from '../lib/noiseProfile';
import { clearDenoised, getDenoiseJob, startDenoise } from '../lib/api';
import { clamp } from '../lib/curves';
@@ -19,7 +19,10 @@ import type {
import CurveEditor from './CurveEditor';
import { getBitmap } from '../lib/images';
import { grainSampleWindow, rotatedBounds, Renderer } from '../gl/renderer';
import { applyFilmVariant, FILM_VARIANTS, type FilmVariant } from '../lib/presets';
import { applyFilmVariant, FILM_VARIANTS, PRESET_CATEGORIES, type FilmVariant } from '../lib/presets';
import { usePersistentState } from '../lib/usePersistentState';
import { loadProofProfile, setActiveProofCube, type SoftProofCube } from '../lib/softProof';
import { dcpRgbCam, parseDcp } from '../lib/dcp';
import { usePresetThumbs } from './PresetThumbs';
import { availableFor, findLensForMeta, searchLens, type LensSearchResult } from '../lib/lensfun';
import {
@@ -74,6 +77,7 @@ export function BasicPanel({
onPicker,
}: PanelSetProps & { picker?: boolean; onPicker?: (active: boolean) => void }) {
const [autoBusy, setAutoBusy] = useState(false);
const [wbBusy, setWbBusy] = useState(false);
const auto = async () => {
setAutoBusy(true);
@@ -85,6 +89,15 @@ export function BasicPanel({
}
};
const autoWb = async () => {
setWbBusy(true);
try {
set(await computeAutoWhiteBalance(photo.thumb), 'Auto white balance');
} finally {
setWbBusy(false);
}
};
return (
<Panel title="Light">
<div className="subhead">
@@ -98,17 +111,41 @@ export function BasicPanel({
>
{picker ? 'Picking…' : 'Eyedropper'}
</button>
<button className="link-btn" onClick={() => set({ temp: 0, tint: 0 }, 'As shot')}>
<button className="link-btn" onClick={() => void autoWb()} disabled={wbBusy}>
{wbBusy ? 'Reading…' : 'Auto WB'}
</button>
<button className="link-btn" onClick={() => set({ temp: 0, tint: 0, kelvin: null }, 'As shot')}>
As shot
</button>
</div>
</div>
<Slider
label="Temp"
value={edits.temp}
onChange={(v) => set({ temp: v }, 'Temperature')}
track="linear-gradient(90deg,#3f74d8,#a8b6c6,#f4b23f)"
/>
<label className="check-row">
<input
type="checkbox"
checked={edits.kelvin != null}
onChange={(e) => set({ kelvin: e.target.checked ? 5500 : null }, 'Kelvin white balance')}
/>
Absolute Kelvin (5500 K reference)
</label>
{edits.kelvin == null ? (
<Slider
label="Temp"
value={edits.temp}
onChange={(v) => set({ temp: v }, 'Temperature')}
track="linear-gradient(90deg,#3f74d8,#a8b6c6,#f4b23f)"
/>
) : (
<Slider
label="Temperature"
min={1500}
max={12000}
step={50}
value={edits.kelvin}
onChange={(v) => set({ kelvin: v }, 'Kelvin temperature')}
format={(v) => `${Math.round(v)} K`}
track="linear-gradient(90deg,#3f74d8,#a8b6c6,#f4b23f)"
/>
)}
<Slider
label="Tint"
value={edits.tint}
@@ -154,6 +191,14 @@ export function BasicPanel({
<Slider label="Dehaze" value={edits.dehaze} onChange={(v) => set({ dehaze: v }, 'Dehaze')} />
<Slider label="Vibrance" value={edits.vibrance} onChange={(v) => set({ vibrance: v }, 'Vibrance')} />
<Slider label="Saturation" value={edits.saturation} onChange={(v) => set({ saturation: v }, 'Saturation')} />
<Slider
label="Redscale"
min={0}
max={100}
value={edits.redscale}
onChange={(v) => set({ redscale: v }, 'Redscale')}
track="linear-gradient(90deg,#a8b6c6,#d96b34,#8f1d12)"
/>
<label className="toggle">
<input type="checkbox" checked={edits.bw} onChange={(e) => set({ bw: e.target.checked }, 'Black & white')} />
@@ -214,7 +259,11 @@ export function CurvePanel({ edits, set }: PanelSetProps) {
className="link-btn"
onClick={() =>
set(
{ curve: { ...edits.curve, [channel]: identityCurve() }, parametric: { highlights: 0, lights: 0, darks: 0, blacks: 0 } },
{
curve: { ...edits.curve, [channel]: identityCurve() },
levels: { black: 0, white: 100, gamma: 1 },
parametric: { highlights: 0, lights: 0, darks: 0, blacks: 0 },
},
'Reset tone curve',
)
}
@@ -223,6 +272,39 @@ export function CurvePanel({ edits, set }: PanelSetProps) {
</button>
}
>
<div className="subhead">
<span>Input levels</span>
</div>
<Slider
label="Black point"
min={0}
max={45}
value={edits.levels.black}
onChange={(v) =>
set({ levels: { ...edits.levels, black: Math.min(v, edits.levels.white - 5) } }, 'Black point')
}
format={(v) => `${Math.round(v)}`}
/>
<Slider
label="White point"
min={55}
max={100}
value={edits.levels.white}
onChange={(v) =>
set({ levels: { ...edits.levels, white: Math.max(v, edits.levels.black + 5) } }, 'White point')
}
format={(v) => `${Math.round(v)}`}
/>
<Slider
label="Gamma"
min={0.3}
max={3}
step={0.05}
value={edits.levels.gamma}
onChange={(v) => set({ levels: { ...edits.levels, gamma: v } }, 'Midtone gamma')}
format={(v) => v.toFixed(2)}
def={1}
/>
<div className="tabs">
{(['rgb', 'red', 'green', 'blue'] as CurveChannel[]).map((c) => (
<button key={c} className={`tab ${channel === c ? 'on' : ''}`} onClick={() => setChannel(c)}>
@@ -230,7 +312,18 @@ export function CurvePanel({ edits, set }: PanelSetProps) {
</button>
))}
</div>
<CurveEditor points={points} onChange={update} color={CURVE_COLORS[channel]} />
<CurveEditor
points={points}
onChange={update}
color={CURVE_COLORS[channel]}
parametric={edits.parametric}
onParametric={(key, value) =>
set(
{ parametric: { ...edits.parametric, [key]: value } },
`Parametric ${key}`,
)
}
/>
<div className="subhead">
<span>Parametric</span>
</div>
@@ -689,36 +782,210 @@ export function DetailPanel({ edits, photo, set }: PanelSetProps) {
);
}
const BRAND_PREFIX = /^(Kodak|Fujifilm|Ilford|Agfa|CineStill|Lomography) /;
const ALL = 'All';
const FAVOURITES = 'Favourites';
const MY_PRESETS = 'My presets';
function presetCategory(preset: Preset): string {
if (preset.custom || preset.group === 'User presets') return MY_PRESETS;
return preset.category ?? 'Essentials';
}
/** Film tiles drop the brand, since the group header already names it. */
function shortName(preset: Preset): string {
if (!preset.film) return preset.name;
const prefix = `${preset.group} `;
return preset.name.startsWith(prefix) ? preset.name.slice(prefix.length) : preset.name;
}
const FILM_CATEGORIES = ['Colour Negative', 'Colour Slide', 'Black & White', 'Cinema', 'Instant', 'Redscale', 'Experimental'];
/**
* Category picker for the preset browser. This is a plain menu rather than a
* native <select>: the browser popup tears down when the panel repaints while
* the preset thumbnails stream in, so it would close before you could pick.
*/
function PresetFilterMenu({
value,
onChange,
filmCats,
lookCats,
counts,
}: {
value: string;
onChange: (id: string) => void;
filmCats: { id: string; label: string; hint: string }[];
lookCats: { id: string; label: string; hint: string }[];
counts: Map<string, number>;
}) {
const [open, setOpen] = useState(false);
const root = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const onPointerDown = (event: PointerEvent) => {
if (root.current && event.target instanceof Node && root.current.contains(event.target)) return;
setOpen(false);
};
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') setOpen(false);
};
window.addEventListener('pointerdown', onPointerDown, true);
window.addEventListener('keydown', onKeyDown, true);
return () => {
window.removeEventListener('pointerdown', onPointerDown, true);
window.removeEventListener('keydown', onKeyDown, true);
};
}, [open]);
const labelOf = (id: string) => {
if (id === ALL) return 'All';
if (id === FAVOURITES) return 'Favourites';
if (id === MY_PRESETS) return 'My presets';
return PRESET_CATEGORIES.find((category) => category.id === id)?.label ?? id;
};
const pick = (id: string) => {
onChange(id);
setOpen(false);
};
const item = (id: string, text: string, hint?: string) => (
<button
key={id}
type="button"
role="option"
aria-selected={id === value}
className={`preset-menu-item ${id === value ? 'on' : ''}`}
title={hint}
onClick={() => pick(id)}
>
<span className="preset-menu-label">{text}</span>
<span className="preset-menu-count">{counts.get(id) ?? 0}</span>
</button>
);
return (
<div className="preset-filter" ref={root}>
<button
type="button"
className="preset-select"
aria-label="Preset category"
aria-haspopup="listbox"
aria-expanded={open}
onClick={() => setOpen((prev) => !prev)}
>
<span className="preset-select-text">{labelOf(value)}</span>
<span className="preset-select-chev" aria-hidden="true">
▾
</span>
</button>
{open && (
<div className="preset-menu" role="listbox" aria-label="Preset category">
{item(ALL, 'All')}
{item(FAVOURITES, '★ Favourites')}
{(counts.get(MY_PRESETS) ?? 0) > 0 && item(MY_PRESETS, 'My presets')}
<div className="preset-menu-head">Film stocks</div>
{filmCats.map((category) => item(category.id, category.label, category.hint))}
{lookCats.length > 0 && <div className="preset-menu-head">Creative looks</div>}
{lookCats.map((category) => item(category.id, category.label, category.hint))}
</div>
)}
</div>
);
}
export function PresetsPanel({
presets,
photo,
onApply,
onSave,
onDelete,
}: {
presets: Preset[];
photo: PhotoRecord;
onApply: (preset: Preset) => void;
onSave: (name: string) => void;
onDelete?: (id: string) => void;
}) {
const [query, setQuery] = useState('');
const [filter, setFilter] = usePersistentState<string>('presets.filter', ALL);
const [favourites, setFavourites] = usePersistentState<string[]>('presets.favourites', []);
const [collapsed, setCollapsed] = useState<string[]>([]);
const [variant, setVariant] = useState<FilmVariant>('base');
// Variants are derived on the fly, so every stock gets push/pull and split
// grade versions without tripling the catalogue.
const shown = useMemo(() => presets.map((p) => applyFilmVariant(p, variant)), [presets, variant]);
const [focusedId, setFocusedId] = useState<string | null>(null);
const groups = new Map<string, Preset[]>();
for (const preset of shown) {
const arr = groups.get(preset.group) ?? [];
arr.push(preset);
groups.set(preset.group, arr);
}
const all = useMemo(
() => presets.map((preset) => ({ ...preset, category: presetCategory(preset) })),
[presets],
);
const counts = useMemo(() => {
const map = new Map<string, number>([[ALL, all.length]]);
for (const preset of all) {
map.set(preset.category!, (map.get(preset.category!) ?? 0) + 1);
} map.set(FAVOURITES, all.reduce((n, preset) => n + (favourites.includes(preset.id) ? 1 : 0), 0));
map.set(MY_PRESETS, all.reduce((n, preset) => n + (preset.category === MY_PRESETS ? 1 : 0), 0));
return map;
}, [all, favourites]);
// One compact picker instead of a wall of pills: film stocks and creative
// looks are separated, and empty categories stay out of the list.
const filmCats = useMemo(
() => PRESET_CATEGORIES.filter((category) => FILM_CATEGORIES.includes(category.id) && (counts.get(category.id) ?? 0) > 0),
[counts],
);
const lookCats = useMemo(
() => PRESET_CATEGORIES.filter((category) => !FILM_CATEGORIES.includes(category.id) && (counts.get(category.id) ?? 0) > 0),
[counts],
);
const validFilter =
filter === ALL || filter === FAVOURITES || filter === MY_PRESETS || (counts.get(filter) ?? 0) > 0 ? filter : ALL;
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
return all.filter((preset) => {
if (validFilter === FAVOURITES) {
if (!favourites.includes(preset.id)) return false;
} else if (validFilter !== ALL && preset.category !== validFilter) {
return false;
}
if (!q) return true;
return [preset.name, preset.group, preset.category, preset.description ?? '', ...(preset.tags ?? [])]
.join(' ')
.toLowerCase()
.includes(q);
});
}, [all, favourites, validFilter, query]);
// Variants are derived on the fly so every stock ships push/pull and split
// grade versions without multiplying the catalogue.
const shown = useMemo(() => filtered.map((preset) => applyFilmVariant(preset, variant)), [filtered, variant]);
const hasFilm = shown.some((preset) => preset.film);
const thumbs = usePresetThumbs(photo, shown);
const groups = useMemo(() => {
const map = new Map<string, Preset[]>();
for (const preset of shown) {
const arr = map.get(preset.group) ?? [];
arr.push(preset);
map.set(preset.group, arr);
}
return [...map.entries()];
}, [shown]);
const focused = shown.find((preset) => preset.id === focusedId) ?? null;
const starId = (preset: Preset) => (preset.film ? preset.id.split('::')[0] : preset.id);
const toggleFavourite = (id: string) =>
setFavourites((prev) => (prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]));
const toggleGroup = (group: string) =>
setCollapsed((prev) => (prev.includes(group) ? prev.filter((item) => item !== group) : [...prev, group]));
return (
<div className="panel-stack">
<div className="panel-stack preset-browser">
<div className="dev-panel-head">
<span>Presets</span>
<span className="muted small">{shown.length}</span>
<button
className="icon-btn"
title="Save current settings as a preset"
@@ -730,43 +997,131 @@ export function PresetsPanel({
+
</button>
</div>
<div className="variant-row">
{FILM_VARIANTS.map((v) => (
<button
key={v.id}
className={`variant-btn ${variant === v.id ? 'on' : ''}`}
title={v.hint}
onClick={() => setVariant(v.id)}
>
{v.label}
</button>
))}
</div>
{[...groups.entries()].map(([group, items]) => (
<div key={group} className="preset-group">
<div className="preset-group-name">{group}</div>
<div className="preset-grid">
{items.map((preset) => {
const src = thumbs[preset.id];
return (
<button
key={preset.id}
className="preset-tile"
onClick={() => onApply(preset)}
title={`${preset.name}${src ? '' : ' — rendering preview…'}`}
>
{src ? (
<img src={src} alt={preset.name} loading="lazy" draggable={false} />
) : (
<span className="preset-tile-blank" />
)}
<span className="preset-tile-name">{preset.name.replace(BRAND_PREFIX, '')}</span>
</button>
);
})}
</div>
<div className="preset-toolbar">
<div className="preset-search">
<input
value={query}
placeholder="Search film, brand or tag…"
aria-label="Search presets"
onChange={(event) => setQuery(event.target.value)}
onKeyDown={(event) => {
if (event.key === 'Escape') setQuery('');
}}
/>
{query && (
<button className="preset-search-clear" aria-label="Clear search" onClick={() => setQuery('')}>
×
</button>
)}
</div>
))}
<PresetFilterMenu
value={validFilter}
onChange={setFilter}
filmCats={filmCats}
lookCats={lookCats}
counts={counts}
/>
</div>
{hasFilm && (
<div className="variant-row">
{FILM_VARIANTS.map((v) => (
<button
key={v.id}
className={`variant-btn ${variant === v.id ? 'on' : ''}`}
title={v.hint}
onClick={() => setVariant(v.id)}
>
{v.label}
</button>
))}
</div>
)}
<div className="preset-list">
{!shown.length && (
<div className="preset-empty">
{validFilter === FAVOURITES
? 'No favourites yet — hover a preset and click the star.'
: 'No presets match this search.'}
</div>
)}
{groups.map(([group, items]) => {
const isCollapsed = collapsed.includes(group);
return (
<div key={group} className="preset-group">
<button
className="preset-group-head"
aria-expanded={!isCollapsed}
onClick={() => toggleGroup(group)}
>
<span>{group}</span>
<span className="preset-group-count">{items.length}</span>
<span className="preset-group-chev">{isCollapsed ? '▸' : '▾'}</span>
</button>
{!isCollapsed && (
<div className="preset-grid">
{items.map((preset) => {
const src = thumbs[preset.id];
const favourite = favourites.includes(starId(preset));
return (
<div key={preset.id} className="preset-tile-wrap">
<button
className="preset-tile"
onClick={() => onApply(preset)}
onMouseEnter={() => setFocusedId(preset.id)}
onFocus={() => setFocusedId(preset.id)}
title={`${preset.name}${src ? '' : ' — rendering preview…'}`}
>
{src ? (
<img src={src} alt={preset.name} loading="lazy" draggable={false} />
) : (
<span className="preset-tile-blank" />
)}
<span className="preset-tile-name">{shortName(preset)}</span>
</button>
<button
className={`preset-star ${favourite ? 'on' : ''}`}
aria-label={favourite ? `Unstar ${preset.name}` : `Star ${preset.name}`}
aria-pressed={favourite}
onClick={() => toggleFavourite(starId(preset))}
>
★
</button>
{onDelete && presetCategory(preset) === MY_PRESETS && (
<button
className="preset-del"
aria-label={`Delete ${preset.name}`}
title="Delete preset"
onClick={() => {
if (window.confirm(`Delete preset “${preset.name}”?`)) onDelete(preset.id);
}}
>
×
</button>
)}
</div>
);
})}
</div>
)}
</div>
);
})}
</div>
{focused && (
<div className="preset-detail">
<strong>{focused.name}</strong>
{focused.description && <span>{focused.description}</span>}
<span className="preset-detail-meta">
{[focused.film?.process, focused.film?.speed ? `ISO ${focused.film.speed}` : null, focused.group]
.filter(Boolean)
.join(' · ')}
</span>
</div>
)}
</div>
);
}
@@ -1130,6 +1485,7 @@ export function LocalPanel({
onPasteLayer,
canPaste,
onAutoMask,
onSampleRange,
autoBusy,
}: PanelSetProps & {
activeId: string | null;
@@ -1145,6 +1501,8 @@ export function LocalPanel({
onPasteLayer: () => void;
canPaste: boolean;
onAutoMask: (kind: 'subject' | 'sky' | 'background') => void;
/** Arms the canvas click that samples a colour range for the active layer. */
onSampleRange: () => void;
autoBusy?: boolean;
}) {
const layers = edits.local ?? [];
@@ -1160,26 +1518,26 @@ export function LocalPanel({
active && patch({ range: { ...active.range, [key]: value } }, 'Local range');
return (
<Panel title="Local adjustments" right={<span className="muted small">{layers.length}/4</span>}>
<Panel title="Local adjustments" right={<span className="muted small">{layers.length}/{MAX_LOCAL_LAYERS}</span>}>
<div className="btn-row local-add">
<button className="btn ghost small" onClick={() => onAdd('brush')} disabled={layers.length >= 4}>
<button className="btn ghost small" onClick={() => onAdd('brush')} disabled={layers.length >= MAX_LOCAL_LAYERS}>
{LOCAL_ICON.brush} Brush
</button>
<button className="btn ghost small" onClick={() => onAdd('linear')} disabled={layers.length >= 4}>
<button className="btn ghost small" onClick={() => onAdd('linear')} disabled={layers.length >= MAX_LOCAL_LAYERS}>
{LOCAL_ICON.linear} Linear
</button>
<button className="btn ghost small" onClick={() => onAdd('radial')} disabled={layers.length >= 4}>
<button className="btn ghost small" onClick={() => onAdd('radial')} disabled={layers.length >= MAX_LOCAL_LAYERS}>
{LOCAL_ICON.radial} Radial
</button>
</div>
<div className="btn-row local-add auto-mask-row">
<button className="btn ghost small" onClick={() => onAutoMask('subject')} disabled={layers.length >= 4 || autoBusy}>
<button className="btn ghost small" onClick={() => onAutoMask('subject')} disabled={layers.length >= MAX_LOCAL_LAYERS || autoBusy}>
{autoBusy ? '…' : '✦'} Subject
</button>
<button className="btn ghost small" onClick={() => onAutoMask('sky')} disabled={layers.length >= 4 || autoBusy}>
<button className="btn ghost small" onClick={() => onAutoMask('sky')} disabled={layers.length >= MAX_LOCAL_LAYERS || autoBusy}>
{autoBusy ? '…' : '✦'} Sky
</button>
<button className="btn ghost small" onClick={() => onAutoMask('background')} disabled={layers.length >= 4 || autoBusy}>
<button className="btn ghost small" onClick={() => onAutoMask('background')} disabled={layers.length >= MAX_LOCAL_LAYERS || autoBusy}>
{autoBusy ? '…' : '✦'} Background
</button>
</div>
@@ -1195,7 +1553,7 @@ export function LocalPanel({
<button
className="btn ghost small"
onClick={onPasteLayer}
disabled={!canPaste || layers.length >= 4}
disabled={!canPaste || layers.length >= MAX_LOCAL_LAYERS}
title="Paste the copied mask into this photo"
>
Paste mask
@@ -1234,7 +1592,7 @@ export function LocalPanel({
>
{maskMode ? 'Done mask' : 'Edit mask'}
</button>
<button className="btn ghost small" onClick={() => onDuplicate(active.id)} disabled={layers.length >= 4}>
<button className="btn ghost small" onClick={() => onDuplicate(active.id)} disabled={layers.length >= MAX_LOCAL_LAYERS}>
Duplicate
</button>
<button className="btn ghost small danger" onClick={() => onDelete(active.id)}>
@@ -1272,6 +1630,26 @@ export function LocalPanel({
/>
)}
<div className="local-subhead">Combine</div>
<div className="btn-row local-modes">
{(['add', 'subtract', 'intersect'] as const).map((mode) => (
<button
key={mode}
className={`chip tiny ${active.mode === mode ? 'on' : ''}`}
title={
mode === 'add'
? 'Apply this adjustment inside the mask'
: mode === 'subtract'
? 'Apply it outside this mask, within the layer above'
: 'Apply it only where this mask overlaps the layer above'
}
onClick={() => patch({ mode }, `Mask ${mode}`)}
>
{mode === 'add' ? 'Add' : mode === 'subtract' ? 'Subtract' : 'Intersect'}
</button>
))}
</div>
<div className="local-subhead">Light</div>
<Slider
label="Exposure"
@@ -1297,6 +1675,38 @@ export function LocalPanel({
value={active.adjust.shadows}
onChange={(v) => adjust('shadows', v)}
/>
<Slider
label="Whites"
value={active.adjust.whites}
onChange={(v) => adjust('whites', v)}
/>
<Slider
label="Blacks"
value={active.adjust.blacks}
onChange={(v) => adjust('blacks', v)}
/>
<div className="local-subhead">Detail</div>
<Slider
label="Texture"
value={active.adjust.texture}
onChange={(v) => adjust('texture', v)}
/>
<Slider
label="Clarity"
value={active.adjust.clarity}
onChange={(v) => adjust('clarity', v)}
/>
<Slider
label="Dehaze"
value={active.adjust.dehaze}
onChange={(v) => adjust('dehaze', v)}
/>
<Slider
label="Sharpen"
value={active.adjust.sharpen}
onChange={(v) => adjust('sharpen', v)}
/>
<div className="local-subhead">Colour</div>
<Slider
@@ -1311,9 +1721,30 @@ export function LocalPanel({
value={active.adjust.saturation}
onChange={(v) => adjust('saturation', v)}
/>
<Slider
label="Vibrance"
value={active.adjust.vibrance}
onChange={(v) => adjust('vibrance', v)}
/>
<Slider
label="Hue shift"
min={-180}
max={180}
value={active.adjust.hue}
onChange={(v) => adjust('hue', v)}
format={(v) => `${v > 0 ? '+' : ''}${Math.round(v)}°`}
track={HUE_TRACK}
/>
<div className="local-subhead">
Range
<button
className="chip tiny"
onClick={onSampleRange}
title="Click a colour in the photo to limit this mask to similar hues"
>
Sample
</button>
<button
className={`chip tiny ${active.range.enabled ? 'on' : ''}`}
onClick={() => range('enabled', !active.range.enabled)}
@@ -1380,9 +1811,17 @@ export function LocalPanel({
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,
},
range: { ...active.range, enabled: false },
},
@@ -1725,8 +2164,104 @@ export function OpticsPanel({
);
}
export function ProofPanel({ edits, set }: PanelSetProps) {
/**
* A DCP profile supplies the same XYZ-to-camera matrix the body writes into a
* raw. Only the derived camera-to-sRGB matrix is stored in the edit: the profile
* file itself is not kept, so a photo stays self-contained and the choice
* round-trips through presets and XMP like any other setting.
*/
export function CameraProfilePanel({
edits,
photo,
set,
cameraNative = false,
}: PanelSetProps & { cameraNative?: boolean }) {
const [error, setError] = useState<string | null>(null);
const profile = edits.cameraProfile;
const load = async (file: File) => {
if (!cameraNative) return;
try {
const parsed = parseDcp(new Uint8Array(await file.arrayBuffer()));
if (!parsed) throw new Error('That file is not a DCP camera profile');
const matrix = dcpRgbCam(parsed);
if (!matrix) throw new Error('This profile has no usable colour matrix');
setError(null);
set({ cameraProfile: { name: parsed.name, matrix } }, 'Camera profile');
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not read that profile');
}
};
// Camera profiles describe raw sensor data; a JPEG has already been through
// the body's converter, so the panel would have nothing to act on.
if (!photo.raw) return null;
return (
<Panel title="Camera profile" defaultOpen={false}>
{cameraNative && (
<div className="btn-row">
<label className="btn ghost small">
{profile ? 'Replace DCP profile' : 'Load DCP profile'}
<input
type="file"
accept=".dcp"
hidden
onChange={(e) => {
const file = e.target.files?.[0];
if (file) void load(file);
e.target.value = '';
}}
/>
</label>
{profile && (
<button
className="btn ghost small"
onClick={() => {
setError(null);
set({ cameraProfile: null }, 'Body camera profile');
}}
>
Use body matrix
</button>
)}
</div>
)}
<p className="muted small panel-hint">
{!cameraNative
? 'This proxy was decoded straight to sRGB, so there are no camera samples to profile. Reprocess the RAW to enable camera profiles.'
: profile
? `Rendering through ${profile.name}.`
: 'Rendering with the matrix stored in the raw. Load a .dcp to render through a different camera profile.'}
</p>
{error && <p className="muted small panel-hint">{error}</p>}
</Panel>
);
}
export function ProofPanel({
edits,
set,
proofProfile,
onProofProfile,
}: PanelSetProps & {
/** Name of the printer profile loaded for this session, if any. */
proofProfile?: string | null;
onProofProfile?: (cube: SoftProofCube | null) => void;
}) {
const proof = edits.proof;
const [profileError, setProfileError] = useState<string | null>(null);
const loadProfile = async (file: File) => {
try {
const cube = loadProofProfile(new Uint8Array(await file.arrayBuffer()));
setProfileError(null);
onProofProfile?.(cube);
} catch (err) {
setProfileError(err instanceof Error ? err.message : 'Could not read that profile');
}
};
return (
<Panel title="Soft proofing" defaultOpen={false}>
<div className="btn-row">
@@ -1767,8 +2302,44 @@ export function ProofPanel({ edits, set }: PanelSetProps) {
format={(v) => `${Math.round(v)}%`}
def={2}
/>
<div className="subhead">
<span>Printer profile</span>
</div>
<div className="btn-row">
<label className="btn ghost small">
{proofProfile ? 'Replace ICC profile' : 'Load ICC profile'}
<input
type="file"
accept=".icc,.icm,application/vnd.iccprofile"
hidden
onChange={(e) => {
const file = e.target.files?.[0];
if (file) void loadProfile(file);
e.target.value = '';
}}
/>
</label>
{proofProfile && (
<button
className="btn ghost small"
onClick={() => {
setActiveProofCube(null);
setProfileError(null);
onProofProfile?.(null);
}}
>
Use paper simulation
</button>
)}
</div>
<p className="muted small panel-hint">
Paper white, black point and a print-gamut preview are applied to the canvas and export. Turn off before delivering screen files.
{proofProfile
? `Proofing through ${proofProfile}: the canvas and exports show what this printer can reproduce.`
: 'Load a printer .icc/.icm to prove through its real A2B/B2A tables. Without one, the paper controls are an approximation.'}
</p>
{profileError && <p className="muted small panel-hint">{profileError}</p>}
<p className="muted small panel-hint">
Turn proofing off before delivering screen files.
</p>
</Panel>
);
+68 -4
View File
@@ -3,9 +3,11 @@ import {
addGalleryComment,
galleryDownloadAllUrl,
galleryDownloadUrl,
getGalleryStatus,
loadGallery,
setGalleryPick,
setGalleryReview,
unlockGallery,
} from '../lib/api';
import type { GalleryPayload, GalleryPhoto } from '../lib/api';
@@ -74,9 +76,22 @@ export default function ProofingGallery({ token }: { token: string }) {
const [saving, setSaving] = useState<Set<string>>(new Set());
const [commentDraft, setCommentDraft] = useState('');
const [feedbackBusy, setFeedbackBusy] = useState(false);
const [locked, setLocked] = useState(false);
const [password, setPassword] = useState('');
const [unlocking, setUnlocking] = useState(false);
const load = useCallback(async () => {
try {
// The status call is what turns a locked link into a password prompt
// instead of a dead end: the gallery body is a 401 while locked.
const status = await getGalleryStatus(token);
if (status.locked) {
setLocked(true);
setData(null);
setFatal(null);
return;
}
setLocked(false);
const payload = await loadGallery(token, identity.current.id);
setData(payload);
setPicks(new Set(payload.photos.filter((p) => p.mine).map((p) => p.id)));
@@ -103,6 +118,21 @@ export default function ProofingGallery({ token }: { token: string }) {
};
}, [data]);
const unlock = async () => {
if (unlocking || !password) return;
setUnlocking(true);
setError(null);
try {
await unlockGallery(token, password);
setPassword('');
await load();
} catch (err) {
setError(err instanceof Error ? err.message : 'That password did not work');
} finally {
setUnlocking(false);
}
};
const rememberName = (name: string) => {
setClientName(name);
try {
@@ -260,6 +290,38 @@ export default function ProofingGallery({ token }: { token: string }) {
);
}
if (!data && locked) {
return (
<div className="proof">
<div className="proof-splash proof-lock">
<div className="logo large">Luminary</div>
<h1>This gallery is private</h1>
<p>Enter the password the photographer gave you.</p>
<form
className="proof-lock-form"
onSubmit={(e) => {
e.preventDefault();
void unlock();
}}
>
<input
type="password"
value={password}
autoFocus
autoComplete="current-password"
placeholder="Gallery password"
onChange={(e) => setPassword(e.target.value)}
/>
<button className="btn primary" type="submit" disabled={!password || unlocking}>
{unlocking ? 'Opening…' : 'Open gallery'}
</button>
</form>
{error && <p className="proof-subtle">{error}</p>}
</div>
</div>
);
}
if (!data) {
return (
<div className="proof">
@@ -320,7 +382,7 @@ export default function ProofingGallery({ token }: { token: string }) {
>
My picks {pickedCount ? `(${pickedCount})` : ''}
</button>
{pickedCount > 0 && (
{pickedCount > 0 && data.downloads?.allowed !== false && (
<a
className="btn ghost small"
href={galleryDownloadAllUrl(token, identity.current.id)}
@@ -419,9 +481,11 @@ export default function ProofingGallery({ token }: { token: string }) {
<div className="proof-lb-bar">
<div className="proof-lb-title">
<span className="proof-lb-name">{lightboxPhoto.name}</span>
<a className="btn ghost small" href={galleryDownloadUrl(token, lightboxPhoto.id)} download>
Download
</a>
{data.downloads?.allowed !== false && (
<a className="btn ghost small" href={galleryDownloadUrl(token, lightboxPhoto.id)} download>
Download
</a>
)}
</div>
<button
className={`proof-lb-pick ${picks.has(lightboxPhoto.id) ? 'on' : ''}`}
+103
View File
@@ -0,0 +1,103 @@
export interface RawReprocessFailure {
name: string;
error: string;
}
export interface RawReprocessJob {
running: boolean;
/** Files attempted so far, including failures. */
done: number;
total: number;
current: string;
eventName?: string;
failures: RawReprocessFailure[];
cancelled?: boolean;
}
interface Props {
job: RawReprocessJob;
onCancel: () => void;
onClose: () => void;
}
/**
* Progress and summary for a RAW re-decode run. The job keeps running while the
* dialog is open; Cancel stops it after the file already in flight.
*/
export default function RawReprocessModal({ job, onCancel, onClose }: Props) {
const succeeded = Math.max(0, job.done - job.failures.length);
const pct = job.total ? Math.round((job.done / job.total) * 100) : 0;
const scope = job.eventName ? `“${job.eventName}”` : 'the selection';
return (
<div
className="modal-backdrop"
onPointerDown={(e) => e.target === e.currentTarget && !job.running && onClose()}
>
<div className="modal raw-modal" role="dialog" aria-modal="true" aria-label="RAW reprocess">
<header className="modal-head">
<div>
<h2>{job.running ? 'Reprocessing RAW files' : 'RAW reprocess summary'}</h2>
<p className="muted small">
{job.total} RAW file{job.total === 1 ? '' : 's'} from {scope}. Existing edits and crops
are kept.
</p>
</div>
{!job.running && (
<button className="icon-btn" onClick={onClose} title="Close">
×
</button>
)}
</header>
<div className="modal-body">
<div className="progress-bar">
<div className="progress-fill" style={{ width: `${pct}%` }} />
</div>
<p className="muted small">
{job.running
? job.cancelled
? `Stopping after the current file · ${job.done} of ${job.total}`
: `${job.done} of ${job.total}${job.current ? ` · ${job.current}` : '…'}`
: job.cancelled
? `Stopped after ${job.done} of ${job.total}. Reprocessed ${succeeded}.`
: `Reprocessed ${succeeded} of ${job.total}.`}
</p>
{!job.running && job.failures.length > 0 && (
<div className="failures">
<strong>
{job.failures.length} file{job.failures.length === 1 ? '' : 's'} failed
</strong>
<ul>
{job.failures.slice(0, 12).map((failure) => (
<li key={failure.name}>
{failure.name}: {failure.error}
</li>
))}
</ul>
{job.failures.length > 12 && (
<p className="muted small">And {job.failures.length - 12} more…</p>
)}
</div>
)}
</div>
<footer className="modal-foot">
{job.running ? (
<>
<span className="muted small">Cancel stops after the current file.</span>
<button className="btn ghost danger" onClick={onCancel} disabled={job.cancelled}>
{job.cancelled ? 'Stopping…' : 'Cancel'}
</button>
</>
) : (
<button className="btn primary" onClick={onClose}>
Done
</button>
)}
</footer>
</div>
</div>
);
}
+152 -6
View File
@@ -1,9 +1,10 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { createShare, getShare, pushProof, revokeShare } from '../lib/api';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createShare, getShare, pushProof, revokeShare, saveShareSettings } from '../lib/api';
import type { ShareState } from '../lib/api';
import { DEFAULT_EXPORT, renderPhotoBlob } from '../lib/export';
import type { ExportOptions } from '../lib/export';
import type { PhotoRecord } from '../types';
import { Renderer } from '../gl/renderer';
interface Props {
event: { id: string; name: string };
@@ -50,6 +51,13 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
const [published, setPublished] = useState(0);
const [error, setError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const [passwordDraft, setPasswordDraft] = useState('');
const [expiryDraft, setExpiryDraft] = useState('');
const [watermarkDraft, setWatermarkDraft] = useState('');
const [downloadsOn, setDownloadsOn] = useState(true);
const [capDraft, setCapDraft] = useState('0');
const [savingSettings, setSavingSettings] = useState(false);
const settingsLoaded = useRef(false);
const refresh = useCallback(async () => {
try {
@@ -93,15 +101,44 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
const namesByPhoto = useMemo(() => new Map(photos.map((p) => [p.id, p.name])), [photos]);
const publishProofs = async () => {
// Seeded once: the 20-second refresh must not overwrite fields being typed.
useEffect(() => {
const saved = share?.settings;
if (!saved || settingsLoaded.current) return;
settingsLoaded.current = true;
setExpiryDraft(saved.expiresAt ? new Date(saved.expiresAt).toISOString().slice(0, 10) : '');
setWatermarkDraft(saved.watermark ?? '');
setDownloadsOn(saved.allowDownloads !== false);
setCapDraft(String(saved.downloadCap || 0));
}, [share]);
const publishProofs = async (watermark = share?.settings?.watermark ?? '') => {
if (!photos.length || publishing) return 0;
// The gallery watermark is baked into the published proof, so the
// downloadable file carries it too — not just the on-screen overlay.
const proofExport: ExportOptions = {
...PROOF_EXPORT,
watermark: {
...PROOF_EXPORT.watermark,
enabled: Boolean(watermark.trim()),
text: watermark.trim(),
},
};
setPublishing(true);
setPublished(0);
setError(null);
let done = 0;
// One context and one shader compile for the whole batch: a proof run over
// an event would otherwise create and tear down a renderer per photo.
let shared: Renderer | null = null;
try {
shared = new Renderer(document.createElement('canvas'));
} catch {
shared = null;
}
try {
for (const photo of photos) {
const blob = await renderPhotoBlob(photo, PROOF_EXPORT);
const blob = await renderPhotoBlob(photo, proofExport, shared ?? undefined);
const result = await pushProof(photo.id, await proofBase64(blob));
onProofPublished?.(photo.id, result.thumbUrl, result.proofAt);
done += 1;
@@ -113,6 +150,7 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
setError(err instanceof Error ? err.message : 'Could not publish the edited proofs');
return done;
} finally {
shared?.dispose();
setPublishing(false);
}
};
@@ -122,9 +160,10 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
setError(null);
try {
await createShare(event.id);
await refresh();
const state = await getShare(event.id);
setShare(state);
// A gallery without rendered proofs would show the unedited originals.
await publishProofs();
await publishProofs(state.settings?.watermark ?? '');
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not create the link');
} finally {
@@ -144,6 +183,28 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
}
};
const saveSettings = async (password?: string) => {
if (savingSettings) return;
setSavingSettings(true);
setError(null);
try {
const settings = await saveShareSettings(event.id, {
...(password === undefined ? {} : { password }),
expiresAt: expiryDraft ? new Date(`${expiryDraft}T23:59:59`).getTime() : null,
watermark: watermarkDraft.trim(),
allowDownloads: downloadsOn,
downloadCap: Math.max(0, Math.round(Number(capDraft) || 0)),
});
setShare((prev) => (prev ? { ...prev, settings } : prev));
setPasswordDraft('');
onToast(password === '' ? 'Gallery password removed' : 'Gallery settings saved');
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not save the gallery settings');
} finally {
setSavingSettings(false);
}
};
const revoke = async () => {
if (!window.confirm('Turn off this proofing link? Anyone using it will lose access and its picks will be cleared.')) {
return;
@@ -212,6 +273,91 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
</div>
</div>
<div className="share-settings">
<div className="share-picks-head">
<span>Access and delivery</span>
<span className="muted small">
{share.settings?.passwordSet ? 'Password protected' : 'Anyone with the link'}
</span>
</div>
<div className="share-settings-grid">
<label>
<span>Password</span>
<input
type="password"
value={passwordDraft}
autoComplete="new-password"
placeholder={
share.settings?.passwordSet ? 'Set — type a new one' : 'Optional'
}
onChange={(e) => setPasswordDraft(e.target.value)}
/>
</label>
<label>
<span>Expires</span>
<input
type="date"
value={expiryDraft}
onChange={(e) => setExpiryDraft(e.target.value)}
/>
</label>
<label>
<span>Download cap</span>
<input
type="number"
min={0}
step={1}
value={capDraft}
onChange={(e) => setCapDraft(e.target.value)}
/>
</label>
<label className="share-settings-wide">
<span>Watermark on proofs</span>
<input
value={watermarkDraft}
maxLength={80}
placeholder="© Studio name"
onChange={(e) => setWatermarkDraft(e.target.value)}
/>
</label>
</div>
<div className="share-settings-actions">
<button
className={`chip tiny ${downloadsOn ? 'on' : ''}`}
onClick={() => setDownloadsOn((v) => !v)}
title="Let clients download their picks"
>
Downloads {downloadsOn ? 'on' : 'off'}
</button>
<span className="muted small">
Cap 0 means unlimited · {share.settings?.downloadCount ?? 0} used
</span>
<div className="spacer" />
{share.settings?.passwordSet && (
<button
className="btn ghost small"
disabled={savingSettings}
onClick={() => void saveSettings('')}
>
Remove password
</button>
)}
<button
className="btn primary small"
disabled={savingSettings}
onClick={() =>
void saveSettings(passwordDraft.trim() ? passwordDraft.trim() : undefined)
}
>
{savingSettings ? 'Saving…' : 'Save settings'}
</button>
</div>
<p className="muted small">
Expiry closes the link at the end of that day. The watermark is rendered into
freshly published proofs; republish after changing it.
</p>
</div>
<div className="share-publish">
<div>
<strong>Edited proofs</strong>
+194
View File
@@ -0,0 +1,194 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { listTether, removeTetherFile, tetherFileUrl } from '../lib/api';
import type { TetherFile } from '../lib/api';
interface Props {
event: { id: string; name: string };
/** Imports the frames and resolves with how many became photos. */
onImport: (files: File[]) => Promise<number>;
onClose: () => void;
}
interface LogEntry {
name: string;
at: number;
ok: boolean;
message: string;
}
const POLL_MS = 4000;
function stamp(ms: number) {
return new Date(ms).toLocaleTimeString(undefined, {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
});
}
/**
* Tethering: watch a folder on the server and import what appears in it.
*
* Cameras and capture apps write into `<data>/tether/<event>`; this panel
* polls that folder, pulls each new frame, runs the normal import path (so raw
* decoding, metadata and cloud mirroring all behave the same as a drag and
* drop), then deletes the file from the folder. A file is only deleted after a
* successful import, so a closed tab or a dropped connection leaves it queued.
*/
export default function TetherPanel({ event, onImport, onClose }: Props) {
const [folder, setFolder] = useState('');
const [waiting, setWaiting] = useState<TetherFile[]>([]);
const [log, setLog] = useState<LogEntry[]>([]);
const [watching, setWatching] = useState(true);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [imported, setImported] = useState(0);
const seen = useRef(new Set<string>());
const working = useRef(false);
const watchingRef = useRef(true);
watchingRef.current = watching;
const drain = useCallback(async () => {
if (working.current || !watchingRef.current) return;
working.current = true;
setBusy(true);
try {
const state = await listTether(event.id);
setFolder(state.folder);
setWaiting(state.files);
setError(null);
for (const file of state.files) {
if (!watchingRef.current) break;
const key = `${file.name}:${file.mtime}:${file.size}`;
if (seen.current.has(key)) continue;
seen.current.add(key);
try {
const res = await fetch(tetherFileUrl(event.id, file.name), {
credentials: 'same-origin',
});
if (!res.ok) throw new Error(`Download failed (${res.status})`);
const blob = await res.blob();
const upload = new File([blob], file.name, {
type: blob.type || 'application/octet-stream',
lastModified: file.mtime,
});
const count = await onImport([upload]);
if (count < 1) {
seen.current.delete(key);
throw new Error('Nothing was imported');
}
await removeTetherFile(event.id, file.name).catch(() => undefined);
setImported((n) => n + count);
setLog((entries) =>
[{ name: file.name, at: Date.now(), ok: true, message: 'imported' }, ...entries].slice(0, 40),
);
setWaiting((files) => files.filter((item) => item.name !== file.name));
} catch (err) {
seen.current.delete(key);
setLog((entries) =>
[
{
name: file.name,
at: Date.now(),
ok: false,
message: err instanceof Error ? err.message : 'Import failed',
},
...entries,
].slice(0, 40),
);
}
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not read the tether folder');
} finally {
working.current = false;
setBusy(false);
}
}, [event.id, onImport]);
useEffect(() => {
void drain();
const timer = window.setInterval(() => void drain(), POLL_MS);
return () => window.clearInterval(timer);
}, [drain]);
return (
<div
className="modal-backdrop"
onPointerDown={(e) => e.target === e.currentTarget && onClose()}
>
<div className="modal tether-modal" role="dialog" aria-modal="true" aria-label="Tethering">
<header className="modal-head">
<div>
<h2>Tethering</h2>
<p className="muted small">
Frames dropped into the folder are imported into “{event.name}” automatically.
</p>
</div>
<button className="icon-btn" onClick={onClose} title="Close">
×
</button>
</header>
<div className="modal-body">
{error && <div className="banner error">{error}</div>}
<div className="tether-folder">
<span className="muted small">Watch folder on the server</span>
<code>{folder || 'Reading…'}</code>
<p className="muted small">
Point a tethering app, a camera's transfer folder or a sync client at this path.
JPEG, TIFF, WebP and camera raw files are picked up.
</p>
</div>
<div className="tether-actions">
<button
className={`chip ${watching ? 'on' : ''}`}
onClick={() => setWatching((value) => !value)}
>
{watching ? 'Watching' : 'Paused'}
</button>
<span className="muted small">
{busy
? 'Pulling frames…'
: waiting.length
? `${waiting.length} frame${waiting.length === 1 ? '' : 's'} queued`
: 'Folder is empty'}
</span>
<div className="spacer" />
<span className="muted small">
{imported} imported this session
</span>
<button className="btn ghost small" onClick={() => void drain()} disabled={busy}>
Check now
</button>
</div>
{log.length > 0 && (
<ul className="tether-log">
{log.map((entry, index) => (
<li key={`${entry.name}:${entry.at}:${index}`} className={entry.ok ? 'ok' : 'fail'}>
<span className="tether-time">{stamp(entry.at)}</span>
<span className="tether-name" title={entry.name}>
{entry.name}
</span>
<span className="muted small">{entry.message}</span>
</li>
))}
</ul>
)}
</div>
<footer className="modal-foot">
<span className="muted small">
Files leave the folder only after a successful import.
</span>
<button className="btn" onClick={onClose}>
Done
</button>
</footer>
</div>
</div>
);
}
+11 -6
View File
@@ -2,14 +2,17 @@ import type { LocalLayer } from '../types';
import { MAX_LOCAL_LAYERS } from '../lib/edits';
/**
* Local masks are baked on the CPU into one RGBA texture, one layer per
* channel, so the grade shader can apply up to four adjustments in a single
* Local masks are baked on the CPU into two RGBA textures, one layer per
* channel, so the grade shader can apply up to eight adjustments in a single
* pass. The mask is source-space, which keeps brushes and gradients attached to
* the picture through crops, straightening, zoom and lens correction.
*/
export interface PackedMasks {
/** Layers 1–4, one per channel. */
data: Uint8Array;
/** Layers 5–8, one per channel. */
data2: Uint8Array;
w: number;
h: number;
}
@@ -156,8 +159,9 @@ export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number
const w = 800;
const h = Math.max(120, Math.min(1400, Math.round((w * Math.max(1, srcH)) / Math.max(1, srcW))));
const out = new Uint8Array(w * h * 4);
const out2 = new Uint8Array(w * h * 4);
const count = Math.min(MAX_LOCAL_LAYERS, layers.length);
if (!count) return { data: out, w, h };
if (!count) return { data: out, data2: out2, w, h };
for (let index = 0; index < count; index++) {
const layer = layers[index];
@@ -189,12 +193,13 @@ export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number
const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data;
if (!pixels) continue;
const channel = index;
const channel = index % 4;
const target = index < 4 ? out : out2;
for (let p = 0, o = 0; p < pixels.length; p += 4, o += 4) {
const alpha = pixels[p + 3];
out[o + channel] = layer.inverted ? 255 - alpha : alpha;
target[o + channel] = layer.inverted ? 255 - alpha : alpha;
}
}
return { data: out, w, h };
return { data: out, data2: out2, w, h };
}
+499 -135
View File
@@ -1,8 +1,11 @@
import type { LensCorrection } from '../lib/lensfun';
import type { Preview16 } from '../lib/preview16';
import type { Edits, GeometryEdits } from '../types';
import { buildSampler, clamp01 } from '../lib/curves';
import { bwFilterRgb, MAX_HEAL_SPOTS, MAX_LOCAL_LAYERS } from '../lib/edits';
import { wbGainFor } from '../lib/whiteBalance';
import { buildLocalMasks, maskSignature } from './masks';
import { getActiveProofCube, type SoftProofCube } from '../lib/softProof';
const VERT = `#version 300 es
layout(location = 0) in vec2 a_pos;
@@ -34,8 +37,12 @@ uniform float u_upscale;
/** Explicit source mip level: 0 at 1:1 or magnification, log2(scale) when shrinking. */
uniform float u_srcLod;
uniform float u_temp;
uniform float u_tint;
// Camera-native surrogate: the 16-bit sidecar holds the sensor's own RGB, and
// this matrix takes it to linear sRGB. Zero for ordinary sRGB proxies.
uniform mat3 u_srcCam;
uniform float u_srcMatrix;
uniform vec3 u_wbGain;
uniform float u_exposure;
uniform float u_recovery;
uniform float u_contrast;
@@ -45,6 +52,7 @@ uniform float u_whites;
uniform float u_blacks;
uniform float u_vibrance;
uniform float u_saturation;
uniform float u_redscale;
uniform float u_bw;
uniform vec3 u_bwFilter;
uniform float u_bwFilterAmt;
@@ -65,13 +73,15 @@ uniform vec4 u_healSpot[24];
// x = radius as a fraction of the source width, y = feather (0–1).
uniform vec2 u_healSize[24];
// Local adjustments: four masks packed into one RGBA texture.
uniform sampler2D u_masks;
// Local adjustments: eight masks packed into two RGBA textures.
uniform sampler2D u_masks; // layers 1-4
uniform sampler2D u_masks2; // layers 5-8
uniform int u_localCount;
uniform vec4 u_localAdj[4]; // exposure, contrast, temp, tint
uniform vec4 u_localAdj2[4]; // saturation, highlights, shadows, unused
uniform vec4 u_localRange[4]; // lumaMin, lumaMax, hue, hueRange
uniform vec4 u_localRange2[4]; // satMin, enabled, unused, unused
uniform vec4 u_localAdj[8]; // exposure, contrast, temp, tint
uniform vec4 u_localAdj2[8]; // saturation, highlights, shadows, unused
uniform vec4 u_localAdj3[8]; // whites, blacks, vibrance, hue degrees
uniform vec4 u_localRange[8]; // lumaMin, lumaMax, hue, hueRange
uniform vec4 u_localRange2[8]; // satMin, enabled, unused, unused
// Lens/perspective correction: distortion, vertical, horizontal, rotation.
uniform vec4 u_geom;
@@ -117,6 +127,15 @@ vec3 toSRGB(vec3 c){
return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));
}
// Camera-native proxies keep the sensor's gamma-encoded RGB so the matrix stays
// swappable (a camera profile is just a different matrix). Decode, convert,
// re-encode: every stage below keeps working on sRGB numbers.
vec3 decodeSource(vec3 c){
if (u_srcMatrix < 0.5) return c;
vec3 linear = u_srcCam * toLinear(clamp(c, 0.0, 1.0));
return clamp(toSRGB(max(linear, vec3(0.0))), 0.0, 1.0);
}
vec3 rgb2hsv(vec3 c){
vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
@@ -132,6 +151,79 @@ vec3 hsv2rgb(vec3 c){
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}
// OkLab (Björn Ottosson). Hue and chroma are much closer to perception than
// HSV, so rotating a hue band or lifting saturation no longer drags luminance
// with it, which is what made strong HSL edits look plasticky.
vec3 linearToOkLab(vec3 c){
float l = 0.4122214708 * c.r + 0.5363325363 * c.g + 0.0514459929 * c.b;
float m = 0.2119034982 * c.r + 0.6806995451 * c.g + 0.1073969566 * c.b;
float s = 0.0883024619 * c.r + 0.2817188376 * c.g + 0.6299787005 * c.b;
l = pow(max(l, 0.0), 1.0 / 3.0);
m = pow(max(m, 0.0), 1.0 / 3.0);
s = pow(max(s, 0.0), 1.0 / 3.0);
return vec3(
0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s,
1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s
);
}
vec3 okLabToLinear(vec3 c){
float l = c.x + 0.3963377774 * c.y + 0.2158037573 * c.z;
float m = c.x - 0.1055613458 * c.y - 0.0638541728 * c.z;
float s = c.x - 0.0894841775 * c.y - 1.2914855480 * c.z;
l = l * l * l;
m = m * m * m;
s = s * s * s;
return vec3(
4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s
);
}
// Hue rotation, chroma scale and lightness scale in OkLCh. Vibrance is applied
// as a chroma boost that is strongest where chroma is already low.
vec3 applyHslVibrance(vec3 srgb, float hueDeg, float satScale, float lightScale, float vibrance){
vec3 lab = linearToOkLab(toLinear(clamp(srgb, 0.0, 1.0)));
float C = length(lab.yz);
float h = atan(lab.z, lab.y) + radians(hueDeg);
float vib = 1.0 + (vibrance / 100.0) * 0.9 * (1.0 - clamp(C / 0.22, 0.0, 1.0));
C = clamp(C * satScale * vib, 0.0, 0.4);
lab.x = clamp(lab.x * lightScale, 0.0, 1.25);
lab.y = C * cos(h);
lab.z = C * sin(h);
return clamp(toSRGB(max(okLabToLinear(lab), 0.0)), 0.0, 1.0);
}
// Multiplicative tone controls. Adding a constant in linear light shifts hue
// and cannot set a true black point; a luminance-shaped gain brightens or
// darkens without turning shadows grey or highlights magenta.
vec3 perceptualGain(float lm, float shadows, float highlights, float whites, float blacks){
float sm = smoothstep(0.0, 0.12, lm) * pow(1.0 - lm, 3.0);
float hm = pow(lm, 2.0);
float wm = smoothstep(0.55, 1.0, lm);
float bm = smoothstep(0.30, 0.0, lm);
float g = 1.0
+ (shadows / 100.0) * 0.85 * sm
+ (highlights / 100.0) * 0.70 * hm
+ (whites / 100.0) * 0.50 * wm
+ (blacks / 100.0) * 0.32 * bm;
return vec3(max(0.0, g));
}
// Pushes the shoulder down as a whole and keeps the channel ratios, so a
// recovered highlight stays the colour it was instead of turning grey.
vec3 compressHighlights(vec3 c, float rec){
float m = max(c.r, max(c.g, c.b));
float knee = 0.78;
if (m > knee && rec > 0.001) {
float pulled = knee + (m - knee) / (1.0 + (m - knee) * (2.0 + 12.0 * rec));
c *= mix(1.0, pulled / m, rec);
}
return c;
}
// Catmull-Rom weights for one axis; t is the fraction inside a texel.
vec4 cubicWeights(float t){
float t2 = t * t;
@@ -192,7 +284,7 @@ void main(){
// view is zoomed out or the window aspect differs from the photo.
if (frame.x < u_valid.x || frame.y < u_valid.y ||
frame.x > u_valid.x + u_valid.z || frame.y > u_valid.y + u_valid.w) {
outColor = vec4(0.035, 0.035, 0.04, 1.0);
outColor = vec4(0.035, 0.035, 0.04, 0.0);
return;
}
@@ -208,7 +300,7 @@ void main(){
}
if (s.x < 0.0 || s.x > 1.0 || s.y < 0.0 || s.y > 1.0) {
outColor = vec4(0.035, 0.035, 0.04, 1.0);
outColor = vec4(0.035, 0.035, 0.04, 0.0);
return;
}
@@ -242,19 +334,10 @@ void main(){
src *= lensSample(u_lensVig, u_lensVigSize, lensQ).rgb;
}
// The denoised proxy is the same frame as the source, so it samples at the
// same coordinate and is mixed in before white balance and tone. Grading the
// blend rather than the source keeps the edit looking identical with the
// denoise at 0 and at 100.
if (u_denMix > 0.0) {
src = mix(src, textureLod(u_den, uv, u_srcLod).rgb, u_denMix);
}
// Eyedropper: hand back the untouched source colour at the sampled point.
if (u_pick > 0.5) {
outColor = vec4(src, 1.0);
return;
}
// Camera-native proxies are converted once, before the source is read any
// further: the frame, the healed patches and the eyedropper all work on the
// same sRGB values whatever the camera matrix was.
src = decodeSource(src);
// Spot healing copies a clean patch over the blemish, feathered at the rim.
// It runs on the source colour, before white balance and tone, so a healed
@@ -279,41 +362,56 @@ void main(){
? 1.0 - smoothstep(1.0 - feather, 1.0, dist)
: 1.0;
vec2 patchUv = clamp(uv + (spot.zw - spot.xy), vec2(0.0), vec2(1.0));
src = mix(src, textureLod(u_src, patchUv, u_srcLod).rgb, falloff);
src = mix(src, decodeSource(textureLod(u_src, patchUv, u_srcLod).rgb), falloff);
}
}
// Eyedropper: hand back the untouched source colour at the sampled point.
if (u_pick > 0.5) {
outColor = vec4(src, 1.0);
return;
}
// The denoised proxy is the same frame as the source, at the same coordinate.
// It is generated from the JPEG and is already sRGB, so it is blended after
// the camera conversion. Grading the blend rather than the source keeps the
// edit looking identical with the denoise at 0 and at 100.
if (u_denMix > 0.0) {
src = mix(src, textureLod(u_den, uv, u_srcLod).rgb, u_denMix);
}
vec3 col = toLinear(clamp(src, 0.0, 1.0));
// White balance (relative to as-shot)
float t = u_temp / 100.0;
float ti = u_tint / 100.0;
vec3 wb = vec3(1.0 + 0.30 * t + 0.06 * ti, 1.0 - 0.16 * ti, 1.0 - 0.26 * t + 0.06 * ti);
col *= wb / max(0.05, luma(wb));
// White balance gains, solved on the CPU: either the relative Temp offset or
// the absolute Kelvin control, both normalised so exposure is unchanged.
col *= u_wbGain;
// Redscale: colour film respooled backwards, exposed through its base. The
// red-sensitive layer is hit first, green gets what passes through, and blue
// is almost entirely absorbed by the base and mask -- hence red shadows and
// amber/yellow highlights. The matrix encodes that layer order; dividing by
// the neutral response keeps a midtone at its original brightness instead of
// looking underexposed by the light lost in the base.
float rs = clamp(u_redscale / 100.0, 0.0, 1.0);
if (rs > 0.001) {
vec3 baseCol = col;
vec3 redscale = vec3(
baseCol.r * 0.78 + baseCol.g * 0.32 + baseCol.b * 0.06,
baseCol.r * 0.18 + baseCol.g * 0.34 + baseCol.b * 0.03,
baseCol.r * 0.06 + baseCol.g * 0.04 + baseCol.b * 0.02
) / 0.649;
col = mix(baseCol, redscale, rs);
}
// Exposure
col *= exp2(u_exposure);
// Highlight recovery: compress the shoulder instead of clipping it. Scaling
// every channel by one factor keeps hue, so recovered skin stays skin instead
// of turning grey or yellow.
float rec = clamp(u_recovery / 100.0, 0.0, 1.0);
if (rec > 0.001) {
float lum = max(luma(col), 1e-5);
float knee = 0.7;
float over = max(lum - knee, 0.0);
if (over > 0.0) {
float pulled = knee + over / (1.0 + over * (2.0 + 12.0 * rec));
col *= mix(1.0, pulled / lum, rec);
}
}
// Highlight recovery: compress the shoulder and keep the channel ratios.
col = compressHighlights(col, clamp(u_recovery / 100.0, 0.0, 1.0));
// Tonal range
// Tonal range, as luminance-shaped gains so hue survives strong moves.
float lm = clamp(luma(col), 0.0, 1.0);
col += (u_shadows / 100.0) * 0.45 * pow(1.0 - lm, 3.0);
col += (u_highlights / 100.0) * 0.50 * pow(lm, 2.0);
col += (u_whites / 100.0) * 0.34 * smoothstep(0.55, 1.0, lm);
col += (u_blacks / 100.0) * 0.13 * smoothstep(0.30, 0.0, lm);
col *= perceptualGain(lm, u_shadows, u_highlights, u_whites, u_blacks);
vec3 srgb = clamp(toSRGB(col), 0.0, 1.0);
@@ -327,7 +425,9 @@ void main(){
texture(u_curve, vec2(clamp(srgb.b, 0.0, 1.0), 0.5)).b
);
// HSL bands
// HSL bands. The band weights still use sRGB hue (that is what the wheel and
// the presets were authored against), but the shift itself happens in OkLCh,
// where rotating hue does not also change perceived brightness.
vec3 hsv = rgb2hsv(srgb);
float hdeg = hsv.x * 360.0;
float hueWeight = smoothstep(0.02, 0.18, hsv.y);
@@ -349,11 +449,14 @@ void main(){
sShift = sShift / norm;
lShift = lShift / norm;
hsv.x = fract(hsv.x + (hShift / 100.0) * 0.08 + 1.0);
float satMul = sShift >= 0.0 ? 1.0 + (sShift / 100.0) * 0.8 : 1.0 + sShift / 100.0;
hsv.y = clamp(hsv.y * satMul, 0.0, 1.0);
hsv.z = clamp(hsv.z * (1.0 + (lShift / 100.0) * 0.5), 0.0, 1.0);
srgb = hsv2rgb(hsv);
srgb = applyHslVibrance(
srgb,
(hShift / 100.0) * 28.8,
satMul * max(0.0, 1.0 + u_saturation / 100.0),
1.0 + (lShift / 100.0) * 0.35,
u_vibrance
);
if (u_bw > 0.5) {
// A colored filter over the lens changes which hues turn dark in the print:
@@ -364,15 +467,6 @@ void main(){
srgb = vec3(luma(srgb * bwTint) / wl);
}
// Vibrance and saturation
vec3 satRgb = clamp(srgb, 0.0, 1.0);
float mx = max(max(satRgb.r, satRgb.g), satRgb.b);
float mn = min(min(satRgb.r, satRgb.g), satRgb.b);
float curSat = mx - mn;
float gray = luma(satRgb);
srgb = mix(vec3(gray), satRgb, clamp(1.0 + (u_vibrance / 100.0) * (1.0 - curSat) * 0.9, 0.0, 3.0));
srgb = mix(vec3(luma(srgb)), srgb, clamp(1.0 + u_saturation / 100.0, 0.0, 3.0));
// Color grading
float gl = clamp(luma(srgb), 0.0, 1.0);
float bal = u_gBal / 100.0;
@@ -390,15 +484,22 @@ void main(){
// are evaluated from the source colour so they follow skin, sky or shadow
// regardless of how the global grade moved them.
if (u_localCount > 0) {
vec4 maskTexel = texture(u_masks, uv);
vec4 maskA = texture(u_masks, uv);
vec4 maskB = texture(u_masks2, uv);
float srcLuma = luma(clamp(src, 0.0, 1.0));
vec3 srcHsv = rgb2hsv(clamp(src, 0.0, 1.0));
for (int i = 0; i < 4; i++) {
// Mask algebra: 0 = add, 1 = subtract, 2 = intersect. Subtract and
// intersect are relative to the layer above, like Lightroom's modes.
float prevMask = 1.0;
for (int i = 0; i < 8; i++) {
if (i >= u_localCount) break;
float m = i == 0 ? maskTexel.r : i == 1 ? maskTexel.g : i == 2 ? maskTexel.b : maskTexel.a;
int k = i < 4 ? i : i - 4;
vec4 texel = i < 4 ? maskA : maskB;
float m = k == 0 ? texel.r : k == 1 ? texel.g : k == 2 ? texel.b : texel.a;
if (m < 0.002) continue;
vec4 adj = u_localAdj[i];
vec4 adj2 = u_localAdj2[i];
vec4 adj3 = u_localAdj3[i];
vec4 range = u_localRange[i];
vec4 range2 = u_localRange2[i];
@@ -414,6 +515,11 @@ void main(){
float sw = smoothstep(range2.x - 0.02, range2.x + 0.02, srcHsv.y);
m *= lw * hw * sw;
}
float rawMask = m;
float localMode = adj2.w;
if (localMode > 1.5) m = prevMask * rawMask;
else if (localMode > 0.5) m = prevMask * (1.0 - rawMask);
prevMask = rawMask;
if (m < 0.002) continue;
vec3 lin = toLinear(clamp(srgb, 0.0, 1.0));
@@ -422,25 +528,31 @@ void main(){
float lti = adj.w / 100.0;
vec3 lwb = vec3(1.0 + 0.30 * lt + 0.06 * lti, 1.0 - 0.16 * lti, 1.0 - 0.26 * lt + 0.06 * lti);
lin *= lwb / max(0.05, luma(lwb));
vec3 local = toSRGB(clamp(lin, 0.0, 1.0));
vec3 local = clamp(toSRGB(max(lin, 0.0)), 0.0, 1.0);
local = clamp((local - 0.5) * (1.0 + (adj.y / 100.0) * 1.1) + 0.5, 0.0, 1.0);
float ll = clamp(luma(local), 0.0, 1.0);
local += (adj2.z / 100.0) * 0.45 * pow(1.0 - ll, 3.0);
local += (adj2.y / 100.0) * 0.50 * pow(ll, 2.0);
// Desaturate in linear light. Mixing towards a gamma-space luma drags a
// saturated colour towards a much darker grey (a pure red collapses to
// near black), so pulling saturation down made the masked area look muddy
// instead of simply calmer. Scaling chroma around the linear luminance
// keeps the brightness of the patch where it was.
vec3 localLin = toLinear(clamp(local, 0.0, 1.0));
float localLuma = luma(localLin);
localLin = mix(vec3(localLuma), localLin, clamp(1.0 + adj2.x / 100.0, 0.0, 2.0));
local = clamp(toSRGB(max(localLin, vec3(0.0))), 0.0, 1.0);
local = clamp(
toSRGB(max(toLinear(local) * perceptualGain(ll, adj2.z, adj2.y, adj3.x, adj3.y), 0.0)),
0.0,
1.0
);
local = applyHslVibrance(
local,
adj3.w,
max(0.0, 1.0 + adj2.x / 100.0),
1.0,
adj3.z
);
srgb = mix(srgb, clamp(local, 0.0, 1.0), m);
}
}
outColor = vec4(clamp(srgb, 0.0, 1.0), 1.0);
// Alpha carries the *source* clipping state to the finish pass, so the
// warning reflects the pixels the sensor/proxy had, not the graded result.
float clipFlag = 0.0;
if (max(src.r, max(src.g, src.b)) >= 0.996) clipFlag += 0.5;
if (min(src.r, min(src.g, src.b)) <= 0.004) clipFlag += 0.25;
outColor = vec4(clamp(srgb, 0.0, 1.0), clipFlag);
}`;
const BLUR_FRAG = `#version 300 es
@@ -465,11 +577,20 @@ out vec4 outColor;
uniform sampler2D u_graded;
uniform sampler2D u_blurSmall;
uniform sampler2D u_blurBig;
// Local detail masks: shape only, one layer per channel, same packing as the
// grade pass. Amounts are added to the global sliders per pixel.
uniform sampler2D u_masks;
uniform sampler2D u_masks2;
uniform int u_localCount;
uniform vec4 u_localDetail[8]; // texture, clarity, dehaze, sharpen
uniform vec4 u_localModes[8]; // x = add / subtract / intersect
uniform float u_texture;
uniform float u_clarity;
uniform float u_dehaze;
uniform float u_sharpen;
uniform float u_sharpenMask;
uniform float u_sharpenDetail;
uniform float u_nrDetail;
uniform float u_detailScale;
uniform float u_lensSoft;
uniform float u_nr;
@@ -497,6 +618,11 @@ uniform float u_proofEnable;
uniform vec3 u_proofPaper;
uniform float u_proofBlack;
uniform float u_gamut;
// Real ICC proof: a 3D table built from a printer profile, sRGB in and out.
// Its alpha channel flags colours the printer cannot reach.
// sampler3D has no default precision in GLSL ES 3.00, unlike sampler2D.
uniform highp sampler3D u_proofLut;
uniform float u_proofLutOn;
float luma(vec3 c){ return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
@@ -533,24 +659,61 @@ void main(){
vec3 bs = texture(u_blurSmall, v_uv).rgb;
vec3 bb = texture(u_blurBig, v_uv).rgb;
// Noise reduction blends towards a smoothed version first.
// Local detail amounts: walk the same add/subtract/intersect algebra the
// grade pass uses, then add the covered layer amounts to the global sliders.
float localTexture = 0.0;
float localClarity = 0.0;
float localDehaze = 0.0;
float localSharpen = 0.0;
if (u_localCount > 0) {
vec4 maskA = texture(u_masks, v_uv);
vec4 maskB = texture(u_masks2, v_uv);
float prevMask = 1.0;
for (int i = 0; i < 8; i++) {
if (i >= u_localCount) break;
int k = i < 4 ? i : i - 4;
vec4 texel = i < 4 ? maskA : maskB;
float rawMask = k == 0 ? texel.r : k == 1 ? texel.g : k == 2 ? texel.b : texel.a;
float m = rawMask;
float mode = u_localModes[i].x;
if (mode > 1.5) m = prevMask * rawMask;
else if (mode > 0.5) m = prevMask * (1.0 - rawMask);
prevMask = rawMask;
if (m < 0.002) continue;
localTexture += m * u_localDetail[i].x;
localClarity += m * u_localDetail[i].y;
localDehaze += m * u_localDetail[i].z;
localSharpen += m * u_localDetail[i].w;
}
}
float textureAmt = clamp(u_texture + localTexture, -200.0, 200.0);
float clarityAmt = clamp(u_clarity + localClarity, -200.0, 200.0);
float sharpTotal = clamp(u_sharpen + localSharpen, -100.0, 250.0);
float dehazeAmt = clamp(u_dehaze + localDehaze, -200.0, 200.0);
// Noise reduction blends towards a smoothed version first. Detail controls
// how strongly edges are protected from that smoothing.
float nr = clamp(u_nr / 100.0, 0.0, 1.0);
vec3 base = mix(c, mix(bs, bb, 0.5), nr * 0.6);
float nrDetail = clamp(u_nrDetail / 100.0, 0.0, 1.0);
float nrEdge = smoothstep(0.002, 0.02, length(c - bs));
vec3 base = mix(c, mix(bs, bb, 0.5), nr * mix(1.0, nrEdge, nrDetail) * 0.6);
// Local contrast / detail work on gamma encoded values.
vec3 detailSmall = c - bs;
vec3 detailBig = base - bb;
vec3 col = base;
// Masking restricts sharpening to edges. Left at 0 the whole frame is
// sharpened; raised, only differences large enough to be structure qualify,
// so grain and skin texture stop picking up acutance.
// Detail mixes the fine band (texture, pores, grain) with the broader band
// (structure, local contrast), so the slider is a real control instead of a
// stored value. Masking restricts sharpening to edges.
float detailMix = clamp(u_sharpenDetail / 100.0, 0.0, 1.0);
vec3 detailBand = mix(detailBig, detailSmall, detailMix);
float sm = clamp(u_sharpenMask / 100.0, 0.0, 1.0);
float sharpenAmt = (u_sharpen / 100.0) * 1.35;
float sharpenAmt = (sharpTotal / 100.0) * 1.35;
if (sm > 0.001) {
float edge = smoothstep(0.003, 0.012 + sm * 0.085, length(detailSmall));
float edge = smoothstep(0.003, 0.012 + sm * 0.085, length(detailBand));
sharpenAmt *= mix(1.0, edge, sm);
}
col += detailSmall * ((u_texture / 100.0) * 0.9 + sharpenAmt);
col += detailBand * ((textureAmt / 100.0) * 0.9 + sharpenAmt);
// Lens softness compensation: add acutance towards the corners, where most
// wide/normal lenses lose resolving power. It is deliberately edge-weighted
// so the centre does not double-sharpen.
@@ -560,7 +723,7 @@ void main(){
float edge = smoothstep(0.18, 0.72, length(q) / max(0.05, length(vec2(u_aspect, 1.0) * 0.5)));
col += detailSmall * lensSoft * edge * 1.1;
}
col += detailBig * (u_clarity / 100.0) * 1.25;
col += detailBig * (clarityAmt / 100.0) * 1.25;
// Colour noise reduction: smooth only the chroma axes. Luminance is left alone,
// so structure and luminance grain survive while the red/green blotches that
@@ -605,11 +768,15 @@ void main(){
if (green > 0.001) col.g = mix(col.g, (col.r + col.b) * 0.5, green);
}
// Dehaze
float d = u_dehaze / 100.0;
// Dehaze. A single veil value over the whole frame under-corrects a bright
// horizon while flattening the foreground, so the estimate is local: the dark
// channel of the small blur against the atmospheric light in the large blur.
float d = clamp(dehazeAmt / 100.0, -1.0, 1.0);
if (d > 0.0) {
float veil = luma(bb);
col = (col - d * 0.32 * veil * vec3(0.95, 0.98, 1.02)) / max(0.05, 1.0 - d * 0.28);
float dark = min(min(bs.r, bs.g), bs.b);
float atm = max(0.12, luma(bb));
float trans = clamp(1.0 - 0.9 * dark / atm, 0.18, 1.0);
col = (col - atm * (1.0 - trans) * vec3(0.97, 0.99, 1.02)) / mix(1.0, trans, d * 0.9);
} else if (d < 0.0) {
col = mix(col, bb * 0.85 + vec3(0.09), -d * 0.55);
}
@@ -627,21 +794,30 @@ void main(){
else col = mix(col, vec3(1.0), strength * 0.6);
}
// Soft proofing: paper white, black point and a reduced print gamut. This is
// a display simulation, not an ICC transform, but it makes the print intent
// visible while editing and is applied after all creative effects.
// Soft proofing, applied after every creative effect so the paper is what the
// viewer sees. With a printer profile loaded the 3D table is the real ICC
// round trip (PCS -> device -> PCS); without one the paper/black-point
// approximation is all there is.
if (u_proofEnable > 0.5) {
float paperBlack = clamp(u_proofBlack / 100.0, 0.0, 0.2);
col = mix(col, u_proofPaper, 0.035);
col = paperBlack + col * (1.0 - paperBlack);
float y = luma(col);
col = mix(vec3(y), col, 0.88);
if (u_gamut > 0.5) {
float mx = max(col.r, max(col.g, col.b));
float mn = min(col.r, min(col.g, col.b));
float sat = mx > 0.001 ? (mx - mn) / mx : 0.0;
if (sat > 0.62 && (mx > 0.92 || mn < 0.06)) {
col = mix(col, vec3(1.0, 0.0, 0.75), 0.32);
if (u_proofLutOn > 0.5) {
vec4 proofed = texture(u_proofLut, clamp(col, 0.0, 1.0));
col = proofed.rgb;
if (u_gamut > 0.5 && proofed.a > 0.5) {
col = mix(col, vec3(1.0, 0.0, 0.75), 0.55);
}
} else {
float paperBlack = clamp(u_proofBlack / 100.0, 0.0, 0.2);
col = mix(col, u_proofPaper, 0.035);
col = paperBlack + col * (1.0 - paperBlack);
float y = luma(col);
col = mix(vec3(y), col, 0.88);
if (u_gamut > 0.5) {
float mx = max(col.r, max(col.g, col.b));
float mn = min(col.r, min(col.g, col.b));
float sat = mx > 0.001 ? (mx - mn) / mx : 0.0;
if (sat > 0.62 && (mx > 0.92 || mn < 0.06)) {
col = mix(col, vec3(1.0, 0.0, 0.75), 0.32);
}
}
}
}
@@ -681,24 +857,15 @@ void main(){
// Clipping overlay: which channels have run out of headroom. Red/green/blue
// mean one channel clipped, yellow means two, white means all three — the
// same reading Aperture's exposure warnings gave while you dragged.
// The grade pass wrote the untouched source's clipping state into alpha:
// 0.25 shadow, 0.50 highlight, 0.75 both. Warning about the source means it
// still tells the truth after a curve or a shadow lift.
float srcClip = texture(u_graded, v_uv).a;
if (u_clip > 1.5) {
// Shadow clipping: everything that has fallen to the bottom of the range.
if (max(finalCol.r, max(finalCol.g, finalCol.b)) < 0.02) {
finalCol = vec3(0.15, 0.4, 1.0);
}
if (srcClip >= 0.2 && srcClip < 0.5) finalCol = vec3(0.15, 0.4, 1.0);
else if (srcClip >= 0.7) finalCol = vec3(0.15, 0.4, 1.0);
} else if (u_clip > 0.5) {
vec3 k = step(0.985, finalCol);
float n = k.r + k.g + k.b;
if (n > 0.5) {
vec3 mark = vec3(1.0);
if (n < 2.5) {
if (n > 1.5) mark = vec3(1.0, 0.9, 0.1);
else if (k.r > 0.5) mark = vec3(1.0, 0.12, 0.12);
else if (k.g > 0.5) mark = vec3(0.1, 1.0, 0.2);
else mark = vec3(0.15, 0.4, 1.0);
}
finalCol = mark;
}
if (srcClip >= 0.5) finalCol = vec3(1.0);
}
outColor = vec4(finalCol, 1.0);
}`;
@@ -923,6 +1090,13 @@ export function buildCurveLUT(edits: Edits): Uint8Array {
const red = buildSampler(edits.curve.red);
const green = buildSampler(edits.curve.green);
const blue = buildSampler(edits.curve.blue);
const { black, white, gamma } = edits.levels;
const lo = clamp01(black / 100);
const hi = Math.max(lo + 0.01, clamp01(white / 100));
const invGamma = 1 / Math.max(0.3, Math.min(3, gamma));
// Input levels sit before the curve: they set the true black and white points
// and the midtone gamma, so the curve then shapes a full-range signal.
const levels = (x: number) => Math.pow(clamp01((x - lo) / (hi - lo)), invGamma);
const data = new Uint8Array(256 * 4);
// Running maximum keeps the combined curve monotonic: four strong region
// pushes can otherwise fold the curve back on itself and posterise the frame.
@@ -930,7 +1104,7 @@ export function buildCurveLUT(edits: Edits): Uint8Array {
let pg = 0;
let pb = 0;
for (let i = 0; i < 256; i++) {
const base = rgb(i / 255);
const base = rgb(levels(i / 255));
pr = Math.max(pr, parametricTone(edits, red(base)));
pg = Math.max(pg, parametricTone(edits, green(base)));
pb = Math.max(pb, parametricTone(edits, blue(base)));
@@ -984,6 +1158,19 @@ class Prog {
const l = this.loc(name);
if (l) this.gl.uniform3f(l, a, b, c);
}
/**
* Row-major 3x3, as camera matrices are usually written. WebGL wants
* column-major, so the values are transposed on the way in.
*/
m3(name: string, v: ArrayLike<number>) {
const l = this.loc(name);
if (!l || v.length < 9) return;
this.gl.uniformMatrix3fv(
l,
false,
new Float32Array([v[0], v[3], v[6], v[1], v[4], v[7], v[2], v[5], v[8]]),
);
}
fv(name: string, values: Float32Array) {
const l = this.loc(`${name}[0]`) ?? this.loc(name);
if (l) this.gl.uniform1fv(l, values);
@@ -995,6 +1182,13 @@ class Prog {
this.gl.bindTexture(this.gl.TEXTURE_2D, texture);
this.gl.uniform1i(l, unit);
}
tex3d(name: string, texture: WebGLTexture, unit: number) {
const l = this.loc(name);
if (!l) return;
this.gl.activeTexture(this.gl.TEXTURE0 + unit);
this.gl.bindTexture(this.gl.TEXTURE_3D, texture);
this.gl.uniform1i(l, unit);
}
}
function compile(gl: WebGL2RenderingContext, type: number, source: string): WebGLShader {
@@ -1038,6 +1232,7 @@ export class Renderer {
private vao: WebGLVertexArrayObject;
private srcTex: WebGLTexture;
private maskTex: WebGLTexture;
private maskTex2: WebGLTexture;
private lensGeomTex: WebGLTexture;
private lensTcaTex: WebGLTexture;
private lensVigTex: WebGLTexture;
@@ -1046,8 +1241,15 @@ export class Renderer {
private lensSplit = -1;
private maskSig = '';
private srcBitmap: ImageBitmap | null = null;
private srcHdr: Preview16 | null = null;
/** Camera-to-sRGB matrix for a camera-native sidecar, else null. */
private srcCam: number[] | null = null;
private srcW = 1;
private srcH = 1;
private proofTex: WebGLTexture | null = null;
private proofLutOn = 0;
/** Identity guard: the cube is uploaded once per profile, not per frame. */
private proofCube: SoftProofCube | null = null;
private denTex: WebGLTexture;
private denMix = 0;
private denBitmap: ImageBitmap | null = null;
@@ -1130,6 +1332,16 @@ export class Renderer {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
const maskTex2 = gl.createTexture();
if (!maskTex2) throw new Error('Unable to create texture');
this.maskTex2 = maskTex2;
gl.bindTexture(gl.TEXTURE_2D, maskTex2);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4));
const curveTex = gl.createTexture();
if (!curveTex) throw new Error('Unable to create texture');
this.curveTex = curveTex;
@@ -1200,8 +1412,16 @@ export class Renderer {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
}
setImage(bitmap: ImageBitmap) {
if (this.srcBitmap === bitmap) return;
/**
* Uploads the editable source. `hdr` is the 16-bit half of a raw proxy: when
* its size matches the bitmap it replaces the 8-bit JPEG as `u_src`, and the
* whole grade then works from 65,536 levels per channel instead of 256.
*
* The pair is cached together, so a photo whose sidecar arrives a moment after
* its bitmap uploads once more rather than on every redraw.
*/
setImage(bitmap: ImageBitmap, hdr: Preview16 | null = null) {
if (this.srcBitmap === bitmap && this.srcHdr === hdr) return;
// A denoised bitmap belongs to the previous photo; the caller re-supplies it
// after this call when the new photo has one.
this.denMix = 0;
@@ -1210,16 +1430,120 @@ export class Renderer {
this.maskSig = '';
const gl = this.gl;
this.srcBitmap = bitmap;
this.srcHdr = hdr;
this.srcCam = hdr?.rgbCam && hdr.rgbCam.length === 9 ? hdr.rgbCam : null;
this.srcW = bitmap.width;
this.srcH = bitmap.height;
gl.bindTexture(gl.TEXTURE_2D, this.srcTex);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
// Mipmaps: a 6000 px proxy shown fitted is a 4-8x minification, which shimmers
// badly with plain bilinear sampling.
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
const usable = hdr && hdr.width === bitmap.width && hdr.height === bitmap.height ? hdr : null;
let half = false;
if (usable) {
// Clear stale errors so the upload result is ours; bounded in case the
// context is lost and getError keeps reporting CONTEXT_LOST_WEBGL.
for (let guard = 0; guard < 8 && gl.getError() !== gl.NO_ERROR; guard++) {
/* drain */
}
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA16F,
usable.width,
usable.height,
0,
gl.RGBA,
gl.HALF_FLOAT,
usable.rgba,
);
half = gl.getError() === gl.NO_ERROR;
if (half) {
// Half-float mipmaps are optional; without them the fitted view shimmers,
// which is still better than refusing the extra precision.
gl.generateMipmap(gl.TEXTURE_2D);
const mip = gl.getError() === gl.NO_ERROR;
gl.texParameteri(
gl.TEXTURE_2D,
gl.TEXTURE_MIN_FILTER,
mip ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR,
);
}
}
if (!half) {
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
// Mipmaps: a 6000 px proxy shown fitted is a 4-8x minification, which shimmers
// badly with plain bilinear sampling.
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
}
}
/**
* Installs the soft-proof 3D table (an sRGB-to-sRGB cube whose alpha channel
* flags out-of-gamut colours), or clears it to fall back to the paper
* approximation. Uploading happens here rather than per frame: the table is
* built once from a printer profile.
*/
setProofLut(lut: SoftProofCube | null) {
if (lut === this.proofCube) return;
this.proofCube = lut;
const gl = this.gl;
if (!lut) {
if (this.proofTex) {
gl.deleteTexture(this.proofTex);
this.proofTex = null;
}
this.proofLutOn = 0;
return;
}
if (!this.proofTex) {
const tex = gl.createTexture();
if (!tex) return;
this.proofTex = tex;
}
gl.bindTexture(gl.TEXTURE_3D, this.proofTex);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_R, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
for (let guard = 0; guard < 8 && gl.getError() !== gl.NO_ERROR; guard++) {
/* drain, so the upload error below is ours */
}
gl.texImage3D(
gl.TEXTURE_3D,
0,
gl.RGBA16F,
lut.size,
lut.size,
lut.size,
0,
gl.RGBA,
gl.FLOAT,
lut.data,
);
if (gl.getError() !== gl.NO_ERROR) {
// Half-float 3D textures are core WebGL2; if this context refuses them,
// an 8-bit cube still beats silently doing nothing.
const bytes = new Uint8Array(lut.data.length);
for (let i = 0; i < lut.data.length; i++) {
bytes[i] = Math.round(Math.min(1, Math.max(0, lut.data[i])) * 255);
}
gl.texImage3D(
gl.TEXTURE_3D,
0,
gl.RGBA8,
lut.size,
lut.size,
lut.size,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
bytes,
);
}
this.proofLutOn = 1;
}
private makeTarget(w: number, h: number, float = this.floatTargets): Target {
@@ -1317,9 +1641,13 @@ export class Renderer {
const sig = maskSignature(layers, this.srcW, this.srcH);
if (sig !== this.maskSig) {
const packed = buildLocalMasks(layers, this.srcW, this.srcH);
gl.bindTexture(gl.TEXTURE_2D, this.maskTex);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, packed.w, packed.h, 0, gl.RGBA, gl.UNSIGNED_BYTE, packed.data);
const upload = (tex: WebGLTexture, data: Uint8Array) => {
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, packed.w, packed.h, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
};
upload(this.maskTex, packed.data);
upload(this.maskTex2, packed.data2);
this.maskSig = sig;
}
return layers.length;
@@ -1362,6 +1690,12 @@ export class Renderer {
// denoised texture, leaving u_den sampling a 1x1 zero texture -- black.
g.tex('u_den', this.denTex, 6);
g.f('u_denMix', this.denMix);
// A per-photo DCP profile replaces the body matrix, but only when the
// source really is camera-native. Applying one to an sRGB proxy would
// double-convert the pixels.
const srcCam = this.srcCam ? (edits.cameraProfile?.matrix ?? this.srcCam) : null;
g.f('u_srcMatrix', srcCam ? 1 : 0);
if (srcCam) g.m3('u_srcCam', srcCam);
g.v2('u_srcSize', this.srcW, this.srcH);
g.v2('u_frameSize', bounds.w, bounds.h);
g.v4('u_crop', crop.x, crop.y, crop.w, crop.h);
@@ -1373,8 +1707,8 @@ export class Renderer {
g.f('u_srcLod', Math.max(0, Math.min(12, srcLod)));
g.f('u_pick', -1);
g.v2('u_pickUv', 0, 0);
g.f('u_temp', edits.temp);
g.f('u_tint', edits.tint);
const wb = wbGainFor(edits.temp, edits.tint, edits.kelvin);
g.v3('u_wbGain', wb[0], wb[1], wb[2]);
g.f('u_exposure', edits.exposure);
g.f('u_recovery', edits.recovery);
g.f('u_contrast', edits.contrast);
@@ -1384,6 +1718,7 @@ export class Renderer {
g.f('u_blacks', edits.blacks);
g.f('u_vibrance', edits.vibrance);
g.f('u_saturation', edits.saturation);
g.f('u_redscale', edits.redscale ?? 0);
g.f('u_bw', edits.bw ? 1 : 0);
const bwFilter = bwFilterRgb(edits.bwFilter);
g.v3('u_bwFilter', bwFilter[0], bwFilter[1], bwFilter[2]);
@@ -1423,11 +1758,14 @@ export class Renderer {
g.f('u_lensSplit', this.lensSplit);
g.tex('u_masks', this.maskTex, 2);
g.tex('u_masks2', this.maskTex2, 7);
g.i('u_localCount', localCount);
for (let i = 0; i < localCount; i++) {
const layer = edits.local[i];
g.v4i('u_localAdj', i, layer.adjust.exposure, layer.adjust.contrast, layer.adjust.temp, layer.adjust.tint);
g.v4i('u_localAdj2', i, layer.adjust.saturation, layer.adjust.highlights, layer.adjust.shadows, 0);
const maskMode = layer.mode === 'subtract' ? 1 : layer.mode === 'intersect' ? 2 : 0;
g.v4i('u_localAdj2', i, layer.adjust.saturation, layer.adjust.highlights, layer.adjust.shadows, maskMode);
g.v4i('u_localAdj3', i, layer.adjust.whites, layer.adjust.blacks, layer.adjust.vibrance, layer.adjust.hue);
g.v4i('u_localRange', i, layer.range.lumaMin / 100, layer.range.lumaMax / 100, layer.range.hue, layer.range.hueRange);
g.v4i('u_localRange2', i, layer.range.satMin / 100, layer.range.enabled ? 1 : 0, 0, 0);
}
@@ -1511,6 +1849,9 @@ export class Renderer {
): Float32Array | null {
const gl = this.gl;
if (!this.srcBitmap) return null;
// Proofing is a session-level view setting, so every renderer (editor,
// compare view, export) picks up the loaded profile without extra plumbing.
this.setProofLut(getActiveProofCube());
if (opts.lens !== undefined) this.setLensCorrection(opts.lens);
this.lensSplit = opts.lensSplit ?? -1;
const w = Math.max(1, Math.round(opts.width));
@@ -1625,7 +1966,26 @@ export class Renderer {
this.finish.f('u_dehaze', edits.dehaze);
this.finish.f('u_sharpen', edits.sharpen.amount);
this.finish.f('u_sharpenMask', edits.sharpen.mask);
this.finish.f('u_sharpenDetail', edits.sharpen.detail);
this.finish.f('u_nrDetail', edits.noise.detail);
this.finish.f('u_detailScale', detailScale);
this.finish.tex('u_masks', this.maskTex, 3);
this.finish.tex('u_masks2', this.maskTex2, 4);
const innerLayers = (edits.local ?? []).slice(0, MAX_LOCAL_LAYERS);
this.finish.i('u_localCount', innerLayers.length);
for (let i = 0; i < innerLayers.length; i++) {
const layer = innerLayers[i];
this.finish.v4i(
'u_localDetail',
i,
layer.adjust.texture ?? 0,
layer.adjust.clarity ?? 0,
layer.adjust.dehaze ?? 0,
layer.adjust.sharpen ?? 0,
);
const mode = layer.mode === 'subtract' ? 1 : layer.mode === 'intersect' ? 2 : 0;
this.finish.v4i('u_localModes', i, mode, 0, 0, 0);
}
this.finish.f('u_lensSoft', edits.sharpen.lensSoftness);
this.finish.f('u_proofEnable', edits.proof.enabled ? 1 : 0);
const paper = edits.proof.paper === 'gloss'
@@ -1636,6 +1996,8 @@ export class Renderer {
this.finish.v3('u_proofPaper', paper[0], paper[1], paper[2]);
this.finish.f('u_proofBlack', edits.proof.blackPoint);
this.finish.f('u_gamut', edits.proof.gamut ? 1 : 0);
this.finish.f('u_proofLutOn', this.proofLutOn);
if (this.proofTex && this.proofLutOn > 0.5) this.finish.tex3d('u_proofLut', this.proofTex, 7);
this.finish.f('u_nr', edits.noise.luminance);
this.finish.f('u_chroma', edits.noise.chroma);
this.finish.f('u_chromaDetail', edits.noise.chromaDetail);
@@ -1729,10 +2091,12 @@ export class Renderer {
this.freeTarget(this.exportTarget ?? undefined);
gl.deleteTexture(this.srcTex);
gl.deleteTexture(this.maskTex);
gl.deleteTexture(this.maskTex2);
gl.deleteTexture(this.curveTex);
gl.deleteTexture(this.lensGeomTex);
gl.deleteTexture(this.lensTcaTex);
gl.deleteTexture(this.lensVigTex);
if (this.proofTex) gl.deleteTexture(this.proofTex);
gl.deleteBuffer(this.quad);
gl.deleteVertexArray(this.vao);
gl.deleteProgram(this.grade.program);
+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);
}
+499 -6
View File
@@ -1565,13 +1565,9 @@ figcaption {
box-shadow: inset 0 0 0 1px var(--accent), 0 0 0 1px var(--accent);
}
/* Additional photos in a multi-select, as opposed to the one on the canvas. */
/* Every frame in a multi-select gets the canvas photo's accent outline. */
.film.selected {
box-shadow: inset 0 0 0 2px #cfcfda;
}
.film.selected.active {
box-shadow: inset 0 0 0 2px var(--accent), 0 0 0 1px var(--accent);
box-shadow: inset 0 0 0 1px var(--accent), 0 0 0 1px var(--accent);
}
.film-rating {
@@ -1873,6 +1869,281 @@ figcaption {
color: var(--text);
}
/* preset browser: search, category pills and a bounded scrolling list keep a
catalogue of 150+ looks navigable inside the develop sidebar */
.preset-browser {
display: flex;
flex-direction: column;
min-height: 0;
}
.preset-toolbar {
display: flex;
align-items: stretch;
gap: 5px;
padding: 0 10px 7px;
}
.preset-search {
position: relative;
flex: 1 1 auto;
min-width: 0;
}
.preset-search input {
width: 100%;
padding: 5px 24px 5px 8px;
border: 1px solid var(--line);
border-radius: 6px;
background: var(--panel-2);
color: var(--text);
font-size: 11px;
}
.preset-search input:focus {
outline: none;
border-color: var(--accent-dim);
}
.preset-filter {
position: relative;
flex: 0 0 116px;
min-width: 0;
}
.preset-select {
display: flex;
align-items: center;
justify-content: space-between;
gap: 4px;
width: 100%;
height: 26px;
padding: 0 6px;
border: 1px solid var(--line);
border-radius: 6px;
background: var(--panel-2);
color: var(--muted);
font-size: 10px;
text-align: left;
cursor: pointer;
}
.preset-select:hover,
.preset-select[aria-expanded='true'],
.preset-select:focus-visible {
outline: none;
color: var(--text);
border-color: var(--accent-dim);
}
.preset-select-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.preset-select-chev {
flex: 0 0 auto;
font-size: 8px;
line-height: 1;
}
/* Opens over the preset grid instead of inside a native popup, so it stays put
while the tiles are still rendering. */
.preset-menu {
position: absolute;
top: calc(100% + 4px);
right: 0;
z-index: 60;
width: calc(var(--dev-left-w) - 20px);
max-height: min(300px, 40vh);
overflow-y: auto;
padding: 4px;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--panel-2);
box-shadow: 0 18px 44px rgba(0, 0, 0, 0.55);
}
.preset-menu-head {
padding: 6px 6px 3px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.preset-menu-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
width: 100%;
padding: 4px 6px;
border: 0;
border-radius: 4px;
background: none;
color: var(--text);
font-size: 11px;
text-align: left;
}
.preset-menu-item:hover {
background: rgba(255, 255, 255, 0.07);
}
.preset-menu-item.on {
color: var(--accent-dim);
}
.preset-menu-label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.preset-menu-count {
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.preset-search-clear {
position: absolute;
top: 50%;
right: 6px;
transform: translateY(-50%);
padding: 0 3px;
border: 0;
background: none;
color: var(--muted);
font-size: 14px;
line-height: 1;
}
.preset-search-clear:hover {
color: var(--text);
}
.preset-list {
max-height: min(46vh, 440px);
overflow-y: auto;
padding-bottom: 4px;
overscroll-behavior: contain;
}
.preset-group-head {
width: 100%;
margin: 2px 0 5px;
padding: 0;
display: flex;
align-items: center;
gap: 6px;
border: 0;
background: none;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.08em;
text-align: left;
text-transform: uppercase;
}
.preset-group-head:hover {
color: var(--text);
}
.preset-group-count {
font-size: 9px;
opacity: 0.55;
}
.preset-group-chev {
margin-left: auto;
font-size: 9px;
}
.preset-tile-wrap {
position: relative;
}
.preset-tile-wrap .preset-tile {
width: 100%;
}
.preset-star,
.preset-del {
position: absolute;
top: 2px;
display: grid;
place-items: center;
width: 18px;
height: 18px;
padding: 0;
border: 0;
border-radius: 4px;
background: rgba(0, 0, 0, 0.55);
color: #cccccc;
font-size: 11px;
line-height: 1;
opacity: 0;
transition: opacity 120ms ease;
}
.preset-tile-wrap:hover .preset-star,
.preset-tile-wrap:hover .preset-del,
.preset-star:focus-visible,
.preset-del:focus-visible,
.preset-star.on {
opacity: 1;
}
.preset-star {
right: 2px;
}
.preset-star.on {
color: #e8c45a;
}
.preset-del {
left: 2px;
font-size: 13px;
}
.preset-del:hover {
color: #ff8a8a;
}
.preset-empty {
padding: 18px 12px;
color: var(--muted);
font-size: 11px;
text-align: center;
}
.preset-detail {
display: flex;
flex-direction: column;
gap: 2px;
border-top: 1px solid var(--line);
padding: 6px 10px 8px;
color: var(--muted);
font-size: 10px;
}
.preset-detail strong {
color: var(--text);
font-size: 11px;
font-weight: 500;
}
.preset-detail-meta {
font-size: 9px;
letter-spacing: 0.04em;
opacity: 0.7;
text-transform: uppercase;
}
.variant-row {
display: flex;
flex-wrap: wrap;
@@ -2391,6 +2662,9 @@ figcaption {
.cloud-modal { width: 520px; }
.immich-modal { width: 640px; }
.raw-modal { width: 560px; }
.raw-modal .progress-bar { margin-bottom: 10px; }
.raw-modal .failures { margin-top: 12px; }
.immich-intro { margin: 0 0 14px; max-width: 60ch; }
.immich-progress {
bottom: 64px;
@@ -3230,6 +3504,23 @@ figcaption {
line-height: 1.55;
}
.proof-lock-form {
display: flex;
gap: 8px;
margin-top: 18px;
width: min(420px, 100%);
}
.proof-lock-form input {
flex: 1;
padding: 10px 12px;
border-radius: 6px;
border: 1px solid var(--line);
background: var(--panel-2);
color: var(--text);
font: inherit;
}
.proof-head {
position: sticky;
top: 0;
@@ -3742,6 +4033,208 @@ figcaption {
flex: 0 0 auto;
}
.tether-folder {
padding: 13px 15px;
margin-bottom: 12px;
border-radius: 6px;
background: var(--panel-2);
border: 1px solid var(--line);
}
.tether-folder code {
display: block;
margin: 6px 0;
padding: 8px 10px;
border-radius: 5px;
background: var(--panel);
border: 1px solid var(--line);
font-family: var(--mono, ui-monospace, SFMono-Regular, Menlo, monospace);
font-size: 12px;
overflow-wrap: anywhere;
}
.tether-folder p {
margin: 0;
line-height: 1.45;
}
.tether-actions {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 12px;
}
.tether-log {
list-style: none;
margin: 0;
padding: 0;
max-height: 240px;
overflow: auto;
font-size: 12px;
}
.tether-log li {
display: flex;
align-items: center;
gap: 10px;
padding: 5px 0;
border-top: 1px solid var(--line);
}
.tether-log li.fail .tether-name {
color: #e96a6a;
}
.tether-time {
color: var(--muted);
font-variant-numeric: tabular-nums;
}
.tether-name {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.cull-summary {
display: flex;
gap: 22px;
margin-bottom: 12px;
}
.cull-summary > div {
display: flex;
flex-direction: column;
}
.cull-summary strong {
font-size: 20px;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.cull-summary span {
color: var(--muted);
font-size: 11px;
}
.cull-threshold {
display: flex;
align-items: center;
gap: 10px;
margin: 0 0 10px;
font-size: 11px;
color: var(--muted);
}
.cull-threshold input {
flex: 1;
}
.cull-list {
list-style: none;
margin: 0;
padding: 0;
max-height: 300px;
overflow: auto;
}
.cull-list li {
display: flex;
align-items: center;
gap: 10px;
padding: 6px 0;
border-top: 1px solid var(--line);
font-size: 12px;
}
.cull-name {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.cull-grade {
width: 44px;
text-align: center;
border-radius: 999px;
padding: 1px 0;
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.cull-grade.soft {
background: rgba(233, 106, 106, 0.18);
color: #e96a6a;
}
.cull-grade.fair {
background: rgba(227, 179, 65, 0.16);
color: #e3b341;
}
.cull-grade.sharp {
background: rgba(93, 197, 138, 0.14);
color: #5dc58a;
}
.cull-score {
width: 26px;
text-align: right;
font-variant-numeric: tabular-nums;
color: var(--muted);
}
.share-settings {
margin: 0 0 18px;
padding: 13px 15px;
border-radius: 6px;
background: var(--panel-2);
border: 1px solid var(--line);
}
.share-settings-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 10px 12px;
margin: 10px 0;
}
.share-settings-grid label {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 11px;
color: var(--muted);
}
.share-settings-grid input {
width: 100%;
padding: 6px 8px;
border-radius: 5px;
border: 1px solid var(--line);
background: var(--panel);
color: var(--text);
font: inherit;
}
.share-settings-wide {
grid-column: 1 / -1;
}
.share-settings-actions {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.share-picks {
border: 1px solid var(--line);
border-radius: 6px;
+42
View File
@@ -68,6 +68,8 @@ export interface LocalLayer {
id: string;
name: string;
kind: LocalMaskKind;
/** How this mask combines with the layer above it in the list. */
mode: 'add' | 'subtract' | 'intersect';
inverted: boolean;
/** softness of the mask edge, 0–100 */
feather: number;
@@ -89,9 +91,19 @@ export interface LocalLayer {
contrast: number;
highlights: number;
shadows: number;
whites: number;
blacks: number;
temp: number;
tint: number;
saturation: number;
vibrance: number;
/** hue rotation in degrees, -180–180 */
hue: number;
/** detail and haze tools, applied after the global finish pass */
texture: number;
clarity: number;
dehaze: number;
sharpen: number;
};
}
@@ -127,8 +139,15 @@ export interface GeometryEdits {
}
export interface Edits {
/** relative warm/cool offset, used when `kelvin` is null */
temp: number;
tint: number;
/**
* Scene illuminant in Kelvin, or null to use the relative Temp offset. The
* gains are computed against a 5500 K daylight reference, which is also what
* the demosaiced proxy is assumed to be balanced for.
*/
kelvin: number | null;
exposure: number;
/** pulls clipped highlights back into range without shifting hue */
recovery: number;
@@ -142,12 +161,19 @@ export interface Edits {
dehaze: number;
vibrance: number;
saturation: number;
/**
* Redscale film response, 0–100: simulates colour film exposed through its
* base, where the red-sensitive layer is hit first and blue is absorbed.
*/
redscale: number;
bw: boolean;
/** colored filter simulated in black & white mode */
bwFilter: BwFilter;
/** how strongly that filter acts, 0–100 */
bwFilterAmount: number;
curve: Record<CurveChannel, CurvePoint[]>;
/** input black/white points and midtone gamma, applied before the curves */
levels: { black: number; white: number; gamma: number };
/** region tone shaping applied on top of the point curve */
parametric: { highlights: number; lights: number; darks: number; blacks: number };
hsl: { hue: number[]; sat: number[]; lum: number[] };
@@ -160,6 +186,11 @@ export interface Edits {
sharpen: { amount: number; radius: number; detail: number; mask: number; lensSoftness: number };
/** paper/output simulation for soft proofing */
proof: { enabled: boolean; paper: 'matte' | 'gloss' | 'newsprint'; blackPoint: number; gamut: boolean };
/**
* Camera profile override for a raw file, as the camera-to-sRGB matrix derived
* from a DCP's ColorMatrix. Null renders with the matrix the body supplied.
*/
cameraProfile: { name: string; matrix: number[] } | null;
/** chroma is the colour-noise amount; chromaDetail trades smoothing for fine colour */
noise: { luminance: number; detail: number; chroma: number; chromaDetail: number };
/**
@@ -268,6 +299,8 @@ export interface PhotoRecord {
previewUrl?: string;
/** server URL for the grid thumbnail */
thumbUrl?: string;
/** Bumped when the stored RAW is re-decoded, to invalidate cached previews. */
previewVersion?: number;
/** set when this photo was imported from an Immich album */
immich?: { albumId: string; assetId: string; checksum: string };
/** timestamp of the last rendered client proof published to the server */
@@ -326,7 +359,16 @@ export type SortKey = 'taken' | 'added' | 'name' | 'rating' | 'custom';
export interface Preset {
id: string;
name: string;
/** brand for film stocks, sub-collection for creative looks */
group: string;
/** top-level browser category, e.g. "Colour Negative" or "Portrait" */
category?: string;
/** one-line description of the look, shown in the preset browser */
description?: string;
/** free-text search terms */
tags?: string[];
/** present only on film emulations; drives the push/pull variants */
film?: { speed?: number; process?: string };
edits: Partial<Omit<Edits, 'crop'>>;
custom?: boolean;
}