Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 07cd913c8b | |||
| 3b288bc03b | |||
| bd90264c3c | |||
| 8f23e96b92 | |||
| 5f15b528f4 | |||
| 5b4b49200c | |||
| 4d7a123d49 | |||
| df447794ea | |||
| d24cbf26b8 | |||
| 7f0838156b | |||
| fa0a7e64ef |
@@ -3,6 +3,105 @@
|
|||||||
Dated release notes, newest first. The same entries are summarised on the product
|
Dated release notes, newest first. The same entries are summarised on the product
|
||||||
page; this file is the complete list.
|
page; this file is the complete list.
|
||||||
|
|
||||||
|
## Unreleased
|
||||||
|
|
||||||
|
Finished in the tree, not part of any build yet.
|
||||||
|
|
||||||
|
- **Film looks and presets grade over your white balance.** Applying a look used
|
||||||
|
to overwrite Temp and Tint with the stock's own numbers, so a frame that had
|
||||||
|
been corrected came back with the look's cast on an uncorrected image. The
|
||||||
|
cast is now kept apart from the sliders and applied after your correction; it
|
||||||
|
layers on instead of replacing it, and switching looks swaps the cast rather
|
||||||
|
than stacking them. Every preset tile now renders over the photo's whole
|
||||||
|
current grade — exposure, tone, colour, crop and white balance — so a
|
||||||
|
thumbnail is what the click produces, and the rail keeps its images while the
|
||||||
|
tiles catch up. The Light panel reports the applied look's cast and the final
|
||||||
|
balance the photo is graded at, under Temp and Tint.
|
||||||
|
- **An audited offline guarantee.** A content security policy restricts connections to
|
||||||
|
the app's own origin, `npm run check:offline` fails the build if any shipped file
|
||||||
|
reaches for another host, and [docs/OFFLINE-GUARANTEE.md](docs/OFFLINE-GUARANTEE.md)
|
||||||
|
states what the app does and does not contact.
|
||||||
|
- **Object removal on the server** (`POST /api/photos/:id/inpaint`, LaMa, Apache-2.0,
|
||||||
|
bundled weights, no network). The routes and the cached-render store are in place;
|
||||||
|
there is no editor control for it yet, so nothing changes for a user.
|
||||||
|
|
||||||
|
## 0.5.4.1 — 2 December 2026
|
||||||
|
|
||||||
|
Windows patch on 0.5.4 for the Fujifilm import report, plus the metadata work that was
|
||||||
|
finished after 0.5.4. The installer and portable zip are linked from the download page
|
||||||
|
alongside 0.5.4; macOS remains at 0.5.1.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **The launcher no longer rejects a 64-bit PC started from a 32-bit parent.**
|
||||||
|
The platform check read `PROCESSOR_ARCHITECTURE`, which a WOW64 process reports
|
||||||
|
as `x86`. Starting Luminary from the setup's own finish page (a 32-bit NSIS
|
||||||
|
process) therefore stopped at "Luminary ships a 64-bit runtime; this PC reports
|
||||||
|
'x86'" on ordinary 64-bit Windows. It now reads the machine architecture from
|
||||||
|
`PROCESSOR_ARCHITEW6432` and `Is64BitOperatingSystem`, so launch context no
|
||||||
|
longer changes the answer.
|
||||||
|
- **The setup now starts Luminary when "Start Luminary" is ticked.** The finish
|
||||||
|
page ran the launcher with NSIS `Exec`, which passes the path straight to
|
||||||
|
`CreateProcess`. This build ships the PowerShell launcher, so the target was
|
||||||
|
`Luminary.vbs`, a script `CreateProcess` cannot start: the box was ticked, the
|
||||||
|
installer closed and no window opened. It now goes through the shell
|
||||||
|
(`ExecShell`), which starts the `.exe`, `.vbs` and `.cmd` alike. The 0.5.4.1
|
||||||
|
setup was rebuilt from the same staged bundle; the zip is unchanged.
|
||||||
|
- **Fujifilm imports are about five times faster.** LibRaw was asked for three
|
||||||
|
Markesteijn demosaic passes on X-Trans sensors; on a 40 MP X-T5 frame that took
|
||||||
|
**49.9 s**, and one pass takes **8.8 s** with no visible difference in the 6000 px
|
||||||
|
proxy the editor works on. X-Trans files are detected from the camera make and model
|
||||||
|
after the cheap header read, and demosaic at one pass
|
||||||
|
(`LUMINARY_RAW_XTRANS_QUALITY`, 1–3); Bayer files keep their previous setting. A full
|
||||||
|
40 MP decode fell from 44–50 s to about 20 s including the 16-bit sidecar.
|
||||||
|
- **A raw can no longer be saved as an unopenable 0×0 photo.** When decoding failed or
|
||||||
|
timed out, the fallback scanned the container for a JPEG and could stop at a nested
|
||||||
|
EXIF thumbnail's end marker, then store the truncated bytes anyway, with width and
|
||||||
|
height 0. It now tries every embedded candidate largest-first and keeps the first one
|
||||||
|
that actually decodes, so a hard file imports from the camera's own preview instead.
|
||||||
|
The import no longer trusts a server-reported `0` for a dimension either.
|
||||||
|
- **A wide selection no longer fails in waves.** The decode timeout used to start when
|
||||||
|
the request arrived and therefore counted time spent queued for a worker, and a
|
||||||
|
timed-out decoder was returned to the pool while still busy with the abandoned job —
|
||||||
|
four parallel Fuji files produced four timeouts and four broken previews. The clock now
|
||||||
|
starts when a worker picks the job up, and a timed-out worker is discarded.
|
||||||
|
- **Progress starts with the import.** The bar was only updated when a file finished, so
|
||||||
|
a 16-file Fuji import showed nothing for the first minute and then jumped to 4/16. It
|
||||||
|
now reports before each file starts, names the file, and says how many are still
|
||||||
|
waiting (`7 / 16 · 9 waiting · DSCF1024.RAF`).
|
||||||
|
- **The 16-bit sidecar no longer blocks previews.** Its PNG is compressed off the main
|
||||||
|
thread, so the editor stays responsive while an import runs.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Raws import two at a time.** A raw upload request stays open for the whole decode,
|
||||||
|
and four 40 MP X-T5 frames decoded together took 87–102 s each on a 12-core server
|
||||||
|
against 28.4 s alone — long enough for a 60 s reverse-proxy read timeout to answer 504
|
||||||
|
while the server was still working, which reads as the last files of a batch failing.
|
||||||
|
Two-wide holds a request near 45 s and finishes sixteen files sooner (~360 s against
|
||||||
|
~410 s); Bayer files give up a little. Camera JPEGs and PNGs still import four at a
|
||||||
|
time, because the browser decodes those itself. This build reissues 0.5.4.1 with the
|
||||||
|
window reduced from four; the setup, zip, tar.gz and .deb were rebuilt for it.
|
||||||
|
- **The camera-to-sRGB pass runs on a worker thread.** It was the widest synchronous
|
||||||
|
section left in a decode, and four parallel imports queued behind it on the event
|
||||||
|
loop. The frame buffers are now allocated on `SharedArrayBuffer`, so a worker writes
|
||||||
|
the same memory the encoder reads and nothing is copied across the boundary; frames
|
||||||
|
that arrive unshared fall back to the previous synchronous path.
|
||||||
|
|
||||||
|
### Also in this build (finished after 0.5.4)
|
||||||
|
|
||||||
|
- **Hierarchical keywords, IPTC and portable ratings.** Keywords can be grouped as paths
|
||||||
|
(`Wedding > Ceremony > Rings`) with suggestions from what is already in the catalog,
|
||||||
|
the IPTC fields are editable in the metadata panel, and star ratings and colour labels
|
||||||
|
are written to XMP (`xmp:Rating`, `xmp:Label`) alongside `dc:subject` and
|
||||||
|
`lr:hierarchicalSubject`, so they survive a round trip through Lightroom or Bridge.
|
||||||
|
|
||||||
|
### Notes
|
||||||
|
|
||||||
|
- Windows only. `Luminary-0.5.4.1-win-x64-setup.exe` and the portable zip are built
|
||||||
|
locally and published as links on the download page, with their SHA-256 sums in
|
||||||
|
`windows/releases/SHA256SUMS.txt`.
|
||||||
|
|
||||||
## 0.5.4 — 1 December 2026
|
## 0.5.4 — 1 December 2026
|
||||||
|
|
||||||
Windows and Linux bundles rebuilt with the new export format. macOS remains at
|
Windows and Linux bundles rebuilt with the new export format. macOS remains at
|
||||||
|
|||||||
@@ -232,9 +232,11 @@ storage, while quotas are stored per account in the database.
|
|||||||
| `LUMINARY_INVITE` | *(empty)* | Shared registration code for teammates; personal invite links work without it |
|
| `LUMINARY_INVITE` | *(empty)* | Shared registration code for teammates; personal invite links work without it |
|
||||||
| `LUMINARY_MAX_UPLOAD` | `314572800` (300 MB) | Largest accepted upload, in bytes |
|
| `LUMINARY_MAX_UPLOAD` | `314572800` (300 MB) | Largest accepted upload, in bytes |
|
||||||
| `LUMINARY_RAW_EDGE` | `6000` | Long edge of the editable JPEG proxy made from a raw |
|
| `LUMINARY_RAW_EDGE` | `6000` | Long edge of the editable JPEG proxy made from a raw |
|
||||||
| `LUMINARY_16BIT` | `1` | Also keep the decoded samples as a 16-bit PNG beside the raw proxy; `0` saves the disk and download it costs, at the price of grading an 8-bit source |
|
| `LUMINARY_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. The import dialog can also turn it off for a single import |
|
||||||
| `LUMINARY_RAW_WORKERS` | `min(4, cores−1)` | Concurrent LibRaw decoders; each holds a worker and a few hundred MB |
|
| `LUMINARY_RAW_WORKERS` | `min(4, cores−1)` | Concurrent LibRaw decoders; each holds a worker and a few hundred MB |
|
||||||
| `LUMINARY_RAW_IDLE_MS` | `90000` | Idle decoders are disposed after this to release memory |
|
| `LUMINARY_RAW_IDLE_MS` | `90000` | Idle decoders are disposed after this to release memory |
|
||||||
|
| `LUMINARY_RAW_XTRANS_QUALITY` | `1` | Markesteijn passes for Fujifilm X-Trans files, 1–3. Three passes costs 50 s on a 40 MP frame for detail the 6000 px proxy cannot show |
|
||||||
|
| `LUMINARY_RAW_TIMEOUT_MS` | `120000` | Ceiling on one demosaic, timed from when a worker starts the job rather than from the request |
|
||||||
| `LUMINARY_DENOISE_WORKERS` | `min(4, cores−1)` | Concurrent detail-denoise jobs (read directly from the environment) |
|
| `LUMINARY_DENOISE_WORKERS` | `min(4, cores−1)` | Concurrent detail-denoise jobs (read directly from the environment) |
|
||||||
| `LUMINARY_QUOTA_BYTES` | `107374182400` (100 GiB) | Default per-account storage allowance |
|
| `LUMINARY_QUOTA_BYTES` | `107374182400` (100 GiB) | Default per-account storage allowance |
|
||||||
| `LUMINARY_QUOTA_WARN_RATIO` | `0.9` | Fraction of the quota that triggers warnings, clamped to 0.5–0.99 |
|
| `LUMINARY_QUOTA_WARN_RATIO` | `0.9` | Fraction of the quota that triggers warnings, clamped to 0.5–0.99 |
|
||||||
@@ -879,7 +881,10 @@ The browser cannot demosaic camera raw, so the server does it during upload:
|
|||||||
texture and applies `rgb_cam` in the grade shader, so the grade has 65,536 levels per
|
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,
|
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
|
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
|
nothing breaks either way. The import dialog offers this as **Import raws at 16-bit**,
|
||||||
|
checked by default; unchecking it for an import asks the server for the 8-bit path
|
||||||
|
(`?sidecar=0` on the upload), which decodes the same but skips the second encode and
|
||||||
|
its disk cost. 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
|
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
|
`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.
|
shows in every view of the photo. Preset previews do the same.
|
||||||
@@ -905,8 +910,11 @@ same matrix from a DCP `ColorMatrix1` — `inverse(rowNormalise(ColorMatrix · x
|
|||||||
— matches LibRaw's `rgb_cam` to 2.2e-5 on a D700 NEF and 2.7e-5 on a 5D Mark II CR2.
|
— matches LibRaw's `rgb_cam` to 2.2e-5 on a D700 NEF and 2.7e-5 on a 5D Mark II CR2.
|
||||||
|
|
||||||
**Parallel import.** Decoding runs in a bounded pool of LibRaw workers (default
|
**Parallel import.** Decoding runs in a bounded pool of LibRaw workers (default
|
||||||
`min(4, cores−1)`, `LUMINARY_RAW_WORKERS`), and the browser uploads several files at a
|
`min(4, cores−1)`, `LUMINARY_RAW_WORKERS`). The browser keeps four raws in flight to
|
||||||
time. Each instance owns one worker thread; extra jobs queue. Idle instances are
|
match that pool and queues the rest, so the server is never asked for more frames than it
|
||||||
|
can decode; camera JPEGs also go four at a time, since the browser decodes those itself.
|
||||||
|
Eight 12 MP NEFs took 20.8 s two at a time and 17.4 s four at a time (8 was 15.8 s, not
|
||||||
|
worth the extra memory). Each instance owns one worker thread; extra jobs queue. Idle instances are
|
||||||
disposed after `LUMINARY_RAW_IDLE_MS` and recreated on demand, so a burst of imports
|
disposed after `LUMINARY_RAW_IDLE_MS` and recreated on demand, so a burst of imports
|
||||||
does not pin memory forever. A decoder that reports a dead worker is recycled rather
|
does not pin memory forever. A decoder that reports a dead worker is recycled rather
|
||||||
than returned to the pool. Measured on this repo with 8 mixed raws (20 MP average):
|
than returned to the pool. Measured on this repo with 8 mixed raws (20 MP average):
|
||||||
@@ -917,6 +925,17 @@ than returned to the pool. Measured on this repo with 8 mixed raws (20 MP averag
|
|||||||
| 4 | 5.2 s | 3.7× | ~2.5 GB |
|
| 4 | 5.2 s | 3.7× | ~2.5 GB |
|
||||||
| 8 | 3.5 s | 5.4× | ~3.5 GB |
|
| 8 | 3.5 s | 5.4× | ~3.5 GB |
|
||||||
|
|
||||||
|
Those are Bayer files. Fujifilm X-Trans frames behave differently in this wasm build: four
|
||||||
|
concurrent 40 MP X-Trans decodes each took ~65 s here against ~9 s on their own, so the
|
||||||
|
worker pool buys throughput in principle but not latency for that sensor. Two things
|
||||||
|
mattered more than the pool. LibRaw's default 3-pass Markesteijn demosaic took **49.9 s** on
|
||||||
|
one X-T5 frame; one pass takes **8.8 s** and is what `LUMINARY_RAW_XTRANS_QUALITY` selects.
|
||||||
|
And the 45 s decode timeout used to count time spent queued for a worker, so a parallel Fuji
|
||||||
|
import timed out in waves — every file in a wave fell back to the camera preview, and the
|
||||||
|
byte-scan fallback could hand back a truncated JPEG, which surfaced as a 0x0 photo. The
|
||||||
|
timeout now starts when a worker picks the job up, an abandoned worker is recycled instead
|
||||||
|
of being returned to the pool, and the fallback only stores bytes that actually decode.
|
||||||
|
|
||||||
Raise the worker count on a big machine; keep it low on a small VPS, where each worker
|
Raise the worker count on a big machine; keep it low on a small VPS, where each worker
|
||||||
can hold a few hundred MB while decoding. `GET /api/health` reports the pool size and
|
can hold a few hundred MB while decoding. `GET /api/health` reports the pool size and
|
||||||
busy count.
|
busy count.
|
||||||
@@ -975,6 +994,33 @@ listed in [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md).
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Metadata portability
|
||||||
|
|
||||||
|
The catalog is not the only copy of what you typed. Ratings, colour labels, keywords and
|
||||||
|
IPTC fields are written into XMP in both directions, so a library can leave.
|
||||||
|
|
||||||
|
- **Two keyword lists, on purpose.** `photo.keywords` holds the leaf terms and is what search
|
||||||
|
and filters read; `photo.keywordPaths` holds the full `A > B > C` chains. Typing
|
||||||
|
`Nature > Birds > Robin` records `Nature`, `Nature > Birds` and the full path, and adds
|
||||||
|
`Robin` to the flat list, so taggers never have to think about the tree and search never
|
||||||
|
has to.
|
||||||
|
- **The pair Lightroom writes.** `dc:subject` carries the leaves, `lr:hierarchicalSubject`
|
||||||
|
the paths, and `xmp:Rating` / `xmp:Label` the rating and colour label. Another editor
|
||||||
|
sees the same thing Luminary does; a library can be rebuilt from sidecars instead of
|
||||||
|
from this database.
|
||||||
|
- **IPTC core.** Headline, credit, source, city, state, country and sublocation are edited
|
||||||
|
in the Metadata panel and written as `photoshop:` and `Iptc4xmpCore:` properties.
|
||||||
|
- **Import reads both halves.** Importing a sidecar applies its develop settings and its
|
||||||
|
cataloguing fields independently: a metadata-only file from a DAM imports without a
|
||||||
|
`crs:` grade, and a grade imports without keywords. Nothing the file omits is cleared.
|
||||||
|
- **Exported files carry it too.** A JPEG export embeds the same packet as the sidecar, so a
|
||||||
|
delivered file keeps its rating, keywords, hierarchy and IPTC.
|
||||||
|
|
||||||
|
`src/lib/keywords.ts` owns the path rules (separators, ancestors, pruning a subtree and
|
||||||
|
leaving no orphan leaves); `src/lib/xmp.ts` owns the mapping to and from XMP.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Lens profiles
|
## Lens profiles
|
||||||
|
|
||||||
Lens correction uses the calibration data of the
|
Lens correction uses the calibration data of the
|
||||||
@@ -1137,6 +1183,7 @@ details, the isolation guarantees and the smoke tests (`windows/SMOKE-WINDOWS.ps
|
|||||||
| `503` "The web build is missing" | `npm start` was run without `dist/`. Run `npm run build` first, or use `npm run dev` |
|
| `503` "The web build is missing" | `npm start` was run without `dist/`. Run `npm run build` first, or use `npm run dev` |
|
||||||
| Raw upload returns `422` | LibRaw could not decode the file and no embedded preview was found. Check `GET /api/health` → `raw.libraw`; install dependencies and confirm the camera is supported |
|
| Raw upload returns `422` | LibRaw could not decode the file and no embedded preview was found. Check `GET /api/health` → `raw.libraw`; install dependencies and confirm the camera is supported |
|
||||||
| Import is slow or the machine swaps | Lower `LUMINARY_RAW_WORKERS`; each decoder holds a worker and a few hundred MB |
|
| Import is slow or the machine swaps | Lower `LUMINARY_RAW_WORKERS`; each decoder holds a worker and a few hundred MB |
|
||||||
|
| Fuji imports are slow or a Fuji file fails to import | X-Trans demosaic is the cost, not the network. `LUMINARY_RAW_XTRANS_QUALITY` defaults to 1 pass (~9 s for 40 MP); 3 is sharper and about five times slower. A file that still fails should now import from the camera preview — check its `decode` field for `embedded` |
|
||||||
| Emails never arrive | Gmail needs 2-Step Verification and an app password, not the account password. Use **Send test email**; admin-saved settings override the environment |
|
| Emails never arrive | Gmail needs 2-Step Verification and an app password, not the account password. Use **Send test email**; admin-saved settings override the environment |
|
||||||
| Quota looks wrong after deleting | Trash still counts toward usage. Empty Trash to release the bytes |
|
| Quota looks wrong after deleting | Trash still counts toward usage. Empty Trash to release the bytes |
|
||||||
| Cookies not marked `Secure` behind HTTPS | The proxy must forward `X-Forwarded-Proto: https` |
|
| Cookies not marked `Secure` behind HTTPS | The proxy must forward `X-Forwarded-Proto: https` |
|
||||||
|
|||||||
@@ -855,11 +855,11 @@
|
|||||||
|
|
||||||
<figure>
|
<figure>
|
||||||
<img src="img/08-presets.jpg" alt="The preset rail">
|
<img src="img/08-presets.jpg" alt="The preset rail">
|
||||||
<figcaption><b>Figure 14.</b> The preset rail with search, category filter, the look variants (Stock, Push +1, Pull −1, Warm split, Cool split) and tiles rendered from your own photo at your current crop.</figcaption>
|
<figcaption><b>Figure 14.</b> The preset rail with search, category filter, the look variants (Stock, Push +1, Pull −1, Warm split, Cool split) and tiles rendered from your own photo at your current crop, tone, colour and white balance.</figcaption>
|
||||||
</figure>
|
</figure>
|
||||||
|
|
||||||
<h2>Presets</h2>
|
<h2>Presets</h2>
|
||||||
<p>Groups include Essentials, Film, Warm and Cinematic. The variant row re-renders the whole rail a stop brighter or darker, or with the split-tone reversed. Click a tile to apply: it replaces the develop parameters but leaves crop and rotation alone, because those belong to the frame. <b>+</b> saves the current look as your own preset with a rendered preview.</p>
|
<p>Groups include Essentials, Film, Warm and Cinematic. The variant row re-renders the whole rail a stop brighter or darker, or with the split-tone reversed. Click a tile to apply: the look's tone and colour replace the develop parameters, while crop and rotation stay, because those belong to the frame. The white balance you set is kept as the base the look is graded over — the stock's own warmth or coolness is added on top of it, so correct a difficult frame first and the film still sits over that correction. Switching looks swaps that cast instead of stacking one stock's cast on the last one's. Because the look adds its cast to your correction, the Light panel prints both: the look's own cast and the final balance the photo is graded at, right under Temp and Tint. Every tile is rendered over the grade the photo has now, so the thumbnail is what the click produces. <b>+</b> saves the current look as your own preset with a rendered preview.</p>
|
||||||
|
|
||||||
<h2>History, undo and redo</h2>
|
<h2>History, undo and redo</h2>
|
||||||
<p>Every adjustment is recorded with a label. <b>History</b> in the left rail restores any step; <kbd>⌘ / Ctrl</kbd> + <kbd>Z</kbd> steps back, <kbd>⇧</kbd> + <kbd>⌘ / Ctrl</kbd> + <kbd>Z</kbd> steps forward. History is per photo and saved with the catalogue.</p>
|
<p>Every adjustment is recorded with a label. <b>History</b> in the left rail restores any step; <kbd>⌘ / Ctrl</kbd> + <kbd>Z</kbd> steps back, <kbd>⇧</kbd> + <kbd>⌘ / Ctrl</kbd> + <kbd>Z</kbd> steps forward. History is per photo and saved with the catalogue.</p>
|
||||||
|
|||||||
@@ -1,2 +1,4 @@
|
|||||||
3b2a7ac1d5b0057ce0d3796b5e2a57024a5d7d655800ed55245c2f00141827fd Luminary-0.5.4-linux-x64.tar.gz
|
3b2a7ac1d5b0057ce0d3796b5e2a57024a5d7d655800ed55245c2f00141827fd Luminary-0.5.4-linux-x64.tar.gz
|
||||||
45043c4c71003ccf210b7ee5ae8c45a58406aa526fa13e7fdb6e26f89b8c52ec Luminary-0.5.4-linux-amd64.deb
|
45043c4c71003ccf210b7ee5ae8c45a58406aa526fa13e7fdb6e26f89b8c52ec Luminary-0.5.4-linux-amd64.deb
|
||||||
|
895c6c5cffe47a17c18690fb55746d10c225e376721d70f233b10d635e5f2255 Luminary-0.5.4.1-linux-x64.tar.gz
|
||||||
|
d4aae7f9fb91a3c5eb66de284f8ed39977dd0b73d76e622e94d3b9ec98923e58 Luminary-0.5.4.1-linux-amd64.deb
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
/**
|
||||||
|
* Runs the camera-to-sRGB conversion off the main thread when it can.
|
||||||
|
*
|
||||||
|
* The conversion is CPU-bound and synchronous, so at four parallel imports it
|
||||||
|
* was the widest serial section left in the pipeline: four 24 MP frames cost
|
||||||
|
* ~10 s of event-loop time on top of the demosaic. A worker takes that loop off
|
||||||
|
* the main thread while the decoder pool and zlib keep their own threads.
|
||||||
|
*
|
||||||
|
* The frame is shared rather than transferred: `toRgb` allocates both buffers
|
||||||
|
* on SharedArrayBuffer, so `postMessage` hands over views and the worker writes
|
||||||
|
* the same memory the encoder will read. A frame that is not shared (a caller
|
||||||
|
* outside the raw pipeline) stays on this thread instead of being copied.
|
||||||
|
*/
|
||||||
|
import { Worker } from 'node:worker_threads';
|
||||||
|
import { cameraToProxy } from './color.mjs';
|
||||||
|
|
||||||
|
function isShared(view) {
|
||||||
|
return view?.buffer instanceof SharedArrayBuffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
function runInWorker(rgb16, rgb8, matrix) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const worker = new Worker(new URL('./color-worker.mjs', import.meta.url), {
|
||||||
|
workerData: { rgb16, rgb8, matrix },
|
||||||
|
});
|
||||||
|
let settled = false;
|
||||||
|
const finish = (fn, value) => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
worker.terminate().catch(() => {});
|
||||||
|
fn(value);
|
||||||
|
};
|
||||||
|
worker.once('message', (message) => {
|
||||||
|
if (message?.error) finish(reject, new Error(message.error));
|
||||||
|
else finish(resolve, message?.gain);
|
||||||
|
});
|
||||||
|
worker.once('error', (error) => finish(reject, error));
|
||||||
|
worker.once('exit', (code) => {
|
||||||
|
// A clean exit arrives after the message; only a crash before it is an error.
|
||||||
|
if (code !== 0) finish(reject, new Error(`colour worker exited with code ${code}`));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applies the camera matrix to the frame in place and resolves with the white
|
||||||
|
* point gain, exactly like `cameraToProxy`. A worker failure rejects rather
|
||||||
|
* than re-running the conversion here: the worker may have written part of the
|
||||||
|
* frame, and applying it again would double the white point.
|
||||||
|
*/
|
||||||
|
export async function cameraToProxyAsync(rgb16, rgb8, matrix) {
|
||||||
|
if (!isShared(rgb16) || !isShared(rgb8)) return cameraToProxy(rgb16, rgb8, matrix);
|
||||||
|
return runInWorker(rgb16, rgb8, matrix);
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* Off-main-thread camera-to-proxy conversion.
|
||||||
|
*
|
||||||
|
* `cameraToProxy` is a pixel loop over the whole frame: 2.4 s on a 24 MP decode
|
||||||
|
* here, and four parallel imports serialised on it. The buffers arrive as
|
||||||
|
* SharedArrayBuffer views, so the worker mutates the frame in place and nothing
|
||||||
|
* is copied across the thread boundary.
|
||||||
|
*/
|
||||||
|
import { parentPort, workerData } from 'node:worker_threads';
|
||||||
|
import { cameraToProxy } from './color.mjs';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const gain = cameraToProxy(workerData.rgb16, workerData.rgb8, workerData.matrix);
|
||||||
|
parentPort.postMessage({ gain });
|
||||||
|
} catch (error) {
|
||||||
|
parentPort.postMessage({ error: error instanceof Error ? error.message : String(error) });
|
||||||
|
}
|
||||||
@@ -107,3 +107,17 @@ export const RAW_WORKERS = Math.max(
|
|||||||
|
|
||||||
/** Idle decoder workers are disposed after this long to release memory. */
|
/** Idle decoder workers are disposed after this long to release memory. */
|
||||||
export const RAW_IDLE_MS = Number(setting('RAW_IDLE_MS', '90000'));
|
export const RAW_IDLE_MS = Number(setting('RAW_IDLE_MS', '90000'));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Demosaic setting for Fujifilm X-Trans sensors. LibRaw reads `userQual` as
|
||||||
|
* Markesteijn passes for X-Trans, and the 3-pass default costs about 50 s on a
|
||||||
|
* 40 MP frame while 1-pass costs about 9 s. The proxy is downsampled to
|
||||||
|
* RAW_PREVIEW_EDGE, so the difference does not survive to the editor.
|
||||||
|
*/
|
||||||
|
export const RAW_XTRANS_QUALITY = Math.min(
|
||||||
|
3,
|
||||||
|
Math.max(1, Number(setting('RAW_XTRANS_QUALITY', '1')) || 1),
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Ceiling on one demosaic, measured from when a worker picks the job up. */
|
||||||
|
export const RAW_TIMEOUT_MS = Number(setting('RAW_TIMEOUT_MS', '120000'));
|
||||||
|
|||||||
+40
-1
@@ -119,7 +119,38 @@ export function resizeRgb16(rgb16, width, height, tw, th) {
|
|||||||
* client would have to guess the conversion, and a self-describing sidecar also
|
* client would have to guess the conversion, and a self-describing sidecar also
|
||||||
* keeps working for imports that predate a catalogue migration.
|
* keeps working for imports that predate a catalogue migration.
|
||||||
*/
|
*/
|
||||||
|
/**
|
||||||
|
* Deflate settings for the 16-bit sidecar. RLE wins here because the rows are
|
||||||
|
* Sub-filtered first: a photographic row turns into mostly small byte
|
||||||
|
* differences, and run-length coding stores them in a few bits each. On a
|
||||||
|
* 40 MP sidecar this took compression from 2.87 s to 1.10 s and the file from
|
||||||
|
* 58.47 MB to 58.06 MB; the decoded samples are byte-identical.
|
||||||
|
*/
|
||||||
|
const SIDECAR_DEFLATE = { level: 6, strategy: zlib.constants.Z_RLE };
|
||||||
|
|
||||||
export function encodePng16(rgb16, width, height, matrix = null) {
|
export function encodePng16(rgb16, width, height, matrix = null) {
|
||||||
|
const raw = png16Rows(rgb16, width, height);
|
||||||
|
return png16File(zlib.deflateSync(raw, SIDECAR_DEFLATE), width, height, matrix);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The same PNG, with the deflate handed to libuv's thread pool.
|
||||||
|
*
|
||||||
|
* A 40 MP sidecar is ~110 MB and takes about five seconds to compress. Run
|
||||||
|
* synchronously that stalls the entire server for the duration, so four
|
||||||
|
* parallel imports finished one after another while the event loop was busy;
|
||||||
|
* the import felt frozen and preview requests queued behind it.
|
||||||
|
*/
|
||||||
|
export async function encodePng16Async(rgb16, width, height, matrix = null) {
|
||||||
|
const raw = png16Rows(rgb16, width, height);
|
||||||
|
const idat = await new Promise((resolve, reject) => {
|
||||||
|
zlib.deflate(raw, SIDECAR_DEFLATE, (err, out) => (err ? reject(err) : resolve(out)));
|
||||||
|
});
|
||||||
|
return png16File(idat, width, height, matrix);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sub-filtered rows: each byte minus the byte six to its left. */
|
||||||
|
function png16Rows(rgb16, width, height) {
|
||||||
const stride = width * 6;
|
const stride = width * 6;
|
||||||
const raw = Buffer.alloc((stride + 1) * height);
|
const raw = Buffer.alloc((stride + 1) * height);
|
||||||
const row = Buffer.alloc(stride);
|
const row = Buffer.alloc(stride);
|
||||||
@@ -134,7 +165,10 @@ export function encodePng16(rgb16, width, height, matrix = null) {
|
|||||||
raw[base + 1 + i] = (row[i] - (i >= 6 ? row[i - 6] : 0)) & 0xff;
|
raw[base + 1 + i] = (row[i] - (i >= 6 ? row[i - 6] : 0)) & 0xff;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const idat = zlib.deflateSync(raw, { level: 6 });
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
function png16File(idat, width, height, matrix = null) {
|
||||||
const ihdr = Buffer.alloc(13);
|
const ihdr = Buffer.alloc(13);
|
||||||
ihdr.writeUInt32BE(width, 0);
|
ihdr.writeUInt32BE(width, 0);
|
||||||
ihdr.writeUInt32BE(height, 4);
|
ihdr.writeUInt32BE(height, 4);
|
||||||
@@ -199,7 +233,12 @@ export async function cameraThumb16(png16, width, height, matrix = null) {
|
|||||||
const sharp = await loadSharp();
|
const sharp = await loadSharp();
|
||||||
if (!sharp || width < 1 || height < 1) return null;
|
if (!sharp || width < 1 || height < 1) return null;
|
||||||
try {
|
try {
|
||||||
|
// `depth: 'ushort'` on the output only sets the container: without asking
|
||||||
|
// for the rgb16 colourspace, libvips runs the resize on 8-bit pixels and the
|
||||||
|
// samples come back as their high bytes alone (7 instead of 2000), which
|
||||||
|
// renders as a near-black tile.
|
||||||
const { data, info } = await sharp(png16)
|
const { data, info } = await sharp(png16)
|
||||||
|
.toColourspace('rgb16')
|
||||||
.resize({ width, height, fit: 'fill' })
|
.resize({ width, height, fit: 'fill' })
|
||||||
.raw({ depth: 'ushort' })
|
.raw({ depth: 'ushort' })
|
||||||
.toBuffer({ resolveWithObject: true });
|
.toBuffer({ resolveWithObject: true });
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import sharp from 'sharp';
|
||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { cameraThumb16, encodePng16, png16Matrix, resizeRgb16 } from './imaging.mjs';
|
import { cameraThumb16, encodePng16, png16Matrix, resizeRgb16 } from './imaging.mjs';
|
||||||
|
|
||||||
@@ -75,6 +76,19 @@ describe('cameraThumb16', () => {
|
|||||||
expect(out[25]).toBe(2); // colour type RGB
|
expect(out[25]).toBe(2); // colour type RGB
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('keeps the full 16-bit samples, not just their high bytes', async () => {
|
||||||
|
// sharp's raw output is 8-bit unless the pipeline is asked for rgb16, and a
|
||||||
|
// downconverted thumbnail decodes to 7/15/23 instead of 2000/4000/6000.
|
||||||
|
const source = encodePng16(flat16(4, 2, [2000, 4000, 6000]), 4, 2, MATRIX);
|
||||||
|
const out = await cameraThumb16(source, 2, 1);
|
||||||
|
const { data } = await sharp(out)
|
||||||
|
.toColourspace('rgb16')
|
||||||
|
.raw({ depth: 'ushort' })
|
||||||
|
.toBuffer({ resolveWithObject: true });
|
||||||
|
const samples = [0, 2, 4].map((at) => data.readUInt16LE(at));
|
||||||
|
expect(samples).toEqual([2000, 4000, 6000]);
|
||||||
|
});
|
||||||
|
|
||||||
it('keeps the camera matrix so the client can convert the samples', async () => {
|
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 source = encodePng16(flat16(4, 2, [1000, 2000, 3000]), 4, 2, MATRIX);
|
||||||
const out = await cameraThumb16(source, 2, 1);
|
const out = await cameraThumb16(source, 2, 1);
|
||||||
|
|||||||
+5
-1
@@ -2182,6 +2182,10 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
|||||||
const url = new URL(req.url ?? '/', 'http://localhost');
|
const url = new URL(req.url ?? '/', 'http://localhost');
|
||||||
const name = url.searchParams.get('name') || 'upload';
|
const name = url.searchParams.get('name') || 'upload';
|
||||||
const drop = url.searchParams.get('drop') === '1';
|
const drop = url.searchParams.get('drop') === '1';
|
||||||
|
// The import dialog can ask for an 8-bit import; anything else keeps the
|
||||||
|
// LUMINARY_16BIT setting. Only `sidecar=0` is meaningful, so the default path
|
||||||
|
// behaves exactly as before.
|
||||||
|
const sidecar = url.searchParams.get('sidecar') !== '0';
|
||||||
const mime = normalizePhotoMime(url.searchParams.get('mime') || '', name);
|
const mime = normalizePhotoMime(url.searchParams.get('mime') || '', name);
|
||||||
const ext = (name.split('.').pop() || 'bin').toLowerCase();
|
const ext = (name.split('.').pop() || 'bin').toLowerCase();
|
||||||
// TIFF is not a raw container, but browsers cannot decode it either. It takes
|
// TIFF is not a raw container, but browsers cannot decode it either. It takes
|
||||||
@@ -2276,7 +2280,7 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
|||||||
if (raw) {
|
if (raw) {
|
||||||
try {
|
try {
|
||||||
const data = await fsp.readFile(target);
|
const data = await fsp.readFile(target);
|
||||||
const decoded = still ? await decodeStill(data) : await decodeRaw(data);
|
const decoded = still ? await decodeStill(data) : await decodeRaw(data, { sidecar });
|
||||||
await writePreview(params.id, decoded.jpeg, decoded.ext);
|
await writePreview(params.id, decoded.jpeg, decoded.ext);
|
||||||
if (decoded.preview16) {
|
if (decoded.preview16) {
|
||||||
await writePreview16(params.id, decoded.preview16.data);
|
await writePreview16(params.id, decoded.preview16.data);
|
||||||
|
|||||||
+26
-3
@@ -88,17 +88,40 @@ class LibRawPool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Run `fn` with a decoder instance; the instance returns to the pool after. */
|
/**
|
||||||
async use(fn) {
|
* Run `fn` with a decoder instance; the instance returns to the pool after.
|
||||||
|
*
|
||||||
|
* `timeoutMs` covers only the work, never the wait for a free worker: a job
|
||||||
|
* that sat in the queue is not slow, and timing it from the call site made
|
||||||
|
* parallel imports fail in waves. A timed-out worker is still chewing on the
|
||||||
|
* abandoned job, so it is destroyed rather than handed to the next caller.
|
||||||
|
*/
|
||||||
|
async use(fn, { timeoutMs = 0, label = 'LibRaw' } = {}) {
|
||||||
const lib = await this.acquire();
|
const lib = await this.acquire();
|
||||||
let healthy = true;
|
let healthy = true;
|
||||||
|
let timer = null;
|
||||||
try {
|
try {
|
||||||
return await fn(lib);
|
if (!timeoutMs) return await fn(lib);
|
||||||
|
const guard = new Promise((_, reject) => {
|
||||||
|
timer = setTimeout(
|
||||||
|
() => reject(new Error(`${label} timed out on this file`)),
|
||||||
|
timeoutMs,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
return await Promise.race([fn(lib), guard]);
|
||||||
|
} catch (err) {
|
||||||
|
if (timer && /timed out/.test(String(err?.message ?? '')) && err instanceof Error) {
|
||||||
|
healthy = false;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// A dead worker keeps failing, so recycle it instead of handing it back.
|
// A dead worker keeps failing, so recycle it instead of handing it back.
|
||||||
if (/worker|terminated|disposed|memory/i.test(String(err?.message ?? ''))) healthy = false;
|
if (/worker|terminated|disposed|memory/i.test(String(err?.message ?? ''))) healthy = false;
|
||||||
throw err;
|
throw err;
|
||||||
} finally {
|
} finally {
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
this.release(lib, healthy);
|
this.release(lib, healthy);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+135
-67
@@ -1,6 +1,14 @@
|
|||||||
import { RAW_16BIT, RAW_PREVIEW_EDGE } from './config.mjs';
|
import { RAW_16BIT, RAW_PREVIEW_EDGE, RAW_TIMEOUT_MS, RAW_XTRANS_QUALITY } from './config.mjs';
|
||||||
import { cameraToProxy, readRgbCam } from './color.mjs';
|
import { readRgbCam } from './color.mjs';
|
||||||
import { encodePng16, encodeRgb, jpegInfo, loadSharp, resizeRgb16, toJpegProxy } from './imaging.mjs';
|
import { cameraToProxyAsync } from './color-offload.mjs';
|
||||||
|
import {
|
||||||
|
encodePng16Async,
|
||||||
|
encodeRgb,
|
||||||
|
jpegInfo,
|
||||||
|
loadSharp,
|
||||||
|
resizeRgb16,
|
||||||
|
toJpegProxy,
|
||||||
|
} from './imaging.mjs';
|
||||||
import { loadLibRaw, rawPool } from './libraw-pool.mjs';
|
import { loadLibRaw, rawPool } from './libraw-pool.mjs';
|
||||||
|
|
||||||
/** Every raw container the pipeline will attempt, grouped by vendor family. */
|
/** Every raw container the pipeline will attempt, grouped by vendor family. */
|
||||||
@@ -39,15 +47,6 @@ export function isStillName(name = '') {
|
|||||||
return SERVER_IMAGE_EXTENSIONS.has(ext);
|
return SERVER_IMAGE_EXTENSIONS.has(ext);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Rejects instead of waiting forever when a decoder wedges on one file. */
|
|
||||||
function withTimeout(promise, ms, message) {
|
|
||||||
let timer;
|
|
||||||
const guard = new Promise((_, reject) => {
|
|
||||||
timer = setTimeout(() => reject(new Error(message)), ms);
|
|
||||||
});
|
|
||||||
return Promise.race([promise, guard]).finally(() => clearTimeout(timer));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** True when the buffer starts with a container signature LibRaw can open. */
|
/** True when the buffer starts with a container signature LibRaw can open. */
|
||||||
export function looksLikeRaw(buffer) {
|
export function looksLikeRaw(buffer) {
|
||||||
if (!buffer || buffer.length < 64) return false;
|
if (!buffer || buffer.length < 64) return false;
|
||||||
@@ -146,11 +145,14 @@ function toRgb(img) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const rgb = Buffer.alloc(pixelCount * 3);
|
// Both outputs are shared memory: the camera-to-sRGB pass runs in a worker
|
||||||
|
// (color-offload.mjs) and writes these same bytes, so a 24 MP frame is not
|
||||||
|
// copied across the thread boundary.
|
||||||
|
const rgb = Buffer.from(new SharedArrayBuffer(pixelCount * 3));
|
||||||
let rgb16 = null;
|
let rgb16 = null;
|
||||||
if (bits > 8) {
|
if (bits > 8) {
|
||||||
const view = wide instanceof Uint16Array ? wide : src;
|
const view = wide instanceof Uint16Array ? wide : src;
|
||||||
rgb16 = new Uint16Array(pixelCount * 3);
|
rgb16 = new Uint16Array(new SharedArrayBuffer(pixelCount * 3 * 2));
|
||||||
for (let i = 0; i < pixelCount; i++) {
|
for (let i = 0; i < pixelCount; i++) {
|
||||||
const s = i * colors;
|
const s = i * colors;
|
||||||
const r = view[s];
|
const r = view[s];
|
||||||
@@ -182,91 +184,153 @@ function toRgb(img) {
|
|||||||
* matrix metadata. A body LibRaw has no matrix for falls back to the plain sRGB
|
* 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.
|
* decode, which is the same result the pipeline produced before.
|
||||||
*/
|
*/
|
||||||
async function demosaic(buffer, cameraNative = true) {
|
/**
|
||||||
|
* Fujifilm bodies that are *not* X-Trans: the Bayer-sensor GFX and X-A/T100/T200
|
||||||
|
* lines, plus the old FinePix compacts. Everyone else in the X series uses the
|
||||||
|
* 6x6 colour filter array.
|
||||||
|
*/
|
||||||
|
function isXTrans(make, model) {
|
||||||
|
if (!/fuji/i.test(String(make ?? ''))) return false;
|
||||||
|
const m = String(model ?? '').trim();
|
||||||
|
if (/^(gfx|finepix)/i.test(m)) return false;
|
||||||
|
if (/^x-(a\d|t100|t200)\b/i.test(m)) return false;
|
||||||
|
return /^x/i.test(m);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Demosaic one frame. On X-Trans the `userQual` setting counts Markesteijn
|
||||||
|
* passes, and LibRaw's 3-pass default is the single most expensive thing this
|
||||||
|
* pipeline does: 49.9 s on a 40 MP X-T5 frame here, against 8.8 s for one pass,
|
||||||
|
* which pushed every Fuji import into the decode timeout (and, under a parallel
|
||||||
|
* import, every file at once). The proxy is downsampled to RAW_PREVIEW_EDGE, so
|
||||||
|
* the extra passes were being thrown away by the resize anyway.
|
||||||
|
*
|
||||||
|
* The model is only known after the container is opened, and opening is ~0.2 s,
|
||||||
|
* so the file is re-opened with the cheaper setting rather than guessing from
|
||||||
|
* the filename.
|
||||||
|
*/
|
||||||
|
async function demosaic(buffer, { cameraNative = true } = {}) {
|
||||||
if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed');
|
if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed');
|
||||||
return rawPool.use(async (lib) => {
|
return rawPool.use(
|
||||||
// LibRaw transfers the buffer to its worker, which detaches it here. Hand it
|
async (lib) => {
|
||||||
// a copy so the caller's bytes survive for the embedded-preview fallback.
|
const settings = cameraNative
|
||||||
await lib.open(
|
? DECODE_SETTINGS
|
||||||
Buffer.from(buffer),
|
: { ...DECODE_SETTINGS, outputColor: 1, noAutoBright: false };
|
||||||
cameraNative ? DECODE_SETTINGS : { ...DECODE_SETTINGS, outputColor: 1, noAutoBright: false },
|
// 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.
|
||||||
const image = toRgb(await lib.imageData());
|
await lib.open(Buffer.from(buffer), settings);
|
||||||
const rgbCam = cameraNative ? readRgbCam(await lib.metadata(true)) : null;
|
if (settings.userQual > RAW_XTRANS_QUALITY) {
|
||||||
return { ...image, rgbCam };
|
const info = await lib.metadata();
|
||||||
});
|
if (isXTrans(info?.camera_make, info?.camera_model)) {
|
||||||
|
await lib.open(Buffer.from(buffer), { ...settings, userQual: RAW_XTRANS_QUALITY });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const image = toRgb(await lib.imageData());
|
||||||
|
const rgbCam = cameraNative ? readRgbCam(await lib.metadata(true)) : null;
|
||||||
|
return { ...image, rgbCam };
|
||||||
|
},
|
||||||
|
{ timeoutMs: RAW_TIMEOUT_MS, label: 'LibRaw' },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const SOI = Buffer.from([0xff, 0xd8, 0xff]);
|
const SOI = Buffer.from([0xff, 0xd8, 0xff]);
|
||||||
const EOI = Buffer.from([0xff, 0xd9]);
|
const EOI = Buffer.from([0xff, 0xd9]);
|
||||||
|
|
||||||
/** Pull the largest embedded JPEG straight out of a raw container. */
|
/**
|
||||||
export function extractEmbeddedJpeg(buffer) {
|
* Every embedded JPEG in a raw container, largest first.
|
||||||
let best = null;
|
*
|
||||||
let from = 0;
|
* A single scan can land on a thumbnail's end-of-image and cut the file short:
|
||||||
while (from < buffer.length - 3) {
|
* that produced a "preview" sharp refused to decode, which was then stored as a
|
||||||
const start = buffer.indexOf(SOI, from);
|
* 0x0 JPEG. Callers walk the list and keep the first candidate that really
|
||||||
|
* decodes.
|
||||||
|
*/
|
||||||
|
export function extractEmbeddedJpegs(buffer) {
|
||||||
|
const starts = [];
|
||||||
|
let at = 0;
|
||||||
|
while (starts.length < 64) {
|
||||||
|
const start = buffer.indexOf(SOI, at);
|
||||||
if (start < 0) break;
|
if (start < 0) break;
|
||||||
const end = buffer.indexOf(EOI, start + 3);
|
starts.push(start);
|
||||||
if (end < 0) break;
|
at = start + 3;
|
||||||
const length = end + 2 - start;
|
|
||||||
if (length > 4096 && (!best || length > best.length)) best = buffer.subarray(start, end + 2);
|
|
||||||
from = end + 2;
|
|
||||||
}
|
}
|
||||||
return best;
|
const found = [];
|
||||||
|
for (const start of starts) {
|
||||||
|
// Several end-of-image markers can follow one start: a preview that carries
|
||||||
|
// its own EXIF thumbnail ends twice. Take a few candidates per start and let
|
||||||
|
// the decoder pick, instead of committing to the first marker found.
|
||||||
|
let from = start + 3;
|
||||||
|
for (let attempt = 0; attempt < 3; attempt++) {
|
||||||
|
const end = buffer.indexOf(EOI, from);
|
||||||
|
if (end < 0) break;
|
||||||
|
if (end + 2 - start > 4096) found.push(buffer.subarray(start, end + 2));
|
||||||
|
from = end + 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return found.sort((a, b) => b.length - a.length);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Camera preview, preferably the one LibRaw knows the offset and length of. */
|
/** The largest embedded JPEG, for callers that want one candidate. */
|
||||||
async function embeddedPreview(buffer) {
|
export function extractEmbeddedJpeg(buffer) {
|
||||||
|
return extractEmbeddedJpegs(buffer)[0] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Camera previews, best first: the one LibRaw knows about, then byte-scanned. */
|
||||||
|
async function embeddedPreviews(buffer) {
|
||||||
|
const candidates = [];
|
||||||
if ((await rawEngine()) === 'ready') {
|
if ((await rawEngine()) === 'ready') {
|
||||||
try {
|
try {
|
||||||
const thumb = await withTimeout(
|
const thumb = await rawPool.use(
|
||||||
rawPool.use(async (lib) => {
|
async (lib) => {
|
||||||
await lib.open(Buffer.from(buffer), { useCameraWb: true });
|
await lib.open(Buffer.from(buffer), { useCameraWb: true });
|
||||||
return lib.thumbnailData();
|
return lib.thumbnailData();
|
||||||
}),
|
},
|
||||||
12000,
|
{ timeoutMs: 20000, label: 'LibRaw preview' },
|
||||||
'LibRaw preview timed out',
|
|
||||||
);
|
);
|
||||||
if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) {
|
if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) {
|
||||||
return Buffer.from(thumb.data);
|
candidates.push(Buffer.from(thumb.data));
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
/* fall through to the byte scan */
|
/* fall through to the byte scan */
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return extractEmbeddedJpeg(buffer);
|
candidates.push(...extractEmbeddedJpegs(buffer));
|
||||||
|
return candidates;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert a raw file into an editable JPEG. LibRaw demosaics where possible and
|
* Convert a raw file into an editable JPEG. LibRaw demosaics where possible and
|
||||||
* falls back to the camera's own embedded preview when it cannot.
|
* falls back to the camera's own embedded preview when it cannot.
|
||||||
|
*
|
||||||
|
* `sidecar` writes the 16-bit samples beside the JPEG. It defaults to the
|
||||||
|
* server setting, and the import dialog can turn it off for one import: an
|
||||||
|
* 8-bit import decodes exactly the same, it just skips the second encode and the
|
||||||
|
* tens of megabytes of disk it costs.
|
||||||
*/
|
*/
|
||||||
export async function decodeRaw(buffer) {
|
export async function decodeRaw(buffer, { sidecar = RAW_16BIT } = {}) {
|
||||||
let librawError = null;
|
let librawError = null;
|
||||||
if (looksLikeRaw(buffer)) {
|
if (looksLikeRaw(buffer)) {
|
||||||
try {
|
try {
|
||||||
let frame = await withTimeout(demosaic(buffer, true), 45000, 'LibRaw timed out on this file');
|
let frame = await demosaic(buffer, { cameraNative: true });
|
||||||
// No usable matrix (an odd body or older engine): decode the familiar sRGB
|
// No usable matrix (an odd body or older engine): decode the familiar sRGB
|
||||||
// way instead of shipping camera samples nobody can convert.
|
// way instead of shipping camera samples nobody can convert.
|
||||||
if (!frame.rgbCam || !frame.rgb16) frame = await withTimeout(demosaic(buffer, false), 45000, 'LibRaw timed out on this file');
|
if (!frame.rgbCam || !frame.rgb16) frame = await demosaic(buffer, { cameraNative: false });
|
||||||
const { width, height, rgbCam } = frame;
|
const { width, height, rgbCam } = frame;
|
||||||
// Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and
|
// Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and
|
||||||
// `rgb16` the camera-native sidecar, sharing one white point.
|
// `rgb16` the camera-native sidecar, sharing one white point.
|
||||||
if (rgbCam && frame.rgb16) cameraToProxy(frame.rgb16, frame.rgb, rgbCam);
|
if (rgbCam && frame.rgb16) await cameraToProxyAsync(frame.rgb16, frame.rgb, rgbCam);
|
||||||
const { rgb } = frame;
|
const { rgb } = frame;
|
||||||
const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE);
|
const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE);
|
||||||
// The sidecar must match the JPEG pixel for pixel: the editor swaps the
|
// 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
|
// two textures at the same uv, so a size disagreement would misalign the
|
||||||
// whole grade. It is optional -- encoding failures leave the JPEG path.
|
// whole grade. It is optional -- encoding failures leave the JPEG path.
|
||||||
let preview16 = null;
|
let preview16 = null;
|
||||||
if (frame.rgb16 && RAW_16BIT) {
|
if (frame.rgb16 && sidecar) {
|
||||||
try {
|
try {
|
||||||
const scaled = resizeRgb16(frame.rgb16, width, height, encoded.width, encoded.height);
|
const scaled = resizeRgb16(frame.rgb16, width, height, encoded.width, encoded.height);
|
||||||
preview16 = {
|
preview16 = {
|
||||||
// The matrix travels with the samples so the editor knows how to
|
// The matrix travels with the samples so the editor knows how to
|
||||||
// turn camera RGB into sRGB without a second metadata fetch.
|
// turn camera RGB into sRGB without a second metadata fetch.
|
||||||
data: encodePng16(scaled, encoded.width, encoded.height, rgbCam),
|
data: await encodePng16Async(scaled, encoded.width, encoded.height, rgbCam),
|
||||||
width: encoded.width,
|
width: encoded.width,
|
||||||
height: encoded.height,
|
height: encoded.height,
|
||||||
rgbCam,
|
rgbCam,
|
||||||
@@ -290,21 +354,25 @@ export async function decodeRaw(buffer) {
|
|||||||
librawError = 'not a recognised raw container';
|
librawError = 'not a recognised raw container';
|
||||||
}
|
}
|
||||||
|
|
||||||
const embedded = await embeddedPreview(buffer);
|
// Keep the first candidate that sharp can actually decode. Never store bytes
|
||||||
if (embedded) {
|
// that did not decode: a 0x0 "preview" is an unopenable photo in the catalog.
|
||||||
|
// A handful of candidates is enough; each rejected one costs a header parse,
|
||||||
|
// not a full decode.
|
||||||
|
for (const embedded of (await embeddedPreviews(buffer)).slice(0, 6)) {
|
||||||
const proxy = await toJpegProxy(embedded, RAW_PREVIEW_EDGE);
|
const proxy = await toJpegProxy(embedded, RAW_PREVIEW_EDGE);
|
||||||
if (proxy) {
|
if (!proxy) continue;
|
||||||
const size = await jpegInfo(proxy.data);
|
const size = await jpegInfo(proxy.data);
|
||||||
return {
|
const width = size?.width || proxy.width;
|
||||||
jpeg: proxy.data,
|
const height = size?.height || proxy.height;
|
||||||
width: size?.width || proxy.width,
|
if (!width || !height) continue;
|
||||||
height: size?.height || proxy.height,
|
return {
|
||||||
engine: 'embedded',
|
jpeg: proxy.data,
|
||||||
ext: proxy.ext,
|
width,
|
||||||
note: `LibRaw could not decode this file (${librawError}); using the camera preview.`,
|
height,
|
||||||
};
|
engine: 'embedded',
|
||||||
}
|
ext: proxy.ext,
|
||||||
return { jpeg: embedded, width: 0, height: 0, engine: 'embedded', ext: 'jpg', note: librawError ?? undefined };
|
note: `LibRaw could not decode this file (${librawError}); using the camera preview.`,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new Error(
|
throw new Error(
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest';
|
|||||||
import {
|
import {
|
||||||
RAW_EXTENSIONS,
|
RAW_EXTENSIONS,
|
||||||
decodeRaw,
|
decodeRaw,
|
||||||
|
extractEmbeddedJpegs,
|
||||||
decodeStill,
|
decodeStill,
|
||||||
isRawName,
|
isRawName,
|
||||||
isStillName,
|
isStillName,
|
||||||
@@ -52,6 +53,56 @@ describe('raw format coverage', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const JPEG_SOI = Buffer.from([0xff, 0xd8, 0xff]);
|
||||||
|
const JPEG_EOI = Buffer.from([0xff, 0xd9]);
|
||||||
|
|
||||||
|
/** A JPEG-shaped run of `total` bytes with no nested markers. */
|
||||||
|
function jpegBytes(total) {
|
||||||
|
return Buffer.concat([JPEG_SOI, Buffer.alloc(Math.max(1, total - 5), 0x11), JPEG_EOI]);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('embedded preview fallback', () => {
|
||||||
|
it('lists candidates largest first and ignores thumbnail-sized runs', () => {
|
||||||
|
const small = jpegBytes(9000);
|
||||||
|
const big = jpegBytes(90000);
|
||||||
|
const tiny = jpegBytes(1200);
|
||||||
|
const buffer = Buffer.concat([
|
||||||
|
Buffer.alloc(128),
|
||||||
|
small,
|
||||||
|
Buffer.alloc(32),
|
||||||
|
big,
|
||||||
|
Buffer.alloc(32),
|
||||||
|
tiny,
|
||||||
|
Buffer.alloc(32),
|
||||||
|
]);
|
||||||
|
const lengths = extractEmbeddedJpegs(buffer).map((jpeg) => jpeg.length);
|
||||||
|
// Splitting candidates at every end-of-image marker can yield over-long
|
||||||
|
// slices that span two images; those fail to decode and are skipped. What
|
||||||
|
// matters is that both real previews are offered, largest first, and that
|
||||||
|
// thumbnail-sized runs are not.
|
||||||
|
expect(lengths).toEqual([...lengths].sort((a, b) => b - a));
|
||||||
|
expect(lengths).toContain(big.length);
|
||||||
|
expect(lengths).toContain(small.length);
|
||||||
|
expect(lengths).not.toContain(tiny.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not let a nested EXIF thumbnail truncate the full preview', () => {
|
||||||
|
// Regression: the scan used to stop at the thumbnail's end-of-image, so the
|
||||||
|
// "preview" it stored was a cut-off JPEG that sharp refused to decode and
|
||||||
|
// the import ended up as a 0x0 photo.
|
||||||
|
const thumb = jpegBytes(6000);
|
||||||
|
const outer = Buffer.concat([
|
||||||
|
JPEG_SOI,
|
||||||
|
Buffer.alloc(2000, 0x11),
|
||||||
|
thumb,
|
||||||
|
Buffer.alloc(40000, 0x11),
|
||||||
|
JPEG_EOI,
|
||||||
|
]);
|
||||||
|
const found = extractEmbeddedJpegs(Buffer.concat([Buffer.alloc(64), outer]));
|
||||||
|
expect(found[0].length).toBe(outer.length);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('TIFF decoding', () => {
|
describe('TIFF decoding', () => {
|
||||||
it('turns a TIFF into a JPEG proxy', async () => {
|
it('turns a TIFF into a JPEG proxy', async () => {
|
||||||
const { default: sharp } = await import('sharp');
|
const { default: sharp } = await import('sharp');
|
||||||
|
|||||||
+60
-6
@@ -71,7 +71,7 @@ import type { MergeResult } from './lib/merge';
|
|||||||
import { evictBitmap } from './lib/images';
|
import { evictBitmap } from './lib/images';
|
||||||
import { importFiles, uid } from './lib/import';
|
import { importFiles, uid } from './lib/import';
|
||||||
import { PRESETS } from './lib/presets';
|
import { PRESETS } from './lib/presets';
|
||||||
import { downloadXmp, readXmpFile, xmpToEdits } from './lib/xmp';
|
import { downloadXmp, readXmpFile, xmpToEdits, xmpToMetadata } from './lib/xmp';
|
||||||
import type {
|
import type {
|
||||||
Edits,
|
Edits,
|
||||||
EventRecord,
|
EventRecord,
|
||||||
@@ -2099,12 +2099,63 @@ export default function App() {
|
|||||||
try {
|
try {
|
||||||
const xml = await readXmpFile();
|
const xml = await readXmpFile();
|
||||||
if (!xml) return;
|
if (!xml) return;
|
||||||
const result = xmpToEdits(xml, target.edits);
|
|
||||||
updatePhoto(target.id, { edits: result.edits }, 'Import XMP sidecar');
|
// A sidecar can carry a grade, cataloguing fields, or both. Read the two
|
||||||
|
// halves independently: a metadata-only file from a DAM must not fail for
|
||||||
|
// lacking crs: settings, and a grade must not be rejected for lacking
|
||||||
|
// keywords. Whichever half is present is applied; neither wipes the other.
|
||||||
|
let edits = target.edits;
|
||||||
|
let settingsNote = '';
|
||||||
|
try {
|
||||||
|
const result = xmpToEdits(xml, target.edits);
|
||||||
|
edits = result.edits;
|
||||||
|
settingsNote =
|
||||||
|
result.source === 'luminary'
|
||||||
|
? 'Luminary settings'
|
||||||
|
: `${result.applied.length} Lightroom setting${result.applied.length === 1 ? '' : 's'}`;
|
||||||
|
} catch {
|
||||||
|
settingsNote = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
const meta = xmpToMetadata(xml);
|
||||||
|
const patch: Partial<PhotoRecord> = {};
|
||||||
|
const fields: string[] = [];
|
||||||
|
if (edits !== target.edits) patch.edits = edits;
|
||||||
|
if (meta.rating !== undefined) {
|
||||||
|
patch.rating = meta.rating;
|
||||||
|
fields.push('rating');
|
||||||
|
}
|
||||||
|
if (meta.label) {
|
||||||
|
patch.color = meta.label;
|
||||||
|
fields.push('label');
|
||||||
|
}
|
||||||
|
const keywords = new Set(target.keywords);
|
||||||
|
for (const word of meta.keywords) keywords.add(word);
|
||||||
|
if (keywords.size !== target.keywords.length) {
|
||||||
|
patch.keywords = [...keywords];
|
||||||
|
fields.push('keywords');
|
||||||
|
}
|
||||||
|
const paths = new Set(target.keywordPaths ?? []);
|
||||||
|
for (const path of meta.keywordPaths) paths.add(path);
|
||||||
|
if (paths.size !== (target.keywordPaths?.length ?? 0)) {
|
||||||
|
patch.keywordPaths = [...paths];
|
||||||
|
fields.push('keyword paths');
|
||||||
|
}
|
||||||
|
if (Object.keys(meta.iptc).length > 0) {
|
||||||
|
patch.iptc = { ...target.iptc, ...meta.iptc };
|
||||||
|
fields.push('IPTC');
|
||||||
|
}
|
||||||
|
if (meta.title && !target.title) patch.title = meta.title;
|
||||||
|
if (meta.caption) patch.caption = meta.caption;
|
||||||
|
if (meta.creator) patch.creator = meta.creator;
|
||||||
|
if (meta.copyright) patch.copyright = meta.copyright;
|
||||||
|
|
||||||
|
if (!patch.edits && fields.length === 0) {
|
||||||
|
throw new Error('That sidecar has no settings or metadata to import');
|
||||||
|
}
|
||||||
|
updatePhoto(target.id, patch, 'Import XMP sidecar');
|
||||||
setToast(
|
setToast(
|
||||||
result.source === 'luminary'
|
[settingsNote, fields.join(', ')].filter(Boolean).join(' · ') || 'Imported the sidecar',
|
||||||
? 'Imported Luminary settings from the sidecar'
|
|
||||||
: `Imported ${result.applied.length} Lightroom setting${result.applied.length === 1 ? '' : 's'}`,
|
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setToast(err instanceof Error ? err.message : 'Could not import the sidecar');
|
setToast(err instanceof Error ? err.message : 'Could not import the sidecar');
|
||||||
@@ -2516,6 +2567,9 @@ export default function App() {
|
|||||||
onVirtualCopy={() => void createVirtualCopy(activePhoto.id, true)}
|
onVirtualCopy={() => void createVirtualCopy(activePhoto.id, true)}
|
||||||
metadataPresets={metadataPresets}
|
metadataPresets={metadataPresets}
|
||||||
keywordLibrary={[...new Set(photos.flatMap((photo) => photo.keywords))].sort()}
|
keywordLibrary={[...new Set(photos.flatMap((photo) => photo.keywords))].sort()}
|
||||||
|
keywordPathLibrary={[
|
||||||
|
...new Set(photos.flatMap((photo) => photo.keywordPaths ?? [])),
|
||||||
|
].sort()}
|
||||||
onSaveSnapshot={(name) => saveSnapshot(activePhoto.id, name)}
|
onSaveSnapshot={(name) => saveSnapshot(activePhoto.id, name)}
|
||||||
onRestoreSnapshot={(snapshot) => restoreSnapshot(activePhoto.id, snapshot)}
|
onRestoreSnapshot={(snapshot) => restoreSnapshot(activePhoto.id, snapshot)}
|
||||||
onDeleteSnapshot={(snapshot) => deleteSnapshot(activePhoto.id, snapshot.id)}
|
onDeleteSnapshot={(snapshot) => deleteSnapshot(activePhoto.id, snapshot.id)}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import type { Preview16 } from '../lib/preview16';
|
|||||||
import { useMediaQuery } from '../lib/useMediaQuery';
|
import { useMediaQuery } from '../lib/useMediaQuery';
|
||||||
import { usePersistentState } from '../lib/usePersistentState';
|
import { usePersistentState } from '../lib/usePersistentState';
|
||||||
import { solveWhiteBalance } from '../lib/whiteBalance';
|
import { solveWhiteBalance } from '../lib/whiteBalance';
|
||||||
|
import { applyPresetEdits } from '../lib/presets';
|
||||||
import { buildAutoMask, type AutoMaskKind } from '../lib/autoMask';
|
import { buildAutoMask, type AutoMaskKind } from '../lib/autoMask';
|
||||||
import {
|
import {
|
||||||
buildLensCorrection,
|
buildLensCorrection,
|
||||||
@@ -157,6 +158,8 @@ interface Props {
|
|||||||
onVirtualCopy: () => void;
|
onVirtualCopy: () => void;
|
||||||
metadataPresets: MetadataPreset[];
|
metadataPresets: MetadataPreset[];
|
||||||
keywordLibrary: string[];
|
keywordLibrary: string[];
|
||||||
|
/** Hierarchical paths already in the library, for metadata suggestions. */
|
||||||
|
keywordPathLibrary?: string[];
|
||||||
onSaveSnapshot: (name: string) => void;
|
onSaveSnapshot: (name: string) => void;
|
||||||
onRestoreSnapshot: (snapshot: Snapshot) => void;
|
onRestoreSnapshot: (snapshot: Snapshot) => void;
|
||||||
onDeleteSnapshot: (snapshot: Snapshot) => void;
|
onDeleteSnapshot: (snapshot: Snapshot) => void;
|
||||||
@@ -191,6 +194,7 @@ export default function Develop({
|
|||||||
onVirtualCopy,
|
onVirtualCopy,
|
||||||
metadataPresets,
|
metadataPresets,
|
||||||
keywordLibrary,
|
keywordLibrary,
|
||||||
|
keywordPathLibrary = [],
|
||||||
onSaveSnapshot,
|
onSaveSnapshot,
|
||||||
onRestoreSnapshot,
|
onRestoreSnapshot,
|
||||||
onDeleteSnapshot,
|
onDeleteSnapshot,
|
||||||
@@ -1644,18 +1648,9 @@ export default function Develop({
|
|||||||
|
|
||||||
const applyPreset = useCallback(
|
const applyPreset = useCallback(
|
||||||
(preset: Preset) => {
|
(preset: Preset) => {
|
||||||
const next: Edits =
|
// The look grades over the photo's current white balance, so a correction
|
||||||
preset.id === 'original'
|
// made first is the base it is applied against.
|
||||||
? { ...defaultEdits(), crop: photo.edits.crop }
|
const next = applyPresetEdits(photo.edits, preset);
|
||||||
: {
|
|
||||||
...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, { edits: next }, `Preset: ${preset.name}`);
|
||||||
},
|
},
|
||||||
[onUpdate, photo.id, photo.edits],
|
[onUpdate, photo.id, photo.edits],
|
||||||
@@ -1773,6 +1768,7 @@ export default function Develop({
|
|||||||
onUpdate={(patch) => onUpdate(photo.id, patch)}
|
onUpdate={(patch) => onUpdate(photo.id, patch)}
|
||||||
presets={metadataPresets}
|
presets={metadataPresets}
|
||||||
keywordLibrary={keywordLibrary}
|
keywordLibrary={keywordLibrary}
|
||||||
|
keywordPathLibrary={keywordPathLibrary}
|
||||||
onSavePreset={onSaveMetadataPreset}
|
onSavePreset={onSaveMetadataPreset}
|
||||||
onDeletePreset={onDeleteMetadataPreset}
|
onDeletePreset={onDeleteMetadataPreset}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -46,6 +46,9 @@ export default function ImportModal({
|
|||||||
const [progress, setProgress] = useState<ImportProgress | null>(null);
|
const [progress, setProgress] = useState<ImportProgress | null>(null);
|
||||||
const [failures, setFailures] = useState<string[]>([]);
|
const [failures, setFailures] = useState<string[]>([]);
|
||||||
const [allowDuplicates, setAllowDuplicates] = useState(false);
|
const [allowDuplicates, setAllowDuplicates] = useState(false);
|
||||||
|
// 16-bit is the default an editor would expect, and it is what a raw import
|
||||||
|
// should keep unless the whole point is a smaller library.
|
||||||
|
const [sidecar16, setSidecar16] = useState(true);
|
||||||
const [createGallery, setCreateGallery] = useState(immichEnabled);
|
const [createGallery, setCreateGallery] = useState(immichEnabled);
|
||||||
const [galleryCreated, setGalleryCreated] = useState(false);
|
const [galleryCreated, setGalleryCreated] = useState(false);
|
||||||
const [galleryError, setGalleryError] = useState<string | null>(null);
|
const [galleryError, setGalleryError] = useState<string | null>(null);
|
||||||
@@ -128,7 +131,15 @@ export default function ImportModal({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const result = await importFiles(readyFiles, targetId, [], setProgress, cloud ?? null, controller.signal);
|
const result = await importFiles(
|
||||||
|
readyFiles,
|
||||||
|
targetId,
|
||||||
|
[],
|
||||||
|
setProgress,
|
||||||
|
cloud ?? null,
|
||||||
|
controller.signal,
|
||||||
|
{ sidecar16 },
|
||||||
|
);
|
||||||
if (result.photos.length) onImported(result.photos, targetId);
|
if (result.photos.length) onImported(result.photos, targetId);
|
||||||
|
|
||||||
let published = 0;
|
let published = 0;
|
||||||
@@ -347,13 +358,37 @@ export default function ImportModal({
|
|||||||
{rawCount > 0 && cloud && (
|
{rawCount > 0 && cloud && (
|
||||||
<div className="banner info">
|
<div className="banner info">
|
||||||
{local
|
{local
|
||||||
? 'Raw files are demosaiced by the Luminary local engine (LibRaw) on this PC, a few ' +
|
? 'Raw files are demosaiced by the Luminary local engine (LibRaw) on this PC, two ' +
|
||||||
'at a time in parallel. Each file usually takes 2–4 seconds, and nothing leaves your computer.'
|
'at a time; the rest of your selection waits its turn. A 24 MP raw takes a few ' +
|
||||||
: 'Raw files are demosaiced by the server (LibRaw), a few at a time in parallel. Each ' +
|
'seconds; a 40 MP compressed Fuji file takes closer to twenty. Nothing leaves ' +
|
||||||
'file usually takes 2–4 seconds.'}
|
'your computer.'
|
||||||
|
: 'Raw files are demosaiced by the server (LibRaw), two at a time; the rest of your ' +
|
||||||
|
'selection waits its turn. A 24 MP raw takes a few seconds; a 40 MP compressed ' +
|
||||||
|
'Fuji file takes closer to twenty.'}
|
||||||
|
{' '}A file the engine cannot decode still imports from the camera’s own preview.
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{rawCount > 0 && cloud && (
|
||||||
|
<>
|
||||||
|
<label className="check-row">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={sidecar16}
|
||||||
|
onChange={(e) => setSidecar16(e.target.checked)}
|
||||||
|
disabled={busy}
|
||||||
|
/>
|
||||||
|
Import raws at 16-bit (recommended)
|
||||||
|
</label>
|
||||||
|
<p className="muted small">
|
||||||
|
A 16-bit sidecar keeps every level the decoder read, so recovering shadows and
|
||||||
|
highlights works from 65,536 steps per channel instead of 256. It costs roughly
|
||||||
|
25× the JPEG in disk and download. Uncheck to import at 8-bit instead: smaller,
|
||||||
|
quicker to upload, but graded from the JPEG.
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
{progress && (
|
{progress && (
|
||||||
<div className="progress">
|
<div className="progress">
|
||||||
<div className="progress-bar">
|
<div className="progress-bar">
|
||||||
@@ -363,7 +398,9 @@ export default function ImportModal({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="muted small">
|
<div className="muted small">
|
||||||
{progress.done} / {progress.total} {progress.current ? `· ${progress.current}` : ''}
|
{progress.done} / {progress.total}
|
||||||
|
{progress.waiting ? ` · ${progress.waiting} waiting` : ''}
|
||||||
|
{progress.current ? ` · ${progress.current}` : ''}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
+131
-3
@@ -11,6 +11,8 @@ import {
|
|||||||
} from '../lib/denoiseModels';
|
} from '../lib/denoiseModels';
|
||||||
import type { DenoiseProgress } from '../lib/api';
|
import type { DenoiseProgress } from '../lib/api';
|
||||||
import { clamp } from '../lib/curves';
|
import { clamp } from '../lib/curves';
|
||||||
|
import { estimateKelvin, expressWhiteBalance, wbGainWithLook } from '../lib/whiteBalance';
|
||||||
|
import { addKeywordPath, removeKeywordPath } from '../lib/keywords';
|
||||||
import type {
|
import type {
|
||||||
CurveChannel,
|
CurveChannel,
|
||||||
Edits,
|
Edits,
|
||||||
@@ -107,6 +109,12 @@ export function BasicPanel({
|
|||||||
// come back with neutral values, so Auto WB matched As shot exactly.
|
// come back with neutral values, so Auto WB matched As shot exactly.
|
||||||
const thumbSrc = photo.thumbUrl ?? photo.thumb;
|
const thumbSrc = photo.thumbUrl ?? photo.thumb;
|
||||||
|
|
||||||
|
// A look adds its cast to the correction already in the sliders; this shows what
|
||||||
|
// that leaves the white balance at, so the final balance stays visible.
|
||||||
|
const lookCast = edits.presetLook && (edits.presetLook.temp || edits.presetLook.tint) ? edits.presetLook : null;
|
||||||
|
const finalWb = lookCast ? expressWhiteBalance(wbGainWithLook(edits.temp, edits.tint, edits.kelvin, lookCast)) : null;
|
||||||
|
const signed = (v: number) => (v > 0 ? `+${v}` : String(v));
|
||||||
|
|
||||||
const auto = async () => {
|
const auto = async () => {
|
||||||
setAutoBusy(true);
|
setAutoBusy(true);
|
||||||
try {
|
try {
|
||||||
@@ -180,6 +188,23 @@ export function BasicPanel({
|
|||||||
onChange={(v) => set({ tint: v }, 'Tint')}
|
onChange={(v) => set({ tint: v }, 'Tint')}
|
||||||
track="linear-gradient(90deg,#54b364,#a8b6c6,#c56ad2)"
|
track="linear-gradient(90deg,#54b364,#a8b6c6,#c56ad2)"
|
||||||
/>
|
/>
|
||||||
|
{lookCast && finalWb && (
|
||||||
|
<div
|
||||||
|
className="wb-look"
|
||||||
|
title="The look grades over your white balance, so it adds its own temperature and tint on top. These are the numbers the photo is actually graded at."
|
||||||
|
>
|
||||||
|
<span>
|
||||||
|
Look cast <b>{signed(lookCast.temp)} / {signed(lookCast.tint)}</b>
|
||||||
|
</span>
|
||||||
|
<span className="wb-look-final">
|
||||||
|
Final{' '}
|
||||||
|
{edits.kelvin != null
|
||||||
|
? `≈ ${Math.round(estimateKelvin(wbGainWithLook(edits.temp, edits.tint, edits.kelvin, lookCast)) / 10) * 10} K`
|
||||||
|
: `temp ${signed(finalWb.temp)}`}{' '}
|
||||||
|
· tint {signed(finalWb.tint)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="subhead">
|
<div className="subhead">
|
||||||
<span>Tone</span>
|
<span>Tone</span>
|
||||||
@@ -2662,6 +2687,7 @@ export function MetadataPanel({
|
|||||||
onUpdate,
|
onUpdate,
|
||||||
presets = [],
|
presets = [],
|
||||||
keywordLibrary = [],
|
keywordLibrary = [],
|
||||||
|
keywordPathLibrary = [],
|
||||||
onSavePreset,
|
onSavePreset,
|
||||||
onDeletePreset,
|
onDeletePreset,
|
||||||
}: {
|
}: {
|
||||||
@@ -2670,6 +2696,8 @@ export function MetadataPanel({
|
|||||||
onUpdate?: (patch: Partial<PhotoRecord>) => void;
|
onUpdate?: (patch: Partial<PhotoRecord>) => void;
|
||||||
presets?: MetadataPreset[];
|
presets?: MetadataPreset[];
|
||||||
keywordLibrary?: string[];
|
keywordLibrary?: string[];
|
||||||
|
/** Existing hierarchical paths in the library, offered as suggestions. */
|
||||||
|
keywordPathLibrary?: string[];
|
||||||
onSavePreset?: (preset: Omit<MetadataPreset, 'id'>) => void;
|
onSavePreset?: (preset: Omit<MetadataPreset, 'id'>) => void;
|
||||||
onDeletePreset?: (id: string) => void;
|
onDeletePreset?: (id: string) => void;
|
||||||
}) {
|
}) {
|
||||||
@@ -2705,11 +2733,21 @@ export function MetadataPanel({
|
|||||||
|
|
||||||
const patch = (next: Partial<PhotoRecord>) => onUpdate?.(next);
|
const patch = (next: Partial<PhotoRecord>) => onUpdate?.(next);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One entry point for both kinds of tag: a plain word stays flat, and
|
||||||
|
* `Nature > Birds` records the path and its ancestors. The leaf is added to
|
||||||
|
* `keywords` either way, so search and filters keep working on flat terms.
|
||||||
|
*/
|
||||||
const addKeyword = (raw?: string) => {
|
const addKeyword = (raw?: string) => {
|
||||||
const value = (raw ?? keyword).trim().replace(/,$/, '');
|
const value = (raw ?? keyword).trim().replace(/,$/, '');
|
||||||
if (!value) return;
|
if (!value) return;
|
||||||
const exists = photo.keywords.some((word) => word.toLowerCase() === value.toLowerCase());
|
patch(
|
||||||
if (!exists) patch({ keywords: [...photo.keywords, value.slice(0, 48)] });
|
addKeywordPath(
|
||||||
|
{ keywords: photo.keywords, keywordPaths: photo.keywordPaths ?? [] },
|
||||||
|
value,
|
||||||
|
/[>/|]/.test(value),
|
||||||
|
),
|
||||||
|
);
|
||||||
setKeyword('');
|
setKeyword('');
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -2717,6 +2755,19 @@ export function MetadataPanel({
|
|||||||
patch({ keywords: photo.keywords.filter((item) => item !== word) });
|
patch({ keywords: photo.keywords.filter((item) => item !== word) });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const removePath = (path: string) => {
|
||||||
|
patch(
|
||||||
|
removeKeywordPath(
|
||||||
|
{ keywords: photo.keywords, keywordPaths: photo.keywordPaths ?? [] },
|
||||||
|
path,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const patchIptc = (field: keyof NonNullable<PhotoRecord['iptc']>, value: string) => {
|
||||||
|
patch({ iptc: { ...photo.iptc, [field]: value } });
|
||||||
|
};
|
||||||
|
|
||||||
const applyPreset = (id: string) => {
|
const applyPreset = (id: string) => {
|
||||||
setPresetId(id);
|
setPresetId(id);
|
||||||
const preset = presets.find((item) => item.id === id);
|
const preset = presets.find((item) => item.id === id);
|
||||||
@@ -2795,11 +2846,32 @@ export function MetadataPanel({
|
|||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
{photo.keywordPaths?.length ? (
|
||||||
|
<>
|
||||||
|
<div className="metadata-keywords-head">
|
||||||
|
<span>Keyword paths</span>
|
||||||
|
<span className="muted small">{photo.keywordPaths.length}</span>
|
||||||
|
</div>
|
||||||
|
<div className="keyword-chips">
|
||||||
|
{photo.keywordPaths.map((path) => (
|
||||||
|
<button
|
||||||
|
key={path}
|
||||||
|
className="keyword-chip"
|
||||||
|
onClick={() => removePath(path)}
|
||||||
|
title="Remove this path and everything under it"
|
||||||
|
>
|
||||||
|
{path} <span aria-hidden="true">×</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<div className="keyword-add">
|
<div className="keyword-add">
|
||||||
<input
|
<input
|
||||||
value={keyword}
|
value={keyword}
|
||||||
list="lumen-keyword-library"
|
list="lumen-keyword-library"
|
||||||
placeholder="Add keyword…"
|
placeholder="Add keyword, or Nature > Birds…"
|
||||||
onChange={(e) => setKeyword(e.target.value)}
|
onChange={(e) => setKeyword(e.target.value)}
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === 'Enter' || e.key === ',') {
|
if (e.key === 'Enter' || e.key === ',') {
|
||||||
@@ -2816,9 +2888,65 @@ export function MetadataPanel({
|
|||||||
{keywordLibrary.map((word) => (
|
{keywordLibrary.map((word) => (
|
||||||
<option key={word} value={word} />
|
<option key={word} value={word} />
|
||||||
))}
|
))}
|
||||||
|
{keywordPathLibrary.map((path) => (
|
||||||
|
<option key={`path:${path}`} value={path} />
|
||||||
|
))}
|
||||||
</datalist>
|
</datalist>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="metadata-keywords-head">
|
||||||
|
<span>IPTC</span>
|
||||||
|
</div>
|
||||||
|
<label className="field">
|
||||||
|
<span>Headline</span>
|
||||||
|
<input
|
||||||
|
value={photo.iptc?.headline ?? ''}
|
||||||
|
placeholder="Who, what, where"
|
||||||
|
onChange={(e) => patchIptc('headline', e.target.value)}
|
||||||
|
disabled={!onUpdate}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<div className="field-row">
|
||||||
|
<label className="field">
|
||||||
|
<span>Credit</span>
|
||||||
|
<input
|
||||||
|
value={photo.iptc?.credit ?? ''}
|
||||||
|
placeholder="Photographer credit"
|
||||||
|
onChange={(e) => patchIptc('credit', e.target.value)}
|
||||||
|
disabled={!onUpdate}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span>Source</span>
|
||||||
|
<input
|
||||||
|
value={photo.iptc?.source ?? ''}
|
||||||
|
placeholder="Agency or client"
|
||||||
|
onChange={(e) => patchIptc('source', e.target.value)}
|
||||||
|
disabled={!onUpdate}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div className="field-row">
|
||||||
|
<label className="field">
|
||||||
|
<span>City</span>
|
||||||
|
<input
|
||||||
|
value={photo.iptc?.city ?? ''}
|
||||||
|
placeholder="City"
|
||||||
|
onChange={(e) => patchIptc('city', e.target.value)}
|
||||||
|
disabled={!onUpdate}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span>Country</span>
|
||||||
|
<input
|
||||||
|
value={photo.iptc?.country ?? ''}
|
||||||
|
placeholder="Country"
|
||||||
|
onChange={(e) => patchIptc('country', e.target.value)}
|
||||||
|
disabled={!onUpdate}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="metadata-presets">
|
<div className="metadata-presets">
|
||||||
<select value={presetId} onChange={(e) => applyPreset(e.target.value)} disabled={!presets.length || !onUpdate}>
|
<select value={presetId} onChange={(e) => applyPreset(e.target.value)} disabled={!presets.length || !onUpdate}>
|
||||||
<option value="">Apply metadata preset…</option>
|
<option value="">Apply metadata preset…</option>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { normalizeEdits } from '../lib/edits';
|
import { applyPresetEdits } from '../lib/presets';
|
||||||
import { get16BitSource, getBitmap } from '../lib/images';
|
import { get16BitSource, getBitmap } from '../lib/images';
|
||||||
import { Renderer, rotatedBounds } from '../gl/renderer';
|
import { Renderer, rotatedBounds } from '../gl/renderer';
|
||||||
import type { PhotoRecord, Preset } from '../types';
|
import type { PhotoRecord, Preset } from '../types';
|
||||||
@@ -17,17 +17,66 @@ const THUMB_EDGE = 200;
|
|||||||
const keyOf = (photoId: string, presetId: string, crop: string, source: string) =>
|
const keyOf = (photoId: string, presetId: string, crop: string, source: string) =>
|
||||||
`${photoId}|${presetId}|${crop}|${source}`;
|
`${photoId}|${presetId}|${crop}|${source}`;
|
||||||
|
|
||||||
|
/** Stringified grades, cached per edits object so a render loop cannot make this
|
||||||
|
* cost more than one serialisation. */
|
||||||
|
const signatures = new WeakMap<object, string>();
|
||||||
|
|
||||||
|
function gradeSignature(edits: object): string {
|
||||||
|
let sig = signatures.get(edits);
|
||||||
|
if (sig === undefined) {
|
||||||
|
sig = JSON.stringify(edits);
|
||||||
|
signatures.set(edits, sig);
|
||||||
|
}
|
||||||
|
return sig;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A slider drag produces a new grade every frame. Re-rendering the whole rail
|
||||||
|
* that often would make the canvas stutter, so the tiles follow the grade a
|
||||||
|
* moment after it settles.
|
||||||
|
*
|
||||||
|
* The timer is keyed on the grade's signature, not on the object: the editor can
|
||||||
|
* hand down a fresh edits object on every render, and an identity-keyed timer
|
||||||
|
* would then be reset forever and the rail would never catch up.
|
||||||
|
*/
|
||||||
|
function useSettledEdits<T extends object>(edits: T, sig: string, delay: number): T {
|
||||||
|
const [settled, setSettled] = useState(() => ({ sig, edits }));
|
||||||
|
useEffect(() => {
|
||||||
|
if (sig === settled.sig) return;
|
||||||
|
const timer = window.setTimeout(() => setSettled({ sig, edits }), delay);
|
||||||
|
return () => window.clearTimeout(timer);
|
||||||
|
// `edits` is read from the render that changed the signature; restarting on
|
||||||
|
// a new object with the same grade is exactly what this avoids.
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [sig, delay, settled.sig]);
|
||||||
|
return settled.edits;
|
||||||
|
}
|
||||||
|
|
||||||
export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> {
|
export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> {
|
||||||
const [thumbs, setThumbs] = useState<Record<string, string>>({});
|
const [thumbs, setThumbs] = useState<Record<string, string>>({});
|
||||||
|
// Which photo the thumbnails in state belong to; a new photo may not reuse them.
|
||||||
|
const shownPhoto = useRef(photo.id);
|
||||||
// Preset edits never change after creation, so a stable id list is enough to
|
// Preset edits never change after creation, so a stable id list is enough to
|
||||||
// avoid re-running for every parent render.
|
// avoid re-running for every parent render.
|
||||||
const presetKey = presets.map((p) => p.id).join('|');
|
const presetKey = presets.map((p) => p.id).join('|');
|
||||||
const crop = photo.edits.crop;
|
// Tiles show the look over the grade the photo has right now, so clicking one
|
||||||
|
// is what the thumbnail promised. The grade is read once it settles instead of
|
||||||
|
// on every frame of a slider drag.
|
||||||
|
const settled = useSettledEdits(photo.edits, gradeSignature(photo.edits), 280);
|
||||||
|
// Applying a look replaces any cast the last one added, so the current look is
|
||||||
|
// dropped from the base: tiles keep their images while the photographer clicks
|
||||||
|
// through looks, and each tile still shows what that click would produce.
|
||||||
|
const base =
|
||||||
|
settled.presetLook && (settled.presetLook.temp || settled.presetLook.tint)
|
||||||
|
? { ...settled, presetLook: { temp: 0, tint: 0 } }
|
||||||
|
: settled;
|
||||||
|
const crop = base.crop;
|
||||||
const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(',');
|
const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(',');
|
||||||
// The preset previews keep the photo's camera profile, so a reprocess or a
|
// 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.
|
// different profile has to invalidate the tiles the same way the grade does.
|
||||||
const profile = photo.edits.cameraProfile;
|
const profile = base.cameraProfile;
|
||||||
const sourceKey = `${photo.previewVersion ?? 0}|${profile ? profile.matrix.join(',') : ''}`;
|
const gradeKey = JSON.stringify({ ...base, crop: undefined, cameraProfile: undefined });
|
||||||
|
const sourceKey = `${photo.previewVersion ?? 0}|${profile ? profile.matrix.join(',') : ''}|${gradeKey}`;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let alive = true;
|
let alive = true;
|
||||||
@@ -39,7 +88,19 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
|
|||||||
const hit = cache.get(keyOf(photo.id, preset.id, cropKey, sourceKey));
|
const hit = cache.get(keyOf(photo.id, preset.id, cropKey, sourceKey));
|
||||||
if (hit) known[preset.id] = hit;
|
if (hit) known[preset.id] = hit;
|
||||||
}
|
}
|
||||||
setThumbs(known);
|
// Keep the previous tiles of this photo on screen until their replacements
|
||||||
|
// render: a grade change must not empty the rail for the five seconds a full
|
||||||
|
// batch takes.
|
||||||
|
const samePhoto = shownPhoto.current === photo.id;
|
||||||
|
shownPhoto.current = photo.id;
|
||||||
|
setThumbs((prev) => {
|
||||||
|
const next: Record<string, string> = {};
|
||||||
|
for (const preset of presets) {
|
||||||
|
const url = known[preset.id] ?? (samePhoto ? prev[preset.id] : undefined);
|
||||||
|
if (url) next[preset.id] = url;
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
|
||||||
const pending = presets.filter((p) => !known[p.id]);
|
const pending = presets.filter((p) => !known[p.id]);
|
||||||
if (!pending.length) return;
|
if (!pending.length) return;
|
||||||
@@ -63,7 +124,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
|
|||||||
for (const preset of pending) {
|
for (const preset of pending) {
|
||||||
if (!alive) break;
|
if (!alive) break;
|
||||||
try {
|
try {
|
||||||
renderer.render({ ...normalizeEdits(preset.edits), crop, cameraProfile: profile }, {
|
renderer.render(applyPresetEdits(base, preset), {
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
upscale: Math.max(width / cropW, height / cropH) > 1.05,
|
upscale: Math.max(width / cropW, height / cropH) > 1.05,
|
||||||
|
|||||||
+4
-2
@@ -3,7 +3,7 @@ import type { Preview16 } from '../lib/preview16';
|
|||||||
import type { CurvePoint, Edits, GeometryEdits, LocalLayer } from '../types';
|
import type { CurvePoint, Edits, GeometryEdits, LocalLayer } from '../types';
|
||||||
import { buildSampler, clamp01 } from '../lib/curves';
|
import { buildSampler, clamp01 } from '../lib/curves';
|
||||||
import { bwFilterRgb, MAX_HEAL_SPOTS, MAX_LOCAL_LAYERS } from '../lib/edits';
|
import { bwFilterRgb, MAX_HEAL_SPOTS, MAX_LOCAL_LAYERS } from '../lib/edits';
|
||||||
import { wbGainFor } from '../lib/whiteBalance';
|
import { wbGainWithLook } from '../lib/whiteBalance';
|
||||||
import { buildLocalMasks, maskSignature } from './masks';
|
import { buildLocalMasks, maskSignature } from './masks';
|
||||||
import { getActiveProofCube, type SoftProofCube } from '../lib/softProof';
|
import { getActiveProofCube, type SoftProofCube } from '../lib/softProof';
|
||||||
|
|
||||||
@@ -1875,7 +1875,9 @@ export class Renderer {
|
|||||||
g.f('u_srcLod', Math.max(0, Math.min(12, srcLod)));
|
g.f('u_srcLod', Math.max(0, Math.min(12, srcLod)));
|
||||||
g.f('u_pick', -1);
|
g.f('u_pick', -1);
|
||||||
g.v2('u_pickUv', 0, 0);
|
g.v2('u_pickUv', 0, 0);
|
||||||
const wb = wbGainFor(edits.temp, edits.tint, edits.kelvin);
|
// The photographer's correction is the base; an applied look only adds its
|
||||||
|
// cast on top of it (see applyPresetEdits).
|
||||||
|
const wb = wbGainWithLook(edits.temp, edits.tint, edits.kelvin, edits.presetLook);
|
||||||
g.v3('u_wbGain', wb[0], wb[1], wb[2]);
|
g.v3('u_wbGain', wb[0], wb[1], wb[2]);
|
||||||
g.f('u_exposure', edits.exposure);
|
g.f('u_exposure', edits.exposure);
|
||||||
g.f('u_recovery', edits.recovery);
|
g.f('u_recovery', edits.recovery);
|
||||||
|
|||||||
+9
-1
@@ -155,8 +155,16 @@ export function pullProofs(): Promise<ProofSummary[]> {
|
|||||||
return request<{ proofs: ProofSummary[] }>('/api/proofs').then((res) => res.proofs ?? []);
|
return request<{ proofs: ProofSummary[] }>('/api/proofs').then((res) => res.proofs ?? []);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function uploadOriginal(id: string, file: File | Blob, name: string): Promise<UploadResult> {
|
export function uploadOriginal(
|
||||||
|
id: string,
|
||||||
|
file: File | Blob,
|
||||||
|
name: string,
|
||||||
|
options: { sidecar?: boolean } = {},
|
||||||
|
): Promise<UploadResult> {
|
||||||
const query = new URLSearchParams({ name, mime: file.type || 'application/octet-stream' });
|
const query = new URLSearchParams({ name, mime: file.type || 'application/octet-stream' });
|
||||||
|
// Only an opt-out is sent: an older server ignores the parameter and keeps
|
||||||
|
// its configured default, and every other upload keeps the shorter URL.
|
||||||
|
if (options.sidecar === false) query.set('sidecar', '0');
|
||||||
return request<UploadResult>(`/api/photos/${encodeURIComponent(id)}/original?${query}`, {
|
return request<UploadResult>(`/api/photos/${encodeURIComponent(id)}/original?${query}`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/octet-stream' },
|
headers: { 'Content-Type': 'application/octet-stream' },
|
||||||
|
|||||||
@@ -82,6 +82,7 @@ const GROUPS: Record<EditSectionId, (keyof Edits)[]> = {
|
|||||||
'temp',
|
'temp',
|
||||||
'tint',
|
'tint',
|
||||||
'kelvin',
|
'kelvin',
|
||||||
|
'presetLook',
|
||||||
'exposure',
|
'exposure',
|
||||||
'recovery',
|
'recovery',
|
||||||
'contrast',
|
'contrast',
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import type {
|
|||||||
LocalMaskKind,
|
LocalMaskKind,
|
||||||
LocalPoint,
|
LocalPoint,
|
||||||
LocalStroke,
|
LocalStroke,
|
||||||
|
IptcFields,
|
||||||
LensCorrections,
|
LensCorrections,
|
||||||
LensProfile,
|
LensProfile,
|
||||||
RasterMask,
|
RasterMask,
|
||||||
@@ -177,6 +178,7 @@ export function defaultEdits(): Edits {
|
|||||||
temp: 0,
|
temp: 0,
|
||||||
tint: 0,
|
tint: 0,
|
||||||
kelvin: null,
|
kelvin: null,
|
||||||
|
presetLook: { temp: 0, tint: 0 },
|
||||||
exposure: 0,
|
exposure: 0,
|
||||||
recovery: 0,
|
recovery: 0,
|
||||||
contrast: 0,
|
contrast: 0,
|
||||||
@@ -511,6 +513,10 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
|
|||||||
typeof input.kelvin === 'number' && Number.isFinite(input.kelvin)
|
typeof input.kelvin === 'number' && Number.isFinite(input.kelvin)
|
||||||
? clamp(input.kelvin, 1500, 15000)
|
? clamp(input.kelvin, 1500, 15000)
|
||||||
: null,
|
: null,
|
||||||
|
presetLook: {
|
||||||
|
temp: num(input.presetLook?.temp, 0, -100, 100),
|
||||||
|
tint: num(input.presetLook?.tint, 0, -100, 100),
|
||||||
|
},
|
||||||
exposure: num(input.exposure, 0, -5, 5),
|
exposure: num(input.exposure, 0, -5, 5),
|
||||||
recovery: num(input.recovery, 0, 0, 100),
|
recovery: num(input.recovery, 0, 0, 100),
|
||||||
contrast: num(input.contrast, 0, -100, 100),
|
contrast: num(input.contrast, 0, -100, 100),
|
||||||
@@ -638,6 +644,31 @@ export function isEdited(edits: Edits): boolean {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Trimmed, capped strings only: IPTC goes into files, so no objects or arrays. */
|
||||||
|
function textField(value: unknown, max: number): string | undefined {
|
||||||
|
if (typeof value !== 'string') return undefined;
|
||||||
|
const trimmed = value.trim();
|
||||||
|
return trimmed ? trimmed.slice(0, max) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitiseIptc(input: unknown): IptcFields | undefined {
|
||||||
|
if (!input || typeof input !== 'object') return undefined;
|
||||||
|
const raw = input as Record<string, unknown>;
|
||||||
|
const fields: IptcFields = {
|
||||||
|
headline: textField(raw.headline, 256),
|
||||||
|
credit: textField(raw.credit, 128),
|
||||||
|
source: textField(raw.source, 128),
|
||||||
|
city: textField(raw.city, 128),
|
||||||
|
state: textField(raw.state, 128),
|
||||||
|
country: textField(raw.country, 128),
|
||||||
|
location: textField(raw.location, 128),
|
||||||
|
};
|
||||||
|
const kept = Object.fromEntries(
|
||||||
|
Object.entries(fields).filter(([, value]) => value !== undefined),
|
||||||
|
) as IptcFields;
|
||||||
|
return Object.keys(kept).length > 0 ? kept : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): PhotoRecord {
|
export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): PhotoRecord {
|
||||||
const edits = normalizeEdits(input.edits);
|
const edits = normalizeEdits(input.edits);
|
||||||
const addedAt = input.addedAt ?? Date.now();
|
const addedAt = input.addedAt ?? Date.now();
|
||||||
@@ -693,6 +724,12 @@ export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): Ph
|
|||||||
flag: (input.flag ?? 'none') as Flag,
|
flag: (input.flag ?? 'none') as Flag,
|
||||||
color: (input.color ?? '') as ColorLabel,
|
color: (input.color ?? '') as ColorLabel,
|
||||||
keywords: Array.isArray(input.keywords) ? input.keywords : [],
|
keywords: Array.isArray(input.keywords) ? input.keywords : [],
|
||||||
|
keywordPaths: Array.isArray(input.keywordPaths)
|
||||||
|
? input.keywordPaths.filter(
|
||||||
|
(path): path is string => typeof path === 'string' && path.trim().length > 0,
|
||||||
|
).slice(0, 200)
|
||||||
|
: undefined,
|
||||||
|
iptc: sanitiseIptc(input.iptc),
|
||||||
edits,
|
edits,
|
||||||
history:
|
history:
|
||||||
Array.isArray(input.history) && input.history.length
|
Array.isArray(input.history) && input.history.length
|
||||||
|
|||||||
+14
-11
@@ -1,6 +1,7 @@
|
|||||||
import type { Edits, PhotoRecord } from '../types';
|
import type { Edits, PhotoRecord } from '../types';
|
||||||
import { get16BitSource, getBitmap } from './images';
|
import { get16BitSource, getBitmap } from './images';
|
||||||
import { normalizeEdits } from './edits';
|
import { normalizeEdits } from './edits';
|
||||||
|
import { photoMetadataAttributes, photoMetadataElements } from './xmp';
|
||||||
import { buildLensCorrection } from './lensEngine';
|
import { buildLensCorrection } from './lensEngine';
|
||||||
import { outputSize, Renderer } from '../gl/renderer';
|
import { outputSize, Renderer } from '../gl/renderer';
|
||||||
import { getDenoisedBitmap } from './images';
|
import { getDenoisedBitmap } from './images';
|
||||||
@@ -272,18 +273,20 @@ function paintWatermark(source: HTMLCanvasElement, photo: PhotoRecord, opts: Exp
|
|||||||
return canvas;
|
return canvas;
|
||||||
}
|
}
|
||||||
|
|
||||||
function xmlEscape(value: string) {
|
/**
|
||||||
return value
|
* The XMP packet embedded in an exported file.
|
||||||
.replace(/&/g, '&')
|
*
|
||||||
.replace(/</g, '<')
|
* Built from the same helpers the sidecar writer uses, so a JPEG and its .xmp
|
||||||
.replace(/>/g, '>')
|
* cannot drift: rating, colour label, keywords, the `lr:` hierarchy and the
|
||||||
.replace(/"/g, '"');
|
* IPTC core all travel with the file.
|
||||||
}
|
*/
|
||||||
|
|
||||||
function buildXmp(photo: PhotoRecord) {
|
function buildXmp(photo: PhotoRecord) {
|
||||||
const title = photo.title || photo.name;
|
return `<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?><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:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:Iptc4xmpCore="http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:lr="http://ns.adobe.com/lightroom/1.0/"${photoMetadataAttributes(
|
||||||
const keywords = photo.keywords.map((word) => `<rdf:li>${xmlEscape(word)}</rdf:li>`).join('');
|
photo,
|
||||||
return `<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?><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:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/"><dc:title><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(title)}</rdf:li></rdf:Alt></dc:title><dc:description><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(photo.caption ?? '')}</rdf:li></rdf:Alt></dc:description><dc:creator><rdf:Seq><rdf:li>${xmlEscape(photo.creator ?? '')}</rdf:li></rdf:Seq></dc:creator><dc:rights><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(photo.copyright ?? '')}</rdf:li></rdf:Alt></dc:rights><dc:subject><rdf:Bag>${keywords}</rdf:Bag></dc:subject></rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end="w"?>`.slice(0, 65000);
|
)}>${photoMetadataElements(photo)}</rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end="w"?>`.slice(
|
||||||
|
0,
|
||||||
|
65000,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function appSegment(marker: number, header: Uint8Array, payload: Uint8Array): Uint8Array | null {
|
function appSegment(marker: number, header: Uint8Array, payload: Uint8Array): Uint8Array | null {
|
||||||
|
|||||||
+118
-22
@@ -10,6 +10,8 @@ export interface ImportProgress {
|
|||||||
done: number;
|
done: number;
|
||||||
total: number;
|
total: number;
|
||||||
current: string;
|
current: string;
|
||||||
|
/** Files that have not started yet, so a long queue reads as working. */
|
||||||
|
waiting?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ImportResult {
|
export interface ImportResult {
|
||||||
@@ -20,13 +22,44 @@ export interface ImportResult {
|
|||||||
|
|
||||||
/** Provided by the app when a Luminary server is connected. */
|
/** Provided by the app when a Luminary server is connected. */
|
||||||
export interface CloudImport {
|
export interface CloudImport {
|
||||||
uploadOriginal: (id: string, file: File, name: string) => Promise<UploadResult>;
|
uploadOriginal: (
|
||||||
|
id: string,
|
||||||
|
file: File,
|
||||||
|
name: string,
|
||||||
|
options?: { sidecar?: boolean },
|
||||||
|
) => Promise<UploadResult>;
|
||||||
push: (photo: PhotoRecord) => Promise<PhotoRecord>;
|
push: (photo: PhotoRecord) => Promise<PhotoRecord>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Files imported at once; the server bounds how many raws decode in parallel. */
|
export interface ImportOptions {
|
||||||
|
/**
|
||||||
|
* Keep the 16-bit sidecar for raws in this import. On by default: the editor
|
||||||
|
* grades the decoded samples instead of 256-level JPEG pixels. Turning it off
|
||||||
|
* makes each raw import smaller and quicker, at the cost of an 8-bit grade.
|
||||||
|
*/
|
||||||
|
sidecar16?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Files imported at once when a Luminary server is connected. */
|
||||||
const IMPORT_CONCURRENCY = 4;
|
const IMPORT_CONCURRENCY = 4;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Raws and TIFFs are decoded by the server, which is where the work piles up, so
|
||||||
|
* this window is about one thing: how long a single upload request stays open.
|
||||||
|
*
|
||||||
|
* Measured on a 12-core server with 40 MP X-Trans RAFs through the real decode
|
||||||
|
* path: one file 28.4 s, two at once 44.4-45.4 s each, four at once 87.4-102.4 s
|
||||||
|
* each. Parallel X-Trans decodes barely scale here, so four-wide made every
|
||||||
|
* request about 1.5 minutes long and still finished sixteen files slower than
|
||||||
|
* two-wide (about 410 s against 360 s). Anything sitting in front of the server
|
||||||
|
* with a 60 s read timeout - the nginx default - answers 504 while the origin
|
||||||
|
* carries on decoding, which looks like a failed import of the files that were
|
||||||
|
* still in flight. Two keeps a request at ~45 s and is faster overall; Bayer
|
||||||
|
* files lose a little (8 NEFs took 20.8 s two at a time, 17.4 s four at a time)
|
||||||
|
* in exchange for every raw import staying inside a proxy's patience.
|
||||||
|
*/
|
||||||
|
const RAW_IMPORT_CONCURRENCY = 2;
|
||||||
|
|
||||||
export function uid(): string {
|
export function uid(): string {
|
||||||
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID();
|
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID();
|
||||||
return `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
|
return `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
|
||||||
@@ -44,6 +77,31 @@ function mapLimit<T>(items: T[], limit: number, fn: (item: T, index: number) =>
|
|||||||
return Promise.all(runners);
|
return Promise.all(runners);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A counting semaphore. `acquire()` resolves with a release function, so a slot
|
||||||
|
* is returned even when the guarded work throws or the import is cancelled.
|
||||||
|
* Waiters are served in order.
|
||||||
|
*/
|
||||||
|
function createSemaphore(slots: number) {
|
||||||
|
let free = Math.max(1, slots);
|
||||||
|
const waiting: (() => void)[] = [];
|
||||||
|
return {
|
||||||
|
async acquire(): Promise<() => void> {
|
||||||
|
if (free > 0) free -= 1;
|
||||||
|
else await new Promise<void>((resolve) => waiting.push(resolve));
|
||||||
|
let released = false;
|
||||||
|
return () => {
|
||||||
|
if (released) return;
|
||||||
|
released = true;
|
||||||
|
const next = waiting.shift();
|
||||||
|
// Hand the slot straight over, so it is never briefly up for grabs.
|
||||||
|
if (next) next();
|
||||||
|
else free += 1;
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function formatShutter(time: unknown): string | undefined {
|
function formatShutter(time: unknown): string | undefined {
|
||||||
if (typeof time !== 'number' || !Number.isFinite(time) || time <= 0) return undefined;
|
if (typeof time !== 'number' || !Number.isFinite(time) || time <= 0) return undefined;
|
||||||
if (time >= 1) return `${Math.round(time * 10) / 10}s`;
|
if (time >= 1) return `${Math.round(time * 10) / 10}s`;
|
||||||
@@ -127,9 +185,10 @@ async function importRaw(
|
|||||||
defaults: CameraLensDefault[],
|
defaults: CameraLensDefault[],
|
||||||
/** TIFF goes through the same proxy path but is not a raw container. */
|
/** TIFF goes through the same proxy path but is not a raw container. */
|
||||||
raw = true,
|
raw = true,
|
||||||
|
sidecar16 = true,
|
||||||
): Promise<PhotoRecord> {
|
): Promise<PhotoRecord> {
|
||||||
const id = uid();
|
const id = uid();
|
||||||
const upload = await cloud.uploadOriginal(id, file, file.name);
|
const upload = await cloud.uploadOriginal(id, file, file.name, { sidecar: sidecar16 });
|
||||||
const previewUrl = upload.previewUrl ?? `/api/photos/${id}/preview`;
|
const previewUrl = upload.previewUrl ?? `/api/photos/${id}/preview`;
|
||||||
const res = await fetch(previewUrl, { credentials: 'same-origin' });
|
const res = await fetch(previewUrl, { credentials: 'same-origin' });
|
||||||
if (!res.ok) throw new Error('The server could not produce a preview for this raw file');
|
if (!res.ok) throw new Error('The server could not produce a preview for this raw file');
|
||||||
@@ -137,8 +196,10 @@ async function importRaw(
|
|||||||
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
|
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
|
||||||
const thumb = await makeThumb(bitmap);
|
const thumb = await makeThumb(bitmap);
|
||||||
const { meta, takenAt } = await readMeta(file);
|
const { meta, takenAt } = await readMeta(file);
|
||||||
const width = upload.width ?? bitmap.width;
|
// `??` is wrong here: the server reports 0 for a dimension it could not read,
|
||||||
const height = upload.height ?? bitmap.height;
|
// and 0 is not nullish, so a failed decode produced a 0x0 catalog record.
|
||||||
|
const width = upload.width || bitmap.width;
|
||||||
|
const height = upload.height || bitmap.height;
|
||||||
const edits = editsForImport(meta, defaults);
|
const edits = editsForImport(meta, defaults);
|
||||||
bitmap.close();
|
bitmap.close();
|
||||||
|
|
||||||
@@ -232,7 +293,9 @@ export async function importFiles(
|
|||||||
onProgress?: (p: ImportProgress) => void,
|
onProgress?: (p: ImportProgress) => void,
|
||||||
cloud?: CloudImport | null,
|
cloud?: CloudImport | null,
|
||||||
signal?: AbortSignal,
|
signal?: AbortSignal,
|
||||||
|
options: ImportOptions = {},
|
||||||
): Promise<ImportResult> {
|
): Promise<ImportResult> {
|
||||||
|
const sidecar16 = options.sidecar16 !== false;
|
||||||
const result: ImportResult = { photos: [], failed: [] };
|
const result: ImportResult = { photos: [], failed: [] };
|
||||||
const images = files.filter(isSupportedFile);
|
const images = files.filter(isSupportedFile);
|
||||||
const total = images.length;
|
const total = images.length;
|
||||||
@@ -241,27 +304,60 @@ export async function importFiles(
|
|||||||
const collected: { index: number; photo: PhotoRecord }[] = [];
|
const collected: { index: number; photo: PhotoRecord }[] = [];
|
||||||
const defaults = await loadCameraLensDefaults().catch(() => []);
|
const defaults = await loadCameraLensDefaults().catch(() => []);
|
||||||
let done = 0;
|
let done = 0;
|
||||||
|
let active = 0;
|
||||||
|
// A wide selection spends most of its time inside a narrow window: without a
|
||||||
|
// waiting count the dialog would show "4 / 16" and no sign of the other 12.
|
||||||
|
const report = (current: string) =>
|
||||||
|
onProgress?.({ done, total, current, waiting: Math.max(0, total - done - active) });
|
||||||
|
|
||||||
|
const rawSlots = createSemaphore(RAW_IMPORT_CONCURRENCY);
|
||||||
|
|
||||||
await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => {
|
await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => {
|
||||||
if (signal?.aborted) return;
|
if (signal?.aborted) return;
|
||||||
|
const viaServer = isRawFile(file) || isTiffFile(file);
|
||||||
|
// Camera JPEGs and PNGs stay this wide, because the browser decodes them
|
||||||
|
// locally and they are seconds apart at worst. A raw holds one of a couple
|
||||||
|
// of server slots first, so the upload window can stay wide for the network
|
||||||
|
// while the decode window stays as narrow as the decoder pool.
|
||||||
|
const release = viaServer ? await rawSlots.acquire() : null;
|
||||||
try {
|
try {
|
||||||
const viaServer = isRawFile(file) || isTiffFile(file);
|
// The import may have been cancelled while this file queued for a slot.
|
||||||
const photo = viaServer
|
if (signal?.aborted) return;
|
||||||
? cloud
|
// Report before the work starts, not only when it finishes. A 40 MP raw
|
||||||
? await importRaw(file, eventId, keywords, cloud, defaults, isRawFile(file))
|
// takes seconds, and four of them finish together: because progress was
|
||||||
: (() => {
|
// only emitted in `finally`, the bar stayed hidden until the first batch
|
||||||
throw new Error('Raw files need the Luminary server. Sign in, then import again.');
|
// completed and then jumped to 4.
|
||||||
})()
|
active += 1;
|
||||||
: await importStandard(file, eventId, keywords, cloud, defaults);
|
report(file.name);
|
||||||
collected.push({ index, photo });
|
try {
|
||||||
} catch (err) {
|
const photo = viaServer
|
||||||
result.failed.push({
|
? cloud
|
||||||
name: file.name,
|
? await importRaw(
|
||||||
reason: err instanceof Error ? err.message : 'Unsupported image format',
|
file,
|
||||||
});
|
eventId,
|
||||||
|
keywords,
|
||||||
|
cloud,
|
||||||
|
defaults,
|
||||||
|
isRawFile(file),
|
||||||
|
sidecar16,
|
||||||
|
)
|
||||||
|
: (() => {
|
||||||
|
throw new Error('Raw files need the Luminary server. Sign in, then import again.');
|
||||||
|
})()
|
||||||
|
: await importStandard(file, eventId, keywords, cloud, defaults);
|
||||||
|
collected.push({ index, photo });
|
||||||
|
} catch (err) {
|
||||||
|
result.failed.push({
|
||||||
|
name: file.name,
|
||||||
|
reason: err instanceof Error ? err.message : 'Unsupported image format',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
active -= 1;
|
||||||
|
done += 1;
|
||||||
|
report(file.name);
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
done += 1;
|
release?.();
|
||||||
onProgress?.({ done, total, current: file.name });
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -269,6 +365,6 @@ export async function importFiles(
|
|||||||
collected.sort((a, b) => a.index - b.index);
|
collected.sort((a, b) => a.index - b.index);
|
||||||
result.photos = collected.map((c) => c.photo);
|
result.photos = collected.map((c) => c.photo);
|
||||||
result.cancelled = Boolean(signal?.aborted);
|
result.cancelled = Boolean(signal?.aborted);
|
||||||
onProgress?.({ done: total, total, current: '' });
|
onProgress?.({ done: total, total, current: '', waiting: 0 });
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import {
|
||||||
|
addKeywordPath,
|
||||||
|
collectKeywordPaths,
|
||||||
|
keywordTree,
|
||||||
|
normalizeKeywordPath,
|
||||||
|
pathAncestors,
|
||||||
|
pathLeaf,
|
||||||
|
pathsUnder,
|
||||||
|
removeKeywordPath,
|
||||||
|
} from './keywords';
|
||||||
|
|
||||||
|
const empty = { keywords: [] as string[], keywordPaths: [] as string[] };
|
||||||
|
|
||||||
|
describe('keyword paths', () => {
|
||||||
|
it('normalises every separator to the Lightroom form', () => {
|
||||||
|
expect(normalizeKeywordPath('Nature>Birds>Robin')).toBe('Nature > Birds > Robin');
|
||||||
|
expect(normalizeKeywordPath('Nature/Birds / Robin ')).toBe('Nature > Birds > Robin');
|
||||||
|
expect(normalizeKeywordPath('Nature | Birds')).toBe('Nature > Birds');
|
||||||
|
expect(normalizeKeywordPath(' ')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reads the leaf and the ancestor chain', () => {
|
||||||
|
expect(pathLeaf('Nature > Birds > Robin')).toBe('Robin');
|
||||||
|
expect(pathAncestors('Nature > Birds > Robin')).toEqual([
|
||||||
|
'Nature',
|
||||||
|
'Nature > Birds',
|
||||||
|
'Nature > Birds > Robin',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('records ancestors and puts the leaf in the flat list', () => {
|
||||||
|
const next = addKeywordPath(empty, 'Nature > Birds > Robin');
|
||||||
|
expect(next.keywordPaths).toEqual([
|
||||||
|
'Nature',
|
||||||
|
'Nature > Birds',
|
||||||
|
'Nature > Birds > Robin',
|
||||||
|
]);
|
||||||
|
expect(next.keywords).toEqual(['Robin']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps a plain word flat', () => {
|
||||||
|
const next = addKeywordPath(empty, 'Robin', false);
|
||||||
|
expect(next.keywords).toEqual(['Robin']);
|
||||||
|
expect(next.keywordPaths).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not duplicate on case alone', () => {
|
||||||
|
const first = addKeywordPath(empty, 'Nature > Birds');
|
||||||
|
const second = addKeywordPath(first, 'nature > birds');
|
||||||
|
expect(second.keywordPaths).toEqual(['Nature', 'Nature > Birds']);
|
||||||
|
expect(second.keywords).toEqual(['Birds']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('removes a subtree and the leaves it stranded', () => {
|
||||||
|
const full = addKeywordPath(addKeywordPath(empty, 'Nature > Birds > Robin'), 'Nature > Birds > Wren');
|
||||||
|
const next = removeKeywordPath(full, 'Nature > Birds');
|
||||||
|
expect(next.keywordPaths).toEqual(['Nature']);
|
||||||
|
// Robin and Wren came only from the removed branch, Birds was the node.
|
||||||
|
expect(next.keywords).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps a leaf that another path still uses', () => {
|
||||||
|
const both = addKeywordPath(addKeywordPath(empty, 'Nature > Birds > Robin'), 'Garden > Robin');
|
||||||
|
const next = removeKeywordPath(both, 'Nature > Birds');
|
||||||
|
expect(next.keywords).toEqual(['Robin']);
|
||||||
|
expect(next.keywordPaths).toEqual(['Nature', 'Garden', 'Garden > Robin']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('collects suggestions once, sorted', () => {
|
||||||
|
const rows = [
|
||||||
|
{ keywordPaths: ['Nature > Birds', 'Nature'] },
|
||||||
|
{ keywordPaths: ['nature', 'Places > Coast'] },
|
||||||
|
{},
|
||||||
|
];
|
||||||
|
expect(collectKeywordPaths(rows)).toEqual(['Nature', 'Nature > Birds', 'Places > Coast']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds a tree with parents before children', () => {
|
||||||
|
const tree = keywordTree(['Nature > Birds > Robin', 'Nature > Plants', 'Places']);
|
||||||
|
expect(tree.map((node) => node.name)).toEqual(['Nature', 'Places']);
|
||||||
|
const nature = tree[0];
|
||||||
|
expect(nature.path).toBe('Nature');
|
||||||
|
expect(nature.children.map((node) => node.name)).toEqual(['Birds', 'Plants']);
|
||||||
|
expect(nature.children[0].children.map((node) => node.name)).toEqual(['Robin']);
|
||||||
|
expect(nature.children[0].children[0].path).toBe('Nature > Birds > Robin');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('expands a node to everything under it', () => {
|
||||||
|
const paths = ['Nature', 'Nature > Birds', 'Nature > Birds > Robin', 'Places > Coast'];
|
||||||
|
expect(pathsUnder(paths, 'Nature > Birds')).toEqual([
|
||||||
|
'Nature > Birds',
|
||||||
|
'Nature > Birds > Robin',
|
||||||
|
]);
|
||||||
|
expect(pathsUnder(paths, 'Places')).toEqual(['Places > Coast']);
|
||||||
|
// A prefix that is not a path boundary must not match.
|
||||||
|
expect(pathsUnder(paths, 'Nat')).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
/**
|
||||||
|
* Hierarchical keywords, stored so other software can still read them.
|
||||||
|
*
|
||||||
|
* A flat keyword list is portable but useless past a few hundred terms; a tree
|
||||||
|
* is useful but has no agreed storage format. Lightroom's answer is to write
|
||||||
|
* both: `dc:subject` carries the leaf terms, `lr:hierarchicalSubject` carries
|
||||||
|
* the full paths. This module keeps the same pair in the catalog:
|
||||||
|
*
|
||||||
|
* keywords ['Robin'] <- what search and filters use
|
||||||
|
* keywordPaths ['Nature > Birds > Robin'] <- where it sits
|
||||||
|
*
|
||||||
|
* Ancestors are included in `keywordPaths` the way Lightroom does, so a path is
|
||||||
|
* never a dangling leaf and importing a sidecar cannot invent a parent.
|
||||||
|
*
|
||||||
|
* The separator is `>` with spaces because that is the convention every DAM
|
||||||
|
* reads and writes; a user typing `Nature>Birds` gets normalised.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const KEYWORD_SEPARATOR = ' > ';
|
||||||
|
const MAX_DEPTH = 6;
|
||||||
|
const MAX_SEGMENT = 48;
|
||||||
|
|
||||||
|
export interface KeywordPaths {
|
||||||
|
keywords: string[];
|
||||||
|
keywordPaths: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Split a typed path into clean segments. Accepts `>`, `/` and `|`. */
|
||||||
|
export function pathSegments(input: string): string[] {
|
||||||
|
return input
|
||||||
|
.split(/\s*(?:>|\/|\|)\s*/)
|
||||||
|
.map((part) => part.trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
.slice(0, MAX_DEPTH)
|
||||||
|
.map((part) => part.slice(0, MAX_SEGMENT));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Canonical `A > B > C` form for a typed or imported path. */
|
||||||
|
export function normalizeKeywordPath(input: string): string {
|
||||||
|
return pathSegments(input).join(KEYWORD_SEPARATOR);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The leaf term of a path, which is what `keywords` stores. */
|
||||||
|
export function pathLeaf(path: string): string {
|
||||||
|
const segments = pathSegments(path);
|
||||||
|
return segments[segments.length - 1] ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `A > B > C` → `['A', 'A > B', 'A > B > C']`. */
|
||||||
|
export function pathAncestors(path: string): string[] {
|
||||||
|
const segments = pathSegments(path);
|
||||||
|
return segments.map((_, index) => segments.slice(0, index + 1).join(KEYWORD_SEPARATOR));
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameKey(a: string, b: string) {
|
||||||
|
return a.toLowerCase() === b.toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
function addUnique(list: string[], value: string) {
|
||||||
|
if (!value) return;
|
||||||
|
if (list.some((item) => sameKey(item, value))) return;
|
||||||
|
list.push(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a typed path (or a plain keyword) to a photo's pair of lists.
|
||||||
|
*
|
||||||
|
* A plain word stays flat; anything with a separator also records its
|
||||||
|
* ancestors. The leaf always lands in `keywords`, so a photo tagged
|
||||||
|
* `Nature > Birds > Robin` still matches a search for "Robin".
|
||||||
|
*/
|
||||||
|
export function addKeywordPath(
|
||||||
|
current: KeywordPaths,
|
||||||
|
input: string,
|
||||||
|
asPath = input.includes('>') || input.includes('/') || input.includes('|'),
|
||||||
|
): KeywordPaths {
|
||||||
|
const keywords = [...current.keywords];
|
||||||
|
const keywordPaths = [...current.keywordPaths];
|
||||||
|
const normalized = normalizeKeywordPath(input);
|
||||||
|
if (!normalized) return { keywords, keywordPaths };
|
||||||
|
|
||||||
|
addUnique(keywords, pathLeaf(normalized));
|
||||||
|
if (asPath) {
|
||||||
|
for (const ancestor of pathAncestors(normalized)) addUnique(keywordPaths, ancestor);
|
||||||
|
}
|
||||||
|
return { keywords, keywordPaths };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a path and everything under it, then drop leaves that nothing refers
|
||||||
|
* to any more. Removing `Birds` must not leave `Robin` behind as a keyword with
|
||||||
|
* no tree above it, which is how hierarchies rot.
|
||||||
|
*/
|
||||||
|
export function removeKeywordPath(current: KeywordPaths, path: string): KeywordPaths {
|
||||||
|
const target = normalizeKeywordPath(path);
|
||||||
|
if (!target) return current;
|
||||||
|
|
||||||
|
const removed = current.keywordPaths.filter(
|
||||||
|
(entry) => entry === target || entry.startsWith(`${target}${KEYWORD_SEPARATOR}`),
|
||||||
|
);
|
||||||
|
const keywordPaths = current.keywordPaths.filter((entry) => !removed.includes(entry));
|
||||||
|
|
||||||
|
// Every leaf the removal takes with it: the node's own and its descendants'.
|
||||||
|
const goneLeaves = new Set(removed.map((entry) => pathLeaf(entry).toLowerCase()));
|
||||||
|
goneLeaves.add(pathLeaf(target).toLowerCase());
|
||||||
|
const stillUsed = new Set(keywordPaths.map((entry) => pathLeaf(entry).toLowerCase()));
|
||||||
|
const keywords = current.keywords.filter(
|
||||||
|
(word) => stillUsed.has(word.toLowerCase()) || !goneLeaves.has(word.toLowerCase()),
|
||||||
|
);
|
||||||
|
return { keywords, keywordPaths };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every path in a library, sorted, for suggestions. */
|
||||||
|
export function collectKeywordPaths(rows: { keywordPaths?: string[] }[]): string[] {
|
||||||
|
// Case-insensitive dedupe, first spelling wins: "nature" and "Nature" are
|
||||||
|
// one suggestion, not two entries that look like a bug.
|
||||||
|
const seen = new Map<string, string>();
|
||||||
|
for (const row of rows) {
|
||||||
|
for (const path of row.keywordPaths ?? []) {
|
||||||
|
const normalized = normalizeKeywordPath(path);
|
||||||
|
const key = normalized.toLowerCase();
|
||||||
|
if (normalized && !seen.has(key)) seen.set(key, normalized);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...seen.values()].sort((a, b) => a.localeCompare(b));
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface KeywordNode {
|
||||||
|
/** Segment name, e.g. "Birds". */
|
||||||
|
name: string;
|
||||||
|
/** Full path, e.g. "Nature > Birds". */
|
||||||
|
path: string;
|
||||||
|
children: KeywordNode[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function insert(nodes: KeywordNode[], segments: string[], prefix: string[] = []) {
|
||||||
|
const [head, ...rest] = segments;
|
||||||
|
if (!head) return;
|
||||||
|
// The path is this node's own, built from the prefix above it -- not the
|
||||||
|
// whole path being inserted, which would rename every parent to its deepest
|
||||||
|
// descendant.
|
||||||
|
const selfPath = [...prefix, head];
|
||||||
|
let node = nodes.find((entry) => entry.name.toLowerCase() === head.toLowerCase());
|
||||||
|
if (!node) {
|
||||||
|
node = { name: head, path: selfPath.join(KEYWORD_SEPARATOR), children: [] };
|
||||||
|
nodes.push(node);
|
||||||
|
}
|
||||||
|
if (rest.length > 0) insert(node.children, rest, selfPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Paths → a tree for rendering. Sorted, with parents before children. */
|
||||||
|
export function keywordTree(paths: string[]): KeywordNode[] {
|
||||||
|
const roots: KeywordNode[] = [];
|
||||||
|
for (const path of paths) {
|
||||||
|
const segments = pathSegments(path);
|
||||||
|
if (segments.length === 0) continue;
|
||||||
|
if (segments.length === 1) {
|
||||||
|
// A flat keyword appears as its own root, with no children.
|
||||||
|
if (!roots.some((node) => node.name.toLowerCase() === segments[0].toLowerCase())) {
|
||||||
|
roots.push({ name: segments[0], path: segments[0], children: [] });
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
insert(roots, segments);
|
||||||
|
}
|
||||||
|
const sort = (nodes: KeywordNode[]) => {
|
||||||
|
nodes.sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
for (const node of nodes) sort(node.children);
|
||||||
|
};
|
||||||
|
sort(roots);
|
||||||
|
return roots;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every path at or under `root`, so tagging a parent tags its children. */
|
||||||
|
export function pathsUnder(paths: string[], root: string): string[] {
|
||||||
|
const target = normalizeKeywordPath(root);
|
||||||
|
if (!target) return [];
|
||||||
|
return paths.filter(
|
||||||
|
(path) => path === target || path.startsWith(`${target}${KEYWORD_SEPARATOR}`),
|
||||||
|
);
|
||||||
|
}
|
||||||
+77
-2
@@ -1,6 +1,12 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { applyFilmVariant, FILM_PRESETS, PRESETS, PRESET_CATEGORIES } from './presets';
|
import {
|
||||||
import { normalizeEdits } from './edits';
|
applyFilmVariant,
|
||||||
|
applyPresetEdits,
|
||||||
|
FILM_PRESETS,
|
||||||
|
PRESETS,
|
||||||
|
PRESET_CATEGORIES,
|
||||||
|
} from './presets';
|
||||||
|
import { defaultEdits, normalizeEdits } from './edits';
|
||||||
|
|
||||||
describe('preset library', () => {
|
describe('preset library', () => {
|
||||||
it('ships an extensive, uniquely identified catalogue', () => {
|
it('ships an extensive, uniquely identified catalogue', () => {
|
||||||
@@ -44,6 +50,21 @@ describe('preset library', () => {
|
|||||||
expect(redscale.some((preset) => preset.film?.process === 'E-6')).toBe(true);
|
expect(redscale.some((preset) => preset.film?.process === 'E-6')).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('keeps a user preset a full recipe rather than a cast', () => {
|
||||||
|
const base = { ...defaultEdits(), temp: -24, tint: 9 };
|
||||||
|
const custom = {
|
||||||
|
id: 'my-look',
|
||||||
|
name: 'My look',
|
||||||
|
group: 'User presets',
|
||||||
|
custom: true,
|
||||||
|
edits: { temp: 30, contrast: 12 },
|
||||||
|
};
|
||||||
|
const next = applyPresetEdits(base, custom);
|
||||||
|
expect(next.temp).toBe(30);
|
||||||
|
expect(next.presetLook).toEqual({ temp: 0, tint: 0 });
|
||||||
|
expect(next.contrast).toBe(12);
|
||||||
|
});
|
||||||
|
|
||||||
it('derives push/pull variants for film stocks only', () => {
|
it('derives push/pull variants for film stocks only', () => {
|
||||||
const stock = FILM_PRESETS[0];
|
const stock = FILM_PRESETS[0];
|
||||||
expect(applyFilmVariant(stock, 'push').id).toBe(`${stock.id}::push`);
|
expect(applyFilmVariant(stock, 'push').id).toBe(`${stock.id}::push`);
|
||||||
@@ -52,3 +73,57 @@ describe('preset library', () => {
|
|||||||
expect(applyFilmVariant(look!, 'push')).toBe(look);
|
expect(applyFilmVariant(look!, 'push')).toBe(look);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('looks over the photo’s own grade', () => {
|
||||||
|
const graded = () => ({ ...defaultEdits(), temp: -24, tint: 9 });
|
||||||
|
|
||||||
|
it('keeps the white balance already set and layers the look’s cast on it', () => {
|
||||||
|
const stock = FILM_PRESETS.find((preset) => (preset.edits.temp ?? 0) !== 0)!;
|
||||||
|
const next = applyPresetEdits(graded(), stock);
|
||||||
|
expect(next.temp).toBe(-24);
|
||||||
|
expect(next.tint).toBe(9);
|
||||||
|
expect(next.presetLook).toEqual({
|
||||||
|
temp: stock.edits.temp ?? 0,
|
||||||
|
tint: stock.edits.tint ?? 0,
|
||||||
|
});
|
||||||
|
// The look still sets its own tone and colour.
|
||||||
|
expect(next.contrast).toBe(stock.edits.contrast);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('replaces the previous look’s cast instead of stacking it', () => {
|
||||||
|
const warm = FILM_PRESETS.find((preset) => (preset.edits.temp ?? 0) > 10)!;
|
||||||
|
const cool = FILM_PRESETS.find((preset) => (preset.edits.temp ?? 0) < -10)!;
|
||||||
|
const once = applyPresetEdits(graded(), warm);
|
||||||
|
const twice = applyPresetEdits(once, cool);
|
||||||
|
expect(twice.temp).toBe(-24);
|
||||||
|
expect(twice.tint).toBe(9);
|
||||||
|
expect(twice.presetLook).toEqual({ temp: cool.edits.temp ?? 0, tint: cool.edits.tint ?? 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves the white balance alone for a preset with no cast of its own', () => {
|
||||||
|
const plain = PRESETS.find(
|
||||||
|
(preset) =>
|
||||||
|
preset.id !== 'original' &&
|
||||||
|
!preset.film &&
|
||||||
|
preset.edits.temp === undefined &&
|
||||||
|
preset.edits.tint === undefined,
|
||||||
|
)!;
|
||||||
|
const next = applyPresetEdits(graded(), plain);
|
||||||
|
expect(next.temp).toBe(-24);
|
||||||
|
expect(next.tint).toBe(9);
|
||||||
|
expect(next.presetLook).toEqual({ temp: 0, tint: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears the grade and the cast with the original', () => {
|
||||||
|
const applied = applyPresetEdits(graded(), FILM_PRESETS[0]);
|
||||||
|
const original = applyPresetEdits(applied, {
|
||||||
|
id: 'original',
|
||||||
|
name: 'Original',
|
||||||
|
group: 'Essentials',
|
||||||
|
edits: {},
|
||||||
|
});
|
||||||
|
expect(original.temp).toBe(0);
|
||||||
|
expect(original.tint).toBe(0);
|
||||||
|
expect(original.presetLook).toEqual({ temp: 0, tint: 0 });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { BwFilter, Edits, Preset } from '../types';
|
import type { BwFilter, Edits, Preset } from '../types';
|
||||||
|
import { defaultEdits, normalizeEdits } from './edits';
|
||||||
|
|
||||||
const identity = () => [
|
const identity = () => [
|
||||||
{ x: 0, y: 0 },
|
{ x: 0, y: 0 },
|
||||||
@@ -2925,6 +2926,44 @@ export const PRESETS: Preset[] = ([
|
|||||||
: preset;
|
: preset;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applies a look over the grade the photo already has.
|
||||||
|
*
|
||||||
|
* White balance is the base the look is graded against: the look's own Temp and
|
||||||
|
* Tint become a cast in `presetLook` on top of the correction already made,
|
||||||
|
* instead of overwriting it. Storing the cast apart also means switching looks
|
||||||
|
* replaces it rather than stacking one stock's warmth on the last one's, and
|
||||||
|
* the preview tiles can show exactly what the click will produce. A user preset
|
||||||
|
* is a recipe copied from a photo, so it still replaces the whole grade, and
|
||||||
|
* "original" clears it.
|
||||||
|
*/
|
||||||
|
export function applyPresetEdits(base: Edits, preset: Preset): Edits {
|
||||||
|
if (preset.id === 'original') {
|
||||||
|
return { ...defaultEdits(), crop: base.crop, cameraProfile: base.cameraProfile };
|
||||||
|
}
|
||||||
|
const { temp = 0, tint = 0, ...look } = preset.edits;
|
||||||
|
const next: Edits = {
|
||||||
|
...base,
|
||||||
|
...look,
|
||||||
|
crop: base.crop,
|
||||||
|
// The camera profile belongs to the body that produced the raw.
|
||||||
|
cameraProfile: base.cameraProfile,
|
||||||
|
// A strong film response must not leak into the next look.
|
||||||
|
redscale: look.redscale ?? 0,
|
||||||
|
};
|
||||||
|
if (preset.custom) {
|
||||||
|
// A recipe keeps the white balance it was saved with.
|
||||||
|
next.temp = temp;
|
||||||
|
next.tint = tint;
|
||||||
|
} else {
|
||||||
|
next.temp = base.temp;
|
||||||
|
next.tint = base.tint;
|
||||||
|
next.kelvin = base.kelvin;
|
||||||
|
next.presetLook = { temp, tint };
|
||||||
|
}
|
||||||
|
return normalizeEdits(next);
|
||||||
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------- film variants */
|
/* ------------------------------------------------------------- film variants */
|
||||||
|
|
||||||
export type FilmVariant = 'base' | 'push' | 'pull' | 'warm' | 'cool';
|
export type FilmVariant = 'base' | 'push' | 'pull' | 'warm' | 'cool';
|
||||||
|
|||||||
@@ -1,5 +1,48 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { kelvinGains, wbGainFor, WB_REFERENCE_KELVIN } from './whiteBalance';
|
import {
|
||||||
|
estimateKelvin,
|
||||||
|
expressWhiteBalance,
|
||||||
|
kelvinGains,
|
||||||
|
wbGainFor,
|
||||||
|
wbGainWithLook,
|
||||||
|
WB_REFERENCE_KELVIN,
|
||||||
|
} from './whiteBalance';
|
||||||
|
|
||||||
|
describe('expressWhiteBalance', () => {
|
||||||
|
it('recovers the sliders that produced a correction', () => {
|
||||||
|
for (const [temp, tint] of [
|
||||||
|
[30, -12],
|
||||||
|
[-55, 40],
|
||||||
|
[0, 0],
|
||||||
|
[80, 60],
|
||||||
|
]) {
|
||||||
|
const back = expressWhiteBalance(wbGainFor(temp, tint, null));
|
||||||
|
expect(back.temp).toBeCloseTo(temp, 0);
|
||||||
|
expect(back.tint).toBeCloseTo(tint, 0);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reads a look cast as the balance it leaves behind', () => {
|
||||||
|
const look = { temp: 35, tint: -8 };
|
||||||
|
const gain = wbGainWithLook(-20, 10, null, look);
|
||||||
|
const back = expressWhiteBalance(gain);
|
||||||
|
// The recovered pair reproduces the same gain the look left on the photo, to
|
||||||
|
// within what whole-number sliders can express.
|
||||||
|
const again = wbGainFor(back.temp, back.tint, null);
|
||||||
|
expect(again[0]).toBeCloseTo(gain[0], 2);
|
||||||
|
expect(again[1]).toBeCloseTo(gain[1], 2);
|
||||||
|
expect(again[2]).toBeCloseTo(gain[2], 2);
|
||||||
|
// Warm cast over a cool correction lands near the sum of the two.
|
||||||
|
expect(back.temp).toBeGreaterThan(11);
|
||||||
|
expect(back.temp).toBeLessThan(19);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('estimates the Kelvin of an absolute balance', () => {
|
||||||
|
expect(estimateKelvin(kelvinGains(3200))).toBeGreaterThan(3100);
|
||||||
|
expect(estimateKelvin(kelvinGains(3200))).toBeLessThan(3300);
|
||||||
|
expect(estimateKelvin(kelvinGains(WB_REFERENCE_KELVIN))).toBeCloseTo(WB_REFERENCE_KELVIN, -2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('absolute white balance', () => {
|
describe('absolute white balance', () => {
|
||||||
it('is neutral at the daylight reference', () => {
|
it('is neutral at the daylight reference', () => {
|
||||||
@@ -32,4 +75,26 @@ describe('absolute white balance', () => {
|
|||||||
expect(luma).toBeCloseTo(1, 4);
|
expect(luma).toBeCloseTo(1, 4);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('grades a look’s cast over the correction already made', () => {
|
||||||
|
const corrected = wbGainFor(-30, 0, null);
|
||||||
|
const withLook = wbGainWithLook(-30, 0, null, { temp: 20, tint: 0 });
|
||||||
|
// The look warms the corrected frame without throwing the correction away.
|
||||||
|
expect(withLook[0]).toBeGreaterThan(corrected[0]);
|
||||||
|
expect(withLook[2]).toBeLessThan(corrected[2]);
|
||||||
|
// Adding the two offsets is what the sliders would do by hand.
|
||||||
|
const summed = wbGainFor(-10, 0, null);
|
||||||
|
expect(withLook[0]).toBeCloseTo(summed[0], 2);
|
||||||
|
expect(withLook[2]).toBeCloseTo(summed[2], 2);
|
||||||
|
const luma = 0.2126 * withLook[0] + 0.7152 * withLook[1] + 0.0722 * withLook[2];
|
||||||
|
expect(luma).toBeCloseTo(1, 4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves the gain untouched when the look has no cast', () => {
|
||||||
|
expect(wbGainWithLook(0, 0, null, { temp: 0, tint: 0 })).toEqual(wbGainFor(0, 0, null));
|
||||||
|
// An absolute Kelvin correction is still the base for the cast.
|
||||||
|
const kelvin = wbGainFor(0, 0, 3200);
|
||||||
|
const warmed = wbGainWithLook(0, 0, 3200, { temp: 12, tint: 0 });
|
||||||
|
expect(warmed[0]).toBeGreaterThan(kelvin[0]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -108,6 +108,74 @@ export function wbGainFor(
|
|||||||
return gain.map((v) => v / norm) as [number, number, number];
|
return gain.map((v) => v / norm) as [number, number, number];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The white balance with an applied look's cast layered over it.
|
||||||
|
*
|
||||||
|
* The correction the photographer already made stays the base: a look's
|
||||||
|
* Temp/Tint is a cast added on top, not a replacement for it. Keeping the two
|
||||||
|
* separate (see `Edits['presetLook']`) also lets switching looks swap the cast
|
||||||
|
* instead of stacking one stock's warmth on the last one's. Normalised again
|
||||||
|
* so the look changes colour, not exposure.
|
||||||
|
*/
|
||||||
|
export function wbGainWithLook(
|
||||||
|
temp: number,
|
||||||
|
tint: number,
|
||||||
|
kelvin: number | null,
|
||||||
|
look: { temp: number; tint: number } | null | undefined,
|
||||||
|
): [number, number, number] {
|
||||||
|
const base = wbGainFor(temp, tint, kelvin);
|
||||||
|
if (!look || (!look.temp && !look.tint)) return base;
|
||||||
|
const cast = wbGainFor(look.temp, look.tint, null);
|
||||||
|
const gain: [number, number, number] = [base[0] * cast[0], base[1] * cast[1], base[2] * cast[2]];
|
||||||
|
const luma = 0.2126 * gain[0] + 0.7152 * gain[1] + 0.0722 * gain[2];
|
||||||
|
const norm = Math.max(0.05, luma);
|
||||||
|
return gain.map((v) => v / norm) as [number, number, number];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Temp/Tint pair that reproduces a gain vector.
|
||||||
|
*
|
||||||
|
* A look layers its cast over the correction, so the two sliders no longer show
|
||||||
|
* what the photo is graded at. Inverting the gains (ratios only, so the shared
|
||||||
|
* luma normalisation drops out) gives the pair that would: `r/b` is fixed by
|
||||||
|
* temperature alone, then green carries the tint.
|
||||||
|
*/
|
||||||
|
export function expressWhiteBalance(
|
||||||
|
gain: readonly number[],
|
||||||
|
): { temp: number; tint: number } {
|
||||||
|
const [r, g, b] = gain;
|
||||||
|
if (![r, g, b].every((v) => Number.isFinite(v) && v > 0)) return { temp: 0, tint: 0 };
|
||||||
|
// r/b = (1 + 0.3t) / (1 − 0.26t)
|
||||||
|
const t = (r - b) / (T_R * b + T_B * r);
|
||||||
|
// g/r = (1 − 0.16i) / ((1 + 0.3t)(1 + 0.06i))
|
||||||
|
const d = 1 + T_R * t;
|
||||||
|
const a = g / r;
|
||||||
|
const i = (1 - a * d) / (TINT_CROSS * a * d + T_TINT);
|
||||||
|
return {
|
||||||
|
temp: Math.round(clampRange(t * 100, -100, 100)),
|
||||||
|
tint: Math.round(clampRange(i * 100, -100, 100)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Kelvin setting whose black-body balance best matches a gain vector's red
|
||||||
|
* to blue ratio. Used to report a look's cast on the absolute-Kelvin control.
|
||||||
|
*/
|
||||||
|
export function estimateKelvin(gain: readonly number[]): number {
|
||||||
|
const target = Math.log(Math.max(1e-4, gain[0]) / Math.max(1e-4, gain[2]));
|
||||||
|
let best = WB_REFERENCE_KELVIN;
|
||||||
|
let bestErr = Infinity;
|
||||||
|
for (let k = 1500; k <= 12000; k += 25) {
|
||||||
|
const [r, , b] = kelvinGains(k);
|
||||||
|
const err = Math.abs(Math.log(r / b) - target);
|
||||||
|
if (err < bestErr) {
|
||||||
|
bestErr = err;
|
||||||
|
best = k;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Temperature and tint that make a sampled source colour neutral.
|
* Temperature and tint that make a sampled source colour neutral.
|
||||||
* `sample` is the untouched (sRGB-encoded) source pixel, 0–1 per channel.
|
* `sample` is the untouched (sRGB-encoded) source pixel, 0–1 per channel.
|
||||||
|
|||||||
+76
-1
@@ -1,6 +1,6 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { defaultEdits, defaultLocalLayer, normalizeEdits } from './edits';
|
import { defaultEdits, defaultLocalLayer, normalizeEdits } from './edits';
|
||||||
import { editsToXmp, xmpFileName, xmpToEdits } from './xmp';
|
import { editsToXmp, xmpFileName, xmpToEdits, xmpToMetadata } from './xmp';
|
||||||
|
|
||||||
describe('xmp sidecars', () => {
|
describe('xmp sidecars', () => {
|
||||||
it('round-trips every develop field exactly', () => {
|
it('round-trips every develop field exactly', () => {
|
||||||
@@ -55,3 +55,78 @@ describe('xmp sidecars', () => {
|
|||||||
expect(xmpFileName('no-extension')).toBe('no-extension.xmp');
|
expect(xmpFileName('no-extension')).toBe('no-extension.xmp');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('xmp metadata', () => {
|
||||||
|
const photo = {
|
||||||
|
name: 'DSC0123.ARW',
|
||||||
|
meta: {},
|
||||||
|
rating: 4,
|
||||||
|
color: 'green' as const,
|
||||||
|
keywords: ['Birds', 'Robin'],
|
||||||
|
keywordPaths: ['Nature', 'Nature > Birds', 'Nature > Birds > Robin'],
|
||||||
|
iptc: {
|
||||||
|
headline: 'Dawn chorus',
|
||||||
|
credit: 'B. Hursey',
|
||||||
|
source: 'Field notes',
|
||||||
|
city: 'Bristol',
|
||||||
|
state: 'Somerset',
|
||||||
|
country: 'UK',
|
||||||
|
location: 'Ashton Court',
|
||||||
|
},
|
||||||
|
title: 'Robin at dawn',
|
||||||
|
caption: 'First light, heavy frost',
|
||||||
|
creator: 'Brian Hursey',
|
||||||
|
copyright: '© 2026 Brian Hursey',
|
||||||
|
};
|
||||||
|
|
||||||
|
it('writes rating, label, keywords, hierarchy and IPTC, and reads them back', () => {
|
||||||
|
const xml = editsToXmp(defaultEdits(), photo);
|
||||||
|
expect(xml).toContain('xmp:Rating="4"');
|
||||||
|
expect(xml).toContain('xmp:Label="Green"');
|
||||||
|
expect(xml).toContain('<lr:hierarchicalSubject>');
|
||||||
|
expect(xml).toContain('photoshop:City="Bristol"');
|
||||||
|
expect(xml).toContain('Iptc4xmpCore:Location="Ashton Court"');
|
||||||
|
|
||||||
|
const meta = xmpToMetadata(xml);
|
||||||
|
expect(meta.rating).toBe(4);
|
||||||
|
expect(meta.label).toBe('green');
|
||||||
|
expect(meta.keywords).toEqual(['Birds', 'Robin']);
|
||||||
|
expect(meta.keywordPaths).toEqual([
|
||||||
|
'Nature',
|
||||||
|
'Nature > Birds',
|
||||||
|
'Nature > Birds > Robin',
|
||||||
|
]);
|
||||||
|
expect(meta.iptc).toEqual(photo.iptc);
|
||||||
|
expect(meta.title).toBe('Robin at dawn');
|
||||||
|
expect(meta.caption).toBe('First light, heavy frost');
|
||||||
|
expect(meta.creator).toBe('Brian Hursey');
|
||||||
|
expect(meta.copyright).toBe('© 2026 Brian Hursey');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reads a sidecar 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:xmp="http://ns.adobe.com/xap/1.0/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:lr="http://ns.adobe.com/lightroom/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmp:Rating="2" xmp:Label="Red" photoshop:Headline="Press day" photoshop:Country="Ireland"><dc:subject><rdf:Bag><rdf:li>Portrait</rdf:li><rdf:li>Maya</rdf:li></rdf:Bag></dc:subject><lr:hierarchicalSubject><rdf:Bag><rdf:li>People > Portrait</rdf:li></rdf:Bag></lr:hierarchicalSubject></rdf:Description></rdf:RDF></x:xmpmeta>`;
|
||||||
|
const meta = xmpToMetadata(xml);
|
||||||
|
expect(meta.rating).toBe(2);
|
||||||
|
expect(meta.label).toBe('red');
|
||||||
|
expect(meta.keywords).toEqual(['Portrait', 'Maya']);
|
||||||
|
expect(meta.keywordPaths).toEqual(['People > Portrait']);
|
||||||
|
expect(meta.iptc.headline).toBe('Press day');
|
||||||
|
expect(meta.iptc.country).toBe('Ireland');
|
||||||
|
// Nothing the file does not carry is invented.
|
||||||
|
expect(meta.iptc.city).toBeUndefined();
|
||||||
|
expect(meta.caption).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stays quiet when the file has no metadata', () => {
|
||||||
|
const meta = xmpToMetadata(editsToXmp(defaultEdits()));
|
||||||
|
expect(meta.rating).toBeUndefined();
|
||||||
|
expect(meta.label).toBeUndefined();
|
||||||
|
expect(meta.keywords).toEqual([]);
|
||||||
|
expect(meta.keywordPaths).toEqual([]);
|
||||||
|
expect(meta.iptc).toEqual({});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a file that is not a sidecar', () => {
|
||||||
|
expect(() => xmpToMetadata('<html></html>')).toThrow(/not an XMP/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
+184
-6
@@ -1,6 +1,60 @@
|
|||||||
import type { Edits, PhotoRecord } from '../types';
|
import type { ColorLabel, Edits, IptcFields, PhotoRecord } from '../types';
|
||||||
import { normalizeEdits } from './edits';
|
import { normalizeEdits } from './edits';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Everything a sidecar carries besides the develop settings: rating, label,
|
||||||
|
* keywords (flat and hierarchical) and the IPTC core.
|
||||||
|
*
|
||||||
|
* `dc:subject` and `lr:hierarchicalSubject` are written as a pair, the way
|
||||||
|
* Lightroom does: the leaves in the first, the full paths in the second. A
|
||||||
|
* reader that only understands one of them still gets something usable, and a
|
||||||
|
* library round-tripped through another editor keeps its tree.
|
||||||
|
*/
|
||||||
|
export type XmpPhotoFields = Partial<
|
||||||
|
Pick<
|
||||||
|
PhotoRecord,
|
||||||
|
| 'name'
|
||||||
|
| 'meta'
|
||||||
|
| 'rating'
|
||||||
|
| 'color'
|
||||||
|
| 'keywords'
|
||||||
|
| 'keywordPaths'
|
||||||
|
| 'iptc'
|
||||||
|
| 'title'
|
||||||
|
| 'caption'
|
||||||
|
| 'creator'
|
||||||
|
| 'copyright'
|
||||||
|
>
|
||||||
|
>;
|
||||||
|
|
||||||
|
/** Lightroom's label names, which are what other software reads. */
|
||||||
|
const LABEL_NAMES: Record<Exclude<ColorLabel, ''>, string> = {
|
||||||
|
red: 'Red',
|
||||||
|
yellow: 'Yellow',
|
||||||
|
green: 'Green',
|
||||||
|
blue: 'Blue',
|
||||||
|
purple: 'Purple',
|
||||||
|
};
|
||||||
|
|
||||||
|
const LABEL_VALUES: Record<string, Exclude<ColorLabel, ''>> = {
|
||||||
|
red: 'red',
|
||||||
|
yellow: 'yellow',
|
||||||
|
green: 'green',
|
||||||
|
blue: 'blue',
|
||||||
|
purple: 'purple',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** IPTC field → the XMP property that carries it. */
|
||||||
|
const IPTC_ATTRS: [keyof IptcFields, string][] = [
|
||||||
|
['headline', 'photoshop:Headline'],
|
||||||
|
['credit', 'photoshop:Credit'],
|
||||||
|
['source', 'photoshop:Source'],
|
||||||
|
['city', 'photoshop:City'],
|
||||||
|
['state', 'photoshop:State'],
|
||||||
|
['country', 'photoshop:Country'],
|
||||||
|
['location', 'Iptc4xmpCore:Location'],
|
||||||
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Lightroom-compatible XMP sidecars.
|
* Lightroom-compatible XMP sidecars.
|
||||||
*
|
*
|
||||||
@@ -105,7 +159,70 @@ export function xmpFileName(name: string) {
|
|||||||
return `${name.replace(/\.[^.]+$/, '') || 'photo'}.xmp`;
|
return `${name.replace(/\.[^.]+$/, '') || 'photo'}.xmp`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function editsToXmp(edits: Edits, photo?: Pick<PhotoRecord, 'name' | 'meta'>): string {
|
/** Rating, colour label and IPTC, as XMP attributes on the Description. */
|
||||||
|
export function photoMetadataAttributes(photo?: XmpPhotoFields): string {
|
||||||
|
if (!photo) return '';
|
||||||
|
const attrs: string[] = [];
|
||||||
|
const rating = Math.round(photo.rating ?? 0);
|
||||||
|
if (rating > 0) attrs.push(`xmp:Rating="${Math.max(0, Math.min(5, rating))}"`);
|
||||||
|
const label = photo.color ? LABEL_NAMES[photo.color] : '';
|
||||||
|
if (label) attrs.push(`xmp:Label="${label}"`);
|
||||||
|
const iptc = photo.iptc ?? {};
|
||||||
|
for (const [field, property] of IPTC_ATTRS) {
|
||||||
|
const value = iptc[field];
|
||||||
|
if (typeof value === 'string' && value.trim()) {
|
||||||
|
attrs.push(`${property}="${escapeXml(value.trim())}"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return attrs.length ? ` ${attrs.join(' ')}` : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Title, caption, creator, rights, keywords and the hierarchy, as elements. */
|
||||||
|
export function photoMetadataElements(photo?: XmpPhotoFields): string {
|
||||||
|
const parts: string[] = [];
|
||||||
|
const title = photo?.title?.trim() || photo?.name?.trim() || 'Luminary edit';
|
||||||
|
parts.push(
|
||||||
|
`<dc:title><rdf:Alt><rdf:li xml:lang="x-default">${escapeXml(title)}</rdf:li></rdf:Alt></dc:title>`,
|
||||||
|
);
|
||||||
|
if (photo?.caption?.trim()) {
|
||||||
|
parts.push(
|
||||||
|
`<dc:description><rdf:Alt><rdf:li xml:lang="x-default">${escapeXml(
|
||||||
|
photo.caption.trim(),
|
||||||
|
)}</rdf:li></rdf:Alt></dc:description>`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (photo?.creator?.trim()) {
|
||||||
|
parts.push(
|
||||||
|
`<dc:creator><rdf:Seq><rdf:li>${escapeXml(photo.creator.trim())}</rdf:li></rdf:Seq></dc:creator>`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (photo?.copyright?.trim()) {
|
||||||
|
parts.push(
|
||||||
|
`<dc:rights><rdf:Alt><rdf:li xml:lang="x-default">${escapeXml(
|
||||||
|
photo.copyright.trim(),
|
||||||
|
)}</rdf:li></rdf:Alt></dc:rights>`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const keywords = (photo?.keywords ?? []).filter((word) => word && word.trim());
|
||||||
|
if (keywords.length) {
|
||||||
|
parts.push(
|
||||||
|
`<dc:subject><rdf:Bag>${keywords
|
||||||
|
.map((word) => `<rdf:li>${escapeXml(word)}</rdf:li>`)
|
||||||
|
.join('')}</rdf:Bag></dc:subject>`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const paths = (photo?.keywordPaths ?? []).filter((path) => path && path.trim());
|
||||||
|
if (paths.length) {
|
||||||
|
parts.push(
|
||||||
|
`<lr:hierarchicalSubject><rdf:Bag>${paths
|
||||||
|
.map((path) => `<rdf:li>${escapeXml(path)}</rdf:li>`)
|
||||||
|
.join('')}</rdf:Bag></lr:hierarchicalSubject>`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return parts.join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function editsToXmp(edits: Edits, photo?: XmpPhotoFields): string {
|
||||||
const normalized = normalizeEdits(edits);
|
const normalized = normalizeEdits(edits);
|
||||||
const attrs = CRS_FIELDS.map(
|
const attrs = CRS_FIELDS.map(
|
||||||
([name, read]) => `crs:${name}="${num(read(normalized))}"`,
|
([name, read]) => `crs:${name}="${num(read(normalized))}"`,
|
||||||
@@ -113,16 +230,15 @@ export function editsToXmp(edits: Edits, photo?: Pick<PhotoRecord, 'name' | 'met
|
|||||||
attrs.push(`crs:ConvertToGrayscale="${normalized.bw ? 'True' : 'False'}"`);
|
attrs.push(`crs:ConvertToGrayscale="${normalized.bw ? 'True' : 'False'}"`);
|
||||||
if (normalized.kelvin != null) attrs.push(`crs:Temperature="${Math.round(normalized.kelvin)}"`);
|
if (normalized.kelvin != null) attrs.push(`crs:Temperature="${Math.round(normalized.kelvin)}"`);
|
||||||
attrs.push(`lum:Settings="${escapeXml(base64Encode(JSON.stringify(normalized)))}"`);
|
attrs.push(`lum:Settings="${escapeXml(base64Encode(JSON.stringify(normalized)))}"`);
|
||||||
const label = photo ? escapeXml(photo.name) : 'Luminary edit';
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?>',
|
'<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?>',
|
||||||
'<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Luminary">',
|
'<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: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}"`,
|
` <rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmlns:lum="${LUM_NS}" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:Iptc4xmpCore="http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:lr="http://ns.adobe.com/lightroom/1.0/"`,
|
||||||
' crs:Version="15.0" crs:ProcessVersion="15.4" crs:HasSettings="True"',
|
' crs:Version="15.0" crs:ProcessVersion="15.4" crs:HasSettings="True"',
|
||||||
` ${attrs.join('\n ')}>`,
|
` ${attrs.join('\n ')}${photoMetadataAttributes(photo)}>`,
|
||||||
` <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>`,
|
` ${photoMetadataElements(photo)}`,
|
||||||
' </rdf:Description>',
|
' </rdf:Description>',
|
||||||
' </rdf:RDF>',
|
' </rdf:RDF>',
|
||||||
'</x:xmpmeta>',
|
'</x:xmpmeta>',
|
||||||
@@ -202,6 +318,68 @@ export function xmpToEdits(xml: string, base: Edits): XmpImport {
|
|||||||
return { edits: normalizeEdits(next), source: 'lightroom', applied };
|
return { edits: normalizeEdits(next), source: 'lightroom', applied };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface XmpMetadata {
|
||||||
|
rating?: number;
|
||||||
|
label?: Exclude<ColorLabel, ''>;
|
||||||
|
keywords: string[];
|
||||||
|
keywordPaths: string[];
|
||||||
|
iptc: IptcFields;
|
||||||
|
title?: string;
|
||||||
|
caption?: string;
|
||||||
|
creator?: string;
|
||||||
|
copyright?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `<dc:subject><rdf:Bag><rdf:li>…` → the items, unescaped. */
|
||||||
|
function bagItems(xml: string, tag: string): string[] {
|
||||||
|
const block = new RegExp(`<${tag}\\b[^>]*>([\\s\\S]*?)</${tag}>`).exec(xml);
|
||||||
|
if (!block) return [];
|
||||||
|
return [...block[1].matchAll(/<rdf:li\b[^>]*>([\s\S]*?)<\/rdf:li>/g)]
|
||||||
|
.map((match) => unescapeXml(match[1].trim()))
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read the metadata half of a sidecar: rating, label, keywords, hierarchy and
|
||||||
|
* IPTC. Separate from `xmpToEdits` because a photographer may want the
|
||||||
|
* cataloguing fields from a file whose grade they do not want to adopt.
|
||||||
|
*
|
||||||
|
* Returns the fields the file actually carries; the caller decides what to
|
||||||
|
* overwrite, so an empty sidecar cannot wipe a photo's existing metadata.
|
||||||
|
*/
|
||||||
|
export function xmpToMetadata(xml: string): XmpMetadata {
|
||||||
|
if (!/<x:xmpmeta|<rdf:RDF/i.test(xml)) {
|
||||||
|
throw new Error('That file is not an XMP sidecar');
|
||||||
|
}
|
||||||
|
const attrs = attributes(xml);
|
||||||
|
|
||||||
|
const ratingRaw = attrs.get('xmp:Rating');
|
||||||
|
const ratingValue = ratingRaw === undefined ? NaN : Number(ratingRaw);
|
||||||
|
const rating = Number.isFinite(ratingValue)
|
||||||
|
? Math.max(0, Math.min(5, Math.round(ratingValue)))
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const label = LABEL_VALUES[(attrs.get('xmp:Label') ?? '').toLowerCase()];
|
||||||
|
|
||||||
|
const iptc: IptcFields = {};
|
||||||
|
for (const [field, property] of IPTC_ATTRS) {
|
||||||
|
const value = attrs.get(property);
|
||||||
|
if (value) iptc[field] = value.slice(0, 256);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
rating,
|
||||||
|
label,
|
||||||
|
keywords: bagItems(xml, 'dc:subject'),
|
||||||
|
keywordPaths: bagItems(xml, 'lr:hierarchicalSubject'),
|
||||||
|
iptc,
|
||||||
|
title: bagItems(xml, 'dc:title')[0],
|
||||||
|
caption: bagItems(xml, 'dc:description')[0],
|
||||||
|
creator: bagItems(xml, 'dc:creator')[0],
|
||||||
|
copyright: bagItems(xml, 'dc:rights')[0],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/** Opens the OS picker and returns the sidecar text, or null when cancelled. */
|
/** Opens the OS picker and returns the sidecar text, or null when cancelled. */
|
||||||
export function readXmpFile(): Promise<string | null> {
|
export function readXmpFile(): Promise<string | null> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
|
|||||||
@@ -1650,6 +1650,27 @@ figcaption {
|
|||||||
margin-top: 2px;
|
margin-top: 2px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* The look's cast and the balance it leaves the photo at, under Temp/Tint. */
|
||||||
|
.wb-look {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 2px 10px;
|
||||||
|
margin: 1px 0 5px;
|
||||||
|
font-size: 10.5px;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wb-look b {
|
||||||
|
color: #d9d9e2;
|
||||||
|
font-weight: 600;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wb-look-final {
|
||||||
|
margin-left: auto;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
.row {
|
.row {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: 74px 1fr 44px;
|
grid-template-columns: 74px 1fr 44px;
|
||||||
|
|||||||
@@ -167,6 +167,13 @@ export interface Edits {
|
|||||||
* the demosaiced proxy is assumed to be balanced for.
|
* the demosaiced proxy is assumed to be balanced for.
|
||||||
*/
|
*/
|
||||||
kelvin: number | null;
|
kelvin: number | null;
|
||||||
|
/**
|
||||||
|
* White-balance cast of an applied look (film stock or preset), kept apart
|
||||||
|
* from `temp`/`tint`. A look grades on top of the correction already made,
|
||||||
|
* so an adjusted white balance stays the base it is applied against instead
|
||||||
|
* of being replaced by the look's own cast.
|
||||||
|
*/
|
||||||
|
presetLook: { temp: number; tint: number };
|
||||||
exposure: number;
|
exposure: number;
|
||||||
/** pulls clipped highlights back into range without shifting hue */
|
/** pulls clipped highlights back into range without shifting hue */
|
||||||
recovery: number;
|
recovery: number;
|
||||||
@@ -241,6 +248,21 @@ export interface Edits {
|
|||||||
crop: CropState;
|
crop: CropState;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** IPTC core fields, written to XMP so a catalog is readable elsewhere. */
|
||||||
|
export interface IptcFields {
|
||||||
|
/** Single-line summary, the "who/what" a picture desk reads first. */
|
||||||
|
headline?: string;
|
||||||
|
/** Who gets the credit for the image. */
|
||||||
|
credit?: string;
|
||||||
|
/** Agency or organisation that supplied it. */
|
||||||
|
source?: string;
|
||||||
|
city?: string;
|
||||||
|
state?: string;
|
||||||
|
country?: string;
|
||||||
|
/** Sublocation inside the city. */
|
||||||
|
location?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface PhotoMeta {
|
export interface PhotoMeta {
|
||||||
camera?: string;
|
camera?: string;
|
||||||
lens?: string;
|
lens?: string;
|
||||||
@@ -269,6 +291,8 @@ export interface MetadataPreset {
|
|||||||
creator?: string;
|
creator?: string;
|
||||||
copyright?: string;
|
copyright?: string;
|
||||||
keywords: string[];
|
keywords: string[];
|
||||||
|
keywordPaths?: string[];
|
||||||
|
iptc?: IptcFields;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SmartCollection {
|
export interface SmartCollection {
|
||||||
@@ -305,6 +329,13 @@ export interface PhotoRecord {
|
|||||||
flag: Flag;
|
flag: Flag;
|
||||||
color: ColorLabel;
|
color: ColorLabel;
|
||||||
keywords: string[];
|
keywords: string[];
|
||||||
|
/**
|
||||||
|
* Full hierarchical paths (`A > B > C`). The leaf of each is also in
|
||||||
|
* `keywords`, so search and filters do not need to know about the tree.
|
||||||
|
*/
|
||||||
|
keywordPaths?: string[];
|
||||||
|
/** IPTC core, edited in the Metadata panel and written to XMP. */
|
||||||
|
iptc?: IptcFields;
|
||||||
title?: string;
|
title?: string;
|
||||||
caption?: string;
|
caption?: string;
|
||||||
creator?: string;
|
creator?: string;
|
||||||
|
|||||||
@@ -95,6 +95,13 @@ VIAddVersionKey "LegalCopyright" "MIT licensed"
|
|||||||
!endif
|
!endif
|
||||||
!define MUI_FINISHPAGE_RUN "${APP_LAUNCH}"
|
!define MUI_FINISHPAGE_RUN "${APP_LAUNCH}"
|
||||||
!define MUI_FINISHPAGE_RUN_TEXT "Start ${APP_NAME}"
|
!define MUI_FINISHPAGE_RUN_TEXT "Start ${APP_NAME}"
|
||||||
|
; MUI starts the finish-page target with Exec, which hands the path straight to
|
||||||
|
; CreateProcess. That only works for a real executable: when the bundle ships
|
||||||
|
; the PowerShell launcher (no Go toolchain at build time) the target is
|
||||||
|
; Luminary.vbs, and CreateProcess cannot start a script, so the ticked "Start
|
||||||
|
; Luminary" box closed the installer and nothing opened. ExecShell goes through
|
||||||
|
; the shell, so the exe, the .vbs and the .cmd all start.
|
||||||
|
!define MUI_FINISHPAGE_RUN_FUNCTION "StartLuminaryOnFinish"
|
||||||
|
|
||||||
!insertmacro MUI_PAGE_WELCOME
|
!insertmacro MUI_PAGE_WELCOME
|
||||||
!if /FileExists "${SOURCE_DIR}/LICENSE"
|
!if /FileExists "${SOURCE_DIR}/LICENSE"
|
||||||
@@ -114,6 +121,10 @@ LangString DESC_Main ${LANG_ENGLISH} "The editor, film looks, bundled Node runti
|
|||||||
LangString DESC_Desktop ${LANG_ENGLISH} "Put a Luminary shortcut on the desktop."
|
LangString DESC_Desktop ${LANG_ENGLISH} "Put a Luminary shortcut on the desktop."
|
||||||
LangString DESC_Startup ${LANG_ENGLISH} "Start Luminary in the background when you sign in to Windows."
|
LangString DESC_Startup ${LANG_ENGLISH} "Start Luminary in the background when you sign in to Windows."
|
||||||
|
|
||||||
|
Function StartLuminaryOnFinish
|
||||||
|
ExecShell "open" "${APP_LAUNCH}"
|
||||||
|
FunctionEnd
|
||||||
|
|
||||||
Function .onInit
|
Function .onInit
|
||||||
; The launcher refuses these too, but the installer should say so before it
|
; The launcher refuses these too, but the installer should say so before it
|
||||||
; copies 250 MB onto an unsupported PC.
|
; copies 250 MB onto an unsupported PC.
|
||||||
|
|||||||
@@ -239,6 +239,25 @@ function Get-WindowsBuild {
|
|||||||
# node.exe ships with it (and -Repair re-downloads it), libvips needs only the
|
# node.exe ships with it (and -Repair re-downloads it), libvips needs only the
|
||||||
# Universal C Runtime that Windows 10/11 already has, and no admin rights are
|
# Universal C Runtime that Windows 10/11 already has, and no admin rights are
|
||||||
# involved. Verified against the PE imports of node.exe and libvips-42.dll.
|
# involved. Verified against the PE imports of node.exe and libvips-42.dll.
|
||||||
|
# The architecture of the machine, not of this process. Started from a 32-bit
|
||||||
|
# parent - the setup's finish page, or a SysWOW64 shell - a 64-bit PC still
|
||||||
|
# reports PROCESSOR_ARCHITECTURE=x86; the real value is in the WOW64 copy, and
|
||||||
|
# Is64BitOperatingSystem settles it.
|
||||||
|
function Get-MachineArch {
|
||||||
|
$arch = $env:PROCESSOR_ARCHITEW6432
|
||||||
|
if (-not $arch) { $arch = $env:PROCESSOR_ARCHITECTURE }
|
||||||
|
$is64 = $false
|
||||||
|
try { $is64 = [Environment]::Is64BitOperatingSystem } catch { }
|
||||||
|
if (-not $arch) { $arch = if ($is64) { 'AMD64' } else { 'x86' } }
|
||||||
|
if ($is64) {
|
||||||
|
if ($arch -eq 'x86') { $arch = 'AMD64' }
|
||||||
|
} elseif ($arch -eq 'AMD64' -or $arch -eq 'ARM64') {
|
||||||
|
# The OS says 32-bit; believe it rather than a stale variable.
|
||||||
|
$arch = 'x86'
|
||||||
|
}
|
||||||
|
return $arch
|
||||||
|
}
|
||||||
|
|
||||||
function Test-Platform {
|
function Test-Platform {
|
||||||
$problems = @()
|
$problems = @()
|
||||||
$notes = @()
|
$notes = @()
|
||||||
@@ -248,7 +267,7 @@ function Test-Platform {
|
|||||||
$problems += ("Luminary needs Windows 10 or 11. This PC reports build {0}." -f $build)
|
$problems += ("Luminary needs Windows 10 or 11. This PC reports build {0}." -f $build)
|
||||||
}
|
}
|
||||||
|
|
||||||
$arch = $env:PROCESSOR_ARCHITECTURE
|
$arch = Get-MachineArch
|
||||||
if ($arch -and $arch -ne 'AMD64' -and $arch -ne 'ARM64') {
|
if ($arch -and $arch -ne 'AMD64' -and $arch -ne 'ARM64') {
|
||||||
$problems += ("Luminary ships a 64-bit runtime; this PC reports '{0}'." -f $arch)
|
$problems += ("Luminary ships a 64-bit runtime; this PC reports '{0}'." -f $arch)
|
||||||
} elseif ($arch -eq 'ARM64') {
|
} elseif ($arch -eq 'ARM64') {
|
||||||
@@ -521,7 +540,7 @@ if ($Status) {
|
|||||||
Write-Host 'Luminary is not running.'
|
Write-Host 'Luminary is not running.'
|
||||||
}
|
}
|
||||||
$platform = Test-Platform
|
$platform = Test-Platform
|
||||||
Write-Host ("System: Windows build {0}, {1}" -f (Get-WindowsBuild), $env:PROCESSOR_ARCHITECTURE)
|
Write-Host ("System: Windows build {0}, {1}" -f (Get-WindowsBuild), (Get-MachineArch))
|
||||||
foreach ($note in $platform.notes) { Write-Host ("Note: {0}" -f $note) }
|
foreach ($note in $platform.notes) { Write-Host ("Note: {0}" -f $note) }
|
||||||
foreach ($problem in $platform.problems) { Write-Host ("Problem: {0}" -f $problem) }
|
foreach ($problem in $platform.problems) { Write-Host ("Problem: {0}" -f $problem) }
|
||||||
$node = Resolve-Node
|
$node = Resolve-Node
|
||||||
|
|||||||
@@ -1,2 +1,10 @@
|
|||||||
16d033a863345542a07e65bb3914f63d35432fe7b88c33cc65f9d7634428ab98 Luminary-0.5.4-win-x64.zip
|
b33e3d8b595aa3ff20b0898f3adea639e02afe9eb54c4fba5dd09ec07e041a0c Luminary-0.5.1-win-x64-setup.exe
|
||||||
|
22b8943d1ca3bed3ef115530831947e4e03f6a45317ec6b35c10e871fad22a9a Luminary-0.5.1-win-x64.zip
|
||||||
|
c95ae4d21dfd80cd6206fc3f276c1d1d6afa61f55d48e6646f65784b483ca590 Luminary-0.5.2-win-x64-setup.exe
|
||||||
|
e81cbe4001bef43f79a2200acecc5dafbcf6c3c04dc2f6db4685f1f0b3ba3cdc Luminary-0.5.2-win-x64.zip
|
||||||
|
3e5a120b6d7483e0bdc6fb9091cf02e4bbab49e57e4d39c433521fb6ddf44b5a Luminary-0.5.3.1-win-x64-setup.exe
|
||||||
|
f4cd3e4a40dc79d9fb9d0d3dc627f317d33955cc9d6c77c5ee5f8bcb843b9a58 Luminary-0.5.3.1-win-x64.zip
|
||||||
97cceb61bba34733013d21e1fe240f39da790843694e1390f6266aa128f1c456 Luminary-0.5.4-win-x64-setup.exe
|
97cceb61bba34733013d21e1fe240f39da790843694e1390f6266aa128f1c456 Luminary-0.5.4-win-x64-setup.exe
|
||||||
|
16d033a863345542a07e65bb3914f63d35432fe7b88c33cc65f9d7634428ab98 Luminary-0.5.4-win-x64.zip
|
||||||
|
44ba60f6bebf5a43e1f8bd2e9beba1b8636e59dc8d07ae9d43096d3b09992e53 Luminary-0.5.4.1-win-x64-setup.exe
|
||||||
|
2e2ebfcee53edfcb14a58a5535fd384dd99f6c7a386de7f9c59419e8fe6c7969 Luminary-0.5.4.1-win-x64.zip
|
||||||
|
|||||||
Reference in New Issue
Block a user