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>
15 KiB
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
updatewhen 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)
{
"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)
{
"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:
- Load the input via ImageSharp (
Image.Load<Rgba32>(stream)). - Smart crop —
ISmartCropper.ComputeCropRectpicks 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 viaCrop(rect). See "Smart cropping" below. - 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).
- Dither against a palette built from the already-parsed
DisplayColorof eachPaletteEntry, using the configured dither algorithm:var displayPalette = frame.Palette.Select(p => p.DisplayColor).ToArray(); img.Mutate(x => x.Dither(ditherings[frame.Dithering], displayPalette));frame.Ditheringis aDitherAlgorithmenum;ditheringsisIReadOnlyDictionary<DitherAlgorithm, IDither>. - Remap each pixel from
DisplayColor→DeviceColor. Build aDictionary<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. - Rotate 90° if
orientation == portraitso the output PNG is alwayswidth × heightas declared (e.g., 1600×1200), with content rotated for portrait mounting. - Encode as indexed PNG (
PngColorType.Palette,PngBitDepth.Bit4— fits 6 colors in a nibble). ImageSharp'sPngEncoderwithQuantizer = new PaletteQuantizer(deviceColorPalette)produces this in one call. - Atomic write:
{tmpPath} → {finalPath}viaFile.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):
- If source aspect matches target aspect within ~0.5%, return full source bounds — no crop needed.
- 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.
- Downscale a clone of the source to 256 px on the long edge (cheap analysis canvas).
- Compute per-pixel Sobel magnitude on Rec. 601 luma, build a summed-area table for O(1) rectangle sums.
- 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.
- 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
MQTTnetv4 withIMqttClientwrapped in a hosted service (MqttPublisher : IHostedService).- Single persistent connection with
WithCleanSession(false),WithKeepAlivePeriod(KeepAliveSeconds)andWithTimeout(ConnectTimeoutSeconds). Connection state surfaced to/health. - Reconnect (SPEC.md §5.2):
IMqttClienthas no built-in reconnect, soMqttPublisherowns it. ADisconnectedAsynchandler logs the reason and signals a bounded(1)_reconnectchannel — it never callsConnectAsyncitself, so connects are never concurrent.ExecuteAsyncwaits on that signal (or a safety timeout equal to the last backoff value, in case an event is missed), then retriesConnectAsyncon theReconnectBackoffSecondsschedule 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.PublishAsyncreturns aResult(success/failure). If failure, the publisher enqueues the (topic, payload) into an in-memoryChannel<Pending>and a background loop drains it with the configured backoff sequence. The upload response includesmqttPublished: falseso 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.jpgexercises 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)
docker compose up --build— service comes up, connects to broker,/healthreturns{ status: "Healthy", mqttConnected: true }.curl -H "X-Api-Key: ..." -F "image=@photo.jpg" http://localhost:8080/api/frames/living-room/image— returns 200 with aurl.- Open
http://localhost:8080/i/aabbccddeeff.pngin a browser → confirm the dithered, color-remapped PNG looks reasonable visually. - Subscribe with
mosquitto_sub -t 'frames/#' -v→ confirmframes/aabbccddeeff updateappears within ~1s of the upload. - Repeat with
/image-urland a public image URL. - Concurrency check: fire two
curluploads to the same frame in parallel → both return 200, only one final PNG on disk, two MQTT publishes (in serial order). - 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,/healthflips back tomqttConnected: 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 sameClientIdagainst the same broker → logs showSessionTakenOver. Use a distinctMqtt__ClientIdfor local dev. - Run
dotnet test→ golden-image fixtures pass. - 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.