@napuketto/media 0.3.0 → 0.4.1

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.d.mts CHANGED
@@ -34,10 +34,16 @@ interface VideoInfo {
34
34
  /** 时长(毫秒)。 */
35
35
  durationMs: number;
36
36
  }
37
+ interface MediaOperationOptions {
38
+ signal?: AbortSignal | undefined;
39
+ }
37
40
  /** 视频转码选项。 */
38
- interface TranscodeOptions {
41
+ interface TranscodeOptions extends MediaOperationOptions {
42
+ /** 偶整数,2–4096。只指定一边时保持比例。 */
39
43
  width?: number | undefined;
44
+ /** 偶整数,2–4096。 */
40
45
  height?: number | undefined;
46
+ /** 有限数,1–60。 */
41
47
  fps?: number | undefined;
42
48
  }
43
49
  /** SILK 解码产物(pcm_s16le)。 */
@@ -53,37 +59,26 @@ export declare class MediaError extends Error {
53
59
  }
54
60
  /** SILK 默认采样率(Hz)。 */
55
61
  export declare const SILK_SAMPLE_RATE = 24e3;
62
+ export declare const MAX_AUDIO_SECONDS = 600;
63
+ export declare const MAX_AUDIO_INPUT_BYTES: number;
56
64
  /** 解码 SILK 音频为 PCM(pcm_s16le)。 */
57
- export declare function decodeSilkToPcm(input: string, sampleRate?: number): Promise<DecodedAudio>;
58
- /** 解码 SILK → WAV 输出选项。 */
59
- interface DecodeSilkToWavOptions {
60
- /** 采样率(缺省 24000,QQ 语音协议值)。 */
65
+ export declare function decodeSilkToPcm(input: string, sampleRate?: number, { signal }?: MediaOperationOptions): Promise<DecodedAudio>;
66
+ interface DecodeSilkToWavOptions extends MediaOperationOptions {
67
+ /** 缺省 24 kHz。 */
61
68
  sampleRate?: number | undefined;
62
- /** 输出目录(缺省输入同目录;收方向解码建议 tmpdir,避免污染 NT 数据目录)。 */
69
+ /** 缺省输入同目录。 */
63
70
  outDir?: string | undefined;
64
71
  }
65
- /** 解码结果(WAV)。 */
66
72
  interface DecodedWav {
67
73
  wavPath: string;
68
74
  durationMs: number;
69
75
  }
70
- /**
71
- * 解码 SILK → WAV 文件(pcm_s16le 单声道 + 44 字节头,通用可播放格式)。
72
- * 收方向语音接线用(koishi h.audio / 外部客户端):QQ 语音是 silk v3,
73
- * 多数播放器无法直接解码,落 WAV 后以本地路径消费。
74
- */
75
- export declare function decodeSilkToWav(input: string, options?: DecodeSilkToWavOptions): Promise<DecodedWav>;
76
- /**
77
- * 编码任意音频为 SILK 文件(返回输出路径,输出紧随输入文件)。
78
- *
79
- * - 已是 SILK → 原样返回
80
- * - 单声道 16-bit PCM WAV / 显式采样率的原始 pcm_s16le → silk-wasm 直接编码
81
- * - 其余(立体声/浮点/非 16-bit WAV、mp3/ogg/amr/flac 等)→ ffmpeg 归一化为
82
- * 24000Hz 单声道 pcm_s16le → silk-wasm 编码
83
- */
84
- export declare function encodePcmToSilk(input: string, sampleRate?: number): Promise<string>;
85
- /** 获取 SILK 音频信息(时长 / 采样率)。 */
86
- export declare function getSilkInfo(input: string, sampleRate?: number): Promise<AudioInfo>;
76
+ /** 解码 SILK 为可播放 WAV,返回的文件由调用方管理。 */
77
+ export declare function decodeSilkToWav(input: string, { sampleRate, outDir, signal }?: DecodeSilkToWavOptions): Promise<DecodedWav>;
78
+ /** 编码音频为 SILK;已通过边界检查的 SILK 原样返回。 */
79
+ export declare function encodePcmToSilk(input: string, sampleRate?: number, { signal }?: MediaOperationOptions): Promise<string>;
80
+ /** 获取 SILK 音频时长。SILK 容器不携带采样率,返回调用方指定值。 */
81
+ export declare function getSilkInfo(input: string, sampleRate?: number, { signal }?: MediaOperationOptions): Promise<AudioInfo>;
87
82
  /** 按协议调用方的信任边界选择远程媒体出站模式。 */
88
83
  type MediaOutboundPolicy = "public-only" | "compat";
89
84
  /** 下载选项。 */
@@ -105,20 +100,14 @@ export declare function downloadUrl(url: string, dest: string, options?: Downloa
105
100
  export declare function downloadPublicUrl(url: string, dest: string, options?: DownloadUrlOptions): Promise<number>;
106
101
  /** 从 Content-Type / URL 路径推断扩展名(缺省 .bin;下载命名用)。 */
107
102
  export declare function inferExtension(contentType: string | null, url: string): string;
108
- /** 读取图片尺寸(image-size 同步 API,内部读文件 + 计算)。 */
109
- export declare function getImageSize(input: string): Promise<ImageSize>;
103
+ /** 只读取有限的图片头部,尺寸元数据须在前 512 KiB 内。 */
104
+ export declare function getImageSize(input: string, { signal }?: MediaOperationOptions): Promise<ImageSize>;
110
105
  /** 检测文件类型(魔数识别,返回 undefined 时抛 MediaError)。 */
111
- export declare function detectFileType(input: string): Promise<FileTypeResult>;
106
+ export declare function detectFileType(input: string, { signal }?: MediaOperationOptions): Promise<FileTypeResult>;
112
107
  /** 转码到独占目录。成功后调用方拥有输出文件及其父临时目录,消费结束后负责删除。 */
113
108
  export declare function transcodeVideo(input: string, opts?: TranscodeOptions): Promise<string>;
114
- /** 读取视频宽高与时长(ffprobe JSON 输出解析)。 */
115
- export declare function getVideoInfo(input: string): Promise<VideoInfo>;
116
- /**
117
- * 抽视频首帧为 PNG 缩略图(QQ 视频消息发送契约:thumbPath 指向真实图片文件)。
118
- *
119
- * 固定 `-ss 0` 取首帧:QQ 缩略图只需要一张可解码的封面,首帧最稳定
120
- * (部分视频首帧为黑屏时可改 1s,此处不引入额外配置)。转码失败 / ffmpeg
121
- * 缺失 / 输出未生成均抛 MediaError,由调用方决定降级策略。
122
- */
123
- export declare function extractVideoFrame(input: string, outputPath: string): Promise<string>;
124
- export type { AudioInfo, DecodeSilkToWavOptions, DecodedAudio, DecodedWav, DownloadUrlOptions, FileTypeResult, ImageSize, MediaOutboundPolicy, TranscodeOptions, VideoInfo };
109
+ /** 读取视频显示尺寸与时长。 */
110
+ export declare function getVideoInfo(input: string, { signal }?: MediaOperationOptions): Promise<VideoInfo>;
111
+ /** 抽首帧至调用者指定路径。失败时保留原目标。 */
112
+ export declare function extractVideoFrame(input: string, outputPath: string, { signal }?: MediaOperationOptions): Promise<string>;
113
+ export type { AudioInfo, DecodeSilkToWavOptions, DecodedAudio, DecodedWav, DownloadUrlOptions, FileTypeResult, ImageSize, MediaOperationOptions, MediaOutboundPolicy, TranscodeOptions, VideoInfo };
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}`);
144
223
  }
145
- function assertAudioDuration(seconds) {
146
- if (!Number.isFinite(seconds) || seconds <= 0 || seconds > MAX_AUDIO_SECONDS) throw new MediaError(`音频时长必须大于 0 且不超过 ${MAX_AUDIO_SECONDS}s`);
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;
230
+ }
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;
@@ -664,180 +844,268 @@ function inferExtension(contentType, url) {
664
844
  * - `getImageSize`:image-size(读取 Uint8Array,同步计算)
665
845
  * - `detectFileType`:file-type(按文件路径检测魔数)
666
846
  */
667
- /** 读取图片尺寸(image-size 同步 API,内部读文件 + 计算)。 */
668
- async function getImageSize(input) {
669
- const buffer = await readFile(input);
670
- const size = imageSize(buffer);
671
- return {
672
- width: size.width,
673
- height: size.height
674
- };
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
+ }
675
862
  }
676
863
  /** 检测文件类型(魔数识别,返回 undefined 时抛 MediaError)。 */
677
- async function detectFileType(input) {
678
- const result = await fileTypeFromFile(input);
679
- if (result === void 0) throw new MediaError(`无法识别的文件类型: ${input}`);
680
- return {
681
- ext: result.ext,
682
- mime: result.mime
683
- };
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}`);
684
879
  }
