dsh-watch-together 0.2.12 → 0.2.14

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.
@@ -1,341 +1,362 @@
1
- """glass_capture.py — 抓屏、运动判定、所有渲染路径共用的收尾。
2
-
3
- CPU 与 GPU 两条管线以前各写一份「抓屏 → 算静态签名 → 判断要不要重合成 →
4
- 贴麦克风 → 贴圆角遮罩」,于是同一个 bug 要修两遍(#39、#48 都是这么来的:
5
- CPU 修了,GPU 漏了)。这里把它们收成一套:
6
-
7
- - `CaptureSource.grab()`:窗口矩形外扩 PAD、钳位、守卫零尺寸;
8
- - `MotionTracker.observe()`:返回 `(moved, stale)`,**两个判断一次算完**,
9
- 不会再出现「拖动窗口算不算动」这种两边理解不一致;
10
- - `finish()` / `paste_mic()`:两条路径的最后两步。
11
-
12
- 渲染器只负责「一张图 → 一张图」,其余都在这里。
13
- """
14
- from __future__ import annotations
15
-
16
- import os
17
- import time
18
- from dataclasses import dataclass
19
- from pathlib import Path
20
-
21
- import numpy as np
22
- from PIL import Image
23
-
24
- from glass_geometry import KEY, LPF, MIC_SIZE, PAD, Geometry
25
-
26
- try:
27
- import cv2 as _cv2
28
- except Exception: # OpenCV 只是加速,缺了仍走 PIL
29
- _cv2 = None
30
-
31
- HERE = Path(__file__).resolve().parent
32
-
33
- # 静态跳帧:像素差超过这个就算「动了」
34
- SIG_STEP = 4 # 采样步长(像素)
35
- MOVE_MEAN = 0.01 # 平均差阈值(0~255)
36
- MOVE_MAX = 0.5 # 单点最大差阈值
37
- STALE_AFTER = 0.30 # 运动结束后多久允许跳帧
38
-
39
- FORCE = os.environ.get("GLASS_FORCE") == "1"
40
-
41
- # 抓屏连续失败时的替身底板颜色。取窗口本体那种深蓝黑:和气泡底板同一套色,
42
- # 失败时看起来像"玻璃后面是暗背景",而不是一块死黑。
43
- SOLID_RGB = (18, 22, 30)
44
- _solid_cache: dict[tuple[int, int], "_SolidShot"] = {}
45
- _last_warn = [0.0]
46
-
47
-
48
- class _SolidShot:
49
- """`mss` 截图的替身:只实现下游用到的 `.size` / `.rgb` / `.bgra`。
50
-
51
- 下游两条路都在这儿取像素:CPU 走 `Image.frombytes("RGB", size, rgb)`,
52
- GPU 走 `np.frombuffer(shot.shot.bgra).reshape(h, w, 4)`。少给一个属性
53
- 就是「失败时 CPU 能兜、GPU 每帧抛」—— 而 GPU 那条正好是有问题的那台机器
54
- 更可能开的(`DSH_GLASS_GPU=1`)。
55
- """
56
- __slots__ = ("size", "rgb", "bgra")
57
-
58
- def __init__(self, w: int, h: int, color: tuple[int, int, int] = SOLID_RGB):
59
- self.size = (w, h)
60
- r, g, b = color
61
- self.rgb = bytes((r, g, b)) * (w * h)
62
- self.bgra = bytes((b, g, r, 255)) * (w * h)
63
-
64
-
65
- def _solid_shot(w: int, h: int) -> "_SolidShot":
66
- """同尺寸复用一份(失败时每帧都要一张,别一直分配 1MB+)。"""
67
- key = (w, h)
68
- shot = _solid_cache.get(key)
69
- if shot is None:
70
- shot = _SolidShot(w, h)
71
- if len(_solid_cache) > 4:
72
- _solid_cache.clear()
73
- _solid_cache[key] = shot
74
- return shot
75
-
76
-
77
- def _warn_grab(exc: Exception) -> None:
78
- """抓屏失败**只喊一次**(30 秒内不重复)。每帧刷屏等于没有日志。"""
79
- now = time.monotonic()
80
- if now - _last_warn[0] < 30:
81
- return
82
- _last_warn[0] = now
83
- print(f"capture failed, using solid plate: {type(exc).__name__}: {exc}", flush=True)
84
-
85
-
86
- def _load_mic() -> tuple[Image.Image, Image.Image]:
87
- """麦克风图标:去背景得到 alpha,再做浅色/深色两版(按背后亮度挑)。"""
88
- try:
89
- mask = Image.open(HERE / "mic-dsh.png").convert("L")
90
- mask = mask.resize((MIC_SIZE, MIC_SIZE), Image.Resampling.LANCZOS)
91
- except Exception:
92
- mask = Image.new("L", (MIC_SIZE, MIC_SIZE), 200)
93
- light = Image.new("RGBA", mask.size, (235, 244, 255, 0))
94
- light.putalpha(mask)
95
- dark = Image.new("RGBA", mask.size, (24, 48, 72, 0))
96
- dark.putalpha(mask)
97
- return light, dark
98
-
99
-
100
- MIC_LIGHT, MIC_DARK = _load_mic()
101
-
102
-
103
- def resample(arr_or_im, size):
104
- """缩放一张图(两个方向都用);有 OpenCV 走 OpenCV,比 PIL 快一个数量级。"""
105
- if _cv2 is not None:
106
- src = np.asarray(arr_or_im)
107
- return _cv2.resize(src, size, interpolation=_cv2.INTER_LINEAR)
108
- im = arr_or_im if isinstance(arr_or_im, Image.Image) else Image.fromarray(arr_or_im)
109
- return np.asarray(im.resize(size, Image.Resampling.BILINEAR))
110
-
111
-
112
- CORNER_PROBE = 56 # 角块边长:从这个方块里取中位色
113
-
114
-
115
- def _median_color(arr: np.ndarray, y0: int, y1: int, x0: int, x1: int):
116
- """一块区域的三通道中位数(没有像素返回 None)。
117
-
118
- 用中位数而不是均值:桌面图标、文字这类「少数像素」不会把整块颜色带跑,
119
- 均值会被一个白色图标顶到发白。
120
- """
121
- h, w = arr.shape[:2]
122
- y0, y1 = max(0, min(h, y0)), max(0, min(h, y1))
123
- x0, x1 = max(0, min(w, x0)), max(0, min(w, x1))
124
- patch = arr[y0:y1, x0:x1]
125
- if patch.size == 0:
126
- return None
127
- return np.median(patch.reshape(-1, patch.shape[-1]), axis=0).astype(np.float32)
128
-
129
-
130
- def _fill_patch(arr: np.ndarray, box, step: int = 8) -> None:
131
- """把窗口矩形填成「四周环境色」的二维渐变(原地)。
132
-
133
- **不要拿边缘像素插值**。窗口上下左右紧挨着的那一圈里如果正好有桌面图标或
134
- 文字,插值会把它们沿某个方向整条抹开 —— 纵插值是竖条、横插值是横条,换哪种
135
- 都难看(用户两次都撞上了)。
136
-
137
- 现在只取窗口外**四个角块的中位色**,做双线性。角块完全在窗口外面,不含窗口
138
- 自己的内容;中位数又抹掉了图标这类少数像素;四角双线性只有大尺度过渡,
139
- 不存在任何「把东西拉长」的方向。
140
-
141
- 渐变在 `step` 分之一的粗网格上算再放大:这块最后还要被高斯糊一遍,
142
- 8px 的色阶看不出来。全分辨率算一次要 80ms,粗网格是 0.3ms。
143
- """
144
- h, w = arr.shape[:2]
145
- x0, y0, x1, y1 = (int(v) for v in box)
146
- x0, x1 = max(0, min(w, x0)), max(0, min(w, x1))
147
- y0, y1 = max(0, min(h, y0)), max(0, min(h, y1))
148
- bw, bh = x1 - x0, y1 - y0
149
- if bw <= 0 or bh <= 0:
150
- return
151
-
152
- b = CORNER_PROBE
153
- tl = _median_color(arr, y0 - b, y0, x0 - b, x0)
154
- tr = _median_color(arr, y0 - b, y0, x1, x1 + b)
155
- bl = _median_color(arr, y1, y1 + b, x0 - b, x0)
156
- br = _median_color(arr, y1, y1 + b, x1, x1 + b)
157
- # 窗口贴在屏幕边上时角块会缺 —— 用整圈外框的中位色兜底;
158
- # 连外框都没有(窗口铺满屏幕)才退回窗口自己的中位色。
159
- ring = _median_color(arr, y0 - b, y1 + b, x0 - b, x0) if x0 > 0 else None
160
- if ring is None:
161
- ring = _median_color(arr, y0 - b, y1 + b, x1, x1 + b) if x1 < w else None
162
- if ring is None:
163
- ring = _median_color(arr, y0 - b, y0, x0, x1) if y0 > 0 else None
164
- if ring is None:
165
- ring = _median_color(arr, y1, y1 + b, x0, x1) if y1 < h else None
166
- if ring is None:
167
- ring = _median_color(arr, y0, y1, x0, x1) or np.zeros(3, np.float32)
168
- tl = ring if tl is None else tl
169
- tr = ring if tr is None else tr
170
- bl = ring if bl is None else bl
171
- br = ring if br is None else br
172
-
173
- gw, gh = max(2, bw // step), max(2, bh // step)
174
- ty = ((np.arange(gh, dtype=np.float32) + 0.5) / gh)[:, None, None]
175
- tx = ((np.arange(gw, dtype=np.float32) + 0.5) / gw)[None, :, None]
176
- out = (tl * (1 - tx) * (1 - ty) + tr * tx * (1 - ty)
177
- + bl * (1 - tx) * ty + br * tx * ty)
178
- out = np.clip(out, 0, 255)
179
- big = resample(out, (bw, bh)) if (gw, gh) != (bw, bh) else out
180
- arr[y0:y1, x0:x1] = big.astype(np.uint8)
181
-
182
-
183
- def fill_own_rect(im: Image.Image, box) -> Image.Image:
184
- """录屏模式下把「窗口自己」在抓屏帧里占的那块填掉。
185
-
186
- `capturable: true` 会关掉 WDA,于是 mss 抓背景时把窗口也抓进来,玻璃拿它
187
- 当背景就是「透过自己看自己」:背景里带着上一帧的字 → 亮度判据一直抖 →
188
- 字色来回翻;背景一直在变 → `moved` 恒真 → 越滚越浓的假拖尾。
189
-
190
- 窗口外 PAD 一圈仍是真背景,边缘透镜照常取料。
191
- """
192
- arr = np.array(im)
193
- _fill_patch(arr, box)
194
- return Image.fromarray(arr)
195
-
196
-
197
- def fill_own_rect_array(arr: np.ndarray, box) -> None:
198
- """`fill_own_rect` 的原地版本,给直接吃 `shot.bgra` 的 GPU 路径用。
199
-
200
- GPU 不经过 PIL,如果漏了这一步,抓到的背景里永远有自己 —— 每帧都在变,
201
- 静态跳帧一次都不会触发,还叠出自我反馈的拖尾。
202
- """
203
- _fill_patch(arr, box)
204
-
205
-
206
- class MotionTracker:
207
- """静态跳帧 + 运动强度,两条渲染路径共用。
208
-
209
- 语义(和 0.2.9 修过的 CPU 行为一致):
210
-
211
- - **抓取区域变了就算动**。拖动窗口时 `box` 每帧都不同,旧区域的像素本来
212
- 也不能直接做差;不标 `moved` 的话,拖动全程都走「没在动」分支 ——
213
- 运动模糊一路衰减到 0、反而每帧去做静止才该做的色散。这就是 #48。
214
- - 静止超过 `STALE_AFTER` 就允许跳帧(`stale=True`),省掉整条合成;
215
- - `motion` 是 0~1 的平滑值,只有移动帧才拿它去混上一帧。
216
- """
217
-
218
- def __init__(self, force: bool = FORCE):
219
- self.force = force
220
- self.motion = 0.0
221
- self._sig: np.ndarray | None = None
222
- self._bbox = None
223
- self._last_motion = 0.0
224
-
225
- def invalidate(self) -> None:
226
- """形状/尺寸变了:旧签名和旧背景都不能再用。"""
227
- self._sig = None
228
- self._bbox = None
229
- self._last_motion = 0.0
230
- self.motion = 0.0
231
-
232
- def observe(self, small_rgb: np.ndarray, box, now: float | None = None):
233
- """`small_rgb` 是未模糊的 1/4 采样图。返回 `(moved, stale)`。"""
234
- now = time.perf_counter() if now is None else now
235
- sig = small_rgb[::SIG_STEP, ::SIG_STEP].astype(np.int16).mean(axis=2)
236
- moved = False
237
- if self._bbox is not None and box != self._bbox:
238
- moved = True
239
- elif self._sig is not None and sig.shape == self._sig.shape:
240
- d = np.abs(sig - self._sig)
241
- moved = bool(float(d.mean()) > MOVE_MEAN or float(d.max()) > MOVE_MAX)
242
- if moved:
243
- self._last_motion = now
244
- self.motion = min(1.0, self.motion * 0.50 + 0.50)
245
- else:
246
- self.motion *= 0.55
247
- stale = (not self.force and not moved and box == self._bbox
248
- and now - self._last_motion > STALE_AFTER)
249
- self._sig = sig
250
- self._bbox = box
251
- return moved, stale
252
-
253
- @property
254
- def blend(self) -> float:
255
- """移动帧混上一帧的强度;停下后立刻归零,不留残影。"""
256
- return 0.35 * max(0.0, min(1.0, self.motion))
257
-
258
-
259
- @dataclass(slots=True)
260
- class Shot:
261
- """一次抓屏的结果。CPU 用 `rgb`,GPU 用 `bgra`,避免重复抓。"""
262
-
263
- shot: object # mss 的 ScreenShot
264
- box: tuple # 屏幕坐标 (gl, gt, gr, gb)
265
- offset: tuple # 窗口左上角在抓屏图里的 1/4 分辨率坐标
266
-
267
-
268
- class CaptureSource:
269
- """按窗口矩形抓背景,外扩 PAD 供边缘透镜取「框外」的像素。"""
270
-
271
- def __init__(self, screen: tuple[int, int], pad: int = PAD, cappable: bool = False):
272
- self.screen = screen
273
- self.pad = pad
274
- self.cappable = cappable
275
-
276
- def grab(self, sct, bbox) -> Shot | None:
277
- l, t, r, b = (int(v) for v in bbox)
278
- if r <= l or b <= t:
279
- return None
280
- sw, sh = self.screen
281
- gl = max(0, l - self.pad)
282
- gt = max(0, t - self.pad)
283
- gr = min(sw, r + self.pad)
284
- gb = min(sh, b + self.pad)
285
- # 多显示器 / DPI 变化 / 被别的程序挪出屏幕时,钳位后宽高可能 <= 0;
286
- # mss 会抛 "Region has zero or negative size",而 _work() 会每帧吞掉它
287
- # —— 表现就是日志刷屏、背景永久停在旧帧。没有可抓的区域就别抓。
288
- if gr - gl <= 0 or gb - gt <= 0:
289
- return None
290
- try:
291
- shot = sct.grab({"left": gl, "top": gt, "width": gr - gl, "height": gb - gt})
292
- except Exception as exc:
293
- # **抓不到就别把窗变成一块透明玻璃。**
294
- # BitBlt 会在几种场景下失败:桌面锁屏 / UAC 安全桌面 / 远程桌面 /
295
- # 某些 HDR 或全屏独占的机器。以前这里直接把异常抛给 `_work()`,
296
- # 于是每帧一条 "capture error"、一帧都画不出来 —— 用户看到的是
297
- # "背景变成透明的了,只剩字"(2026-11-03 社区反馈)。
298
- # 现在退成一块**纯色底板**:不好看,但字读得清、窗看得见。
299
- _warn_grab(exc)
300
- return Shot(shot=_solid_shot(gr - gl, gb - gt), box=(gl, gt, gr, gb),
301
- offset=(int(round((l - gl) / LPF)), int(round((t - gt) / LPF))))
302
- return Shot(shot=shot, box=(gl, gt, gr, gb),
303
- offset=(int(round((l - gl) / LPF)), int(round((t - gt) / LPF))))
304
-
305
- def to_image(self, shot: Shot, bbox) -> Image.Image:
306
- """抓屏帧 → RGB 图;录屏模式下先把自己挖掉。"""
307
- im = Image.frombytes("RGB", shot.shot.size, shot.shot.rgb)
308
- if self.cappable:
309
- l, t, r, b = (int(v) for v in bbox)
310
- gl, gt = shot.box[0], shot.box[1]
311
- im = fill_own_rect(im, (l - gl, t - gt, r - gl, b - gt))
312
- return im
313
-
314
- def own_rect(self, shot: Shot, bbox) -> tuple[int, int, int, int]:
315
- gl, gt = shot.box[0], shot.box[1]
316
- l, t, r, b = bbox
317
- return (l - gl, t - gt, r - gl, b - gt)
318
-
319
-
320
- def finish(geo: Geometry, panel: Image.Image) -> Image.Image:
321
- """贴二值圆角遮罩;缝隙/圆角外是 KEY,被 Tk 抠成透明。"""
322
- out = Image.new("RGB", (geo.width, geo.height), KEY)
323
- out.paste(panel.convert("RGB"), (0, 0), geo.mask_hard)
324
- return out
325
-
326
-
327
- def paste_mic(geo: Geometry, im: Image.Image) -> Image.Image:
328
- """麦克风图标贴进玻璃帧,按背后亮度选浅/深两版(和仓库原做法一致)。"""
329
- x, y = geo.mic_pos
330
- box = im.crop((x, y, x + MIC_SIZE, y + MIC_SIZE)).convert("L")
331
- bg = float(np.median(np.asarray(box))) / 255.0
332
- out = im.convert("RGBA")
333
- icon = MIC_LIGHT if bg < 0.48 else MIC_DARK
334
- out.paste(icon, (x, y), icon)
335
- return out.convert("RGB")
336
-
337
-
338
- __all__ = [
339
- "CaptureSource", "FORCE", "MIC_DARK", "MIC_LIGHT", "MotionTracker", "Shot",
340
- "fill_own_rect", "finish", "paste_mic", "resample",
341
- ]
1
+ """glass_capture.py — 抓屏、运动判定、所有渲染路径共用的收尾。
2
+
3
+ CPU 与 GPU 两条管线以前各写一份「抓屏 → 算静态签名 → 判断要不要重合成 →
4
+ 贴麦克风 → 贴圆角遮罩」,于是同一个 bug 要修两遍(#39、#48 都是这么来的:
5
+ CPU 修了,GPU 漏了)。这里把它们收成一套:
6
+
7
+ - `CaptureSource.grab()`:窗口矩形外扩 PAD、钳位、守卫零尺寸;
8
+ - `MotionTracker.observe()`:返回 `(moved, stale)`,**两个判断一次算完**,
9
+ 不会再出现「拖动窗口算不算动」这种两边理解不一致;
10
+ - `finish()` / `paste_mic()`:两条路径的最后两步。
11
+
12
+ 渲染器只负责「一张图 → 一张图」,其余都在这里。
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import time
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ from PIL import Image
23
+
24
+ from glass_geometry import KEY, LPF, MIC_SIZE, PAD, Geometry
25
+
26
+ try:
27
+ import cv2 as _cv2
28
+ except Exception: # OpenCV 只是加速,缺了仍走 PIL
29
+ _cv2 = None
30
+
31
+ HERE = Path(__file__).resolve().parent
32
+
33
+ # 静态跳帧:像素差超过这个就算「动了」
34
+ SIG_STEP = 4 # 采样步长(像素)
35
+ MOVE_MEAN = 0.01 # 平均差阈值(0~255)
36
+ MOVE_MAX = 0.5 # 单点最大差阈值
37
+ STALE_AFTER = 0.30 # 运动结束后多久允许跳帧
38
+
39
+ FORCE = os.environ.get("GLASS_FORCE") == "1"
40
+
41
+ # 抓屏连续失败时的替身底板颜色。取窗口本体那种深蓝黑:和气泡底板同一套色,
42
+ # 失败时看起来像"玻璃后面是暗背景",而不是一块死黑。
43
+ SOLID_RGB = (18, 22, 30)
44
+ _solid_cache: dict[tuple[int, int], "_SolidShot"] = {}
45
+ _last_warn = [0.0]
46
+
47
+
48
+ class _SolidShot:
49
+ """`mss` 截图的替身:只实现下游用到的 `.size` / `.rgb` / `.bgra`。
50
+
51
+ 下游两条路都在这儿取像素:CPU 走 `Image.frombytes("RGB", size, rgb)`,
52
+ GPU 走 `np.frombuffer(shot.shot.bgra).reshape(h, w, 4)`。少给一个属性
53
+ 就是「失败时 CPU 能兜、GPU 每帧抛」—— 而 GPU 那条正好是有问题的那台机器
54
+ 更可能开的(`DSH_GLASS_GPU=1`)。
55
+ """
56
+ __slots__ = ("size", "rgb", "bgra")
57
+
58
+ def __init__(self, w: int, h: int, color: tuple[int, int, int] = SOLID_RGB):
59
+ self.size = (w, h)
60
+ r, g, b = color
61
+ self.rgb = bytes((r, g, b)) * (w * h)
62
+ self.bgra = bytes((b, g, r, 255)) * (w * h)
63
+
64
+
65
+ def _solid_shot(w: int, h: int) -> "_SolidShot":
66
+ """同尺寸复用一份(失败时每帧都要一张,别一直分配 1MB+)。"""
67
+ key = (w, h)
68
+ shot = _solid_cache.get(key)
69
+ if shot is None:
70
+ shot = _SolidShot(w, h)
71
+ if len(_solid_cache) > 4:
72
+ _solid_cache.clear()
73
+ _solid_cache[key] = shot
74
+ return shot
75
+
76
+
77
+ def _warn_grab(exc: Exception) -> None:
78
+ """抓屏失败**只喊一次**(30 秒内不重复)。每帧刷屏等于没有日志。"""
79
+ now = time.monotonic()
80
+ if now - _last_warn[0] < 30:
81
+ return
82
+ _last_warn[0] = now
83
+ print(f"capture failed, using solid plate: {type(exc).__name__}: {exc}", flush=True)
84
+
85
+
86
+ def _load_mic() -> tuple[Image.Image, Image.Image]:
87
+ """麦克风图标:去背景得到 alpha,再做浅色/深色两版(按背后亮度挑)。"""
88
+ try:
89
+ mask = Image.open(HERE / "mic-dsh.png").convert("L")
90
+ mask = mask.resize((MIC_SIZE, MIC_SIZE), Image.Resampling.LANCZOS)
91
+ except Exception:
92
+ mask = Image.new("L", (MIC_SIZE, MIC_SIZE), 200)
93
+ light = Image.new("RGBA", mask.size, (235, 244, 255, 0))
94
+ light.putalpha(mask)
95
+ dark = Image.new("RGBA", mask.size, (24, 48, 72, 0))
96
+ dark.putalpha(mask)
97
+ return light, dark
98
+
99
+
100
+ MIC_LIGHT, MIC_DARK = _load_mic()
101
+
102
+
103
+ def resample(arr_or_im, size):
104
+ """缩放一张图(两个方向都用);有 OpenCV 走 OpenCV,比 PIL 快一个数量级。"""
105
+ if _cv2 is not None:
106
+ src = np.asarray(arr_or_im)
107
+ return _cv2.resize(src, size, interpolation=_cv2.INTER_LINEAR)
108
+ im = arr_or_im if isinstance(arr_or_im, Image.Image) else Image.fromarray(arr_or_im)
109
+ return np.asarray(im.resize(size, Image.Resampling.BILINEAR))
110
+
111
+
112
+ CORNER_PROBE = 56 # 角块边长:从这个方块里取中位色
113
+
114
+
115
+ def _median_color(arr: np.ndarray, y0: int, y1: int, x0: int, x1: int):
116
+ """一块区域的三通道中位数(没有像素返回 None)。
117
+
118
+ 用中位数而不是均值:桌面图标、文字这类「少数像素」不会把整块颜色带跑,
119
+ 均值会被一个白色图标顶到发白。
120
+ """
121
+ h, w = arr.shape[:2]
122
+ y0, y1 = max(0, min(h, y0)), max(0, min(h, y1))
123
+ x0, x1 = max(0, min(w, x0)), max(0, min(w, x1))
124
+ patch = arr[y0:y1, x0:x1]
125
+ if patch.size == 0:
126
+ return None
127
+ return np.median(patch.reshape(-1, patch.shape[-1]), axis=0).astype(np.float32)
128
+
129
+
130
+ def _fill_patch(arr: np.ndarray, box, step: int = 8) -> None:
131
+ """把窗口矩形填成「四周环境色」的二维渐变(原地)。
132
+
133
+ **不要拿边缘像素插值**。窗口上下左右紧挨着的那一圈里如果正好有桌面图标或
134
+ 文字,插值会把它们沿某个方向整条抹开 —— 纵插值是竖条、横插值是横条,换哪种
135
+ 都难看(用户两次都撞上了)。
136
+
137
+ 现在只取窗口外**四个角块的中位色**,做双线性。角块完全在窗口外面,不含窗口
138
+ 自己的内容;中位数又抹掉了图标这类少数像素;四角双线性只有大尺度过渡,
139
+ 不存在任何「把东西拉长」的方向。
140
+
141
+ 渐变在 `step` 分之一的粗网格上算再放大:这块最后还要被高斯糊一遍,
142
+ 8px 的色阶看不出来。全分辨率算一次要 80ms,粗网格是 0.3ms。
143
+ """
144
+ h, w = arr.shape[:2]
145
+ x0, y0, x1, y1 = (int(v) for v in box)
146
+ x0, x1 = max(0, min(w, x0)), max(0, min(w, x1))
147
+ y0, y1 = max(0, min(h, y0)), max(0, min(h, y1))
148
+ bw, bh = x1 - x0, y1 - y0
149
+ if bw <= 0 or bh <= 0:
150
+ return
151
+
152
+ b = CORNER_PROBE
153
+ tl = _median_color(arr, y0 - b, y0, x0 - b, x0)
154
+ tr = _median_color(arr, y0 - b, y0, x1, x1 + b)
155
+ bl = _median_color(arr, y1, y1 + b, x0 - b, x0)
156
+ br = _median_color(arr, y1, y1 + b, x1, x1 + b)
157
+ # 窗口贴在屏幕边上时角块会缺 —— 用整圈外框的中位色兜底;
158
+ # 连外框都没有(窗口铺满屏幕)才退回窗口自己的中位色。
159
+ ring = _median_color(arr, y0 - b, y1 + b, x0 - b, x0) if x0 > 0 else None
160
+ if ring is None:
161
+ ring = _median_color(arr, y0 - b, y1 + b, x1, x1 + b) if x1 < w else None
162
+ if ring is None:
163
+ ring = _median_color(arr, y0 - b, y0, x0, x1) if y0 > 0 else None
164
+ if ring is None:
165
+ ring = _median_color(arr, y1, y1 + b, x0, x1) if y1 < h else None
166
+ if ring is None:
167
+ ring = _median_color(arr, y0, y1, x0, x1) or np.zeros(3, np.float32)
168
+ tl = ring if tl is None else tl
169
+ tr = ring if tr is None else tr
170
+ bl = ring if bl is None else bl
171
+ br = ring if br is None else br
172
+
173
+ gw, gh = max(2, bw // step), max(2, bh // step)
174
+ ty = ((np.arange(gh, dtype=np.float32) + 0.5) / gh)[:, None, None]
175
+ tx = ((np.arange(gw, dtype=np.float32) + 0.5) / gw)[None, :, None]
176
+ out = (tl * (1 - tx) * (1 - ty) + tr * tx * (1 - ty)
177
+ + bl * (1 - tx) * ty + br * tx * ty)
178
+ out = np.clip(out, 0, 255)
179
+ big = resample(out, (bw, bh)) if (gw, gh) != (bw, bh) else out
180
+ arr[y0:y1, x0:x1] = big.astype(np.uint8)
181
+
182
+
183
+ def fill_own_rect(im: Image.Image, box) -> Image.Image:
184
+ """录屏模式下把「窗口自己」在抓屏帧里占的那块填掉。
185
+
186
+ `capturable: true` 会关掉 WDA,于是 mss 抓背景时把窗口也抓进来,玻璃拿它
187
+ 当背景就是「透过自己看自己」:背景里带着上一帧的字 → 亮度判据一直抖 →
188
+ 字色来回翻;背景一直在变 → `moved` 恒真 → 越滚越浓的假拖尾。
189
+
190
+ 窗口外 PAD 一圈仍是真背景,边缘透镜照常取料。
191
+ """
192
+ arr = np.array(im)
193
+ _fill_patch(arr, box)
194
+ return Image.fromarray(arr)
195
+
196
+
197
+ def fill_own_rect_array(arr: np.ndarray, box) -> None:
198
+ """`fill_own_rect` 的原地版本,给直接吃 `shot.bgra` 的 GPU 路径用。
199
+
200
+ GPU 不经过 PIL,如果漏了这一步,抓到的背景里永远有自己 —— 每帧都在变,
201
+ 静态跳帧一次都不会触发,还叠出自我反馈的拖尾。
202
+ """
203
+ _fill_patch(arr, box)
204
+
205
+
206
+ class MotionTracker:
207
+ """静态跳帧 + 运动强度,两条渲染路径共用。
208
+
209
+ 语义(和 0.2.9 修过的 CPU 行为一致):
210
+
211
+ - **抓取区域变了就算动**。拖动窗口时 `box` 每帧都不同,旧区域的像素本来
212
+ 也不能直接做差;不标 `moved` 的话,拖动全程都走「没在动」分支 ——
213
+ 运动模糊一路衰减到 0、反而每帧去做静止才该做的色散。这就是 #48。
214
+ - 静止超过 `STALE_AFTER` 就允许跳帧(`stale=True`),省掉整条合成;
215
+ - `motion` 是 0~1 的平滑值,只有移动帧才拿它去混上一帧。
216
+ """
217
+
218
+ def __init__(self, force: bool = FORCE):
219
+ self.force = force
220
+ self.motion = 0.0
221
+ self._sig: np.ndarray | None = None
222
+ self._bbox = None
223
+ self._last_motion = 0.0
224
+
225
+ def invalidate(self) -> None:
226
+ """形状/尺寸变了:旧签名和旧背景都不能再用。"""
227
+ self._sig = None
228
+ self._bbox = None
229
+ self._last_motion = 0.0
230
+ self.motion = 0.0
231
+
232
+ def observe(self, small_rgb: np.ndarray, box, now: float | None = None):
233
+ """`small_rgb` 是未模糊的 1/4 采样图。返回 `(moved, stale)`。"""
234
+ now = time.perf_counter() if now is None else now
235
+ sig = small_rgb[::SIG_STEP, ::SIG_STEP].astype(np.int16).mean(axis=2)
236
+ moved = False
237
+ if self._bbox is not None and box != self._bbox:
238
+ moved = True
239
+ elif self._sig is not None and sig.shape == self._sig.shape:
240
+ d = np.abs(sig - self._sig)
241
+ moved = bool(float(d.mean()) > MOVE_MEAN or float(d.max()) > MOVE_MAX)
242
+ if moved:
243
+ self._last_motion = now
244
+ self.motion = min(1.0, self.motion * 0.50 + 0.50)
245
+ else:
246
+ self.motion *= 0.55
247
+ stale = (not self.force and not moved and box == self._bbox
248
+ and now - self._last_motion > STALE_AFTER)
249
+ self._sig = sig
250
+ self._bbox = box
251
+ return moved, stale
252
+
253
+ @property
254
+ def blend(self) -> float:
255
+ """移动帧混上一帧的强度;停下后立刻归零,不留残影。"""
256
+ return 0.35 * max(0.0, min(1.0, self.motion))
257
+
258
+
259
+ @dataclass(slots=True)
260
+ class Shot:
261
+ """一次抓屏的结果。CPU 用 `rgb`,GPU 用 `bgra`,避免重复抓。"""
262
+
263
+ shot: object # mss 的 ScreenShot
264
+ box: tuple # 屏幕坐标 (gl, gt, gr, gb)
265
+ offset: tuple # 窗口左上角在抓屏图里的 1/4 分辨率坐标
266
+
267
+
268
+ class CaptureSource:
269
+ """按窗口矩形抓背景,外扩 PAD 供边缘透镜取「框外」的像素。"""
270
+
271
+ def __init__(self, screen: tuple[int, int], pad: int = PAD, cappable: bool = False,
272
+ solid: bool = False, bounds: tuple | None = None):
273
+ self.screen = screen
274
+ self.pad = pad
275
+ self.cappable = cappable
276
+ # solid:远程/录屏下 WDA 会让整窗在对面消失;不抓屏,用纯色底板
277
+ # 仍然走同一条渲染管线,文字和气泡都还在,只是背后不透明。
278
+ self.solid = solid
279
+ # bounds = 虚拟桌面 (x, y, w, h)。第二块屏在主屏左边时坐标是负的,
280
+ # 只拿主屏当边界会算出 gr <= gl,玻璃永远停在旧帧(#8)。
281
+ self.bounds = bounds
282
+
283
+ def _clamp_box(self, l: int, t: int, r: int, b: int) -> tuple[int, int, int, int]:
284
+ """抓屏外扩 + 钳位。窗口整个在主屏里时仍按主屏钳(与旧行为逐像素一致)。"""
285
+ sw, sh = self.screen
286
+ if 0 <= l and 0 <= t and r <= sw and b <= sh:
287
+ bl, bt, br, bb = 0, 0, sw, sh
288
+ elif self.bounds and self.bounds[2] > 0 and self.bounds[3] > 0:
289
+ bx, by, bw, bh = self.bounds
290
+ bl, bt, br, bb = bx, by, bx + bw, by + bh
291
+ else:
292
+ bl, bt, br, bb = 0, 0, sw, sh
293
+ return (max(bl, l - self.pad), max(bt, t - self.pad),
294
+ min(br, r + self.pad), min(bb, b + self.pad))
295
+
296
+ def grab(self, sct, bbox) -> Shot | None:
297
+ l, t, r, b = (int(v) for v in bbox)
298
+ if r <= l or b <= t:
299
+ return None
300
+ gl, gt, gr, gb = self._clamp_box(l, t, r, b)
301
+ # 多显示器 / DPI 变化 / 被别的程序挪出屏幕时,钳位后宽高可能 <= 0;
302
+ # mss 会抛 "Region has zero or negative size",而 _work() 会每帧吞掉它
303
+ # —— 表现就是日志刷屏、背景永久停在旧帧。没有可抓的区域就别抓。
304
+ if gr - gl <= 0 or gb - gt <= 0:
305
+ return None
306
+ offset = (int(round((l - gl) / LPF)), int(round((t - gt) / LPF)))
307
+ if self.solid:
308
+ # 不碰 mss:远程桌面/锁屏/独占全屏下 BitBlt 也可能失败,
309
+ # 而纯色底板在这些环境里都能正常显示(更不会触发 WDA 的问题)。
310
+ return Shot(shot=_solid_shot(gr - gl, gb - gt), box=(gl, gt, gr, gb),
311
+ offset=offset)
312
+ try:
313
+ shot = sct.grab({"left": gl, "top": gt, "width": gr - gl, "height": gb - gt})
314
+ except Exception as exc:
315
+ # **抓不到就别把窗变成一块透明玻璃。**
316
+ # BitBlt 会在几种场景下失败:桌面锁屏 / UAC 安全桌面 / 远程桌面 /
317
+ # 某些 HDR 或全屏独占的机器。以前这里直接把异常抛给 `_work()`,
318
+ # 于是每帧一条 "capture error"、一帧都画不出来 —— 用户看到的是
319
+ # "背景变成透明的了,只剩字"(2026-11-03 社区反馈)。
320
+ # 现在退成一块**纯色底板**:不好看,但字读得清、窗看得见。
321
+ _warn_grab(exc)
322
+ return Shot(shot=_solid_shot(gr - gl, gb - gt), box=(gl, gt, gr, gb),
323
+ offset=(int(round((l - gl) / LPF)), int(round((t - gt) / LPF))))
324
+ return Shot(shot=shot, box=(gl, gt, gr, gb), offset=offset)
325
+
326
+ def to_image(self, shot: Shot, bbox) -> Image.Image:
327
+ """抓屏帧 → RGB 图;录屏模式下先把自己挖掉。"""
328
+ im = Image.frombytes("RGB", shot.shot.size, shot.shot.rgb)
329
+ if self.cappable and not self.solid:
330
+ l, t, r, b = (int(v) for v in bbox)
331
+ gl, gt = shot.box[0], shot.box[1]
332
+ im = fill_own_rect(im, (l - gl, t - gt, r - gl, b - gt))
333
+ return im
334
+
335
+ def own_rect(self, shot: Shot, bbox) -> tuple[int, int, int, int]:
336
+ gl, gt = shot.box[0], shot.box[1]
337
+ l, t, r, b = bbox
338
+ return (l - gl, t - gt, r - gl, b - gt)
339
+
340
+
341
+ def finish(geo: Geometry, panel: Image.Image) -> Image.Image:
342
+ """贴二值圆角遮罩;缝隙/圆角外是 KEY,被 Tk 抠成透明。"""
343
+ out = Image.new("RGB", (geo.width, geo.height), KEY)
344
+ out.paste(panel.convert("RGB"), (0, 0), geo.mask_hard)
345
+ return out
346
+
347
+
348
+ def paste_mic(geo: Geometry, im: Image.Image) -> Image.Image:
349
+ """麦克风图标贴进玻璃帧,按背后亮度选浅/深两版(和仓库原做法一致)。"""
350
+ x, y = geo.mic_pos
351
+ box = im.crop((x, y, x + MIC_SIZE, y + MIC_SIZE)).convert("L")
352
+ bg = float(np.median(np.asarray(box))) / 255.0
353
+ out = im.convert("RGBA")
354
+ icon = MIC_LIGHT if bg < 0.48 else MIC_DARK
355
+ out.paste(icon, (x, y), icon)
356
+ return out.convert("RGB")
357
+
358
+
359
+ __all__ = [
360
+ "CaptureSource", "FORCE", "MIC_DARK", "MIC_LIGHT", "MotionTracker", "Shot",
361
+ "fill_own_rect", "finish", "paste_mic", "resample",
362
+ ]