@napuketto/media 0.4.0 → 0.5.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.d.mts CHANGED
@@ -37,8 +37,11 @@ interface VideoInfo {
37
37
  interface MediaOperationOptions {
38
38
  signal?: AbortSignal | undefined;
39
39
  }
40
+ interface MediaOutputOptions extends MediaOperationOptions {
41
+ maxOutputBytes?: number | undefined;
42
+ }
40
43
  /** 视频转码选项。 */
41
- interface TranscodeOptions extends MediaOperationOptions {
44
+ interface TranscodeOptions extends MediaOutputOptions {
42
45
  /** 偶整数,2–4096。只指定一边时保持比例。 */
43
46
  width?: number | undefined;
44
47
  /** 偶整数,2–4096。 */
@@ -57,6 +60,9 @@ interface DecodedAudio {
57
60
  export declare class MediaError extends Error {
58
61
  constructor(message: string, options?: ErrorOptions);
59
62
  }
63
+ export declare class MediaSizeLimitError extends MediaError {
64
+ constructor(message: string);
65
+ }
60
66
  /** SILK 默认采样率(Hz)。 */
61
67
  export declare const SILK_SAMPLE_RATE = 24e3;
62
68
  export declare const MAX_AUDIO_SECONDS = 600;
@@ -75,8 +81,14 @@ interface DecodedWav {
75
81
  }
76
82
  /** 解码 SILK 为可播放 WAV,返回的文件由调用方管理。 */
77
83
  export declare function decodeSilkToWav(input: string, { sampleRate, outDir, signal }?: DecodeSilkToWavOptions): Promise<DecodedWav>;
84
+ interface SilkEncodeOptions extends MediaOutputOptions {
85
+ /** 转码目标。指定时父目录须已存在,且由调用方控制。 */
86
+ outputPath?: string | undefined;
87
+ /** 归一化 PCM 清理后报告其实际写入量。 */
88
+ onPcmWritten?: ((bytes: number) => void) | undefined;
89
+ }
78
90
  /** 编码音频为 SILK;已通过边界检查的 SILK 原样返回。 */
79
- export declare function encodePcmToSilk(input: string, sampleRate?: number, { signal }?: MediaOperationOptions): Promise<string>;
91
+ export declare function encodePcmToSilk(input: string, sampleRate?: number, options?: SilkEncodeOptions): Promise<string>;
80
92
  /** 获取 SILK 音频时长。SILK 容器不携带采样率,返回调用方指定值。 */
81
93
  export declare function getSilkInfo(input: string, sampleRate?: number, { signal }?: MediaOperationOptions): Promise<AudioInfo>;
82
94
  /** 按协议调用方的信任边界选择远程媒体出站模式。 */
@@ -90,6 +102,8 @@ interface DownloadUrlOptions {
90
102
  /** 初始源的附加请求头。传输/路由头忽略,跨源重定向清空所有调用者头。 */
91
103
  headers?: Record<string, string> | undefined;
92
104
  }
105
+ /** 默认大小上限(30MB)。 */
106
+ export declare const DEFAULT_DOWNLOAD_MAX_BYTES: number;
93
107
  /**
94
108
  * 下载 URL 到目标路径(覆盖写)。返回写入字节数。
95
109
  * 失败抛 MediaError(非 2xx / 协议或地址被拒 / 超限 / 超时 / 空 body / IO 错误),
@@ -109,5 +123,5 @@ export declare function transcodeVideo(input: string, opts?: TranscodeOptions):
109
123
  /** 读取视频显示尺寸与时长。 */
110
124
  export declare function getVideoInfo(input: string, { signal }?: MediaOperationOptions): Promise<VideoInfo>;
111
125
  /** 抽首帧至调用者指定路径。失败时保留原目标。 */
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 };
126
+ export declare function extractVideoFrame(input: string, outputPath: string, { signal, maxOutputBytes }?: MediaOutputOptions): Promise<string>;
127
+ export type { AudioInfo, DecodeSilkToWavOptions, DecodedAudio, DecodedWav, DownloadUrlOptions, FileTypeResult, ImageSize, MediaOperationOptions, MediaOutboundPolicy, MediaOutputOptions, SilkEncodeOptions, TranscodeOptions, VideoInfo };
package/dist/index.mjs CHANGED
@@ -21,6 +21,12 @@ var MediaError = class extends Error {
21
21
  this.name = "MediaError";
22
22
  }
23
23
  };
24
+ var MediaSizeLimitError = class extends MediaError {
25
+ constructor(message) {
26
+ super(message);
27
+ this.name = "MediaSizeLimitError";
28
+ }
29
+ };
24
30
  /**
25
31
  * 替换文件扩展名(保持目录与分隔符风格,父目录存在性由调用方保证)。
26
32
  * 统一实现供 audio / video 复用;同时兼容 POSIX `/` 与 Windows `\` 分隔符。
@@ -86,6 +92,10 @@ function mediaProcessOptions(timeout, cancelSignal) {
86
92
  function checkMediaSignal(signal) {
87
93
  if (signal?.aborted) throw new MediaError("媒体操作已取消", { cause: signal.reason });
88
94
  }
95
+ function mediaOutputLimit(hardLimit, callerLimit = hardLimit) {
96
+ if (!Number.isSafeInteger(callerLimit) || callerLimit < 0) throw new MediaSizeLimitError("媒体输出上限必须是非负安全整数");
97
+ return Math.min(hardLimit, callerLimit);
98
+ }
89
99
  function assertLocalPath(input) {
90
100
  const windowsDrive = process.platform === "win32" && WINDOWS_DRIVE.test(input);
91
101
  if (input.length === 0 || input.includes("\0") || NETWORK_OR_DEVICE_PATH.test(input) || PROTOCOL_PREFIX.test(input) && !windowsDrive) throw new MediaError(`媒体输入必须是本地普通文件: ${input}`);
@@ -151,7 +161,7 @@ async function writeFfmpegOutput(args, path, maxBytes, timeout, signal) {
151
161
  let bytes = 0;
152
162
  const limit = new Transform({ transform(chunk, _encoding, callback) {
153
163
  bytes += chunk.length;
154
- if (bytes > maxBytes) callback(new MediaError(`媒体输出超过 ${maxBytes} 字节限制`));
164
+ if (bytes > maxBytes) callback(new MediaSizeLimitError(`媒体输出超过 ${maxBytes} 字节限制`));
155
165
  else callback(null, chunk);
156
166
  } });
157
167
  const writing = Promise.resolve().then(() => {
@@ -404,7 +414,9 @@ function monoWavPcm(header, fileSize) {
404
414
  }
405
415
  }
406
416
  /** 编码音频为 SILK;已通过边界检查的 SILK 原样返回。 */
407
- async function encodePcmToSilk(input, sampleRate = 0, { signal } = {}) {
417
+ async function encodePcmToSilk(input, sampleRate = 0, options = {}) {
418
+ const { signal, maxOutputBytes, onPcmWritten } = options;
419
+ const limit = mediaOutputLimit(62354432, maxOutputBytes);
408
420
  checkMediaSignal(signal);
409
421
  const source = await localMediaPath(input, MAX_AUDIO_INPUT_BYTES);
410
422
  const prefix = await readMediaPrefix(source, 12, signal);
@@ -415,10 +427,14 @@ async function encodePcmToSilk(input, sampleRate = 0, { signal } = {}) {
415
427
  const wav = isRiffWave(prefix);
416
428
  const pcm = wav ? monoWavPcm(await readMediaPrefix(source, 524288, signal), (await stat(source)).size) : void 0;
417
429
  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);
430
+ const silkPath = options.outputPath ?? replaceExt(input, ".silk");
431
+ const data = pcm !== void 0 || directRate !== 0 ? await readPcm(source, directRate, pcm, signal) : await normalizeToPcm(source, dirname(silkPath), limit, signal);
432
+ const pcmBytes = directRate === 0 ? data.byteLength : 0;
433
+ if (pcmBytes > 0) onPcmWritten?.(pcmBytes);
434
+ const result = await runSilk("encode", data, directRate || 24e3, signal);
419
435
  assertAudioDuration(result.duration);
420
- if (result.data.byteLength > 33554432 || result.data.byteLength === 0) throw new MediaError("SILK 输出超出大小限制或为空");
421
- const silkPath = replaceExt(input, ".silk");
436
+ if (result.data.byteLength > Math.min(33554432, limit - pcmBytes)) throw new MediaSizeLimitError("SILK 输出超出大小限制");
437
+ if (result.data.byteLength === 0) throw new MediaError("SILK 输出为空");
422
438
  await publishAudio(input, silkPath, [result.data], signal);
423
439
  return silkPath;
424
440
  }
@@ -430,8 +446,9 @@ async function readPcm(source, sampleRate, wav, signal) {
430
446
  assertAudioDuration(data.byteLength * 500 / sampleRate);
431
447
  return data;
432
448
  }
433
- async function normalizeToPcm(source, signal) {
434
- const partial = join(dirname(source), `.napuketto-${randomBytes(8).toString("hex")}.pcm`);
449
+ async function normalizeToPcm(source, directory, limit, signal) {
450
+ const partial = join(directory, `.napuketto-${randomBytes(8).toString("hex")}.pcm`);
451
+ const maxBytes = Math.min(MAX_NORMALIZED_PCM_BYTES, limit);
435
452
  try {
436
453
  await writeFfmpegOutput([
437
454
  "-nostdin",
@@ -451,10 +468,11 @@ async function normalizeToPcm(source, signal) {
451
468
  String(600.02),
452
469
  "-f",
453
470
  "s16le"
454
- ], partial, MAX_NORMALIZED_PCM_BYTES, 12e4, signal);
455
- return await readBoundedMediaFile(partial, MAX_NORMALIZED_PCM_BYTES, signal);
471
+ ], partial, maxBytes, 12e4, signal);
472
+ return await readBoundedMediaFile(partial, maxBytes, signal);
456
473
  } catch (error) {
457
474
  checkMediaSignal(signal);
475
+ if (error instanceof MediaSizeLimitError) throw error;
458
476
  throw new MediaError(`ffmpeg 音频归一化失败: ${source}`, { cause: error });
459
477
  } finally {
460
478
  await rm(partial, { force: true });
@@ -591,7 +609,7 @@ function createPublicRequest(checkLiteral) {
591
609
  * 兼容入口仅校验字面地址。公网入口同时校验实际连接的地址。
592
610
  */
593
611
  /** 默认大小上限(30MB)。 */
594
- const DEFAULT_MAX_BYTES = 31457280;
612
+ const DEFAULT_DOWNLOAD_MAX_BYTES = 31457280;
595
613
  /** 默认超时(15s)。 */
596
614
  const DEFAULT_TIMEOUT_MS = 15e3;
597
615
  /** 最大跳转次数(每跳都重新校验目标 URL)。 */
@@ -760,7 +778,7 @@ async function writeCapped(body, temp, maxBytes, signal) {
760
778
  const counter = new Transform({ transform(chunk, _encoding, callback) {
761
779
  total += chunk.byteLength;
762
780
  if (total > maxBytes) {
763
- callback(new MediaError(`文件超过大小上限(>${maxBytes} 字节)`));
781
+ callback(new MediaSizeLimitError(`文件超过大小上限(>${maxBytes} 字节)`));
764
782
  return;
765
783
  }
766
784
  callback(null, chunk);
@@ -793,7 +811,7 @@ async function downloadPublicUrl(url, dest, options = {}) {
793
811
  }
794
812
  async function download(url, dest, options, request) {
795
813
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
796
- const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
814
+ const maxBytes = options.maxBytes ?? 31457280;
797
815
  const controller = new AbortController();
798
816
  const timer = setTimeout(() => controller.abort(), timeoutMs);
799
817
  timer.unref?.();
@@ -804,7 +822,7 @@ async function download(url, dest, options, request) {
804
822
  body = response.body;
805
823
  if (response.status < 200 || response.status >= 300) throw new MediaError(`HTTP ${response.status}`);
806
824
  const declared = Number(response.headers.get("Content-Length") ?? "0");
807
- if (declared > maxBytes) throw new MediaError(`文件超过大小上限(${declared} > ${maxBytes} 字节)`);
825
+ if (declared > maxBytes) throw new MediaSizeLimitError(`文件超过大小上限(${declared} > ${maxBytes} 字节)`);
808
826
  if (body === null) throw new MediaError("响应无 body");
809
827
  await mkdir(dirname(dest), { recursive: true });
810
828
  const written = await writeCapped(body, temp, maxBytes, controller.signal);
@@ -983,6 +1001,7 @@ function outputDimensions(source, opts) {
983
1001
  /** 转码到独占目录。成功后调用方拥有输出文件及其父临时目录,消费结束后负责删除。 */
984
1002
  async function transcodeVideo(input, opts = {}) {
985
1003
  const { signal } = opts;
1004
+ const limit = mediaOutputLimit(MAX_VIDEO_BYTES, opts.maxOutputBytes);
986
1005
  checkMediaSignal(signal);
987
1006
  assertTranscodeOptions(opts);
988
1007
  const source = await localMediaPath(input, MAX_VIDEO_BYTES);
@@ -1041,7 +1060,7 @@ async function transcodeVideo(input, opts = {}) {
1041
1060
  "1000000",
1042
1061
  "-f",
1043
1062
  "mp4"
1044
- ], output, MAX_VIDEO_BYTES, 3e5, signal);
1063
+ ], output, limit, 3e5, signal);
1045
1064
  const converted = await probeVideo(output, signal, true);
1046
1065
  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
1066
  if (opts.fps !== void 0 && Math.abs(converted.fps - opts.fps) > opts.fps / 1e3) throw new MediaError("转码产物帧率与请求不符");
@@ -1067,14 +1086,14 @@ async function getVideoInfo(input, { signal } = {}) {
1067
1086
  };
1068
1087
  }
1069
1088
  /** 抽首帧至调用者指定路径。失败时保留原目标。 */
1070
- async function extractVideoFrame(input, outputPath, { signal } = {}) {
1089
+ async function extractVideoFrame(input, outputPath, { signal, maxOutputBytes } = {}) {
1090
+ const limit = mediaOutputLimit(MAX_THUMB_BYTES, maxOutputBytes);
1071
1091
  checkMediaSignal(signal);
1072
1092
  const source = await localMediaPath(input, MAX_VIDEO_BYTES);
1073
1093
  const requestedTarget = resolve(outputPath);
1074
1094
  const target = join(await realpath(dirname(requestedTarget)), basename(requestedTarget));
1075
1095
  if (source === target || process.platform === "win32" && source.toLowerCase() === target.toLowerCase()) throw new MediaError("抽帧输出不能覆盖输入文件");
1076
- const dir = await mkdtemp(join(dirname(target), ".napuketto-frame-"));
1077
- const output = join(dir, "frame.png");
1096
+ const output = join(dirname(target), `media.png.part-${process.pid}-${randomUUID()}`);
1078
1097
  try {
1079
1098
  await writeFfmpegOutput([
1080
1099
  "-nostdin",
@@ -1096,7 +1115,7 @@ async function extractVideoFrame(input, outputPath, { signal } = {}) {
1096
1115
  "2",
1097
1116
  "-f",
1098
1117
  "image2pipe"
1099
- ], output, MAX_THUMB_BYTES, 3e4, signal);
1118
+ ], output, limit, 3e4, signal);
1100
1119
  const header = await readMediaPrefix(output, 24, signal);
1101
1120
  if (header.length !== 24 || !header.subarray(0, 8).equals(PNG_SIGNATURE) || header.toString("latin1", 12, 16) !== "IHDR") throw new MediaError("抽帧产物不是有效的 PNG");
1102
1121
  assertDimensions(header.readUInt32BE(16), header.readUInt32BE(20));
@@ -1107,10 +1126,7 @@ async function extractVideoFrame(input, outputPath, { signal } = {}) {
1107
1126
  if (error instanceof MediaError) throw error;
1108
1127
  throw new MediaError(`ffmpeg 不可用或抽帧失败: ${input}`, { cause: error });
1109
1128
  } finally {
1110
- await rm(dir, {
1111
- recursive: true,
1112
- force: true
1113
- });
1129
+ await rm(output, { force: true });
1114
1130
  }
1115
1131
  }
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 };
1132
+ export { DEFAULT_DOWNLOAD_MAX_BYTES, MAX_AUDIO_INPUT_BYTES, MAX_AUDIO_SECONDS, MediaError, MediaSizeLimitError, SILK_SAMPLE_RATE, decodeSilkToPcm, decodeSilkToWav, detectFileType, downloadPublicUrl, downloadUrl, encodePcmToSilk, extractVideoFrame, getImageSize, getSilkInfo, getVideoInfo, inferExtension, transcodeVideo };
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.4.0",
4
+ "version": "0.5.0",
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",