dsh-folia 4.26.0-pre.62 → 4.26.0-pre.63

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/lib/client.js CHANGED
@@ -745,6 +745,17 @@ window.__ModuleLoader__.load({
745
745
  "在听": "Listening",
746
746
  "在想": "Thinking",
747
747
  "在说": "Speaking",
748
+ // pre.63:连续对话(右键菜单 + 设置页同一 voice.continuous)
749
+ "连续对话": "Continuous conversation",
750
+ "暂停听": "Pause listening",
751
+ "继续听": "Resume listening",
752
+ "连续对话中 · 右键可关闭": "Continuous conversation · right-click to turn off",
753
+ "⏸ 连续对话已暂停(点桌宠继续)": "⏸ Continuous conversation paused (click the pet to resume)",
754
+ "页面隐藏,连续对话已暂停": "Page hidden — continuous conversation paused",
755
+ "连续对话结束:已连续 {n} 轮": "Continuous conversation ended after {n} rounds",
756
+ "连续对话已停止:{e}": "Continuous conversation stopped: {e}",
757
+ "连续对话结束:连续 {n} 轮没听到": "Continuous conversation ended: no speech for {n} rounds",
758
+ "没听到,再说一次({n}/{m})": "Didn't hear that — try again ({n}/{m})",
748
759
  "所选音色不可用,已用系统默认:{name}": "Selected voice is unavailable — using the system default: {name}",
749
760
  "所选音色不可用,已用系统默认音色": "Selected voice is unavailable — using the system default voice",
750
761
  // pre.54:本机音色来源 / 可下载目录骨架。
@@ -19407,6 +19418,25 @@ window.__ModuleLoader__.load({
19407
19418
  hasKey: false, maskedKey: '', lastError: '',
19408
19419
  });
19409
19420
  const update = React.useCallback((patch) => setDraft((prev) => ({ ...prev, ...patch })), []);
19421
+ /** pre.63:把设置页的连续对话开关同步给右键菜单(同一 voice.continuous)。 */
19422
+ const publishContinuous = React.useCallback((enabled) => {
19423
+ try {
19424
+ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {
19425
+ window.dispatchEvent(new CustomEvent('we-pet-continuous-state', { detail: { enabled: enabled === true } }));
19426
+ }
19427
+ } catch { /* 菜单同步是增强 */ }
19428
+ }, []);
19429
+ React.useEffect(() => {
19430
+ const onState = (event) => {
19431
+ const detail = (event && event.detail) || {};
19432
+ if (typeof detail.enabled === 'boolean') {
19433
+ setVoiceCfg((prev) => ({ ...prev, continuous: detail.enabled }));
19434
+ }
19435
+ };
19436
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return undefined;
19437
+ window.addEventListener('we-pet-continuous-state', onState);
19438
+ return () => window.removeEventListener('we-pet-continuous-state', onState);
19439
+ }, []);
19410
19440
 
19411
19441
  const load = React.useCallback(async () => {
19412
19442
  try {
@@ -19419,6 +19449,7 @@ window.__ModuleLoader__.load({
19419
19449
  voice.continuous = voice.continuous !== false;
19420
19450
  setDraft({ ...CHAT_DEFAULTS, ...doc, voice, apiKey: '' });
19421
19451
  setVoiceCfg({ sapiEnabled: voice.sapiEnabled, enabledEngine: voice.enabledEngine, continuous: voice.continuous });
19452
+ publishContinuous(voice.continuous !== false);
19422
19453
  setEnabledEngine(voice.enabledEngine);
19423
19454
  setCheckedEngine(voice.enabledEngine);
19424
19455
  setStatus(doc.hasApiKey
@@ -19426,7 +19457,7 @@ window.__ModuleLoader__.load({
19426
19457
  : { ok: null, text: weT('还没有填 API Key') });
19427
19458
  }
19428
19459
  } catch { /* 首次加载失败不打扰 */ }
19429
- }, []);
19460
+ }, [publishContinuous]);
19430
19461
 
19431
19462
  const loadVoices = React.useCallback(async () => {
19432
19463
  const resp = await apiJson('/pet-chat/tts/voices', { parse: 'always' }).catch(() => null);
@@ -19862,7 +19893,16 @@ window.__ModuleLoader__.load({
19862
19893
  },
19863
19894
  React.createElement('input', {
19864
19895
  type: 'checkbox', checked: continuousOn, disabled: busy,
19865
- onChange: (e) => setVoiceCfg((prev) => ({ ...prev, continuous: e.target.checked })),
19896
+ onChange: (e) => {
19897
+ const on = e.target.checked;
19898
+ setVoiceCfg((prev) => ({ ...prev, continuous: on }));
19899
+ publishContinuous(on);
19900
+ try {
19901
+ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {
19902
+ window.dispatchEvent(new CustomEvent('we-pet-continuous', { detail: { action: 'set', enabled: on } }));
19903
+ }
19904
+ } catch { /* ignore */ }
19905
+ },
19866
19906
  }),
19867
19907
  weT('☑ 连续对话')));
19868
19908
  voicePage.push(React.createElement('div', {
@@ -20597,6 +20637,15 @@ window.__ModuleLoader__.load({
20597
20637
  let walkLeft = 0;
20598
20638
  /** 单击轮换到第几号轨道。 */
20599
20639
  let clickIdx = 0;
20640
+ /** pre.63:右键菜单的连续对话状态(由 pet-chat 通过事件同步)。 */
20641
+ let continuousEnabled = true;
20642
+ let continuousPaused = false;
20643
+ const onContinuousState = (event) => {
20644
+ const detail = (event && event.detail) || {};
20645
+ if (typeof detail.enabled === 'boolean') continuousEnabled = detail.enabled;
20646
+ if (typeof detail.paused === 'boolean') continuousPaused = detail.paused;
20647
+ if (menu) closeMenu();
20648
+ };
20600
20649
 
20601
20650
  let scaleCur = Number(scale) > 0 ? Number(scale) : 1;
20602
20651
  const cw = Math.max(1, Number(pet.cell && pet.cell.width) || 192);
@@ -20816,6 +20865,9 @@ window.__ModuleLoader__.load({
20816
20865
  * 菜单条目 = 9 条动作各一条(点一下立刻试演)+ 声音/大小/复位/隐藏。
20817
20866
  */
20818
20867
  let menu = null;
20868
+ if (typeof window !== "undefined" && window.addEventListener) {
20869
+ window.addEventListener("we-pet-continuous-state", onContinuousState);
20870
+ }
20819
20871
  function closeMenu() {
20820
20872
  if (menu && menu.parentNode) menu.parentNode.removeChild(menu);
20821
20873
  menu = null;
@@ -20858,6 +20910,33 @@ window.__ModuleLoader__.load({
20858
20910
  const hr = document.createElement("div");
20859
20911
  hr.style.cssText = "height:1px;margin:6px 0;background:rgba(255,255,255,0.14)";
20860
20912
  menu.appendChild(hr);
20913
+ // pre.63:连续对话(与设置页 voice.continuous 同一字段,由 pet-chat 同步状态/持久化)
20914
+ const sendContinuous = (action) => {
20915
+ try {
20916
+ window.dispatchEvent(new CustomEvent("we-pet-continuous", { detail: { action } }));
20917
+ } catch { /* 没装 pet-chat 时无副作用 */ }
20918
+ };
20919
+ menu.appendChild(buildMenuItem(
20920
+ (continuousEnabled ? "☑ " : "☐ ") + weT("连续对话"),
20921
+ () => {
20922
+ continuousEnabled = !continuousEnabled;
20923
+ sendContinuous("toggle");
20924
+ closeMenu();
20925
+ },
20926
+ ));
20927
+ if (continuousEnabled) {
20928
+ menu.appendChild(buildMenuItem(
20929
+ continuousPaused ? weT("继续听") : weT("暂停听"),
20930
+ () => {
20931
+ sendContinuous(continuousPaused ? "resume" : "pause");
20932
+ continuousPaused = !continuousPaused;
20933
+ closeMenu();
20934
+ },
20935
+ ));
20936
+ }
20937
+ const hr2 = document.createElement("div");
20938
+ hr2.style.cssText = "height:1px;margin:6px 0;background:rgba(255,255,255,0.14)";
20939
+ menu.appendChild(hr2);
20861
20940
  // 「对话」:打开桌宠对话的输入条(由 pet-chat 特性监听该事件;没装该特性时点了无副作用)
20862
20941
  menu.appendChild(buildMenuItem(weT("对话"), () => {
20863
20942
  try { window.dispatchEvent(new CustomEvent("we-pet-talk")); } catch { /* ignore */ }
@@ -20927,6 +21006,7 @@ window.__ModuleLoader__.load({
20927
21006
  if (typeof window !== "undefined") {
20928
21007
  window.removeEventListener("pointermove", onPointerMove);
20929
21008
  window.removeEventListener("pointerup", onPointerUp);
21009
+ window.removeEventListener("we-pet-continuous-state", onContinuousState);
20930
21010
  }
20931
21011
  }
20932
21012
 
@@ -22512,7 +22592,7 @@ window.__ModuleLoader__.load({
22512
22592
  return;
22513
22593
  }
22514
22594
  const labels = {
22515
- listen: '🎤 ' + (continuous ? tr('连续对话中·点桌宠暂停') : tr('在听')),
22595
+ listen: '🎤 ' + (continuous ? tr('连续对话中 · 右键可关闭') : tr('在听')),
22516
22596
  think: '💭 ' + tr('在想'),
22517
22597
  speak: '🔊 ' + tr('在说'),
22518
22598
  };
@@ -22534,11 +22614,11 @@ window.__ModuleLoader__.load({
22534
22614
 
22535
22615
  function isVisible() { return visible; }
22536
22616
 
22537
- /** 连续对话模式:把「在听」换成一语中的状态条,提醒用户点桌宠可暂停。 */
22617
+ /** 连续对话模式:把「在听」换成一语中的状态条,提醒右键可关闭。 */
22538
22618
  function setContinuous(active) {
22539
22619
  continuous = active === true;
22540
22620
  if (continuous && statusEl && statusEl.dataset && String(statusEl.dataset.state || '') === 'listen') {
22541
- statusEl.textContent = '🎤 ' + tr('连续对话中·点桌宠暂停');
22621
+ statusEl.textContent = '🎤 ' + tr('连续对话中 · 右键可关闭');
22542
22622
  }
22543
22623
  }
22544
22624
 
@@ -23074,6 +23154,7 @@ window.__ModuleLoader__.load({
23074
23154
  } catch { /* 读不到就用默认(不静音) */ }
23075
23155
  petChatContinuousEnabled = petChatVoice.continuous !== false;
23076
23156
  if (petChatContinuousEnabled === false) petChatContinuousStop('', true);
23157
+ petChatPublishContinuousState();
23077
23158
  return petChatVoice;
23078
23159
  }
23079
23160
 
@@ -23096,6 +23177,21 @@ window.__ModuleLoader__.load({
23096
23177
  }
23097
23178
  }
23098
23179
 
23180
+ /** pre.63:把连续对话状态推给右键菜单(pet-layer 监听)。 */
23181
+ function petChatPublishContinuousState() {
23182
+ try {
23183
+ if (typeof window === 'undefined' || typeof window.dispatchEvent !== 'function') return;
23184
+ window.dispatchEvent(new CustomEvent('we-pet-continuous-state', {
23185
+ detail: {
23186
+ enabled: petChatContinuousEnabled === true,
23187
+ active: petChatContinuousActive === true,
23188
+ paused: petChatContinuousPaused === true,
23189
+ rounds: petChatContinuousRounds,
23190
+ },
23191
+ }));
23192
+ } catch { /* 右键菜单是增强,事件失败不影响对话 */ }
23193
+ }
23194
+
23099
23195
  function petChatContinuousStart() {
23100
23196
  if (petChatContinuousEnabled !== true) return false;
23101
23197
  petChatContinuousClearTimer();
@@ -23103,6 +23199,7 @@ window.__ModuleLoader__.load({
23103
23199
  petChatContinuousPaused = false;
23104
23200
  if (petChatContinuousRounds === 0) petChatContinuousSilent = 0;
23105
23201
  petBubble.setContinuous(true);
23202
+ petChatPublishContinuousState();
23106
23203
  return true;
23107
23204
  }
23108
23205
 
@@ -23113,9 +23210,59 @@ window.__ModuleLoader__.load({
23113
23210
  petChatContinuousRounds = 0;
23114
23211
  petChatContinuousSilent = 0;
23115
23212
  petBubble.setContinuous(false);
23213
+ petChatPublishContinuousState();
23116
23214
  if (reason && silent !== true) petBubble.status('info', reason, { delay: 3500 });
23117
23215
  }
23118
23216
 
23217
+ /** 右键「暂停听」:立即停掉自动续听与当前录音,但保留 enabled 字段。 */
23218
+ function petChatContinuousPause(reason) {
23219
+ if (!petChatContinuousEnabled) return false;
23220
+ petChatVoiceAbort = true;
23221
+ try { petVoiceIn.stop(); } catch { /* ignore */ }
23222
+ petChatContinuousStop(reason || weT('⏸ 连续对话已暂停(点桌宠继续)'), false);
23223
+ return true;
23224
+ }
23225
+
23226
+ /** 右键「继续听」:恢复免点击循环,并立刻开下一轮(不用再点桌宠)。 */
23227
+ function petChatContinuousResume() {
23228
+ if (!petChatContinuousEnabled) return false;
23229
+ petChatVoiceAbort = false;
23230
+ petChatContinuousPaused = false;
23231
+ petChatContinuousStart();
23232
+ petChatContinuousArm(450);
23233
+ return true;
23234
+ }
23235
+
23236
+ /** 开关(菜单/设置页共用 voice.continuous):持久化 + 广播给菜单。 */
23237
+ function petChatSetContinuousEnabled(enabled) {
23238
+ const next = enabled === true;
23239
+ petChatContinuousEnabled = next;
23240
+ if (!next) {
23241
+ petChatVoiceAbort = true;
23242
+ try { petVoiceIn.stop(); } catch { /* ignore */ }
23243
+ petChatContinuousStop('', true);
23244
+ } else {
23245
+ petChatContinuousPaused = false;
23246
+ petChatVoiceAbort = false;
23247
+ petChatPublishContinuousState();
23248
+ }
23249
+ try {
23250
+ void apiPostJson('/pet-chat/voice/config', { continuous: next }, { parse: 'always' })
23251
+ .then(() => petChatRefreshVoice())
23252
+ .catch(() => { /* 设置页下次保存会再写 */ });
23253
+ } catch { /* ignore */ }
23254
+ return next;
23255
+ }
23256
+
23257
+ /** 右键菜单事件:toggle / pause / resume。 */
23258
+ function petChatOnContinuousCommand(event) {
23259
+ const action = String((event && event.detail && event.detail.action) || '');
23260
+ if (action === 'toggle') petChatSetContinuousEnabled(!petChatContinuousEnabled);
23261
+ else if (action === 'set') petChatSetContinuousEnabled(event.detail.enabled === true);
23262
+ else if (action === 'pause') petChatContinuousPause();
23263
+ else if (action === 'resume') petChatContinuousResume();
23264
+ }
23265
+
23119
23266
  /** 朗读结束或一次静默后,延迟 0.65s 自动开麦。 */
23120
23267
  function petChatContinuousArm(delayMs) {
23121
23268
  if (!petChatContinuousEnabled || !petChatContinuousActive || petChatContinuousPaused) return;
@@ -23323,6 +23470,7 @@ window.__ModuleLoader__.load({
23323
23470
  }
23324
23471
  petChatContinuousRounds += 1;
23325
23472
  petChatContinuousSilent = 0;
23473
+ petChatPublishContinuousState();
23326
23474
  if (!queuedSpeech) petChatContinuousArm();
23327
23475
  }
23328
23476
  // 没有任何一句进入朗读(静音 / 合成不可用)⇒ 沿用旧行为:整段文字 3 秒后淡出。
@@ -23424,7 +23572,7 @@ window.__ModuleLoader__.load({
23424
23572
  const seq = ++petChatWakeSeq;
23425
23573
  if (petChatContinuousActive || petChatContinuousTimer != null) {
23426
23574
  petChatVoiceAbort = true;
23427
- petChatContinuousStop(weT('连续对话已暂停,点桌宠继续'), false);
23575
+ petChatContinuousStop(weT('⏸ 连续对话已暂停(点桌宠继续)'), false);
23428
23576
  petBubble.hide(0);
23429
23577
  petBubble.hideStatus(0);
23430
23578
  petVoiceIn.stop();
@@ -23519,9 +23667,20 @@ window.__ModuleLoader__.load({
23519
23667
 
23520
23668
  window.addEventListener('we-pet-talk', onTalkEvent);
23521
23669
  window.addEventListener('we-pet-speak', onSpeakEvent);
23670
+ // pre.63:右键菜单的连续对话开关/暂停/继续(与设置页共用 voice.continuous)。
23671
+ const onContinuousEvent = (event) => { petChatOnContinuousCommand(event); };
23672
+ window.addEventListener('we-pet-continuous', onContinuousEvent);
23673
+ // 页面隐藏:自动暂停连续对话(不偷偷在后台开麦)。
23674
+ const onVisibility = () => {
23675
+ if (typeof document === 'undefined' || document.visibilityState !== 'hidden') return;
23676
+ if (petChatContinuousActive && !petChatContinuousPaused) {
23677
+ petChatContinuousPause(weT('页面隐藏,连续对话已暂停'));
23678
+ }
23679
+ };
23680
+ document.addEventListener('visibilitychange', onVisibility);
23522
23681
  document.addEventListener('click', onDocumentClick, true);
23523
23682
  document.addEventListener('keydown', onKeyDown, true);
23524
- void petChatRefreshVoice();
23683
+ void petChatRefreshVoice().then(() => petChatPublishContinuousState()).catch(() => {});
23525
23684
  petChatEventsStart();
23526
23685
  // 对外通道:`speak(text)` 供待办/提醒直接调用(不打开任何窗口)
23527
23686
  try {
@@ -23535,8 +23694,10 @@ window.__ModuleLoader__.load({
23535
23694
  return () => {
23536
23695
  window.removeEventListener('we-pet-talk', onTalkEvent);
23537
23696
  window.removeEventListener('we-pet-speak', onSpeakEvent);
23697
+ window.removeEventListener('we-pet-continuous', onContinuousEvent);
23538
23698
  document.removeEventListener('click', onDocumentClick, true);
23539
23699
  document.removeEventListener('keydown', onKeyDown, true);
23700
+ document.removeEventListener('visibilitychange', onVisibility);
23540
23701
  petChatEventsStop();
23541
23702
  petSpeakStop();
23542
23703
  try { if (window.__dshFoliaPet) delete window.__dshFoliaPet; } catch { /* ignore */ }
@@ -40,7 +40,7 @@ import {
40
40
  // v0.1:旧键迁移与默认值只在 settings-schema 定义一次,路由复用同一个函数
41
41
  import { readPetChat as normalizePetChat } from '../settings-schema.js';
42
42
  import {
43
- createVoiceRecorder, defaultResolveFfmpeg, defaultRunFfmpeg, pickDevice,
43
+ createVoiceRecorder, defaultResolveFfmpeg, defaultRunFfmpeg, defaultRunFfmpegStream, pickDevice,
44
44
  setFfmpegProvisioner, ffmpegProvisionStatus, ensureFfmpegStatus, ensureFfmpegNow,
45
45
  } from '../voice/record.js';
46
46
  // 本地 STT:资源不下发到 npm 包,首次使用时从站点 R2 下载(见 lib/asr/asr-local.js)
@@ -438,6 +438,8 @@ export function registerPetChatRoutes(webServer, c) {
438
438
  const voiceRecorder = createVoiceRecorder({
439
439
  resolveFfmpeg: defaultResolveFfmpeg,
440
440
  runFfmpeg: defaultRunFfmpeg,
441
+ // pre.63:流式 VAD(stdout pipe + Node RMS),说完 0.7s 就停;pipe 不可用回退固定窗口。
442
+ runFfmpegStream: defaultRunFfmpegStream,
441
443
  });
442
444
 
443
445
  /**
@@ -10,7 +10,7 @@
10
10
  * runFfmpeg(ff, args, timeoutMs) → Promise<{ code, stderr }>
11
11
  */
12
12
  import { spawn } from 'node:child_process';
13
- import { closeSync, existsSync, mkdtempSync, openSync, readFileSync, rmSync, statSync } from 'node:fs';
13
+ import { closeSync, existsSync, mkdtempSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
14
14
  import { tmpdir } from 'node:os';
15
15
  import { join } from 'node:path';
16
16
 
@@ -27,6 +27,10 @@ export const RECORD_DEFAULTS = Object.freeze({
27
27
  probeMinRms: 0.004,
28
28
  /** 整段录音阈值(约 -38 dBFS):太低先提示“太小声”,不送 ASR。 */
29
29
  minSpeechRms: 0.002, // 只用来记录静音,不再拒绝录音
30
+ /** pre.63:流式 VAD —— 开口后静音 600–800ms 就停(默认 700ms)。 */
31
+ streamSilenceMs: 700,
32
+ streamMaxMs: 15000,
33
+ noOnsetMs: 8000,
30
34
  });
31
35
 
32
36
  /**
@@ -232,13 +236,143 @@ export function detectAutoStop(stderr, options = {}) {
232
236
  };
233
237
  }
234
238
 
235
- /** 生成 dshow 输入参数(Windows);其它平台没有 dshow,直接报 no-device。 */
239
+ /** 16-bit PCM 的 RMS(0..1);流式 VAD 每 20ms 一帧调用。 */
240
+ export function pcm16Rms(buf) {
241
+ if (!buf || buf.length < 2) return 0;
242
+ const n = Math.floor(buf.length / 2);
243
+ let sum = 0;
244
+ for (let i = 0; i < n; i += 1) {
245
+ const s = buf.readInt16LE(i * 2) / 32768;
246
+ sum += s * s;
247
+ }
248
+ return Math.sqrt(sum / n);
249
+ }
250
+
251
+ /** 给内存 PCM 补 44 字节 WAV 头(流式录音 kill 后不再依赖 ffmpeg 补头)。 */
252
+ export function pcm16Wav(pcm, sampleRate = 16000, channels = 1) {
253
+ const body = Buffer.from(pcm || Buffer.alloc(0));
254
+ const dataLen = body.length - (body.length % 2);
255
+ const header = Buffer.alloc(44);
256
+ const rate = Number(sampleRate) || 16000;
257
+ const ch = Number(channels) || 1;
258
+ header.write('RIFF', 0, 'ascii');
259
+ header.writeUInt32LE(36 + dataLen, 4);
260
+ header.write('WAVE', 8, 'ascii');
261
+ header.write('fmt ', 12, 'ascii');
262
+ header.writeUInt32LE(16, 16);
263
+ header.writeUInt16LE(1, 20);
264
+ header.writeUInt16LE(ch, 22);
265
+ header.writeUInt32LE(rate, 24);
266
+ header.writeUInt32LE(rate * ch * 2, 28);
267
+ header.writeUInt16LE(ch * 2, 32);
268
+ header.writeUInt16LE(16, 34);
269
+ header.write('data', 36, 'ascii');
270
+ header.writeUInt32LE(dataLen, 40);
271
+ return Buffer.concat([header, body.subarray(0, dataLen)]);
272
+ }
273
+
274
+ /**
275
+ * 流式 RMS VAD(纯函数,判据可直接喂假 PCM):
276
+ * 前 300ms 估噪声底;阈值 = max(0.006, 噪声 × 3);
277
+ * 连续 3 帧(60ms)超阈值 = 开口;开口后连续 silenceMs(默认 700ms)低于阈值 = 说完。
278
+ * 8 秒没开口 = no-onset;15 秒上限 = max。
279
+ */
280
+ export function createPcmVad(options = {}) {
281
+ const sampleRate = Number(options.sampleRate) || 16000;
282
+ const frameMs = 20;
283
+ const frameBytes = Math.max(2, Math.floor(sampleRate * frameMs / 1000) * 2);
284
+ const silenceMs = Math.max(300, Math.min(1200, Number(options.silenceMs) || RECORD_DEFAULTS.streamSilenceMs));
285
+ const maxMs = Math.max(1500, Number(options.maxMs) || RECORD_DEFAULTS.streamMaxMs);
286
+ const noOnsetMs = Math.max(1500, Number(options.noOnsetMs) || RECORD_DEFAULTS.noOnsetMs);
287
+ const minThreshold = 0.006;
288
+ const noiseFrames = Math.max(1, Math.round(300 / frameMs));
289
+ const requiredOnset = 3;
290
+ let pending = Buffer.alloc(0);
291
+ let frames = 0;
292
+ let noiseSum = 0;
293
+ let noiseCount = 0;
294
+ let threshold = minThreshold;
295
+ let onsetFrames = 0;
296
+ let speaking = false;
297
+ let onsetMs = 0;
298
+ let lastVoiceMs = 0;
299
+ let silenceFrames = 0;
300
+ let done = false;
301
+ let reason = '';
302
+ let endSilenceMs = 0;
303
+
304
+ function push(chunk) {
305
+ if (done) return { done: true, reason };
306
+ const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk || []);
307
+ pending = pending.length ? Buffer.concat([pending, data]) : data;
308
+ while (!done && pending.length >= frameBytes) {
309
+ const frame = pending.subarray(0, frameBytes);
310
+ pending = pending.subarray(frameBytes);
311
+ const rms = pcm16Rms(frame);
312
+ frames += 1;
313
+ const atMs = frames * frameMs;
314
+ if (!speaking) {
315
+ if (frames <= noiseFrames) {
316
+ noiseSum += rms;
317
+ noiseCount += 1;
318
+ if (noiseCount >= noiseFrames) threshold = Math.max(minThreshold, (noiseSum / noiseCount) * 3);
319
+ }
320
+ if (rms > threshold) onsetFrames += 1;
321
+ else onsetFrames = 0;
322
+ if (onsetFrames >= requiredOnset) {
323
+ speaking = true;
324
+ onsetMs = Math.max(0, atMs - allowedOnsetMs());
325
+ lastVoiceMs = atMs;
326
+ silenceFrames = 0;
327
+ } else if (atMs >= noOnsetMs) {
328
+ done = true;
329
+ reason = 'no-onset';
330
+ }
331
+ } else {
332
+ if (rms > threshold) {
333
+ lastVoiceMs = atMs;
334
+ silenceFrames = 0;
335
+ } else {
336
+ silenceFrames += 1;
337
+ if (silenceFrames * frameMs >= silenceMs) {
338
+ done = true;
339
+ reason = 'silence';
340
+ endSilenceMs = silenceFrames * frameMs;
341
+ }
342
+ }
343
+ if (!done && atMs >= maxMs) {
344
+ done = true;
345
+ reason = 'max';
346
+ }
347
+ }
348
+ }
349
+ return { done, reason };
350
+ }
351
+
352
+ function allowedOnsetMs() {
353
+ return (requiredOnset - 1) * frameMs;
354
+ }
355
+
356
+ function result() {
357
+ return {
358
+ reason: reason || (done ? 'stopped' : ''),
359
+ speechEnd: speaking ? Number((lastVoiceMs / 1000).toFixed(3)) : 0,
360
+ onsetMs,
361
+ endMs: lastVoiceMs,
362
+ endSilenceMs,
363
+ frames,
364
+ threshold: Number(threshold.toFixed(6)),
365
+ maxMs,
366
+ silenceMs,
367
+ };
368
+ }
369
+
370
+ return { push, result, frameBytes };
371
+ }
372
+
373
+ /** 生成固定窗口 dshow 参数(流式不可用时的兜底;带 silencedetect 只作诊断)。 */
236
374
  export function dshowArgs(device, options = {}) {
237
375
  const opts = { ...RECORD_DEFAULTS, ...options };
238
- // 路由会把没传的参数显式传成 undefined:
239
- // { ...DEFAULTS, ...{ maxMs: undefined } } 会把默认值覆盖成 undefined,
240
- // 接着 timeoutMs = NaN ⇒ setTimeout(NaN) 立刻触发 ⇒ /record 0.2s 就回“录音超时”。
241
- // 这里逐项兜底成默认值(0 是合法值,只认真正的非数字)。
242
376
  for (const key of ['maxMs', 'silenceDb', 'silenceMs', 'sampleRate', 'minSpeechMs', 'onsetWaitMs']) {
243
377
  const n = Number(opts[key]);
244
378
  if (!Number.isFinite(n) || n <= 0) opts[key] = RECORD_DEFAULTS[key];
@@ -252,6 +386,103 @@ export function dshowArgs(device, options = {}) {
252
386
  ];
253
387
  }
254
388
 
389
+ /** dshow → raw s16le stdout(VAD 在 Node 侧,不依赖 ffmpeg silencedetect / WAV 文件)。 */
390
+ export function streamArgs(device, options = {}) {
391
+ const sampleRate = Number(options.sampleRate) || 16000;
392
+ return [
393
+ '-hide_banner', '-loglevel', 'error',
394
+ '-f', 'dshow', '-i', `audio=${device}`,
395
+ '-ar', String(sampleRate), '-ac', '1',
396
+ '-acodec', 'pcm_s16le', '-f', 's16le', '-',
397
+ ];
398
+ }
399
+
400
+ /**
401
+ * 流式录音:stdout 单独 pipe(本机实测可用;stdin/stderr 仍走 ignore/文件),
402
+ * 每帧喂 VAD,说完立刻 kill;PCM 在内存里,不依赖 ffmpeg 收尾。
403
+ * 返回 `{ok,pcm,...,unsupported}`;spawn 失败/无数据 ⇒ unsupported=true 交给固定窗口兜底。
404
+ */
405
+ export function defaultRunFfmpegStream(ff, args, timeoutMs = 23000, options = {}) {
406
+ const vad = createPcmVad(options);
407
+ const chunks = [];
408
+ const startedAt = Date.now();
409
+ return new Promise((resolve) => {
410
+ const errFile = join(tmpdir(), 'folia-ffmpeg-stream-' + process.pid + '-' + Date.now() + '.log');
411
+ let fd = null;
412
+ try { fd = openSync(errFile, 'w'); } catch { fd = null; }
413
+ let child = null;
414
+ let settled = false;
415
+ let stopSent = false;
416
+ let reason = '';
417
+ let timer = null;
418
+ let forceTimer = null;
419
+ const cleanup = () => {
420
+ if (timer) { clearTimeout(timer); timer = null; }
421
+ if (forceTimer) { clearTimeout(forceTimer); forceTimer = null; }
422
+ try { if (fd !== null) closeSync(fd); } catch { /* ignore */ }
423
+ let stderr = '';
424
+ try { stderr = readFileSync(errFile, 'utf8'); } catch { /* ignore */ }
425
+ try { rmSync(errFile, { force: true }); } catch { /* ignore */ }
426
+ return stderr;
427
+ };
428
+ const finish = (extra = {}) => {
429
+ if (settled) return;
430
+ settled = true;
431
+ const stderr = cleanup();
432
+ const pcm = Buffer.concat(chunks);
433
+ const vr = vad.result();
434
+ resolve(Object.assign({
435
+ ok: pcm.length >= 640,
436
+ pcm,
437
+ unsupported: false,
438
+ code: extra.code === undefined ? 0 : extra.code,
439
+ signal: extra.signal || '',
440
+ stderrTail: stderrTailOf(stderr),
441
+ elapsedMs: Date.now() - startedAt,
442
+ speechEnd: vr.speechEnd,
443
+ onsetMs: vr.onsetMs,
444
+ endMs: vr.endMs,
445
+ endSilenceMs: vr.endSilenceMs,
446
+ threshold: vr.threshold,
447
+ reason: reason || vr.reason,
448
+ noOnset: (reason || vr.reason) === 'no-onset',
449
+ }, extra));
450
+ };
451
+ const stop = (why) => {
452
+ if (stopSent) return;
453
+ stopSent = true;
454
+ reason = why || reason;
455
+ try { if (child && child.pid !== undefined) child.kill('SIGTERM'); } catch { /* ignore */ }
456
+ // kill 在 Windows 上偶发 close 不来:1.5s 后用已收 PCM 收口(PCM 已在内存)。
457
+ if (!forceTimer) forceTimer = setTimeout(() => finish({ code: null, signal: 'SIGTERM' }), 1500);
458
+ };
459
+ try {
460
+ child = spawn(ff, args, {
461
+ windowsHide: true,
462
+ // stdout 单独 pipe(已验证可用);stdin/stderr 不开管道(DSH 沙箱下会 EPERM)。
463
+ stdio: ['ignore', 'pipe', fd === null ? 'ignore' : fd],
464
+ });
465
+ } catch (error) {
466
+ finish({ ok: false, unsupported: true, code: -1, error: String((error && error.message) || error) });
467
+ return;
468
+ }
469
+ if (!child || !child.stdout) {
470
+ finish({ ok: false, unsupported: true, code: -1, error: 'stdout pipe unavailable' });
471
+ return;
472
+ }
473
+ timer = setTimeout(() => stop('timeout'), Math.max(3000, Number(timeoutMs) || 23000));
474
+ child.on('error', (error) => finish({ ok: false, unsupported: true, code: -1, error: String((error && error.message) || error) }));
475
+ child.stdout.on('error', () => stop('stdout-error'));
476
+ child.stdout.on('data', (chunk) => {
477
+ if (!chunk || !chunk.length) return;
478
+ chunks.push(chunk);
479
+ const state = vad.push(chunk);
480
+ if (state.done) stop(state.reason);
481
+ });
482
+ child.on('close', (code, signal) => finish({ code, signal: signal || '' }));
483
+ });
484
+ }
485
+
255
486
  /** 每个设备先录 1 秒(不加重滤镜)测 RMS;只用来选设备,不算正式录音。 */
256
487
  export function probeArgs(device, options = {}) {
257
488
  const opts = { ...RECORD_DEFAULTS, ...options };
@@ -266,6 +497,7 @@ export function probeArgs(device, options = {}) {
266
497
 
267
498
  export function createVoiceRecorder(deps) {
268
499
  const { resolveFfmpeg, runFfmpeg } = deps || {};
500
+ const runFfmpegStream = deps && typeof deps.runFfmpegStream === 'function' ? deps.runFfmpegStream : null;
269
501
  const probeSize = typeof deps.probeSize === 'function' ? deps.probeSize : (path) => { try { return statSync(path).size; } catch { return 0; } };
270
502
 
271
503
  async function listDevices() {
@@ -332,6 +564,7 @@ async function record(options = {}) {
332
564
  const attempts = [];
333
565
  let lastCode = 'no-speech';
334
566
  let kept = null; // 最近一次失败但保留的录音(供回放)
567
+ let streamBroken = false;
335
568
  const dropKept = () => {
336
569
  if (!kept) return;
337
570
  try { rmSync(kept.dir, { recursive: true, force: true }); } catch { /* ignore */ }
@@ -346,24 +579,54 @@ async function record(options = {}) {
346
579
  let usedPlain = false;
347
580
  let watchStopped = false;
348
581
  let interrupted = false;
582
+ let streamMeta = null;
349
583
  try {
350
584
  const ff = await resolveFfmpeg(null);
351
- const watch = {
352
- stopOnSpeechEnd: { silenceMs: opts.silenceMs, minSpeechMs: opts.minSpeechMs },
353
- onsetWaitMs: opts.onsetWaitMs,
354
- };
355
- // ⚠️ Windows 下 SIGTERM/SIGINT 杀 ffmpeg 会让输出 WAV 变 0 字节(实测)。
356
- // 所以录音不再中途 kill:固定窗口(默认最多 6 秒),让 ffmpeg 自然结束,文件才完整。
357
- const windowMs = Math.max(1500, Math.min(opts.maxMs, 6000));
358
- result = await runFfmpeg(ff, [...dshowArgs(device, { ...opts, maxMs: windowMs }), audioPath], windowMs + 8000);
359
- watchStopped = Boolean(result && result.stoppedByWatch);
360
- interrupted = watchStopped || Boolean(result && (result.timedOut === true || result.signal === 'SIGTERM'));
361
- if (result && result.code !== 0 && !interrupted) {
362
- const args = dshowArgs(device, opts);
363
- const cut = args.indexOf('-af');
364
- const plain = cut >= 0 ? args.slice(0, cut).concat(args.slice(cut + 2)) : args;
365
- const retry = await runFfmpeg(ff, [...plain, audioPath], opts.maxMs + 8000);
366
- if (retry && retry.code === 0) { result = retry; usedPlain = true; }
585
+ // pre.63:流式 VAD 优先 —— stdout PCM 进内存,说话停 700ms 就 kill,不等固定窗口。
586
+ if (runFfmpegStream && !streamBroken) {
587
+ const startedStream = Date.now();
588
+ const stream = await runFfmpegStream(ff, streamArgs(device, opts), opts.maxMs + 8000, {
589
+ sampleRate: opts.sampleRate,
590
+ silenceMs: opts.streamSilenceMs,
591
+ maxMs: Math.min(opts.maxMs, opts.streamMaxMs),
592
+ noOnsetMs: opts.noOnsetMs,
593
+ });
594
+ if (stream && stream.unsupported === true) {
595
+ streamBroken = true; // pipe 不可用 ⇒ 本进程后续走固定窗口
596
+ } else if (stream && stream.pcm && stream.pcm.length >= 640) {
597
+ writeFileSync(audioPath, pcm16Wav(stream.pcm, opts.sampleRate));
598
+ streamMeta = Object.assign({}, stream, { wallMs: Date.now() - startedStream });
599
+ result = { code: 0, stderr: '', stream: true };
600
+ if (stream.reason === 'no-onset' || stream.noOnset === true) {
601
+ // 8 秒没开口:明确 no-speech,不再补 6 秒固定窗口。
602
+ streamMeta = null;
603
+ dropKept();
604
+ kept = { dir, audioPath, bytes: probeSize(audioPath) || 0 };
605
+ attempts.push({ device, code: 'no-speech', stream: true, ms: stream.wallMs, bytes: kept.bytes, reason: 'no-onset' });
606
+ lastCode = 'no-speech';
607
+ continue;
608
+ }
609
+ }
610
+ }
611
+ if (!streamMeta) {
612
+ // 兜底:旧固定窗口(6s),仍保留 silencedetect 诊断;不依赖 kill 后的文件。
613
+ const watch = {
614
+ stopOnSpeechEnd: { silenceMs: opts.silenceMs, minSpeechMs: opts.minSpeechMs },
615
+ onsetWaitMs: opts.onsetWaitMs,
616
+ };
617
+ // ⚠️ Windows 下 SIGTERM/SIGINT 杀 ffmpeg 会让输出 WAV 变 0 字节(实测)。
618
+ // 所以兜底路径不再中途 kill:固定窗口(默认最多 6 秒),让 ffmpeg 自然结束,文件才完整。
619
+ const windowMs = Math.max(1500, Math.min(opts.maxMs, 6000));
620
+ result = await runFfmpeg(ff, [...dshowArgs(device, { ...opts, maxMs: windowMs }), audioPath], windowMs + 8000);
621
+ watchStopped = Boolean(result && result.stoppedByWatch);
622
+ interrupted = watchStopped || Boolean(result && (result.timedOut === true || result.signal === 'SIGTERM'));
623
+ if (result && result.code !== 0 && !interrupted) {
624
+ const args = dshowArgs(device, opts);
625
+ const cut = args.indexOf('-af');
626
+ const plain = cut >= 0 ? args.slice(0, cut).concat(args.slice(cut + 2)) : args;
627
+ const retry = await runFfmpeg(ff, [...plain, audioPath], opts.maxMs + 8000);
628
+ if (retry && retry.code === 0) { result = retry; usedPlain = true; }
629
+ }
367
630
  }
368
631
  } catch {
369
632
  rmSync(dir, { recursive: true, force: true });
@@ -385,6 +648,15 @@ async function record(options = {}) {
385
648
  timedOut: Boolean(result && result.timedOut),
386
649
  signal: (result && result.signal) || '',
387
650
  noOnset: Boolean(result && result.noOnset === true),
651
+ stream: Boolean(streamMeta),
652
+ vad: streamMeta ? {
653
+ reason: streamMeta.reason || '',
654
+ speechEnd: streamMeta.speechEnd || 0,
655
+ onsetMs: streamMeta.onsetMs || 0,
656
+ endSilenceMs: streamMeta.endSilenceMs || 0,
657
+ threshold: streamMeta.threshold || 0,
658
+ wallMs: streamMeta.wallMs || 0,
659
+ } : null,
388
660
  stderrTail: stderrTailOf(stderr),
389
661
  };
390
662
  // 只有"设备打不开"才算 no-device/open-failed;与静音无关。
@@ -401,7 +673,15 @@ async function record(options = {}) {
401
673
  lastCode = 'open-failed';
402
674
  continue;
403
675
  }
404
- let ended = detectSpeechEnd(stderr);
676
+ let ended = streamMeta
677
+ ? {
678
+ speechEnd: Number(streamMeta.speechEnd) || Number(streamMeta.pcm.length / 2 / (Number(opts.sampleRate) || 16000)),
679
+ auto: true,
680
+ stream: true,
681
+ onsetMs: Number(streamMeta.onsetMs) || 0,
682
+ endSilenceMs: Number(streamMeta.endSilenceMs) || 0,
683
+ }
684
+ : detectSpeechEnd(stderr);
405
685
  if (!ended && interrupted) {
406
686
  ended = {
407
687
  speechEnd: Number(result && result.speechEnd) || Number((ms / 1000).toFixed(2)),
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-folia",
3
3
  "displayName": "Folia · 壁纸引擎与桌宠",
4
- "version": "4.26.0-pre.62",
4
+ "version": "4.26.0-pre.63",
5
5
  "description": "DSH 壁纸引擎:本机 WE 壁纸实时渲染,视频/网页/开机动画/桌宠皮肤,一键拉取在线素材。",
6
6
  "type": "module",
7
7
  "engines": {