@litfamily/litgrok 1.0.24 → 1.0.26
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/.grok/hooks/auto-handoff.mjs +1 -1
- package/.grok/hooks/lit-status-line.mjs +414 -269
- package/.grok/hooks/plan-progress.mjs +11 -2
- package/.grok/hooks/record-passive-event.mjs +20 -9
- package/.grok/hooks/workflow-stage.mjs +48 -13
- package/.grok/rules/00-litgrok.md +21 -12
- package/.grok/skills/autoconference/SKILL.md +3 -1
- package/.grok/skills/autoresearch/SKILL.md +3 -1
- package/.grok/skills/browser-drive/SKILL.md +3 -1
- package/.grok/skills/browser-drive/scripts/capability-probe.mjs +2 -2
- package/.grok/skills/comment-checker/SKILL.md +3 -1
- package/.grok/skills/debugging/SKILL.md +3 -1
- package/.grok/skills/deep-interview/SKILL.md +4 -1
- package/.grok/skills/frontend-ui-ux/scripts/probe.mjs +3 -2
- package/.grok/skills/lit-brainstorm/SKILL.md +162 -0
- package/.grok/skills/lit-brainstorm/references/converge-and-score.md +85 -0
- package/.grok/skills/lit-brainstorm/references/handoff-and-notes.md +66 -0
- package/.grok/skills/lit-brainstorm/references/idea-lane-packet.md +58 -0
- package/.grok/skills/lit-brainstorm/references/idea-lenses.md +60 -0
- package/.grok/skills/lit-diagram-drawer/scripts/diagram-metrics.mjs +1 -1
- package/.grok/skills/lit-diagram-drawer/scripts/export.mjs +6 -6
- package/.grok/skills/lit-diagram-drawer/scripts/renderer-status.mjs +3 -3
- package/.grok/skills/lit-docx/SKILL.md +3 -1
- package/.grok/skills/lit-docx/scripts/convert_md_to_pdf.py +7 -4
- package/.grok/skills/lit-docx/scripts/docx_gate.py +5 -2
- package/.grok/skills/lit-docx/scripts/pdf_fonts.py +63 -0
- package/.grok/skills/lit-docx/scripts/run.mjs +3 -5
- package/.grok/skills/lit-docx/templates/latex/acs/template.tex +5 -0
- package/.grok/skills/lit-docx/templates/latex/elsevier/template.tex +5 -0
- package/.grok/skills/lit-docx/templates/latex/ieee/template.tex +5 -0
- package/.grok/skills/lit-docx/templates/latex/korean-generic/template.tex +5 -0
- package/.grok/skills/lit-docx/templates/latex/nature/template.tex +5 -0
- package/.grok/skills/lit-handoff/SKILL.md +3 -1
- package/.grok/skills/lit-humanizer/scripts/extract.mjs +6 -3
- package/.grok/skills/lit-humanizer/scripts/test-fixtures.mjs +3 -1
- package/.grok/skills/lit-plan/SKILL.md +2 -0
- package/.grok/skills/lit-pptx/SKILL.md +3 -1
- package/.grok/skills/lit-pptx/scripts/deps.cjs +18 -8
- package/.grok/skills/lit-pptx/scripts/proc.cjs +192 -0
- package/.grok/skills/lit-pptx/scripts/run.mjs +3 -5
- package/.grok/skills/lit-recap/SKILL.md +3 -1
- package/.grok/skills/lit-typographic-motion/SKILL.md +9 -6
- package/.grok/skills/lit-typographic-motion/THIRD_PARTY_NOTICES +3 -0
- package/.grok/skills/lit-typographic-motion/fonts/JetBrainsMono-OFL.txt +93 -0
- package/.grok/skills/lit-typographic-motion/fonts/JetBrainsMono-wght-latin.woff2 +0 -0
- package/.grok/skills/lit-typographic-motion/fonts/pins.json +15 -0
- package/.grok/skills/lit-typographic-motion/recipes/negatives/card-scenes/expected.json +16 -0
- package/.grok/skills/lit-typographic-motion/recipes/negatives/card-scenes/index.html +36 -0
- package/.grok/skills/lit-typographic-motion/recipes/negatives/reset-sweep/expected.json +16 -0
- package/.grok/skills/lit-typographic-motion/recipes/negatives/reset-sweep/index.html +24 -0
- package/.grok/skills/lit-typographic-motion/recipes/negatives/still-glow/expected.json +17 -0
- package/.grok/skills/lit-typographic-motion/recipes/negatives/still-glow/index.html +25 -0
- package/.grok/skills/lit-typographic-motion/recipes/negatives/title-slam/expected.json +17 -0
- package/.grok/skills/lit-typographic-motion/recipes/negatives/title-slam/index.html +37 -0
- package/.grok/skills/lit-typographic-motion/recipes/orbit-loop/expected.json +67 -0
- package/.grok/skills/lit-typographic-motion/recipes/orbit-loop/index.html +119 -0
- package/.grok/skills/lit-typographic-motion/recipes/painted-light/expected.json +95 -0
- package/.grok/skills/lit-typographic-motion/recipes/painted-light/index.html +192 -0
- package/.grok/skills/lit-typographic-motion/recipes/weight-tide/expected.json +67 -0
- package/.grok/skills/lit-typographic-motion/recipes/weight-tide/index.html +85 -0
- package/.grok/skills/lit-typographic-motion/references/cover.md +380 -0
- package/.grok/skills/lit-typographic-motion/references/craft-loop.md +4 -0
- package/.grok/skills/lit-typographic-motion/references/runtime.md +14 -3
- package/.grok/skills/lit-typographic-motion/references/stage.md +2 -1
- package/.grok/skills/lit-typographic-motion/references/treatment.md +5 -0
- package/.grok/skills/lit-typographic-motion/requirements-audio.txt +3 -3
- package/.grok/skills/lit-typographic-motion/scripts/lib/cache.mjs +1 -1
- package/.grok/skills/lit-typographic-motion/scripts/lib/chrome.mjs +14 -4
- package/.grok/skills/lit-typographic-motion/scripts/lib/constants.mjs +39 -0
- package/.grok/skills/lit-typographic-motion/scripts/lib/cover-assets.mjs +88 -0
- package/.grok/skills/lit-typographic-motion/scripts/lib/cover-capture.mjs +144 -0
- package/.grok/skills/lit-typographic-motion/scripts/lib/cover-gate.mjs +312 -0
- package/.grok/skills/lit-typographic-motion/scripts/lib/cover-image.mjs +111 -0
- package/.grok/skills/lit-typographic-motion/scripts/lib/cover-pool.mjs +62 -0
- package/.grok/skills/lit-typographic-motion/scripts/lib/cover-sheet.mjs +73 -0
- package/.grok/skills/lit-typographic-motion/scripts/lib/cover-treatment.mjs +104 -0
- package/.grok/skills/lit-typographic-motion/scripts/lib/cover-webp.mjs +134 -0
- package/.grok/skills/lit-typographic-motion/scripts/lib/cover.mjs +347 -0
- package/.grok/skills/lit-typographic-motion/scripts/lib/encode.mjs +1 -1
- package/.grok/skills/lit-typographic-motion/scripts/lib/gate.mjs +2 -2
- package/.grok/skills/lit-typographic-motion/scripts/lib/look.mjs +99 -7
- package/.grok/skills/lit-typographic-motion/scripts/lib/render.mjs +8 -11
- package/.grok/skills/lit-typographic-motion/scripts/lib/sound.mjs +1 -1
- package/.grok/skills/lit-typographic-motion/scripts/lib/stage.mjs +3 -1
- package/.grok/skills/lit-typographic-motion/scripts/lib/treatment.mjs +1 -0
- package/.grok/skills/lit-typographic-motion/scripts/motion.mjs +45 -3
- package/.grok/skills/lit-typographic-motion/scripts/prewarm.mjs +35 -22
- package/.grok/skills/lit-typographic-motion/scripts/stage/cover-init.js +44 -0
- package/.grok/skills/lit-typographic-motion/scripts/stage/loop-kit.js +96 -0
- package/.grok/skills/litgoal/SKILL.md +14 -2
- package/.grok/skills/litgrok/SKILL.md +30 -7
- package/.grok/skills/litresearch/SKILL.md +3 -1
- package/.grok/skills/litwork/SKILL.md +12 -1
- package/.grok/skills/lsp/SKILL.md +3 -1
- package/.grok/skills/lsp-setup/SKILL.md +3 -1
- package/.grok/skills/lsp-setup/scripts/lsp-server-table.mjs +3 -3
- package/.grok/skills/readme-studio/templates/hyperframes/package-lock.json +3 -3
- package/.grok/skills/readme-studio/templates/remotion/package-lock.json +3 -3
- package/.grok/skills/refactor/SKILL.md +3 -1
- package/.grok/skills/review-work/SKILL.md +20 -26
- package/.grok/skills/rules/SKILL.md +3 -1
- package/.grok/skills/start-work/SKILL.md +1 -1
- package/.grok/skills/structural-search/SKILL.md +3 -1
- package/.grok/skills/wikify/SKILL.md +2 -0
- package/.grok-plugin/plugin.json +2 -1
- package/CHANGELOG.md +18 -0
- package/README.md +12 -11
- package/README_ko-KR.md +12 -11
- package/bin/litgrok.mjs +7 -2
- package/bin/status-line-config.mjs +26 -14
- package/docs/assets/cover-motion-still.webp +0 -0
- package/docs/assets/cover-motion.webp +0 -0
- package/docs/assets/cover.webp +0 -0
- package/docs/assets/readme/README.md +5 -5
- package/docs/assets/readme/badge-version.svg +1 -1
- package/docs/assets/skills/lit-brainstorm.webp +0 -0
- package/docs/reference.md +18 -8
- package/docs/reference_ko-KR.md +19 -8
- package/package.json +3 -2
- package/plugin.json +1 -1
|
@@ -16,6 +16,8 @@ export const EXIT = Object.freeze({
|
|
|
16
16
|
STAGE_NONDETERMINISTIC: 18,
|
|
17
17
|
STAGE_NETWORK: 19,
|
|
18
18
|
SOUND_INVALID: 20,
|
|
19
|
+
NO_COVER_ENCODER: 21,
|
|
20
|
+
ASSET_MISSING: 22,
|
|
19
21
|
});
|
|
20
22
|
|
|
21
23
|
export const EXIT_NAMES = Object.freeze({
|
|
@@ -31,6 +33,8 @@ export const EXIT_NAMES = Object.freeze({
|
|
|
31
33
|
18: 'STAGE_NONDETERMINISTIC',
|
|
32
34
|
19: 'STAGE_NETWORK_REQUEST',
|
|
33
35
|
20: 'SOUND_INVALID',
|
|
36
|
+
21: 'BLOCKED_NO_COVER_ENCODER',
|
|
37
|
+
22: 'BLOCKED_ASSET_MISSING',
|
|
34
38
|
});
|
|
35
39
|
|
|
36
40
|
export class BlockedError extends Error {
|
|
@@ -188,3 +192,38 @@ export const STAGE = Object.freeze({
|
|
|
188
192
|
determinismMin: 8,
|
|
189
193
|
determinismMax: 16,
|
|
190
194
|
});
|
|
195
|
+
|
|
196
|
+
// Cover mode (references/cover.md): the README cover loop and the gate that reads its DECODED file.
|
|
197
|
+
// Calibrated on 2026-10-20 against eight earlier painted covers, four slide-like negatives and
|
|
198
|
+
// three pilot loops; a number moves only with a new calibration table. FLOOR fails a cover (every
|
|
199
|
+
// calibration cover passes it, every negative fails it). TARGET is what cover mode delivers and
|
|
200
|
+
// what --strict and a cover render demand; the calibration covers miss it on purpose (a 1.9 s
|
|
201
|
+
// hold, a flash at the seam).
|
|
202
|
+
export const COVER = Object.freeze({
|
|
203
|
+
maxBytes: 3 * 1024 * 1024,
|
|
204
|
+
targetBytes: 2 * 1024 * 1024,
|
|
205
|
+
minSec: 6,
|
|
206
|
+
maxSec: 12,
|
|
207
|
+
gridMs: 50, // metrics sample a fixed grid of max(gridMs, shortest decoded frame)
|
|
208
|
+
stillEps: 0.0005, // a grid step whose mean |dY| (luma 0..1 at ~300 px wide) is below this is still
|
|
209
|
+
lumaWidth: 300,
|
|
210
|
+
floor: Object.freeze({ medianD: 0.0004, movingFrac: 0.45, stillSec: 2.0, seamLocal: 8.0 }),
|
|
211
|
+
target: Object.freeze({ medianD: 0.0015, movingFrac: 0.95, stillSec: 0.5, spike: 6, seamLocal: 2.0, seamLo: 0.25 }),
|
|
212
|
+
minContrast: 4.5,
|
|
213
|
+
// G6: cap height of the title at the width a README shows the cover (about 830 CSS px).
|
|
214
|
+
minGlyphPx: 24,
|
|
215
|
+
displayWidth: 830,
|
|
216
|
+
// ART: frame 0 shows the listed base art (SSIM of its check box against the source).
|
|
217
|
+
artSsim: 0.9,
|
|
218
|
+
artMinShare: 0.1,
|
|
219
|
+
seekSamples: 16, // frames re-rendered out of order in a fresh page
|
|
220
|
+
seekLevels: 1, // the software rasterizer's own rounding when opacity and transform change together
|
|
221
|
+
windowPadSec: 0.5,
|
|
222
|
+
maxDefects: 3,
|
|
223
|
+
captureScale: 2,
|
|
224
|
+
fps: Object.freeze([16, 20, 25]),
|
|
225
|
+
aspects: Object.freeze({ '2:1': Object.freeze({ page: Object.freeze([1200, 600]), out: Object.freeze([1000, 500]) }), '3:2': Object.freeze({ page: Object.freeze([1200, 800]), out: Object.freeze([960, 640]) }) }),
|
|
226
|
+
encode: Object.freeze({ q: 86, edgeQ: 97, edgeFrames: 15, method: 4 }),
|
|
227
|
+
sheetTiles: 12,
|
|
228
|
+
defaultSeed: 20261020,
|
|
229
|
+
});
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Cover assets: every raster a cover page can load (base art, logo, wordmark, texture) is listed in
|
|
2
|
+
// <out>/assets.json with its path, role, source (user or generated) and SHA-256, and the list is
|
|
3
|
+
// checked before the first capture. A listed file that is missing is BLOCKED_ASSET_MISSING (exit
|
|
4
|
+
// 22): the art is supplied or generated, never replaced by a drawn stand-in. The painted-light
|
|
5
|
+
// recipe needs its base art listed. After the render, frame 0 has to show that art: the SSIM of its
|
|
6
|
+
// check box in decoded frame 0 against the source scaled into the art's box.
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { BlockedError, COVER, EXIT } from './constants.mjs';
|
|
11
|
+
import { crop, lanczosResize, ssim } from './cover-image.mjs';
|
|
12
|
+
|
|
13
|
+
export const ASSETS_FILE = 'assets.json';
|
|
14
|
+
export const ASSET_ROLES = Object.freeze(['base-art', 'logo', 'wordmark', 'texture']);
|
|
15
|
+
|
|
16
|
+
const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
17
|
+
const invalid = (field, message) => new BlockedError(EXIT.TREATMENT_INVALID, `BLOCKED_TREATMENT_INVALID field=assets.json ${field}: ${message}`);
|
|
18
|
+
const isBox = (b) => Array.isArray(b) && b.length === 4 && b.every((v) => typeof v === 'number' && v >= 0 && v <= 1) && b[2] > 0 && b[3] > 0 && b[0] + b[2] <= 1 + 1e-9 && b[1] + b[3] <= 1 + 1e-9;
|
|
19
|
+
|
|
20
|
+
function entry(raw, i, coverDir) {
|
|
21
|
+
const f = `assets[${i}]`;
|
|
22
|
+
if (!raw || typeof raw !== 'object') throw invalid(f, 'must be an object');
|
|
23
|
+
if (typeof raw.path !== 'string' || !raw.path.startsWith(`${coverDir}/`) || raw.path.split('/').includes('..')) throw invalid(`${f}.path`, `a path inside ${coverDir}/, relative to the output directory`);
|
|
24
|
+
if (!ASSET_ROLES.includes(raw.role)) throw invalid(`${f}.role`, `one of ${ASSET_ROLES.join(', ')}`);
|
|
25
|
+
if (!['user', 'generated'].includes(raw.source)) throw invalid(`${f}.source`, 'user (supplied) or generated (made for this cover)');
|
|
26
|
+
if (!/^[0-9a-f]{64}$/u.test(raw.sha256 ?? '')) throw invalid(`${f}.sha256`, "the file's SHA-256, 64 lowercase hex");
|
|
27
|
+
if ('box' in raw && !isBox(raw.box)) throw invalid(`${f}.box`, '[x, y, w, h] as fractions of the cover, inside it');
|
|
28
|
+
if (raw.role === 'base-art' && !raw.box) throw invalid(`${f}.box`, 'base art names the box it fills on the cover');
|
|
29
|
+
if ('checkBox' in raw) {
|
|
30
|
+
if (!isBox(raw.checkBox)) throw invalid(`${f}.checkBox`, '[x, y, w, h] as fractions of the cover, inside it');
|
|
31
|
+
if (!raw.box) throw invalid(`${f}.checkBox`, "needs the art's box");
|
|
32
|
+
const [bx, by, bw, bh] = raw.box;
|
|
33
|
+
const [cx, cy, cw, ch] = raw.checkBox;
|
|
34
|
+
if (cx < bx - 1e-9 || cy < by - 1e-9 || cx + cw > bx + bw + 1e-9 || cy + ch > by + bh + 1e-9) throw invalid(`${f}.checkBox`, "lies inside the art's box");
|
|
35
|
+
if (cw * ch < COVER.artMinShare * bw * bh) throw invalid(`${f}.checkBox`, `covers at least ${COVER.artMinShare * 100} % of the art's box`);
|
|
36
|
+
}
|
|
37
|
+
return { path: raw.path, role: raw.role, source: raw.source, sha256: raw.sha256, box: raw.box ?? null, checkBox: raw.checkBox ?? null, title: raw.title === true };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Before capture. `rasters` are the static scan's rasters (paths relative to the cover folder).
|
|
41
|
+
// Exit 22: a listed file is missing, or the painted recipe lists no base art. Exit 17: a raster the
|
|
42
|
+
// list does not name, or a listed file whose bytes changed. Exit 16: a malformed entry.
|
|
43
|
+
export function checkAssets({ out, treatment, rasters, coverDir = 'cover' }) {
|
|
44
|
+
const file = join(out, ASSETS_FILE);
|
|
45
|
+
let assets = [];
|
|
46
|
+
if (existsSync(file)) {
|
|
47
|
+
let doc;
|
|
48
|
+
try { doc = JSON.parse(readFileSync(file, 'utf8')); } catch (error) { throw invalid('', `not valid JSON (${error.message})`); }
|
|
49
|
+
if (!doc || !Array.isArray(doc.assets)) throw invalid('assets', 'an array of { path, role, source, sha256 }');
|
|
50
|
+
assets = doc.assets.map((raw, i) => entry(raw, i, coverDir));
|
|
51
|
+
for (const asset of assets) {
|
|
52
|
+
const real = join(out, asset.path);
|
|
53
|
+
if (!existsSync(real)) throw new BlockedError(EXIT.ASSET_MISSING, `BLOCKED_ASSET_MISSING: ${asset.path} is listed in assets.json and missing; supply it or generate it, never draw a stand-in`);
|
|
54
|
+
if (sha(readFileSync(real)) !== asset.sha256) throw new BlockedError(EXIT.STAGE_CONTRACT, `STAGE_CONTRACT_ERROR: ${asset.path} does not match its sha256 in assets.json; list it again after changing it`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (treatment.recipe === 'painted-light' && !assets.some((a) => a.role === 'base-art')) {
|
|
58
|
+
throw new BlockedError(EXIT.ASSET_MISSING, 'BLOCKED_ASSET_MISSING: the painted-light recipe needs its base art listed in assets.json ({ path, role: base-art, source: user or generated, sha256, box }); supply or generate the painting, never draw a stand-in');
|
|
59
|
+
}
|
|
60
|
+
const listed = new Set(assets.map((a) => a.path));
|
|
61
|
+
for (const raster of rasters) {
|
|
62
|
+
const rel = `${coverDir}/${raster.rel}`;
|
|
63
|
+
if (!listed.has(rel)) throw new BlockedError(EXIT.STAGE_CONTRACT, `STAGE_CONTRACT_ERROR: ${rel} is a raster the page can load and assets.json does not list it; list it with its role, source and sha256`);
|
|
64
|
+
}
|
|
65
|
+
return { assets };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const px = (box, W, H) => box.map((v, k) => Math.round(v * (k % 2 ? H : W)));
|
|
69
|
+
|
|
70
|
+
// Frame 0 shows the base art: the check box (default: the whole art box) cut from decoded frame 0
|
|
71
|
+
// against the same region of the source scaled into the art box. Boxes are fractions of the cover.
|
|
72
|
+
export function artCheck({ frame0, width, height, art, box, checkBox = null }) {
|
|
73
|
+
const [bx, by, bw, bh] = px(box, width, height);
|
|
74
|
+
const scaled = lanczosResize(art.rgba, art.width, art.height, bw, bh);
|
|
75
|
+
const [cx, cy, cw, ch] = px(checkBox ?? box, width, height);
|
|
76
|
+
const value = ssim(crop(frame0, width, [cx, cy, cw, ch]), crop(scaled, bw, [cx - bx, cy - by, cw, ch]), cw, ch);
|
|
77
|
+
return { ssim: value, pass: value >= COVER.artSsim, box: [bx, by, bw, bh], checked: [cx, cy, cw, ch] };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// The lines a finished cover's reply has to carry for every generated asset.
|
|
81
|
+
export function generatedLabels(out) {
|
|
82
|
+
const file = join(out, ASSETS_FILE);
|
|
83
|
+
if (!existsSync(file)) return [];
|
|
84
|
+
try {
|
|
85
|
+
const doc = JSON.parse(readFileSync(file, 'utf8'));
|
|
86
|
+
return (doc.assets ?? []).filter((a) => a?.source === 'generated' && typeof a.path === 'string').map((a) => `the ${String(a.role ?? 'asset').replace('-', ' ')} ${a.path} is generated, not supplied: label it as generated in the reply`);
|
|
87
|
+
} catch { return []; }
|
|
88
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Cover capture: one stage Chrome (the software rung and every stage flag, so a mismatch is always
|
|
2
|
+
// the page's doing) laid out at the cover's CSS size and captured at device scale 2. The page is
|
|
3
|
+
// served from <out>/cover/ on the synthetic stage origin through CDP Fetch interception, beside the
|
|
4
|
+
// /lit/ routes (fonts, the loop kit), and the cover init script runs before any page script. The
|
|
5
|
+
// renderer SEEKS: it calls window.renderFrame(t, { mask }) for any t in [0, 1) in any order, so the
|
|
6
|
+
// master pass, the replay in a fresh browser, the seek-order pass and a window re-render each open
|
|
7
|
+
// their own page here.
|
|
8
|
+
import { randomBytes } from 'node:crypto';
|
|
9
|
+
import { readFileSync } from 'node:fs';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { BlockedError, EXIT, STAGE } from './constants.mjs';
|
|
12
|
+
import { COVER_FLAGS, launchStage, resolveChrome } from './chrome.mjs';
|
|
13
|
+
import { SKILL_ROOT } from './fonts.mjs';
|
|
14
|
+
import { CONTENT_TYPES, resolveStagePath } from './stage-session.mjs';
|
|
15
|
+
|
|
16
|
+
export const LOOP_KIT_PATH = join(SKILL_ROOT, 'scripts', 'stage', 'loop-kit.js');
|
|
17
|
+
export const COVER_INIT_PATH = join(SKILL_ROOT, 'scripts', 'stage', 'cover-init.js');
|
|
18
|
+
|
|
19
|
+
const sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
20
|
+
|
|
21
|
+
// Open one cover page and wait for window.ready. `dir` is the folder served as the site root
|
|
22
|
+
// (<out>/cover for a render; the sheet's own folder for the contact sheet).
|
|
23
|
+
export async function openCover({ dir, fonts, width, height, scale, profileRoot, env = process.env, label = 'c', log = () => {} }) {
|
|
24
|
+
const executable = resolveChrome(env);
|
|
25
|
+
if (!executable) throw new BlockedError(EXIT.NO_CHROME, 'BLOCKED_NO_CHROME: Chrome/Chromium not found; set CHROME_PATH to a Chrome executable');
|
|
26
|
+
const browser = await launchStage({ executable, profileDir: join(profileRoot, `${label}-${randomBytes(3).toString('hex')}`), width, height, scale, extra: COVER_FLAGS });
|
|
27
|
+
const network = [];
|
|
28
|
+
const refused = [];
|
|
29
|
+
const errors = [];
|
|
30
|
+
const kit = readFileSync(LOOP_KIT_PATH);
|
|
31
|
+
const respond = (requestId, status, body, type) => browser.send('Fetch.fulfillRequest', {
|
|
32
|
+
requestId, responseCode: status,
|
|
33
|
+
responseHeaders: [{ name: 'Content-Type', value: type ?? 'text/plain' }, { name: 'Cache-Control', value: 'no-store' }],
|
|
34
|
+
body: Buffer.from(body ?? '').toString('base64'),
|
|
35
|
+
}).catch((error) => log(`cover serve: ${error.message}`));
|
|
36
|
+
browser.on(async (message) => {
|
|
37
|
+
if (message.sessionId !== browser.sessionId) return;
|
|
38
|
+
if (message.method === 'Runtime.exceptionThrown') { errors.push(message.params.exceptionDetails?.exception?.description?.split('\n')[0] ?? message.params.exceptionDetails?.text ?? 'page error'); return; }
|
|
39
|
+
if (message.method !== 'Fetch.requestPaused') return;
|
|
40
|
+
const { requestId, request } = message.params;
|
|
41
|
+
let url;
|
|
42
|
+
try { url = new URL(request.url); } catch { url = null; }
|
|
43
|
+
if (!url || url.protocol !== 'http:' || url.host !== STAGE.host) {
|
|
44
|
+
network.push(request.url);
|
|
45
|
+
await browser.send('Fetch.failRequest', { requestId, errorReason: 'BlockedByClient' }).catch(() => {});
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (url.pathname === '/lit/loop-kit.js') { await respond(requestId, 200, kit, CONTENT_TYPES['.js']); return; }
|
|
49
|
+
if (url.pathname === '/lit/fonts.css') { await respond(requestId, 200, fonts.css, CONTENT_TYPES['.css']); return; }
|
|
50
|
+
if (url.pathname.startsWith('/lit/fonts/')) {
|
|
51
|
+
const route = fonts.routes.get(url.pathname);
|
|
52
|
+
if (route) await respond(requestId, 200, readFileSync(route.path), route.type); else await respond(requestId, 404, 'no such face');
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (url.pathname === '/favicon.ico') { await respond(requestId, 404, ''); return; }
|
|
56
|
+
const resolved = resolveStagePath(dir, url.pathname);
|
|
57
|
+
if (resolved.refused) { refused.push(resolved.refused); await respond(requestId, 403, 'refused'); return; }
|
|
58
|
+
if (resolved.missing) { await respond(requestId, 404, 'not found'); return; }
|
|
59
|
+
await respond(requestId, 200, readFileSync(resolved.file), resolved.type);
|
|
60
|
+
});
|
|
61
|
+
const send = browser.send;
|
|
62
|
+
const evaluate = async (expression, timeoutMs = 120000) => {
|
|
63
|
+
const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, timeoutMs);
|
|
64
|
+
if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description?.split('\n')[0] ?? result.exceptionDetails.text ?? 'page exception');
|
|
65
|
+
return result.result?.value;
|
|
66
|
+
};
|
|
67
|
+
// Anything a cover page may not do, as the exit it earns.
|
|
68
|
+
const check = async (context) => {
|
|
69
|
+
if (network.length) throw new BlockedError(EXIT.STAGE_NETWORK, `STAGE_NETWORK_REQUEST: the cover page requested ${network[0].slice(0, 160)} (blocked); everything is local`);
|
|
70
|
+
if (refused.length) throw new BlockedError(EXIT.STAGE_CONTRACT, `STAGE_CONTRACT_ERROR: ${refused[0]}`);
|
|
71
|
+
const misuse = await evaluate('window.__litCoverMisuse ? window.__litCoverMisuse() : []').catch(() => []);
|
|
72
|
+
if (misuse.length) throw new BlockedError(EXIT.STAGE_NONDETERMINISTIC, `STAGE_NONDETERMINISTIC: the cover page called ${misuse.join(', ')}${context ? ` ${context}` : ''}; a cover frame is a function of t alone (LitLoop.rng(seed) for layout)`);
|
|
73
|
+
};
|
|
74
|
+
try {
|
|
75
|
+
await send('Page.enable');
|
|
76
|
+
await send('Runtime.enable');
|
|
77
|
+
await send('Fetch.enable', { patterns: [{ urlPattern: '*', requestStage: 'Request' }] });
|
|
78
|
+
await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: scale, mobile: false });
|
|
79
|
+
await send('Emulation.setDefaultBackgroundColorOverride', { color: { r: 0, g: 0, b: 0, a: 1 } });
|
|
80
|
+
await send('Page.addScriptToEvaluateOnNewDocument', { source: readFileSync(COVER_INIT_PATH, 'utf8') });
|
|
81
|
+
await send('Page.navigate', { url: `${STAGE.origin}/index.html` });
|
|
82
|
+
const deadline = Date.now() + 60000;
|
|
83
|
+
for (;;) {
|
|
84
|
+
const state = await evaluate('[document.readyState, window.ready === true, typeof window.renderFrame]').catch(() => ['loading', false, 'undefined']);
|
|
85
|
+
if (errors.length) {
|
|
86
|
+
// A page that throws while loading never recovers into a contract-honouring cover; report it now, not after the 60 s wait.
|
|
87
|
+
await check('while loading');
|
|
88
|
+
throw new BlockedError(EXIT.STAGE_CONTRACT, `STAGE_CONTRACT_ERROR: the cover page threw while loading; first page error: ${errors[0]}`);
|
|
89
|
+
}
|
|
90
|
+
if (state[0] === 'complete' && state[1]) {
|
|
91
|
+
await check('while loading');
|
|
92
|
+
if (state[2] !== 'function') throw new BlockedError(EXIT.STAGE_CONTRACT, 'STAGE_CONTRACT_ERROR: the cover page set window.ready but defines no window.renderFrame(t)');
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
if (Date.now() > deadline) {
|
|
96
|
+
await check('while loading');
|
|
97
|
+
const why = errors[0] ? `; first page error: ${errors[0]}` : state[0] === 'complete' ? '; it never set window.ready = true' : '';
|
|
98
|
+
throw new BlockedError(EXIT.STAGE_CONTRACT, `STAGE_CONTRACT_ERROR: the cover page was not ready within 60 s${why}`);
|
|
99
|
+
}
|
|
100
|
+
await sleep(50);
|
|
101
|
+
}
|
|
102
|
+
} catch (error) { await browser.close(); throw error; }
|
|
103
|
+
|
|
104
|
+
return {
|
|
105
|
+
width, height, scale,
|
|
106
|
+
// Draw loop time t (or its title mask), then wait for fonts and two native frames.
|
|
107
|
+
async frame(t, { mask = false } = {}) {
|
|
108
|
+
try {
|
|
109
|
+
await evaluate(`(async () => { await window.renderFrame(${t}, ${JSON.stringify({ mask })}); if (document.fonts) await document.fonts.ready; if (window.__litCoverSettle) await window.__litCoverSettle(); return true; })()`);
|
|
110
|
+
} catch (error) {
|
|
111
|
+
await check(`at t = ${t.toFixed(4)}`);
|
|
112
|
+
throw new BlockedError(EXIT.STAGE_CONTRACT, `STAGE_CONTRACT_ERROR: renderFrame(${t.toFixed(4)}${mask ? ', { mask: true }' : ''}) threw: ${error.message}`);
|
|
113
|
+
}
|
|
114
|
+
await check(`at t = ${t.toFixed(4)}`);
|
|
115
|
+
},
|
|
116
|
+
// The viewport at device scale: (width x scale) by (height x scale) pixels.
|
|
117
|
+
async capture() {
|
|
118
|
+
const shot = await send('Page.captureScreenshot', { format: 'png', optimizeForSpeed: true, captureBeyondViewport: false, fromSurface: true, clip: { x: 0, y: 0, width, height, scale: 1 } });
|
|
119
|
+
return Buffer.from(shot.data, 'base64');
|
|
120
|
+
},
|
|
121
|
+
close: () => browser.close(),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Capture `times` ([index, t] pairs, in the order given) into `dir` as <prefix><index>.png at the
|
|
126
|
+
// cover size. Returns Map(index -> SHA-256 of the written PNG).
|
|
127
|
+
export async function capturePass({ page, pool, times, dir, prefix = 'f', mask = false, width, height }) {
|
|
128
|
+
const hashes = new Map();
|
|
129
|
+
const jobs = [];
|
|
130
|
+
const expected = `${page.width * page.scale}x${page.height * page.scale}`;
|
|
131
|
+
for (const [index, t] of times) {
|
|
132
|
+
await page.frame(t, { mask });
|
|
133
|
+
const png = await page.capture();
|
|
134
|
+
const job = pool.shrink(png, width, height, join(dir, `${prefix}${String(index).padStart(4, '0')}.png`)).then((result) => {
|
|
135
|
+
if (result.captured !== expected) throw new BlockedError(EXIT.STAGE_CONTRACT, `STAGE_CONTRACT_ERROR: a capture decoded to ${result.captured}, not ${expected} (the page must not resize its viewport)`);
|
|
136
|
+
hashes.set(index, result.sha256);
|
|
137
|
+
});
|
|
138
|
+
job.catch(() => {}); // awaited below; this only keeps an early failure from being unhandled meanwhile
|
|
139
|
+
jobs.push(job);
|
|
140
|
+
if (jobs.length >= pool.workers.length * 3) await Promise.all(jobs.splice(0, pool.workers.length));
|
|
141
|
+
}
|
|
142
|
+
await Promise.all(jobs);
|
|
143
|
+
return hashes;
|
|
144
|
+
}
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
// The cover gate (references/cover.md, Gate): G0 determinism, G1 budget and loop, G2 motion energy,
|
|
2
|
+
// G3 anti-slide, G4 seam, G5 title contrast and G6 title cap height, read from the DECODED cover
|
|
3
|
+
// (animated WebP, or the GIF fallback) and never only from the frames the encoder was given. Every
|
|
4
|
+
// motion number is taken on a fixed time grid: the encoder merges identical frames into one long
|
|
5
|
+
// frame, and counting frames would make a slide film look busy. FLOOR fails a cover; TARGET is the
|
|
6
|
+
// cover-mode goal, and --strict (like every cover render) fails on it too, the 2 MiB size included.
|
|
7
|
+
// The numbers live in constants.mjs (COVER) and change only with a new calibration table.
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
import { spawnSync } from 'node:child_process';
|
|
10
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
11
|
+
import { join } from 'node:path';
|
|
12
|
+
import { COVER } from './constants.mjs';
|
|
13
|
+
import { lumaGrid } from './cover-image.mjs';
|
|
14
|
+
import { decodeWebp } from './cover-webp.mjs';
|
|
15
|
+
import { toRgba } from './frame-pool.mjs';
|
|
16
|
+
import { decodePng } from './png.mjs';
|
|
17
|
+
import { findTool } from './render.mjs';
|
|
18
|
+
|
|
19
|
+
const median = (values) => {
|
|
20
|
+
const s = [...values].sort((a, b) => a - b);
|
|
21
|
+
const m = s.length >> 1;
|
|
22
|
+
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
|
23
|
+
};
|
|
24
|
+
const quantile = (values, q) => {
|
|
25
|
+
const s = [...values].sort((a, b) => a - b);
|
|
26
|
+
return s[Math.min(s.length - 1, Math.max(0, Math.round(q * (s.length - 1))))];
|
|
27
|
+
};
|
|
28
|
+
const meanAbsDiff = (a, b) => {
|
|
29
|
+
let sum = 0;
|
|
30
|
+
for (let i = 0; i < a.length; i += 1) sum += Math.abs(a[i] - b[i]);
|
|
31
|
+
return sum / a.length / 255;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export function readPngRgba(file) {
|
|
35
|
+
const decoded = decodePng(readFileSync(file));
|
|
36
|
+
return { width: decoded.width, height: decoded.height, rgba: toRgba(decoded) };
|
|
37
|
+
}
|
|
38
|
+
export const pngFrames = (dir, prefix = 'f') => (existsSync(dir) ? readdirSync(dir).filter((name) => name.startsWith(prefix) && name.endsWith('.png')).sort().map((name) => join(dir, name)) : []);
|
|
39
|
+
|
|
40
|
+
// What a GIF's container says and the ffmpeg pipe does not: per-frame delays (ms) and the loop count.
|
|
41
|
+
export function gifTiming(bytes) {
|
|
42
|
+
if (bytes.toString('latin1', 0, 3) !== 'GIF') throw new Error('not a GIF file');
|
|
43
|
+
const delays = [];
|
|
44
|
+
let loop = null;
|
|
45
|
+
let delay = 100;
|
|
46
|
+
let o = 13;
|
|
47
|
+
if (bytes[10] & 0x80) o += 3 * (1 << ((bytes[10] & 0x07) + 1));
|
|
48
|
+
const skipSubBlocks = (p) => { while (p < bytes.length && bytes[p] !== 0) p += bytes[p] + 1; return p + 1; };
|
|
49
|
+
while (o < bytes.length) {
|
|
50
|
+
const block = bytes[o];
|
|
51
|
+
if (block === 0x3b) break;
|
|
52
|
+
if (block === 0x21) {
|
|
53
|
+
const label = bytes[o + 1];
|
|
54
|
+
if (label === 0xf9) delay = 10 * bytes.readUInt16LE(o + 4);
|
|
55
|
+
if (label === 0xff && bytes.toString('latin1', o + 3, o + 14) === 'NETSCAPE2.0') loop = bytes.readUInt16LE(o + 16);
|
|
56
|
+
o = skipSubBlocks(o + 2);
|
|
57
|
+
} else if (block === 0x2c) {
|
|
58
|
+
let p = o + 10;
|
|
59
|
+
if (bytes[o + 9] & 0x80) p += 3 * (1 << ((bytes[o + 9] & 0x07) + 1));
|
|
60
|
+
o = skipSubBlocks(p + 1);
|
|
61
|
+
delays.push(delay > 0 ? delay : 100);
|
|
62
|
+
delay = 100;
|
|
63
|
+
} else break;
|
|
64
|
+
}
|
|
65
|
+
return { delays, loop, width: bytes.readUInt16LE(6), height: bytes.readUInt16LE(8) };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Load a cover for the gate: { lumas, delays, width, height, loop, bytes, format, kept }. keep(i,
|
|
69
|
+
// durationMs) is asked once per decoded frame, in order, and says which frames to keep whole
|
|
70
|
+
// (RGBA) for the stills, the poster and the frame-0 art check.
|
|
71
|
+
export function loadCover(input, { fps = 16, keep = () => false, env = process.env } = {}) {
|
|
72
|
+
const kept = new Map();
|
|
73
|
+
const lumas = [];
|
|
74
|
+
if (statSync(input).isDirectory()) {
|
|
75
|
+
const files = pngFrames(input);
|
|
76
|
+
let width = 0, height = 0;
|
|
77
|
+
files.forEach((file, i) => {
|
|
78
|
+
const image = readPngRgba(file);
|
|
79
|
+
({ width, height } = image);
|
|
80
|
+
lumas.push(lumaGrid(image.rgba, width, height).luma);
|
|
81
|
+
if (keep(i, 1000 / fps)) kept.set(i, image.rgba);
|
|
82
|
+
});
|
|
83
|
+
return { lumas, delays: files.map(() => 1000 / fps), width, height, loop: 0, bytes: null, format: 'png', kept };
|
|
84
|
+
}
|
|
85
|
+
if (input.toLowerCase().endsWith('.gif')) {
|
|
86
|
+
const bytes = readFileSync(input);
|
|
87
|
+
const timing = gifTiming(bytes);
|
|
88
|
+
const ffmpeg = findTool('ffmpeg', env);
|
|
89
|
+
if (!ffmpeg) throw new Error('ffmpeg is needed to decode a GIF cover');
|
|
90
|
+
const raw = spawnSync(ffmpeg, ['-v', 'error', '-i', input, '-fps_mode', 'passthrough', '-f', 'rawvideo', '-pix_fmt', 'rgba', 'pipe:1'], { maxBuffer: 2 ** 31 });
|
|
91
|
+
if (raw.status !== 0) throw new Error(`ffmpeg could not decode ${input}: ${String(raw.stderr).trim().split(/\r?\n/)[0]}`);
|
|
92
|
+
const size = timing.width * timing.height * 4;
|
|
93
|
+
for (let i = 0; (i + 1) * size <= raw.stdout.length; i += 1) {
|
|
94
|
+
const rgba = raw.stdout.subarray(i * size, (i + 1) * size);
|
|
95
|
+
lumas.push(lumaGrid(rgba, timing.width, timing.height).luma);
|
|
96
|
+
if (keep(i, timing.delays[i] ?? 100)) kept.set(i, Buffer.from(rgba));
|
|
97
|
+
}
|
|
98
|
+
return { lumas, delays: timing.delays.slice(0, lumas.length), width: timing.width, height: timing.height, loop: timing.loop, bytes: bytes.length, format: 'gif', kept };
|
|
99
|
+
}
|
|
100
|
+
const info = decodeWebp(input, {
|
|
101
|
+
env,
|
|
102
|
+
onFrame: (i, rgba, ms, width, height) => {
|
|
103
|
+
lumas.push(lumaGrid(rgba, width, height).luma);
|
|
104
|
+
if (keep(i, ms > 0 ? ms : 100)) kept.set(i, Buffer.from(rgba));
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
return { width: info.width, height: info.height, loop: info.loop, bytes: info.bytes, lumas, delays: info.durations.map((d) => (d > 0 ? d : 100)), format: 'webp', kept };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// The frame on screen at every `step` ms (a long frame repeats).
|
|
111
|
+
export function resample(frames, delays, step) {
|
|
112
|
+
const total = delays.reduce((a, b) => a + b, 0);
|
|
113
|
+
const out = [];
|
|
114
|
+
let i = 0;
|
|
115
|
+
let end = delays[0];
|
|
116
|
+
for (let ms = 0; ms < total - 1e-6; ms += step) {
|
|
117
|
+
while (ms >= end && i < frames.length - 1) { i += 1; end += delays[i]; }
|
|
118
|
+
out.push(frames[i]);
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Motion numbers on the grid. The loop is a ring: the seam (last sample to first) is one more step.
|
|
124
|
+
export function motionMetrics({ lumas, delays }) {
|
|
125
|
+
const step = Math.max(COVER.gridMs, Math.min(...delays));
|
|
126
|
+
const grid = resample(lumas, delays, step);
|
|
127
|
+
const n = grid.length;
|
|
128
|
+
const steps = [];
|
|
129
|
+
for (let i = 1; i < n; i += 1) steps.push(meanAbsDiff(grid[i], grid[i - 1]));
|
|
130
|
+
const seam = meanAbsDiff(grid[0], grid[n - 1]);
|
|
131
|
+
const ring = [...steps, seam];
|
|
132
|
+
const med = median(ring);
|
|
133
|
+
const still = ring.map((d) => d < COVER.stillEps);
|
|
134
|
+
// A run of k still steps shows one picture for k + 1 samples, so a loop with no still step still
|
|
135
|
+
// holds each sample for one step. The ring is walked once from a moving step, so a still run
|
|
136
|
+
// across the seam is counted whole.
|
|
137
|
+
let stillSteps = 0;
|
|
138
|
+
if (still.every(Boolean)) stillSteps = n - 1;
|
|
139
|
+
else {
|
|
140
|
+
const start = still.findIndex((s) => !s);
|
|
141
|
+
let run = 0;
|
|
142
|
+
for (let k = 1; k <= n; k += 1) {
|
|
143
|
+
run = still[(start + k) % n] ? run + 1 : 0;
|
|
144
|
+
stillSteps = Math.max(stillSteps, run);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
const longestStillSec = ((stillSteps + 1) * step) / 1000;
|
|
148
|
+
const around = n >= 4 ? (ring[n - 3] + ring[n - 2] + ring[0] + ring[1]) / 4 : med;
|
|
149
|
+
return {
|
|
150
|
+
gridFrames: n, stepMs: step, durationSec: (n * step) / 1000, sourceDurationSec: delays.reduce((a, b) => a + b, 0) / 1000,
|
|
151
|
+
medianD: med, p10D: quantile(ring, 0.1), p90D: quantile(ring, 0.9), maxD: Math.max(...ring),
|
|
152
|
+
movingFrac: ring.filter((d) => d >= COVER.stillEps).length / ring.length,
|
|
153
|
+
longestStillSec, spike: Math.max(...ring) / Math.max(med, COVER.stillEps),
|
|
154
|
+
seam, seamLocal: seam / Math.max(COVER.stillEps, around), diffs: ring,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const linear = (c) => { const v = c / 255; return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; };
|
|
159
|
+
const luminance = (r, g, b) => 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
|
|
160
|
+
const boxPx = (box, W, H) => box.map((v, k) => Math.round(v * (k % 2 ? H : W)));
|
|
161
|
+
|
|
162
|
+
// G5: in every frame, the median title pixel against the worst background decile in the title box
|
|
163
|
+
// (background = box pixels at least 3 px from any title pixel). Needs the mask pass's per-frame masks
|
|
164
|
+
// (white = title); without them G5 fails and says what is missing.
|
|
165
|
+
export function titleContrast({ framesDir, masksDir, box }) {
|
|
166
|
+
const frames = pngFrames(framesDir, 'f');
|
|
167
|
+
const masks = pngFrames(masksDir, 'm');
|
|
168
|
+
if (!frames.length || masks.length !== frames.length) return { measured: false, reason: `needs one mask per frame (${frames.length} frames, ${masks.length} masks)` };
|
|
169
|
+
const ratios = [];
|
|
170
|
+
for (let i = 0; i < frames.length; i += 1) {
|
|
171
|
+
const { width: W, height: H, rgba } = readPngRgba(frames[i]);
|
|
172
|
+
const mask = readPngRgba(masks[i]);
|
|
173
|
+
if (mask.width !== W || mask.height !== H) return { measured: false, reason: `mask ${i} is ${mask.width}x${mask.height}, its frame ${W}x${H}` };
|
|
174
|
+
const [bx, by, bw, bh] = boxPx(box, W, H);
|
|
175
|
+
const kind = new Uint8Array(W * H);
|
|
176
|
+
for (let p = 0; p < W * H; p += 1) if (mask.rgba[p * 4] > 127) kind[p] = 2;
|
|
177
|
+
const R = 3;
|
|
178
|
+
for (let y = by; y < by + bh; y += 1) {
|
|
179
|
+
for (let x = bx; x < bx + bw; x += 1) {
|
|
180
|
+
if (kind[y * W + x] !== 2) continue;
|
|
181
|
+
for (let yy = Math.max(0, y - R); yy <= Math.min(H - 1, y + R); yy += 1) {
|
|
182
|
+
for (let xx = Math.max(0, x - R); xx <= Math.min(W - 1, x + R); xx += 1) if (kind[yy * W + xx] === 0) kind[yy * W + xx] = 1;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const text = [], ground = [];
|
|
187
|
+
for (let y = by; y < by + bh; y += 1) {
|
|
188
|
+
for (let x = bx; x < bx + bw; x += 1) {
|
|
189
|
+
const p = y * W + x, o = p * 4;
|
|
190
|
+
if (kind[p] === 2) text.push(luminance(rgba[o], rgba[o + 1], rgba[o + 2]));
|
|
191
|
+
else if (kind[p] === 0) ground.push(luminance(rgba[o], rgba[o + 1], rgba[o + 2]));
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (!text.length || !ground.length) return { measured: false, reason: `frame ${i}: the title box holds ${text.length} title and ${ground.length} background pixels` };
|
|
195
|
+
const t = median(text);
|
|
196
|
+
const worst = t > median(ground) ? quantile(ground, 0.9) : quantile(ground, 0.1);
|
|
197
|
+
ratios.push((Math.max(t, worst) + 0.05) / (Math.min(t, worst) + 0.05));
|
|
198
|
+
}
|
|
199
|
+
return { measured: true, min: Math.min(...ratios), median: median(ratios), frames: ratios.length };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// G6: the title's cap height where a README shows the cover. In each sampled mask the title pixels
|
|
203
|
+
// in the box split into 4-connected glyphs; specks under 1 % of the largest glyph's area or under
|
|
204
|
+
// 30 % of the tallest glyph's height (dots, accents) are left out, and the median height of the
|
|
205
|
+
// rest is that sample's cap height. The smallest, scaled from the cover width to displayWidth, must
|
|
206
|
+
// reach COVER.minGlyphPx. A title painted into declared base art is measured and reported as INFO
|
|
207
|
+
// (pass: null); contrast alone never makes a title readable.
|
|
208
|
+
export function glyphHeights({ masksDir, box, displayWidth = COVER.displayWidth, exempt = null, samples = 12 }) {
|
|
209
|
+
const masks = pngFrames(masksDir, 'm');
|
|
210
|
+
if (!masks.length) return { pass: false, reason: 'no mask frames to measure the title on' };
|
|
211
|
+
const count = Math.min(samples, masks.length);
|
|
212
|
+
const picks = [...new Set(Array.from({ length: count }, (_, k) => Math.floor((k * masks.length) / count)))];
|
|
213
|
+
let cap = Infinity, glyphs = 0, coverWidth = 0;
|
|
214
|
+
for (const index of picks) {
|
|
215
|
+
const mask = readPngRgba(masks[index]);
|
|
216
|
+
coverWidth = mask.width;
|
|
217
|
+
const [bx, by, bw, bh] = boxPx(box, mask.width, mask.height);
|
|
218
|
+
const label = new Uint8Array(bw * bh);
|
|
219
|
+
for (let y = 0; y < bh; y += 1) for (let x = 0; x < bw; x += 1) label[y * bw + x] = mask.rgba[((by + y) * mask.width + bx + x) * 4] > 127 ? 1 : 0;
|
|
220
|
+
const parts = [];
|
|
221
|
+
for (let seed = 0; seed < label.length; seed += 1) {
|
|
222
|
+
if (label[seed] !== 1) continue;
|
|
223
|
+
label[seed] = 2;
|
|
224
|
+
const stack = [seed];
|
|
225
|
+
let area = 0, top = bh, bottom = -1;
|
|
226
|
+
while (stack.length) {
|
|
227
|
+
const q = stack.pop();
|
|
228
|
+
const y = Math.floor(q / bw), x = q - y * bw;
|
|
229
|
+
area += 1;
|
|
230
|
+
if (y < top) top = y;
|
|
231
|
+
if (y > bottom) bottom = y;
|
|
232
|
+
for (const next of [x > 0 ? q - 1 : -1, x < bw - 1 ? q + 1 : -1, y > 0 ? q - bw : -1, y < bh - 1 ? q + bw : -1]) {
|
|
233
|
+
if (next >= 0 && label[next] === 1) { label[next] = 2; stack.push(next); }
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
parts.push({ area, height: bottom - top + 1 });
|
|
237
|
+
}
|
|
238
|
+
if (!parts.length) return { pass: false, reason: `mask ${index}: no title pixels in the title box` };
|
|
239
|
+
const largest = Math.max(...parts.map((p) => p.area));
|
|
240
|
+
const tallest = Math.max(...parts.map((p) => p.height));
|
|
241
|
+
const letters = parts.filter((p) => p.area >= 0.01 * largest && p.height >= 0.3 * tallest);
|
|
242
|
+
glyphs = Math.max(glyphs, letters.length);
|
|
243
|
+
cap = Math.min(cap, median(letters.map((p) => p.height)));
|
|
244
|
+
}
|
|
245
|
+
const capPx = (cap * displayWidth) / coverWidth;
|
|
246
|
+
const result = { capPx: Math.round(capPx * 10) / 10, coverPx: cap, displayWidth, glyphs, sampled: picks.length };
|
|
247
|
+
if (exempt) return { pass: null, ...result, reason: exempt };
|
|
248
|
+
return { pass: capPx >= COVER.minGlyphPx, ...result };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// G0: SHA-256 per frame file of two captures made in separate browsers.
|
|
252
|
+
export function determinism(dirA, dirB) {
|
|
253
|
+
const a = pngFrames(dirA, 'f');
|
|
254
|
+
const b = pngFrames(dirB, 'f');
|
|
255
|
+
const hash = (file) => createHash('sha256').update(readFileSync(file)).digest('hex');
|
|
256
|
+
const n = Math.min(a.length, b.length);
|
|
257
|
+
let identical = 0, firstDiffering = null;
|
|
258
|
+
for (let i = 0; i < n; i += 1) {
|
|
259
|
+
if (hash(a[i]) === hash(b[i])) identical += 1;
|
|
260
|
+
else firstDiffering ??= i;
|
|
261
|
+
}
|
|
262
|
+
return { compared: n, identical, countsMatch: a.length === b.length, firstDiffering };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Gate one cover file (or a PNG frame folder). frames/frames2 give G0, masks + title give G5,
|
|
266
|
+
// glyph ({ displayWidth, exempt }) adds G6, keep(i, ms) keeps decoded frames whole. Returns the
|
|
267
|
+
// metrics, one verdict per gate, `pass` (every FLOOR) and `target` (every TARGET).
|
|
268
|
+
export function coverGate(input, { frames = null, frames2 = null, masks = null, title = null, glyph = null, fps = 16, keep, env = process.env } = {}) {
|
|
269
|
+
const src = loadCover(input, { fps, keep, env });
|
|
270
|
+
const m = motionMetrics(src);
|
|
271
|
+
const gates = {};
|
|
272
|
+
if (frames && frames2) {
|
|
273
|
+
const det = determinism(frames, frames2);
|
|
274
|
+
gates.G0 = { pass: det.countsMatch && det.compared > 0 && det.identical === det.compared, ...det };
|
|
275
|
+
}
|
|
276
|
+
if (src.format !== 'png') {
|
|
277
|
+
gates.G1 = {
|
|
278
|
+
pass: src.bytes <= COVER.maxBytes && m.sourceDurationSec >= COVER.minSec && m.sourceDurationSec <= COVER.maxSec && src.loop === 0,
|
|
279
|
+
target: src.bytes <= COVER.targetBytes,
|
|
280
|
+
bytes: src.bytes, durationSec: m.sourceDurationSec, loop: src.loop, size: `${src.width}x${src.height}`,
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
const F = COVER.floor, T = COVER.target;
|
|
284
|
+
gates.G2 = { pass: m.medianD >= F.medianD && m.movingFrac >= F.movingFrac, target: m.medianD >= T.medianD && m.movingFrac >= T.movingFrac, medianD: m.medianD, movingFrac: m.movingFrac };
|
|
285
|
+
gates.G3 = { pass: m.longestStillSec <= F.stillSec, target: m.longestStillSec <= T.stillSec && m.spike <= T.spike, longestStillSec: m.longestStillSec, spike: m.spike };
|
|
286
|
+
gates.G4 = { pass: m.seamLocal <= F.seamLocal, target: m.seamLocal <= T.seamLocal && m.seamLocal >= T.seamLo, seam: m.seam, seamLocal: m.seamLocal };
|
|
287
|
+
if (title && frames) {
|
|
288
|
+
const c = titleContrast({ framesDir: frames, masksDir: masks, box: title });
|
|
289
|
+
gates.G5 = c.measured ? { pass: c.min >= COVER.minContrast, min: c.min, median: c.median, frames: c.frames } : { pass: false, reason: c.reason };
|
|
290
|
+
}
|
|
291
|
+
if (title && masks && glyph) gates.G6 = glyphHeights({ masksDir: masks, box: title, displayWidth: glyph.displayWidth ?? COVER.displayWidth, exempt: glyph.exempt ?? null });
|
|
292
|
+
const pass = Object.values(gates).every((g) => g.pass !== false);
|
|
293
|
+
const target = pass && Object.values(gates).every((g) => g.target !== false);
|
|
294
|
+
return { input, format: src.format, width: src.width, height: src.height, bytes: src.bytes, loop: src.loop, sourceFrames: src.lumas.length, durations: src.delays, ...m, gates, pass, target, kept: src.kept };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const short = (x) => (typeof x === 'number' && !Number.isInteger(x) ? Number(x.toPrecision(4)) : x);
|
|
298
|
+
|
|
299
|
+
// The report: a verdict line, a size line, then one line per gate.
|
|
300
|
+
export function coverReportText(r, { strict = false } = {}) {
|
|
301
|
+
const verdict = r.pass ? (r.target ? 'PASS+TARGET' : 'PASS(floor)') : 'FAIL';
|
|
302
|
+
const lines = [
|
|
303
|
+
`COVER gate${strict ? ' --strict' : ''}: ${verdict}`,
|
|
304
|
+
` ${r.width}x${r.height} ${r.format} frames=${r.sourceFrames} dur=${short(r.sourceDurationSec)}s bytes=${r.bytes ?? '-'} loop=${r.loop} grid=${r.stepMs}ms`,
|
|
305
|
+
];
|
|
306
|
+
for (const [name, gate] of Object.entries(r.gates)) {
|
|
307
|
+
const { pass, target, ...detail } = gate;
|
|
308
|
+
const word = pass === null ? 'INFO' : pass ? (target === false ? 'pass(floor)' : 'pass') : 'FAIL';
|
|
309
|
+
lines.push(` ${name} ${word} ${Object.entries(detail).map(([k, v]) => `${k}=${short(v)}`).join(' ')}`);
|
|
310
|
+
}
|
|
311
|
+
return `${lines.join('\n')}\n`;
|
|
312
|
+
}
|