/** * The RGB proxy denoise pipeline: two scales, one gate. * * proxy -> YCbCr * -> base: downscale RGB, run `runBase`, upscale * -> luma: low-pass at the detail scale, gate per pixel * -> reconstruct: crossfade luma to the base where the gate is closed, * and take chroma from the base outright * * `runBase` is the only thing that knows how to denoise. Today it is a guided * filter or NLM; when the ONNX session lands it is a tiled model runner and * nothing else in this file changes. That is the seam the build plan is built * around, and it is RGB so a colour-trained model is fed what it expects. * * The reconstruction invariant: output luma is a per-pixel crossfade between * the untouched input (gate 1) and the denoised base (gate 0). It is bounded by * its two inputs, so it cannot ring or overshoot, and where the gate opens the * pixels are identical to the original. */ import { fromYcc, toYcc, type RgbImage } from './color.ts'; import { DEFAULT_GATE, detailGate, structureMap, type GateOptions, } from './detail.ts'; import { estimateNoise, type NoiseModel } from './noise.ts'; import { boxBlur, clamp01, clamp, resample, smoothstep } from './planes.ts'; import type { BaseDenoiser, BaseImage } from './standin.ts'; export type DenoiserName = 'guided' | 'nlm' | 'onnx'; export interface DenoiseOptions { /** 0..1 blend against the input, applied after reconstruction. */ amount: number; /** * Long edge of the plane the base denoiser runs on. * * Raising this on extreme-ISO frames looks like a free win on a detail metric * (+0.07 retention at 3200 on 18 MP ISO 6400) but was rejected: the corpus * guard measured grain 0.52 -> 1.30 and chroma 0.50 -> 1.20 at 3200. A sharper * base is not more detail, it is grain the crossfade then has to keep. */ baseEdge: number; /** Scale below which content is treated as detail worth protecting. */ detailRadius: number; /** * Radius of the second, coarser detail band. 0 disables it. * * The fine band (radius 2) is what the original gate judged, and it leaves * near-isotropic 3-8 px texture unread: the texture that survives is the * part that happens to be coherent at 2 px. The coarse band is the difference * of two low-passes, so it sees that scale while rejecting both gradients and * pixel-scale grain -- measured in docs/PLAN.md. */ coarseRadius: number; /** Coarse-band thresholds, in fine-band noise units. */ coarseLo: number; coarseHi: number; /** * Below this measured global grain the frame is clean and the pipeline tapers * itself to an identity. Without it a base-ISO file loses real micro-texture * to a denoise it never needed: measured at 36% of high-frequency energy on a * clean ISO 100 D700 frame. */ cleanSigma: number; gate: GateOptions; } export const DEFAULT_OPTIONS: DenoiseOptions = { amount: 1, baseEdge: 1600, detailRadius: 2, coarseRadius: 6, coarseLo: 1.2, coarseHi: 2.0, cleanSigma: 2.5, gate: DEFAULT_GATE, }; export interface StageTimings { noise: number; base: number; detail: number; coarse: number; structure: number; reconstruct: number; total: number; } export interface DenoiseStats { width: number; height: number; baseWidth: number; baseHeight: number; /** How much the base plane was reduced, e.g. 3.25 for a 6000px proxy. */ backscale: number; amount: number; noise: { a: number; b: number; trend: 'fit' | 'flat'; global: number; atMid: number }; /** Mean gate value: the share of the frame given back as structure. */ gateCoverage: number; /** How much of the requested amount survived the clean-image taper (0..1). */ autoGate: number; timings: StageTimings; } export interface DenoiseOutput { rgb: Uint8Array; /** Luma of the denoised base, before detail re-injection, for inspection. */ base: { data: Float32Array; width: number; height: number }; stats: DenoiseStats; } const now = () => performance.now(); /** * Prefiltered decimation of interleaved RGB to the base plane. * * The prefilter is load-bearing, and the coarse gate is what exposed it. A bare * bilinear tap reads four of every ~42 source pixels at `backscale` 3.25, so * pixel-scale grain is aliased into the base and comes back wherever the gate * is closed. Measured on the three mid-ISO frames at sigma 6, with the coarse * band on: grain 0.32/0.20/0.35 with bilinear against 0.22/0.20/0.22 with the * box prefilter, for 1.9% less high-frequency energy. The gate protects detail * and cannot protect grain out of an aliased base, so this belongs in the * decimator rather than in a threshold. * * One channel at a time through the tested `resample`, so the peak extra memory * is a single full-resolution plane, not three. */ function resampleRgb( image: RgbImage, width: number, height: number, prefilterRadius: number, ): BaseImage { const out = new Float32Array(width * height * 3); const src = new Float32Array(image.width * image.height); for (let k = 0; k < 3; k++) { for (let i = 0, p = k; i < src.length; i++, p += 3) src[i] = image.rgb[p]; if (prefilterRadius > 0) boxBlur(src, image.width, image.height, prefilterRadius, src); const small = resample(src, image.width, image.height, width, height); for (let i = 0, p = k; i < small.length; i++, p += 3) out[p] = small[i]; } return { rgb: out, width, height }; } /** * Bilinear upscale of the base to full resolution, quantised to 8 bits so the * tested `toYcc` can be reused rather than duplicating the colour maths here. */ function upsampleBase(base: BaseImage, width: number, height: number): RgbImage { const rgb = new Uint8Array(width * height * 3); const xRatio = base.width / width; const yRatio = base.height / height; for (let y = 0; y < height; y++) { const sy = clamp((y + 0.5) * yRatio - 0.5, 0, base.height - 1); const y0 = Math.floor(sy); const y1 = Math.min(y0 + 1, base.height - 1); const wy = sy - y0; for (let x = 0; x < width; x++) { const sx = clamp((x + 0.5) * xRatio - 0.5, 0, base.width - 1); const x0 = Math.floor(sx); const x1 = Math.min(x0 + 1, base.width - 1); const wx = sx - x0; const a = (y0 * base.width + x0) * 3; const b = (y0 * base.width + x1) * 3; const c = (y1 * base.width + x0) * 3; const d = (y1 * base.width + x1) * 3; const o = (y * width + x) * 3; for (let k = 0; k < 3; k++) { const top = base.rgb[a + k] * (1 - wx) + base.rgb[b + k] * wx; const bot = base.rgb[c + k] * (1 - wx) + base.rgb[d + k] * wx; const v = top * (1 - wy) + bot * wy; rgb[o + k] = v < 0 ? 0 : v > 255 ? 255 : v + 0.5; } } } return { rgb, width, height }; } export async function denoiseRgb( image: RgbImage, options: Partial, runBase: BaseDenoiser, ): Promise { const opts: DenoiseOptions = { ...DEFAULT_OPTIONS, ...options, gate: { ...DEFAULT_GATE, ...options.gate } }; const started = now(); const { width, height } = image; const pixels = width * height; const { y, cb, cr } = toYcc(image); let mark = now(); const noise: NoiseModel = estimateNoise(y, width, height); const timings: StageTimings = { noise: now() - mark, base: 0, detail: 0, coarse: 0, structure: 0, reconstruct: 0, total: 0, }; // --- base: the inference scale ------------------------------------------- const longEdge = Math.max(width, height); const scale = opts.baseEdge > 0 ? Math.min(1, opts.baseEdge / longEdge) : 1; const baseWidth = Math.max(8, Math.round(width * scale)); const baseHeight = Math.max(8, Math.round(height * scale)); const backscale = width / baseWidth; mark = now(); const prefilterRadius = backscale > 1.001 ? Math.max(0, Math.round((backscale - 1) / 2)) : 0; const baseInput = resampleRgb(image, baseWidth, baseHeight, prefilterRadius); // What the base denoiser is told about the noise it will see. // // The decimator is box(W) followed by the two bilinear taps. Along one axis // the taps overlap in W-1 samples at weight 1/W each and contribute // (1-t)^2 + t^2 at the two ends, which averages 2/3 over t, so the per-axis // *variance* gain is (W - 1/3) / W^2. Both axes are equal, so the standard // deviation falls by the same factor squared, i.e. by that number again: // 0.296 at W=3 against 1/backscale = 0.373. // // The old `/ backscale` was a guess -- and with bare bilinear (W=1) the true // figure is 2/3, which is why it read ~2x low. The classical stand-ins never // noticed (`planeSigma` re-measures each plane), but a model consumes this as // a prior, so it has to describe the filter that actually ran. const prefilterWidth = 2 * prefilterRadius + 1; const decimatedSigma = backscale > 1.001 ? (prefilterWidth - 1 / 3) / (prefilterWidth * prefilterWidth) : 1; const baseSigma = noise.sigmaAt(110) * decimatedSigma; const baseOut = await runBase(baseInput, baseSigma); const baseUp = toYcc(upsampleBase(baseOut, width, height)); timings.base = now() - mark; // --- detail gate at full resolution -------------------------------------- // // The split filter is a plain low-pass, deliberately, and not an // edge-preserving one. An edge-aware filter follows strong edges, which // leaves them in the low band; the base cannot represent them after the // downscale, and nothing would put them back -- measured as 41% of edge // contrast lost. A low-pass pushes edges into `detail`, where the gate sees // them as signal. mark = now(); const smooth = boxBlur(y, width, height, opts.detailRadius); const detail = new Float32Array(pixels); for (let i = 0; i < pixels; i++) detail[i] = y[i] - smooth[i]; timings.detail = now() - mark; mark = now(); // The tensor is measured on the *original* luma, not on `smooth`. // // `smooth` is the same 5x5 low-pass that defines the detail band, so 2-3 px // texture has already been attenuated by the time the tensor sees it: the // gate was judging fine texture with a measurement that could not see it, and // coverage on a texture-rich frame came out *lower* than on a smooth one // (3.8% vs 9.3%). `structureMap` resamples to half resolution first, which // halves the noise while leaving 2 px structure intact, so this reads the // scale it is being asked about. const structure = structureMap(y, width, height, 2, 2, noise.global); const coherence = resample(structure.data, structure.width, structure.height, width, height); const sigmaMap = new Float32Array(pixels); for (let i = 0; i < pixels; i++) sigmaMap[i] = noise.sigmaAt(smooth[i]); timings.structure = now() - mark; mark = now(); let gate = detailGate(detail, width, height, sigmaMap, coherence, opts.gate); // Second, coarser band: `smooth2 - smooth6` is a band-pass around 3-8 px. It // rejects gradients (both low-passes follow them) and pixel-scale grain (both // average it), so it can open on texture that the fine band reads as noise // without opening on flat noisy sky. The isolated-point path is a fine-band // instrument and is deliberately disabled here. if (opts.coarseRadius > opts.detailRadius && opts.coarseHi > opts.coarseLo) { const coarseSmooth = boxBlur(y, width, height, opts.coarseRadius); const coarse = new Float32Array(pixels); for (let i = 0; i < pixels; i++) coarse[i] = smooth[i] - coarseSmooth[i]; const coarseGate = detailGate(coarse, width, height, sigmaMap, coherence, { ...opts.gate, lo: opts.coarseLo, hi: opts.coarseHi, pointHi: 0, }); for (let i = 0; i < pixels; i++) if (coarseGate[i] > gate[i]) gate[i] = coarseGate[i]; timings.coarse = now() - mark; } // Clean frames get their amount tapered to nothing: 0.8 sigma of measured // grain is quantisation, 2.5 is a genuinely noisy file. const autoGate = opts.cleanSigma > 0 ? smoothstep(0.8, opts.cleanSigma, noise.global) : 1; const amount = clamp01(opts.amount) * autoGate; const outY = new Float32Array(pixels); const outCb = new Float32Array(pixels); const outCr = new Float32Array(pixels); let gateSum = 0; for (let i = 0; i < pixels; i++) { gateSum += gate[i]; // Crossfade, never additive re-injection: additive detail lands on top of a // base that already contains a softened copy of the same edge and overshoots // by ~40%. A crossfade is bounded by its two inputs, so it cannot ring, and // where the gate opens the pixels are bit-identical to the original. outY[i] = y[i] + amount * (1 - gate[i]) * (baseUp.y[i] - y[i]); // Chroma follows the same gate, for a different reason than luma does. The // base carries chroma upsampled from `backscale` times smaller, so replacing // it outright smears colour across every sharp edge: on a small aircraft // against bright sky that is a magenta fringe along the wing and red/white // paint that loses its boundary. Keeping the original chroma where the gate // says "structure" keeps the paint edge registered with the luma edge it // belongs to. Flat areas still take the base chroma, which is where the // chroma noise lives. outCb[i] = cb[i] + amount * (1 - gate[i]) * (baseUp.cb[i] - cb[i]); outCr[i] = cr[i] + amount * (1 - gate[i]) * (baseUp.cr[i] - cr[i]); } const rgb = fromYcc({ y: outY, cb: outCb, cr: outCr }, width, height); timings.reconstruct = now() - mark; timings.total = now() - started; const baseLuma = new Float32Array(baseWidth * baseHeight); for (let i = 0, p = 0; i < baseLuma.length; i++, p += 3) { baseLuma[i] = 0.299 * baseOut.rgb[p] + 0.587 * baseOut.rgb[p + 1] + 0.114 * baseOut.rgb[p + 2]; } return { rgb, base: { data: baseLuma, width: baseWidth, height: baseHeight }, stats: { width, height, baseWidth, baseHeight, backscale, amount, noise: { a: noise.a, b: noise.b, trend: noise.trend, global: noise.global, atMid: noise.sigmaAt(110), }, gateCoverage: gateSum / pixels, autoGate, timings, }, }; }