fffleet 2.1.0 → 2.2.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/index.d.ts CHANGED
@@ -50,12 +50,30 @@ export interface JobSpecInput {
50
50
  inputs?: Endpoint[];
51
51
  outputs?: Endpoint[];
52
52
  ffmpeg?: { args: string[]; durationMs?: number | null };
53
+ /** For `type: 'ffprobe'`: which sections to print (default format and streams). */
54
+ ffprobe?: { show?: ('format' | 'streams' | 'chapters' | 'programs')[] };
53
55
  [section: string]: unknown;
54
56
  }
55
57
 
56
- export interface JobSpec extends Required<Omit<JobSpecInput, 'id' | 'ffmpeg'>> {
58
+ /** A validated spec with every default filled in (what parseSpec returns). */
59
+ export interface JobSpec {
60
+ contract: 1;
57
61
  id?: string;
62
+ kind: JobKind;
63
+ type: string;
64
+ class: string;
65
+ priority: number;
66
+ owner: string;
67
+ requires: string[];
68
+ labels: Record<string, string>;
69
+ timeoutMs: number | null;
70
+ stdin: boolean;
71
+ stdout: boolean;
72
+ inputs: Endpoint[];
73
+ outputs: Endpoint[];
58
74
  ffmpeg?: { args: string[]; durationMs: number | null };
75
+ /** Sections of other executor types, kept as submitted. */
76
+ [section: string]: unknown;
59
77
  }
60
78
 
61
79
  export interface Progress {
@@ -75,6 +93,8 @@ export interface OutputResult {
75
93
  name: string;
76
94
  uri: string;
77
95
  bytes: number | null;
96
+ /** Small results returned inline instead of written to an endpoint, e.g. an ffprobe job's JSON (`uri: 'inline:'`). */
97
+ data?: unknown;
78
98
  }
79
99
 
80
100
  export interface JobEvent {
@@ -212,6 +232,7 @@ export function normalizeKinds(kinds?: JobKind[] | string): JobKind[];
212
232
  /** Slot pools sized from the CPU count: batch only cores/2, stream only cores, both: default cores/2 plus stream cores/4. */
213
233
  export function autoSlots(opts?: { cpus?: number; kinds?: JobKind[]; coresPerSlot?: number }): Record<string, number>;
214
234
  export function runFfmpegJob(spec: JobSpec & { id: string }, runtime: ExecutorRuntime): Promise<Required<ExecutorResult>>;
235
+ export function runFfprobeJob(spec: JobSpec & { id: string }, runtime: ExecutorRuntime & { ffprobePath?: string }): Promise<Required<ExecutorResult>>;
215
236
 
216
237
  export class JobHandle extends EventEmitter {
217
238
  readonly id: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fffleet",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Run ffmpeg jobs locally, on one worker or across a pool, through one client and one job contract",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -1,11 +1,12 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
+ import { siblingProbe } from './ffprobe.js';
3
4
 
4
5
  const run = promisify(execFile);
5
6
 
6
7
  /**
7
8
  * Lists what this machine can do, as capability strings matched against a spec's `requires`:
8
- * `type:ffmpeg`, `ffmpeg:<major.minor>`, `filter:<name>`, `encoder:<name>`, `font:<family>`.
9
+ * `type:ffmpeg`, `type:ffprobe`, `ffmpeg:<major.minor>`, `filter:<name>`, `encoder:<name>`, `font:<family>`.
9
10
  * Missing tools simply contribute nothing.
10
11
  *
11
12
  * @param {string} [ffmpegPath]
@@ -24,6 +25,7 @@ export async function detectCapabilities(ffmpegPath = 'ffmpeg') {
24
25
  const version = await out(ffmpegPath, ['-hide_banner', '-version']);
25
26
  const v = version.match(/ffmpeg version n?(\d+)\.(\d+)/);
26
27
  if (version) caps.add('type:ffmpeg');
28
+ if (await out(siblingProbe(ffmpegPath), ['-hide_banner', '-version'])) caps.add('type:ffprobe');
27
29
  if (v) caps.add(`ffmpeg:${v[1]}.${v[2]}`);
28
30
 
29
31
  // " T.. ass V->V Render ASS subtitles..."
package/src/ffprobe.js ADDED
@@ -0,0 +1,88 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { mkdir } from 'node:fs/promises';
3
+ import { dirname, extname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { HTTP_SCHEMES } from './contract.js';
6
+ import { FleetError } from './job-record.js';
7
+ import { parseS3Uri } from './s3.js';
8
+
9
+ const SHOW = ['format', 'streams', 'chapters', 'programs'];
10
+ const MAX_RESULT_BYTES = 1024 * 1024;
11
+ const DEFAULT_TIMEOUT_MS = 60_000;
12
+
13
+ /**
14
+ * Runs ffprobe on the job's single input and returns its JSON in the result.
15
+ *
16
+ * Spec: `type: 'ffprobe'`, `kind: 'batch'`, one input (file:, http(s): or s3:), no outputs, and an
17
+ * optional `ffprobe: { show?: ('format' | 'streams' | 'chapters' | 'programs')[] }` (default
18
+ * `['format', 'streams']`). http(s): inputs are read by ffprobe directly (it fetches only what it
19
+ * needs); s3: inputs are staged to the scratch directory first.
20
+ *
21
+ * Result: one output `{ name: 'probe', uri: 'inline:', bytes, data }` where `data` is ffprobe's JSON.
22
+ *
23
+ * @param {import('./types.js').JobSpec & { id: string, ffprobe?: { show?: string[] } }} spec
24
+ * @param {import('./executor.js').ExecutorRuntime & { ffprobePath?: string }} rt
25
+ */
26
+ export async function runFfprobeJob(spec, rt) {
27
+ if (spec.inputs.length !== 1) throw new FleetError('INVALID_SPEC', 'an ffprobe job takes exactly one input', { status: 422 });
28
+ if (spec.outputs.length) throw new FleetError('INVALID_SPEC', 'an ffprobe job takes no outputs; the result is returned inline', { status: 422 });
29
+ const show = spec.ffprobe?.show ?? ['format', 'streams'];
30
+ if (!Array.isArray(show) || !show.length || show.some(s => !SHOW.includes(s))) {
31
+ throw new FleetError('INVALID_SPEC', `ffprobe.show must list some of ${SHOW.join(', ')}`, { status: 422 });
32
+ }
33
+
34
+ const input = spec.inputs[0];
35
+ const url = new URL(input.uri);
36
+ let target = input.uri;
37
+ if (url.protocol === 'file:') {
38
+ target = fileURLToPath(url);
39
+ } else if (url.protocol === 's3:') {
40
+ if (!rt.s3) throw new FleetError('UNSUPPORTED_SCHEME', 'this runner has no S3 credentials for s3: URIs');
41
+ const { bucket, key } = parseS3Uri(input.uri);
42
+ target = join(rt.workDir, 'in', input.name, `file${extname(key)}`);
43
+ await mkdir(dirname(target), { recursive: true });
44
+ rt.setState('staging');
45
+ try {
46
+ await rt.s3.getFile(bucket, key, target, { signal: rt.signal });
47
+ } catch (err) {
48
+ if (rt.signal.aborted) throw rt.signal.reason;
49
+ throw new FleetError('INPUT_FAILED', `could not fetch input "${input.name}": ${err.message}`);
50
+ }
51
+ } else if (!HTTP_SCHEMES.includes(url.protocol)) {
52
+ throw new FleetError('UNSUPPORTED_SCHEME', `ffprobe cannot read ${url.protocol} inputs`);
53
+ }
54
+
55
+ const args = ['-v', 'error', '-print_format', 'json', ...show.map(s => `-show_${s}`), target];
56
+ rt.setState('running');
57
+ const stdout = await runFfprobe(rt.ffprobePath ?? siblingProbe(rt.ffmpegPath), args, spec.timeoutMs ?? DEFAULT_TIMEOUT_MS, rt);
58
+
59
+ let data;
60
+ try {
61
+ data = JSON.parse(stdout);
62
+ } catch {
63
+ throw new FleetError('FFPROBE_OUTPUT', 'ffprobe printed output that is not JSON');
64
+ }
65
+ return { exitCode: 0, outputs: [{ name: 'probe', uri: 'inline:', bytes: Buffer.byteLength(stdout), data }], stderrTail: null };
66
+ }
67
+
68
+ /** `/opt/ffmpeg/bin/ffmpeg` -> `/opt/ffmpeg/bin/ffprobe`; plain `ffmpeg` -> `ffprobe`. */
69
+ export function siblingProbe(ffmpegPath) {
70
+ if (!ffmpegPath) return 'ffprobe';
71
+ return ffmpegPath.replace(/ffmpeg(\.exe)?$/i, 'ffprobe$1');
72
+ }
73
+
74
+ function runFfprobe(cmd, args, timeoutMs, rt) {
75
+ return new Promise((resolve, reject) => {
76
+ const child = execFile(cmd, args, { maxBuffer: MAX_RESULT_BYTES, timeout: timeoutMs, signal: rt.signal }, (err, stdout, stderr) => {
77
+ if (rt.signal.aborted) return reject(rt.signal.reason);
78
+ if (err) {
79
+ if (err.code === 'ENOENT') return reject(new FleetError('SPAWN_FAILED', `could not start ${cmd}: ${err.message}`));
80
+ if (err.killed) return reject(new FleetError('TIMEOUT', `ffprobe did not finish within ${timeoutMs} ms`));
81
+ const tail = String(stderr).trim().slice(-2048) || null;
82
+ return reject(new FleetError('FFPROBE_EXIT', `ffprobe exited with code ${err.code}`, { details: { exitCode: typeof err.code === 'number' ? err.code : null, stderrTail: tail } }));
83
+ }
84
+ resolve(stdout);
85
+ });
86
+ child.stdin?.end();
87
+ });
88
+ }
package/src/index.js CHANGED
@@ -6,6 +6,7 @@ export {
6
6
  export { JobManager, normalizeSlots, normalizeKinds, autoSlots } from './job-manager.js';
7
7
  export { JobRecord, FleetError, byPriority, pruneFinished } from './job-record.js';
8
8
  export { runFfmpegJob } from './executor.js';
9
+ export { runFfprobeJob } from './ffprobe.js';
9
10
  export { createProgressParser } from './progress.js';
10
11
  export { detectCapabilities, satisfies } from './capabilities.js';
11
12
  export { readSse, followJobEvents } from './sse.js';
@@ -8,6 +8,7 @@ import { KINDS, canonicalJson, implicitRequirements, parseSpec } from './contrac
8
8
  import { createInputCache, parseSize } from './input-cache.js';
9
9
  import { createS3Client } from './s3.js';
10
10
  import { runFfmpegJob } from './executor.js';
11
+ import { runFfprobeJob } from './ffprobe.js';
11
12
  import { FleetError, JobRecord, byPriority, pruneFinished } from './job-record.js';
12
13
 
13
14
  /**
@@ -60,7 +61,7 @@ export class JobManager extends EventEmitter {
60
61
  this.maxQueued = maxQueued;
61
62
  this.keepFinished = keepFinished;
62
63
  this.progressIntervalMs = progressIntervalMs;
63
- this.executors = { ffmpeg: runFfmpegJob, ...executors };
64
+ this.executors = { ffmpeg: runFfmpegJob, ffprobe: runFfprobeJob, ...executors };
64
65
  this.workerId = workerId;
65
66
  this.fetch = fetchImpl;
66
67
  this.cache = cache ? createInputCache({ dir: cache.dir, maxBytes: cache.maxBytes === undefined ? undefined : parseSize(cache.maxBytes) }) : null;
package/src/types.js CHANGED
@@ -41,6 +41,7 @@
41
41
  * @property {string} name
42
42
  * @property {string} uri
43
43
  * @property {number | null} bytes
44
+ * @property {unknown} [data] Small result returned inline (an ffprobe job's JSON, `uri: 'inline:'`).
44
45
  *
45
46
  * @typedef {object} JobEvent
46
47
  * @property {string} jobId