bd90264c3c
A raw upload request stays open for the whole decode, and four X-Trans frames decoded together took 87-102 s each on a 12-core server against 28 s alone, so every request outlived a 60 s reverse-proxy read timeout and came back as 504 while the server was still working. Two-wide keeps a request near 45 s and finishes a 16-file batch sooner as well; Bayer files give up a little.
371 lines
13 KiB
TypeScript
371 lines
13 KiB
TypeScript
import exifr from 'exifr';
|
|
import type { UploadResult } from './api';
|
|
import type { PhotoMeta, PhotoRecord } from '../types';
|
|
import { putAsset, putPhoto } from './db';
|
|
import { defaultEdits, normalizePhoto } from './edits';
|
|
import { defaultForMeta, loadCameraLensDefaults, type CameraLensDefault } from './lensDefaults';
|
|
import { isRawFile, isTiffFile, RAW_EXTENSIONS } from './raw';
|
|
|
|
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 {
|
|
photos: PhotoRecord[];
|
|
failed: { name: string; reason: string }[];
|
|
cancelled?: boolean;
|
|
}
|
|
|
|
/** Provided by the app when a Luminary server is connected. */
|
|
export interface CloudImport {
|
|
uploadOriginal: (
|
|
id: string,
|
|
file: File,
|
|
name: string,
|
|
options?: { sidecar?: boolean },
|
|
) => Promise<UploadResult>;
|
|
push: (photo: PhotoRecord) => Promise<PhotoRecord>;
|
|
}
|
|
|
|
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 is about one thing: how long a single upload request stays open.
|
|
*
|
|
* Measured on a 12-core server with 40 MP X-Trans RAFs through the real decode
|
|
* path: one file 28.4 s, two at once 44.4-45.4 s each, four at once 87.4-102.4 s
|
|
* each. Parallel X-Trans decodes barely scale here, so four-wide made every
|
|
* request about 1.5 minutes long and still finished sixteen files slower than
|
|
* two-wide (about 410 s against 360 s). Anything sitting in front of the server
|
|
* with a 60 s read timeout - the nginx default - answers 504 while the origin
|
|
* carries on decoding, which looks like a failed import of the files that were
|
|
* still in flight. Two keeps a request at ~45 s and is faster overall; Bayer
|
|
* files lose a little (8 NEFs took 20.8 s two at a time, 17.4 s four at a time)
|
|
* in exchange for every raw import staying inside a proxy's patience.
|
|
*/
|
|
const RAW_IMPORT_CONCURRENCY = 2;
|
|
|
|
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)}`;
|
|
}
|
|
|
|
function mapLimit<T>(items: T[], limit: number, fn: (item: T, index: number) => Promise<void>): Promise<void[]> {
|
|
let cursor = 0;
|
|
const runners = Array.from({ length: Math.min(Math.max(1, limit), items.length) }, async () => {
|
|
for (;;) {
|
|
const index = cursor++;
|
|
if (index >= items.length) return;
|
|
await fn(items[index], index);
|
|
}
|
|
});
|
|
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`;
|
|
return `1/${Math.round(1 / time)}s`;
|
|
}
|
|
|
|
async function readMeta(file: File): Promise<{ meta: PhotoMeta; takenAt?: number }> {
|
|
try {
|
|
const data = (await exifr.parse(file, {
|
|
tiff: true,
|
|
exif: true,
|
|
gps: false,
|
|
interop: false,
|
|
translateValues: false,
|
|
reviveValues: true,
|
|
})) as Record<string, unknown> | undefined;
|
|
if (!data) return { meta: {} };
|
|
const make = typeof data.Make === 'string' ? data.Make.trim() : '';
|
|
const model = typeof data.Model === 'string' ? data.Model.trim() : '';
|
|
const meta: PhotoMeta = {
|
|
camera: [make, model].filter(Boolean).join(' ').replace(/\s+/g, ' ') || undefined,
|
|
lens: typeof data.LensModel === 'string' ? data.LensModel.trim() : undefined,
|
|
iso: typeof data.ISO === 'number' ? data.ISO : undefined,
|
|
aperture: typeof data.FNumber === 'number' ? data.FNumber : undefined,
|
|
shutter: formatShutter(data.ExposureTime),
|
|
focal: typeof data.FocalLength === 'number' ? Math.round(data.FocalLength) : undefined,
|
|
};
|
|
const taken = data.DateTimeOriginal ?? data.CreateDate ?? data.ModifyDate;
|
|
const takenAt = taken instanceof Date && !Number.isNaN(taken.getTime()) ? taken.getTime() : undefined;
|
|
return { meta, takenAt };
|
|
} catch {
|
|
return { meta: {} };
|
|
}
|
|
}
|
|
|
|
function editsForImport(meta: PhotoMeta, defaults: CameraLensDefault[]) {
|
|
const edits = defaultEdits();
|
|
const match = defaultForMeta(defaults, meta);
|
|
if (match) {
|
|
edits.lens = {
|
|
...match.profile,
|
|
// A saved default still carries whatever the profile had when it was
|
|
// stored. Applying it on import must not switch the vignetting gain back
|
|
// on and over-expose the corners, so that correction stays opt-in.
|
|
corrections: { ...match.profile.corrections, vignetting: false },
|
|
};
|
|
}
|
|
return edits;
|
|
}
|
|
|
|
async function makeThumb(bitmap: ImageBitmap): Promise<string> {
|
|
const max = 560;
|
|
const scale = Math.min(1, max / Math.max(bitmap.width, bitmap.height));
|
|
const w = Math.max(1, Math.round(bitmap.width * scale));
|
|
const h = Math.max(1, Math.round(bitmap.height * scale));
|
|
const canvas = document.createElement('canvas');
|
|
canvas.width = w;
|
|
canvas.height = h;
|
|
const ctx = canvas.getContext('2d');
|
|
if (!ctx) throw new Error('Canvas 2D is unavailable');
|
|
ctx.imageSmoothingQuality = 'high';
|
|
ctx.drawImage(bitmap, 0, 0, w, h);
|
|
return canvas.toDataURL('image/jpeg', 0.82);
|
|
}
|
|
|
|
export function isSupportedFile(file: File): boolean {
|
|
if (file.type.startsWith('image/')) return true;
|
|
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
|
|
return RAW_EXTENSIONS.has(ext) || /^(jpe?g|png|webp|avif|gif|bmp|tiff?)$/.test(ext);
|
|
}
|
|
|
|
/**
|
|
* Raw files cannot be decoded by the browser, so they are sent to the server,
|
|
* demosaiced there, and represented locally by the returned editable proxy.
|
|
*/
|
|
async function importRaw(
|
|
file: File,
|
|
eventId: string,
|
|
keywords: string[],
|
|
cloud: CloudImport,
|
|
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, { 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');
|
|
const blob = await res.blob();
|
|
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
|
|
const thumb = await makeThumb(bitmap);
|
|
const { meta, takenAt } = await readMeta(file);
|
|
// `??` 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();
|
|
|
|
const record = normalizePhoto({
|
|
id,
|
|
eventId,
|
|
name: file.name,
|
|
width,
|
|
height,
|
|
size: file.size,
|
|
mime: 'image/jpeg',
|
|
addedAt: Date.now(),
|
|
takenAt: takenAt ?? file.lastModified,
|
|
meta,
|
|
thumb,
|
|
rating: 0,
|
|
flag: 'none',
|
|
color: '',
|
|
keywords,
|
|
edits,
|
|
history: [{ label: 'Import', ts: Date.now(), edits }],
|
|
raw,
|
|
decode: upload.engine,
|
|
proxyBytes: upload.previewBytes,
|
|
previewUrl,
|
|
});
|
|
|
|
await putPhoto(record);
|
|
// No local blob: the multi-megabyte raw stays on the server.
|
|
const saved = await cloud.push(record);
|
|
const merged = normalizePhoto({ ...record, ...saved });
|
|
await putPhoto(merged);
|
|
return merged;
|
|
}
|
|
|
|
async function importStandard(
|
|
file: File,
|
|
eventId: string,
|
|
keywords: string[],
|
|
cloud: CloudImport | null | undefined,
|
|
defaults: CameraLensDefault[],
|
|
): Promise<PhotoRecord> {
|
|
// Camera JPEGs carry their orientation in EXIF; ask for it to be applied so
|
|
// the thumbnail and the edited proxy agree with what the camera shot.
|
|
const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' });
|
|
const thumb = await makeThumb(bitmap);
|
|
const { meta, takenAt } = await readMeta(file);
|
|
const id = uid();
|
|
const edits = editsForImport(meta, defaults);
|
|
let record = normalizePhoto({
|
|
id,
|
|
eventId,
|
|
name: file.name,
|
|
width: bitmap.width,
|
|
height: bitmap.height,
|
|
size: file.size,
|
|
mime: file.type || 'image/jpeg',
|
|
addedAt: Date.now(),
|
|
takenAt: takenAt ?? file.lastModified,
|
|
meta,
|
|
thumb,
|
|
rating: 0,
|
|
flag: 'none',
|
|
color: '',
|
|
keywords,
|
|
edits,
|
|
history: [{ label: 'Import', ts: Date.now(), edits }],
|
|
});
|
|
await putAsset(id, file);
|
|
bitmap.close();
|
|
|
|
if (cloud) {
|
|
// Originals are mirrored to the server; failures fall back to a local-only import.
|
|
try {
|
|
await cloud.uploadOriginal(id, file, file.name);
|
|
const saved = await cloud.push(record);
|
|
record = normalizePhoto({ ...record, ...saved });
|
|
} catch (err) {
|
|
console.warn('Could not copy the original to the server', file.name, err);
|
|
}
|
|
}
|
|
|
|
await putPhoto(record);
|
|
return record;
|
|
}
|
|
|
|
export async function importFiles(
|
|
files: File[],
|
|
eventId: string,
|
|
keywords: string[] = [],
|
|
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;
|
|
if (!total) return result;
|
|
|
|
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 {
|
|
// 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 {
|
|
release?.();
|
|
}
|
|
});
|
|
|
|
// Keep the shoot in capture/selection order regardless of which finished first.
|
|
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: '', waiting: 0 });
|
|
return result;
|
|
}
|