# IMX477 linear ISP audit - ISP black level (black_level) 0 versus 64

Date: 2026-09-29 - Pi4 `polarscope@10.0.0.5` (`pinox`, kernel 6.18.50+rpt-rpi-v8).
Remote repository: `/home/polarscope/Documents/c++/polarscope`.
No production files were modified: only the QA tools/files listed at the end of
this report were added or synchronised.

## 1. Objective

Determine empirically whether the ~1.065 slope difference observed between the VC4
ISP buffer and EIP software demosaicing (with tuning `black_level` set to 4096,
i.e. 64 in 10 bits) came from **pedestal range rescaling** by the ISP. To test this,
repeat paired capture with tuning `rpi.black_level.black_level = 0` and EIP black
level 0, then compare per-channel slopes/offsets between the two conditions.

## 2. Protocol

- Test bench: `tools/diagnostics/isp_linear_bench.cpp` (QA tool only).
- The **same libcamera Request** produces two paired streams:
  - RAW `SBGGR12_CSI2P`, 2028x1520, stride 3072;
  - Viewfinder `RGB888`, 2028x1520, stride 6144 (60 padding bytes/row).
- EIP reference: `image::bayerPackedToRgb888` applied **to the same RAW** with unity
  WB gains (1.0, 1.0), gamma disabled and a CLI black level (new optional argument,
  default 64). The benchmark therefore compares the **actual `BayerRawCodec`/EIP**
  with the ISP buffer from the same Request, rather than an approximation.
- Sensor mode `bin2x2(2028x1520)`, exposure 20000 us, analogue gain 3.5,
  10 frames per condition, final frame saved.
- Tuning selected through `LIBCAMERA_RPI_TUNING_FILE` (the IPA log
  `Using tuning file ...` confirms application).
- `imaging-server.service` stopped during capture, restored through `trap EXIT`
  (port 8765 checked after each run).
- Analysis: `qa/isp-linear/analyze_captures.py` recalculates everything (no C++
  statistics), corrects stride and B,G,R -> R,G,B memory order, excludes a 24 px
  border and saturated pixels (channel >= 254).

### Captured conditions

| Condition | Tuning | ISP black | EIP black |
|-----------|--------|-----------|-----------|
| official | `/usr/share/libcamera/ipa/rpi/vc4/imx477.json` | (default) | 64 |
| linear | `qa/isp-linear/imx477_linear.json` | 4096 (64) | 64 |
| linear2 | same as linear (repeatability) | 4096 (64) | 64 |
| black64 | same as linear, contemporary control | 4096 (64) | 64 |
| black0 | `qa/isp-linear/imx477_linear_black0.json` | 0 | 0 |

## 3. Active blocks / current configuration

RPiController log for linear tuning:

- Active: `rpi.black_level`, `rpi.dpc`, `rpi.lux`, `rpi.noise`, `rpi.geq`,
  `rpi.sdn`, `rpi.awb`, `rpi.agc`, `rpi.contrast`, `rpi.ccm`, `rpi.sharpen`,
  `rpi.sync`.
- Disabled: `rpi.nn.awb`, `rpi.alsc`, `rpi.hdr`.

Linear tuning neutralisation (`make_linear_tuning.py`): `dpc.strength=0`,
`geq=(0,0)`, `sdn.strength=0`, `contrast.ce_enable=0` + identity gamma
`[0,0,65535,65535]`, identity `ccm`, `sharpen.strength=0`/`limit=0`,
`alsc.enabled=false`, `hdr.enabled=false`, `nn.awb.enabled=false`. Only the
`black0` variant differs, through `rpi.black_level.black_level = 0`.

### Division of settings: libcamera controls versus VC4 tuning

The test bench combines two separate groups of settings.

**a) libcamera controls (`CameraSettings` / Request):**

| Control | Value in this test bench | Note |
|---------|--------------------------|------|
| `AeEnable` (`autoExposure`) | false | manual exposure |
| `ExposureTime` (`exposureUs`) | 20000 us | actual value confirmed: 19999 us (`frame_metadata` metadata) |
| `AnalogueGain` (`analogGain`) | 3.5 | actual value confirmed: 3.49488 (`frame_metadata` metadata) |
| `AwbEnable` (`autoWhiteBalance`) | false | AWB inhibited |
| `ColourGains` | (1.0, 1.0) | unity gains |
| `FrameDurationLimits` | 21000 us requested | `applyRequestControls` (autoExposure=false) imposes `exposureUs + max(1000, exposureUs/20)` = 21000 us for a 20000 us exposure; metadata 22131 us (sensor constraint/rounding) |

**b) Neutralisation through VC4 tuning (`LIBCAMERA_RPI_TUNING_FILE`):**

