framepress 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +165 -18
- package/assets/backdrops/river-dusk.jpg +0 -0
- package/bin/camera.mjs +190 -0
- package/bin/ffmpeg.mjs +23 -0
- package/bin/mcp.mjs +233 -0
- package/bin/record.mjs +58 -13
- package/bin/sound.mjs +372 -0
- package/bin/studio-video.mjs +282 -0
- package/bin/studio.mjs +494 -0
- package/bin/take.mjs +251 -0
- package/examples/synthetic-desktop/check-alignment.mjs +28 -0
- package/examples/synthetic-desktop/check-sound.mjs +104 -0
- package/examples/synthetic-desktop/desktop.html +343 -0
- package/examples/synthetic-desktop/make.mjs +102 -0
- package/native/Package.swift +9 -0
- package/native/Sources/FramepressCapture/Capture.swift +325 -0
- package/native/Sources/FramepressCapture/Command.swift +219 -0
- package/native/Sources/FramepressCapture/Input.swift +202 -0
- package/native/bin/framepress-capture +0 -0
- package/package.json +17 -6
package/bin/take.mjs
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
// Takes: a short script of steps whose camera cues can wait on what the page shows.
|
|
2
|
+
// Runs inside the frame-stepped clock, so a cue that waits on state starts on the
|
|
3
|
+
// exact frame the state first appears.
|
|
4
|
+
//
|
|
5
|
+
// Motion is modelled on per-frame tracks of public Screen Studio exports (see the
|
|
6
|
+
// Framepress motion notes): the real mouse follows a human raw path, the drawn cursor
|
|
7
|
+
// is that path through a spring, and the camera only retargets on script cues or when
|
|
8
|
+
// the cursor heads out of a dead zone.
|
|
9
|
+
import { readFile } from 'node:fs/promises';
|
|
10
|
+
import { resolve, dirname } from 'node:path';
|
|
11
|
+
import { pathToFileURL } from 'node:url';
|
|
12
|
+
import { BACKDROPS, CORNERS, DEFAULT_BACKDROP, PARALLAX } from './studio.mjs';
|
|
13
|
+
import { AUTO, CURSOR, MAX_ZOOM, PRESS, SPRING, createRig } from './camera.mjs';
|
|
14
|
+
|
|
15
|
+
const seconds = s => { const m = /^([\d.]+)(ms|s)$/.exec(s); if (!m) throw Error(`Expected a duration like 0.6s, got "${s}"`); return m[2] === 'ms' ? m[1] / 1000 : Number(m[1]); };
|
|
16
|
+
|
|
17
|
+
export async function parseTake(file) {
|
|
18
|
+
const text = await readFile(file, 'utf8');
|
|
19
|
+
const base = dirname(resolve(file));
|
|
20
|
+
const take = { url: undefined, width: 1280, height: 720, scale: 1, fps: 60, cursor: undefined, output: undefined, backdrop: DEFAULT_BACKDROP, fit: null, style: null, seed: 1, steps: [] };
|
|
21
|
+
text.split('\n').forEach((raw, index) => {
|
|
22
|
+
const line = raw.trim(), n = index + 1;
|
|
23
|
+
if (!line || line.startsWith('# ') || line === '#') return;
|
|
24
|
+
const fail = why => { throw Error(`Line ${n}: ${why}\n ${line}`); };
|
|
25
|
+
let m;
|
|
26
|
+
if ((m = /^open (\S+)$/.exec(line))) take.url = /^[a-z]+:/.test(m[1]) ? m[1] : pathToFileURL(resolve(base, m[1])).href;
|
|
27
|
+
else if ((m = /^viewport (\d+)x(\d+)(?: scale ([\d.]+))?$/.exec(line))) Object.assign(take, { width: +m[1], height: +m[2], scale: m[3] ? +m[3] : 1 });
|
|
28
|
+
else if ((m = /^fps (\d+)$/.exec(line))) take.fps = +m[1];
|
|
29
|
+
else if ((m = /^seed (\d+)$/.exec(line))) take.seed = +m[1];
|
|
30
|
+
else if ((m = /^cursor (\S+)$/.exec(line))) take.cursor = resolve(base, m[1]);
|
|
31
|
+
else if ((m = /^output (\d+)x(\d+)$/.exec(line))) take.output = [+m[1], +m[2]];
|
|
32
|
+
else if ((m = /^backdrop (\S+)$/.exec(line)) && (m[1] === 'none' || m[1] in BACKDROPS || /^#[0-9a-fA-F]{6}$/.test(m[1]))) take.backdrop = m[1];
|
|
33
|
+
else if (line.startsWith('backdrop ')) fail(`Unknown backdrop. Use none, #rrggbb or one of: ${Object.keys(BACKDROPS).join(', ')}.`);
|
|
34
|
+
// The window shows only this element plus padding, so the app fills the window.
|
|
35
|
+
else if ((m = /^style "(.*)"$/.exec(line))) take.style = (take.style ?? '') + m[1];
|
|
36
|
+
else if (line === 'parallax off') take.parallax = null;
|
|
37
|
+
else if ((m = /^parallax (?:zoom )?([\d.]+)(?: pan ([\d.]+))?$/.exec(line))) take.parallax = { ...PARALLAX, zoom: +m[1], pan: m[2] === undefined ? PARALLAX.pan : +m[2] };
|
|
38
|
+
else if (line.startsWith('parallax')) fail(`Use parallax off, or parallax <zoom ratio> [pan <factor>], e.g. parallax ${PARALLAX.zoom}.`);
|
|
39
|
+
else if ((m = /^corner (\S+)$/.exec(line))) { if (!(m[1] in CORNERS)) fail(`Unknown corner. Use one of: ${Object.keys(CORNERS).join(', ')}.`); take.corner = m[1]; }
|
|
40
|
+
else if ((m = /^fit (.+?)(?: pad (\d+))?$/.exec(line))) take.fit = { selector: m[1], pad: m[2] ? +m[2] : 12 };
|
|
41
|
+
else if ((m = /^caption "(.*)"(?: for (\S+))?$/.exec(line))) take.steps.push({ n, line, kind: 'caption', text: m[1], over: m[2] ? seconds(m[2]) : 1.6 });
|
|
42
|
+
// Auto camera: clicks zoom in toward the cursor, the camera follows the cursor while
|
|
43
|
+
// zoomed and pulls back after an idle pause. Scripted camera cues still work alongside.
|
|
44
|
+
else if ((m = /^camera auto(?: zoom ([\d.]+))?(?: idle (\S+))?$/.exec(line))) take.steps.push({ n, line, kind: 'auto', zoom: m[1] ? +m[1] : AUTO.zoom, idle: m[2] ? seconds(m[2]) : AUTO.idle });
|
|
45
|
+
else if ((m = /^camera (?:on (.+?)(?: pad (\d+))?|(wide))(?: over (\S+))?(?: after (\S+))?$/.exec(line))) take.steps.push({ n, line, kind: 'camera', selector: m[1], pad: m[2] ? +m[2] : 24, over: m[4] ? seconds(m[4]) : null, after: m[5] ? seconds(m[5]) : 0 });
|
|
46
|
+
else if ((m = /^type (\S+) on (.+)$/.exec(line))) take.steps.push({ n, line, kind: 'type', text: m[1], selector: m[2] });
|
|
47
|
+
else if ((m = /^click (.+)$/.exec(line))) take.steps.push({ n, line, kind: 'type', text: null, selector: m[1] });
|
|
48
|
+
else if ((m = /^hold (.+?)(?: at ([\d.]+))?(?: for (\S+))?$/.exec(line))) take.steps.push({ n, line, kind: 'hold', selector: m[1], at: m[2] ? +m[2] : null, for: m[3] ? seconds(m[3]) : 0 });
|
|
49
|
+
else if (line === 'release') take.steps.push({ n, line, kind: 'release' });
|
|
50
|
+
else if ((m = /^pause (\S+)$/.exec(line))) take.steps.push({ n, line, kind: 'pause', over: seconds(m[1]) });
|
|
51
|
+
else if ((m = /^wait until (?:js (.+?)|(.+?) reads "(.*)")(?: timeout (\S+))?$/.exec(line))) take.steps.push({ n, line, kind: 'wait', js: m[1], selector: m[2], reads: m[3], timeout: m[4] ? seconds(m[4]) : 15 });
|
|
52
|
+
else fail('Unknown step. Steps: open, viewport, fit, output, backdrop, parallax, corner, fps, seed, cursor, style, caption, camera on A [+ B] [pad] [over] [after], camera auto [zoom Z] [idle S], type ... on, click, hold [at] [for], release, wait until, pause.');
|
|
53
|
+
});
|
|
54
|
+
if (!take.url) throw Error('A take needs an "open <url or path>" line.');
|
|
55
|
+
take.output ??= [take.width, take.height];
|
|
56
|
+
if (take.output.some(v => v % 2 || v < 2 || v > 7680)) throw Error('Output needs even dimensions up to 7680.');
|
|
57
|
+
return take;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export { SPRING, CURSOR, PRESS, FOLLOW, AUTO } from './camera.mjs';
|
|
61
|
+
const minJerk = u => u <= 0 ? 0 : u >= 1 ? 1 : u * u * u * (10 + u * (-15 + 6 * u));
|
|
62
|
+
const mulberry32 = a => () => { a |= 0; a = a + 0x6D2B79F5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; };
|
|
63
|
+
|
|
64
|
+
export async function createTakeRunner(page, take, studio) {
|
|
65
|
+
const { fps, steps } = take;
|
|
66
|
+
const L = studio.layout;
|
|
67
|
+
const rand = mulberry32(take.seed * 9973 + 7);
|
|
68
|
+
const jit = (v, f = CURSOR.jitter) => v * (1 + (rand() * 2 - 1) * f);
|
|
69
|
+
const log = [];
|
|
70
|
+
let index = 0, state = null, done = false;
|
|
71
|
+
// raw: where the real mouse is. drawn: what the viewer sees, the raw path through a spring.
|
|
72
|
+
const C = take.clip ?? { x: 0, y: 0, width: take.width, height: take.height };
|
|
73
|
+
const start = { x: C.x + C.width * .86, y: C.y + C.height * .93 };
|
|
74
|
+
const rig = createRig({ layout: L, fps, toComposite: studio.toComposite, start, cursorSize: take.cursor && 32 * L.s0, log });
|
|
75
|
+
const { raw, rawPrev, drawn, wide, track, clampView, setGoal } = rig;
|
|
76
|
+
let captions = [];
|
|
77
|
+
const pendingCams = [];
|
|
78
|
+
await page.mouse.move(raw.x, raw.y);
|
|
79
|
+
const box1 = async selector => {
|
|
80
|
+
const b = await page.locator(selector).first().boundingBox({ timeout: 2000 }).catch(() => null);
|
|
81
|
+
if (!b) throw Error(`No visible element for "${selector}"`);
|
|
82
|
+
return b;
|
|
83
|
+
};
|
|
84
|
+
// "A + B" frames the union of both elements.
|
|
85
|
+
const box = async selector => {
|
|
86
|
+
const bs = await Promise.all(selector.split(' + ').map(s => box1(s.trim())));
|
|
87
|
+
const x = Math.min(...bs.map(b => b.x)), y = Math.min(...bs.map(b => b.y));
|
|
88
|
+
return { x, y, width: Math.max(...bs.map(b => b.x + b.width)) - x, height: Math.max(...bs.map(b => b.y + b.height)) - y };
|
|
89
|
+
};
|
|
90
|
+
// Fit the padded element to the output, then keep the view inside the window.
|
|
91
|
+
// Then nudge the zoom in (up to 12%) until no button is sliced by a view edge: edges
|
|
92
|
+
// land in the gaps between rows. Tall pills (height over twice width) cannot be avoided.
|
|
93
|
+
const shot = async (selector, pad) => {
|
|
94
|
+
if (!selector) return { ...wide, rect: null };
|
|
95
|
+
const b = await box(selector), p = studio.toComposite(b.x - pad, b.y - pad), w = (b.width + pad * 2) * L.s0, h = (b.height + pad * 2) * L.s0;
|
|
96
|
+
const z0 = Math.max(1, Math.min(MAX_ZOOM, L.W / w, L.H / h));
|
|
97
|
+
const buttons = (await page.$$eval('button', els => els.map(e => { const r = e.getBoundingClientRect(); return { x: r.x, y: r.y, w: r.width, h: r.height }; })))
|
|
98
|
+
.filter(r => r.h <= r.w * 2).map(r => { const a = studio.toComposite(r.x, r.y); return { x: a.x, y: a.y, w: r.w * L.s0, h: r.h * L.s0 }; });
|
|
99
|
+
const core = { x: studio.toComposite(b.x, b.y).x, y: studio.toComposite(b.x, b.y).y, w: b.width * L.s0, h: b.height * L.s0 };
|
|
100
|
+
const sliced = (z, c) => {
|
|
101
|
+
const vx = c.x - L.W / z / 2, vy = c.y - L.H / z / 2, vw = L.W / z, vh = L.H / z;
|
|
102
|
+
if (core.x < vx - .5 || core.y < vy - .5 || core.x + core.w > vx + vw + .5 || core.y + core.h > vy + vh + .5) return Infinity;
|
|
103
|
+
let worst = 0;
|
|
104
|
+
for (const r of buttons) {
|
|
105
|
+
const ix = Math.max(0, Math.min(r.x + r.w, vx + vw) - Math.max(r.x, vx)), iy = Math.max(0, Math.min(r.y + r.h, vy + vh) - Math.max(r.y, vy));
|
|
106
|
+
const f = ix * iy / (r.w * r.h);
|
|
107
|
+
if (f > .02 && f < .98) worst = Math.max(worst, Math.min(f, 1 - f));
|
|
108
|
+
}
|
|
109
|
+
return worst;
|
|
110
|
+
};
|
|
111
|
+
let best = null;
|
|
112
|
+
for (let z = z0; z <= Math.min(MAX_ZOOM, z0 * 1.12) + 1e-9; z += .0025) {
|
|
113
|
+
const c = clampView(p.x + w / 2, p.y + h / 2, z), cut = sliced(z, c);
|
|
114
|
+
if (!best || cut < best.cut - 1e-6) best = { z, c, cut };
|
|
115
|
+
if (cut === 0) break;
|
|
116
|
+
}
|
|
117
|
+
if (!best || best.cut === Infinity) best = { z: z0, c: clampView(p.x + w / 2, p.y + h / 2, z0), cut: null };
|
|
118
|
+
return { z: best.z, ...best.c, rect: b, cut: best.cut };
|
|
119
|
+
};
|
|
120
|
+
// Fitts-style raw duration: a + b log2(1 + D / W), with a little human variation.
|
|
121
|
+
const rawFrames = (from, to, width) => {
|
|
122
|
+
const d = Math.hypot(to.x - from.x, to.y - from.y);
|
|
123
|
+
if (d < 1) return 0;
|
|
124
|
+
return Math.max(6, Math.round(fps * jit(CURSOR.fittsA + CURSOR.fittsB * Math.log2(1 + d / Math.max(12, width)))));
|
|
125
|
+
};
|
|
126
|
+
const target = async (selector, text, at = null) => {
|
|
127
|
+
const b = text === null ? await box(selector) : await page.locator(selector).filter({ hasText: new RegExp(`^\\s*${text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*$`) }).first().boundingBox();
|
|
128
|
+
if (!b) throw Error(`No "${text}" in ${selector}`);
|
|
129
|
+
// Humans do not hit dead centre: aim within the middle fifth of the target.
|
|
130
|
+
return { x: b.x + b.width * (.5 + (rand() - .5) * .2), y: b.y + b.height * ((at ?? .5) + (rand() - .5) * .2 * Math.min(1, b.width / b.height)), w: Math.min(b.width, b.height) };
|
|
131
|
+
};
|
|
132
|
+
const record = (step, frame, extra = {}) => log.push({ line: step.n, step: step.line, frame, ...extra });
|
|
133
|
+
const planMove = (to, s) => {
|
|
134
|
+
const from = { x: raw.x, y: raw.y }, frames = rawFrames(from, to, to.w);
|
|
135
|
+
// A gentle arc: a hand pivots, so long moves bow slightly; sign follows direction.
|
|
136
|
+
const dx = to.x - from.x, dy = to.y - from.y, d = Math.hypot(dx, dy) || 1;
|
|
137
|
+
const bow = jit(CURSOR.arc, .4) * d * (dx >= 0 ? -1 : 1);
|
|
138
|
+
return { from, to, frames, nx: -dy / d * bow, ny: dx / d * bow, t: 0 };
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
async function begin(step, frame) {
|
|
142
|
+
if (step.kind === 'camera') {
|
|
143
|
+
const to = await shot(step.selector, step.pad);
|
|
144
|
+
const at = frame + Math.round(step.after * fps);
|
|
145
|
+
pendingCams.push({ at, to, over: step.over, step });
|
|
146
|
+
if (!step.after) { fireCams(frame); }
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
if (step.kind === 'auto') { rig.startAuto(step.zoom, step.idle, frame); record(step, frame); return null; }
|
|
150
|
+
if (step.kind === 'caption') { record(step, frame); captions.push({ text: step.text, from: frame, to: frame + Math.round(step.over * fps) }); return null; }
|
|
151
|
+
if (step.kind === 'pause') return { until: frame + Math.round(step.over * fps) };
|
|
152
|
+
if (step.kind === 'type') { record(step, frame); return { keys: step.text === null ? [null] : [...step.text], key: 0, phase: 'aim' }; }
|
|
153
|
+
if (step.kind === 'hold') { record(step, frame); return { keys: [null], key: 0, phase: 'aim', hold: true, for: Math.round(step.for * fps) }; }
|
|
154
|
+
if (step.kind === 'release') { await page.mouse.up(); raw.down = false; record(step, frame); return null; }
|
|
155
|
+
if (step.kind === 'wait') {
|
|
156
|
+
// An observer stamps the clock independently of the per-frame check, as evidence.
|
|
157
|
+
await page.evaluate(({ selector, reads, js }) => {
|
|
158
|
+
const test = () => js ? !!(0, eval)(js) : document.querySelector(selector)?.textContent.trim() === reads;
|
|
159
|
+
window.__framepressSeen = test() ? performance.now() : null;
|
|
160
|
+
const ob = new MutationObserver(() => { if (window.__framepressSeen === null && test()) { window.__framepressSeen = performance.now(); ob.disconnect(); } });
|
|
161
|
+
ob.observe(document, { subtree: true, childList: true, characterData: true, attributes: true });
|
|
162
|
+
}, step);
|
|
163
|
+
return { start: frame };
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
function fireCams(frame) {
|
|
167
|
+
for (let i = pendingCams.length - 1; i >= 0; i--) {
|
|
168
|
+
const c = pendingCams[i];
|
|
169
|
+
if (c.at > frame) continue;
|
|
170
|
+
pendingCams.splice(i, 1);
|
|
171
|
+
setGoal(c.to, c.over);
|
|
172
|
+
record(c.step, frame, { cameraStart: frame, zoom: +c.to.z.toFixed(3), sliced: c.to.cut ?? null });
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Returns true when the step has finished on this frame.
|
|
177
|
+
async function advance(step, s, frame) {
|
|
178
|
+
if (!s) return true;
|
|
179
|
+
if (step.kind === 'pause') return frame >= s.until;
|
|
180
|
+
if (step.kind === 'wait') {
|
|
181
|
+
const met = await page.evaluate(({ selector, reads, js }) => js ? !!(0, eval)(js) : document.querySelector(selector)?.textContent.trim() === reads, step);
|
|
182
|
+
if (met) {
|
|
183
|
+
const seen = await page.evaluate(() => window.__framepressSeen);
|
|
184
|
+
record(step, frame, { waitedFrom: s.start, observedFrame: seen === null ? null : Math.round(seen * fps / 1000) });
|
|
185
|
+
return true;
|
|
186
|
+
}
|
|
187
|
+
if (frame - s.start > step.timeout * fps) throw Error(`Line ${step.n}: condition never became true within ${step.timeout}s\n ${step.line}`);
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
// type, click and hold: aim, travel, settle until the drawn tip is on target, press, release.
|
|
191
|
+
if (s.phase === 'aim') {
|
|
192
|
+
const to = await target(step.selector, s.keys[s.key], step.at ?? null);
|
|
193
|
+
s.move = planMove(to, s); s.phase = 'move';
|
|
194
|
+
if (rig.aim(to, frame)) log.push({ line: step.n, step: `follow pan to ${s.keys[s.key] ?? step.selector}`, frame, cameraStart: frame });
|
|
195
|
+
}
|
|
196
|
+
if (s.phase === 'move') {
|
|
197
|
+
const m = s.move;
|
|
198
|
+
if (m.frames && m.t < m.frames) {
|
|
199
|
+
const u = ++m.t / m.frames, e = minJerk(u), b = Math.sin(Math.PI * e);
|
|
200
|
+
raw.x = m.from.x + (m.to.x - m.from.x) * e + m.nx * b; raw.y = m.from.y + (m.to.y - m.from.y) * e + m.ny * b;
|
|
201
|
+
await page.mouse.move(raw.x, raw.y);
|
|
202
|
+
if (m.t < m.frames) return false;
|
|
203
|
+
}
|
|
204
|
+
raw.x = m.to.x; raw.y = m.to.y; await page.mouse.move(raw.x, raw.y);
|
|
205
|
+
Object.assign(s, { phase: 'settle', t: 0 });
|
|
206
|
+
return false;
|
|
207
|
+
}
|
|
208
|
+
if (s.phase === 'settle') {
|
|
209
|
+
// Raj's rule: the visible tip must be within 2 px of the target before a press.
|
|
210
|
+
s.t++;
|
|
211
|
+
if (Math.hypot(drawn.x - raw.x, drawn.y - raw.y) > CURSOR.tipTolerance && s.t < fps) return false;
|
|
212
|
+
await page.mouse.down(); raw.down = true;
|
|
213
|
+
s.pressedAt = frame;
|
|
214
|
+
if (s.hold && !s.for) return true;
|
|
215
|
+
Object.assign(s, { phase: 'press', t: 0, holdFrames: s.for || Math.max(5, Math.round(fps * jit(PRESS.hold, .2))) });
|
|
216
|
+
return false;
|
|
217
|
+
}
|
|
218
|
+
if (s.phase === 'press') {
|
|
219
|
+
if (++s.t < s.holdFrames) return false;
|
|
220
|
+
await page.mouse.up(); raw.down = false;
|
|
221
|
+
if (++s.key >= s.keys.length) return true;
|
|
222
|
+
s.phase = 'aim';
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
return {
|
|
228
|
+
log, track,
|
|
229
|
+
get done() { return done; },
|
|
230
|
+
// Run the script for one frame, then return the camera and cursor pose to draw.
|
|
231
|
+
async frame(frame) {
|
|
232
|
+
Object.assign(rawPrev, { x: raw.x, y: raw.y });
|
|
233
|
+
fireCams(frame);
|
|
234
|
+
while (!done) {
|
|
235
|
+
const step = steps[index];
|
|
236
|
+
if (!step) { done = pendingCams.length === 0; break; }
|
|
237
|
+
if (!state) state = { s: await begin(step, frame) };
|
|
238
|
+
if (!(await advance(step, state.s, frame))) break;
|
|
239
|
+
state = null; index++;
|
|
240
|
+
}
|
|
241
|
+
rig.autoCamera(frame);
|
|
242
|
+
const cap = captions.find(c => frame >= c.from && frame < c.to);
|
|
243
|
+
return rig.pose(frame, cap && { html: captionHtml(cap.text), alpha: Math.min(1, (frame - cap.from) / (0.25 * fps), (cap.to - frame) / (0.35 * fps)) });
|
|
244
|
+
},
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const esc = t => t.replace(/&/g, '&').replace(/</g, '<');
|
|
250
|
+
// "Label | text" sets a small label before the line.
|
|
251
|
+
const captionHtml = t => { const [l, r] = t.includes(' | ') ? t.split(' | ') : [null, t]; return (l ? `<b>${esc(l)}</b>` : '') + `<span>${esc(r)}</span>`; };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Cursor alignment check for a `studio-video --probe --log` render: the cursor is drawn as a
|
|
3
|
+
// red dot on its hotspot, so the dot's centroid in each press frame should sit on the
|
|
4
|
+
// press point projected through that frame's cameras (the log's probes).
|
|
5
|
+
// node check-alignment.mjs <probe.mp4> <probe.json> [tolerance px]
|
|
6
|
+
import ffmpeg from 'ffmpeg-static';
|
|
7
|
+
import { execFileSync } from 'node:child_process';
|
|
8
|
+
import { readFileSync } from 'node:fs';
|
|
9
|
+
|
|
10
|
+
const [video, logFile, tol = '2'] = process.argv.slice(2);
|
|
11
|
+
const log = JSON.parse(readFileSync(logFile, 'utf8'));
|
|
12
|
+
const { W, H } = log.layout;
|
|
13
|
+
let worst = 0;
|
|
14
|
+
for (const p of log.probes) {
|
|
15
|
+
const rgb = execFileSync(ffmpeg, ['-v', 'error', '-i', video, '-vf', `select=eq(n\\,${p.frame})`, '-frames:v', '1', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], { maxBuffer: W * H * 4 });
|
|
16
|
+
// Redness-weighted centroid within 40 px of the expected point. The threshold keeps pure probe
|
|
17
|
+
// red and drops UI reds such as the PDF badge (#e5534b, margin 146).
|
|
18
|
+
let sx = 0, sy = 0, sw = 0;
|
|
19
|
+
for (let y = Math.max(0, Math.floor(p.y - 40)); y < Math.min(H, p.y + 40); y++) for (let x = Math.max(0, Math.floor(p.x - 40)); x < Math.min(W, p.x + 40); x++) {
|
|
20
|
+
const i = (y * W + x) * 3, w = Math.max(0, rgb[i] - Math.max(rgb[i + 1], rgb[i + 2]) - 170);
|
|
21
|
+
sx += (x + .5) * w; sy += (y + .5) * w; sw += w;
|
|
22
|
+
}
|
|
23
|
+
const d = sw ? Math.hypot(sx / sw - p.x, sy / sw - p.y) : Infinity;
|
|
24
|
+
worst = Math.max(worst, d);
|
|
25
|
+
console.log(`f${String(p.frame).padStart(4)} ${p.kind.padEnd(4)} t=${p.t.toFixed(3)}s expected (${p.x.toFixed(2)}, ${p.y.toFixed(2)}) dot (${(sx / sw).toFixed(2)}, ${(sy / sw).toFixed(2)}) error ${d.toFixed(2)} px`);
|
|
26
|
+
}
|
|
27
|
+
console.log(`worst ${worst.toFixed(2)} px, tolerance ${tol} px: ${worst <= Number(tol) ? 'PASS' : 'FAIL'}`);
|
|
28
|
+
process.exitCode = worst <= Number(tol) ? 0 : 1;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Checks a render's soundtrack against its events: decodes the audio back from the MP4,
|
|
3
|
+
// finds onsets blind (high-passed so the whoosh and music bed do not count), matches each
|
|
4
|
+
// sound cue from the --log run to the nearest onset, measures loudness and true peak with
|
|
5
|
+
// ffmpeg's EBU R128 scanner, and draws a waveform PNG with the cue times on top.
|
|
6
|
+
// node check-sound.mjs render.mp4 run.json [waveform.png]
|
|
7
|
+
// PNG: waveform in grey; cue lines red (press), orange (release), blue (key), light blue
|
|
8
|
+
// (key return), green (scroll);
|
|
9
|
+
// black ticks under the waveform are detected onsets; the bottom lane is camera speed.
|
|
10
|
+
import ffmpeg from 'ffmpeg-static';
|
|
11
|
+
import { spawn } from 'node:child_process';
|
|
12
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
13
|
+
import { deflateSync } from 'node:zlib';
|
|
14
|
+
|
|
15
|
+
const [video, runLog, png] = process.argv.slice(2);
|
|
16
|
+
if (!video || !runLog) { console.log('node check-sound.mjs render.mp4 run.json [waveform.png]'); process.exit(1); }
|
|
17
|
+
const RATE = 48000;
|
|
18
|
+
const run = (args, out = 'pipe') => new Promise((res, rej) => {
|
|
19
|
+
const p = spawn(ffmpeg, args, { stdio: ['ignore', out, 'pipe'] }), chunks = []; let err = '';
|
|
20
|
+
p.stdout?.on('data', c => chunks.push(c)); p.stderr.on('data', c => err += c);
|
|
21
|
+
p.once('close', c => c === 0 ? res({ out: Buffer.concat(chunks), err }) : rej(Error(err)));
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const log = JSON.parse(await readFile(runLog, 'utf8'));
|
|
25
|
+
const cues = log.audio?.cues; if (!cues) throw Error('run.json has no audio cues; render with sound on and --log');
|
|
26
|
+
const { out, err: info } = await run(['-hide_banner', '-i', video, '-vn', '-ac', '2', '-ar', String(RATE), '-f', 'f32le', 'pipe:1']);
|
|
27
|
+
const stream = info.match(/Audio: ([^\n]+)/)?.[1];
|
|
28
|
+
const st = new Float32Array(out.buffer, out.byteOffset, out.length >> 2), x = new Float32Array(st.length >> 1);
|
|
29
|
+
for (let i = 0; i < x.length; i++) x[i] = (st[2 * i] + st[2 * i + 1]) / 2;
|
|
30
|
+
|
|
31
|
+
// High-pass at 1.5 kHz (two RBJ stages) so onsets are clicks, keys and ticks only.
|
|
32
|
+
const hp = new Float32Array(x);
|
|
33
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
34
|
+
const w = 2 * Math.PI * 1500 / RATE, c = Math.cos(w), al = Math.sin(w) / (2 * 0.7071), a0 = 1 + al;
|
|
35
|
+
const b = [(1 + c) / 2 / a0, -(1 + c) / a0, (1 + c) / 2 / a0], a = [-2 * c / a0, (1 - al) / a0];
|
|
36
|
+
let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
|
|
37
|
+
for (let i = 0; i < hp.length; i++) { const v = hp[i], y = b[0] * v + b[1] * x1 + b[2] * x2 - a[0] * y1 - a[1] * y2; x2 = x1; x1 = v; y2 = y1; y1 = y; hp[i] = y; }
|
|
38
|
+
}
|
|
39
|
+
// Blind onsets: 0.5 ms frames whose peak jumps above 3x the peak of the previous 5 ms and
|
|
40
|
+
// above an absolute floor (-50 dBFS), at least 10 ms apart. The onset sample is the first
|
|
41
|
+
// one in the 2 ms before the jump frame that reaches 10% of the burst's peak.
|
|
42
|
+
const F = RATE / 2000, frames = Math.floor(hp.length / F), fp = new Float32Array(frames);
|
|
43
|
+
for (let f = 0; f < frames; f++) { let m = 0; for (let i = f * F; i < (f + 1) * F; i++) m = Math.max(m, Math.abs(hp[i])); fp[f] = m; }
|
|
44
|
+
const onsets = []; let last = -Infinity;
|
|
45
|
+
for (let f = 30; f < frames; f++) {
|
|
46
|
+
let prev = 0; for (let j = f - 10; j < f; j++) prev = Math.max(prev, fp[j]);
|
|
47
|
+
if (fp[f] > 10 ** (-50 / 20) && fp[f] > 3 * prev && f - last > 20) {
|
|
48
|
+
let pk = 0; for (let j = f; j < Math.min(frames, f + 10); j++) pk = Math.max(pk, fp[j]);
|
|
49
|
+
let s = Math.max(0, (f - 4) * F); while (s < (f + 10) * F && Math.abs(hp[s]) < 0.1 * pk) s++;
|
|
50
|
+
onsets.push({ t: s / RATE, peak: pk }); last = f;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const ms = v => (v * 1000).toFixed(2);
|
|
54
|
+
const rows = cues.map(c => {
|
|
55
|
+
const o = onsets.reduce((b, o) => Math.abs(o.t - c.t) < Math.abs(b.t - c.t) ? o : b, { t: Infinity });
|
|
56
|
+
return { ...c, onset: o.t, err: o.t - c.t };
|
|
57
|
+
});
|
|
58
|
+
const frame = 1 / log.fps;
|
|
59
|
+
console.log(`audio stream: ${stream}`);
|
|
60
|
+
console.log(`cues ${cues.length}, detected onsets ${onsets.length}`);
|
|
61
|
+
for (const r of rows) console.log(` ${r.kind.padEnd(8)} event ${r.t.toFixed(4)} s onset ${Number.isFinite(r.onset) ? r.onset.toFixed(4) : 'none'} s error ${ms(r.err)} ms ${Math.abs(r.err) <= frame ? 'ok' : 'FAIL'}`);
|
|
62
|
+
const clicks = rows.filter(r => r.kind === 'click' || r.kind === 'release');
|
|
63
|
+
const worst = k => Math.max(0, ...rows.filter(r => k.includes(r.kind)).map(r => Math.abs(r.err)));
|
|
64
|
+
console.log(`worst click/release error ${ms(worst(['click', 'release']))} ms, keys ${ms(worst(['key', 'key-return']))} ms, scroll ${ms(worst(['scroll']))} ms (1 frame = ${ms(frame)} ms)`);
|
|
65
|
+
const matched = new Set(rows.map(r => r.onset));
|
|
66
|
+
const extra = onsets.filter(o => !matched.has(o.t));
|
|
67
|
+
console.log(`onsets with no cue: ${extra.length ? extra.map(o => o.t.toFixed(3)).join(', ') : 'none'}`);
|
|
68
|
+
console.log(`clicks within 1 frame: ${clicks.filter(r => Math.abs(r.err) <= frame).length}/${clicks.length}`);
|
|
69
|
+
|
|
70
|
+
const { err: r128 } = await run(['-hide_banner', '-nostats', '-i', video, '-vn', '-af', 'ebur128=peak=true', '-f', 'null', '-'], 'ignore');
|
|
71
|
+
const sum = r128.slice(r128.lastIndexOf('Summary:'));
|
|
72
|
+
console.log(`integrated ${sum.match(/I:\s+(-?[\d.]+) LUFS/)?.[1]} LUFS, LRA ${sum.match(/LRA:\s+(-?[\d.]+) LU/)?.[1]} LU, true peak ${sum.match(/Peak:\s+(-?[\d.]+) dBFS/)?.[1]} dBTP`);
|
|
73
|
+
let sp = 0; for (const v of st) sp = Math.max(sp, Math.abs(v));
|
|
74
|
+
console.log(`decoded sample peak ${(20 * Math.log10(sp)).toFixed(2)} dBFS (per channel), clipped samples ${st.filter(v => Math.abs(v) >= 1).length}`);
|
|
75
|
+
|
|
76
|
+
if (png) {
|
|
77
|
+
const W = 2400, H = 720, img = Buffer.alloc(W * H * 3, 255), wave = [20, 470], speedLane = [560, 700];
|
|
78
|
+
const px = (X, Y, [r, g, b]) => { if (X < 0 || Y < 0 || X >= W || Y >= H) return; const i = (Y * W + X) * 3; img[i] = r; img[i + 1] = g; img[i + 2] = b; };
|
|
79
|
+
const vline = (X, y0, y1, c) => { for (let Y = y0; Y <= y1; Y++) px(X, Y, c); };
|
|
80
|
+
const dur = x.length / RATE, tx = t => Math.round(t / dur * (W - 1));
|
|
81
|
+
// Second grid.
|
|
82
|
+
for (let s = 0; s <= dur; s++) vline(tx(s), 0, H - 1, [232, 232, 232]);
|
|
83
|
+
const mid = (wave[0] + wave[1]) / 2, half = (wave[1] - wave[0]) / 2;
|
|
84
|
+
for (let X = 0; X < W; X++) {
|
|
85
|
+
const a = Math.floor(X / W * x.length), b = Math.floor((X + 1) / W * x.length);
|
|
86
|
+
let lo = 0, hi = 0; for (let i = a; i < b; i++) { lo = Math.min(lo, x[i]); hi = Math.max(hi, x[i]); }
|
|
87
|
+
vline(X, Math.round(mid - hi * half), Math.round(mid - lo * half), [90, 90, 90]);
|
|
88
|
+
}
|
|
89
|
+
for (let X = 0; X < W; X++) px(X, Math.round(mid), [170, 170, 170]);
|
|
90
|
+
const colours = { click: [220, 30, 30], release: [240, 140, 0], key: [30, 90, 230], scroll: [20, 160, 60], 'key-return': [140, 180, 245] };
|
|
91
|
+
for (const c of cues) for (let d = 0; d < 2; d++) vline(tx(c.t) + d, 0, wave[1] + 20, colours[c.kind]);
|
|
92
|
+
for (const o of onsets) for (let d = -1; d <= 1; d++) vline(tx(o.t) + d, wave[1] + 30, wave[1] + 60, [0, 0, 0]);
|
|
93
|
+
// Camera speed: zoom rate (octaves/s) plus pan speed (widths/s), per frame.
|
|
94
|
+
const tr = log.track, speed = tr.map((b, i) => i ? Math.abs(Math.log2(b.cz / tr[i - 1].cz)) * log.fps + Math.hypot(b.cx - tr[i - 1].cx, b.cy - tr[i - 1].cy) * b.cz / log.layout.W * log.fps : 0);
|
|
95
|
+
const top = Math.max(...speed, 1e-6);
|
|
96
|
+
for (let X = 0; X < W; X++) { const v = speed[Math.min(speed.length - 1, Math.floor(X / W * speed.length))] / top; vline(X, Math.round(speedLane[1] - v * (speedLane[1] - speedLane[0])), speedLane[1], [120, 80, 200]); }
|
|
97
|
+
const raw = Buffer.alloc((W * 3 + 1) * H);
|
|
98
|
+
for (let Y = 0; Y < H; Y++) { raw[Y * (W * 3 + 1)] = 0; img.copy(raw, Y * (W * 3 + 1) + 1, Y * W * 3, (Y + 1) * W * 3); }
|
|
99
|
+
const crc = buf => { let c = ~0; for (const b of buf) { c ^= b; for (let k = 0; k < 8; k++) c = c & 1 ? (c >>> 1) ^ 0xedb88320 : c >>> 1; } return ~c >>> 0; };
|
|
100
|
+
const chunk = (type, data) => { const l = Buffer.alloc(4); l.writeUInt32BE(data.length); const td = Buffer.concat([Buffer.from(type), data]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([l, td, c]); };
|
|
101
|
+
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(W, 0); ihdr.writeUInt32BE(H, 4); ihdr[8] = 8; ihdr[9] = 2;
|
|
102
|
+
await writeFile(png, Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]));
|
|
103
|
+
console.log(`waveform ${png}`);
|
|
104
|
+
}
|