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:
+127
-63
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user