fffleet 2.7.0 → 2.9.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 +67 -2
- package/package.json +1 -1
- package/src/capabilities.js +5 -0
- package/src/client.js +5 -0
- package/src/contract.js +138 -2
- package/src/executor.js +45 -3
- package/src/flash-analysis.js +269 -0
- package/src/http-api.js +9 -1
- package/src/index.js +3 -0
- package/src/job-manager.js +9 -3
- package/src/job-record.js +6 -2
- package/src/types.js +4 -1
package/index.d.ts
CHANGED
|
@@ -10,6 +10,7 @@ export const FILE_SCHEMES: readonly string[];
|
|
|
10
10
|
export const HTTP_SCHEMES: readonly string[];
|
|
11
11
|
export const PASSTHROUGH_SCHEMES: readonly string[];
|
|
12
12
|
export const OBJECT_SCHEMES: readonly string[];
|
|
13
|
+
export const MAX_VARIANTS: 16;
|
|
13
14
|
|
|
14
15
|
export type JobKind = 'stream' | 'batch';
|
|
15
16
|
export type JobState = 'queued' | 'assigned' | 'staging' | 'running' | 'uploading' | 'succeeded' | 'failed' | 'cancelled';
|
|
@@ -22,8 +23,10 @@ export interface Endpoint {
|
|
|
22
23
|
* output folder) or a live scheme such as rtmp:, srt:, udp:.
|
|
23
24
|
*/
|
|
24
25
|
uri: string;
|
|
25
|
-
/** Content-Type sent when an http(s) output is uploaded. */
|
|
26
|
+
/** Content-Type sent when an http(s) output is uploaded; for an inline: output, the type of its result. */
|
|
26
27
|
contentType?: string;
|
|
28
|
+
/** inline: outputs only: the largest result accepted, in bytes (default 1 MiB, at most 8 MiB). A larger one fails the job. */
|
|
29
|
+
maxBytes?: number;
|
|
27
30
|
}
|
|
28
31
|
|
|
29
32
|
/** What a client submits. Only `kind` and `ffmpeg.args` are required. */
|
|
@@ -40,6 +43,12 @@ export interface JobSpecInput {
|
|
|
40
43
|
priority?: number;
|
|
41
44
|
/** Ordered worker IDs. The first eligible worker wins; unlisted workers are excluded. */
|
|
42
45
|
workerPreference?: string[];
|
|
46
|
+
/**
|
|
47
|
+
* Where-dependent versions of this spec (at most 16). After placement the first variant whose `when` fits the
|
|
48
|
+
* chosen worker replaces the base `ffmpeg`, `inputs`, `outputs` and type section and adds its `labels`.
|
|
49
|
+
* Placement itself (requires, class, workerPreference) uses the base spec.
|
|
50
|
+
*/
|
|
51
|
+
variants?: SpecVariant[];
|
|
43
52
|
owner?: string;
|
|
44
53
|
/** Capabilities a worker must have, e.g. 'filter:ass', 'encoder:libx264', 'font:DejaVu Sans'. */
|
|
45
54
|
requires?: string[];
|
|
@@ -56,6 +65,21 @@ export interface JobSpecInput {
|
|
|
56
65
|
ffmpeg?: { args: string[]; durationMs?: number | null };
|
|
57
66
|
/** For `type: 'ffprobe'`: which sections to print (default format and streams). */
|
|
58
67
|
ffprobe?: { show?: ('format' | 'streams' | 'chapters' | 'programs')[] };
|
|
68
|
+
/** For `type: 'flash-analysis'` (the payload is named after the type): see FlashAnalysisOptions. */
|
|
69
|
+
'flash-analysis'?: FlashAnalysisOptions;
|
|
70
|
+
[section: string]: unknown;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface SpecVariant {
|
|
74
|
+
/** Reported as `variant` on the job; 'variant-<index>' by default. */
|
|
75
|
+
name?: string;
|
|
76
|
+
/** `workers`: any of these worker IDs. `capabilities`: all of these. Both must hold when both are set. */
|
|
77
|
+
when: { workers?: string[]; capabilities?: string[] };
|
|
78
|
+
ffmpeg?: { args: string[]; durationMs?: number | null };
|
|
79
|
+
inputs?: Endpoint[];
|
|
80
|
+
outputs?: Endpoint[];
|
|
81
|
+
labels?: Record<string, string>;
|
|
82
|
+
/** The section of the spec's own type, for types other than ffmpeg. */
|
|
59
83
|
[section: string]: unknown;
|
|
60
84
|
}
|
|
61
85
|
|
|
@@ -69,6 +93,9 @@ export interface JobSpec {
|
|
|
69
93
|
priority: number;
|
|
70
94
|
/** Ordered worker IDs; when set, only listed workers may run the job. */
|
|
71
95
|
workerPreference?: string[];
|
|
96
|
+
variants?: (SpecVariant & { name: string })[];
|
|
97
|
+
/** Name of the variant applied, on the spec a worker runs. */
|
|
98
|
+
variant?: string;
|
|
72
99
|
owner: string;
|
|
73
100
|
requires: string[];
|
|
74
101
|
labels: Record<string, string>;
|
|
@@ -99,8 +126,24 @@ export interface OutputResult {
|
|
|
99
126
|
name: string;
|
|
100
127
|
uri: string;
|
|
101
128
|
bytes: number | null;
|
|
102
|
-
/**
|
|
129
|
+
/** The output's content type, when the spec gave one (inline: outputs and flash-analysis reports). */
|
|
130
|
+
contentType?: string;
|
|
131
|
+
/** Small JSON result returned inline (`uri: 'inline:'` with a JSON content type, or a probe/report). */
|
|
103
132
|
data?: unknown;
|
|
133
|
+
/** Small non-JSON result returned inline, base64-encoded (`uri: 'inline:'`). */
|
|
134
|
+
base64?: string;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The `flash-analysis` payload of a `type: 'flash-analysis'` job. Reports facts; the verdict is the consumer's. */
|
|
138
|
+
export interface FlashAnalysisOptions {
|
|
139
|
+
/** Only "wcag-2.3.1" for now. */
|
|
140
|
+
standard?: 'wcag-2.3.1';
|
|
141
|
+
/** Frames per second sampled from the video, 1 to 60 (default 25). */
|
|
142
|
+
sampleFps?: number;
|
|
143
|
+
/** Width the frames are scaled to before measuring, 16 to 512 (default 64). */
|
|
144
|
+
width?: number;
|
|
145
|
+
/** Only analyse the first N seconds of the input. */
|
|
146
|
+
maxSeconds?: number | null;
|
|
104
147
|
}
|
|
105
148
|
|
|
106
149
|
export interface JobEvent {
|
|
@@ -110,6 +153,8 @@ export interface JobEvent {
|
|
|
110
153
|
state: JobState;
|
|
111
154
|
progress?: Progress;
|
|
112
155
|
workerId?: string | null;
|
|
156
|
+
/** On 'assigned' (and 'queued' after a re-dispatch): the spec variant chosen for the worker, null for the base spec. */
|
|
157
|
+
variant?: string | null;
|
|
113
158
|
exitCode?: number | null;
|
|
114
159
|
error?: JobError;
|
|
115
160
|
outputs?: OutputResult[];
|
|
@@ -127,6 +172,8 @@ export interface JobSnapshot {
|
|
|
127
172
|
labels: Record<string, string>;
|
|
128
173
|
state: JobState;
|
|
129
174
|
workerId: string | null;
|
|
175
|
+
/** The spec variant the job runs as, null for the base spec. */
|
|
176
|
+
variant: string | null;
|
|
130
177
|
createdAt: string;
|
|
131
178
|
startedAt: string | null;
|
|
132
179
|
finishedAt: string | null;
|
|
@@ -161,6 +208,8 @@ export function validateSpec(input: unknown): { ok: true; spec: JobSpec } | { ok
|
|
|
161
208
|
export function parseSpec(input: unknown): JobSpec;
|
|
162
209
|
export function resolvePlaceholders(args: string[], values: { input: Record<string, string>; output: Record<string, string> }): string[];
|
|
163
210
|
export function canonicalJson(value: unknown): string;
|
|
211
|
+
/** The spec to run on a worker: the first variant whose `when` fits, merged over the base (no `variants` left), or the base spec. */
|
|
212
|
+
export function resolveVariant(spec: JobSpec, worker?: { workerId?: string | null; capabilities?: Iterable<string> }): { spec: JobSpec; variant: string | null };
|
|
164
213
|
/** Capabilities a job needs beyond `requires`: `type:<type>`, plus `scheme:s3` for s3: URIs. */
|
|
165
214
|
export function implicitRequirements(spec: Pick<JobSpec, 'type' | 'inputs' | 'outputs'>): string[];
|
|
166
215
|
|
|
@@ -198,6 +247,8 @@ export interface JobManagerOptions {
|
|
|
198
247
|
progressIntervalMs?: number;
|
|
199
248
|
executors?: Record<string, Executor>;
|
|
200
249
|
workerId?: string | null;
|
|
250
|
+
/** This runner's capabilities, used to pick a spec variant. */
|
|
251
|
+
capabilities?: () => Iterable<string>;
|
|
201
252
|
fetch?: typeof fetch;
|
|
202
253
|
/** S3 settings or a client; enables s3: URIs. */
|
|
203
254
|
s3?: S3Config | S3Client | null;
|
|
@@ -240,6 +291,18 @@ export function normalizeKinds(kinds?: JobKind[] | string): JobKind[];
|
|
|
240
291
|
export function autoSlots(opts?: { cpus?: number; kinds?: JobKind[]; coresPerSlot?: number }): Record<string, number>;
|
|
241
292
|
export function runFfmpegJob(spec: JobSpec & { id: string }, runtime: ExecutorRuntime): Promise<Required<ExecutorResult>>;
|
|
242
293
|
export function runFfprobeJob(spec: JobSpec & { id: string }, runtime: ExecutorRuntime & { ffprobePath?: string }): Promise<Required<ExecutorResult>>;
|
|
294
|
+
export function runFlashAnalysisJob(spec: JobSpec & { id: string }, runtime: ExecutorRuntime & { ffprobePath?: string }): Promise<Required<ExecutorResult>>;
|
|
295
|
+
export function parseFlashOptions(input: unknown): Required<FlashAnalysisOptions>;
|
|
296
|
+
export function buildReport(luma: number[], red: number[], options: Required<FlashAnalysisOptions>): Record<string, unknown>;
|
|
297
|
+
export function flashesOf(series: number[], sampleFps: number): { start: number, end: number }[];
|
|
298
|
+
export function frameMetrics(frame: Uint8Array, pixels: number): { luma: number, red: number };
|
|
299
|
+
export const FLASH_STANDARD: 'wcag-2.3.1';
|
|
300
|
+
export const INLINE_SCHEME: 'inline:';
|
|
301
|
+
export const INLINE_CAPABILITY: 'result:inline';
|
|
302
|
+
export const INLINE_DEFAULT_MAX_BYTES: number;
|
|
303
|
+
export const INLINE_MAX_BYTES: number;
|
|
304
|
+
export function isInline(endpoint: Endpoint): boolean;
|
|
305
|
+
export function withoutInlinePayload<T extends { data?: unknown, base64?: string }>(output: T): Omit<T, 'data' | 'base64'>;
|
|
243
306
|
|
|
244
307
|
export class JobHandle extends EventEmitter {
|
|
245
308
|
readonly id: string;
|
|
@@ -248,6 +311,8 @@ export class JobHandle extends EventEmitter {
|
|
|
248
311
|
/** The newest stderr lines ffmpeg wrote while the job runs (null until it writes any). */
|
|
249
312
|
stderrTail: string | null;
|
|
250
313
|
snapshot: JobSnapshot | null;
|
|
314
|
+
/** The spec variant chosen where the job runs (set by the 'assigned' event), null for the base spec. Read it before parsing stdout. */
|
|
315
|
+
variant: string | null;
|
|
251
316
|
/** Resolves with the final snapshot whatever the outcome; check `state`. */
|
|
252
317
|
readonly done: Promise<JobSnapshot>;
|
|
253
318
|
cancel(): Promise<unknown>;
|
package/package.json
CHANGED
package/src/capabilities.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { execFile } from 'node:child_process';
|
|
2
2
|
import { promisify } from 'node:util';
|
|
3
|
+
import { INLINE_CAPABILITY } from './contract.js';
|
|
3
4
|
import { siblingProbe } from './ffprobe.js';
|
|
4
5
|
|
|
5
6
|
const run = promisify(execFile);
|
|
@@ -27,6 +28,10 @@ export async function detectCapabilities(ffmpegPath = 'ffmpeg') {
|
|
|
27
28
|
if (version) caps.add('type:ffmpeg');
|
|
28
29
|
if (await out(siblingProbe(ffmpegPath), ['-hide_banner', '-version'])) caps.add('type:ffprobe');
|
|
29
30
|
if (v) caps.add(`ffmpeg:${v[1]}.${v[2]}`);
|
|
31
|
+
// Built-in flash-analysis runs ffmpeg, so it is claimed only where ffmpeg is.
|
|
32
|
+
if (v) caps.add('type:flash-analysis');
|
|
33
|
+
// Inline outputs are part of this package's contract, so every build that has this module returns them.
|
|
34
|
+
caps.add(INLINE_CAPABILITY);
|
|
30
35
|
|
|
31
36
|
// " T.. ass V->V Render ASS subtitles..."
|
|
32
37
|
for (const line of (await out(ffmpegPath, ['-hide_banner', '-filters'])).split('\n')) {
|
package/src/client.js
CHANGED
|
@@ -24,6 +24,8 @@ export class JobHandle extends EventEmitter {
|
|
|
24
24
|
this.snapshot = null;
|
|
25
25
|
/** The newest stderr lines ffmpeg wrote while the job runs (null until it writes any). */
|
|
26
26
|
this.stderrTail = null;
|
|
27
|
+
/** Name of the spec variant chosen where the job runs (known from the 'assigned' event), or null for the base spec. */
|
|
28
|
+
this.variant = null;
|
|
27
29
|
let resolve, reject;
|
|
28
30
|
/** @type {Promise<import('./types.js').JobSnapshot>} */
|
|
29
31
|
this.done = new Promise((res, rej) => {
|
|
@@ -36,6 +38,7 @@ export class JobHandle extends EventEmitter {
|
|
|
36
38
|
}
|
|
37
39
|
|
|
38
40
|
_event(event) {
|
|
41
|
+
if (event.variant !== undefined) this.variant = event.variant;
|
|
39
42
|
this.emit('event', event);
|
|
40
43
|
if (event.progress) this.emit('progress', event.progress, event);
|
|
41
44
|
if (event.stderrTail) {
|
|
@@ -128,6 +131,7 @@ export function createFleet({ url, token, clientId, clientSecret, scope, fallbac
|
|
|
128
131
|
const m = localManager();
|
|
129
132
|
const { job } = m.submit(spec);
|
|
130
133
|
const handle = new JobHandle(job.id, 'local');
|
|
134
|
+
handle.variant = job.variant ?? null;
|
|
131
135
|
handle._cancel = async () => m.cancel(job.id);
|
|
132
136
|
handle._write = data => m.writeStdin(job.id, data);
|
|
133
137
|
handle._endStdin = () => m.closeStdin(job.id);
|
|
@@ -146,6 +150,7 @@ export function createFleet({ url, token, clientId, clientSecret, scope, fallbac
|
|
|
146
150
|
const job = await request('POST', '/v1/jobs', spec);
|
|
147
151
|
const handle = new JobHandle(job.id, 'remote');
|
|
148
152
|
handle.snapshot = job;
|
|
153
|
+
handle.variant = job.variant ?? null;
|
|
149
154
|
const ac = new AbortController();
|
|
150
155
|
controllers.add(ac);
|
|
151
156
|
const enc = encodeURIComponent(job.id);
|
package/src/contract.js
CHANGED
|
@@ -27,8 +27,18 @@ export const PASSTHROUGH_SCHEMES = Object.freeze(['rtmp:', 'rtmps:', 'srt:', 'ud
|
|
|
27
27
|
* s3://bucket/key is one object; s3://bucket/prefix/ (trailing slash) is an output folder.
|
|
28
28
|
*/
|
|
29
29
|
export const OBJECT_SCHEMES = Object.freeze(['s3:']);
|
|
30
|
+
/**
|
|
31
|
+
* Batch outputs only: the result comes back in the job snapshot instead of an endpoint.
|
|
32
|
+
* JSON (`contentType: application/json`) is returned as `data`, anything else as `base64`.
|
|
33
|
+
* A result over `maxBytes` fails the job with OUTPUT_TOO_LARGE; it is never truncated.
|
|
34
|
+
*/
|
|
35
|
+
export const INLINE_SCHEME = 'inline:';
|
|
36
|
+
export const INLINE_DEFAULT_MAX_BYTES = 1024 * 1024;
|
|
37
|
+
export const INLINE_MAX_BYTES = 8 * 1024 * 1024;
|
|
38
|
+
/** Capability a worker reports when it can return inline outputs; jobs with one require it. */
|
|
39
|
+
export const INLINE_CAPABILITY = 'result:inline';
|
|
30
40
|
|
|
31
|
-
const ALL_SCHEMES = new Set([...FILE_SCHEMES, ...HTTP_SCHEMES, ...PASSTHROUGH_SCHEMES, ...OBJECT_SCHEMES]);
|
|
41
|
+
const ALL_SCHEMES = new Set([...FILE_SCHEMES, ...HTTP_SCHEMES, ...PASSTHROUGH_SCHEMES, ...OBJECT_SCHEMES, INLINE_SCHEME]);
|
|
32
42
|
|
|
33
43
|
const ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
34
44
|
const NAME_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
@@ -117,6 +127,11 @@ export function validateSpec(input) {
|
|
|
117
127
|
const inputs = normalizeEndpoints(s.inputs, 'inputs', err);
|
|
118
128
|
const outputs = normalizeEndpoints(s.outputs, 'outputs', err);
|
|
119
129
|
checkObjectEndpoints(s.kind, inputs, outputs, err);
|
|
130
|
+
if (s.kind === 'stream') outputs.forEach((o, i) => { if (isInline(o)) err(`outputs[${i}].uri`, 'inline: is only supported for batch jobs'); });
|
|
131
|
+
|
|
132
|
+
// Set by a runner that applied a variant (see resolveVariant); a client does not send it.
|
|
133
|
+
const variant = s.variant;
|
|
134
|
+
if (variant !== undefined && (typeof variant !== 'string' || !NAME_RE.test(variant))) err('variant', 'must be 1-64 characters of A-Z a-z 0-9 _ -');
|
|
120
135
|
|
|
121
136
|
let ffmpeg;
|
|
122
137
|
if (type === 'ffmpeg') {
|
|
@@ -131,6 +146,8 @@ export function validateSpec(input) {
|
|
|
131
146
|
}
|
|
132
147
|
}
|
|
133
148
|
|
|
149
|
+
const variants = s.variants === undefined || errors.length ? undefined : normalizeVariants(s, type, err);
|
|
150
|
+
|
|
134
151
|
if (errors.length) return { ok: false, errors };
|
|
135
152
|
|
|
136
153
|
/** @type {any} */
|
|
@@ -143,7 +160,7 @@ export function validateSpec(input) {
|
|
|
143
160
|
priority,
|
|
144
161
|
...(workerPreference !== undefined ? { workerPreference: [...workerPreference] } : {}),
|
|
145
162
|
owner,
|
|
146
|
-
requires: [...new Set(requires)].sort(),
|
|
163
|
+
requires: [...new Set([...requires, ...(hasInlineOutput(outputs, variants) ? [INLINE_CAPABILITY] : [])])].sort(),
|
|
147
164
|
labels: { ...labels },
|
|
148
165
|
timeoutMs,
|
|
149
166
|
stdin,
|
|
@@ -154,9 +171,97 @@ export function validateSpec(input) {
|
|
|
154
171
|
if (redact.length) spec.redact = [...new Set(redact)];
|
|
155
172
|
if (ffmpeg) spec.ffmpeg = ffmpeg;
|
|
156
173
|
else if (s[type] !== undefined) spec[type] = s[type];
|
|
174
|
+
if (variant !== undefined) spec.variant = variant;
|
|
175
|
+
if (variants) spec.variants = variants;
|
|
157
176
|
return { ok: true, spec };
|
|
158
177
|
}
|
|
159
178
|
|
|
179
|
+
export const MAX_VARIANTS = 16;
|
|
180
|
+
const VARIANT_KEYS = new Set(['name', 'when', 'ffmpeg', 'inputs', 'outputs', 'labels']);
|
|
181
|
+
|
|
182
|
+
/** The spec a variant produces: its sections replace the base ones, its labels are added. */
|
|
183
|
+
function mergeVariant(base, v, type) {
|
|
184
|
+
const out = { ...base };
|
|
185
|
+
delete out.variants;
|
|
186
|
+
delete out.variant;
|
|
187
|
+
for (const k of ['ffmpeg', 'inputs', 'outputs']) if (v[k] !== undefined) out[k] = v[k];
|
|
188
|
+
if (type !== 'ffmpeg' && v[type] !== undefined) out[type] = v[type];
|
|
189
|
+
if (v.labels !== undefined) out.labels = { ...(base.labels ?? {}), ...v.labels };
|
|
190
|
+
return out;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Checks `variants` and that each one, merged over the base, is a valid spec. */
|
|
194
|
+
function normalizeVariants(s, type, err) {
|
|
195
|
+
const list = s.variants;
|
|
196
|
+
if (!Array.isArray(list) || list.length === 0 || list.length > MAX_VARIANTS) {
|
|
197
|
+
err('variants', `must be a non-empty array of at most ${MAX_VARIANTS} variants`);
|
|
198
|
+
return undefined;
|
|
199
|
+
}
|
|
200
|
+
const names = new Set();
|
|
201
|
+
return list.map((v, i) => {
|
|
202
|
+
const p = `variants[${i}]`;
|
|
203
|
+
if (!v || typeof v !== 'object' || Array.isArray(v)) {
|
|
204
|
+
err(p, 'must be an object');
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
for (const k of Object.keys(v)) {
|
|
208
|
+
if (!VARIANT_KEYS.has(k) && !(k === type && type !== 'ffmpeg')) err(`${p}.${k}`, `a variant may only set name, when, ffmpeg, inputs, outputs, labels${type !== 'ffmpeg' ? ` or ${type}` : ''}`);
|
|
209
|
+
}
|
|
210
|
+
const name = v.name ?? `variant-${i}`;
|
|
211
|
+
if (typeof name !== 'string' || !NAME_RE.test(name)) err(`${p}.name`, 'must be 1-64 characters of A-Z a-z 0-9 _ -');
|
|
212
|
+
else if (names.has(name)) err(`${p}.name`, `duplicate name "${name}"`);
|
|
213
|
+
names.add(name);
|
|
214
|
+
|
|
215
|
+
const w = v.when;
|
|
216
|
+
const when = {};
|
|
217
|
+
if (!w || typeof w !== 'object' || Array.isArray(w)) err(`${p}.when`, 'must be an object with workers and/or capabilities');
|
|
218
|
+
else {
|
|
219
|
+
for (const k of Object.keys(w)) if (k !== 'workers' && k !== 'capabilities') err(`${p}.when.${k}`, 'unknown condition (known: workers, capabilities)');
|
|
220
|
+
for (const k of ['workers', 'capabilities']) {
|
|
221
|
+
if (w[k] === undefined) continue;
|
|
222
|
+
const arr = w[k];
|
|
223
|
+
if (!Array.isArray(arr) || !arr.length || arr.some(x => typeof x !== 'string' || !x.trim() || x.length > 128)) {
|
|
224
|
+
err(`${p}.when.${k}`, 'must be a non-empty array of strings (1-128 characters each)');
|
|
225
|
+
} else when[k] = [...new Set(arr)];
|
|
226
|
+
}
|
|
227
|
+
if (w.workers === undefined && w.capabilities === undefined) err(`${p}.when`, 'needs workers and/or capabilities');
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (v.labels !== undefined && (!v.labels || typeof v.labels !== 'object' || Array.isArray(v.labels))) {
|
|
231
|
+
err(`${p}.labels`, 'must be an object of string values');
|
|
232
|
+
return null;
|
|
233
|
+
}
|
|
234
|
+
const merged = validateSpec(mergeVariant(s, v, type));
|
|
235
|
+
if (!merged.ok) for (const e of merged.errors) err(`${p}.${e.path}`, e.message);
|
|
236
|
+
|
|
237
|
+
const out = { name, when };
|
|
238
|
+
if (merged.ok) {
|
|
239
|
+
for (const k of ['ffmpeg', 'inputs', 'outputs']) if (v[k] !== undefined) out[k] = merged.spec[k];
|
|
240
|
+
if (type !== 'ffmpeg' && v[type] !== undefined) out[type] = v[type];
|
|
241
|
+
if (v.labels !== undefined) out.labels = { ...v.labels };
|
|
242
|
+
}
|
|
243
|
+
return out;
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Picks the first variant whose `when` fits a worker and returns the spec to run there.
|
|
249
|
+
* `when.workers` matches any listed worker ID, `when.capabilities` needs all listed capabilities; both must hold when both are set.
|
|
250
|
+
* Without a matching variant the base spec is used. The returned spec has no `variants`; `variant` names the one applied.
|
|
251
|
+
* @param {import('./types.js').JobSpec} spec A validated spec.
|
|
252
|
+
* @param {{ workerId?: string | null, capabilities?: Iterable<string> }} worker
|
|
253
|
+
* @returns {{ spec: import('./types.js').JobSpec, variant: string | null }}
|
|
254
|
+
*/
|
|
255
|
+
export function resolveVariant(spec, { workerId = null, capabilities = [] } = {}) {
|
|
256
|
+
if (!spec.variants) return { spec, variant: spec.variant ?? null };
|
|
257
|
+
const caps = capabilities instanceof Set ? capabilities : new Set(capabilities);
|
|
258
|
+
const v = spec.variants.find(x => (!x.when.workers || (workerId !== null && x.when.workers.includes(workerId)))
|
|
259
|
+
&& (!x.when.capabilities || x.when.capabilities.every(c => caps.has(c))));
|
|
260
|
+
const resolved = /** @type {any} */ (mergeVariant(spec, v ?? {}, spec.type));
|
|
261
|
+
if (v) resolved.variant = v.name;
|
|
262
|
+
return { spec: resolved, variant: v ? v.name : null };
|
|
263
|
+
}
|
|
264
|
+
|
|
160
265
|
/** Like validateSpec but throws a ContractError. */
|
|
161
266
|
export function parseSpec(input) {
|
|
162
267
|
const r = validateSpec(input);
|
|
@@ -192,10 +297,41 @@ function normalizeEndpoints(list, path, err) {
|
|
|
192
297
|
if (typeof e.contentType !== 'string') err(`${p}.contentType`, 'must be a string');
|
|
193
298
|
else out.contentType = e.contentType;
|
|
194
299
|
}
|
|
300
|
+
if (url?.protocol === INLINE_SCHEME) {
|
|
301
|
+
if (path === 'inputs') err(`${p}.uri`, 'inline: is only valid for outputs');
|
|
302
|
+
const max = e.maxBytes ?? INLINE_DEFAULT_MAX_BYTES;
|
|
303
|
+
if (!Number.isInteger(max) || max < 1 || max > INLINE_MAX_BYTES) err(`${p}.maxBytes`, `must be an integer from 1 to ${INLINE_MAX_BYTES}`);
|
|
304
|
+
else out.maxBytes = max;
|
|
305
|
+
} else if (e.maxBytes !== undefined) {
|
|
306
|
+
err(`${p}.maxBytes`, 'is only valid on an inline: output');
|
|
307
|
+
}
|
|
195
308
|
return out;
|
|
196
309
|
});
|
|
197
310
|
}
|
|
198
311
|
|
|
312
|
+
/** True for an output whose result comes back inline. */
|
|
313
|
+
export function isInline(endpoint) {
|
|
314
|
+
return typeof endpoint?.uri === 'string' && endpoint.uri.startsWith(INLINE_SCHEME);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Whether the base outputs or any variant's outputs return a result inline (such a job needs INLINE_CAPABILITY). */
|
|
318
|
+
function hasInlineOutput(outputs, variants) {
|
|
319
|
+
return outputs.some(isInline) || (variants ?? []).some(v => (v.outputs ?? []).some(isInline));
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* The part of an output that is kept after the job ends (snapshots, lists, the orchestrator's state file):
|
|
324
|
+
* an inline result's `data` and `base64` are dropped, its size and type stay.
|
|
325
|
+
* @template {{ data?: unknown, base64?: string }} T
|
|
326
|
+
* @param {T} output
|
|
327
|
+
* @returns {Omit<T, 'data' | 'base64'>}
|
|
328
|
+
*/
|
|
329
|
+
export function withoutInlinePayload(output) {
|
|
330
|
+
if (!output || typeof output !== 'object' || (!('data' in output) && !('base64' in output))) return output;
|
|
331
|
+
const { data, base64, ...rest } = output;
|
|
332
|
+
return rest;
|
|
333
|
+
}
|
|
334
|
+
|
|
199
335
|
function checkObjectEndpoints(kind, inputs, outputs, err) {
|
|
200
336
|
const check = (list, path, isOutput) => list.forEach((e, i) => {
|
|
201
337
|
let url;
|
package/src/executor.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { createWriteStream } from 'node:fs';
|
|
3
|
-
import { mkdir, open, readdir, stat } from 'node:fs/promises';
|
|
3
|
+
import { mkdir, open, readdir, readFile, rm, stat } from 'node:fs/promises';
|
|
4
4
|
import { dirname, extname, join } from 'node:path';
|
|
5
5
|
import { Readable } from 'node:stream';
|
|
6
6
|
import { pipeline } from 'node:stream/promises';
|
|
7
7
|
import { fileURLToPath } from 'node:url';
|
|
8
|
-
import { HTTP_SCHEMES, resolvePlaceholders } from './contract.js';
|
|
8
|
+
import { HTTP_SCHEMES, INLINE_SCHEME, resolvePlaceholders } from './contract.js';
|
|
9
9
|
import { FleetError } from './job-record.js';
|
|
10
10
|
import { createProgressParser } from './progress.js';
|
|
11
11
|
import { parseS3Uri } from './s3.js';
|
|
@@ -76,6 +76,12 @@ export async function runFfmpegJob(spec, rt) {
|
|
|
76
76
|
await mkdir(folder ? path : dirname(path), { recursive: true });
|
|
77
77
|
outputs.push({ name: output.name, uri: output.uri, local: path, upload: 's3', folder, contentType: output.contentType });
|
|
78
78
|
values.output[output.name] = path;
|
|
79
|
+
} else if (url.protocol === INLINE_SCHEME) {
|
|
80
|
+
// Written to scratch and read back into the snapshot once ffmpeg is done (see readInlineOutput).
|
|
81
|
+
const path = join(rt.workDir, 'out', `${output.name}.bin`);
|
|
82
|
+
await mkdir(dirname(path), { recursive: true });
|
|
83
|
+
outputs.push({ name: output.name, uri: output.uri, local: path, upload: false, inline: { maxBytes: output.maxBytes, contentType: output.contentType } });
|
|
84
|
+
values.output[output.name] = path;
|
|
79
85
|
} else {
|
|
80
86
|
outputs.push({ name: output.name, uri: output.uri, local: null, upload: false });
|
|
81
87
|
values.output[output.name] = output.uri;
|
|
@@ -107,6 +113,10 @@ export async function runFfmpegJob(spec, rt) {
|
|
|
107
113
|
const results = [];
|
|
108
114
|
if (outputs.some(o => o.upload)) rt.setState('uploading');
|
|
109
115
|
for (const o of outputs) {
|
|
116
|
+
if (o.inline) {
|
|
117
|
+
results.push(await readInlineOutput(o, { exitCode, stderrTail }));
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
110
120
|
let bytes = null;
|
|
111
121
|
if (o.local) {
|
|
112
122
|
try {
|
|
@@ -124,7 +134,39 @@ export async function runFfmpegJob(spec, rt) {
|
|
|
124
134
|
return { exitCode, outputs: results, stderrTail };
|
|
125
135
|
}
|
|
126
136
|
|
|
127
|
-
|
|
137
|
+
/**
|
|
138
|
+
* Reads an inline output back from its scratch file, enforcing its size limit. The file is removed.
|
|
139
|
+
* JSON becomes `data`, anything else `base64`.
|
|
140
|
+
*/
|
|
141
|
+
export async function readInlineOutput(o, { exitCode, stderrTail }) {
|
|
142
|
+
let size;
|
|
143
|
+
try {
|
|
144
|
+
size = (await stat(o.local)).size;
|
|
145
|
+
} catch {
|
|
146
|
+
throw new FleetError('OUTPUT_MISSING', `ffmpeg did not write output "${o.name}"`, { details: { exitCode, stderrTail } });
|
|
147
|
+
}
|
|
148
|
+
const { maxBytes, contentType } = o.inline;
|
|
149
|
+
if (size > maxBytes) {
|
|
150
|
+
throw new FleetError('OUTPUT_TOO_LARGE', `output "${o.name}" is ${size} bytes; its limit is ${maxBytes}`, { details: { bytes: size, maxBytes } });
|
|
151
|
+
}
|
|
152
|
+
const buffer = await readFile(o.local);
|
|
153
|
+
await rm(o.local, { force: true });
|
|
154
|
+
const result = { name: o.name, uri: o.uri, bytes: size };
|
|
155
|
+
if (contentType) result.contentType = contentType;
|
|
156
|
+
const type = (contentType ?? '').split(';')[0].trim().toLowerCase();
|
|
157
|
+
if (type === 'application/json' || type.endsWith('+json')) {
|
|
158
|
+
try {
|
|
159
|
+
result.data = JSON.parse(buffer.toString('utf8'));
|
|
160
|
+
} catch {
|
|
161
|
+
throw new FleetError('OUTPUT_INVALID', `output "${o.name}" is not valid JSON`);
|
|
162
|
+
}
|
|
163
|
+
} else {
|
|
164
|
+
result.base64 = buffer.toString('base64');
|
|
165
|
+
}
|
|
166
|
+
return result;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export async function stageInput(input, { batch, rt, doFetch }) {
|
|
128
170
|
const url = new URL(input.uri);
|
|
129
171
|
if (url.protocol === 'file:') {
|
|
130
172
|
const path = fileURLToPath(url);
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
// The built-in flash-analysis job type: decodes a video with ffmpeg, measures relative luminance and a
|
|
2
|
+
// saturated-red measure for each sampled frame, and returns the flashes it finds as one inline JSON report.
|
|
3
|
+
//
|
|
4
|
+
// This reports facts (counts, intervals, whether more than three flashes fell in one second). It does not
|
|
5
|
+
// decide whether a video passes; that is the consumer's call. The rule is an approximation of WCAG 2.3.1,
|
|
6
|
+
// see LIMITATIONS, and has not been validated against a reference clip set.
|
|
7
|
+
|
|
8
|
+
import { execFile, spawn } from 'node:child_process';
|
|
9
|
+
import { INLINE_DEFAULT_MAX_BYTES, INLINE_SCHEME } from './contract.js';
|
|
10
|
+
import { FleetError } from './job-record.js';
|
|
11
|
+
import { siblingProbe } from './ffprobe.js';
|
|
12
|
+
import { stageInput } from './executor.js';
|
|
13
|
+
|
|
14
|
+
export const FLASH_STANDARD = 'wcag-2.3.1';
|
|
15
|
+
/** A change counts when it is at least this much of the maximum relative luminance (1.0). */
|
|
16
|
+
const STEP = 0.1;
|
|
17
|
+
/** The darker state of a flash must be below this relative luminance. */
|
|
18
|
+
const DARK_LIMIT = 0.8;
|
|
19
|
+
const MAX_FLASHES_PER_SECOND = 3;
|
|
20
|
+
const OPTION_KEYS = new Set(['standard', 'sampleFps', 'width', 'maxSeconds']);
|
|
21
|
+
|
|
22
|
+
export const LIMITATIONS = Object.freeze([
|
|
23
|
+
'sampled at sampleFps; a flash shorter than the sample spacing can be missed',
|
|
24
|
+
'frames are scaled to width before measuring, so small high-contrast areas can average out',
|
|
25
|
+
'the whole frame is measured; the WCAG flash-area limit is not applied, so the report is conservative',
|
|
26
|
+
'overlapping pairs of changes are each counted as a flash, so the count can exceed the number of visual flashes',
|
|
27
|
+
'the red measure approximates the saturated-red test; the rule is not validated against a reference clip set',
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
const invalid = message => new FleetError('INVALID_SPEC', message, { status: 422 });
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Checks the `flash-analysis` payload of a spec and fills in defaults.
|
|
34
|
+
* @param {unknown} input
|
|
35
|
+
*/
|
|
36
|
+
export function parseFlashOptions(input) {
|
|
37
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) throw invalid('flash-analysis must be an object');
|
|
38
|
+
for (const key of Object.keys(input)) if (!OPTION_KEYS.has(key)) throw invalid(`flash-analysis.${key} is not a known option`);
|
|
39
|
+
const { standard = FLASH_STANDARD, sampleFps = 25, width = 64, maxSeconds = null } = /** @type {any} */ (input);
|
|
40
|
+
if (standard !== FLASH_STANDARD) throw invalid(`flash-analysis.standard must be "${FLASH_STANDARD}"`);
|
|
41
|
+
if (!Number.isInteger(sampleFps) || sampleFps < 1 || sampleFps > 60) throw invalid('flash-analysis.sampleFps must be an integer from 1 to 60');
|
|
42
|
+
if (!Number.isInteger(width) || width < 16 || width > 512) throw invalid('flash-analysis.width must be an integer from 16 to 512');
|
|
43
|
+
if (maxSeconds !== null && (!Number.isFinite(maxSeconds) || maxSeconds <= 0)) throw invalid('flash-analysis.maxSeconds must be a positive number');
|
|
44
|
+
return { standard, sampleFps, width, maxSeconds };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** sRGB byte to linear light (WCAG relative luminance input). */
|
|
48
|
+
const LINEAR = Float64Array.from({ length: 256 }, (_, v) => {
|
|
49
|
+
const c = v / 255;
|
|
50
|
+
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Mean relative luminance of an RGB24 frame, and the mean of the red luminance of its red-dominant pixels.
|
|
55
|
+
* @param {Uint8Array} frame rgb24 bytes, pixels * 3 long
|
|
56
|
+
* @param {number} pixels
|
|
57
|
+
*/
|
|
58
|
+
export function frameMetrics(frame, pixels) {
|
|
59
|
+
let luma = 0;
|
|
60
|
+
let red = 0;
|
|
61
|
+
for (let p = 0; p < pixels * 3; p += 3) {
|
|
62
|
+
const r = frame[p];
|
|
63
|
+
const g = frame[p + 1];
|
|
64
|
+
const b = frame[p + 2];
|
|
65
|
+
luma += 0.2126 * LINEAR[r] + 0.7152 * LINEAR[g] + 0.0722 * LINEAR[b];
|
|
66
|
+
if (r > 0 && r > 2 * Math.max(g, b)) red += 0.2126 * LINEAR[r];
|
|
67
|
+
}
|
|
68
|
+
return { luma: luma / pixels, red: red / pixels };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Turning points of a series. A swing is a move of at least `step` from one turning point to the next;
|
|
73
|
+
* swings alternate in direction.
|
|
74
|
+
* @param {number[]} series
|
|
75
|
+
* @param {number} [step]
|
|
76
|
+
* @returns {{ from: number, to: number }[]} indices into series
|
|
77
|
+
*/
|
|
78
|
+
export function swingsOf(series, step = STEP) {
|
|
79
|
+
const swings = [];
|
|
80
|
+
let turn = 0;
|
|
81
|
+
let dir = 0;
|
|
82
|
+
let ext = 0;
|
|
83
|
+
for (let i = 1; i < series.length; i++) {
|
|
84
|
+
const v = series[i];
|
|
85
|
+
if (dir === 0) {
|
|
86
|
+
if (v - series[turn] >= step) {
|
|
87
|
+
dir = 1;
|
|
88
|
+
ext = i;
|
|
89
|
+
} else if (series[turn] - v >= step) {
|
|
90
|
+
dir = -1;
|
|
91
|
+
ext = i;
|
|
92
|
+
}
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (dir === 1) {
|
|
96
|
+
if (v > series[ext]) ext = i;
|
|
97
|
+
else if (series[ext] - v >= step) {
|
|
98
|
+
swings.push({ from: turn, to: ext });
|
|
99
|
+
turn = ext;
|
|
100
|
+
dir = -1;
|
|
101
|
+
ext = i;
|
|
102
|
+
}
|
|
103
|
+
} else if (v < series[ext]) ext = i;
|
|
104
|
+
else if (v - series[ext] >= step) {
|
|
105
|
+
swings.push({ from: turn, to: ext });
|
|
106
|
+
turn = ext;
|
|
107
|
+
dir = 1;
|
|
108
|
+
ext = i;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return swings;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Flashes in a series sampled at `sampleFps`: each pair of consecutive opposing swings of at least `step`
|
|
116
|
+
* whose darker state is below `DARK_LIMIT`. Returns start and end times in seconds, in order.
|
|
117
|
+
* @param {number[]} series
|
|
118
|
+
* @param {number} sampleFps
|
|
119
|
+
*/
|
|
120
|
+
export function flashesOf(series, sampleFps) {
|
|
121
|
+
const swings = swingsOf(series);
|
|
122
|
+
const flashes = [];
|
|
123
|
+
for (let k = 0; k + 1 < swings.length; k++) {
|
|
124
|
+
const a = swings[k];
|
|
125
|
+
const b = swings[k + 1];
|
|
126
|
+
const darker = Math.min(series[a.from], series[a.to], series[b.to]);
|
|
127
|
+
if (darker < DARK_LIMIT) flashes.push({ start: a.from / sampleFps, end: b.to / sampleFps });
|
|
128
|
+
}
|
|
129
|
+
return flashes;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const round3 = n => Math.round(n * 1000) / 1000;
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Summary of one kind of flash: counts, the most in any one second, and the intervals.
|
|
136
|
+
* @param {{ start: number, end: number }[]} flashes
|
|
137
|
+
*/
|
|
138
|
+
export function summariseFlashes(flashes) {
|
|
139
|
+
let max = 0;
|
|
140
|
+
let j = 0;
|
|
141
|
+
for (let i = 0; i < flashes.length; i++) {
|
|
142
|
+
while (flashes[i].start - flashes[j].start >= 1) j++;
|
|
143
|
+
max = Math.max(max, i - j + 1);
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
count: flashes.length,
|
|
147
|
+
maxInAnyOneSecond: max,
|
|
148
|
+
exceedsThreePerSecond: max > MAX_FLASHES_PER_SECOND,
|
|
149
|
+
intervals: flashes.map(f => ({ startSeconds: round3(f.start), endSeconds: round3(f.end) })),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Runs the analysis for one video and returns the report (pure apart from the child processes).
|
|
155
|
+
* Exported so the job type can also be called directly.
|
|
156
|
+
*/
|
|
157
|
+
export function buildReport(luma, red, options) {
|
|
158
|
+
return {
|
|
159
|
+
standard: options.standard,
|
|
160
|
+
sampleFps: options.sampleFps,
|
|
161
|
+
width: options.width,
|
|
162
|
+
durationSeconds: round3(luma.length / options.sampleFps),
|
|
163
|
+
generalFlashes: summariseFlashes(flashesOf(luma, options.sampleFps)),
|
|
164
|
+
redFlashes: summariseFlashes(flashesOf(red, options.sampleFps)),
|
|
165
|
+
limitations: [...LIMITATIONS],
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* The built-in job type `flash-analysis` (batch). Spec:
|
|
171
|
+
* inputs: exactly one video (file:, http(s): or s3:)
|
|
172
|
+
* outputs: exactly one inline output, which receives the report (JSON)
|
|
173
|
+
* 'flash-analysis': { standard?, sampleFps?, width?, maxSeconds? } the payload is named after the type, see parseFlashOptions
|
|
174
|
+
*
|
|
175
|
+
* @param {import('./types.js').JobSpec & { id: string, 'flash-analysis'?: unknown }} spec
|
|
176
|
+
* @param {import('./executor.js').ExecutorRuntime & { ffprobePath?: string }} rt
|
|
177
|
+
*/
|
|
178
|
+
export async function runFlashAnalysisJob(spec, rt) {
|
|
179
|
+
const options = parseFlashOptions(spec['flash-analysis'] ?? {});
|
|
180
|
+
if (spec.inputs.length !== 1) throw invalid('a flash-analysis job takes exactly one input');
|
|
181
|
+
if (spec.outputs.length !== 1 || !spec.outputs[0].uri.startsWith(INLINE_SCHEME)) {
|
|
182
|
+
throw invalid('a flash-analysis job takes exactly one inline output, which receives the report');
|
|
183
|
+
}
|
|
184
|
+
const output = spec.outputs[0];
|
|
185
|
+
|
|
186
|
+
rt.setState('staging');
|
|
187
|
+
const local = await stageInput(spec.inputs[0], { batch: true, rt, doFetch: rt.fetch ?? globalThis.fetch });
|
|
188
|
+
const source = await probeVideo(rt, local);
|
|
189
|
+
|
|
190
|
+
const outW = options.width;
|
|
191
|
+
const outH = Math.max(2, 2 * Math.round((source.height * outW) / source.width / 2));
|
|
192
|
+
const pixels = outW * outH;
|
|
193
|
+
const luma = [];
|
|
194
|
+
const red = [];
|
|
195
|
+
const args = [
|
|
196
|
+
'-hide_banner', '-loglevel', 'error', '-nostdin', '-i', local, '-an',
|
|
197
|
+
...(options.maxSeconds ? ['-t', String(options.maxSeconds)] : []),
|
|
198
|
+
'-vf', `fps=${options.sampleFps},scale=${outW}:${outH}:flags=area`,
|
|
199
|
+
'-f', 'rawvideo', '-pix_fmt', 'rgb24', 'pipe:1',
|
|
200
|
+
];
|
|
201
|
+
rt.setState('running');
|
|
202
|
+
await decodeFrames(rt.ffmpegPath ?? 'ffmpeg', args, {
|
|
203
|
+
signal: rt.signal,
|
|
204
|
+
frameBytes: pixels * 3,
|
|
205
|
+
onFrame: frame => {
|
|
206
|
+
const m = frameMetrics(frame, pixels);
|
|
207
|
+
luma.push(m.luma);
|
|
208
|
+
red.push(m.red);
|
|
209
|
+
},
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
const report = buildReport(luma, red, options);
|
|
213
|
+
const bytes = Buffer.byteLength(JSON.stringify(report));
|
|
214
|
+
const maxBytes = output.maxBytes ?? INLINE_DEFAULT_MAX_BYTES;
|
|
215
|
+
if (bytes > maxBytes) throw new FleetError('OUTPUT_TOO_LARGE', `the report is ${bytes} bytes; its limit is ${maxBytes}`, { details: { bytes, maxBytes } });
|
|
216
|
+
return {
|
|
217
|
+
exitCode: 0,
|
|
218
|
+
outputs: [{ name: output.name, uri: output.uri, bytes, contentType: 'application/json', data: report }],
|
|
219
|
+
stderrTail: null,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function probeVideo(rt, file) {
|
|
224
|
+
const probe = rt.ffprobePath ?? siblingProbe(rt.ffmpegPath);
|
|
225
|
+
return new Promise((resolve, reject) => {
|
|
226
|
+
execFile(probe, ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height', '-of', 'json', file], { signal: rt.signal, timeout: 60000 }, (err, stdout) => {
|
|
227
|
+
if (rt.signal.aborted) return reject(rt.signal.reason);
|
|
228
|
+
if (err) return reject(new FleetError('INPUT_FAILED', `could not read the video: ${err.message}`));
|
|
229
|
+
let stream = null;
|
|
230
|
+
try {
|
|
231
|
+
stream = JSON.parse(stdout).streams?.[0] ?? null;
|
|
232
|
+
} catch {
|
|
233
|
+
// handled below
|
|
234
|
+
}
|
|
235
|
+
if (!stream?.width || !stream?.height) return reject(new FleetError('INPUT_FAILED', 'the input has no video stream'));
|
|
236
|
+
resolve({ width: stream.width, height: stream.height });
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Runs ffmpeg and hands each complete rgb24 frame to onFrame. A trailing partial frame is ignored. */
|
|
242
|
+
function decodeFrames(cmd, args, { signal, frameBytes, onFrame }) {
|
|
243
|
+
return new Promise((resolve, reject) => {
|
|
244
|
+
const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], signal });
|
|
245
|
+
let stderr = '';
|
|
246
|
+
let pending = Buffer.alloc(0);
|
|
247
|
+
child.stderr.on('data', chunk => {
|
|
248
|
+
if (stderr.length < 4096) stderr += chunk;
|
|
249
|
+
});
|
|
250
|
+
child.stdout.on('data', chunk => {
|
|
251
|
+
pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
|
|
252
|
+
let off = 0;
|
|
253
|
+
while (pending.length - off >= frameBytes) {
|
|
254
|
+
onFrame(pending.subarray(off, off + frameBytes));
|
|
255
|
+
off += frameBytes;
|
|
256
|
+
}
|
|
257
|
+
pending = pending.subarray(off);
|
|
258
|
+
});
|
|
259
|
+
child.on('error', err => {
|
|
260
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
261
|
+
reject(new FleetError('SPAWN_FAILED', `could not start ${cmd}: ${err.message}`));
|
|
262
|
+
});
|
|
263
|
+
child.on('close', code => {
|
|
264
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
265
|
+
if (code !== 0) return reject(new FleetError('FFMPEG_EXIT', `ffmpeg exited with code ${code}`, { details: { exitCode: code, stderrTail: stderr.slice(-2000) || null } }));
|
|
266
|
+
resolve();
|
|
267
|
+
});
|
|
268
|
+
});
|
|
269
|
+
}
|
package/src/http-api.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createServer } from 'node:http';
|
|
2
2
|
import { createAuthenticator, sameSecret } from './auth.js';
|
|
3
|
+
import { withoutInlinePayload } from './contract.js';
|
|
3
4
|
import { FleetError } from './job-record.js';
|
|
4
5
|
import { METRICS_CONTENT_TYPE } from './metrics.js';
|
|
5
6
|
|
|
@@ -7,6 +8,12 @@ const JSON_LIMIT = 1024 * 1024;
|
|
|
7
8
|
const STDIN_LIMIT = 1024 * 1024;
|
|
8
9
|
const SSE_KEEPALIVE_MS = 15000;
|
|
9
10
|
|
|
11
|
+
/** A job as a list entry: its inline outputs keep their size and type, not their payload. */
|
|
12
|
+
function withoutListPayloads(job) {
|
|
13
|
+
if (!Array.isArray(job?.outputs)) return job;
|
|
14
|
+
return { ...job, outputs: job.outputs.map(withoutInlinePayload) };
|
|
15
|
+
}
|
|
16
|
+
|
|
10
17
|
/**
|
|
11
18
|
* @typedef {object} JobBackend
|
|
12
19
|
* Anything that runs jobs: the local JobManager (worker) or the orchestrator.
|
|
@@ -60,7 +67,8 @@ export function createApiHandler({ backend, token = null, authenticate = createA
|
|
|
60
67
|
// 201: took a slot (or was handed to a worker) now; 202: waiting in the queue; 200: already known.
|
|
61
68
|
return send(res, created ? ((queued ?? job.state === 'queued') ? 202 : 201) : 200, job);
|
|
62
69
|
}
|
|
63
|
-
|
|
70
|
+
// Lists carry no inline payloads: a report can be large, and the job's own snapshot has it.
|
|
71
|
+
if (req.method === 'GET') return send(res, 200, { jobs: backend.list().filter(mine).map(withoutListPayloads) });
|
|
64
72
|
}
|
|
65
73
|
|
|
66
74
|
const m = url.pathname.match(/^\/v1\/jobs\/([^/]+)(\/events|\/stdin|\/stdin\/close|\/stdout)?$/);
|
package/src/index.js
CHANGED
|
@@ -2,7 +2,10 @@ export { createFleet, JobHandle } from './client.js';
|
|
|
2
2
|
export {
|
|
3
3
|
CONTRACT_VERSION, KINDS, STATES, isFinal, validateSpec, parseSpec, ContractError,
|
|
4
4
|
resolvePlaceholders, canonicalJson, implicitRequirements, FILE_SCHEMES, HTTP_SCHEMES, PASSTHROUGH_SCHEMES, OBJECT_SCHEMES,
|
|
5
|
+
resolveVariant, MAX_VARIANTS,
|
|
6
|
+
INLINE_SCHEME, INLINE_CAPABILITY, INLINE_DEFAULT_MAX_BYTES, INLINE_MAX_BYTES, isInline, withoutInlinePayload,
|
|
5
7
|
} from './contract.js';
|
|
8
|
+
export { runFlashAnalysisJob, parseFlashOptions, buildReport, flashesOf, frameMetrics, FLASH_STANDARD } from './flash-analysis.js';
|
|
6
9
|
export { JobManager, normalizeSlots, normalizeKinds, autoSlots } from './job-manager.js';
|
|
7
10
|
export { JobRecord, FleetError, byPriority, pruneFinished } from './job-record.js';
|
|
8
11
|
export { runFfmpegJob } from './executor.js';
|
package/src/job-manager.js
CHANGED
|
@@ -4,11 +4,12 @@ import { EventEmitter } from 'node:events';
|
|
|
4
4
|
import { mkdir, rm } from 'node:fs/promises';
|
|
5
5
|
import { availableParallelism, tmpdir } from 'node:os';
|
|
6
6
|
import { join } from 'node:path';
|
|
7
|
-
import { KINDS, canonicalJson, implicitRequirements, parseSpec } from './contract.js';
|
|
7
|
+
import { KINDS, canonicalJson, implicitRequirements, parseSpec, resolveVariant } from './contract.js';
|
|
8
8
|
import { createInputCache, parseSize } from './input-cache.js';
|
|
9
9
|
import { createS3Client } from './s3.js';
|
|
10
10
|
import { runFfmpegJob } from './executor.js';
|
|
11
11
|
import { runFfprobeJob } from './ffprobe.js';
|
|
12
|
+
import { runFlashAnalysisJob } from './flash-analysis.js';
|
|
12
13
|
import { FleetError, JobRecord, byPriority, pruneFinished } from './job-record.js';
|
|
13
14
|
|
|
14
15
|
/**
|
|
@@ -34,6 +35,7 @@ export class JobManager extends EventEmitter {
|
|
|
34
35
|
* @param {number} [opts.progressIntervalMs]
|
|
35
36
|
* @param {Record<string, Function>} [opts.executors] type -> (spec, runtime) => Promise<result>
|
|
36
37
|
* @param {string} [opts.workerId]
|
|
38
|
+
* @param {() => Iterable<string>} [opts.capabilities] This runner's capabilities, for picking a spec variant.
|
|
37
39
|
* @param {typeof fetch} [opts.fetch]
|
|
38
40
|
* @param {object | null} [opts.s3] S3 settings (see s3ConfigFromEnv) or a client; enables s3: URIs.
|
|
39
41
|
* @param {{ dir: string, maxBytes?: number | string } | null} [opts.cache] Keeps staged s3: and http(s): inputs between jobs (least recently used removed above maxBytes, default 20 GB).
|
|
@@ -48,6 +50,7 @@ export class JobManager extends EventEmitter {
|
|
|
48
50
|
progressIntervalMs = 1000,
|
|
49
51
|
executors = {},
|
|
50
52
|
workerId = null,
|
|
53
|
+
capabilities = () => [],
|
|
51
54
|
fetch: fetchImpl,
|
|
52
55
|
s3 = null,
|
|
53
56
|
cache = null,
|
|
@@ -61,8 +64,9 @@ export class JobManager extends EventEmitter {
|
|
|
61
64
|
this.maxQueued = maxQueued;
|
|
62
65
|
this.keepFinished = keepFinished;
|
|
63
66
|
this.progressIntervalMs = progressIntervalMs;
|
|
64
|
-
this.executors = { ffmpeg: runFfmpegJob, ffprobe: runFfprobeJob, ...executors };
|
|
67
|
+
this.executors = { ffmpeg: runFfmpegJob, ffprobe: runFfprobeJob, 'flash-analysis': runFlashAnalysisJob, ...executors };
|
|
65
68
|
this.workerId = workerId;
|
|
69
|
+
this.capabilities = capabilities;
|
|
66
70
|
this.fetch = fetchImpl;
|
|
67
71
|
this.cache = cache ? createInputCache({ dir: cache.dir, maxBytes: cache.maxBytes === undefined ? undefined : parseSize(cache.maxBytes) }) : null;
|
|
68
72
|
this.s3 = !s3 ? null : typeof s3.getFile === 'function' ? s3 : createS3Client({ fetch: fetchImpl, ...s3 });
|
|
@@ -84,7 +88,9 @@ export class JobManager extends EventEmitter {
|
|
|
84
88
|
*/
|
|
85
89
|
submit(input) {
|
|
86
90
|
if (this.closed) throw new FleetError('SHUTTING_DOWN', 'job manager is closed', { status: 503 });
|
|
87
|
-
const
|
|
91
|
+
const parsed = parseSpec(input);
|
|
92
|
+
// A spec with variants runs as the variant that fits this runner (an orchestrator sends it already resolved).
|
|
93
|
+
const { spec } = resolveVariant(parsed, { workerId: this.workerId, capabilities: this.capabilities() });
|
|
88
94
|
spec.id ??= `job_${randomUUID()}`;
|
|
89
95
|
|
|
90
96
|
const existing = this.jobs.get(spec.id);
|
package/src/job-record.js
CHANGED
|
@@ -30,6 +30,8 @@ export class JobRecord {
|
|
|
30
30
|
this.id = spec.id;
|
|
31
31
|
this.state = 'queued';
|
|
32
32
|
this.workerId = null;
|
|
33
|
+
/** Name of the spec variant applied where the job runs, or null for the base spec. */
|
|
34
|
+
this.variant = spec.variant ?? null;
|
|
33
35
|
this.createdAt = new Date().toISOString();
|
|
34
36
|
this.order = ++order;
|
|
35
37
|
this.startedAt = null;
|
|
@@ -59,7 +61,7 @@ export class JobRecord {
|
|
|
59
61
|
*/
|
|
60
62
|
static restore(spec, saved) {
|
|
61
63
|
const job = new JobRecord(spec);
|
|
62
|
-
for (const key of ['state', 'workerId', 'createdAt', 'startedAt', 'finishedAt', 'progress', 'exitCode', 'error', 'outputs', 'stderrTail', 'seq']) {
|
|
64
|
+
for (const key of ['state', 'workerId', 'variant', 'createdAt', 'startedAt', 'finishedAt', 'progress', 'exitCode', 'error', 'outputs', 'stderrTail', 'seq']) {
|
|
63
65
|
if (saved[key] !== undefined) job[key] = saved[key];
|
|
64
66
|
}
|
|
65
67
|
if (Array.isArray(saved.history) && saved.history.length) job.history = saved.history;
|
|
@@ -81,6 +83,7 @@ export class JobRecord {
|
|
|
81
83
|
const now = new Date().toISOString();
|
|
82
84
|
if (state === 'running' && !this.startedAt) this.startedAt = now;
|
|
83
85
|
if (fields.workerId !== undefined) this.workerId = fields.workerId;
|
|
86
|
+
if (fields.variant !== undefined) this.variant = fields.variant;
|
|
84
87
|
if (fields.progress) this.progress = fields.progress;
|
|
85
88
|
if (fields.stderrTail !== undefined && !isFinal(state)) this.stderrTail = fields.stderrTail;
|
|
86
89
|
this.state = state;
|
|
@@ -92,7 +95,7 @@ export class JobRecord {
|
|
|
92
95
|
this.stderrTail = fields.stderrTail ?? null;
|
|
93
96
|
}
|
|
94
97
|
const event = { jobId: this.id, seq: ++this.seq, at: now, state };
|
|
95
|
-
for (const key of ['progress', 'workerId', 'exitCode', 'error', 'outputs', 'stderrTail']) {
|
|
98
|
+
for (const key of ['progress', 'workerId', 'variant', 'exitCode', 'error', 'outputs', 'stderrTail']) {
|
|
96
99
|
if (fields[key] !== undefined) event[key] = fields[key];
|
|
97
100
|
}
|
|
98
101
|
if (isFinal(state)) {
|
|
@@ -133,6 +136,7 @@ export class JobRecord {
|
|
|
133
136
|
labels: this.spec.labels,
|
|
134
137
|
state: this.state,
|
|
135
138
|
workerId: this.workerId,
|
|
139
|
+
variant: this.variant,
|
|
136
140
|
createdAt: this.createdAt,
|
|
137
141
|
startedAt: this.startedAt,
|
|
138
142
|
finishedAt: this.finishedAt,
|
package/src/types.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* @property {string} name Referenced from args as {{input:name}} or {{output:name}}.
|
|
9
9
|
* @property {string} uri file:, http(s): or a passthrough scheme such as rtmp:.
|
|
10
10
|
* @property {string} [contentType]
|
|
11
|
+
* @property {number} [maxBytes] inline: outputs only: the largest result accepted.
|
|
11
12
|
*
|
|
12
13
|
* @typedef {object} JobSpec
|
|
13
14
|
* @property {1} contract
|
|
@@ -43,7 +44,9 @@
|
|
|
43
44
|
* @property {string} name
|
|
44
45
|
* @property {string} uri
|
|
45
46
|
* @property {number | null} bytes
|
|
46
|
-
* @property {
|
|
47
|
+
* @property {string} [contentType]
|
|
48
|
+
* @property {unknown} [data] Small JSON result returned inline (`uri: 'inline:'`).
|
|
49
|
+
* @property {string} [base64] Small non-JSON result returned inline.
|
|
47
50
|
*
|
|
48
51
|
* @typedef {object} JobEvent
|
|
49
52
|
* @property {string} jobId
|