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
|
@@ -0,0 +1,931 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 谱曲模式的宿主侧核心:方案归一化、依赖探测、scoremill 脚本执行、
|
|
3
|
+
* MIDI 试听渲染、Suno 交接参数、乐谱导出包。
|
|
4
|
+
*
|
|
5
|
+
* 这个文件**不碰任务目录**(那是 `musicgen.ts` 的事),只接收路径与配置,
|
|
6
|
+
* 这样 `musicgen.ts` 可以单向依赖它,避免循环 import。
|
|
7
|
+
*
|
|
8
|
+
* ## 依赖
|
|
9
|
+
*
|
|
10
|
+
* 谱曲本身依赖本机 `python3 + scoremill`(插件不打包 Python,也不把
|
|
11
|
+
* scoremill 改写成 JS)。试听优先 FluidSynth + SoundFont;缺失时用
|
|
12
|
+
* `midipreview.ts` 的内置合成器兜底。两者都没有时仍然保留 MIDI 供下载。
|
|
13
|
+
*/
|
|
14
|
+
import { spawn } from "node:child_process";
|
|
15
|
+
import { existsSync, readdirSync, statSync } from "node:fs";
|
|
16
|
+
import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
17
|
+
import { homedir } from "node:os";
|
|
18
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
19
|
+
import { ffmpegPath, runFfmpeg } from "./media.js";
|
|
20
|
+
import { parseMidiFile } from "./midifile.js";
|
|
21
|
+
import { renderMidiToWav } from "./midipreview.js";
|
|
22
|
+
// ── 小工具 ──────────────────────────────────────────────────────────────
|
|
23
|
+
function clampString(value, max) {
|
|
24
|
+
return typeof value === "string" ? value.slice(0, max) : "";
|
|
25
|
+
}
|
|
26
|
+
function finite(value) {
|
|
27
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
28
|
+
return value;
|
|
29
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
30
|
+
const parsed = Number(value);
|
|
31
|
+
if (Number.isFinite(parsed))
|
|
32
|
+
return parsed;
|
|
33
|
+
}
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
function clampNumber(value, min, max) {
|
|
37
|
+
const number = finite(value);
|
|
38
|
+
if (number === undefined)
|
|
39
|
+
return undefined;
|
|
40
|
+
return Math.min(max, Math.max(min, number));
|
|
41
|
+
}
|
|
42
|
+
function expandHome(value) {
|
|
43
|
+
if (value === "~")
|
|
44
|
+
return homedir();
|
|
45
|
+
if (value.startsWith("~/") || value.startsWith("~\\"))
|
|
46
|
+
return join(homedir(), value.slice(2));
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
function listDir(dir) {
|
|
50
|
+
try {
|
|
51
|
+
return readdirSync(dir);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return [];
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
// ── 方案归一化 ──────────────────────────────────────────────────────────
|
|
58
|
+
/** 把 agent 传来的方案收敛成稳定结构;缺失字段留空,由界面/提示词兜底。 */
|
|
59
|
+
export function normalizeScorePlan(input) {
|
|
60
|
+
const raw = (input ?? {});
|
|
61
|
+
const plan = {};
|
|
62
|
+
const summary = clampString(raw.summary, 20000).trim();
|
|
63
|
+
if (summary !== "")
|
|
64
|
+
plan.summary = summary;
|
|
65
|
+
const style = clampString(raw.style, 300).trim();
|
|
66
|
+
if (style !== "")
|
|
67
|
+
plan.style = style;
|
|
68
|
+
const mood = clampString(raw.mood, 300).trim();
|
|
69
|
+
if (mood !== "")
|
|
70
|
+
plan.mood = mood;
|
|
71
|
+
const key = clampString(raw.key, 80).trim();
|
|
72
|
+
if (key !== "")
|
|
73
|
+
plan.key = key;
|
|
74
|
+
const tempo = clampNumber(raw.tempo, 20, 400);
|
|
75
|
+
if (tempo !== undefined)
|
|
76
|
+
plan.tempo = tempo;
|
|
77
|
+
const timeSignature = clampString(raw.timeSignature, 20).trim();
|
|
78
|
+
if (timeSignature !== "")
|
|
79
|
+
plan.timeSignature = timeSignature;
|
|
80
|
+
const lengthBars = clampNumber(raw.lengthBars, 1, 2000);
|
|
81
|
+
if (lengthBars !== undefined)
|
|
82
|
+
plan.lengthBars = Math.round(lengthBars);
|
|
83
|
+
const durationTarget = clampNumber(raw.durationTarget, 1, 900);
|
|
84
|
+
if (durationTarget !== undefined)
|
|
85
|
+
plan.durationTarget = durationTarget;
|
|
86
|
+
if (typeof raw.instrumental === "boolean")
|
|
87
|
+
plan.instrumental = raw.instrumental;
|
|
88
|
+
if (Array.isArray(raw.structure)) {
|
|
89
|
+
const structure = [];
|
|
90
|
+
for (const entry of raw.structure.slice(0, 64)) {
|
|
91
|
+
if (typeof entry === "string") {
|
|
92
|
+
const name = entry.trim().slice(0, 80);
|
|
93
|
+
if (name !== "")
|
|
94
|
+
structure.push({ name });
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (entry === null || typeof entry !== "object")
|
|
98
|
+
continue;
|
|
99
|
+
const name = clampString(entry.name, 80).trim();
|
|
100
|
+
if (name === "")
|
|
101
|
+
continue;
|
|
102
|
+
const bars = clampNumber(entry.bars, 1, 512);
|
|
103
|
+
const energy = clampString(entry.energy, 80).trim();
|
|
104
|
+
const description = clampString(entry.description, 500).trim();
|
|
105
|
+
structure.push({
|
|
106
|
+
name,
|
|
107
|
+
...(bars === undefined ? {} : { bars: Math.round(bars) }),
|
|
108
|
+
...(energy === "" ? {} : { energy }),
|
|
109
|
+
...(description === "" ? {} : { description })
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
if (structure.length > 0)
|
|
113
|
+
plan.structure = structure;
|
|
114
|
+
}
|
|
115
|
+
else if (typeof raw.structure === "string" && raw.structure.trim() !== "") {
|
|
116
|
+
// 容错:agent 把段落表写成一整段文字时,别再丢掉它。
|
|
117
|
+
plan.notes = [clampString(raw.notes, 4000), raw.structure.slice(0, 4000)].filter((entry) => entry.trim() !== "").join("\n");
|
|
118
|
+
}
|
|
119
|
+
if (Array.isArray(raw.instrumentation)) {
|
|
120
|
+
const instrumentation = [];
|
|
121
|
+
for (const entry of raw.instrumentation.slice(0, 64)) {
|
|
122
|
+
if (typeof entry === "string") {
|
|
123
|
+
const name = entry.trim().slice(0, 80);
|
|
124
|
+
if (name !== "")
|
|
125
|
+
instrumentation.push({ name });
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (entry === null || typeof entry !== "object")
|
|
129
|
+
continue;
|
|
130
|
+
const name = clampString(entry.name, 80).trim();
|
|
131
|
+
if (name === "")
|
|
132
|
+
continue;
|
|
133
|
+
const program = clampNumber(entry.program, 0, 127);
|
|
134
|
+
const channel = clampNumber(entry.channel, 0, 15);
|
|
135
|
+
const role = clampString(entry.role, 80).trim();
|
|
136
|
+
instrumentation.push({
|
|
137
|
+
name,
|
|
138
|
+
...(program === undefined ? {} : { program: Math.round(program) }),
|
|
139
|
+
...(channel === undefined ? {} : { channel: Math.round(channel) }),
|
|
140
|
+
...(role === "" ? {} : { role })
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
if (instrumentation.length > 0)
|
|
144
|
+
plan.instrumentation = instrumentation;
|
|
145
|
+
}
|
|
146
|
+
const motif = clampString(raw.motif, 2000).trim();
|
|
147
|
+
if (motif !== "")
|
|
148
|
+
plan.motif = motif;
|
|
149
|
+
const notes = clampString(raw.notes, 8000).trim();
|
|
150
|
+
if (notes !== "")
|
|
151
|
+
plan.notes = notes;
|
|
152
|
+
const lyrics = clampString(raw.lyrics, 10000).trim();
|
|
153
|
+
if (lyrics !== "")
|
|
154
|
+
plan.lyrics = lyrics;
|
|
155
|
+
const sunoTags = clampString(raw.sunoTags ?? raw.suno_tags, 1000).trim();
|
|
156
|
+
if (sunoTags !== "")
|
|
157
|
+
plan.sunoTags = sunoTags;
|
|
158
|
+
const sunoPrompt = clampString(raw.sunoPrompt ?? raw.suno_prompt, 500).trim();
|
|
159
|
+
if (sunoPrompt !== "")
|
|
160
|
+
plan.sunoPrompt = sunoPrompt;
|
|
161
|
+
const negativeTags = clampString(raw.negativeTags ?? raw.negative_tags, 1000).trim();
|
|
162
|
+
if (negativeTags !== "")
|
|
163
|
+
plan.negativeTags = negativeTags;
|
|
164
|
+
return plan;
|
|
165
|
+
}
|
|
166
|
+
/** 方案是否足够开始谱曲(至少得有点方向,不然只是空任务)。 */
|
|
167
|
+
export function scorePlanReady(plan) {
|
|
168
|
+
if (plan === undefined)
|
|
169
|
+
return false;
|
|
170
|
+
return ((plan.summary ?? "").trim() !== "" ||
|
|
171
|
+
(plan.style ?? "").trim() !== "" ||
|
|
172
|
+
(plan.structure ?? []).length > 0 ||
|
|
173
|
+
(plan.notes ?? "").trim() !== "");
|
|
174
|
+
}
|
|
175
|
+
/** 白名单环境:绝不让 compose.py 看到任何 API Key / 凭据。 */
|
|
176
|
+
function scoreEnv() {
|
|
177
|
+
const keep = [
|
|
178
|
+
"PATH",
|
|
179
|
+
"HOME",
|
|
180
|
+
"TMPDIR",
|
|
181
|
+
"TEMP",
|
|
182
|
+
"TMP",
|
|
183
|
+
"LANG",
|
|
184
|
+
"LC_ALL",
|
|
185
|
+
"LC_CTYPE",
|
|
186
|
+
"SYSTEMROOT",
|
|
187
|
+
"USERPROFILE",
|
|
188
|
+
"APPDATA",
|
|
189
|
+
"LOCALAPPDATA",
|
|
190
|
+
"PROGRAMDATA",
|
|
191
|
+
"PROGRAMFILES",
|
|
192
|
+
"PROGRAMFILES(X86)",
|
|
193
|
+
"COMSPEC",
|
|
194
|
+
"PATHEXT"
|
|
195
|
+
];
|
|
196
|
+
const env = {};
|
|
197
|
+
for (const key of keep) {
|
|
198
|
+
const value = process.env[key];
|
|
199
|
+
if (value !== undefined)
|
|
200
|
+
env[key] = value;
|
|
201
|
+
}
|
|
202
|
+
env.PYTHONIOENCODING = "utf-8";
|
|
203
|
+
env.PYTHONDONTWRITEBYTECODE = "1";
|
|
204
|
+
env.PYTHONHASHSEED = "0";
|
|
205
|
+
env.MPLBACKEND = "Agg";
|
|
206
|
+
return env;
|
|
207
|
+
}
|
|
208
|
+
function killTree(child) {
|
|
209
|
+
if (child.pid === undefined)
|
|
210
|
+
return;
|
|
211
|
+
if (process.platform === "win32") {
|
|
212
|
+
try {
|
|
213
|
+
spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
try {
|
|
217
|
+
child.kill("SIGKILL");
|
|
218
|
+
}
|
|
219
|
+
catch { /* ignore */ }
|
|
220
|
+
}
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
process.kill(-child.pid, "SIGKILL");
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
try {
|
|
228
|
+
child.kill("SIGKILL");
|
|
229
|
+
}
|
|
230
|
+
catch { /* ignore */ }
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
function runProcess(command, args, options = {}) {
|
|
234
|
+
const timeoutMs = Math.max(1000, options.timeoutMs ?? 30000);
|
|
235
|
+
const maxBytes = Math.max(4096, options.maxBytes ?? 1_000_000);
|
|
236
|
+
return new Promise((resolvePromise) => {
|
|
237
|
+
let child;
|
|
238
|
+
try {
|
|
239
|
+
child = spawn(command, args, {
|
|
240
|
+
cwd: options.cwd,
|
|
241
|
+
env: options.env ?? scoreEnv(),
|
|
242
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
243
|
+
windowsHide: true,
|
|
244
|
+
detached: options.detached === true
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
resolvePromise({ code: null, stdout: "", stderr: "", error: error instanceof Error ? error.message : String(error), timedOut: false });
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
const stdout = [];
|
|
252
|
+
const stderr = [];
|
|
253
|
+
let stdoutBytes = 0;
|
|
254
|
+
let stderrBytes = 0;
|
|
255
|
+
let timedOut = false;
|
|
256
|
+
let settled = false;
|
|
257
|
+
const timer = setTimeout(() => {
|
|
258
|
+
timedOut = true;
|
|
259
|
+
killTree(child);
|
|
260
|
+
}, timeoutMs);
|
|
261
|
+
const finish = (code, error) => {
|
|
262
|
+
if (settled)
|
|
263
|
+
return;
|
|
264
|
+
settled = true;
|
|
265
|
+
clearTimeout(timer);
|
|
266
|
+
resolvePromise({
|
|
267
|
+
code,
|
|
268
|
+
stdout: Buffer.concat(stdout).toString("utf8"),
|
|
269
|
+
stderr: Buffer.concat(stderr).toString("utf8"),
|
|
270
|
+
error,
|
|
271
|
+
timedOut
|
|
272
|
+
});
|
|
273
|
+
};
|
|
274
|
+
child.stdout?.on("data", (chunk) => {
|
|
275
|
+
if (stdoutBytes >= maxBytes)
|
|
276
|
+
return;
|
|
277
|
+
const remaining = maxBytes - stdoutBytes;
|
|
278
|
+
const slice = chunk.length > remaining ? chunk.subarray(0, remaining) : chunk;
|
|
279
|
+
stdout.push(slice);
|
|
280
|
+
stdoutBytes += slice.length;
|
|
281
|
+
});
|
|
282
|
+
child.stderr?.on("data", (chunk) => {
|
|
283
|
+
if (stderrBytes >= maxBytes)
|
|
284
|
+
return;
|
|
285
|
+
const remaining = maxBytes - stderrBytes;
|
|
286
|
+
const slice = chunk.length > remaining ? chunk.subarray(0, remaining) : chunk;
|
|
287
|
+
stderr.push(slice);
|
|
288
|
+
stderrBytes += slice.length;
|
|
289
|
+
});
|
|
290
|
+
child.on("error", (error) => finish(null, error.message));
|
|
291
|
+
child.on("close", (code) => finish(code));
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
function firstLine(text) {
|
|
295
|
+
return text.split(/\r?\n/u).map((line) => line.trim()).find((line) => line !== "") ?? "";
|
|
296
|
+
}
|
|
297
|
+
function pythonCandidates(config) {
|
|
298
|
+
const list = [];
|
|
299
|
+
const add = (command, args = [], path = command) => {
|
|
300
|
+
if (command.trim() === "")
|
|
301
|
+
return;
|
|
302
|
+
if (!list.some((entry) => entry.command === command && entry.args.join("\u0000") === args.join("\u0000"))) {
|
|
303
|
+
list.push({ command, args, path });
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
const configured = (config.musicPythonPath ?? "").trim();
|
|
307
|
+
if (configured !== "")
|
|
308
|
+
add(expandHome(configured), [], configured);
|
|
309
|
+
const fromEnv = (process.env.GMM_PYTHON ?? process.env.PYTHON_PATH ?? "").trim();
|
|
310
|
+
if (fromEnv !== "")
|
|
311
|
+
add(expandHome(fromEnv), [], fromEnv);
|
|
312
|
+
add("python3", [], "python3");
|
|
313
|
+
add("python", [], "python");
|
|
314
|
+
if (process.platform === "win32")
|
|
315
|
+
add("py", ["-3"], "py -3");
|
|
316
|
+
return list;
|
|
317
|
+
}
|
|
318
|
+
async function probePython(config) {
|
|
319
|
+
let lastError = "没有找到可用的 Python";
|
|
320
|
+
for (const candidate of pythonCandidates(config)) {
|
|
321
|
+
const result = await runProcess(candidate.command, [...candidate.args, "-c", "import sys, scoremill; print(sys.version.split()[0]); print(getattr(scoremill, '__version__', 'unknown'))"], { timeoutMs: 15000 });
|
|
322
|
+
if (result.code === 0) {
|
|
323
|
+
const lines = result.stdout.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean);
|
|
324
|
+
return {
|
|
325
|
+
python: { ok: true, path: candidate.command, args: candidate.args, version: lines[0] ?? "" },
|
|
326
|
+
scoremill: { ok: true, version: lines[1] ?? "unknown" }
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
lastError = (result.error ?? firstLine(result.stderr) ?? "").trim() || `Python 退出码 ${result.code}`;
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
python: { ok: false, error: lastError },
|
|
333
|
+
scoremill: { ok: false, error: "找不到可导入 scoremill 的 Python" }
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
function fluidSynthCandidates(config) {
|
|
337
|
+
const list = [];
|
|
338
|
+
const add = (value) => {
|
|
339
|
+
const trimmed = (value ?? "").trim();
|
|
340
|
+
if (trimmed !== "" && !list.includes(trimmed))
|
|
341
|
+
list.push(trimmed);
|
|
342
|
+
};
|
|
343
|
+
add(config.musicFluidsynthPath);
|
|
344
|
+
add(process.env.GMM_FLUIDSYNTH);
|
|
345
|
+
add(process.env.FLUIDSYNTH_PATH);
|
|
346
|
+
if (process.platform === "darwin") {
|
|
347
|
+
add("/opt/homebrew/bin/fluidsynth");
|
|
348
|
+
add("/usr/local/bin/fluidsynth");
|
|
349
|
+
}
|
|
350
|
+
add("/usr/bin/fluidsynth");
|
|
351
|
+
add("/usr/local/bin/fluidsynth");
|
|
352
|
+
if (process.platform === "win32") {
|
|
353
|
+
const programFiles = process.env.ProgramFiles ?? "C:\\Program Files";
|
|
354
|
+
add(join(programFiles, "fluid-synth", "bin", "fluidsynth.exe"));
|
|
355
|
+
add("C:\\Program Files (x86)\\fluid-synth\\bin\\fluidsynth.exe");
|
|
356
|
+
}
|
|
357
|
+
add("fluidsynth");
|
|
358
|
+
return list;
|
|
359
|
+
}
|
|
360
|
+
async function probeFluidSynth(config) {
|
|
361
|
+
let lastError = "找不到 fluidsynth";
|
|
362
|
+
for (const candidate of fluidSynthCandidates(config)) {
|
|
363
|
+
const isAbsoluteCandidate = isAbsolute(candidate);
|
|
364
|
+
if (isAbsoluteCandidate && !existsSync(candidate))
|
|
365
|
+
continue;
|
|
366
|
+
const result = await runProcess(candidate, ["--version"], { timeoutMs: 8000 });
|
|
367
|
+
if (result.code === 0) {
|
|
368
|
+
const match = /FluidSynth(?:\s+runtime)?\s+version\s+([0-9.]+)/iu.exec(`${result.stdout}\n${result.stderr}`);
|
|
369
|
+
return { ok: true, path: candidate, version: match?.[1] ?? firstLine(result.stdout) };
|
|
370
|
+
}
|
|
371
|
+
lastError = result.error ?? firstLine(result.stderr) ?? `退出码 ${result.code}`;
|
|
372
|
+
}
|
|
373
|
+
return { ok: false, error: lastError };
|
|
374
|
+
}
|
|
375
|
+
function soundfontCandidates(config) {
|
|
376
|
+
const list = [];
|
|
377
|
+
const add = (value) => {
|
|
378
|
+
const trimmed = (value ?? "").trim();
|
|
379
|
+
if (trimmed === "")
|
|
380
|
+
return;
|
|
381
|
+
const expanded = expandHome(trimmed);
|
|
382
|
+
if (!list.includes(expanded))
|
|
383
|
+
list.push(expanded);
|
|
384
|
+
};
|
|
385
|
+
add(config.musicSoundfontPath);
|
|
386
|
+
add(process.env.GMM_SF2);
|
|
387
|
+
add(process.env.SF);
|
|
388
|
+
const dirs = [
|
|
389
|
+
join(homedir(), "Library", "Audio", "SoundFonts"),
|
|
390
|
+
join(homedir(), ".local", "share", "soundfonts"),
|
|
391
|
+
join(homedir(), "soundfonts"),
|
|
392
|
+
"/usr/share/sounds/sf2",
|
|
393
|
+
"/usr/share/soundfonts",
|
|
394
|
+
"/usr/local/share/soundfonts"
|
|
395
|
+
];
|
|
396
|
+
if (process.platform === "win32") {
|
|
397
|
+
const profile = process.env.USERPROFILE ?? "";
|
|
398
|
+
if (profile !== "")
|
|
399
|
+
dirs.push(join(profile, "soundfonts"));
|
|
400
|
+
dirs.push("C:\\soundfonts");
|
|
401
|
+
}
|
|
402
|
+
for (const dir of dirs) {
|
|
403
|
+
for (const name of listDir(dir)) {
|
|
404
|
+
if (/\.sf2$/iu.test(name))
|
|
405
|
+
add(join(dir, name));
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
// Homebrew 自带的 FluidSynth 会带一个很小的 SF2;有大的用户音源时优先用大的。
|
|
409
|
+
const cellar = "/opt/homebrew/Cellar/fluid-synth";
|
|
410
|
+
for (const version of listDir(cellar).slice(0, 4)) {
|
|
411
|
+
const dir = join(cellar, version, "share", "fluid-synth", "sf2");
|
|
412
|
+
for (const name of listDir(dir)) {
|
|
413
|
+
if (/\.sf2$/iu.test(name))
|
|
414
|
+
add(join(dir, name));
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
const ranked = [...list].sort((a, b) => {
|
|
418
|
+
const score = (value) => {
|
|
419
|
+
const lower = value.toLowerCase();
|
|
420
|
+
if (lower.includes("fluidr3"))
|
|
421
|
+
return 3;
|
|
422
|
+
if (/(^|[\\/])gm|general.?midi/u.test(lower))
|
|
423
|
+
return 2;
|
|
424
|
+
if (lower.includes("vintage"))
|
|
425
|
+
return 1;
|
|
426
|
+
return 0;
|
|
427
|
+
};
|
|
428
|
+
return score(b) - score(a);
|
|
429
|
+
});
|
|
430
|
+
return ranked;
|
|
431
|
+
}
|
|
432
|
+
function findSoundfont(config) {
|
|
433
|
+
for (const candidate of soundfontCandidates(config)) {
|
|
434
|
+
try {
|
|
435
|
+
const info = existsSync(candidate) ? statSync(candidate) : undefined;
|
|
436
|
+
if (info !== undefined && info.isFile() && info.size > 0)
|
|
437
|
+
return { ok: true, path: candidate };
|
|
438
|
+
}
|
|
439
|
+
catch {
|
|
440
|
+
/* ignore */
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
return { ok: false, error: "找不到 SoundFont(.sf2)" };
|
|
444
|
+
}
|
|
445
|
+
async function probeFfmpeg() {
|
|
446
|
+
const path = ffmpegPath();
|
|
447
|
+
const result = await runProcess(path, ["-version"], { timeoutMs: 8000 });
|
|
448
|
+
if (result.code !== 0)
|
|
449
|
+
return { ok: false, path, error: result.error ?? firstLine(result.stderr) ?? `退出码 ${result.code}` };
|
|
450
|
+
const match = /ffmpeg version\s+([^\s]+)/iu.exec(result.stdout);
|
|
451
|
+
return { ok: true, path, version: match?.[1] ?? firstLine(result.stdout) };
|
|
452
|
+
}
|
|
453
|
+
let depsCache;
|
|
454
|
+
let depsPending;
|
|
455
|
+
/** 探测谱曲依赖。缓存 30 秒;`force` 用于设置页「重新检测」。 */
|
|
456
|
+
export async function detectScoreDeps(config = {}, options = {}) {
|
|
457
|
+
const key = `${config.musicPythonPath ?? ""}|${config.musicFluidsynthPath ?? ""}|${config.musicSoundfontPath ?? ""}`;
|
|
458
|
+
const now = Date.now();
|
|
459
|
+
if (!options.force && depsCache !== undefined && depsCache.key === key && now - depsCache.at < 30000)
|
|
460
|
+
return depsCache.status;
|
|
461
|
+
if (!options.force && depsPending !== undefined && depsPending.key === key)
|
|
462
|
+
return depsPending.promise;
|
|
463
|
+
const promise = (async () => {
|
|
464
|
+
const [{ python, scoremill }, fluidsynth, ffmpeg] = await Promise.all([
|
|
465
|
+
probePython(config),
|
|
466
|
+
probeFluidSynth(config),
|
|
467
|
+
probeFfmpeg()
|
|
468
|
+
]);
|
|
469
|
+
const soundfont = findSoundfont(config);
|
|
470
|
+
const warnings = [];
|
|
471
|
+
let blocker = null;
|
|
472
|
+
if (!python.ok) {
|
|
473
|
+
blocker = "找不到可用的 Python 3。请安装 Python 3,或在「设置 → 游戏素材大师 → 谱曲模式」里指定 python3 的绝对路径。";
|
|
474
|
+
}
|
|
475
|
+
else if (!scoremill.ok) {
|
|
476
|
+
const pythonLabel = [python.path ?? "python3", ...(python.args ?? [])].join(" ");
|
|
477
|
+
blocker = `Python 可用(${pythonLabel}),但没有安装 scoremill。请运行:${pythonLabel} -m pip install scoremill`;
|
|
478
|
+
}
|
|
479
|
+
if (!fluidsynth.ok)
|
|
480
|
+
warnings.push("没找到 FluidSynth:试听会用插件内置的简易音源(能听清曲式,但音色不如 SoundFont)。");
|
|
481
|
+
if (!soundfont.ok)
|
|
482
|
+
warnings.push("没找到 SoundFont(.sf2):即使有 FluidSynth 也会退回内置简易音源。可把 FluidR3_GM.sf2 放到 ~/Library/Audio/SoundFonts/。");
|
|
483
|
+
if (!ffmpeg.ok)
|
|
484
|
+
warnings.push("没找到 ffmpeg:试听会保留 WAV,MP3/导出可能不可用。");
|
|
485
|
+
// 自检 / 排障时可以强制用内置音源,避免依赖本机 SoundFont。
|
|
486
|
+
const forceBuiltin = (process.env.GMM_SCORE_RENDERER ?? "").trim().toLowerCase() === "builtin";
|
|
487
|
+
if (forceBuiltin)
|
|
488
|
+
warnings.push("已按 GMM_SCORE_RENDERER=builtin 强制使用内置简易音源。");
|
|
489
|
+
const renderer = !forceBuiltin && fluidsynth.ok && soundfont.ok ? "fluidsynth" : "builtin";
|
|
490
|
+
const status = {
|
|
491
|
+
ok: blocker === null,
|
|
492
|
+
renderer,
|
|
493
|
+
python,
|
|
494
|
+
scoremill,
|
|
495
|
+
fluidsynth,
|
|
496
|
+
soundfont,
|
|
497
|
+
ffmpeg,
|
|
498
|
+
blocker,
|
|
499
|
+
warnings,
|
|
500
|
+
checkedAt: Date.now()
|
|
501
|
+
};
|
|
502
|
+
depsCache = { key, at: Date.now(), status };
|
|
503
|
+
return status;
|
|
504
|
+
})();
|
|
505
|
+
depsPending = { key, promise };
|
|
506
|
+
try {
|
|
507
|
+
return await promise;
|
|
508
|
+
}
|
|
509
|
+
finally {
|
|
510
|
+
if (depsPending?.promise === promise)
|
|
511
|
+
depsPending = undefined;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
/** 设置页改了路径后清缓存,下一次 getConfig 立即重新探测。 */
|
|
515
|
+
export function clearScoreDepsCache() {
|
|
516
|
+
depsCache = undefined;
|
|
517
|
+
}
|
|
518
|
+
function parseReportFromStdout(stdout) {
|
|
519
|
+
const lines = stdout.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean);
|
|
520
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
521
|
+
if (!lines[i].startsWith("{"))
|
|
522
|
+
continue;
|
|
523
|
+
try {
|
|
524
|
+
const parsed = JSON.parse(lines[i]);
|
|
525
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed))
|
|
526
|
+
return parsed;
|
|
527
|
+
}
|
|
528
|
+
catch {
|
|
529
|
+
// 不是 JSON 的普通日志行,继续往前找。
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
return undefined;
|
|
533
|
+
}
|
|
534
|
+
function findMidiFile(scoreDir) {
|
|
535
|
+
const exact = join(scoreDir, "score.mid");
|
|
536
|
+
if (existsSync(exact))
|
|
537
|
+
return exact;
|
|
538
|
+
const candidates = listDir(scoreDir).filter((name) => /\.mid$/iu.test(name) && !/-mix\.mid$/iu.test(name));
|
|
539
|
+
if (candidates.length === 1)
|
|
540
|
+
return join(scoreDir, candidates[0]);
|
|
541
|
+
return undefined;
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* 写 compose.py 并执行。
|
|
545
|
+
*
|
|
546
|
+
* 约定:脚本必须在 cwd 里 `s.save("score.mid")`;不自己渲染音频。
|
|
547
|
+
* 输出上限 1MB,超时杀进程组;失败时保留脚本与日志供 agent 修正。
|
|
548
|
+
*/
|
|
549
|
+
export async function runScoreScript(input) {
|
|
550
|
+
const { scoreDir, script, pythonPath } = input;
|
|
551
|
+
if (script.trim() === "")
|
|
552
|
+
throw new Error("compose.py 是空的:请先写一份 scoremill 记谱脚本。");
|
|
553
|
+
if (script.length > 200_000)
|
|
554
|
+
throw new Error(`compose.py 太大(${script.length} 字符,上限 200000)。`);
|
|
555
|
+
await mkdir(scoreDir, { recursive: true });
|
|
556
|
+
await writeFile(join(scoreDir, "compose.py"), script, "utf8");
|
|
557
|
+
const result = await runProcess(pythonPath, [...(input.pythonArgs ?? []), "compose.py"], {
|
|
558
|
+
cwd: scoreDir,
|
|
559
|
+
env: scoreEnv(),
|
|
560
|
+
timeoutMs: input.timeoutMs ?? 180000,
|
|
561
|
+
maxBytes: 1_000_000,
|
|
562
|
+
detached: process.platform !== "win32"
|
|
563
|
+
});
|
|
564
|
+
await writeFile(join(scoreDir, "run.log"), [
|
|
565
|
+
`python: ${pythonPath}`,
|
|
566
|
+
`exit: ${result.code}${result.timedOut ? " (timeout)" : ""}`,
|
|
567
|
+
result.error === undefined ? "" : `error: ${result.error}`,
|
|
568
|
+
"",
|
|
569
|
+
"--- stdout ---",
|
|
570
|
+
result.stdout,
|
|
571
|
+
"",
|
|
572
|
+
"--- stderr ---",
|
|
573
|
+
result.stderr
|
|
574
|
+
].join("\n"), "utf8");
|
|
575
|
+
if (result.timedOut) {
|
|
576
|
+
throw new Error(`谱曲脚本超时(${Math.round((input.timeoutMs ?? 180000) / 1000)} 秒)。请缩短曲子或检查脚本里是否有死循环。\n${result.stderr.slice(-2000)}`);
|
|
577
|
+
}
|
|
578
|
+
if (result.code !== 0) {
|
|
579
|
+
const detail = (result.stderr.trim() !== "" ? result.stderr : result.stdout).slice(-4000);
|
|
580
|
+
throw new Error(`谱曲脚本运行失败(退出码 ${result.code ?? "?"}):\n${detail || "(没有输出)"}`);
|
|
581
|
+
}
|
|
582
|
+
const midiPath = findMidiFile(scoreDir);
|
|
583
|
+
if (midiPath === undefined) {
|
|
584
|
+
throw new Error(`脚本跑完了,但没有找到 score.mid。请确认脚本最后调用了 s.save("score.mid")。\n` +
|
|
585
|
+
`stdout:${result.stdout.slice(-1500) || "(空)"}\nstderr:${result.stderr.slice(-1500) || "(空)"}`);
|
|
586
|
+
}
|
|
587
|
+
const buffer = await readFile(midiPath);
|
|
588
|
+
const parsed = parseMidiFile(buffer);
|
|
589
|
+
if (parsed.meta.duration > 600) {
|
|
590
|
+
throw new Error(`MIDI 时长 ${parsed.meta.duration.toFixed(1)} 秒,超过 10 分钟上限;请缩短曲子。`);
|
|
591
|
+
}
|
|
592
|
+
const report = parseReportFromStdout(result.stdout);
|
|
593
|
+
if (report !== undefined)
|
|
594
|
+
await writeFile(join(scoreDir, "report.json"), `${JSON.stringify(report, null, 2)}\n`, "utf8");
|
|
595
|
+
return { ok: true, code: result.code, stdout: result.stdout, stderr: result.stderr, timedOut: false, midiPath, parsed, report };
|
|
596
|
+
}
|
|
597
|
+
async function fileHasBytes(path) {
|
|
598
|
+
try {
|
|
599
|
+
const info = await stat(path);
|
|
600
|
+
return info.isFile() && info.size > 0;
|
|
601
|
+
}
|
|
602
|
+
catch {
|
|
603
|
+
return false;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
/** 用 ffmpeg 量峰值并归一化到 -1 dBFS;失败时原样返回。 */
|
|
607
|
+
async function normalizePeak(wavPath) {
|
|
608
|
+
const warnings = [];
|
|
609
|
+
let measured;
|
|
610
|
+
try {
|
|
611
|
+
measured = await runFfmpeg(["-hide_banner", "-i", wavPath, "-af", "volumedetect", "-f", "null", "-"], 60000);
|
|
612
|
+
}
|
|
613
|
+
catch {
|
|
614
|
+
return warnings;
|
|
615
|
+
}
|
|
616
|
+
const text = `${measured.stderr}\n${measured.stdout.toString("utf8")}`;
|
|
617
|
+
const match = /max_volume:\s*(-?[0-9.]+)\s*dB/iu.exec(text);
|
|
618
|
+
if (match === null)
|
|
619
|
+
return warnings;
|
|
620
|
+
const maxVolume = Number(match[1]);
|
|
621
|
+
if (!Number.isFinite(maxVolume))
|
|
622
|
+
return warnings;
|
|
623
|
+
const gain = -1 - maxVolume;
|
|
624
|
+
if (Math.abs(gain) < 1)
|
|
625
|
+
return warnings;
|
|
626
|
+
const gainClamped = Math.max(-12, Math.min(12, gain));
|
|
627
|
+
const temp = `${wavPath}.norm.wav`;
|
|
628
|
+
try {
|
|
629
|
+
await runFfmpeg(["-hide_banner", "-loglevel", "error", "-y", "-i", wavPath, "-af", `volume=${gainClamped.toFixed(2)}dB`, temp], 120000);
|
|
630
|
+
}
|
|
631
|
+
catch {
|
|
632
|
+
warnings.push("试听峰值归一化失败,按原始音量播放。");
|
|
633
|
+
return warnings;
|
|
634
|
+
}
|
|
635
|
+
if (await fileHasBytes(temp)) {
|
|
636
|
+
await rm(wavPath, { force: true });
|
|
637
|
+
await rename(temp, wavPath);
|
|
638
|
+
}
|
|
639
|
+
else {
|
|
640
|
+
warnings.push("试听峰值归一化失败,按原始音量播放。");
|
|
641
|
+
}
|
|
642
|
+
return warnings;
|
|
643
|
+
}
|
|
644
|
+
/** 渲染试听音频:FluidSynth 优先,内置合成器兜底,再转 MP3。 */
|
|
645
|
+
export async function renderScoreAudio(input) {
|
|
646
|
+
const warnings = [];
|
|
647
|
+
const wavPath = join(input.outDir, "preview.wav");
|
|
648
|
+
const mp3Path = join(input.outDir, "preview.mp3");
|
|
649
|
+
let renderer;
|
|
650
|
+
let renderError;
|
|
651
|
+
if (input.deps.renderer === "fluidsynth" && input.deps.fluidsynth.ok && input.deps.soundfont.ok) {
|
|
652
|
+
const result = await runProcess(input.deps.fluidsynth.path ?? "fluidsynth", [
|
|
653
|
+
"-ni",
|
|
654
|
+
"-F",
|
|
655
|
+
wavPath,
|
|
656
|
+
"-r",
|
|
657
|
+
"44100",
|
|
658
|
+
"-g",
|
|
659
|
+
"0.75",
|
|
660
|
+
"-o",
|
|
661
|
+
"synth.reverb.active=1",
|
|
662
|
+
"-o",
|
|
663
|
+
"synth.reverb.room-size=0.78",
|
|
664
|
+
"-o",
|
|
665
|
+
"synth.reverb.damp=0.5",
|
|
666
|
+
"-o",
|
|
667
|
+
"synth.reverb.width=0.9",
|
|
668
|
+
"-o",
|
|
669
|
+
"synth.reverb.level=0.7",
|
|
670
|
+
input.deps.soundfont.path,
|
|
671
|
+
input.midiPath
|
|
672
|
+
], { timeoutMs: input.timeoutMs ?? 180000, maxBytes: 500_000 });
|
|
673
|
+
if (result.code === 0 && (await fileHasBytes(wavPath))) {
|
|
674
|
+
renderer = "fluidsynth";
|
|
675
|
+
warnings.push(...(await normalizePeak(wavPath)));
|
|
676
|
+
}
|
|
677
|
+
else {
|
|
678
|
+
renderError = (result.stderr || result.stdout || result.error || "FluidSynth 渲染失败").slice(-1500);
|
|
679
|
+
warnings.push("FluidSynth 渲染失败,已改用内置简易音源。");
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
if (renderer === undefined) {
|
|
683
|
+
try {
|
|
684
|
+
const builtin = renderMidiToWav(input.parsed, { sampleRate: 44100, maxSeconds: 480 });
|
|
685
|
+
await writeFile(wavPath, builtin.wav);
|
|
686
|
+
renderer = "builtin";
|
|
687
|
+
if (builtin.truncated)
|
|
688
|
+
warnings.push(`曲子超过 ${Math.round(builtin.duration)} 秒,内置试听只渲染了前 ${Math.round(builtin.duration)} 秒;完整音频请装 FluidSynth 或下载 MIDI。`);
|
|
689
|
+
}
|
|
690
|
+
catch (error) {
|
|
691
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
692
|
+
return { error: `试听渲染失败:${message}${renderError === undefined ? "" : `;FluidSynth:${renderError}`}`, warnings, duration: input.parsed.meta.duration };
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
// WAV → MP3;失败就保留 WAV。
|
|
696
|
+
try {
|
|
697
|
+
await runFfmpeg(["-hide_banner", "-loglevel", "error", "-y", "-i", wavPath, "-codec:a", "libmp3lame", "-b:a", "192k", mp3Path], 180000);
|
|
698
|
+
}
|
|
699
|
+
catch {
|
|
700
|
+
warnings.push("MP3 转码失败,试听保留 WAV。");
|
|
701
|
+
}
|
|
702
|
+
if (await fileHasBytes(mp3Path)) {
|
|
703
|
+
await rm(wavPath, { force: true });
|
|
704
|
+
return { audioFile: `${input.relativePrefix}preview.mp3`, renderer, warnings, duration: input.parsed.meta.duration };
|
|
705
|
+
}
|
|
706
|
+
return { audioFile: `${input.relativePrefix}preview.wav`, renderer, warnings, duration: input.parsed.meta.duration };
|
|
707
|
+
}
|
|
708
|
+
function dedupeWords(values, max) {
|
|
709
|
+
const seen = new Set();
|
|
710
|
+
const out = [];
|
|
711
|
+
for (const value of values) {
|
|
712
|
+
const trimmed = (value ?? "").trim();
|
|
713
|
+
if (trimmed === "")
|
|
714
|
+
continue;
|
|
715
|
+
const key = trimmed.toLowerCase();
|
|
716
|
+
if (seen.has(key))
|
|
717
|
+
continue;
|
|
718
|
+
seen.add(key);
|
|
719
|
+
out.push(trimmed);
|
|
720
|
+
if (out.length >= max)
|
|
721
|
+
break;
|
|
722
|
+
}
|
|
723
|
+
return out;
|
|
724
|
+
}
|
|
725
|
+
function tagsFromPlan(plan) {
|
|
726
|
+
const structure = (plan.structure ?? []).map((section) => `${section.name}${section.energy ? ` ${section.energy}` : ""}`);
|
|
727
|
+
const parts = dedupeWords([
|
|
728
|
+
plan.style,
|
|
729
|
+
plan.mood,
|
|
730
|
+
plan.instrumental === false ? undefined : "instrumental",
|
|
731
|
+
...(plan.instrumentation ?? []).map((entry) => entry.name),
|
|
732
|
+
plan.tempo === undefined ? undefined : `${Math.round(plan.tempo)} BPM`,
|
|
733
|
+
plan.key,
|
|
734
|
+
plan.timeSignature,
|
|
735
|
+
"game soundtrack",
|
|
736
|
+
...structure
|
|
737
|
+
], 24);
|
|
738
|
+
const text = parts.join(", ");
|
|
739
|
+
if (text.length <= 1000)
|
|
740
|
+
return text;
|
|
741
|
+
// 逐项丢弃,别在词中间截断。
|
|
742
|
+
const kept = [];
|
|
743
|
+
for (const part of parts) {
|
|
744
|
+
const next = [...kept, part].join(", ");
|
|
745
|
+
if (next.length > 1000)
|
|
746
|
+
break;
|
|
747
|
+
kept.push(part);
|
|
748
|
+
}
|
|
749
|
+
return kept.join(", ").slice(0, 1000);
|
|
750
|
+
}
|
|
751
|
+
function promptFromPlan(plan) {
|
|
752
|
+
const structure = (plan.structure ?? [])
|
|
753
|
+
.map((section) => `${section.name}${section.bars ? ` (${section.bars} bars)` : ""}${section.energy ? ` ${section.energy}` : ""}`)
|
|
754
|
+
.join(" → ");
|
|
755
|
+
const instruments = (plan.instrumentation ?? []).map((entry) => entry.name).join(", ");
|
|
756
|
+
const lines = [
|
|
757
|
+
plan.instrumental === false ? "Vocal game soundtrack." : "Instrumental game soundtrack.",
|
|
758
|
+
plan.style ? `${plan.style}.` : "",
|
|
759
|
+
plan.mood ? `${plan.mood}.` : "",
|
|
760
|
+
[plan.tempo ? `${Math.round(plan.tempo)} BPM` : "", plan.key, plan.timeSignature].filter(Boolean).join(", ") + ".",
|
|
761
|
+
structure ? `Structure: ${structure}.` : "",
|
|
762
|
+
instruments ? `Instrumentation: ${instruments}.` : "",
|
|
763
|
+
plan.motif ? `Motif: ${plan.motif}.` : ""
|
|
764
|
+
].filter((line) => line.trim() !== "");
|
|
765
|
+
const text = lines.join(" ");
|
|
766
|
+
if (text.length <= 500)
|
|
767
|
+
return text;
|
|
768
|
+
const cut = text.slice(0, 500);
|
|
769
|
+
const lastSpace = cut.lastIndexOf(" ");
|
|
770
|
+
return (lastSpace > 300 ? cut.slice(0, lastSpace) : cut).trim();
|
|
771
|
+
}
|
|
772
|
+
/**
|
|
773
|
+
* 把谱曲方案翻译成 Suno 请求。
|
|
774
|
+
*
|
|
775
|
+
* Suno 不接受 MIDI 原文件,但接受音频:`submitMusicScoreToSuno` 会先把这一版的
|
|
776
|
+
* 试听音频上传到 `/v1/suno/audio/upload`,再用返回的 song id 走 cover。这里负责
|
|
777
|
+
* 把方案翻译成 cover 的 tags / lyrics / 时长 / audio_weight;结果不会逐音一致。
|
|
778
|
+
*/
|
|
779
|
+
export function buildScoreSunoParams(input) {
|
|
780
|
+
const plan = input.composition.plan;
|
|
781
|
+
const overrides = input.overrides ?? {};
|
|
782
|
+
const requestedInstrumental = typeof overrides.instrumental === "boolean" ? overrides.instrumental : undefined;
|
|
783
|
+
const lyrics = clampString(overrides.lyrics ?? plan.lyrics ?? input.job.source?.lyrics, 5000).trim();
|
|
784
|
+
const instrumental = requestedInstrumental ?? (plan.instrumental !== false && lyrics === "");
|
|
785
|
+
const title = clampString(overrides.title ?? input.composition.title ?? input.job.name, 80).trim() || input.job.name;
|
|
786
|
+
const tags = clampString(overrides.tags ?? plan.sunoTags, 1000).trim() || tagsFromPlan(plan) || "instrumental game soundtrack";
|
|
787
|
+
const prompt = clampString(overrides.prompt ?? plan.sunoPrompt, 500).trim() || promptFromPlan(plan);
|
|
788
|
+
const negativeTags = clampString(overrides.negativeTags ?? plan.negativeTags ?? input.job.settings?.negativeTags, 1000).trim();
|
|
789
|
+
const requestedDuration = finite(overrides.duration) ?? plan.durationTarget ?? input.composition.midi.duration;
|
|
790
|
+
const duration = Math.max(10, Math.min(360, Math.round(requestedDuration)));
|
|
791
|
+
const warnings = [];
|
|
792
|
+
if (requestedDuration > 360) {
|
|
793
|
+
warnings.push(`原曲约 ${Math.round(requestedDuration)} 秒,超过 Suno 的 360 秒上限;提交时按 360 秒。`);
|
|
794
|
+
}
|
|
795
|
+
if (!instrumental && lyrics === "") {
|
|
796
|
+
warnings.push("方案里没有歌词:Suno 会按纯音乐处理。");
|
|
797
|
+
}
|
|
798
|
+
const coverClipId = clampString(input.coverClipId ?? overrides.coverClipId, 200).trim();
|
|
799
|
+
if (coverClipId !== "") {
|
|
800
|
+
// 音频条件生成:把本地渲染的 MIDI 试听上传成参考音频,再让 Suno cover。
|
|
801
|
+
// CoverDto 没有 instrumental 字段;纯音乐参考通常保持纯音乐,但平台不保证。
|
|
802
|
+
const coverInstrumental = instrumental || lyrics === "";
|
|
803
|
+
const params = {
|
|
804
|
+
title,
|
|
805
|
+
tags,
|
|
806
|
+
duration,
|
|
807
|
+
negativeTags,
|
|
808
|
+
prompt,
|
|
809
|
+
coverClipId,
|
|
810
|
+
audioWeight: clampNumber(input.audioWeight ?? overrides.audioWeight, 0, 1) ?? 0.75
|
|
811
|
+
};
|
|
812
|
+
if (!coverInstrumental)
|
|
813
|
+
params.lyrics = lyrics;
|
|
814
|
+
if (coverInstrumental)
|
|
815
|
+
warnings.push("Suno cover 没有 instrumental 开关;参考音频是纯音乐,通常结果也是纯音乐,若出现人声可用 negativeTags 约束。");
|
|
816
|
+
return {
|
|
817
|
+
engine: "suno",
|
|
818
|
+
mode: "cover",
|
|
819
|
+
model: typeof overrides.model === "string" && overrides.model.trim() !== "" ? overrides.model.trim() : input.job.settings?.model,
|
|
820
|
+
params,
|
|
821
|
+
warnings
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
const params = {
|
|
825
|
+
title,
|
|
826
|
+
tags,
|
|
827
|
+
instrumental: instrumental || lyrics === "",
|
|
828
|
+
duration,
|
|
829
|
+
negativeTags,
|
|
830
|
+
prompt
|
|
831
|
+
};
|
|
832
|
+
if (!params.instrumental)
|
|
833
|
+
params.lyrics = lyrics;
|
|
834
|
+
return {
|
|
835
|
+
engine: "suno",
|
|
836
|
+
mode: "custom",
|
|
837
|
+
model: typeof overrides.model === "string" && overrides.model.trim() !== "" ? overrides.model.trim() : input.job.settings?.model,
|
|
838
|
+
params,
|
|
839
|
+
warnings
|
|
840
|
+
};
|
|
841
|
+
}
|
|
842
|
+
// ── 乐谱导出包 ──────────────────────────────────────────────────────────
|
|
843
|
+
function formatPlanMarkdown(job, composition) {
|
|
844
|
+
const plan = composition.plan;
|
|
845
|
+
const lines = [
|
|
846
|
+
`# ${composition.title || job.name}`,
|
|
847
|
+
"",
|
|
848
|
+
`- 版本:${composition.label}`,
|
|
849
|
+
`- 风格:${plan.style ?? "—"}`,
|
|
850
|
+
`- 情绪:${plan.mood ?? "—"}`,
|
|
851
|
+
`- 调性:${plan.key ?? "—"}`,
|
|
852
|
+
`- 速度:${plan.tempo ?? "—"} BPM`,
|
|
853
|
+
`- 拍号:${plan.timeSignature ?? "—"}`,
|
|
854
|
+
`- 时长:${composition.midi.duration.toFixed(1)} 秒 · ${composition.midi.bars} 小节`,
|
|
855
|
+
`- 纯音乐:${plan.instrumental === false ? "否" : "是"}`,
|
|
856
|
+
""
|
|
857
|
+
];
|
|
858
|
+
if ((plan.structure ?? []).length > 0) {
|
|
859
|
+
lines.push("## 段落", "", "| 段落 | 小节 | 能量 | 说明 |", "|---|---:|---|---|");
|
|
860
|
+
for (const section of plan.structure ?? []) {
|
|
861
|
+
lines.push(`| ${section.name} | ${section.bars ?? "—"} | ${section.energy ?? "—"} | ${section.description ?? ""} |`);
|
|
862
|
+
}
|
|
863
|
+
lines.push("");
|
|
864
|
+
}
|
|
865
|
+
if ((plan.instrumentation ?? []).length > 0) {
|
|
866
|
+
lines.push("## 配器", "");
|
|
867
|
+
for (const entry of plan.instrumentation ?? []) {
|
|
868
|
+
const extras = [entry.program === undefined ? "" : `GM ${entry.program}`, entry.channel === undefined ? "" : `通道 ${entry.channel}`, entry.role ?? ""].filter(Boolean);
|
|
869
|
+
lines.push(`- ${entry.name}${extras.length > 0 ? `(${extras.join(" · ")})` : ""}`);
|
|
870
|
+
}
|
|
871
|
+
lines.push("");
|
|
872
|
+
}
|
|
873
|
+
if (plan.motif)
|
|
874
|
+
lines.push("## 主题动机", "", plan.motif, "");
|
|
875
|
+
if (plan.notes)
|
|
876
|
+
lines.push("## 备注", "", plan.notes, "");
|
|
877
|
+
if (plan.summary)
|
|
878
|
+
lines.push("## 方案原文", "", plan.summary, "");
|
|
879
|
+
lines.push("## 文件", "", "- `score.mid`:MIDI 总谱(Type 0/1,PPQ 480)", "- `preview.mp3` / `preview.wav`:试听", "- `compose.py`:scoremill 记谱脚本(可继续改)", "", "Suno 交接说明:Suno 不接受 MIDI 原文件,但接受音频;插件会先把本方案的试听音频上传为参考(标准上传免费),再用 cover 生成。若 Suno 判定版权,需要走付费版权上传通道。结果不会逐音一致。", "");
|
|
880
|
+
return lines.join("\n");
|
|
881
|
+
}
|
|
882
|
+
/** 生成乐谱包条目(调用方负责写 zip)。 */
|
|
883
|
+
export async function buildScoreBundle(input) {
|
|
884
|
+
const entries = [];
|
|
885
|
+
const base = input.composition.label.replace(/[\\/:*?"<>|]/gu, "_").slice(0, 40) || "score";
|
|
886
|
+
const read = async (relative) => {
|
|
887
|
+
if (relative === undefined || relative === "")
|
|
888
|
+
return undefined;
|
|
889
|
+
try {
|
|
890
|
+
return await input.readFile(relative);
|
|
891
|
+
}
|
|
892
|
+
catch {
|
|
893
|
+
return undefined;
|
|
894
|
+
}
|
|
895
|
+
};
|
|
896
|
+
const midi = await read(input.composition.midiFile);
|
|
897
|
+
if (midi === undefined)
|
|
898
|
+
throw new Error("这一版没有可导出的 MIDI");
|
|
899
|
+
entries.push({ path: `${base}/score.mid`, data: midi });
|
|
900
|
+
const audio = await read(input.composition.audioFile);
|
|
901
|
+
if (audio !== undefined) {
|
|
902
|
+
const ext = input.composition.audioFile?.split(".").pop() ?? "mp3";
|
|
903
|
+
entries.push({ path: `${base}/preview.${ext}`, data: audio });
|
|
904
|
+
}
|
|
905
|
+
entries.push({ path: `${base}/plan.md`, data: Buffer.from(formatPlanMarkdown(input.job, input.composition), "utf8") });
|
|
906
|
+
entries.push({ path: `${base}/compose.py`, data: Buffer.from(input.composition.script, "utf8") });
|
|
907
|
+
entries.push({
|
|
908
|
+
path: `${base}/README.txt`,
|
|
909
|
+
data: Buffer.from([
|
|
910
|
+
`# ${input.composition.title || input.job.name}`,
|
|
911
|
+
"",
|
|
912
|
+
"score.mid MIDI 总谱",
|
|
913
|
+
"preview.* 试听",
|
|
914
|
+
"plan.md 曲式 / 配器 / 段落说明",
|
|
915
|
+
"compose.py scoremill 记谱脚本",
|
|
916
|
+
"",
|
|
917
|
+
"这是本地用 scoremill 写出的 MIDI;交给 Suno 时插件会先把 preview 音频上传为参考,再走 cover(不上传 MIDI 原文件)。",
|
|
918
|
+
""
|
|
919
|
+
].join("\n"), "utf8")
|
|
920
|
+
});
|
|
921
|
+
return entries;
|
|
922
|
+
}
|
|
923
|
+
/** 把相对路径安全地拼到任务目录下(导出前再挡一次目录穿越)。 */
|
|
924
|
+
export function resolveJobRelative(jobDir, relative) {
|
|
925
|
+
const base = resolve(jobDir);
|
|
926
|
+
const target = resolve(base, relative);
|
|
927
|
+
if (target !== base && !target.startsWith(base + "/") && !target.startsWith(base + "\\")) {
|
|
928
|
+
throw new Error(`非法的任务内路径:${relative}`);
|
|
929
|
+
}
|
|
930
|
+
return target;
|
|
931
|
+
}
|