Offer SCUNet and NLM alongside the guided denoise

The AI denoise panel now picks between three bases: the existing guided
filter, non-local means and a learned SCUNet model run through
onnxruntime-node on overlapping tiles. The base is part of the render key, so
each model keeps its own cached render and switching back is instant, and jobs
report stage and tile progress instead of a bare spinner.

onnxruntime-node is pinned to 1.23.0, the last release that ships both macOS
architectures, and every Docker and desktop install skips its CUDA download
because only the CPU binaries in the package are used. The SCUNet weights and
ONNX Runtime are added to the third-party notices, the deb copyright file and
the README's denoise, API and redistribution sections.
This commit is contained in:
2026-12-01 04:03:53 +00:00
parent b34d34dacb
commit f7942d0bd0
26 changed files with 945 additions and 161 deletions
+17 -4
View File
@@ -10,10 +10,10 @@ import { parentPort, workerData } from 'node:worker_threads';
import fs from 'node:fs/promises';
import sharp from 'sharp';
import { denoiseRgb } from './denoise/rgbPipeline.ts';
import { guidedDenoiser } from './denoise/standin.ts';
import { createBaseDenoiser } from './denoise/baseDenoiser.ts';
try {
const { sourcePath, outPath } = workerData;
const { sourcePath, outPath, base = 'guided' } = workerData;
const buffer = await fs.readFile(sourcePath);
const { data, info } = await sharp(buffer)
.rotate()
@@ -37,8 +37,21 @@ try {
const started = performance.now();
// Always full strength: the Amount slider blends on the client, so one render
// serves every setting and the cache key does not move with the slider.
const out = await denoiseRgb({ rgb, width, height }, { amount: 1 }, guidedDenoiser());
// serves every setting and the cache key does not move with the slider. The
// base denoiser (guided / nlm / scunet) is chosen by the request; the cache
// key already folds it in, so a different model is a different render.
//
// Progress is the only window the panel has into a 95 s SCUNet run, so both
// the stage boundaries and the tile counter are forwarded to the job.
const report = (progress) => parentPort?.postMessage({ type: 'progress', progress });
const out = await denoiseRgb(
{ rgb, width, height },
{ amount: 1 },
createBaseDenoiser(base, (tiles) =>
report({ stage: 'base', done: tiles.done, total: tiles.total }),
),
(stage) => report({ stage }),
);
// 4:4:4 so the chroma work is not immediately thrown away by the encoder.
const jpeg = await sharp(Buffer.from(out.rgb), { raw: { width, height, channels: 3 } })
.jpeg({ quality: 95, chromaSubsampling: '4:4:4' })
+28 -16
View File
@@ -1,11 +1,13 @@
/**
* Job runner for the detail-preserving denoise.
*
* `server/denoise/` is a verbatim copy of the dependency-free pipeline from the
* raw-noise package. It reconstructs from a per-pixel crossfade between the
* source and a 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.
* `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:
*
@@ -33,6 +35,9 @@ 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.
@@ -59,23 +64,23 @@ export function getDenoiseJob(id) {
return jobs.get(id) ?? null;
}
/** Stable for a photo and a pipeline version -- Amount is the client's business. */
export function denoiseKey(photoId) {
/** 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}`)
.update(`${photoId}|${PIPELINE_VERSION}|${base}`)
.digest('hex')
.slice(0, 12);
}
export function startDenoise({ photoId, sourcePath }) {
const key = denoiseKey(photoId);
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, state: 'running', startedAt: Date.now() };
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.
@@ -108,19 +113,26 @@ 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 },
workerData: { sourcePath: job.sourcePath, outPath, base: job.base },
});
worker.on('message', (message) => {
if (message?.type === 'done') {
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 one and drop the rest so the folder cannot grow without bound.
// 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, job.key);
removeDenoised(
job.photoId,
DENOISE_BASES.map((base) => denoiseKey(job.photoId, base)),
);
} catch {
/* cleanup is best effort -- never fail a finished job over it */
}
+38
View File
@@ -0,0 +1,38 @@
/**
* Resolve a base denoiser by name -- the slot the pipeline calls as `runBase`.
*
* Three choices, all occupying the same interface from `standin.ts`:
*
* - `guided` (default): the classical guided filter. Fast, edge-preserving,
* the current shipping path.
* - `nlm`: non-local means. Slower, the quality reference the model must beat.
* - `scunet`: the learned SCUNet model, run tiled with overlap-add.
*
* Constructing is free: the ONNX session is created lazily on first use, so the
* model selector can show all three even before a run ever picks SCUNet. A
* missing model surfaces as a clear error at run time, not at import time.
*/
import { fileURLToPath } from 'node:url';
import { guidedDenoiser, nlmDenoiser, type BaseDenoiser } from './standin.ts';
import { createOnnxBaseDenoiser, type TileProgress } from './onnx.ts';
export type BaseDenoiserName = 'guided' | 'nlm' | 'scunet';
/** The SCUNet weights shipped with the server, next to this file. */
const SCUNET_MODEL = fileURLToPath(new URL('./scunet_color_25.onnx', import.meta.url));
export function createBaseDenoiser(
base: BaseDenoiserName,
onProgress?: (progress: TileProgress) => void,
): BaseDenoiser {
switch (base) {
case 'nlm':
return nlmDenoiser();
case 'scunet':
return createOnnxBaseDenoiser({ modelPath: SCUNET_MODEL, tile: 256, overlap: 32, onProgress });
case 'guided':
default:
return guidedDenoiser();
}
}
+205
View File
@@ -0,0 +1,205 @@
/**
* Tiled ONNX inference for the base plane -- the SCUNet path.
*
* This is the only file that may import `onnxruntime-node`, and it imports it
* lazily: nothing here requires a model to exist until a denoiser is actually
* asked to run. The classical stand-ins (`guided`, `nlm`) occupy the same slot
* and need no model at all, so the model selector is safe to show even before a
* run ever selects SCUNet.
*
* The model contract is fixed and small:
*
* input 1 x 3 x TILE x TILE float32, RGB in 0..1
* output 1 x 3 x TILE x TILE float32, same
*
* `runTiled` is separated from the session so the tiling, padding, feathering
* and normalisation can be reasoned about independently of ORT.
*/
import type { BaseDenoiser, BaseImage } from './standin.ts';
/** Runs one `tile x tile`, 3-channel tile. Input and output are interleaved RGB. */
export type RgbTileRunner = (input: Float32Array, tile: number) => Promise<Float32Array>;
export interface TileProgress {
done: number;
total: number;
}
export interface OnnxBaseOptions {
modelPath: string;
/** Fixed square size the graph was exported at. Must match the graph. */
tile?: number;
/** Overlap in pixels between neighbouring tiles. */
overlap?: number;
/** Defaults to physical cores. Keep it below the host's raw decode pool. */
intraOpThreads?: number;
/** Called after each tile lands, so a long run can report where it is. */
onProgress?: (progress: TileProgress) => void;
}
/**
* Raised-cosine feather along one axis, floored so no pixel is weighted zero.
*
* The floor matters: at the image border a tile is the only contributor, and a
* zero weight there would divide 0 by 0.
*/
export function featherWeights(tile: number, overlap: number): Float32Array {
const weights = new Float32Array(tile).fill(1);
const edge = Math.min(Math.max(0, overlap), Math.floor(tile / 2));
for (let i = 0; i < edge; i++) {
const t = (i + 0.5) / edge;
weights[i] = Math.max(0.5 - 0.5 * Math.cos(Math.PI * t), 1e-3);
weights[tile - 1 - i] = weights[i];
}
return weights;
}
/** Tiled inference with overlap-add and feathering. */
export async function runTiled(
runTile: RgbTileRunner,
image: BaseImage,
tile: number,
overlap: number,
onProgress?: (progress: TileProgress) => void,
): Promise<BaseImage> {
const { width, height } = image;
if (!Number.isInteger(tile) || tile < 8) throw new Error(`tile must be an integer >= 8, got ${tile}`);
if (overlap < 0 || overlap >= tile) throw new Error(`overlap must be in [0, tile), got ${overlap}`);
const expected = 3 * tile * tile;
const step = tile - overlap;
const weights = featherWeights(tile, overlap);
const acc = new Float32Array(3 * width * height);
const weight = new Float32Array(width * height);
const patch = new Float32Array(expected);
// Tiles start every `step` pixels, so the last one may hang off the edge.
const total = Math.ceil(width / step) * Math.ceil(height / step);
let done = 0;
for (let ty = 0; ty < height; ty += step) {
for (let tx = 0; tx < width; tx += step) {
// Gather with clamp-to-edge padding; the convolution needs a full tile
// even when the tile hangs off the right or bottom edge.
for (let y = 0; y < tile; y++) {
const sy = ty + y;
const cy = sy < 0 ? 0 : sy >= height ? height - 1 : sy;
for (let x = 0; x < tile; x++) {
const sx = tx + x;
const cx = sx < 0 ? 0 : sx >= width ? width - 1 : sx;
const src = (cy * width + cx) * 3;
const dst = (y * tile + x) * 3;
patch[dst] = image.rgb[src];
patch[dst + 1] = image.rgb[src + 1];
patch[dst + 2] = image.rgb[src + 2];
}
}
const out = await runTile(patch, tile);
if (out.length !== expected) {
throw new Error(`tile runner returned ${out.length} values, expected ${expected}`);
}
for (let y = 0; y < tile; y++) {
const sy = ty + y;
if (sy < 0 || sy >= height) continue;
for (let x = 0; x < tile; x++) {
const sx = tx + x;
if (sx < 0 || sx >= width) continue;
const w = weights[y] * weights[x];
const dst = (sy * width + sx) * 3;
const src = (y * tile + x) * 3;
acc[dst] += out[src] * w;
acc[dst + 1] += out[src + 1] * w;
acc[dst + 2] += out[src + 2] * w;
weight[sy * width + sx] += w;
}
}
done += 1;
onProgress?.({ done, total });
}
}
const rgb = new Float32Array(3 * width * height);
for (let i = 0, p = 0; i < width * height; i++, p += 3) {
const w = weight[i] || 1;
for (let k = 0; k < 3; k++) {
const v = acc[p + k] / w;
rgb[p + k] = v < 0 ? 0 : v > 255 ? 255 : v;
}
}
return { rgb, width, height };
}
interface Session {
run(feeds: Record<string, unknown>): Promise<Record<string, { data: Float32Array }>>;
inputNames: readonly string[];
outputNames: readonly string[];
}
/**
* Build a `BaseDenoiser` backed by an ONNX model.
*
* The session is created on first use and memoised, so constructing this is
* free and a missing model surfaces as a clear error at run time rather than at
* import time.
*/
export function createOnnxBaseDenoiser(options: OnnxBaseOptions): BaseDenoiser {
const tile = options.tile ?? 256;
const overlap = options.overlap ?? 32;
let sessionPromise: Promise<Session> | null = null;
const session = (): Promise<Session> => {
if (!sessionPromise) {
sessionPromise = (async () => {
const ort = await import('onnxruntime-node');
const created = await ort.InferenceSession.create(options.modelPath, {
executionProviders: ['cpu'],
graphOptimizationLevel: 'all',
intraOpNumThreads: options.intraOpThreads ?? 0,
});
return created as unknown as Session;
})();
}
return sessionPromise;
};
return async (image: BaseImage): Promise<BaseImage> => {
const active = await session();
const ort = await import('onnxruntime-node');
const inputName = active.inputNames[0];
const outputName = active.outputNames[0];
if (!inputName || !outputName) throw new Error('model has no input/output');
// The model expects 0..1; everything above works in 0..255.
//
// But the two sides disagree about layout: `runTiled` is interleaved (HWC),
// while every published denoiser is NCHW (`1x3xTILExTILE`). Handing HWC bytes
// to a `[1,3,T,T]` tensor does not throw -- it silently feeds a scrambled
// image, so channel 0 holds a third of every row rather than red. The output
// needs the mirror transpose for the same reason.
const plane = tile * tile;
const runTile: RgbTileRunner = async (input, size) => {
const normalised = new Float32Array(3 * plane);
for (let p = 0, i = 0; p < plane; p++, i += 3) {
normalised[p] = input[i] / 255;
normalised[plane + p] = input[i + 1] / 255;
normalised[2 * plane + p] = input[i + 2] / 255;
}
const tensor = new ort.Tensor('float32', normalised, [1, 3, size, size]);
const result = await active.run({ [inputName]: tensor });
const output = result[outputName]?.data;
if (!output) throw new Error(`model produced no output named ${outputName}`);
const scaled = new Float32Array(output.length);
for (let p = 0, i = 0; p < plane; p++, i += 3) {
scaled[i] = output[p] * 255;
scaled[i + 1] = output[plane + p] * 255;
scaled[i + 2] = output[2 * plane + p] * 255;
}
return scaled;
};
return runTiled(runTile, image, tile, overlap, options.onProgress);
};
}
+12
View File
@@ -105,6 +105,13 @@ export interface DenoiseStats {
timings: StageTimings;
}
/**
* Where a run currently is. The base stage is the expensive one (SCUNet runs it
* tile by tile); the rest are seconds at most, but naming them beats a dead
* spinner while the base is between tiles.
*/
export type DenoiseStage = 'analyse' | 'base' | 'gate' | 'render';
export interface DenoiseOutput {
rgb: Uint8Array;
/** Luma of the denoised base, before detail re-injection, for inspection. */
@@ -184,6 +191,7 @@ export async function denoiseRgb(
image: RgbImage,
options: Partial<DenoiseOptions>,
runBase: BaseDenoiser,
onStage?: (stage: DenoiseStage) => void,
): Promise<DenoiseOutput> {
const opts: DenoiseOptions = { ...DEFAULT_OPTIONS, ...options, gate: { ...DEFAULT_GATE, ...options.gate } };
const started = now();
@@ -193,6 +201,7 @@ export async function denoiseRgb(
const { y, cb, cr } = toYcc(image);
let mark = now();
onStage?.('analyse');
const noise: NoiseModel = estimateNoise(y, width, height);
const timings: StageTimings = {
noise: now() - mark,
@@ -231,6 +240,7 @@ export async function denoiseRgb(
const decimatedSigma =
backscale > 1.001 ? (prefilterWidth - 1 / 3) / (prefilterWidth * prefilterWidth) : 1;
const baseSigma = noise.sigmaAt(110) * decimatedSigma;
onStage?.('base');
const baseOut = await runBase(baseInput, baseSigma);
const baseUp = toYcc(upsampleBase(baseOut, width, height));
timings.base = now() - mark;
@@ -266,6 +276,7 @@ export async function denoiseRgb(
timings.structure = now() - mark;
mark = now();
onStage?.('gate');
let gate = detailGate(detail, width, height, sigmaMap, coherence, opts.gate);
// Second, coarser band: `smooth2 - smooth6` is a band-pass around 3-8 px. It
@@ -292,6 +303,7 @@ export async function denoiseRgb(
const autoGate = opts.cleanSigma > 0 ? smoothstep(0.8, opts.cleanSigma, noise.global) : 1;
const amount = clamp01(opts.amount) * autoGate;
onStage?.('render');
const outY = new Float32Array(pixels);
const outCb = new Float32Array(pixels);
const outCr = new Float32Array(pixels);
Binary file not shown.
Binary file not shown.
+12 -2
View File
@@ -2475,10 +2475,14 @@ route('POST', '/api/photos/:id/denoise', async ({ req, res, params }) => {
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found');
// Denoise the proxy the editor actually shows, not the raw: the result has to
// line up pixel for pixel with the canvas and with the client's export path.
// The Amount slider is the client's: the render is always full strength.
// The Amount slider is the client's: the render is always full strength. The
// base denoiser (guided / nlm / scunet) is chosen here and folded into the
// cache key, so each model renders to its own asset.
const source = findPreview(params.id) ?? findOriginal(params.id);
if (!source) return error(res, 404, 'Nothing to denoise');
const job = startDenoise({ photoId: params.id, sourcePath: source });
const body = await readJson(req).catch(() => ({}));
const base = body?.base === 'nlm' || body?.base === 'scunet' ? body.base : 'guided';
const job = startDenoise({ photoId: params.id, sourcePath: source, base });
return json(res, 202, { jobId: job.id, state: job.state });
});
@@ -2496,6 +2500,12 @@ route('GET', '/api/denoise/jobs/:id', async ({ req, res, params }) => {
error: job.error ?? null,
url: job.url ?? null,
stats: job.stats ?? null,
// Where a long run is, so the panel can name the stage instead of showing a
// spinner with no truth in it.
progress: job.progress ?? null,
// Without this the panel cannot tell a reused render from a fresh one and
// reports "Denoise ready" for both.
cached: Boolean(job.cached),
});
});
+10 -5
View File
@@ -199,16 +199,21 @@ export function findDenoised(id, key) {
return path.join(dir, names[0]);
}
/** Remove every denoised render for a photo, sparing `keepKey` if given. */
export function removeDenoised(id, keepKey) {
/**
* Remove denoised renders for a photo, sparing the keys named in `keepKeys`.
* A single key is accepted too; with none, every render for the photo goes.
*/
export function removeDenoised(id, keepKeys) {
const safe = lookupId(id);
if (!safe) return 0;
const dir = path.join(storageRoot(), 'denoised');
const key = keepKey ? String(keepKey).replace(/[^a-z0-9]/gi, '') : null;
const keep = key ? `${safe}.${key}.jpg` : null;
const keys = (Array.isArray(keepKeys) ? keepKeys : keepKeys ? [keepKeys] : [])
.map((key) => String(key).replace(/[^a-z0-9]/gi, ''))
.filter(Boolean);
const keep = new Set(keys.map((key) => `${safe}.${key}.jpg`));
let removed = 0;
for (const name of listFiles(dir)) {
if (!name.startsWith(`${safe}.`) || name === keep) continue;
if (!name.startsWith(`${safe}.`) || keep.has(name)) continue;
fs.rmSync(path.join(dir, name), { force: true });
removed += 1;
}