import { RAW_16BIT, RAW_PREVIEW_EDGE, RAW_TIMEOUT_MS, RAW_XTRANS_QUALITY } from './config.mjs'; import { cameraToProxy, readRgbCam } from './color.mjs'; import { encodePng16Async, 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); } /** 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. */ /** * Fujifilm bodies that are *not* X-Trans: the Bayer-sensor GFX and X-A/T100/T200 * lines, plus the old FinePix compacts. Everyone else in the X series uses the * 6x6 colour filter array. */ function isXTrans(make, model) { if (!/fuji/i.test(String(make ?? ''))) return false; const m = String(model ?? '').trim(); if (/^(gfx|finepix)/i.test(m)) return false; if (/^x-(a\d|t100|t200)\b/i.test(m)) return false; return /^x/i.test(m); } /** * Demosaic one frame. On X-Trans the `userQual` setting counts Markesteijn * passes, and LibRaw's 3-pass default is the single most expensive thing this * pipeline does: 49.9 s on a 40 MP X-T5 frame here, against 8.8 s for one pass, * which pushed every Fuji import into the decode timeout (and, under a parallel * import, every file at once). The proxy is downsampled to RAW_PREVIEW_EDGE, so * the extra passes were being thrown away by the resize anyway. * * The model is only known after the container is opened, and opening is ~0.2 s, * so the file is re-opened with the cheaper setting rather than guessing from * the filename. */ async function demosaic(buffer, { cameraNative = true } = {}) { if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed'); return rawPool.use( async (lib) => { const settings = cameraNative ? DECODE_SETTINGS : { ...DECODE_SETTINGS, outputColor: 1, noAutoBright: false }; // 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), settings); if (settings.userQual > RAW_XTRANS_QUALITY) { const info = await lib.metadata(); if (isXTrans(info?.camera_make, info?.camera_model)) { await lib.open(Buffer.from(buffer), { ...settings, userQual: RAW_XTRANS_QUALITY }); } } const image = toRgb(await lib.imageData()); const rgbCam = cameraNative ? readRgbCam(await lib.metadata(true)) : null; return { ...image, rgbCam }; }, { timeoutMs: RAW_TIMEOUT_MS, label: 'LibRaw' }, ); } const SOI = Buffer.from([0xff, 0xd8, 0xff]); const EOI = Buffer.from([0xff, 0xd9]); /** * Every embedded JPEG in a raw container, largest first. * * A single scan can land on a thumbnail's end-of-image and cut the file short: * that produced a "preview" sharp refused to decode, which was then stored as a * 0x0 JPEG. Callers walk the list and keep the first candidate that really * decodes. */ export function extractEmbeddedJpegs(buffer) { const starts = []; let at = 0; while (starts.length < 64) { const start = buffer.indexOf(SOI, at); if (start < 0) break; starts.push(start); at = start + 3; } const found = []; for (const start of starts) { // Several end-of-image markers can follow one start: a preview that carries // its own EXIF thumbnail ends twice. Take a few candidates per start and let // the decoder pick, instead of committing to the first marker found. let from = start + 3; for (let attempt = 0; attempt < 3; attempt++) { const end = buffer.indexOf(EOI, from); if (end < 0) break; if (end + 2 - start > 4096) found.push(buffer.subarray(start, end + 2)); from = end + 2; } } return found.sort((a, b) => b.length - a.length); } /** The largest embedded JPEG, for callers that want one candidate. */ export function extractEmbeddedJpeg(buffer) { return extractEmbeddedJpegs(buffer)[0] ?? null; } /** Camera previews, best first: the one LibRaw knows about, then byte-scanned. */ async function embeddedPreviews(buffer) { const candidates = []; if ((await rawEngine()) === 'ready') { try { const thumb = await rawPool.use( async (lib) => { await lib.open(Buffer.from(buffer), { useCameraWb: true }); return lib.thumbnailData(); }, { timeoutMs: 20000, label: 'LibRaw preview' }, ); if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) { candidates.push(Buffer.from(thumb.data)); } } catch { /* fall through to the byte scan */ } } candidates.push(...extractEmbeddedJpegs(buffer)); return candidates; } /** * 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. * * `sidecar` writes the 16-bit samples beside the JPEG. It defaults to the * server setting, and the import dialog can turn it off for one import: an * 8-bit import decodes exactly the same, it just skips the second encode and the * tens of megabytes of disk it costs. */ export async function decodeRaw(buffer, { sidecar = RAW_16BIT } = {}) { let librawError = null; if (looksLikeRaw(buffer)) { try { let frame = await demosaic(buffer, { cameraNative: 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, { cameraNative: 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 && sidecar) { 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: await encodePng16Async(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'; } // Keep the first candidate that sharp can actually decode. Never store bytes // that did not decode: a 0x0 "preview" is an unopenable photo in the catalog. // A handful of candidates is enough; each rejected one costs a header parse, // not a full decode. for (const embedded of (await embeddedPreviews(buffer)).slice(0, 6)) { const proxy = await toJpegProxy(embedded, RAW_PREVIEW_EDGE); if (!proxy) continue; const size = await jpegInfo(proxy.data); const width = size?.width || proxy.width; const height = size?.height || proxy.height; if (!width || !height) continue; return { jpeg: proxy.data, width, height, engine: 'embedded', ext: proxy.ext, note: `LibRaw could not decode this file (${librawError}); using the camera preview.`, }; } 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(), }; }