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
+14
View File
@@ -107,3 +107,17 @@ export const RAW_WORKERS = Math.max(
/** Idle decoder workers are disposed after this long to release memory. */
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
* 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) {
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 raw = Buffer.alloc((stride + 1) * height);
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;
}
}
const idat = zlib.deflateSync(raw, { level: 6 });
return raw;
}
function png16File(idat, width, height, matrix = null) {
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(width, 0);
ihdr.writeUInt32BE(height, 4);
@@ -199,7 +233,12 @@ export async function cameraThumb16(png16, width, height, matrix = null) {
const sharp = await loadSharp();
if (!sharp || width < 1 || height < 1) return null;
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)
.toColourspace('rgb16')
.resize({ width, height, fit: 'fill' })
.raw({ depth: 'ushort' })
.toBuffer({ resolveWithObject: true });
+14
View File
@@ -1,3 +1,4 @@
import sharp from 'sharp';
import { describe, expect, it } from 'vitest';
import { cameraThumb16, encodePng16, png16Matrix, resizeRgb16 } from './imaging.mjs';
@@ -75,6 +76,19 @@ describe('cameraThumb16', () => {
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 () => {
const source = encodePng16(flat16(4, 2, [1000, 2000, 3000]), 4, 2, MATRIX);
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 name = url.searchParams.get('name') || 'upload';
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 ext = (name.split('.').pop() || 'bin').toLowerCase();
// 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) {
try {
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);
if (decoded.preview16) {
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();
let healthy = true;
let timer = null;
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) {
// 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;
throw err;
} finally {
if (timer) clearTimeout(timer);
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 { 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';
/** 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);
}
/** 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. */
export function looksLikeRaw(buffer) {
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
* 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');
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),
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 };
});
return rawPool.use(
async (lib) => {
const settings = 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.
await lib.open(Buffer.from(buffer), settings);
if (settings.userQual > RAW_XTRANS_QUALITY) {
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 EOI = Buffer.from([0xff, 0xd9]);
/** Pull the largest embedded JPEG straight out of a raw container. */
export function extractEmbeddedJpeg(buffer) {
let best = null;
let from = 0;
while (from < buffer.length - 3) {
const start = buffer.indexOf(SOI, from);
/**
* Every embedded JPEG in a raw container, largest first.
*
* A single scan can land on a thumbnail's end-of-image and cut the file short:
* that produced a "preview" sharp refused to decode, which was then stored as a
* 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;
const end = buffer.indexOf(EOI, start + 3);
if (end < 0) break;
const length = end + 2 - start;
if (length > 4096 && (!best || length > best.length)) best = buffer.subarray(start, end + 2);
from = end + 2;
starts.push(start);
at = start + 3;
}
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. */
async function embeddedPreview(buffer) {
/** The largest embedded JPEG, for callers that want one candidate. */
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') {
try {
const thumb = await withTimeout(
rawPool.use(async (lib) => {
const thumb = await rawPool.use(
async (lib) => {
await lib.open(Buffer.from(buffer), { useCameraWb: true });
return lib.thumbnailData();
}),
12000,
'LibRaw preview timed out',
},
{ timeoutMs: 20000, label: 'LibRaw preview' },
);
if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) {
return Buffer.from(thumb.data);
candidates.push(Buffer.from(thumb.data));
}
} catch {
/* 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
* 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;
if (looksLikeRaw(buffer)) {
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
// 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;
// Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and
// `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
// whole grade. It is optional -- encoding failures leave the JPEG path.
let preview16 = null;
if (frame.rgb16 && RAW_16BIT) {
if (frame.rgb16 && sidecar) {
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),
data: await encodePng16Async(scaled, encoded.width, encoded.height, rgbCam),
width: encoded.width,
height: encoded.height,
rgbCam,
@@ -290,21 +350,25 @@ export async function decodeRaw(buffer) {
librawError = 'not a recognised raw container';
}
const embedded = await embeddedPreview(buffer);
if (embedded) {
// Keep the first candidate that sharp can actually decode. Never store bytes
// 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);
if (proxy) {
const size = await jpegInfo(proxy.data);
return {
jpeg: proxy.data,
width: size?.width || proxy.width,
height: size?.height || proxy.height,
engine: 'embedded',
ext: proxy.ext,
note: `LibRaw could not decode this file (${librawError}); using the camera preview.`,
};
}
return { jpeg: embedded, width: 0, height: 0, engine: 'embedded', ext: 'jpg', note: librawError ?? undefined };
if (!proxy) continue;
const size = await jpegInfo(proxy.data);
const width = size?.width || proxy.width;
const height = size?.height || proxy.height;
if (!width || !height) continue;
return {
jpeg: proxy.data,
width,
height,
engine: 'embedded',
ext: proxy.ext,
note: `LibRaw could not decode this file (${librawError}); using the camera preview.`,
};
}
throw new Error(
+51
View File
@@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest';
import {
RAW_EXTENSIONS,
decodeRaw,
extractEmbeddedJpegs,
decodeStill,
isRawName,
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', () => {
it('turns a TIFF into a JPEG proxy', async () => {
const { default: sharp } = await import('sharp');