m4k 0.3.2 → 0.3.4

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/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ All notable changes to `m4k` are documented here.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.3.4]
9
+
10
+ ### Changed
11
+
12
+ - Updated the Sharp peer dependency to `0.35.3`.
13
+ - Updated the TypeScript development dependency.
@@ -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
- opts = Array.isArray(opts) ? opts : [opts];
17
- void exhaustAsyncIterableToWritable(typeof input === "string"
18
- ? createReadStream(input)
19
- : "stream" in input
20
- ? input.stream()
21
- : input, sharpInstance);
22
- const files = opts.map(async ({ colorspace, crop, format = "avif", ext = format, keepExif, keepIcc, keepMetadata, quality, resize, rotate, }, idx) => {
23
- let s = sharpInstance.clone();
24
- s = s.rotate(rotate);
25
- if (resize)
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
- s = s.toFormat(ext, { quality });
46
- return new ProcessedFile(`file${idx + 1}.${ext}`, `image/${ext}`, s);
47
- });
48
- let done = 0;
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 (const file of files) {
51
- yield await file;
52
- done++;
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,6 +1,6 @@
1
1
  {
2
2
  "name": "m4k",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "Media toolkit for node, bun, and deno",
5
5
  "keywords": [
6
6
  "audio",
@@ -33,14 +33,14 @@
33
33
  "test": "bun test"
34
34
  },
35
35
  "dependencies": {
36
- "@m4k/common": "^0.2.6"
36
+ "@m4k/common": "^0.2.8"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@ffmpeg-installer/ffmpeg": "^1.1.0",
40
40
  "tasque": "^0.1.2",
41
- "typescript": "^6.0.2"
41
+ "typescript": "^7.0.2"
42
42
  },
43
43
  "peerDependencies": {
44
- "sharp": "^0.34.5"
44
+ "sharp": "^0.35.3"
45
45
  }
46
46
  }