@napuketto/media 0.5.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
@@ -1,11 +1,11 @@
1
- import { randomBytes, randomUUID } from "node:crypto";
2
1
  import { mkdir, mkdtemp, open, realpath, rename, rm, stat } from "node:fs/promises";
3
2
  import { basename, dirname, join, resolve } from "node:path";
4
- import { Worker } from "node:worker_threads";
3
+ import { randomBytes, randomUUID } from "node:crypto";
5
4
  import { constants, createWriteStream } from "node:fs";
6
5
  import { Readable, Transform } from "node:stream";
7
6
  import { pipeline } from "node:stream/promises";
8
7
  import { execa } from "execa";
8
+ import { Worker } from "node:worker_threads";
9
9
  import { BlockList, isIP } from "node:net";
10
10
  import process$1 from "node:process";
11
11
  import { lookup } from "node:dns/promises";
@@ -203,13 +203,15 @@ async function publishMediaFile(path, chunks, signal) {
203
203
  await rm(partial, { force: true });
204
204
  }
205
205
  }
206
- // src/audio.ts
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
- const MAX_NORMALIZED_PCM_BYTES = 600 * SILK_SAMPLE_RATE * 2;
212
- const MAX_SILK_WORK_MS = 3e4;
213
215
  const SILK_FRAME_MS = 20;
214
216
  const SILK_HEADER = Buffer.from("#!SILK_V3");
