@vitroyfix/streamcraft-cli 0.1.0 → 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/src/cli.ts CHANGED
@@ -1,399 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * streamcraft CLI — inspect, fix, remux, pack/unpack MPEG-TS / MP4 carriers.
3
+ * Bin entry for `streamcraft`. Always runs main() so npm global symlinks work
4
+ * (comparing import.meta.url to process.argv[1] fails when argv[1] is a symlink).
4
5
  */
5
6
 
6
- import { readFileSync } from "node:fs";
7
- import { dirname, join, resolve } from "node:path";
8
- import { fileURLToPath } from "node:url";
9
- import { parseArgs, type ParseArgsConfig } from "node:util";
10
- import {
11
- fixFile,
12
- fixVideo,
13
- inspectFile,
14
- packCarrier,
15
- probeMp4,
16
- unpackCarrier,
17
- type FixReport,
18
- type Mp4DurationReport,
19
- type TimelineReport,
20
- } from "@vitroyfix/streamcraft-node";
7
+ import { friendlyRuntimeMessage, main } from "./main.js";
21
8
 
22
- const EXIT_OK = 0;
23
9
  const EXIT_RUNTIME = 1;
24
- const EXIT_USAGE = 2;
25
10
 
26
- const USAGE = `Usage: streamcraft <command> [options]
27
-
28
- Commands:
29
- inspect <in.ts> [--json] Report PES/PCR timeline
30
- fix <in.ts> <out.ts> Repair timestamp jumps, writing a new file
31
- fix-video <in.ts> <out.mp4> Repair then remux to MP4 (stream copy)
32
- probe <in.mp4> [--json] Report per-frame MP4 sample durations
33
- pack -o <out.mp4> <seg.ts...> [--width N] [--fps N]
34
- Pack MPEG-TS segments into a PNG-carrier MP4
35
- unpack -o <dir> <carrier.mp4> Unpack carrier MP4 to segment files
36
-
37
- Global:
38
- -h, --help Show this help
39
- -V, --version Show version
40
- `;
41
-
42
- function packageVersion(): string {
43
- try {
44
- const here = dirname(fileURLToPath(import.meta.url));
45
- const pkgPath = join(here, "..", "package.json");
46
- const raw = readFileSync(pkgPath, "utf8");
47
- const pkg = JSON.parse(raw) as { version?: string };
48
- return pkg.version ?? "0.0.0";
49
- } catch {
50
- return "0.0.0";
51
- }
52
- }
53
-
54
- function printUsage(stream: { write(chunk: string): unknown } = process.stderr): void {
55
- stream.write(USAGE);
56
- }
57
-
58
- function formatInspectHuman(report: TimelineReport): string {
59
- const lines: string[] = [];
60
- lines.push(
61
- `MPEG-TS timeline (clock=${report.clockHz} Hz, jump > ${report.threshold} ticks)`,
62
- );
63
- lines.push("");
64
-
65
- const pes = report.streams.filter((s) => s.kind === "pes");
66
- const pcr = report.streams.filter((s) => s.kind === "pcr");
67
-
68
- if (pes.length === 0) {
69
- lines.push("PES: (none)");
70
- } else {
71
- for (const stream of pes) {
72
- lines.push(`PES PID ${stream.pid} (${stream.samples.length} samples)`);
73
- lines.push(
74
- `${"idx".padStart(8)} ${"PTS".padStart(12)} ${"DTS".padStart(12)} ${"step".padStart(12)} ${"jump".padStart(6)}`,
75
- );
76
- for (const row of stream.samples) {
77
- const pts = row.pts === null ? "-" : String(row.pts);
78
- const dts = row.dts === null ? "-" : String(row.dts);
79
- const step = row.step === null ? "-" : String(row.step);
80
- const jump = row.jump ? "YES" : "";
81
- lines.push(
82
- `${row.index.toString().padStart(8)} ${pts.padStart(12)} ${dts.padStart(12)} ${step.padStart(12)} ${jump.padStart(6)}`,
83
- );
84
- }
85
- lines.push("");
86
- }
87
- }
88
-
89
- if (pcr.length === 0) {
90
- lines.push("PCR: (none)");
91
- } else {
92
- for (const stream of pcr) {
93
- lines.push(`PCR PID ${stream.pid} (${stream.samples.length} samples)`);
94
- lines.push(
95
- `${"idx".padStart(8)} ${"pcr_base".padStart(12)} ${"step".padStart(12)} ${"jump".padStart(6)}`,
96
- );
97
- for (const row of stream.samples) {
98
- const pcrBase = row.pcr === null ? "-" : String(row.pcr);
99
- const step = row.step === null ? "-" : String(row.step);
100
- const jump = row.jump ? "YES" : "";
101
- lines.push(
102
- `${row.index.toString().padStart(8)} ${pcrBase.padStart(12)} ${step.padStart(12)} ${jump.padStart(6)}`,
103
- );
104
- }
105
- lines.push("");
106
- }
107
- }
108
-
109
- lines.push(`Total jumps flagged: ${report.jumpCount}`);
110
- return lines.join("\n").replace(/\n+$/, "") + "\n";
111
- }
112
-
113
- function formatProbeHuman(report: Mp4DurationReport): string {
114
- const lines: string[] = [];
115
- lines.push("MP4 per-frame duration report");
116
- lines.push("");
117
- let outlierTotal = 0;
118
- if (report.tracks.length === 0) {
119
- lines.push("Tracks: (none with stts)");
120
- }
121
- for (const track of report.tracks) {
122
- const outliers = track.outlierIndexes.length;
123
- outlierTotal += outliers;
124
- lines.push(
125
- `Track ${track.trackId}: timescale=${track.timescale}, ` +
126
- `samples=${track.durations.length}, modal_duration=${track.modalDuration}, ` +
127
- `outliers=${outliers}`,
128
- );
129
- lines.push(
130
- `${"sample".padStart(8)} ${"duration".padStart(12)} ${"seconds".padStart(14)} ${"outlier".padStart(8)}`,
131
- );
132
- const outlierSet = new Set(track.outlierIndexes);
133
- for (let i = 0; i < track.durations.length; i++) {
134
- const dur = track.durations[i] ?? 0;
135
- const seconds = track.timescale ? dur / track.timescale : 0;
136
- const mark = outlierSet.has(i) ? "YES" : "";
137
- lines.push(
138
- `${i.toString().padStart(8)} ${dur.toString().padStart(12)} ${seconds.toFixed(6).padStart(14)} ${mark.padStart(8)}`,
139
- );
140
- }
141
- lines.push("");
142
- }
143
- lines.push(`Total outliers flagged: ${outlierTotal}`);
144
- return lines.join("\n").replace(/\n+$/, "") + "\n";
145
- }
146
-
147
- function formatFixReport(path: string, report: FixReport): string {
148
- return (
149
- `Wrote ${path} (jumps=${report.jumps}, finalOffset=${report.finalOffset}, ` +
150
- `pcrsAdjusted=${report.pcrsAdjusted})\n`
151
- );
152
- }
153
-
154
- class UsageError extends Error {
155
- constructor(message: string) {
156
- super(message);
157
- this.name = "UsageError";
158
- }
159
- }
160
-
161
- function friendlyRuntimeMessage(err: unknown): string {
162
- const code =
163
- err && typeof err === "object" && "code" in err
164
- ? String((err as { code: unknown }).code)
165
- : "";
166
- const pathProp =
167
- err &&
168
- typeof err === "object" &&
169
- "path" in err &&
170
- typeof (err as { path: unknown }).path === "string"
171
- ? (err as { path: string }).path
172
- : undefined;
173
- const msg = err instanceof Error ? err.message : String(err);
174
- if (code === "ENOENT" || /ENOENT|no such file or directory/i.test(msg)) {
175
- const fromMsg = /open '([^']+)'/.exec(msg)?.[1];
176
- const path = pathProp ?? fromMsg ?? "file";
177
- return `streamcraft: cannot read ${path}: no such file`;
178
- }
179
- return msg;
180
- }
181
-
182
- async function cmdInspect(positionals: string[], asJson: boolean): Promise<void> {
183
- if (positionals.length !== 1) {
184
- throw new UsageError("inspect requires exactly one argument: <in.ts>");
185
- }
186
- const input = positionals[0]!;
187
- const report = await inspectFile(input);
188
- if (asJson) {
189
- process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
190
- } else {
191
- process.stdout.write(formatInspectHuman(report));
192
- }
193
- }
194
-
195
- async function cmdFix(positionals: string[]): Promise<void> {
196
- if (positionals.length !== 2) {
197
- throw new UsageError("fix requires <in.ts> <out.ts>");
198
- }
199
- const [input, output] = positionals as [string, string];
200
- const report = await fixFile(input, output);
201
- process.stdout.write(formatFixReport(output, report));
202
- }
203
-
204
- async function cmdFixVideo(positionals: string[]): Promise<void> {
205
- if (positionals.length !== 2) {
206
- throw new UsageError("fix-video requires <in.ts> <out.mp4>");
207
- }
208
- const [input, output] = positionals as [string, string];
209
- const report = await fixVideo(input, output);
210
- process.stdout.write(formatFixReport(output, report));
211
- }
212
-
213
- async function cmdProbe(positionals: string[], asJson: boolean): Promise<void> {
214
- if (positionals.length !== 1) {
215
- throw new UsageError("probe requires exactly one argument: <in.mp4>");
216
- }
217
- const input = positionals[0]!;
218
- const report = await probeMp4(input);
219
- if (asJson) {
220
- process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
221
- } else {
222
- process.stdout.write(formatProbeHuman(report));
223
- }
224
- }
225
-
226
- async function cmdPack(
227
- positionals: string[],
228
- outPath: string | undefined,
229
- width: number | undefined,
230
- fps: number | undefined,
231
- ): Promise<void> {
232
- if (!outPath) {
233
- throw new UsageError("pack requires -o <out.mp4>");
234
- }
235
- if (positionals.length < 1) {
236
- throw new UsageError("pack requires at least one <seg.ts>");
237
- }
238
- const opts: { width?: number; fps?: number } = {};
239
- if (width !== undefined) opts.width = width;
240
- if (fps !== undefined) opts.fps = fps;
241
- await packCarrier(positionals, outPath, opts);
242
- process.stdout.write(
243
- `Packed ${positionals.length} segment(s) -> ${outPath}\n`,
244
- );
245
- }
246
-
247
- async function cmdUnpack(
248
- positionals: string[],
249
- outDir: string | undefined,
250
- ): Promise<void> {
251
- if (!outDir) {
252
- throw new UsageError("unpack requires -o <dir>");
253
- }
254
- if (positionals.length !== 1) {
255
- throw new UsageError("unpack requires exactly one <carrier.mp4>");
256
- }
257
- const carrier = positionals[0]!;
258
- const written = await unpackCarrier(carrier, outDir);
259
- process.stdout.write(
260
- `Unpacked ${written.length} segment(s) -> ${outDir}\n`,
261
- );
262
- for (const path of written) {
263
- process.stdout.write(` ${path}\n`);
264
- }
265
- }
266
-
267
- function parsePositiveInt(raw: string | undefined, flag: string): number | undefined {
268
- if (raw === undefined) return undefined;
269
- const n = Number(raw);
270
- if (!Number.isInteger(n) || n <= 0) {
271
- throw new UsageError(`${flag} must be a positive integer`);
272
- }
273
- return n;
274
- }
275
-
276
- export async function main(argv: string[] = process.argv.slice(2)): Promise<number> {
277
- if (argv.length === 0) {
278
- printUsage();
279
- return EXIT_USAGE;
280
- }
281
-
282
- // Global help/version before command parsing.
283
- if (argv.includes("-h") || argv.includes("--help")) {
284
- printUsage(process.stdout);
285
- return EXIT_OK;
286
- }
287
- if (argv.includes("-V") || argv.includes("--version")) {
288
- process.stdout.write(`${packageVersion()}\n`);
289
- return EXIT_OK;
290
- }
291
-
292
- const command = argv[0];
293
- if (!command || command.startsWith("-")) {
294
- printUsage();
295
- return EXIT_USAGE;
296
- }
297
-
298
- const rest = argv.slice(1);
299
-
300
- const config: ParseArgsConfig = {
301
- args: rest,
302
- allowPositionals: true,
303
- strict: true,
304
- options: {
305
- json: { type: "boolean", default: false },
306
- o: { type: "string", short: "o" },
307
- width: { type: "string" },
308
- fps: { type: "string" },
309
- help: { type: "boolean", short: "h", default: false },
310
- version: { type: "boolean", short: "V", default: false },
311
- },
312
- };
313
-
314
- let values: {
315
- json?: boolean;
316
- o?: string;
317
- width?: string;
318
- fps?: string;
319
- help?: boolean;
320
- version?: boolean;
321
- };
322
- let positionals: string[];
323
- try {
324
- const parsed = parseArgs(config);
325
- values = parsed.values as typeof values;
326
- positionals = parsed.positionals;
327
- } catch (err) {
328
- const msg = err instanceof Error ? err.message : String(err);
329
- process.stderr.write(`${msg}\n`);
330
- printUsage();
331
- return EXIT_USAGE;
332
- }
333
-
334
- if (values.help) {
335
- printUsage(process.stdout);
336
- return EXIT_OK;
337
- }
338
- if (values.version) {
339
- process.stdout.write(`${packageVersion()}\n`);
340
- return EXIT_OK;
341
- }
342
-
343
- try {
344
- switch (command) {
345
- case "inspect":
346
- await cmdInspect(positionals, Boolean(values.json));
347
- break;
348
- case "fix":
349
- await cmdFix(positionals);
350
- break;
351
- case "fix-video":
352
- await cmdFixVideo(positionals);
353
- break;
354
- case "probe":
355
- await cmdProbe(positionals, Boolean(values.json));
356
- break;
357
- case "pack":
358
- await cmdPack(
359
- positionals,
360
- values.o,
361
- parsePositiveInt(values.width, "--width"),
362
- parsePositiveInt(values.fps, "--fps"),
363
- );
364
- break;
365
- case "unpack":
366
- await cmdUnpack(positionals, values.o);
367
- break;
368
- default:
369
- process.stderr.write(`Unknown command: ${command}\n`);
370
- printUsage();
371
- return EXIT_USAGE;
372
- }
373
- } catch (err) {
374
- if (err instanceof UsageError) {
375
- process.stderr.write(`${err.message}\n`);
376
- printUsage();
377
- return EXIT_USAGE;
378
- }
11
+ main()
12
+ .then((code) => {
13
+ process.exitCode = code;
14
+ })
15
+ .catch((err: unknown) => {
379
16
  process.stderr.write(`${friendlyRuntimeMessage(err)}\n`);
380
- return EXIT_RUNTIME;
381
- }
382
-
383
- return EXIT_OK;
384
- }
385
-
386
- const isDirectRun =
387
- process.argv[1] !== undefined &&
388
- resolve(fileURLToPath(import.meta.url)) === resolve(process.argv[1]);
389
-
390
- if (isDirectRun) {
391
- main()
392
- .then((code) => {
393
- process.exitCode = code;
394
- })
395
- .catch((err: unknown) => {
396
- process.stderr.write(`${friendlyRuntimeMessage(err)}\n`);
397
- process.exitCode = EXIT_RUNTIME;
398
- });
399
- }
17
+ process.exitCode = EXIT_RUNTIME;
18
+ });