Speed up raw imports and add a per-import 16-bit toggle

Import raws four at a time to match the decoder pool, compress the 16-bit
sidecar with RLE on the libuv pool, and demosaic X-Trans files in a single
Markesteijn pass so Fuji imports no longer queue into decode timeouts. The
import dialog now offers 16-bit (default) or 8-bit per import, sent as
`?sidecar=0`, and the camera thumbnail and embedded-preview fallbacks no
longer drop to 8-bit samples or store a 0x0 photo.
This commit is contained in:
2026-12-02 03:25:53 +00:00
parent ea7b5b846c
commit fa0a7e64ef
11 changed files with 464 additions and 101 deletions
+24 -4
View File
@@ -232,9 +232,11 @@ storage, while quotas are stored per account in the database.
| `LUMINARY_INVITE` | *(empty)* | Shared registration code for teammates; personal invite links work without it | | `LUMINARY_INVITE` | *(empty)* | Shared registration code for teammates; personal invite links work without it |
| `LUMINARY_MAX_UPLOAD` | `314572800` (300 MB) | Largest accepted upload, in bytes | | `LUMINARY_MAX_UPLOAD` | `314572800` (300 MB) | Largest accepted upload, in bytes |
| `LUMINARY_RAW_EDGE` | `6000` | Long edge of the editable JPEG proxy made from a raw | | `LUMINARY_RAW_EDGE` | `6000` | Long edge of the editable JPEG proxy made from a raw |
| `LUMINARY_16BIT` | `1` | Also keep the decoded samples as a 16-bit PNG beside the raw proxy; `0` saves the disk and download it costs, at the price of grading an 8-bit source | | `LUMINARY_16BIT` | `1` | Also keep the decoded samples as a 16-bit PNG beside the raw proxy; `0` saves the disk and download it costs, at the price of grading an 8-bit source. The import dialog can also turn it off for a single import |
| `LUMINARY_RAW_WORKERS` | `min(4, cores−1)` | Concurrent LibRaw decoders; each holds a worker and a few hundred MB | | `LUMINARY_RAW_WORKERS` | `min(4, cores−1)` | Concurrent LibRaw decoders; each holds a worker and a few hundred MB |
| `LUMINARY_RAW_IDLE_MS` | `90000` | Idle decoders are disposed after this to release memory | | `LUMINARY_RAW_IDLE_MS` | `90000` | Idle decoders are disposed after this to release memory |
| `LUMINARY_RAW_XTRANS_QUALITY` | `1` | Markesteijn passes for Fujifilm X-Trans files, 1–3. Three passes costs 50 s on a 40 MP frame for detail the 6000 px proxy cannot show |
| `LUMINARY_RAW_TIMEOUT_MS` | `120000` | Ceiling on one demosaic, timed from when a worker starts the job rather than from the request |
| `LUMINARY_DENOISE_WORKERS` | `min(4, cores−1)` | Concurrent detail-denoise jobs (read directly from the environment) | | `LUMINARY_DENOISE_WORKERS` | `min(4, cores−1)` | Concurrent detail-denoise jobs (read directly from the environment) |
| `LUMINARY_QUOTA_BYTES` | `107374182400` (100 GiB) | Default per-account storage allowance | | `LUMINARY_QUOTA_BYTES` | `107374182400` (100 GiB) | Default per-account storage allowance |
| `LUMINARY_QUOTA_WARN_RATIO` | `0.9` | Fraction of the quota that triggers warnings, clamped to 0.5–0.99 | | `LUMINARY_QUOTA_WARN_RATIO` | `0.9` | Fraction of the quota that triggers warnings, clamped to 0.5–0.99 |
@@ -879,7 +881,10 @@ The browser cannot demosaic camera raw, so the server does it during upload:
texture and applies `rgb_cam` in the grade shader, so the grade has 65,536 levels per texture and applies `rgb_cam` in the grade shader, so the grade has 65,536 levels per
channel instead of 256. A photo without a sidecar — one imported before this existed, channel instead of 256. A photo without a sidecar — one imported before this existed,
a non-raw file, or a build with `LUMINARY_16BIT=0` — simply grades the JPEG, so a non-raw file, or a build with `LUMINARY_16BIT=0` — simply grades the JPEG, so
nothing breaks either way. The grid and Compare read the same samples: on first nothing breaks either way. The import dialog offers this as **Import raws at 16-bit**,
checked by default; unchecking it for an import asks the server for the 8-bit path
(`?sidecar=0` on the upload), which decodes the same but skips the second encode and
its disk cost. The grid and Compare read the same samples: on first
request the server writes a camera-native tile the size of the JPEG thumbnail at request the server writes a camera-native tile the size of the JPEG thumbnail at
`previews/<id>.t16.png`, and Compare loads the full sidecar, so a loaded DCP profile `previews/<id>.t16.png`, and Compare loads the full sidecar, so a loaded DCP profile
shows in every view of the photo. Preset previews do the same. shows in every view of the photo. Preset previews do the same.
@@ -905,8 +910,11 @@ same matrix from a DCP `ColorMatrix1` — `inverse(rowNormalise(ColorMatrix · x
— matches LibRaw's `rgb_cam` to 2.2e-5 on a D700 NEF and 2.7e-5 on a 5D Mark II CR2. — matches LibRaw's `rgb_cam` to 2.2e-5 on a D700 NEF and 2.7e-5 on a 5D Mark II CR2.
**Parallel import.** Decoding runs in a bounded pool of LibRaw workers (default **Parallel import.** Decoding runs in a bounded pool of LibRaw workers (default
`min(4, cores−1)`, `LUMINARY_RAW_WORKERS`), and the browser uploads several files at a `min(4, cores−1)`, `LUMINARY_RAW_WORKERS`). The browser keeps four raws in flight to
time. Each instance owns one worker thread; extra jobs queue. Idle instances are match that pool and queues the rest, so the server is never asked for more frames than it
can decode; camera JPEGs also go four at a time, since the browser decodes those itself.
Eight 12 MP NEFs took 20.8 s two at a time and 17.4 s four at a time (8 was 15.8 s, not
worth the extra memory). Each instance owns one worker thread; extra jobs queue. Idle instances are
disposed after `LUMINARY_RAW_IDLE_MS` and recreated on demand, so a burst of imports disposed after `LUMINARY_RAW_IDLE_MS` and recreated on demand, so a burst of imports
does not pin memory forever. A decoder that reports a dead worker is recycled rather does not pin memory forever. A decoder that reports a dead worker is recycled rather
than returned to the pool. Measured on this repo with 8 mixed raws (20 MP average): than returned to the pool. Measured on this repo with 8 mixed raws (20 MP average):
@@ -917,6 +925,17 @@ than returned to the pool. Measured on this repo with 8 mixed raws (20 MP averag
| 4 | 5.2 s | 3.7× | ~2.5 GB | | 4 | 5.2 s | 3.7× | ~2.5 GB |
| 8 | 3.5 s | 5.4× | ~3.5 GB | | 8 | 3.5 s | 5.4× | ~3.5 GB |
Those are Bayer files. Fujifilm X-Trans frames behave differently in this wasm build: four
concurrent 40 MP X-Trans decodes each took ~65 s here against ~9 s on their own, so the
worker pool buys throughput in principle but not latency for that sensor. Two things
mattered more than the pool. LibRaw's default 3-pass Markesteijn demosaic took **49.9 s** on
one X-T5 frame; one pass takes **8.8 s** and is what `LUMINARY_RAW_XTRANS_QUALITY` selects.
And the 45 s decode timeout used to count time spent queued for a worker, so a parallel Fuji
import timed out in waves — every file in a wave fell back to the camera preview, and the
byte-scan fallback could hand back a truncated JPEG, which surfaced as a 0x0 photo. The
timeout now starts when a worker picks the job up, an abandoned worker is recycled instead
of being returned to the pool, and the fallback only stores bytes that actually decode.
Raise the worker count on a big machine; keep it low on a small VPS, where each worker Raise the worker count on a big machine; keep it low on a small VPS, where each worker
can hold a few hundred MB while decoding. `GET /api/health` reports the pool size and can hold a few hundred MB while decoding. `GET /api/health` reports the pool size and
busy count. busy count.
@@ -1137,6 +1156,7 @@ details, the isolation guarantees and the smoke tests (`windows/SMOKE-WINDOWS.ps
| `503` "The web build is missing" | `npm start` was run without `dist/`. Run `npm run build` first, or use `npm run dev` | | `503` "The web build is missing" | `npm start` was run without `dist/`. Run `npm run build` first, or use `npm run dev` |
| Raw upload returns `422` | LibRaw could not decode the file and no embedded preview was found. Check `GET /api/health` → `raw.libraw`; install dependencies and confirm the camera is supported | | Raw upload returns `422` | LibRaw could not decode the file and no embedded preview was found. Check `GET /api/health` → `raw.libraw`; install dependencies and confirm the camera is supported |
| Import is slow or the machine swaps | Lower `LUMINARY_RAW_WORKERS`; each decoder holds a worker and a few hundred MB | | Import is slow or the machine swaps | Lower `LUMINARY_RAW_WORKERS`; each decoder holds a worker and a few hundred MB |
| Fuji imports are slow or a Fuji file fails to import | X-Trans demosaic is the cost, not the network. `LUMINARY_RAW_XTRANS_QUALITY` defaults to 1 pass (~9 s for 40 MP); 3 is sharper and about five times slower. A file that still fails should now import from the camera preview — check its `decode` field for `embedded` |
| Emails never arrive | Gmail needs 2-Step Verification and an app password, not the account password. Use **Send test email**; admin-saved settings override the environment | | Emails never arrive | Gmail needs 2-Step Verification and an app password, not the account password. Use **Send test email**; admin-saved settings override the environment |
| Quota looks wrong after deleting | Trash still counts toward usage. Empty Trash to release the bytes | | Quota looks wrong after deleting | Trash still counts toward usage. Empty Trash to release the bytes |
| Cookies not marked `Secure` behind HTTPS | The proxy must forward `X-Forwarded-Proto: https` | | Cookies not marked `Secure` behind HTTPS | The proxy must forward `X-Forwarded-Proto: https` |
+14
View File
@@ -107,3 +107,17 @@ export const RAW_WORKERS = Math.max(
/** Idle decoder workers are disposed after this long to release memory. */ /** Idle decoder workers are disposed after this long to release memory. */
export const RAW_IDLE_MS = Number(setting('RAW_IDLE_MS', '90000')); export const RAW_IDLE_MS = Number(setting('RAW_IDLE_MS', '90000'));
/**
* Demosaic setting for Fujifilm X-Trans sensors. LibRaw reads `userQual` as
* Markesteijn passes for X-Trans, and the 3-pass default costs about 50 s on a
* 40 MP frame while 1-pass costs about 9 s. The proxy is downsampled to
* RAW_PREVIEW_EDGE, so the difference does not survive to the editor.
*/
export const RAW_XTRANS_QUALITY = Math.min(
3,
Math.max(1, Number(setting('RAW_XTRANS_QUALITY', '1')) || 1),
);
/** Ceiling on one demosaic, measured from when a worker picks the job up. */
export const RAW_TIMEOUT_MS = Number(setting('RAW_TIMEOUT_MS', '120000'));
+40 -1
View File
@@ -119,7 +119,38 @@ export function resizeRgb16(rgb16, width, height, tw, th) {
* client would have to guess the conversion, and a self-describing sidecar also * client would have to guess the conversion, and a self-describing sidecar also
* keeps working for imports that predate a catalogue migration. * keeps working for imports that predate a catalogue migration.
*/ */
/**
* Deflate settings for the 16-bit sidecar. RLE wins here because the rows are
* Sub-filtered first: a photographic row turns into mostly small byte
* differences, and run-length coding stores them in a few bits each. On a
* 40 MP sidecar this took compression from 2.87 s to 1.10 s and the file from
* 58.47 MB to 58.06 MB; the decoded samples are byte-identical.
*/
const SIDECAR_DEFLATE = { level: 6, strategy: zlib.constants.Z_RLE };
export function encodePng16(rgb16, width, height, matrix = null) { export function encodePng16(rgb16, width, height, matrix = null) {
const raw = png16Rows(rgb16, width, height);
return png16File(zlib.deflateSync(raw, SIDECAR_DEFLATE), width, height, matrix);
}
/**
* The same PNG, with the deflate handed to libuv's thread pool.
*
* A 40 MP sidecar is ~110 MB and takes about five seconds to compress. Run
* synchronously that stalls the entire server for the duration, so four
* parallel imports finished one after another while the event loop was busy;
* the import felt frozen and preview requests queued behind it.
*/
export async function encodePng16Async(rgb16, width, height, matrix = null) {
const raw = png16Rows(rgb16, width, height);
const idat = await new Promise((resolve, reject) => {
zlib.deflate(raw, SIDECAR_DEFLATE, (err, out) => (err ? reject(err) : resolve(out)));
});
return png16File(idat, width, height, matrix);
}
/** Sub-filtered rows: each byte minus the byte six to its left. */
function png16Rows(rgb16, width, height) {
const stride = width * 6; const stride = width * 6;
const raw = Buffer.alloc((stride + 1) * height); const raw = Buffer.alloc((stride + 1) * height);
const row = Buffer.alloc(stride); const row = Buffer.alloc(stride);
@@ -134,7 +165,10 @@ export function encodePng16(rgb16, width, height, matrix = null) {
raw[base + 1 + i] = (row[i] - (i >= 6 ? row[i - 6] : 0)) & 0xff; raw[base + 1 + i] = (row[i] - (i >= 6 ? row[i - 6] : 0)) & 0xff;
} }
} }
const idat = zlib.deflateSync(raw, { level: 6 }); return raw;
}
function png16File(idat, width, height, matrix = null) {
const ihdr = Buffer.alloc(13); const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(width, 0); ihdr.writeUInt32BE(width, 0);
ihdr.writeUInt32BE(height, 4); ihdr.writeUInt32BE(height, 4);
@@ -199,7 +233,12 @@ export async function cameraThumb16(png16, width, height, matrix = null) {
const sharp = await loadSharp(); const sharp = await loadSharp();
if (!sharp || width < 1 || height < 1) return null; if (!sharp || width < 1 || height < 1) return null;
try { try {
// `depth: 'ushort'` on the output only sets the container: without asking
// for the rgb16 colourspace, libvips runs the resize on 8-bit pixels and the
// samples come back as their high bytes alone (7 instead of 2000), which
// renders as a near-black tile.
const { data, info } = await sharp(png16) const { data, info } = await sharp(png16)
.toColourspace('rgb16')
.resize({ width, height, fit: 'fill' }) .resize({ width, height, fit: 'fill' })
.raw({ depth: 'ushort' }) .raw({ depth: 'ushort' })
.toBuffer({ resolveWithObject: true }); .toBuffer({ resolveWithObject: true });
+14
View File
@@ -1,3 +1,4 @@
import sharp from 'sharp';
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { cameraThumb16, encodePng16, png16Matrix, resizeRgb16 } from './imaging.mjs'; import { cameraThumb16, encodePng16, png16Matrix, resizeRgb16 } from './imaging.mjs';
@@ -75,6 +76,19 @@ describe('cameraThumb16', () => {
expect(out[25]).toBe(2); // colour type RGB expect(out[25]).toBe(2); // colour type RGB
}); });
it('keeps the full 16-bit samples, not just their high bytes', async () => {
// sharp's raw output is 8-bit unless the pipeline is asked for rgb16, and a
// downconverted thumbnail decodes to 7/15/23 instead of 2000/4000/6000.
const source = encodePng16(flat16(4, 2, [2000, 4000, 6000]), 4, 2, MATRIX);
const out = await cameraThumb16(source, 2, 1);
const { data } = await sharp(out)
.toColourspace('rgb16')
.raw({ depth: 'ushort' })
.toBuffer({ resolveWithObject: true });
const samples = [0, 2, 4].map((at) => data.readUInt16LE(at));
expect(samples).toEqual([2000, 4000, 6000]);
});
it('keeps the camera matrix so the client can convert the samples', async () => { it('keeps the camera matrix so the client can convert the samples', async () => {
const source = encodePng16(flat16(4, 2, [1000, 2000, 3000]), 4, 2, MATRIX); const source = encodePng16(flat16(4, 2, [1000, 2000, 3000]), 4, 2, MATRIX);
const out = await cameraThumb16(source, 2, 1); const out = await cameraThumb16(source, 2, 1);
+5 -1
View File
@@ -2182,6 +2182,10 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
const url = new URL(req.url ?? '/', 'http://localhost'); const url = new URL(req.url ?? '/', 'http://localhost');
const name = url.searchParams.get('name') || 'upload'; const name = url.searchParams.get('name') || 'upload';
const drop = url.searchParams.get('drop') === '1'; const drop = url.searchParams.get('drop') === '1';
// The import dialog can ask for an 8-bit import; anything else keeps the
// LUMINARY_16BIT setting. Only `sidecar=0` is meaningful, so the default path
// behaves exactly as before.
const sidecar = url.searchParams.get('sidecar') !== '0';
const mime = normalizePhotoMime(url.searchParams.get('mime') || '', name); const mime = normalizePhotoMime(url.searchParams.get('mime') || '', name);
const ext = (name.split('.').pop() || 'bin').toLowerCase(); const ext = (name.split('.').pop() || 'bin').toLowerCase();
// TIFF is not a raw container, but browsers cannot decode it either. It takes // TIFF is not a raw container, but browsers cannot decode it either. It takes
@@ -2276,7 +2280,7 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
if (raw) { if (raw) {
try { try {
const data = await fsp.readFile(target); const data = await fsp.readFile(target);
const decoded = still ? await decodeStill(data) : await decodeRaw(data); const decoded = still ? await decodeStill(data) : await decodeRaw(data, { sidecar });
await writePreview(params.id, decoded.jpeg, decoded.ext); await writePreview(params.id, decoded.jpeg, decoded.ext);
if (decoded.preview16) { if (decoded.preview16) {
await writePreview16(params.id, decoded.preview16.data); await writePreview16(params.id, decoded.preview16.data);
+26 -3
View File
@@ -88,17 +88,40 @@ class LibRawPool {
} }
} }
/** Run `fn` with a decoder instance; the instance returns to the pool after. */ /**
async use(fn) { * Run `fn` with a decoder instance; the instance returns to the pool after.
*
* `timeoutMs` covers only the work, never the wait for a free worker: a job
* that sat in the queue is not slow, and timing it from the call site made
* parallel imports fail in waves. A timed-out worker is still chewing on the
* abandoned job, so it is destroyed rather than handed to the next caller.
*/
async use(fn, { timeoutMs = 0, label = 'LibRaw' } = {}) {
const lib = await this.acquire(); const lib = await this.acquire();
let healthy = true; let healthy = true;
let timer = null;
try { try {
return await fn(lib); if (!timeoutMs) return await fn(lib);
const guard = new Promise((_, reject) => {
timer = setTimeout(
() => reject(new Error(`${label} timed out on this file`)),
timeoutMs,
);
});
try {
return await Promise.race([fn(lib), guard]);
} catch (err) {
if (timer && /timed out/.test(String(err?.message ?? '')) && err instanceof Error) {
healthy = false;
}
throw err;
}
} catch (err) { } catch (err) {
// A dead worker keeps failing, so recycle it instead of handing it back. // A dead worker keeps failing, so recycle it instead of handing it back.
if (/worker|terminated|disposed|memory/i.test(String(err?.message ?? ''))) healthy = false; if (/worker|terminated|disposed|memory/i.test(String(err?.message ?? ''))) healthy = false;
throw err; throw err;
} finally { } finally {
if (timer) clearTimeout(timer);
this.release(lib, healthy); this.release(lib, healthy);
} }
} }
+127 -63
View File
@@ -1,6 +1,13 @@
import { RAW_16BIT, RAW_PREVIEW_EDGE } from './config.mjs'; import { RAW_16BIT, RAW_PREVIEW_EDGE, RAW_TIMEOUT_MS, RAW_XTRANS_QUALITY } from './config.mjs';
import { cameraToProxy, readRgbCam } from './color.mjs'; import { cameraToProxy, readRgbCam } from './color.mjs';
import { encodePng16, encodeRgb, jpegInfo, loadSharp, resizeRgb16, toJpegProxy } from './imaging.mjs'; import {
encodePng16Async,
encodeRgb,
jpegInfo,
loadSharp,
resizeRgb16,
toJpegProxy,
} from './imaging.mjs';
import { loadLibRaw, rawPool } from './libraw-pool.mjs'; import { loadLibRaw, rawPool } from './libraw-pool.mjs';
/** Every raw container the pipeline will attempt, grouped by vendor family. */ /** Every raw container the pipeline will attempt, grouped by vendor family. */
@@ -39,15 +46,6 @@ export function isStillName(name = '') {
return SERVER_IMAGE_EXTENSIONS.has(ext); return SERVER_IMAGE_EXTENSIONS.has(ext);
} }
/** Rejects instead of waiting forever when a decoder wedges on one file. */
function withTimeout(promise, ms, message) {
let timer;
const guard = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(message)), ms);
});
return Promise.race([promise, guard]).finally(() => clearTimeout(timer));
}
/** True when the buffer starts with a container signature LibRaw can open. */ /** True when the buffer starts with a container signature LibRaw can open. */
export function looksLikeRaw(buffer) { export function looksLikeRaw(buffer) {
if (!buffer || buffer.length < 64) return false; if (!buffer || buffer.length < 64) return false;
@@ -182,74 +180,136 @@ function toRgb(img) {
* matrix metadata. A body LibRaw has no matrix for falls back to the plain sRGB * matrix metadata. A body LibRaw has no matrix for falls back to the plain sRGB
* decode, which is the same result the pipeline produced before. * decode, which is the same result the pipeline produced before.
*/ */
async function demosaic(buffer, cameraNative = true) { /**
* Fujifilm bodies that are *not* X-Trans: the Bayer-sensor GFX and X-A/T100/T200
* lines, plus the old FinePix compacts. Everyone else in the X series uses the
* 6x6 colour filter array.
*/
function isXTrans(make, model) {
if (!/fuji/i.test(String(make ?? ''))) return false;
const m = String(model ?? '').trim();
if (/^(gfx|finepix)/i.test(m)) return false;
if (/^x-(a\d|t100|t200)\b/i.test(m)) return false;
return /^x/i.test(m);
}
/**
* Demosaic one frame. On X-Trans the `userQual` setting counts Markesteijn
* passes, and LibRaw's 3-pass default is the single most expensive thing this
* pipeline does: 49.9 s on a 40 MP X-T5 frame here, against 8.8 s for one pass,
* which pushed every Fuji import into the decode timeout (and, under a parallel
* import, every file at once). The proxy is downsampled to RAW_PREVIEW_EDGE, so
* the extra passes were being thrown away by the resize anyway.
*
* The model is only known after the container is opened, and opening is ~0.2 s,
* so the file is re-opened with the cheaper setting rather than guessing from
* the filename.
*/
async function demosaic(buffer, { cameraNative = true } = {}) {
if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed'); if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed');
return rawPool.use(async (lib) => { return rawPool.use(
// LibRaw transfers the buffer to its worker, which detaches it here. Hand it async (lib) => {
// a copy so the caller's bytes survive for the embedded-preview fallback. const settings = cameraNative
await lib.open( ? DECODE_SETTINGS
Buffer.from(buffer), : { ...DECODE_SETTINGS, outputColor: 1, noAutoBright: false };
cameraNative ? DECODE_SETTINGS : { ...DECODE_SETTINGS, outputColor: 1, noAutoBright: false }, // LibRaw transfers the buffer to its worker, which detaches it here. Hand it
); // a copy so the caller's bytes survive for the embedded-preview fallback.
const image = toRgb(await lib.imageData()); await lib.open(Buffer.from(buffer), settings);
const rgbCam = cameraNative ? readRgbCam(await lib.metadata(true)) : null; if (settings.userQual > RAW_XTRANS_QUALITY) {
return { ...image, rgbCam }; const info = await lib.metadata();
}); if (isXTrans(info?.camera_make, info?.camera_model)) {
await lib.open(Buffer.from(buffer), { ...settings, userQual: RAW_XTRANS_QUALITY });
}
}
const image = toRgb(await lib.imageData());
const rgbCam = cameraNative ? readRgbCam(await lib.metadata(true)) : null;
return { ...image, rgbCam };
},
{ timeoutMs: RAW_TIMEOUT_MS, label: 'LibRaw' },
);
} }
const SOI = Buffer.from([0xff, 0xd8, 0xff]); const SOI = Buffer.from([0xff, 0xd8, 0xff]);
const EOI = Buffer.from([0xff, 0xd9]); const EOI = Buffer.from([0xff, 0xd9]);
/** Pull the largest embedded JPEG straight out of a raw container. */ /**
export function extractEmbeddedJpeg(buffer) { * Every embedded JPEG in a raw container, largest first.
let best = null; *
let from = 0; * A single scan can land on a thumbnail's end-of-image and cut the file short:
while (from < buffer.length - 3) { * that produced a "preview" sharp refused to decode, which was then stored as a
const start = buffer.indexOf(SOI, from); * 0x0 JPEG. Callers walk the list and keep the first candidate that really
* decodes.
*/
export function extractEmbeddedJpegs(buffer) {
const starts = [];
let at = 0;
while (starts.length < 64) {
const start = buffer.indexOf(SOI, at);
if (start < 0) break; if (start < 0) break;
const end = buffer.indexOf(EOI, start + 3); starts.push(start);
if (end < 0) break; at = start + 3;
const length = end + 2 - start;
if (length > 4096 && (!best || length > best.length)) best = buffer.subarray(start, end + 2);
from = end + 2;
} }
return best; const found = [];
for (const start of starts) {
// Several end-of-image markers can follow one start: a preview that carries
// its own EXIF thumbnail ends twice. Take a few candidates per start and let
// the decoder pick, instead of committing to the first marker found.
let from = start + 3;
for (let attempt = 0; attempt < 3; attempt++) {
const end = buffer.indexOf(EOI, from);
if (end < 0) break;
if (end + 2 - start > 4096) found.push(buffer.subarray(start, end + 2));
from = end + 2;
}
}
return found.sort((a, b) => b.length - a.length);
} }
/** Camera preview, preferably the one LibRaw knows the offset and length of. */ /** The largest embedded JPEG, for callers that want one candidate. */
async function embeddedPreview(buffer) { export function extractEmbeddedJpeg(buffer) {
return extractEmbeddedJpegs(buffer)[0] ?? null;
}
/** Camera previews, best first: the one LibRaw knows about, then byte-scanned. */
async function embeddedPreviews(buffer) {
const candidates = [];
if ((await rawEngine()) === 'ready') { if ((await rawEngine()) === 'ready') {
try { try {
const thumb = await withTimeout( const thumb = await rawPool.use(
rawPool.use(async (lib) => { async (lib) => {
await lib.open(Buffer.from(buffer), { useCameraWb: true }); await lib.open(Buffer.from(buffer), { useCameraWb: true });
return lib.thumbnailData(); return lib.thumbnailData();
}), },
12000, { timeoutMs: 20000, label: 'LibRaw preview' },
'LibRaw preview timed out',
); );
if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) { if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) {
return Buffer.from(thumb.data); candidates.push(Buffer.from(thumb.data));
} }
} catch { } catch {
/* fall through to the byte scan */ /* fall through to the byte scan */
} }
} }
return extractEmbeddedJpeg(buffer); candidates.push(...extractEmbeddedJpegs(buffer));
return candidates;
} }
/** /**
* Convert a raw file into an editable JPEG. LibRaw demosaics where possible and * Convert a raw file into an editable JPEG. LibRaw demosaics where possible and
* falls back to the camera's own embedded preview when it cannot. * falls back to the camera's own embedded preview when it cannot.
*
* `sidecar` writes the 16-bit samples beside the JPEG. It defaults to the
* server setting, and the import dialog can turn it off for one import: an
* 8-bit import decodes exactly the same, it just skips the second encode and the
* tens of megabytes of disk it costs.
*/ */
export async function decodeRaw(buffer) { export async function decodeRaw(buffer, { sidecar = RAW_16BIT } = {}) {
let librawError = null; let librawError = null;
if (looksLikeRaw(buffer)) { if (looksLikeRaw(buffer)) {
try { try {
let frame = await withTimeout(demosaic(buffer, true), 45000, 'LibRaw timed out on this file'); let frame = await demosaic(buffer, { cameraNative: true });
// No usable matrix (an odd body or older engine): decode the familiar sRGB // No usable matrix (an odd body or older engine): decode the familiar sRGB
// way instead of shipping camera samples nobody can convert. // way instead of shipping camera samples nobody can convert.
if (!frame.rgbCam || !frame.rgb16) frame = await withTimeout(demosaic(buffer, false), 45000, 'LibRaw timed out on this file'); if (!frame.rgbCam || !frame.rgb16) frame = await demosaic(buffer, { cameraNative: false });
const { width, height, rgbCam } = frame; const { width, height, rgbCam } = frame;
// Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and // Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and
// `rgb16` the camera-native sidecar, sharing one white point. // `rgb16` the camera-native sidecar, sharing one white point.
@@ -260,13 +320,13 @@ export async function decodeRaw(buffer) {
// two textures at the same uv, so a size disagreement would misalign the // two textures at the same uv, so a size disagreement would misalign the
// whole grade. It is optional -- encoding failures leave the JPEG path. // whole grade. It is optional -- encoding failures leave the JPEG path.
let preview16 = null; let preview16 = null;
if (frame.rgb16 && RAW_16BIT) { if (frame.rgb16 && sidecar) {
try { try {
const scaled = resizeRgb16(frame.rgb16, width, height, encoded.width, encoded.height); const scaled = resizeRgb16(frame.rgb16, width, height, encoded.width, encoded.height);
preview16 = { preview16 = {
// The matrix travels with the samples so the editor knows how to // The matrix travels with the samples so the editor knows how to
// turn camera RGB into sRGB without a second metadata fetch. // turn camera RGB into sRGB without a second metadata fetch.
data: encodePng16(scaled, encoded.width, encoded.height, rgbCam), data: await encodePng16Async(scaled, encoded.width, encoded.height, rgbCam),
width: encoded.width, width: encoded.width,
height: encoded.height, height: encoded.height,
rgbCam, rgbCam,
@@ -290,21 +350,25 @@ export async function decodeRaw(buffer) {
librawError = 'not a recognised raw container'; librawError = 'not a recognised raw container';
} }
const embedded = await embeddedPreview(buffer); // Keep the first candidate that sharp can actually decode. Never store bytes
if (embedded) { // that did not decode: a 0x0 "preview" is an unopenable photo in the catalog.
// A handful of candidates is enough; each rejected one costs a header parse,
// not a full decode.
for (const embedded of (await embeddedPreviews(buffer)).slice(0, 6)) {
const proxy = await toJpegProxy(embedded, RAW_PREVIEW_EDGE); const proxy = await toJpegProxy(embedded, RAW_PREVIEW_EDGE);
if (proxy) { if (!proxy) continue;
const size = await jpegInfo(proxy.data); const size = await jpegInfo(proxy.data);
return { const width = size?.width || proxy.width;
jpeg: proxy.data, const height = size?.height || proxy.height;
width: size?.width || proxy.width, if (!width || !height) continue;
height: size?.height || proxy.height, return {
engine: 'embedded', jpeg: proxy.data,
ext: proxy.ext, width,
note: `LibRaw could not decode this file (${librawError}); using the camera preview.`, height,
}; engine: 'embedded',
} ext: proxy.ext,
return { jpeg: embedded, width: 0, height: 0, engine: 'embedded', ext: 'jpg', note: librawError ?? undefined }; note: `LibRaw could not decode this file (${librawError}); using the camera preview.`,
};
} }
throw new Error( throw new Error(
+51
View File
@@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest';
import { import {
RAW_EXTENSIONS, RAW_EXTENSIONS,
decodeRaw, decodeRaw,
extractEmbeddedJpegs,
decodeStill, decodeStill,
isRawName, isRawName,
isStillName, isStillName,
@@ -52,6 +53,56 @@ describe('raw format coverage', () => {
}); });
}); });
const JPEG_SOI = Buffer.from([0xff, 0xd8, 0xff]);
const JPEG_EOI = Buffer.from([0xff, 0xd9]);
/** A JPEG-shaped run of `total` bytes with no nested markers. */
function jpegBytes(total) {
return Buffer.concat([JPEG_SOI, Buffer.alloc(Math.max(1, total - 5), 0x11), JPEG_EOI]);
}
describe('embedded preview fallback', () => {
it('lists candidates largest first and ignores thumbnail-sized runs', () => {
const small = jpegBytes(9000);
const big = jpegBytes(90000);
const tiny = jpegBytes(1200);
const buffer = Buffer.concat([
Buffer.alloc(128),
small,
Buffer.alloc(32),
big,
Buffer.alloc(32),
tiny,
Buffer.alloc(32),
]);
const lengths = extractEmbeddedJpegs(buffer).map((jpeg) => jpeg.length);
// Splitting candidates at every end-of-image marker can yield over-long
// slices that span two images; those fail to decode and are skipped. What
// matters is that both real previews are offered, largest first, and that
// thumbnail-sized runs are not.
expect(lengths).toEqual([...lengths].sort((a, b) => b - a));
expect(lengths).toContain(big.length);
expect(lengths).toContain(small.length);
expect(lengths).not.toContain(tiny.length);
});
it('does not let a nested EXIF thumbnail truncate the full preview', () => {
// Regression: the scan used to stop at the thumbnail's end-of-image, so the
// "preview" it stored was a cut-off JPEG that sharp refused to decode and
// the import ended up as a 0x0 photo.
const thumb = jpegBytes(6000);
const outer = Buffer.concat([
JPEG_SOI,
Buffer.alloc(2000, 0x11),
thumb,
Buffer.alloc(40000, 0x11),
JPEG_EOI,
]);
const found = extractEmbeddedJpegs(Buffer.concat([Buffer.alloc(64), outer]));
expect(found[0].length).toBe(outer.length);
});
});
describe('TIFF decoding', () => { describe('TIFF decoding', () => {
it('turns a TIFF into a JPEG proxy', async () => { it('turns a TIFF into a JPEG proxy', async () => {
const { default: sharp } = await import('sharp'); const { default: sharp } = await import('sharp');
+43 -6
View File
@@ -46,6 +46,9 @@ export default function ImportModal({
const [progress, setProgress] = useState<ImportProgress | null>(null); const [progress, setProgress] = useState<ImportProgress | null>(null);
const [failures, setFailures] = useState<string[]>([]); const [failures, setFailures] = useState<string[]>([]);
const [allowDuplicates, setAllowDuplicates] = useState(false); const [allowDuplicates, setAllowDuplicates] = useState(false);
// 16-bit is the default an editor would expect, and it is what a raw import
// should keep unless the whole point is a smaller library.
const [sidecar16, setSidecar16] = useState(true);
const [createGallery, setCreateGallery] = useState(immichEnabled); const [createGallery, setCreateGallery] = useState(immichEnabled);
const [galleryCreated, setGalleryCreated] = useState(false); const [galleryCreated, setGalleryCreated] = useState(false);
const [galleryError, setGalleryError] = useState<string | null>(null); const [galleryError, setGalleryError] = useState<string | null>(null);
@@ -128,7 +131,15 @@ export default function ImportModal({
); );
} }
} }
const result = await importFiles(readyFiles, targetId, [], setProgress, cloud ?? null, controller.signal); const result = await importFiles(
readyFiles,
targetId,
[],
setProgress,
cloud ?? null,
controller.signal,
{ sidecar16 },
);
if (result.photos.length) onImported(result.photos, targetId); if (result.photos.length) onImported(result.photos, targetId);
let published = 0; let published = 0;
@@ -347,13 +358,37 @@ export default function ImportModal({
{rawCount > 0 && cloud && ( {rawCount > 0 && cloud && (
<div className="banner info"> <div className="banner info">
{local {local
? 'Raw files are demosaiced by the Luminary local engine (LibRaw) on this PC, a few ' + ? 'Raw files are demosaiced by the Luminary local engine (LibRaw) on this PC, four ' +
'at a time in parallel. Each file usually takes 2–4 seconds, and nothing leaves your computer.' 'at a time; the rest of your selection waits its turn. A 24 MP raw takes a few ' +
: 'Raw files are demosaiced by the server (LibRaw), a few at a time in parallel. Each ' + 'seconds; a 40 MP compressed Fuji file takes closer to twenty. Nothing leaves ' +
'file usually takes 2–4 seconds.'} 'your computer.'
: 'Raw files are demosaiced by the server (LibRaw), four at a time; the rest of your ' +
'selection waits its turn. A 24 MP raw takes a few seconds; a 40 MP compressed ' +
'Fuji file takes closer to twenty.'}
{' '}A file the engine cannot decode still imports from the camera’s own preview.
</div> </div>
)} )}
{rawCount > 0 && cloud && (
<>
<label className="check-row">
<input
type="checkbox"
checked={sidecar16}
onChange={(e) => setSidecar16(e.target.checked)}
disabled={busy}
/>
Import raws at 16-bit (recommended)
</label>
<p className="muted small">
A 16-bit sidecar keeps every level the decoder read, so recovering shadows and
highlights works from 65,536 steps per channel instead of 256. It costs roughly
25× the JPEG in disk and download. Uncheck to import at 8-bit instead: smaller,
quicker to upload, but graded from the JPEG.
</p>
</>
)}
{progress && ( {progress && (
<div className="progress"> <div className="progress">
<div className="progress-bar"> <div className="progress-bar">
@@ -363,7 +398,9 @@ export default function ImportModal({
/> />
</div> </div>
<div className="muted small"> <div className="muted small">
{progress.done} / {progress.total} {progress.current ? `· ${progress.current}` : ''} {progress.done} / {progress.total}
{progress.waiting ? ` · ${progress.waiting} waiting` : ''}
{progress.current ? ` · ${progress.current}` : ''}
</div> </div>
</div> </div>
)} )}
+9 -1
View File
@@ -155,8 +155,16 @@ export function pullProofs(): Promise<ProofSummary[]> {
return request<{ proofs: ProofSummary[] }>('/api/proofs').then((res) => res.proofs ?? []); return request<{ proofs: ProofSummary[] }>('/api/proofs').then((res) => res.proofs ?? []);
} }
export function uploadOriginal(id: string, file: File | Blob, name: string): Promise<UploadResult> { export function uploadOriginal(
id: string,
file: File | Blob,
name: string,
options: { sidecar?: boolean } = {},
): Promise<UploadResult> {
const query = new URLSearchParams({ name, mime: file.type || 'application/octet-stream' }); const query = new URLSearchParams({ name, mime: file.type || 'application/octet-stream' });
// Only an opt-out is sent: an older server ignores the parameter and keeps
// its configured default, and every other upload keeps the shorter URL.
if (options.sidecar === false) query.set('sidecar', '0');
return request<UploadResult>(`/api/photos/${encodeURIComponent(id)}/original?${query}`, { return request<UploadResult>(`/api/photos/${encodeURIComponent(id)}/original?${query}`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' }, headers: { 'Content-Type': 'application/octet-stream' },
+111 -22
View File
@@ -10,6 +10,8 @@ export interface ImportProgress {
done: number; done: number;
total: number; total: number;
current: string; current: string;
/** Files that have not started yet, so a long queue reads as working. */
waiting?: number;
} }
export interface ImportResult { export interface ImportResult {
@@ -20,13 +22,37 @@ export interface ImportResult {
/** Provided by the app when a Luminary server is connected. */ /** Provided by the app when a Luminary server is connected. */
export interface CloudImport { export interface CloudImport {
uploadOriginal: (id: string, file: File, name: string) => Promise<UploadResult>; uploadOriginal: (
id: string,
file: File,
name: string,
options?: { sidecar?: boolean },
) => Promise<UploadResult>;
push: (photo: PhotoRecord) => Promise<PhotoRecord>; push: (photo: PhotoRecord) => Promise<PhotoRecord>;
} }
/** Files imported at once; the server bounds how many raws decode in parallel. */ export interface ImportOptions {
/**
* Keep the 16-bit sidecar for raws in this import. On by default: the editor
* grades the decoded samples instead of 256-level JPEG pixels. Turning it off
* makes each raw import smaller and quicker, at the cost of an 8-bit grade.
*/
sidecar16?: boolean;
}
/** Files imported at once when a Luminary server is connected. */
const IMPORT_CONCURRENCY = 4; const IMPORT_CONCURRENCY = 4;
/**
* Raws and TIFFs are decoded by the server, which is where the work piles up, so
* this window matches the decoder pool rather than the network. Eight 12 MP NEFs
* took 20.8 s two at a time and 17.4 s four at a time; eight at once was 15.8 s,
* not enough to justify holding that much memory. The X-Trans frames that once
* made a wide window pathological now demosaic in one Markesteijn pass, so four
* no longer turns a Fuji selection into a queue of timeouts.
*/
const RAW_IMPORT_CONCURRENCY = 4;
export function uid(): string { export function uid(): string {
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID(); if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID();
return `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`; return `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
@@ -44,6 +70,31 @@ function mapLimit<T>(items: T[], limit: number, fn: (item: T, index: number) =>
return Promise.all(runners); return Promise.all(runners);
} }
/**
* A counting semaphore. `acquire()` resolves with a release function, so a slot
* is returned even when the guarded work throws or the import is cancelled.
* Waiters are served in order.
*/
function createSemaphore(slots: number) {
let free = Math.max(1, slots);
const waiting: (() => void)[] = [];
return {
async acquire(): Promise<() => void> {
if (free > 0) free -= 1;
else await new Promise<void>((resolve) => waiting.push(resolve));
let released = false;
return () => {
if (released) return;
released = true;
const next = waiting.shift();
// Hand the slot straight over, so it is never briefly up for grabs.
if (next) next();
else free += 1;
};
},
};
}
function formatShutter(time: unknown): string | undefined { function formatShutter(time: unknown): string | undefined {
if (typeof time !== 'number' || !Number.isFinite(time) || time <= 0) return undefined; if (typeof time !== 'number' || !Number.isFinite(time) || time <= 0) return undefined;
if (time >= 1) return `${Math.round(time * 10) / 10}s`; if (time >= 1) return `${Math.round(time * 10) / 10}s`;
@@ -127,9 +178,10 @@ async function importRaw(
defaults: CameraLensDefault[], defaults: CameraLensDefault[],
/** TIFF goes through the same proxy path but is not a raw container. */ /** TIFF goes through the same proxy path but is not a raw container. */
raw = true, raw = true,
sidecar16 = true,
): Promise<PhotoRecord> { ): Promise<PhotoRecord> {
const id = uid(); const id = uid();
const upload = await cloud.uploadOriginal(id, file, file.name); const upload = await cloud.uploadOriginal(id, file, file.name, { sidecar: sidecar16 });
const previewUrl = upload.previewUrl ?? `/api/photos/${id}/preview`; const previewUrl = upload.previewUrl ?? `/api/photos/${id}/preview`;
const res = await fetch(previewUrl, { credentials: 'same-origin' }); const res = await fetch(previewUrl, { credentials: 'same-origin' });
if (!res.ok) throw new Error('The server could not produce a preview for this raw file'); if (!res.ok) throw new Error('The server could not produce a preview for this raw file');
@@ -137,8 +189,10 @@ async function importRaw(
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' }); const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
const thumb = await makeThumb(bitmap); const thumb = await makeThumb(bitmap);
const { meta, takenAt } = await readMeta(file); const { meta, takenAt } = await readMeta(file);
const width = upload.width ?? bitmap.width; // `??` is wrong here: the server reports 0 for a dimension it could not read,
const height = upload.height ?? bitmap.height; // and 0 is not nullish, so a failed decode produced a 0x0 catalog record.
const width = upload.width || bitmap.width;
const height = upload.height || bitmap.height;
const edits = editsForImport(meta, defaults); const edits = editsForImport(meta, defaults);
bitmap.close(); bitmap.close();
@@ -232,7 +286,9 @@ export async function importFiles(
onProgress?: (p: ImportProgress) => void, onProgress?: (p: ImportProgress) => void,
cloud?: CloudImport | null, cloud?: CloudImport | null,
signal?: AbortSignal, signal?: AbortSignal,
options: ImportOptions = {},
): Promise<ImportResult> { ): Promise<ImportResult> {
const sidecar16 = options.sidecar16 !== false;
const result: ImportResult = { photos: [], failed: [] }; const result: ImportResult = { photos: [], failed: [] };
const images = files.filter(isSupportedFile); const images = files.filter(isSupportedFile);
const total = images.length; const total = images.length;
@@ -241,27 +297,60 @@ export async function importFiles(
const collected: { index: number; photo: PhotoRecord }[] = []; const collected: { index: number; photo: PhotoRecord }[] = [];
const defaults = await loadCameraLensDefaults().catch(() => []); const defaults = await loadCameraLensDefaults().catch(() => []);
let done = 0; let done = 0;
let active = 0;
// A wide selection spends most of its time inside a narrow window: without a
// waiting count the dialog would show "4 / 16" and no sign of the other 12.
const report = (current: string) =>
onProgress?.({ done, total, current, waiting: Math.max(0, total - done - active) });
const rawSlots = createSemaphore(RAW_IMPORT_CONCURRENCY);
await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => { await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => {
if (signal?.aborted) return; if (signal?.aborted) return;
const viaServer = isRawFile(file) || isTiffFile(file);
// Camera JPEGs and PNGs stay this wide, because the browser decodes them
// locally and they are seconds apart at worst. A raw holds one of a couple
// of server slots first, so the upload window can stay wide for the network
// while the decode window stays as narrow as the decoder pool.
const release = viaServer ? await rawSlots.acquire() : null;
try { try {
const viaServer = isRawFile(file) || isTiffFile(file); // The import may have been cancelled while this file queued for a slot.
const photo = viaServer if (signal?.aborted) return;
? cloud // Report before the work starts, not only when it finishes. A 40 MP raw
? await importRaw(file, eventId, keywords, cloud, defaults, isRawFile(file)) // takes seconds, and four of them finish together: because progress was
: (() => { // only emitted in `finally`, the bar stayed hidden until the first batch
throw new Error('Raw files need the Luminary server. Sign in, then import again.'); // completed and then jumped to 4.
})() active += 1;
: await importStandard(file, eventId, keywords, cloud, defaults); report(file.name);
collected.push({ index, photo }); try {
} catch (err) { const photo = viaServer
result.failed.push({ ? cloud
name: file.name, ? await importRaw(
reason: err instanceof Error ? err.message : 'Unsupported image format', file,
}); eventId,
keywords,
cloud,
defaults,
isRawFile(file),
sidecar16,
)
: (() => {
throw new Error('Raw files need the Luminary server. Sign in, then import again.');
})()
: await importStandard(file, eventId, keywords, cloud, defaults);
collected.push({ index, photo });
} catch (err) {
result.failed.push({
name: file.name,
reason: err instanceof Error ? err.message : 'Unsupported image format',
});
} finally {
active -= 1;
done += 1;
report(file.name);
}
} finally { } finally {
done += 1; release?.();
onProgress?.({ done, total, current: file.name });
} }
}); });
@@ -269,6 +358,6 @@ export async function importFiles(
collected.sort((a, b) => a.index - b.index); collected.sort((a, b) => a.index - b.index);
result.photos = collected.map((c) => c.photo); result.photos = collected.map((c) => c.photo);
result.cancelled = Boolean(signal?.aborted); result.cancelled = Boolean(signal?.aborted);
onProgress?.({ done: total, total, current: '' }); onProgress?.({ done: total, total, current: '', waiting: 0 });
return result; return result;
} }