From 0c113e7a91df0b2aab7583aed5a8d1ac546e0c9e Mon Sep 17 00:00:00 2001 From: Brian Hursey Date: Sat, 28 Nov 2026 03:59:55 +0000 Subject: [PATCH] Land camera-native raw profiles, real ICC soft proofing and 16-bit proxies. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Camera profiles, proofing tables and the half-float sidecar all have to agree with the pixels the editor actually grades, so they land together with the preset filter menu that was unusable while thumbnails streamed in. 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- README.md | 147 +- server/color.mjs | 144 ++ server/config.mjs | 7 + server/db.mjs | 77 ++ server/imaging.mjs | 94 +- server/index.mjs | 350 ++++- server/raw.mjs | 112 +- server/storage.mjs | 25 + src/App.tsx | 363 ++++- src/components/CullAssistModal.tsx | 248 ++++ src/components/CurveEditor.tsx | 74 +- src/components/Develop.tsx | 184 ++- src/components/EditedImage.tsx | 10 +- src/components/EventSidebar.tsx | 39 +- src/components/ExportModal.tsx | 22 +- src/components/ImmichPanel.tsx | 4 +- src/components/LibraryGrid.tsx | 15 + src/components/Panels.tsx | 711 +++++++++- src/components/ProofingGallery.tsx | 72 +- src/components/RawReprocessModal.tsx | 103 ++ src/components/ShareModal.tsx | 158 ++- src/components/TetherPanel.tsx | 194 +++ src/gl/masks.ts | 17 +- src/gl/renderer.ts | 634 +++++++-- src/lib/api.ts | 98 ++ src/lib/auto.ts | 67 + src/lib/autoMask.test.ts | 92 ++ src/lib/autoMask.ts | 281 +++- src/lib/colorSpace.test.ts | 49 + src/lib/colorSpace.ts | 103 ++ src/lib/cull.test.ts | 53 + src/lib/cull.ts | 157 +++ src/lib/dcp.test.ts | 145 ++ src/lib/dcp.ts | 255 ++++ src/lib/editSections.ts | 5 +- src/lib/editThumbs.ts | 4 +- src/lib/edits.ts | 73 +- src/lib/export.ts | 58 +- src/lib/icc.ts | 102 +- src/lib/images.ts | 49 + src/lib/levels.test.ts | 31 + src/lib/presets.test.ts | 54 + src/lib/presets.ts | 1922 +++++++++++++++++++++++++- src/lib/preview16.test.ts | 191 +++ src/lib/preview16.ts | 210 +++ src/lib/softProof.test.ts | 340 +++++ src/lib/softProof.ts | 586 ++++++++ src/lib/whiteBalance.test.ts | 35 + src/lib/whiteBalance.ts | 84 ++ src/lib/xmp.test.ts | 61 + src/lib/xmp.ts | 237 ++++ src/styles.css | 505 ++++++- src/types.ts | 42 + 53 files changed, 9217 insertions(+), 476 deletions(-) create mode 100644 server/color.mjs create mode 100644 src/components/CullAssistModal.tsx create mode 100644 src/components/RawReprocessModal.tsx create mode 100644 src/components/TetherPanel.tsx create mode 100644 src/lib/autoMask.test.ts create mode 100644 src/lib/colorSpace.test.ts create mode 100644 src/lib/colorSpace.ts create mode 100644 src/lib/cull.test.ts create mode 100644 src/lib/cull.ts create mode 100644 src/lib/dcp.test.ts create mode 100644 src/lib/dcp.ts create mode 100644 src/lib/levels.test.ts create mode 100644 src/lib/presets.test.ts create mode 100644 src/lib/preview16.test.ts create mode 100644 src/lib/preview16.ts create mode 100644 src/lib/softProof.test.ts create mode 100644 src/lib/softProof.ts create mode 100644 src/lib/whiteBalance.test.ts create mode 100644 src/lib/xmp.test.ts create mode 100644 src/lib/xmp.ts diff --git a/README.md b/README.md index 04d9528..969a4da 100644 --- a/README.md +++ b/README.md @@ -62,16 +62,22 @@ changing the current filters. **Develop.** A WebGL2 multi-pass pipeline (`src/gl/renderer.ts`), per photo, non-destructive: -- white balance, exposure, contrast, highlights/shadows/whites/blacks -- texture, clarity, dehaze, vibrance, saturation, black & white mix -- RGB and per-channel tone curves -- 8-band HSL colour mixer, split toning / colour grading +- white balance as a relative Temp/Tint offset or an absolute Kelvin value with a + 5500 K daylight reference, exposure, contrast, and hue-preserving + highlights/shadows/whites/blacks +- per-channel highlight recovery, texture, clarity, per-pixel dehaze, vibrance, + saturation, black & white mix +- input levels (black point, white point, midtone gamma), RGB and per-channel tone + curves +- 8-band HSL colour mixer evaluated in OkLCh (hue and chroma changes keep their + perceived lightness), split toning / colour grading - sharpening, luminance noise reduction - vignette, grain - crop with nine aspect ratios, straighten, 90° rotation, flips -- local adjustments (up to four layers): brush, linear gradient and radial masks with - feather, invert, luminance/hue/saturation ranges, and per-layer exposure, contrast, - highlights, shadows, temperature, tint and saturation. Masks follow crops, zoom, +- local adjustments (up to eight layers): brush, linear gradient and radial masks + with feather, invert, luminance/hue/saturation ranges, and per-layer exposure, + contrast, highlights, shadows, whites, blacks, temperature, tint, saturation, + vibrance, hue, texture, clarity, dehaze and sharpening. Masks follow crops, zoom, healing and lens correction; Copy mask / Paste mask move one layer between photos - full Lensfun profiles: distortion, transverse chromatic aberration and vignetting from the official database, with manual lens search, "Match EXIF lens" @@ -87,8 +93,8 @@ non-destructive: - histogram, built-in and saved presets, history with undo/redo, selective copy/paste and batch sync, named snapshots, virtual copies, before/after (**\**) - on-device auto subject, sky and background masks (no model download), an - ISO/camera-aware noise starting point, edge-aware lens-softness compensation, and an - approximate paper soft-proof preview + ISO/camera-aware noise starting point, edge-aware lens-softness compensation, and soft + proofing through a loaded printer ICC profile (or a paper simulation when none is) - HDR merge with alignment, horizontal panorama stitching and focus stacking; each result is added to the catalog as a new editable photo - browser print layouts (A4, Letter, 5×7) rendered through the develop pipeline @@ -97,7 +103,9 @@ non-destructive: Clients need no account: they see that event's live photos, heart favourites, leave per-photo comments, mark a photo approved or needing changes, and download proofs individually or as one ZIP. Feedback shows up on the library grid and in the "Client -picks", "Approved" and "Changes" filters. Revoking a link drops its picks and feedback. +picks", "Approved" and "Changes" filters. Each link can carry a password, a closing +date, a download cap or downloads switched off, and a watermark that is rendered into +newly published proofs. Revoking a link drops its picks, feedback and access settings. **Team accounts.** The first signup becomes the admin. Admins create single-use invite links (`/join/`) with an optional email lock and 1–30 day expiry, copy them from @@ -111,6 +119,22 @@ quota, schedule a 24-hour cleanup of the oldest content, send a warning immediat cancel a scheduled cleanup. Cleanups stop at a target percentage of the quota instead of deleting the whole original plan. +**Tethering.** Watch a folder on the server for an event: the editor polls it, pulls +each new JPEG/TIFF/WebP/raw, imports it through the normal path (raw decode, metadata, +cloud mirroring) and only then removes the file from the folder. Point a capture app or +a transfer folder at `/tether/`; nothing is lost if the tab closes. + +**Cull assist.** Run a focus and duplicate pass over the selection from the command +palette. Every frame is scored from its own thumbnail with a Laplacian variance, and +near-duplicates are grouped by 64-bit difference hash, so the sharpest frame of a +burst can be kept and the alternatives flagged in one action. Nothing is rated or +rejected without confirmation. + +**Sidecars.** Export the selected photos' develop settings as Lightroom-style `.xmp` +sidecars (crs: attributes plus a private payload for the rest of the grade) and import +a sidecar back onto a photo. Importing keeps the crop, masks and lens profile for every +field the file does not mention. + **Catalog workflow.** Editable title, caption, creator, copyright and keyword chips with a keyword library and reusable metadata presets. Save the current filters and sort order as a smart collection. Virtual copies share the master file but keep independent @@ -118,9 +142,10 @@ edits; named snapshots preserve alternative looks. **Export and print.** JPEG, PNG, WebP or uncompressed 16-bit TIFF; quality; resize by long edge or percent; filename template (`{name}`, `{date}`, `{time}`, `{index}`); saved -export recipes; output sharpening; watermark; XMP metadata embedded in JPEGs; an -embedded sRGB ICC profile; batch export as one ZIP or separate files. Full-resolution -export runs through the same renderer as the screen preview. +export recipes; output sharpening; watermark; XMP metadata embedded in JPEGs; sRGB, +Display P3 or Adobe RGB output with a matching generated ICC profile (JPEG/TIFF); batch +export as one ZIP or separate files. Full-resolution export runs through the same +renderer as the screen preview. **Administration.** Users, roles, invites, catalog backup/restore, per-account quotas, email settings and a storage relocation tool are all in one panel. @@ -204,6 +229,7 @@ storage, while quotas are stored per account in the database. | `LUMINARY_INVITE` | *(empty)* | Shared registration code for teammates; personal invite links work without it | | `LUMINARY_MAX_UPLOAD` | `314572800` (300 MB) | Largest accepted upload, in bytes | | `LUMINARY_RAW_EDGE` | `6000` | Long edge of the editable JPEG proxy made from a raw | +| `LUMINARY_16BIT` | `1` | Also keep the decoded samples as a 16-bit PNG beside the raw proxy; `0` saves the disk and download it costs, at the price of grading an 8-bit source | | `LUMINARY_RAW_WORKERS` | `min(4, cores−1)` | Concurrent LibRaw decoders; each holds a worker and a few hundred MB | | `LUMINARY_RAW_IDLE_MS` | `90000` | Idle decoders are disposed after this to release memory | | `LUMINARY_DENOISE_WORKERS` | `min(4, cores−1)` | Concurrent detail-denoise jobs (read directly from the environment) | @@ -427,9 +453,14 @@ Data directory | `src/lib/import.ts` | File ingest, EXIF read, preview/thumb creation, upload scheduling | | `src/lib/export.ts` | Renderer-driven export, recipes, watermark, filenames, ZIP | | `src/lib/tiff.ts`, `icc.ts` | Dependency-free 16-bit TIFF writer and sRGB profile | +| `src/lib/preview16.ts` | 16-bit raw-proxy PNG parser, camera matrix and half-float conversion for the RGBA16F source texture | +| `src/lib/softProof.ts` | ICC parsing (lut8/lut16/mAB), printer A2B/B2A round trip and the 3D proof cube | +| `src/lib/dcp.ts` | DCP tag reader and the camera-to-sRGB matrix recipe | | `src/lib/lensfun.ts`, `lensNames.ts`, `lensDefaults.ts` | Lensfun client, EXIF matching, saved defaults | | `src/lib/merge.ts` | HDR / panorama / focus-stack composition | | `src/lib/autoMask.ts`, `noiseProfile.ts` | On-device masks and ISO-aware noise starting points | +| `src/lib/xmp.ts` | Lightroom-compatible XMP sidecar reader/writer | +| `src/lib/cull.ts` | Focus scoring and duplicate hashing for cull assist | | `src/lib/curves.ts`, `whiteBalance.ts`, `clipPreview.ts`, `presets.ts` | Curve sampling, WB maths, clipping display, presets | | `docs/user-guide/` | Source of the in-app user guide (`guide.html`), also shipped as PDF | @@ -510,6 +541,12 @@ routes are public and are gated only by the share token. | --- | --- | --- | --- | | GET | `/api/sync` | session | Everything the workspace needs: user, events, photos, presets, proof summary | | GET | `/api/proofs` | session | Client pick/comment/review summary for the owner's events | +| PUT | `/api/events/:id/share/settings` | owner | Password, expiry, watermark, download switch and cap for the proofing link | +| GET | `/api/galleries/:token/status` | public | Whether the link is locked, its expiry and whether downloads are allowed | +| POST | `/api/galleries/:token/unlock` | public | Exchange the gallery password for a link-scoped unlock cookie | +| GET | `/api/events/:id/tether` | owner | Watch-folder path and the frames waiting in it | +| GET | `/api/events/:id/tether/file?name=` | owner | Stream one waiting frame to the editor | +| DELETE | `/api/events/:id/tether/file?name=` | owner | Remove a frame after it imported | | PUT | `/api/presets` | session | Replace the stored preset library | | PUT | `/api/events/:id` | owner | Upsert an event record | | DELETE | `/api/events/:id` | owner | Delete an event (photos are handled separately) | @@ -783,9 +820,22 @@ for album assets inline first, retries with `withoutAssets=false`, and falls bac The browser cannot demosaic camera raw, so the server does it during upload: 1. The original file is stored byte-for-byte in `originals/` with its real extension. -2. LibRaw (`libraw-wasm`) opens it in a pooled worker with camera white balance, sRGB - output and the container's orientation, then `sharp` encodes an editable JPEG proxy - at `LUMINARY_RAW_EDGE` (6000 px by default). +2. LibRaw (`libraw-wasm`) opens it in a pooled worker with camera white balance and the + container's orientation and returns the frame **before** any output colourspace + (`outputColor: 0`). The camera-to-sRGB step is then the body's own `rgb_cam` matrix, + applied in `server/color.mjs` — the same 3×3 matrix the editor applies to the sidecar, + so changing the camera profile is a matrix swap rather than a second decode. One + white point is chosen for the frame from the matrixed pixels (99th percentile, the + clipping policy LibRaw's auto-bright targets) and baked into both outputs; LibRaw's + own auto-bright measures each output path separately and would leave the JPEG a third + of a stop away from the sidecar. `sharp` encodes the editable JPEG proxy at + `LUMINARY_RAW_EDGE` (6000 px by default). The same decode also writes a 16-bit PNG of + the camera samples beside it (`previews/.p16.png`, roughly 25× the JPEG) with the + matrix in a `tEXt` chunk: the editor inflates that sidecar into an `RGBA16F` source + texture and applies `rgb_cam` in the grade shader, so the grade has 65,536 levels per + channel instead of 256. A photo without a sidecar — one imported before this existed, + a non-raw file, or a build with `LUMINARY_16BIT=0` — simply grades the JPEG, so + nothing breaks either way. 3. If LibRaw cannot open the file, the largest JPEG embedded in the container is extracted and normalised instead. The grid marks such photos `RAW` and the Info panel reports which engine produced the proxy, so exotic or very new cameras still import. @@ -796,6 +846,17 @@ Formats: CR2/CR3/CRW, NEF/NRW, ARW/SRF/SR2, ORF, RW2/RWL/RAW, RAF, PEF, DNG, SRW FFF, IIQ, X3F, ERF, K25/KDC, DCR, MOS, MRW, MEF, SRAW. Content sniffing checks the container signature before wasting a decode attempt. +**Camera-native conversion, measured.** `rgb_cam` is applied to the sRGB-decoded camera +samples; `outputColor: 0` output is sRGB-encoded, not linear (a power curve fits it +1.8 ΔE worse). Against LibRaw's sRGB + auto-bright output on this repository's test +raws, the new proxy sits at mean ΔE 0.3–2.4 on normally exposed frames with the same +~1 % highlight clipping, and 5.5 on one very dark frame where the two auto-bright +policies disagree most — one shared white point cannot match a per-path heuristic +exactly. Applying the sidecar's matrix in the shader reproduces the server-encoded +proxy to within one 8-bit code, so the two outputs cannot drift apart. Deriving the +same matrix from a DCP `ColorMatrix1` — `inverse(rowNormalise(ColorMatrix · xyz_rgb))` +— matches LibRaw's `rgb_cam` to 2.2e-5 on a D700 NEF and 2.7e-5 on a 5D Mark II CR2. + **Parallel import.** Decoding runs in a bounded pool of LibRaw workers (default `min(4, cores−1)`, `LUMINARY_RAW_WORKERS`), and the browser uploads several files at a time. Each instance owns one worker thread; extra jobs queue. Idle instances are @@ -897,7 +958,7 @@ Conventions worth knowing before changing code: ### Tests -`npm test` runs six Vitest files, all pure-logic: +`npm test` runs the pure-logic Vitest suite: | File | Covers | | --- | --- | @@ -907,6 +968,9 @@ Conventions worth knowing before changing code: | `src/lib/lensNames.test.ts` | EXIF lens-name normalisation, search variants and match scoring | | `src/lib/lensDefaults.test.ts` | Camera + lens default selection and rejection rules | | `src/lib/editSections.test.ts` | Selective settings copy and the ISO-aware auto-noise curve | +| `src/lib/preview16.test.ts` | 16-bit PNG proxy parsing, row flip, half-float encoding and the camera matrix chunk | +| `src/lib/dcp.test.ts` | DCP tag parsing and the camera matrix recipe against LibRaw's own values | +| `src/lib/softProof.test.ts` | ICC parsing (including counted lut16 tables), the printer round trip, gamut threshold and CMYK profiles | There are no server integration tests; the API is exercised through the UI. @@ -931,20 +995,51 @@ There are no server integration tests; the API is exercised through the UI. ## Limitations -- **Not a cloud service.** No hosted deployment, no tethered capture, no sync client - beyond one browser tab's whole-record push. The last writer wins per photo; it is +- **Not a cloud service.** No hosted deployment and no camera driver: tethering is a + server drop folder, not a PTP/USB connection. No sync client beyond one browser tab's + whole-record push. The last writer wins per photo; it is designed for a handful of people, not concurrent batch workflows. - **Per-account catalogs.** Workspaces are private to their owner; there is no shared library between two members. Collaboration happens through client proofing links and the admin overview. -- **Proxy-bounded raw.** Raw editing works on the demosaiced JPEG proxy (6000 px - default), not the sensor mosaic; export size is bounded by the proxy. -- **Approximate tools.** Temperature/tint are relative to the as-shot white balance. - Auto masks are an on-device saliency/colour estimate, not a segmentation model. Soft - proofing approximates paper white, black point and print gamut but does not apply a - printer ICC profile; use the browser print dialog for final ICC handling. The +- **Proxy-bounded raw.** Raw editing works on the demosaiced proxy (6000 px default), + not the sensor mosaic; export size is bounded by the proxy. Raw imports keep two + files: the JPEG proxy every browser can decode, and a 16-bit PNG sidecar of the same + pixels. The editor grades the sidecar as a half-float source texture when it is + present, which is what keeps a heavy shadow lift or a 3200 K white balance from + posterising an 8-bit source; the JPEG and everything derived from it (thumbnails, + denoise renders, proofs) stay 8-bit. A per-photo DCP profile is applied wherever + the sidecar is, i.e. the Develop canvas and exports; grid thumbnails and the compare + view grade the sRGB JPEG, which already has the body matrix baked in, so they do not + show a different camera profile. The sidecar costs about 25× the JPEG in disk, one download per photo at open time and + one extra texture in GPU memory (about 8 bytes per pixel), so `LUMINARY_16BIT=0` turns + it off for libraries that would rather have the space. Either way the 16-bit TIFF export writes 65,536 + samples per channel from the `RGBA16F` render target, so its precision is only more + than the source's when the sidecar was available; it never invents detail the decode + did not produce. +- **Approximate tools.** The relative Temp/Tint sliders and the absolute Kelvin + control are display-space gains; they are not a camera-specific white-balance + matrix pair. Raw decode uses the camera's own matrix; a DCP `ColorMatrix` reproduces + it exactly (`src/lib/dcp.ts` parses the file and derives the matrix), and **Develop → + Camera profile** loads a `.dcp` per photo, storing the derived 9-number matrix in + the edit so it follows presets, snapshots and XMP. The picker is available only on + camera-native sidecars; an older sRGB proxy needs a RAW reprocess first. + Auto masks are an on-device colour-model segmentation (border histogram, Otsu split, + connected components), not a trained segmentation network, so a subject that shares + its colour with the background needs a brush pass. Soft + proofing applies a printer profile's real A2B/B2A tables when one is loaded + (**Soft proofing → Load ICC profile**), and falls back to paper white, black point and + a gamut approximation otherwise. The profile is session state rather than part of the + edit, and the print dialog still does its own colour management. Both LUT layouts are + read: v2 `lut16` with fixed 256-entry tables and the counted v4 layout that MOAB/Epson + paper profiles and Ghostscript's press profiles actually use (4096 entries, counts at + offsets 48/50). Against LittleCMS on a MOAB/Epson ET-8550 profile the cube agrees to a + mean 0.97 and p95 3 of 255 per channel. The gamut warning uses a ΔE76 round-trip + threshold of 2.5 with no endpoint rule: on the repository's photos that flags 6–8 % of + pixels, the 90th percentile round trip is 1.5 ΔE, and the neutral ramp stays clean. The auto-noise profile is an ISO/camera heuristic over the existing sliders, not a - calibrated sensor model. + calibrated sensor model, and sharpening is multi-scale unsharp masking rather than + deconvolution. - **Merge scope.** HDR, panorama and focus stacking are translation-aligned and aimed at bracketed, stacked or horizontal sequences, not handheld multi-row composites. They compose at a reduced working edge (2600 px). diff --git a/server/color.mjs b/server/color.mjs new file mode 100644 index 0000000..ad115d2 --- /dev/null +++ b/server/color.mjs @@ -0,0 +1,144 @@ +/** + * Camera-native colour conversion for the raw pipeline. + * + * LibRaw can hand back the demosaiced frame before it applies any output + * colourspace (`outputColor: 0`). Those samples are the camera's own RGB, + * white-balanced and gamma encoded, which is what a camera profile needs: the + * camera-to-sRGB step becomes a matrix the editor can swap out without + * decoding the raw again. + * + * One white point is chosen for the whole frame from the *converted* pixels, so + * the JPEG proxy and the 16-bit sidecar share an exposure. LibRaw's own + * auto-bright is deliberately off: it measures each output path separately, + * which leaves the two outputs a third of a stop apart. + */ + +export function srgbToLinear(value) { + const v = value <= 0 ? 0 : value >= 1 ? 1 : value; + return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; +} + +export function linearToSrgb(value) { + const v = value <= 0 ? 0 : value >= 1 ? 1 : value; + return v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055; +} + +let decodeTable = null; +let encodeTable = null; + +/** 16-bit sample -> linear light, for the camera's own gamma encoding. */ +function linearTable() { + if (!decodeTable) { + decodeTable = new Float32Array(65536); + for (let i = 0; i < 65536; i++) decodeTable[i] = srgbToLinear(i / 65535); + } + return decodeTable; +} + +/** Linear light (indexed as a 16-bit fraction) -> 8-bit sRGB. */ +function encodedTable() { + if (!encodeTable) { + encodeTable = new Uint8Array(65536); + for (let i = 0; i < 65536; i++) { + encodeTable[i] = Math.round(linearToSrgb(i / 65535) * 255); + } + } + return encodeTable; +} + +/** Flattens the metadata's 4x4 `rgb_cam` into the 3x3 camera -> sRGB matrix. */ +export function readRgbCam(meta) { + const raw = meta?.color_data?.rgb_cam; + if (!Array.isArray(raw) || raw.length < 3) return null; + const matrix = []; + for (let row = 0; row < 3; row++) { + const values = raw[row]; + if (!Array.isArray(values) || values.length < 3) return null; + for (let col = 0; col < 3; col++) { + const value = Number(values[col]); + if (!Number.isFinite(value)) return null; + matrix.push(value); + } + } + // A zero matrix would render the whole frame black; that is a metadata + // failure, not a look, so fall back to LibRaw's own conversion. + if (matrix.every((value) => Math.abs(value) < 1e-6)) return null; + return matrix; +} + +/** + * Converts a camera-native 16-bit frame into the two buffers the editor needs, + * in place: + * + * - `rgb8` the sRGB proxy the JPEG is encoded from + * - `rgb16` the camera samples, white-point scaled, still camera native + * + * Returns the white point gain that was applied. The gain is baked into both + * buffers, so the client only has to apply the camera matrix; keeping it out of + * the sidecar would mean shipping a second 16-bit table for no benefit. + */ +export function cameraToProxy(rgb16, rgb8, matrix) { + const linear = linearTable(); + const encode = encodedTable(); + const count = Math.floor(rgb16.length / 3); + const m = matrix ?? [1, 0, 0, 0, 1, 0, 0, 0, 1]; + + // Pass 1: where does the fastest channel sit? Choosing the white point after + // the matrix keeps highlight clipping at about the same 1% LibRaw targets, + // instead of clipping whatever the matrix pushes past 1 on top of that. + const hist = new Uint32Array(65536); + for (let i = 0; i < count; i++) { + const s = i * 3; + const r = linear[rgb16[s]]; + const g = linear[rgb16[s + 1]]; + const b = linear[rgb16[s + 2]]; + const max = Math.max( + m[0] * r + m[1] * g + m[2] * b, + m[3] * r + m[4] * g + m[5] * b, + m[6] * r + m[7] * g + m[8] * b, + ); + const bin = max <= 0 ? 0 : max >= 1 ? 65535 : Math.round(max * 65535); + hist[bin]++; + } + let seen = 0; + let p99 = 65535; + const target = count * 0.99; + for (let i = 0; i < 65536; i++) { + seen += hist[i]; + if (seen >= target) { + p99 = i; + break; + } + } + // Cap the gain: a nearly black frame is a real photograph, not a reason to + // multiply read noise by fifty. + const gain = Math.min(48, Math.max(0.25, 65535 / Math.max(1, p99))); + + // Camera samples stay gamma encoded, so a shadow lift still has 16 bits of + // encoded detail to work from rather than 16 bits of linear light. + const camera = new Uint16Array(65536); + for (let i = 0; i < 65536; i++) { + camera[i] = Math.round(linearToSrgb(linear[i] * gain) * 65535); + } + + // Pass 2: write both buffers. + for (let i = 0; i < count; i++) { + const s = i * 3; + const r = linear[rgb16[s]] * gain; + const g = linear[rgb16[s + 1]] * gain; + const b = linear[rgb16[s + 2]] * gain; + rgb8[s] = encode[clampIndex(m[0] * r + m[1] * g + m[2] * b)]; + rgb8[s + 1] = encode[clampIndex(m[3] * r + m[4] * g + m[5] * b)]; + rgb8[s + 2] = encode[clampIndex(m[6] * r + m[7] * g + m[8] * b)]; + rgb16[s] = camera[rgb16[s]]; + rgb16[s + 1] = camera[rgb16[s + 1]]; + rgb16[s + 2] = camera[rgb16[s + 2]]; + } + return gain; +} + +function clampIndex(value) { + if (!(value > 0)) return 0; + if (value >= 1) return 65535; + return Math.round(value * 65535); +} diff --git a/server/config.mjs b/server/config.mjs index 2e85f4b..9cfe937 100644 --- a/server/config.mjs +++ b/server/config.mjs @@ -75,6 +75,13 @@ export const SMTP_FROM = setting('SMTP_FROM', SMTP_USER); /** Long edge used for the editable proxy of raw files. */ export const RAW_PREVIEW_EDGE = Number(setting('RAW_EDGE', '6000')); +/** + * Also store the 16-bit samples LibRaw decoded as a sidecar next to the JPEG + * proxy. It costs roughly 25x the JPEG in disk and download, but it is the only + * way the editor can grade from more than 256 levels per channel. + */ +export const RAW_16BIT = setting('16BIT', '1') !== '0'; + export const SESSION_DAYS = 30; /** How many raws decode at once. One core is left for the HTTP server. */ diff --git a/server/db.mjs b/server/db.mjs index 4ec75ab..f08ac55 100644 --- a/server/db.mjs +++ b/server/db.mjs @@ -89,6 +89,18 @@ db.exec(` CREATE INDEX IF NOT EXISTS gallery_reviews_token ON gallery_reviews(token); + CREATE TABLE IF NOT EXISTS gallery_settings ( + token TEXT PRIMARY KEY, + password_hash TEXT NOT NULL DEFAULT '', + password_salt TEXT NOT NULL DEFAULT '', + expires_at INTEGER, + watermark TEXT NOT NULL DEFAULT '', + allow_downloads INTEGER NOT NULL DEFAULT 1, + download_cap INTEGER NOT NULL DEFAULT 0, + download_count INTEGER NOT NULL DEFAULT 0, + updated_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS invites ( token TEXT PRIMARY KEY, email TEXT NOT NULL DEFAULT '', @@ -607,6 +619,71 @@ export function picksByOwner(ownerId) { })); } +const gallerySettingsStmt = db.prepare('SELECT * FROM gallery_settings WHERE token = ?'); +const upsertGallerySettings = db.prepare(` + INSERT INTO gallery_settings + (token, password_hash, password_salt, expires_at, watermark, allow_downloads, download_cap, download_count, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(token) DO UPDATE SET + password_hash = excluded.password_hash, + password_salt = excluded.password_salt, + expires_at = excluded.expires_at, + watermark = excluded.watermark, + allow_downloads = excluded.allow_downloads, + download_cap = excluded.download_cap, + updated_at = excluded.updated_at +`); +const deleteGallerySettings = db.prepare('DELETE FROM gallery_settings WHERE token = ?'); +const bumpGalleryDownload = db.prepare( + 'UPDATE gallery_settings SET download_count = download_count + 1 WHERE token = ?', +); +const readGalleryDownloads = db.prepare( + 'SELECT download_count FROM gallery_settings WHERE token = ?', +); + +/** Access rules for a public proofing link; defaults when none were saved. */ +export function gallerySettingsFor(token) { + const row = gallerySettingsStmt.get(token); + return { + passwordHash: row?.password_hash ?? '', + passwordSalt: row?.password_salt ?? '', + expiresAt: row?.expires_at ?? null, + watermark: row?.watermark ?? '', + allowDownloads: row ? Boolean(row.allow_downloads) : true, + downloadCap: row?.download_cap ?? 0, + downloadCount: row?.download_count ?? 0, + }; +} + +/** + * The download counter is deliberately preserved across settings edits: an + * owner tightening or loosening a cap must not hand out a fresh allowance. + */ +export function saveGallerySettings(token, settings) { + upsertGallerySettings.run( + token, + settings.passwordHash ?? '', + settings.passwordSalt ?? '', + settings.expiresAt ?? null, + settings.watermark ?? '', + settings.allowDownloads === false ? 0 : 1, + Math.max(0, Math.round(settings.downloadCap ?? 0)), + 0, + Date.now(), + ); + return gallerySettingsFor(token); +} + +export function clearGallerySettings(token) { + deleteGallerySettings.run(token); +} + +/** Counts a gallery download and reports the new total, or 0 when uncapped. */ +export function noteGalleryDownload(token) { + bumpGalleryDownload.run(token); + return readGalleryDownloads.get(token)?.download_count ?? 0; +} + export function galleryPick(token, photoId, clientId, clientName, picked) { if (!picked) { q.deletePick.run(token, photoId, clientId); diff --git a/server/imaging.mjs b/server/imaging.mjs index eacb214..479e8f9 100644 --- a/server/imaging.mjs +++ b/server/imaging.mjs @@ -68,7 +68,99 @@ export function encodePng(rgb, width, height) { ]); } -/** Encode an interleaved RGB byte buffer as JPEG (sharp) or PNG (fallback). */ +/** + * Box-average a 16-bit RGB image down to the proxy size. sharp's raw pipeline + * does not round-trip 16-bit samples faithfully, and this keeps the sidecar + * pixel-aligned with the JPEG that was encoded by a different library. + */ +export function resizeRgb16(rgb16, width, height, tw, th) { + if (width === tw && height === th) return rgb16; + const out = new Uint16Array(tw * th * 3); + const fx = width / tw; + const fy = height / th; + for (let y = 0; y < th; y++) { + const y0 = Math.floor(y * fy); + const y1 = Math.min(height, Math.max(y0 + 1, Math.ceil((y + 1) * fy))); + for (let x = 0; x < tw; x++) { + const x0 = Math.floor(x * fx); + const x1 = Math.min(width, Math.max(x0 + 1, Math.ceil((x + 1) * fx))); + let r = 0; + let g = 0; + let b = 0; + let n = 0; + for (let sy = y0; sy < y1; sy++) { + let at = (sy * width + x0) * 3; + for (let sx = x0; sx < x1; sx++) { + r += rgb16[at]; + g += rgb16[at + 1]; + b += rgb16[at + 2]; + at += 3; + n += 1; + } + } + const d = (y * tw + x) * 3; + out[d] = Math.round(r / n); + out[d + 1] = Math.round(g / n); + out[d + 2] = Math.round(b / n); + } + } + return out; +} + +/** + * 16-bit RGB PNG (colour type 2, no interlacing, Sub-filtered rows). The editor + * inflates this in the browser and uploads it as a half-float texture, so it has + * to be a standard PNG rather than a private container. Sub filtering subtracts + * each byte from the pixel six bytes to its left, which compresses photographic + * rows far better than storing the samples raw. + * + * `matrix` is the camera-to-sRGB matrix (9 numbers, row major). It is written to + * a tEXt chunk because the sidecar holds camera-native samples: without it the + * client would have to guess the conversion, and a self-describing sidecar also + * keeps working for imports that predate a catalogue migration. + */ +export function encodePng16(rgb16, width, height, matrix = null) { + const stride = width * 6; + const raw = Buffer.alloc((stride + 1) * height); + const row = Buffer.alloc(stride); + for (let y = 0; y < height; y++) { + let at = y * width * 3; + for (let i = 0; i < stride; i += 2) { + row.writeUInt16BE(rgb16[at++] & 0xffff, i); + } + const base = y * (stride + 1); + raw[base] = 1; + for (let i = 0; i < stride; i++) { + raw[base + 1 + i] = (row[i] - (i >= 6 ? row[i - 6] : 0)) & 0xff; + } + } + const idat = zlib.deflateSync(raw, { level: 6 }); + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(width, 0); + ihdr.writeUInt32BE(height, 4); + ihdr[8] = 16; + ihdr[9] = 2; + ihdr[10] = 0; + ihdr[11] = 0; + ihdr[12] = 0; + return Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + chunk('IHDR', ihdr), + ...(matrix && matrix.length === 9 + ? [ + chunk( + 'tEXt', + Buffer.from( + `rgbCam\0${matrix.map((value) => Number(value).toFixed(8)).join(',')}`, + 'latin1', + ), + ), + ] + : []), + chunk('IDAT', idat), + chunk('IEND', Buffer.alloc(0)), + ]); +} export async function encodeRgb(rgb, width, height, quality = 92, maxEdge = 0) { const sharp = await loadSharp(); if (!sharp) { diff --git a/server/index.mjs b/server/index.mjs index 7cebaf3..51c8225 100644 --- a/server/index.mjs +++ b/server/index.mjs @@ -56,16 +56,19 @@ import { defaultRoot, findOriginal, findPreview, + findPreview16, findProof, findProofThumb, findThumb, isCustomRoot, originalTarget, removeAsset, + removePreview16, setStorageRoot, storageBytes, storageRoot, writePreview, + writePreview16, writeProof, writeProofThumb, writeThumb, @@ -238,6 +241,77 @@ function normalizePhotoMime(value, name = '') { return PHOTO_MIME_BY_EXT[ext] ?? 'application/octet-stream'; } +import { + gallerySettingsFor, + saveGallerySettings, + clearGallerySettings, + noteGalleryDownload, +} from './db.mjs'; + +/** Passwords are hashed per link with a random salt, so a database dump is not a key. */ +function hashGalleryPassword(password, salt) { + return crypto.scryptSync(password, salt, 32).toString('hex'); +} + +/* Unlocked galleries live in memory: a restart asks for the password again. */ +const galleryUnlocks = new Map(); +const GALLERY_UNLOCK_MS = 12 * 3600 * 1000; +const galleryCookie = (token) => `lumg_${token}`; + +/** + * One check for every public gallery route: revoked link, expiry, password. + * A locked gallery is a 401 so the page can show the password prompt instead + * of claiming the shoot is gone. + */ +function galleryGate(req, token) { + const shared = eventByShareToken(token); + if (!shared) { + return { ok: false, status: 404, message: 'This proofing gallery is no longer available' }; + } + const settings = gallerySettingsFor(token); + if (settings.expiresAt && Date.now() > settings.expiresAt) { + return { ok: false, status: 410, message: 'This proofing gallery has expired' }; + } + if (settings.passwordHash) { + const cookie = parseCookies(req)[galleryCookie(token)]; + const entry = galleryUnlocks.get(token); + const valid = + cookie && entry && entry.key === cookie && entry.expires > Date.now() + ? true + : false; + if (!valid) { + return { + ok: false, + status: 401, + message: 'This gallery is password protected', + locked: true, + }; + } + } + return { ok: true, shared, settings }; +} + +/** Writes the refusal and returns true when the caller must stop. */ +function galleryDenied(req, res, token) { + const gate = galleryGate(req, token); + if (gate.ok) return false; + error(res, gate.status, gate.message); + return true; +} + +/** Refuses a download when the link turned downloads off or used its allowance. */ +function galleryDownloadDenied(res, token, settings) { + if (!settings.allowDownloads) { + error(res, 403, 'Downloads are disabled for this gallery'); + return true; + } + if (settings.downloadCap > 0 && settings.downloadCount >= settings.downloadCap) { + error(res, 403, 'This gallery has reached its download limit'); + return true; + } + return false; +} + function parseCookies(req) { const out = {}; for (const part of String(req.headers.cookie ?? '').split(';')) { @@ -1315,6 +1389,103 @@ route('GET', '/api/events/:id/share', async ({ req, res, params }) => { .map((p) => ({ photoId: p.photoId, clientName: p.clientName })) : [], feedback, + settings: token + ? (() => { + const saved = gallerySettingsFor(token); + return { + passwordSet: Boolean(saved.passwordHash), + expiresAt: saved.expiresAt, + watermark: saved.watermark, + allowDownloads: saved.allowDownloads, + downloadCap: saved.downloadCap, + downloadCount: saved.downloadCount, + }; + })() + : null, + }); +}); + +/** Owner-side security settings for the proofing link. */ +route('PUT', '/api/events/:id/share/settings', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); + const token = shareTokenFor(params.id); + if (!token) return error(res, 404, 'This event has no proofing link yet'); + const body = await readJson(req, 64 * 1024); + const current = gallerySettingsFor(token); + let passwordHash = current.passwordHash; + let passwordSalt = current.passwordSalt; + if (typeof body.password === 'string') { + const password = body.password.trim(); + if (password === '') { + passwordHash = ''; + passwordSalt = ''; + } else if (password.length < 4) { + return error(res, 400, 'Use at least 4 characters for the gallery password'); + } else { + passwordSalt = crypto.randomBytes(12).toString('hex'); + passwordHash = hashGalleryPassword(password, passwordSalt); + } + } + const saved = saveGallerySettings(token, { + passwordHash, + passwordSalt, + expiresAt: + typeof body.expiresAt === 'number' && body.expiresAt > 0 ? body.expiresAt : null, + watermark: String(body.watermark ?? '').trim().slice(0, 80), + allowDownloads: body.allowDownloads !== false, + downloadCap: Number.isFinite(Number(body.downloadCap)) + ? Math.max(0, Math.min(100000, Math.round(Number(body.downloadCap)))) + : current.downloadCap, + }); + json(res, 200, { + settings: { + passwordSet: Boolean(saved.passwordHash), + expiresAt: saved.expiresAt, + watermark: saved.watermark, + allowDownloads: saved.allowDownloads, + downloadCap: saved.downloadCap, + downloadCount: saved.downloadCount, + }, + }); +}); + +/** Public unlock: exchanges the gallery password for a cookie scoped to the link. */ +route('POST', '/api/galleries/:token/unlock', async ({ req, res, params }) => { + if (!allowGalleryWrite(req, params.token)) { + return error(res, 429, 'Too many attempts. Try again shortly.', { 'Retry-After': '60' }); + } + const gate = galleryGate(req, params.token); + if (!gate.ok && gate.status === 410) return error(res, 410, gate.message); + if (!gate.ok && !gate.locked) return error(res, gate.status, gate.message); + const settings = gallerySettingsFor(params.token); + if (!settings.passwordHash) return json(res, 200, { ok: true }); + const body = await readJson(req, 16 * 1024); + const password = String(body.password ?? ''); + const attempt = Buffer.from(hashGalleryPassword(password, settings.passwordSalt), 'hex'); + const expected = Buffer.from(settings.passwordHash, 'hex'); + const ok = + attempt.length === expected.length && crypto.timingSafeEqual(attempt, expected); + if (!ok) return error(res, 403, 'That password does not open this gallery'); + const key = crypto.randomBytes(24).toString('base64url'); + galleryUnlocks.set(params.token, { key, expires: Date.now() + GALLERY_UNLOCK_MS }); + res.setHeader( + 'Set-Cookie', + `${galleryCookie(params.token)}=${encodeURIComponent(key)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${GALLERY_UNLOCK_MS / 1000}`, + ); + json(res, 200, { ok: true }); +}); + +/** Public: is this link locked or past its expiry? Used before the gallery loads. */ +route('GET', '/api/galleries/:token/status', async ({ req, res, params }) => { + const gate = galleryGate(req, params.token); + if (!gate.ok && !gate.locked) return error(res, gate.status, gate.message); + const settings = gate.ok ? gate.settings : gallerySettingsFor(params.token); + json(res, 200, { + locked: !gate.ok, + expiresAt: settings.expiresAt, + allowDownloads: settings.allowDownloads, }); }); @@ -1334,14 +1505,20 @@ route('DELETE', '/api/events/:id/share', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); + const token = shareTokenFor(params.id); setShareToken(params.id, null); + if (token) { + clearGallerySettings(token); + galleryUnlocks.delete(token); + } json(res, 200, { ok: true }); }); /** Public gallery payload: no session, only the shared event and its photos. */ -route('GET', '/api/galleries/:token', async ({ res, params, url }) => { - const shared = eventByShareToken(params.token); - if (!shared) return error(res, 404, 'This proofing gallery is no longer available'); +route('GET', '/api/galleries/:token', async ({ req, res, params, url }) => { + const gate = galleryGate(req, params.token); + if (!gate.ok) return error(res, gate.status, gate.message); + const shared = gate.shared; const clientId = String(url.searchParams.get('client') ?? '').slice(0, 64); const picks = picksForToken(params.token).filter((p) => p.picked); const counts = new Map(); @@ -1395,16 +1572,26 @@ route('GET', '/api/galleries/:token', async ({ res, params, url }) => { photographer: 'Luminary', photos, picks: { total: picks.length, clients: new Set(picks.map((p) => p.clientId)).size }, + downloads: { + allowed: gate.settings.allowDownloads, + remaining: + gate.settings.downloadCap > 0 + ? Math.max(0, gate.settings.downloadCap - gate.settings.downloadCount) + : null, + }, + watermark: gate.settings.watermark, }); }); route('GET', '/api/galleries/:token/photos/:id/thumb', async ({ req, res, params }) => { + if (galleryDenied(req, res, params.token)) return; if (!galleryPhoto(params.token, params.id)) return error(res, 404, 'Not found'); const file = findProofThumb(params.id) ?? (await findThumb(params.id)); return sendFile(req, res, file, 'image/jpeg', 'private, max-age=3600'); }); route('GET', '/api/galleries/:token/photos/:id/preview', async ({ req, res, params }) => { + if (galleryDenied(req, res, params.token)) return; const hit = galleryPhoto(params.token, params.id); if (!hit) return error(res, 404, 'Not found'); const proof = findProof(params.id); @@ -1423,6 +1610,9 @@ route('GET', '/api/galleries/:token/photos/:id/preview', async ({ req, res, para /** Client download of the edited proof, named like the delivered file. */ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, params }) => { + const gate = galleryGate(req, params.token); + if (!gate.ok) return error(res, gate.status, gate.message); + if (galleryDownloadDenied(res, params.token, gate.settings)) return; const hit = galleryPhoto(params.token, params.id); if (!hit) return error(res, 404, 'Not found'); const proof = findProof(params.id); @@ -1430,6 +1620,7 @@ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, par const originalName = String(hit.photo.name || 'photo.jpg'); const safe = (proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName).replace(/["\\/:*?<>|]+/g, '-'); const mime = proof ? 'image/jpeg' : normalizePhotoMime(hit.photo.mime, hit.photo.name); + noteGalleryDownload(params.token); return sendFile(req, res, file, mime, 'private, max-age=3600', { 'Content-Disposition': `attachment; filename="${safe}"`, }); @@ -1437,8 +1628,10 @@ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, par /** Download the client's favourites as one ZIP. */ route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, url }) => { - const shared = eventByShareToken(params.token); - if (!shared) return error(res, 404, 'This proofing gallery is no longer available'); + const gate = galleryGate(req, params.token); + if (!gate.ok) return error(res, gate.status, gate.message); + if (galleryDownloadDenied(res, params.token, gate.settings)) return; + const shared = gate.shared; const clientId = String(url.searchParams.get('client') ?? '').slice(0, 64); const picks = picksForToken(params.token).filter( (pick) => pick.picked && (!clientId || pick.clientId === clientId), @@ -1487,6 +1680,7 @@ route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, ur if (!entries.length) return error(res, 404, 'There are no downloadable favourites yet'); const archive = createZip(entries); + noteGalleryDownload(params.token); const eventName = String(shared.event.name || 'proofing') .replace(/[^a-z0-9._ -]+/gi, '-') .trim() || 'proofing'; @@ -1502,13 +1696,80 @@ route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, ur } }); +/* ---------------------------------------------------------------- tether */ + +/** + * Tethering is a drop folder, not a camera driver: the owner (or a synced + * tethering app) writes frames into one directory per event, and the open + * editor pulls and imports them. Files are removed from the folder only after + * the client confirms the import, so a dropped connection never loses a frame. + */ +const TETHER_EXT = new Set([ + 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'webp', + 'dng', 'cr2', 'cr3', 'nef', 'arw', 'orf', 'rw2', 'raf', 'pef', 'srw', +]); + +function tetherFolder(eventId) { + const safe = String(eventId).replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 64) || 'event'; + return { safe, dir: path.join(DATA_DIR, 'tether', safe) }; +} + +/** A bare file name in the drop folder; anything with a path is refused. */ +function tetherFileName(raw) { + const name = path.basename(String(raw ?? '')); + if (!name || name !== String(raw ?? '')) return null; + const ext = name.split('.').pop()?.toLowerCase() ?? ''; + return TETHER_EXT.has(ext) ? name : null; +} + +route('GET', '/api/events/:id/tether', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); + const folder = tetherFolder(params.id); + await fsp.mkdir(folder.dir, { recursive: true }); + const names = await fsp.readdir(folder.dir).catch(() => []); + const files = []; + for (const name of names) { + if (!tetherFileName(name)) continue; + const stat = await fsp.stat(path.join(folder.dir, name)).catch(() => null); + if (!stat?.isFile()) continue; + files.push({ name, size: stat.size, mtime: stat.mtimeMs }); + } + files.sort((a, b) => a.mtime - b.mtime); + json(res, 200, { folder: folder.dir, files }); +}); + +route('GET', '/api/events/:id/tether/file', async ({ req, res, params, url }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); + const name = tetherFileName(url.searchParams.get('name')); + if (!name) return error(res, 400, 'No such file'); + const file = path.join(tetherFolder(params.id).dir, name); + const stat = await fsp.stat(file).catch(() => null); + if (!stat?.isFile()) return error(res, 404, 'No such file'); + const mime = normalizePhotoMime('', name); + return sendFile(req, res, file, mime, 'no-store', { + 'Content-Disposition': `attachment; filename="${name}"`, + }); +}); + +route('DELETE', '/api/events/:id/tether/file', async ({ req, res, params, url }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); + const name = tetherFileName(url.searchParams.get('name')); + if (!name) return error(res, 400, 'No such file'); + await fsp.unlink(path.join(tetherFolder(params.id).dir, name)).catch(() => undefined); + json(res, 200, { ok: true }); +}); + route('POST', '/api/galleries/:token/comments', async ({ req, res, params }) => { if (!allowGalleryWrite(req, params.token)) { return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' }); } - if (!eventByShareToken(params.token)) { - return error(res, 404, 'This proofing gallery is no longer available'); - } + if (galleryDenied(req, res, params.token)) return; const body = await readJson(req, 32 * 1024); const hit = galleryPhoto(params.token, String(body.photoId ?? '')); if (!hit) return error(res, 404, 'No such photo'); @@ -1532,9 +1793,7 @@ route('POST', '/api/galleries/:token/reviews', async ({ req, res, params }) => { if (!allowGalleryWrite(req, params.token)) { return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' }); } - if (!eventByShareToken(params.token)) { - return error(res, 404, 'This proofing gallery is no longer available'); - } + if (galleryDenied(req, res, params.token)) return; const body = await readJson(req, 16 * 1024); const hit = galleryPhoto(params.token, String(body.photoId ?? '')); if (!hit) return error(res, 404, 'No such photo'); @@ -1555,9 +1814,7 @@ route('POST', '/api/galleries/:token/picks', async ({ req, res, params }) => { if (!allowGalleryWrite(req, params.token)) { return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' }); } - if (!eventByShareToken(params.token)) { - return error(res, 404, 'This proofing gallery is no longer available'); - } + if (galleryDenied(req, res, params.token)) return; const body = await readJson(req, 32 * 1024); const hit = galleryPhoto(params.token, String(body.photoId ?? '')); if (!hit) return error(res, 404, 'No such photo'); @@ -1683,6 +1940,8 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => { const data = await fsp.readFile(target); const decoded = await decodeRaw(data); await writePreview(params.id, decoded.jpeg, decoded.ext); + if (decoded.preview16) await writePreview16(params.id, decoded.preview16.data); + else await removePreview16(params.id); const info = await jpegInfo(decoded.jpeg); return json(res, 201, { raw: true, @@ -1705,6 +1964,49 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => { return json(res, 201, { raw: false, mime, size }); }); +/** + * Re-decode a stored RAW with the current pipeline settings. The original is + * never touched; only the editable proxy, its thumbnail and the cached denoise + * renders are replaced, so existing edits keep working on fresh pixels. + */ +route('POST', '/api/photos/:id/reprocess', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo'); + const photo = getPhoto(params.id); + if (!photo?.raw) return error(res, 400, 'Only RAW imports can be reprocessed'); + const original = findOriginal(params.id); + if (!original) return error(res, 404, 'The RAW original is missing from storage'); + try { + const decoded = await decodeRaw(await fsp.readFile(original)); + await writePreview(params.id, decoded.jpeg, decoded.ext); + if (decoded.preview16) await writePreview16(params.id, decoded.preview16.data); + else await removePreview16(params.id); + const thumb = await makeThumb(decoded.jpeg, 560); + if (thumb) await writeThumb(params.id, thumb); + // The old denoised renders were made from the previous proxy. + clearDenoised(params.id); + const info = await jpegInfo(decoded.jpeg); + const width = info?.width || decoded.width || photo.width; + const height = info?.height || decoded.height || photo.height; + // Stamp the record so cached previews and thumbnails are fetched again. + const previewVersion = Date.now(); + // Pass the owner explicitly: savePhoto defaults to '' and would orphan the row. + savePhoto({ ...photo, width, height, mime: 'image/jpeg', previewVersion }, Date.now(), user.id); + json(res, 200, { + width, + height, + engine: decoded.engine, + note: decoded.note ?? null, + previewVersion, + previewUrl: `/api/photos/${params.id}/preview?v=${previewVersion}`, + thumbUrl: `/api/photos/${params.id}/thumb?v=${previewVersion}`, + }); + } catch (err) { + return error(res, 422, err instanceof Error ? err.message : 'Could not reprocess this RAW file'); + } +}); + route('GET', '/api/photos/:id/thumb', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); @@ -1784,6 +2086,18 @@ route('GET', '/api/photos/:id/preview', async ({ req, res, params }) => { return sendFile(req, res, findOriginal(params.id), 'application/octet-stream'); }); +/** + * The 16-bit half of a raw proxy. The editor inflates it and uploads it as a + * half-float source texture so a heavy grade keeps its precision; the JPEG at + * `/preview` stays the fallback when this file is absent or too large to fetch. + */ +route('GET', '/api/photos/:id/preview16', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found'); + return sendFile(req, res, findPreview16(params.id), 'image/png'); +}); + route('POST', '/api/photos/:id/denoise', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); @@ -1892,8 +2206,12 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => { await writeThumb(params.id, thumb.data); delete record.thumb; } + const versionQuery = + typeof record.previewVersion === 'number' && Number.isFinite(record.previewVersion) + ? `?v=${record.previewVersion}` + : ''; if (record.raw) { - record.previewUrl = `/api/photos/${params.id}/preview`; + record.previewUrl = `/api/photos/${params.id}/preview${versionQuery}`; const preview = findPreview(params.id); if (!preview) { const original = findOriginal(params.id); @@ -1905,7 +2223,7 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => { } record.thumbUrl = record.proofAt ? `/api/photos/${params.id}/thumb?proof=${record.proofAt}` - : `/api/photos/${params.id}/thumb`; + : `/api/photos/${params.id}/thumb${versionQuery}`; savePhoto(record, Date.now(), user.id); json(res, 200, { photo: record }); }); diff --git a/server/raw.mjs b/server/raw.mjs index 8d05427..9da351f 100644 --- a/server/raw.mjs +++ b/server/raw.mjs @@ -1,5 +1,6 @@ -import { RAW_PREVIEW_EDGE } from './config.mjs'; -import { encodeRgb, jpegInfo, loadSharp, toJpegProxy } from './imaging.mjs'; +import { RAW_16BIT, RAW_PREVIEW_EDGE } from './config.mjs'; +import { cameraToProxy, readRgbCam } from './color.mjs'; +import { encodePng16, encodeRgb, jpegInfo, loadSharp, resizeRgb16, toJpegProxy } from './imaging.mjs'; import { loadLibRaw, rawPool } from './libraw-pool.mjs'; /** Every raw container the pipeline will attempt, grouped by vendor family. */ @@ -57,12 +58,25 @@ export async function rawEngine() { } const DECODE_SETTINGS = { - outputBps: 8, + // Decode at 16 bits and let LibRaw blend reconstructed highlights instead of + // clipping them; the 8-bit proxy is downsampled after the rolloff, so a + // recovered sky keeps gradation instead of a flat white patch. + outputBps: 16, useCameraWb: true, - outputColor: 1, // sRGB + // Camera-native, not sRGB: the camera-to-output matrix is applied here in JS + // (see color.mjs) and again by the editor on the 16-bit sidecar. That makes + // the conversion one swappable matrix instead of a fixed choice inside + // LibRaw, which is what a camera profile needs. + outputColor: 0, userQual: 3, - highlight: 0, - noAutoBright: false, + highlight: 2, + // One white point for the frame, chosen after the matrix. LibRaw's per-path + // auto-bright measures each output colourspace separately, so the JPEG and + // the camera-native sidecar would disagree by up to half a stop. + noAutoBright: true, + // Always use the camera's own colour matrix. The default only does so when + // white balance is applied, which leaves some bodies on the generic matrix. + useCameraMatrix: 3, // Use the orientation stored in the raw container: phone and DSLR files often // record the shot rotated (EXIF 6/8), and demosaicing without it produces a // sideways proxy that no later step can fix without losing the original axes. @@ -70,7 +84,13 @@ const DECODE_SETTINGS = { useFujiRotate: -1, }; -/** Turns one LibRaw `imageData()` result into an interleaved RGB buffer. */ +/** + * Turns one LibRaw `imageData()` result into an interleaved RGB buffer. + * + * The 8-bit copy is what the JPEG proxy is encoded from. The 16-bit copy keeps + * every sample LibRaw produced so the editor can upload a half-float source + * texture; without it, a heavy shadow lift is applied to 256 levels per channel. + */ function toRgb(img) { if (!img || !img.width || !img.height || !img.data) throw new Error('LibRaw returned no pixels'); const width = Number(img.width); @@ -79,19 +99,36 @@ function toRgb(img) { const bits = Number(img.bits ?? 8); const src = img.data; const pixelCount = width * height; - const needed = pixelCount * colors * (bits > 8 ? 2 : 1); - if (src.length < needed) { - throw new Error(`LibRaw buffer too small (${src.length} bytes for ${width}×${height}×${colors})`); + const needed = pixelCount * colors; + // libraw-wasm hands back samples, not bytes: with outputBps 16 the buffer is a + // Uint16Array already. Older builds returned the raw 16-bit bytes, so accept + // both shapes instead of assuming one and rejecting every 16-bit decode. + const wide = + bits > 8 && !(src instanceof Uint16Array) + ? new Uint16Array(src.buffer, src.byteOffset, Math.floor(src.byteLength / 2)) + : src; + if (wide.length < needed) { + throw new Error( + `LibRaw buffer too small (${wide.length} samples for ${width}×${height}×${colors})`, + ); } const rgb = Buffer.alloc(pixelCount * 3); + let rgb16 = null; if (bits > 8) { - const view = new Uint16Array(src.buffer, src.byteOffset, Math.floor(src.byteLength / 2)); + const view = wide instanceof Uint16Array ? wide : src; + rgb16 = new Uint16Array(pixelCount * 3); for (let i = 0; i < pixelCount; i++) { const s = i * colors; - rgb[i * 3] = view[s] >> 8; - rgb[i * 3 + 1] = view[s + 1] >> 8; - rgb[i * 3 + 2] = view[s + 2] >> 8; + const r = view[s]; + const g = view[s + 1]; + const b = view[s + 2]; + rgb[i * 3] = r >> 8; + rgb[i * 3 + 1] = g >> 8; + rgb[i * 3 + 2] = b >> 8; + rgb16[i * 3] = r; + rgb16[i * 3 + 1] = g; + rgb16[i * 3 + 2] = b; } } else { for (let i = 0; i < pixelCount; i++) { @@ -101,20 +138,29 @@ function toRgb(img) { rgb[i * 3 + 2] = src[s + 2]; } } - return { rgb, width, height }; + return { rgb, rgb16, width, height }; } /** * Full demosaic through a pooled LibRaw worker. `open()` only unpacks the file; * the pixels come from `imageData()`, which rejects when the camera is unsupported. + * + * `cameraNative` asks for the frame before LibRaw's output matrix, plus the + * matrix metadata. A body LibRaw has no matrix for falls back to the plain sRGB + * decode, which is the same result the pipeline produced before. */ -async function demosaic(buffer) { +async function demosaic(buffer, cameraNative = true) { if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed'); return rawPool.use(async (lib) => { // LibRaw transfers the buffer to its worker, which detaches it here. Hand it // a copy so the caller's bytes survive for the embedded-preview fallback. - await lib.open(Buffer.from(buffer), DECODE_SETTINGS); - return toRgb(await lib.imageData()); + await lib.open( + Buffer.from(buffer), + cameraNative ? DECODE_SETTINGS : { ...DECODE_SETTINGS, outputColor: 1, noAutoBright: false }, + ); + const image = toRgb(await lib.imageData()); + const rgbCam = cameraNative ? readRgbCam(await lib.metadata(true)) : null; + return { ...image, rgbCam }; }); } @@ -163,10 +209,38 @@ export async function decodeRaw(buffer) { let librawError = null; if (looksLikeRaw(buffer)) { try { - const { rgb, width, height } = await demosaic(buffer); + let frame = await demosaic(buffer, true); + // No usable matrix (an odd body or older engine): decode the familiar sRGB + // way instead of shipping camera samples nobody can convert. + if (!frame.rgbCam || !frame.rgb16) frame = await demosaic(buffer, false); + const { width, height, rgbCam } = frame; + // Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and + // `rgb16` the camera-native sidecar, sharing one white point. + if (rgbCam && frame.rgb16) cameraToProxy(frame.rgb16, frame.rgb, rgbCam); + const { rgb } = frame; const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE); + // The sidecar must match the JPEG pixel for pixel: the editor swaps the + // two textures at the same uv, so a size disagreement would misalign the + // whole grade. It is optional -- encoding failures leave the JPEG path. + let preview16 = null; + if (frame.rgb16 && RAW_16BIT) { + try { + const scaled = resizeRgb16(frame.rgb16, width, height, encoded.width, encoded.height); + preview16 = { + // The matrix travels with the samples so the editor knows how to + // turn camera RGB into sRGB without a second metadata fetch. + data: encodePng16(scaled, encoded.width, encoded.height, rgbCam), + width: encoded.width, + height: encoded.height, + rgbCam, + }; + } catch { + preview16 = null; + } + } return { jpeg: encoded.data, + preview16, width: encoded.width, height: encoded.height, engine: 'libraw', diff --git a/server/storage.mjs b/server/storage.mjs index 421afe8..3db4c5f 100644 --- a/server/storage.mjs +++ b/server/storage.mjs @@ -117,6 +117,30 @@ export function findPreview(id) { return null; } +/** + * The 16-bit sidecar for a raw proxy: the samples LibRaw decoded, before the + * JPEG quantised them. Its name keeps a second extension so `findPreview` keeps + * returning the JPEG for browsers and for photos imported before this existed. + */ +export async function writePreview16(id, data) { + ensureDirs(); + const target = path.join(storageRoot(), 'previews', `${safeId(id)}.p16.png`); + await fsp.writeFile(target, data); + return target; +} + +export function findPreview16(id) { + const safe = lookupId(id); + if (!safe) return null; + const p = path.join(dirs().previews, `${safe}.p16.png`); + return fs.existsSync(p) ? p : null; +} + +export async function removePreview16(id) { + const found = findPreview16(id); + if (found) await fsp.rm(found, { force: true }); +} + /** * Denoised proxies, keyed by the hash of the parameters that produced them, so * switching Amount back to a previous value reuses the file instead of spending @@ -209,6 +233,7 @@ export async function removeAsset(id) { const files = [ findOriginal(id), findPreview(id), + findPreview16(id), findThumb(id), findProof(id), findProofThumb(id), diff --git a/src/App.tsx b/src/App.tsx index 6c65966..f06eb74 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -15,6 +15,12 @@ import MergeModal from './components/MergeModal'; import PasteSettingsModal from './components/PasteSettingsModal'; import PrintModal from './components/PrintModal'; import ShareModal from './components/ShareModal'; +import RawReprocessModal, { + type RawReprocessFailure, + type RawReprocessJob, +} from './components/RawReprocessModal'; +import CullAssistModal from './components/CullAssistModal'; +import TetherPanel from './components/TetherPanel'; import Shortcuts from './components/Shortcuts'; import Stars, { ColorSwatches, FlagButtons } from './components/Stars'; import TopBar from './components/TopBar'; @@ -37,6 +43,7 @@ import { pushImmichPhoto, pushPhoto, register as apiRegister, + reprocessRawPhoto, uploadOriginal, } from './lib/api'; import type { Health, ImmichStatus, ProofSummary, QuotaState, SessionUser } from './lib/api'; @@ -58,8 +65,9 @@ import { COLOR_LABELS, defaultEdits, isEdited, normalizePhoto } from './lib/edit import { applyEditSections, type EditSectionId } from './lib/editSections'; import type { MergeResult } from './lib/merge'; import { evictBitmap } from './lib/images'; -import { uid } from './lib/import'; +import { importFiles, uid } from './lib/import'; import { PRESETS } from './lib/presets'; +import { downloadXmp, readXmpFile, xmpToEdits } from './lib/xmp'; import type { Edits, EventRecord, @@ -185,6 +193,12 @@ export default function App() { const [exportOptions, setExportOptions] = useState(DEFAULT_EXPORT); const [exportRecipes, setExportRecipes] = useState([]); const [mergeOpen, setMergeOpen] = useState(false); + const [rawJob, setRawJob] = useState(null); + const [cullOpen, setCullOpen] = useState(false); + const [tetherEventId, setTetherEventId] = useState(null); + const rawBusyRef = useRef(false); + const rawCancelRef = useRef(false); + const rawBusy = Boolean(rawJob?.running); const [printOpen, setPrintOpen] = useState(false); const saveTimers = useRef(new Map>()); @@ -363,6 +377,151 @@ export default function App() { [queueSave], ); + /** + * Re-decode selected RAW files on the server, then refresh the cached proxy so + * the grid and Develop pick up the new pixels without a reload. Existing edits + * are kept; only width, height and the decode engine change on the record. + */ + const reprocessRawPhotos = useCallback( + async (ids: string[], options: { eventName?: string } = {}) => { + if (rawBusyRef.current) { + setToast('A RAW reprocess is already running'); + return; + } + const targets = photosRef.current.filter( + (photo) => ids.includes(photo.id) && photo.raw && !photo.deletedAt, + ); + if (!targets.length) { + setToast('Select RAW photos to reprocess'); + return; + } + if (!userRef.current) { + setToast('Sign in to the server to reprocess RAW files'); + return; + } + rawBusyRef.current = true; + rawCancelRef.current = false; + const failures: RawReprocessFailure[] = []; + let attempts = 0; + setRawJob({ + running: true, + done: 0, + total: targets.length, + current: targets[0].name, + eventName: options.eventName, + failures: [], + }); + try { + for (let index = 0; index < targets.length; index += 1) { + if (rawCancelRef.current) break; + const photo = targets[index]; + setRawJob((prev) => + prev ? { ...prev, done: index, current: photo.name, failures: failures.slice() } : prev, + ); + try { + const result = await reprocessRawPhoto(photo.id); + const res = await fetch( + `/api/photos/${encodeURIComponent(photo.id)}/preview?v=${Date.now()}`, + { credentials: 'same-origin' }, + ); + if (!res.ok) throw new Error('The new preview could not be read'); + const blob = await res.blob(); + // Replace the cached proxy, then drop the decoded bitmap so the next + // render fetches the new pixels instead of the old ones. + await putAsset(photo.id, blob); + evictBitmap(photo.id); + const version = result.previewVersion ?? Date.now(); + updatePhoto(photo.id, { + width: result.width || photo.width, + height: result.height || photo.height, + decode: result.engine ?? photo.decode, + previewVersion: version, + // The stored files keep their names; the query is only a cache buster. + previewUrl: + result.previewUrl ?? + `/api/photos/${encodeURIComponent(photo.id)}/preview?v=${version}`, + thumbUrl: + result.thumbUrl ?? + `/api/photos/${encodeURIComponent(photo.id)}/thumb?v=${version}`, + }); + attempts += 1; + } catch (err) { + failures.push({ + name: photo.name, + error: err instanceof Error ? err.message : 'could not be reprocessed', + }); + } + setRawJob((prev) => + prev + ? { ...prev, done: index + 1, failures: failures.slice() } + : prev, + ); + } + } finally { + rawBusyRef.current = false; + setRawJob((prev) => + prev + ? { + ...prev, + running: false, + done: attempts, + failures: failures.slice(), + cancelled: rawCancelRef.current, + } + : prev, + ); + } + const succeeded = attempts - failures.length; + const parts = [ + `Reprocessed ${succeeded} of ${targets.length} RAW${targets.length === 1 ? '' : 's'}`, + ]; + if (failures.length) parts.push(`${failures.length} failed`); + if (rawCancelRef.current) parts.push('cancelled'); + setToast(parts.join(' · ')); + }, + [updatePhoto], + ); + + /** Reprocess every RAW file in one event, with a confirmation that names it. */ + const reprocessEventRaws = useCallback( + (id: string) => { + const event = eventsRef.current.find((item) => item.id === id); + if (!event) return; + const raws = photosRef.current.filter( + (photo) => photo.eventId === id && photo.raw && !photo.deletedAt, + ); + if (!raws.length) { + setToast('This event has no RAW photos'); + return; + } + if (!userRef.current) { + setToast('Sign in to the server to reprocess RAW files'); + return; + } + if (rawBusyRef.current) { + setToast('A RAW reprocess is already running'); + return; + } + const ok = window.confirm( + `Re-decode ${raws.length} RAW file${raws.length === 1 ? '' : 's'} in “${event.name}”? ` + + 'Existing edits and crops are kept.', + ); + if (!ok) return; + void reprocessRawPhotos(raws.map((photo) => photo.id), { eventName: event.name }); + }, + [reprocessRawPhotos], + ); + + /** Auto-sync in Develop: merge the same patch into every selected photo. */ + const updatePhotoEdits = useCallback( + (ids: string[], patch: Partial, historyLabel?: string) => { + for (const id of ids) { + updatePhoto(id, (p) => ({ edits: { ...p.edits, ...patch } }), historyLabel); + } + }, + [updatePhoto], + ); + const bulkUpdate = useCallback( (ids: string[], patch: Partial) => { if (!ids.length) return; @@ -868,7 +1027,9 @@ export default function App() { const savePreset = useCallback( (name: string, edits: Edits) => { - const { crop: _crop, ...withoutCrop } = edits; + // Crop and the camera profile are properties of this photo, not a look: + // copying either onto another body would be wrong. + const { crop: _crop, cameraProfile: _cameraProfile, ...withoutCrop } = edits; const preset: Preset = { id: uid(), name, @@ -887,6 +1048,19 @@ export default function App() { [customPresets], ); + const deletePreset = useCallback( + (id: string) => { + const next = customPresets.filter((preset) => preset.id !== id); + setCustomPresets(next); + setKV('customPresets', next).catch((err) => console.error(err)); + if (userRef.current) { + import('./lib/api').then(({ pushPresets }) => pushPresets(next).catch(() => undefined)); + } + setToast('Preset deleted'); + }, + [customPresets], + ); + /* ------------------------------------------------------------- reordering */ const reorderPhotos = useCallback( @@ -1477,6 +1651,40 @@ export default function App() { setToast(message); }, []); + /** + * Manual publish for an event that has no Immich gallery yet: create the + * album, link it to the event, then push originals and current edits. + */ + const publishEventToImmich = useCallback( + async (targetEventId: string) => { + const event = eventsRef.current.find((item) => item.id === targetEventId); + if (!event) return; + if (!immichStatusRef.current?.enabled) { + setToast('Turn on Immich in the Immich sync panel first'); + return; + } + if (event.immich) { + await syncEventGallery(targetEventId); + return; + } + try { + await createImmichGalleryForEvent(targetEventId); + } catch (err) { + setToast(err instanceof Error ? err.message : 'Could not create the Immich gallery'); + return; + } + const count = photosRef.current.filter( + (photo) => photo.eventId === targetEventId && !photo.deletedAt, + ).length; + if (!count) { + setToast(`Immich gallery created for ${event.name} — import photos to fill it`); + return; + } + await syncEventGallery(targetEventId); + }, + [createImmichGalleryForEvent, syncEventGallery], + ); + const openImmichAsset = useCallback((photo: PhotoRecord) => { const status = immichStatusRef.current; if (!status?.url || !photo.immich) return; @@ -1854,7 +2062,94 @@ export default function App() { ? 'Unsorted' : events.find((e) => e.id === eventId)?.name ?? 'All photos'; + const tetherImport = useCallback( + async (files: File[]) => { + if (!tetherEventId) return 0; + const result = await importFiles( + files, + tetherEventId, + [], + undefined, + cloudUser ? { uploadOriginal, push: pushPhoto } : null, + ); + if (result.photos.length) { + const tagged = result.photos.map((photo) => + cloudUser ? { ...photo, workspace: cloudUser.id } : photo, + ); + setPhotos((prev) => [...tagged, ...prev]); + } + return result.photos.length; + }, + [cloudUser, tetherEventId], + ); + + const importSidecar = useCallback(async () => { + if (selected.length !== 1) { + setToast('Select exactly one photo to import a sidecar into'); + return; + } + const target = photos.find((photo) => photo.id === selected[0]); + if (!target) return; + try { + const xml = await readXmpFile(); + if (!xml) return; + const result = xmpToEdits(xml, target.edits); + updatePhoto(target.id, { edits: result.edits }, 'Import XMP sidecar'); + setToast( + result.source === 'luminary' + ? 'Imported Luminary settings from the sidecar' + : `Imported ${result.applied.length} Lightroom setting${result.applied.length === 1 ? '' : 's'}`, + ); + } catch (err) { + setToast(err instanceof Error ? err.message : 'Could not import the sidecar'); + } + }, [photos, selected, updatePhoto]); + const paletteActions = [ + { + id: 'xmp-export', + label: 'Export XMP sidecar for the selection', + hint: 'Sidecar', + run: () => { + const chosen = photos.filter((photo) => selected.includes(photo.id)); + if (!chosen.length) { + setToast('Select photos to export sidecars for'); + return; + } + for (const photo of chosen) downloadXmp(photo); + setToast(`Exported ${chosen.length} sidecar${chosen.length === 1 ? '' : 's'}`); + }, + }, + { + id: 'xmp-import', + label: 'Import XMP sidecar into the selected photo', + hint: 'Sidecar', + run: () => void importSidecar(), + }, + { + id: 'tether', + label: 'Tether this event from a watch folder', + hint: 'Capture', + run: () => { + if (eventId === 'all' || eventId === 'unsorted') { + setToast('Open an event to tether into it'); + return; + } + setTetherEventId(eventId); + }, + }, + { + id: 'cull-assist', + label: 'Cull assist for the selection', + hint: 'Focus', + run: () => { + if (!selected.length) { + setToast('Select photos to cull'); + return; + } + setCullOpen(true); + }, + }, { id: 'import', label: 'Import photos', @@ -1889,6 +2184,29 @@ export default function App() { run: () => setFilters(EMPTY_FILTERS), }, { id: 'shortcuts', label: 'Show keyboard shortcuts', hint: '?', run: () => setHelpOpen(true) }, + ...(cloudUser && + eventId !== 'all' && + eventId !== 'unsorted' && + photos.some((photo) => photo.eventId === eventId && photo.raw && !photo.deletedAt) + ? [ + { + id: 'reprocess-event-raws', + label: 'Reprocess all RAW photos in this event', + hint: 'RAW', + run: () => reprocessEventRaws(eventId), + }, + ] + : []), + ...(cloudUser && immichStatus?.enabled && eventId !== 'all' && eventId !== 'unsorted' + ? [ + { + id: 'immich-publish', + label: 'Publish this event to Immich', + hint: 'Immich', + run: () => void publishEventToImmich(eventId), + }, + ] + : []), ...(cloudUser && eventId !== 'all' && eventId !== 'unsorted' ? [{ id: 'share', label: 'Open client proofing', hint: 'Share', run: () => setShareEventId(eventId) }] : []), @@ -2010,6 +2328,9 @@ export default function App() { await createEvent(name, { immichGallery }); }} onSyncGallery={syncEventGallery} + onPublishGallery={publishEventToImmich} + canReprocessRaw={Boolean(cloudUser)} + onReprocessEvent={reprocessEventRaws} onRename={renameEvent} onDelete={removeEvent} onReorderEvents={reorderEvents} @@ -2117,6 +2438,12 @@ export default function App() { : undefined } immichBusy={Boolean(immichProgress)} + onReprocessRaw={ + cloudUser && selected.some((id) => photos.find((photo) => photo.id === id)?.raw) + ? () => void reprocessRawPhotos(selected) + : undefined + } + reprocessBusy={rawBusy} onDelete={() => (trashOpen ? void removePhotos(selected) : trashPhotos(selected))} onExport={openExport} onCompare={() => setCompareOpen(true)} @@ -2154,6 +2481,7 @@ export default function App() { onSelect={setActiveId} onExit={() => setView('grid')} onUpdate={updatePhoto} + onUpdateEdits={updatePhotoEdits} clipboard={clipboard} onCopy={copySettings} onCopyOf={copySettingsOf} @@ -2170,6 +2498,7 @@ export default function App() { } presets={[...PRESETS, ...customPresets]} onSavePreset={savePreset} + onDeletePreset={deletePreset} onDelete={() => trashPhotos([activePhoto.id])} onVirtualCopy={() => void createVirtualCopy(activePhoto.id, true)} metadataPresets={metadataPresets} @@ -2489,6 +2818,36 @@ export default function App() { )} + {tetherEventId && ( + e.id === tetherEventId)?.name ?? 'this event', + }} + onImport={tetherImport} + onClose={() => setTetherEventId(null)} + /> + )} + + {cullOpen && ( + selected.includes(photo.id))} + onReject={(ids) => bulkUpdate(ids, { flag: 'reject' })} + onClose={() => setCullOpen(false)} + /> + )} + + {rawJob && ( + { + rawCancelRef.current = true; + setRawJob((prev) => (prev ? { ...prev, cancelled: true } : prev)); + }} + onClose={() => setRawJob(null)} + /> + )} + {toast && (
{toast} diff --git a/src/components/CullAssistModal.tsx b/src/components/CullAssistModal.tsx new file mode 100644 index 0000000..0914dfa --- /dev/null +++ b/src/components/CullAssistModal.tsx @@ -0,0 +1,248 @@ +import { useEffect, useMemo, useState } from 'react'; +import { analyseGrey, greyFromPixels, groupDuplicates, sharpnessGrade } from '../lib/cull'; +import type { CullStats } from '../lib/cull'; +import type { PhotoRecord } from '../types'; + +interface Row { + photo: PhotoRecord; + stats: CullStats | null; + error?: string; +} + +interface Props { + photos: PhotoRecord[]; + onReject: (ids: string[]) => void; + onClose: () => void; +} + +const THUMB_EDGE = 96; + +async function statsFor(photo: PhotoRecord): Promise { + const src = photo.thumbUrl ?? photo.thumb; + const image = new Image(); + image.decoding = 'async'; + await new Promise((resolve, reject) => { + image.onload = () => resolve(); + image.onerror = () => reject(new Error('Could not read the thumbnail')); + image.src = src; + }); + const width = THUMB_EDGE; + const height = Math.max(24, Math.round((width * image.naturalHeight) / Math.max(1, image.naturalWidth))); + const canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + const ctx = canvas.getContext('2d', { willReadFrequently: true }); + if (!ctx) throw new Error('Could not analyse the thumbnail'); + ctx.drawImage(image, 0, 0, width, height); + return analyseGrey(greyFromPixels(ctx.getImageData(0, 0, width, height).data), width, height); +} + +/** + * Focus and duplicate pass over a selection, run on the thumbnails the grid + * already loaded. It never edits or rates anything by itself: the owner sees + * the scores and chooses what to reject. + */ +export default function CullAssistModal({ photos, onReject, onClose }: Props) { + const [rows, setRows] = useState([]); + const [done, setDone] = useState(0); + const [running, setRunning] = useState(true); + const [current, setCurrent] = useState(''); + const [threshold, setThreshold] = useState(22); + + useEffect(() => { + let cancelled = false; + const next: Row[] = photos.map((photo) => ({ photo, stats: null })); + setRows(next.map((row) => ({ ...row }))); + setDone(0); + setRunning(true); + + void (async () => { + for (let i = 0; i < next.length; i++) { + if (cancelled) return; + setCurrent(next[i].photo.name); + try { + next[i] = { ...next[i], stats: await statsFor(next[i].photo) }; + } catch (err) { + next[i] = { + ...next[i], + error: err instanceof Error ? err.message : 'Analysis failed', + }; + } + if (cancelled) return; + setRows(next.map((row) => ({ ...row }))); + setDone(i + 1); + } + if (!cancelled) { + setRunning(false); + setCurrent(''); + } + })(); + + return () => { + cancelled = true; + }; + }, [photos]); + + const analysed = rows.filter((row) => row.stats); + const soft = analysed.filter((row) => (row.stats?.sharpness ?? 100) < threshold); + const duplicates = useMemo( + () => + groupDuplicates( + analysed.map((row) => ({ ...row, hash: row.stats?.hash ?? '' })), + 9, + ), + [analysed], + ); + const duplicateRejects = useMemo(() => { + const ids: string[] = []; + for (const group of duplicates) { + // Keep the sharpest frame of the burst; everything close to it is the + // alternative the photographer would otherwise have to compare by eye. + const sorted = [...group].sort( + (a, b) => (b.stats?.sharpness ?? 0) - (a.stats?.sharpness ?? 0), + ); + for (const row of sorted.slice(1)) ids.push(row.photo.id); + } + return ids; + }, [duplicates]); + + const pct = photos.length ? Math.round((done / photos.length) * 100) : 0; + + return ( +
e.target === e.currentTarget && !running && onClose()} + > +
+
+
+

Cull assist

+

+ Focus and duplicate checks on {photos.length} photo{photos.length === 1 ? '' : 's'}. + Nothing is rated or rejected without your say-so. +

+
+ {!running && ( + + )} +
+ +
+ {running && ( + <> +
+
+
+

+ {done} of {photos.length} + {current ? ` · ${current}` : '…'} +

+ + )} + + {!running && ( + <> +
+
+ {soft.length} + soft under {threshold} +
+
+ {duplicates.length} + duplicate set{duplicates.length === 1 ? '' : 's'} +
+
+ {analysed.length} + analysed +
+
+ + + +
    + {[...analysed] + .sort((a, b) => (a.stats?.sharpness ?? 0) - (b.stats?.sharpness ?? 0)) + .slice(0, 60) + .map((row) => { + const stats = row.stats as CullStats; + const grade = sharpnessGrade(stats.sharpness); + return ( +
  • + + {row.photo.name} + + {grade} + {stats.sharpness} + + {stats.clippedHigh > 0.08 + ? 'highlights clipped' + : stats.clippedLow > 0.12 + ? 'crushed shadows' + : stats.mean < 30 + ? 'very dark' + : ''} + +
  • + ); + })} +
+ {analysed.length > 60 && ( +

Showing the 60 softest frames.

+ )} + + )} +
+ +
+ + Scores come from the thumbnails, so treat them as a first pass. + + {running ? ( + + ) : ( + <> + + + + + )} +
+
+
+ ); +} diff --git a/src/components/CurveEditor.tsx b/src/components/CurveEditor.tsx index 2db1ad2..5d3a0b9 100644 --- a/src/components/CurveEditor.tsx +++ b/src/components/CurveEditor.tsx @@ -2,16 +2,33 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { buildSampler, clamp01 } from '../lib/curves'; import type { CurvePoint } from '../types'; +export type ParametricKey = 'highlights' | 'lights' | 'darks' | 'blacks'; + interface Props { points: CurvePoint[]; onChange: (points: CurvePoint[]) => void; color: string; + /** Region tone shaper values, shown as draggable dots on the curve. */ + parametric?: Record; + onParametric?: (key: ParametricKey, value: number) => void; } -export default function CurveEditor({ points, onChange, color }: Props) { +/** Lightroom-scale zones: the four regions share the diagonal evenly. */ +const ZONES: { key: ParametricKey; label: string; x: number }[] = [ + { key: 'highlights', label: 'Highlights', x: 0.875 }, + { key: 'lights', label: 'Lights', x: 0.625 }, + { key: 'darks', label: 'Darks', x: 0.375 }, + { key: 'blacks', label: 'Blacks', x: 0.125 }, +]; + +/** Full slider travel moves a zone dot a quarter of the graph. */ +const ZONE_TRAVEL = 0.18; + +export default function CurveEditor({ points, onChange, color, parametric, onParametric }: Props) { const svgRef = useRef(null); const pointsRef = useRef(points); const [drag, setDrag] = useState(null); + const [paramDrag, setParamDrag] = useState(null); const [hover, setHover] = useState(null); useEffect(() => { @@ -42,6 +59,12 @@ export default function CurveEditor({ points, onChange, color }: Props) { const handleDown = (e: React.PointerEvent) => { e.preventDefault(); + const paramAttr = (e.target as Element).getAttribute('data-param'); + if (paramAttr && parametric && onParametric) { + setParamDrag(paramAttr as ParametricKey); + e.currentTarget.setPointerCapture(e.pointerId); + return; + } const idxAttr = (e.target as Element).getAttribute('data-idx'); let idx: number; if (idxAttr !== null) { @@ -57,6 +80,15 @@ export default function CurveEditor({ points, onChange, color }: Props) { }; const handleMove = (e: React.PointerEvent) => { + if (paramDrag && parametric && onParametric) { + const zone = ZONES.find((item) => item.key === paramDrag); + if (!zone) return; + const p = toNorm(e.clientX, e.clientY); + const base = sampler(zone.x); + const value = ((p.y - base) / ZONE_TRAVEL) * 100; + onParametric(paramDrag, Math.round(Math.max(-100, Math.min(100, value)))); + return; + } if (drag === null) return; const pts = pointsRef.current; const idx = drag; @@ -68,7 +100,10 @@ export default function CurveEditor({ points, onChange, color }: Props) { onChange(next); }; - const handleUp = () => setDrag(null); + const handleUp = () => { + setDrag(null); + setParamDrag(null); + }; const removePoint = (idx: number) => { const pts = pointsRef.current; @@ -101,6 +136,37 @@ export default function CurveEditor({ points, onChange, color }: Props) { ))} + {parametric && + onParametric && + ZONES.map((zone) => { + const value = parametric[zone.key] ?? 0; + const y = clamp01(sampler(zone.x) + (value / 100) * ZONE_TRAVEL); + return ( + + + + {`${zone.label}: ${value > 0 ? '+' : ''}${value}`} + + + ); + })} {points.map((p, i) => ( ))} -
Click to add a point · drag to shape · double-click a point to remove
+
+ Click to add a point · drag to shape · drag the four gold dots for highlights, lights, darks and blacks +
); } diff --git a/src/components/Develop.tsx b/src/components/Develop.tsx index cffa640..48f4f6c 100644 --- a/src/components/Develop.tsx +++ b/src/components/Develop.tsx @@ -7,7 +7,8 @@ import { MAX_LOCAL_LAYERS, } from '../lib/edits'; import { subscribeClipPreview } from '../lib/clipPreview'; -import { getBitmap, getDenoisedBitmap } from '../lib/images'; +import { get16BitSource, getBitmap, getDenoisedBitmap } from '../lib/images'; +import type { Preview16 } from '../lib/preview16'; import { useMediaQuery } from '../lib/useMediaQuery'; import { usePersistentState } from '../lib/usePersistentState'; import { solveWhiteBalance } from '../lib/whiteBalance'; @@ -59,6 +60,7 @@ import { OpticsPanel, PresetsPanel, ProofPanel, + CameraProfilePanel, SnapshotsPanel, } from './Panels'; import Stars, { ColorSwatches, FlagButtons } from './Stars'; @@ -121,6 +123,8 @@ interface Props { onSelect: (id: string) => void; onExit: () => void; onUpdate: (id: string, patch: Partial, historyLabel?: string) => void; + /** Auto-sync: merge a patch into several photos' own edits at once. */ + onUpdateEdits?: (ids: string[], patch: Partial, historyLabel?: string) => void; clipboard: Edits | null; onCopy: () => void; /** Copy settings from a named filmstrip photo instead of the canvas photo. */ @@ -138,6 +142,7 @@ interface Props { onOpenImmich?: () => void; presets: Preset[]; onSavePreset: (name: string, edits: Edits) => void; + onDeletePreset: (id: string) => void; onDelete: () => void; onVirtualCopy: () => void; metadataPresets: MetadataPreset[]; @@ -156,6 +161,7 @@ export default function Develop({ onSelect, onExit, onUpdate, + onUpdateEdits, clipboard, onCopy, onCopyOf, @@ -170,6 +176,7 @@ export default function Develop({ onOpenImmich, presets, onSavePreset, + onDeletePreset, onDelete, onVirtualCopy, metadataPresets, @@ -189,7 +196,10 @@ export default function Develop({ const panRef = useRef<{ x: number; y: number; cx: number; cy: number } | null>(null); const [bitmap, setBitmap] = useState(null); + const [hdrSource, setHdrSource] = useState(null); const [denoisedBitmap, setDenoisedBitmap] = useState(null); + /** Name of the printer ICC profile loaded for this session, if any. */ + const [proofProfile, setProofProfile] = useState(null); const [stage, setStage] = useState({ w: 0, h: 0 }); const [cropMode, setCropMode] = useState(false); const [cropDrag, setCropDrag] = useState(false); @@ -214,6 +224,7 @@ export default function Develop({ const [filmSel, setFilmSel] = useState([photo.id]); const [filmAnchor, setFilmAnchor] = useState(photo.id); const [showOriginal, setShowOriginal] = useState(false); + const [autoSync, setAutoSync] = usePersistentState('develop.autosync', false); const [histVersion, setHistVersion] = useState(0); const [error, setError] = useState(null); const [loading, setLoading] = useState(true); @@ -232,6 +243,7 @@ export default function Develop({ ids?: string[]; } | null>(null); const [healMode, setHealMode] = useState(false); + const [rangePicking, setRangePicking] = useState(false); const [brushPx, setBrushPx] = useState(56); const [healFeather, setHealFeather] = useState(50); const [healSelected, setHealSelected] = useState(null); @@ -340,9 +352,17 @@ export default function Develop({ const setEdits = useCallback( (patch: Partial, label: string) => { + // Auto-sync applies only the changed controls to the rest of the + // filmstrip, so each photo keeps its own untouched settings, crop and + // masks. The canvas photo is always updated last so the preview follows + // the slider that was actually moved. + if (autoSync && filmSel.length > 1 && onUpdateEdits) { + const others = filmSel.filter((id) => id !== photo.id); + if (others.length) onUpdateEdits(others, patch, label); + } onUpdate(photo.id, { edits: { ...photo.edits, ...patch } }, label); }, - [onUpdate, photo.id, photo.edits], + [autoSync, filmSel, onUpdate, onUpdateEdits, photo.id, photo.edits], ); useEffect(() => { @@ -399,6 +419,14 @@ export default function Develop({ useEffect(() => { let alive = true; setLoading(true); + // The 16-bit sidecar is optional and can be tens of megabytes, so it loads + // behind the JPEG and simply swaps the source texture when it lands. + setHdrSource(null); + get16BitSource(photo) + .then((hdr) => { + if (alive) setHdrSource(hdr); + }) + .catch(() => undefined); getBitmap(photo) .then((bmp) => { if (!alive) return; @@ -508,22 +536,14 @@ export default function Develop({ let cssH = Math.max(40, Math.round(contentH * fitScale)); if (zoomFactor > 1.0001) { - // The visible window keeps the stage's aspect, so the canvas is stage sized - // and the shader maps it onto a sub-rect of the frame. Cost stays constant - // no matter how far you zoom, and detail comes from the source bitmap. - const vw = Math.min(1, availW / (fitScale * zoomFactor) / frame.w); - const vh = Math.min(1, availH / (fitScale * zoomFactor) / frame.h); - const cx = - vw >= content.w - ? content.x + content.w / 2 - : clampNum(zoom.cx, content.x + vw / 2, content.x + content.w - vw / 2); - const cy = - vh >= content.h - ? content.y + content.h / 2 - : clampNum(zoom.cy, content.y + vh / 2, content.y + content.h - vh / 2); + // The canvas keeps the photo's fit-sized box while zooming and the window + // shrinks inside the crop at the same aspect. Growing the canvas to the + // stage's shape instead stretched any photo whose aspect differed from it. + const vw = content.w / zoomFactor; + const vh = content.h / zoomFactor; + const cx = clampNum(zoom.cx, content.x + vw / 2, content.x + content.w - vw / 2); + const cy = clampNum(zoom.cy, content.y + vh / 2, content.y + content.h - vh / 2); view = { x: cx - vw / 2, y: cy - vh / 2, w: vw, h: vh }; - cssW = Math.round(availW); - cssH = Math.round(availH); } const dpr = Math.min(window.devicePixelRatio || 1, 2); @@ -555,7 +575,7 @@ export default function Develop({ ); try { - renderer.setImage(bitmap); + renderer.setImage(bitmap, hdrSource); // "Show original" must show the untouched source, not the cleaned proxy. renderer.setDenoised(showOriginal ? null : denoisedBitmap, activeEdits.aiDenoise.amount / 100); renderer.render(activeEdits, { @@ -583,6 +603,7 @@ export default function Develop({ } }, [ bitmap, + hdrSource, denoisedBitmap, edits, cropMode, @@ -595,6 +616,9 @@ export default function Develop({ lensCorrection, lensSplit, lensSplitAt, + // Loading or clearing a printer profile changes the finish pass, and the + // cube lives outside the edit record, so the redraw is keyed on it here. + proofProfile, ]); useEffect(() => { @@ -634,11 +658,11 @@ export default function Develop({ } } - const vw = geo.availW / (geo.fitScale * zNext) / geo.frameW; - const vh = geo.availH / (geo.fitScale * zNext) / geo.frameH; const c = geo.content; - cx = vw >= c.w ? c.x + c.w / 2 : clampNum(cx, c.x + vw / 2, c.x + c.w - vw / 2); - cy = vh >= c.h ? c.y + c.h / 2 : clampNum(cy, c.y + vh / 2, c.y + c.h - vh / 2); + const vw = c.w / zNext; + const vh = c.h / zNext; + cx = clampNum(cx, c.x + vw / 2, c.x + c.w - vw / 2); + cy = clampNum(cy, c.y + vh / 2, c.y + c.h - vh / 2); setZoom({ pct: next, cx, cy }); }, []); @@ -653,16 +677,10 @@ export default function Develop({ const pct = zoom.pct === 'fit' ? 100 : zoom.pct; const z = Math.max(1, pct / geo.fitPct); const c = geo.content; - const vw = Math.min(c.w, geo.availW / (geo.fitScale * z) / geo.frameW); - const vh = Math.min(c.h, geo.availH / (geo.fitScale * z) / geo.frameH); - const cx = - vw >= c.w - ? c.x + c.w / 2 - : clampNum(fx, c.x + vw / 2, c.x + c.w - vw / 2); - const cy = - vh >= c.h - ? c.y + c.h / 2 - : clampNum(fy, c.y + vh / 2, c.y + c.h - vh / 2); + const vw = c.w / z; + const vh = c.h / z; + const cx = clampNum(fx, c.x + vw / 2, c.x + c.w - vw / 2); + const cy = clampNum(fy, c.y + vh / 2, c.y + c.h - vh / 2); setZoom({ pct, cx, cy }); }, [zoom.pct], @@ -717,7 +735,7 @@ export default function Develop({ }, [cropMode, applyZoom, healMode, localMode, activeLocal]); const beginPan = (e: React.PointerEvent) => { - if (picking || cropMode || healMode || localMode || !zoomed || e.button !== 0) return; + if (picking || rangePicking || cropMode || healMode || localMode || !zoomed || e.button !== 0) return; const geo = geoRef.current; panRef.current = { x: e.clientX, @@ -1007,6 +1025,58 @@ export default function Develop({ [autoMaskBusy, bitmap, commitLocal, edits.local, photo], ); + /** + * Colour-range sampler: read the untouched source colour under the pointer and + * shape the active mask's range around its hue, saturation and luma. The same + * source colour the mask range compares against, so the result lines up even + * under a heavy grade. + */ + const pickRangeColour = (e: React.MouseEvent) => { + if (!rangePicking || !activeLocal) return; + const canvas = canvasRef.current; + const renderer = rendererRef.current; + if (!canvas || !renderer) return; + const rect = canvas.getBoundingClientRect(); + if (!rect.width || !rect.height) return; + const geo = geoRef.current; + const sample = renderer.pickSource(edits, { + nx: clampNum((e.clientX - rect.left) / rect.width, 0, 1), + ny: clampNum((e.clientY - rect.top) / rect.height, 0, 1), + view: geo.zoomFactor > 1.0001 ? geo.view : undefined, + upscale: Math.min(window.devicePixelRatio || 1, 2) * geo.fitScale * geo.zoomFactor > 1.1, + }); + setRangePicking(false); + if (!sample) return; + const [r, g, b] = sample; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const delta = max - min; + let hue = 0; + if (delta > 1e-6) { + if (max === r) hue = ((g - b) / delta) % 6; + else if (max === g) hue = (b - r) / delta + 2; + else hue = (r - g) / delta + 4; + hue = (hue * 60 + 360) % 360; + } + const sat = max > 0 ? delta / max : 0; + const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; + patchLocal( + activeLocal.id, + { + range: { + ...activeLocal.range, + enabled: true, + hue: Math.round(hue), + hueRange: 40, + satMin: Math.round(Math.max(0, sat * 100 - 25)), + lumaMin: Math.round(Math.max(0, luma * 100 - 14)), + lumaMax: Math.round(Math.min(100, luma * 100 + 14)), + }, + }, + 'Sample mask colour', + ); + }; + const deleteLocalLayer = useCallback( (id: string) => { commitLocal((edits.local ?? []).filter((layer) => layer.id !== id), 'Delete local adjustment'); @@ -1381,7 +1451,15 @@ export default function Develop({ const next: Edits = preset.id === 'original' ? { ...defaultEdits(), crop: photo.edits.crop } - : { ...photo.edits, ...preset.edits, crop: photo.edits.crop }; + : { + ...photo.edits, + ...preset.edits, + crop: photo.edits.crop, + // The camera profile belongs to the body that produced the raw. + cameraProfile: photo.edits.cameraProfile, + // A strong film response must not leak into the next look. + redscale: preset.edits.redscale ?? 0, + }; onUpdate(photo.id, { edits: next }, `Preset: ${preset.name}`); }, [onUpdate, photo.id, photo.edits], @@ -1433,6 +1511,13 @@ export default function Develop({ onPasteLayer={pasteLocalLayer} canPaste={Boolean(localClipboard)} onAutoMask={(kind) => void addAutoMask(kind)} + onSampleRange={() => { + setRangePicking(true); + setLocalMode(false); + setHealMode(false); + setPicking(false); + setCropMode(false); + }} autoBusy={autoMaskBusy} /> @@ -1445,7 +1530,19 @@ export default function Develop({ lensSplit={lensSplit} onLensSplit={setLensSplit} /> - + + setProofProfile(cube?.name ?? null)} + /> {includeMetadata && ( Before / After + @@ -1731,6 +1840,7 @@ export default function Develop({ photo={photo} onApply={applyPreset} onSave={(name) => onSavePreset(name, photo.edits)} + onDelete={onDeletePreset} /> (rangePicking ? pickRangeColour(e) : pickWhiteBalance(e))} onPointerDown={(e) => { if (localMode) startLocalMask(e); else if (healMode) startHeal(e); diff --git a/src/components/EditedImage.tsx b/src/components/EditedImage.tsx index 4c2d715..04dbcb6 100644 --- a/src/components/EditedImage.tsx +++ b/src/components/EditedImage.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from 'react'; +import { memo, useEffect, useRef, useState } from 'react'; import { thumbTransform } from '../lib/edits'; import { useEditedThumb } from '../lib/editThumbs'; import type { PhotoRecord } from '../types'; @@ -19,7 +19,7 @@ interface Props { * server/import thumbnail and the CSS orientation transform. Rendering starts * only when the tile is close to the viewport. */ -export default function EditedImage({ +function EditedImage({ photo, boxAspect = 4 / 3, alt, @@ -62,3 +62,9 @@ export default function EditedImage({ /> ); } + +/** + * Memoised: a selection change on the library re-renders the whole grid, and a + * picture whose photo, size and props did not change has no work to redo. + */ +export default memo(EditedImage); diff --git a/src/components/EventSidebar.tsx b/src/components/EventSidebar.tsx index 4a3f254..605f15c 100644 --- a/src/components/EventSidebar.tsx +++ b/src/components/EventSidebar.tsx @@ -22,6 +22,10 @@ interface Props { onRename: (id: string, name: string) => void; onDelete: (id: string) => void; onSyncGallery?: (id: string) => void; + onPublishGallery?: (id: string) => void; + /** Server-backed account, so RAW originals can be re-decoded. */ + canReprocessRaw?: boolean; + onReprocessEvent?: (id: string) => void; onReorderEvents: (dragId: string, targetId: string) => void; onDropPhotos: (ids: string[], eventId: string) => void; trashOpen: boolean; @@ -46,6 +50,9 @@ export default function EventSidebar({ onRename, onDelete, onSyncGallery, + onPublishGallery, + canReprocessRaw = false, + onReprocessEvent, onReorderEvents, onDropPhotos, trashOpen, @@ -63,6 +70,7 @@ export default function EventSidebar({ const [dropTarget, setDropTarget] = useState(null); const counts = new Map(); + const rawCounts = new Map(); let unsorted = 0; for (const p of photos) { if (!p.eventId) { @@ -70,6 +78,7 @@ export default function EventSidebar({ continue; } counts.set(p.eventId, (counts.get(p.eventId) ?? 0) + 1); + if (p.raw) rawCounts.set(p.eventId, (rawCounts.get(p.eventId) ?? 0) + 1); } const submit = async () => { @@ -250,15 +259,37 @@ export default function EventSidebar({ {counts.get(event.id) ?? 0}
- {immichEnabled && event.immich && onSyncGallery && ( + {canReprocessRaw && onReprocessEvent && (rawCounts.get(event.id) ?? 0) > 0 && ( )} + {immichEnabled && + (event.immich + ? onSyncGallery && ( + + ) + : onPublishGallery && ( + + ))} + {onReprocessRaw && ( + + )} {onSendToImmich && ( - +
- set({ temp: v }, 'Temperature')} - track="linear-gradient(90deg,#3f74d8,#a8b6c6,#f4b23f)" - /> + + {edits.kelvin == null ? ( + set({ temp: v }, 'Temperature')} + track="linear-gradient(90deg,#3f74d8,#a8b6c6,#f4b23f)" + /> + ) : ( + set({ kelvin: v }, 'Kelvin temperature')} + format={(v) => `${Math.round(v)} K`} + track="linear-gradient(90deg,#3f74d8,#a8b6c6,#f4b23f)" + /> + )} set({ dehaze: v }, 'Dehaze')} /> set({ vibrance: v }, 'Vibrance')} /> set({ saturation: v }, 'Saturation')} /> + set({ redscale: v }, 'Redscale')} + track="linear-gradient(90deg,#a8b6c6,#d96b34,#8f1d12)" + />