m4k 0.3.1 → 0.3.3
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.
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { type ImageOptions, ProcessedFile } from "@m4k/common";
|
|
2
|
+
import { ffmpeg } from "../util/ffmpeg-processor.js";
|
|
3
|
+
export { ffmpeg };
|
|
2
4
|
export type Format = Required<ImageOptions>["format"];
|
|
3
5
|
export type Fit = Required<Required<ImageOptions>["resize"]>["fit"];
|
|
4
6
|
/**
|
|
@@ -1,8 +1,13 @@
|
|
|
1
|
-
import { ProcessedFile } from "@m4k/common";
|
|
1
|
+
import { ProcessedFile, isImageNoOp } from "@m4k/common";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
2
3
|
import { createReadStream } from "node:fs";
|
|
4
|
+
import { readFile, rm } from "node:fs/promises";
|
|
3
5
|
import sharp from "sharp";
|
|
4
6
|
import { createQueue } from "tasque";
|
|
7
|
+
import { ffmpeg, createTmp, randomId } from "../util/ffmpeg-processor.js";
|
|
5
8
|
import { exhaustAsyncIterableToWritable } from "../util/streams.js";
|
|
9
|
+
export { ffmpeg };
|
|
10
|
+
const imageTmpDir = `${process.env.M4K_TMP_DIR ?? "/tmp/m4k"}/image`;
|
|
6
11
|
/**
|
|
7
12
|
* Process an image.
|
|
8
13
|
* @param input - The input image. Can be a file path, a stream or a blob.
|
|
@@ -11,46 +16,32 @@ import { exhaustAsyncIterableToWritable } from "../util/streams.js";
|
|
|
11
16
|
* @returns An iterable of the processed images.
|
|
12
17
|
*/
|
|
13
18
|
export function processImage(input, opts, { signal } = {}) {
|
|
14
|
-
const sharpInstance = sharp();
|
|
15
19
|
const iterable = imageQueue.iterate(async function* () {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
s = s.resize({
|
|
27
|
-
...resize,
|
|
28
|
-
fit: resize.fit ?? "inside",
|
|
29
|
-
});
|
|
30
|
-
if (keepMetadata)
|
|
31
|
-
s = s.keepMetadata();
|
|
32
|
-
if (keepExif)
|
|
33
|
-
s = s.keepExif();
|
|
34
|
-
if (keepIcc)
|
|
35
|
-
s = s.keepIccProfile();
|
|
36
|
-
if (colorspace)
|
|
37
|
-
s = s.toColorspace(colorspace);
|
|
38
|
-
if (crop) {
|
|
39
|
-
s = s.extract({
|
|
40
|
-
...crop,
|
|
41
|
-
left: crop.left ?? 0,
|
|
42
|
-
top: crop.top ?? 0,
|
|
43
|
-
});
|
|
20
|
+
const optsArr = Array.isArray(opts) ? opts : [opts];
|
|
21
|
+
const resolvedInput = await resolveInput(input);
|
|
22
|
+
const inputExt = detectExt(resolvedInput);
|
|
23
|
+
if (inputExt != null && optsArr.every((o) => isImageNoOp(o, inputExt))) {
|
|
24
|
+
yield { progress: 0 };
|
|
25
|
+
const bytes = await toBytes(resolvedInput);
|
|
26
|
+
for (let i = 0; i < optsArr.length; i++) {
|
|
27
|
+
const ext = optsArr[i].ext ?? optsArr[i].format ?? inputExt;
|
|
28
|
+
yield new ProcessedFile(`file${i + 1}.${ext}`, `image/${ext}`, toAsyncIterable(bytes));
|
|
29
|
+
yield { progress: Math.round(((i + 1) / optsArr.length) * 100) };
|
|
44
30
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
let files;
|
|
34
|
+
try {
|
|
35
|
+
files = await runSharp(resolvedInput, optsArr);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
const png = await ffmpegDecodeToPng(resolvedInput);
|
|
39
|
+
files = await runSharp(png, optsArr);
|
|
40
|
+
}
|
|
49
41
|
yield { progress: 0 };
|
|
50
|
-
for (
|
|
51
|
-
yield
|
|
52
|
-
|
|
53
|
-
yield { progress: Math.round((done / files.length) * 100) };
|
|
42
|
+
for (let i = 0; i < files.length; i++) {
|
|
43
|
+
yield files[i];
|
|
44
|
+
yield { progress: Math.round(((i + 1) / files.length) * 100) };
|
|
54
45
|
}
|
|
55
46
|
}, signal);
|
|
56
47
|
if (!iterable)
|
|
@@ -71,4 +62,125 @@ export const imageQueue = createQueue({
|
|
|
71
62
|
parallelize: Number(process.env.IMAGE_PARALLELIZE ?? 5),
|
|
72
63
|
max: Number(process.env.IMAGE_QUEUE_SIZE ?? 100),
|
|
73
64
|
});
|
|
65
|
+
async function runSharp(input, opts) {
|
|
66
|
+
const sharpInstance = sharp();
|
|
67
|
+
void exhaustAsyncIterableToWritable(toSharpInput(input), sharpInstance);
|
|
68
|
+
return Promise.all(opts.map(async ({ colorspace, crop, format = "avif", ext = format, keepExif, keepIcc, keepMetadata, quality, resize, rotate, }, idx) => {
|
|
69
|
+
let s = sharpInstance.clone();
|
|
70
|
+
s = s.rotate(rotate);
|
|
71
|
+
if (resize)
|
|
72
|
+
s = s.resize({
|
|
73
|
+
...resize,
|
|
74
|
+
fit: resize.fit ?? "inside",
|
|
75
|
+
});
|
|
76
|
+
if (keepMetadata)
|
|
77
|
+
s = s.keepMetadata();
|
|
78
|
+
if (keepExif)
|
|
79
|
+
s = s.keepExif();
|
|
80
|
+
if (keepIcc)
|
|
81
|
+
s = s.keepIccProfile();
|
|
82
|
+
if (colorspace)
|
|
83
|
+
s = s.toColorspace(colorspace);
|
|
84
|
+
if (crop) {
|
|
85
|
+
s = s.extract({
|
|
86
|
+
...crop,
|
|
87
|
+
left: crop.left ?? 0,
|
|
88
|
+
top: crop.top ?? 0,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
s = s.toFormat(ext, { quality });
|
|
92
|
+
const buf = await s.toBuffer();
|
|
93
|
+
return new ProcessedFile(`file${idx + 1}.${ext}`, `image/${ext}`, toAsyncIterable(buf));
|
|
94
|
+
}));
|
|
95
|
+
}
|
|
96
|
+
async function ffmpegDecodeToPng(input) {
|
|
97
|
+
const { mkdir } = await import("node:fs/promises");
|
|
98
|
+
await mkdir(imageTmpDir, { recursive: true });
|
|
99
|
+
const id = randomId();
|
|
100
|
+
const outPath = `${imageTmpDir}/out-${id}.png`;
|
|
101
|
+
const inputPath = typeof input === "string"
|
|
102
|
+
? input
|
|
103
|
+
: await createTmp(imageTmpDir, id, input instanceof Buffer ? toAsyncIterable(input) : input);
|
|
104
|
+
try {
|
|
105
|
+
await new Promise((resolve, reject) => {
|
|
106
|
+
const child = spawn(ffmpeg, ["-y", "-i", inputPath, "-update", "1", "-frames:v", "1", outPath], {
|
|
107
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
108
|
+
});
|
|
109
|
+
let errStr = "";
|
|
110
|
+
child.stderr.on("data", (chunk) => { errStr += chunk.toString(); });
|
|
111
|
+
child.on("close", (code) => {
|
|
112
|
+
if (code !== 0)
|
|
113
|
+
reject(new Error(`ffmpeg exited with code ${code}: ${errStr}`));
|
|
114
|
+
else
|
|
115
|
+
resolve();
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
return await readFile(outPath);
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
await rm(outPath, { force: true });
|
|
122
|
+
if (typeof input !== "string")
|
|
123
|
+
await rm(inputPath, { force: true });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
async function resolveInput(input) {
|
|
127
|
+
if (typeof input === "string" || "stream" in input)
|
|
128
|
+
return input;
|
|
129
|
+
const chunks = [];
|
|
130
|
+
for await (const chunk of input)
|
|
131
|
+
chunks.push(chunk);
|
|
132
|
+
return Buffer.concat(chunks);
|
|
133
|
+
}
|
|
134
|
+
async function toBytes(input) {
|
|
135
|
+
if (input instanceof Buffer)
|
|
136
|
+
return input;
|
|
137
|
+
if (typeof input === "string")
|
|
138
|
+
return readFile(input);
|
|
139
|
+
const blob = input;
|
|
140
|
+
return Buffer.from(await blob.arrayBuffer());
|
|
141
|
+
}
|
|
142
|
+
function toSharpInput(input) {
|
|
143
|
+
if (typeof input === "string")
|
|
144
|
+
return createReadStream(input);
|
|
145
|
+
if ("stream" in input)
|
|
146
|
+
return input.stream();
|
|
147
|
+
return toAsyncIterable(input);
|
|
148
|
+
}
|
|
149
|
+
// eslint-disable-next-line typescript/require-await
|
|
150
|
+
async function* toAsyncIterable(buf) {
|
|
151
|
+
yield new Uint8Array(buf instanceof Buffer ? buf : buf);
|
|
152
|
+
}
|
|
153
|
+
function detectExt(input) {
|
|
154
|
+
if (typeof input === "string") {
|
|
155
|
+
const dot = input.lastIndexOf(".");
|
|
156
|
+
return dot !== -1 ? input.slice(dot + 1).toLowerCase() : null;
|
|
157
|
+
}
|
|
158
|
+
if ("type" in input && input.type) {
|
|
159
|
+
const mime = input.type;
|
|
160
|
+
if (mime === "image/avif" || mime === "image/heif")
|
|
161
|
+
return "avif";
|
|
162
|
+
const slash = mime.lastIndexOf("/");
|
|
163
|
+
return slash !== -1 ? mime.slice(slash + 1).toLowerCase() : null;
|
|
164
|
+
}
|
|
165
|
+
if (input instanceof Buffer && input.byteLength >= 12) {
|
|
166
|
+
if (input[0] === 0xff && input[1] === 0xd8)
|
|
167
|
+
return "jpeg";
|
|
168
|
+
if (input[0] === 0x89 && input[1] === 0x50 && input[2] === 0x4e && input[3] === 0x47)
|
|
169
|
+
return "png";
|
|
170
|
+
if (input[0] === 0x47 && input[1] === 0x49 && input[2] === 0x46)
|
|
171
|
+
return "gif";
|
|
172
|
+
if (input[0] === 0x52 && input[1] === 0x49 && input[2] === 0x46 && input[3] === 0x46 &&
|
|
173
|
+
input[8] === 0x57 && input[9] === 0x45 && input[10] === 0x42 && input[11] === 0x50)
|
|
174
|
+
return "webp";
|
|
175
|
+
// AVIF/HEIF: ftyp box at offset 4, brand at offset 8
|
|
176
|
+
if (input[4] === 0x66 && input[5] === 0x74 && input[6] === 0x79 && input[7] === 0x70) {
|
|
177
|
+
const brand = input.slice(8, 12).toString("ascii");
|
|
178
|
+
if (brand.startsWith("avif") || brand.startsWith("avis"))
|
|
179
|
+
return "avif";
|
|
180
|
+
if (brand.startsWith("heic") || brand.startsWith("heix") || brand.startsWith("mif1"))
|
|
181
|
+
return "heif";
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
74
186
|
//# sourceMappingURL=image-processor.js.map
|
|
@@ -26,4 +26,8 @@ export declare function processFfmpeg(input: string | AsyncIterable<Uint8Array>
|
|
|
26
26
|
* @returns The extension for the given format.
|
|
27
27
|
*/
|
|
28
28
|
export declare function getExtension(format: string): string;
|
|
29
|
+
declare function createTmp(tmpDir: string, id: string, input: AsyncIterable<Uint8Array<ArrayBufferLike>> | Blob): Promise<string>;
|
|
30
|
+
declare function randomId(): string;
|
|
31
|
+
export declare const ffmpeg: string;
|
|
32
|
+
export { createTmp, randomId };
|
|
29
33
|
//# sourceMappingURL=ffmpeg-processor.d.ts.map
|
|
@@ -128,7 +128,8 @@ function durationToMs(duration) {
|
|
|
128
128
|
const [, hours, minutes, seconds, centiseconds] = duration.match(/(\d+):(\d+):(\d+)\.(\d+)/)?.map(Number) ?? [];
|
|
129
129
|
return (((hours * 60 + minutes) * 60 + seconds) * 100 + centiseconds) * 10;
|
|
130
130
|
}
|
|
131
|
-
const ffmpeg = process.env.FFMPEG_PATH ?? (await import("@ffmpeg-installer/ffmpeg")).path;
|
|
131
|
+
export const ffmpeg = process.env.FFMPEG_PATH ?? (await import("@ffmpeg-installer/ffmpeg")).path;
|
|
132
|
+
export { createTmp, randomId };
|
|
132
133
|
const extMap = {
|
|
133
134
|
matroska: "mkv",
|
|
134
135
|
};
|
package/package.json
CHANGED
|
@@ -1,46 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "m4k",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.3",
|
|
4
|
+
"description": "Media toolkit for node, bun, and deno",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"audio",
|
|
7
|
+
"ffmpeg",
|
|
8
|
+
"image",
|
|
9
|
+
"media",
|
|
10
|
+
"sharp",
|
|
11
|
+
"video"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"author": "sv2dev",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/sv2dev/m4k.git"
|
|
18
|
+
},
|
|
4
19
|
"type": "module",
|
|
5
20
|
"main": "./lib/index.js",
|
|
6
|
-
"types": "./lib/index.d.ts",
|
|
7
21
|
"module": "./lib/index.js",
|
|
22
|
+
"types": "./lib/index.d.ts",
|
|
8
23
|
"exports": {
|
|
9
24
|
".": {
|
|
10
25
|
"types": "./lib/index.d.ts",
|
|
11
26
|
"import": "./lib/index.js"
|
|
12
27
|
}
|
|
13
28
|
},
|
|
14
|
-
"license": "MIT",
|
|
15
|
-
"description": "Media toolkit for node, bun, and deno",
|
|
16
|
-
"keywords": [
|
|
17
|
-
"media",
|
|
18
|
-
"ffmpeg",
|
|
19
|
-
"video",
|
|
20
|
-
"audio",
|
|
21
|
-
"image",
|
|
22
|
-
"sharp"
|
|
23
|
-
],
|
|
24
|
-
"author": "sv2dev",
|
|
25
29
|
"scripts": {
|
|
26
30
|
"prepublishOnly": "bun run build",
|
|
27
31
|
"build": "tsc -b",
|
|
28
32
|
"typecheck": "tsc --noEmit",
|
|
29
33
|
"test": "bun test"
|
|
30
34
|
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@m4k/common": "^0.2.6"
|
|
37
|
+
},
|
|
31
38
|
"devDependencies": {
|
|
32
39
|
"@ffmpeg-installer/ffmpeg": "^1.1.0",
|
|
33
40
|
"tasque": "^0.1.2",
|
|
34
|
-
"typescript": "^
|
|
35
|
-
},
|
|
36
|
-
"dependencies": {
|
|
37
|
-
"@m4k/common": "0.2.3"
|
|
41
|
+
"typescript": "^6.0.2"
|
|
38
42
|
},
|
|
39
43
|
"peerDependencies": {
|
|
40
|
-
"sharp": "^0.34.
|
|
41
|
-
},
|
|
42
|
-
"repository": {
|
|
43
|
-
"type": "git",
|
|
44
|
-
"url": "git+https://github.com/sv2dev/m4k.git"
|
|
44
|
+
"sharp": "^0.34.5"
|
|
45
45
|
}
|
|
46
46
|
}
|