# Sidecar/1 — a frame-bound answerability record

**Version** `sidecar/1` · **Date** 2026-09-05 · **Authors** resoa / loglens · **Reference implementation** `nanolab/sidecar1.py` (nanolab 0.4.0)

`nanolab.sidecar` puts kilobytes per frame *inside* an H.264 stream as SEI `user_data_unregistered`
NAL units. This document says what those bytes mean. The envelope is one JSON object per frame; each
measurement row carries the record of *whether the question was answerable* — pixels on target,
gate outcome, scalar baseline margin — alongside the answer, and a 64-bit fingerprint of the frame so
the frame binding can be recovered when the transport loses it.

## 1. The envelope

One JSON object per frame, compact keys. Every field except `v` and `f` is optional. Unknown keys
anywhere are preserved and never an error.

```json
{
  "v":  "sidecar/1",
  "f":  17,                       // display frame index (sender's counter)
  "d":  19,                       // decode index; stamped by nanolab.sidecar.json_payload at injection
  "t":  1757000000.033,           // seconds or unix time
  "fp": "9a3c5e70f1b2d4a6",       // 64-bit pHash of the frame luma, 16 lowercase hex chars (§4)
  "src": {"cam": "bay2-east", "res": [1920, 1080], "tx_res": [640, 360]},
  "m":  [ ...measurement rows... ]
}
```

| key | type | meaning |
|---|---|---|
| `v` | string | `"sidecar/1"`. Required. A different string is an error (a later spec bumps the number). |
| `f` | int ≥ 0 | Display frame index. Required. |
| `d` | int ≥ 0 | Decode index. The transport stamps it (`json_payload`), because decode order is only known at injection. |
| `t` | number | Seconds since stream start, or unix time. |
| `fp` | string | Frame fingerprint, §4. |
| `src.cam` | string | Camera id. |
| `src.res` | `[w, h]` | The **original sensor** frame. |
| `src.tx_res` | `[w, h]` | The transmitted video. |
| `m` | list | Measurement rows. Absent `m` is a warning (the envelope says nothing about the frame). |

### Measurement row

```json
{
  "k":    "occupancy",                                   // key: "posture", "faces", "cct", "radar.range_m", ...
  "val":  true,                                          // any JSON; null when there is no value
  "p":    0.91,                                          // probability, or null / absent
  "by":   {"model": "occ-nano", "ver": "3f9a1c", "kind": "nano"},
  "gate": {"px_on_target": 41.0, "task": "detect", "lux": 120, "snr_db": 18.5, "passed": true},
  "base": {"scalar": "thermal_var", "margin": 0.08},
  "ref":  true, "why": "...",                            // only on refusals
  "box":  [812, 340, 210, 460], "space": "orig"          // optional; original sensor pixels unless space = "tx"
}
```

| key | type | meaning |
|---|---|---|
| `k` | string | Measurement key. Required. Dotted namespaces are free-form (`radar.range_m`). |
| `val` | any | The value. Required as a key; `null` is allowed (and is what a refusal usually carries). |
| `p` | number in [0, 1] or null | The model's own probability. **Not a validity signal** (rule 3). |
| `by.model`, `by.ver` | string | What produced it and which build. |
| `by.kind` | `nano` \| `scalar` \| `lookup` \| `sensor` | A learned model, a threshold on a statistic, a table, or a physical sensor. |
| `gate.px_on_target` | number or null | Pixels spanning the diagnostic feature, in the original frame. |
| `gate.task` | `detect` \| `recognise` \| `identify` | Johnson level the key needs: 2 / 8 / 12.8 px. |
| `gate.lux`, `gate.snr_db` | number or null | Illumination and signal-to-noise as measured on the edge. |
| `gate.passed` | bool | Required inside `gate`. The one field a consumer may use as a validity signal. |
| `base.scalar` | string | The cheap baseline this model was carded against. |
| `base.margin` | number or null | Model minus scalar on the model card, transferred split. |
| `ref` | bool | `true` when the measurement was refused; then `why` (non-empty string) is required. |
| `box` | `[x, y, w, h]` | In original sensor pixels unless `space` is `"tx"`. |
| `space` | `orig` \| `tx` | Coordinate space of `box`. Default `orig`. |

