dsh-watch-together 0.2.11 → 0.2.13

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.
@@ -186,22 +186,34 @@ 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
- self.items = [i for i in self.canvas.find_all() if self.canvas.type(i) == "text"]
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=()) -> None:
204
- """按字符拆开建 item;anchor 支持 w/e/center 与 n/s 变体。"""
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
+ 原来只有右下 1px,等于投影 —— 背景是浅色视频时右下那条边不够,字看起来
214
+ 还是浮在水里(#44 第 2 条)。四方向才是真的描边,成本是每字多 3 个 item。
215
+ `adapt=False` 表示这块字有自己的底板,颜色固定、不参与 `adapt()` 采样。
216
+ """
205
217
  font = self.fonts.get(size, bold)
206
218
  measure = font.measure
207
219
  linespace = font.metrics("linespace")
@@ -221,6 +233,9 @@ class TextLayer:
221
233
  center = anchor in ("center", "n", "s")
222
234
  height = font.metrics("ascent") + font.metrics("descent")
223
235
  spec = self.fonts.spec(size, bold)
236
+ base_tags = tags if isinstance(tags, tuple) else ((tags,) if tags else ())
237
+ shadow_tags = base_tags + ("tshadow",) if shadow else ()
238
+ stroke = ((-1, 0), (1, 0), (0, -1), (0, 1)) if shadow else ()
224
239
  for row, line in enumerate(lines):
225
240
  width = measure(line)
226
241
  lx = x - width if right else (x - width / 2 if center else x)
@@ -229,8 +244,14 @@ class TextLayer:
229
244
  # 累积宽度,别对每个字重新 measure 前缀(那是 O(n²) 次 Tcl 调用)
230
245
  cx = lx
231
246
  for ch in line:
232
- self.canvas.create_text(cx, ly, text=ch, anchor="w",
233
- fill=fill, font=spec, tags=tags)
247
+ for dx, dy in stroke:
248
+ self.canvas.create_text(cx + dx, ly + dy, text=ch, anchor="w",
249
+ fill=self.COLOR_DARK, font=spec,
250
+ tags=shadow_tags)
251
+ item = self.canvas.create_text(cx, ly, text=ch, anchor="w",
252
+ fill=fill, font=spec, tags=tags)
253
+ if not adapt:
254
+ self._fixed.add(item)
234
255
  cx += measure(ch)
235
256
 
236
257
  # ---- 翻色 ----
@@ -255,6 +276,8 @@ class TextLayer:
255
276
  gray = np.asarray(frame.convert("L"))
256
277
  h, w = gray.shape[:2]
257
278
  for item in self.items:
279
+ if item in self._fixed: # 有底板的字:颜色固定,别跟着画面翻
280
+ continue
258
281
  box = self.canvas.bbox(item)
259
282
  if not box:
260
283
  continue
@@ -40,10 +40,13 @@
40
40
  * 这样打包发布时不会把某个人的音色带进包里 —— 每个人自己配自己的。
41
41
  */
42
42
 
43
- import { execFile } from 'node:child_process';
43
+ import { execFile, spawn } 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`);
@@ -103,14 +141,36 @@ async function synthEdge(text, { bin, voice, rate }) {
103
141
  return { ok: true, path: out, engine: 'edge-tts' };
104
142
  }
105
143
 
144
+ /**
145
+ * 正在念的那一句的「掐断」句柄(老路的 ffplay 进程)。
146
+ *
147
+ * 常驻通道不需要它 —— 那边走 `stream.interrupt()`,杀的是播放管道那个 ffplay。
148
+ * 两条路都要能被打断:串行链只保证"不重叠",挡不住"越排越长"。
149
+ */
150
+ let currentKill = null;
151
+
106
152
  /** 播放一个已经合成好的 mp3;返回时无论成败都删掉临时文件。 */
107
- async function playEdge(path, onStart = null) {
153
+ function playEdge(path, onStart = null) {
108
154
  // **就在这里上报"要出声了"**:ffplay 一启动就有声 —— 悬浮窗收到才把字摆出来,
109
155
  // 于是"字出现"和"张嘴"几乎是同一刻(见 src/chat-store.js)。
110
156
  try { onStart?.(); } catch { /* 上报失败不影响念 */ }
111
- const played = await run('ffplay', ['-nodisp', '-autoexit', '-loglevel', 'quiet', path], 90_000);
112
- try { unlinkSync(path); } catch { /* 删不掉就留着 */ }
113
- return played;
157
+ // 用 spawn 而不是 execFile:需要拿到 child 才能中途掐断(`interruptCurrent`)
158
+ return new Promise((resolve) => {
159
+ const child = spawn('ffplay', ['-nodisp', '-autoexit', '-loglevel', 'quiet', path], {
160
+ windowsHide: true,
161
+ });
162
+ let settled = false;
163
+ const done = (ok) => {
164
+ if (settled) return;
165
+ settled = true;
166
+ currentKill = null;
167
+ try { unlinkSync(path); } catch { /* 删不掉就留着 */ }
168
+ resolve(ok);
169
+ };
170
+ currentKill = () => { try { child.kill(); } catch { /* 已经退了 */ } };
171
+ child.on('error', () => done(false));
172
+ child.on('exit', (code) => done(code === 0));
173
+ });
114
174
  }
115
175
 
116
176
  /** Windows 系统声音。Linux/macOS 会失败,失败就当没这个引擎。 */
@@ -119,9 +179,23 @@ function speakSapi(text, rate, onStart = null) {
119
179
  const cmd = `$v = New-Object -ComObject SAPI.SpVoice; $v.Rate = ${Math.max(-10, Math.min(10, Number(rate) || 0))}; $null = $v.Speak(${lit})`;
120
180
  // PowerShell 冷启动要几百毫秒,上报放在**起进程之前**,宁可略早也别晚(字等声音没关系,声音等字不行)
121
181
  try { onStart?.(); } catch { /* 上报失败不影响念 */ }
182
+ // spawn 而不是 execFile:`SpVoice.Speak()` 是阻塞的,只有杀掉进程才能让它闭嘴 ——
183
+ // 没有 edge-tts 的机器全走这条路(实测本机就是),不能中断的话"越堆越长"永远治不好。
122
184
  return new Promise((resolve) => {
123
- execFile('powershell', ['-NoProfile', '-NonInteractive', '-Command', cmd],
124
- { timeout: 60_000, windowsHide: true }, (err) => resolve(!err));
185
+ const child = spawn('powershell', ['-NoProfile', '-NonInteractive', '-Command', cmd], {
186
+ windowsHide: true,
187
+ });
188
+ let settled = false;
189
+ const done = (ok) => {
190
+ if (settled) return;
191
+ settled = true;
192
+ currentKill = null;
193
+ resolve(ok);
194
+ };
195
+ const guard = setTimeout(() => { try { child.kill(); } catch { /* 已经退了 */ } done(false); }, 60_000);
196
+ currentKill = () => { try { child.kill(); } catch { /* 已经退了 */ } };
197
+ child.on('error', () => { clearTimeout(guard); done(false); });
198
+ child.on('exit', (code) => { clearTimeout(guard); done(code === 0); });
125
199
  });
126
200
  }
127
201
 
@@ -148,7 +222,29 @@ export function attach(api) {
148
222
  + '想用晓萱等音色请在该文件加 "voice": "zh-CN-XiaoxuanNeural"');
149
223
  const rate = Number(cfg.rate) || 0;
150
224
  const bin = edgeBin(cfg);
225
+ // 常驻合成器:能起就用它(首声 170~200ms),起不来就是 null,全部逻辑退回老路。
226
+ const stream = openStream(bin);
151
227
  let chain = Promise.resolve(); // 播放串行:两句绝不重叠着念
228
+ /**
229
+ * 「该念的是第几句」。新的一句进来就 +1,之前排队的看到代际变了就自己退场。
230
+ *
231
+ * 为什么需要:串行链只保证"不重叠",挡不住"越排越长" —— 模型连说三句,
232
+ * 第三句要等前两句念完才开口,那时候画面早换了,听到的是"它在说上一段的事"。
233
+ * 用户要的是**新的直接顶掉旧的**,不是排队。
234
+ */
235
+ let speakGen = 0;
236
+
237
+ /**
238
+ * 掐断当前这一句,并清空排队。
239
+ *
240
+ * 常驻通道走 `stream.interrupt()`(只杀播放管道那个 ffplay,daemon 还活着);
241
+ * 老路直接 kill 调当前 ffplay。**chain 重置是有意的**:排队的都是"画面已经过去"的旧话。
242
+ */
243
+ function interruptCurrent() {
244
+ if (stream?.alive) { try { stream.interrupt(); } catch { /* 通道挂了就算了 */ } }
245
+ if (currentKill) { try { currentKill(); } catch { /* 已经退了 */ } currentKill = null; }
246
+ chain = Promise.resolve();
247
+ }
152
248
 
153
249
  // **预合成**:核心在台词写好、还没到点时发 `scheduled`。这里趁这段时间把 mp3 合成好,
154
250
  // 到点只播放;否则 due 才开始跑 edge-tts(CLI 冷启动 + 网络往返 + 完整 mp3),
@@ -200,10 +296,28 @@ export function attach(api) {
200
296
 
201
297
  const off = api.onSpeech((e) => {
202
298
  if (e.state === 'scheduled') {
299
+ // 常驻通道不需要"排队 6 句"那套:它按 text 在内存里缓存,满了淘汰最老的。
300
+ // 老路的 `MAX_PREFETCH` 是文件缓存 + 串行 CLI 逼出来的,这里不用照抄。
301
+ if (stream?.alive && e.at !== null && e.at !== undefined && e.text) {
302
+ stream.prefetch(e.text);
303
+ return;
304
+ }
203
305
  prefetch(e);
204
306
  return;
205
307
  }
206
308
  if (e.state !== 'due') return;
309
+
310
+ /**
311
+ * **抢占**:新的一句要开口了,把上一句没念完的直接截断、把还在排队的丢掉。
312
+ *
313
+ * 这是用户明确的诉求("下一句来了直接把上一句停掉,不然越堆越长")。
314
+ * 代价:被截断的那句后面几个字听不到 —— 但那几个字本来就是"上一段画面"的话,
315
+ * 留着说完反而和眼前的东西对不上。
316
+ */
317
+ speakGen += 1;
318
+ const myGen = speakGen;
319
+ interruptCurrent();
320
+
207
321
  // 「真的出声了」只报一次:edge 成功之后就不该再由 SAPI 兜底那条报第二遍。
208
322
  // 展示层(悬浮窗)等的就是这个上报 —— 不是 `due`(见 src/chat-store.js)。
209
323
  let reported = false;
@@ -217,6 +331,8 @@ export function attach(api) {
217
331
  };
218
332
  const queuedAt = Date.now();
219
333
  chain = chain.then(async () => {
334
+ // 已经被更新的一句顶掉了:直接退场,不念
335
+ if (myGen !== speakGen) return;
220
336
  // **排太久了就别念**:串行链只会越排越长,声音离画面越来越远。
221
337
  // 核心那边已经按"上一句念完才发下一句"节流,走到这里说明是真的卡住了
222
338
  // (合成慢、引擎换挡、机器在忙)—— 这一句放弃,队立刻清空。
@@ -236,6 +352,22 @@ export function attach(api) {
236
352
  if (ready) prefetched.delete(key);
237
353
  const t0 = Date.now();
238
354
  let audio = null;
355
+ // **常驻通道优先**:音频边收边写进常驻 ffplay 的管道,首块就是出声
356
+ // (实测 170~200ms;预取命中时 0ms)。失败也只在**没出过声**时才往下兜底,
357
+ // 出过声再补一遍会变成一句话念两次。
358
+ if (stream?.alive) {
359
+ try {
360
+ const r = await stream.say(e.text, { onFirst: onStart });
361
+ if (!r?.skipped) {
362
+ console.error(`[voice ${mmss(e.at)}] stream first=${r?.first ?? '-'}ms `
363
+ + `done=${r?.done ?? '-'}ms (wait ${waited}ms): ${e.text}`);
364
+ return;
365
+ }
366
+ } catch (err) {
367
+ if (reported) return;
368
+ console.error(`[voice] 常驻通道失败(${err?.message ?? err}),本句退回逐句合成`);
369
+ }
370
+ }
239
371
  if (bin) {
240
372
  if (ready) {
241
373
  audio = await ready.task.catch(() => ({ ok: false, reason: 'prefetch-failed' }));
@@ -256,11 +388,12 @@ export function attach(api) {
256
388
  }).catch((err) => console.error(`[voice] ${err?.message ?? err}`));
257
389
  });
258
390
 
259
- console.error(`[voice] 已接上(engine=${bin ? 'edge-tts' : 'sapi'},voice=${voice})`);
391
+ console.error(`[voice] 已接上(engine=${stream?.alive ? 'edge-tts/常驻' : bin ? 'edge-tts' : 'sapi'},voice=${voice})`);
260
392
  return () => {
261
393
  off();
262
394
  for (const entry of prefetched.values()) discard(entry);
263
395
  prefetched.clear();
396
+ try { stream?.stop(); } catch { /* 已经退出 */ }
264
397
  };
265
398
  }
266
399
 
@@ -0,0 +1,159 @@
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
+ /**
147
+ * 截断正在念的那一句(**不停进程**)。
148
+ *
149
+ * 和 `stop()` 的区别:`stop` 是 `SystemExit(0)`,整个常驻合成器没了,下一句要
150
+ * 重新预热 1~2 秒;`interrupt` 只杀播放管道那一个 ffplay,daemon 还活着,
151
+ * 下一句从新进程开始念(多花一次 demuxer 探测 ~200ms)。
152
+ */
153
+ interrupt() { try { send({ op: 'interrupt' }); } catch { /* 已经断了 */ } },
154
+ stop() {
155
+ try { send({ op: 'stop' }); } catch { /* already */ }
156
+ setTimeout(() => { try { proc.kill(); } catch { /* already */ } }, 300);
157
+ },
158
+ };
159
+ }