@napuketto/media 0.5.0 → 0.6.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.
Files changed (2) hide show
  1. package/dist/index.mjs +93 -89
  2. package/package.json +2 -2
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,11 @@ 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
209
  const MAX_AUDIO_SECONDS = 600;
210
210
  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
211
  const SILK_FRAME_MS = 20;
214
212
  const SILK_HEADER = Buffer.from("#!SILK_V3");
215
213
  const ENCODE_SAMPLE_RATES = /* @__PURE__ */ new Set([
@@ -282,12 +280,67 @@ function consumeSilkChunk(scan, chunk) {
282
280
  assertAudioDuration(scan.duration);
283
281
  }
284
282
  }
283
+ // src/audio/pcm-normalizer.ts
284
+ const MAX_NORMALIZED_PCM_BYTES = 600 * SILK_SAMPLE_RATE * 2;
285
+ async function readPcm(source, sampleRate, wav, signal) {
286
+ assertSampleRate(sampleRate, ENCODE_SAMPLE_RATES);
287
+ const file = await readBoundedMediaFile(source, MAX_AUDIO_INPUT_BYTES, signal);
288
+ const data = wav === void 0 ? file : file.subarray(wav.offset, wav.offset + wav.bytes);
289
+ if (data.byteLength % 2 !== 0 || wav !== void 0 && wav.bytes !== data.byteLength) throw new MediaError("PCM 输入帧不完整");
290
+ assertAudioDuration(data.byteLength * 500 / sampleRate);
291
+ return data;
292
+ }
293
+ async function normalizeToPcm(source, directory, limit, signal) {
294
+ const partial = join(directory, `.napuketto-${randomBytes(8).toString("hex")}.pcm`);
295
+ const maxBytes = Math.min(MAX_NORMALIZED_PCM_BYTES, limit);
296
+ try {
297
+ await writeFfmpegOutput([
298
+ "-nostdin",
299
+ "-v",
300
+ "error",
301
+ ...FFMPEG_WORK_OPTIONS,
302
+ ...LOCAL_MEDIA_INPUT_OPTIONS,
303
+ "-i",
304
+ source,
305
+ "-map",
306
+ "0:a:0",
307
+ "-ac",
308
+ "1",
309
+ "-ar",
310
+ String(SILK_SAMPLE_RATE),
311
+ "-t",
312
+ String(600.02),
313
+ "-f",
314
+ "s16le"
315
+ ], partial, maxBytes, 12e4, signal);
316
+ return await readBoundedMediaFile(partial, maxBytes, signal);
317
+ } catch (error) {
318
+ checkMediaSignal(signal);
319
+ if (error instanceof MediaSizeLimitError) throw error;
320
+ throw new MediaError(`ffmpeg 音频归一化失败: ${source}`, { cause: error });
321
+ } finally {
322
+ await rm(partial, { force: true });
323
+ }
324
+ }
325
+ async function publishAudio(input, output, chunks, signal) {
326
+ const source = resolve(input);
327
+ const target = resolve(output);
328
+ if (source === target || process.platform === "win32" && source.toLowerCase() === target.toLowerCase()) throw new MediaError("音频输出不能覆盖输入文件");
329
+ try {
330
+ await publishMediaFile(output, chunks, signal);
331
+ } catch (error) {
332
+ checkMediaSignal(signal);
333
+ throw new MediaError("无法写出音频产物", { cause: error });
334
+ }
335
+ }
336
+ // src/audio/silk-worker-client.ts
337
+ const MAX_SILK_WORK_MS = 3e4;
285
338
  /** silk-wasm 的 Promise 内部运行同步 WASM;取消时等待执行它的 Worker 退出。 */
286
339
  async function runSilk(mode, data, sampleRate, signal) {
287
340
  checkMediaSignal(signal);
288
341
  const source = import.meta.url.endsWith(".ts");
289
342
  try {
290
- const worker = new Worker(new URL(source ? "./silk-worker.mts" : "./silk-worker.mjs", import.meta.url), {
343
+ const worker = new Worker(new URL(source ? "../silk-worker.mts" : "./silk-worker.mjs", import.meta.url), {
291
344
  execArgv: source ? ["--experimental-strip-types"] : [],
292
345
  workerData: {
293
346
  mode,
@@ -326,38 +379,7 @@ async function runSilk(mode, data, sampleRate, signal) {
326
379
  throw new MediaError("SILK 编解码失败", { cause: error });
327
380
  }
328
381
  }
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
- }
382
+ // src/audio/wav-codec.ts
361
383
  function wavHeader(bytes, sampleRate) {
362
384
  const header = Buffer.alloc(44);
363
385
  header.write("RIFF", 0, "ascii");
@@ -374,17 +396,6 @@ function wavHeader(bytes, sampleRate) {
374
396
  header.writeUInt32LE(bytes, 40);
375
397
  return header;
376
398
  }
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
399
  function isRiffWave(header) {
389
400
  return header.toString("latin1", 0, 4) === "RIFF" && header.toString("latin1", 8, 12) === "WAVE";
390
401
  }
@@ -413,6 +424,39 @@ function monoWavPcm(header, fileSize) {
413
424
  offset = data + bytes + bytes % 2;
414
425
  }
415
426
  }
427
+ // src/audio.ts
428
+ async function decodeAudio(input, sampleRate, signal) {
429
+ assertSampleRate(sampleRate, DECODE_SAMPLE_RATES);
430
+ checkMediaSignal(signal);
431
+ const buffer = await readBoundedMediaFile(await localMediaPath(input, MAX_AUDIO_INPUT_BYTES), MAX_AUDIO_INPUT_BYTES, signal);
432
+ const header = silkHeaderLength(buffer);
433
+ if (header === 0) throw new MediaError(`不是有效的 SILK 文件: ${input}`);
434
+ await silkDuration([buffer], header, signal);
435
+ const result = await runSilk("decode", buffer, sampleRate, signal);
436
+ assertAudioDuration(result.duration);
437
+ if (result.data.byteLength === 0 || result.data.byteLength > 600 * sampleRate * 2) throw new MediaError("解码 PCM 超出大小限制或为空");
438
+ return result;
439
+ }
440
+ /** 解码 SILK 音频为 PCM(pcm_s16le)。 */
441
+ async function decodeSilkToPcm(input, sampleRate = SILK_SAMPLE_RATE, { signal } = {}) {
442
+ const result = await decodeAudio(input, sampleRate, signal);
443
+ const pcmPath = replaceExt(input, ".pcm");
444
+ await publishAudio(input, pcmPath, [result.data], signal);
445
+ return {
446
+ pcmPath,
447
+ durationMs: result.duration
448
+ };
449
+ }
450
+ /** 解码 SILK 为可播放 WAV,返回的文件由调用方管理。 */
451
+ async function decodeSilkToWav(input, { sampleRate = SILK_SAMPLE_RATE, outDir, signal } = {}) {
452
+ const result = await decodeAudio(input, sampleRate, signal);
453
+ const wavPath = join(outDir ?? dirname(input), replaceExt(basename(input), ".wav"));
454
+ await publishAudio(input, wavPath, [wavHeader(result.data.byteLength, sampleRate), result.data], signal);
455
+ return {
456
+ wavPath,
457
+ durationMs: result.duration
458
+ };
459
+ }
416
460
  /** 编码音频为 SILK;已通过边界检查的 SILK 原样返回。 */
417
461
  async function encodePcmToSilk(input, sampleRate = 0, options = {}) {
418
462
  const { signal, maxOutputBytes, onPcmWritten } = options;
@@ -438,46 +482,6 @@ async function encodePcmToSilk(input, sampleRate = 0, options = {}) {
438
482
  await publishAudio(input, silkPath, [result.data], signal);
439
483
  return silkPath;
440
484
  }
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
485
  /** 获取 SILK 音频时长。SILK 容器不携带采样率,返回调用方指定值。 */
482
486
  async function getSilkInfo(input, sampleRate = SILK_SAMPLE_RATE, { signal } = {}) {
483
487
  assertSampleRate(sampleRate, DECODE_SAMPLE_RATES);
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.6.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": {