dsh-watch-together 0.2.5 → 0.2.7
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 +79 -0
- package/README.md +19 -3
- package/docs/VOICE.zh.md +9 -2
- package/dsh.plugin.json +1 -1
- package/examples/floating-chat/glass_window_gpu.py +6 -0
- package/examples/floating-chat/window.py +88 -2
- package/examples/voice-edge-tts/index.mjs +101 -18
- package/lib/client.js +74 -17
- package/package.json +1 -1
- package/src/chat-server.js +49 -11
- package/src/chat-view.js +3 -0
- package/src/index.js +9 -1
- package/src/settings/config.js +2 -0
- package/src/settings/deps.js +5 -4
- package/src/tts-interface.js +3 -1
- package/src/watch-lines.js +502 -459
- package/src/watch-loop.js +44 -2
- package/src/watch.js +44 -43
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,85 @@
|
|
|
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.7] - 2026-11-03
|
|
7
|
+
|
|
8
|
+
> 五个社区 PR 一起收(都是 @ggfgfgf-on 提的),外加录屏模式的两个真 bug。
|
|
9
|
+
|
|
10
|
+
### Fixed — 录屏/截图根本拍不到窗口
|
|
11
|
+
|
|
12
|
+
窗口一直开着 `WDA_EXCLUDEFROMCAPTURE`(防截图/直播泄露,这是对的),
|
|
13
|
+
但社区贡献者要调玻璃管线就必须能录。原来只有环境变量 `DSH_GLASS_WDA=0` 一个入口,
|
|
14
|
+
**而插件拉起窗口时不会传环境变量** —— 于是用户在 `~/.dsh/watch-window.json` 里写了
|
|
15
|
+
`"capturable": true` 也没人读,录出来永远是空桌面。
|
|
16
|
+
|
|
17
|
+
现在 `capturable()` 真的读配置:环境变量(临时)→ 配置项(持久)→ 默认排除。
|
|
18
|
+
|
|
19
|
+
### Fixed — 录屏模式下"字一直在闪"、拖尾越滚越浓
|
|
20
|
+
|
|
21
|
+
`capturable: true` 关掉 WDA 之后,**mss 抓背景时把窗口自己也抓进去了**。玻璃拿它当背景
|
|
22
|
+
等于"透过自己看自己",形成反馈回路:背景里带着上一帧的字 → 亮度判据一直抖 → 字色来回翻;
|
|
23
|
+
背景一直在变 → `moved` 一直为真 → 一直混合上一帧 → 越滚越浓的假拖尾(静止画面也在"动")。
|
|
24
|
+
|
|
25
|
+
现在录屏模式下把窗口矩形用**周边均值**刷平(试过按上下边缘插值,相邻列颜色不同会变成
|
|
26
|
+
一根根竖条,更难看)。窗口外 PAD 一圈仍是真背景,边缘透镜照常。
|
|
27
|
+
实测同一位置连续 6 帧:帧差从"每次都在变"降到 **0.00**。
|
|
28
|
+
|
|
29
|
+
### Added — 窗口心跳
|
|
30
|
+
|
|
31
|
+
`<cache>/window-heartbeat`,`_tick` 里每秒最多写一次。宿主那侧靠它区分"进程还在"和
|
|
32
|
+
"窗口真的在画"——只看 pid 的话,pid 被复用或界面卡死时永远认为窗还开着,于是再也不重开。
|
|
33
|
+
|
|
34
|
+
### Fixed — GPU 抓屏越界(合 PR #40,作者 @ggfgfgf-on,fixes #39)
|
|
35
|
+
|
|
36
|
+
GPU 路径的 `capture_gpu()` 有自己一份 `sct.grab()`,没做 `gr-gl/gb-gt` 守卫;
|
|
37
|
+
窗口被拖出屏幕时每帧抛 `Region has zero or negative size`,被 `_work()` 吞掉后背景永久停在旧帧。
|
|
38
|
+
补上和 CPU 路径一样的检查。
|
|
39
|
+
|
|
40
|
+
### Fixed — 台词 `at: null` 被存成第 0 秒(合 PR #38,作者 @ggfgfgf-on)
|
|
41
|
+
|
|
42
|
+
`Number(null) === 0`,显式写 `at: null` 的台词全被当成"第 0 秒",回读时挤在片头。
|
|
43
|
+
|
|
44
|
+
### Fixed — 本机 API 的 CORS 与聊天游标(合 PR #35,作者 @ggfgfgf-on,fixes #33 #34)
|
|
45
|
+
|
|
46
|
+
- 聊天/位置 API 原来对**任意网页**放开 CORS,可被跨站写入;改成只认白名单。
|
|
47
|
+
- `chat.jsonl` 被清短之后,聊天页的游标永久卡在越界位置;改成越界自动归零。
|
|
48
|
+
- 新增 `test/chat-server-guards.test.mjs`。
|
|
49
|
+
|
|
50
|
+
### Fixed — 卸载时没 detach voice adapter(合 PR #31,作者 @ggfgfgf-on,fixes #30)
|
|
51
|
+
|
|
52
|
+
适配器订阅了 speech bus,插件卸载却没退订 —— `speechSubscribers()` 一直 > 0,
|
|
53
|
+
重载后循环误以为"有人会念",模型再也不会被叫醒。
|
|
54
|
+
|
|
55
|
+
### Added — 设置页自动保存(合 PR #32,作者 @ggfgfgf-on)
|
|
56
|
+
|
|
57
|
+
改一项存一项,不用再点保存;顺带补了声音环境变量提示与连接状态。
|
|
58
|
+
|
|
59
|
+
## [0.2.6] - 2026-11-02
|
|
60
|
+
|
|
61
|
+
> 陪看的声音还差最后一步:到点才开始合成。这一轮把"合成"从关键路径上挪开。
|
|
62
|
+
|
|
63
|
+
### Added — `scheduled` 事件(合 PR #36,作者 @ggfgfgf-on)
|
|
64
|
+
|
|
65
|
+
- 循环每一拍把**未来 60 秒内、已经写好且带 `at`** 的台词以 `scheduled` 广播一次(每句一次;
|
|
66
|
+
只在有会出声的订阅者时发)。它不参与"该不该念"的判断,只给适配器时间预合成。
|
|
67
|
+
- `upcomingLines(input, { after, before })`:只读的"未来台词"查询,不消费稿件。
|
|
68
|
+
|
|
69
|
+
### Changed — 示例适配器预合成
|
|
70
|
+
|
|
71
|
+
- `examples/voice-edge-tts`:`speakEdge` 拆成 `synthEdge`(只合成)+ `playEdge`(播放并删临时文件);
|
|
72
|
+
`scheduled` 到达即合成,按 `input|segment|text` 缓存(上限 6 条,满时踢 `at` 最远的一条),
|
|
73
|
+
`due` 优先播缓存。日志多出 `prefetched` / `synth`、`ready Nms`、`wait Nms`。
|
|
74
|
+
- `MAX_QUEUE_LAG_MS` 的计时从 `due` **到达**起算,合成时间本来就算在里面 ——
|
|
75
|
+
预取因此还降低了"排队太久被丢弃"的概率,不只是首声早一点。
|
|
76
|
+
|
|
77
|
+
### Fixed — 评审补丁(`5fa1307`、`bd5b3c7`)
|
|
78
|
+
|
|
79
|
+
- **跨段时缓存 key 对不上**:`dueLine` 跨段挑 `at` 最小的一句,选中上一段的句子时 `due` 报的却是
|
|
80
|
+
当前段,和 `scheduled` 的 `segment` 不一致 → 缓存白做、首声又晚回 0.6~2 秒。
|
|
81
|
+
`dueLine({ meta: true })` 现在多返回 `from`,`speak()` 用它。
|
|
82
|
+
- **`Number(null) === 0`**:没写 `at` 的台词会被当成"at=0"挤进预取窗口;适配器 `prefetch()` 同理,
|
|
83
|
+
6 个槽位被 at=0 占满后永久失效。两处都改成显式判空。
|
|
84
|
+
|
|
6
85
|
## [0.2.5] - 2026-11-02
|
|
7
86
|
|
|
8
87
|
> 0.2.4 里 PR #28 留下的两个 GPU 尾巴,作者当天补了 PR #29 收掉,外加气泡留白微调。
|
package/README.md
CHANGED
|
@@ -286,15 +286,31 @@ watch_together({ browserPort: 9333 }) // 或者单次传参
|
|
|
286
286
|
```
|
|
287
287
|
|
|
288
288
|
后台循环里某句到点时,会把同一条推给你,`state` 变成 `"due"`。
|
|
289
|
+
另外,循环每一拍还会把**未来 1 分钟内、已经写好且带 `at` 的台词**提前推成 `scheduled`(每句一次)——
|
|
290
|
+
这不是让你现在念,而是给适配器时间**预合成**;真正播放仍然只认 `due`。
|
|
291
|
+
|
|
292
|
+
> `scheduled` **一定带有限的 `at`**(没写 `at` 的台词进不了这个窗口)。写适配器时别拿 `Number(at)`
|
|
293
|
+
> 判空——`Number(null)` 是 `0`,会被当成"最早的一句"占满预取队列,之后既踢不掉旧的也进不来新的。
|
|
289
294
|
|
|
290
295
|
### 同进程:订阅
|
|
291
296
|
|
|
292
297
|
```js
|
|
293
298
|
import { onSpeech } from 'dsh-watch-together/voice';
|
|
294
299
|
|
|
295
|
-
const
|
|
296
|
-
|
|
297
|
-
|
|
300
|
+
const pending = new Map(); // key -> 预合成 Promise
|
|
301
|
+
const keyOf = ({ input, segment, text }) => `${input ?? ''}|${segment ?? ''}|${text ?? ''}`;
|
|
302
|
+
|
|
303
|
+
const off = onSpeech(async (event) => {
|
|
304
|
+
const { state, text } = event;
|
|
305
|
+
const key = keyOf(event);
|
|
306
|
+
if (state === 'scheduled') { // 还没到点:先合成,不播放
|
|
307
|
+
if (!pending.has(key)) pending.set(key, mySynth(text));
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
if (state !== 'due') return; // spoken / skipped 不是"该念了"
|
|
311
|
+
const audio = pending.get(key) ? await pending.get(key) : await mySynth(text);
|
|
312
|
+
pending.delete(key);
|
|
313
|
+
await myPlay(audio); // ← 你自己的播放器
|
|
298
314
|
});
|
|
299
315
|
```
|
|
300
316
|
|
package/docs/VOICE.zh.md
CHANGED
|
@@ -191,7 +191,9 @@ export function attach(api) {
|
|
|
191
191
|
### 一定要上报"真的出声了":`api.emitSpoken(e)`
|
|
192
192
|
|
|
193
193
|
`due` 只说明**该念了**。从 `due` 到"真的有声音"之间还隔着一整套合成(edge-tts 一次网络往返
|
|
194
|
-
加一个 ffplay 启动,短句也要 0.6~2
|
|
194
|
+
加一个 ffplay 启动,短句也要 0.6~2 秒)。**不要等 due 才开始合成**:核心会在台词写好、
|
|
195
|
+
还没到点时先发 `scheduled`(未来 1 分钟内,每句一次),适配器可以据此预合成;到点再播放,
|
|
196
|
+
首声就不用再等网络。示例适配器已经这么做。悬浮窗里的台词等的是 `spoken`:
|
|
195
197
|
|
|
196
198
|
```js
|
|
197
199
|
api.onSpeech((e) => {
|
|
@@ -210,12 +212,17 @@ api.onSpeech((e) => {
|
|
|
210
212
|
|
|
211
213
|
`api.onSpeech` 收到的事件关键字段:
|
|
212
214
|
|
|
213
|
-
- `state`:`'due'` =
|
|
215
|
+
- `state`:`'due'` = 到点该念(**播放只处理这个**);`'scheduled'` = 还没到点,
|
|
216
|
+
可以现在预合成(**不要现在播放**);
|
|
214
217
|
`'spoken'` = 适配器上报的"开始出声了";`'skipped'` = 放弃这句(见下)。
|
|
215
218
|
- `text`:要念的台词。
|
|
216
219
|
- `at`:**这句对应的播放位置(秒)**,不是墙钟 —— 打时间码用它。
|
|
217
220
|
- `input` / `segment`:哪一支片子的哪一段(多支片子交叉时用得上)。
|
|
218
221
|
|
|
222
|
+
> **`scheduled` 一定带有限的 `at`**:预取要靠它排"哪句更近",没写 `at` 的台词不会进这个窗口。
|
|
223
|
+
> 适配器自己也别用 `Number(at)` 判空 —— `Number(null)` 是 `0` 且算有限数,会被当成"最早的一句"
|
|
224
|
+
> 占满预取队列,之后既踢不掉旧的、也进不来新的,预取就静默失效了(不报错)。判 `at == null` 才是对的。
|
|
225
|
+
|
|
219
226
|
### 追不上就放弃:`state: 'skipped'`
|
|
220
227
|
|
|
221
228
|
引擎是串行的(一句念完才轮到下一句)。台词一密,队列就会越来越长,声音离画面越来越远。
|
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.7",
|
|
5
5
|
"entry": {
|
|
6
6
|
"name": "dsh-watch-together",
|
|
7
7
|
"inject": [
|
|
@@ -448,6 +448,12 @@ def capture_gpu(self, sct):
|
|
|
448
448
|
gt = max(0, t - G.PAD)
|
|
449
449
|
gr = min(self._sw, r + G.PAD)
|
|
450
450
|
gb = min(self._sh, b + G.PAD)
|
|
451
|
+
# 和 window.py 的 CPU 路径保持一致:多显示器 / DPI 变化 / 被别的程序
|
|
452
|
+
# 挪出屏幕时,钳位后的宽高可能 <= 0;mss 会抛
|
|
453
|
+
# "Region has zero or negative size",而 _work() 会每帧吞掉它 ——
|
|
454
|
+
# 表现就是日志每帧刷一条、背景永久停在旧帧。没有可抓的区域就别抓。
|
|
455
|
+
if gr - gl <= 0 or gb - gt <= 0:
|
|
456
|
+
return None
|
|
451
457
|
shot = sct.grab({"left": gl, "top": gt, "width": gr - gl, "height": gb - gt})
|
|
452
458
|
factor = 1.0 if _gpu.native else 4.0
|
|
453
459
|
px = int(round((l - gl) / factor))
|
|
@@ -87,6 +87,45 @@ CHAT_FILE = cache_dir() / "chat.jsonl"
|
|
|
87
87
|
CONFIG = Path(os.environ.get("DSH_HOME") or os.path.expanduser("~/.dsh")) / "watch-window.json"
|
|
88
88
|
MIC_SCRIPT = HERE / "mic.py"
|
|
89
89
|
|
|
90
|
+
# **心跳**:插件侧靠它区分"进程还在"和"窗口真的在画"。
|
|
91
|
+
# 只看 pid 不够 —— pid 会被系统复用,进程也可能活着但界面已经卡死、或者是一张空窗,
|
|
92
|
+
# 那样宿主会永远认为"窗还开着",于是**再也不重开**(dsh-see-now issue #2 第 3 条)。
|
|
93
|
+
# 每秒最多写一次,别把磁盘当草稿纸。
|
|
94
|
+
HEARTBEAT = cache_dir() / "window-heartbeat"
|
|
95
|
+
HEARTBEAT_EVERY = 1.0
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _fill_own_rect(im, box):
|
|
99
|
+
"""把「窗口自己」在抓屏帧里占的那块填掉。
|
|
100
|
+
|
|
101
|
+
**为什么必须填**:`capturable: true` 关掉了 `WDA_EXCLUDEFROMCAPTURE`,于是 mss
|
|
102
|
+
抓背景时**把窗口自己也抓进去了**。玻璃再拿这张图当背景,就等于"透过自己看自己":
|
|
103
|
+
|
|
104
|
+
- 背景里带着上一帧的字 → 亮度判据一直抖 → **字色来回翻**(看起来就是"字在闪");
|
|
105
|
+
- 背景一直在变 → `moved` 一直为真 → 一直混合上一帧 → **越滚越浓的拖尾**
|
|
106
|
+
(那种"黏黏的"感觉其实是自激,不是真的动态模糊);
|
|
107
|
+
- 静止画面上也会出现"画面在自己动"。
|
|
108
|
+
|
|
109
|
+
填法是拿这块上、下各一行像素做纵向线性插值 —— 得到一片渐变,像磨砂玻璃透出的
|
|
110
|
+
环境色,不会有细节更不会有自己的内容。窗口外的 `PAD` 一圈仍然是真背景,
|
|
111
|
+
边缘透镜照常能取到框外的料。
|
|
112
|
+
"""
|
|
113
|
+
x0, y0, x1, y1 = (int(v) for v in box)
|
|
114
|
+
arr = np.asarray(im)
|
|
115
|
+
h, w = arr.shape[:2]
|
|
116
|
+
x0, x1 = max(1, min(w - 1, x0)), max(1, min(w - 1, x1))
|
|
117
|
+
y0, y1 = max(1, min(h - 2, y0)), max(1, min(h - 2, y1))
|
|
118
|
+
n = y1 - y0
|
|
119
|
+
if x1 <= x0 or n <= 0:
|
|
120
|
+
return im
|
|
121
|
+
out = arr.copy()
|
|
122
|
+
top = arr[y0 - 1, x0:x1].astype(np.float32)
|
|
123
|
+
bot = arr[y1, x0:x1].astype(np.float32)
|
|
124
|
+
t = ((np.arange(n, dtype=np.float32) + 1.0) / (n + 1.0))[:, None, None]
|
|
125
|
+
grad = top[None, :, :] * (1.0 - t) + bot[None, :, :] * t
|
|
126
|
+
out[y0:y1, x0:x1] = np.clip(grad, 0, 255).astype(np.uint8)
|
|
127
|
+
return Image.fromarray(out)
|
|
128
|
+
|
|
90
129
|
|
|
91
130
|
def read_config():
|
|
92
131
|
try:
|
|
@@ -95,6 +134,28 @@ def read_config():
|
|
|
95
134
|
return {}
|
|
96
135
|
|
|
97
136
|
|
|
137
|
+
def capturable():
|
|
138
|
+
"""录屏 / 截图能不能拍到窗口。
|
|
139
|
+
|
|
140
|
+
默认**不能** —— 走 `WDA_EXCLUDEFROMCAPTURE`,窗口不会出现在截图、直播、共享屏幕里。
|
|
141
|
+
要给别人看效果、或者自己录一段发出来,就打开:
|
|
142
|
+
|
|
143
|
+
```json
|
|
144
|
+
// ~/.dsh/watch-window.json
|
|
145
|
+
{ "capturable": true }
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
环境变量 `DSH_GLASS_WDA=0` 也能打开,但它只对**这一次启动**有效(插件拉起窗口时不会传它),
|
|
149
|
+
所以配置项才是那个"开关"。改完要重启窗口才生效。
|
|
150
|
+
"""
|
|
151
|
+
if os.environ.get("DSH_GLASS_WDA") == "0":
|
|
152
|
+
return True
|
|
153
|
+
try:
|
|
154
|
+
return read_config().get("capturable") is True
|
|
155
|
+
except Exception:
|
|
156
|
+
return False
|
|
157
|
+
|
|
158
|
+
|
|
98
159
|
def write_config(patch):
|
|
99
160
|
cfg = read_config()
|
|
100
161
|
cfg.update(patch or {})
|
|
@@ -477,6 +538,9 @@ class LiveGlass:
|
|
|
477
538
|
self._bg = None
|
|
478
539
|
self._hwnd = None
|
|
479
540
|
self._excluded = False
|
|
541
|
+
# 录屏模式(capturable)下 mss 会抓到窗口自己,必须每帧挖掉,见 _fill_own_rect。
|
|
542
|
+
# 缓存起来:读配置是磁盘 IO,不能每帧做。
|
|
543
|
+
self._cappable = capturable()
|
|
480
544
|
self._drag = None
|
|
481
545
|
self._resize = None
|
|
482
546
|
self._preview_at = 0.0
|
|
@@ -508,7 +572,7 @@ class LiveGlass:
|
|
|
508
572
|
self._text_items = [i for i in self.canvas.find_all()
|
|
509
573
|
if self.canvas.type(i) == "text"
|
|
510
574
|
and i not in shadow_ids]
|
|
511
|
-
self._set_exclude(
|
|
575
|
+
self._set_exclude(not capturable())
|
|
512
576
|
self._worker.start()
|
|
513
577
|
self.root.lift()
|
|
514
578
|
self.root.after(80, self.root.lift)
|
|
@@ -902,6 +966,10 @@ class LiveGlass:
|
|
|
902
966
|
shot = sct.grab({"left": gl, "top": gt,
|
|
903
967
|
"width": gr - gl, "height": gb - gt})
|
|
904
968
|
im = Image.frombytes("RGB", shot.size, shot.rgb)
|
|
969
|
+
# **录屏模式必须挖掉自己**:WDA 关了之后 mss 会把窗口也抓进来,
|
|
970
|
+
# 玻璃拿它当背景就变成自我反馈(字闪 / 假拖尾 / 静止画面在动)。
|
|
971
|
+
if self._cappable:
|
|
972
|
+
im = _fill_own_rect(im, (l - gl, t - gt, r - gl, b - gt))
|
|
905
973
|
sw4, sh4 = max(2, (gr - gl) // 4), max(2, (gb - gt) // 4)
|
|
906
974
|
# 60fps 路径:只在 1/4 分辨率做一次模糊和折射,再放大。
|
|
907
975
|
# cv2 的 resize 比 PIL 快一个数量级;没有 OpenCV 时无感回退。
|
|
@@ -1631,7 +1699,25 @@ class LiveGlass:
|
|
|
1631
1699
|
if self._excluded:
|
|
1632
1700
|
self._set_exclude(False)
|
|
1633
1701
|
|
|
1702
|
+
def _beat(self):
|
|
1703
|
+
"""写心跳(每秒最多一次)。插件侧 `windowAlive()` 读它的 mtime。
|
|
1704
|
+
|
|
1705
|
+
为什么不是"进程活着就算活着":pid 会被系统复用,进程也可能活着但界面卡死、
|
|
1706
|
+
或者是一张全透明的空窗。那种情况下宿主一直认为窗还开着,于是**再也不重开** ——
|
|
1707
|
+
用户体感就是"点了没反应"。
|
|
1708
|
+
"""
|
|
1709
|
+
now = time.time()
|
|
1710
|
+
if now - getattr(self, "_beat_at", 0.0) < HEARTBEAT_EVERY:
|
|
1711
|
+
return
|
|
1712
|
+
self._beat_at = now
|
|
1713
|
+
try:
|
|
1714
|
+
HEARTBEAT.parent.mkdir(parents=True, exist_ok=True)
|
|
1715
|
+
HEARTBEAT.write_bytes(b"")
|
|
1716
|
+
except Exception:
|
|
1717
|
+
pass
|
|
1718
|
+
|
|
1634
1719
|
def _tick(self):
|
|
1720
|
+
self._beat()
|
|
1635
1721
|
# 截图模式:worker 已暂停,保持 WDA 关闭;否则下一拍会重新开 WDA,
|
|
1636
1722
|
# 窗口再次从截图/录屏里消失,_snapshot_mode 等于没做。
|
|
1637
1723
|
if SNAPSHOT and getattr(self, "_snapshot_done", False):
|
|
@@ -1656,7 +1742,7 @@ class LiveGlass:
|
|
|
1656
1742
|
# 底部圆角/暗边会闪一下,看起来像渲染错位。
|
|
1657
1743
|
self.root.after(INTERVAL_MS, self._tick)
|
|
1658
1744
|
return
|
|
1659
|
-
if not self._excluded and
|
|
1745
|
+
if not self._excluded and not capturable():
|
|
1660
1746
|
self._set_exclude(True)
|
|
1661
1747
|
self._pause.clear()
|
|
1662
1748
|
|
|
@@ -7,8 +7,9 @@
|
|
|
7
7
|
*
|
|
8
8
|
* ## 两件事,别混
|
|
9
9
|
*
|
|
10
|
-
* 收到 `
|
|
11
|
-
*
|
|
10
|
+
* 收到 `scheduled` = 还没到点,可以**预合成**(本文件按台词缓存 mp3,不播放)
|
|
11
|
+
* 收到 `due` = 该念了(核心按播放位置发的)
|
|
12
|
+
* 发 `spoken` = **真的出声了**(本文件在开始播放那一瞬发)
|
|
12
13
|
*
|
|
13
14
|
* 悬浮窗认的是 `spoken`:不然字会先摆出来、声音一两秒后才到(`due` → 合成是一次网络往返
|
|
14
15
|
* 加一个 ffplay 启动)。上报晚了就等于又回到旧毛病,所以上报点选在**播放之前**。
|
|
@@ -81,21 +82,35 @@ function edgeBin(cfg) {
|
|
|
81
82
|
return null;
|
|
82
83
|
}
|
|
83
84
|
|
|
84
|
-
|
|
85
|
+
/** 只合成,不播放。预取和"到点没赶上预取"两条路共用。 */
|
|
86
|
+
async function synthEdge(text, { bin, voice, rate }) {
|
|
85
87
|
const out = join(tmpdir(), `voice-${Date.now()}-${Math.random().toString(36).slice(2, 7)}.mp3`);
|
|
86
88
|
const pct = Math.round(Math.max(-10, Math.min(10, Number(rate) || 0)) * 3);
|
|
87
89
|
const args = ['--voice', voice, '--text', text, '--write-media', out];
|
|
88
90
|
if (pct) args.push(`--rate=${pct > 0 ? '+' : ''}${pct}%`);
|
|
89
|
-
if (!(await run(bin, args)))
|
|
91
|
+
if (!(await run(bin, args))) {
|
|
92
|
+
try { unlinkSync(out); } catch { /* 没有文件正常 */ }
|
|
93
|
+
return { ok: false, reason: 'synth-failed' };
|
|
94
|
+
}
|
|
90
95
|
try {
|
|
91
|
-
if (statSync(out).size < 800)
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
96
|
+
if (statSync(out).size < 800) {
|
|
97
|
+
try { unlinkSync(out); } catch { /* 空文件删不掉也不影响 */ }
|
|
98
|
+
return { ok: false, reason: 'empty-audio' };
|
|
99
|
+
}
|
|
100
|
+
} catch {
|
|
101
|
+
return { ok: false, reason: 'stat-failed' };
|
|
102
|
+
}
|
|
103
|
+
return { ok: true, path: out, engine: 'edge-tts' };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 播放一个已经合成好的 mp3;返回时无论成败都删掉临时文件。 */
|
|
107
|
+
async function playEdge(path, onStart = null) {
|
|
108
|
+
// **就在这里上报"要出声了"**:ffplay 一启动就有声 —— 悬浮窗收到才把字摆出来,
|
|
109
|
+
// 于是"字出现"和"张嘴"几乎是同一刻(见 src/chat-store.js)。
|
|
95
110
|
try { onStart?.(); } catch { /* 上报失败不影响念 */ }
|
|
96
|
-
const played = await run('ffplay', ['-nodisp', '-autoexit', '-loglevel', 'quiet',
|
|
97
|
-
try { unlinkSync(
|
|
98
|
-
return played
|
|
111
|
+
const played = await run('ffplay', ['-nodisp', '-autoexit', '-loglevel', 'quiet', path], 90_000);
|
|
112
|
+
try { unlinkSync(path); } catch { /* 删不掉就留着 */ }
|
|
113
|
+
return played;
|
|
99
114
|
}
|
|
100
115
|
|
|
101
116
|
/** Windows 系统声音。Linux/macOS 会失败,失败就当没这个引擎。 */
|
|
@@ -133,14 +148,62 @@ export function attach(api) {
|
|
|
133
148
|
+ '想用晓萱等音色请在该文件加 "voice": "zh-CN-XiaoxuanNeural"');
|
|
134
149
|
const rate = Number(cfg.rate) || 0;
|
|
135
150
|
const bin = edgeBin(cfg);
|
|
136
|
-
let chain = Promise.resolve(); //
|
|
151
|
+
let chain = Promise.resolve(); // 播放串行:两句绝不重叠着念
|
|
152
|
+
|
|
153
|
+
// **预合成**:核心在台词写好、还没到点时发 `scheduled`。这里趁这段时间把 mp3 合成好,
|
|
154
|
+
// 到点只播放;否则 due 才开始跑 edge-tts(CLI 冷启动 + 网络往返 + 完整 mp3),
|
|
155
|
+
// 第一声会晚 0.6~2 秒。没有 prefetch 的旧宿主仍然走 due 现场合成,不破坏兼容。
|
|
156
|
+
const MAX_PREFETCH = 6;
|
|
157
|
+
const prefetched = new Map(); // key -> { task, path, at }
|
|
158
|
+
let prefetchTail = Promise.resolve();
|
|
159
|
+
const keyOf = (e) => `${e.input ?? ''}|${e.segment ?? ''}|${String(e.text ?? '')}`;
|
|
160
|
+
const discard = (entry) => {
|
|
161
|
+
entry.task.then((r) => {
|
|
162
|
+
if (r?.ok && r.path) { try { unlinkSync(r.path); } catch { /* 已删 */ } }
|
|
163
|
+
}).catch(() => {});
|
|
164
|
+
};
|
|
165
|
+
const prefetch = (e) => {
|
|
166
|
+
// **没有 `at` 的事件一律不预取**。适配器是陪看和看屏幕两个插件共用的,
|
|
167
|
+
// 那边(`see-now`)的事件是 `at: null`(它没有时间轴)。而 `Number(null)` 是 0、
|
|
168
|
+
// `Number.isFinite(0)` 为真 —— 放进来会被当成"最早的一句"占满队列,之后
|
|
169
|
+
// `Number(e.at) < farthestAt` 永远是 `0 < 0`(假),新句子再也进不来,预取静默失效。
|
|
170
|
+
if (e.at === null || e.at === undefined) return;
|
|
171
|
+
if (!bin || !e.text || !Number.isFinite(Number(e.at))) return;
|
|
172
|
+
const key = keyOf(e);
|
|
173
|
+
if (prefetched.has(key)) return;
|
|
174
|
+
if (prefetched.size >= MAX_PREFETCH) {
|
|
175
|
+
// 队列满时只留更近的:远处的合成完了也大概率赶不上,别把近处的挤掉。
|
|
176
|
+
let farthestKey = null;
|
|
177
|
+
let farthestAt = -Infinity;
|
|
178
|
+
for (const [k, v] of prefetched) {
|
|
179
|
+
if (v.at > farthestAt) { farthestAt = v.at; farthestKey = k; }
|
|
180
|
+
}
|
|
181
|
+
if (!(Number(e.at) < farthestAt)) return;
|
|
182
|
+
const old = prefetched.get(farthestKey);
|
|
183
|
+
prefetched.delete(farthestKey);
|
|
184
|
+
if (old) discard(old);
|
|
185
|
+
}
|
|
186
|
+
const task = prefetchTail.then(() => synthEdge(e.text, { bin, voice, rate }));
|
|
187
|
+
prefetchTail = task.then(() => {}, () => {});
|
|
188
|
+
const entry = { task, at: Number(e.at) };
|
|
189
|
+
prefetched.set(key, entry);
|
|
190
|
+
task.then((r) => {
|
|
191
|
+
if (!r?.ok) {
|
|
192
|
+
if (prefetched.get(key) === entry) prefetched.delete(key);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
entry.path = r.path;
|
|
196
|
+
}).catch(() => {});
|
|
197
|
+
};
|
|
137
198
|
|
|
138
199
|
if (!bin) console.error('[voice] edge-tts 没找到,退回系统声音');
|
|
139
200
|
|
|
140
201
|
const off = api.onSpeech((e) => {
|
|
202
|
+
if (e.state === 'scheduled') {
|
|
203
|
+
prefetch(e);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
141
206
|
if (e.state !== 'due') return;
|
|
142
|
-
// **先打日志再念**:调试时关心的是"它什么时候吐字",不是"有没有声"
|
|
143
|
-
console.error(`[voice ${mmss(e.at)}] ${e.text}`);
|
|
144
207
|
// 「真的出声了」只报一次:edge 成功之后就不该再由 SAPI 兜底那条报第二遍。
|
|
145
208
|
// 展示层(悬浮窗)等的就是这个上报 —— 不是 `due`(见 src/chat-store.js)。
|
|
146
209
|
let reported = false;
|
|
@@ -168,17 +231,37 @@ export function attach(api) {
|
|
|
168
231
|
} catch { /* 上报失败不影响后面的话 */ }
|
|
169
232
|
return;
|
|
170
233
|
}
|
|
234
|
+
const key = keyOf(e);
|
|
235
|
+
const ready = prefetched.get(key);
|
|
236
|
+
if (ready) prefetched.delete(key);
|
|
237
|
+
const t0 = Date.now();
|
|
238
|
+
let audio = null;
|
|
171
239
|
if (bin) {
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
240
|
+
if (ready) {
|
|
241
|
+
audio = await ready.task.catch(() => ({ ok: false, reason: 'prefetch-failed' }));
|
|
242
|
+
} else {
|
|
243
|
+
audio = await synthEdge(e.text, { bin, voice, rate });
|
|
244
|
+
}
|
|
245
|
+
if (audio?.ok) {
|
|
246
|
+
console.error(`[voice ${mmss(e.at)}] ${ready ? 'prefetched' : 'synth'} `
|
|
247
|
+
+ `ready ${Date.now() - t0}ms (wait ${waited}ms): ${e.text}`);
|
|
248
|
+
if (await playEdge(audio.path, onStart)) return;
|
|
249
|
+
console.error('[voice] ffplay 失败,继续兜底');
|
|
250
|
+
} else {
|
|
251
|
+
console.error(`[voice] edge-tts 失败(${audio?.reason ?? 'unknown'}),退回系统声音`);
|
|
252
|
+
}
|
|
175
253
|
}
|
|
254
|
+
console.error(`[voice ${mmss(e.at)}] sapi ${Date.now() - t0}ms (wait ${waited}ms): ${e.text}`);
|
|
176
255
|
if (!(await speakSapi(e.text, rate, onStart))) console.error('[voice] 系统声音也不可用,只打日志');
|
|
177
256
|
}).catch((err) => console.error(`[voice] ${err?.message ?? err}`));
|
|
178
257
|
});
|
|
179
258
|
|
|
180
259
|
console.error(`[voice] 已接上(engine=${bin ? 'edge-tts' : 'sapi'},voice=${voice})`);
|
|
181
|
-
return () =>
|
|
260
|
+
return () => {
|
|
261
|
+
off();
|
|
262
|
+
for (const entry of prefetched.values()) discard(entry);
|
|
263
|
+
prefetched.clear();
|
|
264
|
+
};
|
|
182
265
|
}
|
|
183
266
|
|
|
184
267
|
export default attach;
|
package/lib/client.js
CHANGED
|
@@ -87,6 +87,7 @@ window.__ModuleLoader__.load({
|
|
|
87
87
|
browserPort: video.browserPort ? String(video.browserPort) : '',
|
|
88
88
|
chatPort: watch.chatPort ? String(watch.chatPort) : '9377',
|
|
89
89
|
adapter: typeof voice.adapter === 'string' ? voice.adapter : '',
|
|
90
|
+
voiceEnvOverrides: Array.isArray(voice.envOverrides) ? voice.envOverrides : [],
|
|
90
91
|
};
|
|
91
92
|
}
|
|
92
93
|
|
|
@@ -126,10 +127,14 @@ window.__ModuleLoader__.load({
|
|
|
126
127
|
useInjectedStyle();
|
|
127
128
|
const [form, setForm] = useState(null);
|
|
128
129
|
const [checks, setChecks] = useState([]);
|
|
129
|
-
const [busy, setBusy] = useState(false);
|
|
130
130
|
const [checking, setChecking] = useState(false);
|
|
131
131
|
const [error, setError] = useState('');
|
|
132
132
|
const [notice, setNotice] = useState('');
|
|
133
|
+
const formRef = React.useRef(null);
|
|
134
|
+
const firstRender = React.useRef(true);
|
|
135
|
+
const saving = React.useRef(false);
|
|
136
|
+
const pending = React.useRef(false);
|
|
137
|
+
formRef.current = form;
|
|
133
138
|
|
|
134
139
|
async function runCheck(api) {
|
|
135
140
|
const target = api || apiConfig();
|
|
@@ -157,50 +162,86 @@ window.__ModuleLoader__.load({
|
|
|
157
162
|
setError('设置接口未注入,请重启 DSH。');
|
|
158
163
|
return undefined;
|
|
159
164
|
}
|
|
160
|
-
setBusy(true);
|
|
161
165
|
apiCall(api, '/state').then(state => {
|
|
162
166
|
if (cancelled) return;
|
|
163
167
|
setForm(formFromState(state));
|
|
164
|
-
setBusy(false);
|
|
165
168
|
void runCheck(api);
|
|
166
169
|
}).catch(e => {
|
|
167
170
|
if (cancelled) return;
|
|
168
171
|
setError(String(e && e.message ? e.message : e));
|
|
169
|
-
setBusy(false);
|
|
170
172
|
});
|
|
171
173
|
return () => { cancelled = true; };
|
|
172
174
|
}, []);
|
|
173
175
|
|
|
176
|
+
function validationError(current) {
|
|
177
|
+
const browserPort = current.browserPort === '' ? false : Number(current.browserPort);
|
|
178
|
+
if (browserPort !== false
|
|
179
|
+
&& (!Number.isInteger(browserPort) || browserPort < 1 || browserPort > 65535)) {
|
|
180
|
+
return '浏览器调试端口必须是 1-65535 的整数。';
|
|
181
|
+
}
|
|
182
|
+
const chatPort = Number(current.chatPort);
|
|
183
|
+
if (!Number.isInteger(chatPort) || chatPort < 1 || chatPort > 65535) {
|
|
184
|
+
return '聊天服务端口必须是 1-65535 的整数。';
|
|
185
|
+
}
|
|
186
|
+
return '';
|
|
187
|
+
}
|
|
188
|
+
|
|
174
189
|
async function save() {
|
|
175
|
-
|
|
190
|
+
const current = formRef.current;
|
|
191
|
+
if (!current) return;
|
|
192
|
+
if (saving.current) {
|
|
193
|
+
pending.current = true;
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
176
196
|
const api = apiConfig();
|
|
177
197
|
if (!api) {
|
|
178
198
|
setError('设置接口未注入,请重启 DSH。');
|
|
179
199
|
return;
|
|
180
200
|
}
|
|
181
|
-
|
|
201
|
+
const invalid = validationError(current);
|
|
202
|
+
if (invalid) {
|
|
203
|
+
setError(invalid);
|
|
204
|
+
setNotice('');
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
saving.current = true;
|
|
182
208
|
setError('');
|
|
183
209
|
setNotice('');
|
|
184
210
|
try {
|
|
185
211
|
const video = {
|
|
186
|
-
browserPort:
|
|
212
|
+
browserPort: current.browserPort === '' ? false : Number(current.browserPort),
|
|
187
213
|
};
|
|
188
|
-
const watch = { chatPort: Number(
|
|
189
|
-
const voice = { adapter:
|
|
214
|
+
const watch = { chatPort: Number(current.chatPort) };
|
|
215
|
+
const voice = { adapter: current.adapter };
|
|
190
216
|
await apiCall(api, '/save', { video: video, watch: watch, voice: voice });
|
|
191
|
-
setNotice('
|
|
217
|
+
setNotice('已自动保存。聊天端口改动在下次启动 DSH 后生效。');
|
|
192
218
|
} catch (e) {
|
|
193
219
|
setError(String(e && e.message ? e.message : e));
|
|
194
220
|
} finally {
|
|
195
|
-
|
|
221
|
+
saving.current = false;
|
|
222
|
+
if (pending.current) {
|
|
223
|
+
pending.current = false;
|
|
224
|
+
setTimeout(() => { void save(); }, 0);
|
|
225
|
+
}
|
|
196
226
|
}
|
|
197
227
|
}
|
|
198
228
|
|
|
229
|
+
useEffect(() => {
|
|
230
|
+
if (!form) return undefined;
|
|
231
|
+
if (firstRender.current) {
|
|
232
|
+
firstRender.current = false;
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
const timer = setTimeout(() => { void save(); }, 550);
|
|
236
|
+
return () => clearTimeout(timer);
|
|
237
|
+
}, [form && form.browserPort, form && form.chatPort, form && form.adapter]);
|
|
238
|
+
|
|
199
239
|
if (!form) {
|
|
200
240
|
return h('div', { 'data-dsh-vs': 'watch', className: 'dsh-vs dsh-vs-loading' }, error || '正在加载设置…');
|
|
201
241
|
}
|
|
202
242
|
|
|
203
243
|
const visibleChecks = checks.filter(item => item.id !== 'browser' && item.id !== 'chat' && item.id !== 'voice');
|
|
244
|
+
const connectionChecks = checks.filter(item => item.id === 'browser' || item.id === 'chat' || item.id === 'voice');
|
|
204
245
|
const optionalIds = { python: true, extension: true, floating: true };
|
|
205
246
|
|
|
206
247
|
return h('div', { 'data-dsh-vs': 'watch', className: 'dsh-vs' },
|
|
@@ -241,6 +282,28 @@ window.__ModuleLoader__.load({
|
|
|
241
282
|
onChange: value => setForm(prev => ({ ...prev, adapter: value })),
|
|
242
283
|
}),
|
|
243
284
|
),
|
|
285
|
+
form.voiceEnvOverrides.length
|
|
286
|
+
? h('p', { className: 'dsh-vs-effective' },
|
|
287
|
+
'环境变量优先:' + form.voiceEnvOverrides.join('、') + ';这里的改动不会覆盖它们。')
|
|
288
|
+
: null,
|
|
289
|
+
),
|
|
290
|
+
h('section', { className: 'dsh-vs-section' },
|
|
291
|
+
h('div', { className: 'dsh-vs-section-head' },
|
|
292
|
+
h('h3', { className: 'dsh-vs-section-title' }, '连接状态'),
|
|
293
|
+
),
|
|
294
|
+
connectionChecks.length
|
|
295
|
+
? h('div', { className: 'dsh-vs-deps' }, connectionChecks.map(check =>
|
|
296
|
+
h('div', { className: 'dsh-vs-dep', key: check.id },
|
|
297
|
+
h('span', {
|
|
298
|
+
className: 'dsh-vs-dot'
|
|
299
|
+
+ (check.ok ? '' : optionalIds[check.id] ? ' is-warn' : ' is-bad'),
|
|
300
|
+
}),
|
|
301
|
+
h('div', { className: 'dsh-vs-dep-main' },
|
|
302
|
+
h('div', { className: 'dsh-vs-dep-name' }, check.label || check.id),
|
|
303
|
+
h('div', { className: 'dsh-vs-dep-detail', title: check.detail || '' }, check.detail || ''),
|
|
304
|
+
),
|
|
305
|
+
)))
|
|
306
|
+
: h('p', { className: 'dsh-vs-hint' }, checking ? '正在检查…' : '尚未检查。'),
|
|
244
307
|
),
|
|
245
308
|
h('section', { className: 'dsh-vs-section' },
|
|
246
309
|
h('div', { className: 'dsh-vs-section-head' },
|
|
@@ -270,12 +333,6 @@ window.__ModuleLoader__.load({
|
|
|
270
333
|
: h('p', { className: 'dsh-vs-hint' }, checking ? '正在检查…' : '尚未检查。'),
|
|
271
334
|
),
|
|
272
335
|
h('div', { className: 'dsh-vs-footer' },
|
|
273
|
-
h('button', {
|
|
274
|
-
type: 'button',
|
|
275
|
-
className: 'dsh-vs-btn dsh-vs-btn-primary',
|
|
276
|
-
disabled: busy,
|
|
277
|
-
onClick: save,
|
|
278
|
-
}, busy ? '保存中…' : '保存'),
|
|
279
336
|
h('span', { className: 'dsh-vs-status' + (error ? ' is-error' : ''), role: 'status' },
|
|
280
337
|
error || notice),
|
|
281
338
|
),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-watch-together",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.7",
|
|
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",
|