Files
frame-processor/PLAN.md
T
zyberzeroandClaude Opus 5.5 ac9a0b43a8 Add saliency-based smart crop before resize
Replace the center-crop cover resize with a Sobel edge-density search
that picks the target-aspect window with the most edge energy, so a
subject off-center isn't sliced when the input aspect differs from the
frame's. Failures fall back to the centered crop. Golden fixtures are
regenerated and an asymmetric-edges input exercises the bias.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-03 19:03:22 +01:00

238 lines
15 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Frame Processor — Plan
## Context
A self-hosted ASP.NET Core service that turns arbitrary images (uploaded as JPG/PNG or pulled from a URL) into something a 6-color e-ink frame (Spectra 6) can render. The frame's accepted colors don't match what's *actually displayed* — `#FF0000` in the PNG renders as a muted `#62201E` red on the device — so the pipeline has to dither against the *displayed* palette and then remap each pixel to the device-input color. After the PNG is ready, the service publishes an MQTT signal; the frame wakes and pulls its image from `/i/{mac}.png`.
The firmware is already written, so we get to design both sides. The service must support multiple frames (each with its own MAC, resolution, orientation, palette) so it can grow with the home setup.
---
## Architecture
Single ASP.NET Core (.NET 10) service, sync request handling, packaged as a Docker image with docker-compose.
```
[client] --POST image--> [Service] --dither+remap+save PNG--> [disk] --GET /i/{mac}.png--> [frame]
|
+--MQTT publish "update"--> [broker] -----> [frame]
```
Key non-functional choices:
- **Sync** request model (1600×1200 dither finishes well under 1s; no queue needed).
- **Per-frame lock** to serialize concurrent uploads to the same frame.
- **Latest-only storage** on local disk with atomic temp-file rename.
- **MQTT non-blocking on failure**: PNG saved regardless, background retry loop publishes the `update` when broker recovers.
---
## Project layout
```
src/FrameProcessor/
Program.cs // host + DI + middleware wiring
Domain/ // value types — own their JSON + route binders
MacAddress.cs // record struct; permissive parse, canonical lowercase-no-separator ToString
FrameName.cs // record struct; validates URL-safe charset (RFC 3986 unreserved)
Orientation.cs // enum Landscape | Portrait with JSON converter
Resolution.cs // record; ForOrientation(Orientation) returns rotated pair
PaletteEntry.cs // record with parsed ImageSharp Colors (no hex strings)
DitherAlgorithm.cs // enum (floyd-steinberg | atkinson | stucki | jarvis) with JSON converter
ApiKey.cs // record struct with constant-time comparison
Configuration/
FramesOptions.cs // bound from frames.json (IOptionsMonitor)
MqttOptions.cs // bound from appsettings.json
ApiKeyOptions.cs // wraps an ApiKey
Controllers/
FramesController.cs // POST /api/frames/{name}/image, /image-url
ImageController.cs // GET /i/{mac}.png
HealthController.cs // GET /health
ImagePipeline/
IImagePipeline.cs
ImagePipeline.cs // smart-crop → resize → dither → remap → encode (indexed PNG)
PaletteFactory.cs // builds ImageSharp ReadOnlyMemory<Color> from PaletteEntry list
DitheringRegistry.cs // maps DitherAlgorithm → IDither
SmartCrop/
ISmartCropper.cs // computes a crop rect in source coordinates
SaliencySmartCropper.cs // Sobel edge-density saliency search
Mqtt/
MqttPublisher.cs // persistent MQTTnet client, QoS 1, background retry queue
Storage/
ImageStore.cs // atomic write, path resolution from MacAddress
Middleware/
ApiKeyMiddleware.cs // enforces API key on /api/* only
Concurrency/
FrameLockProvider.cs // keyed SemaphoreSlim per FrameName
tests/FrameProcessor.Tests/
ImagePipelineTests.cs // golden-image fixtures
PaletteFactoryTests.cs
MacAddressTests.cs // round-trips colons/hyphens/uppercase/whitespace → canonical
FrameNameTests.cs // URL-safety validation
Dockerfile
docker-compose.yml
appsettings.json
frames.json // mounted; not in image
```
---
## Settings schemas
### `appsettings.json` (in image, overridable by env)
```jsonc
{
"Mqtt": {
"Host": "mosquitto",
"Port": 1883,
"ClientId": "frame-processor",
"Username": null,
"Password": null,
"UseTls": false,
"BaseTopic": "frames",
"PublishQos": 1,
"RetryBackoffSeconds": [1, 2, 5, 15, 60],
"ReconnectBackoffSeconds": [1, 2, 5, 15, 30],
"KeepAliveSeconds": 15,
"ConnectTimeoutSeconds": 10
},
"ApiKey": "change-me",
"Storage": {
"ImageDirectory": "/data/images"
},
"UrlFetch": {
"MaxBytes": 52428800,
"TimeoutSeconds": 30,
"MaxRedirects": 3
},
"Logging": { "LogLevel": { "Default": "Information" } }
}
```
### `frames.json` (mounted volume, hot-reloaded via `IOptionsMonitor`)
```jsonc
{
"Frames": [
{
"name": "living-room",
"mac": "AA:BB:CC:DD:EE:FF", // normalized to "aabbccddeeff" at load
"resolution": { "width": 1600, "height": 1200 },
"orientation": "landscape", // landscape | portrait
"dithering": "floyd-steinberg", // floyd-steinberg | atkinson | stucki | jarvis
"palette": [
{ "name": "black", "color": "#1F2226", "deviceColor": "#000000" },
{ "name": "white", "color": "#B9C7C9", "deviceColor": "#FFFFFF" },
{ "name": "blue", "color": "#233F8E", "deviceColor": "#0000FF" },
{ "name": "green", "color": "#35563A", "deviceColor": "#00FF00" },
{ "name": "red", "color": "#62201E", "deviceColor": "#FF0000" },
{ "name": "yellow", "color": "#C1BB1E", "deviceColor": "#FFFF00" }
]
}
]
}
```
Validation on load: name URL-safe, MAC parses to 6 bytes, palette has ≥2 entries, all hex colors parse, dithering key is known. Fail startup with a clear message if any frame is invalid; log a warning and skip the bad frame on hot-reload (so a typo doesn't crash a live service).
---
## HTTP API
| Method | Path | Auth | Body | Response |
|--------|-------------------------------------|----------|-------------------------------|----------------------------------------------------------------|
| POST | `/api/frames/{name}/image` | API key | `multipart/form-data` (file) | `200 { frame, mac, url, processedAt, mqttPublished: bool }` |
| POST | `/api/frames/{name}/image-url` | API key | `application/json { url }` | same |
| GET | `/i/{mac}.png` | none | — | `200` PNG with `Cache-Control: no-store`, ETag from mtime; `404` if no image yet |
| GET | `/health` | none | — | `200 { status, mqttConnected }` |
`{name}` resolves to a frame via `FramesOptions` lookup; 404 if unknown.
`{mac}` in `/i/{mac}.png` is normalized on entry (lowercase, separators stripped) and matched against normalized stored MACs.
---
## Image pipeline (the meat)
For each upload:
1. **Load** the input via ImageSharp (`Image.Load<Rgba32>(stream)`).
2. **Smart crop** — `ISmartCropper.ComputeCropRect` picks a source-coordinate rectangle whose aspect matches the frame's oriented resolution (W/H swapped for portrait). If aspects already match within tolerance, the full source bounds is returned and no crop is applied. Otherwise the crop is applied via `Crop(rect)`. See "Smart cropping" below.
3. **Resize** to the frame's oriented resolution. Aspects already match after the smart crop, so this is a pure scale (no cover/crop semantics needed).
4. **Dither** against a palette built from the already-parsed `DisplayColor` of each `PaletteEntry`, using the configured dither algorithm:
```csharp
var displayPalette = frame.Palette.Select(p => p.DisplayColor).ToArray();
img.Mutate(x => x.Dither(ditherings[frame.Dithering], displayPalette));
```
`frame.Dithering` is a `DitherAlgorithm` enum; `ditherings` is `IReadOnlyDictionary<DitherAlgorithm, IDither>`.
5. **Remap** each pixel from `DisplayColor` → `DeviceColor`. Build a `Dictionary<Rgba32, Rgba32>` once per frame from the palette and do a single pixel-buffer pass. Since the dither in step 4 produces only palette colors, every pixel finds a mapping.
6. **Rotate** 90° if `orientation == portrait` so the output PNG is always `width × height` as declared (e.g., 1600×1200), with content rotated for portrait mounting.
7. **Encode** as **indexed PNG** (`PngColorType.Palette`, `PngBitDepth.Bit4` — fits 6 colors in a nibble). ImageSharp's `PngEncoder` with `Quantizer = new PaletteQuantizer(deviceColorPalette)` produces this in one call.
8. **Atomic write**: `{tmpPath} → {finalPath}` via `File.Move(..., overwrite: true)` so the GET endpoint never sees a half-written file.
`IImagePipeline` is a single injected service. Encapsulates 1–7 and returns the bytes; `ImageStore` does step 8.
### Smart cropping
A hard center crop slices the subject in half when going between landscape and portrait. The pipeline instead picks the crop window by Sobel edge density — edge-rich regions tend to coincide with the photo's subject (faces, in particular, contribute a lot of edges via eyes, nose, and hair).
Algorithm (`SaliencySmartCropper`):
1. If source aspect matches target aspect within ~0.5%, return full source bounds — no crop needed.
2. Compute the **max-fitting centered rect** at the target aspect. This is the upper bound on crop size and the fallback if any later step throws.
3. Downscale a clone of the source to **256 px on the long edge** (cheap analysis canvas).
4. Compute per-pixel **Sobel magnitude** on Rec. 601 luma, build a **summed-area table** for O(1) rectangle sums.
5. Slide a target-aspect window over the downscaled image at three sizes (100%, 85%, 70% of the max-fitting size) with an 8 px step, pick the position with maximum total edge energy.
6. Scale the winning rect back to source coordinates, clamp to image bounds, return.
Failure mode: the whole `ComputeCropRect` is wrapped in `try/catch`; on any exception we log a warning and return the centered max-fitting rect. A bad photo must never 500 the upload — same doctrine as MQTT failure being non-fatal.
Determinism: pure managed integer/float math, no native deps, no ML model. Golden-image byte equality holds across runs.
No configuration knob in v1 — smart crop is always on, and same-aspect inputs hit the zero-cost fast path.
---
## MQTT
- `MQTTnet` v4 with `IMqttClient` wrapped in a hosted service (`MqttPublisher : IHostedService`).
- Single persistent connection with `WithCleanSession(false)`, `WithKeepAlivePeriod(KeepAliveSeconds)` and `WithTimeout(ConnectTimeoutSeconds)`. Connection state surfaced to `/health`.
- **Reconnect** (SPEC.md §5.2): `IMqttClient` has no built-in reconnect, so `MqttPublisher` owns it. A `DisconnectedAsync` handler logs the reason and signals a bounded(1) `_reconnect` channel — it never calls `ConnectAsync` itself, so connects are never concurrent. `ExecuteAsync` waits on that signal (or a safety timeout equal to the last backoff value, in case an event is missed), then retries `ConnectAsync` on the `ReconnectBackoffSeconds` schedule until connected. On success it resets the schedule and wakes the retry loop so queued publishes drain immediately.
- Publish: `topic = {BaseTopic}/{normalized-mac}`, payload bytes `"update"`, QoS 1, not retained.
- **Failure handling**: `MqttPublisher.PublishAsync` returns a `Result` (success/failure). If failure, the publisher enqueues the (topic, payload) into an in-memory `Channel<Pending>` and a background loop drains it with the configured backoff sequence. The upload response includes `mqttPublished: false` so callers know.
---
## Concurrency
`FrameLockProvider` exposes `Task<IDisposable> AcquireAsync(FrameName frame, CancellationToken ct)` and hands out a per-frame `SemaphoreSlim(1,1)` keyed by `FrameName`. `FramesController` wraps the whole pipeline (download → process → save → publish-attempt) in the lock for that frame so the latest-written PNG always corresponds to the latest publish attempt.
---
## Tests
`tests/FrameProcessor.Tests` (xUnit + ImageSharp):
- **`ImagePipelineTests`** — golden-image fixtures. Check in synthetic test inputs (`landscape.jpg`, `portrait.jpg`, `tiny-1x1.png`, `non-divisible.jpg`, `asymmetric-edges.jpg`) and expected outputs for one canonical Spectra 6 palette. Assert byte-equality of the indexed PNG output. The pipeline (dither + smart crop) is deterministic for a given input/palette/algorithm, so this is a strong correctness anchor. `asymmetric-edges.jpg` exercises the saliency search by placing a high-edge checkerboard on one half of the source and flat gray on the other — the smart crop must bias toward the edge-rich half.
- **`PaletteFactoryTests`** — hex parsing, count, error messages on bad hex.
- **`MacAddressTests`** — round-trip: `"AA:BB:CC:DD:EE:FF"`, `"aa-bb-cc-dd-ee-ff"`, `"AABBCCDDEEFF"`, and surrounding whitespace all parse to the same value; `ToString()` always emits the canonical lowercase-no-separator form; equality compares on the 6 bytes.
- **`FrameNameTests`** — accepts URL-safe names, rejects names with reserved or whitespace characters with a clear error.
No controller/integration tests in v1 — pipeline correctness is the load-bearing part; HTTP plumbing is thin enough to verify manually with curl.
---
## Verification (end-to-end)
1. `docker compose up --build` — service comes up, connects to broker, `/health` returns `{ status: "Healthy", mqttConnected: true }`.
2. `curl -H "X-Api-Key: ..." -F "image=@photo.jpg" http://localhost:8080/api/frames/living-room/image` — returns 200 with a `url`.
3. Open `http://localhost:8080/i/aabbccddeeff.png` in a browser → confirm the dithered, color-remapped PNG looks reasonable visually.
4. Subscribe with `mosquitto_sub -t 'frames/#' -v` → confirm `frames/aabbccddeeff update` appears within ~1s of the upload.
5. Repeat with `/image-url` and a public image URL.
6. Concurrency check: fire two `curl` uploads to the same frame in parallel → both return 200, only one final PNG on disk, two MQTT publishes (in serial order).
7. Stop the broker, upload an image → response is 200 with `mqttPublished: false`, PNG saved, log shows the disconnect reason and backoff reconnect attempts. Start the broker → service reconnects without a restart, `/health` flips back to `mqttConnected: true`, and the queued publish goes out immediately.
7a. Half-open link: `docker network disconnect <net> <frame-processor container>` → disconnect logged within ~1.5 × `KeepAliveSeconds`; reconnect the network → service recovers on its own.
7b. ClientId collision: run a second instance with the same `ClientId` against the same broker → logs show `SessionTakenOver`. Use a distinct `Mqtt__ClientId` for local dev.
8. Run `dotnet test` → golden-image fixtures pass.
9. Power on the actual Spectra 6 frame mounted with the new firmware → it fetches the PNG and renders it correctly with the expected color mapping.