diff --git a/docs/help/help.json b/docs/help/help.json index d590693c..9806e705 100644 --- a/docs/help/help.json +++ b/docs/help/help.json @@ -3975,12 +3975,27 @@ "fixtureRef": { "line": "The profile name an older config saved, read once and then emptied." }, + "rows": { + "line": "The rows of one panel on a Raspberry Pi's header." + }, + "cols": { + "line": "The columns of one panel on a Raspberry Pi's header." + }, + "panelsPerLane": { + "line": "Panels in series on one lane of a Pi's header; hzeller's `--led-chain` is the same." + }, + "pixelClock": { + "line": "The Pi's pixel clock in kHz; 10,000 is 10 MHz." + }, + "latchBlank": { + "line": "Blank words the Pi's latch holds, 0 for none." + }, "board": { "line": "The board's wiring: picking one fills the fourteen pins, Custom keeps yours.", "more": "A published map hides the pin rows, which stay bound. A pin on flash or PSRAM is refused. Boards and the R1/G1/B1 naming trap: [HUB75 panels](https://moonmodules.org/MoonLight/reference/hardware/hub75-panels.html#which-board)." }, "peripheral": { - "line": "The silicon block that drives the panel, LCD_CAM or Parlio, where the chip has both.", + "line": "The silicon block that drives the panel: LCD_CAM, Parlio or a Pi 5's PIO.", "more": "A P4 has one LCD_CAM and one Parlio, so a board already driving WS2812 strips from one needs the panel on the other. Only you know which way round." }, "scanRate": { @@ -3996,6 +4011,9 @@ }, "refresh": { "line": "The measured refresh rate: the number to report when a panel flickers." + }, + "shown": { + "line": "The frames the panels showed in the last second." } }, "role": "driver", diff --git a/docs/reference/hardware/hub75-bench.md b/docs/reference/hardware/hub75-bench.md new file mode 100644 index 00000000..31f669c6 --- /dev/null +++ b/docs/reference/hardware/hub75-bench.md @@ -0,0 +1,83 @@ +# HUB75 bench record + +What the benches measured on the Raspberry Pi 5 output of the [HUB75 driver](../../moonmodules/light/drivers.md#hub75): `shown` rates, the conditions of each reading, and predictions against readings. Setup and settings are in [Driving a HUB75 panel](hub75-panels.md#raspberry-pi-5-rp1-pio). `shown` is the driver's measured refresh. BENCH-V2 and BENCH-V8 name the bench rounds of 2026-11-13. + +First light and the baseline ran on builds whose engine reached the PIO through piolib, a library the kernel-interface backend (`/dev/pio0`, [Kernels](hub75-panels.md#kernels)) replaces. [The kernel-interface backend](#the-kernel-interface-backend-2026-11-20) measures that backend against the baseline's binary on one wall, and on a second kernel. + +## Raspberry Pi 5 (RP1 PIO) + +The bench is a 256x192 wall on a Pi 5: six 128x64 panels, 2 to a lane, 3 lanes in parallel. + +### Conditions + +| | First light and BENCH-V2, V8 | Baseline | Kernel-interface backend | +|--|--|--|--| +| Date | 2026-11-13 | 2026-11-18, 11:15 to 11:19 UTC | 2026-11-20, 13:24 to 13:39 UTC on 6.18; 16:14 to 17:17 UTC on 6.12 | +| Kernel | 6.18.60+rpt-rpi-2712 | 6.18.60+rpt-rpi-2712 (DietPi, Debian 13.7) | 6.18.60+rpt-rpi-2712 (the same card), and 6.12.109+rpt-rpi-2712 (Raspberry Pi OS Lite 64-bit, Debian 12) | +| Binary | - | `/usr/bin/MoonLight`, md5 d0bcb409, a piolib build of the PIO work of 2026-11-16 | md5 8ef6e72e, version 7.0.0-dev.1, from `release.yml`'s `build-linux-arm64` job; on 6.18 in place of `/usr/bin/MoonLight`, on 6.12 from its `.deb` | +| Backend | piolib, raspberrypi/utils 4284bd7 | piolib, raspberrypi/utils 4284bd74 (2026-11-12), static | the kernel's `/dev/pio0` ioctls | +| Card | rising clock edge, latch blank 0 | falling clock edge (`clockEdge` 1), latch blank 1, curve CIE 1931, local brightness 255 | falling clock edge (`clockEdge` 1), latch blank 1 | +| Method | `bitDepth` and `pixelClock` set on the Hub75 card and `shown` read | `bitDepth` and `pixelClock` set through `POST /api/control`, `shown` read from `GET /api/modules/Hub75`, three readings per setting of a 5 s window with `shown` sampled once a second; thread CPU from `/proc//task/*/stat` over the same window | as the baseline | +| Content | - | `live`: the layers as found (about 690 main-loop fps); `static`: the layers switched off, so no new frames reach the output | `live` and `static` as the baseline, with the layers as found on each card | +| Throttle | - | `throttled=0x0` before and after | `throttled=0x0` before and after | + +### First light, 2026-11-13 + +The PIO output drove the wall: correct picture on all three lanes, 0 submit errors, encode about 1.28 ms a frame, the integrated output at 169 to 170 fps. The measured refresh of about 169 Hz sits under the computed 203.5 Hz because the DMA feed is the ceiling ([Refresh at 6-bit and 8-bit](#refresh-at-6-bit-and-8-bit)). + +### Refresh at 6-bit and 8-bit + +`shown` on the wall, median of three readings, with the 2026-11-13 reading beside it. Frame time is 1000 / `shown`. Wire time is computed, rows / 2 x bits x (256 + latch blank) words at one word per pixel clock; on 2026-11-13 it was computed with the 256 words alone, about 0.4% shorter. + +| bits | pixel clock | content | `shown` | 2026-11-13 | frame ms | wire ms | frame / wire | Hub75 thread CPU % | +|------|-------------|---------|---------|------------|----------|---------|--------------|--------------------| +| 6 | 5 MHz | live | 101 | 101 (V2) | 9.90 | 9.87 | 1.00 | 14.8 | +| 6 | 10 MHz | live | 170 | 169 (V2) | 5.88 | 4.93 | 1.19 | 28.7 | +| 6 | 11.446 MHz | live | 182 | | 5.49 | 4.31 | 1.27 | 28.1 | +| 6 | 20 MHz | live | 225 | 225 (V2) | 4.44 | 2.47 | 1.80 | 34.6 | +| 8 | 5 MHz | live | 76 | 76 (V8) | 13.16 | 13.16 | 1.00 | 19.0 | +| 8 | 10 MHz | live | 127 | 127 (V8) | 7.87 | 6.58 | 1.20 | 28.7 | +| 8 | 11.446 MHz (the wall's own) | live | 136 | | 7.35 | 5.75 | 1.28 | 30.8 | +| 8 | 20 MHz | live | 170 | 169 (V8) | 5.88 | 3.29 | 1.79 | 38.7 | +| 8 | 11.446 MHz | static | 136 | | 7.35 | 5.75 | 1.28 | 0.4 | +| 8 | 20 MHz | static | 169 | | 5.92 | 3.29 | 1.80 | 0.6 | +| 8 | 11.446 MHz, `Drivers.brightness` 64 | live | 136 | | 7.35 | 5.75 | 1.28 | 30.8 | + +- **The spread is 0 or 1 fps at every setting.** Every 1 Hz sample in a window held one value, except at 6-bit 11.446 MHz, where samples read 181 or 182. +- **The 2026-11-18 baseline equals 2026-11-13 or reads 1 fps higher,** within the counter's 1 fps resolution. +- **The feed is the ceiling above 5 MHz.** Frame / wire is 1.0 at 5 MHz, about 1.2 at 10 MHz and about 1.8 at 20 MHz at both depths. At 20 MHz that is about 44.5 MB/s of 32-bit words (computed: words x 4 x `shown`), the "mid-40s MB/s" of 2026-11-13. The cause is untraced. +- **Refresh is the same whether frames arrive or stop:** `static` reads 136 and 169 against `live`'s 136 and 170 at 11.446 and 20 MHz. The encode on that piolib build's refresh thread left `shown` unchanged on this kernel, which matches a submit that returns once queued from kernel 6.18.39 on ([Kernels](hub75-panels.md#kernels)). +- **Brightness 64 against 255 reads 136 and 136:** the engine dims by lit time within the shift. +- **Hub75 thread CPU** is 0.4 to 0.6% when frames stop, so the submit itself costs a fraction of a percent. With moving content it is 15 to 39% and rises with `shown`: about 2.3 to 2.5 ms a frame at 8-bit and 1.5 to 1.7 ms at 6-bit, derived from one encode per refresh. The thread is identified by inference, since it is re-made on every reopen. +- **Memory:** RSS 28,016 kB with content and 27,664 kB when frames stop; the Hub75 card's `dynamicBytes` is 294,912 B (288 KiB) at 6-bit and 8-bit alike. + +### The kernel-interface backend, 2026-11-20 + +A/B/A' on the wall: A is the baseline's piolib binary (d0bcb409), B the kernel-interface build (8ef6e72e), A' the piolib binary again, in that order on one boot of 6.18, three readings of 5 s per setting. The 6.12 column is B's binary on the 6.12 card, with the same card settings. MoonLight CPU is the whole process; the busiest thread is the highest of its threads. + +| bits | pixel clock | content | `shown` A / B / A' | `shown` B on 6.12 | MoonLight CPU % A / B / A' | busiest thread % A / B / A' | +|--|--|--|--|--|--|--| +| 6 | 5 MHz | live | 101 / 101 / 101 | 101 | 54.6 / 52.7 / 53.9 | 27.6 / 20.9 / 27.0 | +| 6 | 10 MHz | live | 170 / 170 / 170 | 198 | 62.3 / 53.1 / 62.1 | 28.0 / 20.5 / 27.2 | +| 6 | 11.446 MHz | live | 182 / 182 / 182 | | 63.7 / 53.1 / 63.1 | 28.0 / 20.5 / 27.2 | +| 6 | 20 MHz | live | 225 / 227 / 225 | 243 | 69.1 / 53.5 / 68.1 | 28.0 / 20.7 / 27.0 | +| 8 | 5 MHz | live | 76 / 76 / 76 | 75 | 54.8 / 57.7 / 53.8 | 28.2 / 20.5 / 27.2 | +| 8 | 10 MHz | live | 127 / 127 / 127 | 148 | 62.6 / 58.2 / 61.5 | 28.2 / 20.7 / 27.0 | +| 8 | 11.446 MHz | live | 136 / 136 / 136 | | 64.3 / 58.3 / 63.1 | 28.2 / 20.7 / 27.4 | +| 8 | 20 MHz | live | 170 / 169 / 170 | 182 | 69.5 / 58.8 / 68.3 | 28.0 / 20.9 / 26.8 | +| 8 | 11.446 MHz, `Drivers.brightness` 64 | live | 136 / 136 / 136 | 148 (at 10 MHz) | 64.0 / 58.4 / 63.3 | 28.0 / 20.7 / 27.0 | +| 8 | 11.446 MHz | static | 136 / 136 / 136 | | 48.5 / 47.0 / 48.5 | 20.5 / 19.9 / 20.5 | +| 8 | 20 MHz | static | 169 / 169 / 169 | 180 | 53.5 / 47.2 / 53.4 | 25.5 / 19.9 / 25.5 | + +- **The two backends refresh the wall at the same rate on 6.18:** B is within 2 fps of A and A' at every setting. +- **B's threads hold flat across clocks.** In A the second-busiest thread, the refresh that also encodes, rises from 11.6% at 5 MHz to 26% at 20 MHz; in B the busiest holds at 20.5 to 20.9%, and the process uses 53 to 59% at 20 MHz against A's 68 to 70%. +- **Memory:** B's RSS is 224 to 528 kB above A's (26,944 to 27,232 kB against 26,704 to 26,720 kB). +- **On 6.12 the feed falls less far behind the wire above 5 MHz.** Frame / wire at 8-bit is 1.01, 1.03 and 1.67 at 5, 10 and 20 MHz, against 1.00, 1.20 and 1.80 on 6.18. The binary and the Hub75 card are the same; the two SD cards differ in the kernel, the Debian release (12 against 13), the content and `Drivers.brightness` (20 on the 6.12 card), and on both kernels `static` reads within 2 fps of `live` and `Drivers.brightness` 64 reads as the card's own: the rate holds across content and brightness. The kernel is the hypothesis, and the cause is untraced. +- **Reopen:** ten changes of `pixelClock` by 1 kHz, each re-preparing the output in the same process, reach a `shown` rate in a median 2.01 s (1.16 to 2.02) on 6.18 and 1.99 s (1.34 to 2.03) on 6.12. `shown` read 136 fps each time on 6.18, the rate of its 8-bit 11.446 MHz row, and 144 to 149 fps per cycle on 6.12, whose run kept 8 bits at 10 MHz, where its row reads 148. +- **After the service stops, OE reads high (`pinctrl get 18`: `hi`) on both kernels:** the panel is dark. +- **The kernel log on 6.12** holds zero timeout lines before and after the runs, so its timeout paths ([Kernels](hub75-panels.md#kernels)) stay unexercised on this wall. +- **The `.deb` on Raspberry Pi OS** gives its service user `/dev/pio0`'s group (`gpio`) at install. + +### 8-bit color + +`shown` at 8-bit reads 76, 127 and 169 to 170 fps at 5, 10 and 20 MHz, the 6-bit readings scaled by 6/8, as the frame holds 8/6 the words. The wall's 8-bit frame is 65,536 words, 256 KiB. At brightness 48 the 2026-11-13 bench saw steps in a dark ramp (BENCH-V8): below brightness 64 the lowest plane drops out ([8-bit color](hub75-panels.md#8-bit-color)). diff --git a/docs/reference/hardware/hub75-panels.md b/docs/reference/hardware/hub75-panels.md index 14302c78..4be2128b 100644 --- a/docs/reference/hardware/hub75-panels.md +++ b/docs/reference/hardware/hub75-panels.md @@ -1,6 +1,6 @@ # Driving a HUB75 panel -A HUB75 LED panel can be driven straight from the board's pins with the [HUB75 driver](../../moonmodules/light/drivers.md#hub75), or over Ethernet through a receiving card with [Panel Card](../../moonmodules/light/drivers.md#panelcard). Board, panel and settings are below, in that order. +A HUB75 LED panel can be driven straight from the board's pins with the [HUB75 driver](../../moonmodules/light/drivers.md#hub75), or over Ethernet through a receiving card with [Panel Card](../../moonmodules/light/drivers.md#panelcard). Board, panel and settings are below, in that order, and the readings behind the Raspberry Pi 5 figures are in the [HUB75 bench record](hub75-bench.md). ## Which of the two paths @@ -10,7 +10,9 @@ A [MoonHub75](https://moonmodules.org/projects/hardware/#moonhub75-pcb) drives a ## Which board -The chip needs an LCD_CAM or a Parlio block: an S3, a P4 or an S31. The classic ESP32 has neither, and its 13 usable output GPIOs are all a 1/16 port needs, which leaves nothing for a strand, a button or a microphone. +The chip needs an LCD_CAM or a Parlio block, which the S3, the P4 and the S31 carry and the classic ESP32 lacks. Its 13 usable output GPIOs are all a 1/16 port needs, so a strand, a button or a microphone has no pin left. + +A Raspberry Pi 5 drives panels through its RP1 PIO from the 40-pin header instead: [Raspberry Pi 5](#raspberry-pi-5-rp1-pio). Three boards have published pin maps, which the `board` select fills in: @@ -44,3 +46,77 @@ On the bench (2026-10-06, the MoonHub75's panel on LCD_CAM) 4-bit refreshes at 2 If a panel flickers, `refresh` is the measured rate to report. Flicker only in the dark areas, while bright ones hold still, is a refresh rate too low: a dim pixel is lit for one short pulse a refresh, and the eye catches the short pulse first. **A panel takes its own 5 V supply on its power connector.** A lit row draws all its columns at once, so the peak current does not fall with brightness: a 64x64 panel at full red and blue pulls about 2.6 A. A supply that sags under it, such as a controller board's USB, drops the blue and green LEDs first, which need about 3 V where red needs 2, so a color with much red in it shows as red or orange. A 128x64 panel measured about 4 A at full white, and panels differ, so a supply is sized from each panel's rated maximum current times the panel count, and the voltage is checked at the far panel's connector under a white frame. A picture that holds on dark content and breaks up on bright content is a power fault, whatever it looks like. + +## Raspberry Pi 5 (RP1 PIO) + +A Pi 5 drives HUB75 panels from its 40-pin header through one RP1 PIO state machine, which clocks all three lanes in lockstep from one 32-bit word per pixel clock. The engine drives the PIO through the kernel's own interface, `/dev/pio0`, with no library in between, so one program carries everything. + +### Which output + +The HUB75 driver takes its output from the machine: an ESP32 takes the bus output, LCD_CAM or Parlio by chip, and a Pi 5 takes the PIO output. The PIO output stays selected when the PIO is refused, and its status gives the reason. A Pi 4 or earlier shows the Pi card with a refusal in its status. + +The machine comes from the kernel's device tree, `/proc/device-tree/compatible`. A container that masks that file (Docker does by default) falls to the `Model` line of `/proc/cpuinfo`, so a Pi 5 in a container is still a Pi 5; the device tree wins where both can be read. The container also needs `/dev/pio0` passed through, for example `docker run --device /dev/pio0`. + +### Wiring + +The board is the active 3-channel one, wired as hzeller's `regular` mapping (see [attributions](../attributions.md#hzeller)). The wiring is soldered, so the card carries no pin controls. Three lanes of HUB75 data lines fan out from shared address, clock, latch and output-enable lines, and each lane takes up to 32 panels in series. + +| Signal | GPIO | Header pin | +|--------|------|-----------| +| OE (active low) | 18 | 12 | +| CLK | 17 | 11 | +| STB (latch) | 4 | 7 | +| A | 22 | 15 | +| B | 23 | 16 | +| C | 24 | 18 | +| D | 25 | 22 | +| E (1/32 scan) | 15 | 10 | + +Each lane's color lines, as GPIO with the header pin in parentheses. R1, G1 and B1 feed the upper half of the panel, R2, G2 and B2 the lower half. + +| Lane | R1 | G1 | B1 | R2 | G2 | B2 | +|------|----|----|----|----|----|----| +| 1 | 11 (23) | 27 (13) | 7 (26) | 8 (24) | 9 (21) | 10 (19) | +| 2 | 12 (32) | 5 (29) | 6 (31) | 19 (35) | 13 (33) | 20 (38) | +| 3 | 14 (8) | 2 (3) | 3 (5) | 26 (37) | 16 (36) | 21 (40) | + +E carries row address bit 4, so a 1/32-scan panel needs it, on HUB75 pin 4 or 8 depending on the panel; the board has a jumper for it. + +### Geometry + +`rows`, `cols` and `panelsPerLane` are one panel's size and the panels in series on one lane. The layout's lights, cut into whole panels, are the panels, and the lanes driven at once follow, up to the board's three. The defaults are a 256x192 wall: 128x64 panels, 2 to a lane, 3 lanes, stacked to 256x192 at 1/32 scan and 6-bit, clocked at 10 MHz. The scan follows the rows, `rows` / 2, so a 64-row panel scans 1/32 on its own. Only a `rows` value of 16, 32 or 64 opens; any other is refused at open, with the status naming the rows that work. A geometry that does not cable into the lanes is refused with the way out, and a layout of another count, or off plain rows, shows a warning. The Pi card's settings live on the driver, so a saved card keeps them through a boot where the PIO refuses. + +### Pins the kernel may own + +The engine muxes GPIO 2 to 27 to the PIO, and the board uses every one of them. A kernel driver owns some of them when it is enabled, takes them back from the panels, and corrupts the picture. Free them in `/boot/firmware/config.txt` before wiring a panel; the driver cannot see these lines. + +| Pins | Owner when enabled | Free them with | +|------|--------------------|----------------| +| GPIO 2, 3 | I2C1 | `dtparam=i2c_arm=off` | +| GPIO 7 to 11 | SPI0 (lane 1's color pins) | `dtparam=spi=off` | +| GPIO 14, 15 | UART0 (lane 3's R1 and the E line) | `enable_uart=0` | +| GPIO 4 | 1-wire (the strobe) | remove `dtoverlay=w1-gpio` | +| GPIO 18 to 21 | I2S (18 is OE); an I2S microphone is what an audio-reactive install adds | remove `dtparam=i2s=on` | +| GPIO 12, 13, 18, 19 | the PWM overlays: `pwm` (pin 18 by default), `pwm-2chan` (pins 18 and 19 by default) and `audremap-pi5` or `audremap` (pins 12 and 13 by default, `audremap` also 18 and 19) | remove the `dtoverlay=` lines of those overlays | + +### Access to the node + +The engine opens `/dev/pio0` for reading and writing. On the bench Pi the node reads `crw-rw---- root gpio`, so the user MoonLight runs as joins the group that owns it, `gpio` there. The Debian package's install does this for the `moonlight` service user: it reads the group from the node and adds the user to it. A failed open names the node's mode, owner and group, so the status line gives the group the machine uses. A node owned by `root` and group `root` takes a udev rule that gives it a group (`SUBSYSTEM=="*-pio", GROUP="gpio", MODE="0660"`), then a reboot. The package's install skips a node whose group is `root`, so after the rule the service user joins the group by installing the package again, which runs the install step again, or by `sudo usermod -a -G gpio moonlight`, and the service restarts with `sudo systemctl restart moonlight`. + +### Kernels + +The output opens where `/dev/pio0` exists and the kernel serves a PIO. What the frame submit returns depends on the kernel: + +- **6.12 (rpi-6.12.y):** the submit returns when every chunk has reached the state machine. A wait for a free buffer lasts up to 1 second; when it expires the kernel logs "DMA bounce timed out" and ends the copy, so the call returns 0 with the frame cut short and no error, after about 2 seconds in all. The completion wait that follows lasts up to 1 second per chunk and answers a timeout (-ETIMEDOUT) when it expires: the engine counts a failed submit, `shown` falls to 0, the status says the PIO is failing, and the engine retries after a pause. The engine's lowest pixel clock, 50 kHz, keeps one 64 KiB chunk inside that second. +- **6.18.39 and later:** the submit returns once the last chunk is queued and blocks only while all four DMA buffers are busy. A state machine that stops draining blocks the call for good, and the engine's shutdown reports it. +- **6.18.39 up to 6.18.59:** a PIO reopen stalls. The output refuses to open on these kernels and the status gives the reason. 6.18.60 and later serve PIO. + +### Pixel clock and refresh + +The frame is `bitDepth` x scan rows x (lane width + the encoder's hold words) pixel clocks, so one state machine sets the refresh by the clock: `pixelClock` runs from 1 to 40 MHz. A lane of at most 2^(`bitDepth` - 2) words, 16 at 6-bit and 64 at 8-bit, carries hold words so that its lowest plane still lights; a wider one, such as the wall's 256, carries 0. `latchBlank` blanks 0 to 8 of the words before each latch, for a panel that ghosts: the frame keeps its length, and only the lit time shortens. The card quotes the computed wire rate, 203.5 Hz on the default wall at 10 MHz and 6-bit, and `shown` is the measured rate, 169 to 170 fps on the bench on kernel 6.18 and 198 on 6.12. + +The gap is the DMA feed, which falls behind the wire as the clock rises: a frame took 1.2 times its wire time at 10 MHz and 1.8 times at 20 MHz on 6.18 ([bench record](hub75-bench.md#refresh-at-6-bit-and-8-bit)), and about 1.0 and 1.7 times on 6.12 ([the kernel-interface backend](hub75-bench.md#the-kernel-interface-backend-2026-11-20)). When the feed runs behind, the state machine stalls on an empty FIFO inside the frame, and a stall lengthens the word it stops on, which shifts plane weights. A pixel clock above 20 MHz, the highest the bench ran, shows a warning in the status. + +### 8-bit color + +The card offers 2 to 8 planes, starting at 6; 8 is set on the card. A frame at 8-bit is 8/6 the words of 6-bit, and the bench readings scale by 6/8 ([bench record](hub75-bench.md#refresh-at-6-bit-and-8-bit)). A narrow row leads with hold words, which cost refresh: the rule is `hub75HoldWords` in [`Hub75Bus.h`](https://github.com/MoonModules/MoonLight/blob/main/src/platform/Hub75Bus.h), and [hold words](hub75-refresh.md#plane-weights-and-hold-words) shows the effect. The brightness below which the lowest plane drops out is in [`Hub75Encode.h`](https://github.com/MoonModules/MoonLight/blob/main/src/platform/Hub75Encode.h): 64 on the wall's 256-word rows at 8-bit, where the picture reads as 7-bit. diff --git a/mkdocs.yml b/mkdocs.yml index 991aebcd..d4d22533 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -267,6 +267,7 @@ nav: - LED drivers: reference/hardware/led-drivers.md - HUB75 panels: reference/hardware/hub75-panels.md - HUB75 refresh rates: reference/hardware/hub75-refresh.md + - HUB75 bench record: reference/hardware/hub75-bench.md - Receiving cards for LED panels: reference/hardware/panel-cards.md - TV backlight: reference/hardware/tv-backlight.md # Contributors: how it is built, the rules, and the references a change needs. diff --git a/src/light/drivers/DriverBase.h b/src/light/drivers/DriverBase.h index f984224e..b7008977 100644 --- a/src/light/drivers/DriverBase.h +++ b/src/light/drivers/DriverBase.h @@ -172,12 +172,35 @@ class DriverBase : public MoonModule { protected: Layer* layer_ = nullptr; + /// Does an enabled sibling driver already claim `block`? RTTI-free: every driver answers hwBlock(), and one owning no block answers None. + bool siblingClaims(LedHwBlock block) const { + if (block == LedHwBlock::None) return false; + const MoonModule* p = parent(); + if (!p) return false; + for (uint8_t i = 0; i < p->childCount(); i++) { + const MoonModule* sib = p->child(i); + if (sib == this || !sib || !sib->enabled()) continue; + // role() confirms it, so this static_cast needs no RTTI. + if (sib->role() != ModuleRole::Driver) continue; + if (static_cast(sib)->hwBlock() == block) return true; + } + return false; + } + /// The status of a driver that stays idle because a sibling holds its block. + static constexpr const char* kBlockInUse = "peripheral already in use by another driver: pick a different one"; + /// One light of a wiring wider than RGB, for correctToRgb, sized off the hot path by sizeLightScratch. ScratchBuffer lightScratch_{*this}; + /// The status while one light of the wiring has no scratch to correct through. + static constexpr const char* kNoLightMemory = "not enough memory for one light of this fixture"; + /// Whether the wiring is wider than RGB and the scratch for one light of it is missing or too small. + bool lightScratchShort() const MM_NONBLOCKING { + return correction_.outChannels > 3 && lightScratch_.bytes() < correction_.outChannels; + } /// Size lightScratch_ to the wiring, saying so in the status when memory runs out; true when an RGB wiring needs none or the light fits. bool sizeLightScratch() { if (correction_.outChannels <= 3 || lightScratch_.resize(correction_.outChannels)) return true; - setStatus("not enough memory for one light of this fixture", Severity::Error); + setStatus(kNoLightMemory, Severity::Error); return false; } @@ -225,9 +248,15 @@ class DriverBase : public MoonModule { if (wire_) { platform::free(wire_); wire_ = nullptr; wireCap_ = 0; publishHeapBytes(); } } - /// The heap bytes this driver holds; one hook rather than setDynamicBytes at every alloc site, where one omission drifts the readout. + /// The heap bytes this driver holds beside its ScratchBuffers, which count themselves; one hook rather than setDynamicBytes at every alloc site, where one omission drifts the readout. virtual size_t driverHeapBytes() const { return wireCap_; } - void publishHeapBytes() { setDynamicBytes(driverHeapBytes()); } + /// Move the readout by the change in driverHeapBytes() since the last report, so every ScratchBuffer's own count stays in it. A driver reports through this alone, which keeps the total in step. + void publishHeapBytes() { + const size_t now = driverHeapBytes(); + setDynamicBytes(dynamicBytes() - reportedHeapBytes_ + now); + reportedHeapBytes_ = now; + } + size_t reportedHeapBytes_ = 0; ///< what driverHeapBytes() read at the last publish /// The resolved correction: the wiring comes from a named profile by stable id, and the render loop never reads the library. Correction correction_; diff --git a/src/light/drivers/Hub75BusOutput.h b/src/light/drivers/Hub75BusOutput.h index bf1e2850..8c788e58 100644 --- a/src/light/drivers/Hub75BusOutput.h +++ b/src/light/drivers/Hub75BusOutput.h @@ -14,7 +14,7 @@ namespace mm { /// The HUB75 driver's output on the ESP32's parallel bus: it packs the corrected frame into the panel's bit planes in the platform's buffer, which LCD_CAM or Parlio clocks out. /// /// It owns the board table and the measured refresh text; the fourteen pins, the scan rate, the bit depth and the clock edge live on the driver, and the output binds them into the driver's card. -class Hub75BusOutput : public Hub75Output { +class Hub75BusOutput final : public Hub75Output { public: /// The board select and the fourteen pin controls, above the peripheral select. void addWiringControls(ControlList& controls) override { @@ -40,7 +40,7 @@ class Hub75BusOutput : public Hub75Output { /// The geometry, the clock edge and the measured refresh, below the peripheral select. void addControls(ControlList& controls) override { controls.addSelect("scanRate", owner_->scanSel, Hub75Settings::kScanOptions, Hub75Settings::kScanCount); - controls.addControl("bitDepth", owner_->bitDepth, 2, kHub75PortMaxBitDepth); + controls.addControl("bitDepth", owner_->bitDepth, depthRange().min, depthRange().max); // The one knob a chip family changes. WLED exposes the same flag as its bus "reversed" box. controls.addSelect("clockEdge", owner_->clockEdgeSel, Hub75Settings::kEdgeOptions, Hub75Settings::kEdgeCount); @@ -67,6 +67,9 @@ class Hub75BusOutput : public Hub75Output { return false; } + /// The planes the ESP32 port takes, which the control bounds. + DepthRange depthRange() const override { return DepthRange{2, kHub75PortMaxBitDepth}; } + /// The bytes the bit planes take for this layout at the selected scan and depth; 0 for an unusable layout. size_t frameBytes(uint16_t width, uint16_t height) const override { const Hub75Geometry probe = geometry(width, height); @@ -121,7 +124,10 @@ class Hub75BusOutput : public Hub75Output { } /// The geometry and the backend, as open() formatted them. - const char* describe() const override { return status_; } + const char* describe() const MM_NONBLOCKING override { return status_; } + + /// The bus raises each refusal as an error at open, so a running bus has no warning to give. + const char* warning() const MM_NONBLOCKING override { return nullptr; } /// The layout's box, one light per panel pixel. size_t lights() const MM_NONBLOCKING override { @@ -131,7 +137,7 @@ class Hub75BusOutput : public Hub75Output { /// Pack the frame into the bit planes, brightness being the planes' lit time. void show(const uint8_t* rgb, uint8_t brightness) MM_NONBLOCKING override { geo_.brightness = brightness; - // No double buffer: a one-pass tear beats a second 256 KB frame, invisible at 300+ Hz. + // One buffer: a one-pass tear beats a second 256 KB frame, invisible at 300+ Hz. hub75Encode(rgb, platform::hub75Buffer(hub_), geo_); // a null buffer, as with no bus open, makes hub75Encode return 0 } @@ -146,7 +152,7 @@ class Hub75BusOutput : public Hub75Output { /// Stop the scan and release the panel's peripheral. void close() override { platform::hub75Deinit(hub_); } - /// The block the selected backend drives: WHICH block, not a guess, since claiming the wrong one frees a live block and holds a free one. + /// The block the selected backend drives, as the select names it, since claiming the wrong one frees a live block and holds a free one. LedHwBlock hwBlock() const override { return owner_->selectedBackend() == platform::Hub75Backend::Parlio ? LedHwBlock::Parlio : LedHwBlock::LcdCam; @@ -214,7 +220,7 @@ class Hub75BusOutput : public Hub75Output { const char* current = (boardSel < boardOptionCount_) ? boardOptions_[boardSel] : nullptr; boardOptionCount_ = 0; for (uint8_t i = 0; i < kBoardCount; i++) { - // A host is none of the three chips and offers every row; silicon sees its own. + // A host offers every row; silicon filters to its own chip's. constexpr bool anyKnownChip = platform::isEsp32S3 || platform::isEsp32P4 || platform::isEsp32S31; if constexpr (anyKnownChip) { @@ -224,7 +230,7 @@ class Hub75BusOutput : public Hub75Output { boardIndex_[boardOptionCount_] = i; boardOptionCount_++; } - // Re-point by LABEL, so a filtered list cannot silently select a different board. + // Re-point by LABEL, so a filtered list keeps the picked board while it is offered, and falls to the first row when it is not. uint8_t sel = 0; if (current) { for (uint8_t k = 0; k < boardOptionCount_; k++) { @@ -292,7 +298,7 @@ class Hub75BusOutput : public Hub75Output { const char* boardOptions_[kBoardCount] = {}; uint8_t boardIndex_[kBoardCount] = {}; uint8_t boardOptionCount_ = 0; - bool prefilled_ = false; // the board map is written once, not on every re-render + bool prefilled_ = false; // the board map is written once, at the first card /// Convert a Pin control's value to the platform seam's pin type; -1 for unset becomes 0xFFFF, since a P4 GPIO number can exceed int8_t's range. static uint16_t toPin(int8_t p) { @@ -301,7 +307,7 @@ class Hub75BusOutput : public Hub75Output { platform::Hub75Handle hub_{}; Hub75Geometry geo_{}; - uint16_t lastRefresh_ = 0xFFFF; // not 0: the first real 0 must still publish + uint16_t lastRefresh_ = 0xFFFF; // 0xFFFF, so the first real 0 still publishes char status_[64] = {}; char refreshStr_[16] = {}; }; diff --git a/src/light/drivers/Hub75Canvas.h b/src/light/drivers/Hub75Canvas.h new file mode 100644 index 00000000..98aabb57 --- /dev/null +++ b/src/light/drivers/Hub75Canvas.h @@ -0,0 +1,198 @@ +/// Where a light sits on a HUB75 lane canvas, the ways to cable a set of panels with the refresh each predicts, and the plain-rows walk that tells whether a layout's lights run panel by panel in plain rows. +/// +/// @technical +/// +/// ## Predicted refresh +/// +/// The defaults are the page's worked example, 130 ns for the LSB, 60.4 ns a pixel and 0.5 us to latch; a driver with its own pixel clock names its shift and its latch instead, so its arrangements quote its own rate. The arithmetic runs in tenths of a nanosecond, so the page's 60.4 ns a pixel stays an integer. +/// +/// Where the frame is the in-tree encoder's (`encoderHold`), a narrow row leads with hold words (Hub75Geometry::holdWords), which the shift counts: the pass, not the row, is what the wire clocks. +/// +/// The hold is 0 where the frame is not the encoder's or the row needs no hold. A PanelSpec row is one encoder group, so the hold adds whole, and `pairs` counts the row's shift words (laneWidth * pairs) for the hold's trigger. + +#pragma once + +#include "platform/Hub75Bus.h" // hub75HoldWords: the hold words a narrow encoder row leads with +#include "platform/Hub75Pio.h" // kHub75PanelsPerLaneMax: the engine's limit, which the card takes + +#include +#include +#include + +namespace mm { + +/// A cell of a HUB75 lane canvas, the raster an encoder reads. +struct CanvasPos { + uint16_t x = 0; ///< the column + uint16_t y = 0; ///< the row +}; + +/// Where light `i` of a layout running panel by panel, plain rows inside each, lands: panel `k` is place `k % panelsPerLane` of lane `k / panelsPerLane`, the lanes stacked. +inline CanvasPos laneCanvasPos(uint32_t i, uint16_t rows, uint16_t cols, uint16_t panelsPerLane) { + const uint32_t perPanel = static_cast(rows) * cols; + if (perPanel == 0 || panelsPerLane == 0) return {}; + const uint32_t panel = i / perPanel; + const uint32_t inPanel = i % perPanel; + CanvasPos p; + p.x = static_cast((panel % panelsPerLane) * cols + inPanel % cols); + p.y = static_cast((panel / panelsPerLane) * rows + inPanel / cols); + return p; +} + +/// One panel and how it is clocked: what a refresh rate and an arrangement depend on. +struct PanelSpec { + uint16_t rows = 0; ///< the panel's rows + uint16_t cols = 0; ///< the panel's columns + uint16_t scanRows = 0; ///< row addresses, 32 for a 64-row panel at 1/32 scan + uint8_t bits = 8; ///< bit planes + uint16_t lsbNs = 130; ///< the shortest plane's lit time: the page's 130 ns, or 0 where no lit time outlasts a row's shift + uint16_t shiftTenthsPerPx = 604; ///< the shift per pixel in tenths of a nanosecond: the page's 60.4 ns, or a pixel clock's own (1000 at 10 MHz) + uint16_t latchTenthsNs = 5000; ///< the latch per row in tenths of a nanosecond: the page's 0.5 us, or 0 where the latch rides the last pixel clock + uint8_t pairs = 1; ///< color passes per address step the encoder shifts together (rowsPerScan / 2): 1 where a row is one shift; the hold's trigger counts laneWidth * pairs + bool encoderHold = false; ///< the frame is the in-tree encoder's, whose hold words stretch a narrow row, and this output clocks them as shift: the rate counts them +}; + +/// A `laneWidth` lane clocked as `panel` says: its predicted refresh in Hz by docs/reference/hardware/hub75-refresh.md, per plane the longer of one row's shift and its lit time, times the scan rows (@xref{predicted-refresh|predicted refresh}). +inline uint16_t hub75PredictedHz(uint32_t laneWidth, const PanelSpec& panel) { + if (laneWidth == 0 || panel.scanRows == 0 || panel.bits == 0 || panel.bits > 16) return 0; + // The hold words per row group in tenths of a nanosecond, added whole to the shift (@xref{predicted-refresh|predicted refresh}). + const uint64_t holdTenths = panel.encoderHold + ? static_cast(hub75HoldWords(static_cast(laneWidth) * (panel.pairs ? panel.pairs : 1), panel.bits)) * panel.shiftTenthsPerPx + : 0; + const uint64_t shift = static_cast(laneWidth) * panel.shiftTenthsPerPx + panel.latchTenthsNs + holdTenths; + uint64_t frame = 0; + for (uint8_t i = 0; i < panel.bits; i++) { + const uint64_t on = (static_cast(panel.lsbNs) * 10) << i; // each plane is lit twice as long as the one before + frame += panel.scanRows * (on > shift ? on : shift); + } + frame = std::max(frame, 1); // a spec with no shift, latch or lit time has a frame of no length, which saturates the rate + const uint64_t hz = (20000000000ull + frame) / (2 * frame); // 1e10 / frame, rounded to the nearest + return hz >= 65535 ? 65535 : static_cast(hz); +} + +/// The most panels in series on one lane a card takes, so no arrangement offers more. +constexpr uint16_t kPanelsPerLaneMax = platform::kHub75PanelsPerLaneMax; + +/// One way to cable a set of panels: `panelsPerLane` panels in series on each of `parallel` lanes. +struct Arrangement { + uint16_t panelsPerLane = 0; ///< panels in series on each lane + uint16_t parallel = 0; ///< lanes, one strip each + uint32_t width = 0; ///< the canvas's width + uint32_t height = 0; ///< the canvas's height + uint16_t hz = 0; ///< the predicted refresh +}; + +/// The arrangement of `panelsPerLane` panels on each of `parallel` lanes, with its canvas and rate. +inline Arrangement makeArrangement(uint16_t panelsPerLane, uint16_t parallel, const PanelSpec& panel) { + Arrangement a; + a.panelsPerLane = panelsPerLane; + a.parallel = parallel; + a.width = static_cast(panel.cols) * panelsPerLane; + a.height = static_cast(panel.rows) * parallel; + a.hz = hub75PredictedHz(a.width, panel); + return a; +} + +/// Every arrangement using all `panels` on at most `maxLanes` lanes and kPanelsPerLaneMax panels a lane, most lanes first since parallel lanes shift together; the count. +inline size_t panelArrangements(uint32_t panels, const PanelSpec& panel, uint8_t maxLanes, Arrangement* out, size_t cap) { + if (!out || panels == 0) return 0; + size_t n = 0; + for (uint32_t parallel = maxLanes; parallel >= 1 && n < cap; parallel--) { + if (panels % parallel != 0 || panels / parallel > kPanelsPerLaneMax) continue; + out[n++] = makeArrangement(static_cast(panels / parallel), static_cast(parallel), panel); + } + return n; +} + +/// What keeps the lanes already built: fewer panels with the rest spare, or more panels up to the next full lane. A zero `panelsPerLane` means none fits. +struct KeepLanes { + Arrangement use; ///< whole lanes of the panels there are, at most the board's lanes + uint32_t spare = 0; ///< the panels `use` leaves over + Arrangement add; ///< the next full set of lanes + uint32_t added = 0; ///< the panels `add` needs beyond those there are +}; + +/// The two ways to keep lanes of `panelsPerLane` panels on at most `maxLanes` lanes: fewer panels, or more. +inline KeepLanes keepLanes(uint32_t panels, const PanelSpec& panel, uint16_t panelsPerLane, uint8_t maxLanes) { + KeepLanes k; + if (panelsPerLane == 0) return k; + // Whole lanes only, and no more of them than the board has lanes for: the rest of the panels stay spare. + const uint32_t wholeLanes = panels / panelsPerLane; + const uint32_t fewer = (wholeLanes < maxLanes ? wholeLanes : maxLanes) * panelsPerLane; + if (fewer > 0) { // a whole number of lanes, capped at the board's lanes above + k.use = makeArrangement(panelsPerLane, static_cast(fewer / panelsPerLane), panel); + k.spare = panels - fewer; + } + const uint32_t more = ((panels + panelsPerLane - 1) / panelsPerLane) * panelsPerLane; + if (more != panels && more / panelsPerLane <= maxLanes) { + k.add = makeArrangement(panelsPerLane, static_cast(more / panelsPerLane), panel); + k.added = more - panels; + } + return k; +} + +/// Whether a layout's lights, cut in index order into runs of one panel, walk each panel in plain rows, in any of its orientations. +/// +/// Every run lies on a grid of unit steps, along a row then one step to the next row; a raster across several panels, or a snaked panel, breaks it. +/// +/// Fed one light at a time in index order, as a layout emits them, so it holds no table. +class PanelWalk { +public: + /// The answer while no panel breaks the rule. + static constexpr uint32_t kNone = 0xFFFFFFFFu; + + /// A walk for panels of `rows` by `cols` lights. + PanelWalk(uint16_t rows, uint16_t cols) : cols_(cols), perPanel_(static_cast(rows) * cols) {} + + /// The light at index `i` sits at (x, y): a panel's first light is its origin, its second and the first of its second row its steps, and every other must sit where they put it. + void light(uint32_t i, int32_t x, int32_t y) { + if (cols_ < 2 || perPanel_ == 0 || offPanel_ != kNone) return; + const uint32_t panel = i / perPanel_, j = i % perPanel_; + if (j == 0) return start(panel, x, y); + if (panel != panel_) return; // a panel whose first light is missing has no origin to measure from + if (!fits(j, x - ox_, y - oy_)) offPanel_ = panel; + } + + /// The first panel, counted from 0, whose lights leave plain rows, or kNone. + uint32_t firstOffPanel() const { return offPanel_; } + +private: + /// A panel's first light: its origin, and both steps still to learn. + void start(uint32_t panel, int32_t x, int32_t y) { + panel_ = panel; + ox_ = x; + oy_ = y; + along_ = down_ = false; + } + + /// Whether the held panel's light `j`, at (dx, dy) from its origin, keeps plain rows; light 1 sets the step along, light `cols_` the step down. + bool fits(uint32_t j, int32_t dx, int32_t dy) { + if (j == 1) { + ux_ = dx; + uy_ = dy; + return along_ = unitStep(dx, dy); + } + if (j == cols_) { + vx_ = dx; + vy_ = dy; + return down_ = unitStep(dx, dy) && dx * ux_ + dy * uy_ == 0; + } + const int32_t col = static_cast(j % cols_), row = static_cast(j / cols_); + if (!along_ || (row > 0 && !down_)) return true; + return dx == col * ux_ + row * vx_ && dy == col * uy_ + row * vy_; + } + + /// One step along an axis, either way. + static bool unitStep(int32_t dx, int32_t dy) { return (dx == 0) != (dy == 0) && dx * dx + dy * dy == 1; } + + uint16_t cols_; + uint32_t perPanel_; + uint32_t offPanel_ = kNone; + uint32_t panel_ = kNone; ///< the panel whose origin is held + int32_t ox_ = 0, oy_ = 0; ///< that panel's first light + int32_t ux_ = 0, uy_ = 0; ///< the step along its rows + int32_t vx_ = 0, vy_ = 0; ///< the step down to its next row + bool along_ = false, down_ = false; +}; + +} // namespace mm diff --git a/src/light/drivers/Hub75Driver.h b/src/light/drivers/Hub75Driver.h index 380ffb52..b24a27e5 100644 --- a/src/light/drivers/Hub75Driver.h +++ b/src/light/drivers/Hub75Driver.h @@ -1,15 +1,31 @@ #pragma once #include "light/drivers/DriverBase.h" -#include "light/drivers/Hub75BusOutput.h" // the output every backend this driver offers takes +#include "light/drivers/Hub75BusOutput.h" // the output that drives the LCD_CAM and Parlio backends +#include "light/drivers/Hub75Fit.h" // kGeometryMessageMax: the longest status the Pi output writes #include "light/drivers/Hub75Output.h" // the strategy that takes the corrected frame to the panel +#include "light/drivers/Hub75PioOutput.h" // the output that drives the Pi 5's PIO backend #include "light/layers/Layer.h" +#include "platform/machine.h" // which machine this is: the output follows it #include "platform/platform.h" +#include #include +#include namespace mm { +/// What the driver holds in the PIO output's place where no Pi 5 can have one: an empty type, so an ESP32 image carries none of it. +struct NoPioOutput { + /// Takes the driver as the PIO output does, and discards it. + explicit NoPioOutput(MoonModule& /*owner*/) {} +}; + +/// `output` as a Hub75Output: the PIO output itself. +inline Hub75Output* asHub75Output(Hub75PioOutput& output) { return &output; } +/// Where no PIO output exists there is no output to give. +inline Hub75Output* asHub75Output(NoPioOutput& /*output*/) { return nullptr; } + /// Drives HUB75 LED panels straight from the board's own pins, with no receiving card in between. /// @card Hub75Driver.png /// @@ -25,31 +41,50 @@ namespace mm { /// /// @technical /// -/// **Output.** The driver corrects the layout into one RGB frame in light order and hands it to its Hub75Output, the bus output, which owns the board table, binds the pins and builds the panel's geometry. The output drives either peripheral, LCD_CAM or Parlio. +/// **One driver per peripheral.** A second driver that asks for LCD_CAM, Parlio or a Pi's header while another holds it stays idle with a status naming why, whichever of the two prepares first keeping it. This applies to the ESP32 too: a HUB75 driver yields to a strip driver holding LCD_CAM, and the strip driver to it. +/// +/// **Outputs.** The driver corrects the layout into one RGB frame in light order for a Hub75Output. The bus output reads a row-major raster; the PIO output's canvas is a stack of lanes of panels, so it places its lights first (Hub75Canvas.h) and hands the frame to the seam. Both are held by value, so the driver's size and memory readout count them; the PIO output is empty where no Pi 5 runs. /// -/// **Continuous output.** A HUB75 panel is lit only while clocked, so the platform arms one scan and re-sends the buffer forever. The bus output writes the next frame into it between scans, so tick() transmits nothing. The wire format is Hub75Encode.h. +/// **Continuous output.** A HUB75 panel is lit only while clocked, so on an ESP32 the platform re-sends one buffer forever and the bus output writes the next frame into it between scans, while tick() starts no transfer; the PIO output hands each frame to the seam, which hands it to the engine's threads. /// /// **Brightness.** Binary coded modulation lights plane `p` for 2^p time units. Each plane is stored once, not 2^p times: `Hub75Geometry::frameSlots()` has the sizes. /// +/// **The output follows the machine** (platform/machine.h), a case tree with one case per kind and no default. An ESP32 takes the bus output and the backends it offers, LCD_CAM and Parlio per chip. A Pi 5 takes the PIO output, which stays selected when the PIO is refused and shows the reason as its status. +/// +/// An earlier Pi shows the Pi card and a refusal. Any other host takes the bus output and its refusal, or the test port's backends. +/// +/// **The Pi's settings** (rows, columns and panels per lane, the pixel clock and the latch blank) live on the driver, bound on every host and shown only on the Pi card, so a saved card keeps them, the 8-bit depth included, through a boot where the PIO refuses. +/// +/// **Swapping outputs.** A machine that changes, which a test makes, quiesces the render worker, which reads the output in tick(), closes the running output and points the driver at the other, moving the depth into its range. The change reaches prepare() as a whole-tree re-prepare, the default prepare scope, which joins the encode worker before the output closes. +/// /// **Pins.** The first definition fills them from the chip's first board; the members stay -1, since a blind guess lands on octal PSRAM, USB, UART0 or a strapping pin. WLED's pin array ends `...LAT,OE,CLK`, so a map transcribed as `...CLK,LAT,OE` swaps three lines silently. class Hub75Driver : public DriverBase, public Hub75Settings { public: - /// The silicon block that drives the panel, LCD_CAM or Parlio, where the chip has both. + /// The silicon block that drives the panel: LCD_CAM, Parlio or a Pi 5's PIO. /// @guide A P4 has one LCD_CAM and one Parlio, so a board already driving WS2812 strips from one needs the panel on the other. Only you know which way round. uint8_t peripheralSel_ = 0; - /// Bind the bus output to this driver, which it reads its settings through. - Hub75Driver() { output_->attach(this); } + /// Bind both outputs to this driver, which they read their settings through. + Hub75Driver() : pioOutput_(*this) { + busOutput_.attach(this); + if (Hub75Output* pio = asHub75Output(pioOutput_)) pio->attach(this); + } + + /// Test-only: the output the driver calls through, which a test reads, or replaces with a counting double before the card is defined; a swap here skips selectOutput()'s quiesce and clamp, and defineControls() reverts it. + Hub75Output*& outputForTest() { return output_; } /// The backend the `peripheral` select names, for the output that drives it. platform::Hub75Backend selectedBackend() const override { return backendIndex_[peripheralSel_ < backendOptionCount_ ? peripheralSel_ : 0]; } + /// The layer this driver reads its layout from, which the Pi output cuts into panels. + Layer* drivenLayer() const override { return layer(); } + /// A panel shows a level only as lit time, so brightness shortens the planes' windows rather than scaling values. bool dimsByTime() const MM_NONBLOCKING override { return true; } - /// The peripheral block this driver holds while the bus is up, so a failed init claims nothing; the sibling claim guard reads it. + /// The peripheral block this driver holds while the panel runs, so a block is claimed only by an init that succeeded; the sibling claim guard reads it. LedHwBlock hwBlock() const override { return running_ ? output_->hwBlock() : LedHwBlock::None; } @@ -60,9 +95,11 @@ class Hub75Driver : public DriverBase, public Hub75Settings { /// No window: the panels open at the layer's full size and take its lights in one pass. bool hasWindowControls() const override { return false; } - /// Publish the output's wiring, the peripheral select, then the output's own controls. + /// Publish the Pi's panel settings where a Pi can run, the output's wiring, the peripheral select, then the output's own controls, the output being the one the select names. void defineDriverControls() override { buildBackendOptions(); + selectOutput(); + if constexpr (platform::hasHub75Pio) addPanelControls(); output_->addWiringControls(controls_); controls_.addSelect("peripheral", peripheralSel_, backendOptions_, backendOptionCount_); output_->addControls(controls_); @@ -80,26 +117,38 @@ class Hub75Driver : public DriverBase, public Hub75Settings { return std::strcmp(name, "peripheral") == 0 || output_->affectsPrepare(name); } - /// Stop the scan, release the panel's peripheral, and free the correction scratch. + /// Stop the scan, release the panel's peripheral, and free the correction scratch; a close the kernel left unfinished leaves its reason as the status. void release() override { stopScan(); DriverBase::release(); + if (const char* why = output_->warning()) setStatus(why, Severity::Warning); } - /// Open the output, then size the correction scratch to its box. + /// Refuse a block a sibling holds, open the output, then size the correction scratch to its box. void prepare() override { stopScan(); // a reinit keeps the correction scratch, which release() frees if (!layer_) { setStatus("no layer", Severity::Warning); return; } + if (const char* why = machineRefusal()) { + setStatus(why, Severity::Error); + return; + } + // One block per peripheral, so a sibling holding it means idle with a status rather than fight, the first to prepare keeping it. + if (siblingClaims(output_->hwBlock())) { + setConfigErr(kBlockInUse); + return; + } if (const char* why = output_->open(static_cast(layer_->physicalWidth()), static_cast(layer_->physicalHeight()))) { setStatus(why, Severity::Error); return; } + // The output's box is fixed while it runs, so it is read here once and tick() reuses it. + lights_ = output_->lights(); // One whole frame of packed RGB: the output needs the frame, not one light at a time. - ensureWire(output_->lights() * 3); + ensureWire(lights_ * 3); if (!wire_) { setStatus("not enough memory for the correction buffer", Severity::Error); output_->close(); @@ -111,7 +160,7 @@ class Hub75Driver : public DriverBase, public Hub75Settings { } running_ = true; - setStatus(output_->describe(), Severity::Status); + showStatus(); // a rebuild before this prepare may have left the gains waiting for tables, which the status says too } /// Correct the frame into one RGB frame and hand it to the output. @@ -120,7 +169,7 @@ class Hub75Driver : public DriverBase, public Hub75Settings { const uint8_t srcCh = sourceBuffer_->channelsPerLight(); const uint8_t outCh = correction_.outChannels; - const nrOfLightsType lights = static_cast(output_->lights()); + const nrOfLightsType lights = static_cast(lights_); if (srcCh == 0 || outCh < 3 || lights == 0) return; if (!wire_ || wireCap_ < static_cast(lights) * 3) return; // not ready // A layout with fewer lights than the panel's box leaves the rest of the panel dark. @@ -137,55 +186,136 @@ class Hub75Driver : public DriverBase, public Hub75Settings { /// Resize the correction scratch when the wiring changes, once core 1 has finished the frame it writes through it. void onCorrectionChanged() override { if (!running_) return; - const size_t frameBytes = output_->lights() * 3; - if (wireCap_ >= frameBytes && !outChannelsChanged()) return; // a brightness change moves no buffer - if (parent()) parent()->quiesce(); // a resize frees the block the encode worker may be writing - ensureWire(frameBytes); - sizeLightScratch(); + const size_t frameBytes = lights_ * 3; + const bool rewired = outChannelsChanged(); + // A brightness change moves no buffer; a light scratch still missing retries at the same width. + if (wireCap_ < frameBytes || rewired || lightScratchShort()) { + if (parent()) parent()->quiesce(); // a resize frees the block the encode worker may be writing + ensureWire(frameBytes); + sizeLightScratch(); + } + showStatus(); // the rebuild's verdicts take their place in the order } - /// Let the output publish its measured readouts; MM_NONBLOCKING stays, or the base's contract widens and the compiler refuses. + /// Let the output publish its measured readouts, then show the status its warning and the base's verdicts decide; MM_NONBLOCKING stays, or the base's contract widens and the compiler refuses. void tick1s() MM_NONBLOCKING override { - if (running_) output_->tick1s(); + if (!running_) return; + output_->tick1s(); + showStatus(); } private: + /// The one status the running panel shows, the same one every call, in this order: a missing light scratch, the output's warning in full, the gains waiting for tables, then the output's describe() while all is healthy. + void showStatus() MM_NONBLOCKING { + if (lightScratchShort()) setStatus(kNoLightMemory, Severity::Error); + else if (const char* warn = output_->warning()) setStatus(warn, Severity::Warning); + else if (gainsDropped_) setStatus(kNoGainMemory, Severity::Warning); + else setStatus(output_->describe(), Severity::Status); + } + /// Stop the scan and release the panel's peripheral, the reinit both release() and prepare() begin with. void stopScan() { output_->close(); running_ = false; } - /// Offer the backends this silicon has and that can carry this geometry, re-pointing by label so a dropped backend cannot select another. + /// Why this machine refuses the HUB75 output, or null; an earlier Pi's reason names the Pi 5's PIO. One case per machine. + static const char* machineRefusal() { + switch (platform::machine()) { + case platform::Machine::PiGpio: return "HUB75 in this build needs a Pi 5's PIO"; + case platform::Machine::Esp32: return nullptr; + case platform::Machine::Pi5: return nullptr; // the PIO refuses for itself, with its reason + case platform::Machine::Other: return nullptr; // the bus output refuses for itself + } + return nullptr; + } + + /// The output a backend drives: the Pi's has its own, and LCD_CAM and Parlio share the bus output. + Hub75Output* outputFor(platform::Hub75Backend backend) { + if (backend == platform::Hub75Backend::Pio) { + if (Hub75Output* pio = asHub75Output(pioOutput_)) return pio; + } + return &busOutput_; + } + + /// Point the driver at the output the selected backend drives, when that is not the one it holds; LCD_CAM and Parlio share the bus output, which keeps its state across them. + void selectOutput() { + Hub75Output* want = outputFor(selectedBackend()); + if (want == output_) return; + MoonModule::notifyQuiesceRender(); // the encode worker reads output_ in tick() + stopScan(); + output_ = want; + // The depth is one setting for both outputs, so it moves into the new output's range. + const DepthRange range = output_->depthRange(); + bitDepth = std::clamp(bitDepth, range.min, range.max); + } + + /// Add the Pi's panel and clock settings, hidden while another output runs: they stay bound, so a saved card keeps them. + void addPanelControls() { + const bool shown = output_->hwBlock() == LedHwBlock::PiHeader; + controls_.addControl("rows", panelRows, 16, 64); // 16 rows scan at 1/8, the fewest the engine drives; 64 is the panel the board is built for + controls_.setHidden(controls_.count() - 1, !shown); + controls_.addControl("cols", panelCols, 16, 512); // 16 is the narrowest panel; 512 by kPanelsPerLaneMax keeps the canvas width, 16,384, inside 16 bits + controls_.setHidden(controls_.count() - 1, !shown); + controls_.addControl("panelsPerLane", panelsPerLane, 1, kPanelsPerLaneMax); + controls_.setHidden(controls_.count() - 1, !shown); + controls_.addControl("pixelClock", pixelClockKhz, 1000, 40000); // 1 to 40 MHz: below 1 MHz the wall crawls, above 40 the divider bottoms out + controls_.setHidden(controls_.count() - 1, !shown); + controls_.addControl("latchBlank", latchBlankWords, 0, 8); // extra dark words before each latch, for a panel that ghosts + controls_.setHidden(controls_.count() - 1, !shown); + } + + /// Offer the backends the machine has, one case per machine: re-pointing by label, so a dropped backend cannot select another. void buildBackendOptions() { const char* current = (peripheralSel_ < backendOptionCount_) ? backendOptions_[peripheralSel_] : nullptr; + backendOptionCount_ = 0; + switch (platform::machine()) { + case platform::Machine::Pi5: // the PIO is offered whether or not it opens, so a refused boot keeps its card + offer(platform::Hub75Backend::Pio); + break; + case platform::Machine::PiGpio: // no output: the Pi card, labeled as none + backendOptions_[0] = "(none)"; + backendIndex_[0] = platform::Hub75Backend::Pio; + backendOptionCount_ = 1; + break; + case platform::Machine::Esp32: + case platform::Machine::Other: + offerBus(); + break; + } + uint8_t sel = 0; + if (current) { + for (uint8_t k = 0; k < backendOptionCount_; k++) { + if (std::strcmp(backendOptions_[k], current) == 0) { sel = k; break; } + } + } + peripheralSel_ = sel; + } + + /// Add `backend` to the offer under its label. + void offer(platform::Hub75Backend backend) { + backendOptions_[backendOptionCount_] = platform::hub75BackendLabel(backend); + backendIndex_[backendOptionCount_] = backend; + backendOptionCount_++; + } + + /// Offer the bus backends this silicon has and that can carry this geometry, or "(none)" when there are none (a host, a classic ESP32). + void offerBus() { // Zero while the layer is unknown, which asks only whether the silicon exists. const size_t bytes = layer_ ? output_->frameBytes(static_cast(layer_->physicalWidth()), static_cast(layer_->physicalHeight())) : 0; - - backendOptionCount_ = 0; for (uint8_t i = 0; i < kBackendCount; i++) { const auto b = static_cast(i); - if (!platform::hub75BackendAvailable(b, bytes)) continue; - backendOptions_[backendOptionCount_] = platform::hub75BackendLabel(b); - backendIndex_[backendOptionCount_] = b; - backendOptionCount_++; + if (platform::hub75BackendAvailable(b, bytes)) offer(b); } - if (backendOptionCount_ == 0) { // no usable backend (host, classic ESP32) + if (backendOptionCount_ == 0) { backendOptions_[0] = "(none)"; backendIndex_[0] = platform::Hub75Backend::LcdCam; backendOptionCount_ = 1; } - uint8_t sel = 0; - if (current) { - for (uint8_t k = 0; k < backendOptionCount_; k++) { - if (std::strcmp(backendOptions_[k], current) == 0) { sel = k; break; } - } - } - peripheralSel_ = sel; } /// The output's lines for the pin map, since their hidden controls read as free there. @@ -193,15 +323,17 @@ class Hub75Driver : public DriverBase, public Hub75Settings { return output_->fixedPins(out, max); } - static constexpr uint8_t kBackendCount = 2; + static constexpr uint8_t kBackendCount = 2; // the bus backends, LCD_CAM and Parlio const char* backendOptions_[kBackendCount + 1] = {}; platform::Hub75Backend backendIndex_[kBackendCount + 1] = {}; uint8_t backendOptionCount_ = 0; - /// The bus output, held by value so the driver's size and memory readout count it. + /// The two outputs, held by value so the driver's size and memory readout count them; the PIO output is an empty type where `hasHub75Pio` is false. Hub75BusOutput busOutput_; + std::conditional_t pioOutput_; Hub75Output* output_ = &busOutput_; // the strategy every call goes through Buffer* sourceBuffer_ = nullptr; + size_t lights_ = 0; ///< the output's lights() as prepare() read it, the length of the frame tick() hands over bool running_ = false; }; diff --git a/src/light/drivers/Hub75Fit.h b/src/light/drivers/Hub75Fit.h new file mode 100644 index 00000000..ec3a7ecb --- /dev/null +++ b/src/light/drivers/Hub75Fit.h @@ -0,0 +1,124 @@ +#pragma once + +#include "light/drivers/Hub75Canvas.h" + +#include +#include +#include +#include + +namespace mm { + +/// Whether a layout's panels cable into lanes of the card's `panelsPerLane` on a board that drives `maxLanes` lanes. +enum class GeometryFit : uint8_t { Ok, Empty, Indivisible, TooManyLanes }; + +/// How `panels` cable into lanes of `panelsPerLane` on `maxLanes` lanes: none, unevenly, past the lanes, or fine. +inline GeometryFit checkGeometry(uint32_t panels, uint16_t panelsPerLane, uint8_t maxLanes) { + if (panels == 0 || panelsPerLane == 0) return GeometryFit::Empty; + if (panels % panelsPerLane != 0) return GeometryFit::Indivisible; + if (panels / panelsPerLane > maxLanes) return GeometryFit::TooManyLanes; + return GeometryFit::Ok; +} + +/// A status buffer this size holds every `geometryMessage` whole for a board of six lanes at most. +constexpr size_t kGeometryMessageMax = 512; + +/// A card's geometry as the messages need it: one panel, the panels per lane, the lanes the board has, and the board's name. +struct CardGeometry { + PanelSpec panel; ///< one panel and how it is clocked + uint16_t panelsPerLane = 1; ///< the card's `panelsPerLane` + uint8_t maxLanes = 1; ///< the lanes the board drives + const char* board = ""; ///< the board's name, for the text +}; + +namespace detail { + +/// Text appended into a caller's buffer. It counts what it needed past the end, as snprintf does, so a cut shows in the count. +struct Text { + char* out; ///< the caller's buffer + size_t cap; ///< its size + size_t n = 0; ///< the length written so far, or needed once past the end + + /// Append `fmt` with its arguments, as printf formats them. + void add(const char* fmt, ...) { + va_list ap; + va_start(ap, fmt); + const bool room = out && n < cap; + const int w = std::vsnprintf(room ? out + n : nullptr, room ? cap - n : 0, fmt, ap); + va_end(ap); + if (w > 0) n += static_cast(w); + } +}; + +inline const char* plural(uint32_t n, const char* one, const char* many) { return n == 1 ? one : many; } + +/// `3 lanes of 2 (256x192, 243 Hz)`. +inline void addArrangement(Text& t, const Arrangement& a) { + t.add("%u lane%s of %u (%ux%u, %u Hz)", static_cast(a.parallel), plural(a.parallel, "", "s"), static_cast(a.panelsPerLane), + static_cast(a.width), static_cast(a.height), static_cast(a.hz)); +} + +/// The first sentence: what is wrong with the panels as the card has them. +inline void addReason(Text& t, GeometryFit why, uint32_t panels, const CardGeometry& g) { + const char* const word = plural(panels, "panel", "panels"); + if (why == GeometryFit::Empty) { + t.add("The layout holds fewer lights than one %ux%u panel.", static_cast(g.panel.cols), static_cast(g.panel.rows)); + } else if (why == GeometryFit::TooManyLanes) { + t.add("%u %s in lanes of %u need %u lanes, but the %s board drives at most %u.", static_cast(panels), word, + static_cast(g.panelsPerLane), static_cast(panels / g.panelsPerLane), g.board, + static_cast(g.maxLanes)); + } else { + t.add("%u %s cannot be cabled in lanes of %u.", static_cast(panels), word, static_cast(g.panelsPerLane)); + } +} + +/// Every arrangement that uses all the panels, widest first; none when every one would put more than kPanelsPerLaneMax panels on a lane. +inline void addArrangements(Text& t, uint32_t panels, const CardGeometry& g) { + Arrangement all[8]; // a board drives six lanes at most + const size_t count = panelArrangements(panels, g.panel, g.maxLanes, all, 8); + if (count == 0) return; + t.add(" Cable all %u (rates computed from the pixel clock): ", static_cast(panels)); + for (size_t i = 0; i < count; i++) { + if (i) t.add("; "); + addArrangement(t, all[i]); + } + t.add("."); +} + +/// What keeps the lanes already built: use fewer panels, or add some. +inline void addKeep(Text& t, uint32_t panels, const CardGeometry& g) { + const KeepLanes keep = keepLanes(panels, g.panel, g.panelsPerLane, g.maxLanes); + const bool hasUse = keep.use.panelsPerLane != 0; + const bool hasAdd = keep.add.panelsPerLane != 0; + if (!hasUse && !hasAdd) return; + t.add(" Keep lanes of %u (rates computed from the pixel clock): ", static_cast(g.panelsPerLane)); + if (hasUse) { + const uint32_t used = static_cast(keep.use.panelsPerLane) * keep.use.parallel; + t.add("use %u %s, %u spare, as %u lane%s (%ux%u, %u Hz)", static_cast(used), plural(used, "panel", "panels"), + static_cast(keep.spare), static_cast(keep.use.parallel), plural(keep.use.parallel, "", "s"), + static_cast(keep.use.width), static_cast(keep.use.height), static_cast(keep.use.hz)); + } + if (hasUse && hasAdd) t.add(", or "); + if (hasAdd) { + t.add("add %u %s for %u lane%s (%ux%u, %u Hz)", static_cast(keep.added), plural(keep.added, "panel", "panels"), + static_cast(keep.add.parallel), plural(keep.add.parallel, "", "s"), static_cast(keep.add.width), + static_cast(keep.add.height), static_cast(keep.add.hz)); + } + t.add("."); +} + +} // namespace detail + +/// What is wrong with a geometry that does not fit, every arrangement using all the panels, then how to keep the lanes; the length needed, snprintf style. +inline size_t geometryMessage(GeometryFit why, uint32_t panels, const CardGeometry& g, char* out, size_t cap) { + detail::Text t{out, cap}; + if (out && cap) out[0] = 0; + if (why == GeometryFit::Ok) return 0; + detail::addReason(t, why, panels, g); + if (why == GeometryFit::Empty) return t.n; + detail::addArrangements(t, panels, g); + detail::addKeep(t, panels, g); + return t.n; +} + +} // namespace mm diff --git a/src/light/drivers/Hub75Output.h b/src/light/drivers/Hub75Output.h index be802d41..11bb08d1 100644 --- a/src/light/drivers/Hub75Output.h +++ b/src/light/drivers/Hub75Output.h @@ -8,13 +8,22 @@ #include "core/module/MoonModule.h" // MoonModule::FixedPin: the lines an output reports to the pin map #include "light/drivers/LedPeripheral.h" // LedHwBlock: the sibling claim guard's vocabulary #include "platform/nonblocking.h" // MM_NONBLOCKING +#include "platform/Hub75Pio.h" // Hub75PioOptions: the defaults of the Pi output's settings #include "platform/platform.h" // Hub75Backend: the backend the driver answers namespace mm { -/// The settings an output reads from its driver, and the backend the `peripheral` select names. +class Layer; // the layout's lights, which the Pi output cuts into panels + +/// The color depths an output drives, in bit planes. +struct DepthRange { + uint8_t min; ///< the fewest planes + uint8_t max; ///< the most planes +}; + +/// The settings an output reads from its driver, the backend the `peripheral` select names, and the layer the driver draws from. /// -/// The settings live on the driver; the output binds them into the driver's card. +/// The settings live on the driver; the output binds them into the driver's card. The Pi output's panel and clock settings live here too, so a saved card keeps them through a boot where the PIO is not offered. class Hub75Settings { public: /// The board's wiring: picking one fills the fourteen pins, Custom keeps yours. @@ -56,8 +65,23 @@ class Hub75Settings { /// @guide Depth costs refresh and memory per plane, more on a layout 16 columns or less at 6-bit. Full white lights about a third of the time at 6-bit. uint8_t bitDepth = 6; - /// The backend the `peripheral` select names, for the output that drives it. + /// The seam's own defaults, the one home every Pi setting below starts from. + static constexpr platform::Hub75PioOptions kPiDefaults{}; + /// The rows of one panel on a Raspberry Pi's header. + uint8_t panelRows = kPiDefaults.rows; + /// The columns of one panel on a Raspberry Pi's header. + uint16_t panelCols = kPiDefaults.cols; + /// Panels in series on one lane of a Pi's header; hzeller's `--led-chain` is the same. + uint8_t panelsPerLane = kPiDefaults.panelsPerLane; + /// The Pi's pixel clock in kHz; 10,000 is 10 MHz. + uint16_t pixelClockKhz = static_cast(kPiDefaults.pixelClockHz / 1000); + /// Blank words the Pi's latch holds, 0 for none. + uint8_t latchBlankWords = kPiDefaults.latchBlankWords; + + /// The backend the `peripheral` select names. Virtual because Hub75BusOutput reads it through this base, in open() and hwBlock() off the frame path, and the driver alone holds the select; drivenLayer() keeps the vtable anyway. virtual platform::Hub75Backend selectedBackend() const = 0; + /// The layer the driver draws from, null while it has none. + virtual Layer* drivenLayer() const = 0; protected: ~Hub75Settings() = default; // protected: a driver is deleted through MoonModule's virtual destructor, so this base's stays trivial @@ -67,7 +91,7 @@ class Hub75Settings { /// /// The driver owns the lifecycle and the correction into one RGB frame in light order. The output owns what happens to that frame: its controls, geometry, hardware claim, and the call that puts it on the panel. /// -/// lights() and show() run once a frame, so the interface costs two dispatches a frame. +/// The driver reads lights() once, in prepare(), and show() runs once a frame, so the interface costs one dispatch a frame; the output's own calls into its seam come on top. class Hub75Output { public: /// Virtual, so a concrete output passes `-Wnon-virtual-dtor`, as LedPeripheral's does. @@ -84,14 +108,18 @@ class Hub75Output { virtual bool onControlChanged(const char* name) = 0; /// Whether a change to control `name` needs the output reopened. virtual bool affectsPrepare(const char* name) const = 0; + /// The planes the driver's one `bitDepth` takes on this output; the driver clamps the depth into it when the output changes. + virtual DepthRange depthRange() const = 0; /// The bytes a frame for a layout of `width` by `height` takes in the platform's buffer, which decides the backends offered; 0 for an unusable layout. virtual size_t frameBytes(uint16_t width, uint16_t height) const = 0; /// Bring the panel up for a layout of `width` by `height`; null when it runs, else the reason it refused, which the driver shows as an error. virtual const char* open(uint16_t width, uint16_t height) = 0; /// The status line while the panel runs. - virtual const char* describe() const = 0; - /// The lights in the layout's box while it runs: the length of the RGB frame show() takes, a size_t since a light type of 16 bits wraps at 65,536. + virtual const char* describe() const MM_NONBLOCKING = 0; + /// What degrades the running panel or the layout's fit to it, in full, shown as a warning in place of describe(); null while the output is healthy. + virtual const char* warning() const MM_NONBLOCKING = 0; + /// The lights in the layout's box while it runs: the length of the RGB frame show() takes, a size_t since a light type of 16 bits wraps at 65,536. It stays fixed from open() to close(), which the driver relies on to read it once. virtual size_t lights() const MM_NONBLOCKING = 0; /// Put one corrected RGB frame of lights() lights on the panel, lit at `brightness`. virtual void show(const uint8_t* rgb, uint8_t brightness) MM_NONBLOCKING = 0; diff --git a/src/light/drivers/Hub75PiOutput.h b/src/light/drivers/Hub75PiOutput.h new file mode 100644 index 00000000..d2bb0f9d --- /dev/null +++ b/src/light/drivers/Hub75PiOutput.h @@ -0,0 +1,303 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include "core/util/format.h" // formatTo: nonblocking formatting into a fixed buffer +#include "core/util/ScratchBuffer.h" // the lane canvas, accounted to the driver and freed with it +#include "light/drivers/Hub75Canvas.h" // where a light of a panel-by-panel layout sits on the lane canvas, and the plain-rows walk +#include "light/drivers/Hub75Fit.h" // whether the layout's panels cable into the lanes, and the way out when they do not +#include "light/drivers/Hub75Output.h" +#include "light/layers/Layer.h" // the layout's lights, which the fit and the plain-rows walk read +#include "light/layouts/Layouts.h" // where each light sits, which the plain-rows walk reads + +#include +#include +#include + +namespace mm { + +/// What a Raspberry Pi output shares: the panel geometry, the fit of the layout to it, the lane canvas, and the handover of a frame to a seam. +/// +/// **The layout sets the geometry.** `panelRows` and `panelCols` are one panel's, `panelsPerLane` the panels in series on one lane, all settings of the driver, and the layout's lights, cut into whole panels, are the panels; the lanes driven at once follow, bounded by the board's three. +/// +/// The subclass names its seam: the panel's timing, the call that opens the engine, the one that feeds it, the one that closes it, and the controls only that engine has. While the panels run it shows their rate and failing submits (@xref{running|Running}). The ESP32 bus output has no panel geometry and inherits none of this. +/// +/// **The wiring is fixed,** the active 3-channel board's: three lanes of HUB75 data lines on the Pi's header, each lane up to 32 panels in series, so the card carries no pin controls and no wiring row. +/// +/// @technical +/// +/// ## Opening +/// +/// open() is the one sequence the seam follows: close, cut the layout into panels, refuse a geometry that does not cable into the lanes with the way out, open the seam, size the lane canvas, and format the status. The driver clamps the depth into the output's range when the output changes, so open() reads the depth as it is. +/// +/// The subclass supplies the steps that differ through protected virtuals: panelSpec() for the panel's timing, openSeam() and seamError() for the engine, seamWarning() for what degrades it, and closeSeam(). +/// +/// ## The lane canvas +/// +/// The seam's canvas is `panelCols * panelsPerLane` wide while the layout's lights run panel by panel, so with several panels per lane each panel row is copied to its place before the push; a layout of another count, or off plain rows, is the warning. +/// +/// ## Running +/// +/// While the panels run, tick1s() publishes the frames shown in the last second and watches the seam's failed submits: a count that rose in the last second joins the warning, so a dead panel does not read as a healthy one. +class Hub75PiOutput : public Hub75Output { +public: + /// The lanes the board drives: three, one per HUB75 data path. + static constexpr uint8_t kParallelMax = static_cast(platform::kHub75Lanes); + + /// No controls of its own beyond the seam's: the panel's rows, columns and panels per lane are the driver's, shown there while this output runs. + void addControls(ControlList& controls) override { addSeamControls(controls); } + + /// The wiring is fixed, so the output adds no wiring row above the peripheral select. + void addWiringControls(ControlList& /*controls*/) override {} + + /// No control changes the card's shape. + bool onControlChanged(const char* /*name*/) override { return false; } + + /// The planes the engine drives: 2 to the encoder's most. + DepthRange depthRange() const override { return DepthRange{2, kHub75EncodeMaxBitDepth}; } + + /// A Pi output's canvas size follows its layout, not a frame size the platform sizes. + size_t frameBytes(uint16_t /*width*/, uint16_t /*height*/) const override { return 0; } + + /// No line has a visible pin control to claim: the wiring is fixed and unlisted. + uint8_t fixedPins(MoonModule::FixedPin* /*out*/, uint8_t /*max*/) const override { return 0; } + + /// Open the panels; the canvas they form is the frame, whatever the layout's box, and warnFit() compares the light counts (@xref{opening}). + const char* open(uint16_t /*width*/, uint16_t /*height*/) override { + close(); + if (const char* why = optionsRefusal()) return why; + const uint8_t bits = owner_->bitDepth; + + // The layout sets the geometry: its lights, cut into whole panels, are the panels, and the card's panels per lane divide them into lanes. + const uint32_t perPanel = static_cast(owner_->panelRows) * owner_->panelCols; + const uint32_t layoutLights = layer() ? layer()->physicalLightCount() : 0; + const uint32_t panels = perPanel ? layoutLights / perPanel : 0; + char board[16]; + std::snprintf(board, sizeof(board), "Pi %s", label_); + const CardGeometry geometry{panelSpec(bits), owner_->panelsPerLane, kParallelMax, board}; + const GeometryFit fit = checkGeometry(panels, owner_->panelsPerLane, kParallelMax); + message_[0] = '\0'; + if (fit != GeometryFit::Ok) { + geometryMessage(fit, panels, geometry, message_, sizeof(message_)); + return message_; + } + derivedParallel_ = static_cast(panels / owner_->panelsPerLane); + + if (!openSeam(canvasW_, canvasH_)) { + // Copied: the seam's text lives in a string its next open rewrites, and the status keeps the pointer. + const char* why = seamError(); + std::snprintf(message_, sizeof(message_), "%s", why ? why : "the panels would not open"); + return message_; + } + open_ = true; + lastErrors_ = shownErrors_ = 0; // the seam counts from this open + stalled_ = false; // a stall still there at the first tick shows, as the tick compares against this open's state + placed_ = {owner_->panelRows, owner_->panelCols, owner_->panelsPerLane}; + // A lane of several panels is not a raster: the layout's lights run panel by panel, so the push reads a second frame they are placed on. + if (owner_->panelsPerLane > 1 && !canvas_.resize(lights() * 3)) { + close(); + return "not enough memory for the lane canvas"; + } + std::snprintf(status_, sizeof(status_), "%ux%u, %u-bit, %s", static_cast(canvasW_), static_cast(canvasH_), + static_cast(bits), label_); + warnFit(layoutLights); + return nullptr; + } + + /// The canvas and the depth, as open() formatted them. + const char* describe() const MM_NONBLOCKING override { return status_; } + + /// What degrades the running panels, in full, none hiding another: the seam's warning, a light count other than the canvas's, the walk's panel, then failing submits; after a close that did not finish, why. + const char* warning() const MM_NONBLOCKING override { return (open_ || closeStuck_) && message_[0] ? message_ : nullptr; } + + /// The panels' canvas, one light per pixel. + size_t lights() const MM_NONBLOCKING override { return open_ ? canvasLights() : 0; } + + /// Hand the frame over, at the global brightness the engine dims by. + void show(const uint8_t* rgb, uint8_t brightness) MM_NONBLOCKING override { + applyBrightness(brightness); + if (canvas_.bytes() == 0) { + push(rgb); + return; + } + placeOnCanvas(rgb); + push(canvas_.data()); + } + + /// Publish the frames shown in the last second, and fold failing submits into the warning. + void tick1s() MM_NONBLOCKING override { + if (!open_) return; + const uint16_t fps = framesShown(); + if (fps != lastShown_) { // a changed value alone re-serializes on the 1 Hz tick + lastShown_ = fps; + mm::formatTo(shownStr_, sizeof(shownStr_), "%u fps", fps); + } + watchSubmits(); + } + + /// Stop the refresh and darken the panels; a close the seam could not finish leaves its reason as the warning. + void close() override { + if (open_) closeSeam(); + open_ = false; + canvasW_ = canvasH_ = 0; + canvas_.resize(0); + shownStr_[0] = '\0'; // a closed panel shows an empty rate + lastShown_ = 0xFFFF; + message_[0] = '\0'; + const char* stuck = seamCloseError(); + closeStuck_ = stuck != nullptr; + if (stuck) std::snprintf(message_, sizeof(message_), "%s", stuck); + baseLen_ = std::strlen(message_); + } + + /// The Pi's header, which one HUB75 driver per Pi drives; every Pi output claims this block, so one drives the header at a time. + LedHwBlock hwBlock() const override { return LedHwBlock::PiHeader; } + +protected: + /// The frames the panels showed in the last second. + char shownStr_[16] = ""; + + /// The lane canvas is `owner`'s memory, counted in its readout and freed on its release; `label` names the seam in the status ("PIO"). + Hub75PiOutput(MoonModule& owner, const char* label) : label_(label), canvas_(owner) {} + + /// Whether `name` is in `list`, for the controls that reopen the panels. + template + static bool isOneOf(const char* name, const char* const (&list)[N]) { + for (const char* n : list) { + if (std::strcmp(name, n) == 0) return true; + } + return false; + } + + /// Fill the options the seam takes: the panel, the lanes the layout decides in open(), the depth and the clock edge. + template + void fillOptions(Options& o) const { + o.rows = owner_->panelRows; + o.cols = owner_->panelCols; + o.panelsPerLane = owner_->panelsPerLane; + o.parallel = parallel(); + o.bitDepth = owner_->bitDepth; + o.clockFallingEdge = owner_->clockEdgeSel == Hub75Settings::kEdgeFalling; + } + + /// The lanes the layout's panels divide into, set by open(); one before it runs. + uint8_t parallel() const { return derivedParallel_ ? derivedParallel_ : 1; } + + /// Why the settings cannot open the seam at all, in the settings' own words, or null. + virtual const char* optionsRefusal() const { return nullptr; } + /// Add the seam's controls: the depth, the edge and the `shown` rate last. + virtual void addSeamControls(ControlList& controls) = 0; + /// The panel as the seam clocks it, for the arrangements' rate and the message of a geometry that does not fit. + virtual PanelSpec panelSpec(uint8_t bits) const = 0; + /// Open the seam with the current options and answer the canvas it forms; false when it would not open. + virtual bool openSeam(uint16_t& width, uint16_t& height) = 0; + /// Why the seam did not open, or null. + virtual const char* seamError() const = 0; + /// What degrades the running seam, or null. + virtual const char* seamWarning() const = 0; + /// Why the seam's last close did not finish, or null. + virtual const char* seamCloseError() const = 0; + /// Stop the seam and release its engine. + virtual void closeSeam() = 0; + /// The frames the seam showed in the last second. + virtual uint16_t framesShown() const MM_NONBLOCKING = 0; + /// The submits the seam counted as failed since it opened. + virtual uint32_t submitErrors() const MM_NONBLOCKING = 0; + /// Whether a submit has been in flight for longer than the seam allows, so the panels hold their last frame. + virtual bool seamStalled() const MM_NONBLOCKING = 0; + /// Hand the seam the global brightness. + virtual void applyBrightness(uint8_t brightness) MM_NONBLOCKING = 0; + /// Hand the seam one frame of the canvas. + virtual void push(const uint8_t* rgb) MM_NONBLOCKING = 0; + +private: + /// The layer the driver draws from. + Layer* layer() const { return owner_->drivenLayer(); } + + /// The canvas's pixels, one light each, whether or not the panels are open. + size_t canvasLights() const MM_NONBLOCKING { return static_cast(canvasW_) * canvasH_; } + + /// Build the warning, each part whole and joined with "; ": the seam's, a light count other than the canvas's, then the walk's panel. + void warnFit(uint32_t layoutLights) { + detail::Text t{message_, sizeof(message_)}; + if (const char* seam = seamWarning()) t.add("%s", seam); + if (layoutLights != lights()) + t.add("%slayout %u lights, panels %u", t.n ? "; " : "", static_cast(layoutLights), static_cast(lights())); + const uint32_t off = offPanel(); + if (off != PanelWalk::kNone) + t.add("%sthe layout's panel %u does not run in plain rows of %u: lay the panels out in cabling order, each in plain rows with snake off", + t.n ? "; " : "", static_cast(off + 1), static_cast(placed_.cols)); + baseLen_ = t.n < sizeof(message_) ? t.n : sizeof(message_) - 1; + } + + /// A stalled submit, or failed submits that rose in the last second, join the warning after its other parts, and leave it when they stop; a stall, the graver, shows alone. + void watchSubmits() MM_NONBLOCKING { + const uint32_t errors = submitErrors(); + const bool stalled = seamStalled(); + const bool failing = errors != lastErrors_; + const bool changed = stalled != stalled_ || failing != failing_ || (failing && !stalled && errors != shownErrors_); + lastErrors_ = errors; + if (!changed) return; + stalled_ = stalled; + failing_ = failing; + shownErrors_ = errors; + message_[baseLen_] = '\0'; + const char* sep = baseLen_ ? "; " : ""; + char* at = message_ + baseLen_; + const size_t room = sizeof(message_) - baseLen_; + if (stalled) mm::formatTo(at, room, "%sthe PIO is stalled: a submit has not returned, and the panels hold their last frame", sep); + else if (failing) mm::formatTo(at, room, "%sthe PIO is failing: %u submits failed since it opened, and the panels may be dark", sep, static_cast(errors)); + } + + /// The first driven panel, counted from 0, whose lights leave plain rows, or PanelWalk::kNone; lights past the last whole panel are the count's. + uint32_t offPanel() const { + Layouts* layouts = layer() ? layer()->layouts() : nullptr; + if (!layouts) return PanelWalk::kNone; + struct Driven { PanelWalk walk; size_t lights; }; + Driven driven{PanelWalk(placed_.rows, placed_.cols), lights()}; + layouts->placeLights(CoordSink{[](void* c, nrOfLightsType i, lengthType x, lengthType y, lengthType) { + auto* d = static_cast(c); + if (i < d->lights) d->walk.light(i, x, y); + }, + nullptr, &driven}); + return driven.walk.firstOffPanel(); + } + + /// Copy the corrected frame onto the canvas a panel row at a time: a panel's row is contiguous in both, so each row is one blit (@xref{the-lane-canvas}). + void placeOnCanvas(const uint8_t* rgb) MM_NONBLOCKING { + const size_t width = static_cast(placed_.cols) * placed_.panelsPerLane; + const size_t rowBytes = static_cast(placed_.cols) * 3; + const size_t n = canvasLights(); // show() runs while the panels are open, so this is lights() read directly + for (size_t i = 0; i + placed_.cols <= n; i += placed_.cols) { + const CanvasPos p = laneCanvasPos(static_cast(i), placed_.rows, placed_.cols, placed_.panelsPerLane); + const size_t to = (static_cast(p.y) * width + p.x) * 3; + if (to + rowBytes > canvas_.bytes()) continue; + std::memcpy(canvas_.data() + to, rgb + i * 3, rowBytes); + } + } + + /// One panel and its panels per lane as the panels were opened, so a control changed before the reopen moves no row. + struct Placed { + uint16_t rows = 0; + uint16_t cols = 0; + uint8_t panelsPerLane = 0; + }; + + const char* label_; ///< the seam's name in the status line + bool open_ = false; + bool closeStuck_ = false; ///< the seam's last close did not finish, and message_ says why + bool failing_ = false; ///< whether submits failed in the last second, and the warning says so + bool stalled_ = false; ///< whether a submit is stalled, and the warning says so + uint8_t derivedParallel_ = 0; ///< the outputs the layout's panels divide into, set by open() + char message_[kGeometryMessageMax] = ""; ///< the way out of a geometry that does not fit, or the running panels' warnings, whole + size_t baseLen_ = 0; ///< the length of the warning's fixed parts, which the failing-submit part follows + uint16_t canvasW_ = 0; + uint16_t canvasH_ = 0; + uint16_t lastShown_ = 0xFFFF; // 0xFFFF, so the first real 0 still publishes + uint32_t lastErrors_ = 0; ///< the failed submits counted at the last tick + uint32_t shownErrors_ = 0; ///< the count the warning shows + char status_[32] = {}; ///< the canvas and the depth, at most "65535x65535, 8-bit, PIO" + Placed placed_; + ScratchBuffer canvas_; ///< the placed frame of lanes of several panels, empty for one panel per lane, whose lights are already a raster +}; + +} // namespace mm diff --git a/src/light/drivers/Hub75PioOutput.h b/src/light/drivers/Hub75PioOutput.h new file mode 100644 index 00000000..4cb909b5 --- /dev/null +++ b/src/light/drivers/Hub75PioOutput.h @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include "light/drivers/Hub75PiOutput.h" // the panel geometry, the fit and the lane canvas +#include "platform/Hub75Pio.h" + +#include + +namespace mm { + +/// The HUB75 driver's output on a Raspberry Pi 5's header, through the RP1's PIO: it hands the corrected frame to the PIO seam, behind which a state machine clocks the panels; the engine dims by lit time (@xref{brightness-and-the-curve|brightness and the curve}). +/// +/// Its pins are the active 3-channel board's (hub75_pio_pins.h). The defaults are a 256x192 wall: 128x64 panels, 2 to a lane, 3 lanes in parallel, stacked to 256x192 at 1/32 scan and 6-bit, clocked at 10 MHz. +/// +/// The scan derives from half the panel's rows (@xref{scan-rate|scan rate}), every rate the card quotes is a computed wire rate (@xref{the-refresh|the refresh}), and 8-bit color is opt-in. +/// +/// @attribution pico-examples, pimoroni-pico +/// +/// @technical +/// +/// ## The refresh +/// +/// The frame is `bitDepth * scanRows * (laneWidth + holdWords)` pixel clocks. Every rate this card quotes is that computed wire rate: 203.5 Hz on the wall at 10 MHz, where `shown` measured 169 fps on kernel 6.18 and 198 on 6.12, as the DMA feed falls behind the wire by a margin that differs by kernel. The rates at other clocks are in docs/reference/hardware/hub75-bench.md. +/// +/// The card offers 2 to 8 planes, starting at 6; the cost and encoding of the 8-bit setting are in docs/reference/hardware/hub75-panels.md. +/// +/// A pixel clock above the benched 20 MHz warns, failed submits show as a warning while they rise, a submit that has not returned shows as a stall, and a close the kernel left unfinished says why. +/// +/// ## Scan rate +/// +/// The scan is rows / 2, so the card carries no `scanRate` control and a 64-row wall is 1/32 on its own; a 1/16 scan on that wall stripes it (bench 2026-11-13). +/// +/// That shuts out a 32-row panel scanned 1/8 and a 64-row panel scanned 1/16, which the engine could drive. Only 16, 32 and 64 rows open; any other count is refused at open with the status line naming the rows that work. +/// +/// ## Brightness and the curve +/// +/// The engine dims by lit time, so the correction keeps full values and bakes the curve itself; the seam's brightness is the global level alone. +class Hub75PioOutput final : public Hub75PiOutput { +public: + /// The lane canvas is `owner`'s memory, counted in its readout and freed on its release. + explicit Hub75PioOutput(MoonModule& owner) : Hub75PiOutput(owner, "PIO") {} + + /// The depth, the clock edge and the frames shown each second, below the peripheral select; the panel's rows, columns, panels per lane, clock and latch blank are the driver's. + void addSeamControls(ControlList& controls) override { + controls.addControl("bitDepth", owner_->bitDepth, depthRange().min, depthRange().max); + controls.addSelect("clockEdge", owner_->clockEdgeSel, Hub75Settings::kEdgeOptions, Hub75Settings::kEdgeCount); + controls.addReadOnly("shown", shownStr_, sizeof(shownStr_)); + } + + /// Every PIO option reopens the panels; the read-only rate does not. + bool affectsPrepare(const char* name) const override { + static const char* const kReopen[] = { + "rows", "cols", "panelsPerLane", "bitDepth", "clockEdge", "pixelClock", "latchBlank", + }; + return isOneOf(name, kReopen); + } + + /// The options as the platform takes them. + platform::Hub75PioOptions options() const { + platform::Hub75PioOptions o; + fillOptions(o); + o.scanRate = scanRate(); + o.pixelClockHz = static_cast(owner_->pixelClockKhz) * 1000; + o.latchBlankWords = owner_->latchBlankWords; + return o; + } + +protected: + /// The rows that give a scan the engine drives, 8, 16 or 32 at rows / 2: 16, 32 and 64. + const char* optionsRefusal() const override { + const uint8_t rows = owner_->panelRows; + if (rows == 16 || rows == 32 || rows == 64) return nullptr; + return "the scan is half the panel's rows, so rows must be 16, 32 or 64"; + } + + /// The panel as the rate counts it: address steps of rows / 2, each one shift of the lane, at the pixel clock. + PanelSpec panelSpec(uint8_t bits) const override { + // The shift is one pixel clock a pixel, the latch rides the last one, and no lit time outlasts a row's shift. + const uint8_t rows = owner_->panelRows; + const uint16_t scanRows = rows > 1 ? static_cast(rows / 2) : 1; + const uint16_t shiftTenths = owner_->pixelClockKhz ? static_cast(10'000'000u / owner_->pixelClockKhz) : 10000; + PanelSpec panel{rows, owner_->panelCols, scanRows, bits, 0, shiftTenths, 0}; + panel.pairs = 1; // a scan of rows / 2 pairs one row of the upper half with one of the lower + panel.encoderHold = true; // the frame is the encoder's: a narrow row's hold words count as shift + return panel; + } + + bool openSeam(uint16_t& width, uint16_t& height) override { + if (!platform::hub75PioOpen(options())) return false; + width = platform::hub75PioWidth(); + height = platform::hub75PioHeight(); + return true; + } + const char* seamError() const override { return platform::hub75PioLastError(); } + const char* seamWarning() const override { return platform::hub75PioWarning(); } + const char* seamCloseError() const override { return platform::hub75PioCloseError(); } + void closeSeam() override { platform::hub75PioClose(); } + uint16_t framesShown() const MM_NONBLOCKING override { return platform::hub75PioFps(); } + uint32_t submitErrors() const MM_NONBLOCKING override { return platform::hub75PioSubmitErrors(); } + bool seamStalled() const MM_NONBLOCKING override { return platform::hub75PioStalled(); } + /// The engine dims by lit time, so the seam's brightness is the global level alone. + void applyBrightness(uint8_t brightness) MM_NONBLOCKING override { platform::hub75PioCorrection(brightness); } + void push(const uint8_t* rgb) MM_NONBLOCKING override { platform::hub75PioPush(rgb); } + +private: + /// The scan rate the panel's rows imply, rows / 2: 64 rows is 1/32, 32 rows 1/16, 16 rows 1/8 (@xref{scan-rate|scan rate}). + uint8_t scanRate() const { + return owner_->panelRows > 1 ? static_cast(owner_->panelRows / 2) : 1; + } +}; + +} // namespace mm diff --git a/src/light/drivers/LedPeripheral.h b/src/light/drivers/LedPeripheral.h index decc93fc..b92654ac 100644 --- a/src/light/drivers/LedPeripheral.h +++ b/src/light/drivers/LedPeripheral.h @@ -9,8 +9,8 @@ namespace mm { class ParallelLedDriver; // the orchestrator; a backend reads shared state through this back-pointer -/// The physical peripheral block a backend drives; two backends on one block conflict. -enum class LedHwBlock : uint8_t { None = 0, LcdCam, I2s, Parlio, GpioDma }; +/// The physical peripheral block a backend drives, or PiHeader, a Raspberry Pi's header, which the PIO output drives; two backends on one block conflict. +enum class LedHwBlock : uint8_t { None = 0, LcdCam, I2s, Parlio, GpioDma, PiHeader }; /// A parallel-WS2812 output peripheral, behind a runtime strategy interface. /// diff --git a/src/light/drivers/ParallelLedDriver.h b/src/light/drivers/ParallelLedDriver.h index eeb676e9..fc5d088e 100644 --- a/src/light/drivers/ParallelLedDriver.h +++ b/src/light/drivers/ParallelLedDriver.h @@ -742,22 +742,8 @@ class ParallelLedDriver : public DriverBase, public platform::InternalRamObject swapPeripheral(peripheralSel_); } - /// Does an enabled sibling driver already claim this backend's hardware block? RTTI-free: every module answers hwBlock(), and a non-parallel driver returns None. - bool siblingClaimsBlock() const { - if (!peripheral_) return false; - const LedHwBlock mine = peripheral_->hwBlock(); - if (mine == LedHwBlock::None) return false; - const MoonModule* p = parent(); - if (!p) return false; - for (uint8_t i = 0; i < p->childCount(); i++) { - const MoonModule* sib = p->child(i); - if (sib == this || !sib || !sib->enabled()) continue; - // role() confirms it, so this static_cast needs no RTTI. - if (sib->role() != ModuleRole::Driver) continue; - if (static_cast(sib)->hwBlock() == mine) return true; - } - return false; - } + /// Does an enabled sibling driver already claim this backend's hardware block? + bool siblingClaimsBlock() const { return peripheral_ && siblingClaims(peripheral_->hwBlock()); } public: /// The hardware block this driver is DRIVING, for the sibling claim guard: gated on inited_, so the claim means the bus is up rather than that a backend is selected. @@ -1056,7 +1042,7 @@ class ParallelLedDriver : public DriverBase, public platform::InternalRamObject // One block per chip, so a sibling holding it means idle with a status rather than fight. if (siblingClaimsBlock()) { deinit(); - setConfigErr("peripheral already in use by another driver — pick a different one"); + setConfigErr(kBlockInUse); return; } // A rebuild is the user fixing the setting, so a driver that gave up starts again. diff --git a/src/platform/Hub75Bus.h b/src/platform/Hub75Bus.h index c20495a8..e6358eb9 100644 --- a/src/platform/Hub75Bus.h +++ b/src/platform/Hub75Bus.h @@ -41,6 +41,15 @@ constexpr uint8_t kHub75EncodeMaxBitDepth = 8; /// The deepest `bitDepth` the ESP32 port takes, until the repeated-planes card (backlog) lifts it: the lit-window weights cost top brightness, and plane 0 of a 64-column row lights 2 words at 6 bits, half that at 7. The driver and the port read it. constexpr uint8_t kHub75PortMaxBitDepth = 6; +/// Hold words for a row of `rowWords` shift words at `bitDepth` planes, the one home of the formula (@xref{hold-words|Technical → Hold words}): 0 for an empty row, and for a wide one whose lowest plane already lights a word. +inline size_t hub75HoldWords(size_t rowWords, uint8_t bitDepth) { + if (rowWords == 0 || bitDepth < 2 || bitDepth > kHub75EncodeMaxBitDepth) return 0; + // The lowest plane's window rounds to zero up to 2^(bitDepth-2) row words; above that the rounding stands. + if (rowWords > (static_cast(1) << (bitDepth - 2))) return 0; + const size_t pass = (static_cast(1) << (bitDepth - 1)) + 1; + return pass - rowWords; +} + /// The geometry one encode needs. `scanRate` is the panel's own and is NOT derivable from the height. Two panels of identical dimensions can scan differently, which is why it is a control rather than a calculation. struct Hub75Geometry { /// Bytes on the wire per pixel clock: one 16-bit bus word, sixteen rather than eight since the control lines live at bits 8-14. @@ -85,14 +94,7 @@ struct Hub75Geometry { } /// Hold words the encoder leads each group with, so a narrow row's lowest plane lights a whole word (Hub75Encode.h): a function of the row width and the depth, 0 for an empty row, see @xref{hold-words|Technical → Hold words}. - size_t holdWords() const { - const size_t row = rowWords(); - if (row == 0 || bitDepth < 2 || bitDepth > kHub75EncodeMaxBitDepth) return 0; - // The lowest plane's window rounds to zero up to 2^(bitDepth-2) row words; above that the rounding stands. - if (row > (static_cast(1) << (bitDepth - 2))) return 0; - const size_t pass = (static_cast(1) << (bitDepth - 1)) + 1; - return pass - row; - } + size_t holdWords() const { return hub75HoldWords(rowWords(), bitDepth); } /// Words one (plane, row) group holds on the wire: the shift words plus the hold words. A wide row needs no hold words, so the pass is the row. size_t passWords() const { return rowWords() + holdWords(); } diff --git a/src/platform/Hub75Pio.h b/src/platform/Hub75Pio.h index d7d195f8..0736c1a6 100644 --- a/src/platform/Hub75Pio.h +++ b/src/platform/Hub75Pio.h @@ -1,7 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later #pragma once -/// HUB75 from a Pi 5's RP1 PIO: the seam MoonLight's own PIO engine sits behind, and the host test port that stands in for it. +/// HUB75 from a Pi 5's RP1 PIO, gated by `hasHub75Pio`: the seam MoonLight's own PIO engine sits behind, and the host test port that stands in for it. /// /// The seam takes tightly packed RGB, since the engine encodes the bit planes and refreshes from its own threads. It drives GPIO 2 to 27, so the header's I2C1, SPI0, UART0, 1-wire, I2S and PWM must be off (hub75_board_pins.h, Pins the kernel may own). It lives apart from platform.h as a self-contained concern, as edid.h and Hub75Bus.h do, and its users include it directly. @@ -12,6 +12,12 @@ namespace mm::platform { +/// The lanes the active 3-channel board drives, one per HUB75 data path: the engines' lane tables, slot streams and repack all take this many, and so does the card. +constexpr int kHub75Lanes = 3; + +/// The most panels in series on one lane an engine takes, 32; an engine refuses longer ones rather than allocating a frame for them, and the card's panels per lane stop here. +constexpr uint8_t kHub75PanelsPerLaneMax = 32; + /// One wall of panels under the PIO output's own option names: the panels as wired, in lanes the active 3-channel board drives together. The canvas is `cols * panelsPerLane` wide and `rows * parallel` high; each lane is one `cols * panelsPerLane` by `rows` strip, the lanes stacked. /// @technical The engine encodes the bit planes and refreshes from its own thread, so the seam takes RGB rather than the bus words `hub75Buffer` takes. MoonLight's correction already applied the curve, so the engine runs identity gamma. struct Hub75PioOptions { diff --git a/src/platform/esp32/platform_config.h b/src/platform/esp32/platform_config.h index c2c23999..d3309a6d 100644 --- a/src/platform/esp32/platform_config.h +++ b/src/platform/esp32/platform_config.h @@ -197,6 +197,9 @@ constexpr bool hasRawEthernet = true; /// False on every ESP32, and not by choice: the runtime is a closed binary for Intel and ARM alone. constexpr bool hasNdi = false; +/// False: no RP1 PIO block on an ESP32. +constexpr bool hasHub75Pio = false; + // True on the P4 alone, mirroring the build symbol, so flag and dependency cannot disagree. #if defined(CONFIG_MM_HLS) constexpr bool hasHls = true; diff --git a/src/platform/host/platform_config.h b/src/platform/host/platform_config.h index f5f8b146..8ae5af24 100644 --- a/src/platform/host/platform_config.h +++ b/src/platform/host/platform_config.h @@ -78,6 +78,9 @@ constexpr bool previewsHardwareControls = true; /// True: a host has several NICs, so a raw sender must name the one it binds. constexpr bool hasNamedNetInterfaces = true; +/// True: the RP1 PIO seam links on every host, and an open that finds no panels says why. +constexpr bool hasHub75Pio = true; + #ifdef __ANDROID__ /// False: an Android app has no NDI runtime to load. constexpr bool hasNdi = false; diff --git a/src/platform/rpi/hub75_board_pins.h b/src/platform/rpi/hub75_board_pins.h index 739a4c2c..1b61828b 100644 --- a/src/platform/rpi/hub75_board_pins.h +++ b/src/platform/rpi/hub75_board_pins.h @@ -34,6 +34,8 @@ #include +#include "platform/Hub75Pio.h" // kHub75Lanes: the board's lane count + namespace mm::platform { /// The signals fanned out to all three lanes: each is a GPIO, with its 40-pin header pin in the trailing comment (@xref{shared-signals|Shared signals}). @@ -54,9 +56,6 @@ struct LanePins { uint8_t r2, g2, b2; ///< lower half }; -/// The lanes the active board drives, one per HUB75 data path: the engines' lane tables, slot streams and repack all take this many. -constexpr int kHub75Lanes = 3; - /// The lanes' color pins in LanePins order; each row's comment gives the 40-pin header pins (@xref{lane-pins|Lane pins}). constexpr LanePins kLanePins[kHub75Lanes] = { {11, 27, 7, 8, 9, 10}, // lane 1: hdr 23, 13, 26, 24, 21, 19 diff --git a/src/platform/rpi/hub75_pio_options.h b/src/platform/rpi/hub75_pio_options.h index b6946c97..79fff9d1 100644 --- a/src/platform/rpi/hub75_pio_options.h +++ b/src/platform/rpi/hub75_pio_options.h @@ -24,13 +24,9 @@ #include "platform/Hub75Bus.h" // Hub75Geometry #include "platform/Hub75Pio.h" // Hub75PioOptions -#include "platform/rpi/hub75_board_pins.h" // kHub75Lanes: the board's lane count namespace mm::platform { -/// The most panels per lane an engine takes, 32: this layer builds independently of light/, so the number is stated here; an engine refuses longer ones rather than allocating a frame for them. -constexpr uint8_t kHub75PanelsPerLaneMax = 32; - /// Whether `value` lies outside lo..hi, the shape of every range rule. constexpr bool hub75Outside(int value, int lo, int hi) { return value < lo || value > hi; } diff --git a/src/platform/rpi/hub75_pio_repack.h b/src/platform/rpi/hub75_pio_repack.h index 7cacde72..768165c6 100644 --- a/src/platform/rpi/hub75_pio_repack.h +++ b/src/platform/rpi/hub75_pio_repack.h @@ -35,7 +35,7 @@ #include #include -#include "platform/rpi/hub75_board_pins.h" // kHub75Lanes: the board's lane count +#include "platform/rpi/hub75_board_pins.h" // the board's pin table, which brings kHub75Lanes from platform/Hub75Pio.h namespace mm::platform { diff --git a/src/platform/rpi/hub75_rpi_common.h b/src/platform/rpi/hub75_rpi_common.h index f27b14a6..195fa07e 100644 --- a/src/platform/rpi/hub75_rpi_common.h +++ b/src/platform/rpi/hub75_rpi_common.h @@ -69,7 +69,7 @@ #endif #include "platform/Hub75Bus.h" // Hub75Geometry, Hub75Layout -#include "platform/rpi/hub75_board_pins.h" // kHub75Lanes: the board's lane count +#include "platform/rpi/hub75_board_pins.h" // the board's pin table, which brings kHub75Lanes from platform/Hub75Pio.h #include "platform/rpi/hub75_pio_options.h" // the option rules, hub75LaneGeometry #include "platform/nonblocking.h" // MM_NONBLOCKING: the triple buffer's publish is tick-safe diff --git a/src/platform/teensy/platform_config.h b/src/platform/teensy/platform_config.h index 78748433..7de5541d 100644 --- a/src/platform/teensy/platform_config.h +++ b/src/platform/teensy/platform_config.h @@ -69,6 +69,8 @@ constexpr bool hasRawEthernet = false; /// No NDI, HLS or RTSP source. constexpr bool hasNdi = false; +/// False: no RP1 PIO block on a Teensy. +constexpr bool hasHub75Pio = false; /// No H.264 encoder. constexpr bool hasHls = false; /// False: the Teensy has no display controller. diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 109c0fc2..d3f40501 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -301,6 +301,11 @@ add_executable(mm_tests unit/light/unit_Hub75Driver_output.cpp unit/light/unit_Hub75Driver_pins.cpp unit/light/unit_Hub75Encode.cpp + unit/light/unit_Hub75Canvas.cpp + unit/light/unit_Hub75Fit.cpp + unit/light/unit_Hub75PiOutput.cpp + unit/light/unit_Hub75PioOutput.cpp + unit/light/unit_Hub75Driver_pi.cpp unit/light/unit_ParallelSlots.cpp unit/light/unit_ParlioPeripheral.cpp unit/light/unit_GpioDmaPeripheral.cpp diff --git a/test/unit/core/unit_ModuleContract.cpp b/test/unit/core/unit_ModuleContract.cpp index 564daee0..66d2f59e 100644 --- a/test/unit/core/unit_ModuleContract.cpp +++ b/test/unit/core/unit_ModuleContract.cpp @@ -12,6 +12,7 @@ #include "core/module/StateDocument.h" #include "core/util/ModuleFactory.h" #include "module_types.h" +#include "platform/Hub75Pio.h" #include "platform/platform.h" #include @@ -71,6 +72,7 @@ const std::vector kTooBig = { {"PanelCardDriver", "the packet_ frame buffer sits inline, sized to the largest card frame", false, mm::platform::hasRawEthernet}, {"ParallelLedDriver", "the pin and strand text fields and the in-flight state sit inline"}, {"HttpServerModule", "the eight WebSocket client connections sit inline"}, + {"Hub75Driver", "the Pi 5's PIO output sits inline beside the bus output, with its 512-byte status text", true}, {"ControlModule", "the surface, touch and resend tables sit inline"}, {"PinsModule", "the 64-claim snapshot table sits inline"}, {"FseqPlayerEffect", "its playlist of tracks sits inline, close enough to the budget that a host's layout decides which side it lands on", true}, @@ -180,8 +182,10 @@ const std::vector& survey() { mm::registerModuleTypes(); // No socket is opened for real: a server module binds, fails and stays idle. mm::platform::setTestBindFails(true); + mm::platform::setTestHub75Pio(mm::platform::Hub75PioMode::Record); // no module lights real panels on a build with the PIO backend std::vector r; for (uint8_t i = 0; i < mm::ModuleFactory::typeCount(); i++) r.push_back(place(i)); + mm::platform::setTestHub75Pio(mm::platform::Hub75PioMode::Off); mm::platform::setTestBindFails(false); return r; }(); diff --git a/test/unit/light/correction_presets.h b/test/unit/light/correction_presets.h index a6a6d5bd..30871ca6 100644 --- a/test/unit/light/correction_presets.h +++ b/test/unit/light/correction_presets.h @@ -1,12 +1,14 @@ #pragma once -/// A test-only convenience for the curated color orders. +/// Test-only conveniences for building a Correction: the curated color orders and a 32-channel moving head. /// /// @technical /// -/// Test-only convenience for building a Correction from a named color order (RGB/GRB/BGR/RGBW/GRBW). -/// The PRODUCTION Correction has one rebuild, rebuild(brightness, ChannelRole* roles, nChannels), because the real wirings come from the FixtureProfiles library as role arrays. The curated-order enum + a rebuild(brightness, preset) overload used to live in Correction.h purely so tests could write `corr.rebuild(255, GRB)` tersely without hand-building a role array. -/// That was a test convenience sitting in production code (zero production callers, and it duplicated "what does GRB mean", which the library's seedBuiltins now owns). It lives here instead: the tests keep the terse form, and Correction.h carries only the one role-array rebuild the device actually uses. +/// The production Correction has one rebuild, rebuild(brightness, ChannelRole* roles, nChannels), because the real wirings come from the FixtureProfiles library as role arrays. +/// +/// The named orders (RGB/GRB/BGR/RGBW/GRBW) live here so a test keeps the terse `rebuildFromPreset(c, 255, PresetOrder::GRB)`; the library's seedBuiltins owns what each order means in production. +/// +/// `WideProfile` places a light's color at channels 9 to 11 of 32, for a case that needs a wiring wider than RGB. #include "light/drivers/Correction.h" #include "light/drivers/ChannelRole.h" @@ -30,4 +32,15 @@ inline void rebuildFromPreset(mm::Correction& c, uint8_t brightness, PresetOrder } } +/// A 32-channel moving head with its color at channels 9 to 11, so correcting one light writes all 32. +struct WideProfile { + ChannelRole roles[32] = {}; ///< every channel's role, unused but the three + /// Red, green and blue at 9, 10 and 11. + WideProfile() { + roles[9] = ChannelRole::Red; + roles[10] = ChannelRole::Green; + roles[11] = ChannelRole::Blue; + } +}; + } // namespace mm diff --git a/test/unit/light/hub75_pi_bench.h b/test/unit/light/hub75_pi_bench.h new file mode 100644 index 00000000..d5fd1fe4 --- /dev/null +++ b/test/unit/light/hub75_pi_bench.h @@ -0,0 +1,166 @@ +#pragma once +/// What the Pi output's tests share: the bench a driver is wired on, the PIO seam's view of what the output opened and handed over, and a rig that runs one driver on the Pi PIO output. + +#include +#include +#include +#include + +#include "correction_presets.h" +#include "doctest.h" +#include "hub75_port.h" // PioPortGuard, PioHost, PioAvailable, optionIndex +#include "light/drivers/Correction.h" +#include "light/drivers/Hub75Driver.h" +#include "light/layers/Buffer.h" +#include "light/layers/Layer.h" +#include "light/layouts/GridLayout.h" +#include "light/layouts/Layouts.h" +#include "light/layouts/PanelsLayout.h" +#include "platform/Hub75Pio.h" +#include "platform/platform.h" + +namespace mm { + +/// A Hub75Driver on a layer of the layouts a case adds, wired as production wires it; declared in destruction-safe order, the layouts before what reads them. +struct Hub75Bench { + mm::Layouts layouts; ///< the layouts the layer reads + mm::GridLayout grid; ///< a raster, for a case that adds it + mm::PanelsLayout panels; ///< panels in cabling order, for a case that adds it + mm::Layer layer; ///< the layer the driver reads + mm::Buffer source; ///< the rendered frame the driver corrects + mm::Hub75Driver driver; ///< the driver under test + + /// Release the driver as its owner does before destroying it, while the layer and the frame it reads still stand, so a case that ends without release() leaves nothing allocated. + ~Hub75Bench() { driver.release(); } + + /// Size the layer from the layouts added, hold `lights` lights of RGB, and bind the driver to both. + void wire(mm::nrOfLightsType lights) { + layouts.applyState(); + layer.setLayouts(&layouts); + layer.setChannelsPerLight(3); + layer.applyState(); + REQUIRE(source.allocate(lights, 3)); + driver.setLayer(&layer); + driver.setSourceBuffer(&source); + } + + /// Open the panels with a linear, full-brightness correction, built in place, so a frame's values read straight. + void open() { + mm::rebuildFromPreset(driver.correctionForTest(), 255, mm::PresetOrder::RGB); + driver.applyState(); + driver.prepare(); + } + + /// Paint light `i` in the rendered frame. + void paint(mm::nrOfLightsType i, uint8_t r, uint8_t g, uint8_t b) { + uint8_t* p = source.data() + static_cast(i) * 3; + p[0] = r; p[1] = g; p[2] = b; + } +}; + +/// The text a read-only text control of `m` shows, empty when there is none. +inline std::string textOf(mm::MoonModule& m, const char* name) { + const int i = mm::controlIndex(m, name); + if (i < 0) return {}; + const char* text = static_cast(m.controls()[static_cast(i)].ptr); + return text ? text : ""; +} + +/// Pick the backend labeled `label` on `driver`'s peripheral select, as the card does, and rebuild the card for it; false when it is not offered. +inline bool pickBackend(mm::Hub75Driver& driver, const char* label) { + driver.defineControls(); // the card as offered, so the select lists what the host has + const int i = mm::optionIndex(driver, "peripheral", label); + if (i < 0) return false; + driver.peripheralSel_ = static_cast(i); + driver.rebuildControls(); // as the scheduler does on a peripheral change, which swaps the output + return true; +} + +/// Make the host answer as `kind` and rebuild `driver`'s card, as a changed machine does: the driver follows the machine to its output. +inline void becomeMachine(mm::Hub75Driver& driver, mm::platform::Machine kind) { + mm::platform::setTestMachine(kind); + driver.rebuildControls(); +} + +/// What the PIO output's tests read from its seam: the output's type and backend, the guard that records, the name the status gives it, and what the seam kept and holds. +struct PioSeam { + using Output = mm::Hub75PioOutput; ///< the output under test + using RecordGuard = mm::PioPortGuard; ///< the guard that makes the seam record + static constexpr const char* backendLabel = "Pi PIO"; ///< the label the peripheral select offers it under + static constexpr const char* label = "PIO"; ///< how the status and the board's refusals name it + static const mm::platform::Hub75PioOptions& options() { return mm::platform::hub75PioTestPort().options; } ///< the options the output opened the engine with + static uint16_t width() { return mm::platform::hub75PioWidth(); } ///< the canvas width the seam holds, 0 when closed + static uint16_t height() { return mm::platform::hub75PioHeight(); } ///< the canvas height the seam holds, 0 when closed + static int frameCount() { return static_cast(mm::platform::hub75PioTestPort().frames); } ///< frames the seam took since it opened + /// Pixel (x, y) of the last frame the seam took, three bytes. + static const uint8_t* pixel(uint16_t x, uint16_t y) { + return mm::platform::hub75PioTestFrame() + (static_cast(y) * width() + x) * 3; + } +}; + +/// A Hub75Driver on one raster or on panels in cabling order, on the heap, on the Pi output `Seam` names, picked by its backend label, not by its offered position. +template +struct PiRig : Hub75Bench { + /// One raster of `width` by `height`, as a single panel's layout is. + PiRig(uint16_t width, uint16_t height, mm::nrOfLightsType lights) { + grid.width = width; + grid.height = height; + grid.depth = 1; + layouts.addChild(&grid); + finish(lights); + } + + /// `across` by `down` panels of `panelW` by `panelH`, chained row by row, each walked `wiring` (0 rows, 1 columns) with `snake` inside: off is what a chained card takes. + PiRig(uint16_t across, uint16_t down, uint16_t panelW, uint16_t panelH, uint8_t wiring, bool snake) { + panels.horizontalPanels = across; + panels.verticalPanels = down; + panels.panelWidth = panelW; + panels.panelHeight = panelH; + panels.wiringOrder = wiring; + panels.snake = snake; + layouts.addChild(&panels); + finish(static_cast(across) * down * panelW * panelH); + driver.panelRows = static_cast(panelH); + driver.panelCols = panelW; + } + + /// A raster of `width` by `height` holding `lights` lights, or as many as the raster has when `lights` is 0. + static std::unique_ptr raster(uint16_t width, uint16_t height, mm::nrOfLightsType lights = 0) { + return std::make_unique(width, height, lights ? lights : static_cast(width) * height); + } + + /// A Panels layout in cabling order, each panel in plain rows unless `snake`. + static std::unique_ptr cabled(uint16_t across, uint16_t down, uint16_t panelW, uint16_t panelH, bool snake = false) { + return std::make_unique(across, down, panelW, panelH, uint8_t{0}, snake); + } + + /// The output the driver selected. + typename Seam::Output& out() { return *static_cast(driver.outputForTest()); } + +private: + void finish(mm::nrOfLightsType lights) { + wire(lights); + REQUIRE(pickBackend(driver, Seam::backendLabel)); // by label, not by position + REQUIRE(driver.outputForTest()->hwBlock() == mm::LedHwBlock::PiHeader); + driver.panelRows = 32; // panels forming a 16x32 canvas, unless a case changes them + driver.panelCols = 16; + driver.panelsPerLane = 1; // one panel per lane, unless a case puts several on one: the card's own default is 2, the wall's + } +}; + +/// A light corrected through a profile of `n` channels, `roles` placing its color, shows its red, green and blue on the panel's first pixel. +template +void showsColorsThrough(const mm::ChannelRole* roles, uint8_t n) { + auto r = PiRig::raster(16, 32); + r->open(); + r->driver.correctionForTest().rebuild(255, roles, n); + r->driver.onCorrectionChanged(); // as the container calls it when the wiring changes + r->paint(0, 10, 20, 30); + r->driver.tick(); + REQUIRE(Seam::frameCount() == 1); + CHECK(Seam::pixel(0, 0)[0] == 10); CHECK(Seam::pixel(0, 0)[1] == 20); CHECK(Seam::pixel(0, 0)[2] == 30); +} + +} // namespace mm + +TYPE_TO_STRING_AS("Pi PIO", mm::PioSeam); diff --git a/test/unit/light/hub75_port.h b/test/unit/light/hub75_port.h index 589e7977..57446977 100644 --- a/test/unit/light/hub75_port.h +++ b/test/unit/light/hub75_port.h @@ -21,6 +21,14 @@ struct PortGuard { ~PortGuard() { platform::setTestHub75(false); } }; +/// The host answers as `kind` for the case, then reads the real machine again. +struct MachineGuard { + /// Answer as `kind`. + explicit MachineGuard(platform::Machine kind) { platform::setTestMachine(kind); } + /// Read the host again. + ~MachineGuard() { platform::clearTestMachine(); } +}; + /// Holds the PIO seam in `mode` for the case, on a host that answers as a Raspberry Pi 5, and leaves the seam closed and off after it, its levers and the stub backend's faults and records back to their start, and the host as it is. struct PioPortGuard { /// Hold the seam in `mode`: the recorder by default. @@ -57,7 +65,7 @@ inline int optionIndex(MoonModule& m, const char* control, const char* label) { REQUIRE(i >= 0); const ControlDescriptor& c = m.controls()[static_cast(i)]; const char* const* options = reinterpret_cast(c.aux); - // int32_t to match the descriptor's own `max`: a uint8_t counter compared against a wider signed type is the narrowing CodeQL flags, and it would never terminate on a select with more options than a byte holds. + // int32_t to match the descriptor's own `max`: a uint8_t counter compared against a wider signed type is the narrowing CodeQL flags, and it would loop forever on a select with more options than a byte holds. for (int32_t k = 0; k < c.max; k++) if (std::strcmp(options[k], label) == 0) return static_cast(k); return -1; diff --git a/test/unit/light/unit_Hub75Canvas.cpp b/test/unit/light/unit_Hub75Canvas.cpp new file mode 100644 index 00000000..5b715977 --- /dev/null +++ b/test/unit/light/unit_Hub75Canvas.cpp @@ -0,0 +1,305 @@ +/// @module Hub75Canvas + +#include "doctest.h" +#include "light/drivers/Hub75Canvas.h" + +#include + +using namespace mm; + +// The expected numbers come from docs/reference/hardware/hub75-refresh.md's formula and tables, worked by hand, and from the placement rule in Hub75Canvas.h; none is read back from the code under test. + +namespace { + +// A 128 by 64 panel's worth of settings: the rows, columns, row addresses, bit planes and, past the default, the LSB time. +PanelSpec panel(uint16_t rows, uint16_t cols, uint16_t scan, uint8_t bits, uint16_t lsb = 130) { + PanelSpec p; + p.rows = rows; p.cols = cols; p.scanRows = scan; p.bits = bits; p.lsbNs = lsb; + return p; +} + +// A PIO-style panel's clocking: no lit time outlasts a row's shift, one clock a pixel at 10 MHz, the latch riding the last clock. +PanelSpec pioClock(uint16_t scan, uint8_t bits, bool encoderHold) { + PanelSpec p; + p.scanRows = scan; p.bits = bits; p.lsbNs = 0; p.shiftTenthsPerPx = 1000; p.latchTenthsNs = 0; p.pairs = 1; p.encoderHold = encoderHold; + return p; +} + +void checkPos(uint32_t i, uint16_t rows, uint16_t cols, uint16_t panelsPerLane, uint16_t x, uint16_t y) { + const CanvasPos p = laneCanvasPos(i, rows, cols, panelsPerLane); + INFO("light " << i << " rows " << rows << " cols " << cols << " panelsPerLane " << panelsPerLane); + CHECK(p.x == x); + CHECK(p.y == y); +} + +} // namespace + +TEST_CASE("Hub75Canvas: one panel's lights run along its rows") { + checkPos(0, 64, 128, 1, 0, 0); + checkPos(1, 64, 128, 1, 1, 0); + checkPos(127, 64, 128, 1, 127, 0); + checkPos(128, 64, 128, 1, 0, 1); + checkPos(8191, 64, 128, 1, 127, 63); +} + +TEST_CASE("Hub75Canvas: the second panel of a lane starts one panel to the right") { + checkPos(8191, 64, 128, 2, 127, 63); + checkPos(8192, 64, 128, 2, 128, 0); + checkPos(8321, 64, 128, 2, 129, 1); + checkPos(16383, 64, 128, 2, 255, 63); +} + +TEST_CASE("Hub75Canvas: six panels as two to a lane, three lanes, fill a 256 by 192 canvas") { + checkPos(0, 64, 128, 2, 0, 0); + checkPos(8192, 64, 128, 2, 128, 0); + checkPos(16384, 64, 128, 2, 0, 64); + checkPos(40960, 64, 128, 2, 128, 128); + checkPos(49151, 64, 128, 2, 255, 191); +} + +TEST_CASE("Hub75Canvas: the same six panels as three to a lane, two lanes, make a 384 by 128 canvas") { + checkPos(0, 64, 128, 3, 0, 0); + checkPos(16384, 64, 128, 3, 256, 0); + checkPos(24576, 64, 128, 3, 0, 64); + checkPos(49151, 64, 128, 3, 383, 127); +} + +TEST_CASE("Hub75Canvas: every light lands on its own cell and the cells fill the canvas exactly") { + struct Config { uint16_t rows, cols; uint32_t panels; uint16_t panelsPerLane; }; + const Config configs[] = {{64, 128, 6, 2}, {64, 128, 6, 3}, {32, 64, 4, 2}, {16, 32, 3, 3}, {8, 16, 5, 1}, {64, 64, 6, 6}}; + for (const Config& c : configs) { + const uint32_t width = static_cast(c.cols) * c.panelsPerLane; + const uint32_t height = static_cast(c.rows) * (c.panels / c.panelsPerLane); + std::vector seen(static_cast(width) * height, false); + bool inside = true, unique = true; + const uint32_t lights = c.panels * c.rows * c.cols; + for (uint32_t i = 0; i < lights; i++) { + const CanvasPos p = laneCanvasPos(i, c.rows, c.cols, c.panelsPerLane); + if (p.x >= width || p.y >= height) { inside = false; continue; } + const size_t cell = static_cast(p.y) * width + p.x; + if (seen[cell]) unique = false; + seen[cell] = true; + } + INFO("rows " << c.rows << " cols " << c.cols << " panels " << c.panels << " panelsPerLane " << c.panelsPerLane); + CHECK(inside); + CHECK(unique); + CHECK(lights == width * height); // as many lights as cells, so unique and inside mean every cell is filled + } +} + +TEST_CASE("Hub75Canvas: refresh falls with lane length, and 8 bits beats 11") { + // 128 by 64 panels at 1/32 scan, the 130 ns default LSB: the page's table. + const uint16_t eight[] = {420, 243, 165, 124, 100, 83}; + const uint16_t eleven[] = {102, 86, 74, 65, 57, 50}; + for (uint32_t n = 1; n <= 6; n++) { + INFO("panels in the lane " << n); + CHECK(hub75PredictedHz(128 * n, panel(0, 0, 32, 8)) == eight[n - 1]); + CHECK(hub75PredictedHz(128 * n, panel(0, 0, 32, 11)) == eleven[n - 1]); + } + CHECK(hub75PredictedHz(256, panel(0, 0, 32, 11, 50)) == 142); // the page's 50 ns figure for two panels +} + +TEST_CASE("Hub75Canvas: an old small panel keeps a long lane fast") { + CHECK(hub75PredictedHz(32 * 15, panel(0, 0, 8, 8)) == 530); // a 32 by 16 panel at 1/8 scan, fifteen on a lane + CHECK(hub75PredictedHz(32 * 30, panel(0, 0, 8, 8)) == 267); +} + +namespace { + +void checkArr(const Arrangement& a, uint16_t panelsPerLane, uint16_t parallel, uint32_t w, uint32_t h, uint16_t hz) { + INFO("arrangement " << a.panelsPerLane << " x " << a.parallel); + CHECK(a.panelsPerLane == panelsPerLane); + CHECK(a.parallel == parallel); + CHECK(a.width == w); + CHECK(a.height == h); + CHECK(a.hz == hz); +} + +} // namespace + +TEST_CASE("Hub75Canvas: six panels are offered wide before deep") { + Arrangement a[4]; + REQUIRE(panelArrangements(6, panel(64, 128, 32, 8), 3, a, 4) == 3); + checkArr(a[0], 2, 3, 256, 192, 243); + checkArr(a[1], 3, 2, 384, 128, 165); + checkArr(a[2], 6, 1, 768, 64, 83); +} + +TEST_CASE("Hub75Canvas: two, four and five panels have the arrangements that use them all") { + Arrangement a[4]; + REQUIRE(panelArrangements(2, panel(64, 128, 32, 8), 3, a, 4) == 2); + checkArr(a[0], 1, 2, 128, 128, 420); + checkArr(a[1], 2, 1, 256, 64, 243); + REQUIRE(panelArrangements(4, panel(64, 128, 32, 8), 3, a, 4) == 2); + checkArr(a[0], 2, 2, 256, 128, 243); + checkArr(a[1], 4, 1, 512, 64, 124); + REQUIRE(panelArrangements(5, panel(64, 128, 32, 8), 3, a, 4) == 1); + checkArr(a[0], 5, 1, 640, 64, 100); +} + +TEST_CASE("Hub75Canvas: the board's lane limit bounds how wide the offer spreads") { + Arrangement a[4]; + REQUIRE(panelArrangements(12, panel(64, 128, 32, 8), 3, a, 4) == 3); + checkArr(a[0], 4, 3, 512, 192, 124); + checkArr(a[1], 6, 2, 768, 128, 83); + checkArr(a[2], 12, 1, 1536, 64, 42); + REQUIRE(panelArrangements(6, panel(64, 128, 32, 8), 1, a, 4) == 1); // one lane only, as a board with one output + checkArr(a[0], 6, 1, 768, 64, 83); +} + +TEST_CASE("Hub75Canvas: no arrangement puts more panels on a lane than the card's panelsPerLane control takes") { + Arrangement a[4]; + REQUIRE(panelArrangements(40, panel(32, 64, 16, 8), 3, a, 4) == 1); // 1 lane of 40 is past kPanelsPerLaneMax + CHECK(a[0].panelsPerLane == 20); + CHECK(a[0].parallel == 2); + CHECK(panelArrangements(41, panel(32, 64, 16, 8), 3, a, 4) == 0); // 41 divides only into a lane of 41 +} + +TEST_CASE("Hub75Canvas: a full buffer stops the list without writing past it") { + Arrangement a[2]; + CHECK(panelArrangements(6, panel(64, 128, 32, 8), 3, a, 2) == 2); +} + +TEST_CASE("Hub75Canvas: keeping the lanes already built means fewer panels or more panels, never a recable") { + KeepLanes k = keepLanes(7, panel(64, 128, 32, 8), 3, 3); + checkArr(k.use, 3, 2, 384, 128, 165); + CHECK(k.spare == 1); + checkArr(k.add, 3, 3, 384, 192, 165); + CHECK(k.added == 2); + + k = keepLanes(5, panel(64, 128, 32, 8), 2, 3); + checkArr(k.use, 2, 2, 256, 128, 243); + CHECK(k.spare == 1); + checkArr(k.add, 2, 3, 256, 192, 243); + CHECK(k.added == 1); + + k = keepLanes(6, panel(64, 128, 32, 8), 4, 3); + checkArr(k.use, 4, 1, 512, 64, 124); + CHECK(k.spare == 2); + checkArr(k.add, 4, 2, 512, 128, 124); + CHECK(k.added == 2); +} + +TEST_CASE("Hub75Canvas: adding panels is not offered past the board's lane limit") { + const KeepLanes k = keepLanes(10, panel(64, 128, 32, 8), 3, 3); + checkArr(k.use, 3, 3, 384, 192, 165); + CHECK(k.spare == 1); + CHECK(k.add.panelsPerLane == 0); // a fourth lane exceeds the board + const KeepLanes fits = keepLanes(6, panel(64, 128, 32, 8), 3, 3); + checkArr(fits.use, 3, 2, 384, 128, 165); + CHECK(fits.spare == 0); + CHECK(fits.add.panelsPerLane == 0); // already a whole number of lanes +} + +TEST_CASE("Hub75Canvas: keeping the lanes caps the panels at what the board's lanes can carry") { + // Six panels in lanes of 2 want three lanes; a board with one carries 2 of them, the other 4 spare. + const KeepLanes k = keepLanes(6, panel(64, 128, 32, 8), 2, 1); + checkArr(k.use, 2, 1, 256, 64, 243); + CHECK(k.spare == 4); + CHECK(k.add.panelsPerLane == 0); +} + +TEST_CASE("Hub75Canvas: the card's LSB time moves every rate the offers quote") { + // Two 128 by 64 panels at 11 bits, the page's own figures: 86 Hz in one lane at the 130 ns default, 142 Hz at 50 ns. + Arrangement a[4]; + REQUIRE(panelArrangements(2, panel(64, 128, 32, 11), 3, a, 4) == 2); + checkArr(a[0], 1, 2, 128, 128, 102); + checkArr(a[1], 2, 1, 256, 64, 86); + REQUIRE(panelArrangements(2, panel(64, 128, 32, 11, 50), 3, a, 4) == 2); + checkArr(a[0], 1, 2, 128, 128, 201); + checkArr(a[1], 2, 1, 256, 64, 142); + const KeepLanes k = keepLanes(3, panel(64, 128, 32, 11, 50), 2, 3); + checkArr(k.use, 2, 1, 256, 64, 142); +} + +// A PIO-style quote (pioClock); the flag says the frame is the in-tree encoder's, so a narrow row's hold words count as shift. +TEST_CASE("Hub75Canvas: where the frame is the encoder's, a narrow row's hold words count as shift and halve its quoted rate") { + // 64 columns at 8 bits: the pass is 129 words, so the frame doubles and the rate halves, 1221 to 606 Hz. + CHECK(hub75PredictedHz(64, pioClock(16, 8, true)) == 606); + CHECK(hub75PredictedHz(64, pioClock(16, 8, false)) == 1221); + // A 16-column row stretches to the same 129-word pass, so it quotes the same rate as the 64-column one. + CHECK(hub75PredictedHz(16, pioClock(16, 8, true)) == 606); + // Two 64-column panels chained are 128 words a row: no hold, so the rate is the shift's own. + CHECK(hub75PredictedHz(128, pioClock(16, 8, true)) == 610); + // The wall's 256-word rows take zero hold words: the flag is a no-op there, 153 Hz either way. + CHECK(hub75PredictedHz(256, pioClock(32, 8, true)) == 153); + CHECK(hub75PredictedHz(256, pioClock(32, 8, false)) == 153); + // The 6-bit 16-word corner in rate terms: the hold stretches the pass 16 to 33 words, so the quote halves. + CHECK(hub75PredictedHz(16, pioClock(16, 6, true)) == 3157); + CHECK(hub75PredictedHz(16, pioClock(16, 6, false)) == 6510); +} + +TEST_CASE("Hub75Canvas: a panel with no shift, latch or lit time quotes the top rate, 65535 Hz") { + PanelSpec spec; + spec.rows = 32; spec.cols = 64; spec.scanRows = 16; spec.bits = 8; spec.lsbNs = 0; + spec.shiftTenthsPerPx = 0; spec.latchTenthsNs = 0; + CHECK(hub75PredictedHz(64, spec) == 65535); +} + +TEST_CASE("Hub75Canvas: an encoder-hold arrangement quotes the stretched rate") { + // One 64 by 32 panel at 8 bits on the PIO output: the arrangement's rate counts the hold words, 606 Hz, not the 1221 the shift alone would quote. + PanelSpec spec; + spec.rows = 32; spec.cols = 64; spec.scanRows = 16; spec.bits = 8; spec.lsbNs = 0; + spec.shiftTenthsPerPx = 1000; spec.latchTenthsNs = 0; spec.pairs = 1; spec.encoderHold = true; + Arrangement a[4]; + REQUIRE(panelArrangements(1, spec, 1, a, 4) == 1); + checkArr(a[0], 1, 1, 64, 32, 606); + // Two of the same panels chained: 128 words a row, no hold, so the rate is the shift's own. + REQUIRE(panelArrangements(2, spec, 1, a, 4) == 1); + checkArr(a[0], 2, 1, 128, 32, 610); + // The same panel with the flag cleared quotes the shift alone. + spec.encoderHold = false; + REQUIRE(panelArrangements(1, spec, 1, a, 4) == 1); + checkArr(a[0], 1, 1, 64, 32, 1221); +} + +namespace { + +// Feed a layout's lights to the walk in index order, as `place(i)` puts them, and say which panel breaks plain rows. +template +uint32_t offPanel(uint16_t rows, uint16_t cols, uint32_t lights, Place place) { + PanelWalk walk(rows, cols); + for (uint32_t i = 0; i < lights; i++) { + const CanvasPos p = place(i); + walk.light(i, p.x, p.y); + } + return walk.firstOffPanel(); +} + +} // namespace + +TEST_CASE("Hub75Canvas: panels laid out in cabling order, each in plain rows, walk true") { + // Six 8 by 16 panels, 2 across and 3 down, chained along each row of panels: the Pi 5 wall in miniature. + CHECK(offPanel(8, 16, 6 * 128, [](uint32_t i) { + const uint32_t k = i / 128, j = i % 128; + return CanvasPos{static_cast((k % 2) * 16 + j % 16), static_cast((k / 2) * 8 + j / 16)}; + }) == PanelWalk::kNone); + // The same panels chained down each column of panels (YX): another cabling, still plain rows inside each panel. + CHECK(offPanel(8, 16, 6 * 128, [](uint32_t i) { + const uint32_t k = i / 128, j = i % 128; + return CanvasPos{static_cast((k / 3) * 16 + j % 16), static_cast((k % 3) * 8 + j / 16)}; + }) == PanelWalk::kNone); +} + +TEST_CASE("Hub75Canvas: a panel mounted mirrored or turned a quarter still walks plain rows in its own orientation") { + CHECK(offPanel(8, 16, 128, [](uint32_t j) { // rows run right to left + return CanvasPos{static_cast(15 - j % 16), static_cast(j / 16)}; + }) == PanelWalk::kNone); + CHECK(offPanel(8, 16, 128, [](uint32_t j) { // portrait: a panel row runs down the picture + return CanvasPos{static_cast(7 - j / 16), static_cast(j % 16)}; + }) == PanelWalk::kNone); +} + +TEST_CASE("Hub75Canvas: one raster across two panels in series breaks the first panel's rows") { + // A 32 by 8 raster: light 16 sits at x 16 of row 0, where the panel's own second row should start. + CHECK(offPanel(8, 16, 256, [](uint32_t i) { return CanvasPos{static_cast(i % 32), static_cast(i / 32)}; }) == 0); +} + +TEST_CASE("Hub75Canvas: a snaked panel breaks plain rows, and the walk names the first such panel") { + const auto snakeSecond = [](uint32_t i) { + const uint32_t k = i / 128, j = i % 128, row = j / 16, col = j % 16; + const uint32_t x = (k == 1 && row % 2 == 1) ? 15 - col : col; // only panel 1 snakes + return CanvasPos{static_cast(k * 16 + x), static_cast(row)}; + }; + CHECK(offPanel(8, 16, 2 * 128, snakeSecond) == 1); +} diff --git a/test/unit/light/unit_Hub75Driver_frame.cpp b/test/unit/light/unit_Hub75Driver_frame.cpp index 2a0d7685..160ec4ef 100644 --- a/test/unit/light/unit_Hub75Driver_frame.cpp +++ b/test/unit/light/unit_Hub75Driver_frame.cpp @@ -1,7 +1,7 @@ /// @module Hub75Driver /// @also Correction -/// Hub75Driver's tick, pinned down to the bit planes without a panel. The host's HUB75 port, opened by the test (`setTestHub75` in platform.h), hands the driver one frame as the ESP32 port does, and each case compares it with what the encoder makes of the colors the panel should show. +/// Hub75Driver's tick, pinned down to the bit planes. The host's HUB75 port, opened by the test (`setTestHub75` in platform.h) in place of a panel, hands the driver one frame as the ESP32 port does, and each case compares it with what the encoder makes of the colors the panel should show. #include "doctest.h" #include "light/drivers/Hub75Driver.h" @@ -22,7 +22,7 @@ namespace { -// 16x32 at the driver's default 1/16 scan, the smallest box that pairs into rows; 6-bit, its default depth. +// The default box, kWidth by kHeight (16 wide, 32 high): the smallest that pairs into rows at the driver's default 1/16 scan; the depth is its default, 6-bit. constexpr uint16_t kWidth = 16; constexpr uint16_t kHeight = 32; @@ -70,7 +70,7 @@ std::unique_ptr rig(uint16_t height = kHeight) { return std::make_unique(height); } -// A 16x32 RGB image, dark but for the one pixel at (x, y). +// An RGB image of kWidth by kHeight pixels, dark but for the one pixel at (x, y); firstDifference reads its height from its size. std::vector onePixel(uint16_t x, uint16_t y, uint8_t r, uint8_t g, uint8_t b) { std::vector rgb(static_cast(kWidth) * kHeight * 3, 0); uint8_t* p = rgb.data() + (static_cast(y) * kWidth + x) * 3; @@ -127,7 +127,7 @@ TEST_CASE("The HUB75 port opens at 6 bit planes and refuses 7, though the encode mm::platform::Hub75Pins pins; CHECK(mm::platform::hub75Init(handle, mm::platform::Hub75Backend::LcdCam, pins, 64, 64, 32, mm::kHub75PortMaxBitDepth)); CHECK_FALSE(mm::platform::hub75Init(handle, mm::platform::Hub75Backend::LcdCam, pins, 64, 64, 32, mm::kHub75PortMaxBitDepth + 1)); - // A refused re-init leaves the port closed, not on the frame it had: nothing to write into, nothing to start. + // A refused re-init leaves the port closed, its buffer and its scan released, where the port had held the earlier frame. CHECK(mm::platform::hub75Buffer(handle) == nullptr); CHECK_FALSE(mm::platform::hub75Start(handle)); mm::platform::hub75Deinit(handle); diff --git a/test/unit/light/unit_Hub75Driver_output.cpp b/test/unit/light/unit_Hub75Driver_output.cpp index 37c7db32..0140293a 100644 --- a/test/unit/light/unit_Hub75Driver_output.cpp +++ b/test/unit/light/unit_Hub75Driver_output.cpp @@ -7,6 +7,8 @@ #include "../core/conditional_controls.h" // mm::isHidden, mm::isVisible, mm::controlIndex #include "core/module/Control.h" #include "hub75_port.h" +#include "light/drivers/Correction.h" +#include "correction_presets.h" // rebuildFromPreset #include "light/drivers/Hub75Driver.h" #include "light/layers/Buffer.h" #include "platform/Hub75Bus.h" // kHub75PortMaxBitDepth @@ -16,6 +18,7 @@ #include #include #include +#include namespace { @@ -36,6 +39,77 @@ struct WiredDriver { ~WiredDriver() { driver.release(); } }; +// An output that counts what the driver asks of it, in place of the bus output, to pin how often the driver calls across the interface. +struct CountingOutput : mm::Hub75Output { + size_t count = 16u * 32u; // the lights it answers + mutable size_t lightsCalls = 0; // counted from const lights() + size_t shows = 0; + size_t probe = 0; // the light whose red show() records + uint8_t probeRed = 0; // the red of light `probe` in the last frame shown + const char* warn = nullptr; // the warning it answers, null while healthy + + void addWiringControls(mm::ControlList&) override {} + void addControls(mm::ControlList&) override {} + bool onControlChanged(const char*) override { return false; } + bool affectsPrepare(const char*) const override { return false; } + mm::DepthRange depthRange() const override { return {2, 6}; } + size_t frameBytes(uint16_t, uint16_t) const override { return 0; } + const char* open(uint16_t, uint16_t) override { return nullptr; } + const char* describe() const MM_NONBLOCKING override { return "counting"; } + const char* warning() const MM_NONBLOCKING override { return warn; } + size_t lights() const MM_NONBLOCKING override { lightsCalls++; return count; } + void show(const uint8_t* rgb, uint8_t) MM_NONBLOCKING override { shows++; probeRed = rgb[probe * 3]; } + void tick1s() MM_NONBLOCKING override {} + void close() override {} + mm::LedHwBlock hwBlock() const override { return mm::LedHwBlock::LcdCam; } + uint8_t fixedPins(mm::MoonModule::FixedPin*, uint8_t) const override { return 0; } +}; + +// A driver on a 16 x 32 wall over a counting output, on the heap since a driver and a layer outgrow a test's stack frame; the driver is unprepared. +struct CountedDriver { + mm::Wall wall{16, 32}; + mm::Buffer source; + mm::Hub75Driver driver; + CountingOutput out; + + CountedDriver() { + REQUIRE(source.allocate(16 * 32, 3)); + driver.outputForTest() = &out; + driver.setLayer(&wall.layer); + driver.setSourceBuffer(&source); + mm::Correction correction; + mm::rebuildFromPreset(correction, 255, mm::PresetOrder::RGB); + driver.correctionForTest() = correction; + } + ~CountedDriver() { driver.release(); } +}; + +// The status a healthy 16x32 panel shows on the bus. +const char* const kHealthyStatus = "16x32, 1/16 scan, 6-bit (LCD_CAM)"; +// A driver on the bus in that layout, opened. +std::unique_ptr runningWiredDriver() { + auto w = std::make_unique(); + REQUIRE(w->driver.severity() == mm::MoonModule::Severity::Status); + return w; +} + +// Wire `d` for a light of 32 channels under a heap that refuses the scratch for one light, which the status says. +void wideWiringShort(mm::Hub75Driver& d) { + const mm::WideProfile wide; + mm::RefuseAbove refuse(16); // the 32-byte scratch is refused + d.correctionForTest().rebuild(255, wide.roles, 32); + d.onCorrectionChanged(); +} + +// Give `d` a gain, which asks for tables, under a heap that refuses them, which the status says. +void gainsShort(mm::Hub75Driver& d) { + d.correctionForTest().gainGreen = 128; + mm::RefuseAbove refuse(512); // the gained tables, four rows of 256 bytes, are refused + d.rebuildCorrection(255); +} + +const char* const kNoLightText = "not enough memory for one light of this fixture"; + const char* const kPinNames[] = {"r1", "g1", "b1", "r2", "g2", "b2", "a", "b", "c", "d", "e", "clk", "lat", "oe"}; } // namespace @@ -193,6 +267,43 @@ TEST_CASE("Hub75Driver publishes the measured refresh on its one-second tick whi CHECK(std::string(refresh) == "60 Hz"); } +TEST_CASE("Hub75Driver reads its output's lights once, in prepare(), and a frame costs the output's show() alone") { + auto w = std::make_unique(); + w->driver.prepare(); + REQUIRE(w->driver.severity() == mm::MoonModule::Severity::Status); + CHECK(w->out.lightsCalls == 1); + w->source.data()[0] = 200; + for (int frame = 0; frame < 5; frame++) w->driver.tick(); + CHECK(w->out.shows == 5); + CHECK(w->out.probeRed == 200); + CHECK(w->out.lightsCalls == 1); // five frames later, still the prepare()'s one + w->driver.onCorrectionChanged(); + CHECK(w->out.lightsCalls == 1); +} + +TEST_CASE("Hub75Driver reads its output's lights again on every prepare, and the next frame has the new length") { + auto w = std::make_unique(); + w->out.count = 16u * 16u; + w->driver.prepare(); + REQUIRE(w->driver.severity() == mm::MoonModule::Severity::Status); + CHECK(w->out.lightsCalls == 1); + CHECK(w->driver.dynamicBytes() == 16u * 16u * 3u); + w->out.count = 16u * 32u; // the box the output opens at has grown + w->driver.prepare(); + REQUIRE(w->driver.severity() == mm::MoonModule::Severity::Status); + CHECK(w->out.lightsCalls == 2); + REQUIRE(w->driver.dynamicBytes() == 16u * 32u * 3u); // the scratch holds the new frame, so the frame below stays inside it + w->out.probe = 300; // a light past the first box + w->source.data()[300 * 3] = 99; + w->driver.tick(); + CHECK(w->out.probeRed == 99); + CHECK(w->out.lightsCalls == 2); +} + +TEST_CASE("Hub75BusOutput is final, so a call whose static type is the bus output resolves without dispatch") { + CHECK(std::is_final_v); +} + TEST_CASE("Hub75Driver sizes its correction scratch to one RGB frame of the layout's box") { mm::PortGuard guard; auto w = std::make_unique(); // 16 x 32 lights, three bytes each @@ -274,6 +385,25 @@ TEST_CASE("Hub75Driver asks the platform about the bytes its layout takes, and n CHECK(mm::platform::hub75TestPort().offeredBytes == 0); } +TEST_CASE("Hub75Driver offers 48 rows at 1/8 scan and refuses them at 1/16, so the scan select reaches the geometry") { + // 48 rows leave 6 rows a scan at 1/8, which pair, and 3 at 1/16, which do not; the select alone changes which. A height of 24 pairs at no scan and 32 pairs at 1/8 and 1/16 alike, so of 24, 32 and 48 only 48 shows that. + mm::PortGuard guard; + auto w = std::make_unique(48); // the default 1/16 scan + CHECK(w->driver.severity() == mm::MoonModule::Severity::Error); + CHECK(mm::platform::hub75TestPort().offeredBytes == 0); + w->driver.scanSel = 0; + w->driver.rebuildControls(); + CHECK(mm::platform::hub75TestPort().offeredBytes > 0); + w->driver.prepare(); + CHECK(w->driver.severity() == mm::MoonModule::Severity::Status); + CHECK(std::string(w->driver.status()) == "16x48, 1/8 scan, 6-bit (LCD_CAM)"); + w->driver.scanSel = 1; + w->driver.rebuildControls(); + CHECK(mm::platform::hub75TestPort().offeredBytes == 0); + w->driver.prepare(); + CHECK(w->driver.severity() == mm::MoonModule::Severity::Error); +} + TEST_CASE("Hub75Driver releases the panel's peripheral when it stops, and when the scan will not start") { mm::PortGuard guard; auto w = std::make_unique(); @@ -311,3 +441,121 @@ TEST_CASE("Hub75Driver releases the panel's peripheral when the memory for one l CHECK(d.hwBlock() == mm::LedHwBlock::None); CHECK(mm::platform::hub75TestPort().deinits == before + 2); // the reinit's stop, then the close after the refusal } + +TEST_CASE("Hub75Driver keeps a light-memory shortage on its status through the one-second tick, and shows the panel's status once the shortage ends") { + mm::PortGuard guard; + auto w = runningWiredDriver(); + mm::Hub75Driver& d = w->driver; + wideWiringShort(d); + CHECK(d.severity() == mm::MoonModule::Severity::Error); + CHECK(std::string(d.status()) == kNoLightText); + d.tick1s(); + CHECK(d.severity() == mm::MoonModule::Severity::Error); + CHECK(std::string(d.status()) == kNoLightText); + + mm::rebuildFromPreset(d.correctionForTest(), 255, mm::PresetOrder::RGB); // an RGB wiring, which corrects straight into the frame + d.onCorrectionChanged(); + CHECK(d.severity() == mm::MoonModule::Severity::Status); + CHECK(std::string(d.status()) == kHealthyStatus); +} + +TEST_CASE("Hub75Driver retries the light scratch at the same width once memory is back, and shows the panel's status") { + mm::PortGuard guard; + auto w = runningWiredDriver(); + mm::Hub75Driver& d = w->driver; + wideWiringShort(d); + REQUIRE(std::string(d.status()) == kNoLightText); + const mm::WideProfile wide; + d.correctionForTest().rebuild(255, wide.roles, 32); // the same 32 channels, with the memory back + d.onCorrectionChanged(); + CHECK(d.severity() == mm::MoonModule::Severity::Status); + CHECK(std::string(d.status()) == kHealthyStatus); + CHECK(d.dynamicBytes() == 16u * 32u * 3u + 32u); +} + +TEST_CASE("Hub75Driver keeps the gain-memory warning on its status through a prepare and the one-second tick, and shows the panel's status once the gains fit") { + mm::PortGuard guard; + auto w = runningWiredDriver(); + mm::Hub75Driver& d = w->driver; + gainsShort(d); + CHECK(d.severity() == mm::MoonModule::Severity::Warning); + CHECK(std::string(d.status()).find("color balance") != std::string::npos); + d.prepare(); // the order production runs: the rebuild first, then the prepare + CHECK(d.severity() == mm::MoonModule::Severity::Warning); + CHECK(std::string(d.status()).find("color balance") != std::string::npos); + d.tick1s(); + CHECK(d.severity() == mm::MoonModule::Severity::Warning); + CHECK(std::string(d.status()).find("color balance") != std::string::npos); + + d.rebuildCorrection(255); // the memory is back, so the gains apply and the warning leaves + d.tick1s(); + CHECK(d.severity() == mm::MoonModule::Severity::Status); + CHECK(std::string(d.status()) == kHealthyStatus); +} + +TEST_CASE("Hub75Driver shows the output's warning over the gain warning, and the gain warning again once the output's ends, the same each second") { + auto w = std::make_unique(); + mm::Hub75Driver& d = w->driver; + d.prepare(); + gainsShort(d); + const std::string gains = d.status(); + REQUIRE(d.severity() == mm::MoonModule::Severity::Warning); + w->out.warn = "the output is stalled"; + for (int second = 0; second < 2; second++) { + d.tick1s(); + CHECK(std::string(d.status()) == "the output is stalled"); + } + w->out.warn = nullptr; + for (int second = 0; second < 2; second++) { + d.tick1s(); + CHECK(std::string(d.status()) == gains); + } + d.rebuildCorrection(255); // the gains fit, so only the output's own status remains + d.tick1s(); + CHECK(std::string(d.status()) == "counting"); +} + +TEST_CASE("Hub75Driver keeps the missing light scratch's error over the output's warning, and over the output's status after it ends") { + auto w = std::make_unique(); + mm::Hub75Driver& d = w->driver; + d.prepare(); + wideWiringShort(d); + w->out.warn = "the output is stalled"; + d.tick1s(); + CHECK(d.severity() == mm::MoonModule::Severity::Error); + CHECK(std::string(d.status()) == kNoLightText); + w->out.warn = nullptr; + d.tick1s(); + CHECK(std::string(d.status()) == kNoLightText); +} + +TEST_CASE("Hub75Driver's memory readout is the frame and the light scratch while it runs, and 0 after a release, for a wiring of 32 channels") { + mm::PortGuard guard; + auto w = runningWiredDriver(); + mm::Hub75Driver& d = w->driver; + CHECK(d.dynamicBytes() == 16u * 32u * 3u); + const mm::WideProfile wide; + d.correctionForTest().rebuild(255, wide.roles, 32); + d.onCorrectionChanged(); + CHECK(d.dynamicBytes() == 16u * 32u * 3u + 32u); // the frame and one 32-channel light + d.prepare(); // a prepare keeps the scratch and the readout + CHECK(d.dynamicBytes() == 16u * 32u * 3u + 32u); + d.release(); + CHECK(d.dynamicBytes() == 0); +} + +TEST_CASE("Hub75Driver's memory readout counts the gained tables and the 16-bit tables beside the frame, and returns to 0 after a release") { + mm::PortGuard guard; + auto w = runningWiredDriver(); + mm::Hub75Driver& d = w->driver; + d.correctionForTest().gainGreen = 128; + d.rebuildCorrection(255); + d.prepare(); + CHECK(d.dynamicBytes() == 16u * 32u * 3u + 4u * 256u); // the frame and four gained rows of 256 bytes + d.correctionForTest().wide = true; + d.rebuildCorrection(255); + d.prepare(); + CHECK(d.dynamicBytes() == 16u * 32u * 3u + 4u * 256u + 2u * (256u + 4u * 256u)); // and the 16-bit curve and its gained rows + d.release(); + CHECK(d.dynamicBytes() == 0); +} diff --git a/test/unit/light/unit_Hub75Driver_pi.cpp b/test/unit/light/unit_Hub75Driver_pi.cpp new file mode 100644 index 00000000..debaf877 --- /dev/null +++ b/test/unit/light/unit_Hub75Driver_pi.cpp @@ -0,0 +1,463 @@ +/// @module Hub75Driver +/// @also Hub75PioOutput, DriverBase + +/// What Hub75Driver does with a Raspberry Pi's PIO beside the bus: the settings a saved card keeps, the output it swaps to and back, the peripheral one sibling drives refused to the next, and what its status says while the panels run and after they stop. The Pi output's own behavior is in unit_Hub75PioOutput.cpp and unit_Hub75PiOutput.cpp; the bus output's is in unit_Hub75Driver_output.cpp. + +#include "doctest.h" +#include "core/module/Scheduler.h" +#include "core/module/StateDocument.h" +#include "core/util/JsonSink.h" +#include "../core/conditional_controls.h" // mm::isHidden, mm::isVisible +#include "light/drivers/Hub75Driver.h" +#ifdef MM_HUB75_PIO_HAS_ENGINE // the stub backend and the engine are built where the compiler takes them (the root CMakeLists.txt) + #include "platform/rpi/hub75_pio_backend_stub.h" + #include "../core/hub75_engine_bench.h" + #include + #include +#endif +#include "hub75_pi_bench.h" + +#include +#include +#include + +namespace { + +// A driver in a running tree, so a stored document applies to it as a boot does; on the heap, past a test's frame limit. +struct Booted { + mm::Scheduler scheduler; + mm::Hub75Driver* driver = new mm::Hub75Driver(); // the scheduler owns it, as the module owner does, and releases and deletes it with the tree + + Booted() { + driver->setTypeName("Hub75Driver"); + driver->setName("Hub75Driver"); + scheduler.addModule(driver); + scheduler.setup(); + } + + /// Apply a stored document, as a boot does. + bool apply(const std::string& doc) { return mm::applyStateDocument(scheduler, doc.c_str(), mm::StateSource::Stored).ok; } + + /// The driver as a state document, the bytes a save writes. + std::string saved() { + mm::JsonSink sink; + sink.append("{"); + mm::writeStateMember(sink, *driver, false); + sink.append("}"); + return std::string(sink.data(), sink.size()); + } +}; + +// The PIO card as a user saved it: a small wall at 20 MHz with two blank words at 8 bits. +const char* const kSavedPioCard = + "{\"Hub75Driver\":{\"peripheral\":0,\"rows\":32,\"cols\":64,\"panelsPerLane\":1,\"pixelClock\":20000,\"latchBlank\":2,\"bitDepth\":8}}"; + +bool has(const std::string& doc, const char* text) { return doc.find(text) != std::string::npos; } + +// The label the select `name` shows for the option it holds. +std::string textOfSelect(mm::MoonModule& m, const char* name) { + const int i = mm::controlIndex(m, name); + if (i < 0) return {}; + const mm::ControlDescriptor& c = m.controls()[static_cast(i)]; + const char* const* options = reinterpret_cast(c.aux); + return options[*static_cast(c.ptr)]; +} + +// Two HUB75 drivers under one container on a 16x32 layout, the box the default 1/16 scan pairs into rows; on the heap, since drivers and a layer outgrow a test's stack frame. +struct Siblings { + mm::MoonModule owner; + mm::Layouts layouts; + mm::GridLayout grid; + mm::Layer layer; + mm::Buffer source; + mm::Hub75Driver first; + mm::Hub75Driver second; + + Siblings() { + grid.width = 16; + grid.height = 32; + grid.depth = 1; + layouts.addChild(&grid); + layouts.applyState(); + layer.setLayouts(&layouts); + layer.setChannelsPerLight(3); + layer.applyState(); + REQUIRE(source.allocate(16 * 32, 3)); + for (mm::Hub75Driver* d : {&first, &second}) { + owner.addChild(d); + d->setLayer(&layer); + d->setSourceBuffer(&source); + mm::Correction correction; + mm::rebuildFromPreset(correction, 255, mm::PresetOrder::RGB); + d->correctionForTest() = correction; + d->applyState(); + } + } + // The owner releases a driver before destroying it, which frees what prepare() allocated. + ~Siblings() { + for (mm::Hub75Driver* d : {&first, &second}) { + d->release(); + owner.removeChild(d); + } + } +}; + +// A 16x32 raster on the Pi PIO output, opened and showing its plain status; the seam is the caller's guard's. +std::unique_ptr> openedHealthyRaster() { + auto r = mm::PiRig::raster(16, 32); + r->open(); + REQUIRE(r->driver.severity() == mm::MoonModule::Severity::Status); + return r; +} + +bool says(const mm::MoonModule& m, const char* text) { + return m.status() && std::strstr(m.status(), text) != nullptr; +} + +} // namespace + +TEST_CASE("Hub75Driver reloads a saved Pi PIO card unchanged") { + mm::PioPortGuard guard; + auto first = std::make_unique(); + REQUIRE(first->apply(kSavedPioCard)); + CHECK(first->driver->panelRows == 32); + CHECK(first->driver->panelCols == 64); + CHECK(first->driver->panelsPerLane == 1); + CHECK(first->driver->pixelClockKhz == 20000); + CHECK(first->driver->latchBlankWords == 2); + CHECK(first->driver->bitDepth == 8); + CHECK(first->driver->selectedBackend() == mm::platform::Hub75Backend::Pio); + + const std::string doc = first->saved(); + for (const char* kept : {"\"rows\":32", "\"cols\":64", "\"panelsPerLane\":1", "\"pixelClock\":20000", "\"latchBlank\":2", "\"bitDepth\":8"}) { + CAPTURE(kept); + CHECK(has(doc, kept)); + } + auto second = std::make_unique(); // a restart: the saved bytes, as written, into a fresh driver + REQUIRE(second->apply(doc)); + CHECK(second->saved() == doc); +} + +TEST_CASE("Hub75Driver on a Pi 5 keeps the PIO output when the PIO refuses, shows why, and loses no saved setting, the 8-bit depth included") { + std::string doc; + { + mm::PioPortGuard guard; + auto booted = std::make_unique(); + REQUIRE(booted->apply(kSavedPioCard)); + doc = booted->saved(); + } + { + // The next boot finds the PIO refused (a stall kernel, a missing node, no permission): the machine is still a Pi 5, so the PIO output stays and says why. + mm::PioPortGuard refusing; // a Pi 5 whose PIO the seam refuses, for a reason the case names + mm::platform::setTestHub75PioOpenFails(true); + auto refused = std::make_unique(); + REQUIRE(refused->apply(doc)); + CHECK(refused->driver->selectedBackend() == mm::platform::Hub75Backend::Pio); + CHECK(refused->driver->hwBlock() == mm::LedHwBlock::None); // the output refused, so no block is held + CHECK(mm::platform::hub75PioWidth() == 0); + const std::string saved = refused->saved(); + CHECK(saved == doc); // every setting survives untouched + CHECK(has(saved, "\"bitDepth\":8")); + for (const char* name : {"rows", "cols", "panelsPerLane", "pixelClock", "latchBlank", "bitDepth"}) { + CAPTURE(name); + CHECK(mm::isVisible(*refused->driver, name)); // the Pi card, not the bus's + } + } + { + mm::PioPortGuard guard; // the PIO is back + auto back = std::make_unique(); + REQUIRE(back->apply(doc)); + CHECK(back->saved() == doc); + CHECK(back->driver->bitDepth == 8); + } +} + +TEST_CASE("Hub75Driver on a Pi 5 whose PIO refuses shows the refusal as its status") { + mm::PioPortGuard guard; + mm::platform::setTestHub75PioOpenFails(true); // the seam refuses with its reason + auto r = mm::PiRig::raster(16, 32); + r->open(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Error); + CHECK(std::string(r->driver.status()) == "the test seam refuses the open"); + CHECK(r->driver.selectedBackend() == mm::platform::Hub75Backend::Pio); + CHECK(std::string(r->driver.status()).find("HUB75 needs an ESP32") == std::string::npos); // the PIO's reason, not the bus's +} + +TEST_CASE("Hub75Driver on an earlier Pi shows the Pi card and a refusal, and keeps every setting") { + mm::MachineGuard pi4(mm::platform::Machine::PiGpio); + auto booted = std::make_unique(); + REQUIRE(booted->apply(kSavedPioCard)); + CHECK(std::string(mm::platform::hub75BackendLabel(booted->driver->selectedBackend())) == "Pi PIO"); // the Pi card's output, named none in the select + CHECK(textOfSelect(*booted->driver, "peripheral") == "(none)"); + CHECK(mm::isVisible(*booted->driver, "rows")); + CHECK(booted->driver->bitDepth == 8); + const std::string saved = booted->saved(); + for (const char* kept : {"\"rows\":32", "\"cols\":64", "\"panelsPerLane\":1", "\"pixelClock\":20000", "\"latchBlank\":2", "\"bitDepth\":8"}) { + CAPTURE(kept); + CHECK(has(saved, kept)); + } + // A layout for it to prepare on: the refusal, not an open. + auto bench = std::make_unique(); + bench->grid.width = 16; + bench->grid.height = 32; + bench->grid.depth = 1; + bench->layouts.addChild(&bench->grid); + bench->wire(16 * 32); + bench->driver.defineControls(); + bench->driver.panelRows = 32; + bench->driver.panelCols = 16; + bench->driver.panelsPerLane = 1; + bench->open(); + CHECK(bench->driver.severity() == mm::MoonModule::Severity::Error); + CHECK(std::string(bench->driver.status()) == "HUB75 in this build needs a Pi 5's PIO"); + CHECK(bench->driver.hwBlock() == mm::LedHwBlock::None); +} + +TEST_CASE("Hub75Driver on another host takes the bus output and its own refusal, the Pi settings hidden and kept") { + mm::MachineGuard other(mm::platform::Machine::Other); + auto booted = std::make_unique(); + CHECK(booted->driver->outputForTest()->hwBlock() != mm::LedHwBlock::PiHeader); + REQUIRE(booted->apply(kSavedPioCard)); + for (const char* name : {"rows", "cols", "panelsPerLane", "pixelClock", "latchBlank"}) { + CAPTURE(name); + CHECK(mm::isHidden(*booted->driver, name)); + } + const std::string saved = booted->saved(); + CHECK(has(saved, "\"rows\":32")); + CHECK(has(saved, "\"pixelClock\":20000")); + CHECK(has(saved, "\"bitDepth\":6")); // the bus's range clamps the depth +} + +TEST_CASE("Hub75Driver on an ESP32 offers the bus backends and falls back within them") { + mm::MachineGuard esp(mm::platform::Machine::Esp32); + { + mm::PortGuard port(true); // LCD_CAM and Parlio both + auto r = std::make_unique(); + CHECK(textOfSelect(*r->driver, "peripheral") == "LCD_CAM"); + const int parlio = mm::optionIndex(*r->driver, "peripheral", "Parlio"); + REQUIRE(parlio >= 0); + CHECK(mm::optionIndex(*r->driver, "peripheral", "Pi PIO") == -1); // an ESP32 lists its bus backends only + r->driver->peripheralSel_ = static_cast(parlio); + r->driver->rebuildControls(); + CHECK(r->driver->selectedBackend() == mm::platform::Hub75Backend::Parlio); + CHECK(r->driver->outputForTest()->hwBlock() == mm::LedHwBlock::Parlio); + r->driver->peripheralSel_ = 9; // a select past the options answers the first on offer + CHECK(r->driver->selectedBackend() == mm::platform::Hub75Backend::LcdCam); + } + { + mm::PortGuard port(false); // the silicon has LCD_CAM alone: a saved Parlio finds it gone and takes the first + auto r = std::make_unique(); + CHECK(mm::optionIndex(*r->driver, "peripheral", "Parlio") == -1); + CHECK(r->driver->selectedBackend() == mm::platform::Hub75Backend::LcdCam); + } +} + +TEST_CASE("Hub75Driver holds both outputs by value, so its size and memory readout count them") { + // The bus output and the PIO output are members side by side, the PIO output an empty type where no Pi 5 can run it. + CHECK(sizeof(mm::Hub75Driver) >= sizeof(mm::DriverBase) + sizeof(mm::Hub75BusOutput) + (mm::platform::hasHub75Pio ? sizeof(mm::Hub75PioOutput) : 0)); + mm::PioPortGuard guard; + auto r = mm::PiRig::cabled(2, 1, 16, 32); // two 16x32 panels in one lane: a canvas to count + r->driver.panelsPerLane = 2; + r->open(); + REQUIRE(r->driver.severity() == mm::MoonModule::Severity::Status); + CHECK(r->driver.dynamicBytes() == 2 * 1024 * 3); // the frame and the canvas, counted once each +} + +TEST_CASE("Hub75Driver moves its depth into the new output's range when the machine changes its output") { + mm::PortGuard bus; + mm::PioPortGuard guard; // a Pi 5 + auto r = mm::PiRig::raster(16, 32); + r->driver.bitDepth = 8; // the PIO's range reaches 8 + becomeMachine(r->driver, mm::platform::Machine::Other); + CHECK(r->driver.selectedBackend() == mm::platform::Hub75Backend::LcdCam); + CHECK(r->driver.bitDepth == mm::kHub75PortMaxBitDepth); // the bus takes 6: the swap clamps, so hub75Init gets 6 at most + becomeMachine(r->driver, mm::platform::Machine::Pi5); + CHECK(r->driver.selectedBackend() == mm::platform::Hub75Backend::Pio); + CHECK(r->driver.bitDepth == mm::kHub75PortMaxBitDepth); // and does not climb back by itself + const int depth = mm::controlIndex(r->driver, "bitDepth"); + REQUIRE(depth >= 0); + CHECK(r->driver.controls()[static_cast(depth)].max == mm::kHub75EncodeMaxBitDepth); +} + +TEST_CASE("Hub75Driver quiesces the render worker before it swaps outputs, and prepares as a whole tree") { + static int quiesced; + quiesced = 0; + mm::MoonModule::setQuiesceRenderHook([] { quiesced++; }); + mm::PortGuard bus; + mm::PioPortGuard guard; + auto r = mm::PiRig::raster(16, 32); + r->open(); + quiesced = 0; + becomeMachine(r->driver, mm::platform::Machine::Other); + CHECK(quiesced >= 1); // the encode worker reads the output in tick(), so it stops before the output moves + CHECK(r->driver.hwBlock() == mm::LedHwBlock::None); // and the Pi output closed + // The default scope re-prepares the parent and its children, which joins the encode worker before an output closes; a driver scoped to itself would not. + CHECK(r->driver.prepareScope() == mm::PrepareScope::Tree); + mm::MoonModule::setQuiesceRenderHook(nullptr); +} + +TEST_CASE("Hub75Driver shows the frames the PIO shows each second") { + mm::PioPortGuard guard; + auto r = mm::PiRig::raster(16, 32); + r->open(); + mm::platform::setTestHub75PioFps(61); + r->driver.tick1s(); + CHECK(textOf(r->driver, "shown") == "61 fps"); + r->driver.release(); + CHECK(textOf(r->driver, "shown").empty()); +} + +TEST_CASE("Hub75Driver warns while the PIO's submits are failing, and says nothing once they stop") { + mm::PioPortGuard guard; + auto r = openedHealthyRaster(); + r->driver.tick1s(); // the count the seam starts at + + mm::platform::setTestHub75PioSubmitErrors(3); + r->driver.tick1s(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Warning); + CHECK(std::string(r->driver.status()).find("the PIO is failing: 3 submits failed") != std::string::npos); + + mm::platform::setTestHub75PioSubmitErrors(5); // still rising + r->driver.tick1s(); + CHECK(std::string(r->driver.status()).find("5 submits failed") != std::string::npos); + + r->driver.tick1s(); // no new failures in the last second + CHECK(r->driver.severity() == mm::MoonModule::Severity::Status); + CHECK(std::string(r->driver.status()) == "16x32, 6-bit, PIO"); +} + +TEST_CASE("Hub75Driver warns while a submit is stalled, alone, and says nothing once it returns") { + mm::PioPortGuard guard; + auto r = openedHealthyRaster(); + mm::platform::setTestHub75PioStalled(true); + mm::platform::setTestHub75PioSubmitErrors(4); // failures too: the stall, the graver, shows + r->driver.tick1s(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Warning); + CHECK(std::string(r->driver.status()).find("the PIO is stalled") != std::string::npos); + CHECK(std::string(r->driver.status()).find("failing") == std::string::npos); + mm::platform::setTestHub75PioStalled(false); + r->driver.tick1s(); // the submit returned, and no failure rose since + CHECK(r->driver.severity() == mm::MoonModule::Severity::Status); +} + +TEST_CASE("Hub75Driver joins the failing submits to the warnings it already shows, none hiding another") { + mm::PioPortGuard guard; + auto r = mm::PiRig::raster(20, 40); // a raster wider than the panel: the walk's warning + r->open(); + const std::string before = r->driver.status(); + REQUIRE(r->driver.severity() == mm::MoonModule::Severity::Warning); + r->driver.tick1s(); + mm::platform::setTestHub75PioSubmitErrors(2); + r->driver.tick1s(); + const std::string failing = r->driver.status(); + CHECK(failing.rfind(before, 0) == 0); // what was there stays first, whole + CHECK(failing.find("; the PIO is failing: 2 submits failed") != std::string::npos); +} + +TEST_CASE("Hub75Driver warns of a pixel clock past the 20 MHz the bench ran, built from the seam's constant") { + mm::PioPortGuard guard; + auto r = mm::PiRig::raster(16, 32); + r->driver.pixelClockKhz = 25000; + r->open(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Warning); + CHECK(std::string(r->driver.status()).find("above 20 MHz") != std::string::npos); +} + +#ifdef MM_HUB75_PIO_HAS_ENGINE // a stuck submit needs the engine on the stub backend +TEST_CASE("Hub75Driver says why a close the kernel never let finish left the PIO held") { + mm::PioPortGuard guard(mm::platform::Hub75PioMode::Stub); + mm::platform::setTestHub75PioJoinDeadlineMs(100); + auto r = mm::PiRig::raster(16, 32); + r->open(); + REQUIRE(r->driver.severity() == mm::MoonModule::Severity::Status); + REQUIRE(mm::test::waitUntil([] { return mm::platform::stubBackendSubmittedFrames() > 0; })); + mm::test::hangSubmits(); + + r->driver.release(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Warning); + CHECK(std::string(r->driver.status()).find("did not return") != std::string::npos); + + mm::platform::stubBackendSetFaults({}); // the kernel lets the submit go + CHECK(mm::test::waitUntil([&] { // the next prepare closes it for good, then opens + r->driver.prepare(); + return r->driver.severity() == mm::MoonModule::Severity::Status; + })); +} +#endif + +TEST_CASE("Hub75Driver stays idle and names why while a sibling driver drives its peripheral") { + mm::PortGuard guard; + auto s = std::make_unique(); + s->first.prepare(); + REQUIRE(s->first.hwBlock() == mm::LedHwBlock::LcdCam); + + s->second.prepare(); + CHECK(says(s->second, "already in use by another driver")); + CHECK(s->second.severity() == mm::MoonModule::Severity::Error); + CHECK(s->second.hwBlock() == mm::LedHwBlock::None); + CHECK(s->first.hwBlock() == mm::LedHwBlock::LcdCam); +} + +TEST_CASE("Hub75Driver takes the peripheral once the sibling driving it releases it") { + mm::PortGuard guard; + auto s = std::make_unique(); + s->first.prepare(); + s->second.prepare(); + REQUIRE(s->second.hwBlock() == mm::LedHwBlock::None); + + s->first.release(); + CHECK(s->first.hwBlock() == mm::LedHwBlock::None); + s->second.prepare(); + CHECK(says(s->second, "1/16 scan")); + CHECK(s->second.hwBlock() == mm::LedHwBlock::LcdCam); +} + +TEST_CASE("Hub75Driver gives the Pi's header to the first of two drivers that prepare, and the second keeps idle") { + mm::PioPortGuard guard; + auto s = std::make_unique(); + for (mm::Hub75Driver* d : {&s->first, &s->second}) { + REQUIRE(pickBackend(*d, "Pi PIO")); + d->panelRows = 32; // one 16x32 panel on a lane, the layout's own box + d->panelCols = 16; + d->panelsPerLane = 1; + } + s->second.prepare(); // the order of the prepares decides, not the order of the siblings + REQUIRE(s->second.hwBlock() == mm::LedHwBlock::PiHeader); + s->first.prepare(); + CHECK(says(s->first, "already in use by another driver")); + CHECK(s->first.hwBlock() == mm::LedHwBlock::None); + s->second.release(); + s->first.prepare(); // and once the holder lets go, the other takes it + CHECK(s->first.hwBlock() == mm::LedHwBlock::PiHeader); +} + +TEST_CASE("Hub75Driver on the bus shows its plain status when the layout holds more lights than its box") { + mm::PortGuard guard; + mm::GridLayout overlap; // a second grid on the first: a 16x32 box holding 1,024 lights + overlap.width = 16; + overlap.height = 32; + overlap.depth = 1; + auto s = std::make_unique(); + s->layouts.addChild(&overlap); + s->layouts.applyState(); + s->layer.applyState(); + REQUIRE(s->layer.physicalLightCount() == 1024); + + s->first.prepare(); + CHECK(s->first.severity() == mm::MoonModule::Severity::Status); + CHECK(std::string(s->first.status()).rfind("16x32, 1/16 scan", 0) == 0); + s->layouts.removeChild(&overlap); +} + +TEST_CASE("Hub75Driver keeps its status readable across a change of machine that swaps its output") { + mm::PortGuard guard; + auto s = std::make_unique(); // a host with a bus port: the bus output + s->first.defineControls(); + s->first.prepare(); + REQUIRE(says(s->first, "1/16 scan")); + const std::string shown = s->first.status(); + + mm::PioPortGuard recorder; // the host turns out to be a Pi 5 + becomeMachine(s->first, mm::platform::Machine::Pi5); + CHECK(std::string(s->first.status()) == shown); // the last prepare's status, until the next prepare says otherwise +} diff --git a/test/unit/light/unit_Hub75Encode.cpp b/test/unit/light/unit_Hub75Encode.cpp index 4df9deb0..38fbd4b1 100644 --- a/test/unit/light/unit_Hub75Encode.cpp +++ b/test/unit/light/unit_Hub75Encode.cpp @@ -393,6 +393,21 @@ TEST_CASE("HUB75 encode: an unusable geometry writes nothing") { CHECK(out[0] == 0xAA); } +TEST_CASE("HUB75 geometry: 96 rows pair at 1/8 and 1/16 and leave an odd three a scan at 1/32") { + // A layout 64 wide and 96 high at 8 bits: 12 rows an address step at 1/8 and 6 at 1/16, all in pairs, but 3 at 1/32, which pair up no better than one. + mm::Hub75Geometry geo; + geo.width = 64; geo.height = 96; geo.bitDepth = 8; + geo.scanRate = 8; + CHECK(geo.rowsPerScan() == 12); + CHECK(geo.valid()); + geo.scanRate = 16; + CHECK(geo.rowsPerScan() == 6); + CHECK(geo.valid()); + geo.scanRate = 32; + CHECK(geo.rowsPerScan() == 3); + CHECK(geo.valid() == false); +} + TEST_CASE("HUB75 frame size is what decides the peripheral") { // The sizes that decide Parlio (65,535 bytes a transfer) against LCD_CAM, two bytes a slot, pinned at 4-bit so a wire-format change cannot move the cliff unseen. mm::Hub75Geometry one; // one 64x64 panel, 1/32 scan diff --git a/test/unit/light/unit_Hub75Fit.cpp b/test/unit/light/unit_Hub75Fit.cpp new file mode 100644 index 00000000..24ec12c4 --- /dev/null +++ b/test/unit/light/unit_Hub75Fit.cpp @@ -0,0 +1,116 @@ +/// @module Hub75Fit + +#include "doctest.h" +#include "light/drivers/Hub75Fit.h" + +#include +#include +#include + +using namespace mm; + +// The expected texts are written by hand; the rates in them come from the refresh page's formula worked by hand rather than taken from the code under test. 128 by 64 panels at 1/32 scan, 8 bits. + +namespace { + +// A card's geometry as the messages read it: one panel's rows, columns, row addresses and bit planes, then the lane and the outputs the board drives. +CardGeometry wall(uint16_t rows, uint16_t cols, uint16_t scan, uint8_t bits, uint16_t panelsPerLane, uint8_t maxLanes, const char* board) { + CardGeometry g; + g.panel.rows = rows; g.panel.cols = cols; g.panel.scanRows = scan; g.panel.bits = bits; g.panel.lsbNs = 130; // the refresh page's lit time + g.panelsPerLane = panelsPerLane; g.maxLanes = maxLanes; g.board = board; + return g; +} + +// What one geometry's message needs; out of line, so the sweep's frame stays under the stack limit. +DOCTEST_NOINLINE size_t lengthOf(uint16_t rows, uint16_t cols, uint32_t panels, uint16_t panelsPerLane, uint8_t maxLanes) { + const GeometryFit why = checkGeometry(panels, panelsPerLane, maxLanes); + if (why == GeometryFit::Ok) return 0; + static char buf[4096]; + const size_t n = geometryMessage(why, panels, wall(rows, cols, rows / 2, 8, panelsPerLane, maxLanes, "Pi PIO"), buf, sizeof(buf)); + return n == std::strlen(buf) ? n : SIZE_MAX; // a cut inside a buffer this size fails the caller's check +} + +// The longest text one panel size and count write, over every lane length up to 64 and board of up to six lanes. +size_t longestFor(uint16_t rows, uint16_t cols, uint32_t panels) { + size_t longest = 0; + for (uint16_t i = 0; i < 64 * 6; i++) longest = std::max(longest, lengthOf(rows, cols, panels, static_cast(1 + i / 6), static_cast(1 + i % 6))); + return longest; +} + +// Every geometry a card could meet, at the sizes panels come in: the longest text any of them writes. +size_t longestMessage() { + size_t longest = 0; + const uint16_t rowsOf[] = {16, 32, 64}; + const uint16_t colsOf[] = {32, 64, 128, 256}; + for (uint16_t rows : rowsOf) + for (uint16_t cols : colsOf) + for (uint32_t panels = 1; panels <= 64; panels++) longest = std::max(longest, longestFor(rows, cols, panels)); + return longest; +} + +std::string message(GeometryFit why, uint32_t panels, uint16_t panelsPerLane, uint8_t maxLanes, const char* board = "Pi PIO") { + static char buf[kGeometryMessageMax]; // static: the test frames stay under the stack limit + const size_t n = geometryMessage(why, panels, wall(64, 128, 32, 8, panelsPerLane, maxLanes, board), buf, sizeof(buf)); + INFO("returned " << n); + return std::string(buf); +} + +} // namespace + +TEST_CASE("Hub75Fit: panels that cable into lanes of the card's length are fine") { + CHECK(checkGeometry(6, 2, 3) == GeometryFit::Ok); // 3 lanes of 2 + CHECK(checkGeometry(6, 3, 3) == GeometryFit::Ok); // 2 lanes of 3 + CHECK(checkGeometry(6, 6, 3) == GeometryFit::Ok); // 1 lane of 6 + CHECK(checkGeometry(1, 1, 3) == GeometryFit::Ok); +} + +TEST_CASE("Hub75Fit: no panel, a zero panelsPerLane, uneven lanes and too many lanes are named apart") { + CHECK(checkGeometry(0, 2, 3) == GeometryFit::Empty); + CHECK(checkGeometry(6, 0, 3) == GeometryFit::Empty); + CHECK(checkGeometry(7, 2, 3) == GeometryFit::Indivisible); + CHECK(checkGeometry(6, 4, 3) == GeometryFit::Indivisible); + CHECK(checkGeometry(2, 3, 3) == GeometryFit::Indivisible); // fewer panels than one lane + CHECK(checkGeometry(6, 2, 1) == GeometryFit::TooManyLanes); // 3 lanes on a one-lane board + CHECK(checkGeometry(12, 2, 3) == GeometryFit::TooManyLanes); // 6 lanes +} + +TEST_CASE("Hub75Fit: an uneven set names the fix in full, and the way to keep the lanes built") { + CHECK(message(GeometryFit::Indivisible, 7, 2, 3) == + "7 panels cannot be cabled in lanes of 2. Cable all 7 (rates computed from the pixel clock): 1 lane of 7 (896x64, 72 Hz). " + "Keep lanes of 2 (rates computed from the pixel clock): use 6 panels, 1 spare, as 3 lanes (256x192, 243 Hz)."); + CHECK(message(GeometryFit::Indivisible, 6, 4, 3) == + "6 panels cannot be cabled in lanes of 4. Cable all 6 (rates computed from the pixel clock): 3 lanes of 2 (256x192, 243 Hz); 2 lanes of 3 (384x128, 165 Hz); " + "1 lane of 6 (768x64, 83 Hz). Keep lanes of 4 (rates computed from the pixel clock): use 4 panels, 2 spare, as 1 lane (512x64, 124 Hz), " + "or add 2 panels for 2 lanes (512x128, 124 Hz)."); +} + +TEST_CASE("Hub75Fit: a set no panelsPerLane of the card's can use whole skips to keeping the lanes") { + CHECK(message(GeometryFit::Indivisible, 41, 2, 3) == + "41 panels cannot be cabled in lanes of 2. Keep lanes of 2 (rates computed from the pixel clock): use 6 panels, 35 spare, as 3 lanes (256x192, 243 Hz)."); +} + +TEST_CASE("Hub75Fit: one panel is named in the singular") { + const std::string s = message(GeometryFit::Indivisible, 1, 2, 3); + CHECK(s.rfind("1 panel cannot be cabled in lanes of 2. Cable all 1 (rates computed from the pixel clock): 1 lane of 1 (128x64, ", 0) == 0); + CHECK(s.find("add 1 panel for 1 lane (256x64, ") != std::string::npos); +} + +TEST_CASE("Hub75Fit: a board with too few lanes says how many it drives") { + CHECK(message(GeometryFit::TooManyLanes, 6, 2, 1, "Pi PIO") == + "6 panels in lanes of 2 need 3 lanes, but the Pi PIO board drives at most 1. Cable all 6 (rates computed from the pixel clock): 1 lane of 6 (768x64, 83 Hz). " + "Keep lanes of 2 (rates computed from the pixel clock): use 2 panels, 4 spare, as 1 lane (256x64, 243 Hz)."); +} + +TEST_CASE("Hub75Fit: no whole panel in the layout is said plainly") { + CHECK(message(GeometryFit::Empty, 0, 2, 3) == "The layout holds fewer lights than one 128x64 panel."); +} + +TEST_CASE("Hub75Fit: a message that fits is never cut, and one that does not says how long it needed") { + const size_t longest = longestMessage(); + CHECK(longest + 1 <= kGeometryMessageMax); // with the terminator + + static char small[16]; + const size_t needed = geometryMessage(GeometryFit::Indivisible, 7, wall(64, 128, 32, 8, 2, 3, "Pi PIO"), small, sizeof(small)); + CHECK(needed > sizeof(small) - 1); // the caller can see it was cut + CHECK(std::strlen(small) == sizeof(small) - 1); +} diff --git a/test/unit/light/unit_Hub75PiOutput.cpp b/test/unit/light/unit_Hub75PiOutput.cpp new file mode 100644 index 00000000..655a9692 --- /dev/null +++ b/test/unit/light/unit_Hub75PiOutput.cpp @@ -0,0 +1,400 @@ +/// @module Hub75PiOutput +/// @also Hub75Driver, Correction + +/// What the Raspberry Pi outputs share, pinned on the Pi PIO output, on a desktop, no panels attached; a case only one output has lives in its own file. + +#include "doctest.h" +#include "light/drivers/Correction.h" +#include "light/drivers/Drivers.h" +#include "unit/core/conditional_controls.h" +#include "light/layers/Buffer.h" +#include "light/layouts/Layouts.h" +#include "light/layouts/GridLayout.h" +#include "light/layouts/PanelsLayout.h" + +#include +#include +#include "hub75_pi_bench.h" + +// The status of a 16x32 panel opened at the default 6 bits and healthy. +template +void checkPlainPanelStatus(mm::Hub75Driver& driver) { + CHECK(driver.severity() == mm::MoonModule::Severity::Status); + CHECK(std::string(driver.status()) == std::string("16x32, 6-bit, ") + S::label); +} + +TEST_CASE_TEMPLATE("Hub75Driver on a Pi output starts its one bitDepth at 6 and hands it over as the engine's depth", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::raster(16, 32); + CHECK(r->driver.bitDepth == 6); + r->driver.bitDepth = 4; + r->open(); + CHECK(S::options().bitDepth == 4); + CHECK(std::string(r->driver.status()) == std::string("16x32, 4-bit, ") + S::label); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput offers 2 to 8 bits, and a depth outside them is the engine's refusal, in the status", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::raster(16, 32); + const int i = mm::controlIndex(r->driver, "bitDepth"); + REQUIRE(i >= 0); + CHECK(r->driver.controls()[static_cast(i)].min == 2); + CHECK(r->driver.controls()[static_cast(i)].max == 8); + + r->driver.bitDepth = 11; // a config loaded from storage sets values and skips the control change; the driver clamps when the output changes + r->open(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Error); + CHECK(std::string(r->driver.status()).find("bitDepth must be 2..8") != std::string::npos); + CHECK(S::width() == 0); + + r->driver.bitDepth = 8; + r->open(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Status); + CHECK(S::options().bitDepth == 8); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput hands light i to canvas pixel i, row by row", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::raster(16, 32); + r->open(); + CHECK(std::string(r->driver.status()) == std::string("16x32, 6-bit, ") + S::label); + + r->paint(0, 10, 20, 30); + r->paint(3 * 16 + 5, 40, 50, 60); // (5, 3) + r->driver.tick(); + + REQUIRE(S::frameCount() == 1); + CHECK(S::pixel(0, 0)[0] == 10); CHECK(S::pixel(0, 0)[1] == 20); CHECK(S::pixel(0, 0)[2] == 30); + CHECK(S::pixel(5, 3)[0] == 40); CHECK(S::pixel(5, 3)[1] == 50); CHECK(S::pixel(5, 3)[2] == 60); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput refuses a layout smaller than one panel, in full, and opens nothing", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::raster(4, 2); // 8 lights, a panel is 16 by 32 + r->open(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Error); + CHECK(std::string(r->driver.status()) == "The layout holds fewer lights than one 16x32 panel."); + CHECK(S::width() == 0); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput takes a layout of the canvas turned on its side as a match, since the layout owns rotation", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = std::make_unique(1, 1, 32, 16, uint8_t{1}, false); // one panel 32 across and 16 down, its rows walked down the columns + r->driver.panelRows = 32; // the card's 16x32 panel, turned on its side by the layout + r->driver.panelCols = 16; + r->open(); + checkPlainPanelStatus(r->driver); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput follows two stacked layouts: two panels' worth of lights make two outputs, and the status says so", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + mm::GridLayout second; // outlives the rig, whose Layouts holds it + second.width = 16; + second.height = 32; + second.depth = 1; + auto r = Rig::raster(16, 32); + r->layouts.addChild(&second); + r->layouts.applyState(); + r->layer.applyState(); + r->open(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Status); + CHECK(std::string(r->driver.status()) == std::string("16x64, 6-bit, ") + S::label); + CHECK(S::options().parallel == 2); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput shows as many of a larger layout's lights as the panels hold", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::raster(20, 40); + r->open(); + r->paint(511, 1, 2, 3); // the canvas's last pixel, (15, 31) + r->paint(512, 9, 9, 9); // one past the canvas + r->driver.tick(); + + REQUIRE(S::frameCount() == 1); + CHECK(S::pixel(15, 31)[0] == 1); CHECK(S::pixel(15, 31)[2] == 3); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput joins a light count other than the canvas's with the walk's panel, so none hides another", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::raster(20, 40); // a raster wider than the 16x32 panel: another light count, and panel 1 leaves plain rows + r->open(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Warning); + CHECK(std::string(r->driver.status()) == + "layout 800 lights, panels 512; " + "the layout's panel 1 does not run in plain rows of 16: lay the panels out in cabling order, each in plain rows with snake off"); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput warns of lights past the last whole panel, and judges only the panels it drives", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + mm::GridLayout extra; // 8 lights after one 16x32 panel in plain rows; outlives the rig, whose Layouts holds it + extra.width = 4; + extra.height = 2; + extra.depth = 1; + auto r = Rig::raster(16, 32, 520); + r->layouts.addChild(&extra); + r->layouts.applyState(); + r->layer.applyState(); + r->open(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Warning); + CHECK(std::string(r->driver.status()) == "layout 520 lights, panels 512"); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput shows a wide profile's red, green and blue, wherever the profile puts them", S, mm::PioSeam) { + typename S::RecordGuard guard; + const mm::WideProfile wide; + mm::showsColorsThrough(wide.roles, 32); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput shows a white-first profile's colors, not its white", S, mm::PioSeam) { + typename S::RecordGuard guard; + const mm::ChannelRole wrgb[4] = {mm::ChannelRole::White, mm::ChannelRole::Red, mm::ChannelRole::Green, mm::ChannelRole::Blue}; + mm::showsColorsThrough(wrgb, 4); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput hands over a layout with fewer lights than its box, the rest dark", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::raster(16, 32, 20); // a ring or any shape short of its box + r->open(); + r->paint(19, 7, 8, 9); // (3, 1), the last light + r->driver.tick(); + REQUIRE(S::frameCount() == 1); + CHECK(S::pixel(3, 1)[0] == 7); + CHECK(S::pixel(4, 1)[0] == 0); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput refuses panels another driver drives, and leaves them to it", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto first = Rig::raster(16, 32); + auto second = Rig::raster(16, 32); + auto drivers = std::make_unique(); // after the rigs, so it goes first + drivers->addChild(&first->driver); + drivers->addChild(&second->driver); + first->open(); + second->open(); + CHECK(second->driver.severity() == mm::MoonModule::Severity::Error); + second->driver.tick(); + CHECK(S::frameCount() == 0); + second->driver.release(); + CHECK(S::width() == 16); // still the first driver's +} + +TEST_CASE_TEMPLATE("Hub75PiOutput's lane canvas counts in the driver's memory while the panels run, and goes with them", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::cabled(2, 1, 16, 32); // two 16x32 panels in cabling order, one lane: a 1024-light canvas + r->driver.panelsPerLane = 2; + r->open(); + REQUIRE(r->driver.severity() == mm::MoonModule::Severity::Status); + CHECK(r->driver.dynamicBytes() == 2 * 1024 * 3); // the corrected frame and the canvas + + r->driver.release(); + CHECK(r->driver.dynamicBytes() == 0); + + r->open(); + REQUIRE(r->driver.dynamicBytes() == 2 * 1024 * 3); + REQUIRE(std::string(mm::platform::hub75BackendLabel(r->driver.selectedBackend())) == S::backendLabel); + mm::PortGuard port; // a host with a bus port + becomeMachine(r->driver, mm::platform::Machine::Other); // the bus output takes over and the Pi output closes, canvas and all + CHECK(r->driver.dynamicBytes() < 1024 * 3 * 2); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput's memory readout is the frame, the canvas and the light scratch while the panels run, and 0 after a release, for a wiring of 32 channels", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::cabled(2, 1, 16, 32); // two 16x32 panels in one lane: a 1024-light canvas + r->driver.panelsPerLane = 2; + r->open(); + REQUIRE(r->driver.severity() == mm::MoonModule::Severity::Status); + const mm::WideProfile wide; + r->driver.correctionForTest().rebuild(255, wide.roles, 32); + r->driver.onCorrectionChanged(); + CHECK(r->driver.dynamicBytes() == 2 * 1024 * 3 + 32); // the frame, the canvas and one 32-channel light + r->driver.prepare(); // a prepare keeps the scratch, the canvas and the readout + CHECK(r->driver.dynamicBytes() == 2 * 1024 * 3 + 32); + r->driver.release(); + CHECK(r->driver.dynamicBytes() == 0); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput closes the panels on release", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::raster(16, 32); + r->open(); + REQUIRE(S::width() == 16); + r->driver.release(); + CHECK(S::width() == 0); +} + +// A 16x32 raster on a Pi output, opened. +template +std::unique_ptr> openedRaster() { + auto r = mm::PiRig::raster(16, 32); + r->open(); + return r; +} + +TEST_CASE_TEMPLATE("Hub75PiOutput shows a stall that is already there at the first second after a reopen", S, mm::PioSeam) { + typename S::RecordGuard guard; + auto r = openedRaster(); + mm::platform::setTestHub75PioStalled(true); + r->driver.tick1s(); + REQUIRE(std::string(r->driver.status()).find("the PIO is stalled") != std::string::npos); + + r->driver.prepare(); // the seam is still stalled + r->driver.tick1s(); + CHECK(std::string(r->driver.status()).find("the PIO is stalled") != std::string::npos); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput counts a reopened panel's failed submits from that open", S, mm::PioSeam) { + typename S::RecordGuard guard; + auto r = openedRaster(); + mm::platform::setTestHub75PioSubmitErrors(3); + r->driver.tick1s(); + REQUIRE(r->driver.severity() == mm::MoonModule::Severity::Warning); + + mm::platform::setTestHub75PioSubmitErrors(0); // the next open's seam counts from 0 + r->driver.prepare(); + r->driver.tick1s(); + checkPlainPanelStatus(r->driver); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput places lights by the panels as opened, whatever a control reads before the reopen", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::raster(32, 32); // two 16 by 32 panels in one lane + r->driver.panelsPerLane = 2; + r->open(); + REQUIRE(S::width() == 32); + r->driver.panelsPerLane = 1; // a control moved before any prepare + r->paint(512, 200, 0, 0); // panel 1, first light + r->paint(528, 0, 200, 0); // panel 1, first light of its second row + r->driver.tick(); + CHECK(S::pixel(16, 0)[0] == 200); // still the second place of the lane + CHECK(S::pixel(16, 1)[1] == 200); +} + +// Lights run panel by panel in cabling order, so a Pi output puts each where its panel sits on the lane canvas; the expected cells are the placement rule by hand. + +TEST_CASE_TEMPLATE("Hub75Driver on a Pi output puts the second panel of a lane to the right of the first", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::raster(32, 32); // 1024 lights: two 16 by 32 panels + r->driver.panelsPerLane = 2; + r->paint(0, 200, 0, 0); // panel 0, first light + r->paint(15, 0, 200, 0); // panel 0, last light of its first row + r->paint(16, 0, 0, 200); // panel 0, first light of its second row + r->paint(512, 100, 100, 100); // panel 1, first light + r->paint(1023, 200, 200, 0); // panel 1, last light + r->open(); + r->driver.tick(); + REQUIRE(S::width() == 32); + CHECK(S::pixel(0, 0)[0] == 200); + CHECK(S::pixel(15, 0)[1] == 200); + CHECK(S::pixel(0, 1)[2] == 200); + CHECK(S::pixel(16, 0)[0] == 100); + CHECK(S::pixel(31, 31)[0] == 200); + CHECK(S::pixel(31, 31)[1] == 200); +} + +TEST_CASE_TEMPLATE("Hub75Driver on a Pi output stacks the lanes: six panels, two to a lane on three lanes, make a 32 by 96 canvas", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::raster(32, 96); // 3072 lights: six 16 by 32 panels + r->driver.panelsPerLane = 2; + r->paint(1024, 200, 0, 0); // panel 2: place 0 of lane 1 + r->paint(2560, 0, 200, 0); // panel 5: place 1 of lane 2 + r->paint(3071, 0, 0, 200); // the last light of the last panel + r->open(); + r->driver.tick(); + REQUIRE(S::width() == 32); + REQUIRE(S::height() == 96); + CHECK(S::pixel(0, 32)[0] == 200); + CHECK(S::pixel(16, 64)[1] == 200); + CHECK(S::pixel(31, 95)[2] == 200); +} + +TEST_CASE_TEMPLATE("Hub75Driver on a Pi output leaves a lane of one panel as it was: light i is canvas pixel i", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::raster(16, 96); // three 16 by 32 panels, one to a lane + r->driver.panelsPerLane = 1; + r->paint(514, 200, 0, 0); + r->open(); + r->driver.tick(); + CHECK(S::pixel(2, 32)[0] == 200); // light 514 is panel 1 (row 32 of the canvas), column 2 +} + +// The panels follow the layout; Hub75Fit's cases pin the geometry text, these that the output shows it whole and leaves the panels closed. + +TEST_CASE_TEMPLATE("Hub75PiOutput derives the parallel lanes from the layout, and the card has no such control", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::cabled(2, 3, 16, 32); // six 16 by 32 panels + r->driver.panelsPerLane = 2; + CHECK(mm::controlIndex(r->driver, "parallel") < 0); + r->open(); + CHECK(S::options().parallel == 3); + CHECK(std::string(r->driver.status()) == std::string("32x96, 6-bit, ") + S::label); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput names the fix in full for panels that do not cable into the lane, and opens nothing", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::raster(112, 32); // seven 16 by 32 panels + r->driver.panelsPerLane = 2; + r->open(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Error); + const std::string s = r->driver.status(); + CHECK(s.rfind("7 panels cannot be cabled in lanes of 2.", 0) == 0); + CHECK(s.find("Cable all 7 (rates computed from the pixel clock): 1 lane of 7") != std::string::npos); + CHECK(s.find("Keep lanes of 2 (rates computed from the pixel clock): use 6 panels, 1 spare, as 3 lanes") != std::string::npos); + CHECK(s.size() > 64); // past 64 bytes, so the status holds a long message whole + CHECK(S::width() == 0); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput says how many lanes the board drives when the layout needs more", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::raster(64, 32); // four 16 by 32 panels, one to a lane: four outputs + r->driver.panelsPerLane = 1; + r->open(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Error); + CHECK(std::string(r->driver.status()).rfind(std::string("4 panels in lanes of 1 need 4 lanes, but the Pi ") + S::label + " board drives at most 3.", 0) == 0); + CHECK(S::width() == 0); +} + +// A raster across panels in series matches every count, so only the walk catches it: the wall shows bands. +TEST_CASE_TEMPLATE("Hub75PiOutput warns when a raster layout feeds panels in series, naming the panel and the fix, and the panels still run", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::raster(256, 64); // one raster across two 128 by 64 panels + r->driver.panelRows = 64; + r->driver.panelCols = 128; + r->driver.panelsPerLane = 2; + r->open(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Warning); + CHECK(std::string(r->driver.status()) == + "the layout's panel 1 does not run in plain rows of 128: lay the panels out in cabling order, each in plain rows with snake off"); + CHECK(S::width() == 256); +} + +TEST_CASE_TEMPLATE("Hub75PiOutput warns when a Panels layout snakes inside its panels, the Panels layout's default", S, mm::PioSeam) { + using Rig = mm::PiRig; + typename S::RecordGuard guard; + auto r = Rig::cabled(2, 1, 16, 32, true); + r->driver.panelsPerLane = 2; + r->open(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Warning); + CHECK(std::string(r->driver.status()).rfind("the layout's panel 1 does not run in plain rows of 16", 0) == 0); +} diff --git a/test/unit/light/unit_Hub75PioOutput.cpp b/test/unit/light/unit_Hub75PioOutput.cpp new file mode 100644 index 00000000..2a50c99f --- /dev/null +++ b/test/unit/light/unit_Hub75PioOutput.cpp @@ -0,0 +1,191 @@ +/// @module Hub75PioOutput +/// @also Hub75Driver, Correction + +/// Hub75Driver on a Raspberry Pi 5's header, through the RP1's PIO, pinned on a desktop, no panels attached. The PIO seam records what the output opened and handed over (the `hub75Pio*` seam in platform/Hub75Pio.h); the bench Pi then only has to show it. + +#include "doctest.h" +#include "light/drivers/Hub75PioOutput.h" +#include "light/drivers/Correction.h" +#include "light/drivers/Drivers.h" +#include "correction_presets.h" +#include "unit/core/conditional_controls.h" +#include "light/layers/Buffer.h" +#include "light/layouts/Layouts.h" +#include "light/layouts/GridLayout.h" +#include "light/layouts/PanelsLayout.h" + +#include +#include +#include +#include "hub75_pi_bench.h" + +namespace { + +using Rig = mm::PiRig; + +constexpr auto pixel = &mm::PioSeam::pixel; + +constexpr uint8_t kLinear = static_cast(mm::Correction::Curve::Linear); // the curve select indexes Curve + +} // namespace + +TEST_CASE("Hub75Driver on a Pi 5 offers Pi PIO and drives it through the PIO output") { + mm::PioPortGuard guard; + auto r = Rig::raster(16, 32); + CHECK(r->driver.selectedBackend() == mm::platform::Hub75Backend::Pio); + CHECK(std::string(mm::platform::hub75BackendLabel(mm::platform::Hub75Backend::Pio)) == "Pi PIO"); + r->open(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Status); + CHECK(r->driver.hwBlock() == mm::LedHwBlock::PiHeader); +} + +namespace { + +// The driver on the PIO output with the PIO on offer, on the heap, past a test's frame limit. +std::unique_ptr piDriver() { + auto driver = std::make_unique(); + REQUIRE(pickBackend(*driver, "Pi PIO")); + return driver; +} + +// The options the PIO output would open the seam with, from the driver's settings. +mm::platform::Hub75PioOptions optionsOf(mm::Hub75Driver& driver) { + return static_cast(driver.outputForTest())->options(); +} + +} // namespace + +TEST_CASE("Hub75PioOutput starts from the seam's own defaults") { + mm::PioPortGuard guard; + const mm::platform::Hub75PioOptions defaults{}; + auto driver = piDriver(); + const auto o = optionsOf(*driver); + CHECK(o.rows == defaults.rows); + CHECK(o.cols == defaults.cols); + CHECK(o.panelsPerLane == defaults.panelsPerLane); + CHECK(o.parallel == 1); // the layout decides it in open(), not the default + CHECK(o.scanRate == 32); // 64 rows, the default, derive 1/32 + CHECK(o.bitDepth == defaults.bitDepth); + CHECK(o.pixelClockHz == defaults.pixelClockHz); + CHECK(o.latchBlankWords == defaults.latchBlankWords); + CHECK(o.clockFallingEdge == defaults.clockFallingEdge); +} + +TEST_CASE("Hub75PioOutput derives the scan from the panel's rows: 64 rows is 1/32, 32 rows 1/16, 16 rows 1/8") { + mm::PioPortGuard guard; + auto driver = piDriver(); + CHECK(optionsOf(*driver).scanRate == 32); // 64 rows, the default, is 1/32, so the wall needs no hand setting + driver->panelRows = 32; + CHECK(optionsOf(*driver).scanRate == 16); + driver->panelRows = 16; + CHECK(optionsOf(*driver).scanRate == 8); +} + +TEST_CASE("Hub75PioOutput refuses a rows count other than 16, 32 or 64, in rows rather than in the scan rate the card hides") { + mm::PioPortGuard guard; + for (const uint8_t rows : {uint8_t{40}, uint8_t{17}, uint8_t{33}, uint8_t{8}}) { // 17 and 33 halve, in whole numbers, to the scans 8 and 16 + CAPTURE(static_cast(rows)); + auto r = Rig::raster(24, rows); + r->driver.panelRows = rows; + r->driver.panelCols = 24; + r->open(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Error); + CHECK(std::string(r->driver.status()) == "the scan is half the panel's rows, so rows must be 16, 32 or 64"); + CHECK(mm::platform::hub75PioWidth() == 0); + } +} + +TEST_CASE("Hub75Driver on Pi PIO opens at 8-bit when set, and the status names it") { + mm::PioPortGuard guard; + auto r = Rig::raster(16, 32); + r->driver.bitDepth = 8; + r->open(); + CHECK(mm::platform::hub75PioTestPort().options.bitDepth == 8); + CHECK(std::string(r->driver.status()) == "16x32, 8-bit, PIO"); +} + +TEST_CASE("Hub75PioOutput opens the wall with its controls: three lanes of two 128x64 panels at 1/32 scan") { + mm::PioPortGuard guard; + auto r = Rig::cabled(2, 3, 128, 64); // the wall: six 128 by 64 panels + r->driver.panelsPerLane = 2; + r->driver.scanSel = 0; // 1/8: the bus output's select, which the PIO output ignores; the scan derives from rows, so the wall is 1/32 with no hand setting + r->driver.bitDepth = 4; + r->driver.clockEdgeSel = 1; // falling + r->driver.pixelClockKhz = 20000; + r->driver.latchBlankWords = 2; + r->open(); + + const auto& o = mm::platform::hub75PioTestPort().options; + CHECK(o.rows == 64); + CHECK(o.cols == 128); + CHECK(o.panelsPerLane == 2); + CHECK(o.parallel == 3); + CHECK(o.scanRate == 32); + CHECK(o.bitDepth == 4); + CHECK(o.pixelClockHz == 20000000); + CHECK(o.latchBlankWords == 2); + CHECK(o.clockFallingEdge); + CHECK(std::string(r->driver.status()) == "256x192, 4-bit, PIO"); +} + +TEST_CASE("Hub75PioOutput dims by lit time and leaves the curve to the correction, the values kept whole") { + mm::PioPortGuard guard; + auto r = Rig::raster(16, 32); + r->open(); + REQUIRE(mm::setControlValue(r->driver, "curve", kLinear)); + r->driver.rebuildCorrection(128); + + r->paint(0, 200, 200, 200); + r->driver.tick(); + + CHECK(mm::platform::hub75PioTestPort().brightness == 128); + CHECK(pixel(0, 0)[0] == 200); // the engine dims it by time, not the value +} + +TEST_CASE("Hub75PioOutput reopens the panels on every PIO option and on nothing else") { + mm::PioPortGuard guard; + auto r = Rig::raster(16, 32); + for (const char* n : {"rows", "cols", "panelsPerLane", "bitDepth", "clockEdge", + "pixelClock", "latchBlank", "peripheral"}) { + CAPTURE(n); + CHECK(r->driver.affectsPrepare(n)); + } + CHECK_FALSE(r->driver.affectsPrepare("scanRate")); // no such control on the PIO card: the scan derives from rows + CHECK_FALSE(r->driver.affectsPrepare("curve")); + CHECK_FALSE(r->driver.affectsPrepare("localBrightness")); + CHECK_FALSE(r->driver.affectsPrepare("shown")); +} + +TEST_CASE("Hub75PioOutput names why the panels would not open, and stays inert") { + mm::PioPortGuard guard; + auto r = Rig::raster(16, 32); + mm::platform::setTestHub75PioOpenFails(true); // a fit geometry on a PIO that will not open: the seam's reason is the status + r->driver.prepare(); + CHECK(r->driver.severity() == mm::MoonModule::Severity::Error); + CHECK(std::string(r->driver.status()) == "the test seam refuses the open"); + r->driver.tick(); // must not crash, and has no frame to hand over + CHECK(mm::platform::hub75PioWidth() == 0); +} + +TEST_CASE("Hub75PioOutput quotes the rates from the pixel clock") { + mm::PioPortGuard guard; + auto r = Rig::cabled(5, 1, 128, 64); // five 128 by 64 panels, which lanes of 2 cannot cable + r->driver.panelsPerLane = 2; + r->open(); + CHECK(std::string(r->driver.status()).find("1 lane of 5 (640x64, 81 Hz)") != std::string::npos); + + r->driver.pixelClockKhz = 20000; // twice the clock, twice the rate + r->open(); + CHECK(std::string(r->driver.status()).find("1 lane of 5 (640x64, 163 Hz)") != std::string::npos); +} + +TEST_CASE("Hub75PioOutput quotes a narrow panel's rate with the encoder's hold words, the rate the wire runs") { + mm::PioPortGuard guard; + auto r = Rig::raster(64, 32); // one 64 by 32 panel at 8 bits, which lanes of 2 cannot cable + r->driver.panelRows = 32; + r->driver.panelCols = 64; + r->driver.panelsPerLane = 2; + r->driver.bitDepth = 8; + r->open(); + CHECK(std::string(r->driver.status()).find("1 lane of 1 (64x32, 606 Hz)") != std::string::npos); // the shift alone would quote 1,221 Hz +}