/** * Job runner for the detail-preserving denoise. * * `server/denoise/` starts from the dependency-free pipeline of the raw-noise * package, which supplies the Guided and NLM bases; SCUNet runs the same stages * around an ONNX model. Every base is reconstructed from a per-pixel crossfade * between the source and the denoised base, so the result is bounded by the * original pixels and cannot ring or overshoot; flat noise is replaced, structure * is given back verbatim. The GPU's own `noise` sliders are a separate, much * simpler path. * * Three things here are deliberate: * * - Amount belongs to the client. The worker always renders the full-strength * denoise and the renderer applies the blend, so the slider is instant, one * file serves every amount, and the amount cannot be applied twice. * - The key carries a pipeline version. A change to `server/denoise/` has to * re-key, or the old renders keep being served as if they were current. * - Each run is seconds of solid CPU, so runs go through a capped queue and a * second request for the same photo joins the run already in progress * instead of starting an identical one. */ import crypto from 'node:crypto'; import os from 'node:os'; import { Worker } from 'node:worker_threads'; import { denoisedPath, findDenoised, removeDenoised } from './storage.mjs'; /** Lookup used by the download route; storage owns where the files live. */ export function findDenoisedFor(photoId, key) { return findDenoised(photoId, key); } /** Drop the renders for a photo, e.g. when its edit is cleared. */ export function clearDenoised(photoId) { return removeDenoised(photoId); } /** Every base the picker offers; the cache keeps one render for each of them. */ export const DENOISE_BASES = ['guided', 'scunet', 'nlm']; /** * Bump whenever the copied modules under `server/denoise/` change output. The key * is the only thing between a fixed pipeline and a stale cached file. */ const PIPELINE_VERSION = 'guided-5'; const MAX_JOBS = 40; /** * A burst of clicks must not pin every core: the raw decoders have their own * budget and the request thread still has the rest of the library to serve. */ const MAX_WORKERS = Math.max( 1, Math.min(4, Number(process.env.LUMINARY_DENOISE_WORKERS) || (os.cpus().length || 2) - 1), ); const jobs = new Map(); /** key -> job that is queued or running, so a repeat request joins it. */ const byKey = new Map(); const queue = []; let active = 0; export function getDenoiseJob(id) { return jobs.get(id) ?? null; } /** Stable for a photo, a pipeline version and a base denoiser -- Amount is the client's business. */ export function denoiseKey(photoId, base = 'guided') { return crypto .createHash('sha1') .update(`${photoId}|${PIPELINE_VERSION}|${base}`) .digest('hex') .slice(0, 12); } export function startDenoise({ photoId, sourcePath, base = 'guided' }) { const key = denoiseKey(photoId, base); const joined = byKey.get(key); if (joined) return joined; const url = `/api/photos/${encodeURIComponent(photoId)}/denoised?v=${key}`; const job = { id: crypto.randomUUID(), photoId, key, base, state: 'running', startedAt: Date.now() }; // Re-running after the edit was cleared, or a second browser, should not pay // for the CPU again. The file is the cache; the job just reports it. if (findDenoised(photoId, key)) { job.state = 'done'; job.cached = true; job.url = url; jobs.set(job.id, job); pruneJobs(); return job; } job.sourcePath = sourcePath; job.url = url; jobs.set(job.id, job); byKey.set(key, job); queue.push(job); pruneJobs(); pump(); return job; } function pump() { while (active < MAX_WORKERS && queue.length > 0) { run(queue.shift()); } } function run(job) { active += 1; const outPath = denoisedPath(job.photoId, job.key); const worker = new Worker(new URL('./denoise-worker.mjs', import.meta.url), { workerData: { sourcePath: job.sourcePath, outPath, base: job.base }, }); worker.on('message', (message) => { if (message?.type === 'progress') { job.progress = message.progress; } else if (message?.type === 'done') { job.state = 'done'; job.progress = null; job.ms = message.ms; job.bytes = message.bytes; job.stats = message.stats; // A version bump (or an older build) leaves its render behind. Keep the // current key of every base and drop only the older ones, so switching // models reuses its cached render instead of paying for the CPU again. try { removeDenoised( job.photoId, DENOISE_BASES.map((base) => denoiseKey(job.photoId, base)), ); } catch { /* cleanup is best effort -- never fail a finished job over it */ } } else if (message?.type === 'error') { job.state = 'error'; job.error = message.error; } }); worker.on('error', (error) => { job.state = 'error'; job.error = error?.message ?? 'denoise worker failed'; }); worker.on('exit', () => { // A crash inside the pipeline would otherwise leave the UI polling forever. if (job.state === 'running') { job.state = 'error'; job.error = 'denoise worker exited unexpectedly'; } active -= 1; byKey.delete(job.key); job.sourcePath = null; pump(); }); } /** Keep the newest finished jobs; never drop one that is queued or running. */ function pruneJobs() { if (jobs.size <= MAX_JOBS) return; for (const [id, job] of jobs) { if (jobs.size <= MAX_JOBS) break; if (job.state === 'running') continue; jobs.delete(id); } }