| Tuning block | Neutralised setting |
|--------------|---------------------|
| `rpi.black_level` | `black_level` = 0 (black0 variant) or 4096 (= 64 in 10 bits) |
| `rpi.ccm` | identity matrix |
| `rpi.contrast` | `ce_enable=0` + identity gamma `[0,0,65535,65535]` |
| `rpi.dpc` | `strength=0` |
| `rpi.alsc` | `enabled=false` |
| `rpi.geq` | `offset=0`, `slope=0` |
| `rpi.sdn` | `strength=0` |
| `rpi.sharpen` | `strength=0`, `limit=0` |
| `rpi.hdr` | `enabled=false` |
| `rpi.nn.awb` | `enabled=false` |

`rpi.lux`, `rpi.noise`, `rpi.agc` and `rpi.sync` are retained (pedestal,
exposure, gain, synchronisation). The tuning's `rpi.awb` block remains present and
enabled, but AWB is effectively inhibited by `AwbEnable=false` + `ColourGains=(1,1)`.

### libcamera controls versus VC4 tuning

The IPA does apply the tuning (`Using tuning file ...` log entry and algorithms'
enabled/disabled status). `pkg-config libcamera` provides `-lcamera -lcamera-base`.
The cross-check is numerical: the `official` condition retains the official
tuning's CCM and gamma (AWB inhibited through controls, as in all conditions), and
the ISP/EIP relationship is nonlinear, whereas it is linear under `linear`
(identity CCM + identity gamma; R2 >= 0.996). This confirms that the linear file
is actually applied, rather than the default tuning.

## 4. Minimal tuning

QA derivation by `qa/isp-linear/make_linear_tuning.py` from the official copy
`imx477_official.json`; the `imx477_linear_black0.json` variant is **identical**
to the linear tuning except for `rpi.black_level.black_level = 0`
(checked programmatically).

## 5. Results - per-channel regression ISP = slope * EIP + offset

Valid pixels (border and saturation excluded): linear 2 663 615, black64 2 660 361,
black0 2 658 957.

### black0 condition (ISP black=0, EIP black=0)

| Channel | slope | offset | R2 | RMSE | MAE |
|---------|-------|--------|----|------|-----|
| R | 1.0012 | -0.314 | 0.99587 | 0.894 | 0.687 |
| G | 0.9983 | +0.119 | 0.99988 | 0.505 | 0.299 |
| B | 0.9984 | -0.143 | 0.99883 | 0.987 | 0.747 |

Mean black0 slope = **0.9993**.

### black64 condition (ISP black=4096, EIP black=64)

| Channel | slope | offset | R2 | RMSE | MAE |
|---------|-------|--------|----|------|-----|
| R | 1.0684 | -0.279 | 0.99618 | 0.920 | 0.675 |
| G | 1.0650 | +0.111 | 0.99987 | 0.567 | 0.461 |
| B | 1.0652 | -0.125 | 0.99890 | 1.027 | 0.777 |

Mean black64 slope = **1.0662** (the ~1.065 difference is reproduced).

### Range rescaling test

Hypothesis: the ISP maps `(RAW - black)` to 0..255 while EIP calculates
`(RAW - black)/4`. Prediction in 10 bits:

- `slope_black64 = 4 * 255 / (1023 - 64) = 1020/959 = 1.0636`;
- `slope_black0  = 4 * 255 / 1023        = 1020/1023 = 0.9971`;
- ratio `slope_black0 / slope_black64 = 959/1023 = 0.93744`.

Measured ratio by channel: R 0.93713, G 0.93738, B 0.93726 (mean ~0.9372),
a difference of < 0.04% from the prediction. Measured slopes (1.0662 and 0.9993)
are approximately 0.2% above predictions (1.0636 and 0.9971).

Direct pedestal relationships (same RAW, same pixels):

- `ISP_black0` versus `ISP_black64`: slope ~0.9365, offset ~**+16.0** LSB, R2 >= 0.993;
- `EIP_black0` versus `EIP_black64`: slope ~0.998, offset ~**+16.0** LSB, R2 >= 0.997.

The 16 LSB offset corresponds exactly to `64/4`, and the 0.9365 slope corresponds
to `959/1023 = 0.9375`. In other words, the ISP in `black0` gives
`0.9375 * ISP_black64 + 16`, the precise signature of range rescaling:
**the ~1.065 difference with black=64 does come from ISP pedestal range
rescaling**. Aligning ISP and EIP to the same black level (0) brings the slope
down to ~1.00.

## 6. Spatial behaviour / edges / noise (linear condition, including black0)

- **Alignment**: `identity` orientation, correlation 1.0 (no flip), integer shift
  (0,0), subpixel peak (0,0) -> pixel-for-pixel pairing.
