dsh-game-material-master 0.8.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/config.js CHANGED
@@ -10,6 +10,7 @@ import { join } from "node:path";
10
10
  import { DEFAULT_ROW_ORDER } from "./directions.js";
11
11
  import { STUDIO_MODULES } from "./links.js";
12
12
  import { MUSIC_DEFAULT_MODEL } from "./musicmodels.js";
13
+ import { SFX_DEFAULT_BASE_URL, SFX_DEFAULT_FORMAT, SFX_DEFAULT_MODEL, SFX_DEFAULT_SAMPLE_RATE, sfxFormatOrDefault, sfxSampleRateOrDefault } from "./sfxapi.js";
13
14
  /**
14
15
  * 上一版的默认行序(按生成依赖顺序)。方位语义修正后,默认改成罗盘顺时针;
15
16
  * 配置里还留着旧默认值的用户应当自动迁过去,而不是被卡在旧顺序上。
@@ -63,6 +64,10 @@ export function tileJobsRoot() {
63
64
  export function musicJobsRoot() {
64
65
  return join(dataRoot(), "music-jobs");
65
66
  }
67
+ /** 音效生成模块(模块八)的任务根。 */
68
+ export function sfxJobsRoot() {
69
+ return join(dataRoot(), "sfx-jobs");
70
+ }
66
71
  /**
67
72
  * 旧版本把数据放在 `8dir-sprites/`。第一次以新名字启动时整体搬过去,
68
73
  * 让已有项目和配置无缝接上——只搬一次,之后两个目录互不影响。
@@ -191,6 +196,13 @@ export const DEFAULT_CONFIG = {
191
196
  musicPythonPath: "",
192
197
  musicFluidsynthPath: "",
193
198
  musicSoundfontPath: "",
199
+ sfxProvider: "volcengine",
200
+ sfxApiKey: "",
201
+ sfxBaseUrl: SFX_DEFAULT_BASE_URL,
202
+ sfxModel: SFX_DEFAULT_MODEL,
203
+ sfxFormat: SFX_DEFAULT_FORMAT,
204
+ sfxSampleRate: SFX_DEFAULT_SAMPLE_RATE,
205
+ sfxTimeoutMs: 300000,
194
206
  cellWidth: 256,
195
207
  cellHeight: 256,
196
208
  frameCount: 8,
@@ -343,6 +355,14 @@ export function normalizeConfig(input) {
343
355
  musicPythonPath: asString(raw.musicPythonPath, DEFAULT_CONFIG.musicPythonPath).trim(),
344
356
  musicFluidsynthPath: asString(raw.musicFluidsynthPath, DEFAULT_CONFIG.musicFluidsynthPath).trim(),
345
357
  musicSoundfontPath: asString(raw.musicSoundfontPath, DEFAULT_CONFIG.musicSoundfontPath).trim(),
358
+ sfxProvider: "volcengine",
359
+ sfxApiKey: asString(raw.sfxApiKey, DEFAULT_CONFIG.sfxApiKey),
360
+ // 允许本地 mock / 反代;完整端点 / /api/v3 的误填在 sfxapi 里再剥一次。
361
+ sfxBaseUrl: asString(raw.sfxBaseUrl, DEFAULT_CONFIG.sfxBaseUrl).replace(/\/+$/u, "") || DEFAULT_CONFIG.sfxBaseUrl,
362
+ sfxModel: asString(raw.sfxModel, DEFAULT_CONFIG.sfxModel).trim() || DEFAULT_CONFIG.sfxModel,
363
+ sfxFormat: sfxFormatOrDefault(raw.sfxFormat),
364
+ sfxSampleRate: sfxSampleRateOrDefault(raw.sfxSampleRate),
365
+ sfxTimeoutMs: asInt(raw.sfxTimeoutMs, DEFAULT_CONFIG.sfxTimeoutMs, 30000, 900000),
346
366
  cellWidth: asInt(raw.cellWidth, DEFAULT_CONFIG.cellWidth, 16, 2048),
347
367
  cellHeight: asInt(raw.cellHeight, DEFAULT_CONFIG.cellHeight, 16, 2048),
348
368
  frameCount: asInt(raw.frameCount, DEFAULT_CONFIG.frameCount, 1, 64),
@@ -389,7 +409,7 @@ export async function saveConfig(patch) {
389
409
  return next;
390
410
  }
391
411
  export function maskConfig(config) {
392
- const { arkApiKey, minimaxApiKey, customApiKey, comfyCookies, musicApiKey, ...rest } = config;
412
+ const { arkApiKey, minimaxApiKey, customApiKey, comfyCookies, musicApiKey, sfxApiKey, ...rest } = config;
393
413
  const cookie = normalizeComfyCookies(comfyCookies);
394
414
  return {
395
415
  ...rest,
@@ -406,7 +426,9 @@ export function maskConfig(config) {
406
426
  comfyCookiesSet: cookie !== "",
407
427
  comfyCookiesHint: hintOf(cookie),
408
428
  musicApiKeySet: musicApiKey.trim() !== "",
409
- musicApiKeyHint: hintOf(musicApiKey)
429
+ musicApiKeyHint: hintOf(musicApiKey),
430
+ sfxApiKeySet: sfxApiKey.trim() !== "",
431
+ sfxApiKeyHint: hintOf(sfxApiKey)
410
432
  };
411
433
  }
412
434
  function hintOf(key) {
package/lib/index.js CHANGED
@@ -30,19 +30,21 @@ import * as riggen from "./riggen.js";
30
30
  import * as tilegen from "./tilegen.js";
31
31
  import * as mapgen from "./mapgen.js";
32
32
  import * as musicgen from "./musicgen.js";
33
+ import * as sfxgen from "./sfxgen.js";
33
34
  import { musicGuidePayload } from "./musicguide.js";
34
35
  import { musicScoreGuidePayload } from "./musicscoreguide.js";
35
36
  import { clearScoreDepsCache, detectScoreDeps } from "./musicscore.js";
36
37
  import { musicBlocker, musicEngineSummary, testMusicConnection } from "./musicapi.js";
38
+ import { SFX_FORMATS, SFX_LIMITS, SFX_SAMPLE_RATES, sfxBlocker, testSfxConnection } from "./sfxapi.js";
37
39
  import { MANIFEST, METHODS, SERVICE_NAME } from "./wire.js";
38
40
  import { assetBasePath, originForLinks, rememberClientOrigin } from "./links.js";
39
41
  import { registerStudioTools } from "./tools.js";
40
42
  /**
41
43
  * 游戏素材大师 —— 宿主半区。
42
44
  *
43
- * 一个 Typert 远程服务("gameStudio")承载七个功能模块的控制面:
45
+ * 一个 Typert 远程服务("gameStudio")承载八个功能模块的控制面:
44
46
  * ① 八方向图生成 ② 图片生成 ③ 序列帧生成 ④ 骨骼动画生成 ⑤ 地图地块生成
45
- * 七者共用同一套配置(各平台的 API Key / 模型 / 抠像默认值),但各自独立存项目 / 任务。
47
+ * 八者共用同一套配置(各平台的 API Key / 模型 / 抠像默认值),但各自独立存项目 / 任务。
46
48
  *
47
49
  * 另外用 `ctx.webServer` 注册一条 prefix 路由,把各模块的产物直接发给浏览器。
48
50
  */
