@napuketto/media 0.0.3 → 0.0.5

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.cjs CHANGED
@@ -2809,7 +2809,7 @@ function parseMilliseconds(milliseconds) {
2809
2809
  throw new TypeError("Expected a finite number or bigint");
2810
2810
  }
2811
2811
  //#endregion
2812
- //#region ../../node_modules/.pnpm/pretty-ms@9.3.0/node_modules/pretty-ms/index.js
2812
+ //#region ../../node_modules/.pnpm/pretty-ms@9.3.1/node_modules/pretty-ms/index.js
2813
2813
  const isZero = (value) => value === 0 || value === 0n;
2814
2814
  const pluralize = (word, count) => count === 1 || count === 1n ? word : `${word}s`;
2815
2815
  const SECOND_ROUNDING_EPSILON = 1e-7;
@@ -2872,7 +2872,9 @@ function prettyMilliseconds(milliseconds, options) {
2872
2872
  } else {
2873
2873
  const millisecondsAndBelow = milliseconds + microseconds / 1e3 + nanoseconds / 1e6;
2874
2874
  const millisecondsDecimalDigits = typeof options.millisecondsDecimalDigits === "number" ? options.millisecondsDecimalDigits : 0;
2875
- const millisecondsString = millisecondsDecimalDigits ? millisecondsAndBelow.toFixed(millisecondsDecimalDigits) : millisecondsAndBelow >= 1 ? Math.round(millisecondsAndBelow) : Math.ceil(millisecondsAndBelow);
2875
+ const roundedMilliseconds = millisecondsAndBelow >= 1 ? Math.round(millisecondsAndBelow) : Math.ceil(millisecondsAndBelow);
2876
+ const maximumMilliseconds = 1e3 - 10 ** -millisecondsDecimalDigits;
2877
+ const millisecondsString = millisecondsDecimalDigits ? Math.min(millisecondsAndBelow, maximumMilliseconds).toFixed(millisecondsDecimalDigits) : Math.min(roundedMilliseconds, maximumMilliseconds);
2876
2878
  add(Number.parseFloat(millisecondsString), "millisecond", "ms", millisecondsString);
2877
2879
  }
2878
2880
  } else {
@@ -6428,6 +6430,55 @@ async function decodeSilkToPcm(input, sampleRate = SILK_SAMPLE_RATE) {
6428
6430
  };
6429
6431
  }
