import zlib from 'node:zlib'; import { RAW_PREVIEW_EDGE } from './config.mjs'; let sharpModule = null; let sharpFailed = false; /** sharp gives us JPEG encoding and resizing; without it we fall back to PNG. */ export async function loadSharp() { if (sharpModule) return sharpModule; if (sharpFailed) return null; try { const mod = await import('sharp'); sharpModule = mod.default; return sharpModule; } catch { sharpFailed = true; return null; } } const CRC_TABLE = (() => { const table = new Int32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; table[n] = c; } return table; })(); function crc32(buf) { let c = 0xffffffff; for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; } function chunk(type, data) { const out = Buffer.alloc(8 + data.length + 4); out.writeUInt32BE(data.length, 0); out.write(type, 4, 'ascii'); data.copy(out, 8); out.writeUInt32BE(crc32(Buffer.concat([Buffer.from(type, 'ascii'), data])), 8 + data.length); return out; } /** Minimal dependency-free 8-bit RGB PNG encoder (used only when sharp is absent). */ export function encodePng(rgb, width, height) { const stride = width * 3; const raw = Buffer.alloc((stride + 1) * height); for (let y = 0; y < height; y++) { raw[y * (stride + 1)] = 0; Buffer.from(rgb.buffer, rgb.byteOffset + y * stride, stride).copy(raw, y * (stride + 1) + 1); } const idat = zlib.deflateSync(raw, { level: 6 }); const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(width, 0); ihdr.writeUInt32BE(height, 4); ihdr[8] = 8; 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), chunk('IDAT', idat), chunk('IEND', Buffer.alloc(0)), ]); } /** * 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)), ]); } /** The camera matrix carried in a 16-bit sidecar's `rgbCam` tEXt chunk. */ export function png16Matrix(png) { const needle = Buffer.from('rgbCam\0', 'latin1'); const at = png.indexOf(needle); if (at < 0) return null; const start = at + needle.length; // The text runs to the end of the tEXt chunk, and the chunk's CRC is binary // and may contain a NUL. Stop at the first byte that cannot be part of the // comma-separated number list instead of searching for a terminator. let end = start; while (end < png.length) { const code = png[end]; const numeric = (code >= 0x30 && code <= 0x39) || // 0-9 code === 0x2e || // . code === 0x2c || // , code === 0x2d || // - code === 0x2b || // + code === 0x65 || // e code === 0x45; // E if (!numeric) break; end++; } const values = png.toString('latin1', start, end).split(',').map(Number); return values.length === 9 && values.every(Number.isFinite) ? values : null; } /** * A camera-native grid thumbnail, resized from the 16-bit sidecar with sharp's * 16-bit path. The grid normally renders the sRGB JPEG, whose body matrix is * already baked in; this gives the client camera samples small enough to fetch * per tile, so a per-photo DCP profile shows everywhere the photo does. The * `rgbCam` tag is rewritten so the client still knows how to convert them. */ export async function cameraThumb16(png16, width, height, matrix = null) { const sharp = await loadSharp(); if (!sharp || width < 1 || height < 1) return null; try { const { data, info } = await sharp(png16) .resize({ width, height, fit: 'fill' }) .raw({ depth: 'ushort' }) .toBuffer({ resolveWithObject: true }); if (info.channels !== 3 || info.depth !== 'ushort') return null; // Copy through a fresh buffer: a raw output offset is not guaranteed to be // 16-bit aligned, and Uint16Array refuses an odd byteOffset. const samples = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); return encodePng16( new Uint16Array(samples), info.width, info.height, matrix ?? png16Matrix(png16), ); } catch { return null; } } export async function encodeRgb(rgb, width, height, quality = 92, maxEdge = 0) { const sharp = await loadSharp(); if (!sharp) { return { data: encodePng(rgb, width, height), ext: 'png', width, height }; } let img = sharp(Buffer.from(rgb.buffer, rgb.byteOffset, rgb.byteLength), { raw: { width, height, channels: 3 }, }); if (maxEdge > 0 && Math.max(width, height) > maxEdge) img = img.resize({ width: width >= height ? maxEdge : null, height: height > width ? maxEdge : null, fit: 'inside' }); const data = await img.jpeg({ quality, chromaSubsampling: '4:4:4' }).toBuffer(); const meta = await sharp(data).metadata(); return { data, ext: 'jpg', width: Number(meta.width ?? width), height: Number(meta.height ?? height) }; } export async function jpegInfo(buffer) { const sharp = await loadSharp(); if (!sharp) return null; try { const meta = await sharp(buffer).metadata(); return { width: Number(meta.width ?? 0), height: Number(meta.height ?? 0), format: meta.format }; } catch { return null; } } /** Re-encode any decodable image to a normalised JPEG proxy. */ export async function toJpegProxy(buffer, maxEdge = RAW_PREVIEW_EDGE) { const sharp = await loadSharp(); if (!sharp) return null; try { let img = sharp(buffer, { failOn: 'none' }).rotate(); const meta = await img.metadata(); const w = Number(meta.width ?? 0); const h = Number(meta.height ?? 0); if (!w || !h) return null; if (maxEdge > 0 && Math.max(w, h) > maxEdge) img = img.resize({ width: maxEdge, height: maxEdge, fit: 'inside' }); const data = await img.jpeg({ quality: 92, chromaSubsampling: '4:4:4' }).toBuffer(); const outMeta = await sharp(data).metadata(); return { data, width: Number(outMeta.width ?? w), height: Number(outMeta.height ?? h), ext: 'jpg' }; } catch { return null; } } export async function makeThumb(buffer, edge = 512) { const sharp = await loadSharp(); if (!sharp) return null; try { const data = await sharp(buffer, { failOn: 'none' }) .rotate() .resize({ width: edge, height: edge, fit: 'inside', withoutEnlargement: true }) .jpeg({ quality: 82 }) .toBuffer(); return data; } catch { return null; } }