pyvisionect 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyvisionect/__init__.py +120 -0
- pyvisionect/devices/__init__.py +92 -0
- pyvisionect/devices/enums.py +403 -0
- pyvisionect/devices/panels.py +242 -0
- pyvisionect/devices/tclv.py +460 -0
- pyvisionect/imaging/README.md +175 -0
- pyvisionect/imaging/__init__.py +181 -0
- pyvisionect/imaging/checksum.py +114 -0
- pyvisionect/imaging/constants.py +131 -0
- pyvisionect/imaging/data/blue_noise_64.npy +0 -0
- pyvisionect/imaging/decode.py +172 -0
- pyvisionect/imaging/dither.py +357 -0
- pyvisionect/imaging/encoder.py +594 -0
- pyvisionect/imaging/geometry.py +129 -0
- pyvisionect/imaging/grey.py +104 -0
- pyvisionect/imaging/interlace.py +244 -0
- pyvisionect/imaging/pack.py +142 -0
- pyvisionect/imaging/panel.py +339 -0
- pyvisionect/imaging/partial.py +931 -0
- pyvisionect/imaging/rects.py +466 -0
- pyvisionect/io/__init__.py +33 -0
- pyvisionect/io/tcp.py +795 -0
- pyvisionect/io/usb/__init__.py +237 -0
- pyvisionect/io/usb/cli.py +278 -0
- pyvisionect/io/usb/commands.py +781 -0
- pyvisionect/io/usb/console.py +730 -0
- pyvisionect/io/usb/device.py +914 -0
- pyvisionect/io/usb/discovery.py +260 -0
- pyvisionect/io/usb/encryption.py +262 -0
- pyvisionect/io/usb/errors.py +175 -0
- pyvisionect/io/usb/fake.py +292 -0
- pyvisionect/io/usb/parsers.py +1464 -0
- pyvisionect/io/usb/provisioning.py +502 -0
- pyvisionect/packets/__init__.py +135 -0
- pyvisionect/packets/control.py +95 -0
- pyvisionect/packets/file.py +325 -0
- pyvisionect/packets/image.py +234 -0
- pyvisionect/packets/misc.py +202 -0
- pyvisionect/packets/param.py +284 -0
- pyvisionect/packets/status.py +518 -0
- pyvisionect/packets/stored.py +217 -0
- pyvisionect/py.typed +0 -0
- pyvisionect/session/__init__.py +100 -0
- pyvisionect/session/connection.py +1043 -0
- pyvisionect/session/device.py +587 -0
- pyvisionect/session/events.py +196 -0
- pyvisionect/session/filetransfer.py +251 -0
- pyvisionect/session/pending.py +425 -0
- pyvisionect/wire/__init__.py +91 -0
- pyvisionect/wire/blocks.py +350 -0
- pyvisionect/wire/checksum.py +115 -0
- pyvisionect/wire/errors.py +176 -0
- pyvisionect/wire/framing.py +334 -0
- pyvisionect-0.1.0.dist-info/METADATA +1030 -0
- pyvisionect-0.1.0.dist-info/RECORD +58 -0
- pyvisionect-0.1.0.dist-info/WHEEL +4 -0
- pyvisionect-0.1.0.dist-info/entry_points.txt +3 -0
- pyvisionect-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,594 @@
|
|
|
1
|
+
"""The imaging pipeline: image in, wire-ready rectangles + state tag out.
|
|
2
|
+
|
|
3
|
+
::
|
|
4
|
+
|
|
5
|
+
grey8 -> (Beautify) -> change-detect -> rect list -> merge/limit(<=15)
|
|
6
|
+
-> align to 16-bit quanta -> crop/rotate per display -> dither
|
|
7
|
+
-> bit-pack -> per-display interlace
|
|
8
|
+
|
|
9
|
+
Everything here is a pure function of its arguments. No I/O, no clock, no
|
|
10
|
+
global mutable state; the only module-level data are the dither matrices.
|
|
11
|
+
|
|
12
|
+
Spec references are to ``artifacts/visionect/02-imaging-framebuffer.md``.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import struct
|
|
18
|
+
import zlib
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import Any, Optional, Sequence
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
|
|
24
|
+
from . import dither as _dither
|
|
25
|
+
from . import pack as _pack
|
|
26
|
+
from .constants import (MAX_REGIONS_PER_DISPLAY, OPTION_NORMAL_UPDATE,
|
|
27
|
+
RECTANGLE_UPDATE_OPTIONS_DEFAULT, Dithering, Encoding,
|
|
28
|
+
ImageType)
|
|
29
|
+
from .checksum import state_checksum
|
|
30
|
+
from .geometry import (mirror_image, rotate_image, translate_to_real,
|
|
31
|
+
unrotate_image)
|
|
32
|
+
from .grey import beautify as _beautify
|
|
33
|
+
from .grey import to_grey8
|
|
34
|
+
from .interlace import interlace as _interlace
|
|
35
|
+
from .interlace import interlace_pairs
|
|
36
|
+
from .panel import Panel
|
|
37
|
+
from .rects import Rect, align_to_quantum, detect_changes, limit_regions
|
|
38
|
+
|
|
39
|
+
__all__ = ["EncodedRect", "EncodedFrame", "FrameState", "encode_frame"]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class EncodedRect:
|
|
44
|
+
"""One wire rectangle: a ``proto.RectangleHeader`` plus its payload.
|
|
45
|
+
|
|
46
|
+
Field names match ``RectangleHeader`` (spec §1.1) except that ``w``/``h``
|
|
47
|
+
are spelled short. All integers are already in range for their wire
|
|
48
|
+
widths (uint16, or uint32 for ``len(data)``).
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
x: int
|
|
52
|
+
y: int
|
|
53
|
+
w: int
|
|
54
|
+
h: int
|
|
55
|
+
screen_id: int
|
|
56
|
+
options: int
|
|
57
|
+
data: bytes
|
|
58
|
+
encoding: int = int(Encoding.FOUR_BIT)
|
|
59
|
+
image_type: int = int(ImageType.GRAY)
|
|
60
|
+
#: ``RectangleUpdateOptions``. Pre-filled with the encoding's default
|
|
61
|
+
#: (``0x0101`` / ``0x0102``) rather than left at 0 for the marshaller to
|
|
62
|
+
#: substitute (``packet/image.go:271-277``, spec §1.2). The captured
|
|
63
|
+
#: traffic shows ``0x0102``, so either route produces identical bytes.
|
|
64
|
+
rectangle_update_options: int = 0
|
|
65
|
+
#: The :class:`~pyvisionect.imaging.constants.Dithering` used. Informational;
|
|
66
|
+
#: it never reaches the wire (spec §3.3).
|
|
67
|
+
dithering: int = int(Dithering.NONE)
|
|
68
|
+
#: ``Reserved``; the vendor never writes anything but 0.
|
|
69
|
+
reserved: int = 0
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def payload_length(self) -> int:
|
|
73
|
+
return len(self.data)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class FrameState:
|
|
78
|
+
"""Opaque encoder state. Pass it back as ``prev_state`` on the next call.
|
|
79
|
+
|
|
80
|
+
:param state_grey: the server's 8-bit model of what the panel shows, in
|
|
81
|
+
**session-canvas** coordinates with ``stride == width`` -- Go's
|
|
82
|
+
``image.Gray.Pix`` for the canvas rectangle. This buffer, and nothing
|
|
83
|
+
else, is what the state checksum hashes (spec §6.1).
|
|
84
|
+
:param source_grey: the (post-Beautify) grey input of the last encode, kept
|
|
85
|
+
so that the next call can run change detection against it
|
|
86
|
+
(``canvas.go:411/445``).
|
|
87
|
+
:param checksum: the ``ImageHeader.Checksum`` that went with ``state_grey``.
|
|
88
|
+
:param encoding: encoding of the last encode; a change forces full screen
|
|
89
|
+
(``image-state.go:757-764``).
|
|
90
|
+
:param dithering: likewise for the dithering mode.
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
state_grey: np.ndarray
|
|
94
|
+
source_grey: np.ndarray
|
|
95
|
+
checksum: int
|
|
96
|
+
encoding: int
|
|
97
|
+
dithering: int
|
|
98
|
+
|
|
99
|
+
def __post_init__(self) -> None:
|
|
100
|
+
object.__setattr__(self, "state_grey",
|
|
101
|
+
np.ascontiguousarray(self.state_grey, dtype=np.uint8))
|
|
102
|
+
object.__setattr__(self, "source_grey",
|
|
103
|
+
np.ascontiguousarray(self.source_grey, dtype=np.uint8))
|
|
104
|
+
|
|
105
|
+
# ---- persistence ---------------------------------------------------
|
|
106
|
+
#
|
|
107
|
+
# Persisting this across a restart is the difference between a free restart
|
|
108
|
+
# and a full-screen 1.84 MB push plus one unit of panel wear, every restart,
|
|
109
|
+
# on a battery device. E-ink is persistent: if the device's echoed
|
|
110
|
+
# ``DisplayStateCRC`` still matches the checksum we stored, the right
|
|
111
|
+
# behaviour on first contact is to do nothing at all.
|
|
112
|
+
#
|
|
113
|
+
# The format is owned here, deliberately, so that adding a field to
|
|
114
|
+
# FrameState is not a breaking change for everyone who persisted one.
|
|
115
|
+
|
|
116
|
+
SERIAL_MAGIC = b"VNFS"
|
|
117
|
+
SERIAL_VERSION = 1
|
|
118
|
+
_SERIAL_HEADER = struct.Struct("<4sBBBBI2I2I2I")
|
|
119
|
+
|
|
120
|
+
def to_bytes(self, *, compress: bool = True) -> bytes:
|
|
121
|
+
"""Serialise to a self-describing, versioned blob.
|
|
122
|
+
|
|
123
|
+
Both grey planes are zlib-deflated by default, which matters: real
|
|
124
|
+
e-ink content is mostly flat white and compresses enormously, so a
|
|
125
|
+
1440x2560 state usually lands in tens of kilobytes rather than 3.7 MB.
|
|
126
|
+
|
|
127
|
+
:param compress: set False to store the planes raw, e.g. if the
|
|
128
|
+
consumer's own store already compresses.
|
|
129
|
+
:returns: bytes safe to hand straight back to :meth:`from_bytes`.
|
|
130
|
+
"""
|
|
131
|
+
state = bytes(self.state_grey.tobytes())
|
|
132
|
+
source = bytes(self.source_grey.tobytes())
|
|
133
|
+
if compress:
|
|
134
|
+
state = zlib.compress(state, 6)
|
|
135
|
+
source = zlib.compress(source, 6)
|
|
136
|
+
header = self._SERIAL_HEADER.pack(
|
|
137
|
+
self.SERIAL_MAGIC,
|
|
138
|
+
self.SERIAL_VERSION,
|
|
139
|
+
1 if compress else 0,
|
|
140
|
+
int(self.encoding) & 0xFF,
|
|
141
|
+
int(self.dithering) & 0xFF,
|
|
142
|
+
int(self.checksum) & 0xFFFFFFFF,
|
|
143
|
+
int(self.state_grey.shape[0]), int(self.state_grey.shape[1]),
|
|
144
|
+
int(self.source_grey.shape[0]), int(self.source_grey.shape[1]),
|
|
145
|
+
len(state), len(source),
|
|
146
|
+
)
|
|
147
|
+
return header + state + source
|
|
148
|
+
|
|
149
|
+
@classmethod
|
|
150
|
+
def from_bytes(cls, raw: bytes) -> "FrameState":
|
|
151
|
+
"""Restore a :class:`FrameState` written by :meth:`to_bytes`.
|
|
152
|
+
|
|
153
|
+
:raises ValueError: on a bad magic, an unknown version, or a truncated
|
|
154
|
+
blob. A future version raises rather than mis-restoring: the
|
|
155
|
+
correct recovery is to discard the blob and push a full frame once,
|
|
156
|
+
not to guess.
|
|
157
|
+
"""
|
|
158
|
+
size = cls._SERIAL_HEADER.size
|
|
159
|
+
if len(raw) < size:
|
|
160
|
+
raise ValueError(
|
|
161
|
+
f"FrameState blob is {len(raw)} bytes, need at least {size}"
|
|
162
|
+
)
|
|
163
|
+
(magic, version, flags, encoding, dithering, checksum,
|
|
164
|
+
state_h, state_w, source_h, source_w,
|
|
165
|
+
state_len, source_len) = cls._SERIAL_HEADER.unpack_from(raw, 0)
|
|
166
|
+
if magic != cls.SERIAL_MAGIC:
|
|
167
|
+
raise ValueError(
|
|
168
|
+
f"not a FrameState blob: magic {magic!r} != {cls.SERIAL_MAGIC!r}"
|
|
169
|
+
)
|
|
170
|
+
if version != cls.SERIAL_VERSION:
|
|
171
|
+
raise ValueError(
|
|
172
|
+
f"FrameState blob version {version} is not {cls.SERIAL_VERSION}; "
|
|
173
|
+
"discard it and push a full frame instead of guessing"
|
|
174
|
+
)
|
|
175
|
+
if len(raw) != size + state_len + source_len:
|
|
176
|
+
raise ValueError(
|
|
177
|
+
f"FrameState blob is {len(raw)} bytes, header describes "
|
|
178
|
+
f"{size + state_len + source_len}"
|
|
179
|
+
)
|
|
180
|
+
state = raw[size:size + state_len]
|
|
181
|
+
source = raw[size + state_len:]
|
|
182
|
+
if flags & 1:
|
|
183
|
+
state = zlib.decompress(state)
|
|
184
|
+
source = zlib.decompress(source)
|
|
185
|
+
expected = (state_h * state_w, source_h * source_w)
|
|
186
|
+
if (len(state), len(source)) != expected:
|
|
187
|
+
raise ValueError(
|
|
188
|
+
f"FrameState planes are {(len(state), len(source))} bytes, "
|
|
189
|
+
f"shapes describe {expected}"
|
|
190
|
+
)
|
|
191
|
+
return cls(
|
|
192
|
+
state_grey=np.frombuffer(state, dtype=np.uint8).reshape(state_h, state_w),
|
|
193
|
+
source_grey=np.frombuffer(source, dtype=np.uint8).reshape(
|
|
194
|
+
source_h, source_w
|
|
195
|
+
),
|
|
196
|
+
checksum=int(checksum),
|
|
197
|
+
encoding=int(encoding),
|
|
198
|
+
dithering=int(dithering),
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@dataclass
|
|
203
|
+
class EncodedFrame:
|
|
204
|
+
"""Result of :func:`encode_frame`.
|
|
205
|
+
|
|
206
|
+
:param rectangles: the rectangles to put in the ``ImagePacket``, in wire
|
|
207
|
+
order. **Empty** means "nothing changed, send no packet".
|
|
208
|
+
:param state_checksum: ``ImageHeader.Checksum`` -- XXHash32(seed 0) of the
|
|
209
|
+
8-bit state image, ``0`` remapped to ``1`` (spec §6.1). Send it in
|
|
210
|
+
every ``ImagePacket``; the device echoes it back as
|
|
211
|
+
``DisplayStateCRC``, and a mismatch costs one redundant full-screen
|
|
212
|
+
redraw.
|
|
213
|
+
:param state: opaque; pass back as ``prev_state`` next call.
|
|
214
|
+
:param full_screen: whether this frame covers every display in full. The
|
|
215
|
+
caller needs it for the inverse-update rule (spec §1.4) and for the
|
|
216
|
+
``noFullUpdateCnt`` budget (spec §1.8).
|
|
217
|
+
:param screen_space: whether ``rectangles`` are addressed in **screen**
|
|
218
|
+
coordinates (one physical panel channel, 2880 wide on the 32" sign)
|
|
219
|
+
rather than in display-local ones. Only
|
|
220
|
+
:func:`~pyvisionect.imaging.partial.encode_partial_frame` sets this.
|
|
221
|
+
It changes nothing about how the packet is marshalled -- a
|
|
222
|
+
``RectangleHeader`` has always been screen-addressed -- but it tells a
|
|
223
|
+
decoder that ``w`` is *not* twice a logical display's width by
|
|
224
|
+
accident.
|
|
225
|
+
:param fallback_reason: when a partial update was asked for and a
|
|
226
|
+
full-screen one came back, the reason, in a short stable string.
|
|
227
|
+
``None`` when nothing was downgraded.
|
|
228
|
+
:param dirty_rects: the **canvas**-space dirty rectangles this frame was
|
|
229
|
+
built from, for logging and tests. Empty on a frame that was always
|
|
230
|
+
going to be full-screen.
|
|
231
|
+
"""
|
|
232
|
+
|
|
233
|
+
rectangles: list[EncodedRect]
|
|
234
|
+
state_checksum: int
|
|
235
|
+
state: FrameState
|
|
236
|
+
full_screen: bool = False
|
|
237
|
+
screen_space: bool = False
|
|
238
|
+
fallback_reason: Optional[str] = None
|
|
239
|
+
dirty_rects: tuple[Rect, ...] = ()
|
|
240
|
+
|
|
241
|
+
#: ``ImageHeader.NrPrimitives`` (``image-state.go:1535``).
|
|
242
|
+
@property
|
|
243
|
+
def nr_primitives(self) -> int:
|
|
244
|
+
return len(self.rectangles)
|
|
245
|
+
|
|
246
|
+
@property
|
|
247
|
+
def payload_length(self) -> int:
|
|
248
|
+
"""``ImageHeader.PayloadLength``: bytes after the 20-byte header."""
|
|
249
|
+
return sum(24 + len(r.data) for r in self.rectangles)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _validate(encoding: int, dithering: int, panel: Panel) -> tuple[int, int]:
|
|
253
|
+
enc = int(encoding)
|
|
254
|
+
if enc not in (int(Encoding.ONE_BIT), int(Encoding.FOUR_BIT)):
|
|
255
|
+
raise ValueError(
|
|
256
|
+
f"bad encoding {encoding!r}: only 1 (1 bpp, 2 levels) and 4 "
|
|
257
|
+
"(4 bpp, 16 levels) exist; 0 is 'undefined' and anything else is "
|
|
258
|
+
"'unknown' (spec §2.1)"
|
|
259
|
+
)
|
|
260
|
+
dith = int(dithering)
|
|
261
|
+
if dith == int(Dithering.DEFAULT):
|
|
262
|
+
raise ValueError(
|
|
263
|
+
"DitheringType 0 ('default') is invalid at the encoder; the vendor "
|
|
264
|
+
"rejects it with render.ErrDithering (image-state.go:754). Pass "
|
|
265
|
+
"1 (none), 2 (bayer), 3 (floyd-steinberg) or 4 (blue-noise)."
|
|
266
|
+
)
|
|
267
|
+
if dith not in (1, 2, 3, 4):
|
|
268
|
+
raise ValueError(
|
|
269
|
+
f"unknown DitheringType {dithering!r}; known values are 1 none, "
|
|
270
|
+
"2 bayer, 3 floyd-steinberg, 4 blue-noise (library extension)"
|
|
271
|
+
)
|
|
272
|
+
if panel.driver.color_mask:
|
|
273
|
+
raise NotImplementedError(
|
|
274
|
+
"colour-mask drivers (eink-32-inch-color-mask*) remap through a "
|
|
275
|
+
"palette image (imgproc.GmMapImage, spec §3.2) and are not "
|
|
276
|
+
"implemented; this module only handles the greyscale path"
|
|
277
|
+
)
|
|
278
|
+
return enc, dith
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def encode_frame(
|
|
282
|
+
img: Any,
|
|
283
|
+
*,
|
|
284
|
+
panel: Panel,
|
|
285
|
+
encoding: int,
|
|
286
|
+
dithering: int,
|
|
287
|
+
rects: Optional[Sequence[Rect]] = None,
|
|
288
|
+
prev_state: Optional[FrameState] = None,
|
|
289
|
+
inverse: bool = False,
|
|
290
|
+
rect_options: int = 0,
|
|
291
|
+
image_type: int = int(ImageType.GRAY),
|
|
292
|
+
rectangle_update_options: Optional[int] = None,
|
|
293
|
+
change_threshold: float = 0.0,
|
|
294
|
+
merge_regions: bool = True,
|
|
295
|
+
max_regions: int = MAX_REGIONS_PER_DISPLAY,
|
|
296
|
+
force_full_screen: bool = False,
|
|
297
|
+
beautify: bool = False,
|
|
298
|
+
beautify_gamma: float = 1.1,
|
|
299
|
+
bayer_matrix: Optional[np.ndarray] = None,
|
|
300
|
+
blue_noise_matrix: Optional[np.ndarray] = None,
|
|
301
|
+
dither_levels: Optional[int] = None,
|
|
302
|
+
partial: bool = False,
|
|
303
|
+
partial_policy: Any = None,
|
|
304
|
+
consecutive_partials: int = 0,
|
|
305
|
+
) -> EncodedFrame:
|
|
306
|
+
"""Encode one frame into wire-ready rectangles and a state checksum.
|
|
307
|
+
|
|
308
|
+
.. warning:: **This is CPU-bound and blocking, and it releases no locks.**
|
|
309
|
+
A 1440x2560 canvas goes through grey conversion, change detection,
|
|
310
|
+
dithering (Floyd-Steinberg is inherently serial), bit packing, 4-pixel
|
|
311
|
+
interlacing and LZ4 -- comfortably hundreds of milliseconds on a desktop
|
|
312
|
+
and plausibly seconds on a Raspberry Pi. **Never call it on an asyncio
|
|
313
|
+
event loop.** In Home Assistant, use
|
|
314
|
+
``hass.async_add_executor_job``; elsewhere,
|
|
315
|
+
``loop.run_in_executor(None, ...)`` or a thread. Running it on the loop
|
|
316
|
+
stalls everything else for the duration, which presents as "the whole
|
|
317
|
+
instance freezes every hour".
|
|
318
|
+
|
|
319
|
+
:param img: a PIL image or a numpy array; anything
|
|
320
|
+
:func:`~pyvisionect.imaging.grey.to_grey8` accepts. Its size must be
|
|
321
|
+
the panel's session canvas (``panel.canvas_width x
|
|
322
|
+
panel.canvas_height``).
|
|
323
|
+
:param panel: an imaging :class:`~pyvisionect.imaging.panel.Panel`, or
|
|
324
|
+
anything :meth:`~pyvisionect.imaging.panel.Panel.adapt` accepts --
|
|
325
|
+
including a :class:`pyvisionect.devices.panels.Panel` from
|
|
326
|
+
``devices.panel_for(display_type)``.
|
|
327
|
+
:param encoding: ``1`` or ``4``. Nothing else exists (spec §2.1).
|
|
328
|
+
:param dithering: a :class:`~pyvisionect.imaging.constants.Dithering`
|
|
329
|
+
value. ``0`` is rejected. ``4`` (blue-noise) is a library extension
|
|
330
|
+
and is safe because the mode never reaches the wire (spec §3.3).
|
|
331
|
+
:param rects: dirty rectangles in **canvas** coordinates. ``None`` means
|
|
332
|
+
"derive them": change-detect against ``prev_state`` if there is one,
|
|
333
|
+
else full screen.
|
|
334
|
+
:param prev_state: the :class:`FrameState` from the previous call.
|
|
335
|
+
:param inverse: request an inverse / ghost-clearing refresh by **clearing**
|
|
336
|
+
``RectangleHeader.Options`` bit ``0x0002`` on every rectangle (spec
|
|
337
|
+
§1.4, §5). Only legal on a full-screen frame, which it forces.
|
|
338
|
+
|
|
339
|
+
.. note:: **[INFERRED]**
|
|
340
|
+
The server-side bit manipulation
|
|
341
|
+
(``image-state.go:1519-1522``) is verified; the *firmware's
|
|
342
|
+
reaction* to a cleared bit 1 is not. With the shipped
|
|
343
|
+
``RectangleFlags = 0`` the bit is already clear, so on a stock
|
|
344
|
+
deployment this signalling is a no-op on the wire -- to use it you
|
|
345
|
+
must pass ``rect_options`` with bit 1 **set**.
|
|
346
|
+
:param rect_options: ``Config.Engine.RectangleFlags`` ->
|
|
347
|
+
``RectangleHeader.Options`` (spec §1.4). The server only ever copies
|
|
348
|
+
it, except for the one bit ``inverse`` clears.
|
|
349
|
+
:param rectangle_update_options: override ``RectangleUpdateOptions``.
|
|
350
|
+
``None`` uses the encoding's marshal-time default, ``0x0101`` (1 bpp)
|
|
351
|
+
or ``0x0102`` (4 bpp) -- spec §1.2. Pass ``0`` to leave the
|
|
352
|
+
substitution to the packet marshaller instead.
|
|
353
|
+
:param change_threshold: per-pixel absolute grey difference for change
|
|
354
|
+
detection; the vendor's default is ``0``, meaning *any* difference
|
|
355
|
+
counts (spec §4.2).
|
|
356
|
+
:param merge_regions: ``MergeRegions.Enable``. When false and a display
|
|
357
|
+
has more than ``max_regions`` dirty rectangles, the frame is promoted
|
|
358
|
+
to full screen (``image-state.go:241``).
|
|
359
|
+
:param force_full_screen: skip change detection and repaint everything.
|
|
360
|
+
:param beautify: run the auto-levels + gamma stage (spec §4.3). **Off by
|
|
361
|
+
default**: it would undo a renderer that already quantised to the
|
|
362
|
+
output ramp.
|
|
363
|
+
:param bayer_matrix: threshold matrix overriding the built-in 8x8 Bayer.
|
|
364
|
+
:param blue_noise_matrix: threshold matrix overriding the shipped 64x64
|
|
365
|
+
void-and-cluster matrix -- drop in the exact matrix your renderer uses
|
|
366
|
+
to get identical output.
|
|
367
|
+
:param dither_levels: force a level count (e.g. ``16`` to make ``bayer``
|
|
368
|
+
multi-level at 4 bpp instead of the vendor's bi-level degeneration).
|
|
369
|
+
:param partial: **opt-in, per-device, not vendor-sanctioned.** Encode the
|
|
370
|
+
dirty region only, as screen-space rectangles, by delegating to
|
|
371
|
+
:func:`pyvisionect.imaging.partial.encode_partial_frame`. Off by
|
|
372
|
+
default, and with it off this function behaves exactly as it did
|
|
373
|
+
before this parameter existed.
|
|
374
|
+
|
|
375
|
+
.. warning::
|
|
376
|
+
Partial updates were verified by hand on **one** device --
|
|
377
|
+
``HardwareNameID 8``-class hardware, the 31.2" Place&Play 32,
|
|
378
|
+
firmware 7.4.4407, hardware revision 1.1.0, on 2026-10-05
|
|
379
|
+
(``OPEN-QUESTIONS.md`` A10). The vendor's own server never sends
|
|
380
|
+
this hardware a partial rectangle (``getRectangleSupport`` is false
|
|
381
|
+
for it unconditionally), so there is no vendor behaviour to match
|
|
382
|
+
and no vendor support to fall back on. It saves **bytes and encode
|
|
383
|
+
time, not refresh latency**: the panel's waveform floor is ~2.9 s
|
|
384
|
+
whatever the rectangle's area.
|
|
385
|
+
:param partial_policy: a
|
|
386
|
+
:class:`pyvisionect.imaging.partial.PartialPolicy`, or ``None`` for
|
|
387
|
+
the default. Only consulted when ``partial`` is true.
|
|
388
|
+
:param consecutive_partials: how many partial frames have gone out since
|
|
389
|
+
the last full-screen one, for the ghosting budget. Only consulted
|
|
390
|
+
when ``partial`` is true; past
|
|
391
|
+
``partial_policy.max_consecutive_partials`` the frame is promoted to
|
|
392
|
+
full screen. :class:`pyvisionect.imaging.partial.DirtyTracker` keeps
|
|
393
|
+
this counter for you.
|
|
394
|
+
|
|
395
|
+
:returns: an :class:`EncodedFrame`. ``rectangles`` is empty when nothing
|
|
396
|
+
changed.
|
|
397
|
+
"""
|
|
398
|
+
if partial:
|
|
399
|
+
from .partial import encode_partial_frame
|
|
400
|
+
|
|
401
|
+
return encode_partial_frame(
|
|
402
|
+
img, panel=panel, encoding=encoding, dithering=dithering,
|
|
403
|
+
rects=rects, prev_state=prev_state, inverse=inverse,
|
|
404
|
+
rect_options=rect_options, image_type=image_type,
|
|
405
|
+
rectangle_update_options=rectangle_update_options,
|
|
406
|
+
change_threshold=change_threshold, merge_regions=merge_regions,
|
|
407
|
+
max_regions=max_regions,
|
|
408
|
+
force_full_screen=force_full_screen, beautify=beautify,
|
|
409
|
+
beautify_gamma=beautify_gamma, bayer_matrix=bayer_matrix,
|
|
410
|
+
blue_noise_matrix=blue_noise_matrix, dither_levels=dither_levels,
|
|
411
|
+
policy=partial_policy, consecutive_partials=consecutive_partials,
|
|
412
|
+
)
|
|
413
|
+
panel = Panel.adapt(panel)
|
|
414
|
+
enc, dith = _validate(encoding, dithering, panel)
|
|
415
|
+
grey = to_grey8(img)
|
|
416
|
+
if grey.shape != panel.canvas_shape:
|
|
417
|
+
raise ValueError(
|
|
418
|
+
f"image is {grey.shape[1]}x{grey.shape[0]} but panel canvas is "
|
|
419
|
+
f"{panel.canvas_width}x{panel.canvas_height} "
|
|
420
|
+
f"({panel.displays} displays of {panel.width}x{panel.height})"
|
|
421
|
+
)
|
|
422
|
+
if beautify:
|
|
423
|
+
grey = _beautify(grey, gamma=beautify_gamma)
|
|
424
|
+
|
|
425
|
+
geometry = panel.geometry()
|
|
426
|
+
canvas = Rect(0, 0, panel.canvas_width, panel.canvas_height)
|
|
427
|
+
|
|
428
|
+
# ---- 1. decide what to repaint -------------------------------------
|
|
429
|
+
#
|
|
430
|
+
# `panel.forces_full_screen` is not a shortcut: on HardwareNameID 8
|
|
431
|
+
# getRectangleSupport() is false unconditionally, and structurally the
|
|
432
|
+
# interlacer needs all four full-size display rectangles (spec §1.6/§1.7).
|
|
433
|
+
reencode = prev_state is not None and (prev_state.encoding != enc
|
|
434
|
+
or prev_state.dithering != dith)
|
|
435
|
+
full_screen = bool(
|
|
436
|
+
force_full_screen
|
|
437
|
+
or inverse
|
|
438
|
+
or prev_state is None
|
|
439
|
+
or panel.forces_full_screen
|
|
440
|
+
or reencode
|
|
441
|
+
)
|
|
442
|
+
if full_screen:
|
|
443
|
+
dirty: list[Rect] = [canvas]
|
|
444
|
+
elif rects is not None:
|
|
445
|
+
dirty = [r for r in (c.intersection(canvas) for c in rects) if r is not None]
|
|
446
|
+
else:
|
|
447
|
+
dirty = detect_changes(grey, prev_state.source_grey, change_threshold)
|
|
448
|
+
|
|
449
|
+
if not dirty:
|
|
450
|
+
assert prev_state is not None
|
|
451
|
+
return EncodedFrame(
|
|
452
|
+
rectangles=[],
|
|
453
|
+
state_checksum=prev_state.checksum,
|
|
454
|
+
state=FrameState(prev_state.state_grey, grey, prev_state.checksum,
|
|
455
|
+
enc, dith),
|
|
456
|
+
full_screen=False,
|
|
457
|
+
)
|
|
458
|
+
|
|
459
|
+
# ---- 2. canvas-wide quantisation for the pixel-local dithers --------
|
|
460
|
+
#
|
|
461
|
+
# Ordered dithers are phased on the *canvas* coordinate, so a rectangle's
|
|
462
|
+
# pixels are identical whether it is encoded alone or as part of a bigger
|
|
463
|
+
# one. That is what keeps partial updates from seaming. Floyd-Steinberg
|
|
464
|
+
# is not pixel-local and is therefore done per rectangle, below.
|
|
465
|
+
pixel_local = _dither.is_pixel_local(dith)
|
|
466
|
+
quant_canvas: Optional[np.ndarray] = None
|
|
467
|
+
if pixel_local:
|
|
468
|
+
quant_canvas = _dither.quantise(
|
|
469
|
+
grey, enc, dith, origin=(0, 0), bayer=bayer_matrix,
|
|
470
|
+
blue_noise=blue_noise_matrix, levels=dither_levels,
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
# ---- 3. per display: clip, merge, align, cut, rotate, mirror, pack ---
|
|
474
|
+
state = (np.zeros(panel.canvas_shape, dtype=np.uint8) if prev_state is None
|
|
475
|
+
else prev_state.state_grey.copy())
|
|
476
|
+
ruo = (RECTANGLE_UPDATE_OPTIONS_DEFAULT[enc] if rectangle_update_options is None
|
|
477
|
+
else int(rectangle_update_options))
|
|
478
|
+
options = int(rect_options) & ~OPTION_NORMAL_UPDATE if inverse else int(rect_options)
|
|
479
|
+
|
|
480
|
+
per_display: list[list[EncodedRect]] = []
|
|
481
|
+
for display in geometry:
|
|
482
|
+
area = Rect(display.x, display.y, display.rotated_width, display.rotated_height)
|
|
483
|
+
clipped = [r for r in (d.intersection(area) for d in dirty) if r is not None]
|
|
484
|
+
if not clipped:
|
|
485
|
+
per_display.append([])
|
|
486
|
+
continue
|
|
487
|
+
|
|
488
|
+
merged = limit_regions(clipped, display.width, display.height,
|
|
489
|
+
merge=merge_regions, max_regions=max_regions)
|
|
490
|
+
if merged is None:
|
|
491
|
+
# ``forceFullScreenUnlocked`` -- restart the whole frame as a
|
|
492
|
+
# full-screen one rather than emit an inconsistent mix.
|
|
493
|
+
return encode_frame(
|
|
494
|
+
img, panel=panel, encoding=enc, dithering=dith, rects=None,
|
|
495
|
+
prev_state=prev_state, inverse=inverse,
|
|
496
|
+
rect_options=rect_options, image_type=image_type,
|
|
497
|
+
rectangle_update_options=rectangle_update_options,
|
|
498
|
+
change_threshold=change_threshold, merge_regions=merge_regions,
|
|
499
|
+
max_regions=max_regions, force_full_screen=True,
|
|
500
|
+
beautify=beautify, beautify_gamma=beautify_gamma,
|
|
501
|
+
bayer_matrix=bayer_matrix, blue_noise_matrix=blue_noise_matrix,
|
|
502
|
+
dither_levels=dither_levels,
|
|
503
|
+
)
|
|
504
|
+
aligned = [align_to_quantum(r, enc, area) for r in merged]
|
|
505
|
+
|
|
506
|
+
out: list[EncodedRect] = []
|
|
507
|
+
for session_rect in aligned:
|
|
508
|
+
local = translate_to_real(session_rect, display)
|
|
509
|
+
rows, cols = session_rect.as_slice()
|
|
510
|
+
if pixel_local:
|
|
511
|
+
assert quant_canvas is not None
|
|
512
|
+
tile = quant_canvas[rows, cols]
|
|
513
|
+
else:
|
|
514
|
+
tile = grey[rows, cols]
|
|
515
|
+
tile = rotate_image(tile, display.rotation)
|
|
516
|
+
if panel.driver.mirror:
|
|
517
|
+
tile = mirror_image(tile)
|
|
518
|
+
if not pixel_local:
|
|
519
|
+
tile = _dither.quantise(tile, enc, dith, levels=dither_levels)
|
|
520
|
+
tile = np.ascontiguousarray(tile)
|
|
521
|
+
|
|
522
|
+
# The state image models the panel in *session* coordinates, so
|
|
523
|
+
# undo the mirror and the rotation on the quantised pixels. For
|
|
524
|
+
# Floyd-Steinberg that matters: the dither ran on the mirrored
|
|
525
|
+
# tile, and the state has to record what the panel will actually
|
|
526
|
+
# show, not a re-dither of the unmirrored tile.
|
|
527
|
+
back = mirror_image(tile) if panel.driver.mirror else tile
|
|
528
|
+
state[rows, cols] = unrotate_image(back, display.rotation)
|
|
529
|
+
|
|
530
|
+
out.append(EncodedRect(
|
|
531
|
+
x=local.x, y=local.y, w=local.width, h=local.height,
|
|
532
|
+
screen_id=display.id, options=options,
|
|
533
|
+
data=_pack.pack(tile, enc),
|
|
534
|
+
encoding=enc, image_type=int(image_type),
|
|
535
|
+
rectangle_update_options=ruo, dithering=dith,
|
|
536
|
+
))
|
|
537
|
+
per_display.append(out)
|
|
538
|
+
|
|
539
|
+
# ---- 4. transmit-side interlacing (spec §1.6) ----------------------
|
|
540
|
+
if panel.interlace_mode:
|
|
541
|
+
flat = _interlace_displays(per_display, panel, enc, options, ruo,
|
|
542
|
+
int(image_type), dith)
|
|
543
|
+
else:
|
|
544
|
+
flat = [r for lst in per_display for r in lst]
|
|
545
|
+
|
|
546
|
+
checksum = state_checksum(np.ascontiguousarray(state).tobytes())
|
|
547
|
+
return EncodedFrame(
|
|
548
|
+
rectangles=flat,
|
|
549
|
+
state_checksum=checksum,
|
|
550
|
+
state=FrameState(state, grey, checksum, enc, dith),
|
|
551
|
+
full_screen=full_screen,
|
|
552
|
+
)
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _interlace_displays(per_display: list[list[EncodedRect]], panel: Panel,
|
|
556
|
+
encoding: int, options: int, ruo: int,
|
|
557
|
+
image_type: int, dithering: int) -> list[EncodedRect]:
|
|
558
|
+
"""Fold N full-size display rectangles into the physical channels.
|
|
559
|
+
|
|
560
|
+
``main.interlacingHack`` (``image_interlacing.go:105-188``) requires
|
|
561
|
+
*exactly* four rectangles, each the full ``1440 x 640``, all with the same
|
|
562
|
+
encoding; anything else is passed through untouched (``:112-118``). Since
|
|
563
|
+
this hardware also has ``RectangleSupport == false``, that precondition is
|
|
564
|
+
always met here -- but we re-check it rather than assume.
|
|
565
|
+
"""
|
|
566
|
+
pairs = interlace_pairs(panel.interlace_mode)
|
|
567
|
+
if len(per_display) != panel.displays or any(len(rs) != 1 for rs in per_display):
|
|
568
|
+
raise ValueError(
|
|
569
|
+
"interlacing needs exactly one full-size rectangle per display "
|
|
570
|
+
f"(got {[len(rs) for rs in per_display]}); a partial update cannot be "
|
|
571
|
+
"interlaced, which is why RectangleSupport is false on this "
|
|
572
|
+
"hardware (spec §1.6/§1.7)"
|
|
573
|
+
)
|
|
574
|
+
singles = [rs[0] for rs in per_display]
|
|
575
|
+
if any(r.w != panel.width or r.h != panel.height for r in singles):
|
|
576
|
+
raise ValueError(
|
|
577
|
+
f"interlacing needs {panel.width}x{panel.height} rectangles, got "
|
|
578
|
+
f"{[(r.w, r.h) for r in singles]}"
|
|
579
|
+
)
|
|
580
|
+
|
|
581
|
+
out: list[EncodedRect] = []
|
|
582
|
+
for screen_id, (lane_a, lane_b) in pairs:
|
|
583
|
+
a, b = singles[lane_a], singles[lane_b]
|
|
584
|
+
out.append(EncodedRect(
|
|
585
|
+
# ``interlacingHack`` copies one of the pair and only doubles
|
|
586
|
+
# ``Width`` (:177-180); X/Y are the display-local 0,0 of a
|
|
587
|
+
# full-screen rectangle.
|
|
588
|
+
x=a.x, y=a.y, w=a.w * 2, h=a.h,
|
|
589
|
+
screen_id=screen_id, options=options,
|
|
590
|
+
data=_interlace(a.data, b.data, encoding),
|
|
591
|
+
encoding=encoding, image_type=image_type,
|
|
592
|
+
rectangle_update_options=ruo, dithering=dithering,
|
|
593
|
+
))
|
|
594
|
+
return out
|