cuetake 0.4.0 → 0.5.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/pipeline.js CHANGED
@@ -8,22 +8,35 @@ import { renderFinal, inspectFinal, composePreview, measureLines } from './rende
8
8
  import { outputSize, atShortSide } from './stage.js';
9
9
  import { resolveAuthProfile } from './auth.js';
10
10
  import { createDirector } from './director.js';
11
+ import { createAppDirector } from './app-director.js';
12
+ import { appLocators } from './app-locators.js';
13
+ import { startDesktop } from './app-capture.js';
14
+ import { desktopWarnings } from './desktop.js';
11
15
  import { collectTimeline } from './probe.js';
12
16
  import { createEdit, evenSize, merge, withDefaults } from './edit.js';
13
17
  import { loadLook, resolvedLook, applyLook, lookFromEdit, saveLook, summarize } from './look.js';
14
18
  import { absolute, bundle, forRender } from './styles.js';
15
19
  import { burnsIn, cuesFor, isCjk, lineProblems, toSrt, toVtt } from './narration.js';
20
+ import { linesInFinal, timeMap } from './time-map.js';
21
+ import { maskWarnings } from './masks.js';
16
22
  import pkg from '../package.json' with { type: 'json' };
17
23
 
18
- const SCHEMA_VERSION = 3;
19
- /** Scenario config: capture settings, validated, plus styling that seeds each Take's Edit, which is not (ADR 0005). */
24
+ const SCHEMA_VERSION = 5;
25
+ /**
26
+ * Scenario config: capture settings, validated, plus styling that seeds each Take's Edit, which is not
27
+ * (ADR 0005). A Scenario opens a start page (`url`) or starts Apps (`app`: one App, a `.app` path or
28
+ * bundle id with its arguments, or a list of them sharing one Desktop), never both (ADR 0009); for Apps,
29
+ * `viewport` is the Desktop's size in points.
30
+ */
31
+ const appSchema = z.object({ path: z.string().min(1), args: z.array(z.string()).default([]) }).strict();
20
32
  export const scenarioSchema = z.object({
21
33
  name: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
22
- url: z.string().url().refine(s => /^https?:/.test(s), 'Capture requires HTTP(S)'),
34
+ url: z.string().url().refine(s => /^https?:/.test(s), 'Capture requires HTTP(S)').optional(),
35
+ app: z.union([appSchema, z.array(appSchema).min(1)]).optional(),
23
36
  viewport: z.object({ width: evenSize, height: evenSize }).default({ width: 1440, height: 900 }),
24
37
  capture: z.object({ fps: z.union([z.literal(30), z.literal(60)]).default(60), resolutionScale: z.union([z.literal(1), z.literal(2)]).default(2) }).default({}),
25
38
  director: z.object({ speed: z.number().positive().default(1), seed: z.number().int().default(1) }).strict().default({}),
26
- }).passthrough();
39
+ }).passthrough().refine(config => !config.url !== !config.app, { message: 'A Scenario names exactly one of url or app', path: ['url'] });
27
40
  /**
28
41
  * A Narration file: Lines in one language, each with its text, its audio (relative to the file) and
29
42
  * optionally word timings from the speech tool and a start in seconds. Any duration it states is
@@ -87,61 +100,210 @@ function voicedLines(edit, narration, dir) {
87
100
  });
88
101
  }
89
102
 
103
+ /**
104
+ * The resolution scale Capture uses: the one the Scenario or Look chose, else 2, or 1 when doctor found
105
+ * Chromium drawing without a GPU, where scale 2 starves a busy page of frames.
106
+ */
107
+ export function captureScale(chosen, gpu) {
108
+ if (chosen !== undefined) return { resolutionScale: chosen, lowered: false };
109
+ return gpu?.accelerated === false ? { resolutionScale: 1, lowered: true } : { resolutionScale: 2, lowered: false };
110
+ }
111
+
112
+ /**
113
+ * The Timeline from `take` (its url, viewport and scale), what Capture observed in each Tab (`observed`,
114
+ * the probe's by Tab id), what the Director noted and what the recorder saw: every input and page load carries the Tab it happened in,
115
+ * in that Tab's CSS pixels, and `front` events note which Tab is in front from when. Each element a
116
+ * Scenario masked is in `elements`, with its boxes over time, and each mask is a `mask` event.
117
+ */
118
+ export function timelineOf(take, stopped, observed, notes, startedAtMs) {
119
+ const t = ms => Math.round(ms - startedAtMs) / 1000, inTab = (list, tab) => list.map(item => ({ ...item, tab }));
120
+ const pointer = [...[...observed].flatMap(([tab, seen]) => seen.pointer.map(sample => [...sample, tab])), ...notes.pointer.map(([ms, x, y, tab]) => [t(ms), x, y, tab])];
121
+ const shapes = [...observed.values()].flatMap(seen => seen.shapes).sort((a, b) => a[0] - b[0]);
122
+ const frameInput = { turned: [...observed.values()].flatMap(seen => seen.turned).sort((a, b) => a - b), unplaced: [...observed.values()].flatMap(seen => seen.unplaced).sort((a, b) => a - b) };
123
+ // Each element a mask follows, with the boxes the probe in its Tab saw it at.
124
+ const elements = (notes.elements ?? []).map(element => ({ ...element, boxes: observed.get(element.tab)?.watched?.find(watched => watched.id === element.id)?.boxes ?? [] }));
125
+ return {
126
+ schemaVersion: SCHEMA_VERSION, ...take, duration: stopped.durationSeconds,
127
+ tabs: stopped.tabs.map(({ id, opener, opened, closed, viewport, url, start }) => ({ id, opener, opened, closed, viewport, url, start })),
128
+ pointer: pointer.sort((a, b) => a[0] - b[0]), shapes, ...((frameInput.turned.length || frameInput.unplaced.length) && { frameInput }), ...(elements.length && { elements }),
129
+ events: [
130
+ ...[...observed].flatMap(([tab, seen]) => inTab(seen.events, tab)),
131
+ ...notes.focus.map(f => ({ type: 'focus', ...f })), ...notes.said.map(line => ({ type: 'say', ...line })), ...notes.forwarded.map(span => ({ type: 'fastForward', ...span })), ...(notes.masks ?? []).map(mask => ({ type: 'mask', ...mask })),
132
+ ...(notes.scrolls ?? []).map(span => ({ type: 'scroll', ...span })),
133
+ ...stopped.tabs.flatMap(tab => inTab(tab.navigations.map(load => ({ type: 'navigate', ...load })), tab.id)),
134
+ ...stopped.fronts.filter(front => front.t > 0).map(front => ({ type: 'front', ...front })),
135
+ ].sort((a, b) => a.t - b.t),
136
+ };
137
+ }
138
+
139
+ /** The Apps a Scenario starts, as a list: `config.app` names one or several. */
140
+ export const appsOf = config => [config.app].flat().filter(Boolean);
141
+
142
+ /**
143
+ * The Timeline of a Take of Apps (ADR 0009) from `take` (the Apps, the Desktop's size in points as the
144
+ * viewport, and its scale), what the helper saw (`stopped`: the duration, the Apps' windows over time,
145
+ * the system cursor's shapes, each element the App focused, as `focused` events the camera follows, and
146
+ * the frames of each masked element, `watched`) and what the Director noted: its pointer path and
147
+ * input, since the App shows none of its own, focus targets, Lines, fast-forwards and masks. Input the Director did not make never enters it. The Take has one
148
+ * Tab, its Desktop; positions are Desktop points.
149
+ */
150
+ export function desktopTimelineOf({ apps, viewport, scale }, stopped, notes) {
151
+ // Each element a mask follows, with the boxes the helper read it at.
152
+ const elements = (notes.elements ?? []).map(element => ({ ...element, boxes: stopped.watched?.find(watched => watched.id === element.id)?.boxes ?? [] }));
153
+ return {
154
+ schemaVersion: SCHEMA_VERSION, apps, viewport, scale, duration: stopped.duration,
155
+ tabs: [{ id: 0, opener: null, opened: 0, closed: null, viewport, start: 0 }],
156
+ pointer: notes.pointer.map(([t, x, y]) => [t, x, y, 0]), shapes: stopped.shapes ?? [], windows: stopped.windows, ...(elements.length && { elements }),
157
+ events: [
158
+ ...notes.focus.map(f => ({ type: 'focus', ...f })), ...notes.said.map(line => ({ type: 'say', ...line })), ...notes.forwarded.map(span => ({ type: 'fastForward', ...span })),
159
+ ...notes.events.map(event => ({ ...event, tab: 0 })), ...(stopped.focused ?? []).map(f => ({ type: 'focused', ...f, tab: 0 })),
160
+ ...(notes.masks ?? []).map(mask => ({ type: 'mask', ...mask })),
161
+ ].sort((a, b) => a.t - b.t),
162
+ };
163
+ }
164
+
165
+ /** The Source of each of a Take's Tabs, by Tab id. */
166
+ const sourcesOf = (dir, timeline) => Object.fromEntries(timeline.tabs.map(tab => [tab.id, join(dir, `source-${tab.id}.${timeline.windows ? 'mp4' : 'webm'}`)]));
167
+
168
+ /**
169
+ * Refuses what does not apply to an App: an Auth profile, since the App runs with the user's own login
170
+ * and data; and a resolution scale, since the Desktop takes its display's (ADR 0009).
171
+ */
172
+ function refuseForApp(given, options) {
173
+ if (options.authProfile) throw new Error('--auth-profile is for web pages: an App runs with the login and data it already has');
174
+ if (given.capture?.resolutionScale !== undefined) throw new Error('capture.resolutionScale does not apply to an App: the Desktop records at the scale of the display it sits on');
175
+ if (options.headed) throw new Error('--headed is for web pages: an App always shows on the screen');
176
+ }
177
+
178
+ /** Captures a start page: the Tabs' Sources, capture.json and poster.png in `dir`; returns the Timeline, the Director's notes and the evidence. */
179
+ async function capturePage(scenario, config, dir, { authState, headed, voiced }) {
180
+ try {
181
+ const session = await startRecording(config.url, {
182
+ ...config.viewport, ...config.capture, outputDir: dir, deferCapture: true, storageState: authState, headed,
183
+ });
184
+ const page = getRecordingPage(session.sessionId);
185
+ if (scenario.prepare) await scenario.prepare(page);
186
+ await page.evaluate(() => document.fonts.ready);
187
+ const capture = await beginCapture(session.sessionId);
188
+ const startedAtMs = Date.parse(capture.startedAt);
189
+ const notes = { focus: [], wide: [], said: [], forwarded: [], pointer: [], elements: [], masks: [] };
190
+ const ran = new AbortController();
191
+ const director = createDirector(capture.tabs, { startedAt: startedAtMs, fps: config.capture.fps, voiced, ...config.director, signal: ran.signal }, notes);
192
+ const evidence = await scenario.run(director).finally(() => ran.abort());
193
+ await capture.tabs.started();
194
+ await capture.tabs.front.page.screenshot({ path: join(dir, 'poster.png') });
195
+ const observed = new Map();
196
+ for (const tab of capture.tabs.list()) if (tab.recorded) observed.set(tab.id, await collectTimeline(tab.page, startedAtMs));
197
+ const stopped = await stopRecording(session.sessionId);
198
+ for (const tab of stopped.tabs) await fs.rename(tab.webmPath, join(dir, `source-${tab.id}.webm`));
199
+ await writeJson(join(dir, 'capture.json'), { tabs: stopped.tabs.map(tab => ({ tab: tab.id, ...tab.stats })) });
200
+ const timeline = timelineOf({ url: capture.url, viewport: config.viewport, scale: config.capture.resolutionScale }, stopped, observed, notes, startedAtMs);
201
+ return { timeline, notes, evidence };
202
+ } finally { await cleanup(); }
203
+ }
204
+
205
+ /**
206
+ * Captures a Desktop of the Apps (ADR 0009) through the helper: source-0.mp4, capture.json and
207
+ * poster.png in `dir`. The Desktop records at its display's scale, which `config.capture` then holds.
208
+ * `prepare(page, { app })` gets the first App's first window, and every App by `app(name)`, before
209
+ * Capture starts, to wait for what the demo needs and arrange the windows with `setFrame`.
210
+ * Returns the Timeline, the Director's notes, the evidence, and the Apps the helper could not quit.
211
+ */
212
+ async function captureApp(scenario, config, dir, { voiced, useRunning }) {
213
+ const { fps } = config.capture, given = appsOf(config);
214
+ process.stderr.write(`CueTake ${useRunning ? 'records' : 'starts'} ${given.map(app => app.path).join(', ')}${useRunning ? ', as the user runs it where it is running' : ` and records ${given.length > 1 ? 'them' : 'it'}`}. Leave the Mac alone until the Take ends: the Scenario moves the real pointer and acts on the real ${given.length > 1 ? 'Apps' : 'App'} and their data.\n`);
215
+ const desktop = await startDesktop({ apps: given, desktop: config.viewport, fps, source: join(dir, 'source-0.mp4'), poster: join(dir, 'poster.png'), useRunning });
216
+ try {
217
+ config.capture.resolutionScale = desktop.ready.scale;
218
+ const apps = given.map((app, i) => ({ ...app, name: desktop.ready.apps[i].name, bundle: desktop.ready.apps[i].bundle }));
219
+ if (scenario.prepare) {
220
+ const arranged = appLocators(desktop, apps, { arrange: true });
221
+ await scenario.prepare(arranged.page('first'), { app: arranged.app });
222
+ }
223
+ // The pointer starts at the Desktop's top-left corner, where the Director's starts.
224
+ await desktop.request({ move: { x: 0, y: 0 } });
225
+ const startedAtMs = await desktop.start();
226
+ const notes = { focus: [], wide: [], said: [], forwarded: [], pointer: [], events: [], elements: [], masks: [] };
227
+ const ran = new AbortController();
228
+ const director = createAppDirector({ startedAt: startedAtMs, fps, voiced, ...config.director, helper: desktop, apps, signal: ran.signal }, notes);
229
+ const evidence = await scenario.run(director).finally(() => ran.abort());
230
+ const stopped = await desktop.stop();
231
+ const { width, height } = stopped.size;
232
+ await writeJson(join(dir, 'capture.json'), { tabs: [{
233
+ tab: 0, settings: { width, height, frameRate: fps }, duration: stopped.duration, dropped: stopped.dropped, otherInput: stopped.otherInput ?? [],
234
+ frames: stopped.frames.map(([t, scale]) => ({ timeMs: Math.round(t * 1e6) / 1000, scale })),
235
+ }] });
236
+ const timeline = desktopTimelineOf({ apps, viewport: config.viewport, scale: desktop.ready.scale }, stopped, notes);
237
+ return { timeline, notes, evidence, unquit: stopped.unquit ?? [], running: desktop.ready.apps.filter(app => app.running).map(app => app.name) };
238
+ } finally { desktop.kill(); }
239
+ }
240
+
241
+ /**
242
+ * What `record` reports of the Apps after a Take, or null when there is nothing to report: those it
243
+ * started that did not quit (`unquit`), and those the user runs that it recorded as they were (`running`).
244
+ */
245
+ export function appReport({ unquit, running }) {
246
+ const notes = [];
247
+ if (unquit.length) notes.push(`${unquit.join(', ')} did not quit after the Take; ${unquit.length > 1 ? 'they' : 'it'} may be asking to save. Quit ${unquit.length > 1 ? 'them' : 'it'} before the next Take.`);
248
+ if (running.length) notes.push(`${running.join(', ')} ${running.length > 1 ? 'were' : 'was'} recorded as the user runs ${running.length > 1 ? 'them' : 'it'}: CueTake left ${running.length > 1 ? 'them' : 'it'} running and put ${running.length > 1 ? 'their' : 'its'} windows back.`);
249
+ if (!notes.length) return null;
250
+ return { ...(unquit.length && { quit: false, unquit }), ...(running.length && { running }), note: notes.join(' ') };
251
+ }
252
+
90
253
  /** New take directories are exclusive: reruns never overwrite a previous take. */