685
880
  // src/video.ts
686
- /**
687
- * 视频(execa 调用外部 ffmpeg 二进制)
688
- *
689
- * ffmpeg 由 execa 以子进程方式调用(非 node 内置),依赖系统 PATH 中的 ffmpeg。
690
- * - `transcodeVideo`:转码 / 缩放 / 帧率
691
- * - `getVideoInfo`:解析 ffprobe 输出取宽高与时长
692
- * - `extractVideoFrame`:抽首帧作缩略图(QQ 视频消息发送需要)
693
- */
694
- const MS_PER_SECOND = 1e3;
695
- /** 判断未知值是否为非 null、非数组的普通对象(media 零内部依赖,就地实现)。 */
696
- function isRecord(val) {
697
- return typeof val === "object" && val !== null && !Array.isArray(val);
698
- }
699
- /** ffprobe 单个 stream 项安全构造(非对象 / 字段类型不符 → null)。 */
700
- function parseFfprobeStream(item) {
701
- if (!isRecord(item)) return null;
702
- const width = item["width"];
703
- const height = item["height"];
704
- 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("视频时长或帧率无效或超出限制");
705
930
  return {
706
- ...typeof width === "number" ? { width } : {},
707
- ...typeof height === "number" ? { height } : {},
708
- ...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"]
709
938
  };
710
939
  }
