@animastor/orchestration 0.3.5 → 1.1.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.
Files changed (58) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +37 -0
  3. package/package.json +11 -8
  4. package/src/gen/accept.js +425 -0
  5. package/src/gen/claim.js +155 -0
  6. package/src/gen/commands.js +367 -0
  7. package/src/gen/index.js +110 -0
  8. package/src/gen/local-runner.js +80 -0
  9. package/src/gen/ports.js +169 -0
  10. package/src/gen/progress.js +99 -0
  11. package/src/gen/sql/001-gen-core.js +130 -0
  12. package/src/gen/sql/002-command-jobs.js +58 -0
  13. package/src/gen/sql/003-scope-scenes.js +38 -0
  14. package/src/gen/sql/index.js +35 -0
  15. package/src/gen/sweeper.js +141 -0
  16. package/src/gen/util.js +136 -0
  17. package/src/gen/validate-media.js +368 -0
  18. package/src/index.js +15 -91
  19. package/src/legacy/index.js +100 -0
  20. package/src/{runtime → legacy/runtime}/command-gate.js +11 -2
  21. package/src/{runtime → legacy/runtime}/persistence-port.js +21 -0
  22. package/src/{runtime → legacy/runtime}/reconciliation-engine.js +15 -0
  23. package/src/{runtime → legacy/runtime}/runtime-scheduler.js +9 -0
  24. package/src/{runtime → legacy/runtime}/scene-window.js +17 -0
  25. package/test/artifact-root-binding.test.js +0 -174
  26. package/test/capacity-deferral.test.js +0 -265
  27. package/test/counter-reconciliation.test.js +0 -164
  28. package/test/mocks/redis-mock.js +0 -231
  29. package/test/reconcile-quota-leak.test.js +0 -366
  30. package/test/stage146-d1-artifact-naming.test.js +0 -103
  31. package/test/stage147-a1-null-build-gate.test.js +0 -211
  32. package/test/test-bindings.js +0 -60
  33. /package/src/{host → legacy/host}/host-bindings.js +0 -0
  34. /package/src/{orchestration → legacy/orchestration}/index.js +0 -0
  35. /package/src/{orchestration → legacy/orchestration}/orchestrator.js +0 -0
  36. /package/src/{orchestration → legacy/orchestration}/runtime-result-consumer.js +0 -0
  37. /package/src/{orchestration → legacy/orchestration}/scene-callbacks.js +0 -0
  38. /package/src/{orchestration → legacy/orchestration}/scene-orchestrator.js +0 -0
  39. /package/src/{orchestration → legacy/orchestration}/scene-restoration.js +0 -0
  40. /package/src/{orchestration → legacy/orchestration}/scene-utils.js +0 -0
  41. /package/src/{runtime → legacy/runtime}/active-scenes-index.js +0 -0
  42. /package/src/{runtime → legacy/runtime}/audio-fsm-port.js +0 -0
  43. /package/src/{runtime → legacy/runtime}/circuit-breaker.js +0 -0
  44. /package/src/{runtime → legacy/runtime}/counter-reconciliation.js +0 -0
  45. /package/src/{runtime → legacy/runtime}/dispatch-engine.js +0 -0
  46. /package/src/{runtime → legacy/runtime}/dispatch-outcomes.js +0 -0
  47. /package/src/{runtime → legacy/runtime}/failure-taxonomy.js +0 -0
  48. /package/src/{runtime → legacy/runtime}/hub-cancel-port.js +0 -0
  49. /package/src/{runtime → legacy/runtime}/layer-config-port.js +0 -0
  50. /package/src/{runtime → legacy/runtime}/lease-manager.js +0 -0
  51. /package/src/{runtime → legacy/runtime}/placeholder-audio-port.js +0 -0
  52. /package/src/{runtime → legacy/runtime}/progress-events-port.js +0 -0
  53. /package/src/{runtime → legacy/runtime}/retry-budget-manager.js +0 -0
  54. /package/src/{runtime → legacy/runtime}/runtime-metrics.js +0 -0
  55. /package/src/{runtime → legacy/runtime}/runtime-result-emitter.js +0 -0
  56. /package/src/{runtime → legacy/runtime}/scene-data-port.js +0 -0
  57. /package/src/{runtime → legacy/runtime}/video-fsm-port.js +0 -0
  58. /package/src/{runtime → legacy/runtime}/worker-health.js +0 -0
