@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.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { randomBytes } from "node:crypto";
3
- import fs, { appendFileSync, closeSync, createReadStream, createWriteStream, mkdirSync, openSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
3
+ import fs, { appendFileSync, closeSync, createReadStream, createWriteStream, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
4
4
  import { readFile, rm, writeFile } from "node:fs/promises";
5
5
  import path, { dirname, join } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
@@ -2804,7 +2804,7 @@ function parseMilliseconds(milliseconds) {
2804
2804
  throw new TypeError("Expected a finite number or bigint");
2805
2805
  }
2806
2806
  //#endregion
2807
- //#region ../../node_modules/.pnpm/pretty-ms@9.3.0/node_modules/pretty-ms/index.js
2807
+ //#region ../../node_modules/.pnpm/pretty-ms@9.3.1/node_modules/pretty-ms/index.js
2808
2808
  const isZero = (value) => value === 0 || value === 0n;
2809
2809
  const pluralize = (word, count) => count === 1 || count === 1n ? word : `${word}s`;
2810
2810
  const SECOND_ROUNDING_EPSILON = 1e-7;
@@ -2867,7 +2867,9 @@ function prettyMilliseconds(milliseconds, options) {
2867
2867
  } else {
2868
2868
  const millisecondsAndBelow = milliseconds + microseconds / 1e3 + nanoseconds / 1e6;
2869
2869
  const millisecondsDecimalDigits = typeof options.millisecondsDecimalDigits === "number" ? options.millisecondsDecimalDigits : 0;
2870
- const millisecondsString = millisecondsDecimalDigits ? millisecondsAndBelow.toFixed(millisecondsDecimalDigits) : millisecondsAndBelow >= 1 ? Math.round(millisecondsAndBelow) : Math.ceil(millisecondsAndBelow);
2870
+ const roundedMilliseconds = millisecondsAndBelow >= 1 ? Math.round(millisecondsAndBelow) : Math.ceil(millisecondsAndBelow);
2871
+ const maximumMilliseconds = 1e3 - 10 ** -millisecondsDecimalDigits;
2872
+ const millisecondsString = millisecondsDecimalDigits ? Math.min(millisecondsAndBelow, maximumMilliseconds).toFixed(millisecondsDecimalDigits) : Math.min(roundedMilliseconds, maximumMilliseconds);
2871
2873
  add(Number.parseFloat(millisecondsString), "millisecond", "ms", millisecondsString);
2872
2874
  }
2873
2875
  } else {
@@ -6423,6 +6425,55 @@ async function decodeSilkToPcm(input, sampleRate = SILK_SAMPLE_RATE) {
6423
6425
  };
6424
6426
  }
6425
6427
  /**
6428
+ * 解码 SILK → WAV 文件(pcm_s16le 单声道 + 44 字节头,通用可播放格式)。
6429
+ * 收方向语音接线用(koishi h.audio / 外部客户端):QQ 语音是 silk v3,
6430
+ * 多数播放器无法直接解码,落 WAV 后以本地路径消费。
6431
+ */
6432
+ async function decodeSilkToWav(input, options = {}) {
6433
+ const sampleRate = options.sampleRate ?? 24e3;
6434
+ const buffer = await readFile(input);
6435
+ if (!isSilk(buffer)) throw new MediaError(`不是有效的 SILK 文件: ${input}`);
6436
+ const result = await decode(buffer, sampleRate);
6437
+ const { dir, name } = outputTarget(input, ".wav", options.outDir);
6438
+ const wav = wrapPcmInWav(result.data, sampleRate);
6439
+ await writeFile(join(dir, name), wav);
6440
+ return {
6441
+ wavPath: join(dir, name),
6442
+ durationMs: result.duration
6443
+ };
6444
+ }
6445
+ /** 输出目标(目录 + 文件名;outDir 优先,否则输入同目录替换扩展名)。 */
6446
+ function outputTarget(input, ext, outDir) {
6447
+ const base = input.replaceAll("\\", "/").split("/").pop() ?? "audio";
6448
+ const dot = base.lastIndexOf(".");
6449
+ const name = `${dot > 0 ? base.slice(0, dot) : base}${ext}`;
6450
+ const dir = outDir !== void 0 ? outDir : dirname(input);
6451
+ mkdirSync(dir, { recursive: true });
6452
+ return {
6453
+ dir,
6454
+ name
6455
+ };
6456
+ }
6457
+ /** PCM(s16le 单声道)→ WAV 文件字节(44 字节头 + 数据)。 */
6458
+ function wrapPcmInWav(pcm, sampleRate) {
6459
+ const blockAlign = 2;
6460
+ const header = Buffer.alloc(44);
6461
+ header.write("RIFF", 0, "ascii");
6462
+ header.writeUInt32LE(36 + pcm.byteLength, 4);
6463
+ header.write("WAVE", 8, "ascii");
6464
+ header.write("fmt ", 12, "ascii");
6465
+ header.writeUInt32LE(16, 16);
6466
+ header.writeUInt16LE(1, 20);
6467
+ header.writeUInt16LE(1, 22);
6468
+ header.writeUInt32LE(sampleRate, 24);
6469
+ header.writeUInt32LE(sampleRate * blockAlign | 0, 28);
6470
+ header.writeUInt16LE(blockAlign, 32);
6471
+ header.writeUInt16LE(16, 34);
6472
+ header.write("data", 36, "ascii");
6473
+ header.writeUInt32LE(pcm.byteLength, 40);
6474
+ return Buffer.concat([header, Buffer.from(pcm)]);
6475
+ }
6476
+ /**
6426
6477
  * 编码任意音频为 SILK 文件(返回输出路径,输出紧随输入文件)。
6427
6478
  *
6428
6479
  * - 已是 SILK → 原样返回
@@ -6481,6 +6532,66 @@ async function getSilkInfo(input, sampleRate = SILK_SAMPLE_RATE) {
6481
6532
  };
6482
6533
  }
6483
6534
  //#endregion
6535
+ //#region src/downloader.ts
6536
+ /** 默认大小上限(30MB)。 */
6537
+ const DEFAULT_MAX_BYTES = 31457280;
6538
+ /** 默认超时(15s)。 */
6539
+ const DEFAULT_TIMEOUT_MS = 15e3;
6540
+ /** 扩展名字符合法性(URL pathname 提取校验)。 */
6541
+ const EXT_RE = /^\.[a-z0-9]+$/i;
6542
+ /**
6543
+ * 下载 URL 到目标路径(覆盖写)。返回写入字节数。
6544
+ * 失败抛错(非 2xx / 超限 / 超时 / 空 body / IO 错误),不产生半成品语义
6545
+ * (失败时目标文件可能残留,调用方负责清理目录)。
6546
+ */
6547
+ async function downloadUrl(url, dest, options = {}) {
6548
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
6549
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
6550
+ const response = await fetch(url, {
6551
+ redirect: "follow",
6552
+ signal: AbortSignal.timeout(timeoutMs)
6553
+ });
6554
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
6555
+ const declared = Number(response.headers.get("content-length") ?? "0");
6556
+ if (declared > maxBytes) throw new Error(`文件超过大小上限(${declared} > ${maxBytes} 字节)`);
6557
+ const body = response.body;
6558
+ if (body === null) throw new Error("响应无 body");
6559
+ const reader = body.getReader();
6560
+ const chunks = [];
6561
+ let total = 0;
6562
+ for (;;) {
6563
+ const { done, value } = await reader.read();
6564
+ if (done) break;
6565
+ if (value === void 0) continue;
6566
+ total += value.byteLength;
6567
+ if (total > maxBytes) {
6568
+ await reader.cancel().catch(() => void 0);
6569
+ throw new Error(`文件超过大小上限(>${maxBytes} 字节)`);
6570
+ }
6571
+ chunks.push(value);
6572
+ }
6573
+ if (total === 0) throw new Error("下载内容为空");
6574
+ const { writeFile } = await import("node:fs/promises");
6575
+ await writeFile(dest, Buffer.concat(chunks));
6576
+ return total;
6577
+ }
6578
+ /** 从 Content-Type / URL 路径推断扩展名(缺省 .bin;下载命名用)。 */
6579
+ function inferExtension(contentType, url) {
6580
+ if (contentType !== null) {
6581
+ const base = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
6582
+ const sub = base.split("/")[1]?.split("+")[0];
6583
+ if (base.startsWith("image/") || base.startsWith("audio/") || base.startsWith("video/")) {
6584
+ if (sub !== void 0 && sub !== "") return `.${sub}`;
6585
+ }
6586
+ }
6587
+ try {
6588
+ const pathname = new URL(url).pathname;
6589
+ const ext = pathname.substring(pathname.lastIndexOf("."));
6590
+ if (ext.length > 1 && ext.length <= 6 && EXT_RE.test(ext)) return ext.toLowerCase();
6591
+ } catch {}
6592
+ return ".bin";
6593
+ }
6594
+ //#endregion
6484
6595
  //#region ../../node_modules/.pnpm/@borewit+text-codec@0.2.2/node_modules/@borewit/text-codec/lib/index.js
6485
6596
  const WINDOWS_1252_EXTRA = {
6486
6597
  128: "€",
@@ -7414,7 +7525,7 @@ var require_ms = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7414
7525
  }
7415
7526
  }));
