Compare commits
8 Commits
e0c76ba965
...
9051b9cfc1
| Author | SHA1 | Date | |
|---|---|---|---|
| 9051b9cfc1 | |||
| d4cce4e001 | |||
| 749047ae9e | |||
| 16456c3c69 | |||
| 637629385a | |||
| 0c113e7a91 | |||
| 6dfddffc14 | |||
| 0b3ab76405 |
@@ -62,16 +62,22 @@ changing the current filters.
|
||||
**Develop.** A WebGL2 multi-pass pipeline (`src/gl/renderer.ts`), per photo,
|
||||
non-destructive:
|
||||
|
||||
- white balance, exposure, contrast, highlights/shadows/whites/blacks
|
||||
- texture, clarity, dehaze, vibrance, saturation, black & white mix
|
||||
- RGB and per-channel tone curves
|
||||
- 8-band HSL colour mixer, split toning / colour grading
|
||||
- white balance as a relative Temp/Tint offset or an absolute Kelvin value with a
|
||||
5500 K daylight reference, exposure, contrast, and hue-preserving
|
||||
highlights/shadows/whites/blacks
|
||||
- per-channel highlight recovery, texture, clarity, per-pixel dehaze, vibrance,
|
||||
saturation, black & white mix
|
||||
- input levels (black point, white point, midtone gamma), RGB and per-channel tone
|
||||
curves
|
||||
- 8-band HSL colour mixer evaluated in OkLCh (hue and chroma changes keep their
|
||||
perceived lightness), split toning / colour grading
|
||||
- sharpening, luminance noise reduction
|
||||
- vignette, grain
|
||||
- crop with nine aspect ratios, straighten, 90° rotation, flips
|
||||
- local adjustments (up to four layers): brush, linear gradient and radial masks with
|
||||
feather, invert, luminance/hue/saturation ranges, and per-layer exposure, contrast,
|
||||
highlights, shadows, temperature, tint and saturation. Masks follow crops, zoom,
|
||||
- local adjustments (up to eight layers): brush, linear gradient and radial masks
|
||||
with feather, invert, luminance/hue/saturation ranges, and per-layer exposure,
|
||||
contrast, highlights, shadows, whites, blacks, temperature, tint, saturation,
|
||||
vibrance, hue, texture, clarity, dehaze and sharpening. Masks follow crops, zoom,
|
||||
healing and lens correction; Copy mask / Paste mask move one layer between photos
|
||||
- full Lensfun profiles: distortion, transverse chromatic aberration and vignetting
|
||||
from the official database, with manual lens search, "Match EXIF lens"
|
||||
@@ -87,8 +93,8 @@ non-destructive:
|
||||
- histogram, built-in and saved presets, history with undo/redo, selective
|
||||
copy/paste and batch sync, named snapshots, virtual copies, before/after (**\**)
|
||||
- on-device auto subject, sky and background masks (no model download), an
|
||||
ISO/camera-aware noise starting point, edge-aware lens-softness compensation, and an
|
||||
approximate paper soft-proof preview
|
||||
ISO/camera-aware noise starting point, edge-aware lens-softness compensation, and soft
|
||||
proofing through a loaded printer ICC profile (or a paper simulation when none is)
|
||||
- HDR merge with alignment, horizontal panorama stitching and focus stacking; each
|
||||
result is added to the catalog as a new editable photo
|
||||
- browser print layouts (A4, Letter, 5×7) rendered through the develop pipeline
|
||||
@@ -97,7 +103,9 @@ non-destructive:
|
||||
Clients need no account: they see that event's live photos, heart favourites, leave
|
||||
per-photo comments, mark a photo approved or needing changes, and download proofs
|
||||
individually or as one ZIP. Feedback shows up on the library grid and in the "Client
|
||||
picks", "Approved" and "Changes" filters. Revoking a link drops its picks and feedback.
|
||||
picks", "Approved" and "Changes" filters. Each link can carry a password, a closing
|
||||
date, a download cap or downloads switched off, and a watermark that is rendered into
|
||||
newly published proofs. Revoking a link drops its picks, feedback and access settings.
|
||||
|
||||
**Team accounts.** The first signup becomes the admin. Admins create single-use invite
|
||||
links (`/join/<token>`) with an optional email lock and 1–30 day expiry, copy them from
|
||||
@@ -111,6 +119,22 @@ quota, schedule a 24-hour cleanup of the oldest content, send a warning immediat
|
||||
cancel a scheduled cleanup. Cleanups stop at a target percentage of the quota instead
|
||||
of deleting the whole original plan.
|
||||
|
||||
**Tethering.** Watch a folder on the server for an event: the editor polls it, pulls
|
||||
each new JPEG/TIFF/WebP/raw, imports it through the normal path (raw decode, metadata,
|
||||
cloud mirroring) and only then removes the file from the folder. Point a capture app or
|
||||
a transfer folder at `<data>/tether/<event>`; nothing is lost if the tab closes.
|
||||
|
||||
**Cull assist.** Run a focus and duplicate pass over the selection from the command
|
||||
palette. Every frame is scored from its own thumbnail with a Laplacian variance, and
|
||||
near-duplicates are grouped by 64-bit difference hash, so the sharpest frame of a
|
||||
burst can be kept and the alternatives flagged in one action. Nothing is rated or
|
||||
rejected without confirmation.
|
||||
|
||||
**Sidecars.** Export the selected photos' develop settings as Lightroom-style `.xmp`
|
||||
sidecars (crs: attributes plus a private payload for the rest of the grade) and import
|
||||
a sidecar back onto a photo. Importing keeps the crop, masks and lens profile for every
|
||||
field the file does not mention.
|
||||
|
||||
**Catalog workflow.** Editable title, caption, creator, copyright and keyword chips
|
||||
with a keyword library and reusable metadata presets. Save the current filters and sort
|
||||
order as a smart collection. Virtual copies share the master file but keep independent
|
||||
@@ -118,9 +142,10 @@ edits; named snapshots preserve alternative looks.
|
||||
|
||||
**Export and print.** JPEG, PNG, WebP or uncompressed 16-bit TIFF; quality; resize by
|
||||
long edge or percent; filename template (`{name}`, `{date}`, `{time}`, `{index}`); saved
|
||||
export recipes; output sharpening; watermark; XMP metadata embedded in JPEGs; an
|
||||
embedded sRGB ICC profile; batch export as one ZIP or separate files. Full-resolution
|
||||
export runs through the same renderer as the screen preview.
|
||||
export recipes; output sharpening; watermark; XMP metadata embedded in JPEGs; sRGB,
|
||||
Display P3 or Adobe RGB output with a matching generated ICC profile (JPEG/TIFF); batch
|
||||
export as one ZIP or separate files. Full-resolution export runs through the same
|
||||
renderer as the screen preview.
|
||||
|
||||
**Administration.** Users, roles, invites, catalog backup/restore, per-account quotas,
|
||||
email settings and a storage relocation tool are all in one panel.
|
||||
@@ -199,9 +224,12 @@ storage, while quotas are stored per account in the database.
|
||||
| `PORT` | `8787` | HTTP port (**not** prefixed with `LUMINARY_`) |
|
||||
| `HOST` | `0.0.0.0` | Bind address (**not** prefixed) |
|
||||
| `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_MAX_UPLOAD` | `314572800` (300 MB) | Largest accepted upload, in bytes |
|
||||
| `LUMINARY_RAW_EDGE` | `6000` | Long edge of the editable JPEG proxy made from a raw |
|
||||
| `LUMINARY_16BIT` | `1` | Also keep the decoded samples as a 16-bit PNG beside the raw proxy; `0` saves the disk and download it costs, at the price of grading an 8-bit source |
|
||||
| `LUMINARY_RAW_WORKERS` | `min(4, cores−1)` | Concurrent LibRaw decoders; each holds a worker and a few hundred MB |
|
||||
| `LUMINARY_RAW_IDLE_MS` | `90000` | Idle decoders are disposed after this to release memory |
|
||||
| `LUMINARY_DENOISE_WORKERS` | `min(4, cores−1)` | Concurrent detail-denoise jobs (read directly from the environment) |
|
||||
@@ -230,6 +258,15 @@ directly and have no legacy alias.
|
||||
per-user salt and a 64-byte derived key.
|
||||
- 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`.
|
||||
- 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.
|
||||
- The SQLite file, the IndexedDB database and the Compose volume all keep the
|
||||
`lumenroom` name so older deployments upgrade in place.
|
||||
@@ -299,7 +336,9 @@ Two independent things to back up:
|
||||
|
||||
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
|
||||
`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
|
||||
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
|
||||
@@ -414,9 +453,14 @@ Data directory
|
||||
| `src/lib/import.ts` | File ingest, EXIF read, preview/thumb creation, upload scheduling |
|
||||
| `src/lib/export.ts` | Renderer-driven export, recipes, watermark, filenames, ZIP |
|
||||
| `src/lib/tiff.ts`, `icc.ts` | Dependency-free 16-bit TIFF writer and sRGB profile |
|
||||
| `src/lib/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/autoMask.ts`, `noiseProfile.ts` | On-device masks and ISO-aware noise starting points |
|
||||
| `src/lib/xmp.ts` | Lightroom-compatible XMP sidecar reader/writer |
|
||||
| `src/lib/cull.ts` | Focus scoring and duplicate hashing for cull assist |
|
||||
| `src/lib/curves.ts`, `whiteBalance.ts`, `clipPreview.ts`, `presets.ts` | Curve sampling, WB maths, clipping display, presets |
|
||||
| `docs/user-guide/` | Source of the in-app user guide (`guide.html`), also shipped as PDF |
|
||||
|
||||
@@ -439,7 +483,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_reviews` | per-token, per-photo, per-client approved / changes status |
|
||||
| `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 |
|
||||
|
||||
Photo and event records are JSON documents with a few extracted columns for ordering,
|
||||
@@ -497,7 +541,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/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 |
|
||||
| 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 |
|
||||
| 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/` |
|
||||
@@ -524,7 +578,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/preview` | public | Gallery preview |
|
||||
| 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/comments` | public | Append a client comment |
|
||||
| POST | `/api/galleries/:token/reviews` | public | Set approved / changes / none |
|
||||
@@ -665,14 +719,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
|
||||
|
||||
The browser cannot demosaic camera raw, so the server does it during upload:
|
||||
|
||||
1. The original file is stored byte-for-byte in `originals/` with its real extension.
|
||||
2. LibRaw (`libraw-wasm`) opens it in a pooled worker with camera white balance, sRGB
|
||||
output and the container's orientation, then `sharp` encodes an editable JPEG proxy
|
||||
at `LUMINARY_RAW_EDGE` (6000 px by default).
|
||||
2. LibRaw (`libraw-wasm`) opens it in a pooled worker with camera white balance and the
|
||||
container's orientation and returns the frame **before** any output colourspace
|
||||
(`outputColor: 0`). The camera-to-sRGB step is then the body's own `rgb_cam` matrix,
|
||||
applied in `server/color.mjs` — the same 3×3 matrix the editor applies to the sidecar,
|
||||
so changing the camera profile is a matrix swap rather than a second decode. One
|
||||
white point is chosen for the frame from the matrixed pixels (99th percentile, the
|
||||
clipping policy LibRaw's auto-bright targets) and baked into both outputs; LibRaw's
|
||||
own auto-bright measures each output path separately and would leave the JPEG a third
|
||||
of a stop away from the sidecar. `sharp` encodes the editable JPEG proxy at
|
||||
`LUMINARY_RAW_EDGE` (6000 px by default). The same decode also writes a 16-bit PNG of
|
||||
the camera samples beside it (`previews/<id>.p16.png`, roughly 25× the JPEG) with the
|
||||
matrix in a `tEXt` chunk: the editor inflates that sidecar into an `RGBA16F` source
|
||||
texture and applies `rgb_cam` in the grade shader, so the grade has 65,536 levels per
|
||||
channel instead of 256. A photo without a sidecar — one imported before this existed,
|
||||
a non-raw file, or a build with `LUMINARY_16BIT=0` — simply grades the JPEG, so
|
||||
nothing breaks either way. 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
|
||||
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.
|
||||
@@ -683,6 +853,17 @@ Formats: CR2/CR3/CRW, NEF/NRW, ARW/SRF/SR2, ORF, RW2/RWL/RAW, RAF, PEF, DNG, SRW
|
||||
FFF, IIQ, X3F, ERF, K25/KDC, DCR, MOS, MRW, MEF, SRAW. Content sniffing checks the
|
||||
container signature before wasting a decode attempt.
|
||||
|
||||
**Camera-native conversion, measured.** `rgb_cam` is applied to the sRGB-decoded camera
|
||||
samples; `outputColor: 0` output is sRGB-encoded, not linear (a power curve fits it
|
||||
1.8 ΔE worse). Against LibRaw's sRGB + auto-bright output on this repository's test
|
||||
raws, the new proxy sits at mean ΔE 0.3–2.4 on normally exposed frames with the same
|
||||
~1 % highlight clipping, and 5.5 on one very dark frame where the two auto-bright
|
||||
policies disagree most — one shared white point cannot match a per-path heuristic
|
||||
exactly. Applying the sidecar's matrix in the shader reproduces the server-encoded
|
||||
proxy to within one 8-bit code, so the two outputs cannot drift apart. Deriving the
|
||||
same matrix from a DCP `ColorMatrix1` — `inverse(rowNormalise(ColorMatrix · xyz_rgb))`
|
||||
— matches LibRaw's `rgb_cam` to 2.2e-5 on a D700 NEF and 2.7e-5 on a 5D Mark II CR2.
|
||||
|
||||
**Parallel import.** Decoding runs in a bounded pool of LibRaw workers (default
|
||||
`min(4, cores−1)`, `LUMINARY_RAW_WORKERS`), and the browser uploads several files at a
|
||||
time. Each instance owns one worker thread; extra jobs queue. Idle instances are
|
||||
@@ -730,28 +911,35 @@ licensed implementation.
|
||||
|
||||
## Lens profiles
|
||||
|
||||
Lens correction uses the [Lensfun](https://lensfun.github.io/) camera and lens database
|
||||
through the [`@neoanaloglabkk/lensfun-wasm`](https://github.com/lexluthor0304/LensfunWasm)
|
||||
build. Runtime assets are served from `public/lensfun/`.
|
||||
Lens correction uses the calibration data of the
|
||||
[Lensfun](https://lensfun.github.io/) camera and lens database, converted at build time
|
||||
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
|
||||
[CC BY-SA 3.0 Unported](https://creativecommons.org/licenses/by-sa/3.0/), taken from
|
||||
Lensfun `data/db` at commit
|
||||
[`655a9c4`](https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data).
|
||||
It is redistributed as bundled by the wrapper build; Luminary adds no profiles of its
|
||||
own.
|
||||
- **Library** — Lensfun is LGPL-3.0 (the bundled notice states "or later"), compiled to
|
||||
WebAssembly. Corresponding source is the upstream repository at the pinned commit plus
|
||||
the wrapper's build scripts.
|
||||
- **Bundled files** — `public/lensfun/LICENSE` is the **MIT licence of the WASM
|
||||
wrapper**, not of the database or the library. `NOTICE.md`,
|
||||
`THIRD_PARTY_LICENSES.md` and `UPSTREAM.md` record the other components and the pin.
|
||||
[`655a9c4`](https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data)
|
||||
and converted by `scripts/build-lens-db.mjs` into `public/lens-db/profiles.json`.
|
||||
Luminary adds no profiles of its own.
|
||||
- **Engine** — `src/lib/lensDb.ts` (loading, matching, camera lookup) and
|
||||
`src/lib/lensEngine.ts` (maps, auto-scale), both MIT like the rest of the app code.
|
||||
- **Team calibrations** — lenses the database lacks can be measured in-house and added
|
||||
from the Optics panel (“Team calibrations”). They are stored in the server's SQLite
|
||||
database (`lens_profiles`), searched next to the bundled profiles with the same sample
|
||||
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
|
||||
redistributing the app or its container image.
|
||||
|
||||
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
|
||||
positions. Camera-lens defaults require both a normalised camera and lens name to match.
|
||||
|
||||
@@ -784,7 +972,7 @@ Conventions worth knowing before changing code:
|
||||
|
||||
### Tests
|
||||
|
||||
`npm test` runs six Vitest files, all pure-logic:
|
||||
`npm test` runs the pure-logic Vitest suite:
|
||||
|
||||
| File | Covers |
|
||||
| --- | --- |
|
||||
@@ -794,6 +982,10 @@ Conventions worth knowing before changing code:
|
||||
| `src/lib/lensNames.test.ts` | EXIF lens-name normalisation, search variants and match scoring |
|
||||
| `src/lib/lensDefaults.test.ts` | Camera + lens default selection and rejection rules |
|
||||
| `src/lib/editSections.test.ts` | Selective settings copy and the ISO-aware auto-noise curve |
|
||||
| `src/lib/preview16.test.ts` | 16-bit PNG proxy parsing, row flip, half-float encoding and the camera matrix chunk |
|
||||
| `src/lib/dcp.test.ts` | DCP tag parsing and the camera matrix recipe against LibRaw's own values |
|
||||
| `src/lib/softProof.test.ts` | ICC parsing (including counted lut16 tables), the printer round trip, gamut threshold, 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.
|
||||
|
||||
@@ -818,20 +1010,60 @@ There are no server integration tests; the API is exercised through the UI.
|
||||
|
||||
## Limitations
|
||||
|
||||
- **Not a cloud service.** No hosted deployment, no tethered capture, no sync client
|
||||
beyond one browser tab's whole-record push. The last writer wins per photo; it is
|
||||
- **Not a cloud service.** No hosted deployment and no camera driver: tethering is a
|
||||
server drop folder, not a PTP/USB connection. No sync client beyond one browser tab's
|
||||
whole-record push. The last writer wins per photo; it is
|
||||
designed for a handful of people, not concurrent batch workflows.
|
||||
- **Per-account catalogs.** Workspaces are private to their owner; there is no shared
|
||||
library between two members. Collaboration happens through client proofing links and
|
||||
the admin overview.
|
||||
- **Proxy-bounded raw.** Raw editing works on the demosaiced JPEG proxy (6000 px
|
||||
default), not the sensor mosaic; export size is bounded by the proxy.
|
||||
- **Approximate tools.** Temperature/tint are relative to the as-shot white balance.
|
||||
Auto masks are an on-device saliency/colour estimate, not a segmentation model. Soft
|
||||
proofing approximates paper white, black point and print gamut but does not apply a
|
||||
printer ICC profile; use the browser print dialog for final ICC handling. The
|
||||
- **Proxy-bounded raw.** Raw editing works on the demosaiced proxy (6000 px default),
|
||||
not the sensor mosaic; export size is bounded by the proxy. Raw imports keep two
|
||||
files: the JPEG proxy every browser can decode, and a 16-bit PNG sidecar of the same
|
||||
pixels. The editor grades the sidecar as a half-float source texture when it is
|
||||
present, which is what keeps a heavy shadow lift or a 3200 K white balance from
|
||||
posterising an 8-bit source; the JPEG and everything derived from it (thumbnails,
|
||||
denoise renders, proofs) stay 8-bit. A per-photo DCP profile is applied wherever
|
||||
the sidecar is: 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
|
||||
calibrated sensor model.
|
||||
calibrated sensor model, and sharpening is multi-scale unsharp masking rather than
|
||||
deconvolution.
|
||||
- **Merge scope.** HDR, panorama and focus stacking are translation-aligned and aimed at
|
||||
bracketed, stacked or horizontal sequences, not handheld multi-row composites. They
|
||||
compose at a reduced working edge (2600 px).
|
||||
@@ -869,17 +1101,13 @@ including Lensfun's CC BY-SA 3.0 database, which the MIT licence does not relice
|
||||
|
||||
| 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/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 |
|
||||
| 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 |
|
||||
| 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 |
|
||||
| `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 |
|
||||
| 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 |
|
||||
| `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 | |
|
||||
| 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 | |
|
||||
@@ -901,18 +1129,15 @@ Creative Commons content licence, and it grants neither patent nor trademark rig
|
||||
|
||||
### Redistribution checklist
|
||||
|
||||
`public/lensfun/` currently ships the notices (`NOTICE.md`, `THIRD_PARTY_LICENSES.md`,
|
||||
`UPSTREAM.md`) and the wrapper's MIT `LICENSE`, but **not** the full LGPL-3.0 or
|
||||
CC BY-SA 3.0 texts. Before distributing Luminary or its container image:
|
||||
`public/lens-db/` currently ships the converted data and `NOTICE.md`, but **not** the
|
||||
full CC BY-SA 3.0 text. Before distributing Luminary or its container image:
|
||||
|
||||
1. Add the upstream licence texts beside the assets: Lensfun `COPYING` and
|
||||
`COPYING.LESSER` (the LGPL incorporates GPL-3.0 by reference), and
|
||||
`data/COPYING.CC_BY-SA_3.0` for the database.
|
||||
2. Keep the notices, the pinned commit and the attribution block above in the distributed
|
||||
copy, served from `public/lensfun/` as they are today.
|
||||
3. Provide corresponding source for the LGPL components: Lensfun and LibRaw at the
|
||||
versions actually built, plus tinyxml2 and utf8proc. Leave
|
||||
`dist/lensfun/lensfun-core.wasm` and its JS loader replaceable.
|
||||
1. Add the upstream licence text beside the data: Lensfun
|
||||
`data/COPYING.CC_BY-SA_3.0`.
|
||||
2. Keep the notice, the pinned commit and the attribution block above in the distributed
|
||||
copy, served from `public/lens-db/` as it is today.
|
||||
3. Provide corresponding source for the LGPL components still shipped: LibRaw at the
|
||||
version actually built.
|
||||
4. When publishing a container image, include the same files and the libvips, Node.js and
|
||||
Debian notices.
|
||||
5. Do not relicense third-party assets under Luminary's own terms, and do not add
|
||||
|
||||
+8
-12
@@ -3,35 +3,31 @@
|
||||
**Luminary** — notices resolved 23 November 2026.
|
||||
|
||||
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`
|
||||
and `public/lensfun/THIRD_PARTY_LICENSES.md` remain the notices served with the
|
||||
Lensfun assets; this file does not replace them.
|
||||
links, or ships in its build output and container image. `public/lens-db/NOTICE.md`
|
||||
remains the notice served with the Lensfun-derived calibration data; this file does not
|
||||
replace it.
|
||||
|
||||
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
|
||||
does not replace their terms.
|
||||
Versions are those resolved in `package-lock.json`; the Lensfun pin is
|
||||
`655a9c4e3e53c25bc04843c853e7e7a0121359e7` (see `public/lensfun/UPSTREAM.md`).
|
||||
Versions are those resolved in `package-lock.json`; the lens database pin is
|
||||
`655a9c4e3e53c25bc04843c853e7e7a0121359e7` (see `public/lens-db/NOTICE.md`).
|
||||
|
||||
## Runtime components
|
||||
|
||||
| Component | Version / pin | Licence | Notice |
|
||||
| --- | --- | --- | --- |
|
||||
| Lensfun library | `655a9c4` | LGPL-3.0-or-later | © Lensfun contributors — https://github.com/lensfun/lensfun |
|
||||
| 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 |
|
||||
| Lensfun camera/lens database (data only) | `655a9c4` | CC BY-SA 3.0 Unported | © Lensfun contributors — https://creativecommons.org/licenses/by-sa/3.0/ |
|
||||
| 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 |
|
||||
| `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 |
|
||||
| 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 |
|
||||
| `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 |
|
||||
|
||||
The Lensfun database is a separate asset from the Lensfun library: CC BY-SA 3.0
|
||||
applies to the profile data, not to Luminary's application code. Attribution and
|
||||
The lens database is a separate asset from Luminary's code: CC BY-SA 3.0 applies to
|
||||
Lensfun's calibration data, not to the correction engine that reads it. Attribution and
|
||||
share-alike requirements are summarised in the README under
|
||||
[Third-party attribution and licences](README.md#third-party-attribution-and-licences).
|
||||
|
||||
|
||||
@@ -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`),
|
||||
`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,
|
||||
`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
|
||||
(`:1144`), grade pass samples it at `:1296`, finish pass at `:1553`.
|
||||
- **Export:** `src/lib/export.ts` builds a fresh `Renderer` from `getBitmap()` — a
|
||||
|
||||
Generated
+6
-12
@@ -7,11 +7,11 @@
|
||||
"": {
|
||||
"name": "luminary",
|
||||
"version": "1.0.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@neoanaloglabkk/lensfun-wasm": "^0.1.3",
|
||||
"exifr": "^7.1.3",
|
||||
"libraw-wasm": "^1.6.0",
|
||||
"nodemailer": "^7.0.13",
|
||||
"nodemailer": "^10.6.1",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"sharp": "^0.35.5"
|
||||
@@ -1306,12 +1306,6 @@
|
||||
"@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": {
|
||||
"version": "1.0.0-beta.27",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
|
||||
@@ -2330,12 +2324,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nodemailer": {
|
||||
"version": "7.0.13",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.13.tgz",
|
||||
"integrity": "sha512-PNDFSJdP+KFgdsG3ZzMXCgquO7I6McjY2vlqILjtJd0hy8wEvtugS9xKRF2NWlPNGxvLCXlTNIae4serI7dinw==",
|
||||
"version": "10.6.1",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.6.1.tgz",
|
||||
"integrity": "sha512-d7kfFfS/tR4Aca+SBvRaQ+MXKNv7d2JiRe5TxaRcFT/kYMh4GGPnW9aKksTIEvyEbA7d/7HYWE4YPDEHxzJj/g==",
|
||||
"license": "MIT-0",
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pathe": {
|
||||
|
||||
+3
-3
@@ -12,13 +12,13 @@
|
||||
"start": "node server/index.mjs",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
"test": "vitest run",
|
||||
"build:lens-db": "node scripts/build-lens-db.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@neoanaloglabkk/lensfun-wasm": "^0.1.3",
|
||||
"exifr": "^7.1.3",
|
||||
"libraw-wasm": "^1.6.0",
|
||||
"nodemailer": "^7.0.13",
|
||||
"nodemailer": "^10.6.1",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"sharp": "^0.35.5"
|
||||
|
||||
@@ -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
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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.
@@ -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(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/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`,
|
||||
);
|
||||
+21
-4
@@ -1,23 +1,40 @@
|
||||
import crypto from 'node:crypto';
|
||||
import { promisify } from 'node:util';
|
||||
import { SESSION_DAYS } from './config.mjs';
|
||||
import { sessions, users } from './db.mjs';
|
||||
|
||||
const KEYLEN = 64;
|
||||
const scrypt = promisify(crypto.scrypt);
|
||||
|
||||
export function hashPassword(password) {
|
||||
export async function hashPassword(password) {
|
||||
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')}`;
|
||||
}
|
||||
|
||||
export function verifyPassword(password, stored) {
|
||||
export async function verifyPassword(password, stored) {
|
||||
const [scheme, saltHex, hashHex] = String(stored).split('$');
|
||||
if (scheme !== 'scrypt' || !saltHex || !hashHex) return false;
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
const expiresAt = Date.now() + SESSION_DAYS * 24 * 60 * 60 * 1000;
|
||||
|
||||
+10
-2
@@ -11,6 +11,7 @@ import crypto from 'node:crypto';
|
||||
import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs';
|
||||
import { db, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs';
|
||||
import { removeAsset } from './storage.mjs';
|
||||
import { open, seal } from './secrets.mjs';
|
||||
|
||||
const VERSION = 'g1';
|
||||
|
||||
@@ -119,7 +120,14 @@ export function bridgePhotoId(sourcePhotoId) {
|
||||
}
|
||||
|
||||
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. */
|
||||
@@ -208,7 +216,7 @@ export async function importBridgeEvent({ serviceToken, sessionId, ownerId = ''
|
||||
bridgeInsert.run(
|
||||
eventId,
|
||||
sessionId,
|
||||
serviceToken,
|
||||
seal(serviceToken),
|
||||
GLENLOCH_URL,
|
||||
listing.event.id,
|
||||
returnUrl,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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. */
|
||||
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. */
|
||||
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. */
|
||||
export const RAW_PREVIEW_EDGE = Number(setting('RAW_EDGE', '6000'));
|
||||
|
||||
/**
|
||||
* Also store the 16-bit samples LibRaw decoded as a sidecar next to the JPEG
|
||||
* proxy. It costs roughly 25x the JPEG in disk and download, but it is the only
|
||||
* way the editor can grade from more than 256 levels per channel.
|
||||
*/
|
||||
export const RAW_16BIT = setting('16BIT', '1') !== '0';
|
||||
|
||||
export const SESSION_DAYS = 30;
|
||||
|
||||
/** How many raws decode at once. One core is left for the HTTP server. */
|
||||
|
||||
+613
@@ -89,6 +89,18 @@ db.exec(`
|
||||
|
||||
CREATE INDEX IF NOT EXISTS gallery_reviews_token ON gallery_reviews(token);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS gallery_settings (
|
||||
token TEXT PRIMARY KEY,
|
||||
password_hash TEXT NOT NULL DEFAULT '',
|
||||
password_salt TEXT NOT NULL DEFAULT '',
|
||||
expires_at INTEGER,
|
||||
watermark TEXT NOT NULL DEFAULT '',
|
||||
allow_downloads INTEGER NOT NULL DEFAULT 1,
|
||||
download_cap INTEGER NOT NULL DEFAULT 0,
|
||||
download_count INTEGER NOT NULL DEFAULT 0,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS invites (
|
||||
token TEXT PRIMARY KEY,
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
@@ -114,6 +126,76 @@ db.exec(`
|
||||
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 (
|
||||
user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||||
bytes_limit INTEGER NOT NULL DEFAULT (100 * 1024 * 1024 * 1024),
|
||||
@@ -122,6 +204,25 @@ db.exec(`
|
||||
prune_notified_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. */
|
||||
@@ -162,6 +263,24 @@ if (!eventColumns.includes('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'");
|
||||
}
|
||||
|
||||
const q = {
|
||||
upsertEvent: db.prepare(`
|
||||
INSERT INTO events (id, owner_id, sort_index, created_at, data) VALUES (?, ?, ?, ?, ?)
|
||||
@@ -255,6 +374,115 @@ const q = {
|
||||
photo: db.prepare('SELECT data FROM photos WHERE id = ?'),
|
||||
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 = ?'),
|
||||
insertUser: db.prepare(
|
||||
'INSERT INTO users (id, email, name, pass_hash, role, created_at) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
@@ -335,6 +563,28 @@ const q = {
|
||||
kvSet: db.prepare(
|
||||
'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) {
|
||||
@@ -361,6 +611,8 @@ export function saveEvent(record, sortIndex = 0, ownerId = '') {
|
||||
|
||||
export function removeEvent(id) {
|
||||
q.deleteEvent.run(id);
|
||||
// An album link must not outlive the event it points at.
|
||||
q.deleteImmichAlbum.run(id);
|
||||
}
|
||||
|
||||
export function shareTokenFor(id) {
|
||||
@@ -408,6 +660,71 @@ export function picksByOwner(ownerId) {
|
||||
}));
|
||||
}
|
||||
|
||||
const gallerySettingsStmt = db.prepare('SELECT * FROM gallery_settings WHERE token = ?');
|
||||
const upsertGallerySettings = db.prepare(`
|
||||
INSERT INTO gallery_settings
|
||||
(token, password_hash, password_salt, expires_at, watermark, allow_downloads, download_cap, download_count, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(token) DO UPDATE SET
|
||||
password_hash = excluded.password_hash,
|
||||
password_salt = excluded.password_salt,
|
||||
expires_at = excluded.expires_at,
|
||||
watermark = excluded.watermark,
|
||||
allow_downloads = excluded.allow_downloads,
|
||||
download_cap = excluded.download_cap,
|
||||
updated_at = excluded.updated_at
|
||||
`);
|
||||
const deleteGallerySettings = db.prepare('DELETE FROM gallery_settings WHERE token = ?');
|
||||
const bumpGalleryDownload = db.prepare(
|
||||
'UPDATE gallery_settings SET download_count = download_count + 1 WHERE token = ?',
|
||||
);
|
||||
const readGalleryDownloads = db.prepare(
|
||||
'SELECT download_count FROM gallery_settings WHERE token = ?',
|
||||
);
|
||||
|
||||
/** Access rules for a public proofing link; defaults when none were saved. */
|
||||
export function gallerySettingsFor(token) {
|
||||
const row = gallerySettingsStmt.get(token);
|
||||
return {
|
||||
passwordHash: row?.password_hash ?? '',
|
||||
passwordSalt: row?.password_salt ?? '',
|
||||
expiresAt: row?.expires_at ?? null,
|
||||
watermark: row?.watermark ?? '',
|
||||
allowDownloads: row ? Boolean(row.allow_downloads) : true,
|
||||
downloadCap: row?.download_cap ?? 0,
|
||||
downloadCount: row?.download_count ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The download counter is deliberately preserved across settings edits: an
|
||||
* owner tightening or loosening a cap must not hand out a fresh allowance.
|
||||
*/
|
||||
export function saveGallerySettings(token, settings) {
|
||||
upsertGallerySettings.run(
|
||||
token,
|
||||
settings.passwordHash ?? '',
|
||||
settings.passwordSalt ?? '',
|
||||
settings.expiresAt ?? null,
|
||||
settings.watermark ?? '',
|
||||
settings.allowDownloads === false ? 0 : 1,
|
||||
Math.max(0, Math.round(settings.downloadCap ?? 0)),
|
||||
0,
|
||||
Date.now(),
|
||||
);
|
||||
return gallerySettingsFor(token);
|
||||
}
|
||||
|
||||
export function clearGallerySettings(token) {
|
||||
deleteGallerySettings.run(token);
|
||||
}
|
||||
|
||||
/** Counts a gallery download and reports the new total, or 0 when uncapped. */
|
||||
export function noteGalleryDownload(token) {
|
||||
bumpGalleryDownload.run(token);
|
||||
return readGalleryDownloads.get(token)?.download_count ?? 0;
|
||||
}
|
||||
|
||||
export function galleryPick(token, photoId, clientId, clientName, picked) {
|
||||
if (!picked) {
|
||||
q.deletePick.run(token, photoId, clientId);
|
||||
@@ -479,6 +796,250 @@ export function getPhoto(id) {
|
||||
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) {
|
||||
return q.photoOwner.get(id)?.owner_id ?? null;
|
||||
}
|
||||
@@ -501,6 +1062,9 @@ export function removePhoto(id) {
|
||||
q.deletePicksForPhoto.run(id);
|
||||
q.deleteCommentsForPhoto.run(id);
|
||||
q.deleteReviewsForPhoto.run(id);
|
||||
q.deleteImmichAssetsForPhoto.run(id);
|
||||
q.deleteImmichPushesForPhoto.run(id);
|
||||
q.deleteImmichMeta.run(id);
|
||||
}
|
||||
|
||||
export function countPhotos() {
|
||||
@@ -590,3 +1154,52 @@ export const kv = {
|
||||
},
|
||||
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
@@ -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) {
|
||||
const sharp = await loadSharp();
|
||||
if (!sharp) {
|
||||
|
||||
@@ -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
File diff suppressed because it is too large
Load Diff
+1119
-80
File diff suppressed because it is too large
Load Diff
@@ -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,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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
@@ -1,5 +1,6 @@
|
||||
import nodemailer from 'nodemailer';
|
||||
import { kv } from './db.mjs';
|
||||
import { open, seal } from './secrets.mjs';
|
||||
import {
|
||||
SMTP_APP_PASSWORD,
|
||||
SMTP_FROM,
|
||||
@@ -13,7 +14,16 @@ const SETTINGS_KEY = 'mailSettings';
|
||||
|
||||
function savedSettings() {
|
||||
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. */
|
||||
@@ -70,7 +80,7 @@ function validateSettings(input) {
|
||||
|
||||
export function saveMailSettings(input) {
|
||||
const next = validateSettings(input ?? {});
|
||||
kv.set(SETTINGS_KEY, next);
|
||||
kv.set(SETTINGS_KEY, { ...next, appPassword: seal(next.appPassword) });
|
||||
return mailStatus();
|
||||
}
|
||||
|
||||
|
||||
+93
-19
@@ -1,5 +1,6 @@
|
||||
import { RAW_PREVIEW_EDGE } from './config.mjs';
|
||||
import { encodeRgb, jpegInfo, loadSharp, toJpegProxy } from './imaging.mjs';
|
||||
import { RAW_16BIT, RAW_PREVIEW_EDGE } from './config.mjs';
|
||||
import { cameraToProxy, readRgbCam } from './color.mjs';
|
||||
import { encodePng16, encodeRgb, jpegInfo, loadSharp, resizeRgb16, toJpegProxy } from './imaging.mjs';
|
||||
import { loadLibRaw, rawPool } from './libraw-pool.mjs';
|
||||
|
||||
/** Every raw container the pipeline will attempt, grouped by vendor family. */
|
||||
@@ -57,12 +58,25 @@ export async function rawEngine() {
|
||||
}
|
||||
|
||||
const DECODE_SETTINGS = {
|
||||
outputBps: 8,
|
||||
// Decode at 16 bits and let LibRaw blend reconstructed highlights instead of
|
||||
// clipping them; the 8-bit proxy is downsampled after the rolloff, so a
|
||||
// recovered sky keeps gradation instead of a flat white patch.
|
||||
outputBps: 16,
|
||||
useCameraWb: true,
|
||||
outputColor: 1, // sRGB
|
||||
// Camera-native, not sRGB: the camera-to-output matrix is applied here in JS
|
||||
// (see color.mjs) and again by the editor on the 16-bit sidecar. That makes
|
||||
// the conversion one swappable matrix instead of a fixed choice inside
|
||||
// LibRaw, which is what a camera profile needs.
|
||||
outputColor: 0,
|
||||
userQual: 3,
|
||||
highlight: 0,
|
||||
noAutoBright: false,
|
||||
highlight: 2,
|
||||
// One white point for the frame, chosen after the matrix. LibRaw's per-path
|
||||
// auto-bright measures each output colourspace separately, so the JPEG and
|
||||
// the camera-native sidecar would disagree by up to half a stop.
|
||||
noAutoBright: true,
|
||||
// Always use the camera's own colour matrix. The default only does so when
|
||||
// white balance is applied, which leaves some bodies on the generic matrix.
|
||||
useCameraMatrix: 3,
|
||||
// Use the orientation stored in the raw container: phone and DSLR files often
|
||||
// record the shot rotated (EXIF 6/8), and demosaicing without it produces a
|
||||
// sideways proxy that no later step can fix without losing the original axes.
|
||||
@@ -70,7 +84,13 @@ const DECODE_SETTINGS = {
|
||||
useFujiRotate: -1,
|
||||
};
|
||||
|
||||
/** Turns one LibRaw `imageData()` result into an interleaved RGB buffer. */
|
||||
/**
|
||||
* Turns one LibRaw `imageData()` result into an interleaved RGB buffer.
|
||||
*
|
||||
* The 8-bit copy is what the JPEG proxy is encoded from. The 16-bit copy keeps
|
||||
* every sample LibRaw produced so the editor can upload a half-float source
|
||||
* texture; without it, a heavy shadow lift is applied to 256 levels per channel.
|
||||
*/
|
||||
function toRgb(img) {
|
||||
if (!img || !img.width || !img.height || !img.data) throw new Error('LibRaw returned no pixels');
|
||||
const width = Number(img.width);
|
||||
@@ -79,19 +99,36 @@ function toRgb(img) {
|
||||
const bits = Number(img.bits ?? 8);
|
||||
const src = img.data;
|
||||
const pixelCount = width * height;
|
||||
const needed = pixelCount * colors * (bits > 8 ? 2 : 1);
|
||||
if (src.length < needed) {
|
||||
throw new Error(`LibRaw buffer too small (${src.length} bytes for ${width}×${height}×${colors})`);
|
||||
const needed = pixelCount * colors;
|
||||
// libraw-wasm hands back samples, not bytes: with outputBps 16 the buffer is a
|
||||
// Uint16Array already. Older builds returned the raw 16-bit bytes, so accept
|
||||
// both shapes instead of assuming one and rejecting every 16-bit decode.
|
||||
const wide =
|
||||
bits > 8 && !(src instanceof Uint16Array)
|
||||
? new Uint16Array(src.buffer, src.byteOffset, Math.floor(src.byteLength / 2))
|
||||
: src;
|
||||
if (wide.length < needed) {
|
||||
throw new Error(
|
||||
`LibRaw buffer too small (${wide.length} samples for ${width}×${height}×${colors})`,
|
||||
);
|
||||
}
|
||||
|
||||
const rgb = Buffer.alloc(pixelCount * 3);
|
||||
let rgb16 = null;
|
||||
if (bits > 8) {
|
||||
const view = new Uint16Array(src.buffer, src.byteOffset, Math.floor(src.byteLength / 2));
|
||||
const view = wide instanceof Uint16Array ? wide : src;
|
||||
rgb16 = new Uint16Array(pixelCount * 3);
|
||||
for (let i = 0; i < pixelCount; i++) {
|
||||
const s = i * colors;
|
||||
rgb[i * 3] = view[s] >> 8;
|
||||
rgb[i * 3 + 1] = view[s + 1] >> 8;
|
||||
rgb[i * 3 + 2] = view[s + 2] >> 8;
|
||||
const r = view[s];
|
||||
const g = view[s + 1];
|
||||
const b = view[s + 2];
|
||||
rgb[i * 3] = r >> 8;
|
||||
rgb[i * 3 + 1] = g >> 8;
|
||||
rgb[i * 3 + 2] = b >> 8;
|
||||
rgb16[i * 3] = r;
|
||||
rgb16[i * 3 + 1] = g;
|
||||
rgb16[i * 3 + 2] = b;
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < pixelCount; i++) {
|
||||
@@ -101,20 +138,29 @@ function toRgb(img) {
|
||||
rgb[i * 3 + 2] = src[s + 2];
|
||||
}
|
||||
}
|
||||
return { rgb, width, height };
|
||||
return { rgb, rgb16, width, height };
|
||||
}
|
||||
|
||||
/**
|
||||
* Full demosaic through a pooled LibRaw worker. `open()` only unpacks the file;
|
||||
* the pixels come from `imageData()`, which rejects when the camera is unsupported.
|
||||
*
|
||||
* `cameraNative` asks for the frame before LibRaw's output matrix, plus the
|
||||
* matrix metadata. A body LibRaw has no matrix for falls back to the plain sRGB
|
||||
* decode, which is the same result the pipeline produced before.
|
||||
*/
|
||||
async function demosaic(buffer) {
|
||||
async function demosaic(buffer, cameraNative = true) {
|
||||
if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed');
|
||||
return rawPool.use(async (lib) => {
|
||||
// LibRaw transfers the buffer to its worker, which detaches it here. Hand it
|
||||
// a copy so the caller's bytes survive for the embedded-preview fallback.
|
||||
await lib.open(Buffer.from(buffer), DECODE_SETTINGS);
|
||||
return toRgb(await lib.imageData());
|
||||
await lib.open(
|
||||
Buffer.from(buffer),
|
||||
cameraNative ? DECODE_SETTINGS : { ...DECODE_SETTINGS, outputColor: 1, noAutoBright: false },
|
||||
);
|
||||
const image = toRgb(await lib.imageData());
|
||||
const rgbCam = cameraNative ? readRgbCam(await lib.metadata(true)) : null;
|
||||
return { ...image, rgbCam };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -163,10 +209,38 @@ export async function decodeRaw(buffer) {
|
||||
let librawError = null;
|
||||
if (looksLikeRaw(buffer)) {
|
||||
try {
|
||||
const { rgb, width, height } = await demosaic(buffer);
|
||||
let frame = await demosaic(buffer, true);
|
||||
// No usable matrix (an odd body or older engine): decode the familiar sRGB
|
||||
// way instead of shipping camera samples nobody can convert.
|
||||
if (!frame.rgbCam || !frame.rgb16) frame = await demosaic(buffer, false);
|
||||
const { width, height, rgbCam } = frame;
|
||||
// Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and
|
||||
// `rgb16` the camera-native sidecar, sharing one white point.
|
||||
if (rgbCam && frame.rgb16) cameraToProxy(frame.rgb16, frame.rgb, rgbCam);
|
||||
const { rgb } = frame;
|
||||
const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE);
|
||||
// The sidecar must match the JPEG pixel for pixel: the editor swaps the
|
||||
// two textures at the same uv, so a size disagreement would misalign the
|
||||
// whole grade. It is optional -- encoding failures leave the JPEG path.
|
||||
let preview16 = null;
|
||||
if (frame.rgb16 && RAW_16BIT) {
|
||||
try {
|
||||
const scaled = resizeRgb16(frame.rgb16, width, height, encoded.width, encoded.height);
|
||||
preview16 = {
|
||||
// The matrix travels with the samples so the editor knows how to
|
||||
// turn camera RGB into sRGB without a second metadata fetch.
|
||||
data: encodePng16(scaled, encoded.width, encoded.height, rgbCam),
|
||||
width: encoded.width,
|
||||
height: encoded.height,
|
||||
rgbCam,
|
||||
};
|
||||
} catch {
|
||||
preview16 = null;
|
||||
}
|
||||
}
|
||||
return {
|
||||
jpeg: encoded.data,
|
||||
preview16,
|
||||
width: encoded.width,
|
||||
height: encoded.height,
|
||||
engine: 'libraw',
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
@@ -83,6 +83,11 @@ export async function writeOriginal(id, ext, data) {
|
||||
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) {
|
||||
const safe = lookupId(id);
|
||||
if (!safe) return null;
|
||||
@@ -112,6 +117,54 @@ export function findPreview(id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The 16-bit sidecar for a raw proxy: the samples LibRaw decoded, before the
|
||||
* JPEG quantised them. Its name keeps a second extension so `findPreview` keeps
|
||||
* returning the JPEG for browsers and for photos imported before this existed.
|
||||
*/
|
||||
export async function writePreview16(id, data) {
|
||||
ensureDirs();
|
||||
const target = path.join(storageRoot(), 'previews', `${safeId(id)}.p16.png`);
|
||||
await fsp.writeFile(target, data);
|
||||
return target;
|
||||
}
|
||||
|
||||
export function findPreview16(id) {
|
||||
const safe = lookupId(id);
|
||||
if (!safe) return null;
|
||||
const p = path.join(dirs().previews, `${safe}.p16.png`);
|
||||
return fs.existsSync(p) ? p : null;
|
||||
}
|
||||
|
||||
export async function removePreview16(id) {
|
||||
const found = findPreview16(id);
|
||||
if (found) await fsp.rm(found, { force: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Camera-native grid thumbnail: the sidecar's samples at the JPEG thumbnail's
|
||||
* size, so the grid can honour a per-photo camera profile without downloading
|
||||
* the full sidecar. Lives beside the sidecar and is regenerated on demand.
|
||||
*/
|
||||
export async function writeThumb16(id, data) {
|
||||
ensureDirs();
|
||||
const target = path.join(storageRoot(), 'previews', `${safeId(id)}.t16.png`);
|
||||
await fsp.writeFile(target, data);
|
||||
return target;
|
||||
}
|
||||
|
||||
export function findThumb16(id) {
|
||||
const safe = lookupId(id);
|
||||
if (!safe) return null;
|
||||
const p = path.join(dirs().previews, `${safe}.t16.png`);
|
||||
return fs.existsSync(p) ? p : null;
|
||||
}
|
||||
|
||||
export async function removeThumb16(id) {
|
||||
const found = findThumb16(id);
|
||||
if (found) await fsp.rm(found, { force: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Denoised proxies, keyed by the hash of the parameters that produced them, so
|
||||
* switching Amount back to a previous value reuses the file instead of spending
|
||||
@@ -204,6 +257,8 @@ export async function removeAsset(id) {
|
||||
const files = [
|
||||
findOriginal(id),
|
||||
findPreview(id),
|
||||
findPreview16(id),
|
||||
findThumb16(id),
|
||||
findThumb(id),
|
||||
findProof(id),
|
||||
findProofThumb(id),
|
||||
|
||||
+699
-19
@@ -9,11 +9,18 @@ import ExportModal from './components/ExportModal';
|
||||
import CompareView from './components/CompareView';
|
||||
import FilterBar from './components/FilterBar';
|
||||
import ImportModal from './components/ImportModal';
|
||||
import ImmichPanel from './components/ImmichPanel';
|
||||
import LibraryGrid from './components/LibraryGrid';
|
||||
import MergeModal from './components/MergeModal';
|
||||
import PasteSettingsModal from './components/PasteSettingsModal';
|
||||
import PrintModal from './components/PrintModal';
|
||||
import ShareModal from './components/ShareModal';
|
||||
import RawReprocessModal, {
|
||||
type RawReprocessFailure,
|
||||
type RawReprocessJob,
|
||||
} from './components/RawReprocessModal';
|
||||
import CullAssistModal from './components/CullAssistModal';
|
||||
import TetherPanel from './components/TetherPanel';
|
||||
import Shortcuts from './components/Shortcuts';
|
||||
import Stars, { ColorSwatches, FlagButtons } from './components/Stars';
|
||||
import TopBar from './components/TopBar';
|
||||
@@ -22,18 +29,24 @@ import {
|
||||
currentUser,
|
||||
deleteEventRemote,
|
||||
deletePhotoRemote,
|
||||
createImmichEventAlbum,
|
||||
getHealth,
|
||||
getImmichStatus,
|
||||
getQuota,
|
||||
immichEventQueue,
|
||||
login as apiLogin,
|
||||
logout as apiLogout,
|
||||
pullAll,
|
||||
pullProofs,
|
||||
pushEvent,
|
||||
publishImmichOriginal,
|
||||
pushImmichPhoto,
|
||||
pushPhoto,
|
||||
register as apiRegister,
|
||||
reprocessRawPhoto,
|
||||
uploadOriginal,
|
||||
} from './lib/api';
|
||||
import type { Health, ProofSummary, QuotaState, SessionUser } from './lib/api';
|
||||
import type { Health, ImmichStatus, ProofSummary, QuotaState, SessionUser } from './lib/api';
|
||||
import {
|
||||
deleteEventRecord,
|
||||
deletePhotoRecord,
|
||||
@@ -52,8 +65,9 @@ import { COLOR_LABELS, defaultEdits, isEdited, normalizePhoto } from './lib/edit
|
||||
import { applyEditSections, type EditSectionId } from './lib/editSections';
|
||||
import type { MergeResult } from './lib/merge';
|
||||
import { evictBitmap } from './lib/images';
|
||||
import { uid } from './lib/import';
|
||||
import { importFiles, uid } from './lib/import';
|
||||
import { PRESETS } from './lib/presets';
|
||||
import { downloadXmp, readXmpFile, xmpToEdits } from './lib/xmp';
|
||||
import type {
|
||||
Edits,
|
||||
EventRecord,
|
||||
@@ -136,6 +150,41 @@ export default function App() {
|
||||
const [cloudUser, setCloudUser] = useState<SessionUser | null>(null);
|
||||
const [cloudOpen, setCloudOpen] = 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 [cloudError, setCloudError] = 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 [exportRecipes, setExportRecipes] = useState<ExportRecipe[]>([]);
|
||||
const [mergeOpen, setMergeOpen] = useState(false);
|
||||
const [rawJob, setRawJob] = useState<RawReprocessJob | null>(null);
|
||||
const [cullOpen, setCullOpen] = useState(false);
|
||||
const [tetherEventId, setTetherEventId] = useState<string | null>(null);
|
||||
const rawBusyRef = useRef(false);
|
||||
const rawCancelRef = useRef(false);
|
||||
const rawBusy = Boolean(rawJob?.running);
|
||||
const [printOpen, setPrintOpen] = useState(false);
|
||||
|
||||
const saveTimers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
|
||||
@@ -322,6 +377,151 @@ export default function App() {
|
||||
[queueSave],
|
||||
);
|
||||
|
||||
/**
|
||||
* Re-decode selected RAW files on the server, then refresh the cached proxy so
|
||||
* the grid and Develop pick up the new pixels without a reload. Existing edits
|
||||
* are kept; only width, height and the decode engine change on the record.
|
||||
*/
|
||||
const reprocessRawPhotos = useCallback(
|
||||
async (ids: string[], options: { eventName?: string } = {}) => {
|
||||
if (rawBusyRef.current) {
|
||||
setToast('A RAW reprocess is already running');
|
||||
return;
|
||||
}
|
||||
const targets = photosRef.current.filter(
|
||||
(photo) => ids.includes(photo.id) && photo.raw && !photo.deletedAt,
|
||||
);
|
||||
if (!targets.length) {
|
||||
setToast('Select RAW photos to reprocess');
|
||||
return;
|
||||
}
|
||||
if (!userRef.current) {
|
||||
setToast('Sign in to the server to reprocess RAW files');
|
||||
return;
|
||||
}
|
||||
rawBusyRef.current = true;
|
||||
rawCancelRef.current = false;
|
||||
const failures: RawReprocessFailure[] = [];
|
||||
let attempts = 0;
|
||||
setRawJob({
|
||||
running: true,
|
||||
done: 0,
|
||||
total: targets.length,
|
||||
current: targets[0].name,
|
||||
eventName: options.eventName,
|
||||
failures: [],
|
||||
});
|
||||
try {
|
||||
for (let index = 0; index < targets.length; index += 1) {
|
||||
if (rawCancelRef.current) break;
|
||||
const photo = targets[index];
|
||||
setRawJob((prev) =>
|
||||
prev ? { ...prev, done: index, current: photo.name, failures: failures.slice() } : prev,
|
||||
);
|
||||
try {
|
||||
const result = await reprocessRawPhoto(photo.id);
|
||||
const res = await fetch(
|
||||
`/api/photos/${encodeURIComponent(photo.id)}/preview?v=${Date.now()}`,
|
||||
{ credentials: 'same-origin' },
|
||||
);
|
||||
if (!res.ok) throw new Error('The new preview could not be read');
|
||||
const blob = await res.blob();
|
||||
// Replace the cached proxy, then drop the decoded bitmap so the next
|
||||
// render fetches the new pixels instead of the old ones.
|
||||
await putAsset(photo.id, blob);
|
||||
evictBitmap(photo.id);
|
||||
const version = result.previewVersion ?? Date.now();
|
||||
updatePhoto(photo.id, {
|
||||
width: result.width || photo.width,
|
||||
height: result.height || photo.height,
|
||||
decode: result.engine ?? photo.decode,
|
||||
previewVersion: version,
|
||||
// The stored files keep their names; the query is only a cache buster.
|
||||
previewUrl:
|
||||
result.previewUrl ??
|
||||
`/api/photos/${encodeURIComponent(photo.id)}/preview?v=${version}`,
|
||||
thumbUrl:
|
||||
result.thumbUrl ??
|
||||
`/api/photos/${encodeURIComponent(photo.id)}/thumb?v=${version}`,
|
||||
});
|
||||
attempts += 1;
|
||||
} catch (err) {
|
||||
failures.push({
|
||||
name: photo.name,
|
||||
error: err instanceof Error ? err.message : 'could not be reprocessed',
|
||||
});
|
||||
}
|
||||
setRawJob((prev) =>
|
||||
prev
|
||||
? { ...prev, done: index + 1, failures: failures.slice() }
|
||||
: prev,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
rawBusyRef.current = false;
|
||||
setRawJob((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
running: false,
|
||||
done: attempts,
|
||||
failures: failures.slice(),
|
||||
cancelled: rawCancelRef.current,
|
||||
}
|
||||
: prev,
|
||||
);
|
||||
}
|
||||
const succeeded = attempts - failures.length;
|
||||
const parts = [
|
||||
`Reprocessed ${succeeded} of ${targets.length} RAW${targets.length === 1 ? '' : 's'}`,
|
||||
];
|
||||
if (failures.length) parts.push(`${failures.length} failed`);
|
||||
if (rawCancelRef.current) parts.push('cancelled');
|
||||
setToast(parts.join(' · '));
|
||||
},
|
||||
[updatePhoto],
|
||||
);
|
||||
|
||||
/** Reprocess every RAW file in one event, with a confirmation that names it. */
|
||||
const reprocessEventRaws = useCallback(
|
||||
(id: string) => {
|
||||
const event = eventsRef.current.find((item) => item.id === id);
|
||||
if (!event) return;
|
||||
const raws = photosRef.current.filter(
|
||||
(photo) => photo.eventId === id && photo.raw && !photo.deletedAt,
|
||||
);
|
||||
if (!raws.length) {
|
||||
setToast('This event has no RAW photos');
|
||||
return;
|
||||
}
|
||||
if (!userRef.current) {
|
||||
setToast('Sign in to the server to reprocess RAW files');
|
||||
return;
|
||||
}
|
||||
if (rawBusyRef.current) {
|
||||
setToast('A RAW reprocess is already running');
|
||||
return;
|
||||
}
|
||||
const ok = window.confirm(
|
||||
`Re-decode ${raws.length} RAW file${raws.length === 1 ? '' : 's'} in “${event.name}”? ` +
|
||||
'Existing edits and crops are kept.',
|
||||
);
|
||||
if (!ok) return;
|
||||
void reprocessRawPhotos(raws.map((photo) => photo.id), { eventName: event.name });
|
||||
},
|
||||
[reprocessRawPhotos],
|
||||
);
|
||||
|
||||
/** Auto-sync in Develop: merge the same patch into every selected photo. */
|
||||
const updatePhotoEdits = useCallback(
|
||||
(ids: string[], patch: Partial<Edits>, historyLabel?: string) => {
|
||||
for (const id of ids) {
|
||||
updatePhoto(id, (p) => ({ edits: { ...p.edits, ...patch } }), historyLabel);
|
||||
}
|
||||
},
|
||||
[updatePhoto],
|
||||
);
|
||||
|
||||
const bulkUpdate = useCallback(
|
||||
(ids: string[], patch: Partial<PhotoRecord>) => {
|
||||
if (!ids.length) return;
|
||||
@@ -337,6 +537,16 @@ export default function App() {
|
||||
[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 trashCount = photos.length - livePhotos.length;
|
||||
const proofCounts = useMemo(() => {
|
||||
@@ -475,19 +685,56 @@ export default function App() {
|
||||
[activeId],
|
||||
);
|
||||
|
||||
const createEvent = useCallback(async (name: string) => {
|
||||
const event: EventRecord = {
|
||||
id: uid(),
|
||||
name: name.trim() || `Event ${new Date().toLocaleDateString()}`,
|
||||
createdAt: Date.now(),
|
||||
date: Date.now(),
|
||||
order: eventsRef.current.length,
|
||||
workspace: userRef.current?.id,
|
||||
};
|
||||
await putEvent(event);
|
||||
if (userRef.current) pushEvent(event).catch(() => undefined);
|
||||
setEvents((prev) => [...prev, event].sort(byOrder));
|
||||
return event;
|
||||
const createEvent = useCallback(
|
||||
async (name: string, options: { immichGallery?: boolean } = {}) => {
|
||||
const event: EventRecord = {
|
||||
id: uid(),
|
||||
name: name.trim() || `Event ${new Date().toLocaleDateString()}`,
|
||||
createdAt: Date.now(),
|
||||
date: Date.now(),
|
||||
order: eventsRef.current.length,
|
||||
workspace: userRef.current?.id,
|
||||
};
|
||||
await putEvent(event);
|
||||
// The gallery endpoint looks the event up server-side, so let this land first.
|
||||
if (userRef.current) await pushEvent(event).catch(() => undefined);
|
||||
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) => {
|
||||
@@ -780,7 +1027,9 @@ export default function App() {
|
||||
|
||||
const savePreset = useCallback(
|
||||
(name: string, edits: Edits) => {
|
||||
const { crop: _crop, ...withoutCrop } = edits;
|
||||
// Crop and the camera profile are properties of this photo, not a look:
|
||||
// copying either onto another body would be wrong.
|
||||
const { crop: _crop, cameraProfile: _cameraProfile, ...withoutCrop } = edits;
|
||||
const preset: Preset = {
|
||||
id: uid(),
|
||||
name,
|
||||
@@ -799,6 +1048,19 @@ export default function App() {
|
||||
[customPresets],
|
||||
);
|
||||
|
||||
const deletePreset = useCallback(
|
||||
(id: string) => {
|
||||
const next = customPresets.filter((preset) => preset.id !== id);
|
||||
setCustomPresets(next);
|
||||
setKV('customPresets', next).catch((err) => console.error(err));
|
||||
if (userRef.current) {
|
||||
import('./lib/api').then(({ pushPresets }) => pushPresets(next).catch(() => undefined));
|
||||
}
|
||||
setToast('Preset deleted');
|
||||
},
|
||||
[customPresets],
|
||||
);
|
||||
|
||||
/* ------------------------------------------------------------- reordering */
|
||||
|
||||
const reorderPhotos = useCallback(
|
||||
@@ -1236,6 +1498,203 @@ export default function App() {
|
||||
}
|
||||
}, [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(
|
||||
async (email: string, password: string) => {
|
||||
setCloudBusy(true);
|
||||
@@ -1603,7 +2062,94 @@ export default function App() {
|
||||
? 'Unsorted'
|
||||
: events.find((e) => e.id === eventId)?.name ?? 'All photos';
|
||||
|
||||
const tetherImport = useCallback(
|
||||
async (files: File[]) => {
|
||||
if (!tetherEventId) return 0;
|
||||
const result = await importFiles(
|
||||
files,
|
||||
tetherEventId,
|
||||
[],
|
||||
undefined,
|
||||
cloudUser ? { uploadOriginal, push: pushPhoto } : null,
|
||||
);
|
||||
if (result.photos.length) {
|
||||
const tagged = result.photos.map((photo) =>
|
||||
cloudUser ? { ...photo, workspace: cloudUser.id } : photo,
|
||||
);
|
||||
setPhotos((prev) => [...tagged, ...prev]);
|
||||
}
|
||||
return result.photos.length;
|
||||
},
|
||||
[cloudUser, tetherEventId],
|
||||
);
|
||||
|
||||
const importSidecar = useCallback(async () => {
|
||||
if (selected.length !== 1) {
|
||||
setToast('Select exactly one photo to import a sidecar into');
|
||||
return;
|
||||
}
|
||||
const target = photos.find((photo) => photo.id === selected[0]);
|
||||
if (!target) return;
|
||||
try {
|
||||
const xml = await readXmpFile();
|
||||
if (!xml) return;
|
||||
const result = xmpToEdits(xml, target.edits);
|
||||
updatePhoto(target.id, { edits: result.edits }, 'Import XMP sidecar');
|
||||
setToast(
|
||||
result.source === 'luminary'
|
||||
? 'Imported Luminary settings from the sidecar'
|
||||
: `Imported ${result.applied.length} Lightroom setting${result.applied.length === 1 ? '' : 's'}`,
|
||||
);
|
||||
} catch (err) {
|
||||
setToast(err instanceof Error ? err.message : 'Could not import the sidecar');
|
||||
}
|
||||
}, [photos, selected, updatePhoto]);
|
||||
|
||||
const paletteActions = [
|
||||
{
|
||||
id: 'xmp-export',
|
||||
label: 'Export XMP sidecar for the selection',
|
||||
hint: 'Sidecar',
|
||||
run: () => {
|
||||
const chosen = photos.filter((photo) => selected.includes(photo.id));
|
||||
if (!chosen.length) {
|
||||
setToast('Select photos to export sidecars for');
|
||||
return;
|
||||
}
|
||||
for (const photo of chosen) downloadXmp(photo);
|
||||
setToast(`Exported ${chosen.length} sidecar${chosen.length === 1 ? '' : 's'}`);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'xmp-import',
|
||||
label: 'Import XMP sidecar into the selected photo',
|
||||
hint: 'Sidecar',
|
||||
run: () => void importSidecar(),
|
||||
},
|
||||
{
|
||||
id: 'tether',
|
||||
label: 'Tether this event from a watch folder',
|
||||
hint: 'Capture',
|
||||
run: () => {
|
||||
if (eventId === 'all' || eventId === 'unsorted') {
|
||||
setToast('Open an event to tether into it');
|
||||
return;
|
||||
}
|
||||
setTetherEventId(eventId);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'cull-assist',
|
||||
label: 'Cull assist for the selection',
|
||||
hint: 'Focus',
|
||||
run: () => {
|
||||
if (!selected.length) {
|
||||
setToast('Select photos to cull');
|
||||
return;
|
||||
}
|
||||
setCullOpen(true);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'import',
|
||||
label: 'Import photos',
|
||||
@@ -1638,6 +2184,29 @@ export default function App() {
|
||||
run: () => setFilters(EMPTY_FILTERS),
|
||||
},
|
||||
{ id: 'shortcuts', label: 'Show keyboard shortcuts', hint: '?', run: () => setHelpOpen(true) },
|
||||
...(cloudUser &&
|
||||
eventId !== 'all' &&
|
||||
eventId !== 'unsorted' &&
|
||||
photos.some((photo) => photo.eventId === eventId && photo.raw && !photo.deletedAt)
|
||||
? [
|
||||
{
|
||||
id: 'reprocess-event-raws',
|
||||
label: 'Reprocess all RAW photos in this event',
|
||||
hint: 'RAW',
|
||||
run: () => reprocessEventRaws(eventId),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(cloudUser && immichStatus?.enabled && eventId !== 'all' && eventId !== 'unsorted'
|
||||
? [
|
||||
{
|
||||
id: 'immich-publish',
|
||||
label: 'Publish this event to Immich',
|
||||
hint: 'Immich',
|
||||
run: () => void publishEventToImmich(eventId),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(cloudUser && eventId !== 'all' && eventId !== 'unsorted'
|
||||
? [{ id: 'share', label: 'Open client proofing', hint: 'Share', run: () => setShareEventId(eventId) }]
|
||||
: []),
|
||||
@@ -1754,9 +2323,14 @@ export default function App() {
|
||||
setTrashOpen(false);
|
||||
setEventId(id);
|
||||
}}
|
||||
onCreate={async (name) => {
|
||||
await createEvent(name);
|
||||
immichEnabled={Boolean(immichStatus?.enabled)}
|
||||
onCreate={async (name, immichGallery) => {
|
||||
await createEvent(name, { immichGallery });
|
||||
}}
|
||||
onSyncGallery={syncEventGallery}
|
||||
onPublishGallery={publishEventToImmich}
|
||||
canReprocessRaw={Boolean(cloudUser)}
|
||||
onReprocessEvent={reprocessEventRaws}
|
||||
onRename={renameEvent}
|
||||
onDelete={removeEvent}
|
||||
onReorderEvents={reorderEvents}
|
||||
@@ -1855,6 +2429,21 @@ export default function App() {
|
||||
onBulkRate={(rating) => bulkUpdate(selected, { rating })}
|
||||
onBulkFlag={(flag) => bulkUpdate(selected, { flag })}
|
||||
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))}
|
||||
onExport={openExport}
|
||||
onCompare={() => setCompareOpen(true)}
|
||||
@@ -1892,15 +2481,24 @@ export default function App() {
|
||||
onSelect={setActiveId}
|
||||
onExit={() => setView('grid')}
|
||||
onUpdate={updatePhoto}
|
||||
onUpdateEdits={updatePhotoEdits}
|
||||
clipboard={clipboard}
|
||||
onCopy={copySettings}
|
||||
onPaste={() => openPaste([activePhoto.id])}
|
||||
onCopyOf={copySettingsOf}
|
||||
onPaste={(ids) => openPaste(ids?.length ? ids : [activePhoto.id])}
|
||||
onResetSelection={resetEdits}
|
||||
localClipboard={localClipboard}
|
||||
onLocalClipboard={setLocalClipboard}
|
||||
onExport={openExport}
|
||||
onPrint={() => setPrintOpen(true)}
|
||||
canPushImmich={canSendToImmich(activePhoto)}
|
||||
onPushImmich={() => void pushImmichQueue([activePhoto])}
|
||||
onOpenImmich={
|
||||
activePhoto.immich ? () => openImmichAsset(activePhoto) : undefined
|
||||
}
|
||||
presets={[...PRESETS, ...customPresets]}
|
||||
onSavePreset={savePreset}
|
||||
onDeletePreset={deletePreset}
|
||||
onDelete={() => trashPhotos([activePhoto.id])}
|
||||
onVirtualCopy={() => void createVirtualCopy(activePhoto.id, true)}
|
||||
metadataPresets={metadataPresets}
|
||||
@@ -1949,6 +2547,8 @@ export default function App() {
|
||||
setToast(`Imported ${imported.length} photo${imported.length === 1 ? '' : 's'}`);
|
||||
}}
|
||||
onCreateEvent={createEvent}
|
||||
immichEnabled={Boolean(immichStatus?.enabled)}
|
||||
onCreateImmichGallery={createImmichGalleryForEvent}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -2061,6 +2661,10 @@ export default function App() {
|
||||
setCloudOpen(false);
|
||||
setAdminOpen(true);
|
||||
}}
|
||||
onImmich={() => {
|
||||
setCloudOpen(false);
|
||||
setImmichOpen(true);
|
||||
}}
|
||||
onClose={() => setCloudOpen(false)}
|
||||
/>
|
||||
)}
|
||||
@@ -2071,11 +2675,23 @@ export default function App() {
|
||||
onClose={() => setAdminOpen(false)}
|
||||
onChanged={() => {
|
||||
void getHealth().then((health) => setCloudHealth(health));
|
||||
void getImmichStatus().then(setImmichStatus).catch(() => undefined);
|
||||
}}
|
||||
onRestored={() => void refreshCatalogFromServer()}
|
||||
/>
|
||||
)}
|
||||
|
||||
{immichOpen && cloudUser && (
|
||||
<ImmichPanel
|
||||
onClose={() => setImmichOpen(false)}
|
||||
onChanged={() => {
|
||||
void getImmichStatus().then(setImmichStatus).catch(() => undefined);
|
||||
void refreshCatalogFromServer();
|
||||
}}
|
||||
onToast={setToast}
|
||||
/>
|
||||
)}
|
||||
|
||||
{menu &&
|
||||
(() => {
|
||||
const targets = photos.filter((p) => menu.ids.includes(p.id));
|
||||
@@ -2133,6 +2749,21 @@ export default function App() {
|
||||
disabled: menu.ids.length < 2,
|
||||
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: '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 && (
|
||||
<div className="toast">
|
||||
<span>{toast}</span>
|
||||
|
||||
@@ -15,14 +15,17 @@ import {
|
||||
adminCreateUser,
|
||||
adminDeleteEvent,
|
||||
adminDeleteUser,
|
||||
adminDisconnectImmich,
|
||||
adminRestoreCatalog,
|
||||
adminRevokeInvite,
|
||||
adminOverview,
|
||||
adminRenameEvent,
|
||||
adminSaveImmich,
|
||||
adminSaveMail,
|
||||
adminSchedulePrune,
|
||||
adminSetQuota,
|
||||
adminSetStorage,
|
||||
adminTestImmich,
|
||||
adminTestMail,
|
||||
adminUpdateUser,
|
||||
adminWarnUser,
|
||||
@@ -68,7 +71,7 @@ const planSummary = (quota: AdminQuota) => {
|
||||
return parts.length ? parts.join(', ') : 'nothing';
|
||||
};
|
||||
|
||||
type Tab = 'users' | 'invites' | 'content' | 'storage' | 'quotas' | 'backup';
|
||||
type Tab = 'users' | 'invites' | 'content' | 'storage' | 'quotas' | 'immich' | 'backup';
|
||||
|
||||
const inviteUrl = (token: string) => `${window.location.origin}/join/${token}`;
|
||||
|
||||
@@ -112,6 +115,8 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
|
||||
const [quotaDrafts, setQuotaDrafts] = useState<Record<string, string>>({});
|
||||
const [mailDraft, setMailDraft] = useState({ user: '', appPassword: '', from: '' });
|
||||
const [mail, setMail] = useState<MailStatus | null>(null);
|
||||
const [immichDraft, setImmichDraft] = useState({ url: '', apiKey: '', enabled: true });
|
||||
|
||||
|
||||
const restoreCatalog = async (file: File | undefined) => {
|
||||
if (!file || busy) return;
|
||||
@@ -161,6 +166,11 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
|
||||
user: current.user || next.mail.user,
|
||||
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));
|
||||
onChanged();
|
||||
}, [onChanged]);
|
||||
@@ -174,6 +184,13 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
|
||||
setOverview(next);
|
||||
setMail(next.mail);
|
||||
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);
|
||||
setQuotaDrafts(
|
||||
Object.fromEntries(
|
||||
@@ -345,6 +362,42 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
|
||||
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 = () => {
|
||||
if (!editEvent) return;
|
||||
const name = editEvent.name.trim();
|
||||
@@ -404,6 +457,9 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
|
||||
<button className={`tab ${tab === 'quotas' ? 'on' : ''}`} onClick={() => setTab('quotas')}>
|
||||
Quotas
|
||||
</button>
|
||||
<button className={`tab ${tab === 'immich' ? 'on' : ''}`} onClick={() => setTab('immich')}>
|
||||
Immich
|
||||
</button>
|
||||
<button className={`tab ${tab === 'backup' ? 'on' : ''}`} onClick={() => setTab('backup')}>
|
||||
Backup
|
||||
</button>
|
||||
@@ -926,6 +982,108 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
|
||||
</p>
|
||||
</div>
|
||||
</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' ? (
|
||||
<section className="admin-section">
|
||||
<h3>Catalog backup</h3>
|
||||
|
||||
@@ -12,6 +12,7 @@ interface Props {
|
||||
onLogout: () => void;
|
||||
onSync: () => void;
|
||||
onAdmin: () => void;
|
||||
onImmich: () => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
@@ -32,6 +33,7 @@ export default function CloudPanel({
|
||||
onLogout,
|
||||
onSync,
|
||||
onAdmin,
|
||||
onImmich,
|
||||
onClose,
|
||||
}: Props) {
|
||||
const [mode, setMode] = useState<'signin' | 'signup'>('signin');
|
||||
@@ -121,6 +123,14 @@ export default function CloudPanel({
|
||||
Administration
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="btn ghost"
|
||||
onClick={onImmich}
|
||||
disabled={busy}
|
||||
title="Optional: sync albums with your own Immich server"
|
||||
>
|
||||
Immich sync
|
||||
</button>
|
||||
</div>
|
||||
{note && <div className="banner ok">{note}</div>}
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { getBitmap } from '../lib/images';
|
||||
import { get16BitSource, getBitmap } from '../lib/images';
|
||||
import type { Preview16 } from '../lib/preview16';
|
||||
import { rotatedBounds, Renderer } from '../gl/renderer';
|
||||
import { buildLensCorrection, type LensCorrection } from '../lib/lensfun';
|
||||
import { buildLensCorrection, type LensCorrection } from '../lib/lensEngine';
|
||||
import type { PhotoRecord } from '../types';
|
||||
|
||||
interface Props {
|
||||
@@ -15,6 +16,7 @@ function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: strin
|
||||
const boxRef = useRef<HTMLDivElement>(null);
|
||||
const rendererRef = useRef<Renderer | 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 [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -29,6 +31,23 @@ function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: strin
|
||||
};
|
||||
}, [photo]);
|
||||
|
||||
// Compare renders the full proxy, so the matching 16-bit sidecar is what lets
|
||||
// a per-photo camera profile show here exactly as it does in Develop. Without
|
||||
// a profile the JPEG already carries the body matrix, so skip the big fetch.
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
if (!photo.edits.cameraProfile) {
|
||||
setHdr(null);
|
||||
return;
|
||||
}
|
||||
get16BitSource(photo)
|
||||
.then((next) => alive && setHdr(next))
|
||||
.catch(() => alive && setHdr(null));
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [photo]);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
if (!photo.edits.lens || !bitmap) {
|
||||
@@ -98,14 +117,14 @@ function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: strin
|
||||
lens: lensCorrection,
|
||||
};
|
||||
try {
|
||||
renderer.setImage(bitmap);
|
||||
renderer.setImage(bitmap, hdr);
|
||||
renderer.render(photo.edits, opts);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Rendering failed');
|
||||
}
|
||||
});
|
||||
return () => cancelAnimationFrame(raf);
|
||||
}, [bitmap, box, photo, lensCorrection]);
|
||||
}, [bitmap, box, photo, lensCorrection, hdr]);
|
||||
|
||||
return (
|
||||
<figure className="compare-tile" onDoubleClick={() => onOpen(photo.id)}>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -2,16 +2,33 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { buildSampler, clamp01 } from '../lib/curves';
|
||||
import type { CurvePoint } from '../types';
|
||||
|
||||
export type ParametricKey = 'highlights' | 'lights' | 'darks' | 'blacks';
|
||||
|
||||
interface Props {
|
||||
points: CurvePoint[];
|
||||
onChange: (points: CurvePoint[]) => void;
|
||||
color: string;
|
||||
/** Region tone shaper values, shown as draggable dots on the curve. */
|
||||
parametric?: Record<ParametricKey, number>;
|
||||
onParametric?: (key: ParametricKey, value: number) => void;
|
||||
}
|
||||
|
||||
export default function CurveEditor({ points, onChange, color }: Props) {
|
||||
/** Lightroom-scale zones: the four regions share the diagonal evenly. */
|
||||
const ZONES: { key: ParametricKey; label: string; x: number }[] = [
|
||||
{ key: 'highlights', label: 'Highlights', x: 0.875 },
|
||||
{ key: 'lights', label: 'Lights', x: 0.625 },
|
||||
{ key: 'darks', label: 'Darks', x: 0.375 },
|
||||
{ key: 'blacks', label: 'Blacks', x: 0.125 },
|
||||
];
|
||||
|
||||
/** Full slider travel moves a zone dot a quarter of the graph. */
|
||||
const ZONE_TRAVEL = 0.18;
|
||||
|
||||
export default function CurveEditor({ points, onChange, color, parametric, onParametric }: Props) {
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const pointsRef = useRef(points);
|
||||
const [drag, setDrag] = useState<number | null>(null);
|
||||
const [paramDrag, setParamDrag] = useState<ParametricKey | null>(null);
|
||||
const [hover, setHover] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -42,6 +59,12 @@ export default function CurveEditor({ points, onChange, color }: Props) {
|
||||
|
||||
const handleDown = (e: React.PointerEvent<SVGSVGElement>) => {
|
||||
e.preventDefault();
|
||||
const paramAttr = (e.target as Element).getAttribute('data-param');
|
||||
if (paramAttr && parametric && onParametric) {
|
||||
setParamDrag(paramAttr as ParametricKey);
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
return;
|
||||
}
|
||||
const idxAttr = (e.target as Element).getAttribute('data-idx');
|
||||
let idx: number;
|
||||
if (idxAttr !== null) {
|
||||
@@ -57,6 +80,15 @@ export default function CurveEditor({ points, onChange, color }: Props) {
|
||||
};
|
||||
|
||||
const handleMove = (e: React.PointerEvent<SVGSVGElement>) => {
|
||||
if (paramDrag && parametric && onParametric) {
|
||||
const zone = ZONES.find((item) => item.key === paramDrag);
|
||||
if (!zone) return;
|
||||
const p = toNorm(e.clientX, e.clientY);
|
||||
const base = sampler(zone.x);
|
||||
const value = ((p.y - base) / ZONE_TRAVEL) * 100;
|
||||
onParametric(paramDrag, Math.round(Math.max(-100, Math.min(100, value))));
|
||||
return;
|
||||
}
|
||||
if (drag === null) return;
|
||||
const pts = pointsRef.current;
|
||||
const idx = drag;
|
||||
@@ -68,7 +100,10 @@ export default function CurveEditor({ points, onChange, color }: Props) {
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
const handleUp = () => setDrag(null);
|
||||
const handleUp = () => {
|
||||
setDrag(null);
|
||||
setParamDrag(null);
|
||||
};
|
||||
|
||||
const removePoint = (idx: number) => {
|
||||
const pts = pointsRef.current;
|
||||
@@ -101,6 +136,37 @@ export default function CurveEditor({ points, onChange, color }: Props) {
|
||||
</g>
|
||||
))}
|
||||
<line x1="0" y1="100" x2="100" y2="0" className="curve-diag" />
|
||||
{parametric &&
|
||||
onParametric &&
|
||||
ZONES.map((zone) => {
|
||||
const value = parametric[zone.key] ?? 0;
|
||||
const y = clamp01(sampler(zone.x) + (value / 100) * ZONE_TRAVEL);
|
||||
return (
|
||||
<g key={zone.key} style={{ cursor: 'ns-resize' }}>
|
||||
<line
|
||||
x1={zone.x * 100}
|
||||
y1="0"
|
||||
x2={zone.x * 100}
|
||||
y2="100"
|
||||
stroke="rgba(255,255,255,0.12)"
|
||||
strokeDasharray="2 3"
|
||||
vectorEffect="non-scaling-stroke"
|
||||
/>
|
||||
<circle
|
||||
data-param={zone.key}
|
||||
cx={zone.x * 100}
|
||||
cy={(1 - y) * 100}
|
||||
r={paramDrag === zone.key ? 3.2 : 2.3}
|
||||
fill="#141416"
|
||||
stroke="#f0c86a"
|
||||
strokeWidth="1.4"
|
||||
vectorEffect="non-scaling-stroke"
|
||||
>
|
||||
<title>{`${zone.label}: ${value > 0 ? '+' : ''}${value}`}</title>
|
||||
</circle>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
<path d={path} fill="none" stroke={color} strokeWidth="1.6" vectorEffect="non-scaling-stroke" />
|
||||
{points.map((p, i) => (
|
||||
<circle
|
||||
@@ -116,7 +182,9 @@ export default function CurveEditor({ points, onChange, color }: Props) {
|
||||
/>
|
||||
))}
|
||||
</svg>
|
||||
<div className="curve-hint">Click to add a point · drag to shape · double-click a point to remove</div>
|
||||
<div className="curve-hint">
|
||||
Click to add a point · drag to shape · drag the four gold dots for highlights, lights, darks and blacks
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+352
-62
@@ -5,10 +5,12 @@ import {
|
||||
defaultLocalLayer,
|
||||
MAX_HEAL_SPOTS,
|
||||
MAX_LOCAL_LAYERS,
|
||||
thumbTransform,
|
||||
} from '../lib/edits';
|
||||
import { subscribeClipPreview } from '../lib/clipPreview';
|
||||
import { getBitmap, getDenoisedBitmap } from '../lib/images';
|
||||
import { get16BitSource, getBitmap, getDenoisedBitmap } from '../lib/images';
|
||||
import { rebuildProofCube, restoreProofProfile } from '../lib/softProof';
|
||||
import { photosForCamera } from '../lib/dcpLibrary';
|
||||
import type { Preview16 } from '../lib/preview16';
|
||||
import { useMediaQuery } from '../lib/useMediaQuery';
|
||||
import { usePersistentState } from '../lib/usePersistentState';
|
||||
import { solveWhiteBalance } from '../lib/whiteBalance';
|
||||
@@ -18,7 +20,7 @@ import {
|
||||
correctLensPoint,
|
||||
uncorrectLensPoint,
|
||||
type LensCorrection,
|
||||
} from '../lib/lensfun';
|
||||
} from '../lib/lensEngine';
|
||||
import {
|
||||
frameToSource,
|
||||
rotatedBounds,
|
||||
@@ -42,6 +44,7 @@ import type {
|
||||
Snapshot,
|
||||
} from '../types';
|
||||
import ContextMenu, { type MenuEntry } from './ContextMenu';
|
||||
import EditedImage from './EditedImage';
|
||||
import CropOverlay from './CropOverlay';
|
||||
import Histogram from './Histogram';
|
||||
import {
|
||||
@@ -59,6 +62,7 @@ import {
|
||||
OpticsPanel,
|
||||
PresetsPanel,
|
||||
ProofPanel,
|
||||
CameraProfilePanel,
|
||||
SnapshotsPanel,
|
||||
} from './Panels';
|
||||
import Stars, { ColorSwatches, FlagButtons } from './Stars';
|
||||
@@ -121,15 +125,26 @@ interface Props {
|
||||
onSelect: (id: string) => void;
|
||||
onExit: () => void;
|
||||
onUpdate: (id: string, patch: Partial<PhotoRecord>, historyLabel?: string) => void;
|
||||
/** Auto-sync: merge a patch into several photos' own edits at once. */
|
||||
onUpdateEdits?: (ids: string[], patch: Partial<Edits>, historyLabel?: string) => void;
|
||||
clipboard: Edits | null;
|
||||
onCopy: () => void;
|
||||
onPaste: () => void;
|
||||
/** Copy settings from a named filmstrip photo instead of the canvas photo. */
|
||||
onCopyOf?: (id: string) => void;
|
||||
/** Paste the copied settings; no ids means the photo on the canvas. */
|
||||
onPaste: (ids?: string[]) => void;
|
||||
/** Reset several photos at once, without a per-photo confirmation. */
|
||||
onResetSelection?: (ids: string[]) => void;
|
||||
localClipboard: LocalLayer | null;
|
||||
onLocalClipboard: (layer: LocalLayer | null) => void;
|
||||
onExport: () => void;
|
||||
onPrint: () => void;
|
||||
canPushImmich?: boolean;
|
||||
onPushImmich?: () => void;
|
||||
onOpenImmich?: () => void;
|
||||
presets: Preset[];
|
||||
onSavePreset: (name: string, edits: Edits) => void;
|
||||
onDeletePreset: (id: string) => void;
|
||||
onDelete: () => void;
|
||||
onVirtualCopy: () => void;
|
||||
metadataPresets: MetadataPreset[];
|
||||
@@ -148,15 +163,22 @@ export default function Develop({
|
||||
onSelect,
|
||||
onExit,
|
||||
onUpdate,
|
||||
onUpdateEdits,
|
||||
clipboard,
|
||||
onCopy,
|
||||
onCopyOf,
|
||||
onPaste,
|
||||
onResetSelection,
|
||||
localClipboard,
|
||||
onLocalClipboard,
|
||||
onExport,
|
||||
onPrint,
|
||||
canPushImmich = false,
|
||||
onPushImmich,
|
||||
onOpenImmich,
|
||||
presets,
|
||||
onSavePreset,
|
||||
onDeletePreset,
|
||||
onDelete,
|
||||
onVirtualCopy,
|
||||
metadataPresets,
|
||||
@@ -176,7 +198,10 @@ export default function Develop({
|
||||
const panRef = useRef<{ x: number; y: number; cx: number; cy: number } | null>(null);
|
||||
|
||||
const [bitmap, setBitmap] = useState<ImageBitmap | null>(null);
|
||||
const [hdrSource, setHdrSource] = useState<Preview16 | null>(null);
|
||||
const [denoisedBitmap, setDenoisedBitmap] = useState<ImageBitmap | null>(null);
|
||||
/** Name of the printer ICC profile loaded for this session, if any. */
|
||||
const [proofProfile, setProofProfile] = useState<string | null>(null);
|
||||
const [stage, setStage] = useState({ w: 0, h: 0 });
|
||||
const [cropMode, setCropMode] = useState(false);
|
||||
const [cropDrag, setCropDrag] = useState(false);
|
||||
@@ -196,7 +221,12 @@ export default function Develop({
|
||||
const toggleStrip = () => (mobile ? setMobileStripOpen((open) => !open) : setStripOpen((open) => !open));
|
||||
const [filmMinRating, setFilmMinRating] = useState(0);
|
||||
const [filmFlag, setFilmFlag] = useState<Flag | 'any'>('any');
|
||||
// Filmstrip multi-select. The canvas keeps its own photo; this is the set a
|
||||
// paste applies to, exactly like Lightroom's filmstrip selection.
|
||||
const [filmSel, setFilmSel] = useState<string[]>([photo.id]);
|
||||
const [filmAnchor, setFilmAnchor] = useState(photo.id);
|
||||
const [showOriginal, setShowOriginal] = useState(false);
|
||||
const [autoSync, setAutoSync] = usePersistentState('develop.autosync', false);
|
||||
const [histVersion, setHistVersion] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -208,8 +238,14 @@ export default function Develop({
|
||||
const [panning, setPanning] = useState(false);
|
||||
const [navigatorView, setNavigatorView] = useState<Rect | null>(null);
|
||||
const [readout, setReadout] = useState({ shown: 100, fit: 100 });
|
||||
const [menu, setMenu] = useState<{ x: number; y: number; kind: 'canvas' | 'film' } | null>(null);
|
||||
const [menu, setMenu] = useState<{
|
||||
x: number;
|
||||
y: number;
|
||||
kind: 'canvas' | 'film';
|
||||
ids?: string[];
|
||||
} | null>(null);
|
||||
const [healMode, setHealMode] = useState(false);
|
||||
const [rangePicking, setRangePicking] = useState(false);
|
||||
const [brushPx, setBrushPx] = useState(56);
|
||||
const [healFeather, setHealFeather] = useState(50);
|
||||
const [healSelected, setHealSelected] = useState<number | null>(null);
|
||||
@@ -236,6 +272,13 @@ export default function Develop({
|
||||
} | null>(null);
|
||||
|
||||
const edits = photo.edits;
|
||||
// A DCP matrix describes the sensor, so one profile can serve every raw from
|
||||
// the same body; the panel offers a bulk apply only when there is more than
|
||||
// this photo to update.
|
||||
const cameraProfileTargets = useMemo(
|
||||
() => photosForCamera(photos, photo.meta?.camera),
|
||||
[photos, photo.meta?.camera],
|
||||
);
|
||||
const activeLocal = (edits.local ?? []).find((layer) => layer.id === localSelected) ?? null;
|
||||
const zoomed = zoom.pct !== 'fit';
|
||||
|
||||
@@ -267,6 +310,49 @@ export default function Develop({
|
||||
[filmPhotos, onSelect, photo.id],
|
||||
);
|
||||
|
||||
// The photo on the canvas is always part of the selection, so a fresh filmstrip
|
||||
// starts with just that frame. Cmd/Shift clicks grow the set without moving it.
|
||||
useEffect(() => {
|
||||
setFilmSel([photo.id]);
|
||||
setFilmAnchor(photo.id);
|
||||
}, [photo.id]);
|
||||
|
||||
// A cull filter can hide part of the selection; drop those frames rather than
|
||||
// pasting settings into photos that are no longer on screen.
|
||||
useEffect(() => {
|
||||
setFilmSel((prev) => {
|
||||
const visible = new Set(filmPhotos.map((item) => item.id));
|
||||
const next = prev.filter((id) => visible.has(id));
|
||||
return next.length === prev.length ? prev : next;
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [filmMinRating, filmFlag]);
|
||||
|
||||
const clickFilm = (p: PhotoRecord, e: React.MouseEvent) => {
|
||||
if (e.shiftKey) {
|
||||
const a = filmPhotos.findIndex((item) => item.id === filmAnchor);
|
||||
const b = filmPhotos.findIndex((item) => item.id === p.id);
|
||||
if (a >= 0 && b >= 0) {
|
||||
const [lo, hi] = a < b ? [a, b] : [b, a];
|
||||
setFilmSel(filmPhotos.slice(lo, hi + 1).map((item) => item.id));
|
||||
} else {
|
||||
setFilmSel([p.id]);
|
||||
setFilmAnchor(p.id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (e.metaKey || e.ctrlKey) {
|
||||
setFilmSel((prev) =>
|
||||
prev.includes(p.id) ? prev.filter((id) => id !== p.id) : [...prev, p.id],
|
||||
);
|
||||
setFilmAnchor(p.id);
|
||||
return;
|
||||
}
|
||||
setFilmSel([p.id]);
|
||||
setFilmAnchor(p.id);
|
||||
onSelect(p.id);
|
||||
};
|
||||
|
||||
const moveLensSplit = (e: React.PointerEvent<HTMLButtonElement>) => {
|
||||
const rect = e.currentTarget.parentElement?.getBoundingClientRect();
|
||||
if (!rect || rect.width <= 0) return;
|
||||
@@ -275,9 +361,17 @@ export default function Develop({
|
||||
|
||||
const setEdits = useCallback(
|
||||
(patch: Partial<Edits>, label: string) => {
|
||||
// Auto-sync applies only the changed controls to the rest of the
|
||||
// filmstrip, so each photo keeps its own untouched settings, crop and
|
||||
// masks. The canvas photo is always updated last so the preview follows
|
||||
// the slider that was actually moved.
|
||||
if (autoSync && filmSel.length > 1 && onUpdateEdits) {
|
||||
const others = filmSel.filter((id) => id !== photo.id);
|
||||
if (others.length) onUpdateEdits(others, patch, label);
|
||||
}
|
||||
onUpdate(photo.id, { edits: { ...photo.edits, ...patch } }, label);
|
||||
},
|
||||
[onUpdate, photo.id, photo.edits],
|
||||
[autoSync, filmSel, onUpdate, onUpdateEdits, photo.id, photo.edits],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -334,6 +428,14 @@ export default function Develop({
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
setLoading(true);
|
||||
// The 16-bit sidecar is optional and can be tens of megabytes, so it loads
|
||||
// behind the JPEG and simply swaps the source texture when it lands.
|
||||
setHdrSource(null);
|
||||
get16BitSource(photo)
|
||||
.then((hdr) => {
|
||||
if (alive) setHdrSource(hdr);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
getBitmap(photo)
|
||||
.then((bmp) => {
|
||||
if (!alive) return;
|
||||
@@ -443,22 +545,14 @@ export default function Develop({
|
||||
let cssH = Math.max(40, Math.round(contentH * fitScale));
|
||||
|
||||
if (zoomFactor > 1.0001) {
|
||||
// The visible window keeps the stage's aspect, so the canvas is stage sized
|
||||
// and the shader maps it onto a sub-rect of the frame. Cost stays constant
|
||||
// no matter how far you zoom, and detail comes from the source bitmap.
|
||||
const vw = Math.min(1, availW / (fitScale * zoomFactor) / frame.w);
|
||||
const vh = Math.min(1, availH / (fitScale * zoomFactor) / frame.h);
|
||||
const cx =
|
||||
vw >= content.w
|
||||
? content.x + content.w / 2
|
||||
: clampNum(zoom.cx, content.x + vw / 2, content.x + content.w - vw / 2);
|
||||
const cy =
|
||||
vh >= content.h
|
||||
? content.y + content.h / 2
|
||||
: clampNum(zoom.cy, content.y + vh / 2, content.y + content.h - vh / 2);
|
||||
// The canvas keeps the photo's fit-sized box while zooming and the window
|
||||
// shrinks inside the crop at the same aspect. Growing the canvas to the
|
||||
// stage's shape instead stretched any photo whose aspect differed from it.
|
||||
const vw = content.w / zoomFactor;
|
||||
const vh = content.h / zoomFactor;
|
||||
const cx = clampNum(zoom.cx, content.x + vw / 2, content.x + content.w - vw / 2);
|
||||
const cy = clampNum(zoom.cy, content.y + vh / 2, content.y + content.h - vh / 2);
|
||||
view = { x: cx - vw / 2, y: cy - vh / 2, w: vw, h: vh };
|
||||
cssW = Math.round(availW);
|
||||
cssH = Math.round(availH);
|
||||
}
|
||||
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2);
|
||||
@@ -490,7 +584,7 @@ export default function Develop({
|
||||
);
|
||||
|
||||
try {
|
||||
renderer.setImage(bitmap);
|
||||
renderer.setImage(bitmap, hdrSource);
|
||||
// "Show original" must show the untouched source, not the cleaned proxy.
|
||||
renderer.setDenoised(showOriginal ? null : denoisedBitmap, activeEdits.aiDenoise.amount / 100);
|
||||
renderer.render(activeEdits, {
|
||||
@@ -518,6 +612,7 @@ export default function Develop({
|
||||
}
|
||||
}, [
|
||||
bitmap,
|
||||
hdrSource,
|
||||
denoisedBitmap,
|
||||
edits,
|
||||
cropMode,
|
||||
@@ -530,6 +625,9 @@ export default function Develop({
|
||||
lensCorrection,
|
||||
lensSplit,
|
||||
lensSplitAt,
|
||||
// Loading or clearing a printer profile changes the finish pass, and the
|
||||
// cube lives outside the edit record, so the redraw is keyed on it here.
|
||||
proofProfile,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -538,6 +636,25 @@ export default function Develop({
|
||||
return () => cancelAnimationFrame(raf);
|
||||
}, [bitmap, drawPreview]);
|
||||
|
||||
// The printer profile lives outside the edit record, so restoring it and
|
||||
// following an intent change are handled here rather than by the proof panel.
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
void restoreProofProfile(edits.proof.intent).then((cube) => {
|
||||
if (alive && cube) setProofProfile(cube.name);
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
// Restore once; intent changes are picked up by the effect below.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const cube = rebuildProofCube(edits.proof.intent);
|
||||
if (cube) setProofProfile(cube.name);
|
||||
}, [edits.proof.intent]);
|
||||
|
||||
/* ------------------------------------------------------------ zoom & pan */
|
||||
|
||||
const applyZoom = useCallback((rawPct: number | 'fit', point?: { x: number; y: number }) => {
|
||||
@@ -569,11 +686,11 @@ export default function Develop({
|
||||
}
|
||||
}
|
||||
|
||||
const vw = geo.availW / (geo.fitScale * zNext) / geo.frameW;
|
||||
const vh = geo.availH / (geo.fitScale * zNext) / geo.frameH;
|
||||
const c = geo.content;
|
||||
cx = vw >= c.w ? c.x + c.w / 2 : clampNum(cx, c.x + vw / 2, c.x + c.w - vw / 2);
|
||||
cy = vh >= c.h ? c.y + c.h / 2 : clampNum(cy, c.y + vh / 2, c.y + c.h - vh / 2);
|
||||
const vw = c.w / zNext;
|
||||
const vh = c.h / zNext;
|
||||
cx = clampNum(cx, c.x + vw / 2, c.x + c.w - vw / 2);
|
||||
cy = clampNum(cy, c.y + vh / 2, c.y + c.h - vh / 2);
|
||||
setZoom({ pct: next, cx, cy });
|
||||
}, []);
|
||||
|
||||
@@ -588,16 +705,10 @@ export default function Develop({
|
||||
const pct = zoom.pct === 'fit' ? 100 : zoom.pct;
|
||||
const z = Math.max(1, pct / geo.fitPct);
|
||||
const c = geo.content;
|
||||
const vw = Math.min(c.w, geo.availW / (geo.fitScale * z) / geo.frameW);
|
||||
const vh = Math.min(c.h, geo.availH / (geo.fitScale * z) / geo.frameH);
|
||||
const cx =
|
||||
vw >= c.w
|
||||
? c.x + c.w / 2
|
||||
: clampNum(fx, c.x + vw / 2, c.x + c.w - vw / 2);
|
||||
const cy =
|
||||
vh >= c.h
|
||||
? c.y + c.h / 2
|
||||
: clampNum(fy, c.y + vh / 2, c.y + c.h - vh / 2);
|
||||
const vw = c.w / z;
|
||||
const vh = c.h / z;
|
||||
const cx = clampNum(fx, c.x + vw / 2, c.x + c.w - vw / 2);
|
||||
const cy = clampNum(fy, c.y + vh / 2, c.y + c.h - vh / 2);
|
||||
setZoom({ pct, cx, cy });
|
||||
},
|
||||
[zoom.pct],
|
||||
@@ -652,7 +763,7 @@ export default function Develop({
|
||||
}, [cropMode, applyZoom, healMode, localMode, activeLocal]);
|
||||
|
||||
const beginPan = (e: React.PointerEvent<HTMLCanvasElement>) => {
|
||||
if (picking || cropMode || healMode || localMode || !zoomed || e.button !== 0) return;
|
||||
if (picking || rangePicking || cropMode || healMode || localMode || !zoomed || e.button !== 0) return;
|
||||
const geo = geoRef.current;
|
||||
panRef.current = {
|
||||
x: e.clientX,
|
||||
@@ -942,6 +1053,58 @@ export default function Develop({
|
||||
[autoMaskBusy, bitmap, commitLocal, edits.local, photo],
|
||||
);
|
||||
|
||||
/**
|
||||
* Colour-range sampler: read the untouched source colour under the pointer and
|
||||
* shape the active mask's range around its hue, saturation and luma. The same
|
||||
* source colour the mask range compares against, so the result lines up even
|
||||
* under a heavy grade.
|
||||
*/
|
||||
const pickRangeColour = (e: React.MouseEvent<HTMLCanvasElement>) => {
|
||||
if (!rangePicking || !activeLocal) return;
|
||||
const canvas = canvasRef.current;
|
||||
const renderer = rendererRef.current;
|
||||
if (!canvas || !renderer) return;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
if (!rect.width || !rect.height) return;
|
||||
const geo = geoRef.current;
|
||||
const sample = renderer.pickSource(edits, {
|
||||
nx: clampNum((e.clientX - rect.left) / rect.width, 0, 1),
|
||||
ny: clampNum((e.clientY - rect.top) / rect.height, 0, 1),
|
||||
view: geo.zoomFactor > 1.0001 ? geo.view : undefined,
|
||||
upscale: Math.min(window.devicePixelRatio || 1, 2) * geo.fitScale * geo.zoomFactor > 1.1,
|
||||
});
|
||||
setRangePicking(false);
|
||||
if (!sample) return;
|
||||
const [r, g, b] = sample;
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
const delta = max - min;
|
||||
let hue = 0;
|
||||
if (delta > 1e-6) {
|
||||
if (max === r) hue = ((g - b) / delta) % 6;
|
||||
else if (max === g) hue = (b - r) / delta + 2;
|
||||
else hue = (r - g) / delta + 4;
|
||||
hue = (hue * 60 + 360) % 360;
|
||||
}
|
||||
const sat = max > 0 ? delta / max : 0;
|
||||
const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
patchLocal(
|
||||
activeLocal.id,
|
||||
{
|
||||
range: {
|
||||
...activeLocal.range,
|
||||
enabled: true,
|
||||
hue: Math.round(hue),
|
||||
hueRange: 40,
|
||||
satMin: Math.round(Math.max(0, sat * 100 - 25)),
|
||||
lumaMin: Math.round(Math.max(0, luma * 100 - 14)),
|
||||
lumaMax: Math.round(Math.min(100, luma * 100 + 14)),
|
||||
},
|
||||
},
|
||||
'Sample mask colour',
|
||||
);
|
||||
};
|
||||
|
||||
const deleteLocalLayer = useCallback(
|
||||
(id: string) => {
|
||||
commitLocal((edits.local ?? []).filter((layer) => layer.id !== id), 'Delete local adjustment');
|
||||
@@ -1277,7 +1440,7 @@ export default function Develop({
|
||||
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'c') {
|
||||
onCopy();
|
||||
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'v') {
|
||||
onPaste();
|
||||
onPaste(filmSel);
|
||||
}
|
||||
};
|
||||
const up = (e: KeyboardEvent) => {
|
||||
@@ -1300,6 +1463,7 @@ export default function Develop({
|
||||
navigateFilm,
|
||||
onCopy,
|
||||
onPaste,
|
||||
filmSel,
|
||||
undo,
|
||||
redo,
|
||||
applyZoom,
|
||||
@@ -1315,7 +1479,15 @@ export default function Develop({
|
||||
const next: Edits =
|
||||
preset.id === 'original'
|
||||
? { ...defaultEdits(), crop: photo.edits.crop }
|
||||
: { ...photo.edits, ...preset.edits, crop: photo.edits.crop };
|
||||
: {
|
||||
...photo.edits,
|
||||
...preset.edits,
|
||||
crop: photo.edits.crop,
|
||||
// The camera profile belongs to the body that produced the raw.
|
||||
cameraProfile: photo.edits.cameraProfile,
|
||||
// A strong film response must not leak into the next look.
|
||||
redscale: preset.edits.redscale ?? 0,
|
||||
};
|
||||
onUpdate(photo.id, { edits: next }, `Preset: ${preset.name}`);
|
||||
},
|
||||
[onUpdate, photo.id, photo.edits],
|
||||
@@ -1367,6 +1539,13 @@ export default function Develop({
|
||||
onPasteLayer={pasteLocalLayer}
|
||||
canPaste={Boolean(localClipboard)}
|
||||
onAutoMask={(kind) => void addAutoMask(kind)}
|
||||
onSampleRange={() => {
|
||||
setRangePicking(true);
|
||||
setLocalMode(false);
|
||||
setHealMode(false);
|
||||
setPicking(false);
|
||||
setCropMode(false);
|
||||
}}
|
||||
autoBusy={autoMaskBusy}
|
||||
/>
|
||||
<EffectsPanel edits={edits} photo={photo} set={setEdits} grainFreeze={cropDrag} />
|
||||
@@ -1379,7 +1558,42 @@ export default function Develop({
|
||||
lensSplit={lensSplit}
|
||||
onLensSplit={setLensSplit}
|
||||
/>
|
||||
<ProofPanel edits={edits} photo={photo} set={setEdits} />
|
||||
<CameraProfilePanel
|
||||
edits={edits}
|
||||
photo={photo}
|
||||
set={setEdits}
|
||||
cameraNative={Boolean(hdrSource?.rgbCam)}
|
||||
cameraPhotoCount={cameraProfileTargets.length}
|
||||
onApplyToCamera={
|
||||
onUpdateEdits
|
||||
? (profile) => {
|
||||
const count = cameraProfileTargets.length;
|
||||
const camera = photo.meta?.camera || 'this camera';
|
||||
if (
|
||||
!window.confirm(
|
||||
`Apply “${profile.name}” to ${count} photos from ${camera}? ` +
|
||||
'This replaces any camera profile they already use.',
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
onUpdateEdits(
|
||||
cameraProfileTargets.map((target) => target.id),
|
||||
{ cameraProfile: profile },
|
||||
'Camera profile',
|
||||
);
|
||||
return true;
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<ProofPanel
|
||||
edits={edits}
|
||||
photo={photo}
|
||||
set={setEdits}
|
||||
proofProfile={proofProfile}
|
||||
onProofProfile={(cube) => setProofProfile(cube?.name ?? null)}
|
||||
/>
|
||||
{includeMetadata && (
|
||||
<MetadataPanel
|
||||
photo={photo}
|
||||
@@ -1450,18 +1664,58 @@ export default function Develop({
|
||||
{ label: 'Before / After', shortcut: '\\', onSelect: () => setShowOriginal((v) => !v) },
|
||||
'separator',
|
||||
{ label: 'Copy settings', shortcut: '⌘C', onSelect: onCopy },
|
||||
{ label: 'Paste settings', shortcut: '⌘V', onSelect: onPaste, disabled: !clipboard },
|
||||
{ label: 'Paste settings', shortcut: '⌘V', onSelect: () => onPaste([photo.id]), disabled: !clipboard },
|
||||
{ label: 'Reset settings', onSelect: resetAll },
|
||||
'separator',
|
||||
...(canPushImmich && onPushImmich
|
||||
? ([{ label: 'Send edit to Immich', onSelect: onPushImmich }] as MenuEntry[])
|
||||
: []),
|
||||
...(onOpenImmich
|
||||
? ([{ label: 'Open in Immich', onSelect: onOpenImmich }] as MenuEntry[])
|
||||
: []),
|
||||
{ label: 'Export…', onSelect: onExport },
|
||||
{ label: 'Delete photo…', danger: true, onSelect: onDelete },
|
||||
];
|
||||
|
||||
// Right-clicking one of several selected frames acts on the whole selection;
|
||||
// right-clicking outside it acts on that frame alone.
|
||||
const filmMenuIds = menu?.kind === 'film' && menu.ids?.length ? menu.ids : [photo.id];
|
||||
const filmMenu: MenuEntry[] = [
|
||||
{ label: 'Copy settings', onSelect: onCopy },
|
||||
{ label: 'Paste settings', onSelect: onPaste, disabled: !clipboard },
|
||||
{ label: 'Reset settings', onSelect: resetAll },
|
||||
{
|
||||
label: 'Open in Develop',
|
||||
disabled: filmMenuIds.includes(photo.id),
|
||||
onSelect: () => onSelect(filmMenuIds[0]),
|
||||
},
|
||||
'separator',
|
||||
{
|
||||
label: 'Copy settings',
|
||||
onSelect: () => (onCopyOf ? onCopyOf(filmMenuIds[0]) : onCopy()),
|
||||
},
|
||||
{
|
||||
label:
|
||||
filmMenuIds.length > 1
|
||||
? `Paste settings to ${filmMenuIds.length} photos…`
|
||||
: 'Paste settings',
|
||||
onSelect: () => onPaste(filmMenuIds),
|
||||
disabled: !clipboard,
|
||||
},
|
||||
{
|
||||
label:
|
||||
filmMenuIds.length > 1
|
||||
? `Reset adjustments on ${filmMenuIds.length} photos`
|
||||
: 'Reset settings',
|
||||
onSelect: () =>
|
||||
filmMenuIds.length > 1 && onResetSelection
|
||||
? onResetSelection(filmMenuIds)
|
||||
: resetAll(),
|
||||
},
|
||||
'separator',
|
||||
...(canPushImmich && onPushImmich
|
||||
? ([{ label: 'Send edit to Immich', onSelect: onPushImmich }] as MenuEntry[])
|
||||
: []),
|
||||
...(onOpenImmich
|
||||
? ([{ label: 'Open in Immich', onSelect: onOpenImmich }] as MenuEntry[])
|
||||
: []),
|
||||
{ label: 'Export…', onSelect: onExport },
|
||||
{ label: 'Delete photo…', danger: true, onSelect: onDelete },
|
||||
];
|
||||
@@ -1491,6 +1745,18 @@ export default function Develop({
|
||||
>
|
||||
Before / After
|
||||
</button>
|
||||
<button
|
||||
className={`btn ghost small ${autoSync ? 'on' : ''}`}
|
||||
onClick={() => setAutoSync((v) => !v)}
|
||||
aria-pressed={autoSync}
|
||||
title={
|
||||
autoSync
|
||||
? 'Auto-sync on: every adjustment applies to all selected filmstrip photos'
|
||||
: 'Auto-sync: apply adjustments to every selected filmstrip photo'
|
||||
}
|
||||
>
|
||||
Auto-sync{autoSync && filmSel.length > 1 ? ` (${filmSel.length})` : ''}
|
||||
</button>
|
||||
<button className={`btn ghost small ${cropMode ? 'on' : ''}`} onClick={() => setCropMode((v) => !v)} title="Crop & straighten (C)">
|
||||
Crop
|
||||
</button>
|
||||
@@ -1507,8 +1773,17 @@ export default function Develop({
|
||||
<button className="btn ghost small" onClick={onVirtualCopy} title="Create a virtual copy with its own edits">
|
||||
Virtual copy
|
||||
</button>
|
||||
<button className="btn ghost small" onClick={onPaste} disabled={!clipboard} title="Paste develop settings (⌘V)">
|
||||
Paste
|
||||
<button
|
||||
className="btn ghost small"
|
||||
onClick={() => onPaste(filmSel)}
|
||||
disabled={!clipboard || !filmSel.length}
|
||||
title={
|
||||
filmSel.length > 1
|
||||
? `Paste develop settings to ${filmSel.length} selected photos (⌘V)`
|
||||
: 'Paste develop settings (⌘V)'
|
||||
}
|
||||
>
|
||||
Paste{filmSel.length > 1 ? ` (${filmSel.length})` : ''}
|
||||
</button>
|
||||
<button className="btn ghost small" onClick={undo} disabled={!canUndo} title="Undo (⌘Z)">
|
||||
Undo
|
||||
@@ -1616,6 +1891,7 @@ export default function Develop({
|
||||
photo={photo}
|
||||
onApply={applyPreset}
|
||||
onSave={(name) => onSavePreset(name, photo.edits)}
|
||||
onDelete={onDeletePreset}
|
||||
/>
|
||||
<SnapshotsPanel
|
||||
snapshots={photo.snapshots ?? []}
|
||||
@@ -1651,8 +1927,8 @@ export default function Develop({
|
||||
<div className="canvas-wrap">
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
className={`preview ${zoomed ? 'zoomed' : ''} ${picking ? 'picking' : ''} ${healMode ? 'healing' : ''} ${localMode ? 'masking' : ''}`}
|
||||
onClick={pickWhiteBalance}
|
||||
className={`preview ${zoomed ? 'zoomed' : ''} ${picking || rangePicking ? 'picking' : ''} ${healMode ? 'healing' : ''} ${localMode ? 'masking' : ''}`}
|
||||
onClick={(e) => (rangePicking ? pickRangeColour(e) : pickWhiteBalance(e))}
|
||||
onPointerDown={(e) => {
|
||||
if (localMode) startLocalMask(e);
|
||||
else if (healMode) startHeal(e);
|
||||
@@ -2207,8 +2483,13 @@ export default function Develop({
|
||||
<button type="button" className="btn ghost small" onClick={onCopy}>
|
||||
Copy
|
||||
</button>
|
||||
<button type="button" className="btn ghost small" onClick={onPaste} disabled={!clipboard}>
|
||||
Paste
|
||||
<button
|
||||
type="button"
|
||||
className="btn ghost small"
|
||||
onClick={() => onPaste(filmSel)}
|
||||
disabled={!clipboard || !filmSel.length}
|
||||
>
|
||||
Paste{filmSel.length > 1 ? ` (${filmSel.length})` : ''}
|
||||
</button>
|
||||
<button type="button" className="btn ghost small" onClick={resetAll}>
|
||||
Reset
|
||||
@@ -2334,6 +2615,9 @@ export default function Develop({
|
||||
)}
|
||||
|
||||
<div className="spacer" />
|
||||
{filmSel.length > 1 && (
|
||||
<span className="film-count">{filmSel.length} selected</span>
|
||||
)}
|
||||
<span className="film-count">
|
||||
{filmPhotos.length} / {photos.length}
|
||||
</span>
|
||||
@@ -2344,22 +2628,28 @@ export default function Develop({
|
||||
{filmPhotos.map((p) => (
|
||||
<button
|
||||
key={p.id}
|
||||
className={`film ${p.id === photo.id ? 'active' : ''}`}
|
||||
onClick={() => onSelect(p.id)}
|
||||
className={`film ${p.id === photo.id ? 'active' : ''} ${
|
||||
filmSel.includes(p.id) ? 'selected' : ''
|
||||
}`}
|
||||
onClick={(e) => clickFilm(p, e)}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
if (p.id !== photo.id) onSelect(p.id);
|
||||
setMenu({ x: e.clientX, y: e.clientY, kind: 'film' });
|
||||
const inSelection = filmSel.includes(p.id);
|
||||
const ids = inSelection ? filmSel : [p.id];
|
||||
if (!inSelection) {
|
||||
setFilmSel([p.id]);
|
||||
setFilmAnchor(p.id);
|
||||
if (p.id !== photo.id) onSelect(p.id);
|
||||
}
|
||||
setMenu({ x: e.clientX, y: e.clientY, kind: 'film', ids });
|
||||
}}
|
||||
title={p.name}
|
||||
title={
|
||||
filmSel.length > 1 && filmSel.includes(p.id)
|
||||
? `${p.name} · ${filmSel.length} selected`
|
||||
: `${p.name} · Shift-click or Ctrl-click to select more`
|
||||
}
|
||||
>
|
||||
<img
|
||||
src={p.thumbUrl ?? p.thumb}
|
||||
alt={p.name}
|
||||
loading="lazy"
|
||||
draggable={false}
|
||||
style={{ transform: thumbTransform(p, 3 / 2) }}
|
||||
/>
|
||||
<EditedImage photo={p} alt={p.name} boxAspect={3 / 2} />
|
||||
{p.rating > 0 && <span className="film-rating">{'★'.repeat(p.rating)}</span>}
|
||||
</button>
|
||||
))}
|
||||
|
||||
@@ -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);
|
||||
@@ -17,9 +17,15 @@ interface Props {
|
||||
photos: PhotoRecord[];
|
||||
eventId: string;
|
||||
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;
|
||||
onDelete: (id: string) => void;
|
||||
onSyncGallery?: (id: string) => void;
|
||||
onPublishGallery?: (id: string) => void;
|
||||
/** Server-backed account, so RAW originals can be re-decoded. */
|
||||
canReprocessRaw?: boolean;
|
||||
onReprocessEvent?: (id: string) => void;
|
||||
onReorderEvents: (dragId: string, targetId: string) => void;
|
||||
onDropPhotos: (ids: string[], eventId: string) => void;
|
||||
trashOpen: boolean;
|
||||
@@ -39,9 +45,14 @@ export default function EventSidebar({
|
||||
photos,
|
||||
eventId,
|
||||
onSelectEvent,
|
||||
immichEnabled = false,
|
||||
onCreate,
|
||||
onRename,
|
||||
onDelete,
|
||||
onSyncGallery,
|
||||
onPublishGallery,
|
||||
canReprocessRaw = false,
|
||||
onReprocessEvent,
|
||||
onReorderEvents,
|
||||
onDropPhotos,
|
||||
trashOpen,
|
||||
@@ -55,9 +66,11 @@ export default function EventSidebar({
|
||||
}: Props) {
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [name, setName] = useState('');
|
||||
const [createGallery, setCreateGallery] = useState(false);
|
||||
const [dropTarget, setDropTarget] = useState<string | null>(null);
|
||||
|
||||
const counts = new Map<string, number>();
|
||||
const rawCounts = new Map<string, number>();
|
||||
let unsorted = 0;
|
||||
for (const p of photos) {
|
||||
if (!p.eventId) {
|
||||
@@ -65,6 +78,7 @@ export default function EventSidebar({
|
||||
continue;
|
||||
}
|
||||
counts.set(p.eventId, (counts.get(p.eventId) ?? 0) + 1);
|
||||
if (p.raw) rawCounts.set(p.eventId, (rawCounts.get(p.eventId) ?? 0) + 1);
|
||||
}
|
||||
|
||||
const submit = async () => {
|
||||
@@ -72,8 +86,9 @@ export default function EventSidebar({
|
||||
setAdding(false);
|
||||
return;
|
||||
}
|
||||
await onCreate(name);
|
||||
await onCreate(name, createGallery);
|
||||
setName('');
|
||||
setCreateGallery(false);
|
||||
setAdding(false);
|
||||
};
|
||||
|
||||
@@ -189,6 +204,16 @@ export default function EventSidebar({
|
||||
<button className="btn primary small" onClick={() => void submit()}>
|
||||
Add
|
||||
</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>
|
||||
)}
|
||||
|
||||
@@ -234,6 +259,37 @@ export default function EventSidebar({
|
||||
<span className="event-count">{counts.get(event.id) ?? 0}</span>
|
||||
</button>
|
||||
<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
|
||||
className="icon-btn"
|
||||
title="Rename event"
|
||||
|
||||
@@ -5,6 +5,8 @@ import Slider from './Slider';
|
||||
import { getBitmap } from '../lib/images';
|
||||
import { frameToSource, grainCellPx, grainSampleWindow, outputSize, rotatedBounds, Renderer } from '../gl/renderer';
|
||||
import type { PhotoRecord } from '../types';
|
||||
import { COLOR_SPACE_OPTIONS } from '../lib/colorSpace';
|
||||
import type { OutputColorSpace } from '../lib/icc';
|
||||
|
||||
interface Props {
|
||||
photos: PhotoRecord[];
|
||||
@@ -280,8 +282,12 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
|
||||
value={opts.format}
|
||||
onChange={(e) => {
|
||||
const format = e.target.value as ExportFormat;
|
||||
const wide = format === 'jpeg' || format === 'tiff16';
|
||||
patch({
|
||||
format,
|
||||
// PNG/WebP output can carry converted pixels but no ICC tag, so
|
||||
// keep those formats in the tagged sRGB default.
|
||||
...(wide ? {} : { colorSpace: 'srgb' as OutputColorSpace }),
|
||||
// Watermarking needs an 8-bit canvas pass; keep the option off
|
||||
// rather than silently downgrading the 16-bit file.
|
||||
...(format === 'tiff16' ? { watermark: { ...opts.watermark, enabled: false } } : {}),
|
||||
@@ -435,6 +441,20 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
|
||||
<div className="subhead">
|
||||
<span>Output</span>
|
||||
</div>
|
||||
<label className="field">
|
||||
<span>Colour space</span>
|
||||
<select
|
||||
value={opts.colorSpace ?? 'srgb'}
|
||||
onChange={(e) => patch({ colorSpace: e.target.value as OutputColorSpace })}
|
||||
disabled={busy || (opts.format !== 'jpeg' && opts.format !== 'tiff16')}
|
||||
>
|
||||
{COLOR_SPACE_OPTIONS.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<Slider
|
||||
label="Output sharpening"
|
||||
min={0}
|
||||
@@ -460,7 +480,7 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
|
||||
onChange={(e) => patch({ embedProfile: e.target.checked })}
|
||||
disabled={opts.format === 'webp' || opts.format === 'png'}
|
||||
/>
|
||||
Embed sRGB profile (JPEG/TIFF)
|
||||
Embed {COLOR_SPACE_OPTIONS.find((option) => option.value === (opts.colorSpace ?? 'srgb'))?.label ?? 'sRGB'} profile (JPEG/TIFF)
|
||||
</label>
|
||||
|
||||
<div className="subhead">
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { publishImmichOriginal } from '../lib/api';
|
||||
import type { CloudImport, ImportProgress } from '../lib/import';
|
||||
import { importFiles, isSupportedFile } from '../lib/import';
|
||||
import { isRawFile, RAW_ACCEPT } from '../lib/raw';
|
||||
@@ -13,6 +14,9 @@ interface Props {
|
||||
onClose: () => void;
|
||||
onImported: (photos: PhotoRecord[], eventId: string) => void;
|
||||
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;
|
||||
onNeedServer: () => void;
|
||||
}
|
||||
@@ -25,6 +29,8 @@ export default function ImportModal({
|
||||
onClose,
|
||||
onImported,
|
||||
onCreateEvent,
|
||||
immichEnabled = false,
|
||||
onCreateImmichGallery,
|
||||
cloud,
|
||||
onNeedServer,
|
||||
}: Props) {
|
||||
@@ -37,11 +43,16 @@ export default function ImportModal({
|
||||
const [progress, setProgress] = useState<ImportProgress | null>(null);
|
||||
const [failures, setFailures] = useState<string[]>([]);
|
||||
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<{
|
||||
imported: number;
|
||||
failed: number;
|
||||
skipped: number;
|
||||
cancelled: boolean;
|
||||
published: number;
|
||||
publishFailed: number;
|
||||
} | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(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));
|
||||
|
||||
useEffect(() => {
|
||||
setGalleryCreated(false);
|
||||
setGalleryError(null);
|
||||
setCreateGallery(immichEnabled);
|
||||
}, [eventId, immichEnabled]);
|
||||
|
||||
useEffect(() => {
|
||||
// Capture phase: Escape closes this dialog even while a photo is open behind it.
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
@@ -91,16 +108,67 @@ export default function ImportModal({
|
||||
const created = await onCreateEvent(newName || `Event ${new Date().toLocaleDateString()}`);
|
||||
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);
|
||||
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;
|
||||
setSummary({
|
||||
imported: result.photos.length,
|
||||
failed: result.failed.length,
|
||||
skipped,
|
||||
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) {
|
||||
setFailures([err instanceof Error ? err.message : 'Import failed']);
|
||||
} finally {
|
||||
@@ -152,6 +220,45 @@ export default function ImportModal({
|
||||
</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'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
|
||||
className={`dropzone ${dragOver ? 'over' : ''}`}
|
||||
onDragOver={(e) => {
|
||||
@@ -260,18 +367,25 @@ export default function ImportModal({
|
||||
{summary.imported} imported
|
||||
{summary.skipped ? ` · ${summary.skipped} duplicate${summary.skipped === 1 ? '' : 's'} skipped` : ''}
|
||||
{summary.failed ? ` · ${summary.failed} failed` : ''}
|
||||
{summary.published ? ` · ${summary.published} added to Immich` : ''}
|
||||
{summary.publishFailed
|
||||
? ` · ${summary.publishFailed} Immich upload${summary.publishFailed === 1 ? '' : 's'} failed`
|
||||
: ''}
|
||||
</span>
|
||||
<p className="muted small">
|
||||
{summary.cancelled
|
||||
? '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.'}
|
||||
{summary.published
|
||||
? ' The imported photos were added to the event\'s Immich gallery.'
|
||||
: ''}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{failures.length > 0 && (
|
||||
<div className="failures">
|
||||
<strong>Some files could not be imported</strong>
|
||||
<strong>Some files had problems</strong>
|
||||
<ul>
|
||||
{failures.map((f) => (
|
||||
<li key={f}>{f}</li>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
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 type { ColorLabel, Flag, PhotoRecord } from '../types';
|
||||
import Stars, { ColorSwatches, FlagButtons } from './Stars';
|
||||
import EditedImage from './EditedImage';
|
||||
|
||||
interface Props {
|
||||
photos: PhotoRecord[];
|
||||
@@ -15,12 +16,17 @@ interface Props {
|
||||
onBulkRate: (rating: number) => void;
|
||||
onBulkFlag: (flag: Flag) => void;
|
||||
onBulkColor: (color: ColorLabel) => void;
|
||||
onSendToImmich?: () => void;
|
||||
immichBusy?: boolean;
|
||||
onDelete: () => void;
|
||||
onExport: () => void;
|
||||
onCompare: () => void;
|
||||
onStack: () => void;
|
||||
onVirtualCopy: () => void;
|
||||
onMerge: () => void;
|
||||
/** Re-decode the selected RAW files with the server's current pipeline. */
|
||||
onReprocessRaw?: () => void;
|
||||
reprocessBusy?: boolean;
|
||||
onPrint: () => void;
|
||||
stacks: Map<string, { count: number; expanded: boolean }>;
|
||||
onToggleStack: (id: string) => void;
|
||||
@@ -51,12 +57,16 @@ export default function LibraryGrid({
|
||||
onBulkRate,
|
||||
onBulkFlag,
|
||||
onBulkColor,
|
||||
onSendToImmich,
|
||||
immichBusy = false,
|
||||
onDelete,
|
||||
onExport,
|
||||
onCompare,
|
||||
onStack,
|
||||
onVirtualCopy,
|
||||
onMerge,
|
||||
onReprocessRaw,
|
||||
reprocessBusy = false,
|
||||
onPrint,
|
||||
stacks,
|
||||
onToggleStack,
|
||||
@@ -277,6 +287,26 @@ export default function LibraryGrid({
|
||||
<button className="btn ghost small" onClick={onMerge} disabled={selected.length < 2}>
|
||||
Merge
|
||||
</button>
|
||||
{onReprocessRaw && (
|
||||
<button
|
||||
className="btn ghost small"
|
||||
onClick={onReprocessRaw}
|
||||
disabled={reprocessBusy}
|
||||
title="Re-decode the selected RAW files with the current pipeline settings"
|
||||
>
|
||||
{reprocessBusy ? 'Reprocessing…' : 'Reprocess RAW'}
|
||||
</button>
|
||||
)}
|
||||
{onSendToImmich && (
|
||||
<button
|
||||
className="btn ghost small"
|
||||
onClick={onSendToImmich}
|
||||
disabled={immichBusy}
|
||||
title="Send rendered edits for this selection to Immich"
|
||||
>
|
||||
Send to Immich
|
||||
</button>
|
||||
)}
|
||||
<button className="btn ghost small" onClick={onExport}>
|
||||
Export
|
||||
</button>
|
||||
@@ -429,13 +459,7 @@ export default function LibraryGrid({
|
||||
}}
|
||||
>
|
||||
<div className="card-thumb">
|
||||
<img
|
||||
src={p.thumbUrl ?? p.thumb}
|
||||
alt={p.name}
|
||||
loading="lazy"
|
||||
draggable={false}
|
||||
style={{ transform: thumbTransform(p) }}
|
||||
/>
|
||||
<EditedImage photo={p} alt={p.name} />
|
||||
<div className="card-badges">
|
||||
{p.flag === 'pick' && <span className="badge pick">✓</span>}
|
||||
{p.flag === 'reject' && <span className="badge reject">✕</span>}
|
||||
|
||||
+766
-73
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { normalizeEdits } from '../lib/edits';
|
||||
import { getBitmap } from '../lib/images';
|
||||
import { get16BitSource, getBitmap } from '../lib/images';
|
||||
import { Renderer, rotatedBounds } from '../gl/renderer';
|
||||
import type { PhotoRecord, Preset } from '../types';
|
||||
|
||||
@@ -14,7 +14,8 @@ const CACHE_LIMIT = 900;
|
||||
const THUMB_EDGE = 200;
|
||||
|
||||
/** The crop is part of the key so a turn, straighten or flip refreshes the tiles. */
|
||||
const keyOf = (photoId: string, presetId: string, crop: string) => `${photoId}|${presetId}|${crop}`;
|
||||
const keyOf = (photoId: string, presetId: string, crop: string, source: string) =>
|
||||
`${photoId}|${presetId}|${crop}|${source}`;
|
||||
|
||||
export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<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 crop = photo.edits.crop;
|
||||
const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(',');
|
||||
// The preset previews keep the photo's camera profile, so a reprocess or a
|
||||
// different profile has to invalidate tiles the same way a crop does.
|
||||
const profile = photo.edits.cameraProfile;
|
||||
const sourceKey = `${photo.previewVersion ?? 0}|${profile ? profile.matrix.join(',') : ''}`;
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
@@ -31,7 +36,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
|
||||
|
||||
const known: Record<string, string> = {};
|
||||
for (const preset of presets) {
|
||||
const hit = cache.get(keyOf(photo.id, preset.id, cropKey));
|
||||
const hit = cache.get(keyOf(photo.id, preset.id, cropKey, sourceKey));
|
||||
if (hit) known[preset.id] = hit;
|
||||
}
|
||||
setThumbs(known);
|
||||
@@ -43,6 +48,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
|
||||
try {
|
||||
const bitmap = await getBitmap(photo);
|
||||
if (!alive) return;
|
||||
const hdr = profile ? await get16BitSource(photo).catch(() => null) : null;
|
||||
renderer = new Renderer(canvas);
|
||||
// Every tile shows the photo as it is framed now, so a turned photo's
|
||||
// presets are turned too.
|
||||
@@ -52,18 +58,18 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
|
||||
const scale = THUMB_EDGE / Math.max(cropW, cropH);
|
||||
const width = Math.max(1, Math.round(cropW * scale));
|
||||
const height = Math.max(1, Math.round(cropH * scale));
|
||||
renderer.setImage(bitmap);
|
||||
renderer.setImage(bitmap, hdr);
|
||||
|
||||
for (const preset of pending) {
|
||||
if (!alive) break;
|
||||
try {
|
||||
renderer.render({ ...normalizeEdits(preset.edits), crop }, {
|
||||
renderer.render({ ...normalizeEdits(preset.edits), crop, cameraProfile: profile }, {
|
||||
width,
|
||||
height,
|
||||
upscale: Math.max(width / cropW, height / cropH) > 1.05,
|
||||
});
|
||||
const url = canvas.toDataURL('image/jpeg', 0.72);
|
||||
cache.set(keyOf(photo.id, preset.id, cropKey), url);
|
||||
cache.set(keyOf(photo.id, preset.id, cropKey, sourceKey), url);
|
||||
setThumbs((prev) => ({ ...prev, [preset.id]: url }));
|
||||
} catch {
|
||||
// One bad preset must not stop the rest of the grid.
|
||||
@@ -85,7 +91,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
|
||||
renderer?.dispose();
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [photo.id, presetKey, cropKey]);
|
||||
}, [photo.id, presetKey, cropKey, sourceKey]);
|
||||
|
||||
return thumbs;
|
||||
}
|
||||
|
||||
@@ -3,9 +3,11 @@ import {
|
||||
addGalleryComment,
|
||||
galleryDownloadAllUrl,
|
||||
galleryDownloadUrl,
|
||||
getGalleryStatus,
|
||||
loadGallery,
|
||||
setGalleryPick,
|
||||
setGalleryReview,
|
||||
unlockGallery,
|
||||
} from '../lib/api';
|
||||
import type { GalleryPayload, GalleryPhoto } from '../lib/api';
|
||||
|
||||
@@ -74,9 +76,22 @@ export default function ProofingGallery({ token }: { token: string }) {
|
||||
const [saving, setSaving] = useState<Set<string>>(new Set());
|
||||
const [commentDraft, setCommentDraft] = useState('');
|
||||
const [feedbackBusy, setFeedbackBusy] = useState(false);
|
||||
const [locked, setLocked] = useState(false);
|
||||
const [password, setPassword] = useState('');
|
||||
const [unlocking, setUnlocking] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
// The status call is what turns a locked link into a password prompt
|
||||
// instead of a dead end: the gallery body is a 401 while locked.
|
||||
const status = await getGalleryStatus(token);
|
||||
if (status.locked) {
|
||||
setLocked(true);
|
||||
setData(null);
|
||||
setFatal(null);
|
||||
return;
|
||||
}
|
||||
setLocked(false);
|
||||
const payload = await loadGallery(token, identity.current.id);
|
||||
setData(payload);
|
||||
setPicks(new Set(payload.photos.filter((p) => p.mine).map((p) => p.id)));
|
||||
@@ -103,6 +118,21 @@ export default function ProofingGallery({ token }: { token: string }) {
|
||||
};
|
||||
}, [data]);
|
||||
|
||||
const unlock = async () => {
|
||||
if (unlocking || !password) return;
|
||||
setUnlocking(true);
|
||||
setError(null);
|
||||
try {
|
||||
await unlockGallery(token, password);
|
||||
setPassword('');
|
||||
await load();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'That password did not work');
|
||||
} finally {
|
||||
setUnlocking(false);
|
||||
}
|
||||
};
|
||||
|
||||
const rememberName = (name: string) => {
|
||||
setClientName(name);
|
||||
try {
|
||||
@@ -260,6 +290,38 @@ export default function ProofingGallery({ token }: { token: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
if (!data && locked) {
|
||||
return (
|
||||
<div className="proof">
|
||||
<div className="proof-splash proof-lock">
|
||||
<div className="logo large">Luminary</div>
|
||||
<h1>This gallery is private</h1>
|
||||
<p>Enter the password the photographer gave you.</p>
|
||||
<form
|
||||
className="proof-lock-form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void unlock();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
autoFocus
|
||||
autoComplete="current-password"
|
||||
placeholder="Gallery password"
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
<button className="btn primary" type="submit" disabled={!password || unlocking}>
|
||||
{unlocking ? 'Opening…' : 'Open gallery'}
|
||||
</button>
|
||||
</form>
|
||||
{error && <p className="proof-subtle">{error}</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return (
|
||||
<div className="proof">
|
||||
@@ -320,7 +382,7 @@ export default function ProofingGallery({ token }: { token: string }) {
|
||||
>
|
||||
My picks {pickedCount ? `(${pickedCount})` : ''}
|
||||
</button>
|
||||
{pickedCount > 0 && (
|
||||
{pickedCount > 0 && data.downloads?.allowed !== false && (
|
||||
<a
|
||||
className="btn ghost small"
|
||||
href={galleryDownloadAllUrl(token, identity.current.id)}
|
||||
@@ -419,9 +481,11 @@ export default function ProofingGallery({ token }: { token: string }) {
|
||||
<div className="proof-lb-bar">
|
||||
<div className="proof-lb-title">
|
||||
<span className="proof-lb-name">{lightboxPhoto.name}</span>
|
||||
<a className="btn ghost small" href={galleryDownloadUrl(token, lightboxPhoto.id)} download>
|
||||
Download
|
||||
</a>
|
||||
{data.downloads?.allowed !== false && (
|
||||
<a className="btn ghost small" href={galleryDownloadUrl(token, lightboxPhoto.id)} download>
|
||||
Download
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
className={`proof-lb-pick ${picks.has(lightboxPhoto.id) ? 'on' : ''}`}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { createShare, getShare, pushProof, revokeShare } from '../lib/api';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { createShare, getShare, pushProof, revokeShare, saveShareSettings } from '../lib/api';
|
||||
import type { ShareState } from '../lib/api';
|
||||
import { DEFAULT_EXPORT, renderPhotoBlob } from '../lib/export';
|
||||
import type { ExportOptions } from '../lib/export';
|
||||
import type { PhotoRecord } from '../types';
|
||||
import { Renderer } from '../gl/renderer';
|
||||
|
||||
interface Props {
|
||||
event: { id: string; name: string };
|
||||
@@ -50,6 +51,13 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
|
||||
const [published, setPublished] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [passwordDraft, setPasswordDraft] = useState('');
|
||||
const [expiryDraft, setExpiryDraft] = useState('');
|
||||
const [watermarkDraft, setWatermarkDraft] = useState('');
|
||||
const [downloadsOn, setDownloadsOn] = useState(true);
|
||||
const [capDraft, setCapDraft] = useState('0');
|
||||
const [savingSettings, setSavingSettings] = useState(false);
|
||||
const settingsLoaded = useRef(false);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
@@ -93,15 +101,44 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
|
||||
|
||||
const namesByPhoto = useMemo(() => new Map(photos.map((p) => [p.id, p.name])), [photos]);
|
||||
|
||||
const publishProofs = async () => {
|
||||
// Seeded once: the 20-second refresh must not overwrite fields being typed.
|
||||
useEffect(() => {
|
||||
const saved = share?.settings;
|
||||
if (!saved || settingsLoaded.current) return;
|
||||
settingsLoaded.current = true;
|
||||
setExpiryDraft(saved.expiresAt ? new Date(saved.expiresAt).toISOString().slice(0, 10) : '');
|
||||
setWatermarkDraft(saved.watermark ?? '');
|
||||
setDownloadsOn(saved.allowDownloads !== false);
|
||||
setCapDraft(String(saved.downloadCap || 0));
|
||||
}, [share]);
|
||||
|
||||
const publishProofs = async (watermark = share?.settings?.watermark ?? '') => {
|
||||
if (!photos.length || publishing) return 0;
|
||||
// The gallery watermark is baked into the published proof, so the
|
||||
// downloadable file carries it too — not just the on-screen overlay.
|
||||
const proofExport: ExportOptions = {
|
||||
...PROOF_EXPORT,
|
||||
watermark: {
|
||||
...PROOF_EXPORT.watermark,
|
||||
enabled: Boolean(watermark.trim()),
|
||||
text: watermark.trim(),
|
||||
},
|
||||
};
|
||||
setPublishing(true);
|
||||
setPublished(0);
|
||||
setError(null);
|
||||
let done = 0;
|
||||
// One context and one shader compile for the whole batch: a proof run over
|
||||
// an event would otherwise create and tear down a renderer per photo.
|
||||
let shared: Renderer | null = null;
|
||||
try {
|
||||
shared = new Renderer(document.createElement('canvas'));
|
||||
} catch {
|
||||
shared = null;
|
||||
}
|
||||
try {
|
||||
for (const photo of photos) {
|
||||
const blob = await renderPhotoBlob(photo, PROOF_EXPORT);
|
||||
const blob = await renderPhotoBlob(photo, proofExport, shared ?? undefined);
|
||||
const result = await pushProof(photo.id, await proofBase64(blob));
|
||||
onProofPublished?.(photo.id, result.thumbUrl, result.proofAt);
|
||||
done += 1;
|
||||
@@ -113,6 +150,7 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
|
||||
setError(err instanceof Error ? err.message : 'Could not publish the edited proofs');
|
||||
return done;
|
||||
} finally {
|
||||
shared?.dispose();
|
||||
setPublishing(false);
|
||||
}
|
||||
};
|
||||
@@ -122,9 +160,10 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
|
||||
setError(null);
|
||||
try {
|
||||
await createShare(event.id);
|
||||
await refresh();
|
||||
const state = await getShare(event.id);
|
||||
setShare(state);
|
||||
// A gallery without rendered proofs would show the unedited originals.
|
||||
await publishProofs();
|
||||
await publishProofs(state.settings?.watermark ?? '');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Could not create the link');
|
||||
} finally {
|
||||
@@ -144,6 +183,28 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
|
||||
}
|
||||
};
|
||||
|
||||
const saveSettings = async (password?: string) => {
|
||||
if (savingSettings) return;
|
||||
setSavingSettings(true);
|
||||
setError(null);
|
||||
try {
|
||||
const settings = await saveShareSettings(event.id, {
|
||||
...(password === undefined ? {} : { password }),
|
||||
expiresAt: expiryDraft ? new Date(`${expiryDraft}T23:59:59`).getTime() : null,
|
||||
watermark: watermarkDraft.trim(),
|
||||
allowDownloads: downloadsOn,
|
||||
downloadCap: Math.max(0, Math.round(Number(capDraft) || 0)),
|
||||
});
|
||||
setShare((prev) => (prev ? { ...prev, settings } : prev));
|
||||
setPasswordDraft('');
|
||||
onToast(password === '' ? 'Gallery password removed' : 'Gallery settings saved');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Could not save the gallery settings');
|
||||
} finally {
|
||||
setSavingSettings(false);
|
||||
}
|
||||
};
|
||||
|
||||
const revoke = async () => {
|
||||
if (!window.confirm('Turn off this proofing link? Anyone using it will lose access and its picks will be cleared.')) {
|
||||
return;
|
||||
@@ -212,6 +273,91 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="share-settings">
|
||||
<div className="share-picks-head">
|
||||
<span>Access and delivery</span>
|
||||
<span className="muted small">
|
||||
{share.settings?.passwordSet ? 'Password protected' : 'Anyone with the link'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="share-settings-grid">
|
||||
<label>
|
||||
<span>Password</span>
|
||||
<input
|
||||
type="password"
|
||||
value={passwordDraft}
|
||||
autoComplete="new-password"
|
||||
placeholder={
|
||||
share.settings?.passwordSet ? 'Set — type a new one' : 'Optional'
|
||||
}
|
||||
onChange={(e) => setPasswordDraft(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
<span>Expires</span>
|
||||
<input
|
||||
type="date"
|
||||
value={expiryDraft}
|
||||
onChange={(e) => setExpiryDraft(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
<span>Download cap</span>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
step={1}
|
||||
value={capDraft}
|
||||
onChange={(e) => setCapDraft(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="share-settings-wide">
|
||||
<span>Watermark on proofs</span>
|
||||
<input
|
||||
value={watermarkDraft}
|
||||
maxLength={80}
|
||||
placeholder="© Studio name"
|
||||
onChange={(e) => setWatermarkDraft(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="share-settings-actions">
|
||||
<button
|
||||
className={`chip tiny ${downloadsOn ? 'on' : ''}`}
|
||||
onClick={() => setDownloadsOn((v) => !v)}
|
||||
title="Let clients download their picks"
|
||||
>
|
||||
Downloads {downloadsOn ? 'on' : 'off'}
|
||||
</button>
|
||||
<span className="muted small">
|
||||
Cap 0 means unlimited · {share.settings?.downloadCount ?? 0} used
|
||||
</span>
|
||||
<div className="spacer" />
|
||||
{share.settings?.passwordSet && (
|
||||
<button
|
||||
className="btn ghost small"
|
||||
disabled={savingSettings}
|
||||
onClick={() => void saveSettings('')}
|
||||
>
|
||||
Remove password
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="btn primary small"
|
||||
disabled={savingSettings}
|
||||
onClick={() =>
|
||||
void saveSettings(passwordDraft.trim() ? passwordDraft.trim() : undefined)
|
||||
}
|
||||
>
|
||||
{savingSettings ? 'Saving…' : 'Save settings'}
|
||||
</button>
|
||||
</div>
|
||||
<p className="muted small">
|
||||
Expiry closes the link at the end of that day. The watermark is rendered into
|
||||
freshly published proofs; republish after changing it.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="share-publish">
|
||||
<div>
|
||||
<strong>Edited proofs</strong>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
+44
-13
@@ -2,14 +2,17 @@ import type { LocalLayer } from '../types';
|
||||
import { MAX_LOCAL_LAYERS } from '../lib/edits';
|
||||
|
||||
/**
|
||||
* Local masks are baked on the CPU into one RGBA texture, one layer per
|
||||
* channel, so the grade shader can apply up to four adjustments in a single
|
||||
* Local masks are baked on the CPU into two RGBA textures, one layer per
|
||||
* channel, so the grade shader can apply up to eight adjustments in a single
|
||||
* pass. The mask is source-space, which keeps brushes and gradients attached to
|
||||
* the picture through crops, straightening, zoom and lens correction.
|
||||
*/
|
||||
|
||||
export interface PackedMasks {
|
||||
/** Layers 1–4, one per channel. */
|
||||
data: Uint8Array;
|
||||
/** Layers 5–8, one per channel. */
|
||||
data2: Uint8Array;
|
||||
w: number;
|
||||
h: number;
|
||||
}
|
||||
@@ -131,12 +134,34 @@ function drawBrush(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number,
|
||||
ctx.globalCompositeOperation = 'source-over';
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number): PackedMasks {
|
||||
const w = 800;
|
||||
const h = Math.max(120, Math.min(1400, Math.round((w * Math.max(1, srcH)) / Math.max(1, srcW))));
|
||||
const out = new Uint8Array(w * h * 4);
|
||||
const out2 = new Uint8Array(w * h * 4);
|
||||
const count = Math.min(MAX_LOCAL_LAYERS, layers.length);
|
||||
if (!count) return { data: out, w, h };
|
||||
if (!count) return { data: out, data2: out2, w, h };
|
||||
|
||||
for (let index = 0; index < count; index++) {
|
||||
const layer = layers[index];
|
||||
@@ -151,24 +176,30 @@ export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number
|
||||
else drawBrush(ctx, layer, w, h);
|
||||
|
||||
let source = canvas;
|
||||
if ((layer.kind === 'brush' || layer.kind === 'raster') && layer.feather > 0) {
|
||||
const blur = makeCanvas(w, h);
|
||||
const bctx = blur.getContext('2d');
|
||||
if (bctx) {
|
||||
bctx.filter = `blur(${Math.max(0.1, ((layer.feather / 100) * w) / 16)}px)`;
|
||||
bctx.drawImage(canvas, 0, 0);
|
||||
source = blur;
|
||||
if (layer.kind === 'brush') {
|
||||
// Feather follows the brush, not the frame: 100% softens the edge by
|
||||
// roughly three quarters of the stroke's half width, so a small dab and a
|
||||
// wide sweep both feel the same under the slider.
|
||||
let widest = 0;
|
||||
for (const stroke of layer.brush.strokes) {
|
||||
widest = Math.max(widest, stroke.size * 2 * w);
|
||||
}
|
||||
source = featherMask(canvas, (layer.feather / 100) * widest * 0.75);
|
||||
} else if (layer.kind === 'raster') {
|
||||
// Generated masks are low-resolution coverage, so their feather is tied
|
||||
// to the frame width and only ever loosens the outside edge.
|
||||
source = featherMask(canvas, ((layer.feather / 100) * w) / 16);
|
||||
}
|
||||
|
||||
const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data;
|
||||
if (!pixels) continue;
|
||||
const channel = index;
|
||||
const channel = index % 4;
|
||||
const target = index < 4 ? out : out2;
|
||||
for (let p = 0, o = 0; p < pixels.length; p += 4, o += 4) {
|
||||
const alpha = pixels[p + 3];
|
||||
out[o + channel] = layer.inverted ? 255 - alpha : alpha;
|
||||
target[o + channel] = layer.inverted ? 255 - alpha : alpha;
|
||||
}
|
||||
}
|
||||
|
||||
return { data: out, w, h };
|
||||
return { data: out, data2: out2, w, h };
|
||||
}
|
||||
|
||||
+500
-128
@@ -1,8 +1,11 @@
|
||||
import type { LensCorrection } from '../lib/lensfun';
|
||||
import type { LensCorrection } from '../lib/lensEngine';
|
||||
import type { Preview16 } from '../lib/preview16';
|
||||
import type { Edits, GeometryEdits } from '../types';
|
||||
import { buildSampler, clamp01 } from '../lib/curves';
|
||||
import { bwFilterRgb, MAX_HEAL_SPOTS, MAX_LOCAL_LAYERS } from '../lib/edits';
|
||||
import { wbGainFor } from '../lib/whiteBalance';
|
||||
import { buildLocalMasks, maskSignature } from './masks';
|
||||
import { getActiveProofCube, type SoftProofCube } from '../lib/softProof';
|
||||
|
||||
const VERT = `#version 300 es
|
||||
layout(location = 0) in vec2 a_pos;
|
||||
@@ -34,8 +37,12 @@ uniform float u_upscale;
|
||||
/** Explicit source mip level: 0 at 1:1 or magnification, log2(scale) when shrinking. */
|
||||
uniform float u_srcLod;
|
||||
|
||||
uniform float u_temp;
|
||||
uniform float u_tint;
|
||||
// Camera-native surrogate: the 16-bit sidecar holds the sensor's own RGB, and
|
||||
// this matrix takes it to linear sRGB. Zero for ordinary sRGB proxies.
|
||||
uniform mat3 u_srcCam;
|
||||
uniform float u_srcMatrix;
|
||||
|
||||
uniform vec3 u_wbGain;
|
||||
uniform float u_exposure;
|
||||
uniform float u_recovery;
|
||||
uniform float u_contrast;
|
||||
@@ -45,6 +52,7 @@ uniform float u_whites;
|
||||
uniform float u_blacks;
|
||||
uniform float u_vibrance;
|
||||
uniform float u_saturation;
|
||||
uniform float u_redscale;
|
||||
uniform float u_bw;
|
||||
uniform vec3 u_bwFilter;
|
||||
uniform float u_bwFilterAmt;
|
||||
@@ -65,13 +73,15 @@ uniform vec4 u_healSpot[24];
|
||||
// x = radius as a fraction of the source width, y = feather (0–1).
|
||||
uniform vec2 u_healSize[24];
|
||||
|
||||
// Local adjustments: four masks packed into one RGBA texture.
|
||||
uniform sampler2D u_masks;
|
||||
// Local adjustments: eight masks packed into two RGBA textures.
|
||||
uniform sampler2D u_masks; // layers 1-4
|
||||
uniform sampler2D u_masks2; // layers 5-8
|
||||
uniform int u_localCount;
|
||||
uniform vec4 u_localAdj[4]; // exposure, contrast, temp, tint
|
||||
uniform vec4 u_localAdj2[4]; // saturation, highlights, shadows, unused
|
||||
uniform vec4 u_localRange[4]; // lumaMin, lumaMax, hue, hueRange
|
||||
uniform vec4 u_localRange2[4]; // satMin, enabled, unused, unused
|
||||
uniform vec4 u_localAdj[8]; // exposure, contrast, temp, tint
|
||||
uniform vec4 u_localAdj2[8]; // saturation, highlights, shadows, unused
|
||||
uniform vec4 u_localAdj3[8]; // whites, blacks, vibrance, hue degrees
|
||||
uniform vec4 u_localRange[8]; // lumaMin, lumaMax, hue, hueRange
|
||||
uniform vec4 u_localRange2[8]; // satMin, enabled, unused, unused
|
||||
|
||||
// Lens/perspective correction: distortion, vertical, horizontal, rotation.
|
||||
uniform vec4 u_geom;
|
||||
@@ -117,6 +127,15 @@ vec3 toSRGB(vec3 c){
|
||||
return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));
|
||||
}
|
||||
|
||||
// Camera-native proxies keep the sensor's gamma-encoded RGB so the matrix stays
|
||||
// swappable (a camera profile is just a different matrix). Decode, convert,
|
||||
// re-encode: every stage below keeps working on sRGB numbers.
|
||||
vec3 decodeSource(vec3 c){
|
||||
if (u_srcMatrix < 0.5) return c;
|
||||
vec3 linear = u_srcCam * toLinear(clamp(c, 0.0, 1.0));
|
||||
return clamp(toSRGB(max(linear, vec3(0.0))), 0.0, 1.0);
|
||||
}
|
||||
|
||||
vec3 rgb2hsv(vec3 c){
|
||||
vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
|
||||
vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
|
||||
@@ -132,6 +151,79 @@ vec3 hsv2rgb(vec3 c){
|
||||
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
|
||||
}
|
||||
|
||||
// OkLab (Björn Ottosson). Hue and chroma are much closer to perception than
|
||||
// HSV, so rotating a hue band or lifting saturation no longer drags luminance
|
||||
// with it, which is what made strong HSL edits look plasticky.
|
||||
vec3 linearToOkLab(vec3 c){
|
||||
float l = 0.4122214708 * c.r + 0.5363325363 * c.g + 0.0514459929 * c.b;
|
||||
float m = 0.2119034982 * c.r + 0.6806995451 * c.g + 0.1073969566 * c.b;
|
||||
float s = 0.0883024619 * c.r + 0.2817188376 * c.g + 0.6299787005 * c.b;
|
||||
l = pow(max(l, 0.0), 1.0 / 3.0);
|
||||
m = pow(max(m, 0.0), 1.0 / 3.0);
|
||||
s = pow(max(s, 0.0), 1.0 / 3.0);
|
||||
return vec3(
|
||||
0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s,
|
||||
1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
|
||||
0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s
|
||||
);
|
||||
}
|
||||
|
||||
vec3 okLabToLinear(vec3 c){
|
||||
float l = c.x + 0.3963377774 * c.y + 0.2158037573 * c.z;
|
||||
float m = c.x - 0.1055613458 * c.y - 0.0638541728 * c.z;
|
||||
float s = c.x - 0.0894841775 * c.y - 1.2914855480 * c.z;
|
||||
l = l * l * l;
|
||||
m = m * m * m;
|
||||
s = s * s * s;
|
||||
return vec3(
|
||||
4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
|
||||
-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
|
||||
-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s
|
||||
);
|
||||
}
|
||||
|
||||
// Hue rotation, chroma scale and lightness scale in OkLCh. Vibrance is applied
|
||||
// as a chroma boost that is strongest where chroma is already low.
|
||||
vec3 applyHslVibrance(vec3 srgb, float hueDeg, float satScale, float lightScale, float vibrance){
|
||||
vec3 lab = linearToOkLab(toLinear(clamp(srgb, 0.0, 1.0)));
|
||||
float C = length(lab.yz);
|
||||
float h = atan(lab.z, lab.y) + radians(hueDeg);
|
||||
float vib = 1.0 + (vibrance / 100.0) * 0.9 * (1.0 - clamp(C / 0.22, 0.0, 1.0));
|
||||
C = clamp(C * satScale * vib, 0.0, 0.4);
|
||||
lab.x = clamp(lab.x * lightScale, 0.0, 1.25);
|
||||
lab.y = C * cos(h);
|
||||
lab.z = C * sin(h);
|
||||
return clamp(toSRGB(max(okLabToLinear(lab), 0.0)), 0.0, 1.0);
|
||||
}
|
||||
|
||||
// Multiplicative tone controls. Adding a constant in linear light shifts hue
|
||||
// and cannot set a true black point; a luminance-shaped gain brightens or
|
||||
// darkens without turning shadows grey or highlights magenta.
|
||||
vec3 perceptualGain(float lm, float shadows, float highlights, float whites, float blacks){
|
||||
float sm = smoothstep(0.0, 0.12, lm) * pow(1.0 - lm, 3.0);
|
||||
float hm = pow(lm, 2.0);
|
||||
float wm = smoothstep(0.55, 1.0, lm);
|
||||
float bm = smoothstep(0.30, 0.0, lm);
|
||||
float g = 1.0
|
||||
+ (shadows / 100.0) * 0.85 * sm
|
||||
+ (highlights / 100.0) * 0.70 * hm
|
||||
+ (whites / 100.0) * 0.50 * wm
|
||||
+ (blacks / 100.0) * 0.32 * bm;
|
||||
return vec3(max(0.0, g));
|
||||
}
|
||||
|
||||
// Pushes the shoulder down as a whole and keeps the channel ratios, so a
|
||||
// recovered highlight stays the colour it was instead of turning grey.
|
||||
vec3 compressHighlights(vec3 c, float rec){
|
||||
float m = max(c.r, max(c.g, c.b));
|
||||
float knee = 0.78;
|
||||
if (m > knee && rec > 0.001) {
|
||||
float pulled = knee + (m - knee) / (1.0 + (m - knee) * (2.0 + 12.0 * rec));
|
||||
c *= mix(1.0, pulled / m, rec);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
// Catmull-Rom weights for one axis; t is the fraction inside a texel.
|
||||
vec4 cubicWeights(float t){
|
||||
float t2 = t * t;
|
||||
@@ -192,7 +284,7 @@ void main(){
|
||||
// view is zoomed out or the window aspect differs from the photo.
|
||||
if (frame.x < u_valid.x || frame.y < u_valid.y ||
|
||||
frame.x > u_valid.x + u_valid.z || frame.y > u_valid.y + u_valid.w) {
|
||||
outColor = vec4(0.035, 0.035, 0.04, 1.0);
|
||||
outColor = vec4(0.035, 0.035, 0.04, 0.0);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -208,7 +300,7 @@ void main(){
|
||||
}
|
||||
|
||||
if (s.x < 0.0 || s.x > 1.0 || s.y < 0.0 || s.y > 1.0) {
|
||||
outColor = vec4(0.035, 0.035, 0.04, 1.0);
|
||||
outColor = vec4(0.035, 0.035, 0.04, 0.0);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -242,19 +334,10 @@ void main(){
|
||||
src *= lensSample(u_lensVig, u_lensVigSize, lensQ).rgb;
|
||||
}
|
||||
|
||||
// The denoised proxy is the same frame as the source, so it samples at the
|
||||
// same coordinate and is mixed in before white balance and tone. Grading the
|
||||
// blend rather than the source keeps the edit looking identical with the
|
||||
// denoise at 0 and at 100.
|
||||
if (u_denMix > 0.0) {
|
||||
src = mix(src, textureLod(u_den, uv, u_srcLod).rgb, u_denMix);
|
||||
}
|
||||
|
||||
// Eyedropper: hand back the untouched source colour at the sampled point.
|
||||
if (u_pick > 0.5) {
|
||||
outColor = vec4(src, 1.0);
|
||||
return;
|
||||
}
|
||||
// Camera-native proxies are converted once, before the source is read any
|
||||
// further: the frame, the healed patches and the eyedropper all work on the
|
||||
// same sRGB values whatever the camera matrix was.
|
||||
src = decodeSource(src);
|
||||
|
||||
// Spot healing copies a clean patch over the blemish, feathered at the rim.
|
||||
// It runs on the source colour, before white balance and tone, so a healed
|
||||
@@ -279,41 +362,56 @@ void main(){
|
||||
? 1.0 - smoothstep(1.0 - feather, 1.0, dist)
|
||||
: 1.0;
|
||||
vec2 patchUv = clamp(uv + (spot.zw - spot.xy), vec2(0.0), vec2(1.0));
|
||||
src = mix(src, textureLod(u_src, patchUv, u_srcLod).rgb, falloff);
|
||||
src = mix(src, decodeSource(textureLod(u_src, patchUv, u_srcLod).rgb), falloff);
|
||||
}
|
||||
}
|
||||
|
||||
// Eyedropper: hand back the untouched source colour at the sampled point.
|
||||
if (u_pick > 0.5) {
|
||||
outColor = vec4(src, 1.0);
|
||||
return;
|
||||
}
|
||||
|
||||
// The denoised proxy is the same frame as the source, at the same coordinate.
|
||||
// It is generated from the JPEG and is already sRGB, so it is blended after
|
||||
// the camera conversion. Grading the blend rather than the source keeps the
|
||||
// edit looking identical with the denoise at 0 and at 100.
|
||||
if (u_denMix > 0.0) {
|
||||
src = mix(src, textureLod(u_den, uv, u_srcLod).rgb, u_denMix);
|
||||
}
|
||||
|
||||
vec3 col = toLinear(clamp(src, 0.0, 1.0));
|
||||
|
||||
// White balance (relative to as-shot)
|
||||
float t = u_temp / 100.0;
|
||||
float ti = u_tint / 100.0;
|
||||
vec3 wb = vec3(1.0 + 0.30 * t + 0.06 * ti, 1.0 - 0.16 * ti, 1.0 - 0.26 * t + 0.06 * ti);
|
||||
col *= wb / max(0.05, luma(wb));
|
||||
// White balance gains, solved on the CPU: either the relative Temp offset or
|
||||
// the absolute Kelvin control, both normalised so exposure is unchanged.
|
||||
col *= u_wbGain;
|
||||
|
||||
// Redscale: colour film respooled backwards, exposed through its base. The
|
||||
// red-sensitive layer is hit first, green gets what passes through, and blue
|
||||
// is almost entirely absorbed by the base and mask -- hence red shadows and
|
||||
// amber/yellow highlights. The matrix encodes that layer order; dividing by
|
||||
// the neutral response keeps a midtone at its original brightness instead of
|
||||
// looking underexposed by the light lost in the base.
|
||||
float rs = clamp(u_redscale / 100.0, 0.0, 1.0);
|
||||
if (rs > 0.001) {
|
||||
vec3 baseCol = col;
|
||||
vec3 redscale = vec3(
|
||||
baseCol.r * 0.78 + baseCol.g * 0.32 + baseCol.b * 0.06,
|
||||
baseCol.r * 0.18 + baseCol.g * 0.34 + baseCol.b * 0.03,
|
||||
baseCol.r * 0.06 + baseCol.g * 0.04 + baseCol.b * 0.02
|
||||
) / 0.649;
|
||||
col = mix(baseCol, redscale, rs);
|
||||
}
|
||||
|
||||
// Exposure
|
||||
col *= exp2(u_exposure);
|
||||
|
||||
// Highlight recovery: compress the shoulder instead of clipping it. Scaling
|
||||
// every channel by one factor keeps hue, so recovered skin stays skin instead
|
||||
// of turning grey or yellow.
|
||||
float rec = clamp(u_recovery / 100.0, 0.0, 1.0);
|
||||
if (rec > 0.001) {
|
||||
float lum = max(luma(col), 1e-5);
|
||||
float knee = 0.7;
|
||||
float over = max(lum - knee, 0.0);
|
||||
if (over > 0.0) {
|
||||
float pulled = knee + over / (1.0 + over * (2.0 + 12.0 * rec));
|
||||
col *= mix(1.0, pulled / lum, rec);
|
||||
}
|
||||
}
|
||||
// Highlight recovery: compress the shoulder and keep the channel ratios.
|
||||
col = compressHighlights(col, clamp(u_recovery / 100.0, 0.0, 1.0));
|
||||
|
||||
// Tonal range
|
||||
// Tonal range, as luminance-shaped gains so hue survives strong moves.
|
||||
float lm = clamp(luma(col), 0.0, 1.0);
|
||||
col += (u_shadows / 100.0) * 0.45 * pow(1.0 - lm, 3.0);
|
||||
col += (u_highlights / 100.0) * 0.50 * pow(lm, 2.0);
|
||||
col += (u_whites / 100.0) * 0.34 * smoothstep(0.55, 1.0, lm);
|
||||
col += (u_blacks / 100.0) * 0.13 * smoothstep(0.30, 0.0, lm);
|
||||
col *= perceptualGain(lm, u_shadows, u_highlights, u_whites, u_blacks);
|
||||
|
||||
vec3 srgb = clamp(toSRGB(col), 0.0, 1.0);
|
||||
|
||||
@@ -327,7 +425,9 @@ void main(){
|
||||
texture(u_curve, vec2(clamp(srgb.b, 0.0, 1.0), 0.5)).b
|
||||
);
|
||||
|
||||
// HSL bands
|
||||
// HSL bands. The band weights still use sRGB hue (that is what the wheel and
|
||||
// the presets were authored against), but the shift itself happens in OkLCh,
|
||||
// where rotating hue does not also change perceived brightness.
|
||||
vec3 hsv = rgb2hsv(srgb);
|
||||
float hdeg = hsv.x * 360.0;
|
||||
float hueWeight = smoothstep(0.02, 0.18, hsv.y);
|
||||
@@ -349,11 +449,14 @@ void main(){
|
||||
sShift = sShift / norm;
|
||||
lShift = lShift / norm;
|
||||
|
||||
hsv.x = fract(hsv.x + (hShift / 100.0) * 0.08 + 1.0);
|
||||
float satMul = sShift >= 0.0 ? 1.0 + (sShift / 100.0) * 0.8 : 1.0 + sShift / 100.0;
|
||||
hsv.y = clamp(hsv.y * satMul, 0.0, 1.0);
|
||||
hsv.z = clamp(hsv.z * (1.0 + (lShift / 100.0) * 0.5), 0.0, 1.0);
|
||||
srgb = hsv2rgb(hsv);
|
||||
srgb = applyHslVibrance(
|
||||
srgb,
|
||||
(hShift / 100.0) * 28.8,
|
||||
satMul * max(0.0, 1.0 + u_saturation / 100.0),
|
||||
1.0 + (lShift / 100.0) * 0.35,
|
||||
u_vibrance
|
||||
);
|
||||
|
||||
if (u_bw > 0.5) {
|
||||
// A colored filter over the lens changes which hues turn dark in the print:
|
||||
@@ -364,15 +467,6 @@ void main(){
|
||||
srgb = vec3(luma(srgb * bwTint) / wl);
|
||||
}
|
||||
|
||||
// Vibrance and saturation
|
||||
vec3 satRgb = clamp(srgb, 0.0, 1.0);
|
||||
float mx = max(max(satRgb.r, satRgb.g), satRgb.b);
|
||||
float mn = min(min(satRgb.r, satRgb.g), satRgb.b);
|
||||
float curSat = mx - mn;
|
||||
float gray = luma(satRgb);
|
||||
srgb = mix(vec3(gray), satRgb, clamp(1.0 + (u_vibrance / 100.0) * (1.0 - curSat) * 0.9, 0.0, 3.0));
|
||||
srgb = mix(vec3(luma(srgb)), srgb, clamp(1.0 + u_saturation / 100.0, 0.0, 3.0));
|
||||
|
||||
// Color grading
|
||||
float gl = clamp(luma(srgb), 0.0, 1.0);
|
||||
float bal = u_gBal / 100.0;
|
||||
@@ -390,15 +484,22 @@ void main(){
|
||||
// are evaluated from the source colour so they follow skin, sky or shadow
|
||||
// regardless of how the global grade moved them.
|
||||
if (u_localCount > 0) {
|
||||
vec4 maskTexel = texture(u_masks, uv);
|
||||
vec4 maskA = texture(u_masks, uv);
|
||||
vec4 maskB = texture(u_masks2, uv);
|
||||
float srcLuma = luma(clamp(src, 0.0, 1.0));
|
||||
vec3 srcHsv = rgb2hsv(clamp(src, 0.0, 1.0));
|
||||
for (int i = 0; i < 4; i++) {
|
||||
// Mask algebra: 0 = add, 1 = subtract, 2 = intersect. Subtract and
|
||||
// intersect are relative to the layer above, like Lightroom's modes.
|
||||
float prevMask = 1.0;
|
||||
for (int i = 0; i < 8; i++) {
|
||||
if (i >= u_localCount) break;
|
||||
float m = i == 0 ? maskTexel.r : i == 1 ? maskTexel.g : i == 2 ? maskTexel.b : maskTexel.a;
|
||||
int k = i < 4 ? i : i - 4;
|
||||
vec4 texel = i < 4 ? maskA : maskB;
|
||||
float m = k == 0 ? texel.r : k == 1 ? texel.g : k == 2 ? texel.b : texel.a;
|
||||
if (m < 0.002) continue;
|
||||
vec4 adj = u_localAdj[i];
|
||||
vec4 adj2 = u_localAdj2[i];
|
||||
vec4 adj3 = u_localAdj3[i];
|
||||
vec4 range = u_localRange[i];
|
||||
vec4 range2 = u_localRange2[i];
|
||||
|
||||
@@ -414,6 +515,11 @@ void main(){
|
||||
float sw = smoothstep(range2.x - 0.02, range2.x + 0.02, srcHsv.y);
|
||||
m *= lw * hw * sw;
|
||||
}
|
||||
float rawMask = m;
|
||||
float localMode = adj2.w;
|
||||
if (localMode > 1.5) m = prevMask * rawMask;
|
||||
else if (localMode > 0.5) m = prevMask * (1.0 - rawMask);
|
||||
prevMask = rawMask;
|
||||
if (m < 0.002) continue;
|
||||
|
||||
vec3 lin = toLinear(clamp(srgb, 0.0, 1.0));
|
||||
@@ -422,17 +528,31 @@ void main(){
|
||||
float lti = adj.w / 100.0;
|
||||
vec3 lwb = vec3(1.0 + 0.30 * lt + 0.06 * lti, 1.0 - 0.16 * lti, 1.0 - 0.26 * lt + 0.06 * lti);
|
||||
lin *= lwb / max(0.05, luma(lwb));
|
||||
vec3 local = toSRGB(clamp(lin, 0.0, 1.0));
|
||||
vec3 local = clamp(toSRGB(max(lin, 0.0)), 0.0, 1.0);
|
||||
local = clamp((local - 0.5) * (1.0 + (adj.y / 100.0) * 1.1) + 0.5, 0.0, 1.0);
|
||||
float ll = clamp(luma(local), 0.0, 1.0);
|
||||
local += (adj2.z / 100.0) * 0.45 * pow(1.0 - ll, 3.0);
|
||||
local += (adj2.y / 100.0) * 0.50 * pow(ll, 2.0);
|
||||
local = mix(vec3(luma(local)), local, clamp(1.0 + adj2.x / 100.0, 0.0, 3.0));
|
||||
local = clamp(
|
||||
toSRGB(max(toLinear(local) * perceptualGain(ll, adj2.z, adj2.y, adj3.x, adj3.y), 0.0)),
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
local = applyHslVibrance(
|
||||
local,
|
||||
adj3.w,
|
||||
max(0.0, 1.0 + adj2.x / 100.0),
|
||||
1.0,
|
||||
adj3.z
|
||||
);
|
||||
srgb = mix(srgb, clamp(local, 0.0, 1.0), m);
|
||||
}
|
||||
}
|
||||
|
||||
outColor = vec4(clamp(srgb, 0.0, 1.0), 1.0);
|
||||
// Alpha carries the *source* clipping state to the finish pass, so the
|
||||
// warning reflects the pixels the sensor/proxy had, not the graded result.
|
||||
float clipFlag = 0.0;
|
||||
if (max(src.r, max(src.g, src.b)) >= 0.996) clipFlag += 0.5;
|
||||
if (min(src.r, min(src.g, src.b)) <= 0.004) clipFlag += 0.25;
|
||||
outColor = vec4(clamp(srgb, 0.0, 1.0), clipFlag);
|
||||
}`;
|
||||
|
||||
const BLUR_FRAG = `#version 300 es
|
||||
@@ -457,11 +577,20 @@ out vec4 outColor;
|
||||
uniform sampler2D u_graded;
|
||||
uniform sampler2D u_blurSmall;
|
||||
uniform sampler2D u_blurBig;
|
||||
// Local detail masks: shape only, one layer per channel, same packing as the
|
||||
// grade pass. Amounts are added to the global sliders per pixel.
|
||||
uniform sampler2D u_masks;
|
||||
uniform sampler2D u_masks2;
|
||||
uniform int u_localCount;
|
||||
uniform vec4 u_localDetail[8]; // texture, clarity, dehaze, sharpen
|
||||
uniform vec4 u_localModes[8]; // x = add / subtract / intersect
|
||||
uniform float u_texture;
|
||||
uniform float u_clarity;
|
||||
uniform float u_dehaze;
|
||||
uniform float u_sharpen;
|
||||
uniform float u_sharpenMask;
|
||||
uniform float u_sharpenDetail;
|
||||
uniform float u_nrDetail;
|
||||
uniform float u_detailScale;
|
||||
uniform float u_lensSoft;
|
||||
uniform float u_nr;
|
||||
@@ -489,6 +618,11 @@ uniform float u_proofEnable;
|
||||
uniform vec3 u_proofPaper;
|
||||
uniform float u_proofBlack;
|
||||
uniform float u_gamut;
|
||||
// Real ICC proof: a 3D table built from a printer profile, sRGB in and out.
|
||||
// Its alpha channel flags colours the printer cannot reach.
|
||||
// sampler3D has no default precision in GLSL ES 3.00, unlike sampler2D.
|
||||
uniform highp sampler3D u_proofLut;
|
||||
uniform float u_proofLutOn;
|
||||
|
||||
float luma(vec3 c){ return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
|
||||
|
||||
@@ -525,24 +659,61 @@ void main(){
|
||||
vec3 bs = texture(u_blurSmall, v_uv).rgb;
|
||||
vec3 bb = texture(u_blurBig, v_uv).rgb;
|
||||
|
||||
// Noise reduction blends towards a smoothed version first.
|
||||
// Local detail amounts: walk the same add/subtract/intersect algebra the
|
||||
// grade pass uses, then add the covered layer amounts to the global sliders.
|
||||
float localTexture = 0.0;
|
||||
float localClarity = 0.0;
|
||||
float localDehaze = 0.0;
|
||||
float localSharpen = 0.0;
|
||||
if (u_localCount > 0) {
|
||||
vec4 maskA = texture(u_masks, v_uv);
|
||||
vec4 maskB = texture(u_masks2, v_uv);
|
||||
float prevMask = 1.0;
|
||||
for (int i = 0; i < 8; i++) {
|
||||
if (i >= u_localCount) break;
|
||||
int k = i < 4 ? i : i - 4;
|
||||
vec4 texel = i < 4 ? maskA : maskB;
|
||||
float rawMask = k == 0 ? texel.r : k == 1 ? texel.g : k == 2 ? texel.b : texel.a;
|
||||
float m = rawMask;
|
||||
float mode = u_localModes[i].x;
|
||||
if (mode > 1.5) m = prevMask * rawMask;
|
||||
else if (mode > 0.5) m = prevMask * (1.0 - rawMask);
|
||||
prevMask = rawMask;
|
||||
if (m < 0.002) continue;
|
||||
localTexture += m * u_localDetail[i].x;
|
||||
localClarity += m * u_localDetail[i].y;
|
||||
localDehaze += m * u_localDetail[i].z;
|
||||
localSharpen += m * u_localDetail[i].w;
|
||||
}
|
||||
}
|
||||
float textureAmt = clamp(u_texture + localTexture, -200.0, 200.0);
|
||||
float clarityAmt = clamp(u_clarity + localClarity, -200.0, 200.0);
|
||||
float sharpTotal = clamp(u_sharpen + localSharpen, -100.0, 250.0);
|
||||
float dehazeAmt = clamp(u_dehaze + localDehaze, -200.0, 200.0);
|
||||
|
||||
// Noise reduction blends towards a smoothed version first. Detail controls
|
||||
// how strongly edges are protected from that smoothing.
|
||||
float nr = clamp(u_nr / 100.0, 0.0, 1.0);
|
||||
vec3 base = mix(c, mix(bs, bb, 0.5), nr * 0.6);
|
||||
float nrDetail = clamp(u_nrDetail / 100.0, 0.0, 1.0);
|
||||
float nrEdge = smoothstep(0.002, 0.02, length(c - bs));
|
||||
vec3 base = mix(c, mix(bs, bb, 0.5), nr * mix(1.0, nrEdge, nrDetail) * 0.6);
|
||||
|
||||
// Local contrast / detail work on gamma encoded values.
|
||||
vec3 detailSmall = c - bs;
|
||||
vec3 detailBig = base - bb;
|
||||
vec3 col = base;
|
||||
// Masking restricts sharpening to edges. Left at 0 the whole frame is
|
||||
// sharpened; raised, only differences large enough to be structure qualify,
|
||||
// so grain and skin texture stop picking up acutance.
|
||||
// Detail mixes the fine band (texture, pores, grain) with the broader band
|
||||
// (structure, local contrast), so the slider is a real control instead of a
|
||||
// stored value. Masking restricts sharpening to edges.
|
||||
float detailMix = clamp(u_sharpenDetail / 100.0, 0.0, 1.0);
|
||||
vec3 detailBand = mix(detailBig, detailSmall, detailMix);
|
||||
float sm = clamp(u_sharpenMask / 100.0, 0.0, 1.0);
|
||||
float sharpenAmt = (u_sharpen / 100.0) * 1.35;
|
||||
float sharpenAmt = (sharpTotal / 100.0) * 1.35;
|
||||
if (sm > 0.001) {
|
||||
float edge = smoothstep(0.003, 0.012 + sm * 0.085, length(detailSmall));
|
||||
float edge = smoothstep(0.003, 0.012 + sm * 0.085, length(detailBand));
|
||||
sharpenAmt *= mix(1.0, edge, sm);
|
||||
}
|
||||
col += detailSmall * ((u_texture / 100.0) * 0.9 + sharpenAmt);
|
||||
col += detailBand * ((textureAmt / 100.0) * 0.9 + sharpenAmt);
|
||||
// Lens softness compensation: add acutance towards the corners, where most
|
||||
// wide/normal lenses lose resolving power. It is deliberately edge-weighted
|
||||
// so the centre does not double-sharpen.
|
||||
@@ -552,7 +723,7 @@ void main(){
|
||||
float edge = smoothstep(0.18, 0.72, length(q) / max(0.05, length(vec2(u_aspect, 1.0) * 0.5)));
|
||||
col += detailSmall * lensSoft * edge * 1.1;
|
||||
}
|
||||
col += detailBig * (u_clarity / 100.0) * 1.25;
|
||||
col += detailBig * (clarityAmt / 100.0) * 1.25;
|
||||
|
||||
// Colour noise reduction: smooth only the chroma axes. Luminance is left alone,
|
||||
// so structure and luminance grain survive while the red/green blotches that
|
||||
@@ -597,11 +768,15 @@ void main(){
|
||||
if (green > 0.001) col.g = mix(col.g, (col.r + col.b) * 0.5, green);
|
||||
}
|
||||
|
||||
// Dehaze
|
||||
float d = u_dehaze / 100.0;
|
||||
// Dehaze. A single veil value over the whole frame under-corrects a bright
|
||||
// horizon while flattening the foreground, so the estimate is local: the dark
|
||||
// channel of the small blur against the atmospheric light in the large blur.
|
||||
float d = clamp(dehazeAmt / 100.0, -1.0, 1.0);
|
||||
if (d > 0.0) {
|
||||
float veil = luma(bb);
|
||||
col = (col - d * 0.32 * veil * vec3(0.95, 0.98, 1.02)) / max(0.05, 1.0 - d * 0.28);
|
||||
float dark = min(min(bs.r, bs.g), bs.b);
|
||||
float atm = max(0.12, luma(bb));
|
||||
float trans = clamp(1.0 - 0.9 * dark / atm, 0.18, 1.0);
|
||||
col = (col - atm * (1.0 - trans) * vec3(0.97, 0.99, 1.02)) / mix(1.0, trans, d * 0.9);
|
||||
} else if (d < 0.0) {
|
||||
col = mix(col, bb * 0.85 + vec3(0.09), -d * 0.55);
|
||||
}
|
||||
@@ -619,21 +794,30 @@ void main(){
|
||||
else col = mix(col, vec3(1.0), strength * 0.6);
|
||||
}
|
||||
|
||||
// Soft proofing: paper white, black point and a reduced print gamut. This is
|
||||
// a display simulation, not an ICC transform, but it makes the print intent
|
||||
// visible while editing and is applied after all creative effects.
|
||||
// Soft proofing, applied after every creative effect so the paper is what the
|
||||
// viewer sees. With a printer profile loaded the 3D table is the real ICC
|
||||
// round trip (PCS -> device -> PCS); without one the paper/black-point
|
||||
// approximation is all there is.
|
||||
if (u_proofEnable > 0.5) {
|
||||
float paperBlack = clamp(u_proofBlack / 100.0, 0.0, 0.2);
|
||||
col = mix(col, u_proofPaper, 0.035);
|
||||
col = paperBlack + col * (1.0 - paperBlack);
|
||||
float y = luma(col);
|
||||
col = mix(vec3(y), col, 0.88);
|
||||
if (u_gamut > 0.5) {
|
||||
float mx = max(col.r, max(col.g, col.b));
|
||||
float mn = min(col.r, min(col.g, col.b));
|
||||
float sat = mx > 0.001 ? (mx - mn) / mx : 0.0;
|
||||
if (sat > 0.62 && (mx > 0.92 || mn < 0.06)) {
|
||||
col = mix(col, vec3(1.0, 0.0, 0.75), 0.32);
|
||||
if (u_proofLutOn > 0.5) {
|
||||
vec4 proofed = texture(u_proofLut, clamp(col, 0.0, 1.0));
|
||||
col = proofed.rgb;
|
||||
if (u_gamut > 0.5 && proofed.a > 0.5) {
|
||||
col = mix(col, vec3(1.0, 0.0, 0.75), 0.55);
|
||||
}
|
||||
} else {
|
||||
float paperBlack = clamp(u_proofBlack / 100.0, 0.0, 0.2);
|
||||
col = mix(col, u_proofPaper, 0.035);
|
||||
col = paperBlack + col * (1.0 - paperBlack);
|
||||
float y = luma(col);
|
||||
col = mix(vec3(y), col, 0.88);
|
||||
if (u_gamut > 0.5) {
|
||||
float mx = max(col.r, max(col.g, col.b));
|
||||
float mn = min(col.r, min(col.g, col.b));
|
||||
float sat = mx > 0.001 ? (mx - mn) / mx : 0.0;
|
||||
if (sat > 0.62 && (mx > 0.92 || mn < 0.06)) {
|
||||
col = mix(col, vec3(1.0, 0.0, 0.75), 0.32);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -673,24 +857,15 @@ void main(){
|
||||
// Clipping overlay: which channels have run out of headroom. Red/green/blue
|
||||
// mean one channel clipped, yellow means two, white means all three — the
|
||||
// same reading Aperture's exposure warnings gave while you dragged.
|
||||
// The grade pass wrote the untouched source's clipping state into alpha:
|
||||
// 0.25 shadow, 0.50 highlight, 0.75 both. Warning about the source means it
|
||||
// still tells the truth after a curve or a shadow lift.
|
||||
float srcClip = texture(u_graded, v_uv).a;
|
||||
if (u_clip > 1.5) {
|
||||
// Shadow clipping: everything that has fallen to the bottom of the range.
|
||||
if (max(finalCol.r, max(finalCol.g, finalCol.b)) < 0.02) {
|
||||
finalCol = vec3(0.15, 0.4, 1.0);
|
||||
}
|
||||
if (srcClip >= 0.2 && srcClip < 0.5) finalCol = vec3(0.15, 0.4, 1.0);
|
||||
else if (srcClip >= 0.7) finalCol = vec3(0.15, 0.4, 1.0);
|
||||
} else if (u_clip > 0.5) {
|
||||
vec3 k = step(0.985, finalCol);
|
||||
float n = k.r + k.g + k.b;
|
||||
if (n > 0.5) {
|
||||
vec3 mark = vec3(1.0);
|
||||
if (n < 2.5) {
|
||||
if (n > 1.5) mark = vec3(1.0, 0.9, 0.1);
|
||||
else if (k.r > 0.5) mark = vec3(1.0, 0.12, 0.12);
|
||||
else if (k.g > 0.5) mark = vec3(0.1, 1.0, 0.2);
|
||||
else mark = vec3(0.15, 0.4, 1.0);
|
||||
}
|
||||
finalCol = mark;
|
||||
}
|
||||
if (srcClip >= 0.5) finalCol = vec3(1.0);
|
||||
}
|
||||
outColor = vec4(finalCol, 1.0);
|
||||
}`;
|
||||
@@ -915,6 +1090,13 @@ export function buildCurveLUT(edits: Edits): Uint8Array {
|
||||
const red = buildSampler(edits.curve.red);
|
||||
const green = buildSampler(edits.curve.green);
|
||||
const blue = buildSampler(edits.curve.blue);
|
||||
const { black, white, gamma } = edits.levels;
|
||||
const lo = clamp01(black / 100);
|
||||
const hi = Math.max(lo + 0.01, clamp01(white / 100));
|
||||
const invGamma = 1 / Math.max(0.3, Math.min(3, gamma));
|
||||
// Input levels sit before the curve: they set the true black and white points
|
||||
// and the midtone gamma, so the curve then shapes a full-range signal.
|
||||
const levels = (x: number) => Math.pow(clamp01((x - lo) / (hi - lo)), invGamma);
|
||||
const data = new Uint8Array(256 * 4);
|
||||
// Running maximum keeps the combined curve monotonic: four strong region
|
||||
// pushes can otherwise fold the curve back on itself and posterise the frame.
|
||||
@@ -922,7 +1104,7 @@ export function buildCurveLUT(edits: Edits): Uint8Array {
|
||||
let pg = 0;
|
||||
let pb = 0;
|
||||
for (let i = 0; i < 256; i++) {
|
||||
const base = rgb(i / 255);
|
||||
const base = rgb(levels(i / 255));
|
||||
pr = Math.max(pr, parametricTone(edits, red(base)));
|
||||
pg = Math.max(pg, parametricTone(edits, green(base)));
|
||||
pb = Math.max(pb, parametricTone(edits, blue(base)));
|
||||
@@ -976,6 +1158,19 @@ class Prog {
|
||||
const l = this.loc(name);
|
||||
if (l) this.gl.uniform3f(l, a, b, c);
|
||||
}
|
||||
/**
|
||||
* Row-major 3x3, as camera matrices are usually written. WebGL wants
|
||||
* column-major, so the values are transposed on the way in.
|
||||
*/
|
||||
m3(name: string, v: ArrayLike<number>) {
|
||||
const l = this.loc(name);
|
||||
if (!l || v.length < 9) return;
|
||||
this.gl.uniformMatrix3fv(
|
||||
l,
|
||||
false,
|
||||
new Float32Array([v[0], v[3], v[6], v[1], v[4], v[7], v[2], v[5], v[8]]),
|
||||
);
|
||||
}
|
||||
fv(name: string, values: Float32Array) {
|
||||
const l = this.loc(`${name}[0]`) ?? this.loc(name);
|
||||
if (l) this.gl.uniform1fv(l, values);
|
||||
@@ -987,6 +1182,13 @@ class Prog {
|
||||
this.gl.bindTexture(this.gl.TEXTURE_2D, texture);
|
||||
this.gl.uniform1i(l, unit);
|
||||
}
|
||||
tex3d(name: string, texture: WebGLTexture, unit: number) {
|
||||
const l = this.loc(name);
|
||||
if (!l) return;
|
||||
this.gl.activeTexture(this.gl.TEXTURE0 + unit);
|
||||
this.gl.bindTexture(this.gl.TEXTURE_3D, texture);
|
||||
this.gl.uniform1i(l, unit);
|
||||
}
|
||||
}
|
||||
|
||||
function compile(gl: WebGL2RenderingContext, type: number, source: string): WebGLShader {
|
||||
@@ -1030,6 +1232,7 @@ export class Renderer {
|
||||
private vao: WebGLVertexArrayObject;
|
||||
private srcTex: WebGLTexture;
|
||||
private maskTex: WebGLTexture;
|
||||
private maskTex2: WebGLTexture;
|
||||
private lensGeomTex: WebGLTexture;
|
||||
private lensTcaTex: WebGLTexture;
|
||||
private lensVigTex: WebGLTexture;
|
||||
@@ -1038,8 +1241,15 @@ export class Renderer {
|
||||
private lensSplit = -1;
|
||||
private maskSig = '';
|
||||
private srcBitmap: ImageBitmap | null = null;
|
||||
private srcHdr: Preview16 | null = null;
|
||||
/** Camera-to-sRGB matrix for a camera-native sidecar, else null. */
|
||||
private srcCam: number[] | null = null;
|
||||
private srcW = 1;
|
||||
private srcH = 1;
|
||||
private proofTex: WebGLTexture | null = null;
|
||||
private proofLutOn = 0;
|
||||
/** Identity guard: the cube is uploaded once per profile, not per frame. */
|
||||
private proofCube: SoftProofCube | null = null;
|
||||
private denTex: WebGLTexture;
|
||||
private denMix = 0;
|
||||
private denBitmap: ImageBitmap | null = null;
|
||||
@@ -1122,6 +1332,16 @@ export class Renderer {
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||||
|
||||
const maskTex2 = gl.createTexture();
|
||||
if (!maskTex2) throw new Error('Unable to create texture');
|
||||
this.maskTex2 = maskTex2;
|
||||
gl.bindTexture(gl.TEXTURE_2D, maskTex2);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4));
|
||||
|
||||
const curveTex = gl.createTexture();
|
||||
if (!curveTex) throw new Error('Unable to create texture');
|
||||
this.curveTex = curveTex;
|
||||
@@ -1192,8 +1412,16 @@ export class Renderer {
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
|
||||
}
|
||||
|
||||
setImage(bitmap: ImageBitmap) {
|
||||
if (this.srcBitmap === bitmap) return;
|
||||
/**
|
||||
* Uploads the editable source. `hdr` is the 16-bit half of a raw proxy: when
|
||||
* its size matches the bitmap it replaces the 8-bit JPEG as `u_src`, and the
|
||||
* whole grade then works from 65,536 levels per channel instead of 256.
|
||||
*
|
||||
* The pair is cached together, so a photo whose sidecar arrives a moment after
|
||||
* its bitmap uploads once more rather than on every redraw.
|
||||
*/
|
||||
setImage(bitmap: ImageBitmap, hdr: Preview16 | null = null) {
|
||||
if (this.srcBitmap === bitmap && this.srcHdr === hdr) return;
|
||||
// A denoised bitmap belongs to the previous photo; the caller re-supplies it
|
||||
// after this call when the new photo has one.
|
||||
this.denMix = 0;
|
||||
@@ -1202,16 +1430,120 @@ export class Renderer {
|
||||
this.maskSig = '';
|
||||
const gl = this.gl;
|
||||
this.srcBitmap = bitmap;
|
||||
this.srcHdr = hdr;
|
||||
this.srcCam = hdr?.rgbCam && hdr.rgbCam.length === 9 ? hdr.rgbCam : null;
|
||||
this.srcW = bitmap.width;
|
||||
this.srcH = bitmap.height;
|
||||
gl.bindTexture(gl.TEXTURE_2D, this.srcTex);
|
||||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
|
||||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||||
// Mipmaps: a 6000 px proxy shown fitted is a 4-8x minification, which shimmers
|
||||
// badly with plain bilinear sampling.
|
||||
gl.generateMipmap(gl.TEXTURE_2D);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
|
||||
const usable = hdr && hdr.width === bitmap.width && hdr.height === bitmap.height ? hdr : null;
|
||||
let half = false;
|
||||
if (usable) {
|
||||
// Clear stale errors so the upload result is ours; bounded in case the
|
||||
// context is lost and getError keeps reporting CONTEXT_LOST_WEBGL.
|
||||
for (let guard = 0; guard < 8 && gl.getError() !== gl.NO_ERROR; guard++) {
|
||||
/* drain */
|
||||
}
|
||||
gl.texImage2D(
|
||||
gl.TEXTURE_2D,
|
||||
0,
|
||||
gl.RGBA16F,
|
||||
usable.width,
|
||||
usable.height,
|
||||
0,
|
||||
gl.RGBA,
|
||||
gl.HALF_FLOAT,
|
||||
usable.rgba,
|
||||
);
|
||||
half = gl.getError() === gl.NO_ERROR;
|
||||
if (half) {
|
||||
// Half-float mipmaps are optional; without them the fitted view shimmers,
|
||||
// which is still better than refusing the extra precision.
|
||||
gl.generateMipmap(gl.TEXTURE_2D);
|
||||
const mip = gl.getError() === gl.NO_ERROR;
|
||||
gl.texParameteri(
|
||||
gl.TEXTURE_2D,
|
||||
gl.TEXTURE_MIN_FILTER,
|
||||
mip ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!half) {
|
||||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
|
||||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||||
// Mipmaps: a 6000 px proxy shown fitted is a 4-8x minification, which shimmers
|
||||
// badly with plain bilinear sampling.
|
||||
gl.generateMipmap(gl.TEXTURE_2D);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs the soft-proof 3D table (an sRGB-to-sRGB cube whose alpha channel
|
||||
* flags out-of-gamut colours), or clears it to fall back to the paper
|
||||
* approximation. Uploading happens here rather than per frame: the table is
|
||||
* built once from a printer profile.
|
||||
*/
|
||||
setProofLut(lut: SoftProofCube | null) {
|
||||
if (lut === this.proofCube) return;
|
||||
this.proofCube = lut;
|
||||
const gl = this.gl;
|
||||
if (!lut) {
|
||||
if (this.proofTex) {
|
||||
gl.deleteTexture(this.proofTex);
|
||||
this.proofTex = null;
|
||||
}
|
||||
this.proofLutOn = 0;
|
||||
return;
|
||||
}
|
||||
if (!this.proofTex) {
|
||||
const tex = gl.createTexture();
|
||||
if (!tex) return;
|
||||
this.proofTex = tex;
|
||||
}
|
||||
gl.bindTexture(gl.TEXTURE_3D, this.proofTex);
|
||||
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_R, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||||
for (let guard = 0; guard < 8 && gl.getError() !== gl.NO_ERROR; guard++) {
|
||||
/* drain, so the upload error below is ours */
|
||||
}
|
||||
gl.texImage3D(
|
||||
gl.TEXTURE_3D,
|
||||
0,
|
||||
gl.RGBA16F,
|
||||
lut.size,
|
||||
lut.size,
|
||||
lut.size,
|
||||
0,
|
||||
gl.RGBA,
|
||||
gl.FLOAT,
|
||||
lut.data,
|
||||
);
|
||||
if (gl.getError() !== gl.NO_ERROR) {
|
||||
// Half-float 3D textures are core WebGL2; if this context refuses them,
|
||||
// an 8-bit cube still beats silently doing nothing.
|
||||
const bytes = new Uint8Array(lut.data.length);
|
||||
for (let i = 0; i < lut.data.length; i++) {
|
||||
bytes[i] = Math.round(Math.min(1, Math.max(0, lut.data[i])) * 255);
|
||||
}
|
||||
gl.texImage3D(
|
||||
gl.TEXTURE_3D,
|
||||
0,
|
||||
gl.RGBA8,
|
||||
lut.size,
|
||||
lut.size,
|
||||
lut.size,
|
||||
0,
|
||||
gl.RGBA,
|
||||
gl.UNSIGNED_BYTE,
|
||||
bytes,
|
||||
);
|
||||
}
|
||||
this.proofLutOn = 1;
|
||||
}
|
||||
|
||||
private makeTarget(w: number, h: number, float = this.floatTargets): Target {
|
||||
@@ -1309,9 +1641,13 @@ export class Renderer {
|
||||
const sig = maskSignature(layers, this.srcW, this.srcH);
|
||||
if (sig !== this.maskSig) {
|
||||
const packed = buildLocalMasks(layers, this.srcW, this.srcH);
|
||||
gl.bindTexture(gl.TEXTURE_2D, this.maskTex);
|
||||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, packed.w, packed.h, 0, gl.RGBA, gl.UNSIGNED_BYTE, packed.data);
|
||||
const upload = (tex: WebGLTexture, data: Uint8Array) => {
|
||||
gl.bindTexture(gl.TEXTURE_2D, tex);
|
||||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, packed.w, packed.h, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
|
||||
};
|
||||
upload(this.maskTex, packed.data);
|
||||
upload(this.maskTex2, packed.data2);
|
||||
this.maskSig = sig;
|
||||
}
|
||||
return layers.length;
|
||||
@@ -1354,6 +1690,12 @@ export class Renderer {
|
||||
// denoised texture, leaving u_den sampling a 1x1 zero texture -- black.
|
||||
g.tex('u_den', this.denTex, 6);
|
||||
g.f('u_denMix', this.denMix);
|
||||
// A per-photo DCP profile replaces the body matrix, but only when the
|
||||
// source really is camera-native. Applying one to an sRGB proxy would
|
||||
// double-convert the pixels.
|
||||
const srcCam = this.srcCam ? (edits.cameraProfile?.matrix ?? this.srcCam) : null;
|
||||
g.f('u_srcMatrix', srcCam ? 1 : 0);
|
||||
if (srcCam) g.m3('u_srcCam', srcCam);
|
||||
g.v2('u_srcSize', this.srcW, this.srcH);
|
||||
g.v2('u_frameSize', bounds.w, bounds.h);
|
||||
g.v4('u_crop', crop.x, crop.y, crop.w, crop.h);
|
||||
@@ -1365,8 +1707,8 @@ export class Renderer {
|
||||
g.f('u_srcLod', Math.max(0, Math.min(12, srcLod)));
|
||||
g.f('u_pick', -1);
|
||||
g.v2('u_pickUv', 0, 0);
|
||||
g.f('u_temp', edits.temp);
|
||||
g.f('u_tint', edits.tint);
|
||||
const wb = wbGainFor(edits.temp, edits.tint, edits.kelvin);
|
||||
g.v3('u_wbGain', wb[0], wb[1], wb[2]);
|
||||
g.f('u_exposure', edits.exposure);
|
||||
g.f('u_recovery', edits.recovery);
|
||||
g.f('u_contrast', edits.contrast);
|
||||
@@ -1376,6 +1718,7 @@ export class Renderer {
|
||||
g.f('u_blacks', edits.blacks);
|
||||
g.f('u_vibrance', edits.vibrance);
|
||||
g.f('u_saturation', edits.saturation);
|
||||
g.f('u_redscale', edits.redscale ?? 0);
|
||||
g.f('u_bw', edits.bw ? 1 : 0);
|
||||
const bwFilter = bwFilterRgb(edits.bwFilter);
|
||||
g.v3('u_bwFilter', bwFilter[0], bwFilter[1], bwFilter[2]);
|
||||
@@ -1415,11 +1758,14 @@ export class Renderer {
|
||||
g.f('u_lensSplit', this.lensSplit);
|
||||
|
||||
g.tex('u_masks', this.maskTex, 2);
|
||||
g.tex('u_masks2', this.maskTex2, 7);
|
||||
g.i('u_localCount', localCount);
|
||||
for (let i = 0; i < localCount; i++) {
|
||||
const layer = edits.local[i];
|
||||
g.v4i('u_localAdj', i, layer.adjust.exposure, layer.adjust.contrast, layer.adjust.temp, layer.adjust.tint);
|
||||
g.v4i('u_localAdj2', i, layer.adjust.saturation, layer.adjust.highlights, layer.adjust.shadows, 0);
|
||||
const maskMode = layer.mode === 'subtract' ? 1 : layer.mode === 'intersect' ? 2 : 0;
|
||||
g.v4i('u_localAdj2', i, layer.adjust.saturation, layer.adjust.highlights, layer.adjust.shadows, maskMode);
|
||||
g.v4i('u_localAdj3', i, layer.adjust.whites, layer.adjust.blacks, layer.adjust.vibrance, layer.adjust.hue);
|
||||
g.v4i('u_localRange', i, layer.range.lumaMin / 100, layer.range.lumaMax / 100, layer.range.hue, layer.range.hueRange);
|
||||
g.v4i('u_localRange2', i, layer.range.satMin / 100, layer.range.enabled ? 1 : 0, 0, 0);
|
||||
}
|
||||
@@ -1503,6 +1849,9 @@ export class Renderer {
|
||||
): Float32Array | null {
|
||||
const gl = this.gl;
|
||||
if (!this.srcBitmap) return null;
|
||||
// Proofing is a session-level view setting, so every renderer (editor,
|
||||
// compare view, export) picks up the loaded profile without extra plumbing.
|
||||
this.setProofLut(getActiveProofCube());
|
||||
if (opts.lens !== undefined) this.setLensCorrection(opts.lens);
|
||||
this.lensSplit = opts.lensSplit ?? -1;
|
||||
const w = Math.max(1, Math.round(opts.width));
|
||||
@@ -1617,7 +1966,26 @@ export class Renderer {
|
||||
this.finish.f('u_dehaze', edits.dehaze);
|
||||
this.finish.f('u_sharpen', edits.sharpen.amount);
|
||||
this.finish.f('u_sharpenMask', edits.sharpen.mask);
|
||||
this.finish.f('u_sharpenDetail', edits.sharpen.detail);
|
||||
this.finish.f('u_nrDetail', edits.noise.detail);
|
||||
this.finish.f('u_detailScale', detailScale);
|
||||
this.finish.tex('u_masks', this.maskTex, 3);
|
||||
this.finish.tex('u_masks2', this.maskTex2, 4);
|
||||
const innerLayers = (edits.local ?? []).slice(0, MAX_LOCAL_LAYERS);
|
||||
this.finish.i('u_localCount', innerLayers.length);
|
||||
for (let i = 0; i < innerLayers.length; i++) {
|
||||
const layer = innerLayers[i];
|
||||
this.finish.v4i(
|
||||
'u_localDetail',
|
||||
i,
|
||||
layer.adjust.texture ?? 0,
|
||||
layer.adjust.clarity ?? 0,
|
||||
layer.adjust.dehaze ?? 0,
|
||||
layer.adjust.sharpen ?? 0,
|
||||
);
|
||||
const mode = layer.mode === 'subtract' ? 1 : layer.mode === 'intersect' ? 2 : 0;
|
||||
this.finish.v4i('u_localModes', i, mode, 0, 0, 0);
|
||||
}
|
||||
this.finish.f('u_lensSoft', edits.sharpen.lensSoftness);
|
||||
this.finish.f('u_proofEnable', edits.proof.enabled ? 1 : 0);
|
||||
const paper = edits.proof.paper === 'gloss'
|
||||
@@ -1628,6 +1996,8 @@ export class Renderer {
|
||||
this.finish.v3('u_proofPaper', paper[0], paper[1], paper[2]);
|
||||
this.finish.f('u_proofBlack', edits.proof.blackPoint);
|
||||
this.finish.f('u_gamut', edits.proof.gamut ? 1 : 0);
|
||||
this.finish.f('u_proofLutOn', this.proofLutOn);
|
||||
if (this.proofTex && this.proofLutOn > 0.5) this.finish.tex3d('u_proofLut', this.proofTex, 7);
|
||||
this.finish.f('u_nr', edits.noise.luminance);
|
||||
this.finish.f('u_chroma', edits.noise.chroma);
|
||||
this.finish.f('u_chromaDetail', edits.noise.chromaDetail);
|
||||
@@ -1721,10 +2091,12 @@ export class Renderer {
|
||||
this.freeTarget(this.exportTarget ?? undefined);
|
||||
gl.deleteTexture(this.srcTex);
|
||||
gl.deleteTexture(this.maskTex);
|
||||
gl.deleteTexture(this.maskTex2);
|
||||
gl.deleteTexture(this.curveTex);
|
||||
gl.deleteTexture(this.lensGeomTex);
|
||||
gl.deleteTexture(this.lensTcaTex);
|
||||
gl.deleteTexture(this.lensVigTex);
|
||||
if (this.proofTex) gl.deleteTexture(this.proofTex);
|
||||
gl.deleteBuffer(this.quad);
|
||||
gl.deleteVertexArray(this.vao);
|
||||
gl.deleteProgram(this.grade.program);
|
||||
|
||||
Vendored
-83
@@ -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>;
|
||||
}
|
||||
+282
-2
@@ -1,4 +1,4 @@
|
||||
import type { EventRecord, PhotoRecord, Preset } from '../types';
|
||||
import type { EventRecord, Flag, PhotoRecord, Preset } from '../types';
|
||||
|
||||
export interface Health {
|
||||
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;
|
||||
try {
|
||||
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> {
|
||||
return request<{ photo: PhotoRecord }>(`/api/photos/${encodeURIComponent(photo.id)}`, {
|
||||
method: 'PUT',
|
||||
@@ -221,10 +236,26 @@ export interface ShareFeedback {
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export interface ShareSettings {
|
||||
passwordSet: boolean;
|
||||
expiresAt: number | null;
|
||||
watermark: string;
|
||||
allowDownloads: boolean;
|
||||
downloadCap: number;
|
||||
downloadCount: number;
|
||||
}
|
||||
|
||||
export interface ShareState {
|
||||
token: string | null;
|
||||
picks: { photoId: string; clientName: string }[];
|
||||
feedback?: ShareFeedback[];
|
||||
settings?: ShareSettings | null;
|
||||
}
|
||||
|
||||
export interface GalleryStatus {
|
||||
locked: boolean;
|
||||
expiresAt: number | null;
|
||||
allowDownloads: boolean;
|
||||
}
|
||||
|
||||
export interface GalleryComment {
|
||||
@@ -253,6 +284,8 @@ export interface GalleryPayload {
|
||||
photographer: string;
|
||||
photos: GalleryPhoto[];
|
||||
picks: { total: number; clients: number };
|
||||
downloads?: { allowed: boolean; remaining: number | null };
|
||||
watermark?: string;
|
||||
}
|
||||
|
||||
export function getShare(eventId: string): Promise<ShareState> {
|
||||
@@ -274,6 +307,71 @@ export function galleryDownloadAllUrl(token: string, clientId: string): string {
|
||||
return `/api/galleries/${encodeURIComponent(token)}/download-all?${query}`;
|
||||
}
|
||||
|
||||
export interface ShareSettingsInput {
|
||||
password?: string;
|
||||
expiresAt?: number | null;
|
||||
watermark?: string;
|
||||
allowDownloads?: boolean;
|
||||
downloadCap?: number;
|
||||
}
|
||||
|
||||
export function saveShareSettings(
|
||||
eventId: string,
|
||||
input: ShareSettingsInput,
|
||||
): Promise<ShareSettings> {
|
||||
return request<{ settings: ShareSettings }>(
|
||||
`/api/events/${encodeURIComponent(eventId)}/share/settings`,
|
||||
{
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
},
|
||||
).then((res) => res.settings);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ tether api */
|
||||
|
||||
export interface TetherFile {
|
||||
name: string;
|
||||
size: number;
|
||||
mtime: number;
|
||||
}
|
||||
|
||||
export interface TetherState {
|
||||
folder: string;
|
||||
files: TetherFile[];
|
||||
}
|
||||
|
||||
export function listTether(eventId: string): Promise<TetherState> {
|
||||
return request<TetherState>(`/api/events/${encodeURIComponent(eventId)}/tether`);
|
||||
}
|
||||
|
||||
export function tetherFileUrl(eventId: string, name: string): string {
|
||||
const query = new URLSearchParams({ name });
|
||||
return `/api/events/${encodeURIComponent(eventId)}/tether/file?${query}`;
|
||||
}
|
||||
|
||||
export function removeTetherFile(eventId: string, name: string): Promise<void> {
|
||||
const query = new URLSearchParams({ name });
|
||||
return request(`/api/events/${encodeURIComponent(eventId)}/tether/file?${query}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
}
|
||||
|
||||
/** Public check for the link's lock and expiry, before loading the gallery. */
|
||||
export function getGalleryStatus(token: string): Promise<GalleryStatus> {
|
||||
return request<GalleryStatus>(`/api/galleries/${encodeURIComponent(token)}/status`);
|
||||
}
|
||||
|
||||
/** Exchanges the gallery password for the unlock cookie the routes require. */
|
||||
export function unlockGallery(token: string, password: string): Promise<void> {
|
||||
return request(`/api/galleries/${encodeURIComponent(token)}/unlock`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password }),
|
||||
});
|
||||
}
|
||||
|
||||
export function revokeShare(eventId: string): Promise<void> {
|
||||
return request(`/api/events/${encodeURIComponent(eventId)}/share`, { method: 'DELETE' });
|
||||
}
|
||||
@@ -418,6 +516,75 @@ export interface MailStatus {
|
||||
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 {
|
||||
users: AdminUser[];
|
||||
events: AdminEvent[];
|
||||
@@ -426,6 +593,7 @@ export interface AdminOverview {
|
||||
storage: { root: string; defaultRoot: string; custom: boolean; diskBytes?: number };
|
||||
quotas: AdminQuota[];
|
||||
mail: MailStatus;
|
||||
immich: ImmichStatus;
|
||||
}
|
||||
|
||||
export interface StorageChange {
|
||||
@@ -576,6 +744,118 @@ 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 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> {
|
||||
return request('/api/presets', {
|
||||
method: 'PUT',
|
||||
|
||||
@@ -71,3 +71,70 @@ export async function computeAutoEdits(thumb: string): Promise<Partial<Edits>> {
|
||||
return { contrast: 12, shadows: 12, highlights: -12, vibrance: 8 };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Grey-world auto white balance. It averages the unclipped midtones, then
|
||||
* searches the two WB sliders for the multipliers that neutralise them. This is
|
||||
* a starting point for mixed or unknown light, not a substitute for the
|
||||
* eyedropper on a known neutral.
|
||||
*/
|
||||
export async function computeAutoWhiteBalance(
|
||||
thumb: string,
|
||||
): Promise<{ temp: number; tint: number }> {
|
||||
try {
|
||||
const img = new Image();
|
||||
img.src = thumb;
|
||||
await img.decode();
|
||||
const w = 96;
|
||||
const h = Math.max(1, Math.round((img.height / img.width) * w)) || 96;
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) throw new Error('Canvas unavailable');
|
||||
ctx.drawImage(img, 0, 0, w, h);
|
||||
const { data } = ctx.getImageData(0, 0, w, h);
|
||||
|
||||
let r = 0;
|
||||
let g = 0;
|
||||
let b = 0;
|
||||
let count = 0;
|
||||
for (let i = 0; i < data.length; i += 4) {
|
||||
const rr = data[i];
|
||||
const gg = data[i + 1];
|
||||
const bb = data[i + 2];
|
||||
const sum = rr + gg + bb;
|
||||
// Clipped highlights and near-black pixels carry no reliable cast.
|
||||
if (sum > 735 || sum < 24) continue;
|
||||
r += rr;
|
||||
g += gg;
|
||||
b += bb;
|
||||
count += 1;
|
||||
}
|
||||
if (!count) return { temp: 0, tint: 0 };
|
||||
|
||||
const ar = r / count / 255;
|
||||
const ag = g / count / 255;
|
||||
const ab = b / count / 255;
|
||||
let best = { temp: 0, tint: 0, err: Number.POSITIVE_INFINITY };
|
||||
for (let temp = -100; temp <= 100; temp += 4) {
|
||||
for (let tint = -100; tint <= 100; tint += 4) {
|
||||
const t = temp / 100;
|
||||
const ti = tint / 100;
|
||||
// Same channel multipliers the grade shader applies.
|
||||
const mr = 1 + 0.3 * t + 0.06 * ti;
|
||||
const mg = 1 - 0.16 * ti;
|
||||
const mb = 1 - 0.26 * t + 0.06 * ti;
|
||||
const rr = ar * mr;
|
||||
const gg = ag * mg;
|
||||
const bb = ab * mb;
|
||||
const mean = (rr + gg + bb) / 3;
|
||||
const err = (rr - mean) ** 2 + (gg - mean) ** 2 + (bb - mean) ** 2;
|
||||
if (err < best.err) best = { temp, tint, err };
|
||||
}
|
||||
}
|
||||
return { temp: best.temp, tint: best.tint };
|
||||
} catch {
|
||||
return { temp: 0, tint: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { fillHoles, otsuThreshold, segmentMask } from './autoMask';
|
||||
|
||||
/** Flat grey background with a red block in the middle. */
|
||||
function portrait(width = 64, height = 64): Uint8Array {
|
||||
const data = new Uint8Array(width * height * 4);
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
const o = (y * width + x) * 4;
|
||||
const inside = x > width * 0.3 && x < width * 0.7 && y > height * 0.25 && y < height * 0.85;
|
||||
data[o] = inside ? 190 : 120;
|
||||
data[o + 1] = inside ? 40 : 120;
|
||||
data[o + 2] = inside ? 30 : 120;
|
||||
data[o + 3] = 255;
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
describe('segmentation', () => {
|
||||
it('selects the centred subject against a flat border', () => {
|
||||
const width = 64;
|
||||
const height = 64;
|
||||
const mask = segmentMask(portrait(width, height), width, height, 'subject');
|
||||
const at = (x: number, y: number) => mask[y * width + x];
|
||||
expect(at(32, 32)).toBe(255);
|
||||
expect(at(2, 32)).toBe(0);
|
||||
expect(at(32, 2)).toBe(0);
|
||||
let inside = 0;
|
||||
let outside = 0;
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
const inSubject = x > width * 0.3 && x < width * 0.7 && y > height * 0.25 && y < height * 0.85;
|
||||
if (inSubject && mask[y * width + x]) inside++;
|
||||
if (!inSubject && mask[y * width + x]) outside++;
|
||||
}
|
||||
}
|
||||
// Most of the subject is covered, and the flat wall mostly is not.
|
||||
expect(inside / (width * height * 0.24)).toBeGreaterThan(0.6);
|
||||
expect(outside).toBeLessThan(width * height * 0.2);
|
||||
});
|
||||
|
||||
it('finds a blue sky above the horizon only', () => {
|
||||
const width = 64;
|
||||
const height = 64;
|
||||
const data = new Uint8Array(width * height * 4);
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
const o = (y * width + x) * 4;
|
||||
const sky = y < height / 2;
|
||||
data[o] = sky ? 70 : 120;
|
||||
data[o + 1] = sky ? 130 : 110;
|
||||
data[o + 2] = sky ? 220 : 80;
|
||||
data[o + 3] = 255;
|
||||
}
|
||||
}
|
||||
const mask = segmentMask(data, width, height, 'sky');
|
||||
expect(mask[10 * width + 32]).toBe(255);
|
||||
expect(mask[55 * width + 32]).toBe(0);
|
||||
});
|
||||
|
||||
it('inverts the subject for the background selection', () => {
|
||||
const width = 64;
|
||||
const height = 64;
|
||||
const subject = segmentMask(portrait(width, height), width, height, 'subject');
|
||||
const background = segmentMask(portrait(width, height), width, height, 'background');
|
||||
expect(subject[32 * width + 32]).toBe(255);
|
||||
expect(background[32 * width + 32]).toBe(0);
|
||||
});
|
||||
|
||||
it('splits a bimodal score map', () => {
|
||||
const values = new Float32Array(1000);
|
||||
for (let i = 0; i < 500; i++) values[i] = 0.1;
|
||||
for (let i = 500; i < 1000; i++) values[i] = 0.9;
|
||||
const threshold = otsuThreshold(values);
|
||||
expect(threshold).toBeGreaterThan(0.1);
|
||||
expect(threshold).toBeLessThan(0.9);
|
||||
});
|
||||
|
||||
it('fills an enclosed hole without spilling over the rim', () => {
|
||||
const width = 9;
|
||||
const height = 9;
|
||||
const mask = new Uint8Array(width * height);
|
||||
for (let y = 2; y < 7; y++) {
|
||||
for (let x = 2; x < 7; x++) mask[y * width + x] = 255;
|
||||
}
|
||||
mask[4 * width + 4] = 0;
|
||||
fillHoles(mask, width, height);
|
||||
expect(mask[4 * width + 4]).toBe(255);
|
||||
expect(mask[0]).toBe(0);
|
||||
});
|
||||
});
|
||||
+236
-45
@@ -6,15 +6,17 @@ export type AutoMaskKind = 'subject' | 'sky' | 'background';
|
||||
* On-device mask estimation for the three selections that matter most in an
|
||||
* event edit: the subject, the sky and the background around the subject.
|
||||
*
|
||||
* The estimator works from a downsampled preview. It combines distance from
|
||||
* the border colour (the usual studio/event background) with a centre bias,
|
||||
* saturation and a vertical sky prior. This is intentionally lightweight: it
|
||||
* has no model download and produces a low-resolution raster that the normal
|
||||
* mask pipeline feathers and scales. The output is editable like any brush
|
||||
* mask, so a missed edge can be fixed without another model pass.
|
||||
* The estimator works from a downsampled preview and is deliberately
|
||||
* model-free: there is nothing to download and it runs in a few milliseconds.
|
||||
* It builds a coarse colour histogram of the frame's border (the usual studio,
|
||||
* venue or sky background), scores every pixel against that model plus a centre
|
||||
* prior, splits the score map with an Otsu threshold, then keeps the connected
|
||||
* regions that actually matter and fills interior holes. The result is a
|
||||
* low-resolution raster the normal mask pipeline feathers and scales, and it is
|
||||
* editable like any brush mask, so a missed edge can be fixed by hand.
|
||||
*/
|
||||
export async function buildAutoMask(bitmap: ImageBitmap, kind: AutoMaskKind): Promise<RasterMask> {
|
||||
const width = Math.max(128, Math.min(320, Math.round(bitmap.width / 16)));
|
||||
const width = Math.max(128, Math.min(384, Math.round(bitmap.width / 12)));
|
||||
const height = Math.max(48, Math.round((width * bitmap.height) / Math.max(1, bitmap.width)));
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = width;
|
||||
@@ -23,12 +25,26 @@ export async function buildAutoMask(bitmap: ImageBitmap, kind: AutoMaskKind): Pr
|
||||
if (!ctx) throw new Error('Could not analyse the image for a mask');
|
||||
ctx.drawImage(bitmap, 0, 0, width, height);
|
||||
const image = ctx.getImageData(0, 0, width, height);
|
||||
const data = image.data;
|
||||
const count = width * height;
|
||||
const mask = segmentMask(image.data, width, height, kind);
|
||||
return { data: encodeBase64(mask), width, height };
|
||||
}
|
||||
|
||||
const subject = new Float32Array(count);
|
||||
const sky = new Float32Array(count);
|
||||
const border = borderColor(data, width, height);
|
||||
/**
|
||||
* Pure segmentation step, exported so it can be exercised without a canvas.
|
||||
* Returns one byte per pixel: 255 inside the selection, 0 outside.
|
||||
*/
|
||||
export function segmentMask(
|
||||
data: Uint8ClampedArray | Uint8Array,
|
||||
width: number,
|
||||
height: number,
|
||||
kind: AutoMaskKind,
|
||||
): Uint8Array {
|
||||
const count = width * height;
|
||||
if (!count) return new Uint8Array(0);
|
||||
|
||||
const border = borderModel(data, width, height);
|
||||
const score = new Float32Array(count);
|
||||
const luma = new Float32Array(count);
|
||||
|
||||
for (let y = 0; y < height; y++) {
|
||||
const ny = y / Math.max(1, height - 1);
|
||||
@@ -38,55 +54,230 @@ export async function buildAutoMask(bitmap: ImageBitmap, kind: AutoMaskKind): Pr
|
||||
const r = data[o] / 255;
|
||||
const g = data[o + 1] / 255;
|
||||
const b = data[o + 2] / 255;
|
||||
const dist = Math.min(1, Math.sqrt((r - border[0]) ** 2 + (g - border[1]) ** 2 + (b - border[2]) ** 2) / 1.35);
|
||||
const center = 1 - Math.min(1, Math.sqrt(((x / width - 0.5) * 1.7) ** 2 + ((y / height - 0.5) * 1.35) ** 2));
|
||||
const value = 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
luma[i] = value;
|
||||
const maxc = Math.max(r, g, b);
|
||||
const minc = Math.min(r, g, b);
|
||||
const sat = maxc > 0.001 ? (maxc - minc) / maxc : 0;
|
||||
const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
subject[i] = dist * 0.58 + center * 0.27 + sat * 0.1 + (1 - Math.abs(luma - 0.48)) * 0.05;
|
||||
const blue = Math.max(0, b - (r + g) * 0.5);
|
||||
sky[i] = blue * 2.5 + Math.max(0, luma - 0.4) * 0.5 + (1 - ny) * 0.28 - (1 - sat) * 0.08;
|
||||
|
||||
if (kind === 'sky') {
|
||||
// Blue excess, brightness and height above the horizon. A foreground
|
||||
// building keeps a hard edge, which the component pass protects.
|
||||
const blue = Math.max(0, b - (r + g) * 0.5);
|
||||
score[i] =
|
||||
blue * 2.4 +
|
||||
Math.max(0, value - 0.35) * 0.55 +
|
||||
(1 - ny) * 0.42 -
|
||||
sat * 0.18;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Background probability from the border histogram, softened so a pixel
|
||||
// next to a slightly different bin still reads as background.
|
||||
const bg = border.probability(r, g, b);
|
||||
const centre =
|
||||
1 - Math.min(1, Math.sqrt(((x / width - 0.5) * 1.7) ** 2 + ((y / height - 0.5) * 1.35) ** 2));
|
||||
const chroma = Math.min(
|
||||
1,
|
||||
Math.sqrt((r - border.mean[0]) ** 2 + (g - border.mean[1]) ** 2 + (b - border.mean[2]) ** 2) /
|
||||
1.2,
|
||||
);
|
||||
// Skin and clothing usually sit near the centre and differ in chroma from
|
||||
// a neutral wall; the histogram alone would eat a white shirt.
|
||||
const subject = (1 - bg) * 0.46 + centre * 0.28 + chroma * 0.17 + sat * 0.09;
|
||||
score[i] = kind === 'background' ? 1 - subject : subject;
|
||||
}
|
||||
}
|
||||
|
||||
const raw = kind === 'sky' ? sky : subject;
|
||||
const sorted = [...raw].sort((a, b) => a - b);
|
||||
const median = sorted[Math.floor(sorted.length * 0.5)] ?? 0;
|
||||
const high = sorted[Math.floor(sorted.length * 0.82)] ?? 1;
|
||||
const threshold = kind === 'sky' ? Math.max(0.35, median) : Math.max(0.36, median + (high - median) * 0.22);
|
||||
const threshold = otsuThreshold(score);
|
||||
const mask = new Uint8Array(count);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const on = raw[i] >= threshold;
|
||||
mask[i] = (kind === 'background' ? !on : on) ? 255 : 0;
|
||||
}
|
||||
smooth(mask, width, height);
|
||||
smooth(mask, width, height);
|
||||
for (let i = 0; i < count; i++) mask[i] = score[i] >= threshold ? 255 : 0;
|
||||
|
||||
return { data: encodeBase64(mask), width, height };
|
||||
keepLargeRegions(mask, width, height);
|
||||
if (kind !== 'background') fillHoles(mask, width, height);
|
||||
smooth(mask, width, height);
|
||||
smooth(mask, width, height);
|
||||
return mask;
|
||||
}
|
||||
|
||||
function borderColor(data: Uint8ClampedArray, width: number, height: number): [number, number, number] {
|
||||
let r = 0;
|
||||
let g = 0;
|
||||
let b = 0;
|
||||
interface BorderModel {
|
||||
/** 4×4×4 RGB histogram of the frame's edge, normalised to the fullest bin. */
|
||||
probability: (r: number, g: number, b: number) => number;
|
||||
mean: [number, number, number];
|
||||
}
|
||||
|
||||
function borderModel(
|
||||
data: Uint8ClampedArray | Uint8Array,
|
||||
width: number,
|
||||
height: number,
|
||||
): BorderModel {
|
||||
const bins = new Float32Array(64);
|
||||
let mr = 0;
|
||||
let mg = 0;
|
||||
let mb = 0;
|
||||
let n = 0;
|
||||
const add = (x: number, y: number) => {
|
||||
const ring = Math.max(1, Math.round(Math.min(width, height) * 0.03));
|
||||
const sample = (x: number, y: number) => {
|
||||
const o = (y * width + x) * 4;
|
||||
r += data[o];
|
||||
g += data[o + 1];
|
||||
b += data[o + 2];
|
||||
n++;
|
||||
const r = data[o];
|
||||
const g = data[o + 1];
|
||||
const b = data[o + 2];
|
||||
bins[((r >> 6) << 4) | ((g >> 6) << 2) | (b >> 6)] += 1;
|
||||
mr += r;
|
||||
mg += g;
|
||||
mb += b;
|
||||
n += 1;
|
||||
};
|
||||
for (let y = 0; y < height; y++) {
|
||||
const edgeRow = y < ring || y >= height - ring;
|
||||
for (let x = 0; x < width; x++) {
|
||||
if (edgeRow || x < ring || x >= width - ring) sample(x, y);
|
||||
}
|
||||
}
|
||||
// Blur the histogram across neighbouring bins: real backgrounds are not
|
||||
// quantised to 64 colours, and a hard lookup would call a wall foreground.
|
||||
const soft = new Float32Array(64);
|
||||
for (let r = 0; r < 4; r++) {
|
||||
for (let g = 0; g < 4; g++) {
|
||||
for (let b = 0; b < 4; b++) {
|
||||
const index = (r << 4) | (g << 2) | b;
|
||||
let total = 0;
|
||||
for (let dr = -1; dr <= 1; dr++) {
|
||||
for (let dg = -1; dg <= 1; dg++) {
|
||||
for (let db = -1; db <= 1; db++) {
|
||||
const rr = r + dr;
|
||||
const gg = g + dg;
|
||||
const bb = b + db;
|
||||
if (rr < 0 || rr > 3 || gg < 0 || gg > 3 || bb < 0 || bb > 3) continue;
|
||||
total += bins[(rr << 4) | (gg << 2) | bb] * (dr === 0 && dg === 0 && db === 0 ? 3 : 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
soft[index] = total;
|
||||
}
|
||||
}
|
||||
}
|
||||
const max = soft.reduce((best, value) => Math.max(best, value), 0) || 1;
|
||||
return {
|
||||
probability: (r, g, b) => {
|
||||
const value = soft[((Math.min(3, r * 4) | 0) << 4) | ((Math.min(3, g * 4) | 0) << 2) | (Math.min(3, b * 4) | 0)];
|
||||
return Math.min(1, value / max);
|
||||
},
|
||||
mean: n ? [mr / n / 255, mg / n / 255, mb / n / 255] : [0.5, 0.5, 0.5],
|
||||
};
|
||||
}
|
||||
|
||||
/** Otsu split of the score histogram: adapts to flat and busy frames alike. */
|
||||
export function otsuThreshold(values: Float32Array): number {
|
||||
let min = Infinity;
|
||||
let max = -Infinity;
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
min = Math.min(min, values[i]);
|
||||
max = Math.max(max, values[i]);
|
||||
}
|
||||
if (!Number.isFinite(min) || max - min < 1e-4) return max + 1;
|
||||
const bins = 64;
|
||||
const hist = new Float64Array(bins);
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
const bin = Math.min(bins - 1, Math.floor(((values[i] - min) / (max - min)) * bins));
|
||||
hist[bin] += 1;
|
||||
}
|
||||
const total = values.length;
|
||||
let sum = 0;
|
||||
for (let i = 0; i < bins; i++) sum += i * hist[i];
|
||||
let sumB = 0;
|
||||
let wB = 0;
|
||||
let best = 0;
|
||||
let bestVariance = -1;
|
||||
for (let i = 0; i < bins; i++) {
|
||||
wB += hist[i];
|
||||
if (!wB) continue;
|
||||
const wF = total - wB;
|
||||
if (!wF) break;
|
||||
sumB += i * hist[i];
|
||||
const mB = sumB / wB;
|
||||
const mF = (sum - sumB) / wF;
|
||||
const variance = wB * wF * (mB - mF) ** 2;
|
||||
if (variance > bestVariance) {
|
||||
bestVariance = variance;
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
// Otsu's split lies between bin `best` and the next: taking the upper edge
|
||||
// puts the threshold above the lower mode rather than inside it.
|
||||
return min + ((best + 1) / bins) * (max - min);
|
||||
}
|
||||
|
||||
/** Drops specks: keeps every region at least a fifth of the largest one. */
|
||||
export function keepLargeRegions(mask: Uint8Array, width: number, height: number) {
|
||||
const labels = new Int32Array(mask.length).fill(-1);
|
||||
const sizes: number[] = [];
|
||||
const stack: number[] = [];
|
||||
for (let start = 0; start < mask.length; start++) {
|
||||
if (!mask[start] || labels[start] !== -1) continue;
|
||||
const label = sizes.length;
|
||||
let size = 0;
|
||||
stack.push(start);
|
||||
labels[start] = label;
|
||||
while (stack.length) {
|
||||
const index = stack.pop() as number;
|
||||
size++;
|
||||
const x = index % width;
|
||||
const y = (index - x) / width;
|
||||
const visit = (nx: number, ny: number) => {
|
||||
if (nx < 0 || ny < 0 || nx >= width || ny >= height) return;
|
||||
const next = ny * width + nx;
|
||||
if (!mask[next] || labels[next] !== -1) return;
|
||||
labels[next] = label;
|
||||
stack.push(next);
|
||||
};
|
||||
visit(x - 1, y);
|
||||
visit(x + 1, y);
|
||||
visit(x, y - 1);
|
||||
visit(x, y + 1);
|
||||
}
|
||||
sizes.push(size);
|
||||
}
|
||||
const largest = sizes.reduce((best, value) => Math.max(best, value), 0);
|
||||
const min = largest * 0.2;
|
||||
for (let i = 0; i < mask.length; i++) {
|
||||
if (!mask[i]) continue;
|
||||
const label = labels[i];
|
||||
if (label >= 0 && sizes[label] < min) mask[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** Fills enclosed background so a subject's face and clothes stay covered. */
|
||||
export function fillHoles(mask: Uint8Array, width: number, height: number) {
|
||||
const outside = new Uint8Array(mask.length);
|
||||
const stack: number[] = [];
|
||||
const push = (x: number, y: number) => {
|
||||
if (x < 0 || y < 0 || x >= width || y >= height) return;
|
||||
const index = y * width + x;
|
||||
if (mask[index] || outside[index]) return;
|
||||
outside[index] = 1;
|
||||
stack.push(index);
|
||||
};
|
||||
for (let x = 0; x < width; x++) {
|
||||
add(x, 0);
|
||||
add(x, height - 1);
|
||||
push(x, 0);
|
||||
push(x, height - 1);
|
||||
}
|
||||
for (let y = 1; y < height - 1; y++) {
|
||||
add(0, y);
|
||||
add(width - 1, y);
|
||||
for (let y = 0; y < height; y++) {
|
||||
push(0, y);
|
||||
push(width - 1, y);
|
||||
}
|
||||
while (stack.length) {
|
||||
const index = stack.pop() as number;
|
||||
const x = index % width;
|
||||
const y = (index - x) / width;
|
||||
push(x - 1, y);
|
||||
push(x + 1, y);
|
||||
push(x, y - 1);
|
||||
push(x, y + 1);
|
||||
}
|
||||
for (let i = 0; i < mask.length; i++) {
|
||||
if (!mask[i] && !outside[i]) mask[i] = 255;
|
||||
}
|
||||
return [r / n / 255, g / n / 255, b / n / 255];
|
||||
}
|
||||
|
||||
function smooth(mask: Uint8Array, width: number, height: number) {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
@@ -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
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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));
|
||||
}
|
||||
@@ -30,7 +30,7 @@ export const EDIT_SECTIONS: EditSection[] = [
|
||||
{
|
||||
id: 'color',
|
||||
label: 'Color',
|
||||
hint: 'Curves, HSL, grading, black & white',
|
||||
hint: 'Curves, HSL, grading, redscale, black & white',
|
||||
defaultOn: true,
|
||||
},
|
||||
{
|
||||
@@ -81,6 +81,7 @@ const GROUPS: Record<EditSectionId, (keyof Edits)[]> = {
|
||||
light: [
|
||||
'temp',
|
||||
'tint',
|
||||
'kelvin',
|
||||
'exposure',
|
||||
'recovery',
|
||||
'contrast',
|
||||
@@ -94,7 +95,7 @@ const GROUPS: Record<EditSectionId, (keyof Edits)[]> = {
|
||||
'vibrance',
|
||||
'saturation',
|
||||
],
|
||||
color: ['bw', 'bwFilter', 'bwFilterAmount', 'curve', 'parametric', 'hsl', 'grading'],
|
||||
color: ['bw', 'bwFilter', 'bwFilterAmount', 'curve', 'levels', 'parametric', 'hsl', 'grading', 'redscale'],
|
||||
detail: ['sharpen', 'noise', 'defringe'],
|
||||
effects: ['vignette', 'grain', 'proof'],
|
||||
geometry: ['geometry'],
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
+75
-4
@@ -96,11 +96,27 @@ export function thumbTransform(photo: PhotoRecord, boxAspect = 4 / 3): string {
|
||||
/** The shader carries a fixed spot array; more than this would silently drop. */
|
||||
export const MAX_HEAL_SPOTS = 24;
|
||||
|
||||
/** Four masks are packed into one RGBA texture. */
|
||||
export const MAX_LOCAL_LAYERS = 4;
|
||||
/** Eight masks are packed into two RGBA textures. */
|
||||
export const MAX_LOCAL_LAYERS = 8;
|
||||
|
||||
export function defaultLocalAdjust(): LocalLayer['adjust'] {
|
||||
return { exposure: 0, contrast: 0, highlights: 0, shadows: 0, temp: 0, tint: 0, saturation: 0 };
|
||||
return {
|
||||
exposure: 0,
|
||||
contrast: 0,
|
||||
highlights: 0,
|
||||
shadows: 0,
|
||||
whites: 0,
|
||||
blacks: 0,
|
||||
temp: 0,
|
||||
tint: 0,
|
||||
saturation: 0,
|
||||
vibrance: 0,
|
||||
hue: 0,
|
||||
texture: 0,
|
||||
clarity: 0,
|
||||
dehaze: 0,
|
||||
sharpen: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLayer {
|
||||
@@ -108,6 +124,7 @@ export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLaye
|
||||
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
|
||||
name: `Local ${index + 1}`,
|
||||
kind,
|
||||
mode: 'add',
|
||||
inverted: false,
|
||||
feather: 50,
|
||||
brush: { strokes: [] },
|
||||
@@ -146,6 +163,7 @@ export function defaultEdits(): Edits {
|
||||
return {
|
||||
temp: 0,
|
||||
tint: 0,
|
||||
kelvin: null,
|
||||
exposure: 0,
|
||||
recovery: 0,
|
||||
contrast: 0,
|
||||
@@ -158,6 +176,7 @@ export function defaultEdits(): Edits {
|
||||
dehaze: 0,
|
||||
vibrance: 0,
|
||||
saturation: 0,
|
||||
redscale: 0,
|
||||
bw: false,
|
||||
bwFilter: 'none',
|
||||
bwFilterAmount: 100,
|
||||
@@ -167,6 +186,7 @@ export function defaultEdits(): Edits {
|
||||
green: identityCurve(),
|
||||
blue: identityCurve(),
|
||||
},
|
||||
levels: { black: 0, white: 100, gamma: 1 },
|
||||
parametric: { highlights: 0, lights: 0, darks: 0, blacks: 0 },
|
||||
hsl: {
|
||||
hue: HUE_BANDS.map(() => 0),
|
||||
@@ -179,7 +199,8 @@ export function defaultEdits(): Edits {
|
||||
balance: 0,
|
||||
},
|
||||
sharpen: { amount: 0, radius: 1, detail: 25, mask: 0, lensSoftness: 0 },
|
||||
proof: { enabled: false, paper: 'matte', blackPoint: 2, gamut: false },
|
||||
proof: { enabled: false, paper: 'matte', blackPoint: 2, gamut: false, intent: 'perceptual' },
|
||||
cameraProfile: null,
|
||||
noise: { luminance: 0, detail: 50, chroma: 0, chromaDetail: 50 },
|
||||
aiDenoise: { amount: 100, key: null, model: 'guided' },
|
||||
defringe: { purple: 0, green: 0 },
|
||||
@@ -264,6 +285,8 @@ function localLayers(input: unknown): LocalLayer[] {
|
||||
id: typeof layer.id === 'string' && layer.id ? layer.id : `local-${out.length}`,
|
||||
name: typeof layer.name === 'string' && layer.name.trim() ? layer.name.slice(0, 40) : `Local ${out.length + 1}`,
|
||||
kind,
|
||||
mode:
|
||||
layer.mode === 'subtract' || layer.mode === 'intersect' ? layer.mode : 'add',
|
||||
inverted: !!layer.inverted,
|
||||
feather: num(layer.feather, 50, 0, 100),
|
||||
brush: { strokes: localStrokes(layer.brush?.strokes) },
|
||||
@@ -293,9 +316,17 @@ function localLayers(input: unknown): LocalLayer[] {
|
||||
contrast: num(adjust.contrast, 0, -100, 100),
|
||||
highlights: num(adjust.highlights, 0, -100, 100),
|
||||
shadows: num(adjust.shadows, 0, -100, 100),
|
||||
whites: num(adjust.whites, 0, -100, 100),
|
||||
blacks: num(adjust.blacks, 0, -100, 100),
|
||||
temp: num(adjust.temp, 0, -100, 100),
|
||||
tint: num(adjust.tint, 0, -100, 100),
|
||||
saturation: num(adjust.saturation, 0, -100, 100),
|
||||
vibrance: num(adjust.vibrance, 0, -100, 100),
|
||||
hue: num(adjust.hue, 180, -180, 180),
|
||||
texture: num(adjust.texture, 0, -100, 100),
|
||||
clarity: num(adjust.clarity, 0, -100, 100),
|
||||
dehaze: num(adjust.dehaze, 0, -100, 100),
|
||||
sharpen: num(adjust.sharpen, 0, -100, 100),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -338,10 +369,28 @@ function lensProfile(input: unknown): LensProfile | undefined {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a stored camera profile usable: a profile with a missing or non-finite
|
||||
* matrix would black out the photo, so it is dropped instead.
|
||||
*/
|
||||
export function normalizeCameraProfile(value: unknown): Edits['cameraProfile'] {
|
||||
if (!value || typeof value !== 'object') return null;
|
||||
const raw = value as { name?: unknown; matrix?: unknown };
|
||||
if (!Array.isArray(raw.matrix)) return null;
|
||||
const matrix = raw.matrix.slice(0, 9).map(Number);
|
||||
if (matrix.length !== 9 || !matrix.every(Number.isFinite)) return null;
|
||||
const name =
|
||||
typeof raw.name === 'string' && raw.name.trim()
|
||||
? raw.name.trim().slice(0, 80)
|
||||
: 'Camera profile';
|
||||
return { name, matrix };
|
||||
}
|
||||
|
||||
export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits {
|
||||
const d = defaultEdits();
|
||||
if (!input) return d;
|
||||
const curve = (input.curve ?? {}) as Partial<Edits['curve']>;
|
||||
const levels = (input.levels ?? {}) as Partial<Edits['levels']>;
|
||||
const parametric = (input.parametric ?? {}) as Partial<Edits['parametric']>;
|
||||
const grading = (input.grading ?? {}) as Partial<Edits['grading']>;
|
||||
const sharpen = (input.sharpen ?? {}) as Partial<Edits['sharpen']>;
|
||||
@@ -355,6 +404,7 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
|
||||
return {
|
||||
...d,
|
||||
...input,
|
||||
cameraProfile: normalizeCameraProfile(input.cameraProfile),
|
||||
aiDenoise: {
|
||||
amount: num(aiDenoise.amount, d.aiDenoise.amount, 0, 100),
|
||||
key: typeof aiDenoise.key === 'string' && aiDenoise.key ? aiDenoise.key : null,
|
||||
@@ -362,6 +412,10 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
|
||||
},
|
||||
temp: num(input.temp, 0, -100, 100),
|
||||
tint: num(input.tint, 0, -100, 100),
|
||||
kelvin:
|
||||
typeof input.kelvin === 'number' && Number.isFinite(input.kelvin)
|
||||
? clamp(input.kelvin, 1500, 15000)
|
||||
: null,
|
||||
exposure: num(input.exposure, 0, -5, 5),
|
||||
recovery: num(input.recovery, 0, 0, 100),
|
||||
contrast: num(input.contrast, 0, -100, 100),
|
||||
@@ -374,6 +428,7 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
|
||||
dehaze: num(input.dehaze, 0, -100, 100),
|
||||
vibrance: num(input.vibrance, 0, -100, 100),
|
||||
saturation: num(input.saturation, 0, -100, 100),
|
||||
redscale: num(input.redscale, 0, 0, 100),
|
||||
bw: !!input.bw,
|
||||
bwFilter: BW_FILTERS.some((f) => f.id === input.bwFilter) ? (input.bwFilter as BwFilter) : 'none',
|
||||
bwFilterAmount: num(input.bwFilterAmount, d.bwFilterAmount, 0, 100),
|
||||
@@ -383,6 +438,14 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
|
||||
green: sanitizeCurve(curve.green),
|
||||
blue: sanitizeCurve(curve.blue),
|
||||
},
|
||||
levels: {
|
||||
black: num(levels.black, 0, 0, 45),
|
||||
white: Math.max(
|
||||
num(levels.black, 0, 0, 45) + 5,
|
||||
num(levels.white, 100, 55, 100),
|
||||
),
|
||||
gamma: num(levels.gamma, 1, 0.3, 3),
|
||||
},
|
||||
parametric: {
|
||||
highlights: num(parametric.highlights, 0, -100, 100),
|
||||
lights: num(parametric.lights, 0, -100, 100),
|
||||
@@ -417,6 +480,10 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
|
||||
paper: input.proof?.paper === 'gloss' || input.proof?.paper === 'newsprint' ? input.proof.paper : 'matte',
|
||||
blackPoint: num(input.proof?.blackPoint, 2, 0, 20),
|
||||
gamut: !!input.proof?.gamut,
|
||||
intent:
|
||||
input.proof?.intent === 'relative' || input.proof?.intent === 'saturation'
|
||||
? input.proof.intent
|
||||
: 'perceptual',
|
||||
},
|
||||
noise: {
|
||||
luminance: num(noise.luminance, 0, 0, 100),
|
||||
@@ -489,6 +556,10 @@ export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): Ph
|
||||
decode: input.decode,
|
||||
previewUrl: input.previewUrl,
|
||||
thumbUrl: input.thumbUrl,
|
||||
previewVersion:
|
||||
typeof input.previewVersion === 'number' && Number.isFinite(input.previewVersion)
|
||||
? input.previewVersion
|
||||
: undefined,
|
||||
proofAt: typeof input.proofAt === 'number' && Number.isFinite(input.proofAt) ? input.proofAt : undefined,
|
||||
name: input.name ?? 'Untitled',
|
||||
width: input.width ?? 0,
|
||||
|
||||
+45
-15
@@ -1,11 +1,12 @@
|
||||
import type { Edits, PhotoRecord } from '../types';
|
||||
import { getBitmap } from './images';
|
||||
import { get16BitSource, getBitmap } from './images';
|
||||
import { normalizeEdits } from './edits';
|
||||
import { buildLensCorrection } from './lensfun';
|
||||
import { buildLensCorrection } from './lensEngine';
|
||||
import { outputSize, Renderer } from '../gl/renderer';
|
||||
import { getDenoisedBitmap } from './images';
|
||||
import { createZipBlob, zipFileName } from './zip';
|
||||
import { srgbProfile } from './icc';
|
||||
import { profileFor, type OutputColorSpace } from './icc';
|
||||
import { convertFloatPixels, convertImageData } from './colorSpace';
|
||||
import { encodeTiff16 } from './tiff';
|
||||
|
||||
export type ExportFormat = 'jpeg' | 'png' | 'webp' | 'tiff16';
|
||||
@@ -16,6 +17,8 @@ export type WatermarkPosition = 'br' | 'bl' | 'tr' | 'tl' | 'center';
|
||||
export interface ExportOptions {
|
||||
format: ExportFormat;
|
||||
quality: number;
|
||||
/** Delivery colour space; affects pixels and the embedded ICC profile. */
|
||||
colorSpace: OutputColorSpace;
|
||||
resize: ResizeMode;
|
||||
longEdge: number;
|
||||
percent: number;
|
||||
@@ -46,6 +49,7 @@ export interface ExportRecipe {
|
||||
export const DEFAULT_EXPORT: ExportOptions = {
|
||||
format: 'jpeg',
|
||||
quality: 92,
|
||||
colorSpace: 'srgb',
|
||||
resize: 'none',
|
||||
longEdge: 3000,
|
||||
percent: 100,
|
||||
@@ -114,7 +118,12 @@ function targetSize(photo: PhotoRecord, edits: Edits, bitmap: ImageBitmap, opts:
|
||||
};
|
||||
}
|
||||
|
||||
export async function renderPhotoBlob(photo: PhotoRecord, opts: ExportOptions): Promise<Blob> {
|
||||
export async function renderPhotoBlob(
|
||||
photo: PhotoRecord,
|
||||
opts: ExportOptions,
|
||||
/** Reuse one WebGL renderer across a batch instead of one context per photo. */
|
||||
sharedRenderer?: Renderer,
|
||||
): Promise<Blob> {
|
||||
const bitmap = await getBitmap(photo);
|
||||
const base = normalizeEdits(photo.edits);
|
||||
const edits = opts.outputSharpen > 0
|
||||
@@ -125,12 +134,17 @@ export async function renderPhotoBlob(photo: PhotoRecord, opts: ExportOptions):
|
||||
// Let the shader use its Catmull-Rom path when the crop is being enlarged,
|
||||
// so an intentional 150–200% export does not turn into a bilinear blur.
|
||||
const upscale = w > native.w * 1.05 || h > native.h * 1.05;
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 1;
|
||||
canvas.height = 1;
|
||||
const renderer = new Renderer(canvas);
|
||||
const canvas = sharedRenderer ? sharedRenderer.canvas : document.createElement('canvas');
|
||||
if (!sharedRenderer) {
|
||||
canvas.width = 1;
|
||||
canvas.height = 1;
|
||||
}
|
||||
const renderer = sharedRenderer ?? new Renderer(canvas);
|
||||
try {
|
||||
renderer.setImage(bitmap);
|
||||
// The sidecar is what makes a 16-bit TIFF export genuinely 16-bit rather
|
||||
// than a 65,536-code container around 256 real levels.
|
||||
const hdr = await get16BitSource(photo).catch(() => null);
|
||||
renderer.setImage(bitmap, hdr);
|
||||
// Forgetting this is how denoise silently goes missing from exports: the
|
||||
// preview and the file would be graded from different pixels.
|
||||
if (edits.aiDenoise.key) {
|
||||
@@ -141,26 +155,28 @@ export async function renderPhotoBlob(photo: PhotoRecord, opts: ExportOptions):
|
||||
? await buildLensCorrection(edits.lens, { width: bitmap.width, height: bitmap.height, meta: photo.meta })
|
||||
: null;
|
||||
|
||||
const space: OutputColorSpace = opts.colorSpace ?? 'srgb';
|
||||
if (opts.format === 'tiff16') {
|
||||
if (opts.watermark.enabled && opts.watermark.text.trim()) {
|
||||
throw new Error('Watermarking is not available for 16-bit TIFF exports');
|
||||
}
|
||||
const pixels = renderer.render(edits, { width: w, height: h, lens, upscale, floatOut: true });
|
||||
let pixels = renderer.render(edits, { width: w, height: h, lens, upscale, floatOut: true });
|
||||
if (!pixels) throw new Error('Could not read the 16-bit render');
|
||||
pixels = convertFloatPixels(pixels, space);
|
||||
return encodeTiff16({
|
||||
width: w,
|
||||
height: h,
|
||||
pixels,
|
||||
icc: opts.embedProfile ? srgbProfile() : null,
|
||||
icc: opts.embedProfile ? profileFor(space) : null,
|
||||
});
|
||||
}
|
||||
|
||||
renderer.render(edits, { width: w, height: h, lens, upscale });
|
||||
renderer.finishGpu();
|
||||
|
||||
let output = canvas;
|
||||
let output = space === 'srgb' ? canvas : convertCanvas(canvas, space);
|
||||
if (opts.watermark.enabled && opts.watermark.text.trim()) {
|
||||
output = paintWatermark(canvas, photo, opts);
|
||||
output = paintWatermark(output, photo, opts);
|
||||
}
|
||||
const mime = MIME[opts.format];
|
||||
let blob = await new Promise<Blob | null>((resolve) =>
|
||||
@@ -171,15 +187,29 @@ export async function renderPhotoBlob(photo: PhotoRecord, opts: ExportOptions):
|
||||
blob = await embedJpegMetadata(
|
||||
blob,
|
||||
opts.metadata ? buildXmp(photo) : '',
|
||||
opts.embedProfile ? srgbProfile() : null,
|
||||
opts.embedProfile ? profileFor(space) : null,
|
||||
);
|
||||
}
|
||||
return blob;
|
||||
} finally {
|
||||
renderer.dispose();
|
||||
// A caller-owned renderer outlives the photo, so it is theirs to dispose.
|
||||
if (!sharedRenderer) renderer.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
function convertCanvas(source: HTMLCanvasElement, space: OutputColorSpace) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = source.width;
|
||||
canvas.height = source.height;
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||
if (!ctx) return source;
|
||||
ctx.drawImage(source, 0, 0);
|
||||
const image = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
convertImageData(image.data, space);
|
||||
ctx.putImageData(image, 0, 0);
|
||||
return canvas;
|
||||
}
|
||||
|
||||
function paintWatermark(source: HTMLCanvasElement, photo: PhotoRecord, opts: ExportOptions) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = source.width;
|
||||
|
||||
+84
-18
@@ -1,13 +1,54 @@
|
||||
/**
|
||||
* A small, self-contained ICC v2 sRGB display profile.
|
||||
* Self-contained ICC v2 display profiles, generated rather than shipped as
|
||||
* binary assets.
|
||||
*
|
||||
* It is generated rather than shipped as a binary so the export pipeline can
|
||||
* tag sRGB files without adding a third-party profile asset. The matrix and
|
||||
* gamma describe the standard sRGB primaries; the browser already converted
|
||||
* the working pixels into sRGB when it decoded the source image.
|
||||
* sRGB, Display P3 and Adobe RGB (1998) are all RGB display spaces, so one
|
||||
* builder covers them: only the primaries, transfer curve and description
|
||||
* change. The primaries are the D50-adapted values an ICC profile expects; the
|
||||
* pixels themselves are converted by `colorSpace.ts` before encoding.
|
||||
*/
|
||||
|
||||
let cached: Uint8Array | null = null;
|
||||
export type OutputColorSpace = 'srgb' | 'p3' | 'adobe';
|
||||
|
||||
interface SpaceDefinition {
|
||||
description: string;
|
||||
/** D50-adapted XYZ of the red, green and blue primaries. */
|
||||
primaries: [[number, number, number], [number, number, number], [number, number, number]];
|
||||
/** sRGB piecewise curve, or a straight display gamma. */
|
||||
transfer: 'srgb' | number;
|
||||
}
|
||||
|
||||
const SPACES: Record<OutputColorSpace, SpaceDefinition> = {
|
||||
srgb: {
|
||||
description: 'sRGB IEC61966-2.1 (Luminary)',
|
||||
primaries: [
|
||||
[0.4360747, 0.2225045, 0.0139322],
|
||||
[0.3850649, 0.7168786, 0.0971045],
|
||||
[0.1430804, 0.0606169, 0.7141733],
|
||||
],
|
||||
transfer: 'srgb',
|
||||
},
|
||||
p3: {
|
||||
description: 'Display P3 (Luminary)',
|
||||
primaries: [
|
||||
[0.5151188, 0.2411894, -0.0010657],
|
||||
[0.2919771, 0.6922441, 0.0418837],
|
||||
[0.1571035, 0.0665752, 0.7845088],
|
||||
],
|
||||
transfer: 'srgb',
|
||||
},
|
||||
adobe: {
|
||||
description: 'Adobe RGB (1998) (Luminary)',
|
||||
primaries: [
|
||||
[0.6097559, 0.3111242, 0.0194811],
|
||||
[0.2052401, 0.625656, 0.0608899],
|
||||
[0.1493582, 0.0632197, 0.7446702],
|
||||
],
|
||||
transfer: 2.2,
|
||||
},
|
||||
};
|
||||
|
||||
const cache = new Map<OutputColorSpace, Uint8Array>();
|
||||
|
||||
function be32(out: DataView, offset: number, value: number) {
|
||||
out.setUint32(offset, value >>> 0, false);
|
||||
@@ -39,7 +80,7 @@ function xyzTag(x: number, y: number, z: number) {
|
||||
return data;
|
||||
}
|
||||
|
||||
function curveTag() {
|
||||
function srgbCurveTag() {
|
||||
// ICC v2 curveType with the piecewise sRGB transfer function sampled at
|
||||
// 1024 points. A gamma-2.2 shortcut is close, but this is exact to the
|
||||
// standard (within 16-bit quantisation) and still readable by old CMMs.
|
||||
@@ -59,6 +100,16 @@ function curveTag() {
|
||||
return data;
|
||||
}
|
||||
|
||||
function gammaCurveTag(gamma: number) {
|
||||
// A one-entry curveType stores the gamma as u8Fixed8; 2.2 -> 563.
|
||||
const data = new Uint8Array(14);
|
||||
const view = new DataView(data.buffer);
|
||||
data.set(ascii('curv'), 0);
|
||||
be32(view, 8, 1);
|
||||
be16(view, 12, Math.round(gamma * 256));
|
||||
return data;
|
||||
}
|
||||
|
||||
function descTag(text: string) {
|
||||
const value = new TextEncoder().encode(text);
|
||||
const size = pad4(12 + value.length + 1 + 4 + 4);
|
||||
@@ -83,20 +134,24 @@ function textTag(text: string) {
|
||||
return data;
|
||||
}
|
||||
|
||||
export function srgbProfile(): Uint8Array {
|
||||
if (cached) return cached;
|
||||
function buildProfile(space: OutputColorSpace): Uint8Array {
|
||||
const definition = SPACES[space];
|
||||
const curve =
|
||||
definition.transfer === 'srgb' ? srgbCurveTag() : gammaCurveTag(definition.transfer);
|
||||
const [r, g, b] = definition.primaries;
|
||||
|
||||
// sRGB primaries adapted to the D50 profile connection space.
|
||||
const tags: { sig: string; data: Uint8Array }[] = [
|
||||
{ sig: 'desc', data: descTag('sRGB IEC61966-2.1 (Luminary)') },
|
||||
{ sig: 'desc', data: descTag(definition.description) },
|
||||
{ sig: 'cprt', data: textTag('No copyright, use freely') },
|
||||
{ sig: 'wtpt', data: xyzTag(0.9642, 1.0, 0.8249) },
|
||||
{ sig: 'rXYZ', data: xyzTag(0.4360747, 0.2225045, 0.0139322) },
|
||||
{ sig: 'gXYZ', data: xyzTag(0.3850649, 0.7168786, 0.0971045) },
|
||||
{ sig: 'bXYZ', data: xyzTag(0.1430804, 0.0606169, 0.7141733) },
|
||||
{ sig: 'rTRC', data: curveTag() },
|
||||
{ sig: 'gTRC', data: curveTag() },
|
||||
{ sig: 'bTRC', data: curveTag() },
|
||||
{ sig: 'rXYZ', data: xyzTag(r[0], r[1], r[2]) },
|
||||
{ sig: 'gXYZ', data: xyzTag(g[0], g[1], g[2]) },
|
||||
{ sig: 'bXYZ', data: xyzTag(b[0], b[1], b[2]) },
|
||||
// All three channels share the transfer function; the writer copies the
|
||||
// bytes at each tag's own offset.
|
||||
{ sig: 'rTRC', data: curve },
|
||||
{ sig: 'gTRC', data: curve },
|
||||
{ sig: 'bTRC', data: curve },
|
||||
];
|
||||
|
||||
const tableSize = 4 + tags.length * 12;
|
||||
@@ -147,6 +202,17 @@ export function srgbProfile(): Uint8Array {
|
||||
data.set(tag.data, tag.at);
|
||||
});
|
||||
|
||||
cached = data;
|
||||
return data;
|
||||
}
|
||||
|
||||
export function profileFor(space: OutputColorSpace): Uint8Array {
|
||||
const hit = cache.get(space);
|
||||
if (hit) return hit;
|
||||
const profile = buildProfile(space);
|
||||
cache.set(space, profile);
|
||||
return profile;
|
||||
}
|
||||
|
||||
export function srgbProfile(): Uint8Array {
|
||||
return profileFor('srgb');
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { PhotoRecord } from '../types';
|
||||
import { getAsset, putAsset } from './db';
|
||||
import { parsePreview16, type Preview16 } from './preview16';
|
||||
|
||||
const CACHE_LIMIT = 6;
|
||||
const cache = new Map<string, ImageBitmap>();
|
||||
@@ -93,11 +94,97 @@ export function evictBitmap(photoId: string) {
|
||||
bmp.close();
|
||||
}
|
||||
|
||||
const hdrCache = new Map<string, Preview16 | null>();
|
||||
|
||||
/** Version stamp from the preview URL, so a reprocess invalidates the sidecar too. */
|
||||
function preview16Url(photo: PhotoRecord): string {
|
||||
const base = `/api/photos/${encodeURIComponent(photo.id)}/preview16`;
|
||||
const query = (photo.previewUrl ?? '').split('?')[1];
|
||||
return query ? `${base}?${query}` : base;
|
||||
}
|
||||
|
||||
/**
|
||||
* The 16-bit samples behind a raw proxy, or null when there are none.
|
||||
*
|
||||
* Null is normal, not an error: photos imported before the sidecar existed,
|
||||
* non-raw files and oversized fetches all end up grading the JPEG. Only a 404
|
||||
* is remembered, so a dropped connection is retried on the next look.
|
||||
*/
|
||||
export async function get16BitSource(photo: PhotoRecord): Promise<Preview16 | null> {
|
||||
if (!photo.raw) return null;
|
||||
const hit = hdrCache.get(photo.id);
|
||||
if (hit !== undefined) return hit;
|
||||
let parsed: Preview16 | null = null;
|
||||
let missing = false;
|
||||
try {
|
||||
const res = await fetch(preview16Url(photo), { credentials: 'same-origin' });
|
||||
if (!res.ok) {
|
||||
missing = true;
|
||||
} else {
|
||||
parsed = await parsePreview16(await res.arrayBuffer());
|
||||
missing = parsed === null;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (parsed) {
|
||||
hdrCache.set(photo.id, parsed);
|
||||
// Each sidecar is up to ~100 MB of typed array, so only the last two stay.
|
||||
while (hdrCache.size > 2) {
|
||||
const first = hdrCache.keys().next();
|
||||
if (first.done) break;
|
||||
hdrCache.delete(first.value);
|
||||
}
|
||||
} else if (missing) {
|
||||
hdrCache.set(photo.id, null);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
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() {
|
||||
cameraThumbCache.clear();
|
||||
for (const bmp of cache.values()) bmp.close();
|
||||
cache.clear();
|
||||
for (const bmp of denoisedCache.values()) bmp.close();
|
||||
denoisedCache.clear();
|
||||
hdrCache.clear();
|
||||
}
|
||||
|
||||
const denoisedCache = new Map<string, ImageBitmap>();
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,448 @@
|
||||
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. */
|
||||
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 };
|
||||
}
|
||||
@@ -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' });
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,191 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { halfBits, parsePreview16 } from './preview16';
|
||||
|
||||
/**
|
||||
* A stored-block zlib stream: valid deflate without a dependency, which is all
|
||||
* the parser needs to prove it reads a real PNG byte stream rather than a mock.
|
||||
*/
|
||||
function zlibStored(data: Uint8Array): Uint8Array {
|
||||
const blocks = Math.max(1, Math.ceil(data.length / 65535));
|
||||
const out = new Uint8Array(2 + data.length + blocks * 5 + 4);
|
||||
out[0] = 0x78;
|
||||
out[1] = 0x01;
|
||||
let at = 2;
|
||||
for (let b = 0; b < blocks; b++) {
|
||||
const start = b * 65535;
|
||||
const len = Math.min(65535, data.length - start);
|
||||
out[at++] = b === blocks - 1 ? 1 : 0;
|
||||
out[at++] = len & 0xff;
|
||||
out[at++] = (len >> 8) & 0xff;
|
||||
out[at++] = ~len & 0xff;
|
||||
out[at++] = (~len >> 8) & 0xff;
|
||||
out.set(data.subarray(start, start + len), at);
|
||||
at += len;
|
||||
}
|
||||
let a = 1;
|
||||
let c = 0;
|
||||
for (const byte of data) {
|
||||
a = (a + byte) % 65521;
|
||||
c = (c + a) % 65521;
|
||||
}
|
||||
out[at++] = (c >> 8) & 0xff;
|
||||
out[at++] = c & 0xff;
|
||||
out[at++] = (a >> 8) & 0xff;
|
||||
out[at++] = a & 0xff;
|
||||
return out;
|
||||
}
|
||||
|
||||
const CRC_TABLE = (() => {
|
||||
const table = new Int32Array(256);
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
table[n] = c;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(bytes: Uint8Array): number {
|
||||
let c = 0xffffffff;
|
||||
for (const byte of bytes) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
|
||||
return (c ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function concat(parts: Uint8Array[]): Uint8Array {
|
||||
const total = parts.reduce((n, p) => n + p.length, 0);
|
||||
const out = new Uint8Array(total);
|
||||
let at = 0;
|
||||
for (const part of parts) {
|
||||
out.set(part, at);
|
||||
at += part.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Mirror of the server encoder: 16-bit RGB, Sub-filtered rows. */
|
||||
function encodePng16(
|
||||
samples: number[][],
|
||||
width: number,
|
||||
height: number,
|
||||
text?: string,
|
||||
): ArrayBuffer {
|
||||
const stride = width * 6;
|
||||
const raw = new Uint8Array((stride + 1) * height);
|
||||
const row = new Uint8Array(stride);
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
const [r, g, b] = samples[y * width + x];
|
||||
row[x * 6] = (r >> 8) & 0xff;
|
||||
row[x * 6 + 1] = r & 0xff;
|
||||
row[x * 6 + 2] = (g >> 8) & 0xff;
|
||||
row[x * 6 + 3] = g & 0xff;
|
||||
row[x * 6 + 4] = (b >> 8) & 0xff;
|
||||
row[x * 6 + 5] = b & 0xff;
|
||||
}
|
||||
const base = y * (stride + 1);
|
||||
raw[base] = 1; // Sub
|
||||
for (let i = 0; i < stride; i++) raw[base + 1 + i] = (row[i] - (i >= 6 ? row[i - 6] : 0)) & 0xff;
|
||||
}
|
||||
const ihdr = new Uint8Array(13);
|
||||
ihdr[0] = (width >>> 24) & 0xff;
|
||||
ihdr[1] = (width >>> 16) & 0xff;
|
||||
ihdr[2] = (width >>> 8) & 0xff;
|
||||
ihdr[3] = width & 0xff;
|
||||
ihdr[4] = (height >>> 24) & 0xff;
|
||||
ihdr[5] = (height >>> 16) & 0xff;
|
||||
ihdr[6] = (height >>> 8) & 0xff;
|
||||
ihdr[7] = height & 0xff;
|
||||
ihdr[8] = 16;
|
||||
ihdr[9] = 2;
|
||||
|
||||
const chunk = (type: string, data: Uint8Array) => {
|
||||
const head = new Uint8Array(8 + data.length + 4);
|
||||
head[0] = (data.length >>> 24) & 0xff;
|
||||
head[1] = (data.length >>> 16) & 0xff;
|
||||
head[2] = (data.length >>> 8) & 0xff;
|
||||
head[3] = data.length & 0xff;
|
||||
for (let i = 0; i < 4; i++) head[4 + i] = type.charCodeAt(i);
|
||||
head.set(data, 8);
|
||||
const crc = crc32(concat([head.subarray(4, 8), data]));
|
||||
head[8 + data.length] = (crc >>> 24) & 0xff;
|
||||
head[9 + data.length] = (crc >>> 16) & 0xff;
|
||||
head[10 + data.length] = (crc >>> 8) & 0xff;
|
||||
head[11 + data.length] = crc & 0xff;
|
||||
return head;
|
||||
};
|
||||
const png = concat([
|
||||
new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
chunk('IHDR', ihdr),
|
||||
...(text ? [chunk('tEXt', new TextEncoder().encode(text))] : []),
|
||||
chunk('IDAT', zlibStored(raw)),
|
||||
chunk('IEND', new Uint8Array(0)),
|
||||
]);
|
||||
const copy = new Uint8Array(png.length);
|
||||
copy.set(png);
|
||||
return copy.buffer;
|
||||
}
|
||||
|
||||
describe('halfBits', () => {
|
||||
it('matches the reference encodings', () => {
|
||||
expect(halfBits(0)).toBe(0);
|
||||
expect(halfBits(1)).toBe(0x3c00);
|
||||
expect(halfBits(0.5)).toBe(0x3800);
|
||||
expect(halfBits(0.25)).toBe(0x3400);
|
||||
expect(halfBits(2)).toBe(0x3c00);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parsePreview16', () => {
|
||||
it('reads 16-bit samples back as half-float RGBA', async () => {
|
||||
const samples = [
|
||||
[0, 32768, 65535],
|
||||
[65535, 0, 32768],
|
||||
];
|
||||
const parsed = await parsePreview16(encodePng16(samples, 2, 1));
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed!.width).toBe(2);
|
||||
expect(parsed!.height).toBe(1);
|
||||
expect(Array.from(parsed!.rgba.slice(0, 4))).toEqual([0, 0x3800, 0x3c00, 0x3c00]);
|
||||
expect(Array.from(parsed!.rgba.slice(4, 8))).toEqual([0x3c00, 0, 0x3800, 0x3c00]);
|
||||
});
|
||||
|
||||
it('flips the rows so upload needs no UNPACK_FLIP_Y', async () => {
|
||||
const parsed = await parsePreview16(
|
||||
encodePng16(
|
||||
[
|
||||
[65535, 65535, 65535],
|
||||
[0, 0, 0],
|
||||
],
|
||||
1,
|
||||
2,
|
||||
),
|
||||
);
|
||||
expect(parsed).not.toBeNull();
|
||||
// Row 0 of the returned buffer is the last image row.
|
||||
expect(parsed!.rgba[0]).toBe(0);
|
||||
expect(parsed!.rgba[4]).toBe(0x3c00);
|
||||
});
|
||||
|
||||
it('reads the camera matrix out of the sidecar text chunk', async () => {
|
||||
const matrix = [1.66943598, -0.4847292, -0.18470675, -0.00096075, 1.25268972, -0.25172901, 0.04713935, -0.30006605, 1.25292671];
|
||||
const parsed = await parsePreview16(
|
||||
encodePng16([[1000, 2000, 3000]], 1, 1, `rgbCam\0${matrix.join(',')}`),
|
||||
);
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed!.rgbCam).toHaveLength(9);
|
||||
expect(parsed!.rgbCam![0]).toBeCloseTo(matrix[0], 6);
|
||||
expect(parsed!.rgbCam![8]).toBeCloseTo(matrix[8], 6);
|
||||
});
|
||||
|
||||
it('leaves rgbCam undefined for canister sRGB sidecars', async () => {
|
||||
const parsed = await parsePreview16(encodePng16([[1, 2, 3]], 1, 1));
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed!.rgbCam).toBeUndefined();
|
||||
});
|
||||
|
||||
it('rejects 8-bit or non-PNG input instead of guessing', async () => {
|
||||
const eight = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
expect(await parsePreview16(eight.buffer)).toBeNull();
|
||||
expect(await parsePreview16(new Uint8Array(64).buffer)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* Client half of the 16-bit raw proxy.
|
||||
*
|
||||
* The server keeps the samples LibRaw decoded in a 16-bit PNG next to the JPEG
|
||||
* proxy. Decoding that PNG here and uploading it as a half-float texture is what
|
||||
* lets a heavy grade work from 65,536 levels per channel instead of 256: the
|
||||
* JPEG proxy is still what ordinary imports and thumbnails use, so this is
|
||||
* always optional.
|
||||
*
|
||||
* The parser only accepts what the encoder writes (16-bit, non-interlaced,
|
||||
* RGB or RGBA) and returns the samples as half-float RGBA with the rows already
|
||||
* flipped, because `UNPACK_FLIP_Y_WEBGL` is ignored for ArrayBufferView uploads.
|
||||
*/
|
||||
|
||||
export interface Preview16 {
|
||||
width: number;
|
||||
height: number;
|
||||
/** RGBA half-float, rows bottom-up, ready for `texImage2D` without a flip. */
|
||||
rgba: Uint16Array;
|
||||
/**
|
||||
* Camera-to-sRGB matrix, row major, when the samples are camera native.
|
||||
* Absent on older sidecars, which already hold sRGB.
|
||||
*/
|
||||
rgbCam?: number[];
|
||||
}
|
||||
|
||||
const scratchFloat = new Float32Array(1);
|
||||
const scratchBits = new Uint32Array(scratchFloat.buffer);
|
||||
|
||||
/** IEEE-754 half representation of a unit value; 1 -> 0x3c00. */
|
||||
export function halfBits(value: number): number {
|
||||
if (!(value > 0)) return value < 0 ? 0x8000 : 0;
|
||||
if (value >= 1) return 0x3c00;
|
||||
scratchFloat[0] = value;
|
||||
const bits = scratchBits[0];
|
||||
const exponent = ((bits >>> 23) & 0xff) - (127 - 15);
|
||||
const mantissa = bits & 0x7fffff;
|
||||
if (exponent <= 0) {
|
||||
// Subnormal half: shift the implicit bit down and round to nearest.
|
||||
if (exponent < -10) return 0;
|
||||
const shift = 14 - exponent;
|
||||
const full = mantissa | 0x800000;
|
||||
return (full >>> shift) + ((full >>> (shift - 1)) & 1);
|
||||
}
|
||||
let half = (exponent << 10) | (mantissa >>> 13);
|
||||
const rest = mantissa & 0x1fff;
|
||||
if (rest > 0x1000 || (rest === 0x1000 && (half & 1) === 1)) half += 1;
|
||||
return half;
|
||||
}
|
||||
|
||||
let unitTable: Uint16Array | null = null;
|
||||
|
||||
/** 65,536-entry lookup so converting a 12-megapixel sidecar stays a table read. */
|
||||
function halfTable(): Uint16Array {
|
||||
if (!unitTable) {
|
||||
const table = new Uint16Array(65536);
|
||||
for (let i = 0; i < 65536; i++) table[i] = halfBits(i / 65535);
|
||||
unitTable = table;
|
||||
}
|
||||
return unitTable;
|
||||
}
|
||||
|
||||
function paeth(a: number, b: number, c: number): number {
|
||||
const p = a + b - c;
|
||||
const pa = Math.abs(p - a);
|
||||
const pb = Math.abs(p - b);
|
||||
const pc = Math.abs(p - c);
|
||||
if (pa <= pb && pa <= pc) return a;
|
||||
return pb <= pc ? b : c;
|
||||
}
|
||||
|
||||
/** Reverses the PNG row filters in place; PNG filters are byte-oriented. */
|
||||
function unfilter(data: Uint8Array, width: number, height: number, bpp: number): boolean {
|
||||
const stride = width * bpp;
|
||||
if (data.length < (stride + 1) * height) return false;
|
||||
for (let y = 0; y < height; y++) {
|
||||
const base = y * (stride + 1);
|
||||
const filter = data[base];
|
||||
const row = base + 1;
|
||||
const prev = row - (stride + 1);
|
||||
if (filter === 0) continue;
|
||||
if (filter === 1) {
|
||||
for (let i = bpp; i < stride; i++) data[row + i] = (data[row + i] + data[row + i - bpp]) & 0xff;
|
||||
} else if (filter === 2) {
|
||||
if (y === 0) continue;
|
||||
for (let i = 0; i < stride; i++) data[row + i] = (data[row + i] + data[prev + i]) & 0xff;
|
||||
} else if (filter === 3) {
|
||||
for (let i = 0; i < stride; i++) {
|
||||
const left = i >= bpp ? data[row + i - bpp] : 0;
|
||||
const up = y > 0 ? data[prev + i] : 0;
|
||||
data[row + i] = (data[row + i] + ((left + up) >> 1)) & 0xff;
|
||||
}
|
||||
} else if (filter === 4) {
|
||||
for (let i = 0; i < stride; i++) {
|
||||
const left = i >= bpp ? data[row + i - bpp] : 0;
|
||||
const up = y > 0 ? data[prev + i] : 0;
|
||||
const upLeft = y > 0 && i >= bpp ? data[prev + i - bpp] : 0;
|
||||
data[row + i] = (data[row + i] + paeth(left, up, upLeft)) & 0xff;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async function inflate(data: Uint8Array): Promise<Uint8Array | null> {
|
||||
try {
|
||||
// Copy into a plain ArrayBuffer: Blob parts cannot take a view whose buffer
|
||||
// might be a SharedArrayBuffer.
|
||||
const copy = new Uint8Array(data.byteLength);
|
||||
copy.set(data);
|
||||
const stream = new Blob([copy.buffer]).stream().pipeThrough(new DecompressionStream('deflate'));
|
||||
return new Uint8Array(await new Response(stream).arrayBuffer());
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a 16-bit RGB(A) PNG into half-float RGBA. Returns null for anything the
|
||||
* encoder would not have produced, so a corrupt or unexpectedly large sidecar
|
||||
* simply leaves the editor on the JPEG proxy.
|
||||
*/
|
||||
export async function parsePreview16(buffer: ArrayBuffer): Promise<Preview16 | null> {
|
||||
const bytes = new Uint8Array(buffer);
|
||||
if (bytes.length < 33) return null;
|
||||
if (bytes[0] !== 0x89 || bytes[1] !== 0x50 || bytes[2] !== 0x4e || bytes[3] !== 0x47) return null;
|
||||
const view = new DataView(buffer);
|
||||
let at = 8;
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
let depth = 0;
|
||||
let colorType = 0;
|
||||
let interlace = 0;
|
||||
let sawHeader = false;
|
||||
let rgbCam: number[] | undefined;
|
||||
const parts: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
while (at + 12 <= bytes.length) {
|
||||
const length = view.getUint32(at);
|
||||
if (at + 12 + length > bytes.length) return null;
|
||||
const type = String.fromCharCode(bytes[at + 4], bytes[at + 5], bytes[at + 6], bytes[at + 7]);
|
||||
const data = bytes.subarray(at + 8, at + 8 + length);
|
||||
if (type === 'IHDR') {
|
||||
if (length < 13) return null;
|
||||
width = view.getUint32(at + 8);
|
||||
height = view.getUint32(at + 12);
|
||||
depth = bytes[at + 16];
|
||||
colorType = bytes[at + 17];
|
||||
interlace = bytes[at + 20];
|
||||
sawHeader = true;
|
||||
} else if (type === 'IDAT') {
|
||||
parts.push(data);
|
||||
total += data.length;
|
||||
} else if (type === 'tEXt') {
|
||||
// Self-describing sidecars: the camera matrix is written next to the
|
||||
// pixels, so a sidecar and the matrix that converts it never split.
|
||||
const zero = data.indexOf(0);
|
||||
if (zero > 0) {
|
||||
const keyword = String.fromCharCode(...data.subarray(0, zero));
|
||||
if (keyword === 'rgbCam') {
|
||||
const text = String.fromCharCode(...data.subarray(zero + 1));
|
||||
const values = text.split(',').map(Number);
|
||||
if (values.length === 9 && values.every((value) => Number.isFinite(value))) {
|
||||
rgbCam = values;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (type === 'IEND') {
|
||||
break;
|
||||
}
|
||||
at += 12 + length;
|
||||
}
|
||||
if (!sawHeader || !width || !height) return null;
|
||||
if (depth !== 16 || interlace !== 0) return null;
|
||||
const channels = colorType === 2 ? 3 : colorType === 6 ? 4 : 0;
|
||||
if (!channels || total === 0) return null;
|
||||
|
||||
const idat = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const part of parts) {
|
||||
idat.set(part, offset);
|
||||
offset += part.length;
|
||||
}
|
||||
const raw = await inflate(idat);
|
||||
if (!raw) return null;
|
||||
|
||||
const bpp = channels * 2;
|
||||
const stride = width * bpp;
|
||||
if (raw.length < (stride + 1) * height) return null;
|
||||
if (!unfilter(raw, width, height, bpp)) return null;
|
||||
|
||||
const table = halfTable();
|
||||
const rgba = new Uint16Array(width * height * 4);
|
||||
const opaque = table[65535];
|
||||
let out = 0;
|
||||
for (let y = height - 1; y >= 0; y--) {
|
||||
// Bottom-up: the texture upload cannot flip an ArrayBufferView.
|
||||
let src = y * (stride + 1) + 1;
|
||||
for (let x = 0; x < width; x++) {
|
||||
rgba[out++] = table[(raw[src] << 8) | raw[src + 1]];
|
||||
rgba[out++] = table[(raw[src + 2] << 8) | raw[src + 3]];
|
||||
rgba[out++] = table[(raw[src + 4] << 8) | raw[src + 5]];
|
||||
rgba[out++] = opaque;
|
||||
src += bpp;
|
||||
}
|
||||
}
|
||||
return { width, height, rgba, ...(rgbCam ? { rgbCam } : {}) };
|
||||
}
|
||||
@@ -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/);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { kelvinGains, wbGainFor, WB_REFERENCE_KELVIN } from './whiteBalance';
|
||||
|
||||
describe('absolute white balance', () => {
|
||||
it('is neutral at the daylight reference', () => {
|
||||
const gain = kelvinGains(WB_REFERENCE_KELVIN);
|
||||
expect(gain[0]).toBeCloseTo(1, 2);
|
||||
expect(gain[1]).toBeCloseTo(1, 2);
|
||||
expect(gain[2]).toBeCloseTo(1, 2);
|
||||
});
|
||||
|
||||
it('warms a tungsten scene by lifting blue and pulling red', () => {
|
||||
const gain = kelvinGains(3200);
|
||||
expect(gain[2]).toBeGreaterThan(1.4);
|
||||
expect(gain[0]).toBeLessThan(1);
|
||||
expect(gain[1]).toBeCloseTo(1, 2);
|
||||
});
|
||||
|
||||
it('cools a high-temperature scene by lifting red', () => {
|
||||
const gain = kelvinGains(9000);
|
||||
expect(gain[0]).toBeGreaterThan(1);
|
||||
expect(gain[2]).toBeLessThan(1);
|
||||
});
|
||||
|
||||
it('keeps the relative sliders neutral at zero and normalises luminance', () => {
|
||||
const neutral = wbGainFor(0, 0, null);
|
||||
expect(neutral[0]).toBeCloseTo(1, 5);
|
||||
expect(neutral[1]).toBeCloseTo(1, 5);
|
||||
expect(neutral[2]).toBeCloseTo(1, 5);
|
||||
for (const gain of [wbGainFor(40, 20, null), wbGainFor(0, 0, 3200)]) {
|
||||
const luma = 0.2126 * gain[0] + 0.7152 * gain[1] + 0.0722 * gain[2];
|
||||
expect(luma).toBeCloseTo(1, 4);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,90 @@ function toLinear(v: number): number {
|
||||
|
||||
const clampRange = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
|
||||
|
||||
/** Reference illuminant for the absolute Kelvin control; daylight-balanced. */
|
||||
export const WB_REFERENCE_KELVIN = 5500;
|
||||
|
||||
/** CIE 1931 chromaticity of a black body at `kelvin` (Kim et al. approximation). */
|
||||
export function planckianXy(kelvin: number): { x: number; y: number } {
|
||||
const t = clampRange(kelvin, 1667, 25000);
|
||||
const x =
|
||||
t <= 4000
|
||||
? -0.2661239e9 / (t * t * t) -
|
||||
0.2343589e6 / (t * t) +
|
||||
0.8776956e3 / t +
|
||||
0.17991
|
||||
: -3.0258469e9 / (t * t * t) +
|
||||
2.1070379e6 / (t * t) +
|
||||
0.2226347e3 / t +
|
||||
0.24039;
|
||||
let y: number;
|
||||
if (t <= 2222) {
|
||||
y = -1.1063814 * x ** 3 - 1.3481102 * x ** 2 + 2.18555832 * x - 0.20219683;
|
||||
} else if (t <= 4000) {
|
||||
y = -0.9549476 * x ** 3 - 1.37418593 * x ** 2 + 2.09137015 * x - 0.16748867;
|
||||
} else {
|
||||
y = 3.081758 * x ** 3 - 5.8733867 * x ** 2 + 3.75112997 * x - 0.37001483;
|
||||
}
|
||||
// Guard the fit at the extremes; outside the Planckian locus it can drift.
|
||||
if (!Number.isFinite(y) || y <= 0.001) y = Math.max(0.001, 2 / (x * 1000 + 2));
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
/* sRGB primaries, D65 white. */
|
||||
const XYZ_TO_LINEAR_SRGB: readonly (readonly [number, number, number])[] = [
|
||||
[3.2404542, -1.5371385, -0.4985314],
|
||||
[-0.969266, 1.8760108, 0.041556],
|
||||
[0.0556434, -0.2040259, 1.0572252],
|
||||
];
|
||||
|
||||
function whiteForKelvin(kelvin: number): [number, number, number] {
|
||||
const { x, y } = planckianXy(kelvin);
|
||||
const X = x / y;
|
||||
const Y = 1;
|
||||
const Z = (1 - x - y) / y;
|
||||
return [
|
||||
XYZ_TO_LINEAR_SRGB[0][0] * X + XYZ_TO_LINEAR_SRGB[0][1] * Y + XYZ_TO_LINEAR_SRGB[0][2] * Z,
|
||||
XYZ_TO_LINEAR_SRGB[1][0] * X + XYZ_TO_LINEAR_SRGB[1][1] * Y + XYZ_TO_LINEAR_SRGB[1][2] * Z,
|
||||
XYZ_TO_LINEAR_SRGB[2][0] * X + XYZ_TO_LINEAR_SRGB[2][1] * Y + XYZ_TO_LINEAR_SRGB[2][2] * Z,
|
||||
].map((v) => Math.max(1e-4, v)) as [number, number, number];
|
||||
}
|
||||
|
||||
/**
|
||||
* Linear-light channel gains that treat the scene as lit at `kelvin` and render
|
||||
* it neutral, relative to the 5500 K daylight balance of the proxy. A lower
|
||||
* Kelvin warms the picture (as if correcting tungsten), a higher one cools it.
|
||||
* Green is normalised to 1 so the control changes colour, not exposure.
|
||||
*/
|
||||
export function kelvinGains(kelvin: number): [number, number, number] {
|
||||
const ref = whiteForKelvin(WB_REFERENCE_KELVIN);
|
||||
const white = whiteForKelvin(kelvin);
|
||||
const g = ref[1] / white[1];
|
||||
return [ref[0] / white[0] / g, 1, ref[2] / white[2] / g].map((v) =>
|
||||
Number.isFinite(v) ? Math.max(0.05, v) : 1,
|
||||
) as [number, number, number];
|
||||
}
|
||||
|
||||
/** The gain the grade shader applies for the current white-balance controls. */
|
||||
export function wbGainFor(
|
||||
temp: number,
|
||||
tint: number,
|
||||
kelvin: number | null,
|
||||
): [number, number, number] {
|
||||
const t = temp / 100;
|
||||
const ti = tint / 100;
|
||||
let gain: [number, number, number] = kelvin
|
||||
? kelvinGains(kelvin)
|
||||
: [1 + 0.3 * t, 1, 1 - 0.26 * t];
|
||||
gain = [
|
||||
gain[0] * (1 + 0.06 * ti),
|
||||
gain[1] * (1 - 0.16 * ti),
|
||||
gain[2] * (1 + 0.06 * ti),
|
||||
];
|
||||
const l = 0.2126 * gain[0] + 0.7152 * gain[1] + 0.0722 * gain[2];
|
||||
const norm = Math.max(0.05, l);
|
||||
return gain.map((v) => v / norm) as [number, number, number];
|
||||
}
|
||||
|
||||
/**
|
||||
* Temperature and tint that make a sampled source colour neutral.
|
||||
* `sample` is the untouched (sRGB-encoded) source pixel, 0–1 per channel.
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { defaultEdits, normalizeEdits } from './edits';
|
||||
import { editsToXmp, xmpFileName, xmpToEdits } from './xmp';
|
||||
|
||||
describe('xmp sidecars', () => {
|
||||
it('round-trips every develop field exactly', () => {
|
||||
const edits = defaultEdits();
|
||||
edits.exposure = 0.65;
|
||||
edits.temp = -14;
|
||||
edits.kelvin = 4200;
|
||||
edits.contrast = 22;
|
||||
edits.parametric.darks = -17;
|
||||
edits.hsl.hue[3] = 12;
|
||||
edits.grain.roughness = 71;
|
||||
edits.local = [
|
||||
{
|
||||
...defaultEdits().local[0],
|
||||
kind: 'linear',
|
||||
linear: { x1: 0.1, y1: 0.2, x2: 0.8, y2: 0.9 },
|
||||
},
|
||||
];
|
||||
|
||||
const xml = editsToXmp(edits);
|
||||
const back = xmpToEdits(xml, defaultEdits());
|
||||
expect(back.source).toBe('luminary');
|
||||
// Sanitising on the way in is allowed; it must not change any value.
|
||||
expect(back.edits).toEqual(normalizeEdits(edits));
|
||||
});
|
||||
|
||||
it('reads crs fields written by Lightroom', () => {
|
||||
const xml = `<?xpacket begin=""?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:Exposure2012="1.25" crs:Contrast2012="-18" crs:Clarity2012="34" crs:GrainAmount="40" crs:ConvertToGrayscale="True"/></rdf:RDF></x:xmpmeta>`;
|
||||
const base = defaultEdits();
|
||||
base.saturation = 9;
|
||||
const result = xmpToEdits(xml, base);
|
||||
expect(result.source).toBe('lightroom');
|
||||
expect(result.edits.exposure).toBe(1.25);
|
||||
expect(result.edits.contrast).toBe(-18);
|
||||
expect(result.edits.clarity).toBe(34);
|
||||
expect(result.edits.grain.amount).toBe(40);
|
||||
expect(result.edits.bw).toBe(true);
|
||||
// Fields the sidecar does not mention keep the photo's own settings.
|
||||
expect(result.edits.saturation).toBe(9);
|
||||
});
|
||||
|
||||
it('reads an absolute Kelvin temperature written by Lightroom', () => {
|
||||
const xml = `<?xpacket begin=""?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:Temperature="3800" crs:Tint="12" crs:Exposure2012="0.4"/></rdf:RDF></x:xmpmeta>`;
|
||||
const result = xmpToEdits(xml, defaultEdits());
|
||||
expect(result.edits.kelvin).toBe(3800);
|
||||
expect(result.edits.tint).toBe(12);
|
||||
expect(result.applied).toContain('Temperature');
|
||||
});
|
||||
|
||||
it('rejects a file that is not a sidecar', () => {
|
||||
expect(() => xmpToEdits('<html></html>', defaultEdits())).toThrow(/not an XMP/);
|
||||
});
|
||||
|
||||
it('names the sidecar after the photo', () => {
|
||||
expect(xmpFileName('DSC0123.ARW')).toBe('DSC0123.xmp');
|
||||
expect(xmpFileName('no-extension')).toBe('no-extension.xmp');
|
||||
});
|
||||
});
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
import type { Edits, PhotoRecord } from '../types';
|
||||
import { normalizeEdits } from './edits';
|
||||
|
||||
/**
|
||||
* Lightroom-compatible XMP sidecars.
|
||||
*
|
||||
* The crs: attributes are the shared vocabulary, so a sidecar written here
|
||||
* carries the grade into Lightroom and one written by Lightroom opens here.
|
||||
* Lightroom has no slot for everything Luminary can do (film curves, HSL,
|
||||
* local layers, denoise), so the full edit is also written to a private
|
||||
* `lum:Settings` attribute as base64 JSON. Import prefers that attribute when
|
||||
* it is present and falls back to reading the crs: fields otherwise, which
|
||||
* keeps round trips exact without making the file useless elsewhere.
|
||||
*/
|
||||
|
||||
const LUM_NS = 'https://luminary.app/xmp/1.0';
|
||||
|
||||
/** crs field, direction: our edits use the same -100…100 scale. */
|
||||
const CRS_FIELDS: [string, (edits: Edits) => number][] = [
|
||||
['Exposure2012', (e) => e.exposure],
|
||||
['Contrast2012', (e) => e.contrast],
|
||||
['Highlights2012', (e) => e.highlights],
|
||||
['Shadows2012', (e) => e.shadows],
|
||||
['Whites2012', (e) => e.whites],
|
||||
['Blacks2012', (e) => e.blacks],
|
||||
['Texture', (e) => e.texture],
|
||||
['Clarity2012', (e) => e.clarity],
|
||||
['Dehaze', (e) => e.dehaze],
|
||||
['Vibrance', (e) => e.vibrance],
|
||||
['Saturation', (e) => e.saturation],
|
||||
['ParametricHighlights', (e) => e.parametric.highlights],
|
||||
['ParametricLights', (e) => e.parametric.lights],
|
||||
['ParametricDarks', (e) => e.parametric.darks],
|
||||
['ParametricBlacks', (e) => e.parametric.blacks],
|
||||
['PostCropVignetteAmount', (e) => e.vignette.amount],
|
||||
['GrainAmount', (e) => e.grain.amount],
|
||||
];
|
||||
|
||||
const CRS_TO_EDIT: Record<string, (edits: Edits, value: number) => void> = {
|
||||
Exposure2012: (e, v) => (e.exposure = v),
|
||||
Contrast2012: (e, v) => (e.contrast = v),
|
||||
Highlights2012: (e, v) => (e.highlights = v),
|
||||
Shadows2012: (e, v) => (e.shadows = v),
|
||||
Whites2012: (e, v) => (e.whites = v),
|
||||
Blacks2012: (e, v) => (e.blacks = v),
|
||||
Texture: (e, v) => (e.texture = v),
|
||||
Clarity2012: (e, v) => (e.clarity = v),
|
||||
Dehaze: (e, v) => (e.dehaze = v),
|
||||
Vibrance: (e, v) => (e.vibrance = v),
|
||||
Saturation: (e, v) => (e.saturation = v),
|
||||
ParametricHighlights: (e, v) => (e.parametric.highlights = v),
|
||||
ParametricLights: (e, v) => (e.parametric.lights = v),
|
||||
ParametricDarks: (e, v) => (e.parametric.darks = v),
|
||||
ParametricBlacks: (e, v) => (e.parametric.blacks = v),
|
||||
PostCropVignetteAmount: (e, v) => (e.vignette.amount = v),
|
||||
GrainAmount: (e, v) => (e.grain.amount = v),
|
||||
ConvertToGrayscale: (e, v) => (e.bw = v >= 0.5 || v === 1),
|
||||
};
|
||||
|
||||
export interface XmpImport {
|
||||
edits: Edits;
|
||||
/** How the settings were read: exact Luminary payload or crs fallback. */
|
||||
source: 'luminary' | 'lightroom';
|
||||
/** crs fields the sidecar set, for the toast. */
|
||||
applied: string[];
|
||||
}
|
||||
|
||||
function escapeXml(value: string) {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function unescapeXml(value: string) {
|
||||
return value
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/&/g, '&');
|
||||
}
|
||||
|
||||
function base64Encode(text: string) {
|
||||
const bytes = new TextEncoder().encode(text);
|
||||
let binary = '';
|
||||
for (const byte of bytes) binary += String.fromCharCode(byte);
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
function base64Decode(value: string) {
|
||||
const binary = atob(value);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
||||
return new TextDecoder().decode(bytes);
|
||||
}
|
||||
|
||||
function num(value: number) {
|
||||
return Number.isFinite(value) ? String(Math.round(value * 1000) / 1000) : '0';
|
||||
}
|
||||
|
||||
/** Sidecar name for a photo: "DSC0123.ARW" → "DSC0123.xmp". */
|
||||
export function xmpFileName(name: string) {
|
||||
return `${name.replace(/\.[^.]+$/, '') || 'photo'}.xmp`;
|
||||
}
|
||||
|
||||
export function editsToXmp(edits: Edits, photo?: Pick<PhotoRecord, 'name' | 'meta'>): string {
|
||||
const normalized = normalizeEdits(edits);
|
||||
const attrs = CRS_FIELDS.map(
|
||||
([name, read]) => `crs:${name}="${num(read(normalized))}"`,
|
||||
);
|
||||
attrs.push(`crs:ConvertToGrayscale="${normalized.bw ? 'True' : 'False'}"`);
|
||||
if (normalized.kelvin != null) attrs.push(`crs:Temperature="${Math.round(normalized.kelvin)}"`);
|
||||
attrs.push(`lum:Settings="${escapeXml(base64Encode(JSON.stringify(normalized)))}"`);
|
||||
const label = photo ? escapeXml(photo.name) : 'Luminary edit';
|
||||
|
||||
return [
|
||||
'<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?>',
|
||||
'<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Luminary">',
|
||||
' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">',
|
||||
` <rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmlns:lum="${LUM_NS}"`,
|
||||
' crs:Version="15.0" crs:ProcessVersion="15.4" crs:HasSettings="True"',
|
||||
` ${attrs.join('\n ')}>`,
|
||||
` <dc:title xmlns:dc="http://purl.org/dc/elements/1.1/"><rdf:Alt><rdf:li xml:lang="x-default">${label}</rdf:li></rdf:Alt></dc:title>`,
|
||||
' </rdf:Description>',
|
||||
' </rdf:RDF>',
|
||||
'</x:xmpmeta>',
|
||||
'<?xpacket end="w"?>',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function attributes(xml: string) {
|
||||
const out = new Map<string, string>();
|
||||
const pattern = /([A-Za-z][\w:.-]*)\s*=\s*"([^"]*)"/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = pattern.exec(xml))) {
|
||||
// Later duplicates lose: rdf:about="" repeats on every nested node.
|
||||
if (!out.has(match[1])) out.set(match[1], unescapeXml(match[2]));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads settings from a sidecar. `base` supplies every field the file does not
|
||||
* mention, so importing a Lightroom crop-free sidecar keeps the photo's mask
|
||||
* layers, crop and lens profile instead of resetting them.
|
||||
*/
|
||||
export function xmpToEdits(xml: string, base: Edits): XmpImport {
|
||||
if (!/<x:xmpmeta|<rdf:RDF/i.test(xml)) {
|
||||
throw new Error('That file is not an XMP sidecar');
|
||||
}
|
||||
const attrs = attributes(xml);
|
||||
const exact = attrs.get('lum:Settings');
|
||||
if (exact) {
|
||||
try {
|
||||
const parsed = JSON.parse(base64Decode(exact)) as Partial<Edits>;
|
||||
return {
|
||||
edits: normalizeEdits({ ...base, ...parsed }),
|
||||
source: 'luminary',
|
||||
applied: ['Luminary settings'],
|
||||
};
|
||||
} catch {
|
||||
// A damaged private payload still leaves the crs: fields to read.
|
||||
}
|
||||
}
|
||||
|
||||
const next = normalizeEdits(base);
|
||||
const applied: string[] = [];
|
||||
for (const [name, apply] of Object.entries(CRS_TO_EDIT)) {
|
||||
const raw = attrs.get(`crs:${name}`);
|
||||
if (raw === undefined) continue;
|
||||
const value = name === 'ConvertToGrayscale'
|
||||
? raw === 'True' || raw === 'true' || raw === '1'
|
||||
? 1
|
||||
: 0
|
||||
: Number(raw);
|
||||
if (!Number.isFinite(value)) continue;
|
||||
apply(next, value);
|
||||
applied.push(name);
|
||||
}
|
||||
const temperature = attrs.get('crs:Temperature');
|
||||
const tint = attrs.get('crs:Tint');
|
||||
if (temperature !== undefined) {
|
||||
const kelvin = Number(temperature);
|
||||
// Lightroom's Temperature is absolute Kelvin; the absolute control here is
|
||||
// defined against a 5500 K daylight reference, so the value transfers
|
||||
// directly and the panel shows the same number.
|
||||
if (Number.isFinite(kelvin) && kelvin >= 1500 && kelvin <= 15000) {
|
||||
next.kelvin = kelvin;
|
||||
applied.push('Temperature');
|
||||
}
|
||||
}
|
||||
if (tint !== undefined) {
|
||||
const value = Number(tint);
|
||||
if (Number.isFinite(value)) {
|
||||
next.tint = Math.max(-100, Math.min(100, value));
|
||||
applied.push('Tint');
|
||||
}
|
||||
}
|
||||
if (!applied.length) throw new Error('No develop settings found in that sidecar');
|
||||
return { edits: normalizeEdits(next), source: 'lightroom', applied };
|
||||
}
|
||||
|
||||
/** Opens the OS picker and returns the sidecar text, or null when cancelled. */
|
||||
export function readXmpFile(): Promise<string | null> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = '.xmp,application/rdf+xml,text/xml,application/xml';
|
||||
input.onchange = () => {
|
||||
const file = input.files?.[0];
|
||||
if (!file) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
file.text().then(resolve, reject);
|
||||
};
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sidecars named after the file next to the original, the way Lightroom writes
|
||||
* them, plus the download helper used by the library action.
|
||||
*/
|
||||
export function downloadXmp(photo: PhotoRecord) {
|
||||
const blob = new Blob([editsToXmp(photo.edits, photo)], { type: 'application/rdf+xml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = xmpFileName(photo.name);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 4000);
|
||||
}
|
||||
+580
@@ -1565,6 +1565,11 @@ figcaption {
|
||||
box-shadow: inset 0 0 0 1px var(--accent), 0 0 0 1px var(--accent);
|
||||
}
|
||||
|
||||
/* Every frame in a multi-select gets the canvas photo's accent outline. */
|
||||
.film.selected {
|
||||
box-shadow: inset 0 0 0 1px var(--accent), 0 0 0 1px var(--accent);
|
||||
}
|
||||
|
||||
.film-rating {
|
||||
position: absolute;
|
||||
bottom: 2px;
|
||||
@@ -1864,6 +1869,281 @@ figcaption {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
/* preset browser: search, category pills and a bounded scrolling list keep a
|
||||
catalogue of 150+ looks navigable inside the develop sidebar */
|
||||
.preset-browser {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.preset-toolbar {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 5px;
|
||||
padding: 0 10px 7px;
|
||||
}
|
||||
|
||||
.preset-search {
|
||||
position: relative;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.preset-search input {
|
||||
width: 100%;
|
||||
padding: 5px 24px 5px 8px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
background: var(--panel-2);
|
||||
color: var(--text);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.preset-search input:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent-dim);
|
||||
}
|
||||
|
||||
.preset-filter {
|
||||
position: relative;
|
||||
flex: 0 0 116px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.preset-select {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 4px;
|
||||
width: 100%;
|
||||
height: 26px;
|
||||
padding: 0 6px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
background: var(--panel-2);
|
||||
color: var(--muted);
|
||||
font-size: 10px;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.preset-select:hover,
|
||||
.preset-select[aria-expanded='true'],
|
||||
.preset-select:focus-visible {
|
||||
outline: none;
|
||||
color: var(--text);
|
||||
border-color: var(--accent-dim);
|
||||
}
|
||||
|
||||
.preset-select-text {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.preset-select-chev {
|
||||
flex: 0 0 auto;
|
||||
font-size: 8px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
/* Opens over the preset grid instead of inside a native popup, so it stays put
|
||||
while the tiles are still rendering. */
|
||||
.preset-menu {
|
||||
position: absolute;
|
||||
top: calc(100% + 4px);
|
||||
right: 0;
|
||||
z-index: 60;
|
||||
width: calc(var(--dev-left-w) - 20px);
|
||||
max-height: min(300px, 40vh);
|
||||
overflow-y: auto;
|
||||
padding: 4px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
background: var(--panel-2);
|
||||
box-shadow: 0 18px 44px rgba(0, 0, 0, 0.55);
|
||||
}
|
||||
|
||||
.preset-menu-head {
|
||||
padding: 6px 6px 3px;
|
||||
color: var(--muted);
|
||||
font-size: 9px;
|
||||
letter-spacing: 0.09em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.preset-menu-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 4px 6px;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
background: none;
|
||||
color: var(--text);
|
||||
font-size: 11px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.preset-menu-item:hover {
|
||||
background: rgba(255, 255, 255, 0.07);
|
||||
}
|
||||
|
||||
.preset-menu-item.on {
|
||||
color: var(--accent-dim);
|
||||
}
|
||||
|
||||
.preset-menu-label {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.preset-menu-count {
|
||||
color: var(--muted);
|
||||
font-size: 10px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.preset-search-clear {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 6px;
|
||||
transform: translateY(-50%);
|
||||
padding: 0 3px;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--muted);
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.preset-search-clear:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.preset-list {
|
||||
max-height: min(46vh, 440px);
|
||||
overflow-y: auto;
|
||||
padding-bottom: 4px;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
.preset-group-head {
|
||||
width: 100%;
|
||||
margin: 2px 0 5px;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--muted);
|
||||
font-size: 10px;
|
||||
letter-spacing: 0.08em;
|
||||
text-align: left;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.preset-group-head:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.preset-group-count {
|
||||
font-size: 9px;
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.preset-group-chev {
|
||||
margin-left: auto;
|
||||
font-size: 9px;
|
||||
}
|
||||
|
||||
.preset-tile-wrap {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.preset-tile-wrap .preset-tile {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.preset-star,
|
||||
.preset-del {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
color: #cccccc;
|
||||
font-size: 11px;
|
||||
line-height: 1;
|
||||
opacity: 0;
|
||||
transition: opacity 120ms ease;
|
||||
}
|
||||
|
||||
.preset-tile-wrap:hover .preset-star,
|
||||
.preset-tile-wrap:hover .preset-del,
|
||||
.preset-star:focus-visible,
|
||||
.preset-del:focus-visible,
|
||||
.preset-star.on {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.preset-star {
|
||||
right: 2px;
|
||||
}
|
||||
|
||||
.preset-star.on {
|
||||
color: #e8c45a;
|
||||
}
|
||||
|
||||
.preset-del {
|
||||
left: 2px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.preset-del:hover {
|
||||
color: #ff8a8a;
|
||||
}
|
||||
|
||||
.preset-empty {
|
||||
padding: 18px 12px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.preset-detail {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
border-top: 1px solid var(--line);
|
||||
padding: 6px 10px 8px;
|
||||
color: var(--muted);
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.preset-detail strong {
|
||||
color: var(--text);
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.preset-detail-meta {
|
||||
font-size: 9px;
|
||||
letter-spacing: 0.04em;
|
||||
opacity: 0.7;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.variant-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
@@ -2381,6 +2661,21 @@ figcaption {
|
||||
.field-row .field.narrow { flex: 0 0 96px; }
|
||||
|
||||
.cloud-modal { width: 520px; }
|
||||
.immich-modal { width: 640px; }
|
||||
.raw-modal { width: 560px; }
|
||||
.raw-modal .progress-bar { margin-bottom: 10px; }
|
||||
.raw-modal .failures { margin-top: 12px; }
|
||||
.immich-intro { margin: 0 0 14px; max-width: 60ch; }
|
||||
.immich-progress {
|
||||
bottom: 64px;
|
||||
min-width: min(320px, calc(100vw - 32px));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 6px;
|
||||
}
|
||||
.immich-progress-head { display: flex; justify-content: space-between; gap: 18px; }
|
||||
.new-event-gallery { flex: 1 0 100%; margin-top: 4px; }
|
||||
.cloud-offline strong { display: block; margin-bottom: 6px; }
|
||||
.code-block {
|
||||
background: #16161a;
|
||||
@@ -3209,6 +3504,23 @@ figcaption {
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.proof-lock-form {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 18px;
|
||||
width: min(420px, 100%);
|
||||
}
|
||||
|
||||
.proof-lock-form input {
|
||||
flex: 1;
|
||||
padding: 10px 12px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--panel-2);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.proof-head {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
@@ -3721,6 +4033,208 @@ figcaption {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.tether-folder {
|
||||
padding: 13px 15px;
|
||||
margin-bottom: 12px;
|
||||
border-radius: 6px;
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.tether-folder code {
|
||||
display: block;
|
||||
margin: 6px 0;
|
||||
padding: 8px 10px;
|
||||
border-radius: 5px;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
font-family: var(--mono, ui-monospace, SFMono-Regular, Menlo, monospace);
|
||||
font-size: 12px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.tether-folder p {
|
||||
margin: 0;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.tether-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.tether-log {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
max-height: 240px;
|
||||
overflow: auto;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.tether-log li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 5px 0;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.tether-log li.fail .tether-name {
|
||||
color: #e96a6a;
|
||||
}
|
||||
|
||||
.tether-time {
|
||||
color: var(--muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.tether-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cull-summary {
|
||||
display: flex;
|
||||
gap: 22px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.cull-summary > div {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.cull-summary strong {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.cull-summary span {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.cull-threshold {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin: 0 0 10px;
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.cull-threshold input {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.cull-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
max-height: 300px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.cull-list li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 6px 0;
|
||||
border-top: 1px solid var(--line);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.cull-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cull-grade {
|
||||
width: 44px;
|
||||
text-align: center;
|
||||
border-radius: 999px;
|
||||
padding: 1px 0;
|
||||
font-size: 10px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.cull-grade.soft {
|
||||
background: rgba(233, 106, 106, 0.18);
|
||||
color: #e96a6a;
|
||||
}
|
||||
|
||||
.cull-grade.fair {
|
||||
background: rgba(227, 179, 65, 0.16);
|
||||
color: #e3b341;
|
||||
}
|
||||
|
||||
.cull-grade.sharp {
|
||||
background: rgba(93, 197, 138, 0.14);
|
||||
color: #5dc58a;
|
||||
}
|
||||
|
||||
.cull-score {
|
||||
width: 26px;
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.share-settings {
|
||||
margin: 0 0 18px;
|
||||
padding: 13px 15px;
|
||||
border-radius: 6px;
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.share-settings-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 10px 12px;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.share-settings-grid label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.share-settings-grid input {
|
||||
width: 100%;
|
||||
padding: 6px 8px;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--panel);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.share-settings-wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.share-settings-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.share-picks {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
@@ -4330,6 +4844,7 @@ figcaption {
|
||||
.lens-default-manage {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 4px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
@@ -4337,6 +4852,71 @@ figcaption {
|
||||
width: min(640px, 100%);
|
||||
}
|
||||
|
||||
/* Team-calibrated lens profiles */
|
||||
|
||||
.lens-calib-modal {
|
||||
width: min(880px, 100%);
|
||||
}
|
||||
|
||||
.lens-calib-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.lens-calib-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.lens-calib-field .text-input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.lens-calib-section {
|
||||
margin-top: 14px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 7px;
|
||||
background: var(--panel-2);
|
||||
}
|
||||
|
||||
.lens-calib-section > header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.lens-calib-row {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
align-items: end;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.lens-calib-row.cols-distortion {
|
||||
grid-template-columns: 90px 130px repeat(3, minmax(0, 1fr)) 28px;
|
||||
}
|
||||
|
||||
.lens-calib-row.cols-tca {
|
||||
grid-template-columns: 90px 110px repeat(6, minmax(0, 1fr)) 28px;
|
||||
}
|
||||
|
||||
.lens-calib-row.cols-vignetting {
|
||||
grid-template-columns: 90px 90px 100px repeat(3, minmax(0, 1fr)) 28px;
|
||||
}
|
||||
|
||||
.lens-default-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.settings-kicker {
|
||||
display: block;
|
||||
margin-bottom: 3px;
|
||||
|
||||
+65
-2
@@ -68,6 +68,8 @@ export interface LocalLayer {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: LocalMaskKind;
|
||||
/** How this mask combines with the layer above it in the list. */
|
||||
mode: 'add' | 'subtract' | 'intersect';
|
||||
inverted: boolean;
|
||||
/** softness of the mask edge, 0–100 */
|
||||
feather: number;
|
||||
@@ -89,9 +91,19 @@ export interface LocalLayer {
|
||||
contrast: number;
|
||||
highlights: number;
|
||||
shadows: number;
|
||||
whites: number;
|
||||
blacks: number;
|
||||
temp: number;
|
||||
tint: number;
|
||||
saturation: number;
|
||||
vibrance: number;
|
||||
/** hue rotation in degrees, -180–180 */
|
||||
hue: number;
|
||||
/** detail and haze tools, applied after the global finish pass */
|
||||
texture: number;
|
||||
clarity: number;
|
||||
dehaze: number;
|
||||
sharpen: number;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -103,7 +115,9 @@ export interface LensCorrections {
|
||||
}
|
||||
|
||||
export interface LensProfile {
|
||||
/** Lensfun maker/model and the sensor crop used for calibration. */
|
||||
/** Profile id in the bundled lens database, when it came from a search. */
|
||||
id?: string;
|
||||
/** Maker/model and the sensor crop used for calibration. */
|
||||
maker: string;
|
||||
model: string;
|
||||
crop: number;
|
||||
@@ -126,9 +140,19 @@ export interface GeometryEdits {
|
||||
scale: number;
|
||||
}
|
||||
|
||||
/** ICC rendering intents the soft proof can build its round trip from. */
|
||||
export type ProofIntent = 'perceptual' | 'relative' | 'saturation';
|
||||
|
||||
export interface Edits {
|
||||
/** relative warm/cool offset, used when `kelvin` is null */
|
||||
temp: number;
|
||||
tint: number;
|
||||
/**
|
||||
* Scene illuminant in Kelvin, or null to use the relative Temp offset. The
|
||||
* gains are computed against a 5500 K daylight reference, which is also what
|
||||
* the demosaiced proxy is assumed to be balanced for.
|
||||
*/
|
||||
kelvin: number | null;
|
||||
exposure: number;
|
||||
/** pulls clipped highlights back into range without shifting hue */
|
||||
recovery: number;
|
||||
@@ -142,12 +166,19 @@ export interface Edits {
|
||||
dehaze: number;
|
||||
vibrance: number;
|
||||
saturation: number;
|
||||
/**
|
||||
* Redscale film response, 0–100: simulates colour film exposed through its
|
||||
* base, where the red-sensitive layer is hit first and blue is absorbed.
|
||||
*/
|
||||
redscale: number;
|
||||
bw: boolean;
|
||||
/** colored filter simulated in black & white mode */
|
||||
bwFilter: BwFilter;
|
||||
/** how strongly that filter acts, 0–100 */
|
||||
bwFilterAmount: number;
|
||||
curve: Record<CurveChannel, CurvePoint[]>;
|
||||
/** input black/white points and midtone gamma, applied before the curves */
|
||||
levels: { black: number; white: number; gamma: number };
|
||||
/** region tone shaping applied on top of the point curve */
|
||||
parametric: { highlights: number; lights: number; darks: number; blacks: number };
|
||||
hsl: { hue: number[]; sat: number[]; lum: number[] };
|
||||
@@ -159,7 +190,19 @@ export interface Edits {
|
||||
/** lensSoftness compensates for edge softness, 0–100 */
|
||||
sharpen: { amount: number; radius: number; detail: number; mask: number; lensSoftness: number };
|
||||
/** paper/output simulation for soft proofing */
|
||||
proof: { enabled: boolean; paper: 'matte' | 'gloss' | 'newsprint'; blackPoint: number; gamut: boolean };
|
||||
proof: {
|
||||
enabled: boolean;
|
||||
paper: 'matte' | 'gloss' | 'newsprint';
|
||||
blackPoint: number;
|
||||
gamut: boolean;
|
||||
/** Which ICC table pair the printer round trip is built from. */
|
||||
intent: ProofIntent;
|
||||
};
|
||||
/**
|
||||
* Camera profile override for a raw file, as the camera-to-sRGB matrix derived
|
||||
* from a DCP's ColorMatrix. Null renders with the matrix the body supplied.
|
||||
*/
|
||||
cameraProfile: { name: string; matrix: number[] } | null;
|
||||
/** chroma is the colour-noise amount; chromaDetail trades smoothing for fine colour */
|
||||
noise: { luminance: number; detail: number; chroma: number; chromaDetail: number };
|
||||
/**
|
||||
@@ -268,6 +311,10 @@ export interface PhotoRecord {
|
||||
previewUrl?: string;
|
||||
/** server URL for the grid thumbnail */
|
||||
thumbUrl?: string;
|
||||
/** Bumped when the stored RAW is re-decoded, to invalidate cached previews. */
|
||||
previewVersion?: number;
|
||||
/** set when this photo was imported from an Immich album */
|
||||
immich?: { albumId: string; assetId: string; checksum: string };
|
||||
/** timestamp of the last rendered client proof published to the server */
|
||||
proofAt?: number;
|
||||
/** Account this cached record belongs to (server workspaces). */
|
||||
@@ -289,6 +336,13 @@ export interface EventRecord {
|
||||
order?: number;
|
||||
/** Account this cached record belongs to (server workspaces). */
|
||||
workspace?: string;
|
||||
/** Set when this event mirrors an Immich album. */
|
||||
immich?: {
|
||||
albumId: string;
|
||||
albumName: string;
|
||||
serverUrl: string;
|
||||
lastSyncAt: number;
|
||||
};
|
||||
/** Set when this event is a temporary import from the dashboard bridge. */
|
||||
bridge?: {
|
||||
sessionId: string;
|
||||
@@ -317,7 +371,16 @@ export type SortKey = 'taken' | 'added' | 'name' | 'rating' | 'custom';
|
||||
export interface Preset {
|
||||
id: string;
|
||||
name: string;
|
||||
/** brand for film stocks, sub-collection for creative looks */
|
||||
group: string;
|
||||
/** top-level browser category, e.g. "Colour Negative" or "Portrait" */
|
||||
category?: string;
|
||||
/** one-line description of the look, shown in the preset browser */
|
||||
description?: string;
|
||||
/** free-text search terms */
|
||||
tags?: string[];
|
||||
/** present only on film emulations; drives the push/pull variants */
|
||||
film?: { speed?: number; process?: string };
|
||||
edits: Partial<Omit<Edits, 'crop'>>;
|
||||
custom?: boolean;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user