dsh-game-material-master 0.7.0 → 0.9.0

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/sfxgen.js ADDED
@@ -0,0 +1,819 @@
1
+ /**
2
+ * 音效生成(模块八)的数据层与作业。
3
+ *
4
+ * ## 落盘
5
+ *
6
+ * ```
7
+ * <DSH_HOME>/game-material-master/sfx-jobs/<f…>/
8
+ * ├── job.json
9
+ * ├── refs/ 参考图(1 张)/ 参考音频(≤3 条)
10
+ * ├── takes/ 每次生成的音频(一次请求 = 一条,永不覆盖)
11
+ * └── out/ 导出
12
+ * ```
13
+ *
14
+ * ## 与音乐模块的区别
15
+ *
16
+ * 火山引擎的 `seed-audio-1.0` 是**同步接口**:一次 POST 直接返回整段音频,
17
+ * 没有 taskId、没有轮询。这里仍然用后台任务表承载,是为了不阻塞网关调用,
18
+ * 也让 `game_material_wait` / 界面的「生成中」状态有统一落点。
19
+ *
20
+ * 所有写 `job.json` 的地方都走 `patchSfxJob()` 的**按任务串行队列**:界面保存
21
+ * 提示词、后台任务收尾、上传参考同时发生时,后写的不会覆盖前一次改动。
22
+ */
23
+ import { copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
24
+ import { existsSync } from "node:fs";
25
+ import { basename, join, resolve, sep } from "node:path";
26
+ import { randomUUID } from "node:crypto";
27
+ import { loadConfig, sfxJobsRoot } from "./config.js";
28
+ import { appendJobLog, messageOf, readJson, sweepTempFiles, writeJsonAtomic } from "./jsonio.js";
29
+ import { SFX_LIMITS, buildSfxBody, generateSfx, normalizeSfxSettings, sfxBlocker } from "./sfxapi.js";
30
+ import { probeAudio } from "./musicaudio.js";
31
+ import { sniffBinary } from "./musicapi.js";
32
+ import { sniffImage } from "./imagegen.js";
33
+ import { zipEntries } from "./zip.js";
34
+ import { assetBasePath, originForLinks } from "./links.js";
35
+ export const SFX_STAGES = ["generate", "export"];
36
+ const JOB_ID_PATTERN = /^f[a-z0-9]{4,40}$/;
37
+ /** 音效任务可经资源路由读取的子目录(唯一真源,`index.ts` 直接引用)。 */
38
+ export const SERVABLE_SFX_DIRS = new Set(["refs", "takes", "out"]);
39
+ export function sfxJobDir(id) {
40
+ return join(sfxJobsRoot(), id);
41
+ }
42
+ export function sfxJobFile(id) {
43
+ return join(sfxJobDir(id), "job.json");
44
+ }
45
+ /** 任务内相对路径 → 绝对路径,并挡住目录穿越。 */
46
+ export function sfxAssetPath(id, relative) {
47
+ const base = resolve(sfxJobDir(id));
48
+ const target = resolve(base, relative);
49
+ if (target !== base && !target.startsWith(base + sep))
50
+ throw new Error(`非法的任务内路径:${relative}`);
51
+ return target;
52
+ }
53
+ export function isValidSfxJobId(id) {
54
+ return JOB_ID_PATTERN.test(id);
55
+ }
56
+ function assertJobId(id) {
57
+ if (!isValidSfxJobId(id))
58
+ throw new Error(`非法音效任务 id:${id}`);
59
+ }
60
+ function now() {
61
+ return Date.now();
62
+ }
63
+ function logOf(job) {
64
+ if (!Array.isArray(job.log))
65
+ job.log = [];
66
+ return job.log;
67
+ }
68
+ export function sfxLog(job, level, message) {
69
+ appendJobLog(logOf(job), level, message);
70
+ }
71
+ function clampString(value, max = 20000) {
72
+ return typeof value === "string" ? value.slice(0, max) : "";
73
+ }
74
+ export function safeSfxStem(value) {
75
+ const base = basename(String(value ?? ""))
76
+ .replace(/[^\w.\-()\u4e00-\u9fa5]+/gu, "_")
77
+ .replace(/^[._]+/u, "");
78
+ return base === "" ? "sfx" : base.slice(0, 80);
79
+ }
80
+ function deriveSfxName(prompt) {
81
+ const flat = prompt.replace(/\s+/gu, " ").trim();
82
+ return flat === "" ? "未命名音效" : flat.slice(0, 24);
83
+ }
84
+ function defaultStages() {
85
+ return {
86
+ generate: { status: "idle", approved: false },
87
+ export: { status: "idle", approved: false }
88
+ };
89
+ }
90
+ function normalizeRefImage(raw) {
91
+ const entry = raw !== null && typeof raw === "object" ? raw : undefined;
92
+ if (entry === undefined || typeof entry.file !== "string" || entry.file === "")
93
+ return undefined;
94
+ return {
95
+ file: entry.file,
96
+ name: typeof entry.name === "string" ? entry.name : basename(entry.file),
97
+ bytes: Number.isFinite(Number(entry.bytes)) ? Number(entry.bytes) : 0,
98
+ ext: typeof entry.ext === "string" ? entry.ext : "png"
99
+ };
100
+ }
101
+ function normalizeRefAudio(raw) {
102
+ const entry = raw !== null && typeof raw === "object" ? raw : undefined;
103
+ if (entry === undefined || typeof entry.file !== "string" || entry.file === "")
104
+ return undefined;
105
+ return {
106
+ file: entry.file,
107
+ name: typeof entry.name === "string" ? entry.name : basename(entry.file),
108
+ bytes: Number.isFinite(Number(entry.bytes)) ? Number(entry.bytes) : 0,
109
+ ext: typeof entry.ext === "string" ? entry.ext : "wav",
110
+ ...(Number.isFinite(Number(entry.duration)) && Number(entry.duration) > 0 ? { duration: Number(entry.duration) } : {})
111
+ };
112
+ }
113
+ /** 读回来的老数据补齐数组与阶段字段,避免界面拿 undefined 当空。 */
114
+ function normalizeJob(raw, id) {
115
+ const config = raw ?? {};
116
+ const settings = (() => {
117
+ try {
118
+ return normalizeSfxSettings(config.settings);
119
+ }
120
+ catch {
121
+ return normalizeSfxSettings({});
122
+ }
123
+ })();
124
+ const stages = config.stages !== null && typeof config.stages === "object" ? config.stages : {};
125
+ return {
126
+ id,
127
+ name: clampString(config.name, 200) || "未命名音效",
128
+ createdAt: Number(config.createdAt) || now(),
129
+ updatedAt: Number(config.updatedAt) || Number(config.createdAt) || now(),
130
+ prompt: clampString(config.prompt, SFX_LIMITS.promptChars),
131
+ settings,
132
+ reviewMode: config.reviewMode === "manual" ? "manual" : config.reviewMode === "auto" ? "auto" : undefined,
133
+ refs: {
134
+ ...(normalizeRefImage(config.refs?.image) === undefined ? {} : { image: normalizeRefImage(config.refs?.image) }),
135
+ audios: Array.isArray(config.refs?.audios)
136
+ ? config.refs.audios.map(normalizeRefAudio).filter((entry) => entry !== undefined)
137
+ : []
138
+ },
139
+ status: ["idle", "running", "ready", "error"].includes(config.status) ? config.status : "idle",
140
+ ...(typeof config.error === "string" && config.error !== "" ? { error: config.error } : {}),
141
+ takes: Array.isArray(config.takes)
142
+ ? config.takes
143
+ .filter((take) => take !== null && typeof take === "object" && typeof take.file === "string" && take.file !== "")
144
+ .map((take) => ({
145
+ id: typeof take.id === "string" ? take.id : randomUUID().slice(0, 8),
146
+ file: take.file,
147
+ bytes: Number.isFinite(Number(take.bytes)) ? Number(take.bytes) : 0,
148
+ format: typeof take.format === "string" ? take.format : "wav",
149
+ ...(Number.isFinite(Number(take.duration)) && Number(take.duration) > 0 ? { duration: Number(take.duration) } : {}),
150
+ ...(Number.isFinite(Number(take.originalDuration)) && Number(take.originalDuration) > 0 ? { originalDuration: Number(take.originalDuration) } : {}),
151
+ prompt: clampString(take.prompt, SFX_LIMITS.promptChars),
152
+ settings: (() => {
153
+ try {
154
+ return normalizeSfxSettings(take.settings, settings);
155
+ }
156
+ catch {
157
+ return settings;
158
+ }
159
+ })(),
160
+ createdAt: Number(take.createdAt) || now(),
161
+ ...(typeof take.logId === "string" && take.logId !== "" ? { logId: take.logId } : {})
162
+ }))
163
+ : [],
164
+ stages: {
165
+ generate: normalizeStage(stages.generate),
166
+ export: normalizeStage(stages.export)
167
+ },
168
+ exports: Array.isArray(config.exports)
169
+ ? config.exports
170
+ .filter((entry) => entry !== null && typeof entry === "object" && typeof entry.file === "string")
171
+ .map((entry) => ({
172
+ id: typeof entry.id === "string" ? entry.id : randomUUID().slice(0, 8),
173
+ takeId: typeof entry.takeId === "string" ? entry.takeId : null,
174
+ file: entry.file,
175
+ bytes: Number.isFinite(Number(entry.bytes)) ? Number(entry.bytes) : 0,
176
+ format: typeof entry.format === "string" ? entry.format : "wav",
177
+ createdAt: Number(entry.createdAt) || now()
178
+ }))
179
+ : [],
180
+ log: Array.isArray(config.log) ? config.log.slice(-200) : []
181
+ };
182
+ }
183
+ function normalizeStage(raw) {
184
+ const entry = raw !== null && typeof raw === "object" ? raw : {};
185
+ return {
186
+ status: ["idle", "running", "done", "error"].includes(entry.status) ? entry.status : "idle",
187
+ approved: entry.approved === true,
188
+ ...(typeof entry.error === "string" && entry.error !== "" ? { error: entry.error } : {}),
189
+ ...(Number.isFinite(Number(entry.at)) ? { at: Number(entry.at) } : {})
190
+ };
191
+ }
192
+ export async function createSfxJob(input) {
193
+ const config = await loadConfig();
194
+ if (input.prompt.length > SFX_LIMITS.promptChars) {
195
+ throw new Error(`提示词太长:${input.prompt.length} 字符,上限 ${SFX_LIMITS.promptChars}`);
196
+ }
197
+ const prompt = clampString(input.prompt, SFX_LIMITS.promptChars).trim();
198
+ if (prompt === "")
199
+ throw new Error("提示词不能为空:先写清要什么声音");
200
+ const settings = normalizeSfxSettings(input.settings, {
201
+ format: config.sfxFormat,
202
+ sampleRate: config.sfxSampleRate
203
+ });
204
+ const id = `f${now().toString(36)}${randomUUID().slice(0, 6)}`;
205
+ const createdAt = now();
206
+ const job = {
207
+ id,
208
+ name: clampString(input.name, 200).trim() || deriveSfxName(prompt),
209
+ createdAt,
210
+ updatedAt: createdAt,
211
+ prompt,
212
+ settings,
213
+ ...(input.reviewMode === "manual" ? { reviewMode: "manual" } : input.reviewMode === "auto" ? { reviewMode: "auto" } : {}),
214
+ refs: { audios: [] },
215
+ status: "idle",
216
+ takes: [],
217
+ stages: defaultStages(),
218
+ exports: [],
219
+ log: []
220
+ };
221
+ await mkdir(join(sfxJobDir(id), "refs"), { recursive: true });
222
+ await mkdir(join(sfxJobDir(id), "takes"), { recursive: true });
223
+ await mkdir(join(sfxJobDir(id), "out"), { recursive: true });
224
+ sfxLog(job, "info", `新建音效任务:${job.name}`);
225
+ await writeJsonAtomic(sfxJobFile(id), job);
226
+ return job;
227
+ }
228
+ export async function readSfxJob(id) {
229
+ assertJobId(id);
230
+ const raw = await readJson(sfxJobFile(id));
231
+ if (raw === undefined)
232
+ return undefined;
233
+ return normalizeJob(raw, id);
234
+ }
235
+ /** 保存提示词 / 名称 / 参数 / 审核模式。生成中的任务也允许改,下一次生成才生效。 */
236
+ export async function saveSfxJob(id, input) {
237
+ assertJobId(id);
238
+ const job = await patchSfxJob(id, (current) => {
239
+ if (typeof input.name === "string") {
240
+ const name = input.name.trim().slice(0, 200);
241
+ if (name !== "")
242
+ current.name = name;
243
+ }
244
+ if (typeof input.prompt === "string") {
245
+ if (input.prompt.length > SFX_LIMITS.promptChars) {
246
+ throw new Error(`提示词太长:${input.prompt.length} 字符,上限 ${SFX_LIMITS.promptChars}`);
247
+ }
248
+ current.prompt = input.prompt.trim();
249
+ }
250
+ if (input.settings !== undefined) {
251
+ current.settings = normalizeSfxSettings(input.settings, current.settings);
252
+ }
253
+ if (input.reviewMode === "auto" || input.reviewMode === "manual") {
254
+ current.reviewMode = input.reviewMode;
255
+ }
256
+ sfxLog(current, "info", "任务参数已更新");
257
+ return current;
258
+ });
259
+ return sfxSnapshot(job, originForLinks());
260
+ }
261
+ export async function writeSfxJob(job) {
262
+ assertJobId(job.id);
263
+ await sweepTempFiles(sfxJobDir(job.id)).catch(() => undefined);
264
+ await writeJsonAtomic(sfxJobFile(job.id), job);
265
+ }
266
+ const jobQueues = new Map();
267
+ /**
268
+ * 按任务串行写。后台任务收尾与用户保存同时发生时,只靠「读-改-写」会丢改动。
269
+ */
270
+ export function patchSfxJob(id, mutator) {
271
+ assertJobId(id);
272
+ const previous = jobQueues.get(id) ?? Promise.resolve();
273
+ const next = previous
274
+ .catch(() => undefined)
275
+ .then(async () => {
276
+ const job = await readSfxJob(id);
277
+ if (job === undefined)
278
+ throw new Error(`音效任务不存在:${id}`);
279
+ const result = await mutator(job);
280
+ job.updatedAt = now();
281
+ await writeSfxJob(job);
282
+ return result;
283
+ });
284
+ jobQueues.set(id, next);
285
+ void next.finally(() => {
286
+ if (jobQueues.get(id) === next)
287
+ jobQueues.delete(id);
288
+ }).catch(() => undefined);
289
+ return next;
290
+ }
291
+ export async function listSfxJobs() {
292
+ let entries = [];
293
+ try {
294
+ entries = (await readdir(sfxJobsRoot(), { withFileTypes: true }))
295
+ .filter((entry) => entry.isDirectory() && isValidSfxJobId(entry.name))
296
+ .map((entry) => entry.name);
297
+ }
298
+ catch {
299
+ return [];
300
+ }
301
+ const jobs = [];
302
+ for (const id of entries) {
303
+ const job = await readSfxJob(id).catch(() => undefined);
304
+ if (job !== undefined)
305
+ jobs.push(summarizeSfxJob(job));
306
+ }
307
+ return jobs.sort((a, b) => b.updatedAt - a.updatedAt);
308
+ }
309
+ export function summarizeSfxJob(job) {
310
+ const latest = job.takes[job.takes.length - 1];
311
+ return {
312
+ id: job.id,
313
+ name: job.name,
314
+ createdAt: job.createdAt,
315
+ updatedAt: job.updatedAt,
316
+ status: job.status,
317
+ busy: sfxBusy(job.id, job),
318
+ takes: job.takes.length,
319
+ latestDuration: latest?.duration ?? null,
320
+ format: latest?.format ?? null,
321
+ reviewMode: job.reviewMode ?? null
322
+ };
323
+ }
324
+ export async function deleteSfxJob(id) {
325
+ assertJobId(id);
326
+ const job = await readSfxJob(id);
327
+ if (job === undefined)
328
+ return;
329
+ if (sfxBusy(id, job))
330
+ throw new Error("任务正在生成,先取消或等它结束再删除。");
331
+ await rm(sfxJobDir(id), { recursive: true, force: true });
332
+ }
333
+ // ── 后台任务表 ──────────────────────────────────────────────────────────
334
+ const running = new Map();
335
+ const controllers = new Map();
336
+ let disposed = false;
337
+ /** DSH 重载插件时模块级 disposed 会留着,apply 时靠它复位。 */
338
+ export function activateSfx() {
339
+ disposed = false;
340
+ running.clear();
341
+ for (const controller of controllers.values())
342
+ controller.abort();
343
+ controllers.clear();
344
+ }
345
+ export function disposeSfx() {
346
+ disposed = true;
347
+ for (const controller of controllers.values())
348
+ controller.abort();
349
+ controllers.clear();
350
+ running.clear();
351
+ }
352
+ export function sfxBusy(id, job) {
353
+ if ((running.get(id)?.size ?? 0) > 0)
354
+ return true;
355
+ return job?.status === "running";
356
+ }
357
+ function trackSfxTask(id, key, run) {
358
+ if (disposed)
359
+ return false;
360
+ const set = running.get(id) ?? new Set();
361
+ if (set.has(key))
362
+ return false;
363
+ running.set(id, set);
364
+ set.add(key);
365
+ const controller = new AbortController();
366
+ controllers.set(`${id}:${key}`, controller);
367
+ void run()
368
+ .catch((error) => {
369
+ void patchSfxJob(id, (job) => sfxLog(job, "error", `${key} 失败:${messageOf(error)}`)).catch(() => undefined);
370
+ })
371
+ .finally(() => {
372
+ set.delete(key);
373
+ controllers.delete(`${id}:${key}`);
374
+ if (set.size === 0 && running.get(id) === set)
375
+ running.delete(id);
376
+ });
377
+ return true;
378
+ }
379
+ function controllerOf(id) {
380
+ return controllers.get(`${id}:generation`);
381
+ }
382
+ export async function cancelSfxGeneration(id) {
383
+ assertJobId(id);
384
+ const controller = controllerOf(id);
385
+ if (controller === undefined)
386
+ return false;
387
+ controller.abort();
388
+ return true;
389
+ }
390
+ // ── 参考素材 ────────────────────────────────────────────────────────────
391
+ const IMAGE_REF_EXTS = new Set(["png", "jpg", "jpeg", "webp"]);
392
+ function safeRefName(name, fallback) {
393
+ const value = typeof name === "string" ? name.trim() : "";
394
+ if (value === "")
395
+ return fallback;
396
+ return value.replace(/[^\w.\-()\u4e00-\u9fa5]+/gu, "_").slice(0, 120);
397
+ }
398
+ export async function uploadSfxRef(id, kind, name, data) {
399
+ assertJobId(id);
400
+ const job = await readSfxJob(id);
401
+ if (job === undefined)
402
+ throw new Error(`音效任务不存在:${id}`);
403
+ const raw = typeof data === "string" ? data.replace(/^data:[^,]*,/u, "") : "";
404
+ if (raw.trim() === "")
405
+ throw new Error("上传内容为空");
406
+ let bytes;
407
+ try {
408
+ bytes = Buffer.from(raw, "base64");
409
+ }
410
+ catch {
411
+ throw new Error("上传内容不是合法 base64");
412
+ }
413
+ if (bytes.length === 0)
414
+ throw new Error("上传内容为空");
415
+ if (bytes.length > SFX_LIMITS.refBytes) {
416
+ throw new Error(`参考文件太大:${(bytes.length / 1024 / 1024).toFixed(1)}MB(上限 10MB)`);
417
+ }
418
+ await mkdir(join(sfxJobDir(id), "refs"), { recursive: true });
419
+ if (kind === "image") {
420
+ if (job.refs.audios.length > 0)
421
+ throw new Error("参考图与参考音频不能同时使用:先删掉参考音频,再上传参考图。");
422
+ const sniffed = sniffImage(raw);
423
+ if (sniffed === undefined || !IMAGE_REF_EXTS.has(sniffed.ext)) {
424
+ throw new Error("无法识别的参考图格式(支持 PNG / JPEG / WebP)");
425
+ }
426
+ const ext = sniffed.ext === "jpeg" ? "jpg" : sniffed.ext;
427
+ const relative = `refs/image-${randomUUID().slice(0, 8)}.${ext}`;
428
+ await writeFile(sfxAssetPath(id, relative), bytes);
429
+ const previous = job.refs.image;
430
+ await patchSfxJob(id, (current) => {
431
+ current.refs.image = {
432
+ file: relative,
433
+ name: safeRefName(name, `参考图.${ext}`),
434
+ bytes: bytes.length,
435
+ ext
436
+ };
437
+ sfxLog(current, "info", `上传参考图:${current.refs.image.name}`);
438
+ });
439
+ if (previous !== undefined)
440
+ await rm(sfxAssetPath(id, previous.file), { force: true }).catch(() => undefined);
441
+ const latest = await readSfxJob(id);
442
+ return sfxSnapshot(latest ?? job, originForLinks());
443
+ }
444
+ if (job.refs.image !== undefined)
445
+ throw new Error("参考图与参考音频不能同时使用:先删掉参考图,再上传参考音频。");
446
+ if (job.refs.audios.length >= SFX_LIMITS.audioRefs) {
447
+ throw new Error(`参考音频最多 ${SFX_LIMITS.audioRefs} 条:先删掉一条再上传。`);
448
+ }
449
+ const sniffed = sniffBinary(bytes.subarray(0, 24));
450
+ const allowed = new Set(["wav", "mp3", "ogg"]);
451
+ if (sniffed === undefined || !allowed.has(sniffed.ext)) {
452
+ throw new Error("无法识别的参考音频格式(支持 WAV / MP3 / OGG(Opus))");
453
+ }
454
+ let duration;
455
+ const probeRelative = `refs/.probe-${randomUUID().slice(0, 8)}.${sniffed.ext}`;
456
+ try {
457
+ const probePath = sfxAssetPath(id, probeRelative);
458
+ await writeFile(probePath, bytes);
459
+ const probe = await probeAudio(probePath);
460
+ duration = probe.duration;
461
+ if (duration > SFX_LIMITS.refSeconds + 0.5) {
462
+ throw new Error(`参考音频太长:${duration.toFixed(1)} 秒(上限 ${SFX_LIMITS.refSeconds} 秒)`);
463
+ }
464
+ }
465
+ catch (error) {
466
+ // 缺 ffprobe 时 probeAudio 会抛 MediaError;这不是用户文件的问题,交给平台校验。
467
+ if (error instanceof Error && /参考音频太长/u.test(error.message))
468
+ throw error;
469
+ }
470
+ finally {
471
+ await rm(sfxAssetPath(id, probeRelative), { force: true }).catch(() => undefined);
472
+ }
473
+ const relative = `refs/audio-${job.refs.audios.length + 1}-${randomUUID().slice(0, 8)}.${sniffed.ext}`;
474
+ await writeFile(sfxAssetPath(id, relative), bytes);
475
+ await patchSfxJob(id, (current) => {
476
+ current.refs.audios.push({
477
+ file: relative,
478
+ name: safeRefName(name, `参考音频 ${current.refs.audios.length + 1}.${sniffed.ext}`),
479
+ bytes: bytes.length,
480
+ ext: sniffed.ext,
481
+ ...(duration === undefined ? {} : { duration })
482
+ });
483
+ sfxLog(current, "info", `上传参考音频:${current.refs.audios[current.refs.audios.length - 1].name}`);
484
+ });
485
+ const latest = await readSfxJob(id);
486
+ return sfxSnapshot(latest ?? job, originForLinks());
487
+ }
488
+ export async function removeSfxRef(id, kind, file) {
489
+ assertJobId(id);
490
+ const job = await readSfxJob(id);
491
+ if (job === undefined)
492
+ throw new Error(`音效任务不存在:${id}`);
493
+ const removed = [];
494
+ await patchSfxJob(id, (current) => {
495
+ if (kind === "image") {
496
+ if (current.refs.image !== undefined) {
497
+ removed.push(current.refs.image.file);
498
+ current.refs.image = undefined;
499
+ sfxLog(current, "info", "删除参考图");
500
+ }
501
+ return;
502
+ }
503
+ const target = typeof file === "string" && file !== "" ? file : undefined;
504
+ const keep = [];
505
+ for (const entry of current.refs.audios) {
506
+ if (target === undefined || entry.file === target)
507
+ removed.push(entry.file);
508
+ else
509
+ keep.push(entry);
510
+ }
511
+ current.refs.audios = keep;
512
+ if (removed.length > 0)
513
+ sfxLog(current, "info", `删除 ${removed.length} 条参考音频`);
514
+ });
515
+ for (const relative of removed)
516
+ await rm(sfxAssetPath(id, relative), { force: true }).catch(() => undefined);
517
+ const latest = await readSfxJob(id);
518
+ return sfxSnapshot(latest ?? job, originForLinks());
519
+ }
520
+ async function readRefs(id, job) {
521
+ const image = job.refs.image === undefined ? undefined : await readFile(sfxAssetPath(id, job.refs.image.file)).catch(() => undefined);
522
+ if (job.refs.image !== undefined && image === undefined) {
523
+ throw new Error(`参考图文件已丢失:${job.refs.image.file};请删掉后重新上传。`);
524
+ }
525
+ const audios = [];
526
+ for (const entry of job.refs.audios) {
527
+ const bytes = await readFile(sfxAssetPath(id, entry.file)).catch(() => undefined);
528
+ if (bytes === undefined)
529
+ throw new Error(`参考音频文件已丢失:${entry.file};请删掉后重新上传。`);
530
+ audios.push(bytes);
531
+ }
532
+ return { ...(image === undefined ? {} : { image }), audios };
533
+ }
534
+ export async function startSfxGeneration(id) {
535
+ assertJobId(id);
536
+ const job = await readSfxJob(id);
537
+ if (job === undefined)
538
+ throw new Error(`音效任务不存在:${id}`);
539
+ if (sfxBusy(id, job))
540
+ return { started: false, reason: "这个任务正在生成,等它结束再提交(重复提交会重复计费)。" };
541
+ const config = await loadConfig();
542
+ const blocker = sfxBlocker(config);
543
+ if (blocker !== undefined)
544
+ throw new Error(blocker);
545
+ if (job.prompt.trim() === "")
546
+ throw new Error("提示词为空:先写清要什么声音");
547
+ const refs = await readRefs(id, job);
548
+ // 先在主线程校验一遍(不消耗网络),避免「任务已置 running 才因为参数不合法失败」。
549
+ buildSfxBody({ prompt: job.prompt, settings: job.settings, refs }, config.sfxModel);
550
+ const startedAt = now();
551
+ await patchSfxJob(id, (current) => {
552
+ current.status = "running";
553
+ current.error = undefined;
554
+ current.stages.generate = { status: "running", approved: false, at: startedAt };
555
+ sfxLog(current, "info", `提交生成:${job.settings.format} / ${job.settings.sampleRate}Hz`);
556
+ });
557
+ const ok = trackSfxTask(id, "generation", () => runSfxGeneration(id, refs));
558
+ if (!ok) {
559
+ await patchSfxJob(id, (current) => {
560
+ current.status = "error";
561
+ current.error = "后台任务没有启动(插件正在重载?)";
562
+ current.stages.generate = { status: "error", approved: false, error: current.error, at: now() };
563
+ sfxLog(current, "error", current.error);
564
+ });
565
+ return { started: false, reason: "后台任务没有启动,请重启插件后再试。" };
566
+ }
567
+ return { started: true };
568
+ }
569
+ async function runSfxGeneration(id, refs) {
570
+ const config = await loadConfig();
571
+ const controller = controllerOf(id);
572
+ const job = await readSfxJob(id);
573
+ if (job === undefined)
574
+ return;
575
+ try {
576
+ const result = await generateSfx({
577
+ baseUrl: config.sfxBaseUrl,
578
+ apiKey: config.sfxApiKey,
579
+ model: config.sfxModel,
580
+ timeoutMs: config.sfxTimeoutMs
581
+ }, {
582
+ prompt: job.prompt,
583
+ settings: job.settings,
584
+ refs
585
+ }, controller?.signal);
586
+ const takeId = `k${now().toString(36)}${randomUUID().slice(0, 6)}`;
587
+ const relative = `takes/${takeId}.${result.ext}`;
588
+ const target = sfxAssetPath(id, relative);
589
+ const tmp = `${target}.${randomUUID().slice(0, 6)}.part`;
590
+ await mkdir(join(sfxJobDir(id), "takes"), { recursive: true });
591
+ await writeFile(tmp, result.bytes);
592
+ await rename(tmp, target);
593
+ let duration = result.duration;
594
+ if (duration === undefined) {
595
+ try {
596
+ duration = (await probeAudio(target)).duration;
597
+ }
598
+ catch {
599
+ duration = undefined;
600
+ }
601
+ }
602
+ await patchSfxJob(id, (current) => {
603
+ current.status = "ready";
604
+ current.error = undefined;
605
+ current.takes.push({
606
+ id: takeId,
607
+ file: relative,
608
+ bytes: result.bytes.length,
609
+ format: result.ext,
610
+ ...(duration === undefined ? {} : { duration }),
611
+ ...(result.originalDuration === undefined ? {} : { originalDuration: result.originalDuration }),
612
+ prompt: job.prompt,
613
+ settings: job.settings,
614
+ createdAt: now(),
615
+ ...(result.logId === undefined ? {} : { logId: result.logId })
616
+ });
617
+ current.stages.generate = { status: "done", approved: false, at: now() };
618
+ sfxLog(current, "info", `生成完成:${relative}(${result.bytes.length} 字节${duration === undefined ? "" : `,${duration.toFixed(2)} 秒`})`);
619
+ });
620
+ }
621
+ catch (error) {
622
+ const message = messageOf(error);
623
+ await patchSfxJob(id, (current) => {
624
+ current.status = "error";
625
+ current.error = message;
626
+ current.stages.generate = { status: "error", approved: false, error: message, at: now() };
627
+ sfxLog(current, "error", message);
628
+ }).catch(() => undefined);
629
+ }
630
+ }
631
+ // ── 验收 / 导出 ─────────────────────────────────────────────────────────
632
+ export async function setSfxApproved(id, stage, approved) {
633
+ assertJobId(id);
634
+ if (stage !== undefined && !SFX_STAGES.includes(stage))
635
+ throw new Error(`未知阶段:${stage}(可选:${SFX_STAGES.join(" / ")})`);
636
+ const job = await patchSfxJob(id, (current) => {
637
+ const stages = stage === undefined ? [...SFX_STAGES] : [stage];
638
+ for (const key of stages)
639
+ current.stages[key].approved = approved;
640
+ sfxLog(current, "info", `${approved ? "通过" : "取消通过"}:${stage ?? "全部阶段"}`);
641
+ return current;
642
+ });
643
+ return sfxSnapshot(job, originForLinks());
644
+ }
645
+ function sfxAssetBase(id) {
646
+ return assetBasePath(`/dsh-game-material-master/sfx-assets/${id}/`);
647
+ }
648
+ function absUrl(origin, assetBase, relative) {
649
+ if (typeof relative !== "string" || relative === "")
650
+ return undefined;
651
+ return `${origin}${assetBase}${relative.split("/").map(encodeURIComponent).join("/")}`;
652
+ }
653
+ export async function exportSfx(id, input = {}) {
654
+ assertJobId(id);
655
+ const job = await readSfxJob(id);
656
+ if (job === undefined)
657
+ throw new Error(`音效任务不存在:${id}`);
658
+ if (job.takes.length === 0)
659
+ throw new Error("还没有可导出的音频:先生成一条。");
660
+ const outDir = join(sfxJobDir(id), "out");
661
+ await mkdir(outDir, { recursive: true });
662
+ const origin = originForLinks();
663
+ const assetBase = sfxAssetBase(id);
664
+ const stem = safeSfxStem(job.name);
665
+ if (input.zip === true) {
666
+ const entries = [];
667
+ for (const take of job.takes) {
668
+ entries.push({ path: basename(take.file), data: await readFile(sfxAssetPath(id, take.file)) });
669
+ }
670
+ const zip = zipEntries(entries);
671
+ const zipName = `${stem}-${Date.now().toString(36)}.zip`;
672
+ await writeFile(join(outDir, zipName), zip);
673
+ const relative = `out/${zipName}`;
674
+ const exportId = `e${Date.now().toString(36)}${randomUUID().slice(0, 6)}`;
675
+ await patchSfxJob(id, (current) => {
676
+ current.exports.push({
677
+ id: exportId,
678
+ takeId: null,
679
+ file: relative,
680
+ bytes: zip.length,
681
+ format: "zip",
682
+ createdAt: now()
683
+ });
684
+ current.stages.export = { status: "done", approved: false, at: now() };
685
+ sfxLog(current, "info", `导出打包:${relative}(${job.takes.length} 条)`);
686
+ });
687
+ const url = absUrl(origin, assetBase, relative) ?? null;
688
+ return {
689
+ ok: true,
690
+ zip: true,
691
+ file: relative,
692
+ path: join(outDir, zipName),
693
+ url,
694
+ downloadUrl: url === null ? null : `${url}?download=1`,
695
+ bytes: zip.length,
696
+ count: job.takes.length
697
+ };
698
+ }
699
+ const take = input.takeId === undefined || input.takeId === ""
700
+ ? job.takes[job.takes.length - 1]
701
+ : job.takes.find((entry) => entry.id === input.takeId);
702
+ if (take === undefined)
703
+ throw new Error(`找不到这一条生成:${input.takeId}`);
704
+ const source = sfxAssetPath(id, take.file);
705
+ const fileName = `${stem}-${take.id}.${take.format}`;
706
+ const target = join(outDir, fileName);
707
+ await copyFile(source, target);
708
+ const info = await stat(target);
709
+ const relative = `out/${fileName}`;
710
+ const exportId = `e${now().toString(36)}${randomUUID().slice(0, 6)}`;
711
+ await patchSfxJob(id, (current) => {
712
+ current.exports.push({
713
+ id: exportId,
714
+ takeId: take.id,
715
+ file: relative,
716
+ bytes: info.size,
717
+ format: take.format,
718
+ createdAt: now()
719
+ });
720
+ current.stages.export = { status: "done", approved: false, at: now() };
721
+ sfxLog(current, "info", `导出:${relative}`);
722
+ });
723
+ const url = absUrl(origin, assetBase, relative) ?? null;
724
+ return {
725
+ ok: true,
726
+ file: relative,
727
+ path: target,
728
+ url,
729
+ downloadUrl: url === null ? null : `${url}?download=1`,
730
+ bytes: info.size,
731
+ format: take.format,
732
+ takeId: take.id
733
+ };
734
+ }
735
+ // ── 视图 ────────────────────────────────────────────────────────────────
736
+ export async function sfxSnapshot(job, origin = originForLinks()) {
737
+ const config = await loadConfig();
738
+ const assetBase = sfxAssetBase(job.id);
739
+ return {
740
+ module: "sfx",
741
+ id: job.id,
742
+ name: job.name,
743
+ dir: sfxJobDir(job.id),
744
+ assetBase,
745
+ createdAt: job.createdAt,
746
+ updatedAt: job.updatedAt,
747
+ reviewMode: job.reviewMode ?? null,
748
+ busy: sfxBusy(job.id, job),
749
+ blocker: sfxBlocker(config) ?? null,
750
+ prompt: job.prompt,
751
+ settings: job.settings,
752
+ status: job.status,
753
+ ...(job.error === undefined ? {} : { error: job.error }),
754
+ refs: {
755
+ image: job.refs.image === undefined
756
+ ? null
757
+ : { ...job.refs.image, url: absUrl(origin, assetBase, job.refs.image.file) ?? null },
758
+ audios: job.refs.audios.map((entry) => ({
759
+ ...entry,
760
+ url: absUrl(origin, assetBase, entry.file) ?? null
761
+ }))
762
+ },
763
+ takes: job.takes.map((take) => ({
764
+ ...take,
765
+ url: absUrl(origin, assetBase, take.file) ?? null
766
+ })),
767
+ stages: job.stages,
768
+ exports: job.exports.map((entry) => ({
769
+ ...entry,
770
+ url: absUrl(origin, assetBase, entry.file) ?? null,
771
+ downloadUrl: absUrl(origin, assetBase, entry.file) === undefined ? null : `${absUrl(origin, assetBase, entry.file)}?download=1`
772
+ })),
773
+ log: job.log.slice(-40)
774
+ };
775
+ }
776
+ /** 进程重启后:没有远端 taskId 可续查,残留的 running 一律标失败。 */
777
+ export async function resumeSfxJobs() {
778
+ const jobs = await listSfxJobs().catch(() => []);
779
+ for (const summary of jobs) {
780
+ if (summary.status !== "running")
781
+ continue;
782
+ await patchSfxJob(summary.id, (job) => {
783
+ job.status = "error";
784
+ job.error = "宿主重启导致生成中断;远端可能已经完成并计费,请重新生成或先到控制台核对。";
785
+ job.stages.generate = { status: "error", approved: false, error: job.error, at: now() };
786
+ sfxLog(job, "warn", job.error);
787
+ }).catch(() => undefined);
788
+ }
789
+ }
790
+ export async function sweepSfxJob(id) {
791
+ await sweepTempFiles(sfxJobDir(id)).catch(() => undefined);
792
+ }
793
+ export function sfxJobExists(id) {
794
+ return existsSync(sfxJobFile(id));
795
+ }
796
+ /** 工具/界面都用的「下一步」提示。 */
797
+ export function sfxNextActions(snapshot) {
798
+ const actions = [];
799
+ if (typeof snapshot.blocker === "string" && snapshot.blocker !== "")
800
+ actions.push(snapshot.blocker);
801
+ const takes = Array.isArray(snapshot.takes) ? snapshot.takes : [];
802
+ if (snapshot.busy === true) {
803
+ actions.push("正在生成:用 game_material_wait({module:'sfx', id}) 等它结束;不要重复提交。");
804
+ }
805
+ else if (takes.length === 0) {
806
+ actions.push("还没有生成:runSfxGeneration({jobId})(★真实计费,每次一条),然后 game_material_wait。");
807
+ }
808
+ else {
809
+ actions.push("试听 takes 里的 URL;满意就 exportSfx({jobId, takeId}),不满意改提示词再 runSfxGeneration(会再计费一次)。");
810
+ }
811
+ if (typeof snapshot.error === "string" && snapshot.error !== "") {
812
+ actions.push(`上次失败:${snapshot.error};重试会再计费,先向用户确认。`);
813
+ }
814
+ if (snapshot.reviewMode === "manual")
815
+ actions.push("审核模式是 manual:生成后贴 openUrl 并停下等用户说「通过」。");
816
+ if (actions.length === 0)
817
+ actions.push("任务已就绪:可以继续生成或导出。");
818
+ return actions;
819
+ }