@@ -185,6 +187,7 @@ const MIME_TYPES = {
185
187
  ".aac": "audio/aac",
186
188
  ".flac": "audio/flac",
187
189
  ".ogg": "audio/ogg",
190
+ ".opus": "audio/ogg",
188
191
  ".mid": "audio/midi",
189
192
  ".midi": "audio/midi",
190
193
  ".py": "text/x-python; charset=utf-8",
@@ -299,6 +302,23 @@ export class GameStudioGateway extends TypertRemoteService {
299
302
  /** 音乐生成编辑(模块七):引擎/模型预设、Key 阻塞原因、文档地址。 */
300
303
  musicEngines: musicEngineSummary(),
301
304
  musicBlocker: musicBlocker(config) ?? null,
305
+ /** 音效生成(模块八,火山引擎 Seed-Audio):格式/采样率/限制与 Key 阻塞原因。 */
306
+ sfxBlocker: sfxBlocker(config) ?? null,
307
+ sfxFormats: SFX_FORMATS.map((format) => ({
308
+ id: format,
309
+ label: format === "mp3"
310
+ ? "MP3(体积小,适合预览 / 网页)"
311
+ : format === "wav"
312
+ ? "WAV(无损,游戏引擎常用)"
313
+ : "Ogg Opus(体积更小)"
314
+ })),
315
+ sfxSampleRates: [...SFX_SAMPLE_RATES],
316
+ sfxLimits: { ...SFX_LIMITS },
317
+ sfxModelPresets: [
318
+ { id: "seed-audio-1.0", label: "seed-audio-1.0(默认 · 音效 / 环境音 / 角色配音)" }
319
+ ],
320
+ sfxDocsUrl: "https://docs.volcengine.com/docs/DoubaoVoice/audio-generation-http",
321
+ sfxConsoleUrl: "https://console.volcengine.com/speech/new/setting/apikeys",
302
322
  /** 谱曲模式依赖(Python / scoremill / FluidSynth / SoundFont / ffmpeg)。 */
303
323
  musicScoreStatus: await detectScoreDeps(config),
304
324
  musicDocsUrl: "https://api.yourmusic.fun/docs",
@@ -368,6 +388,13 @@ export class GameStudioGateway extends TypertRemoteService {
368
388
  "musicPythonPath",
369
389
  "musicFluidsynthPath",
370
390
  "musicSoundfontPath",
391
+ // 音效生成(模块八)。Key 同样不进这里(见下面单独处理)。
392
+ "sfxProvider",
393
+ "sfxBaseUrl",
394
+ "sfxModel",
395
+ "sfxFormat",
396
+ "sfxSampleRate",
397
+ "sfxTimeoutMs",
371
398
  "cellWidth",
372
399
  "cellHeight",
373
400
  "frameCount",
@@ -402,6 +429,9 @@ export class GameStudioGateway extends TypertRemoteService {
402
429
  // 音乐模块的 Key 与其它凭据同一套约定:不带 = 保持原值,带串 = 覆盖。
403
430
  if (typeof input.musicApiKey === "string")
404
431
  patch.musicApiKey = input.musicApiKey.trim();
432
+ // 音效模块的 Key 是**语音控制台**的 API Key(X-Api-Key),与方舟 Key 不同源。
433
+ if (typeof input.sfxApiKey === "string")
434
+ patch.sfxApiKey = input.sfxApiKey.trim();
405
435
  if (input.clearArkApiKey === true)
406
436
  patch.arkApiKey = "";
407
437
  if (input.clearMinimaxApiKey === true)
@@ -410,6 +440,8 @@ export class GameStudioGateway extends TypertRemoteService {
410
440
  patch.customApiKey = "";
411
441
  if (input.clearMusicApiKey === true)
412
442
  patch.musicApiKey = "";
443
+ if (input.clearSfxApiKey === true)
444
+ patch.sfxApiKey = "";
413
445
  // ComfyUI 的 Cookie 也是凭据,与 API Key 同一套约定:不带 = 保持原值,带串 = 覆盖,
414
446
  // clearComfyCookies = 清空。它**不进** directKeys——那里是原样透传,Cookie 要先归一化。
415
447
  if (typeof input.comfyCookies === "string")
@@ -523,6 +555,29 @@ export class GameStudioGateway extends TypertRemoteService {
523
555
  model: config.musicModel
524
556
  };
525
557
  }
558
+ /**
559
+ * 【火山引擎 Seed-Audio】连接自检:真实生成一条极短音效。
560
+ *
561
+ * 没有免费的探活端点;读历史 / 模型列表都不能证明「Key 能生成」。设置页按钮
562
+ * 必须写明会产生少量费用。
563
+ */
564
+ async testSfx() {
565
+ const config = await loadConfig();
566
+ const blocker = sfxBlocker(config);
567
+ if (blocker !== undefined)
568
+ throw new Error(blocker);
569
+ const result = await testSfxConnection({
570
+ baseUrl: config.sfxBaseUrl,
571
+ apiKey: config.sfxApiKey,
572
+ model: config.sfxModel,
573
+ timeoutMs: Math.min(config.sfxTimeoutMs, 180000)
574
+ });
575
+ return {
576
+ ...result,
577
+ baseUrl: config.sfxBaseUrl,
578
+ model: config.sfxModel
579
+ };
580
+ }
526
581
  /**
527
582
  * 浏览器半区上报自己的 `location.origin` 与应用路径前缀。
528
583
  *
@@ -875,6 +930,14 @@ export class GameStudioGateway extends TypertRemoteService {
875
930
  });
876
931
  return { ok: true, id, module, reviewMode };
877
932
  }
933
+ // 音效生成(模块八)。同样:wire 的 module 枚举、tools 的模块表与这里必须成对加。
934
+ if (module === "sfx") {
935
+ await sfxgen.patchSfxJob(id, (job) => {
936
+ job.reviewMode = reviewMode;
937
+ sfxgen.sfxLog(job, "info", `审核模式:${reviewMode === "manual" ? "每一步人工审核" : "agent 自动审核"}`);
938
+ });
939
+ return { ok: true, id, module, reviewMode };
940
+ }
878
941
  throw new Error(`未知模块:${module}`);
879
942
  }
880
943
  // ── 地图地块生成(模块五)──────────────────────────────────────────────
@@ -2533,6 +2596,93 @@ export class GameStudioGateway extends TypertRemoteService {
2533
2596
  zip: input.zip === true
2534
2597
  }, { origin: originForLinks() });
2535
2598
  }
2599
+ // ── 音效生成(模块八,火山引擎 Seed-Audio)────────────────────────────
2600
+ //
2601
+ // 这一组只碰 `sfx-jobs/`。生成是同步 HTTP,但由 sfxgen 的后台任务表承载,
2602
+ // 界面与对话都通过 `getSfxJob` 看状态。
2603
+ async listSfxJobs() {
2604
+ return { jobs: await sfxgen.listSfxJobs() };
2605
+ }
2606
+ async createSfxJob(payload) {
2607
+ const input = asRecord(payload);
2608
+ const job = await sfxgen.createSfxJob({
2609
+ name: typeof input.name === "string" ? input.name : undefined,
2610
+ prompt: asString(input.prompt),
2611
+ settings: input.settings,
2612
+ reviewMode: input.reviewMode === "manual" ? "manual" : input.reviewMode === "auto" ? "auto" : undefined
2613
+ });
2614
+ return sfxgen.sfxSnapshot(job, originForLinks());
2615
+ }
2616
+ async getSfxJob(payload) {
2617
+ const id = asString(asRecord(payload).jobId);
2618
+ const job = await sfxgen.readSfxJob(id);
2619
+ if (job === undefined)
2620
+ throw new Error(`音效任务不存在:${id}`);
2621
+ return sfxgen.sfxSnapshot(job, originForLinks());
2622
+ }
2623
+ async saveSfxJob(payload) {
2624
+ const input = asRecord(payload);
2625
+ return sfxgen.saveSfxJob(asString(input.jobId), {
2626
+ name: typeof input.name === "string" ? input.name : undefined,
2627
+ prompt: typeof input.prompt === "string" ? input.prompt : undefined,
2628
+ settings: input.settings,
2629
+ reviewMode: input.reviewMode === "manual" ? "manual" : input.reviewMode === "auto" ? "auto" : undefined
2630
+ });
2631
+ }
2632
+ async deleteSfxJob(payload) {
2633
+ const id = asString(asRecord(payload).jobId);
2634
+ await sfxgen.deleteSfxJob(id);
2635
+ return { ok: true };
2636
+ }
2637
+ async uploadSfxRef(payload) {
2638
+ const input = asRecord(payload);
2639
+ return sfxgen.uploadSfxRef(asString(input.jobId), input.kind === "audio" ? "audio" : "image", typeof input.name === "string" ? input.name : undefined, asString(input.data));
2640
+ }
2641
+ async removeSfxRef(payload) {
2642
+ const input = asRecord(payload);
2643
+ return sfxgen.removeSfxRef(asString(input.jobId), input.kind === "audio" ? "audio" : "image", typeof input.file === "string" ? input.file : undefined);
2644
+ }
2645
+ async runSfxGeneration(payload) {
2646
+ return sfxgen.startSfxGeneration(asString(asRecord(payload).jobId));
2647
+ }
2648
+ async cancelSfxGeneration(payload) {
2649
+ const id = asString(asRecord(payload).jobId);
2650
+ const canceled = await sfxgen.cancelSfxGeneration(id);
2651
+ return {
2652
+ ok: true,
2653
+ canceled,
2654
+ message: canceled
2655
+ ? "已取消本地请求。远端可能仍会完成并计费;不要为了「确认」再提交一次。"
2656
+ : "当前没有可取消的生成任务。"
2657
+ };
2658
+ }
2659
+ async setSfxApproved(payload) {
2660
+ const input = asRecord(payload);
2661
+ const stage = input.stage === "generate" || input.stage === "export" ? input.stage : undefined;
2662
+ return sfxgen.setSfxApproved(asString(input.jobId), stage, input.approved === true);
2663
+ }
2664
+ async revealSfxJob(payload) {
2665
+ const id = asString(asRecord(payload).jobId);
2666
+ const job = await sfxgen.readSfxJob(id);
2667
+ if (job === undefined)
2668
+ throw new Error(`音效任务不存在:${id}`);
2669
+ const dir = sfxgen.sfxJobDir(id);
2670
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
2671
+ try {
2672
+ spawn(command, [dir], { detached: true, stdio: "ignore" }).unref();
2673
+ }
2674
+ catch (error) {
2675
+ throw new Error(`无法打开目录:${error instanceof Error ? error.message : String(error)}`);
2676
+ }
2677
+ return { ok: true, dir };
2678
+ }
2679
+ async exportSfx(payload) {
2680
+ const input = asRecord(payload);
2681
+ return sfxgen.exportSfx(asString(input.jobId), {
2682
+ takeId: typeof input.takeId === "string" ? input.takeId : undefined,
2683
+ zip: input.zip === true
2684
+ });
2685
+ }
2536
2686
  assertSurface() {
2537
2687
  for (const spec of METHODS) {
2538
2688
  if (typeof this[spec.method] !== "function") {
@@ -2646,6 +2796,8 @@ const SERVABLE_TILE_DIRS = new Set(["template", "raw", "cell", "decor", "map", "
2646
2796
  const SERVABLE_MAP_DIRS = mapgen.SERVABLE_MAP_DIRS;
2647
2797
  /** 音乐生成编辑(模块七):原曲、版本、波形缓存、工具产物、导出。 */
2648
2798
  const SERVABLE_MUSIC_DIRS = musicgen.SERVABLE_MUSIC_DIRS;
2799
+ /** 音效生成(模块八):参考素材、每次生成的音频、导出。 */
2800
+ const SERVABLE_SFX_DIRS = sfxgen.SERVABLE_SFX_DIRS;
2649
2801
  function resolveAssetTarget(scope, id, relative) {
2650
2802
  if (scope === "assets") {
2651
2803
  if (!PROJECT_ID_PATTERN.test(id))
@@ -2677,6 +2829,11 @@ function resolveAssetTarget(scope, id, relative) {
2677
2829
  return undefined;
2678
2830
  return { file: musicgen.musicAssetPath(id, relative), dirs: SERVABLE_MUSIC_DIRS };
2679
2831
  }
2832
+ if (scope === "sfx-assets") {
2833
+ if (!sfxgen.isValidSfxJobId(id))
2834
+ return undefined;
2835
+ return { file: sfxgen.sfxAssetPath(id, relative), dirs: SERVABLE_SFX_DIRS };
2836
+ }
2680
2837
  if (!seqgen.isValidSequenceJobId(id))
2681
2838
  return undefined;
2682
2839
  return { file: seqgen.sequenceAssetPath(id, relative), dirs: SERVABLE_SEQUENCE_DIRS };
@@ -2727,7 +2884,7 @@ async function handleAsset(req, res) {
2727
2884
  // 三处同步。只改类型不改这里,TypeScript 一句话都不会说 —— `scope` 是断言出来的,
2728
2885
  // 而漏掉的那个 scope 会在这里直接掉进 404(界面表现只是「图裂了」)。
2729
2886
  // 实测:`tile-assets` 就这么漏过一轮,模板图全 404。
2730
- const SCOPES = ["assets", "image-assets", "sequence-assets", "rig-assets", "tile-assets", "map-assets", "music-assets"];
2887
+ const SCOPES = ["assets", "image-assets", "sequence-assets", "rig-assets", "tile-assets", "map-assets", "music-assets", "sfx-assets"];
2731
2888
  if (!SCOPES.includes(scope)) {
2732
2889
  sendText(res, 404, "Not Found");
2733
2890
  return;
@@ -2831,6 +2988,7 @@ export function apply(ctx) {
2831
2988
  seqgen.activateSequence();
2832
2989
  riggen.activateRig();
2833
2990
  musicgen.activateMusic();
2991
+ sfxgen.activateSfx();
2834
2992
  // 旧版本的数据目录叫 8dir-sprites,插件改名后搬一次,已有项目无缝接上。
2835
2993
  void migrateLegacyDataRoot()
2836
2994
  .then((moved) => {
@@ -2882,10 +3040,13 @@ export function apply(ctx) {
2882
3040
  })();
2883
3041
  // 音乐任务(模块七):把上次没跑完的生成/工具任务接上(不重新提交,只继续查询/下载)。
2884
3042
  void musicgen.resumeMusicJobs().catch(() => undefined);
3043
+ // 音效任务(模块八):同步接口没有远端 taskId 可续查,残留的 running 标失败。
3044
+ void sfxgen.resumeSfxJobs().catch(() => undefined);
2885
3045
  ctx.effect(() => () => {
2886
3046
  disposePipeline();
2887
3047
  seqgen.disposeSequence();
2888
3048
  riggen.disposeRig();
2889
3049
  musicgen.disposeMusic();
3050
+ sfxgen.disposeSfx();
2890
3051
  }, "dsh-game-material-master: pipeline cleanup");
2891
3052
  }
package/lib/links.js CHANGED
@@ -30,12 +30,14 @@
30
30
  export const OPEN_QUERY_KEY = "dsh-gmm";
31
31
  /** 工作台在 `main` 槽里的 key,也是侧栏 `sidebar.panellist` 的 id。 */
32
32
  export const PANEL_KEY = "gameStudio";
33
- /** 七个模块的 key。 */
34
- export const STUDIO_MODULES = ["sprite", "image", "sequence", "rig", "tile", "map", "music"];
33
+ /** 八个模块的 key。 */
34
+ export const STUDIO_MODULES = ["sprite", "image", "sequence", "rig", "tile", "map", "music", "sfx"];
35
35
  /** 八方向图的四个阶段。 */
36
36
  export const SPRITE_STAGES = ["images", "videos", "frames", "sheet"];
37
37
  /** 音乐生成编辑(模块七)的三个阶段:生成 / 编辑 / 导出。 */
38
38
  export const MUSIC_STAGES = ["compose", "generate", "edit", "export"];
39
+ /** 音效生成(模块八)的两个阶段:生成 / 导出。 */
40
+ export const SFX_STAGES = ["generate", "export"];
39
41
  /**
40
42
  * 地图地块的四个阶段。
41
43
  *
package/lib/musicapi.js CHANGED
@@ -809,6 +809,13 @@ export async function downloadToFile(rawUrl, destDir, config, options) {
809
809
  await rm(tmp, { force: true }).catch(() => undefined);
810
810
  throw error instanceof MusicApiError ? error : new MusicApiError(`下载写入失败:${error instanceof Error ? error.message : String(error)}`);
811
811
  }
812
+ if (options.requireAudio === true) {
813
+ const audioExts = new Set(["mp3", "m4a", "wav", "flac", "ogg", "aac"]);
814
+ if (sniffed === undefined || !audioExts.has(sniffed.ext)) {
815
+ await rm(tmp, { force: true }).catch(() => undefined);
816
+ throw new MusicApiError(`下载到的内容不是音频(Content-Type: ${contentType || "unknown"},文件头无法识别);已丢弃,稍后可重试`);
817
+ }
818
+ }
812
819
  const byMime = EXT_BY_MIME[contentType];
813
820
  const byUrl = extFromUrl(url);
814
821
  const ext = sniffed?.ext ?? byMime ?? byUrl ?? options.fallbackExt ?? "bin";
package/lib/musicgen.js CHANGED
@@ -25,13 +25,13 @@
25
25
  * 改名/保存同时发生时,后写的不会把前一次改动覆盖掉。
26
26
  */
27
27
  import { mkdir, readFile, readdir, rm, stat } from "node:fs/promises";
28
- import { existsSync } from "node:fs";
28
+ import { closeSync, existsSync, openSync, readSync } from "node:fs";
29
29
  import { join, resolve, sep } from "node:path";
30
30
  import { createHash, randomUUID } from "node:crypto";
31
31
  import { loadConfig, musicJobsRoot } from "./config.js";
32
32
  import { appendJobLog, messageOf, readJson, sweepTempFiles, writeJsonAtomic } from "./jsonio.js";
33
33
  import { MUSIC_EDIT_FORMATS, MUSIC_ENGINES, MUSIC_TOOL_KINDS, defaultModelOf, enginePresetOf, isMusicEngine, isMusicMode, isMusicToolKind } from "./musicmodels.js";
34
- import { MusicApiError, buildGenerationRequest, downloadToFile, generateLrc, musicBlocker, musicHistory, querySongs, requestWav, safeStem, stemInstruments, submitAudioConvert, submitGeneration, submitMidi, submitProStemSplit, submitSheetMusic, submitStemSplit, submitStyleAnalysis, toolTask, uploadSunoAudio } from "./musicapi.js";
34
+ import { MusicApiError, buildGenerationRequest, downloadToFile, generateLrc, musicBlocker, musicHistory, querySongs, requestWav, safeStem, sniffBinary, stemInstruments, submitAudioConvert, submitGeneration, submitMidi, submitProStemSplit, submitSheetMusic, submitStemSplit, submitStyleAnalysis, toolTask, uploadSunoAudio } from "./musicapi.js";
35
35
  import { audioPeaks, normalizeEditOps, probeAudio, renderAudioEdit } from "./musicaudio.js";
36
36
  import { zipEntries } from "./zip.js";
37
37
  import { assetBasePath, buildOpenLink, originForLinks } from "./links.js";
@@ -401,15 +401,24 @@ function absUrl(origin, assetBase, relative) {
401
401
  export async function musicSnapshot(job, origin = originForLinks()) {
402
402
  const config = await loadConfig();
403
403
  const assetBase = musicAssetBase(job.id);
404
- const songs = job.songs.map((song) => ({
405
- ...song,
406
- file: song.localFile ?? null,
407
- url: absUrl(origin, assetBase, song.localFile) ?? song.audioUrl ?? null,
408
- remoteUrl: song.audioUrl ?? null,
409
- coverUrl: absUrl(origin, assetBase, song.coverFile) ?? song.imageUrl ?? null,
410
- wavUrl: absUrl(origin, assetBase, song.wavFile) ?? null,
411
- lrcUrl: absUrl(origin, assetBase, song.lrcFile) ?? null
412
- }));
404
+ const songs = job.songs.map((song) => {
405
+ // 不能只看 localFile 是否存在:CDN 偶尔会返回一段随机/加密内容,文件在、但播放器打不开。
406
+ // 文件头不是音频容器时回退到远端 audioUrl(用户至少能先听),并提示可以刷新重下。
407
+ const localOk = localSongUsable(job.id, song.localFile);
408
+ return {
409
+ ...song,
410
+ localFile: localOk ? song.localFile : null,
411
+ file: localOk ? song.localFile : null,
412
+ url: absUrl(origin, assetBase, localOk ? song.localFile : undefined) ?? song.audioUrl ?? null,
413
+ remoteUrl: song.audioUrl ?? null,
414
+ coverUrl: absUrl(origin, assetBase, song.coverFile) ?? song.imageUrl ?? null,
415
+ wavUrl: absUrl(origin, assetBase, song.wavFile) ?? null,
416
+ lrcUrl: absUrl(origin, assetBase, song.lrcFile) ?? null,
417
+ ...(song.localFile !== undefined && !localOk
418
+ ? { downloadError: "本地音频文件无效,已回退到远端播放;点「刷新」或编辑/导出时会自动重新下载。" }
419
+ : {})
420
+ };
421
+ });
413
422
  const versions = job.versions.map((version) => ({
414
423
  ...version,
415
424
  url: absUrl(origin, assetBase, version.file) ?? null
@@ -688,7 +697,7 @@ async function runGeneration(id, generationId, request) {
688
697
  const jobNow = await readMusicJob(id);
689
698
  const songs = jobNow?.songs.filter((song) => songIds.includes(song.id)) ?? [];
690
699
  // 先到先下载:即使另一首还没完成,用户也能先试听已完成的那首。
691
- for (const song of songs.filter((entry) => entry.status === "succeeded" && entry.localFile === undefined)) {
700
+ for (const song of songs.filter((entry) => entry.status === "succeeded" && !localSongUsable(id, entry.localFile))) {
692
701
  await ensureLocalSong(id, song.id).catch((error) => {
693
702
  void patchMusicJob(id, (job) => {
694
703
  const entry = job.songs.find((item) => item.id === song.id);
@@ -701,7 +710,7 @@ async function runGeneration(id, generationId, request) {
701
710
  const failed = songs.filter((song) => song.status === "failed");
702
711
  if (songs.length > 0 && songs.every((song) => song.status === "succeeded" || song.status === "failed")) {
703
712
  for (const song of succeeded) {
704
- if (song.localFile === undefined) {
713
+ if (!localSongUsable(id, song.localFile)) {
705
714
  try {
706
715
  await ensureLocalSong(id, song.id);
707
716
  }
@@ -781,6 +790,38 @@ function applySongPayload(song, payload) {
781
790
  song.error = undefined;
782
791
  }
783
792
  // ── 下载 / 补查 / WAV / LRC ─────────────────────────────────────────────
793
+ const PLAYABLE_AUDIO_EXTS = new Set(["mp3", "m4a", "wav", "flac", "ogg", "aac"]);
794
+ /** 文件头是否是音频容器;只读前 16 字节,不依赖 ffprobe。 */
795
+ function isPlayableAudioFile(file) {
796
+ let fd;
797
+ try {
798
+ fd = openSync(file, "r");
799
+ const head = Buffer.alloc(16);
800
+ const read = readSync(fd, head, 0, 16, 0);
801
+ if (read < 4)
802
+ return false;
803
+ const sniffed = sniffBinary(head.subarray(0, read));
804
+ return sniffed !== undefined && PLAYABLE_AUDIO_EXTS.has(sniffed.ext);
805
+ }
806
+ catch {
807
+ return false;
808
+ }
809
+ finally {
810
+ if (fd !== undefined)
811
+ closeSync(fd);
812
+ }
813
+ }
814
+ /** 本地文件可用(存在 + 文件头可识别);localFile 为空 / 路径非法都算不可用。 */
815
+ function localSongUsable(jobId, localFile) {
816
+ if (typeof localFile !== "string" || localFile === "")
817
+ return false;
818
+ try {
819
+ return isPlayableAudioFile(musicAssetPath(jobId, localFile));
820
+ }
821
+ catch {
822
+ return false;
823
+ }
824
+ }
784
825
  const downloading = new Map();
785
826
  /** 确保一首歌的音频已落盘;失败时抛错,调用方决定是记 downloadError 还是中断。 */
786
827
  export async function ensureLocalSong(id, songId) {
@@ -796,16 +837,61 @@ export async function ensureLocalSong(id, songId) {
796
837
  const song = job.songs.find((entry) => entry.id === songId);
797
838
  if (song === undefined)
798
839
  throw new Error(`歌曲不存在:${songId}`);
799
- if (song.localFile !== undefined && existsSync(musicAssetPath(id, song.localFile)))
800
- return song;
840
+ if (song.localFile !== undefined) {
841
+ let existing;
842
+ try {
843
+ existing = musicAssetPath(id, song.localFile);
844
+ }
845
+ catch {
846
+ existing = undefined;
847
+ }
848
+ if (existing !== undefined && existsSync(existing) && isPlayableAudioFile(existing))
849
+ return song;
850
+ // 旧文件在但头不对(或路径非法):删掉重下,避免界面继续引用坏文件。
851
+ if (existing !== undefined)
852
+ await rm(existing, { force: true }).catch(() => undefined);
853
+ await patchMusicJob(id, (current) => {
854
+ const entry = current.songs.find((item) => item.id === songId);
855
+ if (entry !== undefined) {
856
+ entry.localFile = undefined;
857
+ entry.downloadError = undefined;
858
+ }
859
+ });
860
+ song.localFile = undefined;
861
+ }
801
862
  if (typeof song.audioUrl !== "string" || song.audioUrl === "")
802
863
  throw new Error("这首歌没有可下载的音频地址");
803
864
  const config = await loadConfig();
804
865
  const api = apiConfigOf(config);
805
- const result = await downloadToFile(song.audioUrl, join(musicJobDir(id), "songs"), api, {
866
+ const downloadAudio = (url) => downloadToFile(url, join(musicJobDir(id), "songs"), api, {
806
867
  stem: `song-${safeStem(songId)}`,
807
- fallbackExt: "mp3"
868
+ fallbackExt: "mp3",
869
+ requireAudio: true
808
870
  });
871
+ let result;
872
+ let lastError;
873
+ for (let attempt = 0; attempt < 2; attempt++) {
874
+ const retryUrl = attempt === 0 || song.audioUrl.includes("?")
875
+ ? song.audioUrl
876
+ : `${song.audioUrl}?_gmm_retry=${Date.now().toString(36)}`;
877
+ try {
878
+ const candidate = await downloadAudio(retryUrl);
879
+ if (isPlayableAudioFile(candidate.file)) {
880
+ result = candidate;
881
+ break;
882
+ }
883
+ await rm(candidate.file, { force: true }).catch(() => undefined);
884
+ lastError = new Error("下载到的音频不是可识别的音频容器");
885
+ }
886
+ catch (error) {
887
+ lastError = error;
888
+ }
889
+ if (attempt === 0)
890
+ await sleep(1000);
891
+ }
892
+ if (result === undefined) {
893
+ throw new Error(`音频下载失败,且重试后仍不是可播放的音频:${messageOf(lastError)}`);
894
+ }
809
895
  const relative = `songs/${result.file.split(/[\\/]/u).pop()}`;
810
896
  const cover = await downloadCover(id, song, api).catch(() => undefined);
811
897
  let duration = song.duration;
@@ -873,7 +959,7 @@ export async function refreshMusicJob(id) {
873
959
  const latest = await readMusicJob(id);
874
960
  const songs = latest?.songs.filter((song) => generation.songIds.includes(song.id)) ?? [];
875
961
  if (songs.length > 0 && songs.every((song) => song.status === "succeeded" || song.status === "failed")) {
876
- for (const song of songs.filter((entry) => entry.status === "succeeded" && entry.localFile === undefined)) {
962
+ for (const song of songs.filter((entry) => entry.status === "succeeded" && !localSongUsable(id, entry.localFile))) {
877
963
  await ensureLocalSong(id, song.id).catch(() => undefined);
878
964
  }
879
965
  await patchMusicJob(id, (current) => {
@@ -896,7 +982,7 @@ export async function refreshMusicJob(id) {
896
982
  }
897
983
  // 已成功但还没下载的歌曲:补下载。
898
984
  const latest = await readMusicJob(id);
899
- for (const song of latest?.songs.filter((entry) => entry.status === "succeeded" && entry.localFile === undefined) ?? []) {
985
+ for (const song of latest?.songs.filter((entry) => entry.status === "succeeded" && !localSongUsable(id, entry.localFile)) ?? []) {
900
986
  await ensureLocalSong(id, song.id).catch((error) => {
901
987
  void patchMusicJob(id, (current) => {
902
988
  const entry = current.songs.find((item) => item.id === song.id);
@@ -1280,7 +1366,7 @@ async function resumeGeneration(id, generationId) {
1280
1366
  const latest = await readMusicJob(id);
1281
1367
  const songs = latest?.songs.filter((song) => generation.songIds.includes(song.id)) ?? [];
1282
1368
  if (songs.length > 0 && songs.every((song) => song.status === "succeeded" || song.status === "failed")) {
1283
- for (const song of songs.filter((entry) => entry.status === "succeeded" && entry.localFile === undefined)) {
1369
+ for (const song of songs.filter((entry) => entry.status === "succeeded" && !localSongUsable(id, entry.localFile))) {
1284
1370
  await ensureLocalSong(id, song.id).catch(() => undefined);
1285
1371
  }
1286
1372
  await patchMusicJob(id, (current) => {