dsh-game-material-master 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/sfxapi.js ADDED
@@ -0,0 +1,391 @@
1
+ /**
2
+ * 火山引擎「音频生成大模型 seed-audio-1.0」HTTP 客户端。
3
+ *
4
+ * 文档:https://docs.volcengine.com/docs/DoubaoVoice/audio-generation-http
5
+ *
6
+ * ## 这个接口的四个硬事实(写错都不会报类型错,只会在真机上坏)
7
+ *
8
+ * 1. **模型名是短名 `seed-audio-1.0`**,不是方舟的 `doubao-seed-audio-1-0`。
9
+ * 语音的 `openspeech` 端点不能把方舟 id 转过来,填错会直接 4xx。
10
+ * 2. **认证只有 `X-Api-Key`**(语音控制台的 API Key),不是方舟的 `ARK_API_KEY`;
11
+ * `X-Api-Request-Id` 只是链路追踪。`/tts/create` **不发** `X-Api-Resource-Id`
12
+ * (模型在 body 的 `model` 里)。
13
+ * 3. **同步接口**:一次 POST 返回整段音频(`audio` base64;也可能只给一个 2 小时
14
+ * 有效的 `url`)。没有任务 id、没有轮询。
15
+ * 4. **响应必须按文件头校验**:`Content-Type` 不可信,CDN 可能返回一段错误页或
16
+ * 未完成的临时对象;只信它会把随机字节落成 `.mp3`。
17
+ *
18
+ * 这一层只负责「参数 → HTTP → 结构化结果」;任务目录、后台任务表、导出都在
19
+ * `sfxgen.ts` 里。两者都不碰界面。
20
+ */
21
+ import { randomUUID } from "node:crypto";
22
+ import { sniffBinary } from "./musicapi.js";
23
+ /** 当前唯一支持的生成式音频模型。 */
24
+ export const SFX_DEFAULT_MODEL = "seed-audio-1.0";
25
+ /** 国内站默认端点;BytePlus / 反代可以改。 */
26
+ export const SFX_DEFAULT_BASE_URL = "https://openspeech.bytedance.com";
27
+ export const SFX_DEFAULT_FORMAT = "wav";
28
+ export const SFX_DEFAULT_SAMPLE_RATE = 24000;
29
+ export const SFX_FORMATS = ["mp3", "wav", "ogg_opus"];
30
+ /**
31
+ * 官方支持的采样率。全部暴露给界面:游戏音效常用 44100 / 48000,
32
+ * 语音便签用 16000 / 24000 就够。
33
+ */
34
+ export const SFX_SAMPLE_RATES = [8000, 16000, 24000, 32000, 44100, 48000];
35
+ export const SFX_LIMITS = {
36
+ /** text_prompt 上限(官方文档)。 */
37
+ promptChars: 2048,
38
+ /** 单次输出上限(秒)。没有 duration 参数,时长只能写进提示词。 */
39
+ maxSeconds: 120,
40
+ /** 参考音频最多 3 条。 */
41
+ audioRefs: 3,
42
+ /** 单条参考(图 / 音频)上限 10MB。 */
43
+ refBytes: 10 * 1024 * 1024,
44
+ /** 单条参考音频时长上限(秒)。 */
45
+ refSeconds: 30,
46
+ /** 响应 / 下载音频的硬上限,防止异常响应把内存吃满。 */
47
+ responseBytes: 120 * 1024 * 1024
48
+ };
49
+ export class SfxApiError extends Error {
50
+ status;
51
+ code;
52
+ logId;
53
+ constructor(message, options = {}) {
54
+ super(message);
55
+ this.name = "SfxApiError";
56
+ this.status = options.status;
57
+ this.code = options.code;
58
+ this.logId = options.logId;
59
+ }
60
+ }
61
+ export function isSfxFormat(value) {
62
+ return typeof value === "string" && SFX_FORMATS.includes(value);
63
+ }
64
+ export function isSfxSampleRate(value) {
65
+ const n = typeof value === "number" ? value : Number(value);
66
+ return Number.isFinite(n) && SFX_SAMPLE_RATES.includes(n);
67
+ }
68
+ /** 配置层用:非法值静默回到默认(配置文件可能被手改过)。 */
69
+ export function sfxFormatOrDefault(value) {
70
+ return isSfxFormat(value) ? value : SFX_DEFAULT_FORMAT;
71
+ }
72
+ export function sfxSampleRateOrDefault(value) {
73
+ return isSfxSampleRate(value) ? Number(value) : SFX_DEFAULT_SAMPLE_RATE;
74
+ }
75
+ /**
76
+ * 统一 Base URL:去尾斜杠;用户把完整端点整段粘进来时也认。
77
+ *
78
+ * 不做「本机地址放行」之类的安全判断:这里是**提交端点**,用户填本地 mock / 反代
79
+ * 是明确意图;下载远端 `url` 时另外校验。
80
+ */
81
+ export function normalizeSfxBaseUrl(value) {
82
+ let raw = typeof value === "string" ? value.trim() : "";
83
+ if (raw === "")
84
+ return SFX_DEFAULT_BASE_URL;
85
+ raw = raw.replace(/\/+$/u, "");
86
+ raw = raw.replace(/\/api\/v3\/tts\/create$/iu, "");
87
+ raw = raw.replace(/\/api\/v3$/iu, "");
88
+ raw = raw.replace(/\/+$/u, "");
89
+ return raw === "" ? SFX_DEFAULT_BASE_URL : raw;
90
+ }
91
+ export function sfxEndpoint(baseUrl) {
92
+ return `${normalizeSfxBaseUrl(baseUrl)}/api/v3/tts/create`;
93
+ }
94
+ /**
95
+ * 配置是否足以提交生成。
96
+ *
97
+ * 同时接受完整 Config(`sfxApiKey`)与脱敏视图(`sfxApiKeySet`),界面、工具
98
+ * intake、网关读同一份判断,避免「界面说没配好、模型说配好了」。
99
+ */
100
+ export function sfxBlocker(config) {
101
+ const hasKey = config?.sfxApiKeySet === true || (typeof config?.sfxApiKey === "string" && config.sfxApiKey.trim() !== "");
102
+ if (!hasKey) {
103
+ return "还没配置火山引擎语音 API Key:设置 → 游戏素材大师 → 音效生成(火山引擎 Seed-Audio)。注意它是语音控制台的 API Key,不是火山方舟的 ARK_API_KEY。";
104
+ }
105
+ return undefined;
106
+ }
107
+ function text(value) {
108
+ return typeof value === "string" ? value.trim() : "";
109
+ }
110
+ function numberIn(value, fallback, min, max, field) {
111
+ if (value === undefined || value === null || value === "")
112
+ return fallback;
113
+ const n = typeof value === "number" ? value : Number(value);
114
+ if (!Number.isFinite(n))
115
+ throw new SfxApiError(`${field} 必须是数字`);
116
+ if (n < min || n > max)
117
+ throw new SfxApiError(`${field} 超出范围:${n}(允许 ${min}–${max})`);
118
+ return Math.round(n);
119
+ }
120
+ /**
121
+ * 任务参数归一化。`fallback` 是配置里的默认值。
122
+ *
123
+ * **越界直接报错,不静默夹**:用户以为「调了音调」,结果被悄悄夹到 12,
124
+ * 生成出来的东西和预期不一样,比报错更难查。
125
+ */
126
+ export function normalizeSfxSettings(raw, fallback = {}) {
127
+ const input = raw !== null && typeof raw === "object" ? raw : {};
128
+ const format = input.format === undefined || input.format === "" ? sfxFormatOrDefault(fallback.format) : input.format;
129
+ if (!isSfxFormat(format)) {
130
+ throw new SfxApiError(`输出格式不合法:${String(format)}(允许:${SFX_FORMATS.join(" / ")})`);
131
+ }
132
+ const sampleRate = input.sampleRate === undefined || input.sampleRate === ""
133
+ ? sfxSampleRateOrDefault(fallback.sampleRate)
134
+ : Number(input.sampleRate);
135
+ if (!isSfxSampleRate(sampleRate)) {
136
+ throw new SfxApiError(`采样率不合法:${String(input.sampleRate)}(允许:${SFX_SAMPLE_RATES.join(" / ")})`);
137
+ }
138
+ return {
139
+ format,
140
+ sampleRate,
141
+ speechRate: numberIn(input.speechRate, fallback.speechRate ?? 0, -50, 100, "语速 speech_rate"),
142
+ loudnessRate: numberIn(input.loudnessRate, fallback.loudnessRate ?? 0, -50, 100, "音量 loudness_rate"),
143
+ pitchRate: numberIn(input.pitchRate, fallback.pitchRate ?? 0, -12, 12, "音调 pitch_rate"),
144
+ watermark: input.watermark === undefined ? fallback.watermark === true : input.watermark === true
145
+ };
146
+ }
147
+ function b64(buffer) {
148
+ return buffer.toString("base64");
149
+ }
150
+ /** 把一次请求变成真实 body;所有校验都在这里,错误信息点名到字段。 */
151
+ export function buildSfxBody(request, model = SFX_DEFAULT_MODEL) {
152
+ const prompt = text(request.prompt);
153
+ if (prompt === "")
154
+ throw new SfxApiError("提示词不能为空:先写清要什么声音");
155
+ if (prompt.length > SFX_LIMITS.promptChars) {
156
+ throw new SfxApiError(`提示词太长:${prompt.length} 字符,上限 ${SFX_LIMITS.promptChars}。请精简后再提交(不会自动截断)。`);
157
+ }
158
+ const modelName = text(model) || SFX_DEFAULT_MODEL;
159
+ const settings = normalizeSfxSettings(request.settings);
160
+ const image = request.refs?.image;
161
+ const audios = request.refs?.audios ?? [];
162
+ if (image !== undefined && audios.length > 0) {
163
+ throw new SfxApiError("参考图与参考音频不能同时使用:先删掉其中一种,再提交。");
164
+ }
165
+ if (image !== undefined && image.length > SFX_LIMITS.refBytes) {
166
+ throw new SfxApiError(`参考图太大:${(image.length / 1024 / 1024).toFixed(1)}MB(上限 10MB)`);
167
+ }
168
+ if (audios.length > SFX_LIMITS.audioRefs) {
169
+ throw new SfxApiError(`参考音频最多 ${SFX_LIMITS.audioRefs} 条,当前 ${audios.length} 条`);
170
+ }
171
+ for (const [index, audio] of audios.entries()) {
172
+ if (audio.length > SFX_LIMITS.refBytes) {
173
+ throw new SfxApiError(`第 ${index + 1} 条参考音频太大:${(audio.length / 1024 / 1024).toFixed(1)}MB(上限 10MB)`);
174
+ }
175
+ }
176
+ const body = {
177
+ model: modelName,
178
+ text_prompt: prompt,
179
+ audio_config: {
180
+ format: settings.format,
181
+ sample_rate: settings.sampleRate,
182
+ speech_rate: settings.speechRate,
183
+ loudness_rate: settings.loudnessRate,
184
+ pitch_rate: settings.pitchRate
185
+ }
186
+ };
187
+ if (image !== undefined)
188
+ body.references = [{ image_data: b64(image) }];
189
+ else if (audios.length > 0)
190
+ body.references = audios.map((audio) => ({ audio_data: b64(audio) }));
191
+ if (settings.watermark)
192
+ body.watermark = { aigc_watermark: true };
193
+ return body;
194
+ }
195
+ function combinedSignal(timeoutMs, signal) {
196
+ const timeout = AbortSignal.timeout(Math.max(10000, timeoutMs));
197
+ return { signal: signal === undefined ? timeout : AbortSignal.any([signal, timeout]), timeout };
198
+ }
199
+ function errorHint(status, bodyText, code) {
200
+ if (/resource\s+not\s+granted|10074|not\s+granted/iu.test(bodyText) || String(code ?? "") === "10074") {
201
+ return "模型未开通:到火山引擎语音控制台开通「音频生成大模型 seed-audio-1.0」;API Key 不用换。";
202
+ }
203
+ if (status === 401 || status === 403) {
204
+ return "鉴权失败:确认填的是语音控制台的 API Key(X-Api-Key),不是火山方舟的 ARK_API_KEY。";
205
+ }
206
+ if (status === 429)
207
+ return "请求太频繁(429):等一会儿再试;不要连续重复提交,每次都会计费。";
208
+ if (status === 404)
209
+ return "端点不存在:确认 Base URL 是语音服务的根地址(国内默认 https://openspeech.bytedance.com)。";
210
+ return "";
211
+ }
212
+ async function readError(response, logId) {
213
+ const textBody = await response.text().catch(() => "");
214
+ let payload;
215
+ try {
216
+ payload = JSON.parse(textBody);
217
+ }
218
+ catch {
219
+ payload = undefined;
220
+ }
221
+ const body = payload?.body ?? payload;
222
+ const message = typeof body?.message === "string" ? body.message : typeof body?.error === "string" ? body.error : textBody.slice(0, 400);
223
+ const code = body?.code ?? body?.error_code ?? undefined;
224
+ const hint = errorHint(response.status, `${textBody} ${message}`, code);
225
+ const parts = [`火山引擎音频生成失败(HTTP ${response.status})`];
226
+ if (message.trim() !== "")
227
+ parts.push(message.trim());
228
+ if (code !== undefined)
229
+ parts.push(`code=${String(code)}`);
230
+ if (logId !== undefined && logId !== "")
231
+ parts.push(`logId=${logId}`);
232
+ if (hint !== "")
233
+ parts.push(hint);
234
+ return new SfxApiError(parts.join(";"), { status: response.status, code, logId });
235
+ }
236
+ async function downloadAudio(url, timeoutMs, signal) {
237
+ let parsed;
238
+ try {
239
+ parsed = new URL(url);
240
+ }
241
+ catch {
242
+ throw new SfxApiError(`返回的音频 URL 不合法:${url.slice(0, 200)}`);
243
+ }
244
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
245
+ throw new SfxApiError(`只接受 http(s) 音频 URL:${parsed.protocol}`);
246
+ }
247
+ const { signal: composed } = combinedSignal(timeoutMs, signal);
248
+ let response;
249
+ try {
250
+ response = await fetch(parsed.toString(), { signal: composed });
251
+ }
252
+ catch (error) {
253
+ if (composed.aborted)
254
+ throw new SfxApiError("下载音频超时或被取消");
255
+ throw new SfxApiError(`下载音频失败:${error instanceof Error ? error.message : String(error)}`);
256
+ }
257
+ if (!response.ok)
258
+ throw new SfxApiError(`下载音频失败(HTTP ${response.status})`, { status: response.status });
259
+ const length = Number(response.headers.get("content-length") ?? 0);
260
+ if (Number.isFinite(length) && length > SFX_LIMITS.responseBytes) {
261
+ throw new SfxApiError(`音频太大:${(length / 1024 / 1024).toFixed(1)}MB(上限 120MB)`);
262
+ }
263
+ const bytes = Buffer.from(await response.arrayBuffer());
264
+ if (bytes.length > SFX_LIMITS.responseBytes) {
265
+ throw new SfxApiError(`音频太大:${(bytes.length / 1024 / 1024).toFixed(1)}MB(上限 120MB)`);
266
+ }
267
+ return { bytes, remoteUrl: parsed.toString() };
268
+ }
269
+ function decodeBase64Audio(value) {
270
+ const raw = value.startsWith("data:") ? value.slice(value.indexOf(",") + 1) : value;
271
+ try {
272
+ return Buffer.from(raw, "base64");
273
+ }
274
+ catch {
275
+ throw new SfxApiError("返回的 audio 不是合法 base64");
276
+ }
277
+ }
278
+ /**
279
+ * 调一次生成。`signal` 用于取消;超时由 `config.timeoutMs` 控制。
280
+ *
281
+ * 成功时一定返回**能按文件头识别的音频字节**;解码失败 / 不是音频容器都会抛错,
282
+ * 不把坏字节交给调用方落盘。
283
+ */
284
+ export async function generateSfx(config, request, signal) {
285
+ const apiKey = config.apiKey.trim();
286
+ if (apiKey === "")
287
+ throw new SfxApiError(sfxBlocker({ sfxApiKey: "" }) ?? "尚未配置语音 API Key");
288
+ const endpoint = sfxEndpoint(config.baseUrl);
289
+ const body = buildSfxBody(request, config.model);
290
+ const requestId = randomUUID();
291
+ const { signal: composed, timeout } = combinedSignal(config.timeoutMs, signal);
292
+ let response;
293
+ try {
294
+ response = await fetch(endpoint, {
295
+ method: "POST",
296
+ headers: {
297
+ "Content-Type": "application/json",
298
+ "X-Api-Key": apiKey,
299
+ "X-Api-Request-Id": requestId
300
+ },
301
+ body: JSON.stringify(body),
302
+ signal: composed
303
+ });
304
+ }
305
+ catch (error) {
306
+ if (timeout.aborted) {
307
+ throw new SfxApiError(`生成超时(${Math.round(config.timeoutMs / 1000)} 秒):音频生成较慢,可以调大超时后再试;失败重试会再计费,先问用户。`);
308
+ }
309
+ if (composed.aborted)
310
+ throw new SfxApiError("生成已取消(远端可能仍会完成并计费)");
311
+ throw new SfxApiError(`请求火山引擎失败:${error instanceof Error ? error.message : String(error)}`);
312
+ }
313
+ const logId = response.headers.get("x-tt-logid") ?? undefined;
314
+ if (!response.ok)
315
+ throw await readError(response, logId);
316
+ const textBody = await response.text();
317
+ let payload;
318
+ try {
319
+ payload = textBody === "" ? {} : JSON.parse(textBody);
320
+ }
321
+ catch {
322
+ throw new SfxApiError(`火山引擎返回了无法解析的 JSON(X-Tt-Logid=${logId ?? "无"}):${textBody.slice(0, 300)}`, { logId });
323
+ }
324
+ const data = payload?.body !== null && typeof payload?.body === "object" ? payload.body : payload;
325
+ if (typeof data?.code === "number" && data.code !== 0 && !data?.audio && !data?.url) {
326
+ throw new SfxApiError(`火山引擎音频生成失败:${typeof data.message === "string" ? data.message : "未知错误"}(code=${data.code}${logId === undefined ? "" : `,logId=${logId}`})${errorHint(undefined, String(data.message ?? ""), data.code) === "" ? "" : `;${errorHint(undefined, String(data.message ?? ""), data.code)}`}`, { code: data.code, logId });
327
+ }
328
+ let bytes;
329
+ let remoteUrl;
330
+ if (typeof data?.audio === "string" && data.audio.trim() !== "") {
331
+ bytes = decodeBase64Audio(data.audio.trim());
332
+ }
333
+ else if (typeof data?.url === "string" && data.url.trim() !== "") {
334
+ const downloaded = await downloadAudio(data.url.trim(), config.timeoutMs, signal);
335
+ bytes = downloaded.bytes;
336
+ remoteUrl = downloaded.remoteUrl;
337
+ }
338
+ else {
339
+ throw new SfxApiError(`火山引擎没有返回音频(code=${String(data?.code ?? "无")},message=${String(data?.message ?? "空")}${logId === undefined ? "" : `,logId=${logId}`})`, { code: data?.code, logId });
340
+ }
341
+ if (bytes.length === 0)
342
+ throw new SfxApiError("火山引擎返回了空音频", { logId });
343
+ if (bytes.length > SFX_LIMITS.responseBytes) {
344
+ throw new SfxApiError(`返回的音频太大:${(bytes.length / 1024 / 1024).toFixed(1)}MB(上限 120MB)`, { logId });
345
+ }
346
+ const sniffed = sniffBinary(bytes);
347
+ const audioExts = new Set(["mp3", "m4a", "wav", "flac", "ogg", "aac"]);
348
+ if (sniffed === undefined || !audioExts.has(sniffed.ext)) {
349
+ throw new SfxApiError(`返回的内容不是可识别的音频容器(Content-Type=${response.headers.get("content-type") ?? "unknown"})。已丢弃,未落盘;可稍后重试。`, { logId });
350
+ }
351
+ const duration = Number(data?.duration);
352
+ const originalDuration = Number(data?.original_duration);
353
+ return {
354
+ bytes,
355
+ ext: sniffed.ext,
356
+ mime: sniffed.mime,
357
+ duration: Number.isFinite(duration) && duration > 0 ? duration : undefined,
358
+ originalDuration: Number.isFinite(originalDuration) && originalDuration > 0 ? originalDuration : undefined,
359
+ remoteUrl,
360
+ logId
361
+ };
362
+ }
363
+ /**
364
+ * 设置页「测试连接」:真实生成一条极短音效。
365
+ *
366
+ * 没有免费的探活端点;读历史 / 读模型列表都不能证明「这个 Key 能生成」。
367
+ * 所以这里真的调一次,只返回统计、不落盘。按钮文案必须写明会产生少量费用。
368
+ */
369
+ export async function testSfxConnection(config) {
370
+ const result = await generateSfx(config, {
371
+ prompt: "短促清脆的 UI 按钮点击声,约 0.5 秒",
372
+ settings: {
373
+ format: "mp3",
374
+ sampleRate: 16000,
375
+ speechRate: 0,
376
+ loudnessRate: 0,
377
+ pitchRate: 0,
378
+ watermark: false
379
+ }
380
+ });
381
+ return {
382
+ ok: true,
383
+ model: config.model || SFX_DEFAULT_MODEL,
384
+ endpoint: sfxEndpoint(config.baseUrl),
385
+ bytes: result.bytes.length,
386
+ duration: result.duration ?? null,
387
+ originalDuration: result.originalDuration ?? null,
388
+ format: result.ext,
389
+ message: `连接正常:返回 ${result.bytes.length} 字节音频${result.duration === undefined ? "" : `,${result.duration.toFixed(2)} 秒`}`
390
+ };
391
+ }