cuetake 0.4.0 → 0.6.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/src/render.js CHANGED
@@ -22,14 +22,24 @@ const pageFiles = {
22
22
  '/stage.js': { path: fileURLToPath(new URL('./stage.js', import.meta.url)), type: 'text/javascript' },
23
23
  '/narration.js': { path: fileURLToPath(new URL('./narration.js', import.meta.url)), type: 'text/javascript' },
24
24
  '/shortcuts.js': { path: fileURLToPath(new URL('./shortcuts.js', import.meta.url)), type: 'text/javascript' },
25
+ '/time-map.js': { path: fileURLToPath(new URL('./time-map.js', import.meta.url)), type: 'text/javascript' },
26
+ '/tabs.js': { path: fileURLToPath(new URL('./tabs.js', import.meta.url)), type: 'text/javascript' },
27
+ '/shutter.js': { path: fileURLToPath(new URL('./shutter.js', import.meta.url)), type: 'text/javascript' },
28
+ '/masks.js': { path: fileURLToPath(new URL('./masks.js', import.meta.url)), type: 'text/javascript' },
29
+ '/desktop.js': { path: fileURLToPath(new URL('./desktop.js', import.meta.url)), type: 'text/javascript' },
25
30
  '/mediabunny.js': { path: mediabunnyBundle, type: 'text/javascript' },
26
31
  };
27
32
 
