diff --git a/2.13/mono/spi/video/.gitignore b/2.13/mono/spi/video/.gitignore new file mode 100644 index 0000000..1c3867d --- /dev/null +++ b/2.13/mono/spi/video/.gitignore @@ -0,0 +1,6 @@ +# keep source video and generated packs out of the repo +*.mp4 +*.mkv +*.webm +*.gif +*.epdv diff --git a/2.13/mono/spi/video/Makefile b/2.13/mono/spi/video/Makefile new file mode 100644 index 0000000..016d3eb --- /dev/null +++ b/2.13/mono/spi/video/Makefile @@ -0,0 +1,22 @@ +# Local build for the 2.13" 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-213-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/2.13/mono/spi/video/README.md b/2.13/mono/spi/video/README.md new file mode 100644 index 0000000..39d6542 --- /dev/null +++ b/2.13/mono/spi/video/README.md @@ -0,0 +1,237 @@ +# Video playback on the 2.13" mono PixPaper + +Plays a video on a 250x122 e-paper panel, using the same partial-refresh path +as the Open-EP Pet demo (`../pet/`). + + 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 4000-byte SPI burst per frame. Nothing is decoded or +bit-twiddled on the target — that matters on a slow SoC. + +Flat black-and-white silhouette animation is what a 1-bit panel renders best; +live-action footage works but needs dithering and still reads as mush at +250x122. + +## Build + +```sh +make +``` + +Needs libgpiod **v2** (`libgpiod-dev` on Trixie) — the Pi 5 backend uses the v2 +API and the Makefile stops with a clear message if it finds v1. + +The board `.c` is a thin GPIO backend; the SPI/EPD/player core lives in +`video_app.h`. If `gpiodetect` shows the `pinctrl-rp1` chip somewhere other than +`gpiochip15`, point the build at it — on Trixie / kernel 6.12+ it is `gpiochip0`: + +```sh +make EXTRA_CFLAGS='-DEPD_GPIO_CHIP=\"gpiochip0\"' +``` + +Getting this wrong fails at startup with "Error opening GPIO chip", which looks +like a wiring fault but is not. + +Only the Raspberry Pi 5 target exists here, because that is the only board this +has been run on. To add another, copy the board `.c`, change the gpiochip and +the three pins, and keep `#include "video_app.h"` last — the backend contract is +the five items listed at the top of that header. + +## Make a clip + +Needs `opencv-python` and `numpy` on the host (same deps as `../png2bit.py`). + +```sh +python3 video2epd.py your_video.mp4 -o clip.epdv --fps 6 + +# see what the panel will show, without a panel +python3 video2epd.py your_video.mp4 -o clip.epdv --fps 6 --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 6). Sets the file size and the pacing — match it to what your `--tp`/`--fr` actually sustain. | +| `--fit pad\|crop\|stretch` | letterbox (default), fill-and-cut, or squash. A 4:3 source letterboxes to 162x122; `crop` fills the screen but cuts heads off 4:3 footage. | +| `--thresh N` | black/white cut point, default 128. Lower = more black. | +| `--dither none\|bayer\|fs` | `none` suits flat animation. `bayer` is fast and fine for real footage; `fs` looks best but is slow (pure Python). | +| `--invert`, `--gamma`, `--start`, `--duration` | the obvious things. | +| `--portrait` | pack for a 122x250 portrait mounting. | + +The source can also be a directory of numbered PNGs (`--src-fps` then matters). + +At 6 fps a 3:40 clip is about 1300 frames, ~5 MB. + +## Play + +```sh +./pixpaper-213-m-test-rpi5-video clip.epdv +./pixpaper-213-m-test-rpi5-video clip.epdv --loop --tp 10 +./pixpaper-213-m-test-rpi5-video clip.epdv --free --quiet +``` + +| 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 | +| `--tp N` / `--fr N` | partial-waveform tuning, see below | +| `--refresh N` | full white refresh every N frames, to clear ghosting | +| `--start N`, `--keep`, `--quiet`, `--spi HZ` | | + +By default the player follows the wall clock: it works out which frame *should* +be on screen and skips any it could not keep up with, so the clip always runs +for its own length. `--free` turns that off and shows every frame, which is what +you want when measuring the panel. Either way it prints its own `ms/frame` and +sustained fps on exit. + +Ctrl-C (or SIGTERM) leaves partial mode cleanly and clears to white; `--keep` +leaves the last frame up. + +## Speed: --tp and --fr + +Per-frame time is set by the waveform, not by SPI — 4000 bytes at 5 MHz is +~6 ms. + +### Two things are called a "frame" + +Keep these apart or none of the numbers below make sense: + +| | what it is | how long | +| --- | --- | --- | +| **LUT frame** (a *tick*) | the waveform engine's time unit — one step at which the controller can change the voltage it applies | `period(fr)`, e.g. 13.3 ms at `--fr 3` | +| **displayed picture** | one image you actually see | `47.3 + (tp + 2) * period` ms | + +One picture = one whole run of the LUT = `tp + 2` ticks. A tick is not a +picture; `--tp` is not "pictures per second". + +### What one tick does + +Each tick the controller applies a voltage to every pixel, chosen by which +old-value → new-value group that pixel falls in. Phase 0 of `WF_PARTIAL`: + +| LUT group | transition | phase-0 byte | voltage | +| --- | --- | --- | --- | +| LUT0 | 0 → 0 (unchanged) | 0x00 | VSS — not driven | +| LUT1 | 0 → 1 (changing) | 0x80 | VSL (negative) | +| LUT2 | 1 → 0 (changing) | 0x40 | VSH1 (positive) | +| LUT3 | 1 → 1 (unchanged) | 0x00 | VSS — not driven | + +That is the ping-pong differential in hardware: unchanged pixels get VSS for the +whole picture and never move. + +E-paper pixels are physical — charged pigment particles migrating through fluid +— and one 13.3 ms tick nowhere near finishes the trip. `--tp` is therefore +closer to an **exposure time** than to a frame rate: `(tp + 2) * period` is how +long the field is held on the pixels that need to flip. Hold it too briefly and +the particles only get part way across, which reads as grey instead of black. + +The default `--tp 16 --fr 3` breaks down as: + + 287 ms per picture + ├─ 4 ms SPI: 4000 bytes into RAM + ├─ 43 ms 0x22/0x20 update sequence + BUSY wait <- fixed overhead + └─ 239 ms the LUT ─┬─ phase 0: 16 ticks x 13.3 ms = 213 ms <- the drive + ├─ phase 1: 1 tick x 13.3 ms = 13 ms + └─ phase 2: 1 tick x 13.3 ms = 13 ms + +Phases 3..11 are all zero in this waveform, which is where the `+ 2` comes +from — it is structural, not a fudge factor. + +### The model + +Measured on a Raspberry Pi 5 at 5 MHz SPI: + + frame_ms ~= 47.3 + (tp + 2) * period(fr) + +`--fr` is a *code*, not a duration: the 3-bit value goes into LUT bytes +144..149 (one nibble per phase, both nibbles set the same here) and the +controller looks the period up in its own table. + +| `--fr` | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| tick (ms) | 66.6 | 39.9 | 20.0 | **13.3** | 10.0 | 8.0 | 6.65 | 5.70 | +| ≈ Hz | 15 | 25 | 50 | **75** | 100 | 125 | 150 | 175 | + +`--tp` is LUT byte 60 (`TP[A]` of phase 0). That byte reads `0x14` (20) in the +`WF_PARTIAL` array but is always overwritten at upload, so the 20 is never +used — do not be misled by it when reading the table. + +The ~47 ms is fixed cost — the SPI burst, the update sequence and the BUSY +wait — so it is the hard floor: about 21 fps with zero drive time, which of +course draws nothing. Some real points: + + --tp 16 --fr 3 287 ms 3.5 fps (default; 239 ms of drive, solid black) + --tp 8 --fr 3 180 ms 5.6 fps + --tp 16 --fr 7 150 ms 6.7 fps + --tp 8 --fr 7 104 ms 9.6 fps (57 ms of drive -- expect it light) + --tp 1 --fr 7 64 ms 15.6 fps (17 ms of drive -- probably blank) + +The catch: what actually moves a pixel is the total drive time, +`(tp + 2) * period`, and every bit of speed above comes out of it. At matched +drive time the two knobs are interchangeable — `--tp 21 --fr 7` and +`--tp 8 --fr 3` are both ~132 ms of drive and both land at ~180 ms per frame. +So `--fr` buys no free speed; it buys **finer granularity** (5.7 ms steps +instead of 13.3 ms), which is what you want when tuning near the edge. + +No number here is right for your panel: contrast at a given drive time depends +on the unit and on room temperature. Sweep it and look at the screen: + +```sh +for tp in 16 12 10 8; do + ./pixpaper-213-m-test-rpi5-video clip.epdv --free --tp $tp --fr 7 +done +``` + +Then rebuild the pack at whatever fps you settled on, so playback is paced +instead of permanently dropping frames. + +## Ghosting + +Partial refresh never fully clears the previous image, and over thousands of +frames a faint residue builds up. `--refresh N` does a full white refresh every +N frames; it costs about two seconds and a visible flash, and the player +re-syncs the playhead afterwards. High-contrast silhouette footage tolerates a +lot of ghosting, so the default is off. + +## Why 0x24 only + +`epd_partial_frame()` writes the new frame to RAM bank 0x24 and never touches +0x26. The 0x37 setting loaded with the partial LUT puts the controller in +ping-pong mode: it keeps the previous frame in the other bank and drives only +the pixels that differ. Writing 0x26 by hand fights that and scrambles the +image. Same rule as the pet demo and the `partial`/`clock` modes in +`../pixpaper-213-m-test-rpi5.c`. + +## .epdv format + +64-byte little-endian header, then `frame_count` frames of `frame_bytes` each, +back to back: + +``` +0 char magic[4] "EPDV" +4 uint16 version 1 +6 uint16 flags bit0 = portrait +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 4000 for this panel +24 uint32 reserved[10] +64 frames... +``` + +Each frame is controller RAM order, bit 1 = white: + +``` +landscape byte = frame[x * 16 + (y >> 3)], bit 0x80 >> (y & 7) +portrait same, with gate = y and bit = 121 - x +``` + +which is exactly the layout `fb_set()` writes in the other examples, so anything +that can build one of those framebuffers can write a `.epdv` frame. diff --git a/2.13/mono/spi/video/pixpaper-213-m-test-rpi5-video.c b/2.13/mono/spi/video/pixpaper-213-m-test-rpi5-video.c new file mode 100644 index 0000000..eefb2c9 --- /dev/null +++ b/2.13/mono/spi/video/pixpaper-213-m-test-rpi5-video.c @@ -0,0 +1,149 @@ +/* + * 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. + */ +#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/2.13/mono/spi/video/video2epd.py b/2.13/mono/spi/video/video2epd.py new file mode 100644 index 0000000..80719e6 --- /dev/null +++ b/2.13/mono/spi/video/video2epd.py @@ -0,0 +1,327 @@ +#!/usr/bin/env python3 +"""Pack a video (or a directory of images) into an .epdv frame file for the +2.13" 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: + + landscape RAM byte = frame[x * 16 + (y >> 3)], bit 0x80 >> (y & 7) + portrait same, with gate = y and bit = 121 - x + +Bit value 1 = white, 0 = black -- same convention as fb_set() in the C code. + +examples: + python3 video2epd.py clip.mp4 -o clip.epdv --fps 6 + python3 video2epd.py clip.mp4 -o clip.epdv --fps 8 --preview sheet.png + python3 video2epd.py frames/ -o clip.epdv --fps 4 --src-fps 30 --dither bayer +""" + +import argparse +import os +import struct +import sys + +import cv2 +import numpy as np + +DISP_W = 250 # gate axis (landscape width) +DISP_VIS = 122 # visible rows +DISP_H = 128 # RAM rows per gate line (122 visible + 6 padding) +DISP_STRIDE = DISP_H // 8 +FRAME_BYTES = DISP_W * DISP_STRIDE # 4000 + +EPDV_MAGIC = b"EPDV" +EPDV_VERSION = 1 +EPDV_FLAG_PORTRAIT = 0x0001 +HDR_FMT = "<4sHHHHIII40x" # 64 bytes, see struct epdv_hdr + +IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".bmp", ".pgm", ".tif", ".tiff") + + +def parse_args(): + p = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + p.add_argument("input", help="video file, or a directory of numbered images") + p.add_argument("-o", "--output", default="clip.epdv", help="output .epdv file") + p.add_argument("--fps", type=float, default=6.0, + help="playback frame rate (default 6; the panel does roughly " + "3-8 fps depending on the player's --tp)") + p.add_argument("--src-fps", type=float, + help="source frame rate; needed only for image directories " + "or when the container lies (default 30)") + p.add_argument("--portrait", action="store_true", + help="pack for a portrait (122x250) panel orientation") + 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, portrait): + """bw: bool array indexed [y][x], True = white -- (122,250) landscape, + (250,122) portrait. Returns FRAME_BYTES of controller-RAM-order data.""" + if portrait: + # logical (x,y) -> gate = y, bit = 121 - x + canvas = np.ones((DISP_W, DISP_H), dtype=bool) # 250 gates x 128 bits + canvas[:, :DISP_VIS] = bw[:, ::-1] + else: + # logical (x,y) -> gate = x, bit = y + canvas = np.ones((DISP_W, DISP_H), dtype=bool) + canvas[:, :DISP_VIS] = bw.T + + # packbits is MSB-first along axis 1, which is exactly 0x80 >> (bit & 7) + return np.packbits(canvas, axis=1).tobytes() + + +def unpack_frame(data, portrait): + """Inverse of pack_frame, for --preview.""" + canvas = np.unpackbits( + np.frombuffer(data, dtype=np.uint8).reshape(DISP_W, DISP_STRIDE), axis=1 + ).astype(bool) + vis = canvas[:, :DISP_VIS] + return vis[:, ::-1] if portrait else vis.T + + +def write_preview(pack_path, png_path, portrait, 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), portrait) + 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.""" + if os.path.isdir(args.input): + names = sorted( + n for n in os.listdir(args.input) if n.lower().endswith(IMAGE_EXTS) + ) + if not names: + sys.exit(f"{args.input}: no images found") + src_fps = args.src_fps or 30.0 + + def gen(): + for n in names: + img = cv2.imread(os.path.join(args.input, n), cv2.IMREAD_GRAYSCALE) + if img is None: + sys.exit(f"{n}: cannot read") + yield img + + return gen(), src_fps, len(names) + + cap = cv2.VideoCapture(args.input) + if not cap.isOpened(): + sys.exit(f"{args.input}: cannot open") + src_fps = args.src_fps or 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) + 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_VIS, DISP_W) if args.portrait else (DISP_W, DISP_VIS) + 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}" + f"{' portrait' if args.portrait else ''} @ {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, args.portrait) + + 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, + EPDV_FLAG_PORTRAIT if args.portrait else 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, args.portrait) + 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/2.13/mono/spi/video/video_app.h b/2.13/mono/spi/video/video_app.h new file mode 100644 index 0000000..46176b4 --- /dev/null +++ b/2.13/mono/spi/video/video_app.h @@ -0,0 +1,705 @@ +/* + * Author: LC Wang + * Date: 2026-08-11 + * + * Video player for the 2.13" mono PixPaper (250x122 landscape). + * 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 250 +#define DISP_H 128 +#define DISP_VIS 122 +#define DISP_STRIDE (DISP_H / 8) +#define DISP_BUF_SIZE (DISP_W * DISP_STRIDE) +#define DISP_GATE_MAX (DISP_W - 1) + +int spi_fd; + +static uint32_t g_spi_speed = 5000000; + +/* LUT byte 60 (phase-0 frame count) and the frame-rate code that fills + * bytes 144..149; both overridable from the command line. */ +static int g_phase0_tp = 0x10; +static int g_fr = 3; + +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() { + sleep_ms(2); + while (epd_busy_get() != 0) + ; +} + +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) { + epd_waitUntilIdle(); + epd_writeCommand(0x12); /* SW reset */ + epd_waitUntilIdle(); + + epd_writeCommand(0x01); /* driver output: 250 gate lines */ + epd_writeData(0xF9); + epd_writeData(0x00); + epd_writeData(0x00); + + epd_writeCommand(0x11); /* data entry: Y decrement, X increment */ + epd_writeData(0x01); + + epd_writeCommand(0x44); /* RAM X window: 0..15 (16 bytes) */ + epd_writeData(0x00); + epd_writeData(0x0F); + + epd_writeCommand(0x45); /* RAM Y window: 249..0 */ + epd_writeData(0xF9); + epd_writeData(0x00); + epd_writeData(0x00); + epd_writeData(0x00); + + epd_writeCommand(0x3C); /* border waveform (full update) */ + epd_writeData(0x05); + + epd_writeCommand(0x21); /* display update control 1 */ + epd_writeData(0x00); + epd_writeData(0x80); + + epd_writeCommand(0x18); /* internal temperature sensor */ + epd_writeData(0x80); + + epd_writeCommand(0x4E); /* RAM X counter = 0 */ + epd_writeData(0x00); + epd_writeCommand(0x4F); /* RAM Y counter = 249 */ + epd_writeData(0xF9); + epd_writeData(0x00); + + epd_waitUntilIdle(); +} + +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); + + epd_HWreset(); + sleep_ms(1000); + epd_waitUntilIdle(); + epd_reg_init(); +} + +/* xb* are RAM-X byte addresses (0x44/0x4E); g_* are 9-bit gate lines, counting + * down (0x45/0x4F, data-entry mode 0x01). */ +static void epd_set_window(int xb_start, int xb_end, int g_start, int g_end) { + epd_writeCommand(0x44); + epd_writeData(xb_start & 0xFF); + epd_writeData(xb_end & 0xFF); + + epd_writeCommand(0x45); + epd_writeData(g_start & 0xFF); + epd_writeData((g_start >> 8) & 0xFF); + epd_writeData(g_end & 0xFF); + epd_writeData((g_end >> 8) & 0xFF); +} + +static void epd_set_cursor(int xb, int g) { + epd_writeCommand(0x4E); + epd_writeData(xb & 0xFF); + + epd_writeCommand(0x4F); + epd_writeData(g & 0xFF); + epd_writeData((g >> 8) & 0xFF); +} + +static void epd_set_full_window(void) { + epd_set_window(0x00, DISP_STRIDE - 1, DISP_GATE_MAX, 0x00); +} + +static void epd_set_full_cursor(void) { + epd_set_cursor(0x00, DISP_GATE_MAX); +} + +/* Seed both RAM banks (0x24 new, 0x26 old/diff) and full-refresh (0xF7). */ +void epd_set_base_map(const uint8_t *buf) { + epd_set_full_window(); + + epd_set_full_cursor(); + epd_writeCommand(0x24); + epd_writeData_bulk(buf, DISP_BUF_SIZE); + + epd_set_full_cursor(); + epd_writeCommand(0x26); + epd_writeData_bulk(buf, DISP_BUF_SIZE); + + epd_writeCommand(0x22); + epd_writeData(0xF7); + epd_writeCommand(0x20); + epd_waitUntilIdle(); +} + +/* + * Partial-refresh waveform. The panel's built-in OTP Mode-2 waveform leaves + * static areas grey, so drive our own: 153 LUT bytes + 6 voltage bytes. + */ +static const uint8_t WF_PARTIAL[159] = { + 0x0, 0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x80, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x40, 0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x14, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x0, 0x0, 0x0, /* end of 153 LUT bytes */ + 0x22, 0x17, 0x41, 0x0, 0x32, 0x36, /* EOPT, VGH, VSH1, VSH2, VSL, VCOM */ +}; + +/* Upload the partial waveform + voltages (0x37 enables RAM ping-pong). */ +void epd_load_partial_lut(void) { + uint8_t fr_byte = ((g_fr & 7) << 4) | (g_fr & 7); + + epd_writeCommand(0x32); /* LUT (153 bytes) */ + for (int i = 0; i < 153; i++) { + uint8_t b = WF_PARTIAL[i]; + if (i == 60) + b = (uint8_t)g_phase0_tp; + else if (i >= 144 && i <= 149) + b = fr_byte; + epd_writeData(b); + } + epd_waitUntilIdle(); + + epd_writeCommand(0x3F); /* EOPT */ + epd_writeData(WF_PARTIAL[153]); + epd_writeCommand(0x03); /* gate voltage */ + epd_writeData(WF_PARTIAL[154]); + epd_writeCommand(0x04); /* source voltage */ + epd_writeData(WF_PARTIAL[155]); + epd_writeData(WF_PARTIAL[156]); + epd_writeData(WF_PARTIAL[157]); + epd_writeCommand(0x2C); /* VCOM */ + epd_writeData(WF_PARTIAL[158]); + + epd_writeCommand(0x37); + epd_writeData(0x00); + epd_writeData(0x00); + epd_writeData(0x00); + epd_writeData(0x00); + epd_writeData(0x00); + epd_writeData(0x40); + epd_writeData(0x00); + epd_writeData(0x00); + epd_writeData(0x00); + epd_writeData(0x00); + + epd_writeCommand(0x3C); /* partial border */ + epd_writeData(0x80); +} + +/* Re-assert orientation/source registers after the reset pulse (no 0x12, so + * the RAM banks survive for the ping-pong differential). */ +static void epd_partial_regs(void) { + epd_writeCommand(0x01); /* 250 gate lines */ + epd_writeData(0xF9); + epd_writeData(0x00); + epd_writeData(0x00); + + epd_writeCommand(0x11); /* data entry: Y decrement, X increment */ + epd_writeData(0x01); + + epd_writeCommand(0x21); /* display update control 1 */ + epd_writeData(0x00); + epd_writeData(0x80); + + epd_writeCommand(0x18); /* internal temperature sensor */ + epd_writeData(0x80); +} + +#define DISPLAY_PART_KEEP_ON 0x0C /* display only, leave clock+analog on */ + +/* Enter partial mode once: reset pulse, registers, LUT, power up. */ +void epd_partial_begin(void) { + epd_rst_set(0); /* reset pulse (RAM is preserved) */ + sleep_ms(2); + epd_rst_set(1); + sleep_ms(2); + + epd_partial_regs(); + epd_load_partial_lut(); + + epd_writeCommand(0x22); /* warm up: enable clock + analog */ + epd_writeData(0xC0); + epd_writeCommand(0x20); + epd_waitUntilIdle(); + + epd_set_full_window(); +} + +/* + * One frame. Write the whole frame to the new bank (0x24) ONLY: hardware + * ping-pong keeps the last frame in the old bank and diffs against it, so only + * changed pixels are driven. Writing 0x26 here would fight the ping-pong and + * scramble the image. + */ +void epd_partial_frame(const uint8_t *image) { + epd_set_full_cursor(); + epd_writeCommand(0x24); + epd_writeData_bulk(image, DISP_BUF_SIZE); + + epd_writeCommand(0x22); + epd_writeData(DISPLAY_PART_KEEP_ON); + epd_writeCommand(0x20); + epd_waitUntilIdle(); +} + +/* Leave partial mode: power the analog back down. */ +void epd_partial_end(void) { + epd_writeCommand(0x22); + epd_writeData(0x03); + epd_writeCommand(0x20); + epd_waitUntilIdle(); +} + +/* ---------------------------------------------------------------- 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 +#define EPDV_FLAG_PORTRAIT 0x0001 + +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 volatile sig_atomic_t g_stop; + +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\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 : 200000; + 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 ping-pong. */ +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 2.13\" 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" +" --tp N LUT phase-0 frames, default %d; lower = faster, lighter\n" +" --fr N LUT frame-rate code 0..7, default %d\n" +" --spi HZ SPI clock, default %u\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_phase0_tp, g_fr, g_spi_speed); +} + +/* --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]; + + 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, "--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, "--spi")) + g_spi_speed = 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; + } + 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)%s\n", + o.path, clip.hdr->width, clip.hdr->height, clip.count, + 1000000.0 / clip.frame_us, + clip.count * clip.frame_us / 1000000.0, + (clip.hdr->flags & EPDV_FLAG_PORTRAIT) ? ", portrait" : ""); + printf("waveform: tp=%d fr=%d, spi=%u Hz, mode=%s\n", + g_phase0_tp, g_fr, g_spi_speed, 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) { + /* whatever the tail overshot is dropped too */ + dropped += clip.count - 1 - last_idx; + break; + } + t_start = now_us(); + o.start = 0; + last_idx = -1; + continue; + } + + /* count the skipped frames only once we know they were real */ + 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 & 0x0F) == 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 */