cd52a2f82f
Browser-based photo catalog with an optional team server (SQLite + LibRaw). Local database, uploaded photos, build output and dependencies are gitignored. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
317 lines
14 KiB
Markdown
317 lines
14 KiB
Markdown
# AI denoise — feasibility review and raw-decoder prototype
|
||
|
||
**Status:** review + prototype only. No application code was changed.
|
||
**Date:** 2026-11-22
|
||
**Scope:** could Luminary get a Lightroom-class AI denoise, and what stands in the way?
|
||
**Revisit when:** high-ISO raw material is available (see
|
||
[§8](#8-the-test-material-gap)).
|
||
|
||
---
|
||
|
||
## 1. What the app actually is
|
||
|
||
This matters because an earlier design assumed an Electron desktop app. It is not.
|
||
|
||
- **Front end:** React 18 + Vite, WebGL2. All editing happens in the browser on a
|
||
demosaiced proxy. `Edits` JSON (`src/types.ts`) is the non-destructive document.
|
||
- **Server:** plain `node:http` (`server/index.mjs`, ~1,310 lines, hand-rolled
|
||
router at `:284`), cookie sessions, SQLite catalog, deployed as
|
||
`node:24-bookworm-slim` in Docker as an unprivileged user.
|
||
- **Raw path:** `libraw-wasm` in a `worker_threads` pool (`server/libraw-pool.mjs`),
|
||
`open()` + `imageData()` → 8-bit sRGB JPEG proxy at `RAW_PREVIEW_EDGE = 6000`
|
||
long edge (`server/config.mjs:14`, `RAW_PREVIEW_EDGE`). `sharp` for JPEG ingest,
|
||
`lensfun-wasm` for lens correction.
|
||
- **Renderer:** `src/gl/renderer.ts`. `setImage()` uploads one `u_src` texture
|
||
(`:1144`), grade pass samples it at `:1296`, finish pass at `:1553`.
|
||
- **Export:** `src/lib/export.ts` builds a fresh `Renderer` from `getBitmap()` — a
|
||
second place any new image stage must be wired, or exports silently omit it.
|
||
|
||
### What exists today under the name "noise reduction"
|
||
|
||
`Edits.noise = { luminance, detail, chroma, chromaDetail }` (`src/types.ts:164`),
|
||
UI in `DetailPanel` (`src/components/Panels.tsx:495`), defaults seeded from
|
||
`autoNoiseFor()` (`src/lib/noiseProfile.ts`) — an ISO→slider heuristic, not a
|
||
physical noise model.
|
||
|
||
The shaders are classical and coarse:
|
||
|
||
- Luminance (`renderer.ts:517`): `mix(c, mix(bs, bb, 0.5), nr * 0.6)` — a two-tap
|
||
blur blend.
|
||
- Chroma (`:545`): a 17-tap circular average on the chroma axes.
|
||
|
||
So AI denoise is not a marginal improvement here; it is a different category. Keep
|
||
the classical path as the instant/non-AI option rather than replacing it.
|
||
|
||
`noiseProfile.ts` gives the UI a starting point but is **not** a Poisson–Gaussian
|
||
model — a denoiser needs real per-camera `k`/`σ²` (see [§7](#7-what-is-still-unknown)).
|
||
|
||
---
|
||
|
||
## 2. Verdict
|
||
|
||
**Moderate-to-hard, and the difficulty is not where it looks.**
|
||
|
||
The integration seams are good: the server already owns the raw file, already has a
|
||
worker pool, and the renderer takes a texture cleanly. A two-week path to a working
|
||
raw-domain pipeline exists. The real risks are three:
|
||
|
||
1. **No trained model.** Independent track, measured in weeks. Nothing in this repo
|
||
or the earlier prototype has weights; `onnxruntime-node` has never actually run a
|
||
model end to end here.
|
||
2. **There is no mosaic→RGB path back.** LibRaw demosaics internally, so denoising
|
||
the mosaic means re-deriving RGB yourself. This is where colour drift appears.
|
||
3. **No GPU.** `onnxruntime-node` ships CPU + DirectML only; DML is Windows-only and
|
||
the server is a Linux container. Plan for the dual-Xeon CPU, ~30–90 s/frame.
|
||
|
||
Also: the editable proxy is an **8-bit JPEG at ≤6000 px**, so any denoise performed
|
||
*after* it is materially worse than Lightroom, which denoises the mosaic.
|
||
|
||
### Effort at a glance
|
||
|
||
| Piece | Size | Notes |
|
||
|---|---|---|
|
||
| Mosaic helper in `server/raw.mjs` | ½ d | ~180 ms/frame, leaves `demosaic()` untouched |
|
||
| Black-level + orientation calibration | 2–4 d | see §5, §6 — real work, not a one-liner |
|
||
| Denoise endpoint + asset cache | 1–2 d | `data/denoised/<id>.jpg`, keyed by raw hash + model version + params |
|
||
| Job progress channel | 1–2 d | **nothing exists**; every route is request/response |
|
||
| Raw-domain denoise (DNG round-trip) | 3–6 d | mosaic → VST → tiled ONNX → DNG → LibRaw → proxy |
|
||
| Renderer: second texture + `mix()` | ½ d | `u_den` + amount uniform at `renderer.ts:512` |
|
||
| Edit model, panel, history, presets | 1–2 d | `Edits.aiDenoise`, `normalizeEdits`, `DetailPanel` |
|
||
| Export path | ½ d | easy to forget → denoise missing from exports |
|
||
| **Model (train/obtain)** | **weeks** | independent; the long pole |
|
||
|
||
**≈1.5–2 weeks of plumbing**, excluding the model.
|
||
|
||
---
|
||
|
||
## 3. Three placement options
|
||
|
||
**A. Server-side, raw mosaic domain (the goal).** Best quality; matches what
|
||
Lightroom does. Requires a demosaic path (B or C below).
|
||
|
||
**B. DNG round-trip — recommended.** Write the denoised mosaic as a minimal DNG
|
||
(CFA pattern, black/white, `AsShotNeutral`, colour matrix) and hand it back to
|
||
`libraw-wasm.open()`. LibRaw then does its normal demosaic and colour handling, so
|
||
the denoised proxy matches the current proxy's tone exactly. `src/lib/tiff.ts`
|
||
already contains 16-bit TIFF writing.
|
||
|
||
**C. Own demosaic.** Malvar-He-Cutler is ~150 lines and removes the second decode,
|
||
but colour will not match LibRaw's output — visible as a shift when the Amount
|
||
slider sits mid-range, since the two textures are blended.
|
||
|
||
**D. Proxy domain (cheap, not the goal).** Denoise the 8-bit JPEG the client already
|
||
has. Fast to build, quality ceiling well below Lightroom.
|
||
|
||
---
|
||
|
||
## 4. Raw decoder prototype — what was verified
|
||
|
||
Run against the 37 sample raws in `server/data/originals/` (36 × Nikon D700 NEF,
|
||
1 × Canon 20D CR2) through the repo's own loader, so the worker shim and wasm module
|
||
resolve exactly as they do in production. Scripts were throwaway (`/tmp`), none of
|
||
this is committed.
|
||
|
||
### The mosaic path works
|
||
|
||
| | Nikon D700 | Canon 20D |
|
||
|---|---|---|
|
||
| mosaic frame | 4288 × 2844 | 3596 × 2348 |
|
||
| visible frame | 4284 × 2844 | 3522 × 2348 |
|
||
| margins (top, left) | 0, 2 | 12, 74 |
|
||
| `data.length` | 12,195,072 = `rawW × rawH` | 8,443,408 = `rawW × rawH` |
|
||
| element type | `Uint16Array` | `Uint16Array` |
|
||
| `color_data.maximum` | 16383 (14-bit) | 4095 (12-bit) |
|
||
| `meta.filters` | `0xB4B4B4B4` → RGGB | `0xB4B4B4B4` → RGGB |
|
||
| `meta.cdesc` / `meta.colors` | `RGBG` / 3 | `RGBG` / 3 |
|
||
| `color_data.cam_mul` | e.g. 436/256/355 | 1806/1015/1673 |
|
||
|
||
`data.length === raw_width * raw_height` in every file, so the buffer spans the
|
||
whole sensor and cropping to visible is exactly
|
||
`(top_margin, left_margin, width, height)` — no stride surprises.
|
||
|
||
Cost, measured on this machine:
|
||
|
||
| operation | D700 | 20D |
|
||
|---|---|---|
|
||
| `open()` | ~140 ms | — |
|
||
| `rawImageData()` | **32–38 ms** | ~30 ms |
|
||
| `imageData()` (current demosaic) | **~1,965 ms** | ~1,604 ms |
|
||
|
||
Mosaic access is ~60× cheaper than demosaicing. Memory: 24.4 MB per D700 frame as
|
||
`Uint16Array`.
|
||
|
||
### CFA decode
|
||
|
||
`meta.filters` is a dcraw bitmask: 8 rows × 2 columns of 2-bit colour codes.
|
||
|
||
```js
|
||
const FC = (filters, row, col) =>
|
||
(filters >> ((((row << 1) & 14) + (col & 1)) << 1)) & 3;
|
||
```
|
||
|
||
`0xB4B4B4B4` decodes to standard RGGB on both bodies:
|
||
|
||
```
|
||
R G R G R G R G
|
||
G B G B G B G B
|
||
...
|
||
```
|
||
|
||
---
|
||
|
||
## 5. Correction: the black level is not exposed and must be derived
|
||
|
||
`color_data.black` is **0** for both cameras, and `color_data.dng_levels.dng_black`
|
||
is 0 too. For the Canon that is false.
|
||
|
||
| | D700 | 20D |
|
||
|---|---|---|
|
||
| `color_data.black` | 0 | 0 |
|
||
| darkest 0.2 % quads, per CFA channel | 21.7 / 28.8 / 29.3 / 17.4 | **146.1 / 165.6 / 165.8 / 151.6** |
|
||
| darkest-quad sd | 6.4–6.5 | 3.2–4.5 |
|
||
| masked-border median | 770 | **128** |
|
||
|
||
The 20D carries an unsubtracted pedestal of ~128 DN with a **per-channel spread**
|
||
(R and B 15–20 DN above the greens) — the signature of Canon per-channel black that
|
||
dcraw keeps in `cblack`, which this libraw-wasm build does not surface. Feeding that
|
||
into an Anscombe VST without subtracting it biases the variance estimate and leaves
|
||
a DC lift.
|
||
|
||
The border is **not** a safe universal fallback: on the D700 the two "margin" columns
|
||
read 770 DN, brighter than the darkest visible pixels (p0 = 8.75), so they are
|
||
uncalibrated active pixels rather than masked ones.
|
||
|
||
**Working rule:** use the masked-border median only when
|
||
`borderMedian < visibleP01`; otherwise fall back to a per-camera constant, else 0.
|
||
This needs to be validated per body — it is calibration work, not a one-liner.
|
||
|
||
---
|
||
|
||
## 6. Correction: the mosaic is never flipped, the proxy always is
|
||
|
||
`rawImageData()` returns sensor orientation regardless of EXIF. `metadata()` reports
|
||
visible dims already swapped for rotated frames, and `imageData()` returns the
|
||
rotated frame (`userFlip: -1` in `DECODE_SETTINGS`, `server/raw.mjs:59`).
|
||
|
||
Correlating a 2×2-quad downsample of the mosaic against demosaiced luma:
|
||
|
||
| file | `flip` | matching orientation | r |
|
||
|---|---|---|---|
|
||
| `p_mwpnuqw4_de2ag7dq.nef` | 0 | none | 0.9437 |
|
||
| `p_mwpnuoyg_24j6va1c.nef` | 5 | **90° CCW** | 0.9512 |
|
||
| `p_mwpnv4gt_tffz1ydw.cr2` | 0 | none | 0.9592 |
|
||
|
||
r < 1 is expected: the mosaic quad mean is pre-white-balance, the demosaiced luma is
|
||
post-`cam_mul`.
|
||
|
||
**Consequence:** a denoised proxy written straight from the mosaic comes back
|
||
**sideways on every portrait frame**. Orientation is a pipeline step, not a detail.
|
||
`flip: 6` and `flip: 3` are still untested — no samples in the catalog.
|
||
|
||
---
|
||
|
||
## 7. What is still unknown
|
||
|
||
- **`flip` 6 / 3 / 8 mapping** — only `flip: 5` and `0` appear in the samples.
|
||
- **Per-camera black constants** — only D700 and 20D measured. Every body in real use
|
||
needs its own (empirical pedestal, per-channel offsets).
|
||
- **Whether a DNG round-trip preserves tone exactly** — the central assumption of
|
||
option B, untested.
|
||
- **Real Poisson–Gaussian `k`/`σ²`** — not derivable from ISO alone; needs
|
||
flat-field frames per body per ISO.
|
||
- **Denoise timings** — no model has ever run on this machine
|
||
(`onnxruntime-node` native binary could not be downloaded here).
|
||
- **Behaviour on bridged photos** — bridge-imported items may have no local original
|
||
(`server/storage.mjs:findOriginal`); denoise must fetch upstream or grey out.
|
||
- **Virtual copies** — `copyOf` shares the master's bytes; cache must key on the
|
||
master's raw hash, not the photo id.
|
||
|
||
---
|
||
|
||
## 8. The test material gap
|
||
|
||
**All 37 samples are ISO 100** (D700: 1/60 s, f/5.6, 44 mm). Nothing in this
|
||
catalogue exercises the range where denoise matters, so no denoise work can be
|
||
validated against it.
|
||
|
||
To revisit this properly, collect:
|
||
|
||
1. **A high-ISO ladder on one body** — e.g. 1600 / 3200 / 6400 / 12800 / 25600 of the
|
||
same static scene, tripod, dim tungsten light, some deep shadows.
|
||
2. **Flat field / lens-cap frames per ISO** — to derive per-channel black and the
|
||
noise model instead of guessing.
|
||
3. **A portrait-orientation frame** per body — to confirm the `flip: 6` mapping.
|
||
4. **At least one second vendor** — the catalogue is effectively Nikon-only; the
|
||
Canon black-level behaviour above shows vendor assumptions break fast.
|
||
5. **A reference render** — the same frame pushed through Lightroom AI Denoise at a
|
||
known strength, to have an objective target rather than an impression.
|
||
|
||
Synthetic noise added to the existing ISO 100 mosaics is fine for pipeline and
|
||
plumbing tests (tiling seams, orientation, cache keys) but cannot validate a model.
|
||
|
||
---
|
||
|
||
## 9. What carries over from the earlier reference implementation
|
||
|
||
Written previously in a different project directory for the (incorrect) Electron
|
||
assumption:
|
||
|
||
| file | status |
|
||
|---|---|
|
||
| `src/denoise/math.ts` — VST, Bayer packing, tiling, `blendMosaics` | **reuse** |
|
||
| `src/denoise/pipeline.ts` — tile runner with injected backend | **reuse** |
|
||
| `src/denoise/engine.ts` — ONNX Runtime adapter | **reuse** |
|
||
| `src/denoise/types.ts` — `RawMosaic` | reuse, but **extend** (see §1, §5) |
|
||
| `src/denoise/worker.ts` — `utilityProcess` | **discard** (Node worker_threads instead) |
|
||
| `src/main/*`, `src/preload/*` | **discard** (no Electron) |
|
||
| `src/renderer/denoise-notice.ts` | rewrite as a React component on `Panel`/`Slider` |
|
||
| tests (`node:test`, 19/19 passing) | port to **vitest** (`npm test` = `vitest run`) |
|
||
|
||
Key algorithmic finding to keep: the affine noise model `u/k + σ²/k²` is wrong in
|
||
0–1 normalised units (measured 664× noise amplification). The generalised Anscombe
|
||
VST is unit-agnostic — keep that.
|
||
|
||
---
|
||
|
||
## 10. Recommended next steps
|
||
|
||
1. **DNG round-trip spike** — take one sample's mosaic, write a minimal DNG, reopen it
|
||
in `libraw-wasm`, and diff the RGB against the current demosaic output. This
|
||
decides option B vs C and is the single highest-value unknown.
|
||
2. **Black-level calibration** — per-body, per-channel, with the border heuristic in
|
||
§5 validated across vendors.
|
||
3. **Server plan** — mosaic helper, orientation step, endpoint, job channel, cache
|
||
keying, export wiring, and worker-pool limits (`RAW_WORKERS` defaults to
|
||
`min(4, cores-1)`; a 14-thread denoise beside it will starve `/api/health`).
|
||
4. **Source the high-ISO material** in §8 before any model work.
|
||
|
||
---
|
||
|
||
## 11. Reproducing the probe
|
||
|
||
The throwaway scripts lived in `/tmp` (`rawprobe.mjs`, `rawmeta.mjs`, `rawalign.mjs`,
|
||
`raworient.mjs`). To rebuild, import the repo's own loader so the runtime shim is
|
||
installed and the wasm resolves:
|
||
|
||
```js
|
||
import { loadLibRaw } from '<repo>/server/libraw-pool.mjs';
|
||
|
||
const Ctor = await loadLibRaw();
|
||
const lib = new Ctor();
|
||
await lib.open(Buffer.from(rawBytes), {}); // note: open() detaches the buffer
|
||
const meta = await lib.metadata(true); // fullOutput — needed for color_data
|
||
const raw = await lib.rawImageData(); // { raw_width, raw_height,
|
||
// top_margin, left_margin,
|
||
// width, height, data: Uint16Array }
|
||
lib.dispose();
|
||
```
|
||
|
||
Gotchas confirmed during the prototype:
|
||
|
||
- `metadata()` **without** `true` omits `color_data` entirely; `filters`/`cdesc`/
|
||
`colors` are top-level either way.
|
||
- `open()` transfers the buffer to the worker and detaches it — hand it a copy if the
|
||
caller's bytes are needed again (`server/raw.mjs` already does this).
|
||
- `imageData({ noInterpolation: true })` returns 8-bit, pre-rotated, CFA-gap-zeroed
|
||
output. Useless as a mosaic source; `rawImageData()` is the only option.
|