framepress 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +227 -2
- 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 +146 -0
- 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/art-variants.js +77 -0
- package/examples/ember.html +1 -0
- package/examples/indexed.html +1 -0
- package/examples/phosphor.html +1 -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 +55 -4
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Studio look for real screen recordings. Reads a capture folder (screen.mov, meta.json,
|
|
3
|
+
// events.jsonl from the native recorder) and renders it through the same compositor and
|
|
4
|
+
// camera rig as web takes: clicks drive auto zoom and pans, the cursor is drawn from the
|
|
5
|
+
// event path, every frame is 32 blurred subframes, and the backdrop moves with parallax.
|
|
6
|
+
import { parseArgs } from 'node:util';
|
|
7
|
+
import { chromium } from 'playwright-core';
|
|
8
|
+
import { ffmpegPath } from './ffmpeg.mjs';
|
|
9
|
+
import { spawn } from 'node:child_process';
|
|
10
|
+
import { once } from 'node:events';
|
|
11
|
+
import { realpathSync } from 'node:fs';
|
|
12
|
+
import { access, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
13
|
+
import { resolve, dirname } from 'node:path';
|
|
14
|
+
import { pathToFileURL } from 'node:url';
|
|
15
|
+
import { BACKDROPS, CORNERS, LOOK, PARALLAX, createStudio } from './studio.mjs';
|
|
16
|
+
import { MAX_ZOOM, createRig } from './camera.mjs';
|
|
17
|
+
import { RATE, soundtrack, writeWav } from './sound.mjs';
|
|
18
|
+
|
|
19
|
+
const ASPECTS = { '16:9': [1920, 1080], '16:10': [1920, 1200], '4:5': [1080, 1350], '1:1': [1080, 1080] };
|
|
20
|
+
// Wide frames: Screen Studio's 1080p export keeps 8.0 to 8.3% of the height above and below
|
|
21
|
+
// the recording (its 720p exports 10 to 10.8%), so a 16:10 desktop fills 84% of the height.
|
|
22
|
+
// Tall and square frames keep the studio pad.
|
|
23
|
+
export const VIDEO_PAD = { '16:9': 0.08, '16:10': 0.08 };
|
|
24
|
+
export const VIDEO_LOOK = 'acid-forest';
|
|
25
|
+
// Window captures (meta.source "window"): Screen Studio window recordings keep 7.4 to 11%
|
|
26
|
+
// of the short side on every side (three 720p exports: 53, 67 and 78 to 79 px), so 9%.
|
|
27
|
+
// The window gets its own corner radius and a deeper shadow, like a macOS window on a desktop:
|
|
28
|
+
// a tight contact shadow and a wide soft one. Layers are [dx, dy, sigma, alpha] of frame height.
|
|
29
|
+
export const WINDOW_PAD = 0.09;
|
|
30
|
+
export const WINDOW_SHADOW = [[0, 0.002, 0.003, 0.3], [0, 0.026, 0.045, 0.62]];
|
|
31
|
+
const help = `framepress-video --in <capture dir> --out <file.mp4> [options]
|
|
32
|
+
--look ${VIDEO_LOOK.padEnd(15)}Backdrop: none, #rrggbb or ${Object.keys(BACKDROPS).join(', ')}
|
|
33
|
+
--corner measured Window corner: ${Object.keys(CORNERS).join(', ')}
|
|
34
|
+
--zoom 1.75 Auto zoom on clicks (up to ${MAX_ZOOM})
|
|
35
|
+
--idle 0.45 Seconds without activity before zooming out
|
|
36
|
+
--parallax 0.5 Backdrop follows the camera at this ratio; 'off' pins it
|
|
37
|
+
--aspect 16:9 ${Object.keys(ASPECTS).join(' | ')}
|
|
38
|
+
--pad 0.08 Padding around the recording, as a fraction of the short side
|
|
39
|
+
(default 0.08 for 16:9 and 16:10, ${LOOK.pad} otherwise;
|
|
40
|
+
window captures ${WINDOW_PAD})
|
|
41
|
+
--trim a:b Seconds of the recording to keep, e.g. 1.5:9 or 2:
|
|
42
|
+
--cursor arrow.png Arrow image (360 px box, tip at 60,120 mirrored, like the chrome arrow);
|
|
43
|
+
default FRAMEPRESS_CURSOR, else a built-in arrow
|
|
44
|
+
--debug Draw a crosshair on every click point
|
|
45
|
+
--probe Draw the cursor as a dot on its hotspot (alignment check)
|
|
46
|
+
--log run.json Write the camera log and per-frame track
|
|
47
|
+
--browser /path Chrome executable (or CHROME_PATH)
|
|
48
|
+
--sound on Synthesized sound: clicks, key taps, scroll ticks, camera whoosh; off for silent
|
|
49
|
+
--sound-clicks 1 Level of press and release clicks (1 default, 0 mutes, up to 4)
|
|
50
|
+
--sound-keys 1 Level of key taps
|
|
51
|
+
--sound-scroll 1 Level of scroll ticks
|
|
52
|
+
--sound-whoosh 1 Level of the air whoosh on zooms and pans
|
|
53
|
+
--music <file|soft-keys|pad>
|
|
54
|
+
Background bed: an audio file you own, or a generated one ('soft-keys':
|
|
55
|
+
warm electric piano, 'pad': plain chords); off by default
|
|
56
|
+
--music-level 1 Level of the bed (1 sits 14 LU under the effects)
|
|
57
|
+
--force Replace an existing output`;
|
|
58
|
+
|
|
59
|
+
// Drawn cursor: zero-phase smoothing of the event path (no lag), pinned to the exact
|
|
60
|
+
// event position while a button is down and eased back to the smooth path around it,
|
|
61
|
+
// so the tip lands on every click and stays on a dragged handle.
|
|
62
|
+
export const SMOOTH = { sigma: 0.035, pin: 0.15, rate: 1000 };
|
|
63
|
+
// Click targets: the move that leads to a click starts after a still gap of `gap` seconds,
|
|
64
|
+
// looked for at most `look` seconds back; a drag whose end is `drag` points away also aims.
|
|
65
|
+
// merge: the camera stays zoomed through a pause when the next press is this close (we
|
|
66
|
+
// know the future offline, so a click then a drag is one zoom, not out and in again).
|
|
67
|
+
export const TARGETS = { gap: 0.12, still: 1.5, look: 1.5, drag: 12, noMoveLead: 0.2, merge: 1.2 };
|
|
68
|
+
|
|
69
|
+
export function loadEvents(text, trimA = 0, trimB = Infinity) {
|
|
70
|
+
const all = text.split('\n').filter(l => l.trim()).map(l => JSON.parse(l)).filter(e => Number.isFinite(e.t) && Number.isFinite(e.x) && Number.isFinite(e.y));
|
|
71
|
+
all.sort((a, b) => a.t - b.t);
|
|
72
|
+
return all.filter(e => e.t <= trimB + 1).map(e => ({ ...e, t: e.t - trimA }));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Everything the rig needs from the event log, as functions of time in seconds.
|
|
76
|
+
// bounds: {w, h} for window captures; presses outside the window still move the cursor but
|
|
77
|
+
// never aim the camera (the backdrop has nothing to show).
|
|
78
|
+
export function eventTrack(events, duration, bounds = null) {
|
|
79
|
+
const pts = events.map(e => ({ t: e.t, x: e.x, y: e.y }));
|
|
80
|
+
if (!pts.length) pts.push({ t: 0, x: 0, y: 0 });
|
|
81
|
+
const idx = t => { let lo = 0, hi = pts.length - 1; if (t <= pts[0].t) return -1; while (lo < hi) { const m = (lo + hi + 1) >> 1; if (pts[m].t <= t) lo = m; else hi = m - 1; } return lo; };
|
|
82
|
+
const rawAt = t => {
|
|
83
|
+
const i = idx(t); if (i < 0) return { x: pts[0].x, y: pts[0].y };
|
|
84
|
+
const a = pts[i], b = pts[i + 1]; if (!b || b.t === a.t) return { x: a.x, y: a.y };
|
|
85
|
+
const w = (t - a.t) / (b.t - a.t); return { x: a.x + (b.x - a.x) * w, y: a.y + (b.y - a.y) * w };
|
|
86
|
+
};
|
|
87
|
+
// Button intervals; a press with no release lasts to the end.
|
|
88
|
+
const presses = [];
|
|
89
|
+
for (const e of events) {
|
|
90
|
+
if (e.type === 'down') presses.push({ a: e.t, b: Infinity, down: e, up: null });
|
|
91
|
+
else if (e.type === 'up') { const p = presses.findLast(p => p.b === Infinity); if (p) { p.b = e.t; p.up = e; } }
|
|
92
|
+
}
|
|
93
|
+
const downAt = t => presses.some(p => t >= p.a && t < p.b);
|
|
94
|
+
// Smoothed tip on a fixed grid.
|
|
95
|
+
const { sigma, pin, rate } = SMOOTH, n = Math.ceil((duration + 1) * rate) + 1, t0 = -0.5;
|
|
96
|
+
const rx = new Float64Array(n), ry = new Float64Array(n);
|
|
97
|
+
for (let i = 0; i < n; i++) { const p = rawAt(t0 + i / rate); rx[i] = p.x; ry[i] = p.y; }
|
|
98
|
+
const R = Math.ceil(sigma * 3 * rate), k = Array.from({ length: 2 * R + 1 }, (_, j) => Math.exp(-0.5 * ((j - R) / (sigma * rate)) ** 2));
|
|
99
|
+
const tx = new Float64Array(n), ty = new Float64Array(n);
|
|
100
|
+
for (let i = 0; i < n; i++) {
|
|
101
|
+
let sx = 0, sy = 0, sw = 0;
|
|
102
|
+
for (let j = -R; j <= R; j++) { const q = Math.min(n - 1, Math.max(0, i + j)), w = k[j + R]; sx += rx[q] * w; sy += ry[q] * w; sw += w; }
|
|
103
|
+
const t = t0 + i / rate;
|
|
104
|
+
let d = Infinity; for (const p of presses) d = Math.min(d, t < p.a ? p.a - t : t > p.b ? t - p.b : 0);
|
|
105
|
+
const u = Math.min(1, d / pin), w = 1 - u * u * (3 - 2 * u);
|
|
106
|
+
tx[i] = sx / sw + (rx[i] - sx / sw) * w; ty[i] = sy / sw + (ry[i] - sy / sw) * w;
|
|
107
|
+
}
|
|
108
|
+
const tipAt = t => {
|
|
109
|
+
const f = Math.min(n - 1, Math.max(0, (t - t0) * rate)), i = Math.min(n - 2, Math.floor(f)), w = f - i;
|
|
110
|
+
return { x: tx[i] + (tx[i + 1] - tx[i]) * w, y: ty[i] + (ty[i + 1] - ty[i]) * w };
|
|
111
|
+
};
|
|
112
|
+
const shapes = events.filter(e => 'cursor' in e);
|
|
113
|
+
const shapeAt = t => { let s = 'arrow'; for (const e of shapes) { if (e.t > t) break; s = e.cursor ?? 'arrow'; } return s; };
|
|
114
|
+
// Camera targets: each click aims at its press point from the moment its move set off.
|
|
115
|
+
const moving = (i, j) => Math.hypot(pts[j].x - pts[i].x, pts[j].y - pts[i].y) > 0.25;
|
|
116
|
+
const onsetBefore = t => {
|
|
117
|
+
const { gap, look, still, noMoveLead } = TARGETS;
|
|
118
|
+
// The last movement before the press, then back to where that move set off.
|
|
119
|
+
let i = idx(t);
|
|
120
|
+
while (i > 0 && !moving(i - 1, i) && pts[i].t > t - look) i--;
|
|
121
|
+
if (i <= 0 || pts[i].t <= t - look || t - pts[i].t > 0.6) return t - noMoveLead;
|
|
122
|
+
const end = rawAt(pts[i].t);
|
|
123
|
+
let start = pts[i].t - pts[i - 1].t > gap ? pts[i].t - 1 / 120 : pts[i - 1].t, edge = start;
|
|
124
|
+
for (i--; i > 0 && start > t - look; i--) {
|
|
125
|
+
const a = pts[i - 1], b = pts[i];
|
|
126
|
+
if (b.t - a.t > gap) break;
|
|
127
|
+
if (moving(i - 1, i)) start = edge = a.t;
|
|
128
|
+
else if (edge - a.t > gap) break;
|
|
129
|
+
}
|
|
130
|
+
const s0 = rawAt(start);
|
|
131
|
+
// A click with (almost) no travel before it zooms as it lands.
|
|
132
|
+
return Math.hypot(end.x - s0.x, end.y - s0.y) > still ? Math.max(start, t - look) : t - noMoveLead;
|
|
133
|
+
};
|
|
134
|
+
const targets = [];
|
|
135
|
+
const inside = q => !bounds || (q.x >= 0 && q.y >= 0 && q.x <= bounds.w && q.y <= bounds.h);
|
|
136
|
+
for (const p of presses) {
|
|
137
|
+
if (!inside(p.down)) continue;
|
|
138
|
+
targets.push({ at: onsetBefore(p.a), to: { x: p.down.x, y: p.down.y }, kind: 'click', t: p.a });
|
|
139
|
+
if (p.up && inside(p.up) && Math.hypot(p.up.x - p.down.x, p.up.y - p.down.y) > TARGETS.drag) {
|
|
140
|
+
const first = events.find(e => e.t > p.a && e.t <= p.b && Math.hypot(e.x - p.down.x, e.y - p.down.y) > 2);
|
|
141
|
+
targets.push({ at: first?.t ?? p.a, to: { x: p.up.x, y: p.up.y }, kind: 'drag', t: p.b });
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
targets.sort((a, b) => a.at - b.at);
|
|
145
|
+
// Typing and scrolling keep a zoom alive but never start one.
|
|
146
|
+
const activity = events.filter(e => e.type === 'key' || e.type === 'scroll').map(e => e.t);
|
|
147
|
+
const activeIn = (a, b) => activity.some(t => t > a && t <= b);
|
|
148
|
+
return { rawAt, downAt, tipAt, shapeAt, targets, presses, activeIn };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// JPEG frames from an ffmpeg pipe, one at a time.
|
|
152
|
+
async function* jpegFrames(stream) {
|
|
153
|
+
let buf = Buffer.alloc(0);
|
|
154
|
+
for await (const chunk of stream) {
|
|
155
|
+
buf = Buffer.concat([buf, chunk]);
|
|
156
|
+
for (;;) {
|
|
157
|
+
const s = buf.indexOf(Buffer.from([0xff, 0xd8])); if (s < 0) break;
|
|
158
|
+
const e = buf.indexOf(Buffer.from([0xff, 0xd9]), s + 2); if (e < 0) break;
|
|
159
|
+
yield buf.subarray(s, e + 2); buf = buf.subarray(e + 2);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function main() {
|
|
165
|
+
const { values: v } = parseArgs({ options: {
|
|
166
|
+
in: { type: 'string' }, out: { type: 'string' }, look: { type: 'string', default: VIDEO_LOOK }, corner: { type: 'string', default: 'measured' },
|
|
167
|
+
zoom: { type: 'string', default: '1.75' }, idle: { type: 'string', default: '0.45' }, parallax: { type: 'string', default: String(PARALLAX.zoom) },
|
|
168
|
+
aspect: { type: 'string', default: '16:9' }, pad: { type: 'string' }, trim: { type: 'string' }, cursor: { type: 'string' }, debug: { type: 'boolean' }, probe: { type: 'boolean' },
|
|
169
|
+
sound: { type: 'string', default: 'on' }, 'sound-clicks': { type: 'string', default: '1' }, 'sound-keys': { type: 'string', default: '1' },
|
|
170
|
+
'sound-scroll': { type: 'string', default: '1' }, 'sound-whoosh': { type: 'string', default: '1' }, music: { type: 'string' }, 'music-level': { type: 'string', default: '1' },
|
|
171
|
+
log: { type: 'string' }, browser: { type: 'string' }, force: { type: 'boolean' }, help: { type: 'boolean' },
|
|
172
|
+
} });
|
|
173
|
+
if (v.help || !v.in || !v.out) { console.log(help); process.exit(v.help ? 0 : 1); }
|
|
174
|
+
const dir = resolve(v.in), out = resolve(v.out);
|
|
175
|
+
if (!out.endsWith('.mp4')) throw Error('Output must end in .mp4');
|
|
176
|
+
const output = ASPECTS[v.aspect]; if (!output) throw Error(`Aspect must be one of ${Object.keys(ASPECTS).join(', ')}`);
|
|
177
|
+
if (!(v.look === 'none' || v.look in BACKDROPS || /^#[0-9a-fA-F]{6}$/.test(v.look))) throw Error(`Unknown look. Use none, #rrggbb or ${Object.keys(BACKDROPS).join(', ')}`);
|
|
178
|
+
if (!(v.corner in CORNERS)) throw Error(`Unknown corner. Use ${Object.keys(CORNERS).join(', ')}`);
|
|
179
|
+
|
|
180
|
+
if (!['on', 'off'].includes(v.sound)) throw Error('Sound is on or off.');
|
|
181
|
+
const level = k => { const x = Number(v[k]); if (!(x >= 0 && x <= 4)) throw Error(`--${k} is a level from 0 to 4.`); return x; };
|
|
182
|
+
const sound = v.sound === 'on' && { clicks: level('sound-clicks'), keys: level('sound-keys'), scroll: level('sound-scroll'), whoosh: level('sound-whoosh'),
|
|
183
|
+
music: v.music && (['pad', 'soft-keys'].includes(v.music) ? v.music : resolve(v.music)), musicLevel: level('music-level') };
|
|
184
|
+
if (sound?.music && !['pad', 'soft-keys'].includes(sound.music)) await access(sound.music).catch(() => { throw Error(`Music file not found: ${sound.music}`); });
|
|
185
|
+
const zoom = Math.min(MAX_ZOOM, Number(v.zoom)), idle = Number(v.idle);
|
|
186
|
+
if (!(zoom >= 1) || !(idle > 0)) throw Error('Zoom must be 1 or more and idle above 0.');
|
|
187
|
+
const parallax = v.parallax === 'off' ? null : { ...PARALLAX, zoom: Number(v.parallax) };
|
|
188
|
+
if (parallax && !(parallax.zoom >= 0 && parallax.zoom <= 1)) throw Error('Parallax is a ratio from 0 to 1, or off.');
|
|
189
|
+
const meta = JSON.parse(await readFile(resolve(dir, 'meta.json'), 'utf8'));
|
|
190
|
+
if (meta.version !== 1) throw Error(`Unsupported meta.json version ${meta.version}`);
|
|
191
|
+
const fps = meta.fps, dp = meta.display_points, isWindow = meta.source === 'window';
|
|
192
|
+
const pad = v.pad === undefined ? (isWindow ? WINDOW_PAD : VIDEO_PAD[v.aspect] ?? LOOK.pad) : Number(v.pad);
|
|
193
|
+
if (!(pad >= 0 && pad < 0.4)) throw Error('Pad is a fraction of the short side from 0 to 0.4.');
|
|
194
|
+
const [ta, tb] = (v.trim ?? '0:').split(':').map((x, i) => x === '' || x === undefined ? (i ? meta.duration_s : 0) : Number(x));
|
|
195
|
+
if (!(ta >= 0 && tb > ta)) throw Error('Trim is a:b seconds with b after a.');
|
|
196
|
+
const duration = Math.min(tb, meta.duration_s) - ta;
|
|
197
|
+
const events = loadEvents(await readFile(resolve(dir, 'events.jsonl'), 'utf8'), ta, tb);
|
|
198
|
+
const track = eventTrack(events, duration, isWindow ? dp : null);
|
|
199
|
+
let exists = false; try { await access(out); exists = true; } catch {}
|
|
200
|
+
if (exists && !v.force) throw Error(`${out} exists. Use --force to replace it.`);
|
|
201
|
+
await mkdir(dirname(out), { recursive: true });
|
|
202
|
+
const cursor = v.cursor ?? process.env.FRAMEPRESS_CURSOR;
|
|
203
|
+
|
|
204
|
+
const ffmpeg = ffmpegPath();
|
|
205
|
+
const partial = `${out}.${process.pid}.partial.mp4`, wav = `${out}.${process.pid}.partial.wav`, muxed = `${out}.${process.pid}.muxed.mp4`;
|
|
206
|
+
let browser, decoder, encoder;
|
|
207
|
+
const started = performance.now();
|
|
208
|
+
try {
|
|
209
|
+
browser = await chromium.launch({ headless: true, ...(v.browser || process.env.CHROME_PATH ? { executablePath: v.browser || process.env.CHROME_PATH } : { channel: 'chrome' }), args: ['--mute-audio'] });
|
|
210
|
+
const take = { output, width: dp.w, height: dp.h, backdrop: v.look, pad, corner: v.corner, parallax, cursor: cursor && resolve(cursor), cursorShapes: true, probe: v.probe, fit: null,
|
|
211
|
+
...(isWindow && { windowRadius: meta.corner_radius_points ?? 10, shadow: WINDOW_SHADOW }) };
|
|
212
|
+
const studio = await createStudio(browser, take);
|
|
213
|
+
const L = studio.layout;
|
|
214
|
+
const log = [], probes = [];
|
|
215
|
+
const rig = createRig({ layout: L, fps, toComposite: studio.toComposite, start: track.rawAt(0), cursorSize: 32 * L.s0, tipAt: track.tipAt, downAt: track.downAt, shapeAt: track.shapeAt, log });
|
|
216
|
+
rig.startAuto(zoom, idle, 0);
|
|
217
|
+
// Decode at the most the camera can show: the window width at full zoom.
|
|
218
|
+
const srcW = Math.min(meta.width_px, 2 * Math.ceil(L.win.w * MAX_ZOOM / 2));
|
|
219
|
+
decoder = spawn(ffmpeg, ['-hide_banner', '-loglevel', 'error', ...(ta ? ['-ss', String(ta)] : []), '-i', resolve(dir, 'screen.mov'), '-t', String(duration), '-an',
|
|
220
|
+
'-vf', `scale=${srcW}:-2:flags=lanczos`, '-r', String(fps), '-f', 'image2pipe', '-c:v', 'mjpeg', '-q:v', '2', 'pipe:1'], { stdio: ['ignore', 'pipe', 'inherit'] });
|
|
221
|
+
encoder = spawn(ffmpeg, ['-hide_banner', '-loglevel', 'error', '-y', '-f', 'image2pipe', '-vcodec', 'mjpeg', '-framerate', String(fps), '-i', 'pipe:0', '-an', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '17', '-pix_fmt', 'yuv420p', '-r', String(fps), '-movflags', '+faststart', partial], { stdio: ['pipe', 'ignore', 'inherit'] });
|
|
222
|
+
const encoded = new Promise((res, rej) => encoder.once('close', c => c === 0 ? res() : rej(Error(`Encoder exited ${c}`)))); encoded.catch(() => {});
|
|
223
|
+
console.log(`\n ◈ FRAMEPRESS VIDEO\n ${dir}\n ${output.join(' × ')} / ${fps} fps / ${duration.toFixed(2)} s / ${isWindow ? `window ${dp.w}×${dp.h} pt, corner ${meta.corner_radius_points ?? 10} pt / ` : ''}source ${meta.width_px}×${meta.height_px} decoded at ${srcW} wide\n`);
|
|
224
|
+
let frame = 0, ti = 0;
|
|
225
|
+
const frames = Math.round(duration * fps);
|
|
226
|
+
for await (const jpeg of jpegFrames(decoder.stdout)) {
|
|
227
|
+
if (frame >= frames) break;
|
|
228
|
+
const t = frame / fps;
|
|
229
|
+
Object.assign(rig.rawPrev, { x: rig.raw.x, y: rig.raw.y });
|
|
230
|
+
Object.assign(rig.raw, track.rawAt(t), { down: track.downAt(t) });
|
|
231
|
+
// Aim at every click whose move set off since the last frame.
|
|
232
|
+
while (ti < track.targets.length && track.targets[ti].at <= t + 1e-9) {
|
|
233
|
+
const g = track.targets[ti++];
|
|
234
|
+
rig.aim(g.to, frame);
|
|
235
|
+
log.push({ line: 0, step: `target ${g.kind} at ${g.t.toFixed(3)}s (${g.to.x.toFixed(1)}, ${g.to.y.toFixed(1)})`, frame });
|
|
236
|
+
}
|
|
237
|
+
rig.autoCamera(frame, track.activeIn(t - 1 / fps, t) || track.presses.some(p => p.a > t && p.a - t <= TARGETS.merge));
|
|
238
|
+
const pose = rig.pose(frame);
|
|
239
|
+
// Screen content between two source frames: blend by subframe time.
|
|
240
|
+
for (const s of pose.subs) { s.mix = frame === 0 ? 1 : s.t; delete s.t; }
|
|
241
|
+
const toOut = (c, q) => ({ x: (q.x - c.x) * c.z + L.W / 2, y: (q.y - c.y) * c.z + L.H / 2 });
|
|
242
|
+
if (v.debug) pose.marks = track.presses.filter(p => Math.abs(p.a - t) < 0.25 || (t >= p.a && t <= p.b)).map(p => toOut(pose.subs.at(-1).cam, studio.toComposite(p.down.x, p.down.y)));
|
|
243
|
+
// Where each press point lands in this frame, averaged over the same subframe cameras.
|
|
244
|
+
if (v.probe) for (const [kind, p] of track.presses.flatMap(p => [['down', p.down], ['up', p.up]])) {
|
|
245
|
+
if (!p || Math.abs(p.t - t) > 0.5 / fps) continue;
|
|
246
|
+
const o = pose.subs.map(s => toOut(s.cam, studio.toComposite(p.x, p.y)));
|
|
247
|
+
probes.push({ frame, kind, t: p.t, x: o.reduce((a, q) => a + q.x, 0) / o.length, y: o.reduce((a, q) => a + q.y, 0) / o.length });
|
|
248
|
+
}
|
|
249
|
+
const data = await studio.render(jpeg.toString('base64'), pose, frame > 0);
|
|
250
|
+
if (!encoder.stdin.write(Buffer.from(data, 'base64'))) await Promise.race([once(encoder.stdin, 'drain'), encoded]);
|
|
251
|
+
if (frame % 30 === 0) process.stdout.write(`\r frame ${frame}/${frames}`);
|
|
252
|
+
frame++;
|
|
253
|
+
}
|
|
254
|
+
decoder.kill();
|
|
255
|
+
encoder.stdin.end(); await encoded;
|
|
256
|
+
if (!frame) throw Error('No frames decoded from screen.mov');
|
|
257
|
+
for (const e of log.filter(e => e.cameraStart !== undefined)) console.log(`\n f${String(e.frame).padStart(4)} ${e.step}`);
|
|
258
|
+
// Sound: synthesized against the output timeline (event times are already trim-shifted),
|
|
259
|
+
// then muxed with the video as AAC 48 kHz.
|
|
260
|
+
let audio = null;
|
|
261
|
+
if (sound) {
|
|
262
|
+
const st = await soundtrack({ events, duration, frames: frame, fps, track: rig.track, W: L.W, width: dp.w, opts: sound, ffmpeg });
|
|
263
|
+
await writeWav(wav, st.L, st.R);
|
|
264
|
+
const mux = spawn(ffmpeg, ['-hide_banner', '-loglevel', 'error', '-y', '-i', partial, '-i', wav, '-map', '0:v', '-map', '1:a', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-ar', String(RATE), '-movflags', '+faststart', muxed], { stdio: ['ignore', 'ignore', 'inherit'] });
|
|
265
|
+
const [code] = await once(mux, 'close'); if (code !== 0) throw Error(`Audio mux exited ${code}`);
|
|
266
|
+
await rename(muxed, partial);
|
|
267
|
+
audio = { cues: st.cues, ...st.stats };
|
|
268
|
+
const count = k => st.cues.filter(c => c.kind === k).length;
|
|
269
|
+
console.log(`\n sound: ${count('click')} clicks, ${count('release')} releases, ${count('key')} keys, ${count('scroll')} scroll ticks${sound.whoosh ? ', whoosh' : ''}${sound.music ? `, music ${['pad', 'soft-keys'].includes(sound.music) ? sound.music : 'file'} ${st.stats.music_vs_fx_lu} LU vs effects` : ''} / ${st.stats.lufs} LUFS, peak ${st.stats.peak_dbfs} dBFS, limiter ${st.stats.limiter_db} dB`);
|
|
270
|
+
}
|
|
271
|
+
if (v.log) await writeFile(resolve(v.log), JSON.stringify({ input: dir, fps, frames: frame, trim: [ta, ta + duration], layout: L, steps: log, track: rig.track, targets: track.targets, probes, audio }) + '\n');
|
|
272
|
+
await rename(partial, out);
|
|
273
|
+
const el = (performance.now() - started) / 1000;
|
|
274
|
+
console.log(`\n\n ✓ ${out}\n ${frame} frames · ${(frame / el).toFixed(1)} render fps · ${el.toFixed(1)}s elapsed\n`);
|
|
275
|
+
} finally {
|
|
276
|
+
decoder?.kill(); encoder?.kill(); await browser?.close().catch(() => {});
|
|
277
|
+
await Promise.all([partial, wav, muxed].map(f => rm(f, { force: true })));
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// realpath: npm links bins, so argv[1] is the symlink, not this file.
|
|
282
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) main().catch(e => { console.error(`\n ${e.message}`); process.exitCode = 1; });
|