cuetake 0.2.0 → 0.4.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
@@ -1,36 +1,99 @@
1
1
  import fs from 'node:fs/promises';
2
- import { join, resolve } from 'node:path';
2
+ import { dirname, extname, join, resolve } from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
4
  import { doctor } from './environment.js';
5
5
  import { z } from 'zod';
6
6
  import { startRecording, getRecordingPage, beginCapture, stopRecording, cleanup } from './recorder.js';
7
- import { renderFinal, inspectFinal, composePreview } from './render.js';
8
- import { outputSize } from './stage.js';
7
+ import { renderFinal, inspectFinal, composePreview, measureLines } from './render.js';
8
+ import { outputSize, atShortSide } from './stage.js';
9
9
  import { resolveAuthProfile } from './auth.js';
10
10
  import { createDirector } from './director.js';
11
11
  import { collectTimeline } from './probe.js';
12
- import { editFields, editSchema, createEdit, evenSize } from './edit.js';
13
- import { loadLook, mergeLook, applyLook, lookFromEdit, saveLook, summarize } from './look.js';
12
+ import { createEdit, evenSize, merge, withDefaults } from './edit.js';
13
+ import { loadLook, resolvedLook, applyLook, lookFromEdit, saveLook, summarize } from './look.js';
14
+ import { absolute, bundle, forRender } from './styles.js';
15
+ import { burnsIn, cuesFor, isCjk, lineProblems, toSrt, toVtt } from './narration.js';
14
16
  import pkg from '../package.json' with { type: 'json' };
15
17
 
16
- const SCHEMA_VERSION = 2;
17
- /** Scenario config: capture settings plus the defaults that seed each Take's Edit. */
18
+ const SCHEMA_VERSION = 3;
19
+ /** Scenario config: capture settings, validated, plus styling that seeds each Take's Edit, which is not (ADR 0005). */
18
20
  export const scenarioSchema = z.object({
19
21
  name: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
20
22
  url: z.string().url().refine(s => /^https?:/.test(s), 'Capture requires HTTP(S)'),
21
23
  viewport: z.object({ width: evenSize, height: evenSize }).default({ width: 1440, height: 900 }),
22
24
  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({}),
23
- ...editFields,
25
+ director: z.object({ speed: z.number().positive().default(1), seed: z.number().int().default(1) }).strict().default({}),
26
+ }).passthrough();
27
+ /**
28
+ * A Narration file: Lines in one language, each with its text, its audio (relative to the file) and
29
+ * optionally word timings from the speech tool and a start in seconds. Any duration it states is
30
+ * ignored: CueTake measures each Line from its audio.
31
+ */
32
+ export const narrationSchema = z.object({
33
+ language: z.string().min(2),
34
+ lines: z.array(z.object({
35
+ id: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/, 'Use a short Line id of letters, digits, dots, dashes and underscores'),
36
+ text: z.string().min(1),
37
+ audio: z.string().min(1),
38
+ start: z.number().min(0).optional(),
39
+ words: z.array(z.object({ text: z.string(), start: z.number().min(0), end: z.number().min(0) }).refine(word => word.end >= word.start, 'A word ends before it starts')).optional(),
40
+ })).min(1).refine(lines => new Set(lines.map(line => line.id)).size === lines.length, 'Line ids must be unique'),
24
41
  });
42
+ const SUBTITLE_FILES = [['subtitles.srt', toSrt], ['subtitles.vtt', toVtt]];
25
43
  const writeJson = (path, data) => fs.writeFile(path, JSON.stringify(data, null, 2) + '\n');
26
44
  const readJson = async path => JSON.parse(await fs.readFile(path, 'utf8'));
