dsh-watch-together 0.2.11 → 0.2.12
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.
- package/CHANGELOG.md +92 -0
- package/docs/VOICE.zh.md +49 -1
- package/dsh.plugin.json +1 -1
- package/examples/floating-chat/glass_capture.py +56 -1
- package/examples/floating-chat/glass_geometry.py +31 -8
- package/examples/floating-chat/window.py +7 -2
- package/examples/floating-chat/window_widgets.py +25 -5
- package/examples/voice-edge-tts/index.mjs +65 -2
- package/examples/voice-edge-tts/stream/client.mjs +151 -0
- package/examples/voice-edge-tts/stream/daemon.py +494 -0
- package/examples/voice-edge-tts/stream/warm.mp3 +0 -0
- package/package.json +5 -2
- package/src/watch-loop.js +12 -6
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,98 @@
|
|
|
3
3
|
All notable changes to **dsh-watch-together** are documented here.
|
|
4
4
|
This package starts its own version line at `0.0.7` — it is not a continuation of `dsh-video-storyboard`.
|
|
5
5
|
|
|
6
|
+
## [0.2.12] - 2026-11-04
|
|
7
|
+
|
|
8
|
+
### Fixed
|
|
9
|
+
|
|
10
|
+
- **在悬浮窗打字不再往宿主的「排队消息」里塞一条**(`wakeOnChat` 默认 `true` → `false`)。
|
|
11
|
+
每打一句话,输入框上方就多一条排队消息 —— 而窗口里明明已经有气泡显示过了,
|
|
12
|
+
队列里再来一条既是噪音、又占住输入框。根因是 `wakeSession` 走宿主的 `agent.followup()`,
|
|
13
|
+
而 DSH 的 QueueDock 不过滤来源,绕不开,只能不投。
|
|
14
|
+
**关掉不会丢话**:钟那一拍整个跳过、聊天通道不消费,消息留在里面,模型下次调
|
|
15
|
+
`watch_together` 时 poll 得到;真正的阻塞等待(`wait` / `nextLine`)走另一条路,
|
|
16
|
+
照旧能随时打断。
|
|
17
|
+
|
|
18
|
+
### Added — 气泡底板
|
|
19
|
+
|
|
20
|
+
聊天气泡内部铺一层 `#07111d`、alpha 0.50 的圆角底板(`glass_geometry.BUBBLE_PLATE`),
|
|
21
|
+
文字的对比度不再跟着画面走。底板在玻璃合成层做(`_overlay` 的 tint),CPU / GPU 两条
|
|
22
|
+
路径共用同一份实现;气泡宽度变了跟着一起重算;空态不铺(四个占位框铺深色会像四个空洞)。
|
|
23
|
+
|
|
24
|
+
实测:760×560、同一段消息、同一位置,只切 `DSH_GLASS_PLATE` 拍两版,取气泡内
|
|
25
|
+
「底板中位灰度 / 文字笔画 p97」算 WCAG 对比度。
|
|
26
|
+
|
|
27
|
+
| 背景 | 改动前 | 改动后 |
|
|
28
|
+
|---|---|---|
|
|
29
|
+
| 纯白(最坏情况) | 1.26–1.53:1 | 3.83–4.25:1 |
|
|
30
|
+
| 深蓝黑 | 16.3–17.7:1 | 17.0–17.2:1 |
|
|
31
|
+
|
|
32
|
+
alpha 0.40 时纯白背景只有 2.88–3.31:1(试过),0.50 才到 4.2。
|
|
33
|
+
|
|
34
|
+
`TextLayer.draw(shadow=True)` 给每个字先落一层 `+1px` 的深色副本。Tk 的 text item 没有
|
|
35
|
+
stroke / outline,只能多建一层 item;只在气泡正文开,`refresh()` 用 `tshadow` 标签把
|
|
36
|
+
它排除在翻色之外(目前暂存)。
|
|
37
|
+
|
|
38
|
+
### Changed — 声音延迟 2.4 秒 → 0.2 秒(常驻合成器)
|
|
39
|
+
|
|
40
|
+
> 台词几分钟前就写好了,第一声却要等两秒多 —— 听起来不像它在说,像在等我念。
|
|
41
|
+
|
|
42
|
+
老路是**每句起两个进程**:一个 `edge-tts.exe` 合成到临时 mp3,一个 `ffplay` 播放。
|
|
43
|
+
实测(Win11 / i9-12900HX,短句与长句各三次取均值)端到端 **2.4~3.0 秒**,
|
|
44
|
+
而且这四笔开销**每句都要重付一次**:
|
|
45
|
+
|
|
46
|
+
| 段 | 耗时 |
|
|
47
|
+
|---|---|
|
|
48
|
+
| pip 的 exe shim 拉起 python | ~600ms |
|
|
49
|
+
| python 解释器冷启动 | ~600ms |
|
|
50
|
+
| `import edge_tts` | ~700ms |
|
|
51
|
+
| WebSocket 建连(DNS+TCP+TLS+token) | 620~760ms |
|
|
52
|
+
| 首块合成 | 200~300ms |
|
|
53
|
+
| 剩余音频块 | 30~130ms |
|
|
54
|
+
| ffplay 启动 + demuxer 探测 | 380~410ms |
|
|
55
|
+
|
|
56
|
+
`examples/voice-edge-tts/stream/daemon.py` 把三件事搬进一个常驻进程:
|
|
57
|
+
|
|
58
|
+
1. **常驻 python**:`import edge_tts` 只做一次。
|
|
59
|
+
2. **长连接复用**:一条 WebSocket 上连发多个 SSML 请求(Azure 协议本来就支持)。
|
|
60
|
+
实测连续 20 句首块 **min 182 / avg 200 / max 235ms**,没有退化。
|
|
61
|
+
服务端在 `turn.end` 之后约 **30 秒**关连接(30s 还活着、35s 已死;发 ping 保不住),
|
|
62
|
+
所以空闲超 25s 主动断、下次用时重建(620~760ms)。
|
|
63
|
+
3. **常驻 ffplay**:一个进程从 stdin 连续吃 mp3 帧。实测三段音频拼着写进去,
|
|
64
|
+
时间码一路涨到 7.3s、进程没退 —— 每句起进程要付 380ms 首声。
|
|
65
|
+
|
|
66
|
+
同一条 `due` 事件、同一台机器上的对照:
|
|
67
|
+
|
|
68
|
+
| 场景 | 老路 | 现在 |
|
|
69
|
+
|---|---|---|
|
|
70
|
+
| 预取命中(`scheduled` 已合成) | 1009~1674ms | **1ms** |
|
|
71
|
+
| 没赶上预取(`see-now` 的 `at:null`) | 2485ms | **230ms** |
|
|
72
|
+
| 连续第三句 | 排队 4.9s 后被丢弃 | 1ms |
|
|
73
|
+
|
|
74
|
+
预取队列也不再"满 6 句就丢弃":常驻通道按 text 在内存里缓存(上限 80 句),
|
|
75
|
+
老路那个 `MAX_PREFETCH = 6` 是文件缓存 + 串行 CLI 逼出来的,这里不用照抄。
|
|
76
|
+
|
|
77
|
+
**兜底**:python 找不到、`daemon.py` 不存在、进程起不来 —— 任何一步失败都退回老路
|
|
78
|
+
(每句一个 CLI 进程),没有一行 throw。`DSH_TTS_STREAM=0` 可强制走老路排查。
|
|
79
|
+
调试时 `DSH_TTS_FFPLAY_LOG=info` 会把 ffplay 的时间码放出来。
|
|
80
|
+
|
|
81
|
+
`test/tts-stream.test.mjs` 覆盖协议(first/done 顺序、error 后通道继续可用、进程死掉后不挂在超时上),
|
|
82
|
+
不依赖网络和 ffplay。
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
> Issue #44 第 2 条:文字直接压在实时视频上,对比度每秒都在变,连看 5–10 分钟眼睛发酸。
|
|
86
|
+
|
|
87
|
+
有底板之后底色恒定,`TextLayer.adapt()` 对气泡正文已经没有意义,反而会在过渡帧翻错
|
|
88
|
+
(白字被翻成深色,压在深色底板上更看不见)。给 `draw()` 加了 `adapt=False`:这些 item
|
|
89
|
+
不参与采样。标题栏、输入框、空态提示仍走逐字翻色 —— 它们确实直接压在玻璃上。
|
|
90
|
+
|
|
91
|
+
- 跟 `dsh-video-storyboard` 0.6.6 一起发。依赖范围 `^0.6.0` 不用改。
|
|
92
|
+
上游这次是排布与计费对齐(同素材 token -9.3%),**本包自己的代码没有改动**。
|
|
93
|
+
|
|
94
|
+
### 调试开关
|
|
95
|
+
|
|
96
|
+
`DSH_GLASS_PLATE=0` 关掉底板和描边,回到 0.2.11 的行为 —— 只用来拍新旧对比图。
|
|
97
|
+
|
|
6
98
|
## [0.2.11] - 2026-11-03
|
|
7
99
|
|
|
8
100
|
> 悬浮窗从头拆了一遍(单文件 1931 行 → 五层),顺带修掉 GPU 路径三个真 bug。
|
package/docs/VOICE.zh.md
CHANGED
|
@@ -250,7 +250,53 @@ api.onSpeech((e) => {
|
|
|
250
250
|
|
|
251
251
|
---
|
|
252
252
|
|
|
253
|
-
## 7.
|
|
253
|
+
## 7. 为什么延迟只有 0.2 秒(常驻合成器)
|
|
254
|
+
|
|
255
|
+
> 这一节是给"想搞清楚它快在哪"的人看的。只想让它出声,前面几节就够了。
|
|
256
|
+
|
|
257
|
+
适配器有两条路,默认走新的:
|
|
258
|
+
|
|
259
|
+
| 路 | 怎么干活 | 一句的代价 |
|
|
260
|
+
|---|---|---|
|
|
261
|
+
| **常驻**(默认) | 一个 python 进程 + 一条 WebSocket + 一个 ffplay,一直活着 | 首块 **170~200ms**;预取命中 **~0ms** |
|
|
262
|
+
| 逐句(兜底) | 每句起一个 `edge-tts.exe`、合成到临时 mp3、再起一个 `ffplay` | **2.4~3.0 秒** |
|
|
263
|
+
|
|
264
|
+
老路慢不是因为网络,是因为四笔**固定开销每句重付一遍**:pip 的 exe shim 拉 python(~600ms)、
|
|
265
|
+
解释器冷启动(~600ms)、`import edge_tts`(~700ms)、WebSocket 建连(620~760ms),
|
|
266
|
+
再加上 ffplay 启动与 demuxer 探测(~400ms)。
|
|
267
|
+
|
|
268
|
+
常驻版把这三件事各自省掉:
|
|
269
|
+
|
|
270
|
+
- **进程只起一次** → 前 1.9 秒消失;
|
|
271
|
+
- **连接复用**:一条 WebSocket 上连发多句(Azure 协议本来支持)。实测连续 20 句首块
|
|
272
|
+
`min 182 / avg 200 / max 235ms`,不退化。服务端在 `turn.end` 后约 **30 秒**关连接,
|
|
273
|
+
所以空闲超 25s 就主动断,下次用重建(620~760ms)——**不会拿死连接去发请求**(那是丢句子);
|
|
274
|
+
- **ffplay 常驻**:一个进程从 stdin 连续吃 mp3 帧,句与句之间不用重启。
|
|
275
|
+
启动时先喂 0.3 秒静音把 demuxer 探测(~200ms)提前花掉。
|
|
276
|
+
|
|
277
|
+
预取也和以前不一样:`scheduled` 到了就把整句合成好放内存,`due` 时只写管道 ——
|
|
278
|
+
所以"到点"和"出声"几乎是同一刻。
|
|
279
|
+
|
|
280
|
+
**开关**:
|
|
281
|
+
|
|
282
|
+
```bash
|
|
283
|
+
# 强制走老路(怀疑常驻通道有问题时,用来排除)
|
|
284
|
+
DSH_TTS_STREAM=0
|
|
285
|
+
|
|
286
|
+
# 看 ffplay 的时间码(M-A 一路涨 = 真的在播,不是管道里堆着)
|
|
287
|
+
DSH_TTS_FFPLAY_LOG=info
|
|
288
|
+
|
|
289
|
+
# 调音量(0~100,默认 100)
|
|
290
|
+
DSH_TTS_VOLUME=60
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
**它不会因为挂了就没声音**:python 找不到、`daemon.py` 缺了、进程起不来 ——
|
|
294
|
+
任何一种情况都退回逐句那条路,日志里会有一行
|
|
295
|
+
`[voice] 常驻合成器起不来:…` 或 `[voice] 常驻合成器停了(…),下一句起退回逐句合成`。
|
|
296
|
+
|
|
297
|
+
---
|
|
298
|
+
|
|
299
|
+
## 8. 排错表
|
|
254
300
|
|
|
255
301
|
| 现象 | 原因 | 怎么办 |
|
|
256
302
|
|---|---|---|
|
|
@@ -260,3 +306,5 @@ api.onSpeech((e) => {
|
|
|
260
306
|
| 想确认现在用的是不是晓萱 | —— | 跑 `node watch.mjs say "测试"`,听音色 |
|
|
261
307
|
| `doctor` 说一切正常,但就是没声音 | 正常——`doctor` 不查声音 | 以 stderr 的 `[voice …]` 为准 |
|
|
262
308
|
| 改了 `tts.json` 没生效 | 没重启陪看 | 重启陪看进程 |
|
|
309
|
+
| 每句都要等两秒才出声 | 没走常驻通道(stderr 里是 `[voice …] synth ready …` 而不是 `stream first=…`) | 看有没有 `[voice] 常驻合成器起不来:…`;确认 `DSH_TTS_STREAM` 不是 `0`;`python -c "import edge_tts"` 能不能跑通 |
|
|
310
|
+
| 第一句快、过一会儿又变慢 | 空闲超过 30 秒,服务端把连接关了,正在重建 | 正常现象(重建 ~700ms)。连着说话时不会发生 |
|
package/dsh.plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-watch-together",
|
|
3
3
|
"description": "Watch a video together with a text-only agent: follow the user's real playback position and hand over one segment at a time, just before the segment ends.",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.12",
|
|
5
5
|
"entry": {
|
|
6
6
|
"name": "dsh-watch-together",
|
|
7
7
|
"inject": [
|
|
@@ -38,6 +38,50 @@ STALE_AFTER = 0.30 # 运动结束后多久允许跳帧
|
|
|
38
38
|
|
|
39
39
|
FORCE = os.environ.get("GLASS_FORCE") == "1"
|
|
40
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
|
+
|
|
41
85
|
|
|
42
86
|
def _load_mic() -> tuple[Image.Image, Image.Image]:
|
|
43
87
|
"""麦克风图标:去背景得到 alpha,再做浅色/深色两版(按背后亮度挑)。"""
|
|
@@ -243,7 +287,18 @@ class CaptureSource:
|
|
|
243
287
|
# —— 表现就是日志刷屏、背景永久停在旧帧。没有可抓的区域就别抓。
|
|
244
288
|
if gr - gl <= 0 or gb - gt <= 0:
|
|
245
289
|
return None
|
|
246
|
-
|
|
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))))
|
|
247
302
|
return Shot(shot=shot, box=(gl, gt, gr, gb),
|
|
248
303
|
offset=(int(round((l - gl) / LPF)), int(round((t - gt) / LPF))))
|
|
249
304
|
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
"""
|
|
14
14
|
from __future__ import annotations
|
|
15
15
|
|
|
16
|
+
import os
|
|
16
17
|
from dataclasses import dataclass, field, replace
|
|
17
18
|
from typing import Iterable
|
|
18
19
|
|
|
@@ -34,6 +35,13 @@ SLAB_OUT, SLAB_TOP_H, SLAB_BOT_H = 12, 54, 70
|
|
|
34
35
|
SLAB_GAP = 10
|
|
35
36
|
SLAB_RADIUS = 22
|
|
36
37
|
|
|
38
|
+
# 气泡底板:文字底下是实时视频,对比度每秒都在变;给每块气泡铺一层深色,
|
|
39
|
+
# 文字的对比度就只由这层决定,不再跟着画面走。alpha 0.50(128/255)——
|
|
40
|
+
# 白字压在纯白画面上也能到 4.2:1,达到正文可读的下限;再低(0.40)只有 2.9:1。
|
|
41
|
+
# `DSH_GLASS_PLATE=0` 关掉(只用于新旧对比截图,正常别用)。
|
|
42
|
+
PLATE = os.environ.get("DSH_GLASS_PLATE", "1") != "0"
|
|
43
|
+
BUBBLE_PLATE = (7, 17, 29, 128) if PLATE else (0, 0, 0, 0)
|
|
44
|
+
|
|
37
45
|
# 抓屏时向外扩一圈,边缘透镜才有「框外」的像素可采
|
|
38
46
|
PAD = 40
|
|
39
47
|
BAND = 64 # 全分辨率下的透镜带宽度
|
|
@@ -101,15 +109,24 @@ def _rounded_mask(w: int, h: int, boxes: Iterable[Box]) -> Image.Image:
|
|
|
101
109
|
return m.resize((w, h), Image.Resampling.LANCZOS)
|
|
102
110
|
|
|
103
111
|
|
|
104
|
-
def _overlay(w: int, h: int, shapes: tuple[Box, ...]) -> Image.Image:
|
|
105
|
-
"""
|
|
112
|
+
def _overlay(w: int, h: int, shapes: tuple[Box, ...], plate: bool = True) -> Image.Image:
|
|
113
|
+
"""内部框的染色。气泡铺底板(文字靠它稳住对比度),其余仍是极淡的冷色。
|
|
114
|
+
|
|
115
|
+
`plate=False` 用于没有消息的空态:那四个槽位只是占位,铺深色反而像四个空洞。
|
|
116
|
+
"""
|
|
106
117
|
layer = Image.new("RGBA", (w, h), (0, 0, 0, 0))
|
|
107
118
|
d = ImageDraw.Draw(layer)
|
|
108
119
|
tints = ((235, 242, 255, 5), (110, 175, 255, 14), (235, 242, 255, 4),
|
|
109
120
|
(235, 242, 255, 4), (235, 242, 255, 5), (110, 175, 255, 12))
|
|
110
|
-
for (x0, y0, x1, y1, r), fill in zip(shapes, tints):
|
|
121
|
+
for i, ((x0, y0, x1, y1, r), fill) in enumerate(zip(shapes, tints)):
|
|
111
122
|
if x1 > x0 and y1 > y0:
|
|
112
|
-
|
|
123
|
+
if plate and PLATE and i < MESSAGE_SLOTS:
|
|
124
|
+
# 向外 1px:内框边缘有折射带,底板正好压在它上面,否则那圈
|
|
125
|
+
# 折射出来的背景色会变成一条彩色描边(亮背景上特别明显)
|
|
126
|
+
d.rounded_rectangle((x0 - 1, y0 - 1, x1 + 1, y1 + 1), radius=r + 1,
|
|
127
|
+
fill=BUBBLE_PLATE)
|
|
128
|
+
else:
|
|
129
|
+
d.rounded_rectangle((x0, y0, x1, y1), radius=r, fill=fill)
|
|
113
130
|
return layer
|
|
114
131
|
|
|
115
132
|
|
|
@@ -199,6 +216,7 @@ class Geometry:
|
|
|
199
216
|
shapes: tuple[Box, ...] = ()
|
|
200
217
|
overlay: Image.Image | None = None
|
|
201
218
|
overlay_half: Image.Image | None = None
|
|
219
|
+
plate: bool = False # 当前 overlay 有没有气泡底板(空态为 False)
|
|
202
220
|
box_maps: tuple[tuple, ...] = ()
|
|
203
221
|
box_union_half: Image.Image | None = None
|
|
204
222
|
_mic_pos: tuple[int, int] = field(default=(0, 0), repr=False)
|
|
@@ -217,18 +235,23 @@ class Geometry:
|
|
|
217
235
|
slabs=slabs_for(w, h), mask_hard=mask_hard,
|
|
218
236
|
warp_x=warp_x, warp_y=warp_y,
|
|
219
237
|
_mic_pos=(MIC_MARGIN[0], h - MIC_MARGIN[1]))
|
|
220
|
-
return base.with_shapes(shapes, version=version)
|
|
238
|
+
return base.with_shapes(shapes, version=version, plate=False)
|
|
221
239
|
|
|
222
|
-
def with_shapes(self, shapes: Iterable[Box], version: int | None = None
|
|
240
|
+
def with_shapes(self, shapes: Iterable[Box], version: int | None = None,
|
|
241
|
+
plate: bool = True) -> "Geometry":
|
|
223
242
|
shapes = tuple(shapes)
|
|
224
|
-
overlay = _overlay(self.width, self.height, shapes)
|
|
243
|
+
overlay = _overlay(self.width, self.height, shapes, plate=plate)
|
|
225
244
|
hw, hh = max(1, self.width // 2), max(1, self.height // 2)
|
|
245
|
+
# GPU 只按 (尺寸, version) 决定要不要重传纹理:形状没变、只多了底板时
|
|
246
|
+
# 也得换 version,否则会一直显示空态那张 overlay。
|
|
247
|
+
bump = version is None or plate != self.plate
|
|
226
248
|
return replace(
|
|
227
249
|
self,
|
|
228
|
-
version=(self.version + 1) if
|
|
250
|
+
version=(self.version + 1) if bump else self.version,
|
|
229
251
|
shapes=shapes,
|
|
230
252
|
overlay=overlay,
|
|
231
253
|
overlay_half=overlay.resize((hw, hh), Image.Resampling.BILINEAR),
|
|
254
|
+
plate=plate,
|
|
232
255
|
box_maps=_box_maps(shapes, self.width, self.height),
|
|
233
256
|
box_union_half=_box_union(self.width, self.height, hw, hh, shapes),
|
|
234
257
|
)
|
|
@@ -75,6 +75,9 @@ SNAPSHOT = os.environ.get("DSH_GLASS_SNAPSHOT") == "1"
|
|
|
75
75
|
# GPU:native 表示全分辨率采样(边缘透镜没有 1/4 放大的像素感)
|
|
76
76
|
NATIVE = os.environ.get("DSH_GLASS_NATIVE") == "1"
|
|
77
77
|
USE_GPU = NATIVE or os.environ.get("DSH_GLASS_GPU") == "1"
|
|
78
|
+
# 气泡底板(和 glass_geometry.BUBBLE_PLATE 同一个开关):关掉 = 回到逐字翻色,
|
|
79
|
+
# 只用来拍新旧对比图,正常别动。
|
|
80
|
+
PLATE = os.environ.get("DSH_GLASS_PLATE", "1") != "0"
|
|
78
81
|
|
|
79
82
|
HERE = Path(__file__).resolve().parent
|
|
80
83
|
|
|
@@ -796,15 +799,17 @@ class LiveGlass:
|
|
|
796
799
|
shapes, infos = shapes_for(w, self._geo.height), []
|
|
797
800
|
if shapes != self._geo.shapes:
|
|
798
801
|
with self._geo_lock:
|
|
799
|
-
self._set_geometry(self._geo.with_shapes(shapes))
|
|
802
|
+
self._set_geometry(self._geo.with_shapes(shapes, plate=bool(shown)))
|
|
800
803
|
# 每条消息只按正文占一块;时间戳贴在气泡上方,不进框
|
|
801
804
|
for info in infos:
|
|
802
805
|
if info["stamp"]:
|
|
803
806
|
self.text.draw(info["tx"], info["stamp_y"], info["stamp"],
|
|
804
807
|
anchor=info["ta"], fill="#a8b7c9", size=9, tags=("feed",))
|
|
805
808
|
for li, line in enumerate(info["lines"]):
|
|
809
|
+
# 气泡里有底板,文字颜色固定、再补一层 1px 深色偏移当描边
|
|
806
810
|
self.text.draw(info["tx"], info["ty"] + li * info["ls"], line,
|
|
807
|
-
anchor=info["ta"], fill="#edf6ff", size=11, tags=("feed",)
|
|
811
|
+
anchor=info["ta"], fill="#edf6ff", size=11, tags=("feed",),
|
|
812
|
+
shadow=PLATE, adapt=not PLATE)
|
|
808
813
|
if not shown:
|
|
809
814
|
slot = self._geo.shapes[0]
|
|
810
815
|
self.text.draw(w // 2, slot[1] + (slot[3] - slot[1]) // 2,
|
|
@@ -186,22 +186,32 @@ class TextLayer:
|
|
|
186
186
|
self.items: list[int] = []
|
|
187
187
|
self._colors: dict = {}
|
|
188
188
|
self._pending: dict = {}
|
|
189
|
+
self._fixed: set = set() # 有底板的文字:颜色不跟背景走
|
|
189
190
|
self._at = 0.0
|
|
190
191
|
|
|
191
192
|
def refresh(self) -> None:
|
|
192
|
-
|
|
193
|
+
# 描边是另建的一层 item,翻色不能把它也算进去(会跟着一起变色)
|
|
194
|
+
shadow = set(self.canvas.find_withtag("tshadow"))
|
|
195
|
+
self.items = [i for i in self.canvas.find_all()
|
|
196
|
+
if i not in shadow and self.canvas.type(i) == "text"]
|
|
193
197
|
|
|
194
198
|
def reset(self) -> None:
|
|
195
199
|
self.items = []
|
|
196
200
|
self._colors.clear()
|
|
197
201
|
self._pending.clear()
|
|
202
|
+
self._fixed.clear()
|
|
198
203
|
self._at = 0.0
|
|
199
204
|
|
|
200
205
|
# ---- 绘制 ----
|
|
201
206
|
|
|
202
207
|
def draw(self, x, y, text, anchor="center", fill=COLOR_LIGHT,
|
|
203
|
-
size=11, bold=False, max_width=None, tags=()
|
|
204
|
-
|
|
208
|
+
size=11, bold=False, max_width=None, tags=(), shadow=False,
|
|
209
|
+
adapt=True) -> None:
|
|
210
|
+
"""按字符拆开建 item;anchor 支持 w/e/center 与 n/s 变体。
|
|
211
|
+
|
|
212
|
+
`shadow=True` 时每个字先落一层偏移 1px 的深色副本,给亮背景一条边界;
|
|
213
|
+
`adapt=False` 表示这块字有自己的底板,颜色固定、不参与 `adapt()` 采样。
|
|
214
|
+
"""
|
|
205
215
|
font = self.fonts.get(size, bold)
|
|
206
216
|
measure = font.measure
|
|
207
217
|
linespace = font.metrics("linespace")
|
|
@@ -221,6 +231,8 @@ class TextLayer:
|
|
|
221
231
|
center = anchor in ("center", "n", "s")
|
|
222
232
|
height = font.metrics("ascent") + font.metrics("descent")
|
|
223
233
|
spec = self.fonts.spec(size, bold)
|
|
234
|
+
base_tags = tags if isinstance(tags, tuple) else ((tags,) if tags else ())
|
|
235
|
+
shadow_tags = base_tags + ("tshadow",) if shadow else ()
|
|
224
236
|
for row, line in enumerate(lines):
|
|
225
237
|
width = measure(line)
|
|
226
238
|
lx = x - width if right else (x - width / 2 if center else x)
|
|
@@ -229,8 +241,14 @@ class TextLayer:
|
|
|
229
241
|
# 累积宽度,别对每个字重新 measure 前缀(那是 O(n²) 次 Tcl 调用)
|
|
230
242
|
cx = lx
|
|
231
243
|
for ch in line:
|
|
232
|
-
|
|
233
|
-
|
|
244
|
+
if shadow:
|
|
245
|
+
self.canvas.create_text(cx + 1, ly + 1, text=ch, anchor="w",
|
|
246
|
+
fill=self.COLOR_DARK, font=spec,
|
|
247
|
+
tags=shadow_tags)
|
|
248
|
+
item = self.canvas.create_text(cx, ly, text=ch, anchor="w",
|
|
249
|
+
fill=fill, font=spec, tags=tags)
|
|
250
|
+
if not adapt:
|
|
251
|
+
self._fixed.add(item)
|
|
234
252
|
cx += measure(ch)
|
|
235
253
|
|
|
236
254
|
# ---- 翻色 ----
|
|
@@ -255,6 +273,8 @@ class TextLayer:
|
|
|
255
273
|
gray = np.asarray(frame.convert("L"))
|
|
256
274
|
h, w = gray.shape[:2]
|
|
257
275
|
for item in self.items:
|
|
276
|
+
if item in self._fixed: # 有底板的字:颜色固定,别跟着画面翻
|
|
277
|
+
continue
|
|
258
278
|
box = self.canvas.bbox(item)
|
|
259
279
|
if not box:
|
|
260
280
|
continue
|
|
@@ -43,7 +43,10 @@
|
|
|
43
43
|
import { execFile } from 'node:child_process';
|
|
44
44
|
import { existsSync, readFileSync, statSync, unlinkSync } from 'node:fs';
|
|
45
45
|
import { homedir, tmpdir } from 'node:os';
|
|
46
|
-
import { join } from 'node:path';
|
|
46
|
+
import { dirname, join } from 'node:path';
|
|
47
|
+
import { fileURLToPath } from 'node:url';
|
|
48
|
+
|
|
49
|
+
import { pythonFor, startStream } from './stream/client.mjs';
|
|
47
50
|
|
|
48
51
|
const run = (bin, args, timeoutMs = 60_000) => new Promise((resolve) => {
|
|
49
52
|
execFile(bin, args, { timeout: timeoutMs, windowsHide: true }, (err) => resolve(!err));
|
|
@@ -82,6 +85,41 @@ function edgeBin(cfg) {
|
|
|
82
85
|
return null;
|
|
83
86
|
}
|
|
84
87
|
|
|
88
|
+
/**
|
|
89
|
+
* 起常驻合成器(`stream/daemon.py`)。**任何一步失败都返回 null**。
|
|
90
|
+
*
|
|
91
|
+
* 声音是可选能力:这里出问题只能退回"每句一个 CLI 进程"的老路,
|
|
92
|
+
* 不能让陪看因为守护进程起不来就整个没声音。所以没有一行 throw。
|
|
93
|
+
*
|
|
94
|
+
* 收益(实测,Win11):每句 2.4~3.0s → **170~200ms**;预取命中时 **0ms**。
|
|
95
|
+
* 老路每一句都要重付 python 启动 + import + 建连 + ffplay 启动,那是四笔固定开销。
|
|
96
|
+
*
|
|
97
|
+
* `DSH_TTS_STREAM=0` 可以用来强制走老路(排查"到底是不是它的问题")。
|
|
98
|
+
*/
|
|
99
|
+
function openStream(bin) {
|
|
100
|
+
if (String(process.env.DSH_TTS_STREAM ?? '1') === '0') return null;
|
|
101
|
+
const python = pythonFor(bin);
|
|
102
|
+
if (!python) return null;
|
|
103
|
+
let script;
|
|
104
|
+
try {
|
|
105
|
+
script = join(dirname(fileURLToPath(import.meta.url)), 'stream', 'daemon.py');
|
|
106
|
+
} catch {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
if (!existsSync(script)) return null;
|
|
110
|
+
try {
|
|
111
|
+
return startStream({
|
|
112
|
+
python,
|
|
113
|
+
script,
|
|
114
|
+
log: (m) => console.error(m),
|
|
115
|
+
onError: (reason) => console.error(`[voice] 常驻合成器停了(${reason}),下一句起退回逐句合成`),
|
|
116
|
+
});
|
|
117
|
+
} catch (e) {
|
|
118
|
+
console.error(`[voice] 常驻合成器起不来:${e?.message ?? e}`);
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
85
123
|
/** 只合成,不播放。预取和"到点没赶上预取"两条路共用。 */
|
|
86
124
|
async function synthEdge(text, { bin, voice, rate }) {
|
|
87
125
|
const out = join(tmpdir(), `voice-${Date.now()}-${Math.random().toString(36).slice(2, 7)}.mp3`);
|
|
@@ -148,6 +186,8 @@ export function attach(api) {
|
|
|
148
186
|
+ '想用晓萱等音色请在该文件加 "voice": "zh-CN-XiaoxuanNeural"');
|
|
149
187
|
const rate = Number(cfg.rate) || 0;
|
|
150
188
|
const bin = edgeBin(cfg);
|
|
189
|
+
// 常驻合成器:能起就用它(首声 170~200ms),起不来就是 null,全部逻辑退回老路。
|
|
190
|
+
const stream = openStream(bin);
|
|
151
191
|
let chain = Promise.resolve(); // 播放串行:两句绝不重叠着念
|
|
152
192
|
|
|
153
193
|
// **预合成**:核心在台词写好、还没到点时发 `scheduled`。这里趁这段时间把 mp3 合成好,
|
|
@@ -200,6 +240,12 @@ export function attach(api) {
|
|
|
200
240
|
|
|
201
241
|
const off = api.onSpeech((e) => {
|
|
202
242
|
if (e.state === 'scheduled') {
|
|
243
|
+
// 常驻通道不需要"排队 6 句"那套:它按 text 在内存里缓存,满了淘汰最老的。
|
|
244
|
+
// 老路的 `MAX_PREFETCH` 是文件缓存 + 串行 CLI 逼出来的,这里不用照抄。
|
|
245
|
+
if (stream?.alive && e.at !== null && e.at !== undefined && e.text) {
|
|
246
|
+
stream.prefetch(e.text);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
203
249
|
prefetch(e);
|
|
204
250
|
return;
|
|
205
251
|
}
|
|
@@ -236,6 +282,22 @@ export function attach(api) {
|
|
|
236
282
|
if (ready) prefetched.delete(key);
|
|
237
283
|
const t0 = Date.now();
|
|
238
284
|
let audio = null;
|
|
285
|
+
// **常驻通道优先**:音频边收边写进常驻 ffplay 的管道,首块就是出声
|
|
286
|
+
// (实测 170~200ms;预取命中时 0ms)。失败也只在**没出过声**时才往下兜底,
|
|
287
|
+
// 出过声再补一遍会变成一句话念两次。
|
|
288
|
+
if (stream?.alive) {
|
|
289
|
+
try {
|
|
290
|
+
const r = await stream.say(e.text, { onFirst: onStart });
|
|
291
|
+
if (!r?.skipped) {
|
|
292
|
+
console.error(`[voice ${mmss(e.at)}] stream first=${r?.first ?? '-'}ms `
|
|
293
|
+
+ `done=${r?.done ?? '-'}ms (wait ${waited}ms): ${e.text}`);
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
} catch (err) {
|
|
297
|
+
if (reported) return;
|
|
298
|
+
console.error(`[voice] 常驻通道失败(${err?.message ?? err}),本句退回逐句合成`);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
239
301
|
if (bin) {
|
|
240
302
|
if (ready) {
|
|
241
303
|
audio = await ready.task.catch(() => ({ ok: false, reason: 'prefetch-failed' }));
|
|
@@ -256,11 +318,12 @@ export function attach(api) {
|
|
|
256
318
|
}).catch((err) => console.error(`[voice] ${err?.message ?? err}`));
|
|
257
319
|
});
|
|
258
320
|
|
|
259
|
-
console.error(`[voice] 已接上(engine=${bin ? 'edge-tts' : 'sapi'},voice=${voice})`);
|
|
321
|
+
console.error(`[voice] 已接上(engine=${stream?.alive ? 'edge-tts/常驻' : bin ? 'edge-tts' : 'sapi'},voice=${voice})`);
|
|
260
322
|
return () => {
|
|
261
323
|
off();
|
|
262
324
|
for (const entry of prefetched.values()) discard(entry);
|
|
263
325
|
prefetched.clear();
|
|
326
|
+
try { stream?.stop(); } catch { /* 已经退出 */ }
|
|
264
327
|
};
|
|
265
328
|
}
|
|
266
329
|
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* client.mjs — 跑 `daemon.py` 并把它的 JSON 行协议包成 Promise。
|
|
3
|
+
*
|
|
4
|
+
* 只做三件事:起进程、按 id 配对请求与回执、进程死了让上层知道。
|
|
5
|
+
* **不判断该不该念**(那是语音总线的事),**也不碰引擎参数**(那是 daemon 自己的事)。
|
|
6
|
+
*
|
|
7
|
+
* 音频不经过这里:daemon 直接写进 ffplay 的管道,node 只收状态行。
|
|
8
|
+
* 这样多一跳就多一份缓冲,首声全被它吃掉。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { spawn } from 'node:child_process';
|
|
12
|
+
import { existsSync } from 'node:fs';
|
|
13
|
+
import { dirname, join } from 'node:path';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 从 `edge-tts` 可执行文件反推 python。
|
|
17
|
+
*
|
|
18
|
+
* 不用 `python` 裸名:用户机器上可能有好几个 python,而 edge_tts 只装在其中一个里
|
|
19
|
+
* (`<venv>/Scripts/edge-tts.exe` 旁边的 `python.exe` 才是对的)。
|
|
20
|
+
*/
|
|
21
|
+
export function pythonFor(edgeBin) {
|
|
22
|
+
if (!edgeBin) return null;
|
|
23
|
+
const dir = dirname(String(edgeBin));
|
|
24
|
+
const win = process.platform === 'win32';
|
|
25
|
+
const cands = win
|
|
26
|
+
? [join(dir, 'python.exe'), join(dir, 'python3.exe')]
|
|
27
|
+
: [join(dir, 'python3'), join(dir, 'python')];
|
|
28
|
+
for (const c of cands) {
|
|
29
|
+
try { if (existsSync(c)) return c; } catch { /* 下一个 */ }
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param {{ python: string, script: string, args?: string[], onError?: Function, log?: Function }} o
|
|
36
|
+
*/
|
|
37
|
+
export function startStream({ python, script, args = ['-u', script], onError, log = () => {} }) {
|
|
38
|
+
const extra = process.platform === 'win32' ? { windowsHide: true } : {};
|
|
39
|
+
const proc = spawn(python, args, {
|
|
40
|
+
stdio: ['pipe', 'pipe', 'pipe'], ...extra,
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
/** id -> {resolve, reject, first} */
|
|
44
|
+
const pending = new Map();
|
|
45
|
+
let buf = '';
|
|
46
|
+
let dead = null;
|
|
47
|
+
let ready = false;
|
|
48
|
+
let lastError = null;
|
|
49
|
+
|
|
50
|
+
proc.stdout.setEncoding('utf8');
|
|
51
|
+
proc.stdout.on('data', (d) => {
|
|
52
|
+
buf += d;
|
|
53
|
+
let i;
|
|
54
|
+
while ((i = buf.indexOf('\n')) >= 0) {
|
|
55
|
+
const line = buf.slice(0, i).trim();
|
|
56
|
+
buf = buf.slice(i + 1);
|
|
57
|
+
if (!line) continue;
|
|
58
|
+
let ev;
|
|
59
|
+
try { ev = JSON.parse(line); } catch { continue; }
|
|
60
|
+
if (ev.ev === 'ready') { ready = true; continue; }
|
|
61
|
+
if (ev.ev === 'boot') { log(`[stream] daemon 起来:voice=${ev.voice} rate=${ev.rate}`); continue; }
|
|
62
|
+
const entry = pending.get(ev.id);
|
|
63
|
+
if (!entry) continue;
|
|
64
|
+
if (ev.ev === 'first') {
|
|
65
|
+
entry.first = ev.ms;
|
|
66
|
+
// **先报出声,再等 done**:展示层要的是"字可以出现了",不是"这段念完了"。
|
|
67
|
+
try { entry.onFirst?.(ev.ms); } catch { /* 回调自己的事 */ }
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (ev.ev === 'done') {
|
|
71
|
+
pending.delete(ev.id);
|
|
72
|
+
entry.resolve({ first: entry.first ?? ev.ms ?? null, done: ev.ms ?? null });
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (ev.ev === 'skip') {
|
|
76
|
+
pending.delete(ev.id);
|
|
77
|
+
entry.resolve({ skipped: true });
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (ev.ev === 'error') {
|
|
81
|
+
pending.delete(ev.id);
|
|
82
|
+
lastError = ev.reason || 'unknown';
|
|
83
|
+
entry.reject(new Error(lastError));
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
proc.stderr.setEncoding('utf8');
|
|
90
|
+
proc.stderr.on('data', (d) => {
|
|
91
|
+
for (const line of String(d).split(/\r?\n/)) {
|
|
92
|
+
if (line.trim()) log(line);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
const fail = (reason) => {
|
|
97
|
+
if (dead) return;
|
|
98
|
+
dead = reason;
|
|
99
|
+
for (const [, entry] of pending) entry.reject(new Error(reason));
|
|
100
|
+
pending.clear();
|
|
101
|
+
try { onError?.(reason); } catch { /* 回调自己的事 */ }
|
|
102
|
+
};
|
|
103
|
+
proc.on('exit', (code) => fail(`daemon 退出 code=${code}`));
|
|
104
|
+
proc.on('error', (e) => fail(`daemon 起不来:${e.message}`));
|
|
105
|
+
|
|
106
|
+
const send = (obj) => {
|
|
107
|
+
if (dead) return false;
|
|
108
|
+
try {
|
|
109
|
+
proc.stdin.write(JSON.stringify(obj) + '\n');
|
|
110
|
+
return true;
|
|
111
|
+
} catch {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
let seq = 0;
|
|
117
|
+
const ask = (op, text, timeoutMs, onFirst) => new Promise((resolve, reject) => {
|
|
118
|
+
if (dead) { reject(new Error(dead)); return; }
|
|
119
|
+
seq += 1;
|
|
120
|
+
const id = seq;
|
|
121
|
+
// 超时兜底:网络卡住时 daemon 那边可能永远不返回,这边不能跟着挂住
|
|
122
|
+
const timer = setTimeout(() => {
|
|
123
|
+
pending.delete(id);
|
|
124
|
+
reject(new Error('timeout'));
|
|
125
|
+
}, timeoutMs);
|
|
126
|
+
pending.set(id, {
|
|
127
|
+
onFirst,
|
|
128
|
+
resolve: (v) => { clearTimeout(timer); resolve(v); },
|
|
129
|
+
reject: (e) => { clearTimeout(timer); reject(e); },
|
|
130
|
+
});
|
|
131
|
+
if (!send({ op, id, text })) {
|
|
132
|
+
clearTimeout(timer);
|
|
133
|
+
pending.delete(id);
|
|
134
|
+
reject(new Error(dead || 'send-failed'));
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
get alive() { return !dead; },
|
|
140
|
+
get warm() { return ready; },
|
|
141
|
+
get lastError() { return lastError; },
|
|
142
|
+
warmUp() { send({ op: 'warm' }); },
|
|
143
|
+
say: (text, { timeoutMs = 30_000, onFirst = null } = {}) => ask('say', text, timeoutMs, onFirst),
|
|
144
|
+
prefetch: (text, timeoutMs = 30_000) => ask('prefetch', text, timeoutMs).catch(() => ({ failed: true })),
|
|
145
|
+
forget: (text) => send({ op: 'forget', text }),
|
|
146
|
+
stop() {
|
|
147
|
+
try { send({ op: 'stop' }); } catch { /* already */ }
|
|
148
|
+
setTimeout(() => { try { proc.kill(); } catch { /* already */ } }, 300);
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
"""daemon.py — 常驻的 edge-tts 合成器 + 常驻播放管道。
|
|
2
|
+
|
|
3
|
+
## 为什么要有它(实测,2026-11-04,Win11 / i9-12900HX)
|
|
4
|
+
|
|
5
|
+
老路子是「每句起一个 `edge-tts.exe`,合成到临时 mp3,再起一个 `ffplay`」。实测端到端
|
|
6
|
+
**2.4~3.0 秒**,拆开是:
|
|
7
|
+
|
|
8
|
+
| 段 | 耗时 |
|
|
9
|
+
|---|---|
|
|
10
|
+
| pip 的 exe shim 拉起 python | ~600ms |
|
|
11
|
+
| python 解释器冷启动 | ~600ms |
|
|
12
|
+
| `import edge_tts` | ~700ms |
|
|
13
|
+
| WebSocket 建连(DNS+TCP+TLS+token) | 620~760ms |
|
|
14
|
+
| 首块合成 | 200~300ms |
|
|
15
|
+
| 剩余音频块 | 30~130ms |
|
|
16
|
+
| ffplay 启动 + demuxer 探测 | 380~410ms |
|
|
17
|
+
|
|
18
|
+
每一段都是**每句付一次**。所以优化不是一个点,是三条:
|
|
19
|
+
|
|
20
|
+
1. **常驻进程**:python 和 edge_tts 只加载一次 —— 省掉上面第 1~3 段(~1.9s)。
|
|
21
|
+
2. **长连接复用**:一条 WebSocket 上连发多个 SSML 请求(Azure 协议本来就支持)。
|
|
22
|
+
实测连续 20 句首块 **min 182 / avg 200 / max 235ms**,没有退化。
|
|
23
|
+
服务端在 `turn.end` 之后约 **30 秒**关连接(30s 还活着、35s 已死;发 ping 保不住),
|
|
24
|
+
所以空闲超过 `IDLE_TTL` 就主动断,下次用时重建。
|
|
25
|
+
3. **常驻 ffplay**:一个 ffplay 从 stdin 连续吃 mp3 帧。实测两段音频拼着写进去能
|
|
26
|
+
连着播、播完不退出(`M-A` 时间码一路涨到 3.0s)。每句起进程 = 380~410ms 首声。
|
|
27
|
+
|
|
28
|
+
落到的效果(同一台机器):
|
|
29
|
+
- 已预取(音频在内存)→ 写管道即出声,**~0ms**
|
|
30
|
+
- 未预取、连接热 → 首块 **200~300ms**
|
|
31
|
+
- 连接刚断(空闲 >30s)→ 重建 620~760ms + 首块
|
|
32
|
+
|
|
33
|
+
## 协议
|
|
34
|
+
|
|
35
|
+
stdin(每行一个 JSON):
|
|
36
|
+
|
|
37
|
+
{"op":"warm"} 起 ffplay + 建连(不阻塞)
|
|
38
|
+
{"op":"prefetch","id":N,"text":"…"} 只合成,存内存,可撤回
|
|
39
|
+
{"op":"say","id":N,"text":"…"} 合成并播放(缓存命中则直接播)
|
|
40
|
+
{"op":"forget","id":N} 丢掉这句的缓存
|
|
41
|
+
{"op":"stop"}
|
|
42
|
+
|
|
43
|
+
stdout(每行一个 JSON,全部是**状态**,不含音频):
|
|
44
|
+
|
|
45
|
+
{"ev":"ready"} 预热完成
|
|
46
|
+
{"ev":"first","id":N,"ms":230} 首块已进播放管道 = 马上出声
|
|
47
|
+
{"ev":"done","id":N,"ms":380}
|
|
48
|
+
{"ev":"skip","id":N,"reason":"…"} 缓存被丢掉(forget)
|
|
49
|
+
{"ev":"error","id":N,"reason":"…"}
|
|
50
|
+
|
|
51
|
+
`first` 的语义和语音总线里的 `spoken` 一致:**音频已经交给播放设备**,展示层收到
|
|
52
|
+
就可以把字摆出来。报早了我们只是把字提前一点点,报晚了就是老毛病(字等人声)。
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
import asyncio
|
|
56
|
+
import json
|
|
57
|
+
import os
|
|
58
|
+
import queue
|
|
59
|
+
import ssl
|
|
60
|
+
import subprocess
|
|
61
|
+
import sys
|
|
62
|
+
import threading
|
|
63
|
+
import time
|
|
64
|
+
import uuid
|
|
65
|
+
|
|
66
|
+
import aiohttp
|
|
67
|
+
|
|
68
|
+
from edge_tts.communicate import date_to_string, mkssml
|
|
69
|
+
from edge_tts.constants import SEC_MS_GEC_VERSION, WSS_HEADERS, WSS_URL
|
|
70
|
+
from edge_tts.data_classes import TTSConfig
|
|
71
|
+
from edge_tts.drm import DRM
|
|
72
|
+
|
|
73
|
+
# edge_tts 用的是同一份 SSL 配置;照抄,否则某些机器握手失败。
|
|
74
|
+
_SSL = ssl.create_default_context()
|
|
75
|
+
_SSL.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")
|
|
76
|
+
try:
|
|
77
|
+
_SSL.set_alpn_protocols(["http/1.1"])
|
|
78
|
+
except NotImplementedError:
|
|
79
|
+
pass
|
|
80
|
+
_SSL.options |= ssl.OP_LEGACY_SERVER_CONNECT
|
|
81
|
+
|
|
82
|
+
#: 服务端实测 30s 关连接,留 5s 余量:宁可早断一次(重建 700ms),
|
|
83
|
+
#: 也不要拿着一条已经死的连接去发请求(那是直接丢一句话)。
|
|
84
|
+
IDLE_TTL = 25.0
|
|
85
|
+
|
|
86
|
+
#: 缓存的音频上限。一句中文 30 字约 30~60KB,80 句 ≈ 4MB,够一整段还有余。
|
|
87
|
+
MAX_CACHED = 80
|
|
88
|
+
|
|
89
|
+
EMIT_LOCK = threading.Lock()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def emit(**kw):
|
|
93
|
+
"""写一行 JSON 到 stdout。多线程调用,必须串行(否则两行会缠在一起)。"""
|
|
94
|
+
with EMIT_LOCK:
|
|
95
|
+
sys.stdout.write(json.dumps(kw, ensure_ascii=False) + "\n")
|
|
96
|
+
sys.stdout.flush()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def log(msg):
|
|
100
|
+
sys.stderr.write(f"[tts] {msg}\n")
|
|
101
|
+
sys.stderr.flush()
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def config():
|
|
105
|
+
home = os.environ.get("DSH_HOME") or os.path.join(
|
|
106
|
+
os.environ.get("USERPROFILE") or os.environ.get("HOME") or os.path.expanduser("~"), ".dsh")
|
|
107
|
+
try:
|
|
108
|
+
with open(os.path.join(home, "tts.json"), encoding="utf-8") as f:
|
|
109
|
+
return json.load(f) or {}
|
|
110
|
+
except Exception:
|
|
111
|
+
return {}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def escape(text):
|
|
115
|
+
return text.replace("&", "&").replace("<", "<").replace(">", ">")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# --------------------------------------------------------------- 播放
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class Player:
|
|
122
|
+
"""常驻 ffplay。一个进程连续吃 mp3 帧,句与句之间不重启。
|
|
123
|
+
|
|
124
|
+
写管道用独立线程:ffplay 的管道缓冲区满了会阻塞,而调用方(事件循环)不能停在
|
|
125
|
+
那里 —— 它还得收下一句的请求。阻塞的部分扔给线程,主循环永远不卡。
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
def __init__(self, volume=100, loglevel="quiet"):
|
|
129
|
+
self.volume = volume
|
|
130
|
+
self.loglevel = loglevel
|
|
131
|
+
self._q = queue.Queue()
|
|
132
|
+
self._proc = None
|
|
133
|
+
self._thread = None
|
|
134
|
+
self._broken = False
|
|
135
|
+
self._fails = 0
|
|
136
|
+
|
|
137
|
+
def start(self):
|
|
138
|
+
if self._thread is None:
|
|
139
|
+
self._thread = threading.Thread(target=self._loop, daemon=True)
|
|
140
|
+
self._thread.start()
|
|
141
|
+
return not self._broken
|
|
142
|
+
|
|
143
|
+
def play(self, data):
|
|
144
|
+
"""把一段 mp3 交给播放队列。返回 False = 播放器起不来。"""
|
|
145
|
+
if self._broken or not data:
|
|
146
|
+
return False
|
|
147
|
+
# 线程意外退出(写入线程里抛了没兜住)时自己拉起来,别让后面整场哑掉
|
|
148
|
+
if self._thread is None or not self._thread.is_alive():
|
|
149
|
+
self._thread = threading.Thread(target=self._loop, daemon=True)
|
|
150
|
+
self._thread.start()
|
|
151
|
+
self._q.put(bytes(data))
|
|
152
|
+
return True
|
|
153
|
+
|
|
154
|
+
def prime(self):
|
|
155
|
+
"""喂一小段静音,把 ffplay 的 demuxer 探测(~200ms)提前花掉。
|
|
156
|
+
|
|
157
|
+
探测是按"流里第一块数据"触发的,所以光起进程没用 —— 必须真喂点字节。
|
|
158
|
+
这段是 0.3 秒静音,用户听不见,但它让真正的第一句话省下 200ms。
|
|
159
|
+
"""
|
|
160
|
+
try:
|
|
161
|
+
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "warm.mp3"), "rb") as f:
|
|
162
|
+
self.play(f.read())
|
|
163
|
+
except Exception:
|
|
164
|
+
pass # 没有这个文件就退回"第一句多等 200ms",不影响功能
|
|
165
|
+
|
|
166
|
+
def stop(self):
|
|
167
|
+
self._q.put(None)
|
|
168
|
+
proc = self._proc
|
|
169
|
+
self._proc = None
|
|
170
|
+
if proc is not None:
|
|
171
|
+
try:
|
|
172
|
+
proc.stdin.close()
|
|
173
|
+
except Exception:
|
|
174
|
+
pass
|
|
175
|
+
try:
|
|
176
|
+
proc.kill()
|
|
177
|
+
except Exception:
|
|
178
|
+
pass
|
|
179
|
+
|
|
180
|
+
def _spawn(self):
|
|
181
|
+
args = ["ffplay", "-nodisp", "-loglevel", self.loglevel, "-volume", str(self.volume), "-"]
|
|
182
|
+
extra = {"creationflags": 0x08000000} if os.name == "nt" else {} # CREATE_NO_WINDOW
|
|
183
|
+
# 默认 quiet + 丢掉 stderr;调试时 `DSH_TTS_FFPLAY_LOG=info` 把时间码放出来
|
|
184
|
+
# (看得到 `M-A` 一路涨就说明真的在播,而不是管道里堆着)。
|
|
185
|
+
err = subprocess.DEVNULL if self.loglevel == "quiet" else None
|
|
186
|
+
# bufsize=0:mp3 帧要立刻流出去,带缓冲会让首声晚一个 8KB
|
|
187
|
+
proc = subprocess.Popen(
|
|
188
|
+
args, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
|
|
189
|
+
stderr=err, bufsize=0, **extra,
|
|
190
|
+
)
|
|
191
|
+
self._proc = proc
|
|
192
|
+
return proc
|
|
193
|
+
|
|
194
|
+
def _loop(self):
|
|
195
|
+
while True:
|
|
196
|
+
data = self._q.get()
|
|
197
|
+
if data is None:
|
|
198
|
+
break
|
|
199
|
+
ok = False
|
|
200
|
+
for _ in range(2): # 一次重试:ffplay 偶发启动失败(设备被独占)时拉起来
|
|
201
|
+
try:
|
|
202
|
+
proc = self._proc
|
|
203
|
+
if proc is None or proc.poll() is not None:
|
|
204
|
+
proc = self._spawn()
|
|
205
|
+
assert proc.stdin is not None
|
|
206
|
+
proc.stdin.write(data)
|
|
207
|
+
proc.stdin.flush()
|
|
208
|
+
ok = True
|
|
209
|
+
break
|
|
210
|
+
except Exception as e: # noqa: BLE001
|
|
211
|
+
log(f"ffplay 写入失败:{e}")
|
|
212
|
+
self._proc = None
|
|
213
|
+
if ok:
|
|
214
|
+
self._fails = 0
|
|
215
|
+
continue
|
|
216
|
+
# 连续三次都起不来才认定播放通道死了。一次失败(切音频设备、独占冲突)
|
|
217
|
+
# 不该让后面整场都没声音 —— 下一句还会再试。
|
|
218
|
+
self._fails += 1
|
|
219
|
+
if self._fails >= 3:
|
|
220
|
+
self._broken = True
|
|
221
|
+
log("ffplay 连续起不来,播放通道关闭")
|
|
222
|
+
break
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
# --------------------------------------------------------------- 合成
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class EdgeLink:
|
|
229
|
+
"""一条 WebSocket,连发多句。同一时刻只能有一个请求在飞(aiohttp 不允许并发 receive)。"""
|
|
230
|
+
|
|
231
|
+
def __init__(self, voice, rate):
|
|
232
|
+
self.conf = TTSConfig(voice=voice, rate=rate, volume="+0%",
|
|
233
|
+
pitch="+0Hz", boundary="SentenceBoundary")
|
|
234
|
+
self.ws = None
|
|
235
|
+
self.session = None
|
|
236
|
+
self.last_used = 0.0
|
|
237
|
+
self.builds = 0
|
|
238
|
+
|
|
239
|
+
async def ensure(self):
|
|
240
|
+
fresh = self.ws is not None and not self.ws.closed \
|
|
241
|
+
and (time.monotonic() - self.last_used) < IDLE_TTL
|
|
242
|
+
if fresh:
|
|
243
|
+
return True
|
|
244
|
+
await self.close()
|
|
245
|
+
url = (f"{WSS_URL}&ConnectionId={uuid.uuid4().hex}"
|
|
246
|
+
f"&Sec-MS-GEC={DRM.generate_sec_ms_gec()}&Sec-MS-GEC-Version={SEC_MS_GEC_VERSION}")
|
|
247
|
+
self.session = aiohttp.ClientSession(trust_env=True)
|
|
248
|
+
self.ws = await self.session.ws_connect(url, compress=15, headers=WSS_HEADERS, ssl=_SSL)
|
|
249
|
+
await self.ws.send_str(
|
|
250
|
+
f"X-Timestamp:{date_to_string()}\r\n"
|
|
251
|
+
"Content-Type:application/json; charset=utf-8\r\n"
|
|
252
|
+
"Path:speech.config\r\n\r\n"
|
|
253
|
+
'{"context":{"synthesis":{"audio":{"metadataoptions":{'
|
|
254
|
+
'"sentenceBoundaryEnabled":"true","wordBoundaryEnabled":"false"},'
|
|
255
|
+
'"outputFormat":"audio-24khz-48kbitrate-mono-mp3"}}}}\r\n'
|
|
256
|
+
)
|
|
257
|
+
self.builds += 1
|
|
258
|
+
# **建连成功就要打时间戳**:不打的话下一次 `ensure()` 会看到
|
|
259
|
+
# `monotonic() - 0` 是个巨大的数,判定"已过期"再重建一遍 —— 预热白做,
|
|
260
|
+
# 第一句反而多付 700ms(实测踩过)。
|
|
261
|
+
self.last_used = time.monotonic()
|
|
262
|
+
log(f"连接已建立(第 {self.builds} 次)")
|
|
263
|
+
return True
|
|
264
|
+
|
|
265
|
+
async def close(self):
|
|
266
|
+
if self.ws is not None:
|
|
267
|
+
try:
|
|
268
|
+
await self.ws.close()
|
|
269
|
+
except Exception:
|
|
270
|
+
pass
|
|
271
|
+
self.ws = None
|
|
272
|
+
if self.session is not None:
|
|
273
|
+
try:
|
|
274
|
+
await self.session.close()
|
|
275
|
+
except Exception:
|
|
276
|
+
pass
|
|
277
|
+
self.session = None
|
|
278
|
+
|
|
279
|
+
async def synth(self, text, on_chunk):
|
|
280
|
+
"""合成一句。`on_chunk(bytes)` 每块调一次 —— 想边收边播就把块直接写进管道。
|
|
281
|
+
|
|
282
|
+
返回总字节数。连接中途断掉会重建并**整句重来**(半句音频已经写出去了,
|
|
283
|
+
拼接会错位;这一句宁可慢一次也要完整)。
|
|
284
|
+
"""
|
|
285
|
+
for attempt in (0, 1):
|
|
286
|
+
try:
|
|
287
|
+
await self.ensure()
|
|
288
|
+
total = await self._run_turn(text, on_chunk if attempt == 0 else None)
|
|
289
|
+
if total is None and attempt == 0:
|
|
290
|
+
continue # 收到一半断了:重来一次,这次先收全再给
|
|
291
|
+
self.last_used = time.monotonic()
|
|
292
|
+
return total
|
|
293
|
+
except Exception as e: # noqa: BLE001
|
|
294
|
+
if attempt == 1:
|
|
295
|
+
raise
|
|
296
|
+
log(f"合成失败,重建连接重试:{e}")
|
|
297
|
+
await self.close()
|
|
298
|
+
return 0
|
|
299
|
+
|
|
300
|
+
async def _run_turn(self, text, on_chunk):
|
|
301
|
+
rid = uuid.uuid4().hex
|
|
302
|
+
ssml = mkssml(self.conf, escape(text))
|
|
303
|
+
payload = (f"X-RequestId:{rid}\r\n"
|
|
304
|
+
"Content-Type:application/ssml+xml\r\n"
|
|
305
|
+
f"X-Timestamp:{date_to_string()}Z\r\n"
|
|
306
|
+
"Path:ssml\r\n\r\n"
|
|
307
|
+
f"{ssml}")
|
|
308
|
+
await self.ws.send_str(payload)
|
|
309
|
+
total = 0
|
|
310
|
+
while True:
|
|
311
|
+
msg = await asyncio.wait_for(self.ws.receive(), timeout=20)
|
|
312
|
+
if msg.type == aiohttp.WSMsgType.BINARY:
|
|
313
|
+
data = msg.data
|
|
314
|
+
hlen = int.from_bytes(data[:2], "big")
|
|
315
|
+
body = data[2 + hlen:]
|
|
316
|
+
if body:
|
|
317
|
+
total += len(body)
|
|
318
|
+
if on_chunk is not None:
|
|
319
|
+
on_chunk(body)
|
|
320
|
+
elif msg.type == aiohttp.WSMsgType.TEXT:
|
|
321
|
+
if "Path:turn.end" in msg.data:
|
|
322
|
+
return total
|
|
323
|
+
else:
|
|
324
|
+
# 连接没了。已经写出半句时不能重来(音频会错位),只能当这句失败。
|
|
325
|
+
raise ConnectionError(f"连接关闭(type={msg.type},已收 {total}B)")
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
# --------------------------------------------------------------- 主流程
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
class Daemon:
|
|
332
|
+
def __init__(self):
|
|
333
|
+
cfg = config()
|
|
334
|
+
self.cfg = cfg
|
|
335
|
+
self.voice = cfg.get("voice") or "zh-CN-YunxiNeural"
|
|
336
|
+
rate = float(cfg.get("rate") or 0)
|
|
337
|
+
self.rate = f"{'+' if rate >= 0 else ''}{round(rate * 3)}%"
|
|
338
|
+
try:
|
|
339
|
+
volume = int(os.environ.get("DSH_TTS_VOLUME") or 100)
|
|
340
|
+
except ValueError:
|
|
341
|
+
volume = 100
|
|
342
|
+
self.player = Player(volume=volume, loglevel=os.environ.get("DSH_TTS_FFPLAY_LOG") or "quiet")
|
|
343
|
+
self.edge = EdgeLink(self.voice, self.rate)
|
|
344
|
+
self.cache = {} # text -> bytes
|
|
345
|
+
self.order = [] # 缓存淘汰顺序
|
|
346
|
+
self.jobs = asyncio.PriorityQueue()
|
|
347
|
+
self.seq = 0
|
|
348
|
+
self.said = {} # id -> text(say 用,便于 forget 精确删)
|
|
349
|
+
self.warm_task = None
|
|
350
|
+
|
|
351
|
+
def cached(self, text):
|
|
352
|
+
return self.cache.get(text)
|
|
353
|
+
|
|
354
|
+
def remember(self, text, data):
|
|
355
|
+
if text in self.cache:
|
|
356
|
+
return
|
|
357
|
+
self.cache[text] = data
|
|
358
|
+
self.order.append(text)
|
|
359
|
+
while len(self.order) > MAX_CACHED:
|
|
360
|
+
old = self.order.pop(0)
|
|
361
|
+
self.cache.pop(old, None)
|
|
362
|
+
|
|
363
|
+
async def warm(self):
|
|
364
|
+
if self.warm_task is None:
|
|
365
|
+
self.warm_task = asyncio.create_task(self._warm())
|
|
366
|
+
return self.warm_task
|
|
367
|
+
|
|
368
|
+
async def _warm(self):
|
|
369
|
+
self.player.start()
|
|
370
|
+
self.player.prime()
|
|
371
|
+
try:
|
|
372
|
+
await self.edge.ensure()
|
|
373
|
+
except Exception as e: # noqa: BLE001
|
|
374
|
+
log(f"预热建连失败(第一次会再试):{e}")
|
|
375
|
+
emit(ev="ready")
|
|
376
|
+
|
|
377
|
+
async def handle(self, req):
|
|
378
|
+
op = req.get("op")
|
|
379
|
+
if op == "warm":
|
|
380
|
+
await self.warm()
|
|
381
|
+
return
|
|
382
|
+
if op == "say":
|
|
383
|
+
await self.jobs.put((0, self.seq, req))
|
|
384
|
+
self.seq += 1
|
|
385
|
+
return
|
|
386
|
+
if op == "prefetch":
|
|
387
|
+
if not req.get("text"):
|
|
388
|
+
return
|
|
389
|
+
await self.jobs.put((1, self.seq, req))
|
|
390
|
+
self.seq += 1
|
|
391
|
+
return
|
|
392
|
+
if op == "forget":
|
|
393
|
+
text = req.get("text") or self.said.get(req.get("id"))
|
|
394
|
+
if text:
|
|
395
|
+
self.cache.pop(text, None)
|
|
396
|
+
try:
|
|
397
|
+
self.order.remove(text)
|
|
398
|
+
except ValueError:
|
|
399
|
+
pass
|
|
400
|
+
emit(ev="skip", id=req.get("id"))
|
|
401
|
+
return
|
|
402
|
+
if op == "stop":
|
|
403
|
+
raise SystemExit(0)
|
|
404
|
+
|
|
405
|
+
async def run_job(self, req):
|
|
406
|
+
rid = req.get("id")
|
|
407
|
+
text = str(req.get("text") or "").strip()
|
|
408
|
+
if not text:
|
|
409
|
+
emit(ev="error", id=rid, reason="empty-text")
|
|
410
|
+
return
|
|
411
|
+
hit = self.cached(text)
|
|
412
|
+
if hit is not None and req.get("op") == "say":
|
|
413
|
+
# 预取已经合成好了:音频直接进管道,首声就是设备延迟(~50ms)。
|
|
414
|
+
t0 = time.monotonic()
|
|
415
|
+
if not self.player.play(hit):
|
|
416
|
+
emit(ev="error", id=rid, reason="player-unavailable")
|
|
417
|
+
return
|
|
418
|
+
emit(ev="first", id=rid, ms=round((time.monotonic() - t0) * 1000))
|
|
419
|
+
emit(ev="done", id=rid, ms=round((time.monotonic() - t0) * 1000))
|
|
420
|
+
return
|
|
421
|
+
|
|
422
|
+
if req.get("op") == "prefetch":
|
|
423
|
+
if hit is not None:
|
|
424
|
+
emit(ev="done", id=rid, ms=0)
|
|
425
|
+
return
|
|
426
|
+
buf = bytearray()
|
|
427
|
+
t0 = time.monotonic()
|
|
428
|
+
try:
|
|
429
|
+
await self.edge.synth(text, buf.extend)
|
|
430
|
+
except Exception as e: # noqa: BLE001
|
|
431
|
+
emit(ev="error", id=rid, reason=str(e)[:160])
|
|
432
|
+
return
|
|
433
|
+
self.remember(text, bytes(buf))
|
|
434
|
+
emit(ev="done", id=rid, ms=round((time.monotonic() - t0) * 1000), bytes=len(buf))
|
|
435
|
+
return
|
|
436
|
+
|
|
437
|
+
# say 且没缓存:边收边播 —— 首块进管道就算出声,不等整句。
|
|
438
|
+
t0 = time.monotonic()
|
|
439
|
+
first = [None]
|
|
440
|
+
buf = bytearray()
|
|
441
|
+
|
|
442
|
+
def sink(chunk):
|
|
443
|
+
buf.extend(chunk)
|
|
444
|
+
if first[0] is None:
|
|
445
|
+
if self.player.play(chunk):
|
|
446
|
+
first[0] = (time.monotonic() - t0) * 1000
|
|
447
|
+
emit(ev="first", id=rid, ms=round(first[0]))
|
|
448
|
+
else:
|
|
449
|
+
self.player.play(chunk)
|
|
450
|
+
|
|
451
|
+
try:
|
|
452
|
+
await self.edge.synth(text, sink)
|
|
453
|
+
except Exception as e: # noqa: BLE001
|
|
454
|
+
emit(ev="error", id=rid, reason=str(e)[:160])
|
|
455
|
+
return
|
|
456
|
+
self.remember(text, bytes(buf))
|
|
457
|
+
emit(ev="done", id=rid, ms=round((time.monotonic() - t0) * 1000))
|
|
458
|
+
|
|
459
|
+
async def worker(self):
|
|
460
|
+
while True:
|
|
461
|
+
_, _, req = await self.jobs.get()
|
|
462
|
+
try:
|
|
463
|
+
await self.run_job(req)
|
|
464
|
+
except Exception as e: # noqa: BLE001
|
|
465
|
+
log(f"任务异常:{e}")
|
|
466
|
+
finally:
|
|
467
|
+
self.jobs.task_done()
|
|
468
|
+
|
|
469
|
+
async def main(self):
|
|
470
|
+
emit(ev="boot", voice=self.voice, rate=self.rate)
|
|
471
|
+
asyncio.create_task(self.worker())
|
|
472
|
+
loop = asyncio.get_running_loop()
|
|
473
|
+
# 前台保持一根暖连接:进程起来就把建连(~700ms)花掉,别等第一句话。
|
|
474
|
+
asyncio.create_task(self.warm())
|
|
475
|
+
try:
|
|
476
|
+
while True:
|
|
477
|
+
line = await loop.run_in_executor(None, sys.stdin.buffer.readline)
|
|
478
|
+
if not line:
|
|
479
|
+
break
|
|
480
|
+
try:
|
|
481
|
+
req = json.loads(line.decode("utf-8", "replace"))
|
|
482
|
+
except Exception:
|
|
483
|
+
continue
|
|
484
|
+
await self.handle(req)
|
|
485
|
+
finally:
|
|
486
|
+
self.player.stop()
|
|
487
|
+
await self.edge.close()
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
if __name__ == "__main__":
|
|
491
|
+
try:
|
|
492
|
+
asyncio.run(Daemon().main())
|
|
493
|
+
except (KeyboardInterrupt, SystemExit):
|
|
494
|
+
pass
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-watch-together",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.12",
|
|
4
4
|
"description": "Watch a video together with a text-only agent: follow the user's real playback position, hand over one segment at a time just before it ends, and keep a single text stream of scripted lines, interjections and the user's replies.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh",
|
|
@@ -66,7 +66,10 @@
|
|
|
66
66
|
"examples/floating-chat/*.cmd",
|
|
67
67
|
"examples/floating-chat/*.png",
|
|
68
68
|
"examples/floating-chat/*.txt",
|
|
69
|
-
"examples/voice-edge-tts/index.mjs"
|
|
69
|
+
"examples/voice-edge-tts/index.mjs",
|
|
70
|
+
"examples/voice-edge-tts/stream/*.mjs",
|
|
71
|
+
"examples/voice-edge-tts/stream/*.py",
|
|
72
|
+
"examples/voice-edge-tts/stream/*.mp3"
|
|
70
73
|
],
|
|
71
74
|
"engines": {
|
|
72
75
|
"node": ">=20"
|
package/src/watch-loop.js
CHANGED
|
@@ -323,12 +323,18 @@ export function startWatchLoop({
|
|
|
323
323
|
// 只有真的开过窗才生效(`windowGuard: true` 由 handler 在窗口就绪时传);
|
|
324
324
|
// 没开窗(环境变量关掉、Python 缺失、或压根不需要插话)时为 false,不会误停。
|
|
325
325
|
windowGuard = false,
|
|
326
|
-
//
|
|
327
|
-
//
|
|
328
|
-
//
|
|
329
|
-
//
|
|
330
|
-
//
|
|
331
|
-
|
|
326
|
+
// 悬浮窗里的插话要不要**主动叫醒**模型。
|
|
327
|
+
//
|
|
328
|
+
// 2026-11-04 默认改成 false。原来开着是为了补"我思考 / 钟在后台空转"那段——
|
|
329
|
+
// 阻塞等待里本来就会 poll,但那段时间没人听。代价是:`wakeSession` 走的是宿主的
|
|
330
|
+
// `agent.followup()`,而 DSH 的 QueueDock **不过滤 source**,于是用户在悬浮窗
|
|
331
|
+
// 每打一句话,输入框上方就多一条"排队消息"。悬浮窗里明明已经有气泡显示过了,
|
|
332
|
+
// 队列里再来一条既是噪音、又占住输入框。
|
|
333
|
+
//
|
|
334
|
+
// 关掉之后**不会丢话**:这一段整个跳过,`chatWatcher()` 也就不消费,
|
|
335
|
+
// 消息留在通道里,模型下次 `watch_together` 时 poll 得到。真正的阻塞等待
|
|
336
|
+
// (`wait` / `nextLine`)走的是另一条路,照旧能随时打断。
|
|
337
|
+
wakeOnChat = false,
|
|
332
338
|
// **字幕轨**:只转写、不建图,跑到"当前位置 + 余量"为止。默认开(用户要的是"字先到先给")。
|
|
333
339
|
// 关掉它就退回原来的行为:字和画面一起在图那一次给。
|
|
334
340
|
transcriptTrack = true,
|