7416
7527
  //#endregion
7417
- //#region ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js
7528
+ //#region ../../node_modules/.pnpm/debug@4.4.3_supports-color@8.1.1/node_modules/debug/src/common.js
7418
7529
  var require_common = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7419
7530
  /**
7420
7531
  * This is the common logic for both the Node.js and web browser
@@ -7617,7 +7728,7 @@ var require_common = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7617
7728
  module.exports = setup;
7618
7729
  }));
7619
7730
  //#endregion
7620
- //#region ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js
7731
+ //#region ../../node_modules/.pnpm/debug@4.4.3_supports-color@8.1.1/node_modules/debug/src/browser.js
7621
7732
  var require_browser = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7622
7733
  /**
7623
7734
  * This is the web browser implementation of `debug()`.
@@ -7823,19 +7934,21 @@ var require_has_flag = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7823
7934
  };
7824
7935
  }));
7825
7936
  //#endregion
7826
- //#region ../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js
7937
+ //#region ../../node_modules/.pnpm/supports-color@8.1.1/node_modules/supports-color/index.js
7827
7938
  var require_supports_color = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7828
7939
  const os = __require("os");
7829
7940
  const tty$2 = __require("tty");
7830
7941
  const hasFlag = require_has_flag();
7831
7942
  const { env } = process;
7832
- let forceColor;
7833
- if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) forceColor = 0;
7834
- else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) forceColor = 1;
7835
- if ("FORCE_COLOR" in env) {
7836
- if (env.FORCE_COLOR === "true") forceColor = 1;
7837
- else if (env.FORCE_COLOR === "false") forceColor = 0;
7838
- else forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
7943
+ let flagForceColor;
7944
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) flagForceColor = 0;
7945
+ else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) flagForceColor = 1;
7946
+ function envForceColor() {
7947
+ if ("FORCE_COLOR" in env) {
7948
+ if (env.FORCE_COLOR === "true") return 1;
7949
+ if (env.FORCE_COLOR === "false") return 0;
7950
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
7951
+ }
7839
7952
  }
7840
7953
  function translateLevel(level) {
7841
7954
  if (level === 0) return false;
@@ -7846,10 +7959,15 @@ var require_supports_color = /* @__PURE__ */ __commonJSMin(((exports, module) =>
7846
7959
  has16m: level >= 3
7847
7960
  };
7848
7961
  }