- **High frequency**: `hf_slope` 0.9998-0.9999 and local variance ratio
  1.000-1.006 across R/G/B -> neither ISP sharpening nor smoothing (sharpen and
  sdn neutralised).
- **Vignetting**: ISP/fit ratio min 0.991-0.997, median 1.0002, max <= 1.0045,
  standard deviation <= 0.0014 -> no shading correction (alsc disabled).
- **Mixing matrix** after 5x5 smoothing: black0 ~ identity with gains
  (1.006, 0.999, 0.993) and off-diagonal terms < 0.003; black64 ~ identity with
  gains (1.068, 1.066, 1.061). The full-resolution matrix is contaminated by
  demosaicing interpolation (off-diagonal terms ~0.2) and can only be interpreted
  after smoothing.
- **Repeatability, linear versus linear2**: ISP mean |delta| 0.89 LSB, standard
  deviation 1.28, p99 4; EIP mean |delta| 0.82, standard deviation 1.23.
  Temporal noise ~1 LSB.

## 7. Limitations

- A single scene (no test chart), exposure and gain; valid for this operating point.
- The codec normalises 12-bit RAW to 10 bits; the prediction model is written in 10 bits.
- In `black0`, no pedestal is subtracted: both streams (ISP and EIP) retain the
  sensor black level, hence the residual ~16 LSB offset between conditions but
  unity slope between ISP and EIP.
- EIP uses bilinear demosaicing; the ISP uses its own algorithm, explaining the
  residual RMSE of ~0.5-1.0 LSB, independently of black level.
- Digital gain: no independent `DigitalGain` control is applied by the test bench,
  and no digital-gain metadata is read. Only actual exposure (19999 us) and actual
  analogue gain (3.49488) are confirmed by `frame_metadata`. Any internal ISP
  digital-gain component is therefore not quantified here; digital gain cannot
  be claimed to be explicitly controlled.
- The `official` condition cannot be compared linearly (official CCM and gamma
  active; AWB inhibited through controls) and is provided only as context.

## 8. Factual conclusion

The ISP/EIP slope changes from **1.0662** (ISP black_level 64) to **0.9993**
(ISP black_level 0), with R2 from 0.996 to 0.9999 and a measured ratio of 0.9372
versus 0.93744 predicted. The ~1.065 difference is therefore fully explained by
pedestal range rescaling: the ISP expands `(RAW - black)` across the full range.
Once ISP and EIP share the same black level, EIP software demosaicing reproduces
the ISP buffer from the same Request to within ~0.1% in slope.

This agreement is obtained with unity white-balance gains (1,1): ISP and EIP
therefore show the same native colour appearance (green/turquoise cast). This
is precisely the expected experimental result and does not constitute colour
correction; no chromatic correction is claimed here.

## 9. Final checks

- `imaging-server.service`: `active`, `enabled`.
- Port 8765: listening (`ss -ltn`).
- `python3 qa/isp-linear/analyze_captures.py`: rerun successfully.

## 10. QA files added / synchronised

- `qa/isp-linear/imx477_linear_black0.json` (new, derived from `imx477_linear.json`).
- `tools/diagnostics/isp_linear_bench.cpp` (EIP black-level CLI argument, default 64).
- `qa/isp-linear/run_final_black0_pi.sh` (black0 capture + black64 control, service trap).
- `qa/isp-linear/analyze_captures.py` (black0/black64 conditions, black-level comparison).
- `qa/isp-linear/results/captures/final_black0_*` and `final_black64_*`.
- `qa/isp-linear/results/{json/measurements.json,csv/black_level_slopes.csv,images/*,plots/*}`.

Test-bench compilation command on the Pi (identical to the server build's source set):

```
g++ -std=c++17 -O2 \
  -DEIP_POLARSCOPE_ONLY -DPOLARSCOPE_HAS_LIBCAMERA -DEIP_HAS_LIBCAMERA \
  -DPOLARSCOPE_HAS_JPEG -DEIP_HAS_JPEG \
  -Isrc/bootstrap -Isrc/apps/polarscope -Isrc/model -Isrc/model/astronomy \
  -Isrc/model/camera -Isrc/model/hardware -Isrc/model/image -Isrc/model/network \
  -Isrc/model/polar -Isrc/utils $(pkg-config --cflags libcamera) \
  tools/diagnostics/isp_linear_bench.cpp \
  src/model/camera/LibcameraCaptureBackend.cpp src/model/camera/CameraCaptureBackend.cpp \
  src/model/camera/CameraSettings.cpp src/model/camera/CameraFrame.cpp \
  src/model/polar/PolarScopeSettings.cpp src/model/image/BayerRawCodec.cpp \
  -o /tmp/ispbuild/isp_linear_bench \
  $(pkg-config --libs libcamera) -fopenmp -lpthread
```
