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.
Files changed (58) hide show
  1. pyvisionect/__init__.py +120 -0
  2. pyvisionect/devices/__init__.py +92 -0
  3. pyvisionect/devices/enums.py +403 -0
  4. pyvisionect/devices/panels.py +242 -0
  5. pyvisionect/devices/tclv.py +460 -0
  6. pyvisionect/imaging/README.md +175 -0
  7. pyvisionect/imaging/__init__.py +181 -0
  8. pyvisionect/imaging/checksum.py +114 -0
  9. pyvisionect/imaging/constants.py +131 -0
  10. pyvisionect/imaging/data/blue_noise_64.npy +0 -0
  11. pyvisionect/imaging/decode.py +172 -0
  12. pyvisionect/imaging/dither.py +357 -0
  13. pyvisionect/imaging/encoder.py +594 -0
  14. pyvisionect/imaging/geometry.py +129 -0
  15. pyvisionect/imaging/grey.py +104 -0
  16. pyvisionect/imaging/interlace.py +244 -0
  17. pyvisionect/imaging/pack.py +142 -0
  18. pyvisionect/imaging/panel.py +339 -0
  19. pyvisionect/imaging/partial.py +931 -0
  20. pyvisionect/imaging/rects.py +466 -0
  21. pyvisionect/io/__init__.py +33 -0
  22. pyvisionect/io/tcp.py +795 -0
  23. pyvisionect/io/usb/__init__.py +237 -0
  24. pyvisionect/io/usb/cli.py +278 -0
  25. pyvisionect/io/usb/commands.py +781 -0
  26. pyvisionect/io/usb/console.py +730 -0
  27. pyvisionect/io/usb/device.py +914 -0
  28. pyvisionect/io/usb/discovery.py +260 -0
  29. pyvisionect/io/usb/encryption.py +262 -0
  30. pyvisionect/io/usb/errors.py +175 -0
  31. pyvisionect/io/usb/fake.py +292 -0
  32. pyvisionect/io/usb/parsers.py +1464 -0
  33. pyvisionect/io/usb/provisioning.py +502 -0
  34. pyvisionect/packets/__init__.py +135 -0
  35. pyvisionect/packets/control.py +95 -0
  36. pyvisionect/packets/file.py +325 -0
  37. pyvisionect/packets/image.py +234 -0
  38. pyvisionect/packets/misc.py +202 -0
  39. pyvisionect/packets/param.py +284 -0
  40. pyvisionect/packets/status.py +518 -0
  41. pyvisionect/packets/stored.py +217 -0
  42. pyvisionect/py.typed +0 -0
  43. pyvisionect/session/__init__.py +100 -0
  44. pyvisionect/session/connection.py +1043 -0
  45. pyvisionect/session/device.py +587 -0
  46. pyvisionect/session/events.py +196 -0
  47. pyvisionect/session/filetransfer.py +251 -0
  48. pyvisionect/session/pending.py +425 -0
  49. pyvisionect/wire/__init__.py +91 -0
  50. pyvisionect/wire/blocks.py +350 -0
  51. pyvisionect/wire/checksum.py +115 -0
  52. pyvisionect/wire/errors.py +176 -0
  53. pyvisionect/wire/framing.py +334 -0
  54. pyvisionect-0.1.0.dist-info/METADATA +1030 -0
  55. pyvisionect-0.1.0.dist-info/RECORD +58 -0
  56. pyvisionect-0.1.0.dist-info/WHEEL +4 -0
  57. pyvisionect-0.1.0.dist-info/entry_points.txt +3 -0
  58. pyvisionect-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,181 @@
