Initial commit: Luminary photo catalog and RAW editor
Browser-based photo catalog with an optional team server (SQLite + LibRaw). Local database, uploaded photos, build output and dependencies are gitignored. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
+214
@@ -0,0 +1,214 @@
|
||||
import { RAW_PREVIEW_EDGE } from './config.mjs';
|
||||
import { encodeRgb, jpegInfo, loadSharp, toJpegProxy } from './imaging.mjs';
|
||||
import { loadLibRaw, rawPool } from './libraw-pool.mjs';
|
||||
|
||||
/** Every raw container the pipeline will attempt, grouped by vendor family. */
|
||||
export const RAW_EXTENSIONS = new Set([
|
||||
// Canon
|
||||
'cr2', 'cr3', 'crw',
|
||||
// Nikon
|
||||
'nef', 'nrw',
|
||||
// Sony
|
||||
'arw', 'srf', 'sr2',
|
||||
// Olympus / OM System
|
||||
'orf',
|
||||
// Panasonic / Leica
|
||||
'rw2', 'raw', 'rwl',
|
||||
// Fujifilm
|
||||
'raf',
|
||||
// Pentax / Ricoh
|
||||
'pef', 'dng',
|
||||
// Samsung, Hasselblad, Leaf, Phase One, Sigma, Epson, Kodak, Minolta
|
||||
'srw', '3fr', 'fff', 'iiq', 'x3f', 'erf', 'k25', 'kdc', 'dcr', 'mos', 'mrw', 'mef', 'sraw',
|
||||
]);
|
||||
|
||||
export function isRawName(name = '') {
|
||||
const ext = name.split('.').pop()?.toLowerCase() ?? '';
|
||||
return RAW_EXTENSIONS.has(ext);
|
||||
}
|
||||
|
||||
/** True when the buffer starts with a container signature LibRaw can open. */
|
||||
export function looksLikeRaw(buffer) {
|
||||
if (!buffer || buffer.length < 64) return false;
|
||||
const hex4 = buffer.subarray(0, 4).toString('hex');
|
||||
const ascii = buffer.subarray(0, 16).toString('latin1');
|
||||
if (hex4 === '49492a00' || hex4 === '4d4d002a') return true; // TIFF family
|
||||
if (hex4 === '4949524f' || hex4 === '4d4d4f52') return true; // ORF
|
||||
if (hex4 === '49495500') return true; // RW2
|
||||
if (hex4 === '49494949') return true; // Phase One IIQ
|
||||
if (ascii.startsWith('FUJIFILMCCD-RAW')) return true; // RAF
|
||||
if (ascii.startsWith('FOVb')) return true; // X3F
|
||||
if (buffer.subarray(4, 8).toString('latin1') === 'ftyp') return true; // CR3
|
||||
return false;
|
||||
}
|
||||
|
||||
let engineState = 'unloaded';
|
||||
|
||||
export async function rawEngine() {
|
||||
if (engineState === 'unloaded') {
|
||||
try {
|
||||
await loadLibRaw();
|
||||
engineState = 'ready';
|
||||
} catch {
|
||||
engineState = 'missing';
|
||||
}
|
||||
}
|
||||
return engineState;
|
||||
}
|
||||
|
||||
const DECODE_SETTINGS = {
|
||||
outputBps: 8,
|
||||
useCameraWb: true,
|
||||
outputColor: 1, // sRGB
|
||||
userQual: 3,
|
||||
highlight: 0,
|
||||
noAutoBright: false,
|
||||
// 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.
|
||||
userFlip: -1,
|
||||
useFujiRotate: -1,
|
||||
};
|
||||
|
||||
/** Turns one LibRaw `imageData()` result into an interleaved RGB buffer. */
|
||||
function toRgb(img) {
|
||||
if (!img || !img.width || !img.height || !img.data) throw new Error('LibRaw returned no pixels');
|
||||
const width = Number(img.width);
|
||||
const height = Number(img.height);
|
||||
const colors = Number(img.colors ?? 3);
|
||||
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 rgb = Buffer.alloc(pixelCount * 3);
|
||||
if (bits > 8) {
|
||||
const view = new Uint16Array(src.buffer, src.byteOffset, Math.floor(src.byteLength / 2));
|
||||
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;
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < pixelCount; i++) {
|
||||
const s = i * colors;
|
||||
rgb[i * 3] = src[s];
|
||||
rgb[i * 3 + 1] = src[s + 1];
|
||||
rgb[i * 3 + 2] = src[s + 2];
|
||||
}
|
||||
}
|
||||
return { rgb, 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.
|
||||
*/
|
||||
async function demosaic(buffer) {
|
||||
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());
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
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;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Camera preview, preferably the one LibRaw knows the offset and length of. */
|
||||
async function embeddedPreview(buffer) {
|
||||
if ((await rawEngine()) === 'ready') {
|
||||
try {
|
||||
const thumb = await rawPool.use(async (lib) => {
|
||||
await lib.open(Buffer.from(buffer), { useCameraWb: true });
|
||||
return lib.thumbnailData();
|
||||
});
|
||||
if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) {
|
||||
return Buffer.from(thumb.data);
|
||||
}
|
||||
} catch {
|
||||
/* fall through to the byte scan */
|
||||
}
|
||||
}
|
||||
return extractEmbeddedJpeg(buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export async function decodeRaw(buffer) {
|
||||
let librawError = null;
|
||||
if (looksLikeRaw(buffer)) {
|
||||
try {
|
||||
const { rgb, width, height } = await demosaic(buffer);
|
||||
const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE);
|
||||
return {
|
||||
jpeg: encoded.data,
|
||||
width: encoded.width,
|
||||
height: encoded.height,
|
||||
engine: 'libraw',
|
||||
ext: encoded.ext,
|
||||
};
|
||||
} catch (err) {
|
||||
librawError = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
} else {
|
||||
librawError = 'not a recognised raw container';
|
||||
}
|
||||
|
||||
const embedded = await embeddedPreview(buffer);
|
||||
if (embedded) {
|
||||
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 };
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Could not decode this raw file. ${librawError ? `LibRaw said: ${librawError}.` : 'LibRaw is not installed.'}`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function rawSupport() {
|
||||
const engine = await rawEngine();
|
||||
const sharp = await loadSharp();
|
||||
return {
|
||||
libraw: engine === 'ready',
|
||||
sharp: Boolean(sharp),
|
||||
workers: rawPool.size,
|
||||
busy: rawPool.stats.busy,
|
||||
formats: [...RAW_EXTENSIONS].sort(),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user