m4k 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Sven
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/README.md ADDED
@@ -0,0 +1,30 @@
1
+ # m4k - media kit
2
+
3
+ A media conversion toolkit based on [ffmpeg](https://ffmpeg.org/) and [sharp](https://sharp.pixelplumbing.com/)/[libvips](https://github.com/libvips/libvips).
4
+ It provides queueing and progress reporting via async iterables.
5
+
6
+ ## Usage
7
+
8
+ Image optimization happens completely in memory.
9
+
10
+ ```ts
11
+ import { optimizeImage, ConvertedFile } from "m4k";
12
+ // input is a ReadableStream or Blob
13
+ for await (const value of optimizeImage(input, opts)) {
14
+ if (value instanceof ConvertedFile) {
15
+ // do something with the file
16
+ }
17
+ }
18
+ ```
19
+
20
+ For lower memory usage, video optimization happens with files.
21
+
22
+ ```ts
23
+ import { optimizeVideo, ConvertedFile } from "m4k";
24
+ // input is a file path
25
+ for await (const value of optimizeVideo(input, opts)) {
26
+ if (value instanceof ConvertedFile) {
27
+ // do something with the file
28
+ }
29
+ }
30
+ ```
@@ -0,0 +1,9 @@
1
+ import { type ImageOptimizerOptions, ConvertedFile } from "@m4k/types";
2
+ export type Format = Required<ImageOptimizerOptions>["format"];
3
+ export type Fit = Required<Required<ImageOptimizerOptions>["resize"]>["fit"];
4
+ export declare function optimizeImage(input: ReadableStream | Blob, opts: ImageOptimizerOptions | ImageOptimizerOptions[], signal?: AbortSignal): AsyncGenerator<ConvertedFile | {
5
+ progress: number;
6
+ } | {
7
+ position: number;
8
+ }, void, unknown> | null;
9
+ export declare const imageQueue: import("tasque").Tasque;
@@ -0,0 +1,58 @@
1
+ import { ConvertedFile } from "@m4k/types";
2
+ import sharp from "sharp";
3
+ import { createQueue } from "tasque";
4
+ import { readableFromWeb, readableToWeb } from "../util/streams";
5
+ export function optimizeImage(input, opts, signal) {
6
+ const sharpInstance = sharp();
7
+ const iterable = imageQueue.iterate(async function* () {
8
+ opts = Array.isArray(opts) ? opts : [opts];
9
+ readableFromWeb("stream" in input ? input.stream() : input).pipe(sharpInstance);
10
+ const files = await Promise.all(opts.map(async ({ colorspace, crop, format = "avif", keepExif, keepIcc, keepMetadata, quality, resize, rotate, }, idx) => {
11
+ let s = sharpInstance.clone();
12
+ s = s.rotate(rotate);
13
+ if (resize)
14
+ s = s.resize({
15
+ ...resize,
16
+ fit: resize.fit ?? "inside",
17
+ });
18
+ if (keepMetadata)
19
+ s = s.keepMetadata();
20
+ if (keepExif)
21
+ s = s.keepExif();
22
+ if (keepIcc)
23
+ s = s.keepIccProfile();
24
+ if (colorspace)
25
+ s = s.toColorspace(colorspace);
26
+ if (crop) {
27
+ s = s.extract({
28
+ ...crop,
29
+ left: crop.left ?? 0,
30
+ top: crop.top ?? 0,
31
+ });
32
+ }
33
+ s = s.toFormat(format, { quality });
34
+ return new ConvertedFile(`file${idx + 1}.${format}`, `image/${format}`, readableToWeb(s));
35
+ }));
36
+ let done = 0;
37
+ yield { progress: 0 };
38
+ for (const file of files) {
39
+ yield file;
40
+ done++;
41
+ yield { progress: Math.round((done / files.length) * 100) };
42
+ }
43
+ }, signal);
44
+ if (!iterable)
45
+ return null;
46
+ return (async function* () {
47
+ for await (const [position, value] of iterable) {
48
+ if (position !== null)
49
+ yield { position };
50
+ else
51
+ yield value;
52
+ }
53
+ })();
54
+ }
55
+ export const imageQueue = createQueue({
56
+ parallelize: Number(process.env.IMAGE_PARALLELIZE ?? 5),
57
+ max: Number(process.env.IMAGE_QUEUE_SIZE ?? 100),
58
+ });
@@ -0,0 +1,3 @@
1
+ export { ConvertedFile } from "@m4k/types";
2
+ export { imageQueue, optimizeImage } from "./images/image-optimizer";
3
+ export { getExtension, optimizeVideo, tmpVideoDir, videoQueue, } from "./videos/video-optimizer";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { ConvertedFile } from "@m4k/types";
2
+ export { imageQueue, optimizeImage } from "./images/image-optimizer";
3
+ export { getExtension, optimizeVideo, tmpVideoDir, videoQueue, } from "./videos/video-optimizer";
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Mapping from file extensions to their corresponding MIME types
3
+ */
4
+ export declare const mimeTypes: Record<string, string>;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Mapping from file extensions to their corresponding MIME types
3
+ */
4
+ export const mimeTypes = {
5
+ // Image formats
6
+ jpg: "image/jpeg",
7
+ jpeg: "image/jpeg",
8
+ png: "image/png",
9
+ gif: "image/gif",
10
+ webp: "image/webp",
11
+ avif: "image/avif",
12
+ heic: "image/heic",
13
+ heif: "image/heif",
14
+ svg: "image/svg+xml",
15
+ tiff: "image/tiff",
16
+ tif: "image/tiff",
17
+ bmp: "image/bmp",
18
+ ico: "image/x-icon",
19
+ // Video formats
20
+ mp4: "video/mp4",
21
+ asx: "video/x-ms-asf",
22
+ asf: "video/x-ms-asf",
23
+ mkv: "video/x-matroska",
24
+ mov: "video/quicktime",
25
+ avi: "video/x-msvideo",
26
+ wmv: "video/x-ms-wmv",
27
+ flv: "video/x-flv",
28
+ webm: "video/webm",
29
+ m4v: "video/x-m4v",
30
+ mng: "video/x-mng",
31
+ mpg: "video/mpeg",
32
+ mpeg: "video/mpeg",
33
+ ogv: "video/ogg",
34
+ "3gpp": "video/3gpp",
35
+ "3gp": "video/3gpp",
36
+ ts: "video/mp2t",
37
+ // Audio formats
38
+ mp3: "audio/mpeg",
39
+ wav: "audio/wav",
40
+ ogg: "audio/ogg",
41
+ oga: "audio/ogg",
42
+ m4a: "audio/mp4",
43
+ aac: "audio/aac",
44
+ flac: "audio/flac",
45
+ wma: "audio/x-ms-wma",
46
+ m4b: "audio/mp4",
47
+ m4p: "audio/mp4",
48
+ opus: "audio/opus",
49
+ aiff: "audio/aiff",
50
+ alac: "audio/alac",
51
+ };
@@ -0,0 +1,3 @@
1
+ import { Readable } from "node:stream";
2
+ export declare function readableFromWeb(stream: ReadableStream): Readable;
3
+ export declare function readableToWeb(stream: Readable): ReadableStream & AsyncIterable<Uint8Array>;
@@ -0,0 +1,8 @@
1
+ import { Readable } from "node:stream";
2
+ export function readableFromWeb(stream) {
3
+ // Currently node types don't match with TS lib types for ReadableStream, so we need to cast to any.
4
+ return Readable.fromWeb(stream);
5
+ }
6
+ export function readableToWeb(stream) {
7
+ return Readable.toWeb(stream);
8
+ }
@@ -0,0 +1,15 @@
1
+ import { ConvertedFile, type VideoOptimizerOptions } from "@m4k/types";
2
+ export declare function optimizeVideo(inputPath: string, opts: VideoOptimizerOptions, signal?: AbortSignal): AsyncGenerator<ConvertedFile | {
3
+ progress: number;
4
+ } | {
5
+ position: number;
6
+ }, void, unknown> | null;
7
+ /**
8
+ * Get the extension for a given format.
9
+ * May not be complete yet. Most of the time, the format will be the same as the extension.
10
+ * @param format - The format to get the extension for.
11
+ * @returns The extension for the given format.
12
+ */
13
+ export declare function getExtension(format: string): string;
14
+ export declare const videoQueue: import("tasque").Tasque;
15
+ export declare const tmpVideoDir: string;
@@ -0,0 +1,124 @@
1
+ import { ConvertedFile } from "@m4k/types";
2
+ import { spawn } from "node:child_process";
3
+ import { getRandomValues } from "node:crypto";
4
+ import { mkdir, rm } from "node:fs/promises";
5
+ import { createQueue } from "tasque";
6
+ import { mimeTypes } from "../util/mime";
7
+ export function optimizeVideo(inputPath, opts, signal) {
8
+ const iterable = videoQueue.iterate(async function* () {
9
+ await mkdir(tmpVideoDir, { recursive: true });
10
+ const outputPath = `${tmpVideoDir}/out-${Buffer.from(getRandomValues(new Uint8Array(16))).toString("base64url")}.${getExtension(opts.format ?? "mp4")}`;
11
+ const inArgs = [];
12
+ if (opts.inputFormat)
13
+ inArgs.push("-f", opts.inputFormat);
14
+ if (opts.seek)
15
+ inArgs.push("-ss", opts.seek.toString());
16
+ if (opts.duration)
17
+ inArgs.push("-t", opts.duration.toString());
18
+ const outArgs = [];
19
+ if (opts.format)
20
+ outArgs.push("-f", opts.format);
21
+ if (opts.audioBitrate)
22
+ outArgs.push("-b:a", opts.audioBitrate.toString());
23
+ if (opts.videoBitrate)
24
+ outArgs.push("-b:v", opts.videoBitrate.toString());
25
+ if (opts.audioFilters)
26
+ outArgs.push("-af", opts.audioFilters);
27
+ if (opts.videoFilters)
28
+ outArgs.push("-vf", opts.videoFilters);
29
+ if (opts.complexFilters)
30
+ outArgs.push("-filter_complex", opts.complexFilters);
31
+ if (opts.aspect)
32
+ outArgs.push("-aspect", opts.aspect.toString());
33
+ if (opts.pad)
34
+ outArgs.push("-pad", opts.pad);
35
+ if (opts.fps)
36
+ outArgs.push("-r", opts.fps.toString());
37
+ if (opts.size)
38
+ outArgs.push("-scale", opts.size);
39
+ outArgs.push("-c:v", opts.videoCodec ?? "copy");
40
+ outArgs.push("-c:a", opts.audioCodec ?? "copy");
41
+ try {
42
+ const child = spawn(ffmpeg, ["-y", ...inArgs, "-i", inputPath, ...outArgs, outputPath], { stdio: ["pipe", "pipe", "pipe"], signal });
43
+ const decoder = new TextDecoder();
44
+ let metadataStr = "";
45
+ let duration = null;
46
+ let progress = 0;
47
+ let errStr = "";
48
+ for await (const chunk of child.stderr) {
49
+ const str = decoder.decode(chunk);
50
+ errStr += str;
51
+ if (duration === null) {
52
+ metadataStr += str;
53
+ duration = parseDuration(metadataStr);
54
+ if (duration === null) {
55
+ metadataStr = str.slice(-30);
56
+ continue;
57
+ }
58
+ yield { progress };
59
+ continue;
60
+ }
61
+ const match = str.match(/time=(\d\d:\d\d:\d\d.\d\d)/);
62
+ if (match) {
63
+ const time = durationToMs(match[1]);
64
+ const p = Math.round((time / duration) * 100);
65
+ if (p !== progress) {
66
+ progress = p;
67
+ yield { progress };
68
+ }
69
+ }
70
+ }
71
+ if (progress !== 100) {
72
+ yield { progress: 100 };
73
+ }
74
+ const code = await new Promise((resolve) => {
75
+ child.on("close", resolve);
76
+ });
77
+ if (code !== 0) {
78
+ throw new Error(`ffmpeg exited with code ${code}: ${errStr}`);
79
+ }
80
+ yield new ConvertedFile(outputPath, mimeTypes[opts.format ?? "mp4"]);
81
+ }
82
+ finally {
83
+ await rm(outputPath, { force: true });
84
+ }
85
+ }, signal);
86
+ if (!iterable)
87
+ return null;
88
+ return (async function* () {
89
+ for await (const [position, value] of iterable) {
90
+ if (position !== null)
91
+ yield { position };
92
+ else
93
+ yield value;
94
+ }
95
+ })();
96
+ }
97
+ /**
98
+ * Get the extension for a given format.
99
+ * May not be complete yet. Most of the time, the format will be the same as the extension.
100
+ * @param format - The format to get the extension for.
101
+ * @returns The extension for the given format.
102
+ */
103
+ export function getExtension(format) {
104
+ return extMap[format] ?? format;
105
+ }
106
+ export const videoQueue = createQueue({
107
+ parallelize: Number(process.env.VIDEO_PARALLELIZE ?? 1),
108
+ max: Number(process.env.VIDEO_QUEUE_SIZE ?? 5),
109
+ });
110
+ export const tmpVideoDir = `${process.env.TMP_DIR ?? "/tmp"}/videos`;
111
+ function parseDuration(metadataStr) {
112
+ const match = metadataStr.match(/Duration: (\d+:\d+:\d+\.\d+)/);
113
+ if (!match)
114
+ return null;
115
+ return durationToMs(match[1]);
116
+ }
117
+ function durationToMs(duration) {
118
+ const [, hours, minutes, seconds, centiseconds] = duration.match(/(\d+):(\d+):(\d+)\.(\d+)/)?.map(Number) ?? [];
119
+ return (((hours * 60 + minutes) * 60 + seconds) * 100 + centiseconds) * 10;
120
+ }
121
+ const ffmpeg = process.env.FFMPEG_PATH ?? (await import("@ffmpeg-installer/ffmpeg")).path;
122
+ const extMap = {
123
+ matroska: "mkv",
124
+ };
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "m4k",
3
+ "module": "./dist/index.js",
4
+ "type": "module",
5
+ "version": "0.1.0",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "scripts": {
9
+ "prepublishOnly": "bun tsc",
10
+ "build": "tsc",
11
+ "typecheck": "tsc --noEmit",
12
+ "test": "bun test"
13
+ },
14
+ "devDependencies": {
15
+ "@ffmpeg-installer/ffmpeg": "^1.1.0",
16
+ "tasque": "^0.1.2",
17
+ "typescript": "^5.0.0"
18
+ },
19
+ "peerDependencies": {
20
+ "sharp": "^0.33.5"
21
+ },
22
+ "repository": "github:sv2dev/m4k"
23
+ }