@vitroyfix/streamstitch-node 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 peter wangimwa
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 CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @vitroyfix/streamstitch-node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Node.js (≥20) helpers on top of `@vitroyfix/streamstitch-core`: file I/O, ffmpeg stream-copy remux, and PNG-carrier MP4 pack/unpack.
4
+
5
+ See the [repository README](https://github.com/vitroyfix/streamstitch-js#readme) for overview, requirements, and examples.
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Node.js helpers for Streamstitch: file I/O, ffmpeg remux, PNG-carrier MP4 pack/unpack.
3
+ */
4
+ import { type Mp4FrameDurations, type TimelineReport, type TimestampOptions } from "@vitroyfix/streamstitch-core";
5
+ /** Alias matching CLI / docs naming. */
6
+ export type Mp4DurationReport = Mp4FrameDurations;
7
+ export type { TimelineReport, Mp4FrameDurations, TimestampOptions };
8
+ /** Subset of fixTimestampsWithReport without the output buffer. */
9
+ export type FixReport = {
10
+ jumps: number;
11
+ finalOffset: number;
12
+ pcrsAdjusted: number;
13
+ };
14
+ export type RemuxOptions = {
15
+ copyts?: boolean;
16
+ };
17
+ export type PackCarrierOptions = {
18
+ width?: number;
19
+ fps?: number;
20
+ };
21
+ export declare function ffmpegAvailable(): Promise<boolean>;
22
+ export declare function inspectFile(path: string, options?: TimestampOptions): Promise<TimelineReport>;
23
+ export declare function fixFile(inPath: string, outPath: string, options?: TimestampOptions): Promise<FixReport>;
24
+ export declare function remuxToMp4(inTs: string, outMp4: string, opts?: RemuxOptions): Promise<void>;
25
+ export declare function fixVideo(inTs: string, outMp4: string, options?: TimestampOptions): Promise<FixReport>;
26
+ export declare function probeMp4(path: string): Promise<Mp4DurationReport>;
27
+ /**
28
+ * Pack MPEG-TS segments into a lossless PNG-codec carrier MP4.
29
+ * All frames share one geometry (sized for the largest segment) so ffmpeg
30
+ * never scales later frames onto the first frame's size.
31
+ */
32
+ export declare function packCarrier(segmentPaths: string[], outMp4: string, opts?: PackCarrierOptions): Promise<void>;
33
+ /**
34
+ * Extract PNG frames from a carrier MP4 and write MPEG-TS segments to outDir.
35
+ * @returns paths of written `segment_XXXXXX.ts` files, in order.
36
+ */
37
+ export declare function unpackCarrier(carrierMp4: string, outDir: string): Promise<string[]>;
38
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAgBH,OAAO,EAQL,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACt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,MAAM,EAAE,MAAM,EACd,IAAI,CAAC,EAAE,kBAAkB,GACxB,OAAO,CAAC,IAAI,CAAC,CA2Cf;AAED;;;GAGG;AACH,wBAAsB,aAAa,CACjC,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,MAAM,EAAE,CAAC,CAoBnB"}
package/dist/index.js ADDED
@@ -0,0 +1,259 @@
1
+ /**
2
+ * Node.js helpers for Streamstitch: file I/O, ffmpeg remux, PNG-carrier MP4 pack/unpack.
3
+ */
4
+ import { spawn } from "node:child_process";
5
+ import { access, constants, copyFile, mkdtemp, mkdir, readFile, readdir, rm, writeFile, } from "node:fs/promises";
6
+ import { tmpdir } from "node:os";
7
+ import { dirname, join } from "node:path";
8
+ import { analyzeTimeline, decodePng, encodePng, fixTimestampsWithReport, parseMp4FrameDurations, pngToSegment, segmentToPng, } from "@vitroyfix/streamstitch-core";
9
+ function ffmpegMissingError() {
10
+ return new Error("ffmpeg not found on PATH. Install ffmpeg and ensure it is available to this process.");
11
+ }
12
+ async function which(cmd) {
13
+ const pathEnv = process.env["PATH"] ?? "";
14
+ const sep = process.platform === "win32" ? ";" : ":";
15
+ for (const dir of pathEnv.split(sep)) {
16
+ if (!dir)
17
+ continue;
18
+ const full = join(dir, cmd);
19
+ try {
20
+ await access(full, constants.X_OK);
21
+ return full;
22
+ }
23
+ catch {
24
+ // try next
25
+ }
26
+ }
27
+ return null;
28
+ }
29
+ async function resolveFfmpeg() {
30
+ const fromEnv = process.env["FFMPEG"]?.trim();
31
+ if (fromEnv) {
32
+ try {
33
+ await access(fromEnv, constants.X_OK);
34
+ return fromEnv;
35
+ }
36
+ catch {
37
+ throw new Error(`FFMPEG=${fromEnv} is not executable`);
38
+ }
39
+ }
40
+ const candidates = process.platform === "win32" ? ["ffmpeg.exe", "ffmpeg"] : ["ffmpeg"];
41
+ for (const name of candidates) {
42
+ const found = await which(name);
43
+ if (found)
44
+ return found;
45
+ }
46
+ throw ffmpegMissingError();
47
+ }
48
+ export async function ffmpegAvailable() {
49
+ try {
50
+ await resolveFfmpeg();
51
+ return true;
52
+ }
53
+ catch {
54
+ return false;
55
+ }
56
+ }
57
+ function runSpawn(command, args) {
58
+ return new Promise((resolve, reject) => {
59
+ const child = spawn(command, args, {
60
+ shell: false,
61
+ stdio: ["ignore", "pipe", "pipe"],
62
+ });
63
+ const stdoutChunks = [];
64
+ const stderrChunks = [];
65
+ child.stdout.on("data", (c) => stdoutChunks.push(c));
66
+ child.stderr.on("data", (c) => stderrChunks.push(c));
67
+ child.on("error", (err) => {
68
+ if (err.code === "ENOENT") {
69
+ reject(ffmpegMissingError());
70
+ return;
71
+ }
72
+ reject(err);
73
+ });
74
+ child.on("close", (code) => {
75
+ resolve({
76
+ code: code ?? 1,
77
+ stdout: Buffer.concat(stdoutChunks),
78
+ stderr: Buffer.concat(stderrChunks),
79
+ });
80
+ });
81
+ });
82
+ }
83
+ async function runFfmpeg(args) {
84
+ const ffmpeg = await resolveFfmpeg();
85
+ const result = await runSpawn(ffmpeg, ["-y", ...args]);
86
+ if (result.code !== 0) {
87
+ const errText = result.stderr.toString("utf8").trim() || "(no stderr)";
88
+ throw new Error(`ffmpeg failed (${result.code}): ${errText}`);
89
+ }
90
+ }
91
+ async function ensureParentDir(filePath) {
92
+ const parent = dirname(filePath);
93
+ if (parent && parent !== ".") {
94
+ await mkdir(parent, { recursive: true });
95
+ }
96
+ }
97
+ export async function inspectFile(path, options) {
98
+ const data = new Uint8Array(await readFile(path));
99
+ return analyzeTimeline(data, options);
100
+ }
101
+ export async function fixFile(inPath, outPath, options) {
102
+ const data = new Uint8Array(await readFile(inPath));
103
+ const report = fixTimestampsWithReport(data, options);
104
+ await ensureParentDir(outPath);
105
+ await writeFile(outPath, report.output);
106
+ return {
107
+ jumps: report.jumps,
108
+ finalOffset: report.finalOffset,
109
+ pcrsAdjusted: report.pcrsAdjusted,
110
+ };
111
+ }
112
+ export async function remuxToMp4(inTs, outMp4, opts) {
113
+ await ensureParentDir(outMp4);
114
+ const args = ["-f", "mpegts"];
115
+ if (opts?.copyts === true) {
116
+ args.push("-copyts");
117
+ }
118
+ args.push("-i", inTs, "-c", "copy", "-bsf:a", "aac_adtstoasc", "-avoid_negative_ts", "make_zero", "-movflags", "+faststart", outMp4);
119
+ await runFfmpeg(args);
120
+ }
121
+ export async function fixVideo(inTs, outMp4, options) {
122
+ const tmpRoot = await mkdtemp(join(tmpdir(), "streamstitch-fix-"));
123
+ const tmpTs = join(tmpRoot, "fixed.ts");
124
+ try {
125
+ const report = await fixFile(inTs, tmpTs, options);
126
+ await remuxToMp4(tmpTs, outMp4);
127
+ return report;
128
+ }
129
+ finally {
130
+ await rm(tmpRoot, { recursive: true, force: true });
131
+ }
132
+ }
133
+ export async function probeMp4(path) {
134
+ const data = new Uint8Array(await readFile(path));
135
+ return parseMp4FrameDurations(data);
136
+ }
137
+ function chooseSharedDimensions(pixelByteCounts, widthOpt) {
138
+ const maxBytes = Math.max(...pixelByteCounts);
139
+ if (maxBytes <= 0) {
140
+ throw new Error("segments produced empty frames");
141
+ }
142
+ if (widthOpt !== undefined) {
143
+ if (!Number.isInteger(widthOpt) || widthOpt <= 0) {
144
+ throw new Error("width must be a positive integer");
145
+ }
146
+ const height = Math.max(1, Math.ceil(maxBytes / (widthOpt * 3)));
147
+ return { width: widthOpt, height };
148
+ }
149
+ let side = Math.max(1, Math.ceil(Math.sqrt(maxBytes / 3)));
150
+ while (side * side * 3 < maxBytes)
151
+ side += 1;
152
+ return { width: side, height: side };
153
+ }
154
+ async function framesToMp4(pngPaths, outputMp4, fps) {
155
+ if (pngPaths.length === 0) {
156
+ throw new Error("no PNG frames to assemble");
157
+ }
158
+ const tmpRoot = await mkdtemp(join(tmpdir(), "streamstitch-pack-"));
159
+ try {
160
+ for (let i = 0; i < pngPaths.length; i++) {
161
+ const dest = join(tmpRoot, `frame_${String(i + 1).padStart(6, "0")}.png`);
162
+ await copyFile(pngPaths[i], dest);
163
+ }
164
+ const pattern = join(tmpRoot, "frame_%06d.png");
165
+ await ensureParentDir(outputMp4);
166
+ await runFfmpeg([
167
+ "-framerate",
168
+ String(fps),
169
+ "-i",
170
+ pattern,
171
+ "-fps_mode",
172
+ "passthrough",
173
+ "-vsync",
174
+ "passthrough",
175
+ "-c:v",
176
+ "png",
177
+ "-pix_fmt",
178
+ "rgb24",
179
+ outputMp4,
180
+ ]);
181
+ }
182
+ finally {
183
+ await rm(tmpRoot, { recursive: true, force: true });
184
+ }
185
+ }
186
+ async function mp4ToFrames(inputMp4, outputDir) {
187
+ await mkdir(outputDir, { recursive: true });
188
+ const pattern = join(outputDir, "frame_%06d.png");
189
+ await runFfmpeg(["-i", inputMp4, "-c", "copy", pattern]);
190
+ const names = (await readdir(outputDir))
191
+ .filter((n) => /^frame_\d+\.png$/.test(n))
192
+ .sort();
193
+ if (names.length === 0) {
194
+ throw new Error(`no PNG frames extracted from ${inputMp4}`);
195
+ }
196
+ return names.map((n) => join(outputDir, n));
197
+ }
198
+ /**
199
+ * Pack MPEG-TS segments into a lossless PNG-codec carrier MP4.
200
+ * All frames share one geometry (sized for the largest segment) so ffmpeg
201
+ * never scales later frames onto the first frame's size.
202
+ */
203
+ export async function packCarrier(segmentPaths, outMp4, opts) {
204
+ if (segmentPaths.length === 0) {
205
+ throw new Error("packCarrier requires at least one segment path");
206
+ }
207
+ const fps = opts?.fps ?? 1;
208
+ if (!Number.isInteger(fps) || fps <= 0) {
209
+ throw new Error("fps must be a positive integer");
210
+ }
211
+ const segments = await Promise.all(segmentPaths.map(async (p) => new Uint8Array(await readFile(p))));
212
+ const firstPngs = await Promise.all(segments.map((seg) => opts?.width !== undefined
213
+ ? segmentToPng(seg, { width: opts.width })
214
+ : segmentToPng(seg)));
215
+ const decoded = await Promise.all(firstPngs.map((png) => decodePng(png)));
216
+ const { width, height } = chooseSharedDimensions(decoded.map((d) => d.rgb.length), opts?.width);
217
+ const frameBytes = width * height * 3;
218
+ const tmpRoot = await mkdtemp(join(tmpdir(), "streamstitch-carrier-"));
219
+ try {
220
+ const pngPaths = [];
221
+ for (let i = 0; i < decoded.length; i++) {
222
+ const { rgb } = decoded[i];
223
+ const pixels = new Uint8Array(frameBytes);
224
+ pixels.set(rgb.subarray(0, Math.min(rgb.length, frameBytes)));
225
+ const png = await encodePng(pixels, width, height, 0);
226
+ const path = join(tmpRoot, `frame_${String(i + 1).padStart(6, "0")}.png`);
227
+ await writeFile(path, png);
228
+ pngPaths.push(path);
229
+ }
230
+ await framesToMp4(pngPaths, outMp4, fps);
231
+ }
232
+ finally {
233
+ await rm(tmpRoot, { recursive: true, force: true });
234
+ }
235
+ }
236
+ /**
237
+ * Extract PNG frames from a carrier MP4 and write MPEG-TS segments to outDir.
238
+ * @returns paths of written `segment_XXXXXX.ts` files, in order.
239
+ */
240
+ export async function unpackCarrier(carrierMp4, outDir) {
241
+ await mkdir(outDir, { recursive: true });
242
+ const frameTmp = await mkdtemp(join(tmpdir(), "streamstitch-unpack-"));
243
+ try {
244
+ const frames = await mp4ToFrames(carrierMp4, frameTmp);
245
+ const written = [];
246
+ for (let i = 0; i < frames.length; i++) {
247
+ const png = new Uint8Array(await readFile(frames[i]));
248
+ const segment = await pngToSegment(png);
249
+ const outPath = join(outDir, `segment_${String(i).padStart(6, "0")}.ts`);
250
+ await writeFile(outPath, segment);
251
+ written.push(outPath);
252
+ }
253
+ return written;
254
+ }
255
+ finally {
256
+ await rm(frameTmp, { recursive: true, force: true });
257
+ }
258
+ }
259
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EACL,MAAM,EACN,SAAS,EACT,QAAQ,EACR,OAAO,EACP,KAAK,EACL,QAAQ,EACR,OAAO,EACP,EAAE,EACF,SAAS,GACV,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE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sBAAsB,CAAC,CAAC,CAAC;IACvE,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;QACvD,MAAM,OAAO,GAAa,EAAE,CAAC;QAC7B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACvC,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,MAAM,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAE,CAAC,CAAC,CAAC;YACvD,MAAM,OAAO,GAAG,MAAM,YAAY,CAAC,GAAG,CAAC,CAAC;YACxC,MAAM,OAAO,GAAG,IAAI,CAClB,MAAM,EACN,WAAW,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,KAAK,CAC3C,CAAC;YACF,MAAM,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAClC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACxB,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;YAAS,CAAC;QACT,MAAM,EAAE,CAAC,QAAQ,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IACvD,CAAC;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@vitroyfix/streamstitch-node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Node.js helpers for MPEG-TS repair, MP4 remux, and PNG-carrier pack/unpack",
5
+ "author": "vitroyfix",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "src",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "engines": {
21
+ "node": ">=20"
22
+ },
23
+ "scripts": {
24
+ "build": "tsc -b",
25
+ "test": "npm run build && node --test test/*.test.js"
26
+ },
27
+ "dependencies": {
28
+ "@vitroyfix/streamstitch-core": "0.1.1"
29
+ },
30
+ "devDependencies": {
31
+ "@types/node": "^22.10.2"
32
+ },
33
+ "keywords": [
34
+ "mpeg-ts",
35
+ "hls",
36
+ "mp4",
37
+ "timestamps",
38
+ "pts",
39
+ "dts",
40
+ "pcr",
41
+ "video",
42
+ "ffmpeg",
43
+ "nodejs"
44
+ ],
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/vitroyfix/streamstitch-js.git",
48
+ "directory": "packages/node"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ }
53
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Minimal Node ambient types so this package can typecheck before
3
+ * @types/node is installed into the workspace.
4
+ * Prefer @types/node when available (listed in package.json).
5
+ */
6
+
7
+ declare module "node:child_process" {
8
+ import type { EventEmitter } from "node:events";
9
+
10
+ interface ChildProcessWithoutNullStreams extends EventEmitter {
11
+ readonly stdout: NodeJS.ReadableStream;
12
+ readonly stderr: NodeJS.ReadableStream;
13
+ on(event: "error", listener: (err: NodeJS.ErrnoException) => void): this;
14
+ on(event: "close", listener: (code: number | null) => void): this;
15
+ }
16
+
17
+ export function spawn(
18
+ command: string,
19
+ args: readonly string[],
20
+ options?: {
21
+ shell?: boolean;
22
+ stdio?: ReadonlyArray<"ignore" | "pipe" | "inherit">;
23
+ cwd?: string;
24
+ env?: NodeJS.ProcessEnv;
25
+ },
26
+ ): ChildProcessWithoutNullStreams;
27
+ }
28
+
29
+ declare module "node:events" {
30
+ export class EventEmitter {
31
+ on(event: string, listener: (...args: unknown[]) => void): this;
32
+ }
33
+ }
34
+
35
+ declare module "node:fs/promises" {
36
+ export function access(path: string, mode?: number): Promise<void>;
37
+ export function copyFile(src: string, dest: string): Promise<void>;
38
+ export function mkdtemp(prefix: string): Promise<string>;
39
+ export function mkdir(
40
+ path: string,
41
+ options?: { recursive?: boolean },
42
+ ): Promise<string | undefined>;
43
+ export function readFile(path: string): Promise<Buffer>;
44
+ export function readdir(path: string): Promise<string[]>;
45
+ export function rm(
46
+ path: string,
47
+ options?: { recursive?: boolean; force?: boolean },
48
+ ): Promise<void>;
49
+ export function writeFile(
50
+ path: string,
51
+ data: string | Uint8Array | Buffer,
52
+ ): Promise<void>;
53
+ export const constants: { X_OK: number };
54
+ }
55
+
56
+ declare module "node:os" {
57
+ export function tmpdir(): string;
58
+ }
59
+
60
+ declare module "node:path" {
61
+ export function join(...parts: string[]): string;
62
+ export function dirname(path: string): string;
63
+ }
64
+
65
+ declare namespace NodeJS {
66
+ interface ErrnoException extends Error {
67
+ code?: string;
68
+ }
69
+ interface ReadableStream {
70
+ on(event: "data", listener: (chunk: Buffer) => void): this;
71
+ }
72
+ interface ProcessEnv {
73
+ [key: string]: string | undefined;
74
+ }
75
+ interface Process {
76
+ readonly env: ProcessEnv;
77
+ readonly platform: string;
78
+ }
79
+ }
80
+
81
+ declare const process: NodeJS.Process;
82
+
83
+ declare class Buffer extends Uint8Array {
84
+ static concat(list: readonly Buffer[]): Buffer;
85
+ toString(encoding?: string): string;
86
+ }
87
+
88
+ interface BufferConstructor {
89
+ concat(list: readonly Buffer[]): Buffer;
90
+ }
package/src/index.ts ADDED
@@ -0,0 +1,374 @@
1
+ /**
2
+ * Node.js helpers for Streamstitch: file I/O, ffmpeg remux, PNG-carrier MP4 pack/unpack.
3
+ */
4
+
5
+ import { spawn } from "node:child_process";
6
+ import {
7
+ access,
8
+ constants,
9
+ copyFile,
10
+ mkdtemp,
11
+ mkdir,
12
+ readFile,
13
+ readdir,
14
+ rm,
15
+ writeFile,
16
+ } from "node:fs/promises";
17
+ import { tmpdir } from "node:os";
18
+ import { dirname, join } from "node:path";
19
+ import {
20
+ analyzeTimeline,
21
+ decodePng,
22
+ encodePng,
23
+ fixTimestampsWithReport,
24
+ parseMp4FrameDurations,
25
+ pngToSegment,
26
+ segmentToPng,
27
+ type Mp4FrameDurations,
28
+ type TimelineReport,
29
+ type TimestampOptions,
30
+ } from "@vitroyfix/streamstitch-core";
31
+
32
+ /** Alias matching CLI / docs naming. */
33
+ export type Mp4DurationReport = Mp4FrameDurations;
34
+ export type { TimelineReport, Mp4FrameDurations, TimestampOptions };
35
+
36
+ /** Subset of fixTimestampsWithReport without the output buffer. */
37
+ export type FixReport = {
38
+ jumps: number;
39
+ finalOffset: number;
40
+ pcrsAdjusted: number;
41
+ };
42
+
43
+ export type RemuxOptions = {
44
+ copyts?: boolean;
45
+ };
46
+
47
+ export type PackCarrierOptions = {
48
+ width?: number;
49
+ fps?: number;
50
+ };
51
+
52
+ function ffmpegMissingError(): Error {
53
+ return new Error(
54
+ "ffmpeg not found on PATH. Install ffmpeg and ensure it is available to this process.",
55
+ );
56
+ }
57
+
58
+ async function which(cmd: string): Promise<string | null> {
59
+ const pathEnv = process.env["PATH"] ?? "";
60
+ const sep = process.platform === "win32" ? ";" : ":";
61
+ for (const dir of pathEnv.split(sep)) {
62
+ if (!dir) continue;
63
+ const full = join(dir, cmd);
64
+ try {
65
+ await access(full, constants.X_OK);
66
+ return full;
67
+ } catch {
68
+ // try next
69
+ }
70
+ }
71
+ return null;
72
+ }
73
+
74
+ async function resolveFfmpeg(): Promise<string> {
75
+ const fromEnv = process.env["FFMPEG"]?.trim();
76
+ if (fromEnv) {
77
+ try {
78
+ await access(fromEnv, constants.X_OK);
79
+ return fromEnv;
80
+ } catch {
81
+ throw new Error(`FFMPEG=${fromEnv} is not executable`);
82
+ }
83
+ }
84
+ const candidates =
85
+ process.platform === "win32" ? ["ffmpeg.exe", "ffmpeg"] : ["ffmpeg"];
86
+ for (const name of candidates) {
87
+ const found = await which(name);
88
+ if (found) return found;
89
+ }
90
+ throw ffmpegMissingError();
91
+ }
92
+
93
+ export async function ffmpegAvailable(): Promise<boolean> {
94
+ try {
95
+ await resolveFfmpeg();
96
+ return true;
97
+ } catch {
98
+ return false;
99
+ }
100
+ }
101
+
102
+ type SpawnResult = { code: number; stdout: Buffer; stderr: Buffer };
103
+
104
+ function runSpawn(
105
+ command: string,
106
+ args: readonly string[],
107
+ ): Promise<SpawnResult> {
108
+ return new Promise((resolve, reject) => {
109
+ const child = spawn(command, args, {
110
+ shell: false,
111
+ stdio: ["ignore", "pipe", "pipe"],
112
+ });
113
+ const stdoutChunks: Buffer[] = [];
114
+ const stderrChunks: Buffer[] = [];
115
+ child.stdout.on("data", (c: Buffer) => stdoutChunks.push(c));
116
+ child.stderr.on("data", (c: Buffer) => stderrChunks.push(c));
117
+ child.on("error", (err: NodeJS.ErrnoException) => {
118
+ if (err.code === "ENOENT") {
119
+ reject(ffmpegMissingError());
120
+ return;
121
+ }
122
+ reject(err);
123
+ });
124
+ child.on("close", (code) => {
125
+ resolve({
126
+ code: code ?? 1,
127
+ stdout: Buffer.concat(stdoutChunks),
128
+ stderr: Buffer.concat(stderrChunks),
129
+ });
130
+ });
131
+ });
132
+ }
133
+
134
+ async function runFfmpeg(args: readonly string[]): Promise<void> {
135
+ const ffmpeg = await resolveFfmpeg();
136
+ const result = await runSpawn(ffmpeg, ["-y", ...args]);
137
+ if (result.code !== 0) {
138
+ const errText = result.stderr.toString("utf8").trim() || "(no stderr)";
139
+ throw new Error(`ffmpeg failed (${result.code}): ${errText}`);
140
+ }
141
+ }
142
+
143
+ async function ensureParentDir(filePath: string): Promise<void> {
144
+ const parent = dirname(filePath);
145
+ if (parent && parent !== ".") {
146
+ await mkdir(parent, { recursive: true });
147
+ }
148
+ }
149
+
150
+ export async function inspectFile(
151
+ path: string,
152
+ options?: TimestampOptions,
153
+ ): Promise<TimelineReport> {
154
+ const data = new Uint8Array(await readFile(path));
155
+ return analyzeTimeline(data, options);
156
+ }
157
+
158
+ export async function fixFile(
159
+ inPath: string,
160
+ outPath: string,
161
+ options?: TimestampOptions,
162
+ ): Promise<FixReport> {
163
+ const data = new Uint8Array(await readFile(inPath));
164
+ const report = fixTimestampsWithReport(data, options);
165
+ await ensureParentDir(outPath);
166
+ await writeFile(outPath, report.output);
167
+ return {
168
+ jumps: report.jumps,
169
+ finalOffset: report.finalOffset,
170
+ pcrsAdjusted: report.pcrsAdjusted,
171
+ };
172
+ }
173
+
174
+ export async function remuxToMp4(
175
+ inTs: string,
176
+ outMp4: string,
177
+ opts?: RemuxOptions,
178
+ ): Promise<void> {
179
+ await ensureParentDir(outMp4);
180
+ const args: string[] = ["-f", "mpegts"];
181
+ if (opts?.copyts === true) {
182
+ args.push("-copyts");
183
+ }
184
+ args.push(
185
+ "-i",
186
+ inTs,
187
+ "-c",
188
+ "copy",
189
+ "-bsf:a",
190
+ "aac_adtstoasc",
191
+ "-avoid_negative_ts",
192
+ "make_zero",
193
+ "-movflags",
194
+ "+faststart",
195
+ outMp4,
196
+ );
197
+ await runFfmpeg(args);
198
+ }
199
+
200
+ export async function fixVideo(
201
+ inTs: string,
202
+ outMp4: string,
203
+ options?: TimestampOptions,
204
+ ): Promise<FixReport> {
205
+ const tmpRoot = await mkdtemp(join(tmpdir(), "streamstitch-fix-"));
206
+ const tmpTs = join(tmpRoot, "fixed.ts");
207
+ try {
208
+ const report = await fixFile(inTs, tmpTs, options);
209
+ await remuxToMp4(tmpTs, outMp4);
210
+ return report;
211
+ } finally {
212
+ await rm(tmpRoot, { recursive: true, force: true });
213
+ }
214
+ }
215
+
216
+ export async function probeMp4(path: string): Promise<Mp4DurationReport> {
217
+ const data = new Uint8Array(await readFile(path));
218
+ return parseMp4FrameDurations(data);
219
+ }
220
+
221
+ function chooseSharedDimensions(
222
+ pixelByteCounts: number[],
223
+ widthOpt?: number,
224
+ ): { width: number; height: number } {
225
+ const maxBytes = Math.max(...pixelByteCounts);
226
+ if (maxBytes <= 0) {
227
+ throw new Error("segments produced empty frames");
228
+ }
229
+ if (widthOpt !== undefined) {
230
+ if (!Number.isInteger(widthOpt) || widthOpt <= 0) {
231
+ throw new Error("width must be a positive integer");
232
+ }
233
+ const height = Math.max(1, Math.ceil(maxBytes / (widthOpt * 3)));
234
+ return { width: widthOpt, height };
235
+ }
236
+ let side = Math.max(1, Math.ceil(Math.sqrt(maxBytes / 3)));
237
+ while (side * side * 3 < maxBytes) side += 1;
238
+ return { width: side, height: side };
239
+ }
240
+
241
+ async function framesToMp4(
242
+ pngPaths: string[],
243
+ outputMp4: string,
244
+ fps: number,
245
+ ): Promise<void> {
246
+ if (pngPaths.length === 0) {
247
+ throw new Error("no PNG frames to assemble");
248
+ }
249
+ const tmpRoot = await mkdtemp(join(tmpdir(), "streamstitch-pack-"));
250
+ try {
251
+ for (let i = 0; i < pngPaths.length; i++) {
252
+ const dest = join(tmpRoot, `frame_${String(i + 1).padStart(6, "0")}.png`);
253
+ await copyFile(pngPaths[i]!, dest);
254
+ }
255
+ const pattern = join(tmpRoot, "frame_%06d.png");
256
+ await ensureParentDir(outputMp4);
257
+ await runFfmpeg([
258
+ "-framerate",
259
+ String(fps),
260
+ "-i",
261
+ pattern,
262
+ "-fps_mode",
263
+ "passthrough",
264
+ "-vsync",
265
+ "passthrough",
266
+ "-c:v",
267
+ "png",
268
+ "-pix_fmt",
269
+ "rgb24",
270
+ outputMp4,
271
+ ]);
272
+ } finally {
273
+ await rm(tmpRoot, { recursive: true, force: true });
274
+ }
275
+ }
276
+
277
+ async function mp4ToFrames(
278
+ inputMp4: string,
279
+ outputDir: string,
280
+ ): Promise<string[]> {
281
+ await mkdir(outputDir, { recursive: true });
282
+ const pattern = join(outputDir, "frame_%06d.png");
283
+ await runFfmpeg(["-i", inputMp4, "-c", "copy", pattern]);
284
+ const names = (await readdir(outputDir))
285
+ .filter((n) => /^frame_\d+\.png$/.test(n))
286
+ .sort();
287
+ if (names.length === 0) {
288
+ throw new Error(`no PNG frames extracted from ${inputMp4}`);
289
+ }
290
+ return names.map((n) => join(outputDir, n));
291
+ }
292
+
293
+ /**
294
+ * Pack MPEG-TS segments into a lossless PNG-codec carrier MP4.
295
+ * All frames share one geometry (sized for the largest segment) so ffmpeg
296
+ * never scales later frames onto the first frame's size.
297
+ */
298
+ export async function packCarrier(
299
+ segmentPaths: string[],
300
+ outMp4: string,
301
+ opts?: PackCarrierOptions,
302
+ ): Promise<void> {
303
+ if (segmentPaths.length === 0) {
304
+ throw new Error("packCarrier requires at least one segment path");
305
+ }
306
+ const fps = opts?.fps ?? 1;
307
+ if (!Number.isInteger(fps) || fps <= 0) {
308
+ throw new Error("fps must be a positive integer");
309
+ }
310
+
311
+ const segments = await Promise.all(
312
+ segmentPaths.map(async (p) => new Uint8Array(await readFile(p))),
313
+ );
314
+
315
+ const firstPngs = await Promise.all(
316
+ segments.map((seg) =>
317
+ opts?.width !== undefined
318
+ ? segmentToPng(seg, { width: opts.width })
319
+ : segmentToPng(seg),
320
+ ),
321
+ );
322
+ const decoded = await Promise.all(firstPngs.map((png) => decodePng(png)));
323
+ const { width, height } = chooseSharedDimensions(
324
+ decoded.map((d) => d.rgb.length),
325
+ opts?.width,
326
+ );
327
+ const frameBytes = width * height * 3;
328
+
329
+ const tmpRoot = await mkdtemp(join(tmpdir(), "streamstitch-carrier-"));
330
+ try {
331
+ const pngPaths: string[] = [];
332
+ for (let i = 0; i < decoded.length; i++) {
333
+ const { rgb } = decoded[i]!;
334
+ const pixels = new Uint8Array(frameBytes);
335
+ pixels.set(rgb.subarray(0, Math.min(rgb.length, frameBytes)));
336
+ const png = await encodePng(pixels, width, height, 0);
337
+ const path = join(tmpRoot, `frame_${String(i + 1).padStart(6, "0")}.png`);
338
+ await writeFile(path, png);
339
+ pngPaths.push(path);
340
+ }
341
+ await framesToMp4(pngPaths, outMp4, fps);
342
+ } finally {
343
+ await rm(tmpRoot, { recursive: true, force: true });
344
+ }
345
+ }
346
+
347
+ /**
348
+ * Extract PNG frames from a carrier MP4 and write MPEG-TS segments to outDir.
349
+ * @returns paths of written `segment_XXXXXX.ts` files, in order.
350
+ */
351
+ export async function unpackCarrier(
352
+ carrierMp4: string,
353
+ outDir: string,
354
+ ): Promise<string[]> {
355
+ await mkdir(outDir, { recursive: true });
356
+ const frameTmp = await mkdtemp(join(tmpdir(), "streamstitch-unpack-"));
357
+ try {
358
+ const frames = await mp4ToFrames(carrierMp4, frameTmp);
359
+ const written: string[] = [];
360
+ for (let i = 0; i < frames.length; i++) {
361
+ const png = new Uint8Array(await readFile(frames[i]!));
362
+ const segment = await pngToSegment(png);
363
+ const outPath = join(
364
+ outDir,
365
+ `segment_${String(i).padStart(6, "0")}.ts`,
366
+ );
367
+ await writeFile(outPath, segment);
368
+ written.push(outPath);
369
+ }
370
+ return written;
371
+ } finally {
372
+ await rm(frameTmp, { recursive: true, force: true });
373
+ }
374
+ }