711
- /** ffprobe format 段安全构造(缺失 / duration 非字符串 → undefined)。 */
712
- function parseFfprobeFormat(raw) {
713
- if (!isRecord(raw)) return;
714
- const duration = raw["duration"];
715
- return typeof duration === "string" ? { duration } : void 0;
716
- }
717
- /** ffprobe JSON → 安全构造的形状(非对象 / 字段类型不符 → null)。 */
718
- function parseFfprobe(raw) {
719
- if (!isRecord(raw)) return null;
720
- const streams = [];
721
- const streamsRaw = raw["streams"];
722
- if (Array.isArray(streamsRaw)) for (const item of streamsRaw) {
723
- const stream = parseFfprobeStream(item);
724
- 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 });
725
965
  }
726
- const format = parseFfprobeFormat(raw["format"]);
727
- return {
728
- ...streams.length > 0 ? { streams } : {},
729
- ...format !== void 0 ? { format } : {}
730
- };
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];
731
982
  }
732
983
  /** 转码到独占目录。成功后调用方拥有输出文件及其父临时目录,消费结束后负责删除。 */
733
984
  async function transcodeVideo(input, opts = {}) {
734
- const source = await localMediaPath(input);
735
- const args = [
736
- "-nostdin",
737
- "-v",
738
- "error",
739
- "-y",
740
- ...LOCAL_MEDIA_INPUT_OPTIONS,
741
- "-i",
742
- source
743
- ];
744
- if (opts.width !== void 0 && opts.height !== void 0) args.push("-vf", `scale=${opts.width}:${opts.height}`);
745
- else if (opts.width !== void 0) args.push("-vf", `scale=${opts.width}:-2`);
746
- else if (opts.height !== void 0) args.push("-vf", `scale=-2:${opts.height}`);
747
- 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);
748
994
  const dir = await mkdtemp(join(dirname(source), ".napuketto-video-"));
749
995
  const output = join(dir, "output.mp4");
