dsh-folia 4.26.0-pre.4 → 4.26.0-pre.41

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.
Files changed (76) hide show
  1. package/lib/asr/asr-local.js +166 -0
  2. package/lib/asr/asr-worker.cjs +169 -0
  3. package/lib/boot/index.js +140 -8
  4. package/lib/client.js +1172 -790
  5. package/lib/index.js +3 -7
  6. package/lib/media-state.js +5 -1
  7. package/lib/pet-chat-proactive.js +112 -112
  8. package/lib/route-registry.js +1 -1
  9. package/lib/routes/boot.js +82 -6
  10. package/lib/routes/pet-chat.js +1375 -800
  11. package/lib/routes/skins.js +3 -1
  12. package/lib/settings-schema.js +2161 -2171
  13. package/lib/switch-cache-family.js +9 -0
  14. package/lib/tts/tts-worker.cjs +129 -0
  15. package/lib/voice/record.js +230 -0
  16. package/package.json +6 -62
  17. package/assets/readme/OFL-Jersey20.txt +0 -93
  18. package/assets/readme/SOURCES.md +0 -17
  19. package/assets/readme/hero-dark.png +0 -0
  20. package/assets/readme/hero-light.png +0 -0
  21. package/assets/readme/key-docs-dark.png +0 -0
  22. package/assets/readme/key-docs-light.png +0 -0
  23. package/assets/readme/key-get-dark.png +0 -0
  24. package/assets/readme/key-get-light.png +0 -0
  25. package/assets/readme/key-lang-en-dark.png +0 -0
  26. package/assets/readme/key-lang-en-light.png +0 -0
  27. package/assets/readme/key-lang-start-dark.png +0 -0
  28. package/assets/readme/key-lang-start-light.png +0 -0
  29. package/assets/readme/key-lang-zh-dark.png +0 -0
  30. package/assets/readme/key-lang-zh-light.png +0 -0
  31. package/assets/readme/key-release-dark.png +0 -0
  32. package/assets/readme/key-release-light.png +0 -0
  33. package/assets/readme/key-setup-dark.png +0 -0
  34. package/assets/readme/key-setup-light.png +0 -0
  35. package/assets/readme/mascot-eating-rice-1280x1784.jpg +0 -0
  36. package/assets/readme/section-community-dark.png +0 -0
  37. package/assets/readme/section-community-light.png +0 -0
  38. package/assets/readme/section-compat-dark.png +0 -0
  39. package/assets/readme/section-compat-light.png +0 -0
  40. package/assets/readme/section-config-dark.png +0 -0
  41. package/assets/readme/section-config-light.png +0 -0
  42. package/assets/readme/section-credits-dark.png +0 -0
  43. package/assets/readme/section-credits-light.png +0 -0
  44. package/assets/readme/section-develop-dark.png +0 -0
  45. package/assets/readme/section-develop-light.png +0 -0
  46. package/assets/readme/section-features-dark.png +0 -0
  47. package/assets/readme/section-features-light.png +0 -0
  48. package/assets/readme/section-formats-dark.png +0 -0
  49. package/assets/readme/section-formats-light.png +0 -0
  50. package/assets/readme/section-index-dark.png +0 -0
  51. package/assets/readme/section-index-light.png +0 -0
  52. package/assets/readme/section-install-dark.png +0 -0
  53. package/assets/readme/section-install-light.png +0 -0
  54. package/assets/readme/section-intro-dark.png +0 -0
  55. package/assets/readme/section-intro-light.png +0 -0
  56. package/assets/readme/section-pet-dark.png +0 -0
  57. package/assets/readme/section-pet-light.png +0 -0
  58. package/assets/readme/section-preview-dark.png +0 -0
  59. package/assets/readme/section-preview-light.png +0 -0
  60. package/assets/readme/section-stars-dark.png +0 -0
  61. package/assets/readme/section-stars-light.png +0 -0
  62. package/assets/readme/section-start-dark.png +0 -0
  63. package/assets/readme/section-start-light.png +0 -0
  64. package/assets/readme/section-support-dark.png +0 -0
  65. package/assets/readme/section-support-light.png +0 -0
  66. package/assets/readme/section-usage-dark.png +0 -0
  67. package/assets/readme/section-usage-light.png +0 -0
  68. package/assets/readme/stat-formats-dark.png +0 -0
  69. package/assets/readme/stat-formats-light.png +0 -0
  70. package/assets/readme/stat-mascots-dark.png +0 -0
  71. package/assets/readme/stat-mascots-light.png +0 -0
  72. package/assets/readme/stat-modules-dark.png +0 -0
  73. package/assets/readme/stat-modules-light.png +0 -0
  74. package/assets/readme/stat-version-dark.png +0 -0
  75. package/assets/readme/stat-version-light.png +0 -0
  76. package/lib/pet-chat-edge-tts.js +0 -105