6430
6432
  /**
6433
+ * 解码 SILK → WAV 文件(pcm_s16le 单声道 + 44 字节头,通用可播放格式)。
6434
+ * 收方向语音接线用(koishi h.audio / 外部客户端):QQ 语音是 silk v3,
6435
+ * 多数播放器无法直接解码,落 WAV 后以本地路径消费。
6436
+ */
6437
+ async function decodeSilkToWav(input, options = {}) {
6438
+ const sampleRate = options.sampleRate ?? 24e3;
6439
+ const buffer = await (0, node_fs_promises.readFile)(input);
6440
+ if (!(0, silk_wasm.isSilk)(buffer)) throw new MediaError(`不是有效的 SILK 文件: ${input}`);
6441
+ const result = await (0, silk_wasm.decode)(buffer, sampleRate);
6442
+ const { dir, name } = outputTarget(input, ".wav", options.outDir);
6443
+ const wav = wrapPcmInWav(result.data, sampleRate);
6444
+ await (0, node_fs_promises.writeFile)((0, node_path.join)(dir, name), wav);
6445
+ return {
6446
+ wavPath: (0, node_path.join)(dir, name),
6447
+ durationMs: result.duration
6448
+ };
6449
+ }
6450
+ /** 输出目标(目录 + 文件名;outDir 优先,否则输入同目录替换扩展名)。 */
6451
+ function outputTarget(input, ext, outDir) {
6452
+ const base = input.replaceAll("\\", "/").split("/").pop() ?? "audio";
6453
+ const dot = base.lastIndexOf(".");
6454
+ const name = `${dot > 0 ? base.slice(0, dot) : base}${ext}`;
6455
+ const dir = outDir !== void 0 ? outDir : (0, node_path.dirname)(input);
6456
+ (0, node_fs.mkdirSync)(dir, { recursive: true });
6457
+ return {
6458
+ dir,
6459
+ name
6460
+ };
6461
+ }
6462
+ /** PCM(s16le 单声道)→ WAV 文件字节(44 字节头 + 数据)。 */
6463
+ function wrapPcmInWav(pcm, sampleRate) {
6464
+ const blockAlign = 2;
6465
+ const header = Buffer.alloc(44);
6466
+ header.write("RIFF", 0, "ascii");
6467
+ header.writeUInt32LE(36 + pcm.byteLength, 4);
6468
+ header.write("WAVE", 8, "ascii");
6469
+ header.write("fmt ", 12, "ascii");
6470
+ header.writeUInt32LE(16, 16);
6471
+ header.writeUInt16LE(1, 20);
6472
+ header.writeUInt16LE(1, 22);
6473
+ header.writeUInt32LE(sampleRate, 24);
6474
+ header.writeUInt32LE(sampleRate * blockAlign | 0, 28);
6475
+ header.writeUInt16LE(blockAlign, 32);
6476
+ header.writeUInt16LE(16, 34);
6477
+ header.write("data", 36, "ascii");
6478
+ header.writeUInt32LE(pcm.byteLength, 40);
6479
+ return Buffer.concat([header, Buffer.from(pcm)]);
6480
+ }
6481
+ /**
6431
6482
  * 编码任意音频为 SILK 文件(返回输出路径,输出紧随输入文件)。
6432
6483
  *
6433
6484
  * - 已是 SILK → 原样返回
@@ -6486,6 +6537,66 @@ async function getSilkInfo(input, sampleRate = SILK_SAMPLE_RATE) {
6486
6537
  };
6487
6538
  }
6488
6539
  //#endregion
6540
+ //#region src/downloader.ts
6541
+ /** 默认大小上限(30MB)。 */
6542
+ const DEFAULT_MAX_BYTES = 31457280;
6543
+ /** 默认超时(15s)。 */
6544
+ const DEFAULT_TIMEOUT_MS = 15e3;
6545
+ /** 扩展名字符合法性(URL pathname 提取校验)。 */
6546
+ const EXT_RE = /^\.[a-z0-9]+$/i;
6547
+ /**
6548
+ * 下载 URL 到目标路径(覆盖写)。返回写入字节数。
6549
+ * 失败抛错(非 2xx / 超限 / 超时 / 空 body / IO 错误),不产生半成品语义
6550
+ * (失败时目标文件可能残留,调用方负责清理目录)。
6551
+ */
6552
+ async function downloadUrl(url, dest, options = {}) {
6553
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
6554
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
6555
+ const response = await fetch(url, {
6556
+ redirect: "follow",
6557
+ signal: AbortSignal.timeout(timeoutMs)
6558
+ });
6559
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
6560
+ const declared = Number(response.headers.get("content-length") ?? "0");
6561
+ if (declared > maxBytes) throw new Error(`文件超过大小上限(${declared} > ${maxBytes} 字节)`);
6562
+ const body = response.body;
6563
+ if (body === null) throw new Error("响应无 body");
6564
+ const reader = body.getReader();
6565
+ const chunks = [];
6566
+ let total = 0;
6567
+ for (;;) {
6568
+ const { done, value } = await reader.read();
6569
+ if (done) break;
6570
+ if (value === void 0) continue;
6571
+ total += value.byteLength;
6572
+ if (total > maxBytes) {
6573
+ await reader.cancel().catch(() => void 0);
6574
+ throw new Error(`文件超过大小上限(>${maxBytes} 字节)`);
6575
+ }
6576
+ chunks.push(value);
6577
+ }
6578
+ if (total === 0) throw new Error("下载内容为空");
6579
+ const { writeFile } = await import("node:fs/promises");
6580
+ await writeFile(dest, Buffer.concat(chunks));
6581
+ return total;
6582
+ }
6583
+ /** 从 Content-Type / URL 路径推断扩展名(缺省 .bin;下载命名用)。 */
6584
+ function inferExtension(contentType, url) {
6585
+ if (contentType !== null) {
6586
+ const base = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
6587
+ const sub = base.split("/")[1]?.split("+")[0];
6588
+ if (base.startsWith("image/") || base.startsWith("audio/") || base.startsWith("video/")) {
6589
+ if (sub !== void 0 && sub !== "") return `.${sub}`;
6590
+ }
6591
+ }
6592
+ try {
6593
+ const pathname = new URL(url).pathname;
6594
+ const ext = pathname.substring(pathname.lastIndexOf("."));
6595
+ if (ext.length > 1 && ext.length <= 6 && EXT_RE.test(ext)) return ext.toLowerCase();
6596
+ } catch {}
6597
+ return ".bin";
6598
+ }
6599
+ //#endregion
6489
6600
  //#region ../../node_modules/.pnpm/@borewit+text-codec@0.2.2/node_modules/@borewit/text-codec/lib/index.js
6490
6601
  const WINDOWS_1252_EXTRA = {
6491
6602
  128: "€",
@@ -7419,7 +7530,7 @@ var require_ms = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7419
7530
  }
7420
7531
  }));
7421
7532
  //#endregion
7422
- //#region ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js
7533
+ //#region ../../node_modules/.pnpm/debug@4.4.3_supports-color@8.1.1/node_modules/debug/src/common.js
7423
7534
  var require_common = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7424
7535
  /**
7425
7536
  * This is the common logic for both the Node.js and web browser
@@ -7622,7 +7733,7 @@ var require_common = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7622
7733
  module.exports = setup;
7623
7734
  }));
7624
7735
  //#endregion
7625
- //#region ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js
7736
+ //#region ../../node_modules/.pnpm/debug@4.4.3_supports-color@8.1.1/node_modules/debug/src/browser.js
7626
7737
  var require_browser = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7627
7738
  /**
7628
7739
  * This is the web browser implementation of `debug()`.
@@ -7828,19 +7939,21 @@ var require_has_flag = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7828
7939
  };
7829
7940
  }));
7830
7941
  //#endregion
7831
- //#region ../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js
7942
+ //#region ../../node_modules/.pnpm/supports-color@8.1.1/node_modules/supports-color/index.js
7832
7943
  var require_supports_color = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7833
7944
  const os = require("os");
7834
7945
  const tty$1 = require("tty");
7835
7946
  const hasFlag = require_has_flag();
7836
7947
  const { env } = process;
7837
- let forceColor;
7838
- if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) forceColor = 0;
7839
- else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) forceColor = 1;
7840
- if ("FORCE_COLOR" in env) {
7841
- if (env.FORCE_COLOR === "true") forceColor = 1;
7842
- else if (env.FORCE_COLOR === "false") forceColor = 0;
7843
- else forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
7948
+ let flagForceColor;
7949
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) flagForceColor = 0;
7950
+ else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) flagForceColor = 1;
7951
+ function envForceColor() {
7952
+ if ("FORCE_COLOR" in env) {
7953
+ if (env.FORCE_COLOR === "true") return 1;
7954
+ if (env.FORCE_COLOR === "false") return 0;
7955
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
7956
+ }
7844
7957
  }
7845
7958
  function translateLevel(level) {
7846
7959
  if (level === 0) return false;
@@ -7851,10 +7964,15 @@ var require_supports_color = /* @__PURE__ */ __commonJSMin(((exports, module) =>
7851
7964
  has16m: level >= 3
7852
7965
  };
7853
7966
  }
