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/README.md +8 -6
- package/package.json +2 -2
- package/src/auth.js +8 -1
- package/src/cli.js +26 -8
- package/src/cursor.js +57 -30
- package/src/director.js +80 -25
- package/src/edit.js +55 -45
- package/src/environment.js +23 -7
- package/src/look.js +88 -60
- package/src/motion.js +66 -0
- package/src/narration.js +146 -0
- package/src/pipeline.js +188 -33
- package/src/probe.js +78 -20
- package/src/render-page.js +498 -207
- package/src/render.js +68 -17
- package/src/shortcuts.js +73 -0
- package/src/stage.js +28 -44
- package/src/styles/arrow.js +133 -0
- package/src/styles/browser.js +24 -0
- package/src/styles/dot.js +12 -0
- package/src/styles/fluted.glsl +35 -0
- package/src/styles/keycaps.js +38 -0
- package/src/styles/macos.js +12 -0
- package/src/styles/shadow.glsl +10 -0
- package/src/styles/spark.js +19 -0
- package/src/styles/subtitles.js +17 -0
- package/src/styles.js +108 -0
- package/src/uninstall.js +62 -0
package/src/look.js
CHANGED
|
@@ -1,46 +1,35 @@
|
|
|
1
1
|
import fs from 'node:fs/promises';
|
|
2
2
|
import { homedir } from 'node:os';
|
|
3
3
|
import { basename, dirname, join, resolve } from 'node:path';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { merge } from './edit.js';
|
|
5
|
+
import { absolute, bundle, codeRefs, fileRefs } from './styles.js';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* A Look is the part of an Edit that does not depend on one Take: everything except camera targets,
|
|
9
|
-
* the address bar's url
|
|
9
|
+
* the address bar's url, the frame rate, the Shortcuts and the Narration's Lines. A Look sets only what
|
|
10
|
+
* it names, and is not validated.
|
|
10
11
|
*/
|
|
11
|
-
export const
|
|
12
|
-
cursor: editFields.cursor.removeDefault().partial().strict(),
|
|
13
|
-
clickEffect: editFields.clickEffect.removeDefault().partial().strict(),
|
|
14
|
-
output: outputFields.partial().strict(),
|
|
15
|
-
frame: z.union([z.literal(false), frameFields.omit({ url: true }).partial().strict()]),
|
|
16
|
-
camera: editFields.camera.removeDefault().partial().strict(),
|
|
17
|
-
}).partial().strict();
|
|
18
|
-
|
|
19
|
-
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
20
|
-
/** `over` wins field by field: nested objects merge, anything else (including `frame: false`) replaces. */
|
|
21
|
-
export function mergeLook(base, over) {
|
|
22
|
-
const merged = { ...base };
|
|
23
|
-
for (const [key, value] of Object.entries(over ?? {})) merged[key] = isObject(value) && isObject(base?.[key]) ? mergeLook(base[key], value) : value;
|
|
24
|
-
return merged;
|
|
25
|
-
}
|
|
12
|
+
export const mergeLook = merge;
|
|
26
13
|
|
|
27
14
|
/** The Look an Edit carries. */
|
|
28
|
-
export function lookFromEdit(
|
|
29
|
-
const {
|
|
30
|
-
|
|
15
|
+
export function lookFromEdit(edit) {
|
|
16
|
+
const { schemaVersion, narration, shortcuts, output: { fps, ...output } = {}, frame, camera: { targets, ...camera } = {}, ...rest } = edit;
|
|
17
|
+
const { url, ...styling } = frame ?? {};
|
|
18
|
+
return { ...rest, output, frame: styling, camera };
|
|
31
19
|
}
|
|
32
20
|
|
|
33
|
-
/** The Edit with a Look adopted. Camera targets
|
|
21
|
+
/** The Edit with a Look adopted. Camera targets, the frame rate, the Shortcuts and the Lines stay; the address bar keeps its url, else shows `host`. */
|
|
34
22
|
export function applyLook(edit, look, host) {
|
|
35
|
-
const next =
|
|
36
|
-
|
|
37
|
-
return
|
|
23
|
+
const next = merge(edit, look);
|
|
24
|
+
next.frame = { ...next.frame, url: edit.frame?.url ?? host };
|
|
25
|
+
return next;
|
|
38
26
|
}
|
|
39
27
|
|
|
40
|
-
|
|
28
|
+
const label = item => item && typeof item === 'object' ? basename(String(item.shader ?? item.draw ?? item.image ?? '')) : item === false ? 'none' : null;
|
|
29
|
+
/** One line for listings, such as "browser-dark · fluted · 3840×2160". */
|
|
41
30
|
export function summarize(look) {
|
|
42
|
-
const { frame, output
|
|
43
|
-
const parts = frame
|
|
31
|
+
const { frame, output } = look;
|
|
32
|
+
const parts = [label(frame?.chrome), ...(Array.isArray(frame?.background) ? frame.background.map(label) : []), output?.width && output?.height ? `${output.width}×${output.height}` : null];
|
|
44
33
|
return parts.filter(Boolean).join(' · ') || Object.keys(look).join(', ') || 'empty';
|
|
45
34
|
}
|
|
46
35
|
|
|
@@ -49,59 +38,98 @@ const scopes = (cwd = process.cwd()) => ({
|
|
|
49
38
|
local: join(cwd, '.cuetake', 'looks'),
|
|
50
39
|
global: process.env.CUETAKE_LOOK_DIR || join(homedir(), '.local/share/cuetake/looks'),
|
|
51
40
|
});
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
41
|
+
const NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
42
|
+
function checkName(name) {
|
|
43
|
+
if (!NAME.test(name)) throw new Error('Use a short lowercase Look name, such as brand');
|
|
55
44
|
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
45
|
+
const readIfPresent = path => fs.readFile(path, 'utf8').catch(error => { if (['ENOENT', 'ENOTDIR'].includes(error.code)) return null; throw error; });
|
|
46
|
+
const parse = (text, path) => { try { return JSON.parse(text); } catch (error) { throw new Error(`${path} is not JSON: ${error.message}`); } };
|
|
47
|
+
|
|
48
|
+
/** A saved Look is `<name>.json`, or a `<name>/` folder holding `look.json` and the files it names. */
|
|
49
|
+
async function readSaved(dir, name) {
|
|
50
|
+
for (const path of [join(dir, `${name}.json`), join(dir, name, 'look.json')]) {
|
|
51
|
+
const text = await readIfPresent(path);
|
|
52
|
+
if (text !== null) return { path, dir: dirname(path), look: parse(text, path) };
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
60
55
|
}
|
|
61
|
-
const readIfPresent = path => fs.readFile(path, 'utf8').catch(error => { if (error.code === 'ENOENT') return null; throw error; });
|
|
62
56
|
|
|
63
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
* A Look by name, local before global, or from a JSON file labeled by its `name` or file name. `dir` is
|
|
59
|
+
* where its file refs resolve.
|
|
60
|
+
*/
|
|
64
61
|
export async function loadLook(ref, cwd = process.cwd()) {
|
|
65
62
|
if (ref.endsWith('.json')) {
|
|
66
63
|
const path = resolve(cwd, ref);
|
|
67
|
-
const { name = basename(ref, '.json'), ...look } =
|
|
68
|
-
return { name: String(name),
|
|
64
|
+
const { name = basename(ref, '.json'), ...look } = parse(await fs.readFile(path, 'utf8'), path);
|
|
65
|
+
return { name: String(name), dir: dirname(path), look };
|
|
69
66
|
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
67
|
+
checkName(ref);
|
|
68
|
+
for (const [scope, root] of Object.entries(scopes(cwd))) {
|
|
69
|
+
const saved = await readSaved(root, ref);
|
|
70
|
+
if (saved) return { name: ref, scope, dir: saved.dir, look: saved.look };
|
|
73
71
|
}
|
|
74
72
|
const { local, global } = scopes(cwd);
|
|
75
73
|
throw new Error(`No Look named '${ref}' in ${local} or ${global}`);
|
|
76
74
|
}
|
|
77
75
|
|
|
78
|
-
/**
|
|
76
|
+
/** A Look's styling with its file refs made absolute, ready to merge with styling from elsewhere. */
|
|
77
|
+
export const resolvedLook = ({ look, dir }) => absolute(look, dir);
|
|
78
|
+
|
|
79
|
+
/** Every saved Look, with the code files it runs; a global Look hidden by a local one with the same name is marked shadowed. */
|
|
79
80
|
export async function listLooks(cwd = process.cwd()) {
|
|
80
81
|
const found = [];
|
|
81
|
-
for (const [scope,
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
const
|
|
86
|
-
|
|
82
|
+
for (const [scope, root] of Object.entries(scopes(cwd))) {
|
|
83
|
+
const entries = await fs.readdir(root, { withFileTypes: true }).catch(error => { if (error.code === 'ENOENT') return []; throw error; });
|
|
84
|
+
const names = entries.flatMap(e => e.isDirectory() ? [e.name] : e.name.endsWith('.json') ? [basename(e.name, '.json')] : []).sort();
|
|
85
|
+
for (const name of new Set(names)) {
|
|
86
|
+
const saved = await readSaved(root, name).catch(error => ({ error }));
|
|
87
|
+
if (!saved) continue;
|
|
88
|
+
const entry = { name, scope, shadowed: scope === 'global' && found.some(l => l.scope === 'local' && l.name === name), path: saved.path ?? join(root, name) };
|
|
89
|
+
if (saved.error) found.push({ ...entry, summary: `invalid: ${saved.error.message}` });
|
|
90
|
+
else found.push({ ...entry, summary: summarize(saved.look), code: codeRefs(absolute(saved.look, saved.dir)) });
|
|
87
91
|
}
|
|
88
92
|
}
|
|
89
93
|
return found;
|
|
90
94
|
}
|
|
91
95
|
|
|
92
|
-
/**
|
|
93
|
-
|
|
94
|
-
|
|
96
|
+
/**
|
|
97
|
+
* Saves a Look locally unless `global`, with its file refs resolved against `from`. A Look that names
|
|
98
|
+
* files becomes a folder holding copies of them. An existing Look with the name is kept unless `replace`.
|
|
99
|
+
*/
|
|
100
|
+
export async function saveLook(name, look, { global = false, replace = false, cwd, from = cwd ?? process.cwd() } = {}) {
|
|
101
|
+
checkName(name);
|
|
102
|
+
const scope = global ? 'global' : 'local', root = scopes(cwd)[scope];
|
|
103
|
+
const existing = await readSaved(root, name);
|
|
104
|
+
if (existing && !replace) throw new Error(`A ${scope} Look named '${name}' already exists at ${existing.path}; pass --replace to overwrite it`);
|
|
105
|
+
await fs.rm(join(root, `${name}.json`), { force: true });
|
|
106
|
+
await fs.rm(join(root, name), { recursive: true, force: true });
|
|
107
|
+
const hasFiles = fileRefs(look).length > 0, dir = hasFiles ? join(root, name) : root;
|
|
108
|
+
const saved = hasFiles ? await bundle(look, from, dir) : look;
|
|
109
|
+
const path = hasFiles ? join(dir, 'look.json') : join(root, `${name}.json`);
|
|
95
110
|
await fs.mkdir(dirname(path), { recursive: true });
|
|
96
|
-
await fs.writeFile(path, JSON.stringify(
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
111
|
+
await fs.writeFile(path, JSON.stringify(saved, null, 2) + '\n');
|
|
112
|
+
return { name, scope, path, summary: summarize(saved), code: codeRefs(absolute(saved, dir)) };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The file or folder of every global Look; other files in the folder are not CueTake's. */
|
|
116
|
+
export async function globalLookFiles() {
|
|
117
|
+
const dir = scopes().global, paths = [];
|
|
118
|
+
const entries = await fs.readdir(dir, { withFileTypes: true }).catch(error => { if (error.code === 'ENOENT') return []; throw error; });
|
|
119
|
+
for (const entry of entries) {
|
|
120
|
+
const path = join(dir, entry.name);
|
|
121
|
+
if (entry.isFile() && entry.name.endsWith('.json') && NAME.test(basename(entry.name, '.json'))) paths.push(path);
|
|
122
|
+
else if (entry.isDirectory() && NAME.test(entry.name) && await readIfPresent(join(path, 'look.json')) !== null) paths.push(path);
|
|
123
|
+
}
|
|
124
|
+
return { dir, paths: paths.sort() };
|
|
101
125
|
}
|
|
102
126
|
|
|
103
127
|
export async function removeLook(name, { global = false, cwd } = {}) {
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
128
|
+
checkName(name);
|
|
129
|
+
const scope = global ? 'global' : 'local', root = scopes(cwd)[scope];
|
|
130
|
+
const saved = await readSaved(root, name);
|
|
131
|
+
if (!saved) throw new Error(`No ${scope} Look named '${name}' in ${root}`);
|
|
132
|
+
const removed = saved.path === join(root, `${name}.json`) ? saved.path : saved.dir;
|
|
133
|
+
await fs.rm(removed, { recursive: true, force: true });
|
|
134
|
+
return { name, scope, removed };
|
|
107
135
|
}
|
package/src/motion.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the Director's hand moves: durations from Fitts's law, a quick start and a long settle, a
|
|
3
|
+
* slight arc, pauses around presses and Shortcuts, a held click or key and uneven typing. Pure and
|
|
4
|
+
* seeded, so a Scenario moves the same way on every recording. CSS pixels and milliseconds throughout.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const REACH_MS = 250, REACH_MS_PER_BIT = 150; // Fitts's law: REACH_MS + REACH_MS_PER_BIT * log2(distance / size + 1)
|
|
8
|
+
const MAX_AVERAGE_SPEED = 1100; // CSS px/s; with the ease's 1.8× peak, a move at speed 1 stays under about 2000 px/s
|
|
9
|
+
const DRAG_SLOWDOWN = 1.5; // a held button makes people slower
|
|
10
|
+
const POINT_SIZE = 24; // target size for moves to a bare point
|
|
11
|
+
const BEND = 0.1, MAX_BEND = 80; // the arc's sideways offset, as a share of the distance and in CSS px
|
|
12
|
+
const LANDING = 0.15, MAX_LANDING = 8; // a click lands at most this share of its box's size, and CSS px, from the center
|
|
13
|
+
const PAUSES = { beforePress: 120, press: 100, afterRelease: 150, afterGrab: 100, beforeDrop: 100, beforeKey: 150, afterKey: 250 }; // press: how long a click or key is held
|
|
14
|
+
const PAUSE_JITTER = 0.25, TYPING_JITTER = 0.4, WORD_BREAK = 1.5;
|
|
15
|
+
|
|
16
|
+
/** A deterministic source of numbers in [0, 1) (mulberry32). */
|
|
17
|
+
export function random(seed) {
|
|
18
|
+
let a = seed >>> 0;
|
|
19
|
+
return () => {
|
|
20
|
+
a = (a + 0x6d2b79f5) >>> 0;
|
|
21
|
+
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
|
22
|
+
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
23
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** How long a person takes to move `distance` onto a target `size` across. */
|
|
28
|
+
export function reachMs(distance, size = POINT_SIZE, { speed = 1, drag = false } = {}) {
|
|
29
|
+
if (distance < 1) return 0;
|
|
30
|
+
const fitts = REACH_MS + REACH_MS_PER_BIT * Math.log2(distance / Math.max(1, size) + 1);
|
|
31
|
+
return Math.max(fitts, distance / MAX_AVERAGE_SPEED * 1000) * (drag ? DRAG_SLOWDOWN : 1) / speed;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Progress along a move at time share `t`: minimum-jerk, warped so it peaks early and settles long. */
|
|
35
|
+
const ease = t => { const u = t ** 0.75; return u * u * u * (10 - 15 * u + 6 * u * u); };
|
|
36
|
+
|
|
37
|
+
/** A move from `from` to `to`: its duration and its point at time share `t`, along a slight arc. */
|
|
38
|
+
export function reach(from, to, { size, duration, speed, drag, rand }) {
|
|
39
|
+
const dx = to.x - from.x, dy = to.y - from.y, distance = Math.hypot(dx, dy);
|
|
40
|
+
const bend = Math.min(distance * BEND, MAX_BEND) * (0.5 + rand() / 2) * (rand() < 0.5 ? -1 : 1);
|
|
41
|
+
const control = { x: from.x + dx / 2 - dy / (distance || 1) * bend, y: from.y + dy / 2 + dx / (distance || 1) * bend };
|
|
42
|
+
return {
|
|
43
|
+
duration: duration ?? reachMs(distance, size, { speed, drag }),
|
|
44
|
+
at(t) {
|
|
45
|
+
const k = ease(t), j = 1 - k;
|
|
46
|
+
return { x: j * j * from.x + 2 * j * k * control.x + k * k * to.x, y: j * j * from.y + 2 * j * k * control.y + k * k * to.y };
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Where a click lands: a little off the center of its box, never more than a few pixels. */
|
|
52
|
+
export function landing(box, rand) {
|
|
53
|
+
const off = size => (rand() * 2 - 1) * Math.min(LANDING * size, MAX_LANDING);
|
|
54
|
+
return { x: box.x + box.width / 2 + off(box.width), y: box.y + box.height / 2 + off(box.height) };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A named pause, a little uneven. */
|
|
58
|
+
export const pauseMs = (name, speed, rand) => PAUSES[name] * (1 + (rand() * 2 - 1) * PAUSE_JITTER) / speed;
|
|
59
|
+
|
|
60
|
+
/** The delay after each typed character: uneven, longer after a word, averaging `msPerChar`. */
|
|
61
|
+
export function typingDelays(text, msPerChar, rand) {
|
|
62
|
+
const chars = [...text];
|
|
63
|
+
const raw = chars.map(c => (1 + (rand() * 2 - 1) * TYPING_JITTER) * (/[\s.,;:!?,。;:!?]/.test(c) ? WORD_BREAK : 1));
|
|
64
|
+
const total = raw.reduce((sum, d) => sum + d, 0);
|
|
65
|
+
return raw.map(d => d / total * msPerChar * chars.length);
|
|
66
|
+
}
|
package/src/narration.js
ADDED
|
@@ -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')}`;
|