/** * Interleaved RGB <-> luma/chroma, so luma and chroma can take different * denoise paths. * * Chroma noise is low-frequency and the eye has little chroma acuity, so it is * worth smoothing hard; luma carries all the detail and is the expensive, * gated path. The transform is the standard sRGB-weighted one and round-trips * to within rounding. */ export interface RgbImage { /** Interleaved 8-bit RGB, `width * height * 3` bytes. */ rgb: Uint8Array; width: number; height: number; } export interface YccPlanes { y: Float32Array; cb: Float32Array; cr: Float32Array; } export function toYcc(image: RgbImage): YccPlanes { const { rgb, width, height } = image; const n = width * height; const y = new Float32Array(n); const cb = new Float32Array(n); const cr = new Float32Array(n); for (let i = 0, p = 0; i < n; i++, p += 3) { const r = rgb[p]; const g = rgb[p + 1]; const b = rgb[p + 2]; y[i] = 0.299 * r + 0.587 * g + 0.114 * b; cb[i] = 128 - 0.168736 * r - 0.331264 * g + 0.5 * b; cr[i] = 128 + 0.5 * r - 0.418688 * g - 0.081312 * b; } return { y, cb, cr }; } export function fromYcc(planes: YccPlanes, width: number, height: number): Uint8Array { const n = width * height; const out = new Uint8Array(n * 3); for (let i = 0, p = 0; i < n; i++, p += 3) { const y = planes.y[i]; const cb = planes.cb[i] - 128; const cr = planes.cr[i] - 128; const r = y + 1.402 * cr; const g = y - 0.344136 * cb - 0.714136 * cr; const b = y + 1.772 * cb; out[p] = r < 0 ? 0 : r > 255 ? 255 : r + 0.5; out[p + 1] = g < 0 ? 0 : g > 255 ? 255 : g + 0.5; out[p + 2] = b < 0 ? 0 : b > 255 ? 255 : b + 0.5; } return out; }