215
217
  const ENCODE_SAMPLE_RATES = /* @__PURE__ */ new Set([
@@ -228,8 +230,15 @@ const DECODE_SAMPLE_RATES = /* @__PURE__ */ new Set([
228
230
  24e3,
229
231
  48e3
230
232
  ]);
233
+ function parseSampleRate(rate, allowed) {
234
+ for (const candidate of allowed) if (candidate === rate) return candidate;
235
+ throw new MediaError(`不支持的音频采样率: ${rate}`);
236
+ }
231
237
  function assertSampleRate(rate, allowed) {
232
- 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)`);
233
242
  }
234
243
  function assertAudioDuration(durationMs) {
235
244
  if (!Number.isFinite(durationMs) || durationMs <= 0 || durationMs > 6e5) throw new MediaError(`音频时长必须大于 0 且不超过 600s`);
@@ -282,19 +291,71 @@ function consumeSilkChunk(scan, chunk) {
282
291
  assertAudioDuration(scan.duration);
283
292
  }
284
293
  }
285
- /** silk-wasm 的 Promise 内部运行同步 WASM;取消时等待执行它的 Worker 退出。 */
286
- async function runSilk(mode, data, sampleRate, signal) {
294
+ // src/audio/pcm-normalizer.ts
295
+ const MAX_NORMALIZED_PCM_BYTES = 600 * SILK_SAMPLE_RATE * 2;
296
+ async function readPcm(source, sampleRate, wav, signal) {
297
+ assertSampleRate(sampleRate, ENCODE_SAMPLE_RATES);
298
+ const file = await readBoundedMediaFile(source, MAX_AUDIO_INPUT_BYTES, signal);
299
+ const data = wav === void 0 ? file : file.subarray(wav.offset, wav.offset + wav.bytes);
300
+ if (data.byteLength % 2 !== 0 || wav !== void 0 && wav.bytes !== data.byteLength) throw new MediaError("PCM 输入帧不完整");
301
+ assertAudioDuration(data.byteLength * 500 / sampleRate);
302
+ return data;
303
+ }
304
+ async function normalizeToPcm(source, directory, limit, signal) {
305
+ const partial = join(directory, `.napuketto-${randomBytes(8).toString("hex")}.pcm`);
306
+ const maxBytes = Math.min(MAX_NORMALIZED_PCM_BYTES, limit);
307
+ try {
308
+ await writeFfmpegOutput([
309
+ "-nostdin",
310
+ "-v",
311
+ "error",
312
+ ...FFMPEG_WORK_OPTIONS,
313
+ ...LOCAL_MEDIA_INPUT_OPTIONS,
314
+ "-i",
315
+ source,
316
+ "-map",
317
+ "0:a:0",
318
+ "-ac",
319
+ "1",
320
+ "-ar",
321
+ String(SILK_SAMPLE_RATE),
322
+ "-t",
323
+ String(600.02),
324
+ "-f",
325
+ "s16le"
326
+ ], partial, maxBytes, 12e4, signal);
327
+ return await readBoundedMediaFile(partial, maxBytes, signal);
328
+ } catch (error) {
329
+ checkMediaSignal(signal);
330
+ if (error instanceof MediaSizeLimitError) throw error;
331
+ throw new MediaError(`ffmpeg 音频归一化失败: ${source}`, { cause: error });
332
+ } finally {
333
+ await rm(partial, { force: true });
334
+ }
335
+ }
336
+ async function publishAudio(input, output, chunks, signal) {
337
+ const source = resolve(input);
338
+ const target = resolve(output);
339
+ if (source === target || process.platform === "win32" && source.toLowerCase() === target.toLowerCase()) throw new MediaError("音频输出不能覆盖输入文件");
340
+ try {
341
+ await publishMediaFile(output, chunks, signal);
342
+ } catch (error) {
343
+ checkMediaSignal(signal);
344
+ throw new MediaError("无法写出音频产物", { cause: error });
345
+ }
346
+ }
347
+ // src/audio/silk-worker-client.ts
348
+ const MAX_SILK_WORK_MS = 3e4;
349
+ /** 在独立 Worker 中执行同步 silkr 编解码,以支持超时与取消强杀并等待 Worker 退出。 */
350
+ async function runSilk(job, signal) {
287
351
  checkMediaSignal(signal);
288
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] : [];
289
354
  try {
290
- const worker = new Worker(new URL(source ? "./silk-worker.mts" : "./silk-worker.mjs", import.meta.url), {
355
+ const worker = new Worker(new URL(source ? "../silk-worker.mts" : "./silk-worker.mjs", import.meta.url), {
291
356
  execArgv: source ? ["--experimental-strip-types"] : [],
292
- workerData: {
293
- mode,
294
- data,
295
- sampleRate
296
- },
297
- transferList: data.buffer instanceof ArrayBuffer ? [data.buffer] : []
357
+ workerData: job,
358
+ transferList: transferable
298
359
  });
299
360
  return await new Promise((done, reject) => {
300
361
  let result;
@@ -326,38 +387,7 @@ async function runSilk(mode, data, sampleRate, signal) {
326
387
  throw new MediaError("SILK 编解码失败", { cause: error });
327
388
  }
328
389
  }
329
- async function decodeAudio(input, sampleRate, signal) {
330
- assertSampleRate(sampleRate, DECODE_SAMPLE_RATES);
331
- checkMediaSignal(signal);
332
- const buffer = await readBoundedMediaFile(await localMediaPath(input, MAX_AUDIO_INPUT_BYTES), MAX_AUDIO_INPUT_BYTES, signal);
333
- const header = silkHeaderLength(buffer);
334
- if (header === 0) throw new MediaError(`不是有效的 SILK 文件: ${input}`);
335
- await silkDuration([buffer], header, signal);
336
- const result = await runSilk("decode", buffer, sampleRate, signal);
337
- assertAudioDuration(result.duration);
338
- if (result.data.byteLength === 0 || result.data.byteLength > 600 * sampleRate * 2) throw new MediaError("解码 PCM 超出大小限制或为空");
339
- return result;
340
- }
341
- /** 解码 SILK 音频为 PCM(pcm_s16le)。 */
342
- async function decodeSilkToPcm(input, sampleRate = SILK_SAMPLE_RATE, { signal } = {}) {
343
- const result = await decodeAudio(input, sampleRate, signal);
344
- const pcmPath = replaceExt(input, ".pcm");
345
- await publishAudio(input, pcmPath, [result.data], signal);
346
- return {
347
- pcmPath,
348
- durationMs: result.duration
349
- };
350
- }
351
- /** 解码 SILK 为可播放 WAV,返回的文件由调用方管理。 */
352
- async function decodeSilkToWav(input, { sampleRate = SILK_SAMPLE_RATE, outDir, signal } = {}) {
353
- const result = await decodeAudio(input, sampleRate, signal);
354
- const wavPath = join(outDir ?? dirname(input), replaceExt(basename(input), ".wav"));
355
- await publishAudio(input, wavPath, [wavHeader(result.data.byteLength, sampleRate), result.data], signal);
356
- return {
357
- wavPath,
358
- durationMs: result.duration
359
- };
360
- }
390
+ // src/audio/wav-codec.ts
361
391
  function wavHeader(bytes, sampleRate) {
362
392
  const header = Buffer.alloc(44);
363
393
  header.write("RIFF", 0, "ascii");
@@ -374,17 +404,6 @@ function wavHeader(bytes, sampleRate) {
374
404
  header.writeUInt32LE(bytes, 40);
375
405
  return header;
376
406
  }
377
- async function publishAudio(input, output, chunks, signal) {
378
- const source = resolve(input);
379
- const target = resolve(output);
380
- if (source === target || process.platform === "win32" && source.toLowerCase() === target.toLowerCase()) throw new MediaError("音频输出不能覆盖输入文件");
381
- try {
382
- await publishMediaFile(output, chunks, signal);
383
- } catch (error) {
384
- checkMediaSignal(signal);
385
- throw new MediaError("无法写出音频产物", { cause: error });
386
- }
387
- }
388
407
  function isRiffWave(header) {
389
408
  return header.toString("latin1", 0, 4) === "RIFF" && header.toString("latin1", 8, 12) === "WAVE";
390
409
  }
@@ -413,9 +432,48 @@ function monoWavPcm(header, fileSize) {
413
432
  offset = data + bytes + bytes % 2;
414
433
  }
415
434
  }
435
+ // src/audio.ts
436
+ async function decodeAudio(input, sampleRate, signal) {
437
+ const rate = parseSampleRate(sampleRate, DECODE_SAMPLE_RATES);
438
+ checkMediaSignal(signal);
439
+ const buffer = await readBoundedMediaFile(await localMediaPath(input, MAX_AUDIO_INPUT_BYTES), MAX_AUDIO_INPUT_BYTES, signal);
440
+ const header = silkHeaderLength(buffer);
441
+ if (header === 0) throw new MediaError(`不是有效的 SILK 文件: ${input}`);
442
+ await silkDuration([buffer], header, signal);
443
+ const result = await runSilk({
444
+ mode: "decode",
445
+ data: buffer,
446
+ sampleRate: rate
447
+ }, signal);
448
+ assertAudioDuration(result.duration);
449
+ if (result.data.byteLength === 0 || result.data.byteLength > 600 * rate * 2) throw new MediaError("解码 PCM 超出大小限制或为空");
450
+ return result;
451
+ }
452
+ /** 解码 SILK 音频为 PCM(pcm_s16le)。 */
453
+ async function decodeSilkToPcm(input, sampleRate = SILK_SAMPLE_RATE, { signal } = {}) {
454
+ const result = await decodeAudio(input, sampleRate, signal);
455
+ const pcmPath = replaceExt(input, ".pcm");
456
+ await publishAudio(input, pcmPath, [result.data], signal);
457
+ return {
458
+ pcmPath,
459
+ durationMs: result.duration
460
+ };
461
+ }
462
+ /** 解码 SILK 为可播放 WAV,返回的文件由调用方管理。 */
463
+ async function decodeSilkToWav(input, { sampleRate = SILK_SAMPLE_RATE, outDir, signal } = {}) {
464
+ const result = await decodeAudio(input, sampleRate, signal);
465
+ const wavPath = join(outDir ?? dirname(input), replaceExt(basename(input), ".wav"));
466
+ await publishAudio(input, wavPath, [wavHeader(result.data.byteLength, sampleRate), result.data], signal);
467
+ return {
468
+ wavPath,
469
+ durationMs: result.duration
470
+ };
471
+ }
416
472
  /** 编码音频为 SILK;已通过边界检查的 SILK 原样返回。 */
417
473
  async function encodePcmToSilk(input, sampleRate = 0, options = {}) {
418
474
  const { signal, maxOutputBytes, onPcmWritten } = options;
475
+ const bitRate = options.bitRate ?? 48e3;
476
+ assertBitRate(bitRate);
419
477
  const limit = mediaOutputLimit(62354432, maxOutputBytes);
420
478
  checkMediaSignal(signal);
421
479
  const source = await localMediaPath(input, MAX_AUDIO_INPUT_BYTES);
@@ -431,53 +489,18 @@ async function encodePcmToSilk(input, sampleRate = 0, options = {}) {
431
489
  const data = pcm !== void 0 || directRate !== 0 ? await readPcm(source, directRate, pcm, signal) : await normalizeToPcm(source, dirname(silkPath), limit, signal);
432
490
  const pcmBytes = directRate === 0 ? data.byteLength : 0;
433
491
  if (pcmBytes > 0) onPcmWritten?.(pcmBytes);
434
- 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);
435
498
  assertAudioDuration(result.duration);
436
499
  if (result.data.byteLength > Math.min(33554432, limit - pcmBytes)) throw new MediaSizeLimitError("SILK 输出超出大小限制");
437
500
  if (result.data.byteLength === 0) throw new MediaError("SILK 输出为空");
438
501
  await publishAudio(input, silkPath, [result.data], signal);
439
502
  return silkPath;
440
503
  }
441
- async function readPcm(source, sampleRate, wav, signal) {
442
- assertSampleRate(sampleRate, ENCODE_SAMPLE_RATES);
443
- const file = await readBoundedMediaFile(source, MAX_AUDIO_INPUT_BYTES, signal);
444
- const data = wav === void 0 ? file : file.subarray(wav.offset, wav.offset + wav.bytes);
445
- if (data.byteLength % 2 !== 0 || wav !== void 0 && wav.bytes !== data.byteLength) throw new MediaError("PCM 输入帧不完整");
446
- assertAudioDuration(data.byteLength * 500 / sampleRate);
447
- return data;
448
- }
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);
452
- try {
453
- await writeFfmpegOutput([
454
- "-nostdin",
455
- "-v",
456
- "error",
457
- ...FFMPEG_WORK_OPTIONS,
458
- ...LOCAL_MEDIA_INPUT_OPTIONS,
459
- "-i",
460
- source,
461
- "-map",
462
- "0:a:0",
463
- "-ac",
464
- "1",
465
- "-ar",
466
- String(SILK_SAMPLE_RATE),
467
- "-t",
468
- String(600.02),
469
- "-f",
470
- "s16le"
471
- ], partial, maxBytes, 12e4, signal);
472
- return await readBoundedMediaFile(partial, maxBytes, signal);
473
- } catch (error) {
474
- checkMediaSignal(signal);
475
- if (error instanceof MediaSizeLimitError) throw error;
476
- throw new MediaError(`ffmpeg 音频归一化失败: ${source}`, { cause: error });
477
- } finally {
478
- await rm(partial, { force: true });
479
- }
480
- }
481
504
  /** 获取 SILK 音频时长。SILK 容器不携带采样率,返回调用方指定值。 */
482
505
  async function getSilkInfo(input, sampleRate = SILK_SAMPLE_RATE, { signal } = {}) {
483
506
  assertSampleRate(sampleRate, DECODE_SAMPLE_RATES);
@@ -1129,4 +1152,4 @@ async function extractVideoFrame(input, outputPath, { signal, maxOutputBytes } =
1129
1152
  await rm(output, { force: true });
1130
1153
  }
1131
1154
  }
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 };
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.5.0",
4
+ "version": "0.7.0",
5
5
  "type": "module",
6
6
  "description": "Media utilities for Napuketto",
7
7
  "keywords": [
@@ -28,7 +28,7 @@
28
28
  "url": "https://github.com/Oppenheymu"
29
29
  },
30
30
  "engines": {
31
- "node": ">=22.12.0"
31
+ "node": ">=24.11.0"
32
32
  },
33
33
  "sideEffects": false,
34
34
  "publishConfig": {
@@ -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"