@@ -0,0 +1,141 @@
1
+ // ======================================================
2
+ // gen/sweeper — the only background loop of v2 generation (ADR §9)
3
+ // ======================================================
4
+ // 1. running with deadline < now() → error 'timeout' (retry or failed)
5
+ // 2. running on a worker silent > offlineAfter → error 'worker_offline' (retry or failed)
6
+ // 3. active command with no live job in gen_command_jobs (created + joined + next stages)
7
+ // → done | partial | failed | cancelled
8
+ // 4. .incoming/*.tmp older than incomingMaxAge → deleted
9
+ // Idempotent. I1: it never INSERTs into gen_jobs — a retry re-queues the
10
+ // SAME row (attempt is kept, the next claim increments it).
11
+
12
+ 'use strict';
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+ const { withTx, notifyProgress } = require('./util');
17
+
18
+ const BATCH = 200;
19
+
20
+ function createSweeper({ pool, accept, outputDir = null, offlineAfterMs = 60_000, incomingMaxAgeMs = 60 * 60_000, logger = console }) {
21
+ const offlineAfterS = Math.max(1, Math.round(offlineAfterMs / 1000));
22
+
23
+ async function failMany(rows, cls, reason) {
24
+ let n = 0;
25
+ for (const row of rows) {
26
+ const r = await accept.failAttempt(row.job_id, row.attempt, cls, reason);
27
+ if (r.status === 200) n += 1;
28
+ }
29
+ return n;
30
+ }
31
+
32
+ const NOTHING_LIVE_SQL = `
33
+ NOT EXISTS (SELECT 1 FROM gen_command_jobs l JOIN gen_jobs j ON j.job_id = l.job_id
34
+ WHERE l.command_id = c.command_id AND j.status IN ('queued','running'))`;
35
+
36
+ async function finishCommands() {
37
+ const cand = await pool.query(
38
+ `SELECT c.command_id FROM gen_commands c WHERE c.status = 'active' AND ${NOTHING_LIVE_SQL} LIMIT ${BATCH}`);
39
+ let n = 0;
40
+ for (const { command_id: id } of cand.rows) {
41
+ const done = await withTx(pool, async (client) => {
42
+ const c = (await client.query(
43
+ `SELECT c.* FROM gen_commands c WHERE c.command_id = $1 AND c.status = 'active' AND ${NOTHING_LIVE_SQL}
44
+ FOR UPDATE OF c SKIP LOCKED`, [id])).rows[0];
45
+ if (!c) return false;
46
+ const k = (await client.query(
47
+ `SELECT count(*) FILTER (WHERE status = 'done')::int AS done,
48
+ count(*) FILTER (WHERE status = 'failed')::int AS failed,
49
+ count(*) FILTER (WHERE status = 'cancelled')::int AS cancelled
50
+ FROM gen_command_jobs l JOIN gen_jobs j ON j.job_id = l.job_id
51
+ WHERE l.command_id = $1`, [id])).rows[0];
52
+ let status;
53
+ if (k.failed === 0 && k.cancelled === 0) status = 'done';
54
+ else if (k.done > 0) status = 'partial';
55
+ else if (k.failed > 0) status = 'failed';
56
+ else status = 'cancelled';
57
+ const err = k.failed || k.cancelled ? `failed=${k.failed} cancelled=${k.cancelled}` : null;
58
+ await client.query(
59
+ `UPDATE gen_commands SET status = $2, finished_at = now(), error = $3 WHERE command_id = $1`,
60
+ [id, status, err]);
61
+ await notifyProgress(client, c.book_id, id);
62
+ return true;
63
+ });
64
+ if (done) n += 1;
65
+ }
66
+ return n;
67
+ }
68
+
69
+ async function cleanIncoming() {
70
+ if (!outputDir) return 0;
71
+ let removed = 0;
72
+ let builds;
73
+ try { builds = await fs.promises.readdir(outputDir, { withFileTypes: true }); } catch (_) { return 0; }
74
+ const cutoff = Date.now() - incomingMaxAgeMs;
75
+ for (const d of builds) {
76
+ if (!d.isDirectory()) continue;
77
+ const dir = path.join(outputDir, d.name, '.incoming');
78
+ let files;
79
+ try { files = await fs.promises.readdir(dir); } catch (_) { continue; }
80
+ for (const f of files) {
81
+ if (!f.endsWith('.tmp')) continue;
82
+ const p = path.join(dir, f);
83
+ try {
84
+ const st = await fs.promises.stat(p);
85
+ if (st.isFile() && st.mtimeMs < cutoff) { await fs.promises.unlink(p); removed += 1; }
86
+ } catch (_) { /* raced with acceptance */ }
87
+ }
88
+ }
89
+ return removed;
90
+ }
91
+
92
+ /** One pass. @returns {Promise<{timeouts:number, offline:number, commands_finished:number, tmp_removed:number}>} */
93
+ async function sweepOnce() {
94
+ const expired = await pool.query(
95
+ `SELECT job_id, attempt FROM gen_jobs WHERE status = 'running' AND deadline < now()
96
+ ORDER BY deadline LIMIT ${BATCH}`);
97
+ const timeouts = await failMany(expired.rows, 'timeout', 'deadline exceeded');
98
+
99
+ const silent = await pool.query(
100
+ `SELECT j.job_id, j.attempt FROM gen_jobs j
101
+ LEFT JOIN workers w ON w.worker_id = j.worker_id
102
+ WHERE j.status = 'running' AND j.executor <> 'local'
103
+ AND (w.worker_id IS NULL OR w.last_seen IS NULL
104
+ OR w.last_seen < floor(extract(epoch from now()))::bigint - $1)
105
+ LIMIT ${BATCH}`, [offlineAfterS]);
106
+ const offline = await failMany(silent.rows, 'worker_offline', `worker silent > ${offlineAfterS}s`);
107
+
108
+ const commandsFinished = await finishCommands();
109
+ const tmpRemoved = await cleanIncoming();
110
+ return { timeouts, offline, commands_finished: commandsFinished, tmp_removed: tmpRemoved };
111
+ }
112
+
113
+ let timer = null;
114
+ let busy = false;
115
+ let stopped = true;
116
+ function startSweeper(intervalMs = 10_000) {
117
+ if (!stopped) return;
118
+ stopped = false;
119
+ const tick = async () => {
120
+ if (stopped) return;
121
+ if (!busy) {
122
+ busy = true;
123
+ try { await sweepOnce(); } catch (err) {
124
+ logger.error && logger.error(`[gen-v2] sweeper: ${err && err.message}`);
125
+ } finally { busy = false; }
126
+ }
127
+ if (!stopped) { timer = setTimeout(tick, intervalMs); if (timer.unref) timer.unref(); }
128
+ };
129
+ timer = setTimeout(tick, intervalMs);
130
+ if (timer.unref) timer.unref();
131
+ }
132
+ function stopSweeper() {
133
+ stopped = true;
134
+ if (timer) clearTimeout(timer);
135
+ timer = null;
136
+ }
137
+
138
+ return { sweepOnce, startSweeper, stopSweeper };
139
+ }
140
+
141
+ module.exports = { createSweeper };
@@ -0,0 +1,136 @@
1
+ // ======================================================
2
+ // gen/util — shared helpers of the v2 orchestration core
3
+ // ======================================================
4
+ // No I/O except through the pg pool handed in by the host. No requires of
5
+ // src/legacy, Redis, Express or ComfyUI (ADR ORCHESTRATION_V2 §5).
6
+
7
+ 'use strict';
8
+
9
+ const crypto = require('crypto');
10
+
11
+ /** Error with an HTTP-ish status and a stable machine code. */
12
+ class GenError extends Error {
13
+ constructor(code, status, message, extra) {
14
+ super(message || code);
15
+ this.name = 'GenError';
16
+ this.code = code;
17
+ this.status = status;
18
+ if (extra) Object.assign(this, extra);
19
+ }
20
+ }
21
+
22
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
23
+ function isUuid(v) { return typeof v === 'string' && UUID_RE.test(v); }
24
+
25
+ function requireUuid(v, name) {
26
+ if (!isUuid(v)) throw new GenError('bad_request', 400, `${name} must be a UUID`);
27
+ return v;
28
+ }
29
+
30
+ function requireText(v, name, max = 256) {
31
+ if (typeof v !== 'string' || v.length === 0 || v.length > max) {
32
+ throw new GenError('bad_request', 400, `${name} must be a non-empty string (<= ${max})`);
33
+ }
34
+ return v;
35
+ }
36
+
37
+ /**
38
+ * Run fn(client) inside BEGIN/COMMIT on a dedicated pooled client.
39
+ * Rolls back on throw. The client is always released.
40
+ */
41
+ async function withTx(pool, fn) {
42
+ const client = await pool.connect();
43
+ try {
44
+ await client.query('BEGIN');
45
+ const out = await fn(client);
46
+ await client.query('COMMIT');
47
+ return out;
48
+ } catch (err) {
49
+ try { await client.query('ROLLBACK'); } catch (_) { /* connection gone */ }
50
+ throw err;
51
+ } finally {
52
+ client.release();
53
+ }
54
+ }
55
+
56
+ // ── kinds / executors / layers ───────────────────────────────────────────
57
+ const KINDS = Object.freeze(['audio_chunk', 'iu_image', 'video_group', 'audio_merge', 'video_merge']);
58
+ const EXECUTOR_OF_KIND = Object.freeze({
59
+ audio_chunk: 'gpu:audio',
60
+ iu_image: 'gpu:image',
61
+ video_group: 'gpu:video',
62
+ audio_merge: 'local',
63
+ video_merge: 'local',
64
+ });
65
+ const LAYER_OF_KIND = Object.freeze({
66
+ audio_chunk: 'audio',
67
+ audio_merge: 'audio',
68
+ iu_image: 'image',
69
+ video_group: 'video',
70
+ video_merge: 'video',
71
+ });
72
+ /** Kinds a command may create directly (first stage, ADR §6.1 п.5 / §6.3). */
73
+ const FIRST_STAGE_KINDS = Object.freeze(['audio_chunk', 'iu_image', 'video_group']);
74
+ const LAYERS = Object.freeze(['audio', 'image', 'video']);
75
+ const WORKER_TYPES = LAYERS;
76
+ const LIVE = Object.freeze(['queued', 'running']);
77
+
78
+ // ── upload token (ADR §7: HMAC of job_id, attempt, exp) ──────────────────
79
+ function sign(secret, jobId, attempt, exp) {
80
+ return crypto.createHmac('sha256', secret)
81
+ .update(`gen-upload:v1:${jobId}:${attempt}:${exp}`)
82
+ .digest('base64url');
83
+ }
84
+
85
+ function issueUploadToken(secret, jobId, attempt, exp) {
86
+ return `v1.${exp}.${sign(secret, jobId, attempt, exp)}`;
87
+ }
88
+
89
+ /** @returns {boolean} true when the token is a valid, unexpired one for (jobId, attempt). */
90
+ function verifyUploadToken(secret, token, jobId, attempt, nowMs = Date.now()) {
91
+ if (typeof token !== 'string') return false;
92
+ const parts = token.split('.');
93
+ if (parts.length !== 3 || parts[0] !== 'v1') return false;
94
+ const exp = Number(parts[1]);
95
+ if (!Number.isSafeInteger(exp) || exp < nowMs) return false;
96
+ const expected = Buffer.from(sign(secret, jobId, attempt, exp));
97
+ const got = Buffer.from(parts[2]);
98
+ return expected.length === got.length && crypto.timingSafeEqual(expected, got);
99
+ }
100
+
101
+ // ── NOTIFY (ADR §9: payload book_id, command_id; delivered on COMMIT) ─────
102
+ const PROGRESS_CHANNEL = 'gen_progress';
103
+ async function notifyProgress(client, bookId, commandId) {
104
+ await client.query('SELECT pg_notify($1, $2)', [PROGRESS_CHANNEL,
105
+ JSON.stringify({ book_id: bookId, command_id: commandId || null })]);
106
+ }
107
+
108
+ /** Link jobs to commands (§4.2a). Idempotent. */
109
+ async function linkJobs(client, commandIds, jobIds) {
110
+ if (!commandIds.length || !jobIds.length) return 0;
111
+ const r = await client.query(
112
+ `INSERT INTO gen_command_jobs (command_id, job_id)
113
+ SELECT c, j FROM unnest($1::uuid[]) AS c CROSS JOIN unnest($2::uuid[]) AS j
114
+ ON CONFLICT DO NOTHING`, [commandIds, jobIds]);
115
+ return r.rowCount;
116
+ }
117
+
118
+ module.exports = {
119
+ PROGRESS_CHANNEL,
120
+ notifyProgress,
121
+ linkJobs,
122
+ GenError,
123
+ isUuid,
124
+ requireUuid,
125
+ requireText,
126
+ withTx,
127
+ KINDS,
128
+ EXECUTOR_OF_KIND,
129
+ LAYER_OF_KIND,
130
+ FIRST_STAGE_KINDS,
131
+ LAYERS,
132
+ WORKER_TYPES,
133
+ LIVE,
134
+ issueUploadToken,
135
+ verifyUploadToken,
136
+ };
@@ -0,0 +1,368 @@
1
+ // ======================================================
2
+ // gen/validate-media — default result validators (ADR §7 п.1, §13.4)
3
+ // ======================================================
4
+ // Audio: MP3 magic bytes (ID3v2 tag or MPEG Layer III frame sync), duration
5
+ // > 0 from the frame headers, and NOT silence — RMS of the decoded PCM above
6
+ // a threshold (parameter, dBFS). Image (1.1.0): PNG structure + CRC, dimensions > 0,
7
+ // pixel data inflates to the IHDR size, NOT a blank / single-colour frame (luma
8
+ // stddev threshold, parameter). Video: MP4 `ftyp` box.
9
+ //
10
+ // PCM decoding is injected (`decodePcm(path) → Int16Array`); the default
11
+ // spawns the `ffmpeg` binary (node builtin child_process, no npm dependency).
12
+ // Fail-closed: no decoder → the result is NOT accepted (reason
13
+ // decoder_unavailable) — «тишина = ready» must never come back.
14
+
15
+ 'use strict';
16
+
17
+ const fs = require('fs');
18
+ const zlib = require('zlib');
19
+ const { spawn } = require('child_process');
20
+
21
+ const DEFAULT_RMS_THRESHOLD_DBFS = -50;
22
+ const MIN_AUDIO_BYTES = 256;
23
+
24
+ // MPEG audio tables (Layer III only)
25
+ const BITRATES_KBPS = {
26
+ 1: [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
27
+ 2: [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
28
+ };
29
+ const SAMPLE_RATES = { 1: [44100, 48000, 32000], 2: [22050, 24000, 16000], 25: [11025, 12000, 8000] };
30
+
31
+ /** Parse one MPEG Layer III frame header at buf[off]. @returns {{len:number, samples:number, sr:number}|null} */
32
+ function parseFrameHeader(buf, off) {
33
+ if (off + 4 > buf.length) return null;
34
+ const b1 = buf[off + 1], b2 = buf[off + 2];
35
+ if (buf[off] !== 0xff || (b1 & 0xe0) !== 0xe0) return null;
36
+ const verBits = (b1 >> 3) & 0x03; // 00 = 2.5, 10 = 2, 11 = 1
37
+ const layerBits = (b1 >> 1) & 0x03; // 01 = Layer III
38
+ if (verBits === 0x01 || layerBits !== 0x01) return null;
39
+ const version = verBits === 0x03 ? 1 : verBits === 0x02 ? 2 : 25;
40
+ const brIdx = (b2 >> 4) & 0x0f;
41
+ const srIdx = (b2 >> 2) & 0x03;
42
+ if (brIdx === 0 || brIdx === 0x0f || srIdx === 0x03) return null;
43
+ const padding = (b2 >> 1) & 0x01;
44
+ const bitrate = BITRATES_KBPS[version === 1 ? 1 : 2][brIdx] * 1000;
45
+ const sr = SAMPLE_RATES[version][srIdx];
46
+ const coef = version === 1 ? 144 : 72;
47
+ const len = Math.floor((coef * bitrate) / sr) + padding;
48
+ return { len, samples: version === 1 ? 1152 : 576, sr };
49
+ }
50
+
51
+ /**
52
+ * Inspect an MP3 buffer: magic + frame walk.
53
+ * @returns {{ok:true, durationSec:number, frames:number}|{ok:false, reason:string}}
54
+ */
55
+ function inspectMp3(buf) {
56
+ if (!Buffer.isBuffer(buf) || buf.length < MIN_AUDIO_BYTES) return { ok: false, reason: 'too_small' };
57
+ let off = 0;
58
+ if (buf[0] === 0x49 && buf[1] === 0x44 && buf[2] === 0x33) { // "ID3"
59
+ if (buf.length < 10) return { ok: false, reason: 'not_mp3' };
60
+ const size = ((buf[6] & 0x7f) << 21) | ((buf[7] & 0x7f) << 14) | ((buf[8] & 0x7f) << 7) | (buf[9] & 0x7f);
61
+ off = 10 + size + ((buf[5] & 0x10) ? 10 : 0);
62
+ }
63
+ const first = parseFrameHeader(buf, off);
64
+ if (!first) return { ok: false, reason: 'not_mp3' };
65
+ let frames = 0;
66
+ let duration = 0;
67
+ while (off < buf.length) {
68
+ const h = parseFrameHeader(buf, off);
69
+ if (!h || h.len <= 4) break;
70
+ if (off + h.len > buf.length) break; // truncated tail frame — not counted
71
+ frames += 1;
72
+ duration += h.samples / h.sr;
73
+ off += h.len;
74
+ }
75
+ if (frames === 0 || !(duration > 0)) return { ok: false, reason: 'zero_duration' };
76
+ return { ok: true, durationSec: duration, frames };
77
+ }
78
+
79
+ /** RMS of 16-bit PCM in dBFS (-Infinity for digital silence). */
80
+ function rmsDbfs(samples) {
81
+ if (!samples || samples.length === 0) return -Infinity;
82
+ let acc = 0;
83
+ for (let i = 0; i < samples.length; i += 1) acc += samples[i] * samples[i];
84
+ const rms = Math.sqrt(acc / samples.length);
85
+ return rms === 0 ? -Infinity : 20 * Math.log10(rms / 32768);
86
+ }
87
+
88
+ /** Default decoder: ffmpeg → mono 16 kHz s16le. Rejects with code ENOENT if ffmpeg is absent. */
89
+ function ffmpegDecodePcm(filePath, { ffmpegPath = 'ffmpeg', timeoutMs = 60_000 } = {}) {
90
+ return new Promise((resolve, reject) => {
91
+ const p = spawn(ffmpegPath, ['-v', 'error', '-nostdin', '-i', filePath, '-f', 's16le', '-ac', '1', '-ar', '16000', '-'],
92
+ { stdio: ['ignore', 'pipe', 'pipe'] });
93
+ const chunks = [];
94
+ let stderr = '';
95
+ const timer = setTimeout(() => { p.kill('SIGKILL'); }, timeoutMs);
96
+ p.stdout.on('data', (d) => chunks.push(d));
97
+ p.stderr.on('data', (d) => { if (stderr.length < 2000) stderr += d.toString(); });
98
+ p.on('error', (err) => { clearTimeout(timer); reject(err); });
99
+ p.on('close', (code) => {
100
+ clearTimeout(timer);
101
+ if (code !== 0) return reject(Object.assign(new Error(`ffmpeg exit ${code}: ${stderr.trim()}`), { code: 'EDECODE' }));
102
+ const buf = Buffer.concat(chunks);
103
+ resolve(new Int16Array(buf.buffer, buf.byteOffset, Math.floor(buf.length / 2)));
104
+ });
105
+ });
106
+ }
107
+
108
+ /**
109
+ * @param {object} [opts]
110
+ * @param {number} [opts.rmsThresholdDbfs=-50] below → silence (rejected)
111
+ * @param {(path:string)=>Promise<Int16Array>} [opts.decodePcm] PCM decoder
112
+ * @returns {(tmpPath:string)=>Promise<{ok:boolean, reason?:string, durationSec?:number, rmsDbfs?:number}>}
113
+ */
114
+ function createAudioValidator(opts = {}) {
115
+ const threshold = Number.isFinite(opts.rmsThresholdDbfs) ? opts.rmsThresholdDbfs : DEFAULT_RMS_THRESHOLD_DBFS;
116
+ const decodePcm = typeof opts.decodePcm === 'function' ? opts.decodePcm : ffmpegDecodePcm;
117
+ return async function validateAudio(tmpPath) {
118
+ const buf = await fs.promises.readFile(tmpPath);
119
+ const mp3 = inspectMp3(buf);
120
+ if (!mp3.ok) return mp3;
121
+ let pcm;
122
+ try {
123
+ pcm = await decodePcm(tmpPath);
124
+ } catch (err) {
125
+ if (err && err.code === 'ENOENT') return { ok: false, reason: 'decoder_unavailable' };
126
+ return { ok: false, reason: 'decode_failed' };
127
+ }
128
+ const level = rmsDbfs(pcm);
129
+ if (!(level >= threshold)) {
130
+ return { ok: false, reason: 'silence', durationSec: mp3.durationSec, rmsDbfs: level };
131
+ }
132
+ return { ok: true, durationSec: mp3.durationSec, rmsDbfs: level };
133
+ };
134
+ }
135
+
136
+ const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
137
+
138
+ // ── PNG (1.1.0): structure + dimensions + «not a blank frame» ────────────
139
+ // A GPU image result is accepted only if it is a well-formed PNG (signature,
140
+ // IHDR first, CRC of every chunk, IDAT present, IEND last), its dimensions are
141
+ // > 0, the pixel stream inflates to exactly the size IHDR promises, and the
142
+ // frame is not one flat colour: the standard deviation of the luma over
143
+ // sampled pixels must reach `minLumaStddev` (default 2.0 on a 0..255 scale).
144
+ // A black / single-colour frame (a VAE or safety-filter failure) has stddev 0;
145
+ // any real picture is far above 2. The same «blank = invalid_result» rule as
146
+ // silence for audio (ADR §7 п.1, §13.4): one retry, then failed.
147
+ const DEFAULT_MIN_LUMA_STDDEV = 2.0;
148
+ const PNG_MAX_SIDE = 16384;
149
+ const PNG_MAX_DECODE_PIXELS = 64 * 1024 * 1024;
150
+ const PNG_SAMPLE_TARGET = 1 << 16; // ~65k pixels sampled for the flatness check
151
+ const PNG_CHANNELS = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
152
+ const PNG_DEPTHS = { 0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6: [8, 16] };
153
+
154
+ const CRC_TABLE = (() => {
155
+ const t = new Uint32Array(256);
156
+ for (let n = 0; n < 256; n += 1) {
157
+ let c = n;
158
+ for (let k = 0; k < 8; k += 1) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
159
+ t[n] = c >>> 0;
160
+ }
161
+ return t;
162
+ })();
163
+ function crc32(buf, start, end) {
164
+ let c = 0xffffffff;
165
+ for (let i = start; i < end; i += 1) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
166
+ return (c ^ 0xffffffff) >>> 0;
167
+ }
168
+
169
+ function paeth(a, b, c) {
170
+ const p = a + b - c;
171
+ const pa = Math.abs(p - a); const pb = Math.abs(p - b); const pc = Math.abs(p - c);
172
+ if (pa <= pb && pa <= pc) return a;
173
+ return pb <= pc ? b : c;
174
+ }
175
+
176
+ /** Undo the per-scanline filters in place. @returns {Buffer|null} raw rows (no filter bytes) */
177
+ function unfilter(data, width, height, bpp, rowBytes) {
178
+ const out = Buffer.alloc(rowBytes * height);
179
+ let prev = null;
180
+ for (let y = 0; y < height; y += 1) {
181
+ const off = y * (rowBytes + 1);
182
+ const type = data[off];
183
+ const row = out.subarray(y * rowBytes, (y + 1) * rowBytes);
184
+ for (let x = 0; x < rowBytes; x += 1) {
185
+ const raw = data[off + 1 + x];
186
+ const a = x >= bpp ? row[x - bpp] : 0;
187
+ const b = prev ? prev[x] : 0;
188
+ const c = prev && x >= bpp ? prev[x - bpp] : 0;
189
+ let v;
190
+ switch (type) {
191
+ case 0: v = raw; break;
192
+ case 1: v = raw + a; break;
193
+ case 2: v = raw + b; break;
194
+ case 3: v = raw + ((a + b) >> 1); break;
195
+ case 4: v = raw + paeth(a, b, c); break;
196
+ default: return null;
197
+ }
198
+ row[x] = v & 0xff;
199
+ }
200
+ prev = row;
201
+ }
202
+ return out;
203
+ }
204
+
205
+ /**
206
+ * Luma standard deviation over sampled pixels (8/16-bit, non-palette or palette).
207
+ * @returns {number}
208
+ */
209
+ function lumaStddev(rows, width, height, colorType, depth, rowBytes, palette) {
210
+ const ch = PNG_CHANNELS[colorType];
211
+ const bytesPerSample = depth === 16 ? 2 : 1;
212
+ const step = Math.max(1, Math.floor(Math.sqrt((width * height) / PNG_SAMPLE_TARGET)));
213
+ const sample = (rowOff, idx) => (depth === 16 ? rows[rowOff + idx * 2] : rows[rowOff + idx]); // high byte
214
+ let n = 0; let sum = 0; let sumSq = 0;
215
+ for (let y = 0; y < height; y += step) {
216
+ const rowOff = y * rowBytes;
217
+ for (let x = 0; x < width; x += step) {
218
+ let l;
219
+ if (colorType === 3) {
220
+ const i = rows[rowOff + x];
221
+ const p = palette && i * 3 + 2 < palette.length ? i * 3 : 0;
222
+ l = palette ? 0.299 * palette[p] + 0.587 * palette[p + 1] + 0.114 * palette[p + 2] : i;
223
+ } else if (colorType === 0 || colorType === 4) {
224
+ l = sample(rowOff, x * ch);
225
+ } else {
226
+ const base = x * ch;
227
+ l = 0.299 * sample(rowOff, base) + 0.587 * sample(rowOff, base + 1) + 0.114 * sample(rowOff, base + 2);
228
+ }
229
+ n += 1; sum += l; sumSq += l * l;
230
+ }
231
+ }
232
+ if (n === 0) return 0;
233
+ const mean = sum / n;
234
+ return Math.sqrt(Math.max(0, sumSq / n - mean * mean));
235
+ }
236
+
237
+ /**
238
+ * Inspect a PNG buffer.
239
+ * @param {Buffer} buf
240
+ * @param {{minLumaStddev?:number}} [opts]
241
+ * @returns {{ok:true, width:number, height:number, lumaStddev:number|null, flat_check:string}
242
+ * |{ok:false, reason:string, width?:number, height?:number, lumaStddev?:number}}
243
+ * reason ∈ not_png | truncated | bad_crc | no_ihdr | bad_dimensions | bad_header | no_idat
244
+ * | no_iend | corrupt_data | blank_frame
245
+ */
246
+ function inspectPng(buf, opts = {}) {
247
+ const minStd = Number.isFinite(opts.minLumaStddev) ? opts.minLumaStddev : DEFAULT_MIN_LUMA_STDDEV;
248
+ if (!Buffer.isBuffer(buf) || buf.length < 8 || !buf.subarray(0, 8).equals(PNG_SIG)) return { ok: false, reason: 'not_png' };
249
+ let off = 8;
250
+ let ihdr = null; let palette = null; let sawIend = false;
251
+ const idat = [];
252
+ let first = true;
253
+ while (off < buf.length) {
254
+ if (off + 12 > buf.length) return { ok: false, reason: 'truncated' };
255
+ const len = buf.readUInt32BE(off);
256
+ const type = buf.toString('latin1', off + 4, off + 8);
257
+ if (len > 0x7fffffff || off + 12 + len > buf.length) return { ok: false, reason: 'truncated' };
258
+ const crc = buf.readUInt32BE(off + 8 + len);
259
+ if (crc32(buf, off + 4, off + 8 + len) !== crc) return { ok: false, reason: 'bad_crc' };
260
+ const data = buf.subarray(off + 8, off + 8 + len);
261
+ if (first && type !== 'IHDR') return { ok: false, reason: 'no_ihdr' };
262
+ first = false;
263
+ if (type === 'IHDR') {
264
+ if (len !== 13) return { ok: false, reason: 'bad_header' };
265
+ ihdr = {
266
+ width: data.readUInt32BE(0), height: data.readUInt32BE(4), depth: data[8], colorType: data[9],
267
+ compression: data[10], filter: data[11], interlace: data[12],
268
+ };
269
+ } else if (type === 'PLTE') {
270
+ palette = data;
271
+ } else if (type === 'IDAT') {
272
+ idat.push(data);
273
+ } else if (type === 'IEND') {
274
+ sawIend = true;
275
+ break;
276
+ }
277
+ off += 12 + len;
278
+ }
279
+ if (!ihdr) return { ok: false, reason: 'no_ihdr' };
280
+ const { width, height, depth, colorType } = ihdr;
281
+ if (!(width > 0 && height > 0) || width > PNG_MAX_SIDE || height > PNG_MAX_SIDE) {
282
+ return { ok: false, reason: 'bad_dimensions', width, height };
283
+ }
284
+ if (!PNG_CHANNELS[colorType] || !PNG_DEPTHS[colorType].includes(depth) || ihdr.compression !== 0 || ihdr.filter !== 0 || ihdr.interlace > 1) {
285
+ return { ok: false, reason: 'bad_header', width, height };
286
+ }
287
+ if (!idat.length) return { ok: false, reason: 'no_idat', width, height };
288
+ if (!sawIend) return { ok: false, reason: 'no_iend', width, height };
289
+
290
+ const bitsPerPixel = PNG_CHANNELS[colorType] * depth;
291
+ const rowBytes = Math.ceil((width * bitsPerPixel) / 8);
292
+ // flatness is measured on non-interlaced, byte-aligned frames (ComfyUI SaveImage:
293
+ // 8-bit RGB/RGBA, no interlace); other layouts are checked structurally only
294
+ const flatCheckable = ihdr.interlace === 0 && depth >= 8 && width * height <= PNG_MAX_DECODE_PIXELS;
295
+ if (!flatCheckable) return { ok: true, width, height, lumaStddev: null, flat_check: 'skipped' };
296
+ let raw;
297
+ try {
298
+ raw = zlib.inflateSync(Buffer.concat(idat), { maxOutputLength: (rowBytes + 1) * height + 1 });
299
+ } catch (_) {
300
+ return { ok: false, reason: 'corrupt_data', width, height };
301
+ }
302
+ if (raw.length !== (rowBytes + 1) * height) return { ok: false, reason: 'corrupt_data', width, height };
303
+ const rows = unfilter(raw, width, height, Math.max(1, bitsPerPixel >> 3), rowBytes);
304
+ if (!rows) return { ok: false, reason: 'corrupt_data', width, height };
305
+ const std = lumaStddev(rows, width, height, colorType, depth, rowBytes, palette);
306
+ if (!(std >= minStd)) return { ok: false, reason: 'blank_frame', width, height, lumaStddev: std };
307
+ return { ok: true, width, height, lumaStddev: std, flat_check: 'done' };
308
+ }
309
+
310
+ /**
311
+ * @param {{minLumaStddev?:number}} [opts]
312
+ * @returns {(tmpPath:string)=>Promise<object>} the iu_image validator (inspectPng of the file)
313
+ */
314
+ function createPngValidator(opts = {}) {
315
+ return async function validatePngFile(tmpPath) {
316
+ return inspectPng(await fs.promises.readFile(tmpPath), opts);
317
+ };
318
+ }
319
+
320
+ async function readHead(filePath, n) {
321
+ const fh = await fs.promises.open(filePath, 'r');
322
+ try {
323
+ const buf = Buffer.alloc(n);
324
+ const { bytesRead } = await fh.read(buf, 0, n, 0);
325
+ return buf.subarray(0, bytesRead);
326
+ } finally { await fh.close(); }
327
+ }
328
+
329
+ /** Full PNG check with the default threshold (1.0.0 checked the signature only). */
330
+ const validatePng = createPngValidator();
331
+
332
+ async function validateMp4(tmpPath) {
333
+ const head = await readHead(tmpPath, 12);
334
+ return head.length >= 8 && head.toString('latin1', 4, 8) === 'ftyp' ? { ok: true } : { ok: false, reason: 'not_mp4' };
335
+ }
336
+
337
+ /**
338
+ * Default validateResult port: dispatches by job.kind.
339
+ * @param {object} [opts] forwarded to createAudioValidator; opts.minLumaStddev → createPngValidator
340
+ */
341
+ function createDefaultValidateResult(opts = {}) {
342
+ const audio = createAudioValidator(opts);
343
+ const png = createPngValidator({ minLumaStddev: opts.minLumaStddev });
344
+ return async function validateResult(job, tmpPath) {
345
+ switch (job && job.kind) {
346
+ case 'audio_chunk':
347
+ case 'audio_merge': return audio(tmpPath);
348
+ case 'iu_image': return png(tmpPath);
349
+ case 'video_group':
350
+ case 'video_merge': return validateMp4(tmpPath);
351
+ default: return { ok: false, reason: 'unknown_kind' };
352
+ }
353
+ };
354
+ }
355
+
356
+ module.exports = {
357
+ DEFAULT_RMS_THRESHOLD_DBFS,
358
+ inspectMp3,
359
+ rmsDbfs,
360
+ ffmpegDecodePcm,
361
+ createAudioValidator,
362
+ createDefaultValidateResult,
363
+ validatePng,
364
+ validateMp4,
365
+ inspectPng,
366
+ createPngValidator,
367
+ DEFAULT_MIN_LUMA_STDDEV,
368
+ };