diff --git a/4.26/mono/spi/video/.gitignore b/4.26/mono/spi/video/.gitignore new file mode 100644 index 0000000..88ace90 --- /dev/null +++ b/4.26/mono/spi/video/.gitignore @@ -0,0 +1,10 @@ +# keep source video and generated packs out of the repo +*.mp4 +*.mkv +*.webm +*.gif +*.epdv + +# editor and interpreter droppings +*.swp +__pycache__/ diff --git a/4.26/mono/spi/video/Makefile b/4.26/mono/spi/video/Makefile new file mode 100644 index 0000000..42e2641 --- /dev/null +++ b/4.26/mono/spi/video/Makefile @@ -0,0 +1,22 @@ +# Local build for the 4.26" mono video player. + +CC ?= cc +CFLAGS ?= -std=gnu11 -Wall -Wextra \ + -Wno-error=incompatible-pointer-types \ + -Werror=implicit-function-declaration +LDLIBS ?= -lgpiod + +COMMON := video_app.h +RPI5 := pixpaper-426-m-test-rpi5-video + +.PHONY: all clean +all: $(RPI5) + +$(RPI5): $(RPI5).c $(COMMON) + @grep -qs gpiod_chip_request_lines /usr/include/gpiod.h || { \ + echo "this player needs libgpiod v2 headers; /usr/include/gpiod.h is $(if $(wildcard /usr/include/gpiod.h),v1,missing) -- apt install libgpiod-dev" >&2; \ + exit 1; } + $(CC) $(CFLAGS) $(EXTRA_CFLAGS) -I. $< -o $@ $(LDLIBS) + +clean: + $(RM) $(RPI5) diff --git a/4.26/mono/spi/video/README.md b/4.26/mono/spi/video/README.md new file mode 100644 index 0000000..4b215c3 --- /dev/null +++ b/4.26/mono/spi/video/README.md @@ -0,0 +1,195 @@ +# Video playback on the 4.26" mono PixPaper + +Plays a video on an 800x480 e-paper panel. + + your video (mp4/gif/frames) -> video2epd.py -> clip.epdv -> player on the board + +All the work happens on the host. `video2epd.py` decodes, scales, thresholds and +**packs every frame into controller RAM order**, so at play time the board only +does `mmap` + one SPI burst per frame. + +Flat black-and-white silhouette animation is what a 1-bit panel renders best, +though 800x480 is enough resolution for dithered live-action to be legible. + +The panel manages 30 fps at full rate, and about 16 fps with the default +settings, because the controller will diff frames in hardware and only drive +the pixels that changed. + +## Build + +```sh +make +``` + +Needs libgpiod **v2**. If `gpiodetect` shows the `pinctrl-rp1` chip somewhere +other than `gpiochip15` — on Trixie / kernel 6.12+ it is `gpiochip0`: + +```sh +make EXTRA_CFLAGS='-DEPD_GPIO_CHIP=\"gpiochip0\"' +``` + +The 4.26" panel has no other Raspberry Pi 5 example in this repo; the pins in +`pixpaper-426-m-test-rpi5-video.c` (DC 5, RST 6, BUSY 26, `/dev/spidev0.0`) are +the ones this was measured on. + +## Make a clip + +Needs `opencv-python` and `numpy` on the host. + +```sh +python3 video2epd.py your_video.mp4 -o clip.epdv --fps 15 +python3 video2epd.py your_video.mp4 -o clip.epdv --fps 15 --preview sheet.png +``` + +`--preview` writes a 9-frame contact sheet sampled across the clip, unpacked +back out of the file just written — so it checks the packing, not just the +source. + +| flag | what it does | +| --- | --- | +| `--fps N` | playback rate, default 15 — roughly what the player's defaults sustain. Never higher than the source's own rate. | +| `--fit pad\|crop\|stretch` | letterbox (default), fill-and-cut, or squash. A 4:3 source letterboxes to 640x480 on this 5:3 panel. | +| `--thresh N` | black/white cut point, default 128. | +| `--dither none\|bayer\|fs` | `none` suits flat animation; `bayer` is fast and worth trying here, since 800x480 has the resolution to carry a dither. | +| `--invert`, `--gamma`, `--start`, `--duration` | the obvious things. | + +**Frames are 48000 bytes**, so clips get large fast: a 3:40 video is ~160 MB at +15 fps, 300 MB at 30 fps. Keep `.epdv` files out of the repo — +`.gitignore` here already does. + +## Play + +```sh +./pixpaper-426-m-test-rpi5-video clip.epdv +./pixpaper-426-m-test-rpi5-video clip.epdv --loop +./pixpaper-426-m-test-rpi5-video clip.epdv --free --quiet # measure +``` + +| flag | what it does | +| --- | --- | +| `--loop` | repeat until Ctrl-C | +| `--free` | show every frame as fast as the panel manages, ignoring the clip's rate | +| `--fps N` | override the clip's rate | +| `--spi HZ` | SPI clock, default 20 MHz. It is the floor on frame time here, see below. | +| `--update N` | override the panel's per-frame update sequence | +| `--tp N` | drive frames per update, default 4; `--tp 0` uses the OTP waveform | +| `--fr N` | frame-rate code, i.e. how long one drive frame lasts; 4 by default, 6 is the practical floor | +| `--no-pingpong` | repaint every pixel instead of only the changed ones | +| `--refresh N` | full white refresh every N frames, see Ghosting | +| `--start N`, `--keep`, `--quiet` | | + +By default the player follows the wall clock and skips frames it could not keep +up with, so a clip always runs for its own length. `--free` shows every frame +and reports sustained fps — that is how you measure. + +Ctrl-C (or SIGTERM) leaves partial mode cleanly and clears to white. + +## Speed: --tp and --fr + +Measured on a Raspberry Pi 5, every setting below checked on the panel rather +than inferred from timing: + + frame_ms ~= SPI burst + tp * period(fr) + +| setting | frame time | sustained | note | +| --- | --- | --- | --- | +| `--tp 0` | 670 ms | 1.5 fps | the controller's OTP waveform | +| `--tp 8 --fr 4` | 101 ms | 9.9 fps | | +| `--tp 4 --fr 4` | 61 ms | 16.5 fps | **default** | +| `--tp 3 --fr 4 --spi 32000000` | 47 ms | 21.3 fps | plays 20 fps content with margin | +| `--tp 2 --fr 6 --spi 32000000` | 30 ms | 33.2 fps | plays 30 fps content at full rate | +| `--tp 1 --fr 6 --spi 32000000` | 23 ms | 42.7 fps | near the floor | + +**The SPI burst is the hard floor.** 48000 bytes is 384000 bits: 77 ms at +5 MHz, 20 ms at 20 MHz, 17 ms at the ~23 MHz the Pi actually produces when +asked for 32. Drive time can go to zero, that cannot, so ~58 fps is the +ceiling — raising the clock is the first thing worth doing here. + +**`--tp` is drive frames, `--fr` is how long a frame lasts.** Total drive is +`tp * period(fr)`, and that is what moves pigment. Measured periods: + +| `--fr` | 2 | 3 | 4 | 5 | 6 | +| --- | --- | --- | --- | --- | --- | +| period | 20.1 ms | 13.4 ms | 10.1 ms | 8.1 ms | 6.7 ms | + +`--fr` has a floor: one frame has to be long enough for the controller to scan +all 480 gate lines. At `--fr 8` (5 ms) it cannot, and a whole band of the panel +is left undrawn. `--fr 6` works; 7 is untested. + +## Four things that have to be right + +Every one of these was wrong at some point here. They produce different +symptoms, and each is easy to misread as one of the others: + +| what you see | what it usually is | +| --- | --- | +| smeared, static areas degrading | frame differencing not enabled (1) | +| pale, washed out | source voltage too low (2) | +| present but unclear, never quite black | gate voltage too low, or VCOM unset (2) | +| a band of the panel never drawn | `--fr` too low to scan every gate line (3) | +| frozen image, but timings perfect and linear | supply (4) | + +**1. Frame differencing is off until you enable it.** The controller can carry +the displayed frame forward and drive only the pixels that differ, but it does +not do so at power-on. `epd_partial_begin()` turns it on, and that is what +makes a short waveform viable: static areas are never repainted, so they never +accumulate smear. Without it every frame repaints all 800x480 and a short drive +looks filthy. + +**2. Drive voltages have to be the panel's, not the stock example's.** The +voltages in the stock `../pixpaper-426-m-test-*.c` waveform belong to its +greyscale passes, which drive deliberately weakly to land on intermediate +tones. Reused for a black/white refresh they leave the image pale, and the gate +voltage in particular is low enough that the pixel TFTs never fully open -- +which reads as an unclear image rather than merely a pale one. `video_app.h` +sets all of them to the panel's rated levels instead; the datasheet for your +panel has the figures. + +**3. `--fr` has a floor.** A drive frame must last long enough for the +controller to scan every gate line. Below that a whole band of the panel is +left undrawn. `--fr 6` works on this panel and 8 does not. + +**4. Supply current.** An underpowered Pi produces the most misleading failure +here: the controller answers normally, BUSY is punctual and frame times are +exact and perfectly linear in `--tp` -- and nothing moves on the glass, because +the booster cannot reach drive voltage. If the image freezes, check +`vcgencmd get_throttled` before suspecting the waveform. A full refresh +finishing in well under a second means it is not really driving. + +## Ghosting + +Ping-pong is what keeps a short waveform clean, and it works by never +repainting a pixel that has not changed. The flip side is that a static area is +also never refreshed, so any residue it picks up stays. `--refresh N` does a +full white refresh every N frames, which clears it at the cost of about four +seconds and a visible flash; the player re-syncs the playhead afterwards so the +clip keeps its own length. The default is off. + +**How much residue actually builds up over a long run has not been measured +here** -- the runs behind the figures above were minutes, not hours. If you are +leaving a clip playing unattended, watch the background for a while before +trusting it, and set `--refresh` if it drifts. + +## .epdv format + +A pack is panel-specific and the player checks it: `frame_bytes` must be 48000 +here, so a file built for another panel is rejected with a message rather than +displayed as noise. + +``` +0 char magic[4] "EPDV" +4 uint16 version 1 +6 uint16 flags +8 uint16 width logical, informational +10 uint16 height +12 uint32 frame_us nominal display time per frame +16 uint32 frame_count +20 uint32 frame_bytes 48000 for this panel +24 uint32 reserved[10] +64 frames... +``` + +Each frame is in the order the panel wants it: bit 1 = white, row-major, 100 +bytes per row, the top bit of each byte being the leftmost of its eight pixels. +No horizontal flip — `../png2bit_426.py` mirrors its input, but on this wiring +that comes out backwards. diff --git a/4.26/mono/spi/video/pixpaper-426-m-test-rpi5-video.c b/4.26/mono/spi/video/pixpaper-426-m-test-rpi5-video.c new file mode 100644 index 0000000..34dd812 --- /dev/null +++ b/4.26/mono/spi/video/pixpaper-426-m-test-rpi5-video.c @@ -0,0 +1,151 @@ +/* + * Author: LC Wang + * Date: 2026-08-11 + * + * Video player for Raspberry Pi 5: libgpiod v2 GPIO backend. + * Shared SPI/EPD/player logic lives in video_app.h. + * + * Check the pins below against your wiring before the first run. + */ +#include +#include +#include + +/* The header GPIO has moved between Pi 5 kernels (gpiochip4/15, gpiochip0 on + * 6.12+). `gpiodetect` shows which one is labelled pinctrl-rp1; override with + * make EXTRA_CFLAGS='-DEPD_GPIO_CHIP=\"gpiochip0\"'. */ +#ifndef EPD_GPIO_CHIP +#define EPD_GPIO_CHIP "gpiochip15" +#endif + +#define EPD_DC_PIN 5 +#define EPD_RST_PIN 6 +#define EPD_BUSY_PIN 26 + +struct gpiod_chip *chip; +struct gpiod_line_request *epd_dc_line, *epd_rst_line, *epd_busy_line; + +static const unsigned int EPD_DC_OFFSET = EPD_DC_PIN; +static const unsigned int EPD_RST_OFFSET = EPD_RST_PIN; +static const unsigned int EPD_BUSY_OFFSET = EPD_BUSY_PIN; + +static struct gpiod_line_request * +gpiod_request_output(struct gpiod_chip *c, unsigned int offset, + const char *consumer, int value) +{ + struct gpiod_line_settings *settings; + struct gpiod_line_config *line_cfg; + struct gpiod_request_config *req_cfg; + struct gpiod_line_request *request = NULL; + + settings = gpiod_line_settings_new(); + if (!settings) + return NULL; + gpiod_line_settings_set_direction(settings, GPIOD_LINE_DIRECTION_OUTPUT); + gpiod_line_settings_set_output_value(settings, + value ? GPIOD_LINE_VALUE_ACTIVE : GPIOD_LINE_VALUE_INACTIVE); + + line_cfg = gpiod_line_config_new(); + if (!line_cfg) { + gpiod_line_settings_free(settings); + return NULL; + } + if (gpiod_line_config_add_line_settings(line_cfg, &offset, 1, settings) < 0) + goto out; + + req_cfg = gpiod_request_config_new(); + if (req_cfg) + gpiod_request_config_set_consumer(req_cfg, consumer); + + request = gpiod_chip_request_lines(c, req_cfg, line_cfg); + + if (req_cfg) + gpiod_request_config_free(req_cfg); +out: + gpiod_line_config_free(line_cfg); + gpiod_line_settings_free(settings); + return request; +} + +static struct gpiod_line_request * +gpiod_request_input(struct gpiod_chip *c, unsigned int offset, + const char *consumer) +{ + struct gpiod_line_settings *settings; + struct gpiod_line_config *line_cfg; + struct gpiod_request_config *req_cfg; + struct gpiod_line_request *request = NULL; + + settings = gpiod_line_settings_new(); + if (!settings) + return NULL; + gpiod_line_settings_set_direction(settings, GPIOD_LINE_DIRECTION_INPUT); + + line_cfg = gpiod_line_config_new(); + if (!line_cfg) { + gpiod_line_settings_free(settings); + return NULL; + } + if (gpiod_line_config_add_line_settings(line_cfg, &offset, 1, settings) < 0) + goto out; + + req_cfg = gpiod_request_config_new(); + if (req_cfg) + gpiod_request_config_set_consumer(req_cfg, consumer); + + request = gpiod_chip_request_lines(c, req_cfg, line_cfg); + + if (req_cfg) + gpiod_request_config_free(req_cfg); +out: + gpiod_line_config_free(line_cfg); + gpiod_line_settings_free(settings); + return request; +} + +static inline void +gpiod_set_value(struct gpiod_line_request *req, unsigned int offset, int value) +{ + gpiod_line_request_set_value(req, offset, + value ? GPIOD_LINE_VALUE_ACTIVE : GPIOD_LINE_VALUE_INACTIVE); +} + +static inline int +gpiod_get_value(struct gpiod_line_request *req, unsigned int offset) +{ + return gpiod_line_request_get_value(req, offset) == GPIOD_LINE_VALUE_ACTIVE + ? 1 : 0; +} + +#define epd_dc_set(v) gpiod_set_value(epd_dc_line, EPD_DC_OFFSET, (v)) +#define epd_rst_set(v) gpiod_set_value(epd_rst_line, EPD_RST_OFFSET, (v)) +#define epd_busy_get() gpiod_get_value(epd_busy_line, EPD_BUSY_OFFSET) + +static int epd_gpio_init(void) { + chip = gpiod_chip_open("/dev/" EPD_GPIO_CHIP); + if (!chip) { + perror("Error opening GPIO chip"); + return -1; + } + + epd_dc_line = gpiod_request_output(chip, EPD_DC_OFFSET, "epd_dc", 0); + epd_rst_line = gpiod_request_output(chip, EPD_RST_OFFSET, "epd_rst", 0); + epd_busy_line = gpiod_request_input(chip, EPD_BUSY_OFFSET, "epd_busy"); + + if (!epd_dc_line || !epd_rst_line || !epd_busy_line) { + perror("Error requesting GPIO lines"); + gpiod_chip_close(chip); + return -1; + } + + return 0; +} + +static void epd_gpio_release(void) { + gpiod_line_request_release(epd_dc_line); + gpiod_line_request_release(epd_rst_line); + gpiod_line_request_release(epd_busy_line); + gpiod_chip_close(chip); +} + +#include "video_app.h" diff --git a/4.26/mono/spi/video/video2epd.py b/4.26/mono/spi/video/video2epd.py new file mode 100644 index 0000000..c890929 --- /dev/null +++ b/4.26/mono/spi/video/video2epd.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Pack a video into an .epdv frame file for the +4.26" mono PixPaper. + +Every frame is stored exactly as the controller wants it in RAM, so the on-board +player only has to memcpy it out over SPI: row-major, 100 bytes per row, the +top bit of each byte being the leftmost of its eight pixels. + +Bit value 1 = white, 0 = black. + +examples: + python3 video2epd.py clip.mp4 -o clip.epdv --fps 15 + python3 video2epd.py clip.mp4 -o clip.epdv --fps 15 --preview sheet.png +""" + +import argparse +import struct +import sys + +import cv2 +import numpy as np + +DISP_W = 800 +DISP_H = 480 +DISP_STRIDE = DISP_W // 8 # 100 bytes per row +FRAME_BYTES = DISP_STRIDE * DISP_H # 48000 + +EPDV_MAGIC = b"EPDV" +EPDV_VERSION = 1 +HDR_FMT = "<4sHHHHIII40x" # 64 bytes, see struct epdv_hdr + +def parse_args(): + p = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + p.add_argument("input", help="video file") + p.add_argument("-o", "--output", default="clip.epdv", help="output .epdv file") + p.add_argument("--fps", type=float, default=15.0, + help="playback frame rate (default 15, about what the " + "player's defaults sustain; measure yours with --free)") + p.add_argument("--fit", choices=["pad", "crop", "stretch"], default="pad", + help="pad = letterbox and keep the whole frame (default), " + "crop = fill the screen and cut the overflow, " + "stretch = ignore the aspect ratio") + p.add_argument("--pad-color", choices=["white", "black"], default="white", + help="letterbox colour for --fit pad (default white)") + p.add_argument("--thresh", type=int, default=128, + help="black/white threshold 0..255 (default 128)") + p.add_argument("--dither", choices=["none", "bayer", "fs"], default="none", + help="none = hard threshold, right for flat silhouette " + "animation (default); bayer = fast 8x8 ordered dither " + "for real footage; fs = Floyd-Steinberg, best looking " + "but slow (seconds per frame in pure Python)") + p.add_argument("--invert", action="store_true", help="invert black and white") + p.add_argument("--gamma", type=float, default=1.0, + help="gamma applied before thresholding (>1 brightens)") + p.add_argument("--start", type=float, default=0.0, + help="skip the first N seconds of the source") + p.add_argument("--duration", type=float, + help="encode only N seconds") + p.add_argument("--preview", metavar="PNG", + help="write a 9-frame contact sheet sampled across the clip, " + "unpacked from the file just written (so it checks the " + "packing, not just the source)") + return p.parse_args() + + +def to_gray(frame): + if frame.ndim == 3: + return cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) + return frame + + +def fit_frame(gray, dst_w, dst_h, mode, pad_value): + """Resize gray into dst_w x dst_h under the chosen fit rule.""" + if mode == "stretch": + return cv2.resize(gray, (dst_w, dst_h), interpolation=cv2.INTER_AREA) + + sh, sw = gray.shape[:2] + scale = min(dst_w / sw, dst_h / sh) if mode == "pad" else max(dst_w / sw, dst_h / sh) + nw, nh = max(1, round(sw * scale)), max(1, round(sh * scale)) + interp = cv2.INTER_AREA if scale < 1 else cv2.INTER_LINEAR + small = cv2.resize(gray, (nw, nh), interpolation=interp) + + if mode == "crop": + x0, y0 = (nw - dst_w) // 2, (nh - dst_h) // 2 + return small[y0:y0 + dst_h, x0:x0 + dst_w] + + canvas = np.full((dst_h, dst_w), pad_value, dtype=np.uint8) + x0, y0 = (dst_w - nw) // 2, (dst_h - nh) // 2 + canvas[y0:y0 + nh, x0:x0 + nw] = small + return canvas + + +BAYER8 = np.array([ + [0, 32, 8, 40, 2, 34, 10, 42], + [48, 16, 56, 24, 50, 18, 58, 26], + [12, 44, 4, 36, 14, 46, 6, 38], + [60, 28, 52, 20, 62, 30, 54, 22], + [3, 35, 11, 43, 1, 33, 9, 41], + [51, 19, 59, 27, 49, 17, 57, 25], + [15, 47, 7, 39, 13, 45, 5, 37], + [63, 31, 55, 23, 61, 29, 53, 21], +], dtype=np.float32) + + +def dither_bayer(gray): + """8x8 ordered dither to 1 bit; returns a bool array, True = white.""" + h, w = gray.shape + tile = np.tile((BAYER8 + 0.5) * (255.0 / 64.0), + (h // 8 + 1, w // 8 + 1))[:h, :w] + return gray.astype(np.float32) >= tile + + +def dither_fs(gray): + """Floyd-Steinberg to 1 bit; returns a bool array, True = white.""" + buf = gray.astype(np.float32) + h, w = buf.shape + for y in range(h): + row = buf[y] + for x in range(w): + old = row[x] + new = 255.0 if old >= 128.0 else 0.0 + row[x] = new + err = old - new + if x + 1 < w: + row[x + 1] += err * 7 / 16 + if y + 1 < h: + nxt = buf[y + 1] + if x: + nxt[x - 1] += err * 3 / 16 + nxt[x] += err * 5 / 16 + if x + 1 < w: + nxt[x + 1] += err * 1 / 16 + return buf >= 128.0 + + +def pack_frame(bw): + """bw: bool array indexed [y][x], True = white, shape (480, 800). + Returns FRAME_BYTES of controller-RAM-order data.""" + # packbits is MSB-first along the row, which is what the panel clocks out. + # No horizontal flip: png2bit_426.py mirrors its input, but on this wiring + # that comes out backwards -- checked against the panel. + return np.packbits(bw, axis=1).tobytes() + + +def unpack_frame(data): + """Inverse of pack_frame, for --preview.""" + return np.unpackbits( + np.frombuffer(data, dtype=np.uint8).reshape(DISP_H, DISP_STRIDE), axis=1 + ).astype(bool) + + +def write_preview(pack_path, png_path, tiles=9, scale=2): + """Contact sheet of frames read back out of the finished pack.""" + with open(pack_path, "rb") as f: + count = struct.unpack(HDR_FMT, f.read(64))[6] + n = min(tiles, count) + idx = ([round(i * (count - 1) / (n - 1)) for i in range(n)] + if n > 1 else [0]) + shots = [] + for i in idx: + f.seek(64 + i * FRAME_BYTES) + vis = unpack_frame(f.read(FRAME_BYTES)) + shots.append(np.where(vis, 255, 0).astype(np.uint8)) + + th, tw = shots[0].shape + cols = min(3, n) + rows = (n + cols - 1) // cols + gap = 6 + sheet = np.full((rows * (th + gap) + gap, cols * (tw + gap) + gap), + 128, dtype=np.uint8) # grey, so white frames show up + for k, shot in enumerate(shots): + r, c = divmod(k, cols) + y0, x0 = gap + r * (th + gap), gap + c * (tw + gap) + sheet[y0:y0 + th, x0:x0 + tw] = shot + + if scale > 1: + sheet = cv2.resize(sheet, (sheet.shape[1] * scale, sheet.shape[0] * scale), + interpolation=cv2.INTER_NEAREST) + cv2.imwrite(png_path, sheet) + return idx + + +def iter_source(args): + """Yield grayscale source frames along with the source frame rate.""" + cap = cv2.VideoCapture(args.input) + if not cap.isOpened(): + sys.exit(f"{args.input}: cannot open") + src_fps = cap.get(cv2.CAP_PROP_FPS) or 30.0 + total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) + + def gen(): + while True: + ok, frame = cap.read() + if not ok: + break + yield to_gray(frame) + cap.release() + + return gen(), src_fps, total + + +def main(): + args = parse_args() + + if args.fps <= 0: + sys.exit("--fps must be positive") + + source, src_fps, src_total = iter_source(args) + if args.fps > src_fps: + # there is nothing to sample past the source's own rate, so the pack + # would hold every frame there is but claim to play them faster -- + # i.e. silently speed the clip up + sys.exit(f"--fps {args.fps:g} is above the source's {src_fps:.2f} fps; " + f"the clip would play {args.fps / src_fps:.2f}x too fast") + step = src_fps / args.fps # source frames per output frame + first_src = int(round(args.start * src_fps)) + last_src = ( + first_src + int(round(args.duration * src_fps)) if args.duration else None + ) + + dst_w, dst_h = DISP_W, DISP_H + pad_value = 255 if args.pad_color == "white" else 0 + + lut = None + if args.gamma != 1.0: + lut = np.array( + [min(255, int(round(255.0 * (i / 255.0) ** (1.0 / args.gamma)))) + for i in range(256)], dtype=np.uint8 + ) + + print(f"source: {args.input} {src_fps:.2f} fps" + f"{f', {src_total} frames' if src_total else ''}") + print(f"output: {args.output} {dst_w}x{dst_h} @ {args.fps} fps" + f" ({FRAME_BYTES} bytes/frame)") + + frame_us = int(round(1_000_000 / args.fps)) + written = 0 + next_src = float(first_src) + + with open(args.output, "wb") as out: + out.write(struct.pack(HDR_FMT, EPDV_MAGIC, EPDV_VERSION, 0, 0, 0, 0, 0, 0)) + + for i, gray in enumerate(source): + if i < first_src: + continue + if last_src is not None and i >= last_src: + break + if i < next_src: + continue + next_src += step + + if lut is not None: + gray = cv2.LUT(gray, lut) + gray = fit_frame(gray, dst_w, dst_h, args.fit, pad_value) + if args.dither == "fs": + bw = dither_fs(gray) + elif args.dither == "bayer": + bw = dither_bayer(gray) + else: + bw = gray >= args.thresh + if args.invert: + bw = ~bw + data = pack_frame(bw) + + out.write(data) + written += 1 + if written % 100 == 0: + print(f"\r {written} frames packed", end="", flush=True) + + out.seek(0) + out.write(struct.pack(HDR_FMT, EPDV_MAGIC, EPDV_VERSION, 0, + dst_w, dst_h, frame_us, written, FRAME_BYTES)) + + if not written: + sys.exit("no frames written -- check --start/--duration") + + size_mb = (64 + written * FRAME_BYTES) / (1024 * 1024) + print(f"\rpacked {written} frames, {size_mb:.1f} MB, " + f"{written / args.fps:.1f} s of playback") + + if args.preview: + idx = write_preview(args.output, args.preview) + print(f"preview (unpacked from the file): {args.preview} " + f"frames {', '.join(str(i) for i in idx)}") + + +if __name__ == "__main__": + main() diff --git a/4.26/mono/spi/video/video_app.h b/4.26/mono/spi/video/video_app.h new file mode 100644 index 0000000..a0f6934 --- /dev/null +++ b/4.26/mono/spi/video/video_app.h @@ -0,0 +1,765 @@ +/* + * Author: LC Wang + * Date: 2026-08-11 + * + * Video player for the 4.26" mono PixPaper (800x480). + * Board-independent core: SPI, EPD command sequence, partial-refresh LUT and + * the frame-pack player. + * + * The GPIO backend is board-specific and lives in the per-board .c file, + * which must, before including this header, provide: + * + * epd_dc_set(v) set the DC line + * epd_rst_set(v) set the RST line + * epd_busy_get() read the BUSY line (1 = busy) + * int epd_gpio_init(void) acquire DC/RST/BUSY; return <0 on error + * void epd_gpio_release(void) release the lines and close the chip + */ +#ifndef VIDEO_APP_H +#define VIDEO_APP_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef EPD_SPI_DEVICE /* a board .c may pick a different spidev node */ +#define EPD_SPI_DEVICE "/dev/spidev0.0" +#endif + +#define DISP_W 800 +#define DISP_H 480 +#define DISP_STRIDE (DISP_W / 8) /* 100 bytes per row */ +#define DISP_BUF_SIZE (DISP_STRIDE * DISP_H) /* 48000 */ + +int spi_fd; + +static uint32_t g_spi_speed = 20000000; +static volatile sig_atomic_t g_stop; + +/* A wrong BUSY pin, or an unpowered panel, otherwise spins here forever -- + * and a tight spin cannot even be interrupted. */ +#define EPD_BUSY_TIMEOUT_MS 5000 + +/* Named so a stall says which step stalled, not just that one did. */ +static const char *g_wait_what = "startup"; + +/* 0x22 sequence run for each frame. 0x0C displays without cycling the analog + * supply, which epd_partial_begin() has already powered up; the OTP path uses + * 0xFF instead, which reloads that waveform on every frame. */ +static int g_update_seq = 0x0C; + +/* + * Drive length in frames, and the frame period the LUT counts them in. With + * ping-pong on, only the pixels that change are driven, so a short drive still + * looks clean: 4 frames at fr 4 runs about 16 fps with margin to spare. + * --tp 0 falls back to the controller's OTP waveform, five times slower. + */ +static int g_phase0_tp = 4; +static int g_fr = 4; /* -1 leaves the frame rate the OTP chose */ + +void sleep_ms(unsigned int milliseconds) { + struct timespec ts; + ts.tv_sec = milliseconds / 1000; + ts.tv_nsec = (milliseconds % 1000) * 1000000; + nanosleep(&ts, NULL); +} + +void sleep_us(unsigned int microseconds) { + struct timespec ts; + ts.tv_sec = microseconds / 1000000; + ts.tv_nsec = (microseconds % 1000000) * 1000; + nanosleep(&ts, NULL); +} + +static uint64_t now_us(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000000ull + ts.tv_nsec / 1000; +} + +void spi_write(uint8_t *data, int len) { + struct spi_ioc_transfer tr = { + .tx_buf = (unsigned long)data, + .len = len, + .speed_hz = g_spi_speed, + .bits_per_word = 8, + }; + ioctl(spi_fd, SPI_IOC_MESSAGE(1), &tr); +} + +void epd_writeCommand(uint8_t command) { + epd_dc_set(0); + sleep_us(1); + spi_write(&command, 1); +} + +void epd_writeData(uint8_t data) { + epd_dc_set(1); + sleep_us(1); + spi_write(&data, 1); +} + +void epd_writeData_bulk(const uint8_t *data, int len) { + epd_dc_set(1); + sleep_us(1); + while (len > 0) { + int chunk = len > 4096 ? 4096 : len; + spi_write((uint8_t *)data, chunk); + data += chunk; + len -= chunk; + } +} + +void epd_waitUntilIdle(void) { + uint64_t deadline = now_us() + EPD_BUSY_TIMEOUT_MS * 1000ull; + + sleep_ms(2); + while (epd_busy_get() != 0) { + if (g_stop) + return; + if (now_us() > deadline) { + fprintf(stderr, "\nBUSY still asserted %d ms into '%s' " + "-- check the BUSY pin, and that the panel is " + "connected and powered\n", + EPD_BUSY_TIMEOUT_MS, g_wait_what); + exit(1); + } + sleep_us(200); + } +} + +void epd_HWreset() { + sleep_ms(50); + epd_rst_set(0); + sleep_ms(50); + epd_rst_set(1); + sleep_ms(50); +} + +void epd_reg_init(void) { + g_wait_what = "reg init"; + epd_waitUntilIdle(); + + epd_writeCommand(0x18); /* internal temperature sensor */ + epd_writeData(0x80); + + epd_writeCommand(0x0C); /* booster soft start */ + epd_writeData(0xAE); + epd_writeData(0xC7); + epd_writeData(0xC3); + epd_writeData(0xC0); + epd_writeData(0x80); + + epd_writeCommand(0x01); /* driver output: 480 gate lines */ + epd_writeData((DISP_H - 1) & 0xFF); + epd_writeData((DISP_H - 1) >> 8); + epd_writeData(0x02); + + epd_writeCommand(0x3C); /* border waveform (full update) */ + epd_writeData(0x01); + + epd_writeCommand(0x44); /* RAM X window: 0..799 */ + epd_writeData(0x00); + epd_writeData(0x00); + epd_writeData((DISP_W - 1) & 0xFF); + epd_writeData((DISP_W - 1) >> 8); + + epd_writeCommand(0x45); /* RAM Y window: 0..479 */ + epd_writeData(0x00); + epd_writeData(0x00); + epd_writeData((DISP_H - 1) & 0xFF); + epd_writeData((DISP_H - 1) >> 8); + + epd_waitUntilIdle(); +} + +static void epd_reset_ram_counters(void) { + epd_writeCommand(0x4E); + epd_writeData(0x00); + epd_writeData(0x00); + + epd_writeCommand(0x4F); + epd_writeData(0x00); + epd_writeData(0x00); +} + +void epd_init(void) { + spi_fd = open(EPD_SPI_DEVICE, O_RDWR); + if (spi_fd < 0) { + perror("Error opening SPI device"); + exit(1); + } + + uint8_t spi_mode = SPI_MODE_0; + ioctl(spi_fd, SPI_IOC_WR_MODE, &spi_mode); + ioctl(spi_fd, SPI_IOC_WR_MAX_SPEED_HZ, &g_spi_speed); + + if (epd_gpio_init() < 0) + exit(1); + + g_wait_what = "power-on reset"; + epd_HWreset(); + sleep_ms(1000); + epd_waitUntilIdle(); + epd_reg_init(); + epd_reset_ram_counters(); +} + +/* Seed both RAM banks and full-refresh, so the differential has a known base. */ +void epd_set_base_map(const uint8_t *buf) { + g_wait_what = "base map"; + epd_reset_ram_counters(); + epd_writeCommand(0x24); + epd_writeData_bulk(buf, DISP_BUF_SIZE); + + epd_reset_ram_counters(); + epd_writeCommand(0x26); + epd_writeData_bulk(buf, DISP_BUF_SIZE); + + epd_writeCommand(0x22); + epd_writeData(0xF7); + epd_writeCommand(0x20); + epd_waitUntilIdle(); +} + +/* + * Partial waveform. Layout: bytes 0..49 are LUT0..LUT4, ten bytes each, one + * byte per group holding four phases at two bits (A in the top bits; + * 00 VSS, 01 VSH1, 10 VSL, 11 VSH2). Bytes 50..99 are ten groups of + * TP[A] TP[B] TP[C] TP[D] RP. Bytes 100..104 set the frame rate. + * + * Which of LUT0..LUT3 a pixel uses depends on ping-pong: without it the LUT + * follows the target colour alone, with it the pair (what is on the glass, + * what we want). wf_build() writes the second form, since epd_partial_begin() + * always turns ping-pong on. VSH1 drives toward black and VSL toward white -- + * that polarity is from the panel, which showed a negative with the other one, + * not from the datasheet. + */ +#define WF_LUT_BYTES 100 /* 105 when a frame rate is set */ +#define WF_TIMING_AT 50 +#define WF_FRAMERATE_AT 100 + +static uint8_t wf_partial[WF_FRAMERATE_AT + 5]; +static int wf_len = WF_LUT_BYTES; + +/* + * Panel-rated levels: 15 V / -15 V source swing, 20 V gate, -2.0 V VCOM. + * The stock driver's LUT carries 12 V / -12 V and a 13 V gate instead, but + * that belongs to its greyscale passes -- borrowing those for a black/white + * refresh leaves the gate unable to switch the pixel TFTs fully, which reads + * as an unclear image rather than merely a pale one. + */ +static uint8_t WF_VGH = 0x17; /* 20 V, what the panel is rated for */ +static uint8_t WF_VSH1 = 0x41; /* 15 V */ +static uint8_t WF_VSH2 = 0xA8; /* 5 V, power-on default; unused here */ +static uint8_t WF_VSL = 0x32; /* -15 V */ +static uint8_t WF_VCOM = 0x50; /* -2.0 V */ + +static int wf_build(int tp, int fr) { + memset(wf_partial, 0, sizeof(wf_partial)); + + /* + * With ping-pong on, the LUT is picked by the pair (what is on the + * glass, what we want), so the two no-change combinations stay at VSS + * and static areas are never touched. That is what lets a drive this + * short stay clean. Phase byte is [A:7-6][B:5-4][C:3-2][D:1-0], and + * only phase A runs. + */ + wf_partial[0] = 0x00; /* black -> black: idle */ + wf_partial[10] = 0x80; /* black -> white: VSL */ + wf_partial[20] = 0x40; /* white -> black: VSH1 */ + wf_partial[30] = 0x00; /* white -> white: idle */ + + wf_partial[WF_TIMING_AT] = (uint8_t)tp; /* TP[0A] */ + + if (fr < 0) /* leave the frame rate the OTP set */ + return WF_LUT_BYTES; + + memset(wf_partial + WF_FRAMERATE_AT, ((fr & 0xF) << 4) | (fr & 0xF), 5); + return WF_FRAMERATE_AT + 5; +} + +void epd_load_partial_lut(void) { + epd_writeCommand(0x03); /* gate voltage */ + epd_writeData(WF_VGH); + + epd_writeCommand(0x04); /* source voltage */ + epd_writeData(WF_VSH1); + epd_writeData(WF_VSH2); + epd_writeData(WF_VSL); + + epd_writeCommand(0x2C); /* VCOM */ + epd_writeData(WF_VCOM); + + epd_writeCommand(0x32); + epd_writeData_bulk(wf_partial, wf_len); + epd_waitUntilIdle(); +} + +/* + * Enter partial mode once. The stock driver resets the panel and reprograms + * these registers for every partial frame; hoisting that out of the loop is + * most of what makes this a video player rather than a slideshow. + */ +void epd_partial_begin(void) { + g_wait_what = "partial begin"; + epd_rst_set(0); + sleep_ms(10); + epd_rst_set(1); + sleep_ms(10); + epd_waitUntilIdle(); + + epd_writeCommand(0x18); + epd_writeData(0x80); + + epd_writeCommand(0x3C); /* partial border */ + epd_writeData(0x80); + + { + /* + * 0x37 byte F bit 6 turns on RAM ping-pong for display mode 2: + * the controller carries the displayed frame into the old bank + * itself and drives only the pixels that differ. It is off at + * power-on, and without it every frame repaints the whole panel, + * which is what smears. Mode 1 does not support it. + */ + static const uint8_t opt[10] = { + 0, 0, 0, 0, 0, 0x40, 0, 0, 0, 0 + }; + epd_writeCommand(0x37); + epd_writeData_bulk(opt, sizeof(opt)); + } + + if (g_phase0_tp > 0) { + wf_len = wf_build(g_phase0_tp, g_fr); + epd_load_partial_lut(); + } + + epd_writeCommand(0x44); + epd_writeData(0x00); + epd_writeData(0x00); + epd_writeData((DISP_W - 1) & 0xFF); + epd_writeData((DISP_W - 1) >> 8); + + epd_writeCommand(0x45); + epd_writeData(0x00); + epd_writeData(0x00); + epd_writeData((DISP_H - 1) & 0xFF); + epd_writeData((DISP_H - 1) >> 8); + + /* Power the analog up once here so a per-frame sequence does not have + * to. A display-only sequence such as 0x0C needs this: with the + * analog off it would wait on a frame that can never finish. */ + epd_writeCommand(0x22); + epd_writeData(0xC0); + epd_writeCommand(0x20); + epd_waitUntilIdle(); +} + +/* + * Only 0x24. On this controller the LUT is chosen by the pixel's target + * colour, not by an old-to-new transition: 0x24 = 0 picks LUT0 (drive black) + * and 0x24 = 1 picks LUT1 (drive white). The 0x26 RAM is the red channel, + * and on a black/white panel LUT2 and LUT3 are aliases of LUT0 and LUT1, so + * its content cannot change what is displayed -- writing it per frame would + * just double the SPI burst for nothing. + */ +void epd_partial_frame(const uint8_t *image) { + g_wait_what = "frame"; + epd_reset_ram_counters(); + epd_writeCommand(0x24); + epd_writeData_bulk(image, DISP_BUF_SIZE); + + epd_writeCommand(0x22); + epd_writeData((uint8_t)g_update_seq); + epd_writeCommand(0x20); + epd_waitUntilIdle(); +} + +/* + * A sequence ending in "disable analog, disable clock" -- 0xFF and friends -- + * has already powered the panel down, so there is nothing to do. Only a + * keep-on sequence leaves it running, and issuing 0x22 = 0x03 once the analog + * is already off leaves BUSY asserted, so use deep sleep instead; the next + * epd_HWreset() undoes it. + */ +void epd_partial_end(void) { + if (g_update_seq & 0x03) + return; + + epd_writeCommand(0x10); + epd_writeData(0x01); + sleep_ms(10); +} + +/* ---------------------------------------------------------------- player */ + +/* + * .epdv frame pack, written by video2epd.py. Little-endian. Frames follow + * the 64-byte header back to back, each already in controller RAM order + * (1 = white, 0 = black). + */ +#define EPDV_MAGIC "EPDV" +#define EPDV_VERSION 1 + +struct epdv_hdr { + char magic[4]; + uint16_t version; + uint16_t flags; + uint16_t width; /* logical, informational */ + uint16_t height; + uint32_t frame_us; /* nominal display time per frame */ + uint32_t frame_count; + uint32_t frame_bytes; + uint32_t reserved[10]; +}; + +_Static_assert(sizeof(struct epdv_hdr) == 64, "epdv header must be 64 bytes"); + +struct clip { + const struct epdv_hdr *hdr; + const uint8_t *frames; + void *map; + size_t map_len; + uint32_t count; + uint32_t frame_us; +}; + +static void on_signal(int sig) { + (void)sig; + g_stop = 1; +} + +static int clip_open(struct clip *c, const char *path) { + struct stat st; + int fd; + + fd = open(path, O_RDONLY); + if (fd < 0) { + fprintf(stderr, "%s: %s\n", path, strerror(errno)); + return -1; + } + if (fstat(fd, &st) < 0 || (size_t)st.st_size < sizeof(struct epdv_hdr)) { + fprintf(stderr, "%s: too small to be an .epdv pack\n", path); + close(fd); + return -1; + } + + c->map_len = st.st_size; + c->map = mmap(NULL, c->map_len, PROT_READ, MAP_PRIVATE, fd, 0); + close(fd); + if (c->map == MAP_FAILED) { + perror("mmap"); + return -1; + } + + c->hdr = c->map; + if (memcmp(c->hdr->magic, EPDV_MAGIC, 4)) { + fprintf(stderr, "%s: not an .epdv pack\n", path); + goto fail; + } + if (c->hdr->version != EPDV_VERSION) { + fprintf(stderr, "%s: unsupported version %u\n", path, + c->hdr->version); + goto fail; + } + if (c->hdr->frame_bytes != DISP_BUF_SIZE) { + fprintf(stderr, "%s: frame is %u bytes, this panel needs %d " + "(is this a pack for a different panel?)\n", + path, c->hdr->frame_bytes, DISP_BUF_SIZE); + goto fail; + } + + c->count = c->hdr->frame_count; + c->frame_us = c->hdr->frame_us ? c->hdr->frame_us : 500000; + if (!c->count || + c->map_len < sizeof(*c->hdr) + (size_t)c->count * DISP_BUF_SIZE) { + fprintf(stderr, "%s: truncated (%u frames declared)\n", path, + c->count); + goto fail; + } + + c->frames = (const uint8_t *)c->map + sizeof(struct epdv_hdr); + return 0; + +fail: + munmap(c->map, c->map_len); + return -1; +} + +static void clip_close(struct clip *c) { + if (c->map) + munmap(c->map, c->map_len); + c->map = NULL; +} + +static inline const uint8_t *clip_frame(const struct clip *c, uint32_t i) { + return c->frames + (size_t)i * DISP_BUF_SIZE; +} + +static uint8_t white_buf[DISP_BUF_SIZE]; + +/* Full white refresh; also re-seeds both RAM banks for the differential. */ +static void epd_clear_white(void) { + memset(white_buf, 0xFF, sizeof(white_buf)); + epd_HWreset(); + epd_reg_init(); + epd_set_base_map(white_buf); +} + +struct opts { + const char *path; + int loop; + int free_run; /* ignore the clip's rate: show every frame, flat out */ + int fps; /* 0 = use the clip's own rate */ + uint32_t start; + uint32_t refresh; /* full white refresh every N frames, 0 = never */ + int keep; /* leave the last frame on screen at exit */ + int quiet; +}; + +static void usage(const char *prog) { + fprintf(stderr, +"usage: %s [options] \n" +"\n" +"Play a packed frame file on the 4.26\" mono PixPaper. Build the pack with\n" +"video2epd.py (see README.md).\n" +"\n" +" --loop repeat the clip until Ctrl-C\n" +" --free show every frame as fast as the panel allows\n" +" --fps N play at N fps instead of the clip's own rate\n" +" --start N start at frame N\n" +" --refresh N full white refresh every N frames (0 = never, default)\n" +" --spi HZ SPI clock, default %u; 48000 bytes a frame makes this\n" +" the first thing worth raising\n" +" --update N 0x22 sequence per frame, default 0x%02X\n" +" --tp N drive frames per update, default %d; --tp 0 uses the\n" +" controller's OTP waveform instead (much slower)\n" +" --fr N LUT frame-rate code, how long one drive frame lasts,\n" +" default %d; too low and the gate scan cannot finish\n" +" --keep leave the last frame on screen instead of clearing\n" +" --quiet no per-frame progress line\n" +"\n" +"Unless --free is given the player follows the wall clock and drops frames it\n" +"cannot keep up with, so the clip always runs for its own length.\n", + prog, g_spi_speed, g_update_seq, g_phase0_tp, g_fr); +} + +/* --opt N: returns the value, or exits with the usage message. */ +static long need_arg(int argc, char **argv, int *i, const char *prog) { + char *end; + long v; + + if (*i + 1 >= argc) { + fprintf(stderr, "%s: missing value\n", argv[*i]); + usage(prog); + exit(2); + } + v = strtol(argv[++*i], &end, 0); + if (*end) { + fprintf(stderr, "%s: bad value '%s'\n", argv[*i - 1], argv[*i]); + exit(2); + } + return v; +} + +static int parse_opts(int argc, char **argv, struct opts *o) { + const char *prog = argv[0]; + int update_given = 0; + + for (int i = 1; i < argc; i++) { + const char *a = argv[i]; + + if (!strcmp(a, "--loop")) + o->loop = 1; + else if (!strcmp(a, "--free")) + o->free_run = 1; + else if (!strcmp(a, "--keep")) + o->keep = 1; + else if (!strcmp(a, "--quiet")) + o->quiet = 1; + else if (!strcmp(a, "--fps")) + o->fps = need_arg(argc, argv, &i, prog); + else if (!strcmp(a, "--start")) + o->start = need_arg(argc, argv, &i, prog); + else if (!strcmp(a, "--refresh")) + o->refresh = need_arg(argc, argv, &i, prog); + else if (!strcmp(a, "--spi")) + g_spi_speed = need_arg(argc, argv, &i, prog); + else if (!strcmp(a, "--update")) { + g_update_seq = need_arg(argc, argv, &i, prog); + update_given = 1; + } + else if (!strcmp(a, "--tp")) + g_phase0_tp = need_arg(argc, argv, &i, prog); + else if (!strcmp(a, "--fr")) + g_fr = need_arg(argc, argv, &i, prog); + else if (!strcmp(a, "-h") || !strcmp(a, "--help")) { + usage(prog); + exit(0); + } else if (a[0] == '-') { + fprintf(stderr, "unknown option: %s\n", a); + usage(prog); + return -1; + } else if (!o->path) { + o->path = a; + } else { + fprintf(stderr, "extra argument: %s\n", a); + return -1; + } + } + + if (!o->path) { + usage(prog); + return -1; + } + if (o->fps < 0 || o->fps > 1000) { + fprintf(stderr, "--fps out of range\n"); + return -1; + } + if (g_phase0_tp > 0xFF) { + fprintf(stderr, "--tp must fit in a byte\n"); + return -1; + } + /* 0x10 in the update sequence loads the OTP waveform, and it does so + * before displaying -- so it would discard a custom LUT every frame. */ + if (g_phase0_tp <= 0) { + if (!update_given) + g_update_seq = 0xFF; + } else if (update_given && (g_update_seq & 0x10)) { + fprintf(stderr, "warning: --update 0x%02X reloads the OTP " + "waveform, so --tp will have no effect\n", g_update_seq); + } + return 0; +} + +int main(int argc, char **argv) { + struct opts o = { 0 }; + struct clip clip = { 0 }; + uint64_t t_start, t_render = 0; + uint32_t shown = 0, dropped = 0, since_refresh = 0; + int64_t idx, last_idx; + + if (parse_opts(argc, argv, &o) < 0) + return 2; + if (clip_open(&clip, o.path) < 0) + return 1; + + if (o.fps) + clip.frame_us = 1000000u / (uint32_t)o.fps; + if (o.start >= clip.count) { + fprintf(stderr, "--start %u past the end (%u frames)\n", + o.start, clip.count); + clip_close(&clip); + return 2; + } + + printf("%s: %ux%u, %u frames, %.2f fps nominal (%.1f s)\n", + o.path, clip.hdr->width, clip.hdr->height, clip.count, + 1000000.0 / clip.frame_us, + clip.count * clip.frame_us / 1000000.0); + printf("spi=%u Hz (%.0f ms/frame of burst), update=0x%02X, waveform=%s," + " mode=%s\n", g_spi_speed, + DISP_BUF_SIZE * 8.0 * 1000.0 / g_spi_speed, g_update_seq, + g_phase0_tp > 0 ? "custom" : "OTP", + o.free_run ? "free-run" : "clocked"); + + signal(SIGINT, on_signal); + signal(SIGTERM, on_signal); + + epd_init(); + epd_clear_white(); + epd_partial_begin(); + + t_start = now_us(); + last_idx = (int64_t)o.start - 1; + + while (!g_stop) { + uint64_t t0, t1; + + if (o.free_run) { + idx = last_idx + 1; + } else { + /* wall-clock playhead: which frame should be up now */ + idx = o.start + (int64_t)((now_us() - t_start) / + clip.frame_us); + if (idx == last_idx) { + /* ahead of schedule: wait out the frame */ + uint64_t due = t_start + + (uint64_t)(idx + 1 - o.start) * clip.frame_us; + uint64_t n = now_us(); + if (due > n) + sleep_us(due - n); + continue; + } + } + + if (idx >= (int64_t)clip.count) { + if (!o.loop) { + dropped += clip.count - 1 - last_idx; + break; + } + t_start = now_us(); + o.start = 0; + last_idx = -1; + continue; + } + + dropped += idx - last_idx - 1; + + t0 = now_us(); + epd_partial_frame(clip_frame(&clip, (uint32_t)idx)); + t1 = now_us(); + + t_render += t1 - t0; + last_idx = idx; + shown++; + + if (!o.quiet && (shown & 0x07) == 0) { + printf("\rframe %6ld/%u shown %u dropped %u " + "%.1f ms/frame", (long)idx, clip.count, shown, + dropped, t_render / 1000.0 / shown); + fflush(stdout); + } + + if (o.refresh && ++since_refresh >= o.refresh) { + since_refresh = 0; + epd_partial_end(); + epd_clear_white(); + epd_partial_begin(); + if (!o.free_run) /* the hiccup is not the clip's fault */ + t_start = now_us() - + (uint64_t)(idx + 1 - o.start) * clip.frame_us; + } + } + + if (!o.quiet) + printf("\n"); + + epd_partial_end(); + if (!o.keep) + epd_clear_white(); + + if (shown) + printf("done: %u frames shown, %u dropped, %.1f ms/frame " + "(%.2f fps sustained)\n", shown, dropped, + t_render / 1000.0 / shown, 1000000.0 * shown / t_render); + + clip_close(&clip); + close(spi_fd); + epd_gpio_release(); + return 0; +} + +#endif /* VIDEO_APP_H */