28
- async function serveRange(route, path) {
33
+ // A range reader such as Mediabunny's UrlSource asks for `bytes=N-`; answering with the rest of a long
34
+ // Source or Final at once sends hundreds of MB through one Playwright message and takes the browser down.
35
+ const RANGE_CHUNK = 8 * 1024 * 1024;
36
+
37
+ /** Answers `route` from the file at `path`: a range with at most RANGE_CHUNK bytes, a plain request with the whole file. */
38
+ export async function serveRange(route, path) {
29
39
  const { size } = await fs.stat(path);
30
40
  const match = /bytes=(\d+)-(\d*)/.exec(route.request().headers().range ?? '');
31
41
  const start = match ? Number(match[1]) : 0;
32
- const end = match && match[2] ? Math.min(Number(match[2]), size - 1) : size - 1;
42
+ const end = match ? Math.min(match[2] ? Number(match[2]) : size - 1, start + RANGE_CHUNK - 1, size - 1) : size - 1;
33
43
  const handle = await fs.open(path);
34
44
  try {
35
45
  const body = Buffer.alloc(end - start + 1);
@@ -96,29 +106,43 @@ function servedLines(lines, files) {
96
106
  }
97
107
 
98
108
  /**
99
- * Composes the Final from a Source, Timeline and Edit; `files` serves the Edit's styling files (styles.js
100
- * forRender). `narration` ({ language, volume, lines }) adds its Lines' audio and Subtitles.
109
+ * The Timeline as the render page reads it, with each Tab's Source (`sources`, paths by Tab id) served
110
+ * from `files`. A Timeline without Tabs has one, the first, the viewport's size. A Take of Apps has
111
+ * `windows`, which show over its Desktop (desktop.js).
112
+ */
113
+ function forPage(timeline, sources, files) {
114
+ const tabs = timeline.tabs ?? [{ id: 0, opener: null, opened: 0, closed: null, viewport: timeline.viewport, start: 0 }];
115
+ for (const tab of tabs) files[`source-${tab.id}`] = sources[tab.id];
116
+ return {
117
+ duration: timeline.duration, viewport: timeline.viewport, tabs,
118
+ pointer: timeline.pointer ?? [], shapes: timeline.shapes ?? [], events: timeline.events ?? [], elements: timeline.elements ?? [], windows: timeline.windows ?? null,
119
+ sources: tabs.map(tab => ({ tab: tab.id, url: `${ORIGIN}/files/source-${tab.id}` })),
120
+ };
121
+ }
122
+
123
+ /**
124
+ * Composes the Final from each Tab's Source (`sources`, paths by Tab id), the Timeline and the Edit;
125
+ * `files` serves the Edit's styling files (styles.js forRender). `narration` ({ language, volume, lines })
126
+ * adds its Lines' audio and Subtitles.
101
127
  */
102
- export async function renderFinal({ sourcePath, finalPath, timeline, edit, files = {}, narration = null }) {
128
+ export async function renderFinal({ sources, finalPath, timeline, edit, files = {}, narration = null }) {
103
129
  const handle = await fs.open(finalPath, 'w');
104
- const served = { ...files, source: sourcePath };
130
+ const served = { ...files };
105
131
  const spoken = narration && { ...narration, lines: servedLines(narration.lines, served) };
132
+ const take = forPage(timeline, sources, served);
106
133
  try {
107
134
  return await withRenderPage({ files: served, writable: { final: handle } }, page => page.evaluate(options => window.cuetakeRender(options), {
108
- sourceUrl: `${ORIGIN}/files/source`, finalUrl: `${ORIGIN}/files/final`, duration: timeline.duration,
109
- viewport: timeline.viewport, pointer: timeline.pointer ?? [], shapes: timeline.shapes ?? [], events: timeline.events ?? [], edit, narration: spoken,
135
+ ...take, finalUrl: `${ORIGIN}/files/final`, edit, narration: spoken,
110
136
  }));
111
137
  } finally { await handle.close(); }
112
138
  }
113
139
 
114
140
  /** A Preview PNG of `tiles` ([{ name, edit }]) at `at` seconds, or at the end with the camera wide. No Final is touched. */
115
- export async function composePreview({ sourcePath, timeline, tiles, at, files = {}, narration = null }) {
116
- const served = { ...files, source: sourcePath };
141
+ export async function composePreview({ sources, timeline, tiles, at, files = {}, narration = null }) {
142
+ const served = { ...files };
117
143
  const spoken = narration && { ...narration, lines: servedLines(narration.lines, served) };
118
- const png = await withRenderPage({ files: served }, page => page.evaluate(options => window.cuetakePreview(options), {
119
- sourceUrl: `${ORIGIN}/files/source`, duration: timeline.duration, viewport: timeline.viewport,
120
- pointer: timeline.pointer ?? [], shapes: timeline.shapes ?? [], events: timeline.events ?? [], tiles, at: at ?? null, narration: spoken,
121
- }));
144
+ const take = forPage(timeline, sources, served);
145
+ const png = await withRenderPage({ files: served }, page => page.evaluate(options => window.cuetakePreview(options), { ...take, tiles, at: at ?? null, narration: spoken }));
122
146
  return Buffer.from(png, 'base64');
123
147
  }
124
148
 
package/src/shutter.js ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Motion blur, shared by Node and the render page. Pure functions, no imports.
3
+ *
4
+ * Each output frame of the Final is exposed over the last `shutter` of its time, a fraction of a frame
5
+ * like a film camera's shutter: Render composes the moving parts of the frame at several moments of
6
+ * that exposure and averages them. Times are Final seconds.
7
+ */
8
+
9
+ /** The shutter Render uses for the Edit's `output.shutter`: between 0 and 1, and 0 for anything that is not a number. */
10
+ export const shutterOf = shutter => typeof shutter === 'number' && shutter > 0 ? Math.min(1, shutter) : 0;
11
+
12
+ /**
13
+ * The exposure of the frame at Final time `t`, as { start, end }, or null where the frame shows one
14
+ * sharp instant: with no shutter, on the first frame, and on a frame the camera cuts on, since `cuts`
15
+ * jump the camera and the Tab shown.
16
+ */
17
+ export function exposure(t, fps, shutter, cuts = []) {
18
+ const frame = 1 / fps;
19
+ if (!shutterOf(shutter) || t < frame - 1e-9 || cuts.some(cut => cut > t - frame + 1e-9 && cut <= t + 1e-9)) return null;
20
+ return { start: t - shutterOf(shutter) * frame, end: t };
21
+ }
22
+
23
+ /** The camera's crop at Final time `t`, part way between the crops of the frames on either side (`crops` has one per frame). */
24
+ export function cropAt(crops, fps, t) {
25
+ const at = Math.max(0, Math.min(crops.length - 1, t * fps)), nearest = Math.round(at);
26
+ if (Math.abs(at - nearest) < 1e-6) return crops[nearest];
27
+ const low = Math.floor(at), a = crops[low], b = crops[low + 1], u = at - low;
28
+ return { x: a.x + (b.x - a.x) * u, y: a.y + (b.y - a.y) * u, w: a.w + (b.w - a.w) * u, h: a.h + (b.h - a.h) * u };
29
+ }
30
+
31
+ const MAX_MOMENTS = 16;
32
+
33
+ /**
34
+ * The moments a frame at `t` averages for content that moves `distance` output pixels on screen over
35
+ * its exposure `span`: evenly spaced, at most `step` pixels of movement apart, ending on `t` itself. A
36
+ * frame without an exposure, or whose content moves less than a step, shows the one moment `t`.
37
+ */
38
+ export function moments(t, span, distance, step) {
39
+ if (!span || !(distance >= step)) return [t];
40
+ const count = Math.min(MAX_MOMENTS, Math.ceil(distance / step) + 1);
41
+ return Array.from({ length: count }, (_, i) => i === count - 1 ? t : span.start + (span.end - span.start) * i / (count - 1));
42
+ }
@@ -12,7 +12,8 @@ export function draw(ctx, { width, height, url, params }) {
12
12
  ctx.beginPath(); ctx.arc(20 + i * 20, height / 2, 6, 0, 2 * Math.PI);
13
13
  ctx.fillStyle = light; ctx.fill(); ctx.strokeStyle = '#0000001f'; ctx.lineWidth = 0.5; ctx.stroke();
14
14
  });
15
- const w = 420, h = 28, x = (width - w) / 2, y = (height - h) / 2;
15
+ // The field narrows in a narrow window, such as a popup's, to stay clear of the lights.
16
+ const w = Math.min(420, width - 160), h = 28, x = (width - w) / 2, y = (height - h) / 2;
16
17
  ctx.beginPath(); ctx.roundRect(x, y, w, h, h / 2);
17
18
  ctx.fillStyle = t.field; ctx.fill(); ctx.strokeStyle = t.fieldLine; ctx.lineWidth = 0.8; ctx.stroke();
18
19
  ctx.font = '13px system-ui, -apple-system, sans-serif'; ctx.textBaseline = 'middle';
@@ -0,0 +1,22 @@
1
+ // Fast-forward badge: two arrowheads and the span's rate on a rounded band, centered in the Final.
2
+ // Parameters: fontSize, color, band (#rrggbbaa, '' for none), x and y (where its center sits, as fractions of the Final).
3
+ // Drawn in 1080p pixels over the whole Final, outside the camera, while it fast-forwards; `rate` is the span's rate.
4
+ export function draw(ctx, { width, height, rate, params, files }) {
5
+ const { fontSize: size = 44, color = '#ffffff', band = '#000000a6', x: across = 0.5, y: down = 0.5 } = params;
6
+ const family = files.font ? `"${files.font}"` : '-apple-system, "SF Pro Text", "Helvetica Neue", "DejaVu Sans", system-ui, sans-serif';
7
+ const label = `${+rate.toFixed(2)}×`;
8
+ ctx.font = `600 ${size}px ${family}`;
9
+ ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
10
+ const h = size * 1.8, padding = size * 0.6, arrow = size * 0.5, gap = size * 0.35;
11
+ const w = padding + 2 * arrow + gap + ctx.measureText(label).width + padding;
12
+ const x = width * across - w / 2, y = height * down - h / 2, middle = y + h / 2;
13
+ if (band) {
14
+ ctx.fillStyle = band;
15
+ ctx.beginPath(); ctx.roundRect(x, y, w, h, h / 2); ctx.fill();
16
+ }
17
+ ctx.fillStyle = color;
18
+ for (const left of [x + padding, x + padding + arrow]) {
19
+ ctx.beginPath(); ctx.moveTo(left, middle - arrow * 0.7); ctx.lineTo(left + arrow, middle); ctx.lineTo(left, middle + arrow * 0.7); ctx.closePath(); ctx.fill();
20
+ }
21
+ ctx.fillText(label, x + padding + 2 * arrow + gap, middle);
22
+ }
package/src/styles.js CHANGED
@@ -21,14 +21,15 @@ export const BUILTINS = {
21
21
  spark: { file: 'spark.js', params: { radius: 32, length: 16, count: 8 } },
22
22
  keycaps: { file: 'keycaps.js', params: { symbols: true, fontSize: 34, color: '#ffffff', cap: '#1f1f23e6', edge: '#ffffff40', right: 80, bottom: 80 } },
23
23
  subtitles: { file: 'subtitles.js', params: { fontSize: 40, weight: 600, color: '#ffffff', band: '#000000b3', bottom: 72, padding: 14 } },
24
+ 'fast-forward': { file: 'fast-forward.js', params: { fontSize: 44, color: '#ffffff', band: '#000000a6', x: 0.5, y: 0.5 } },
24
25
  };
25
26
  export const KINDS = ['shader', 'draw', 'image'];
26
27
  export const isFile = ref => typeof ref === 'string' && extname(ref) !== '';
27
28
 
28
29
  /** Every drawn item an Edit or (partial) Look holds. */
29
30
  function items(style) {
30
- const { frame, cursor, clickEffect, keycaps, subtitles } = style ?? {};
31
- return [...(Array.isArray(frame?.background) ? frame.background : []), ...(Array.isArray(frame?.effects) ? frame.effects : []), frame?.chrome, cursor, clickEffect, keycaps, subtitles]
31
+ const { frame, cursor, clickEffect, keycaps, subtitles, fastForwardBadge } = style ?? {};
32
+ return [...(Array.isArray(frame?.background) ? frame.background : []), ...(Array.isArray(frame?.effects) ? frame.effects : []), frame?.chrome, cursor, clickEffect, keycaps, subtitles, fastForwardBadge]
32
33
  .filter(item => item && typeof item === 'object');
33
34
  }
34
35
 
@@ -1,88 +1,236 @@
1
1
  import { writeFile } from 'node:fs/promises';
2
2
 
3
- // Capture Chromium's current tab at its device-pixel resolution. Unlike
4
- // Playwright recordVideo, this does not use the 25 fps / 1 Mbps VP8 encoder.
5
- // A full-document navigation ends this recorder; SPA navigation is supported.
6
- export async function startTabCapture(page, options) {
3
+ /** The title the demo page wears for an instant, so Chromium hands its tab to the recorder. */
4
+ const CAPTURE_TITLE = '__cuetake_capture__';
5
+ /** Chromium flags Capture needs: pick the tab with that title without asking. */
6
+ export const captureArgs = [`--auto-select-tab-capture-source-by-title=${CAPTURE_TITLE}`];
7
+ /** The recorder's page, answered by its own route so it is a secure context that loads nothing. */
8
+ const RECORDER_URL = 'https://recorder.cuetake.invalid/';
9
+
10
+ const captures = new WeakMap(), counting = new WeakSet();
11
+ let nextKey = 0;
12
+
13
+ /**
14
+ * Counts the page's animation frames in its top document, sending their times to Node a few times a
15
+ * second and as the document goes away. A still page sends few Source frames, but its animation frames
16
+ * keep the display rate while the browser keeps up, so a shortfall means the machine fell behind.
17
+ */
18
+ function countAnimationFrames() {
19
+ if (window !== window.top || window.__cuetakeAnimationFrames) return;
20
+ window.__cuetakeAnimationFrames = true;
21
+ let times = [];
22
+ const flush = () => { if (!times.length) return; const sent = times; times = []; try { window.__cuetakePaint?.(sent)?.catch?.(() => {}); } catch {} };
23
+ const animate = now => { times.push(performance.timeOrigin + now); requestAnimationFrame(animate); };
24
+ requestAnimationFrame(animate);
25
+ setInterval(flush, 250);
26
+ addEventListener('pagehide', flush);
27
+ }
28
+
29
+ /**
30
+ * Opens the page that records every Tab of a Take, in a window of its own beside `page`, the first Tab.
31
+ * Chromium on macOS starts a capture only from the page in front, and a recorder that were a tab of the
32
+ * Tabs' window would hide the tab it starts on, which then paints no first frame for a second or more; it
33
+ * would also give that window a tab strip, which leaves each tab less room than the viewport, and tab
34
+ * capture records only that room.
35
+ */
36
+ export async function openRecorder(page) {
37
+ const context = page.context(), own = await context.newCDPSession(page), browser = await context.browser().newBrowserCDPSession();
38
+ try {
39
+ const { targetInfo } = await own.send('Target.getTargetInfo');
40
+ const [recorder] = await Promise.all([context.waitForEvent('page'), browser.send('Target.createTarget', { url: 'about:blank', newWindow: true, browserContextId: targetInfo.browserContextId })]);
41
+ try {
42
+ await recorder.route(RECORDER_URL, route => route.fulfill({ contentType: 'text/html', body: '<!doctype html><title>CueTake recorder</title>' }));
43
+ await recorder.goto(RECORDER_URL);
44
+ return recorder;
45
+ } catch (error) { await recorder.close().catch(() => {}); throw error; }
46
+ } finally { await Promise.all([own.detach(), browser.detach()].map(detached => detached.catch(() => {}))); }
47
+ }
48
+
49
+ /**
50
+ * Notes each main-frame navigation of the page, from its request until the new document has loaded,
51
+ * with when the page took its new address (`commit`), for startTabCapture. A Tab is watched from the
52
+ * moment it opens, so a popup's first navigations are noted before its capture starts.
53
+ */
54
+ export function watchNavigations(page) {
55
+ const state = { paints: [], navigations: [] };
56
+ // A redirect, or a navigation started before the last one committed, continues it.
57
+ const onRequest = request => {
58
+ if (!request.isNavigationRequest() || request.frame() !== page.mainFrame()) return;
59
+ const last = state.navigations.at(-1);
60
+ if (last?.end === null && !last.commit) { last.url = request.url(); return; }
61
+ // One that starts after the last committed, such as a script's redirect while loading, is its own.
62
+ if (last?.end === null) last.end = Date.now();
63
+ state.navigations.push({ ms: Date.now(), url: request.url(), end: null });
64
+ };
65
+ // A navigation that fails or turns into a download never loads a document.
66
+ const onEnd = () => { const last = state.navigations.at(-1); if (last?.end === null) last.end = Date.now(); };
67
+ // The page takes its new address when the new document commits, after any redirect. A same-document
68
+ // navigation (pushState, a fragment) also reports here, but finds no navigation waiting for one.
69
+ const onCommit = frame => {
70
+ const last = state.navigations.at(-1);
71
+ if (frame !== page.mainFrame() || last?.end !== null || last.commit) return;
72
+ last.commit = Date.now();
73
+ last.url = frame.url();
74
+ };
75
+ const onFailed = request => { if (request.isNavigationRequest() && request.frame() === page.mainFrame()) onEnd(); };
76
+ page.on('request', onRequest);
77
+ page.on('load', onEnd);
78
+ page.on('requestfailed', onFailed);
79
+ page.on('download', onEnd);
80
+ page.on('framenavigated', onCommit);
81
+ state.detach = () => { page.off('request', onRequest); page.off('load', onEnd); page.off('requestfailed', onFailed); page.off('download', onEnd); page.off('framenavigated', onCommit); };
82
+ captures.set(page, state);
83
+ return state;
84
+ }
85
+
86
+ /**
87
+ * Captures the page's tab at its device-pixel resolution from `recorder` (openRecorder), so the Source
88
+ * keeps recording across full navigations and reloads of the page, whether the tab is in front or not,
89
+ * until it closes. One recorder records several tabs, one stream each. Unlike Playwright recordVideo,
90
+ * this does not use the 25 fps / 1 Mbps VP8 encoder. Its navigations are noted (watchNavigations).
91
+ * Returns the page's address when Capture started as `url`.
92
+ */
93
+ export async function startTabCapture(page, recorder, options) {
94
+ const state = captures.get(page) ?? watchNavigations(page);
95
+ // A page that captured before keeps its binding and init script; only the collection starts over.
96
+ if (!counting.has(page)) {
97
+ counting.add(page);
98
+ await page.exposeBinding('__cuetakePaint', (_, times) => { if (Array.isArray(times)) captures.get(page)?.paints.push(...times); });
99
+ await page.addInitScript(countAnimationFrames);
100
+ }
101
+ const key = String(nextKey++);
102
+ Object.assign(state, { recorder, key });
7
103
  let timeout;
8
104
  try {
9
- return await Promise.race([page.evaluate(async ({ fps, width, height, bitrate }) => {
10
- // The stage names the step a stalled start is waiting on.
11
- window.__cuetakeCaptureStage = 'getDisplayMedia';
12
- const stream = await navigator.mediaDevices.getDisplayMedia({
13
- video: { width: { ideal: width }, height: { ideal: height }, frameRate: { ideal: fps, max: fps } },
14
- audio: false,
15
- preferCurrentTab: true,
16
- });
105
+ await page.evaluate(countAnimationFrames);
17
106
  // Headless Chromium paints only on change, so a settled page sends no frame and play() never
18
107
  // resolves. A near-invisible pixel flickers until recording starts to force paints.
19
- const nudge = Object.assign(document.createElement('div'), { style: 'position:fixed;left:0;top:0;width:1px;height:1px;pointer-events:none;z-index:2147483647' });
20
- document.documentElement.append(nudge);
21
- let flip = false;
22
- const nudging = setInterval(() => { flip = !flip; nudge.style.background = flip ? 'rgba(0,0,0,0.004)' : 'rgba(0,0,0,0.002)'; }, 50);
23
- const stopNudging = () => { clearInterval(nudging); nudge.remove(); };
108
+ const named = await page.evaluate(title => {
109
+ const nudge = Object.assign(document.createElement('div'), { style: 'position:fixed;left:0;top:0;width:1px;height:1px;pointer-events:none;z-index:2147483647' });
110
+ document.documentElement.append(nudge);
111
+ let flip = false;
112
+ const nudging = setInterval(() => { flip = !flip; nudge.style.background = flip ? 'rgba(0,0,0,0.004)' : 'rgba(0,0,0,0.002)'; }, 50);
113
+ window.__cuetakeStopNudging = () => { clearInterval(nudging); nudge.remove(); delete window.__cuetakeStopNudging; };
114
+ const had = Boolean(document.querySelector('title')), old = document.title;
115
+ document.title = title;
116
+ return { had, old };
117
+ }, CAPTURE_TITLE);
118
+ const restore = () => page.evaluate(({ had, old }) => {
119
+ window.__cuetakeStopNudging?.();
120
+ if (had) document.title = old; else document.querySelector('title')?.remove();
121
+ }, named).catch(() => {});
24
122
  try {
25
- const track = stream.getVideoTracks()[0];
26
- window.__cuetakeCaptureStage = 'applyConstraints';
27
- await track.applyConstraints({ width, height, frameRate: fps });
28
- const video = document.createElement('video');
29
- video.srcObject = stream;
30
- video.muted = true;
31
- // Subscribe before play: a static tab may never produce a second frame.
32
- const firstFrame = new Promise(resolve => video.requestVideoFrameCallback(resolve));
33
- window.__cuetakeCaptureStage = 'play';
34
- await video.play();
35
- window.__cuetakeCaptureStage = 'first frame';
36
- await firstFrame;
37
- const mimeType = 'video/webm;codecs=vp9';
38
- if (!MediaRecorder.isTypeSupported(mimeType)) throw new Error('VP9 tab capture unavailable');
39
- const recorder = new MediaRecorder(stream, { mimeType, videoBitsPerSecond: bitrate });
40
- const state = { stream, video, recorder, chunks: [], frames: [], settings: track.getSettings(), error: null };
41
- window.__cuetakeCapture = state;
42
- const tick = (now, metadata) => {
43
- if (recorder.state !== 'recording') return;
44
- state.frames.push({ timeMs: performance.timeOrigin + now - state.startedAtMs, mediaTime: metadata.mediaTime, presentedFrames: metadata.presentedFrames });
45
- video.requestVideoFrameCallback(tick);
46
- };
47
- recorder.ondataavailable = event => { if (event.data.size) state.chunks.push(event.data); };
48
- recorder.onerror = event => { state.error = event.error?.message || 'MediaRecorder error'; };
49
- window.__cuetakeCaptureStage = 'MediaRecorder start';
50
- await new Promise(resolve => {
51
- recorder.onstart = () => { state.startedAtMs = Date.now(); stopNudging(); video.requestVideoFrameCallback(tick); resolve(); };
52
- recorder.start(1000);
53
- });
54
- return { startedAt: new Date(state.startedAtMs).toISOString(), settings: state.settings };
55
- } catch (error) {
56
- stopNudging();
57
- stream.getTracks().forEach(track => track.stop());
58
- throw error;
59
- }
60
- }, options), new Promise((_, reject) => {
61
- timeout = setTimeout(async () => {
62
- const stage = await page.evaluate(() => window.__cuetakeCaptureStage).catch(() => 'unknown');
63
- reject(new Error(`Tab capture did not start within 15 seconds (waiting on: ${stage})`));
64
- }, 15_000);
65
- })]);
66
- } finally { clearTimeout(timeout); }
123
+ // Chromium on macOS starts a capture only from the page in front; the tab comes back after.
124
+ await recorder.bringToFront();
125
+ return await Promise.race([recorder.evaluate(async ({ key, fps, width, height, bitrate }) => {
126
+ // The stage names the step a stalled start is waiting on.
127
+ window.__cuetakeCaptureStage = 'getDisplayMedia';
128
+ const stream = await navigator.mediaDevices.getDisplayMedia({
129
+ video: { width: { ideal: width }, height: { ideal: height }, frameRate: { ideal: fps, max: fps } },
130
+ audio: false,
131
+ selfBrowserSurface: 'exclude',
132
+ });
133
+ try {
134
+ const track = stream.getVideoTracks()[0];
135
+ window.__cuetakeCaptureStage = 'applyConstraints';
136
+ await track.applyConstraints({ width, height, frameRate: fps });
137
+ const video = document.createElement('video');
138
+ video.srcObject = stream;
139
+ video.muted = true;
140
+ // Subscribe before play: a static tab may never produce a second frame.
141
+ const firstFrame = new Promise(resolve => video.requestVideoFrameCallback(resolve));
142
+ window.__cuetakeCaptureStage = 'play';
143
+ await video.play();
144
+ window.__cuetakeCaptureStage = 'first frame';
145
+ await firstFrame;
146
+ const mimeType = 'video/webm;codecs=vp9';
147
+ if (!MediaRecorder.isTypeSupported(mimeType)) throw new Error('VP9 tab capture unavailable');
148
+ const recorder = new MediaRecorder(stream, { mimeType, videoBitsPerSecond: bitrate });
149
+ const state = { stream, video, recorder, chunks: [], frames: [], settings: track.getSettings(), error: null, endedAtMs: null };
150
+ (window.__cuetakeCaptures ??= {})[key] = state;
151
+ // A tab that closes ends its stream, and with it the recording.
152
+ state.stopped = new Promise(resolve => { recorder.onstop = resolve; });
153
+ track.addEventListener('ended', () => { state.endedAtMs ??= Date.now(); });
154
+ const tick = (now, metadata) => {
155
+ if (recorder.state !== 'recording') return;
156
+ state.frames.push({ timeMs: performance.timeOrigin + now - state.startedAtMs, mediaTime: metadata.mediaTime, presentedFrames: metadata.presentedFrames });
157
+ video.requestVideoFrameCallback(tick);
158
+ };
159
+ recorder.ondataavailable = event => { if (event.data.size) state.chunks.push(event.data); };
160
+ recorder.onerror = event => { state.error = event.error?.message || 'MediaRecorder error'; };
161
+ window.__cuetakeCaptureStage = 'MediaRecorder start';
162
+ await new Promise(resolve => {
163
+ recorder.onstart = () => { state.startedAtMs = Date.now(); video.requestVideoFrameCallback(tick); resolve(); };
164
+ recorder.start(1000);
165
+ });
166
+ return { startedAt: new Date(state.startedAtMs).toISOString(), settings: state.settings };
167
+ } catch (error) {
168
+ stream.getTracks().forEach(track => track.stop());
169
+ throw error;
170
+ }
171
+ }, { ...options, key }), new Promise((_, reject) => {
172
+ timeout = setTimeout(async () => {
173
+ const stage = await recorder.evaluate(() => window.__cuetakeCaptureStage).catch(() => 'unknown');
174
+ reject(new Error(`Tab capture did not start within 15 seconds (waiting on: ${stage})`));
175
+ }, 15_000);
176
+ })]).then(started => { state.startedAtMs = Date.parse(started.startedAt); return { ...started, url: page.url() }; });
177
+ } finally { clearTimeout(timeout); await page.bringToFront().catch(() => {}); await restore(); }
178
+ } catch (error) {
179
+ stopListening(page);
180
+ throw error;
181
+ }
182
+ }
183
+
184
+ function stopListening(page) {
185
+ const state = captures.get(page);
186
+ if (!state) return null;
187
+ captures.delete(page);
188
+ state.detach();
189
+ return state;
67
190
  }
68
191
 
192
+ /**
193
+ * Seconds since the tab's capture started of each animation frame's second, and of each navigation, from its
194
+ * request until its document loaded (or Capture stopped), with when it committed, if it did. A navigation
195
+ * noted before the capture started, such as a popup's first, has negative times.
196
+ */
197
+ export function captureSeconds({ paints, navigations, startedAtMs }, stoppedAtMs) {
198
+ const pageFrames = [];
199
+ for (const ms of paints) {
200
+ if (ms < startedAtMs || ms >= stoppedAtMs) continue;
201
+ const second = Math.floor((ms - startedAtMs) / 1000);
202
+ pageFrames[second] = (pageFrames[second] ?? 0) + 1;
203
+ }
204
+ const t = ms => Math.round(Math.min(ms, stoppedAtMs) - startedAtMs) / 1000;
205
+ return {
206
+ pageFrames: Array.from(pageFrames, n => n ?? 0),
207
+ navigations: navigations.filter(n => n.ms < stoppedAtMs).map(n => ({ t: t(n.ms), end: t(n.end ?? stoppedAtMs), url: n.url, ...(n.commit && n.commit < stoppedAtMs && { commit: t(n.commit) }) })),
208
+ };
209
+ }
210
+
211
+ /** Stops capturing the page's tab, or reads what it recorded until it closed, and writes the Source and its stats. */
69
212
  export async function stopTabCapture(page, outputPath) {
70
- const result = await page.evaluate(async () => {
71
- const state = window.__cuetakeCapture;
72
- if (!state) throw new Error('Tab recorder lost: full-document navigation is unsupported in hd-tab mode');
73
- const stoppedAtMs = Date.now();
74
- await new Promise(resolve => { state.recorder.onstop = resolve; state.recorder.stop(); });
75
- state.stream.getTracks().forEach(track => track.stop());
76
- state.video.srcObject = null;
77
- if (state.error) throw new Error(state.error);
78
- const bytes = new Uint8Array(await new Blob(state.chunks).arrayBuffer());
79
- let binary = '';
80
- for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
81
- const stats = { settings: state.settings, duration: (stoppedAtMs - state.startedAtMs) / 1000, frames: state.frames };
82
- delete window.__cuetakeCapture;
83
- return { data: btoa(binary), stats };
84
- });
85
- await writeFile(outputPath, Buffer.from(result.data, 'base64'));
86
- await writeFile(outputPath.replace(/\.webm$/, '-capture.json'), JSON.stringify(result.stats, null, 2));
87
- return result.stats;
213
+ const state = captures.get(page);
214
+ if (!state) throw new Error('This page is not being captured');
215
+ try {
216
+ // Animation frames the page counted before the stop arrive before its answer to an evaluate.
217
+ await page.evaluate(() => 0).catch(() => {});
218
+ const result = await state.recorder.evaluate(async key => {
219
+ const state = window.__cuetakeCaptures[key];
220
+ const stoppedAtMs = state.endedAtMs ?? Date.now();
221
+ if (state.recorder.state !== 'inactive') state.recorder.stop();
222
+ await state.stopped;
223
+ state.stream.getTracks().forEach(track => track.stop());
224
+ state.video.srcObject = null;
225
+ if (state.error) throw new Error(state.error);
226
+ const bytes = new Uint8Array(await new Blob(state.chunks).arrayBuffer());
227
+ let binary = '';
228
+ for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
229
+ delete window.__cuetakeCaptures[key];
230
+ return { data: btoa(binary), stoppedAtMs, stats: { settings: state.settings, duration: (stoppedAtMs - state.startedAtMs) / 1000, frames: state.frames } };
231
+ }, state.key);
232
+ const stats = { ...result.stats, ...captureSeconds(state, result.stoppedAtMs) };
233
+ await writeFile(outputPath, Buffer.from(result.data, 'base64'));
234
+ return stats;
235
+ } finally { stopListening(page); }
88
236
  }
package/src/tabs.js ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Tabs, shared by Node and the render page. Pure functions, no imports.
3
+ *
4
+ * A Take shows one Tab or more: the start page and each page the demo opened (ADR 0008). A Tab the
5
+ * size of the viewport is a tab of the same window; any other is a popup window over the Tab that
6
+ * opened it. Each Tab's input is in its own CSS pixels; the window's are those of the viewport, which
7
+ * the camera and the Cursor use.
8
+ *
9
+ * Tabs are the Timeline's `{ id, opener, opened, closed, viewport, start }`, times in Source seconds.
10
+ */
11
+
12
+ /** Whether a Tab is drawn as a popup window rather than as a tab of the window. */
13
+ export const isPopup = (tab, viewport) => tab.viewport.width !== viewport.width || tab.viewport.height !== viewport.height;
14
+
15
+ /**
16
+ * Where each Tab's CSS pixels sit in the window's, as `{ x, y, scale }` by Tab id. A popup's page is
17
+ * centered over its opener's page and scaled down to fit it, unless the Edit's `placement` ([{ tab, x,
18
+ * y }], in the opener's CSS pixels) names where; the popups it opened move with it.
19
+ */
20
+ export function windowMaps(tabs, viewport, placement = []) {
21
+ const byId = new Map(tabs.map(tab => [tab.id, tab])), maps = new Map();
22
+ const mapOf = (tab, depth = 0) => {
23
+ if (maps.has(tab.id)) return maps.get(tab.id);
24
+ let map = { x: 0, y: 0, scale: 1 };
25
+ const opener = byId.get(tab.opener);
26
+ if (isPopup(tab, viewport) && opener && depth < 32) {
27
+ const outer = mapOf(opener, depth + 1), room = opener.viewport, { width, height } = tab.viewport;
28
+ const scale = Math.min(1, room.width / width, room.height / height);
29
+ const placed = placement.find(p => p.tab === tab.id);
30
+ const x = placed?.x ?? (room.width - width * scale) / 2, y = placed?.y ?? (room.height - height * scale) / 2;
31
+ map = { x: outer.x + x * outer.scale, y: outer.y + y * outer.scale, scale: scale * outer.scale };
32
+ }
33
+ maps.set(tab.id, map);
34
+ return map;
35
+ };
36
+ for (const tab of tabs) mapOf(tab);
37
+ return maps;
38
+ }
39
+
40
+ /**
41
+ * What the Final shows of the Tabs through the Take. `at(t)` lists, at Final time `t`, what to draw in
42
+ * order, each as `{ tab, popup, opacity, scale }`: the tab the window shows (two while one fades into
43
+ * the next), then each popup window over it, opener first. The window shows the Tab in front, or, while
44
+ * a popup is in front, the tab beneath it; the popups between them show over it. `cuts` are the Final
45
+ * times the window starts showing another tab, where the camera cuts to wide.
46
+ *
47
+ * Tabs switch in Source time (the Timeline's `front` events; the first Tab is in front until one) and
48
+ * their transitions keep their pace in Final time: `style` is the Edit's `tabs`, whose `transition` is
49
+ * 'cut' or `{ fade }` seconds, and whose `popupAnimation` (`{ duration, scale }`, or false) scales and
50
+ * fades a popup window in as it comes to show and out as it goes.
51
+ */
52
+ export function tabTrack({ tabs, events = [], viewport }, style, map) {
53
+ const byId = new Map(tabs.map(tab => [tab.id, tab]));
54
+ const popup = id => byId.has(id) && isPopup(byId.get(id), viewport);
55
+ // The Tabs shown with `front` in front: the tab beneath it, then the popups up to it.
56
+ const stackOf = front => {
57
+ const chain = [front];
58
+ for (let id = front; popup(id) && byId.has(byId.get(id).opener) && chain.length < 32;) chain.unshift(id = byId.get(id).opener);
59
+ return chain;
60
+ };
61
+ const fronts = events.filter(event => event.type === 'front').toSorted((a, b) => a.t - b.t);
62
+ const states = [{ t: 0, stack: stackOf(tabs[0]?.id ?? 0) }, ...fronts.map(event => ({ t: map.outputAt(event.t), stack: stackOf(event.tab) }))];
63
+ // Each time the window shows another tab, with the one it showed before.
64
+ const switches = states.flatMap((state, i) => i && state.stack[0] !== states[i - 1].stack[0] ? [{ t: state.t, before: states[i - 1].stack[0] }] : []);
65
+ // Each popup's spans of the Final while it shows: [from, until), until Infinity while still showing.
66
+ const spans = new Map();
67
+ states.forEach((state, i) => {
68
+ const until = states[i + 1]?.t ?? Infinity;
69
+ for (const id of state.stack.slice(1)) {
70
+ const list = spans.get(id) ?? [], last = list.at(-1);
71
+ if (last && last.until === state.t) last.until = until; else list.push({ from: state.t, until });
72
+ spans.set(id, list);
73
+ }
74
+ });
75
+ const depth = id => stackOf(id).length;
76
+ const fade = typeof style?.transition === 'object' ? style.transition.fade ?? 0 : 0;
77
+ const animation = style?.popupAnimation || null, duration = animation?.duration ?? 0, smallest = animation?.scale ?? 1;
78
+ return {
79
+ cuts: switches.map(({ t }) => t),
80
+ at(t) {
81
+ const k = states.findLastIndex(state => state.t <= t), shown = [];
82
+ const switched = switches.findLast(({ t: at }) => at <= t);
83
+ if (fade > 0 && switched && t - switched.t < fade) {
84
+ shown.push({ tab: switched.before, popup: false, opacity: 1, scale: 1 }, { tab: states[k].stack[0], popup: false, opacity: (t - switched.t) / fade, scale: 1 });
85
+ } else shown.push({ tab: states[k].stack[0], popup: false, opacity: 1, scale: 1 });
86
+ const popups = [];
87
+ for (const [id, list] of spans) for (const { from, until } of list) {
88
+ const progress = duration > 0 ? Math.min(1, (t - from) / duration, (until + duration - t) / duration) : t < until ? 1 : 0;
89
+ if (t >= from && progress > 0) popups.push({ tab: id, popup: true, opacity: progress, scale: smallest + (1 - smallest) * progress, from });
90
+ }
91
+ popups.sort((a, b) => depth(a.tab) - depth(b.tab) || a.from - b.from);
92
+ return [...shown, ...popups.map(({ from, ...drawn }) => drawn)];
93
+ },
94
+ };
95
+ }
96
+
97
+ /**
98
+ * The Timeline's pointer path and events, and the camera's targets, moved from each Tab's CSS pixels
99
+ * to the window's by `maps` (windowMaps). A sample or item without a `tab` is the first Tab's.
100
+ */
101
+ export function inWindow({ pointer = [], events = [] }, targets = [], maps) {
102
+ const mapOf = tab => maps.get(tab ?? 0) ?? { x: 0, y: 0, scale: 1 };
103
+ const point = (m, p) => p && { ...p, x: m.x + p.x * m.scale, y: m.y + p.y * m.scale };
104
+ const box = (m, b) => b && { x: m.x + b.x * m.scale, y: m.y + b.y * m.scale, width: b.width * m.scale, height: b.height * m.scale };
105
+ const placed = item => {
106
+ const m = mapOf(item.tab), moved = { ...item };
107
+ if (typeof item.x === 'number') Object.assign(moved, point(m, { x: item.x, y: item.y }));
108
+ for (const key of ['from', 'to']) if (item[key]) moved[key] = point(m, item[key]);
109
+ if (item.box) moved.box = box(m, item.box);
110
+ return moved;
111
+ };
112
+ return {
113
+ pointer: pointer.map(([t, x, y, tab]) => { const m = mapOf(tab); return [t, m.x + x * m.scale, m.y + y * m.scale]; }),
114
+ events: events.map(placed),
115
+ targets: targets.map(placed),
116
+ };
117
+ }
118
+
119
+ /** A point in one Tab's CSS pixels as it sits in another's, through the window (`maps`: windowMaps). */
120
+ export function carried(point, from, to, maps) {
121
+ const a = maps.get(from), b = maps.get(to);
122
+ return { x: (a.x + point.x * a.scale - b.x) / b.scale, y: (a.y + point.y * a.scale - b.y) / b.scale };
123
+ }
124
+
125
+ /** Whether a Tab's page sees the pointer at `point`, which it does only over its viewport. */
126
+ export const seenBy = (point, viewport) => point.x >= 0 && point.y >= 0 && point.x < viewport.width && point.y < viewport.height;