diff --git a/README.md b/README.md
index d8a8891d6..11977f2cc 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@ Supported operating systems : macOS, Windows, Linux (incl. Raspberry Pi), basica
| ✅ Turing Smart Screen / TURZX |
|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
-| All available sizes and hardware revisions supported: **2.1" / 2.8" / 3.5" / 4.6" / 5" / 5.2" / 8.0" / 8.8" / 9.2" / 12.3"**
UART and USB protocols supported. Note: no video or storage support for now |
+| All available sizes and hardware revisions supported: **2.1" / 2.8" / 3.5" / 4.6" / 5" / 5.2" / 8.0" / 8.8" / 9.2" / 12.3"**
UART and USB protocols supported. Note: no video or storage support for now, except the [rev C 2.1" video face](res/docs/rev-c-video-face.md) |
| ✅ XuanFang 3.5" | ✅ [UsbPCMonitor 3.5" / 5"](https://aliexpress.com/item/1005003931363455.html) | ✅ Kipye Qiye Smart Display 3.5" |
|---------------------------------------------------|-----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
@@ -94,6 +94,8 @@ Some themes are already included for a quick start!
### [> Themes shared by the community](https://github.com/mathoudebine/turing-smart-screen-python/discussions/categories/themes)
and more... Share yours!
+### [> Animated video face for 2.1" round rev C screens](res/docs/rev-c-video-face.md)
+
## Control the display from your Python projects
diff --git a/config.yaml b/config.yaml
index 8aef493e4..a9ee5a272 100644
--- a/config.yaml
+++ b/config.yaml
@@ -78,3 +78,33 @@ display:
# This behavior causes the display to disconnect/reconnect, and the COM port to change.
# On some displays (like rev. A) it can be an issue, in this case change the value to "false".
RESET_ON_STARTUP: true
+
+# Optional: only used by video-face-rev-c.py (animated video face for the 2.1" round rev C screen)
+# See res/docs/rev-c-video-face.md. All keys are optional, the values below are the defaults.
+video_face:
+ # Rows to display, top to bottom, among CPU / GPU / RAM
+ ROWS: [CPU, GPU, RAM]
+
+ # Seconds between sensor samples (one new bar each time)
+ SAMPLE_PERIOD: 0.5
+
+ # Directory of the screen where the video is stored, and name prefix of the video file in it.
+ # Older videos with this prefix are deleted when a new one is uploaded (the storage is only about 1.2 MB)
+ REMOTE_DIR: /root/video/
+ REMOTE_PREFIX: video_face_
+
+ # Bar colours: bars are a vertical gradient (like btop), the colour of each pixel row depends on its level (%, distance
+ # from the centre line relative to the max bar height), not on the bar value, so a bar "stops" at the colour of its
+ # level. List of [level %, [R, G, B]] stops, sorted by level, from 0 to 100; colours are linearly interpolated
+ # between stops. Replaces the former BAR_COLOR_* / *_UNTIL / *_FROM keys (ignored with a warning if still present)
+ BAR_GRADIENT:
+ - [0, [25, 160, 230]] # light blue
+ - [25, [25, 160, 230]] # light blue until 25 %
+ - [35, [110, 210, 240]] # light cyan
+ - [42, [235, 245, 205]] # pale cream (bright bridge, avoids a muddy blue-yellow mix)
+ - [50, [255, 235, 90]] # pale yellow
+ - [60, [255, 210, 40]] # golden yellow
+ - [70, [255, 170, 30]] # amber
+ - [82, [255, 120, 25]] # orange
+ - [94, [255, 50, 40]] # red
+ - [100, [255, 50, 40]]
diff --git a/library/config.py b/library/config.py
index c89200322..bac9ccb20 100644
--- a/library/config.py
+++ b/library/config.py
@@ -40,6 +40,30 @@ def load_yaml(configfile):
FONTS_DIR = str(MAIN_DIRECTORY / "res" / "fonts") + "/"
CONFIG_DATA = load_yaml(MAIN_DIRECTORY / "config.yaml")
THEME_DEFAULT = load_yaml(MAIN_DIRECTORY / "res/themes/default.yaml")
+
+# Optional "video_face" section of config.yaml, only used by video-face-rev-c.py (see res/docs/rev-c-video-face.md)
+VIDEO_FACE_DEFAULT = {
+ "ROWS": ["CPU", "GPU", "RAM"], # rows to display, among CPU / GPU / RAM
+ "SAMPLE_PERIOD": 0.5, # seconds between sensor samples (one new bar each)
+ "REMOTE_DIR": "/root/video/", # directory of the screen where the video is stored
+ "REMOTE_PREFIX": "video_face_", # name prefix of the video on the screen (older ones with it are replaced)
+ # Bar colours by level (%, 0 = centre line of the row, 100 = max bar extent): [level, [R, G, B]] stops, sorted,
+ # from 0 to 100, colours are linearly interpolated between stops
+ "BAR_GRADIENT": [
+ [0, [25, 160, 230]], # light blue
+ [25, [25, 160, 230]], # light blue until 25 %
+ [35, [110, 210, 240]], # light cyan
+ [42, [235, 245, 205]], # pale cream (bright bridge, avoids a muddy blue-yellow mix)
+ [50, [255, 235, 90]], # pale yellow
+ [60, [255, 210, 40]], # golden yellow
+ [70, [255, 170, 30]], # amber
+ [82, [255, 120, 25]], # orange
+ [94, [255, 50, 40]], # red
+ [100, [255, 50, 40]],
+ ],
+}
+_video_face_user = CONFIG_DATA.get("video_face")
+VIDEO_FACE_DATA = {**VIDEO_FACE_DEFAULT, **(_video_face_user if isinstance(_video_face_user, dict) else {})}
THEME_DATA = None
diff --git a/library/lcd/lcd_comm_rev_c.py b/library/lcd/lcd_comm_rev_c.py
index 5de42bfa0..ddd7e09fb 100644
--- a/library/lcd/lcd_comm_rev_c.py
+++ b/library/lcd/lcd_comm_rev_c.py
@@ -363,13 +363,15 @@ def DisplayPILImage(
payload=bytearray(self._generate_full_image(image)),
readsize=1024)
self._send_command(Command.QUERY_STATUS, readsize=1024)
+ # The display expects the render count of partial updates to restart at 0 after each full frame
+ Count.Start = 0
else:
with self.update_queue_mutex:
img, pyd = self._generate_update_image(image, x, y, Count.Start, Command.UPDATE_BITMAP)
self._send_command(Command.SEND_PAYLOAD, payload=pyd)
self._send_command(Command.SEND_PAYLOAD, payload=img)
self._send_command(Command.QUERY_STATUS, readsize=1024)
- Count.Start += 1
+ Count.Start += 1
def _generate_full_image(self, image: Image.Image) -> bytes:
if self.sub_revision == SubRevision.REV_8INCH:
@@ -460,8 +462,9 @@ def _generate_update_image(
payload.extend(Padding.NULL.value * 3)
payload.extend(count.to_bytes(4, 'big'))
- if len(img_raw_data) > 250:
- img_raw_data = bytearray(b'\x00').join(chunked(bytes(img_raw_data), 249))
+ # The display reads 249 data bytes per 250-byte packet, the last byte of each packet being a separator.
+ # The "ef69" terminator is part of this data stream, so it must be added before chunking.
img_raw_data += b'\xef\x69'
+ img_raw_data = bytearray(b'\x00').join(chunked(bytes(img_raw_data), 249))
return img_raw_data, payload
diff --git a/library/lcd/lcd_comm_rev_c_video.py b/library/lcd/lcd_comm_rev_c_video.py
new file mode 100644
index 000000000..b66c83557
--- /dev/null
+++ b/library/lcd/lcd_comm_rev_c_video.py
@@ -0,0 +1,486 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# turing-smart-screen-python - a Python system monitor and library for USB-C displays like Turing Smart Screen or XuanFang
+# https://github.com/mathoudebine/turing-smart-screen-python/
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see .
+
+# Driver extension for the rev C 2.1" round screen (480x480) using its built-in video player plus the video overlay:
+# a looping video is stored on the screen and decoded by the screen itself, the host only sends small incremental
+# overlay updates on top of it. This module only adds to LcdCommRevC (port detection, commands, framing helpers); it
+# does not change the behaviour of the existing driver. See res/docs/rev-c-video-face.md for protocol notes.
+#
+# Protocol credits: incremental overlay updates derive from PR #348 of mathoudebine/turing-smart-screen-python
+# (gwendal-h), video overlay initialisation from maylton/turing-smart-screen-video-overlay (both GPL-3.0).
+
+import hashlib
+import itertools
+import re
+import threading
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Callable, List, Optional, Tuple
+
+import numpy as np
+import serial
+
+from library.lcd.lcd_comm_rev_c import LcdCommRevC, Command, SubRevision
+from library.lcd.rev_c_errors import DeviceError, FatalError, StopRequested, UploadSizeError, VideoFaceError # noqa: F401
+from library.lcd.serialize import chunked
+from library.log import logger
+
+SIZE = 480
+
+# The storage for videos on the screen (/root/video/) holds about 1.2 MB: larger uploads are silently truncated
+MAX_VIDEO_BYTES = 1_100_000
+
+SERIAL_OPEN_ATTEMPTS = 10
+SERIAL_WRITE_TIMEOUT = 10 # seconds
+HELLO_ATTEMPTS = 5
+UPLOAD_WRITE_PACKETS = 128 # 250-byte packets per serial write during an upload (32 KB)
+
+CMD_LIST, CMD_DELETE, CMD_UPLOAD, CMD_FILE_SIZE, CMD_PLAY = 0x65, 0x66, 0x6F, 0x6E, 0x78
+CMD_INIT_OVERLAY = bytes((0xCA, 0xEF, 0x69, 0x00, 0x0E, 0x10))
+CMD_OVERLAY_VISIBLE = bytes((0xD0, 0xEF, 0x69, 0x00))
+TERMINATOR = b"\xef\x69"
+
+
+@dataclass
+class Status:
+ need_resend: Optional[bool] # None: empty or unparsable reply
+ render_cnt: Optional[int]
+ text: str
+
+ @property
+ def ok(self) -> bool:
+ return self.need_resend is False
+
+
+@dataclass
+class UpdateResult:
+ status: Status
+ payload_bytes: int # 0 when nothing changed
+ seconds: float
+ recovered: bool # the overlay had to be re-initialised
+
+
+def pad250(data: bytes, fill: int = 0x00) -> bytes:
+ """Every write to the screen is a multiple of 250 bytes."""
+ data = bytes(data)
+ return data + bytes([fill]) * (-len(data) % 250)
+
+
+def chunk_stream(data: bytes) -> bytes:
+ """The screen takes 249 data bytes from each 250-byte packet; the 250th byte is a separator."""
+ return b"\x00".join(chunked(bytes(data), 249))
+
+
+def to_native(rgba: np.ndarray, reverse: bool) -> np.ndarray:
+ """Rotate an upright image into the screen's native frame: DISPLAY_REVERSE true -> np.rot90 k=3 (confirmed upright
+ on the device), false -> k=1 (derived by adding 180 degrees, not verified on a device)."""
+ return np.ascontiguousarray(np.rot90(rgba, 3 if reverse else 1))
+
+
+def runs(mask_row: np.ndarray, min_gap: int = 1) -> List[Tuple[int, int]]:
+ """[(start, end)] of the True runs in a 1-D mask; runs separated by less than min_gap pixels are merged."""
+ xs = np.flatnonzero(mask_row)
+ if xs.size == 0:
+ return []
+ br = np.flatnonzero(np.diff(xs) > min_gap)
+ return list(zip(xs[np.concatenate(([0], br + 1))].tolist(), (xs[np.concatenate((br, [xs.size - 1]))] + 1).tolist()))
+
+
+def visible_list(alpha: np.ndarray) -> bytes:
+ """Runs `pos(3)=y*480+x, len(2)` of all the pixels with alpha > 0 (native frame)."""
+ out = bytearray()
+ for y in np.flatnonzero((alpha > 0).any(axis=1)):
+ for s, e in runs(alpha[y] > 0):
+ out += int(y * SIZE + s).to_bytes(3, "big") + int(e - s).to_bytes(2, "big")
+ return bytes(out)
+
+
+def compress_px(rgba_row: np.ndarray) -> bytes:
+ """3 bytes per pixel: B&0xFC | a4>>2, G&0xFC | a4&3, R with a4 = alpha>>4."""
+ r, g, b, a = (rgba_row[:, i].astype(np.uint16) for i in range(4))
+ a4 = a >> 4
+ return np.stack([(b & 0xFC) | (a4 >> 2), (g & 0xFC) | (a4 & 3), r], axis=1).astype(np.uint8).tobytes()
+
+
+def frame_overlay_update(raw: bytes, count: int, visible_size: int) -> Tuple[bytes, bytes]:
+ """(header, body) of one overlay update (UPDATE_BITMAP with the extra visible_size field). Each part must be
+ zero-padded to a multiple of 250 bytes when written. Same framing as LcdCommRevC._generate_update_image: the
+ terminator is part of the 249-byte chunked data stream."""
+ header = (bytes(Command.UPDATE_BITMAP.value) + (len(raw) + 2).to_bytes(3, "big") + bytes(3)
+ + count.to_bytes(4, "big") + visible_size.to_bytes(4, "big"))
+ return header, chunk_stream(bytes(raw) + TERMINATOR)
+
+
+def parse_status(text: str) -> Status:
+ """'needReSend:0|renderCnt:123' -> Status; need_resend / render_cnt are None if not parseable."""
+ m = re.search(r"needReSend:(\d)\|renderCnt:(\d+)", text)
+ if not m:
+ return Status(None, None, text)
+ return Status(m.group(1) == "1", int(m.group(2)), text)
+
+
+def parse_hello(reply: str) -> Optional[int]:
+ """ROM version from a HELLO reply like 'chs_5inch.dev1_rom1.89'; None if the reply is not a valid ID."""
+ if not reply.startswith("chs_"):
+ return None
+ try:
+ return int(reply.split(".")[2])
+ except (IndexError, ValueError):
+ return 0 # valid ID but unknown ROM version
+
+
+def check_video_size(size: int) -> None:
+ """Refuse a video that cannot fit in the storage of the screen, before anything is deleted or written there."""
+ if size > MAX_VIDEO_BYTES:
+ raise FatalError(f"video is {size} bytes, more than the {MAX_VIDEO_BYTES} bytes the screen can store "
+ f"(/root/video/ holds about 1.2 MB)")
+
+
+def remote_video_name(prefix: str, data: bytes) -> str:
+ return f"{prefix}{hashlib.sha1(data).hexdigest()[:8]}.mp4"
+
+
+class LcdCommRevCVideo(LcdCommRevC):
+ """LcdCommRevC for the 2.1" model with video storage / playback and video overlay commands. Unlike the base
+ driver it does not use the update queue (everything is sequential) and raises DeviceError instead of exiting
+ when the serial link fails, so the caller can recover."""
+
+ def __init__(self, com_port: str = "AUTO"):
+ self._lock = threading.RLock()
+ self.stop_requested = lambda: False # type: Callable[[], bool]
+ self.port = None # type: Optional[str]
+ LcdCommRevC.__init__(self, com_port, SIZE, SIZE, None)
+ self.sub_revision = SubRevision.REV_2INCH
+ self._prev = None # last overlay image shown (native RGBA)
+ self._count = 0 # overlay update count: restarts at 0 after each full overlay init
+ self._video = None # type: Optional[str]
+ self._rc = None # last renderCnt
+ self._rc_since = time.monotonic()
+ self.stats = dict(updates=0, failures=0, recoveries=0, replays=0)
+
+ def check_stop(self):
+ if self.stop_requested():
+ raise StopRequested("stop requested")
+
+ # ---- serial link
+ def openSerial(self):
+ last = "screen not found"
+ for attempt in range(1, SERIAL_OPEN_ATTEMPTS + 1):
+ port = self.com_port
+ if port in (None, "", "AUTO"):
+ # Wakes the screen up if needed and finds the awake interface (same detection as the base driver)
+ port = self.auto_detect_com_port()
+ if port:
+ try:
+ self.lcd_serial = serial.Serial(port, 115200, timeout=1, rtscts=True,
+ write_timeout=SERIAL_WRITE_TIMEOUT)
+ self.port = port
+ logger.debug(f"Opened {port}")
+ return
+ except (serial.SerialException, OSError) as e:
+ last = f"cannot open {port}: {e}"
+ logger.warning(f"{last}, retrying ({attempt}/{SERIAL_OPEN_ATTEMPTS})")
+ time.sleep(1)
+ raise DeviceError(f"cannot open the screen's serial port after {SERIAL_OPEN_ATTEMPTS} attempts ({last})")
+
+ def reconnect(self):
+ """Close and reopen the serial port (the port is detected again on AUTO, it can change after a re-enumeration)."""
+ with self._lock:
+ self.close()
+ self.openSerial()
+
+ def close(self):
+ try:
+ if self.lcd_serial is not None:
+ self.lcd_serial.close()
+ except (serial.SerialException, OSError):
+ pass
+ self.lcd_serial = None
+
+ def _write(self, data: bytes, fill: int = 0x00):
+ if self.lcd_serial is None:
+ raise DeviceError("serial port is closed")
+ try:
+ self.lcd_serial.write(pad250(data, fill))
+ except (serial.SerialException, OSError) as e: # includes SerialTimeoutException
+ raise DeviceError(f"serial write failed: {e}") from e
+
+ def _read(self, timeout: float = 1.0, settle: float = 0.03) -> bytes:
+ """Read what the screen sends, until nothing more arrives for `settle` seconds (or `timeout`)."""
+ end = time.monotonic() + timeout
+ buf = bytearray()
+ last = None
+ try:
+ while time.monotonic() < end:
+ n = self.lcd_serial.in_waiting
+ if n:
+ buf += self.lcd_serial.read(n)
+ last = time.monotonic()
+ elif last and time.monotonic() - last > settle:
+ break
+ else:
+ time.sleep(0.002)
+ except (serial.SerialException, OSError, AttributeError) as e:
+ raise DeviceError(f"serial read failed: {e}") from e
+ return bytes(buf)
+
+ def _flush_input(self):
+ try:
+ self.lcd_serial.reset_input_buffer()
+ except (serial.SerialException, OSError, AttributeError) as e:
+ raise DeviceError(f"serial error: {e}") from e
+
+ @staticmethod
+ def _txt(data: bytes) -> str:
+ return data.replace(b"\x00", b"").decode("ascii", "replace")
+
+ @staticmethod
+ def _path_cmd(op: int, path: str) -> bytes:
+ p = path.encode()
+ return bytes((op, 0xEF, 0x69, 0)) + len(p).to_bytes(3, "big") + b"\x00\x00\x00" + p
+
+ # ---- basic commands
+ def hello(self, attempts: int = HELLO_ATTEMPTS) -> str:
+ """Returns the ID of the screen (e.g. 'chs_5inch.dev1_rom1.89'). Raises DeviceError if it does not answer."""
+ with self._lock:
+ reply = ""
+ for i in range(attempts):
+ self._flush_input()
+ self._write(bytes(Command.HELLO.value))
+ reply = self._txt(self._read(1.0))
+ rom = parse_hello(reply)
+ if rom is not None:
+ self.rom_version = rom
+ return reply
+ if i < attempts - 1:
+ time.sleep(1)
+ raise DeviceError(f"no valid reply to HELLO after {attempts} attempts (last: {reply!r})")
+
+ def set_brightness(self, percent: int):
+ if not isinstance(percent, (int, float)) or isinstance(percent, bool) or not 0 <= percent <= 100:
+ raise FatalError(f"BRIGHTNESS must be between 0 and 100, got {percent!r}")
+ with self._lock:
+ self._write(bytes(Command.SET_BRIGHTNESS.value) + bytes((int(percent / 100 * 255),)))
+
+ def options(self, mode: int = 0, flip: int = 0, sleep: int = 0):
+ with self._lock:
+ self._write(bytes(Command.OPTIONS.value) + bytes((mode, 0, flip, sleep)))
+
+ def stop_video(self):
+ with self._lock:
+ self._write(bytes(Command.STOP_VIDEO.value))
+
+ def soft_reset(self):
+ """Stop the video and media playback and discard pending replies (the screen is not rebooted)."""
+ with self._lock:
+ self.stop_video()
+ self._write(bytes(Command.STOP_MEDIA.value))
+ self._read(0.5)
+ self._flush_input()
+
+ # ---- files
+ def list_dir(self, path: str) -> List[str]:
+ """File names in a directory of the screen. Note: listing a missing directory creates it."""
+ with self._lock:
+ self._flush_input()
+ self._write(self._path_cmd(CMD_LIST, path))
+ text = self._txt(self._read(2.0))
+ m = re.search(r"file:(.*)", text)
+ return [f for f in (m.group(1).split("/") if m else []) if f]
+
+ def file_size(self, path: str) -> int:
+ with self._lock:
+ self._flush_input()
+ self._write(self._path_cmd(CMD_FILE_SIZE, path))
+ text = self._txt(self._read(2.0))
+ m = re.search(r"\d+", text)
+ return int(m.group()) if m else 0
+
+ def delete(self, path: str):
+ with self._lock:
+ self._write(self._path_cmd(CMD_DELETE, path))
+ self._read(0.3) # no reply expected
+
+ def upload(self, local: Path, dest: str) -> float:
+ """Upload a file (an existing file at `dest` is deleted first) and wait until the screen confirms it.
+ Returns the transfer time in seconds. Raises DeviceError on a serial error and UploadSizeError if the screen does not store the whole file."""
+ data = Path(local).read_bytes()
+ check_video_size(len(data))
+ with self._lock:
+ if self.file_size(dest):
+ self.delete(dest)
+ t0 = time.monotonic()
+ self._write(self._path_cmd(CMD_UPLOAD, dest) + len(data).to_bytes(4, "little"))
+ packets = (chunk + bytes(250 - len(chunk)) for chunk in chunked(data, 249))
+ try:
+ while True:
+ self.check_stop()
+ piece = b"".join(itertools.islice(packets, UPLOAD_WRITE_PACKETS))
+ if not piece:
+ break
+ self.lcd_serial.write(piece) # each write has its own timeout (SERIAL_WRITE_TIMEOUT)
+ self.lcd_serial.flush()
+ except (serial.SerialException, OSError, AttributeError) as e:
+ raise DeviceError(f"serial write failed during upload: {e}") from e
+ reply = b""
+ end = time.monotonic() + 15
+ while b"file_rev_done" not in reply.replace(b"\x00", b"") and time.monotonic() < end:
+ reply += self._read(0.5)
+ seconds = time.monotonic() - t0 # transfer + flash write, not the settling delays below
+ time.sleep(0.5) # img_show_ follows file_rev_done: make sure it does not leak into the next reply
+ self._read(0.5)
+ self._flush_input()
+ if self.file_size(dest) != len(data):
+ self.delete(dest) # drop the truncated file
+ raise UploadSizeError(f"upload of {dest} failed (screen storage full?): {self._txt(reply)!r}")
+ return seconds
+
+ def ensure_video(self, local: Path, remote_dir: str, prefix: str, log=logger.info) -> str:
+ """Make sure the video is on the screen as .mp4 and return that path.
+
+ The size is checked before anything is deleted. Older * videos are removed only when a new upload is
+ needed (the storage only holds about one video), so a correct video already on the screen is never rewritten."""
+ local = Path(local)
+ data = local.read_bytes()
+ check_video_size(len(data))
+ name = remote_video_name(prefix, data)
+ dest = remote_dir + name
+ with self._lock:
+ files = self.list_dir(remote_dir)
+ stale = [f for f in files if f.startswith(prefix) and f != name]
+ if self.file_size(dest) == len(data):
+ log(f"{dest} already on the screen")
+ else:
+ # The storage only holds about one video: the old ones have to go before the new one is written
+ for f in stale:
+ log(f"deleting {f} from the screen")
+ self.delete(remote_dir + f)
+ stale = []
+ log(f"uploading {local.name} ({len(data)} bytes) to {dest}")
+ try:
+ seconds = self.upload(local, dest)
+ except UploadSizeError as e: # serial errors are not caught: the caller reconnects
+ log(f"upload failed ({e}), trying once more")
+ try:
+ seconds = self.upload(local, dest)
+ except UploadSizeError as e2:
+ raise FatalError(f"cannot store the video on the screen: {e2}. Free some space in "
+ f"{remote_dir} or reset the screen. Not retrying, to avoid wearing out "
+ f"its flash.", exit_code=3) from e2
+ log(f"upload took {seconds:.1f} s")
+ for f in stale:
+ log(f"deleting {f} from the screen")
+ self.delete(remote_dir + f)
+ return dest
+
+ def play(self, path: str) -> bool:
+ """Start looping a stored video. The screen says success even for a missing file, so check the size first."""
+ with self._lock:
+ if not self.file_size(path):
+ return False
+ self._flush_input()
+ self._write(self._path_cmd(CMD_PLAY, path))
+ return "play_video_success" in self._txt(self._read(3.0))
+
+ def start_video(self, path: str, settle: float = 1.0):
+ """play() then wait for the player to start. Raises DeviceError if the screen cannot play the file."""
+ with self._lock:
+ if not self.play(path):
+ raise DeviceError(f"could not play {path}")
+ time.sleep(settle)
+ self._video = path
+ self._rc = None
+ self._rc_since = time.monotonic()
+
+ # ---- status
+ def status(self) -> Status:
+ with self._lock:
+ self._flush_input()
+ self._write(bytes(Command.QUERY_STATUS.value))
+ try:
+ raw = self.lcd_serial.read(1024) # reply is always exactly 1024 bytes (1 s timeout if swallowed)
+ except (serial.SerialException, OSError, AttributeError) as e:
+ raise DeviceError(f"serial read failed: {e}") from e
+ st = parse_status(self._txt(raw))
+ if st.render_cnt is not None and st.render_cnt != self._rc:
+ self._rc = st.render_cnt
+ self._rc_since = time.monotonic()
+ return st
+
+ def render_stalled(self, timeout: float = 3.0) -> bool:
+ """True if a video was started but renderCnt has not increased for `timeout` seconds."""
+ return self._video is not None and time.monotonic() - self._rc_since > timeout
+
+ # ---- overlay
+ def init_overlay(self, native_rgba: np.ndarray) -> Status:
+ """Full overlay init (bitmap + visibility map). Clears needReSend and restarts the update count at 0.
+ Raises DeviceError if needReSend is still set afterwards."""
+ with self._lock:
+ self._write(bytes(Command.PRE_UPDATE_BITMAP.value))
+ self._write(bytes(Command.START_DISPLAY_BITMAP.value), fill=0x2C)
+ self._write(CMD_INIT_OVERLAY)
+ self._write(chunk_stream(native_rgba[..., [2, 1, 0, 3]].tobytes()))
+ self._read(2.0) # seq_png_init_sucess
+ vis = bytearray(visible_list(native_rgba[..., 3]))
+ if not vis: # at least one run is required
+ vis = bytearray(5)
+ vis[4] = 1
+ vis += b"\x00" + TERMINATOR
+ self._write(pad250(CMD_OVERLAY_VISIBLE + len(vis).to_bytes(3, "big")) + chunk_stream(bytes(vis)))
+ self._read(0.2)
+ self._prev = native_rgba.copy()
+ self._count = 0
+ st = self.status()
+ if not st.ok:
+ raise DeviceError(f"overlay init did not clear needReSend: {st.text!r}")
+ return st
+
+ def update_overlay(self, native_rgba: np.ndarray, min_gap: int = 3) -> UpdateResult:
+ """Send only the changed pixels as an incremental overlay update. On a bad status the full overlay is
+ re-initialised once; DeviceError is raised if that does not work either."""
+ with self._lock:
+ t0 = time.monotonic()
+ cur = native_rgba
+ changed = (cur != self._prev).any(axis=2)
+ nbytes = 0
+ if changed.any():
+ rec = bytearray()
+ for y in np.flatnonzero(changed.any(axis=1)):
+ for s, e in runs(changed[y], min_gap):
+ rec += (int(y * SIZE + s).to_bytes(3, "big") + int(e - s).to_bytes(2, "big")
+ + compress_px(cur[y, s:e]))
+ vis = visible_list(cur[..., 3])
+ header, body = frame_overlay_update(bytes(rec) + vis, self._count, len(vis))
+ self._write(header)
+ self._write(body)
+ nbytes = len(rec) + len(vis)
+ self.stats["updates"] += 1
+ st = self.status()
+ recovered = False
+ if st.ok:
+ if nbytes:
+ self._count += 1
+ self._prev = cur.copy()
+ else:
+ self.stats["failures"] += 1
+ logger.warning(f"overlay status {st.text!r}, re-initialising overlay")
+ st = self.init_overlay(cur) # raises DeviceError if it does not clear the error
+ recovered = True
+ self.stats["recoveries"] += 1
+ return UpdateResult(st, nbytes, time.monotonic() - t0, recovered)
diff --git a/library/lcd/rev_c_errors.py b/library/lcd/rev_c_errors.py
new file mode 100644
index 000000000..2f975c3b6
--- /dev/null
+++ b/library/lcd/rev_c_errors.py
@@ -0,0 +1,44 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# turing-smart-screen-python - a Python system monitor and library for USB-C displays like Turing Smart Screen or XuanFang
+# https://github.com/mathoudebine/turing-smart-screen-python/
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see .
+
+# Errors of the rev C video face driver (library/lcd/lcd_comm_rev_c_video.py) and of the program using it.
+
+
+class VideoFaceError(Exception):
+ """Base class of the errors raised by the video face driver."""
+
+
+class DeviceError(VideoFaceError):
+ """Recoverable error: serial failure, unexpected or missing reply. The caller can back off and reconnect."""
+
+
+class UploadSizeError(DeviceError):
+ """The screen did not store the whole video (storage full?) although the serial link worked."""
+
+
+class StopRequested(VideoFaceError):
+ """The program was asked to stop (Ctrl-C / SIGTERM) while a long operation was running."""
+
+
+class FatalError(VideoFaceError):
+ """Unrecoverable error (configuration, unsupported screen, video too large, upload failing...): retrying the
+ same thing cannot succeed, so the caller should exit with `exit_code` and a clear message."""
+
+ def __init__(self, message: str, exit_code: int = 2):
+ super().__init__(message)
+ self.exit_code = exit_code
diff --git a/library/video_face/__init__.py b/library/video_face/__init__.py
new file mode 100644
index 000000000..31d49ed82
--- /dev/null
+++ b/library/video_face/__init__.py
@@ -0,0 +1 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
diff --git a/library/video_face/app.py b/library/video_face/app.py
new file mode 100644
index 000000000..52f8edd01
--- /dev/null
+++ b/library/video_face/app.py
@@ -0,0 +1,278 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# turing-smart-screen-python - a Python system monitor and library for USB-C displays like Turing Smart Screen or XuanFang
+# https://github.com/mathoudebine/turing-smart-screen-python/
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see .
+
+# Rev C video face: runs the animated face on the 2.1" round rev C screen using the screen's NATIVE video player. The
+# animated background (flame ring + sparkles, see video.py) loops on the screen by itself, and this program only draws
+# the live CPU / GPU / RAM rows (labels, scrolling bar history, %) as small incremental video-overlay updates.
+#
+# Exit codes: 0 clean stop, 1 screen not reachable at startup, 2 configuration / unsupported screen / video problem,
+# 3 the video could not be stored on the screen. Codes 2 and 3 will not fix themselves, so a service manager should
+# not restart on them (they are reported with a clear message and nothing is rewritten on the screen).
+
+import argparse
+import signal
+import sys
+import threading
+import time
+from pathlib import Path
+from typing import List, Optional
+
+import numpy as np
+from PIL import Image
+
+from library.lcd.lcd_comm_rev_c_video import LcdCommRevCVideo, to_native
+from library.lcd.rev_c_errors import DeviceError, FatalError, StopRequested
+from library.log import logger
+from library.video_face.render import N_BARS, UiLayer, blend
+from library.video_face.sampler import Sampler, select_sensors
+from library.video_face.settings import Settings, from_config
+from library.video_face.video import FPS, ensure_video, encode, iter_loop_frames
+
+STATS_PERIOD = 60.0
+BACKOFF_MAX = 30.0
+STABLE_AFTER = 60.0 # seconds without error before the backoff delay goes back to its minimum
+TESTED_ROM = 89
+
+
+def sweep_histories(t: float, seconds: float, n_rows: int, period: float) -> List[List[float]]:
+ """Preview-only fake load: each row's newest value ramps 0 -> 100 % (rows with different curves) and the
+ history holds the earlier part of the ramp, so every bar colour shows."""
+ out = []
+ for r in range(n_rows):
+ hist = []
+ for j in range(N_BARS):
+ tt = t - (N_BARS - 1 - j) * period
+ u = (tt + N_BARS * period) / (N_BARS * period + seconds)
+ hist.append(100 * min(max(u, 0.0), 1.0) ** (1.0 + 0.4 * r))
+ out.append(hist)
+ return out
+
+
+def preview(path: str, settings: Settings, seconds: float = 3.0):
+ """Composite the video and the UI with a fake load into a GIF or MP4; the screen is not used."""
+ ui = UiLayer(settings.rows, settings.colors)
+ frames = []
+ for i, fr in enumerate(iter_loop_frames()):
+ if i >= int(seconds * FPS):
+ break
+ hist = sweep_histories(i / FPS, seconds, len(settings.rows), settings.sample_period)
+ frames.append(blend(fr, ui.render(hist)))
+ if path.lower().endswith(".mp4"):
+ encode(iter(frames), Path(path), False, crf=18, rotate=False)
+ else:
+ ims = [Image.fromarray(f) for f in frames]
+ ims[0].save(path, save_all=True, append_images=ims[1:], duration=int(1000 / FPS), loop=0)
+ print(f"wrote {path} ({len(frames)} frames)")
+
+
+def check_screen_config(config) -> bool:
+ """Refuse anything but a 2.1" rev C screen (the hello reply of the 2.1" is 'chs_5inch', so the model comes from
+ config.yaml). Returns DISPLAY_REVERSE."""
+ disp = config.CONFIG_DATA["display"]
+ if disp.get("REVISION") != "C":
+ raise FatalError(f"video-face-rev-c.py only supports REVISION: C (2.1\" round screen), config.yaml has "
+ f"{disp.get('REVISION')!r}")
+ size = config.THEME_DATA["display"].get("DISPLAY_SIZE")
+ if size != '2.1"':
+ raise FatalError(f"video-face-rev-c.py needs the 2.1\" (480x480) screen: select a 2.1\" theme (such as 26) "
+ f"in config.yaml, THEME has size {size!r}")
+ return bool(disp.get("DISPLAY_REVERSE", False))
+
+
+def install_signal_handlers(stop: threading.Event):
+ for name in ("SIGTERM", "SIGINT"):
+ sig = getattr(signal, name, None)
+ if sig is not None:
+ try:
+ signal.signal(sig, lambda *_: stop.set())
+ except (ValueError, OSError): # not in the main thread / not supported
+ pass
+
+
+class Face:
+ """The running face: brings the screen up and keeps the overlay updated, recovering from serial errors."""
+
+ def __init__(self, config, settings: Settings, reverse: bool, video: Path, sampler: Sampler):
+ self.config = config
+ self.settings = settings
+ self.reverse = reverse
+ self.video = video
+ self.sampler = sampler
+ self.ui = UiLayer(settings.rows, settings.colors)
+ self.dev = None # type: Optional[LcdCommRevCVideo]
+
+ def native(self) -> np.ndarray:
+ return to_native(self.ui.render(self.sampler.snapshot()), self.reverse)
+
+ def ensure_and_play(self) -> None:
+ s = self.settings
+ # The video file may have been removed from the cache since startup: rebuild it, size-checked
+ self.video = ensure_video(self.reverse, out=self.video)
+ dest = self.dev.ensure_video(self.video, s.remote_dir, s.remote_prefix, logger.info)
+ self.dev.start_video(dest) # waits for the player like at startup
+
+ def bring_up(self, first: bool):
+ """Hello, reset, brightness, video on the screen and playing, overlay initialised."""
+ dev, disp = self.dev, self.config.CONFIG_DATA["display"]
+ dev.check_stop() # shutdown stays prompt: the stop flag is checked between the steps (and upload chunks)
+ hello = dev.hello()
+ dev.check_stop()
+ logger.info(f"Screen: {hello} on {dev.port}")
+ if dev.rom_version != TESTED_ROM:
+ logger.warning(f"ROM version {dev.rom_version}: only ROM {TESTED_ROM} was tested with the video face")
+ if not first or disp.get("RESET_ON_STARTUP", True):
+ dev.soft_reset() # the screen is not rebooted
+ else:
+ dev.stop_video()
+ dev.check_stop()
+ dev.set_brightness(disp.get("BRIGHTNESS", 50))
+ dev.options(0, 0, 0)
+ dev.check_stop()
+ self.ensure_and_play()
+ dev.check_stop()
+ self.sampler.first_sample.wait(2 * self.settings.sample_period + 1)
+ dev.check_stop()
+ st = dev.init_overlay(self.native())
+ logger.info(f"Overlay initialised: needReSend={st.need_resend} renderCnt={st.render_cnt}")
+
+ def replay(self):
+ """renderCnt stopped increasing: put the video back (re-uploading it if it is gone) and the overlay."""
+ logger.warning("renderCnt is not increasing, restarting the video")
+ self.dev.stats["replays"] += 1
+ self.ensure_and_play()
+ self.dev.init_overlay(self.native())
+
+ def run(self, stop: threading.Event):
+ s = self.settings
+ self.dev = LcdCommRevCVideo(self.config.CONFIG_DATA["config"].get("COM_PORT", "AUTO"))
+ self.dev.stop_requested = stop.is_set
+ self.bring_up(first=True)
+
+ connected = True
+ backoff, last_error = 1.0, 0.0
+ t_stats = time.monotonic()
+ n0 = dict(self.dev.stats)
+ rc_last, rc_gain, lat = None, 0, []
+ nxt = time.monotonic() + s.sample_period
+ while not stop.is_set():
+ if not connected:
+ if stop.wait(backoff):
+ break
+ try:
+ self.dev.reconnect()
+ self.bring_up(first=False)
+ except StopRequested:
+ break
+ except DeviceError as e:
+ backoff = min(backoff * 2, BACKOFF_MAX)
+ last_error = time.monotonic()
+ logger.error(f"Cannot recover the screen: {e}. Next try in {backoff:.0f} s")
+ continue
+ connected, rc_last = True, None
+ self.dev.stats["recoveries"] += 1
+ logger.info("Screen recovered")
+ nxt = time.monotonic() + s.sample_period
+ if stop.wait(max(0, nxt - time.monotonic())):
+ break
+ now = time.monotonic()
+ nxt += s.sample_period
+ if nxt < now: # behind schedule (slow update, suspend...): do not accumulate lag
+ nxt = now + s.sample_period
+ try:
+ res = self.dev.update_overlay(self.native())
+ if res.payload_bytes:
+ lat.append(res.seconds)
+ rc = res.status.render_cnt
+ if rc is not None:
+ if rc_last is not None and rc >= rc_last:
+ rc_gain += rc - rc_last
+ rc_last = rc
+ if self.dev.render_stalled():
+ self.replay()
+ rc_last = None
+ except DeviceError as e:
+ connected = False
+ self.dev.stats["failures"] += 1
+ last_error = time.monotonic()
+ logger.error(f"Screen error: {e}. Reconnecting in {backoff:.0f} s")
+ continue
+ now = time.monotonic()
+ if backoff > 1.0 and now - last_error > STABLE_AFTER:
+ backoff = 1.0
+ if now - t_stats >= STATS_PERIOD:
+ st = {k: self.dev.stats[k] - n0[k] for k in n0}
+ logger.info(f"video face: updates={st['updates']} failures={st['failures']} "
+ f"recoveries={st['recoveries']} replays={st['replays']} "
+ f"renderCnt={rc_gain / (now - t_stats):.1f}/s "
+ f"latency avg={1000 * np.mean(lat) if lat else 0:.0f} ms "
+ f"max={1000 * max(lat, default=0):.0f} ms")
+ t_stats, n0, rc_gain, lat = now, dict(self.dev.stats), 0, []
+
+
+def run_screen(config, settings: Settings):
+ reverse = check_screen_config(config)
+ video = ensure_video(reverse) # builds it if needed (ffmpeg), before the screen is touched
+ stop = threading.Event()
+ install_signal_handlers(stop)
+ sampler = None
+ face = None
+ try:
+ sampler = Sampler(settings.rows, settings.sample_period,
+ select_sensors(config.CONFIG_DATA["config"].get("HW_SENSORS", "AUTO")))
+ sampler.start()
+ face = Face(config, settings, reverse, video, sampler)
+ face.run(stop)
+ finally:
+ if sampler is not None:
+ sampler.stop()
+ if face is not None and face.dev is not None:
+ face.dev.close()
+ logger.info("video face stopped (the video keeps looping on the screen)")
+
+
+def main(argv: Optional[List[str]] = None) -> int:
+ ap = argparse.ArgumentParser(description="Animated video face for the 2.1\" round rev C screen")
+ ap.add_argument("--preview", metavar="OUT.gif|OUT.mp4",
+ help="composite 3 s with a fake load into a GIF or MP4, the screen is not used")
+ ap.add_argument("--rebuild-video", action="store_true", help="rebuild the cached loop video and exit")
+ args = ap.parse_args(argv)
+
+ from library import config # loads config.yaml and the theme
+ try:
+ settings = from_config(config.VIDEO_FACE_DATA)
+ if args.preview:
+ preview(args.preview, settings)
+ elif args.rebuild_video:
+ reverse = bool(config.CONFIG_DATA["display"].get("DISPLAY_REVERSE", False))
+ print(ensure_video(reverse, rebuild=True))
+ else:
+ run_screen(config, settings)
+ except StopRequested:
+ logger.info("stopped during startup")
+ return 0
+ except FatalError as e:
+ logger.error(str(e))
+ return e.exit_code
+ except DeviceError as e:
+ logger.error(f"Screen not reachable: {e}")
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/library/video_face/render.py b/library/video_face/render.py
new file mode 100644
index 000000000..ddda73190
--- /dev/null
+++ b/library/video_face/render.py
@@ -0,0 +1,113 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# turing-smart-screen-python - a Python system monitor and library for USB-C displays like Turing Smart Screen or XuanFang
+# https://github.com/mathoudebine/turing-smart-screen-python/
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see .
+
+# Rendering of the rev C video face UI: labels, scrolling bar history and percentage of each row, as a straight-alpha
+# RGBA layer drawn directly over the video (no backing).
+
+import math
+from pathlib import Path
+from typing import List, Optional, Sequence
+
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+
+from library.lcd.lcd_comm_rev_c_video import SIZE
+from library.video_face.settings import BarColors
+
+FONT_DIR = Path(__file__).resolve().parent.parent.parent / "res" / "fonts" / "jetbrains-mono"
+FONT_BOLD = str(FONT_DIR / "JetBrainsMono-Bold.ttf")
+FONT_REG = str(FONT_DIR / "JetBrainsMono-Medium.ttf")
+
+N_BARS = 26
+BAR_W, BAR_GAP, BAR_H = 5, 2, 48
+ROW_SPACING = 80
+LABEL_X = 80
+BARS_X = 140 # left edge of the bar strip
+PCT_RIGHT = 404 # right edge of the percentage text
+UNAVAILABLE_BAR = (90, 100, 115) # bars of a sensor that is not available
+
+Value = Optional[float] # None: not available
+
+
+def row_centres(n: int) -> List[int]:
+ """Vertical centre of each row, evenly spaced around the middle of the screen (160 / 240 / 320 for 3 rows)."""
+ return [round(SIZE / 2 + (i - (n - 1) / 2) * ROW_SPACING) for i in range(n)]
+
+
+def clean(v: Value) -> Value:
+ return None if v is None or (isinstance(v, float) and math.isnan(v)) else float(v)
+
+
+def _text_layer(size, x, cy, text, font, color, anchor):
+ """Anti-aliased text as straight-alpha RGBA (colour stays pure, only alpha carries the edge). The ink box is
+ centred vertically on cy (anchor 'l' or 'r' sets the horizontal side)."""
+ l, t, r, b = font.getbbox(text, anchor="l" + "s")
+ y = cy - (t + b) / 2 # baseline such that the ink centre sits on cy
+ mask = Image.new("L", size, 0)
+ ImageDraw.Draw(mask).text((x, y), text, font=font, fill=255, anchor=anchor + "s")
+ layer = Image.new("RGBA", size, color + (0,))
+ layer.putalpha(mask)
+ return layer
+
+
+def gradient_strip(colors: BarColors) -> np.ndarray:
+ """(BAR_H, 3) RGB column for a full-height bar: each pixel row is coloured by its level, the distance from the
+ centre line as a % of the max half-height, so the strip is mirror symmetric. A bar is a centred slice of it."""
+ half = BAR_H / 2
+ levels = [abs(i + 0.5 - half) / half * 100 for i in range(BAR_H)]
+ return np.array([colors.color(lv) for lv in levels], np.uint8)
+
+
+class UiLayer:
+ """Upright 480x480 straight-alpha RGBA overlay."""
+
+ def __init__(self, rows: Sequence[str], colors: BarColors):
+ self.rows = list(rows)
+ self.centres = row_centres(len(self.rows))
+ self.colors = colors
+ self.strip = gradient_strip(colors)
+ self.f_label = ImageFont.truetype(FONT_REG, 26)
+ self.f_pct = ImageFont.truetype(FONT_BOLD, 30)
+
+ def render(self, histories: Sequence[Sequence[Value]]) -> np.ndarray:
+ bars = np.zeros((SIZE, SIZE, 4), np.uint8)
+ text = Image.new("RGBA", (SIZE, SIZE), (0, 0, 0, 0))
+ for label, cy, hist in zip(self.rows, self.centres, histories):
+ vals = [clean(v) for v in hist]
+ vals = [0.0] * (N_BARS - len(vals)) + vals # newest on the right
+ for k, v in enumerate(vals):
+ x = BARS_X + k * (BAR_W + BAR_GAP)
+ bh = 2 if v is None else max(2, round(BAR_H * min(max(v, 0), 100) / 100))
+ top = cy - bh // 2 # symmetric around the row's centre line
+ if v is None:
+ bars[top:top + bh, x:x + BAR_W] = UNAVAILABLE_BAR + (255,)
+ else: # centred slice of the vertical gradient: colour depends on the level, not on the value
+ s = BAR_H // 2 - bh // 2
+ bars[top:top + bh, x:x + BAR_W, :3] = self.strip[s:s + bh, None, :]
+ bars[top:top + bh, x:x + BAR_W, 3] = 255
+ pct = "N/A" if vals[-1] is None else f"{round(vals[-1])}%"
+ text = Image.alpha_composite(text, _text_layer((SIZE, SIZE), LABEL_X, cy, label, self.f_label,
+ (170, 200, 225), "l"))
+ text = Image.alpha_composite(text, _text_layer((SIZE, SIZE), PCT_RIGHT, cy, pct, self.f_pct,
+ (255, 255, 255), "r"))
+ return np.asarray(Image.alpha_composite(Image.fromarray(bars, "RGBA"), text))
+
+
+def blend(frame_rgb: np.ndarray, rgba: np.ndarray) -> np.ndarray:
+ a = rgba[..., 3:4].astype(np.float32) / 255.0
+ return (frame_rgb * (1 - a) + rgba[..., :3] * a).astype(np.uint8)
diff --git a/library/video_face/sampler.py b/library/video_face/sampler.py
new file mode 100644
index 000000000..dc4e16629
--- /dev/null
+++ b/library/video_face/sampler.py
@@ -0,0 +1,128 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# turing-smart-screen-python - a Python system monitor and library for USB-C displays like Turing Smart Screen or XuanFang
+# https://github.com/mathoudebine/turing-smart-screen-python/
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see .
+
+# Sensor sampling for the rev C video face, through the project's sensor layer (library/sensors) as selected by
+# HW_SENSORS in config.yaml, so Nvidia / AMD / Intel (Python libraries) and LibreHardwareMonitor (Windows) all work.
+
+import math
+import platform
+import threading
+import time
+from collections import deque
+from typing import Any, Callable, Dict, List, Optional
+
+from library.lcd.lcd_comm_rev_c_video import FatalError
+from library.log import logger
+from library.video_face.render import N_BARS, Value
+
+
+def select_sensors(hw_sensors: str) -> Any:
+ """The sensors module for a HW_SENSORS value, same selection as library/stats.py (imported only when needed,
+ because the LibreHardwareMonitor one only exists on Windows)."""
+ hw_sensors = str(hw_sensors).upper()
+ if hw_sensors == "AUTO":
+ hw_sensors = "LHM" if platform.system() == "Windows" else "PYTHON"
+ if hw_sensors == "PYTHON":
+ import library.sensors.sensors_python as sensors
+ elif hw_sensors == "LHM":
+ if platform.system() != "Windows":
+ raise FatalError("HW_SENSORS: LHM (LibreHardwareMonitor) is only available on Windows")
+ import library.sensors.sensors_librehardwaremonitor as sensors
+ elif hw_sensors == "STUB":
+ import library.sensors.sensors_stub_random as sensors
+ elif hw_sensors == "STATIC":
+ import library.sensors.sensors_stub_static as sensors
+ else:
+ raise FatalError(f"Unsupported HW_SENSORS value in config.yaml: {hw_sensors!r}")
+ return sensors
+
+
+class Sampler(threading.Thread):
+ """Samples the rows (CPU / GPU / RAM) every `period` seconds into fixed-length histories. A value that cannot be
+ read is None ("N/A"); the reason is logged once, not at every sample."""
+
+ def __init__(self, rows: List[str], period: float, sensors: Any):
+ super().__init__(daemon=True)
+ self.rows = list(rows)
+ self.period = period
+ self.sensors = sensors
+ self.lock = threading.Lock()
+ self.hist = [deque(maxlen=N_BARS) for _ in self.rows]
+ self.stop_evt = threading.Event()
+ self.first_sample = threading.Event()
+ self._warned = set()
+ self._gpu_available = None # type: Optional[bool]
+ self._readers = {"CPU": self._cpu, "GPU": self._gpu, "RAM": self._ram} # type: Dict[str, Callable[[], Value]]
+ if "CPU" in self.rows:
+ self._safe("CPU", lambda: self.sensors.Cpu.percentage(interval=None)) # the first reading is meaningless
+
+ def _warn_once(self, key: str, message: str):
+ if key not in self._warned:
+ self._warned.add(key)
+ logger.warning(message)
+
+ def _safe(self, name: str, fn: Callable[[], float]) -> Value:
+ try:
+ v = float(fn())
+ except Exception as e:
+ self._warn_once(name, f"{name} sensor error, showing N/A: {e}")
+ return None
+ return None if math.isnan(v) else v
+
+ def _cpu(self) -> Value:
+ return self._safe("CPU", lambda: self.sensors.Cpu.percentage(interval=None))
+
+ def _ram(self) -> Value:
+ return self._safe("RAM", self.sensors.Memory.virtual_percent)
+
+ def _gpu(self) -> Value:
+ if self._gpu_available is None:
+ try:
+ self._gpu_available = bool(self.sensors.Gpu.is_available())
+ except Exception as e:
+ logger.warning(f"GPU detection failed: {e}")
+ self._gpu_available = False
+ if not self._gpu_available:
+ logger.warning("No supported GPU found with the selected HW_SENSORS: the GPU row shows N/A")
+ if not self._gpu_available:
+ return None
+ return self._safe("GPU", lambda: self.sensors.Gpu.stats()[0])
+
+ def sample(self) -> List[Value]:
+ return [self._readers[r]() for r in self.rows]
+
+ def run(self):
+ nxt = time.monotonic()
+ while not self.stop_evt.is_set():
+ vals = self.sample()
+ with self.lock:
+ for h, v in zip(self.hist, vals):
+ h.append(v)
+ self.first_sample.set()
+ nxt += self.period
+ now = time.monotonic()
+ if nxt < now:
+ nxt = now + self.period
+ self.stop_evt.wait(max(0, nxt - now))
+
+ def snapshot(self) -> List[List[Value]]:
+ with self.lock:
+ return [list(h) for h in self.hist]
+
+ def stop(self):
+ self.stop_evt.set()
diff --git a/library/video_face/settings.py b/library/video_face/settings.py
new file mode 100644
index 000000000..342db1918
--- /dev/null
+++ b/library/video_face/settings.py
@@ -0,0 +1,118 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# turing-smart-screen-python - a Python system monitor and library for USB-C displays like Turing Smart Screen or XuanFang
+# https://github.com/mathoudebine/turing-smart-screen-python/
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see .
+
+# Settings of the rev C video face: validation of the optional "video_face" section of config.yaml (the defaults are
+# in library/config.py).
+
+from dataclasses import dataclass
+from typing import Any, Dict, List, Tuple
+
+from library.lcd.lcd_comm_rev_c_video import FatalError
+from library.log import logger
+
+ROW_NAMES = ("CPU", "GPU", "RAM")
+
+Color = Tuple[int, int, int]
+
+
+@dataclass(frozen=True)
+class BarColors:
+ """Bar colour by level (%, the distance from the bar's centre line relative to the max bar height): a multi-stop
+ gradient, colours are linearly interpolated (sRGB) between the stops, sorted by level and covering 0..100."""
+ stops: Tuple[Tuple[float, Color], ...]
+
+ def color(self, v: float) -> Color:
+ stops = self.stops
+ if v <= stops[0][0]:
+ return stops[0][1]
+ for (v0, c0), (v1, c1) in zip(stops, stops[1:]):
+ if v <= v1:
+ f = (v - v0) / (v1 - v0)
+ return tuple(int(round(a + (b - a) * f)) for a, b in zip(c0, c1))
+ return stops[-1][1]
+
+
+@dataclass(frozen=True)
+class Settings:
+ rows: List[str]
+ sample_period: float
+ remote_dir: str
+ remote_prefix: str
+ colors: BarColors
+
+
+LEGACY_COLOR_KEYS = ("BAR_COLOR_LOW", "BAR_COLOR_MID", "BAR_COLOR_HIGH", "BLUE_UNTIL", "YELLOW_FROM",
+ "YELLOW_UNTIL", "RED_FROM")
+_legacy_warned = False
+
+
+def _gradient(data: Dict[str, Any]) -> BarColors:
+ v = data.get("BAR_GRADIENT")
+ err = "video_face.BAR_GRADIENT must be a list of [level %, [R, G, B]] stops"
+ if not isinstance(v, (list, tuple)) or len(v) < 2:
+ raise FatalError(f"{err} (at least 2), got {v!r}")
+ stops = []
+ for stop in v:
+ if (not isinstance(stop, (list, tuple)) or len(stop) != 2 or not isinstance(stop[0], (int, float))
+ or isinstance(stop[0], bool) or not isinstance(stop[1], (list, tuple))
+ or len(stop[1]) != 3 or not all(isinstance(c, int) and not isinstance(c, bool) and 0 <= c <= 255
+ for c in stop[1])):
+ raise FatalError(f"{err} with 3 integers between 0 and 255 per colour, got stop {stop!r}")
+ stops.append((float(stop[0]), tuple(stop[1])))
+ levels = [lv for lv, _ in stops]
+ if any(not 0 <= lv <= 100 for lv in levels):
+ raise FatalError(f"video_face.BAR_GRADIENT levels must be between 0 and 100, got {levels!r}")
+ if any(b <= a for a, b in zip(levels, levels[1:])):
+ raise FatalError(f"video_face.BAR_GRADIENT levels must be strictly increasing, got {levels!r}")
+ if levels[0] != 0 or levels[-1] != 100:
+ raise FatalError(f"video_face.BAR_GRADIENT must start at level 0 and end at level 100, got {levels!r}")
+ return BarColors(tuple(stops))
+
+
+def _number(data: Dict[str, Any], key: str, low: float, high: float) -> float:
+ v = data.get(key)
+ if not isinstance(v, (int, float)) or isinstance(v, bool) or not low <= v <= high:
+ raise FatalError(f"video_face.{key} must be a number between {low} and {high}, got {v!r}")
+ return v
+
+
+def from_config(data: Dict[str, Any]) -> Settings:
+ """Validate the merged video_face configuration (defaults + config.yaml). Raises FatalError with a clear message."""
+ rows = data.get("ROWS")
+ if not isinstance(rows, (list, tuple)) or not rows:
+ raise FatalError(f"video_face.ROWS must be a non-empty list among {', '.join(ROW_NAMES)}, got {rows!r}")
+ rows = [str(r).upper() for r in rows]
+ if any(r not in ROW_NAMES for r in rows) or len(set(rows)) != len(rows):
+ raise FatalError(f"video_face.ROWS must list each of {', '.join(ROW_NAMES)} at most once, got {rows!r}")
+
+ remote_dir = data.get("REMOTE_DIR")
+ if not isinstance(remote_dir, str) or not remote_dir.startswith("/"):
+ raise FatalError(f"video_face.REMOTE_DIR must be an absolute path of the screen, got {remote_dir!r}")
+ if not remote_dir.endswith("/"):
+ remote_dir += "/"
+ prefix = data.get("REMOTE_PREFIX")
+ if not isinstance(prefix, str) or not prefix or "/" in prefix:
+ raise FatalError(f"video_face.REMOTE_PREFIX must be a non-empty file name prefix, got {prefix!r}")
+
+ global _legacy_warned
+ legacy = [k for k in LEGACY_COLOR_KEYS if k in data]
+ if legacy and not _legacy_warned:
+ _legacy_warned = True
+ logger.warning(f"video_face: {', '.join(legacy)} are no longer used and are ignored, use BAR_GRADIENT instead")
+ colors = _gradient(data)
+ return Settings(rows, _number(data, "SAMPLE_PERIOD", 0.1, 60), remote_dir, prefix, colors)
diff --git a/library/video_face/video.py b/library/video_face/video.py
new file mode 100644
index 000000000..e2dd1f406
--- /dev/null
+++ b/library/video_face/video.py
@@ -0,0 +1,271 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# turing-smart-screen-python - a Python system monitor and library for USB-C displays like Turing Smart Screen or XuanFang
+# https://github.com/mathoudebine/turing-smart-screen-python/
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see .
+
+# Procedural animated background of the rev C video face (dark navy background + flame ring + sparkles, no UI) and its
+# encoding for the built-in video player of the screen. The video is 480x480, 30 fps, 240 frames (8 s). The ring uses
+# integer wave cycles per loop and the sparkles are periodic over the loop, so the seam is invisible.
+#
+# The file is pre-rotated with ffmpeg because the screen plays videos in its native orientation:
+# DISPLAY_REVERSE: true -> transpose=1 (90 deg clockwise; confirmed upright on a device)
+# DISPLAY_REVERSE: false -> transpose=2 (90 deg counter-clockwise = the above + 180 deg; derived, not verified)
+
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+from typing import Iterator, Optional
+
+import numpy as np
+from PIL import Image, ImageDraw, ImageFilter
+
+from library.lcd.lcd_comm_rev_c_video import MAX_VIDEO_BYTES
+from library.lcd.rev_c_errors import FatalError
+from library.log import logger
+
+SIZE = 480
+CENTER = SIZE / 2
+SS = 2 # supersampling for strand drawing
+
+FPS = 30
+LOOP_FRAMES = 240
+VIDEO_VERSION = 2
+N_SPARKLES = 40
+# The screen only stores about 1.2 MB: the video is re-encoded at a higher CRF until it fits MAX_VIDEO_BYTES
+CRF_LADDER = (25, 27, 29, 31, 33)
+
+# (colour, base radius offset, line width at 1x) -- sampled from the theme 26 ring
+STRANDS = [
+ ((70, 190, 240), -2, 1.6),
+ ((20, 130, 215), 6, 1.6),
+ ((120, 215, 255), -10, 1.2),
+ ((10, 90, 190), 12, 2.0),
+ ((40, 160, 230), -6, 1.4),
+ ((150, 225, 255), 2, 1.0),
+ ((15, 110, 200), -14, 1.8),
+]
+R0 = 214.0
+
+
+def build_background() -> np.ndarray:
+ """Dark navy radial gradient with a faint, static dot texture. Returns HxWx3 uint8."""
+ yy, xx = np.mgrid[0:SIZE, 0:SIZE].astype(np.float32)
+ d = np.hypot(xx - CENTER + 0.5, yy - CENTER + 0.5) / (SIZE / 2)
+ t = np.clip(d, 0, 1.2)
+ centre = np.array([12, 18, 62], np.float32)
+ edge = np.array([6, 7, 34], np.float32)
+ bg = centre + (edge - centre) * (t[..., None] ** 1.5)
+ bg[d > 1.0] = edge
+
+ rng = np.random.default_rng(26)
+ n = 900
+ ang = rng.uniform(0, 2 * np.pi, n)
+ rad = np.sqrt(rng.uniform(0, 1, n)) * (R0 - 22)
+ px = np.clip((CENTER + rad * np.cos(ang)).astype(int), 0, SIZE - 1)
+ py = np.clip((CENTER + rad * np.sin(ang)).astype(int), 0, SIZE - 1)
+ boost = rng.uniform(8, 26, n)[:, None] * np.array([0.35, 0.8, 1.0], np.float32)
+ bg[py, px] += boost
+ return np.clip(bg, 0, 255).astype(np.uint8)
+
+
+def _strand_points(base, amps, ks, phis, ns, t, scale, period):
+ th = np.linspace(0, 2 * np.pi, 720, endpoint=True)
+ r = np.full_like(th, base)
+ for a, k, ph, n in zip(amps, ks, phis, ns):
+ r += a * np.sin(k * th + ph + 2 * np.pi * n * t / period)
+ c = CENTER * scale
+ return [(c + rr * scale * np.cos(tt), c + rr * scale * np.sin(tt)) for rr, tt in zip(r, th)]
+
+
+def _strand_params():
+ """Per-strand (base radius, amplitudes, lobe counts, phases, integer cycles per loop). Integer cycles per loop keep
+ the loop seamless."""
+ rng = np.random.default_rng(11)
+ params = []
+ for _color, off, _w in STRANDS:
+ ks = list(rng.choice([2, 3, 4, 5, 6, 7], size=3, replace=False)) + [int(rng.choice([9, 11, 13]))]
+ amps = [rng.uniform(4.5, 9.0) / (1 + 0.1 * k) for k in ks[:3]] + [rng.uniform(1.2, 2.4)]
+ phis = rng.uniform(0, 2 * np.pi, 4)
+ ns = [int(rng.choice([-1, 1]) * rng.integers(3, 8)) for _ in ks[:3]] + [int(rng.choice([-1, 1]) * rng.integers(10, 21))]
+ params.append((R0 + off, amps, ks, phis, ns))
+ return params
+
+
+def render_ring_frame(f: int, params, period: int) -> np.ndarray:
+ """One additive RGB ring frame (HxWx3 uint8) for loop position f of `period` frames."""
+ layer = Image.new("RGB", (SIZE * SS, SIZE * SS), (0, 0, 0))
+ draw = ImageDraw.Draw(layer)
+ for (color, _off, w), (base, amps, ks, phis, ns) in zip(STRANDS, params):
+ pts = _strand_points(base, amps, ks, phis, ns, f, SS, period)
+ draw.line(pts, fill=color, width=max(1, round(w * SS)), joint="curve")
+ sharp = layer.resize((SIZE, SIZE), Image.LANCZOS)
+ glow = sharp.filter(ImageFilter.GaussianBlur(5))
+ wide = sharp.filter(ImageFilter.GaussianBlur(1.0))
+ out = (np.asarray(sharp, np.float32) * 0.85 + np.asarray(wide, np.float32) * 0.5
+ + np.asarray(glow, np.float32) * 2.2)
+ return np.clip(out, 0, 255).astype(np.uint8)
+
+
+def iter_ring_frames(n_frames: int):
+ """Yield n_frames seamlessly looping ring frames one by one (low memory)."""
+ params = _strand_params()
+ for f in range(n_frames):
+ yield render_ring_frame(f, params, n_frames)
+
+
+class LoopSparkles:
+ """Deterministic twinkling particles that repeat exactly every loop. Sparkle i twinkles m_i times per loop
+ (period = loop / m_i) and takes a new, precomputed position on each twinkle."""
+
+ def __init__(self, n=N_SPARKLES, seed=5):
+ rng = np.random.default_rng(seed)
+ self.m = rng.integers(2, 6, n) # twinkles per loop -> period 1.6 .. 4 s
+ self.phase = rng.uniform(0, 1, n)
+ self.peak = rng.uniform(0.5, 0.95, n)
+ self.pos = []
+ for m in self.m:
+ r = np.sqrt(rng.uniform(0.02, 1.0, m)) * 205
+ a = rng.uniform(0, 2 * np.pi, m)
+ xs = (CENTER + r * np.cos(a)).astype(int)
+ ys = (CENTER + r * np.sin(a)).astype(int)
+ self.pos.append(list(zip(xs.tolist(), ys.tolist())))
+ yy, xx = np.mgrid[-4:5, -4:5]
+ d2 = xx ** 2 + yy ** 2
+ self.sprite = np.clip(np.exp(-d2 / 6.0) * 0.5 + (d2 <= 1) * 1.0, 0, 1).astype(np.float32)
+ self.color = np.array([150, 205, 255], np.float32)
+
+ def draw(self, frame: np.ndarray, f: int):
+ """Add sparkles for loop frame f (0..LOOP_FRAMES-1) to an int16 HxWx3 frame."""
+ for i in range(len(self.m)):
+ u = f / LOOP_FRAMES * self.m[i] + self.phase[i]
+ cyc = int(u)
+ ph = u - cyc
+ b = np.sin(np.pi * ph) ** 2 * self.peak[i]
+ if b < 0.02:
+ continue
+ x, y = self.pos[i][cyc % self.m[i]]
+ frame[y - 4:y + 5, x - 4:x + 5] += (self.sprite[..., None] * self.color * b).astype(np.int16)
+
+
+def iter_loop_frames():
+ """Yield the LOOP_FRAMES upright RGB uint8 frames of the background loop."""
+ bg = build_background().astype(np.int16)
+ sparkles = LoopSparkles()
+ for f, ring in enumerate(iter_ring_frames(LOOP_FRAMES)):
+ frame = np.minimum(bg + ring, 255).astype(np.int16) # ring is additive
+ sparkles.draw(frame, f)
+ yield np.clip(frame, 0, 255).astype(np.uint8)
+
+
+def rotation_filter(reverse: bool) -> str:
+ return "transpose=1" if reverse else "transpose=2"
+
+
+def user_cache_dir() -> Path:
+ """Per-user cache directory of the generated assets (not the source tree)."""
+ try:
+ if os.name == "nt":
+ base = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local")
+ elif sys.platform == "darwin":
+ base = Path.home() / "Library" / "Caches"
+ else:
+ base = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache")
+ except (RuntimeError, KeyError, OSError): # Path.home() fails without HOME / passwd entry
+ base = Path(tempfile.gettempdir())
+ return base / "turing-smart-screen-python"
+
+
+def cache_path(reverse: bool, cache_dir: Optional[Path] = None) -> Path:
+ return (cache_dir or user_cache_dir()) / f"video_face_v{VIDEO_VERSION}_{'rev' if reverse else 'norev'}.mp4"
+
+
+def require_ffmpeg() -> str:
+ exe = shutil.which("ffmpeg")
+ if not exe:
+ raise FatalError("ffmpeg was not found on the PATH. It is needed once to build the video of the screen "
+ "(libx264 required): install it (e.g. 'apt install ffmpeg', 'brew install ffmpeg', "
+ "'winget install ffmpeg') and run again.")
+ return exe
+
+
+def encode(frames: Iterator[np.ndarray], out: Path, reverse: bool, crf: int, rotate: bool = True, fps: int = FPS):
+ """Pipe upright RGB frames into ffmpeg (libx264, yuv420p, +faststart)."""
+ vf = (rotation_filter(reverse) + "," if rotate else "") + "format=yuv420p"
+ cmd = [require_ffmpeg(), "-hide_banner", "-loglevel", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24",
+ "-s", f"{SIZE}x{SIZE}", "-r", str(fps), "-i", "-", "-vf", vf, "-c:v", "libx264", "-profile:v", "main",
+ "-pix_fmt", "yuv420p", "-crf", str(crf), "-preset", "slow", "-g", str(fps), "-an",
+ "-movflags", "+faststart", "-f", "mp4", str(out)]
+ # stderr goes to a temp file: a pipe nobody reads while frames are written could fill up and block ffmpeg
+ errfile = tempfile.TemporaryFile()
+ try:
+ proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=errfile)
+ except OSError as e:
+ errfile.close()
+ raise FatalError(f"cannot run ffmpeg: {e}") from e
+ try:
+ try:
+ for fr in frames:
+ proc.stdin.write(np.ascontiguousarray(fr).tobytes())
+ except BrokenPipeError:
+ pass # ffmpeg exited early: its error output is reported below
+ finally:
+ try:
+ proc.stdin.close()
+ except OSError:
+ pass
+ code = proc.wait()
+ errfile.seek(0)
+ err = errfile.read(4000).decode(errors="replace").strip()
+ if code != 0:
+ raise FatalError(f"ffmpeg failed: {err or 'no error output'}")
+ finally:
+ if proc.poll() is None:
+ proc.kill()
+ proc.wait()
+ errfile.close()
+
+
+def build_video(out: Path, reverse: bool) -> Path:
+ """Encode the loop into `out` (atomically), re-encoding at a higher CRF until it fits the storage of the
+ screen. Leaves no partial file behind. Raises FatalError if it cannot be made small enough."""
+ out.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp_name = tempfile.mkstemp(prefix=out.stem + ".", suffix=".tmp.mp4", dir=out.parent) # unique per run
+ os.close(fd)
+ tmp = Path(tmp_name)
+ try:
+ for crf in CRF_LADDER:
+ logger.info(f"Encoding the video face loop (CRF {crf})...")
+ encode(iter_loop_frames(), tmp, reverse, crf)
+ size = tmp.stat().st_size
+ if size <= MAX_VIDEO_BYTES:
+ tmp.replace(out)
+ return out
+ logger.warning(f"video is {size} bytes, more than {MAX_VIDEO_BYTES}: trying a higher CRF")
+ raise FatalError(f"cannot encode the video within {MAX_VIDEO_BYTES} bytes (the screen stores about 1.2 MB)")
+ finally:
+ if tmp.exists():
+ tmp.unlink()
+
+
+def ensure_video(reverse: bool, rebuild: bool = False, out: Optional[Path] = None) -> Path:
+ """Path of the encoded loop, built if missing, if too large for the screen, or if `rebuild` is set."""
+ out = Path(out) if out else cache_path(reverse)
+ if not rebuild and out.exists() and 0 < out.stat().st_size <= MAX_VIDEO_BYTES:
+ return out
+ return build_video(out, reverse)
diff --git a/res/docs/rev-c-video-face.gif b/res/docs/rev-c-video-face.gif
new file mode 100644
index 000000000..481b4b7d6
Binary files /dev/null and b/res/docs/rev-c-video-face.gif differ
diff --git a/res/docs/rev-c-video-face.md b/res/docs/rev-c-video-face.md
new file mode 100644
index 000000000..4d46b3d3e
--- /dev/null
+++ b/res/docs/rev-c-video-face.md
@@ -0,0 +1,120 @@
+# Video face for the 2.1" round rev C screen
+
+
+
+`video-face-rev-c.py` shows an animated face (flame ring, sparkles, CPU / GPU / RAM rows with a scrolling bar history)
+on the 2.1" round (480x480) Turing rev C screen. It is not a theme.
+
+The animated background is a **video stored on the screen and decoded by the screen itself**. The computer only sends
+small incremental *video overlay* updates (labels, bars, percentages) every 0.5 s, so the load is very low and the
+animation keeps running when the program stops.
+
+The look is based on theme 26. The existing driver and themes are not modified: this adds
+`library/lcd/lcd_comm_rev_c_video.py` (an `LcdCommRevC` extension) and `library/video_face/`.
+
+## Requirements
+- A 2.1" rev C screen with `REVISION: C` and a 2.1" theme (for example `26`) in `config.yaml`. The program refuses to
+ run with another revision or screen size.
+- Python dependencies of `requirements.txt`.
+- **ffmpeg with libx264 on the PATH**, only to build the loop video once (it is cached in the per-user cache directory,
+ `~/.cache/turing-smart-screen-python` on Linux, `~/Library/Caches/...` on macOS, `%LOCALAPPDATA%\turing-smart-screen-python`
+ on Windows). Install it with `sudo apt install ffmpeg`, `brew install ffmpeg` or `winget install ffmpeg`.
+
+## Usage
+ python video-face-rev-c.py # run on the screen
+ python video-face-rev-c.py --preview out.gif # composite 3 s with a fake load (.gif or .mp4), no screen needed
+ python video-face-rev-c.py --rebuild-video # rebuild the cached loop video
+
+`config.yaml` is used for `COM_PORT`, `HW_SENSORS`, `BRIGHTNESS`, `DISPLAY_REVERSE` and `RESET_ON_STARTUP` (a soft
+reset: stop video/media, the screen is not rebooted). Sensors are read through `library/sensors`, so everything
+supported by `HW_SENSORS` works (Nvidia, AMD, LibreHardwareMonitor...). If a value is not available, for example no
+supported GPU, a warning is logged once and the row shows `N/A`.
+
+Stop with Ctrl-C (or SIGTERM): the video keeps looping on the screen with the last overlay.
+
+## Configuration
+The optional `video_face:` section of `config.yaml` (defaults shown in `config.yaml`, loaded by `library/config.py`):
+rows to show and their order, sample period, directory and name prefix of the video on the screen, and the bar colours.
+Bars are vertical gradients (like btop): the colour of each pixel row depends on its level, the distance from the
+centre line as a percentage of the maximum bar height, not on the bar's value. `BAR_GRADIENT` is a list of
+`[level %, [R, G, B]]` stops, sorted by level and covering 0 to 100; colours are linearly interpolated between stops.
+The default is light blue up to 25 %, light cyan (35 %), pale cream (42 %, a bright bridge that avoids a muddy
+blue-yellow mix), pale yellow (50 %), golden yellow (60 %), amber (70 %), orange (82 %) and red (94-100 %):
+
+```yaml
+video_face:
+ BAR_GRADIENT:
+ - [0, [25, 160, 230]] # light blue
+ - [25, [25, 160, 230]] # light blue until 25 %
+ - [35, [110, 210, 240]] # light cyan
+ - [42, [235, 245, 205]] # pale cream (bright bridge, avoids a muddy blue-yellow mix)
+ - [50, [255, 235, 90]] # pale yellow
+ - [60, [255, 210, 40]] # golden yellow
+ - [70, [255, 170, 30]] # amber
+ - [82, [255, 120, 25]] # orange
+ - [94, [255, 50, 40]] # red
+ - [100, [255, 50, 40]]
+```
+
+To change the look, edit, add or remove stops (at least 2, first level 0, last level 100, levels strictly increasing,
+RGB 0-255); an invalid list is a configuration error (exit code `2`). A 25 % bar is all blue, an 80 % bar goes from blue
+at the centre to amber/orange at its tips, and only bars near 100 % get red tips. The former `BAR_COLOR_*`,
+`BLUE_UNTIL`, `YELLOW_FROM`, `YELLOW_UNTIL` and `RED_FROM` keys are ignored (a warning is logged once).
+
+## Errors and exit codes
+- The video is checked against the storage limit of the screen **before anything is deleted or written** there; it is
+ re-encoded at a higher CRF if needed. An older video of this program is only removed when a new upload is needed.
+- Serial errors (write timeout, disconnection, re-enumeration of the port) are logged, then the program backs off, reopens
+ or re-detects the port and initialises the video and overlay again. If the screen reports `needReSend` again right
+ after re-initialisation, the same backoff applies.
+- `0` clean stop; `1` screen not reachable at startup; `2` configuration, unsupported screen/revision, missing ffmpeg or a
+ video that cannot fit; `3` the video could not be stored on the screen. Codes 2 and 3 do not fix themselves, so a service
+ manager should not restart on them.
+
+## Running as a service (Linux, optional)
+A systemd user unit, for example `~/.config/systemd/user/video-face.service` (adjust the paths):
+
+ [Unit]
+ Description=Rev C video face
+ After=graphical-session.target
+ PartOf=graphical-session.target
+
+ [Service]
+ WorkingDirectory=%h/turing-smart-screen-python
+ ExecStart=%h/turing-smart-screen-python/.venv/bin/python video-face-rev-c.py
+ Restart=on-failure
+ RestartSec=10
+ RestartPreventExitStatus=2 3
+
+ [Install]
+ WantedBy=graphical-session.target
+
+Then `systemctl --user daemon-reload && systemctl --user enable --now video-face.service`. Logs are in `log.log` in the
+working directory (and in `journalctl --user -u video-face -f`); a status line is logged every 60 s.
+
+## Protocol notes and limitations
+Measured on a screen with **ROM 89** (hello reply `chs_5inch.dev1_rom1.89`, which is also what the 2.1" model returns);
+other ROM versions or models are untested (a warning is logged for another ROM).
+- **Storage**: `/root/video/` holds only about **1.2 MB**. Larger uploads are silently truncated, so the loop is encoded
+ at CRF 25 (about 1.0 MB, higher CRF if needed). Upload: `file_rev_done` must be awaited. Do not leave other large
+ videos in that directory.
+- **Orientation**: the screen plays videos in its native frame. With `DISPLAY_REVERSE: true` the video is pre-rotated with
+ `transpose=1` and overlay images with `np.rot90(upright, 3)`; both were confirmed upright by eye. For
+ `DISPLAY_REVERSE: false` an extra 180 degrees is added (`transpose=2`, `np.rot90(upright, 1)`): this is **derived, not
+ verified** on a device.
+- **Update framing**: the display reads 249 data bytes from each 250-byte packet (the 250th is a separator) and the
+ `EF 69` terminator is part of that stream, so it must be chunked together with the payload. The old
+ `LcdCommRevC._generate_update_image` chunked only the payload; updates whose raw length n satisfies n = 248 or 0
+ (mod 249) (248, 249, 497, 498, ...) lost the terminator, plus n = 250 under the old `> 250` threshold. The status
+ then showed a sticky `needReSend:1`. The fix is in `_generate_update_image` (upstream PR #1149).
+- **Count**: the update count must restart at 0 after every full frame or full overlay init and rise by exactly 1.
+ `needReSend:1` is only cleared by a full frame or overlay init, which is what the program does on any bad status.
+- **Status**: `QUERY_STATUS` returns `needReSend:N|renderCnt:M`. `renderCnt` rises about 30 per second while the video
+ plays; if it stalls the video is started again (and re-uploaded if it is gone).
+- Overlay pixel format is 3 bytes per pixel (`B&0xFC | a4>>2`, `G&0xFC | a4&3`, `R`, `a4 = alpha>>4`); the colour
+ fidelity compared to other encodings was not checked by eye. Typical update: 10 ms for the rows (about 2-5 KB).
+
+## Credits
+The overlay protocol derives from PR #348 of mathoudebine/turing-smart-screen-python by gwendal-h (incremental overlay
+updates) and from maylton/turing-smart-screen-video-overlay (video overlay initialisation and visibility map), both
+GPL-3.0 like this project.
diff --git a/tests/library/lcd/test_lcd_comm_rev_c_update_framing.py b/tests/library/lcd/test_lcd_comm_rev_c_update_framing.py
new file mode 100644
index 000000000..022b3e163
--- /dev/null
+++ b/tests/library/lcd/test_lcd_comm_rev_c_update_framing.py
@@ -0,0 +1,115 @@
+import unittest
+
+from PIL import Image
+
+from library.lcd import lcd_comm_rev_c
+from library.lcd.lcd_comm_rev_c import LcdCommRevC, Orientation, SubRevision, Command
+
+from .serial_mock import new_testing_serial
+
+
+class MockedLcdCommRevC(LcdCommRevC):
+ def openSerial(self):
+ self.lcd_serial = new_testing_serial()
+
+
+def new_lcd(sub_revision: SubRevision, rom_version: int, width: int, height: int) -> MockedLcdCommRevC:
+ lcd = MockedLcdCommRevC(display_width=width, display_height=height)
+ lcd.sub_revision = sub_revision
+ lcd.rom_version = rom_version
+ lcd.SetOrientation(Orientation.LANDSCAPE) # no image rotation
+ lcd.lcd_serial.reset_mock()
+ return lcd
+
+
+def device_parse(body: bytes, size: int) -> bytes:
+ """Model of the display firmware: the body is sent in 250-byte packets zero-padded; only the first 249 bytes of
+ each packet are data, the 250th is a separator. `size` data bytes are read (the "ef69" terminator included)."""
+ if len(body) % 250:
+ body += bytes(250 - len(body) % 250)
+ stream = b"".join(body[i:i + 249] for i in range(0, len(body), 250))
+ return stream[:size]
+
+
+def update_for(lcd, width: int, height: int):
+ """Run the real _generate_update_image and return (body, header, raw_length)."""
+ image = Image.new("RGB", (width, height), (10, 20, 30))
+ body, header = lcd._generate_update_image(image, 0, 0, 0, Command.UPDATE_BITMAP)
+ size = int.from_bytes(header[4:7], "big")
+ return bytes(body), bytes(header), size - 2
+
+
+class TestLcdCommRevCUpdateFraming(unittest.TestCase):
+ def test_terminator_survives_for_any_raw_length(self):
+ # With the 2.1" 3-byte pixel encoding, raw length = height * (3 + 2 + 3 * width)
+ lcd = new_lcd(SubRevision.REV_2INCH, 89, 480, 480)
+ covered = set()
+ sizes = [(w, h) for w in range(1, 300) for h in range(1, 9)]
+ sizes += [(480, h) for h in range(150, 161)] # ~227 KB, close to a quarter of the screen
+ for w, h in sizes:
+ body, header, n = update_for(lcd, w, h)
+ covered.add(n)
+ with self.subTest(width=w, height=h, raw_length=n):
+ self.assertEqual(n, h * (5 + 3 * w))
+ data = device_parse(body, n + 2)
+ self.assertEqual(data[-2:], b"\xef\x69")
+ self.assertEqual(len(data), n + 2)
+ # The data (without the separators) is the raw records followed by the terminator
+ self.assertEqual(data[:5], bytes(3) + w.to_bytes(2, "big"))
+ # Raw lengths that used to be framed wrongly (248, 249, 250, then 497, 498 and so on) must be covered
+ for n in (248, 249, 250, 251, 497, 498, 746, 1992):
+ self.assertTrue(n in covered, f"raw length {n} not covered")
+ self.assertTrue(any(226000 < n < 228000 for n in covered))
+
+ def test_header_layout_and_chunking(self):
+ lcd = new_lcd(SubRevision.REV_2INCH, 89, 480, 480)
+ img = Image.new("RGB", (10, 2), (1, 2, 3))
+ body, header = lcd._generate_update_image(img, 4, 6, 9, Command.UPDATE_BITMAP)
+ # 2 lines of (3 pos + 2 width + 30 colour) bytes + 2 terminator bytes
+ self.assertEqual(bytes(header), bytes.fromhex("cc ef 69 00") + (72).to_bytes(3, "big") + bytes(3)
+ + (9).to_bytes(4, "big"))
+ self.assertEqual(bytes(body)[-2:], b"\xef\x69")
+ self.assertEqual(len(body), 72)
+
+ def test_all_models_use_same_framing(self):
+ for sub_revision, rom, width, height in (
+ (SubRevision.REV_2INCH, 89, 480, 480),
+ (SubRevision.REV_5INCH, 89, 480, 800),
+ (SubRevision.REV_5INCH, 87, 480, 800),
+ (SubRevision.REV_8INCH, 89, 480, 1920)):
+ lcd = new_lcd(sub_revision, rom, width, height)
+ for w, h in ((1, 1), (28, 3), (83, 1), (160, 2), (200, 100)):
+ with self.subTest(sub_revision=sub_revision, rom=rom, size=(w, h)):
+ body, header, n = update_for(lcd, w, h)
+ size = n + 2
+ data = device_parse(bytes(body), size)
+ self.assertEqual(len(data), size)
+ self.assertEqual(data[-2:], b"\xef\x69")
+ # The separator bytes must not be part of the data: de-chunked data is body without separators
+ self.assertEqual(len(body), size + (size - 1) // 249)
+
+ def test_count_restarts_after_full_frame_and_increments_per_update(self):
+ lcd = new_lcd(SubRevision.REV_2INCH, 89, 480, 480)
+ full = Image.new("RGB", (480, 480))
+ patch = Image.new("RGB", (20, 10))
+ lcd_comm_rev_c.Count.Start = 5
+ lcd.DisplayPILImage(full)
+ self.assertEqual(lcd_comm_rev_c.Count.Start, 0)
+
+ counts = []
+ for _ in range(3):
+ lcd.lcd_serial.reset_mock()
+ lcd.DisplayPILImage(patch, x=0, y=0, image_width=20, image_height=10)
+ header = lcd.lcd_serial.mock_calls[0].args[0]
+ counts.append(int.from_bytes(header[10:14], "big"))
+ self.assertEqual(counts, [0, 1, 2])
+ self.assertEqual(lcd_comm_rev_c.Count.Start, 3)
+
+ lcd.DisplayPILImage(full)
+ lcd.lcd_serial.reset_mock()
+ lcd.DisplayPILImage(patch, x=0, y=0, image_width=20, image_height=10)
+ self.assertEqual(int.from_bytes(lcd.lcd_serial.mock_calls[0].args[0][10:14], "big"), 0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/library/lcd/test_lcd_comm_rev_c_video.py b/tests/library/lcd/test_lcd_comm_rev_c_video.py
new file mode 100644
index 000000000..710127859
--- /dev/null
+++ b/tests/library/lcd/test_lcd_comm_rev_c_video.py
@@ -0,0 +1,251 @@
+import pathlib
+import tempfile
+import unittest
+from unittest import mock
+
+import numpy as np
+
+from library.lcd.lcd_comm_rev_c_video import (
+ LcdCommRevCVideo, DeviceError, FatalError, StopRequested, UploadSizeError, MAX_VIDEO_BYTES, check_video_size, compress_px, frame_overlay_update,
+ parse_hello, parse_status, remote_video_name, runs, to_native, visible_list, SIZE)
+
+from .test_lcd_comm_rev_c_update_framing import device_parse
+
+
+class FakeSerial:
+ """Scripted serial port: records the writes, answers QUERY_STATUS (cf ef 69 ...) with the next scripted text."""
+
+ def __init__(self, statuses=()):
+ self.writes = []
+ self.statuses = list(statuses)
+ self.pending = b""
+ self.in_waiting = 0
+ self.write_timeout = 10
+
+ def write(self, data):
+ self.writes.append(bytes(data))
+ if bytes(data)[:3] == bytes.fromhex("cfef69"):
+ text = self.statuses.pop(0) if self.statuses else "needReSend:0|renderCnt:1"
+ self.pending = text.encode().ljust(1024, b"\x00")
+
+ def read(self, n=1):
+ data, self.pending = self.pending[:n], self.pending[n:]
+ return data
+
+ def flush(self):
+ pass
+
+ def reset_input_buffer(self):
+ self.pending = b""
+
+ def close(self):
+ pass
+
+
+class TestableDriver(LcdCommRevCVideo):
+ def __init__(self, statuses=()):
+ self._fake = FakeSerial(statuses)
+ super().__init__("AUTO")
+
+ def openSerial(self):
+ self.lcd_serial = self._fake
+
+ def _read(self, timeout=1.0, settle=0.03):
+ return b"" # the scripted replies only answer QUERY_STATUS: do not wait for the others
+
+
+def overlay(value, size=SIZE):
+ img = np.zeros((size, size, 4), np.uint8)
+ img[10:14, 20:50] = (value, 2, 3, 255)
+ return img
+
+
+class TestPureHelpers(unittest.TestCase):
+ def test_parse_status(self):
+ st = parse_status("needReSend:0|renderCnt:123")
+ self.assertTrue(st.ok)
+ self.assertEqual((st.need_resend, st.render_cnt), (False, 123))
+ st = parse_status("needReSend:1|renderCnt:5")
+ self.assertFalse(st.ok)
+ self.assertTrue(st.need_resend)
+ for bad in ("", "garbage", "needReSend:0"):
+ st = parse_status(bad)
+ self.assertFalse(st.ok)
+ self.assertIsNone(st.need_resend)
+ self.assertIsNone(st.render_cnt)
+
+ def test_parse_hello(self):
+ self.assertEqual(parse_hello("chs_5inch.dev1_rom1.89"), 89)
+ self.assertEqual(parse_hello("chs_5inch"), 0)
+ self.assertIsNone(parse_hello(""))
+ self.assertIsNone(parse_hello("xyz"))
+
+ def test_size_guard(self):
+ check_video_size(MAX_VIDEO_BYTES)
+ with self.assertRaises(FatalError) as ctx:
+ check_video_size(MAX_VIDEO_BYTES + 1)
+ self.assertEqual(ctx.exception.exit_code, 2)
+
+ def test_remote_name_depends_on_content(self):
+ a, b = remote_video_name("p_", b"abc"), remote_video_name("p_", b"abd")
+ self.assertTrue(a.startswith("p_") and a.endswith(".mp4"))
+ self.assertNotEqual(a, b)
+ self.assertEqual(a, remote_video_name("p_", b"abc"))
+
+ def test_runs(self):
+ mask = np.array([0, 1, 1, 0, 0, 1, 0, 0, 0, 1], bool)
+ self.assertEqual(runs(mask), [(1, 3), (5, 6), (9, 10)])
+ self.assertEqual(runs(mask, min_gap=3), [(1, 6), (9, 10)]) # gaps of 2 are merged
+ self.assertEqual(runs(np.zeros(5, bool)), [])
+
+ def test_visible_list(self):
+ alpha = np.zeros((SIZE, SIZE), np.uint8)
+ alpha[2, 3:6] = 1
+ alpha[2, 10] = 255
+ alpha[7, 0:2] = 9
+ expected = ((2 * SIZE + 3).to_bytes(3, "big") + (3).to_bytes(2, "big")
+ + (2 * SIZE + 10).to_bytes(3, "big") + (1).to_bytes(2, "big")
+ + (7 * SIZE).to_bytes(3, "big") + (2).to_bytes(2, "big"))
+ self.assertEqual(visible_list(alpha), expected)
+ self.assertEqual(visible_list(np.zeros((SIZE, SIZE), np.uint8)), b"")
+
+ def test_compress_px(self):
+ row = np.array([[0x11, 0x22, 0x33, 0xF0], [0xFF, 0xFF, 0xFF, 0x00]], np.uint8) # R, G, B, A
+ a4 = 0xF0 >> 4
+ self.assertEqual(compress_px(row), bytes((0x33 & 0xFC | a4 >> 2, 0x22 & 0xFC | a4 & 3, 0x11,
+ 0xFC, 0xFC, 0xFF)))
+
+ def test_to_native(self):
+ img = np.arange(2 * 3 * 4, dtype=np.uint8).reshape(2, 3, 4)
+ self.assertTrue(np.array_equal(to_native(img, True), np.rot90(img, 3)))
+ self.assertTrue(np.array_equal(to_native(img, False), np.rot90(img, 1)))
+ self.assertTrue(to_native(img, True).flags["C_CONTIGUOUS"])
+
+ def test_overlay_update_framing(self):
+ header, body = frame_overlay_update(b"x" * 10, 5, 7)
+ self.assertEqual(header, bytes.fromhex("cc ef 69 00") + (12).to_bytes(3, "big") + bytes(3)
+ + (5).to_bytes(4, "big") + (7).to_bytes(4, "big"))
+ for n in list(range(1, 600)) + [1991, 1992, 227000, 227001]:
+ raw = bytes((i * 11 + 1) % 253 for i in range(n))
+ _, body = frame_overlay_update(raw, 0, 0)
+ self.assertEqual(device_parse(body, n + 2), raw + b"\xef\x69", n)
+
+
+class TestDriver(unittest.TestCase):
+ def test_set_brightness_validation(self):
+ dev = TestableDriver()
+ for bad in (-1, 101, None, "50", True):
+ with self.assertRaises(FatalError):
+ dev.set_brightness(bad)
+ self.assertEqual(dev._fake.writes, [])
+ dev.set_brightness(100)
+ self.assertEqual(dev._fake.writes[0][10], 255)
+
+ def test_ensure_video_refuses_oversized_file_before_any_write(self):
+ import tempfile, pathlib
+ dev = TestableDriver()
+ with tempfile.TemporaryDirectory() as d:
+ big = pathlib.Path(d) / "big.mp4"
+ big.write_bytes(bytes(MAX_VIDEO_BYTES + 1))
+ with self.assertRaises(FatalError):
+ dev.ensure_video(big, "/root/video/", "p_")
+ self.assertEqual(dev._fake.writes, []) # nothing listed, deleted or uploaded
+
+ def test_update_overlay_counts_and_recovers(self):
+ dev = TestableDriver()
+ dev.init_overlay(overlay(1))
+ self.assertEqual(dev._count, 0)
+ counts = []
+ for v in (2, 3, 4):
+ dev._fake.writes.clear()
+ res = dev.update_overlay(overlay(v))
+ self.assertTrue(res.status.ok and not res.recovered)
+ counts.append(int.from_bytes(dev._fake.writes[0][10:14], "big"))
+ self.assertEqual(counts, [0, 1, 2])
+ # unchanged image: nothing sent but the status query
+ dev._fake.writes.clear()
+ res = dev.update_overlay(overlay(4))
+ self.assertEqual(res.payload_bytes, 0)
+ self.assertEqual(len(dev._fake.writes), 1)
+
+ # bad status: overlay re-initialised, count back to 0
+ dev._fake.statuses = ["needReSend:1|renderCnt:9", "needReSend:0|renderCnt:10"]
+ res = dev.update_overlay(overlay(5))
+ self.assertTrue(res.recovered and res.status.ok)
+ self.assertEqual(res.status.render_cnt, 10)
+ self.assertEqual(dev._count, 0)
+ self.assertEqual(dev.stats["recoveries"], 1)
+
+ def test_update_overlay_raises_when_reinit_does_not_clear_error(self):
+ dev = TestableDriver()
+ dev.init_overlay(overlay(1))
+ dev._fake.statuses = ["needReSend:1|renderCnt:9", "needReSend:1|renderCnt:9"]
+ with self.assertRaises(DeviceError):
+ dev.update_overlay(overlay(2))
+
+ def test_empty_status_is_a_failure(self):
+ dev = TestableDriver()
+ dev.init_overlay(overlay(1))
+ dev._fake.statuses = ["", ""]
+ with self.assertRaises(DeviceError):
+ dev.update_overlay(overlay(2))
+
+ def _upload_setup(self, size=100_000):
+ dev = TestableDriver()
+ d = tempfile.TemporaryDirectory()
+ self.addCleanup(d.cleanup)
+ f = pathlib.Path(d.name) / "v.mp4"
+ f.write_bytes(bytes((i * 7) % 251 for i in range(size)))
+ return dev, f
+
+ def test_upload_chunked_writes_keep_the_protocol_bytes(self):
+ dev, f = self._upload_setup()
+ data = f.read_bytes()
+ with mock.patch.object(dev, "file_size", side_effect=[0, len(data)]):
+ dev.upload(f, "/root/video/x.mp4")
+ writes = dev._fake.writes
+ self.assertGreater(len(writes), 3) # command + several data writes
+ self.assertTrue(all(len(w) % 250 == 0 for w in writes[1:]))
+ self.assertLessEqual(max(len(w) for w in writes[1:]), 250 * 128)
+ blob = b"".join(writes[1:])
+ expected = b"".join(data[i:i + 249].ljust(250, b"\x00") for i in range(0, len(data), 249))
+ self.assertEqual(blob, expected)
+
+ def test_upload_stops_between_chunks(self):
+ dev, f = self._upload_setup()
+ dev.stop_requested = lambda: len(dev._fake.writes) >= 2
+ with mock.patch.object(dev, "file_size", return_value=0):
+ with self.assertRaises(StopRequested):
+ dev.upload(f, "/root/video/x.mp4")
+ self.assertEqual(len(dev._fake.writes), 2)
+
+ def test_upload_serial_error_is_a_device_error_not_fatal(self):
+ dev, f = self._upload_setup()
+ import serial
+ dev._fake.write = mock.Mock(side_effect=serial.SerialTimeoutException("timeout"))
+ with mock.patch.object(dev, "file_size", return_value=0):
+ with self.assertRaises(DeviceError) as ctx:
+ dev.ensure_video(f, "/root/video/", "p_")
+ self.assertNotIsInstance(ctx.exception, FatalError)
+ dev._fake.write.assert_called_once() # no second upload attempt on a serial error
+
+ def test_ensure_video_size_mismatch_retries_once_then_fatal(self):
+ dev, f = self._upload_setup()
+ with mock.patch.object(dev, "upload", side_effect=UploadSizeError("short")) as up, \
+ mock.patch.object(dev, "list_dir", return_value=[]), \
+ mock.patch.object(dev, "file_size", return_value=0):
+ with self.assertRaises(FatalError) as ctx:
+ dev.ensure_video(f, "/root/video/", "p_", log=lambda *_: None)
+ self.assertEqual(ctx.exception.exit_code, 3)
+ self.assertEqual(up.call_count, 2)
+
+ def test_hello_does_not_sleep_after_last_attempt(self):
+ dev = TestableDriver()
+ with mock.patch("library.lcd.lcd_comm_rev_c_video.time.sleep") as sl:
+ with self.assertRaises(DeviceError):
+ dev.hello(attempts=3)
+ self.assertEqual(sl.call_count, 2)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/library/video_face/__init__.py b/tests/library/video_face/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/library/video_face/test_video_face.py b/tests/library/video_face/test_video_face.py
new file mode 100644
index 000000000..1c06167c2
--- /dev/null
+++ b/tests/library/video_face/test_video_face.py
@@ -0,0 +1,332 @@
+import math
+import pathlib
+import tempfile
+import unittest
+from unittest import mock
+
+import numpy as np
+
+from library.config import VIDEO_FACE_DEFAULT
+from library.lcd.lcd_comm_rev_c_video import MAX_VIDEO_BYTES
+from library.lcd.rev_c_errors import FatalError
+from library.video_face import video
+from library.video_face.render import UiLayer, clean, gradient_strip, row_centres
+from library.video_face.sampler import Sampler, select_sensors
+from library.video_face.settings import from_config
+
+# Deliberately the documented defaults, so a change of the defaults is noticed by the tests
+BLUE, CYAN, CREAM, PALE, GOLD, AMBER, ORANGE, RED = (
+ (25, 160, 230), (110, 210, 240), (235, 245, 205), (255, 235, 90), (255, 210, 40), (255, 170, 30), (255, 120, 25),
+ (255, 50, 40))
+
+
+def settings(**overrides):
+ return from_config({**VIDEO_FACE_DEFAULT, **overrides})
+
+
+class TestBarColors(unittest.TestCase):
+ def setUp(self):
+ self.colors = settings().colors
+
+ def test_stops(self):
+ c = self.colors.color
+ for v in (-5, 0, 10, 25):
+ self.assertEqual(c(v), BLUE) # blue until 25 %
+ for v, col in ((35, CYAN), (42, CREAM), (50, PALE), (60, GOLD), (70, AMBER), (82, ORANGE), (94, RED), (100, RED),
+ (120, RED)):
+ self.assertEqual(c(v), col)
+
+ def test_midpoints(self):
+ c = self.colors.color
+ for v, (c0, c1) in ((30, (BLUE, CYAN)), (38.5, (CYAN, CREAM)), (46, (CREAM, PALE)), (55, (PALE, GOLD)),
+ (65, (GOLD, AMBER)), (76, (AMBER, ORANGE)), (88, (ORANGE, RED))):
+ self.assertEqual(c(v), tuple(int(round((a + b) / 2)) for a, b in zip(c0, c1)))
+ self.assertNotEqual(c(25.1), BLUE)
+ self.assertNotEqual(c(93.9), RED)
+
+ def test_no_muddy_band(self):
+ """The blue to yellow transition stays bright: no level between 25 % and 60 % is darker than both endpoints."""
+ luma = lambda col: 0.299 * col[0] + 0.587 * col[1] + 0.114 * col[2]
+ low_value = min(max(BLUE), max(PALE))
+ low_luma = min(luma(BLUE), luma(PALE))
+ strip = gradient_strip(self.colors)
+ levels = [abs(i + 0.5 - len(strip) / 2) / (len(strip) / 2) * 100 for i in range(len(strip))]
+ band = [tuple(int(x) for x in p) for p, lv in zip(strip, levels) if 25 <= lv <= 60]
+ self.assertGreater(len(band), 10)
+ for col in band:
+ self.assertGreaterEqual(max(col), low_value, col)
+ self.assertGreaterEqual(luma(col), low_luma - 1, col)
+
+ def test_custom_gradient(self):
+ colors = settings(BAR_GRADIENT=[[0, [0, 0, 0]], [50.5, [100, 200, 50]], [100, [255, 255, 255]]]).colors
+ self.assertEqual(colors.color(0), (0, 0, 0))
+ self.assertEqual(colors.color(50.5), (100, 200, 50))
+ self.assertEqual(colors.color(100), (255, 255, 255))
+
+
+class TestSettings(unittest.TestCase):
+ def test_defaults(self):
+ s = settings()
+ self.assertEqual(s.rows, ["CPU", "GPU", "RAM"])
+ self.assertEqual(s.sample_period, 0.5)
+ self.assertEqual(s.remote_dir, "/root/video/")
+
+ def test_normalisation(self):
+ s = settings(ROWS=["ram", "cpu"], REMOTE_DIR="/root/video")
+ self.assertEqual(s.rows, ["RAM", "CPU"])
+ self.assertEqual(s.remote_dir, "/root/video/")
+
+ def test_invalid_values(self):
+ for bad in (dict(ROWS=[]), dict(ROWS=["CPU", "CPU"]), dict(ROWS=["DISK"]), dict(SAMPLE_PERIOD=0),
+ dict(SAMPLE_PERIOD="fast"), dict(REMOTE_DIR="video"), dict(REMOTE_PREFIX=""),
+ dict(REMOTE_PREFIX="a/b"), dict(BAR_GRADIENT=None), dict(BAR_GRADIENT=[[0, [1, 2, 3]]]),
+ dict(BAR_GRADIENT=[[0, [1, 2]], [100, [1, 2, 3]]]),
+ dict(BAR_GRADIENT=[[0, [1, 2, 300]], [100, [1, 2, 3]]]),
+ dict(BAR_GRADIENT=[[0, [1, 2, 3]], [60, [1, 2, 3]], [50, [1, 2, 3]], [100, [1, 2, 3]]]),
+ dict(BAR_GRADIENT=[[10, [1, 2, 3]], [100, [1, 2, 3]]]),
+ dict(BAR_GRADIENT=[[0, [1, 2, 3]], [90, [1, 2, 3]]]),
+ dict(BAR_GRADIENT=[[0, [1, 2, 3]], [101, [1, 2, 3]]]),
+ dict(BAR_GRADIENT=[[0, [1, 2, 3]], [0, [1, 2, 3]], [100, [1, 2, 3]]]),
+ dict(BAR_GRADIENT=[0, 100])):
+ with self.subTest(bad=bad), self.assertRaises(FatalError):
+ settings(**bad)
+
+
+ def test_legacy_keys_are_ignored_with_one_warning(self):
+ import library.video_face.settings as mod
+ mod._legacy_warned = False
+ with self.assertLogs("root", "WARNING") as logs:
+ s = settings(BAR_COLOR_LOW=[1, 2, 3], BLUE_UNTIL=10)
+ settings(BLUE_UNTIL=10) # only warned once
+ self.assertEqual(len(logs.records), 1)
+ self.assertIn("BAR_GRADIENT", logs.output[0])
+ self.assertEqual(s.colors.color(0), BLUE)
+
+
+class TestConfigGuard(unittest.TestCase):
+ def test_non_mapping_video_face_section_is_ignored(self):
+ import importlib
+ import yaml
+ import library.config as cfg
+ real = yaml.safe_load
+
+ def load(stream):
+ data = real(stream)
+ if isinstance(data, dict) and "config" in data and "display" in data: # config.yaml
+ data["video_face"] = self.bad
+ return data
+
+ try:
+ for self.bad in ("oops", ["a"], 3, None, {"ROWS": ["CPU"]}):
+ with self.subTest(bad=self.bad), mock.patch("yaml.safe_load", side_effect=load):
+ importlib.reload(cfg) # must not raise
+ expected = dict(VIDEO_FACE_DEFAULT, **(self.bad if isinstance(self.bad, dict) else {}))
+ self.assertEqual(cfg.VIDEO_FACE_DATA, expected)
+ finally:
+ importlib.reload(cfg)
+
+
+class TestRender(unittest.TestCase):
+ def test_row_centres(self):
+ self.assertEqual(row_centres(3), [160, 240, 320])
+ self.assertEqual(row_centres(1), [240])
+ self.assertEqual(row_centres(2), [200, 280])
+
+ def test_clean(self):
+ self.assertIsNone(clean(None))
+ self.assertIsNone(clean(math.nan))
+ self.assertEqual(clean(3), 3.0)
+
+ def test_render_is_480_rgba_with_transparent_background(self):
+ s = settings()
+ ui = UiLayer(s.rows, s.colors)
+ img = ui.render([[10.0, 60.0, 99.0], [None], [50.0] * 30])
+ self.assertEqual(img.shape, (480, 480, 4))
+ self.assertEqual(img[0, 0, 3], 0) # no backing
+ self.assertTrue((img[..., 3] > 0).any())
+ # Row bars are centred on the row's centre line, the 100 % bar spans 48 px
+ col = img[:, 140 + 25 * 7 + 1, 3]
+ self.assertEqual(int((col[130:190] > 0).sum()), 48)
+
+ def _bar(self, v):
+ """RGB column of the newest bar of the first row (centre line y=160) for a single 3-row render."""
+ s = settings()
+ img = UiLayer(s.rows, s.colors).render([[v], [0.0], [0.0]])
+ col = img[:, 140 + 25 * 7 + 1]
+ ys = np.nonzero(col[130:190, 3])[0] + 130
+ return col[ys[0]:ys[-1] + 1, :3]
+
+ def test_bar_is_a_gradient_by_level(self):
+ col = self._bar(80.0)
+ self.assertEqual(len(col), 38)
+ self.assertEqual(tuple(col[len(col) // 2]), BLUE) # near the centre
+ for tip in (col[0], col[-1]): # level 80 %: between amber and orange, no red
+ self.assertTrue(AMBER[1] > tip[1] > ORANGE[1], tip)
+ self.assertFalse(any(tuple(p) == RED for p in col))
+ self.assertFalse(any(p[1] < ORANGE[1] for p in col))
+
+ def test_twenty_five_percent_bar_is_still_blue(self):
+ self.assertTrue(all(tuple(p) == BLUE for p in self._bar(25.0)))
+
+ def test_forty_percent_bar_has_bright_cyan_cream_tips(self):
+ col = self._bar(40.0)
+ self.assertEqual(tuple(col[len(col) // 2]), BLUE)
+ for tip in (col[0], col[-1]): # level 40 %: between cyan and cream
+ self.assertTrue(CYAN[0] < tip[0] < CREAM[0], tip)
+ self.assertTrue(CYAN[1] <= tip[1] <= CREAM[1], tip)
+ # no channel dip: red and green never decrease from the centre to the tip
+ half = col[len(col) // 2:]
+ self.assertTrue(all(a[0] <= b[0] and a[1] <= b[1] for a, b in zip(half, half[1:])))
+ self.assertTrue(all(p[1] >= BLUE[1] for p in col))
+
+ def test_full_bar_has_red_tips(self):
+ col = self._bar(100.0)
+ self.assertEqual(len(col), 48)
+ self.assertEqual(tuple(col[0]), RED)
+ self.assertEqual(tuple(col[-1]), RED)
+ self.assertEqual(tuple(col[24]), BLUE)
+
+ def test_low_bar_is_all_blue_and_gradient_is_symmetric(self):
+ col = self._bar(20.0)
+ self.assertTrue(all(tuple(p) == BLUE for p in col))
+ full = self._bar(100.0)
+ self.assertEqual(full.tolist(), full[::-1].tolist())
+ even = self._bar(80.0)
+ self.assertEqual(even.tolist(), even[::-1].tolist())
+
+
+class FakeSensors:
+ class Cpu:
+ @staticmethod
+ def percentage(interval):
+ return 12.5
+
+ class Memory:
+ @staticmethod
+ def virtual_percent():
+ return 40.0
+
+ class Gpu:
+ available = True
+ load = 33.0
+
+ @classmethod
+ def is_available(cls):
+ return cls.available
+
+ @classmethod
+ def stats(cls):
+ if isinstance(cls.load, Exception):
+ raise cls.load
+ return cls.load, 0, 0, 0, 0
+
+
+class TestSampler(unittest.TestCase):
+ def make(self, gpu_available=True, gpu_load=33.0):
+ sensors = type("S", (), dict(Cpu=FakeSensors.Cpu, Memory=FakeSensors.Memory,
+ Gpu=type("G", (FakeSensors.Gpu,), dict(available=gpu_available, load=gpu_load))))
+ return Sampler(["CPU", "GPU", "RAM"], 0.5, sensors)
+
+ def test_values(self):
+ self.assertEqual(self.make().sample(), [12.5, 33.0, 40.0])
+
+ def test_gpu_unavailable_is_none_and_logged_once(self):
+ s = self.make(gpu_available=False)
+ with mock.patch("library.video_face.sampler.logger") as log:
+ self.assertEqual(s.sample(), [12.5, None, 40.0])
+ self.assertEqual(s.sample(), [12.5, None, 40.0])
+ self.assertEqual(log.warning.call_count, 1)
+
+ def test_nan_and_errors_are_none(self):
+ self.assertEqual(self.make(gpu_load=math.nan).sample()[1], None)
+ s = self.make(gpu_load=RuntimeError("boom"))
+ with mock.patch("library.video_face.sampler.logger") as log:
+ self.assertIsNone(s.sample()[1])
+ self.assertIsNone(s.sample()[1])
+ self.assertEqual(log.warning.call_count, 1)
+
+ def test_history_is_bounded(self):
+ s = self.make()
+ for _ in range(40):
+ for h, v in zip(s.hist, s.sample()):
+ h.append(v)
+ self.assertTrue(all(len(h) == 26 for h in s.snapshot()))
+
+ def test_select_sensors(self):
+ self.assertTrue(select_sensors("STATIC").__name__.endswith("sensors_stub_static"))
+ self.assertTrue(select_sensors("stub").__name__.endswith("sensors_stub_random"))
+ with self.assertRaises(FatalError):
+ select_sensors("NOPE")
+
+
+class TestVideo(unittest.TestCase):
+ def test_cache_path_is_outside_the_source_tree(self):
+ p = video.cache_path(True)
+ self.assertNotIn(str(pathlib.Path(video.__file__).resolve().parent.parent.parent), str(p))
+ self.assertEqual(p.name, f"video_face_v{video.VIDEO_VERSION}_rev.mp4")
+ self.assertTrue(video.cache_path(False).name.endswith("_norev.mp4"))
+
+ def test_user_cache_dir_platforms(self):
+ with mock.patch.dict("os.environ", {"XDG_CACHE_HOME": "/xdg"}), mock.patch("os.name", "posix"), \
+ mock.patch("sys.platform", "linux"):
+ self.assertEqual(video.user_cache_dir(), pathlib.Path("/xdg/turing-smart-screen-python"))
+
+ def test_ffmpeg_missing_is_a_clear_error(self):
+ with mock.patch("shutil.which", return_value=None), self.assertRaises(FatalError) as ctx:
+ video.require_ffmpeg()
+ self.assertIn("ffmpeg", str(ctx.exception))
+
+ def fake_encoder(self, sizes):
+ calls = []
+
+ def encode(frames, out, reverse, crf, **kwargs):
+ calls.append(crf)
+ out.write_bytes(bytes(sizes[min(len(calls), len(sizes)) - 1]))
+
+ return encode, calls
+
+ def test_build_video_reencodes_until_it_fits(self):
+ enc, calls = self.fake_encoder([MAX_VIDEO_BYTES + 10, MAX_VIDEO_BYTES + 1, MAX_VIDEO_BYTES])
+ with tempfile.TemporaryDirectory() as d, mock.patch.object(video, "encode", enc), \
+ mock.patch.object(video, "iter_loop_frames", lambda: iter(())):
+ out = pathlib.Path(d) / "sub" / "v.mp4"
+ self.assertEqual(video.build_video(out, True), out)
+ self.assertEqual(out.stat().st_size, MAX_VIDEO_BYTES)
+ self.assertEqual(calls, list(video.CRF_LADDER[:3]))
+ self.assertEqual([p.name for p in out.parent.iterdir()], ["v.mp4"]) # no .tmp.mp4 left
+
+ def test_build_video_gives_up_without_leaving_files(self):
+ enc, calls = self.fake_encoder([MAX_VIDEO_BYTES + 1])
+ with tempfile.TemporaryDirectory() as d, mock.patch.object(video, "encode", enc), \
+ mock.patch.object(video, "iter_loop_frames", lambda: iter(())):
+ out = pathlib.Path(d) / "v.mp4"
+ with self.assertRaises(FatalError):
+ video.build_video(out, True)
+ self.assertEqual(calls, list(video.CRF_LADDER))
+ self.assertEqual(list(pathlib.Path(d).iterdir()), [])
+
+ def test_encode_failure_removes_partial_file(self):
+ def boom(frames, out, reverse, crf, **kwargs):
+ out.write_bytes(b"partial")
+ raise FatalError("ffmpeg failed")
+
+ with tempfile.TemporaryDirectory() as d, mock.patch.object(video, "encode", boom), \
+ mock.patch.object(video, "iter_loop_frames", lambda: iter(())):
+ with self.assertRaises(FatalError):
+ video.build_video(pathlib.Path(d) / "v.mp4", True)
+ self.assertEqual(list(pathlib.Path(d).iterdir()), [])
+
+ def test_ensure_video_reuses_a_fitting_cache_and_rebuilds_an_oversized_one(self):
+ with tempfile.TemporaryDirectory() as d:
+ out = pathlib.Path(d) / "v.mp4"
+ out.write_bytes(b"x" * 100)
+ with mock.patch.object(video, "build_video") as build:
+ self.assertEqual(video.ensure_video(True, out=out), out)
+ build.assert_not_called()
+ out.write_bytes(bytes(MAX_VIDEO_BYTES + 1))
+ video.ensure_video(True, out=out)
+ build.assert_called_once()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/video-face-rev-c.py b/video-face-rev-c.py
new file mode 100755
index 000000000..e341de7df
--- /dev/null
+++ b/video-face-rev-c.py
@@ -0,0 +1,31 @@
+#!/usr/bin/env python
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# turing-smart-screen-python - a Python system monitor and library for USB-C displays like Turing Smart Screen or XuanFang
+# https://github.com/mathoudebine/turing-smart-screen-python/
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see .
+
+# Animated video face for the 2.1" round rev C screen: see res/docs/rev-c-video-face.md
+
+from library.pythoncheck import check_python_version
+
+check_python_version()
+
+import sys
+
+from library.video_face.app import main
+
+if __name__ == "__main__":
+ sys.exit(main())