7849
- function supportsColor(haveStream, streamIsTTY) {
7962
+ function supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
7963
+ const noFlagForceColor = envForceColor();
7964
+ if (noFlagForceColor !== void 0) flagForceColor = noFlagForceColor;
7965
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
7850
7966
  if (forceColor === 0) return 0;
7851
- if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) return 3;
7852
- if (hasFlag("color=256")) return 2;
7967
+ if (sniffFlags) {
7968
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) return 3;
7969
+ if (hasFlag("color=256")) return 2;
7970
+ }
7853
7971
  if (haveStream && !streamIsTTY && forceColor === void 0) return 0;
7854
7972
  const min = forceColor || 0;
7855
7973
  if (env.TERM === "dumb") return min;
@@ -7865,14 +7983,15 @@ var require_supports_color = /* @__PURE__ */ __commonJSMin(((exports, module) =>
7865
7983
  "APPVEYOR",
7866
7984
  "GITLAB_CI",
7867
7985
  "GITHUB_ACTIONS",
7868
- "BUILDKITE"
7986
+ "BUILDKITE",
7987
+ "DRONE"
7869
7988
  ].some((sign) => sign in env) || env.CI_NAME === "codeship") return 1;
7870
7989
  return min;
7871
7990
  }
7872
7991
  if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
7873
7992
  if (env.COLORTERM === "truecolor") return 3;