7854
- function supportsColor(haveStream, streamIsTTY) {
7967
+ function supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
7968
+ const noFlagForceColor = envForceColor();
7969
+ if (noFlagForceColor !== void 0) flagForceColor = noFlagForceColor;
7970
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
7855
7971
  if (forceColor === 0) return 0;
7856
- if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) return 3;
7857
- if (hasFlag("color=256")) return 2;
7972
+ if (sniffFlags) {
7973
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) return 3;
7974
+ if (hasFlag("color=256")) return 2;
7975
+ }
7858
7976
  if (haveStream && !streamIsTTY && forceColor === void 0) return 0;
7859
7977
  const min = forceColor || 0;
7860
7978
  if (env.TERM === "dumb") return min;
@@ -7870,14 +7988,15 @@ var require_supports_color = /* @__PURE__ */ __commonJSMin(((exports, module) =>
7870
7988
  "APPVEYOR",
7871
7989
  "GITLAB_CI",
7872
7990
  "GITHUB_ACTIONS",
7873
- "BUILDKITE"
7991
+ "BUILDKITE",
7992
+ "DRONE"
7874
7993
  ].some((sign) => sign in env) || env.CI_NAME === "codeship") return 1;
7875
7994
  return min;
7876
7995
  }
7877
7996
  if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
7878
7997
  if (env.COLORTERM === "truecolor") return 3;
