cuetake 0.3.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.
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Narration timing and Subtitles, shared by Node and the render page. Pure functions, no imports.
3
+ *
4
+ * A placed Line is `{ id, text, start, duration, words? }`: `start` is seconds of Source time,
5
+ * `duration` is measured from its audio, and each word is `{ text, start, end }` in seconds from the
6
+ * start of the Line's audio. Subtitle cues are `{ id, start, end, rows }`, `id` naming their Line.
7
+ */
8
+
9
+ const CJK = /[⺀-鿿豈-﫿＀-￯]/u;
10
+ const SENTENCE_END = /[.!?。!?…]["'”’))]*$/u;
11
+ const CLAUSE_END = /[,;:,、;:—–]["'”’))]*$/u;
12
+ // Closing punctuation never starts a row; it joins what it follows.
13
+ const CLOSING = /^[.,;:!?)\]}'"”’。,、;:!?)》」』…]/u;
14
+ /** The characters that are spoken, which word timings count: no spaces or punctuation. */
15
+ const spoken = text => Array.from(text.replace(/[\s\p{P}\p{S}]/gu, '')).length;
16
+ const length = text => Array.from(text).length;
17
+
18
+ /** Whether `text` (or a language tag such as zh-CN) is written without spaces between words. */
19
+ export const isCjk = (text, language) => /^(zh|ja|ko)\b/i.test(language ?? '') || CJK.test(text);
20
+
21
+ /**
22
+ * The text broken into atoms that rows never split: a CJK character or a run of other non-space
23
+ * characters, with any closing punctuation after it. `space` marks a space before the atom.
24
+ */
25
+ function atoms(text) {
26
+ const list = [];
27
+ for (const [piece] of text.trim().matchAll(/\s+|[⺀-鿿豈-﫿＀-￯]|[^\s⺀-鿿豈-﫿＀-￯]+/gu)) {
28
+ if (/^\s+$/u.test(piece)) { if (list.length) list.at(-1).spaceAfter = true; continue; }
29
+ const last = list.at(-1);
30
+ if (last && !last.spaceAfter && CLOSING.test(piece)) last.text += piece;
31
+ else list.push({ text: piece, space: Boolean(last?.spaceAfter) });
32
+ }
33
+ return list;
34
+ }
35
+ /** How good a break after `atom` is: sentence end, clause end, between words, inside CJK text. */
36
+ const breakScore = (atom, next) => SENTENCE_END.test(atom.text) ? 3 : CLAUSE_END.test(atom.text) ? 2 : next?.space ? 1 : 0.5;
37
+ const join = list => list.map((atom, i) => (i && atom.space ? ' ' : '') + atom.text).join('');
38
+
39
+ /**
40
+ * The text as subtitle rows of at most `maxChars` characters, broken at the best place: a sentence
41
+ * end after the first third of an even row, then a clause end after its first half, then the word
42
+ * boundary nearest an even width, so a Line one word too long does not leave that word alone on a
43
+ * row. A single word longer than a row gets a row of its own.
44
+ */
45
+ export function subtitleRows(text, maxChars) {
46
+ const total = length(text.trim()), even = Math.min(maxChars, Math.ceil(total / Math.ceil(total / maxChars)));
47
+ const least = { 3: even * 0.3, 2: even * 0.5 };
48
+ const rows = [];
49
+ let row = [];
50
+ for (const atom of atoms(text)) {
51
+ row.push(atom);
52
+ if (row.length < 2 || length(join(row)) <= maxChars) continue;
53
+ let cut = row.length - 1, best = -1, distance = Infinity;
54
+ for (let i = 0; i < row.length - 1; i++) {
55
+ const score = breakScore(row[i], row[i + 1]), prefix = length(join(row.slice(0, i + 1)));
56
+ if (prefix < (least[score] ?? 0)) continue;
57
+ if (score > best || (score === best && Math.abs(prefix - even) < distance)) { best = score; distance = Math.abs(prefix - even); cut = i + 1; }
58
+ }
59
+ rows.push(join(row.slice(0, cut)));
60
+ row = row.slice(cut);
61
+ }
62
+ if (row.length) rows.push(join(row));
63
+ return rows;
64
+ }
65
+
66
+ /**
67
+ * When a Line's spoken characters are said, in seconds from the start of its audio: `start(k)` when
68
+ * the `k`th begins and `end(k)` when the one before it ends. With word timings each character takes
69
+ * an equal share of its word, so a pause between words shows as a gap; without, of the whole Line.
70
+ */
71
+ function clock(line) {
72
+ const total = spoken(line.text);
73
+ if (!line.words?.length) { const at = k => line.duration * (total ? k / total : 0); return { start: at, end: at }; }
74
+ const spans = [];
75
+ let count = 0;
76
+ for (const word of line.words) { const n = Math.max(1, spoken(word.text)); spans.push({ from: count, n, ...word }); count += n; }
77
+ const at = (k, closing) => {
78
+ const position = total ? k * count / total : 0;
79
+ const span = spans.find(s => closing ? position <= s.from + s.n : position < s.from + s.n) ?? spans.at(-1);
80
+ return span.start + (span.end - span.start) * Math.min(1, Math.max(0, (position - span.from) / span.n));
81
+ };
82
+ return { start: k => at(k, false), end: k => at(k, true) };
83
+ }
84
+
85
+ /**
86
+ * Subtitle cues for placed Lines: each Line's rows, `maxRows` to a cue (a cue also ends after a
87
+ * sentence), shown while they are spoken. A cue shorter than `minDuration` takes time from the next
88
+ * cue of its Line, or from the silence after its Line, up to `end`, the end of the Final.
89
+ */
90
+ export function subtitleCues(lines, { language, maxChars, maxRows = 2, minDuration = 1, end = Infinity } = {}) {
91
+ const cues = [];
92
+ for (const line of [...lines].sort((a, b) => a.start - b.start)) {
93
+ const width = maxChars ?? (isCjk(line.text, language) ? 16 : 42), said = clock(line);
94
+ const groups = [];
95
+ for (const row of subtitleRows(line.text, width)) {
96
+ const last = groups.at(-1);
97
+ if (last && last.length < maxRows && !SENTENCE_END.test(last.at(-1))) last.push(row); else groups.push([row]);
98
+ }
99
+ let k = 0;
100
+ const own = groups.map(rows => {
101
+ const n = rows.reduce((sum, row) => sum + spoken(row), 0);
102
+ const cue = { id: line.id, start: line.start + said.start(k), end: line.start + (k + n >= spoken(line.text) ? line.duration : said.end(k + n)), rows };
103
+ k += n;
104
+ return cue;
105
+ });
106
+ cues.push(...own);
107
+ }
108
+ for (const [i, cue] of cues.entries()) {
109
+ if (cue.end - cue.start >= minDuration) continue;
110
+ const next = cues[i + 1], want = cue.start + minDuration;
111
+ if (next?.id === cue.id) cue.end = next.start = Math.min(want, Math.max(cue.end, (cue.start + next.end) / 2));
112
+ else cue.end = Math.min(want, next ? Math.max(cue.end, next.start) : Math.max(cue.end, end));
113
+ }
114
+ return cues;
115
+ }
116
+
117
+ /** Whether the Edit's `subtitles` item draws them into the Final; otherwise they go only to the subtitle files. */
118
+ export const burnsIn = subtitles => Boolean(subtitles) && subtitles.burn !== false;
119
+
120
+ /** The cues of placed Lines as the Edit's `subtitles` item lays them out, ending by `end`. */
121
+ export const cuesFor = (lines, language, subtitles, end) => subtitleCues(lines, { language, maxChars: subtitles?.maxChars, maxRows: subtitles?.maxRows, minDuration: subtitles?.minDuration, end });
122
+
123
+ /**
124
+ * What stops Lines from playing as placed: a Line overlapping the next one, starting before the
125
+ * Take, or running past the end of the Final (`end` seconds). Each problem names its Line.
126
+ */
127
+ export function lineProblems(lines, end) {
128
+ const sorted = [...lines].sort((a, b) => a.start - b.start), problems = [];
129
+ const seconds = s => `${s.toFixed(2)} s`;
130
+ for (const [i, line] of sorted.entries()) {
131
+ const next = sorted[i + 1], stops = line.start + line.duration;
132
+ if (line.start < 0) problems.push(`Line '${line.id}' starts ${seconds(-line.start)} before the Take`);
133
+ if (next && stops > next.start + 0.005) problems.push(`Line '${line.id}' overlaps '${next.id}' by ${seconds(stops - next.start)}`);
134
+ if (stops > end + 0.005) problems.push(`Line '${line.id}' runs ${seconds(stops - end)} past the end of the Final`);
135
+ }
136
+ return problems;
137
+ }
138
+
139
+ const stamp = (seconds, separator) => {
140
+ const ms = Math.max(0, Math.round(seconds * 1000)), pad = (n, w = 2) => String(n).padStart(w, '0');
141
+ return `${pad(Math.floor(ms / 3600000))}:${pad(Math.floor(ms / 60000) % 60)}:${pad(Math.floor(ms / 1000) % 60)}${separator}${pad(ms % 1000, 3)}`;
142
+ };
143
+ /** Cues as a SubRip (.srt) file. */
144
+ export const toSrt = cues => cues.map((cue, i) => `${i + 1}\n${stamp(cue.start, ',')} --> ${stamp(cue.end, ',')}\n${cue.rows.join('\n')}\n`).join('\n');
145
+ /** Cues as a WebVTT (.vtt) file. */
146
+ export const toVtt = cues => `WEBVTT\n\n${cues.map(cue => `${stamp(cue.start, '.')} --> ${stamp(cue.end, '.')}\n${cue.rows.join('\n')}\n`).join('\n')}`;
package/src/pipeline.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import fs from 'node:fs/promises';
2
- import { dirname, 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';
7
+ import { renderFinal, inspectFinal, composePreview, measureLines } from './render.js';
8
8
  import { outputSize, atShortSide } from './stage.js';
9
9
  import { resolveAuthProfile } from './auth.js';
10
10
  import { createDirector } from './director.js';
@@ -12,6 +12,7 @@ import { collectTimeline } from './probe.js';
12
12
  import { createEdit, evenSize, merge, withDefaults } from './edit.js';
13
13
  import { loadLook, resolvedLook, applyLook, lookFromEdit, saveLook, summarize } from './look.js';
14
14
  import { absolute, bundle, forRender } from './styles.js';
15
+ import { burnsIn, cuesFor, isCjk, lineProblems, toSrt, toVtt } from './narration.js';
15
16
  import pkg from '../package.json' with { type: 'json' };
16
17
 
17
18
  const SCHEMA_VERSION = 3;
@@ -21,9 +22,70 @@ export const scenarioSchema = z.object({
21
22
  url: z.string().url().refine(s => /^https?:/.test(s), 'Capture requires HTTP(S)'),
22
23
  viewport: z.object({ width: evenSize, height: evenSize }).default({ width: 1440, height: 900 }),
23
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({}),
25
+ director: z.object({ speed: z.number().positive().default(1), seed: z.number().int().default(1) }).strict().default({}),
24
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'),
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 = {}) {
@@ -42,7 +104,10 @@ export async function recordScenario(scenarioPath, outputDir, options = {}) {
42
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 };
43
105
  await writeJson(join(dir, 'project.json'), project);
44
106
  await fs.copyFile(resolve(scenarioPath), join(dir, 'scenario.mjs'));
107
+ let unplaced = [], unvoiced = [];
45
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;
46
111
  const session = await startRecording(config.url, {
47
112
  ...config.viewport, ...config.capture, outputDir: dir, deferCapture: true, storageState: authState, headed: options.headed,
48
113
  });
@@ -51,8 +116,8 @@ export async function recordScenario(scenarioPath, outputDir, options = {}) {
51
116
  await page.evaluate(() => document.fonts.ready);
52
117
  const capture = await beginCapture(session.sessionId);
53
118
  const startedAtMs = Date.parse(capture.startedAt);
54
- const focus = [], wide = [];
55
- 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);
56
121
  const evidence = await scenario.run(director);
57
122
  await page.screenshot({ path: join(dir, 'poster.png') });
58
123
  const observed = await collectTimeline(page, startedAtMs);
@@ -61,10 +126,13 @@ export async function recordScenario(scenarioPath, outputDir, options = {}) {
61
126
  await fs.rename(stopped.webmPath.replace(/\.webm$/, '-capture.json'), join(dir, 'capture.json'));
62
127
  const timeline = {
63
128
  schemaVersion: SCHEMA_VERSION, viewport: config.viewport, scale: config.capture.resolutionScale, duration: stopped.durationSeconds,
64
- 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),
65
130
  };
66
131
  await writeJson(join(dir, 'timeline.json'), timeline);
67
- await writeJson(join(dir, 'edit.json'), await intoTake(createEdit(config, timeline, focus, wide), dir));
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));
68
136
  project = { ...project, status: 'captured', duration: stopped.durationSeconds, evidence: evidence ?? null };
69
137
  await writeJson(join(dir, 'project.json'), project);
70
138
  } catch (error) {
@@ -73,7 +141,26 @@ export async function recordScenario(scenarioPath, outputDir, options = {}) {
73
141
  } finally { await cleanup(); }
74
142
  await renderTake(dir);
75
143
  const verification = await verifyTake(dir);
76
- 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>` } }) };
146
+ }
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}` };
77
164
  }