91
254
  export async function recordScenario(scenarioPath, outputDir, options = {}) {
92
255
  const scenario = await import(pathToFileURL(resolve(scenarioPath)).href);
93
256
  // A Look sits under the Scenario: every field the config names wins over it. File refs resolve
94
257
  // against the Look and the Scenario file, and the files are copied into the Take.
95
258
  const look = options.look ? await loadLook(options.look) : null;
96
- const config = scenarioSchema.parse(merge(look ? resolvedLook(look) : {}, absolute(scenario.config, dirname(resolve(scenarioPath)))));
259
+ const given = merge(look ? resolvedLook(look) : {}, absolute(scenario.config, dirname(resolve(scenarioPath))));
260
+ const config = scenarioSchema.parse(given);
97
261
  if (typeof scenario.run !== 'function') throw new Error('Scenario must export run(director)');
262
+ if (config.app) refuseForApp(given, options);
263
+ else if (options.useRunning) throw new Error('--use-running is for Apps: it records an App the user already runs, as it is');
264
+ // A relative .app path names an App beside the Scenario.
265
+ for (const app of appsOf(config)) if (app.path.includes('/')) app.path = resolve(dirname(resolve(scenarioPath)), app.path);
98
266
  const authState = options.authProfile ? await resolveAuthProfile(options.authProfile) : undefined;
99
267
  const ready = await doctor();
100
268
  if (!ready.ok) throw new Error(JSON.stringify(ready));
269
+ if (config.app && !ready.apps?.ok) {
270
+ const missing = ready.apps ? ready.checks.filter(check => !check.ok).map(check => `${check.name}: ${check.fix}`) : ['Recording an App needs macOS'];
271
+ throw new Error(`This Mac cannot record an App yet. ${missing.join(' ')} Nothing was requested; run cuetake doctor after the change.`);
272
+ }
273
+ const gpu = ready.checks.find(check => check.name === 'gpu');
274
+ const { resolutionScale, lowered } = config.app ? { resolutionScale: config.capture.resolutionScale, lowered: false } : captureScale(given.capture?.resolutionScale, gpu);
275
+ config.capture.resolutionScale = resolutionScale;
101
276
  const dir = resolve(outputDir || join('recordings', config.name, new Date().toISOString().replace(/[:.]/g, '-')));
102
277
  await fs.mkdir(resolve(dir, '..'), { recursive: true });
103
278
  await fs.mkdir(dir); // EEXIST is intentional, including for empty existing folders.
104
279
  let project = { schemaVersion: SCHEMA_VERSION, tool: 'CueTake', version: pkg.version, createdAt: new Date().toISOString(), status: 'recording', authenticated: Boolean(authState), ...(look && { look: look.name }), config };
105
280
  await writeJson(join(dir, 'project.json'), project);
106
281
  await fs.copyFile(resolve(scenarioPath), join(dir, 'scenario.mjs'));
107
- let unplaced = [], unvoiced = [];
282
+ let unplaced = [], unvoiced = [], captured;
108
283
  try {
109
284
  // The Narration is voiced before Capture, so d.say can hold each Line for its audio (ADR 0006).
110
285
  const imported = options.narration ? await intoTakeNarration(options.narration, dir) : null;
111
- const session = await startRecording(config.url, {
112
- ...config.viewport, ...config.capture, outputDir: dir, deferCapture: true, storageState: authState, headed: options.headed,
113
- });
114
- const page = getRecordingPage(session.sessionId);
115
- if (scenario.prepare) await scenario.prepare(page);
116
- await page.evaluate(() => document.fonts.ready);
117
- const capture = await beginCapture(session.sessionId);
118
- const startedAtMs = Date.parse(capture.startedAt);
119
- const focus = [], wide = [], said = [];
120
- const director = createDirector(page, startedAtMs, config.capture.fps, focus, wide, said, imported && new Map(Object.entries(imported.durations)), config.director);
121
- const evidence = await scenario.run(director);
122
- await page.screenshot({ path: join(dir, 'poster.png') });
123
- const observed = await collectTimeline(page, startedAtMs);
124
- const stopped = await stopRecording(session.sessionId);
125
- await fs.rename(stopped.webmPath, join(dir, 'source.webm'));
126
- await fs.rename(stopped.webmPath.replace(/\.webm$/, '-capture.json'), join(dir, 'capture.json'));
127
- const timeline = {
128
- schemaVersion: SCHEMA_VERSION, viewport: config.viewport, scale: config.capture.resolutionScale, duration: stopped.durationSeconds,
129
- pointer: observed.pointer, shapes: observed.shapes, events: [...observed.events, ...focus.map(f => ({ type: 'focus', ...f })), ...said.map(line => ({ type: 'say', ...line }))].sort((a, b) => a.t - b.t),
130
- };
286
+ const voiced = imported && new Map(Object.entries(imported.durations));
287
+ captured = config.app ? await captureApp(scenario, config, dir, { voiced, useRunning: options.useRunning }) : await capturePage(scenario, config, dir, { authState, headed: options.headed, voiced });
288
+ const { timeline, notes: { focus, wide }, evidence } = captured;
131
289
  await writeJson(join(dir, 'timeline.json'), timeline);
132
290
  let edit = createEdit(config, timeline, focus, wide);
133
291
  if (imported) ({ edit, unplaced } = placeLines(edit, imported.narration));
134
292
  else unvoiced = edit.narration.lines.map(line => line.id);
135
293
  await writeJson(join(dir, 'edit.json'), await intoTake(edit, dir));
136
- project = { ...project, status: 'captured', duration: stopped.durationSeconds, evidence: evidence ?? null };
294
+ project = { ...project, status: 'captured', duration: timeline.duration, evidence: evidence ?? null };
137
295
  await writeJson(join(dir, 'project.json'), project);
138
296
  } catch (error) {
139
297
  await writeJson(join(dir, 'project.json'), { ...project, status: 'failed', error: error.message });
140
298
  throw error;
141
- } finally { await cleanup(); }
299
+ }
142
300
  await renderTake(dir);