7879
7998
  if ("TERM_PROGRAM" in env) {
7880
- const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
7999
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
7881
8000
  switch (env.TERM_PROGRAM) {
7882
8001
  case "iTerm.app": return version >= 3 ? 3 : 2;
7883
8002
  case "Apple_Terminal": return 2;
@@ -7888,17 +8007,20 @@ var require_supports_color = /* @__PURE__ */ __commonJSMin(((exports, module) =>
7888
8007
  if ("COLORTERM" in env) return 1;
7889
8008
  return min;
7890
8009
  }
7891
- function getSupportLevel(stream) {
7892
- return translateLevel(supportsColor(stream, stream && stream.isTTY));
8010
+ function getSupportLevel(stream, options = {}) {
8011
+ return translateLevel(supportsColor(stream, {
8012
+ streamIsTTY: stream && stream.isTTY,
8013
+ ...options
8014
+ }));
7893
8015
  }
7894
8016
  module.exports = {
7895
8017
  supportsColor: getSupportLevel,
7896
- stdout: translateLevel(supportsColor(true, tty$1.isatty(1))),
7897
- stderr: translateLevel(supportsColor(true, tty$1.isatty(2)))
8018
+ stdout: getSupportLevel({ isTTY: tty$1.isatty(1) }),
8019
+ stderr: getSupportLevel({ isTTY: tty$1.isatty(2) })
7898
8020
  };
7899
8021
  }));
7900
8022
  //#endregion
7901
- //#region ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js
8023
+ //#region ../../node_modules/.pnpm/debug@4.4.3_supports-color@8.1.1/node_modules/debug/src/node.js
7902
8024
  var require_node = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7903
8025
  /**
7904
8026
  * Module dependencies.
@@ -8470,7 +8592,7 @@ function getUintBE(view) {
8470
8592
  if (byteLength === 1) return view.getUint8(0);
8471
8593
  }
8472
8594
  //#endregion
8473
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/tokens.js
8595
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/tokens.js
8474
8596
  function stringToBytes(string, encoding) {
8475
8597
  if (encoding === "utf-16le") {
8476
8598
  const bytes = [];
@@ -8514,7 +8636,7 @@ const uint32SyncSafeToken = {
8514
8636
  len: 4
8515
8637
  };
8516
8638
  //#endregion
8517
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/supported.js
8639
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/supported.js
8518
8640
  const extensions = [
8519
8641
  "jpg",
8520
8642
  "png",
@@ -8881,7 +9003,7 @@ const mimeTypes = [
8881
9003
  "application/vnd.apple.pages"
8882
9004
  ];
8883
9005
  //#endregion
8884
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/parser.js
9006
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/parser.js
8885
9007
  const maximumUntrustedSkipSizeInBytes = 16777216;
8886
9008
  var ParserHardLimitError = class extends Error {};
8887
9009
  function getSafeBound(value, maximum, reason) {
@@ -8917,7 +9039,7 @@ function hasExceededUnknownSizeScanBudget(tokenizer, startOffset, maximumBytes)
8917
9039
  return hasUnknownFileSize(tokenizer) && tokenizer.position - startOffset > maximumBytes;
8918
9040
  }
8919
9041
  //#endregion
8920
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/detectors/zip.js
9042
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/detectors/zip.js
8921
9043
  const maximumZipEntrySizeInBytes = 1048576;
8922
9044
  const maximumZipEntryCount = 1024;
8923
9045
  const maximumZipBufferedReadSizeInBytes = 2 ** 31 - 1;
@@ -8952,11 +9074,13 @@ async function decompressDeflateRawWithLimit(data, { maximumLength = maximumZipE
8952
9074
  if (done) break;
8953
9075
  totalLength += value.length;
8954
9076
  if (totalLength > maximumLength) {
8955
- await reader.cancel();
9077
+ await reader.cancel().catch(() => {});
8956
9078
  throw new Error(`ZIP entry decompressed data exceeds ${maximumLength} bytes`);
8957
9079
  }
8958
9080
  chunks.push(value);
8959
9081
  }
9082
+ } catch (error) {
9083
+ if (error.code !== "ERR_TRAILING_JUNK_AFTER_STREAM_END") throw error;
8960
9084
  } finally {
8961
9085
  reader.releaseLock();
8962
9086
  }
@@ -9349,7 +9473,7 @@ async function detectZip(tokenizer) {
9349
9473
  };
9350
9474
  }
9351
9475
  //#endregion
9352
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/detectors/ebml.js
9476
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/detectors/ebml.js
9353
9477
  const maximumEbmlDocumentTypeSizeInBytes = 64;
9354
9478
  const maximumEbmlElementPayloadSizeInBytes = 1048576;
9355
9479
  const maximumEbmlElementCount = 256;
@@ -9417,7 +9541,7 @@ async function detectEbml(tokenizer) {
9417
9541
  }
9418
9542
  }
9419
9543
  //#endregion
9420
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/detectors/png.js
9544
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/detectors/png.js
9421
9545
  const maximumPngChunkCount = 512;
9422
9546
  const maximumPngStreamScanBudgetInBytes = 16777216;
9423
9547
  const maximumPngChunkSizeInBytes = 1048576;
@@ -9476,7 +9600,7 @@ async function detectPng(tokenizer) {
9476
9600
  return pngFileType;
9477
9601
  }
9478
9602
  //#endregion
9479
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/detectors/asf.js
9603
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/detectors/asf.js
9480
9604
  const maximumAsfHeaderObjectCount = 512;
9481
9605
  const maximumAsfHeaderPayloadSizeInBytes = 1048576;
9482
9606
  async function detectAsf(tokenizer) {
@@ -9603,12 +9727,12 @@ async function detectAsf(tokenizer) {
9603
9727
  };
9604
9728
  }
9605
9729
  //#endregion
9606
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/index.js
9730
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/index.js
9607
9731
  /**
9608
9732
  Primary entry point, Node.js specific entry point is index.js
9609
9733
  */
9610
9734
  const reasonableDetectionSizeInBytes = 4100;
9611
- const maximumMpegOffsetTolerance = 4098;
9735
+ const maximumMpegOffsetTolerance = 4096;
9612
9736
  const maximumNestedGzipDetectionSizeInBytes = maximumUntrustedSkipSizeInBytes;
9613
9737
  const maximumNestedGzipProbeDepth = 1;
9614
9738
  const unknownSizeGzipProbeTimeoutInMilliseconds = 100;
@@ -11201,10 +11325,10 @@ var FileTypeParser = class FileTypeParser {
11201
11325
  mime: "image/x-icon"
11202
11326
  };
11203
11327
  await tokenizer.peekBuffer(this.buffer, {
11204
- length: Math.min(2 + this.options.mpegOffsetTolerance, fileSize),
11328
+ length: Math.min(4 + this.options.mpegOffsetTolerance, fileSize),
11205
11329
  mayBeLess: true
11206
11330
  });
11207
- if (this.buffer.length >= 2 + this.options.mpegOffsetTolerance) for (let depth = 0; depth <= this.options.mpegOffsetTolerance; ++depth) {
11331
+ if (this.buffer.length >= 4 + this.options.mpegOffsetTolerance) for (let depth = 0; depth <= this.options.mpegOffsetTolerance; ++depth) {
11208
11332
  const type = this.scanMpeg(depth);
11209
11333
  if (type) return type;
11210
11334
  }
@@ -11290,19 +11414,23 @@ var FileTypeParser = class FileTypeParser {
11290
11414
  if (this.check([16], {
11291
11415
  offset: offset + 1,
11292
11416
  mask: [22]
11293
- })) {
11294
- if (this.check([8], {
11295
- offset: offset + 1,
11296
- mask: [8]
11297
- })) return {
11298
- ext: "aac",
11299
- mime: "audio/aac"
11300
- };
11301
- return {
11302
- ext: "aac",
11303
- mime: "audio/aac"
11304
- };
11305
- }
11417
+ })) return {
11418
+ ext: "aac",
11419
+ mime: "audio/aac"
11420
+ };
11421
+ if (this.check([255, 254], { offset })) return;
11422
+ if (this.check([8], {
11423
+ offset: offset + 1,
11424
+ mask: [24]
11425
+ })) return;
11426
+ if (this.check([240], {
11427
+ offset: offset + 2,
11428
+ mask: [240]
11429
+ })) return;
11430
+ if (this.check([12], {
11431
+ offset: offset + 2,
11432
+ mask: [12]
11433
+ })) return;
11306
11434
  if (this.check([2], {
11307
11435
  offset: offset + 1,
11308
11436
  mask: [6]
@@ -11366,6 +11494,7 @@ async function detectFileType(input) {
11366
11494
  * ffmpeg 由 execa 以子进程方式调用(非 node 内置),依赖系统 PATH 中的 ffmpeg。
11367
11495
  * - `transcodeVideo`:转码 / 缩放 / 帧率
11368
11496
  * - `getVideoInfo`:解析 ffprobe 输出取宽高与时长
11497
+ * - `extractVideoFrame`:抽首帧作缩略图(QQ 视频消息发送需要)
11369
11498
  */
11370
11499
  const MS_PER_SECOND = 1e3;
11371
11500
  /** 替换扩展名(保持目录,父目录由调用方保证存在)。 */
@@ -11388,7 +11517,7 @@ function replaceExt(input, ext) {
11388
11517
  else stem = base;
11389
11518
  return `${dir}${stem}${ext}`;
11390
11519
  }
11391
- /** 转码:按选项输出到替换扩展名后的路径(.mp4)。 */
11520
+ /** 转码:按选项输出到替换扩展名后的路径(.mp4)。ffmpeg 缺失/失败抛 MediaError。 */
11392
11521
  async function transcodeVideo(input, opts = {}) {
11393
11522
  const args = [
11394
11523
  "-y",
@@ -11401,11 +11530,13 @@ async function transcodeVideo(input, opts = {}) {
11401
11530
  if (opts.fps !== void 0) args.push("-r", String(opts.fps));
11402
11531
  const output = replaceExt(input, ".mp4");
11403
11532
  args.push("-c:v", "libx264", "-preset", "fast", output);
11533
+ let exitCode;
11404
11534
  try {
11405
- await execa("ffmpeg", args, { reject: false });
11535
+ exitCode = (await execa("ffmpeg", args, { reject: false })).exitCode;
11406
11536
  } catch (err) {
11407
- throw new MediaError(`ffmpeg 转码失败: ${input}`, { cause: err });
11537
+ throw new MediaError(`ffmpeg 不可用或转码失败: ${input}`, { cause: err });
11408
11538
  }
11539
+ if (exitCode !== 0 || !(0, node_fs.existsSync)(output)) throw new MediaError(`ffmpeg 转码失败: ${input}(exit ${exitCode ?? "?"})`);
11409
11540
  return output;
11410
11541
  }
11411
11542
  /** 读取视频宽高与时长(ffprobe JSON 输出解析)。 */
@@ -11438,13 +11569,48 @@ async function getVideoInfo(input) {
11438
11569
  durationMs: Math.round(Number(durationStr) * MS_PER_SECOND)
11439
11570
  };
11440
11571
  }
11572
+ /**
11573
+ * 抽视频首帧为 PNG 缩略图(QQ 视频消息发送契约:thumbPath 指向真实图片文件)。
11574
+ *
11575
+ * 固定 `-ss 0` 取首帧:QQ 缩略图只需要一张可解码的封面,首帧最稳定
11576
+ * (部分视频首帧为黑屏时可改 1s,此处不引入额外配置)。转码失败 / ffmpeg
11577
+ * 缺失 / 输出未生成均抛 MediaError,由调用方决定降级策略。
11578
+ */
11579
+ async function extractVideoFrame(input, outputPath) {
11580
+ const args = [
11581
+ "-y",
11582
+ "-ss",
11583
+ "0",
11584
+ "-i",
11585
+ input,
11586
+ "-frames:v",
11587
+ "1",
11588
+ "-q:v",
11589
+ "3",
11590
+ "-f",
11591
+ "image2",
11592
+ outputPath
11593
+ ];
11594
+ let exitCode;
11595
+ try {
11596
+ exitCode = (await execa("ffmpeg", args, { reject: false })).exitCode;
11597
+ } catch (err) {
11598
+ throw new MediaError(`ffmpeg 不可用或抽帧失败: ${input}`, { cause: err });
11599
+ }
11600
+ if (exitCode !== 0 || !(0, node_fs.existsSync)(outputPath)) throw new MediaError(`ffmpeg 抽帧失败: ${input}(exit ${exitCode ?? "?"})`);
11601
+ return outputPath;
11602
+ }
11441
11603
  //#endregion
11442
11604
  exports.MediaError = MediaError;
11443
11605
  exports.SILK_SAMPLE_RATE = SILK_SAMPLE_RATE;
11444
11606
  exports.decodeSilkToPcm = decodeSilkToPcm;
11607
+ exports.decodeSilkToWav = decodeSilkToWav;
11445
11608
  exports.detectFileType = detectFileType;
11609
+ exports.downloadUrl = downloadUrl;
11446
11610
  exports.encodePcmToSilk = encodePcmToSilk;
11611
+ exports.extractVideoFrame = extractVideoFrame;
11447
11612
  exports.getImageSize = getImageSize;
11448
11613
  exports.getSilkInfo = getSilkInfo;
11449
11614
  exports.getVideoInfo = getVideoInfo;
11615
+ exports.inferExtension = inferExtension;
11450
11616
  exports.transcodeVideo = transcodeVideo;
package/dist/index.d.cts CHANGED
@@ -53,6 +53,24 @@ declare class MediaError extends Error {
53
53
  declare const SILK_SAMPLE_RATE = 24000;
54
54
  /** 解码 SILK 音频为 PCM(pcm_s16le)。 */
55
55
  declare function decodeSilkToPcm(input: string, sampleRate?: number): Promise<DecodedAudio>;
56
+ /** 解码 SILK → WAV 输出选项。 */
57
+ interface DecodeSilkToWavOptions {
58
+ /** 采样率(缺省 24000,QQ 语音协议值)。 */
59
+ sampleRate?: number;
60
+ /** 输出目录(缺省输入同目录;收方向解码建议 tmpdir,避免污染 NT 数据目录)。 */
61
+ outDir?: string;
62
+ }
63
+ /** 解码结果(WAV)。 */
64
+ interface DecodedWav {
65
+ wavPath: string;
66
+ durationMs: number;
67
+ }
68
+ /**
69
+ * 解码 SILK → WAV 文件(pcm_s16le 单声道 + 44 字节头,通用可播放格式)。
70
+ * 收方向语音接线用(koishi h.audio / 外部客户端):QQ 语音是 silk v3,
71
+ * 多数播放器无法直接解码,落 WAV 后以本地路径消费。
72
+ */
73
+ declare function decodeSilkToWav(input: string, options?: DecodeSilkToWavOptions): Promise<DecodedWav>;
56
74
  /**
57
75
  * 编码任意音频为 SILK 文件(返回输出路径,输出紧随输入文件)。
58
76
  *
@@ -65,6 +83,30 @@ declare function encodePcmToSilk(input: string, sampleRate?: number): Promise<st
65
83
  /** 获取 SILK 音频信息(时长 / 采样率)。 */
66
84
  declare function getSilkInfo(input: string, sampleRate?: number): Promise<AudioInfo>;
67
85
  //#endregion
86
+ //#region src/downloader.d.ts
87
+ /**
88
+ * downloader.ts:HTTP(S) 媒体下载(2026-09-08 T5)
89
+ *
90
+ * 协议层(adapter get_image 主动下载 / koishi 插件发送侧下沉)共用的
91
+ * 最小下载原语:fetch + 大小上限 + 超时,写目标路径(调用方管理目录与清理)。
92
+ * 零额外依赖(Node 18+ 内建 fetch)。
93
+ */
94
+ /** 下载选项。 */
95
+ interface DownloadUrlOptions {
96
+ /** 超时毫秒(缺省 15s)。 */
97
+ timeoutMs?: number;
98
+ /** 大小上限字节(缺省 30MB)。 */
99
+ maxBytes?: number;
100
+ }
101
+ /**
102
+ * 下载 URL 到目标路径(覆盖写)。返回写入字节数。
103
+ * 失败抛错(非 2xx / 超限 / 超时 / 空 body / IO 错误),不产生半成品语义
104
+ * (失败时目标文件可能残留,调用方负责清理目录)。
105
+ */
106
+ declare function downloadUrl(url: string, dest: string, options?: DownloadUrlOptions): Promise<number>;
107
+ /** 从 Content-Type / URL 路径推断扩展名(缺省 .bin;下载命名用)。 */
108
+ declare function inferExtension(contentType: string | null, url: string): string;
109
+ //#endregion
68
110
  //#region src/image.d.ts
69
111
  /** 读取图片尺寸(image-size 同步 API,内部读文件 + 计算)。 */
70
112
  declare function getImageSize(input: string): Promise<ImageSize>;
@@ -72,10 +114,18 @@ declare function getImageSize(input: string): Promise<ImageSize>;
72
114
  declare function detectFileType(input: string): Promise<FileTypeResult>;
73
115
  //#endregion
74
116
  //#region src/video.d.ts
75
- /** 转码:按选项输出到替换扩展名后的路径(.mp4)。 */
117
+ /** 转码:按选项输出到替换扩展名后的路径(.mp4)。ffmpeg 缺失/失败抛 MediaError。 */
76
118
  declare function transcodeVideo(input: string, opts?: TranscodeOptions): Promise<string>;
77
119
  /** 读取视频宽高与时长(ffprobe JSON 输出解析)。 */
78
120
  declare function getVideoInfo(input: string): Promise<VideoInfo>;
121
+ /**
122
+ * 抽视频首帧为 PNG 缩略图(QQ 视频消息发送契约:thumbPath 指向真实图片文件)。
123
+ *
124
+ * 固定 `-ss 0` 取首帧:QQ 缩略图只需要一张可解码的封面,首帧最稳定
125
+ * (部分视频首帧为黑屏时可改 1s,此处不引入额外配置)。转码失败 / ffmpeg
126
+ * 缺失 / 输出未生成均抛 MediaError,由调用方决定降级策略。
127
+ */
128
+ declare function extractVideoFrame(input: string, outputPath: string): Promise<string>;
79
129
  //#endregion
80
- export { type AudioInfo, type DecodedAudio, type FileTypeResult, type ImageSize, MediaError, SILK_SAMPLE_RATE, type TranscodeOptions, type VideoInfo, decodeSilkToPcm, detectFileType, encodePcmToSilk, getImageSize, getSilkInfo, getVideoInfo, transcodeVideo };
130
+ export { type AudioInfo, type DecodeSilkToWavOptions, type DecodedAudio, type DecodedWav, type DownloadUrlOptions, type FileTypeResult, type ImageSize, MediaError, SILK_SAMPLE_RATE, type TranscodeOptions, type VideoInfo, decodeSilkToPcm, decodeSilkToWav, detectFileType, downloadUrl, encodePcmToSilk, extractVideoFrame, getImageSize, getSilkInfo, getVideoInfo, inferExtension, transcodeVideo };
81
131
  //# sourceMappingURL=index.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../src/types.ts","../src/audio.ts","../src/image.ts","../src/video.ts"],"mappings":";;;;;;;UAOiB;EACb;EACA;;;UAIa;;EAEb;;EAEA;;;UAIa;;EAEb;;EAEA;;;UAIa;EACb;EACA;;EAEA;;;UAIa;EACb;EACA;EACA;;;UAIa;;EAEb;;EAEA;;;cAIS,mBAAmB;EAC5B,YAAY,iBAAiB,UAAU;;;;;cChC9B;;iBAmBS,gBAClB,eACA,sBACD,QAAQ;;;;;;;;;iBAmBW,gBAAgB,eAAe,sBAAiB;;iBAuEhD,YAClB,eACA,sBACD,QAAQ;;;;iBC3HW,aAAa,gBAAgB,QAAQ;;iBAOrC,eAAe,gBAAgB,QAAQ;;;;iBCwBvC,eAAe,eAAe,OAAM,mBAAwB;;iBAwB5D,aAAa,gBAAgB,QAAQ"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/types.ts","../src/audio.ts","../src/downloader.ts","../src/image.ts","../src/video.ts"],"mappings":";;;;;;;UAOiB;EACb;EACA;;;UAIa;;EAEb;;EAEA;;;UAIa;;EAEb;;EAEA;;;UAIa;EACb;EACA;;EAEA;;;UAIa;EACb;EACA;EACA;;;UAIa;;EAEb;;EAEA;;;cAIS,mBAAmB;EAC5B,YAAY,iBAAiB,UAAU;;;;;cChC9B;;iBAmBS,gBAClB,eACA,sBACD,QAAQ;;UAYM;;EAEb;;EAEA;;;UAIa;EACb;EACA;;;;;;;iBAQkB,gBAClB,eACA,UAAS,yBACV,QAAQ;;;;;;;;;iBAqDW,gBAAgB,eAAe,sBAAiB;;iBAuEhD,YAClB,eACA,sBACD,QAAQ;;;;;;;;;;;UClMM;;EAEb;;EAEA;;;;;;;iBAiBkB,YAClB,aACA,cACA,UAAS,qBACV;;iBA6Ca,eAAe,4BAA4B;;;;iBClErC,aAAa,gBAAgB,QAAQ;;iBAOrC,eAAe,gBAAgB,QAAQ;;;;iBC0BvC,eAAe,eAAe,OAAM,mBAAwB;;iBA+B5D,aAAa,gBAAgB,QAAQ;;;;;;;;iBAoCrC,kBAAkB,eAAe,qBAAqB"}
package/dist/index.d.mts CHANGED
@@ -53,6 +53,24 @@ declare class MediaError extends Error {
53
53
  declare const SILK_SAMPLE_RATE = 24000;
54
54
  /** 解码 SILK 音频为 PCM(pcm_s16le)。 */
55
55
  declare function decodeSilkToPcm(input: string, sampleRate?: number): Promise<DecodedAudio>;
56
+ /** 解码 SILK → WAV 输出选项。 */
57
+ interface DecodeSilkToWavOptions {
58
+ /** 采样率(缺省 24000,QQ 语音协议值)。 */
59
+ sampleRate?: number;
60
+ /** 输出目录(缺省输入同目录;收方向解码建议 tmpdir,避免污染 NT 数据目录)。 */
61
+ outDir?: string;
62
+ }
63
+ /** 解码结果(WAV)。 */
64
+ interface DecodedWav {
65
+ wavPath: string;
66
+ durationMs: number;
67
+ }
68
+ /**
69
+ * 解码 SILK → WAV 文件(pcm_s16le 单声道 + 44 字节头,通用可播放格式)。
70
+ * 收方向语音接线用(koishi h.audio / 外部客户端):QQ 语音是 silk v3,
71
+ * 多数播放器无法直接解码,落 WAV 后以本地路径消费。
72
+ */
73
+ declare function decodeSilkToWav(input: string, options?: DecodeSilkToWavOptions): Promise<DecodedWav>;
56
74
  /**
57
75
  * 编码任意音频为 SILK 文件(返回输出路径,输出紧随输入文件)。
58
76
  *
@@ -65,6 +83,30 @@ declare function encodePcmToSilk(input: string, sampleRate?: number): Promise<st
65
83
  /** 获取 SILK 音频信息(时长 / 采样率)。 */
66
84
  declare function getSilkInfo(input: string, sampleRate?: number): Promise<AudioInfo>;
67
85
  //#endregion
86
+ //#region src/downloader.d.ts
87
+ /**
88
+ * downloader.ts:HTTP(S) 媒体下载(2026-09-08 T5)
89
+ *
90
+ * 协议层(adapter get_image 主动下载 / koishi 插件发送侧下沉)共用的
91
+ * 最小下载原语:fetch + 大小上限 + 超时,写目标路径(调用方管理目录与清理)。
92
+ * 零额外依赖(Node 18+ 内建 fetch)。
93
+ */
94
+ /** 下载选项。 */
95
+ interface DownloadUrlOptions {
96
+ /** 超时毫秒(缺省 15s)。 */
97
+ timeoutMs?: number;
98
+ /** 大小上限字节(缺省 30MB)。 */
99
+ maxBytes?: number;
100
+ }
101
+ /**
102
+ * 下载 URL 到目标路径(覆盖写)。返回写入字节数。
103
+ * 失败抛错(非 2xx / 超限 / 超时 / 空 body / IO 错误),不产生半成品语义
104
+ * (失败时目标文件可能残留,调用方负责清理目录)。
105
+ */
106
+ declare function downloadUrl(url: string, dest: string, options?: DownloadUrlOptions): Promise<number>;
107
+ /** 从 Content-Type / URL 路径推断扩展名(缺省 .bin;下载命名用)。 */
108
+ declare function inferExtension(contentType: string | null, url: string): string;
109
+ //#endregion
68
110
  //#region src/image.d.ts
69
111
  /** 读取图片尺寸(image-size 同步 API,内部读文件 + 计算)。 */
70
112
  declare function getImageSize(input: string): Promise<ImageSize>;
@@ -72,10 +114,18 @@ declare function getImageSize(input: string): Promise<ImageSize>;
72
114
  declare function detectFileType(input: string): Promise<FileTypeResult>;
73
115
  //#endregion
74
116
  //#region src/video.d.ts
75
- /** 转码:按选项输出到替换扩展名后的路径(.mp4)。 */
117
+ /** 转码:按选项输出到替换扩展名后的路径(.mp4)。ffmpeg 缺失/失败抛 MediaError。 */
76
118
  declare function transcodeVideo(input: string, opts?: TranscodeOptions): Promise<string>;
77
119
  /** 读取视频宽高与时长(ffprobe JSON 输出解析)。 */
78
120
  declare function getVideoInfo(input: string): Promise<VideoInfo>;
121
+ /**
122
+ * 抽视频首帧为 PNG 缩略图(QQ 视频消息发送契约:thumbPath 指向真实图片文件)。
123
+ *
124
+ * 固定 `-ss 0` 取首帧:QQ 缩略图只需要一张可解码的封面,首帧最稳定
125
+ * (部分视频首帧为黑屏时可改 1s,此处不引入额外配置)。转码失败 / ffmpeg
126
+ * 缺失 / 输出未生成均抛 MediaError,由调用方决定降级策略。
127
+ */
128
+ declare function extractVideoFrame(input: string, outputPath: string): Promise<string>;
79
129
  //#endregion
80
- export { type AudioInfo, type DecodedAudio, type FileTypeResult, type ImageSize, MediaError, SILK_SAMPLE_RATE, type TranscodeOptions, type VideoInfo, decodeSilkToPcm, detectFileType, encodePcmToSilk, getImageSize, getSilkInfo, getVideoInfo, transcodeVideo };
130
+ export { type AudioInfo, type DecodeSilkToWavOptions, type DecodedAudio, type DecodedWav, type DownloadUrlOptions, type FileTypeResult, type ImageSize, MediaError, SILK_SAMPLE_RATE, type TranscodeOptions, type VideoInfo, decodeSilkToPcm, decodeSilkToWav, detectFileType, downloadUrl, encodePcmToSilk, extractVideoFrame, getImageSize, getSilkInfo, getVideoInfo, inferExtension, transcodeVideo };
81
131
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/audio.ts","../src/image.ts","../src/video.ts"],"mappings":";;;;;;;UAOiB;EACb;EACA;;;UAIa;;EAEb;;EAEA;;;UAIa;;EAEb;;EAEA;;;UAIa;EACb;EACA;;EAEA;;;UAIa;EACb;EACA;EACA;;;UAIa;;EAEb;;EAEA;;;cAIS,mBAAmB;EAC5B,YAAY,iBAAiB,UAAU;;;;;cChC9B;;iBAmBS,gBAClB,eACA,sBACD,QAAQ;;;;;;;;;iBAmBW,gBAAgB,eAAe,sBAAiB;;iBAuEhD,YAClB,eACA,sBACD,QAAQ;;;;iBC3HW,aAAa,gBAAgB,QAAQ;;iBAOrC,eAAe,gBAAgB,QAAQ;;;;iBCwBvC,eAAe,eAAe,OAAM,mBAAwB;;iBAwB5D,aAAa,gBAAgB,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/audio.ts","../src/downloader.ts","../src/image.ts","../src/video.ts"],"mappings":";;;;;;;UAOiB;EACb;EACA;;;UAIa;;EAEb;;EAEA;;;UAIa;;EAEb;;EAEA;;;UAIa;EACb;EACA;;EAEA;;;UAIa;EACb;EACA;EACA;;;UAIa;;EAEb;;EAEA;;;cAIS,mBAAmB;EAC5B,YAAY,iBAAiB,UAAU;;;;;cChC9B;;iBAmBS,gBAClB,eACA,sBACD,QAAQ;;UAYM;;EAEb;;EAEA;;;UAIa;EACb;EACA;;;;;;;iBAQkB,gBAClB,eACA,UAAS,yBACV,QAAQ;;;;;;;;;iBAqDW,gBAAgB,eAAe,sBAAiB;;iBAuEhD,YAClB,eACA,sBACD,QAAQ;;;;;;;;;;;UClMM;;EAEb;;EAEA;;;;;;;iBAiBkB,YAClB,aACA,cACA,UAAS,qBACV;;iBA6Ca,eAAe,4BAA4B;;;;iBClErC,aAAa,gBAAgB,QAAQ;;iBAOrC,eAAe,gBAAgB,QAAQ;;;;iBC0BvC,eAAe,eAAe,OAAM,mBAAwB;;iBA+B5D,aAAa,gBAAgB,QAAQ;;;;;;;;iBAoCrC,kBAAkB,eAAe,qBAAqB"}