`gate()` in the reference implementation fills `passed` from `px_on_target` against the task's
threshold when you do not pass it explicitly; a gate nobody evaluated (`px_on_target` null, no
`passed`) is `false`.

## 2. Design rules

1. **Coordinates default to the original sensor frame.** The point of the record is that it was
   computed *before* downscaling: a 6 mm cannula puts 3.9 px on target from the best wall mount in a
   6 m x 4 m bay against a 12.8 px identify line, and that number is only meaningful in sensor
   pixels — in the 640 px transmitted frame it would read 1.3 px and the receiver could not tell
   whether the sender ever had a chance.
2. **A row without `gate` is allowed but second-class; the validator warns.** The gate is where the
   measured thresholds live (accuracy degrades sharply below ~8 px on the diagnostic feature and the
   effect survives controlling for training-set size: +0.074 / +0.112 / +0.144 within support bands),
   so a row without one is a number with no statement about whether the question was answerable.
3. **`p` alone is never a validity signal; `gate.passed` is, and it must be evaluated AT
   INFERENCE.** Measured 2026-08: model confidence is worse than random under distribution shift,
   which is exactly the condition a receiver is in, while pixels-on-target is a physical quantity
   that does not know which dataset the model was trained on. Measured 2026-09-05: moving the same
   criterion upstream into a training-data filter does NOT work -- a 47K face-presence student
   trained on tiles of a compressed stream was confident on 89.7% of tiles whose face was below the
   8 px recognise threshold whether or not those tiles were removed from its training set (0.897 vs
   0.914 vs 0.927 across three selection policies, 440 unanswerable tiles, held-out scenes). A model
   cannot infer that its own input is unanswerable; only a gate carried alongside the measurement
   can say so, which is why `gate` is a field on the row and a failed gate is a refusal row.
4. **Refusals are rows, not absences.** An absent key is indistinguishable from a sensor that was
   never asked; a finite-state gate that silently refused a quarter of the sensor's own ground truth
   (2026-09-05, §5cp of the lab notes) was only found because the refusals were counted, so they are
   written down with a `why`.
5. **Unknown keys are preserved.** The validator never reports a key it does not know, at the
   envelope or the row level; a `sidecar/1` consumer must pass them through, so that a sender can add
   fields before the spec catches up.
6. **Payload size: ~300–600 B per frame.** At 30 fps that is 100–150 kbit/s, under 2% of an 8 Mbit/s
   stream; the transport measured 325 B/frame for a 300-byte payload (SEI framing costs ~25 B), 9% of
   a 0.9 Mbit/s stream and <1% above ~8 Mbit/s. A full row (`by` + `gate` + `base`) is ~230 B, a
   refusal ~170 B, so the guidance is two or three full rows per frame; keys that do not change
   frame to frame (`cct`, `radar.*`) belong on every Nth frame. The validator warns above 1200 B.

## 3. Example

A bedside camera: occupancy detected by a nano model that beat its thermal-variance scalar by 0.08,
colour temperature from a scalar, a face measurement refused for lack of pixels, and a radar range.
986 bytes compact — four full rows, at the top of the guidance.

