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,129 @@
|
|
|
1
|
+
"""Session-canvas <-> display-local coordinate translation. Spec §1.5.
|
|
2
|
+
|
|
3
|
+
``Display.RectangleTranslateToReal`` (``display-translations.go:246``) takes a
|
|
4
|
+
rectangle in *session/canvas* coordinates and produces a *display-local,
|
|
5
|
+
rotation-applied* rectangle stamped with that display's ``ScreenID``::
|
|
6
|
+
|
|
7
|
+
Wd, Hd = display.DimensionsRotated()
|
|
8
|
+
rctX = clamp(in.X, display.X, display.X+Wd)
|
|
9
|
+
rctY = clamp(in.Y, display.Y, display.Y+Hd)
|
|
10
|
+
rctFarX = clamp(in.X+in.Width, rctX, display.X+Wd)
|
|
11
|
+
rctFarY = clamp(in.Y+in.Height, rctY, display.Y+Hd)
|
|
12
|
+
if rctFarX <= rctX || rctFarY <= rctY: error "rectangle is not for this display"
|
|
13
|
+
Xd, Yd = rctX-display.X, rctY-display.Y
|
|
14
|
+
switch rotation {
|
|
15
|
+
case 0: out.X, out.Y = Xd, Yd
|
|
16
|
+
case 1: out.X, out.Y = Hd-Yd-h, Xd ; out.W, out.H = h, w
|
|
17
|
+
case 2: out.X, out.Y = Wd-Xd-w, Hd-Yd-h
|
|
18
|
+
case 3: out.X, out.Y = Yd, Wd-Xd-w ; out.W, out.H = h, w
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
.. note::
|
|
22
|
+
Only ``rotation == 0`` is verified against real captured traffic (our sign
|
|
23
|
+
runs it). 1/2/3 implement the formulas above and are covered by
|
|
24
|
+
round-trip tests against :func:`translate_to_session`, but no rotated
|
|
25
|
+
hardware was available.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import numpy as np
|
|
31
|
+
|
|
32
|
+
from .panel import DisplayGeometry
|
|
33
|
+
from .rects import Rect
|
|
34
|
+
|
|
35
|
+
__all__ = ["translate_to_real", "translate_to_session", "rotate_image",
|
|
36
|
+
"unrotate_image", "mirror_image"]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _clamp(v: int, lo: int, hi: int) -> int:
|
|
40
|
+
return lo if v < lo else (hi if v > hi else v)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def translate_to_real(rect: Rect, display: DisplayGeometry) -> Rect:
|
|
44
|
+
"""Canvas rectangle -> display-local, rotation-applied rectangle.
|
|
45
|
+
|
|
46
|
+
:raises ValueError: if the rectangle does not intersect this display
|
|
47
|
+
(the vendor logs ``"rectangle is outside of this display"`` and
|
|
48
|
+
returns ``errors.New("rectangle is not for this display")``).
|
|
49
|
+
"""
|
|
50
|
+
wd, hd = display.rotated_width, display.rotated_height
|
|
51
|
+
x0 = _clamp(rect.x, display.x, display.x + wd)
|
|
52
|
+
y0 = _clamp(rect.y, display.y, display.y + hd)
|
|
53
|
+
x1 = _clamp(rect.far_x, x0, display.x + wd)
|
|
54
|
+
y1 = _clamp(rect.far_y, y0, display.y + hd)
|
|
55
|
+
if x1 <= x0 or y1 <= y0:
|
|
56
|
+
raise ValueError(f"rectangle {rect!r} is not for display {display.id}")
|
|
57
|
+
w, h = x1 - x0, y1 - y0
|
|
58
|
+
xd, yd = x0 - display.x, y0 - display.y
|
|
59
|
+
rot = display.rotation
|
|
60
|
+
if rot == 0:
|
|
61
|
+
return Rect(xd, yd, w, h)
|
|
62
|
+
if rot == 1:
|
|
63
|
+
return Rect(hd - yd - h, xd, h, w)
|
|
64
|
+
if rot == 2:
|
|
65
|
+
return Rect(wd - xd - w, hd - yd - h, w, h)
|
|
66
|
+
if rot == 3:
|
|
67
|
+
return Rect(yd, wd - xd - w, h, w)
|
|
68
|
+
raise ValueError(f"bad display rotation {rot!r}")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def translate_to_session(rect: Rect, display: DisplayGeometry) -> Rect:
|
|
72
|
+
"""Inverse of :func:`translate_to_real` (``display-translations.go:287``)."""
|
|
73
|
+
wd, hd = display.rotated_width, display.rotated_height
|
|
74
|
+
rot = display.rotation
|
|
75
|
+
if rot == 0:
|
|
76
|
+
xd, yd, w, h = rect.x, rect.y, rect.width, rect.height
|
|
77
|
+
elif rot == 1:
|
|
78
|
+
w, h = rect.height, rect.width
|
|
79
|
+
xd, yd = rect.y, hd - rect.x - h
|
|
80
|
+
elif rot == 2:
|
|
81
|
+
w, h = rect.width, rect.height
|
|
82
|
+
xd, yd = wd - rect.x - w, hd - rect.y - h
|
|
83
|
+
elif rot == 3:
|
|
84
|
+
w, h = rect.height, rect.width
|
|
85
|
+
xd, yd = wd - rect.y - w, rect.x
|
|
86
|
+
else:
|
|
87
|
+
raise ValueError(f"bad display rotation {rot!r}")
|
|
88
|
+
return Rect(display.x + xd, display.y + yd, w, h)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def rotate_image(tile: np.ndarray, rotation: int) -> np.ndarray:
|
|
92
|
+
"""``imgproc.CvRotateOrthogonal`` -- rotate a display-local crop.
|
|
93
|
+
|
|
94
|
+
The rotation sense is pinned to :func:`translate_to_real`: after rotating,
|
|
95
|
+
the pixel at the rectangle's translated ``(x, y)`` must be the pixel that
|
|
96
|
+
was at its canvas ``(x, y)``. ``rotation == 1`` (90 degrees) therefore
|
|
97
|
+
maps canvas ``(xd, yd)`` to ``(Hd-yd-h, xd)``, which is ``np.rot90`` with
|
|
98
|
+
``k = -1`` (clockwise).
|
|
99
|
+
"""
|
|
100
|
+
if rotation == 0:
|
|
101
|
+
return tile
|
|
102
|
+
if rotation == 1:
|
|
103
|
+
return np.rot90(tile, k=-1)
|
|
104
|
+
if rotation == 2:
|
|
105
|
+
return np.rot90(tile, k=2)
|
|
106
|
+
if rotation == 3:
|
|
107
|
+
return np.rot90(tile, k=1)
|
|
108
|
+
raise ValueError(f"bad display rotation {rotation!r}")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def unrotate_image(tile: np.ndarray, rotation: int) -> np.ndarray:
|
|
112
|
+
"""Inverse of :func:`rotate_image`."""
|
|
113
|
+
if rotation == 0:
|
|
114
|
+
return tile
|
|
115
|
+
if rotation == 1:
|
|
116
|
+
return np.rot90(tile, k=1)
|
|
117
|
+
if rotation == 2:
|
|
118
|
+
return np.rot90(tile, k=2)
|
|
119
|
+
if rotation == 3:
|
|
120
|
+
return np.rot90(tile, k=-1)
|
|
121
|
+
raise ValueError(f"bad display rotation {rotation!r}")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def mirror_image(tile: np.ndarray) -> np.ndarray:
|
|
125
|
+
"""Horizontal flip -- ``imgproc.CvFlip``, the whole of ``eink-flip``.
|
|
126
|
+
|
|
127
|
+
Spec §1.6. Self-inverse, so the same function un-mirrors.
|
|
128
|
+
"""
|
|
129
|
+
return tile[:, ::-1]
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Input conversion to 8-bit grey, and the optional ``Beautify`` stage.
|
|
2
|
+
|
|
3
|
+
Spec §3.3 (``imgproc.CvToGrayImage``, ``eink-generic.go:111``) and §4.3
|
|
4
|
+
(``pretty.BeautifyCV``).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
__all__ = ["to_grey8", "beautify"]
|
|
14
|
+
|
|
15
|
+
#: Go's ``color.GrayModel`` / OpenCV's ``CV_RGB2GRAY`` luma weights, in the
|
|
16
|
+
#: fixed-point form Go uses: ``(19595*r + 38470*g + 7471*b + 1<<15) >> 16``,
|
|
17
|
+
#: i.e. 0.299 / 0.587 / 0.114.
|
|
18
|
+
_LUMA = (19595, 38470, 7471)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def to_grey8(img: Any) -> np.ndarray:
|
|
22
|
+
"""Coerce an image to a contiguous ``(height, width)`` uint8 array.
|
|
23
|
+
|
|
24
|
+
Accepts:
|
|
25
|
+
|
|
26
|
+
* a PIL ``Image`` in any mode (converted with ``.convert("L")``, which uses
|
|
27
|
+
the same ITU-R 601 luma weights);
|
|
28
|
+
* a 2-D numpy array (uint8 passed through; float assumed to be ``0..1`` if
|
|
29
|
+
its max is ``<= 1.0``, else ``0..255``);
|
|
30
|
+
* a 3-D numpy array with 1, 3 or 4 channels (RGB / RGBA; alpha is ignored,
|
|
31
|
+
matching ``CvToGrayImage``, which only looks at the colour channels).
|
|
32
|
+
"""
|
|
33
|
+
if hasattr(img, "convert") and hasattr(img, "size"): # PIL.Image.Image
|
|
34
|
+
pil = img if img.mode == "L" else img.convert("L")
|
|
35
|
+
return np.ascontiguousarray(np.asarray(pil, dtype=np.uint8))
|
|
36
|
+
|
|
37
|
+
arr = np.asarray(img)
|
|
38
|
+
if arr.ndim == 3:
|
|
39
|
+
if arr.shape[2] == 1:
|
|
40
|
+
arr = arr[:, :, 0]
|
|
41
|
+
elif arr.shape[2] in (3, 4):
|
|
42
|
+
rgb = arr[:, :, :3].astype(np.uint32)
|
|
43
|
+
acc = (rgb[:, :, 0] * _LUMA[0] + rgb[:, :, 1] * _LUMA[1]
|
|
44
|
+
+ rgb[:, :, 2] * _LUMA[2] + (1 << 15)) >> 16
|
|
45
|
+
arr = np.clip(acc, 0, 255).astype(np.uint8)
|
|
46
|
+
else:
|
|
47
|
+
raise ValueError(f"cannot convert a {arr.shape[2]}-channel image to grey")
|
|
48
|
+
if arr.ndim != 2:
|
|
49
|
+
raise ValueError(f"expected a 2-D image, got shape {arr.shape}")
|
|
50
|
+
if arr.dtype != np.uint8:
|
|
51
|
+
f = arr.astype(np.float64)
|
|
52
|
+
scale = 255.0 if (f.size and f.max() <= 1.0) else 1.0
|
|
53
|
+
arr = np.clip(np.rint(f * scale), 0, 255).astype(np.uint8)
|
|
54
|
+
return np.ascontiguousarray(arr)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def beautify(grey: np.ndarray, gamma: float = 1.1, do2step: bool = False,
|
|
58
|
+
fallback: tuple[float, float] = (0.0, 255.0)) -> np.ndarray:
|
|
59
|
+
"""``pretty.BeautifyCV.Beautify`` on a grey image -- spec §4.3.
|
|
60
|
+
|
|
61
|
+
A per-channel linear contrast stretch (auto-levels) followed by a gamma
|
|
62
|
+
LUT. Reconstructed from the compiled ``beautify.cpp`` helpers::
|
|
63
|
+
|
|
64
|
+
minMax(img, &lo, &hi, fallbackLo, fallbackHi)
|
|
65
|
+
cvMinMaxLoc(...); if (lo == hi) { lo = fallbackLo; hi = fallbackHi; }
|
|
66
|
+
rangeMap(img, inLo, inHi, outLo, outHi)
|
|
67
|
+
range = (inHi == inLo) ? inHi : (inHi - inLo);
|
|
68
|
+
scale = (outHi - outLo) / range; shift = outLo;
|
|
69
|
+
cvConvertScale(img, img, scale, shift);
|
|
70
|
+
gammaCorrect(src, dst, gamma)
|
|
71
|
+
cvLUT(src, dst, generateGammaLUT(gamma));
|
|
72
|
+
|
|
73
|
+
.. note:: **[INFERRED]**
|
|
74
|
+
The spec flags the exact ``shift`` term as unverified -- the compiled
|
|
75
|
+
code zeroes ``inLo`` before computing it, which is only consistent with
|
|
76
|
+
callers that always pass ``inLo = 0``. We implement the textbook
|
|
77
|
+
auto-levels form ``(v - lo) * 255 / (hi - lo)``, which is what the
|
|
78
|
+
helper computes when ``outLo = 0`` and ``inLo`` is subtracted first.
|
|
79
|
+
Do not treat this function as byte-exact to the vendor.
|
|
80
|
+
|
|
81
|
+
This stage is **off by default** in :func:`pyvisionect.imaging.encode_frame`.
|
|
82
|
+
The vendor enables it (``Beautify{Enable: true, Gamma: 1.1}``) for HTML
|
|
83
|
+
sessions, but it destroys content that the renderer has already quantised
|
|
84
|
+
to the output ramp -- which is exactly how the live session is driven.
|
|
85
|
+
|
|
86
|
+
:param do2step: run the contrast stretch twice (the vendor's ``do2Step``).
|
|
87
|
+
"""
|
|
88
|
+
g = np.asarray(grey, dtype=np.uint8)
|
|
89
|
+
if g.size == 0:
|
|
90
|
+
return g.copy()
|
|
91
|
+
out = g.astype(np.float64)
|
|
92
|
+
for _ in range(2 if do2step else 1):
|
|
93
|
+
lo = float(out.min())
|
|
94
|
+
hi = float(out.max())
|
|
95
|
+
if lo == hi:
|
|
96
|
+
lo, hi = fallback
|
|
97
|
+
rng = hi - lo if hi != lo else (hi if hi else 1.0)
|
|
98
|
+
out = (out - lo) * (255.0 / rng)
|
|
99
|
+
out = np.clip(out, 0.0, 255.0)
|
|
100
|
+
if gamma and gamma != 1.0:
|
|
101
|
+
lut = np.clip(np.rint(((np.arange(256) / 255.0) ** (1.0 / gamma)) * 255.0),
|
|
102
|
+
0, 255).astype(np.uint8)
|
|
103
|
+
return lut[np.clip(np.rint(out), 0, 255).astype(np.uint8)]
|
|
104
|
+
return np.clip(np.rint(out), 0, 255).astype(np.uint8)
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""Transmit-side interlacing for the 32" sign (``HardwareNameID == 8``).
|
|
2
|
+
|
|
3
|
+
Spec §1.6, ``vss/cmd/engine/image_interlacing.go``.
|
|
4
|
+
|
|
5
|
+
The server models the sign as **4 logical displays of 1440 x 640** stacked
|
|
6
|
+
vertically, but the panel has **2 physical 2880 x 640 channels**. Immediately
|
|
7
|
+
before the gRPC hand-off to the gateway, ``main.interlacingHack``
|
|
8
|
+
(``image_interlacing.go:105``) folds the four full-size rectangles into two,
|
|
9
|
+
interleaving each pair **at 4-pixel granularity** -- which is exactly the
|
|
10
|
+
"16-bit quantum" the rectangle sizer enforces (spec §2.4).
|
|
11
|
+
|
|
12
|
+
4 bpp interleaver (``image_interlacing.go:43-46``), 2 bytes = 4 pixels at a
|
|
13
|
+
time::
|
|
14
|
+
|
|
15
|
+
for i, io := 0, 0; io+4 <= len(out); io += 4, i += 2 {
|
|
16
|
+
out[io+0]=a[i]; out[io+1]=a[i+1]; out[io+2]=b[i]; out[io+3]=b[i+1]
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
1 bpp interleaver (``image_interlacing.go:75-76``), one nibble = 4 pixels at a
|
|
20
|
+
time::
|
|
21
|
+
|
|
22
|
+
out[io+0] = (a[i] & 0xF0) | (b[i] >> 4)
|
|
23
|
+
out[io+1] = (a[i] << 4) | (b[i] & 0x0F)
|
|
24
|
+
|
|
25
|
+
Both produce the same pixel sequence: ``a[0:4], b[0:4], a[4:8], b[4:8], ...``.
|
|
26
|
+
|
|
27
|
+
Pairing
|
|
28
|
+
-------
|
|
29
|
+
``getInterlacingMode`` (``image_interlacing.go:92``) returns ``2`` for
|
|
30
|
+
``HardwareNameID == 8`` at any hardware revision other than 1.0.0 (ours is
|
|
31
|
+
1.1.0), and ``1`` for 1.0.0.
|
|
32
|
+
|
|
33
|
+
**Mode 2's pairing and lane order were recovered from real captured traffic,
|
|
34
|
+
not from the disassembly** -- see :data:`INTERLACE_PAIRS` and
|
|
35
|
+
``tests/imaging/test_golden_capture.py``. Mode 1's pairing was *not*
|
|
36
|
+
recovered, so it raises.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
from __future__ import annotations
|
|
40
|
+
|
|
41
|
+
import numpy as np
|
|
42
|
+
|
|
43
|
+
from .constants import Encoding
|
|
44
|
+
|
|
45
|
+
__all__ = ["INTERLACE_PAIRS", "interlace_4bpp", "deinterlace_4bpp",
|
|
46
|
+
"interlace_1bpp", "deinterlace_1bpp", "interlace", "deinterlace",
|
|
47
|
+
"interlace_pairs", "INTERLACE_GROUP", "SCREEN_X_QUANTUM",
|
|
48
|
+
"lane_span", "screen_span", "lane_of_display", "displays_of_screen"]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
#: Pixels per interleave group -- the "4-pixel granularity" of the fold.
|
|
52
|
+
#: ``image_interlacing.go:43-46`` moves 2 bytes (4 pixels) of lane A, then 2 of
|
|
53
|
+
#: lane B; the 1 bpp interleaver moves one nibble (4 pixels) at a time. Both
|
|
54
|
+
#: produce ``a[0:4], b[0:4], a[4:8], b[4:8], ...``.
|
|
55
|
+
INTERLACE_GROUP = 4
|
|
56
|
+
|
|
57
|
+
#: Screen-space x/width quantum: one lane group plus its partner's. A screen
|
|
58
|
+
#: rectangle whose ``x`` is not a multiple of this starts part-way into a group
|
|
59
|
+
#: and the lanes come out swapped; one whose ``width`` is not a multiple of it
|
|
60
|
+
#: ends mid-group and the packed lane rows stop being whole numbers of groups.
|
|
61
|
+
SCREEN_X_QUANTUM = 2 * INTERLACE_GROUP
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
#: ``{mode: ((screen_id, (lane_a_display, lane_b_display)), ...)}``
|
|
65
|
+
#:
|
|
66
|
+
#: Mode 2, **verified byte-exactly** against the 1.84 MB image push in
|
|
67
|
+
#: ``tmp/visionect/agent-live/pcap/device-11113.pcap``: de-interlacing the two
|
|
68
|
+
#: captured 2880 x 640 payloads with this table, decoding the nibbles,
|
|
69
|
+
#: un-mirroring each 1440-wide tile and stacking them as displays 0..3
|
|
70
|
+
#: reproduces ``ImageHeader.Checksum == 3741864387`` exactly. All 24
|
|
71
|
+
#: permutations x 2 nibble orders x 2 mirror settings were tried; this is the
|
|
72
|
+
#: only combination that matches.
|
|
73
|
+
#:
|
|
74
|
+
#: Note that **screen 1's lanes are swapped** relative to screen 0 -- that is
|
|
75
|
+
#: the ``displayOrder`` argument of the vendor's interleaver
|
|
76
|
+
#: (``image_interlacing.go:32-37``) and is a physical panel-wiring detail.
|
|
77
|
+
INTERLACE_PAIRS: dict[int, tuple[tuple[int, tuple[int, int]], ...]] = {
|
|
78
|
+
2: ((0, (0, 1)), (1, (3, 2))),
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def interlace_pairs(mode: int) -> tuple[tuple[int, tuple[int, int]], ...]:
|
|
83
|
+
"""Lane table for an interlacing mode, or raise for an unknown one."""
|
|
84
|
+
try:
|
|
85
|
+
return INTERLACE_PAIRS[mode]
|
|
86
|
+
except KeyError:
|
|
87
|
+
if mode == 1:
|
|
88
|
+
raise NotImplementedError(
|
|
89
|
+
"interlacing mode 1 (HardwareNameID 8 at hardware revision "
|
|
90
|
+
"1.0.0) uses a different pairing (image_interlacing.go:167-170) "
|
|
91
|
+
"that was not recovered from the binary and could not be "
|
|
92
|
+
"verified against hardware; refusing to guess"
|
|
93
|
+
) from None
|
|
94
|
+
raise ValueError(f"unknown interlacing mode {mode!r}") from None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _pair(a: bytes, b: bytes) -> tuple[np.ndarray, np.ndarray]:
|
|
98
|
+
aa = np.frombuffer(a, dtype=np.uint8)
|
|
99
|
+
bb = np.frombuffer(b, dtype=np.uint8)
|
|
100
|
+
if aa.size != bb.size:
|
|
101
|
+
raise ValueError(f"interlace halves differ in size: {aa.size} != {bb.size}")
|
|
102
|
+
return aa, bb
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def interlace_4bpp(a: bytes, b: bytes) -> bytes:
|
|
106
|
+
"""Interleave two 4 bpp payloads, 2 bytes (4 pixels) at a time."""
|
|
107
|
+
aa, bb = _pair(a, b)
|
|
108
|
+
if aa.size % 2:
|
|
109
|
+
raise ValueError("4 bpp interlace needs an even byte count per half")
|
|
110
|
+
out = np.empty((aa.size // 2, 4), dtype=np.uint8)
|
|
111
|
+
out[:, 0:2] = aa.reshape(-1, 2)
|
|
112
|
+
out[:, 2:4] = bb.reshape(-1, 2)
|
|
113
|
+
return out.reshape(-1).tobytes()
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def deinterlace_4bpp(data: bytes) -> tuple[bytes, bytes]:
|
|
117
|
+
"""Inverse of :func:`interlace_4bpp` (``liveview/helpers.go:21``)."""
|
|
118
|
+
g = np.frombuffer(data, dtype=np.uint8)
|
|
119
|
+
if g.size % 4:
|
|
120
|
+
raise ValueError("4 bpp de-interlace needs a byte count divisible by 4")
|
|
121
|
+
g = g.reshape(-1, 4)
|
|
122
|
+
return (g[:, 0:2].reshape(-1).tobytes(), g[:, 2:4].reshape(-1).tobytes())
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def interlace_1bpp(a: bytes, b: bytes) -> bytes:
|
|
126
|
+
"""Interleave two 1 bpp payloads, one nibble (4 pixels) at a time."""
|
|
127
|
+
aa, bb = _pair(a, b)
|
|
128
|
+
out = np.empty((aa.size, 2), dtype=np.uint8)
|
|
129
|
+
out[:, 0] = (aa & 0xF0) | (bb >> 4)
|
|
130
|
+
out[:, 1] = ((aa << 4) & 0xFF) | (bb & 0x0F)
|
|
131
|
+
return out.reshape(-1).tobytes()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def deinterlace_1bpp(data: bytes) -> tuple[bytes, bytes]:
|
|
135
|
+
"""Inverse of :func:`interlace_1bpp` (``liveview/helpers.go:43``)."""
|
|
136
|
+
g = np.frombuffer(data, dtype=np.uint8)
|
|
137
|
+
if g.size % 2:
|
|
138
|
+
raise ValueError("1 bpp de-interlace needs an even byte count")
|
|
139
|
+
g = g.reshape(-1, 2)
|
|
140
|
+
a = (g[:, 0] & 0xF0) | (g[:, 1] >> 4)
|
|
141
|
+
b = ((g[:, 0] << 4) & 0xFF) | (g[:, 1] & 0x0F)
|
|
142
|
+
return (a.tobytes(), b.tobytes())
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def interlace(a: bytes, b: bytes, encoding: int) -> bytes:
|
|
146
|
+
"""Dispatch on encoding -- ``image_interlacing.go:131-133``."""
|
|
147
|
+
if encoding == Encoding.ONE_BIT:
|
|
148
|
+
return interlace_1bpp(a, b)
|
|
149
|
+
if encoding == Encoding.FOUR_BIT:
|
|
150
|
+
return interlace_4bpp(a, b)
|
|
151
|
+
raise ValueError(f"bad encoding {encoding!r}; only 1 and 4 exist (spec §2.1)")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def deinterlace(data: bytes, encoding: int) -> tuple[bytes, bytes]:
|
|
155
|
+
"""Inverse of :func:`interlace`."""
|
|
156
|
+
if encoding == Encoding.ONE_BIT:
|
|
157
|
+
return deinterlace_1bpp(data)
|
|
158
|
+
if encoding == Encoding.FOUR_BIT:
|
|
159
|
+
return deinterlace_4bpp(data)
|
|
160
|
+
raise ValueError(f"bad encoding {encoding!r}; only 1 and 4 exist (spec §2.1)")
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
# --------------------------------------------------------------------------
|
|
164
|
+
# sub-range geometry -- what a *partial* screen rectangle needs
|
|
165
|
+
# --------------------------------------------------------------------------
|
|
166
|
+
#
|
|
167
|
+
# The fold is a pure permutation of columns, so it restricts to a sub-range.
|
|
168
|
+
# Screen column ``s`` carries lane ``(s // INTERLACE_GROUP) % 2`` at lane
|
|
169
|
+
# column ``(s // SCREEN_X_QUANTUM) * INTERLACE_GROUP + s % INTERLACE_GROUP``.
|
|
170
|
+
# Inverting that for a whole number of *paired* groups:
|
|
171
|
+
#
|
|
172
|
+
# lane columns [c0, c1) <-> screen columns [2*c0, 2*c1)
|
|
173
|
+
#
|
|
174
|
+
# with ``c0`` and ``c1`` multiples of ``INTERLACE_GROUP``. Which is why
|
|
175
|
+
# :data:`SCREEN_X_QUANTUM` is 8 and not 4: 4 would address one lane's group
|
|
176
|
+
# without its partner's, and there is no way to say that on the wire.
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def lane_span(screen_x: int, screen_width: int) -> tuple[int, int]:
|
|
180
|
+
"""Lane-column range ``[c0, c1)`` covered by a screen-space x-range.
|
|
181
|
+
|
|
182
|
+
Both lanes of the screen cover the *same* lane columns -- that is the
|
|
183
|
+
whole reason a partial update has to carry the partner lane.
|
|
184
|
+
|
|
185
|
+
:raises ValueError: if ``screen_x`` or ``screen_width`` is not a multiple
|
|
186
|
+
of :data:`SCREEN_X_QUANTUM`, or either is negative.
|
|
187
|
+
"""
|
|
188
|
+
if screen_x < 0 or screen_width < 0:
|
|
189
|
+
raise ValueError(f"negative screen x-range {screen_x}+{screen_width}")
|
|
190
|
+
if screen_x % SCREEN_X_QUANTUM or screen_width % SCREEN_X_QUANTUM:
|
|
191
|
+
raise ValueError(
|
|
192
|
+
f"screen x={screen_x} width={screen_width} must both be multiples "
|
|
193
|
+
f"of {SCREEN_X_QUANTUM} so the interleave lanes stay paired"
|
|
194
|
+
)
|
|
195
|
+
return (screen_x // 2, (screen_x + screen_width) // 2)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def screen_span(lane_x: int, lane_width: int) -> tuple[int, int]:
|
|
199
|
+
"""Inverse of :func:`lane_span`: ``(screen_x, screen_width)``.
|
|
200
|
+
|
|
201
|
+
:raises ValueError: if ``lane_x`` or ``lane_width`` is not a multiple of
|
|
202
|
+
:data:`INTERLACE_GROUP`, or either is negative.
|
|
203
|
+
"""
|
|
204
|
+
if lane_x < 0 or lane_width < 0:
|
|
205
|
+
raise ValueError(f"negative lane x-range {lane_x}+{lane_width}")
|
|
206
|
+
if lane_x % INTERLACE_GROUP or lane_width % INTERLACE_GROUP:
|
|
207
|
+
raise ValueError(
|
|
208
|
+
f"lane x={lane_x} width={lane_width} must both be multiples of "
|
|
209
|
+
f"{INTERLACE_GROUP}, the interleave group"
|
|
210
|
+
)
|
|
211
|
+
return (lane_x * 2, lane_width * 2)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def lane_of_display(mode: int, display: int) -> tuple[int, int]:
|
|
215
|
+
"""``(screen_id, lane_index)`` carrying a logical display's band.
|
|
216
|
+
|
|
217
|
+
``lane_index`` is ``0`` for lane A (the first half of each interleave
|
|
218
|
+
group) and ``1`` for lane B. On mode 2, display 2 is **screen 1's lane
|
|
219
|
+
B** and display 3 is screen 1's lane A -- the swap.
|
|
220
|
+
|
|
221
|
+
:raises ValueError: if no screen carries that display.
|
|
222
|
+
"""
|
|
223
|
+
for screen_id, lanes in interlace_pairs(mode):
|
|
224
|
+
for index, lane_display in enumerate(lanes):
|
|
225
|
+
if lane_display == display:
|
|
226
|
+
return (screen_id, index)
|
|
227
|
+
raise ValueError(
|
|
228
|
+
f"interlacing mode {mode} has no lane for display {display}"
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def displays_of_screen(mode: int, screen_id: int) -> tuple[int, int]:
|
|
233
|
+
"""``(lane_a_display, lane_b_display)`` for a ``ScreenID``.
|
|
234
|
+
|
|
235
|
+
:raises ValueError: if the mode has no such screen.
|
|
236
|
+
"""
|
|
237
|
+
for sid, lanes in interlace_pairs(mode):
|
|
238
|
+
if sid == screen_id:
|
|
239
|
+
return lanes
|
|
240
|
+
known = sorted(sid for sid, _ in interlace_pairs(mode))
|
|
241
|
+
raise ValueError(
|
|
242
|
+
f"interlacing mode {mode} has no ScreenID {screen_id}; known "
|
|
243
|
+
f"screens are {known}"
|
|
244
|
+
)
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""1 bpp / 4 bpp bit packing. Spec §2.3.
|
|
2
|
+
|
|
3
|
+
All four vendor helpers (``encode_eight_to_four``, ``encode_eight_to_one``,
|
|
4
|
+
``decode_four_to_eight``, ``decode_one_to_eight``, compiled C in
|
|
5
|
+
``vss/pkg/driver``) operate on a **flat, row-major, ``stride == width`` buffer
|
|
6
|
+
for the whole rectangle**. The pack runs straight across row boundaries;
|
|
7
|
+
there is **no per-row padding**. That is why the alignment constraint in
|
|
8
|
+
:mod:`pyvisionect.imaging.rects` is on ``width * height`` and not on width.
|
|
9
|
+
|
|
10
|
+
4 bpp (``encode_eight_to_four``)::
|
|
11
|
+
|
|
12
|
+
dst[o] = (src[c+1] & 0xF0) | (src[c] >> 4);
|
|
13
|
+
|
|
14
|
+
src: [ P0 ][ P1 ][ P2 ][ P3 ] ... 8-bit grey
|
|
15
|
+
dst: bit 7 6 5 4 3 2 1 0
|
|
16
|
+
P1 P0 EVEN pixel in the LOW nibble
|
|
17
|
+
|
|
18
|
+
Each nibble is the *top 4 bits* of the 8-bit grey value -- truncation, not
|
|
19
|
+
rounding. The inverse ``decode_four_to_eight`` expands nibble ``n`` to
|
|
20
|
+
``n * 17`` (``(b << 4) + (b & 0x0F)``), which is where the uniform 16-level
|
|
21
|
+
ramp ``0, 17, 34, ... 255`` comes from.
|
|
22
|
+
|
|
23
|
+
1 bpp (``encode_eight_to_one``)::
|
|
24
|
+
|
|
25
|
+
dst byte: bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0
|
|
26
|
+
P0 P1 P2 P3 P4 P5 P6 P7 MSB-FIRST
|
|
27
|
+
|
|
28
|
+
Each pixel contributes only its MSB, i.e. a hard threshold at ``>= 0x80``.
|
|
29
|
+
This is *not* a dither; dithering has to have happened earlier.
|
|
30
|
+
|
|
31
|
+
.. warning::
|
|
32
|
+
The vendor's ``cEightToOneBit`` computes ``encodedLen = (len+extra)/8``
|
|
33
|
+
where ``extra = len & 7`` (``encode.go:50-52``), which **under-allocates**
|
|
34
|
+
for any length that is not a multiple of 8 and makes the cgo call write past
|
|
35
|
+
the slice. In practice the rectangle sizer guarantees ``w*h % 16 == 0`` for
|
|
36
|
+
1 bpp, so it never fires. We use ``ceil(len / 8)``, as the spec recommends.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
from __future__ import annotations
|
|
40
|
+
|
|
41
|
+
import numpy as np
|
|
42
|
+
|
|
43
|
+
from .constants import BITS_PER_PIXEL, Encoding
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
"pack_4bpp",
|
|
47
|
+
"unpack_4bpp",
|
|
48
|
+
"pack_1bpp",
|
|
49
|
+
"unpack_1bpp",
|
|
50
|
+
"pack",
|
|
51
|
+
"unpack",
|
|
52
|
+
"payload_size",
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _flat(pix: np.ndarray) -> np.ndarray:
|
|
57
|
+
arr = np.ascontiguousarray(pix)
|
|
58
|
+
if arr.dtype != np.uint8:
|
|
59
|
+
raise TypeError(f"pixel buffer must be uint8, got {arr.dtype}")
|
|
60
|
+
return arr.reshape(-1)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def pack_4bpp(pix: np.ndarray) -> bytes:
|
|
64
|
+
"""8 bpp grey -> 4 bpp, even pixel in the low nibble.
|
|
65
|
+
|
|
66
|
+
An odd pixel count is padded with one ``0x00`` (black) byte, matching
|
|
67
|
+
``CEightToFourBit`` (``encode.go:33-38``).
|
|
68
|
+
"""
|
|
69
|
+
flat = _flat(pix)
|
|
70
|
+
if flat.size % 2:
|
|
71
|
+
flat = np.concatenate([flat, np.zeros(1, dtype=np.uint8)])
|
|
72
|
+
lo = flat[0::2] >> 4
|
|
73
|
+
hi = flat[1::2] >> 4
|
|
74
|
+
return ((hi << 4) | lo).astype(np.uint8).tobytes()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def unpack_4bpp(data: bytes, count: int | None = None) -> np.ndarray:
|
|
78
|
+
"""4 bpp -> 8 bpp grey on the ``n * 17`` ramp (``decode_four_to_eight``).
|
|
79
|
+
|
|
80
|
+
:param count: number of pixels to return; defaults to ``2 * len(data)``.
|
|
81
|
+
Use it to drop the padding pixel added by :func:`pack_4bpp`.
|
|
82
|
+
"""
|
|
83
|
+
b = np.frombuffer(data, dtype=np.uint8)
|
|
84
|
+
out = np.empty(b.size * 2, dtype=np.uint8)
|
|
85
|
+
out[0::2] = (b & 0x0F) * 17
|
|
86
|
+
out[1::2] = (b >> 4) * 17
|
|
87
|
+
return out if count is None else out[:count]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def pack_1bpp(pix: np.ndarray) -> bytes:
|
|
91
|
+
"""8 bpp grey -> 1 bpp, MSB-first, hard threshold at ``>= 0x80``.
|
|
92
|
+
|
|
93
|
+
A pixel count that is not a multiple of 8 is padded with zero bytes
|
|
94
|
+
(black -> bit 0), matching ``cEightToOneBit`` (``encode.go:54-55``), but
|
|
95
|
+
using ``ceil(len / 8)`` output bytes rather than the vendor's buggy
|
|
96
|
+
``(len + (len & 7)) / 8``.
|
|
97
|
+
"""
|
|
98
|
+
flat = _flat(pix)
|
|
99
|
+
bits = flat >= 0x80
|
|
100
|
+
rem = -flat.size % 8
|
|
101
|
+
if rem:
|
|
102
|
+
bits = np.concatenate([bits, np.zeros(rem, dtype=bool)])
|
|
103
|
+
return np.packbits(bits, bitorder="big").tobytes()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def unpack_1bpp(data: bytes, count: int | None = None) -> np.ndarray:
|
|
107
|
+
"""1 bpp -> 8 bpp grey, ``1 -> 0xFF`` / ``0 -> 0x00`` (``decode_one_to_eight``)."""
|
|
108
|
+
b = np.frombuffer(data, dtype=np.uint8)
|
|
109
|
+
out = np.unpackbits(b, bitorder="big") * np.uint8(255)
|
|
110
|
+
out = out.astype(np.uint8)
|
|
111
|
+
return out if count is None else out[:count]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def pack(pix: np.ndarray, encoding: int) -> bytes:
|
|
115
|
+
"""Dispatch on ``proto.EncodingType`` -- ``eink-generic.go:146-151``."""
|
|
116
|
+
if encoding == Encoding.ONE_BIT:
|
|
117
|
+
return pack_1bpp(pix)
|
|
118
|
+
if encoding == Encoding.FOUR_BIT:
|
|
119
|
+
return pack_4bpp(pix)
|
|
120
|
+
raise ValueError(f"bad encoding {encoding!r}; only 1 and 4 exist (spec §2.1)")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def unpack(data: bytes, encoding: int, count: int | None = None) -> np.ndarray:
|
|
124
|
+
"""Inverse of :func:`pack` -- ``eink-generic.go:154-186`` (``image-decode``)."""
|
|
125
|
+
if encoding == Encoding.ONE_BIT:
|
|
126
|
+
return unpack_1bpp(data, count)
|
|
127
|
+
if encoding == Encoding.FOUR_BIT:
|
|
128
|
+
return unpack_4bpp(data, count)
|
|
129
|
+
raise ValueError(f"bad encoding {encoding!r}; only 1 and 4 exist (spec §2.1)")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def payload_size(width: int, height: int, encoding: int) -> int:
|
|
133
|
+
"""``RectangleHeader.PayloadLength`` -- spec §2.3.
|
|
134
|
+
|
|
135
|
+
``width * height // (8 // bpp)``, i.e. ``w*h/2`` for 4 bpp and ``w*h/8``
|
|
136
|
+
for 1 bpp. Rounded up, as :func:`pack` pads.
|
|
137
|
+
"""
|
|
138
|
+
bpp = BITS_PER_PIXEL.get(int(encoding))
|
|
139
|
+
if bpp is None:
|
|
140
|
+
raise ValueError(f"bad encoding {encoding!r}; only 1 and 4 exist (spec §2.1)")
|
|
141
|
+
per_byte = 8 // bpp
|
|
142
|
+
return (width * height + per_byte - 1) // per_byte
|