@napuketto/media 0.4.1 → 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.
- package/dist/index.d.mts +18 -4
- package/dist/index.mjs +126 -106
- package/package.json +2 -2
package/dist/index.d.mts
CHANGED
|
@@ -37,8 +37,11 @@ interface VideoInfo {
|
|
|
37
37
|
interface MediaOperationOptions {
|
|
38
38
|
signal?: AbortSignal | undefined;
|
|
39
39
|
}
|
|
40
|
+
interface MediaOutputOptions extends MediaOperationOptions {
|
|
41
|
+
maxOutputBytes?: number | undefined;
|
|
42
|
+
}
|
|
40
43
|
/** 视频转码选项。 */
|
|
41
|
-
interface TranscodeOptions extends
|
|
44
|
+
interface TranscodeOptions extends MediaOutputOptions {
|
|
42
45
|
/** 偶整数,2–4096。只指定一边时保持比例。 */
|
|
43
46
|
width?: number | undefined;
|
|
44
47
|
/** 偶整数,2–4096。 */
|
|
@@ -57,6 +60,9 @@ interface DecodedAudio {
|
|
|
57
60
|
export declare class MediaError extends Error {
|
|
58
61
|
constructor(message: string, options?: ErrorOptions);
|
|
59
62
|
}
|
|
63
|
+
export declare class MediaSizeLimitError extends MediaError {
|
|
64
|
+
constructor(message: string);
|
|
65
|
+
}
|
|
60
66
|
/** SILK 默认采样率(Hz)。 */
|
|
61
67
|
export declare const SILK_SAMPLE_RATE = 24e3;
|
|
62
68
|
export declare const MAX_AUDIO_SECONDS = 600;
|
|
@@ -75,8 +81,14 @@ interface DecodedWav {
|
|
|
75
81
|
}
|
|
76
82
|
/** 解码 SILK 为可播放 WAV,返回的文件由调用方管理。 */
|
|
77
83
|
export declare function decodeSilkToWav(input: string, { sampleRate, outDir, signal }?: DecodeSilkToWavOptions): Promise<DecodedWav>;
|
|
84
|
+
interface SilkEncodeOptions extends MediaOutputOptions {
|
|
85
|
+
/** 转码目标。指定时父目录须已存在,且由调用方控制。 */
|
|
86
|
+
outputPath?: string | undefined;
|
|
87
|
+
/** 归一化 PCM 清理后报告其实际写入量。 */
|
|
88
|
+
onPcmWritten?: ((bytes: number) => void) | undefined;
|
|
89
|
+
}
|
|
78
90
|
/** 编码音频为 SILK;已通过边界检查的 SILK 原样返回。 */
|
|
79
|
-
export declare function encodePcmToSilk(input: string, sampleRate?: number,
|
|
91
|
+
export declare function encodePcmToSilk(input: string, sampleRate?: number, options?: SilkEncodeOptions): Promise<string>;
|
|
80
92
|
/** 获取 SILK 音频时长。SILK 容器不携带采样率,返回调用方指定值。 */
|
|
81
93
|
export declare function getSilkInfo(input: string, sampleRate?: number, { signal }?: MediaOperationOptions): Promise<AudioInfo>;
|
|
82
94
|
/** 按协议调用方的信任边界选择远程媒体出站模式。 */
|
|
@@ -90,6 +102,8 @@ interface DownloadUrlOptions {
|
|
|
90
102
|
/** 初始源的附加请求头。传输/路由头忽略,跨源重定向清空所有调用者头。 */
|
|
91
103
|
headers?: Record<string, string> | undefined;
|
|
92
104
|
}
|
|
105
|
+
/** 默认大小上限(30MB)。 */
|
|
106
|
+
export declare const DEFAULT_DOWNLOAD_MAX_BYTES: number;
|
|
93
107
|
/**
|
|
94
108
|
* 下载 URL 到目标路径(覆盖写)。返回写入字节数。
|
|
95
109
|
* 失败抛 MediaError(非 2xx / 协议或地址被拒 / 超限 / 超时 / 空 body / IO 错误),
|
|
@@ -109,5 +123,5 @@ export declare function transcodeVideo(input: string, opts?: TranscodeOptions):
|
|
|
109
123
|
/** 读取视频显示尺寸与时长。 */
|
|
110
124
|
export declare function getVideoInfo(input: string, { signal }?: MediaOperationOptions): Promise<VideoInfo>;
|
|
111
125
|
/** 抽首帧至调用者指定路径。失败时保留原目标。 */
|
|
112
|
-
export declare function extractVideoFrame(input: string, outputPath: string, { signal }?:
|
|
113
|
-
export type { AudioInfo, DecodeSilkToWavOptions, DecodedAudio, DecodedWav, DownloadUrlOptions, FileTypeResult, ImageSize, MediaOperationOptions, MediaOutboundPolicy, TranscodeOptions, VideoInfo };
|
|
126
|
+
export declare function extractVideoFrame(input: string, outputPath: string, { signal, maxOutputBytes }?: MediaOutputOptions): Promise<string>;
|
|
127
|
+
export type { AudioInfo, DecodeSilkToWavOptions, DecodedAudio, DecodedWav, DownloadUrlOptions, FileTypeResult, ImageSize, MediaOperationOptions, MediaOutboundPolicy, MediaOutputOptions, SilkEncodeOptions, TranscodeOptions, VideoInfo };
|
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 {
|
|
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";
|
|
@@ -21,6 +21,12 @@ var MediaError = class extends Error {
|
|
|
21
21
|
this.name = "MediaError";
|
|
22
22
|
}
|
|
23
23
|
};
|
|
24
|
+
var MediaSizeLimitError = class extends MediaError {
|
|
25
|
+
constructor(message) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = "MediaSizeLimitError";
|
|
28
|
+
}
|
|
29
|
+
};
|
|
24
30
|
/**
|
|
25
31
|
* 替换文件扩展名(保持目录与分隔符风格,父目录存在性由调用方保证)。
|
|
26
32
|
* 统一实现供 audio / video 复用;同时兼容 POSIX `/` 与 Windows `\` 分隔符。
|
|
@@ -86,6 +92,10 @@ function mediaProcessOptions(timeout, cancelSignal) {
|
|
|
86
92
|
function checkMediaSignal(signal) {
|
|
87
93
|
if (signal?.aborted) throw new MediaError("媒体操作已取消", { cause: signal.reason });
|
|
88
94
|
}
|
|
95
|
+
function mediaOutputLimit(hardLimit, callerLimit = hardLimit) {
|
|
96
|
+
if (!Number.isSafeInteger(callerLimit) || callerLimit < 0) throw new MediaSizeLimitError("媒体输出上限必须是非负安全整数");
|
|
97
|
+
return Math.min(hardLimit, callerLimit);
|
|
98
|
+
}
|
|
89
99
|
function assertLocalPath(input) {
|
|
90
100
|
const windowsDrive = process.platform === "win32" && WINDOWS_DRIVE.test(input);
|
|
91
101
|
if (input.length === 0 || input.includes("\0") || NETWORK_OR_DEVICE_PATH.test(input) || PROTOCOL_PREFIX.test(input) && !windowsDrive) throw new MediaError(`媒体输入必须是本地普通文件: ${input}`);
|
|
@@ -151,7 +161,7 @@ async function writeFfmpegOutput(args, path, maxBytes, timeout, signal) {
|
|
|
151
161
|
let bytes = 0;
|
|
152
162
|
const limit = new Transform({ transform(chunk, _encoding, callback) {
|
|
153
163
|
bytes += chunk.length;
|
|
154
|
-
if (bytes > maxBytes) callback(new
|
|
164
|
+
if (bytes > maxBytes) callback(new MediaSizeLimitError(`媒体输出超过 ${maxBytes} 字节限制`));
|
|
155
165
|
else callback(null, chunk);
|
|
156
166
|
} });
|
|
157
167
|
const writing = Promise.resolve().then(() => {
|
|
@@ -193,13 +203,11 @@ async function publishMediaFile(path, chunks, signal) {
|
|
|
193
203
|
await rm(partial, { force: true });
|
|
194
204
|
}
|
|
195
205
|
}
|
|
196
|
-
// src/audio.ts
|
|
206
|
+
// src/audio/silk-format.ts
|
|
197
207
|
/** SILK 默认采样率(Hz)。 */
|
|
198
208
|
const SILK_SAMPLE_RATE = 24e3;
|
|
199
209
|
const MAX_AUDIO_SECONDS = 600;
|
|
200
210
|
const MAX_AUDIO_INPUT_BYTES = 33554432;
|
|
201
|
-
const MAX_NORMALIZED_PCM_BYTES = 600 * SILK_SAMPLE_RATE * 2;
|
|
202
|
-
const MAX_SILK_WORK_MS = 3e4;
|
|
203
211
|
const SILK_FRAME_MS = 20;
|
|
204
212
|
const SILK_HEADER = Buffer.from("#!SILK_V3");
|
|
205
213
|
const ENCODE_SAMPLE_RATES = /* @__PURE__ */ new Set([
|
|
@@ -272,12 +280,67 @@ function consumeSilkChunk(scan, chunk) {
|
|
|
272
280
|
assertAudioDuration(scan.duration);
|
|
273
281
|
}
|
|
274
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;
|
|
275
338
|
/** silk-wasm 的 Promise 内部运行同步 WASM;取消时等待执行它的 Worker 退出。 */
|
|
276
339
|
async function runSilk(mode, data, sampleRate, signal) {
|
|
277
340
|
checkMediaSignal(signal);
|
|
278
341
|
const source = import.meta.url.endsWith(".ts");
|
|
279
342
|
try {
|
|
280
|
-
const worker = new Worker(new URL(source ? "
|
|
343
|
+
const worker = new Worker(new URL(source ? "../silk-worker.mts" : "./silk-worker.mjs", import.meta.url), {
|
|
281
344
|
execArgv: source ? ["--experimental-strip-types"] : [],
|
|
282
345
|
workerData: {
|
|
283
346
|
mode,
|
|
@@ -316,38 +379,7 @@ async function runSilk(mode, data, sampleRate, signal) {
|
|
|
316
379
|
throw new MediaError("SILK 编解码失败", { cause: error });
|
|
317
380
|
}
|
|
318
381
|
}
|
|
319
|
-
|
|
320
|
-
assertSampleRate(sampleRate, DECODE_SAMPLE_RATES);
|
|
321
|
-
checkMediaSignal(signal);
|
|
322
|
-
const buffer = await readBoundedMediaFile(await localMediaPath(input, MAX_AUDIO_INPUT_BYTES), MAX_AUDIO_INPUT_BYTES, signal);
|
|
323
|
-
const header = silkHeaderLength(buffer);
|
|
324
|
-
if (header === 0) throw new MediaError(`不是有效的 SILK 文件: ${input}`);
|
|
325
|
-
await silkDuration([buffer], header, signal);
|
|
326
|
-
const result = await runSilk("decode", buffer, sampleRate, signal);
|
|
327
|
-
assertAudioDuration(result.duration);
|
|
328
|
-
if (result.data.byteLength === 0 || result.data.byteLength > 600 * sampleRate * 2) throw new MediaError("解码 PCM 超出大小限制或为空");
|
|
329
|
-
return result;
|
|
330
|
-
}
|
|
331
|
-
/** 解码 SILK 音频为 PCM(pcm_s16le)。 */
|
|
332
|
-
async function decodeSilkToPcm(input, sampleRate = SILK_SAMPLE_RATE, { signal } = {}) {
|
|
333
|
-
const result = await decodeAudio(input, sampleRate, signal);
|
|
334
|
-
const pcmPath = replaceExt(input, ".pcm");
|
|
335
|
-
await publishAudio(input, pcmPath, [result.data], signal);
|
|
336
|
-
return {
|
|
337
|
-
pcmPath,
|
|
338
|
-
durationMs: result.duration
|
|
339
|
-
};
|
|
340
|
-
}
|
|
341
|
-
/** 解码 SILK 为可播放 WAV,返回的文件由调用方管理。 */
|
|
342
|
-
async function decodeSilkToWav(input, { sampleRate = SILK_SAMPLE_RATE, outDir, signal } = {}) {
|
|
343
|
-
const result = await decodeAudio(input, sampleRate, signal);
|
|
344
|
-
const wavPath = join(outDir ?? dirname(input), replaceExt(basename(input), ".wav"));
|
|
345
|
-
await publishAudio(input, wavPath, [wavHeader(result.data.byteLength, sampleRate), result.data], signal);
|
|
346
|
-
return {
|
|
347
|
-
wavPath,
|
|
348
|
-
durationMs: result.duration
|
|
349
|
-
};
|
|
350
|
-
}
|
|
382
|
+
// src/audio/wav-codec.ts
|
|
351
383
|
function wavHeader(bytes, sampleRate) {
|
|
352
384
|
const header = Buffer.alloc(44);
|
|
353
385
|
header.write("RIFF", 0, "ascii");
|
|
@@ -364,17 +396,6 @@ function wavHeader(bytes, sampleRate) {
|
|
|
364
396
|
header.writeUInt32LE(bytes, 40);
|
|
365
397
|
return header;
|
|
366
398
|
}
|
|
367
|
-
async function publishAudio(input, output, chunks, signal) {
|
|
368
|
-
const source = resolve(input);
|
|
369
|
-
const target = resolve(output);
|
|
370
|
-
if (source === target || process.platform === "win32" && source.toLowerCase() === target.toLowerCase()) throw new MediaError("音频输出不能覆盖输入文件");
|
|
371
|
-
try {
|
|
372
|
-
await publishMediaFile(output, chunks, signal);
|
|
373
|
-
} catch (error) {
|
|
374
|
-
checkMediaSignal(signal);
|
|
375
|
-
throw new MediaError("无法写出音频产物", { cause: error });
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
399
|
function isRiffWave(header) {
|
|
379
400
|
return header.toString("latin1", 0, 4) === "RIFF" && header.toString("latin1", 8, 12) === "WAVE";
|
|
380
401
|
}
|
|
@@ -403,8 +424,43 @@ function monoWavPcm(header, fileSize) {
|
|
|
403
424
|
offset = data + bytes + bytes % 2;
|
|
404
425
|
}
|
|
405
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
|
+
}
|
|
406
460
|
/** 编码音频为 SILK;已通过边界检查的 SILK 原样返回。 */
|
|
407
|
-
async function encodePcmToSilk(input, sampleRate = 0,
|
|
461
|
+
async function encodePcmToSilk(input, sampleRate = 0, options = {}) {
|
|
462
|
+
const { signal, maxOutputBytes, onPcmWritten } = options;
|
|
463
|
+
const limit = mediaOutputLimit(62354432, maxOutputBytes);
|
|
408
464
|
checkMediaSignal(signal);
|
|
409
465
|
const source = await localMediaPath(input, MAX_AUDIO_INPUT_BYTES);
|
|
410
466
|
const prefix = await readMediaPrefix(source, 12, signal);
|
|
@@ -415,51 +471,17 @@ async function encodePcmToSilk(input, sampleRate = 0, { signal } = {}) {
|
|
|
415
471
|
const wav = isRiffWave(prefix);
|
|
416
472
|
const pcm = wav ? monoWavPcm(await readMediaPrefix(source, 524288, signal), (await stat(source)).size) : void 0;
|
|
417
473
|
const directRate = pcm?.sampleRate ?? (wav ? 0 : sampleRate);
|
|
418
|
-
const
|
|
474
|
+
const silkPath = options.outputPath ?? replaceExt(input, ".silk");
|
|
475
|
+
const data = pcm !== void 0 || directRate !== 0 ? await readPcm(source, directRate, pcm, signal) : await normalizeToPcm(source, dirname(silkPath), limit, signal);
|
|
476
|
+
const pcmBytes = directRate === 0 ? data.byteLength : 0;
|
|
477
|
+
if (pcmBytes > 0) onPcmWritten?.(pcmBytes);
|
|
478
|
+
const result = await runSilk("encode", data, directRate || 24e3, signal);
|
|
419
479
|
assertAudioDuration(result.duration);
|
|
420
|
-
if (result.data.byteLength > 33554432
|
|
421
|
-
|
|
480
|
+
if (result.data.byteLength > Math.min(33554432, limit - pcmBytes)) throw new MediaSizeLimitError("SILK 输出超出大小限制");
|
|
481
|
+
if (result.data.byteLength === 0) throw new MediaError("SILK 输出为空");
|
|
422
482
|
await publishAudio(input, silkPath, [result.data], signal);
|
|
423
483
|
return silkPath;
|
|
424
484
|
}
|
|
425
|
-
async function readPcm(source, sampleRate, wav, signal) {
|
|
426
|
-
assertSampleRate(sampleRate, ENCODE_SAMPLE_RATES);
|
|
427
|
-
const file = await readBoundedMediaFile(source, MAX_AUDIO_INPUT_BYTES, signal);
|
|
428
|
-
const data = wav === void 0 ? file : file.subarray(wav.offset, wav.offset + wav.bytes);
|
|
429
|
-
if (data.byteLength % 2 !== 0 || wav !== void 0 && wav.bytes !== data.byteLength) throw new MediaError("PCM 输入帧不完整");
|
|
430
|
-
assertAudioDuration(data.byteLength * 500 / sampleRate);
|
|
431
|
-
return data;
|
|
432
|
-
}
|
|
433
|
-
async function normalizeToPcm(source, signal) {
|
|
434
|
-
const partial = join(dirname(source), `.napuketto-${randomBytes(8).toString("hex")}.pcm`);
|
|
435
|
-
try {
|
|
436
|
-
await writeFfmpegOutput([
|
|
437
|
-
"-nostdin",
|
|
438
|
-
"-v",
|
|
439
|
-
"error",
|
|
440
|
-
...FFMPEG_WORK_OPTIONS,
|
|
441
|
-
...LOCAL_MEDIA_INPUT_OPTIONS,
|
|
442
|
-
"-i",
|
|
443
|
-
source,
|
|
444
|
-
"-map",
|
|
445
|
-
"0:a:0",
|
|
446
|
-
"-ac",
|
|
447
|
-
"1",
|
|
448
|
-
"-ar",
|
|
449
|
-
String(SILK_SAMPLE_RATE),
|
|
450
|
-
"-t",
|
|
451
|
-
String(600.02),
|
|
452
|
-
"-f",
|
|
453
|
-
"s16le"
|
|
454
|
-
], partial, MAX_NORMALIZED_PCM_BYTES, 12e4, signal);
|
|
455
|
-
return await readBoundedMediaFile(partial, MAX_NORMALIZED_PCM_BYTES, signal);
|
|
456
|
-
} catch (error) {
|
|
457
|
-
checkMediaSignal(signal);
|
|
458
|
-
throw new MediaError(`ffmpeg 音频归一化失败: ${source}`, { cause: error });
|
|
459
|
-
} finally {
|
|
460
|
-
await rm(partial, { force: true });
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
485
|
/** 获取 SILK 音频时长。SILK 容器不携带采样率,返回调用方指定值。 */
|
|
464
486
|
async function getSilkInfo(input, sampleRate = SILK_SAMPLE_RATE, { signal } = {}) {
|
|
465
487
|
assertSampleRate(sampleRate, DECODE_SAMPLE_RATES);
|
|
@@ -591,7 +613,7 @@ function createPublicRequest(checkLiteral) {
|
|
|
591
613
|
* 兼容入口仅校验字面地址。公网入口同时校验实际连接的地址。
|
|
592
614
|
*/
|
|
593
615
|
/** 默认大小上限(30MB)。 */
|
|
594
|
-
const
|
|
616
|
+
const DEFAULT_DOWNLOAD_MAX_BYTES = 31457280;
|
|
595
617
|
/** 默认超时(15s)。 */
|
|
596
618
|
const DEFAULT_TIMEOUT_MS = 15e3;
|
|
597
619
|
/** 最大跳转次数(每跳都重新校验目标 URL)。 */
|
|
@@ -760,7 +782,7 @@ async function writeCapped(body, temp, maxBytes, signal) {
|
|
|
760
782
|
const counter = new Transform({ transform(chunk, _encoding, callback) {
|
|
761
783
|
total += chunk.byteLength;
|
|
762
784
|
if (total > maxBytes) {
|
|
763
|
-
callback(new
|
|
785
|
+
callback(new MediaSizeLimitError(`文件超过大小上限(>${maxBytes} 字节)`));
|
|
764
786
|
return;
|
|
765
787
|
}
|
|
766
788
|
callback(null, chunk);
|
|
@@ -793,7 +815,7 @@ async function downloadPublicUrl(url, dest, options = {}) {
|
|
|
793
815
|
}
|
|
794
816
|
async function download(url, dest, options, request) {
|
|
795
817
|
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
796
|
-
const maxBytes = options.maxBytes ??
|
|
818
|
+
const maxBytes = options.maxBytes ?? 31457280;
|
|
797
819
|
const controller = new AbortController();
|
|
798
820
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
799
821
|
timer.unref?.();
|
|
@@ -804,7 +826,7 @@ async function download(url, dest, options, request) {
|
|
|
804
826
|
body = response.body;
|
|
805
827
|
if (response.status < 200 || response.status >= 300) throw new MediaError(`HTTP ${response.status}`);
|
|
806
828
|
const declared = Number(response.headers.get("Content-Length") ?? "0");
|
|
807
|
-
if (declared > maxBytes) throw new
|
|
829
|
+
if (declared > maxBytes) throw new MediaSizeLimitError(`文件超过大小上限(${declared} > ${maxBytes} 字节)`);
|
|
808
830
|
if (body === null) throw new MediaError("响应无 body");
|
|
809
831
|
await mkdir(dirname(dest), { recursive: true });
|
|
810
832
|
const written = await writeCapped(body, temp, maxBytes, controller.signal);
|
|
@@ -983,6 +1005,7 @@ function outputDimensions(source, opts) {
|
|
|
983
1005
|
/** 转码到独占目录。成功后调用方拥有输出文件及其父临时目录,消费结束后负责删除。 */
|
|
984
1006
|
async function transcodeVideo(input, opts = {}) {
|
|
985
1007
|
const { signal } = opts;
|
|
1008
|
+
const limit = mediaOutputLimit(MAX_VIDEO_BYTES, opts.maxOutputBytes);
|
|
986
1009
|
checkMediaSignal(signal);
|
|
987
1010
|
assertTranscodeOptions(opts);
|
|
988
1011
|
const source = await localMediaPath(input, MAX_VIDEO_BYTES);
|
|
@@ -1041,7 +1064,7 @@ async function transcodeVideo(input, opts = {}) {
|
|
|
1041
1064
|
"1000000",
|
|
1042
1065
|
"-f",
|
|
1043
1066
|
"mp4"
|
|
1044
|
-
], output,
|
|
1067
|
+
], output, limit, 3e5, signal);
|
|
1045
1068
|
const converted = await probeVideo(output, signal, true);
|
|
1046
1069
|
if (converted.width !== width || converted.height !== height || converted.codec !== "h264" || typeof converted.format !== "string" || !converted.format.split(",").includes("mp4") || !Number.isSafeInteger(converted.packets) || converted.packets === 0 || converted.packets > maxFrames) throw new MediaError("转码产物的封装、尺寸、编码或帧数无效");
|
|
1047
1070
|
if (opts.fps !== void 0 && Math.abs(converted.fps - opts.fps) > opts.fps / 1e3) throw new MediaError("转码产物帧率与请求不符");
|
|
@@ -1067,14 +1090,14 @@ async function getVideoInfo(input, { signal } = {}) {
|
|
|
1067
1090
|
};
|
|
1068
1091
|
}
|
|
1069
1092
|
/** 抽首帧至调用者指定路径。失败时保留原目标。 */
|
|
1070
|
-
async function extractVideoFrame(input, outputPath, { signal } = {}) {
|
|
1093
|
+
async function extractVideoFrame(input, outputPath, { signal, maxOutputBytes } = {}) {
|
|
1094
|
+
const limit = mediaOutputLimit(MAX_THUMB_BYTES, maxOutputBytes);
|
|
1071
1095
|
checkMediaSignal(signal);
|
|
1072
1096
|
const source = await localMediaPath(input, MAX_VIDEO_BYTES);
|
|
1073
1097
|
const requestedTarget = resolve(outputPath);
|
|
1074
1098
|
const target = join(await realpath(dirname(requestedTarget)), basename(requestedTarget));
|
|
1075
1099
|
if (source === target || process.platform === "win32" && source.toLowerCase() === target.toLowerCase()) throw new MediaError("抽帧输出不能覆盖输入文件");
|
|
1076
|
-
const
|
|
1077
|
-
const output = join(dir, "frame.png");
|
|
1100
|
+
const output = join(dirname(target), `media.png.part-${process.pid}-${randomUUID()}`);
|
|
1078
1101
|
try {
|
|
1079
1102
|
await writeFfmpegOutput([
|
|
1080
1103
|
"-nostdin",
|
|
@@ -1096,7 +1119,7 @@ async function extractVideoFrame(input, outputPath, { signal } = {}) {
|
|
|
1096
1119
|
"2",
|
|
1097
1120
|
"-f",
|
|
1098
1121
|
"image2pipe"
|
|
1099
|
-
], output,
|
|
1122
|
+
], output, limit, 3e4, signal);
|
|
1100
1123
|
const header = await readMediaPrefix(output, 24, signal);
|
|
1101
1124
|
if (header.length !== 24 || !header.subarray(0, 8).equals(PNG_SIGNATURE) || header.toString("latin1", 12, 16) !== "IHDR") throw new MediaError("抽帧产物不是有效的 PNG");
|
|
1102
1125
|
assertDimensions(header.readUInt32BE(16), header.readUInt32BE(20));
|
|
@@ -1107,10 +1130,7 @@ async function extractVideoFrame(input, outputPath, { signal } = {}) {
|
|
|
1107
1130
|
if (error instanceof MediaError) throw error;
|
|
1108
1131
|
throw new MediaError(`ffmpeg 不可用或抽帧失败: ${input}`, { cause: error });
|
|
1109
1132
|
} finally {
|
|
1110
|
-
await rm(
|
|
1111
|
-
recursive: true,
|
|
1112
|
-
force: true
|
|
1113
|
-
});
|
|
1133
|
+
await rm(output, { force: true });
|
|
1114
1134
|
}
|
|
1115
1135
|
}
|
|
1116
|
-
export { MAX_AUDIO_INPUT_BYTES, MAX_AUDIO_SECONDS, MediaError, SILK_SAMPLE_RATE, decodeSilkToPcm, decodeSilkToWav, detectFileType, downloadPublicUrl, downloadUrl, encodePcmToSilk, extractVideoFrame, getImageSize, getSilkInfo, getVideoInfo, inferExtension, transcodeVideo };
|
|
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 };
|
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.
|
|
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": ">=
|
|
31
|
+
"node": ">=24.11.0"
|
|
32
32
|
},
|
|
33
33
|
"sideEffects": false,
|
|
34
34
|
"publishConfig": {
|