45
+ const readIfPresent = path => readJson(path).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
46
+
47
+ /**
48
+ * Copies a Narration file and its audio into the Take's narration/ folder, replacing any earlier one,
49
+ * and measures each Line. The audio is renamed after its Line.
50
+ */
51
+ async function intoTakeNarration(file, dir) {
52
+ const path = resolve(file), parsed = narrationSchema.safeParse(await readJson(path));
53
+ if (!parsed.success) throw new Error(`${path} is not a Narration file: ${parsed.error.issues.map(issue => `${issue.path.join('.') || 'file'}: ${issue.message}`).join('; ')}`);
54
+ // Read everything first: the file may already be the Take's own.
55
+ const lines = await Promise.all(parsed.data.lines.map(async line => {
56
+ const from = resolve(dirname(path), line.audio);
57
+ const bytes = await fs.readFile(from).catch(error => { throw error.code === 'ENOENT' ? new Error(`Line '${line.id}': no audio at ${from}`) : error; });
58
+ return { line: { ...line, audio: line.id + extname(from).toLowerCase() }, bytes };
59
+ }));
60
+ const folder = join(dir, 'narration');
61
+ await fs.rm(folder, { recursive: true, force: true });
62
+ await fs.mkdir(folder, { recursive: true });
63
+ for (const { line, bytes } of lines) await fs.writeFile(join(folder, line.audio), bytes);
64
+ const narration = { language: parsed.data.language, lines: lines.map(({ line }) => line) };
65
+ await writeJson(join(folder, 'narration.json'), narration);
66
+ return { narration, durations: await measureLines(narration.lines.map(line => ({ id: line.id, path: join(folder, line.audio) }))) };
67
+ }
68
+
69
+ /** The Edit with a Line added at its `start` for each Narration Line that has one and is not placed yet; also names the Lines left unplaced. */
70
+ function placeLines(edit, narration) {
71
+ const placed = new Set(edit.narration.lines.map(line => line.id));
72
+ const added = narration.lines.filter(line => !placed.has(line.id) && line.start !== undefined).map(line => ({ id: line.id, start: line.start }));
73
+ const lines = [...edit.narration.lines, ...added].sort((a, b) => a.start - b.start);
74
+ return { edit: { ...edit, narration: { ...edit.narration, lines } }, unplaced: narration.lines.filter(line => !placed.has(line.id) && line.start === undefined).map(line => line.id) };
75
+ }
76
+
77
+ /**
78
+ * The Edit's Lines joined with the Narration's text, audio and word timings, as Render takes them.
79
+ * A Line the Narration does not voice stops the Render.
80
+ */
81
+ function voicedLines(edit, narration, dir) {
82
+ const byId = new Map(narration.lines.map(line => [line.id, line]));
83
+ return edit.narration.lines.map(line => {
84
+ const voiced = byId.get(line.id);
85
+ if (!voiced) throw new Error(`Line '${line.id}' has no audio in the Take's Narration; import one with cuetake narrate import ${dir} <narration.json>`);
86
+ return { ...line, text: voiced.text, words: voiced.words, path: join(dir, 'narration', voiced.audio) };
87
+ });
88
+ }
27
89
 
28
90
  /** New take directories are exclusive: reruns never overwrite a previous take. */
