/** * Scalar float planes plus the resampling and box-filter primitives the * detail-preserving denoise is built from. * * Everything here is plain `Float32Array` arithmetic with no allocation in the * hot loops: the full-resolution stage runs at proxy size (up to 24 MP), and * allocation churn is the difference between two seconds and six per photo. */ export interface Plane { data: Float32Array; width: number; height: number; } export function createPlane(width: number, height: number): Plane { return { data: new Float32Array(width * height), width, height }; } export function clamp01(v: number): number { return v < 0 ? 0 : v > 1 ? 1 : v; } export function clamp(v: number, lo: number, hi: number): number { return v < lo ? lo : v > hi ? hi : v; } /** Hermite ramp: 0 below `lo`, 1 above `hi`. */ export function smoothstep(lo: number, hi: number, x: number): number { if (hi <= lo) return x >= hi ? 1 : 0; const t = clamp01((x - lo) / (hi - lo)); return t * t * (3 - 2 * t); } function edge(i: number, n: number): number { return i < 0 ? 0 : i >= n ? n - 1 : i; } /** * Scratch buffer for the separable passes, grown on demand. * * Safe because `boxBlur` is not reentrant: every caller finishes with the * buffer before making another call, and the buffer is never handed out. */ let scratchBuffer: Float32Array | null = null; function scratch(length: number): Float32Array { if (!scratchBuffer || scratchBuffer.length < length) scratchBuffer = new Float32Array(length); return scratchBuffer.subarray(0, length); } /** * Separable box blur with clamped edges, O(1) per pixel. * * `out` may alias `src`: the horizontal pass goes through the shared scratch * buffer, and only the vertical pass writes `out`, so an in-place call is * safe. That aliasing is what keeps the guided filter allocation-light. */ export function boxBlur( src: Float32Array, width: number, height: number, radius: number, out?: Float32Array, ): Float32Array { const dst = out ?? new Float32Array(src.length); if (src.length < width * height) { throw new Error(`plane is ${src.length} values, expected ${width * height}`); } if (radius <= 0) { if (dst !== src) dst.set(src); return dst; } const tmp = scratch(width * height); const norm = 1 / (2 * radius + 1); // Horizontal pass: src -> tmp. for (let y = 0; y < height; y++) { const row = y * width; let sum = 0; for (let x = -radius; x <= radius; x++) sum += src[row + edge(x, width)]; for (let x = 0; x < width; x++) { tmp[row + x] = sum * norm; sum += src[row + edge(x + radius + 1, width)] - src[row + edge(x - radius, width)]; } } // Vertical pass: tmp -> dst. for (let x = 0; x < width; x++) { let sum = 0; for (let y = -radius; y <= radius; y++) sum += tmp[edge(y, height) * width + x]; for (let y = 0; y < height; y++) { dst[y * width + x] = sum * norm; sum += tmp[edge(y + radius + 1, height) * width + x] - tmp[edge(y - radius, height) * width + x]; } } return dst; } /** * Bilinear resample. Used for the two-scale split: luma is reduced to the * inference size, denoised, then brought back up so full-resolution detail can * be re-injected on top. */ export function resample( src: Float32Array, sw: number, sh: number, dw: number, dh: number, ): Float32Array { if (sw === dw && sh === dh) return src.slice(); const out = new Float32Array(dw * dh); const xRatio = sw / dw; const yRatio = sh / dh; for (let y = 0; y < dh; y++) { // Sample at pixel centres so a downscale is a centred box, not a shifted one. const sy = clamp((y + 0.5) * yRatio - 0.5, 0, sh - 1); const y0 = Math.floor(sy); const y1 = Math.min(y0 + 1, sh - 1); const wy = sy - y0; for (let x = 0; x < dw; x++) { const sx = clamp((x + 0.5) * xRatio - 0.5, 0, sw - 1); const x0 = Math.floor(sx); const x1 = Math.min(x0 + 1, sw - 1); const wx = sx - x0; const top = src[y0 * sw + x0] * (1 - wx) + src[y0 * sw + x1] * wx; const bot = src[y1 * sw + x0] * (1 - wx) + src[y1 * sw + x1] * wx; out[y * dw + x] = top * (1 - wy) + bot * wy; } } return out; } /** * O(n) percentile for large non-negative arrays, by histogram. * * `quantile` sorts, which is correct and fine for a 256-value block but ruinous * for an 18 MP plane: two sorts there cost 11.5 s against a 6.6 s denoise. Bins * over [0, max] return a median accurate to ~0.2 on 8-bit data, far inside the * noise being measured. * * `values` must be non-negative (magnitudes, gradients, residuals). */ export function fastPercentile(values: Float32Array, q: number, bins = 1024): number { const n = values.length; if (n === 0) return 0; let max = 0; for (let i = 0; i < n; i++) { const v = values[i]; if (v > max) max = v; } if (!(max > 0)) return 0; const hist = new Uint32Array(bins); const scale = (bins - 1) / max; for (let i = 0; i < n; i++) hist[(values[i] * scale) | 0]++; const target = clamp(q, 0, 1) * (n - 1); let seen = 0; for (let b = 0; b < bins; b++) { seen += hist[b]; if (seen > target) return b / scale; } return max; } /** Linear-interpolated quantile of a copy of `values`. `q` is 0..1. */ export function quantile(values: Float32Array | number[], q: number): number { const n = values.length; if (n === 0) return 0; const sorted = Float32Array.from(values as ArrayLike).sort(); const pos = clamp(q, 0, 1) * (n - 1); const lo = Math.floor(pos); const hi = Math.min(lo + 1, n - 1); return sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo); }