1
+ """``pyvisionect.imaging`` -- the Visionect e-ink imaging pipeline.
2
+
3
+ Pure, sans-io. Give it a PIL image or a numpy array and a
4
+ :class:`~pyvisionect.imaging.panel.Panel`; get back the rectangles to put in an
5
+ ``ImagePacket`` and the ``ImageHeader.Checksum`` to stamp on it.
6
+
7
+ >>> from pyvisionect.imaging import encode_frame, PANEL_32INCH, Dithering
8
+ >>> frame = encode_frame(img, panel=PANEL_32INCH, encoding=4,
9
+ ... dithering=Dithering.BLUE_NOISE)
10
+ >>> len(frame.rectangles), frame.rectangles[0].w, frame.state_checksum
11
+ (2, 2880, 1234567890)
12
+
13
+ Everything the panel shows is decided here: the device receives
14
+ already-quantised, already-bit-packed 1 bpp or 4 bpp data and only drives the
15
+ waveform (spec §3.3).
16
+
17
+ This module is CPU-bound -- run it in an executor
18
+ -------------------------------------------------
19
+ :func:`encode_frame` is **blocking, CPU-bound, and releases no locks**. A
20
+ 1440x2560 canvas goes through grey conversion, change detection, dithering
21
+ (Floyd-Steinberg is inherently serial), bit packing, 4-pixel interlacing and
22
+ LZ4: comfortably hundreds of milliseconds on a desktop and plausibly seconds on
23
+ a Raspberry Pi. **Never call it on an asyncio event loop.**
24
+
25
+ >>> frame = await hass.async_add_executor_job( # doctest: +SKIP
26
+ ... functools.partial(encode_frame, img, panel=panel,
27
+ ... encoding=4, dithering=3, prev_state=prev))
28
+
29
+ Calling it on the loop stalls everything else for the duration, which presents
30
+ to a user as "the whole instance freezes every hour". The resulting ~1.84 MB
31
+ socket write is a different matter and is fine on the loop -- it is just a
32
+ ``write`` plus a ``drain``.
33
+
34
+ :meth:`FrameState.to_bytes` / :meth:`FrameState.from_bytes` persist the encoder
35
+ state across a restart, which is what turns a restart from "a full-screen push
36
+ plus a unit of panel wear" into "nothing to do" -- e-ink keeps its image, so if
37
+ the device's echoed ``DisplayStateCRC`` still matches the checksum you stored,
38
+ the correct action on first contact is none.
39
+
40
+ Verified against real device bytes
41
+ ---------------------------------
42
+ The 1.84 MB image push captured in
43
+ ``tmp/visionect/agent-live/pcap/device-11113.pcap`` is reproduced
44
+ **byte-exactly**: both 2880x640 payloads and
45
+ ``ImageHeader.Checksum == 3741864387``. That one test pins down the nibble
46
+ order, the 4-pixel interlace granularity, the screen-1 lane swap, the
47
+ ``eink-flip`` mirror, the display stacking order and the XXHash32 state tag all
48
+ at once -- see ``tests/imaging/test_golden_capture.py``.
49
+
50
+ Partial updates are opt-in
51
+ --------------------------
52
+ :func:`encode_frame` always pushes the whole screen, which is what the vendor's
53
+ server does on this hardware and what every captured frame shows.
54
+ :mod:`pyvisionect.imaging.partial` adds a screen-space partial path --
55
+ ``encode_frame(..., partial=True)`` or
56
+ :class:`~pyvisionect.imaging.partial.DirtyTracker` -- which saves ~250x on the
57
+ wire and nothing at all on refresh latency. It was verified by hand on one
58
+ device and is **not** vendor-sanctioned; read that module's docstring before
59
+ turning it on.
60
+
61
+ Spec: ``artifacts/visionect/02-imaging-framebuffer.md``.
62
+ """
63
+
64
+ from __future__ import annotations
65
+
66
+ from .checksum import state_checksum, xxh32
67
+ from .constants import (ALIGN_QUANTUM, BITS_PER_PIXEL, ENCODING_LEVELS,
68
+ LEVEL_STEP, MAX_NO_FULL_UPDATE,
69
+ MAX_REGIONS_PER_DISPLAY, OPTION_NORMAL_UPDATE,
70
+ RECTANGLE_UPDATE_OPTIONS_DEFAULT, VENDOR_DITHERING,
71
+ Dithering, Encoding, ImageType)
72
+ from .decode import DecodedFrame, decode_image_packet
73
+ from .dither import (BAYER_8, bayer_matrix, blue_noise_matrix, quantise,
74
+ quantise_floyd_steinberg, quantise_none, quantise_ordered)
75
+ from .encoder import EncodedFrame, EncodedRect, FrameState, encode_frame
76
+ from .geometry import (mirror_image, rotate_image, translate_to_real,
77
+ translate_to_session, unrotate_image)
78
+ from .grey import beautify, to_grey8
79
+ from .interlace import (INTERLACE_GROUP, INTERLACE_PAIRS, SCREEN_X_QUANTUM,
80
+ deinterlace, deinterlace_1bpp, deinterlace_4bpp,
81
+ displays_of_screen, interlace, interlace_1bpp,
82
+ interlace_4bpp, lane_of_display, lane_span,
83
+ screen_span)
84
+ from .pack import (pack, pack_1bpp, pack_4bpp, payload_size, unpack,
85
+ unpack_1bpp, unpack_4bpp)
86
+ from .partial import (DirtyTracker, PartialPolicy, align_and_unite_screen_rects,
87
+ align_screen_rect, canvas_regions_for_screen_rect,
88
+ encode_partial_frame, encode_screen_rect,
89
+ full_screen_cost, partial_cost, screen_bounds,
90
+ screen_rects_for_canvas_rect, validate_screen_rect)
91
+ from .panel import DRIVERS, PANEL_32INCH, DisplayGeometry, Driver, Panel
92
+ from .rects import (Rect, align_to_quantum, apply_region_count_limit,
93
+ detect_changes, is_aligned, join_contours, limit_regions,
94
+ unite_overlapping_regions)
95
+
96
+ __all__ = [
97
+ # the interface the rest of the library codes against
98
+ "encode_frame",
99
+ # screen-space partial updates (opt-in; see pyvisionect.imaging.partial)
100
+ "encode_partial_frame",
101
+ "DirtyTracker",
102
+ "PartialPolicy",
103
+ "decode_image_packet",
104
+ "DecodedFrame",
105
+ "EncodedFrame",
106
+ "EncodedRect",
107
+ "FrameState",
108
+ # panels / drivers (may move to pyvisionect.devices and be re-exported)
109
+ "Panel",
110
+ "Driver",
111
+ "DisplayGeometry",
112
+ "DRIVERS",
113
+ "PANEL_32INCH",
114
+ # constants
115
+ "Encoding",
116
+ "Dithering",
117
+ "ImageType",
118
+ "BITS_PER_PIXEL",
119
+ "ENCODING_LEVELS",
120
+ "LEVEL_STEP",
121
+ "ALIGN_QUANTUM",
122
+ "RECTANGLE_UPDATE_OPTIONS_DEFAULT",
123
+ "OPTION_NORMAL_UPDATE",
124
+ "MAX_REGIONS_PER_DISPLAY",
125
+ "MAX_NO_FULL_UPDATE",
126
+ "VENDOR_DITHERING",
127
+ # building blocks
128
+ "Rect",
129
+ "detect_changes",
130
+ "unite_overlapping_regions",
131
+ "join_contours",
132
+ "apply_region_count_limit",
133
+ "limit_regions",
134
+ "align_to_quantum",
135
+ "is_aligned",
136
+ "to_grey8",
137
+ "beautify",
138
+ "quantise",
139
+ "quantise_none",
140
+ "quantise_ordered",
141
+ "quantise_floyd_steinberg",
142
+ "bayer_matrix",
143
+ "BAYER_8",
144
+ "blue_noise_matrix",
145
+ "pack",
146
+ "unpack",
147
+ "pack_1bpp",
148
+ "unpack_1bpp",
149
+ "pack_4bpp",
150
+ "unpack_4bpp",
151
+ "payload_size",
152
+ "interlace",
153
+ "deinterlace",
154
+ "interlace_1bpp",
155
+ "deinterlace_1bpp",
156
+ "interlace_4bpp",
157
+ "deinterlace_4bpp",
158
+ "INTERLACE_PAIRS",
159
+ "INTERLACE_GROUP",
160
+ "SCREEN_X_QUANTUM",
161
+ "lane_span",
162
+ "screen_span",
163
+ "lane_of_display",
164
+ "displays_of_screen",
165
+ "screen_bounds",
166
+ "screen_rects_for_canvas_rect",
167
+ "canvas_regions_for_screen_rect",
168
+ "align_screen_rect",
169
+ "align_and_unite_screen_rects",
170
+ "validate_screen_rect",
171
+ "encode_screen_rect",
172
+ "partial_cost",
173
+ "full_screen_cost",
174
+ "translate_to_real",
175
+ "translate_to_session",
176
+ "rotate_image",
177
+ "unrotate_image",
178
+ "mirror_image",
179
+ "xxh32",
180
+ "state_checksum",
181
+ ]
@@ -0,0 +1,114 @@
1
+ """XXHash32 -- the image *state* tag. Spec §6.1.
2
+
3
+ ``render.(*DisplaysEncoder).calculateStateImageChecksum`` (``image-state.go:1577``)
4
+ is::
5
+
6
+ dg.checksum = xxhash.Checksum32S(stateImg.Pix, 0) // :1594
7
+ if dg.checksum == 0 { dg.checksum = 1 } // :1596
8
+
9
+ i.e. **XXHash32, seed 0, over the raw 8-bit ``Pix`` bytes of the server's
10
+ state image**, with the result ``0`` remapped to ``1`` so that ``0`` can mean
11
+ "unknown". This is the value the device echoes back as ``DisplayStateCRC`` /
12
+ ``ImageChecksum``.
13
+
14
+ Two things it is **not**:
15
+
16
+ * it is not a CRC (transport-level checksums are CRC-32/IEEE -- spec §6.4);
17
+ * it is not computed over the *encoded* data, but over the un-encoded 8-bit
18
+ model of what the panel shows.
19
+
20
+ Getting it wrong makes the device and server disagree forever: the real server
21
+ resends a full screen whenever the echoed value differs from its own
22
+ (``checkAndPrepareIfFullScreenNeededUnlocked``, ``image-state.go:1395-1405``).
23
+
24
+ A pure-Python XXH32 is included so that ``imaging/`` needs nothing but numpy
25
+ and Pillow. If the ``xxhash`` C extension is importable it is used instead,
26
+ which is ~200x faster on a full 3.7 MB canvas; both paths are checked against
27
+ each other in the test suite.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import struct
33
+ from typing import Callable
34
+
35
+ __all__ = ["xxh32", "state_checksum", "HAVE_NATIVE_XXHASH"]
36
+
37
+ _MASK = 0xFFFFFFFF
38
+ _P1 = 2654435761
39
+ _P2 = 2246822519
40
+ _P3 = 3266489917
41
+ _P4 = 668265263
42
+ _P5 = 374761393
43
+
44
+
45
+ def _rotl(x: int, r: int) -> int:
46
+ return ((x << r) | (x >> (32 - r))) & _MASK
47
+
48
+
49
+ def _xxh32_python(data: bytes, seed: int = 0) -> int:
50
+ """Reference XXH32 (``github.com/OneOfOne/xxhash.Checksum32S`` equivalent)."""
51
+ view = memoryview(data)
52
+ n = len(view)
53
+ pos = 0
54
+ if n >= 16:
55
+ v1 = (seed + _P1 + _P2) & _MASK
56
+ v2 = (seed + _P2) & _MASK
57
+ v3 = seed & _MASK
58
+ v4 = (seed - _P1) & _MASK
59
+ unpack = struct.unpack_from
60
+ limit = n - 16
61
+ while pos <= limit:
62
+ a, b, c, d = unpack("<4I", view, pos)
63
+ v1 = (_rotl((v1 + a * _P2) & _MASK, 13) * _P1) & _MASK
64
+ v2 = (_rotl((v2 + b * _P2) & _MASK, 13) * _P1) & _MASK
65
+ v3 = (_rotl((v3 + c * _P2) & _MASK, 13) * _P1) & _MASK
66
+ v4 = (_rotl((v4 + d * _P2) & _MASK, 13) * _P1) & _MASK
67
+ pos += 16
68
+ h = (_rotl(v1, 1) + _rotl(v2, 7) + _rotl(v3, 12) + _rotl(v4, 18)) & _MASK
69
+ else:
70
+ h = (seed + _P5) & _MASK
71
+ h = (h + n) & _MASK
72
+ while n - pos >= 4:
73
+ h = (h + struct.unpack_from("<I", view, pos)[0] * _P3) & _MASK
74
+ h = (_rotl(h, 17) * _P4) & _MASK
75
+ pos += 4
76
+ while pos < n:
77
+ h = (h + view[pos] * _P5) & _MASK
78
+ h = (_rotl(h, 11) * _P1) & _MASK
79
+ pos += 1
80
+ h ^= h >> 15
81
+ h = (h * _P2) & _MASK
82
+ h ^= h >> 13
83
+ h = (h * _P3) & _MASK
84
+ h ^= h >> 16
85
+ return h
86
+
87
+
88
+ try: # pragma: no cover - depends on the environment
89
+ import xxhash as _xxhash_mod
90
+
91
+ def _xxh32_native(data: bytes, seed: int = 0) -> int:
92
+ return _xxhash_mod.xxh32(data, seed=seed).intdigest()
93
+
94
+ HAVE_NATIVE_XXHASH = True
95
+ xxh32: Callable[..., int] = _xxh32_native
96
+ except ImportError: # pragma: no cover
97
+ HAVE_NATIVE_XXHASH = False
98
+ xxh32 = _xxh32_python
99
+
100
+ #: Always available, for differential testing against :data:`xxh32`.
101
+ xxh32_python = _xxh32_python
102
+
103
+
104
+ def state_checksum(pix: bytes) -> int:
105
+ """``ImageHeader.Checksum`` for a state image's raw ``Pix`` bytes.
106
+
107
+ ``pix`` must be the contiguous, row-major, ``stride == width`` 8-bit
108
+ buffer of the whole session canvas -- exactly what Go's
109
+ ``image.NewGray(image.Rect(0, 0, w, h)).Pix`` is.
110
+
111
+ Spec §6.1: XXHash32 seed 0, with ``0`` remapped to ``1``.
112
+ """
113
+ h = xxh32(pix, 0)
114
+ return h if h != 0 else 1
@@ -0,0 +1,131 @@
1
+ """Protocol constants for the Visionect imaging path.
2
+
3
+ Every value here is cited to a section of
4
+ ``artifacts/visionect/02-imaging-framebuffer.md`` (the reverse-engineering
5
+ report), which in turn cites the vendor's Go/C sources by file:line.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from enum import IntEnum
11
+
12
+ __all__ = [
13
+ "Encoding",
14
+ "Dithering",
15
+ "ImageType",
16
+ "BITS_PER_PIXEL",
17
+ "ENCODING_LEVELS",
18
+ "LEVEL_STEP",
19
+ "ALIGN_QUANTUM",
20
+ "RECTANGLE_UPDATE_OPTIONS_DEFAULT",
21
+ "OPTION_NORMAL_UPDATE",
22
+ "MAX_REGIONS_PER_DISPLAY",
23
+ "MAX_NO_FULL_UPDATE",
24
+ "MERGE_THRESHOLD_PERCENT",
25
+ "MERGE_THRESHOLD_STEP_PERCENT",
26
+ "VENDOR_DITHERING",
27
+ ]
28
+
29
+
30
+ class Encoding(IntEnum):
31
+ """``proto.EncodingType`` -- spec §2.1.
32
+
33
+ Only ``1`` and ``4`` exist. ``0`` is ``"undefined"`` and is rejected by
34
+ the vendor's ``updateDefaultRectUnlocked`` with ``render.ErrEncoding``;
35
+ anything else is ``"unknown"`` and rejected by
36
+ ``driver.isDividableTo16BitQuants``.
37
+ """
38
+
39
+ ONE_BIT = 1
40
+ FOUR_BIT = 4
41
+
42
+
43
+ class Dithering(IntEnum):
44
+ """``common.DitheringType`` -- spec §3.1, plus one library extension.
45
+
46
+ ``0``..``3`` are the vendor's values (``common/types.go:123``):
47
+
48
+ * ``DEFAULT`` (0) -- *invalid at the encoder*. The vendor's
49
+ ``updateDefaultRectUnlocked`` returns ``render.ErrDithering`` for it
50
+ (``image-state.go:754``), and so do we.
51
+ * ``NONE`` (1) -- no dithering: plain truncation of the top nibble (4 bpp)
52
+ or an MSB threshold at 128 (1 bpp).
53
+ * ``BAYER`` (2) -- GraphicsMagick ``OrderedDitherImage``.
54
+ * ``FLOYD_STEINBERG`` (3) -- GraphicsMagick ``QuantizeImage(dither=1)``.
55
+
56
+ ``BLUE_NOISE`` (4) is **ours, not the vendor's.** It is safe to invent a
57
+ value here because *the dithering mode never appears on the wire*: the
58
+ device receives already-quantised, already-bit-packed 1 bpp/4 bpp data and
59
+ performs only waveform drive (spec §3.3). ``DitheringType`` is a
60
+ server-side-only knob, and we replace the server, so the enum is ours to
61
+ extend. Nothing downstream of :func:`pyvisionect.imaging.encode_frame`
62
+ ever sees this number.
63
+ """
64
+
65
+ DEFAULT = 0
66
+ NONE = 1
67
+ BAYER = 2
68
+ FLOYD_STEINBERG = 3
69
+ BLUE_NOISE = 4
70
+
71
+
72
+ #: The subset of :class:`Dithering` that the vendor server understands. Values
73
+ #: outside this set are library extensions (see :class:`Dithering`).
74
+ VENDOR_DITHERING = frozenset({Dithering.DEFAULT, Dithering.NONE, Dithering.BAYER,
75
+ Dithering.FLOYD_STEINBERG})
76
+
77
+
78
+ class ImageType(IntEnum):
79
+ """``proto.VimageType`` -- spec §2.2. Only ``GRAY`` is meaningful."""
80
+
81
+ UNKNOWN = 0
82
+ GRAY = 1
83
+
84
+
85
+ #: Bits per pixel on the wire, per encoding. Spec §2.3.
86
+ BITS_PER_PIXEL: dict[int, int] = {Encoding.ONE_BIT: 1, Encoding.FOUR_BIT: 4}
87
+
88
+ #: Grey levels per encoding -- ``driver.encodingLevels``, ``encode.go:17``:
89
+ #: ``2 ** (1 if enc == 1 else 4)``. Spec §2.1.
90
+ ENCODING_LEVELS: dict[int, int] = {Encoding.ONE_BIT: 2, Encoding.FOUR_BIT: 16}
91
+
92
+ #: Distance between adjacent output levels in 8-bit grey. 4 bpp nibble ``n``
93
+ #: decodes to ``n * 17`` (``decode_four_to_eight``), 1 bpp bit ``b`` decodes to
94
+ #: ``b * 255`` (``decode_one_to_eight``). Spec §2.3.
95
+ LEVEL_STEP: dict[int, int] = {Encoding.ONE_BIT: 255, Encoding.FOUR_BIT: 17}
96
+
97
+ #: Sub-pixels per 16-bit word -- ``noSubpixelsIn16BitQuant``,
98
+ #: ``sixteen-bit-limitation.go:15``: ``16 // bpp``. The constraint is on
99
+ #: ``width * height``, not on width alone, because the packer runs linearly
100
+ #: over the whole rectangle with no row padding. Spec §2.4.
101
+ ALIGN_QUANTUM: dict[int, int] = {Encoding.ONE_BIT: 16, Encoding.FOUR_BIT: 4}
102
+
103
+ #: ``packet.(*RectangleHeader).MarshalBinaryTo`` substitutes these when
104
+ #: ``RectangleUpdateOptions == 0`` (``packet/image.go:271-277``). Spec §1.2.
105
+ RECTANGLE_UPDATE_OPTIONS_DEFAULT: dict[int, int] = {
106
+ Encoding.ONE_BIT: 0x0101,
107
+ Encoding.FOUR_BIT: 0x0102,
108
+ }
109
+
110
+ #: ``RectangleHeader.Options`` bit 1 is the "normal update" bit. The server
111
+ #: *clears* it on every rectangle of one full-screen packet to request an
112
+ #: inverse / ghost-clearing refresh (``image-state.go:1519-1522``). Spec §1.4,
113
+ #: §5. Verified on hardware: with the bit clear the firmware logs ``inv: 1``
114
+ #: and ``Force Inverse and full area update``, with it set ``inv: 0``. Since
115
+ #: the vendor ships ``RectangleFlags = 0``, the default is to invert on *every*
116
+ #: full-screen push.
117
+ OPTION_NORMAL_UPDATE = 0x0002
118
+
119
+ #: ``maxRegions`` -- hard constant in ``displayRects.update``
120
+ #: (``image-state.go:221``). Spec §4.1.
121
+ MAX_REGIONS_PER_DISPLAY = 15
122
+
123
+ #: ``noFullUpdateMax`` -- at most this many partial updates between full ones
124
+ #: (``vss/cmd/engine/client.go:217``). Informational; the caller owns the
125
+ #: counter, this module is stateless about it. Spec §1.8.
126
+ MAX_NO_FULL_UPDATE = 10
127
+
128
+ #: ``MergeRegions`` defaults, as **percentages of the display diagonal**
129
+ #: (``image-state.go:234-235``, ``NewMergeParameters``). Spec §4.1.
130
+ MERGE_THRESHOLD_PERCENT = 5.0
131
+ MERGE_THRESHOLD_STEP_PERCENT = 10.0
@@ -0,0 +1,172 @@
1
+ """Wire rectangles -> canvas. The inverse of :func:`encode_frame`.
2
+
3
+ This is the vendor's own preview path, ``liveview.DeviceView.Update``
4
+ (``device-view.go:89-158``): de-interlace, nibble-decode, un-mirror, blit per
5
+ display. It is exercised byte-exactly by
6
+ ``tests/imaging/test_golden_capture.py``, which decodes the captured 1.84 MB
7
+ push and gets the original canvas back.
8
+
9
+ What it can and cannot give you back
10
+ ------------------------------------
11
+
12
+ The device holds the **post-dither, post-pack** form of a frame, so a decode
13
+ gives you exactly the 16-level image the panel was driven with -- never the
14
+ source photograph. Against the rectangles we encoded, though, the round trip
15
+ is exact: same bytes in, same canvas out.
16
+
17
+ ``full_canvas`` wants a frame that covers the canvas
18
+ ----------------------------------------------------
19
+
20
+ A full-screen push on the 32" sign is two interlaced 2880x640 rectangles that
21
+ unfold into four 1440x640 bands. A *partial* rectangle addressed in screen
22
+ coordinates (``OPEN-QUESTIONS.md`` A10) decodes to its own tile but says
23
+ nothing about the rest of the canvas, so :func:`decode_image_packet` leaves
24
+ the uncovered area at *background* and reports what it covered rather than
25
+ pretending to a full picture.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from dataclasses import dataclass, field
31
+
32
+ import numpy as np
33
+
34
+ from .interlace import deinterlace, interlace_pairs
35
+ from .pack import unpack
36
+ from .panel import Panel
37
+ from .geometry import mirror_image
38
+
39
+ __all__ = ["DecodedFrame", "decode_image_packet"]
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class DecodedFrame:
44
+ """The pixels a device was sent, plus what was actually covered."""
45
+
46
+ canvas: np.ndarray
47
+ """``(canvas_height, canvas_width)`` uint8, on the ``n * 17`` ramp."""
48
+
49
+ covered: tuple[tuple[int, int, int, int], ...] = ()
50
+ """``(x, y, w, h)`` canvas-space boxes this frame actually wrote."""
51
+
52
+ full: bool = False
53
+ """Whether the covered boxes account for the whole canvas."""
54
+
55
+ screens: tuple[int, ...] = field(default=())
56
+ """The ``ScreenID``s the packet addressed."""
57
+
58
+ @property
59
+ def shape(self) -> tuple[int, int]:
60
+ return self.canvas.shape # type: ignore[return-value]
61
+
62
+ def to_image(self):
63
+ """A PIL ``L`` image. Needs Pillow."""
64
+ from PIL import Image
65
+
66
+ return Image.fromarray(self.canvas, "L")
67
+
68
+
69
+ def _bands(panel: Panel) -> int:
70
+ return panel.displays
71
+
72
+
73
+ def decode_image_packet(
74
+ packet, panel: Panel, *, background: int = 0xFF
75
+ ) -> DecodedFrame:
76
+ """Rebuild the canvas from an :class:`~pyvisionect.packets.image.ImagePacket`.
77
+
78
+ Accepts anything with ``.rectangles``, each exposing ``screen_id``, ``x``,
79
+ ``y``, ``width``, ``height``, ``encoding`` and ``data`` -- so it takes a
80
+ packet decoded off the wire, one read back out of a ``.pv2`` file, or one
81
+ you built yourself.
82
+
83
+ Args:
84
+ packet: the image packet.
85
+ panel: the geometry to rebuild into. Pass the same panel the frame was
86
+ encoded for; :func:`pyvisionect.devices.panel_for` gives you the
87
+ right one from the device's ``DisplayType``.
88
+ background: fill for anything the frame did not cover. ``0xFF`` is
89
+ white, the paper colour.
90
+
91
+ Raises:
92
+ ValueError: if a rectangle's payload is not the size its geometry
93
+ implies, or if an interlaced frame is missing a screen's half.
94
+ """
95
+ panel = Panel.adapt(panel)
96
+ canvas = np.full(panel.canvas_shape, background, dtype=np.uint8)
97
+ mirror = bool(getattr(panel.driver, "mirror", False))
98
+ mode = panel.interlace_mode
99
+ band_h = panel.rotated_height
100
+ covered: list[tuple[int, int, int, int]] = []
101
+ screens: list[int] = []
102
+
103
+ by_screen = {}
104
+ for rect in packet.rectangles:
105
+ by_screen.setdefault(int(rect.screen_id), []).append(rect)
106
+ screens.append(int(rect.screen_id))
107
+
108
+ if mode:
109
+ pairs = dict(interlace_pairs(mode))
110
+ for screen_id, rects in sorted(by_screen.items()):
111
+ lanes = pairs.get(screen_id)
112
+ if lanes is None:
113
+ raise ValueError(
114
+ f"interlacing mode {mode} has no lane pair for ScreenID "
115
+ f"{screen_id}; known screens are {sorted(pairs)}"
116
+ )
117
+ for rect in rects:
118
+ # A screen-space rectangle is 2x as wide as each lane's tile.
119
+ lane_w, lane_h = rect.width // 2, rect.height
120
+ a, b = deinterlace(rect.data, int(rect.encoding))
121
+ for lane_data, display in zip((a, b), lanes):
122
+ tile = unpack(
123
+ lane_data, int(rect.encoding), lane_w * lane_h
124
+ )
125
+ if tile.size != lane_w * lane_h:
126
+ raise ValueError(
127
+ f"ScreenID {screen_id} lane for display {display} "
128
+ f"has {tile.size} pixels, expected "
129
+ f"{lane_w * lane_h} for {lane_w}x{lane_h}"
130
+ )
131
+ tile = tile.reshape(lane_h, lane_w)
132
+ # The eink-flip mirror is applied to the whole display
133
+ # row, so a sub-rectangle lands mirrored about the
134
+ # display's own width, not its own.
135
+ x0 = (
136
+ panel.rotated_width - (rect.x // 2) - lane_w
137
+ if mirror
138
+ else rect.x // 2
139
+ )
140
+ y0 = display * band_h + rect.y
141
+ canvas[y0 : y0 + lane_h, x0 : x0 + lane_w] = (
142
+ mirror_image(tile) if mirror else tile
143
+ )
144
+ covered.append((x0, y0, lane_w, lane_h))
145
+ else:
146
+ for screen_id, rects in sorted(by_screen.items()):
147
+ for rect in rects:
148
+ pixels = unpack(
149
+ rect.data, int(rect.encoding), rect.width * rect.height
150
+ )
151
+ if pixels.size != rect.width * rect.height:
152
+ raise ValueError(
153
+ f"ScreenID {screen_id} rectangle has {pixels.size} "
154
+ f"pixels, expected {rect.width * rect.height}"
155
+ )
156
+ tile = pixels.reshape(rect.height, rect.width)
157
+ x0 = (
158
+ panel.rotated_width - rect.x - rect.width if mirror else rect.x
159
+ )
160
+ y0 = screen_id * band_h + rect.y
161
+ canvas[y0 : y0 + rect.height, x0 : x0 + rect.width] = (
162
+ mirror_image(tile) if mirror else tile
163
+ )
164
+ covered.append((x0, y0, rect.width, rect.height))
165
+
166
+ area = sum(w * h for _x, _y, w, h in covered)
167
+ return DecodedFrame(
168
+ canvas=canvas,
169
+ covered=tuple(covered),
170
+ full=area >= panel.canvas_width * panel.canvas_height,
171
+ screens=tuple(sorted(set(screens))),
172
+ )