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/mcp.mjs
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { execFile, spawn } from 'node:child_process';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { constants } from 'node:fs';
|
|
5
|
+
import { access, mkdir, readFile, rmdir } from 'node:fs/promises';
|
|
6
|
+
import { tmpdir } from 'node:os';
|
|
7
|
+
import { join, resolve } from 'node:path';
|
|
8
|
+
import { createInterface } from 'node:readline';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { promisify } from 'node:util';
|
|
11
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
12
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
13
|
+
import { z } from 'zod';
|
|
14
|
+
import { BACKDROPS } from './studio.mjs';
|
|
15
|
+
import { VIDEO_LOOK } from './studio-video.mjs';
|
|
16
|
+
import { MAX_ZOOM } from './camera.mjs';
|
|
17
|
+
|
|
18
|
+
const run = promisify(execFile);
|
|
19
|
+
const local = (path) => fileURLToPath(new URL(path, import.meta.url));
|
|
20
|
+
const server = new McpServer({
|
|
21
|
+
name: 'framepress-mcp-server',
|
|
22
|
+
version: JSON.parse(await readFile(local('../package.json'), 'utf8')).version,
|
|
23
|
+
});
|
|
24
|
+
const recordings = new Map();
|
|
25
|
+
let closing = false;
|
|
26
|
+
|
|
27
|
+
async function captureBinary() {
|
|
28
|
+
if (process.platform !== 'darwin') throw Error('Native capture requires macOS 14 or newer.');
|
|
29
|
+
for (const candidate of ['../native/.build/release/framepress-capture', '../native/bin/framepress-capture']) {
|
|
30
|
+
if (candidate.includes('/bin/') && process.arch !== 'arm64') continue;
|
|
31
|
+
const path = local(candidate);
|
|
32
|
+
if (await access(path, constants.X_OK).then(() => true, () => false)) return path;
|
|
33
|
+
}
|
|
34
|
+
throw Error('Capture binary unavailable. In a Framepress checkout, run swift build -c release --package-path native.');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function launchRecording(binary, args, duration) {
|
|
38
|
+
const child = spawn(binary, args, { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
39
|
+
const lines = createInterface({ input: child.stderr });
|
|
40
|
+
let diagnostics = '';
|
|
41
|
+
let startError;
|
|
42
|
+
child.once('error', (error) => { startError = error; });
|
|
43
|
+
const closed = new Promise((done) => {
|
|
44
|
+
child.once('close', (code, signal) => done({
|
|
45
|
+
code,
|
|
46
|
+
error: startError?.message || diagnostics.trim() || `Recorder exited with ${signal ?? code}.`,
|
|
47
|
+
}));
|
|
48
|
+
});
|
|
49
|
+
const ready = new Promise((accept, reject) => {
|
|
50
|
+
lines.on('line', (line) => {
|
|
51
|
+
if (line === 'framepress-capture: ready') accept();
|
|
52
|
+
else {
|
|
53
|
+
diagnostics = `${diagnostics}${line}\n`.slice(-8192);
|
|
54
|
+
process.stderr.write(`${line}\n`);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
closed.then(({ error }) => reject(Error(error)));
|
|
58
|
+
});
|
|
59
|
+
let stopping;
|
|
60
|
+
return {
|
|
61
|
+
ready,
|
|
62
|
+
stop() {
|
|
63
|
+
stopping ??= (async () => {
|
|
64
|
+
// A timed recording ends by itself: wait for it, with a margin, before stopping it early.
|
|
65
|
+
if (duration !== undefined && !closing) await Promise.race([closed, new Promise((done) => setTimeout(done, (duration + 30) * 1000))]);
|
|
66
|
+
if (child.exitCode === null && child.signalCode === null) child.kill('SIGTERM');
|
|
67
|
+
const timeout = setTimeout(() => child.kill('SIGKILL'), 20_000);
|
|
68
|
+
try {
|
|
69
|
+
const result = await closed;
|
|
70
|
+
if (result.code !== 0) throw Error(result.error);
|
|
71
|
+
} finally {
|
|
72
|
+
clearTimeout(timeout);
|
|
73
|
+
}
|
|
74
|
+
})();
|
|
75
|
+
return stopping;
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function tool(name, config, handler) {
|
|
81
|
+
server.registerTool(name, config, async (input) => {
|
|
82
|
+
try {
|
|
83
|
+
const result = await handler(input);
|
|
84
|
+
return { structuredContent: result, content: [{ type: 'text', text: JSON.stringify(result) }] };
|
|
85
|
+
} catch (error) {
|
|
86
|
+
return { isError: true, content: [{ type: 'text', text: error.stderr?.trim() || error.message }] };
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const path = z.string().min(1);
|
|
92
|
+
const ASPECTS = ['16:9', '16:10', '4:5', '1:1'];
|
|
93
|
+
const LOOK = new RegExp(`^(none|#[0-9a-fA-F]{6}|${Object.keys(BACKDROPS).join('|')})$`);
|
|
94
|
+
const size = z.object({ w: z.number(), h: z.number() });
|
|
95
|
+
const point = z.object({ x: z.number(), y: z.number() });
|
|
96
|
+
|
|
97
|
+
tool('list_displays', {
|
|
98
|
+
description: 'List active macOS displays and their IDs, dimensions and origins.',
|
|
99
|
+
inputSchema: {},
|
|
100
|
+
outputSchema: {
|
|
101
|
+
displays: z.array(z.object({
|
|
102
|
+
id: z.number().int(), main: z.boolean(), width_px: z.number().int(), height_px: z.number().int(),
|
|
103
|
+
display_points: size, origin_points: point,
|
|
104
|
+
})),
|
|
105
|
+
},
|
|
106
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
107
|
+
}, async () => {
|
|
108
|
+
const { stdout } = await run(await captureBinary(), ['displays']);
|
|
109
|
+
return { displays: JSON.parse(stdout) };
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
tool('start_recording', {
|
|
113
|
+
description: 'Start native macOS capture of a display or of one app window. Window capture records only that window (no desktop, menu bar or shadow), which renders as a floating window on the backdrop. Returns as soon as capture is running. With duration, the recording stops on its own after that many seconds; call stop_recording right away and it waits for the end and returns the folder. Without duration, call stop_recording when the user is done.',
|
|
114
|
+
inputSchema: {
|
|
115
|
+
display: z.number().int().min(0).max(0xffffffff).optional().describe('Display ID from list_displays. Defaults to the main display.'),
|
|
116
|
+
window: z.string().min(1).optional().describe('Record only this window: a visible window title, or an application bundle ID such as com.apple.finder (its frontmost window). Omit display when selecting a window.'),
|
|
117
|
+
fps: z.number().int().min(1).max(120).optional().describe('Video frame rate. Defaults to 60.'),
|
|
118
|
+
duration: z.number().positive().max(600).optional().describe('Seconds to record, then stop automatically. Use this for "record for 20 seconds". Omit to record until stop_recording.'),
|
|
119
|
+
},
|
|
120
|
+
outputSchema: { recording_id: z.string(), dir: path },
|
|
121
|
+
annotations: { destructiveHint: false, openWorldHint: false },
|
|
122
|
+
}, async ({ display, window, fps, duration }) => {
|
|
123
|
+
if (display !== undefined && window !== undefined) throw Error('Choose either display or window.');
|
|
124
|
+
const binary = await captureBinary();
|
|
125
|
+
const recordingId = randomUUID();
|
|
126
|
+
const dir = join(tmpdir(), 'framepress', recordingId);
|
|
127
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
128
|
+
const args = ['record', '--out', dir];
|
|
129
|
+
if (display !== undefined) args.push('--display', String(display));
|
|
130
|
+
if (window !== undefined) args.push('--window', window);
|
|
131
|
+
if (fps !== undefined) args.push('--fps', String(fps));
|
|
132
|
+
if (duration !== undefined) args.push('--duration', String(duration));
|
|
133
|
+
if (closing) throw Error('The MCP session is closing.');
|
|
134
|
+
const recording = launchRecording(binary, args, duration);
|
|
135
|
+
recordings.set(recordingId, { dir, recording });
|
|
136
|
+
try {
|
|
137
|
+
await recording.ready;
|
|
138
|
+
} catch (error) {
|
|
139
|
+
recordings.delete(recordingId);
|
|
140
|
+
await rmdir(dir).catch(() => {});
|
|
141
|
+
const displays = await run(binary, ['displays']).then(({ stdout }) => JSON.parse(stdout), () => []);
|
|
142
|
+
if (!displays.length) throw Error(`${error.message} macOS reports no active displays: the screen is locked or asleep, or Screen Recording is not allowed for the app running this agent (System Settings > Privacy & Security > Screen & System Audio Recording).`);
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
return { recording_id: recordingId, dir };
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
tool('stop_recording', {
|
|
149
|
+
description: 'Stop a recording from this MCP session and wait for screen.mov, events.jsonl and meta.json. For a recording started with duration, this waits until that duration has elapsed instead of cutting it short.',
|
|
150
|
+
inputSchema: { recording_id: z.string().min(1) },
|
|
151
|
+
outputSchema: { dir: path, duration_s: z.number() },
|
|
152
|
+
annotations: { destructiveHint: false, openWorldHint: false },
|
|
153
|
+
}, async ({ recording_id }) => {
|
|
154
|
+
const entry = recordings.get(recording_id);
|
|
155
|
+
if (!entry) throw Error('Unknown recording_id. Use the ID returned by start_recording in this session.');
|
|
156
|
+
const { dir, recording } = entry;
|
|
157
|
+
try {
|
|
158
|
+
await recording.stop();
|
|
159
|
+
const { duration_s } = JSON.parse(await readFile(join(dir, 'meta.json'), 'utf8'));
|
|
160
|
+
return { dir, duration_s };
|
|
161
|
+
} finally {
|
|
162
|
+
recordings.delete(recording_id);
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
tool('render', {
|
|
167
|
+
description: 'Render a native recording directory to a styled MP4 with the Framepress compositor: backdrop, auto zoom on clicks, drawn cursor, motion blur. Window captures render as a rounded window with a soft shadow on the backdrop, 9% padding. Needs Google Chrome.',
|
|
168
|
+
inputSchema: {
|
|
169
|
+
dir: path.describe('Capture directory from stop_recording (screen.mov, events.jsonl, meta.json).'),
|
|
170
|
+
out: path.optional().describe('Output MP4 path. Defaults to render.mp4 in dir.'),
|
|
171
|
+
look: z.string().regex(LOOK).optional().describe(`Backdrop: none, #rrggbb or ${Object.keys(BACKDROPS).join(', ')}. Defaults to ${VIDEO_LOOK}.`),
|
|
172
|
+
zoom: z.number().min(1).max(MAX_ZOOM).optional().describe(`Auto zoom on clicks, 1 to ${MAX_ZOOM}. 1 disables zoom. Defaults to 1.75.`),
|
|
173
|
+
parallax: z.union([z.number().min(0).max(1), z.literal('off')]).optional().describe('Ratio the backdrop follows the camera, 0 to 1, or off to pin it. Defaults to 0.5.'),
|
|
174
|
+
aspect: z.enum(ASPECTS).optional().describe('Output frame: 16:9 (1920x1080, default), 16:10, 4:5 or 1:1. Wide frames keep 8% padding; window captures 9%.'),
|
|
175
|
+
trim: z.string().regex(/^\d*\.?\d*:\d*\.?\d*$/).optional().describe('Seconds of the recording to keep as start:end, e.g. 1.5:9 or 2: for start only.'),
|
|
176
|
+
cursor: path.optional().describe('PNG arrow image in a 360 px box with the tip at 60,120, mirrored. Defaults to FRAMEPRESS_CURSOR if set, else the built-in arrow.'),
|
|
177
|
+
sound: z.object({
|
|
178
|
+
on: z.boolean().optional().describe('Synthesized sound. Defaults to true: press and release clicks, key taps, scroll ticks and a faint whoosh on camera moves.'),
|
|
179
|
+
clicks: z.number().min(0).max(4).optional().describe('Click level, 1 default, 0 mutes.'),
|
|
180
|
+
keys: z.number().min(0).max(4).optional().describe('Key tap level, 1 default, 0 mutes.'),
|
|
181
|
+
scroll: z.number().min(0).max(4).optional().describe('Scroll tick level, 1 default, 0 mutes.'),
|
|
182
|
+
whoosh: z.number().min(0).max(4).optional().describe('Camera whoosh level, 1 default, 0 mutes.'),
|
|
183
|
+
music: z.string().optional().describe("Background bed: 'soft-keys' (warm electric piano) or 'pad' for a generated one, or a path to an audio file the user owns. Off by default."),
|
|
184
|
+
music_level: z.number().min(0).max(4).optional().describe('Bed level, 1 default.'),
|
|
185
|
+
}).optional().describe('Sound options. Audio is AAC 48 kHz, normalized toward -18 LUFS with a limiter.'),
|
|
186
|
+
force: z.boolean().optional().describe('Replace an existing output file.'),
|
|
187
|
+
},
|
|
188
|
+
outputSchema: { video_path: path },
|
|
189
|
+
}, async ({ dir, out, look, zoom, parallax, aspect, trim, cursor, sound, force }) => {
|
|
190
|
+
const video_path = resolve(out ?? join(dir, 'render.mp4'));
|
|
191
|
+
const args = [local('./studio-video.mjs'), '--in', resolve(dir), '--out', video_path];
|
|
192
|
+
if (look !== undefined) args.push('--look', look);
|
|
193
|
+
if (zoom !== undefined) args.push('--zoom', String(zoom));
|
|
194
|
+
if (parallax !== undefined) args.push('--parallax', String(parallax));
|
|
195
|
+
if (aspect !== undefined) args.push('--aspect', aspect);
|
|
196
|
+
if (trim !== undefined) args.push('--trim', trim);
|
|
197
|
+
if (cursor !== undefined) args.push('--cursor', resolve(cursor));
|
|
198
|
+
if (sound?.on === false) args.push('--sound', 'off');
|
|
199
|
+
for (const [k, flag] of [['clicks', '--sound-clicks'], ['keys', '--sound-keys'], ['scroll', '--sound-scroll'], ['whoosh', '--sound-whoosh'], ['music_level', '--music-level']])
|
|
200
|
+
if (sound?.[k] !== undefined) args.push(flag, String(sound[k]));
|
|
201
|
+
if (sound?.music !== undefined) args.push('--music', ['pad', 'soft-keys'].includes(sound.music) ? sound.music : resolve(sound.music));
|
|
202
|
+
if (force) args.push('--force');
|
|
203
|
+
await run(process.execPath, args, { maxBuffer: 16 << 20 });
|
|
204
|
+
return { video_path };
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
tool('record_web_take', {
|
|
208
|
+
description: 'Run a Framepress web take script in headless Chrome and return the rendered MP4 path.',
|
|
209
|
+
inputSchema: {
|
|
210
|
+
take: path.describe('Path to a .take file.'),
|
|
211
|
+
out: path.optional().describe('Output MP4 path. Defaults to take.mp4 in the working directory.'),
|
|
212
|
+
log: path.optional().describe('Optional output JSON path for the take timeline.'),
|
|
213
|
+
},
|
|
214
|
+
outputSchema: { video_path: path },
|
|
215
|
+
}, async ({ take, out, log }) => {
|
|
216
|
+
const video_path = resolve(out ?? 'take.mp4');
|
|
217
|
+
const args = [local('./record.mjs'), '--take', resolve(take), '--out', video_path];
|
|
218
|
+
if (log !== undefined) args.push('--log', resolve(log));
|
|
219
|
+
await run(process.execPath, args, { maxBuffer: 16 << 20 });
|
|
220
|
+
return { video_path };
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
async function shutdown() {
|
|
224
|
+
if (closing) return;
|
|
225
|
+
closing = true;
|
|
226
|
+
await Promise.allSettled([...recordings.values()].map(({ recording }) => recording.stop()));
|
|
227
|
+
process.exit();
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
process.stdin.once('end', shutdown);
|
|
231
|
+
process.once('SIGINT', shutdown);
|
|
232
|
+
process.once('SIGTERM', shutdown);
|
|
233
|
+
await server.connect(new StdioServerTransport());
|
package/bin/record.mjs
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { parseArgs } from 'node:util';
|
|
3
3
|
import { chromium } from 'playwright-core';
|
|
4
|
-
import
|
|
4
|
+
import { ffmpegPath } from './ffmpeg.mjs';
|
|
5
5
|
import { spawn } from 'node:child_process';
|
|
6
6
|
import { once } from 'node:events';
|
|
7
7
|
import { access, mkdir, rename, rm } from 'node:fs/promises';
|
|
8
8
|
import { resolve, dirname } from 'node:path';
|
|
9
9
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
10
|
+
import { writeFile } from 'node:fs/promises';
|
|
11
|
+
import { parseTake, createTakeRunner } from './take.mjs';
|
|
12
|
+
import { createStudio } from './studio.mjs';
|
|
10
13
|
|
|
11
14
|
const help = `framepress <url> [options]
|
|
15
|
+
framepress --take shot.take [--log shot.json]
|
|
12
16
|
--demo Render a bundled art study
|
|
13
17
|
--style ember ember | indexed | phosphor
|
|
14
18
|
--out clip.mp4 Output path (default: demo.mp4)
|
|
@@ -17,6 +21,8 @@ const help = `framepress <url> [options]
|
|
|
17
21
|
--width 1280 --height 720
|
|
18
22
|
--ready '#canvas' Wait for a visible element before capture
|
|
19
23
|
--browser /path Chrome/Chromium executable (or CHROME_PATH)
|
|
24
|
+
--take shot.take Run a take script; camera cues can wait on page state
|
|
25
|
+
--log shot.json Write the take's step timeline with frame numbers
|
|
20
26
|
--force Replace an existing output
|
|
21
27
|
--help
|
|
22
28
|
|
|
@@ -33,14 +39,18 @@ try {
|
|
|
33
39
|
demo: { type: 'boolean' }, style: { type: 'string', default: 'ember' }, out: { type: 'string', default: 'demo.mp4' },
|
|
34
40
|
seconds: { type: 'string', default: '6' }, fps: { type: 'string', default: '60' },
|
|
35
41
|
width: { type: 'string', default: '1280' }, height: { type: 'string', default: '720' },
|
|
36
|
-
ready: { type: 'string' }, browser: { type: 'string' }, force: { type: 'boolean' }, help: { type: 'boolean' },
|
|
42
|
+
ready: { type: 'string' }, take: { type: 'string' }, log: { type: 'string' }, browser: { type: 'string' }, force: { type: 'boolean' }, help: { type: 'boolean' },
|
|
37
43
|
}});
|
|
38
44
|
if (v.help) { console.log(help); process.exit(0); }
|
|
39
|
-
const
|
|
45
|
+
const take = v.take ? await parseTake(v.take) : undefined;
|
|
46
|
+
if (take && (v.demo || positionals.length)) throw Error('Use --take on its own; the take names its page.');
|
|
47
|
+
const width = take?.width ?? Number(v.width), height = take?.height ?? Number(v.height), fps = take?.fps ?? Number(v.fps);
|
|
48
|
+
// For a take, --seconds is only a safety limit; the script decides the length.
|
|
49
|
+
const seconds = take && v.seconds === '6' ? 120 : Number(v.seconds);
|
|
40
50
|
if (![width, height, fps].every(Number.isInteger) || width < 2 || height < 2 || width > 7680 || height > 7680 || width % 2 || height % 2 || fps < 1 || fps > 120 || !Number.isFinite(seconds) || seconds <= 0 || seconds > 600) throw Error('Use even dimensions 2–7680, fps 1–120 and duration 0–600 seconds.');
|
|
41
|
-
if ((!v.demo && positionals.length !== 1) || (v.demo && positionals.length)) throw Error(help);
|
|
51
|
+
if (!take && (!v.demo && positionals.length !== 1) || (v.demo && positionals.length)) throw Error(help);
|
|
42
52
|
if (!['indexed', 'phosphor', 'ember'].includes(v.style)) throw Error('Style must be ember, indexed or phosphor.');
|
|
43
|
-
const url = v.demo ? pathToFileURL(fileURLToPath(new URL(`../examples/${v.style}.html`, import.meta.url))).href : new URL(positionals[0]).href;
|
|
53
|
+
const url = take ? take.url : v.demo ? pathToFileURL(fileURLToPath(new URL(`../examples/${v.style}.html`, import.meta.url))).href : new URL(positionals[0]).href;
|
|
44
54
|
if (!['http:', 'https:', 'file:'].includes(new URL(url).protocol)) throw Error('URL must use http, https or file.');
|
|
45
55
|
const out = resolve(v.out);
|
|
46
56
|
if (!out.endsWith('.mp4')) throw Error('Output must end in .mp4');
|
|
@@ -50,12 +60,13 @@ try {
|
|
|
50
60
|
partial = `${out}.${process.pid}.partial.mp4`;
|
|
51
61
|
const start = performance.now();
|
|
52
62
|
const frames = Math.max(1, Math.round(seconds * fps));
|
|
53
|
-
console.log(`\n ◈ FRAMEPRESS\n ${width} × ${height} / ${fps} fps / ${frames} frames\n`);
|
|
63
|
+
console.log(`\n ◈ FRAMEPRESS\n ${take ? take.output.join(' × ') : `${width} × ${height}`} / ${fps} fps / ${take ? `take ${v.take}` : `${frames} frames`}\n`);
|
|
64
|
+
const ffmpeg = ffmpegPath();
|
|
54
65
|
browser = await chromium.launch({ headless: true, ...(v.browser || process.env.CHROME_PATH ? { executablePath: v.browser || process.env.CHROME_PATH } : { channel: 'chrome' }), args: ['--mute-audio'] });
|
|
55
|
-
const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: 1 });
|
|
66
|
+
const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: take?.scale ?? 1 });
|
|
56
67
|
const errors = [];
|
|
57
68
|
page.on('pageerror', e => errors.push(e.message));
|
|
58
|
-
await page.addInitScript(
|
|
69
|
+
await page.addInitScript(lockAnimations => {
|
|
59
70
|
let time = 0, next = 0;
|
|
60
71
|
const callbacks = new Map();
|
|
61
72
|
Object.defineProperty(performance, 'now', { value: () => time });
|
|
@@ -65,14 +76,37 @@ try {
|
|
|
65
76
|
time = ms;
|
|
66
77
|
if (typeof window.__demoRender === 'function') await window.__demoRender(ms / 1000);
|
|
67
78
|
else { const batch = [...callbacks.values()]; callbacks.clear(); for (const callback of batch) callback(ms); }
|
|
79
|
+
window.__framepressSyncAnimations?.();
|
|
68
80
|
};
|
|
69
|
-
|
|
81
|
+
if (!lockAnimations) return;
|
|
82
|
+
// Takes also put CSS transitions and Web Animations on the virtual clock.
|
|
83
|
+
const born = new WeakMap();
|
|
84
|
+
window.__framepressSyncAnimations = () => {
|
|
85
|
+
for (const animation of document.getAnimations()) {
|
|
86
|
+
if (!born.has(animation)) { born.set(animation, time); animation.pause(); }
|
|
87
|
+
animation.currentTime = time - born.get(animation);
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
}, !!take);
|
|
70
91
|
await page.goto(url, { waitUntil: 'load', timeout: 30000 });
|
|
71
92
|
// Prime applications that create their canvas inside the first animation frame.
|
|
72
93
|
await page.evaluate(() => window.__recorderStep(0));
|
|
73
94
|
if (v.ready) await page.locator(v.ready).waitFor({ state: 'visible', timeout: 15000 });
|
|
74
95
|
await page.evaluate(() => document.fonts.ready);
|
|
75
96
|
if (errors.length) throw Error(errors.join('\n'));
|
|
97
|
+
if (take?.style) { await page.addStyleTag({ content: take.style }); await page.evaluate(() => window.__recorderStep(0)); }
|
|
98
|
+
if (take?.fit) {
|
|
99
|
+
const b = await page.locator(take.fit.selector).first().boundingBox();
|
|
100
|
+
if (!b) throw Error(`fit: no visible element for "${take.fit.selector}"`);
|
|
101
|
+
const p = take.fit.pad, x = Math.max(0, Math.floor(b.x - p)), y = Math.max(0, Math.floor(b.y - p));
|
|
102
|
+
take.clip = { x, y, width: Math.min(width - x, Math.ceil(b.width + 2 * p)), height: Math.min(height - y, Math.ceil(b.height + 2 * p)) };
|
|
103
|
+
// The element's own corners and its gap to the clip edge, for nested or frameless window corners.
|
|
104
|
+
take.fit.radii = await page.locator(take.fit.selector).first().evaluate(e => { const s = getComputedStyle(e);
|
|
105
|
+
return ['borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomRightRadius', 'borderBottomLeftRadius'].map(k => parseFloat(s[k]) || 0); });
|
|
106
|
+
take.fit.gap = { l: b.x - x, t: b.y - y, r: x + take.clip.width - b.x - b.width, b: y + take.clip.height - b.y - b.height };
|
|
107
|
+
}
|
|
108
|
+
const studio = take && await createStudio(browser, take);
|
|
109
|
+
const runner = take && await createTakeRunner(page, take, studio);
|
|
76
110
|
const cdp = await page.context().newCDPSession(page);
|
|
77
111
|
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', '-movflags', '+faststart', partial], { stdio: ['pipe', 'ignore', 'pipe'] });
|
|
78
112
|
let encodingError = ''; encoder.stderr.on('data', b => { encodingError = (encodingError + b).slice(-4000); });
|
|
@@ -80,19 +114,30 @@ try {
|
|
|
80
114
|
const encoded = new Promise((res, rej) => { encoder.once('error', rej); encoder.once('close', code => code === 0 ? res() : rej(Error(`FFmpeg exited ${code}: ${encodingError}`))); });
|
|
81
115
|
// Attach immediately so an early encoder failure cannot become an unhandled rejection.
|
|
82
116
|
encoded.catch(() => {});
|
|
83
|
-
|
|
117
|
+
let captured = 0;
|
|
118
|
+
for (let i = 0; i < frames && !runner?.done; i++) {
|
|
84
119
|
if (cancelled) throw Error('Recording cancelled.');
|
|
85
120
|
if (encoder.exitCode !== null) throw Error(`FFmpeg stopped: ${encodingError}`);
|
|
86
121
|
await page.evaluate(ms => window.__recorderStep(ms), i * 1000 / fps);
|
|
122
|
+
const pose = runner && await runner.frame(i);
|
|
87
123
|
if (errors.length) throw Error(errors.join('\n'));
|
|
88
|
-
|
|
124
|
+
let { data } = await cdp.send('Page.captureScreenshot', { format: 'jpeg', quality: 96, fromSurface: true, clip: take?.clip ? { ...take.clip, scale: take.scale } : { x: 0, y: 0, width, height, scale: take?.scale ?? 1 } });
|
|
125
|
+
// Takes are composited: window, backdrop, camera, cursor and motion blur.
|
|
126
|
+
if (studio) data = await studio.render(data, pose);
|
|
127
|
+
captured = i + 1;
|
|
89
128
|
if (!encoder.stdin.write(Buffer.from(data, 'base64'))) await Promise.race([once(encoder.stdin, 'drain'), encoded.then(() => { throw Error('Encoder ended before all frames were written.'); })]);
|
|
90
|
-
if (i % 30 === 0
|
|
129
|
+
if (runner) { if (i % 30 === 0) process.stdout.write(`\r frame ${i}`); }
|
|
130
|
+
else if (i % 30 === 0 || i === frames - 1) process.stdout.write(`\r ${'━'.repeat(Math.floor((i + 1) / frames * 24)).padEnd(24, '─')} ${Math.round((i + 1) / frames * 100)}%`);
|
|
91
131
|
}
|
|
132
|
+
if (runner && !runner.done) throw Error(`Take still running after ${seconds}s. Raise --seconds.`);
|
|
92
133
|
encoder.stdin.end(); await encoded;
|
|
134
|
+
if (runner) {
|
|
135
|
+
for (const entry of runner.log) console.log(`\n f${String(entry.frame).padStart(4)} ${entry.step}${entry.observedFrame !== undefined ? ` (observer: f${entry.observedFrame})` : ''}`);
|
|
136
|
+
if (v.log) await writeFile(resolve(v.log), JSON.stringify({ take: resolve(v.take), fps, frames: captured, clip: take.clip ?? null, layout: studio.layout, steps: runner.log, track: runner.track }) + '\n');
|
|
137
|
+
}
|
|
93
138
|
await rename(partial, out); partial = undefined;
|
|
94
139
|
const elapsed = (performance.now() - start) / 1000;
|
|
95
|
-
console.log(`\n\n ✓ ${out}\n ${(
|
|
140
|
+
console.log(`\n\n ✓ ${out}\n ${(captured / elapsed).toFixed(1)} render fps · ${elapsed.toFixed(1)}s elapsed · ${(captured / fps).toFixed(2)}s video\n`);
|
|
96
141
|
} catch (e) { console.error(`\n ${e.message}`); process.exitCode = 1; }
|
|
97
142
|
finally {
|
|
98
143
|
encoder?.kill('SIGTERM'); await browser?.close().catch(() => {});
|