143
301
  const verification = await verifyTake(dir);
144
- return { directory: dir, final: join(dir, 'final.mp4'), verification, ...(unplaced.length && { unplaced: { lines: unplaced, note: 'These Lines were never said and have no start; add d.say or a start in edit.json' } }),
302
+ return { directory: dir, final: join(dir, 'final.mp4'), verification,
303
+ ...(lowered && { capture: { resolutionScale, note: `Chromium draws without a GPU here (${gpu.renderer}), so Capture used resolutionScale 1; set capture.resolutionScale to 2 in the Scenario to override` } }),
304
+ ...(config.app && { capture: { resolutionScale: config.capture.resolutionScale, note: 'The Desktop records at the scale of the display it sits on' } }),
305
+ ...(config.app && appReport(captured) && { app: appReport(captured) }),
306
+ ...(unplaced.length && { unplaced: { lines: unplaced, note: 'These Lines were never said and have no start; add d.say or a start in edit.json' } }),
145
307
  ...(unvoiced.length && { unvoiced: { lines: unvoiced, note: `These Lines have no audio yet; voice them and run cuetake narrate import ${dir} <narration.json>` } }) };
146
308
  }
147
309
 
@@ -154,12 +316,13 @@ export async function importNarration(directory, file) {
154
316
  const dir = resolve(directory);
155
317
  const { timeline, edit } = await loadTake(dir);
156
318
  const { narration, durations } = await intoTakeNarration(file, dir);
157
- const end = Math.round(timeline.duration * edit.output.fps) / edit.output.fps;
158
319
  const { edit: next, unplaced } = placeLines(edit, narration);
159
320
  await writeJson(join(dir, 'edit.json'), next);
160
321
  const lines = next.narration.lines.filter(line => line.id in durations).map(line => ({ ...line, duration: durations[line.id] }));
161
322
  const missing = next.narration.lines.filter(line => !(line.id in durations)).map(line => line.id);
162
- const problems = [...lineProblems(lines, end), ...missing.map(id => `Line '${id}' is placed in edit.json but the Narration has no audio for it`)];
323
+ const map = timeMap(next.fastForward, timeline.duration), end = Math.round(map.duration * next.output.fps) / next.output.fps;
324
+ const inFinal = linesInFinal(lines, map);
325
+ const problems = [...inFinal.problems, ...lineProblems(inFinal.lines, end), ...missing.map(id => `Line '${id}' is placed in edit.json but the Narration has no audio for it`)];
163
326
  return { narration: join(dir, 'narration', 'narration.json'), lines, unplaced, problems, next: `cuetake render ${dir}` };
164
327
  }
