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,931 @@
1
+ """Screen-space partial updates: dirty-region tracking for the interlaced sign.
2
+
3
+ **Opt-in, per-device, and not vendor-sanctioned.** The vendor's server never
4
+ sends ``HardwareNameID 8`` a partial rectangle -- ``getRectangleSupport``
5
+ returns false for it unconditionally (``vss/cmd/engine/client.go:41``) -- so
6
+ there is no vendor behaviour here to match and none to fall back on. What
7
+ there is instead is a hand-run experiment on one physical sign: 17 pushes, 17
8
+ acks, zero NACKs, the firmware echoing our rectangle headers back verbatim, and
9
+ the device's ``DisplayStateCRC`` equal to our computed state checksum every
10
+ time. See ``OPEN-QUESTIONS.md`` A10.
11
+
12
+ What it buys
13
+ ------------
14
+ **Bytes and encode time. Not latency.** Measured on the sign from the
15
+ firmware's own ``Profiling:`` line:
16
+
17
+ ==================================== =============== =========== ==========
18
+ push wire (``Pv2Len``) raw bytes ``EpdUpd``
19
+ ==================================== =============== =========== ==========
20
+ full screen, steady state 77 613 1 843 200 2 916 ms
21
+ ``2880 x 128`` strip 2 143 184 320 2 908 ms
22
+ ``256 x 128`` block 292 16 384 2 904 ms
23
+ ==================================== =============== =========== ==========
24
+
25
+ The wire cost collapses by ~250x; the panel time does not move. ``EpdUpd`` has
26
+ a ~2.9 s floor on this panel whatever the rectangle's area. So this module is
27
+ worth having on a battery device over wifi, and for a Raspberry Pi that would
28
+ otherwise dither, pack, interlace and LZ4 1.84 MB every tick. It will **not**
29
+ make the glass refresh faster, and nothing here should be read as promising
30
+ that.
31
+
32
+ Why a canvas rectangle cannot be sent on its own
33
+ ------------------------------------------------
34
+ The sign has **2 physical screens of 2880 x 640**; the session canvas is
35
+ **1440 x 2560** in 4 bands. ``ScreenID 0`` is the 4-pixel interleave of bands
36
+ 0 and 1, ``ScreenID 1`` of bands **3 and 2** -- note the swap
37
+ (:data:`~pyvisionect.imaging.interlace.INTERLACE_PAIRS`). A band's pixels are
38
+ therefore interleaved with its partner's, and *any* screen-space rectangle
39
+ covering some of one band necessarily covers the matching rows of the other.
40
+
41
+ There is no way to say "only this lane" on the wire. So a partial update
42
+ carries the partner lane's **current, unchanged** pixels alongside the changed
43
+ ones, read back out of the state image. That is a flat 2x on payload, it is
44
+ structural, and it is not a bug to optimise away -- A10 verified it works and
45
+ leaves the partner band visually untouched.
46
+
47
+ The mapping, end to end::
48
+
49
+ canvas rect -> per band: band-local rows, canvas column range
50
+ -> lane column range (canvas col c <-> lane col 1439-c, the
51
+ eink-flip mirror)
52
+ -> snap lane columns out to the 4-px interleave group
53
+ -> screen rect: x = 2*c0, w = 2*(c1-c0), y and h unchanged
54
+ -> cut BOTH lanes of that screen from the new state image,
55
+ mirror, pack, interleave
56
+ -> one EncodedRect, screen-addressed, with that ScreenID
57
+
58
+ Ghosting
59
+ --------
60
+ E-ink accumulates ghosting under partial updates, and the vendor caps
61
+ consecutive partials at ``noFullUpdateMax = 10`` precisely for that
62
+ (``client.go:217``). The firmware enforces no such cap of its own, and --
63
+ measured, not assumed -- **it also clears nothing of its own accord**: across
64
+ eight accepted partial pushes and twelve rectangles the console showed
65
+ ``wfn: 2, inv: 0`` into one ``UPD_FULL_AREA`` per rectangle, every time, with
66
+ no unrequested ``inv: 1``, no ``Force Inverse`` and no ``UPD_FULL``. So the
67
+ policy is not a precaution, it is the only thing clearing the panel.
68
+ :class:`PartialPolicy` keeps it, defaulting to the vendor's 10, and
69
+ :class:`DirtyTracker` counts for you.
70
+
71
+ The full-screen push is where the budget is spent because that is the lever we
72
+ have evidence for: with the shipped ``RectangleFlags = 0`` the ``Options``
73
+ "normal update" bit is clear, which **requests** the inverse clearing waveform
74
+ (B1). Note *requests*: on this firmware some full pushes with byte-identical
75
+ ``inv: 1`` headers logged ``Force Inverse and full area update`` and ran 8
76
+ ``UPD_FULL`` passes while others logged nothing and ran 4 ``UPD_FULL_AREA``
77
+ passes, for reasons nobody has pinned down. That is a reason to keep the
78
+ default conservative rather than to raise it. A tracker configured never to
79
+ force a full refresh never even asks, and the panel slowly turns to mush.
80
+
81
+ Nothing here selects a waveform. ``wfn: 2`` is the only value ever observed on
82
+ this panel and no API is exposed for it.
83
+
84
+ A partial may not also ask for the clearing waveform
85
+ ---------------------------------------------------
86
+ ``RectangleHeader.Options`` bit ``0x0002`` **clear** means "inverse update"
87
+ (``OPEN-QUESTIONS.md`` B1), and the vendor ships ``RectangleFlags = 0``, so the
88
+ bit is clear on an ordinary push and the firmware runs its clearing waveform.
89
+ On a rectangle smaller than the screen the firmware refuses outright::
90
+
91
+ l: (0 1168 160 512 128), enc: 0x4 pde: 0x0, te: 0x0
92
+ u: (0 1168 160 512 128), wfn: 2, dum: 1, inv: 1
93
+ Image download completed (0 0)
94
+ Skip image update: partial image not allowed
95
+ -> NACK, ErrorCode 0x06000000
96
+
97
+ Which is reasonable: an inverse clearing refresh drives the whole panel, so
98
+ "clear only this rectangle" is not a thing the waveform can do. Measured on
99
+ the sign on 2026-10-05; with bit ``0x0002`` **set** the same rectangle acks and
100
+ draws. So :func:`encode_partial_frame` **always sets the bit on a partial
101
+ rectangle**, whatever ``rect_options`` says, and leaves ``rect_options``
102
+ untouched on the full-screen fallback -- which is where you *want* the clearing
103
+ waveform, and is what makes the ghosting budget work.
104
+
105
+ Checksums
106
+ ---------
107
+ ``ImageHeader.Checksum`` is XXHash32 over the **whole 8-bit canvas state**, not
108
+ over the rectangle. A partial that does not fold its own pixels into the state
109
+ image before hashing will disagree with the device's echoed
110
+ ``DisplayStateCRC`` forever, and the vendor's own recovery for that is a
111
+ redundant full-screen redraw. :func:`encode_partial_frame` updates the state
112
+ and hashes the whole canvas, exactly as a full push does.
113
+ """
114
+
115
+ from __future__ import annotations
116
+
117
+ from dataclasses import dataclass, replace
118
+ from typing import Any, Optional, Sequence
119
+
120
+ import numpy as np
121
+
122
+ from .checksum import state_checksum
123
+ from .constants import (MAX_NO_FULL_UPDATE, MAX_REGIONS_PER_DISPLAY,
124
+ OPTION_NORMAL_UPDATE,
125
+ RECTANGLE_UPDATE_OPTIONS_DEFAULT, Dithering,
126
+ ImageType)
127
+ from .encoder import EncodedFrame, EncodedRect, FrameState, _validate
128
+ from .encoder import encode_frame as _encode_frame
129
+ from .geometry import mirror_image
130
+ from .grey import beautify as _beautify
131
+ from .grey import to_grey8
132
+ from .interlace import (INTERLACE_GROUP, SCREEN_X_QUANTUM, displays_of_screen,
133
+ interlace, lane_of_display, lane_span)
134
+ from .dither import is_pixel_local as _is_pixel_local
135
+ from .dither import quantise as _quantise
136
+ from .pack import pack as _pack
137
+ from .pack import payload_size as _payload_size
138
+ from .panel import Panel
139
+ from .rects import (Rect, detect_changes, is_aligned, limit_regions,
140
+ unite_overlapping_regions)
141
+
142
+ __all__ = [
143
+ "PartialPolicy",
144
+ "DirtyTracker",
145
+ "encode_partial_frame",
146
+ "encode_screen_rect",
147
+ "screen_bounds",
148
+ "screen_rects_for_canvas_rect",
149
+ "canvas_regions_for_screen_rect",
150
+ "align_screen_rect",
151
+ "align_and_unite_screen_rects",
152
+ "validate_screen_rect",
153
+ "partial_cost",
154
+ "full_screen_cost",
155
+ ]
156
+
157
+ #: Bytes of ``RectangleHeader`` in front of every rectangle's payload
158
+ #: (spec §1.1). Counted into the cost comparison so that "many small
159
+ #: rectangles" is not free.
160
+ RECTANGLE_HEADER_BYTES = 24
161
+
162
+
163
+ # --------------------------------------------------------------------------
164
+ # policy
165
+ # --------------------------------------------------------------------------
166
+
167
+ @dataclass(frozen=True)
168
+ class PartialPolicy:
169
+ """When to give up on a partial and push the whole screen instead.
170
+
171
+ :param max_consecutive_partials: force a full-screen push once this many
172
+ partials have gone out since the last full one. The default is the
173
+ vendor's ``noFullUpdateMax`` (``client.go:217``). This is the
174
+ **ghosting budget** and the full-screen push is what spends it: with
175
+ the shipped ``RectangleFlags = 0`` the firmware runs its inverse
176
+ clearing waveform on every full-screen update (``OPEN-QUESTIONS.md``
177
+ B1). Set it to ``0`` to disable partials entirely; set it to a
178
+ negative number to never force a refresh, which is a decision about
179
+ your panel's lifetime and not a thing to do casually.
180
+ :param max_cost_fraction: fall back when the partial's wire cost (payloads
181
+ plus rectangle headers, *including* the 2x partner-lane cost) reaches
182
+ this fraction of a full-screen push's. Many scattered rectangles cost
183
+ more than one full push; past roughly half there is nothing left to
184
+ win and a full push also clears ghosting for free.
185
+ """
186
+
187
+ max_consecutive_partials: int = MAX_NO_FULL_UPDATE
188
+ max_cost_fraction: float = 0.5
189
+
190
+ def __post_init__(self) -> None:
191
+ if not 0.0 < self.max_cost_fraction <= 1.0:
192
+ raise ValueError(
193
+ f"max_cost_fraction must be in (0, 1], got "
194
+ f"{self.max_cost_fraction!r}"
195
+ )
196
+
197
+ def refresh_due(self, consecutive_partials: int) -> bool:
198
+ """Whether the ghosting counter has tripped."""
199
+ if self.max_consecutive_partials < 0:
200
+ return False
201
+ return consecutive_partials >= self.max_consecutive_partials
202
+
203
+
204
+ # --------------------------------------------------------------------------
205
+ # screen-space geometry
206
+ # --------------------------------------------------------------------------
207
+
208
+ def screen_bounds(panel: Panel) -> Rect:
209
+ """The in-bounds region for a screen-space rectangle on this panel.
210
+
211
+ ``2880 x 640`` on the 32" sign. Rectangles are validated against this and
212
+ **refused** rather than clamped: whether the firmware clamps, refuses, or
213
+ writes past its framebuffer on an out-of-bounds rectangle is deliberately
214
+ unmeasured (``OPEN-QUESTIONS.md`` A10, "Still unknown"), and probing a
215
+ memory-safety edge on hardware in daily use was not worth it.
216
+ """
217
+ panel = Panel.adapt(panel)
218
+ return Rect(0, 0, panel.screen_width, panel.screen_height)
219
+
220
+
221
+ def validate_screen_rect(screen_id: int, rect: Rect, panel: Panel,
222
+ encoding: int) -> None:
223
+ """Refuse a screen rectangle the device could not safely be sent.
224
+
225
+ :raises ValueError: if the panel has no such ``ScreenID``, if the
226
+ rectangle leaves :func:`screen_bounds`, if its ``x``/``width`` are not
227
+ multiples of :data:`~pyvisionect.imaging.interlace.SCREEN_X_QUANTUM`,
228
+ or if ``width * height`` does not divide the 16-bit quantum.
229
+ """
230
+ panel = Panel.adapt(panel)
231
+ if not panel.supports_screen_rectangles:
232
+ raise ValueError(
233
+ f"panel {panel.width}x{panel.height}x{panel.displays} "
234
+ f"(interlace mode {panel.interlace_mode}, rotation "
235
+ f"{panel.rotation}) cannot address screen-space rectangles"
236
+ )
237
+ displays_of_screen(panel.interlace_mode, int(screen_id))
238
+ bounds = screen_bounds(panel)
239
+ if rect.is_empty:
240
+ raise ValueError(f"empty screen rectangle {rect!r}")
241
+ if (rect.x < 0 or rect.y < 0 or rect.far_x > bounds.far_x
242
+ or rect.far_y > bounds.far_y):
243
+ raise ValueError(
244
+ f"screen rectangle {rect!r} leaves the panel bounds {bounds!r}; "
245
+ "refusing to send it -- out-of-bounds rectangles were never "
246
+ "probed on hardware and the firmware's reaction is unknown"
247
+ )
248
+ if rect.x % SCREEN_X_QUANTUM or rect.width % SCREEN_X_QUANTUM:
249
+ raise ValueError(
250
+ f"screen rectangle {rect!r} needs x and width to be multiples of "
251
+ f"{SCREEN_X_QUANTUM} so the interleave lanes stay paired"
252
+ )
253
+ if not is_aligned(rect, encoding):
254
+ raise ValueError(
255
+ f"screen rectangle {rect!r} has width*height = "
256
+ f"{rect.width * rect.height}, which does not divide the 16-bit "
257
+ f"quantum for encoding {int(encoding)} (spec §2.4)"
258
+ )
259
+
260
+
261
+ def align_screen_rect(rect: Rect, encoding: int, bounds: Rect) -> Rect:
262
+ """Grow a screen rectangle until it is legal, inside ``bounds``.
263
+
264
+ Two constraints, in order:
265
+
266
+ 1. ``x`` and ``width`` snap out to multiples of
267
+ :data:`~pyvisionect.imaging.interlace.SCREEN_X_QUANTUM` (8), so the
268
+ rectangle starts on an even interleave group and ends on a whole pair.
269
+ 2. ``width * height`` must then divide the 16-bit quantum
270
+ (:func:`~pyvisionect.imaging.rects.is_aligned`). At 4 bpp step 1
271
+ already guarantees it. At 1 bpp the quantum is 16 sub-pixels, so an
272
+ **odd height** additionally needs ``width`` to be a multiple of 16; one
273
+ more 8-pixel growth always supplies that.
274
+
275
+ Growth prefers to extend right, falling back to left -- the same
276
+ [INFERRED] order :func:`~pyvisionect.imaging.rects.align_to_quantum` uses
277
+ for canvas rectangles, kept the same so the two cannot drift.
278
+
279
+ :raises ValueError: if no legal rectangle containing ``rect`` fits in
280
+ ``bounds``.
281
+ """
282
+ clipped = rect.intersection(bounds)
283
+ if clipped is None:
284
+ raise ValueError(f"screen rectangle {rect!r} is outside {bounds!r}")
285
+ x0 = clipped.x - (clipped.x - bounds.x) % SCREEN_X_QUANTUM
286
+ far = clipped.far_x + -(clipped.far_x - bounds.x) % SCREEN_X_QUANTUM
287
+ far = min(far, bounds.far_x)
288
+ out = Rect(x0, clipped.y, far - x0, clipped.height)
289
+ while not is_aligned(out, encoding):
290
+ if out.far_x + SCREEN_X_QUANTUM <= bounds.far_x:
291
+ out = replace(out, width=out.width + SCREEN_X_QUANTUM)
292
+ elif out.x - SCREEN_X_QUANTUM >= bounds.x:
293
+ out = Rect(out.x - SCREEN_X_QUANTUM, out.y,
294
+ out.width + SCREEN_X_QUANTUM, out.height)
295
+ else:
296
+ raise ValueError(
297
+ f"screen rectangle {rect!r} cannot be aligned to the 16-bit "
298
+ f"quantum for encoding {int(encoding)} inside {bounds!r}"
299
+ )
300
+ return out
301
+
302
+
303
+ def align_and_unite_screen_rects(rects: Sequence[Rect], encoding: int,
304
+ bounds: Rect) -> list[Rect]:
305
+ """Align every screen rectangle, then re-unite the overlaps that created.
306
+
307
+ Growing two neighbours to the quantum can make them overlap, and sending
308
+ the same pixels twice in one packet is at best wasteful. Uniting can in
309
+ turn un-align the result -- a union's height is neither input's -- so this
310
+ iterates to a fixpoint. It converges in one or two passes in practice,
311
+ and the bound is here so a pathological input cannot spin.
312
+
313
+ :raises ValueError: if a rectangle cannot be aligned inside ``bounds``, or
314
+ if align/unite does not settle.
315
+ """
316
+ out = list(rects)
317
+ for _ in range(8):
318
+ aligned = [align_screen_rect(r, encoding, bounds) for r in out]
319
+ united = unite_overlapping_regions(aligned, area_criteria=False)
320
+ if united == aligned:
321
+ return aligned
322
+ out = united
323
+ raise ValueError(
324
+ f"screen rectangles {list(rects)!r} did not settle into an aligned, "
325
+ f"non-overlapping set inside {bounds!r}"
326
+ )
327
+
328
+
329
+ def screen_rects_for_canvas_rect(
330
+ rect: Rect, panel: Panel
331
+ ) -> list[tuple[int, Rect]]:
332
+ """Map one canvas rectangle to the screen rectangles that cover it.
333
+
334
+ One per band the input touches, so a rectangle straddling a band seam
335
+ yields two (and one spanning the whole canvas yields four, two per
336
+ ``ScreenID``). The returned rectangles are **not** merged or aligned;
337
+ :func:`encode_partial_frame` does both.
338
+
339
+ Each result covers more than it was asked to: the partner lane's matching
340
+ rows, always, and up to 3 extra lane columns on each side from the
341
+ interleave-group snap. Those pixels are re-sent unchanged, which is why
342
+ the caller must cut them from the state image and not from thin air.
343
+
344
+ :returns: ``[(screen_id, screen_rect), ...]``, in band order.
345
+ """
346
+ panel = Panel.adapt(panel)
347
+ if not panel.supports_screen_rectangles:
348
+ raise ValueError(
349
+ f"panel with interlacing mode {panel.interlace_mode} and rotation "
350
+ f"{panel.rotation} has no screen-space addressing"
351
+ )
352
+ mirror = bool(panel.driver.mirror) # type: ignore[union-attr]
353
+ band_h = panel.rotated_height
354
+ lane_w = panel.rotated_width
355
+ out: list[tuple[int, Rect]] = []
356
+ for display in range(panel.displays):
357
+ band = Rect(0, display * band_h, lane_w, band_h)
358
+ part = rect.intersection(band)
359
+ if part is None:
360
+ continue
361
+ screen_id, _lane = lane_of_display(panel.interlace_mode, display)
362
+ # canvas columns -> lane columns (the eink-flip mirror is applied to
363
+ # the whole display row, so it reverses the column order)
364
+ if mirror:
365
+ c0, c1 = lane_w - part.far_x, lane_w - part.x
366
+ else:
367
+ c0, c1 = part.x, part.far_x
368
+ # snap out to whole interleave groups so lane_span() accepts it
369
+ c0 -= c0 % INTERLACE_GROUP
370
+ c1 += -c1 % INTERLACE_GROUP
371
+ c1 = min(c1, lane_w)
372
+ sx, sw = c0 * 2, (c1 - c0) * 2
373
+ out.append((screen_id, Rect(sx, part.y - display * band_h, sw,
374
+ part.height)))
375
+ return out
376
+
377
+
378
+ def canvas_regions_for_screen_rect(
379
+ screen_id: int, rect: Rect, panel: Panel
380
+ ) -> tuple[tuple[int, Rect], ...]:
381
+ """Inverse of :func:`screen_rects_for_canvas_rect`, for one screen rect.
382
+
383
+ :returns: ``((display, canvas_rect), (display, canvas_rect))`` -- always
384
+ exactly two, lane A first, because a screen rectangle always lands on
385
+ both of its screen's bands.
386
+ """
387
+ panel = Panel.adapt(panel)
388
+ lanes = displays_of_screen(panel.interlace_mode, int(screen_id))
389
+ c0, c1 = lane_span(rect.x, rect.width)
390
+ lane_w = panel.rotated_width
391
+ band_h = panel.rotated_height
392
+ if bool(panel.driver.mirror): # type: ignore[union-attr]
393
+ x0, x1 = lane_w - c1, lane_w - c0
394
+ else:
395
+ x0, x1 = c0, c1
396
+ return tuple(
397
+ (display, Rect(x0, display * band_h + rect.y, x1 - x0, rect.height))
398
+ for display in lanes
399
+ )
400
+
401
+
402
+ # --------------------------------------------------------------------------
403
+ # cost accounting
404
+ # --------------------------------------------------------------------------
405
+
406
+ def full_screen_cost(panel: Panel, encoding: int) -> int:
407
+ """Wire bytes of a full-screen push: payloads plus rectangle headers.
408
+
409
+ ``2 x (24 + 921600) = 1 843 248`` for the 32" sign at 4 bpp. This is the
410
+ *uncompressed* figure; LZ4 shrinks both sides of the comparison and does
411
+ not shrink them equally, but a partial that is already a fraction of the
412
+ full raw size is a fraction of the compressed size too.
413
+ """
414
+ panel = Panel.adapt(panel)
415
+ per_screen = _payload_size(panel.screen_width, panel.screen_height,
416
+ encoding)
417
+ return panel.screens * (RECTANGLE_HEADER_BYTES + per_screen)
418
+
419
+
420
+ def partial_cost(rects: Sequence[EncodedRect]) -> int:
421
+ """Wire bytes of a rectangle list: payloads plus rectangle headers."""
422
+ return sum(RECTANGLE_HEADER_BYTES + len(r.data) for r in rects)
423
+
424
+
425
+ # --------------------------------------------------------------------------
426
+ # payload construction
427
+ # --------------------------------------------------------------------------
428
+
429
+ def encode_screen_rect(
430
+ state_grey: np.ndarray,
431
+ *,
432
+ screen_id: int,
433
+ rect: Rect,
434
+ panel: Panel,
435
+ encoding: int,
436
+ options: int = 0,
437
+ image_type: int = int(ImageType.GRAY),
438
+ rectangle_update_options: Optional[int] = None,
439
+ dithering: int = int(Dithering.NONE),
440
+ ) -> EncodedRect:
441
+ """Build one screen-addressed :class:`~.encoder.EncodedRect` from a state image.
442
+
443
+ Both lanes of ``screen_id`` are cut from ``state_grey`` at the same
444
+ band-local rows and lane columns, mirrored if the driver mirrors, packed,
445
+ and interleaved. Pixels that are not changing are therefore re-sent as
446
+ they already are -- which is exactly what the partner lane needs.
447
+
448
+ ``state_grey`` must already hold the pixels you want on the glass, on the
449
+ output ramp (``n * 17`` at 4 bpp, ``0``/``255`` at 1 bpp). Packing is
450
+ idempotent on that ramp, so a region cut from the state re-encodes to the
451
+ same bytes a full push would have carried for it.
452
+
453
+ :param state_grey: the full ``(canvas_height, canvas_width)`` 8-bit state.
454
+ :raises ValueError: via :func:`validate_screen_rect`, or if the resulting
455
+ payload is not the length the geometry implies (a library bug, not a
456
+ caller error).
457
+ """
458
+ panel = Panel.adapt(panel)
459
+ enc = int(encoding)
460
+ validate_screen_rect(screen_id, rect, panel, enc)
461
+ state = np.asarray(state_grey, dtype=np.uint8)
462
+ if state.shape != panel.canvas_shape:
463
+ raise ValueError(
464
+ f"state image is {state.shape[1]}x{state.shape[0]} but panel "
465
+ f"canvas is {panel.canvas_width}x{panel.canvas_height}"
466
+ )
467
+ mirror = bool(panel.driver.mirror) # type: ignore[union-attr]
468
+ c0, c1 = lane_span(rect.x, rect.width)
469
+ band_h = panel.rotated_height
470
+ halves: list[bytes] = []
471
+ for display in displays_of_screen(panel.interlace_mode, int(screen_id)):
472
+ y0 = display * band_h + rect.y
473
+ rows = state[y0:y0 + rect.height]
474
+ lane = mirror_image(rows) if mirror else rows
475
+ halves.append(_pack(np.ascontiguousarray(lane[:, c0:c1]), enc))
476
+ data = interlace(halves[0], halves[1], enc)
477
+ want = _payload_size(rect.width, rect.height, enc)
478
+ if len(data) != want:
479
+ raise ValueError(
480
+ f"interlaced payload for {rect!r} is {len(data)} bytes, geometry "
481
+ f"implies {want}; this is a bug in pyvisionect, not in your call"
482
+ )
483
+ ruo = (RECTANGLE_UPDATE_OPTIONS_DEFAULT[enc]
484
+ if rectangle_update_options is None else int(rectangle_update_options))
485
+ return EncodedRect(
486
+ x=rect.x, y=rect.y, w=rect.width, h=rect.height,
487
+ screen_id=int(screen_id), options=int(options), data=data,
488
+ encoding=enc, image_type=int(image_type),
489
+ rectangle_update_options=ruo, dithering=int(dithering),
490
+ )
491
+
492
+
493
+ def _apply_to_state(state: np.ndarray, grey: np.ndarray,
494
+ dirty: Sequence[Rect], panel: Panel, enc: int, dith: int,
495
+ *, bayer: Optional[np.ndarray],
496
+ blue_noise: Optional[np.ndarray],
497
+ dither_levels: Optional[int]) -> None:
498
+ """Fold the dirty regions' new pixels into the state image, in place.
499
+
500
+ Mirrors :func:`~.encoder.encode_frame`'s own state bookkeeping, with one
501
+ deliberate difference that is the whole point of a partial: the dither runs
502
+ on the **dirty slice only**, not on the canvas.
503
+
504
+ For a pixel-local dither that is free. The threshold matrix is phased on
505
+ the canvas coordinate, so passing the slice's canvas origin produces byte
506
+ for byte what quantising the whole canvas and cutting the slice out of it
507
+ would -- which is also exactly what keeps partials from seaming against
508
+ their neighbours. Quantising 300x120 pixels instead of 1440x2560 is where
509
+ most of the encode-time saving comes from.
510
+
511
+ Floyd-Steinberg is **not** pixel-local: the error that reaches a pixel
512
+ depends on everything above and left of it. It is run per band-slice on
513
+ the mirrored tile, the way a full push runs it per display, and a partial
514
+ *will* differ from a full push's pixels under it. The partial stays
515
+ self-consistent -- its state and checksum describe the bytes it sent -- so
516
+ the device never notices, but neighbouring regions can seam visibly.
517
+ """
518
+ mirror = bool(panel.driver.mirror) # type: ignore[union-attr]
519
+ band_h = panel.rotated_height
520
+ lane_w = panel.rotated_width
521
+ pixel_local = _is_pixel_local(dith)
522
+ for rect in dirty:
523
+ for display in range(panel.displays):
524
+ band = Rect(0, display * band_h, lane_w, band_h)
525
+ part = rect.intersection(band)
526
+ if part is None:
527
+ continue
528
+ rows, cols = part.as_slice()
529
+ if pixel_local:
530
+ state[rows, cols] = _quantise(
531
+ grey[rows, cols], enc, dith, origin=(part.y, part.x),
532
+ bayer=bayer, blue_noise=blue_noise, levels=dither_levels,
533
+ )
534
+ continue
535
+ tile = grey[rows, cols]
536
+ if mirror:
537
+ tile = mirror_image(tile)
538
+ tile = _quantise(tile, enc, dith, levels=dither_levels)
539
+ state[rows, cols] = mirror_image(tile) if mirror else tile
540
+
541
+
542
+ # --------------------------------------------------------------------------
543
+ # the encoder
544
+ # --------------------------------------------------------------------------
545
+
546
+ def encode_partial_frame(
547
+ img: Any,
548
+ *,
549
+ panel: Panel,
550
+ encoding: int,
551
+ dithering: int,
552
+ prev_state: Optional[FrameState],
553
+ rects: Optional[Sequence[Rect]] = None,
554
+ policy: Optional[PartialPolicy] = None,
555
+ consecutive_partials: int = 0,
556
+ inverse: bool = False,
557
+ rect_options: int = 0,
558
+ image_type: int = int(ImageType.GRAY),
559
+ rectangle_update_options: Optional[int] = None,
560
+ change_threshold: float = 0.0,
561
+ merge_regions: bool = True,
562
+ max_regions: int = MAX_REGIONS_PER_DISPLAY,
563
+ force_full_screen: bool = False,
564
+ beautify: bool = False,
565
+ beautify_gamma: float = 1.1,
566
+ bayer_matrix: Optional[np.ndarray] = None,
567
+ blue_noise_matrix: Optional[np.ndarray] = None,
568
+ dither_levels: Optional[int] = None,
569
+ ) -> EncodedFrame:
570
+ """Encode only what changed, as screen-space rectangles.
571
+
572
+ Same contract as :func:`~.encoder.encode_frame` -- image in, wire-ready
573
+ rectangles and a state checksum out, no I/O, no clock, pure in its
574
+ arguments -- except that the rectangles are addressed in **screen**
575
+ coordinates and cover only the dirty region plus its partner lane.
576
+
577
+ Falls back to a full-screen push, with
578
+ :attr:`~.encoder.EncodedFrame.fallback_reason` set, whenever a partial is
579
+ not possible or not worth it:
580
+
581
+ ================================ ==========================================
582
+ ``fallback_reason`` cause
583
+ ================================ ==========================================
584
+ ``"no-previous-state"`` nothing to diff against, and nothing known
585
+ about what the glass currently shows
586
+ ``"forced"`` ``force_full_screen=True``
587
+ ``"inverse"`` ``inverse=True``; the clearing waveform is
588
+ only legal full-screen (spec §1.4)
589
+ ``"re-encode"`` encoding or dithering changed, so every
590
+ pixel on the panel is stale
591
+ ``"panel-unsupported"`` the panel has no screen-space addressing
592
+ (:attr:`~.panel.Panel.supports_screen_rectangles`)
593
+ ``"ghosting-refresh-due"`` the consecutive-partial budget tripped
594
+ ``"too-many-regions"`` more dirty regions than merging allows
595
+ ``"not-worth-it"`` the partial would cost more than
596
+ ``policy.max_cost_fraction`` of a full push
597
+ ================================ ==========================================
598
+
599
+ On a panel with no interlacing (``interlace_mode == 0``) there is no fold
600
+ to work around, a canvas rectangle *is* a wire rectangle, and this
601
+ function delegates straight to :func:`~.encoder.encode_frame` with the
602
+ detected dirty rectangles -- so the ghosting policy and the dirty tracking
603
+ are usable there too. ``screen_space`` comes back False in that case.
604
+
605
+ .. warning:: **Verified on one device, by hand, and not vendor-sanctioned.**
606
+ Partial rectangles were measured working on ``HardwareNameID 8``-class
607
+ hardware only -- the 31.2" Place&Play 32, firmware 7.4.4407, hardware
608
+ revision 1.1.0 (``OPEN-QUESTIONS.md`` A10). The vendor's server never
609
+ sends this hardware a partial, so this path has no vendor
610
+ implementation behind it and no vendor support if it misbehaves. It
611
+ saves **bytes and encode time, not refresh latency**: the panel's
612
+ waveform floor is ~2.9 s regardless of area.
613
+
614
+ .. warning:: **CPU-bound and blocking**, for the same reasons
615
+ :func:`~.encoder.encode_frame` is. Never call it on an asyncio event
616
+ loop. It is cheaper than a full push -- it dithers and packs a
617
+ fraction of the canvas -- but change detection still runs over the
618
+ whole thing.
619
+
620
+ :param prev_state: the :class:`~.encoder.FrameState` from the previous
621
+ call. Required: without it there is no partner-lane content to hold
622
+ and no model of what the glass shows. ``None`` falls back to full
623
+ screen rather than raising.
624
+ :param rects: dirty rectangles in **canvas** coordinates, if you already
625
+ know them. ``None`` means change-detect against ``prev_state``.
626
+ :param rect_options: ``RectangleHeader.Options``. On a partial rectangle
627
+ the "normal update" bit :data:`~.constants.OPTION_NORMAL_UPDATE` is
628
+ **always added**, because the firmware refuses a partial that also
629
+ asks for the inverse clearing waveform (see the module docstring). On
630
+ the full-screen fallback it is passed through untouched.
631
+ :param policy: a :class:`PartialPolicy`; ``None`` uses the defaults.
632
+ :param consecutive_partials: partials pushed since the last full-screen
633
+ frame. :class:`DirtyTracker` keeps this for you.
634
+
635
+ :returns: an :class:`~.encoder.EncodedFrame`. ``rectangles`` is empty when
636
+ nothing changed; ``screen_space`` is True on a real partial.
637
+ """
638
+ panel = Panel.adapt(panel)
639
+ policy = policy or PartialPolicy()
640
+ enc, dith = _validate(encoding, dithering, panel)
641
+
642
+ def full(reason: str) -> EncodedFrame:
643
+ frame = _encode_frame(
644
+ img, panel=panel, encoding=enc, dithering=dith, rects=None,
645
+ prev_state=prev_state, inverse=inverse, rect_options=rect_options,
646
+ image_type=image_type,
647
+ rectangle_update_options=rectangle_update_options,
648
+ change_threshold=change_threshold, merge_regions=merge_regions,
649
+ max_regions=max_regions, force_full_screen=True,
650
+ beautify=beautify, beautify_gamma=beautify_gamma,
651
+ bayer_matrix=bayer_matrix, blue_noise_matrix=blue_noise_matrix,
652
+ dither_levels=dither_levels,
653
+ )
654
+ frame.fallback_reason = reason
655
+ return frame
656
+
657
+ # ---- structural gates, cheapest first ------------------------------
658
+ if force_full_screen:
659
+ return full("forced")
660
+ if inverse:
661
+ return full("inverse")
662
+ if prev_state is None:
663
+ return full("no-previous-state")
664
+ if prev_state.encoding != enc or prev_state.dithering != dith:
665
+ return full("re-encode")
666
+ if policy.refresh_due(consecutive_partials):
667
+ return full("ghosting-refresh-due")
668
+ if panel.interlace_mode and not panel.supports_screen_rectangles:
669
+ return full("panel-unsupported")
670
+
671
+ grey = to_grey8(img)
672
+ if grey.shape != panel.canvas_shape:
673
+ raise ValueError(
674
+ f"image is {grey.shape[1]}x{grey.shape[0]} but panel canvas is "
675
+ f"{panel.canvas_width}x{panel.canvas_height} "
676
+ f"({panel.displays} displays of {panel.width}x{panel.height})"
677
+ )
678
+ if beautify:
679
+ grey = _beautify(grey, gamma=beautify_gamma)
680
+
681
+ canvas = Rect(0, 0, panel.canvas_width, panel.canvas_height)
682
+ if rects is not None:
683
+ dirty = [r for r in (c.intersection(canvas) for c in rects)
684
+ if r is not None]
685
+ else:
686
+ dirty = detect_changes(grey, prev_state.source_grey, change_threshold)
687
+ dirty = unite_overlapping_regions(dirty, area_criteria=True)
688
+
689
+ if not dirty:
690
+ return EncodedFrame(
691
+ rectangles=[],
692
+ state_checksum=prev_state.checksum,
693
+ state=FrameState(prev_state.state_grey, grey, prev_state.checksum,
694
+ enc, dith),
695
+ full_screen=False,
696
+ screen_space=bool(panel.interlace_mode),
697
+ dirty_rects=(),
698
+ )
699
+
700
+ # ---- no fold: a canvas rectangle is already a wire rectangle --------
701
+ if not panel.interlace_mode:
702
+ frame = _encode_frame(
703
+ img, panel=panel, encoding=enc, dithering=dith, rects=dirty,
704
+ prev_state=prev_state, inverse=False,
705
+ rect_options=int(rect_options) | OPTION_NORMAL_UPDATE,
706
+ image_type=image_type,
707
+ rectangle_update_options=rectangle_update_options,
708
+ change_threshold=change_threshold, merge_regions=merge_regions,
709
+ max_regions=max_regions, beautify=beautify,
710
+ beautify_gamma=beautify_gamma, bayer_matrix=bayer_matrix,
711
+ blue_noise_matrix=blue_noise_matrix, dither_levels=dither_levels,
712
+ )
713
+ frame.dirty_rects = tuple(dirty)
714
+ if frame.full_screen and frame.fallback_reason is None:
715
+ frame.fallback_reason = "too-many-regions"
716
+ if partial_cost(frame.rectangles) >= (
717
+ policy.max_cost_fraction * full_screen_cost(panel, enc)
718
+ ) and not frame.full_screen:
719
+ return full("not-worth-it")
720
+ return frame
721
+
722
+ # ---- canvas rects -> screen rects ----------------------------------
723
+ bounds = screen_bounds(panel)
724
+ per_screen: dict[int, list[Rect]] = {}
725
+ for rect in dirty:
726
+ for screen_id, screen_rect in screen_rects_for_canvas_rect(rect, panel):
727
+ per_screen.setdefault(screen_id, []).append(screen_rect)
728
+
729
+ merged: dict[int, list[Rect]] = {}
730
+ for screen_id, screen_rects in sorted(per_screen.items()):
731
+ limited = limit_regions(screen_rects, bounds.width, bounds.height,
732
+ merge=merge_regions, max_regions=max_regions)
733
+ if limited is None:
734
+ return full("too-many-regions")
735
+ # alignment can make two rectangles overlap, and uniting can un-align
736
+ # the result, so this iterates (see align_and_unite_screen_rects)
737
+ merged[screen_id] = align_and_unite_screen_rects(limited, enc, bounds)
738
+ if len(merged[screen_id]) > max_regions:
739
+ return full("too-many-regions")
740
+
741
+ # ---- new state image, then cut the rectangles out of it -------------
742
+ if prev_state.state_grey.shape != panel.canvas_shape:
743
+ raise ValueError(
744
+ f"prev_state's state image is {prev_state.state_grey.shape[1]}x"
745
+ f"{prev_state.state_grey.shape[0]} but panel canvas is "
746
+ f"{panel.canvas_width}x{panel.canvas_height}"
747
+ )
748
+ state = prev_state.state_grey.copy()
749
+ _apply_to_state(state, grey, dirty, panel, enc, dith,
750
+ bayer=bayer_matrix, blue_noise=blue_noise_matrix,
751
+ dither_levels=dither_levels)
752
+
753
+ # A partial that also requests the inverse clearing waveform is refused by
754
+ # the firmware ("Skip image update: partial image not allowed"), so the
755
+ # "normal update" bit is set here regardless of rect_options. The
756
+ # full-screen fallback above keeps rect_options as given, which is what
757
+ # spends the ghosting budget on a clearing refresh.
758
+ options = int(rect_options) | OPTION_NORMAL_UPDATE
759
+ out: list[EncodedRect] = []
760
+ for screen_id, screen_rects in sorted(merged.items()):
761
+ for rect in screen_rects:
762
+ out.append(encode_screen_rect(
763
+ state, screen_id=screen_id, rect=rect, panel=panel,
764
+ encoding=enc, options=options, image_type=int(image_type),
765
+ rectangle_update_options=rectangle_update_options,
766
+ dithering=dith,
767
+ ))
768
+
769
+ if partial_cost(out) >= policy.max_cost_fraction * full_screen_cost(panel, enc):
770
+ return full("not-worth-it")
771
+
772
+ checksum = state_checksum(np.ascontiguousarray(state).tobytes())
773
+ return EncodedFrame(
774
+ rectangles=out,
775
+ state_checksum=checksum,
776
+ state=FrameState(state, grey, checksum, enc, dith),
777
+ full_screen=False,
778
+ screen_space=True,
779
+ dirty_rects=tuple(dirty),
780
+ )
781
+
782
+
783
+ # --------------------------------------------------------------------------
784
+ # the tracker
785
+ # --------------------------------------------------------------------------
786
+
787
+ class DirtyTracker:
788
+ """Successive frames in, partial updates out, with the ghosting budget kept.
789
+
790
+ The one piece of :mod:`pyvisionect.imaging` that is deliberately
791
+ **stateful**: it holds the :class:`~.encoder.FrameState` and the
792
+ consecutive-partial counter so the caller does not have to thread them
793
+ through every call. Everything it does is still a pure function of that
794
+ state plus the new image -- there is no clock and no I/O.
795
+
796
+ ::
797
+
798
+ tracker = DirtyTracker(panel=PANEL_32INCH, encoding=4, dithering=1)
799
+ frame = tracker.update(img) # first frame: full screen
800
+ frame = tracker.update(img2) # then partials
801
+ if frame.rectangles:
802
+ conn.push_image(frame) # your transport
803
+
804
+ Push what comes back, in order, and nothing else: a frame with no
805
+ rectangles means the panel already shows this image and the right action is
806
+ none. If a push **fails**, call :meth:`rollback` -- the tracker's state
807
+ image claims the device drew something it did not, and the next partial
808
+ would hold the wrong partner-lane pixels.
809
+
810
+ :param panel: anything :meth:`~.panel.Panel.adapt` accepts.
811
+ :param encoding: ``1`` or ``4``.
812
+ :param dithering: a :class:`~.constants.Dithering` value.
813
+ :param policy: a :class:`PartialPolicy`, or ``None`` for the defaults.
814
+ :param state: a :class:`~.encoder.FrameState` to resume from, e.g. one
815
+ restored with :meth:`~.encoder.FrameState.from_bytes` after a restart.
816
+ E-ink keeps its image, so resuming is the difference between a free
817
+ restart and a full-screen push plus a unit of panel wear.
818
+ :param consecutive_partials: the counter to resume with. Persist it beside
819
+ the state, or pass nothing and spend one extra full refresh.
820
+ """
821
+
822
+ def __init__(
823
+ self,
824
+ *,
825
+ panel: Panel,
826
+ encoding: int,
827
+ dithering: int,
828
+ policy: Optional[PartialPolicy] = None,
829
+ state: Optional[FrameState] = None,
830
+ consecutive_partials: int = 0,
831
+ rect_options: int = 0,
832
+ image_type: int = int(ImageType.GRAY),
833
+ rectangle_update_options: Optional[int] = None,
834
+ change_threshold: float = 0.0,
835
+ merge_regions: bool = True,
836
+ max_regions: int = MAX_REGIONS_PER_DISPLAY,
837
+ beautify: bool = False,
838
+ beautify_gamma: float = 1.1,
839
+ bayer_matrix: Optional[np.ndarray] = None,
840
+ blue_noise_matrix: Optional[np.ndarray] = None,
841
+ dither_levels: Optional[int] = None,
842
+ ) -> None:
843
+ self.panel = Panel.adapt(panel)
844
+ self.encoding, self.dithering = _validate(encoding, dithering,
845
+ self.panel)
846
+ self.policy = policy or PartialPolicy()
847
+ self.state = state
848
+ if consecutive_partials < 0:
849
+ raise ValueError("consecutive_partials cannot be negative")
850
+ self._consecutive = int(consecutive_partials)
851
+ self._previous: Optional[FrameState] = None
852
+ self._previous_consecutive = self._consecutive
853
+ self._kwargs = dict(
854
+ rect_options=rect_options, image_type=image_type,
855
+ rectangle_update_options=rectangle_update_options,
856
+ change_threshold=change_threshold, merge_regions=merge_regions,
857
+ max_regions=max_regions, beautify=beautify,
858
+ beautify_gamma=beautify_gamma, bayer_matrix=bayer_matrix,
859
+ blue_noise_matrix=blue_noise_matrix, dither_levels=dither_levels,
860
+ )
861
+
862
+ # -- the budget -------------------------------------------------------
863
+
864
+ @property
865
+ def consecutive_partials(self) -> int:
866
+ """Partials pushed since the last full-screen frame."""
867
+ return self._consecutive
868
+
869
+ @property
870
+ def refresh_due(self) -> bool:
871
+ """Whether the next :meth:`update` will be promoted to full screen.
872
+
873
+ Only the ghosting budget; the cost and region gates depend on the
874
+ image and cannot be answered before encoding it.
875
+ """
876
+ return self.policy.refresh_due(self._consecutive)
877
+
878
+ # -- frames -----------------------------------------------------------
879
+
880
+ def update(self, img: Any, *, rects: Optional[Sequence[Rect]] = None,
881
+ force_full_screen: bool = False,
882
+ inverse: bool = False) -> EncodedFrame:
883
+ """Encode the next frame, partial if that is possible and worthwhile.
884
+
885
+ The counter advances only for frames that **carry rectangles**: a
886
+ no-change frame draws nothing, so it spends no ghosting budget, and a
887
+ full-screen frame resets the counter to zero.
888
+
889
+ :param rects: canvas-space dirty rectangles, if you know them.
890
+ :param force_full_screen: skip change detection and repaint
891
+ everything; also resets the ghosting counter.
892
+ :param inverse: request the inverse / clearing refresh, which forces
893
+ full screen (spec §1.4).
894
+ """
895
+ frame = encode_partial_frame(
896
+ img, panel=self.panel, encoding=self.encoding,
897
+ dithering=self.dithering, prev_state=self.state, rects=rects,
898
+ policy=self.policy, consecutive_partials=self._consecutive,
899
+ inverse=inverse, force_full_screen=force_full_screen,
900
+ **self._kwargs,
901
+ )
902
+ self._previous = self.state
903
+ self._previous_consecutive = self._consecutive
904
+ self.state = frame.state
905
+ if frame.rectangles:
906
+ self._consecutive = 0 if frame.full_screen else self._consecutive + 1
907
+ return frame
908
+
909
+ def rollback(self) -> None:
910
+ """Undo the last :meth:`update`, for a push that did not go out.
911
+
912
+ The state image is the tracker's claim about what the glass shows. If
913
+ a push failed, that claim is wrong, and the next partial would hold
914
+ stale partner-lane pixels and compute a checksum the device will never
915
+ echo. Only one step of history is kept, so roll back immediately or
916
+ drop the state with :meth:`reset` and take one full push.
917
+ """
918
+ self.state = self._previous
919
+ self._consecutive = self._previous_consecutive
920
+ self._previous = None
921
+
922
+ def reset(self, state: Optional[FrameState] = None) -> None:
923
+ """Forget what the panel shows, so the next frame is a full push.
924
+
925
+ Pass a ``state`` to adopt one instead, e.g. after restoring a
926
+ persisted :class:`~.encoder.FrameState`.
927
+ """
928
+ self._previous = self.state
929
+ self._previous_consecutive = self._consecutive
930
+ self.state = state
931
+ self._consecutive = 0