750
- 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}`;
751
998
  try {
752
- const result = await execa("ffmpeg", args, mediaProcessOptions(3e5));
753
- if (result.exitCode !== 0 || result.failed) throw new MediaError(`ffmpeg 转码失败: ${input}(exit ${result.exitCode ?? "?"})`, { cause: result });
754
- 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);
755
1049
  return output;
756
- } catch (err) {
1050
+ } catch (error) {
757
1051
  await rm(dir, {
758
1052
  recursive: true,
759
1053
  force: true
760
1054
  });
761
- if (err instanceof MediaError) throw err;
762
- throw new MediaError(`ffmpeg 不可用或转码失败: ${input}`, { cause: err });
1055
+ if (error instanceof MediaError) throw error;
1056
+ throw new MediaError(`ffmpeg 不可用或转码失败: ${input}`, { cause: error });
763
1057
  }
764
1058
  }
765
- /** 读取视频宽高与时长(ffprobe JSON 输出解析)。 */
766
- async function getVideoInfo(input) {
767
- const source = await localMediaPath(input);
768
- let parsed;
769
- try {
770
- const result = await execa("ffprobe", [
771
- "-v",
772
- "error",
773
- ...LOCAL_MEDIA_INPUT_OPTIONS,
774
- "-print_format",
775
- "json",
776
- "-show_format",
777
- "-show_streams",
778
- "-i",
779
- source
780
- ], mediaProcessOptions(15e3));
781
- if (result.exitCode !== 0 || result.failed) throw new MediaError(`ffprobe 读取失败: ${input}(exit ${result.exitCode})`, { cause: result });
782
- const info = parseFfprobe(JSON.parse(result.stdout));
783
- if (info === null) throw new MediaError(`ffprobe 输出格式无效: ${input}`);
784
- parsed = info;
785
- } catch (err) {
786
- if (err instanceof MediaError) throw err;
787
- throw new MediaError(`ffprobe 读取失败: ${input}`, { cause: err });
788
- }
789
- const videoStream = parsed.streams?.find((s) => s["codec_type"] === "video");
790
- const width = videoStream?.width;
791
- const height = videoStream?.height;
792
- const durationStr = parsed.format?.duration;
793
- 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);
794
1063
  return {
795
1064
  width,
796
1065
  height,
797
- durationMs: Math.round(Number(durationStr) * MS_PER_SECOND)
1066
+ durationMs: Math.round(seconds * 1e3)
798
1067
  };
799
1068
  }
800
- /**
801
- * 抽视频首帧为 PNG 缩略图(QQ 视频消息发送契约:thumbPath 指向真实图片文件)。
802
- *
803
- * 固定 `-ss 0` 取首帧:QQ 缩略图只需要一张可解码的封面,首帧最稳定
804
- * (部分视频首帧为黑屏时可改 1s,此处不引入额外配置)。转码失败 / ffmpeg
805
- * 缺失 / 输出未生成均抛 MediaError,由调用方决定降级策略。
806
- */
807
- async function extractVideoFrame(input, outputPath) {
808
- 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);
809
1073
  const requestedTarget = resolve(outputPath);
810
1074
  const target = join(await realpath(dirname(requestedTarget)), basename(requestedTarget));
811
1075
  if (source === target || process.platform === "win32" && source.toLowerCase() === target.toLowerCase()) throw new MediaError("抽帧输出不能覆盖输入文件");
812
1076
  const dir = await mkdtemp(join(dirname(target), ".napuketto-frame-"));
813
1077
  const output = join(dir, "frame.png");
814
- const args = [
815
- "-nostdin",
816
- "-v",
817
- "error",
818
- "-y",
819
- "-ss",
820
- "0",
821
- ...LOCAL_MEDIA_INPUT_OPTIONS,
822
- "-i",
823
- source,
824
- "-frames:v",
825
- "1",
826
- "-q:v",
827
- "3",
828
- "-f",
829
- "image2",
830
- output
831
- ];
832
1078
  try {
833
- const result = await execa("ffmpeg", args, mediaProcessOptions(3e4));
834
- if (result.exitCode !== 0 || result.failed) throw new MediaError(`ffmpeg 抽帧失败: ${input}(exit ${result.exitCode ?? "?"})`, { cause: result });
835
- 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);
836
1104
  await rename(output, target);
837
1105
  return outputPath;
838
- } catch (err) {
839
- if (err instanceof MediaError) throw err;
840
- 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 });
841
1109
  } finally {
842
1110
  await rm(dir, {
843
1111
  recursive: true,
@@ -845,4 +1113,4 @@ async function extractVideoFrame(input, outputPath) {
845
1113
  });
846
1114
  }
847
1115
  }
848
- 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 };
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,8 @@
1
+ import { parentPort, workerData } from "node:worker_threads";
2
+ import { decode, encode } from "silk-wasm";
3
+ // src/silk-worker.mts
4
+ const job = workerData;
5
+ const result = await (job.mode === "encode" ? encode : decode)(job.data, job.sampleRate);
6
+ const buffer = result.data.buffer;
7
+ parentPort?.postMessage(result, buffer instanceof ArrayBuffer ? [buffer] : []);
8
+ export {};
package/package.json CHANGED
@@ -1,11 +1,10 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@napuketto/media",
4
- "version": "0.3.0",
4
+ "version": "0.4.1",
5
5
  "type": "module",
6
- "description": "Media utilities for NapukettoQQ",
6
+ "description": "Media utilities for Napuketto",
7
7
  "keywords": [
8
- "qq",
9
8
  "bot",
10
9
  "napuketto",
11
10
  "media",
@@ -13,13 +12,13 @@
13
12
  "image",
14
13
  "silk"
15
14
  ],
16
- "homepage": "https://github.com/NapukettoDev/NapukettoQQ/tree/main/packages/media#readme",
15
+ "homepage": "https://github.com/NapukettoDev/Napuketto/tree/main/packages/media#readme",
17
16
  "bugs": {
18
- "url": "https://github.com/NapukettoDev/NapukettoQQ/issues"
17
+ "url": "https://github.com/NapukettoDev/Napuketto/issues"
19
18
  },
20
19
  "repository": {
21
20
  "type": "git",
22
- "url": "git+https://github.com/NapukettoDev/NapukettoQQ.git",
21
+ "url": "git+https://github.com/NapukettoDev/Napuketto.git",
23
22
  "directory": "packages/media"
24
23
  },
25
24
  "license": "MIT",