32 Commits

Author SHA1 Message Date
bhursey fb43ca8e99 Make the mask tint a view toggle and mask local detail in source space
The mask overlay was always painted while the mask tool was open, at a fixed
strength; it is now a persisted view toggle (O or the Mask button) with its own
strength slider, so the photo underneath stays readable. The mask HUD also
gains + and - so a brush can erase and a shape can subtract without leaving the
canvas.

Local texture, clarity, dehaze and sharpen sampled the baked masks at the view
coordinate in the finish pass, so their coverage slid off the subject under a
crop or zoom. The grade pass now writes each pixel's source coordinate to a
second render target and the finish pass reads the masks through it, which also
follows straightening and lens correction.

The render gate checks the tint and a local dehaze amount through a quarter
frame crop and a synthetic lens warp, plus the tint strength and toggle.
2026-11-28 17:39:31 +00:00
bhursey 46dcc231a7 Show the baked local mask in the develop view instead of a drawn band.
The overlay redrew every stroke as a flat translucent band, so the feather
never appeared and the guide did not match the shape it stood for. The
develop view now tints the selected layer's baked mask, sampled with the
same source uv the adjustments use: the preview follows crops,
straightening, zoom, lens correction, subtract shapes and the feather
exactly as the mask stores it. Only the stroke still under the pointer is
drawn, as a preview of what will be baked, and the histogram is left
alone while a tint is showing.

The render gate now checks the overlay ranks its tint from the dab core
through the feathered rim to untouched pixels outside the brush circle.
2026-11-28 17:14:00 +00:00
bhursey c05dbce580 Keep the brush guide round and show the feather in it.
The local brush cursor took its height from the canvas aspect and its width
from the frame window, so a cropped or zoomed photo drew an oval cursor
over a round mask, and the stroke preview was scaled the same wrong way.
Both now convert the brush radius through the visible frame on each axis,
which matches the baked mask at any crop or zoom.

The feather band was also invisible in the guide: the preview painted one
flat band and the cursor was a single ring. Painted strokes now show the
soft band under the solid core, and the cursor adds an inner ring at
1 - feather of the radius.

Masks shrink their width instead of clamping their height, so tall or wide
frames keep square mask pixels and round dabs.
2026-11-28 17:09:02 +00:00
bhursey 69a327cd45 Draw brush masks with a soft dab inside the brush circle.
Feathering blurred a copy of the stroke and unioned it with the hard
stroke, so coverage stayed at full strength across the whole stroke and
then continued as a halo past the brush outline. The adjustment visibly
spilled outside the brush circle and its rim read as a step rather than a
falloff.

Each stroke is now stamped with a dab that is solid out to 1 - feather of
its radius and fades to nothing at the rim, so the mask follows the brush
circle and softens smoothly at any size. The render gate measures the
dab's core, its rim and the area just outside the circle.
2026-11-28 16:47:49 +00:00
bhursey 5c2903eeef Apply the lens vignetting gain in linear light.
Lensfun's vignetting coefficients describe linear transmission, so
multiplying them into the sRGB-encoded proxy brightened the corners far
more than the lens had lost and over-exposed the edges. The gain now runs
after the decode, in both the grade and the eyedropper.

Existing records that stored the old auto-enabled flag are cleared once,
on the server catalogue at boot and in the browser cache on its next
IndexedDB upgrade, and the Optics panel says when the correction is off.
2026-11-28 16:34:31 +00:00
bhursey be8cf3c88a Make lens-profile vignetting correction opt-in.
Applying a profile used to enable distortion, CA and vignetting together,
and the flat-field gain lifts the already tone-mapped corners above the
frame centre, over-exposing the edges. Vignetting now defaults off when a
profile is applied or restored from a camera default, and only turns on
when a profile explicitly stored vignetting: true.
2026-11-28 16:21:19 +00:00
bhursey b884616889 Group local mask shapes into editable components.
A local adjustment is now a list of shapes composited in order (add, subtract,
intersect) instead of a single shape, so dodging and burning can be built from
several brushes, gradients and auto masks without spending layer channels.
Existing edits migrate on load: the flat layer fields become components[0],
keeping geometry, invert, feather and the layer's blend mode unchanged. The
panel gains a shape list with active-shape editing, and the render gate now
asserts a subtract shape clears the group while an intersect keeps it.
2026-11-28 16:09:14 +00:00
bhursey acf582251f Give every mask its own tone curve.
Local masks could only shift tone globally, so a burnt sky or a backlit face had
to fight the frame-wide sliders. Each mask now carries an RGB point curve,
applied to the masked pixels before the mask blend. All eight curves ride in one
256×8 LUT texture, so the grade shader needs a single extra sampler rather than
eight. Masks saved before this exist migrate to an identity curve, so old edits
keep their look; the render check fails if the curve stops reaching the grade,
and a unit test pins the LUT's identity, per-row isolation and monotonicity.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 15:42:24 +00:00
bhursey 00e6fee9bd Pin the mask cases a model benchmark exposed.
A cluster-based rewrite of the model-free estimator was measured against u2netp
on seven real 60D frames and came out worse than the border-histogram version
(0.214 vs 0.305 mean IoU against the model, best blend weight 0.298), so it was
not shipped. The two cases that mattered are now regression tests: a saturated
object running off the frame must stay out of the subject, and a dark scene with
no clear subject must not be swallowed.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 15:36:53 +00:00
bhursey 24deb8e69b Deploy through the predeploy gate instead of by hand.
`npm run deploy` now runs the gate (typecheck, unit suite, render check) before
anything is copied, then rsyncs the source, rebuilds and restarts the service on
the target from LUMINARY_DEPLOY_* variables, and fails if the server is not
serving the same bundle hashes as the reviewed local build. npm runs a script
named predeploy before deploy on its own, so the gate runs once; invoked as
`node scripts/deploy.mjs` the script gates itself. Both scripts exit through
process.exitCode, because process.exit() truncated the failure messages when
they were piped.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 15:20:18 +00:00
bhursey 4b17ca00db Skip the pre-deploy build when only test files changed.
predeploy was a shell chain that always rebuilt, so a test-only edit paid for a
full Vite build. It is now scripts/predeploy.mjs: typecheck, tests and the render
check always run, and the build is skipped when a content hash of the bundle
inputs (src and public minus test files, plus the Vite/TS/package config) matches
the last successful build. The signature lives in node_modules/.cache, so it is
gitignored and never rsynced to the server.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 15:02:00 +00:00
bhursey 6e80699829 Show the shadow palette in the clipping legend and pin both overlay checks.
The shadow warning gained per-channel colours but the legend only explained the
highlight palette, so the new marks had no key. The legend now switches to the
shadow palette whenever shadow clipping is on, listing one channel, the three
two-channel colours and all three. The render check also fails if the shadow
overlay stops following Exposure, the way the highlight side already did.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 14:58:03 +00:00
bhursey a67e9ef458 Name the channels in the shadow clipping warning too.
Shadow warnings were a flat blue, so a single crushed channel looked the same as
all three. The shadow branch now uses the highlight palette: red/green/blue for
one channel, yellow (red+green), magenta (red+blue) and cyan (green+blue) for
pairs, white for all three. The render check covers both ends of the range, and
`npm run predeploy` chains typecheck, tests, the render check and the build so a
shader regression cannot reach a deploy.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 14:40:50 +00:00
bhursey a6491f6ef6 Show the clipping overlay's per-channel colours and follow the sliders.
The overlay had been collapsed to a single highlight bit, so every warning was
white. It now reads the finished frame per channel again: red for one clipped
channel, yellow for two, white for all three, and it updates as Exposure or
Recovery moves, which is what holding Ctrl is for. The render check renders the
overlay and asserts both the colours and that +6 EV turns a clear band white.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 14:38:48 +00:00
bhursey fe9d2aff3f Name the clipped channels in the Ctrl clipping overlay again.
0c113e7 packed clipping into two alpha states (shadow / highlight), so the finish
pass could only paint white even though the legend still promised red, green,
blue and yellow. The grade pass now writes a 4-bit code (R/G/B + shadow) into
alpha and the overlay paints the channels it actually lost: red for one, yellow
for two, white for all three. The render check renders the overlay so this
cannot regress silently.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 14:35:30 +00:00
bhursey 1e7ec0cf15 Add a headless render check for the 16-bit sidecar swap.
The proxy and sidecar reach the GPU through different upload paths, and whether
they agree depends on UNPACK_FLIP_Y_WEBGL being ignored for ImageBitmap. A unit
test cannot see that, so the picture could silently start flipping again. The
check encodes a two-tone sidecar with the server's encoder, serves it beside the
matching JPEG and measures the rows that land in a WebGL2 texture in headless
Chrome.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 14:30:36 +00:00
bhursey c10ff97670 Upload the 16-bit sidecar unflipped so it matches the JPEG proxy.
Chrome ignores UNPACK_FLIP_Y_WEBGL for ImageBitmap uploads, so the JPEG proxy
lands in the texture top-down while the parser pre-flipped the sidecar rows.
The picture jumped upside down a few seconds after load, when the sidecar
replaced the proxy. The parser now keeps the PNG's row order.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 06:59:55 +00:00
bhursey 2dc569256c Give Auto tone and Auto WB the raw's thumbnail URL.
Raw records keep their pixels in `thumbUrl` and leave `thumb` empty, so the
analysis was handed an empty string, failed to decode, and returned neutral
values — which made Auto WB look identical to As shot.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 06:45:37 +00:00
bhursey c7b01b31cb Resume the preview rebuild where a restart left it.
The job only lived in memory, so every deploy discarded hours of proxy work and
the next run started at the first photo. Mirror progress to the storage root
after each photo and pick the pending ids back up on boot.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 06:45:37 +00:00
bhursey 32616d5404 Report a failed GPU draw instead of painting black.
A rejected draw leaves the canvas untouched, so a broken frame looked like a
black photo with nothing to explain it. Poll the error queue once per frame and
raise an error the editor can show.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 06:45:37 +00:00
bhursey 7e53bb5059 Keep the proof cube off the graded image's texture unit.
The finish shader gained a sampler3D for ICC soft proofing, but that sampler was
only assigned when proofing was on; unset it defaulted to unit 0, where the
graded image is bound, and WebGL rejects a draw whose samplers mix types on one
unit. Every frame then failed and photo after photo showed a black canvas with
no console error. Assign the proof sampler on every draw and bind a 1x1x1
placeholder while proofing is off.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 06:40:25 +00:00
bhursey 158dccddf1 Add an admin action that rebuilds preview proxies
A library imported by an older pipeline keeps whatever proxy it was given, and
the editor can only show those bytes. The Storage tab now re-decodes every
camera raw from its original, writing a fresh JPEG proxy, thumbnail, 16-bit
sidecar and denoise prune, then stamps previewVersion so browsers refetch.

The decode loop runs one photo at a time on the server behind a status route:
an hour of LibRaw work would time out as a request, and parallel decodes would
starve the editor. The single-photo reprocess route shares the same helper.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 06:20:44 +00:00
bhursey 2bec4102a2 Recover when a cached proxy will not decode
The editor decodes the copy of the proxy kept in IndexedDB before asking the
server, so one stale or truncated copy fails with Chrome's "The source image
could not be decoded." on every later visit. A failed decode now drops that
copy, refetches the current bytes and retries, and the orientation option falls
back to a plain decode if the decoder refuses it.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 06:09:57 +00:00
bhursey ecb3d5de7c Use the Luminary mark in the top-bar wordmark
The glowing dot beside "Luminary" is replaced by the brand mark, trimmed to
its bars and resized for the 20px header slot so the 1 MB master art is not
shipped to browsers.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 05:53:13 +00:00
bhursey 9051b9cfc1 Cover the server 16-bit imaging helpers with tests
🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 05:49:47 +00:00
bhursey d4cce4e001 Apply a camera profile to every raw from the same camera body
A DCP matrix describes the sensor, so a profile chosen for one frame belongs to
all camera-native raws from that body; the panel offers the bulk apply when the
library holds more photos than the one on screen.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 05:49:47 +00:00
bhursey 749047ae9e Match EXIF lens names by brand and share team calibrations
EXIF folds the brand into the focal range ("EF75-300mm"), so split letters
from digits before scoring, keep the score a pure name score that a caller can
trust, and rank a same-mount-family lens higher without filtering. Auto-match
now declines below 0.75 rather than applying the best of a bad list.

Lenses the bundled database lacks can be measured in-house: /api/lens-profiles
stores calibrations in SQLite, the Optics panel edits them and marks them
"Team", and search treats them as ordinary entries.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 05:49:47 +00:00
bhursey 16456c3c69 Replace the Lensfun WebAssembly runtime with our own lens engine.
The wrapper's wasm, its 5 MB data blob and the runtime chunk were fragile to
serve (CSP, MIME, cache) and pulled an LGPL runtime into the bundle just for
calibration data. The Lensfun XML is now converted at build time into
public/lens-db/profiles.json, and search, matching and the correction maths live
in src/lib/lensDb.ts and src/lib/lensEngine.ts. Maps are pinned against output
captured from the previous implementation, so results are unchanged.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 05:17:02 +00:00
bhursey 637629385a Show camera profiles in every view and remember proof and DCP settings.
A profile chosen for a raw only changed Develop and exports, so the grid,
Compare and preset previews could disagree with the file. They now grade
camera-native samples, while the proof profile persists with a rendering
intent and DCP matrices can be reused per camera body.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-28 04:04:44 +00:00
bhursey 0c113e7a91 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>
2026-11-28 03:59:55 +00:00
bhursey 6dfddffc14 Show edited renders in thumbnails and paste to a filmstrip selection
The grid and filmstrip only ever showed the import thumbnail, so edits and
virtual copies looked untouched. Edited tiles now render client-side with the
same shader as the canvas, once each, from the small cached thumbnail. The
filmstrip also gains Cmd/Shift multi-select so Paste, Copy and Reset can act on
several photos from the toolbar or the right-click menu.
2026-11-25 20:37:51 +00:00
bhursey 0b3ab76405 Add the optional Immich integration and manual gallery push
Immich connections stay server-side with an encrypted API key, albums can be
imported, and photos are only sent back when an event's push button is pressed:
originals upload once, edited photos re-render, and edits hashes plus checksums
skip anything already in Immich. This also lands the accompanying editor, cloud
and administration work that was still uncommitted.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-25 17:43:05 +00:00
106 changed files with 20289 additions and 67433 deletions
+318 -60
View File
@@ -62,16 +62,22 @@ changing the current filters.
**Develop.** A WebGL2 multi-pass pipeline (`src/gl/renderer.ts`), per photo, **Develop.** A WebGL2 multi-pass pipeline (`src/gl/renderer.ts`), per photo,
non-destructive: non-destructive:
- white balance, exposure, contrast, highlights/shadows/whites/blacks - white balance as a relative Temp/Tint offset or an absolute Kelvin value with a
- texture, clarity, dehaze, vibrance, saturation, black & white mix 5500 K daylight reference, exposure, contrast, and hue-preserving
- RGB and per-channel tone curves highlights/shadows/whites/blacks
- 8-band HSL colour mixer, split toning / colour grading - 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 - sharpening, luminance noise reduction
- vignette, grain - vignette, grain
- crop with nine aspect ratios, straighten, 90° rotation, flips - crop with nine aspect ratios, straighten, 90° rotation, flips
- local adjustments (up to four layers): brush, linear gradient and radial masks with - local adjustments (up to eight layers): brush, linear gradient and radial masks
feather, invert, luminance/hue/saturation ranges, and per-layer exposure, contrast, with feather, invert, luminance/hue/saturation ranges, and per-layer exposure,
highlights, shadows, temperature, tint and saturation. Masks follow crops, zoom, 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 healing and lens correction; Copy mask / Paste mask move one layer between photos
- full Lensfun profiles: distortion, transverse chromatic aberration and vignetting - full Lensfun profiles: distortion, transverse chromatic aberration and vignetting
from the official database, with manual lens search, "Match EXIF lens" 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 - histogram, built-in and saved presets, history with undo/redo, selective
copy/paste and batch sync, named snapshots, virtual copies, before/after (**\**) copy/paste and batch sync, named snapshots, virtual copies, before/after (**\**)
- on-device auto subject, sky and background masks (no model download), an - 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 ISO/camera-aware noise starting point, edge-aware lens-softness compensation, and soft
approximate paper soft-proof preview 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 - HDR merge with alignment, horizontal panorama stitching and focus stacking; each
result is added to the catalog as a new editable photo result is added to the catalog as a new editable photo
- browser print layouts (A4, Letter, 5×7) rendered through the develop pipeline - 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 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 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 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 **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 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 cancel a scheduled cleanup. Cleanups stop at a target percentage of the quota instead
of deleting the whole original plan. 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 **Catalog workflow.** Editable title, caption, creator, copyright and keyword chips
with a keyword library and reusable metadata presets. Save the current filters and sort 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 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 **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 long edge or percent; filename template (`{name}`, `{date}`, `{time}`, `{index}`); saved
export recipes; output sharpening; watermark; XMP metadata embedded in JPEGs; an export recipes; output sharpening; watermark; XMP metadata embedded in JPEGs; sRGB,
embedded sRGB ICC profile; batch export as one ZIP or separate files. Full-resolution Display P3 or Adobe RGB output with a matching generated ICC profile (JPEG/TIFF); batch
export runs through the same renderer as the screen preview. 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, **Administration.** Users, roles, invites, catalog backup/restore, per-account quotas,
email settings and a storage relocation tool are all in one panel. email settings and a storage relocation tool are all in one panel.
@@ -199,9 +224,12 @@ storage, while quotas are stored per account in the database.
| `PORT` | `8787` | HTTP port (**not** prefixed with `LUMINARY_`) | | `PORT` | `8787` | HTTP port (**not** prefixed with `LUMINARY_`) |
| `HOST` | `0.0.0.0` | Bind address (**not** prefixed) | | `HOST` | `0.0.0.0` | Bind address (**not** prefixed) |
| `LUMINARY_DATA` | `server/data` | Where the database and image folders live | | `LUMINARY_DATA` | `server/data` | Where the database and image folders live |
| `LUMINARY_SECRET_KEY` | *(auto)* | Key for encrypting the saved SMTP password and bridge service tokens; when empty, a generated key is kept in `<data>/secret.key` — back it up with the database |
| `LUMINARY_TRUST_PROXY` | *(empty)* | Set to `1` only behind a proxy that overwrites `X-Forwarded-For`; makes login limits and `Secure` cookie detection use the real client address |
| `LUMINARY_INVITE` | *(empty)* | Shared registration code for teammates; personal invite links work without it | | `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_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_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_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_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) | | `LUMINARY_DENOISE_WORKERS` | `min(4, cores−1)` | Concurrent detail-denoise jobs (read directly from the environment) |
@@ -230,6 +258,15 @@ directly and have no legacy alias.
per-user salt and a 64-byte derived key. per-user salt and a 64-byte derived key.
- The session cookie is named `lumen_session` and is `HttpOnly; SameSite=Lax`. It is - The session cookie is named `lumen_session` and is `HttpOnly; SameSite=Lax`. It is
marked `Secure` only when the request arrives with `X-Forwarded-Proto: https`. marked `Secure` only when the request arrives with `X-Forwarded-Proto: https`.
- Responses carry `X-Content-Type-Options: nosniff` and a self-only CSP, and stored
photo MIME types are limited to raster images. A member cannot make a gallery link
serve HTML or SVG, even by uploading a file with that content.
- Sign-in is throttled per account and address (8 failures per account per 15 minutes;
50 per client address, or 500 when a proxy's address is shared). Set
`LUMINARY_TRUST_PROXY=1` behind a proxy so `X-Forwarded-For` identifies the caller.
Gallery writes are limited to 120 per minute per link.
- Uploads are streamed to disk and charged to the uploader's quota before their catalog
row exists, so an interrupted import cannot leave unbilled files behind.
- There is no TLS in the server. Terminate HTTPS at a reverse proxy. - There is no TLS in the server. Terminate HTTPS at a reverse proxy.
- The SQLite file, the IndexedDB database and the Compose volume all keep the - The SQLite file, the IndexedDB database and the Compose volume all keep the
`lumenroom` name so older deployments upgrade in place. `lumenroom` name so older deployments upgrade in place.
@@ -244,6 +281,22 @@ npm run build # type-checks and bundles dist/
npm start # serves dist/ and /api from one Node process npm start # serves dist/ and /api from one Node process
``` ```
To push a running install over ssh, `npm run deploy` runs the whole predeploy gate
first — a type error, a failing test or a clipping-overlay regression stops it before
anything is copied — then rsyncs the source, rebuilds, restarts the service and checks
that the server is serving the same bundle hashes. npm runs the `predeploy` script
before `deploy` on its own, so the gate runs exactly once; calling `node
scripts/deploy.mjs` directly runs the gate itself:
```bash
LUMINARY_DEPLOY_HOST=bhursey@photos.example.org \
LUMINARY_DEPLOY_SUDO_PASS=… npm run deploy
```
`LUMINARY_DEPLOY_PATH` (default `/srv/luminary`), `LUMINARY_DEPLOY_SERVICE` (default
`luminary`) and `LUMINARY_DEPLOY_SSH_PASS` cover a different layout; without the
password variables it uses your ssh key and passwordless sudo.
The server serves the built UI with an SPA fallback (unknown non-API paths return The server serves the built UI with an SPA fallback (unknown non-API paths return
`index.html`), caches `/assets/*` for a year as immutable, and returns `503` with a `index.html`), caches `/assets/*` for a year as immutable, and returns `503` with a
build hint if `dist/index.html` is missing. JSON responses are `no-store`; image bytes build hint if `dist/index.html` is missing. JSON responses are `no-store`; image bytes
@@ -299,7 +352,9 @@ Two independent things to back up:
1. **The catalog plus originals** — copy the whole data directory (or the Docker 1. **The catalog plus originals** — copy the whole data directory (or the Docker
volume). Stop the server, or accept that SQLite is in WAL mode and copy volume). Stop the server, or accept that SQLite is in WAL mode and copy
`lumenroom.db`, `lumenroom.db-wal` and `lumenroom.db-shm` together. `lumenroom.db`, `lumenroom.db-wal` and `lumenroom.db-shm` together. Keep
`secret.key` with it (unless `LUMINARY_SECRET_KEY` is set): without it the saved
SMTP password and bridge tokens cannot be decrypted.
2. **A logical catalog export** — an admin can download a JSON backup (events, photo 2. **A logical catalog export** — an admin can download a JSON backup (events, photo
records, presets and key/value settings) from the admin panel, or via records, presets and key/value settings) from the admin panel, or via
`GET /api/admin/catalog`, and restore it with `POST /api/admin/catalog`. This does `GET /api/admin/catalog`, and restore it with `POST /api/admin/catalog`. This does
@@ -414,9 +469,14 @@ Data directory
| `src/lib/import.ts` | File ingest, EXIF read, preview/thumb creation, upload scheduling | | `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/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/tiff.ts`, `icc.ts` | Dependency-free 16-bit TIFF writer and sRGB profile |
| `src/lib/lensfun.ts`, `lensNames.ts`, `lensDefaults.ts` | Lensfun client, EXIF matching, saved defaults | | `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/lensDb.ts`, `lensEngine.ts`, `lensNames.ts`, `lensDefaults.ts` | Lens database, correction maps, EXIF matching, saved defaults |
| `src/lib/merge.ts` | HDR / panorama / focus-stack composition | | `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/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 | | `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 | | `docs/user-guide/` | Source of the in-app user guide (`guide.html`), also shipped as PDF |
@@ -439,7 +499,7 @@ SQLite is created and migrated at boot. All statements are prepared once in `db.
| `gallery_comments` | per-token client comments with author name and timestamp | | `gallery_comments` | per-token client comments with author name and timestamp |
| `gallery_reviews` | per-token, per-photo, per-client approved / changes status | | `gallery_reviews` | per-token, per-photo, per-client approved / changes status |
| `invites` | token, optional email lock, role, expiry, acceptance and revocation | | `invites` | token, optional email lock, role, expiry, acceptance and revocation |
| `bridge_events` | imported event id, dashboard session, encrypted-at-rest token, TTL | | `bridge_events` | imported event id, dashboard session, AES-GCM-sealed service token, TTL |
| `user_quota` | limit, scheduled prune time/plan, last warning timestamps | | `user_quota` | limit, scheduled prune time/plan, last warning timestamps |
Photo and event records are JSON documents with a few extracted columns for ordering, Photo and event records are JSON documents with a few extracted columns for ordering,
@@ -497,7 +557,17 @@ 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/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 | | 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/presets` | session | Replace the stored preset library |
| GET | `/api/lens-profiles` | session | Team-measured lens calibrations, shared by every member |
| POST | `/api/lens-profiles` | session | Add a calibration; coefficient ranges and sample shapes are validated |
| PUT | `/api/lens-profiles/:id` | author or admin | Replace a calibration |
| DELETE | `/api/lens-profiles/:id` | author or admin | Remove a calibration |
| PUT | `/api/events/:id` | owner | Upsert an event record | | PUT | `/api/events/:id` | owner | Upsert an event record |
| DELETE | `/api/events/:id` | owner | Delete an event (photos are handled separately) | | DELETE | `/api/events/:id` | owner | Delete an event (photos are handled separately) |
| PUT | `/api/photos/:id` | owner | Upsert a photo record; accepts a data-URL thumbnail, which is written to `thumbs/` | | PUT | `/api/photos/:id` | owner | Upsert a photo record; accepts a data-URL thumbnail, which is written to `thumbs/` |
@@ -524,7 +594,7 @@ routes are public and are gated only by the share token.
| GET | `/api/galleries/:token/photos/:id/thumb` | public | Gallery thumbnail | | GET | `/api/galleries/:token/photos/:id/thumb` | public | Gallery thumbnail |
| GET | `/api/galleries/:token/photos/:id/preview` | public | Gallery preview | | GET | `/api/galleries/:token/photos/:id/preview` | public | Gallery preview |
| GET | `/api/galleries/:token/photos/:id/download` | public | Download one proof | | GET | `/api/galleries/:token/photos/:id/download` | public | Download one proof |
| GET | `/api/galleries/:token/download-all?client=` | public | ZIP of the event's proofs, generated in-stream | | GET | `/api/galleries/:token/download-all?client=` | public | ZIP of the event's proofs; at most 400 files / 512 MB, one archive at a time |
| POST | `/api/galleries/:token/picks` | public | Add or remove a client favourite | | POST | `/api/galleries/:token/picks` | public | Add or remove a client favourite |
| POST | `/api/galleries/:token/comments` | public | Append a client comment | | POST | `/api/galleries/:token/comments` | public | Append a client comment |
| POST | `/api/galleries/:token/reviews` | public | Set approved / changes / none | | POST | `/api/galleries/:token/reviews` | public | Set approved / changes / none |
@@ -545,6 +615,8 @@ routes are public and are gated only by the share token.
| POST | `/api/admin/catalog` | Restore a backup produced by the GET | | POST | `/api/admin/catalog` | Restore a backup produced by the GET |
| GET | `/api/admin/storage` | Current and default storage roots, custom flag | | GET | `/api/admin/storage` | Current and default storage roots, custom flag |
| PUT | `/api/admin/storage` | Move image storage to another absolute path | | PUT | `/api/admin/storage` | Move image storage to another absolute path |
| GET | `/api/admin/previews/rebuild` | Progress of the raw proxy rebuild |
| POST | `/api/admin/previews/rebuild` | Re-decode every camera raw into a fresh proxy, thumbnail and 16-bit sidecar |
| PATCH | `/api/admin/quotas/:id` | Set an account's byte limit | | PATCH | `/api/admin/quotas/:id` | Set an account's byte limit |
| POST | `/api/admin/quotas/:id/prune` | Compute the oldest-first plan and schedule it 24 h out | | POST | `/api/admin/quotas/:id/prune` | Compute the oldest-first plan and schedule it 24 h out |
| DELETE | `/api/admin/quotas/:id/prune` | Cancel a scheduled cleanup | | DELETE | `/api/admin/quotas/:id/prune` | Cancel a scheduled cleanup |
@@ -665,14 +737,130 @@ Empty `GLENLOCH_URL` or `BRIDGE_SECRET` disables the bridge entirely.
--- ---
## Immich album sync
Immich support is optional. An administrator can configure one server-wide connection, and
nothing appears in the app for accounts until that connection is enabled. Per-account
connections are still supported as a fallback when no shared connection exists.
Open **Administration → Immich** as an administrator:
1. Enter your Immich server address and an API key from Account Settings → API Keys.
The key is sealed with AES-256-GCM, stays on the server, and is never returned by the
API — the browser only ever sees `hasKey`. Back up `LUMINARY_SECRET_KEY` (or the
generated `<data>/secret.key`) with the database.
2. Leave **Automatically publish event photos and edits** on and **Test connection**.
3. Users can then **Refresh albums** in the per-account Immich panel and import one.
Imports run as a background job with progress.
Required key permissions: `album.read`, `album.create`, `albumAsset.create`, `asset.read`,
`asset.download`, `asset.upload` and `asset.update`. Add `tag.read`, `tag.create` and
`tag.asset` for keyword sync. Add `asset.delete` only if you intend to move originals to
the Immich trash after an edit is uploaded.
### Pull
- Streams each image to disk; raws use the normal LibRaw pipeline, so the editable proxy
matches an upload exactly.
- One Luminary event per album, reused on every sync. Every source asset is recorded in
`immich_assets`, so a re-import adds only missing photos and never duplicates one.
- Capture date and basic EXIF (camera, lens, ISO, aperture, shutter, focal length) are
carried across. Ratings, flags, edits and keywords stay Luminary-side.
- Formats the browser cannot display (for example HEIC) keep their original bytes and get
a server-rendered JPEG proxy.
- Uses the account storage quota; a full quota stops the job with a message.
### Event galleries
When importing into an event, Luminary creates a matching Immich album by default, links
it to the event, and makes that album the destination for originals and edits. The checkbox
in the import dialog can turn this off for one import. Unlike an imported album, a gallery
is never re-imported and is skipped by scheduled sync, so the versions uploaded from
Luminary do not come back as new photos.
Every successful import into an event with a gallery is added automatically: the server
uploads each original (converting non-JPEG and raw files to JPEG) and the existing checksum
record prevents a retry from uploading the same file twice. Import failures are reported per
photo and do not stop the rest of the set.
### Push back
Edits are saved automatically after you stop adjusting a photo: Luminary waits briefly,
renders the current edit at full resolution as a JPEG, uploads it to the event's Immich album,
and uses the checksum record to skip an unchanged render. You can still use **Send edit to
Immich** from the context menu to send immediately. Luminary:
1. Uploads it as a **new** Immich asset — current Immich removed in-place replacement, so
the original is never overwritten.
2. Copies album, stack, favourite and sidecar associations from the source asset using the
version-appropriate copy endpoint, then adds the new asset to the same album explicitly
as a fallback. Photos without an Immich original go straight into their event's gallery.
3. Optionally moves the original to the Immich trash (`force: false`, recoverable, never
a permanent delete). This is off by default and needs `asset.delete`.
4. Records the checksum in `immich_pushes`, so sending the same render twice returns the
existing asset instead of uploading a duplicate.
The action only appears for accounts that enabled the integration, on photos with an
Immich source or an event gallery. Select several photos and use **Send to Immich** in the selection
bar, or the right-click action, to send a queue: each edit is rendered and uploaded in
turn, with a progress card, per-photo failure isolation and checksum skipping for edits
that are already there. **Open in Immich** jumps straight to the source asset.
### Metadata
With **Keep ratings, flags and keywords in sync** enabled (the default), Luminary and
Immich stay aligned:
- Luminary stars map to Immich's 1–5 rating; no stars map to unrated.
- A rejected flag maps to Immich's −1 rating; a pick maps to the favourite flag.
- Keywords map to Immich tags; removing a keyword removes that tag from the imported
asset and any edits pushed from it.
Edits made in Luminary are debounced and sent to Immich for the imported original and
every edit asset pushed from it. Album sync also reconciles in the other direction: a
rating, favourite or tag changed in Immich is written back to Luminary. Each photo keeps
a local/remote fingerprint snapshot in `immich_meta`, so only genuinely changed sides are
acted on; if both changed, the Luminary value wins. Metadata sync needs `asset.update`
and the tag permissions above, and can be turned off per account.
### Scheduled sync
Each account can enable **Keep linked albums in sync automatically** and choose 15 minutes
to once a day. The worker only touches imported albums that account already linked; it
never imports a new album on its own and never re-imports an event gallery. A sync respects the per-album interval, one job per account, and the
storage quota. Manual and automatic syncs share the same job path, so re-imports remain
idempotent. Last run time and the last error are shown in the panel.
Version differences are handled at runtime: the client reads `/api/server/version`, asks
for album assets inline first, retries with `withoutAssets=false`, and falls back to
`/api/search/metadata` on builds that paginate album contents.
---
## Raw pipeline ## Raw pipeline
The browser cannot demosaic camera raw, so the server does it during upload: 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. 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 2. LibRaw (`libraw-wasm`) opens it in a pooled worker with camera white balance and the
output and the container's orientation, then `sharp` encodes an editable JPEG proxy container's orientation and returns the frame **before** any output colourspace
at `LUMINARY_RAW_EDGE` (6000 px by default). (`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. The grid and Compare read the same samples: on first
request the server writes a camera-native tile the size of the JPEG thumbnail at
`previews/<id>.t16.png`, and Compare loads the full sidecar, so a loaded DCP profile
shows in every view of the photo. Preset previews do the same.
3. If LibRaw cannot open the file, the largest JPEG embedded in the container is 3. If LibRaw cannot open the file, the largest JPEG embedded in the container is
extracted and normalised instead. The grid marks such photos `RAW` and the Info panel extracted and normalised instead. The grid marks such photos `RAW` and the Info panel
reports which engine produced the proxy, so exotic or very new cameras still import. reports which engine produced the proxy, so exotic or very new cameras still import.
@@ -683,6 +871,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 FFF, IIQ, X3F, ERF, K25/KDC, DCR, MOS, MRW, MEF, SRAW. Content sniffing checks the
container signature before wasting a decode attempt. 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 **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 `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 time. Each instance owns one worker thread; extra jobs queue. Idle instances are
@@ -730,28 +929,35 @@ licensed implementation.
## Lens profiles ## Lens profiles
Lens correction uses the [Lensfun](https://lensfun.github.io/) camera and lens database Lens correction uses the calibration data of the
through the [`@neoanaloglabkk/lensfun-wasm`](https://github.com/lexluthor0304/LensfunWasm) [Lensfun](https://lensfun.github.io/) camera and lens database, converted at build time
build. Runtime assets are served from `public/lensfun/`. into the compact profile file the editor ships. The correction maths is Luminary's own
(`src/lib/lensEngine.ts`): PanoTools, poly3 and poly5 distortion, poly3 TCA and `pa`
vignetting, evaluated in the same normalised coordinates Lensfun used. No WebAssembly
runtime, no XML parser and no `blob:` or eval allowance is involved, and a unit test
pins the output against maps captured from the previous implementation.
- **Database** — © Lensfun contributors, licensed - **Database** — © Lensfun contributors, licensed
[CC BY-SA 3.0 Unported](https://creativecommons.org/licenses/by-sa/3.0/), taken from [CC BY-SA 3.0 Unported](https://creativecommons.org/licenses/by-sa/3.0/), taken from
Lensfun `data/db` at commit Lensfun `data/db` at commit
[`655a9c4`](https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data). [`655a9c4`](https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data)
It is redistributed as bundled by the wrapper build; Luminary adds no profiles of its and converted by `scripts/build-lens-db.mjs` into `public/lens-db/profiles.json`.
own. Luminary adds no profiles of its own.
- **Library** — Lensfun is LGPL-3.0 (the bundled notice states "or later"), compiled to - **Engine** — `src/lib/lensDb.ts` (loading, matching, camera lookup) and
WebAssembly. Corresponding source is the upstream repository at the pinned commit plus `src/lib/lensEngine.ts` (maps, auto-scale), both MIT like the rest of the app code.
the wrapper's build scripts. - **Team calibrations** — lenses the database lacks can be measured in-house and added
- **Bundled files** — `public/lensfun/LICENSE` is the **MIT licence of the WASM from the Optics panel (“Team calibrations”). They are stored in the server's SQLite
wrapper**, not of the database or the library. `NOTICE.md`, database (`lens_profiles`), searched next to the bundled profiles with the same sample
`THIRD_PARTY_LICENSES.md` and `UPSTREAM.md` record the other components and the pin. layout, and are Luminary's own data rather than Lensfun content.
- **Bundled files** — `public/lens-db/NOTICE.md` records the attribution and the pin;
`public/lens-db/profiles.json` carries the same provenance in its `source` field.
See [Third-party attribution and licences](#third-party-attribution-and-licences) before See [Third-party attribution and licences](#third-party-attribution-and-licences) before
redistributing the app or its container image. redistributing the app or its container image.
Profiles load lazily the first time the Optics panel needs one, so a library that never Profiles load lazily the first time the Optics panel needs one, so a library that never
uses lens correction does not download the ~5 MB database. A profile is built for the uses lens correction does not download the ~1.8 MB database. Team calibrations are a
small extra request and are ignored when offline or signed out. A profile is built for the
photo's current focal length and aperture; it is not interpolated between zoom photo's current focal length and aperture; it is not interpolated between zoom
positions. Camera-lens defaults require both a normalised camera and lens name to match. positions. Camera-lens defaults require both a normalised camera and lens name to match.
@@ -766,6 +972,9 @@ positions. Camera-lens defaults require both a normalised camera and lens name t
| `npm run dev` | Vite HMR on 5173 | | `npm run dev` | Vite HMR on 5173 |
| `npm run typecheck` | `tsc --noEmit` | | `npm run typecheck` | `tsc --noEmit` |
| `npm test` | Vitest, one pass then exit | | `npm test` | Vitest, one pass then exit |
| `npm run check:render` | Headless Chrome check that the 16-bit sidecar and JPEG proxy upload in the same row order |
| `npm run predeploy` | Typecheck, unit suite, render check, then build — run this before pushing a deploy; the build is skipped when only test files changed since the last build |
| `npm run deploy` | Predeploy gate, then rsync, remote build, restart and bundle-hash check (see [Production deployment](#production-deployment)) |
Conventions worth knowing before changing code: Conventions worth knowing before changing code:
@@ -784,7 +993,7 @@ Conventions worth knowing before changing code:
### Tests ### Tests
`npm test` runs six Vitest files, all pure-logic: `npm test` runs the pure-logic Vitest suite:
| File | Covers | | File | Covers |
| --- | --- | | --- | --- |
@@ -794,9 +1003,25 @@ Conventions worth knowing before changing code:
| `src/lib/lensNames.test.ts` | EXIF lens-name normalisation, search variants and match scoring | | `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/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/editSections.test.ts` | Selective settings copy and the ISO-aware auto-noise curve |
| `src/lib/preview16.test.ts` | 16-bit PNG proxy parsing, row order, 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, rendering-intent selection and CMYK profiles |
| `src/lib/dcpLibrary.test.ts` | Per-camera DCP library: validation, replacement, forgetting and camera matching |
There are no server integration tests; the API is exercised through the UI. There are no server integration tests; the API is exercised through the UI.
`npm run check:render` covers the one thing the unit suite cannot: what a shader does to
real GPU pixels. It encodes a 16-bit sidecar with the server's own encoder, serves it
beside the matching JPEG proxy and measures the rows that reach a WebGL2 texture in
headless Chrome. Then it renders that image through the real `Renderer` with the Ctrl
clipping preview on, so the overlay has to paint red for one clipped channel and yellow
for two instead of collapsing to white, and an unclipped band has to turn white once
Exposure is pushed past the top of the range. The same run checks the shadow warning:
red for one channel at black, yellow for red+green, cyan for green+blue. `npm run
predeploy` chains it with the typecheck, unit suite and build. It fails on either regression, printing the
measured values, needs Chrome (`CHROME_PATH` overrides discovery) and skips with a notice
when none is installed.
--- ---
## Troubleshooting ## Troubleshooting
@@ -818,20 +1043,60 @@ There are no server integration tests; the API is exercised through the UI.
## Limitations ## Limitations
- **Not a cloud service.** No hosted deployment, no tethered capture, no sync client - **Not a cloud service.** No hosted deployment and no camera driver: tethering is a
beyond one browser tab's whole-record push. The last writer wins per photo; it is 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. designed for a handful of people, not concurrent batch workflows.
- **Per-account catalogs.** Workspaces are private to their owner; there is no shared - **Per-account catalogs.** Workspaces are private to their owner; there is no shared
library between two members. Collaboration happens through client proofing links and library between two members. Collaboration happens through client proofing links and
the admin overview. the admin overview.
- **Proxy-bounded raw.** Raw editing works on the demosaiced JPEG proxy (6000 px - **Proxy-bounded raw.** Raw editing works on the demosaiced proxy (6000 px default),
default), not the sensor mosaic; export size is bounded by the proxy. not the sensor mosaic; export size is bounded by the proxy. Raw imports keep two
- **Approximate tools.** Temperature/tint are relative to the as-shot white balance. files: the JPEG proxy every browser can decode, and a 16-bit PNG sidecar of the same
Auto masks are an on-device saliency/colour estimate, not a segmentation model. Soft pixels. The editor grades the sidecar as a half-float source texture when it is
proofing approximates paper white, black point and print gamut but does not apply a present, which is what keeps a heavy shadow lift or a 3200 K white balance from
printer ICC profile; use the browser print dialog for final ICC handling. The 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: the Develop canvas, exports, Compare and preset previews. The grid
uses a camera-native tile built on demand beside the sidecar (`previews/<id>.t16.png`),
so a profile does not cost a 50 MB fetch per card; a photo that predates the tile or
was imported with `LUMINARY_16BIT=0` falls back to the JPEG, which already has the
body matrix baked in. The sidecar costs about 25× the JPEG in disk, one download per photo at open time and
one extra texture in GPU memory (about 8 bytes per pixel), so `LUMINARY_16BIT=0` turns
it off for libraries that would rather have the space. Either way the 16-bit TIFF export writes 65,536
samples per channel from the `RGBA16F` render target, so its precision is only more
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. A loaded matrix is also remembered
per camera body in a local profile library (`src/lib/dcpLibrary.ts`), so the next
frame from that body needs one menu pick instead of another file dialog; the edit
keeps its own copy, so the library is only a shortcut. The picker is available only on
camera-native sidecars; an older sRGB proxy needs a RAW reprocess first.
Auto masks are an on-device colour-model segmentation (border histogram, Otsu split,
connected components), not a trained segmentation network, so a subject that shares
its colour with the background needs a brush pass. Soft
proofing applies a printer profile's real A2B/B2A tables when one is loaded
(**Soft proofing → Load ICC profile**), and falls back to paper white, black point and
a gamut approximation otherwise. The loaded profile is remembered on this device (a
small IndexedDB store, not the photo record or the catalog) and the edit stores the
rendering intent — perceptual, relative colorimetric or saturation — so a proof
survives reloads and follows the photo. A profile without tables for the chosen intent
falls back to its perceptual pair. The print dialog still does its own colour
management. Both LUT layouts are
read: v2 `lut16` with fixed 256-entry tables and the counted v4 layout that MOAB/Epson
paper profiles and Ghostscript's press profiles actually use (4096 entries, counts at
offsets 48/50). Against LittleCMS on a MOAB/Epson ET-8550 profile the cube agrees to a
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 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 - **Merge scope.** HDR, panorama and focus stacking are translation-aligned and aimed at
bracketed, stacked or horizontal sequences, not handheld multi-row composites. They bracketed, stacked or horizontal sequences, not handheld multi-row composites. They
compose at a reduced working edge (2600 px). compose at a reduced working edge (2600 px).
@@ -869,17 +1134,13 @@ including Lensfun's CC BY-SA 3.0 database, which the MIT licence does not relice
| Component | Version / pin | Upstream | Licence | Notes | | Component | Version / pin | Upstream | Licence | Notes |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| Lensfun library | `655a9c4` | [lensfun/lensfun](https://github.com/lensfun/lensfun) | LGPL-3.0; bundled notices say "or later" | Compiled to WebAssembly; distribution needs the licence text and corresponding source | | Lensfun database | `655a9c4` | [lensfun `data/db`](https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data) | CC BY-SA 3.0 Unported | © Lensfun contributors; shipped as `public/lens-db/profiles.json`; attribution and share-alike apply to the data only |
| Lensfun database | `655a9c4` | [lensfun `data/db`](https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data) | CC BY-SA 3.0 Unported | © Lensfun contributors; shipped as `public/lensfun/lensfun-core.data`; attribution and share-alike apply |
| Lensfun WASM wrapper | 0.1.3 | [lexluthor0304/LensfunWasm](https://github.com/lexluthor0304/LensfunWasm) | MIT | `public/lensfun/LICENSE` is this licence and covers neither the database nor the library |
| LibRaw | via `libraw-wasm` 1.6.0 | [LibRaw/LibRaw](https://github.com/LibRaw/LibRaw) | LGPL-2.1 **or** CDDL-1.0 (dual) | The decoder compiled into the WASM | | LibRaw | via `libraw-wasm` 1.6.0 | [LibRaw/LibRaw](https://github.com/LibRaw/LibRaw) | LGPL-2.1 **or** CDDL-1.0 (dual) | The decoder compiled into the WASM |
| `libraw-wasm` | 1.6.0 | [ybouane/LibRaw-Wasm](https://github.com/ybouane/LibRaw-Wasm) | ISC | Binding layer only; its metadata does not replace LibRaw's terms for the compiled library | | `libraw-wasm` | 1.6.0 | [ybouane/LibRaw-Wasm](https://github.com/ybouane/LibRaw-Wasm) | ISC | Binding layer only; its metadata does not replace LibRaw's terms for the compiled library |
| `sharp` | 0.35.5 | [lovell/sharp](https://github.com/lovell/sharp) | Apache-2.0 | Prebuilt binaries bundle libvips | | `sharp` | 0.35.5 | [lovell/sharp](https://github.com/lovell/sharp) | Apache-2.0 | Prebuilt binaries bundle libvips |
| libvips | bundled by `sharp` | [libvips/libvips](https://github.com/libvips/libvips) | LGPL-2.1-or-later | Applies when distributing binaries or container images | | libvips | bundled by `sharp` | [libvips/libvips](https://github.com/libvips/libvips) | LGPL-2.1-or-later | Applies when distributing binaries or container images |
| tinyxml2 | bundled in Lensfun WASM | [leethomason/tinyxml2](https://github.com/leethomason/tinyxml2) | zlib | |
| utf8proc | bundled in Lensfun WASM | [JuliaStrings/utf8proc](https://github.com/JuliaStrings/utf8proc) | MIT | |
| `exifr` | 7.1.3 | [MikeKovarik/exifr](https://github.com/MikeKovarik/exifr) | MIT | Browser EXIF parsing | | `exifr` | 7.1.3 | [MikeKovarik/exifr](https://github.com/MikeKovarik/exifr) | MIT | Browser EXIF parsing |
| `nodemailer` | 7.0.13 | [nodemailer](https://github.com/nodemailer/nodemailer) | MIT-0 | SMTP notifications | | `nodemailer` | 10.6.1 | [nodemailer](https://github.com/nodemailer/nodemailer) | MIT-0 | SMTP notifications |
| React / React DOM | 18.3.1 | [facebook/react](https://github.com/facebook/react) | MIT | | | React / React DOM | 18.3.1 | [facebook/react](https://github.com/facebook/react) | MIT | |
| Vite / Vitest / plugin-react | 5.4.21 / 2.1.9 / 4.7.0 | [vitejs/vite](https://github.com/vitejs/vite) | MIT | | | Vite / Vitest / plugin-react | 5.4.21 / 2.1.9 / 4.7.0 | [vitejs/vite](https://github.com/vitejs/vite) | MIT | |
| TypeScript | 5.9.3 | [microsoft/TypeScript](https://github.com/microsoft/TypeScript) | Apache-2.0 | | | TypeScript | 5.9.3 | [microsoft/TypeScript](https://github.com/microsoft/TypeScript) | Apache-2.0 | |
@@ -901,18 +1162,15 @@ Creative Commons content licence, and it grants neither patent nor trademark rig
### Redistribution checklist ### Redistribution checklist
`public/lensfun/` currently ships the notices (`NOTICE.md`, `THIRD_PARTY_LICENSES.md`, `public/lens-db/` currently ships the converted data and `NOTICE.md`, but **not** the
`UPSTREAM.md`) and the wrapper's MIT `LICENSE`, but **not** the full LGPL-3.0 or full CC BY-SA 3.0 text. Before distributing Luminary or its container image:
CC BY-SA 3.0 texts. Before distributing Luminary or its container image:
1. Add the upstream licence texts beside the assets: Lensfun `COPYING` and 1. Add the upstream licence text beside the data: Lensfun
`COPYING.LESSER` (the LGPL incorporates GPL-3.0 by reference), and `data/COPYING.CC_BY-SA_3.0`.
`data/COPYING.CC_BY-SA_3.0` for the database. 2. Keep the notice, the pinned commit and the attribution block above in the distributed
2. Keep the notices, the pinned commit and the attribution block above in the distributed copy, served from `public/lens-db/` as it is today.
copy, served from `public/lensfun/` as they are today. 3. Provide corresponding source for the LGPL components still shipped: LibRaw at the
3. Provide corresponding source for the LGPL components: Lensfun and LibRaw at the version actually built.
versions actually built, plus tinyxml2 and utf8proc. Leave
`dist/lensfun/lensfun-core.wasm` and its JS loader replaceable.
4. When publishing a container image, include the same files and the libvips, Node.js and 4. When publishing a container image, include the same files and the libvips, Node.js and
Debian notices. Debian notices.
5. Do not relicense third-party assets under Luminary's own terms, and do not add 5. Do not relicense third-party assets under Luminary's own terms, and do not add
+8 -12
View File
@@ -3,35 +3,31 @@
**Luminary** — notices resolved 23 November 2026. **Luminary** — notices resolved 23 November 2026.
This file consolidates the notices for third-party software that Luminary bundles, This file consolidates the notices for third-party software that Luminary bundles,
links, or ships in its build output and container image. `public/lensfun/NOTICE.md` links, or ships in its build output and container image. `public/lens-db/NOTICE.md`
and `public/lensfun/THIRD_PARTY_LICENSES.md` remain the notices served with the remains the notice served with the Lensfun-derived calibration data; this file does not
Lensfun assets; this file does not replace them. replace it.
The Luminary application code is licensed under the [MIT licence](LICENSE). That licence The Luminary application code is licensed under the [MIT licence](LICENSE). That licence
covers only Luminary's original code: it grants no rights in the components below and covers only Luminary's original code: it grants no rights in the components below and
does not replace their terms. does not replace their terms.
Versions are those resolved in `package-lock.json`; the Lensfun pin is Versions are those resolved in `package-lock.json`; the lens database pin is
`655a9c4e3e53c25bc04843c853e7e7a0121359e7` (see `public/lensfun/UPSTREAM.md`). `655a9c4e3e53c25bc04843c853e7e7a0121359e7` (see `public/lens-db/NOTICE.md`).
## Runtime components ## Runtime components
| Component | Version / pin | Licence | Notice | | Component | Version / pin | Licence | Notice |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| Lensfun library | `655a9c4` | LGPL-3.0-or-later | © Lensfun contributors — https://github.com/lensfun/lensfun | | Lensfun camera/lens database (data only) | `655a9c4` | CC BY-SA 3.0 Unported | © Lensfun contributors — https://creativecommons.org/licenses/by-sa/3.0/ |
| Lensfun camera/lens database | `655a9c4` | CC BY-SA 3.0 Unported | © Lensfun contributors — https://creativecommons.org/licenses/by-sa/3.0/ |
| Lensfun WebAssembly wrapper | 0.1.3 | MIT | © 2026 lex — https://github.com/lexluthor0304/LensfunWasm |
| LibRaw (compiled into `libraw-wasm`) | via `libraw-wasm` 1.6.0 | LGPL-2.1 **or** CDDL-1.0 | © LibRaw LLC — https://github.com/LibRaw/LibRaw | | LibRaw (compiled into `libraw-wasm`) | via `libraw-wasm` 1.6.0 | LGPL-2.1 **or** CDDL-1.0 | © LibRaw LLC — https://github.com/LibRaw/LibRaw |
| `libraw-wasm` | 1.6.0 | ISC | Copyright holder not stated by the package — https://github.com/ybouane/LibRaw-Wasm | | `libraw-wasm` | 1.6.0 | ISC | Copyright holder not stated by the package — https://github.com/ybouane/LibRaw-Wasm |
| `sharp` | 0.35.5 | Apache-2.0 | https://github.com/lovell/sharp | | `sharp` | 0.35.5 | Apache-2.0 | https://github.com/lovell/sharp |
| libvips (bundled in `sharp` binaries) | shipped by `sharp` 0.35.5 | LGPL-2.1-or-later | © libvips contributors — https://github.com/libvips/libvips | | libvips (bundled in `sharp` binaries) | shipped by `sharp` 0.35.5 | LGPL-2.1-or-later | © libvips contributors — https://github.com/libvips/libvips |
| tinyxml2 (in the Lensfun WASM) | — | zlib | © Lee Thomason — https://github.com/leethomason/tinyxml2 |
| utf8proc (in the Lensfun WASM) | — | MIT | © utf8proc contributors — https://github.com/JuliaStrings/utf8proc |
| `exifr` | 7.1.3 | MIT | © 2020 Mike Kovařík, Mutiny.cz — https://github.com/MikeKovarik/exifr | | `exifr` | 7.1.3 | MIT | © 2020 Mike Kovařík, Mutiny.cz — https://github.com/MikeKovarik/exifr |
| `nodemailer` | 7.0.13 | MIT-0 | © 2011-2023 Andris Reinman — https://github.com/nodemailer/nodemailer | | `nodemailer` | 7.0.13 | MIT-0 | © 2011-2023 Andris Reinman — https://github.com/nodemailer/nodemailer |
| React / React DOM | 18.3.1 | MIT | © Facebook, Inc. and its affiliates — https://github.com/facebook/react | | React / React DOM | 18.3.1 | MIT | © Facebook, Inc. and its affiliates — https://github.com/facebook/react |
The Lensfun database is a separate asset from the Lensfun library: CC BY-SA 3.0 The lens database is a separate asset from Luminary's code: CC BY-SA 3.0 applies to
applies to the profile data, not to Luminary's application code. Attribution and Lensfun's calibration data, not to the correction engine that reads it. Attribution and
share-alike requirements are summarised in the README under share-alike requirements are summarised in the README under
[Third-party attribution and licences](README.md#third-party-attribution-and-licences). [Third-party attribution and licences](README.md#third-party-attribution-and-licences).
+1 -1
View File
@@ -20,7 +20,7 @@ This matters because an earlier design assumed an Electron desktop app. It is no
- **Raw path:** `libraw-wasm` in a `worker_threads` pool (`server/libraw-pool.mjs`), - **Raw path:** `libraw-wasm` in a `worker_threads` pool (`server/libraw-pool.mjs`),
`open()` + `imageData()` → 8-bit sRGB JPEG proxy at `RAW_PREVIEW_EDGE = 6000` `open()` + `imageData()` → 8-bit sRGB JPEG proxy at `RAW_PREVIEW_EDGE = 6000`
long edge (`server/config.mjs:14`, `RAW_PREVIEW_EDGE`). `sharp` for JPEG ingest, long edge (`server/config.mjs:14`, `RAW_PREVIEW_EDGE`). `sharp` for JPEG ingest,
`lensfun-wasm` for lens correction. Lensfun's calibration data with Luminary's own correction engine (`src/lib/lensEngine.ts`).
- **Renderer:** `src/gl/renderer.ts`. `setImage()` uploads one `u_src` texture - **Renderer:** `src/gl/renderer.ts`. `setImage()` uploads one `u_src` texture
(`:1144`), grade pass samples it at `:1296`, finish pass at `:1553`. (`:1144`), grade pass samples it at `:1296`, finish pass at `:1553`.
- **Export:** `src/lib/export.ts` builds a fresh `Renderer` from `getBitmap()` — a - **Export:** `src/lib/export.ts` builds a fresh `Renderer` from `getBitmap()` — a
+6 -12
View File
@@ -7,11 +7,11 @@
"": { "": {
"name": "luminary", "name": "luminary",
"version": "1.0.0", "version": "1.0.0",
"license": "MIT",
"dependencies": { "dependencies": {
"@neoanaloglabkk/lensfun-wasm": "^0.1.3",
"exifr": "^7.1.3", "exifr": "^7.1.3",
"libraw-wasm": "^1.6.0", "libraw-wasm": "^1.6.0",
"nodemailer": "^7.0.13", "nodemailer": "^10.6.1",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"sharp": "^0.35.5" "sharp": "^0.35.5"
@@ -1306,12 +1306,6 @@
"@jridgewell/sourcemap-codec": "^1.4.14" "@jridgewell/sourcemap-codec": "^1.4.14"
} }
}, },
"node_modules/@neoanaloglabkk/lensfun-wasm": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/@neoanaloglabkk/lensfun-wasm/-/lensfun-wasm-0.1.3.tgz",
"integrity": "sha512-+Me+P4kqr2CgJ7Tg+VatLSTfWxJkBt/xE9kG0qxD3KCcVY4MVgm/kkMwiVWTJt4EgzdIi3mFwUGO7HEuyziBpw==",
"license": "LGPL-3.0-or-later"
},
"node_modules/@rolldown/pluginutils": { "node_modules/@rolldown/pluginutils": {
"version": "1.0.0-beta.27", "version": "1.0.0-beta.27",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
@@ -2330,12 +2324,12 @@
} }
}, },
"node_modules/nodemailer": { "node_modules/nodemailer": {
"version": "7.0.13", "version": "10.6.1",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.13.tgz", "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.6.1.tgz",
"integrity": "sha512-PNDFSJdP+KFgdsG3ZzMXCgquO7I6McjY2vlqILjtJd0hy8wEvtugS9xKRF2NWlPNGxvLCXlTNIae4serI7dinw==", "integrity": "sha512-d7kfFfS/tR4Aca+SBvRaQ+MXKNv7d2JiRe5TxaRcFT/kYMh4GGPnW9aKksTIEvyEbA7d/7HYWE4YPDEHxzJj/g==",
"license": "MIT-0", "license": "MIT-0",
"engines": { "engines": {
"node": ">=6.0.0" "node": ">=20.0.0"
} }
}, },
"node_modules/pathe": { "node_modules/pathe": {
+6 -3
View File
@@ -12,13 +12,16 @@
"start": "node server/index.mjs", "start": "node server/index.mjs",
"preview": "vite preview", "preview": "vite preview",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"test": "vitest run" "test": "vitest run",
"check:render": "node scripts/render-check.mjs",
"predeploy": "node scripts/predeploy.mjs",
"deploy": "node scripts/deploy.mjs",
"build:lens-db": "node scripts/build-lens-db.mjs"
}, },
"dependencies": { "dependencies": {
"@neoanaloglabkk/lensfun-wasm": "^0.1.3",
"exifr": "^7.1.3", "exifr": "^7.1.3",
"libraw-wasm": "^1.6.0", "libraw-wasm": "^1.6.0",
"nodemailer": "^7.0.13", "nodemailer": "^10.6.1",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"sharp": "^0.35.5" "sharp": "^0.35.5"
+21
View File
@@ -0,0 +1,21 @@
# Lens database notice
`profiles.json` in this directory is a converted copy of the Lensfun camera and lens
database, produced by `scripts/build-lens-db.mjs`.
```text
Lens database: © Lensfun contributors, CC BY-SA 3.0 Unported
https://lensfun.github.io/ · https://creativecommons.org/licenses/by-sa/3.0/
Pinned source: https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data
```
- Only the calibration measurements come from Lensfun. The correction maths, the
search/matching code and the file format are Luminary's own (MIT).
- The data remains under CC BY-SA 3.0. Keep this attribution with it, and if you edit
`profiles.json` or regenerate it with different calibration data, distribute the
result under CC BY-SA 3.0 or a compatible licence and indicate the changes.
- Do not describe the database as MIT, public domain or OSI-approved open source: it is
a Creative Commons content licence and grants neither patent nor trademark rights.
- The full licence text is not bundled here; add Lensfun's
`data/COPYING.CC_BY-SA_3.0` beside this file before redistributing the app or its
container image.
File diff suppressed because one or more lines are too long
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2026 lex
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-10
View File
@@ -1,10 +0,0 @@
# Notices
This project bundles and/or links the following third-party components:
1. Lensfun library source code (`third_party/lensfun/libs`) under LGPL-3.0-or-later.
2. Lensfun camera/lens database (`third_party/lensfun/data/db`) under CC BY-SA 3.0.
3. tinyxml2 (`third_party/tinyxml2`) under zlib license.
4. utf8proc (`third_party/utf8proc`) under MIT license.
Refer to `THIRD_PARTY_LICENSES.md` for license texts and links.
-20
View File
@@ -1,20 +0,0 @@
# Third-Party Licenses
## Lensfun
- Repository: https://github.com/lensfun/lensfun
- Library license: GNU LGPL v3.0 or later
- Database license: Creative Commons Attribution-ShareAlike 3.0
- Copyright: Lensfun contributors
## tinyxml2
- Repository: https://github.com/leethomason/tinyxml2
- License: zlib
- Copyright: Lee Thomason
## utf8proc
- Repository: https://github.com/JuliaStrings/utf8proc
- License: MIT
- Copyright: utf8proc contributors
-23
View File
@@ -1,23 +0,0 @@
# Upstream Tracking
## Source of truth
- Upstream repo: https://github.com/lensfun/lensfun.git
- Integration mode: git submodule (`third_party/lensfun`)
- Current pinned commit: `655a9c4e3e53c25bc04843c853e7e7a0121359e7`
- Commit date: `2026-02-28`
- Commit subject: `Add tca data for Meike SL 35mm F1.8 STM PRO`
## Update policy
- Pin exact commits.
- Upgrade manually via PR.
- Run full build/test after each bump.
## Update steps
1. `scripts/sync-upstream.sh origin/master`
2. Review upstream diff impact (API, DB changes, compile behavior)
3. Rebuild wasm assets
4. Run tests
5. Update this file with new commit metadata
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
Binary file not shown.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+308
View File
@@ -0,0 +1,308 @@
#!/usr/bin/env node
/**
* Builds the lens profile database the editor ships.
*
* The calibration measurements come from the Lensfun project's database
* (CC BY-SA 3.0, © Lensfun contributors); this script only converts the XML
* into the compact form `src/lib/lensDb.ts` reads, so the app no longer needs
* the Lensfun WebAssembly runtime. Data, not code: the maths lives in
* `src/lib/lensEngine.ts`.
*
* Usage:
* node scripts/build-lens-db.mjs --db <lensfun/data/db> [--out <file>]
*
* `--db` is a checkout of https://github.com/lensfun/lensfun at the pinned commit
* recorded in `public/lens-db/NOTICE.md`; only its `data/db/*.xml` files are read.
* The generated file is committed, so a normal build does not need the checkout.
*/
import { readFileSync, writeFileSync, readdirSync, mkdirSync, existsSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
const DIST_MODELS = ['poly3', 'poly5', 'ptlens', 'linear', 'acm'];
const TCA_MODELS = ['poly3', 'linear', 'acm'];
const args = process.argv.slice(2);
const argValue = (name, fallback) => {
const at = args.indexOf(name);
return at >= 0 && args[at + 1] ? args[at + 1] : fallback;
};
const DB_DIR = argValue('--db', '');
const OUT = resolve(argValue('--out', 'public/lens-db/profiles.json'));
/* ------------------------------------------------------------------ parsing */
/** Rounds to six decimals and drops trailing zeros, to keep the file small. */
function round(n) {
return Number.isFinite(n) ? Math.round(n * 1e6) / 1e6 : 0;
}
function num(value) {
if (value == null || value === '') return 0;
return round(Number(value));
}
/** "3:2" or "1.5" as a number, 0 when absent so the engine can use the image. */
function aspectRatio(value) {
if (!value) return 0;
const parts = value.split(':').map(Number);
if (parts.length === 2 && parts[0] > 0 && parts[1] > 0) return round(parts[0] / parts[1]);
return num(value);
}
const TAG = /<(\/?)([a-zA-Z0-9_:.-]+)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
const ATTR = /([a-zA-Z0-9_:.-]+)\s*=\s*("([^"]*)"|'([^']*)')/g;
function attributes(source) {
const out = {};
for (const match of source.matchAll(ATTR)) {
out[match[1]] = decode(match[3] ?? match[4] ?? '');
}
return out;
}
/**
* Minimal XML reader for the Lensfun schema: elements, attributes and text.
* Comments and the doctype are skipped; nothing here needs namespaces,
* entities beyond the five predefined ones, or CDATA.
*/
function parseXml(source) {
// Comments carry prose (and markup examples) that must not reach the tag
// scanner, or they unbalance the element stack.
const xml = source.replace(/<!--[\s\S]*?-->/g, '');
const root = { name: '#root', attrs: {}, children: [], text: '' };
const stack = [root];
let cursor = 0;
TAG.lastIndex = 0;
for (let match = TAG.exec(xml); match; match = TAG.exec(xml)) {
const [whole, closing, name, rawAttrs, selfClosing] = match;
const between = xml.slice(cursor, match.index);
cursor = match.index + whole.length;
if (between.trim()) stack[stack.length - 1].text += decode(between.trim());
if (closing) {
if (stack.length > 1) stack.pop();
continue;
}
const node = { name, attrs: attributes(rawAttrs), children: [], text: '' };
stack[stack.length - 1].children.push(node);
if (!selfClosing) stack.push(node);
}
return root;
}
function decode(text) {
return text
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&amp;/g, '&');
}
const kids = (node, name) => node.children.filter((child) => child.name === name);
const kid = (node, name) => kids(node, name)[0];
const text = (node) => (node ? node.text.trim() : '');
/** Picks the untagged value, falling back to English. */
function localized(node, name) {
const all = kids(node, name);
if (!all.length) return '';
const plain = all.find((entry) => !entry.attrs.lang);
if (plain) return text(plain);
const english = all.find((entry) => entry.attrs.lang === 'en' || entry.attrs.lang === 'en_US');
return text(english ?? all[0]);
}
/* --------------------------------------------------------------- conversion */
function convertFile(xml, db) {
const doc = parseXml(xml);
const root = kid(doc, 'lensdatabase');
if (!root) return;
for (const mount of kids(root, 'mount')) {
const name = text(kid(mount, 'name'));
if (name) db.mounts.add(name);
}
for (const camera of kids(root, 'camera')) {
const maker = localized(camera, 'maker');
const model = localized(camera, 'model');
if (!maker || !model) continue;
db.cameras.push({ maker, model, mount: text(kid(camera, 'mount')), crop: num(text(kid(camera, 'cropfactor'))) || 1 });
}
for (const lens of kids(root, 'lens')) {
const maker = localized(lens, 'maker');
const model = localized(lens, 'model');
if (!maker || !model) continue;
const record = {
maker,
model,
crop: num(text(kid(lens, 'cropfactor'))) || 1,
mounts: kids(lens, 'mount').map((entry) => text(entry)).filter(Boolean),
aspect: aspectRatio(text(kid(lens, 'aspect-ratio'))),
centerX: num(text(kid(lens, 'center-x'))),
centerY: num(text(kid(lens, 'center-y'))),
d: [],
t: [],
v: [],
};
const calibration = kid(lens, 'calibration');
if (calibration) {
for (const entry of kids(calibration, 'distortion')) {
const terms = distortionTerms(entry);
if (!terms) continue;
// A few calibrations were measured at a focal length other than the
// nominal one; Lensfun scales by the ratio, so keep it (0 = same focal).
record.d.push([
num(entry.attrs.focal),
terms.model,
...terms.terms,
num(entry.attrs['real-focal']),
]);
}
for (const entry of kids(calibration, 'tca')) {
const terms = tcaTerms(entry);
if (!terms) continue;
record.t.push([num(entry.attrs.focal), terms.model, ...terms.terms]);
}
for (const entry of kids(calibration, 'vignetting')) {
const model = entry.attrs.model;
if (model !== 'pa' && model !== 'acm') continue;
record.v.push([
num(entry.attrs.focal),
num(entry.attrs.aperture),
num(entry.attrs.distance),
num(entry.attrs.k1),
num(entry.attrs.k2),
num(entry.attrs.k3),
]);
}
}
db.stats.lenses += 1;
if (record.d.length || record.t.length || record.v.length) db.lenses.push(record);
else db.stats.withoutCalibration += 1;
}
}
/**
* Lensfun stores poly3 as `k1`, polygon (poly5) as `k1`/`k2`, and PanoTools as
* `a`/`b`/`c`. Everything is normalised to the `a·r³ + b·r² + c·r + 1` form the
* engine evaluates, with the PanoTools `d = 1 - a - b - c` factor divided out
* the way Lensfun does so the focal length is preserved.
*/
function distortionTerms(entry) {
const attrs = entry.attrs;
switch (attrs.model) {
case 'poly3': {
const k1 = num(attrs.k1);
const d = 1 - k1;
return { model: DIST_MODELS.indexOf('poly3'), terms: [0, round(k1 / d ** 3), 0] };
}
case 'poly5':
return { model: DIST_MODELS.indexOf('poly5'), terms: [0, num(attrs.k1), num(attrs.k2)] };
case 'ptlens': {
const a = num(attrs.a);
const b = num(attrs.b);
const c = num(attrs.c);
const d = 1 - a - b - c;
return {
model: DIST_MODELS.indexOf('ptlens'),
terms: [round(a / d ** 4), round(b / d ** 3), round(c / d ** 2)],
};
}
case 'linear':
return { model: DIST_MODELS.indexOf('linear'), terms: [0, 0, 0] };
default:
return null;
}
}
function tcaTerms(entry) {
const attrs = entry.attrs;
if (attrs.model === 'poly3') {
// Stored per channel as [br, cr, vr] / [bb, cb, vb], matching the term
// order the engine evaluates: r_d = r * (v + c*r + b*r^2).
return {
model: TCA_MODELS.indexOf('poly3'),
terms: [num(attrs.br), num(attrs.cr), num(attrs.vr || 1), num(attrs.bb), num(attrs.cb), num(attrs.vb || 1)],
};
}
if (attrs.model === 'linear') {
return { model: TCA_MODELS.indexOf('linear'), terms: [num(attrs.kr || 1), num(attrs.kb || 1)] };
}
return null;
}
/* --------------------------------------------------------------------- main */
function loadXmlFiles() {
if (!DB_DIR) {
throw new Error(
'pass --db <path to lensfun/data/db>; the profiles are committed, so this is only ' +
'needed when refreshing them',
);
}
const dir = resolve(DB_DIR);
if (!existsSync(dir)) throw new Error(`database directory not found: ${dir}`);
return readdirSync(dir)
.filter((name) => name.endsWith('.xml'))
.sort()
.map((name) => readFileSync(join(dir, name), 'utf8'));
}
const db = { mounts: new Set(), cameras: [], lenses: [], stats: { lenses: 0, withoutCalibration: 0 } };
for (const xml of loadXmlFiles()) {
try {
convertFile(xml, db);
} catch (err) {
console.warn(`skipped a database file: ${err.message}`);
}
}
const slug = (value) =>
value
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
const seen = new Map();
const lenses = db.lenses.map((lens) => {
const base = `${slug(lens.maker)}-${slug(lens.model)}`;
const count = (seen.get(base) ?? 0) + 1;
seen.set(base, count);
return {
id: count === 1 ? base : `${base}-${count}`,
maker: lens.maker,
model: lens.model,
crop: lens.crop,
mounts: lens.mounts,
aspect: lens.aspect,
centerX: lens.centerX,
centerY: lens.centerY,
d: lens.d.sort((a, b) => a[0] - b[0]),
t: lens.t.sort((a, b) => a[0] - b[0]),
v: lens.v.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]),
};
});
const payload = {
source: {
project: 'lensfun',
commit: '655a9c4e3e53c25bc04843c853e7e7a0121359e7',
licence: 'CC BY-SA 3.0 Unported',
note: 'Calibration data only; the correction maths is Luminary\u2019s own.',
},
models: { distortion: DIST_MODELS, tca: TCA_MODELS },
mounts: [...db.mounts].sort(),
cameras: db.cameras.sort((a, b) => a.maker.localeCompare(b.maker) || a.model.localeCompare(b.model)),
lenses,
};
mkdirSync(dirname(OUT), { recursive: true });
writeFileSync(OUT, `${JSON.stringify(payload)}\n`);
console.log(
`wrote ${OUT}: ${lenses.length} lenses with calibration (${db.stats.withoutCalibration} of ` +
`${db.stats.lenses} entries have none), ${payload.cameras.length} cameras, ` +
`${lenses.reduce((n, lens) => n + lens.v.length, 0)} vignetting samples`,
);
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env node
/**
* Deploy Luminary: run the predeploy gate, then copy the source to the server,
* rebuild it there and restart the service.
*
* The gate runs first and a failure exits before anything touches the server,
* so a type error, a failing test or a shader regression caught by the render
* check cannot reach production. The local bundle is compared with the one the
* server just built, so a deploy that silently ships stale assets is visible.
*
* Exits via process.exitCode rather than process.exit(): stdout/stderr are
* async when piped, and exiting early truncates the very lines that explain
* why a deploy stopped.
*
* Environment:
* LUMINARY_DEPLOY_HOST ssh target, e.g. bhursey@photos.example.org (required)
* LUMINARY_DEPLOY_PATH remote checkout of this repo (default /srv/luminary)
* LUMINARY_DEPLOY_SERVICE systemd unit to restart (default luminary)
* LUMINARY_DEPLOY_SSH_PASS optional ssh password, passed to sshpass via env
* LUMINARY_DEPLOY_SUDO_PASS optional sudo password for the remote build/restart
*/
import { execFileSync } from 'node:child_process';
import { existsSync, readdirSync } from 'node:fs';
import path from 'node:path';
const env = process.env;
const HOST = env.LUMINARY_DEPLOY_HOST;
const REMOTE_PATH = env.LUMINARY_DEPLOY_PATH || '/srv/luminary';
const SERVICE = env.LUMINARY_DEPLOY_SERVICE || 'luminary';
const SSH_PASS = env.LUMINARY_DEPLOY_SSH_PASS || '';
const SUDO_PASS = env.LUMINARY_DEPLOY_SUDO_PASS || '';
/** Local-only state that must never be copied over the server's copy. */
const EXCLUDES = [
'node_modules',
'dist',
'data',
'.git',
'.freebuff',
'.check',
'.smoke',
'logo.png',
'*.log',
];
function run(command, args, extraEnv) {
execFileSync(command, args, {
stdio: 'inherit',
env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
});
}
function sshArgs(script) {
return ['-o', 'StrictHostKeyChecking=accept-new', HOST, script];
}
/** Runs a remote script with stdout echoed, returning what it printed. */
function sshCapture(script, input) {
const piped = input !== undefined;
const output = execFileSync(
SSH_PASS ? 'sshpass' : 'ssh',
SSH_PASS ? ['-e', 'ssh', ...sshArgs(script)] : sshArgs(script),
{
stdio: [piped ? 'pipe' : 'inherit', 'pipe', 'inherit'],
input,
encoding: 'utf8',
env: SSH_PASS ? { ...process.env, SSHPASS: SSH_PASS } : process.env,
},
);
process.stdout.write(output);
return output;
}
function localBundles() {
const dir = path.join(process.cwd(), 'dist', 'assets');
if (!existsSync(dir)) return [];
return readdirSync(dir)
.filter((file) => /^index-.*\.(js|css)$/.test(file))
.sort();
}
function main() {
if (!HOST) {
console.error('deploy: set LUMINARY_DEPLOY_HOST to the ssh target, e.g. user@server.');
return 2;
}
// 1. Gate. Nothing below this line may run if the gate fails.
// npm runs a script called "predeploy" before "deploy", so under `npm run
// deploy` the gate has already passed before this process starts; running it
// again would typecheck and render-check the same source twice. Invoked
// directly, this script has to run the gate itself.
if (env.npm_lifecycle_event === 'deploy') {
console.log('deploy: predeploy gate passed (npm predeploy hook)');
} else {
console.log('deploy: predeploy gate');
try {
run(process.execPath, [path.join('scripts', 'predeploy.mjs')]);
} catch {
console.error('deploy: aborted - predeploy failed, nothing was sent to the server.');
return 1;
}
}
// 2. Copy the source, keeping server-side data and build output.
console.log(`\ndeploy: rsync to ${HOST}:${REMOTE_PATH}`);
const rsyncArgs = ['-az'];
for (const item of EXCLUDES) rsyncArgs.push(`--exclude=${item}`);
const remoteShell = SSH_PASS
? `sshpass -e ssh -o StrictHostKeyChecking=accept-new`
: `ssh -o StrictHostKeyChecking=accept-new`;
rsyncArgs.push('-e', remoteShell, './', `${HOST}:${REMOTE_PATH}/`);
try {
run('rsync', rsyncArgs, SSH_PASS ? { SSHPASS: SSH_PASS } : undefined);
} catch {
console.error('deploy: aborted - rsync failed.');
return 1;
}
// 3. Rebuild and restart there, then report what is actually being served.
const sudo = SUDO_PASS ? `sudo -S -p '' ` : '';
const sudoLines = SUDO_PASS ? `${SUDO_PASS}\n${SUDO_PASS}\n` : undefined;
const script = [
`cd ${REMOTE_PATH} || exit 3`,
`${sudo}npm run build`,
'build=$?',
'[ "$build" -eq 0 ] || { echo "deploy: remote build failed ($build)"; exit "$build"; }',
`${sudo}systemctl restart ${SERVICE}`,
'sleep 2',
`systemctl is-active ${SERVICE}`,
'sha256sum dist/assets/*.js dist/assets/*.css',
].join('\n');
console.log(`\ndeploy: build and restart ${SERVICE} on ${HOST}`);
let output;
try {
output = sshCapture(script, sudoLines);
} catch {
console.error('deploy: aborted - the remote build or restart failed.');
return 1;
}
// 4. The server must be serving the bundle the gate just reviewed.
const remoteHashes = new Map();
for (const line of output.split('\n')) {
const match = /^([0-9a-f]{64})\s+dist\/assets\/(index-[^/\s]+)$/.exec(line.trim());
if (match) remoteHashes.set(match[2], match[1]);
}
const missing = localBundles().filter((file) => !remoteHashes.has(file));
if (missing.length) {
console.error(
`\ndeploy: FAILED - the server is not serving ${missing.join(', ')}; check the remote build.`,
);
return 1;
}
const served = [...remoteHashes.entries()];
console.log(
`\ndeploy PASSED: ${SERVICE} is active on ${HOST} serving ${served
.map(([file, hash]) => `${file} (${hash.slice(0, 12)})`)
.join(', ')}.`,
);
return 0;
}
process.exitCode = main();
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env node
/**
* Pre-deploy gate: typecheck, unit suite, render check, then the production
* build -- skipped when nothing that feeds the bundle has changed since the
* last successful build, so editing only a test file does not rebuild dist.
*
* The signature is stored under node_modules/.cache: that directory is
* gitignored and excluded from the deploy rsync, so it is per-checkout state
* and never travels to the server.
*
* Exits via process.exitCode rather than process.exit(): piped stdout is async
* and exiting early truncates the failure message.
*/
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import {
existsSync,
mkdirSync,
readFileSync,
readdirSync,
statSync,
writeFileSync,
} from 'node:fs';
import path from 'node:path';
const ROOT = process.cwd();
const CACHE = path.join(ROOT, 'node_modules', '.cache', 'luminary-predeploy.json');
/** Vite inputs: everything the bundle is built from, plus the config it reads. */
const INPUTS = [
'src',
'public',
'index.html',
'vite.config.ts',
'tsconfig.json',
'package.json',
'package-lock.json',
];
/** Test files never reach the bundle, so their edits must not force a rebuild. */
const NOT_BUNDLED = /(^|\/)(__tests__|__mocks__|__fixtures__)(\/|$)|\.(test|spec)\.[cm]?[jt]sx?$/;
class StepFailed extends Error {}
function walk(target) {
if (!existsSync(target)) return [];
if (statSync(target).isFile()) return [target];
return readdirSync(target, { withFileTypes: true }).flatMap((entry) =>
walk(path.join(target, entry.name)),
);
}
function inputSignature() {
const files = INPUTS.flatMap((entry) => walk(entry))
.map((file) => path.relative(ROOT, file).split(path.sep).join('/'))
.filter((file) => !NOT_BUNDLED.test(file))
.sort();
const hash = createHash('sha256');
for (const file of files) {
hash.update(file);
hash.update('\0');
hash.update(readFileSync(path.join(ROOT, file)));
hash.update('\0');
}
return { count: files.length, digest: hash.digest('hex') };
}
function run(name, args) {
console.log(`\npredeploy: ${name}`);
try {
execFileSync('npm', args, { cwd: ROOT, stdio: 'inherit' });
} catch {
throw new StepFailed(name);
}
}
function main() {
const signature = inputSignature();
const previous = existsSync(CACHE) ? JSON.parse(readFileSync(CACHE, 'utf8')) : null;
const upToDate =
existsSync(path.join(ROOT, 'dist', 'index.html')) && previous?.digest === signature.digest;
try {
run('typecheck', ['run', 'typecheck']);
run('tests', ['run', 'test']);
run('render check', ['run', 'check:render']);
if (upToDate) {
console.log(
`\npredeploy: build skipped - the ${signature.count} bundle inputs are unchanged since the last build.`,
);
} else {
run('build', ['run', 'build']);
}
} catch (err) {
if (!(err instanceof StepFailed)) throw err;
console.error(`\npredeploy FAILED at ${err.message}.`);
return 1;
}
if (!upToDate) {
mkdirSync(path.dirname(CACHE), { recursive: true });
writeFileSync(
CACHE,
`${JSON.stringify({ digest: signature.digest, count: signature.count, at: new Date().toISOString() }, null, 2)}\n`,
);
}
console.log('\npredeploy PASSED.');
return 0;
}
process.exitCode = main();
+740
View File
@@ -0,0 +1,740 @@
#!/usr/bin/env node
/**
* Headless render check for the 16-bit proxy swap.
*
* The editor shows the JPEG proxy first and swaps in the 16-bit sidecar a few
* seconds later. Both uploads go through `Renderer.setImage`, and whether they
* agree depends on a WebGL detail that no unit test can cover: `UNPACK_FLIP_Y_WEBGL`
* is ignored for `ImageBitmap` sources (the proxy) but honoured for typed arrays
* (the sidecar). If the two disagree, the picture jumps upside down at the swap.
*
* This script builds a two-tone 16-bit PNG with the server's own encoder plus the
* matching JPEG, serves `parsePreview16` through Vite, and measures the rows that
* actually reach the GPU in headless Chrome. It fails if the top row of the proxy
* is not the top row of the sidecar.
*
* Runs outside `npm test` because it needs a WebGL2-capable Chrome:
* npm run check:render
*/
import { spawn } from 'node:child_process';
import { existsSync } from 'node:fs';
import { mkdir, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import sharp from 'sharp';
import { createServer } from 'vite';
import { encodePng16 } from '../server/imaging.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const DIR = path.join(ROOT, '.render-check');
const PAGE = path.join(DIR, 'index.html');
const W = 96;
const H = 64;
const CHROME_CANDIDATES = [
process.env.CHROME_PATH,
'google-chrome',
'google-chrome-stable',
'chromium',
'chromium-browser',
].filter(Boolean);
async function findChrome() {
for (const candidate of CHROME_CANDIDATES) {
if (candidate.includes(path.sep)) {
if (existsSync(candidate)) return candidate;
continue;
}
if (await spawnSyncOk(candidate)) return candidate;
}
return null;
}
function spawnSyncOk(bin) {
const probe = spawn(bin, ['--version'], { stdio: 'ignore' });
return new Promise((resolve) => {
probe.on('error', () => resolve(false));
probe.on('exit', (code) => resolve(code === 0));
});
}
/**
* Horizontal bands that exercise both ends of the range: one and two channels
* blown, one clean band, then one and two channels crushed, plus a green+blue
* crush to check the secondary colour. The same image proves the clipping
* overlay names the channels instead of painting every warning one colour.
*/
const BANDS = [
[1.0, 0.55, 0.08], // highlight: red only
[1.0, 1.0, 0.08], // highlight: red + green (yellow)
[0.24, 0.28, 0.35], // nothing clipped
[0.0, 0.3, 0.35], // shadow: red only
[0.0, 0.0, 0.35], // shadow: red + green (yellow)
[0.3, 0.0, 0.0], // shadow: green + blue (cyan)
];
function buildSource() {
const rgb16 = new Uint16Array(W * H * 3);
const rgb8 = new Uint8Array(W * H * 3);
const bands = BANDS;
for (let y = 0; y < H; y++) {
const band = bands[Math.min(bands.length - 1, Math.floor((y / H) * bands.length))];
for (let x = 0; x < W; x++) {
const i = (y * W + x) * 3;
for (let c = 0; c < 3; c++) {
rgb16[i + c] = Math.round(band[c] * 65535);
rgb8[i + c] = Math.round(band[c] * 255);
}
}
}
return { rgb8, rgb16 };
}
const PAGE_HTML = `<!doctype html>
<meta charset="utf-8" />
<pre id="out">boot</pre>
<script type="module">
import { parsePreview16 } from '/src/lib/preview16.ts';
import { Renderer } from '/src/gl/renderer.ts';
import { defaultEdits, defaultLocalComponent, defaultLocalLayer } from '/src/lib/edits.ts';
const pre = document.getElementById('out');
const half = (bits) => {
const s = bits >> 15 ? -1 : 1;
const e = (bits >> 10) & 0x1f;
const m = bits & 0x3ff;
if (e === 0) return s * m * Math.pow(2, -24);
if (e === 31) return m ? NaN : s * Infinity;
return s * (1 + m / 1024) * Math.pow(2, e - 15);
};
try {
const canvas = document.createElement('canvas');
const gl = canvas.getContext('webgl2', { alpha: false, antialias: false });
if (!gl) { pre.textContent = 'ERROR no WebGL2 in this Chrome'; throw new Error('no webgl2'); }
const makeTex = () => {
const t = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, t);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
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);
return t;
};
// readPixels rows start at the framebuffer's bottom row, which is texel row 0.
const rowLuma = (tex, y, w) => {
gl.bindTexture(gl.TEXTURE_2D, tex);
const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {
throw new Error('framebuffer incomplete');
}
const buf = new Uint8Array(w * 4);
gl.readPixels(0, y, w, 1, gl.RGBA, gl.UNSIGNED_BYTE, buf);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.deleteFramebuffer(fb);
let sum = 0;
for (let i = 0; i < w; i++) {
sum += 0.2126 * buf[i * 4] + 0.7152 * buf[i * 4 + 1] + 0.0722 * buf[i * 4 + 2];
}
return sum / w / 255;
};
const blob = await (await fetch('/.render-check/proxy.jpg')).blob();
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
const w = bitmap.width;
const h = bitmap.height;
// Exactly what Renderer.setImage does for the JPEG proxy.
const texFlip = makeTex();
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
const texNoFlip = makeTex();
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
const png = await (await fetch('/.render-check/side.p16.png')).arrayBuffer();
const parsed = await parsePreview16(png);
if (!parsed) throw new Error('parsePreview16 returned null');
if (parsed.width !== w || parsed.height !== h) {
throw new Error('sidecar ' + parsed.width + 'x' + parsed.height + ' vs proxy ' + w + 'x' + h);
}
// Exactly what Renderer.setImage does for the sidecar: rows in parser order, unflipped.
const sideRow = (y) => {
const out = new Uint8Array(w * 4);
for (let x = 0; x < w; x++) {
const i = (y * w + x) * 4;
const toByte = (bits) => Math.round(Math.min(1, Math.max(0, half(bits))) * 255);
out[x * 4] = toByte(parsed.rgba[i]);
out[x * 4 + 1] = toByte(parsed.rgba[i + 1]);
out[x * 4 + 2] = toByte(parsed.rgba[i + 2]);
out[x * 4 + 3] = 255;
}
const tex = makeTex();
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, out);
return tex;
};
const sideTopTex = sideRow(0);
const sideBottomTex = sideRow(h - 1);
const proxyTop = rowLuma(texFlip, 0, w);
const proxyBottom = rowLuma(texFlip, h - 1, w);
const proxyNoFlipTop = rowLuma(texNoFlip, 0, w);
const sideTop = rowLuma(sideTopTex, 0, w);
const sideBottom = rowLuma(sideBottomTex, 0, w);
const same = (a, b) => Math.abs(a - b) < 0.02;
// Clipping overlay: red for one clipped channel, yellow for two. This renders
// through the real Renderer, so a shader that collapses the warning to white
// (or loses the shadow/highlight bit) fails here.
const view = document.createElement('canvas');
const renderer = new Renderer(view);
renderer.setImage(bitmap, parsed);
renderer.render(defaultEdits(), { width: w, height: h, clipPreview: true });
const viewGl = view.getContext('webgl2');
const sampleBand = (index) => {
// readPixels rows start at the bottom, so flip the band centre.
const py = h - 1 - Math.floor((h * (index + 0.5)) / ${BANDS.length});
const px = new Uint8Array(4);
viewGl.readPixels(Math.floor(w / 2), py, 1, 1, viewGl.RGBA, viewGl.UNSIGNED_BYTE, px);
return [px[0], px[1], px[2]];
};
const clipPixels = [0, 1, 2].map(sampleBand);
const near = (pixel, target) =>
Math.abs(pixel[0] - target[0]) < 14 &&
Math.abs(pixel[1] - target[1]) < 14 &&
Math.abs(pixel[2] - target[2]) < 14;
const RED_MARK = [255, 31, 31];
const YELLOW_MARK = [255, 230, 26];
// The preview has to follow the sliders it is shown for: +6 EV blows every
// channel of the unclipped band, so it must turn white, not stay clear.
const brightEdits = defaultEdits();
brightEdits.exposure = 6;
renderer.render(brightEdits, { width: w, height: h, clipPreview: true });
const brightPixel = sampleBand(2);
// Shadow clipping: same palette at the other end of the histogram.
renderer.render(defaultEdits(), { width: w, height: h, clipping: 'shadows' });
const shadowPixels = [2, 3, 4, 5].map(sampleBand);
// And it has to move with the sliders, not just exist: -9 EV drives every
// channel of the clean band to black, so that band must turn white in shadow
// mode, just as it turns white at +6 EV in highlight mode.
const shadowEdits = defaultEdits();
shadowEdits.exposure = -9;
renderer.render(shadowEdits, { width: w, height: h, clipping: 'shadows' });
const shadowDarkPixel = sampleBand(2);
// Per-mask curve: a radial covering the whole frame, first with an identity
// curve and then with one that halves the output. The mask must leave the
// frame alone with the identity curve and darken it with the real one.
const maskLayer = defaultLocalLayer('radial', 0);
const maskShape = maskLayer.components[0];
maskShape.feather = 0;
maskShape.radial = { cx: 0.5, cy: 0.5, rx: 1.2, ry: 1.2 };
const darkCurve = [
{ x: 0, y: 0 },
{ x: 1, y: 0.4 },
];
const maskedEdits = defaultEdits();
maskedEdits.local = [{ ...maskLayer, curve: [{ x: 0, y: 0 }, { x: 1, y: 1 }] }];
renderer.render(maskedEdits, { width: w, height: h });
const maskIdentityPixel = sampleBand(2);
maskedEdits.local = [{ ...maskLayer, curve: darkCurve }];
renderer.render(maskedEdits, { width: w, height: h });
const maskCurvePixel = sampleBand(2);
// Mask groups: a second shape has to composite into the layer's own mask.
// Subtracting a frame-wide shape from an equally wide add shape clears the
// group, so the darkened curve must stop touching the frame; intersecting
// with the same shape keeps full coverage, so it must still darken.
const groupShape = defaultLocalComponent('radial');
groupShape.feather = 0;
groupShape.radial = { cx: 0.5, cy: 0.5, rx: 1.2, ry: 1.2 };
const groupEdits = defaultEdits();
groupEdits.local = [
{
...maskLayer,
curve: darkCurve,
components: [maskShape, { ...groupShape, mode: 'subtract' }],
},
];
renderer.render(groupEdits, { width: w, height: h });
const maskGroupSubtractPixel = sampleBand(2);
groupEdits.local = [
{
...maskLayer,
curve: darkCurve,
components: [maskShape, { ...groupShape, mode: 'intersect' }],
},
];
renderer.render(groupEdits, { width: w, height: h });
const maskGroupIntersectPixel = sampleBand(2);
// Brush masks are source-space and feather softens the rim inside the brush
// circle. The dab below has a radius of 0.08 of the frame width, so it spans
// 0.12 of the frame height; nothing outside that may be touched, even at a
// high feather, and the rim itself must be a gradient rather than a step.
const pixelAt = (fx, fy) => {
const px = new Uint8Array(4);
const py = h - 1 - Math.min(h - 1, Math.floor(fy * h));
viewGl.readPixels(Math.min(w - 1, Math.floor(fx * w)), py, 1, 1, viewGl.RGBA, viewGl.UNSIGNED_BYTE, px);
return [px[0], px[1], px[2]];
};
const dabRadiusY = 0.08 * (w / h);
const brushEdits = (feather) => {
const layer = defaultLocalLayer('brush', 0);
const shape = layer.components[0];
shape.feather = feather;
shape.brush.strokes = [{ points: [{ x: 0.25, y: 0.2 }], size: 0.08, erase: false }];
return { ...defaultEdits(), local: [{ ...layer, curve: darkCurve }] };
};
renderer.render(brushEdits(0), { width: w, height: h });
const dabHard = pixelAt(0.25, 0.2);
const dabOutsideHard = pixelAt(0.25, 0.2 + dabRadiusY * 1.15);
renderer.render(brushEdits(80), { width: w, height: h });
const dabSoft = pixelAt(0.25, 0.2);
const dabRimSoft = pixelAt(0.25, 0.2 + dabRadiusY * 0.75);
const dabOutsideSoft = pixelAt(0.25, 0.2 + dabRadiusY * 1.15);
// The develop view tints the baked mask instead of redrawing the stroke, so
// the overlay has to follow the same coverage: strong in the core, a real
// gradient at the rim, and nothing at all outside the brush circle.
renderer.render(brushEdits(80), { width: w, height: h, maskView: 0 });
const tintCore = pixelAt(0.25, 0.2);
const tintRim = pixelAt(0.25, 0.2 + dabRadiusY * 0.75);
const tintOutside = pixelAt(0.25, 0.2 + dabRadiusY * 1.15);
// Source-space alignment. Masks are baked over the whole source, so a crop
// that keeps a dab in frame but moves it on screen must move its tint and
// its local detail with it: source (0.6, 0.4) inside a quarter-frame crop
// lands at screen (0.4, 0.6), and nothing may be tinted at (0.6, 0.4).
const cropRect = {
x: 0.5,
y: 0.25,
w: 0.25,
h: 0.25,
angle: 0,
quarter: 0,
aspect: 'original',
flipH: false,
flipV: false,
};
const dabEdits = (at, size, adjust) => {
const layer = defaultLocalLayer('brush', 0);
const shape = layer.components[0];
shape.feather = 0;
shape.brush.strokes = [{ points: [at], size, erase: false }];
return {
...defaultEdits(),
local: [{ ...layer, adjust: { ...layer.adjust, ...(adjust || {}) } }],
};
};
const cropped = { ...defaultEdits(), crop: cropRect };
renderer.render(cropped, { width: w, height: h });
const cropRef = pixelAt(0.4, 0.6);
const cropRefOff = pixelAt(0.6, 0.4);
const cropDab = dabEdits({ x: 0.6, y: 0.4 }, 0.02);
cropDab.crop = cropRect;
renderer.render(cropDab, { width: w, height: h, maskView: 0 });
const cropTintOn = pixelAt(0.4, 0.6);
const cropTintOff = pixelAt(0.6, 0.4);
// Same crop and dab, but as a local detail amount instead of a tint: the
// finish pass has to read the mask through the same source coordinate.
const cropDetail = dabEdits({ x: 0.6, y: 0.4 }, 0.02, { dehaze: 100 });
cropDetail.crop = cropRect;
renderer.render(cropDetail, { width: w, height: h });
const cropDetailOn = pixelAt(0.4, 0.6);
const cropDetailOff = pixelAt(0.6, 0.4);
// Tint strength and toggle: full strength must read stronger than the default
// half, and no maskView at all must leave the photo untouched.
renderer.render(brushEdits(80), { width: w, height: h, maskView: 0, maskStrength: 1 });
const tintFull = pixelAt(0.25, 0.2);
renderer.render(brushEdits(80), { width: w, height: h });
const tintOffPixel = pixelAt(0.25, 0.2);
// Lens warp: a geometry map that magnifies the centre by 1.6 puts the dab at
// source (0.7, 0.45) at screen (0.625, 0.469); its source uv must be clear.
const lensN = 33;
const lensData = new Float32Array(lensN * lensN * 4);
for (let ly = 0; ly < lensN; ly++) {
for (let lx = 0; lx < lensN; lx++) {
const i = (ly * lensN + lx) * 4;
lensData[i] = 0.5 + ((lx + 0.5) / lensN - 0.5) * 1.6;
lensData[i + 1] = 0.5 + ((ly + 0.5) / lensN - 0.5) * 1.6;
lensData[i + 2] = 0;
lensData[i + 3] = 1;
}
}
const lensWarp = {
key: 'render-check-warp',
scale: 1,
geometry: { data: lensData, width: lensN, height: lensN },
};
renderer.render(defaultEdits(), { width: w, height: h, lens: lensWarp });
const lensRef = pixelAt(0.625, 0.469);
const lensRefOff = pixelAt(0.7, 0.469);
const lensDab = dabEdits({ x: 0.7, y: 0.45 }, 0.04);
renderer.render(lensDab, { width: w, height: h, lens: lensWarp, maskView: 0 });
const lensTintOn = pixelAt(0.625, 0.469);
const lensTintOff = pixelAt(0.7, 0.469);
pre.textContent = 'RESULT ' + JSON.stringify({
clipPixels,
clipRed: near(clipPixels[0], RED_MARK),
clipYellow: near(clipPixels[1], YELLOW_MARK),
clipClear:
!near(clipPixels[2], RED_MARK) &&
!near(clipPixels[2], YELLOW_MARK) &&
!near(clipPixels[2], [255, 255, 255]),
clipFollowsExposure: near(brightPixel, [255, 255, 255]),
brightPixel,
shadowPixels,
shadowClear:
!near(shadowPixels[0], RED_MARK) && !near(shadowPixels[0], YELLOW_MARK),
shadowRed: near(shadowPixels[1], RED_MARK),
shadowYellow: near(shadowPixels[2], YELLOW_MARK),
shadowCyan: near(shadowPixels[3], [26, 217, 255]),
shadowFollowsExposure: near(shadowDarkPixel, [255, 255, 255]),
shadowDarkPixel,
maskIdentityPixel,
maskCurvePixel,
maskIdentityFlat: near(maskIdentityPixel, [61, 71, 89]),
maskCurveDarkens: maskCurvePixel[0] < maskIdentityPixel[0] * 0.75,
maskGroupSubtractPixel,
maskGroupSubtractCleared: near(maskGroupSubtractPixel, maskIdentityPixel),
maskGroupIntersectPixel,
maskGroupIntersectDarkens: maskGroupIntersectPixel[0] < maskIdentityPixel[0] * 0.75,
dabHard,
dabOutsideHard,
dabSoft,
dabRimSoft,
dabOutsideSoft,
tintCore,
tintRim,
tintOutside,
// Orange tint: blue is the channel the overlay pushes up, so it ranks the
// coverage without depending on how dark the adjustment left the pixels.
tintFollowsMask: tintCore[2] > tintRim[2] && tintRim[2] > tintOutside[2] + 5,
tintBounded: Math.abs(tintOutside[2] - dabOutsideSoft[2]) <= 1,
cropRef,
cropRefOff,
cropTintOn,
cropTintOff,
cropDetailOn,
cropDetailOff,
lensRef,
lensRefOff,
lensTintOn,
lensTintOff,
tintFull,
tintOffPixel,
// The tint pushes red up hard on the dark mid band, so red ranks coverage.
cropTintAligned: cropTintOn[0] > cropRef[0] + 40,
cropTintBounded: Math.abs(cropTintOff[0] - cropRefOff[0]) <= 2,
// Local dehaze lifts the blue of that band, so blue marks where it landed.
cropDetailAligned: cropDetailOn[2] > cropDetailOff[2] + 10,
cropDetailBounded: Math.abs(cropDetailOff[2] - cropRefOff[2]) <= 3,
lensTintAligned: lensTintOn[0] > lensRef[0] + 40,
lensTintBounded: Math.abs(lensTintOff[0] - lensRefOff[0]) <= 2,
tintStrengthWorks: tintFull[2] > tintCore[2] + 8,
tintOffMatches: Math.abs(tintOffPixel[2] - dabSoft[2]) <= 1,
// A hard dab covers the core, and even an 80 % feather stops at the rim.
dabCoreDarkened: dabHard[0] < 140,
dabSoftCoreDarkened: dabSoft[0] < 140,
dabRimSmooth: dabRimSoft[0] > 140 && dabRimSoft[0] < 240,
dabBoundedHard: dabOutsideHard[0] > 240,
dabBoundedSoft: dabOutsideSoft[0] > 240,
flagHonouredForBitmap: !same(proxyTop, proxyNoFlipTop),
proxyTop: +proxyTop.toFixed(4),
sidecarTop: +sideTop.toFixed(4),
proxyBottom: +proxyBottom.toFixed(4),
sidecarBottom: +sideBottom.toFixed(4),
matchTop: same(proxyTop, sideTop),
matchBottom: same(proxyBottom, sideBottom),
reversed: same(proxyTop, sideBottom) && same(proxyBottom, sideTop),
});
} catch (err) {
if (!String(pre.textContent).startsWith('ERROR')) {
pre.textContent = 'ERROR ' + (err && err.message ? err.message : String(err));
}
}
</script>`;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function drive(chromeBin, url) {
const port = 9333 + Math.floor(Math.random() * 200);
const child = spawn(
chromeBin,
[
'--headless=new',
'--no-sandbox',
'--disable-gpu-sandbox',
'--use-gl=angle',
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
`--remote-debugging-port=${port}`,
`--user-data-dir=${path.join(DIR, 'profile')}`,
'about:blank',
],
{ stdio: 'ignore' },
);
try {
let target = null;
for (let i = 0; i < 120 && !target; i++) {
try {
const res = await fetch(`http://127.0.0.1:${port}/json/list`);
target = (await res.json()).find((t) => t.type === 'page') ?? null;
} catch {
/* devtools not up yet */
}
if (!target) await sleep(250);
}
if (!target) throw new Error('Chrome DevTools endpoint never came up');
const ws = new WebSocket(target.webSocketDebuggerUrl);
await new Promise((resolve, reject) => {
ws.onopen = resolve;
ws.onerror = () => reject(new Error('DevTools websocket failed'));
});
let nextId = 1;
const pending = new Map();
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.id && pending.has(message.id)) {
pending.get(message.id)(message);
pending.delete(message.id);
}
};
const send = (method, params = {}) => {
const id = nextId++;
return new Promise((resolve) => {
pending.set(id, resolve);
ws.send(JSON.stringify({ id, method, params }));
});
};
await send('Page.enable');
await send('Runtime.enable');
await send('Page.navigate', { url });
let text = '';
const deadline = Date.now() + 90000;
while (Date.now() < deadline) {
const res = await send('Runtime.evaluate', {
expression: "document.getElementById('out')?.textContent ?? ''",
returnByValue: true,
});
text = res.result?.result?.value ?? '';
if (text.includes('RESULT') || text.startsWith('ERROR')) break;
await sleep(500);
}
ws.close();
return text;
} finally {
child.kill('SIGKILL');
// Chrome writes its profile until the process is gone; give it a moment so
// the cleanup below does not race the file handles it still holds.
await sleep(500);
}
}
async function main() {
const chromeBin = await findChrome();
const { rgb8, rgb16 } = buildSource();
await mkdir(DIR, { recursive: true });
await writeFile(path.join(DIR, 'proxy.jpg'), await sharp(rgb8, { raw: { width: W, height: H, channels: 3 } })
.jpeg({ quality: 96, chromaSubsampling: '4:4:4' })
.toBuffer());
await writeFile(path.join(DIR, 'side.p16.png'), encodePng16(rgb16, W, H));
await writeFile(PAGE, PAGE_HTML);
const server = await createServer({
root: ROOT,
logLevel: 'error',
server: { host: '127.0.0.1', port: 5199, strictPort: false },
});
await server.listen();
const base = server.resolvedUrls?.local?.[0] ?? 'http://127.0.0.1:5199/';
let text = '';
try {
if (!chromeBin) {
console.log('render check SKIPPED: no Chrome/Chromium found (set CHROME_PATH to run it).');
return 0;
}
text = await drive(chromeBin, `${base.replace(/\/$/, '')}/.render-check/`);
} finally {
await server.close();
}
if (text.startsWith('ERROR')) {
console.error(`render check FAILED: ${text.slice(6)}`);
return 1;
}
const marker = text.indexOf('RESULT');
if (marker < 0) {
console.error('render check FAILED: the probe never reported a result.');
console.error(text.slice(0, 500));
return 1;
}
const result = JSON.parse(text.slice(marker + 7));
console.log(
`render check: proxy top=${result.proxyTop} bottom=${result.proxyBottom}` +
` | sidecar top=${result.sidecarTop} bottom=${result.sidecarBottom}` +
` | flip flag honoured for ImageBitmap=${result.flagHonouredForBitmap}`,
);
console.log(
`render check: clipping overlay red=${JSON.stringify(result.clipPixels[0])}` +
` yellow=${JSON.stringify(result.clipPixels[1])}` +
` clear=${JSON.stringify(result.clipPixels[2])}` +
` | at +6EV the clear band is ${JSON.stringify(result.brightPixel)}`,
);
console.log(
`render check: shadow overlay clear=${JSON.stringify(result.shadowPixels[0])}` +
` red=${JSON.stringify(result.shadowPixels[1])}` +
` yellow=${JSON.stringify(result.shadowPixels[2])}` +
` cyan=${JSON.stringify(result.shadowPixels[3])}` +
` | at -9EV the clean band is ${JSON.stringify(result.shadowDarkPixel)}`,
);
console.log(
`render check: mask curve identity=${JSON.stringify(result.maskIdentityPixel)}` +
` darkened=${JSON.stringify(result.maskCurvePixel)}`,
);
console.log(
`render check: mask group subtract=${JSON.stringify(result.maskGroupSubtractPixel)}` +
` intersect=${JSON.stringify(result.maskGroupIntersectPixel)}`,
);
if (!result.matchTop || !result.matchBottom) {
console.error(
result.reversed
? 'render check FAILED: the sidecar lands upside down against the proxy.'
: 'render check FAILED: proxy and sidecar rows do not line up.',
);
return 1;
}
if (!result.clipRed || !result.clipYellow || !result.clipClear) {
console.error(
'render check FAILED: the clipping overlay lost its channel colours ' +
`(red=${result.clipRed}, yellow=${result.clipYellow}, clear=${result.clipClear}).`,
);
return 1;
}
if (!result.shadowClear || !result.shadowRed || !result.shadowYellow || !result.shadowCyan) {
console.error(
'render check FAILED: the shadow clipping overlay lost its channel colours ' +
`(clear=${result.shadowClear}, red=${result.shadowRed}, ` +
`yellow=${result.shadowYellow}, cyan=${result.shadowCyan}).`,
);
return 1;
}
if (!result.maskIdentityFlat || !result.maskCurveDarkens) {
console.error(
'render check FAILED: the per-mask curve is not reaching the grade ' +
`(identity=${JSON.stringify(result.maskIdentityPixel)}, ` +
`curve=${JSON.stringify(result.maskCurvePixel)}).`,
);
return 1;
}
if (!result.maskGroupSubtractCleared || !result.maskGroupIntersectDarkens) {
console.error(
'render check FAILED: mask group shapes are not compositing ' +
`(subtract=${JSON.stringify(result.maskGroupSubtractPixel)}, ` +
`intersect=${JSON.stringify(result.maskGroupIntersectPixel)}).`,
);
return 1;
}
if (!result.shadowFollowsExposure) {
console.error(
'render check FAILED: the shadow clipping overlay does not follow Exposure; ' +
`at -9EV the clean band stayed ${JSON.stringify(result.shadowDarkPixel)}.`,
);
return 1;
}
if (!result.clipFollowsExposure) {
console.error(
'render check FAILED: the clipping overlay does not follow Exposure; ' +
`the unclipped band stayed ${JSON.stringify(result.brightPixel)} at +6 EV.`,
);
return 1;
}
console.log(
`render check: brush dab hard=${JSON.stringify(result.dabHard)}` +
` outsideHard=${JSON.stringify(result.dabOutsideHard)} soft=${JSON.stringify(result.dabSoft)}` +
` rimSoft=${JSON.stringify(result.dabRimSoft)} outsideSoft=${JSON.stringify(result.dabOutsideSoft)}`,
);
console.log(
`render check: mask overlay core=${JSON.stringify(result.tintCore)}` +
` rim=${JSON.stringify(result.tintRim)} outside=${JSON.stringify(result.tintOutside)}`,
);
console.log(
`render check: crop mask tint on=${JSON.stringify(result.cropTintOn)}` +
` off=${JSON.stringify(result.cropTintOff)} ref=${JSON.stringify(result.cropRef)}` +
` | local detail on=${JSON.stringify(result.cropDetailOn)}` +
` off=${JSON.stringify(result.cropDetailOff)}`,
);
console.log(
`render check: lens mask tint on=${JSON.stringify(result.lensTintOn)}` +
` off=${JSON.stringify(result.lensTintOff)} ref=${JSON.stringify(result.lensRef)}` +
` | tint strength full=${JSON.stringify(result.tintFull)}` +
` half=${JSON.stringify(result.tintCore)}`,
);
if (
!result.cropTintAligned ||
!result.cropTintBounded ||
!result.cropDetailAligned ||
!result.cropDetailBounded ||
!result.lensTintAligned ||
!result.lensTintBounded ||
!result.tintStrengthWorks ||
!result.tintOffMatches
) {
console.error(
'render check FAILED: the local mask does not stay on its source pixels ' +
'through a crop or a lens warp ' +
`(crop tint ${JSON.stringify(result.cropTintOn)}/${JSON.stringify(result.cropTintOff)}` +
` vs ${JSON.stringify(result.cropRef)}, detail ` +
`${JSON.stringify(result.cropDetailOn)}/${JSON.stringify(result.cropDetailOff)}` +
`, lens tint ${JSON.stringify(result.lensTintOn)}/${JSON.stringify(result.lensTintOff)}` +
` vs ${JSON.stringify(result.lensRef)}).`,
);
return 1;
}
if (
!result.dabCoreDarkened ||
!result.dabSoftCoreDarkened ||
!result.dabRimSmooth ||
!result.dabBoundedHard ||
!result.dabBoundedSoft ||
!result.tintFollowsMask ||
!result.tintBounded
) {
console.error(
'render check FAILED: the brush mask does not follow the brush circle ' +
`(hard=${JSON.stringify(result.dabHard)}, rim=${JSON.stringify(result.dabRimSoft)}, ` +
`outsideHard=${JSON.stringify(result.dabOutsideHard)}, ` +
`outsideSoft=${JSON.stringify(result.dabOutsideSoft)}, ` +
`tint=${JSON.stringify(result.tintCore)}/${JSON.stringify(result.tintRim)}/` +
`${JSON.stringify(result.tintOutside)}).`,
);
return 1;
}
console.log(
'render check PASSED: proxy and sidecar share a row order and the clipping overlay names the channels.',
);
return 0;
}
let code = 1;
try {
code = await main();
} catch (err) {
console.error(`render check FAILED: ${err instanceof Error ? err.message : String(err)}`);
} finally {
await rm(DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }).catch(() => {
/* a stray Chrome profile is not worth failing the check over */
});
}
process.exit(code);
+21 -4
View File
@@ -1,23 +1,40 @@
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import { promisify } from 'node:util';
import { SESSION_DAYS } from './config.mjs'; import { SESSION_DAYS } from './config.mjs';
import { sessions, users } from './db.mjs'; import { sessions, users } from './db.mjs';
const KEYLEN = 64; const KEYLEN = 64;
const scrypt = promisify(crypto.scrypt);
export function hashPassword(password) { export async function hashPassword(password) {
const salt = crypto.randomBytes(16); const salt = crypto.randomBytes(16);
const hash = crypto.scryptSync(password, salt, KEYLEN); const hash = await scrypt(password, salt, KEYLEN);
return `scrypt$${salt.toString('hex')}$${hash.toString('hex')}`; return `scrypt$${salt.toString('hex')}$${hash.toString('hex')}`;
} }
export function verifyPassword(password, stored) { export async function verifyPassword(password, stored) {
const [scheme, saltHex, hashHex] = String(stored).split('$'); const [scheme, saltHex, hashHex] = String(stored).split('$');
if (scheme !== 'scrypt' || !saltHex || !hashHex) return false; if (scheme !== 'scrypt' || !saltHex || !hashHex) return false;
const expected = Buffer.from(hashHex, 'hex'); const expected = Buffer.from(hashHex, 'hex');
const actual = crypto.scryptSync(password, Buffer.from(saltHex, 'hex'), expected.length); const actual = await scrypt(password, Buffer.from(saltHex, 'hex'), expected.length);
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual); return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
} }
/**
* A fixed hash for addresses that do not exist, so a failed login costs the
* same scrypt work as a real one and does not reveal registration by timing.
* Built synchronously once at boot; this is not on a request path.
*/
const DUMMY_HASH = (() => {
const salt = crypto.randomBytes(16);
const hash = crypto.scryptSync('luminary-timing-equalizer', salt, KEYLEN);
return `scrypt$${salt.toString('hex')}$${hash.toString('hex')}`;
})();
export async function spendPasswordCheck(password) {
await verifyPassword(password, DUMMY_HASH);
}
export function createSession(userId) { export function createSession(userId) {
const token = crypto.randomBytes(32).toString('hex'); const token = crypto.randomBytes(32).toString('hex');
const expiresAt = Date.now() + SESSION_DAYS * 24 * 60 * 60 * 1000; const expiresAt = Date.now() + SESSION_DAYS * 24 * 60 * 60 * 1000;
+10 -2
View File
@@ -11,6 +11,7 @@ import crypto from 'node:crypto';
import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs'; import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs';
import { db, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs'; import { db, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs';
import { removeAsset } from './storage.mjs'; import { removeAsset } from './storage.mjs';
import { open, seal } from './secrets.mjs';
const VERSION = 'g1'; const VERSION = 'g1';
@@ -119,7 +120,14 @@ export function bridgePhotoId(sourcePhotoId) {
} }
export function bridgeForEvent(eventId) { export function bridgeForEvent(eventId) {
return bridgeGet.get(eventId) ?? null; const row = bridgeGet.get(eventId);
if (!row) return null;
try {
return { ...row, token: open(row.token) };
} catch (err) {
console.error(`[luminary] could not decrypt the bridge token for ${eventId}: ${err.message}`);
return { ...row, token: '' };
}
} }
/** Deletes an imported event, its rows and any cached previews/thumbnails. */ /** Deletes an imported event, its rows and any cached previews/thumbnails. */
@@ -208,7 +216,7 @@ export async function importBridgeEvent({ serviceToken, sessionId, ownerId = ''
bridgeInsert.run( bridgeInsert.run(
eventId, eventId,
sessionId, sessionId,
serviceToken, seal(serviceToken),
GLENLOCH_URL, GLENLOCH_URL,
listing.event.id, listing.event.id,
returnUrl, returnUrl,
+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);
}
+14
View File
@@ -33,6 +33,13 @@ export const GLENLOCH_URL = (process.env.GLENLOCH_URL || '').replace(/\/+$/, '')
/** Shared HMAC secret for bridge tokens; must match the dashboard's value. */ /** Shared HMAC secret for bridge tokens; must match the dashboard's value. */
export const BRIDGE_SECRET = process.env.BRIDGE_SECRET || ''; export const BRIDGE_SECRET = process.env.BRIDGE_SECRET || '';
/** Optional key for encrypting saved SMTP and bridge credentials at rest. */
export const SECRET_KEY = setting('SECRET_KEY');
/** Trust X-Forwarded-For for rate limits; only behind a proxy that sets it. */
export const TRUST_PROXY = setting('TRUST_PROXY') === '1';
/** How long an imported bridge event survives without being reopened. */ /** How long an imported bridge event survives without being reopened. */
export const BRIDGE_TTL_HOURS = Number(setting('BRIDGE_TTL_HOURS', '12')); export const BRIDGE_TTL_HOURS = Number(setting('BRIDGE_TTL_HOURS', '12'));
@@ -68,6 +75,13 @@ export const SMTP_FROM = setting('SMTP_FROM', SMTP_USER);
/** Long edge used for the editable proxy of raw files. */ /** Long edge used for the editable proxy of raw files. */
export const RAW_PREVIEW_EDGE = Number(setting('RAW_EDGE', '6000')); 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; export const SESSION_DAYS = 30;
/** How many raws decode at once. One core is left for the HTTP server. */ /** How many raws decode at once. One core is left for the HTTP server. */
+663
View File
@@ -89,6 +89,18 @@ db.exec(`
CREATE INDEX IF NOT EXISTS gallery_reviews_token ON gallery_reviews(token); 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 ( CREATE TABLE IF NOT EXISTS invites (
token TEXT PRIMARY KEY, token TEXT PRIMARY KEY,
email TEXT NOT NULL DEFAULT '', email TEXT NOT NULL DEFAULT '',
@@ -114,6 +126,76 @@ db.exec(`
created_at INTEGER NOT NULL created_at INTEGER NOT NULL
); );
CREATE TABLE IF NOT EXISTS immich_albums (
event_id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL,
server_url TEXT NOT NULL,
album_id TEXT NOT NULL,
album_name TEXT NOT NULL DEFAULT '',
asset_count INTEGER NOT NULL DEFAULT 0,
kind TEXT NOT NULL DEFAULT 'import',
last_sync_at INTEGER,
created_at INTEGER NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS immich_albums_key
ON immich_albums(owner_id, server_url, album_id);
CREATE TABLE IF NOT EXISTS immich_assets (
event_id TEXT NOT NULL,
asset_id TEXT NOT NULL,
photo_id TEXT NOT NULL,
owner_id TEXT NOT NULL,
album_id TEXT NOT NULL,
checksum TEXT NOT NULL DEFAULT '',
file_name TEXT NOT NULL DEFAULT '',
imported_at INTEGER NOT NULL,
PRIMARY KEY (event_id, asset_id)
);
CREATE INDEX IF NOT EXISTS immich_assets_photo ON immich_assets(photo_id);
CREATE TABLE IF NOT EXISTS immich_settings (
owner_id TEXT PRIMARY KEY,
server_url TEXT NOT NULL DEFAULT '',
api_key TEXT NOT NULL DEFAULT '',
enabled INTEGER NOT NULL DEFAULT 0,
auto_sync INTEGER NOT NULL DEFAULT 0,
sync_minutes INTEGER NOT NULL DEFAULT 60,
trash_original INTEGER NOT NULL DEFAULT 0,
sync_metadata INTEGER NOT NULL DEFAULT 1,
last_sync_at INTEGER,
last_error TEXT,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS immich_pushes (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL,
photo_id TEXT NOT NULL,
source_asset_id TEXT NOT NULL,
new_asset_id TEXT,
checksum TEXT NOT NULL,
edits_hash TEXT NOT NULL DEFAULT '',
state TEXT NOT NULL,
trashed_source INTEGER NOT NULL DEFAULT 0,
error TEXT,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS immich_pushes_photo ON immich_pushes(photo_id, checksum);
CREATE TABLE IF NOT EXISTS immich_meta (
photo_id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL,
asset_id TEXT NOT NULL,
local_fingerprint TEXT NOT NULL DEFAULT '',
remote_fingerprint TEXT NOT NULL DEFAULT '',
remote_updated_at INTEGER,
last_synced_at INTEGER,
last_error TEXT
);
CREATE TABLE IF NOT EXISTS user_quota ( CREATE TABLE IF NOT EXISTS user_quota (
user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
bytes_limit INTEGER NOT NULL DEFAULT (100 * 1024 * 1024 * 1024), bytes_limit INTEGER NOT NULL DEFAULT (100 * 1024 * 1024 * 1024),
@@ -122,6 +204,25 @@ db.exec(`
prune_notified_at INTEGER, prune_notified_at INTEGER,
last_quota_email_at INTEGER last_quota_email_at INTEGER
); );
/* Lens calibrations measured by the team, alongside the bundled database. */
CREATE TABLE IF NOT EXISTS lens_profiles (
id TEXT PRIMARY KEY,
maker TEXT NOT NULL,
model TEXT NOT NULL,
mount TEXT NOT NULL DEFAULT '',
crop REAL NOT NULL DEFAULT 1,
aspect REAL NOT NULL DEFAULT 0,
center_x REAL NOT NULL DEFAULT 0,
center_y REAL NOT NULL DEFAULT 0,
notes TEXT NOT NULL DEFAULT '',
data TEXT NOT NULL,
created_by TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS lens_profiles_updated ON lens_profiles(updated_at);
`); `);
/* Databases created before account disabling existed get the column in place. */ /* Databases created before account disabling existed get the column in place. */
@@ -162,6 +263,74 @@ if (!eventColumns.includes('share_token')) {
} }
db.exec('CREATE UNIQUE INDEX IF NOT EXISTS events_share_token ON events(share_token)'); db.exec('CREATE UNIQUE INDEX IF NOT EXISTS events_share_token ON events(share_token)');
/* Metadata round-tripping arrived after the first Immich release. */
const immichSettingsColumns = db.prepare('PRAGMA table_info(immich_settings)').all().map((c) => c.name);
if (!immichSettingsColumns.includes('sync_metadata')) {
db.exec('ALTER TABLE immich_settings ADD COLUMN sync_metadata INTEGER NOT NULL DEFAULT 1');
}
/* Manual pushes remember which edit version reached Immich. */
const immichPushColumns = db.prepare('PRAGMA table_info(immich_pushes)').all().map((c) => c.name);
if (!immichPushColumns.includes('edits_hash')) {
db.exec("ALTER TABLE immich_pushes ADD COLUMN edits_hash TEXT NOT NULL DEFAULT ''");
}
/* Galleries created from an event are destinations, not import sources. */
const immichAlbumColumns = db.prepare('PRAGMA table_info(immich_albums)').all().map((c) => c.name);
if (!immichAlbumColumns.includes('kind')) {
db.exec("ALTER TABLE immich_albums ADD COLUMN kind TEXT NOT NULL DEFAULT 'import'");
}
/**
* Applying a lens profile used to enable its vignetting correction, and that
* flat-field gain over-exposed the edges. The correction is opt-in now, so the
* flag older edits stored is cleared once, here, before anything reads the
* catalogue. Matching on the JSON text keeps the scan to the few rows that ever
* carried it, and the rows it rewrites no longer match, so it is idempotent.
*/
const legacyVignetting = db
.prepare(`SELECT id, data FROM photos WHERE instr(data, '"vignetting":true') > 0`)
.all();
if (legacyVignetting.length) {
const updateData = db.prepare('UPDATE photos SET data = ?, updated_at = ? WHERE id = ?');
const clear = (edits) => {
const lens = edits && edits.lens;
if (!lens || !lens.corrections || lens.corrections.vignetting !== true) return edits;
return { ...edits, lens: { ...lens, corrections: { ...lens.corrections, vignetting: false } } };
};
let cleared = 0;
for (const row of legacyVignetting) {
let record;
try {
record = JSON.parse(row.data);
} catch {
continue;
}
if (!record || typeof record !== 'object') continue;
let changed = false;
const strip = (edits) => {
const next = clear(edits);
if (next !== edits) changed = true;
return next;
};
record.edits = strip(record.edits);
if (Array.isArray(record.snapshots)) {
record.snapshots = record.snapshots.map((snap) =>
snap && snap.edits ? { ...snap, edits: strip(snap.edits) } : snap,
);
}
if (Array.isArray(record.history)) {
record.history = record.history.map((entry) =>
entry && entry.edits ? { ...entry, edits: strip(entry.edits) } : entry,
);
}
if (!changed) continue;
updateData.run(JSON.stringify(record), Date.now(), row.id);
cleared += 1;
}
if (cleared) console.log(`lens vignetting: cleared the stored corner gain on ${cleared} photo(s)`);
}
const q = { const q = {
upsertEvent: db.prepare(` upsertEvent: db.prepare(`
INSERT INTO events (id, owner_id, sort_index, created_at, data) VALUES (?, ?, ?, ?, ?) INSERT INTO events (id, owner_id, sort_index, created_at, data) VALUES (?, ?, ?, ?, ?)
@@ -255,6 +424,115 @@ const q = {
photo: db.prepare('SELECT data FROM photos WHERE id = ?'), photo: db.prepare('SELECT data FROM photos WHERE id = ?'),
photoCount: db.prepare('SELECT COUNT(*) AS n FROM photos'), photoCount: db.prepare('SELECT COUNT(*) AS n FROM photos'),
event: db.prepare('SELECT data FROM events WHERE id = ?'),
immichAlbum: db.prepare(
'SELECT * FROM immich_albums WHERE owner_id = ? AND server_url = ? AND album_id = ?',
),
immichAlbumForEvent: db.prepare('SELECT * FROM immich_albums WHERE event_id = ?'),
immichAlbumByAlbum: db.prepare(
'SELECT * FROM immich_albums WHERE owner_id = ? AND album_id = ? LIMIT 1',
),
immichAlbumsByOwner: db.prepare(
'SELECT * FROM immich_albums WHERE owner_id = ? ORDER BY last_sync_at DESC, created_at DESC',
),
upsertImmichAlbum: db.prepare(`
INSERT INTO immich_albums (event_id, owner_id, server_url, album_id, album_name, asset_count, kind, last_sync_at, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(event_id) DO UPDATE SET
server_url = excluded.server_url,
album_id = excluded.album_id,
album_name = excluded.album_name,
asset_count = excluded.asset_count,
kind = excluded.kind,
last_sync_at = excluded.last_sync_at
`),
deleteImmichAlbum: db.prepare('DELETE FROM immich_albums WHERE event_id = ?'),
immichAssetsByEvent: db.prepare('SELECT * FROM immich_assets WHERE event_id = ?'),
upsertImmichAsset: db.prepare(`
INSERT INTO immich_assets (event_id, asset_id, photo_id, owner_id, album_id, checksum, file_name, imported_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(event_id, asset_id) DO UPDATE SET
photo_id = excluded.photo_id,
checksum = excluded.checksum,
file_name = excluded.file_name,
imported_at = excluded.imported_at
`),
deleteImmichAsset: db.prepare('DELETE FROM immich_assets WHERE event_id = ? AND asset_id = ?'),
deleteImmichAssetsForPhoto: db.prepare('DELETE FROM immich_assets WHERE photo_id = ?'),
immichAssetForPhoto: db.prepare('SELECT * FROM immich_assets WHERE photo_id = ? LIMIT 1'),
immichSettings: db.prepare('SELECT * FROM immich_settings WHERE owner_id = ?'),
allImmichSettings: db.prepare('SELECT * FROM immich_settings'),
upsertImmichSettings: db.prepare(`
INSERT INTO immich_settings (owner_id, server_url, api_key, enabled, auto_sync, sync_minutes, trash_original, sync_metadata, last_sync_at, last_error, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(owner_id) DO UPDATE SET
server_url = excluded.server_url,
api_key = excluded.api_key,
enabled = excluded.enabled,
auto_sync = excluded.auto_sync,
sync_minutes = excluded.sync_minutes,
trash_original = excluded.trash_original,
sync_metadata = excluded.sync_metadata,
last_sync_at = excluded.last_sync_at,
last_error = excluded.last_error
`),
deleteImmichSettings: db.prepare('DELETE FROM immich_settings WHERE owner_id = ?'),
setImmichSyncState: db.prepare(
'UPDATE immich_settings SET last_sync_at = ?, last_error = ? WHERE owner_id = ?',
),
immichPush: db.prepare(
'SELECT * FROM immich_pushes WHERE photo_id = ? AND checksum = ? ORDER BY created_at DESC LIMIT 1',
),
immichPushedForPhoto: db.prepare(
"SELECT * FROM immich_pushes WHERE photo_id = ? AND state = 'done' AND new_asset_id IS NOT NULL ORDER BY created_at DESC LIMIT 1",
),
immichPhotoIdsByEvent: db.prepare(
'SELECT id FROM photos WHERE event_id = ? AND owner_id = ? ORDER BY sort_index ASC, updated_at ASC',
),
immichPendingByEvent: db.prepare(`
SELECT p.data FROM photos p
WHERE p.event_id = ? AND p.owner_id = ?
AND NOT EXISTS (SELECT 1 FROM immich_assets a WHERE a.photo_id = p.id)
AND NOT EXISTS (
SELECT 1 FROM immich_pushes u
WHERE u.photo_id = p.id AND u.state = 'done' AND u.new_asset_id IS NOT NULL
)
ORDER BY p.sort_index ASC, p.updated_at ASC
`),
upsertImmichPush: db.prepare(`
INSERT INTO immich_pushes (id, owner_id, photo_id, source_asset_id, new_asset_id, checksum, edits_hash, state, trashed_source, error, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
new_asset_id = excluded.new_asset_id,
edits_hash = excluded.edits_hash,
state = excluded.state,
trashed_source = excluded.trashed_source,
error = excluded.error
`),
deleteImmichPushesForPhoto: db.prepare('DELETE FROM immich_pushes WHERE photo_id = ?'),
immichMeta: db.prepare('SELECT * FROM immich_meta WHERE photo_id = ?'),
upsertImmichMeta: db.prepare(`
INSERT INTO immich_meta (photo_id, owner_id, asset_id, local_fingerprint, remote_fingerprint, remote_updated_at, last_synced_at, last_error)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(photo_id) DO UPDATE SET
owner_id = excluded.owner_id,
asset_id = excluded.asset_id,
local_fingerprint = excluded.local_fingerprint,
remote_fingerprint = excluded.remote_fingerprint,
remote_updated_at = excluded.remote_updated_at,
last_synced_at = excluded.last_synced_at,
last_error = excluded.last_error
`),
deleteImmichMeta: db.prepare('DELETE FROM immich_meta WHERE photo_id = ?'),
immichPushAssets: db.prepare(
"SELECT DISTINCT new_asset_id FROM immich_pushes WHERE photo_id = ? AND state = 'done' AND new_asset_id IS NOT NULL",
),
patchPhotoMeta: db.prepare(`
UPDATE photos
SET data = json_set(data, '$.rating', ?, '$.flag', ?, '$.keywords', json(?)), updated_at = ?
WHERE id = ?
`),
findUserByEmail: db.prepare('SELECT * FROM users WHERE email = ?'), findUserByEmail: db.prepare('SELECT * FROM users WHERE email = ?'),
insertUser: db.prepare( insertUser: db.prepare(
'INSERT INTO users (id, email, name, pass_hash, role, created_at) VALUES (?, ?, ?, ?, ?, ?)', 'INSERT INTO users (id, email, name, pass_hash, role, created_at) VALUES (?, ?, ?, ?, ?, ?)',
@@ -335,6 +613,28 @@ const q = {
kvSet: db.prepare( kvSet: db.prepare(
'INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value', 'INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
), ),
allLensProfiles: db.prepare(
'SELECT * FROM lens_profiles ORDER BY maker COLLATE NOCASE ASC, model COLLATE NOCASE ASC',
),
lensProfile: db.prepare('SELECT * FROM lens_profiles WHERE id = ?'),
upsertLensProfile: db.prepare(`
INSERT INTO lens_profiles
(id, maker, model, mount, crop, aspect, center_x, center_y, notes, data, created_by, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
maker = excluded.maker,
model = excluded.model,
mount = excluded.mount,
crop = excluded.crop,
aspect = excluded.aspect,
center_x = excluded.center_x,
center_y = excluded.center_y,
notes = excluded.notes,
data = excluded.data,
updated_at = excluded.updated_at
`),
deleteLensProfile: db.prepare('DELETE FROM lens_profiles WHERE id = ?'),
}; };
function parse(json) { function parse(json) {
@@ -361,6 +661,8 @@ export function saveEvent(record, sortIndex = 0, ownerId = '') {
export function removeEvent(id) { export function removeEvent(id) {
q.deleteEvent.run(id); q.deleteEvent.run(id);
// An album link must not outlive the event it points at.
q.deleteImmichAlbum.run(id);
} }
export function shareTokenFor(id) { export function shareTokenFor(id) {
@@ -408,6 +710,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) { export function galleryPick(token, photoId, clientId, clientName, picked) {
if (!picked) { if (!picked) {
q.deletePick.run(token, photoId, clientId); q.deletePick.run(token, photoId, clientId);
@@ -479,6 +846,250 @@ export function getPhoto(id) {
return row ? parse(row.data) : null; return row ? parse(row.data) : null;
} }
export function getEvent(id) {
const row = q.event.get(id);
return row ? parse(row.data) : null;
}
/** The Luminary event already linked to an Immich album, if any. */
export function immichAlbumFor(ownerId, serverUrl, albumId) {
const row = q.immichAlbum.get(ownerId, serverUrl, albumId);
return row ? albumLinkFromRow(row) : null;
}
export function immichAlbumLinks(ownerId) {
return q.immichAlbumsByOwner.all(ownerId).map(albumLinkFromRow);
}
export function immichAlbumForEvent(eventId) {
const row = q.immichAlbumForEvent.get(eventId);
return row ? albumLinkFromRow(row) : null;
}
export function immichAlbumByAlbum(ownerId, albumId) {
const row = q.immichAlbumByAlbum.get(ownerId, albumId);
return row ? albumLinkFromRow(row) : null;
}
function albumLinkFromRow(row) {
return {
eventId: row.event_id,
ownerId: row.owner_id,
serverUrl: row.server_url,
albumId: row.album_id,
albumName: row.album_name,
assetCount: Number(row.asset_count ?? 0),
kind: row.kind ?? 'import',
lastSyncAt: row.last_sync_at ?? null,
createdAt: row.created_at,
};
}
export function saveImmichAlbum(link) {
q.upsertImmichAlbum.run(
link.eventId,
link.ownerId,
link.serverUrl,
link.albumId,
link.albumName ?? '',
Number(link.assetCount ?? 0),
link.kind === 'gallery' ? 'gallery' : 'import',
link.lastSyncAt ?? Date.now(),
link.createdAt ?? Date.now(),
);
}
export function immichAssetsForEvent(eventId) {
return q.immichAssetsByEvent.all(eventId).map((row) => ({
eventId: row.event_id,
assetId: row.asset_id,
photoId: row.photo_id,
ownerId: row.owner_id,
albumId: row.album_id,
checksum: row.checksum,
fileName: row.file_name,
importedAt: row.imported_at,
}));
}
export function saveImmichAsset(asset) {
q.upsertImmichAsset.run(
asset.eventId,
asset.assetId,
asset.photoId,
asset.ownerId,
asset.albumId,
asset.checksum ?? '',
asset.fileName ?? '',
asset.importedAt ?? Date.now(),
);
}
export function removeImmichAsset(eventId, assetId) {
q.deleteImmichAsset.run(eventId, assetId);
}
/** The Immich source row for a photo, used when sending an edit back. */
export function immichAssetForPhoto(photoId) {
const row = q.immichAssetForPhoto.get(photoId);
if (!row) return null;
return {
eventId: row.event_id,
assetId: row.asset_id,
photoId: row.photo_id,
ownerId: row.owner_id,
albumId: row.album_id,
checksum: row.checksum,
fileName: row.file_name,
importedAt: row.imported_at,
};
}
function immichSettingsFromRow(row) {
if (!row) return null;
return {
ownerId: row.owner_id,
serverUrl: row.server_url,
apiKey: row.api_key,
enabled: Boolean(row.enabled),
autoSync: Boolean(row.auto_sync),
syncMinutes: Number(row.sync_minutes ?? 60),
trashOriginal: Boolean(row.trash_original),
syncMetadata: Boolean(row.sync_metadata ?? 1),
lastSyncAt: row.last_sync_at ?? null,
lastError: row.last_error ?? null,
createdAt: row.created_at,
};
}
export function immichSettingsFor(ownerId) {
return immichSettingsFromRow(q.immichSettings.get(ownerId));
}
export function allImmichSettings() {
return q.allImmichSettings.all().map(immichSettingsFromRow);
}
export function saveImmichSettingsRecord(record) {
q.upsertImmichSettings.run(
record.ownerId,
record.serverUrl ?? '',
record.apiKey ?? '',
record.enabled ? 1 : 0,
record.autoSync ? 1 : 0,
Math.max(15, Math.min(1440, Number(record.syncMinutes) || 60)),
record.trashOriginal ? 1 : 0,
record.syncMetadata === false ? 0 : 1,
record.lastSyncAt ?? null,
record.lastError ?? null,
record.createdAt ?? Date.now(),
);
}
export function deleteImmichSettingsRecord(ownerId) {
q.deleteImmichSettings.run(ownerId);
}
export function setImmichSyncState(ownerId, lastSyncAt, lastError) {
q.setImmichSyncState.run(lastSyncAt ?? null, lastError ?? null, ownerId);
}
export function immichPushFor(photoId, checksum) {
const row = q.immichPush.get(photoId, checksum);
if (!row) return null;
return {
id: row.id,
ownerId: row.owner_id,
photoId: row.photo_id,
sourceAssetId: row.source_asset_id,
newAssetId: row.new_asset_id ?? null,
checksum: row.checksum,
state: row.state,
trashedSource: Boolean(row.trashed_source),
error: row.error ?? null,
createdAt: row.created_at,
};
}
export function saveImmichPush(record) {
q.upsertImmichPush.run(
record.id,
record.ownerId,
record.photoId,
record.sourceAssetId,
record.newAssetId ?? null,
record.checksum,
record.editsHash ?? '',
record.state,
record.trashedSource ? 1 : 0,
record.error ?? null,
record.createdAt ?? Date.now(),
);
}
export function immichMetaFor(photoId) {
const row = q.immichMeta.get(photoId);
if (!row) return null;
return {
photoId: row.photo_id,
ownerId: row.owner_id,
assetId: row.asset_id,
localFingerprint: row.local_fingerprint,
remoteFingerprint: row.remote_fingerprint,
remoteUpdatedAt: row.remote_updated_at ?? null,
lastSyncedAt: row.last_synced_at ?? null,
lastError: row.last_error ?? null,
};
}
export function saveImmichMeta(record) {
q.upsertImmichMeta.run(
record.photoId,
record.ownerId,
record.assetId,
record.localFingerprint,
record.remoteFingerprint,
record.remoteUpdatedAt ?? null,
record.lastSyncedAt ?? Date.now(),
record.lastError ?? null,
);
}
export function immichPushAssetsForPhoto(photoId) {
return q.immichPushAssets.all(photoId).map((row) => row.new_asset_id);
}
/** The first successful upload for a photo, whatever checksum produced it. */
export function immichPushDoneForPhoto(photoId) {
return q.immichPushedForPhoto.get(photoId) ?? null;
}
/** Every photo id in an event, in the order it is shown. */
export function photoIdsForEvent(eventId, ownerId) {
return q.immichPhotoIdsByEvent.all(eventId, ownerId).map((row) => row.id);
}
/** Live photo ids in an event that still need to reach its Immich gallery. */
export function immichPendingForEvent(eventId, ownerId) {
return q.immichPendingByEvent
.all(eventId, ownerId)
.map((row) => parse(row.data))
.filter((photo) => photo && !photo.deletedAt)
.map((photo) => photo.id);
}
/** Updates only metadata fields in the stored record, preserving sort order. */
export function patchPhotoMeta(photoId, patch, updatedAt = Date.now()) {
q.patchPhotoMeta.run(
Math.max(0, Math.min(5, Number(patch.rating) || 0)),
patch.flag ?? 'none',
JSON.stringify(Array.isArray(patch.keywords) ? patch.keywords : []),
updatedAt,
photoId,
);
return getPhoto(photoId);
}
export function photoOwner(id) { export function photoOwner(id) {
return q.photoOwner.get(id)?.owner_id ?? null; return q.photoOwner.get(id)?.owner_id ?? null;
} }
@@ -501,6 +1112,9 @@ export function removePhoto(id) {
q.deletePicksForPhoto.run(id); q.deletePicksForPhoto.run(id);
q.deleteCommentsForPhoto.run(id); q.deleteCommentsForPhoto.run(id);
q.deleteReviewsForPhoto.run(id); q.deleteReviewsForPhoto.run(id);
q.deleteImmichAssetsForPhoto.run(id);
q.deleteImmichPushesForPhoto.run(id);
q.deleteImmichMeta.run(id);
} }
export function countPhotos() { export function countPhotos() {
@@ -590,3 +1204,52 @@ export const kv = {
}, },
set: (key, value) => q.kvSet.run(key, JSON.stringify(value)), set: (key, value) => q.kvSet.run(key, JSON.stringify(value)),
}; };
function lensProfileFromRow(row) {
const data = parse(row.data) ?? {};
return {
id: row.id,
maker: row.maker,
model: row.model,
mount: row.mount,
crop: Number(row.crop),
aspect: Number(row.aspect),
centerX: Number(row.center_x),
centerY: Number(row.center_y),
notes: row.notes,
d: Array.isArray(data.d) ? data.d : [],
t: Array.isArray(data.t) ? data.t : [],
v: Array.isArray(data.v) ? data.v : [],
createdBy: row.created_by,
createdAt: row.created_at,
updatedAt: row.updated_at,
};
}
/** Team-measured calibrations, shared by every signed-in member. */
export const lensProfiles = {
list: () => q.allLensProfiles.all().map(lensProfileFromRow),
get: (id) => {
const row = q.lensProfile.get(String(id));
return row ? lensProfileFromRow(row) : null;
},
save: (record) => {
q.upsertLensProfile.run(
record.id,
record.maker,
record.model,
record.mount ?? '',
Number(record.crop ?? 1),
Number(record.aspect ?? 0),
Number(record.centerX ?? 0),
Number(record.centerY ?? 0),
record.notes ?? '',
JSON.stringify({ d: record.d ?? [], t: record.t ?? [], v: record.v ?? [] }),
record.createdBy ?? '',
record.createdAt ?? Date.now(),
record.updatedAt ?? Date.now(),
);
return lensProfiles.get(record.id);
},
remove: (id) => q.deleteLensProfile.run(String(id)).changes > 0,
};
+150 -1
View File
@@ -68,7 +68,156 @@ 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)),
]);
}
/** The camera matrix carried in a 16-bit sidecar's `rgbCam` tEXt chunk. */
export function png16Matrix(png) {
const needle = Buffer.from('rgbCam\0', 'latin1');
const at = png.indexOf(needle);
if (at < 0) return null;
const start = at + needle.length;
// The text runs to the end of the tEXt chunk, and the chunk's CRC is binary
// and may contain a NUL. Stop at the first byte that cannot be part of the
// comma-separated number list instead of searching for a terminator.
let end = start;
while (end < png.length) {
const code = png[end];
const numeric =
(code >= 0x30 && code <= 0x39) || // 0-9
code === 0x2e || // .
code === 0x2c || // ,
code === 0x2d || // -
code === 0x2b || // +
code === 0x65 || // e
code === 0x45; // E
if (!numeric) break;
end++;
}
const values = png.toString('latin1', start, end).split(',').map(Number);
return values.length === 9 && values.every(Number.isFinite) ? values : null;
}
/**
* A camera-native grid thumbnail, resized from the 16-bit sidecar with sharp's
* 16-bit path. The grid normally renders the sRGB JPEG, whose body matrix is
* already baked in; this gives the client camera samples small enough to fetch
* per tile, so a per-photo DCP profile shows everywhere the photo does. The
* `rgbCam` tag is rewritten so the client still knows how to convert them.
*/
export async function cameraThumb16(png16, width, height, matrix = null) {
const sharp = await loadSharp();
if (!sharp || width < 1 || height < 1) return null;
try {
const { data, info } = await sharp(png16)
.resize({ width, height, fit: 'fill' })
.raw({ depth: 'ushort' })
.toBuffer({ resolveWithObject: true });
if (info.channels !== 3 || info.depth !== 'ushort') return null;
// Copy through a fresh buffer: a raw output offset is not guaranteed to be
// 16-bit aligned, and Uint16Array refuses an odd byteOffset.
const samples = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
return encodePng16(
new Uint16Array(samples),
info.width,
info.height,
matrix ?? png16Matrix(png16),
);
} catch {
return null;
}
}
export async function encodeRgb(rgb, width, height, quality = 92, maxEdge = 0) { export async function encodeRgb(rgb, width, height, quality = 92, maxEdge = 0) {
const sharp = await loadSharp(); const sharp = await loadSharp();
if (!sharp) { if (!sharp) {
+95
View File
@@ -0,0 +1,95 @@
import { describe, expect, it } from 'vitest';
import { cameraThumb16, encodePng16, png16Matrix, resizeRgb16 } from './imaging.mjs';
/** A sample camera-to-sRGB matrix, in the shape a DCP derivation produces. */
const MATRIX = [
1.66943598, -0.4847292, -0.18470675, -0.00096075, 1.25268972, -0.25172901, 0.04713935,
-0.30006605, 1.25292671,
];
/** Flat 16-bit RGB samples, row major. */
function flat16(width, height, rgb) {
const out = new Uint16Array(width * height * 3);
for (let i = 0; i < out.length; i += 3) {
out[i] = rgb[0];
out[i + 1] = rgb[1];
out[i + 2] = rgb[2];
}
return out;
}
describe('png16Matrix', () => {
it('reads the nine numbers back out of the tEXt chunk', () => {
const png = encodePng16(flat16(2, 1, [1000, 2000, 3000]), 2, 1, MATRIX);
const parsed = png16Matrix(png);
expect(parsed).not.toBeNull();
expect(parsed).toHaveLength(9);
parsed.forEach((value, index) => expect(value).toBeCloseTo(MATRIX[index], 8));
});
it('returns null when the tag is absent or short', () => {
expect(png16Matrix(encodePng16(flat16(1, 1, [0, 0, 0]), 1, 1))).toBeNull();
const short = Buffer.concat([Buffer.from('rgbCam\0', 'latin1'), Buffer.from('1,2,3,4')]);
expect(png16Matrix(short)).toBeNull();
});
it('stops at the end of the tag instead of reading the chunk CRC', () => {
// The first parser scanned for the next NUL, so a CRC with no zero byte ran
// into the following chunk header and every matrix came back as NaN.
const text = `rgbCam\0${MATRIX.map((value) => value.toFixed(8)).join(',')}`;
const png = Buffer.concat([
Buffer.from(text, 'latin1'),
Buffer.from([0x31, 0x32, 0x00, 0x33]),
]);
const parsed = png16Matrix(png);
expect(parsed).toHaveLength(9);
parsed.forEach((value, index) => expect(value).toBeCloseTo(MATRIX[index], 8));
});
});
describe('resizeRgb16', () => {
it('box-averages samples when shrinking', () => {
const source = new Uint16Array([
1000, 1000, 1000, 1000, 1000, 1000, 3000, 3000, 3000, 3000, 3000, 3000,
]);
expect(Array.from(resizeRgb16(source, 4, 1, 2, 1))).toEqual([
1000, 1000, 1000, 3000, 3000, 3000,
]);
});
it('leaves an already-sized image untouched', () => {
const source = new Uint16Array([1, 2, 3, 4, 5, 6]);
expect(resizeRgb16(source, 2, 1, 2, 1)).toBe(source);
});
});
describe('cameraThumb16', () => {
it('writes a 16-bit RGB thumbnail at the requested grid size', async () => {
const source = encodePng16(flat16(4, 2, [2000, 4000, 6000]), 4, 2, MATRIX);
const out = await cameraThumb16(source, 3, 2);
expect(out).not.toBeNull();
// PNG signature, then IHDR: length at 8, type at 12, data from 16.
expect(out.readUInt32BE(16)).toBe(3);
expect(out.readUInt32BE(20)).toBe(2);
expect(out[24]).toBe(16); // bit depth
expect(out[25]).toBe(2); // colour type RGB
});
it('keeps the camera matrix so the client can convert the samples', async () => {
const source = encodePng16(flat16(4, 2, [1000, 2000, 3000]), 4, 2, MATRIX);
const out = await cameraThumb16(source, 2, 1);
const parsed = png16Matrix(out);
expect(parsed).toHaveLength(9);
parsed.forEach((value, index) => expect(value).toBeCloseTo(MATRIX[index], 8));
});
it('falls back to the matrix stored in the source sidecar', async () => {
const source = encodePng16(flat16(2, 2, [500, 600, 700]), 2, 2, MATRIX);
const out = await cameraThumb16(source, 1, 1);
expect(png16Matrix(out)).toHaveLength(9);
});
it('declines input sharp cannot decode', async () => {
expect(await cameraThumb16(Buffer.alloc(64), 2, 2)).toBeNull();
});
});
+1540
View File
File diff suppressed because it is too large Load Diff
+1194 -50
View File
File diff suppressed because it is too large Load Diff
+138
View File
@@ -0,0 +1,138 @@
/**
* Validation for team-measured lens calibrations.
*
* A profile carries the same sample rows the bundled Lensfun database uses, so
* the correction engine can read both without a second code path:
*
* d: [focal, model, a, b, c, realFocal] distortion
* t: [focal, model, br, cr, vr, bb, cb, vb] lateral chromatic aberration
* v: [focal, aperture, distance, k1, k2, k3] vignetting
*
* Coefficients are entered as measured: the engine rescales them by focal and
* sensor size exactly as it does for the bundled data.
*/
const MAX_DISTORTION = 60;
const MAX_TCA = 60;
const MAX_VIGNETTING = 120;
const MAX_COEFFICIENT = 100;
const DISTORTION_MODELS = [0, 1, 2]; // poly3, poly5, ptlens
const TCA_MODELS = [0, 1]; // poly3, linear
const finite = (value) => typeof value === 'number' && Number.isFinite(value);
const clampText = (value, max) =>
typeof value === 'string' ? value.trim().replace(/\s+/g, ' ').slice(0, max) : '';
function row(values, count) {
if (!Array.isArray(values) || values.length !== count) return null;
const numbers = values.map((value) => (typeof value === 'number' ? value : Number(value)));
return numbers.every(finite) ? numbers : null;
}
function distortionRows(input) {
if (input === undefined) return { rows: [] };
if (!Array.isArray(input)) return { error: 'Distortion samples must be a list' };
if (input.length > MAX_DISTORTION) return { error: `At most ${MAX_DISTORTION} distortion samples` };
const rows = [];
for (const entry of input) {
const values = row(entry, 6);
if (!values) return { error: 'Each distortion sample needs 6 numbers' };
const [focal, model, a, b, c, realFocal] = values;
if (!(focal > 0)) return { error: 'Distortion samples need a focal length above zero' };
if (!DISTORTION_MODELS.includes(model)) return { error: 'Unknown distortion model' };
if ([a, b, c].some((value) => Math.abs(value) > MAX_COEFFICIENT)) {
return { error: 'Distortion coefficients look out of range' };
}
if (realFocal < 0 || realFocal > 2000) return { error: 'Real focal length looks out of range' };
rows.push([focal, model, a, b, c, realFocal]);
}
return { rows };
}
function tcaRows(input) {
if (input === undefined) return { rows: [] };
if (!Array.isArray(input)) return { error: 'Chromatic aberration samples must be a list' };
if (input.length > MAX_TCA) return { error: `At most ${MAX_TCA} chromatic aberration samples` };
const rows = [];
for (const entry of input) {
const values = row(entry, 8);
if (!values) return { error: 'Each chromatic aberration sample needs 8 numbers' };
const [focal, model] = values;
if (!(focal > 0)) return { error: 'Chromatic aberration samples need a focal length above zero' };
if (!TCA_MODELS.includes(model)) return { error: 'Unknown chromatic aberration model' };
if (values.some((value) => Math.abs(value) > MAX_COEFFICIENT)) {
return { error: 'Chromatic aberration coefficients look out of range' };
}
rows.push(values);
}
return { rows };
}
function vignettingRows(input) {
if (input === undefined) return { rows: [] };
if (!Array.isArray(input)) return { error: 'Vignetting samples must be a list' };
if (input.length > MAX_VIGNETTING) return { error: `At most ${MAX_VIGNETTING} vignetting samples` };
const rows = [];
for (const entry of input) {
const values = row(entry, 6);
if (!values) return { error: 'Each vignetting sample needs 6 numbers' };
const [focal, aperture, distance, k1, k2, k3] = values;
if (!(focal > 0)) return { error: 'Vignetting samples need a focal length above zero' };
if (!(aperture > 0)) return { error: 'Vignetting samples need an aperture above zero' };
if (!(distance > 0)) return { error: 'Vignetting samples need a focus distance above zero' };
if ([k1, k2, k3].some((value) => Math.abs(value) > MAX_COEFFICIENT)) {
return { error: 'Vignetting coefficients look out of range' };
}
rows.push(values);
}
return { rows };
}
/** Returns `{ value }` for a valid body, or `{ error }` describing the first problem. */
export function parseCalibration(body) {
if (!body || typeof body !== 'object') return { error: 'Expected a lens profile' };
const maker = clampText(body.maker, 80);
const model = clampText(body.model, 120);
if (!maker) return { error: 'Lens maker is required' };
if (!model) return { error: 'Lens model is required' };
const crop = Number(body.crop);
if (!(crop >= 0.5 && crop <= 3)) return { error: 'Crop factor must be between 0.5 and 3' };
const aspect = body.aspect === undefined || body.aspect === '' ? 0 : Number(body.aspect);
if (!(aspect >= 0 && aspect <= 4)) return { error: 'Aspect ratio must be between 0 and 4' };
const centerX = body.centerX === undefined || body.centerX === '' ? 0 : Number(body.centerX);
const centerY = body.centerY === undefined || body.centerY === '' ? 0 : Number(body.centerY);
if (Math.abs(centerX) > 0.5 || Math.abs(centerY) > 0.5) {
return { error: 'Lens centre offset must be between -0.5 and 0.5' };
}
const distortion = distortionRows(body.d);
if (distortion.error) return { error: distortion.error };
const tca = tcaRows(body.t);
if (tca.error) return { error: tca.error };
const vignetting = vignettingRows(body.v);
if (vignetting.error) return { error: vignetting.error };
if (!distortion.rows.length && !tca.rows.length && !vignetting.rows.length) {
return { error: 'Add at least one distortion, chromatic aberration or vignetting sample' };
}
return {
value: {
maker,
model,
mount: clampText(body.mount, 40),
crop,
aspect,
centerX,
centerY,
notes: clampText(body.notes, 500),
d: distortion.rows,
t: tca.rows,
v: vignetting.rows,
},
};
}
+70
View File
@@ -0,0 +1,70 @@
import { describe, expect, it } from 'vitest';
import { parseCalibration } from './lensCalibration.mjs';
const base = {
maker: 'Tamron',
model: 'SP 24-70mm f/2.8 Di VC USD',
mount: 'Canon EF',
crop: 1,
d: [[24, 2, 0.01, -0.02, 0.03, 0]],
};
describe('team lens calibration validation', () => {
it('accepts a measured profile and normalises its text', () => {
const result = parseCalibration({ ...base, maker: ' Tamron ', notes: ' shot on a 5D ' });
expect(result.error).toBeUndefined();
expect(result.value).toMatchObject({
maker: 'Tamron',
model: 'SP 24-70mm f/2.8 Di VC USD',
mount: 'Canon EF',
crop: 1,
notes: 'shot on a 5D',
aspect: 0,
centerX: 0,
centerY: 0,
});
expect(result.value.d).toEqual([[24, 2, 0.01, -0.02, 0.03, 0]]);
});
it('requires a maker and a model', () => {
expect(parseCalibration({ ...base, maker: ' ' }).error).toMatch(/maker/i);
expect(parseCalibration({ ...base, model: '' }).error).toMatch(/model/i);
});
it('rejects unknown models and impossible focals', () => {
expect(parseCalibration({ ...base, d: [[24, 7, 0.01, 0, 0, 0]] }).error).toMatch(/model/i);
expect(parseCalibration({ ...base, d: [[0, 2, 0.01, 0, 0, 0]] }).error).toMatch(/focal/i);
});
it('rejects a row with the wrong number of values', () => {
expect(parseCalibration({ ...base, d: [[24, 2, 0.01]] }).error).toMatch(/6 numbers/);
expect(parseCalibration({ ...base, t: [[24, 0, 0, 0]] }).error).toMatch(/8 numbers/);
});
it('rejects a crop factor no lens has', () => {
expect(parseCalibration({ ...base, crop: 0 }).error).toMatch(/crop/i);
expect(parseCalibration({ ...base, crop: 9 }).error).toMatch(/crop/i);
});
it('needs at least one sample of any kind', () => {
expect(parseCalibration({ ...base, d: [] }).error).toMatch(/at least one/i);
});
it('keeps vignetting samples that a measurement pass produced', () => {
const result = parseCalibration({
...base,
d: [],
v: [
[24, 2.8, 1000, 0.31, -0.12, 0.02],
[70, 2.8, 1000, 0.42, -0.2, 0.05],
],
});
expect(result.error).toBeUndefined();
expect(result.value.v).toHaveLength(2);
expect(result.value.d).toEqual([]);
});
it('rejects vignetting without an aperture', () => {
expect(parseCalibration({ ...base, d: [], v: [[24, 0, 1000, 0.3, 0, 0]] }).error).toMatch(/aperture/i);
});
});
+12 -2
View File
@@ -1,5 +1,6 @@
import nodemailer from 'nodemailer'; import nodemailer from 'nodemailer';
import { kv } from './db.mjs'; import { kv } from './db.mjs';
import { open, seal } from './secrets.mjs';
import { import {
SMTP_APP_PASSWORD, SMTP_APP_PASSWORD,
SMTP_FROM, SMTP_FROM,
@@ -13,7 +14,16 @@ const SETTINGS_KEY = 'mailSettings';
function savedSettings() { function savedSettings() {
const value = kv.get(SETTINGS_KEY); const value = kv.get(SETTINGS_KEY);
return value && typeof value === 'object' ? value : {}; if (!value || typeof value !== 'object') return {};
if (typeof value.appPassword === 'string' && value.appPassword) {
try {
return { ...value, appPassword: open(value.appPassword) };
} catch (err) {
console.error('[luminary] could not decrypt the saved SMTP password:', err.message);
return { ...value, appPassword: '' };
}
}
return value;
} }
/** Never returns the app password; `hasPassword` is enough for the admin UI. */ /** Never returns the app password; `hasPassword` is enough for the admin UI. */
@@ -70,7 +80,7 @@ function validateSettings(input) {
export function saveMailSettings(input) { export function saveMailSettings(input) {
const next = validateSettings(input ?? {}); const next = validateSettings(input ?? {});
kv.set(SETTINGS_KEY, next); kv.set(SETTINGS_KEY, { ...next, appPassword: seal(next.appPassword) });
return mailStatus(); return mailStatus();
} }
+54
View File
@@ -0,0 +1,54 @@
/**
* Rebuilds stored raw proxies from their originals.
*
* A decode is CPU bound and holds a LibRaw worker for seconds, so the work runs
* one photo at a time behind a snapshot: a request that blocked for an hour
* would time out, and decoding in parallel would starve the editor. The job
* itself keeps progress in memory; `onProgress` lets the caller persist it so a
* restart can pick the run up where it stopped.
*/
/** Photos that have a proxy worth regenerating: camera raws that still exist. */
export function previewRebuildTargets(photos) {
return photos.filter((photo) => photo && photo.raw === true && !photo.deletedAt);
}
/**
* Runs `regenerate(photo)` for every target and reports progress.
*
* A photo that fails is counted and recorded, and the run continues: one
* unreadable original must not strand the rest of the library.
*/
export function startPreviewRebuild({ targets, regenerate, now = Date.now, onProgress }) {
const job = {
state: 'running',
total: targets.length,
done: 0,
failed: 0,
sidecars: 0,
startedAt: now(),
finishedAt: null,
errors: [],
};
const finished = (async () => {
for (const [index, photo] of targets.entries()) {
try {
const result = await regenerate(photo);
if (result?.sidecar) job.sidecars += 1;
} catch (err) {
job.failed += 1;
if (job.errors.length < 5) {
const label = photo?.name || photo?.id || 'photo';
job.errors.push(`${label}: ${err instanceof Error ? err.message : String(err)}`);
}
}
job.done += 1;
onProgress?.({ ...job, errors: [...job.errors] }, targets.slice(index + 1));
}
job.state = 'done';
job.finishedAt = now();
})();
return { snapshot: () => ({ ...job, errors: [...job.errors] }), finished };
}
+87
View File
@@ -0,0 +1,87 @@
import { describe, expect, it } from 'vitest';
import { previewRebuildTargets, startPreviewRebuild } from './previewRebuild.mjs';
describe('preview rebuild targets', () => {
it('takes live camera raws and nothing else', () => {
const photos = [
{ id: 'raw', raw: true },
{ id: 'jpeg', raw: false },
{ id: 'trashed', raw: true, deletedAt: 1 },
{ id: 'unknown' },
];
expect(previewRebuildTargets(photos).map((photo) => photo.id)).toEqual(['raw']);
});
});
describe('preview rebuild job', () => {
it('walks every target in order and counts the 16-bit sidecars', async () => {
const seen = [];
const job = startPreviewRebuild({
targets: [{ id: 'a' }, { id: 'b' }],
regenerate: async (photo) => {
seen.push(photo.id);
return { sidecar: photo.id === 'a' };
},
now: () => 7,
});
expect(job.snapshot()).toMatchObject({ state: 'running', total: 2, done: 0 });
await job.finished;
expect(seen).toEqual(['a', 'b']);
expect(job.snapshot()).toMatchObject({
state: 'done',
done: 2,
failed: 0,
sidecars: 1,
startedAt: 7,
finishedAt: 7,
});
});
it('keeps going after a photo that cannot be decoded', async () => {
const job = startPreviewRebuild({
targets: [{ id: 'a', name: 'A.CR2' }, { id: 'b', name: 'B.CR2' }],
regenerate: async (photo) => {
if (photo.id === 'a') throw new Error('the original is missing');
return { sidecar: false };
},
});
await job.finished;
const snapshot = job.snapshot();
expect(snapshot).toMatchObject({ state: 'done', done: 2, failed: 1, sidecars: 0 });
expect(snapshot.errors[0]).toContain('A.CR2');
expect(snapshot.errors[0]).toContain('the original is missing');
});
it('hands out copies, so a caller cannot edit the live progress', async () => {
const job = startPreviewRebuild({
targets: [{ id: 'a' }],
regenerate: async () => ({ sidecar: false }),
});
const snapshot = job.snapshot();
snapshot.errors.push('tampered');
await job.finished;
expect(job.snapshot().errors).toEqual([]);
});
it('reports progress and what is still pending after each photo', async () => {
const steps = [];
const job = startPreviewRebuild({
targets: [{ id: 'a' }, { id: 'b' }, { id: 'c' }],
regenerate: async () => ({ sidecar: false }),
onProgress: (snapshot, pending) =>
steps.push({ done: snapshot.done, pending: pending.map((photo) => photo.id) }),
});
await job.finished;
expect(steps).toEqual([
{ done: 1, pending: ['b', 'c'] },
{ done: 2, pending: ['c'] },
{ done: 3, pending: [] },
]);
});
it('finishes immediately when there is nothing to rebuild', async () => {
const job = startPreviewRebuild({ targets: [], regenerate: async () => ({ sidecar: false }) });
await job.finished;
expect(job.snapshot()).toMatchObject({ state: 'done', total: 0, done: 0, failed: 0 });
});
});
+93 -19
View File
@@ -1,5 +1,6 @@
import { RAW_PREVIEW_EDGE } from './config.mjs'; import { RAW_16BIT, RAW_PREVIEW_EDGE } from './config.mjs';
import { encodeRgb, jpegInfo, loadSharp, toJpegProxy } from './imaging.mjs'; import { cameraToProxy, readRgbCam } from './color.mjs';
import { encodePng16, encodeRgb, jpegInfo, loadSharp, resizeRgb16, toJpegProxy } from './imaging.mjs';
import { loadLibRaw, rawPool } from './libraw-pool.mjs'; import { loadLibRaw, rawPool } from './libraw-pool.mjs';
/** Every raw container the pipeline will attempt, grouped by vendor family. */ /** Every raw container the pipeline will attempt, grouped by vendor family. */
@@ -57,12 +58,25 @@ export async function rawEngine() {
} }
const DECODE_SETTINGS = { 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, 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, userQual: 3,
highlight: 0, highlight: 2,
noAutoBright: false, // 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 // 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 // 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. // sideways proxy that no later step can fix without losing the original axes.
@@ -70,7 +84,13 @@ const DECODE_SETTINGS = {
useFujiRotate: -1, 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) { function toRgb(img) {
if (!img || !img.width || !img.height || !img.data) throw new Error('LibRaw returned no pixels'); if (!img || !img.width || !img.height || !img.data) throw new Error('LibRaw returned no pixels');
const width = Number(img.width); const width = Number(img.width);
@@ -79,19 +99,36 @@ function toRgb(img) {
const bits = Number(img.bits ?? 8); const bits = Number(img.bits ?? 8);
const src = img.data; const src = img.data;
const pixelCount = width * height; const pixelCount = width * height;
const needed = pixelCount * colors * (bits > 8 ? 2 : 1); const needed = pixelCount * colors;
if (src.length < needed) { // libraw-wasm hands back samples, not bytes: with outputBps 16 the buffer is a
throw new Error(`LibRaw buffer too small (${src.length} bytes for ${width}×${height}×${colors})`); // 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); const rgb = Buffer.alloc(pixelCount * 3);
let rgb16 = null;
if (bits > 8) { 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++) { for (let i = 0; i < pixelCount; i++) {
const s = i * colors; const s = i * colors;
rgb[i * 3] = view[s] >> 8; const r = view[s];
rgb[i * 3 + 1] = view[s + 1] >> 8; const g = view[s + 1];
rgb[i * 3 + 2] = view[s + 2] >> 8; 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 { } else {
for (let i = 0; i < pixelCount; i++) { for (let i = 0; i < pixelCount; i++) {
@@ -101,20 +138,29 @@ function toRgb(img) {
rgb[i * 3 + 2] = src[s + 2]; 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; * Full demosaic through a pooled LibRaw worker. `open()` only unpacks the file;
* the pixels come from `imageData()`, which rejects when the camera is unsupported. * 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'); if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed');
return rawPool.use(async (lib) => { return rawPool.use(async (lib) => {
// LibRaw transfers the buffer to its worker, which detaches it here. Hand it // 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. // a copy so the caller's bytes survive for the embedded-preview fallback.
await lib.open(Buffer.from(buffer), DECODE_SETTINGS); await lib.open(
return toRgb(await lib.imageData()); 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; let librawError = null;
if (looksLikeRaw(buffer)) { if (looksLikeRaw(buffer)) {
try { 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); 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 { return {
jpeg: encoded.data, jpeg: encoded.data,
preview16,
width: encoded.width, width: encoded.width,
height: encoded.height, height: encoded.height,
engine: 'libraw', engine: 'libraw',
+73
View File
@@ -0,0 +1,73 @@
/**
* Small AES-256-GCM helper for credentials stored in SQLite (SMTP app password,
* bridge service tokens). Values written before this file existed are plain
* strings and are still readable; they are sealed the next time they are saved.
*/
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { DATA_DIR, SECRET_KEY } from './config.mjs';
const PREFIX = 'enc:v1:';
let cachedKey = null;
function loadKey() {
if (cachedKey) return cachedKey;
if (SECRET_KEY) {
cachedKey = crypto.createHash('sha256').update(SECRET_KEY).digest();
return cachedKey;
}
// Without an explicit key, keep one beside the database. It protects copies
// of the database (backups, dumps) but not an attacker who has the whole
// data directory.
const file = path.join(DATA_DIR, 'secret.key');
const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8').trim() : '';
if (existing) {
cachedKey = crypto.createHash('sha256').update(existing).digest();
return cachedKey;
}
const generated = crypto.randomBytes(32).toString('hex');
fs.mkdirSync(DATA_DIR, { recursive: true });
try {
fs.writeFileSync(file, generated, { mode: 0o600, flag: 'wx' });
cachedKey = crypto.createHash('sha256').update(generated).digest();
} catch {
cachedKey = crypto
.createHash('sha256')
.update(fs.readFileSync(file, 'utf8').trim())
.digest();
}
return cachedKey;
}
export function isSealed(value) {
return typeof value === 'string' && value.startsWith(PREFIX);
}
export function seal(value) {
if (typeof value !== 'string' || !value) return value;
if (isSealed(value)) return value;
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', loadKey(), iv);
const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
return `${PREFIX}${iv.toString('base64url')}.${cipher.getAuthTag().toString('base64url')}.${ciphertext.toString('base64url')}`;
}
export function open(value) {
if (!isSealed(value)) return value;
const [iv, tag, ciphertext] = String(value).slice(PREFIX.length).split('.');
const decipher = crypto.createDecipheriv(
'aes-256-gcm',
loadKey(),
Buffer.from(iv, 'base64url'),
);
decipher.setAuthTag(Buffer.from(tag, 'base64url'));
return Buffer.concat([
decipher.update(Buffer.from(ciphertext, 'base64url')),
decipher.final(),
]).toString('utf8');
}
+55
View File
@@ -83,6 +83,11 @@ export async function writeOriginal(id, ext, data) {
return target; return target;
} }
/** Final path for a streamed upload; the caller writes it without buffering. */
export function originalTarget(id, ext = 'bin') {
return originalPath(id, ext);
}
export function findOriginal(id) { export function findOriginal(id) {
const safe = lookupId(id); const safe = lookupId(id);
if (!safe) return null; if (!safe) return null;
@@ -112,6 +117,54 @@ export function findPreview(id) {
return null; 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 });
}
/**
* Camera-native grid thumbnail: the sidecar's samples at the JPEG thumbnail's
* size, so the grid can honour a per-photo camera profile without downloading
* the full sidecar. Lives beside the sidecar and is regenerated on demand.
*/
export async function writeThumb16(id, data) {
ensureDirs();
const target = path.join(storageRoot(), 'previews', `${safeId(id)}.t16.png`);
await fsp.writeFile(target, data);
return target;
}
export function findThumb16(id) {
const safe = lookupId(id);
if (!safe) return null;
const p = path.join(dirs().previews, `${safe}.t16.png`);
return fs.existsSync(p) ? p : null;
}
export async function removeThumb16(id) {
const found = findThumb16(id);
if (found) await fsp.rm(found, { force: true });
}
/** /**
* Denoised proxies, keyed by the hash of the parameters that produced them, so * Denoised proxies, keyed by the hash of the parameters that produced them, so
* switching Amount back to a previous value reuses the file instead of spending * switching Amount back to a previous value reuses the file instead of spending
@@ -204,6 +257,8 @@ export async function removeAsset(id) {
const files = [ const files = [
findOriginal(id), findOriginal(id),
findPreview(id), findPreview(id),
findPreview16(id),
findThumb16(id),
findThumb(id), findThumb(id),
findProof(id), findProof(id),
findProofThumb(id), findProofThumb(id),
+690 -10
View File
@@ -9,11 +9,18 @@ import ExportModal from './components/ExportModal';
import CompareView from './components/CompareView'; import CompareView from './components/CompareView';
import FilterBar from './components/FilterBar'; import FilterBar from './components/FilterBar';
import ImportModal from './components/ImportModal'; import ImportModal from './components/ImportModal';
import ImmichPanel from './components/ImmichPanel';
import LibraryGrid from './components/LibraryGrid'; import LibraryGrid from './components/LibraryGrid';
import MergeModal from './components/MergeModal'; import MergeModal from './components/MergeModal';
import PasteSettingsModal from './components/PasteSettingsModal'; import PasteSettingsModal from './components/PasteSettingsModal';
import PrintModal from './components/PrintModal'; import PrintModal from './components/PrintModal';
import ShareModal from './components/ShareModal'; 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 Shortcuts from './components/Shortcuts';
import Stars, { ColorSwatches, FlagButtons } from './components/Stars'; import Stars, { ColorSwatches, FlagButtons } from './components/Stars';
import TopBar from './components/TopBar'; import TopBar from './components/TopBar';
@@ -22,18 +29,24 @@ import {
currentUser, currentUser,
deleteEventRemote, deleteEventRemote,
deletePhotoRemote, deletePhotoRemote,
createImmichEventAlbum,
getHealth, getHealth,
getImmichStatus,
getQuota, getQuota,
immichEventQueue,
login as apiLogin, login as apiLogin,
logout as apiLogout, logout as apiLogout,
pullAll, pullAll,
pullProofs, pullProofs,
pushEvent, pushEvent,
publishImmichOriginal,
pushImmichPhoto,
pushPhoto, pushPhoto,
register as apiRegister, register as apiRegister,
reprocessRawPhoto,
uploadOriginal, uploadOriginal,
} from './lib/api'; } from './lib/api';
import type { Health, ProofSummary, QuotaState, SessionUser } from './lib/api'; import type { Health, ImmichStatus, ProofSummary, QuotaState, SessionUser } from './lib/api';
import { import {
deleteEventRecord, deleteEventRecord,
deletePhotoRecord, deletePhotoRecord,
@@ -52,8 +65,9 @@ import { COLOR_LABELS, defaultEdits, isEdited, normalizePhoto } from './lib/edit
import { applyEditSections, type EditSectionId } from './lib/editSections'; import { applyEditSections, type EditSectionId } from './lib/editSections';
import type { MergeResult } from './lib/merge'; import type { MergeResult } from './lib/merge';
import { evictBitmap } from './lib/images'; import { evictBitmap } from './lib/images';
import { uid } from './lib/import'; import { importFiles, uid } from './lib/import';
import { PRESETS } from './lib/presets'; import { PRESETS } from './lib/presets';
import { downloadXmp, readXmpFile, xmpToEdits } from './lib/xmp';
import type { import type {
Edits, Edits,
EventRecord, EventRecord,
@@ -136,6 +150,41 @@ export default function App() {
const [cloudUser, setCloudUser] = useState<SessionUser | null>(null); const [cloudUser, setCloudUser] = useState<SessionUser | null>(null);
const [cloudOpen, setCloudOpen] = useState(false); const [cloudOpen, setCloudOpen] = useState(false);
const [adminOpen, setAdminOpen] = useState(false); const [adminOpen, setAdminOpen] = useState(false);
const [immichOpen, setImmichOpen] = useState(false);
const [immichStatus, setImmichStatus] = useState<ImmichStatus | null>(null);
const [immichProgress, setImmichProgress] = useState<{
done: number;
total: number;
current: string;
} | null>(null);
const immichStatusRef = useRef<ImmichStatus | null>(null);
immichStatusRef.current = immichStatus;
const immichBusyRef = useRef(false);
// The Immich entry points only appear when this account has opted in.
useEffect(() => {
if (!cloudUser) {
setImmichStatus(null);
return;
}
let alive = true;
getImmichStatus()
.then((status) => {
if (alive) setImmichStatus(status);
})
.catch(() => {
if (alive) setImmichStatus(null);
});
return () => {
alive = false;
};
}, [cloudUser]);
useEffect(
() => () => {
},
[],
);
const [cloudBusy, setCloudBusy] = useState(false); const [cloudBusy, setCloudBusy] = useState(false);
const [cloudError, setCloudError] = useState<string | null>(null); const [cloudError, setCloudError] = useState<string | null>(null);
const [cloudNote, setCloudNote] = useState<string | null>(null); const [cloudNote, setCloudNote] = useState<string | null>(null);
@@ -144,6 +193,12 @@ export default function App() {
const [exportOptions, setExportOptions] = useState<ExportOptions>(DEFAULT_EXPORT); const [exportOptions, setExportOptions] = useState<ExportOptions>(DEFAULT_EXPORT);
const [exportRecipes, setExportRecipes] = useState<ExportRecipe[]>([]); const [exportRecipes, setExportRecipes] = useState<ExportRecipe[]>([]);
const [mergeOpen, setMergeOpen] = useState(false); 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 [printOpen, setPrintOpen] = useState(false);
const saveTimers = useRef(new Map<string, ReturnType<typeof setTimeout>>()); const saveTimers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
@@ -322,6 +377,151 @@ export default function App() {
[queueSave], [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( const bulkUpdate = useCallback(
(ids: string[], patch: Partial<PhotoRecord>) => { (ids: string[], patch: Partial<PhotoRecord>) => {
if (!ids.length) return; if (!ids.length) return;
@@ -337,6 +537,16 @@ export default function App() {
[queueSave], [queueSave],
); );
const immichEventIds = useMemo(
() => new Set(events.filter((event) => event.immich).map((event) => event.id)),
[events],
);
const canSendToImmich = useCallback(
(photo: PhotoRecord) =>
Boolean(immichStatus?.enabled && (photo.immich || immichEventIds.has(photo.eventId))),
[immichStatus?.enabled, immichEventIds],
);
const livePhotos = useMemo(() => photos.filter((p) => !p.deletedAt), [photos]); const livePhotos = useMemo(() => photos.filter((p) => !p.deletedAt), [photos]);
const trashCount = photos.length - livePhotos.length; const trashCount = photos.length - livePhotos.length;
const proofCounts = useMemo(() => { const proofCounts = useMemo(() => {
@@ -475,7 +685,8 @@ export default function App() {
[activeId], [activeId],
); );
const createEvent = useCallback(async (name: string) => { const createEvent = useCallback(
async (name: string, options: { immichGallery?: boolean } = {}) => {
const event: EventRecord = { const event: EventRecord = {
id: uid(), id: uid(),
name: name.trim() || `Event ${new Date().toLocaleDateString()}`, name: name.trim() || `Event ${new Date().toLocaleDateString()}`,
@@ -485,9 +696,45 @@ export default function App() {
workspace: userRef.current?.id, workspace: userRef.current?.id,
}; };
await putEvent(event); await putEvent(event);
if (userRef.current) pushEvent(event).catch(() => undefined); // The gallery endpoint looks the event up server-side, so let this land first.
setEvents((prev) => [...prev, event].sort(byOrder)); if (userRef.current) await pushEvent(event).catch(() => undefined);
return event; let created = event;
if (options.immichGallery && userRef.current && immichStatusRef.current?.enabled) {
try {
const result = await createImmichEventAlbum(event.id, event.name);
created = result.event;
await putEvent(created);
setToast(`Immich gallery created for ${created.name}`);
} catch (err) {
setToast(
`Event created, but the Immich gallery failed: ${
err instanceof Error ? err.message : 'unknown error'
}`,
);
}
}
const nextEvents = [...eventsRef.current.filter((e) => e.id !== created.id), created].sort(byOrder);
// ImportModal creates an event and immediately asks for its Immich gallery.
// Update the ref now so that follow-up call can find the new event.
eventsRef.current = nextEvents;
setEvents(nextEvents);
return created;
},
[],
);
const createImmichGalleryForEvent = useCallback(async (id: string) => {
const event = eventsRef.current.find((item) => item.id === id);
if (!event) throw new Error('No such event');
const result = await createImmichEventAlbum(id, event.name);
await putEvent(result.event);
const nextEvents = eventsRef.current
.map((item) => (item.id === id ? result.event : item))
.sort(byOrder);
eventsRef.current = nextEvents;
setEvents(nextEvents);
setToast(`Immich gallery created for ${event.name}`);
return result.event;
}, []); }, []);
const renameEvent = useCallback(async (id: string, name: string) => { const renameEvent = useCallback(async (id: string, name: string) => {
@@ -780,7 +1027,9 @@ export default function App() {
const savePreset = useCallback( const savePreset = useCallback(
(name: string, edits: Edits) => { (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 = { const preset: Preset = {
id: uid(), id: uid(),
name, name,
@@ -799,6 +1048,19 @@ export default function App() {
[customPresets], [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 */ /* ------------------------------------------------------------- reordering */
const reorderPhotos = useCallback( const reorderPhotos = useCallback(
@@ -1236,6 +1498,203 @@ export default function App() {
} }
}, [activePhoto, bridgeEvent]); }, [activePhoto, bridgeEvent]);
/**
* Renders each edit and uploads the queue one at a time. Checksums make a
* repeat send of an unchanged edit a no-op on the server.
*/
const pushImmichQueue = useCallback(async (targets: PhotoRecord[]) => {
if (immichBusyRef.current) return;
const queue = targets.filter(
(photo) => photo.immich || immichEventIds.has(photo.eventId),
);
const localCount = targets.length - queue.length;
if (!queue.length) {
setToast('None of the selected photos can go to Immich yet');
return;
}
immichBusyRef.current = true;
let sent = 0;
let skipped = 0;
let failed = 0;
let trashed = 0;
let warning = '';
setImmichProgress({ done: 0, total: queue.length, current: queue[0].name });
try {
for (let i = 0; i < queue.length; i += 1) {
const photo = queue[i];
setImmichProgress({ done: i, total: queue.length, current: photo.name });
try {
const blob = await renderPhotoBlob(photo, {
...DEFAULT_EXPORT,
format: 'jpeg',
quality: 92,
resize: 'none',
});
const result = await pushImmichPhoto(photo.id, await blobToBase64(blob));
if (result.alreadyPushed) skipped += 1;
else sent += 1;
if (result.trashed) trashed += 1;
if (result.warning && !warning) warning = result.warning;
} catch (err) {
failed += 1;
if (!warning) warning = err instanceof Error ? err.message : 'A photo could not be sent';
}
setImmichProgress({ done: i + 1, total: queue.length, current: photo.name });
// Let the progress paint before the next full-resolution render.
await new Promise((resolve) => setTimeout(resolve, 0));
}
} finally {
immichBusyRef.current = false;
setImmichProgress(null);
}
const parts = [];
if (sent) parts.push(`Sent ${sent} edit${sent === 1 ? '' : 's'}`);
if (skipped) parts.push(`${skipped} already in Immich`);
if (localCount) parts.push(`${localCount} not from Immich`);
if (trashed) parts.push(`${trashed} original${trashed === 1 ? '' : 's'} in trash`);
if (failed) parts.push(`${failed} failed`);
let message = parts.length ? parts.join(' · ') : 'Nothing to send';
if (warning) message += ` · ${warning}`;
setToast(message);
}, [immichEventIds]);
/**
* Manual push for one event. Photos Immich has never seen upload their
* original from the server; photos edited since the last push are rendered
* here so the gallery receives the current look. Nothing runs on its own -
* this only happens when the button is pressed, and each finished upload is
* recorded so a repeat press skips everything that is already up to date.
*/
const syncEventGallery = useCallback(async (targetEventId: string) => {
if (immichBusyRef.current) {
setToast('An Immich upload is already running');
return;
}
if (!immichStatusRef.current?.enabled) {
setToast('Turn on Immich in the Immich sync panel first');
return;
}
let plan: { photoId: string; mode: 'original' | 'edit' }[];
try {
plan = (await immichEventQueue(targetEventId)).queue;
} catch (err) {
setToast(err instanceof Error ? err.message : 'Could not read the Immich queue');
return;
}
const byId = new Map(
photosRef.current.filter((photo) => !photo.deletedAt).map((photo) => [photo.id, photo]),
);
const queue: { entry: { photoId: string; mode: 'original' | 'edit' }; photo: PhotoRecord }[] = [];
for (const entry of plan) {
const photo = byId.get(entry.photoId);
if (!photo) continue;
// A photo Immich already has only needs a new upload once it is edited.
if (entry.mode === 'edit' && !isEdited(photo.edits)) continue;
queue.push({ entry, photo });
}
if (!queue.length) {
setToast('Everything in this event is already in Immich');
return;
}
immichBusyRef.current = true;
let sent = 0;
let skipped = 0;
let failed = 0;
let warning = '';
setImmichProgress({ done: 0, total: queue.length, current: queue[0].photo.name });
try {
for (let i = 0; i < queue.length; i += 1) {
const { entry, photo } = queue[i];
setImmichProgress({ done: i, total: queue.length, current: photo.name });
try {
const result = entry.mode === 'edit'
? await pushImmichPhoto(
photo.id,
await blobToBase64(
await renderPhotoBlob(photo, {
...DEFAULT_EXPORT,
format: 'jpeg',
quality: 92,
resize: 'none',
}),
),
)
: await publishImmichOriginal(photo.id);
if (result.alreadyPushed || result.skipped) skipped += 1;
else sent += 1;
if (result.warning && !warning) warning = result.warning;
} catch (err) {
failed += 1;
if (!warning) {
warning = `${photo.name}: ${
err instanceof Error ? err.message : 'could not be sent'
}`;
}
}
setImmichProgress({ done: i + 1, total: queue.length, current: photo.name });
// Let the progress paint before the next render or upload.
await new Promise((resolve) => setTimeout(resolve, 0));
}
} finally {
immichBusyRef.current = false;
setImmichProgress(null);
}
const parts = [];
if (sent) parts.push(`Sent ${sent} photo${sent === 1 ? '' : 's'}`);
if (skipped) parts.push(`${skipped} already in Immich`);
if (failed) parts.push(`${failed} failed`);
let message = parts.length ? parts.join(' · ') : 'Nothing to send';
if (warning) message += ` · ${warning}`;
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;
window.open(
`${status.url.replace(/\/+$/, '')}/photos/${encodeURIComponent(photo.immich.assetId)}`,
'_blank',
'noopener,noreferrer',
);
}, []);
const handleCloudLogin = useCallback( const handleCloudLogin = useCallback(
async (email: string, password: string) => { async (email: string, password: string) => {
setCloudBusy(true); setCloudBusy(true);
@@ -1603,7 +2062,94 @@ export default function App() {
? 'Unsorted' ? 'Unsorted'
: events.find((e) => e.id === eventId)?.name ?? 'All photos'; : 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 = [ 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', id: 'import',
label: 'Import photos', label: 'Import photos',
@@ -1638,6 +2184,29 @@ export default function App() {
run: () => setFilters(EMPTY_FILTERS), run: () => setFilters(EMPTY_FILTERS),
}, },
{ id: 'shortcuts', label: 'Show keyboard shortcuts', hint: '?', run: () => setHelpOpen(true) }, { 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' ...(cloudUser && eventId !== 'all' && eventId !== 'unsorted'
? [{ id: 'share', label: 'Open client proofing', hint: 'Share', run: () => setShareEventId(eventId) }] ? [{ id: 'share', label: 'Open client proofing', hint: 'Share', run: () => setShareEventId(eventId) }]
: []), : []),
@@ -1754,9 +2323,14 @@ export default function App() {
setTrashOpen(false); setTrashOpen(false);
setEventId(id); setEventId(id);
}} }}
onCreate={async (name) => { immichEnabled={Boolean(immichStatus?.enabled)}
await createEvent(name); onCreate={async (name, immichGallery) => {
await createEvent(name, { immichGallery });
}} }}
onSyncGallery={syncEventGallery}
onPublishGallery={publishEventToImmich}
canReprocessRaw={Boolean(cloudUser)}
onReprocessEvent={reprocessEventRaws}
onRename={renameEvent} onRename={renameEvent}
onDelete={removeEvent} onDelete={removeEvent}
onReorderEvents={reorderEvents} onReorderEvents={reorderEvents}
@@ -1855,6 +2429,21 @@ export default function App() {
onBulkRate={(rating) => bulkUpdate(selected, { rating })} onBulkRate={(rating) => bulkUpdate(selected, { rating })}
onBulkFlag={(flag) => bulkUpdate(selected, { flag })} onBulkFlag={(flag) => bulkUpdate(selected, { flag })}
onBulkColor={(color) => bulkUpdate(selected, { color })} onBulkColor={(color) => bulkUpdate(selected, { color })}
onSendToImmich={
selected.some((id) => {
const photo = photos.find((item) => item.id === id);
return photo ? canSendToImmich(photo) : false;
})
? () => void pushImmichQueue(photos.filter((photo) => selected.includes(photo.id)))
: 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))} onDelete={() => (trashOpen ? void removePhotos(selected) : trashPhotos(selected))}
onExport={openExport} onExport={openExport}
onCompare={() => setCompareOpen(true)} onCompare={() => setCompareOpen(true)}
@@ -1892,15 +2481,24 @@ export default function App() {
onSelect={setActiveId} onSelect={setActiveId}
onExit={() => setView('grid')} onExit={() => setView('grid')}
onUpdate={updatePhoto} onUpdate={updatePhoto}
onUpdateEdits={updatePhotoEdits}
clipboard={clipboard} clipboard={clipboard}
onCopy={copySettings} onCopy={copySettings}
onPaste={() => openPaste([activePhoto.id])} onCopyOf={copySettingsOf}
onPaste={(ids) => openPaste(ids?.length ? ids : [activePhoto.id])}
onResetSelection={resetEdits}
localClipboard={localClipboard} localClipboard={localClipboard}
onLocalClipboard={setLocalClipboard} onLocalClipboard={setLocalClipboard}
onExport={openExport} onExport={openExport}
onPrint={() => setPrintOpen(true)} onPrint={() => setPrintOpen(true)}
canPushImmich={canSendToImmich(activePhoto)}
onPushImmich={() => void pushImmichQueue([activePhoto])}
onOpenImmich={
activePhoto.immich ? () => openImmichAsset(activePhoto) : undefined
}
presets={[...PRESETS, ...customPresets]} presets={[...PRESETS, ...customPresets]}
onSavePreset={savePreset} onSavePreset={savePreset}
onDeletePreset={deletePreset}
onDelete={() => trashPhotos([activePhoto.id])} onDelete={() => trashPhotos([activePhoto.id])}
onVirtualCopy={() => void createVirtualCopy(activePhoto.id, true)} onVirtualCopy={() => void createVirtualCopy(activePhoto.id, true)}
metadataPresets={metadataPresets} metadataPresets={metadataPresets}
@@ -1949,6 +2547,8 @@ export default function App() {
setToast(`Imported ${imported.length} photo${imported.length === 1 ? '' : 's'}`); setToast(`Imported ${imported.length} photo${imported.length === 1 ? '' : 's'}`);
}} }}
onCreateEvent={createEvent} onCreateEvent={createEvent}
immichEnabled={Boolean(immichStatus?.enabled)}
onCreateImmichGallery={createImmichGalleryForEvent}
/> />
)} )}
@@ -2061,6 +2661,10 @@ export default function App() {
setCloudOpen(false); setCloudOpen(false);
setAdminOpen(true); setAdminOpen(true);
}} }}
onImmich={() => {
setCloudOpen(false);
setImmichOpen(true);
}}
onClose={() => setCloudOpen(false)} onClose={() => setCloudOpen(false)}
/> />
)} )}
@@ -2071,11 +2675,23 @@ export default function App() {
onClose={() => setAdminOpen(false)} onClose={() => setAdminOpen(false)}
onChanged={() => { onChanged={() => {
void getHealth().then((health) => setCloudHealth(health)); void getHealth().then((health) => setCloudHealth(health));
void getImmichStatus().then(setImmichStatus).catch(() => undefined);
}} }}
onRestored={() => void refreshCatalogFromServer()} onRestored={() => void refreshCatalogFromServer()}
/> />
)} )}
{immichOpen && cloudUser && (
<ImmichPanel
onClose={() => setImmichOpen(false)}
onChanged={() => {
void getImmichStatus().then(setImmichStatus).catch(() => undefined);
void refreshCatalogFromServer();
}}
onToast={setToast}
/>
)}
{menu && {menu &&
(() => { (() => {
const targets = photos.filter((p) => menu.ids.includes(p.id)); const targets = photos.filter((p) => menu.ids.includes(p.id));
@@ -2133,6 +2749,21 @@ export default function App() {
disabled: menu.ids.length < 2, disabled: menu.ids.length < 2,
onSelect: () => setMergeOpen(true), onSelect: () => setMergeOpen(true),
}, },
...(targets.some(canSendToImmich)
? ([
{
label:
targets.filter(canSendToImmich).length === 1
? 'Send edit to Immich'
: `Send ${targets.filter(canSendToImmich).length} edits to Immich`,
disabled: Boolean(immichProgress),
onSelect: () => void pushImmichQueue(targets),
},
...(lead.immich
? [{ label: 'Open in Immich', onSelect: () => openImmichAsset(lead) }]
: []),
] as MenuEntry[])
: []),
{ label: 'Export…', onSelect: openExport }, { label: 'Export…', onSelect: openExport },
{ label: 'Print…', onSelect: () => setPrintOpen(true) }, { label: 'Print…', onSelect: () => setPrintOpen(true) },
{ {
@@ -2168,6 +2799,55 @@ export default function App() {
/> />
)} )}
{immichProgress && (
<div className="toast immich-progress" role="status" aria-live="polite">
<div className="immich-progress-head">
<strong>Sending to Immich</strong>
<span>
{immichProgress.done} / {immichProgress.total}
</span>
</div>
<div className="quota-meter">
<span
style={{
width: `${immichProgress.total ? Math.round((immichProgress.done / immichProgress.total) * 100) : 0}%`,
}}
/>
</div>
<span className="muted small">{immichProgress.current}</span>
</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 && ( {toast && (
<div className="toast"> <div className="toast">
<span>{toast}</span> <span>{toast}</span>
+262 -1
View File
@@ -6,6 +6,7 @@ import type {
AdminUser, AdminUser,
CatalogBackup, CatalogBackup,
MailStatus, MailStatus,
PreviewRebuildStatus,
SessionUser, SessionUser,
StorageChange, StorageChange,
} from '../lib/api'; } from '../lib/api';
@@ -15,14 +16,19 @@ import {
adminCreateUser, adminCreateUser,
adminDeleteEvent, adminDeleteEvent,
adminDeleteUser, adminDeleteUser,
adminDisconnectImmich,
adminRestoreCatalog, adminRestoreCatalog,
adminRevokeInvite, adminRevokeInvite,
adminOverview, adminOverview,
adminPreviewRebuildStatus,
adminRebuildPreviews,
adminRenameEvent, adminRenameEvent,
adminSaveImmich,
adminSaveMail, adminSaveMail,
adminSchedulePrune, adminSchedulePrune,
adminSetQuota, adminSetQuota,
adminSetStorage, adminSetStorage,
adminTestImmich,
adminTestMail, adminTestMail,
adminUpdateUser, adminUpdateUser,
adminWarnUser, adminWarnUser,
@@ -68,7 +74,19 @@ const planSummary = (quota: AdminQuota) => {
return parts.length ? parts.join(', ') : 'nothing'; return parts.length ? parts.join(', ') : 'nothing';
}; };
type Tab = 'users' | 'invites' | 'content' | 'storage' | 'quotas' | 'backup'; type Tab = 'users' | 'invites' | 'content' | 'storage' | 'quotas' | 'immich' | 'backup';
/** No rebuild has run in this process yet. */
const idleRebuild: PreviewRebuildStatus = {
state: 'idle',
total: 0,
done: 0,
failed: 0,
sidecars: 0,
startedAt: null,
finishedAt: null,
errors: [],
};
const inviteUrl = (token: string) => `${window.location.origin}/join/${token}`; const inviteUrl = (token: string) => `${window.location.origin}/join/${token}`;
@@ -106,12 +124,61 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
const [rootInput, setRootInput] = useState(''); const [rootInput, setRootInput] = useState('');
const [change, setChange] = useState<StorageChange | null>(null); const [change, setChange] = useState<StorageChange | null>(null);
const [rebuild, setRebuild] = useState<PreviewRebuildStatus>(idleRebuild);
const [rebuildBusy, setRebuildBusy] = useState(false);
const restoreInput = useRef<HTMLInputElement>(null); const restoreInput = useRef<HTMLInputElement>(null);
const [restoreNote, setRestoreNote] = useState<string | null>(null); const [restoreNote, setRestoreNote] = useState<string | null>(null);
const [quotaDrafts, setQuotaDrafts] = useState<Record<string, string>>({}); const [quotaDrafts, setQuotaDrafts] = useState<Record<string, string>>({});
const [mailDraft, setMailDraft] = useState({ user: '', appPassword: '', from: '' }); const [mailDraft, setMailDraft] = useState({ user: '', appPassword: '', from: '' });
const [mail, setMail] = useState<MailStatus | null>(null); const [mail, setMail] = useState<MailStatus | null>(null);
const [immichDraft, setImmichDraft] = useState({ url: '', apiKey: '', enabled: true });
// The rebuild runs inside the server, so the panel reads its progress instead
// of holding the work: closing the modal does not stop it, and reopening the
// tab picks up a run that is already in flight.
useEffect(() => {
if (tab !== 'storage') return;
let alive = true;
adminPreviewRebuildStatus()
.then((next) => {
if (alive) setRebuild(next);
})
.catch(() => undefined);
return () => {
alive = false;
};
}, [tab]);
const rebuildRunning = rebuild.state === 'running';
useEffect(() => {
if (tab !== 'storage' || !rebuildRunning) return;
const timer = setInterval(() => {
adminPreviewRebuildStatus()
.then(setRebuild)
.catch(() => undefined);
}, 2000);
return () => clearInterval(timer);
}, [tab, rebuildRunning]);
const rebuildPreviews = async () => {
setRebuildBusy(true);
setError(null);
setNote(null);
try {
const started = await adminRebuildPreviews();
setRebuild(started);
setNote(
started.state === 'done'
? 'Nothing to rebuild: every camera raw is a JPEG-only import'
: `Rebuilding ${started.total} preview proxies`,
);
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not rebuild the previews');
} finally {
setRebuildBusy(false);
}
};
const restoreCatalog = async (file: File | undefined) => { const restoreCatalog = async (file: File | undefined) => {
if (!file || busy) return; if (!file || busy) return;
@@ -161,6 +228,11 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
user: current.user || next.mail.user, user: current.user || next.mail.user,
from: current.from || next.mail.from, from: current.from || next.mail.from,
})); }));
setImmichDraft((current) => ({
url: next.immich.hasKey ? current.url || next.immich.url : next.immich.url,
apiKey: '',
enabled: next.immich.hasKey ? (current.url ? current.enabled : next.immich.enabled) : true,
}));
setRootInput((current) => (current ? current : next.storage.root)); setRootInput((current) => (current ? current : next.storage.root));
onChanged(); onChanged();
}, [onChanged]); }, [onChanged]);
@@ -174,6 +246,13 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
setOverview(next); setOverview(next);
setMail(next.mail); setMail(next.mail);
setMailDraft({ user: next.mail.user, appPassword: '', from: next.mail.from }); setMailDraft({ user: next.mail.user, appPassword: '', from: next.mail.from });
// A connection being set up for the first time defaults to on; the box
// would otherwise be unchecked and silently save publishing as off.
setImmichDraft({
url: next.immich.url,
apiKey: '',
enabled: next.immich.hasKey ? next.immich.enabled : true,
});
setRootInput(next.storage.root); setRootInput(next.storage.root);
setQuotaDrafts( setQuotaDrafts(
Object.fromEntries( Object.fromEntries(
@@ -345,6 +424,42 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
setNote(`Test email sent to ${user.email}`); setNote(`Test email sent to ${user.email}`);
}); });
const saveImmich = () =>
run(async () => {
const next = await adminSaveImmich({
url: immichDraft.url.trim(),
apiKey: immichDraft.apiKey,
enabled: immichDraft.enabled,
});
setImmichDraft({ url: next.url, apiKey: '', enabled: next.enabled });
setNote(
next.enabled
? 'Immich connection saved for every account'
: 'Immich connection saved; automatic publishing is off',
);
});
const testImmich = () =>
run(async () => {
const result = await adminTestImmich();
setNote(
`Connected to Immich ${result.version} · ${result.albumCount} album${
result.albumCount === 1 ? '' : 's'
}`,
);
});
const disconnectImmichConnection = () => {
if (!window.confirm('Remove the server-wide Immich connection? Existing albums and photos stay in Immich.')) {
return;
}
void run(async () => {
const next = await adminDisconnectImmich();
setImmichDraft({ url: next.url, apiKey: '', enabled: next.enabled });
setNote('Immich connection removed');
});
};
const renameEvent = () => { const renameEvent = () => {
if (!editEvent) return; if (!editEvent) return;
const name = editEvent.name.trim(); const name = editEvent.name.trim();
@@ -404,6 +519,9 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
<button className={`tab ${tab === 'quotas' ? 'on' : ''}`} onClick={() => setTab('quotas')}> <button className={`tab ${tab === 'quotas' ? 'on' : ''}`} onClick={() => setTab('quotas')}>
Quotas Quotas
</button> </button>
<button className={`tab ${tab === 'immich' ? 'on' : ''}`} onClick={() => setTab('immich')}>
Immich
</button>
<button className={`tab ${tab === 'backup' ? 'on' : ''}`} onClick={() => setTab('backup')}> <button className={`tab ${tab === 'backup' ? 'on' : ''}`} onClick={() => setTab('backup')}>
Backup Backup
</button> </button>
@@ -926,6 +1044,108 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
</p> </p>
</div> </div>
</section> </section>
) : tab === 'immich' ? (
<section className="admin-section">
<h3>Immich connection</h3>
<p className="muted small">
One connection is shared by every account. When it is enabled, importing into a
Luminary event creates a matching Immich album, publishes the originals there, and
saves edited versions to the same album.
</p>
<label className="field">
<span>Immich server address</span>
<input
value={immichDraft.url}
spellCheck={false}
placeholder="http://192.168.1.10:2283"
onChange={(e) =>
setImmichDraft((current) => ({ ...current, url: e.target.value }))
}
onKeyDown={(e) => e.key === 'Enter' && saveImmich()}
/>
</label>
<label className="field">
<span>API key</span>
<input
type="password"
autoComplete="off"
value={immichDraft.apiKey}
placeholder={overview.immich.hasKey ? 'Saved — type to replace' : 'Immich API key'}
onChange={(e) =>
setImmichDraft((current) => ({ ...current, apiKey: e.target.value }))
}
onKeyDown={(e) => e.key === 'Enter' && saveImmich()}
/>
</label>
<label className="check-row">
<input
type="checkbox"
checked={immichDraft.enabled}
disabled={busy}
onChange={(e) =>
setImmichDraft((current) => ({ ...current, enabled: e.target.checked }))
}
/>
Automatically publish event photos and edits
</label>
<div className="btn-row">
<button
className="btn primary"
onClick={saveImmich}
disabled={
busy ||
!immichDraft.url.trim() ||
(!immichDraft.apiKey && !overview.immich.hasKey)
}
>
Save connection
</button>
<button
className="btn ghost"
onClick={testImmich}
disabled={busy || !overview.immich.hasKey}
>
Test connection
</button>
{overview.immich.hasKey && (
<button
className="btn ghost"
onClick={disconnectImmichConnection}
disabled={busy}
>
Disconnect
</button>
)}
</div>
{overview.immich.configured ? (
<div className={`banner ${overview.immich.enabled ? 'ok' : 'info'}`}>
{overview.immich.enabled
? 'Connected and automatic publishing is on.'
: 'Connection saved; automatic publishing is off.'}{' '}
{overview.immich.version ? `Immich ${overview.immich.version}.` : 'Test it to verify access.'}
</div>
) : (
<div className="banner info">
Add the server address and API key to enable Immich publishing.
</div>
)}
<div className="admin-note">
<p>
The key needs <code>album.read</code>, <code>album.create</code>,{' '}
<code>albumAsset.create</code>, <code>asset.read</code>,{' '}
<code>asset.download</code>, <code>asset.upload</code> and{' '}
<code>asset.update</code>. Add <code>asset.delete</code> only if originals should
move to the Immich trash after an edited version is uploaded.
</p>
<p className="muted small">
The key is encrypted on the server and never sent back to a browser. Existing
albums already in Immich stay untouched if the connection is removed.
</p>
</div>
</section>
) : tab === 'backup' ? ( ) : tab === 'backup' ? (
<section className="admin-section"> <section className="admin-section">
<h3>Catalog backup</h3> <h3>Catalog backup</h3>
@@ -1030,6 +1250,47 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
container first (for example <code>-v /photos:/photos</code>), then use that container path. container first (for example <code>-v /photos:/photos</code>), then use that container path.
</p> </p>
</div> </div>
<h3>Preview proxies</h3>
<p className="muted small">
Re-decode every camera raw from its original and replace its JPEG proxy, grid thumbnail
and 16-bit sidecar. Run this after a change to the raw pipeline: edits, ratings and
events are kept, and the originals are never modified.
</p>
<div className="btn-row">
<button
className="btn primary"
onClick={() => void rebuildPreviews()}
disabled={busy || rebuildBusy || rebuildRunning || rebuild.total === 0}
title={
rebuild.total === 0 && rebuild.state === 'done'
? 'The last rebuild found no camera raws to process'
: undefined
}
>
{rebuildRunning
? `Rebuilding ${rebuild.done} / ${rebuild.total}…`
: rebuildBusy
? 'Starting…'
: 'Rebuild previews'}
</button>
</div>
{rebuildRunning && (
<p className="muted small">
{rebuild.done} of {rebuild.total} raws rebuilt
{rebuild.failed ? ` · ${rebuild.failed} failed` : ''} · the server keeps going when
this panel closes.
</p>
)}
{rebuild.state === 'done' && (
<p className="muted small">
Rebuilt {rebuild.done - rebuild.failed} of {rebuild.total} raws
{rebuild.sidecars ? `, ${rebuild.sidecars} with a 16-bit sidecar` : ''}
{rebuild.failed ? ` · ${rebuild.failed} failed` : ''}.
{rebuild.errors.length > 0 ? ` First failure: ${rebuild.errors[0]}` : ''}
</p>
)}
</section> </section>
)} )}
+10
View File
@@ -12,6 +12,7 @@ interface Props {
onLogout: () => void; onLogout: () => void;
onSync: () => void; onSync: () => void;
onAdmin: () => void; onAdmin: () => void;
onImmich: () => void;
onClose: () => void; onClose: () => void;
} }
@@ -32,6 +33,7 @@ export default function CloudPanel({
onLogout, onLogout,
onSync, onSync,
onAdmin, onAdmin,
onImmich,
onClose, onClose,
}: Props) { }: Props) {
const [mode, setMode] = useState<'signin' | 'signup'>('signin'); const [mode, setMode] = useState<'signin' | 'signup'>('signin');
@@ -121,6 +123,14 @@ export default function CloudPanel({
Administration Administration
</button> </button>
)} )}
<button
className="btn ghost"
onClick={onImmich}
disabled={busy}
title="Optional: sync albums with your own Immich server"
>
Immich sync
</button>
</div> </div>
{note && <div className="banner ok">{note}</div>} {note && <div className="banner ok">{note}</div>}
</div> </div>
+23 -4
View File
@@ -1,7 +1,8 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { getBitmap } from '../lib/images'; import { get16BitSource, getBitmap } from '../lib/images';
import type { Preview16 } from '../lib/preview16';
import { rotatedBounds, Renderer } from '../gl/renderer'; import { rotatedBounds, Renderer } from '../gl/renderer';
import { buildLensCorrection, type LensCorrection } from '../lib/lensfun'; import { buildLensCorrection, type LensCorrection } from '../lib/lensEngine';
import type { PhotoRecord } from '../types'; import type { PhotoRecord } from '../types';
interface Props { interface Props {
@@ -15,6 +16,7 @@ function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: strin
const boxRef = useRef<HTMLDivElement>(null); const boxRef = useRef<HTMLDivElement>(null);
const rendererRef = useRef<Renderer | null>(null); const rendererRef = useRef<Renderer | null>(null);
const [bitmap, setBitmap] = useState<ImageBitmap | null>(null); const [bitmap, setBitmap] = useState<ImageBitmap | null>(null);
const [hdr, setHdr] = useState<Preview16 | null>(null);
const [box, setBox] = useState({ w: 0, h: 0 }); const [box, setBox] = useState({ w: 0, h: 0 });
const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null); const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@@ -29,6 +31,23 @@ function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: strin
}; };
}, [photo]); }, [photo]);
// Compare renders the full proxy, so the matching 16-bit sidecar is what lets
// a per-photo camera profile show here exactly as it does in Develop. Without
// a profile the JPEG already carries the body matrix, so skip the big fetch.
useEffect(() => {
let alive = true;
if (!photo.edits.cameraProfile) {
setHdr(null);
return;
}
get16BitSource(photo)
.then((next) => alive && setHdr(next))
.catch(() => alive && setHdr(null));
return () => {
alive = false;
};
}, [photo]);
useEffect(() => { useEffect(() => {
let alive = true; let alive = true;
if (!photo.edits.lens || !bitmap) { if (!photo.edits.lens || !bitmap) {
@@ -98,14 +117,14 @@ function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: strin
lens: lensCorrection, lens: lensCorrection,
}; };
try { try {
renderer.setImage(bitmap); renderer.setImage(bitmap, hdr);
renderer.render(photo.edits, opts); renderer.render(photo.edits, opts);
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : 'Rendering failed'); setError(err instanceof Error ? err.message : 'Rendering failed');
} }
}); });
return () => cancelAnimationFrame(raf); return () => cancelAnimationFrame(raf);
}, [bitmap, box, photo, lensCorrection]); }, [bitmap, box, photo, lensCorrection, hdr]);
return ( return (
<figure className="compare-tile" onDoubleClick={() => onOpen(photo.id)}> <figure className="compare-tile" onDoubleClick={() => onOpen(photo.id)}>
+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 { buildSampler, clamp01 } from '../lib/curves';
import type { CurvePoint } from '../types'; import type { CurvePoint } from '../types';
export type ParametricKey = 'highlights' | 'lights' | 'darks' | 'blacks';
interface Props { interface Props {
points: CurvePoint[]; points: CurvePoint[];
onChange: (points: CurvePoint[]) => void; onChange: (points: CurvePoint[]) => void;
color: string; 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 svgRef = useRef<SVGSVGElement>(null);
const pointsRef = useRef(points); const pointsRef = useRef(points);
const [drag, setDrag] = useState<number | null>(null); const [drag, setDrag] = useState<number | null>(null);
const [paramDrag, setParamDrag] = useState<ParametricKey | null>(null);
const [hover, setHover] = useState<number | null>(null); const [hover, setHover] = useState<number | null>(null);
useEffect(() => { useEffect(() => {
@@ -42,6 +59,12 @@ export default function CurveEditor({ points, onChange, color }: Props) {
const handleDown = (e: React.PointerEvent<SVGSVGElement>) => { const handleDown = (e: React.PointerEvent<SVGSVGElement>) => {
e.preventDefault(); 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'); const idxAttr = (e.target as Element).getAttribute('data-idx');
let idx: number; let idx: number;
if (idxAttr !== null) { if (idxAttr !== null) {
@@ -57,6 +80,15 @@ export default function CurveEditor({ points, onChange, color }: Props) {
}; };
const handleMove = (e: React.PointerEvent<SVGSVGElement>) => { 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; if (drag === null) return;
const pts = pointsRef.current; const pts = pointsRef.current;
const idx = drag; const idx = drag;
@@ -68,7 +100,10 @@ export default function CurveEditor({ points, onChange, color }: Props) {
onChange(next); onChange(next);
}; };
const handleUp = () => setDrag(null); const handleUp = () => {
setDrag(null);
setParamDrag(null);
};
const removePoint = (idx: number) => { const removePoint = (idx: number) => {
const pts = pointsRef.current; const pts = pointsRef.current;
@@ -101,6 +136,37 @@ export default function CurveEditor({ points, onChange, color }: Props) {
</g> </g>
))} ))}
<line x1="0" y1="100" x2="100" y2="0" className="curve-diag" /> <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" /> <path d={path} fill="none" stroke={color} strokeWidth="1.6" vectorEffect="non-scaling-stroke" />
{points.map((p, i) => ( {points.map((p, i) => (
<circle <circle
@@ -116,7 +182,9 @@ export default function CurveEditor({ points, onChange, color }: Props) {
/> />
))} ))}
</svg> </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> </div>
); );
} }
+699 -144
View File
File diff suppressed because it is too large Load Diff
+70
View File
@@ -0,0 +1,70 @@
import { memo, useEffect, useRef, useState } from 'react';
import { thumbTransform } from '../lib/edits';
import { useEditedThumb } from '../lib/editThumbs';
import type { PhotoRecord } from '../types';
interface Props {
photo: PhotoRecord;
/** Aspect of the tile the picture fills; the rotation transform needs it. */
boxAspect?: number;
alt?: string;
loading?: 'lazy' | 'eager';
draggable?: boolean;
}
/**
* A thumbnail that follows the photo's edits.
*
* Edited photos get a freshly rendered small JPEG; everything else keeps the
* server/import thumbnail and the CSS orientation transform. Rendering starts
* only when the tile is close to the viewport.
*/
function EditedImage({
photo,
boxAspect = 4 / 3,
alt,
loading = 'lazy',
draggable = false,
}: Props) {
const ref = useRef<HTMLImageElement>(null);
const [nearView, setNearView] = useState(false);
useEffect(() => {
const el = ref.current;
if (!el) return;
if (typeof IntersectionObserver === 'undefined') {
setNearView(true);
return;
}
const observer = new IntersectionObserver(
(entries) => {
if (!entries.some((entry) => entry.isIntersecting)) return;
setNearView(true);
observer.disconnect();
},
{ rootMargin: '400px' },
);
observer.observe(el);
return () => observer.disconnect();
}, []);
const edited = useEditedThumb(photo, nearView);
return (
<img
ref={ref}
src={edited ?? photo.thumbUrl ?? photo.thumb}
alt={alt ?? photo.name}
loading={loading}
draggable={draggable}
// A rendered tile already has the crop, turn and flips baked in.
style={{ transform: edited ? 'none' : thumbTransform(photo, boxAspect) }}
/>
);
}
/**
* 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);
+58 -2
View File
@@ -17,9 +17,15 @@ interface Props {
photos: PhotoRecord[]; photos: PhotoRecord[];
eventId: string; eventId: string;
onSelectEvent: (id: string) => void; onSelectEvent: (id: string) => void;
onCreate: (name: string) => Promise<void> | void; immichEnabled?: boolean;
onCreate: (name: string, immichGallery?: boolean) => Promise<void> | void;
onRename: (id: string, name: string) => void; onRename: (id: string, name: string) => void;
onDelete: (id: 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; onReorderEvents: (dragId: string, targetId: string) => void;
onDropPhotos: (ids: string[], eventId: string) => void; onDropPhotos: (ids: string[], eventId: string) => void;
trashOpen: boolean; trashOpen: boolean;
@@ -39,9 +45,14 @@ export default function EventSidebar({
photos, photos,
eventId, eventId,
onSelectEvent, onSelectEvent,
immichEnabled = false,
onCreate, onCreate,
onRename, onRename,
onDelete, onDelete,
onSyncGallery,
onPublishGallery,
canReprocessRaw = false,
onReprocessEvent,
onReorderEvents, onReorderEvents,
onDropPhotos, onDropPhotos,
trashOpen, trashOpen,
@@ -55,9 +66,11 @@ export default function EventSidebar({
}: Props) { }: Props) {
const [adding, setAdding] = useState(false); const [adding, setAdding] = useState(false);
const [name, setName] = useState(''); const [name, setName] = useState('');
const [createGallery, setCreateGallery] = useState(false);
const [dropTarget, setDropTarget] = useState<string | null>(null); const [dropTarget, setDropTarget] = useState<string | null>(null);
const counts = new Map<string, number>(); const counts = new Map<string, number>();
const rawCounts = new Map<string, number>();
let unsorted = 0; let unsorted = 0;
for (const p of photos) { for (const p of photos) {
if (!p.eventId) { if (!p.eventId) {
@@ -65,6 +78,7 @@ export default function EventSidebar({
continue; continue;
} }
counts.set(p.eventId, (counts.get(p.eventId) ?? 0) + 1); 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 () => { const submit = async () => {
@@ -72,8 +86,9 @@ export default function EventSidebar({
setAdding(false); setAdding(false);
return; return;
} }
await onCreate(name); await onCreate(name, createGallery);
setName(''); setName('');
setCreateGallery(false);
setAdding(false); setAdding(false);
}; };
@@ -189,6 +204,16 @@ export default function EventSidebar({
<button className="btn primary small" onClick={() => void submit()}> <button className="btn primary small" onClick={() => void submit()}>
Add Add
</button> </button>
{immichEnabled && (
<label className="check-row small new-event-gallery">
<input
type="checkbox"
checked={createGallery}
onChange={(e) => setCreateGallery(e.target.checked)}
/>
Create Immich gallery
</label>
)}
</div> </div>
)} )}
@@ -234,6 +259,37 @@ export default function EventSidebar({
<span className="event-count">{counts.get(event.id) ?? 0}</span> <span className="event-count">{counts.get(event.id) ?? 0}</span>
</button> </button>
<div className="event-tools"> <div className="event-tools">
{canReprocessRaw && onReprocessEvent && (rawCounts.get(event.id) ?? 0) > 0 && (
<button
className="icon-btn"
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 <button
className="icon-btn" className="icon-btn"
title="Rename event" title="Rename event"
+21 -1
View File
@@ -5,6 +5,8 @@ import Slider from './Slider';
import { getBitmap } from '../lib/images'; import { getBitmap } from '../lib/images';
import { frameToSource, grainCellPx, grainSampleWindow, outputSize, rotatedBounds, Renderer } from '../gl/renderer'; import { frameToSource, grainCellPx, grainSampleWindow, outputSize, rotatedBounds, Renderer } from '../gl/renderer';
import type { PhotoRecord } from '../types'; import type { PhotoRecord } from '../types';
import { COLOR_SPACE_OPTIONS } from '../lib/colorSpace';
import type { OutputColorSpace } from '../lib/icc';
interface Props { interface Props {
photos: PhotoRecord[]; photos: PhotoRecord[];
@@ -280,8 +282,12 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
value={opts.format} value={opts.format}
onChange={(e) => { onChange={(e) => {
const format = e.target.value as ExportFormat; const format = e.target.value as ExportFormat;
const wide = format === 'jpeg' || format === 'tiff16';
patch({ patch({
format, 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 // Watermarking needs an 8-bit canvas pass; keep the option off
// rather than silently downgrading the 16-bit file. // rather than silently downgrading the 16-bit file.
...(format === 'tiff16' ? { watermark: { ...opts.watermark, enabled: false } } : {}), ...(format === 'tiff16' ? { watermark: { ...opts.watermark, enabled: false } } : {}),
@@ -435,6 +441,20 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
<div className="subhead"> <div className="subhead">
<span>Output</span> <span>Output</span>
</div> </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 <Slider
label="Output sharpening" label="Output sharpening"
min={0} min={0}
@@ -460,7 +480,7 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
onChange={(e) => patch({ embedProfile: e.target.checked })} onChange={(e) => patch({ embedProfile: e.target.checked })}
disabled={opts.format === 'webp' || opts.format === 'png'} 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> </label>
<div className="subhead"> <div className="subhead">
+431
View File
@@ -0,0 +1,431 @@
import { useCallback, useEffect, useState } from 'react';
import type { ImmichAlbum, ImmichImportJob, ImmichStatus } from '../lib/api';
import {
disconnectImmich,
getImmichJob,
getImmichStatus,
immichAlbums,
immichImportAlbum,
saveImmichSettings,
testImmich,
} from '../lib/api';
interface Props {
onClose: () => void;
onChanged: () => void;
onToast: (message: string) => void;
}
const fmtDate = (ms: number | null) =>
ms
? new Date(ms).toLocaleString(undefined, {
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
})
: 'never';
/**
* Optional, per-account Immich setup. Nothing here is shown anywhere else in
* the app until the user saves a connection and turns the integration on.
*/
export default function ImmichPanel({ onClose, onChanged, onToast }: Props) {
const [status, setStatus] = useState<ImmichStatus | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [draft, setDraft] = useState({ url: '', apiKey: '' });
const [albums, setAlbums] = useState<ImmichAlbum[] | null>(null);
const [albumsLoading, setAlbumsLoading] = useState(false);
const [job, setJob] = useState<ImmichImportJob | null>(null);
const load = useCallback(async () => {
try {
const next = await getImmichStatus();
setStatus(next);
setDraft((current) => ({ url: current.url || next.url, apiKey: '' }));
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not read the Immich settings');
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void load();
}, [load]);
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
if (event.key !== 'Escape') return;
event.preventDefault();
event.stopImmediatePropagation();
if (!saving) onClose();
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [saving, onClose]);
useEffect(() => {
if (!job || job.state !== 'running') return;
let alive = true;
const timer = setInterval(() => {
void getImmichJob(job.id)
.then((next) => {
if (!alive) return;
setJob(next);
if (next.state === 'running') return;
onToast(next.message || 'Immich import finished');
setAlbums(null);
void load();
onChanged();
})
.catch((err) => {
if (!alive) return;
setError(err instanceof Error ? err.message : 'Could not check the import');
setJob({ ...job, state: 'error' });
});
}, 1500);
return () => {
alive = false;
clearInterval(timer);
};
}, [job, load, onChanged, onToast]);
const save = async (patch: Record<string, unknown> = {}) => {
if (saving) return null;
setSaving(true);
setError(null);
try {
const next = await saveImmichSettings({
url: draft.url.trim(),
apiKey: draft.apiKey,
...patch,
});
setStatus(next);
setDraft({ url: next.url, apiKey: '' });
onChanged();
return next;
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not save the Immich connection');
return null;
} finally {
setSaving(false);
}
};
const test = async () => {
if (saving) return;
setSaving(true);
setError(null);
try {
const result = await testImmich();
onToast(
`Connected to Immich ${result.version} · ${result.albumCount} album${result.albumCount === 1 ? '' : 's'}`,
);
await load();
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not reach Immich');
} finally {
setSaving(false);
}
};
const loadAlbums = async () => {
if (albumsLoading) return;
setAlbumsLoading(true);
setError(null);
try {
setAlbums(await immichAlbums());
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not load Immich albums');
} finally {
setAlbumsLoading(false);
}
};
const startImport = async (album: ImmichAlbum) => {
if (job?.state === 'running') return;
if (
album.eventId &&
!window.confirm(
`“${album.name}” is already linked to a Luminary event. Importing again adds new photos and skips ones already here.`,
)
) {
return;
}
setError(null);
try {
setJob(await immichImportAlbum(album.id));
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not start the import');
}
};
const disconnect = async () => {
if (!window.confirm('Disconnect Immich? Imported events and photos stay in the library.')) return;
setSaving(true);
setError(null);
try {
const next = await disconnectImmich();
setStatus(next);
setDraft({ url: next.url, apiKey: '' });
setAlbums(null);
setJob(null);
onChanged();
onToast('Immich disconnected');
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not disconnect');
} finally {
setSaving(false);
}
};
const configured = Boolean(status?.configured);
const enabled = Boolean(status?.enabled);
const managed = Boolean(status?.managed);
const running = job?.state === 'running';
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal immich-modal">
<header className="modal-head">
<h2>Immich sync</h2>
<button className="icon-btn" onClick={onClose} title="Close (Esc)">
✕
</button>
</header>
<div className="modal-body">
<p className="muted small immich-intro">
{managed
? 'This server uses an Immich connection managed by an administrator. You can import albums, but the server address and API key are managed centrally.'
: 'Optional and private to your account. Your API key is stored encrypted on the server and is never sent to the browser. Nothing changes in the library until you turn this on.'}
</p>
{managed && status?.url && (
<div className="banner info">
Shared Immich server: <code>{status.url}</code>
</div>
)}
{loading && !status ? (
<p className="muted small">Checking…</p>
) : (
<>
<label className="field">
<span>Immich server</span>
<input
value={draft.url}
spellCheck={false}
placeholder="http://192.168.1.10:2283"
disabled={saving || managed}
onChange={(e) => setDraft((current) => ({ ...current, url: e.target.value }))}
onKeyDown={(e) => e.key === 'Enter' && void save()}
/>
</label>
<label className="field">
<span>API key</span>
<input
type="password"
value={draft.apiKey}
disabled={saving || managed}
placeholder={
managed
? 'Managed by an administrator'
: status?.hasKey
? 'Saved — type to replace'
: 'Immich API key'
}
onChange={(e) => setDraft((current) => ({ ...current, apiKey: e.target.value }))}
onKeyDown={(e) => e.key === 'Enter' && void save()}
/>
</label>
<div className="btn-row">
<button
className="btn primary"
onClick={() => void save()}
disabled={
saving || managed || !draft.url.trim() || (!draft.apiKey && !status?.hasKey)
}
>
{saving ? 'Saving…' : configured ? 'Save connection' : 'Connect'}
</button>
<button className="btn ghost" onClick={() => void test()} disabled={saving || !status?.hasKey}>
Test connection
</button>
{configured && !managed && (
<button className="btn ghost" onClick={() => void disconnect()} disabled={saving}>
Disconnect
</button>
)}
</div>
<p className="muted small">
Create a key in Immich under Account Settings → API Keys. It needs{' '}
<code>album.read</code>, <code>album.create</code>, <code>albumAsset.create</code>,{' '}
<code>asset.read</code>,
<code>asset.download</code>, <code>asset.upload</code> and <code>asset.update</code>;
add <code>tag.read</code>, <code>tag.create</code> and <code>tag.asset</code> for
keyword sync, and <code>asset.delete</code> only if you want originals moved to the
Immich trash after an upload.
</p>
{configured && (
<>
<div className="subhead">
<span>Integration</span>
<span className="muted small">
{status?.version ? `Immich ${status.version}` : 'Not tested yet'}
</span>
</div>
<label className="check-row">
<input
type="checkbox"
checked={enabled}
disabled={saving || managed}
onChange={(e) => void save({ enabled: e.target.checked })}
/>
Show Immich tools in my account (import albums, send edits back)
</label>
<p className="muted small">
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">
<input
type="checkbox"
checked={Boolean(status?.trashOriginal)}
disabled={saving || !enabled || managed}
onChange={(e) => void save({ trashOriginal: e.target.checked })}
/>
After uploading an edit, move the original to the Immich trash
</label>
<p className="muted small">
Recoverable in Immich. Luminary never permanently deletes the Immich original.
</p>
{enabled && (
<>
<div className="subhead">
<span>Albums</span>
<span className="muted small">Only linked albums sync automatically</span>
</div>
<div className="admin-table">
<div className="admin-row admin-row-head content-row">
<span>Album</span>
<span>Photos</span>
<span>Last sync</span>
<span>Actions</span>
</div>
{albums === null ? (
<p className="muted small">
{albumsLoading
? 'Loading albums…'
: 'Choose Refresh to list albums from this Immich account.'}
</p>
) : albums.length === 0 ? (
<p className="muted small">This Immich account has no albums.</p>
) : (
albums.map((album) => (
<div className="admin-row content-row" key={album.id}>
<div className="admin-event-name">
<strong>{album.name}</strong>
<div className="muted small">
{album.updatedAt
? `Updated ${fmtDate(album.updatedAt)}`
: 'Immich album'}
</div>
</div>
<span className="admin-num">{album.assetCount}</span>
<span className="admin-num">
{album.lastSyncAt ? fmtDate(album.lastSyncAt) : '—'}
</span>
<div className="admin-actions">
{album.kind === 'gallery' ? (
<span className="muted small">Gallery</span>
) : (
<button
className="btn small"
disabled={running}
onClick={() => void startImport(album)}
>
{album.eventId ? 'Sync again' : 'Import'}
</button>
)}
</div>
</div>
))
)}
</div>
<div className="btn-row">
<button
className="btn ghost"
onClick={() => void loadAlbums()}
disabled={albumsLoading}
>
{albumsLoading ? 'Loading…' : 'Refresh albums'}
</button>
</div>
</>
)}
{job && (
<div className="admin-note">
<p>
<strong>{job.albumName || 'Album'}</strong> ·{' '}
{job.state === 'running'
? job.scheduled
? 'Syncing in the background…'
: 'Importing…'
: job.state === 'done'
? 'Complete'
: 'Stopped'}
</p>
<div className="quota-meter" aria-label="Import progress">
<span
className={job.state === 'error' ? 'warn' : ''}
style={{
width: `${job.total ? Math.round(((job.done + job.skipped + job.failed) / job.total) * 100) : 0}%`,
}}
/>
</div>
<p className="muted small">
{job.done} imported · {job.skipped} already present
{job.failed ? ` · ${job.failed} failed` : ''}
</p>
{job.message && <p className="muted small">{job.message}</p>}
{job.errors.length > 0 && (
<ul className="muted small">
{job.errors.map((message) => (
<li key={message}>{message}</li>
))}
</ul>
)}
</div>
)}
</>
)}
</>
)}
{error && <div className="banner error">{error}</div>}
</div>
<footer className="modal-foot">
<span className="muted small">
Nothing uploads automatically. Use ☁ on an event to push its edits and originals.
</span>
<button className="btn" onClick={onClose}>
Done
</button>
</footer>
</div>
</div>
);
}
+116 -2
View File
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react'; import { useEffect, useMemo, useRef, useState } from 'react';
import { publishImmichOriginal } from '../lib/api';
import type { CloudImport, ImportProgress } from '../lib/import'; import type { CloudImport, ImportProgress } from '../lib/import';
import { importFiles, isSupportedFile } from '../lib/import'; import { importFiles, isSupportedFile } from '../lib/import';
import { isRawFile, RAW_ACCEPT } from '../lib/raw'; import { isRawFile, RAW_ACCEPT } from '../lib/raw';
@@ -13,6 +14,9 @@ interface Props {
onClose: () => void; onClose: () => void;
onImported: (photos: PhotoRecord[], eventId: string) => void; onImported: (photos: PhotoRecord[], eventId: string) => void;
onCreateEvent: (name: string) => Promise<EventRecord>; onCreateEvent: (name: string) => Promise<EventRecord>;
/** Turns on the optional Immich gallery for the created/target event. */
immichEnabled?: boolean;
onCreateImmichGallery?: (eventId: string) => Promise<EventRecord>;
cloud?: CloudImport | null; cloud?: CloudImport | null;
onNeedServer: () => void; onNeedServer: () => void;
} }
@@ -25,6 +29,8 @@ export default function ImportModal({
onClose, onClose,
onImported, onImported,
onCreateEvent, onCreateEvent,
immichEnabled = false,
onCreateImmichGallery,
cloud, cloud,
onNeedServer, onNeedServer,
}: Props) { }: Props) {
@@ -37,11 +43,16 @@ export default function ImportModal({
const [progress, setProgress] = useState<ImportProgress | null>(null); const [progress, setProgress] = useState<ImportProgress | null>(null);
const [failures, setFailures] = useState<string[]>([]); const [failures, setFailures] = useState<string[]>([]);
const [allowDuplicates, setAllowDuplicates] = useState(false); const [allowDuplicates, setAllowDuplicates] = useState(false);
const [createGallery, setCreateGallery] = useState(immichEnabled);
const [galleryCreated, setGalleryCreated] = useState(false);
const [galleryError, setGalleryError] = useState<string | null>(null);
const [summary, setSummary] = useState<{ const [summary, setSummary] = useState<{
imported: number; imported: number;
failed: number; failed: number;
skipped: number; skipped: number;
cancelled: boolean; cancelled: boolean;
published: number;
publishFailed: number;
} | null>(null); } | null>(null);
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const abortRef = useRef<AbortController | null>(null); const abortRef = useRef<AbortController | null>(null);
@@ -56,6 +67,12 @@ export default function ImportModal({
); );
const readyFiles = allowDuplicates ? files : files.filter((file) => !duplicateFiles.includes(file)); const readyFiles = allowDuplicates ? files : files.filter((file) => !duplicateFiles.includes(file));
useEffect(() => {
setGalleryCreated(false);
setGalleryError(null);
setCreateGallery(immichEnabled);
}, [eventId, immichEnabled]);
useEffect(() => { useEffect(() => {
// Capture phase: Escape closes this dialog even while a photo is open behind it. // Capture phase: Escape closes this dialog even while a photo is open behind it.
const onKey = (e: KeyboardEvent) => { const onKey = (e: KeyboardEvent) => {
@@ -91,16 +108,67 @@ export default function ImportModal({
const created = await onCreateEvent(newName || `Event ${new Date().toLocaleDateString()}`); const created = await onCreateEvent(newName || `Event ${new Date().toLocaleDateString()}`);
targetId = created.id; targetId = created.id;
} }
let hasGallery = Boolean(events.find((event) => event.id === targetId)?.immich);
if (
createGallery &&
!galleryCreated &&
onCreateImmichGallery &&
!hasGallery
) {
try {
await onCreateImmichGallery(targetId);
hasGallery = true;
setGalleryCreated(true);
} catch (err) {
setGalleryError(
err instanceof Error ? err.message : 'The Immich gallery could not be created',
);
}
}
const result = await importFiles(readyFiles, targetId, [], setProgress, cloud ?? null, controller.signal); const result = await importFiles(readyFiles, targetId, [], setProgress, cloud ?? null, controller.signal);
if (result.photos.length) onImported(result.photos, targetId); if (result.photos.length) onImported(result.photos, targetId);
let published = 0;
let publishFailed = 0;
const publishFailures: string[] = [];
if (hasGallery && immichEnabled && cloud && result.photos.length) {
const total = result.photos.length;
for (let index = 0; index < total; index++) {
if (controller.signal.aborted) break;
const photo = result.photos[index];
setProgress({
done: index,
total,
current: `Adding ${photo.name} to the Immich gallery…`,
});
try {
const pushed = await publishImmichOriginal(photo.id);
if (!pushed.skipped) published += 1;
} catch (err) {
publishFailed += 1;
publishFailures.push(
`${photo.name} — Immich: ${err instanceof Error ? err.message : 'upload failed'}`,
);
}
}
setProgress({ done: total, total, current: '' });
}
const skipped = allowDuplicates ? 0 : duplicateFiles.length; const skipped = allowDuplicates ? 0 : duplicateFiles.length;
setSummary({ setSummary({
imported: result.photos.length, imported: result.photos.length,
failed: result.failed.length, failed: result.failed.length,
skipped, skipped,
cancelled: Boolean(result.cancelled), cancelled: Boolean(result.cancelled),
published,
publishFailed,
}); });
if (result.failed.length) setFailures(result.failed.map((f) => `${f.name} — ${f.reason}`)); if (result.failed.length || publishFailures.length) {
setFailures([
...result.failed.map((f) => `${f.name} — ${f.reason}`),
...publishFailures,
]);
}
} catch (err) { } catch (err) {
setFailures([err instanceof Error ? err.message : 'Import failed']); setFailures([err instanceof Error ? err.message : 'Import failed']);
} finally { } finally {
@@ -152,6 +220,45 @@ export default function ImportModal({
</label> </label>
)} )}
{immichEnabled &&
!galleryCreated &&
!events.find((event) => event.id === eventId)?.immich && (
<>
<label className="check-row">
<input
type="checkbox"
checked={createGallery}
onChange={(e) => setCreateGallery(e.target.checked)}
disabled={busy}
/>
Create an Immich album and publish originals
</label>
<p className="muted small">
Luminary creates a matching album in Immich, uploads each original into it, and
saves edited versions to the same album as you work.
</p>
</>
)}
{galleryCreated && (
<p className="muted small">
Immich album linked. Imported originals will upload automatically, and edits will be
saved there as new versions.
</p>
)}
{!galleryCreated &&
immichEnabled &&
Boolean(events.find((event) => event.id === eventId)?.immich) && (
<p className="muted small">
Imported originals will be added to this event&apos;s Immich album automatically.
Edits will be saved there too.
</p>
)}
{galleryError && (
<div className="banner warn">
<strong>Immich gallery not created.</strong> {galleryError}
</div>
)}
<div <div
className={`dropzone ${dragOver ? 'over' : ''}`} className={`dropzone ${dragOver ? 'over' : ''}`}
onDragOver={(e) => { onDragOver={(e) => {
@@ -260,18 +367,25 @@ export default function ImportModal({
{summary.imported} imported {summary.imported} imported
{summary.skipped ? ` · ${summary.skipped} duplicate${summary.skipped === 1 ? '' : 's'} skipped` : ''} {summary.skipped ? ` · ${summary.skipped} duplicate${summary.skipped === 1 ? '' : 's'} skipped` : ''}
{summary.failed ? ` · ${summary.failed} failed` : ''} {summary.failed ? ` · ${summary.failed} failed` : ''}
{summary.published ? ` · ${summary.published} added to Immich` : ''}
{summary.publishFailed
? ` · ${summary.publishFailed} Immich upload${summary.publishFailed === 1 ? '' : 's'} failed`
: ''}
</span> </span>
<p className="muted small"> <p className="muted small">
{summary.cancelled {summary.cancelled
? 'Files already in progress were allowed to finish. The imported photos are in the catalog.' ? 'Files already in progress were allowed to finish. The imported photos are in the catalog.'
: 'New photos are selected in the library and ready to review.'} : 'New photos are selected in the library and ready to review.'}
{summary.published
? ' The imported photos were added to the event\'s Immich gallery.'
: ''}
</p> </p>
</div> </div>
)} )}
{failures.length > 0 && ( {failures.length > 0 && (
<div className="failures"> <div className="failures">
<strong>Some files could not be imported</strong> <strong>Some files had problems</strong>
<ul> <ul>
{failures.map((f) => ( {failures.map((f) => (
<li key={f}>{f}</li> <li key={f}>{f}</li>
+510
View File
@@ -0,0 +1,510 @@
import { useEffect, useState } from 'react';
import {
deleteTeamProfile,
loadTeamProfiles,
saveTeamProfile,
type TeamLensDraft,
type TeamLensProfile,
} from '../lib/lensProfiles';
import type { LensProfile, PhotoRecord } from '../types';
/**
* Calibrations the team measured for lenses the bundled database lacks. The
* numbers are stored on the server next to the bundled data, so everyone's
* editor and exports pick them up.
*/
interface Props {
photo: PhotoRecord;
/** Profile currently applied, used to prefill the form. */
profile?: LensProfile;
onClose: () => void;
/** Apply a saved calibration to the photo on screen. */
onUse: (profile: TeamLensProfile) => void;
}
const DISTORTION_MODEL_ID = { poly3: 0, poly5: 1, ptlens: 2 } as const;
const DISTORTION_MODEL_NAME = { 0: 'poly3', 1: 'poly5', 2: 'ptlens' } as const;
const TCA_MODEL_ID = { poly3: 0, linear: 1 } as const;
const TCA_MODEL_NAME = { 0: 'poly3', 1: 'linear' } as const;
type DistortionModel = keyof typeof DISTORTION_MODEL_ID;
type TcaModel = keyof typeof TCA_MODEL_ID;
interface DistortionRow {
focal: string;
model: DistortionModel;
a: string;
b: string;
c: string;
}
interface TcaRow {
focal: string;
model: TcaModel;
br: string;
cr: string;
vr: string;
bb: string;
cb: string;
vb: string;
}
interface VignettingRow {
focal: string;
aperture: string;
distance: string;
k1: string;
k2: string;
k3: string;
}
interface Draft {
id?: string;
maker: string;
model: string;
mount: string;
crop: string;
notes: string;
d: DistortionRow[];
t: TcaRow[];
v: VignettingRow[];
}
const num = (value: string) => (value.trim() === '' ? 0 : Number(value));
const text = (value: number) => (Number.isFinite(value) && value !== 0 ? String(value) : '');
function toDraft(profile: TeamLensProfile): Draft {
return {
id: profile.id,
maker: profile.maker,
model: profile.model,
mount: profile.mount,
crop: String(profile.crop),
notes: profile.notes,
d: profile.d.map(([focal, model, a, b, c]) => ({
focal: String(focal),
model: DISTORTION_MODEL_NAME[model as 0 | 1 | 2] ?? 'poly3',
a: text(a),
b: text(b),
c: text(c),
})),
t: profile.t.map(([focal, model, br, cr, vr, bb, cb, vb]) => ({
focal: String(focal),
model: TCA_MODEL_NAME[model as 0 | 1] ?? 'poly3',
br: text(br),
cr: text(cr),
vr: text(vr),
bb: text(bb),
cb: text(cb),
vb: text(vb),
})),
v: profile.v.map(([focal, aperture, distance, k1, k2, k3]) => ({
focal: String(focal),
aperture: String(aperture),
distance: text(distance),
k1: text(k1),
k2: text(k2),
k3: text(k3),
})),
};
}
function toPayload(draft: Draft): TeamLensDraft {
const focal = draft.d.find((row) => row.focal.trim())?.focal;
return {
id: draft.id,
maker: draft.maker.trim(),
model: draft.model.trim(),
mount: draft.mount.trim(),
crop: num(draft.crop) || 1,
aspect: 0,
centerX: 0,
centerY: 0,
notes: draft.notes.trim(),
d: draft.d
.filter((row) => row.focal.trim())
.map((row) => [
num(row.focal),
DISTORTION_MODEL_ID[row.model],
num(row.a),
num(row.b),
num(row.c),
0,
]),
t: draft.t
.filter((row) => row.focal.trim())
.map((row) => [
num(row.focal),
TCA_MODEL_ID[row.model],
num(row.br),
num(row.cr),
num(row.vr),
num(row.bb),
num(row.cb),
num(row.vb),
]),
v: draft.v
.filter((row) => row.focal.trim())
.map((row) => [
num(row.focal),
num(row.aperture),
num(row.distance) || 1000,
num(row.k1),
num(row.k2),
num(row.k3),
]),
};
}
const sampleCounts = (profile: TeamLensProfile) =>
[
profile.d.length ? `${profile.d.length} distortion` : '',
profile.t.length ? `${profile.t.length} CA` : '',
profile.v.length ? `${profile.v.length} vignetting` : '',
]
.filter(Boolean)
.join(' · ') || 'no samples';
export default function LensCalibrationModal({ photo, profile, onClose, onUse }: Props) {
const [profiles, setProfiles] = useState<TeamLensProfile[] | null>(null);
const [draft, setDraft] = useState<Draft | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const blank = (): Draft => ({
maker: profile?.maker ?? '',
model: profile?.model ?? photo.meta?.lens ?? '',
mount: '',
crop: String(profile?.crop ?? 1),
notes: '',
d: [
{
focal: photo.meta?.focal ? String(photo.meta.focal) : '',
model: 'ptlens',
a: '',
b: '',
c: '',
},
],
t: [],
v: [],
});
useEffect(() => {
let alive = true;
loadTeamProfiles(true)
.then((saved) => alive && setProfiles(saved))
.catch((err) => {
if (!alive) return;
setProfiles([]);
setError(err instanceof Error ? err.message : 'Could not load the team calibrations');
});
return () => {
alive = false;
};
}, []);
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
if (event.key !== 'Escape') return;
event.preventDefault();
event.stopImmediatePropagation();
if (!busy) onClose();
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [busy, onClose]);
const patch = (next: Partial<Draft>) => setDraft((current) => (current ? { ...current, ...next } : current));
const patchRow = <K extends 'd' | 't' | 'v'>(
key: K,
index: number,
patchValue: Partial<Draft[K][number]>,
) =>
setDraft((current) => {
if (!current) return current;
const rows = current[key].map((row, i) => (i === index ? { ...row, ...patchValue } : row));
return { ...current, [key]: rows } as Draft;
});
const addRow = (key: 'd' | 't' | 'v') =>
setDraft((current) => {
if (!current) return current;
const focal = photo.meta?.focal ? String(photo.meta.focal) : '';
const aperture = photo.meta?.aperture ? String(photo.meta.aperture) : '';
if (key === 'd') return { ...current, d: [...current.d, { focal, model: 'ptlens', a: '', b: '', c: '' }] };
if (key === 't') {
return {
...current,
t: [...current.t, { focal, model: 'poly3', br: '', cr: '', vr: '', bb: '', cb: '', vb: '' }],
};
}
return { ...current, v: [...current.v, { focal, aperture, distance: '1000', k1: '', k2: '', k3: '' }] };
});
const removeRow = (key: 'd' | 't' | 'v', index: number) =>
setDraft((current) => {
if (!current) return current;
return { ...current, [key]: current[key].filter((_, i) => i !== index) } as Draft;
});
const save = async () => {
if (!draft || busy) return;
setBusy(true);
setError(null);
try {
const saved = await saveTeamProfile(toPayload(draft));
setProfiles((current) =>
current
? [saved, ...current.filter((entry) => entry.id !== saved.id)]
: [saved],
);
setDraft(null);
onUse(saved);
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not save the calibration');
} finally {
setBusy(false);
}
};
const remove = async (entry: TeamLensProfile) => {
if (busy) return;
if (!window.confirm(`Delete the team calibration for ${entry.maker} ${entry.model}?`)) return;
setBusy(true);
setError(null);
try {
await deleteTeamProfile(entry.id);
setProfiles((current) => current?.filter((saved) => saved.id !== entry.id) ?? []);
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not delete the calibration');
} finally {
setBusy(false);
}
};
const field = (label: string, value: string, onChange: (value: string) => void, type = 'text') => (
<label className="lens-calib-field">
<span className="muted small">{label}</span>
<input
className="text-input"
type={type}
step="any"
value={value}
onChange={(event) => onChange(event.target.value)}
/>
</label>
);
return (
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal lens-calib-modal">
<header className="modal-head">
<div>
<span className="settings-kicker">Team</span>
<h2>Lens calibrations</h2>
</div>
<button className="icon-btn" onClick={onClose} title="Close">
✕
</button>
</header>
<div className="modal-body">
{draft ? (
<>
<p className="muted small lens-defaults-lead">
Enter the measurements from your calibration tool. Coefficients are used as measured:
distortion is a·r³ + b·r² + c·r + 1 for PanoTools, 1 + a·r² + b·r⁴ for poly5 and
1 + k₁·r² for poly3. Add a row per focal length you measured.
</p>
<div className="lens-calib-grid">
{field('Maker', draft.maker, (value) => patch({ maker: value }))}
{field('Model', draft.model, (value) => patch({ model: value }))}
{field('Mount', draft.mount, (value) => patch({ mount: value }))}
{field('Crop factor', draft.crop, (value) => patch({ crop: value }), 'number')}
</div>
{field('Notes', draft.notes, (value) => patch({ notes: value }))}
<section className="lens-calib-section">
<header>
<strong>Distortion</strong>
<button className="btn ghost tiny" onClick={() => addRow('d')}>
+ Sample
</button>
</header>
{draft.d.length === 0 && <p className="muted small">No distortion measured.</p>}
{draft.d.map((row, index) => (
<div className="lens-calib-row cols-distortion" key={index}>
{field('Focal mm', row.focal, (value) => patchRow('d', index, { focal: value }), 'number')}
<label className="lens-calib-field">
<span className="muted small">Model</span>
<select
className="text-input"
value={row.model}
onChange={(event) =>
patchRow('d', index, { model: event.target.value as DistortionModel })
}
>
<option value="ptlens">PanoTools</option>
<option value="poly3">poly3</option>
<option value="poly5">poly5</option>
</select>
</label>
{field('a', row.a, (value) => patchRow('d', index, { a: value }), 'number')}
{field('b', row.b, (value) => patchRow('d', index, { b: value }), 'number')}
{field('c', row.c, (value) => patchRow('d', index, { c: value }), 'number')}
<button
className="icon-btn"
title="Remove sample"
onClick={() => removeRow('d', index)}
>
✕
</button>
</div>
))}
</section>
<section className="lens-calib-section">
<header>
<strong>Chromatic aberration</strong>
<button className="btn ghost tiny" onClick={() => addRow('t')}>
+ Sample
</button>
</header>
{draft.t.length === 0 && <p className="muted small">No lateral CA measured.</p>}
{draft.t.map((row, index) => (
<div className="lens-calib-row cols-tca" key={index}>
{field('Focal mm', row.focal, (value) => patchRow('t', index, { focal: value }), 'number')}
<label className="lens-calib-field">
<span className="muted small">Model</span>
<select
className="text-input"
value={row.model}
onChange={(event) => patchRow('t', index, { model: event.target.value as TcaModel })}
>
<option value="poly3">poly3</option>
<option value="linear">linear</option>
</select>
</label>
{field('red b', row.br, (value) => patchRow('t', index, { br: value }), 'number')}
{field('red c', row.cr, (value) => patchRow('t', index, { cr: value }), 'number')}
{field('red v', row.vr, (value) => patchRow('t', index, { vr: value }), 'number')}
{field('blue b', row.bb, (value) => patchRow('t', index, { bb: value }), 'number')}
{field('blue c', row.cb, (value) => patchRow('t', index, { cb: value }), 'number')}
{field('blue v', row.vb, (value) => patchRow('t', index, { vb: value }), 'number')}
<button
className="icon-btn"
title="Remove sample"
onClick={() => removeRow('t', index)}
>
✕
</button>
</div>
))}
</section>
<section className="lens-calib-section">
<header>
<strong>Vignetting</strong>
<button className="btn ghost tiny" onClick={() => addRow('v')}>
+ Sample
</button>
</header>
{draft.v.length === 0 && <p className="muted small">No vignetting measured.</p>}
{draft.v.map((row, index) => (
<div className="lens-calib-row cols-vignetting" key={index}>
{field('Focal mm', row.focal, (value) => patchRow('v', index, { focal: value }), 'number')}
{field('Aperture', row.aperture, (value) => patchRow('v', index, { aperture: value }), 'number')}
{field('Distance', row.distance, (value) => patchRow('v', index, { distance: value }), 'number')}
{field('k₁', row.k1, (value) => patchRow('v', index, { k1: value }), 'number')}
{field('k₂', row.k2, (value) => patchRow('v', index, { k2: value }), 'number')}
{field('k₃', row.k3, (value) => patchRow('v', index, { k3: value }), 'number')}
<button
className="icon-btn"
title="Remove sample"
onClick={() => removeRow('v', index)}
>
✕
</button>
</div>
))}
</section>
</>
) : profiles === null ? (
<p className="muted small">Loading the team calibrations…</p>
) : (
<>
<p className="muted small lens-defaults-lead">
These are shared with everyone signed in to this library. The Optics panel finds them
by maker or model, next to the bundled profiles.
</p>
<div className="lens-defaults-list">
{profiles.length === 0 && (
<p className="muted small">No team calibrations yet — add the first one.</p>
)}
{profiles.map((entry) => (
<article className="lens-default-item" key={entry.id}>
<div className="lens-default-main">
<div className="lens-default-title">
<strong>
{entry.maker} {entry.model}
</strong>
<span className="muted small">crop {entry.crop}×</span>
</div>
<p className="lens-default-match">
{entry.mount || 'any mount'} <span className="muted small">· {sampleCounts(entry)}</span>
</p>
{entry.notes && <p className="muted small lens-default-meta">{entry.notes}</p>}
</div>
<div className="lens-default-actions">
<button className="btn ghost small" onClick={() => onUse(entry)}>
Use
</button>
<button className="btn ghost tiny" onClick={() => setDraft(toDraft(entry))}>
Edit
</button>
<button
className="btn ghost tiny"
disabled={busy}
onClick={() => void remove(entry)}
>
Delete
</button>
</div>
</article>
))}
</div>
</>
)}
{error && <p className="small lens-error">{error}</p>}
</div>
<footer className="modal-foot">
{draft ? (
<>
<button className="btn ghost" onClick={() => setDraft(null)} disabled={busy}>
Cancel
</button>
<button className="btn primary" onClick={() => void save()} disabled={busy}>
{busy ? 'Saving…' : draft.id ? 'Save calibration' : 'Add calibration'}
</button>
</>
) : (
<>
<button className="btn ghost" onClick={onClose}>
Done
</button>
<button className="btn primary" onClick={() => setDraft(blank())} disabled={busy}>
New calibration
</button>
</>
)}
</footer>
</div>
</div>
);
}
+32 -8
View File
@@ -1,8 +1,9 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { COLOR_LABELS, isEdited, thumbTransform } from '../lib/edits'; import { COLOR_LABELS, isEdited } from '../lib/edits';
import { draggedPhotoIds, endDrag, PHOTO_DRAG, startPhotoDrag } from '../lib/drag'; import { draggedPhotoIds, endDrag, PHOTO_DRAG, startPhotoDrag } from '../lib/drag';
import type { ColorLabel, Flag, PhotoRecord } from '../types'; import type { ColorLabel, Flag, PhotoRecord } from '../types';
import Stars, { ColorSwatches, FlagButtons } from './Stars'; import Stars, { ColorSwatches, FlagButtons } from './Stars';
import EditedImage from './EditedImage';
interface Props { interface Props {
photos: PhotoRecord[]; photos: PhotoRecord[];
@@ -15,12 +16,17 @@ interface Props {
onBulkRate: (rating: number) => void; onBulkRate: (rating: number) => void;
onBulkFlag: (flag: Flag) => void; onBulkFlag: (flag: Flag) => void;
onBulkColor: (color: ColorLabel) => void; onBulkColor: (color: ColorLabel) => void;
onSendToImmich?: () => void;
immichBusy?: boolean;
onDelete: () => void; onDelete: () => void;
onExport: () => void; onExport: () => void;
onCompare: () => void; onCompare: () => void;
onStack: () => void; onStack: () => void;
onVirtualCopy: () => void; onVirtualCopy: () => void;
onMerge: () => void; onMerge: () => void;
/** Re-decode the selected RAW files with the server's current pipeline. */
onReprocessRaw?: () => void;
reprocessBusy?: boolean;
onPrint: () => void; onPrint: () => void;
stacks: Map<string, { count: number; expanded: boolean }>; stacks: Map<string, { count: number; expanded: boolean }>;
onToggleStack: (id: string) => void; onToggleStack: (id: string) => void;
@@ -51,12 +57,16 @@ export default function LibraryGrid({
onBulkRate, onBulkRate,
onBulkFlag, onBulkFlag,
onBulkColor, onBulkColor,
onSendToImmich,
immichBusy = false,
onDelete, onDelete,
onExport, onExport,
onCompare, onCompare,
onStack, onStack,
onVirtualCopy, onVirtualCopy,
onMerge, onMerge,
onReprocessRaw,
reprocessBusy = false,
onPrint, onPrint,
stacks, stacks,
onToggleStack, onToggleStack,
@@ -277,6 +287,26 @@ export default function LibraryGrid({
<button className="btn ghost small" onClick={onMerge} disabled={selected.length < 2}> <button className="btn ghost small" onClick={onMerge} disabled={selected.length < 2}>
Merge Merge
</button> </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"
onClick={onSendToImmich}
disabled={immichBusy}
title="Send rendered edits for this selection to Immich"
>
Send to Immich
</button>
)}
<button className="btn ghost small" onClick={onExport}> <button className="btn ghost small" onClick={onExport}>
Export Export
</button> </button>
@@ -429,13 +459,7 @@ export default function LibraryGrid({
}} }}
> >
<div className="card-thumb"> <div className="card-thumb">
<img <EditedImage photo={p} alt={p.name} />
src={p.thumbUrl ?? p.thumb}
alt={p.name}
loading="lazy"
draggable={false}
style={{ transform: thumbTransform(p) }}
/>
<div className="card-badges"> <div className="card-badges">
{p.flag === 'pick' && <span className="badge pick">✓</span>} {p.flag === 'pick' && <span className="badge pick">✓</span>}
{p.flag === 'reject' && <span className="badge reject">✕</span>} {p.flag === 'reject' && <span className="badge reject">✕</span>}
+864 -49
View File
File diff suppressed because it is too large Load Diff
+13 -7
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { normalizeEdits } from '../lib/edits'; import { normalizeEdits } from '../lib/edits';
import { getBitmap } from '../lib/images'; import { get16BitSource, getBitmap } from '../lib/images';
import { Renderer, rotatedBounds } from '../gl/renderer'; import { Renderer, rotatedBounds } from '../gl/renderer';
import type { PhotoRecord, Preset } from '../types'; import type { PhotoRecord, Preset } from '../types';
@@ -14,7 +14,8 @@ const CACHE_LIMIT = 900;
const THUMB_EDGE = 200; const THUMB_EDGE = 200;
/** The crop is part of the key so a turn, straighten or flip refreshes the tiles. */ /** The crop is part of the key so a turn, straighten or flip refreshes the tiles. */
const keyOf = (photoId: string, presetId: string, crop: string) => `${photoId}|${presetId}|${crop}`; const keyOf = (photoId: string, presetId: string, crop: string, source: string) =>
`${photoId}|${presetId}|${crop}|${source}`;
export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> { export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> {
const [thumbs, setThumbs] = useState<Record<string, string>>({}); const [thumbs, setThumbs] = useState<Record<string, string>>({});
@@ -23,6 +24,10 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
const presetKey = presets.map((p) => p.id).join('|'); const presetKey = presets.map((p) => p.id).join('|');
const crop = photo.edits.crop; const crop = photo.edits.crop;
const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(','); const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(',');
// The preset previews keep the photo's camera profile, so a reprocess or a
// different profile has to invalidate tiles the same way a crop does.
const profile = photo.edits.cameraProfile;
const sourceKey = `${photo.previewVersion ?? 0}|${profile ? profile.matrix.join(',') : ''}`;
useEffect(() => { useEffect(() => {
let alive = true; let alive = true;
@@ -31,7 +36,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
const known: Record<string, string> = {}; const known: Record<string, string> = {};
for (const preset of presets) { for (const preset of presets) {
const hit = cache.get(keyOf(photo.id, preset.id, cropKey)); const hit = cache.get(keyOf(photo.id, preset.id, cropKey, sourceKey));
if (hit) known[preset.id] = hit; if (hit) known[preset.id] = hit;
} }
setThumbs(known); setThumbs(known);
@@ -43,6 +48,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
try { try {
const bitmap = await getBitmap(photo); const bitmap = await getBitmap(photo);
if (!alive) return; if (!alive) return;
const hdr = profile ? await get16BitSource(photo).catch(() => null) : null;
renderer = new Renderer(canvas); renderer = new Renderer(canvas);
// Every tile shows the photo as it is framed now, so a turned photo's // Every tile shows the photo as it is framed now, so a turned photo's
// presets are turned too. // presets are turned too.
@@ -52,18 +58,18 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
const scale = THUMB_EDGE / Math.max(cropW, cropH); const scale = THUMB_EDGE / Math.max(cropW, cropH);
const width = Math.max(1, Math.round(cropW * scale)); const width = Math.max(1, Math.round(cropW * scale));
const height = Math.max(1, Math.round(cropH * scale)); const height = Math.max(1, Math.round(cropH * scale));
renderer.setImage(bitmap); renderer.setImage(bitmap, hdr);
for (const preset of pending) { for (const preset of pending) {
if (!alive) break; if (!alive) break;
try { try {
renderer.render({ ...normalizeEdits(preset.edits), crop }, { renderer.render({ ...normalizeEdits(preset.edits), crop, cameraProfile: profile }, {
width, width,
height, height,
upscale: Math.max(width / cropW, height / cropH) > 1.05, upscale: Math.max(width / cropW, height / cropH) > 1.05,
}); });
const url = canvas.toDataURL('image/jpeg', 0.72); const url = canvas.toDataURL('image/jpeg', 0.72);
cache.set(keyOf(photo.id, preset.id, cropKey), url); cache.set(keyOf(photo.id, preset.id, cropKey, sourceKey), url);
setThumbs((prev) => ({ ...prev, [preset.id]: url })); setThumbs((prev) => ({ ...prev, [preset.id]: url }));
} catch { } catch {
// One bad preset must not stop the rest of the grid. // One bad preset must not stop the rest of the grid.
@@ -85,7 +91,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
renderer?.dispose(); renderer?.dispose();
}; };
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [photo.id, presetKey, cropKey]); }, [photo.id, presetKey, cropKey, sourceKey]);
return thumbs; return thumbs;
} }
+65 -1
View File
@@ -3,9 +3,11 @@ import {
addGalleryComment, addGalleryComment,
galleryDownloadAllUrl, galleryDownloadAllUrl,
galleryDownloadUrl, galleryDownloadUrl,
getGalleryStatus,
loadGallery, loadGallery,
setGalleryPick, setGalleryPick,
setGalleryReview, setGalleryReview,
unlockGallery,
} from '../lib/api'; } from '../lib/api';
import type { GalleryPayload, GalleryPhoto } 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 [saving, setSaving] = useState<Set<string>>(new Set());
const [commentDraft, setCommentDraft] = useState(''); const [commentDraft, setCommentDraft] = useState('');
const [feedbackBusy, setFeedbackBusy] = useState(false); const [feedbackBusy, setFeedbackBusy] = useState(false);
const [locked, setLocked] = useState(false);
const [password, setPassword] = useState('');
const [unlocking, setUnlocking] = useState(false);
const load = useCallback(async () => { const load = useCallback(async () => {
try { 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); const payload = await loadGallery(token, identity.current.id);
setData(payload); setData(payload);
setPicks(new Set(payload.photos.filter((p) => p.mine).map((p) => p.id))); 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]); }, [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) => { const rememberName = (name: string) => {
setClientName(name); setClientName(name);
try { 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) { if (!data) {
return ( return (
<div className="proof"> <div className="proof">
@@ -320,7 +382,7 @@ export default function ProofingGallery({ token }: { token: string }) {
> >
My picks {pickedCount ? `(${pickedCount})` : ''} My picks {pickedCount ? `(${pickedCount})` : ''}
</button> </button>
{pickedCount > 0 && ( {pickedCount > 0 && data.downloads?.allowed !== false && (
<a <a
className="btn ghost small" className="btn ghost small"
href={galleryDownloadAllUrl(token, identity.current.id)} 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-bar">
<div className="proof-lb-title"> <div className="proof-lb-title">
<span className="proof-lb-name">{lightboxPhoto.name}</span> <span className="proof-lb-name">{lightboxPhoto.name}</span>
{data.downloads?.allowed !== false && (
<a className="btn ghost small" href={galleryDownloadUrl(token, lightboxPhoto.id)} download> <a className="btn ghost small" href={galleryDownloadUrl(token, lightboxPhoto.id)} download>
Download Download
</a> </a>
)}
</div> </div>
<button <button
className={`proof-lb-pick ${picks.has(lightboxPhoto.id) ? 'on' : ''}`} 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 { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createShare, getShare, pushProof, revokeShare } from '../lib/api'; import { createShare, getShare, pushProof, revokeShare, saveShareSettings } from '../lib/api';
import type { ShareState } from '../lib/api'; import type { ShareState } from '../lib/api';
import { DEFAULT_EXPORT, renderPhotoBlob } from '../lib/export'; import { DEFAULT_EXPORT, renderPhotoBlob } from '../lib/export';
import type { ExportOptions } from '../lib/export'; import type { ExportOptions } from '../lib/export';
import type { PhotoRecord } from '../types'; import type { PhotoRecord } from '../types';
import { Renderer } from '../gl/renderer';
interface Props { interface Props {
event: { id: string; name: string }; event: { id: string; name: string };
@@ -50,6 +51,13 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
const [published, setPublished] = useState(0); const [published, setPublished] = useState(0);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [copied, setCopied] = useState(false); 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 () => { const refresh = useCallback(async () => {
try { 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 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; 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); setPublishing(true);
setPublished(0); setPublished(0);
setError(null); setError(null);
let done = 0; 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 { try {
for (const photo of photos) { 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)); const result = await pushProof(photo.id, await proofBase64(blob));
onProofPublished?.(photo.id, result.thumbUrl, result.proofAt); onProofPublished?.(photo.id, result.thumbUrl, result.proofAt);
done += 1; 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'); setError(err instanceof Error ? err.message : 'Could not publish the edited proofs');
return done; return done;
} finally { } finally {
shared?.dispose();
setPublishing(false); setPublishing(false);
} }
}; };
@@ -122,9 +160,10 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
setError(null); setError(null);
try { try {
await createShare(event.id); await createShare(event.id);
await refresh(); const state = await getShare(event.id);
setShare(state);
// A gallery without rendered proofs would show the unedited originals. // A gallery without rendered proofs would show the unedited originals.
await publishProofs(); await publishProofs(state.settings?.watermark ?? '');
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : 'Could not create the link'); setError(err instanceof Error ? err.message : 'Could not create the link');
} finally { } 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 () => { const revoke = async () => {
if (!window.confirm('Turn off this proofing link? Anyone using it will lose access and its picks will be cleared.')) { if (!window.confirm('Turn off this proofing link? Anyone using it will lose access and its picks will be cleared.')) {
return; return;
@@ -212,6 +273,91 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
</div> </div>
</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 className="share-publish">
<div> <div>
<strong>Edited proofs</strong> <strong>Edited proofs</strong>
+1
View File
@@ -36,6 +36,7 @@ const GROUPS: { title: string; rows: [string, string][] }[] = [
['C', 'Crop & straighten'], ['C', 'Crop & straighten'],
['Q', 'Spot healing brush'], ['Q', 'Spot healing brush'],
['M', 'Edit the selected local mask'], ['M', 'Edit the selected local mask'],
['O', 'Show or hide the mask tint'],
['Enter', 'Apply the crop'], ['Enter', 'Apply the crop'],
['\\ (hold)', 'Before / after'], ['\\ (hold)', 'Before / after'],
['1 – 5', 'Star rating'], ['1 – 5', 'Star rating'],
+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>
);
}
+1 -1
View File
@@ -38,7 +38,7 @@ export default function TopBar({
return ( return (
<header className="topbar"> <header className="topbar">
<div className="brand"> <div className="brand">
<span className="dot" /> <img className="brand-mark" src="/logo.png" alt="" height={20} />
Luminary Luminary
</div> </div>
<button <button
+40
View File
@@ -0,0 +1,40 @@
import { describe, expect, it } from 'vitest';
import { blendCoverage, maskSize } from './masks';
/** Coverage values are 0–1 inside the baker, which this keeps readable. */
describe('mask texture size', () => {
it('keeps square mask pixels so a round brush stays round', () => {
const tall = maskSize(3000, 9000);
expect(tall.h).toBeLessThanOrEqual(1400);
expect(tall.w / tall.h).toBeCloseTo(1 / 3, 2);
const wide = maskSize(15000, 1000);
expect(wide.h).toBeGreaterThanOrEqual(120);
expect(wide.w / wide.h).toBeCloseTo(15, 1);
});
it('uses the full width for a normal photo', () => {
expect(maskSize(3464, 5202)).toEqual({ w: 800, h: 1201 });
});
});
describe('mask group compositing', () => {
it('starts a group with the first shape whatever its mode says', () => {
expect(blendCoverage(0, 0.6, 'subtract', true)).toBe(0.6);
expect(blendCoverage(0, 0.6, 'intersect', true)).toBe(0.6);
});
it('unions added shapes instead of stacking them', () => {
expect(blendCoverage(0.4, 0.7, 'add', false)).toBe(0.7);
expect(blendCoverage(0.7, 0.4, 'add', false)).toBe(0.7);
});
it('subtracts coverage from the group', () => {
expect(blendCoverage(1, 0.25, 'subtract', false)).toBeCloseTo(0.75, 6);
expect(blendCoverage(1, 1, 'subtract', false)).toBe(0);
});
it('keeps only the overlap for an intersect shape', () => {
expect(blendCoverage(0.8, 0.5, 'intersect', false)).toBeCloseTo(0.4, 6);
expect(blendCoverage(0.8, 0, 'intersect', false)).toBe(0);
});
});
+162 -61
View File
@@ -1,15 +1,20 @@
import type { LocalLayer } from '../types'; import type { LocalComponent, LocalLayer } from '../types';
import { MAX_LOCAL_LAYERS } from '../lib/edits'; import { MAX_LOCAL_LAYERS } from '../lib/edits';
/** /**
* Local masks are baked on the CPU into one RGBA texture, one layer per * Local masks are baked on the CPU into two RGBA textures, one layer per
* channel, so the grade shader can apply up to four adjustments in a single * 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 * pass. A layer's mask is a group of shapes composited in order: add unions,
* the picture through crops, straightening, zoom and lens correction. * subtract cuts a hole, intersect keeps the overlap. The mask is source-space,
* which keeps brushes and gradients attached to the picture through crops,
* straightening, zoom and lens correction.
*/ */
export interface PackedMasks { export interface PackedMasks {
/** Layers 1–4, one per channel. */
data: Uint8Array; data: Uint8Array;
/** Layers 5–8, one per channel. */
data2: Uint8Array;
w: number; w: number;
h: number; h: number;
} }
@@ -20,20 +25,23 @@ export function maskSignature(layers: LocalLayer[], srcW: number, srcH: number)
srcW, srcW,
srcH, srcH,
layers: layers.slice(0, MAX_LOCAL_LAYERS).map((layer) => ({ layers: layers.slice(0, MAX_LOCAL_LAYERS).map((layer) => ({
kind: layer.kind, components: (layer.components ?? []).map((component) => ({
inverted: layer.inverted, kind: component.kind,
feather: layer.feather, mode: component.mode,
brush: layer.brush, inverted: component.inverted,
linear: layer.linear, feather: component.feather,
radial: layer.radial, brush: component.brush,
raster: layer.raster linear: component.linear,
radial: component.radial,
raster: component.raster
? { ? {
width: layer.raster.width, width: component.raster.width,
height: layer.raster.height, height: component.raster.height,
hash: rasterHash(layer.raster.data), hash: rasterHash(component.raster.data),
} }
: null, : null,
})), })),
})),
}); });
} }
@@ -46,8 +54,8 @@ function rasterHash(data: string) {
return `${data.length}:${hash >>> 0}`; return `${data.length}:${hash >>> 0}`;
} }
function drawRaster(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) { function drawRaster(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
const mask = layer.raster; const mask = component.raster;
if (!mask) return; if (!mask) return;
try { try {
const binary = atob(mask.data); const binary = atob(mask.data);
@@ -79,13 +87,13 @@ function makeCanvas(w: number, h: number) {
return canvas; return canvas;
} }
function drawRadial(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) { function drawRadial(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
const { cx, cy, rx, ry } = layer.radial; const { cx, cy, rx, ry } = component.radial;
ctx.save(); ctx.save();
ctx.translate(cx * w, cy * h); ctx.translate(cx * w, cy * h);
ctx.scale(Math.max(1, rx * w), Math.max(1, ry * h)); ctx.scale(Math.max(1, rx * w), Math.max(1, ry * h));
const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 1); const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 1);
const inner = Math.max(0, Math.min(0.98, 1 - layer.feather / 100)); const inner = Math.max(0, Math.min(0.98, 1 - component.feather / 100));
gradient.addColorStop(0, 'rgba(255,255,255,1)'); gradient.addColorStop(0, 'rgba(255,255,255,1)');
if (inner > 0.001) gradient.addColorStop(inner, 'rgba(255,255,255,1)'); if (inner > 0.001) gradient.addColorStop(inner, 'rgba(255,255,255,1)');
gradient.addColorStop(1, 'rgba(255,255,255,0)'); gradient.addColorStop(1, 'rgba(255,255,255,0)');
@@ -96,8 +104,8 @@ function drawRadial(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number,
ctx.restore(); ctx.restore();
} }
function drawLinear(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) { function drawLinear(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
const { x1, y1, x2, y2 } = layer.linear; const { x1, y1, x2, y2 } = component.linear;
const gradient = ctx.createLinearGradient(x1 * w, y1 * h, x2 * w, y2 * h); const gradient = ctx.createLinearGradient(x1 * w, y1 * h, x2 * w, y2 * h);
gradient.addColorStop(0, 'rgba(255,255,255,1)'); gradient.addColorStop(0, 'rgba(255,255,255,1)');
gradient.addColorStop(1, 'rgba(255,255,255,0)'); gradient.addColorStop(1, 'rgba(255,255,255,0)');
@@ -105,70 +113,163 @@ function drawLinear(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number,
ctx.fillRect(0, 0, w, h); ctx.fillRect(0, 0, w, h);
} }
function drawBrush(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) { /**
ctx.lineCap = 'round'; * One brush dab: white, solid out to `1 - feather` of the radius and fading to
ctx.lineJoin = 'round'; * nothing at the rim. Feather is the width of that band, so a stroke softens
for (const stroke of layer.brush.strokes) { * inside the brush outline instead of spreading a halo past it.
*/
function brushDab(feather: number) {
const size = 64;
const canvas = makeCanvas(size, size);
const ctx = canvas.getContext('2d');
if (!ctx) return canvas;
const r = size / 2;
// A hair of softness even at 0 keeps the rim from aliasing on screen.
const soft = Math.max(0.02, Math.min(1, feather / 100));
const gradient = ctx.createRadialGradient(r, r, r * (1 - soft), r, r, r);
gradient.addColorStop(0, 'rgba(255,255,255,1)');
gradient.addColorStop(0.45, 'rgba(255,255,255,0.88)');
gradient.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, size, size);
return canvas;
}
/**
* Stamps the dab along the path. A stroked line can only have a hard edge, so
* the stroke is drawn as overlapping dabs: the rim is the dab's falloff, which
* keeps the mask inside the brush circle and smooth at every size.
*/
function drawBrush(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
const dab = brushDab(component.feather);
for (const stroke of component.brush.strokes) {
if (!stroke.points.length) continue; if (!stroke.points.length) continue;
const width = Math.max(1, stroke.size * 2 * w); const radius = Math.max(1, stroke.size * w);
const stamp = (x: number, y: number) =>
ctx.drawImage(dab, x - radius, y - radius, radius * 2, radius * 2);
ctx.globalCompositeOperation = stroke.erase ? 'destination-out' : 'source-over'; ctx.globalCompositeOperation = stroke.erase ? 'destination-out' : 'source-over';
ctx.strokeStyle = 'rgba(255,255,255,1)'; const first = stroke.points[0];
ctx.fillStyle = 'rgba(255,255,255,1)'; stamp(first.x * w, first.y * h);
ctx.lineWidth = width; // Close enough that consecutive dabs overlap well inside the soft band.
if (stroke.points.length === 1) { const spacing = Math.max(0.75, radius * 0.35);
ctx.beginPath();
ctx.arc(stroke.points[0].x * w, stroke.points[0].y * h, width / 2, 0, Math.PI * 2);
ctx.fill();
continue;
}
ctx.beginPath();
ctx.moveTo(stroke.points[0].x * w, stroke.points[0].y * h);
for (let i = 1; i < stroke.points.length; i++) { for (let i = 1; i < stroke.points.length; i++) {
ctx.lineTo(stroke.points[i].x * w, stroke.points[i].y * h); const a = stroke.points[i - 1];
const b = stroke.points[i];
const dx = (b.x - a.x) * w;
const dy = (b.y - a.y) * h;
const steps = Math.max(1, Math.ceil(Math.hypot(dx, dy) / spacing));
for (let step = 1; step <= steps; step++) {
stamp(a.x * w + (dx * step) / steps, a.y * h + (dy * step) / steps);
}
} }
ctx.stroke();
} }
ctx.globalCompositeOperation = 'source-over'; ctx.globalCompositeOperation = 'source-over';
} }
function drawComponent(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
if (component.kind === 'radial') drawRadial(ctx, component, w, h);
else if (component.kind === 'linear') drawLinear(ctx, component, w, h);
else if (component.kind === 'raster') drawRaster(ctx, component, w, h);
else drawBrush(ctx, component, w, h);
}
/**
* Softens a mask rim without thinning what was painted. A plain blur pulls the
* stroke edge inward and drops thin strokes below full coverage, which reads as
* a weaker, uneven adjustment. Blurring a copy and keeping the original on top
* (lighten = max) softens only the outside of the edge: the painted core stays
* at 100% and the falloff grows past the brush outline.
*/
function featherMask(canvas: HTMLCanvasElement, radius: number) {
const out = makeCanvas(canvas.width, canvas.height);
const ctx = out.getContext('2d');
if (!ctx) return canvas;
// A sub-pixel blur keeps a feather of 0 from aliasing along the brush edge.
ctx.filter = `blur(${Math.max(0.4, radius)}px)`;
ctx.drawImage(canvas, 0, 0);
ctx.filter = 'none';
ctx.globalCompositeOperation = 'lighten';
ctx.drawImage(canvas, 0, 0);
ctx.globalCompositeOperation = 'source-over';
return out;
}
/**
* How one shape's coverage joins the accumulated mask inside its layer. The
* first shape starts the group, so its mode is ignored: there is nothing to
* subtract from or intersect with yet.
*/
export function blendCoverage(
acc: number,
value: number,
mode: LocalComponent['mode'],
first: boolean,
) {
if (first) return value;
if (mode === 'subtract') return acc * (1 - value);
if (mode === 'intersect') return acc * value;
return Math.max(acc, value);
}
/**
* Mask texture size. Pixels are square, so both dimensions scale together with
* the source: clamping only the height would squeeze every round dab into an
* ellipse on tall or wide frames, so the width shrinks instead.
*/
export function maskSize(srcW: number, srcH: number) {
const safeW = Math.max(1, srcW);
const safeH = Math.max(1, srcH);
let w = 800;
let h = Math.round((w * safeH) / safeW);
const limit = h > 1400 ? 1400 : h < 120 ? 120 : 0;
if (limit) {
h = limit;
w = Math.max(160, Math.round((h * safeW) / safeH));
}
return { w, h: Math.max(1, h) };
}
export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number): PackedMasks { export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number): PackedMasks {
const w = 800; const { w, h } = maskSize(srcW, srcH);
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 out = new Uint8Array(w * h * 4);
const out2 = new Uint8Array(w * h * 4);
const count = Math.min(MAX_LOCAL_LAYERS, layers.length); 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++) { for (let index = 0; index < count; index++) {
const layer = layers[index]; const layer = layers[index];
const components = layer.components ?? [];
const acc = new Uint8Array(w * h);
let first = true;
for (const component of components) {
const canvas = makeCanvas(w, h); const canvas = makeCanvas(w, h);
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
if (!ctx) continue; if (!ctx) continue;
ctx.clearRect(0, 0, w, h); ctx.clearRect(0, 0, w, h);
drawComponent(ctx, component, w, h);
if (layer.kind === 'radial') drawRadial(ctx, layer, w, h);
else if (layer.kind === 'linear') drawLinear(ctx, layer, w, h);
else if (layer.kind === 'raster') drawRaster(ctx, layer, w, h);
else drawBrush(ctx, layer, w, h);
let source = canvas; let source = canvas;
if ((layer.kind === 'brush' || layer.kind === 'raster') && layer.feather > 0) { if (component.kind === 'raster') {
const blur = makeCanvas(w, h); // Generated masks are low-resolution coverage, so their feather is tied
const bctx = blur.getContext('2d'); // to the frame width and only ever loosens the outside edge.
if (bctx) { source = featherMask(canvas, ((component.feather / 100) * w) / 16);
bctx.filter = `blur(${Math.max(0.1, ((layer.feather / 100) * w) / 16)}px)`;
bctx.drawImage(canvas, 0, 0);
source = blur;
}
} }
const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data; const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data;
if (!pixels) continue; if (!pixels) continue;
const channel = index; for (let p = 0, o = 0; p < pixels.length; p += 4, o++) {
for (let p = 0, o = 0; p < pixels.length; p += 4, o += 4) { let value = pixels[p + 3] / 255;
const alpha = pixels[p + 3]; if (component.inverted) value = 1 - value;
out[o + channel] = layer.inverted ? 255 - alpha : alpha; acc[o] = Math.round(blendCoverage(acc[o] / 255, value, component.mode, first) * 255);
} }
first = false;
} }
return { data: out, w, h }; const channel = index % 4;
const target = index < 4 ? out : out2;
for (let o = 0; o < acc.length; o++) target[o * 4 + channel] = acc[o];
}
return { data: out, data2: out2, w, h };
} }
+702 -110
View File
File diff suppressed because it is too large Load Diff
-83
View File
@@ -1,83 +0,0 @@
/**
* The published package's `types` entry points at a file that is not shipped in
* 0.1.3, so declare the small surface we use here.
*/
declare module '@neoanaloglabkk/lensfun-wasm' {
export interface LensfunInitOptions {
moduleFactory?: (options?: Record<string, unknown>) => Promise<unknown>;
moduleJsUrl?: string;
wasmUrl?: string;
dataUrl?: string;
dbPath?: string;
autoInitDb?: boolean;
locateFile?: (path: string, prefix: string) => string;
}
export interface LensMatch {
handle: number;
maker: string;
model: string;
score: number;
minFocal: number;
maxFocal: number;
minAperture: number;
maxAperture: number;
cropFactor: number;
}
export interface CameraMatch {
maker: string;
model: string;
variant: string;
mount: string;
cropFactor: number;
score: number;
}
export interface SearchLensesInput {
lensMaker?: string;
lensModel: string;
cameraMaker?: string;
cameraModel?: string;
searchFlags?: number;
}
export interface SearchCamerasInput {
maker?: string;
model?: string;
searchFlags?: number;
}
export interface CorrectionInput {
lensHandle: number;
width: number;
height: number;
focal: number;
crop: number;
step?: number;
reverse?: boolean;
includeTca?: boolean;
includeVignetting?: boolean;
aperture?: number;
distance?: number;
}
export interface CorrectionMaps {
gridWidth: number;
gridHeight: number;
step: number;
geometry: Float32Array;
tca?: Float32Array;
vignetting?: Float32Array;
}
export interface LensfunClient {
dispose(): void;
searchLenses(input: SearchLensesInput): LensMatch[];
searchCameras(input: SearchCamerasInput): CameraMatch[];
getAvailableModifications(lensHandle: number, crop: number): number;
buildCorrectionMaps(input: CorrectionInput): CorrectionMaps;
}
export function createLensfun(options?: LensfunInitOptions): Promise<LensfunClient>;
}
+308 -2
View File
@@ -1,4 +1,4 @@
import type { EventRecord, PhotoRecord, Preset } from '../types'; import type { EventRecord, Flag, PhotoRecord, Preset } from '../types';
export interface Health { export interface Health {
ok: boolean; ok: boolean;
@@ -39,7 +39,7 @@ export class ApiError extends Error {
} }
} }
async function request<T>(path: string, init?: RequestInit): Promise<T> { export async function request<T>(path: string, init?: RequestInit): Promise<T> {
let res: Response; let res: Response;
try { try {
res = await fetch(path, { credentials: 'same-origin', ...init }); res = await fetch(path, { credentials: 'same-origin', ...init });
@@ -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> { export function pushPhoto(photo: PhotoRecord): Promise<PhotoRecord> {
return request<{ photo: PhotoRecord }>(`/api/photos/${encodeURIComponent(photo.id)}`, { return request<{ photo: PhotoRecord }>(`/api/photos/${encodeURIComponent(photo.id)}`, {
method: 'PUT', method: 'PUT',
@@ -221,10 +236,26 @@ export interface ShareFeedback {
createdAt: number; createdAt: number;
} }
export interface ShareSettings {
passwordSet: boolean;
expiresAt: number | null;
watermark: string;
allowDownloads: boolean;
downloadCap: number;
downloadCount: number;
}
export interface ShareState { export interface ShareState {
token: string | null; token: string | null;
picks: { photoId: string; clientName: string }[]; picks: { photoId: string; clientName: string }[];
feedback?: ShareFeedback[]; feedback?: ShareFeedback[];
settings?: ShareSettings | null;
}
export interface GalleryStatus {
locked: boolean;
expiresAt: number | null;
allowDownloads: boolean;
} }
export interface GalleryComment { export interface GalleryComment {
@@ -253,6 +284,8 @@ export interface GalleryPayload {
photographer: string; photographer: string;
photos: GalleryPhoto[]; photos: GalleryPhoto[];
picks: { total: number; clients: number }; picks: { total: number; clients: number };
downloads?: { allowed: boolean; remaining: number | null };
watermark?: string;
} }
export function getShare(eventId: string): Promise<ShareState> { 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}`; 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> { export function revokeShare(eventId: string): Promise<void> {
return request(`/api/events/${encodeURIComponent(eventId)}/share`, { method: 'DELETE' }); return request(`/api/events/${encodeURIComponent(eventId)}/share`, { method: 'DELETE' });
} }
@@ -418,6 +516,75 @@ export interface MailStatus {
gmail: boolean; gmail: boolean;
} }
export interface ImmichStatus {
configured: boolean;
enabled: boolean;
/** The connection is configured server-wide by an administrator. */
managed?: boolean;
url: string;
hasKey: boolean;
autoSync: boolean;
syncMinutes: number;
trashOriginal: boolean;
syncMetadata: boolean;
lastSyncAt: number | null;
lastError: string | null;
version: string | null;
albumCount: number;
}
export interface ImmichAlbum {
id: string;
name: string;
assetCount: number;
/** A gallery created from a Luminary event is an upload destination, not an import source. */
kind?: 'import' | 'gallery';
updatedAt: number | null;
startDate: number | null;
endDate: number | null;
thumbnailAssetId: string | null;
/** Set when this account already imported the album. */
eventId?: string | null;
lastSyncAt?: number | null;
}
export interface ImmichImportJob {
id: string;
albumId: string;
albumName: string;
eventId: string | null;
state: 'running' | 'done' | 'error';
scheduled?: boolean;
total: number;
done: number;
skipped: number;
failed: number;
bytes: number;
message: string;
errors: string[];
startedAt: number;
finishedAt: number | null;
}
export interface ImmichTestResult {
ok: boolean;
url: string;
version: string;
major: number;
albumCount: number;
}
export interface ImmichPushResult {
ok: boolean;
assetId: string;
alreadyPushed: boolean;
/** True when the photo already existed in Immich and no upload was made. */
skipped?: boolean;
trashed: boolean;
associations: Partial<Record<'albums' | 'stack' | 'favorite' | 'sidecar', boolean>>;
warning: string;
}
export interface AdminOverview { export interface AdminOverview {
users: AdminUser[]; users: AdminUser[];
events: AdminEvent[]; events: AdminEvent[];
@@ -426,6 +593,7 @@ export interface AdminOverview {
storage: { root: string; defaultRoot: string; custom: boolean; diskBytes?: number }; storage: { root: string; defaultRoot: string; custom: boolean; diskBytes?: number };
quotas: AdminQuota[]; quotas: AdminQuota[];
mail: MailStatus; mail: MailStatus;
immich: ImmichStatus;
} }
export interface StorageChange { export interface StorageChange {
@@ -576,6 +744,144 @@ export function adminSetStorage(root: string): Promise<StorageChange> {
}); });
} }
export function adminSaveImmich(input: {
url: string;
apiKey?: string;
enabled?: boolean;
}): Promise<ImmichStatus> {
return request<{ immich: ImmichStatus }>('/api/admin/immich', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
}).then((res) => res.immich);
}
export function adminTestImmich(): Promise<ImmichTestResult> {
return request<ImmichTestResult>('/api/admin/immich/test', { method: 'POST' });
}
export interface PreviewRebuildStatus {
state: 'idle' | 'running' | 'done';
total: number;
/** Photos attempted so far, including the failures. */
done: number;
failed: number;
/** Rebuilt proxies that also wrote a 16-bit sidecar. */
sidecars: number;
startedAt: number | null;
finishedAt: number | null;
errors: string[];
}
/** Starts a server-side rebuild and returns its first progress snapshot. */
export function adminRebuildPreviews(): Promise<PreviewRebuildStatus> {
return request<{ rebuild: PreviewRebuildStatus }>('/api/admin/previews/rebuild', {
method: 'POST',
}).then((res) => res.rebuild);
}
export function adminPreviewRebuildStatus(): Promise<PreviewRebuildStatus> {
return request<{ rebuild: PreviewRebuildStatus }>('/api/admin/previews/rebuild').then(
(res) => res.rebuild,
);
}
export function adminDisconnectImmich(): Promise<ImmichStatus> {
return request<{ immich: ImmichStatus }>('/api/admin/immich', { method: 'DELETE' }).then(
(res) => res.immich,
);
}
export function getImmichStatus(): Promise<ImmichStatus> {
return request<{ immich: ImmichStatus }>('/api/immich').then((res) => res.immich);
}
export function saveImmichSettings(input: {
url: string;
apiKey?: string;
enabled?: boolean;
autoSync?: boolean;
syncMinutes?: number;
trashOriginal?: boolean;
syncMetadata?: boolean;
}): Promise<ImmichStatus> {
return request<{ immich: ImmichStatus }>('/api/immich', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
}).then((res) => res.immich);
}
export function disconnectImmich(): Promise<ImmichStatus> {
return request<{ immich: ImmichStatus }>('/api/immich', { method: 'DELETE' }).then(
(res) => res.immich,
);
}
export function testImmich(): Promise<ImmichTestResult> {
return request<ImmichTestResult>('/api/immich/test', { method: 'POST' });
}
export function pushImmichPhoto(photoId: string, jpegBase64: string): Promise<ImmichPushResult> {
return request<ImmichPushResult>(
`/api/immich/photos/${encodeURIComponent(photoId)}/push`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ jpeg: jpegBase64 }),
},
);
}
export interface ImmichQueueEntry {
photoId: string;
name: string;
/** Upload the untouched original, or the current rendered edit. */
mode: 'original' | 'edit';
}
/** The manual push plan for an event: originals and edits changed since last push. */
export function immichEventQueue(
eventId: string,
): Promise<{ queue: ImmichQueueEntry[]; total: number }> {
return request(`/api/immich/events/${encodeURIComponent(eventId)}/queue`);
}
export function publishImmichOriginal(photoId: string): Promise<ImmichPushResult> {
return request(
`/api/immich/photos/${encodeURIComponent(photoId)}/publish`,
{ method: 'POST' },
);
}
export function createImmichEventAlbum(
eventId: string,
name: string,
): Promise<{ album: ImmichAlbum; event: EventRecord }> {
return request('/api/immich/albums', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ eventId, name }),
});
}
export function immichAlbums(): Promise<ImmichAlbum[]> {
return request<{ albums: ImmichAlbum[] }>('/api/immich/albums').then((res) => res.albums ?? []);
}
export function immichImportAlbum(albumId: string): Promise<ImmichImportJob> {
return request<{ job: ImmichImportJob }>(
`/api/immich/albums/${encodeURIComponent(albumId)}/import`,
{ method: 'POST' },
).then((res) => res.job);
}
export function getImmichJob(jobId: string): Promise<ImmichImportJob> {
return request<{ job: ImmichImportJob }>(
`/api/immich/jobs/${encodeURIComponent(jobId)}`,
).then((res) => res.job);
}
export function pushPresets(presets: Preset[]): Promise<void> { export function pushPresets(presets: Preset[]): Promise<void> {
return request('/api/presets', { return request('/api/presets', {
method: 'PUT', method: 'PUT',
+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 }; 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 };
}
}
+146
View File
@@ -0,0 +1,146 @@
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('leaves a saturated object that runs off the frame out of the subject', () => {
// Grass around a red mat that spans the whole bottom edge, with the person
// sitting in the middle: the mat touches three borders, the person none.
const width = 96;
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 mat = y > height * 0.6;
const person = x > width * 0.42 && x < width * 0.58 && y > height * 0.35 && y < height * 0.68;
if (person) {
data[o] = 40;
data[o + 1] = 70;
data[o + 2] = 180;
} else if (mat) {
data[o] = 200;
data[o + 1] = 30;
data[o + 2] = 40;
} else {
data[o] = 90;
data[o + 1] = 130;
data[o + 2] = 70;
}
data[o + 3] = 255;
}
}
const mask = segmentMask(data, width, height, 'subject');
const at = (x: number, y: number) => mask[Math.round(y) * width + Math.round(x)];
expect(at(width * 0.5, height * 0.5)).toBe(255);
expect(at(4, height * 0.9)).toBe(0);
expect(at(width * 0.5, height * 0.95)).toBe(0);
});
it('does not swallow a dark scene with no clear subject', () => {
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 streak = y > 30 && y < 33 && x > 8 && x < 52;
data[o] = streak ? 220 : 18;
data[o + 1] = streak ? 90 : 22;
data[o + 2] = streak ? 40 : 34;
data[o + 3] = 255;
}
}
const mask = segmentMask(data, width, height, 'subject');
let inside = 0;
for (const value of mask) if (value) inside++;
expect(inside / mask.length).toBeLessThan(0.6);
});
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);
});
});
+235 -44
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 * 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. * event edit: the subject, the sky and the background around the subject.
* *
* The estimator works from a downsampled preview. It combines distance from * The estimator works from a downsampled preview and is deliberately
* the border colour (the usual studio/event background) with a centre bias, * model-free: there is nothing to download and it runs in a few milliseconds.
* saturation and a vertical sky prior. This is intentionally lightweight: it * It builds a coarse colour histogram of the frame's border (the usual studio,
* has no model download and produces a low-resolution raster that the normal * venue or sky background), scores every pixel against that model plus a centre
* mask pipeline feathers and scales. The output is editable like any brush * prior, splits the score map with an Otsu threshold, then keeps the connected
* mask, so a missed edge can be fixed without another model pass. * 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> { 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 height = Math.max(48, Math.round((width * bitmap.height) / Math.max(1, bitmap.width)));
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
canvas.width = width; 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'); if (!ctx) throw new Error('Could not analyse the image for a mask');
ctx.drawImage(bitmap, 0, 0, width, height); ctx.drawImage(bitmap, 0, 0, width, height);
const image = ctx.getImageData(0, 0, width, height); const image = ctx.getImageData(0, 0, width, height);
const data = image.data; const mask = segmentMask(image.data, width, height, kind);
const count = width * height; return { data: encodeBase64(mask), width, height };
}
const subject = new Float32Array(count); /**
const sky = new Float32Array(count); * Pure segmentation step, exported so it can be exercised without a canvas.
const border = borderColor(data, width, height); * 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++) { for (let y = 0; y < height; y++) {
const ny = y / Math.max(1, height - 1); 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 r = data[o] / 255;
const g = data[o + 1] / 255; const g = data[o + 1] / 255;
const b = data[o + 2] / 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 value = 0.2126 * r + 0.7152 * g + 0.0722 * b;
const center = 1 - Math.min(1, Math.sqrt(((x / width - 0.5) * 1.7) ** 2 + ((y / height - 0.5) * 1.35) ** 2)); luma[i] = value;
const maxc = Math.max(r, g, b); const maxc = Math.max(r, g, b);
const minc = Math.min(r, g, b); const minc = Math.min(r, g, b);
const sat = maxc > 0.001 ? (maxc - minc) / maxc : 0; 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; 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); 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; 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 threshold = otsuThreshold(score);
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 mask = new Uint8Array(count); const mask = new Uint8Array(count);
for (let i = 0; i < count; i++) { for (let i = 0; i < count; i++) mask[i] = score[i] >= threshold ? 255 : 0;
const on = raw[i] >= threshold;
mask[i] = (kind === 'background' ? !on : on) ? 255 : 0;
}
smooth(mask, width, height);
smooth(mask, width, height);
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] { interface BorderModel {
let r = 0; /** 4×4×4 RGB histogram of the frame's edge, normalised to the fullest bin. */
let g = 0; probability: (r: number, g: number, b: number) => number;
let b = 0; 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; 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; const o = (y * width + x) * 4;
r += data[o]; const r = data[o];
g += data[o + 1]; const g = data[o + 1];
b += data[o + 2]; const b = data[o + 2];
n++; 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++) { for (let x = 0; x < width; x++) {
add(x, 0); push(x, 0);
add(x, height - 1); push(x, height - 1);
} }
for (let y = 1; y < height - 1; y++) { for (let y = 0; y < height; y++) {
add(0, y); push(0, y);
add(width - 1, 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) { 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);
}
+29 -2
View File
@@ -1,7 +1,8 @@
import type { EventRecord, PhotoRecord } from '../types'; import type { EventRecord, PhotoRecord } from '../types';
import { withoutLensVignetting } from './edits';
const DB_NAME = 'lumenroom'; const DB_NAME = 'lumenroom';
const DB_VERSION = 1; const DB_VERSION = 2;
let dbPromise: Promise<IDBDatabase> | null = null; let dbPromise: Promise<IDBDatabase> | null = null;
@@ -9,7 +10,7 @@ export function openDB(): Promise<IDBDatabase> {
if (dbPromise) return dbPromise; if (dbPromise) return dbPromise;
dbPromise = new Promise((resolve, reject) => { dbPromise = new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VERSION); const req = indexedDB.open(DB_NAME, DB_VERSION);
req.onupgradeneeded = () => { req.onupgradeneeded = (event) => {
const db = req.result; const db = req.result;
if (!db.objectStoreNames.contains('photos')) { if (!db.objectStoreNames.contains('photos')) {
const store = db.createObjectStore('photos', { keyPath: 'id' }); const store = db.createObjectStore('photos', { keyPath: 'id' });
@@ -18,6 +19,11 @@ export function openDB(): Promise<IDBDatabase> {
if (!db.objectStoreNames.contains('assets')) db.createObjectStore('assets'); if (!db.objectStoreNames.contains('assets')) db.createObjectStore('assets');
if (!db.objectStoreNames.contains('events')) db.createObjectStore('events', { keyPath: 'id' }); if (!db.objectStoreNames.contains('events')) db.createObjectStore('events', { keyPath: 'id' });
if (!db.objectStoreNames.contains('kv')) db.createObjectStore('kv'); if (!db.objectStoreNames.contains('kv')) db.createObjectStore('kv');
// v2: applying a lens profile used to enable its vignetting correction,
// and the corner gain over-exposed the edges. Clear that flag once, here,
// instead of on every load, so a profile the user enables afterwards stays
// enabled.
if (event.oldVersion < 2) clearStoredLensVignetting(req.transaction);
}; };
req.onsuccess = () => resolve(req.result); req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error ?? new Error('Unable to open database')); req.onerror = () => reject(req.error ?? new Error('Unable to open database'));
@@ -25,6 +31,22 @@ export function openDB(): Promise<IDBDatabase> {
return dbPromise; return dbPromise;
} }
/**
* Walks the photo store inside the version-change transaction and clears any
* stored lens vignetting flag. Runs once, on the database upgrade.
*/
function clearStoredLensVignetting(tx: IDBTransaction | null) {
if (!tx) return;
const cursorRequest = tx.objectStore('photos').openCursor();
cursorRequest.onsuccess = () => {
const cursor = cursorRequest.result;
if (!cursor) return;
const cleared = withoutLensVignetting(cursor.value as PhotoRecord);
if (cleared) cursor.update(cleared);
cursor.continue();
};
}
function wrap<T>(request: IDBRequest<T>): Promise<T> { function wrap<T>(request: IDBRequest<T>): Promise<T> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result); request.onsuccess = () => resolve(request.result);
@@ -64,6 +86,11 @@ export async function getAsset(id: string): Promise<Blob | undefined> {
return wrap((await store('assets')).get(id) as IDBRequest<Blob | undefined>); return wrap((await store('assets')).get(id) as IDBRequest<Blob | undefined>);
} }
/** Drop one cached file without touching its photo record. */
export async function deleteAsset(id: string): Promise<void> {
await wrap((await store('assets', 'readwrite')).delete(id));
}
export async function getAllEvents(): Promise<EventRecord[]> { export async function getAllEvents(): Promise<EventRecord[]> {
return wrap((await store('events')).getAll() as IDBRequest<EventRecord[]>); return wrap((await store('events')).getAll() as IDBRequest<EventRecord[]>);
} }
+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,
};
}
+72
View File
@@ -0,0 +1,72 @@
import { describe, expect, it } from 'vitest';
import {
loadSavedCameraProfiles,
photosForCamera,
removeCameraProfile,
saveCameraProfile,
savedProfilesForCamera,
type ProfileStore,
} from './dcpLibrary';
function memoryStore(): ProfileStore {
const data = new Map<string, string>();
return {
getItem: (key) => data.get(key) ?? null,
setItem: (key, value) => {
data.set(key, value);
},
};
}
const matrix = [0.4, 0.3, 0.3, 0.2, 0.7, 0.1, 0.01, 0.09, 0.9];
describe('camera profile library', () => {
it('keeps a profile and finds it by camera body', () => {
const store = memoryStore();
saveCameraProfile({ name: 'Studio DCP', camera: 'Nikon D700', matrix }, store);
const saved = loadSavedCameraProfiles(store);
expect(saved).toHaveLength(1);
expect(saved[0].matrix).toEqual(matrix);
expect(savedProfilesForCamera(saved, 'NIKON CORPORATION D700')).toHaveLength(1);
expect(savedProfilesForCamera(saved, 'Canon EOS 5D')).toHaveLength(0);
});
it('replaces the same name for the same body instead of duplicating it', () => {
const store = memoryStore();
saveCameraProfile({ name: 'Studio', camera: 'Nikon D700', matrix }, store);
const next = saveCameraProfile(
{ name: 'Studio', camera: 'nikon d700', matrix: matrix.map((value) => value * 0.9) },
store,
);
expect(next).toHaveLength(1);
expect(next[0].matrix[0]).toBeCloseTo(0.36, 6);
});
it('forgets a profile and tolerates corrupt storage', () => {
const store = memoryStore();
const saved = saveCameraProfile({ name: 'Studio', camera: 'Nikon D700', matrix }, store);
expect(removeCameraProfile(saved[0].id, store)).toHaveLength(0);
store.setItem('lumenroom.cameraProfiles', JSON.stringify([{ id: 'x', name: 'bad', matrix: [1] }]));
expect(loadSavedCameraProfiles(store)).toHaveLength(0);
});
it('collects the camera-native raws of one body for a bulk apply', () => {
const photos = [
{ id: 'a', raw: true, decode: 'libraw', meta: { camera: 'NIKON CORPORATION D700' } },
{ id: 'b', raw: true, decode: 'libraw', meta: { camera: 'Nikon D700' } },
{ id: 'c', raw: true, decode: 'embedded', meta: { camera: 'Nikon D700' } },
{ id: 'd', raw: false, meta: { camera: 'Nikon D700' } },
{ id: 'e', raw: true, decode: 'libraw', deletedAt: 1, meta: { camera: 'Nikon D700' } },
{ id: 'f', raw: true, decode: 'libraw', meta: { camera: 'Canon EOS 5D' } },
];
expect(photosForCamera(photos, 'Nikon D700').map((photo) => photo.id)).toEqual(['a', 'b']);
expect(photosForCamera(photos, '')).toHaveLength(0);
});
it('refuses a matrix that is not nine finite numbers', () => {
const store = memoryStore();
const saved = saveCameraProfile({ name: 'Bad', camera: 'Nikon D700', matrix: [1, 2, 3] }, store);
expect(saved).toHaveLength(0);
});
});
+156
View File
@@ -0,0 +1,156 @@
/**
* Per-camera DCP profile library.
*
* A DCP's colour matrix describes the sensor, not the frame, so every raw from
* the same body can use the same derived matrix. The library keeps those
* matrices in localStorage (name, camera and nine numbers — never the file) so
* switching photos does not mean opening a file dialog again. Each edit still
* stores its own copy of the matrix, so a photo stays self-contained and the
* library is only a shortcut for filling it in.
*/
import { cameraKey } from './lensNames';
export interface SavedCameraProfile {
id: string;
name: string;
camera: string;
matrix: number[];
savedAt: number;
}
const STORAGE_KEY = 'lumenroom.cameraProfiles';
/** Enough for a shelf of bodies without letting a stray write grow unbounded. */
const LIMIT = 32;
/** The slice of Storage the library needs; injectable so it is testable. */
export type ProfileStore = Pick<Storage, 'getItem' | 'setItem'>;
function defaultStore(): ProfileStore | null {
try {
return globalThis.localStorage ?? null;
} catch {
return null;
}
}
function validMatrix(value: unknown): value is number[] {
return (
Array.isArray(value) &&
value.length === 9 &&
value.every((entry) => typeof entry === 'number' && Number.isFinite(entry))
);
}
/** Reads the library, dropping anything that no longer looks like a matrix. */
export function loadSavedCameraProfiles(store: ProfileStore | null = defaultStore()): SavedCameraProfile[] {
if (!store) return [];
try {
const raw = store.getItem(STORAGE_KEY);
if (!raw) return [];
const parsed: unknown = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
return parsed.flatMap((entry) => {
if (!entry || typeof entry !== 'object') return [];
const { id, name, camera, matrix, savedAt } = entry as Record<string, unknown>;
if (typeof id !== 'string' || typeof name !== 'string' || typeof camera !== 'string') return [];
if (!validMatrix(matrix)) return [];
return [
{
id,
name,
camera,
matrix: [...matrix],
savedAt: typeof savedAt === 'number' && Number.isFinite(savedAt) ? savedAt : 0,
},
];
});
} catch {
return [];
}
}
function persist(entries: SavedCameraProfile[], store: ProfileStore | null) {
if (!store) return;
try {
store.setItem(STORAGE_KEY, JSON.stringify(entries));
} catch {
/* Quota or private mode: the edit still has the matrix it was given. */
}
}
/**
* Adds or replaces a profile for the same camera and name. Returns the library
* as saved so a panel can update without re-reading storage.
*/
export function saveCameraProfile(
entry: { name: string; camera: string; matrix: number[] },
store: ProfileStore | null = defaultStore(),
): SavedCameraProfile[] {
const saved = loadSavedCameraProfiles(store);
if (!entry.name.trim() || !validMatrix(entry.matrix)) return saved;
const camera = entry.camera.trim() || 'Unknown camera';
const id = `${cameraKey(camera) || 'camera'}|${entry.name.trim()}`.toLowerCase();
const next: SavedCameraProfile[] = [
{
id,
name: entry.name.trim(),
camera,
matrix: [...entry.matrix],
savedAt: Date.now(),
},
...saved.filter((profile) => profile.id !== id),
].slice(0, LIMIT);
persist(next, store);
return next;
}
export function removeCameraProfile(
id: string,
store: ProfileStore | null = defaultStore(),
): SavedCameraProfile[] {
const next = loadSavedCameraProfiles(store).filter((profile) => profile.id !== id);
persist(next, store);
return next;
}
/** Minimal photo shape needed to pick the raws of one body. */
export interface CameraProfileTarget {
id: string;
raw?: boolean;
decode?: string;
deletedAt?: number;
meta?: { camera?: string };
}
/**
* Every live camera-native raw from the same body, including the one on screen.
* A JPEG, or a raw the server decoded straight to sRGB, already has its colour
* baked in, so a camera profile has nothing to act on there.
*/
export function photosForCamera<T extends CameraProfileTarget>(
photos: T[],
camera?: string,
): T[] {
const key = cameraKey(camera);
if (!key) return [];
return photos.filter(
(photo) =>
photo.raw &&
photo.decode !== 'embedded' &&
!photo.deletedAt &&
cameraKey(photo.meta?.camera) === key,
);
}
/** Profiles that belong to this body, most recently saved first. */
export function savedProfilesForCamera(
profiles: SavedCameraProfile[],
camera?: string,
): SavedCameraProfile[] {
const key = cameraKey(camera);
if (!key) return [];
return profiles
.filter((profile) => cameraKey(profile.camera) === key)
.sort((left, right) => right.savedAt - left.savedAt || left.name.localeCompare(right.name));
}
+3 -2
View File
@@ -30,7 +30,7 @@ export const EDIT_SECTIONS: EditSection[] = [
{ {
id: 'color', id: 'color',
label: 'Color', label: 'Color',
hint: 'Curves, HSL, grading, black & white', hint: 'Curves, HSL, grading, redscale, black & white',
defaultOn: true, defaultOn: true,
}, },
{ {
@@ -81,6 +81,7 @@ const GROUPS: Record<EditSectionId, (keyof Edits)[]> = {
light: [ light: [
'temp', 'temp',
'tint', 'tint',
'kelvin',
'exposure', 'exposure',
'recovery', 'recovery',
'contrast', 'contrast',
@@ -94,7 +95,7 @@ const GROUPS: Record<EditSectionId, (keyof Edits)[]> = {
'vibrance', 'vibrance',
'saturation', 'saturation',
], ],
color: ['bw', 'bwFilter', 'bwFilterAmount', 'curve', 'parametric', 'hsl', 'grading'], color: ['bw', 'bwFilter', 'bwFilterAmount', 'curve', 'levels', 'parametric', 'hsl', 'grading', 'redscale'],
detail: ['sharpen', 'noise', 'defringe'], detail: ['sharpen', 'noise', 'defringe'],
effects: ['vignette', 'grain', 'proof'], effects: ['vignette', 'grain', 'proof'],
geometry: ['geometry'], geometry: ['geometry'],
+184
View File
@@ -0,0 +1,184 @@
import { useEffect, useState } from 'react';
import type { Edits, PhotoRecord } from '../types';
import { isEdited } from './edits';
import { Renderer, rotatedBounds } from '../gl/renderer';
import { getCameraThumb } from './images';
/**
* Thumbnails of edited photos.
*
* The server thumbnail is always the *undeveloped* frame, so the grid and the
* filmstrip would otherwise show the import look no matter how far a photo was
* edited. These are rendered on demand with the same shader the canvas uses,
* from the already-cached small thumbnail (not the multi-megapixel proxy), and
* kept as data URLs. One renderer does every tile: a WebGL context per picture
* would exhaust the browser's limit long before a shoot.
*/
/** Long edge of a rendered thumb; twice the largest card, so it stays sharp. */
const RENDER_EDGE = 384;
const CACHE_LIMIT = 700;
const cache = new Map<string, string>();
/**
* Edits are immutable: every change stores a new object (undo re-uses an old
* one). A per-object version number is therefore a cheap, exact cache key — far
* cheaper than serializing the whole edit for every visible card on every render.
*/
const versions = new WeakMap<Edits, number>();
let versionSeq = 0;
function versionOf(edits: Edits): number {
let version = versions.get(edits);
if (version === undefined) {
version = ++versionSeq;
versions.set(edits, version);
}
return version;
}
function keyOf(photo: PhotoRecord): string {
// 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;
let rendererFailed = false;
function getRenderer(): Renderer | null {
if (renderer) return renderer;
if (rendererFailed) return null;
try {
renderer = new Renderer(document.createElement('canvas'));
} catch {
// No WebGL2: tiles quietly keep their plain thumbnails.
rendererFailed = true;
}
return renderer;
}
/** The small picture the browser already has, decoded for the shader. */
async function loadThumb(photo: PhotoRecord): Promise<ImageBitmap | null> {
const src = photo.thumbUrl ?? photo.thumb;
if (!src) return null;
try {
const res = await fetch(src, { credentials: 'same-origin' });
if (!res.ok) return null;
return await createImageBitmap(await res.blob(), { imageOrientation: 'from-image' });
} catch {
return null;
}
}
async function renderThumb(photo: PhotoRecord): Promise<string | null> {
const r = getRenderer();
if (!r) return null;
const bitmap = await loadThumb(photo);
if (!bitmap) return null;
try {
// Only a profile override can differ from the JPEG: without one the thumb
// already has the body matrix baked in and the extra fetch is wasted.
const cameraThumb = photo.edits.cameraProfile ? await getCameraThumb(photo) : null;
const crop = photo.edits.crop;
const frame = rotatedBounds(bitmap.width, bitmap.height, crop.angle, crop.quarter);
const cropW = Math.max(1, frame.w * crop.w);
const cropH = Math.max(1, frame.h * crop.h);
const scale = Math.min(2, RENDER_EDGE / Math.max(cropW, cropH));
const width = Math.max(16, Math.round(cropW * scale));
const height = Math.max(16, Math.round(cropH * scale));
r.setImage(bitmap, cameraThumb);
// `lens: null` clears the previous photo's calibration maps: this renderer
// is shared, and a stale map would warp the next thumbnail.
r.render(photo.edits, { width, height, lens: null, upscale: scale > 1.02 });
return r.canvas.toDataURL('image/jpeg', 0.74);
} finally {
bitmap.close();
}
}
interface Job {
photo: PhotoRecord;
key: string;
waiters: ((url: string | null) => void)[];
}
const jobs: Job[] = [];
let pumping = false;
function enqueue(photo: PhotoRecord, key: string): Promise<string | null> {
return new Promise((resolve) => {
const existing = jobs.find((job) => job.key === key);
if (existing) {
existing.waiters.push(resolve);
return;
}
jobs.push({ photo, key, waiters: [resolve] });
void pump();
});
}
/** One render at a time, yielding between tiles so the UI stays responsive. */
async function pump() {
if (pumping) return;
pumping = true;
while (jobs.length) {
const job = jobs.shift()!;
let url: string | null = null;
try {
url = await renderThumb(job.photo);
} catch {
url = null;
}
if (url) {
cache.set(job.key, url);
while (cache.size > CACHE_LIMIT) {
const first = cache.keys().next();
if (first.done) break;
cache.delete(first.value);
}
}
for (const waiter of job.waiters) waiter(url);
await new Promise((resolve) => setTimeout(resolve, 0));
}
pumping = false;
}
/**
* The edited thumbnail for a photo, or null while there is none to show.
*
* Only edited photos are rendered, and only once the tile is near the viewport
* (`enabled`), so a long shoot does not pay for pictures nobody can see. Until
* a render lands the caller keeps showing the plain thumbnail.
*/
export function useEditedThumb(photo: PhotoRecord, enabled = true): string | null {
const key = isEdited(photo.edits) ? keyOf(photo) : '';
const [src, setSrc] = useState<string | null>(() => (key ? cache.get(key) ?? null : null));
useEffect(() => {
if (!key) {
setSrc(null);
return;
}
const hit = cache.get(key);
if (hit) {
setSrc(hit);
return;
}
if (!enabled) return;
let alive = true;
// Coalesce slider drags: only the setting you stopped on gets rendered.
const timer = window.setTimeout(() => {
void enqueue(photo, key).then((url) => {
if (alive && url) setSrc(url);
});
}, 120);
return () => {
alive = false;
window.clearTimeout(timer);
};
}, [key, photo, enabled]);
return src;
}
+192 -29
View File
@@ -6,6 +6,7 @@ import type {
Edits, Edits,
Flag, Flag,
HealSpot, HealSpot,
LocalComponent,
LocalLayer, LocalLayer,
LocalMaskKind, LocalMaskKind,
LocalPoint, LocalPoint,
@@ -96,24 +97,53 @@ export function thumbTransform(photo: PhotoRecord, boxAspect = 4 / 3): string {
/** The shader carries a fixed spot array; more than this would silently drop. */ /** The shader carries a fixed spot array; more than this would silently drop. */
export const MAX_HEAL_SPOTS = 24; export const MAX_HEAL_SPOTS = 24;
/** Four masks are packed into one RGBA texture. */ /** Eight masks are packed into two RGBA textures. */
export const MAX_LOCAL_LAYERS = 4; export const MAX_LOCAL_LAYERS = 8;
/** More shapes than this in one group stops being quicker than a second layer. */
export const MAX_LOCAL_COMPONENTS = 8;
export function defaultLocalAdjust(): LocalLayer['adjust'] { 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 defaultLocalComponent(kind: LocalMaskKind): LocalComponent {
return {
id: `shape-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
kind,
mode: 'add',
inverted: false,
feather: 50,
brush: { strokes: [] },
linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 },
radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 },
};
} }
export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLayer { export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLayer {
return { return {
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`, id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
name: `Local ${index + 1}`, name: `Local ${index + 1}`,
kind, mode: 'add',
inverted: false, components: [defaultLocalComponent(kind)],
feather: 50,
brush: { strokes: [] },
linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 },
radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 },
range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 }, range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 },
curve: identityCurve(),
adjust: defaultLocalAdjust(), adjust: defaultLocalAdjust(),
}; };
} }
@@ -146,6 +176,7 @@ export function defaultEdits(): Edits {
return { return {
temp: 0, temp: 0,
tint: 0, tint: 0,
kelvin: null,
exposure: 0, exposure: 0,
recovery: 0, recovery: 0,
contrast: 0, contrast: 0,
@@ -158,6 +189,7 @@ export function defaultEdits(): Edits {
dehaze: 0, dehaze: 0,
vibrance: 0, vibrance: 0,
saturation: 0, saturation: 0,
redscale: 0,
bw: false, bw: false,
bwFilter: 'none', bwFilter: 'none',
bwFilterAmount: 100, bwFilterAmount: 100,
@@ -167,6 +199,7 @@ export function defaultEdits(): Edits {
green: identityCurve(), green: identityCurve(),
blue: identityCurve(), blue: identityCurve(),
}, },
levels: { black: 0, white: 100, gamma: 1 },
parametric: { highlights: 0, lights: 0, darks: 0, blacks: 0 }, parametric: { highlights: 0, lights: 0, darks: 0, blacks: 0 },
hsl: { hsl: {
hue: HUE_BANDS.map(() => 0), hue: HUE_BANDS.map(() => 0),
@@ -179,7 +212,8 @@ export function defaultEdits(): Edits {
balance: 0, balance: 0,
}, },
sharpen: { amount: 0, radius: 1, detail: 25, mask: 0, lensSoftness: 0 }, sharpen: { amount: 0, radius: 1, detail: 25, mask: 0, lensSoftness: 0 },
proof: { enabled: false, paper: 'matte', blackPoint: 2, gamut: false }, proof: { enabled: false, paper: 'matte', blackPoint: 2, gamut: false, intent: 'perceptual' },
cameraProfile: null,
noise: { luminance: 0, detail: 50, chroma: 0, chromaDetail: 50 }, noise: { luminance: 0, detail: 50, chroma: 0, chromaDetail: 50 },
aiDenoise: { amount: 100, key: null, model: 'guided' }, aiDenoise: { amount: 100, key: null, model: 'guided' },
defringe: { purple: 0, green: 0 }, defringe: { purple: 0, green: 0 },
@@ -248,26 +282,47 @@ function rasterMask(input: unknown): RasterMask | undefined {
return { data: raw.data, width, height }; return { data: raw.data, width, height };
} }
function localLayers(input: unknown): LocalLayer[] { /**
if (!Array.isArray(input)) return []; * Per-mask curve points. Masks saved before the field existed have none, and
const out: LocalLayer[] = []; * they must come back as the identity rather than leaving the shader LUT row
for (const raw of input.slice(0, MAX_LOCAL_LAYERS)) { * undefined.
*/
function localCurve(input: unknown): CurvePoint[] {
if (!Array.isArray(input)) return identityCurve();
const points: CurvePoint[] = [];
for (const raw of input.slice(0, 16)) {
if (!raw || typeof raw !== 'object') continue; if (!raw || typeof raw !== 'object') continue;
const layer = raw as Partial<LocalLayer>; const point = raw as Partial<CurvePoint>;
points.push({ x: clamp01(num(point.x, 0, 0, 1)), y: clamp01(num(point.y, 0, 0, 1)) });
}
points.sort((a, b) => a.x - b.x);
return points.length >= 2 ? points : identityCurve();
}
/**
* One shape from stored edits. It also reads the pre-group flat layout, where
* the layer itself carried kind/feather/brush/...: that is how every mask saved
* before mask groups existed migrates into `components[0]`.
*/
function localComponent(input: unknown, index: number): LocalComponent | null {
if (!input || typeof input !== 'object') return null;
const shape = input as Partial<LocalComponent> & { kind?: unknown };
const kind: LocalMaskKind = const kind: LocalMaskKind =
layer.kind === 'linear' || layer.kind === 'radial' || layer.kind === 'raster' ? layer.kind : 'brush'; shape.kind === 'linear' || shape.kind === 'radial' || shape.kind === 'raster' ? shape.kind : 'brush';
const adjust = (layer.adjust ?? {}) as Partial<LocalLayer['adjust']>; const linear = (shape.linear ?? {}) as Partial<LocalComponent['linear']>;
const range = (layer.range ?? {}) as Partial<LocalLayer['range']>; const radial = (shape.radial ?? {}) as Partial<LocalComponent['radial']>;
const linear = (layer.linear ?? {}) as Partial<LocalLayer['linear']>; const raster = kind === 'raster' ? rasterMask(shape.raster) : undefined;
const radial = (layer.radial ?? {}) as Partial<LocalLayer['radial']>; // A raster shape without its coverage would composite an empty hole, so it
out.push({ // falls back to a brush shape that can at least be painted over.
id: typeof layer.id === 'string' && layer.id ? layer.id : `local-${out.length}`, const resolved: LocalMaskKind = kind === 'raster' && !raster ? 'brush' : kind;
name: typeof layer.name === 'string' && layer.name.trim() ? layer.name.slice(0, 40) : `Local ${out.length + 1}`, return {
kind, id: typeof shape.id === 'string' && shape.id ? shape.id.slice(0, 60) : `shape-${index}`,
inverted: !!layer.inverted, kind: resolved,
feather: num(layer.feather, 50, 0, 100), mode: shape.mode === 'subtract' || shape.mode === 'intersect' ? shape.mode : 'add',
brush: { strokes: localStrokes(layer.brush?.strokes) }, inverted: !!shape.inverted,
raster: kind === 'raster' ? rasterMask(layer.raster) : undefined, feather: num(shape.feather, 50, 0, 100),
brush: { strokes: localStrokes(shape.brush?.strokes) },
raster: resolved === 'raster' ? raster : undefined,
linear: { linear: {
x1: clamp01(num(linear.x1, 0.5, 0, 1)), x1: clamp01(num(linear.x1, 0.5, 0, 1)),
y1: clamp01(num(linear.y1, 0.2, 0, 1)), y1: clamp01(num(linear.y1, 0.2, 0, 1)),
@@ -280,6 +335,31 @@ function localLayers(input: unknown): LocalLayer[] {
rx: num(radial.rx, 0.25, 0.01, 1.5), rx: num(radial.rx, 0.25, 0.01, 1.5),
ry: num(radial.ry, 0.3, 0.01, 1.5), ry: num(radial.ry, 0.3, 0.01, 1.5),
}, },
};
}
function localLayers(input: unknown): LocalLayer[] {
if (!Array.isArray(input)) return [];
const out: LocalLayer[] = [];
for (const raw of input.slice(0, MAX_LOCAL_LAYERS)) {
if (!raw || typeof raw !== 'object') continue;
const layer = raw as Partial<LocalLayer>;
const adjust = (layer.adjust ?? {}) as Partial<LocalLayer['adjust']>;
const range = (layer.range ?? {}) as Partial<LocalLayer['range']>;
const stored = Array.isArray(layer.components) && layer.components.length ? layer.components : [layer];
const components: LocalComponent[] = [];
for (const entry of stored.slice(0, MAX_LOCAL_COMPONENTS)) {
const component = localComponent(entry, components.length);
if (component) components.push(component);
}
// A layer must keep at least one shape, or it would adjust nothing with no
// way to tell why from the panel.
if (!components.length) components.push(defaultLocalComponent('brush'));
out.push({
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}`,
mode: layer.mode === 'subtract' || layer.mode === 'intersect' ? layer.mode : 'add',
components,
range: { range: {
enabled: !!range.enabled, enabled: !!range.enabled,
lumaMin: num(range.lumaMin, 0, 0, 100), lumaMin: num(range.lumaMin, 0, 0, 100),
@@ -288,14 +368,23 @@ function localLayers(input: unknown): LocalLayer[] {
hueRange: num(range.hueRange, 180, 0, 180), hueRange: num(range.hueRange, 180, 0, 180),
satMin: num(range.satMin, 0, 0, 100), satMin: num(range.satMin, 0, 0, 100),
}, },
curve: localCurve(layer.curve),
adjust: { adjust: {
exposure: num(adjust.exposure, 0, -4, 4), exposure: num(adjust.exposure, 0, -4, 4),
contrast: num(adjust.contrast, 0, -100, 100), contrast: num(adjust.contrast, 0, -100, 100),
highlights: num(adjust.highlights, 0, -100, 100), highlights: num(adjust.highlights, 0, -100, 100),
shadows: num(adjust.shadows, 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), temp: num(adjust.temp, 0, -100, 100),
tint: num(adjust.tint, 0, -100, 100), tint: num(adjust.tint, 0, -100, 100),
saturation: num(adjust.saturation, 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),
}, },
}); });
} }
@@ -332,16 +421,68 @@ function lensProfile(input: unknown): LensProfile | undefined {
corrections: { corrections: {
distortion: corrections?.distortion !== false, distortion: corrections?.distortion !== false,
tca: corrections?.tca !== false, tca: corrections?.tca !== false,
vignetting: corrections?.vignetting !== false, // The vignetting map is a flat-field gain applied to the already
// tone-mapped proxy, which pushes the corners brighter than the frame
// centre and over-exposes the edges. It stays opt-in, so a profile saved
// without an explicit flag never brightens the corners.
vignetting: corrections?.vignetting === true,
}, },
distance: num(raw.distance, 1000, 0.1, 100000), distance: num(raw.distance, 1000, 0.1, 100000),
}; };
} }
/**
* One-off cleanup for records saved while applying a lens profile enabled all
* three corrections. The vignetting gain over-exposed the edges on the tone
* mapped proxy, so it is opt-in now; this clears the flag old edits stored,
* including snapshots and history, and returns null when nothing needed doing.
*/
export function withoutLensVignetting(photo: PhotoRecord): PhotoRecord | null {
let changed = false;
const strip = (edits: Edits): Edits => {
const lens = edits.lens;
if (!lens || lens.corrections.vignetting !== true) return edits;
changed = true;
return {
...edits,
lens: { ...lens, corrections: { ...lens.corrections, vignetting: false } },
};
};
const edits = strip(photo.edits);
const snapshots = photo.snapshots?.map((snapshot) => ({
...snapshot,
edits: strip(snapshot.edits),
}));
const history = photo.history?.map((entry) => ({ ...entry, edits: strip(entry.edits) }));
if (!changed) return null;
const next: PhotoRecord = { ...photo, edits };
if (snapshots) next.snapshots = snapshots;
if (history) next.history = history;
return next;
}
/**
* 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 { export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits {
const d = defaultEdits(); const d = defaultEdits();
if (!input) return d; if (!input) return d;
const curve = (input.curve ?? {}) as Partial<Edits['curve']>; 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 parametric = (input.parametric ?? {}) as Partial<Edits['parametric']>;
const grading = (input.grading ?? {}) as Partial<Edits['grading']>; const grading = (input.grading ?? {}) as Partial<Edits['grading']>;
const sharpen = (input.sharpen ?? {}) as Partial<Edits['sharpen']>; const sharpen = (input.sharpen ?? {}) as Partial<Edits['sharpen']>;
@@ -355,6 +496,7 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
return { return {
...d, ...d,
...input, ...input,
cameraProfile: normalizeCameraProfile(input.cameraProfile),
aiDenoise: { aiDenoise: {
amount: num(aiDenoise.amount, d.aiDenoise.amount, 0, 100), amount: num(aiDenoise.amount, d.aiDenoise.amount, 0, 100),
key: typeof aiDenoise.key === 'string' && aiDenoise.key ? aiDenoise.key : null, key: typeof aiDenoise.key === 'string' && aiDenoise.key ? aiDenoise.key : null,
@@ -362,6 +504,10 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
}, },
temp: num(input.temp, 0, -100, 100), temp: num(input.temp, 0, -100, 100),
tint: num(input.tint, 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), exposure: num(input.exposure, 0, -5, 5),
recovery: num(input.recovery, 0, 0, 100), recovery: num(input.recovery, 0, 0, 100),
contrast: num(input.contrast, 0, -100, 100), contrast: num(input.contrast, 0, -100, 100),
@@ -374,6 +520,7 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
dehaze: num(input.dehaze, 0, -100, 100), dehaze: num(input.dehaze, 0, -100, 100),
vibrance: num(input.vibrance, 0, -100, 100), vibrance: num(input.vibrance, 0, -100, 100),
saturation: num(input.saturation, 0, -100, 100), saturation: num(input.saturation, 0, -100, 100),
redscale: num(input.redscale, 0, 0, 100),
bw: !!input.bw, bw: !!input.bw,
bwFilter: BW_FILTERS.some((f) => f.id === input.bwFilter) ? (input.bwFilter as BwFilter) : 'none', bwFilter: BW_FILTERS.some((f) => f.id === input.bwFilter) ? (input.bwFilter as BwFilter) : 'none',
bwFilterAmount: num(input.bwFilterAmount, d.bwFilterAmount, 0, 100), bwFilterAmount: num(input.bwFilterAmount, d.bwFilterAmount, 0, 100),
@@ -383,6 +530,14 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
green: sanitizeCurve(curve.green), green: sanitizeCurve(curve.green),
blue: sanitizeCurve(curve.blue), 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: { parametric: {
highlights: num(parametric.highlights, 0, -100, 100), highlights: num(parametric.highlights, 0, -100, 100),
lights: num(parametric.lights, 0, -100, 100), lights: num(parametric.lights, 0, -100, 100),
@@ -417,6 +572,10 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
paper: input.proof?.paper === 'gloss' || input.proof?.paper === 'newsprint' ? input.proof.paper : 'matte', paper: input.proof?.paper === 'gloss' || input.proof?.paper === 'newsprint' ? input.proof.paper : 'matte',
blackPoint: num(input.proof?.blackPoint, 2, 0, 20), blackPoint: num(input.proof?.blackPoint, 2, 0, 20),
gamut: !!input.proof?.gamut, gamut: !!input.proof?.gamut,
intent:
input.proof?.intent === 'relative' || input.proof?.intent === 'saturation'
? input.proof.intent
: 'perceptual',
}, },
noise: { noise: {
luminance: num(noise.luminance, 0, 0, 100), luminance: num(noise.luminance, 0, 0, 100),
@@ -489,6 +648,10 @@ export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): Ph
decode: input.decode, decode: input.decode,
previewUrl: input.previewUrl, previewUrl: input.previewUrl,
thumbUrl: input.thumbUrl, 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, proofAt: typeof input.proofAt === 'number' && Number.isFinite(input.proofAt) ? input.proofAt : undefined,
name: input.name ?? 'Untitled', name: input.name ?? 'Untitled',
width: input.width ?? 0, width: input.width ?? 0,
+43 -13
View File
@@ -1,11 +1,12 @@
import type { Edits, PhotoRecord } from '../types'; import type { Edits, PhotoRecord } from '../types';
import { getBitmap } from './images'; import { get16BitSource, getBitmap } from './images';
import { normalizeEdits } from './edits'; import { normalizeEdits } from './edits';
import { buildLensCorrection } from './lensfun'; import { buildLensCorrection } from './lensEngine';
import { outputSize, Renderer } from '../gl/renderer'; import { outputSize, Renderer } from '../gl/renderer';
import { getDenoisedBitmap } from './images'; import { getDenoisedBitmap } from './images';
import { createZipBlob, zipFileName } from './zip'; import { createZipBlob, zipFileName } from './zip';
import { srgbProfile } from './icc'; import { profileFor, type OutputColorSpace } from './icc';
import { convertFloatPixels, convertImageData } from './colorSpace';
import { encodeTiff16 } from './tiff'; import { encodeTiff16 } from './tiff';
export type ExportFormat = 'jpeg' | 'png' | 'webp' | 'tiff16'; export type ExportFormat = 'jpeg' | 'png' | 'webp' | 'tiff16';
@@ -16,6 +17,8 @@ export type WatermarkPosition = 'br' | 'bl' | 'tr' | 'tl' | 'center';
export interface ExportOptions { export interface ExportOptions {
format: ExportFormat; format: ExportFormat;
quality: number; quality: number;
/** Delivery colour space; affects pixels and the embedded ICC profile. */
colorSpace: OutputColorSpace;
resize: ResizeMode; resize: ResizeMode;
longEdge: number; longEdge: number;
percent: number; percent: number;
@@ -46,6 +49,7 @@ export interface ExportRecipe {
export const DEFAULT_EXPORT: ExportOptions = { export const DEFAULT_EXPORT: ExportOptions = {
format: 'jpeg', format: 'jpeg',
quality: 92, quality: 92,
colorSpace: 'srgb',
resize: 'none', resize: 'none',
longEdge: 3000, longEdge: 3000,
percent: 100, 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 bitmap = await getBitmap(photo);
const base = normalizeEdits(photo.edits); const base = normalizeEdits(photo.edits);
const edits = opts.outputSharpen > 0 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, // 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. // 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 upscale = w > native.w * 1.05 || h > native.h * 1.05;
const canvas = document.createElement('canvas'); const canvas = sharedRenderer ? sharedRenderer.canvas : document.createElement('canvas');
if (!sharedRenderer) {
canvas.width = 1; canvas.width = 1;
canvas.height = 1; canvas.height = 1;
const renderer = new Renderer(canvas); }
const renderer = sharedRenderer ?? new Renderer(canvas);
try { 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 // Forgetting this is how denoise silently goes missing from exports: the
// preview and the file would be graded from different pixels. // preview and the file would be graded from different pixels.
if (edits.aiDenoise.key) { 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 }) ? await buildLensCorrection(edits.lens, { width: bitmap.width, height: bitmap.height, meta: photo.meta })
: null; : null;
const space: OutputColorSpace = opts.colorSpace ?? 'srgb';
if (opts.format === 'tiff16') { if (opts.format === 'tiff16') {
if (opts.watermark.enabled && opts.watermark.text.trim()) { if (opts.watermark.enabled && opts.watermark.text.trim()) {
throw new Error('Watermarking is not available for 16-bit TIFF exports'); 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'); if (!pixels) throw new Error('Could not read the 16-bit render');
pixels = convertFloatPixels(pixels, space);
return encodeTiff16({ return encodeTiff16({
width: w, width: w,
height: h, height: h,
pixels, pixels,
icc: opts.embedProfile ? srgbProfile() : null, icc: opts.embedProfile ? profileFor(space) : null,
}); });
} }
renderer.render(edits, { width: w, height: h, lens, upscale }); renderer.render(edits, { width: w, height: h, lens, upscale });
renderer.finishGpu(); renderer.finishGpu();
let output = canvas; let output = space === 'srgb' ? canvas : convertCanvas(canvas, space);
if (opts.watermark.enabled && opts.watermark.text.trim()) { if (opts.watermark.enabled && opts.watermark.text.trim()) {
output = paintWatermark(canvas, photo, opts); output = paintWatermark(output, photo, opts);
} }
const mime = MIME[opts.format]; const mime = MIME[opts.format];
let blob = await new Promise<Blob | null>((resolve) => let blob = await new Promise<Blob | null>((resolve) =>
@@ -171,15 +187,29 @@ export async function renderPhotoBlob(photo: PhotoRecord, opts: ExportOptions):
blob = await embedJpegMetadata( blob = await embedJpegMetadata(
blob, blob,
opts.metadata ? buildXmp(photo) : '', opts.metadata ? buildXmp(photo) : '',
opts.embedProfile ? srgbProfile() : null, opts.embedProfile ? profileFor(space) : null,
); );
} }
return blob; return blob;
} finally { } 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) { function paintWatermark(source: HTMLCanvasElement, photo: PhotoRecord, opts: ExportOptions) {
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
canvas.width = source.width; 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 * sRGB, Display P3 and Adobe RGB (1998) are all RGB display spaces, so one
* tag sRGB files without adding a third-party profile asset. The matrix and * builder covers them: only the primaries, transfer curve and description
* gamma describe the standard sRGB primaries; the browser already converted * change. The primaries are the D50-adapted values an ICC profile expects; the
* the working pixels into sRGB when it decoded the source image. * 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) { function be32(out: DataView, offset: number, value: number) {
out.setUint32(offset, value >>> 0, false); out.setUint32(offset, value >>> 0, false);
@@ -39,7 +80,7 @@ function xyzTag(x: number, y: number, z: number) {
return data; return data;
} }
function curveTag() { function srgbCurveTag() {
// ICC v2 curveType with the piecewise sRGB transfer function sampled at // 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 // 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. // standard (within 16-bit quantisation) and still readable by old CMMs.
@@ -59,6 +100,16 @@ function curveTag() {
return data; 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) { function descTag(text: string) {
const value = new TextEncoder().encode(text); const value = new TextEncoder().encode(text);
const size = pad4(12 + value.length + 1 + 4 + 4); const size = pad4(12 + value.length + 1 + 4 + 4);
@@ -83,20 +134,24 @@ function textTag(text: string) {
return data; return data;
} }
export function srgbProfile(): Uint8Array { function buildProfile(space: OutputColorSpace): Uint8Array {
if (cached) return cached; 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 }[] = [ 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: 'cprt', data: textTag('No copyright, use freely') },
{ sig: 'wtpt', data: xyzTag(0.9642, 1.0, 0.8249) }, { sig: 'wtpt', data: xyzTag(0.9642, 1.0, 0.8249) },
{ sig: 'rXYZ', data: xyzTag(0.4360747, 0.2225045, 0.0139322) }, { sig: 'rXYZ', data: xyzTag(r[0], r[1], r[2]) },
{ sig: 'gXYZ', data: xyzTag(0.3850649, 0.7168786, 0.0971045) }, { sig: 'gXYZ', data: xyzTag(g[0], g[1], g[2]) },
{ sig: 'bXYZ', data: xyzTag(0.1430804, 0.0606169, 0.7141733) }, { sig: 'bXYZ', data: xyzTag(b[0], b[1], b[2]) },
{ sig: 'rTRC', data: curveTag() }, // All three channels share the transfer function; the writer copies the
{ sig: 'gTRC', data: curveTag() }, // bytes at each tag's own offset.
{ sig: 'bTRC', data: curveTag() }, { sig: 'rTRC', data: curve },
{ sig: 'gTRC', data: curve },
{ sig: 'bTRC', data: curve },
]; ];
const tableSize = 4 + tags.length * 12; const tableSize = 4 + tags.length * 12;
@@ -147,6 +202,17 @@ export function srgbProfile(): Uint8Array {
data.set(tag.data, tag.at); data.set(tag.data, tag.at);
}); });
cached = data;
return 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');
}
+112 -2
View File
@@ -1,5 +1,6 @@
import type { PhotoRecord } from '../types'; import type { PhotoRecord } from '../types';
import { getAsset, putAsset } from './db'; import { deleteAsset, getAsset, putAsset } from './db';
import { parsePreview16, type Preview16 } from './preview16';
const CACHE_LIMIT = 6; const CACHE_LIMIT = 6;
const cache = new Map<string, ImageBitmap>(); const cache = new Map<string, ImageBitmap>();
@@ -55,6 +56,18 @@ async function fetchRemote(photo: PhotoRecord): Promise<Blob | null> {
} }
} }
/**
* Decode upright, falling back for decoders that refuse the orientation option
* (a plain decode is better than no frame at all).
*/
async function decodeBitmap(blob: Blob): Promise<ImageBitmap> {
try {
return await createImageBitmap(blob, { imageOrientation: 'from-image' });
} catch {
return await createImageBitmap(blob);
}
}
export async function getBitmap(photo: PhotoRecord): Promise<ImageBitmap> { export async function getBitmap(photo: PhotoRecord): Promise<ImageBitmap> {
const hit = cache.get(photo.id); const hit = cache.get(photo.id);
if (hit) { if (hit) {
@@ -74,7 +87,18 @@ export async function getBitmap(photo: PhotoRecord): Promise<ImageBitmap> {
} }
// Apply EXIF orientation so the pixels the editor works on are upright. // Apply EXIF orientation so the pixels the editor works on are upright.
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' }); // A cached copy can be stale — truncated by an interrupted download, or
// written when the server produced a different proxy — and then it decodes
// to nothing forever, so one failure drops it and refetches the current bytes.
let bitmap: ImageBitmap;
try {
bitmap = await decodeBitmap(blob);
} catch (err) {
await deleteAsset(photo.id).catch(() => undefined);
const fresh = (await fetchRemoteCopy(photo)) ?? undefined;
if (!fresh) throw err;
bitmap = await decodeBitmap(fresh);
}
cache.set(photo.id, bitmap); cache.set(photo.id, bitmap);
while (cache.size > CACHE_LIMIT) { while (cache.size > CACHE_LIMIT) {
const first = cache.keys().next(); const first = cache.keys().next();
@@ -93,11 +117,97 @@ export function evictBitmap(photoId: string) {
bmp.close(); 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;
}
const cameraThumbCache = new Map<string, Preview16 | null>();
/**
* Camera-native grid thumbnail for a raw, or null when the server has none.
*
* The grid otherwise renders the sRGB JPEG, whose body matrix is already baked
* in, so a loaded DCP profile would only show in Develop. This is the sidecar
* resized to the JPEG thumbnail's dimensions, small enough to fetch per tile;
* null (a normal state for older imports) falls back to the JPEG.
*/
export async function getCameraThumb(photo: PhotoRecord): Promise<Preview16 | null> {
if (!photo.raw) return null;
const key = `${photo.id}|${photo.previewVersion ?? 0}`;
const hit = cameraThumbCache.get(key);
if (hit !== undefined) return hit;
try {
const res = await fetch(`/api/photos/${encodeURIComponent(photo.id)}/thumb16`, {
credentials: 'same-origin',
});
if (!res.ok) {
cameraThumbCache.set(key, null);
return null;
}
const parsed = await parsePreview16(await res.arrayBuffer());
cameraThumbCache.set(key, parsed);
while (cameraThumbCache.size > 12) {
const first = cameraThumbCache.keys().next();
if (first.done) break;
cameraThumbCache.delete(first.value);
}
return parsed;
} catch {
// A dropped connection is retried on the next tile, not cached as missing.
return null;
}
}
export function clearBitmapCache() { export function clearBitmapCache() {
cameraThumbCache.clear();
for (const bmp of cache.values()) bmp.close(); for (const bmp of cache.values()) bmp.close();
cache.clear(); cache.clear();
for (const bmp of denoisedCache.values()) bmp.close(); for (const bmp of denoisedCache.values()) bmp.close();
denoisedCache.clear(); denoisedCache.clear();
hdrCache.clear();
} }
const denoisedCache = new Map<string, ImageBitmap>(); const denoisedCache = new Map<string, ImageBitmap>();
+4 -1
View File
@@ -85,7 +85,10 @@ function editsForImport(meta: PhotoMeta, defaults: CameraLensDefault[]) {
if (match) { if (match) {
edits.lens = { edits.lens = {
...match.profile, ...match.profile,
corrections: { ...match.profile.corrections }, // A saved default still carries whatever the profile had when it was
// stored. Applying it on import must not switch the vignetting gain back
// on and over-expose the corners, so that correction stays opt-in.
corrections: { ...match.profile.corrections, vignetting: false },
}; };
} }
return edits; return edits;
+238
View File
@@ -0,0 +1,238 @@
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import {
availableFor,
findCamera,
findLensForMeta,
getLensEntry,
searchLens,
type LensDatabase,
} from './lensDb';
import { fixtureLenses } from './lensEngine.fixture';
import { invalidateTeamProfiles, type TeamLensProfile } from './lensProfiles';
import type { LensProfile } from '../types';
/**
* A miniature database: enough to exercise matching (brand, focal length, exact
* model), the mount tie-break and the availability flags without downloading
* the real 1.7 MB file.
*/
const database: LensDatabase = {
source: { project: 'lensfun', commit: 'test', licence: 'CC BY-SA 3.0', note: '' },
models: { distortion: ['poly3', 'poly5', 'ptlens', 'linear', 'acm'], tca: ['poly3', 'linear', 'acm'] },
mounts: ['Nikon F AF', 'Canon EF', 'Canon EF-M', 'Canon EF-S', 'Sony E'],
cameras: [
{ maker: 'Nikon Corporation', model: 'Nikon D700', mount: 'Nikon F AF', crop: 1 },
{ maker: 'Canon', model: 'Canon EOS R5', mount: 'Canon EF', crop: 1 },
{ maker: 'Canon', model: 'Canon EOS 60D', mount: 'Canon EF-S', crop: 1.62 },
],
lenses: [
...fixtureLenses,
{
id: 'canon-ef-50mm-f1-8',
maker: 'Canon',
model: 'Canon EF 50mm f/1.8 STM',
crop: 1,
mounts: ['Canon EF'],
aspect: 0,
centerX: 0,
centerY: 0,
d: [[50, 0, 0, -0.01, 0, 0]],
t: [],
v: [],
},
{
id: 'canon-ef-75-300',
maker: 'Canon',
model: 'Canon EF 75-300mm f/4-5.6 III USM',
crop: 1,
mounts: ['Canon EF'],
aspect: 0,
centerX: 0,
centerY: 0,
d: [[75, 2, 0.01, -0.02, 0.03, 0]],
t: [[75, 0, 0.001, 0, 0, 0.001, 0, 0]],
v: [],
},
{
id: 'canon-ef-s-17-85',
maker: 'Canon',
model: 'Canon EF-S 17-85mm f/4-5.6 IS USM',
crop: 1.6,
mounts: ['Canon EF-S'],
aspect: 0,
centerX: 0,
centerY: 0,
d: [[17, 0, 0, -0.03, 0, 0]],
t: [],
v: [],
},
{
id: 'tamron-11-20-sony',
maker: 'Tamron',
model: 'Tamron E 11-20mm F2.8',
crop: 1,
mounts: ['Sony E'],
aspect: 0,
centerX: 0,
centerY: 0,
d: [[11, 0, 0, -0.02, 0, 0]],
t: [],
v: [],
},
{
id: 'tamron-11-20-canon',
maker: 'Tamron',
model: 'Tamron 11-20mm F2.8 Di III-A',
crop: 1,
mounts: ['Canon EF'],
aspect: 0,
centerX: 0,
centerY: 0,
d: [[11, 0, 0, -0.02, 0, 0]],
t: [],
v: [],
},
],
};
/** Calibrations the team stored on the server; filled by the merge test. */
const teamProfiles: TeamLensProfile[] = [];
beforeAll(() => {
vi.stubGlobal('fetch', async (input: RequestInfo | URL) => {
const url = String(input);
const body = url.includes('/api/lens-profiles') ? { profiles: teamProfiles } : database;
return new Response(JSON.stringify(body), { status: 200 });
});
});
afterEach(() => {
teamProfiles.length = 0;
invalidateTeamProfiles();
});
describe('lens search', () => {
it('finds a maker the way people type it', async () => {
const results = await searchLens('tamron');
expect(results.length).toBeGreaterThan(0);
expect(results.every((result) => result.maker === 'Tamron')).toBe(true);
});
it('finds a lens by focal length alone', async () => {
const results = await searchLens('28-75');
expect(results[0]?.model).toContain('28-75');
});
it('matches an EXIF lens name to a profile', async () => {
const match = await findLensForMeta({
camera: 'NIKON CORPORATION NIKON D700',
lens: 'Tamron SP AF 28-75mm f/2.8 XR Di LD Aspherical (IF) Macro',
});
expect(match?.maker).toBe('Tamron');
});
it('matches EXIF names that fold the brand into the focal range', async () => {
const match = await findLensForMeta({
camera: 'Canon Canon EOS 60D',
lens: 'EF75-300mm f/4-5.6 USM',
});
expect(match?.model).toContain('75-300');
expect(match?.model).not.toContain('17-85');
});
it('does not guess a profile from a weak name match', async () => {
// Nothing in the fixture shares the focal range or the brand, so despite
// overlapping aperture tokens the auto-match must decline.
const meta = { camera: 'Canon Canon EOS 60D', lens: 'Sigma 18-35mm f/1.8 DC HSM' };
expect(await findLensForMeta(meta)).toBeNull();
expect((await searchLens(meta.lens, meta)).length).toBe(0);
});
it('ranks a lens from the same mount family first', async () => {
const results = await searchLens('tamron 11-20', { camera: 'Canon Canon EOS 60D' });
expect(results[0]?.model).toBe('Tamron 11-20mm F2.8 Di III-A');
});
it('returns nothing for a name that is not in the database', async () => {
expect(await searchLens('zzzz nonexistent lens')).toEqual([]);
expect(await searchLens('')).toEqual([]);
});
});
describe('camera lookup', () => {
it('reads the mount and crop factor from an EXIF body name', async () => {
const camera = await findCamera('NIKON CORPORATION NIKON D700');
expect(camera).toMatchObject({ mount: 'Nikon F AF', cropFactor: 1 });
});
it('keeps lenses filed under another mount findable', async () => {
// The Canon EF 50mm is not a Nikon F lens, but a search must not hide it.
const results = await searchLens('canon ef 50mm', { camera: 'NIKON CORPORATION NIKON D700' });
expect(results.some((result) => result.model.includes('50mm'))).toBe(true);
});
});
describe('team calibrations', () => {
const measured: TeamLensProfile = {
id: 'team-1',
maker: 'Sigma',
model: 'Sigma 24-70mm f/2.8 DG DN Art',
mount: 'Canon EF',
crop: 1,
aspect: 0,
centerX: 0,
centerY: 0,
notes: 'measured on a 5D',
d: [[24, 2, 0.01, -0.02, 0.03, 0]],
t: [],
v: [],
createdBy: 'user-1',
createdAt: 1,
updatedAt: 1,
};
it('is found by a search and marked as the team\u2019s own', async () => {
teamProfiles.push(measured);
invalidateTeamProfiles();
const results = await searchLens('sigma 24-70');
const match = results.find((result) => result.team);
expect(match).toMatchObject({ id: 'team:team-1', maker: 'Sigma' });
});
it('resolves a stored profile by its team id', async () => {
teamProfiles.push(measured);
invalidateTeamProfiles();
const entry = await getLensEntry({
id: 'team:team-1',
maker: 'Sigma',
model: 'Sigma 24-70mm f/2.8 DG DN Art',
crop: 1,
corrections: { distortion: true, tca: true, vignetting: true },
});
expect(entry?.id).toBe('team:team-1');
// Only distortion was measured, so the panel must offer only that.
expect(
await availableFor({
id: 'team:team-1',
maker: 'Sigma',
model: 'Sigma 24-70mm f/2.8 DG DN Art',
crop: 1,
corrections: { distortion: true, tca: true, vignetting: true },
}),
).toBe(8);
});
});
describe('availability', () => {
it('reports which corrections a profile supports', async () => {
const [tamron] = fixtureLenses;
const profile: LensProfile = {
maker: tamron.maker,
model: tamron.model,
crop: tamron.crop,
corrections: { distortion: true, tca: true, vignetting: true },
};
// Distortion, TCA and vignetting all have calibration samples.
expect(await availableFor(profile)).toBe(11);
});
});
+296
View File
@@ -0,0 +1,296 @@
import { TEAM_PREFIX, loadTeamProfiles, teamProfileToEntry } from './lensProfiles';
import type { LensProfile, PhotoMeta } from '../types';
/**
* Lens profiles are built from the Lensfun project's calibration database
* (CC BY-SA 3.0, © Lensfun contributors) by `scripts/build-lens-db.mjs`. Only
* the measurements come from there; searching, matching and the correction
* maths are ours, so the editor ships no WebAssembly runtime and no database
* parser.
*
* The file is fetched the first time the Optics panel, a stored profile or a
* lens-corrected export needs it, and then kept in memory.
*/
/** [focal, model, a, b, c, realFocal] — a·r³ + b·r² + c·r + 1; 0 = nominal focal */
export type DistortionSample = [number, number, number, number, number, number];
/** [focal, model, br, cr, vr, bb, cb, vb] — r·(v + c·r + b·r²) per channel */
export type TcaSample = [number, number, number, number, number, number, number, number];
/** [focal, aperture, distance, k1, k2, k3] */
export type VignettingSample = [number, number, number, number, number, number];
export const DIST_MODEL = { poly3: 0, poly5: 1, ptlens: 2, linear: 3, acm: 4 } as const;
export const TCA_MODEL = { poly3: 0, linear: 1, acm: 2 } as const;
export interface LensEntry {
id: string;
maker: string;
model: string;
/** Crop factor the calibration was measured at. */
crop: number;
mounts: string[];
/** Calibration sensor aspect ratio, 0 when the database does not say. */
aspect: number;
centerX: number;
centerY: number;
d: DistortionSample[];
t: TcaSample[];
v: VignettingSample[];
/** Set for a calibration the team stored on the server, not the bundle. */
team?: boolean;
}
export interface CameraEntry {
maker: string;
model: string;
mount: string;
crop: number;
}
export interface LensDatabase {
source: { project: string; commit: string; licence: string; note: string };
models: { distortion: string[]; tca: string[] };
mounts: string[];
cameras: CameraEntry[];
lenses: LensEntry[];
}
export interface CameraMatch {
maker: string;
model: string;
mount: string;
cropFactor: number;
score: number;
}
export interface LensSearchResult {
id: string;
maker: string;
model: string;
crop: number;
score: number;
/** Bit mask of the corrections the calibration supports. */
available: number;
/** True when the profile came from the team's own calibrations. */
team?: boolean;
}
export const FLAG_TCA = 1;
export const FLAG_VIGNETTING = 2;
export const FLAG_DISTORTION = 8;
let databasePromise: Promise<LensDatabase> | null = null;
/**
* Team calibrations are additive and optional: a signed-out or offline browser
* still gets the bundled database, so a failed request is not an error.
*/
async function loadTeamEntries(): Promise<LensEntry[]> {
try {
const profiles = await loadTeamProfiles();
return profiles.map(teamProfileToEntry);
} catch {
return [];
}
}
export function loadLensDatabase(): Promise<LensDatabase> {
if (!databasePromise) {
databasePromise = fetch('/lens-db/profiles.json')
.then((response) => {
if (!response.ok) throw new Error(`The lens database could not be loaded (${response.status})`);
return response.json() as Promise<LensDatabase>;
})
.catch((err) => {
databasePromise = null;
throw err;
});
}
return databasePromise;
}
/** Available corrections for a profile, matching the flags the renderer uses. */
export function availableFlags(entry: LensEntry): number {
return (
(entry.d.length ? FLAG_DISTORTION : 0) |
(entry.t.length ? FLAG_TCA : 0) |
(entry.v.length ? FLAG_VIGNETTING : 0)
);
}
export function toResult(entry: LensEntry, score = 0): LensSearchResult {
return {
id: entry.id,
maker: entry.maker,
model: entry.model,
crop: entry.crop,
score,
available: availableFlags(entry),
team: entry.team,
};
}
/* ------------------------------------------------------------------ matching */
/** Lowercase word tokens, with units folded so "28-75mm" meets "28-75". */
function tokens(value: string): string[] {
return value
.toLowerCase()
.replace(/[^a-z0-9]+/g, ' ')
.trim()
.split(' ')
.filter(Boolean)
.map((token) => token.replace(/mm$/, '').replace(/^f(?=\d)/, ''));
}
function coverage(query: string[], target: Set<string>): number {
if (!query.length) return 0;
let hit = 0;
for (const token of query) if (target.has(token)) hit += 1;
return hit / query.length;
}
/**
* 3 for an exact model, otherwise the fraction of query words the entry covers,
* with a small bonus when every word matches. Both maker and model count, so
* "tamron" finds Tamron glass without needing the focal length.
*/
function scoreEntry(entry: LensEntry, variants: string[]): number {
const target = new Set([...tokens(entry.maker), ...tokens(entry.model)]);
const maker = tokens(entry.maker);
const model = tokens(entry.model);
let best = 0;
for (const variant of variants) {
const query = tokens(variant);
if (!query.length) continue;
const name = [...maker, ...model].join(' ');
if (query.join(' ') === name || query.join(' ') === model.join(' ')) return 3;
const hit = coverage(query, target);
best = Math.max(best, hit >= 1 ? 1.25 : hit);
}
return best;
}
/** Variants of the query worth matching: as typed, plus unit-normalised forms. */
function queryVariants(query: string): string[] {
const raw = query.trim();
if (raw.length < 2) return [];
const compact = raw.replace(/(\d)\s*mm\b/gi, '$1mm').replace(/\s+/g, ' ');
// EXIF folds the brand into the focal range ("EF75-300mm", "SEL2870", "RF24-105mm");
// splitting letters from digits lets "ef 75" meet "EF 75-300mm".
const split = compact.replace(/([a-z])(\d)/gi, '$1 $2');
return [...new Set([raw, compact, compact.replace(/\s+/g, ''), split])].filter(
(text) => text.length >= 2,
);
}
/** "Canon EF" and "Canon EF-S" are one family when ranking fits. */
function sameMountFamily(a: string, b: string) {
const family = (mount: string) => mount.trim().split(/\s+/)[0] ?? '';
return family(a) !== '' && family(a) === family(b);
}
/* ------------------------------------------------------------------- queries */
export async function searchLens(
query: string,
meta?: Pick<PhotoMeta, 'camera' | 'lens'>,
): Promise<LensSearchResult[]> {
const variants = queryVariants(query);
if (!variants.length) return [];
const db = await loadLensDatabase();
const camera = await findCamera(meta?.camera);
const mount = camera?.mount ?? '';
const scored: { entry: LensEntry; score: number; rank: number }[] = [];
for (const entry of [...db.lenses, ...(await loadTeamEntries())]) {
const score = scoreEntry(entry, variants);
if (score < 0.5) continue;
// A mount the camera actually uses is a tie-break, never a filter: a
// profile that is in the database but filed under another mount must still
// be findable. A crop Canon body lists Canon EF-S, so EF glass (and the
// third-party lenses filed under it) only gets the family bonus.
const fits = !mount
? 0
: entry.mounts.includes(mount)
? 0.3
: entry.mounts.some((other) => sameMountFamily(other, mount))
? 0.1
: 0;
// `score` stays a pure name score so callers can trust a threshold;
// `rank` is what orders the list.
scored.push({ entry, score, rank: score + fits });
}
scored.sort((a, b) => b.rank - a.rank || a.entry.model.length - b.entry.model.length);
return scored.slice(0, 20).map(({ entry, score }) => toResult(entry, Math.min(3, score)));
}
export async function findLensForMeta(
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
): Promise<LensSearchResult | null> {
if (!meta.lens) return null;
const results = await searchLens(meta.lens, meta);
// Applying the wrong profile is worse than applying none: the closest match
// must share most of the EXIF name, not merely outrank the alternatives.
return results.find((result) => result.score >= 0.75) ?? null;
}
const cameraCache = new Map<string, CameraMatch | null>();
export async function findCamera(camera?: string): Promise<CameraMatch | null> {
if (!camera) return null;
const cached = cameraCache.get(camera);
if (cached !== undefined) return cached;
const db = await loadLensDatabase();
const query = tokens(camera);
let best: CameraMatch | null = null;
let bestScore = 0;
for (const entry of db.cameras) {
const target = new Set([...tokens(entry.maker), ...tokens(entry.model)]);
// Ignore the maker prefix the EXIF repeats, e.g. "NIKON CORPORATION".
const model = tokens(entry.model);
const score = Math.max(coverage(query, target), coverage(model, target) * 0.9);
if (score > bestScore) {
bestScore = score;
best = {
maker: entry.maker,
model: entry.model,
mount: entry.mount,
cropFactor: entry.crop,
score,
};
}
}
const match = bestScore >= 0.6 ? best : null;
cameraCache.set(camera, match);
return match;
}
/** Exact entry for a stored profile, falling back to the closest name match. */
export async function getLensEntry(profile: LensProfile): Promise<LensEntry | null> {
const db = await loadLensDatabase();
if (profile.id) {
if (profile.id.startsWith(TEAM_PREFIX)) {
const team = (await loadTeamEntries()).find((entry) => entry.id === profile.id);
if (team) return team;
}
const byId = db.lenses.find((entry) => entry.id === profile.id);
if (byId) return byId;
}
const maker = profile.maker.trim().toLowerCase();
const model = profile.model.trim().toLowerCase();
const exact = db.lenses.find(
(entry) => entry.maker.toLowerCase() === maker && entry.model.toLowerCase() === model,
);
if (exact) return exact;
const sameModel = db.lenses.filter((entry) => entry.model.toLowerCase() === model);
if (sameModel.length === 1) return sameModel[0];
const scored = db.lenses
.map((entry) => ({ entry, score: scoreEntry(entry, [profile.model, `${profile.maker} ${profile.model}`]) }))
.sort((a, b) => b.score - a.score);
return scored[0] && scored[0].score >= 0.5 ? scored[0].entry : null;
}
export async function availableFor(profile: LensProfile): Promise<number> {
const entry = await getLensEntry(profile);
return entry ? availableFlags(entry) : 0;
}
+45 -1
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { normalizeEdits, withoutLensVignetting } from './edits';
import { defaultForMeta, type CameraLensDefault } from './lensDefaults'; import { defaultForMeta, type CameraLensDefault } from './lensDefaults';
import type { LensProfile } from '../types'; import type { LensProfile, PhotoRecord } from '../types';
const profile = (model: string): LensProfile => ({ const profile = (model: string): LensProfile => ({
maker: 'Nikon', maker: 'Nikon',
@@ -64,4 +65,47 @@ describe('camera-lens default selection', () => {
).toBe(newer); ).toBe(newer);
}); });
it('leaves the vignetting correction off unless the profile asked for it', () => {
// Older saved profiles carry no corrections block at all; the flat-field
// gain would brighten the corners past the frame centre if it defaulted on.
const legacy = normalizeEdits({ lens: { maker: 'Nikon', model: 'Nikkor 50mm', crop: 1 } } as never);
expect(legacy.lens?.corrections).toEqual({ distortion: true, tca: true, vignetting: false });
const optedIn = normalizeEdits({
lens: {
maker: 'Nikon',
model: 'Nikkor 50mm',
crop: 1,
corrections: { distortion: true, tca: true, vignetting: true },
},
} as never);
expect(optedIn.lens?.corrections.vignetting).toBe(true);
});
it('clears a stored vignetting flag once, in edits, snapshots and history', () => {
const profile: LensProfile = {
maker: 'Canon',
model: 'EF 50mm',
crop: 1,
corrections: { distortion: true, tca: true, vignetting: true },
};
const photo = {
id: 'p1',
edits: { lens: profile },
snapshots: [{ id: 's1', name: 'Before', ts: 1, edits: { lens: profile } }],
history: [
{ label: 'Import', ts: 1, edits: { lens: profile } },
{ label: 'Exposure', ts: 2, edits: {} },
],
} as unknown as PhotoRecord;
const cleared = withoutLensVignetting(photo);
expect(cleared?.edits.lens?.corrections.vignetting).toBe(false);
expect(cleared?.snapshots?.[0].edits.lens?.corrections.vignetting).toBe(false);
expect(cleared?.history?.[0].edits.lens?.corrections.vignetting).toBe(false);
// Geometry and CA stay on: only the corner gain was the problem.
expect(cleared?.edits.lens?.corrections.distortion).toBe(true);
// Nothing left to do the second time, so the upgrade is idempotent.
expect(withoutLensVignetting(cleared as PhotoRecord)).toBeNull();
});
}); });
File diff suppressed because one or more lines are too long
+91
View File
@@ -0,0 +1,91 @@
import { describe, expect, it } from 'vitest';
import { autoScaleFor, computeMaps, type LensCorrection, type LensMap } from './lensEngine';
import { fixtureLenses, referenceCases } from './lensEngine.fixture';
const GRID = { width: 64, height: 43 };
function mapsFor(model: string, focal: number, aperture: number) {
const entry = fixtureLenses.find((lens) => lens.model === model);
expect(entry, model).toBeTruthy();
return computeMaps(entry!, {
...GRID,
focal,
crop: entry!.crop,
aperture,
distance: 1000,
distortion: true,
});
}
/**
* The reference values were captured from the Lensfun WebAssembly build this
* engine replaced, at 25 points of a 64x43 grid. Matching them proves the ported
* models (PanoTools and poly3 distortion, poly3 TCA, pa vignetting) agree with
* what the editor used to render.
*/
describe('lens engine matches the reference implementation', () => {
for (const testCase of referenceCases) {
it(`corrects ${testCase.model} the same way`, () => {
const maps = mapsFor(testCase.model, testCase.focal, testCase.aperture);
for (const point of testCase.points) {
const index = point.y * GRID.width + point.x;
const where = `${testCase.key} at ${point.x},${point.y}`;
expect(maps.geometry[index * 2], `${where} x`).toBeCloseTo(point.g[0], 3);
expect(maps.geometry[index * 2 + 1], `${where} y`).toBeCloseTo(point.g[1], 3);
if (point.t && maps.tca) {
expect(maps.tca[index * 6], `${where} red x`).toBeCloseTo(point.t[0], 3);
expect(maps.tca[index * 6 + 1], `${where} red y`).toBeCloseTo(point.t[1], 3);
expect(maps.tca[index * 6 + 4], `${where} blue x`).toBeCloseTo(point.t[2], 3);
expect(maps.tca[index * 6 + 5], `${where} blue y`).toBeCloseTo(point.t[3], 3);
}
if (point.v != null && maps.vignetting) {
expect(maps.vignetting[index * 3], `${where} gain`).toBeCloseTo(point.v, 3);
}
}
});
}
});
describe('lens engine basics', () => {
it('leaves coordinates untouched when the calibration has no distortion', () => {
const entry = { ...fixtureLenses[0], d: [] };
const maps = computeMaps(entry, { ...GRID, focal: 50, crop: entry.crop, distortion: true });
for (const [x, y] of [
[0, 0],
[31, 21],
[63, 42],
]) {
const index = y * GRID.width + x;
expect(maps.geometry[index * 2]).toBeCloseTo(x, 3);
expect(maps.geometry[index * 2 + 1]).toBeCloseTo(y, 3);
}
});
it('only emits the maps the calibration and the toggles ask for', () => {
const entry = fixtureLenses[0];
const plain = computeMaps(entry, { ...GRID, focal: 50, crop: entry.crop, distortion: false });
expect(plain.tca).toBeUndefined();
const cooled = computeMaps(entry, { ...GRID, focal: 28, crop: entry.crop, aperture: 2.8, distortion: true });
expect(cooled.tca?.length).toBe(GRID.width * GRID.height * 6);
expect(cooled.vignetting?.length).toBe(GRID.width * GRID.height * 3);
// Flat-field gains brighten the corners of a vignetted lens.
expect(cooled.vignetting![0]).toBeGreaterThan(cooled.vignetting![(21 * GRID.width + 31) * 3]);
});
it('scales up when the correction samples outside the frame', () => {
const geometry: LensMap = {
width: 3,
height: 3,
// Every sample points slightly outside the image.
data: new Float32Array(3 * 3 * 4),
};
for (let i = 0; i < 3 * 3; i++) {
geometry.data[i * 4] = -0.1;
geometry.data[i * 4 + 1] = -0.1;
geometry.data[i * 4 + 3] = 1;
}
const correction: LensCorrection = { key: 'test', geometry, scale: 1 };
expect(autoScaleFor(correction.geometry)).toBeGreaterThan(1);
});
});
+452
View File
@@ -0,0 +1,452 @@
import {
DIST_MODEL,
TCA_MODEL,
getLensEntry,
type DistortionSample,
type LensEntry,
type TcaSample,
type VignettingSample,
} from './lensDb';
import type { LensProfile, PhotoMeta } from '../types';
/**
* Lens correction without Lensfun's runtime.
*
* The calibration data comes from the Lensfun database (see `lensDb.ts`); the
* maths below is a port of the models it describes, evaluated in the same
* normalised coordinate system so results match what the previous WebAssembly
* build produced:
*
* norm = (36, 24) diagonal / crop / hypot(width + 1, height + 1) / focal
* x = column * norm - centreX
*
* Distortion maps sample the original image for each corrected pixel, TCA maps
* carry per-channel positions, and the vignetting map is a flat-field gain.
*/
export interface LensMap {
data: Float32Array;
width: number;
height: number;
}
export interface LensCorrection {
key: string;
geometry: LensMap;
/** RG offsets: red dx, red dy, blue dx, blue dy, normalized source units. */
tca?: LensMap;
/** RGB vignetting gains. */
vignette?: LensMap;
/** Centre zoom needed to hide transformed corners. */
scale: number;
}
const SENSOR_DIAGONAL = Math.hypot(36, 24);
const DEFAULT_ASPECT = 3 / 2;
const correctionCache = new Map<string, LensCorrection>();
function clampAspect(entry: LensEntry) {
return entry.aspect > 0 ? entry.aspect : DEFAULT_ASPECT;
}
/** Lensfun rescales each coefficient by focal / half-diagonal, per model. */
function distortionScale(entry: LensEntry, realFocal: number) {
const halfDiagonalMm = SENSOR_DIAGONAL / entry.crop / Math.hypot(clampAspect(entry), 1) / 2;
return realFocal / halfDiagonalMm;
}
function vignettingScale(entry: LensEntry, focal: number) {
const halfDiagonalMm = SENSOR_DIAGONAL / entry.crop / 2;
return focal / halfDiagonalMm;
}
/* ------------------------------------------------------------- interpolation */
function pickDistortion(entry: LensEntry, focal: number): DistortionSample | null {
const samples = entry.d;
if (!samples.length) return null;
return nearestByFocal(samples, focal);
}
function pickTca(entry: LensEntry, focal: number): TcaSample | null {
const samples = entry.t;
if (!samples.length) return null;
return nearestByFocal(samples, focal);
}
/**
* Linear in focal for a pair of samples that share a model; otherwise the
* closest focal. Lensfun uses splines, but at the handful of focal lengths
* these calibrations carry the difference is far below a pixel.
*/
function nearestByFocal<T extends number[]>(samples: T[], focal: number): T {
if (samples.length === 1 || !focal) return samples[0];
if (focal <= samples[0][0]) return samples[0];
const last = samples[samples.length - 1];
if (focal >= last[0]) return last;
let index = 0;
while (index < samples.length - 1 && samples[index + 1][0] < focal) index += 1;
const a = samples[index];
const b = samples[index + 1];
const span = b[0] - a[0];
if (!span) return a;
const t = (focal - a[0]) / span;
return a.map((value, i) => value + (b[i] - value) * t) as unknown as T;
}
/** Closest focal group, then closest aperture, then closest focus distance. */
function pickVignetting(entry: LensEntry, focal: number, aperture: number, distance: number): VignettingSample | null {
const samples = entry.v;
if (!samples.length) return null;
const closest = (values: number[], target: number) =>
values.reduce((best, value) => (Math.abs(value - target) < Math.abs(best - target) ? value : best), values[0]);
const focals = [...new Set(samples.map((sample) => sample[0]))];
const focalPick = focal ? closest(focals, focal) : focals[0];
let group = samples.filter((sample) => sample[0] === focalPick);
if (!group.length) group = samples;
const apertures = [...new Set(group.map((sample) => sample[1]))];
const aperturePick = aperture ? closest(apertures, aperture) : apertures[0];
group = group.filter((sample) => sample[1] === aperturePick);
if (!group.length) group = samples;
const distances = [...new Set(group.map((sample) => sample[2]))];
const distancePick = distance ? closest(distances, distance) : distances[0];
return group.find((sample) => sample[2] === distancePick) ?? group[0];
}
/* ------------------------------------------------------------------ the maps */
type TcaTerms =
| { model: 1; kr: number; kb: number }
| { model: 0; r: [number, number, number]; b: [number, number, number] };
export interface MapOptions {
width: number;
height: number;
focal: number;
crop: number;
aperture?: number;
distance?: number;
distortion: boolean;
}
export interface MapSet {
width: number;
height: number;
/** 2 floats per point: source x/y in map pixels. */
geometry: Float32Array;
/** 6 floats per point: red x/y, input x/y, blue x/y. */
tca?: Float32Array;
/**
* 3 floats per point: the same gain for R, G and B. Lensfun's vignetting
* model describes linear light, so the renderer must apply this after the
* sRGB decode rather than to encoded code values.
*/
vignetting?: Float32Array;
}
export function computeMaps(entry: LensEntry, options: MapOptions): MapSet {
const { width, height } = options;
const crop = options.crop || entry.crop;
const distortion = pickDistortion(entry, options.focal);
const realFocal = (distortion && distortion[5]) || options.focal;
const normScale = SENSOR_DIAGONAL / crop / Math.hypot(width, height) / realFocal || 1;
const centreSize = Math.min(width - 1, height - 1);
const centreX = ((width - 1) / 2 + (centreSize / 2) * entry.centerX) * normScale;
const centreY = ((height - 1) / 2 + (centreSize / 2) * entry.centerY) * normScale;
const scale = distortionScale(entry, realFocal);
const dTerms =
distortion && options.distortion
? {
model: distortion[1],
a: distortion[2],
b: distortion[3],
c: distortion[4],
scaled:
distortion[1] === DIST_MODEL.ptlens
? [distortion[2] * scale ** 3, distortion[3] * scale ** 2, distortion[4] * scale]
: distortion[1] === DIST_MODEL.poly5
? [0, distortion[3] * scale ** 2, distortion[4] * scale ** 4]
: [0, distortion[3] * scale ** 2, 0],
}
: null;
const tcaSample = options.distortion ? pickTca(entry, options.focal) : null;
const tcaTerms: TcaTerms | null = tcaSample
? tcaSample[1] === TCA_MODEL.linear
? { model: 1, kr: tcaSample[2], kb: tcaSample[5] }
: {
model: 0,
// r·(v + c·r + b·r²); c is scaled by focal, b by focal squared.
r: [tcaSample[2] * scale ** 2, tcaSample[3] * scale, tcaSample[4]],
b: [tcaSample[5] * scale ** 2, tcaSample[6] * scale, tcaSample[7]],
}
: null;
const vignSample = pickVignetting(entry, options.focal, options.aperture ?? 0, options.distance ?? 1000);
const vigScale = vignettingScale(entry, options.focal);
const vigTerms = vignSample
? [
vignSample[3] * vigScale ** 2,
vignSample[4] * vigScale ** 4,
vignSample[5] * vigScale ** 6,
]
: null;
const geometry = new Float32Array(width * height * 2);
const tca = tcaTerms ? new Float32Array(width * height * 6) : undefined;
const vignetting = vigTerms ? new Float32Array(width * height * 3) : undefined;
for (let row = 0; row < height; row++) {
const v = row * normScale - centreY;
for (let col = 0; col < width; col++) {
const u = col * normScale - centreX;
const radius2 = u * u + v * v;
const at = row * width + col;
let factor = 1;
if (dTerms) {
if (dTerms.model === DIST_MODEL.ptlens) {
const r = Math.sqrt(radius2);
factor = 1 + dTerms.scaled[0] * radius2 * r + dTerms.scaled[1] * radius2 + dTerms.scaled[2] * r;
} else if (dTerms.model === DIST_MODEL.poly5) {
factor = 1 + dTerms.scaled[1] * radius2 + dTerms.scaled[2] * radius2 * radius2;
} else if (dTerms.model === DIST_MODEL.poly3) {
factor = 1 + dTerms.scaled[1] * radius2;
}
}
geometry[at * 2] = (u * factor + centreX) / normScale;
geometry[at * 2 + 1] = (v * factor + centreY) / normScale;
if (tca && tcaTerms) {
const r = Math.sqrt(radius2);
if (tcaTerms.model === 1) {
tca[at * 6] = (u * tcaTerms.kr + centreX) / normScale;
tca[at * 6 + 1] = (v * tcaTerms.kr + centreY) / normScale;
tca[at * 6 + 4] = (u * tcaTerms.kb + centreX) / normScale;
tca[at * 6 + 5] = (v * tcaTerms.kb + centreY) / normScale;
} else {
const red = tcaTerms.r[0] * radius2 + tcaTerms.r[1] * r + tcaTerms.r[2];
const blue = tcaTerms.b[0] * radius2 + tcaTerms.b[1] * r + tcaTerms.b[2];
tca[at * 6] = (u * red + centreX) / normScale;
tca[at * 6 + 1] = (v * red + centreY) / normScale;
tca[at * 6 + 4] = (u * blue + centreX) / normScale;
tca[at * 6 + 5] = (v * blue + centreY) / normScale;
}
// Green keeps the input position; the renderer only needs red and blue.
tca[at * 6 + 2] = col;
tca[at * 6 + 3] = row;
}
if (vignetting && vigTerms) {
const gain =
1 / (1 + vigTerms[0] * radius2 + vigTerms[1] * radius2 ** 2 + vigTerms[2] * radius2 ** 3);
vignetting[at * 3] = gain;
vignetting[at * 3 + 1] = gain;
vignetting[at * 3 + 2] = gain;
}
}
}
return { width, height, geometry, tca, vignetting };
}
/* --------------------------------------------------------------- assembling */
function bilinear(values: Float32Array, w: number, h: number, x: number, y: number, stride: number, offset: number) {
const px = Math.max(0, Math.min(w - 1, x * (w - 1)));
const py = Math.max(0, Math.min(h - 1, y * (h - 1)));
const x0 = Math.floor(px);
const y0 = Math.floor(py);
const x1 = Math.min(w - 1, x0 + 1);
const y1 = Math.min(h - 1, y0 + 1);
const fx = px - x0;
const fy = py - y0;
const at = (xx: number, yy: number) => (yy * w + xx) * stride + offset;
const a = values[at(x0, y0)];
const b = values[at(x1, y0)];
const c = values[at(x0, y1)];
const d = values[at(x1, y1)];
return (a * (1 - fx) + b * fx) * (1 - fy) + (c * (1 - fx) + d * fx) * fy;
}
export function autoScaleFor(geometry: LensMap): number {
const sample = (x: number, y: number) => {
const px = x * (geometry.width - 1);
const py = y * (geometry.height - 1);
const x0 = Math.max(0, Math.min(geometry.width - 1, Math.floor(px)));
const y0 = Math.max(0, Math.min(geometry.height - 1, Math.floor(py)));
const x1 = Math.min(geometry.width - 1, x0 + 1);
const y1 = Math.min(geometry.height - 1, y0 + 1);
const fx = px - x0;
const fy = py - y0;
const at = (xx: number, yy: number) => (yy * geometry.width + xx) * 4;
const a = at(x0, y0);
const b = at(x1, y0);
const c = at(x0, y1);
const d = at(x1, y1);
return {
x: (geometry.data[a] * (1 - fx) + geometry.data[b] * fx) * (1 - fy) +
(geometry.data[c] * (1 - fx) + geometry.data[d] * fx) * fy,
y: (geometry.data[a + 1] * (1 - fx) + geometry.data[b + 1] * fx) * (1 - fy) +
(geometry.data[c + 1] * (1 - fx) + geometry.data[d + 1] * fx) * fy,
};
};
const inside = (scale: number) => {
for (let iy = 0; iy <= 24; iy++) {
for (let ix = 0; ix <= 24; ix++) {
const x = 0.5 + (ix / 24 - 0.5) / scale;
const y = 0.5 + (iy / 24 - 0.5) / scale;
const p = sample(x, y);
if (p.x < 0.001 || p.y < 0.001 || p.x > 0.999 || p.y > 0.999) return false;
}
}
return true;
};
if (inside(1)) return 1;
let lo = 1;
let hi = 2.5;
for (let i = 0; i < 12; i++) {
const mid = (lo + hi) / 2;
if (inside(mid)) hi = mid;
else lo = mid;
}
return hi;
}
export async function buildLensCorrection(
profile: LensProfile,
photo: { width: number; height: number; meta: Pick<PhotoMeta, 'focal' | 'aperture'> },
): Promise<LensCorrection> {
const key = `${profile.maker}\u0000${profile.model}|${profile.crop}|${photo.width}x${photo.height}|${
photo.meta.focal ?? 0
}|${photo.meta.aperture ?? 0}|${profile.corrections.distortion ? 1 : 0}${
profile.corrections.tca ? 1 : 0
}${profile.corrections.vignetting ? 1 : 0}|${profile.distance ?? 1000}`;
const cached = correctionCache.get(key);
if (cached) return cached;
const entry = await getLensEntry(profile);
if (!entry) throw new Error('Lens profile not found in the database');
const focal = Number(photo.meta.focal) || 0;
if (!focal) throw new Error('This photo has no focal length in its EXIF data');
const available =
(entry.d.length ? 8 : 0) | (entry.t.length ? 1 : 0) | (entry.v.length ? 2 : 0);
const useDistortion = profile.corrections.distortion && (available & 8) !== 0;
const useTca = profile.corrections.tca && (available & 1) !== 0;
const useVignetting =
profile.corrections.vignetting && (available & 2) !== 0 && Number(photo.meta.aperture) > 0;
const long = 640;
const aspect = Math.max(0.1, photo.width / Math.max(1, photo.height));
const mapW = aspect >= 1 ? long : Math.max(8, Math.round(long * aspect));
const mapH = aspect >= 1 ? Math.max(8, Math.round(long / aspect)) : long;
const maps = computeMaps(entry, {
width: mapW,
height: mapH,
focal,
crop: profile.crop,
aperture: Number(photo.meta.aperture) || 1,
distance: profile.distance ?? 1000,
distortion: useDistortion,
});
// Textures are RGBA32F so the renderer can use one upload path for all three
// maps. Geometry and TCA only need the first channels, but keeping four
// channels also means the texture is always fully specified.
const geometry = new Float32Array(mapW * mapH * 4);
for (let i = 0; i < mapW * mapH; i++) {
if (useDistortion) {
geometry[i * 4] = maps.geometry[i * 2] / Math.max(1, mapW - 1);
geometry[i * 4 + 1] = maps.geometry[i * 2 + 1] / Math.max(1, mapH - 1);
} else {
geometry[i * 4] = (i % mapW) / Math.max(1, mapW - 1);
geometry[i * 4 + 1] = Math.floor(i / mapW) / Math.max(1, mapH - 1);
}
geometry[i * 4 + 3] = 1;
}
const geometryMap: LensMap = { data: geometry, width: mapW, height: mapH };
let tca: LensMap | undefined;
if (useTca && maps.tca) {
tca = { data: new Float32Array(mapW * mapH * 4), width: mapW, height: mapH };
for (let i = 0; i < mapW * mapH; i++) {
const x = (i % mapW) / Math.max(1, mapW - 1);
const y = Math.floor(i / mapW) / Math.max(1, mapH - 1);
const gx = useDistortion ? geometry[i * 4] : x;
const gy = useDistortion ? geometry[i * 4 + 1] : y;
const rx = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 0) / Math.max(1, mapW - 1);
const ry = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 1) / Math.max(1, mapH - 1);
const bx = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 4) / Math.max(1, mapW - 1);
const by = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 5) / Math.max(1, mapH - 1);
tca.data[i * 4] = rx - gx;
tca.data[i * 4 + 1] = ry - gy;
tca.data[i * 4 + 2] = bx - gx;
tca.data[i * 4 + 3] = by - gy;
}
}
let vignette: LensMap | undefined;
if (useVignetting && maps.vignetting) {
vignette = { data: new Float32Array(mapW * mapH * 4), width: mapW, height: mapH };
for (let i = 0; i < mapW * mapH; i++) {
vignette.data[i * 4] = maps.vignetting[i * 3];
vignette.data[i * 4 + 1] = maps.vignetting[i * 3 + 1];
vignette.data[i * 4 + 2] = maps.vignetting[i * 3 + 2];
vignette.data[i * 4 + 3] = 1;
}
}
const correction: LensCorrection = {
key,
geometry: geometryMap,
tca,
vignette,
scale: useDistortion ? autoScaleFor(geometryMap) : 1,
};
correctionCache.set(key, correction);
return correction;
}
/* ------------------------------------------------------------- CPU map math */
export function sampleLensMap(map: LensMap, x: number, y: number): { x: number; y: number } {
return {
x: bilinear(map.data, map.width, map.height, x, y, 4, 0),
y: bilinear(map.data, map.width, map.height, x, y, 4, 1),
};
}
export function correctLensPoint(
correction: LensCorrection | null,
x: number,
y: number,
): { x: number; y: number } {
if (!correction) return { x, y };
const sx = 0.5 + (x - 0.5) / Math.max(1e-5, correction.scale);
const sy = 0.5 + (y - 0.5) / Math.max(1e-5, correction.scale);
return sampleLensMap(correction.geometry, sx, sy);
}
export function uncorrectLensPoint(
correction: LensCorrection | null,
x: number,
y: number,
): { x: number; y: number } {
if (!correction) return { x, y };
let px = x;
let py = y;
for (let i = 0; i < 10; i++) {
const mapped = correctLensPoint(correction, px, py);
px += x - mapped.x;
py += y - mapped.y;
}
return { x: px, y: py };
}
+98
View File
@@ -0,0 +1,98 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
TEAM_PREFIX,
deleteTeamProfile,
invalidateTeamProfiles,
loadTeamProfiles,
saveTeamProfile,
teamProfileToEntry,
type TeamLensProfile,
} from './lensProfiles';
const profile: TeamLensProfile = {
id: 'abc-123',
maker: 'Tamron',
model: 'SP 24-70mm f/2.8 Di VC USD',
mount: 'Canon EF',
crop: 1,
aspect: 0,
centerX: 0,
centerY: 0,
notes: '',
d: [[24, 2, 0.01, -0.02, 0.03, 0]],
t: [],
v: [],
createdBy: 'user-1',
createdAt: 1,
updatedAt: 1,
};
let calls: { url: string; method: string }[] = [];
function stubFetch(handler: (url: string, init?: RequestInit) => unknown) {
vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
calls.push({ url, method: init?.method ?? 'GET' });
return new Response(JSON.stringify(handler(url, init)), { status: 200 });
});
}
beforeEach(() => {
calls = [];
invalidateTeamProfiles();
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('team lens profiles', () => {
it('loads the list once and caches it', async () => {
stubFetch(() => ({ profiles: [profile] }));
const first = await loadTeamProfiles();
const second = await loadTeamProfiles();
expect(first).toHaveLength(1);
expect(second).toBe(first);
expect(calls.filter((call) => call.url === '/api/lens-profiles')).toHaveLength(1);
});
it('turns a saved profile into an entry the engine can use', () => {
const entry = teamProfileToEntry(profile);
expect(entry).toMatchObject({
id: `${TEAM_PREFIX}abc-123`,
maker: 'Tamron',
mounts: ['Canon EF'],
crop: 1,
team: true,
});
expect(entry.d).toHaveLength(1);
});
it('posts a new profile and drops the cached list', async () => {
stubFetch((url, init) => {
if (url === '/api/lens-profiles' && init?.method === 'POST') return { profile };
return { profiles: [profile] };
});
await loadTeamProfiles();
const { id: _id, createdBy: _by, createdAt: _at, updatedAt: _up, ...draft } = profile;
const saved = await saveTeamProfile(draft);
expect(saved.id).toBe('abc-123');
const post = calls.find((call) => call.method === 'POST');
expect(post?.url).toBe('/api/lens-profiles');
// The next read must go back to the server rather than the pre-save cache.
await loadTeamProfiles();
expect(calls.filter((call) => call.method === 'GET').length).toBe(2);
});
it('updates an existing profile with PUT to its id', async () => {
stubFetch(() => ({ profile }));
await saveTeamProfile({ ...profile, notes: 're-measured' });
expect(calls[0]).toEqual({ url: '/api/lens-profiles/abc-123', method: 'PUT' });
});
it('deletes by id', async () => {
stubFetch(() => ({ ok: true }));
await deleteTeamProfile('abc-123');
expect(calls[0]).toEqual({ url: '/api/lens-profiles/abc-123', method: 'DELETE' });
});
});
+90
View File
@@ -0,0 +1,90 @@
import { request } from './api';
import type { DistortionSample, LensEntry, TcaSample, VignettingSample } from './lensDb';
/**
* Lens calibrations measured by the team and stored on the server, so a lens
* the bundled database lacks can still be corrected for everyone. The rows use
* the same layout as the bundled profiles, which keeps one engine for both.
*/
/** Profile ids from this table carry this prefix so lookups know where to go. */
export const TEAM_PREFIX = 'team:';
export interface TeamLensProfile {
id: string;
maker: string;
model: string;
/** Mount the calibration was measured on; empty when the lens fits many. */
mount: string;
crop: number;
/** Calibration sensor aspect ratio, 0 when not recorded. */
aspect: number;
centerX: number;
centerY: number;
notes: string;
d: DistortionSample[];
t: TcaSample[];
v: VignettingSample[];
createdBy: string;
createdAt: number;
updatedAt: number;
}
export type TeamLensDraft = Pick<
TeamLensProfile,
'maker' | 'model' | 'mount' | 'crop' | 'aspect' | 'centerX' | 'centerY' | 'notes' | 'd' | 't' | 'v'
> & { id?: string };
let cache: Promise<TeamLensProfile[]> | null = null;
/** The team's calibrations, fetched once per session unless forced. */
export function loadTeamProfiles(force = false): Promise<TeamLensProfile[]> {
if (!cache || force) {
cache = request<{ profiles: TeamLensProfile[] }>('/api/lens-profiles')
.then((body) => (Array.isArray(body.profiles) ? body.profiles : []))
.catch((err) => {
cache = null;
throw err;
});
}
return cache;
}
/** Drop the cached list after a save or delete. */
export function invalidateTeamProfiles(): void {
cache = null;
}
export function teamProfileToEntry(profile: TeamLensProfile): LensEntry {
return {
id: `${TEAM_PREFIX}${profile.id}`,
maker: profile.maker,
model: profile.model,
crop: profile.crop,
mounts: profile.mount ? [profile.mount] : [],
aspect: profile.aspect,
centerX: profile.centerX,
centerY: profile.centerY,
d: profile.d,
t: profile.t,
v: profile.v,
team: true,
};
}
export async function saveTeamProfile(draft: TeamLensDraft): Promise<TeamLensProfile> {
const init: RequestInit = {
method: draft.id ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(draft),
};
const path = draft.id ? `/api/lens-profiles/${encodeURIComponent(draft.id)}` : '/api/lens-profiles';
const saved = await request<{ profile: TeamLensProfile }>(path, init);
invalidateTeamProfiles();
return saved.profile;
}
export async function deleteTeamProfile(id: string): Promise<void> {
await request(`/api/lens-profiles/${encodeURIComponent(id)}`, { method: 'DELETE' });
invalidateTeamProfiles();
}
-479
View File
@@ -1,479 +0,0 @@
import type {
CameraMatch,
CorrectionMaps,
LensMatch,
LensfunClient,
} from '@neoanaloglabkk/lensfun-wasm';
import { lensMatchScore, lensSearchVariants } from './lensNames';
import type { LensProfile, PhotoMeta } from '../types';
/**
* Lensfun is loaded on demand from public/lensfun. The database and the
* WebAssembly wrapper are third-party assets; see public/lensfun/NOTICE.md.
*/
export interface LensMap {
data: Float32Array;
width: number;
height: number;
}
export interface LensCorrection {
key: string;
geometry: LensMap;
/** RG offsets: red dx, red dy, blue dx, blue dy, normalized source units. */
tca?: LensMap;
/** RGB vignetting gains. */
vignette?: LensMap;
/** Centre zoom needed to hide transformed corners. */
scale: number;
}
const FLAG_TCA = 1;
const FLAG_VIGNETTING = 2;
const FLAG_DISTORTION = 8;
let clientPromise: Promise<LensfunClient> | null = null;
let client: LensfunClient | null = null;
const handleCache = new Map<string, LensMatch>();
const cameraCache = new Map<string, CameraMatch | null>();
const correctionCache = new Map<string, LensCorrection>();
async function loadCoreFactory(): Promise<(options?: Record<string, unknown>) => Promise<unknown>> {
const response = await fetch('/lensfun/lensfun-core.js');
if (!response.ok) throw new Error('Could not load the Lensfun runtime');
let source = await response.text();
// The 0.1.3 Emscripten build keeps the float heap view in a closure and the
// wrapper reads it from `module.HEAPF32`, so expose it after every memory
// resize. The asset itself is untouched on disk.
if (!source.includes('Module["HEAPF32"]')) {
const marker = 'HEAPF32=new Float32Array(b)';
if (!source.includes(marker)) throw new Error('Unexpected Lensfun runtime layout');
source = source.replace(marker, `${marker};Module["HEAPF32"]=HEAPF32;`);
}
const scriptUrl = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
try {
await new Promise<void>((resolve, reject) => {
const script = document.createElement('script');
script.src = scriptUrl;
script.onload = () => {
script.remove();
resolve();
};
script.onerror = () => {
script.remove();
reject(new Error('Could not start the Lensfun runtime'));
};
document.head.appendChild(script);
});
} finally {
URL.revokeObjectURL(scriptUrl);
}
const factory = (globalThis as Record<string, unknown>).createLensfunCoreModule;
if (typeof factory !== 'function') throw new Error('Lensfun runtime did not initialize');
return factory as (options?: Record<string, unknown>) => Promise<unknown>;
}
export async function getLensfun(): Promise<LensfunClient> {
if (client) return client;
if (!clientPromise) {
clientPromise = import('@neoanaloglabkk/lensfun-wasm')
.then(async ({ createLensfun }) => {
const moduleFactory = await loadCoreFactory();
return createLensfun({
moduleFactory,
wasmUrl: '/lensfun/lensfun-core.wasm',
dataUrl: '/lensfun/lensfun-core.data',
});
})
.then((instance) => {
client = instance;
return instance;
})
.catch((err) => {
clientPromise = null;
throw err;
});
}
return clientPromise;
}
export function profileKey(profile: LensProfile) {
return `${profile.maker}\u0000${profile.model}`;
}
export interface LensSearchResult {
maker: string;
model: string;
crop: number;
score: number;
available: number;
}
function toResult(match: LensMatch, available = 0): LensSearchResult {
return {
maker: match.maker,
model: match.model,
crop: match.cropFactor,
score: match.score,
available,
};
}
export async function searchLens(
query: string,
meta?: Pick<PhotoMeta, 'camera' | 'lens'>,
): Promise<LensSearchResult[]> {
const variants = lensSearchVariants(query);
if (!variants.length) return [];
const lf = await getLensfun();
const camera = cameraParts(meta?.camera);
const cameraFields = {
...(camera.maker ? { cameraMaker: camera.maker } : {}),
...(camera.model ? { cameraModel: camera.model } : {}),
};
const byName = new Map<string, LensMatch>();
for (const variant of variants) {
let matches: LensMatch[] = [];
try {
matches = lf.searchLenses({ lensModel: variant, ...cameraFields });
} catch {
matches = [];
}
if (!matches.length) {
try {
matches = lf.searchLenses({ lensModel: variant });
} catch {
matches = [];
}
}
for (const match of matches) {
const key = `${match.maker}\u0000${match.model}`;
if (!byName.has(key)) byName.set(key, match);
}
}
const crop = (await findCamera(meta?.camera))?.cropFactor || 1;
return [...byName.values()].slice(0, 20).map((match) => {
handleCache.set(`${match.maker}\u0000${match.model}`, match);
return toResult(match, lf.getAvailableModifications(match.handle, crop));
});
}
export async function findLensForMeta(
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
): Promise<LensSearchResult | null> {
if (!meta.lens) return null;
const results = await searchLens(meta.lens, meta);
if (!results.length) return null;
let best = results[0];
let score = lensMatchScore(meta.lens, best.model);
for (const candidate of results.slice(1)) {
const next = lensMatchScore(meta.lens, candidate.model);
if (next > score) {
best = candidate;
score = next;
}
}
return score > 0 ? best : null;
}
export async function resolveLens(profile: LensProfile): Promise<LensMatch | null> {
const key = profileKey(profile);
const cached = handleCache.get(key);
if (cached) return cached;
const lf = await getLensfun();
const cam = cameraParts(profile.cameraModel);
const cameraFields = {
...(profile.cameraMaker || cam.maker ? { cameraMaker: profile.cameraMaker ?? cam.maker } : {}),
...(profile.cameraModel || cam.model ? { cameraModel: cam.model ?? profile.cameraModel } : {}),
};
const tokens = profile.model.split(/\s+/).filter(Boolean);
const focal = tokens.find((token) => /^\d+(?:\.\d+)?mm$/i.test(token));
const aperture = tokens.find((token) => /^f\/\d+(?:\.\d+)?[a-z]*$/i.test(token));
const shortened = tokens
.filter((token) => !/^(af|af-s|af-i|ai|ai-s|ais|d|g|ed|vr|if|asp|ld|dx|fx)$/i.test(token))
.join(' ');
const queries: { lensMaker?: string; lensModel: string; cameraMaker?: string; cameraModel?: string }[] = [
{ ...cameraFields, lensMaker: profile.maker, lensModel: profile.model },
{ ...cameraFields, lensModel: profile.model },
{ ...cameraFields, lensModel: shortened },
...(focal
? [{ ...cameraFields, lensModel: [tokens[0], focal, aperture].filter(Boolean).join(' ') }]
: []),
];
const attempts: LensMatch[] = [];
for (const query of queries) {
try {
const found = lf.searchLenses(query);
if (found.length) {
attempts.push(...found);
break;
}
} catch {
/* try the next, looser query */
}
}
const exact =
attempts.find(
(match) =>
match.maker.toLowerCase() === profile.maker.toLowerCase() &&
match.model.toLowerCase() === profile.model.toLowerCase(),
) ?? attempts[0];
if (exact) handleCache.set(key, exact);
return exact ?? null;
}
export async function availableFor(profile: LensProfile): Promise<number> {
const match = await resolveLens(profile);
if (!match) return 0;
const lf = await getLensfun();
return lf.getAvailableModifications(match.handle, profile.crop);
}
/* ------------------------------------------------------------- camera search */
function cameraParts(camera?: string): { maker?: string; model?: string } {
if (!camera) return {};
const cleaned = camera.replace(/\s+/g, ' ').trim();
const lower = cleaned.toLowerCase();
const makerNames = [
'Nikon Corporation',
'Canon',
'Sony',
'FUJIFILM',
'Olympus',
'Panasonic',
'PENTAX',
'Sigma',
'Tamron',
'Leica',
'Hasselblad',
'Samsung',
'Ricoh',
];
const maker = makerNames.find((name) => lower.startsWith(name.toLowerCase()));
if (maker) {
return { maker, model: cleaned.slice(maker.length).trim() || cleaned };
}
const [first, ...rest] = cleaned.split(' ');
return rest.length ? { maker: first, model: rest.join(' ') } : { model: cleaned };
}
export async function findCamera(camera?: string): Promise<CameraMatch | null> {
if (!camera) return null;
const cached = cameraCache.get(camera);
if (cached !== undefined) return cached;
const lf = await getLensfun();
const parts = cameraParts(camera);
let found: CameraMatch[] = [];
try {
found = lf.searchCameras({ ...parts, searchFlags: 1 });
} catch {
found = [];
}
if (!found.length) {
try {
found = lf.searchCameras({ model: camera, searchFlags: 1 });
} catch {
found = [];
}
}
const best = found[0] ?? null;
cameraCache.set(camera, best);
return best;
}
/* ---------------------------------------------------------- correction maps */
export function autoScaleFor(geometry: LensMap): number {
const sample = (x: number, y: number) => {
const px = x * (geometry.width - 1);
const py = y * (geometry.height - 1);
const x0 = Math.max(0, Math.min(geometry.width - 1, Math.floor(px)));
const y0 = Math.max(0, Math.min(geometry.height - 1, Math.floor(py)));
const x1 = Math.min(geometry.width - 1, x0 + 1);
const y1 = Math.min(geometry.height - 1, y0 + 1);
const fx = px - x0;
const fy = py - y0;
const at = (xx: number, yy: number) => (yy * geometry.width + xx) * 4;
const a = at(x0, y0);
const b = at(x1, y0);
const c = at(x0, y1);
const d = at(x1, y1);
return {
x: (geometry.data[a] * (1 - fx) + geometry.data[b] * fx) * (1 - fy) +
(geometry.data[c] * (1 - fx) + geometry.data[d] * fx) * fy,
y: (geometry.data[a + 1] * (1 - fx) + geometry.data[b + 1] * fx) * (1 - fy) +
(geometry.data[c + 1] * (1 - fx) + geometry.data[d + 1] * fx) * fy,
};
};
const inside = (scale: number) => {
for (let iy = 0; iy <= 24; iy++) {
for (let ix = 0; ix <= 24; ix++) {
const x = 0.5 + (ix / 24 - 0.5) / scale;
const y = 0.5 + (iy / 24 - 0.5) / scale;
const p = sample(x, y);
if (p.x < 0.001 || p.y < 0.001 || p.x > 0.999 || p.y > 0.999) return false;
}
}
return true;
};
if (inside(1)) return 1;
let lo = 1;
let hi = 2.5;
for (let i = 0; i < 12; i++) {
const mid = (lo + hi) / 2;
if (inside(mid)) hi = mid;
else lo = mid;
}
return hi;
}
function bilinear(values: Float32Array, w: number, h: number, x: number, y: number, stride: number, offset: number) {
const px = Math.max(0, Math.min(w - 1, x * (w - 1)));
const py = Math.max(0, Math.min(h - 1, y * (h - 1)));
const x0 = Math.floor(px);
const y0 = Math.floor(py);
const x1 = Math.min(w - 1, x0 + 1);
const y1 = Math.min(h - 1, y0 + 1);
const fx = px - x0;
const fy = py - y0;
const at = (xx: number, yy: number) => (yy * w + xx) * stride + offset;
const a = values[at(x0, y0)];
const b = values[at(x1, y0)];
const c = values[at(x0, y1)];
const d = values[at(x1, y1)];
return (a * (1 - fx) + b * fx) * (1 - fy) + (c * (1 - fx) + d * fx) * fy;
}
export async function buildLensCorrection(
profile: LensProfile,
photo: { width: number; height: number; meta: Pick<PhotoMeta, 'focal' | 'aperture'> },
): Promise<LensCorrection> {
const key = `${profileKey(profile)}|${profile.crop}|${photo.width}x${photo.height}|${photo.meta.focal ?? 0}|${
photo.meta.aperture ?? 0
}|${profile.corrections.distortion ? 1 : 0}${profile.corrections.tca ? 1 : 0}${
profile.corrections.vignetting ? 1 : 0
}|${profile.distance ?? 1000}`;
const cached = correctionCache.get(key);
if (cached) return cached;
const match = await resolveLens(profile);
if (!match) throw new Error('Lens profile not found in the Lensfun database');
const focal = Number(photo.meta.focal) || 0;
if (!focal) throw new Error('This photo has no focal length in its EXIF data');
const lf = await getLensfun();
const available = lf.getAvailableModifications(match.handle, profile.crop);
const useDistortion =
profile.corrections.distortion && (available & FLAG_DISTORTION) !== 0;
const useTca = profile.corrections.tca && (available & FLAG_TCA) !== 0;
const useVignetting =
profile.corrections.vignetting &&
(available & FLAG_VIGNETTING) !== 0 &&
Number(photo.meta.aperture) > 0;
const long = 640;
const aspect = Math.max(0.1, photo.width / Math.max(1, photo.height));
const mapW = aspect >= 1 ? long : Math.max(8, Math.round(long * aspect));
const mapH = aspect >= 1 ? Math.max(8, Math.round(long / aspect)) : long;
const maps: CorrectionMaps = lf.buildCorrectionMaps({
lensHandle: match.handle,
width: mapW,
height: mapH,
focal,
crop: profile.crop,
step: 1,
includeTca: useTca,
includeVignetting: useVignetting,
aperture: Number(photo.meta.aperture) || 1,
distance: profile.distance ?? 1000,
});
// Textures are RGBA32F so the renderer can use one upload path for all three
// maps. Geometry and TCA only need the first channels, but keeping four
// channels also means the texture is always fully specified.
const geometry = new Float32Array(mapW * mapH * 4);
for (let i = 0; i < mapW * mapH; i++) {
if (useDistortion) {
geometry[i * 4] = maps.geometry[i * 2] / Math.max(1, mapW - 1);
geometry[i * 4 + 1] = maps.geometry[i * 2 + 1] / Math.max(1, mapH - 1);
} else {
geometry[i * 4] = (i % mapW) / Math.max(1, mapW - 1);
geometry[i * 4 + 1] = Math.floor(i / mapW) / Math.max(1, mapH - 1);
}
geometry[i * 4 + 3] = 1;
}
const geometryMap: LensMap = { data: geometry, width: mapW, height: mapH };
let tca: LensMap | undefined;
if (useTca && maps.tca) {
tca = { data: new Float32Array(mapW * mapH * 4), width: mapW, height: mapH };
for (let i = 0; i < mapW * mapH; i++) {
const x = (i % mapW) / Math.max(1, mapW - 1);
const y = Math.floor(i / mapW) / Math.max(1, mapH - 1);
const gx = useDistortion ? geometry[i * 4] : x;
const gy = useDistortion ? geometry[i * 4 + 1] : y;
const rx = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 0) / Math.max(1, mapW - 1);
const ry = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 1) / Math.max(1, mapH - 1);
const bx = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 4) / Math.max(1, mapW - 1);
const by = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 5) / Math.max(1, mapH - 1);
tca.data[i * 4] = rx - gx;
tca.data[i * 4 + 1] = ry - gy;
tca.data[i * 4 + 2] = bx - gx;
tca.data[i * 4 + 3] = by - gy;
}
}
let vignette: LensMap | undefined;
if (useVignetting && maps.vignetting) {
vignette = { data: new Float32Array(mapW * mapH * 4), width: mapW, height: mapH };
for (let i = 0; i < mapW * mapH; i++) {
vignette.data[i * 4] = maps.vignetting[i * 3];
vignette.data[i * 4 + 1] = maps.vignetting[i * 3 + 1];
vignette.data[i * 4 + 2] = maps.vignetting[i * 3 + 2];
vignette.data[i * 4 + 3] = 1;
}
}
const correction: LensCorrection = {
key,
geometry: geometryMap,
tca,
vignette,
scale: useDistortion ? autoScaleFor(geometryMap) : 1,
};
correctionCache.set(key, correction);
return correction;
}
/* ------------------------------------------------------------- CPU map math */
export function sampleLensMap(map: LensMap, x: number, y: number): { x: number; y: number } {
return {
x: bilinear(map.data, map.width, map.height, x, y, 4, 0),
y: bilinear(map.data, map.width, map.height, x, y, 4, 1),
};
}
export function correctLensPoint(
correction: LensCorrection | null,
x: number,
y: number,
): { x: number; y: number } {
if (!correction) return { x, y };
const sx = 0.5 + (x - 0.5) / Math.max(1e-5, correction.scale);
const sy = 0.5 + (y - 0.5) / Math.max(1e-5, correction.scale);
return sampleLensMap(correction.geometry, sx, sy);
}
export function uncorrectLensPoint(
correction: LensCorrection | null,
x: number,
y: number,
): { x: number; y: number } {
if (!correction) return { x, y };
let px = x;
let py = y;
for (let i = 0; i < 10; i++) {
const mapped = correctLensPoint(correction, px, py);
px += x - mapped.x;
py += y - mapped.y;
}
return { x: px, y: py };
}
+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);
});
});
+106
View File
@@ -0,0 +1,106 @@
import { describe, expect, it } from 'vitest';
import { defaultLocalLayer, MAX_LOCAL_COMPONENTS, normalizeEdits } from './edits';
/** Stored edits as they look before mask groups: geometry on the layer itself. */
function legacyLayer() {
return {
id: 'local-1',
name: 'Sky',
kind: 'gradientish' as unknown as string,
mode: 'subtract',
inverted: true,
feather: 20,
brush: { strokes: [] },
linear: { x1: 0.1, y1: 0.2, x2: 0.3, y2: 0.9 },
radial: { cx: 0.4, cy: 0.6, rx: 0.2, ry: 0.3 },
range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 },
curve: [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
],
adjust: {},
};
}
describe('mask groups', () => {
it('migrates a flat layer into a single component without changing the mask', () => {
const edits = normalizeEdits({ local: [legacyLayer()] as never });
const layer = edits.local[0];
expect(layer.components).toHaveLength(1);
const shape = layer.components[0];
// An unknown kind is a brush, as it always was; geometry and the layer's
// combine mode move onto the shape, layer mode stays for blending layers.
expect(shape.kind).toBe('brush');
expect(shape.mode).toBe('subtract');
expect(shape.inverted).toBe(true);
expect(shape.feather).toBe(20);
expect(shape.linear.x2).toBe(0.3);
expect(shape.radial.ry).toBe(0.3);
expect(layer.mode).toBe('subtract');
expect(layer.name).toBe('Sky');
});
it('keeps a stored component list in order with its own modes', () => {
const edit = normalizeEdits({
local: [
{
id: 'local-a',
name: 'Group',
mode: 'add',
components: [
{ id: 's1', kind: 'radial', mode: 'add', radial: { cx: 0.5, cy: 0.5, rx: 0.4, ry: 0.4 } },
{ id: 's2', kind: 'linear', mode: 'subtract', feather: 0, linear: { x1: 0, y1: 0, x2: 1, y2: 1 } },
{ id: 's3', kind: 'brush', mode: 'intersect', brush: { strokes: [] } },
],
curve: [],
adjust: {},
},
],
} as never);
const shapes = edit.local[0].components;
expect(shapes.map((shape) => shape.id)).toEqual(['s1', 's2', 's3']);
expect(shapes.map((shape) => shape.mode)).toEqual(['add', 'subtract', 'intersect']);
expect(shapes[1].kind).toBe('linear');
expect(shapes[2].kind).toBe('brush');
});
it('drops a raster component that lost its coverage instead of baking an empty mask', () => {
const edit = normalizeEdits({
local: [
{
id: 'local-r',
name: 'Raster',
mode: 'add',
components: [{ id: 's1', kind: 'raster', mode: 'add' }],
curve: [],
adjust: {},
},
],
} as never);
expect(edit.local[0].components[0].kind).toBe('brush');
expect(edit.local[0].components[0].raster).toBeUndefined();
});
it('always leaves a layer with at least one shape and caps the group', () => {
const many = Array.from({ length: MAX_LOCAL_COMPONENTS + 4 }, (_, i) => ({
id: `s${i}`,
kind: 'radial',
mode: 'add',
}));
const edit = normalizeEdits({
local: [
{ id: 'local-m', name: 'Many', mode: 'add', components: many, curve: [], adjust: {} },
{ id: 'local-e', name: 'Empty', mode: 'add', components: [], curve: [], adjust: {} },
],
} as never);
expect(edit.local[0].components).toHaveLength(MAX_LOCAL_COMPONENTS);
expect(edit.local[1].components).toHaveLength(1);
});
it('creates new layers with one shape so the panel always has something to edit', () => {
const layer = defaultLocalLayer('linear', 0);
expect(layer.components).toHaveLength(1);
expect(layer.components[0].kind).toBe('linear');
expect(layer.components[0].mode).toBe('add');
});
});
+40
View File
@@ -0,0 +1,40 @@
import { describe, expect, it } from 'vitest';
import { buildLocalCurveLUT } from '../gl/renderer';
/** Bytes of one LUT row (red channel; R/G/B are written identically). */
function row(data: Uint8Array, index: number) {
return Array.from(data.slice(index * 256 * 4, (index + 1) * 256 * 4)).filter((_, i) => i % 4 === 0);
}
describe('mask curve LUT', () => {
it('is the identity for a mask without a curve', () => {
const values = row(buildLocalCurveLUT([{}]), 0);
expect(values[0]).toBe(0);
expect(values[64]).toBeGreaterThan(60);
expect(values[64]).toBeLessThan(69);
expect(values[255]).toBe(255);
});
it('lifts only the row belonging to that mask', () => {
const data = buildLocalCurveLUT([{}, { curve: [{ x: 0, y: 0.25 }, { x: 1, y: 1 }] }]);
expect(row(data, 0)[64]).toBeLessThan(80);
expect(row(data, 1)[64]).toBeGreaterThan(100);
});
it('keeps an inverted curve monotonic instead of folding', () => {
// A curve that dips and rises again would posterise the masked area.
const values = row(
buildLocalCurveLUT([
{ curve: [{ x: 0, y: 0 }, { x: 0.3, y: 0.8 }, { x: 0.7, y: 0.2 }, { x: 1, y: 1 }] },
]),
0,
);
for (let i = 1; i < values.length; i++) expect(values[i]).toBeGreaterThanOrEqual(values[i - 1]);
});
it('fills all eight rows so a ninth mask cannot read stale data', () => {
const data = buildLocalCurveLUT([{ curve: [{ x: 0, y: 0 }, { x: 1, y: 0.5 }] }]);
expect(data.length).toBe(256 * 8 * 4);
expect(row(data, 7)[255]).toBe(255);
});
});
+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);
});
});
+1915 -82
View File
File diff suppressed because it is too large Load Diff
+193
View File
@@ -0,0 +1,193 @@
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('keeps the PNG row order so the sidecar matches the JPEG texture', async () => {
const parsed = await parsePreview16(
encodePng16(
[
[65535, 65535, 65535],
[0, 0, 0],
],
1,
2,
),
);
expect(parsed).not.toBeNull();
// Chrome ignores UNPACK_FLIP_Y_WEBGL for ImageBitmap uploads, so the JPEG
// proxy is top-down in the texture. Flipping here put the 16-bit sidecar
// upside down once it replaced the proxy a few seconds after load.
expect(parsed!.rgba[0]).toBe(0x3c00);
expect(parsed!.rgba[4]).toBe(0);
});
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();
});
});
+213
View File
@@ -0,0 +1,213 @@
/**
* 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 in the PNG's own
* top-down row order. That is the order the JPEG proxy already lands in: an
* ImageBitmap upload ignores `UNPACK_FLIP_Y_WEBGL`, so the sidecar has to match
* it row for row or the picture jumps upside down when it swaps in.
*/
export interface Preview16 {
width: number;
height: number;
/** RGBA half-float, top-down like the proxy, ready for `texImage2D` unflipped. */
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 = 0; y < height; y++) {
// Top-down: the JPEG texture is uploaded from an ImageBitmap, which ignores
// UNPACK_FLIP_Y_WEBGL, so both sources must hand the GPU the same row order.
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 } : {}) };
}
+375
View File
@@ -0,0 +1,375 @@
import { describe, expect, it } from 'vitest';
import {
buildProofCube,
GAMUT_DELTA,
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,
extra = [],
}: {
name: string;
colourSpace?: string;
pcs?: string;
a2b: Uint8Array;
b2a: Uint8Array;
/** Additional intent tables, e.g. A2B1/B2A1 for relative colorimetric. */
extra?: { signature: string; bytes: Uint8Array }[];
}): Uint8Array {
const tags: { signature: string; bytes: Uint8Array }[] = [
{ signature: 'desc', bytes: descTag(name) },
{ signature: 'A2B0', bytes: a2b },
{ signature: 'B2A0', bytes: b2a },
...extra,
];
let cursor = 128 + 4 + tags.length * 12;
const placed = tags.map((tag) => {
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('builds the round trip from the requested rendering intent', () => {
const identityTable = () => mft2({ map: identity });
// Relative colorimetric darkens what the printer returns, so its cube must
// differ from the perceptual one built from the primary tables.
const profile = parseIcc(
buildIcc({
name: 'Two intents',
a2b: identityTable(),
b2a: identityTable(),
extra: [
{ signature: 'A2B1', bytes: mft2({ map: ([lightness, a, b]) => [lightness * 0.6, a, b] }) },
{ signature: 'B2A1', bytes: identityTable() },
],
}),
)!;
expect(profile.a2bIntents[1]).not.toBeNull();
const perceptual = cubeAt(buildProofCube(profile, 9), 4, 4, 4)[0];
const relative = cubeAt(buildProofCube(profile, 9, GAMUT_DELTA, 'relative'), 4, 4, 4)[0];
expect(perceptual).toBeCloseTo(0.5, 2);
expect(relative).toBeLessThan(perceptual - 0.05);
});
it('falls back to the perceptual pair when an intent has no tables', () => {
const profile = parseIcc(
buildIcc({ name: 'One intent', a2b: mft2({ map: identity }), b2a: mft2({ map: identity }) }),
)!;
const saturation = buildProofCube(profile, 5, GAMUT_DELTA, 'saturation');
expect(cubeAt(saturation, 2, 2, 2)[0]).toBeCloseTo(0.5, 2);
});
it('refuses a profile without a round trip', () => {
const bytes = buildIcc({
name: 'Half',
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/);
});
});
+738
View File
@@ -0,0 +1,738 @@
/**
* 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.
*/
import type { ProofIntent } from '../types';
const D50_WHITE = [0.9642, 1, 0.8249] as const;
/** Linear sRGB (D50 adapted) to XYZ, matching the primaries in `icc.ts`. */
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;
/** Device→PCS tables by intent: perceptual, relative colorimetric, saturation. */
a2bIntents: (IccTransform | null)[];
/** PCS→device tables by intent, in the same order. */
b2aIntents: (IccTransform | null)[];
}
export interface SoftProofCube {
/** 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');
const a2bIntents = [transform('A2B0', true), transform('A2B1', true), transform('A2B2', true)];
const b2aIntents = [transform('B2A0', false), transform('B2A1', false), transform('B2A2', false)];
return {
name: (description && parseDescription(view, description.at, description.size)) || 'ICC profile',
profileClass: ascii(12),
colourSpace,
pcs,
// Perceptual first, then relative colorimetric: a printer profile often
// ships one and not the other. The full table set is kept as well, so the
// proof can be rebuilt for a different rendering intent.
a2b: a2bIntents[0] ?? a2bIntents[1],
b2a: b2aIntents[0] ?? b2aIntents[1],
a2bIntents,
b2aIntents,
};
}
/* --------------------------------------------------------------- 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.
*/
const INTENT_SLOT: Record<ProofIntent, number> = {
perceptual: 0,
relative: 1,
saturation: 2,
};
/**
* The table pair for an intent. Perceptual uses the primary pair, which is what
* a profile that only ships one set provides and what hand-built profiles in
* tests carry. Other intents need both of their own tables; falling back to the
* perceptual pair keeps a profile that omits saturation usable (many output
* profiles do) instead of refusing to proof at all.
*/
function tablesForIntent(
profile: IccProfile,
intent: ProofIntent,
): { a2b: IccTransform; b2a: IccTransform } | null {
if (INTENT_SLOT[intent] === 0) {
return profile.a2b && profile.b2a ? { a2b: profile.a2b, b2a: profile.b2a } : null;
}
const slot = INTENT_SLOT[intent];
const a2b = profile.a2bIntents?.[slot] ?? profile.a2b;
const b2a = profile.b2aIntents?.[slot] ?? profile.b2a;
return a2b && b2a ? { a2b, b2a } : null;
}
export function buildProofCube(
profile: IccProfile,
size = 33,
gamutDelta = GAMUT_DELTA,
intent: ProofIntent = 'perceptual',
): SoftProofCube {
const tables = tablesForIntent(profile, intent);
if (!tables) {
throw new Error('This profile has no A2B/B2A tables, so it cannot be soft proofed');
}
const edge = Math.max(2, Math.min(65, Math.round(size)));
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(tables.b2a, pcs);
const printed = evaluate(tables.a2b, device);
const back = decodePcs(profile.pcs, printed);
const rgb = multiply3(XYZ_TO_RGB, back.xyz);
data[at++] = clamp01(linearToSrgb(rgb[0]));
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;
/**
* The bytes behind the active cube. Kept so changing the rendering intent can
* rebuild the table without asking for the file again, and so the profile can
* be restored in the next session.
*/
let activeBytes: Uint8Array | null = null;
/** Clears the active profile; the bytes go too, so an intent change cannot
* silently re-install a profile the user switched off. */
export function setActiveProofCube(cube: SoftProofCube | null) {
active = cube;
if (!cube) activeBytes = null;
}
export function getActiveProofCube(): SoftProofCube | null {
return active;
}
function activate(bytes: Uint8Array, size: number, intent: ProofIntent): SoftProofCube {
const profile = parseIcc(bytes);
if (!profile) throw new Error('That file is not an ICC profile');
const cube = buildProofCube(profile, size, GAMUT_DELTA, intent);
activeBytes = bytes.slice();
active = cube;
return cube;
}
/** Parses a .icc/.icm file and makes it the active proof profile. */
export function loadProofProfile(
bytes: Uint8Array,
size = 33,
intent: ProofIntent = 'perceptual',
): SoftProofCube {
return activate(bytes, size, intent);
}
/**
* Rebuilds the active profile for a different intent. Returns null when no
* profile is loaded, so the caller can leave the paper simulation alone.
*/
export function rebuildProofCube(intent: ProofIntent, size = 33): SoftProofCube | null {
if (!activeBytes) return null;
try {
return activate(activeBytes, size, intent);
} catch {
return null;
}
}
/* ------------------------------------------------- persisted proof profile */
const PROOF_DB = 'lumenroom.proof';
const PROOF_STORE = 'profile';
const PROOF_KEY = 'active';
let proofDb: Promise<IDBDatabase> | null = null;
/**
* A one-store database for the loaded printer profile. It is separate from the
* catalogue so a server-backed workspace can remember the profile on this
* device without writing a megabyte into a photo record or the SQLite catalog.
*/
function openProofDb(): Promise<IDBDatabase> {
if (proofDb) return proofDb;
proofDb = new Promise((resolve, reject) => {
if (typeof indexedDB === 'undefined') {
reject(new Error('IndexedDB is unavailable'));
return;
}
const req = indexedDB.open(PROOF_DB, 1);
req.onupgradeneeded = () => {
if (!req.result.objectStoreNames.contains(PROOF_STORE)) {
req.result.createObjectStore(PROOF_STORE);
}
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error ?? new Error('Unable to open the proof profile store'));
});
return proofDb;
}
/** Remembers the active profile for the next session; failures are harmless. */
export async function persistProofProfile(): Promise<void> {
if (!activeBytes) return;
try {
const db = await openProofDb();
const bytes = activeBytes.slice();
const name = active?.name ?? 'ICC profile';
await new Promise<void>((resolve, reject) => {
const tx = db.transaction(PROOF_STORE, 'readwrite');
tx.objectStore(PROOF_STORE).put({ name, bytes }, PROOF_KEY);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error ?? new Error('Could not save the proof profile'));
});
} catch {
/* Private mode or no IndexedDB: the profile still lasts for this session. */
}
}
export async function clearPersistedProofProfile(): Promise<void> {
try {
const db = await openProofDb();
await new Promise<void>((resolve, reject) => {
const tx = db.transaction(PROOF_STORE, 'readwrite');
tx.objectStore(PROOF_STORE).delete(PROOF_KEY);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error ?? new Error('Could not clear the proof profile'));
});
} catch {
/* nothing persisted to clear */
}
}
/** Loads the profile saved by a previous session and rebuilds its cube. */
export async function restoreProofProfile(
intent: ProofIntent = 'perceptual',
): Promise<SoftProofCube | null> {
try {
const db = await openProofDb();
const stored = await new Promise<{ bytes?: Uint8Array } | undefined>((resolve, reject) => {
const req = db.transaction(PROOF_STORE, 'readonly').objectStore(PROOF_STORE).get(PROOF_KEY);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
if (!stored?.bytes) return null;
return activate(stored.bytes, 33, intent);
} catch {
return null;
}
}

Some files were not shown because too many files have changed in this diff Show More