```json
{"v":"sidecar/1","f":17,"t":1757000000.033,"fp":"9a3c5e70f1b2d4a6",
 "src":{"cam":"bay2-east","res":[1920,1080],"tx_res":[640,360]},
 "m":[
  {"k":"occupancy","val":true,"p":0.91,
   "by":{"model":"occ-nano","ver":"3f9a1c","kind":"nano"},
   "gate":{"px_on_target":41.0,"task":"detect","lux":120,"snr_db":18.5,"passed":true},
   "base":{"scalar":"thermal_var","margin":0.08},
   "box":[812.0,340.0,210.0,460.0]},
  {"k":"cct","val":4100,
   "by":{"model":"grey-world","ver":"1","kind":"scalar"},
   "gate":{"px_on_target":null,"task":"detect","lux":null,"snr_db":null,"passed":true},
   "base":{"scalar":"grey_world","margin":null}},
  {"k":"faces","val":null,
   "by":{"model":"face-nano","ver":"b77","kind":"nano"},
   "gate":{"px_on_target":3.9,"task":"recognise","lux":null,"snr_db":null,"passed":false},
   "ref":true,"why":"3.9 px on target, recognise needs 8"},
  {"k":"radar.range_m","val":2.4,
   "by":{"model":"ld2410","ver":"fw2.1","kind":"sensor"},
   "gate":{"px_on_target":null,"task":"detect","lux":null,"snr_db":null,"passed":true}}
 ]}
```

`validate(env)` returns `[]` for this object. Adding `{"k": "posture", "val": "sitting", "p": 0.99}`
returns one string: `warning: m[4] (posture) has no gate -- second-class row; p alone is not a
validity signal`. Deleting `v` returns `error: v is required (expected 'sidecar/1')`.

## 4. The fingerprint

`fp` is a 64-bit perceptual hash (pHash, after Zauner 2010) of the frame's luma. The steps below are
the specification; a receiver in any language must reproduce them bit for bit on the same input, and
within a few bits on a transcoded one.

**Input.** A 2-D array `g[y][x]` of luma values in 0–255, any size ≥ 1×1. From RGB use BT.601,
`Y = 0.299 R + 0.587 G + 0.114 B`; from a decoded YUV frame use the Y plane directly. The sender
fingerprints the luma it hands to the encoder (at `tx_res`); the hash is resolution-invariant to
within the survival tolerance, so a receiver may hash whatever size it decodes.

**Step 1 — 32×32 block mean.** For an axis of length `L`, cell `i` (0 ≤ i < 32) covers input indices
`[lo, hi)` with `lo = floor(i·L/32)`, `hi = max(floor((i+1)·L/32), lo+1)`. Cell (i, j) of `s` is the
arithmetic mean of `g` over rows `[lo_i, hi_i)` and columns `[lo_j, hi_j)`, in double precision. For
`L < 32` cells repeat rows (nearest), which is what makes tiny inputs legal.

**Step 2 — DCT.** Orthonormal DCT-II along both axes, keeping the first 8 coefficients of each:

```
D[u][x] = c(u) · cos(π · (2x + 1) · u / 64),   x = 0..31, u = 0..7
c(0) = sqrt(1/32),  c(u > 0) = sqrt(2/32)
C = D · s · Dᵀ                                  (8 × 8)
```

**Step 3 — median.** Flatten `C` row-major into 64 values `c[0..63]` (`c[8u + v] = C[u][v]`). Sort a
copy ascending; `median = (sorted[31] + sorted[32]) / 2`. The DC term is included, so bit 0 is almost
always 1; it costs one bit and keeps the layout identical to the common pHash.

**Step 4 — bits.** `bit[k] = 1 if c[k] > median else 0` (strictly greater). Pack MSB first —
`value = Σ bit[k] · 2^(63 − k)` — and print as 16 lowercase hex digits, zero-padded.

**Check vector.** For the 64×64 image `g[y][x] = uint8(4y + 0.5x)` (a diagonal gradient), the
reference produces `aa0a7f817e817e85`. Coefficients within ~1e-9 of the median may differ between
float implementations; that is at most one or two bits and inside the tolerance below.

**Distance.** `hamming(a, b)` is the popcount of `a XOR b`, 0–64. Independent images sit near 32.

### Measured (2026-09-05, 600 frames, 640×360 synthetic scene with a moving block, x264)

| degradation | Hamming to original: median | p99 | max |
|---|---|---|---|
| transcode libx264 CRF 28 | 0 | 2 | 4 |
| 2× downscale to 320×180 + CRF 28 | 0 | 4 | 4 |

