@napuketto/media 0.6.0 → 0.7.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/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  媒体编解码与识别。
4
4
 
5
5
  - **image** — 尺寸识别(image-size)+ 类型嗅探(file-type)
6
- - **audio** — silk 编解码(silk-wasm)
6
+ - **audio** — silk 编解码(silkr)
7
7
  - **video** — ffmpeg 转码(execa)
8
8
 
9
9
  ## 约束
package/dist/index.d.mts CHANGED
@@ -65,6 +65,8 @@ export declare class MediaSizeLimitError extends MediaError {
65
65
  }
66
66
  /** SILK 默认采样率(Hz)。 */
67
67
  export declare const SILK_SAMPLE_RATE = 24e3;
68
+ /** SILK 默认目标码率(bps),兼顾音乐语音音质与体积。 */
69
+ export declare const SILK_DEFAULT_BIT_RATE = 48e3;
68
70
  export declare const MAX_AUDIO_SECONDS = 600;
69
71
  export declare const MAX_AUDIO_INPUT_BYTES: number;
70
72
  /** 解码 SILK 音频为 PCM(pcm_s16le)。 */
@@ -84,6 +86,8 @@ export declare function decodeSilkToWav(input: string, { sampleRate, outDir, sig
84
86
  interface SilkEncodeOptions extends MediaOutputOptions {
85
87
  /** 转码目标。指定时父目录须已存在,且由调用方控制。 */
86
88
  outputPath?: string | undefined;
89
+ /** 目标码率(bps,5000–100000),缺省 48000。 */
90
+ bitRate?: number | undefined;
87
91
  /** 归一化 PCM 清理后报告其实际写入量。 */
88
92
  onPcmWritten?: ((bytes: number) => void) | undefined;
89
93
  }
package/dist/index.mjs CHANGED
@@ -206,6 +206,10 @@ async function publishMediaFile(path, chunks, signal) {
206
206
  // src/audio/silk-format.ts
207
207
  /** SILK 默认采样率(Hz)。 */
208
208
  const SILK_SAMPLE_RATE = 24e3;
209
+ /** SILK 默认目标码率(bps),兼顾音乐语音音质与体积。 */
210
+ const SILK_DEFAULT_BIT_RATE = 48e3;
211
+ const SILK_MIN_BIT_RATE = 5e3;
212
+ const SILK_MAX_BIT_RATE = 1e5;
209
213
  const MAX_AUDIO_SECONDS = 600;
210
214
  const MAX_AUDIO_INPUT_BYTES = 33554432;
211
215
  const SILK_FRAME_MS = 20;
@@ -226,8 +230,15 @@ const DECODE_SAMPLE_RATES = /* @__PURE__ */ new Set([
226
230
  24e3,
227
231
  48e3
228
232
  ]);
233
+ function parseSampleRate(rate, allowed) {
234
+ for (const candidate of allowed) if (candidate === rate) return candidate;
235
+ throw new MediaError(`不支持的音频采样率: ${rate}`);
236
+ }
229
237
  function assertSampleRate(rate, allowed) {
230
- if (!allowed.has(rate)) throw new MediaError(`不支持的音频采样率: ${rate}`);
238
+ parseSampleRate(rate, allowed);
239
+ }
240
+ function assertBitRate(bitRate) {
241
+ if (!Number.isInteger(bitRate) || bitRate < 5e3 || bitRate > 1e5) throw new MediaError(`不支持的音频码率: ${bitRate}(允许 ${SILK_MIN_BIT_RATE}–${SILK_MAX_BIT_RATE} bps)`);
231
242
  }
232
243
  function assertAudioDuration(durationMs) {
233
244
  if (!Number.isFinite(durationMs) || durationMs <= 0 || durationMs > 6e5) throw new MediaError(`音频时长必须大于 0 且不超过 600s`);
@@ -335,19 +346,16 @@ async function publishAudio(input, output, chunks, signal) {
335
346
  }
336
347
  // src/audio/silk-worker-client.ts
337
348
  const MAX_SILK_WORK_MS = 3e4;
338
- /** silk-wasm 的 Promise 内部运行同步 WASM;取消时等待执行它的 Worker 退出。 */
339
- async function runSilk(mode, data, sampleRate, signal) {
349
+ /** 在独立 Worker 中执行同步 silkr 编解码,以支持超时与取消强杀并等待 Worker 退出。 */
350
+ async function runSilk(job, signal) {
340
351
  checkMediaSignal(signal);
341
352
  const source = import.meta.url.endsWith(".ts");
353
+ const transferable = job.data.buffer instanceof ArrayBuffer && job.data.byteOffset === 0 && job.data.byteLength === job.data.buffer.byteLength ? [job.data.buffer] : [];
342
354
  try {
343
355
  const worker = new Worker(new URL(source ? "../silk-worker.mts" : "./silk-worker.mjs", import.meta.url), {
344
356
  execArgv: source ? ["--experimental-strip-types"] : [],
345
- workerData: {
346
- mode,
347
- data,
348
- sampleRate
349
- },
350
- transferList: data.buffer instanceof ArrayBuffer ? [data.buffer] : []
357
+ workerData: job,
358
+ transferList: transferable
351
359
  });
352
360
  return await new Promise((done, reject) => {
353
361
  let result;
@@ -426,15 +434,19 @@ function monoWavPcm(header, fileSize) {
426
434
  }
427
435
  // src/audio.ts
428
436
  async function decodeAudio(input, sampleRate, signal) {
429
- assertSampleRate(sampleRate, DECODE_SAMPLE_RATES);
437
+ const rate = parseSampleRate(sampleRate, DECODE_SAMPLE_RATES);
430
438
  checkMediaSignal(signal);
431
439
  const buffer = await readBoundedMediaFile(await localMediaPath(input, MAX_AUDIO_INPUT_BYTES), MAX_AUDIO_INPUT_BYTES, signal);
432
440
  const header = silkHeaderLength(buffer);
433
441
  if (header === 0) throw new MediaError(`不是有效的 SILK 文件: ${input}`);
434
442
  await silkDuration([buffer], header, signal);
435
- const result = await runSilk("decode", buffer, sampleRate, signal);
443
+ const result = await runSilk({
444
+ mode: "decode",
445
+ data: buffer,
446
+ sampleRate: rate
447
+ }, signal);
436
448
  assertAudioDuration(result.duration);
437
- if (result.data.byteLength === 0 || result.data.byteLength > 600 * sampleRate * 2) throw new MediaError("解码 PCM 超出大小限制或为空");
449
+ if (result.data.byteLength === 0 || result.data.byteLength > 600 * rate * 2) throw new MediaError("解码 PCM 超出大小限制或为空");
438
450
  return result;
439
451
  }
440
452
  /** 解码 SILK 音频为 PCM(pcm_s16le)。 */
@@ -460,6 +472,8 @@ async function decodeSilkToWav(input, { sampleRate = SILK_SAMPLE_RATE, outDir, s
460
472
  /** 编码音频为 SILK;已通过边界检查的 SILK 原样返回。 */
461
473
  async function encodePcmToSilk(input, sampleRate = 0, options = {}) {
462
474
  const { signal, maxOutputBytes, onPcmWritten } = options;
475
+ const bitRate = options.bitRate ?? 48e3;
476
+ assertBitRate(bitRate);
463
477
  const limit = mediaOutputLimit(62354432, maxOutputBytes);
464
478
  checkMediaSignal(signal);
465
479
  const source = await localMediaPath(input, MAX_AUDIO_INPUT_BYTES);
@@ -475,7 +489,12 @@ async function encodePcmToSilk(input, sampleRate = 0, options = {}) {
475
489
  const data = pcm !== void 0 || directRate !== 0 ? await readPcm(source, directRate, pcm, signal) : await normalizeToPcm(source, dirname(silkPath), limit, signal);
476
490
  const pcmBytes = directRate === 0 ? data.byteLength : 0;
477
491
  if (pcmBytes > 0) onPcmWritten?.(pcmBytes);
478
- const result = await runSilk("encode", data, directRate || 24e3, signal);
492
+ const result = await runSilk({
493
+ mode: "encode",
494
+ data,
495
+ sampleRate: parseSampleRate(directRate || 24e3, ENCODE_SAMPLE_RATES),
496
+ bitRate
497
+ }, signal);
479
498
  assertAudioDuration(result.duration);
480
499
  if (result.data.byteLength > Math.min(33554432, limit - pcmBytes)) throw new MediaSizeLimitError("SILK 输出超出大小限制");
481
500
  if (result.data.byteLength === 0) throw new MediaError("SILK 输出为空");
@@ -1133,4 +1152,4 @@ async function extractVideoFrame(input, outputPath, { signal, maxOutputBytes } =
1133
1152
  await rm(output, { force: true });
1134
1153
  }
1135
1154
  }
1136
- 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 };
1155
+ export { DEFAULT_DOWNLOAD_MAX_BYTES, MAX_AUDIO_INPUT_BYTES, MAX_AUDIO_SECONDS, MediaError, MediaSizeLimitError, SILK_DEFAULT_BIT_RATE, SILK_SAMPLE_RATE, decodeSilkToPcm, decodeSilkToWav, detectFileType, downloadPublicUrl, downloadUrl, encodePcmToSilk, extractVideoFrame, getImageSize, getSilkInfo, getVideoInfo, inferExtension, transcodeVideo };
@@ -1,8 +1,28 @@
1
1
  import { parentPort, workerData } from "node:worker_threads";
2
- import { decode, encode } from "silk-wasm";
2
+ import { decodeSync, encodeSync, getDuration } from "silkr";
3
3
  // src/silk-worker.mts
4
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] : []);
5
+ function execute(input) {
6
+ if (input.mode === "encode") {
7
+ const data = encodeSync(input.data, {
8
+ sampleRate: input.sampleRate,
9
+ bitRate: input.bitRate,
10
+ maxInternalSampleRate: 24e3,
11
+ complexity: 2,
12
+ useDtx: false,
13
+ tencentHeader: true
14
+ });
15
+ return {
16
+ data,
17
+ duration: getDuration(data)
18
+ };
19
+ }
20
+ const data = decodeSync(input.data, { sampleRate: input.sampleRate });
21
+ return {
22
+ data,
23
+ duration: Math.round(data.byteLength / (input.sampleRate * 2) * 1e3)
24
+ };
25
+ }
26
+ const result = execute(job);
27
+ parentPort?.postMessage(result);
8
28
  export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@napuketto/media",
4
- "version": "0.6.0",
4
+ "version": "0.7.0",
5
5
  "type": "module",
6
6
  "description": "Media utilities for Napuketto",
7
7
  "keywords": [
@@ -53,8 +53,8 @@
53
53
  "dependencies": {
54
54
  "execa": "^10.2.1",
55
55
  "file-type": "^22.3.0",
56
- "image-size": "^2.1.0",
57
- "silk-wasm": "^3.7.1"
56
+ "image-size": "^2.2.0",
57
+ "silkr": "^1.0.0"
58
58
  },
59
59
  "devDependencies": {
60
60
  "tsdown": "^0.23.7"