165
328
 
@@ -193,17 +356,19 @@ function narrationForRender(edit, narration, dir) {
193
356
 
194
357
  /**
195
358
  * Writes preview.png: the Take's current Edit beside each Look (names or JSON files), composed with a
196
- * 1080-pixel short side in each output's own proportions. Without `at` it shows the last moment with the camera wide.
359
+ * 1080-pixel short side in each output's own proportions. `at` is seconds of the Final; without it the
360
+ * Preview shows the last moment with the camera wide.
197
361
  */
198
362
  export async function previewTake(directory, refs = [], { at } = {}) {
199
363
  const dir = resolve(directory);
200
364
  const { config, timeline, edit, narration } = await loadTake(dir);
201
- if (at !== undefined && !(at >= 0 && at <= timeline.duration)) throw new Error(`--at must be between 0 and ${timeline.duration} seconds`);
202
- const host = new URL(config.url).host;
365
+ const length = timeMap(edit.fastForward, timeline.duration).duration;
366
+ if (at !== undefined && !(at >= 0 && at <= length)) throw new Error(`--at must be between 0 and ${+length.toFixed(3)} seconds of the Final`);
367
+ const host = config.url && new URL(config.url).host;
203
368
  const looks = await Promise.all(refs.map(ref => loadLook(ref)));
204
369
  const tiles = [{ name: 'current', edit }, ...looks.map(look => ({ name: look.name, edit: applyLook(edit, resolvedLook(look), host) }))];
205
370
  const files = {}, shown = tiles.map(({ name, edit }) => ({ name, edit: forRender(atShortSide(edit, 1080), dir, files).edit }));
206
- const png = await composePreview({ sourcePath: join(dir, 'source.webm'), timeline, at, tiles: shown, files, narration: narrationForRender(edit, narration, dir) });
371
+ const png = await composePreview({ sources: sourcesOf(dir, timeline), timeline, at, tiles: shown, files, narration: narrationForRender(edit, narration, dir) });
207
372
  const preview = join(dir, 'preview.png');
208
373
  await fs.writeFile(preview, png);
209
374
  return { preview, at: at ?? 'end, camera wide', tiles: tiles.map(({ name, edit }) => ({ name, summary: summarize(lookFromEdit(edit)) })) };
@@ -214,7 +379,7 @@ export async function applyLookToTake(ref, directory) {
214
379
  const dir = resolve(directory);
215
380
  const { config, edit } = await loadTake(dir);
216
381
  const look = await loadLook(ref);
217
- const next = await intoTake(applyLook(edit, resolvedLook(look), new URL(config.url).host), dir);
382
+ const next = await intoTake(applyLook(edit, resolvedLook(look), config.url && new URL(config.url).host), dir);
218
383
  await writeJson(join(dir, 'edit.json'), next);
219
384
  return { look: look.name, edit: join(dir, 'edit.json'), summary: summarize(lookFromEdit(next)), next: `cuetake render ${dir}` };
220
385
  }
@@ -239,7 +404,7 @@ export async function renderTake(directory) {
239
404
  // Render to a temporary output; preserve the last complete final if encoding fails.
240
405
  const temporary = join(dir, 'final.pending.mp4');
241
406
  try {
242
- const render = await renderFinal({ sourcePath: join(dir, 'source.webm'), finalPath: temporary, timeline, ...forRender(edit, dir), narration: spoken });
407
+ const render = await renderFinal({ sources: sourcesOf(dir, timeline), finalPath: temporary, timeline, ...forRender(edit, dir), narration: spoken });
243
408
  await fs.rename(temporary, join(dir, 'final.mp4'));
244
409
  await writeSubtitles(dir, render.subtitles?.map(({ frames, ...cue }) => cue) ?? null);
245
410
  await writeJson(join(dir, 'render.json'), render);
@@ -254,7 +419,7 @@ export async function renderTake(directory) {
254
419
  * Line, Lines that do not fit, subtitle files that do not match the Lines, and burned-in Subtitles
255
420
  * Render did not draw for a Line.
256
421
  */
257
- async function narrationProblems(dir, edit, narration, media, end) {
422
+ async function narrationProblems(dir, edit, narration, media, map, end) {
258
423
  const problems = [], fps = edit.output.fps;
259
424
  if (!media.audio) return ['no audio track, though the Edit places Lines'];
260
425
  if (media.audio.error) problems.push(`the audio track does not decode: ${media.audio.error}`);
@@ -262,8 +427,8 @@ async function narrationProblems(dir, edit, narration, media, end) {
262
427
  const measured = new Map(media.lines.map(line => [line.id, line]));
263
428
  for (const line of media.lines) if (line.error) problems.push(line.error);
264
429
  if (problems.length) return problems;
265
- const lines = narration.lines.map(line => ({ ...line, duration: measured.get(line.id).duration }));
266
- problems.push(...lineProblems(lines, end));
430
+ const inFinal = linesInFinal(narration.lines.map(line => ({ ...line, duration: measured.get(line.id).duration })), map), { lines } = inFinal;
431
+ problems.push(...inFinal.problems, ...lineProblems(lines, end));
267
432
  if (problems.length) return problems;
268
433
  const cues = cuesFor(lines, narration.language, edit.subtitles, end);
269
434
  for (const [name, format] of SUBTITLE_FILES) {
@@ -287,25 +452,64 @@ export function summarizeFrames(frames, duration) {
287
452
  return { callbacks: frames.length, medianIntervalMs: sorted[Math.floor(sorted.length / 2)] ?? null, maxIntervalMs: sorted.at(-1) ?? null, perSecond: seconds, note: 'Source capture is variable frame rate. Static sections reduce cadence; callback counts are observations, not a guarantee of unique encoded frames. Final output uses constant frame rate without motion interpolation.' };
288
453
  }
289
454
 
455
+ /** Animation frames per second below which the page in a Final visibly jumps. */
456
+ const SLOW_PAGE_FRAMES = 20;
457
+
458
+ /**
459
+ * Warns when the browser fell behind during Capture: the page got fewer than SLOW_PAGE_FRAMES animation
460
+ * frames in at least two whole seconds. The Source's own frames cannot tell, since a still page sends few.
461
+ * A second that a navigation or reload touches is left out, since no document draws while one loads.
462
+ * At resolution scale 1 the Take cannot be helped by lowering it again. `tab`, the Timeline's Tab,
463
+ * is named in a Take with several Tabs.
464
+ */
465
+ export function captureWarnings(capture, scale, tab = null) {
466
+ const loading = second => (capture.navigations ?? []).some(load => load.t < second + 1 && load.end >= second);
467
+ const whole = (capture.pageFrames ?? []).slice(0, Math.floor(capture.duration)).filter((_, second) => !loading(second));
468
+ const slow = whole.filter(n => n < SLOW_PAGE_FRAMES);
469
+ if (slow.length < 2) return [];
470
+ const fix = scale > 1
471
+ ? 'Record again with capture: { resolutionScale: 1 } in the Scenario, or close other work'
472
+ : 'Capture already used resolutionScale 1: close other work, use a smaller viewport, or record on a machine with a GPU';
473
+ const lead = tab ? `In Tab ${tab.id}, opened at ${tab.opened.toFixed(2)} s, the browser` : 'The browser';
474
+ return [`${lead} fell behind during Capture: the page got fewer than ${SLOW_PAGE_FRAMES} frames per second for ${slow.length} of ${whole.length} s (lowest ${Math.min(...slow)}), so the page in the Final jumps while the Cursor moves smoothly. ${fix}.`];
475
+ }
476
+
477
+ /**
478
+ * Warns when input landed inside an iframe Capture could not place exactly: one rotated, skewed or
479
+ * 3D-transformed, placed as if it were only scaled, or one it could not place at all, which the Cursor
480
+ * and camera do not follow.
481
+ */
482
+ export function timelineWarnings(timeline) {
483
+ const { turned = [], unplaced = [] } = timeline.frameInput ?? {};
484
+ const at = times => times.slice(0, 5).map(t => `${t.toFixed(2)} s`).join(', ') + (times.length > 5 ? ` and ${times.length - 5} more` : '');
485
+ return [
486
+ turned.length && `Input at ${at(turned)} landed inside an iframe that is rotated, skewed or 3D-transformed, which Capture places as if it were only scaled, so the Cursor and camera there may sit off what the page shows. Check those moments with frame, and record again once the iframe is upright, after any opening animation.`,
487
+ unplaced.length && `Input at ${at(unplaced)} landed inside an iframe Capture could not place, so the Cursor and camera do not follow it there. Check those moments with frame.`,
488
+ ].filter(Boolean);
489
+ }
490
+
290
491
  export async function verifyTake(directory) {
291
492
  const dir = resolve(directory);
292
- const { project, edit, narration } = await loadTake(dir);
493
+ const { project, config, timeline, edit, narration } = await loadTake(dir);
293
494
  const spoken = narrationForRender(edit, narration, dir);
294
495
  const media = await inspectFinal(join(dir, 'final.mp4'), spoken?.lines ?? []);
295
- const { fps } = edit.output;
296
- const expected = { ...outputSize(edit), fps, frames: Math.round(project.duration * fps) };
496
+ const { fps } = edit.output, map = timeMap(edit.fastForward, project.duration);
497
+ const expected = { ...outputSize(edit), fps, frames: Math.round(map.duration * fps) };
297
498
  const problems = [
298
499
  media.width !== expected.width || media.height !== expected.height ? `size ${media.width}×${media.height}, expected ${expected.width}×${expected.height}` : null,
299
500
  Math.abs(media.fps - expected.fps) > 0.01 ? `${media.fps} fps, expected ${expected.fps}` : null,
300
501
  media.packets !== expected.frames ? `${media.packets} frames, expected ${expected.frames}` : null,
301
502
  media.decodedFrames !== media.packets ? `only ${media.decodedFrames} of ${media.packets} frames decoded` : null,
302
- ...(spoken ? await narrationProblems(dir, edit, spoken, media, expected.frames / fps) : []),
503
+ ...(spoken ? await narrationProblems(dir, edit, spoken, media, map, expected.frames / fps) : []),
303
504
  ].filter(Boolean);
304
505
  if (problems.length) throw new Error(`Final failed verification: ${problems.join('; ')}`);
305
- const capture = await readJson(join(dir, 'capture.json'));
506
+ const capture = await readJson(join(dir, 'capture.json')), several = capture.tabs.length > 1;
507
+ const tabOf = id => timeline.tabs.find(tab => tab.id === id);
306
508
  const { lines, ...final } = media;
307
509
  const verification = {
308
- passed: true, checkedAt: new Date().toISOString(), media: final, source: { settings: capture.settings, ...summarizeFrames(capture.frames, capture.duration) }, fullDecode: 'passed',
510
+ passed: true, checkedAt: new Date().toISOString(), media: final,
511
+ warnings: [...capture.tabs.flatMap(stats => captureWarnings(stats, config.capture.resolutionScale, several ? tabOf(stats.tab) : null)), ...timelineWarnings(timeline), ...maskWarnings(edit.masks, timeline.elements), ...(timeline.windows ? desktopWarnings(timeline, capture.tabs[0]) : [])],
512
+ sources: capture.tabs.map(stats => ({ tab: stats.tab, settings: stats.settings, ...summarizeFrames(stats.frames, stats.duration), ...(stats.pageFrames && { pageFramesPerSecond: stats.pageFrames }) })), fullDecode: 'passed',
309
513
  ...(spoken && { narration: { lines: spoken.lines.map(({ id, start }) => ({ id, start, duration: lines.find(line => line.id === id).duration })), subtitles: SUBTITLE_FILES.map(([name]) => name), burned: burnsIn(edit.subtitles) } }),
310
514
  };
311
515
  await writeJson(join(dir, 'verification.json'), verification);