Consecutive frames of the moving scene differ by 4 bits (median; p10 2). Of the static variant
(one frame held with sensor noise) by 0. Those two numbers together are the whole rebinding story.

## 5. Rebinding after a transcode

SEI survives a remux (300/300, mp4 → mkv → mp4, and `-c copy` to Annex-B) and dies on any default
re-encode (0/300). A receiver that gets the video by an unknown path therefore treats the SEI as
a fast path and the fingerprint as the fallback: it hashes each decoded frame, and re-associates the
envelope sequence (still in time order, e.g. delivered over a data channel) with the frame sequence.

**Why not nearest neighbour.** The survival tolerance (p99 4 bits) is the same size as the distance
between neighbouring frames (median 4), so the nearest fingerprint within a window is a look-alike
neighbour for a measurable fraction of frames: 0.905 correct after a transcode, **0.86** after
downscale + transcode.

**Alignment.** Both sequences are monotone in time, so `rebind(rows, frame_fps, window=60,
gap=6.0)` runs a banded Needleman-Wunsch: a match costs its Hamming distance, skipping a row or a
frame costs `gap`, and only pairs within ±`window` indices are considered. A pair is matched only
when cheaper than skipping both (Hamming < 2·gap = 12). Measured on the same clip: **1.00** correct
after downscale + transcode, and 1.00 with every 50th decoded frame dropped. Ties in the backtrack
prefer a match over a row skip over a frame skip, at the later row. A row without a fingerprint
keeps its slot as a zero-cost wildcard and comes back with the frame its position implies and no
Hamming (order is its only evidence). `rebind_nearest` keeps the naive version for comparison.

**When it cannot work.** On a static scene the fingerprint carries no ordering information:
consecutive frames are 0 bits apart, nearest neighbour is right 0.003 of the time, and alignment is
arbitrary within runs (0.10 correct on one degradation of the static clip, 1.00 on another — luck,
not signal). `ambiguous(frame_fps, max_hamming=4, window=60)` is the fraction of decoded frames
with a look-alike within the window; it read 1.0 on the static clip. Read it together with the
consecutive-frame Hamming median (0 static, 4 moving): a slowly moving scene also flags (0.83–0.97
on the synthetic sequence in the tests) and is exactly what alignment handles, while a flagged
sequence whose consecutive median is 0 must fall back to timestamps and decode index. The failure is
detected, not silent.

**Receiver procedure.**
1. If SEI payloads are present (`nanolab.sidecar.extract`), bind by `d` / pts. Done.
2. Else hash every decoded frame (§4), call `rebind` with the envelopes in time order, and accept
   matches. Rows that come back `None` had no frame within the band, or the frame was dropped.
3. Compute `ambiguous` and the consecutive median; if the scene is static, bind by `t` instead and
   mark the binding as timestamp-derived.

## 6. Priority statement (2026-09-05)

No individual mechanism here is new; the schema and the coupling are. The primitives and their
owners, credited so nobody has to do it for us:

- **Per-frame ML metadata inside the bitstream**: HEVC v7 "annotated regions" SEI (2019) and the
  Intel end-to-end pipeline built on it (Guruvareddiar, Boyce & Poornachandran, SPIE 2021,
  doi 10.1117/12.2593619); NVIDIA DeepStream `nvdsmetainsert` / `nvdsmetaextract` (SEI
  unregistered user data); Axis signed-video (SEI and AV1 metadata OBU); ffmpeg `-udu_sei`.
  Browser-side SEI parsing is a shipped API (WebRTC Encoded Transform), not an invention.
- **Per-target confidence, pixels-on-target and algorithm name/version, per frame**: MISB ST 0903
  VMTI (~2010); per-window quality metrics: MISB ST 1108. ONVIF analytics metadata is a separate
  RTP stream whose timestamps carry no meaning, which is exactly what in-band binding fixes.
- **Refusal as selective classification**: Geifman & El-Yaniv 2017 (arXiv 1705.08500).
- **Fingerprint soft-binding after metadata stripping**: C2PA 2.2 soft bindings; robust per-frame
  video hashes: Oostveen, Kalker & Haitsma 2002; pHash (Zauner 2010). Sequence alignment is
  Needleman-Wunsch (1970). Johnson's criteria are from 1958.
