dsh-folia 4.26.0-pre.3 → 4.26.0-pre.30
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/asr/asr-local.js +166 -0
- package/lib/asr/asr-worker.cjs +169 -0
- package/lib/boot/index.js +83 -6
- package/lib/client.js +919 -782
- package/lib/index.js +5 -3
- package/lib/pet-chat-proactive.js +112 -112
- package/lib/route-registry.js +1 -1
- package/lib/routes/boot.js +39 -6
- package/lib/routes/pet-chat.js +1375 -800
- package/lib/settings-schema.js +2161 -2171
- package/lib/tts/tts-worker.cjs +129 -0
- package/lib/voice/record.js +230 -0
- package/package.json +5 -2
- 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
|
@@ -43,9 +43,16 @@ function readConfig() {
|
|
|
43
43
|
export function readBoot() {
|
|
44
44
|
const cfg = readConfig();
|
|
45
45
|
const raw = cfg && typeof cfg.boot === 'object' && cfg.boot ? cfg.boot : {};
|
|
46
|
+
// 素材池:items 是 id 数组;旧配置只有 clipId ⇒ 自动包成单条池(向后兼容)
|
|
47
|
+
const rawItems = Array.isArray(raw.items) ? raw.items.filter((x) => typeof x === 'string' && x) : [];
|
|
48
|
+
const legacyId = typeof raw.clipId === 'string' ? raw.clipId : '';
|
|
49
|
+
const items = rawItems.length ? rawItems : (legacyId ? [legacyId] : []);
|
|
46
50
|
return {
|
|
47
51
|
enabled: raw.enabled === true,
|
|
48
|
-
clipId:
|
|
52
|
+
clipId: legacyId || (items[0] || ''),
|
|
53
|
+
items,
|
|
54
|
+
// 素材池取片方式:first=固定第一条;random=随机;rotate=按启动次数轮换
|
|
55
|
+
poolMode: ['first', 'random', 'rotate'].includes(String(raw.poolMode)) ? String(raw.poolMode) : 'first',
|
|
49
56
|
// 进入方式:tail = 播完再进(默认);ready = 应用就绪就进;click = 点一下才进。
|
|
50
57
|
// 之前没有这个字段,一律「就绪即进」,于是 8~15 秒的片子 1.2 秒就被掐掉。
|
|
51
58
|
enterMode: ['tail', 'ready', 'click'].includes(String(raw.enterMode)) ? String(raw.enterMode) : 'tail',
|
|
@@ -63,7 +70,16 @@ export function readBoot() {
|
|
|
63
70
|
export function writeBoot(patch) {
|
|
64
71
|
const cfg = readConfig();
|
|
65
72
|
const cur = cfg && typeof cfg.boot === 'object' && cfg.boot ? cfg.boot : {};
|
|
66
|
-
|
|
73
|
+
const next = { ...cur, ...patch };
|
|
74
|
+
// items 与 clipId 保持一致:写 items 时把 clipId 定成第一条(旧读路径仍能工作)
|
|
75
|
+
if (Array.isArray(next.items)) {
|
|
76
|
+
next.items = next.items.filter((x) => typeof x === 'string' && x);
|
|
77
|
+
if (next.items.length) next.clipId = next.items[0];
|
|
78
|
+
else if (typeof next.clipId === 'string' && next.clipId) next.items = [next.clipId];
|
|
79
|
+
} else if (typeof next.clipId === 'string' && next.clipId) {
|
|
80
|
+
next.items = [next.clipId];
|
|
81
|
+
}
|
|
82
|
+
cfg.boot = next;
|
|
67
83
|
writeFileSync(bootConfigPath(), JSON.stringify(cfg, null, 2) + '\n');
|
|
68
84
|
return readBoot();
|
|
69
85
|
}
|
|
@@ -156,7 +172,11 @@ export function listLocalClips() {
|
|
|
156
172
|
let meta = {};
|
|
157
173
|
try { meta = JSON.parse(readFileSync(join(dir, stem + '.json'), 'utf8')) || {}; } catch { /* 没 meta 也能用 */ }
|
|
158
174
|
const id = String(meta.id || stem);
|
|
159
|
-
out.push({
|
|
175
|
+
out.push({
|
|
176
|
+
id, bytes, title: meta.title || id, durationSec: meta.durationSec || null,
|
|
177
|
+
// 来源:站点下载的 meta 里有 url/sha256;本地导入的 meta.source='local'
|
|
178
|
+
source: meta.source === 'local' ? 'local' : 'site',
|
|
179
|
+
});
|
|
160
180
|
}
|
|
161
181
|
return out;
|
|
162
182
|
}
|
|
@@ -271,6 +291,61 @@ export const BOOT_SCREEN_SOURCE = String.raw`
|
|
|
271
291
|
})();
|
|
272
292
|
`;
|
|
273
293
|
|
|
294
|
+
/** 素材池状态文件(轮换计数;与 config.json 分开,避免每次启动都改配置)。 */
|
|
295
|
+
function poolStatePath() { return join(bootHome(), 'boot-pool.json'); }
|
|
296
|
+
function readPoolState() {
|
|
297
|
+
try { return JSON.parse(readFileSync(poolStatePath(), 'utf8')) || {}; } catch { return {}; }
|
|
298
|
+
}
|
|
299
|
+
function writePoolState(next) {
|
|
300
|
+
try { writeFileSync(poolStatePath(), JSON.stringify(next, null, 2) + '\n'); } catch { /* 只读盘:轮换退化成固定第一条 */ }
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* 按 poolMode 从素材池里挑一条;只挑**本地真的存在**的(缺文件不能注入,否则黑屏)。
|
|
305
|
+
* return null ⇒ 一条可用的都没有,调用方直接不注入。
|
|
306
|
+
*/
|
|
307
|
+
export function pickClipForBoot(boot) {
|
|
308
|
+
const items = Array.isArray(boot && boot.items) ? boot.items.filter((id) => id && clipExists(id)) : [];
|
|
309
|
+
if (!items.length) return null;
|
|
310
|
+
const mode = (boot && boot.poolMode) || 'first';
|
|
311
|
+
if (mode === 'random') return items[Math.floor(Math.random() * items.length)];
|
|
312
|
+
if (mode === 'rotate') {
|
|
313
|
+
const state = readPoolState();
|
|
314
|
+
const next = (Number(state.index) || 0) % items.length;
|
|
315
|
+
writePoolState({ index: next + 1 });
|
|
316
|
+
return items[next];
|
|
317
|
+
}
|
|
318
|
+
return items[0];
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* 导入一条本地动画(mp4/webm)。只写 `$DSH_HOME/boot/`,不碰站点、不联网。
|
|
323
|
+
* 校验:文件头必须像视频(ftyp/EBML)、大小 ≤ CLIP_MAX_BYTES、目录固定。
|
|
324
|
+
* @returns {{ok:true,id:string,bytes:number}|{ok:false,error:string}}
|
|
325
|
+
*/
|
|
326
|
+
export function importLocalClip(buffer, options = {}) {
|
|
327
|
+
const max = Number(options.maxBytes) || 64 * 1024 * 1024;
|
|
328
|
+
if (!buffer || !buffer.length) return { ok: false, error: 'empty' };
|
|
329
|
+
if (buffer.length > max) return { ok: false, error: 'too-large' };
|
|
330
|
+
const head = buffer.subarray(0, 12);
|
|
331
|
+
const isMp4 = head.length >= 8 && head.toString('latin1', 4, 8) === 'ftyp';
|
|
332
|
+
const isWebm = head.length >= 4 && head[0] === 0x1a && head[1] === 0x45 && head[2] === 0xdf && head[3] === 0xa3;
|
|
333
|
+
if (!isMp4 && !isWebm) return { ok: false, error: 'not-a-video' };
|
|
334
|
+
const title = String(options.title || '').trim() || '本地导入';
|
|
335
|
+
const id = 'local-' + createHash('sha256').update(buffer).digest('hex').slice(0, 12);
|
|
336
|
+
const dest = clipFile(id);
|
|
337
|
+
try {
|
|
338
|
+
writeFileSync(dest, buffer);
|
|
339
|
+
writeFileSync(clipMetaFile(id), JSON.stringify({
|
|
340
|
+
id, title, source: 'local', bytes: buffer.length,
|
|
341
|
+
mime: isMp4 ? 'video/mp4' : 'video/webm', importedAt: Date.now(),
|
|
342
|
+
}, null, 2) + '\n');
|
|
343
|
+
} catch (error) {
|
|
344
|
+
try { rmSync(dest, { force: true }); } catch { /* ignore */ }
|
|
345
|
+
return { ok: false, error: String((error && error.message) || error) };
|
|
346
|
+
}
|
|
347
|
+
return { ok: true, id, bytes: buffer.length, title };
|
|
348
|
+
}
|
|
274
349
|
/**
|
|
275
350
|
* 装注入。**订阅在 apply() 里做一次**,每次 index 渲染时按当前配置决定注不注。
|
|
276
351
|
*
|
|
@@ -286,10 +361,12 @@ export function installBootInjection(ctx, note) {
|
|
|
286
361
|
if (!Array.isArray(table)) return;
|
|
287
362
|
const boot = readBoot();
|
|
288
363
|
// 关 = 一行都不注入(不是"注入了再自己退出")。
|
|
289
|
-
if (!boot.enabled
|
|
290
|
-
|
|
364
|
+
if (!boot.enabled) return;
|
|
365
|
+
// 素材池取片:按 poolMode 从 items 里挑一条本地真的存在的;一条都没有就不注入。
|
|
366
|
+
const picked = pickClipForBoot(boot);
|
|
367
|
+
if (!picked) return; // 片段被删了:静默不注入,别让用户卡黑屏
|
|
291
368
|
const cfg = {
|
|
292
|
-
clip: '/folia/boot/clip?v=' + encodeURIComponent(
|
|
369
|
+
clip: '/folia/boot/clip?v=' + encodeURIComponent(picked),
|
|
293
370
|
fadeMs: boot.fadeMs,
|
|
294
371
|
minShowMs: boot.minShowMs,
|
|
295
372
|
maxHoldMs: boot.maxHoldMs,
|