7874
7993
  if ("TERM_PROGRAM" in env) {
7875
- const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
7994
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
7876
7995
  switch (env.TERM_PROGRAM) {
7877
7996
  case "iTerm.app": return version >= 3 ? 3 : 2;
7878
7997
  case "Apple_Terminal": return 2;
@@ -7883,17 +8002,20 @@ var require_supports_color = /* @__PURE__ */ __commonJSMin(((exports, module) =>
7883
8002
  if ("COLORTERM" in env) return 1;
7884
8003
  return min;
7885
8004
  }
7886
- function getSupportLevel(stream) {
7887
- return translateLevel(supportsColor(stream, stream && stream.isTTY));
8005
+ function getSupportLevel(stream, options = {}) {
8006
+ return translateLevel(supportsColor(stream, {
8007
+ streamIsTTY: stream && stream.isTTY,
8008
+ ...options
8009
+ }));
7888
8010
  }
7889
8011
  module.exports = {
7890
8012
  supportsColor: getSupportLevel,
7891
- stdout: translateLevel(supportsColor(true, tty$2.isatty(1))),
7892
- stderr: translateLevel(supportsColor(true, tty$2.isatty(2)))
8013
+ stdout: getSupportLevel({ isTTY: tty$2.isatty(1) }),
8014
+ stderr: getSupportLevel({ isTTY: tty$2.isatty(2) })
7893
8015
  };
7894
8016
  }));
7895
8017
  //#endregion
7896
- //#region ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js
8018
+ //#region ../../node_modules/.pnpm/debug@4.4.3_supports-color@8.1.1/node_modules/debug/src/node.js
7897
8019
  var require_node = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7898
8020
  /**
7899
8021
  * Module dependencies.
@@ -8465,7 +8587,7 @@ function getUintBE(view) {
8465
8587
  if (byteLength === 1) return view.getUint8(0);
8466
8588
  }
8467
8589
  //#endregion
8468
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/tokens.js
8590
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/tokens.js
8469
8591
  function stringToBytes(string, encoding) {
8470
8592
  if (encoding === "utf-16le") {
8471
8593
  const bytes = [];
@@ -8509,7 +8631,7 @@ const uint32SyncSafeToken = {
8509
8631
  len: 4
8510
8632
  };
8511
8633
  //#endregion
8512
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/supported.js
8634
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/supported.js
8513
8635
  const extensions = [
8514
8636
  "jpg",
8515
8637
  "png",
@@ -8876,7 +8998,7 @@ const mimeTypes = [
8876
8998
  "application/vnd.apple.pages"
8877
8999
  ];
8878
9000
  //#endregion
8879
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/parser.js
9001
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/parser.js
8880
9002
  const maximumUntrustedSkipSizeInBytes = 16777216;
8881
9003
  var ParserHardLimitError = class extends Error {};
8882
9004
  function getSafeBound(value, maximum, reason) {
@@ -8912,7 +9034,7 @@ function hasExceededUnknownSizeScanBudget(tokenizer, startOffset, maximumBytes)
8912
9034
  return hasUnknownFileSize(tokenizer) && tokenizer.position - startOffset > maximumBytes;
8913
9035
  }
8914
9036
  //#endregion
8915
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/detectors/zip.js
9037
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/detectors/zip.js
8916
9038
  const maximumZipEntrySizeInBytes = 1048576;
8917
9039
  const maximumZipEntryCount = 1024;
8918
9040
  const maximumZipBufferedReadSizeInBytes = 2 ** 31 - 1;
@@ -8947,11 +9069,13 @@ async function decompressDeflateRawWithLimit(data, { maximumLength = maximumZipE
8947
9069
  if (done) break;
8948
9070
  totalLength += value.length;
8949
9071
  if (totalLength > maximumLength) {
8950
- await reader.cancel();
9072
+ await reader.cancel().catch(() => {});
8951
9073
  throw new Error(`ZIP entry decompressed data exceeds ${maximumLength} bytes`);
8952
9074
  }
8953
9075
  chunks.push(value);
8954
9076
  }
9077
+ } catch (error) {
9078
+ if (error.code !== "ERR_TRAILING_JUNK_AFTER_STREAM_END") throw error;
8955
9079
  } finally {
8956
9080
  reader.releaseLock();
8957
9081
  }
@@ -9344,7 +9468,7 @@ async function detectZip(tokenizer) {
9344
9468
  };
9345
9469
  }
9346
9470
  //#endregion
9347
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/detectors/ebml.js
9471
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/detectors/ebml.js
9348
9472
  const maximumEbmlDocumentTypeSizeInBytes = 64;
9349
9473
  const maximumEbmlElementPayloadSizeInBytes = 1048576;
9350
9474
  const maximumEbmlElementCount = 256;
@@ -9412,7 +9536,7 @@ async function detectEbml(tokenizer) {
9412
9536
  }
9413
9537
  }
9414
9538
  //#endregion
9415
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/detectors/png.js
9539
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/detectors/png.js
9416
9540
  const maximumPngChunkCount = 512;
9417
9541
  const maximumPngStreamScanBudgetInBytes = 16777216;
9418
9542
  const maximumPngChunkSizeInBytes = 1048576;
@@ -9471,7 +9595,7 @@ async function detectPng(tokenizer) {
9471
9595
  return pngFileType;
9472
9596
  }
9473
9597
  //#endregion
9474
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/detectors/asf.js
9598
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/detectors/asf.js
9475
9599
  const maximumAsfHeaderObjectCount = 512;
9476
9600
  const maximumAsfHeaderPayloadSizeInBytes = 1048576;
9477
9601
  async function detectAsf(tokenizer) {
@@ -9598,12 +9722,12 @@ async function detectAsf(tokenizer) {
9598
9722
  };
9599
9723
  }
9600
9724
  //#endregion
9601
- //#region ../../node_modules/.pnpm/file-type@22.0.1/node_modules/file-type/source/index.js
9725
+ //#region ../../node_modules/.pnpm/file-type@22.0.2/node_modules/file-type/source/index.js
9602
9726
  /**
9603
9727
  Primary entry point, Node.js specific entry point is index.js
9604
9728
  */
9605
9729
  const reasonableDetectionSizeInBytes = 4100;
9606
- const maximumMpegOffsetTolerance = 4098;
9730
+ const maximumMpegOffsetTolerance = 4096;
9607
9731
  const maximumNestedGzipDetectionSizeInBytes = maximumUntrustedSkipSizeInBytes;
9608
9732
  const maximumNestedGzipProbeDepth = 1;
9609
9733
  const unknownSizeGzipProbeTimeoutInMilliseconds = 100;
@@ -11196,10 +11320,10 @@ var FileTypeParser = class FileTypeParser {
11196
11320
  mime: "image/x-icon"
11197
11321
  };
11198
11322
  await tokenizer.peekBuffer(this.buffer, {
11199
- length: Math.min(2 + this.options.mpegOffsetTolerance, fileSize),
11323
+ length: Math.min(4 + this.options.mpegOffsetTolerance, fileSize),
11200
11324
  mayBeLess: true
11201
11325
  });
11202
- if (this.buffer.length >= 2 + this.options.mpegOffsetTolerance) for (let depth = 0; depth <= this.options.mpegOffsetTolerance; ++depth) {
11326
+ if (this.buffer.length >= 4 + this.options.mpegOffsetTolerance) for (let depth = 0; depth <= this.options.mpegOffsetTolerance; ++depth) {
11203
11327
  const type = this.scanMpeg(depth);
11204
11328
  if (type) return type;
11205
11329
  }
@@ -11285,19 +11409,23 @@ var FileTypeParser = class FileTypeParser {
11285
11409
  if (this.check([16], {
11286
11410
  offset: offset + 1,
11287
11411
  mask: [22]
11288
- })) {
11289
- if (this.check([8], {
11290
- offset: offset + 1,
11291
- mask: [8]
11292
- })) return {
11293
- ext: "aac",
11294
- mime: "audio/aac"
11295
- };
11296
- return {
11297
- ext: "aac",
11298
- mime: "audio/aac"
11299
- };
11300
- }
11412
+ })) return {
11413
+ ext: "aac",
11414
+ mime: "audio/aac"
11415
+ };
11416
+ if (this.check([255, 254], { offset })) return;
11417
+ if (this.check([8], {
11418
+ offset: offset + 1,
11419
+ mask: [24]
11420
+ })) return;
11421
+ if (this.check([240], {
11422
+ offset: offset + 2,
11423
+ mask: [240]
11424
+ })) return;
11425
+ if (this.check([12], {
11426
+ offset: offset + 2,
11427
+ mask: [12]
11428
+ })) return;
11301
11429
  if (this.check([2], {
11302
11430
  offset: offset + 1,
11303
11431
  mask: [6]
@@ -11361,6 +11489,7 @@ async function detectFileType(input) {
11361
11489
  * ffmpeg 由 execa 以子进程方式调用(非 node 内置),依赖系统 PATH 中的 ffmpeg。
11362
11490
  * - `transcodeVideo`:转码 / 缩放 / 帧率
11363
11491
  * - `getVideoInfo`:解析 ffprobe 输出取宽高与时长
11492
+ * - `extractVideoFrame`:抽首帧作缩略图(QQ 视频消息发送需要)
11364
11493
  */
11365
11494
  const MS_PER_SECOND = 1e3;
11366
11495
  /** 替换扩展名(保持目录,父目录由调用方保证存在)。 */
@@ -11383,7 +11512,7 @@ function replaceExt(input, ext) {
11383
11512
  else stem = base;
11384
11513
  return `${dir}${stem}${ext}`;
11385
11514
  }
11386
- /** 转码:按选项输出到替换扩展名后的路径(.mp4)。 */
11515
+ /** 转码:按选项输出到替换扩展名后的路径(.mp4)。ffmpeg 缺失/失败抛 MediaError。 */
11387
11516
  async function transcodeVideo(input, opts = {}) {
11388
11517
  const args = [
11389
11518
  "-y",
@@ -11396,11 +11525,13 @@ async function transcodeVideo(input, opts = {}) {
11396
11525
  if (opts.fps !== void 0) args.push("-r", String(opts.fps));
11397
11526
  const output = replaceExt(input, ".mp4");
11398
11527
  args.push("-c:v", "libx264", "-preset", "fast", output);
11528
+ let exitCode;
11399
11529
  try {
11400
- await execa("ffmpeg", args, { reject: false });
11530
+ exitCode = (await execa("ffmpeg", args, { reject: false })).exitCode;
11401
11531
  } catch (err) {
11402
- throw new MediaError(`ffmpeg 转码失败: ${input}`, { cause: err });
11532
+ throw new MediaError(`ffmpeg 不可用或转码失败: ${input}`, { cause: err });
11403
11533
  }
11534
+ if (exitCode !== 0 || !existsSync(output)) throw new MediaError(`ffmpeg 转码失败: ${input}(exit ${exitCode ?? "?"})`);
11404
11535
  return output;
11405
11536
  }
11406
11537
  /** 读取视频宽高与时长(ffprobe JSON 输出解析)。 */
@@ -11433,7 +11564,38 @@ async function getVideoInfo(input) {
11433
11564
  durationMs: Math.round(Number(durationStr) * MS_PER_SECOND)
11434
11565
  };
11435
11566
  }
11567
+ /**
11568
+ * 抽视频首帧为 PNG 缩略图(QQ 视频消息发送契约:thumbPath 指向真实图片文件)。
11569
+ *
11570
+ * 固定 `-ss 0` 取首帧:QQ 缩略图只需要一张可解码的封面,首帧最稳定
11571
+ * (部分视频首帧为黑屏时可改 1s,此处不引入额外配置)。转码失败 / ffmpeg
11572
+ * 缺失 / 输出未生成均抛 MediaError,由调用方决定降级策略。
11573
+ */
11574
+ async function extractVideoFrame(input, outputPath) {
11575
+ const args = [
11576
+ "-y",
11577
+ "-ss",
11578
+ "0",
11579
+ "-i",
11580
+ input,
11581
+ "-frames:v",
11582
+ "1",
11583
+ "-q:v",
11584
+ "3",
11585
+ "-f",
11586
+ "image2",
11587
+ outputPath
11588
+ ];
11589
+ let exitCode;
11590
+ try {
11591
+ exitCode = (await execa("ffmpeg", args, { reject: false })).exitCode;
11592
+ } catch (err) {
11593
+ throw new MediaError(`ffmpeg 不可用或抽帧失败: ${input}`, { cause: err });
11594
+ }
11595
+ if (exitCode !== 0 || !existsSync(outputPath)) throw new MediaError(`ffmpeg 抽帧失败: ${input}(exit ${exitCode ?? "?"})`);
11596
+ return outputPath;
11597
+ }
11436
11598
  //#endregion
11437
- export { MediaError, SILK_SAMPLE_RATE, decodeSilkToPcm, detectFileType, encodePcmToSilk, getImageSize, getSilkInfo, getVideoInfo, transcodeVideo };
11599
+ export { MediaError, SILK_SAMPLE_RATE, decodeSilkToPcm, decodeSilkToWav, detectFileType, downloadUrl, encodePcmToSilk, extractVideoFrame, getImageSize, getSilkInfo, getVideoInfo, inferExtension, transcodeVideo };
11438
11600
 
11439
11601
  //# sourceMappingURL=index.mjs.map