import type { PhotoRecord } from '../types'; import { deleteAsset, getAsset, putAsset } from './db'; import { parsePreview16, type Preview16 } from './preview16'; const CACHE_LIMIT = 6; const cache = new Map(); /** Where to fetch the original (or raw proxy) when it is not cached on this device. */ export function remoteAssetUrl(photo: PhotoRecord): string { if (photo.raw) return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`; return `/api/photos/${encodeURIComponent(photo.id)}/original`; } /** Virtual copies reuse the master's bytes when no local copy exists. */ async function copyAsset(photo: PhotoRecord, id: string): Promise { const own = await getAsset(photo.id); if (own) { if (photo.copyOf) await putAsset(id, own).catch(() => undefined); return own; } if (!photo.copyOf) return undefined; const master = await getAsset(photo.copyOf); if (master) { await putAsset(id, master).catch(() => undefined); return master; } return undefined; } async function fetchRemoteCopy(photo: PhotoRecord): Promise { const direct = await fetchRemote(photo); if (direct || !photo.copyOf) return direct; // A virtual copy has no server file of its own; ask for the master's proxy. try { const master = { ...photo, id: photo.copyOf, copyOf: undefined }; const res = await fetch(remoteAssetUrl(master), { credentials: 'same-origin' }); if (!res.ok) return null; const blob = await res.blob(); await putAsset(photo.id, blob).catch(() => undefined); return blob; } catch { return null; } } async function fetchRemote(photo: PhotoRecord): Promise { try { const res = await fetch(remoteAssetUrl(photo), { credentials: 'same-origin' }); if (!res.ok) return null; const blob = await res.blob(); // Cache it locally so the photo keeps working offline after the first look. await putAsset(photo.id, blob).catch(() => undefined); return blob; } catch { return null; } } /** * Decode upright, falling back for decoders that refuse the orientation option * (a plain decode is better than no frame at all). */ async function decodeBitmap(blob: Blob): Promise { try { return await createImageBitmap(blob, { imageOrientation: 'from-image' }); } catch { return await createImageBitmap(blob); } } export async function getBitmap(photo: PhotoRecord): Promise { const hit = cache.get(photo.id); if (hit) { cache.delete(photo.id); cache.set(photo.id, hit); return hit; } let blob = await copyAsset(photo, photo.id); if (!blob) blob = (await fetchRemoteCopy(photo)) ?? undefined; if (!blob) { throw new Error( photo.raw ? 'This raw file has no editable proxy yet. Sign in to the server and sync to fetch it.' : 'Original image data is missing from browser storage', ); } // Apply EXIF orientation so the pixels the editor works on are upright. // A cached copy can be stale — truncated by an interrupted download, or // written when the server produced a different proxy — and then it decodes // to nothing forever, so one failure drops it and refetches the current bytes. let bitmap: ImageBitmap; try { bitmap = await decodeBitmap(blob); } catch (err) { await deleteAsset(photo.id).catch(() => undefined); const fresh = (await fetchRemoteCopy(photo)) ?? undefined; if (!fresh) throw err; bitmap = await decodeBitmap(fresh); } cache.set(photo.id, bitmap); while (cache.size > CACHE_LIMIT) { const first = cache.keys().next(); if (first.done) break; const old = cache.get(first.value); cache.delete(first.value); old?.close(); } return bitmap; } export function evictBitmap(photoId: string) { const bmp = cache.get(photoId); if (!bmp) return; cache.delete(photoId); bmp.close(); } const hdrCache = new Map(); /** Version stamp from the preview URL, so a reprocess invalidates the sidecar too. */ function preview16Url(photo: PhotoRecord): string { const base = `/api/photos/${encodeURIComponent(photo.id)}/preview16`; const query = (photo.previewUrl ?? '').split('?')[1]; return query ? `${base}?${query}` : base; } /** * The 16-bit samples behind a raw proxy, or null when there are none. * * Null is normal, not an error: photos imported before the sidecar existed, * non-raw files and oversized fetches all end up grading the JPEG. Only a 404 * is remembered, so a dropped connection is retried on the next look. */ export async function get16BitSource(photo: PhotoRecord): Promise { if (!photo.raw) return null; const hit = hdrCache.get(photo.id); if (hit !== undefined) return hit; let parsed: Preview16 | null = null; let missing = false; try { const res = await fetch(preview16Url(photo), { credentials: 'same-origin' }); if (!res.ok) { missing = true; } else { parsed = await parsePreview16(await res.arrayBuffer()); missing = parsed === null; } } catch { return null; } if (parsed) { hdrCache.set(photo.id, parsed); // Each sidecar is up to ~100 MB of typed array, so only the last two stay. while (hdrCache.size > 2) { const first = hdrCache.keys().next(); if (first.done) break; hdrCache.delete(first.value); } } else if (missing) { hdrCache.set(photo.id, null); } return parsed; } const cameraThumbCache = new Map(); /** * Camera-native grid thumbnail for a raw, or null when the server has none. * * The grid otherwise renders the sRGB JPEG, whose body matrix is already baked * in, so a loaded DCP profile would only show in Develop. This is the sidecar * resized to the JPEG thumbnail's dimensions, small enough to fetch per tile; * null (a normal state for older imports) falls back to the JPEG. */ export async function getCameraThumb(photo: PhotoRecord): Promise { if (!photo.raw) return null; const key = `${photo.id}|${photo.previewVersion ?? 0}`; const hit = cameraThumbCache.get(key); if (hit !== undefined) return hit; try { const res = await fetch(`/api/photos/${encodeURIComponent(photo.id)}/thumb16`, { credentials: 'same-origin', }); if (!res.ok) { cameraThumbCache.set(key, null); return null; } const parsed = await parsePreview16(await res.arrayBuffer()); cameraThumbCache.set(key, parsed); while (cameraThumbCache.size > 12) { const first = cameraThumbCache.keys().next(); if (first.done) break; cameraThumbCache.delete(first.value); } return parsed; } catch { // A dropped connection is retried on the next tile, not cached as missing. return null; } } export function clearBitmapCache() { cameraThumbCache.clear(); for (const bmp of cache.values()) bmp.close(); cache.clear(); for (const bmp of denoisedCache.values()) bmp.close(); denoisedCache.clear(); hdrCache.clear(); } const denoisedCache = new Map(); /** * The server-rendered denoised proxy for an edit's `aiDenoise.key`. * * These are separate files from the edit and cost a few seconds to produce, so * they are cached by key and never re-fetched while the key stays the same. * Returns null when the asset is gone (cache pruned, storage moved), which the * caller treats as "no denoise". */ export async function getDenoisedBitmap(photo: PhotoRecord, key: string): Promise { const sig = `${photo.id}:${key}`; const hit = denoisedCache.get(sig); if (hit) return hit; try { const res = await fetch( `/api/photos/${encodeURIComponent(photo.id)}/denoised?v=${encodeURIComponent(key)}`, { credentials: 'same-origin' }, ); if (!res.ok) return null; const bitmap = await createImageBitmap(await res.blob(), { imageOrientation: 'from-image' }); denoisedCache.set(sig, bitmap); while (denoisedCache.size > 4) { const first = denoisedCache.keys().next(); if (first.done) break; denoisedCache.get(first.value)?.close(); denoisedCache.delete(first.value); } return bitmap; } catch { return null; } }