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:
+585
@@ -0,0 +1,585 @@
|
||||
import type { EventRecord, PhotoRecord, Preset } from '../types';
|
||||
|
||||
export interface Health {
|
||||
ok: boolean;
|
||||
app: string;
|
||||
version: string;
|
||||
needsSetup: boolean;
|
||||
registrationOpen: boolean;
|
||||
photos: number;
|
||||
bytes: number;
|
||||
storage?: { root: string; custom: boolean };
|
||||
raw: { libraw: boolean; sharp: boolean; formats: string[] };
|
||||
}
|
||||
|
||||
export interface SessionUser {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: string;
|
||||
}
|
||||
|
||||
export interface UploadResult {
|
||||
raw: boolean;
|
||||
engine?: 'libraw' | 'embedded';
|
||||
width?: number;
|
||||
height?: number;
|
||||
mime?: string;
|
||||
size?: number;
|
||||
previewUrl?: string;
|
||||
thumbUrl?: string;
|
||||
note?: string | null;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
constructor(message: string, status: number) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(path, { credentials: 'same-origin', ...init });
|
||||
} catch {
|
||||
throw new ApiError('Cannot reach the Luminary server', 0);
|
||||
}
|
||||
if (!res.ok) {
|
||||
let message = `Request failed (${res.status})`;
|
||||
try {
|
||||
const body = (await res.json()) as { error?: string };
|
||||
if (body?.error) message = body.error;
|
||||
} catch {
|
||||
/* non-JSON error body */
|
||||
}
|
||||
throw new ApiError(message, res.status);
|
||||
}
|
||||
if (res.status === 204) return undefined as T;
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
function jsonBody(payload: unknown): RequestInit {
|
||||
return {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
};
|
||||
}
|
||||
|
||||
/** Returns null when the app is running without a server (pure browser library). */
|
||||
export async function getHealth(): Promise<Health | null> {
|
||||
try {
|
||||
const res = await fetch('/api/health', { credentials: 'same-origin' });
|
||||
if (!res.ok) return null;
|
||||
const body = (await res.json()) as Health;
|
||||
return body?.ok ? body : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function register(input: {
|
||||
email: string;
|
||||
password: string;
|
||||
name?: string;
|
||||
invite?: string;
|
||||
inviteToken?: string;
|
||||
}): Promise<SessionUser> {
|
||||
const res = await request<{ user: SessionUser }>('/api/auth/register', jsonBody(input));
|
||||
return res.user;
|
||||
}
|
||||
|
||||
export async function login(email: string, password: string): Promise<SessionUser> {
|
||||
const res = await request<{ user: SessionUser }>('/api/auth/login', jsonBody({ email, password }));
|
||||
return res.user;
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
await request('/api/auth/logout', { method: 'POST' });
|
||||
}
|
||||
|
||||
export async function currentUser(): Promise<SessionUser | null> {
|
||||
try {
|
||||
const res = await request<{ user: SessionUser }>('/api/auth/me');
|
||||
return res.user;
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 401) return null;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ProofSummary {
|
||||
photoId: string;
|
||||
eventId: string;
|
||||
count: number;
|
||||
clients: string[];
|
||||
comments?: number;
|
||||
approved?: number;
|
||||
changes?: number;
|
||||
}
|
||||
|
||||
export interface SyncPayload {
|
||||
user: SessionUser;
|
||||
events: EventRecord[];
|
||||
photos: PhotoRecord[];
|
||||
presets: Preset[];
|
||||
proofs?: ProofSummary[];
|
||||
}
|
||||
|
||||
export function pullAll(): Promise<SyncPayload> {
|
||||
return request<SyncPayload>('/api/sync');
|
||||
}
|
||||
|
||||
export function pullProofs(): Promise<ProofSummary[]> {
|
||||
return request<{ proofs: ProofSummary[] }>('/api/proofs').then((res) => res.proofs ?? []);
|
||||
}
|
||||
|
||||
export function uploadOriginal(id: string, file: File | Blob, name: string): Promise<UploadResult> {
|
||||
const query = new URLSearchParams({ name, mime: file.type || 'application/octet-stream' });
|
||||
return request<UploadResult>(`/api/photos/${encodeURIComponent(id)}/original?${query}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/octet-stream' },
|
||||
body: file,
|
||||
});
|
||||
}
|
||||
|
||||
export function pushPhoto(photo: PhotoRecord): Promise<PhotoRecord> {
|
||||
return request<{ photo: PhotoRecord }>(`/api/photos/${encodeURIComponent(photo.id)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(photo),
|
||||
}).then((res) => res.photo);
|
||||
}
|
||||
|
||||
export interface ProofUpload {
|
||||
proofAt: number;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
thumbUrl: string;
|
||||
}
|
||||
|
||||
/** Upload a rendered (edited) proof for the client gallery and owner grid. */
|
||||
export interface DenoiseJob {
|
||||
id: string;
|
||||
key: string;
|
||||
state: 'running' | 'done' | 'error';
|
||||
ms: number | null;
|
||||
error: string | null;
|
||||
url: string | null;
|
||||
/** Reported by a job that found the render already on disk. */
|
||||
cached?: boolean;
|
||||
stats: { amount: number; autoGate: number; gate: number; noise: number; baseWidth: number } | null;
|
||||
}
|
||||
|
||||
/** Starts a server-side denoise job; the work runs off the request thread. */
|
||||
export function startDenoise(photoId: string): Promise<{ jobId: string }> {
|
||||
return request(`/api/photos/${encodeURIComponent(photoId)}/denoise`, { method: 'POST' });
|
||||
}
|
||||
|
||||
/** Drops the rendered files for a photo; the next run renders from scratch. */
|
||||
export function clearDenoised(photoId: string): Promise<void> {
|
||||
return request(`/api/photos/${encodeURIComponent(photoId)}/denoised`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function getDenoiseJob(jobId: string): Promise<DenoiseJob> {
|
||||
return request(`/api/denoise/jobs/${encodeURIComponent(jobId)}`);
|
||||
}
|
||||
|
||||
export function pushProof(id: string, jpegBase64: string): Promise<ProofUpload> {
|
||||
return request<ProofUpload>(`/api/photos/${encodeURIComponent(id)}/proof`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ jpeg: jpegBase64 }),
|
||||
});
|
||||
}
|
||||
|
||||
export function deletePhotoRemote(id: string): Promise<void> {
|
||||
return request(`/api/photos/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function pushEvent(event: EventRecord): Promise<EventRecord> {
|
||||
return request<{ event: EventRecord }>(`/api/events/${encodeURIComponent(event.id)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(event),
|
||||
}).then((res) => res.event);
|
||||
}
|
||||
|
||||
export function deleteEventRemote(id: string): Promise<void> {
|
||||
return request(`/api/events/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ proofing api */
|
||||
|
||||
export interface ShareFeedback {
|
||||
kind: 'comment' | 'approved' | 'changes';
|
||||
photoId: string;
|
||||
clientName: string;
|
||||
body?: string;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export interface ShareState {
|
||||
token: string | null;
|
||||
picks: { photoId: string; clientName: string }[];
|
||||
feedback?: ShareFeedback[];
|
||||
}
|
||||
|
||||
export interface GalleryComment {
|
||||
id: string;
|
||||
clientName: string;
|
||||
body: string;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export interface GalleryPhoto {
|
||||
id: string;
|
||||
name: string;
|
||||
width: number;
|
||||
height: number;
|
||||
takenAt: number | null;
|
||||
thumbUrl: string;
|
||||
previewUrl: string;
|
||||
pickCount: number;
|
||||
mine: boolean;
|
||||
comments: GalleryComment[];
|
||||
reviewStatus: 'approved' | 'changes' | null;
|
||||
}
|
||||
|
||||
export interface GalleryPayload {
|
||||
event: { name: string; date: number | null; notes: string };
|
||||
photographer: string;
|
||||
photos: GalleryPhoto[];
|
||||
picks: { total: number; clients: number };
|
||||
}
|
||||
|
||||
export function getShare(eventId: string): Promise<ShareState> {
|
||||
return request<ShareState>(`/api/events/${encodeURIComponent(eventId)}/share`);
|
||||
}
|
||||
|
||||
export function createShare(eventId: string): Promise<string> {
|
||||
return request<{ token: string }>(`/api/events/${encodeURIComponent(eventId)}/share`, {
|
||||
method: 'POST',
|
||||
}).then((res) => res.token);
|
||||
}
|
||||
|
||||
export function galleryDownloadUrl(token: string, photoId: string): string {
|
||||
return `/api/galleries/${encodeURIComponent(token)}/photos/${encodeURIComponent(photoId)}/download`;
|
||||
}
|
||||
|
||||
export function galleryDownloadAllUrl(token: string, clientId: string): string {
|
||||
const query = new URLSearchParams({ client: clientId });
|
||||
return `/api/galleries/${encodeURIComponent(token)}/download-all?${query}`;
|
||||
}
|
||||
|
||||
export function revokeShare(eventId: string): Promise<void> {
|
||||
return request(`/api/events/${encodeURIComponent(eventId)}/share`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
/** Public, session-free gallery load. */
|
||||
export function loadGallery(token: string, clientId: string): Promise<GalleryPayload> {
|
||||
const query = new URLSearchParams({ client: clientId });
|
||||
return request<GalleryPayload>(`/api/galleries/${encodeURIComponent(token)}?${query}`);
|
||||
}
|
||||
|
||||
export function setGalleryPick(
|
||||
token: string,
|
||||
input: { photoId: string; picked: boolean; clientId: string; clientName: string },
|
||||
): Promise<void> {
|
||||
return request(`/api/galleries/${encodeURIComponent(token)}/picks`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function addGalleryComment(
|
||||
token: string,
|
||||
input: { photoId: string; clientId: string; clientName: string; body: string },
|
||||
): Promise<GalleryComment> {
|
||||
return request<{ comment: GalleryComment }>(`/api/galleries/${encodeURIComponent(token)}/comments`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
}).then((res) => res.comment);
|
||||
}
|
||||
|
||||
export function setGalleryReview(
|
||||
token: string,
|
||||
input: {
|
||||
photoId: string;
|
||||
clientId: string;
|
||||
clientName: string;
|
||||
status: 'approved' | 'changes' | 'none';
|
||||
},
|
||||
): Promise<void> {
|
||||
return request(`/api/galleries/${encodeURIComponent(token)}/reviews`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- admin api */
|
||||
|
||||
export interface AdminUser {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: string;
|
||||
disabled: boolean;
|
||||
createdAt: number | null;
|
||||
}
|
||||
|
||||
export interface AdminEvent {
|
||||
id: string;
|
||||
name: string;
|
||||
createdAt: number | null;
|
||||
photos: number;
|
||||
bytes: number;
|
||||
ownerId: string;
|
||||
ownerEmail: string;
|
||||
}
|
||||
|
||||
export interface AdminInvite {
|
||||
token: string;
|
||||
email: string;
|
||||
role: string;
|
||||
status: 'pending' | 'accepted' | 'expired' | 'revoked';
|
||||
createdAt: number | null;
|
||||
expiresAt: number | null;
|
||||
acceptedAt: number | null;
|
||||
acceptedBy: string | null;
|
||||
revokedAt: number | null;
|
||||
}
|
||||
|
||||
export interface InviteInfo {
|
||||
status: AdminInvite['status'];
|
||||
email: string;
|
||||
role: string;
|
||||
expiresAt: number | null;
|
||||
}
|
||||
|
||||
export interface QuotaPlanEvent {
|
||||
id: string;
|
||||
name: string;
|
||||
createdAt: number;
|
||||
photos: string[];
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
export interface QuotaPlanPhoto {
|
||||
id: string;
|
||||
name: string;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
export interface QuotaPlan {
|
||||
targetBytes: number;
|
||||
usedBytes: number;
|
||||
projectedBytes: number;
|
||||
freedBytes: number;
|
||||
events: QuotaPlanEvent[];
|
||||
photos: QuotaPlanPhoto[];
|
||||
}
|
||||
|
||||
export interface QuotaState {
|
||||
userId: string;
|
||||
limit: number;
|
||||
used: number;
|
||||
remaining: number;
|
||||
ratio: number;
|
||||
percent: number;
|
||||
warn: boolean;
|
||||
over: boolean;
|
||||
warnAt: number;
|
||||
pruneAt: number | null;
|
||||
prunePlan: QuotaPlan | null;
|
||||
pruneNotifiedAt: number | null;
|
||||
lastWarningAt: number | null;
|
||||
}
|
||||
|
||||
export interface AdminQuota extends QuotaState {
|
||||
user: AdminUser;
|
||||
plan: QuotaPlan;
|
||||
}
|
||||
|
||||
export interface MailStatus {
|
||||
configured: boolean;
|
||||
source: 'admin' | 'environment' | 'none';
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
user: string;
|
||||
from: string;
|
||||
hasPassword: boolean;
|
||||
gmail: boolean;
|
||||
}
|
||||
|
||||
export interface AdminOverview {
|
||||
users: AdminUser[];
|
||||
events: AdminEvent[];
|
||||
invites: AdminInvite[];
|
||||
totals: { users: number; photos: number; bytes: number; pendingInvites: number };
|
||||
storage: { root: string; defaultRoot: string; custom: boolean; diskBytes?: number };
|
||||
quotas: AdminQuota[];
|
||||
mail: MailStatus;
|
||||
}
|
||||
|
||||
export interface StorageChange {
|
||||
root: string;
|
||||
previous: string;
|
||||
files: number;
|
||||
bytes: number;
|
||||
moved: boolean;
|
||||
photos: number;
|
||||
}
|
||||
|
||||
export function loadInvite(token: string): Promise<InviteInfo> {
|
||||
return request<InviteInfo>(`/api/invites/${encodeURIComponent(token)}`);
|
||||
}
|
||||
|
||||
export function adminCreateInvite(input: {
|
||||
email: string;
|
||||
role: string;
|
||||
days: number;
|
||||
}): Promise<AdminInvite> {
|
||||
return request<{ invite: AdminInvite }>('/api/admin/invites', jsonBody(input)).then(
|
||||
(res) => res.invite,
|
||||
);
|
||||
}
|
||||
|
||||
export function adminRevokeInvite(token: string): Promise<void> {
|
||||
return request(`/api/admin/invites/${encodeURIComponent(token)}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function adminOverview(): Promise<AdminOverview> {
|
||||
return request<AdminOverview>('/api/admin/overview');
|
||||
}
|
||||
|
||||
export function adminCreateUser(input: {
|
||||
email: string;
|
||||
name: string;
|
||||
password: string;
|
||||
role: string;
|
||||
}): Promise<AdminUser> {
|
||||
return request<{ user: AdminUser }>('/api/admin/users', jsonBody(input)).then((res) => res.user);
|
||||
}
|
||||
|
||||
export function adminUpdateUser(
|
||||
id: string,
|
||||
patch: { name?: string; role?: string; disabled?: boolean; password?: string },
|
||||
): Promise<AdminUser> {
|
||||
return request<{ user: AdminUser }>(`/api/admin/users/${encodeURIComponent(id)}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(patch),
|
||||
}).then((res) => res.user);
|
||||
}
|
||||
|
||||
export function adminDeleteUser(id: string): Promise<void> {
|
||||
return request(`/api/admin/users/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function adminRenameEvent(id: string, name: string): Promise<void> {
|
||||
return request(`/api/admin/events/${encodeURIComponent(id)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name }),
|
||||
});
|
||||
}
|
||||
|
||||
export function adminDeleteEvent(id: string): Promise<{ photos: number }> {
|
||||
return request<{ photos: number }>(`/api/admin/events/${encodeURIComponent(id)}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
}
|
||||
|
||||
export interface CatalogBackup {
|
||||
kind: 'lumenroom-catalog';
|
||||
version: number;
|
||||
generatedAt: number;
|
||||
events: EventRecord[];
|
||||
photos: PhotoRecord[];
|
||||
kv: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function adminRestoreCatalog(
|
||||
catalog: CatalogBackup,
|
||||
): Promise<{ ok: boolean; events: number; photos: number }> {
|
||||
return request('/api/admin/catalog', jsonBody(catalog));
|
||||
}
|
||||
|
||||
export function adminStorage(): Promise<StorageChange & { defaultRoot: string; custom: boolean }> {
|
||||
return request('/api/admin/storage');
|
||||
}
|
||||
|
||||
export function getQuota(): Promise<QuotaState> {
|
||||
return request<QuotaState>('/api/quota');
|
||||
}
|
||||
|
||||
export function adminSetQuota(userId: string, bytes: number): Promise<QuotaState> {
|
||||
return request<{ quota: QuotaState }>(`/api/admin/quotas/${encodeURIComponent(userId)}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ bytes }),
|
||||
}).then((res) => res.quota);
|
||||
}
|
||||
|
||||
export function adminSchedulePrune(
|
||||
userId: string,
|
||||
): Promise<{ pruneAt: number; plan: QuotaPlan; warningSent: boolean }> {
|
||||
return request(`/api/admin/quotas/${encodeURIComponent(userId)}/prune`, { method: 'POST' });
|
||||
}
|
||||
|
||||
export function adminCancelPrune(userId: string): Promise<QuotaState> {
|
||||
return request<{ quota: QuotaState }>(`/api/admin/quotas/${encodeURIComponent(userId)}/prune`, {
|
||||
method: 'DELETE',
|
||||
}).then((res) => res.quota);
|
||||
}
|
||||
|
||||
export function adminWarnUser(userId: string): Promise<QuotaState> {
|
||||
return request<{ quota: QuotaState }>(`/api/admin/quotas/${encodeURIComponent(userId)}/warn`, {
|
||||
method: 'POST',
|
||||
}).then((res) => res.quota);
|
||||
}
|
||||
|
||||
export function adminGetMail(): Promise<MailStatus> {
|
||||
return request<{ mail: MailStatus }>('/api/admin/mail').then((res) => res.mail);
|
||||
}
|
||||
|
||||
export function adminSaveMail(input: {
|
||||
user: string;
|
||||
appPassword: string;
|
||||
from: string;
|
||||
host?: string;
|
||||
port?: number;
|
||||
}): Promise<MailStatus> {
|
||||
return request<{ mail: MailStatus }>('/api/admin/mail', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
}).then((res) => res.mail);
|
||||
}
|
||||
|
||||
export function adminTestMail(to?: string): Promise<{ ok: boolean; to: string }> {
|
||||
return request('/api/admin/mail/test', jsonBody(to ? { to } : {}));
|
||||
}
|
||||
|
||||
export function adminSetStorage(root: string): Promise<StorageChange> {
|
||||
return request<StorageChange>('/api/admin/storage', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ root }),
|
||||
});
|
||||
}
|
||||
|
||||
export function pushPresets(presets: Preset[]): Promise<void> {
|
||||
return request('/api/presets', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ presets }),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { Edits } from '../types';
|
||||
import { clamp } from './curves';
|
||||
|
||||
interface Stats {
|
||||
mean: number;
|
||||
p05: number;
|
||||
p95: number;
|
||||
saturation: number;
|
||||
}
|
||||
|
||||
async function analyze(thumb: string): Promise<Stats> {
|
||||
const img = new Image();
|
||||
img.src = thumb;
|
||||
await img.decode();
|
||||
const w = 96;
|
||||
const h = Math.max(1, Math.round((img.height / img.width) * w)) || 96;
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) throw new Error('Canvas unavailable');
|
||||
ctx.drawImage(img, 0, 0, w, h);
|
||||
const { data } = ctx.getImageData(0, 0, w, h);
|
||||
const hist = new Uint32Array(256);
|
||||
let total = 0;
|
||||
let lumaSum = 0;
|
||||
let satSum = 0;
|
||||
for (let i = 0; i < data.length; i += 4) {
|
||||
const r = data[i] / 255;
|
||||
const g = data[i + 1] / 255;
|
||||
const b = data[i + 2] / 255;
|
||||
const l = 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
hist[Math.round(l * 255)]++;
|
||||
lumaSum += l;
|
||||
satSum += Math.max(r, g, b) - Math.min(r, g, b);
|
||||
total++;
|
||||
}
|
||||
const percentile = (p: number) => {
|
||||
const target = total * p;
|
||||
let acc = 0;
|
||||
for (let i = 0; i < 256; i++) {
|
||||
acc += hist[i];
|
||||
if (acc >= target) return i / 255;
|
||||
}
|
||||
return 1;
|
||||
};
|
||||
return {
|
||||
mean: lumaSum / total,
|
||||
p05: percentile(0.05),
|
||||
p95: percentile(0.95),
|
||||
saturation: satSum / total,
|
||||
};
|
||||
}
|
||||
|
||||
/** Simple histogram based auto tone, in the spirit of Lightroom's Auto button. */
|
||||
export async function computeAutoEdits(thumb: string): Promise<Partial<Edits>> {
|
||||
try {
|
||||
const s = await analyze(thumb);
|
||||
const mean = clamp(s.mean, 0.03, 0.97);
|
||||
const exposure = clamp(Math.log2(0.46 / mean), -2, 2);
|
||||
return {
|
||||
exposure: Math.round(exposure * 100) / 100,
|
||||
contrast: s.p95 - s.p05 < 0.55 ? 18 : 10,
|
||||
highlights: s.p95 > 0.94 ? -32 : 4,
|
||||
shadows: s.p05 < 0.055 ? 32 : 4,
|
||||
whites: s.p95 > 0.96 ? -8 : 10,
|
||||
blacks: s.p05 < 0.03 ? 6 : -6,
|
||||
vibrance: s.saturation < 0.18 ? 18 : 8,
|
||||
};
|
||||
} catch {
|
||||
return { contrast: 12, shadows: 12, highlights: -12, vibrance: 8 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { RasterMask } from '../types';
|
||||
|
||||
export type AutoMaskKind = 'subject' | 'sky' | 'background';
|
||||
|
||||
/**
|
||||
* On-device mask estimation for the three selections that matter most in an
|
||||
* event edit: the subject, the sky and the background around the subject.
|
||||
*
|
||||
* The estimator works from a downsampled preview. It combines distance from
|
||||
* the border colour (the usual studio/event background) with a centre bias,
|
||||
* saturation and a vertical sky prior. This is intentionally lightweight: it
|
||||
* has no model download and produces a low-resolution raster that the normal
|
||||
* mask pipeline feathers and scales. The output is editable like any brush
|
||||
* mask, so a missed edge can be fixed without another model pass.
|
||||
*/
|
||||
export async function buildAutoMask(bitmap: ImageBitmap, kind: AutoMaskKind): Promise<RasterMask> {
|
||||
const width = Math.max(128, Math.min(320, Math.round(bitmap.width / 16)));
|
||||
const height = Math.max(48, Math.round((width * bitmap.height) / Math.max(1, bitmap.width)));
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||
if (!ctx) throw new Error('Could not analyse the image for a mask');
|
||||
ctx.drawImage(bitmap, 0, 0, width, height);
|
||||
const image = ctx.getImageData(0, 0, width, height);
|
||||
const data = image.data;
|
||||
const count = width * height;
|
||||
|
||||
const subject = new Float32Array(count);
|
||||
const sky = new Float32Array(count);
|
||||
const border = borderColor(data, width, height);
|
||||
|
||||
for (let y = 0; y < height; y++) {
|
||||
const ny = y / Math.max(1, height - 1);
|
||||
for (let x = 0; x < width; x++) {
|
||||
const i = y * width + x;
|
||||
const o = i * 4;
|
||||
const r = data[o] / 255;
|
||||
const g = data[o + 1] / 255;
|
||||
const b = data[o + 2] / 255;
|
||||
const dist = Math.min(1, Math.sqrt((r - border[0]) ** 2 + (g - border[1]) ** 2 + (b - border[2]) ** 2) / 1.35);
|
||||
const center = 1 - Math.min(1, Math.sqrt(((x / width - 0.5) * 1.7) ** 2 + ((y / height - 0.5) * 1.35) ** 2));
|
||||
const maxc = Math.max(r, g, b);
|
||||
const minc = Math.min(r, g, b);
|
||||
const sat = maxc > 0.001 ? (maxc - minc) / maxc : 0;
|
||||
const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
subject[i] = dist * 0.58 + center * 0.27 + sat * 0.1 + (1 - Math.abs(luma - 0.48)) * 0.05;
|
||||
const blue = Math.max(0, b - (r + g) * 0.5);
|
||||
sky[i] = blue * 2.5 + Math.max(0, luma - 0.4) * 0.5 + (1 - ny) * 0.28 - (1 - sat) * 0.08;
|
||||
}
|
||||
}
|
||||
|
||||
const raw = kind === 'sky' ? sky : subject;
|
||||
const sorted = [...raw].sort((a, b) => a - b);
|
||||
const median = sorted[Math.floor(sorted.length * 0.5)] ?? 0;
|
||||
const high = sorted[Math.floor(sorted.length * 0.82)] ?? 1;
|
||||
const threshold = kind === 'sky' ? Math.max(0.35, median) : Math.max(0.36, median + (high - median) * 0.22);
|
||||
const mask = new Uint8Array(count);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const on = raw[i] >= threshold;
|
||||
mask[i] = (kind === 'background' ? !on : on) ? 255 : 0;
|
||||
}
|
||||
smooth(mask, width, height);
|
||||
smooth(mask, width, height);
|
||||
|
||||
return { data: encodeBase64(mask), width, height };
|
||||
}
|
||||
|
||||
function borderColor(data: Uint8ClampedArray, width: number, height: number): [number, number, number] {
|
||||
let r = 0;
|
||||
let g = 0;
|
||||
let b = 0;
|
||||
let n = 0;
|
||||
const add = (x: number, y: number) => {
|
||||
const o = (y * width + x) * 4;
|
||||
r += data[o];
|
||||
g += data[o + 1];
|
||||
b += data[o + 2];
|
||||
n++;
|
||||
};
|
||||
for (let x = 0; x < width; x++) {
|
||||
add(x, 0);
|
||||
add(x, height - 1);
|
||||
}
|
||||
for (let y = 1; y < height - 1; y++) {
|
||||
add(0, y);
|
||||
add(width - 1, y);
|
||||
}
|
||||
return [r / n / 255, g / n / 255, b / n / 255];
|
||||
}
|
||||
|
||||
function smooth(mask: Uint8Array, width: number, height: number) {
|
||||
const copy = new Uint8Array(mask);
|
||||
for (let y = 1; y < height - 1; y++) {
|
||||
for (let x = 1; x < width - 1; x++) {
|
||||
const i = y * width + x;
|
||||
let sum = 0;
|
||||
for (let dy = -1; dy <= 1; dy++) {
|
||||
for (let dx = -1; dx <= 1; dx++) sum += copy[i + dy * width + dx];
|
||||
}
|
||||
mask[i] = sum / 9 >= 128 ? 255 : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function encodeBase64(bytes: Uint8Array): string {
|
||||
let binary = '';
|
||||
const chunk = 0x8000;
|
||||
for (let i = 0; i < bytes.length; i += chunk) {
|
||||
binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Tracks the "hold Ctrl while dragging Exposure" clipping preview.
|
||||
*
|
||||
* The slider starts a session on pointer down; the overlay follows the
|
||||
* modifier key for as long as the drag lasts, so Ctrl can be pressed or
|
||||
* released mid-drag. Kept outside React so the pointer listeners are attached
|
||||
* once and the renderer subscription stays cheap.
|
||||
*/
|
||||
|
||||
type Listener = (active: boolean) => void;
|
||||
|
||||
let dragging = false;
|
||||
let active = false;
|
||||
const listeners = new Set<Listener>();
|
||||
|
||||
function emit() {
|
||||
for (const listener of listeners) listener(active);
|
||||
}
|
||||
|
||||
export function clipPreviewActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
export function subscribeClipPreview(listener: Listener) {
|
||||
listeners.add(listener);
|
||||
listener(active);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function beginClipPreview(ctrlHeld: boolean) {
|
||||
dragging = true;
|
||||
active = Boolean(ctrlHeld);
|
||||
emit();
|
||||
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Control' && e.key !== 'Meta') return;
|
||||
active = dragging && e.type === 'keydown';
|
||||
emit();
|
||||
};
|
||||
|
||||
const stop = () => {
|
||||
dragging = false;
|
||||
active = false;
|
||||
emit();
|
||||
window.removeEventListener('keydown', onKey, true);
|
||||
window.removeEventListener('keyup', onKey, true);
|
||||
window.removeEventListener('pointerup', stop, true);
|
||||
window.removeEventListener('pointercancel', stop, true);
|
||||
window.removeEventListener('blur', stop);
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', onKey, true);
|
||||
window.addEventListener('keyup', onKey, true);
|
||||
window.addEventListener('pointerup', stop, true);
|
||||
window.addEventListener('pointercancel', stop, true);
|
||||
window.addEventListener('blur', stop);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { CurvePoint } from '../types';
|
||||
|
||||
export const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
|
||||
export const clamp01 = (v: number) => clamp(v, 0, 1);
|
||||
export const round2 = (v: number) => Math.round(v * 100) / 100;
|
||||
|
||||
export type CurveSampler = (x: number) => number;
|
||||
|
||||
/** Monotone cubic (Fritsch-Carlson) interpolation through normalized curve points. */
|
||||
export function buildSampler(input: CurvePoint[]): CurveSampler {
|
||||
const pts = [...input].sort((a, b) => a.x - b.x);
|
||||
if (pts.length < 2) return (x: number) => clamp01(x);
|
||||
const xs = pts.map((p) => clamp01(p.x));
|
||||
const ys = pts.map((p) => clamp01(p.y));
|
||||
const n = xs.length;
|
||||
|
||||
const d: number[] = [];
|
||||
for (let i = 0; i < n - 1; i++) d.push((ys[i + 1] - ys[i]) / Math.max(1e-6, xs[i + 1] - xs[i]));
|
||||
|
||||
const m: number[] = new Array(n);
|
||||
m[0] = d[0];
|
||||
m[n - 1] = d[n - 2];
|
||||
for (let i = 1; i < n - 1; i++) {
|
||||
if (d[i - 1] * d[i] <= 0) m[i] = 0;
|
||||
else m[i] = (d[i - 1] + d[i]) / 2;
|
||||
}
|
||||
for (let i = 0; i < n - 1; i++) {
|
||||
if (d[i] === 0) {
|
||||
m[i] = 0;
|
||||
m[i + 1] = 0;
|
||||
continue;
|
||||
}
|
||||
const a = m[i] / d[i];
|
||||
const b = m[i + 1] / d[i];
|
||||
const s = a * a + b * b;
|
||||
if (s > 9) {
|
||||
const t = 3 / Math.sqrt(s);
|
||||
m[i] = t * a * d[i];
|
||||
m[i + 1] = t * b * d[i];
|
||||
}
|
||||
}
|
||||
|
||||
return (x: number) => {
|
||||
if (x <= xs[0]) return clamp01(ys[0] + (x - xs[0]) * m[0]);
|
||||
if (x >= xs[n - 1]) return clamp01(ys[n - 1] + (x - xs[n - 1]) * m[n - 1]);
|
||||
let i = 0;
|
||||
while (i < n - 2 && x > xs[i + 1]) i++;
|
||||
const h = xs[i + 1] - xs[i];
|
||||
const t = (x - xs[i]) / h;
|
||||
const t2 = t * t;
|
||||
const t3 = t2 * t;
|
||||
const h00 = 2 * t3 - 3 * t2 + 1;
|
||||
const h10 = t3 - 2 * t2 + t;
|
||||
const h01 = -2 * t3 + 3 * t2;
|
||||
const h11 = t3 - t2;
|
||||
return clamp01(h00 * ys[i] + h10 * h * m[i] + h01 * ys[i + 1] + h11 * h * m[i + 1]);
|
||||
};
|
||||
}
|
||||
|
||||
export function sanitizeCurve(input: unknown): CurvePoint[] {
|
||||
const fallback: CurvePoint[] = [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 1, y: 1 },
|
||||
];
|
||||
if (!Array.isArray(input)) return fallback;
|
||||
const pts = input
|
||||
.filter((p): p is CurvePoint => !!p && typeof p.x === 'number' && typeof p.y === 'number')
|
||||
.map((p) => ({ x: clamp01(p.x), y: clamp01(p.y) }))
|
||||
.sort((a, b) => a.x - b.x);
|
||||
return pts.length >= 2 ? pts : fallback;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { EventRecord, PhotoRecord } from '../types';
|
||||
|
||||
const DB_NAME = 'lumenroom';
|
||||
const DB_VERSION = 1;
|
||||
|
||||
let dbPromise: Promise<IDBDatabase> | null = null;
|
||||
|
||||
export function openDB(): Promise<IDBDatabase> {
|
||||
if (dbPromise) return dbPromise;
|
||||
dbPromise = new Promise((resolve, reject) => {
|
||||
const req = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
req.onupgradeneeded = () => {
|
||||
const db = req.result;
|
||||
if (!db.objectStoreNames.contains('photos')) {
|
||||
const store = db.createObjectStore('photos', { keyPath: 'id' });
|
||||
store.createIndex('eventId', 'eventId', { unique: false });
|
||||
}
|
||||
if (!db.objectStoreNames.contains('assets')) db.createObjectStore('assets');
|
||||
if (!db.objectStoreNames.contains('events')) db.createObjectStore('events', { keyPath: 'id' });
|
||||
if (!db.objectStoreNames.contains('kv')) db.createObjectStore('kv');
|
||||
};
|
||||
req.onsuccess = () => resolve(req.result);
|
||||
req.onerror = () => reject(req.error ?? new Error('Unable to open database'));
|
||||
});
|
||||
return dbPromise;
|
||||
}
|
||||
|
||||
function wrap<T>(request: IDBRequest<T>): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error ?? new Error('IndexedDB request failed'));
|
||||
});
|
||||
}
|
||||
|
||||
async function store(name: string, mode: IDBTransactionMode = 'readonly') {
|
||||
const db = await openDB();
|
||||
return db.transaction(name, mode).objectStore(name);
|
||||
}
|
||||
|
||||
export async function getAllPhotos(): Promise<PhotoRecord[]> {
|
||||
return wrap((await store('photos')).getAll() as IDBRequest<PhotoRecord[]>);
|
||||
}
|
||||
|
||||
export async function putPhoto(photo: PhotoRecord): Promise<void> {
|
||||
await wrap((await store('photos', 'readwrite')).put(photo));
|
||||
}
|
||||
|
||||
export async function deletePhotoRecord(id: string): Promise<void> {
|
||||
const db = await openDB();
|
||||
const tx = db.transaction(['photos', 'assets'], 'readwrite');
|
||||
tx.objectStore('photos').delete(id);
|
||||
tx.objectStore('assets').delete(id);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function putAsset(id: string, blob: Blob): Promise<void> {
|
||||
await wrap((await store('assets', 'readwrite')).put(blob, id));
|
||||
}
|
||||
|
||||
export async function getAsset(id: string): Promise<Blob | undefined> {
|
||||
return wrap((await store('assets')).get(id) as IDBRequest<Blob | undefined>);
|
||||
}
|
||||
|
||||
export async function getAllEvents(): Promise<EventRecord[]> {
|
||||
return wrap((await store('events')).getAll() as IDBRequest<EventRecord[]>);
|
||||
}
|
||||
|
||||
export async function putEvent(event: EventRecord): Promise<void> {
|
||||
await wrap((await store('events', 'readwrite')).put(event));
|
||||
}
|
||||
|
||||
export async function deleteEventRecord(id: string): Promise<void> {
|
||||
await wrap((await store('events', 'readwrite')).delete(id));
|
||||
}
|
||||
|
||||
export async function getKV<T>(key: string): Promise<T | undefined> {
|
||||
return wrap((await store('kv')).get(key) as IDBRequest<T | undefined>);
|
||||
}
|
||||
|
||||
export async function setKV(key: string, value: unknown): Promise<void> {
|
||||
await wrap((await store('kv', 'readwrite')).put(value, key));
|
||||
}
|
||||
|
||||
export async function estimateUsage(): Promise<{ usage: number; quota: number }> {
|
||||
if (!navigator.storage?.estimate) return { usage: 0, quota: 0 };
|
||||
const est = await navigator.storage.estimate();
|
||||
return { usage: est.usage ?? 0, quota: est.quota ?? 0 };
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Drag payloads live in a module variable because browsers only expose
|
||||
* `dataTransfer.getData` on drop, not during dragover — and we need to know
|
||||
* whether a photo (rather than an OS file) is being dragged while hovering.
|
||||
*/
|
||||
|
||||
let photoIds: string[] = [];
|
||||
let eventId: string | null = null;
|
||||
|
||||
export const PHOTO_DRAG = 'application/x-lumen-photos';
|
||||
export const EVENT_DRAG = 'application/x-lumen-event';
|
||||
|
||||
export function startPhotoDrag(ids: string[]) {
|
||||
photoIds = ids;
|
||||
eventId = null;
|
||||
}
|
||||
|
||||
export function draggedPhotoIds(): string[] {
|
||||
return photoIds;
|
||||
}
|
||||
|
||||
export function startEventDrag(id: string) {
|
||||
eventId = id;
|
||||
photoIds = [];
|
||||
}
|
||||
|
||||
export function draggedEventId(): string | null {
|
||||
return eventId;
|
||||
}
|
||||
|
||||
export function endDrag() {
|
||||
photoIds = [];
|
||||
eventId = null;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { defaultEdits, defaultLocalLayer } from './edits';
|
||||
import { applyEditSections } from './editSections';
|
||||
import { autoNoiseFor } from './noiseProfile';
|
||||
|
||||
describe('applyEditSections', () => {
|
||||
it('copies only the selected panel groups', () => {
|
||||
const source = defaultEdits();
|
||||
source.exposure = 1.25;
|
||||
source.saturation = 18;
|
||||
source.crop = { ...source.crop, x: 0.1, w: 0.7 };
|
||||
const target = defaultEdits();
|
||||
target.crop = { ...target.crop, x: 0.4, w: 0.2 };
|
||||
|
||||
const next = applyEditSections(source, target, ['light']);
|
||||
|
||||
expect(next.exposure).toBe(1.25);
|
||||
expect(next.saturation).toBe(18);
|
||||
expect(next.crop.x).toBe(0.4);
|
||||
expect(next.crop.w).toBe(0.2);
|
||||
});
|
||||
|
||||
it('does not mutate either edit record', () => {
|
||||
const source = defaultEdits();
|
||||
source.exposure = 2;
|
||||
const target = defaultEdits();
|
||||
applyEditSections(source, target, ['light']);
|
||||
expect(source.exposure).toBe(2);
|
||||
expect(target.exposure).toBe(0);
|
||||
});
|
||||
|
||||
it('can copy crop and local masks separately', () => {
|
||||
const source = defaultEdits();
|
||||
source.crop = { ...source.crop, angle: 4.5 };
|
||||
source.local = [
|
||||
{
|
||||
...defaultLocalLayer('radial', 0),
|
||||
id: 'mask-1',
|
||||
name: 'Face',
|
||||
},
|
||||
];
|
||||
const target = defaultEdits();
|
||||
const cropped = applyEditSections(source, target, ['crop']);
|
||||
expect(cropped.crop.angle).toBe(4.5);
|
||||
expect(cropped.local).toHaveLength(0);
|
||||
|
||||
const masked = applyEditSections(source, target, ['local']);
|
||||
expect(masked.local[0].name).toBe('Face');
|
||||
expect(masked.crop.angle).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('autoNoiseFor', () => {
|
||||
it('raises luminance and chroma smoothing with ISO', () => {
|
||||
const low = autoNoiseFor({ iso: 100 });
|
||||
const high = autoNoiseFor({ iso: 6400 });
|
||||
expect(high.luminance).toBeGreaterThan(low.luminance);
|
||||
expect(high.chroma).toBeGreaterThan(low.chroma);
|
||||
expect(high.detail).toBeLessThanOrEqual(low.detail);
|
||||
});
|
||||
|
||||
it('keeps every slider inside the editor range', () => {
|
||||
const noise = autoNoiseFor({ iso: 204800 });
|
||||
expect(noise.luminance).toBeGreaterThanOrEqual(0);
|
||||
expect(noise.luminance).toBeLessThanOrEqual(100);
|
||||
expect(noise.chroma).toBeGreaterThanOrEqual(0);
|
||||
expect(noise.chroma).toBeLessThanOrEqual(100);
|
||||
expect(noise.detail).toBeGreaterThanOrEqual(0);
|
||||
expect(noise.chromaDetail).toBeLessThanOrEqual(100);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import type { Edits } from '../types';
|
||||
|
||||
export type EditSectionId =
|
||||
| 'light'
|
||||
| 'color'
|
||||
| 'detail'
|
||||
| 'effects'
|
||||
| 'geometry'
|
||||
| 'lens'
|
||||
| 'crop'
|
||||
| 'healing'
|
||||
| 'local';
|
||||
|
||||
export interface EditSection {
|
||||
id: EditSectionId;
|
||||
label: string;
|
||||
hint: string;
|
||||
/** applied by default when pasting or syncing */
|
||||
defaultOn: boolean;
|
||||
}
|
||||
|
||||
/** The copy/paste contract is deliberately grouped the way the panels are. */
|
||||
export const EDIT_SECTIONS: EditSection[] = [
|
||||
{
|
||||
id: 'light',
|
||||
label: 'Light & tone',
|
||||
hint: 'White balance, exposure, tone, presence',
|
||||
defaultOn: true,
|
||||
},
|
||||
{
|
||||
id: 'color',
|
||||
label: 'Color',
|
||||
hint: 'Curves, HSL, grading, black & white',
|
||||
defaultOn: true,
|
||||
},
|
||||
{
|
||||
id: 'detail',
|
||||
label: 'Detail',
|
||||
hint: 'Sharpening, noise reduction, defringe',
|
||||
defaultOn: true,
|
||||
},
|
||||
{
|
||||
id: 'effects',
|
||||
label: 'Effects',
|
||||
hint: 'Vignette and grain',
|
||||
defaultOn: true,
|
||||
},
|
||||
{
|
||||
id: 'geometry',
|
||||
label: 'Geometry',
|
||||
hint: 'Perspective, rotation and scale',
|
||||
defaultOn: true,
|
||||
},
|
||||
{
|
||||
id: 'lens',
|
||||
label: 'Lens profile',
|
||||
hint: 'Lensfun profile and correction switches',
|
||||
defaultOn: true,
|
||||
},
|
||||
{
|
||||
id: 'crop',
|
||||
label: 'Crop & orientation',
|
||||
hint: 'Crop, straighten, rotation and flips',
|
||||
defaultOn: false,
|
||||
},
|
||||
{
|
||||
id: 'healing',
|
||||
label: 'Spot healing',
|
||||
hint: 'Healing spots and source points',
|
||||
defaultOn: false,
|
||||
},
|
||||
{
|
||||
id: 'local',
|
||||
label: 'Local masks',
|
||||
hint: 'Brush, gradient and auto-mask layers',
|
||||
defaultOn: false,
|
||||
},
|
||||
];
|
||||
|
||||
const GROUPS: Record<EditSectionId, (keyof Edits)[]> = {
|
||||
light: [
|
||||
'temp',
|
||||
'tint',
|
||||
'exposure',
|
||||
'recovery',
|
||||
'contrast',
|
||||
'highlights',
|
||||
'shadows',
|
||||
'whites',
|
||||
'blacks',
|
||||
'texture',
|
||||
'clarity',
|
||||
'dehaze',
|
||||
'vibrance',
|
||||
'saturation',
|
||||
],
|
||||
color: ['bw', 'bwFilter', 'bwFilterAmount', 'curve', 'parametric', 'hsl', 'grading'],
|
||||
detail: ['sharpen', 'noise', 'defringe'],
|
||||
effects: ['vignette', 'grain', 'proof'],
|
||||
geometry: ['geometry'],
|
||||
lens: ['lens'],
|
||||
crop: ['crop'],
|
||||
healing: ['heal'],
|
||||
local: ['local'],
|
||||
};
|
||||
|
||||
/**
|
||||
* Merge selected sections of one photo's edits into another.
|
||||
*
|
||||
* The source is never mutated. Nested groups are copied as whole values, which
|
||||
* mirrors the checkboxes: choosing "Color" brings the curves, HSL and grading
|
||||
* together, not half of each.
|
||||
*/
|
||||
export function applyEditSections(source: Edits, target: Edits, sections: EditSectionId[]): Edits {
|
||||
const next: Edits = { ...target };
|
||||
for (const section of sections) {
|
||||
for (const key of GROUPS[section]) {
|
||||
(next as unknown as Record<string, unknown>)[key] = source[key];
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function defaultSections(): EditSectionId[] {
|
||||
return EDIT_SECTIONS.filter((section) => section.defaultOn).map((section) => section.id);
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
import type {
|
||||
BwFilter,
|
||||
ColorLabel,
|
||||
CropState,
|
||||
CurvePoint,
|
||||
Edits,
|
||||
Flag,
|
||||
HealSpot,
|
||||
LocalLayer,
|
||||
LocalMaskKind,
|
||||
LocalPoint,
|
||||
LocalStroke,
|
||||
LensCorrections,
|
||||
LensProfile,
|
||||
RasterMask,
|
||||
PhotoRecord,
|
||||
PhotoMeta,
|
||||
} from '../types';
|
||||
import { clamp, clamp01, sanitizeCurve } from './curves';
|
||||
|
||||
export interface HueBand {
|
||||
key: string;
|
||||
name: string;
|
||||
center: number;
|
||||
swatch: string;
|
||||
}
|
||||
|
||||
export const HUE_BANDS: HueBand[] = [
|
||||
{ key: 'red', name: 'Red', center: 0, swatch: '#e2453c' },
|
||||
{ key: 'orange', name: 'Orange', center: 32, swatch: '#e88b3a' },
|
||||
{ key: 'yellow', name: 'Yellow', center: 62, swatch: '#e3cd48' },
|
||||
{ key: 'green', name: 'Green', center: 120, swatch: '#57a95a' },
|
||||
{ key: 'aqua', name: 'Aqua', center: 180, swatch: '#48b3b8' },
|
||||
{ key: 'blue', name: 'Blue', center: 230, swatch: '#4a72c9' },
|
||||
{ key: 'purple', name: 'Purple', center: 280, swatch: '#8a63c6' },
|
||||
{ key: 'magenta', name: 'Magenta', center: 320, swatch: '#c455a0' },
|
||||
];
|
||||
|
||||
/**
|
||||
* Photographic contrast filters for black & white: transmission per channel.
|
||||
* A red filter passes red and blocks blue, so skies print almost black.
|
||||
*/
|
||||
export const BW_FILTERS: { id: BwFilter; label: string; rgb: [number, number, number] }[] = [
|
||||
{ id: 'none', label: 'None', rgb: [1, 1, 1] },
|
||||
{ id: 'yellow', label: 'Yellow', rgb: [1, 0.9, 0.28] },
|
||||
{ id: 'orange', label: 'Orange', rgb: [1, 0.66, 0.13] },
|
||||
{ id: 'red', label: 'Red', rgb: [1, 0.36, 0.05] },
|
||||
{ id: 'green', label: 'Green', rgb: [0.42, 1, 0.45] },
|
||||
{ id: 'blue', label: 'Blue', rgb: [0.35, 0.75, 1] },
|
||||
];
|
||||
|
||||
export function bwFilterRgb(id: BwFilter): [number, number, number] {
|
||||
return BW_FILTERS.find((f) => f.id === id)?.rgb ?? [1, 1, 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* CSS transform that shows a grid thumbnail in the photo's *current* orientation.
|
||||
* Uses the same order as the renderer: flips act on the photo, then the quarter
|
||||
* turns and straighten rotate it, and the result is scaled so the rotated image
|
||||
* still fills the card (a 90 degree turn of a 4:3 photo would otherwise leave gaps).
|
||||
*/
|
||||
export function thumbTransform(photo: PhotoRecord, boxAspect = 4 / 3): string {
|
||||
const { quarter, angle, flipH, flipV } = photo.edits.crop;
|
||||
const deg = quarter * 90 + angle;
|
||||
if (Math.abs(deg) < 1e-6 && !flipH && !flipV) return 'none';
|
||||
|
||||
const w = Math.max(1, photo.width || 1);
|
||||
const h = Math.max(1, photo.height || 1);
|
||||
const boxH = 1 / boxAspect;
|
||||
// object-fit: cover — the photo already fills the card before any transform.
|
||||
const cover = Math.max(1 / w, boxH / h);
|
||||
const dw = w * cover;
|
||||
const dh = h * cover;
|
||||
const rad = (Math.abs(deg) * Math.PI) / 180;
|
||||
const c = Math.abs(Math.cos(rad));
|
||||
const s = Math.abs(Math.sin(rad));
|
||||
// A rotated photo has to contain all four corners of the card, not just its
|
||||
// bounding box: after un-rotating a card corner by -deg it sits at
|
||||
// ((c + boxH*s)/2, (s + boxH*c)/2), so the photo must be at least that wide
|
||||
// and tall. Fitting the bounding box instead leaves gaps on angle-only turns.
|
||||
const coverFit = Math.max((c + boxH * s) / dw, (s + boxH * c) / dh);
|
||||
// A thumbnail's rounded pixel size can differ from the record's ratio by a
|
||||
// fraction of a percent; a hair of slack keeps it from showing a sliver at
|
||||
// the edge. It is invisible at any real card size.
|
||||
const fit = Math.abs(deg) > 1e-6 ? coverFit * 1.005 : coverFit;
|
||||
|
||||
const parts = [`rotate(${deg.toFixed(2)}deg)`];
|
||||
// Round up: rounding the scale down would leave a hairline gap at the edge.
|
||||
const rounded = Math.ceil(fit * 1e4) / 1e4;
|
||||
if (Math.abs(rounded - 1) > 1e-4) parts.push(`scale(${rounded.toFixed(4)})`);
|
||||
if (flipH) parts.push('scaleX(-1)');
|
||||
if (flipV) parts.push('scaleY(-1)');
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
/** The shader carries a fixed spot array; more than this would silently drop. */
|
||||
export const MAX_HEAL_SPOTS = 24;
|
||||
|
||||
/** Four masks are packed into one RGBA texture. */
|
||||
export const MAX_LOCAL_LAYERS = 4;
|
||||
|
||||
export function defaultLocalAdjust(): LocalLayer['adjust'] {
|
||||
return { exposure: 0, contrast: 0, highlights: 0, shadows: 0, temp: 0, tint: 0, saturation: 0 };
|
||||
}
|
||||
|
||||
export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLayer {
|
||||
return {
|
||||
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
|
||||
name: `Local ${index + 1}`,
|
||||
kind,
|
||||
inverted: false,
|
||||
feather: 50,
|
||||
brush: { strokes: [] },
|
||||
linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 },
|
||||
radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 },
|
||||
range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 },
|
||||
adjust: defaultLocalAdjust(),
|
||||
};
|
||||
}
|
||||
|
||||
export const ASPECTS: { id: string; label: string; ratio: number | null }[] = [
|
||||
{ id: 'original', label: 'Original', ratio: null },
|
||||
{ id: 'free', label: 'Free', ratio: null },
|
||||
{ id: '1:1', label: '1 × 1', ratio: 1 },
|
||||
{ id: '4:5', label: '4 × 5', ratio: 4 / 5 },
|
||||
{ id: '5:4', label: '5 × 4', ratio: 5 / 4 },
|
||||
{ id: '4:3', label: '4 × 3', ratio: 4 / 3 },
|
||||
{ id: '3:2', label: '3 × 2', ratio: 3 / 2 },
|
||||
{ id: '16:9', label: '16 × 9', ratio: 16 / 9 },
|
||||
{ id: '2:1', label: '2 × 1', ratio: 2 },
|
||||
{ id: '9:16', label: '9 × 16', ratio: 9 / 16 },
|
||||
];
|
||||
|
||||
export function defaultCrop(): CropState {
|
||||
return { x: 0, y: 0, w: 1, h: 1, angle: 0, quarter: 0, aspect: 'original', flipH: false, flipV: false };
|
||||
}
|
||||
|
||||
export function identityCurve(): CurvePoint[] {
|
||||
return [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 1, y: 1 },
|
||||
];
|
||||
}
|
||||
|
||||
export function defaultEdits(): Edits {
|
||||
return {
|
||||
temp: 0,
|
||||
tint: 0,
|
||||
exposure: 0,
|
||||
recovery: 0,
|
||||
contrast: 0,
|
||||
highlights: 0,
|
||||
shadows: 0,
|
||||
whites: 0,
|
||||
blacks: 0,
|
||||
texture: 0,
|
||||
clarity: 0,
|
||||
dehaze: 0,
|
||||
vibrance: 0,
|
||||
saturation: 0,
|
||||
bw: false,
|
||||
bwFilter: 'none',
|
||||
bwFilterAmount: 100,
|
||||
curve: {
|
||||
rgb: identityCurve(),
|
||||
red: identityCurve(),
|
||||
green: identityCurve(),
|
||||
blue: identityCurve(),
|
||||
},
|
||||
parametric: { highlights: 0, lights: 0, darks: 0, blacks: 0 },
|
||||
hsl: {
|
||||
hue: HUE_BANDS.map(() => 0),
|
||||
sat: HUE_BANDS.map(() => 0),
|
||||
lum: HUE_BANDS.map(() => 0),
|
||||
},
|
||||
grading: {
|
||||
shadows: { h: 210, s: 0 },
|
||||
highlights: { h: 45, s: 0 },
|
||||
balance: 0,
|
||||
},
|
||||
sharpen: { amount: 0, radius: 1, detail: 25, mask: 0, lensSoftness: 0 },
|
||||
proof: { enabled: false, paper: 'matte', blackPoint: 2, gamut: false },
|
||||
noise: { luminance: 0, detail: 50, chroma: 0, chromaDetail: 50 },
|
||||
aiDenoise: { amount: 100, key: null, model: 'guided' },
|
||||
defringe: { purple: 0, green: 0 },
|
||||
heal: [],
|
||||
local: [],
|
||||
geometry: { distortion: 0, vertical: 0, horizontal: 0, rotate: 0, scale: 100 },
|
||||
vignette: { amount: 0, midpoint: 50, feather: 50 },
|
||||
grain: { amount: 0, size: 25, roughness: 50 },
|
||||
crop: defaultCrop(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Keeps stored spots inside the image and caps the count the shader accepts. */
|
||||
function healSpots(input: unknown): HealSpot[] {
|
||||
if (!Array.isArray(input)) return [];
|
||||
const spots: HealSpot[] = [];
|
||||
for (const raw of input.slice(0, MAX_HEAL_SPOTS)) {
|
||||
if (!raw || typeof raw !== 'object') continue;
|
||||
const s = raw as Partial<HealSpot>;
|
||||
const x = clamp01(num(s.x, 0.5, 0, 1));
|
||||
const y = clamp01(num(s.y, 0.5, 0, 1));
|
||||
spots.push({
|
||||
x,
|
||||
y,
|
||||
r: num(s.r, 0.02, 0.001, 0.35),
|
||||
feather: num(s.feather, 50, 0, 100),
|
||||
sx: clamp01(num(s.sx, x + 0.05, 0, 1)),
|
||||
sy: clamp01(num(s.sy, y, 0, 1)),
|
||||
});
|
||||
}
|
||||
return spots;
|
||||
}
|
||||
|
||||
function clampPoint(input: unknown, fallback: LocalPoint): LocalPoint {
|
||||
if (!input || typeof input !== 'object') return fallback;
|
||||
const p = input as Partial<LocalPoint>;
|
||||
return { x: clamp01(num(p.x, fallback.x, 0, 1)), y: clamp01(num(p.y, fallback.y, 0, 1)) };
|
||||
}
|
||||
|
||||
function localStrokes(input: unknown): LocalStroke[] {
|
||||
if (!Array.isArray(input)) return [];
|
||||
const out: LocalStroke[] = [];
|
||||
for (const raw of input.slice(-300)) {
|
||||
if (!raw || typeof raw !== 'object') continue;
|
||||
const stroke = raw as Partial<LocalStroke>;
|
||||
if (!Array.isArray(stroke.points) || !stroke.points.length) continue;
|
||||
const points = stroke.points
|
||||
.slice(-4000)
|
||||
.map((p) => clampPoint(p, { x: 0.5, y: 0.5 }));
|
||||
out.push({
|
||||
points,
|
||||
size: num(stroke.size, 0.04, 0.002, 0.5),
|
||||
erase: !!stroke.erase,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function rasterMask(input: unknown): RasterMask | undefined {
|
||||
if (!input || typeof input !== 'object') return undefined;
|
||||
const raw = input as Partial<RasterMask>;
|
||||
if (typeof raw.data !== 'string' || !raw.data || raw.data.length > 2_000_000) return undefined;
|
||||
const width = Math.round(num(raw.width, 0, 1, 1024));
|
||||
const height = Math.round(num(raw.height, 0, 1, 1024));
|
||||
if (!width || !height) return undefined;
|
||||
return { data: raw.data, width, height };
|
||||
}
|
||||
|
||||
function localLayers(input: unknown): LocalLayer[] {
|
||||
if (!Array.isArray(input)) return [];
|
||||
const out: LocalLayer[] = [];
|
||||
for (const raw of input.slice(0, MAX_LOCAL_LAYERS)) {
|
||||
if (!raw || typeof raw !== 'object') continue;
|
||||
const layer = raw as Partial<LocalLayer>;
|
||||
const kind: LocalMaskKind =
|
||||
layer.kind === 'linear' || layer.kind === 'radial' || layer.kind === 'raster' ? layer.kind : 'brush';
|
||||
const adjust = (layer.adjust ?? {}) as Partial<LocalLayer['adjust']>;
|
||||
const range = (layer.range ?? {}) as Partial<LocalLayer['range']>;
|
||||
const linear = (layer.linear ?? {}) as Partial<LocalLayer['linear']>;
|
||||
const radial = (layer.radial ?? {}) as Partial<LocalLayer['radial']>;
|
||||
out.push({
|
||||
id: typeof layer.id === 'string' && layer.id ? layer.id : `local-${out.length}`,
|
||||
name: typeof layer.name === 'string' && layer.name.trim() ? layer.name.slice(0, 40) : `Local ${out.length + 1}`,
|
||||
kind,
|
||||
inverted: !!layer.inverted,
|
||||
feather: num(layer.feather, 50, 0, 100),
|
||||
brush: { strokes: localStrokes(layer.brush?.strokes) },
|
||||
raster: kind === 'raster' ? rasterMask(layer.raster) : undefined,
|
||||
linear: {
|
||||
x1: clamp01(num(linear.x1, 0.5, 0, 1)),
|
||||
y1: clamp01(num(linear.y1, 0.2, 0, 1)),
|
||||
x2: clamp01(num(linear.x2, 0.5, 0, 1)),
|
||||
y2: clamp01(num(linear.y2, 0.8, 0, 1)),
|
||||
},
|
||||
radial: {
|
||||
cx: clamp01(num(radial.cx, 0.5, 0, 1)),
|
||||
cy: clamp01(num(radial.cy, 0.5, 0, 1)),
|
||||
rx: num(radial.rx, 0.25, 0.01, 1.5),
|
||||
ry: num(radial.ry, 0.3, 0.01, 1.5),
|
||||
},
|
||||
range: {
|
||||
enabled: !!range.enabled,
|
||||
lumaMin: num(range.lumaMin, 0, 0, 100),
|
||||
lumaMax: num(range.lumaMax, 100, 0, 100),
|
||||
hue: num(range.hue, 30, 0, 360),
|
||||
hueRange: num(range.hueRange, 180, 0, 180),
|
||||
satMin: num(range.satMin, 0, 0, 100),
|
||||
},
|
||||
adjust: {
|
||||
exposure: num(adjust.exposure, 0, -4, 4),
|
||||
contrast: num(adjust.contrast, 0, -100, 100),
|
||||
highlights: num(adjust.highlights, 0, -100, 100),
|
||||
shadows: num(adjust.shadows, 0, -100, 100),
|
||||
temp: num(adjust.temp, 0, -100, 100),
|
||||
tint: num(adjust.tint, 0, -100, 100),
|
||||
saturation: num(adjust.saturation, 0, -100, 100),
|
||||
},
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function bands(input: unknown): number[] {
|
||||
const arr = Array.isArray(input) ? input : [];
|
||||
return HUE_BANDS.map((_, i) => {
|
||||
const v = arr[i];
|
||||
return typeof v === 'number' && Number.isFinite(v) ? clamp(v, -100, 100) : 0;
|
||||
});
|
||||
}
|
||||
|
||||
function num(value: unknown, fallback: number, lo: number, hi: number): number {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? clamp(value, lo, hi) : fallback;
|
||||
}
|
||||
|
||||
/** Deep-merge stored edits with the current defaults so older records keep working. */
|
||||
function lensProfile(input: unknown): LensProfile | undefined {
|
||||
if (!input || typeof input !== 'object') return undefined;
|
||||
const raw = input as Partial<LensProfile>;
|
||||
if (typeof raw.maker !== 'string' || typeof raw.model !== 'string') return undefined;
|
||||
const maker = raw.maker.trim();
|
||||
const model = raw.model.trim();
|
||||
if (!maker || !model) return undefined;
|
||||
const corrections = raw.corrections as Partial<LensCorrections> | undefined;
|
||||
return {
|
||||
maker,
|
||||
model,
|
||||
crop: num(raw.crop, 1, 0.3, 10),
|
||||
cameraMaker: typeof raw.cameraMaker === 'string' ? raw.cameraMaker : undefined,
|
||||
cameraModel: typeof raw.cameraModel === 'string' ? raw.cameraModel : undefined,
|
||||
corrections: {
|
||||
distortion: corrections?.distortion !== false,
|
||||
tca: corrections?.tca !== false,
|
||||
vignetting: corrections?.vignetting !== false,
|
||||
},
|
||||
distance: num(raw.distance, 1000, 0.1, 100000),
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits {
|
||||
const d = defaultEdits();
|
||||
if (!input) return d;
|
||||
const curve = (input.curve ?? {}) as Partial<Edits['curve']>;
|
||||
const parametric = (input.parametric ?? {}) as Partial<Edits['parametric']>;
|
||||
const grading = (input.grading ?? {}) as Partial<Edits['grading']>;
|
||||
const sharpen = (input.sharpen ?? {}) as Partial<Edits['sharpen']>;
|
||||
const noise = (input.noise ?? {}) as Partial<Edits['noise']>;
|
||||
const aiDenoise = (input.aiDenoise ?? {}) as Partial<Edits['aiDenoise']>;
|
||||
const defringe = (input.defringe ?? {}) as Partial<Edits['defringe']>;
|
||||
const vignette = (input.vignette ?? {}) as Partial<Edits['vignette']>;
|
||||
const grain = (input.grain ?? {}) as Partial<Edits['grain']>;
|
||||
const crop = (input.crop ?? {}) as Partial<CropState>;
|
||||
|
||||
return {
|
||||
...d,
|
||||
...input,
|
||||
aiDenoise: {
|
||||
amount: num(aiDenoise.amount, d.aiDenoise.amount, 0, 100),
|
||||
key: typeof aiDenoise.key === 'string' && aiDenoise.key ? aiDenoise.key : null,
|
||||
model: 'guided',
|
||||
},
|
||||
temp: num(input.temp, 0, -100, 100),
|
||||
tint: num(input.tint, 0, -100, 100),
|
||||
exposure: num(input.exposure, 0, -5, 5),
|
||||
recovery: num(input.recovery, 0, 0, 100),
|
||||
contrast: num(input.contrast, 0, -100, 100),
|
||||
highlights: num(input.highlights, 0, -100, 100),
|
||||
shadows: num(input.shadows, 0, -100, 100),
|
||||
whites: num(input.whites, 0, -100, 100),
|
||||
blacks: num(input.blacks, 0, -100, 100),
|
||||
texture: num(input.texture, 0, -100, 100),
|
||||
clarity: num(input.clarity, 0, -100, 100),
|
||||
dehaze: num(input.dehaze, 0, -100, 100),
|
||||
vibrance: num(input.vibrance, 0, -100, 100),
|
||||
saturation: num(input.saturation, 0, -100, 100),
|
||||
bw: !!input.bw,
|
||||
bwFilter: BW_FILTERS.some((f) => f.id === input.bwFilter) ? (input.bwFilter as BwFilter) : 'none',
|
||||
bwFilterAmount: num(input.bwFilterAmount, d.bwFilterAmount, 0, 100),
|
||||
curve: {
|
||||
rgb: sanitizeCurve(curve.rgb),
|
||||
red: sanitizeCurve(curve.red),
|
||||
green: sanitizeCurve(curve.green),
|
||||
blue: sanitizeCurve(curve.blue),
|
||||
},
|
||||
parametric: {
|
||||
highlights: num(parametric.highlights, 0, -100, 100),
|
||||
lights: num(parametric.lights, 0, -100, 100),
|
||||
darks: num(parametric.darks, 0, -100, 100),
|
||||
blacks: num(parametric.blacks, 0, -100, 100),
|
||||
},
|
||||
hsl: {
|
||||
hue: bands(input.hsl?.hue),
|
||||
sat: bands(input.hsl?.sat),
|
||||
lum: bands(input.hsl?.lum),
|
||||
},
|
||||
grading: {
|
||||
shadows: {
|
||||
h: num(grading.shadows?.h, d.grading.shadows.h, 0, 360),
|
||||
s: num(grading.shadows?.s, 0, 0, 100),
|
||||
},
|
||||
highlights: {
|
||||
h: num(grading.highlights?.h, d.grading.highlights.h, 0, 360),
|
||||
s: num(grading.highlights?.s, 0, 0, 100),
|
||||
},
|
||||
balance: num(grading.balance, 0, -100, 100),
|
||||
},
|
||||
sharpen: {
|
||||
amount: num(sharpen.amount, 0, 0, 150),
|
||||
radius: num(sharpen.radius, 1, 0.5, 3),
|
||||
detail: num(sharpen.detail, 25, 0, 100),
|
||||
mask: num(sharpen.mask, 0, 0, 100),
|
||||
lensSoftness: num(sharpen.lensSoftness, 0, 0, 100),
|
||||
},
|
||||
proof: {
|
||||
enabled: !!input.proof?.enabled,
|
||||
paper: input.proof?.paper === 'gloss' || input.proof?.paper === 'newsprint' ? input.proof.paper : 'matte',
|
||||
blackPoint: num(input.proof?.blackPoint, 2, 0, 20),
|
||||
gamut: !!input.proof?.gamut,
|
||||
},
|
||||
noise: {
|
||||
luminance: num(noise.luminance, 0, 0, 100),
|
||||
detail: num(noise.detail, 50, 0, 100),
|
||||
chroma: num(noise.chroma, 0, 0, 100),
|
||||
chromaDetail: num(noise.chromaDetail, 50, 0, 100),
|
||||
},
|
||||
defringe: {
|
||||
purple: num(defringe.purple, 0, 0, 100),
|
||||
green: num(defringe.green, 0, 0, 100),
|
||||
},
|
||||
heal: healSpots(input.heal),
|
||||
local: localLayers(input.local),
|
||||
geometry: {
|
||||
distortion: num(input.geometry?.distortion, 0, -100, 100),
|
||||
vertical: num(input.geometry?.vertical, 0, -100, 100),
|
||||
horizontal: num(input.geometry?.horizontal, 0, -100, 100),
|
||||
rotate: num(input.geometry?.rotate, 0, -15, 15),
|
||||
scale: num(input.geometry?.scale, 100, 50, 200),
|
||||
},
|
||||
lens: lensProfile(input.lens),
|
||||
vignette: {
|
||||
amount: num(vignette.amount, 0, -100, 100),
|
||||
midpoint: num(vignette.midpoint, 50, 0, 100),
|
||||
feather: num(vignette.feather, 50, 0, 100),
|
||||
},
|
||||
grain: {
|
||||
amount: num(grain.amount, 0, 0, 100),
|
||||
size: num(grain.size, 25, 10, 100),
|
||||
roughness: num(grain.roughness, 50, 0, 100),
|
||||
},
|
||||
crop: {
|
||||
x: clamp01(num(crop.x, 0, 0, 1)),
|
||||
y: clamp01(num(crop.y, 0, 0, 1)),
|
||||
w: clamp01(num(crop.w, 1, 0.02, 1)),
|
||||
h: clamp01(num(crop.h, 1, 0.02, 1)),
|
||||
angle: num(crop.angle, 0, -45, 45),
|
||||
quarter: typeof crop.quarter === 'number' && Number.isFinite(crop.quarter)
|
||||
? ((Math.round(crop.quarter) % 4) + 4) % 4
|
||||
: 0,
|
||||
aspect: typeof crop.aspect === 'string' ? crop.aspect : 'original',
|
||||
flipH: !!crop.flipH,
|
||||
flipV: !!crop.flipV,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const editCache = new WeakMap<Edits, boolean>();
|
||||
|
||||
export function isEdited(edits: Edits): boolean {
|
||||
const cached = editCache.get(edits);
|
||||
if (cached !== undefined) return cached;
|
||||
const d = defaultEdits();
|
||||
const strip = (e: Edits) => JSON.stringify({ ...e, crop: { ...e.crop, aspect: undefined } });
|
||||
const result = strip(edits) !== strip(d);
|
||||
editCache.set(edits, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): PhotoRecord {
|
||||
const edits = normalizeEdits(input.edits);
|
||||
const addedAt = input.addedAt ?? Date.now();
|
||||
const meta: PhotoMeta = input.meta ?? {};
|
||||
return {
|
||||
id: input.id,
|
||||
eventId: input.eventId ?? '',
|
||||
order: typeof input.order === 'number' ? input.order : undefined,
|
||||
raw: !!input.raw,
|
||||
workspace: input.workspace,
|
||||
decode: input.decode,
|
||||
previewUrl: input.previewUrl,
|
||||
thumbUrl: input.thumbUrl,
|
||||
proofAt: typeof input.proofAt === 'number' && Number.isFinite(input.proofAt) ? input.proofAt : undefined,
|
||||
name: input.name ?? 'Untitled',
|
||||
width: input.width ?? 0,
|
||||
height: input.height ?? 0,
|
||||
size: input.size ?? 0,
|
||||
mime: input.mime ?? 'image/jpeg',
|
||||
addedAt,
|
||||
takenAt: input.takenAt,
|
||||
meta,
|
||||
thumb: input.thumb ?? '',
|
||||
title: typeof input.title === 'string' ? input.title.slice(0, 200) : undefined,
|
||||
caption: typeof input.caption === 'string' ? input.caption.slice(0, 4000) : undefined,
|
||||
creator: typeof input.creator === 'string' ? input.creator.slice(0, 200) : undefined,
|
||||
copyright: typeof input.copyright === 'string' ? input.copyright.slice(0, 300) : undefined,
|
||||
copyOf: typeof input.copyOf === 'string' && input.copyOf ? input.copyOf : undefined,
|
||||
copyName: typeof input.copyName === 'string' && input.copyName ? input.copyName.slice(0, 80) : undefined,
|
||||
snapshots: Array.isArray(input.snapshots)
|
||||
? input.snapshots
|
||||
.filter((s) => s && typeof s === 'object' && typeof s.id === 'string' && typeof s.name === 'string')
|
||||
.slice(-30)
|
||||
.map((s) => ({ id: s.id, name: s.name.slice(0, 40), ts: Number(s.ts) || Date.now(), edits: normalizeEdits(s.edits) }))
|
||||
: undefined,
|
||||
merge: input.merge && (input.merge.kind === 'hdr' || input.merge.kind === 'panorama' || input.merge.kind === 'focus')
|
||||
? { kind: input.merge.kind, sourceIds: Array.isArray(input.merge.sourceIds) ? input.merge.sourceIds : [] }
|
||||
: undefined,
|
||||
rating: clamp(Math.round(input.rating ?? 0), 0, 5),
|
||||
deletedAt: typeof input.deletedAt === 'number' ? input.deletedAt : undefined,
|
||||
stackId: typeof input.stackId === 'string' && input.stackId ? input.stackId : undefined,
|
||||
stackIndex: typeof input.stackIndex === 'number' && Number.isFinite(input.stackIndex)
|
||||
? Math.max(0, Math.round(input.stackIndex))
|
||||
: undefined,
|
||||
flag: (input.flag ?? 'none') as Flag,
|
||||
color: (input.color ?? '') as ColorLabel,
|
||||
keywords: Array.isArray(input.keywords) ? input.keywords : [],
|
||||
edits,
|
||||
history:
|
||||
Array.isArray(input.history) && input.history.length
|
||||
? input.history
|
||||
: [{ label: 'Import', ts: addedAt, edits }],
|
||||
};
|
||||
}
|
||||
|
||||
export const COLOR_LABELS: { value: ColorLabel; name: string; hex: string }[] = [
|
||||
{ value: 'red', name: 'Red', hex: '#e05252' },
|
||||
{ value: 'yellow', name: 'Yellow', hex: '#e0c04a' },
|
||||
{ value: 'green', name: 'Green', hex: '#56b268' },
|
||||
{ value: 'blue', name: 'Blue', hex: '#4f86e0' },
|
||||
{ value: 'purple', name: 'Purple', hex: '#9b6ede' },
|
||||
];
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { outputSize } from '../gl/renderer';
|
||||
import { defaultEdits } from './edits';
|
||||
|
||||
describe('export output dimensions', () => {
|
||||
it('matches the source for an uncropped image', () => {
|
||||
expect(outputSize(defaultEdits(), 6000, 4000)).toEqual({ w: 6000, h: 4000 });
|
||||
});
|
||||
|
||||
it('swaps dimensions for a quarter turn', () => {
|
||||
const edits = defaultEdits();
|
||||
edits.crop.quarter = 1;
|
||||
expect(outputSize(edits, 6000, 4000)).toEqual({ w: 4000, h: 6000 });
|
||||
});
|
||||
|
||||
it('includes the triangular points added by straightening', () => {
|
||||
const edits = defaultEdits();
|
||||
edits.crop.angle = 45;
|
||||
expect(outputSize(edits, 4000, 3000)).toEqual({ w: 4950, h: 4950 });
|
||||
});
|
||||
|
||||
it('applies the crop after the rotated frame is calculated', () => {
|
||||
const edits = defaultEdits();
|
||||
edits.crop.angle = 45;
|
||||
edits.crop.w = 0.5;
|
||||
edits.crop.h = 0.5;
|
||||
expect(outputSize(edits, 4000, 3000)).toEqual({ w: 2475, h: 2475 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,365 @@
|
||||
import type { Edits, PhotoRecord } from '../types';
|
||||
import { getBitmap } from './images';
|
||||
import { normalizeEdits } from './edits';
|
||||
import { buildLensCorrection } from './lensfun';
|
||||
import { outputSize, Renderer } from '../gl/renderer';
|
||||
import { getDenoisedBitmap } from './images';
|
||||
import { createZipBlob, zipFileName } from './zip';
|
||||
import { srgbProfile } from './icc';
|
||||
import { encodeTiff16 } from './tiff';
|
||||
|
||||
export type ExportFormat = 'jpeg' | 'png' | 'webp' | 'tiff16';
|
||||
export type ResizeMode = 'none' | 'longEdge' | 'percent';
|
||||
|
||||
export type WatermarkPosition = 'br' | 'bl' | 'tr' | 'tl' | 'center';
|
||||
|
||||
export interface ExportOptions {
|
||||
format: ExportFormat;
|
||||
quality: number;
|
||||
resize: ResizeMode;
|
||||
longEdge: number;
|
||||
percent: number;
|
||||
nameTemplate: string;
|
||||
/** Bundle multiple photos into one downloadable archive. */
|
||||
zip: boolean;
|
||||
/** Extra capture sharpening applied only to the exported pixels. */
|
||||
outputSharpen: number;
|
||||
/** Write title/caption/creator/copyright/keywords into the file. */
|
||||
metadata: boolean;
|
||||
/** Embed the generated sRGB ICC profile in JPEG/TIFF files. */
|
||||
embedProfile: boolean;
|
||||
watermark: {
|
||||
enabled: boolean;
|
||||
text: string;
|
||||
position: WatermarkPosition;
|
||||
opacity: number;
|
||||
size: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ExportRecipe {
|
||||
id: string;
|
||||
name: string;
|
||||
options: ExportOptions;
|
||||
}
|
||||
|
||||
export const DEFAULT_EXPORT: ExportOptions = {
|
||||
format: 'jpeg',
|
||||
quality: 92,
|
||||
resize: 'none',
|
||||
longEdge: 3000,
|
||||
percent: 100,
|
||||
nameTemplate: '{name}',
|
||||
zip: true,
|
||||
outputSharpen: 0,
|
||||
metadata: true,
|
||||
embedProfile: true,
|
||||
watermark: { enabled: false, text: '', position: 'br', opacity: 55, size: 4 },
|
||||
};
|
||||
|
||||
const MIME: Record<ExportFormat, string> = {
|
||||
jpeg: 'image/jpeg',
|
||||
png: 'image/png',
|
||||
webp: 'image/webp',
|
||||
tiff16: 'image/tiff',
|
||||
};
|
||||
|
||||
const EXT: Record<ExportFormat, string> = {
|
||||
jpeg: 'jpg',
|
||||
png: 'png',
|
||||
webp: 'webp',
|
||||
tiff16: 'tif',
|
||||
};
|
||||
|
||||
function download(blob: Blob, filename: string) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 4000);
|
||||
}
|
||||
|
||||
function pad(n: number) {
|
||||
return String(n).padStart(2, '0');
|
||||
}
|
||||
|
||||
export function buildFileName(template: string, photo: PhotoRecord, index: number, opts: ExportOptions) {
|
||||
const stamp = new Date(photo.takenAt ?? photo.addedAt);
|
||||
const base = photo.name.replace(/\.[^.]+$/, '') || 'export';
|
||||
const name = (template || '{name}')
|
||||
.replace(/\{name\}/g, base)
|
||||
.replace(/\{date\}/g, `${stamp.getFullYear()}${pad(stamp.getMonth() + 1)}${pad(stamp.getDate())}`)
|
||||
.replace(/\{time\}/g, `${pad(stamp.getHours())}${pad(stamp.getMinutes())}`)
|
||||
.replace(/\{index\}/g, String(index + 1).padStart(3, '0'))
|
||||
.replace(/[\\/:*?"<>|]+/g, '-')
|
||||
.trim();
|
||||
return `${name || 'export'}.${EXT[opts.format]}`;
|
||||
}
|
||||
|
||||
function targetSize(photo: PhotoRecord, edits: Edits, bitmap: ImageBitmap, opts: ExportOptions) {
|
||||
const size = outputSize(edits, bitmap.width, bitmap.height);
|
||||
const longEdge = Math.max(size.w, size.h);
|
||||
let scale = 1;
|
||||
if (opts.resize === 'longEdge' && opts.longEdge > 0 && longEdge > opts.longEdge) {
|
||||
scale = opts.longEdge / longEdge;
|
||||
} else if (opts.resize === 'percent') {
|
||||
scale = Math.min(2, Math.max(0.05, opts.percent / 100));
|
||||
}
|
||||
return {
|
||||
w: Math.max(1, Math.round(size.w * scale)),
|
||||
h: Math.max(1, Math.round(size.h * scale)),
|
||||
};
|
||||
}
|
||||
|
||||
export async function renderPhotoBlob(photo: PhotoRecord, opts: ExportOptions): Promise<Blob> {
|
||||
const bitmap = await getBitmap(photo);
|
||||
const base = normalizeEdits(photo.edits);
|
||||
const edits = opts.outputSharpen > 0
|
||||
? { ...base, sharpen: { ...base.sharpen, amount: Math.min(150, base.sharpen.amount + opts.outputSharpen) } }
|
||||
: base;
|
||||
const { w, h } = targetSize(photo, edits, bitmap, opts);
|
||||
const native = outputSize(edits, bitmap.width, bitmap.height);
|
||||
// Let the shader use its Catmull-Rom path when the crop is being enlarged,
|
||||
// so an intentional 150–200% export does not turn into a bilinear blur.
|
||||
const upscale = w > native.w * 1.05 || h > native.h * 1.05;
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 1;
|
||||
canvas.height = 1;
|
||||
const renderer = new Renderer(canvas);
|
||||
try {
|
||||
renderer.setImage(bitmap);
|
||||
// Forgetting this is how denoise silently goes missing from exports: the
|
||||
// preview and the file would be graded from different pixels.
|
||||
if (edits.aiDenoise.key) {
|
||||
const denoised = await getDenoisedBitmap(photo, edits.aiDenoise.key);
|
||||
renderer.setDenoised(denoised, edits.aiDenoise.amount / 100);
|
||||
}
|
||||
const lens = edits.lens
|
||||
? await buildLensCorrection(edits.lens, { width: bitmap.width, height: bitmap.height, meta: photo.meta })
|
||||
: null;
|
||||
|
||||
if (opts.format === 'tiff16') {
|
||||
if (opts.watermark.enabled && opts.watermark.text.trim()) {
|
||||
throw new Error('Watermarking is not available for 16-bit TIFF exports');
|
||||
}
|
||||
const pixels = renderer.render(edits, { width: w, height: h, lens, upscale, floatOut: true });
|
||||
if (!pixels) throw new Error('Could not read the 16-bit render');
|
||||
return encodeTiff16({
|
||||
width: w,
|
||||
height: h,
|
||||
pixels,
|
||||
icc: opts.embedProfile ? srgbProfile() : null,
|
||||
});
|
||||
}
|
||||
|
||||
renderer.render(edits, { width: w, height: h, lens, upscale });
|
||||
renderer.finishGpu();
|
||||
|
||||
let output = canvas;
|
||||
if (opts.watermark.enabled && opts.watermark.text.trim()) {
|
||||
output = paintWatermark(canvas, photo, opts);
|
||||
}
|
||||
const mime = MIME[opts.format];
|
||||
let blob = await new Promise<Blob | null>((resolve) =>
|
||||
output.toBlob(resolve, mime, Math.min(1, Math.max(0.1, opts.quality / 100))),
|
||||
);
|
||||
if (!blob) throw new Error('Export failed while encoding the image');
|
||||
if (opts.format === 'jpeg') {
|
||||
blob = await embedJpegMetadata(
|
||||
blob,
|
||||
opts.metadata ? buildXmp(photo) : '',
|
||||
opts.embedProfile ? srgbProfile() : null,
|
||||
);
|
||||
}
|
||||
return blob;
|
||||
} finally {
|
||||
renderer.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
function paintWatermark(source: HTMLCanvasElement, photo: PhotoRecord, opts: ExportOptions) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = source.width;
|
||||
canvas.height = source.height;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return source;
|
||||
ctx.drawImage(source, 0, 0);
|
||||
const longest = Math.max(canvas.width, canvas.height);
|
||||
const size = Math.max(10, Math.round((longest * opts.watermark.size) / 100));
|
||||
ctx.font = `600 ${size}px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`;
|
||||
ctx.textBaseline = 'middle';
|
||||
const text = opts.watermark.text.trim();
|
||||
const metrics = ctx.measureText(text);
|
||||
const pad = Math.round(size * 0.55);
|
||||
const x =
|
||||
opts.watermark.position === 'bl' || opts.watermark.position === 'tl'
|
||||
? pad
|
||||
: opts.watermark.position === 'center'
|
||||
? (canvas.width - metrics.width) / 2
|
||||
: canvas.width - metrics.width - pad;
|
||||
const y =
|
||||
opts.watermark.position === 'tr' || opts.watermark.position === 'tl'
|
||||
? pad + size / 2
|
||||
: opts.watermark.position === 'center'
|
||||
? canvas.height / 2
|
||||
: canvas.height - pad - size / 2;
|
||||
ctx.globalAlpha = Math.min(1, Math.max(0.05, opts.watermark.opacity / 100));
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.shadowColor = 'rgba(0,0,0,.65)';
|
||||
ctx.shadowBlur = Math.max(1, size * 0.12);
|
||||
ctx.shadowOffsetY = Math.max(1, size * 0.03);
|
||||
ctx.fillText(text, x, y);
|
||||
ctx.globalAlpha = 1;
|
||||
return canvas;
|
||||
}
|
||||
|
||||
function xmlEscape(value: string) {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function buildXmp(photo: PhotoRecord) {
|
||||
const title = photo.title || photo.name;
|
||||
const keywords = photo.keywords.map((word) => `<rdf:li>${xmlEscape(word)}</rdf:li>`).join('');
|
||||
return `<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/"><dc:title><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(title)}</rdf:li></rdf:Alt></dc:title><dc:description><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(photo.caption ?? '')}</rdf:li></rdf:Alt></dc:description><dc:creator><rdf:Seq><rdf:li>${xmlEscape(photo.creator ?? '')}</rdf:li></rdf:Seq></dc:creator><dc:rights><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(photo.copyright ?? '')}</rdf:li></rdf:Alt></dc:rights><dc:subject><rdf:Bag>${keywords}</rdf:Bag></dc:subject></rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end="w"?>`.slice(0, 65000);
|
||||
}
|
||||
|
||||
function appSegment(marker: number, header: Uint8Array, payload: Uint8Array): Uint8Array | null {
|
||||
const length = header.length + payload.length + 2;
|
||||
if (length > 65533) return null;
|
||||
const segment = new Uint8Array(length + 2);
|
||||
segment[0] = 0xff;
|
||||
segment[1] = marker;
|
||||
segment[2] = (length >> 8) & 255;
|
||||
segment[3] = length & 255;
|
||||
segment.set(header, 4);
|
||||
segment.set(payload, 4 + header.length);
|
||||
return segment;
|
||||
}
|
||||
|
||||
async function embedJpegMetadata(blob: Blob, xmp: string, icc: Uint8Array | null): Promise<Blob> {
|
||||
try {
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return blob;
|
||||
const chunks: Uint8Array[] = [bytes.subarray(0, 2)];
|
||||
|
||||
// Insert our own metadata immediately after SOI. Existing ICC APP2 blocks
|
||||
// are dropped below: canvas encoders often add one already, and duplicated
|
||||
// profiles can confuse colour-managed viewers.
|
||||
if (icc) {
|
||||
const header = new TextEncoder().encode('ICC_PROFILE\0');
|
||||
const payload = new Uint8Array(2 + icc.length);
|
||||
payload[0] = 1;
|
||||
payload[1] = 1;
|
||||
payload.set(icc, 2);
|
||||
const segment = appSegment(0xe2, header, payload);
|
||||
if (segment) chunks.push(segment);
|
||||
}
|
||||
if (xmp) {
|
||||
const header = new TextEncoder().encode('http://ns.adobe.com/xap/1.0/\0');
|
||||
const segment = appSegment(0xe1, header, new TextEncoder().encode(xmp));
|
||||
if (segment) chunks.push(segment);
|
||||
}
|
||||
|
||||
let at = 2;
|
||||
while (at + 4 <= bytes.length) {
|
||||
if (bytes[at] !== 0xff) {
|
||||
// Not a marker (or malformed); keep the remaining bytes intact.
|
||||
chunks.push(bytes.subarray(at));
|
||||
at = bytes.length;
|
||||
break;
|
||||
}
|
||||
const marker = bytes[at + 1];
|
||||
if (marker === 0xda) {
|
||||
chunks.push(bytes.subarray(at));
|
||||
at = bytes.length;
|
||||
break;
|
||||
}
|
||||
if (marker === 0xd8 || marker === 0xd9) {
|
||||
chunks.push(bytes.subarray(at, at + 2));
|
||||
at += 2;
|
||||
continue;
|
||||
}
|
||||
const length = (bytes[at + 2] << 8) | bytes[at + 3];
|
||||
const end = at + 2 + length;
|
||||
if (end > bytes.length) {
|
||||
chunks.push(bytes.subarray(at));
|
||||
at = bytes.length;
|
||||
break;
|
||||
}
|
||||
const isIcc =
|
||||
marker === 0xe2 &&
|
||||
bytes.subarray(at + 4, at + 16).every((value, index) => value === 'ICC_PROFILE\0'.charCodeAt(index));
|
||||
if (!isIcc) chunks.push(bytes.subarray(at, end));
|
||||
at = end;
|
||||
}
|
||||
if (at < bytes.length) chunks.push(bytes.subarray(at));
|
||||
return new Blob(chunks as BlobPart[], { type: 'image/jpeg' });
|
||||
} catch {
|
||||
return blob;
|
||||
}
|
||||
}
|
||||
|
||||
export async function exportPhotos(
|
||||
photos: PhotoRecord[],
|
||||
opts: ExportOptions,
|
||||
onProgress?: (done: number, total: number) => void,
|
||||
onStage?: (stage: 'render' | 'pack') => void,
|
||||
): Promise<{ count: number; failed: string[] }> {
|
||||
const bundle = opts.zip && photos.length > 1;
|
||||
const entries: { name: string; data: Blob }[] = [];
|
||||
const failed: string[] = [];
|
||||
let count = 0;
|
||||
|
||||
onStage?.('render');
|
||||
for (let i = 0; i < photos.length; i++) {
|
||||
const photo = photos[i];
|
||||
try {
|
||||
const blob = await renderPhotoBlob(photo, opts);
|
||||
const name = buildFileName(opts.nameTemplate, photo, i, opts);
|
||||
if (bundle) entries.push({ name, data: blob });
|
||||
else {
|
||||
download(blob, name);
|
||||
count++;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Export failed for', photo.name, err);
|
||||
failed.push(photo.name);
|
||||
}
|
||||
onProgress?.(i + 1, photos.length);
|
||||
// Give the browser a beat so long batches keep the tab responsive.
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
}
|
||||
|
||||
if (bundle && entries.length) {
|
||||
// One good file needs no archive; hand it over directly.
|
||||
if (entries.length === 1) {
|
||||
download(entries[0].data, entries[0].name);
|
||||
count = 1;
|
||||
} else {
|
||||
onStage?.('pack');
|
||||
const archive = await createZipBlob(entries);
|
||||
download(archive, zipFileName());
|
||||
count = entries.length;
|
||||
}
|
||||
}
|
||||
|
||||
return { count, failed };
|
||||
}
|
||||
|
||||
/** Backwards compatible single-photo export. */
|
||||
export async function exportPhoto(photo: PhotoRecord, maxLongEdge = 0): Promise<void> {
|
||||
const opts: ExportOptions = {
|
||||
...DEFAULT_EXPORT,
|
||||
resize: maxLongEdge > 0 ? 'longEdge' : 'none',
|
||||
longEdge: maxLongEdge || DEFAULT_EXPORT.longEdge,
|
||||
};
|
||||
const blob = await renderPhotoBlob(photo, opts);
|
||||
download(blob, buildFileName(opts.nameTemplate, photo, 0, opts));
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { srgbProfile } from './icc';
|
||||
|
||||
describe('sRGB ICC profile', () => {
|
||||
it('is a self-consistent v2 RGB display profile', () => {
|
||||
const profile = srgbProfile();
|
||||
const view = new DataView(profile.buffer);
|
||||
expect(profile.length).toBeGreaterThan(2000);
|
||||
expect(view.getUint32(0, false)).toBe(profile.length);
|
||||
expect(String.fromCharCode(...profile.subarray(36, 40))).toBe('acsp');
|
||||
expect(String.fromCharCode(...profile.subarray(16, 20))).toBe('RGB ');
|
||||
expect(String.fromCharCode(...profile.subarray(20, 24))).toBe('XYZ ');
|
||||
expect(view.getUint32(128, false)).toBeGreaterThan(5);
|
||||
});
|
||||
|
||||
it('carries a readable description for colour-managed viewers', () => {
|
||||
const profile = srgbProfile();
|
||||
const view = new DataView(profile.buffer);
|
||||
const count = view.getUint32(128, false);
|
||||
let descriptionAt = -1;
|
||||
for (let index = 0; index < count; index++) {
|
||||
const at = 132 + index * 12;
|
||||
if (String.fromCharCode(...profile.subarray(at, at + 4)) === 'desc') {
|
||||
descriptionAt = view.getUint32(at + 4, false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
expect(descriptionAt).toBeGreaterThan(0);
|
||||
expect(String.fromCharCode(...profile.subarray(descriptionAt, descriptionAt + 4))).toBe('desc');
|
||||
});
|
||||
|
||||
it('uses the sampled sRGB transfer curve rather than gamma 2.2', () => {
|
||||
const profile = srgbProfile();
|
||||
const view = new DataView(profile.buffer);
|
||||
const count = view.getUint32(128, false);
|
||||
let curveAt = -1;
|
||||
for (let index = 0; index < count; index++) {
|
||||
const at = 132 + index * 12;
|
||||
if (String.fromCharCode(...profile.subarray(at, at + 4)) === 'rTRC') {
|
||||
curveAt = view.getUint32(at + 4, false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
expect(curveAt).toBeGreaterThan(0);
|
||||
expect(String.fromCharCode(...profile.subarray(curveAt, curveAt + 4))).toBe('curv');
|
||||
expect(view.getUint32(curveAt + 8, false)).toBe(1024);
|
||||
expect(view.getUint16(curveAt + 12, false)).toBe(0);
|
||||
expect(view.getUint16(curveAt + 12 + 2 * 1023, false)).toBe(65535);
|
||||
const midpoint = view.getUint16(curveAt + 12 + 2 * 512, false);
|
||||
expect(midpoint).toBeGreaterThan(13000);
|
||||
expect(midpoint).toBeLessThan(15000);
|
||||
});
|
||||
});
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* A small, self-contained ICC v2 sRGB display profile.
|
||||
*
|
||||
* It is generated rather than shipped as a binary so the export pipeline can
|
||||
* tag sRGB files without adding a third-party profile asset. The matrix and
|
||||
* gamma describe the standard sRGB primaries; the browser already converted
|
||||
* the working pixels into sRGB when it decoded the source image.
|
||||
*/
|
||||
|
||||
let cached: Uint8Array | null = null;
|
||||
|
||||
function be32(out: DataView, offset: number, value: number) {
|
||||
out.setUint32(offset, value >>> 0, false);
|
||||
}
|
||||
|
||||
function be16(out: DataView, offset: number, value: number) {
|
||||
out.setUint16(offset, value & 0xffff, false);
|
||||
}
|
||||
|
||||
function s15(value: number) {
|
||||
return Math.round(value * 65536) >>> 0;
|
||||
}
|
||||
|
||||
function ascii(text: string) {
|
||||
return new TextEncoder().encode(text);
|
||||
}
|
||||
|
||||
function pad4(value: number) {
|
||||
return (value + 3) & ~3;
|
||||
}
|
||||
|
||||
function xyzTag(x: number, y: number, z: number) {
|
||||
const data = new Uint8Array(20);
|
||||
const view = new DataView(data.buffer);
|
||||
data.set(ascii('XYZ '), 0);
|
||||
be32(view, 8, s15(x));
|
||||
be32(view, 12, s15(y));
|
||||
be32(view, 16, s15(z));
|
||||
return data;
|
||||
}
|
||||
|
||||
function curveTag() {
|
||||
// ICC v2 curveType with the piecewise sRGB transfer function sampled at
|
||||
// 1024 points. A gamma-2.2 shortcut is close, but this is exact to the
|
||||
// standard (within 16-bit quantisation) and still readable by old CMMs.
|
||||
const samples = 1024;
|
||||
const data = new Uint8Array(12 + samples * 2);
|
||||
const view = new DataView(data.buffer);
|
||||
data.set(ascii('curv'), 0);
|
||||
be32(view, 8, samples);
|
||||
for (let index = 0; index < samples; index++) {
|
||||
const linear = index / (samples - 1);
|
||||
const encoded =
|
||||
linear <= 0.04045
|
||||
? linear / 12.92
|
||||
: ((linear + 0.055) / 1.055) ** 2.4;
|
||||
be16(view, 12 + index * 2, Math.round(encoded * 65535));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function descTag(text: string) {
|
||||
const value = new TextEncoder().encode(text);
|
||||
const size = pad4(12 + value.length + 1 + 4 + 4);
|
||||
const data = new Uint8Array(size);
|
||||
const view = new DataView(data.buffer);
|
||||
data.set(ascii('desc'), 0);
|
||||
be32(view, 8, value.length + 1);
|
||||
data.set(value, 12);
|
||||
data[12 + value.length] = 0;
|
||||
// Unicode language code and count are both zero.
|
||||
return data;
|
||||
}
|
||||
|
||||
function textTag(text: string) {
|
||||
const value = new TextEncoder().encode(text);
|
||||
const size = pad4(8 + value.length + 1);
|
||||
const data = new Uint8Array(size);
|
||||
const view = new DataView(data.buffer);
|
||||
data.set(ascii('text'), 0);
|
||||
data.set(value, 8);
|
||||
data[8 + value.length] = 0;
|
||||
return data;
|
||||
}
|
||||
|
||||
export function srgbProfile(): Uint8Array {
|
||||
if (cached) return cached;
|
||||
|
||||
// sRGB primaries adapted to the D50 profile connection space.
|
||||
const tags: { sig: string; data: Uint8Array }[] = [
|
||||
{ sig: 'desc', data: descTag('sRGB IEC61966-2.1 (Luminary)') },
|
||||
{ sig: 'cprt', data: textTag('No copyright, use freely') },
|
||||
{ sig: 'wtpt', data: xyzTag(0.9642, 1.0, 0.8249) },
|
||||
{ sig: 'rXYZ', data: xyzTag(0.4360747, 0.2225045, 0.0139322) },
|
||||
{ sig: 'gXYZ', data: xyzTag(0.3850649, 0.7168786, 0.0971045) },
|
||||
{ sig: 'bXYZ', data: xyzTag(0.1430804, 0.0606169, 0.7141733) },
|
||||
{ sig: 'rTRC', data: curveTag() },
|
||||
{ sig: 'gTRC', data: curveTag() },
|
||||
{ sig: 'bTRC', data: curveTag() },
|
||||
];
|
||||
|
||||
const tableSize = 4 + tags.length * 12;
|
||||
let offset = 128 + tableSize;
|
||||
const placed = tags.map((tag) => {
|
||||
offset = pad4(offset);
|
||||
const at = offset;
|
||||
offset += tag.data.length;
|
||||
return { ...tag, at };
|
||||
});
|
||||
const total = pad4(offset);
|
||||
const data = new Uint8Array(total);
|
||||
const view = new DataView(data.buffer);
|
||||
|
||||
// Header. Date is fixed so identical exports have identical profile bytes.
|
||||
be32(view, 0, total);
|
||||
data.set(ascii('LNRM'), 4);
|
||||
be32(view, 8, 0x02100000);
|
||||
data.set(ascii('mntr'), 12);
|
||||
data.set(ascii('RGB '), 16);
|
||||
data.set(ascii('XYZ '), 20);
|
||||
be16(view, 24, 2026);
|
||||
be16(view, 26, 1);
|
||||
be16(view, 28, 1);
|
||||
be16(view, 30, 0);
|
||||
be16(view, 32, 0);
|
||||
be16(view, 34, 0);
|
||||
data.set(ascii('acsp'), 36);
|
||||
be32(view, 40, 0);
|
||||
be32(view, 44, 0);
|
||||
be32(view, 48, 0);
|
||||
be32(view, 52, 0);
|
||||
be32(view, 56, 0);
|
||||
be32(view, 60, 0);
|
||||
be32(view, 64, 0); // perceptual rendering intent
|
||||
be32(view, 68, 0x0000f6d6); // D50 X 0.9642
|
||||
be32(view, 72, 0x00010000); // D50 Y 1.0
|
||||
be32(view, 76, 0x0000d32d); // D50 Z 0.8249
|
||||
data.set(ascii('LNRM'), 80);
|
||||
// bytes 84-127 (profile ID and reserved) remain zero.
|
||||
|
||||
be32(view, 128, placed.length);
|
||||
placed.forEach((tag, index) => {
|
||||
const at = 132 + index * 12;
|
||||
data.set(ascii(tag.sig), at);
|
||||
be32(view, at + 4, tag.at);
|
||||
be32(view, at + 8, tag.data.length);
|
||||
data.set(tag.data, tag.at);
|
||||
});
|
||||
|
||||
cached = data;
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import type { PhotoRecord } from '../types';
|
||||
import { getAsset, putAsset } from './db';
|
||||
|
||||
const CACHE_LIMIT = 6;
|
||||
const cache = new Map<string, ImageBitmap>();
|
||||
|
||||
/** 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<Blob | undefined> {
|
||||
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<Blob | null> {
|
||||
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<Blob | null> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getBitmap(photo: PhotoRecord): Promise<ImageBitmap> {
|
||||
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.
|
||||
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
|
||||
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();
|
||||
}
|
||||
|
||||
export function clearBitmapCache() {
|
||||
for (const bmp of cache.values()) bmp.close();
|
||||
cache.clear();
|
||||
for (const bmp of denoisedCache.values()) bmp.close();
|
||||
denoisedCache.clear();
|
||||
}
|
||||
|
||||
const denoisedCache = new Map<string, ImageBitmap>();
|
||||
|
||||
/**
|
||||
* 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<ImageBitmap | null> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
import exifr from 'exifr';
|
||||
import type { UploadResult } from './api';
|
||||
import type { PhotoMeta, PhotoRecord } from '../types';
|
||||
import { putAsset, putPhoto } from './db';
|
||||
import { defaultEdits, normalizePhoto } from './edits';
|
||||
import { defaultForMeta, loadCameraLensDefaults, type CameraLensDefault } from './lensDefaults';
|
||||
import { isRawFile, RAW_EXTENSIONS } from './raw';
|
||||
|
||||
export interface ImportProgress {
|
||||
done: number;
|
||||
total: number;
|
||||
current: string;
|
||||
}
|
||||
|
||||
export interface ImportResult {
|
||||
photos: PhotoRecord[];
|
||||
failed: { name: string; reason: string }[];
|
||||
cancelled?: boolean;
|
||||
}
|
||||
|
||||
/** Provided by the app when a Luminary server is connected. */
|
||||
export interface CloudImport {
|
||||
uploadOriginal: (id: string, file: File, name: string) => Promise<UploadResult>;
|
||||
push: (photo: PhotoRecord) => Promise<PhotoRecord>;
|
||||
}
|
||||
|
||||
/** Files imported at once; the server bounds how many raws decode in parallel. */
|
||||
const IMPORT_CONCURRENCY = 4;
|
||||
|
||||
export function uid(): string {
|
||||
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID();
|
||||
return `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
|
||||
}
|
||||
|
||||
function mapLimit<T>(items: T[], limit: number, fn: (item: T, index: number) => Promise<void>): Promise<void[]> {
|
||||
let cursor = 0;
|
||||
const runners = Array.from({ length: Math.min(Math.max(1, limit), items.length) }, async () => {
|
||||
for (;;) {
|
||||
const index = cursor++;
|
||||
if (index >= items.length) return;
|
||||
await fn(items[index], index);
|
||||
}
|
||||
});
|
||||
return Promise.all(runners);
|
||||
}
|
||||
|
||||
function formatShutter(time: unknown): string | undefined {
|
||||
if (typeof time !== 'number' || !Number.isFinite(time) || time <= 0) return undefined;
|
||||
if (time >= 1) return `${Math.round(time * 10) / 10}s`;
|
||||
return `1/${Math.round(1 / time)}s`;
|
||||
}
|
||||
|
||||
async function readMeta(file: File): Promise<{ meta: PhotoMeta; takenAt?: number }> {
|
||||
try {
|
||||
const data = (await exifr.parse(file, {
|
||||
tiff: true,
|
||||
exif: true,
|
||||
gps: false,
|
||||
interop: false,
|
||||
translateValues: false,
|
||||
reviveValues: true,
|
||||
})) as Record<string, unknown> | undefined;
|
||||
if (!data) return { meta: {} };
|
||||
const make = typeof data.Make === 'string' ? data.Make.trim() : '';
|
||||
const model = typeof data.Model === 'string' ? data.Model.trim() : '';
|
||||
const meta: PhotoMeta = {
|
||||
camera: [make, model].filter(Boolean).join(' ').replace(/\s+/g, ' ') || undefined,
|
||||
lens: typeof data.LensModel === 'string' ? data.LensModel.trim() : undefined,
|
||||
iso: typeof data.ISO === 'number' ? data.ISO : undefined,
|
||||
aperture: typeof data.FNumber === 'number' ? data.FNumber : undefined,
|
||||
shutter: formatShutter(data.ExposureTime),
|
||||
focal: typeof data.FocalLength === 'number' ? Math.round(data.FocalLength) : undefined,
|
||||
};
|
||||
const taken = data.DateTimeOriginal ?? data.CreateDate ?? data.ModifyDate;
|
||||
const takenAt = taken instanceof Date && !Number.isNaN(taken.getTime()) ? taken.getTime() : undefined;
|
||||
return { meta, takenAt };
|
||||
} catch {
|
||||
return { meta: {} };
|
||||
}
|
||||
}
|
||||
|
||||
function editsForImport(meta: PhotoMeta, defaults: CameraLensDefault[]) {
|
||||
const edits = defaultEdits();
|
||||
const match = defaultForMeta(defaults, meta);
|
||||
if (match) {
|
||||
edits.lens = {
|
||||
...match.profile,
|
||||
corrections: { ...match.profile.corrections },
|
||||
};
|
||||
}
|
||||
return edits;
|
||||
}
|
||||
|
||||
async function makeThumb(bitmap: ImageBitmap): Promise<string> {
|
||||
const max = 560;
|
||||
const scale = Math.min(1, max / Math.max(bitmap.width, bitmap.height));
|
||||
const w = Math.max(1, Math.round(bitmap.width * scale));
|
||||
const h = Math.max(1, Math.round(bitmap.height * scale));
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) throw new Error('Canvas 2D is unavailable');
|
||||
ctx.imageSmoothingQuality = 'high';
|
||||
ctx.drawImage(bitmap, 0, 0, w, h);
|
||||
return canvas.toDataURL('image/jpeg', 0.82);
|
||||
}
|
||||
|
||||
export function isSupportedFile(file: File): boolean {
|
||||
if (file.type.startsWith('image/')) return true;
|
||||
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
|
||||
return RAW_EXTENSIONS.has(ext) || /^(jpe?g|png|webp|avif|gif|bmp|tiff?)$/.test(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw files cannot be decoded by the browser, so they are sent to the server,
|
||||
* demosaiced there, and represented locally by the returned editable proxy.
|
||||
*/
|
||||
async function importRaw(
|
||||
file: File,
|
||||
eventId: string,
|
||||
keywords: string[],
|
||||
cloud: CloudImport,
|
||||
defaults: CameraLensDefault[],
|
||||
): Promise<PhotoRecord> {
|
||||
const id = uid();
|
||||
const upload = await cloud.uploadOriginal(id, file, file.name);
|
||||
const previewUrl = upload.previewUrl ?? `/api/photos/${id}/preview`;
|
||||
const res = await fetch(previewUrl, { credentials: 'same-origin' });
|
||||
if (!res.ok) throw new Error('The server could not produce a preview for this raw file');
|
||||
const blob = await res.blob();
|
||||
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
|
||||
const thumb = await makeThumb(bitmap);
|
||||
const { meta, takenAt } = await readMeta(file);
|
||||
const width = upload.width ?? bitmap.width;
|
||||
const height = upload.height ?? bitmap.height;
|
||||
const edits = editsForImport(meta, defaults);
|
||||
bitmap.close();
|
||||
|
||||
const record = normalizePhoto({
|
||||
id,
|
||||
eventId,
|
||||
name: file.name,
|
||||
width,
|
||||
height,
|
||||
size: file.size,
|
||||
mime: 'image/jpeg',
|
||||
addedAt: Date.now(),
|
||||
takenAt: takenAt ?? file.lastModified,
|
||||
meta,
|
||||
thumb,
|
||||
rating: 0,
|
||||
flag: 'none',
|
||||
color: '',
|
||||
keywords,
|
||||
edits,
|
||||
history: [{ label: 'Import', ts: Date.now(), edits }],
|
||||
raw: true,
|
||||
decode: upload.engine,
|
||||
previewUrl,
|
||||
});
|
||||
|
||||
await putPhoto(record);
|
||||
// No local blob: the multi-megabyte raw stays on the server.
|
||||
const saved = await cloud.push(record);
|
||||
const merged = normalizePhoto({ ...record, ...saved });
|
||||
await putPhoto(merged);
|
||||
return merged;
|
||||
}
|
||||
|
||||
async function importStandard(
|
||||
file: File,
|
||||
eventId: string,
|
||||
keywords: string[],
|
||||
cloud: CloudImport | null | undefined,
|
||||
defaults: CameraLensDefault[],
|
||||
): Promise<PhotoRecord> {
|
||||
// Camera JPEGs carry their orientation in EXIF; ask for it to be applied so
|
||||
// the thumbnail and the edited proxy agree with what the camera shot.
|
||||
const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' });
|
||||
const thumb = await makeThumb(bitmap);
|
||||
const { meta, takenAt } = await readMeta(file);
|
||||
const id = uid();
|
||||
const edits = editsForImport(meta, defaults);
|
||||
let record = normalizePhoto({
|
||||
id,
|
||||
eventId,
|
||||
name: file.name,
|
||||
width: bitmap.width,
|
||||
height: bitmap.height,
|
||||
size: file.size,
|
||||
mime: file.type || 'image/jpeg',
|
||||
addedAt: Date.now(),
|
||||
takenAt: takenAt ?? file.lastModified,
|
||||
meta,
|
||||
thumb,
|
||||
rating: 0,
|
||||
flag: 'none',
|
||||
color: '',
|
||||
keywords,
|
||||
edits,
|
||||
history: [{ label: 'Import', ts: Date.now(), edits }],
|
||||
});
|
||||
await putAsset(id, file);
|
||||
bitmap.close();
|
||||
|
||||
if (cloud) {
|
||||
// Originals are mirrored to the server; failures fall back to a local-only import.
|
||||
try {
|
||||
await cloud.uploadOriginal(id, file, file.name);
|
||||
const saved = await cloud.push(record);
|
||||
record = normalizePhoto({ ...record, ...saved });
|
||||
} catch (err) {
|
||||
console.warn('Could not copy the original to the server', file.name, err);
|
||||
}
|
||||
}
|
||||
|
||||
await putPhoto(record);
|
||||
return record;
|
||||
}
|
||||
|
||||
export async function importFiles(
|
||||
files: File[],
|
||||
eventId: string,
|
||||
keywords: string[] = [],
|
||||
onProgress?: (p: ImportProgress) => void,
|
||||
cloud?: CloudImport | null,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ImportResult> {
|
||||
const result: ImportResult = { photos: [], failed: [] };
|
||||
const images = files.filter(isSupportedFile);
|
||||
const total = images.length;
|
||||
if (!total) return result;
|
||||
|
||||
const collected: { index: number; photo: PhotoRecord }[] = [];
|
||||
const defaults = await loadCameraLensDefaults().catch(() => []);
|
||||
let done = 0;
|
||||
|
||||
await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => {
|
||||
if (signal?.aborted) return;
|
||||
try {
|
||||
const photo = isRawFile(file)
|
||||
? cloud
|
||||
? await importRaw(file, eventId, keywords, cloud, defaults)
|
||||
: (() => {
|
||||
throw new Error('Raw files need the Luminary server. Sign in, then import again.');
|
||||
})()
|
||||
: await importStandard(file, eventId, keywords, cloud, defaults);
|
||||
collected.push({ index, photo });
|
||||
} catch (err) {
|
||||
result.failed.push({
|
||||
name: file.name,
|
||||
reason: err instanceof Error ? err.message : 'Unsupported image format',
|
||||
});
|
||||
} finally {
|
||||
done += 1;
|
||||
onProgress?.({ done, total, current: file.name });
|
||||
}
|
||||
});
|
||||
|
||||
// Keep the shoot in capture/selection order regardless of which finished first.
|
||||
collected.sort((a, b) => a.index - b.index);
|
||||
result.photos = collected.map((c) => c.photo);
|
||||
result.cancelled = Boolean(signal?.aborted);
|
||||
onProgress?.({ done: total, total, current: '' });
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { defaultForMeta, type CameraLensDefault } from './lensDefaults';
|
||||
import type { LensProfile } from '../types';
|
||||
|
||||
const profile = (model: string): LensProfile => ({
|
||||
maker: 'Nikon',
|
||||
model,
|
||||
crop: 1,
|
||||
corrections: { distortion: true, tca: true, vignetting: true },
|
||||
});
|
||||
|
||||
const savedDefault = (
|
||||
camera: string,
|
||||
exifLens: string,
|
||||
model = 'Nikkor AF 50mm f/1.8D',
|
||||
): CameraLensDefault => ({
|
||||
camera,
|
||||
exifLens,
|
||||
profile: profile(model),
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
|
||||
describe('camera-lens default selection', () => {
|
||||
it('matches a camera and lens after normalizing both names', () => {
|
||||
const defaults = [
|
||||
savedDefault('NIKON CORPORATION NIKON D700', 'NIKON AF NIKKOR 50MM F/1.8D'),
|
||||
];
|
||||
expect(
|
||||
defaultForMeta(defaults, {
|
||||
camera: 'NIKON D700',
|
||||
lens: 'Nikkor AF 50mm 1:1.8D',
|
||||
}),
|
||||
).toBe(defaults[0]);
|
||||
});
|
||||
|
||||
it('does not apply a default to a different lens on the same body', () => {
|
||||
const defaults = [
|
||||
savedDefault('NIKON CORPORATION NIKON D700', 'NIKON AF NIKKOR 50MM F/1.8D'),
|
||||
];
|
||||
expect(
|
||||
defaultForMeta(defaults, {
|
||||
camera: 'NIKON CORPORATION NIKON D700',
|
||||
lens: 'NIKON AF NIKKOR 85MM F/1.8G',
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('requires both camera and lens metadata', () => {
|
||||
const defaults = [
|
||||
savedDefault('NIKON CORPORATION NIKON D700', 'NIKON AF NIKKOR 50MM F/1.8D'),
|
||||
];
|
||||
expect(defaultForMeta(defaults, { camera: 'NIKON D700', lens: undefined })).toBeNull();
|
||||
expect(defaultForMeta(defaults, { camera: undefined, lens: 'NIKKOR 50mm f/1.8D' })).toBeNull();
|
||||
});
|
||||
|
||||
it('uses the first row when more than one entry has the same key', () => {
|
||||
const older = { ...savedDefault('NIKON D700', 'NIKKOR 50mm f/1.8D'), updatedAt: 1 };
|
||||
const newer = { ...savedDefault('NIKON D700', 'NIKON AF NIKKOR 50MM F/1.8D'), updatedAt: 2 };
|
||||
expect(
|
||||
defaultForMeta([newer, older], {
|
||||
camera: 'NIKON CORPORATION NIKON D700',
|
||||
lens: 'Nikkor AF 50mm f/1.8D',
|
||||
}),
|
||||
).toBe(newer);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { getKV, setKV } from './db';
|
||||
import { cameraKey, lensMatchKey } from './lensNames';
|
||||
import type { LensProfile, PhotoMeta } from '../types';
|
||||
|
||||
const DEFAULTS_KEY = 'cameraLensDefaults';
|
||||
const MAX_DEFAULTS = 40;
|
||||
|
||||
/** A profile that should be applied automatically when this body + lens imports. */
|
||||
export interface CameraLensDefault {
|
||||
camera: string;
|
||||
exifLens: string;
|
||||
profile: LensProfile;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
function validProfile(profile: unknown): profile is LensProfile {
|
||||
if (!profile || typeof profile !== 'object') return false;
|
||||
const value = profile as Partial<LensProfile>;
|
||||
return (
|
||||
typeof value.maker === 'string' &&
|
||||
value.maker.trim().length > 0 &&
|
||||
typeof value.model === 'string' &&
|
||||
value.model.trim().length > 0
|
||||
);
|
||||
}
|
||||
|
||||
export async function loadCameraLensDefaults(): Promise<CameraLensDefault[]> {
|
||||
const saved = await getKV<CameraLensDefault[]>(DEFAULTS_KEY);
|
||||
if (!Array.isArray(saved)) return [];
|
||||
return saved.filter(
|
||||
(entry): entry is CameraLensDefault =>
|
||||
Boolean(
|
||||
entry &&
|
||||
typeof entry.camera === 'string' &&
|
||||
entry.camera.trim() &&
|
||||
typeof entry.exifLens === 'string' &&
|
||||
entry.exifLens.trim() &&
|
||||
validProfile(entry.profile),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Default for this exact body and normalized EXIF lens, newest first. */
|
||||
export function defaultForMeta(
|
||||
defaults: CameraLensDefault[],
|
||||
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||
): CameraLensDefault | null {
|
||||
if (!meta.camera || !meta.lens) return null;
|
||||
const body = cameraKey(meta.camera);
|
||||
const lens = lensMatchKey(meta.lens);
|
||||
if (!body || !lens) return null;
|
||||
return (
|
||||
defaults.find(
|
||||
(entry) => cameraKey(entry.camera) === body && lensMatchKey(entry.exifLens) === lens,
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export async function saveCameraLensDefault(
|
||||
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||
profile: LensProfile,
|
||||
): Promise<CameraLensDefault | null> {
|
||||
if (!meta.camera || !meta.lens) return null;
|
||||
const entry: CameraLensDefault = {
|
||||
camera: meta.camera,
|
||||
exifLens: meta.lens,
|
||||
profile,
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
const defaults = await loadCameraLensDefaults();
|
||||
const body = cameraKey(meta.camera);
|
||||
const lens = lensMatchKey(meta.lens);
|
||||
const next = [
|
||||
entry,
|
||||
...defaults.filter(
|
||||
(old) => !(cameraKey(old.camera) === body && lensMatchKey(old.exifLens) === lens),
|
||||
),
|
||||
].slice(0, MAX_DEFAULTS);
|
||||
await setKV(DEFAULTS_KEY, next);
|
||||
return entry;
|
||||
}
|
||||
|
||||
export async function removeCameraLensDefault(
|
||||
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||
): Promise<void> {
|
||||
if (!meta.camera || !meta.lens) return;
|
||||
const body = cameraKey(meta.camera);
|
||||
const lens = lensMatchKey(meta.lens);
|
||||
const defaults = await loadCameraLensDefaults();
|
||||
await setKV(
|
||||
DEFAULTS_KEY,
|
||||
defaults.filter(
|
||||
(entry) => !(cameraKey(entry.camera) === body && lensMatchKey(entry.exifLens) === lens),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getCameraLensDefault(
|
||||
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||
): Promise<CameraLensDefault | null> {
|
||||
return defaultForMeta(await loadCameraLensDefaults(), meta);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
cameraKey,
|
||||
decodeLensText,
|
||||
lensMatchKey,
|
||||
lensMatchScore,
|
||||
lensSearchVariants,
|
||||
} from './lensNames';
|
||||
|
||||
describe('lens name normalization', () => {
|
||||
it('decodes EXIF entities and collapses whitespace', () => {
|
||||
expect(decodeLensText(' Canon "L" 50mm ')).toBe('Canon "L" 50mm');
|
||||
});
|
||||
|
||||
it('ignores manufacturer prefixes when comparing equivalent lens names', () => {
|
||||
expect(lensMatchKey('NIKON AF NIKKOR 50MM F/1.8D')).toBe(
|
||||
lensMatchKey('Nikkor AF 50mm f/1.8D'),
|
||||
);
|
||||
expect(lensMatchKey('SIGMA 35mm F1.4 DG HSM | Art')).toBe(
|
||||
lensMatchKey('35mm F1.4 DG HSM Art'),
|
||||
);
|
||||
});
|
||||
|
||||
it('normalizes 1: apertures and AF-S aliases', () => {
|
||||
expect(lensMatchKey('NIKON 50mm 1:1.8D')).toBe(lensMatchKey('Nikkor 50mm f/1.8D'));
|
||||
expect(lensMatchKey('AF-S NIKKOR 24-70mm f/2.8E ED VR')).toBe(
|
||||
lensMatchKey('Nikon AF-S NIKKOR 24-70mm f/2.8E ED VR'),
|
||||
);
|
||||
});
|
||||
|
||||
it('builds progressively looser Lensfun search variants', () => {
|
||||
const variants = lensSearchVariants('NIKON AF NIKKOR 50MM F/1.8D');
|
||||
expect(variants).toContain('NIKON AF NIKKOR 50MM F/1.8D');
|
||||
expect(variants).toContain('af 50mm f/1.8');
|
||||
});
|
||||
|
||||
it('collapses a duplicated camera maker', () => {
|
||||
expect(cameraKey('NIKON CORPORATION NIKON D700')).toBe(cameraKey('NIKON D700'));
|
||||
expect(cameraKey('NIKON CORPORATION NIKON D700')).toBe('nikon d700');
|
||||
});
|
||||
});
|
||||
|
||||
describe('lens match scoring', () => {
|
||||
it('gives exact normalized matches the highest score', () => {
|
||||
expect(lensMatchScore('NIKON AF NIKKOR 50MM F/1.8D', 'Nikkor AF 50mm f/1.8D')).toBe(3);
|
||||
});
|
||||
|
||||
it('scores useful partial matches and rejects unrelated lenses', () => {
|
||||
const partial = lensMatchScore('NIKKOR 50mm 1:1.8D', 'Nikkor AF 50mm f/1.8D');
|
||||
expect(partial).toBeGreaterThan(0);
|
||||
expect(partial).toBeLessThan(3);
|
||||
expect(lensMatchScore('NIKKOR 50mm f/1.8D', 'Canon EF 24-70mm f/2.8L')).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* Camera and lens names arrive in several dialects: bodies repeat the maker
|
||||
* ("NIKON CORPORATION NIKON D700"), lenses carry maker prefixes and feature
|
||||
* suffixes ("NIKON AF NIKKOR 50MM F/1.8D"), and EXIF sometimes uses 1:1.8 for
|
||||
* the aperture. These helpers put those names into one comparable form.
|
||||
*/
|
||||
|
||||
const LENS_MAKERS = [
|
||||
'carl zeiss',
|
||||
'nikon corporation',
|
||||
'fujifilm',
|
||||
'fujinon',
|
||||
'hasselblad',
|
||||
'panasonic',
|
||||
'olympus',
|
||||
'voigtlander',
|
||||
'samsung',
|
||||
'pentax',
|
||||
'ricoh',
|
||||
'sigma',
|
||||
'tamron',
|
||||
'tokina',
|
||||
'samyang',
|
||||
'rokinon',
|
||||
'sony',
|
||||
'canon',
|
||||
'nikon',
|
||||
'nikkor',
|
||||
'leica',
|
||||
'zeiss',
|
||||
];
|
||||
|
||||
const LENS_TOKEN_ALIASES: Record<string, string> = {
|
||||
nikkor: '',
|
||||
nikon: '',
|
||||
canon: '',
|
||||
fujinon: '',
|
||||
fujifilm: '',
|
||||
sony: '',
|
||||
minolta: '',
|
||||
konica: '',
|
||||
olympus: '',
|
||||
panasonic: '',
|
||||
leica: '',
|
||||
pentax: '',
|
||||
sigma: '',
|
||||
tamron: '',
|
||||
tokina: '',
|
||||
samyang: '',
|
||||
rokinon: '',
|
||||
voigtlander: '',
|
||||
hasselblad: '',
|
||||
samsung: '',
|
||||
ricoh: '',
|
||||
zeiss: '',
|
||||
'af-s': 'afs',
|
||||
'af s': 'afs',
|
||||
'af-i': 'afi',
|
||||
'af i': 'afi',
|
||||
'ai-s': 'ais',
|
||||
'ai s': 'ais',
|
||||
'vr-ii': 'vr2',
|
||||
'vr ii': 'vr2',
|
||||
};
|
||||
|
||||
export function decodeLensText(value?: string): string {
|
||||
if (!value) return '';
|
||||
return value
|
||||
.replace(/\0/g, ' ')
|
||||
.replace(/"/gi, '"')
|
||||
.replace(/'|'/gi, "'")
|
||||
.replace(/&/gi, '&')
|
||||
.replace(/</gi, '<')
|
||||
.replace(/>/gi, '>')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Lowercase, normalize units/apertures and remove punctuation noise. */
|
||||
function cleanLensName(value?: string): string {
|
||||
let text = decodeLensText(value).toLowerCase();
|
||||
text = text
|
||||
.replace(/[“”„]/g, '"')
|
||||
.replace(/\b(lens model|lens|zoom|camera)\b/g, ' ')
|
||||
.replace(/\b1\s*:\s*/g, 'f/')
|
||||
.replace(/\bf\s*\/?\s*(\d+(?:\.\d+)?)/g, 'f/$1')
|
||||
.replace(/(\d)\s*mm\b/g, '$1mm')
|
||||
.replace(/([a-z]{2,})(\d)/g, '$1 $2')
|
||||
.replace(/f\/(\d+(?:\.\d+)?)([a-z]+)/g, 'f/$1 $2')
|
||||
.replace(/[–—]/g, '-')
|
||||
.replace(/[^a-z0-9./-]+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
return text;
|
||||
}
|
||||
|
||||
function withoutMakerPrefix(value: string): string {
|
||||
let text = value.trim();
|
||||
for (const maker of LENS_MAKERS) {
|
||||
if (text.startsWith(`${maker} `)) {
|
||||
text = text.slice(maker.length + 1).trim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
return text
|
||||
.split(' ')
|
||||
.map((token) => LENS_TOKEN_ALIASES[token] ?? token)
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Canonical token set; good for deciding whether two EXIF strings mean the same lens. */
|
||||
export function lensMatchKey(value?: string): string {
|
||||
if (!value) return '';
|
||||
return withoutMakerPrefix(cleanLensName(value))
|
||||
.split(/\s+/)
|
||||
.filter((token) => token && token !== 'lens')
|
||||
.sort()
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
/** Text forms worth passing to Lensfun's fuzzy search, loosest last. */
|
||||
export function lensSearchVariants(value?: string): string[] {
|
||||
const raw = decodeLensText(value);
|
||||
if (raw.length < 2) return [];
|
||||
const normalized = cleanLensName(raw);
|
||||
const stripped = withoutMakerPrefix(normalized);
|
||||
const tokens = (stripped || normalized).split(/\s+/).filter(Boolean);
|
||||
const focal = tokens.find((token) => /^\d+(?:\.\d+)?(?:-\d+)?mm$/.test(token));
|
||||
const aperture = tokens.find((token) => /^f\/\d+(?:\.\d+)?$/.test(token));
|
||||
const series = tokens.filter((token) =>
|
||||
/^(afs|afi|ai|ais|ef|efs|rf|fe|e|z|sp|art|sports|dg|dn|hsm|usm|stm|vc|vr|is|ii|iii|iv)$/.test(token),
|
||||
);
|
||||
const compact = [tokens[0], focal, aperture].filter(Boolean).join(' ');
|
||||
const withSeries = [compact, ...series].filter(Boolean).join(' ');
|
||||
const variants = [raw, normalized, stripped, compact, withSeries];
|
||||
return [...new Set(variants.filter((text) => text.length >= 2))];
|
||||
}
|
||||
|
||||
/** Trace a camera body to a stable key, collapsing duplicate maker names. */
|
||||
export function cameraKey(camera?: string): string {
|
||||
if (!camera) return '';
|
||||
const tokens = decodeLensText(camera)
|
||||
.toLowerCase()
|
||||
.replace(/\b(corporation|corp|incorporated|inc|ltd|limited|co)\b/g, ' ')
|
||||
.replace(/[^a-z0-9]+/g, ' ')
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter(Boolean);
|
||||
const out: string[] = [];
|
||||
for (const token of tokens) {
|
||||
if (out[out.length - 1] !== token) out.push(token);
|
||||
}
|
||||
return out.join(' ');
|
||||
}
|
||||
|
||||
/** Token overlap score used to pick the best Lensfun search result. */
|
||||
export function lensMatchScore(left?: string, right?: string): number {
|
||||
const a = lensMatchKey(left);
|
||||
const b = lensMatchKey(right);
|
||||
if (!a || !b) return 0;
|
||||
if (a === b) return 3;
|
||||
const at = new Set(a.split(' '));
|
||||
const bt = new Set(b.split(' '));
|
||||
let shared = 0;
|
||||
for (const token of at) if (bt.has(token)) shared += 1;
|
||||
if (!shared) return 0;
|
||||
return shared / Math.max(at.size, bt.size);
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
import type {
|
||||
CameraMatch,
|
||||
CorrectionMaps,
|
||||
LensMatch,
|
||||
LensfunClient,
|
||||
} from '@neoanaloglabkk/lensfun-wasm';
|
||||
import { lensMatchScore, lensSearchVariants } from './lensNames';
|
||||
import type { LensProfile, PhotoMeta } from '../types';
|
||||
|
||||
/**
|
||||
* Lensfun is loaded on demand from public/lensfun. The database and the
|
||||
* WebAssembly wrapper are third-party assets; see public/lensfun/NOTICE.md.
|
||||
*/
|
||||
export interface LensMap {
|
||||
data: Float32Array;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface LensCorrection {
|
||||
key: string;
|
||||
geometry: LensMap;
|
||||
/** RG offsets: red dx, red dy, blue dx, blue dy, normalized source units. */
|
||||
tca?: LensMap;
|
||||
/** RGB vignetting gains. */
|
||||
vignette?: LensMap;
|
||||
/** Centre zoom needed to hide transformed corners. */
|
||||
scale: number;
|
||||
}
|
||||
|
||||
const FLAG_TCA = 1;
|
||||
const FLAG_VIGNETTING = 2;
|
||||
const FLAG_DISTORTION = 8;
|
||||
|
||||
let clientPromise: Promise<LensfunClient> | null = null;
|
||||
let client: LensfunClient | null = null;
|
||||
const handleCache = new Map<string, LensMatch>();
|
||||
const cameraCache = new Map<string, CameraMatch | null>();
|
||||
const correctionCache = new Map<string, LensCorrection>();
|
||||
|
||||
async function loadCoreFactory(): Promise<(options?: Record<string, unknown>) => Promise<unknown>> {
|
||||
const response = await fetch('/lensfun/lensfun-core.js');
|
||||
if (!response.ok) throw new Error('Could not load the Lensfun runtime');
|
||||
let source = await response.text();
|
||||
// The 0.1.3 Emscripten build keeps the float heap view in a closure and the
|
||||
// wrapper reads it from `module.HEAPF32`, so expose it after every memory
|
||||
// resize. The asset itself is untouched on disk.
|
||||
if (!source.includes('Module["HEAPF32"]')) {
|
||||
const marker = 'HEAPF32=new Float32Array(b)';
|
||||
if (!source.includes(marker)) throw new Error('Unexpected Lensfun runtime layout');
|
||||
source = source.replace(marker, `${marker};Module["HEAPF32"]=HEAPF32;`);
|
||||
}
|
||||
const scriptUrl = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.src = scriptUrl;
|
||||
script.onload = () => {
|
||||
script.remove();
|
||||
resolve();
|
||||
};
|
||||
script.onerror = () => {
|
||||
script.remove();
|
||||
reject(new Error('Could not start the Lensfun runtime'));
|
||||
};
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
} finally {
|
||||
URL.revokeObjectURL(scriptUrl);
|
||||
}
|
||||
const factory = (globalThis as Record<string, unknown>).createLensfunCoreModule;
|
||||
if (typeof factory !== 'function') throw new Error('Lensfun runtime did not initialize');
|
||||
return factory as (options?: Record<string, unknown>) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export async function getLensfun(): Promise<LensfunClient> {
|
||||
if (client) return client;
|
||||
if (!clientPromise) {
|
||||
clientPromise = import('@neoanaloglabkk/lensfun-wasm')
|
||||
.then(async ({ createLensfun }) => {
|
||||
const moduleFactory = await loadCoreFactory();
|
||||
return createLensfun({
|
||||
moduleFactory,
|
||||
wasmUrl: '/lensfun/lensfun-core.wasm',
|
||||
dataUrl: '/lensfun/lensfun-core.data',
|
||||
});
|
||||
})
|
||||
.then((instance) => {
|
||||
client = instance;
|
||||
return instance;
|
||||
})
|
||||
.catch((err) => {
|
||||
clientPromise = null;
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
return clientPromise;
|
||||
}
|
||||
|
||||
export function profileKey(profile: LensProfile) {
|
||||
return `${profile.maker}\u0000${profile.model}`;
|
||||
}
|
||||
|
||||
export interface LensSearchResult {
|
||||
maker: string;
|
||||
model: string;
|
||||
crop: number;
|
||||
score: number;
|
||||
available: number;
|
||||
}
|
||||
|
||||
function toResult(match: LensMatch, available = 0): LensSearchResult {
|
||||
return {
|
||||
maker: match.maker,
|
||||
model: match.model,
|
||||
crop: match.cropFactor,
|
||||
score: match.score,
|
||||
available,
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchLens(
|
||||
query: string,
|
||||
meta?: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||
): Promise<LensSearchResult[]> {
|
||||
const variants = lensSearchVariants(query);
|
||||
if (!variants.length) return [];
|
||||
const lf = await getLensfun();
|
||||
const camera = cameraParts(meta?.camera);
|
||||
const cameraFields = {
|
||||
...(camera.maker ? { cameraMaker: camera.maker } : {}),
|
||||
...(camera.model ? { cameraModel: camera.model } : {}),
|
||||
};
|
||||
const byName = new Map<string, LensMatch>();
|
||||
for (const variant of variants) {
|
||||
let matches: LensMatch[] = [];
|
||||
try {
|
||||
matches = lf.searchLenses({ lensModel: variant, ...cameraFields });
|
||||
} catch {
|
||||
matches = [];
|
||||
}
|
||||
if (!matches.length) {
|
||||
try {
|
||||
matches = lf.searchLenses({ lensModel: variant });
|
||||
} catch {
|
||||
matches = [];
|
||||
}
|
||||
}
|
||||
for (const match of matches) {
|
||||
const key = `${match.maker}\u0000${match.model}`;
|
||||
if (!byName.has(key)) byName.set(key, match);
|
||||
}
|
||||
}
|
||||
const crop = (await findCamera(meta?.camera))?.cropFactor || 1;
|
||||
return [...byName.values()].slice(0, 20).map((match) => {
|
||||
handleCache.set(`${match.maker}\u0000${match.model}`, match);
|
||||
return toResult(match, lf.getAvailableModifications(match.handle, crop));
|
||||
});
|
||||
}
|
||||
|
||||
export async function findLensForMeta(
|
||||
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||
): Promise<LensSearchResult | null> {
|
||||
if (!meta.lens) return null;
|
||||
const results = await searchLens(meta.lens, meta);
|
||||
if (!results.length) return null;
|
||||
let best = results[0];
|
||||
let score = lensMatchScore(meta.lens, best.model);
|
||||
for (const candidate of results.slice(1)) {
|
||||
const next = lensMatchScore(meta.lens, candidate.model);
|
||||
if (next > score) {
|
||||
best = candidate;
|
||||
score = next;
|
||||
}
|
||||
}
|
||||
return score > 0 ? best : null;
|
||||
}
|
||||
|
||||
export async function resolveLens(profile: LensProfile): Promise<LensMatch | null> {
|
||||
const key = profileKey(profile);
|
||||
const cached = handleCache.get(key);
|
||||
if (cached) return cached;
|
||||
const lf = await getLensfun();
|
||||
const cam = cameraParts(profile.cameraModel);
|
||||
const cameraFields = {
|
||||
...(profile.cameraMaker || cam.maker ? { cameraMaker: profile.cameraMaker ?? cam.maker } : {}),
|
||||
...(profile.cameraModel || cam.model ? { cameraModel: cam.model ?? profile.cameraModel } : {}),
|
||||
};
|
||||
const tokens = profile.model.split(/\s+/).filter(Boolean);
|
||||
const focal = tokens.find((token) => /^\d+(?:\.\d+)?mm$/i.test(token));
|
||||
const aperture = tokens.find((token) => /^f\/\d+(?:\.\d+)?[a-z]*$/i.test(token));
|
||||
const shortened = tokens
|
||||
.filter((token) => !/^(af|af-s|af-i|ai|ai-s|ais|d|g|ed|vr|if|asp|ld|dx|fx)$/i.test(token))
|
||||
.join(' ');
|
||||
const queries: { lensMaker?: string; lensModel: string; cameraMaker?: string; cameraModel?: string }[] = [
|
||||
{ ...cameraFields, lensMaker: profile.maker, lensModel: profile.model },
|
||||
{ ...cameraFields, lensModel: profile.model },
|
||||
{ ...cameraFields, lensModel: shortened },
|
||||
...(focal
|
||||
? [{ ...cameraFields, lensModel: [tokens[0], focal, aperture].filter(Boolean).join(' ') }]
|
||||
: []),
|
||||
];
|
||||
const attempts: LensMatch[] = [];
|
||||
for (const query of queries) {
|
||||
try {
|
||||
const found = lf.searchLenses(query);
|
||||
if (found.length) {
|
||||
attempts.push(...found);
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
/* try the next, looser query */
|
||||
}
|
||||
}
|
||||
const exact =
|
||||
attempts.find(
|
||||
(match) =>
|
||||
match.maker.toLowerCase() === profile.maker.toLowerCase() &&
|
||||
match.model.toLowerCase() === profile.model.toLowerCase(),
|
||||
) ?? attempts[0];
|
||||
if (exact) handleCache.set(key, exact);
|
||||
return exact ?? null;
|
||||
}
|
||||
|
||||
export async function availableFor(profile: LensProfile): Promise<number> {
|
||||
const match = await resolveLens(profile);
|
||||
if (!match) return 0;
|
||||
const lf = await getLensfun();
|
||||
return lf.getAvailableModifications(match.handle, profile.crop);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- camera search */
|
||||
|
||||
function cameraParts(camera?: string): { maker?: string; model?: string } {
|
||||
if (!camera) return {};
|
||||
const cleaned = camera.replace(/\s+/g, ' ').trim();
|
||||
const lower = cleaned.toLowerCase();
|
||||
const makerNames = [
|
||||
'Nikon Corporation',
|
||||
'Canon',
|
||||
'Sony',
|
||||
'FUJIFILM',
|
||||
'Olympus',
|
||||
'Panasonic',
|
||||
'PENTAX',
|
||||
'Sigma',
|
||||
'Tamron',
|
||||
'Leica',
|
||||
'Hasselblad',
|
||||
'Samsung',
|
||||
'Ricoh',
|
||||
];
|
||||
const maker = makerNames.find((name) => lower.startsWith(name.toLowerCase()));
|
||||
if (maker) {
|
||||
return { maker, model: cleaned.slice(maker.length).trim() || cleaned };
|
||||
}
|
||||
const [first, ...rest] = cleaned.split(' ');
|
||||
return rest.length ? { maker: first, model: rest.join(' ') } : { model: cleaned };
|
||||
}
|
||||
|
||||
export async function findCamera(camera?: string): Promise<CameraMatch | null> {
|
||||
if (!camera) return null;
|
||||
const cached = cameraCache.get(camera);
|
||||
if (cached !== undefined) return cached;
|
||||
const lf = await getLensfun();
|
||||
const parts = cameraParts(camera);
|
||||
let found: CameraMatch[] = [];
|
||||
try {
|
||||
found = lf.searchCameras({ ...parts, searchFlags: 1 });
|
||||
} catch {
|
||||
found = [];
|
||||
}
|
||||
if (!found.length) {
|
||||
try {
|
||||
found = lf.searchCameras({ model: camera, searchFlags: 1 });
|
||||
} catch {
|
||||
found = [];
|
||||
}
|
||||
}
|
||||
const best = found[0] ?? null;
|
||||
cameraCache.set(camera, best);
|
||||
return best;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- correction maps */
|
||||
|
||||
export function autoScaleFor(geometry: LensMap): number {
|
||||
const sample = (x: number, y: number) => {
|
||||
const px = x * (geometry.width - 1);
|
||||
const py = y * (geometry.height - 1);
|
||||
const x0 = Math.max(0, Math.min(geometry.width - 1, Math.floor(px)));
|
||||
const y0 = Math.max(0, Math.min(geometry.height - 1, Math.floor(py)));
|
||||
const x1 = Math.min(geometry.width - 1, x0 + 1);
|
||||
const y1 = Math.min(geometry.height - 1, y0 + 1);
|
||||
const fx = px - x0;
|
||||
const fy = py - y0;
|
||||
const at = (xx: number, yy: number) => (yy * geometry.width + xx) * 4;
|
||||
const a = at(x0, y0);
|
||||
const b = at(x1, y0);
|
||||
const c = at(x0, y1);
|
||||
const d = at(x1, y1);
|
||||
return {
|
||||
x: (geometry.data[a] * (1 - fx) + geometry.data[b] * fx) * (1 - fy) +
|
||||
(geometry.data[c] * (1 - fx) + geometry.data[d] * fx) * fy,
|
||||
y: (geometry.data[a + 1] * (1 - fx) + geometry.data[b + 1] * fx) * (1 - fy) +
|
||||
(geometry.data[c + 1] * (1 - fx) + geometry.data[d + 1] * fx) * fy,
|
||||
};
|
||||
};
|
||||
const inside = (scale: number) => {
|
||||
for (let iy = 0; iy <= 24; iy++) {
|
||||
for (let ix = 0; ix <= 24; ix++) {
|
||||
const x = 0.5 + (ix / 24 - 0.5) / scale;
|
||||
const y = 0.5 + (iy / 24 - 0.5) / scale;
|
||||
const p = sample(x, y);
|
||||
if (p.x < 0.001 || p.y < 0.001 || p.x > 0.999 || p.y > 0.999) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
if (inside(1)) return 1;
|
||||
let lo = 1;
|
||||
let hi = 2.5;
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const mid = (lo + hi) / 2;
|
||||
if (inside(mid)) hi = mid;
|
||||
else lo = mid;
|
||||
}
|
||||
return hi;
|
||||
}
|
||||
|
||||
function bilinear(values: Float32Array, w: number, h: number, x: number, y: number, stride: number, offset: number) {
|
||||
const px = Math.max(0, Math.min(w - 1, x * (w - 1)));
|
||||
const py = Math.max(0, Math.min(h - 1, y * (h - 1)));
|
||||
const x0 = Math.floor(px);
|
||||
const y0 = Math.floor(py);
|
||||
const x1 = Math.min(w - 1, x0 + 1);
|
||||
const y1 = Math.min(h - 1, y0 + 1);
|
||||
const fx = px - x0;
|
||||
const fy = py - y0;
|
||||
const at = (xx: number, yy: number) => (yy * w + xx) * stride + offset;
|
||||
const a = values[at(x0, y0)];
|
||||
const b = values[at(x1, y0)];
|
||||
const c = values[at(x0, y1)];
|
||||
const d = values[at(x1, y1)];
|
||||
return (a * (1 - fx) + b * fx) * (1 - fy) + (c * (1 - fx) + d * fx) * fy;
|
||||
}
|
||||
|
||||
export async function buildLensCorrection(
|
||||
profile: LensProfile,
|
||||
photo: { width: number; height: number; meta: Pick<PhotoMeta, 'focal' | 'aperture'> },
|
||||
): Promise<LensCorrection> {
|
||||
const key = `${profileKey(profile)}|${profile.crop}|${photo.width}x${photo.height}|${photo.meta.focal ?? 0}|${
|
||||
photo.meta.aperture ?? 0
|
||||
}|${profile.corrections.distortion ? 1 : 0}${profile.corrections.tca ? 1 : 0}${
|
||||
profile.corrections.vignetting ? 1 : 0
|
||||
}|${profile.distance ?? 1000}`;
|
||||
const cached = correctionCache.get(key);
|
||||
if (cached) return cached;
|
||||
|
||||
const match = await resolveLens(profile);
|
||||
if (!match) throw new Error('Lens profile not found in the Lensfun database');
|
||||
const focal = Number(photo.meta.focal) || 0;
|
||||
if (!focal) throw new Error('This photo has no focal length in its EXIF data');
|
||||
const lf = await getLensfun();
|
||||
const available = lf.getAvailableModifications(match.handle, profile.crop);
|
||||
const useDistortion =
|
||||
profile.corrections.distortion && (available & FLAG_DISTORTION) !== 0;
|
||||
const useTca = profile.corrections.tca && (available & FLAG_TCA) !== 0;
|
||||
const useVignetting =
|
||||
profile.corrections.vignetting &&
|
||||
(available & FLAG_VIGNETTING) !== 0 &&
|
||||
Number(photo.meta.aperture) > 0;
|
||||
const long = 640;
|
||||
const aspect = Math.max(0.1, photo.width / Math.max(1, photo.height));
|
||||
const mapW = aspect >= 1 ? long : Math.max(8, Math.round(long * aspect));
|
||||
const mapH = aspect >= 1 ? Math.max(8, Math.round(long / aspect)) : long;
|
||||
|
||||
const maps: CorrectionMaps = lf.buildCorrectionMaps({
|
||||
lensHandle: match.handle,
|
||||
width: mapW,
|
||||
height: mapH,
|
||||
focal,
|
||||
crop: profile.crop,
|
||||
step: 1,
|
||||
includeTca: useTca,
|
||||
includeVignetting: useVignetting,
|
||||
aperture: Number(photo.meta.aperture) || 1,
|
||||
distance: profile.distance ?? 1000,
|
||||
});
|
||||
|
||||
// Textures are RGBA32F so the renderer can use one upload path for all three
|
||||
// maps. Geometry and TCA only need the first channels, but keeping four
|
||||
// channels also means the texture is always fully specified.
|
||||
const geometry = new Float32Array(mapW * mapH * 4);
|
||||
for (let i = 0; i < mapW * mapH; i++) {
|
||||
if (useDistortion) {
|
||||
geometry[i * 4] = maps.geometry[i * 2] / Math.max(1, mapW - 1);
|
||||
geometry[i * 4 + 1] = maps.geometry[i * 2 + 1] / Math.max(1, mapH - 1);
|
||||
} else {
|
||||
geometry[i * 4] = (i % mapW) / Math.max(1, mapW - 1);
|
||||
geometry[i * 4 + 1] = Math.floor(i / mapW) / Math.max(1, mapH - 1);
|
||||
}
|
||||
geometry[i * 4 + 3] = 1;
|
||||
}
|
||||
const geometryMap: LensMap = { data: geometry, width: mapW, height: mapH };
|
||||
let tca: LensMap | undefined;
|
||||
if (useTca && maps.tca) {
|
||||
tca = { data: new Float32Array(mapW * mapH * 4), width: mapW, height: mapH };
|
||||
for (let i = 0; i < mapW * mapH; i++) {
|
||||
const x = (i % mapW) / Math.max(1, mapW - 1);
|
||||
const y = Math.floor(i / mapW) / Math.max(1, mapH - 1);
|
||||
const gx = useDistortion ? geometry[i * 4] : x;
|
||||
const gy = useDistortion ? geometry[i * 4 + 1] : y;
|
||||
const rx = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 0) / Math.max(1, mapW - 1);
|
||||
const ry = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 1) / Math.max(1, mapH - 1);
|
||||
const bx = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 4) / Math.max(1, mapW - 1);
|
||||
const by = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 5) / Math.max(1, mapH - 1);
|
||||
tca.data[i * 4] = rx - gx;
|
||||
tca.data[i * 4 + 1] = ry - gy;
|
||||
tca.data[i * 4 + 2] = bx - gx;
|
||||
tca.data[i * 4 + 3] = by - gy;
|
||||
}
|
||||
}
|
||||
let vignette: LensMap | undefined;
|
||||
if (useVignetting && maps.vignetting) {
|
||||
vignette = { data: new Float32Array(mapW * mapH * 4), width: mapW, height: mapH };
|
||||
for (let i = 0; i < mapW * mapH; i++) {
|
||||
vignette.data[i * 4] = maps.vignetting[i * 3];
|
||||
vignette.data[i * 4 + 1] = maps.vignetting[i * 3 + 1];
|
||||
vignette.data[i * 4 + 2] = maps.vignetting[i * 3 + 2];
|
||||
vignette.data[i * 4 + 3] = 1;
|
||||
}
|
||||
}
|
||||
const correction: LensCorrection = {
|
||||
key,
|
||||
geometry: geometryMap,
|
||||
tca,
|
||||
vignette,
|
||||
scale: useDistortion ? autoScaleFor(geometryMap) : 1,
|
||||
};
|
||||
correctionCache.set(key, correction);
|
||||
return correction;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- CPU map math */
|
||||
|
||||
export function sampleLensMap(map: LensMap, x: number, y: number): { x: number; y: number } {
|
||||
return {
|
||||
x: bilinear(map.data, map.width, map.height, x, y, 4, 0),
|
||||
y: bilinear(map.data, map.width, map.height, x, y, 4, 1),
|
||||
};
|
||||
}
|
||||
|
||||
export function correctLensPoint(
|
||||
correction: LensCorrection | null,
|
||||
x: number,
|
||||
y: number,
|
||||
): { x: number; y: number } {
|
||||
if (!correction) return { x, y };
|
||||
const sx = 0.5 + (x - 0.5) / Math.max(1e-5, correction.scale);
|
||||
const sy = 0.5 + (y - 0.5) / Math.max(1e-5, correction.scale);
|
||||
return sampleLensMap(correction.geometry, sx, sy);
|
||||
}
|
||||
|
||||
export function uncorrectLensPoint(
|
||||
correction: LensCorrection | null,
|
||||
x: number,
|
||||
y: number,
|
||||
): { x: number; y: number } {
|
||||
if (!correction) return { x, y };
|
||||
let px = x;
|
||||
let py = y;
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const mapped = correctLensPoint(correction, px, py);
|
||||
px += x - mapped.x;
|
||||
py += y - mapped.y;
|
||||
}
|
||||
return { x: px, y: py };
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
import type { PhotoRecord } from '../types';
|
||||
import { getBitmap } from './images';
|
||||
|
||||
export type MergeKind = 'hdr' | 'panorama' | 'focus';
|
||||
|
||||
export interface MergeResult {
|
||||
blob: Blob;
|
||||
width: number;
|
||||
height: number;
|
||||
thumb: string;
|
||||
kind: MergeKind;
|
||||
sourceIds: string[];
|
||||
}
|
||||
|
||||
interface Layer {
|
||||
canvas: HTMLCanvasElement;
|
||||
pixels: Uint8ClampedArray;
|
||||
gray: Uint8Array;
|
||||
grayW: number;
|
||||
grayH: number;
|
||||
dx: number;
|
||||
dy: number;
|
||||
}
|
||||
|
||||
const MAX_EDGE = 2600;
|
||||
|
||||
function scaledCanvas(bitmap: ImageBitmap): HTMLCanvasElement {
|
||||
const scale = Math.min(1, MAX_EDGE / Math.max(bitmap.width, bitmap.height));
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
|
||||
canvas.height = Math.max(1, Math.round(bitmap.height * scale));
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||
if (!ctx) throw new Error('Could not create a merge canvas');
|
||||
ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
|
||||
return canvas;
|
||||
}
|
||||
|
||||
function readPixels(canvas: HTMLCanvasElement) {
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||
if (!ctx) throw new Error('Could not read the merge pixels');
|
||||
return ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
}
|
||||
|
||||
function grayFrom(pixels: Uint8ClampedArray, width: number, height: number, maxW = 360) {
|
||||
const scale = Math.min(1, maxW / width);
|
||||
const w = Math.max(1, Math.round(width * scale));
|
||||
const h = Math.max(1, Math.round(height * scale));
|
||||
const out = new Uint8Array(w * h);
|
||||
for (let y = 0; y < h; y++) {
|
||||
const sy = Math.min(height - 1, Math.round((y / h) * height));
|
||||
for (let x = 0; x < w; x++) {
|
||||
const sx = Math.min(width - 1, Math.round((x / w) * width));
|
||||
const o = (sy * width + sx) * 4;
|
||||
out[y * w + x] = Math.round(0.2126 * pixels[o] + 0.7152 * pixels[o + 1] + 0.0722 * pixels[o + 2]);
|
||||
}
|
||||
}
|
||||
return { data: out, w, h };
|
||||
}
|
||||
|
||||
/** Translation-only alignment is enough for bracketed and focus-stacked frames. */
|
||||
function align(ref: Layer, layer: Layer, maxShift = 36) {
|
||||
const { data: a, w, h } = { data: ref.gray, w: ref.grayW, h: ref.grayH };
|
||||
let best = { dx: 0, dy: 0, score: Number.POSITIVE_INFINITY };
|
||||
for (let dy = -maxShift; dy <= maxShift; dy += 2) {
|
||||
for (let dx = -maxShift; dx <= maxShift; dx += 2) {
|
||||
let score = 0;
|
||||
let n = 0;
|
||||
for (let y = maxShift; y < h - maxShift; y += 4) {
|
||||
for (let x = maxShift; x < w - maxShift; x += 4) {
|
||||
const bx = x + Math.round((dx / maxShift) * maxShift);
|
||||
const by = y + Math.round((dy / maxShift) * maxShift);
|
||||
if (bx < 0 || by < 0 || bx >= w || by >= h) continue;
|
||||
score += Math.abs(a[y * w + x] - layer.gray[by * w + bx]);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
if (n && score / n < best.score) best = { dx, dy, score: score / n };
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function luma(pixels: Uint8ClampedArray, o: number) {
|
||||
return (0.2126 * pixels[o] + 0.7152 * pixels[o + 1] + 0.0722 * pixels[o + 2]) / 255;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exposure blending. Each frame contributes more where it is mid-toned, so a
|
||||
* blown highlight in the bright frame does not wash out the dark frame, and a
|
||||
* noisy shadow does not dominate the final image.
|
||||
*/
|
||||
function mergeHdr(layers: Layer[]) {
|
||||
const width = Math.min(...layers.map((l) => l.canvas.width));
|
||||
const height = Math.min(...layers.map((l) => l.canvas.height));
|
||||
const out = new Uint8ClampedArray(width * height * 4);
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
let r = 0;
|
||||
let g = 0;
|
||||
let b = 0;
|
||||
let total = 0;
|
||||
for (const layer of layers) {
|
||||
const sx = Math.min(layer.canvas.width - 1, Math.max(0, x + layer.dx));
|
||||
const sy = Math.min(layer.canvas.height - 1, Math.max(0, y + layer.dy));
|
||||
const o = (sy * layer.canvas.width + sx) * 4;
|
||||
const l = luma(layer.pixels, o);
|
||||
const weight = Math.max(0.03, 1 - Math.abs(l - 0.46) * 1.75);
|
||||
r += layer.pixels[o] * weight;
|
||||
g += layer.pixels[o + 1] * weight;
|
||||
b += layer.pixels[o + 2] * weight;
|
||||
total += weight;
|
||||
}
|
||||
const o = (y * width + x) * 4;
|
||||
out[o] = r / total;
|
||||
out[o + 1] = g / total;
|
||||
out[o + 2] = b / total;
|
||||
out[o + 3] = 255;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function sharpness(pixels: Uint8ClampedArray, width: number, x: number, y: number) {
|
||||
if (x < 1 || y < 1 || x >= width - 1) return 0;
|
||||
const o = (y * width + x) * 4;
|
||||
const l = luma(pixels, o);
|
||||
const lx = luma(pixels, o - 4);
|
||||
const rx = luma(pixels, o + 4);
|
||||
const ty = luma(pixels, o - width * 4);
|
||||
const by = luma(pixels, o + width * 4);
|
||||
return Math.abs(l * 4 - lx - rx - ty - by);
|
||||
}
|
||||
|
||||
/** Pick the locally sharpest source pixel, then feather the decision with a 3×3 vote. */
|
||||
function mergeFocus(layers: Layer[]) {
|
||||
const width = Math.min(...layers.map((l) => l.canvas.width));
|
||||
const height = Math.min(...layers.map((l) => l.canvas.height));
|
||||
const out = new Uint8ClampedArray(width * height * 4);
|
||||
const picks = new Uint8Array(width * height);
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
let best = 0;
|
||||
let bestScore = -1;
|
||||
for (let i = 0; i < layers.length; i++) {
|
||||
const layer = layers[i];
|
||||
const sx = Math.min(layer.canvas.width - 1, Math.max(0, x + layer.dx));
|
||||
const sy = Math.min(layer.canvas.height - 1, Math.max(0, y + layer.dy));
|
||||
const score = sharpness(layer.pixels, layer.canvas.width, sx, sy);
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
picks[y * width + x] = best;
|
||||
}
|
||||
}
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
const votes = new Map<number, number>();
|
||||
for (let dy = -1; dy <= 1; dy++) {
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
const px = Math.min(width - 1, Math.max(0, x + dx));
|
||||
const py = Math.min(height - 1, Math.max(0, y + dy));
|
||||
const pick = picks[py * width + px];
|
||||
votes.set(pick, (votes.get(pick) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
let best = picks[y * width + x];
|
||||
let bestVotes = 0;
|
||||
for (const [pick, count] of votes) {
|
||||
if (count > bestVotes) {
|
||||
best = pick;
|
||||
bestVotes = count;
|
||||
}
|
||||
}
|
||||
const layer = layers[best];
|
||||
const sx = Math.min(layer.canvas.width - 1, Math.max(0, x + layer.dx));
|
||||
const sy = Math.min(layer.canvas.height - 1, Math.max(0, y + layer.dy));
|
||||
const so = (sy * layer.canvas.width + sx) * 4;
|
||||
const o = (y * width + x) * 4;
|
||||
out[o] = layer.pixels[so];
|
||||
out[o + 1] = layer.pixels[so + 1];
|
||||
out[o + 2] = layer.pixels[so + 2];
|
||||
out[o + 3] = 255;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function panoramaOffset(left: Layer, right: Layer) {
|
||||
const w = Math.min(left.grayW, right.grayW);
|
||||
const h = Math.min(left.grayH, right.grayH);
|
||||
const minOverlap = Math.round(w * 0.12);
|
||||
const maxOverlap = Math.round(w * 0.72);
|
||||
let best = { overlap: Math.round(w * 0.35), dy: 0, score: Number.POSITIVE_INFINITY };
|
||||
for (let dy = -8; dy <= 8; dy += 2) {
|
||||
for (let overlap = minOverlap; overlap <= maxOverlap; overlap += 3) {
|
||||
let score = 0;
|
||||
let n = 0;
|
||||
for (let y = 6; y < h - 6; y += 5) {
|
||||
for (let x = w - overlap; x < w - 2; x += 4) {
|
||||
const ry = y + dy;
|
||||
if (ry < 0 || ry >= h) continue;
|
||||
score += Math.abs(left.gray[y * w + x] - right.gray[ry * w + (x - (w - overlap))]);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
if (n && score / n < best.score) best = { overlap, dy, score: score / n };
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function mergePanorama(layers: Layer[]) {
|
||||
const overlaps: number[] = [];
|
||||
const dys: number[] = [];
|
||||
for (let i = 1; i < layers.length; i++) {
|
||||
const match = panoramaOffset(layers[i - 1], layers[i]);
|
||||
overlaps.push(Math.round((match.overlap / Math.max(1, layers[i - 1].grayW)) * layers[i - 1].canvas.width));
|
||||
dys.push(Math.round((match.dy / Math.max(1, layers[i - 1].grayH)) * layers[i - 1].canvas.height));
|
||||
}
|
||||
const xs = [0];
|
||||
for (let i = 1; i < layers.length; i++) xs.push(xs[i - 1] + layers[i - 1].canvas.width - overlaps[i - 1]);
|
||||
const width = Math.max(...xs.map((x, i) => x + layers[i].canvas.width));
|
||||
const height = Math.max(...layers.map((l) => l.canvas.height));
|
||||
const acc = new Float32Array(width * height * 3);
|
||||
const weight = new Float32Array(width * height);
|
||||
|
||||
layers.forEach((layer, i) => {
|
||||
const x0 = xs[i];
|
||||
const y0 = Math.round((height - layer.canvas.height) / 2 + (i ? dys[i - 1] : 0));
|
||||
for (let y = 0; y < layer.canvas.height; y++) {
|
||||
const oy = y + y0;
|
||||
if (oy < 0 || oy >= height) continue;
|
||||
for (let x = 0; x < layer.canvas.width; x++) {
|
||||
const ox = x + x0;
|
||||
if (ox < 0 || ox >= width) continue;
|
||||
const o = (y * layer.canvas.width + x) * 4;
|
||||
const target = oy * width + ox;
|
||||
const edge = Math.min(1, Math.min(x, layer.canvas.width - 1 - x) / Math.max(1, layer.canvas.width * 0.08));
|
||||
const w = 0.15 + edge * 0.85;
|
||||
acc[target * 3] += layer.pixels[o] * w;
|
||||
acc[target * 3 + 1] += layer.pixels[o + 1] * w;
|
||||
acc[target * 3 + 2] += layer.pixels[o + 2] * w;
|
||||
weight[target] += w;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const out = new Uint8ClampedArray(width * height * 4);
|
||||
for (let i = 0; i < width * height; i++) {
|
||||
const w = weight[i] || 1;
|
||||
out[i * 4] = acc[i * 3] / w;
|
||||
out[i * 4 + 1] = acc[i * 3 + 1] / w;
|
||||
out[i * 4 + 2] = acc[i * 3 + 2] / w;
|
||||
out[i * 4 + 3] = 255;
|
||||
}
|
||||
return { pixels: out, width, height };
|
||||
}
|
||||
|
||||
function canvasFromPixels(pixels: Uint8ClampedArray, width: number, height: number) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) throw new Error('Could not build the merged image');
|
||||
const image = ctx.createImageData(width, height);
|
||||
image.data.set(pixels);
|
||||
ctx.putImageData(image, 0, 0);
|
||||
return canvas;
|
||||
}
|
||||
|
||||
function thumbFrom(canvas: HTMLCanvasElement) {
|
||||
const thumb = document.createElement('canvas');
|
||||
const scale = 480 / Math.max(canvas.width, canvas.height);
|
||||
thumb.width = Math.max(1, Math.round(canvas.width * scale));
|
||||
thumb.height = Math.max(1, Math.round(canvas.height * scale));
|
||||
thumb.getContext('2d')?.drawImage(canvas, 0, 0, thumb.width, thumb.height);
|
||||
return thumb.toDataURL('image/jpeg', 0.82);
|
||||
}
|
||||
|
||||
export async function mergePhotos(
|
||||
photos: PhotoRecord[],
|
||||
kind: MergeKind,
|
||||
onProgress?: (done: number, total: number) => void,
|
||||
): Promise<MergeResult> {
|
||||
if (photos.length < 2) throw new Error('Select at least two photos to merge');
|
||||
const layers: Layer[] = [];
|
||||
for (let i = 0; i < photos.length; i++) {
|
||||
onProgress?.(i, photos.length);
|
||||
const bitmap = await getBitmap(photos[i]);
|
||||
const canvas = scaledCanvas(bitmap);
|
||||
const image = readPixels(canvas);
|
||||
const gray = grayFrom(image.data, canvas.width, canvas.height);
|
||||
layers.push({
|
||||
canvas,
|
||||
pixels: image.data,
|
||||
gray: gray.data,
|
||||
grayW: gray.w,
|
||||
grayH: gray.h,
|
||||
dx: 0,
|
||||
dy: 0,
|
||||
});
|
||||
}
|
||||
onProgress?.(photos.length, photos.length);
|
||||
|
||||
if (kind === 'panorama') {
|
||||
const merged = mergePanorama(layers);
|
||||
const canvas = canvasFromPixels(merged.pixels, merged.width, merged.height);
|
||||
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.94));
|
||||
if (!blob) throw new Error('Could not encode the panorama');
|
||||
return { blob, width: merged.width, height: merged.height, thumb: thumbFrom(canvas), kind, sourceIds: photos.map((p) => p.id) };
|
||||
}
|
||||
|
||||
const progress = (n: number) => onProgress?.(Math.min(photos.length, photos.length - 1 + n / 10), photos.length);
|
||||
const ref = layers[0];
|
||||
for (let i = 1; i < layers.length; i++) {
|
||||
const match = align(ref, layers[i]);
|
||||
layers[i].dx = Math.round((match.dx / Math.max(1, ref.grayW)) * ref.canvas.width);
|
||||
layers[i].dy = Math.round((match.dy / Math.max(1, ref.grayH)) * ref.canvas.height);
|
||||
progress(i);
|
||||
}
|
||||
|
||||
const width = Math.min(...layers.map((l) => l.canvas.width));
|
||||
const height = Math.min(...layers.map((l) => l.canvas.height));
|
||||
const pixels = kind === 'hdr' ? mergeHdr(layers) : mergeFocus(layers);
|
||||
const canvas = canvasFromPixels(pixels, width, height);
|
||||
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.94));
|
||||
if (!blob) throw new Error('Could not encode the merged image');
|
||||
return { blob, width, height, thumb: thumbFrom(canvas), kind, sourceIds: photos.map((p) => p.id) };
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { Edits, PhotoMeta } from '../types';
|
||||
|
||||
/**
|
||||
* A camera/ISO-aware starting point for the existing denoise sliders.
|
||||
*
|
||||
* This is a deterministic profile curve, not a learned denoiser: it scales the
|
||||
* luminance and chroma smoothing with the ISO the file was shot at and keeps
|
||||
* more detail at low ISOs. The user can still tune every value afterwards.
|
||||
*/
|
||||
export function autoNoiseFor(meta: PhotoMeta): Edits['noise'] {
|
||||
const iso = Math.max(50, Number(meta.iso) || 100);
|
||||
const stops = Math.max(0, Math.log2(iso / 100));
|
||||
const luminance = Math.round(Math.min(78, stops * 11));
|
||||
const chroma = Math.round(Math.min(88, 6 + stops * 12));
|
||||
const detail = Math.round(Math.max(18, 52 - stops * 3));
|
||||
const chromaDetail = Math.round(Math.max(22, 54 - stops * 4));
|
||||
// Cameras with a known strong high-ISO reputation get a small nudge; the
|
||||
// number is deliberately modest so this never becomes a hidden "look".
|
||||
const camera = (meta.camera ?? '').toLowerCase();
|
||||
const nudge = /a7s|a7s ii|a7s iii|fx3|r6|r5|z6|z7|d5|d6/.test(camera) ? -4 : 0;
|
||||
return {
|
||||
luminance: Math.max(0, luminance + nudge),
|
||||
detail,
|
||||
chroma: Math.max(0, chroma + nudge),
|
||||
chromaDetail,
|
||||
};
|
||||
}
|
||||
+1171
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,18 @@
|
||||
/** Raw containers the server can demosaic (LibRaw) or fall back to previews for. */
|
||||
export const RAW_EXTENSIONS = new Set([
|
||||
'cr2', 'cr3', 'crw',
|
||||
'nef', 'nrw',
|
||||
'arw', 'srf', 'sr2',
|
||||
'orf',
|
||||
'rw2', 'raw', 'rwl',
|
||||
'raf',
|
||||
'pef', 'dng',
|
||||
'srw', '3fr', 'fff', 'iiq', 'x3f', 'erf', 'k25', 'kdc', 'dcr', 'mos', 'mrw', 'mef',
|
||||
]);
|
||||
|
||||
export function isRawFile(file: File): boolean {
|
||||
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
|
||||
return RAW_EXTENSIONS.has(ext);
|
||||
}
|
||||
|
||||
export const RAW_ACCEPT = [...RAW_EXTENSIONS].map((e) => `.${e}`).join(',');
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { encodeTiff16 } from './tiff';
|
||||
|
||||
function entries(bytes: Uint8Array) {
|
||||
const view = new DataView(bytes.buffer);
|
||||
const ifd = view.getUint32(4, true);
|
||||
const count = view.getUint16(ifd, true);
|
||||
const tags = new Map<number, { type: number; count: number; value: number }>();
|
||||
for (let index = 0; index < count; index++) {
|
||||
const at = ifd + 2 + index * 12;
|
||||
tags.set(view.getUint16(at, true), {
|
||||
type: view.getUint16(at + 2, true),
|
||||
count: view.getUint32(at + 4, true),
|
||||
value: view.getUint32(at + 8, true),
|
||||
});
|
||||
}
|
||||
return { tags, view };
|
||||
}
|
||||
|
||||
describe('16-bit TIFF export', () => {
|
||||
it('writes a little-endian RGB TIFF with top-down rows', async () => {
|
||||
const pixels = new Float32Array([
|
||||
// readPixels order is bottom-left first: bottom blue, top red.
|
||||
0, 0, 1, 1, 1, 0, 0, 1,
|
||||
]);
|
||||
const blob = encodeTiff16({ width: 1, height: 2, pixels });
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
const { tags, view } = entries(bytes);
|
||||
expect(bytes[0]).toBe(0x49);
|
||||
expect(bytes[1]).toBe(0x49);
|
||||
expect(tags.get(256)?.value).toBe(1);
|
||||
expect(tags.get(257)?.value).toBe(2);
|
||||
expect(tags.get(258)?.count).toBe(3);
|
||||
expect(tags.get(259)?.value).toBe(1);
|
||||
expect(tags.get(279)?.value).toBe(12);
|
||||
const dataAt = tags.get(273)?.value ?? 0;
|
||||
expect(view.getUint16(dataAt, true)).toBe(65535);
|
||||
expect(view.getUint16(dataAt + 2, true)).toBe(0);
|
||||
expect(view.getUint16(dataAt + 4, true)).toBe(0);
|
||||
expect(view.getUint16(dataAt + 6, true)).toBe(0);
|
||||
expect(view.getUint16(dataAt + 8, true)).toBe(0);
|
||||
expect(view.getUint16(dataAt + 10, true)).toBe(65535);
|
||||
});
|
||||
|
||||
it('stores an ICC profile and exposes it through tag 34675', async () => {
|
||||
const icc = new Uint8Array([1, 2, 3, 4, 5]);
|
||||
const blob = encodeTiff16({
|
||||
width: 1,
|
||||
height: 1,
|
||||
pixels: new Float32Array([1, 1, 1, 1]),
|
||||
icc,
|
||||
});
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
const { tags } = entries(bytes);
|
||||
expect(tags.get(34675)?.type).toBe(7);
|
||||
expect(tags.get(34675)?.count).toBe(icc.length);
|
||||
const at = tags.get(34675)?.value ?? 0;
|
||||
expect([...bytes.subarray(at, at + icc.length)]).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
});
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
export interface Tiff16Options {
|
||||
width: number;
|
||||
height: number;
|
||||
/** RGB samples, top-to-bottom, already in output colour space. */
|
||||
pixels: Float32Array;
|
||||
/** Optional embedded ICC profile. */
|
||||
icc?: Uint8Array | null;
|
||||
}
|
||||
|
||||
const LE = (() => {
|
||||
const probe = new Uint8Array(new Uint16Array([1]).buffer);
|
||||
return probe[0] === 1;
|
||||
})();
|
||||
|
||||
function set16(view: DataView, at: number, value: number) {
|
||||
view.setUint16(at, value & 0xffff, true);
|
||||
}
|
||||
|
||||
function set32(view: DataView, at: number, value: number) {
|
||||
view.setUint32(at, value >>> 0, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal uncompressed little-endian 16-bit RGB TIFF.
|
||||
*
|
||||
* The profile tag (34675) is included when supplied. Uncompressed keeps the
|
||||
* encoder dependency-free and lossless; the files are larger than JPEG but are
|
||||
* intended as delivery masters rather than web files.
|
||||
*/
|
||||
export function encodeTiff16({ width, height, pixels, icc }: Tiff16Options): Blob {
|
||||
const w = Math.max(1, Math.round(width));
|
||||
const h = Math.max(1, Math.round(height));
|
||||
const pixelBytes = w * h * 3 * 2;
|
||||
const profileLength = icc?.length ?? 0;
|
||||
const entries = profileLength ? 14 : 13;
|
||||
|
||||
// IFD starts after the 8-byte header. Extras follow the IFD and are aligned.
|
||||
const ifdAt = 8;
|
||||
const ifdBytes = 2 + entries * 12 + 4;
|
||||
let extraAt = ifdAt + ifdBytes;
|
||||
const align4 = (n: number) => (n + 3) & ~3;
|
||||
extraAt = align4(extraAt);
|
||||
|
||||
const bitsAt = extraAt;
|
||||
const xResAt = bitsAt + 8;
|
||||
const yResAt = xResAt + 8;
|
||||
const profileAt = yResAt + 8;
|
||||
const dataAt = align4(profileAt + profileLength);
|
||||
const total = dataAt + pixelBytes;
|
||||
const out = new Uint8Array(total);
|
||||
const view = new DataView(out.buffer);
|
||||
|
||||
// TIFF header.
|
||||
out[0] = 0x49;
|
||||
out[1] = 0x49;
|
||||
set16(view, 2, 42);
|
||||
set32(view, 4, ifdAt);
|
||||
|
||||
// IFD entries must be sorted by tag.
|
||||
set16(view, ifdAt, entries);
|
||||
let at = ifdAt + 2;
|
||||
const entry = (tag: number, type: number, count: number, value: number, inline = true) => {
|
||||
set16(view, at, tag);
|
||||
set16(view, at + 2, type);
|
||||
set32(view, at + 4, count);
|
||||
if (inline) set32(view, at + 8, value);
|
||||
else {
|
||||
set16(view, at + 8, value & 0xffff);
|
||||
set16(view, at + 10, value >>> 16);
|
||||
}
|
||||
at += 12;
|
||||
};
|
||||
|
||||
entry(256, 4, 1, w);
|
||||
entry(257, 4, 1, h);
|
||||
entry(258, 3, 3, bitsAt, false);
|
||||
entry(259, 3, 1, 1);
|
||||
entry(262, 3, 1, 2);
|
||||
entry(273, 4, 1, dataAt);
|
||||
entry(277, 3, 1, 3);
|
||||
entry(278, 4, 1, h);
|
||||
entry(279, 4, 1, pixelBytes);
|
||||
entry(282, 5, 1, xResAt, false);
|
||||
entry(283, 5, 1, yResAt, false);
|
||||
entry(284, 3, 1, 1);
|
||||
entry(296, 3, 1, 2);
|
||||
if (profileLength) entry(34675, 7, profileLength, profileAt, false);
|
||||
set32(view, at, 0); // next IFD
|
||||
|
||||
// BitsPerSample = 16,16,16; rational resolution = 300/1.
|
||||
set16(view, bitsAt, 16);
|
||||
set16(view, bitsAt + 2, 16);
|
||||
set16(view, bitsAt + 4, 16);
|
||||
set32(view, xResAt, 300);
|
||||
set32(view, xResAt + 4, 1);
|
||||
set32(view, yResAt, 300);
|
||||
set32(view, yResAt + 4, 1);
|
||||
if (icc && profileLength) out.set(icc, profileAt);
|
||||
|
||||
// WebGL's readPixels starts at the bottom-left; TIFF rows run top-to-bottom.
|
||||
if (LE) {
|
||||
const words = new Uint16Array(out.buffer, dataAt, w * h * 3);
|
||||
for (let y = 0; y < h; y++) {
|
||||
const srcY = h - 1 - y;
|
||||
for (let x = 0; x < w; x++) {
|
||||
const src = (srcY * w + x) * 4;
|
||||
const dst = (y * w + x) * 3;
|
||||
words[dst] = Math.round(Math.max(0, Math.min(1, pixels[src])) * 65535);
|
||||
words[dst + 1] = Math.round(Math.max(0, Math.min(1, pixels[src + 1])) * 65535);
|
||||
words[dst + 2] = Math.round(Math.max(0, Math.min(1, pixels[src + 2])) * 65535);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Rare big-endian browser: keep the file little-endian explicitly.
|
||||
for (let y = 0; y < h; y++) {
|
||||
const srcY = h - 1 - y;
|
||||
for (let x = 0; x < w; x++) {
|
||||
const src = (srcY * w + x) * 4;
|
||||
const dst = dataAt + (y * w + x) * 6;
|
||||
set16(view, dst, Math.round(Math.max(0, Math.min(1, pixels[src])) * 65535));
|
||||
set16(view, dst + 2, Math.round(Math.max(0, Math.min(1, pixels[src + 1])) * 65535));
|
||||
set16(view, dst + 4, Math.round(Math.max(0, Math.min(1, pixels[src + 2])) * 65535));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new Blob([out], { type: 'image/tiff' });
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export function useMediaQuery(query: string): boolean {
|
||||
const [matches, setMatches] = useState(() => {
|
||||
if (typeof window === 'undefined' || !window.matchMedia) return false;
|
||||
return window.matchMedia(query).matches;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined' || !window.matchMedia) return;
|
||||
const media = window.matchMedia(query);
|
||||
const update = () => setMatches(media.matches);
|
||||
update();
|
||||
media.addEventListener?.('change', update);
|
||||
return () => media.removeEventListener?.('change', update);
|
||||
}, [query]);
|
||||
|
||||
return matches;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useEffect, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
|
||||
const PREFIX = 'lumenroom.ui.';
|
||||
|
||||
/**
|
||||
* UI state that should survive a reload without becoming catalog data.
|
||||
* Storage failures (private mode, full disk) silently fall back to memory.
|
||||
*/
|
||||
export function usePersistentState<T>(
|
||||
key: string,
|
||||
initial: T | (() => T),
|
||||
): [T, Dispatch<SetStateAction<T>>] {
|
||||
const storageKey = `${PREFIX}${key}`;
|
||||
const [value, setValue] = useState<T>(() => {
|
||||
try {
|
||||
const raw = localStorage.getItem(storageKey);
|
||||
if (raw !== null) return JSON.parse(raw) as T;
|
||||
} catch {
|
||||
/* private mode or malformed old state */
|
||||
}
|
||||
return typeof initial === 'function' ? (initial as () => T)() : initial;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
localStorage.setItem(storageKey, JSON.stringify(value));
|
||||
} catch {
|
||||
/* storage is optional for UI preferences */
|
||||
}
|
||||
}, [storageKey, value]);
|
||||
|
||||
return [value, setValue];
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* White balance eyedropper maths.
|
||||
*
|
||||
* The grade shader applies these gains in linear light:
|
||||
* r × (1 + 0.30t + 0.06i)
|
||||
* g × (1 − 0.16i)
|
||||
* b × (1 − 0.26t + 0.06i)
|
||||
* where t = temp / 100 and i = tint / 100 (a shared luma normalisation cancels
|
||||
* out of the neutrality condition, so it is ignored here).
|
||||
*
|
||||
* Solving r·wr = g·wg and b·wb = g·wg for t and i is linear in i, which gives a
|
||||
* closed-form answer: no iteration and no drift as the sliders move.
|
||||
*/
|
||||
|
||||
const T_R = 0.3;
|
||||
const T_B = 0.26;
|
||||
const T_TINT = 0.16;
|
||||
const TINT_CROSS = 0.06;
|
||||
|
||||
function toLinear(v: number): number {
|
||||
const c = Math.min(1, Math.max(0, v));
|
||||
return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
|
||||
}
|
||||
|
||||
const clampRange = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
|
||||
|
||||
/**
|
||||
* Temperature and tint that make a sampled source colour neutral.
|
||||
* `sample` is the untouched (sRGB-encoded) source pixel, 0–1 per channel.
|
||||
* Returns null for samples too dark to carry a reliable colour cast.
|
||||
*/
|
||||
export function solveWhiteBalance(
|
||||
sample: readonly [number, number, number],
|
||||
): { temp: number; tint: number } | null {
|
||||
const r = toLinear(sample[0]);
|
||||
const g = toLinear(sample[1]);
|
||||
const b = toLinear(sample[2]);
|
||||
if (![r, g, b].every(Number.isFinite)) return null;
|
||||
if (Math.max(r, g, b) < 0.004) return null;
|
||||
|
||||
// Ratios stay finite for very saturated or very dark picks; clamping them only
|
||||
// caps how extreme the result can get, it does not affect ordinary neutrals.
|
||||
const gr = clampRange(g / Math.max(1e-4, r), 0.02, 40);
|
||||
const gb = clampRange(g / Math.max(1e-4, b), 0.02, 40);
|
||||
|
||||
const denom =
|
||||
T_R * (TINT_CROSS + T_TINT * gb) + T_B * (T_TINT * gr + TINT_CROSS);
|
||||
if (Math.abs(denom) < 1e-6) return null;
|
||||
|
||||
const ti = (T_B * (gr - 1) - T_R * (1 - gb)) / denom;
|
||||
const t = ((1 - T_TINT * ti) * gr - 1 - TINT_CROSS * ti) / T_R;
|
||||
if (!Number.isFinite(t) || !Number.isFinite(ti)) return null;
|
||||
|
||||
return {
|
||||
temp: Math.round(clampRange(t * 100, -100, 100)),
|
||||
tint: Math.round(clampRange(ti * 100, -100, 100)),
|
||||
};
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Minimal ZIP writer for photo exports. Images are already compressed, so every
|
||||
* entry is stored (method 0) instead of deflated: no CPU spent re-packing JPEGs,
|
||||
* and no extra copy of each file in memory.
|
||||
*
|
||||
* Supports UTF-8 names, up to 65535 files and up to 4 GB of total output. Larger
|
||||
* batches need ZIP64, which browsers have no business producing from a tab.
|
||||
*/
|
||||
|
||||
export interface ZipEntry {
|
||||
name: string;
|
||||
data: Blob;
|
||||
}
|
||||
|
||||
const MAX_ENTRIES = 0xffff;
|
||||
const MAX_SIZE = 0xffffffff;
|
||||
const MAX_TOTAL = MAX_SIZE - 1024 * 1024; // room for headers and the central directory
|
||||
|
||||
const CRC_TABLE = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let i = 0; i < 256; i++) {
|
||||
let c = i;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
table[i] = c >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crcUpdate(crc: number, bytes: Uint8Array) {
|
||||
let c = crc;
|
||||
for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
|
||||
return c >>> 0;
|
||||
}
|
||||
|
||||
async function blobCrc32(blob: Blob) {
|
||||
const reader = blob.stream().getReader();
|
||||
let crc = 0xffffffff;
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (value) crc = crcUpdate(crc, value);
|
||||
}
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function dosStamp(date: Date) {
|
||||
const year = Math.min(2107, Math.max(1980, date.getFullYear()));
|
||||
const time = (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1);
|
||||
const day = ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate();
|
||||
return { time, day };
|
||||
}
|
||||
|
||||
/** Keep the entry a flat file name and make collisions predictable. */
|
||||
function safeEntryName(name: string, used: Set<string>) {
|
||||
const clean = (name || 'photo.jpg').replace(/[\\/]+/g, '-').replace(/[\u0000-\u001f]/g, '').trim();
|
||||
const base = clean || 'photo.jpg';
|
||||
if (!used.has(base.toLowerCase())) {
|
||||
used.add(base.toLowerCase());
|
||||
return base;
|
||||
}
|
||||
const dot = base.lastIndexOf('.');
|
||||
const stem = dot > 0 ? base.slice(0, dot) : base;
|
||||
const ext = dot > 0 ? base.slice(dot) : '';
|
||||
let n = 2;
|
||||
while (used.has(`${stem} (${n})${ext}`.toLowerCase())) n++;
|
||||
const unique = `${stem} (${n})${ext}`;
|
||||
used.add(unique.toLowerCase());
|
||||
return unique;
|
||||
}
|
||||
|
||||
function header(size: number, write: (view: DataView, offset: number) => void) {
|
||||
const bytes = new Uint8Array(new ArrayBuffer(size));
|
||||
write(new DataView(bytes.buffer), 0);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
export async function createZipBlob(entries: ZipEntry[]): Promise<Blob> {
|
||||
if (!entries.length) throw new Error('Nothing to archive');
|
||||
if (entries.length > MAX_ENTRIES) {
|
||||
throw new Error('Too many photos for one ZIP file. Export them in smaller groups.');
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const { time, day } = dosStamp(new Date());
|
||||
const used = new Set<string>();
|
||||
const parts: BlobPart[] = [];
|
||||
const central: { name: ArrayBuffer; crc: number; size: number; offset: number }[] = [];
|
||||
let offset = 0;
|
||||
|
||||
for (const entry of entries) {
|
||||
const name = encoder.encode(safeEntryName(entry.name, used)).buffer as ArrayBuffer;
|
||||
const size = entry.data.size;
|
||||
if (size > MAX_SIZE) throw new Error(`${entry.name} is too large for a ZIP file`);
|
||||
const crc = await blobCrc32(entry.data);
|
||||
const start = offset;
|
||||
|
||||
const local = header(30, (view, at) => {
|
||||
view.setUint32(at, 0x04034b50, true);
|
||||
view.setUint16(at + 4, 20, true); // version needed
|
||||
view.setUint16(at + 6, 0x0800, true); // UTF-8 names
|
||||
view.setUint16(at + 8, 0, true); // stored
|
||||
view.setUint16(at + 10, time, true);
|
||||
view.setUint16(at + 12, day, true);
|
||||
view.setUint32(at + 14, crc, true);
|
||||
view.setUint32(at + 18, size, true);
|
||||
view.setUint32(at + 22, size, true);
|
||||
view.setUint16(at + 26, name.byteLength, true);
|
||||
view.setUint16(at + 28, 0, true);
|
||||
});
|
||||
parts.push(local, name, entry.data);
|
||||
offset += local.length + name.byteLength + size;
|
||||
|
||||
central.push({ name, crc, size, offset: start });
|
||||
if (offset > MAX_TOTAL) {
|
||||
throw new Error('This batch is too large for one ZIP file. Export it in smaller groups.');
|
||||
}
|
||||
}
|
||||
|
||||
const centralStart = offset;
|
||||
let centralSize = 0;
|
||||
for (const file of central) {
|
||||
const record = header(46, (view, at) => {
|
||||
view.setUint32(at, 0x02014b50, true);
|
||||
view.setUint16(at + 4, 20, true); // made by
|
||||
view.setUint16(at + 6, 20, true); // needed
|
||||
view.setUint16(at + 8, 0x0800, true);
|
||||
view.setUint16(at + 10, 0, true); // stored
|
||||
view.setUint16(at + 12, time, true);
|
||||
view.setUint16(at + 14, day, true);
|
||||
view.setUint32(at + 16, file.crc, true);
|
||||
view.setUint32(at + 20, file.size, true);
|
||||
view.setUint32(at + 24, file.size, true);
|
||||
view.setUint16(at + 28, file.name.byteLength, true);
|
||||
view.setUint16(at + 30, 0, true); // extra
|
||||
view.setUint16(at + 32, 0, true); // comment
|
||||
view.setUint16(at + 34, 0, true); // disk
|
||||
view.setUint16(at + 36, 0, true); // internal attrs
|
||||
view.setUint32(at + 38, 0, true); // external attrs
|
||||
view.setUint32(at + 42, file.offset, true);
|
||||
});
|
||||
parts.push(record, file.name);
|
||||
centralSize += record.length + file.name.byteLength;
|
||||
}
|
||||
|
||||
const end = header(22, (view, at) => {
|
||||
view.setUint32(at, 0x06054b50, true);
|
||||
view.setUint16(at + 4, 0, true);
|
||||
view.setUint16(at + 6, 0, true);
|
||||
view.setUint16(at + 8, central.length, true);
|
||||
view.setUint16(at + 10, central.length, true);
|
||||
view.setUint32(at + 12, centralSize, true);
|
||||
view.setUint32(at + 16, centralStart, true);
|
||||
view.setUint16(at + 20, 0, true);
|
||||
});
|
||||
parts.push(end);
|
||||
|
||||
return new Blob(parts, { type: 'application/zip' });
|
||||
}
|
||||
|
||||
function pad(n: number) {
|
||||
return String(n).padStart(2, '0');
|
||||
}
|
||||
|
||||
export function zipFileName(date = new Date()) {
|
||||
return `luminary-${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}.zip`;
|
||||
}
|
||||
Reference in New Issue
Block a user