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. */ 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); } /** * Standard images that browsers cannot decode. TIFF takes the raw upload path * (store the original, serve a JPEG proxy) but is decoded by sharp, not LibRaw. */ export const SERVER_IMAGE_EXTENSIONS = new Set(['tif', 'tiff']); export function isStillName(name = '') { const ext = name.split('.').pop()?.toLowerCase() ?? ''; 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; 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 decodeStill(buffer) { const proxy = await toJpegProxy(buffer, RAW_PREVIEW_EDGE); if (!proxy) throw new Error('Could not decode this image'); const size = await jpegInfo(proxy.data); return { jpeg: proxy.data, width: size?.width || proxy.width, height: size?.height || proxy.height, engine: 'sharp', ext: proxy.ext, }; } export async function rawEngine() { if (engineState === 'unloaded') { try { await loadLibRaw(); engineState = 'ready'; } catch { engineState = 'missing'; } } return engineState; } const DECODE_SETTINGS = { // 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, // 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: 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. userFlip: -1, useFujiRotate: -1, }; /** * 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); 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; // 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 = wide instanceof Uint16Array ? wide : src; rgb16 = new Uint16Array(pixelCount * 3); for (let i = 0; i < pixelCount; i++) { const s = i * colors; 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++) { 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, 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, 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 }; }); } 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 withTimeout( rawPool.use(async (lib) => { await lib.open(Buffer.from(buffer), { useCameraWb: true }); return lib.thumbnailData(); }), 12000, 'LibRaw preview timed out', ); 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 { let frame = await withTimeout(demosaic(buffer, true), 45000, 'LibRaw timed out on this file'); // 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'); 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', 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(), }; }