- **Detection-driven bit allocation**: Itti 2004 (foveated compression), AccMPEG (MLSys 2022,
  arXiv 2204.12534), Axis Zipstream, ffmpeg `addroi`.
- **Low-resolution video for privacy** (Ryoo et al. 2017) and on-sensor inference (Sony IMX500).
- **Hash chains over video**: Axis Signed Video and C2PA `c2pa.hash.bmff.v3`; this spec carries no
  chain and claims none.

What is claimed as first published in this package, nanolab 0.4.0, on 2026-09-05, is the
combination and its measured justification:

- **An answerability record per measurement, bound to the frame in-band** — `gate.px_on_target`
  against the task's Johnson level, `gate.passed` as the only validity signal, and `base.margin`
  from the model card — as the unit of a per-frame video sidecar, together with the measured reason
  that `p` cannot serve that role.
- **Refusal as a row**, with the `ref` / `why` pair, as the representation of a measurement that was
  declined for answerability reasons rather than omitted.
- **Fingerprint rebinding by monotone alignment** as the recovery path for a stripped SEI, with the
  measurement that nearest-neighbour rebinding fails (0.86) for the specific reason that the
  survival tolerance equals the inter-frame distance, and the `ambiguous` flag as the detectable
  boundary of the method.

- **The coupling**: the record is computed from the pre-compression, full-resolution, multi-sensor
  signal with coordinates in the original sensor frame, so the transmitted video may be lower-
  resolution or privacy-degraded while the record is not; and the same attention map that produced
  the record can steer the encoder's region-of-interest quantisation. Each half exists (VMTI;
  AccMPEG); their composition with an answerability record, in one ordinary H.264 stream that
  legacy players ignore, is what is claimed. The steering half is an OPTION, not a measured
  benefit: on faces above Johnson's recognise line a uniform encode already gives a modern
  detector 97-99% recall at 150-600 kbit/s, ROI offsets add nothing for the machine and cost
  the human 1-10 dB elsewhere, while the inverse offset drops recall to 0.43 (measured
  2026-09-05, `code/roi_ratecontrol.py`). Where it may still pay -- targets near the threshold
  at scarce bitrate -- is unmeasured.

The general idea of in-band per-frame metadata is not claimed, nor is any single field: VMTI has
carried confidence, pixels-on-target and algorithm version since 2010. What no prior format
carries is `base.margin` (the baseline the model beat) or a refusal row, and none binds a
per-row rebinding key to the measurement.

## 7. Measured survival through infrastructure (2026-09-05)

The synthetic 600-frame sample from the sidecar demo, one SEI per access unit, checked with
`nanolab.sidecar.extract` after each path:

| path | intact |
|---|---|
| remux mp4 -> mkv -> mp4 | 600/600 |
| `-c copy` + Annex-B | 600/600 |
| HLS packaging, copy, 2 s MPEG-TS segments | 600/600 |
| MPEG-TS remux | 600/600 |
| fragmented mp4 (CMAF / DASH style) | 600/600 |
| libx264 transcode, default | 0/600 |
| libx264 transcode with `-udu_sei 1` | 600/600 |
| libx265 re-encode (HEVC) | 0 -- SEI is codec-specific; an HEVC injector is a separate small job |

Rule of thumb: every COPY path keeps the record; every RE-ENCODE drops it unless told to carry
it; the per-row fingerprint (section 4) covers the rest. Fingerprint survival on the same
material: median Hamming 0 after a CRF 28 transcode, p99 2; median 0 after a 2x downscale plus
transcode, p99 4; rebinding by monotone alignment 1.000 with 2% of frames dropped, nearest-
neighbour 0.86. Untested and owed: RTSP/RTP packetizers, a WebRTC SFU, HLS through a CDN,
hardware encoders (NVENC via ffmpeg produced no output on the test machine).