29
91
  export async function recordScenario(scenarioPath, outputDir, options = {}) {
30
92
  const scenario = await import(pathToFileURL(resolve(scenarioPath)).href);
31
- // A Look sits under the Scenario: every field the config names wins over it.
93
+ // A Look sits under the Scenario: every field the config names wins over it. File refs resolve
94
+ // against the Look and the Scenario file, and the files are copied into the Take.
32
95
  const look = options.look ? await loadLook(options.look) : null;
33
- const config = scenarioSchema.parse(look ? mergeLook(look.look, scenario.config) : scenario.config);
96
+ const config = scenarioSchema.parse(merge(look ? resolvedLook(look) : {}, absolute(scenario.config, dirname(resolve(scenarioPath)))));
34
97
  if (typeof scenario.run !== 'function') throw new Error('Scenario must export run(director)');
35
98
  const authState = options.authProfile ? await resolveAuthProfile(options.authProfile) : undefined;
36
99
  const ready = await doctor();
@@ -41,7 +104,10 @@ export async function recordScenario(scenarioPath, outputDir, options = {}) {
41
104
  let project = { schemaVersion: SCHEMA_VERSION, tool: 'CueTake', version: pkg.version, createdAt: new Date().toISOString(), status: 'recording', authenticated: Boolean(authState), ...(look && { look: look.name }), config };
42
105
  await writeJson(join(dir, 'project.json'), project);
43
106
  await fs.copyFile(resolve(scenarioPath), join(dir, 'scenario.mjs'));
107
+ let unplaced = [], unvoiced = [];
44
108
  try {
109
+ // The Narration is voiced before Capture, so d.say can hold each Line for its audio (ADR 0006).
110
+ const imported = options.narration ? await intoTakeNarration(options.narration, dir) : null;
45
111
  const session = await startRecording(config.url, {
46
112
  ...config.viewport, ...config.capture, outputDir: dir, deferCapture: true, storageState: authState, headed: options.headed,
47
113
  });
@@ -50,8 +116,8 @@ export async function recordScenario(scenarioPath, outputDir, options = {}) {
50
116
  await page.evaluate(() => document.fonts.ready);
51
117
  const capture = await beginCapture(session.sessionId);
52
118
  const startedAtMs = Date.parse(capture.startedAt);
53
- const focus = [], wide = [];
54
- const director = createDirector(page, startedAtMs, config.capture.fps, focus, wide);
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);
55
121
  const evidence = await scenario.run(director);
56
122
  await page.screenshot({ path: join(dir, 'poster.png') });
57
123
  const observed = await collectTimeline(page, startedAtMs);
@@ -60,10 +126,13 @@ export async function recordScenario(scenarioPath, outputDir, options = {}) {
60
126
  await fs.rename(stopped.webmPath.replace(/\.webm$/, '-capture.json'), join(dir, 'capture.json'));
61
127
  const timeline = {
62
128
  schemaVersion: SCHEMA_VERSION, viewport: config.viewport, scale: config.capture.resolutionScale, duration: stopped.durationSeconds,
63
- pointer: observed.pointer, events: [...observed.events, ...focus.map(f => ({ type: 'focus', ...f }))].sort((a, b) => a.t - b.t),
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),
64
130
  };
65
131
  await writeJson(join(dir, 'timeline.json'), timeline);
66
- await writeJson(join(dir, 'edit.json'), createEdit(config, timeline, focus, wide));
132
+ let edit = createEdit(config, timeline, focus, wide);
133
+ if (imported) ({ edit, unplaced } = placeLines(edit, imported.narration));
134
+ else unvoiced = edit.narration.lines.map(line => line.id);
135
+ await writeJson(join(dir, 'edit.json'), await intoTake(edit, dir));
67
136
  project = { ...project, status: 'captured', duration: stopped.durationSeconds, evidence: evidence ?? null };
68
137
  await writeJson(join(dir, 'project.json'), project);
69
138
  } catch (error) {
@@ -72,29 +141,69 @@ export async function recordScenario(scenarioPath, outputDir, options = {}) {
72
141
  } finally { await cleanup(); }
73
142
  await renderTake(dir);
74
143
  const verification = await verifyTake(dir);
75
- return { directory: dir, final: join(dir, 'final.mp4'), verification };
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' } }),
145
+ ...(unvoiced.length && { unvoiced: { lines: unvoiced, note: `These Lines have no audio yet; voice them and run cuetake narrate import ${dir} <narration.json>` } }) };
76
146
  }
77
147
 
148
+ /**
149
+ * Imports a Narration into a recorded Take, replacing its earlier one. Lines keep their place in the
150
+ * Edit; a new Line is placed at its `start`, if the file gives one. Problems are reported here and
151
+ * stop the next Render.
152
+ */
153
+ export async function importNarration(directory, file) {
154
+ const dir = resolve(directory);
155
+ const { timeline, edit } = await loadTake(dir);
156
+ const { narration, durations } = await intoTakeNarration(file, dir);
157
+ const end = Math.round(timeline.duration * edit.output.fps) / edit.output.fps;
158
+ const { edit: next, unplaced } = placeLines(edit, narration);
159
+ await writeJson(join(dir, 'edit.json'), next);
160
+ const lines = next.narration.lines.filter(line => line.id in durations).map(line => ({ ...line, duration: durations[line.id] }));
161
+ 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`)];
163
+ return { narration: join(dir, 'narration', 'narration.json'), lines, unplaced, problems, next: `cuetake render ${dir}` };
164
+ }
165
+
166
+ /** The Edit with every file it names copied into the Take's styles/ folder, so the Take stands alone (ADR 0002). */
167
+ const intoTake = (edit, dir) => bundle(edit, dir, join(dir, 'styles'), 'styles/');
168
+
78
169
  /** Reads a Take's project.json, Timeline and Edit, refusing Takes from an older schema. */
79
170
  async function loadTake(dir) {
80
171
  const project = await readJson(join(dir, 'project.json'));
81
172
  if (project.schemaVersion !== SCHEMA_VERSION) throw new Error(`${dir} was recorded by an older CueTake (schema ${project.schemaVersion ?? 1}); record it again`);
82
- return { project, config: scenarioSchema.parse(project.config), timeline: await readJson(join(dir, 'timeline.json')), edit: editSchema.parse(await readJson(join(dir, 'edit.json'))) };
173
+ return {
174
+ project, config: scenarioSchema.parse(project.config), timeline: await readJson(join(dir, 'timeline.json')),
175
+ edit: withDefaults(await readJson(join(dir, 'edit.json'))), narration: await readIfPresent(join(dir, 'narration', 'narration.json')),
176
+ };
177
+ }
178
+
179
+ /**
180
+ * The Narration as Render takes it, or null for a Take without Lines or without a Narration yet (a
181
+ * draft whose Lines `d.say` placed before any audio existed). Burned-in Chinese, Japanese or Korean
182
+ * Subtitles drawn by the built-in need a font: macOS has PingFang SC; elsewhere the Edit or Look names one.
183
+ */
184
+ function narrationForRender(edit, narration, dir) {
185
+ if (!edit.narration.lines.length || !narration) return null;
186
+ const lines = voicedLines(edit, narration, dir), { subtitles } = edit;
187
+ const builtin = burnsIn(subtitles) && subtitles.draw === 'subtitles' && !subtitles.files?.font;
188
+ if (builtin && process.platform !== 'darwin' && lines.some(line => isCjk(line.text, narration.language))) {
189
+ throw new Error('Burned-in Subtitles in this language need a font outside macOS: add one to the Edit or Look as subtitles.files.font (a .woff2, .ttf or .otf file), or set subtitles.burn to false');
190
+ }
191
+ return { language: narration.language, volume: edit.narration.volume, lines };
83
192
  }
84
193
 
85
194
  /**
86
- * Writes preview.png: the Take's current Edit beside each Look (names or JSON files), composed at 1080p,
87
- * whose proportions match every output size. Without `at` it shows the last moment with the camera wide.
195
+ * 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.
88
197
  */
89
198
  export async function previewTake(directory, refs = [], { at } = {}) {
90
199
  const dir = resolve(directory);
91
- const { config, timeline, edit } = await loadTake(dir);
92
- if (refs.length > 5) throw new Error('Compare at most five Looks with the current Edit');
200
+ const { config, timeline, edit, narration } = await loadTake(dir);
93
201
  if (at !== undefined && !(at >= 0 && at <= timeline.duration)) throw new Error(`--at must be between 0 and ${timeline.duration} seconds`);
94
202
  const host = new URL(config.url).host;
95
203
  const looks = await Promise.all(refs.map(ref => loadLook(ref)));
96
- const tiles = [{ name: 'current', edit }, ...looks.map(({ name, look }) => ({ name, edit: applyLook(edit, look, host) }))];
97
- const png = await composePreview({ sourcePath: join(dir, 'source.webm'), timeline, at, tiles: tiles.map(({ name, edit }) => ({ name, edit: { ...edit, output: { ...edit.output, size: '1080p' } } })) });
204
+ const tiles = [{ name: 'current', edit }, ...looks.map(look => ({ name: look.name, edit: applyLook(edit, resolvedLook(look), host) }))];
205
+ 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) });
98
207
  const preview = join(dir, 'preview.png');
99
208
  await fs.writeFile(preview, png);
100
209
  return { preview, at: at ?? 'end, camera wide', tiles: tiles.map(({ name, edit }) => ({ name, summary: summarize(lookFromEdit(edit)) })) };
@@ -104,26 +213,35 @@ export async function previewTake(directory, refs = [], { at } = {}) {
104
213
  export async function applyLookToTake(ref, directory) {
105
214
  const dir = resolve(directory);
106
215
  const { config, edit } = await loadTake(dir);
107
- const { name, look } = await loadLook(ref);
108
- const next = applyLook(edit, look, new URL(config.url).host);
216
+ const look = await loadLook(ref);
217
+ const next = await intoTake(applyLook(edit, resolvedLook(look), new URL(config.url).host), dir);
109
218
  await writeJson(join(dir, 'edit.json'), next);
110
- return { look: name, edit: join(dir, 'edit.json'), summary: summarize(lookFromEdit(next)), next: `cuetake render ${dir}` };
219
+ return { look: look.name, edit: join(dir, 'edit.json'), summary: summarize(lookFromEdit(next)), next: `cuetake render ${dir}` };
111
220
  }
112
221
 
113
222
  /** Saves the Take's styling as a Look, locally unless `global`. */
114
223
  export async function saveLookFromTake(name, directory, options) {
115
- const { edit } = await loadTake(resolve(directory));
116
- return saveLook(name, lookFromEdit(edit), options);
224
+ const dir = resolve(directory), { edit } = await loadTake(dir);
225
+ return saveLook(name, lookFromEdit(edit), { ...options, from: dir });
226
+ }
227
+
228
+ /** Writes subtitles.srt and subtitles.vtt for the cues Render drew from, or removes them for a Take without Lines. */
229
+ async function writeSubtitles(dir, cues) {
230
+ for (const [name, format] of SUBTITLE_FILES) {
231
+ if (cues) await fs.writeFile(join(dir, name), format(cues)); else await fs.rm(join(dir, name), { force: true });
232
+ }
117
233
  }
118
234
 
119
235
  export async function renderTake(directory) {
120
236
  const dir = resolve(directory);
121
- const { project, config, timeline, edit } = await loadTake(dir);
237
+ const { project, timeline, edit, narration } = await loadTake(dir);
238
+ const spoken = narrationForRender(edit, narration, dir);
122
239
  // Render to a temporary output; preserve the last complete final if encoding fails.
123
240
  const temporary = join(dir, 'final.pending.mp4');
124
241
  try {
125
- const render = await renderFinal({ sourcePath: join(dir, 'source.webm'), finalPath: temporary, timeline, edit });
242
+ const render = await renderFinal({ sourcePath: join(dir, 'source.webm'), finalPath: temporary, timeline, ...forRender(edit, dir), narration: spoken });
126
243
  await fs.rename(temporary, join(dir, 'final.mp4'));
244
+ await writeSubtitles(dir, render.subtitles?.map(({ frames, ...cue }) => cue) ?? null);
127
245
  await writeJson(join(dir, 'render.json'), render);
128
246
  await fs.rm(join(dir, 'verification.json'), { force: true });
129
247
  await writeJson(join(dir, 'project.json'), { ...project, status: 'rendered' });
@@ -131,6 +249,37 @@ export async function renderTake(directory) {
131
249
  return join(dir, 'final.mp4');
132
250
  }
133
251
 
252
+ /**
253
+ * What stops the Final from playing the Narration as placed: a missing or undecodable audio track or
254
+ * Line, Lines that do not fit, subtitle files that do not match the Lines, and burned-in Subtitles
255
+ * Render did not draw for a Line.
256
+ */
257
+ async function narrationProblems(dir, edit, narration, media, end) {
258
+ const problems = [], fps = edit.output.fps;
259
+ if (!media.audio) return ['no audio track, though the Edit places Lines'];
260
+ if (media.audio.error) problems.push(`the audio track does not decode: ${media.audio.error}`);
261
+ if (Math.abs(media.audio.duration - media.duration) > 0.1) problems.push(`audio lasts ${media.audio.duration.toFixed(3)} s, video ${media.duration.toFixed(3)} s`);
262
+ const measured = new Map(media.lines.map(line => [line.id, line]));
263
+ for (const line of media.lines) if (line.error) problems.push(line.error);
264
+ 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));
267
+ if (problems.length) return problems;
268
+ const cues = cuesFor(lines, narration.language, edit.subtitles, end);
269
+ for (const [name, format] of SUBTITLE_FILES) {
270
+ const text = await fs.readFile(join(dir, name), 'utf8').catch(() => null);
271
+ if (text !== format(cues)) problems.push(`${name} ${text === null ? 'is missing' : 'does not match the Lines'}; render again`);
272
+ }
273
+ if (burnsIn(edit.subtitles)) {
274
+ const drawn = (await readIfPresent(join(dir, 'render.json')))?.subtitles ?? [];
275
+ for (const line of lines) {
276
+ const own = drawn.filter(cue => cue.id === line.id);
277
+ if (!own.length || own.some(cue => !cue.frames || cue.frames[0] > Math.ceil(cue.start * fps) + 1 || cue.frames[1] < Math.floor(cue.end * fps) - 2)) problems.push(`Subtitles for Line '${line.id}' were not drawn while it is spoken`);
278
+ }
279
+ }
280
+ return problems;
281
+ }
282
+
134
283
  export function summarizeFrames(frames, duration) {
135
284
  const intervals = frames.slice(1).map((f, i) => f.timeMs - frames[i].timeMs);
136
285
  const sorted = intervals.toSorted((a, b) => a - b);
@@ -140,19 +289,25 @@ export function summarizeFrames(frames, duration) {
140
289
 
141
290
  export async function verifyTake(directory) {
142
291
  const dir = resolve(directory);
143
- const { project, config, timeline, edit } = await loadTake(dir);
144
- const media = await inspectFinal(join(dir, 'final.mp4'));
292
+ const { project, edit, narration } = await loadTake(dir);
293
+ const spoken = narrationForRender(edit, narration, dir);
294
+ const media = await inspectFinal(join(dir, 'final.mp4'), spoken?.lines ?? []);
145
295
  const { fps } = edit.output;
146
- const expected = { ...outputSize(edit, timeline.viewport), fps, frames: Math.round(project.duration * fps) };
296
+ const expected = { ...outputSize(edit), fps, frames: Math.round(project.duration * fps) };
147
297
  const problems = [
148
298
  media.width !== expected.width || media.height !== expected.height ? `size ${media.width}×${media.height}, expected ${expected.width}×${expected.height}` : null,
149
299
  Math.abs(media.fps - expected.fps) > 0.01 ? `${media.fps} fps, expected ${expected.fps}` : null,
150
300
  media.packets !== expected.frames ? `${media.packets} frames, expected ${expected.frames}` : null,
151
301
  media.decodedFrames !== media.packets ? `only ${media.decodedFrames} of ${media.packets} frames decoded` : null,
302
+ ...(spoken ? await narrationProblems(dir, edit, spoken, media, expected.frames / fps) : []),
152
303
  ].filter(Boolean);
153
304
  if (problems.length) throw new Error(`Final failed verification: ${problems.join('; ')}`);
154
305
  const capture = await readJson(join(dir, 'capture.json'));
155
- const verification = { passed: true, checkedAt: new Date().toISOString(), media, source: { settings: capture.settings, ...summarizeFrames(capture.frames, capture.duration) }, fullDecode: 'passed' };
306
+ const { lines, ...final } = media;
307
+ const verification = {
308
+ passed: true, checkedAt: new Date().toISOString(), media: final, source: { settings: capture.settings, ...summarizeFrames(capture.frames, capture.duration) }, fullDecode: 'passed',
309
+ ...(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
+ };
156
311
  await writeJson(join(dir, 'verification.json'), verification);
157
312
  await writeJson(join(dir, 'project.json'), { ...project, status: 'verified' });
158
313
  return verification;
package/src/probe.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { shortcutKeys } from './shortcuts.js';
2
+
1
3
  /**
2
4
  * In-page Timeline probe. It records input exactly as the page receives it, so
3
5
  * director actions and raw Playwright input are captured alike. All positions
@@ -16,42 +18,98 @@ export async function installProbe(page) {
16
18
  const r = target?.getBoundingClientRect?.();
17
19
  return r ? { x: r.x, y: r.y, width: r.width, height: r.height } : null;
18
20
  };
19
- const state = { pointer: [], downs: [], ups: [], keys: [] };
20
- on('pointermove', e => state.pointer.push([at(e), e.clientX, e.clientY]));
21
+ const state = { pointer: [], downs: [], ups: [], keys: [], shapes: [] };
22
+ const BUTTONS = { 0: 'left', 2: 'right' };
23
+ // The tab capture never shows the pointer, so the page keeps its cursor and Render draws the shape it
24
+ // asks for, as the browser would show it: `auto` is text over editable fields and selectable text,
25
+ // otherwise default; an image cursor gives way to its fallback keyword.
26
+ const deepest = (x, y) => {
27
+ let element = document.elementFromPoint(x, y);
28
+ for (let inner; element?.shadowRoot && (inner = element.shadowRoot.elementFromPoint(x, y)) && inner !== element;) element = inner;
29
+ return element;
30
+ };
31
+ const editable = element => element.isContentEditable
32
+ || element.matches('textarea:not(:disabled), input:not(:disabled):not([type=button],[type=submit],[type=reset],[type=checkbox],[type=radio],[type=range],[type=color],[type=file],[type=image])');
33
+ const overText = (element, x, y) => {
34
+ const caret = document.caretPositionFromPoint?.(x, y), node = caret?.offsetNode;
35
+ const parent = node?.nodeType === Node.TEXT_NODE && node.data.trim() && element.contains(node) && node.parentElement;
36
+ if (!parent || parent.closest('button, select') || getComputedStyle(parent).userSelect === 'none') return false;
37
+ const range = document.createRange();
38
+ range.selectNodeContents(node);
39
+ return [...range.getClientRects()].some(r => x >= r.left && x <= r.right && y >= r.top && y <= r.bottom);
40
+ };
41
+ const shapeAt = (x, y) => {
42
+ const element = deepest(x, y);
43
+ if (!element) return 'default';
44
+ const keyword = getComputedStyle(element).cursor.match(/([a-z-]+)\s*$/)?.[1] ?? 'auto';
45
+ return keyword !== 'auto' ? keyword : editable(element) || overText(element, x, y) ? 'text' : 'default';
46
+ };
47
+ // Read after the page's own handlers have run, since they often set the cursor themselves.
48
+ let point = null, due = null;
49
+ const sampleShape = ms => {
50
+ if (!point || due !== null) return;
51
+ due = ms;
52
+ setTimeout(() => {
53
+ try {
54
+ const shape = shapeAt(point.x, point.y);
55
+ if (shape !== state.shapes.at(-1)?.[1]) state.shapes.push([due, shape]);
56
+ } finally { due = null; }
57
+ });
58
+ };
59
+ const moved = e => { point = { x: e.clientX, y: e.clientY }; sampleShape(at(e)); };
60
+ on('pointermove', e => { state.pointer.push([at(e), e.clientX, e.clientY]); moved(e); });
21
61
  on('pointerdown', e => {
22
- state.pointer.push([at(e), e.clientX, e.clientY]);
23
- if (e.button === 0) state.downs.push({ ms: at(e), x: e.clientX, y: e.clientY, box: box(e.target) });
62
+ state.pointer.push([at(e), e.clientX, e.clientY]); moved(e);
63
+ if (BUTTONS[e.button]) state.downs.push({ ms: at(e), button: BUTTONS[e.button], x: e.clientX, y: e.clientY, box: box(e.target) });
24
64
  });
25
- on('pointerup', e => { if (e.button === 0) state.ups.push({ ms: at(e), x: e.clientX, y: e.clientY }); });
26
- on('keydown', e => state.keys.push({ ms: at(e), box: box(document.activeElement) }));
27
- // The tab capture never shows the OS pointer; Render draws the cursor instead.
28
- const css = document.createElement('style');
29
- css.textContent = '* { cursor:none !important; }';
30
- document.documentElement.append(css);
31
- window.__cuetakeProbe = { state, dispose() { abort.abort(); css.remove(); } };
65
+ on('pointerup', e => { moved(e); if (BUTTONS[e.button]) state.ups.push({ ms: at(e), button: BUTTONS[e.button], x: e.clientX, y: e.clientY }); });
66
+ // Each key with what Node needs to tell typing from a Shortcut (shortcuts.js); only Shortcuts reach the Timeline.
67
+ const focused = () => { let element = document.activeElement; while (element?.shadowRoot?.activeElement) element = element.shadowRoot.activeElement; return element; };
68
+ on('keydown', e => {
69
+ const element = focused();
70
+ const { key, code, ctrlKey, altKey, shiftKey, metaKey, repeat } = e;
71
+ state.keys.push({ ms: at(e), box: box(element), key, code, ctrlKey, altKey, shiftKey, metaKey, repeat, field: Boolean(element && editable(element)) });
72
+ sampleShape(at(e));
73
+ });
74
+ on('keyup', e => sampleShape(at(e)));
75
+ on('scroll', e => sampleShape(at(e)));
76
+ window.__cuetakeProbe = { state, dispose() { abort.abort(); } };
32
77
  });
33
78
  }
34
79
 
35
80
  const CLICK_SLOP = 6; // CSS px a press may travel and still count as a click
36
81
 
37
- /** Rebases probe records to seconds since capture start and derives clicks, drags and typing. */
82
+ /**
83
+ * Rebases probe records to seconds since capture start and derives clicks and drags (from press to
84
+ * release; a right click is marked `button: 'right'`), typing, Shortcuts with their keys, and the
85
+ * cursor shapes: each change as [t, keyword], starting with the one shown when Capture began.
86
+ */
38
87
  export async function collectTimeline(page, startedAtMs) {
39
88
  const raw = await page.evaluate(() => window.__cuetakeProbe.state);
40
89
  const t = ms => Math.round(ms - startedAtMs) / 1000;
41
90
  const pointer = raw.pointer.filter(([ms]) => ms >= startedAtMs).map(([ms, x, y]) => [t(ms), x, y]);
42
91
  const events = [];
43
92
  for (const down of raw.downs.filter(d => d.ms >= startedAtMs)) {
44
- const up = raw.ups.find(u => u.ms >= down.ms);
45
- const moved = up && Math.hypot(up.x - down.x, up.y - down.y) > CLICK_SLOP;
93
+ const up = raw.ups.find(u => u.ms >= down.ms && u.button === down.button);
94
+ // Only the left button drags; a right click opens a context menu wherever it is released.
95
+ const moved = down.button === 'left' && up && Math.hypot(up.x - down.x, up.y - down.y) > CLICK_SLOP;
46
96
  events.push(moved
47
97
  ? { type: 'drag', t: t(down.ms), end: t(up.ms), from: { x: down.x, y: down.y }, to: { x: up.x, y: up.y } }
48
- : { type: 'click', t: t(down.ms), x: down.x, y: down.y, box: down.box });
98
+ : { type: 'click', t: t(down.ms), end: t(up?.ms ?? down.ms), x: down.x, y: down.y, box: down.box, ...(down.button === 'right' && { button: 'right' }) });
49
99
  }
50
100
  // Consecutive keys into the same field within a second form one typing burst.
51
- for (const key of raw.keys.filter(k => k.ms >= startedAtMs)) {
52
- const last = events.at(-1);
53
- if (last?.type === 'type' && t(key.ms) - last.end <= 1 && JSON.stringify(last.box) === JSON.stringify(key.box)) last.end = t(key.ms);
54
- else events.push({ type: 'type', t: t(key.ms), end: t(key.ms), box: key.box });
101
+ const keys = raw.keys.filter(k => k.ms >= startedAtMs), typing = [];
102
+ for (const key of keys) {
103
+ const last = typing.at(-1);
104
+ if (last && t(key.ms) - last.end <= 1 && JSON.stringify(last.box) === JSON.stringify(key.box)) last.end = t(key.ms);
105
+ else typing.push({ type: 'type', t: t(key.ms), end: t(key.ms), box: key.box });
106
+ }
107
+ events.push(...typing);
108
+ for (const key of keys) {
109
+ const shown = shortcutKeys(key);
110
+ if (shown) events.push({ type: 'shortcut', t: t(key.ms), keys: shown });
55
111
  }
56
- return { pointer, events: events.sort((a, b) => a.t - b.t) };
112
+ const before = raw.shapes.filter(([ms]) => ms < startedAtMs).at(-1);
113
+ const shapes = [...(before ? [[0, before[1]]] : []), ...raw.shapes.filter(([ms]) => ms >= startedAtMs).map(([ms, shape]) => [t(ms), shape])];
114
+ return { pointer, shapes, events: events.sort((a, b) => a.t - b.t) };
57
115
  }