@napuketto/media 0.0.1
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/LICENSE +21 -0
- package/dist/index.d.mts +74 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +182 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +32 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 睦 <oppenheymu@gmail.com>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
//#region src/types.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* @napuketto/media 统一返回结构(ADR-011)
|
|
4
|
+
*
|
|
5
|
+
* 媒体编解码与文件识别的公共类型:图片尺寸、文件类型、音频/视频信息。
|
|
6
|
+
*/
|
|
7
|
+
/** 图片尺寸(宽高,像素)。 */
|
|
8
|
+
interface ImageSize {
|
|
9
|
+
width: number;
|
|
10
|
+
height: number;
|
|
11
|
+
}
|
|
12
|
+
/** 文件类型识别结果。 */
|
|
13
|
+
interface FileTypeResult {
|
|
14
|
+
/** 扩展名(不带点,如 "png" / "mp3")。 */
|
|
15
|
+
ext: string;
|
|
16
|
+
/** MIME 类型,如 "image/png" / "audio/mpeg"。 */
|
|
17
|
+
mime: string;
|
|
18
|
+
}
|
|
19
|
+
/** 音频信息。 */
|
|
20
|
+
interface AudioInfo {
|
|
21
|
+
/** 时长(毫秒)。 */
|
|
22
|
+
durationMs: number;
|
|
23
|
+
/** 采样率(Hz),如 24000。 */
|
|
24
|
+
sampleRate: number;
|
|
25
|
+
}
|
|
26
|
+
/** 视频信息。 */
|
|
27
|
+
interface VideoInfo {
|
|
28
|
+
width: number;
|
|
29
|
+
height: number;
|
|
30
|
+
/** 时长(毫秒)。 */
|
|
31
|
+
durationMs: number;
|
|
32
|
+
}
|
|
33
|
+
/** 视频转码选项。 */
|
|
34
|
+
interface TranscodeOptions {
|
|
35
|
+
width?: number;
|
|
36
|
+
height?: number;
|
|
37
|
+
fps?: number;
|
|
38
|
+
}
|
|
39
|
+
/** SILK 解码产物(pcm_s16le)。 */
|
|
40
|
+
interface DecodedAudio {
|
|
41
|
+
/** PCM 文件路径。 */
|
|
42
|
+
pcmPath: string;
|
|
43
|
+
/** 时长(毫秒)。 */
|
|
44
|
+
durationMs: number;
|
|
45
|
+
}
|
|
46
|
+
/** 无法识别的文件类型(file-type 返回 undefined 时)。 */
|
|
47
|
+
declare class MediaError extends Error {
|
|
48
|
+
constructor(message: string, options?: ErrorOptions);
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/audio.d.ts
|
|
52
|
+
/** 解码 SILK 音频为 PCM(pcm_s16le)。 */
|
|
53
|
+
declare function decodeSilkToPcm(input: string, sampleRate?: number): Promise<DecodedAudio>;
|
|
54
|
+
/** 编码 PCM / WAV 为 SILK 文件(返回输出路径,输出紧随输入文件)。 */
|
|
55
|
+
declare function encodePcmToSilk(input: string, sampleRate?: number): Promise<string>;
|
|
56
|
+
/** 获取 SILK 音频信息(时长 / 采样率)。 */
|
|
57
|
+
declare function getSilkInfo(input: string, sampleRate?: number): Promise<AudioInfo>;
|
|
58
|
+
/** SILK 默认采样率(Hz)。 */
|
|
59
|
+
declare const SILK_SAMPLE_RATE = 24000;
|
|
60
|
+
//#endregion
|
|
61
|
+
//#region src/image.d.ts
|
|
62
|
+
/** 读取图片尺寸(image-size 同步 API,内部读文件 + 计算)。 */
|
|
63
|
+
declare function getImageSize(input: string): Promise<ImageSize>;
|
|
64
|
+
/** 检测文件类型(魔数识别,返回 undefined 时抛 MediaError)。 */
|
|
65
|
+
declare function detectFileType(input: string): Promise<FileTypeResult>;
|
|
66
|
+
//#endregion
|
|
67
|
+
//#region src/video.d.ts
|
|
68
|
+
/** 转码:按选项输出到替换扩展名后的路径(.mp4)。 */
|
|
69
|
+
declare function transcodeVideo(input: string, opts?: TranscodeOptions): Promise<string>;
|
|
70
|
+
/** 读取视频宽高与时长(ffprobe JSON 输出解析)。 */
|
|
71
|
+
declare function getVideoInfo(input: string): Promise<VideoInfo>;
|
|
72
|
+
//#endregion
|
|
73
|
+
export { type AudioInfo, type DecodedAudio, type FileTypeResult, type ImageSize, MediaError, SILK_SAMPLE_RATE, type TranscodeOptions, type VideoInfo, decodeSilkToPcm, detectFileType, encodePcmToSilk, getImageSize, getSilkInfo, getVideoInfo, transcodeVideo };
|
|
74
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/audio.ts","../src/image.ts","../src/video.ts"],"mappings":";;;;;;;UAOiB;EACb;EACA;;;UAIa;;EAEb;;EAEA;;;UAIa;;EAEb;;EAEA;;;UAIa;EACb;EACA;;EAEA;;;UAIa;EACb;EACA;EACA;;;UAIa;;EAEb;;EAEA;;;cAIS,mBAAmB;EAC5B,YAAY,iBAAiB,UAAU;;;;;iBCpBrB,gBAClB,eACA,sBACD,QAAQ;;iBAYW,gBAAgB,eAAe,sBAAiB;;iBAehD,YAClB,eACA,sBACD,QAAQ;;cASE;;;;iBC9DS,aAAa,gBAAgB,QAAQ;;iBAOrC,eAAe,gBAAgB,QAAQ;;;;iBCwBvC,eAAe,eAAe,OAAM,mBAAwB;;iBAwB5D,aAAa,gBAAgB,QAAQ"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { decode, encode, getDuration, isSilk, isWav } from "silk-wasm";
|
|
5
|
+
import { fileTypeFromFile } from "file-type";
|
|
6
|
+
import { imageSize } from "image-size";
|
|
7
|
+
import { execa } from "execa";
|
|
8
|
+
//#region src/types.ts
|
|
9
|
+
/** 无法识别的文件类型(file-type 返回 undefined 时)。 */
|
|
10
|
+
var MediaError = class extends Error {
|
|
11
|
+
constructor(message, options) {
|
|
12
|
+
super(message, options);
|
|
13
|
+
this.name = "MediaError";
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/audio.ts
|
|
18
|
+
/**
|
|
19
|
+
* 音频(silk-wasm 编解码)
|
|
20
|
+
*
|
|
21
|
+
* - `decodeSilkToPcm`:SILK → pcm_s16le 文件 + 时长
|
|
22
|
+
* - `encodePcmToSilk`:WAV 或单声道 pcm_s16le → SILK 文件
|
|
23
|
+
*
|
|
24
|
+
* silk-wasm 3.x 输入为 ArrayBuffer(非文件路径),需自行读文件 / 写文件。
|
|
25
|
+
* `encode` 的 sampleRate 在输入为 WAV 时可传 0 自动识别。
|
|
26
|
+
*/
|
|
27
|
+
/** 替换文件扩展名(保持目录不变,父目录存在性由调用方保证)。 */
|
|
28
|
+
function replaceExt$1(input, ext) {
|
|
29
|
+
const dir = dirname(input);
|
|
30
|
+
const base = input.slice(dir.length + 1);
|
|
31
|
+
const dot = base.lastIndexOf(".");
|
|
32
|
+
let stem;
|
|
33
|
+
if (dot > 0) stem = base.slice(0, dot);
|
|
34
|
+
else stem = base;
|
|
35
|
+
const out = `${dir}/${stem}${ext}`;
|
|
36
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
/** 解码 SILK 音频为 PCM(pcm_s16le)。 */
|
|
40
|
+
async function decodeSilkToPcm(input, sampleRate = SILK_SAMPLE_RATE) {
|
|
41
|
+
const buffer = await readFile(input);
|
|
42
|
+
if (!isSilk(buffer)) throw new MediaError(`不是有效的 SILK 文件: ${input}`);
|
|
43
|
+
const result = await decode(buffer, sampleRate);
|
|
44
|
+
const pcmPath = replaceExt$1(input, ".pcm");
|
|
45
|
+
await writeFile(pcmPath, result.data);
|
|
46
|
+
return {
|
|
47
|
+
pcmPath,
|
|
48
|
+
durationMs: result.duration
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** 编码 PCM / WAV 为 SILK 文件(返回输出路径,输出紧随输入文件)。 */
|
|
52
|
+
async function encodePcmToSilk(input, sampleRate = 0) {
|
|
53
|
+
const buffer = await readFile(input);
|
|
54
|
+
let rate;
|
|
55
|
+
if (isWav(buffer)) rate = 0;
|
|
56
|
+
else rate = sampleRate;
|
|
57
|
+
const result = await encode(buffer, rate);
|
|
58
|
+
const silkPath = replaceExt$1(input, ".silk");
|
|
59
|
+
await writeFile(silkPath, result.data);
|
|
60
|
+
return silkPath;
|
|
61
|
+
}
|
|
62
|
+
/** 获取 SILK 音频信息(时长 / 采样率)。 */
|
|
63
|
+
async function getSilkInfo(input, sampleRate = SILK_SAMPLE_RATE) {
|
|
64
|
+
const buffer = await readFile(input);
|
|
65
|
+
if (!isSilk(buffer)) throw new MediaError(`不是有效的 SILK 文件: ${input}`);
|
|
66
|
+
return {
|
|
67
|
+
durationMs: getDuration(buffer),
|
|
68
|
+
sampleRate
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/** SILK 默认采样率(Hz)。 */
|
|
72
|
+
const SILK_SAMPLE_RATE = 24e3;
|
|
73
|
+
//#endregion
|
|
74
|
+
//#region src/image.ts
|
|
75
|
+
/**
|
|
76
|
+
* 图片与文件识别
|
|
77
|
+
*
|
|
78
|
+
* - `getImageSize`:image-size(读取 Uint8Array,同步计算)
|
|
79
|
+
* - `detectFileType`:file-type(按文件路径检测魔数)
|
|
80
|
+
*/
|
|
81
|
+
/** 读取图片尺寸(image-size 同步 API,内部读文件 + 计算)。 */
|
|
82
|
+
async function getImageSize(input) {
|
|
83
|
+
const buffer = await readFile(input);
|
|
84
|
+
const size = imageSize(buffer);
|
|
85
|
+
return {
|
|
86
|
+
width: size.width,
|
|
87
|
+
height: size.height
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/** 检测文件类型(魔数识别,返回 undefined 时抛 MediaError)。 */
|
|
91
|
+
async function detectFileType(input) {
|
|
92
|
+
const result = await fileTypeFromFile(input);
|
|
93
|
+
if (result === void 0) throw new MediaError(`无法识别的文件类型: ${input}`);
|
|
94
|
+
return {
|
|
95
|
+
ext: result.ext,
|
|
96
|
+
mime: result.mime
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
//#endregion
|
|
100
|
+
//#region src/video.ts
|
|
101
|
+
/**
|
|
102
|
+
* 视频(execa 调用外部 ffmpeg 二进制)
|
|
103
|
+
*
|
|
104
|
+
* ffmpeg 由 execa 以子进程方式调用(非 node 内置),依赖系统 PATH 中的 ffmpeg。
|
|
105
|
+
* - `transcodeVideo`:转码 / 缩放 / 帧率
|
|
106
|
+
* - `getVideoInfo`:解析 ffprobe 输出取宽高与时长
|
|
107
|
+
*/
|
|
108
|
+
const MS_PER_SECOND = 1e3;
|
|
109
|
+
/** 替换扩展名(保持目录,父目录由调用方保证存在)。 */
|
|
110
|
+
function replaceExt(input, ext) {
|
|
111
|
+
const slash = input.lastIndexOf("/");
|
|
112
|
+
const backslash = input.lastIndexOf("\\");
|
|
113
|
+
const dirEnd = Math.max(slash, backslash);
|
|
114
|
+
let dir;
|
|
115
|
+
let base;
|
|
116
|
+
if (dirEnd >= 0) {
|
|
117
|
+
dir = input.slice(0, dirEnd + 1);
|
|
118
|
+
base = input.slice(dirEnd + 1);
|
|
119
|
+
} else {
|
|
120
|
+
dir = "";
|
|
121
|
+
base = input;
|
|
122
|
+
}
|
|
123
|
+
const dot = base.lastIndexOf(".");
|
|
124
|
+
let stem;
|
|
125
|
+
if (dot > 0) stem = base.slice(0, dot);
|
|
126
|
+
else stem = base;
|
|
127
|
+
return `${dir}${stem}${ext}`;
|
|
128
|
+
}
|
|
129
|
+
/** 转码:按选项输出到替换扩展名后的路径(.mp4)。 */
|
|
130
|
+
async function transcodeVideo(input, opts = {}) {
|
|
131
|
+
const args = [
|
|
132
|
+
"-y",
|
|
133
|
+
"-i",
|
|
134
|
+
input
|
|
135
|
+
];
|
|
136
|
+
if (opts.width !== void 0 && opts.height !== void 0) args.push("-vf", `scale=${opts.width}:${opts.height}`);
|
|
137
|
+
else if (opts.width !== void 0) args.push("-vf", `scale=${opts.width}:-2`);
|
|
138
|
+
else if (opts.height !== void 0) args.push("-vf", `scale=-2:${opts.height}`);
|
|
139
|
+
if (opts.fps !== void 0) args.push("-r", String(opts.fps));
|
|
140
|
+
const output = replaceExt(input, ".mp4");
|
|
141
|
+
args.push("-c:v", "libx264", "-preset", "fast", output);
|
|
142
|
+
try {
|
|
143
|
+
await execa("ffmpeg", args, { reject: false });
|
|
144
|
+
} catch (err) {
|
|
145
|
+
throw new MediaError(`ffmpeg 转码失败: ${input}`, { cause: err });
|
|
146
|
+
}
|
|
147
|
+
return output;
|
|
148
|
+
}
|
|
149
|
+
/** 读取视频宽高与时长(ffprobe JSON 输出解析)。 */
|
|
150
|
+
async function getVideoInfo(input) {
|
|
151
|
+
let parsed;
|
|
152
|
+
try {
|
|
153
|
+
const result = await execa("ffprobe", [
|
|
154
|
+
"-v",
|
|
155
|
+
"error",
|
|
156
|
+
"-print_format",
|
|
157
|
+
"json",
|
|
158
|
+
"-show_format",
|
|
159
|
+
"-show_streams",
|
|
160
|
+
input
|
|
161
|
+
], { reject: false });
|
|
162
|
+
if (result.exitCode !== 0) throw new MediaError(`ffprobe 读取失败: ${input}(exit ${result.exitCode})`);
|
|
163
|
+
parsed = JSON.parse(result.stdout);
|
|
164
|
+
} catch (err) {
|
|
165
|
+
if (err instanceof MediaError) throw err;
|
|
166
|
+
throw new MediaError(`ffprobe 读取失败: ${input}`, { cause: err });
|
|
167
|
+
}
|
|
168
|
+
const videoStream = parsed.streams?.find((s) => s["codec_type"] === "video");
|
|
169
|
+
const width = videoStream?.width;
|
|
170
|
+
const height = videoStream?.height;
|
|
171
|
+
const durationStr = parsed.format?.duration;
|
|
172
|
+
if (width === void 0 || height === void 0 || durationStr === void 0) throw new MediaError(`ffprobe 未取到视频信息: ${input}`);
|
|
173
|
+
return {
|
|
174
|
+
width,
|
|
175
|
+
height,
|
|
176
|
+
durationMs: Math.round(Number(durationStr) * MS_PER_SECOND)
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
//#endregion
|
|
180
|
+
export { MediaError, SILK_SAMPLE_RATE, decodeSilkToPcm, detectFileType, encodePcmToSilk, getImageSize, getSilkInfo, getVideoInfo, transcodeVideo };
|
|
181
|
+
|
|
182
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["replaceExt"],"sources":["../src/types.ts","../src/audio.ts","../src/image.ts","../src/video.ts"],"sourcesContent":["/**\n * @napuketto/media 统一返回结构(ADR-011)\n *\n * 媒体编解码与文件识别的公共类型:图片尺寸、文件类型、音频/视频信息。\n */\n\n/** 图片尺寸(宽高,像素)。 */\nexport interface ImageSize {\n width: number;\n height: number;\n}\n\n/** 文件类型识别结果。 */\nexport interface FileTypeResult {\n /** 扩展名(不带点,如 \"png\" / \"mp3\")。 */\n ext: string;\n /** MIME 类型,如 \"image/png\" / \"audio/mpeg\"。 */\n mime: string;\n}\n\n/** 音频信息。 */\nexport interface AudioInfo {\n /** 时长(毫秒)。 */\n durationMs: number;\n /** 采样率(Hz),如 24000。 */\n sampleRate: number;\n}\n\n/** 视频信息。 */\nexport interface VideoInfo {\n width: number;\n height: number;\n /** 时长(毫秒)。 */\n durationMs: number;\n}\n\n/** 视频转码选项。 */\nexport interface TranscodeOptions {\n width?: number;\n height?: number;\n fps?: number;\n}\n\n/** SILK 解码产物(pcm_s16le)。 */\nexport interface DecodedAudio {\n /** PCM 文件路径。 */\n pcmPath: string;\n /** 时长(毫秒)。 */\n durationMs: number;\n}\n\n/** 无法识别的文件类型(file-type 返回 undefined 时)。 */\nexport class MediaError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"MediaError\";\n }\n}\n","/**\n * 音频(silk-wasm 编解码)\n *\n * - `decodeSilkToPcm`:SILK → pcm_s16le 文件 + 时长\n * - `encodePcmToSilk`:WAV 或单声道 pcm_s16le → SILK 文件\n *\n * silk-wasm 3.x 输入为 ArrayBuffer(非文件路径),需自行读文件 / 写文件。\n * `encode` 的 sampleRate 在输入为 WAV 时可传 0 自动识别。\n */\nimport { mkdirSync } from \"node:fs\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { decode, encode, getDuration, isSilk, isWav } from \"silk-wasm\";\nimport type { AudioInfo, DecodedAudio } from \"./types.js\";\nimport { MediaError } from \"./types.js\";\n\n/** 替换文件扩展名(保持目录不变,父目录存在性由调用方保证)。 */\nfunction replaceExt(input: string, ext: string): string {\n const dir = dirname(input);\n const base = input.slice(dir.length + 1);\n const dot = base.lastIndexOf(\".\");\n let stem: string;\n if (dot > 0) {\n stem = base.slice(0, dot);\n } else {\n stem = base;\n }\n const out = `${dir}/${stem}${ext}`;\n mkdirSync(dirname(out), { recursive: true });\n return out;\n}\n\n/** 解码 SILK 音频为 PCM(pcm_s16le)。 */\nexport async function decodeSilkToPcm(\n input: string,\n sampleRate = SILK_SAMPLE_RATE,\n): Promise<DecodedAudio> {\n const buffer = await readFile(input);\n if (!isSilk(buffer)) {\n throw new MediaError(`不是有效的 SILK 文件: ${input}`);\n }\n const result = await decode(buffer, sampleRate);\n const pcmPath = replaceExt(input, \".pcm\");\n await writeFile(pcmPath, result.data);\n return { pcmPath, durationMs: result.duration };\n}\n\n/** 编码 PCM / WAV 为 SILK 文件(返回输出路径,输出紧随输入文件)。 */\nexport async function encodePcmToSilk(input: string, sampleRate = 0): Promise<string> {\n const buffer = await readFile(input);\n let rate: number;\n if (isWav(buffer)) {\n rate = 0; // WAV 头部自带采样率\n } else {\n rate = sampleRate;\n }\n const result = await encode(buffer, rate);\n const silkPath = replaceExt(input, \".silk\");\n await writeFile(silkPath, result.data);\n return silkPath;\n}\n\n/** 获取 SILK 音频信息(时长 / 采样率)。 */\nexport async function getSilkInfo(\n input: string,\n sampleRate = SILK_SAMPLE_RATE,\n): Promise<AudioInfo> {\n const buffer = await readFile(input);\n if (!isSilk(buffer)) {\n throw new MediaError(`不是有效的 SILK 文件: ${input}`);\n }\n return { durationMs: getDuration(buffer), sampleRate };\n}\n\n/** SILK 默认采样率(Hz)。 */\nexport const SILK_SAMPLE_RATE = 24_000;\n","/**\n * 图片与文件识别\n *\n * - `getImageSize`:image-size(读取 Uint8Array,同步计算)\n * - `detectFileType`:file-type(按文件路径检测魔数)\n */\nimport { readFile } from \"node:fs/promises\";\nimport { fileTypeFromFile } from \"file-type\";\nimport { imageSize } from \"image-size\";\nimport type { FileTypeResult, ImageSize } from \"./types.js\";\nimport { MediaError } from \"./types.js\";\n\n/** 读取图片尺寸(image-size 同步 API,内部读文件 + 计算)。 */\nexport async function getImageSize(input: string): Promise<ImageSize> {\n const buffer = await readFile(input);\n const size = imageSize(buffer);\n return { width: size.width, height: size.height };\n}\n\n/** 检测文件类型(魔数识别,返回 undefined 时抛 MediaError)。 */\nexport async function detectFileType(input: string): Promise<FileTypeResult> {\n const result = await fileTypeFromFile(input);\n if (result === undefined) {\n throw new MediaError(`无法识别的文件类型: ${input}`);\n }\n return { ext: result.ext, mime: result.mime };\n}\n","/**\n * 视频(execa 调用外部 ffmpeg 二进制)\n *\n * ffmpeg 由 execa 以子进程方式调用(非 node 内置),依赖系统 PATH 中的 ffmpeg。\n * - `transcodeVideo`:转码 / 缩放 / 帧率\n * - `getVideoInfo`:解析 ffprobe 输出取宽高与时长\n */\nimport { execa } from \"execa\";\nimport type { TranscodeOptions, VideoInfo } from \"./types.js\";\nimport { MediaError } from \"./types.js\";\n\nconst MS_PER_SECOND = 1000;\n\n/** ffprobe JSON 输出的解析形状。 */\ninterface FfprobeParse {\n streams?: Array<{ width?: number; height?: number; [\"codec_type\"]?: string }>;\n format?: { duration?: string };\n}\n\n/** 替换扩展名(保持目录,父目录由调用方保证存在)。 */\nfunction replaceExt(input: string, ext: string): string {\n const slash = input.lastIndexOf(\"/\");\n const backslash = input.lastIndexOf(\"\\\\\");\n const dirEnd = Math.max(slash, backslash);\n let dir: string;\n let base: string;\n if (dirEnd >= 0) {\n dir = input.slice(0, dirEnd + 1);\n base = input.slice(dirEnd + 1);\n } else {\n dir = \"\";\n base = input;\n }\n const dot = base.lastIndexOf(\".\");\n let stem: string;\n if (dot > 0) {\n stem = base.slice(0, dot);\n } else {\n stem = base;\n }\n return `${dir}${stem}${ext}`;\n}\n\n/** 转码:按选项输出到替换扩展名后的路径(.mp4)。 */\nexport async function transcodeVideo(input: string, opts: TranscodeOptions = {}): Promise<string> {\n const args = [\"-y\", \"-i\", input];\n if (opts.width !== undefined && opts.height !== undefined) {\n args.push(\"-vf\", `scale=${opts.width}:${opts.height}`);\n } else if (opts.width !== undefined) {\n args.push(\"-vf\", `scale=${opts.width}:-2`);\n } else if (opts.height !== undefined) {\n args.push(\"-vf\", `scale=-2:${opts.height}`);\n }\n if (opts.fps !== undefined) {\n args.push(\"-r\", String(opts.fps));\n }\n const output = replaceExt(input, \".mp4\");\n args.push(\"-c:v\", \"libx264\", \"-preset\", \"fast\", output);\n\n try {\n await execa(\"ffmpeg\", args, { reject: false });\n } catch (err) {\n throw new MediaError(`ffmpeg 转码失败: ${input}`, { cause: err });\n }\n return output;\n}\n\n/** 读取视频宽高与时长(ffprobe JSON 输出解析)。 */\nexport async function getVideoInfo(input: string): Promise<VideoInfo> {\n let parsed: FfprobeParse;\n try {\n const result = await execa(\n \"ffprobe\",\n [\"-v\", \"error\", \"-print_format\", \"json\", \"-show_format\", \"-show_streams\", input],\n { reject: false },\n );\n if (result.exitCode !== 0) {\n throw new MediaError(`ffprobe 读取失败: ${input}(exit ${result.exitCode})`);\n }\n parsed = JSON.parse(result.stdout) as FfprobeParse;\n } catch (err) {\n if (err instanceof MediaError) {\n throw err;\n }\n throw new MediaError(`ffprobe 读取失败: ${input}`, { cause: err });\n }\n\n const videoStream = parsed.streams?.find((s) => s[\"codec_type\"] === \"video\");\n const width = videoStream?.width;\n const height = videoStream?.height;\n const durationStr = parsed.format?.duration;\n if (width === undefined || height === undefined || durationStr === undefined) {\n throw new MediaError(`ffprobe 未取到视频信息: ${input}`);\n }\n return { width, height, durationMs: Math.round(Number(durationStr) * MS_PER_SECOND) };\n}\n"],"mappings":";;;;;;;;;AAoDA,IAAa,aAAb,cAAgC,MAAM;CAClC,YAAY,SAAiB,SAAwB;EACjD,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CAChB;AACJ;;;;;;;;;;;;;ACxCA,SAASA,aAAW,OAAe,KAAqB;CACpD,MAAM,MAAM,QAAQ,KAAK;CACzB,MAAM,OAAO,MAAM,MAAM,IAAI,SAAS,CAAC;CACvC,MAAM,MAAM,KAA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AAK;EACV,MAAM,IAAI,WAAW,gBAAgB,SAAS,EAAE,OAAO,IAAI,CAAC;CAChE;CACA,OAAO;AACX;;AAGA,eAAsB,aAAa,OAAmC;CAClE,IAAI;CACJ,IAAI;EACA,MAAM,SAAS,MAAM,MACjB,WACA;GAAC;GAAM;GAAS;GAAiB;GAAQ;GAAgB;GAAiB;EAAK,GAC/E,EAAE,QAAQ,MAAM,CACpB;EACA,IAAI,OAAO,aAAa,GACpB,MAAM,IAAI,WAAW,iBAAiB,MAAM,QAAQ,OAAO,SAAS,EAAE;EAE1E,SAAS,KAAK,MAAM,OAAO,MAAM;CACrC,SAAS,KAAK;EACV,IAAI,eAAe,YACf,MAAM;EAEV,MAAM,IAAI,WAAW,iBAAiB,SAAS,EAAE,OAAO,IAAI,CAAC;CACjE;CAEA,MAAM,cAAc,OAAO,SAAS,MAAM,MAAM,EAAE,kBAAkB,OAAO;CAC3E,MAAM,QAAQ,aAAa;CAC3B,MAAM,SAAS,aAAa;CAC5B,MAAM,cAAc,OAAO,QAAQ;CACnC,IAAI,UAAU,KAAA,KAAa,WAAW,KAAA,KAAa,gBAAgB,KAAA,GAC/D,MAAM,IAAI,WAAW,oBAAoB,OAAO;CAEpD,OAAO;EAAE;EAAO;EAAQ,YAAY,KAAK,MAAM,OAAO,WAAW,IAAI,aAAa;CAAE;AACxF"}
|
package/package.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@napuketto/media",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Media utilities for NapukettoQQ",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"files": [
|
|
7
|
+
"dist"
|
|
8
|
+
],
|
|
9
|
+
"main": "./dist/index.mjs",
|
|
10
|
+
"module": "./dist/index.mjs",
|
|
11
|
+
"types": "./dist/index.d.mts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.mts",
|
|
15
|
+
"import": "./dist/index.mjs"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"tsdown": "^0.22.14"
|
|
20
|
+
},
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"execa": "^10.0.1",
|
|
24
|
+
"file-type": "^22.0.1",
|
|
25
|
+
"image-size": "^2.0.2",
|
|
26
|
+
"silk-wasm": "^3.7.1"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"dev": "tsdown --watch",
|
|
30
|
+
"build": "tsdown"
|
|
31
|
+
}
|
|
32
|
+
}
|