@@ -0,0 +1,166 @@
1
+ /**
2
+ * asr-local.js — 本地 STT 运行时:下载/校验/启动 worker(宿主侧,普通 node 进程)。
3
+ *
4
+ * 设计约束(和 tts 那套一致):
5
+ * · 资源不进 npm 包,放站点 R2,按 manifest 逐文件下载(带 sha256 校验、可续传)
6
+ * · **不能**在本进程里 require sherpa(Electron 里 native addon 会抛
7
+ * `External buffers are not allowed`)⇒ 一律走 node.exe 子进程 + NDJSON
8
+ * · 用户零操作:第一次用语音时自动下载,进度通过 onProgress 回给上层
9
+ *
10
+ * manifest 形状(站点 /media/asr/v1/manifest.json):
11
+ * { "version":"v1", "sampleRate":16000,
12
+ * "files":[ { "key":"asr/v1/models/sensevoice/model.int8.onnx", "size":123, "sha256":"…" } ] }
13
+ * key 同时也是相对 /media/ 的路径(便于复用别的包里的文件,例如 node.exe)。
14
+ */
15
+ import { createHash } from 'node:crypto';
16
+ import { createWriteStream, createReadStream, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs';
17
+ import { spawn } from 'node:child_process';
18
+ import { dirname, join } from 'node:path';
19
+ import { Readable } from 'node:stream';
20
+ import { pipeline } from 'node:stream/promises';
21
+
22
+ const MEDIA_BASE = 'https://folia-5ve.pages.dev/media/';
23
+ const DEFAULT_MANIFEST = MEDIA_BASE + 'asr/v1/manifest.json';
24
+
25
+ /** 下载一个文件到 dest(先写 .part,校验通过再改名;支持 Range 续传)。 */
26
+ async function downloadOne(url, dest, expectedSize, onBytes) {
27
+ const part = dest + '.part';
28
+ let start = 0;
29
+ if (existsSync(part)) start = statSync(part).size;
30
+ if (existsSync(dest) && expectedSize > 0 && statSync(dest).size === expectedSize) {
31
+ if (typeof onBytes === 'function') onBytes(expectedSize);
32
+ return;
33
+ }
34
+ const headers = {};
35
+ if (start > 0) headers.Range = `bytes=${start}-`;
36
+ const resp = await fetch(url, { headers });
37
+ if (!resp.ok && resp.status !== 206) throw new Error(`下载失败 ${resp.status} ${url}`);
38
+ if (resp.status !== 206) start = 0; // 服务器不支持续传 ⇒ 重头写
39
+ await pipeline(Readable.fromWeb(resp.body), createWriteStream(part, { flags: start > 0 ? 'a' : 'w' }));
40
+ const size = statSync(part).size;
41
+ if (expectedSize > 0 && size !== expectedSize) {
42
+ throw new Error(`大小不符:${dest} 期望 ${expectedSize} 实际 ${size}`);
43
+ }
44
+ rmSync(dest, { force: true });
45
+ renameSync(part, dest);
46
+ if (typeof onBytes === 'function') onBytes(expectedSize - start);
47
+ }
48
+
49
+ /** 校验 sha256(不匹配则删掉重来一次)。 */
50
+ async function verifyOrDrop(file, sha256) {
51
+ if (!sha256) return true;
52
+ if (!existsSync(file)) return false;
53
+ const hash = createHash('sha256');
54
+ await pipeline(createReadStream(file), hash);
55
+ const actual = hash.digest('hex');
56
+ if (actual === String(sha256).toLowerCase()) return true;
57
+ rmSync(file, { force: true });
58
+ return false;
59
+ }
60
+
61
+ /**
62
+ * 确保运行时完整(缺什么下什么)。
63
+ * @returns {Promise<{ root: string, manifest: object }>}
64
+ */
65
+ export async function ensureInstalled(root, options = {}) {
66
+ const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
67
+ const manifestUrl = options.manifestUrl || DEFAULT_MANIFEST;
68
+ const resp = await fetch(manifestUrl, { cache: 'no-store' });
69
+ if (!resp.ok) throw new Error(`manifest 获取失败 ${resp.status}`);
70
+ const manifest = await resp.json();
71
+ const files = Array.isArray(manifest.files) ? manifest.files : [];
72
+ const total = files.reduce((sum, f) => sum + (Number(f.size) || 0), 0);
73
+ let done = 0;
74
+ for (const file of files) {
75
+ const dest = join(root, ...String(file.key).split('/').slice(2)); // 去掉 'asr/v1/'
76
+ mkdirSync(dirname(dest), { recursive: true });
77
+ const ok = await verifyOrDrop(dest, file.sha256);
78
+ if (!ok) {
79
+ await downloadOne(MEDIA_BASE + file.key, dest, Number(file.size) || 0, (n) => {
80
+ done += n;
81
+ if (onProgress) onProgress({ doneBytes: done, totalBytes: total, file: file.key });
82
+ });
83
+ const verified = await verifyOrDrop(dest, file.sha256);
84
+ if (!verified) throw new Error(`校验失败:${file.key}`);
85
+ } else {
86
+ done += Number(file.size) || 0;
87
+ if (onProgress) onProgress({ doneBytes: done, totalBytes: total, file: file.key });
88
+ }
89
+ }
90
+ return { root, manifest };
91
+ }
92
+
93
+ /** worker 运行所需的路径(相对安装根)。 */
94
+ function workerPaths(root) {
95
+ return {
96
+ nodeExe: join(root, 'runtime', 'node.exe'),
97
+ worker: join(root, 'runtime', 'asr-worker.cjs'),
98
+ };
99
+ }
100
+
101
+ /**
102
+ * 启动 worker(或复用已启动的)。返回 { request(wavPath) }。
103
+ * 协议见 lib/asr/asr-worker.cjs;这里只做进程管理与超时。
104
+ */
105
+ export function startWorker(root) {
106
+ const { nodeExe, worker } = workerPaths(root);
107
+ if (!existsSync(nodeExe)) throw new Error('缺少 runtime/node.exe');
108
+ if (!existsSync(worker)) throw new Error('缺少 runtime/asr-worker.cjs');
109
+ const child = spawn(nodeExe, [worker, '--model-dir', root], { windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
110
+ const pending = new Map();
111
+ let seq = 0;
112
+ let buffer = '';
113
+ let ready = false;
114
+
115
+ child.stdout.setEncoding('utf8');
116
+ child.stdout.on('data', (chunk) => {
117
+ buffer += chunk;
118
+ for (;;) {
119
+ const cut = buffer.indexOf('\n');
120
+ if (cut < 0) break;
121
+ const line = buffer.slice(0, cut).trim();
122
+ buffer = buffer.slice(cut + 1);
123
+ if (!line) continue;
124
+ let msg = null;
125
+ try { msg = JSON.parse(line); } catch { continue; }
126
+ if (msg && msg.ready) { ready = true; continue; }
127
+ const key = msg && msg.id !== undefined ? String(msg.id) : '';
128
+ if (key && pending.has(key)) {
129
+ const { resolve, timer } = pending.get(key);
130
+ clearTimeout(timer);
131
+ pending.delete(key);
132
+ resolve(msg);
133
+ }
134
+ }
135
+ });
136
+ child.on('error', (error) => { lastError = String((error && error.message) || error); });
137
+ child.stderr.setEncoding('utf8');
138
+ let lastError = '';
139
+ child.stderr.on('data', (chunk) => { lastError = (lastError + chunk).slice(-2000); });
140
+
141
+ const request = (wavPath, timeoutMs = 30000) => new Promise((resolve, reject) => {
142
+ const id = String(++seq);
143
+ const timer = setTimeout(() => {
144
+ pending.delete(id);
145
+ reject(new Error('识别超时'));
146
+ }, timeoutMs);
147
+ pending.set(id, { resolve, timer });
148
+ child.stdin.write(JSON.stringify({ id, wavPath }) + '\n', (err) => {
149
+ if (err) {
150
+ clearTimeout(timer);
151
+ pending.delete(id);
152
+ reject(err);
153
+ }
154
+ });
155
+ });
156
+
157
+ return {
158
+ isReady: () => ready,
159
+ lastError: () => lastError,
160
+ request,
161
+ stop: () => {
162
+ try { child.stdin.end(); } catch { /* ignore */ }
163
+ try { if (child && child.pid) child.kill(); } catch { /* ignore */ }
164
+ },
165
+ };
166
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * asr-worker.cjs — 本地 STT 子进程入口(普通 node.exe 运行,**不能**在 Electron 里跑)
3
+ *
4
+ * 为什么独立进程:与 tts-worker.cjs 同一原因 —— sherpa-onnx 的 native 扩展会创建 V8
5
+ * external buffer,Electron 进程里直接抛 `External buffers are not allowed`。
6
+ *
7
+ * 协议(stdin/stdout 各一行一条 JSON,stdout 只写协议、日志走 stderr):
8
+ * 请求:{ "id": "1", "wavPath": "C:\\...\\in.wav" }
9
+ * 成功:{ "id": "1", "ok": true, "text": "你好", "ms": 420 }
10
+ * 失败:{ "id": "1", "ok": false, "error": "原因" }
11
+ * 就绪:{ "ready": true, "model": "sensevoice", "sampleRate": 16000 }
12
+ *
13
+ * 用法:node asr-worker.cjs --model-dir <dir>
14
+ * <dir> 里要有:runtime/sherpa-onnx-node/、runtime/sherpa-onnx-win-x64/、models/sensevoice/
15
+ * models/sensevoice/ 需要 model.int8.onnx(或 model.onnx)+ tokens.txt
16
+ */
17
+ 'use strict';
18
+
19
+ const path = require('node:path');
20
+ const fs = require('node:fs');
21
+ const os = require('node:os');
22
+ const readline = require('node:readline');
23
+
24
+ function arg(name, dflt) {
25
+ const i = process.argv.indexOf('--' + name);
26
+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : dflt;
27
+ }
28
+
29
+ const root = arg('model-dir', '');
30
+ if (!root) {
31
+ process.stderr.write('[asr-worker] 缺少 --model-dir\n');
32
+ process.exit(2);
33
+ }
34
+
35
+ const modelDir = path.join(root, 'models', 'sensevoice');
36
+ const sherpaDir = path.join(root, 'runtime', 'sherpa-onnx-node');
37
+ const sherpaNative = path.join(root, 'runtime', 'sherpa-onnx-win-x64');
38
+
39
+ const modelFile = fs.existsSync(path.join(modelDir, 'model.int8.onnx'))
40
+ ? path.join(modelDir, 'model.int8.onnx')
41
+ : path.join(modelDir, 'model.onnx');
42
+ const tokensFile = path.join(modelDir, 'tokens.txt');
43
+
44
+ for (const p of [modelFile, tokensFile, sherpaDir]) {
45
+ if (!fs.existsSync(p)) {
46
+ process.stderr.write('[asr-worker] 缺少文件:' + p + '\n');
47
+ process.exit(3);
48
+ }
49
+ }
50
+
51
+ // native 扩展按模块名解析同目录的 sherpa-onnx-win-x64
52
+ process.env.PATH = sherpaNative + ';' + process.env.PATH;
53
+ process.env.NODE_PATH = root;
54
+
55
+ let OfflineRecognizer;
56
+ try {
57
+ ({ OfflineRecognizer } = require(path.join(sherpaDir, 'non-streaming-asr.js')));
58
+ } catch (e) {
59
+ process.stderr.write('[asr-worker] 加载 sherpa 失败:' + e.message + '\n');
60
+ process.exit(4);
61
+ }
62
+
63
+ const numThreads = Math.max(1, Math.min(4, (os.cpus().length || 2) - 1));
64
+ let recognizer;
65
+ try {
66
+ recognizer = new OfflineRecognizer({
67
+ featConfig: { sampleRate: 16000, featureDim: 80 },
68
+ modelConfig: {
69
+ senseVoice: {
70
+ model: modelFile,
71
+ language: 'zh',
72
+ useInverseTextNormalization: 1,
73
+ },
74
+ tokens: tokensFile,
75
+ numThreads,
76
+ debug: 0,
77
+ provider: 'cpu',
78
+ },
79
+ });
80
+ } catch (e) {
81
+ process.stderr.write('[asr-worker] 初始化模型失败:' + e.message + '\n');
82
+ process.exit(5);
83
+ }
84
+
85
+ /**
86
+ * 读 16-bit PCM WAV → Float32Array(-1..1)。
87
+ * 只认 ffmpeg 产出的形态(PCM s16le、单声道);多声道取第一声道。
88
+ */
89
+ function readWav(file) {
90
+ const buf = fs.readFileSync(file);
91
+ if (buf.length < 44 || buf.toString('ascii', 0, 4) !== 'RIFF') throw new Error('不是 WAV 文件');
92
+ let pos = 12;
93
+ let fmt = null;
94
+ let data = null;
95
+ while (pos + 8 <= buf.length) {
96
+ const id = buf.toString('ascii', pos, pos + 4);
97
+ const size = buf.readUInt32LE(pos + 4);
98
+ const body = pos + 8;
99
+ if (id === 'fmt ') {
100
+ fmt = {
101
+ channels: buf.readUInt16LE(body + 2),
102
+ sampleRate: buf.readUInt32LE(body + 4),
103
+ bits: buf.readUInt16LE(body + 14),
104
+ };
105
+ } else if (id === 'data') {
106
+ data = buf.subarray(body, Math.min(body + size, buf.length));
107
+ }
108
+ pos = body + size + (size % 2);
109
+ }
110
+ if (!fmt || !data) throw new Error('WAV 缺少 fmt/data 段');
111
+ if (fmt.bits !== 16) throw new Error('只支持 16-bit PCM,收到 ' + fmt.bits + ' bit');
112
+ const frames = Math.floor(data.length / (2 * fmt.channels));
113
+ const out = new Float32Array(frames);
114
+ for (let i = 0; i < frames; i += 1) {
115
+ out[i] = data.readInt16LE(i * 2 * fmt.channels) / 32768;
116
+ }
117
+ return { samples: out, sampleRate: fmt.sampleRate };
118
+ }
119
+
120
+ /** 采样率不是 16k 时做一次线性重采样(ffmpeg 一般已给 16k,这里兜底)。 */
121
+ function resample16k(samples, sampleRate) {
122
+ if (!sampleRate || sampleRate === 16000) return samples;
123
+ const ratio = 16000 / sampleRate;
124
+ const length = Math.max(1, Math.floor(samples.length * ratio));
125
+ const out = new Float32Array(length);
126
+ for (let i = 0; i < length; i += 1) {
127
+ const src = i / ratio;
128
+ const i0 = Math.floor(src);
129
+ const i1 = Math.min(samples.length - 1, i0 + 1);
130
+ const t = src - i0;
131
+ out[i] = samples[i0] * (1 - t) + samples[i1] * t;
132
+ }
133
+ return out;
134
+ }
135
+
136
+ function transcribe(wavPath) {
137
+ const started = Date.now();
138
+ const { samples, sampleRate } = readWav(wavPath);
139
+ if (!samples.length) return { ok: true, text: '', ms: 0 };
140
+ const stream = recognizer.createStream();
141
+ stream.acceptWaveform({ samples: resample16k(samples, sampleRate), sampleRate: 16000 });
142
+ recognizer.decode(stream);
143
+ const result = recognizer.getResult(stream);
144
+ const text = String((result && result.text) || '').trim();
145
+ return { ok: true, text, ms: Date.now() - started };
146
+ }
147
+
148
+ const rl = readline.createInterface({ input: process.stdin });
149
+ rl.on('line', (line) => {
150
+ const raw = String(line || '').trim();
151
+ if (!raw) return;
152
+ let req;
153
+ try {
154
+ req = JSON.parse(raw);
155
+ } catch {
156
+ process.stdout.write(JSON.stringify({ ok: false, error: 'bad-json' }) + '\n');
157
+ return;
158
+ }
159
+ const id = req && req.id !== undefined ? req.id : null;
160
+ try {
161
+ if (!req || typeof req.wavPath !== 'string') throw new Error('缺少 wavPath');
162
+ const result = transcribe(req.wavPath);
163
+ process.stdout.write(JSON.stringify({ id, ...result }) + '\n');
164
+ } catch (e) {
165
+ process.stdout.write(JSON.stringify({ id, ok: false, error: String((e && e.message) || e) }) + '\n');
166
+ }
167
+ });
168
+
169
+ process.stdout.write(JSON.stringify({ ready: true, model: 'sensevoice', sampleRate: 16000 }) + '\n');
package/lib/boot/index.js CHANGED
@@ -23,6 +23,14 @@ export function bootDir() {
23
23
  try { if (!existsSync(d)) mkdirSync(d, { recursive: true }); } catch { /* 只读盘:后续写入会失败并如实报错 */ }
24
24
  return d;
25
25
  }
26
+ /** 第一幕图片(本地文件;存在且 act1.image=true 时注入脚本才用它)。 */
27
+ export function act1ImagePath() {
28
+ return join(bootDir(), 'act1-image.png');
29
+ }
30
+ export function act1ImageExists() {
31
+ try { return existsSync(act1ImagePath()) && statSync(act1ImagePath()).size > 0; } catch { return false; }
32
+ }
33
+
26
34
  export function bootConfigPath() {
27
35
  return join(bootHome(), 'config.json');
28
36
  }
@@ -43,9 +51,29 @@ function readConfig() {
43
51
  export function readBoot() {
44
52
  const cfg = readConfig();
45
53
  const raw = cfg && typeof cfg.boot === 'object' && cfg.boot ? cfg.boot : {};
54
+ // 素材池:items 是 id 数组;旧配置只有 clipId ⇒ 自动包成单条池(向后兼容)
55
+ const rawItems = Array.isArray(raw.items) ? raw.items.filter((x) => typeof x === 'string' && x) : [];
56
+ const legacyId = typeof raw.clipId === 'string' ? raw.clipId : '';
57
+ const items = rawItems.length ? rawItems : (legacyId ? [legacyId] : []);
46
58
  return {
47
59
  enabled: raw.enabled === true,
48
- clipId: typeof raw.clipId === 'string' ? raw.clipId : '',
60
+ clipId: legacyId || (items[0] || ''),
61
+ items,
62
+ // 素材池取片方式:first=固定第一条;random=随机;rotate=按启动次数轮换
63
+ poolMode: ['first', 'random', 'rotate'].includes(String(raw.poolMode)) ? String(raw.poolMode) : 'first',
64
+ // 退场转场:fade(默认,只透明度)/ scale(轻微放大)/ slide(上滑)
65
+ transition: ['fade', 'scale', 'slide'].includes(String(raw.transition)) ? String(raw.transition) : 'fade',
66
+ // 两幕冷启动:第一幕是纯色 + 一行字(固定标识),第二幕才是素材
67
+ act1: (() => {
68
+ const a = raw.act1 && typeof raw.act1 === 'object' ? raw.act1 : {};
69
+ return {
70
+ enabled: a.enabled === true,
71
+ text: typeof a.text === 'string' ? a.text.slice(0, 60) : '',
72
+ durationMs: Number.isFinite(Number(a.durationMs)) ? Math.min(5000, Math.max(300, Number(a.durationMs))) : 1200,
73
+ // 有图片且开启时,第一幕用图(图存在 boot 目录,由 /boot/act1-image 提供)
74
+ image: a.image === true,
75
+ };
76
+ })(),
49
77
  // 进入方式:tail = 播完再进(默认);ready = 应用就绪就进;click = 点一下才进。
50
78
  // 之前没有这个字段,一律「就绪即进」,于是 8~15 秒的片子 1.2 秒就被掐掉。
51
79
  enterMode: ['tail', 'ready', 'click'].includes(String(raw.enterMode)) ? String(raw.enterMode) : 'tail',
@@ -63,7 +91,19 @@ export function readBoot() {
63
91
  export function writeBoot(patch) {
64
92
  const cfg = readConfig();
65
93
  const cur = cfg && typeof cfg.boot === 'object' && cfg.boot ? cfg.boot : {};
66
- cfg.boot = { ...cur, ...patch };
94
+ const next = { ...cur, ...patch };
95
+ // items 与 clipId 保持一致:写 items 时把 clipId 定成第一条(旧读路径仍能工作)
96
+ if (Array.isArray(next.items)) {
97
+ next.items = next.items.filter((x) => typeof x === 'string' && x);
98
+ // ⚠️ 只有「没显式给 clipId」时才用 items[0] 兜底。
99
+ // 真实事故:select 传了 clipId+items,被这里强制改成 items[0] ⇒ 点「使用」切不过去。
100
+ const explicit = Object.prototype.hasOwnProperty.call(patch, 'clipId') && typeof patch.clipId === 'string' && patch.clipId;
101
+ if (next.items.length) { if (!explicit || !next.items.includes(explicit)) next.clipId = next.items[0]; }
102
+ else if (typeof next.clipId === 'string' && next.clipId) next.items = [next.clipId];
103
+ } else if (typeof next.clipId === 'string' && next.clipId) {
104
+ next.items = [next.clipId];
105
+ }
106
+ cfg.boot = next;
67
107
  writeFileSync(bootConfigPath(), JSON.stringify(cfg, null, 2) + '\n');
68
108
  return readBoot();
69
109
  }
@@ -156,7 +196,11 @@ export function listLocalClips() {
156
196
  let meta = {};
157
197
  try { meta = JSON.parse(readFileSync(join(dir, stem + '.json'), 'utf8')) || {}; } catch { /* 没 meta 也能用 */ }
158
198
  const id = String(meta.id || stem);
159
- out.push({ id, bytes, title: meta.title || id, durationSec: meta.durationSec || null });
199
+ out.push({
200
+ id, bytes, title: meta.title || id, durationSec: meta.durationSec || null,
201
+ // 来源:站点下载的 meta 里有 url/sha256;本地导入的 meta.source='local'
202
+ source: meta.source === 'local' ? 'local' : 'site',
203
+ });
160
204
  }
161
205
  return out;
162
206
  }
@@ -187,7 +231,14 @@ export const BOOT_SCREEN_SOURCE = String.raw`
187
231
  function teardown() {
188
232
  if (done) return;
189
233
  done = true;
190
- try { if (root) root.style.opacity = "0"; } catch (e) {}
234
+ // 退场转场:CSS transition 已在 root 上声明;这里只改目标样式
235
+ try {
236
+ if (root) {
237
+ root.style.opacity = "0";
238
+ if (cfg.transition === "scale") root.style.transform = "scale(1.06)";
239
+ else if (cfg.transition === "slide") root.style.transform = "translateY(-8%)";
240
+ }
241
+ } catch (e) {}
191
242
  setTimeout(function () {
192
243
  try { if (video) { video.pause(); video.removeAttribute("src"); video.load && video.load(); } } catch (e) {}
193
244
  try { if (root && root.parentNode) root.parentNode.removeChild(root); } catch (e) {}
@@ -200,7 +251,7 @@ export const BOOT_SCREEN_SOURCE = String.raw`
200
251
  root.setAttribute("style",
201
252
  "position:fixed;inset:0;z-index:2147483647;background:#000;" +
202
253
  "display:flex;align-items:center;justify-content:center;" +
203
- "transition:opacity " + (cfg.fadeMs || 900) + "ms ease;opacity:1;");
254
+ "transition:opacity " + (cfg.fadeMs || 900) + "ms ease,transform " + (cfg.fadeMs || 900) + "ms ease;opacity:1;transform:none;");
204
255
  video = doc.createElement("video");
205
256
  video.setAttribute("muted", "");
206
257
  video.muted = true;
@@ -212,6 +263,26 @@ export const BOOT_SCREEN_SOURCE = String.raw`
212
263
  video.addEventListener("error", teardown, { once: true });
213
264
  root.appendChild(video);
214
265
  (doc.body || doc.documentElement).appendChild(root);
266
+ // 两幕冷启动:第一幕是纯色 + 一行字,盖在素材上;到时淡出露出第二幕
267
+ try {
268
+ if (cfg.act1 && cfg.act1.enabled) {
269
+ var act1 = doc.createElement("div");
270
+ act1.setAttribute("style",
271
+ "position:absolute;inset:0;background:#000;display:flex;align-items:center;justify-content:center;" +
272
+ "color:#fff;font-size:28px;letter-spacing:2px;transition:opacity 500ms ease;opacity:1;");
273
+ if (cfg.act1.imageUrl) {
274
+ act1.style.backgroundImage = "url(" + cfg.act1.imageUrl + ")";
275
+ act1.style.backgroundSize = "cover";
276
+ act1.style.backgroundPosition = "center";
277
+ }
278
+ act1.textContent = cfg.act1.text || "";
279
+ root.appendChild(act1);
280
+ setTimeout(function () {
281
+ try { act1.style.opacity = "0"; } catch (e) {}
282
+ setTimeout(function () { try { if (act1.parentNode) act1.parentNode.removeChild(act1); } catch (e) {} }, 520);
283
+ }, Math.max(300, (cfg.act1.durationMs || 1200)));
284
+ }
285
+ } catch (e) {}
215
286
  // 声音:只有用户显式开启才带声;否则静音(否则 Chromium 直接拒绝自动播放)。
216
287
  try {
217
288
  if (cfg.sound) { video.muted = false; video.volume = (typeof cfg.volume === "number" ? cfg.volume : 1); }
@@ -271,6 +342,61 @@ export const BOOT_SCREEN_SOURCE = String.raw`
271
342
  })();
272
343
  `;
273
344
 
345
+ /** 素材池状态文件(轮换计数;与 config.json 分开,避免每次启动都改配置)。 */
346
+ function poolStatePath() { return join(bootHome(), 'boot-pool.json'); }
347
+ function readPoolState() {
348
+ try { return JSON.parse(readFileSync(poolStatePath(), 'utf8')) || {}; } catch { return {}; }
349
+ }
350
+ function writePoolState(next) {
351
+ try { writeFileSync(poolStatePath(), JSON.stringify(next, null, 2) + '\n'); } catch { /* 只读盘:轮换退化成固定第一条 */ }
352
+ }
353
+
354
+ /**
355
+ * 按 poolMode 从素材池里挑一条;只挑**本地真的存在**的(缺文件不能注入,否则黑屏)。
356
+ * return null ⇒ 一条可用的都没有,调用方直接不注入。
357
+ */
358
+ export function pickClipForBoot(boot) {
359
+ const items = Array.isArray(boot && boot.items) ? boot.items.filter((id) => id && clipExists(id)) : [];
360
+ if (!items.length) return null;
361
+ const mode = (boot && boot.poolMode) || 'first';
362
+ if (mode === 'random') return items[Math.floor(Math.random() * items.length)];
363
+ if (mode === 'rotate') {
364
+ const state = readPoolState();
365
+ const next = (Number(state.index) || 0) % items.length;
366
+ writePoolState({ index: next + 1 });
367
+ return items[next];
368
+ }
369
+ return items[0];
370
+ }
371
+
372
+ /**
373
+ * 导入一条本地动画(mp4/webm)。只写 `$DSH_HOME/boot/`,不碰站点、不联网。
374
+ * 校验:文件头必须像视频(ftyp/EBML)、大小 ≤ CLIP_MAX_BYTES、目录固定。
375
+ * @returns {{ok:true,id:string,bytes:number}|{ok:false,error:string}}
376
+ */
377
+ export function importLocalClip(buffer, options = {}) {
378
+ const max = Number(options.maxBytes) || 64 * 1024 * 1024;
379
+ if (!buffer || !buffer.length) return { ok: false, error: 'empty' };
380
+ if (buffer.length > max) return { ok: false, error: 'too-large' };
381
+ const head = buffer.subarray(0, 12);
382
+ const isMp4 = head.length >= 8 && head.toString('latin1', 4, 8) === 'ftyp';
383
+ const isWebm = head.length >= 4 && head[0] === 0x1a && head[1] === 0x45 && head[2] === 0xdf && head[3] === 0xa3;
384
+ if (!isMp4 && !isWebm) return { ok: false, error: 'not-a-video' };
385
+ const title = String(options.title || '').trim() || '本地导入';
386
+ const id = 'local-' + createHash('sha256').update(buffer).digest('hex').slice(0, 12);
387
+ const dest = clipFile(id);
388
+ try {
389
+ writeFileSync(dest, buffer);
390
+ writeFileSync(clipMetaFile(id), JSON.stringify({
391
+ id, title, source: 'local', bytes: buffer.length,
392
+ mime: isMp4 ? 'video/mp4' : 'video/webm', importedAt: Date.now(),
393
+ }, null, 2) + '\n');
394
+ } catch (error) {
395
+ try { rmSync(dest, { force: true }); } catch { /* ignore */ }
396
+ return { ok: false, error: String((error && error.message) || error) };
397
+ }
398
+ return { ok: true, id, bytes: buffer.length, title };
399
+ }
274
400
  /**
275
401
  * 装注入。**订阅在 apply() 里做一次**,每次 index 渲染时按当前配置决定注不注。
276
402
  *
@@ -286,15 +412,21 @@ export function installBootInjection(ctx, note) {
286
412
  if (!Array.isArray(table)) return;
287
413
  const boot = readBoot();
288
414
  // 关 = 一行都不注入(不是"注入了再自己退出")。
289
- if (!boot.enabled || !boot.clipId) return;
290
- if (!clipExists(boot.clipId)) return; // 片段被删了:静默不注入,别让用户卡黑屏
415
+ if (!boot.enabled) return;
416
+ // 素材池取片:按 poolMode 从 items 里挑一条本地真的存在的;一条都没有就不注入。
417
+ const picked = pickClipForBoot(boot);
418
+ if (!picked) return; // 片段被删了:静默不注入,别让用户卡黑屏
291
419
  const cfg = {
292
- clip: '/folia/boot/clip?v=' + encodeURIComponent(boot.clipId),
420
+ clip: '/folia/boot/clip?v=' + encodeURIComponent(picked),
293
421
  fadeMs: boot.fadeMs,
294
422
  minShowMs: boot.minShowMs,
295
423
  maxHoldMs: boot.maxHoldMs,
296
424
  enterMode: boot.enterMode,
297
425
  sound: boot.sound,
426
+ transition: boot.transition,
427
+ act1: (boot.act1 && boot.act1.image && act1ImageExists())
428
+ ? { ...boot.act1, imageUrl: '/folia/boot/act1-image?v=' + Date.now() }
429
+ : boot.act1,
298
430
  volume: boot.volume,
299
431
  };
300
432
  table.push({ kind: 'script', placement: 'head', text: 'globalThis.__FOLIA_BOOT__=' + JSON.stringify(cfg) });