fffleet 2.8.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 CHANGED
@@ -23,8 +23,10 @@ export interface Endpoint {
23
23
  * output folder) or a live scheme such as rtmp:, srt:, udp:.
24
24
  */
25
25
  uri: string;
26
- /** 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. */
27
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;
28
30
  }
29
31
 
30
32
  /** What a client submits. Only `kind` and `ffmpeg.args` are required. */
@@ -63,6 +65,8 @@ export interface JobSpecInput {
63
65
  ffmpeg?: { args: string[]; durationMs?: number | null };
64
66
  /** For `type: 'ffprobe'`: which sections to print (default format and streams). */
65
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;
66
70
  [section: string]: unknown;
67
71
  }
68
72
 
@@ -122,8 +126,24 @@ export interface OutputResult {
122
126
  name: string;
123
127
  uri: string;
124
128
  bytes: number | null;
125
- /** Small results returned inline instead of written to an endpoint, e.g. an ffprobe job's JSON (`uri: 'inline:'`). */
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). */
126
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;
127
147
  }
128
148
 
129
149
  export interface JobEvent {
@@ -271,6 +291,18 @@ export function normalizeKinds(kinds?: JobKind[] | string): JobKind[];
271
291
  export function autoSlots(opts?: { cpus?: number; kinds?: JobKind[]; coresPerSlot?: number }): Record<string, number>;
272
292
  export function runFfmpegJob(spec: JobSpec & { id: string }, runtime: ExecutorRuntime): Promise<Required<ExecutorResult>>;
273
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'>;
274
306
 
275
307
  export class JobHandle extends EventEmitter {
276
308
  readonly id: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fffleet",
3
- "version": "2.8.0",
3
+ "version": "2.9.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,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/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,7 @@ 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'); });
120
131
 
121
132
  // Set by a runner that applied a variant (see resolveVariant); a client does not send it.
122
133
  const variant = s.variant;
@@ -149,7 +160,7 @@ export function validateSpec(input) {
149
160
  priority,
150
161
  ...(workerPreference !== undefined ? { workerPreference: [...workerPreference] } : {}),
151
162
  owner,
152
- requires: [...new Set(requires)].sort(),
163
+ requires: [...new Set([...requires, ...(hasInlineOutput(outputs, variants) ? [INLINE_CAPABILITY] : [])])].sort(),
153
164
  labels: { ...labels },
154
165
  timeoutMs,
155
166
  stdin,
@@ -286,10 +297,41 @@ function normalizeEndpoints(list, path, err) {
286
297
  if (typeof e.contentType !== 'string') err(`${p}.contentType`, 'must be a string');
287
298
  else out.contentType = e.contentType;
288
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
+ }
289
308
  return out;
290
309
  });
291
310
  }
292
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
+
293
335
  function checkObjectEndpoints(kind, inputs, outputs, err) {
294
336
  const check = (list, path, isOutput) => list.forEach((e, i) => {
295
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
- async function stageInput(input, { batch, rt, doFetch }) {
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
- if (req.method === 'GET') return send(res, 200, { jobs: backend.list().filter(mine) });
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
@@ -3,7 +3,9 @@ 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
5
  resolveVariant, MAX_VARIANTS,
6
+ INLINE_SCHEME, INLINE_CAPABILITY, INLINE_DEFAULT_MAX_BYTES, INLINE_MAX_BYTES, isInline, withoutInlinePayload,
6
7
  } from './contract.js';
8
+ export { runFlashAnalysisJob, parseFlashOptions, buildReport, flashesOf, frameMetrics, FLASH_STANDARD } from './flash-analysis.js';
7
9
  export { JobManager, normalizeSlots, normalizeKinds, autoSlots } from './job-manager.js';
8
10
  export { JobRecord, FleetError, byPriority, pruneFinished } from './job-record.js';
9
11
  export { runFfmpegJob } from './executor.js';
@@ -9,6 +9,7 @@ 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
  /**
@@ -63,7 +64,7 @@ export class JobManager extends EventEmitter {
63
64
  this.maxQueued = maxQueued;
64
65
  this.keepFinished = keepFinished;
65
66
  this.progressIntervalMs = progressIntervalMs;
66
- this.executors = { ffmpeg: runFfmpegJob, ffprobe: runFfprobeJob, ...executors };
67
+ this.executors = { ffmpeg: runFfmpegJob, ffprobe: runFfprobeJob, 'flash-analysis': runFlashAnalysisJob, ...executors };
67
68
  this.workerId = workerId;
68
69
  this.capabilities = capabilities;
69
70
  this.fetch = fetchImpl;
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 {unknown} [data] Small result returned inline (an ffprobe job's JSON, `uri: 'inline:'`).
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