@napuketto/media 0.2.3 → 0.4.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/dist/index.mjs CHANGED
@@ -1,17 +1,17 @@
1
1
  import { randomBytes, randomUUID } from "node:crypto";
2
- import { createWriteStream, mkdirSync } from "node:fs";
3
- import { mkdir, mkdtemp, open, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
2
+ import { mkdir, mkdtemp, open, realpath, rename, rm, stat } from "node:fs/promises";
4
3
  import { basename, dirname, join, resolve } from "node:path";
4
+ import { Worker } from "node:worker_threads";
5
+ import { constants, createWriteStream } from "node:fs";
6
+ import { Readable, Transform } from "node:stream";
7
+ import { pipeline } from "node:stream/promises";
5
8
  import { execa } from "execa";
6
- import { decode, encode, getDuration, getWavFileInfo, isSilk, isWav } from "silk-wasm";
7
9
  import { BlockList, isIP } from "node:net";
8
10
  import process$1 from "node:process";
9
- import { Readable, Transform } from "node:stream";
10
- import { pipeline } from "node:stream/promises";
11
11
  import { lookup } from "node:dns/promises";
12
12
  import { get } from "node:http";
13
13
  import { get as get$1 } from "node:https";
14
- import { fileTypeFromFile } from "file-type";
14
+ import { fileTypeFromBuffer } from "file-type";
15
15
  import { imageSize } from "image-size";
16
16
  // src/types.ts
17
17
  /** 无法识别的文件类型(file-type 返回 undefined 时)。 */
@@ -48,15 +48,31 @@ function replaceExt(input, ext) {
48
48
  const WINDOWS_DRIVE = /^[a-z]:[\\/]/i;
49
49
  const NETWORK_OR_DEVICE_PATH = /^[\\/]{2}/;
50
50
  const PROTOCOL_PREFIX = /^[a-z][a-z\d+.-]*:/i;
51
+ const MAX_VIDEO_PIXELS = 8294400;
52
+ const MAX_FFMPEG_ALLOCATION = String(134217728);
51
53
  /** Input options must precede -i (also applied by ffprobe to nested inputs). */
52
54
  const LOCAL_MEDIA_INPUT_OPTIONS = [
53
55
  "-protocol_whitelist",
54
56
  "file",
55
57
  "-format_whitelist",
56
- "mov,matroska,webm,avi,flv,asf,mpeg,mpegts,ogg,wav,mp3,flac,aac,amr,aiff,ape,ac3,eac3,dts,au"
58
+ "mov,matroska,webm,avi,flv,asf,mpeg,mpegts,ogg,wav,mp3,flac,aac,amr,aiff,ape,ac3,eac3,dts,au",
59
+ "-max_streams",
60
+ "16",
61
+ "-max_pixels",
62
+ String(MAX_VIDEO_PIXELS),
63
+ "-threads",
64
+ "2"
65
+ ];
66
+ const FFPROBE_WORK_OPTIONS = ["-max_alloc", MAX_FFMPEG_ALLOCATION];
67
+ const FFMPEG_WORK_OPTIONS = [
68
+ ...FFPROBE_WORK_OPTIONS,
69
+ "-filter_threads",
70
+ "1",
71
+ "-xerror"
57
72
  ];
58
- function mediaProcessOptions(timeout) {
73
+ function mediaProcessOptions(timeout, cancelSignal) {
59
74
  return {
75
+ ...cancelSignal === void 0 ? {} : { cancelSignal },
60
76
  reject: false,
61
77
  timeout,
62
78
  killSignal: "SIGTERM",
@@ -67,62 +83,125 @@ function mediaProcessOptions(timeout) {
67
83
  maxBuffer: 1048576
68
84
  };
69
85
  }
86
+ function checkMediaSignal(signal) {
87
+ if (signal?.aborted) throw new MediaError("媒体操作已取消", { cause: signal.reason });
88
+ }
70
89
  function assertLocalPath(input) {
71
90
  const windowsDrive = process.platform === "win32" && WINDOWS_DRIVE.test(input);
72
91
  if (input.length === 0 || input.includes("\0") || NETWORK_OR_DEVICE_PATH.test(input) || PROTOCOL_PREFIX.test(input) && !windowsDrive) throw new MediaError(`媒体输入必须是本地普通文件: ${input}`);
73
92
  }
74
93
  /** Absolute paths protect option-like filenames; realpath also checks symlink targets. No root sandbox. */
75
- async function localMediaPath(input) {
94
+ async function localMediaPath(input, maxBytes = Number.MAX_SAFE_INTEGER) {
76
95
  assertLocalPath(input);
77
96
  try {
78
97
  const path = await realpath(resolve(input));
79
98
  assertLocalPath(path);
80
- if (!(await stat(path)).isFile()) throw new MediaError(`媒体输入必须是本地普通文件: ${input}`);
99
+ const info = await stat(path);
100
+ if (!info.isFile()) throw new MediaError(`媒体输入必须是本地普通文件: ${input}`);
101
+ if (info.size === 0 || info.size > maxBytes) throw new MediaError(`媒体输入为空或超出大小限制: ${input}`);
81
102
  return path;
82
103
  } catch (error) {
83
104
  if (error instanceof MediaError) throw error;
84
105
  throw new MediaError(`无法读取本地媒体: ${input}`, { cause: error });
85
106
  }
86
107
  }
87
- async function assertMediaOutput(path, maxBytes = Number.MAX_SAFE_INTEGER) {
108
+ async function assertMediaOutput(path, maxBytes) {
88
109
  const info = await stat(path);
89
110
  if (!info.isFile() || info.size === 0 || info.size > maxBytes) throw new MediaError(`媒体输出缺失、为空或超出大小限制: ${path}`);
90
111
  }
112
+ async function openMediaInput(path) {
113
+ return await open(path, constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NONBLOCK));
114
+ }
91
115
  /** Bound allocation and reads even if a caller changes the input after stat. */
92
- async function readBoundedMediaFile(path, maxBytes) {
93
- const handle = await open(path, "r");
116
+ async function readBoundedMediaFile(path, maxBytes, signal) {
117
+ return await readMediaBytes(path, maxBytes, "file", signal);
118
+ }
119
+ async function readMediaPrefix(path, maxBytes, signal) {
120
+ return await readMediaBytes(path, maxBytes, "prefix", signal);
121
+ }
122
+ async function readMediaBytes(path, maxBytes, mode, signal) {
123
+ checkMediaSignal(signal);
124
+ const handle = await openMediaInput(path);
94
125
  try {
95
126
  const info = await handle.stat();
96
- if (!info.isFile() || info.size === 0 || info.size > maxBytes) throw new MediaError(`媒体文件为空或超出大小限制: ${path}`);
97
- const buffer = Buffer.alloc(info.size + 1);
127
+ if (!info.isFile() || info.size === 0 || mode === "file" && info.size > maxBytes) throw new MediaError(`媒体文件为空或超出大小限制: ${path}`);
128
+ const buffer = Buffer.alloc(mode === "file" ? info.size + 1 : Math.min(maxBytes, info.size));
98
129
  let offset = 0;
99
- while (offset < buffer.byteLength) {
100
- const { bytesRead } = await handle.read(buffer, offset, buffer.byteLength - offset);
101
- if (bytesRead === 0) return buffer.subarray(0, offset);
130
+ while (offset < buffer.length) {
131
+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset);
132
+ checkMediaSignal(signal);
133
+ if (bytesRead === 0) break;
102
134
  offset += bytesRead;
103
135
  }
104
- throw new MediaError(`读取期间媒体文件大小发生变化: ${path}`);
136
+ if (mode === "file" && offset !== info.size) throw new MediaError(`读取期间媒体文件大小发生变化: ${path}`);
137
+ return buffer.subarray(0, offset);
105
138
  } finally {
106
139
  await handle.close();
107
140
  }
108
141
  }
142
+ /** Enforce the byte limit before writing each chunk, and join the child before allowing cleanup. */
143
+ async function writeFfmpegOutput(args, path, maxBytes, timeout, signal) {
144
+ checkMediaSignal(signal);
145
+ const stop = new AbortController();
146
+ const cancel = signal === void 0 ? stop.signal : AbortSignal.any([signal, stop.signal]);
147
+ const child = execa("ffmpeg", [...args, "pipe:1"], {
148
+ ...mediaProcessOptions(timeout, cancel),
149
+ buffer: { stdout: false }
150
+ });
151
+ let bytes = 0;
152
+ const limit = new Transform({ transform(chunk, _encoding, callback) {
153
+ bytes += chunk.length;
154
+ if (bytes > maxBytes) callback(new MediaError(`媒体输出超过 ${maxBytes} 字节限制`));
155
+ else callback(null, chunk);
156
+ } });
157
+ const writing = Promise.resolve().then(() => {
158
+ if (child.stdout == null) throw new MediaError("无法读取 FFmpeg 输出管道");
159
+ return pipeline(child.stdout, limit, createWriteStream(path, {
160
+ flags: "wx",
161
+ mode: 384
162
+ }));
163
+ }).catch((error) => {
164
+ stop.abort();
165
+ throw error;
166
+ });
167
+ const [output, processResult] = await Promise.allSettled([writing, child]);
168
+ checkMediaSignal(signal);
169
+ if (output.status === "rejected" && limit.errored instanceof MediaError) throw limit.errored;
170
+ if (processResult.status === "rejected") throw processResult.reason;
171
+ const result = processResult.value;
172
+ if (result.exitCode !== 0 || result.failed) throw new MediaError(`ffmpeg 执行失败(exit ${result.exitCode ?? "?"})`, { cause: result });
173
+ if (output.status === "rejected") throw output.reason;
174
+ await assertMediaOutput(path, maxBytes);
175
+ }
176
+ async function publishMediaFile(path, chunks, signal) {
177
+ checkMediaSignal(signal);
178
+ await mkdir(dirname(path), { recursive: true });
179
+ const partial = `${path}.part-${process.pid}-${randomUUID()}`;
180
+ const handle = await open(partial, "wx", 384);
181
+ try {
182
+ try {
183
+ for (const chunk of chunks) {
184
+ checkMediaSignal(signal);
185
+ await handle.writeFile(chunk, signal === void 0 ? void 0 : { signal });
186
+ }
187
+ } finally {
188
+ await handle.close();
189
+ }
190
+ checkMediaSignal(signal);
191
+ await rename(partial, path);
192
+ } finally {
193
+ await rm(partial, { force: true });
194
+ }
195
+ }
109
196
  // src/audio.ts
110
- /**
111
- * 音频(silk-wasm + ffmpeg)
112
- *
113
- * - `decodeSilkToPcm`:SILK → pcm_s16le 文件 + 时长
114
- * - `encodePcmToSilk`:任意音频(wav/pcm/mp3/ogg/amr/flac…)→ SILK 文件
115
- * - `getSilkInfo`:SILK 音频信息(时长 / 采样率)
116
- *
117
- * silk-wasm 的 `encode` 只接受「单声道 16-bit PCM WAV / 单声道 pcm_s16le」;立体声、非 16-bit、
118
- * 或压缩编码(mp3/ogg/amr/flac 等)一律先经 ffmpeg 归一化为 24000Hz 单声道 pcm_s16le 再编码
119
- * (QQ 语音协议 silk v3 固定 24000Hz,ffmpeg 用法同 video.ts,依赖系统 PATH 中的 ffmpeg)。
120
- */
121
197
  /** SILK 默认采样率(Hz)。 */
122
198
  const SILK_SAMPLE_RATE = 24e3;
123
199
  const MAX_AUDIO_SECONDS = 600;
124
200
  const MAX_AUDIO_INPUT_BYTES = 33554432;
125
- const MAX_NORMALIZED_PCM_BYTES = MAX_AUDIO_SECONDS * SILK_SAMPLE_RATE * 2;
201
+ const MAX_NORMALIZED_PCM_BYTES = 600 * SILK_SAMPLE_RATE * 2;
202
+ const MAX_SILK_WORK_MS = 3e4;
203
+ const SILK_FRAME_MS = 20;
204
+ const SILK_HEADER = Buffer.from("#!SILK_V3");
126
205
  const ENCODE_SAMPLE_RATES = /* @__PURE__ */ new Set([
127
206
  8e3,
128
207
  12e3,
@@ -139,174 +218,275 @@ const DECODE_SAMPLE_RATES = /* @__PURE__ */ new Set([
139
218
  24e3,
140
219
  48e3
141
220
  ]);
142
- function assertSampleRate(rate, decoding = false) {
143
- if (!(decoding ? DECODE_SAMPLE_RATES : ENCODE_SAMPLE_RATES).has(rate)) throw new MediaError(`不支持的音频采样率: ${rate}`);
221
+ function assertSampleRate(rate, allowed) {
222
+ if (!allowed.has(rate)) throw new MediaError(`不支持的音频采样率: ${rate}`);
223
+ }
224
+ function assertAudioDuration(durationMs) {
225
+ if (!Number.isFinite(durationMs) || durationMs <= 0 || durationMs > 6e5) throw new MediaError(`音频时长必须大于 0 且不超过 600s`);
226
+ }
227
+ function silkHeaderLength(bytes) {
228
+ const prefix = bytes[0] === 2 ? 1 : 0;
229
+ return bytes.subarray(prefix, prefix + SILK_HEADER.length).equals(SILK_HEADER) ? prefix + SILK_HEADER.length : 0;
144
230
  }
145
- function assertAudioDuration(seconds) {
146
- if (!Number.isFinite(seconds) || seconds <= 0 || seconds > MAX_AUDIO_SECONDS) throw new MediaError(`音频时长必须大于 0 且不超过 ${MAX_AUDIO_SECONDS}s`);
231
+ /** SILK 包按长度跳过,不为元数据读取累计输入,也不接受截断的包。 */
232
+ async function silkDuration(chunks, headerLength, signal) {
233
+ const scan = {
234
+ remaining: headerLength,
235
+ duration: 0,
236
+ ended: false,
237
+ lengthLow: void 0
238
+ };
239
+ let bytes = 0;
240
+ for await (const chunk of chunks) {
241
+ checkMediaSignal(signal);
242
+ bytes += chunk.length;
243
+ if (bytes > 33554432) throw new MediaError("SILK 文件超出大小限制");
244
+ consumeSilkChunk(scan, chunk);
245
+ }
246
+ if (scan.remaining !== 0 || scan.lengthLow !== void 0) throw new MediaError("SILK 帧不完整");
247
+ assertAudioDuration(scan.duration);
248
+ return scan.duration;
147
249
  }
148
- async function readAudioInput(input) {
149
- return readBoundedMediaFile(await localMediaPath(input), MAX_AUDIO_INPUT_BYTES);
250
+ function consumeSilkChunk(scan, chunk) {
251
+ let offset = 0;
252
+ while (offset < chunk.length) {
253
+ if (scan.ended) throw new MediaError("SILK 结束标记后仍有数据");
254
+ const skipped = Math.min(scan.remaining, chunk.length - offset);
255
+ scan.remaining -= skipped;
256
+ offset += skipped;
257
+ if (offset === chunk.length) break;
258
+ const value = chunk.readUInt8(offset++);
259
+ if (scan.lengthLow === void 0) {
260
+ scan.lengthLow = value;
261
+ continue;
262
+ }
263
+ scan.remaining = scan.lengthLow + value * 256;
264
+ scan.lengthLow = void 0;
265
+ if (scan.remaining === 65535) {
266
+ scan.remaining = 0;
267
+ scan.ended = true;
268
+ continue;
269
+ }
270
+ if (scan.remaining > 32767) throw new MediaError("SILK 帧长度无效");
271
+ scan.duration += SILK_FRAME_MS;
272
+ assertAudioDuration(scan.duration);
273
+ }
150
274
  }
151
- function assertSilkDuration(buffer) {
275
+ /** silk-wasm 的 Promise 内部运行同步 WASM;取消时等待执行它的 Worker 退出。 */
276
+ async function runSilk(mode, data, sampleRate, signal) {
277
+ checkMediaSignal(signal);
278
+ const source = import.meta.url.endsWith(".ts");
152
279
  try {
153
- assertAudioDuration(getDuration(buffer) / 1e3);
280
+ const worker = new Worker(new URL(source ? "./silk-worker.mts" : "./silk-worker.mjs", import.meta.url), {
281
+ execArgv: source ? ["--experimental-strip-types"] : [],
282
+ workerData: {
283
+ mode,
284
+ data,
285
+ sampleRate
286
+ },
287
+ transferList: data.buffer instanceof ArrayBuffer ? [data.buffer] : []
288
+ });
289
+ return await new Promise((done, reject) => {
290
+ let result;
291
+ let failure;
292
+ const stop = (error) => {
293
+ failure = error;
294
+ worker.terminate().catch(reject);
295
+ };
296
+ const abort = () => stop(new MediaError("媒体操作已取消", { cause: signal?.reason }));
297
+ const timer = setTimeout(() => stop(new MediaError("SILK 编解码超时")), MAX_SILK_WORK_MS);
298
+ signal?.addEventListener("abort", abort, { once: true });
299
+ worker.once("message", (message) => {
300
+ result = message;
301
+ });
302
+ worker.once("error", (error) => {
303
+ failure ??= error;
304
+ });
305
+ worker.once("exit", (code) => {
306
+ clearTimeout(timer);
307
+ signal?.removeEventListener("abort", abort);
308
+ if (failure !== void 0) reject(failure);
309
+ else if (code !== 0 || result === void 0) reject(new MediaError(`SILK Worker 退出: ${code}`));
310
+ else done(result);
311
+ });
312
+ if (signal?.aborted) abort();
313
+ });
154
314
  } catch (error) {
155
- throw new MediaError("SILK 时长无效或超出限制", { cause: error });
315
+ if (error instanceof MediaError) throw error;
316
+ throw new MediaError("SILK 编解码失败", { cause: error });
156
317
  }
157
318
  }
158
- function assertDecodedAudio(data, durationMs, sampleRate) {
159
- assertAudioDuration(durationMs / 1e3);
160
- if (data.byteLength === 0 || data.byteLength > MAX_AUDIO_SECONDS * sampleRate * 2) throw new MediaError("解码 PCM 超出大小限制或为空");
319
+ async function decodeAudio(input, sampleRate, signal) {
320
+ assertSampleRate(sampleRate, DECODE_SAMPLE_RATES);
321
+ checkMediaSignal(signal);
322
+ const buffer = await readBoundedMediaFile(await localMediaPath(input, MAX_AUDIO_INPUT_BYTES), MAX_AUDIO_INPUT_BYTES, signal);
323
+ const header = silkHeaderLength(buffer);
324
+ if (header === 0) throw new MediaError(`不是有效的 SILK 文件: ${input}`);
325
+ await silkDuration([buffer], header, signal);
326
+ const result = await runSilk("decode", buffer, sampleRate, signal);
327
+ assertAudioDuration(result.duration);
328
+ if (result.data.byteLength === 0 || result.data.byteLength > 600 * sampleRate * 2) throw new MediaError("解码 PCM 超出大小限制或为空");
329
+ return result;
161
330
  }
162
331
  /** 解码 SILK 音频为 PCM(pcm_s16le)。 */
163
- async function decodeSilkToPcm(input, sampleRate = SILK_SAMPLE_RATE) {
164
- assertSampleRate(sampleRate, true);
165
- const buffer = await readAudioInput(input);
166
- if (!isSilk(buffer)) throw new MediaError(`不是有效的 SILK 文件: ${input}`);
167
- assertSilkDuration(buffer);
168
- const result = await decode(buffer, sampleRate);
169
- assertDecodedAudio(result.data, result.duration, sampleRate);
332
+ async function decodeSilkToPcm(input, sampleRate = SILK_SAMPLE_RATE, { signal } = {}) {
333
+ const result = await decodeAudio(input, sampleRate, signal);
170
334
  const pcmPath = replaceExt(input, ".pcm");
171
- mkdirSync(dirname(pcmPath), { recursive: true });
172
- await writeFile(pcmPath, result.data);
335
+ await publishAudio(input, pcmPath, [result.data], signal);
173
336
  return {
174
337
  pcmPath,
175
338
  durationMs: result.duration
176
339
  };
177
340
  }
178
- /**
179
- * 解码 SILK → WAV 文件(pcm_s16le 单声道 + 44 字节头,通用可播放格式)。
180
- * 收方向语音接线用(koishi h.audio / 外部客户端):QQ 语音是 silk v3,
181
- * 多数播放器无法直接解码,落 WAV 后以本地路径消费。
182
- */
183
- async function decodeSilkToWav(input, options = {}) {
184
- const sampleRate = options.sampleRate ?? 24e3;
185
- assertSampleRate(sampleRate, true);
186
- const buffer = await readAudioInput(input);
187
- if (!isSilk(buffer)) throw new MediaError(`不是有效的 SILK 文件: ${input}`);
188
- assertSilkDuration(buffer);
189
- const result = await decode(buffer, sampleRate);
190
- assertDecodedAudio(result.data, result.duration, sampleRate);
191
- const { dir, name } = outputTarget(input, ".wav", options.outDir);
192
- const wav = wrapPcmInWav(result.data, sampleRate);
193
- await writeFile(join(dir, name), wav);
341
+ /** 解码 SILK 为可播放 WAV,返回的文件由调用方管理。 */
342
+ async function decodeSilkToWav(input, { sampleRate = SILK_SAMPLE_RATE, outDir, signal } = {}) {
343
+ const result = await decodeAudio(input, sampleRate, signal);
344
+ const wavPath = join(outDir ?? dirname(input), replaceExt(basename(input), ".wav"));
345
+ await publishAudio(input, wavPath, [wavHeader(result.data.byteLength, sampleRate), result.data], signal);
194
346
  return {
195
- wavPath: join(dir, name),
347
+ wavPath,
196
348
  durationMs: result.duration
197
349
  };
198
350
  }
199
- /** 输出目标(目录 + 文件名;outDir 优先,否则输入同目录替换扩展名)。 */
200
- function outputTarget(input, ext, outDir) {
201
- const base = input.replaceAll("\\", "/").split("/").pop() ?? "audio";
202
- const dot = base.lastIndexOf(".");
203
- const name = `${dot > 0 ? base.slice(0, dot) : base}${ext}`;
204
- const dir = outDir !== void 0 ? outDir : dirname(input);
205
- mkdirSync(dir, { recursive: true });
206
- return {
207
- dir,
208
- name
209
- };
210
- }
211
- /** PCM(s16le 单声道)→ WAV 文件字节(44 字节头 + 数据)。 */
212
- function wrapPcmInWav(pcm, sampleRate) {
213
- const blockAlign = 2;
351
+ function wavHeader(bytes, sampleRate) {
214
352
  const header = Buffer.alloc(44);
215
353
  header.write("RIFF", 0, "ascii");
216
- header.writeUInt32LE(36 + pcm.byteLength, 4);
217
- header.write("WAVE", 8, "ascii");
218
- header.write("fmt ", 12, "ascii");
354
+ header.writeUInt32LE(36 + bytes, 4);
355
+ header.write("WAVEfmt ", 8, "ascii");
219
356
  header.writeUInt32LE(16, 16);
220
357
  header.writeUInt16LE(1, 20);
221
358
  header.writeUInt16LE(1, 22);
222
359
  header.writeUInt32LE(sampleRate, 24);
223
- header.writeUInt32LE(sampleRate * blockAlign | 0, 28);
224
- header.writeUInt16LE(blockAlign, 32);
360
+ header.writeUInt32LE(sampleRate * 2, 28);
361
+ header.writeUInt16LE(2, 32);
225
362
  header.writeUInt16LE(16, 34);
226
363
  header.write("data", 36, "ascii");
227
- header.writeUInt32LE(pcm.byteLength, 40);
228
- return Buffer.concat([header, Buffer.from(pcm)]);
364
+ header.writeUInt32LE(bytes, 40);
365
+ return header;
229
366
  }
230
- /**
231
- * 编码任意音频为 SILK 文件(返回输出路径,输出紧随输入文件)。
232
- *
233
- * - 已是 SILK → 原样返回
234
- * - 单声道 16-bit PCM WAV / 显式采样率的原始 pcm_s16le → silk-wasm 直接编码
235
- * - 其余(立体声/浮点/非 16-bit WAV、mp3/ogg/amr/flac 等)→ ffmpeg 归一化为
236
- * 24000Hz 单声道 pcm_s16le → silk-wasm 编码
237
- */
238
- async function encodePcmToSilk(input, sampleRate = 0) {
239
- const buffer = await readAudioInput(input);
240
- if (isSilk(buffer)) {
241
- assertSilkDuration(buffer);
367
+ async function publishAudio(input, output, chunks, signal) {
368
+ const source = resolve(input);
369
+ const target = resolve(output);
370
+ if (source === target || process.platform === "win32" && source.toLowerCase() === target.toLowerCase()) throw new MediaError("音频输出不能覆盖输入文件");
371
+ try {
372
+ await publishMediaFile(output, chunks, signal);
373
+ } catch (error) {
374
+ checkMediaSignal(signal);
375
+ throw new MediaError("无法写出音频产物", { cause: error });
376
+ }
377
+ }
378
+ function isRiffWave(header) {
379
+ return header.toString("latin1", 0, 4) === "RIFF" && header.toString("latin1", 8, 12) === "WAVE";
380
+ }
381
+ function readMonoWavRate(header, offset, bytes) {
382
+ if (bytes < 16 || offset + 16 > header.length || header.readUInt16LE(offset) !== 1 || header.readUInt16LE(offset + 2) !== 1 || header.readUInt16LE(offset + 12) !== 2 || header.readUInt16LE(offset + 14) !== 16) return;
383
+ return header.readUInt32LE(offset + 4);
384
+ }
385
+ /** Locate common PCM WAV chunks without walking the audio payload. Other WAVs use ffmpeg. */
386
+ function monoWavPcm(header, fileSize) {
387
+ if (!isRiffWave(header) || header.readUInt32LE(4) + 8 !== fileSize) return void 0;
388
+ let sampleRate;
389
+ for (let offset = 12; offset + 8 <= header.length;) {
390
+ const name = header.toString("latin1", offset, offset + 4);
391
+ const bytes = header.readUInt32LE(offset + 4);
392
+ const data = offset + 8;
393
+ if (data + bytes > fileSize) return void 0;
394
+ if (name === "fmt ") {
395
+ sampleRate = readMonoWavRate(header, data, bytes);
396
+ if (sampleRate === void 0) return void 0;
397
+ }
398
+ if (name === "data" && sampleRate !== void 0 && bytes % 2 === 0) return {
399
+ offset: data,
400
+ bytes,
401
+ sampleRate
402
+ };
403
+ offset = data + bytes + bytes % 2;
404
+ }
405
+ }
406
+ /** 编码音频为 SILK;已通过边界检查的 SILK 原样返回。 */
407
+ async function encodePcmToSilk(input, sampleRate = 0, { signal } = {}) {
408
+ checkMediaSignal(signal);
409
+ const source = await localMediaPath(input, MAX_AUDIO_INPUT_BYTES);
410
+ const prefix = await readMediaPrefix(source, 12, signal);
411
+ if (silkHeaderLength(prefix) !== 0) {
412
+ await getSilkInfo(source, SILK_SAMPLE_RATE, { signal });
242
413
  return input;
243
414
  }
244
- let result;
245
- if (isWav(buffer)) {
246
- const info = getWavFileInfo(buffer);
247
- if (info.fmt.numberOfChannels === 1 && info.fmt.formatCode === 1 && info.fmt.bitsPerSample === 16) {
248
- assertSampleRate(info.fmt.sampleRate);
249
- assertAudioDuration((info.chunkInfo.find((chunk) => chunk.chunkId === "data")?.dataLength ?? 0) / (info.fmt.sampleRate * 2));
250
- result = await encode(buffer, 0);
251
- } else result = await encode(await normalizeToPcm(input), SILK_SAMPLE_RATE);
252
- } else if (sampleRate > 0) {
253
- assertSampleRate(sampleRate);
254
- assertAudioDuration(buffer.byteLength / (sampleRate * 2));
255
- result = await encode(buffer, sampleRate);
256
- } else result = await encode(await normalizeToPcm(input), SILK_SAMPLE_RATE);
415
+ const wav = isRiffWave(prefix);
416
+ const pcm = wav ? monoWavPcm(await readMediaPrefix(source, 524288, signal), (await stat(source)).size) : void 0;
417
+ const directRate = pcm?.sampleRate ?? (wav ? 0 : sampleRate);
418
+ const result = await runSilk("encode", pcm !== void 0 || directRate !== 0 ? await readPcm(source, directRate, pcm, signal) : await normalizeToPcm(source, signal), directRate || 24e3, signal);
419
+ assertAudioDuration(result.duration);
420
+ if (result.data.byteLength > 33554432 || result.data.byteLength === 0) throw new MediaError("SILK 输出超出大小限制或为空");
257
421
  const silkPath = replaceExt(input, ".silk");
258
- mkdirSync(dirname(silkPath), { recursive: true });
259
- await writeFile(silkPath, result.data);
422
+ await publishAudio(input, silkPath, [result.data], signal);
260
423
  return silkPath;
261
424
  }
262
- /**
263
- * ffmpeg 归一化:任意音频 → 24000Hz 单声道 pcm_s16le(写临时文件,返回 PCM 数据)。
264
- *
265
- * 输入目录与 .silk 输出同目录(保证可写),临时文件编码后删除。
266
- */
267
- async function normalizeToPcm(input) {
268
- const source = await localMediaPath(input);
269
- const tmpPath = join(dirname(source), `.napuketto-${randomBytes(8).toString("hex")}.pcm`);
425
+ async function readPcm(source, sampleRate, wav, signal) {
426
+ assertSampleRate(sampleRate, ENCODE_SAMPLE_RATES);
427
+ const file = await readBoundedMediaFile(source, MAX_AUDIO_INPUT_BYTES, signal);
428
+ const data = wav === void 0 ? file : file.subarray(wav.offset, wav.offset + wav.bytes);
429
+ if (data.byteLength % 2 !== 0 || wav !== void 0 && wav.bytes !== data.byteLength) throw new MediaError("PCM 输入帧不完整");
430
+ assertAudioDuration(data.byteLength * 500 / sampleRate);
431
+ return data;
432
+ }
433
+ async function normalizeToPcm(source, signal) {
434
+ const partial = join(dirname(source), `.napuketto-${randomBytes(8).toString("hex")}.pcm`);
270
435
  try {
271
- const result = await execa("ffmpeg", [
436
+ await writeFfmpegOutput([
272
437
  "-nostdin",
273
438
  "-v",
274
439
  "error",
275
- "-y",
440
+ ...FFMPEG_WORK_OPTIONS,
276
441
  ...LOCAL_MEDIA_INPUT_OPTIONS,
277
442
  "-i",
278
443
  source,
279
- "-vn",
444
+ "-map",
445
+ "0:a:0",
280
446
  "-ac",
281
447
  "1",
282
448
  "-ar",
283
449
  String(SILK_SAMPLE_RATE),
284
450
  "-t",
285
451
  String(600.02),
286
- "-fs",
287
- String(28800002),
288
452
  "-f",
289
- "s16le",
290
- tmpPath
291
- ], mediaProcessOptions(12e4));
292
- if (result.exitCode !== 0 || result.failed) throw new MediaError(`ffmpeg 音频归一化失败: ${input}(exit ${result.exitCode ?? "spawn failed"})`, { cause: result });
293
- await assertMediaOutput(tmpPath, MAX_NORMALIZED_PCM_BYTES);
294
- return new Uint8Array(await readBoundedMediaFile(tmpPath, MAX_NORMALIZED_PCM_BYTES));
453
+ "s16le"
454
+ ], partial, MAX_NORMALIZED_PCM_BYTES, 12e4, signal);
455
+ return await readBoundedMediaFile(partial, MAX_NORMALIZED_PCM_BYTES, signal);
295
456
  } catch (error) {
296
- if (error instanceof MediaError) throw error;
297
- throw new MediaError(`ffmpeg 音频归一化失败: ${input}`, { cause: error });
457
+ checkMediaSignal(signal);
458
+ throw new MediaError(`ffmpeg 音频归一化失败: ${source}`, { cause: error });
298
459
  } finally {
299
- await rm(tmpPath, { force: true });
460
+ await rm(partial, { force: true });
300
461
  }
301
462
  }
302
- /** 获取 SILK 音频信息(时长 / 采样率)。 */
303
- async function getSilkInfo(input, sampleRate = SILK_SAMPLE_RATE) {
304
- const buffer = await readFile(input);
305
- if (!isSilk(buffer)) throw new MediaError(`不是有效的 SILK 文件: ${input}`);
306
- return {
307
- durationMs: getDuration(buffer),
308
- sampleRate
309
- };
463
+ /** 获取 SILK 音频时长。SILK 容器不携带采样率,返回调用方指定值。 */
464
+ async function getSilkInfo(input, sampleRate = SILK_SAMPLE_RATE, { signal } = {}) {
465
+ assertSampleRate(sampleRate, DECODE_SAMPLE_RATES);
466
+ checkMediaSignal(signal);
467
+ const handle = await openMediaInput(await localMediaPath(input, MAX_AUDIO_INPUT_BYTES));
468
+ try {
469
+ const info = await handle.stat();
470
+ if (!info.isFile() || info.size === 0 || info.size > 33554432) throw new MediaError("无效的 SILK 文件或输入超出大小限制");
471
+ const prefix = Buffer.alloc(10);
472
+ const { bytesRead } = await handle.read(prefix, 0, prefix.length, 0);
473
+ const header = silkHeaderLength(prefix.subarray(0, bytesRead));
474
+ if (header === 0) throw new MediaError(`不是有效的 SILK 文件: ${input}`);
475
+ return {
476
+ durationMs: await silkDuration(handle.createReadStream({
477
+ start: 0,
478
+ autoClose: false,
479
+ signal
480
+ }), header, signal),
481
+ sampleRate
482
+ };
483
+ } catch (error) {
484
+ checkMediaSignal(signal);
485
+ if (error instanceof MediaError) throw error;
486
+ throw new MediaError("无法读取 SILK 信息", { cause: error });
487
+ } finally {
488
+ await handle.close();
489
+ }
310
490
  }
311
491
  // src/public-download.ts
312
492
  const ADDRESS_BRACKETS = /^\[|\]$/g;
@@ -358,7 +538,7 @@ function publicLookup(checkLiteral, signal) {
358
538
  };
359
539
  }
360
540
  function createPublicRequest(checkLiteral) {
361
- return async (url, signal) => {
541
+ return async (url, signal, headers) => {
362
542
  if (url.username !== "" || url.password !== "") throw new MediaError("公网下载策略拒绝 URL 凭据");
363
543
  const host = url.hostname.replace(ADDRESS_BRACKETS, "");
364
544
  if (isIP(host) !== 0) assertPublicAddress(host);
@@ -368,22 +548,25 @@ function createPublicRequest(checkLiteral) {
368
548
  rejectUnauthorized: true,
369
549
  signal,
370
550
  autoSelectFamily: true,
371
- headers: { "accept-encoding": "identity" },
551
+ headers: {
552
+ ...headers,
553
+ "accept-encoding": "identity"
554
+ },
372
555
  lookup: publicLookup(checkLiteral, signal)
373
556
  };
374
557
  return new Promise((resolve, reject) => {
375
558
  get$2(url, options, (response) => {
376
559
  const status = response.statusCode ?? 0;
377
560
  const encoding = response.headers["content-encoding"];
378
- if (status >= 200 && status < 300 && encoding && encoding !== "identity") {
561
+ if (status >= 200 && status < 300 && encoding && encoding.toLowerCase() !== "identity") {
379
562
  response.destroy();
380
563
  reject(new MediaError("公网下载响应使用了不支持的内容编码"));
381
564
  return;
382
565
  }
383
566
  resolve({
384
567
  status,
385
- headers: { get: (name) => response.headers[name]?.toString() ?? null },
386
- body: Readable.toWeb(response)
568
+ headers: { get: (name) => response.headers[name.toLowerCase()]?.toString() ?? null },
569
+ body: response
387
570
  });
388
571
  }).once("error", reject);
389
572
  });
@@ -425,6 +608,50 @@ const REDIRECT_STATUS = /* @__PURE__ */ new Set([
425
608
  const ALLOWED_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
426
609
  /** 扩展名字符合法性(URL pathname 提取校验)。 */
427
610
  const EXT_RE = /^\.[a-z0-9]+$/i;
611
+ const MEDIA_EXTENSIONS = /* @__PURE__ */ new Map([
612
+ ["image/avif", ".avif"],
613
+ ["image/bmp", ".bmp"],
614
+ ["image/gif", ".gif"],
615
+ ["image/heic", ".heic"],
616
+ ["image/heif", ".heif"],
617
+ ["image/jpeg", ".jpeg"],
618
+ ["image/png", ".png"],
619
+ ["image/svg+xml", ".svg"],
620
+ ["image/tiff", ".tiff"],
621
+ ["image/vnd.microsoft.icon", ".ico"],
622
+ ["image/webp", ".webp"],
623
+ ["image/x-icon", ".ico"],
624
+ ["audio/aac", ".aac"],
625
+ ["audio/amr", ".amr"],
626
+ ["audio/flac", ".flac"],
627
+ ["audio/mp4", ".m4a"],
628
+ ["audio/mpeg", ".mpeg"],
629
+ ["audio/ogg", ".ogg"],
630
+ ["audio/opus", ".opus"],
631
+ ["audio/silk", ".silk"],
632
+ ["audio/wav", ".wav"],
633
+ ["audio/webm", ".webm"],
634
+ ["audio/x-wav", ".wav"],
635
+ ["video/mpeg", ".mpeg"],
636
+ ["video/mp4", ".mp4"],
637
+ ["video/ogg", ".ogv"],
638
+ ["video/quicktime", ".mov"],
639
+ ["video/webm", ".webm"],
640
+ ["video/x-matroska", ".mkv"]
641
+ ]);
642
+ const MANAGED_REQUEST_HEADERS = /* @__PURE__ */ new Set([
643
+ "accept-encoding",
644
+ "connection",
645
+ "content-length",
646
+ "expect",
647
+ "forwarded",
648
+ "host",
649
+ "keep-alive",
650
+ "te",
651
+ "trailer",
652
+ "transfer-encoding",
653
+ "upgrade"
654
+ ]);
428
655
  /** WHATWG URL 归一化后的 IPv4-mapped IPv6(::ffff:h:h,低 32 位为 IPv4)。 */
429
656
  const IPV4_MAPPED_RE = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/;
430
657
  /**
@@ -493,20 +720,37 @@ function assertDownloadUrlSafe(raw) {
493
720
  function isRedirect(status) {
494
721
  return REDIRECT_STATUS.has(status);
495
722
  }
723
+ function initialRequestHeaders(input) {
724
+ if (input === void 0) return void 0;
725
+ const headers = new Headers();
726
+ for (const [name, value] of Object.entries(input)) {
727
+ const key = name.toLowerCase();
728
+ if (!MANAGED_REQUEST_HEADERS.has(key) && !key.startsWith("proxy-") && !key.startsWith("sec-") && !key.startsWith("x-forwarded-")) headers.append(key, value);
729
+ }
730
+ return Object.fromEntries(headers);
731
+ }
732
+ async function closeBody(body) {
733
+ if (body instanceof Readable) body.destroy();
734
+ else await body?.cancel().catch(() => void 0);
735
+ }
496
736
  /**
497
737
  * 发起请求并手动跟随重定向:每一跳都先过 assertDownloadUrlSafe。
498
738
  * 返回非 30x 的最终响应。
499
739
  */
500
- async function requestFollowingRedirects(url, request, signal) {
501
- let current = url;
740
+ async function requestFollowingRedirects(url, request, signal, callerHeaders) {
741
+ let current = assertDownloadUrlSafe(url);
742
+ let headers = initialRequestHeaders(callerHeaders);
502
743
  for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
503
- const parsed = assertDownloadUrlSafe(current);
504
- const response = await request(parsed, signal);
744
+ signal.throwIfAborted();
745
+ const response = await request(current, signal, headers);
505
746
  if (!isRedirect(response.status)) return response;
506
- const location = response.headers.get("location");
507
- await response.body?.cancel().catch(() => void 0);
747
+ await closeBody(response.body);
748
+ if (hop === MAX_REDIRECTS) break;
749
+ const location = response.headers.get("Location");
508
750
  if (location === null || location === "") throw new MediaError(`重定向缺少 Location(HTTP ${response.status})`);
509
- current = new URL(location, parsed).href;
751
+ const next = assertDownloadUrlSafe(new URL(location, current).href);
752
+ if (next.origin !== current.origin) headers = void 0;
753
+ current = next;
510
754
  }
511
755
  throw new MediaError(`重定向次数超过上限(${MAX_REDIRECTS})`);
512
756
  }
@@ -521,13 +765,14 @@ async function writeCapped(body, temp, maxBytes, signal) {
521
765
  }
522
766
  callback(null, chunk);
523
767
  } });
524
- await pipeline(Readable.fromWeb(body), counter, createWriteStream(temp, { flags: "wx" }), { signal });
768
+ const source = body instanceof Readable ? body : Readable.fromWeb(body);
769
+ await pipeline(source, counter, createWriteStream(temp, { flags: "wx" }), { signal });
525
770
  return total;
526
771
  }
527
772
  /** 下载失败的统一错误类型(保留超时语义,其余包成 MediaError)。 */
528
- function toMediaError(err, timeoutMs) {
773
+ function toMediaError(err, timeoutMs, aborted) {
529
774
  if (err instanceof MediaError) return err;
530
- if (err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError")) return new MediaError(`下载超时(${timeoutMs}ms)`, { cause: err });
775
+ if (aborted || err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError")) return new MediaError(`下载超时(${timeoutMs}ms)`, { cause: err });
531
776
  return new MediaError(err instanceof Error ? err.message : "下载失败", { cause: err });
532
777
  }
533
778
  /**
@@ -536,8 +781,8 @@ function toMediaError(err, timeoutMs) {
536
781
  * 失败不留半成品(临时文件已清理)。
537
782
  */
538
783
  async function downloadUrl(url, dest, options = {}) {
539
- return download(url, dest, options, (target, signal) => fetch(target.href, {
540
- ...options.headers === void 0 ? {} : { headers: options.headers },
784
+ return download(url, dest, options, (target, signal, headers) => fetch(target.href, {
785
+ ...headers === void 0 ? {} : { headers },
541
786
  redirect: "manual",
542
787
  signal
543
788
  }));
@@ -555,10 +800,10 @@ async function download(url, dest, options, request) {
555
800
  const temp = `${dest}.part-${process$1.pid}-${randomUUID()}`;
556
801
  let body = null;
557
802
  try {
558
- const response = await requestFollowingRedirects(url, request, controller.signal);
803
+ const response = await requestFollowingRedirects(url, request, controller.signal, options.headers);
559
804
  body = response.body;
560
805
  if (response.status < 200 || response.status >= 300) throw new MediaError(`HTTP ${response.status}`);
561
- const declared = Number(response.headers.get("content-length") ?? "0");
806
+ const declared = Number(response.headers.get("Content-Length") ?? "0");
562
807
  if (declared > maxBytes) throw new MediaError(`文件超过大小上限(${declared} > ${maxBytes} 字节)`);
563
808
  if (body === null) throw new MediaError("响应无 body");
564
809
  await mkdir(dirname(dest), { recursive: true });
@@ -567,26 +812,28 @@ async function download(url, dest, options, request) {
567
812
  await rename(temp, dest);
568
813
  return written;
569
814
  } catch (err) {
815
+ const error = toMediaError(err, timeoutMs, controller.signal.aborted);
570
816
  await rm(temp, { force: true }).catch(() => void 0);
571
- throw toMediaError(err, timeoutMs);
817
+ throw error;
572
818
  } finally {
573
819
  clearTimeout(timer);
574
- await body?.cancel().catch(() => void 0);
820
+ await closeBody(body);
575
821
  }
576
822
  }
577
823
  /** 从 Content-Type / URL 路径推断扩展名(缺省 .bin;下载命名用)。 */
578
824
  function inferExtension(contentType, url) {
579
825
  if (contentType !== null) {
580
826
  const base = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
581
- const sub = base.split("/")[1]?.split("+")[0];
582
- if (base.startsWith("image/") || base.startsWith("audio/") || base.startsWith("video/")) {
583
- if (sub !== void 0 && sub !== "") return `.${sub}`;
584
- }
827
+ const ext = MEDIA_EXTENSIONS.get(base);
828
+ if (ext !== void 0) return ext;
585
829
  }
586
830
  try {
587
831
  const pathname = new URL(url).pathname;
588
- const ext = pathname.substring(pathname.lastIndexOf("."));
589
- if (ext.length > 1 && ext.length <= 6 && EXT_RE.test(ext)) return ext.toLowerCase();
832
+ const dot = pathname.lastIndexOf(".");
833
+ if (dot > pathname.lastIndexOf("/")) {
834
+ const ext = pathname.slice(dot);
835
+ if (ext.length <= 6 && EXT_RE.test(ext)) return ext.toLowerCase();
836
+ }
590
837
  } catch {}
591
838
  return ".bin";
592
839
  }
@@ -597,180 +844,268 @@ function inferExtension(contentType, url) {
597
844
  * - `getImageSize`:image-size(读取 Uint8Array,同步计算)
598
845
  * - `detectFileType`:file-type(按文件路径检测魔数)
599
846
  */
600
- /** 读取图片尺寸(image-size 同步 API,内部读文件 + 计算)。 */
601
- async function getImageSize(input) {
602
- const buffer = await readFile(input);
603
- const size = imageSize(buffer);
604
- return {
605
- width: size.width,
606
- height: size.height
607
- };
847
+ /** 只读取有限的图片头部,尺寸元数据须在前 512 KiB 内。 */
848
+ async function getImageSize(input, { signal } = {}) {
849
+ checkMediaSignal(signal);
850
+ try {
851
+ const buffer = await readMediaPrefix(await localMediaPath(input), 524288, signal);
852
+ const { width, height } = imageSize(buffer);
853
+ if (!Number.isSafeInteger(width) || width <= 0 || !Number.isSafeInteger(height) || height <= 0) throw new MediaError("图片尺寸无效");
854
+ return {
855
+ width,
856
+ height
857
+ };
858
+ } catch (error) {
859
+ checkMediaSignal(signal);
860
+ throw new MediaError(`无法读取图片尺寸: ${input}`, { cause: error });
861
+ }
608
862
  }
609
863
  /** 检测文件类型(魔数识别,返回 undefined 时抛 MediaError)。 */
610
- async function detectFileType(input) {
611
- const result = await fileTypeFromFile(input);
612
- if (result === void 0) throw new MediaError(`无法识别的文件类型: ${input}`);
613
- return {
614
- ext: result.ext,
615
- mime: result.mime
616
- };
864
+ async function detectFileType(input, { signal } = {}) {
865
+ checkMediaSignal(signal);
866
+ try {
867
+ const bytes = await readMediaPrefix(await localMediaPath(input), 1048576, signal);
868
+ const result = await fileTypeFromBuffer(bytes, signal === void 0 ? void 0 : { signal });
869
+ checkMediaSignal(signal);
870
+ if (result !== void 0) return {
871
+ ext: result.ext,
872
+ mime: result.mime
873
+ };
874
+ } catch (error) {
875
+ checkMediaSignal(signal);
876
+ throw new MediaError(`无法识别的文件类型: ${input}`, { cause: error });
877
+ }
878
+ throw new MediaError(`无法识别的文件类型: ${input}`);
617
879
  }
618
880
  // src/video.ts
619
- /**
620
- * 视频(execa 调用外部 ffmpeg 二进制)
621
- *
622
- * ffmpeg 由 execa 以子进程方式调用(非 node 内置),依赖系统 PATH 中的 ffmpeg。
623
- * - `transcodeVideo`:转码 / 缩放 / 帧率
624
- * - `getVideoInfo`:解析 ffprobe 输出取宽高与时长
625
- * - `extractVideoFrame`:抽首帧作缩略图(QQ 视频消息发送需要)
626
- */
627
- const MS_PER_SECOND = 1e3;
628
- /** 判断未知值是否为非 null、非数组的普通对象(media 零内部依赖,就地实现)。 */
629
- function isRecord(val) {
630
- return typeof val === "object" && val !== null && !Array.isArray(val);
631
- }
632
- /** ffprobe 单个 stream 项安全构造(非对象 / 字段类型不符 → null)。 */
633
- function parseFfprobeStream(item) {
634
- if (!isRecord(item)) return null;
635
- const width = item["width"];
636
- const height = item["height"];
637
- const codecType = item["codec_type"];
881
+ const MAX_VIDEO_BYTES = 134217728;
882
+ const MAX_THUMB_BYTES = 16777216;
883
+ const MAX_SECONDS = 600;
884
+ const MAX_EDGE = 4096;
885
+ const MAX_PIXEL_FRAMES = 186624e5;
886
+ const MAX_FPS = 60;
887
+ const PNG_SIGNATURE = Buffer.from([
888
+ 137,
889
+ 80,
890
+ 78,
891
+ 71,
892
+ 13,
893
+ 10,
894
+ 26,
895
+ 10
896
+ ]);
897
+ function record(value) {
898
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
899
+ }
900
+ function positiveNumber(value) {
901
+ const number = typeof value === "string" && value !== "" ? Number(value) : value;
902
+ return typeof number === "number" && Number.isFinite(number) && number > 0 ? number : 0;
903
+ }
904
+ function frameRate(value) {
905
+ if (typeof value !== "string") return 0;
906
+ const [numerator, denominator] = value.split("/");
907
+ const divisor = positiveNumber(denominator);
908
+ return divisor === 0 ? 0 : positiveNumber(numerator) / divisor;
909
+ }
910
+ function assertDimensions(width, height) {
911
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 || width > MAX_EDGE || height > MAX_EDGE || width * height > 8294400) throw new MediaError("视频尺寸无效或超出像素限制");
912
+ }
913
+ function displayDimensions(stream) {
914
+ const width = positiveNumber(stream["width"]);
915
+ const height = positiveNumber(stream["height"]);
916
+ assertDimensions(width, height);
917
+ const sideData = stream["side_data_list"];
918
+ return Array.isArray(sideData) && sideData.some((item) => Math.abs(Number(record(item)?.["rotation"])) % 180 === 90) ? [height, width] : [width, height];
919
+ }
920
+ function parseVideoProbe(output, source) {
921
+ const parsed = record(JSON.parse(output));
922
+ const streams = parsed?.["streams"];
923
+ const stream = Array.isArray(streams) ? record(streams[0]) : void 0;
924
+ if (stream === void 0) throw new MediaError(`ffprobe 未取到视频信息: ${source}`);
925
+ const [width, height] = displayDimensions(stream);
926
+ const format = record(parsed?.["format"]);
927
+ const seconds = positiveNumber(format?.["duration"]);
928
+ const fps = frameRate(stream["avg_frame_rate"]) || frameRate(stream["r_frame_rate"]);
929
+ if (seconds === 0 || seconds > MAX_SECONDS || fps === 0 || fps > MAX_FPS) throw new MediaError("视频时长或帧率无效或超出限制");
638
930
  return {
639
- ...typeof width === "number" ? { width } : {},
640
- ...typeof height === "number" ? { height } : {},
641
- ...typeof codecType === "string" ? { ["codec_type"]: codecType } : {}
931
+ width,
932
+ height,
933
+ seconds,
934
+ fps,
935
+ packets: positiveNumber(stream["nb_read_packets"]),
936
+ codec: stream["codec_name"],
937
+ format: format?.["format_name"]
642
938
  };
643
939
  }
644
- /** ffprobe format 段安全构造(缺失 / duration 非字符串 → undefined)。 */
645
- function parseFfprobeFormat(raw) {
646
- if (!isRecord(raw)) return;
647
- const duration = raw["duration"];
648
- return typeof duration === "string" ? { duration } : void 0;
649
- }
650
- /** ffprobe JSON → 安全构造的形状(非对象 / 字段类型不符 → null)。 */
651
- function parseFfprobe(raw) {
652
- if (!isRecord(raw)) return null;
653
- const streams = [];
654
- const streamsRaw = raw["streams"];
655
- if (Array.isArray(streamsRaw)) for (const item of streamsRaw) {
656
- const stream = parseFfprobeStream(item);
657
- if (stream !== null) streams.push(stream);
940
+ async function probeVideo(source, signal, countPackets = false) {
941
+ checkMediaSignal(signal);
942
+ try {
943
+ const result = await execa("ffprobe", [
944
+ "-v",
945
+ "error",
946
+ ...FFPROBE_WORK_OPTIONS,
947
+ ...LOCAL_MEDIA_INPUT_OPTIONS,
948
+ "-select_streams",
949
+ "V:0",
950
+ ...countPackets ? ["-count_packets"] : [],
951
+ "-show_entries",
952
+ "stream=width,height,codec_name,avg_frame_rate,r_frame_rate,nb_read_packets:stream_side_data=rotation:format=duration,format_name",
953
+ "-of",
954
+ "json",
955
+ "-i",
956
+ source
957
+ ], mediaProcessOptions(15e3, signal));
958
+ checkMediaSignal(signal);
959
+ if (result.exitCode !== 0 || result.failed) throw new MediaError(`ffprobe 读取失败: ${source}(exit ${result.exitCode ?? "?"})`, { cause: result });
960
+ return parseVideoProbe(result.stdout, source);
961
+ } catch (error) {
962
+ checkMediaSignal(signal);
963
+ if (error instanceof MediaError) throw error;
964
+ throw new MediaError(`ffprobe 读取失败: ${source}`, { cause: error });
658
965
  }
659
- const format = parseFfprobeFormat(raw["format"]);
660
- return {
661
- ...streams.length > 0 ? { streams } : {},
662
- ...format !== void 0 ? { format } : {}
663
- };
966
+ }
967
+ function validOutputEdge(edge) {
968
+ return edge === void 0 || Number.isSafeInteger(edge) && edge >= 2 && edge <= MAX_EDGE && edge % 2 === 0;
969
+ }
970
+ function assertTranscodeOptions(opts) {
971
+ const { width, height, fps } = opts;
972
+ if (!validOutputEdge(width) || !validOutputEdge(height)) throw new MediaError("转码宽高须为 2–4096 的偶整数");
973
+ if (width !== void 0 && height !== void 0) assertDimensions(width, height);
974
+ if (fps !== void 0 && (!Number.isFinite(fps) || fps < 1 || fps > MAX_FPS)) throw new MediaError("转码帧率须为 1–60 的有限数");
975
+ }
976
+ function outputDimensions(source, opts) {
977
+ const { width, height } = source;
978
+ const w = opts.width ?? (opts.height === void 0 ? Math.max(2, width - width % 2) : Math.round(opts.height * width / height / 2) * 2);
979
+ const h = opts.height ?? (opts.width === void 0 ? Math.max(2, height - height % 2) : Math.round(opts.width * height / width / 2) * 2);
980
+ assertDimensions(w, h);
981
+ return [w, h];
664
982
  }
665
983
  /** 转码到独占目录。成功后调用方拥有输出文件及其父临时目录,消费结束后负责删除。 */
666
984
  async function transcodeVideo(input, opts = {}) {
667
- const source = await localMediaPath(input);
668
- const args = [
669
- "-nostdin",
670
- "-v",
671
- "error",
672
- "-y",
673
- ...LOCAL_MEDIA_INPUT_OPTIONS,
674
- "-i",
675
- source
676
- ];
677
- if (opts.width !== void 0 && opts.height !== void 0) args.push("-vf", `scale=${opts.width}:${opts.height}`);
678
- else if (opts.width !== void 0) args.push("-vf", `scale=${opts.width}:-2`);
679
- else if (opts.height !== void 0) args.push("-vf", `scale=-2:${opts.height}`);
680
- if (opts.fps !== void 0) args.push("-r", String(opts.fps));
985
+ const { signal } = opts;
986
+ checkMediaSignal(signal);
987
+ assertTranscodeOptions(opts);
988
+ const source = await localMediaPath(input, MAX_VIDEO_BYTES);
989
+ const info = await probeVideo(source, signal);
990
+ const [width, height] = outputDimensions(info, opts);
991
+ const maxFrames = Math.floor(MAX_PIXEL_FRAMES / (width * height));
992
+ if (info.width * info.height * Math.ceil(info.seconds * info.fps) > MAX_PIXEL_FRAMES || Math.ceil(info.seconds * (opts.fps ?? info.fps)) > maxFrames) throw new MediaError("视频超出转码像素帧预算");
993
+ checkMediaSignal(signal);
681
994
  const dir = await mkdtemp(join(dirname(source), ".napuketto-video-"));
682
995
  const output = join(dir, "output.mp4");
683
- args.push("-c:v", "libx264", "-preset", "fast", output);
996
+ const scale = `scale=${width}:${height}`;
997
+ const filter = opts.fps === void 0 ? scale : `fps=${opts.fps}:eof_action=pass,${scale}`;
684
998
  try {
685
- const result = await execa("ffmpeg", args, mediaProcessOptions(3e5));
686
- if (result.exitCode !== 0 || result.failed) throw new MediaError(`ffmpeg 转码失败: ${input}(exit ${result.exitCode ?? "?"})`, { cause: result });
687
- await assertMediaOutput(output);
999
+ await writeFfmpegOutput([
1000
+ "-nostdin",
1001
+ "-v",
1002
+ "error",
1003
+ ...FFMPEG_WORK_OPTIONS,
1004
+ ...LOCAL_MEDIA_INPUT_OPTIONS,
1005
+ "-i",
1006
+ source,
1007
+ "-map",
1008
+ "0:V:0",
1009
+ "-map",
1010
+ "0:a:0?",
1011
+ "-vf",
1012
+ filter,
1013
+ ...opts.fps === void 0 ? ["-fpsmax", String(MAX_FPS)] : [],
1014
+ "-frames:v",
1015
+ String(maxFrames + 1),
1016
+ "-t",
1017
+ String(601),
1018
+ "-c:v",
1019
+ "libx264",
1020
+ "-preset",
1021
+ "fast",
1022
+ "-pix_fmt",
1023
+ "yuv420p",
1024
+ "-bf",
1025
+ "0",
1026
+ "-threads:v",
1027
+ "2",
1028
+ "-maxrate",
1029
+ "8M",
1030
+ "-bufsize",
1031
+ "16M",
1032
+ "-c:a",
1033
+ "aac",
1034
+ "-ac",
1035
+ "2",
1036
+ "-b:a",
1037
+ "128k",
1038
+ "-movflags",
1039
+ "+empty_moov+default_base_moof+frag_keyframe+negative_cts_offsets",
1040
+ "-frag_duration",
1041
+ "1000000",
1042
+ "-f",
1043
+ "mp4"
1044
+ ], output, MAX_VIDEO_BYTES, 3e5, signal);
1045
+ const converted = await probeVideo(output, signal, true);
1046
+ if (converted.width !== width || converted.height !== height || converted.codec !== "h264" || typeof converted.format !== "string" || !converted.format.split(",").includes("mp4") || !Number.isSafeInteger(converted.packets) || converted.packets === 0 || converted.packets > maxFrames) throw new MediaError("转码产物的封装、尺寸、编码或帧数无效");
1047
+ if (opts.fps !== void 0 && Math.abs(converted.fps - opts.fps) > opts.fps / 1e3) throw new MediaError("转码产物帧率与请求不符");
1048
+ checkMediaSignal(signal);
688
1049
  return output;
689
- } catch (err) {
1050
+ } catch (error) {
690
1051
  await rm(dir, {
691
1052
  recursive: true,
692
1053
  force: true
693
1054
  });
694
- if (err instanceof MediaError) throw err;
695
- throw new MediaError(`ffmpeg 不可用或转码失败: ${input}`, { cause: err });
1055
+ if (error instanceof MediaError) throw error;
1056
+ throw new MediaError(`ffmpeg 不可用或转码失败: ${input}`, { cause: error });
696
1057
  }
697
1058
  }
698
- /** 读取视频宽高与时长(ffprobe JSON 输出解析)。 */
699
- async function getVideoInfo(input) {
700
- const source = await localMediaPath(input);
701
- let parsed;
702
- try {
703
- const result = await execa("ffprobe", [
704
- "-v",
705
- "error",
706
- ...LOCAL_MEDIA_INPUT_OPTIONS,
707
- "-print_format",
708
- "json",
709
- "-show_format",
710
- "-show_streams",
711
- "-i",
712
- source
713
- ], mediaProcessOptions(15e3));
714
- if (result.exitCode !== 0 || result.failed) throw new MediaError(`ffprobe 读取失败: ${input}(exit ${result.exitCode})`, { cause: result });
715
- const info = parseFfprobe(JSON.parse(result.stdout));
716
- if (info === null) throw new MediaError(`ffprobe 输出格式无效: ${input}`);
717
- parsed = info;
718
- } catch (err) {
719
- if (err instanceof MediaError) throw err;
720
- throw new MediaError(`ffprobe 读取失败: ${input}`, { cause: err });
721
- }
722
- const videoStream = parsed.streams?.find((s) => s["codec_type"] === "video");
723
- const width = videoStream?.width;
724
- const height = videoStream?.height;
725
- const durationStr = parsed.format?.duration;
726
- if (width === void 0 || height === void 0 || durationStr === void 0) throw new MediaError(`ffprobe 未取到视频信息: ${input}`);
1059
+ /** 读取视频显示尺寸与时长。 */
1060
+ async function getVideoInfo(input, { signal } = {}) {
1061
+ checkMediaSignal(signal);
1062
+ const { width, height, seconds } = await probeVideo(await localMediaPath(input, MAX_VIDEO_BYTES), signal);
727
1063
  return {
728
1064
  width,
729
1065
  height,
730
- durationMs: Math.round(Number(durationStr) * MS_PER_SECOND)
1066
+ durationMs: Math.round(seconds * 1e3)
731
1067
  };
732
1068
  }
733
- /**
734
- * 抽视频首帧为 PNG 缩略图(QQ 视频消息发送契约:thumbPath 指向真实图片文件)。
735
- *
736
- * 固定 `-ss 0` 取首帧:QQ 缩略图只需要一张可解码的封面,首帧最稳定
737
- * (部分视频首帧为黑屏时可改 1s,此处不引入额外配置)。转码失败 / ffmpeg
738
- * 缺失 / 输出未生成均抛 MediaError,由调用方决定降级策略。
739
- */
740
- async function extractVideoFrame(input, outputPath) {
741
- const source = await localMediaPath(input);
1069
+ /** 抽首帧至调用者指定路径。失败时保留原目标。 */
1070
+ async function extractVideoFrame(input, outputPath, { signal } = {}) {
1071
+ checkMediaSignal(signal);
1072
+ const source = await localMediaPath(input, MAX_VIDEO_BYTES);
742
1073
  const requestedTarget = resolve(outputPath);
743
1074
  const target = join(await realpath(dirname(requestedTarget)), basename(requestedTarget));
744
1075
  if (source === target || process.platform === "win32" && source.toLowerCase() === target.toLowerCase()) throw new MediaError("抽帧输出不能覆盖输入文件");
745
1076
  const dir = await mkdtemp(join(dirname(target), ".napuketto-frame-"));
746
1077
  const output = join(dir, "frame.png");
747
- const args = [
748
- "-nostdin",
749
- "-v",
750
- "error",
751
- "-y",
752
- "-ss",
753
- "0",
754
- ...LOCAL_MEDIA_INPUT_OPTIONS,
755
- "-i",
756
- source,
757
- "-frames:v",
758
- "1",
759
- "-q:v",
760
- "3",
761
- "-f",
762
- "image2",
763
- output
764
- ];
765
1078
  try {
766
- const result = await execa("ffmpeg", args, mediaProcessOptions(3e4));
767
- if (result.exitCode !== 0 || result.failed) throw new MediaError(`ffmpeg 抽帧失败: ${input}(exit ${result.exitCode ?? "?"})`, { cause: result });
768
- await assertMediaOutput(output);
1079
+ await writeFfmpegOutput([
1080
+ "-nostdin",
1081
+ "-v",
1082
+ "error",
1083
+ ...FFMPEG_WORK_OPTIONS,
1084
+ "-ss",
1085
+ "0",
1086
+ ...LOCAL_MEDIA_INPUT_OPTIONS,
1087
+ "-i",
1088
+ source,
1089
+ "-map",
1090
+ "0:V:0",
1091
+ "-frames:v",
1092
+ "1",
1093
+ "-c:v",
1094
+ "png",
1095
+ "-threads:v",
1096
+ "2",
1097
+ "-f",
1098
+ "image2pipe"
1099
+ ], output, MAX_THUMB_BYTES, 3e4, signal);
1100
+ const header = await readMediaPrefix(output, 24, signal);
1101
+ if (header.length !== 24 || !header.subarray(0, 8).equals(PNG_SIGNATURE) || header.toString("latin1", 12, 16) !== "IHDR") throw new MediaError("抽帧产物不是有效的 PNG");
1102
+ assertDimensions(header.readUInt32BE(16), header.readUInt32BE(20));
1103
+ checkMediaSignal(signal);
769
1104
  await rename(output, target);
770
1105
  return outputPath;
771
- } catch (err) {
772
- if (err instanceof MediaError) throw err;
773
- throw new MediaError(`ffmpeg 不可用或抽帧失败: ${input}`, { cause: err });
1106
+ } catch (error) {
1107
+ if (error instanceof MediaError) throw error;
1108
+ throw new MediaError(`ffmpeg 不可用或抽帧失败: ${input}`, { cause: error });
774
1109
  } finally {
775
1110
  await rm(dir, {
776
1111
  recursive: true,
@@ -778,4 +1113,4 @@ async function extractVideoFrame(input, outputPath) {
778
1113
  });
779
1114
  }
780
1115
  }
781
- export { MediaError, SILK_SAMPLE_RATE, decodeSilkToPcm, decodeSilkToWav, detectFileType, downloadPublicUrl, downloadUrl, encodePcmToSilk, extractVideoFrame, getImageSize, getSilkInfo, getVideoInfo, inferExtension, transcodeVideo };
1116
+ export { MAX_AUDIO_INPUT_BYTES, MAX_AUDIO_SECONDS, MediaError, SILK_SAMPLE_RATE, decodeSilkToPcm, decodeSilkToWav, detectFileType, downloadPublicUrl, downloadUrl, encodePcmToSilk, extractVideoFrame, getImageSize, getSilkInfo, getVideoInfo, inferExtension, transcodeVideo };