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
+43 -6
View File
@@ -46,6 +46,9 @@ export default function ImportModal({
const [progress, setProgress] = useState<ImportProgress | null>(null);
const [failures, setFailures] = useState<string[]>([]);
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 [galleryCreated, setGalleryCreated] = useState(false);
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);
let published = 0;
@@ -347,13 +358,37 @@ export default function ImportModal({
{rawCount > 0 && cloud && (
<div className="banner info">
{local
? 'Raw files are demosaiced by the Luminary local engine (LibRaw) on this PC, a few ' +
'at a time in parallel. Each file usually takes 2–4 seconds, and nothing leaves your computer.'
: 'Raw files are demosaiced by the server (LibRaw), a few at a time in parallel. Each ' +
'file usually takes 2–4 seconds.'}
? 'Raw files are demosaiced by the Luminary local engine (LibRaw) on this PC, 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. Nothing leaves ' +
'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>
)}
{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 && (
<div className="progress">
<div className="progress-bar">
@@ -363,7 +398,9 @@ export default function ImportModal({
/>
</div>
<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>
)}
+9 -1
View File
@@ -155,8 +155,16 @@ export function pullProofs(): Promise<ProofSummary[]> {
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' });
// 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}`, {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
+111 -22
View File
@@ -10,6 +10,8 @@ export interface ImportProgress {
done: number;
total: number;
current: string;
/** Files that have not started yet, so a long queue reads as working. */
waiting?: number;
}
export interface ImportResult {
@@ -20,13 +22,37 @@ export interface ImportResult {
/** Provided by the app when a Luminary server is connected. */
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>;
}
/** 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;
/**
* 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 {
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID();
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);
}
/**
* 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 {
if (typeof time !== 'number' || !Number.isFinite(time) || time <= 0) return undefined;
if (time >= 1) return `${Math.round(time * 10) / 10}s`;
@@ -127,9 +178,10 @@ async function importRaw(
defaults: CameraLensDefault[],
/** TIFF goes through the same proxy path but is not a raw container. */
raw = true,
sidecar16 = true,
): Promise<PhotoRecord> {
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 res = await fetch(previewUrl, { credentials: 'same-origin' });
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 thumb = await makeThumb(bitmap);
const { meta, takenAt } = await readMeta(file);
const width = upload.width ?? bitmap.width;
const height = upload.height ?? bitmap.height;
// `??` is wrong here: the server reports 0 for a dimension it could not read,
// 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);
bitmap.close();
@@ -232,7 +286,9 @@ export async function importFiles(
onProgress?: (p: ImportProgress) => void,
cloud?: CloudImport | null,
signal?: AbortSignal,
options: ImportOptions = {},
): Promise<ImportResult> {
const sidecar16 = options.sidecar16 !== false;
const result: ImportResult = { photos: [], failed: [] };
const images = files.filter(isSupportedFile);
const total = images.length;
@@ -241,27 +297,60 @@ export async function importFiles(
const collected: { index: number; photo: PhotoRecord }[] = [];
const defaults = await loadCameraLensDefaults().catch(() => []);
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) => {
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 {
const viaServer = isRawFile(file) || isTiffFile(file);
const photo = viaServer
? cloud
? await importRaw(file, eventId, keywords, cloud, defaults, isRawFile(file))
: (() => {
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',
});
// The import may have been cancelled while this file queued for a slot.
if (signal?.aborted) return;
// Report before the work starts, not only when it finishes. A 40 MP raw
// takes seconds, and four of them finish together: because progress was
// only emitted in `finally`, the bar stayed hidden until the first batch
// completed and then jumped to 4.
active += 1;
report(file.name);
try {
const photo = viaServer
? cloud
? await importRaw(
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 {
done += 1;
onProgress?.({ done, total, current: file.name });
release?.();
}
});
@@ -269,6 +358,6 @@ export async function importFiles(
collected.sort((a, b) => a.index - b.index);
result.photos = collected.map((c) => c.photo);
result.cancelled = Boolean(signal?.aborted);
onProgress?.({ done: total, total, current: '' });
onProgress?.({ done: total, total, current: '', waiting: 0 });
return result;
}