78
165
 
79
166
  /** The Edit with every file it names copied into the Take's styles/ folder, so the Take stands alone (ADR 0002). */
@@ -83,7 +170,25 @@ const intoTake = (edit, dir) => bundle(edit, dir, join(dir, 'styles'), 'styles/'
83
170
  async function loadTake(dir) {
84
171
  const project = await readJson(join(dir, 'project.json'));
85
172
  if (project.schemaVersion !== SCHEMA_VERSION) throw new Error(`${dir} was recorded by an older CueTake (schema ${project.schemaVersion ?? 1}); record it again`);
86
- return { project, config: scenarioSchema.parse(project.config), timeline: await readJson(join(dir, 'timeline.json')), edit: withDefaults(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 };
87
192
  }
88
193
 
89
194
  /**
@@ -92,13 +197,13 @@ async function loadTake(dir) {
92
197
  */
93
198
  export async function previewTake(directory, refs = [], { at } = {}) {
94
199
  const dir = resolve(directory);
95
- const { config, timeline, edit } = await loadTake(dir);
200
+ const { config, timeline, edit, narration } = await loadTake(dir);
96
201
  if (at !== undefined && !(at >= 0 && at <= timeline.duration)) throw new Error(`--at must be between 0 and ${timeline.duration} seconds`);
97
202
  const host = new URL(config.url).host;
98
203
  const looks = await Promise.all(refs.map(ref => loadLook(ref)));
99
204
  const tiles = [{ name: 'current', edit }, ...looks.map(look => ({ name: look.name, edit: applyLook(edit, resolvedLook(look), host) }))];
100
205
  const files = {}, shown = tiles.map(({ name, edit }) => ({ name, edit: forRender(atShortSide(edit, 1080), dir, files).edit }));
101
- const png = await composePreview({ sourcePath: join(dir, 'source.webm'), timeline, at, tiles: shown, files });
206
+ const png = await composePreview({ sourcePath: join(dir, 'source.webm'), timeline, at, tiles: shown, files, narration: narrationForRender(edit, narration, dir) });
102
207
  const preview = join(dir, 'preview.png');
103
208
  await fs.writeFile(preview, png);
104
209
  return { preview, at: at ?? 'end, camera wide', tiles: tiles.map(({ name, edit }) => ({ name, summary: summarize(lookFromEdit(edit)) })) };
@@ -120,14 +225,23 @@ export async function saveLookFromTake(name, directory, options) {
120
225
  return saveLook(name, lookFromEdit(edit), { ...options, from: dir });
121
226
  }
122
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
+ }
233
+ }
234
+
123
235
  export async function renderTake(directory) {
124
236
  const dir = resolve(directory);
125
- const { project, config, timeline, edit } = await loadTake(dir);
237
+ const { project, timeline, edit, narration } = await loadTake(dir);
238
+ const spoken = narrationForRender(edit, narration, dir);
126
239
  // Render to a temporary output; preserve the last complete final if encoding fails.
127
240
  const temporary = join(dir, 'final.pending.mp4');
128
241
  try {
129
- const render = await renderFinal({ sourcePath: join(dir, 'source.webm'), finalPath: temporary, timeline, ...forRender(edit, dir) });
242
+ const render = await renderFinal({ sourcePath: join(dir, 'source.webm'), finalPath: temporary, timeline, ...forRender(edit, dir), narration: spoken });
130
243
  await fs.rename(temporary, join(dir, 'final.mp4'));
244
+ await writeSubtitles(dir, render.subtitles?.map(({ frames, ...cue }) => cue) ?? null);
131
245
  await writeJson(join(dir, 'render.json'), render);
132
246
  await fs.rm(join(dir, 'verification.json'), { force: true });
133
247
  await writeJson(join(dir, 'project.json'), { ...project, status: 'rendered' });
@@ -135,6 +249,37 @@ export async function renderTake(directory) {
135
249
  return join(dir, 'final.mp4');
136
250
  }
137
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
+
138
283
  export function summarizeFrames(frames, duration) {
139
284
  const intervals = frames.slice(1).map((f, i) => f.timeMs - frames[i].timeMs);
140
285
  const sorted = intervals.toSorted((a, b) => a - b);
@@ -144,8 +289,9 @@ export function summarizeFrames(frames, duration) {
144
289
 
145
290
  export async function verifyTake(directory) {
146
291
  const dir = resolve(directory);
147
- const { project, config, timeline, edit } = await loadTake(dir);
148
- 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 ?? []);
149
295
  const { fps } = edit.output;
150
296
  const expected = { ...outputSize(edit), fps, frames: Math.round(project.duration * fps) };
151
297
  const problems = [
@@ -153,10 +299,15 @@ export async function verifyTake(directory) {
153
299
  Math.abs(media.fps - expected.fps) > 0.01 ? `${media.fps} fps, expected ${expected.fps}` : null,
154
300
  media.packets !== expected.frames ? `${media.packets} frames, expected ${expected.frames}` : null,
155
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) : []),
156
303
  ].filter(Boolean);
157
304
  if (problems.length) throw new Error(`Final failed verification: ${problems.join('; ')}`);
158
305
  const capture = await readJson(join(dir, 'capture.json'));
159
- 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
+ };
160
311
  await writeJson(join(dir, 'verification.json'), verification);
161
312
  await writeJson(join(dir, 'project.json'), { ...project, status: 'verified' });
162
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
  }