Land camera-native raw profiles, real ICC soft proofing and 16-bit proxies.
Camera profiles, proofing tables and the half-float sidecar all have to agree with the pixels the editor actually grades, so they land together with the preset filter menu that was unusable while thumbnails streamed in. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* Camera-native colour conversion for the raw pipeline.
|
||||
*
|
||||
* LibRaw can hand back the demosaiced frame before it applies any output
|
||||
* colourspace (`outputColor: 0`). Those samples are the camera's own RGB,
|
||||
* white-balanced and gamma encoded, which is what a camera profile needs: the
|
||||
* camera-to-sRGB step becomes a matrix the editor can swap out without
|
||||
* decoding the raw again.
|
||||
*
|
||||
* One white point is chosen for the whole frame from the *converted* pixels, so
|
||||
* the JPEG proxy and the 16-bit sidecar share an exposure. LibRaw's own
|
||||
* auto-bright is deliberately off: it measures each output path separately,
|
||||
* which leaves the two outputs a third of a stop apart.
|
||||
*/
|
||||
|
||||
export function srgbToLinear(value) {
|
||||
const v = value <= 0 ? 0 : value >= 1 ? 1 : value;
|
||||
return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
|
||||
}
|
||||
|
||||
export function linearToSrgb(value) {
|
||||
const v = value <= 0 ? 0 : value >= 1 ? 1 : value;
|
||||
return v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;
|
||||
}
|
||||
|
||||
let decodeTable = null;
|
||||
let encodeTable = null;
|
||||
|
||||
/** 16-bit sample -> linear light, for the camera's own gamma encoding. */
|
||||
function linearTable() {
|
||||
if (!decodeTable) {
|
||||
decodeTable = new Float32Array(65536);
|
||||
for (let i = 0; i < 65536; i++) decodeTable[i] = srgbToLinear(i / 65535);
|
||||
}
|
||||
return decodeTable;
|
||||
}
|
||||
|
||||
/** Linear light (indexed as a 16-bit fraction) -> 8-bit sRGB. */
|
||||
function encodedTable() {
|
||||
if (!encodeTable) {
|
||||
encodeTable = new Uint8Array(65536);
|
||||
for (let i = 0; i < 65536; i++) {
|
||||
encodeTable[i] = Math.round(linearToSrgb(i / 65535) * 255);
|
||||
}
|
||||
}
|
||||
return encodeTable;
|
||||
}
|
||||
|
||||
/** Flattens the metadata's 4x4 `rgb_cam` into the 3x3 camera -> sRGB matrix. */
|
||||
export function readRgbCam(meta) {
|
||||
const raw = meta?.color_data?.rgb_cam;
|
||||
if (!Array.isArray(raw) || raw.length < 3) return null;
|
||||
const matrix = [];
|
||||
for (let row = 0; row < 3; row++) {
|
||||
const values = raw[row];
|
||||
if (!Array.isArray(values) || values.length < 3) return null;
|
||||
for (let col = 0; col < 3; col++) {
|
||||
const value = Number(values[col]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
matrix.push(value);
|
||||
}
|
||||
}
|
||||
// A zero matrix would render the whole frame black; that is a metadata
|
||||
// failure, not a look, so fall back to LibRaw's own conversion.
|
||||
if (matrix.every((value) => Math.abs(value) < 1e-6)) return null;
|
||||
return matrix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a camera-native 16-bit frame into the two buffers the editor needs,
|
||||
* in place:
|
||||
*
|
||||
* - `rgb8` the sRGB proxy the JPEG is encoded from
|
||||
* - `rgb16` the camera samples, white-point scaled, still camera native
|
||||
*
|
||||
* Returns the white point gain that was applied. The gain is baked into both
|
||||
* buffers, so the client only has to apply the camera matrix; keeping it out of
|
||||
* the sidecar would mean shipping a second 16-bit table for no benefit.
|
||||
*/
|
||||
export function cameraToProxy(rgb16, rgb8, matrix) {
|
||||
const linear = linearTable();
|
||||
const encode = encodedTable();
|
||||
const count = Math.floor(rgb16.length / 3);
|
||||
const m = matrix ?? [1, 0, 0, 0, 1, 0, 0, 0, 1];
|
||||
|
||||
// Pass 1: where does the fastest channel sit? Choosing the white point after
|
||||
// the matrix keeps highlight clipping at about the same 1% LibRaw targets,
|
||||
// instead of clipping whatever the matrix pushes past 1 on top of that.
|
||||
const hist = new Uint32Array(65536);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const s = i * 3;
|
||||
const r = linear[rgb16[s]];
|
||||
const g = linear[rgb16[s + 1]];
|
||||
const b = linear[rgb16[s + 2]];
|
||||
const max = Math.max(
|
||||
m[0] * r + m[1] * g + m[2] * b,
|
||||
m[3] * r + m[4] * g + m[5] * b,
|
||||
m[6] * r + m[7] * g + m[8] * b,
|
||||
);
|
||||
const bin = max <= 0 ? 0 : max >= 1 ? 65535 : Math.round(max * 65535);
|
||||
hist[bin]++;
|
||||
}
|
||||
let seen = 0;
|
||||
let p99 = 65535;
|
||||
const target = count * 0.99;
|
||||
for (let i = 0; i < 65536; i++) {
|
||||
seen += hist[i];
|
||||
if (seen >= target) {
|
||||
p99 = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Cap the gain: a nearly black frame is a real photograph, not a reason to
|
||||
// multiply read noise by fifty.
|
||||
const gain = Math.min(48, Math.max(0.25, 65535 / Math.max(1, p99)));
|
||||
|
||||
// Camera samples stay gamma encoded, so a shadow lift still has 16 bits of
|
||||
// encoded detail to work from rather than 16 bits of linear light.
|
||||
const camera = new Uint16Array(65536);
|
||||
for (let i = 0; i < 65536; i++) {
|
||||
camera[i] = Math.round(linearToSrgb(linear[i] * gain) * 65535);
|
||||
}
|
||||
|
||||
// Pass 2: write both buffers.
|
||||
for (let i = 0; i < count; i++) {
|
||||
const s = i * 3;
|
||||
const r = linear[rgb16[s]] * gain;
|
||||
const g = linear[rgb16[s + 1]] * gain;
|
||||
const b = linear[rgb16[s + 2]] * gain;
|
||||
rgb8[s] = encode[clampIndex(m[0] * r + m[1] * g + m[2] * b)];
|
||||
rgb8[s + 1] = encode[clampIndex(m[3] * r + m[4] * g + m[5] * b)];
|
||||
rgb8[s + 2] = encode[clampIndex(m[6] * r + m[7] * g + m[8] * b)];
|
||||
rgb16[s] = camera[rgb16[s]];
|
||||
rgb16[s + 1] = camera[rgb16[s + 1]];
|
||||
rgb16[s + 2] = camera[rgb16[s + 2]];
|
||||
}
|
||||
return gain;
|
||||
}
|
||||
|
||||
function clampIndex(value) {
|
||||
if (!(value > 0)) return 0;
|
||||
if (value >= 1) return 65535;
|
||||
return Math.round(value * 65535);
|
||||
}
|
||||
@@ -75,6 +75,13 @@ export const SMTP_FROM = setting('SMTP_FROM', SMTP_USER);
|
||||
/** Long edge used for the editable proxy of raw files. */
|
||||
export const RAW_PREVIEW_EDGE = Number(setting('RAW_EDGE', '6000'));
|
||||
|
||||
/**
|
||||
* Also store the 16-bit samples LibRaw decoded as a sidecar next to the JPEG
|
||||
* proxy. It costs roughly 25x the JPEG in disk and download, but it is the only
|
||||
* way the editor can grade from more than 256 levels per channel.
|
||||
*/
|
||||
export const RAW_16BIT = setting('16BIT', '1') !== '0';
|
||||
|
||||
export const SESSION_DAYS = 30;
|
||||
|
||||
/** How many raws decode at once. One core is left for the HTTP server. */
|
||||
|
||||
@@ -89,6 +89,18 @@ db.exec(`
|
||||
|
||||
CREATE INDEX IF NOT EXISTS gallery_reviews_token ON gallery_reviews(token);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS gallery_settings (
|
||||
token TEXT PRIMARY KEY,
|
||||
password_hash TEXT NOT NULL DEFAULT '',
|
||||
password_salt TEXT NOT NULL DEFAULT '',
|
||||
expires_at INTEGER,
|
||||
watermark TEXT NOT NULL DEFAULT '',
|
||||
allow_downloads INTEGER NOT NULL DEFAULT 1,
|
||||
download_cap INTEGER NOT NULL DEFAULT 0,
|
||||
download_count INTEGER NOT NULL DEFAULT 0,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS invites (
|
||||
token TEXT PRIMARY KEY,
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
@@ -607,6 +619,71 @@ export function picksByOwner(ownerId) {
|
||||
}));
|
||||
}
|
||||
|
||||
const gallerySettingsStmt = db.prepare('SELECT * FROM gallery_settings WHERE token = ?');
|
||||
const upsertGallerySettings = db.prepare(`
|
||||
INSERT INTO gallery_settings
|
||||
(token, password_hash, password_salt, expires_at, watermark, allow_downloads, download_cap, download_count, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(token) DO UPDATE SET
|
||||
password_hash = excluded.password_hash,
|
||||
password_salt = excluded.password_salt,
|
||||
expires_at = excluded.expires_at,
|
||||
watermark = excluded.watermark,
|
||||
allow_downloads = excluded.allow_downloads,
|
||||
download_cap = excluded.download_cap,
|
||||
updated_at = excluded.updated_at
|
||||
`);
|
||||
const deleteGallerySettings = db.prepare('DELETE FROM gallery_settings WHERE token = ?');
|
||||
const bumpGalleryDownload = db.prepare(
|
||||
'UPDATE gallery_settings SET download_count = download_count + 1 WHERE token = ?',
|
||||
);
|
||||
const readGalleryDownloads = db.prepare(
|
||||
'SELECT download_count FROM gallery_settings WHERE token = ?',
|
||||
);
|
||||
|
||||
/** Access rules for a public proofing link; defaults when none were saved. */
|
||||
export function gallerySettingsFor(token) {
|
||||
const row = gallerySettingsStmt.get(token);
|
||||
return {
|
||||
passwordHash: row?.password_hash ?? '',
|
||||
passwordSalt: row?.password_salt ?? '',
|
||||
expiresAt: row?.expires_at ?? null,
|
||||
watermark: row?.watermark ?? '',
|
||||
allowDownloads: row ? Boolean(row.allow_downloads) : true,
|
||||
downloadCap: row?.download_cap ?? 0,
|
||||
downloadCount: row?.download_count ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The download counter is deliberately preserved across settings edits: an
|
||||
* owner tightening or loosening a cap must not hand out a fresh allowance.
|
||||
*/
|
||||
export function saveGallerySettings(token, settings) {
|
||||
upsertGallerySettings.run(
|
||||
token,
|
||||
settings.passwordHash ?? '',
|
||||
settings.passwordSalt ?? '',
|
||||
settings.expiresAt ?? null,
|
||||
settings.watermark ?? '',
|
||||
settings.allowDownloads === false ? 0 : 1,
|
||||
Math.max(0, Math.round(settings.downloadCap ?? 0)),
|
||||
0,
|
||||
Date.now(),
|
||||
);
|
||||
return gallerySettingsFor(token);
|
||||
}
|
||||
|
||||
export function clearGallerySettings(token) {
|
||||
deleteGallerySettings.run(token);
|
||||
}
|
||||
|
||||
/** Counts a gallery download and reports the new total, or 0 when uncapped. */
|
||||
export function noteGalleryDownload(token) {
|
||||
bumpGalleryDownload.run(token);
|
||||
return readGalleryDownloads.get(token)?.download_count ?? 0;
|
||||
}
|
||||
|
||||
export function galleryPick(token, photoId, clientId, clientName, picked) {
|
||||
if (!picked) {
|
||||
q.deletePick.run(token, photoId, clientId);
|
||||
|
||||
+93
-1
@@ -68,7 +68,99 @@ export function encodePng(rgb, width, height) {
|
||||
]);
|
||||
}
|
||||
|
||||
/** Encode an interleaved RGB byte buffer as JPEG (sharp) or PNG (fallback). */
|
||||
/**
|
||||
* Box-average a 16-bit RGB image down to the proxy size. sharp's raw pipeline
|
||||
* does not round-trip 16-bit samples faithfully, and this keeps the sidecar
|
||||
* pixel-aligned with the JPEG that was encoded by a different library.
|
||||
*/
|
||||
export function resizeRgb16(rgb16, width, height, tw, th) {
|
||||
if (width === tw && height === th) return rgb16;
|
||||
const out = new Uint16Array(tw * th * 3);
|
||||
const fx = width / tw;
|
||||
const fy = height / th;
|
||||
for (let y = 0; y < th; y++) {
|
||||
const y0 = Math.floor(y * fy);
|
||||
const y1 = Math.min(height, Math.max(y0 + 1, Math.ceil((y + 1) * fy)));
|
||||
for (let x = 0; x < tw; x++) {
|
||||
const x0 = Math.floor(x * fx);
|
||||
const x1 = Math.min(width, Math.max(x0 + 1, Math.ceil((x + 1) * fx)));
|
||||
let r = 0;
|
||||
let g = 0;
|
||||
let b = 0;
|
||||
let n = 0;
|
||||
for (let sy = y0; sy < y1; sy++) {
|
||||
let at = (sy * width + x0) * 3;
|
||||
for (let sx = x0; sx < x1; sx++) {
|
||||
r += rgb16[at];
|
||||
g += rgb16[at + 1];
|
||||
b += rgb16[at + 2];
|
||||
at += 3;
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
const d = (y * tw + x) * 3;
|
||||
out[d] = Math.round(r / n);
|
||||
out[d + 1] = Math.round(g / n);
|
||||
out[d + 2] = Math.round(b / n);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 16-bit RGB PNG (colour type 2, no interlacing, Sub-filtered rows). The editor
|
||||
* inflates this in the browser and uploads it as a half-float texture, so it has
|
||||
* to be a standard PNG rather than a private container. Sub filtering subtracts
|
||||
* each byte from the pixel six bytes to its left, which compresses photographic
|
||||
* rows far better than storing the samples raw.
|
||||
*
|
||||
* `matrix` is the camera-to-sRGB matrix (9 numbers, row major). It is written to
|
||||
* a tEXt chunk because the sidecar holds camera-native samples: without it the
|
||||
* client would have to guess the conversion, and a self-describing sidecar also
|
||||
* keeps working for imports that predate a catalogue migration.
|
||||
*/
|
||||
export function encodePng16(rgb16, width, height, matrix = null) {
|
||||
const stride = width * 6;
|
||||
const raw = Buffer.alloc((stride + 1) * height);
|
||||
const row = Buffer.alloc(stride);
|
||||
for (let y = 0; y < height; y++) {
|
||||
let at = y * width * 3;
|
||||
for (let i = 0; i < stride; i += 2) {
|
||||
row.writeUInt16BE(rgb16[at++] & 0xffff, i);
|
||||
}
|
||||
const base = y * (stride + 1);
|
||||
raw[base] = 1;
|
||||
for (let i = 0; i < stride; i++) {
|
||||
raw[base + 1 + i] = (row[i] - (i >= 6 ? row[i - 6] : 0)) & 0xff;
|
||||
}
|
||||
}
|
||||
const idat = zlib.deflateSync(raw, { level: 6 });
|
||||
const ihdr = Buffer.alloc(13);
|
||||
ihdr.writeUInt32BE(width, 0);
|
||||
ihdr.writeUInt32BE(height, 4);
|
||||
ihdr[8] = 16;
|
||||
ihdr[9] = 2;
|
||||
ihdr[10] = 0;
|
||||
ihdr[11] = 0;
|
||||
ihdr[12] = 0;
|
||||
return Buffer.concat([
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
chunk('IHDR', ihdr),
|
||||
...(matrix && matrix.length === 9
|
||||
? [
|
||||
chunk(
|
||||
'tEXt',
|
||||
Buffer.from(
|
||||
`rgbCam\0${matrix.map((value) => Number(value).toFixed(8)).join(',')}`,
|
||||
'latin1',
|
||||
),
|
||||
),
|
||||
]
|
||||
: []),
|
||||
chunk('IDAT', idat),
|
||||
chunk('IEND', Buffer.alloc(0)),
|
||||
]);
|
||||
}
|
||||
export async function encodeRgb(rgb, width, height, quality = 92, maxEdge = 0) {
|
||||
const sharp = await loadSharp();
|
||||
if (!sharp) {
|
||||
|
||||
+334
-16
@@ -56,16 +56,19 @@ import {
|
||||
defaultRoot,
|
||||
findOriginal,
|
||||
findPreview,
|
||||
findPreview16,
|
||||
findProof,
|
||||
findProofThumb,
|
||||
findThumb,
|
||||
isCustomRoot,
|
||||
originalTarget,
|
||||
removeAsset,
|
||||
removePreview16,
|
||||
setStorageRoot,
|
||||
storageBytes,
|
||||
storageRoot,
|
||||
writePreview,
|
||||
writePreview16,
|
||||
writeProof,
|
||||
writeProofThumb,
|
||||
writeThumb,
|
||||
@@ -238,6 +241,77 @@ function normalizePhotoMime(value, name = '') {
|
||||
return PHOTO_MIME_BY_EXT[ext] ?? 'application/octet-stream';
|
||||
}
|
||||
|
||||
import {
|
||||
gallerySettingsFor,
|
||||
saveGallerySettings,
|
||||
clearGallerySettings,
|
||||
noteGalleryDownload,
|
||||
} from './db.mjs';
|
||||
|
||||
/** Passwords are hashed per link with a random salt, so a database dump is not a key. */
|
||||
function hashGalleryPassword(password, salt) {
|
||||
return crypto.scryptSync(password, salt, 32).toString('hex');
|
||||
}
|
||||
|
||||
/* Unlocked galleries live in memory: a restart asks for the password again. */
|
||||
const galleryUnlocks = new Map();
|
||||
const GALLERY_UNLOCK_MS = 12 * 3600 * 1000;
|
||||
const galleryCookie = (token) => `lumg_${token}`;
|
||||
|
||||
/**
|
||||
* One check for every public gallery route: revoked link, expiry, password.
|
||||
* A locked gallery is a 401 so the page can show the password prompt instead
|
||||
* of claiming the shoot is gone.
|
||||
*/
|
||||
function galleryGate(req, token) {
|
||||
const shared = eventByShareToken(token);
|
||||
if (!shared) {
|
||||
return { ok: false, status: 404, message: 'This proofing gallery is no longer available' };
|
||||
}
|
||||
const settings = gallerySettingsFor(token);
|
||||
if (settings.expiresAt && Date.now() > settings.expiresAt) {
|
||||
return { ok: false, status: 410, message: 'This proofing gallery has expired' };
|
||||
}
|
||||
if (settings.passwordHash) {
|
||||
const cookie = parseCookies(req)[galleryCookie(token)];
|
||||
const entry = galleryUnlocks.get(token);
|
||||
const valid =
|
||||
cookie && entry && entry.key === cookie && entry.expires > Date.now()
|
||||
? true
|
||||
: false;
|
||||
if (!valid) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 401,
|
||||
message: 'This gallery is password protected',
|
||||
locked: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
return { ok: true, shared, settings };
|
||||
}
|
||||
|
||||
/** Writes the refusal and returns true when the caller must stop. */
|
||||
function galleryDenied(req, res, token) {
|
||||
const gate = galleryGate(req, token);
|
||||
if (gate.ok) return false;
|
||||
error(res, gate.status, gate.message);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Refuses a download when the link turned downloads off or used its allowance. */
|
||||
function galleryDownloadDenied(res, token, settings) {
|
||||
if (!settings.allowDownloads) {
|
||||
error(res, 403, 'Downloads are disabled for this gallery');
|
||||
return true;
|
||||
}
|
||||
if (settings.downloadCap > 0 && settings.downloadCount >= settings.downloadCap) {
|
||||
error(res, 403, 'This gallery has reached its download limit');
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function parseCookies(req) {
|
||||
const out = {};
|
||||
for (const part of String(req.headers.cookie ?? '').split(';')) {
|
||||
@@ -1315,6 +1389,103 @@ route('GET', '/api/events/:id/share', async ({ req, res, params }) => {
|
||||
.map((p) => ({ photoId: p.photoId, clientName: p.clientName }))
|
||||
: [],
|
||||
feedback,
|
||||
settings: token
|
||||
? (() => {
|
||||
const saved = gallerySettingsFor(token);
|
||||
return {
|
||||
passwordSet: Boolean(saved.passwordHash),
|
||||
expiresAt: saved.expiresAt,
|
||||
watermark: saved.watermark,
|
||||
allowDownloads: saved.allowDownloads,
|
||||
downloadCap: saved.downloadCap,
|
||||
downloadCount: saved.downloadCount,
|
||||
};
|
||||
})()
|
||||
: null,
|
||||
});
|
||||
});
|
||||
|
||||
/** Owner-side security settings for the proofing link. */
|
||||
route('PUT', '/api/events/:id/share/settings', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event');
|
||||
const token = shareTokenFor(params.id);
|
||||
if (!token) return error(res, 404, 'This event has no proofing link yet');
|
||||
const body = await readJson(req, 64 * 1024);
|
||||
const current = gallerySettingsFor(token);
|
||||
let passwordHash = current.passwordHash;
|
||||
let passwordSalt = current.passwordSalt;
|
||||
if (typeof body.password === 'string') {
|
||||
const password = body.password.trim();
|
||||
if (password === '') {
|
||||
passwordHash = '';
|
||||
passwordSalt = '';
|
||||
} else if (password.length < 4) {
|
||||
return error(res, 400, 'Use at least 4 characters for the gallery password');
|
||||
} else {
|
||||
passwordSalt = crypto.randomBytes(12).toString('hex');
|
||||
passwordHash = hashGalleryPassword(password, passwordSalt);
|
||||
}
|
||||
}
|
||||
const saved = saveGallerySettings(token, {
|
||||
passwordHash,
|
||||
passwordSalt,
|
||||
expiresAt:
|
||||
typeof body.expiresAt === 'number' && body.expiresAt > 0 ? body.expiresAt : null,
|
||||
watermark: String(body.watermark ?? '').trim().slice(0, 80),
|
||||
allowDownloads: body.allowDownloads !== false,
|
||||
downloadCap: Number.isFinite(Number(body.downloadCap))
|
||||
? Math.max(0, Math.min(100000, Math.round(Number(body.downloadCap))))
|
||||
: current.downloadCap,
|
||||
});
|
||||
json(res, 200, {
|
||||
settings: {
|
||||
passwordSet: Boolean(saved.passwordHash),
|
||||
expiresAt: saved.expiresAt,
|
||||
watermark: saved.watermark,
|
||||
allowDownloads: saved.allowDownloads,
|
||||
downloadCap: saved.downloadCap,
|
||||
downloadCount: saved.downloadCount,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
/** Public unlock: exchanges the gallery password for a cookie scoped to the link. */
|
||||
route('POST', '/api/galleries/:token/unlock', async ({ req, res, params }) => {
|
||||
if (!allowGalleryWrite(req, params.token)) {
|
||||
return error(res, 429, 'Too many attempts. Try again shortly.', { 'Retry-After': '60' });
|
||||
}
|
||||
const gate = galleryGate(req, params.token);
|
||||
if (!gate.ok && gate.status === 410) return error(res, 410, gate.message);
|
||||
if (!gate.ok && !gate.locked) return error(res, gate.status, gate.message);
|
||||
const settings = gallerySettingsFor(params.token);
|
||||
if (!settings.passwordHash) return json(res, 200, { ok: true });
|
||||
const body = await readJson(req, 16 * 1024);
|
||||
const password = String(body.password ?? '');
|
||||
const attempt = Buffer.from(hashGalleryPassword(password, settings.passwordSalt), 'hex');
|
||||
const expected = Buffer.from(settings.passwordHash, 'hex');
|
||||
const ok =
|
||||
attempt.length === expected.length && crypto.timingSafeEqual(attempt, expected);
|
||||
if (!ok) return error(res, 403, 'That password does not open this gallery');
|
||||
const key = crypto.randomBytes(24).toString('base64url');
|
||||
galleryUnlocks.set(params.token, { key, expires: Date.now() + GALLERY_UNLOCK_MS });
|
||||
res.setHeader(
|
||||
'Set-Cookie',
|
||||
`${galleryCookie(params.token)}=${encodeURIComponent(key)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${GALLERY_UNLOCK_MS / 1000}`,
|
||||
);
|
||||
json(res, 200, { ok: true });
|
||||
});
|
||||
|
||||
/** Public: is this link locked or past its expiry? Used before the gallery loads. */
|
||||
route('GET', '/api/galleries/:token/status', async ({ req, res, params }) => {
|
||||
const gate = galleryGate(req, params.token);
|
||||
if (!gate.ok && !gate.locked) return error(res, gate.status, gate.message);
|
||||
const settings = gate.ok ? gate.settings : gallerySettingsFor(params.token);
|
||||
json(res, 200, {
|
||||
locked: !gate.ok,
|
||||
expiresAt: settings.expiresAt,
|
||||
allowDownloads: settings.allowDownloads,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1334,14 +1505,20 @@ route('DELETE', '/api/events/:id/share', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event');
|
||||
const token = shareTokenFor(params.id);
|
||||
setShareToken(params.id, null);
|
||||
if (token) {
|
||||
clearGallerySettings(token);
|
||||
galleryUnlocks.delete(token);
|
||||
}
|
||||
json(res, 200, { ok: true });
|
||||
});
|
||||
|
||||
/** Public gallery payload: no session, only the shared event and its photos. */
|
||||
route('GET', '/api/galleries/:token', async ({ res, params, url }) => {
|
||||
const shared = eventByShareToken(params.token);
|
||||
if (!shared) return error(res, 404, 'This proofing gallery is no longer available');
|
||||
route('GET', '/api/galleries/:token', async ({ req, res, params, url }) => {
|
||||
const gate = galleryGate(req, params.token);
|
||||
if (!gate.ok) return error(res, gate.status, gate.message);
|
||||
const shared = gate.shared;
|
||||
const clientId = String(url.searchParams.get('client') ?? '').slice(0, 64);
|
||||
const picks = picksForToken(params.token).filter((p) => p.picked);
|
||||
const counts = new Map();
|
||||
@@ -1395,16 +1572,26 @@ route('GET', '/api/galleries/:token', async ({ res, params, url }) => {
|
||||
photographer: 'Luminary',
|
||||
photos,
|
||||
picks: { total: picks.length, clients: new Set(picks.map((p) => p.clientId)).size },
|
||||
downloads: {
|
||||
allowed: gate.settings.allowDownloads,
|
||||
remaining:
|
||||
gate.settings.downloadCap > 0
|
||||
? Math.max(0, gate.settings.downloadCap - gate.settings.downloadCount)
|
||||
: null,
|
||||
},
|
||||
watermark: gate.settings.watermark,
|
||||
});
|
||||
});
|
||||
|
||||
route('GET', '/api/galleries/:token/photos/:id/thumb', async ({ req, res, params }) => {
|
||||
if (galleryDenied(req, res, params.token)) return;
|
||||
if (!galleryPhoto(params.token, params.id)) return error(res, 404, 'Not found');
|
||||
const file = findProofThumb(params.id) ?? (await findThumb(params.id));
|
||||
return sendFile(req, res, file, 'image/jpeg', 'private, max-age=3600');
|
||||
});
|
||||
|
||||
route('GET', '/api/galleries/:token/photos/:id/preview', async ({ req, res, params }) => {
|
||||
if (galleryDenied(req, res, params.token)) return;
|
||||
const hit = galleryPhoto(params.token, params.id);
|
||||
if (!hit) return error(res, 404, 'Not found');
|
||||
const proof = findProof(params.id);
|
||||
@@ -1423,6 +1610,9 @@ route('GET', '/api/galleries/:token/photos/:id/preview', async ({ req, res, para
|
||||
|
||||
/** Client download of the edited proof, named like the delivered file. */
|
||||
route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, params }) => {
|
||||
const gate = galleryGate(req, params.token);
|
||||
if (!gate.ok) return error(res, gate.status, gate.message);
|
||||
if (galleryDownloadDenied(res, params.token, gate.settings)) return;
|
||||
const hit = galleryPhoto(params.token, params.id);
|
||||
if (!hit) return error(res, 404, 'Not found');
|
||||
const proof = findProof(params.id);
|
||||
@@ -1430,6 +1620,7 @@ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, par
|
||||
const originalName = String(hit.photo.name || 'photo.jpg');
|
||||
const safe = (proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName).replace(/["\\/:*?<>|]+/g, '-');
|
||||
const mime = proof ? 'image/jpeg' : normalizePhotoMime(hit.photo.mime, hit.photo.name);
|
||||
noteGalleryDownload(params.token);
|
||||
return sendFile(req, res, file, mime, 'private, max-age=3600', {
|
||||
'Content-Disposition': `attachment; filename="${safe}"`,
|
||||
});
|
||||
@@ -1437,8 +1628,10 @@ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, par
|
||||
|
||||
/** Download the client's favourites as one ZIP. */
|
||||
route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, url }) => {
|
||||
const shared = eventByShareToken(params.token);
|
||||
if (!shared) return error(res, 404, 'This proofing gallery is no longer available');
|
||||
const gate = galleryGate(req, params.token);
|
||||
if (!gate.ok) return error(res, gate.status, gate.message);
|
||||
if (galleryDownloadDenied(res, params.token, gate.settings)) return;
|
||||
const shared = gate.shared;
|
||||
const clientId = String(url.searchParams.get('client') ?? '').slice(0, 64);
|
||||
const picks = picksForToken(params.token).filter(
|
||||
(pick) => pick.picked && (!clientId || pick.clientId === clientId),
|
||||
@@ -1487,6 +1680,7 @@ route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, ur
|
||||
if (!entries.length) return error(res, 404, 'There are no downloadable favourites yet');
|
||||
|
||||
const archive = createZip(entries);
|
||||
noteGalleryDownload(params.token);
|
||||
const eventName = String(shared.event.name || 'proofing')
|
||||
.replace(/[^a-z0-9._ -]+/gi, '-')
|
||||
.trim() || 'proofing';
|
||||
@@ -1502,13 +1696,80 @@ route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, ur
|
||||
}
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------- tether */
|
||||
|
||||
/**
|
||||
* Tethering is a drop folder, not a camera driver: the owner (or a synced
|
||||
* tethering app) writes frames into one directory per event, and the open
|
||||
* editor pulls and imports them. Files are removed from the folder only after
|
||||
* the client confirms the import, so a dropped connection never loses a frame.
|
||||
*/
|
||||
const TETHER_EXT = new Set([
|
||||
'jpg', 'jpeg', 'png', 'tif', 'tiff', 'webp',
|
||||
'dng', 'cr2', 'cr3', 'nef', 'arw', 'orf', 'rw2', 'raf', 'pef', 'srw',
|
||||
]);
|
||||
|
||||
function tetherFolder(eventId) {
|
||||
const safe = String(eventId).replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 64) || 'event';
|
||||
return { safe, dir: path.join(DATA_DIR, 'tether', safe) };
|
||||
}
|
||||
|
||||
/** A bare file name in the drop folder; anything with a path is refused. */
|
||||
function tetherFileName(raw) {
|
||||
const name = path.basename(String(raw ?? ''));
|
||||
if (!name || name !== String(raw ?? '')) return null;
|
||||
const ext = name.split('.').pop()?.toLowerCase() ?? '';
|
||||
return TETHER_EXT.has(ext) ? name : null;
|
||||
}
|
||||
|
||||
route('GET', '/api/events/:id/tether', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event');
|
||||
const folder = tetherFolder(params.id);
|
||||
await fsp.mkdir(folder.dir, { recursive: true });
|
||||
const names = await fsp.readdir(folder.dir).catch(() => []);
|
||||
const files = [];
|
||||
for (const name of names) {
|
||||
if (!tetherFileName(name)) continue;
|
||||
const stat = await fsp.stat(path.join(folder.dir, name)).catch(() => null);
|
||||
if (!stat?.isFile()) continue;
|
||||
files.push({ name, size: stat.size, mtime: stat.mtimeMs });
|
||||
}
|
||||
files.sort((a, b) => a.mtime - b.mtime);
|
||||
json(res, 200, { folder: folder.dir, files });
|
||||
});
|
||||
|
||||
route('GET', '/api/events/:id/tether/file', async ({ req, res, params, url }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event');
|
||||
const name = tetherFileName(url.searchParams.get('name'));
|
||||
if (!name) return error(res, 400, 'No such file');
|
||||
const file = path.join(tetherFolder(params.id).dir, name);
|
||||
const stat = await fsp.stat(file).catch(() => null);
|
||||
if (!stat?.isFile()) return error(res, 404, 'No such file');
|
||||
const mime = normalizePhotoMime('', name);
|
||||
return sendFile(req, res, file, mime, 'no-store', {
|
||||
'Content-Disposition': `attachment; filename="${name}"`,
|
||||
});
|
||||
});
|
||||
|
||||
route('DELETE', '/api/events/:id/tether/file', async ({ req, res, params, url }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event');
|
||||
const name = tetherFileName(url.searchParams.get('name'));
|
||||
if (!name) return error(res, 400, 'No such file');
|
||||
await fsp.unlink(path.join(tetherFolder(params.id).dir, name)).catch(() => undefined);
|
||||
json(res, 200, { ok: true });
|
||||
});
|
||||
|
||||
route('POST', '/api/galleries/:token/comments', async ({ req, res, params }) => {
|
||||
if (!allowGalleryWrite(req, params.token)) {
|
||||
return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' });
|
||||
}
|
||||
if (!eventByShareToken(params.token)) {
|
||||
return error(res, 404, 'This proofing gallery is no longer available');
|
||||
}
|
||||
if (galleryDenied(req, res, params.token)) return;
|
||||
const body = await readJson(req, 32 * 1024);
|
||||
const hit = galleryPhoto(params.token, String(body.photoId ?? ''));
|
||||
if (!hit) return error(res, 404, 'No such photo');
|
||||
@@ -1532,9 +1793,7 @@ route('POST', '/api/galleries/:token/reviews', async ({ req, res, params }) => {
|
||||
if (!allowGalleryWrite(req, params.token)) {
|
||||
return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' });
|
||||
}
|
||||
if (!eventByShareToken(params.token)) {
|
||||
return error(res, 404, 'This proofing gallery is no longer available');
|
||||
}
|
||||
if (galleryDenied(req, res, params.token)) return;
|
||||
const body = await readJson(req, 16 * 1024);
|
||||
const hit = galleryPhoto(params.token, String(body.photoId ?? ''));
|
||||
if (!hit) return error(res, 404, 'No such photo');
|
||||
@@ -1555,9 +1814,7 @@ route('POST', '/api/galleries/:token/picks', async ({ req, res, params }) => {
|
||||
if (!allowGalleryWrite(req, params.token)) {
|
||||
return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' });
|
||||
}
|
||||
if (!eventByShareToken(params.token)) {
|
||||
return error(res, 404, 'This proofing gallery is no longer available');
|
||||
}
|
||||
if (galleryDenied(req, res, params.token)) return;
|
||||
const body = await readJson(req, 32 * 1024);
|
||||
const hit = galleryPhoto(params.token, String(body.photoId ?? ''));
|
||||
if (!hit) return error(res, 404, 'No such photo');
|
||||
@@ -1683,6 +1940,8 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||
const data = await fsp.readFile(target);
|
||||
const decoded = await decodeRaw(data);
|
||||
await writePreview(params.id, decoded.jpeg, decoded.ext);
|
||||
if (decoded.preview16) await writePreview16(params.id, decoded.preview16.data);
|
||||
else await removePreview16(params.id);
|
||||
const info = await jpegInfo(decoded.jpeg);
|
||||
return json(res, 201, {
|
||||
raw: true,
|
||||
@@ -1705,6 +1964,49 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||
return json(res, 201, { raw: false, mime, size });
|
||||
});
|
||||
|
||||
/**
|
||||
* Re-decode a stored RAW with the current pipeline settings. The original is
|
||||
* never touched; only the editable proxy, its thumbnail and the cached denoise
|
||||
* renders are replaced, so existing edits keep working on fresh pixels.
|
||||
*/
|
||||
route('POST', '/api/photos/:id/reprocess', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo');
|
||||
const photo = getPhoto(params.id);
|
||||
if (!photo?.raw) return error(res, 400, 'Only RAW imports can be reprocessed');
|
||||
const original = findOriginal(params.id);
|
||||
if (!original) return error(res, 404, 'The RAW original is missing from storage');
|
||||
try {
|
||||
const decoded = await decodeRaw(await fsp.readFile(original));
|
||||
await writePreview(params.id, decoded.jpeg, decoded.ext);
|
||||
if (decoded.preview16) await writePreview16(params.id, decoded.preview16.data);
|
||||
else await removePreview16(params.id);
|
||||
const thumb = await makeThumb(decoded.jpeg, 560);
|
||||
if (thumb) await writeThumb(params.id, thumb);
|
||||
// The old denoised renders were made from the previous proxy.
|
||||
clearDenoised(params.id);
|
||||
const info = await jpegInfo(decoded.jpeg);
|
||||
const width = info?.width || decoded.width || photo.width;
|
||||
const height = info?.height || decoded.height || photo.height;
|
||||
// Stamp the record so cached previews and thumbnails are fetched again.
|
||||
const previewVersion = Date.now();
|
||||
// Pass the owner explicitly: savePhoto defaults to '' and would orphan the row.
|
||||
savePhoto({ ...photo, width, height, mime: 'image/jpeg', previewVersion }, Date.now(), user.id);
|
||||
json(res, 200, {
|
||||
width,
|
||||
height,
|
||||
engine: decoded.engine,
|
||||
note: decoded.note ?? null,
|
||||
previewVersion,
|
||||
previewUrl: `/api/photos/${params.id}/preview?v=${previewVersion}`,
|
||||
thumbUrl: `/api/photos/${params.id}/thumb?v=${previewVersion}`,
|
||||
});
|
||||
} catch (err) {
|
||||
return error(res, 422, err instanceof Error ? err.message : 'Could not reprocess this RAW file');
|
||||
}
|
||||
});
|
||||
|
||||
route('GET', '/api/photos/:id/thumb', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
@@ -1784,6 +2086,18 @@ route('GET', '/api/photos/:id/preview', async ({ req, res, params }) => {
|
||||
return sendFile(req, res, findOriginal(params.id), 'application/octet-stream');
|
||||
});
|
||||
|
||||
/**
|
||||
* The 16-bit half of a raw proxy. The editor inflates it and uploads it as a
|
||||
* half-float source texture so a heavy grade keeps its precision; the JPEG at
|
||||
* `/preview` stays the fallback when this file is absent or too large to fetch.
|
||||
*/
|
||||
route('GET', '/api/photos/:id/preview16', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found');
|
||||
return sendFile(req, res, findPreview16(params.id), 'image/png');
|
||||
});
|
||||
|
||||
route('POST', '/api/photos/:id/denoise', async ({ req, res, params }) => {
|
||||
const user = currentUser(req);
|
||||
if (!user) return error(res, 401, 'Not signed in');
|
||||
@@ -1892,8 +2206,12 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
|
||||
await writeThumb(params.id, thumb.data);
|
||||
delete record.thumb;
|
||||
}
|
||||
const versionQuery =
|
||||
typeof record.previewVersion === 'number' && Number.isFinite(record.previewVersion)
|
||||
? `?v=${record.previewVersion}`
|
||||
: '';
|
||||
if (record.raw) {
|
||||
record.previewUrl = `/api/photos/${params.id}/preview`;
|
||||
record.previewUrl = `/api/photos/${params.id}/preview${versionQuery}`;
|
||||
const preview = findPreview(params.id);
|
||||
if (!preview) {
|
||||
const original = findOriginal(params.id);
|
||||
@@ -1905,7 +2223,7 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
|
||||
}
|
||||
record.thumbUrl = record.proofAt
|
||||
? `/api/photos/${params.id}/thumb?proof=${record.proofAt}`
|
||||
: `/api/photos/${params.id}/thumb`;
|
||||
: `/api/photos/${params.id}/thumb${versionQuery}`;
|
||||
savePhoto(record, Date.now(), user.id);
|
||||
json(res, 200, { photo: record });
|
||||
});
|
||||
|
||||
+93
-19
@@ -1,5 +1,6 @@
|
||||
import { RAW_PREVIEW_EDGE } from './config.mjs';
|
||||
import { encodeRgb, jpegInfo, loadSharp, toJpegProxy } from './imaging.mjs';
|
||||
import { RAW_16BIT, RAW_PREVIEW_EDGE } from './config.mjs';
|
||||
import { cameraToProxy, readRgbCam } from './color.mjs';
|
||||
import { encodePng16, 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. */
|
||||
@@ -57,12 +58,25 @@ export async function rawEngine() {
|
||||
}
|
||||
|
||||
const DECODE_SETTINGS = {
|
||||
outputBps: 8,
|
||||
// Decode at 16 bits and let LibRaw blend reconstructed highlights instead of
|
||||
// clipping them; the 8-bit proxy is downsampled after the rolloff, so a
|
||||
// recovered sky keeps gradation instead of a flat white patch.
|
||||
outputBps: 16,
|
||||
useCameraWb: true,
|
||||
outputColor: 1, // sRGB
|
||||
// Camera-native, not sRGB: the camera-to-output matrix is applied here in JS
|
||||
// (see color.mjs) and again by the editor on the 16-bit sidecar. That makes
|
||||
// the conversion one swappable matrix instead of a fixed choice inside
|
||||
// LibRaw, which is what a camera profile needs.
|
||||
outputColor: 0,
|
||||
userQual: 3,
|
||||
highlight: 0,
|
||||
noAutoBright: false,
|
||||
highlight: 2,
|
||||
// One white point for the frame, chosen after the matrix. LibRaw's per-path
|
||||
// auto-bright measures each output colourspace separately, so the JPEG and
|
||||
// the camera-native sidecar would disagree by up to half a stop.
|
||||
noAutoBright: true,
|
||||
// Always use the camera's own colour matrix. The default only does so when
|
||||
// white balance is applied, which leaves some bodies on the generic matrix.
|
||||
useCameraMatrix: 3,
|
||||
// Use the orientation stored in the raw container: phone and DSLR files often
|
||||
// record the shot rotated (EXIF 6/8), and demosaicing without it produces a
|
||||
// sideways proxy that no later step can fix without losing the original axes.
|
||||
@@ -70,7 +84,13 @@ const DECODE_SETTINGS = {
|
||||
useFujiRotate: -1,
|
||||
};
|
||||
|
||||
/** Turns one LibRaw `imageData()` result into an interleaved RGB buffer. */
|
||||
/**
|
||||
* Turns one LibRaw `imageData()` result into an interleaved RGB buffer.
|
||||
*
|
||||
* The 8-bit copy is what the JPEG proxy is encoded from. The 16-bit copy keeps
|
||||
* every sample LibRaw produced so the editor can upload a half-float source
|
||||
* texture; without it, a heavy shadow lift is applied to 256 levels per channel.
|
||||
*/
|
||||
function toRgb(img) {
|
||||
if (!img || !img.width || !img.height || !img.data) throw new Error('LibRaw returned no pixels');
|
||||
const width = Number(img.width);
|
||||
@@ -79,19 +99,36 @@ function toRgb(img) {
|
||||
const bits = Number(img.bits ?? 8);
|
||||
const src = img.data;
|
||||
const pixelCount = width * height;
|
||||
const needed = pixelCount * colors * (bits > 8 ? 2 : 1);
|
||||
if (src.length < needed) {
|
||||
throw new Error(`LibRaw buffer too small (${src.length} bytes for ${width}×${height}×${colors})`);
|
||||
const needed = pixelCount * colors;
|
||||
// libraw-wasm hands back samples, not bytes: with outputBps 16 the buffer is a
|
||||
// Uint16Array already. Older builds returned the raw 16-bit bytes, so accept
|
||||
// both shapes instead of assuming one and rejecting every 16-bit decode.
|
||||
const wide =
|
||||
bits > 8 && !(src instanceof Uint16Array)
|
||||
? new Uint16Array(src.buffer, src.byteOffset, Math.floor(src.byteLength / 2))
|
||||
: src;
|
||||
if (wide.length < needed) {
|
||||
throw new Error(
|
||||
`LibRaw buffer too small (${wide.length} samples for ${width}×${height}×${colors})`,
|
||||
);
|
||||
}
|
||||
|
||||
const rgb = Buffer.alloc(pixelCount * 3);
|
||||
let rgb16 = null;
|
||||
if (bits > 8) {
|
||||
const view = new Uint16Array(src.buffer, src.byteOffset, Math.floor(src.byteLength / 2));
|
||||
const view = wide instanceof Uint16Array ? wide : src;
|
||||
rgb16 = new Uint16Array(pixelCount * 3);
|
||||
for (let i = 0; i < pixelCount; i++) {
|
||||
const s = i * colors;
|
||||
rgb[i * 3] = view[s] >> 8;
|
||||
rgb[i * 3 + 1] = view[s + 1] >> 8;
|
||||
rgb[i * 3 + 2] = view[s + 2] >> 8;
|
||||
const r = view[s];
|
||||
const g = view[s + 1];
|
||||
const b = view[s + 2];
|
||||
rgb[i * 3] = r >> 8;
|
||||
rgb[i * 3 + 1] = g >> 8;
|
||||
rgb[i * 3 + 2] = b >> 8;
|
||||
rgb16[i * 3] = r;
|
||||
rgb16[i * 3 + 1] = g;
|
||||
rgb16[i * 3 + 2] = b;
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < pixelCount; i++) {
|
||||
@@ -101,20 +138,29 @@ function toRgb(img) {
|
||||
rgb[i * 3 + 2] = src[s + 2];
|
||||
}
|
||||
}
|
||||
return { rgb, width, height };
|
||||
return { rgb, rgb16, width, height };
|
||||
}
|
||||
|
||||
/**
|
||||
* Full demosaic through a pooled LibRaw worker. `open()` only unpacks the file;
|
||||
* the pixels come from `imageData()`, which rejects when the camera is unsupported.
|
||||
*
|
||||
* `cameraNative` asks for the frame before LibRaw's output matrix, plus the
|
||||
* 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) {
|
||||
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), DECODE_SETTINGS);
|
||||
return toRgb(await lib.imageData());
|
||||
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 };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -163,10 +209,38 @@ export async function decodeRaw(buffer) {
|
||||
let librawError = null;
|
||||
if (looksLikeRaw(buffer)) {
|
||||
try {
|
||||
const { rgb, width, height } = await demosaic(buffer);
|
||||
let frame = await demosaic(buffer, 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 demosaic(buffer, 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.
|
||||
if (rgbCam && frame.rgb16) cameraToProxy(frame.rgb16, frame.rgb, rgbCam);
|
||||
const { rgb } = frame;
|
||||
const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE);
|
||||
// The sidecar must match the JPEG pixel for pixel: the editor swaps 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.
|
||||
let preview16 = null;
|
||||
if (frame.rgb16 && RAW_16BIT) {
|
||||
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),
|
||||
width: encoded.width,
|
||||
height: encoded.height,
|
||||
rgbCam,
|
||||
};
|
||||
} catch {
|
||||
preview16 = null;
|
||||
}
|
||||
}
|
||||
return {
|
||||
jpeg: encoded.data,
|
||||
preview16,
|
||||
width: encoded.width,
|
||||
height: encoded.height,
|
||||
engine: 'libraw',
|
||||
|
||||
@@ -117,6 +117,30 @@ export function findPreview(id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The 16-bit sidecar for a raw proxy: the samples LibRaw decoded, before the
|
||||
* JPEG quantised them. Its name keeps a second extension so `findPreview` keeps
|
||||
* returning the JPEG for browsers and for photos imported before this existed.
|
||||
*/
|
||||
export async function writePreview16(id, data) {
|
||||
ensureDirs();
|
||||
const target = path.join(storageRoot(), 'previews', `${safeId(id)}.p16.png`);
|
||||
await fsp.writeFile(target, data);
|
||||
return target;
|
||||
}
|
||||
|
||||
export function findPreview16(id) {
|
||||
const safe = lookupId(id);
|
||||
if (!safe) return null;
|
||||
const p = path.join(dirs().previews, `${safe}.p16.png`);
|
||||
return fs.existsSync(p) ? p : null;
|
||||
}
|
||||
|
||||
export async function removePreview16(id) {
|
||||
const found = findPreview16(id);
|
||||
if (found) await fsp.rm(found, { force: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Denoised proxies, keyed by the hash of the parameters that produced them, so
|
||||
* switching Amount back to a previous value reuses the file instead of spending
|
||||
@@ -209,6 +233,7 @@ export async function removeAsset(id) {
|
||||
const files = [
|
||||
findOriginal(id),
|
||||
findPreview(id),
|
||||
findPreview16(id),
|
||||
findThumb(id),
|
||||
findProof(id),
|
||||
findProofThumb(id),
|
||||
|
||||
Reference in New Issue
Block a user