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/README.en.md +173 -16
- package/README.md +136 -17
- package/lib/client.js +4145 -259
- package/lib/comfy.js +769 -0
- package/lib/config.js +83 -2
- package/lib/directions.js +9 -2
- package/lib/index.js +677 -26
- package/lib/links.js +152 -10
- package/lib/mapdoc.js +178 -14
- package/lib/mapexport.js +30 -2
- package/lib/mapgen.js +643 -44
- package/lib/maprender.js +155 -13
- package/lib/mapsamplegen.js +139 -12
- package/lib/maptiles.js +1014 -1
- package/lib/media.js +106 -4
- package/lib/midifile.js +390 -0
- package/lib/midipreview.js +326 -0
- package/lib/minimax.js +2 -2
- package/lib/musicapi.js +883 -0
- package/lib/musicaudio.js +249 -0
- package/lib/musicgen.js +2215 -0
- package/lib/musicguide.js +287 -0
- package/lib/musicmodels.js +200 -0
- package/lib/musicscore.js +931 -0
- package/lib/musicscoreguide.js +496 -0
- package/lib/pipeline.js +102 -51
- package/lib/riggen.js +7 -1
- package/lib/seqgen.js +31 -23
- package/lib/sfxapi.js +391 -0
- package/lib/sfxgen.js +819 -0
- package/lib/store.js +81 -0
- package/lib/tilegen.js +3 -2
- package/lib/tools.js +621 -37
- package/lib/videogen.js +150 -0
- package/lib/wire.js +366 -10
- package/package.json +20 -6
package/lib/musicgen.js
ADDED
|
@@ -0,0 +1,2215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 音乐生成编辑(模块七)的数据层与作业。
|
|
3
|
+
*
|
|
4
|
+
* ## 落盘
|
|
5
|
+
*
|
|
6
|
+
* ```
|
|
7
|
+
* <DSH_HOME>/game-material-master/music-jobs/<a…>/
|
|
8
|
+
* ├── job.json
|
|
9
|
+
* ├── songs/<songId>.mp3|.m4a|.wav 下载的原曲
|
|
10
|
+
* ├── songs/<songId>-cover.jpg|.png
|
|
11
|
+
* ├── songs/<songId>-lrc.json
|
|
12
|
+
* ├── versions/<v…>.<ext>
|
|
13
|
+
* ├── peaks/<hash>.json
|
|
14
|
+
* ├── tools/<toolTaskId>/…
|
|
15
|
+
* └── out/<安全名>.<ext> / <任务名>.zip
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* ## 状态机
|
|
19
|
+
*
|
|
20
|
+
* `runMusicGeneration` 先落一条 `submitting` 的 generation 并启动后台任务:
|
|
21
|
+
* 提交 → `polling`(每 5 秒查一次)→ 下载 → `succeeded` / `partial` / `failed`
|
|
22
|
+
* / `timeout`。进程重启后 `resumeMusicJobs()` 会把 `polling` 的任务接上。
|
|
23
|
+
*
|
|
24
|
+
* 所有写 job.json 的地方都走 `patchMusicJob()` 的**按任务串行队列**:轮询器与用户
|
|
25
|
+
* 改名/保存同时发生时,后写的不会把前一次改动覆盖掉。
|
|
26
|
+
*/
|
|
27
|
+
import { mkdir, readFile, readdir, rm, stat } from "node:fs/promises";
|
|
28
|
+
import { closeSync, existsSync, openSync, readSync } from "node:fs";
|
|
29
|
+
import { join, resolve, sep } from "node:path";
|
|
30
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
31
|
+
import { loadConfig, musicJobsRoot } from "./config.js";
|
|
32
|
+
import { appendJobLog, messageOf, readJson, sweepTempFiles, writeJsonAtomic } from "./jsonio.js";
|
|
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, sniffBinary, stemInstruments, submitAudioConvert, submitGeneration, submitMidi, submitProStemSplit, submitSheetMusic, submitStemSplit, submitStyleAnalysis, toolTask, uploadSunoAudio } from "./musicapi.js";
|
|
35
|
+
import { audioPeaks, normalizeEditOps, probeAudio, renderAudioEdit } from "./musicaudio.js";
|
|
36
|
+
import { zipEntries } from "./zip.js";
|
|
37
|
+
import { assetBasePath, buildOpenLink, originForLinks } from "./links.js";
|
|
38
|
+
import { buildScoreBundle, buildScoreSunoParams, detectScoreDeps, normalizeScorePlan, renderScoreAudio, runScoreScript, scorePlanReady } from "./musicscore.js";
|
|
39
|
+
export const MUSIC_STAGES = ["compose", "generate", "edit", "export"];
|
|
40
|
+
const JOB_ID_PATTERN = /^a[a-z0-9]{4,40}$/;
|
|
41
|
+
/** 音乐任务可经资源路由读取的子目录(唯一真源,`index.ts` 直接引用)。 */
|
|
42
|
+
export const SERVABLE_MUSIC_DIRS = new Set(["songs", "versions", "peaks", "tools", "out", "scores"]);
|
|
43
|
+
export function musicJobDir(id) {
|
|
44
|
+
return join(musicJobsRoot(), id);
|
|
45
|
+
}
|
|
46
|
+
export function musicJobFile(id) {
|
|
47
|
+
return join(musicJobDir(id), "job.json");
|
|
48
|
+
}
|
|
49
|
+
/** 任务内相对路径 → 绝对路径,并挡住目录穿越。 */
|
|
50
|
+
export function musicAssetPath(id, relative) {
|
|
51
|
+
const base = resolve(musicJobDir(id));
|
|
52
|
+
const target = resolve(base, relative);
|
|
53
|
+
if (target !== base && !target.startsWith(base + sep))
|
|
54
|
+
throw new Error(`非法的任务内路径:${relative}`);
|
|
55
|
+
return target;
|
|
56
|
+
}
|
|
57
|
+
export function isValidMusicJobId(id) {
|
|
58
|
+
return JOB_ID_PATTERN.test(id);
|
|
59
|
+
}
|
|
60
|
+
function assertJobId(id) {
|
|
61
|
+
if (!isValidMusicJobId(id))
|
|
62
|
+
throw new Error(`非法音乐任务 id:${id}`);
|
|
63
|
+
}
|
|
64
|
+
function logOf(job) {
|
|
65
|
+
if (!Array.isArray(job.log))
|
|
66
|
+
job.log = [];
|
|
67
|
+
return job.log;
|
|
68
|
+
}
|
|
69
|
+
export function musicLog(job, level, message) {
|
|
70
|
+
appendJobLog(logOf(job), level, message);
|
|
71
|
+
}
|
|
72
|
+
function now() {
|
|
73
|
+
return Date.now();
|
|
74
|
+
}
|
|
75
|
+
function clampString(value, max = 20000) {
|
|
76
|
+
return typeof value === "string" ? value.slice(0, max) : "";
|
|
77
|
+
}
|
|
78
|
+
/** 用户输入的归一化:原文保留,扩写结果单独存。 */
|
|
79
|
+
export function normalizeMusicSource(input) {
|
|
80
|
+
const raw = (input ?? {});
|
|
81
|
+
const kind = raw.kind === "lyrics" ? "lyrics" : "prompt";
|
|
82
|
+
const prompt = clampString(raw.prompt);
|
|
83
|
+
const lyrics = clampString(raw.lyrics);
|
|
84
|
+
return {
|
|
85
|
+
kind,
|
|
86
|
+
prompt,
|
|
87
|
+
lyrics,
|
|
88
|
+
note: clampString(raw.note, 4000),
|
|
89
|
+
title: clampString(raw.title, 200),
|
|
90
|
+
tags: clampString(raw.tags, 4000),
|
|
91
|
+
instrumental: raw.instrumental === true,
|
|
92
|
+
preferredEngine: isMusicEngine(raw.preferredEngine) ? raw.preferredEngine : undefined,
|
|
93
|
+
adaptedPrompt: typeof raw.adaptedPrompt === "string" ? clampString(raw.adaptedPrompt) : undefined,
|
|
94
|
+
adaptedLyrics: typeof raw.adaptedLyrics === "string" ? clampString(raw.adaptedLyrics) : undefined,
|
|
95
|
+
adaptedTags: typeof raw.adaptedTags === "string" ? clampString(raw.adaptedTags) : undefined,
|
|
96
|
+
adaptedNote: typeof raw.adaptedNote === "string" ? clampString(raw.adaptedNote, 4000) : undefined
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/** 任务设置归一化:引擎/模式/模型给默认值,其余可选字段只保留合法值。 */
|
|
100
|
+
export function normalizeMusicSettings(input, source) {
|
|
101
|
+
const raw = (input ?? {});
|
|
102
|
+
const engine = isMusicEngine(raw.engine)
|
|
103
|
+
? raw.engine
|
|
104
|
+
: source?.preferredEngine ?? "suno";
|
|
105
|
+
const preset = enginePresetOf(engine);
|
|
106
|
+
const mode = isMusicMode(raw.mode) && preset.modes.some((entry) => entry.id === raw.mode)
|
|
107
|
+
? raw.mode
|
|
108
|
+
: preset.modes[0].id;
|
|
109
|
+
const requestedModel = typeof raw.model === "string" && raw.model.trim() !== "" ? raw.model.trim() : defaultModelOf(engine);
|
|
110
|
+
// 切引擎时旧模型可能不属于新引擎:别把非法值留在设置里,回落到该引擎默认模型。
|
|
111
|
+
const model = preset.models.some((entry) => entry.id === requestedModel) ? requestedModel : defaultModelOf(engine);
|
|
112
|
+
const out = { engine, mode, model };
|
|
113
|
+
const putNum = (key, value, min, max) => {
|
|
114
|
+
const n = typeof value === "number" ? value : Number.parseFloat(String(value ?? ""));
|
|
115
|
+
if (Number.isFinite(n))
|
|
116
|
+
out[key] = Math.min(max, Math.max(min, n));
|
|
117
|
+
};
|
|
118
|
+
if (raw.n !== undefined)
|
|
119
|
+
putNum("n", raw.n, 1, 3);
|
|
120
|
+
if (typeof raw.vocalGender === "string")
|
|
121
|
+
out.vocalGender = raw.vocalGender;
|
|
122
|
+
if (typeof raw.negativeTags === "string")
|
|
123
|
+
out.negativeTags = clampString(raw.negativeTags, 2000);
|
|
124
|
+
putNum("styleWeight", raw.styleWeight, 0, 1);
|
|
125
|
+
putNum("weirdness", raw.weirdness, 0, 1);
|
|
126
|
+
putNum("duration", raw.duration, 10, 360);
|
|
127
|
+
putNum("augCreativity", raw.augCreativity, 0, 4);
|
|
128
|
+
putNum("bpm", raw.bpm, 30, 300);
|
|
129
|
+
putNum("sampleRate", raw.sampleRate, 8000, 192000);
|
|
130
|
+
putNum("bitrate", raw.bitrate, 8000, 512000);
|
|
131
|
+
if (typeof raw.isMaxMode === "boolean")
|
|
132
|
+
out.isMaxMode = raw.isMaxMode;
|
|
133
|
+
if (typeof raw.vocalLanguage === "string")
|
|
134
|
+
out.vocalLanguage = raw.vocalLanguage;
|
|
135
|
+
if (typeof raw.keyScale === "string")
|
|
136
|
+
out.keyScale = raw.keyScale;
|
|
137
|
+
if (typeof raw.timeSignature === "string")
|
|
138
|
+
out.timeSignature = raw.timeSignature;
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
function summarizeSource(source) {
|
|
142
|
+
const text = source.kind === "lyrics" ? source.lyrics : source.prompt;
|
|
143
|
+
const flat = text.replace(/\s+/gu, " ").trim();
|
|
144
|
+
return flat === "" ? "未命名音乐" : flat.slice(0, 80);
|
|
145
|
+
}
|
|
146
|
+
function deriveMusicName(source) {
|
|
147
|
+
const text = source.kind === "lyrics" ? source.lyrics : source.prompt;
|
|
148
|
+
const flat = text.replace(/\s+/gu, " ").trim();
|
|
149
|
+
if (flat === "")
|
|
150
|
+
return "音乐任务";
|
|
151
|
+
return flat.slice(0, 20);
|
|
152
|
+
}
|
|
153
|
+
export async function createMusicJob(input = {}) {
|
|
154
|
+
const source = normalizeMusicSource(input.source);
|
|
155
|
+
const name = (typeof input.name === "string" && input.name.trim() !== "" ? input.name.trim() : deriveMusicName(source)).slice(0, 80);
|
|
156
|
+
const id = `a${Date.now().toString(36)}${randomUUID().slice(0, 6)}`;
|
|
157
|
+
const timestamp = now();
|
|
158
|
+
const workflow = input.workflow === "compose" ? "compose" : "generate";
|
|
159
|
+
const job = {
|
|
160
|
+
id,
|
|
161
|
+
name,
|
|
162
|
+
createdAt: timestamp,
|
|
163
|
+
updatedAt: timestamp,
|
|
164
|
+
workflow,
|
|
165
|
+
source,
|
|
166
|
+
settings: normalizeMusicSettings(input.settings, source),
|
|
167
|
+
reviewMode: input.reviewMode === "manual" ? "manual" : input.reviewMode === "auto" ? "auto" : undefined,
|
|
168
|
+
stages: {
|
|
169
|
+
compose: { status: "idle" },
|
|
170
|
+
generate: { status: "idle" },
|
|
171
|
+
edit: { status: "idle" },
|
|
172
|
+
export: { status: "idle" }
|
|
173
|
+
},
|
|
174
|
+
compositions: [],
|
|
175
|
+
generations: [],
|
|
176
|
+
songs: [],
|
|
177
|
+
versions: [],
|
|
178
|
+
tools: [],
|
|
179
|
+
exports: [],
|
|
180
|
+
log: []
|
|
181
|
+
};
|
|
182
|
+
for (const sub of ["songs", "versions", "peaks", "tools", "out", "scores"]) {
|
|
183
|
+
await mkdir(join(musicJobDir(id), sub), { recursive: true });
|
|
184
|
+
}
|
|
185
|
+
musicLog(job, "info", `新建音乐任务:${name}(${workflow === "compose" ? "谱曲模式" : source.kind === "lyrics" ? "完整歌词" : "灵感提示词"})`);
|
|
186
|
+
await writeJsonAtomic(musicJobFile(id), job);
|
|
187
|
+
return job;
|
|
188
|
+
}
|
|
189
|
+
export async function readMusicJob(id) {
|
|
190
|
+
if (!isValidMusicJobId(id))
|
|
191
|
+
return undefined;
|
|
192
|
+
const job = await readJson(musicJobFile(id));
|
|
193
|
+
if (job === undefined || job === null || typeof job !== "object")
|
|
194
|
+
return undefined;
|
|
195
|
+
job.songs = Array.isArray(job.songs) ? job.songs : [];
|
|
196
|
+
job.generations = Array.isArray(job.generations) ? job.generations : [];
|
|
197
|
+
job.versions = Array.isArray(job.versions) ? job.versions : [];
|
|
198
|
+
job.tools = Array.isArray(job.tools) ? job.tools : [];
|
|
199
|
+
job.exports = Array.isArray(job.exports) ? job.exports : [];
|
|
200
|
+
job.log = Array.isArray(job.log) ? job.log : [];
|
|
201
|
+
job.workflow = job.workflow === "compose" ? "compose" : "generate";
|
|
202
|
+
job.compositions = Array.isArray(job.compositions) ? job.compositions : [];
|
|
203
|
+
const stages = (job.stages ?? {});
|
|
204
|
+
for (const stage of MUSIC_STAGES) {
|
|
205
|
+
if (stages[stage] === undefined || stages[stage] === null)
|
|
206
|
+
stages[stage] = { status: "idle" };
|
|
207
|
+
}
|
|
208
|
+
job.stages = stages;
|
|
209
|
+
// 老任务没有 compose 字段;readMusicJob 已经补上,这里只保证类型完整。
|
|
210
|
+
if (job.scorePlan !== undefined && job.scorePlan !== null && typeof job.scorePlan !== "object")
|
|
211
|
+
job.scorePlan = undefined;
|
|
212
|
+
if (typeof job.currentScoreId === "string" && !job.compositions.some((entry) => entry.id === job.currentScoreId))
|
|
213
|
+
job.currentScoreId = undefined;
|
|
214
|
+
return job;
|
|
215
|
+
}
|
|
216
|
+
export async function writeMusicJob(job) {
|
|
217
|
+
assertJobId(job.id);
|
|
218
|
+
await writeJsonAtomic(musicJobFile(job.id), job);
|
|
219
|
+
}
|
|
220
|
+
const jobQueues = new Map();
|
|
221
|
+
/**
|
|
222
|
+
* 按任务串行地读-改-写。所有写入口都必须走它。
|
|
223
|
+
*
|
|
224
|
+
* 不串行的话,轮询器刚读到旧 job、用户同时改名,两边各写一次,后写的会把
|
|
225
|
+
* 前一次的改动覆盖掉——表现是「改了名字过一会儿又变回去」。
|
|
226
|
+
*/
|
|
227
|
+
export function patchMusicJob(id, mutator) {
|
|
228
|
+
assertJobId(id);
|
|
229
|
+
const previous = jobQueues.get(id) ?? Promise.resolve();
|
|
230
|
+
const result = previous
|
|
231
|
+
.catch(() => undefined)
|
|
232
|
+
.then(async () => {
|
|
233
|
+
const job = await readMusicJob(id);
|
|
234
|
+
if (job === undefined)
|
|
235
|
+
throw new Error(`音乐任务不存在:${id}`);
|
|
236
|
+
const value = await mutator(job);
|
|
237
|
+
job.updatedAt = now();
|
|
238
|
+
await writeJsonAtomic(musicJobFile(id), job);
|
|
239
|
+
return value;
|
|
240
|
+
});
|
|
241
|
+
jobQueues.set(id, result.then(() => undefined, () => undefined));
|
|
242
|
+
return result;
|
|
243
|
+
}
|
|
244
|
+
export async function listMusicJobs() {
|
|
245
|
+
const root = musicJobsRoot();
|
|
246
|
+
let names;
|
|
247
|
+
try {
|
|
248
|
+
names = await readdir(root);
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
return [];
|
|
252
|
+
}
|
|
253
|
+
const jobs = [];
|
|
254
|
+
for (const name of names) {
|
|
255
|
+
if (!isValidMusicJobId(name))
|
|
256
|
+
continue;
|
|
257
|
+
const job = await readMusicJob(name);
|
|
258
|
+
if (job === undefined)
|
|
259
|
+
continue;
|
|
260
|
+
jobs.push(summarizeMusicJob(job));
|
|
261
|
+
}
|
|
262
|
+
jobs.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
263
|
+
return jobs;
|
|
264
|
+
}
|
|
265
|
+
export function summarizeMusicJob(job) {
|
|
266
|
+
const ready = job.songs.filter((song) => song.status === "succeeded");
|
|
267
|
+
return {
|
|
268
|
+
id: job.id,
|
|
269
|
+
name: job.name,
|
|
270
|
+
createdAt: job.createdAt,
|
|
271
|
+
updatedAt: job.updatedAt,
|
|
272
|
+
workflow: job.workflow,
|
|
273
|
+
songsReady: ready.length,
|
|
274
|
+
songsTotal: job.songs.length,
|
|
275
|
+
versions: job.versions.filter((version) => version.status === "ready").length,
|
|
276
|
+
compositions: job.compositions.filter((entry) => entry.status === "ready").length,
|
|
277
|
+
engines: [...new Set(job.songs.map((song) => song.engine))],
|
|
278
|
+
busy: musicBusy(job.id, job),
|
|
279
|
+
reviewMode: job.reviewMode,
|
|
280
|
+
coverFile: ready.find((song) => typeof song.coverFile === "string")?.coverFile
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
export async function deleteMusicJob(id) {
|
|
284
|
+
assertJobId(id);
|
|
285
|
+
for (const [key, controller] of [...controllers.entries()]) {
|
|
286
|
+
if (key.startsWith(`${id}:`)) {
|
|
287
|
+
controller.abort();
|
|
288
|
+
controllers.delete(key);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
cancelMusicGeneration(id);
|
|
292
|
+
scoreRuns.delete(id);
|
|
293
|
+
await rm(musicJobDir(id), { recursive: true, force: true });
|
|
294
|
+
jobQueues.delete(id);
|
|
295
|
+
}
|
|
296
|
+
export function musicBusy(id, job) {
|
|
297
|
+
if (scoreRuns.has(id))
|
|
298
|
+
return true;
|
|
299
|
+
if ((running.get(id)?.size ?? 0) > 0)
|
|
300
|
+
return true;
|
|
301
|
+
if (job === undefined)
|
|
302
|
+
return false;
|
|
303
|
+
if (job.generations.some((generation) => generation.status === "submitting" || generation.status === "polling"))
|
|
304
|
+
return true;
|
|
305
|
+
// ⚠️ 不要把「歌曲还是 pending」单独算忙:等待超时后 generation 已标成 timeout,
|
|
306
|
+
// 但平台仍可能在跑;这时 busy 必须是 false,界面才能刷新/补查,而不是永远转圈。
|
|
307
|
+
if (job.tools.some((tool) => tool.status === "submitting" || tool.status === "polling"))
|
|
308
|
+
return true;
|
|
309
|
+
if (job.versions.some((version) => version.status === "rendering"))
|
|
310
|
+
return true;
|
|
311
|
+
return false;
|
|
312
|
+
}
|
|
313
|
+
// ── 后台任务表 ──────────────────────────────────────────────────────────
|
|
314
|
+
const running = new Map();
|
|
315
|
+
const controllers = new Map();
|
|
316
|
+
/** 正在跑谱曲脚本的 job(runMusicScore 是同步的,用一个集合挡住并发)。 */
|
|
317
|
+
const scoreRuns = new Set();
|
|
318
|
+
let disposed = false;
|
|
319
|
+
/** DSH 重载插件时模块级 disposed 会留着,apply 时靠它复位。 */
|
|
320
|
+
export function activateMusic() {
|
|
321
|
+
disposed = false;
|
|
322
|
+
running.clear();
|
|
323
|
+
scoreRuns.clear();
|
|
324
|
+
for (const controller of controllers.values())
|
|
325
|
+
controller.abort();
|
|
326
|
+
controllers.clear();
|
|
327
|
+
}
|
|
328
|
+
export function disposeMusic() {
|
|
329
|
+
disposed = true;
|
|
330
|
+
for (const controller of controllers.values())
|
|
331
|
+
controller.abort();
|
|
332
|
+
controllers.clear();
|
|
333
|
+
running.clear();
|
|
334
|
+
scoreRuns.clear();
|
|
335
|
+
}
|
|
336
|
+
function trackMusicTask(id, key, run) {
|
|
337
|
+
if (disposed)
|
|
338
|
+
return false;
|
|
339
|
+
const set = running.get(id) ?? new Set();
|
|
340
|
+
if (set.has(key))
|
|
341
|
+
return false;
|
|
342
|
+
running.set(id, set);
|
|
343
|
+
set.add(key);
|
|
344
|
+
const controller = new AbortController();
|
|
345
|
+
controllers.set(`${id}:${key}`, controller);
|
|
346
|
+
void run()
|
|
347
|
+
.catch((error) => {
|
|
348
|
+
musicLogSafe(id, "error", `${key} 失败:${messageOf(error)}`);
|
|
349
|
+
})
|
|
350
|
+
.finally(() => {
|
|
351
|
+
set.delete(key);
|
|
352
|
+
controllers.delete(`${id}:${key}`);
|
|
353
|
+
if (set.size === 0 && running.get(id) === set)
|
|
354
|
+
running.delete(id);
|
|
355
|
+
});
|
|
356
|
+
return true;
|
|
357
|
+
}
|
|
358
|
+
function musicLogSafe(id, level, message) {
|
|
359
|
+
void patchMusicJob(id, (job) => musicLog(job, level, message)).catch(() => undefined);
|
|
360
|
+
}
|
|
361
|
+
function sleep(ms, signal) {
|
|
362
|
+
return new Promise((resolve, reject) => {
|
|
363
|
+
if (signal?.aborted === true) {
|
|
364
|
+
reject(new Error("已取消"));
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
const timer = setTimeout(() => {
|
|
368
|
+
signal?.removeEventListener?.("abort", onAbort);
|
|
369
|
+
resolve();
|
|
370
|
+
}, ms);
|
|
371
|
+
const onAbort = () => {
|
|
372
|
+
clearTimeout(timer);
|
|
373
|
+
reject(new Error("已取消"));
|
|
374
|
+
};
|
|
375
|
+
signal?.addEventListener?.("abort", onAbort, { once: true });
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
function apiConfigOf(config) {
|
|
379
|
+
return {
|
|
380
|
+
baseUrl: config.musicBaseUrl,
|
|
381
|
+
apiKey: config.musicApiKey,
|
|
382
|
+
timeoutMs: config.musicTimeoutMs
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
async function requireApi() {
|
|
386
|
+
const config = await loadConfig();
|
|
387
|
+
const blocker = musicBlocker(config);
|
|
388
|
+
if (blocker !== undefined)
|
|
389
|
+
throw new MusicApiError(blocker);
|
|
390
|
+
return apiConfigOf(config);
|
|
391
|
+
}
|
|
392
|
+
// ── 任务视图 ────────────────────────────────────────────────────────────
|
|
393
|
+
export function musicAssetBase(id) {
|
|
394
|
+
return assetBasePath(`/dsh-game-material-master/music-assets/${id}/`);
|
|
395
|
+
}
|
|
396
|
+
function absUrl(origin, assetBase, relative) {
|
|
397
|
+
if (typeof relative !== "string" || relative === "")
|
|
398
|
+
return undefined;
|
|
399
|
+
return `${origin}${assetBase}${relative.split("/").map(encodeURIComponent).join("/")}`;
|
|
400
|
+
}
|
|
401
|
+
export async function musicSnapshot(job, origin = originForLinks()) {
|
|
402
|
+
const config = await loadConfig();
|
|
403
|
+
const assetBase = musicAssetBase(job.id);
|
|
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
|
+
});
|
|
422
|
+
const versions = job.versions.map((version) => ({
|
|
423
|
+
...version,
|
|
424
|
+
url: absUrl(origin, assetBase, version.file) ?? null
|
|
425
|
+
}));
|
|
426
|
+
const tools = job.tools.map((tool) => ({
|
|
427
|
+
...tool,
|
|
428
|
+
files: (tool.files ?? []).map((file) => ({ ...file, url: absUrl(origin, assetBase, file.file) ?? null }))
|
|
429
|
+
}));
|
|
430
|
+
const exports = job.exports.map((entry) => ({
|
|
431
|
+
...entry,
|
|
432
|
+
url: absUrl(origin, assetBase, entry.file) ?? null,
|
|
433
|
+
downloadUrl: absUrl(origin, assetBase, entry.file) === undefined ? null : `${absUrl(origin, assetBase, entry.file)}?download=1`
|
|
434
|
+
}));
|
|
435
|
+
const compositions = job.compositions.map((entry) => ({
|
|
436
|
+
...entry,
|
|
437
|
+
midiUrl: absUrl(origin, assetBase, entry.midiFile) ?? null,
|
|
438
|
+
audioUrl: absUrl(origin, assetBase, entry.audioFile) ?? null,
|
|
439
|
+
scriptUrl: absUrl(origin, assetBase, entry.scriptFile) ?? null
|
|
440
|
+
}));
|
|
441
|
+
return {
|
|
442
|
+
module: "music",
|
|
443
|
+
id: job.id,
|
|
444
|
+
name: job.name,
|
|
445
|
+
dir: musicJobDir(job.id),
|
|
446
|
+
assetBase,
|
|
447
|
+
createdAt: job.createdAt,
|
|
448
|
+
updatedAt: job.updatedAt,
|
|
449
|
+
workflow: job.workflow,
|
|
450
|
+
reviewMode: job.reviewMode ?? null,
|
|
451
|
+
busy: musicBusy(job.id, job),
|
|
452
|
+
blocker: musicBlocker(config) ?? null,
|
|
453
|
+
source: job.source,
|
|
454
|
+
settings: job.settings,
|
|
455
|
+
scorePlan: job.scorePlan ?? null,
|
|
456
|
+
currentScoreId: job.currentScoreId ?? null,
|
|
457
|
+
compositions,
|
|
458
|
+
stages: job.stages,
|
|
459
|
+
generations: job.generations.map((generation) => ({
|
|
460
|
+
...generation,
|
|
461
|
+
// 请求体里可能有歌词,保留;但永远不会有 Key(Key 只在请求头里)。
|
|
462
|
+
request: generation.request
|
|
463
|
+
})),
|
|
464
|
+
songs,
|
|
465
|
+
versions,
|
|
466
|
+
tools,
|
|
467
|
+
exports,
|
|
468
|
+
songsReady: songs.filter((song) => song.status === "succeeded").length,
|
|
469
|
+
songsTotal: songs.length,
|
|
470
|
+
log: job.log.slice(-30)
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
function pickParam(params, ...keys) {
|
|
474
|
+
for (const key of keys) {
|
|
475
|
+
if (params[key] !== undefined && params[key] !== null && params[key] !== "")
|
|
476
|
+
return params[key];
|
|
477
|
+
}
|
|
478
|
+
return undefined;
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* 把任务里的原文 / 设置与本次覆盖参数合并成 API 请求。
|
|
482
|
+
*
|
|
483
|
+
* 兼容 camelCase 与 snake_case:agent 可能照着 API 文档写 `cover_clip_id`,
|
|
484
|
+
* 也可能照着工具描述写 `coverClipId`;两种都收,只认一套内部字段。
|
|
485
|
+
*/
|
|
486
|
+
function mergeGenerationInput(job, input) {
|
|
487
|
+
const params = input.params ?? {};
|
|
488
|
+
const engine = isMusicEngine(input.engine) ? input.engine : job.settings.engine;
|
|
489
|
+
const preset = enginePresetOf(engine);
|
|
490
|
+
const mode = isMusicMode(input.mode) && preset.modes.some((entry) => entry.id === input.mode)
|
|
491
|
+
? input.mode
|
|
492
|
+
: job.settings.mode;
|
|
493
|
+
const source = job.source;
|
|
494
|
+
const settings = job.settings;
|
|
495
|
+
const explicitModel = typeof input.model === "string" && input.model.trim() !== "" ? input.model.trim() : "";
|
|
496
|
+
const jobModel = job.settings.model || "";
|
|
497
|
+
const model = explicitModel !== ""
|
|
498
|
+
? explicitModel
|
|
499
|
+
: engine !== job.settings.engine && !enginePresetOf(engine).models.some((entry) => entry.id === jobModel)
|
|
500
|
+
? defaultModelOf(engine)
|
|
501
|
+
: jobModel || defaultModelOf(engine);
|
|
502
|
+
const requestInput = {
|
|
503
|
+
engine,
|
|
504
|
+
mode,
|
|
505
|
+
model,
|
|
506
|
+
title: pickParam(params, "title") ?? (source.title || job.name),
|
|
507
|
+
prompt: pickParam(params, "prompt") ?? (source.adaptedPrompt || source.prompt),
|
|
508
|
+
lyrics: pickParam(params, "lyrics") ?? (source.adaptedLyrics || source.lyrics),
|
|
509
|
+
tags: pickParam(params, "tags") ?? (source.adaptedTags || source.tags),
|
|
510
|
+
instrumental: typeof pickParam(params, "instrumental") === "boolean" ? pickParam(params, "instrumental") : source.instrumental,
|
|
511
|
+
n: pickParam(params, "n") ?? settings.n,
|
|
512
|
+
vocalGender: pickParam(params, "vocalGender", "vocal_gender") ?? settings.vocalGender,
|
|
513
|
+
negativeTags: pickParam(params, "negativeTags", "negative_tags") ?? settings.negativeTags,
|
|
514
|
+
styleWeight: pickParam(params, "styleWeight", "style_weight") ?? settings.styleWeight,
|
|
515
|
+
weirdness: pickParam(params, "weirdness", "weirdness_constraint") ?? settings.weirdness,
|
|
516
|
+
duration: pickParam(params, "duration") ?? settings.duration,
|
|
517
|
+
isMaxMode: pickParam(params, "isMaxMode", "is_max_mode") ?? settings.isMaxMode,
|
|
518
|
+
augCreativity: pickParam(params, "augCreativity", "aug_creativity") ?? settings.augCreativity,
|
|
519
|
+
vocalLanguage: pickParam(params, "vocalLanguage", "vocal_language") ?? settings.vocalLanguage,
|
|
520
|
+
bpm: pickParam(params, "bpm") ?? settings.bpm,
|
|
521
|
+
keyScale: pickParam(params, "keyScale", "key_scale") ?? settings.keyScale,
|
|
522
|
+
timeSignature: pickParam(params, "timeSignature", "time_signature") ?? settings.timeSignature,
|
|
523
|
+
sampleRate: pickParam(params, "sampleRate", "sample_rate") ?? settings.sampleRate,
|
|
524
|
+
bitrate: pickParam(params, "bitrate") ?? settings.bitrate,
|
|
525
|
+
coverClipId: pickParam(params, "coverClipId", "cover_clip_id"),
|
|
526
|
+
sourceSongId: pickParam(params, "sourceSongId", "source_clip_id"),
|
|
527
|
+
audioWeight: pickParam(params, "audioWeight", "audio_weight"),
|
|
528
|
+
continueClipId: pickParam(params, "continueClipId", "continue_clip_id"),
|
|
529
|
+
continueAt: pickParam(params, "continueAt", "continue_at"),
|
|
530
|
+
startTime: pickParam(params, "startTime", "start_time"),
|
|
531
|
+
endTime: pickParam(params, "endTime", "end_time"),
|
|
532
|
+
clipId: pickParam(params, "clipId", "clip_id"),
|
|
533
|
+
sourceSongIds: (() => {
|
|
534
|
+
const raw = pickParam(params, "sourceSongIds", "source_clip_ids");
|
|
535
|
+
if (Array.isArray(raw))
|
|
536
|
+
return raw.map(String);
|
|
537
|
+
if (typeof raw === "string" && raw.trim() !== "")
|
|
538
|
+
return raw.split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
539
|
+
return undefined;
|
|
540
|
+
})()
|
|
541
|
+
};
|
|
542
|
+
return { requestInput, engine, mode };
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* 提交一次生成。★计费。
|
|
546
|
+
*
|
|
547
|
+
* 两道闸:同任务已有任务在跑拒绝;已有歌曲时再提交必须 `regenerate:true`。
|
|
548
|
+
* 两条都是为了「不为确认状态白花一次积分」。
|
|
549
|
+
*/
|
|
550
|
+
export async function startMusicGeneration(id, input = {}) {
|
|
551
|
+
assertJobId(id);
|
|
552
|
+
const job = await readMusicJob(id);
|
|
553
|
+
if (job === undefined)
|
|
554
|
+
throw new Error(`音乐任务不存在:${id}`);
|
|
555
|
+
if (musicBusy(id, job))
|
|
556
|
+
return { started: false, reason: "这个任务已有生成/编辑任务在跑,等它结束再提交(重复提交会重复计费)。" };
|
|
557
|
+
if (job.songs.some((song) => song.status === "succeeded") && input.regenerate !== true) {
|
|
558
|
+
return {
|
|
559
|
+
started: false,
|
|
560
|
+
reason: "这个任务已经有歌曲了。再生成一批会再计费;确认要重做请传 regenerate:true。"
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
const { requestInput, engine, mode } = mergeGenerationInput(job, input);
|
|
564
|
+
const request = buildGenerationRequest(requestInput);
|
|
565
|
+
const generationId = `g${Date.now().toString(36)}${randomUUID().slice(0, 6)}`;
|
|
566
|
+
const startedAt = now();
|
|
567
|
+
await patchMusicJob(id, (current) => {
|
|
568
|
+
current.settings = { ...current.settings, engine, mode, model: requestInput.model ?? current.settings.model };
|
|
569
|
+
current.generations.push({
|
|
570
|
+
id: generationId,
|
|
571
|
+
engine,
|
|
572
|
+
mode,
|
|
573
|
+
model: requestInput.model ?? defaultModelOf(engine),
|
|
574
|
+
endpoint: request.endpoint,
|
|
575
|
+
summary: request.summary,
|
|
576
|
+
request: request.body,
|
|
577
|
+
...(typeof input.scoreId === "string" && input.scoreId !== "" ? { scoreId: input.scoreId } : {}),
|
|
578
|
+
...(typeof input.sourceClipId === "string" && input.sourceClipId !== "" ? { sourceClipId: input.sourceClipId } : {}),
|
|
579
|
+
status: "submitting",
|
|
580
|
+
songIds: [],
|
|
581
|
+
startedAt,
|
|
582
|
+
updatedAt: startedAt
|
|
583
|
+
});
|
|
584
|
+
current.stages.generate = { status: "running", at: startedAt };
|
|
585
|
+
musicLog(current, "info", `提交生成:${request.summary}`);
|
|
586
|
+
});
|
|
587
|
+
const ok = trackMusicTask(id, "generation", () => runGeneration(id, generationId, request));
|
|
588
|
+
if (!ok) {
|
|
589
|
+
await patchMusicJob(id, (current) => {
|
|
590
|
+
const generation = current.generations.find((entry) => entry.id === generationId);
|
|
591
|
+
if (generation !== undefined) {
|
|
592
|
+
generation.status = "failed";
|
|
593
|
+
generation.error = "后台任务没有启动(插件正在重载?)";
|
|
594
|
+
generation.updatedAt = now();
|
|
595
|
+
}
|
|
596
|
+
current.stages.generate = { status: "error", error: "后台任务没有启动", at: now() };
|
|
597
|
+
});
|
|
598
|
+
return { started: false, reason: "后台任务没有启动,请重启插件后再试。" };
|
|
599
|
+
}
|
|
600
|
+
return { started: true, generationId };
|
|
601
|
+
}
|
|
602
|
+
async function runGeneration(id, generationId, request) {
|
|
603
|
+
const config = await loadConfig();
|
|
604
|
+
const api = apiConfigOf(config);
|
|
605
|
+
const controller = controllers.get(`${id}:generation`);
|
|
606
|
+
const deadline = now() + Math.max(60000, config.musicPollTimeoutMs || 900000);
|
|
607
|
+
let submitted;
|
|
608
|
+
try {
|
|
609
|
+
submitted = await submitGeneration(api, request);
|
|
610
|
+
}
|
|
611
|
+
catch (error) {
|
|
612
|
+
await patchMusicJob(id, (job) => {
|
|
613
|
+
const generation = job.generations.find((entry) => entry.id === generationId);
|
|
614
|
+
if (generation !== undefined) {
|
|
615
|
+
generation.status = "failed";
|
|
616
|
+
generation.error = messageOf(error);
|
|
617
|
+
generation.updatedAt = now();
|
|
618
|
+
}
|
|
619
|
+
job.stages.generate = { status: "error", error: messageOf(error), at: now() };
|
|
620
|
+
musicLog(job, "error", `提交失败:${messageOf(error)}`);
|
|
621
|
+
});
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
await patchMusicJob(id, (job) => {
|
|
625
|
+
const generation = job.generations.find((entry) => entry.id === generationId);
|
|
626
|
+
if (generation === undefined)
|
|
627
|
+
return;
|
|
628
|
+
generation.status = "polling";
|
|
629
|
+
generation.taskId = submitted.taskId;
|
|
630
|
+
generation.songIds = submitted.songs.map((song) => song.id);
|
|
631
|
+
generation.updatedAt = now();
|
|
632
|
+
for (const payload of submitted.songs) {
|
|
633
|
+
const existing = job.songs.find((song) => song.id === payload.id);
|
|
634
|
+
if (existing === undefined) {
|
|
635
|
+
job.songs.push(songFromPayload(payload, generation.engine, generationId));
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
musicLog(job, "info", `已提交:${submitted.songs.length} 首(task ${submitted.taskId ?? "—"})`);
|
|
639
|
+
});
|
|
640
|
+
const songIds = submitted.songs.map((song) => song.id);
|
|
641
|
+
let lastError;
|
|
642
|
+
for (;;) {
|
|
643
|
+
if (controller?.signal.aborted === true) {
|
|
644
|
+
await patchMusicJob(id, (job) => {
|
|
645
|
+
const generation = job.generations.find((entry) => entry.id === generationId);
|
|
646
|
+
if (generation !== undefined) {
|
|
647
|
+
generation.status = "canceled";
|
|
648
|
+
generation.updatedAt = now();
|
|
649
|
+
}
|
|
650
|
+
musicLog(job, "warn", "已停止本地轮询;已提交的远端生成仍可能完成并计费。");
|
|
651
|
+
});
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
if (now() >= deadline) {
|
|
655
|
+
await patchMusicJob(id, (job) => {
|
|
656
|
+
const generation = job.generations.find((entry) => entry.id === generationId);
|
|
657
|
+
if (generation !== undefined) {
|
|
658
|
+
generation.status = "timeout";
|
|
659
|
+
generation.error = `等待超时(${Math.round((config.musicPollTimeoutMs || 900000) / 1000)} 秒);可以 refreshMusicJob 继续查询。`;
|
|
660
|
+
generation.updatedAt = now();
|
|
661
|
+
}
|
|
662
|
+
job.stages.generate = { status: "error", error: generation?.error ?? "等待超时", at: now() };
|
|
663
|
+
musicLog(job, "warn", `等待超时:${generationId}(可 refreshMusicJob 继续)`);
|
|
664
|
+
});
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
let payloads = [];
|
|
668
|
+
try {
|
|
669
|
+
payloads = await querySongs(api, songIds);
|
|
670
|
+
}
|
|
671
|
+
catch (error) {
|
|
672
|
+
if (error instanceof MusicApiError && error.status === 429) {
|
|
673
|
+
await sleep(15000, controller?.signal);
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
lastError = messageOf(error);
|
|
677
|
+
// 查询失败不立刻判死:可能是网络抖动,继续重试到 deadline。
|
|
678
|
+
musicLogSafe(id, "warn", `查询失败,稍后重试:${lastError}`);
|
|
679
|
+
await sleep(8000, controller?.signal);
|
|
680
|
+
continue;
|
|
681
|
+
}
|
|
682
|
+
if (payloads.length > 0) {
|
|
683
|
+
await patchMusicJob(id, (job) => {
|
|
684
|
+
const generation = job.generations.find((entry) => entry.id === generationId);
|
|
685
|
+
for (const payload of payloads) {
|
|
686
|
+
const song = job.songs.find((entry) => entry.id === payload.id);
|
|
687
|
+
if (song === undefined) {
|
|
688
|
+
job.songs.push(songFromPayload(payload, generation?.engine ?? "suno", generationId));
|
|
689
|
+
}
|
|
690
|
+
else {
|
|
691
|
+
applySongPayload(song, payload);
|
|
692
|
+
song.generationId = generationId;
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
const jobNow = await readMusicJob(id);
|
|
698
|
+
const songs = jobNow?.songs.filter((song) => songIds.includes(song.id)) ?? [];
|
|
699
|
+
// 先到先下载:即使另一首还没完成,用户也能先试听已完成的那首。
|
|
700
|
+
for (const song of songs.filter((entry) => entry.status === "succeeded" && !localSongUsable(id, entry.localFile))) {
|
|
701
|
+
await ensureLocalSong(id, song.id).catch((error) => {
|
|
702
|
+
void patchMusicJob(id, (job) => {
|
|
703
|
+
const entry = job.songs.find((item) => item.id === song.id);
|
|
704
|
+
if (entry !== undefined)
|
|
705
|
+
entry.downloadError = messageOf(error);
|
|
706
|
+
});
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
const succeeded = songs.filter((song) => song.status === "succeeded");
|
|
710
|
+
const failed = songs.filter((song) => song.status === "failed");
|
|
711
|
+
if (songs.length > 0 && songs.every((song) => song.status === "succeeded" || song.status === "failed")) {
|
|
712
|
+
for (const song of succeeded) {
|
|
713
|
+
if (!localSongUsable(id, song.localFile)) {
|
|
714
|
+
try {
|
|
715
|
+
await ensureLocalSong(id, song.id);
|
|
716
|
+
}
|
|
717
|
+
catch (error) {
|
|
718
|
+
await patchMusicJob(id, (job) => {
|
|
719
|
+
const entry = job.songs.find((item) => item.id === song.id);
|
|
720
|
+
if (entry !== undefined)
|
|
721
|
+
entry.downloadError = messageOf(error);
|
|
722
|
+
musicLog(job, "warn", `歌曲 ${song.id} 下载失败:${messageOf(error)}`);
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
await patchMusicJob(id, (job) => {
|
|
728
|
+
const generation = job.generations.find((entry) => entry.id === generationId);
|
|
729
|
+
if (generation !== undefined) {
|
|
730
|
+
generation.status = failed.length === 0 ? "succeeded" : succeeded.length === 0 ? "failed" : "partial";
|
|
731
|
+
generation.error = failed.length > 0 ? `${failed.length} 首失败` : undefined;
|
|
732
|
+
generation.updatedAt = now();
|
|
733
|
+
}
|
|
734
|
+
job.stages.generate = {
|
|
735
|
+
status: succeeded.length > 0 ? "done" : "error",
|
|
736
|
+
error: succeeded.length === 0 ? (generation?.error ?? "生成失败") : undefined,
|
|
737
|
+
at: now()
|
|
738
|
+
};
|
|
739
|
+
musicLog(job, succeeded.length > 0 ? "info" : "error", `生成结束:${succeeded.length} 首成功${failed.length > 0 ? `,${failed.length} 首失败` : ""}`);
|
|
740
|
+
});
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
await sleep(5000, controller?.signal);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
function songFromPayload(payload, engine, generationId) {
|
|
747
|
+
const timestamp = now();
|
|
748
|
+
return {
|
|
749
|
+
id: payload.id,
|
|
750
|
+
generationId,
|
|
751
|
+
engine,
|
|
752
|
+
status: normalizeSongStatus(payload.status),
|
|
753
|
+
title: typeof payload.title === "string" ? payload.title : undefined,
|
|
754
|
+
audioUrl: typeof payload.audio_url === "string" ? payload.audio_url : undefined,
|
|
755
|
+
wavUrl: typeof payload.audio_wav_url === "string" ? payload.audio_wav_url : undefined,
|
|
756
|
+
imageUrl: typeof payload.image_url === "string" ? payload.image_url : undefined,
|
|
757
|
+
duration: typeof payload.duration === "number" ? payload.duration : undefined,
|
|
758
|
+
lyric: typeof payload.lyric === "string" ? payload.lyric : undefined,
|
|
759
|
+
tags: typeof payload.tags === "string" ? payload.tags : undefined,
|
|
760
|
+
modelName: typeof payload.model_name === "string" ? payload.model_name : undefined,
|
|
761
|
+
createdAt: timestamp,
|
|
762
|
+
updatedAt: timestamp
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
function normalizeSongStatus(value) {
|
|
766
|
+
return value === "succeeded" || value === "failed" || value === "processing" ? value : "pending";
|
|
767
|
+
}
|
|
768
|
+
function applySongPayload(song, payload) {
|
|
769
|
+
song.status = normalizeSongStatus(payload.status);
|
|
770
|
+
song.updatedAt = now();
|
|
771
|
+
if (typeof payload.title === "string")
|
|
772
|
+
song.title = payload.title;
|
|
773
|
+
if (typeof payload.audio_url === "string")
|
|
774
|
+
song.audioUrl = payload.audio_url;
|
|
775
|
+
if (typeof payload.audio_wav_url === "string")
|
|
776
|
+
song.wavUrl = payload.audio_wav_url;
|
|
777
|
+
if (typeof payload.image_url === "string")
|
|
778
|
+
song.imageUrl = payload.image_url;
|
|
779
|
+
if (typeof payload.duration === "number")
|
|
780
|
+
song.duration = payload.duration;
|
|
781
|
+
if (typeof payload.lyric === "string")
|
|
782
|
+
song.lyric = payload.lyric;
|
|
783
|
+
if (typeof payload.tags === "string")
|
|
784
|
+
song.tags = payload.tags;
|
|
785
|
+
if (typeof payload.model_name === "string")
|
|
786
|
+
song.modelName = payload.model_name;
|
|
787
|
+
if (payload.status === "failed")
|
|
788
|
+
song.error = "平台返回失败";
|
|
789
|
+
if (payload.status === "succeeded")
|
|
790
|
+
song.error = undefined;
|
|
791
|
+
}
|
|
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
|
+
}
|
|
825
|
+
const downloading = new Map();
|
|
826
|
+
/** 确保一首歌的音频已落盘;失败时抛错,调用方决定是记 downloadError 还是中断。 */
|
|
827
|
+
export async function ensureLocalSong(id, songId) {
|
|
828
|
+
assertJobId(id);
|
|
829
|
+
const key = `${id}:${songId}`;
|
|
830
|
+
const runningDownload = downloading.get(key);
|
|
831
|
+
if (runningDownload !== undefined)
|
|
832
|
+
return runningDownload;
|
|
833
|
+
const promise = (async () => {
|
|
834
|
+
const job = await readMusicJob(id);
|
|
835
|
+
if (job === undefined)
|
|
836
|
+
throw new Error(`音乐任务不存在:${id}`);
|
|
837
|
+
const song = job.songs.find((entry) => entry.id === songId);
|
|
838
|
+
if (song === undefined)
|
|
839
|
+
throw new Error(`歌曲不存在:${songId}`);
|
|
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
|
+
}
|
|
862
|
+
if (typeof song.audioUrl !== "string" || song.audioUrl === "")
|
|
863
|
+
throw new Error("这首歌没有可下载的音频地址");
|
|
864
|
+
const config = await loadConfig();
|
|
865
|
+
const api = apiConfigOf(config);
|
|
866
|
+
const downloadAudio = (url) => downloadToFile(url, join(musicJobDir(id), "songs"), api, {
|
|
867
|
+
stem: `song-${safeStem(songId)}`,
|
|
868
|
+
fallbackExt: "mp3",
|
|
869
|
+
requireAudio: true
|
|
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
|
+
}
|
|
895
|
+
const relative = `songs/${result.file.split(/[\\/]/u).pop()}`;
|
|
896
|
+
const cover = await downloadCover(id, song, api).catch(() => undefined);
|
|
897
|
+
let duration = song.duration;
|
|
898
|
+
try {
|
|
899
|
+
const probe = await probeAudio(result.file);
|
|
900
|
+
duration = probe.duration;
|
|
901
|
+
}
|
|
902
|
+
catch {
|
|
903
|
+
// 探测失败不影响播放;API 的 duration 先顶着。
|
|
904
|
+
}
|
|
905
|
+
return await patchMusicJob(id, (current) => {
|
|
906
|
+
const entry = current.songs.find((item) => item.id === songId);
|
|
907
|
+
if (entry === undefined)
|
|
908
|
+
throw new Error(`歌曲不存在:${songId}`);
|
|
909
|
+
entry.localFile = relative;
|
|
910
|
+
entry.downloadError = undefined;
|
|
911
|
+
if (cover !== undefined)
|
|
912
|
+
entry.coverFile = cover;
|
|
913
|
+
if (duration !== undefined)
|
|
914
|
+
entry.duration = duration;
|
|
915
|
+
musicLog(current, "info", `已下载歌曲:${entry.title ?? songId}`);
|
|
916
|
+
return entry;
|
|
917
|
+
});
|
|
918
|
+
})();
|
|
919
|
+
downloading.set(key, promise);
|
|
920
|
+
return promise.finally(() => {
|
|
921
|
+
downloading.delete(key);
|
|
922
|
+
});
|
|
923
|
+
}
|
|
924
|
+
async function downloadCover(id, song, api) {
|
|
925
|
+
if (typeof song.imageUrl !== "string" || song.imageUrl === "")
|
|
926
|
+
return undefined;
|
|
927
|
+
const result = await downloadToFile(song.imageUrl, join(musicJobDir(id), "songs"), api, {
|
|
928
|
+
stem: `cover-${safeStem(song.id)}`,
|
|
929
|
+
fallbackExt: "jpg",
|
|
930
|
+
maxBytes: 50 * 1024 * 1024
|
|
931
|
+
});
|
|
932
|
+
return `songs/${result.file.split(/[\\/]/u).pop()}`;
|
|
933
|
+
}
|
|
934
|
+
/** 补查未完成歌曲 / 补下载 / 恢复工具轮询。界面「刷新」与工具 `refreshMusicJob` 都走它。 */
|
|
935
|
+
export async function refreshMusicJob(id) {
|
|
936
|
+
assertJobId(id);
|
|
937
|
+
const job = await readMusicJob(id);
|
|
938
|
+
if (job === undefined)
|
|
939
|
+
throw new Error(`音乐任务不存在:${id}`);
|
|
940
|
+
const api = await requireApi();
|
|
941
|
+
// 未完成的 generation:先查一次当前状态(不重复提交)。
|
|
942
|
+
const pendingGenerations = job.generations.filter((generation) => generation.status === "polling" || generation.status === "submitting");
|
|
943
|
+
for (const generation of pendingGenerations) {
|
|
944
|
+
if (generation.songIds.length === 0)
|
|
945
|
+
continue;
|
|
946
|
+
try {
|
|
947
|
+
const payloads = await querySongs(api, generation.songIds);
|
|
948
|
+
await patchMusicJob(id, (current) => {
|
|
949
|
+
for (const payload of payloads) {
|
|
950
|
+
const song = current.songs.find((entry) => entry.id === payload.id);
|
|
951
|
+
if (song !== undefined)
|
|
952
|
+
applySongPayload(song, payload);
|
|
953
|
+
}
|
|
954
|
+
});
|
|
955
|
+
}
|
|
956
|
+
catch (error) {
|
|
957
|
+
musicLogSafe(id, "warn", `补查失败:${messageOf(error)}`);
|
|
958
|
+
}
|
|
959
|
+
const latest = await readMusicJob(id);
|
|
960
|
+
const songs = latest?.songs.filter((song) => generation.songIds.includes(song.id)) ?? [];
|
|
961
|
+
if (songs.length > 0 && songs.every((song) => song.status === "succeeded" || song.status === "failed")) {
|
|
962
|
+
for (const song of songs.filter((entry) => entry.status === "succeeded" && !localSongUsable(id, entry.localFile))) {
|
|
963
|
+
await ensureLocalSong(id, song.id).catch(() => undefined);
|
|
964
|
+
}
|
|
965
|
+
await patchMusicJob(id, (current) => {
|
|
966
|
+
const entry = current.generations.find((item) => item.id === generation.id);
|
|
967
|
+
const failed = songs.filter((song) => song.status === "failed").length;
|
|
968
|
+
if (entry !== undefined) {
|
|
969
|
+
entry.status = failed === 0 ? "succeeded" : failed === songs.length ? "failed" : "partial";
|
|
970
|
+
entry.updatedAt = now();
|
|
971
|
+
}
|
|
972
|
+
current.stages.generate = { status: failed === songs.length ? "error" : "done", at: now() };
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
else {
|
|
976
|
+
// 还没完成:把后台轮询接上(如果本来就有一条在跑,track 会拒绝,不会重复)。
|
|
977
|
+
const generationNow = latest?.generations.find((entry) => entry.id === generation.id);
|
|
978
|
+
if (generationNow !== undefined && (generationNow.status === "polling" || generationNow.status === "submitting")) {
|
|
979
|
+
trackMusicTask(id, "generation", () => resumeGeneration(id, generation.id));
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
// 已成功但还没下载的歌曲:补下载。
|
|
984
|
+
const latest = await readMusicJob(id);
|
|
985
|
+
for (const song of latest?.songs.filter((entry) => entry.status === "succeeded" && !localSongUsable(id, entry.localFile)) ?? []) {
|
|
986
|
+
await ensureLocalSong(id, song.id).catch((error) => {
|
|
987
|
+
void patchMusicJob(id, (current) => {
|
|
988
|
+
const entry = current.songs.find((item) => item.id === song.id);
|
|
989
|
+
if (entry !== undefined)
|
|
990
|
+
entry.downloadError = messageOf(error);
|
|
991
|
+
});
|
|
992
|
+
});
|
|
993
|
+
}
|
|
994
|
+
// 工具任务:恢复轮询。
|
|
995
|
+
const pendingTools = latest?.tools.filter((tool) => tool.status === "polling" || tool.status === "submitting") ?? [];
|
|
996
|
+
for (const tool of pendingTools) {
|
|
997
|
+
trackMusicTask(id, `tool:${tool.id}`, () => resumeToolTask(id, tool.id));
|
|
998
|
+
}
|
|
999
|
+
const after = await readMusicJob(id);
|
|
1000
|
+
if (after === undefined)
|
|
1001
|
+
throw new Error(`音乐任务不存在:${id}`);
|
|
1002
|
+
return musicSnapshot(after);
|
|
1003
|
+
}
|
|
1004
|
+
export function cancelMusicGeneration(id) {
|
|
1005
|
+
const controller = controllers.get(`${id}:generation`);
|
|
1006
|
+
if (controller === undefined)
|
|
1007
|
+
return false;
|
|
1008
|
+
controller.abort();
|
|
1009
|
+
return true;
|
|
1010
|
+
}
|
|
1011
|
+
// ── 谱曲模式 ────────────────────────────────────────────────────────────
|
|
1012
|
+
/** 保存/更新谱曲方案(草稿)。方案不产生 MIDI,先让用户看到再谱曲。 */
|
|
1013
|
+
export async function saveMusicScorePlan(id, plan) {
|
|
1014
|
+
assertJobId(id);
|
|
1015
|
+
const normalized = normalizeScorePlan(plan);
|
|
1016
|
+
if (!scorePlanReady(normalized)) {
|
|
1017
|
+
throw new Error("谱曲方案太短了:至少写清曲风、段落或一段给用户看的方案说明。");
|
|
1018
|
+
}
|
|
1019
|
+
const job = await patchMusicJob(id, (current) => {
|
|
1020
|
+
if (current.workflow !== "compose")
|
|
1021
|
+
throw new Error("这个任务是「直接生成」模式;谱曲模式请在新建音乐时选择。");
|
|
1022
|
+
current.scorePlan = normalized;
|
|
1023
|
+
musicLog(current, "info", "谱曲方案已保存");
|
|
1024
|
+
return current;
|
|
1025
|
+
});
|
|
1026
|
+
return musicSnapshot(job, originForLinks());
|
|
1027
|
+
}
|
|
1028
|
+
/**
|
|
1029
|
+
* 执行一版谱曲:写 compose.py → 跑 Python/scoremill → 解析 score.mid →
|
|
1030
|
+
* 渲染试听 → 追加一个 composition。
|
|
1031
|
+
*
|
|
1032
|
+
* ★ 本地免费。失败不新增版本,只把 stages.compose 标 error 并抛出带
|
|
1033
|
+
* stderr 尾部的错误,方便 agent 按小节修正。
|
|
1034
|
+
*/
|
|
1035
|
+
export async function runMusicScore(id, input) {
|
|
1036
|
+
assertJobId(id);
|
|
1037
|
+
if (typeof input.script !== "string" || input.script.trim() === "") {
|
|
1038
|
+
throw new Error("compose.py 是空的:请先写一份 scoremill 记谱脚本。");
|
|
1039
|
+
}
|
|
1040
|
+
if (scoreRuns.has(id))
|
|
1041
|
+
throw new Error("这个任务已经有谱曲任务在跑,等它结束再提交。");
|
|
1042
|
+
const job = await readMusicJob(id);
|
|
1043
|
+
if (job === undefined)
|
|
1044
|
+
throw new Error(`音乐任务不存在:${id}`);
|
|
1045
|
+
if (job.workflow !== "compose")
|
|
1046
|
+
throw new Error("这个任务是「直接生成」模式;谱曲模式请在新建音乐时选择。");
|
|
1047
|
+
const inlinePlan = input.plan === undefined || input.plan === null ? undefined : normalizeScorePlan(input.plan);
|
|
1048
|
+
const plan = scorePlanReady(inlinePlan) ? inlinePlan : job.scorePlan;
|
|
1049
|
+
if (!scorePlanReady(plan)) {
|
|
1050
|
+
throw new Error("还没有谱曲方案:先用 saveMusicScorePlan 保存方案(或在本次调用里传 plan),再谱曲。");
|
|
1051
|
+
}
|
|
1052
|
+
if (inlinePlan !== undefined && scorePlanReady(inlinePlan)) {
|
|
1053
|
+
await patchMusicJob(id, (current) => {
|
|
1054
|
+
current.scorePlan = inlinePlan;
|
|
1055
|
+
return current;
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
const config = await loadConfig();
|
|
1059
|
+
const deps = await detectScoreDeps(config);
|
|
1060
|
+
if (!deps.ok)
|
|
1061
|
+
throw new Error(deps.blocker ?? "谱曲依赖不完整:请安装 Python 3 + scoremill。");
|
|
1062
|
+
if (deps.python.ok !== true)
|
|
1063
|
+
throw new Error(deps.python.error ?? "找不到 Python 3");
|
|
1064
|
+
const scoreId = `c${Date.now().toString(36)}${randomUUID().slice(0, 6)}`;
|
|
1065
|
+
const scoreDir = join(musicJobDir(id), "scores", scoreId);
|
|
1066
|
+
const relativePrefix = `scores/${scoreId}/`;
|
|
1067
|
+
const title = (typeof input.title === "string" && input.title.trim() !== "" ? input.title.trim() : job.name).slice(0, 200);
|
|
1068
|
+
const label = (typeof input.label === "string" && input.label.trim() !== "" ? input.label.trim() : `第 ${job.compositions.length + 1} 版`).slice(0, 80);
|
|
1069
|
+
const startedAt = now();
|
|
1070
|
+
scoreRuns.add(id);
|
|
1071
|
+
try {
|
|
1072
|
+
await mkdir(scoreDir, { recursive: true });
|
|
1073
|
+
await writeJsonAtomic(join(scoreDir, "plan.json"), plan);
|
|
1074
|
+
const ran = await runScoreScript({
|
|
1075
|
+
scoreDir,
|
|
1076
|
+
script: input.script,
|
|
1077
|
+
pythonPath: deps.python.path ?? "python3",
|
|
1078
|
+
pythonArgs: deps.python.args ?? []
|
|
1079
|
+
});
|
|
1080
|
+
if (disposed)
|
|
1081
|
+
throw new Error("插件已重载,谱曲中断;请重新提交。");
|
|
1082
|
+
const audio = await renderScoreAudio({
|
|
1083
|
+
midiPath: ran.midiPath,
|
|
1084
|
+
outDir: scoreDir,
|
|
1085
|
+
deps,
|
|
1086
|
+
parsed: ran.parsed,
|
|
1087
|
+
relativePrefix
|
|
1088
|
+
});
|
|
1089
|
+
const warnings = [...audio.warnings];
|
|
1090
|
+
if (plan.lengthBars !== undefined && Math.abs(plan.lengthBars - ran.parsed.meta.bars) > 1) {
|
|
1091
|
+
warnings.push(`方案写的是 ${plan.lengthBars} 小节,MIDI 实际 ${ran.parsed.meta.bars} 小节;如果是有意的请忽略。`);
|
|
1092
|
+
}
|
|
1093
|
+
const composition = {
|
|
1094
|
+
id: scoreId,
|
|
1095
|
+
label,
|
|
1096
|
+
title,
|
|
1097
|
+
plan,
|
|
1098
|
+
script: input.script,
|
|
1099
|
+
scriptFile: `${relativePrefix}compose.py`,
|
|
1100
|
+
midiFile: `${relativePrefix}${ran.midiPath.split(/[\\/]/u).pop() ?? "score.mid"}`,
|
|
1101
|
+
...(audio.audioFile === undefined ? {} : { audioFile: audio.audioFile }),
|
|
1102
|
+
...(audio.renderer === undefined ? {} : { audioRenderer: audio.renderer }),
|
|
1103
|
+
...(audio.error === undefined ? {} : { audioError: audio.error }),
|
|
1104
|
+
midi: {
|
|
1105
|
+
duration: ran.parsed.meta.duration,
|
|
1106
|
+
bars: ran.parsed.meta.bars,
|
|
1107
|
+
tempo: ran.parsed.meta.tempo,
|
|
1108
|
+
timeSignature: ran.parsed.meta.timeSignature,
|
|
1109
|
+
tracks: ran.parsed.meta.tracks,
|
|
1110
|
+
channels: ran.parsed.meta.channels,
|
|
1111
|
+
notes: ran.parsed.meta.notes
|
|
1112
|
+
},
|
|
1113
|
+
...(ran.report === undefined ? {} : { report: ran.report }),
|
|
1114
|
+
stdout: ran.stdout.slice(-8000),
|
|
1115
|
+
status: "ready",
|
|
1116
|
+
...(typeof input.basedOn === "string" && input.basedOn !== "" ? { basedOn: input.basedOn } : {}),
|
|
1117
|
+
createdAt: startedAt,
|
|
1118
|
+
updatedAt: now()
|
|
1119
|
+
};
|
|
1120
|
+
await patchMusicJob(id, (current) => {
|
|
1121
|
+
current.compositions.push(composition);
|
|
1122
|
+
current.currentScoreId = composition.id;
|
|
1123
|
+
current.stages.compose = { status: "done", at: now() };
|
|
1124
|
+
musicLog(current, "info", `谱曲完成:${composition.label}(${composition.midi.bars} 小节 / ${composition.midi.duration.toFixed(1)} 秒 / ${composition.midi.notes} 个音)`);
|
|
1125
|
+
for (const warning of warnings)
|
|
1126
|
+
musicLog(current, "warn", warning);
|
|
1127
|
+
if (audio.error !== undefined)
|
|
1128
|
+
musicLog(current, "warn", `试听渲染失败:${audio.error}`);
|
|
1129
|
+
});
|
|
1130
|
+
return {
|
|
1131
|
+
ok: true,
|
|
1132
|
+
jobId: id,
|
|
1133
|
+
scoreId,
|
|
1134
|
+
title,
|
|
1135
|
+
duration: composition.midi.duration,
|
|
1136
|
+
bars: composition.midi.bars,
|
|
1137
|
+
midiUrl: absUrl(originForLinks(), musicAssetBase(id), composition.midiFile) ?? null,
|
|
1138
|
+
audioUrl: absUrl(originForLinks(), musicAssetBase(id), composition.audioFile) ?? null,
|
|
1139
|
+
...(composition.audioRenderer === undefined ? {} : { audioRenderer: composition.audioRenderer }),
|
|
1140
|
+
warnings,
|
|
1141
|
+
openUrl: musicOpenLink(id, "compose", scoreId)
|
|
1142
|
+
};
|
|
1143
|
+
}
|
|
1144
|
+
catch (error) {
|
|
1145
|
+
const message = messageOf(error);
|
|
1146
|
+
await patchMusicJob(id, (current) => {
|
|
1147
|
+
current.stages.compose = { status: "error", error: message.slice(0, 4000), at: now() };
|
|
1148
|
+
musicLog(current, "error", `谱曲失败:${message.slice(0, 1000)}`);
|
|
1149
|
+
}).catch(() => undefined);
|
|
1150
|
+
throw error;
|
|
1151
|
+
}
|
|
1152
|
+
finally {
|
|
1153
|
+
scoreRuns.delete(id);
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
/**
|
|
1157
|
+
* 把某一版谱曲交给 Suno。
|
|
1158
|
+
*
|
|
1159
|
+
* 链路:这一版的试听音频(`preview.mp3` / `preview.wav`)→
|
|
1160
|
+
* `POST /v1/suno/audio/upload` 拿参考 song id → `POST /v1/suno/generate/cover`。
|
|
1161
|
+
* Suno 不接受 MIDI 原文件,但接受音频;标准上传免费,版权通道需用户确认。
|
|
1162
|
+
*
|
|
1163
|
+
* ⚠️ 真实计费;必须 `confirm:true`,已有歌曲时必须 `regenerate:true`。
|
|
1164
|
+
*/
|
|
1165
|
+
export async function submitMusicScoreToSuno(id, input = {}) {
|
|
1166
|
+
assertJobId(id);
|
|
1167
|
+
if (input.confirm !== true) {
|
|
1168
|
+
throw new Error("交给 Suno 会真实消耗积分;确认要提交请传 confirm:true(并先向用户说明)。插件会先把这一版的试听音频上传给 Suno 作为参考(标准上传免费),再走 cover;Suno 不接受 MIDI 原文件。");
|
|
1169
|
+
}
|
|
1170
|
+
const job = await readMusicJob(id);
|
|
1171
|
+
if (job === undefined)
|
|
1172
|
+
throw new Error(`音乐任务不存在:${id}`);
|
|
1173
|
+
if (job.workflow !== "compose")
|
|
1174
|
+
throw new Error("这个任务不是谱曲模式,没有可提交的谱曲版本。");
|
|
1175
|
+
const scoreId = typeof input.scoreId === "string" && input.scoreId !== "" ? input.scoreId : job.currentScoreId;
|
|
1176
|
+
const composition = job.compositions.find((entry) => entry.id === scoreId);
|
|
1177
|
+
if (composition === undefined)
|
|
1178
|
+
throw new Error(`谱曲版本不存在:${scoreId ?? "(空)"}`);
|
|
1179
|
+
if (composition.status !== "ready")
|
|
1180
|
+
throw new Error("这一版谱曲还没有完成,无法提交。");
|
|
1181
|
+
const config = await loadConfig();
|
|
1182
|
+
const blocker = musicBlocker(config);
|
|
1183
|
+
if (blocker !== undefined && blocker !== null)
|
|
1184
|
+
throw new Error(blocker);
|
|
1185
|
+
// 先过计费/并发闸门,避免「明知不会启动还先上传一次」。
|
|
1186
|
+
if (job.songs.some((song) => song.status === "succeeded") && input.regenerate !== true) {
|
|
1187
|
+
return {
|
|
1188
|
+
ok: false,
|
|
1189
|
+
started: false,
|
|
1190
|
+
reason: "这个任务已经有歌曲了。再生成一批会再计费;确认要重做请传 regenerate:true。",
|
|
1191
|
+
scoreId: composition.id,
|
|
1192
|
+
warnings: []
|
|
1193
|
+
};
|
|
1194
|
+
}
|
|
1195
|
+
if (musicBusy(id, job)) {
|
|
1196
|
+
return {
|
|
1197
|
+
ok: false,
|
|
1198
|
+
started: false,
|
|
1199
|
+
reason: "这个任务已有生成/编辑任务在跑,等它结束再提交(重复提交会重复计费)。",
|
|
1200
|
+
scoreId: composition.id,
|
|
1201
|
+
warnings: []
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
if (typeof composition.audioFile !== "string" || composition.audioFile === "") {
|
|
1205
|
+
throw new Error("这一版没有试听音频,无法作为 Suno 的参考。请先修复试听渲染(装 FluidSynth + SoundFont,或检查 ffmpeg),或下载 MIDI 自行处理。");
|
|
1206
|
+
}
|
|
1207
|
+
const audioPath = musicAssetPath(id, composition.audioFile);
|
|
1208
|
+
let uploaded;
|
|
1209
|
+
try {
|
|
1210
|
+
uploaded = await uploadSunoAudio(apiConfigOf(config), {
|
|
1211
|
+
filePath: audioPath,
|
|
1212
|
+
fileName: composition.audioFile.split(/[\\/]/u).pop(),
|
|
1213
|
+
copyright: input.copyrightAudio === true
|
|
1214
|
+
});
|
|
1215
|
+
}
|
|
1216
|
+
catch (error) {
|
|
1217
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1218
|
+
const errorCode = error instanceof MusicApiError ? `${error.code ?? ""} ${error.type ?? ""}` : "";
|
|
1219
|
+
if (input.copyrightAudio !== true && error instanceof MusicApiError && /copyright|版权|拷贝/iu.test(`${message} ${errorCode}`)) {
|
|
1220
|
+
return {
|
|
1221
|
+
ok: false,
|
|
1222
|
+
started: false,
|
|
1223
|
+
needsCopyrightConsent: true,
|
|
1224
|
+
scoreId: composition.id,
|
|
1225
|
+
reason: `Suno 判定这段参考音频有版权,需要走付费版权上传通道(会扣积分)。确认后传 copyrightAudio:true 重试。原始错误:${message}`
|
|
1226
|
+
};
|
|
1227
|
+
}
|
|
1228
|
+
throw error;
|
|
1229
|
+
}
|
|
1230
|
+
const built = buildScoreSunoParams({
|
|
1231
|
+
job,
|
|
1232
|
+
composition,
|
|
1233
|
+
coverClipId: uploaded.songId,
|
|
1234
|
+
audioWeight: input.audioWeight,
|
|
1235
|
+
overrides: { ...(input.params ?? {}), ...(typeof input.model === "string" && input.model.trim() !== "" ? { model: input.model.trim() } : {}) }
|
|
1236
|
+
});
|
|
1237
|
+
const started = await startMusicGeneration(id, {
|
|
1238
|
+
engine: "suno",
|
|
1239
|
+
mode: built.mode,
|
|
1240
|
+
model: built.model,
|
|
1241
|
+
params: built.params,
|
|
1242
|
+
regenerate: input.regenerate === true,
|
|
1243
|
+
by: "human",
|
|
1244
|
+
scoreId: composition.id,
|
|
1245
|
+
sourceClipId: uploaded.songId
|
|
1246
|
+
});
|
|
1247
|
+
if (!started.started) {
|
|
1248
|
+
return {
|
|
1249
|
+
ok: false,
|
|
1250
|
+
started: false,
|
|
1251
|
+
reason: started.reason ?? "提交没有启动",
|
|
1252
|
+
scoreId: composition.id,
|
|
1253
|
+
warnings: built.warnings
|
|
1254
|
+
};
|
|
1255
|
+
}
|
|
1256
|
+
return {
|
|
1257
|
+
ok: true,
|
|
1258
|
+
started: true,
|
|
1259
|
+
generationId: started.generationId,
|
|
1260
|
+
scoreId: composition.id,
|
|
1261
|
+
mode: built.mode,
|
|
1262
|
+
uploadedClipId: uploaded.songId,
|
|
1263
|
+
copyrightAudio: input.copyrightAudio === true,
|
|
1264
|
+
warnings: built.warnings,
|
|
1265
|
+
message: "已上传这一版的试听音频作为参考并提交给 Suno(真实计费)。结果会基于这段音频重新演奏,但不会逐音一致。",
|
|
1266
|
+
openUrl: musicOpenLink(id, "generate", composition.id)
|
|
1267
|
+
};
|
|
1268
|
+
}
|
|
1269
|
+
/** 插件启动时接上未完成的任务(进程重启后没有内存里的后台任务)。 */
|
|
1270
|
+
export async function resumeMusicJobs() {
|
|
1271
|
+
const jobs = await listMusicJobs();
|
|
1272
|
+
for (const summary of jobs) {
|
|
1273
|
+
if (!summary.busy)
|
|
1274
|
+
continue;
|
|
1275
|
+
const job = await readMusicJob(summary.id);
|
|
1276
|
+
if (job === undefined)
|
|
1277
|
+
continue;
|
|
1278
|
+
// 谱曲是同步调用:重启后还停在 running,说明进程在谱曲中途被杀了。
|
|
1279
|
+
if (job.stages.compose?.status === "running") {
|
|
1280
|
+
await patchMusicJob(job.id, (current) => {
|
|
1281
|
+
current.stages.compose = { status: "error", error: "插件重启,谱曲中断;请重新谱曲。", at: now() };
|
|
1282
|
+
musicLog(current, "warn", "谱曲中断:插件重启");
|
|
1283
|
+
});
|
|
1284
|
+
}
|
|
1285
|
+
const pendingGeneration = job.generations.find((generation) => generation.status === "polling" || generation.status === "submitting");
|
|
1286
|
+
if (pendingGeneration !== undefined && pendingGeneration.songIds.length > 0) {
|
|
1287
|
+
trackMusicTask(job.id, "generation", () => resumeGeneration(job.id, pendingGeneration.id));
|
|
1288
|
+
}
|
|
1289
|
+
else if (pendingGeneration !== undefined) {
|
|
1290
|
+
// 提交请求发出去了但还没拿到歌曲 id 就重启:没有可续查的远端任务,只能标失败。
|
|
1291
|
+
await patchMusicJob(job.id, (current) => {
|
|
1292
|
+
const entry = current.generations.find((item) => item.id === pendingGeneration.id);
|
|
1293
|
+
if (entry !== undefined) {
|
|
1294
|
+
entry.status = "failed";
|
|
1295
|
+
entry.error = "插件重启前没有拿到歌曲 id,无法续查;请重新生成(会再计费)。";
|
|
1296
|
+
entry.updatedAt = now();
|
|
1297
|
+
}
|
|
1298
|
+
current.stages.generate = { status: "error", error: "插件重启前提交未完成", at: now() };
|
|
1299
|
+
});
|
|
1300
|
+
}
|
|
1301
|
+
for (const tool of job.tools.filter((entry) => entry.status === "polling" || entry.status === "submitting")) {
|
|
1302
|
+
trackMusicTask(job.id, `tool:${tool.id}`, () => resumeToolTask(job.id, tool.id));
|
|
1303
|
+
}
|
|
1304
|
+
// 编辑任务没有持久化的子进程:重启后在跑的那一版只能标失败,让用户重试。
|
|
1305
|
+
const rendering = job.versions.filter((version) => version.status === "rendering");
|
|
1306
|
+
if (rendering.length > 0) {
|
|
1307
|
+
await patchMusicJob(job.id, (current) => {
|
|
1308
|
+
for (const version of current.versions.filter((entry) => entry.status === "rendering")) {
|
|
1309
|
+
version.status = "error";
|
|
1310
|
+
version.error = "插件重启,渲染中断;请重新导出这一版。";
|
|
1311
|
+
}
|
|
1312
|
+
current.stages.edit = { status: "error", error: "插件重启,渲染中断", at: now() };
|
|
1313
|
+
});
|
|
1314
|
+
}
|
|
1315
|
+
for (const song of job.songs.filter((entry) => entry.status === "succeeded" && entry.localFile === undefined)) {
|
|
1316
|
+
void ensureLocalSong(job.id, song.id).catch(() => undefined);
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
/** 重启后接上一条已提交的 generation:不再提交,只继续查询/下载。 */
|
|
1321
|
+
async function resumeGeneration(id, generationId) {
|
|
1322
|
+
const job = await readMusicJob(id);
|
|
1323
|
+
if (job === undefined)
|
|
1324
|
+
return;
|
|
1325
|
+
const generation = job.generations.find((entry) => entry.id === generationId);
|
|
1326
|
+
if (generation === undefined || generation.songIds.length === 0)
|
|
1327
|
+
return;
|
|
1328
|
+
const config = await loadConfig();
|
|
1329
|
+
const api = apiConfigOf(config);
|
|
1330
|
+
const controller = controllers.get(`${id}:generation`);
|
|
1331
|
+
const deadline = now() + Math.max(60000, config.musicPollTimeoutMs || 900000);
|
|
1332
|
+
for (;;) {
|
|
1333
|
+
if (controller?.signal.aborted === true)
|
|
1334
|
+
return;
|
|
1335
|
+
if (now() >= deadline) {
|
|
1336
|
+
await patchMusicJob(id, (current) => {
|
|
1337
|
+
const entry = current.generations.find((item) => item.id === generationId);
|
|
1338
|
+
if (entry !== undefined) {
|
|
1339
|
+
entry.status = "timeout";
|
|
1340
|
+
entry.updatedAt = now();
|
|
1341
|
+
}
|
|
1342
|
+
current.stages.generate = { status: "error", error: "等待超时", at: now() };
|
|
1343
|
+
});
|
|
1344
|
+
return;
|
|
1345
|
+
}
|
|
1346
|
+
try {
|
|
1347
|
+
const payloads = await querySongs(api, generation.songIds);
|
|
1348
|
+
if (payloads.length > 0) {
|
|
1349
|
+
await patchMusicJob(id, (current) => {
|
|
1350
|
+
for (const payload of payloads) {
|
|
1351
|
+
const song = current.songs.find((entry) => entry.id === payload.id);
|
|
1352
|
+
if (song !== undefined)
|
|
1353
|
+
applySongPayload(song, payload);
|
|
1354
|
+
}
|
|
1355
|
+
});
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
catch (error) {
|
|
1359
|
+
if (error instanceof MusicApiError && error.status === 429) {
|
|
1360
|
+
await sleep(15000, controller?.signal);
|
|
1361
|
+
continue;
|
|
1362
|
+
}
|
|
1363
|
+
await sleep(8000, controller?.signal);
|
|
1364
|
+
continue;
|
|
1365
|
+
}
|
|
1366
|
+
const latest = await readMusicJob(id);
|
|
1367
|
+
const songs = latest?.songs.filter((song) => generation.songIds.includes(song.id)) ?? [];
|
|
1368
|
+
if (songs.length > 0 && songs.every((song) => song.status === "succeeded" || song.status === "failed")) {
|
|
1369
|
+
for (const song of songs.filter((entry) => entry.status === "succeeded" && !localSongUsable(id, entry.localFile))) {
|
|
1370
|
+
await ensureLocalSong(id, song.id).catch(() => undefined);
|
|
1371
|
+
}
|
|
1372
|
+
await patchMusicJob(id, (current) => {
|
|
1373
|
+
const entry = current.generations.find((item) => item.id === generationId);
|
|
1374
|
+
const failed = songs.filter((song) => song.status === "failed").length;
|
|
1375
|
+
if (entry !== undefined) {
|
|
1376
|
+
entry.status = failed === 0 ? "succeeded" : failed === songs.length ? "failed" : "partial";
|
|
1377
|
+
entry.updatedAt = now();
|
|
1378
|
+
}
|
|
1379
|
+
current.stages.generate = { status: failed === songs.length ? "error" : "done", at: now() };
|
|
1380
|
+
});
|
|
1381
|
+
return;
|
|
1382
|
+
}
|
|
1383
|
+
await sleep(5000, controller?.signal);
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
export async function getMusicWav(id, songId) {
|
|
1387
|
+
assertJobId(id);
|
|
1388
|
+
const job = await readMusicJob(id);
|
|
1389
|
+
if (job === undefined)
|
|
1390
|
+
throw new Error(`音乐任务不存在:${id}`);
|
|
1391
|
+
const song = job.songs.find((entry) => entry.id === songId);
|
|
1392
|
+
if (song === undefined)
|
|
1393
|
+
throw new Error(`歌曲不存在:${songId}`);
|
|
1394
|
+
if (song.wavFile !== undefined && existsSync(musicAssetPath(id, song.wavFile))) {
|
|
1395
|
+
return { ok: true, reused: true, file: song.wavFile };
|
|
1396
|
+
}
|
|
1397
|
+
const api = await requireApi();
|
|
1398
|
+
const wav = await requestWav(api, songId);
|
|
1399
|
+
const result = await downloadToFile(wav.url, join(musicJobDir(id), "songs"), api, {
|
|
1400
|
+
stem: `song-${safeStem(songId)}-lossless`,
|
|
1401
|
+
fallbackExt: "wav"
|
|
1402
|
+
});
|
|
1403
|
+
const relative = `songs/${result.file.split(/[\\/]/u).pop()}`;
|
|
1404
|
+
await patchMusicJob(id, (current) => {
|
|
1405
|
+
const entry = current.songs.find((item) => item.id === songId);
|
|
1406
|
+
if (entry !== undefined) {
|
|
1407
|
+
entry.wavFile = relative;
|
|
1408
|
+
entry.wavUrl = wav.url;
|
|
1409
|
+
}
|
|
1410
|
+
musicLog(current, "info", `已获取无损 WAV:${song.title ?? songId}`);
|
|
1411
|
+
});
|
|
1412
|
+
return { ok: true, file: relative, url: wav.url, bytes: result.bytes };
|
|
1413
|
+
}
|
|
1414
|
+
export async function getMusicLrc(id, songIds) {
|
|
1415
|
+
assertJobId(id);
|
|
1416
|
+
const job = await readMusicJob(id);
|
|
1417
|
+
if (job === undefined)
|
|
1418
|
+
throw new Error(`音乐任务不存在:${id}`);
|
|
1419
|
+
const targetIds = (Array.isArray(songIds) && songIds.length > 0 ? songIds : job.songs.filter((song) => song.status === "succeeded").map((song) => song.id))
|
|
1420
|
+
.filter((songId) => job.songs.some((song) => song.id === songId));
|
|
1421
|
+
if (targetIds.length === 0)
|
|
1422
|
+
throw new Error("没有已完成的歌曲可以生成滚动歌词");
|
|
1423
|
+
const api = await requireApi();
|
|
1424
|
+
const results = await generateLrc(api, targetIds);
|
|
1425
|
+
const saved = [];
|
|
1426
|
+
for (const result of results) {
|
|
1427
|
+
if (!result.success || result.lrcAlignment === undefined)
|
|
1428
|
+
continue;
|
|
1429
|
+
const relative = `songs/${safeStem(result.id)}-lrc.json`;
|
|
1430
|
+
await writeTextAtomic(musicAssetPath(id, relative), `${JSON.stringify({ id: result.id, lrc_alignment: result.lrcAlignment }, null, 2)}\n`);
|
|
1431
|
+
saved.push(result.id);
|
|
1432
|
+
await patchMusicJob(id, (current) => {
|
|
1433
|
+
const entry = current.songs.find((song) => song.id === result.id);
|
|
1434
|
+
if (entry !== undefined)
|
|
1435
|
+
entry.lrcFile = relative;
|
|
1436
|
+
musicLog(current, "info", `滚动歌词已就绪:${entry?.title ?? result.id}`);
|
|
1437
|
+
});
|
|
1438
|
+
}
|
|
1439
|
+
return { ok: true, results, saved };
|
|
1440
|
+
}
|
|
1441
|
+
async function writeTextAtomic(file, text) {
|
|
1442
|
+
const { writeFile } = await import("node:fs/promises");
|
|
1443
|
+
await writeFile(file, text, "utf8");
|
|
1444
|
+
}
|
|
1445
|
+
// ── 工具任务 ────────────────────────────────────────────────────────────
|
|
1446
|
+
export async function listMusicStemInstruments() {
|
|
1447
|
+
const api = await requireApi();
|
|
1448
|
+
return stemInstruments(api);
|
|
1449
|
+
}
|
|
1450
|
+
function pickSong(job, songId) {
|
|
1451
|
+
const song = songId === undefined ? job.songs.find((entry) => entry.status === "succeeded") : job.songs.find((entry) => entry.id === songId);
|
|
1452
|
+
if (song === undefined)
|
|
1453
|
+
throw new Error(songId === undefined ? "任务里还没有已完成的歌曲" : `歌曲不存在:${songId}`);
|
|
1454
|
+
return song;
|
|
1455
|
+
}
|
|
1456
|
+
function publicAudioOf(song) {
|
|
1457
|
+
const url = song.wavUrl || song.audioUrl;
|
|
1458
|
+
if (typeof url !== "string" || url === "")
|
|
1459
|
+
throw new Error("这首歌没有公开音频 URL(工具类接口只接受公开可访问的 URL)");
|
|
1460
|
+
return url;
|
|
1461
|
+
}
|
|
1462
|
+
export async function runMusicTool(id, kind, params = {}) {
|
|
1463
|
+
assertJobId(id);
|
|
1464
|
+
if (!isMusicToolKind(kind))
|
|
1465
|
+
throw new Error(`未知音乐工具:${kind}(可用:${MUSIC_TOOL_KINDS.join(" / ")})`);
|
|
1466
|
+
const job = await readMusicJob(id);
|
|
1467
|
+
if (job === undefined)
|
|
1468
|
+
throw new Error(`音乐任务不存在:${id}`);
|
|
1469
|
+
if (job.tools.some((tool) => tool.status === "submitting" || tool.status === "polling")) {
|
|
1470
|
+
return { started: false, reason: "已有工具任务在跑,等它结束再提交。" };
|
|
1471
|
+
}
|
|
1472
|
+
const toolId = `t${Date.now().toString(36)}${randomUUID().slice(0, 6)}`;
|
|
1473
|
+
const startedAt = now();
|
|
1474
|
+
await patchMusicJob(id, (current) => {
|
|
1475
|
+
current.tools.push({
|
|
1476
|
+
id: toolId,
|
|
1477
|
+
kind: kind,
|
|
1478
|
+
status: "submitting",
|
|
1479
|
+
params: { ...params },
|
|
1480
|
+
startedAt,
|
|
1481
|
+
updatedAt: startedAt
|
|
1482
|
+
});
|
|
1483
|
+
musicLog(current, "info", `提交音乐工具:${kind}`);
|
|
1484
|
+
});
|
|
1485
|
+
const ok = trackMusicTask(id, `tool:${toolId}`, () => runToolTask(id, toolId));
|
|
1486
|
+
if (!ok) {
|
|
1487
|
+
await patchMusicJob(id, (current) => {
|
|
1488
|
+
const tool = current.tools.find((entry) => entry.id === toolId);
|
|
1489
|
+
if (tool !== undefined) {
|
|
1490
|
+
tool.status = "failed";
|
|
1491
|
+
tool.error = "后台任务没有启动";
|
|
1492
|
+
tool.updatedAt = now();
|
|
1493
|
+
}
|
|
1494
|
+
});
|
|
1495
|
+
return { started: false, reason: "后台任务没有启动,请重启插件后再试。" };
|
|
1496
|
+
}
|
|
1497
|
+
return { started: true, toolId };
|
|
1498
|
+
}
|
|
1499
|
+
/**
|
|
1500
|
+
* 接上重启前已经提交过的工具任务:**只查询和下载,绝不重新提交**。
|
|
1501
|
+
*
|
|
1502
|
+
* 同步类工具(midi / sheet-music / style-analysis)没有可查的远端任务;如果它们在
|
|
1503
|
+
* 重启前没落盘,只能标失败让用户重新运行——重新运行会再计费,必须由用户决定。
|
|
1504
|
+
*/
|
|
1505
|
+
async function resumeToolTask(id, toolId) {
|
|
1506
|
+
const job = await readMusicJob(id);
|
|
1507
|
+
if (job === undefined)
|
|
1508
|
+
return;
|
|
1509
|
+
const tool = job.tools.find((entry) => entry.id === toolId);
|
|
1510
|
+
if (tool === undefined)
|
|
1511
|
+
return;
|
|
1512
|
+
try {
|
|
1513
|
+
if (tool.remoteTaskId === undefined || tool.remoteTaskId === "" || !["stems", "pro-stems", "convert"].includes(tool.kind)) {
|
|
1514
|
+
throw new Error("插件重启前这一步没有可续查的远端任务,请重新运行(会再计费)。");
|
|
1515
|
+
}
|
|
1516
|
+
const api = await requireApi();
|
|
1517
|
+
const finished = await pollTool(api, id, toolId, {
|
|
1518
|
+
taskId: tool.remoteTaskId,
|
|
1519
|
+
status: tool.status === "polling" ? "processing" : "pending",
|
|
1520
|
+
type: tool.kind,
|
|
1521
|
+
raw: {}
|
|
1522
|
+
});
|
|
1523
|
+
const params = tool.params ?? {};
|
|
1524
|
+
const fallback = tool.kind === "convert"
|
|
1525
|
+
? (typeof params.targetFormat === "string" ? params.targetFormat : "mp3")
|
|
1526
|
+
: (typeof params.outputFormat === "string" ? params.outputFormat : "mp3");
|
|
1527
|
+
const toolDir = join(musicJobDir(id), "tools", toolId);
|
|
1528
|
+
await downloadToolFiles(id, toolId, finished.raw, toolDir, fallback);
|
|
1529
|
+
}
|
|
1530
|
+
catch (error) {
|
|
1531
|
+
await patchMusicJob(id, (current) => {
|
|
1532
|
+
const entry = current.tools.find((item) => item.id === toolId);
|
|
1533
|
+
if (entry !== undefined) {
|
|
1534
|
+
entry.status = "failed";
|
|
1535
|
+
entry.error = messageOf(error);
|
|
1536
|
+
entry.updatedAt = now();
|
|
1537
|
+
}
|
|
1538
|
+
musicLog(current, "error", `工具任务未能续跑:${messageOf(error)}`);
|
|
1539
|
+
});
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
async function runToolTask(id, toolId) {
|
|
1543
|
+
const job = await readMusicJob(id);
|
|
1544
|
+
if (job === undefined)
|
|
1545
|
+
return;
|
|
1546
|
+
const tool = job.tools.find((entry) => entry.id === toolId);
|
|
1547
|
+
if (tool === undefined)
|
|
1548
|
+
return;
|
|
1549
|
+
const api = await requireApi();
|
|
1550
|
+
const params = tool.params ?? {};
|
|
1551
|
+
// sheet-music 只需要一个公开 MIDI URL,不依赖这首歌;其余分支才需要 song/audioUrl。
|
|
1552
|
+
let songCache;
|
|
1553
|
+
const songOf = () => {
|
|
1554
|
+
if (songCache === undefined)
|
|
1555
|
+
songCache = pickSong(job, typeof params.songId === "string" ? params.songId : undefined);
|
|
1556
|
+
return songCache;
|
|
1557
|
+
};
|
|
1558
|
+
const audioUrlOf = () => typeof params.audioUrl === "string" && params.audioUrl !== "" ? params.audioUrl : publicAudioOf(songOf());
|
|
1559
|
+
const toolDir = join(musicJobDir(id), "tools", toolId);
|
|
1560
|
+
try {
|
|
1561
|
+
if (tool.kind === "stems") {
|
|
1562
|
+
const stemCount = Number(params.stemCount ?? 4);
|
|
1563
|
+
const outputFormat = typeof params.outputFormat === "string" ? params.outputFormat : "mp3";
|
|
1564
|
+
const submitted = await submitStemSplit(api, { audioUrl: audioUrlOf(), filename: `${safeStem(songOf().title ?? songOf().id)}.mp3`, stemCount, outputFormat });
|
|
1565
|
+
await markToolSubmitted(id, toolId, submitted);
|
|
1566
|
+
const finished = await pollTool(api, id, toolId, submitted);
|
|
1567
|
+
await downloadToolFiles(id, toolId, finished.raw, toolDir, outputFormat);
|
|
1568
|
+
return;
|
|
1569
|
+
}
|
|
1570
|
+
if (tool.kind === "pro-stems") {
|
|
1571
|
+
const itemCode = typeof params.itemCode === "string" ? params.itemCode : "";
|
|
1572
|
+
const outputFormat = typeof params.outputFormat === "string" ? params.outputFormat : "mp3";
|
|
1573
|
+
const submitted = await submitProStemSplit(api, { audioUrl: audioUrlOf(), itemCode, filename: `${safeStem(songOf().title ?? songOf().id)}.mp3`, outputFormat });
|
|
1574
|
+
await markToolSubmitted(id, toolId, submitted);
|
|
1575
|
+
const finished = await pollTool(api, id, toolId, submitted);
|
|
1576
|
+
await downloadToolFiles(id, toolId, finished.raw, toolDir, outputFormat);
|
|
1577
|
+
return;
|
|
1578
|
+
}
|
|
1579
|
+
if (tool.kind === "midi") {
|
|
1580
|
+
const midi = await submitMidi(api, { audioUrl: audioUrlOf(), audioName: `${safeStem(songOf().title ?? songOf().id)}.mp3` });
|
|
1581
|
+
const downloaded = await downloadToFile(midi.midiUrl, toolDir, api, { stem: "midi", fallbackExt: "mid" });
|
|
1582
|
+
await patchMusicJob(id, (current) => {
|
|
1583
|
+
const entry = current.tools.find((item) => item.id === toolId);
|
|
1584
|
+
if (entry !== undefined) {
|
|
1585
|
+
entry.status = "succeeded";
|
|
1586
|
+
entry.result = { midiUrl: midi.midiUrl };
|
|
1587
|
+
entry.files = [{ name: "midi.mid", file: `tools/${toolId}/${downloaded.file.split(/[\\/]/u).pop()}`, bytes: downloaded.bytes }];
|
|
1588
|
+
entry.updatedAt = now();
|
|
1589
|
+
}
|
|
1590
|
+
musicLog(current, "info", "音频转 MIDI 完成");
|
|
1591
|
+
});
|
|
1592
|
+
return;
|
|
1593
|
+
}
|
|
1594
|
+
if (tool.kind === "sheet-music") {
|
|
1595
|
+
const midiUrl = typeof params.midiUrl === "string" ? params.midiUrl : "";
|
|
1596
|
+
if (midiUrl === "")
|
|
1597
|
+
throw new Error("乐谱转换需要 midiUrl(可以先用 midi 工具拿到公开 MIDI URL)");
|
|
1598
|
+
const sheet = await submitSheetMusic(api, midiUrl);
|
|
1599
|
+
const files = [];
|
|
1600
|
+
if (sheet.pdfUrl !== undefined) {
|
|
1601
|
+
const downloaded = await downloadToFile(sheet.pdfUrl, toolDir, api, { stem: "score", fallbackExt: "pdf", maxBytes: 80 * 1024 * 1024 });
|
|
1602
|
+
files.push({ name: "score.pdf", file: `tools/${toolId}/${downloaded.file.split(/[\\/]/u).pop()}`, bytes: downloaded.bytes });
|
|
1603
|
+
}
|
|
1604
|
+
if (sheet.xmlUrl !== undefined) {
|
|
1605
|
+
const downloaded = await downloadToFile(sheet.xmlUrl, toolDir, api, { stem: "score", fallbackExt: "musicxml", maxBytes: 80 * 1024 * 1024 });
|
|
1606
|
+
files.push({ name: "score.musicxml", file: `tools/${toolId}/${downloaded.file.split(/[\\/]/u).pop()}`, bytes: downloaded.bytes });
|
|
1607
|
+
}
|
|
1608
|
+
await patchMusicJob(id, (current) => {
|
|
1609
|
+
const entry = current.tools.find((item) => item.id === toolId);
|
|
1610
|
+
if (entry !== undefined) {
|
|
1611
|
+
entry.status = "succeeded";
|
|
1612
|
+
entry.result = { pdfUrl: sheet.pdfUrl, xmlUrl: sheet.xmlUrl };
|
|
1613
|
+
entry.files = files;
|
|
1614
|
+
entry.updatedAt = now();
|
|
1615
|
+
}
|
|
1616
|
+
musicLog(current, "info", "MIDI 转乐谱完成");
|
|
1617
|
+
});
|
|
1618
|
+
return;
|
|
1619
|
+
}
|
|
1620
|
+
if (tool.kind === "style-analysis") {
|
|
1621
|
+
const analysis = await submitStyleAnalysis(api, { audioUrl: audioUrlOf(), audioName: `${safeStem(songOf().title ?? songOf().id)}.mp3` });
|
|
1622
|
+
await patchMusicJob(id, (current) => {
|
|
1623
|
+
const entry = current.tools.find((item) => item.id === toolId);
|
|
1624
|
+
if (entry !== undefined) {
|
|
1625
|
+
entry.status = "succeeded";
|
|
1626
|
+
entry.result = { instruments: analysis.instruments, genres: analysis.genres, tags: analysis.tags, description: analysis.description };
|
|
1627
|
+
entry.files = [];
|
|
1628
|
+
entry.updatedAt = now();
|
|
1629
|
+
}
|
|
1630
|
+
musicLog(current, "info", "风格分析完成");
|
|
1631
|
+
});
|
|
1632
|
+
return;
|
|
1633
|
+
}
|
|
1634
|
+
// convert
|
|
1635
|
+
const targetFormat = typeof params.targetFormat === "string" ? params.targetFormat : "mp3";
|
|
1636
|
+
const submitted = await submitAudioConvert(api, { sourceUrl: audioUrlOf(), targetFormat });
|
|
1637
|
+
await markToolSubmitted(id, toolId, submitted);
|
|
1638
|
+
const finished = await pollTool(api, id, toolId, submitted);
|
|
1639
|
+
await downloadToolFiles(id, toolId, finished.raw, toolDir, targetFormat);
|
|
1640
|
+
}
|
|
1641
|
+
catch (error) {
|
|
1642
|
+
await patchMusicJob(id, (current) => {
|
|
1643
|
+
const entry = current.tools.find((item) => item.id === toolId);
|
|
1644
|
+
if (entry !== undefined) {
|
|
1645
|
+
entry.status = "failed";
|
|
1646
|
+
entry.error = messageOf(error);
|
|
1647
|
+
entry.updatedAt = now();
|
|
1648
|
+
}
|
|
1649
|
+
musicLog(current, "error", `音乐工具失败(${tool.kind}):${messageOf(error)}`);
|
|
1650
|
+
});
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
async function markToolSubmitted(id, toolId, task) {
|
|
1654
|
+
await patchMusicJob(id, (current) => {
|
|
1655
|
+
const entry = current.tools.find((item) => item.id === toolId);
|
|
1656
|
+
if (entry !== undefined) {
|
|
1657
|
+
entry.status = task.status === "succeeded" || task.status === "failed" ? task.status : "polling";
|
|
1658
|
+
entry.remoteTaskId = task.taskId;
|
|
1659
|
+
entry.updatedAt = now();
|
|
1660
|
+
}
|
|
1661
|
+
});
|
|
1662
|
+
}
|
|
1663
|
+
async function pollTool(api, id, toolId, submitted) {
|
|
1664
|
+
let current = submitted;
|
|
1665
|
+
const deadline = now() + 15 * 60 * 1000;
|
|
1666
|
+
while (current.status !== "succeeded" && current.status !== "failed") {
|
|
1667
|
+
if (now() >= deadline)
|
|
1668
|
+
throw new Error("工具任务等待超时(15 分钟)");
|
|
1669
|
+
await sleep(5000);
|
|
1670
|
+
current = await toolTask(api, current.taskId || submitted.taskId);
|
|
1671
|
+
await patchMusicJob(id, (job) => {
|
|
1672
|
+
const entry = job.tools.find((item) => item.id === toolId);
|
|
1673
|
+
if (entry !== undefined) {
|
|
1674
|
+
entry.status = current.status === "succeeded" || current.status === "failed" ? current.status : "polling";
|
|
1675
|
+
entry.updatedAt = now();
|
|
1676
|
+
}
|
|
1677
|
+
});
|
|
1678
|
+
}
|
|
1679
|
+
if (current.status === "failed") {
|
|
1680
|
+
throw new Error(`工具任务失败:${JSON.stringify(current.raw).slice(0, 300)}`);
|
|
1681
|
+
}
|
|
1682
|
+
return current;
|
|
1683
|
+
}
|
|
1684
|
+
/** 从工具响应里收集可下载的 URL(stems 的 tracks / 转码的 url / tracks 都收)。 */
|
|
1685
|
+
function collectToolUrls(raw) {
|
|
1686
|
+
const out = [];
|
|
1687
|
+
const seen = new Set();
|
|
1688
|
+
const push = (name, url, ext) => {
|
|
1689
|
+
if (typeof url !== "string" || url === "" || seen.has(url))
|
|
1690
|
+
return;
|
|
1691
|
+
seen.add(url);
|
|
1692
|
+
out.push({ name, url, ext });
|
|
1693
|
+
};
|
|
1694
|
+
const result = raw?.result ?? raw;
|
|
1695
|
+
const tracks = Array.isArray(result?.tracks) ? result.tracks : [];
|
|
1696
|
+
for (const [index, track] of tracks.entries()) {
|
|
1697
|
+
const type = typeof track?.type === "string" ? track.type : `track-${index + 1}`;
|
|
1698
|
+
push(type, track?.url, typeof track?.format === "string" ? track.format : undefined);
|
|
1699
|
+
}
|
|
1700
|
+
push("audio", result?.url ?? result?.audio_url ?? result?.output_url);
|
|
1701
|
+
return out;
|
|
1702
|
+
}
|
|
1703
|
+
async function downloadToolFiles(id, toolId, raw, dir, fallbackExt) {
|
|
1704
|
+
const urls = collectToolUrls(raw);
|
|
1705
|
+
if (urls.length === 0)
|
|
1706
|
+
throw new Error(`工具任务完成但没有返回可下载文件:${JSON.stringify(raw).slice(0, 300)}`);
|
|
1707
|
+
const api = await requireApi();
|
|
1708
|
+
const files = [];
|
|
1709
|
+
for (const entry of urls) {
|
|
1710
|
+
const downloaded = await downloadToFile(entry.url, dir, api, {
|
|
1711
|
+
stem: safeStem(entry.name),
|
|
1712
|
+
fallbackExt: entry.ext ?? fallbackExt,
|
|
1713
|
+
maxBytes: 200 * 1024 * 1024
|
|
1714
|
+
});
|
|
1715
|
+
files.push({
|
|
1716
|
+
name: `${safeStem(entry.name)}.${downloaded.ext}`,
|
|
1717
|
+
file: `tools/${toolId}/${downloaded.file.split(/[\\/]/u).pop()}`,
|
|
1718
|
+
bytes: downloaded.bytes
|
|
1719
|
+
});
|
|
1720
|
+
}
|
|
1721
|
+
await patchMusicJob(id, (current) => {
|
|
1722
|
+
const entry = current.tools.find((item) => item.id === toolId);
|
|
1723
|
+
if (entry !== undefined) {
|
|
1724
|
+
entry.status = "succeeded";
|
|
1725
|
+
entry.result = raw;
|
|
1726
|
+
entry.files = files;
|
|
1727
|
+
entry.updatedAt = now();
|
|
1728
|
+
}
|
|
1729
|
+
musicLog(current, "info", `工具产物已下载:${files.length} 个文件`);
|
|
1730
|
+
});
|
|
1731
|
+
}
|
|
1732
|
+
// ── 编辑 / 版本 ─────────────────────────────────────────────────────────
|
|
1733
|
+
function opsHashOf(sourceRelative, ops, sourceSize, sourceMtime) {
|
|
1734
|
+
return createHash("sha1")
|
|
1735
|
+
.update(`${sourceRelative}|${sourceSize}|${sourceMtime}|${JSON.stringify(ops)}`)
|
|
1736
|
+
.digest("hex");
|
|
1737
|
+
}
|
|
1738
|
+
/**
|
|
1739
|
+
* 渲染一次编辑(后台)。
|
|
1740
|
+
*
|
|
1741
|
+
* 返回预分配的 versionId:界面据此轮询到「这一版就绪」,而不是靠比较列表长度。
|
|
1742
|
+
* 相同源 + 相同 ops 默认复用已有版本(`force:true` 可强制重跑)。
|
|
1743
|
+
*/
|
|
1744
|
+
export async function renderMusicEdit(id, input) {
|
|
1745
|
+
assertJobId(id);
|
|
1746
|
+
const job = await readMusicJob(id);
|
|
1747
|
+
if (job === undefined)
|
|
1748
|
+
throw new Error(`音乐任务不存在:${id}`);
|
|
1749
|
+
const baseVersion = typeof input.versionId === "string" ? job.versions.find((version) => version.id === input.versionId && version.status === "ready") : undefined;
|
|
1750
|
+
const song = baseVersion !== undefined
|
|
1751
|
+
? job.songs.find((entry) => entry.id === baseVersion.songId)
|
|
1752
|
+
: job.songs.find((entry) => entry.id === (input.songId ?? job.songs.find((entry) => entry.status === "succeeded")?.id));
|
|
1753
|
+
if (song === undefined)
|
|
1754
|
+
throw new Error("任务里还没有可编辑的歌曲");
|
|
1755
|
+
if (baseVersion === undefined && song.localFile === undefined)
|
|
1756
|
+
await ensureLocalSong(id, song.id);
|
|
1757
|
+
// ensureLocalSong 写的是**磁盘上的 job**,上面的 `job` 还是旧对象;重新读一次再取 localFile。
|
|
1758
|
+
const fresh = baseVersion === undefined ? await readMusicJob(id) : job;
|
|
1759
|
+
const freshSong = fresh?.songs.find((entry) => entry.id === song.id) ?? song;
|
|
1760
|
+
const sourceRelative = baseVersion?.file ?? freshSong.localFile;
|
|
1761
|
+
if (sourceRelative === undefined)
|
|
1762
|
+
throw new Error("这首歌还没有下载到本地,无法编辑");
|
|
1763
|
+
const sourceFile = musicAssetPath(id, sourceRelative);
|
|
1764
|
+
const sourceInfo = await stat(sourceFile).catch(() => undefined);
|
|
1765
|
+
if (sourceInfo === undefined)
|
|
1766
|
+
throw new Error(`源音频不存在:${sourceRelative}`);
|
|
1767
|
+
const probe = await probeAudio(sourceFile);
|
|
1768
|
+
const ops = normalizeEditOps(input.ops ?? {}, probe.duration);
|
|
1769
|
+
const hash = opsHashOf(sourceRelative, ops, sourceInfo.size, sourceInfo.mtimeMs);
|
|
1770
|
+
if (input.force !== true) {
|
|
1771
|
+
const existing = job.versions.find((version) => version.opsHash === hash && version.status === "ready");
|
|
1772
|
+
if (existing !== undefined) {
|
|
1773
|
+
// 同一组参数先「试听」再「保存为版本」:直接把试听版转正,没必要再花一次本地渲染。
|
|
1774
|
+
if (input.preview !== true && existing.preview === true) {
|
|
1775
|
+
await patchMusicJob(id, (current) => {
|
|
1776
|
+
const entry = current.versions.find((version) => version.id === existing.id);
|
|
1777
|
+
if (entry !== undefined) {
|
|
1778
|
+
entry.preview = false;
|
|
1779
|
+
if (typeof input.label === "string" && input.label.trim() !== "")
|
|
1780
|
+
entry.label = input.label.trim().slice(0, 80);
|
|
1781
|
+
}
|
|
1782
|
+
musicLog(current, "info", `试听版转正:${entry?.label ?? existing.label}`);
|
|
1783
|
+
});
|
|
1784
|
+
}
|
|
1785
|
+
return { started: false, versionId: existing.id, reused: true, reason: input.preview !== true && existing.preview === true ? "试听版已转为正式版本" : "相同参数已有版本,直接复用" };
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
const versionId = `v${Date.now().toString(36)}${randomUUID().slice(0, 5)}`;
|
|
1789
|
+
const relative = `versions/${versionId}.${ops.format}`;
|
|
1790
|
+
const label = (typeof input.label === "string" && input.label.trim() !== "" ? input.label.trim() : describeOps(ops)).slice(0, 80);
|
|
1791
|
+
const createdAt = now();
|
|
1792
|
+
await patchMusicJob(id, (current) => {
|
|
1793
|
+
current.versions.push({
|
|
1794
|
+
id: versionId,
|
|
1795
|
+
songId: song.id,
|
|
1796
|
+
label,
|
|
1797
|
+
file: relative,
|
|
1798
|
+
format: ops.format,
|
|
1799
|
+
duration: ops.end - ops.start,
|
|
1800
|
+
size: 0,
|
|
1801
|
+
ops,
|
|
1802
|
+
opsHash: hash,
|
|
1803
|
+
preview: input.preview === true,
|
|
1804
|
+
status: "rendering",
|
|
1805
|
+
by: input.by === "ai" ? "ai" : "human",
|
|
1806
|
+
baseVersionId: baseVersion?.id,
|
|
1807
|
+
createdAt
|
|
1808
|
+
});
|
|
1809
|
+
current.stages.edit = { status: "running", at: createdAt };
|
|
1810
|
+
musicLog(current, "info", `开始渲染版本:${label}`);
|
|
1811
|
+
});
|
|
1812
|
+
const ok = trackMusicTask(id, `edit:${versionId}`, async () => {
|
|
1813
|
+
try {
|
|
1814
|
+
const rendered = await renderAudioEdit({ source: sourceFile, dest: musicAssetPath(id, relative), ops });
|
|
1815
|
+
await patchMusicJob(id, (current) => {
|
|
1816
|
+
const version = current.versions.find((entry) => entry.id === versionId);
|
|
1817
|
+
if (version !== undefined) {
|
|
1818
|
+
version.status = "ready";
|
|
1819
|
+
version.duration = rendered.duration;
|
|
1820
|
+
version.size = rendered.size;
|
|
1821
|
+
version.ops = rendered.ops;
|
|
1822
|
+
version.label = label;
|
|
1823
|
+
}
|
|
1824
|
+
current.stages.edit = { status: "done", at: now() };
|
|
1825
|
+
for (const warning of rendered.warnings)
|
|
1826
|
+
musicLog(current, "warn", warning);
|
|
1827
|
+
musicLog(current, "info", `版本已就绪:${label}(${rendered.duration.toFixed(1)} 秒)`);
|
|
1828
|
+
});
|
|
1829
|
+
}
|
|
1830
|
+
catch (error) {
|
|
1831
|
+
await patchMusicJob(id, (current) => {
|
|
1832
|
+
const version = current.versions.find((entry) => entry.id === versionId);
|
|
1833
|
+
if (version !== undefined) {
|
|
1834
|
+
version.status = "error";
|
|
1835
|
+
version.error = messageOf(error);
|
|
1836
|
+
}
|
|
1837
|
+
current.stages.edit = { status: "error", error: messageOf(error), at: now() };
|
|
1838
|
+
musicLog(current, "error", `版本渲染失败:${messageOf(error)}`);
|
|
1839
|
+
});
|
|
1840
|
+
}
|
|
1841
|
+
});
|
|
1842
|
+
if (!ok) {
|
|
1843
|
+
await patchMusicJob(id, (current) => {
|
|
1844
|
+
const version = current.versions.find((entry) => entry.id === versionId);
|
|
1845
|
+
if (version !== undefined) {
|
|
1846
|
+
version.status = "error";
|
|
1847
|
+
version.error = "后台任务没有启动";
|
|
1848
|
+
}
|
|
1849
|
+
current.stages.edit = { status: "error", error: "后台任务没有启动", at: now() };
|
|
1850
|
+
});
|
|
1851
|
+
return { started: false, versionId, reason: "后台任务没有启动,请重启插件后再试。" };
|
|
1852
|
+
}
|
|
1853
|
+
return { started: true, versionId };
|
|
1854
|
+
}
|
|
1855
|
+
export function describeOps(ops) {
|
|
1856
|
+
const parts = [];
|
|
1857
|
+
if (ops.start !== undefined || ops.end !== undefined)
|
|
1858
|
+
parts.push("裁剪");
|
|
1859
|
+
if (typeof ops.gainDb === "number" && ops.gainDb !== 0)
|
|
1860
|
+
parts.push(`${ops.gainDb > 0 ? "+" : ""}${ops.gainDb} dB`);
|
|
1861
|
+
if (typeof ops.fadeIn === "number" && ops.fadeIn > 0)
|
|
1862
|
+
parts.push(`淡入 ${ops.fadeIn}s`);
|
|
1863
|
+
if (typeof ops.fadeOut === "number" && ops.fadeOut > 0)
|
|
1864
|
+
parts.push(`淡出 ${ops.fadeOut}s`);
|
|
1865
|
+
if (ops.normalize === true)
|
|
1866
|
+
parts.push(`标准化 ${ops.lufs ?? -14} LUFS`);
|
|
1867
|
+
if (typeof ops.format === "string")
|
|
1868
|
+
parts.push(ops.format.toUpperCase());
|
|
1869
|
+
return parts.length === 0 ? "原始音频" : parts.join(" · ");
|
|
1870
|
+
}
|
|
1871
|
+
export async function saveMusicVersion(id, versionId, label) {
|
|
1872
|
+
assertJobId(id);
|
|
1873
|
+
const job = await patchMusicJob(id, (current) => {
|
|
1874
|
+
const version = current.versions.find((entry) => entry.id === versionId);
|
|
1875
|
+
if (version === undefined)
|
|
1876
|
+
throw new Error(`版本不存在:${versionId}`);
|
|
1877
|
+
version.preview = false;
|
|
1878
|
+
if (typeof label === "string" && label.trim() !== "")
|
|
1879
|
+
version.label = label.trim().slice(0, 80);
|
|
1880
|
+
musicLog(current, "info", `保存版本:${version.label}`);
|
|
1881
|
+
return current;
|
|
1882
|
+
});
|
|
1883
|
+
return musicSnapshot(job);
|
|
1884
|
+
}
|
|
1885
|
+
export async function deleteMusicVersion(id, versionId) {
|
|
1886
|
+
assertJobId(id);
|
|
1887
|
+
let file;
|
|
1888
|
+
await patchMusicJob(id, (job) => {
|
|
1889
|
+
const index = job.versions.findIndex((entry) => entry.id === versionId);
|
|
1890
|
+
if (index < 0)
|
|
1891
|
+
throw new Error(`版本不存在:${versionId}`);
|
|
1892
|
+
file = job.versions[index].file;
|
|
1893
|
+
job.versions.splice(index, 1);
|
|
1894
|
+
musicLog(job, "info", `删除版本:${versionId}`);
|
|
1895
|
+
});
|
|
1896
|
+
if (file !== undefined)
|
|
1897
|
+
await rm(musicAssetPath(id, file), { force: true }).catch(() => undefined);
|
|
1898
|
+
}
|
|
1899
|
+
// ── 波形 ────────────────────────────────────────────────────────────────
|
|
1900
|
+
export async function musicPeaks(id, input = {}, origin = originForLinks()) {
|
|
1901
|
+
assertJobId(id);
|
|
1902
|
+
const job = await readMusicJob(id);
|
|
1903
|
+
if (job === undefined)
|
|
1904
|
+
throw new Error(`音乐任务不存在:${id}`);
|
|
1905
|
+
let relative;
|
|
1906
|
+
if (typeof input.scoreId === "string" && input.scoreId !== "") {
|
|
1907
|
+
const composition = job.compositions.find((entry) => entry.id === input.scoreId);
|
|
1908
|
+
if (composition === undefined)
|
|
1909
|
+
throw new Error(`谱曲版本不存在:${input.scoreId}`);
|
|
1910
|
+
if (typeof composition.audioFile !== "string" || composition.audioFile === "") {
|
|
1911
|
+
throw new Error("这一版还没有试听音频,无法生成波形");
|
|
1912
|
+
}
|
|
1913
|
+
relative = composition.audioFile;
|
|
1914
|
+
}
|
|
1915
|
+
else {
|
|
1916
|
+
const version = typeof input.versionId === "string" ? job.versions.find((entry) => entry.id === input.versionId && entry.status === "ready") : undefined;
|
|
1917
|
+
const song = version !== undefined ? job.songs.find((entry) => entry.id === version.songId) : pickSong(job, input.songId);
|
|
1918
|
+
if (song === undefined)
|
|
1919
|
+
throw new Error("找不到对应歌曲");
|
|
1920
|
+
if (version === undefined && song.localFile === undefined)
|
|
1921
|
+
await ensureLocalSong(id, song.id);
|
|
1922
|
+
relative = version?.file ?? song.localFile;
|
|
1923
|
+
}
|
|
1924
|
+
if (relative === undefined)
|
|
1925
|
+
throw new Error("这首歌还没有下载到本地,无法生成波形");
|
|
1926
|
+
const file = musicAssetPath(id, relative);
|
|
1927
|
+
const info = await stat(file).catch(() => undefined);
|
|
1928
|
+
if (info === undefined)
|
|
1929
|
+
throw new Error(`音频文件不存在:${relative}`);
|
|
1930
|
+
const buckets = Math.min(2000, Math.max(64, Math.round(Number(input.buckets ?? 800))));
|
|
1931
|
+
const hash = createHash("sha1").update(`${relative}|${info.size}|${info.mtimeMs}|${buckets}`).digest("hex");
|
|
1932
|
+
const cacheFile = join(musicJobDir(id), "peaks", `${hash}.json`);
|
|
1933
|
+
const cached = await readJson(cacheFile);
|
|
1934
|
+
if (cached !== undefined && Array.isArray(cached.peaks)) {
|
|
1935
|
+
return { ...cached, file: relative, url: absUrl(origin, musicAssetBase(id), relative) ?? null };
|
|
1936
|
+
}
|
|
1937
|
+
const result = await audioPeaks(file, buckets);
|
|
1938
|
+
await writeJsonAtomic(cacheFile, result);
|
|
1939
|
+
return {
|
|
1940
|
+
peaks: result.peaks,
|
|
1941
|
+
buckets: result.buckets,
|
|
1942
|
+
duration: result.duration,
|
|
1943
|
+
file: relative,
|
|
1944
|
+
url: absUrl(origin, musicAssetBase(id), relative) ?? null
|
|
1945
|
+
};
|
|
1946
|
+
}
|
|
1947
|
+
function extOf(relative) {
|
|
1948
|
+
const match = /\.([a-z0-9]{2,5})$/iu.exec(relative);
|
|
1949
|
+
return (match?.[1] ?? "mp3").toLowerCase();
|
|
1950
|
+
}
|
|
1951
|
+
function normalizeExportFormat(value, fallback) {
|
|
1952
|
+
const raw = typeof value === "string" && value !== "" ? value : fallback;
|
|
1953
|
+
return MUSIC_EDIT_FORMATS.includes(raw) ? raw : "mp3";
|
|
1954
|
+
}
|
|
1955
|
+
async function uniqueExportPath(dir, stem, ext) {
|
|
1956
|
+
const safe = safeStem(stem);
|
|
1957
|
+
for (let index = 0; index < 1000; index++) {
|
|
1958
|
+
const name = index === 0 ? `${safe}.${ext}` : `${safe}-${index + 1}.${ext}`;
|
|
1959
|
+
const full = join(dir, name);
|
|
1960
|
+
if (!existsSync(full))
|
|
1961
|
+
return full;
|
|
1962
|
+
}
|
|
1963
|
+
throw new Error("导出文件名冲突太多");
|
|
1964
|
+
}
|
|
1965
|
+
/**
|
|
1966
|
+
* 导出到 `out/`。
|
|
1967
|
+
*
|
|
1968
|
+
* - 指定 versionId / songId:导出单个文件(必要时转码);
|
|
1969
|
+
* - 不指定:全部已完成的歌 + 已保存版本 + manifest.json,打成一个 zip;
|
|
1970
|
+
* - `zip:true` 时即使只有一个目标也打 zip。
|
|
1971
|
+
*/
|
|
1972
|
+
export async function exportMusic(id, input = {}, options = {}) {
|
|
1973
|
+
assertJobId(id);
|
|
1974
|
+
const job = await readMusicJob(id);
|
|
1975
|
+
if (job === undefined)
|
|
1976
|
+
throw new Error(`音乐任务不存在:${id}`);
|
|
1977
|
+
const outDir = join(musicJobDir(id), "out");
|
|
1978
|
+
await mkdir(outDir, { recursive: true });
|
|
1979
|
+
// 谱曲模式:导出一个「乐谱包」(MIDI + 试听 + 方案 + compose.py)。
|
|
1980
|
+
if (typeof input.scoreId === "string" && input.scoreId !== "") {
|
|
1981
|
+
const composition = job.compositions.find((entry) => entry.id === input.scoreId);
|
|
1982
|
+
if (composition === undefined)
|
|
1983
|
+
throw new Error(`谱曲版本不存在:${input.scoreId}`);
|
|
1984
|
+
if (composition.status !== "ready")
|
|
1985
|
+
throw new Error("这一版谱曲还没有完成,无法导出");
|
|
1986
|
+
const entries = await buildScoreBundle({
|
|
1987
|
+
job,
|
|
1988
|
+
composition,
|
|
1989
|
+
readFile: async (relative) => readFile(musicAssetPath(id, relative))
|
|
1990
|
+
});
|
|
1991
|
+
const zip = zipEntries(entries);
|
|
1992
|
+
const stem = `${safeStem(input.name ?? composition.title ?? job.name)}-${safeStem(composition.label)}`;
|
|
1993
|
+
const zipPath = await uniqueExportPath(outDir, stem, "zip");
|
|
1994
|
+
const { writeFile } = await import("node:fs/promises");
|
|
1995
|
+
await writeFile(zipPath, zip);
|
|
1996
|
+
const zipRelative = `out/${zipPath.split(/[\\/]/u).pop()}`;
|
|
1997
|
+
const record = {
|
|
1998
|
+
id: `e${Date.now().toString(36)}${randomUUID().slice(0, 5)}`,
|
|
1999
|
+
file: zipRelative,
|
|
2000
|
+
format: "zip",
|
|
2001
|
+
bytes: zip.length,
|
|
2002
|
+
createdAt: now(),
|
|
2003
|
+
scoreId: composition.id,
|
|
2004
|
+
files: entries.map((entry) => entry.path)
|
|
2005
|
+
};
|
|
2006
|
+
await patchMusicJob(id, (current) => {
|
|
2007
|
+
current.exports.push(record);
|
|
2008
|
+
current.stages.export = { status: "done", at: now() };
|
|
2009
|
+
musicLog(current, "info", `导出乐谱包:${zipRelative}(${entries.length} 个文件)`);
|
|
2010
|
+
});
|
|
2011
|
+
const origin = options.origin ?? originForLinks();
|
|
2012
|
+
const assetBase = musicAssetBase(id);
|
|
2013
|
+
return {
|
|
2014
|
+
ok: true,
|
|
2015
|
+
zip: true,
|
|
2016
|
+
file: zipRelative,
|
|
2017
|
+
path: zipPath,
|
|
2018
|
+
url: absUrl(origin, assetBase, zipRelative) ?? null,
|
|
2019
|
+
downloadUrl: absUrl(origin, assetBase, zipRelative) === undefined ? null : `${absUrl(origin, assetBase, zipRelative)}?download=1`,
|
|
2020
|
+
bytes: zip.length,
|
|
2021
|
+
files: entries.map((entry) => ({ path: entry.path, bytes: entry.data.length })),
|
|
2022
|
+
name: `${stem}.zip`,
|
|
2023
|
+
scoreId: composition.id
|
|
2024
|
+
};
|
|
2025
|
+
}
|
|
2026
|
+
const targets = [];
|
|
2027
|
+
if (typeof input.versionId === "string") {
|
|
2028
|
+
const version = job.versions.find((entry) => entry.id === input.versionId && entry.status === "ready");
|
|
2029
|
+
if (version === undefined)
|
|
2030
|
+
throw new Error(`版本不存在或尚未完成:${input.versionId}`);
|
|
2031
|
+
const song = job.songs.find((entry) => entry.id === version.songId);
|
|
2032
|
+
targets.push({
|
|
2033
|
+
label: `${song?.title ?? job.name} · ${version.label}`,
|
|
2034
|
+
sourceRelative: version.file,
|
|
2035
|
+
format: normalizeExportFormat(input.format, version.format),
|
|
2036
|
+
songId: song?.id,
|
|
2037
|
+
versionId: version.id
|
|
2038
|
+
});
|
|
2039
|
+
}
|
|
2040
|
+
else if (typeof input.songId === "string") {
|
|
2041
|
+
const song = job.songs.find((entry) => entry.id === input.songId);
|
|
2042
|
+
if (song === undefined)
|
|
2043
|
+
throw new Error(`歌曲不存在:${input.songId}`);
|
|
2044
|
+
if (song.localFile === undefined)
|
|
2045
|
+
await ensureLocalSong(id, song.id);
|
|
2046
|
+
if (song.localFile === undefined)
|
|
2047
|
+
throw new Error("歌曲还没有下载到本地");
|
|
2048
|
+
targets.push({
|
|
2049
|
+
label: song.title ?? job.name,
|
|
2050
|
+
sourceRelative: song.localFile,
|
|
2051
|
+
format: normalizeExportFormat(input.format, extOf(song.localFile)),
|
|
2052
|
+
songId: song.id
|
|
2053
|
+
});
|
|
2054
|
+
}
|
|
2055
|
+
else {
|
|
2056
|
+
for (const song of job.songs.filter((entry) => entry.status === "succeeded")) {
|
|
2057
|
+
if (song.localFile === undefined)
|
|
2058
|
+
await ensureLocalSong(id, song.id).catch(() => undefined);
|
|
2059
|
+
if (song.localFile === undefined)
|
|
2060
|
+
continue;
|
|
2061
|
+
targets.push({
|
|
2062
|
+
label: song.title ?? job.name,
|
|
2063
|
+
sourceRelative: song.localFile,
|
|
2064
|
+
format: normalizeExportFormat(input.format, extOf(song.localFile)),
|
|
2065
|
+
songId: song.id
|
|
2066
|
+
});
|
|
2067
|
+
}
|
|
2068
|
+
for (const version of job.versions.filter((entry) => entry.status === "ready" && entry.preview !== true)) {
|
|
2069
|
+
targets.push({
|
|
2070
|
+
label: `${job.name} · ${version.label}`,
|
|
2071
|
+
sourceRelative: version.file,
|
|
2072
|
+
format: normalizeExportFormat(input.format, version.format),
|
|
2073
|
+
versionId: version.id
|
|
2074
|
+
});
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
if (targets.length === 0)
|
|
2078
|
+
throw new Error("任务里没有可导出的歌曲或版本");
|
|
2079
|
+
const exported = [];
|
|
2080
|
+
for (const target of targets) {
|
|
2081
|
+
const source = musicAssetPath(id, target.sourceRelative);
|
|
2082
|
+
const sourceExt = extOf(target.sourceRelative);
|
|
2083
|
+
const desiredName = targets.length === 1 && typeof input.name === "string" && input.name.trim() !== "" ? input.name.trim() : target.label;
|
|
2084
|
+
const dest = await uniqueExportPath(outDir, desiredName, target.format);
|
|
2085
|
+
if (sourceExt === target.format) {
|
|
2086
|
+
const { copyFile } = await import("node:fs/promises");
|
|
2087
|
+
await copyFile(source, dest);
|
|
2088
|
+
}
|
|
2089
|
+
else {
|
|
2090
|
+
await renderAudioEdit({ source, dest, ops: { format: target.format } });
|
|
2091
|
+
}
|
|
2092
|
+
const info = await stat(dest);
|
|
2093
|
+
exported.push({ label: target.label, file: `out/${dest.split(/[\\/]/u).pop()}`, bytes: info.size, format: target.format });
|
|
2094
|
+
}
|
|
2095
|
+
const origin = options.origin ?? originForLinks();
|
|
2096
|
+
const assetBase = musicAssetBase(id);
|
|
2097
|
+
if (exported.length === 1 && input.zip !== true) {
|
|
2098
|
+
const entry = exported[0];
|
|
2099
|
+
const record = {
|
|
2100
|
+
id: `e${Date.now().toString(36)}${randomUUID().slice(0, 5)}`,
|
|
2101
|
+
file: entry.file,
|
|
2102
|
+
format: entry.format,
|
|
2103
|
+
bytes: entry.bytes,
|
|
2104
|
+
createdAt: now(),
|
|
2105
|
+
songId: targets[0].songId,
|
|
2106
|
+
versionId: targets[0].versionId
|
|
2107
|
+
};
|
|
2108
|
+
await patchMusicJob(id, (current) => {
|
|
2109
|
+
current.exports.push(record);
|
|
2110
|
+
current.stages.export = { status: "done", at: now() };
|
|
2111
|
+
musicLog(current, "info", `导出:${entry.file}`);
|
|
2112
|
+
});
|
|
2113
|
+
return {
|
|
2114
|
+
ok: true,
|
|
2115
|
+
file: entry.file,
|
|
2116
|
+
path: musicAssetPath(id, entry.file),
|
|
2117
|
+
url: absUrl(origin, assetBase, entry.file) ?? null,
|
|
2118
|
+
downloadUrl: absUrl(origin, assetBase, entry.file) === undefined ? null : `${absUrl(origin, assetBase, entry.file)}?download=1`,
|
|
2119
|
+
bytes: entry.bytes,
|
|
2120
|
+
format: entry.format
|
|
2121
|
+
};
|
|
2122
|
+
}
|
|
2123
|
+
const manifest = {
|
|
2124
|
+
job: { id: job.id, name: job.name, createdAt: job.createdAt },
|
|
2125
|
+
platform: "谱乐 AI (YourMusic)",
|
|
2126
|
+
exportedAt: new Date().toISOString(),
|
|
2127
|
+
files: exported,
|
|
2128
|
+
songs: job.songs.filter((song) => song.status === "succeeded").map((song) => ({
|
|
2129
|
+
id: song.id,
|
|
2130
|
+
title: song.title,
|
|
2131
|
+
duration: song.duration,
|
|
2132
|
+
tags: song.tags,
|
|
2133
|
+
lyric: song.lyric,
|
|
2134
|
+
modelName: song.modelName
|
|
2135
|
+
})),
|
|
2136
|
+
versions: job.versions.filter((version) => version.status === "ready").map((version) => ({
|
|
2137
|
+
id: version.id,
|
|
2138
|
+
songId: version.songId,
|
|
2139
|
+
label: version.label,
|
|
2140
|
+
format: version.format,
|
|
2141
|
+
duration: version.duration,
|
|
2142
|
+
ops: version.ops
|
|
2143
|
+
}))
|
|
2144
|
+
};
|
|
2145
|
+
const entries = [];
|
|
2146
|
+
for (const entry of exported) {
|
|
2147
|
+
const { readFile } = await import("node:fs/promises");
|
|
2148
|
+
entries.push({ path: entry.file.replace(/^out\//u, ""), data: await readFile(musicAssetPath(id, entry.file)) });
|
|
2149
|
+
}
|
|
2150
|
+
entries.push({ path: "manifest.json", data: Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`, "utf8") });
|
|
2151
|
+
const zip = zipEntries(entries);
|
|
2152
|
+
const zipName = `${safeStem(input.name ?? job.name)}.zip`;
|
|
2153
|
+
const zipPath = await uniqueExportPath(outDir, `${safeStem(input.name ?? job.name)}`, "zip");
|
|
2154
|
+
const { writeFile } = await import("node:fs/promises");
|
|
2155
|
+
await writeFile(zipPath, zip);
|
|
2156
|
+
const zipRelative = `out/${zipPath.split(/[\\/]/u).pop()}`;
|
|
2157
|
+
const record = {
|
|
2158
|
+
id: `e${Date.now().toString(36)}${randomUUID().slice(0, 5)}`,
|
|
2159
|
+
file: zipRelative,
|
|
2160
|
+
format: "zip",
|
|
2161
|
+
bytes: zip.length,
|
|
2162
|
+
createdAt: now(),
|
|
2163
|
+
files: exported.map((entry) => entry.file)
|
|
2164
|
+
};
|
|
2165
|
+
await patchMusicJob(id, (current) => {
|
|
2166
|
+
current.exports.push(record);
|
|
2167
|
+
current.stages.export = { status: "done", at: now() };
|
|
2168
|
+
musicLog(current, "info", `导出打包:${zipRelative}(${exported.length} 个文件)`);
|
|
2169
|
+
});
|
|
2170
|
+
return {
|
|
2171
|
+
ok: true,
|
|
2172
|
+
zip: true,
|
|
2173
|
+
file: zipRelative,
|
|
2174
|
+
path: zipPath,
|
|
2175
|
+
url: absUrl(origin, assetBase, zipRelative) ?? null,
|
|
2176
|
+
downloadUrl: absUrl(origin, assetBase, zipRelative) === undefined ? null : `${absUrl(origin, assetBase, zipRelative)}?download=1`,
|
|
2177
|
+
bytes: zip.length,
|
|
2178
|
+
files: exported,
|
|
2179
|
+
name: zipName
|
|
2180
|
+
};
|
|
2181
|
+
}
|
|
2182
|
+
// ── 杂项 ────────────────────────────────────────────────────────────────
|
|
2183
|
+
/** 供工具面/界面展示「历史里有哪些歌」(只读,不生成)。 */
|
|
2184
|
+
export async function listMusicHistory(input = {}) {
|
|
2185
|
+
const api = await requireApi();
|
|
2186
|
+
const history = await musicHistory(api, input);
|
|
2187
|
+
return history;
|
|
2188
|
+
}
|
|
2189
|
+
/** 清理任务目录里遗留的 tmp(读任务时顺手做一次,别让它们越积越多)。 */
|
|
2190
|
+
export async function sweepMusicJob(id) {
|
|
2191
|
+
await sweepTempFiles(musicJobDir(id)).catch(() => undefined);
|
|
2192
|
+
}
|
|
2193
|
+
/** 给工具面用的「任务是否存在」判断(不读全量 job)。 */
|
|
2194
|
+
export async function musicJobExists(id) {
|
|
2195
|
+
if (!isValidMusicJobId(id))
|
|
2196
|
+
return false;
|
|
2197
|
+
try {
|
|
2198
|
+
await stat(musicJobFile(id));
|
|
2199
|
+
return true;
|
|
2200
|
+
}
|
|
2201
|
+
catch {
|
|
2202
|
+
return false;
|
|
2203
|
+
}
|
|
2204
|
+
}
|
|
2205
|
+
/** 给 `links.ts` / 工具面用的「打开任务」链接。 */
|
|
2206
|
+
export function musicOpenLink(id, stage, scoreId) {
|
|
2207
|
+
return buildOpenLink({
|
|
2208
|
+
module: "music",
|
|
2209
|
+
jobId: id,
|
|
2210
|
+
...(stage === undefined ? {} : { stage }),
|
|
2211
|
+
...(scoreId === undefined || scoreId === "" ? {} : { scoreId })
|
|
2212
|
+
});
|
|
2213
|
+
}
|
|
2214
|
+
/** 任务里的引擎 key(避免界面重复实现)。 */
|
|
2215
|
+
export const MUSIC_ENGINE_KEYS = [...MUSIC_ENGINES];
|