@biunow/agent-biutalk 0.0.0-stage → 1.1.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/bin/server.js +355 -0
- package/engine/AGENTS.md +1414 -0
- package/engine/CLAUDE.md +1 -0
- package/engine/LICENSE +21 -0
- package/engine/README.md +216 -0
- package/engine/bin/explainroo.js +19 -0
- package/engine/dev/audio-lab.mjs +268 -0
- package/engine/docs/media/contact-sheet.jpg +0 -0
- package/engine/docs/media/dns-poster.jpg +0 -0
- package/engine/docs/media/intro-poster.jpg +0 -0
- package/engine/docs/media/logo-dark.png +0 -0
- package/engine/docs/media/logo-light.png +0 -0
- package/engine/docs/media/looks-dark.webp +0 -0
- package/engine/docs/media/looks-light.webp +0 -0
- package/engine/docs/media/product-demo.webp +0 -0
- package/engine/docs/media/rebase-poster.jpg +0 -0
- package/engine/docs/media/sizes-dark.webp +0 -0
- package/engine/docs/media/sizes-light.webp +0 -0
- package/engine/engine/audio/dsp.js +69 -0
- package/engine/engine/audio/instruments.js +147 -0
- package/engine/engine/audio/music.js +576 -0
- package/engine/engine/audio/pcm.js +93 -0
- package/engine/engine/audio/rng.js +40 -0
- package/engine/engine/audio/sfx.js +287 -0
- package/engine/engine/audio/soundtrack.js +201 -0
- package/engine/engine/audio/synth.js +721 -0
- package/engine/engine/audio/theory.js +105 -0
- package/engine/engine/audio/wav.js +47 -0
- package/engine/engine/captions.js +131 -0
- package/engine/engine/clips.js +107 -0
- package/engine/engine/code.js +179 -0
- package/engine/engine/director.js +475 -0
- package/engine/engine/frame.html +135 -0
- package/engine/engine/icons/LICENSE-lucide.txt +43 -0
- package/engine/engine/icons/lucide-tags.json +1 -0
- package/engine/engine/icons/lucide.json +1 -0
- package/engine/engine/layout.js +69 -0
- package/engine/engine/pathdata.js +234 -0
- package/engine/engine/pen.js +240 -0
- package/engine/engine/player.html +67 -0
- package/engine/engine/player.js +219 -0
- package/engine/engine/readability.js +9 -0
- package/engine/engine/runtime.js +690 -0
- package/engine/engine/stage.js +2247 -0
- package/engine/engine/studio.html +216 -0
- package/engine/engine/text.js +81 -0
- package/engine/engine/themes.js +360 -0
- package/engine/engine/transitions.js +161 -0
- package/engine/engine/ui.js +1042 -0
- package/engine/engine/upload.js +32 -0
- package/engine/engine/util.js +204 -0
- package/engine/examples/callbacks-to-async-await/code-versions.js +34 -0
- package/engine/examples/callbacks-to-async-await/scenes.js +106 -0
- package/engine/examples/callbacks-to-async-await/script.md +22 -0
- package/engine/examples/callbacks-to-async-await/video.json +16 -0
- package/engine/examples/circle-area/scenes.js +228 -0
- package/engine/examples/circle-area/script.md +37 -0
- package/engine/examples/circle-area/video.json +14 -0
- package/engine/examples/explainroo-intro/scenes.js +133 -0
- package/engine/examples/explainroo-intro/script.md +27 -0
- package/engine/examples/explainroo-intro/video.json +8 -0
- package/engine/examples/how-dns-works/scenes.js +130 -0
- package/engine/examples/how-dns-works/script.md +28 -0
- package/engine/examples/how-dns-works/video.json +8 -0
- package/engine/examples/leap-years/scenes.js +156 -0
- package/engine/examples/leap-years/script.md +25 -0
- package/engine/examples/leap-years/video.json +16 -0
- package/engine/examples/leap-years-ja/scenes.js +194 -0
- package/engine/examples/leap-years-ja/script.md +32 -0
- package/engine/examples/leap-years-ja/video.json +17 -0
- package/engine/examples/merge-vs-rebase/scenes.js +129 -0
- package/engine/examples/merge-vs-rebase/script.md +22 -0
- package/engine/examples/merge-vs-rebase/video.json +8 -0
- package/engine/examples/password-storage-zh/scenes.js +185 -0
- package/engine/examples/password-storage-zh/script.md +25 -0
- package/engine/examples/password-storage-zh/video.json +19 -0
- package/engine/examples/sqlite-demo/README.md +19 -0
- package/engine/examples/sqlite-demo/scenes.js +423 -0
- package/engine/examples/sqlite-demo/script.md +35 -0
- package/engine/examples/sqlite-demo/video.json +17 -0
- package/engine/examples/unspar-demo/assets/fonts/Figtree-400.woff2 +0 -0
- package/engine/examples/unspar-demo/assets/fonts/Figtree-500.woff2 +0 -0
- package/engine/examples/unspar-demo/assets/fonts/Figtree-600.woff2 +0 -0
- package/engine/examples/unspar-demo/assets/fonts/Figtree-700.woff2 +0 -0
- package/engine/examples/unspar-demo/assets/fonts/Figtree-OFL.txt +93 -0
- package/engine/examples/unspar-demo/assets/unspar-logo.svg +23 -0
- package/engine/examples/unspar-demo/scenes.js +367 -0
- package/engine/examples/unspar-demo/script.md +25 -0
- package/engine/examples/unspar-demo/video.json +21 -0
- package/engine/examples/why-is-the-sky-blue-es/scenes.js +160 -0
- package/engine/examples/why-is-the-sky-blue-es/script.md +22 -0
- package/engine/examples/why-is-the-sky-blue-es/video.json +15 -0
- package/engine/fonts/ArchitectsDaughter-400-latin-ext.woff2 +0 -0
- package/engine/fonts/ArchitectsDaughter-400-latin.woff2 +0 -0
- package/engine/fonts/CabinSketch-400-latin.woff2 +0 -0
- package/engine/fonts/CabinSketch-700-latin.woff2 +0 -0
- package/engine/fonts/InstrumentSerif-400-italic-latin-ext.woff2 +0 -0
- package/engine/fonts/InstrumentSerif-400-italic-latin.woff2 +0 -0
- package/engine/fonts/InstrumentSerif-400-normal-latin-ext.woff2 +0 -0
- package/engine/fonts/InstrumentSerif-400-normal-latin.woff2 +0 -0
- package/engine/fonts/Inter-400-latin-ext.woff2 +0 -0
- package/engine/fonts/Inter-400-latin.woff2 +0 -0
- package/engine/fonts/JetBrainsMono-400-latin-ext.woff2 +0 -0
- package/engine/fonts/JetBrainsMono-400-latin.woff2 +0 -0
- package/engine/fonts/Kalam-400-latin-ext.woff2 +0 -0
- package/engine/fonts/Kalam-400-latin.woff2 +0 -0
- package/engine/fonts/Kalam-700-latin-ext.woff2 +0 -0
- package/engine/fonts/Kalam-700-latin.woff2 +0 -0
- package/engine/fonts/NotoSansDevanagari-400.ttf +0 -0
- package/engine/fonts/NotoSansDevanagari-700.ttf +0 -0
- package/engine/fonts/PatrickHand-400-latin-ext.woff2 +0 -0
- package/engine/fonts/PatrickHand-400-latin.woff2 +0 -0
- package/engine/fonts/PlusJakartaSans-600-latin-ext.woff2 +0 -0
- package/engine/fonts/PlusJakartaSans-600-latin.woff2 +0 -0
- package/engine/fonts/SpaceGrotesk-500-latin-ext.woff2 +0 -0
- package/engine/fonts/SpaceGrotesk-500-latin.woff2 +0 -0
- package/engine/fonts/fonts.json +216 -0
- package/engine/fonts/licenses/ArchitectsDaughter-OFL.txt +93 -0
- package/engine/fonts/licenses/CabinSketch-OFL.txt +93 -0
- package/engine/fonts/licenses/InstrumentSerif-OFL.txt +93 -0
- package/engine/fonts/licenses/Inter-OFL.txt +93 -0
- package/engine/fonts/licenses/JetBrainsMono-OFL.txt +93 -0
- package/engine/fonts/licenses/Kalam-OFL.txt +93 -0
- package/engine/fonts/licenses/NotoSansDevanagari-OFL.txt +118 -0
- package/engine/fonts/licenses/PatrickHand-OFL.txt +93 -0
- package/engine/fonts/licenses/PlusJakartaSans-OFL.txt +93 -0
- package/engine/fonts/licenses/SpaceGrotesk-OFL.txt +93 -0
- package/engine/package-lock.json +1201 -0
- package/engine/package.json +67 -0
- package/engine/scripts/build-icons.mjs +74 -0
- package/engine/scripts/fetch-fonts.mjs +68 -0
- package/engine/skills/explainroo/SKILL.md +51 -0
- package/engine/src/align.js +357 -0
- package/engine/src/browser.js +121 -0
- package/engine/src/capture.js +315 -0
- package/engine/src/chapters.js +32 -0
- package/engine/src/cli.js +421 -0
- package/engine/src/clips.js +19 -0
- package/engine/src/elevenlabs.js +90 -0
- package/engine/src/env.js +16 -0
- package/engine/src/export.js +187 -0
- package/engine/src/ffmpeg.js +103 -0
- package/engine/src/fonts.js +86 -0
- package/engine/src/g2p.py +76 -0
- package/engine/src/images.js +151 -0
- package/engine/src/licenses/misaki-Apache-2.0.txt +201 -0
- package/engine/src/math.js +83 -0
- package/engine/src/models.js +161 -0
- package/engine/src/phonemes.js +162 -0
- package/engine/src/pipeline.js +63 -0
- package/engine/src/project.js +331 -0
- package/engine/src/qa.js +186 -0
- package/engine/src/recordings.js +89 -0
- package/engine/src/render.js +156 -0
- package/engine/src/script.js +266 -0
- package/engine/src/server.js +288 -0
- package/engine/src/subtitles.js +78 -0
- package/engine/src/timeline.js +55 -0
- package/engine/src/voice.js +240 -0
- package/engine/src/wav.js +98 -0
- package/engine/templates/starter/scenes.js +31 -0
- package/engine/templates/starter/script.md +14 -0
- package/engine/test/align.test.js +108 -0
- package/engine/test/brand.test.js +41 -0
- package/engine/test/browser.test.js +89 -0
- package/engine/test/camera-browser.test.js +225 -0
- package/engine/test/caption-phrases.test.js +35 -0
- package/engine/test/capture-browser.test.js +90 -0
- package/engine/test/capture-fixture.js +46 -0
- package/engine/test/capture.test.js +62 -0
- package/engine/test/chapters.test.js +41 -0
- package/engine/test/cjk-browser.test.js +101 -0
- package/engine/test/cjk.test.js +232 -0
- package/engine/test/cli-exit.test.js +25 -0
- package/engine/test/cli.test.js +116 -0
- package/engine/test/clips-browser.test.js +125 -0
- package/engine/test/clips.test.js +67 -0
- package/engine/test/code-morph-browser.test.js +99 -0
- package/engine/test/code-morph.test.js +110 -0
- package/engine/test/contrast-browser.test.js +63 -0
- package/engine/test/contrast.test.js +80 -0
- package/engine/test/director.test.js +316 -0
- package/engine/test/engine-pure.test.js +29 -0
- package/engine/test/export-browser.test.js +224 -0
- package/engine/test/export.test.js +96 -0
- package/engine/test/fixtures/capture.html +55 -0
- package/engine/test/formats-pace.test.js +104 -0
- package/engine/test/languages-browser.test.js +78 -0
- package/engine/test/languages.test.js +140 -0
- package/engine/test/looks-browser.test.js +109 -0
- package/engine/test/looks-preview.test.js +57 -0
- package/engine/test/looks.test.js +130 -0
- package/engine/test/math-browser.test.js +114 -0
- package/engine/test/math.test.js +54 -0
- package/engine/test/multi-size-browser.test.js +133 -0
- package/engine/test/multi-size.test.js +116 -0
- package/engine/test/phonemes.test.js +92 -0
- package/engine/test/readability-browser.test.js +36 -0
- package/engine/test/readability.test.js +20 -0
- package/engine/test/render-options.test.js +52 -0
- package/engine/test/script.test.js +67 -0
- package/engine/test/server.test.js +256 -0
- package/engine/test/stills-browser.test.js +70 -0
- package/engine/test/subtitles.test.js +83 -0
- package/engine/test/timeline.test.js +31 -0
- package/engine/test/transparent-browser.test.js +123 -0
- package/engine/test/ui-kit.test.js +96 -0
- package/engine/test/upload-browser.test.js +55 -0
- package/engine/test/voice-providers.test.js +338 -0
- package/lib/host.mjs +480 -0
- package/manifest.json +54 -0
- package/package.json +8 -4
- package/skills/biutalk/SKILL.md +21 -0
- package/studio/app.js +209 -0
- package/studio/assert-panel-permit.mjs +67 -0
- package/studio/composer.css +354 -0
- package/studio/composer.js +169 -0
- package/studio/index.html +82 -0
- package/studio/looks/blueprint.svg +21 -0
- package/studio/looks/chalk.svg +15 -0
- package/studio/looks/clean.svg +20 -0
- package/studio/looks/editorial.svg +18 -0
- package/studio/looks/midnight.svg +17 -0
- package/studio/looks/paper.svg +11 -0
- package/studio/select-menu.js +268 -0
- package/studio/styles.css +4 -0
- package/README.md +0 -3
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// Renders video or GIF: frames in parallel pages, encode, mux and extra files.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { prepare, withEngine } from './pipeline.js';
|
|
6
|
+
import { frameEncoder, ffmpeg, normalizeLoudness } from './ffmpeg.js';
|
|
7
|
+
import { subtitleCues, toSrt, toVtt } from './subtitles.js';
|
|
8
|
+
import { buildChapters, toChaptersText, toChapterMetadata } from './chapters.js';
|
|
9
|
+
import { resolveTimes } from './qa.js';
|
|
10
|
+
import { outputPath } from './project.js';
|
|
11
|
+
|
|
12
|
+
export function renderFormat({ format = 'mp4', out, transparent = false } = {}) {
|
|
13
|
+
if (!['mp4', 'gif', 'webm', 'mov'].includes(format)) throw new Error('--format must be mp4, gif, webm or mov');
|
|
14
|
+
if (transparent && !['webm', 'mov'].includes(format)) throw new Error('--transparent needs --format webm or --format mov');
|
|
15
|
+
if (out && path.extname(out).toLowerCase() !== `.${format}`) throw new Error(`--out must end in .${format} for --format ${format}`);
|
|
16
|
+
return format;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function renderOutput(project, opts = {}) {
|
|
20
|
+
const format = renderFormat(opts);
|
|
21
|
+
return outputPath(project, opts.draft ? 'draft' : 'video', `.${format}`, opts.out);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function render(project, opts = {}) {
|
|
25
|
+
const log = opts.log || (() => {});
|
|
26
|
+
const format = renderFormat(opts);
|
|
27
|
+
const t0 = Date.now();
|
|
28
|
+
const { timeline } = await prepare(project, { log });
|
|
29
|
+
const draft = !!opts.draft;
|
|
30
|
+
const transparent = !!opts.transparent;
|
|
31
|
+
const segmentFormat = format === 'gif' ? 'mp4' : format;
|
|
32
|
+
const scale = opts.scale ?? (draft ? 0.5 : 1);
|
|
33
|
+
const fps = project.config.fps;
|
|
34
|
+
const total = timeline.frames;
|
|
35
|
+
const from = Math.max(0, Math.floor((opts.from ?? 0) * fps));
|
|
36
|
+
const to = Math.min(total, opts.to !== undefined ? Math.ceil(opts.to * fps) : total);
|
|
37
|
+
if (to <= from) throw new Error('nothing to render: --from must be before --to');
|
|
38
|
+
const partial = from > 0 || to < total;
|
|
39
|
+
const out = renderOutput(project, opts);
|
|
40
|
+
const base = out.slice(0, -path.extname(out).length);
|
|
41
|
+
const cues = subtitleCues(timeline, { from: from / fps, to: to / fps });
|
|
42
|
+
const chapters = partial ? [] : buildChapters(timeline, project.script.title || project.config.title);
|
|
43
|
+
const coverTime = partial ? null : resolveTimes(timeline, [project.config.cover === 'auto' ? `${timeline.scenes[0].id}@end` : project.config.cover])[0];
|
|
44
|
+
const workers = Math.max(1, Math.min(opts.workers ?? Math.min(8, Math.max(1, Math.floor(os.cpus().length / 2))), to - from));
|
|
45
|
+
const quality = draft ? 0.82 : 0.93;
|
|
46
|
+
// Final renders get motion blur. Drafts, GIFs and transparent videos skip it.
|
|
47
|
+
const samples = draft || format === 'gif' || transparent || project.config.motionBlur === false ? 1 : 6;
|
|
48
|
+
const segDir = path.join(project.paths.build, 'segments');
|
|
49
|
+
fs.rmSync(segDir, { recursive: true, force: true });
|
|
50
|
+
fs.mkdirSync(segDir, { recursive: true });
|
|
51
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
52
|
+
log(`rendering ${((to - from) / fps).toFixed(1)}s (${to - from} frames at ${fps} fps, ${Math.round(project.config.width * scale)}x${Math.round(project.config.height * scale)}) with ${workers} worker${workers > 1 ? 's' : ''}`);
|
|
53
|
+
|
|
54
|
+
const mix = path.join(project.paths.build, 'mix.wav');
|
|
55
|
+
const mixNorm = path.join(project.paths.build, 'mix-norm.wav');
|
|
56
|
+
const encoders = [];
|
|
57
|
+
try {
|
|
58
|
+
await withEngine(project, timeline, { scale, pages: workers, transparent, log }, async (pages) => {
|
|
59
|
+
const list = Array.isArray(pages) ? pages : [pages];
|
|
60
|
+
let norm;
|
|
61
|
+
if (format !== 'gif') {
|
|
62
|
+
const ta = Date.now();
|
|
63
|
+
const sound = await list[0].evaluate((p) => window.explainroo.soundtrack(p), 'build/mix.wav');
|
|
64
|
+
log(`soundtrack: ${sound.cues} sound cues, mixed in ${((Date.now() - ta) / 1000).toFixed(1)}s`);
|
|
65
|
+
norm = normalizeLoudness(mix, mixNorm, project.config.loudness);
|
|
66
|
+
norm.catch(() => {});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const per = Math.ceil((to - from) / list.length);
|
|
70
|
+
let done = 0;
|
|
71
|
+
let lastLog = Date.now();
|
|
72
|
+
const tf = Date.now();
|
|
73
|
+
await Promise.all(list.map(async (page, k) => {
|
|
74
|
+
const a = from + k * per;
|
|
75
|
+
const b = Math.min(to, a + per);
|
|
76
|
+
if (a >= b) return;
|
|
77
|
+
const enc = frameEncoder({ fps, out: path.join(segDir, `seg-${String(k).padStart(2, '0')}.${segmentFormat}`), draft, format: segmentFormat, transparent });
|
|
78
|
+
encoders.push(enc);
|
|
79
|
+
const batch = 6;
|
|
80
|
+
for (let f = a; f < b; f += batch) {
|
|
81
|
+
const frames = [];
|
|
82
|
+
for (let i = f; i < Math.min(b, f + batch); i++) frames.push(i);
|
|
83
|
+
const jpegs = await page.evaluate(([l, q, n]) => window.explainroo.frames(l, q, n), [frames, quality, samples]);
|
|
84
|
+
for (const j of jpegs) await enc.write(Buffer.from(j, 'base64'));
|
|
85
|
+
done += frames.length;
|
|
86
|
+
if (Date.now() - lastLog > 3000) {
|
|
87
|
+
lastLog = Date.now();
|
|
88
|
+
const rate = done / ((Date.now() - tf) / 1000);
|
|
89
|
+
log(`frames ${done}/${to - from} (${rate.toFixed(1)} fps, about ${Math.ceil((to - from - done) / rate)}s left)`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
await enc.close();
|
|
93
|
+
}));
|
|
94
|
+
log(`frames done in ${((Date.now() - tf) / 1000).toFixed(1)}s`);
|
|
95
|
+
await norm;
|
|
96
|
+
});
|
|
97
|
+
} catch (e) {
|
|
98
|
+
for (const enc of encoders) enc.kill();
|
|
99
|
+
throw e;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const segs = fs.readdirSync(segDir).filter((f) => f.endsWith(`.${segmentFormat}`)).sort();
|
|
103
|
+
const listFile = path.join(segDir, 'list.txt');
|
|
104
|
+
fs.writeFileSync(listFile, segs.map((s) => `file '${path.join(segDir, s).replace(/'/g, "'\\''")}'`).join('\n') + '\n');
|
|
105
|
+
const audioArgs = partial ? ['-ss', String(from / fps), '-t', String((to - from) / fps), '-i', mixNorm] : ['-i', mixNorm];
|
|
106
|
+
const metadata = path.join(project.paths.build, 'chapters.ffmeta');
|
|
107
|
+
if (chapters.length) fs.writeFileSync(metadata, toChapterMetadata(chapters));
|
|
108
|
+
const metadataArgs = chapters.length ? ['-f', 'ffmetadata', '-i', metadata, '-map_metadata', '2', '-map_chapters', '2'] : [];
|
|
109
|
+
let width = 2 * Math.round(project.config.width * scale / 2);
|
|
110
|
+
let height = 2 * Math.round(project.config.height * scale / 2);
|
|
111
|
+
if (format === 'gif') {
|
|
112
|
+
const temp = path.join(project.paths.build, 'gif.mp4');
|
|
113
|
+
const palette = path.join(project.paths.build, 'gif-palette.png');
|
|
114
|
+
const ratio = Math.min(1, 960 / Math.max(width, height));
|
|
115
|
+
width = Math.max(2, 2 * Math.floor(width * ratio / 2));
|
|
116
|
+
height = Math.max(2, 2 * Math.floor(height * ratio / 2));
|
|
117
|
+
const filter = `fps=15,scale=${width}:${height}:flags=lanczos`;
|
|
118
|
+
try {
|
|
119
|
+
await ffmpeg(['-loglevel', 'error', '-f', 'concat', '-safe', '0', '-i', listFile, '-map', '0:v', '-c:v', 'copy', '-an', temp]);
|
|
120
|
+
await ffmpeg(['-loglevel', 'error', '-i', temp, '-vf', `${filter},palettegen=stats_mode=diff`, '-frames:v', '1', '-threads', '1', palette]);
|
|
121
|
+
await ffmpeg(['-loglevel', 'error', '-i', temp, '-i', palette, '-lavfi', `${filter}[v];[v][1:v]paletteuse=dither=sierra2_4a`, '-an', out]);
|
|
122
|
+
} finally {
|
|
123
|
+
fs.rmSync(temp, { force: true });
|
|
124
|
+
fs.rmSync(palette, { force: true });
|
|
125
|
+
}
|
|
126
|
+
} else {
|
|
127
|
+
const audioCodec = format === 'webm' ? ['-c:a', 'libopus', '-b:a', '192k']
|
|
128
|
+
: format === 'mov' ? ['-c:a', 'pcm_s16le'] : ['-c:a', 'aac', '-b:a', '192k'];
|
|
129
|
+
const containerArgs = format === 'webm' ? [] : ['-movflags', '+faststart'];
|
|
130
|
+
await ffmpeg(['-loglevel', 'error', '-f', 'concat', '-safe', '0', '-i', listFile, ...audioArgs, ...metadataArgs, '-map', '0:v', '-map', '1:a', '-c:v', 'copy', ...audioCodec, ...containerArgs, '-shortest', out]);
|
|
131
|
+
}
|
|
132
|
+
fs.rmSync(segDir, { recursive: true, force: true });
|
|
133
|
+
const files = { subtitles: null, chapters: null, cover: null };
|
|
134
|
+
if (timeline.scenes.some((s) => s.words.length)) {
|
|
135
|
+
files.subtitles = { srt: `${base}.srt`, vtt: `${base}.vtt` };
|
|
136
|
+
fs.writeFileSync(files.subtitles.srt, toSrt(cues));
|
|
137
|
+
fs.writeFileSync(files.subtitles.vtt, toVtt(cues));
|
|
138
|
+
} else {
|
|
139
|
+
for (const ext of ['srt', 'vtt']) fs.rmSync(`${base}.${ext}`, { force: true });
|
|
140
|
+
}
|
|
141
|
+
if (chapters.length) {
|
|
142
|
+
files.chapters = `${base}.chapters.txt`;
|
|
143
|
+
fs.writeFileSync(files.chapters, toChaptersText(chapters));
|
|
144
|
+
} else fs.rmSync(`${base}.chapters.txt`, { force: true });
|
|
145
|
+
if (coverTime) {
|
|
146
|
+
const temp = path.join(project.paths.build, 'cover.jpg');
|
|
147
|
+
try {
|
|
148
|
+
await withEngine(project, timeline, { scale: 1, log }, (page) => page.evaluate((T) => window.explainroo.stills([{ T, path: 'build/cover.jpg' }], { type: 'image/jpeg', quality: 0.9, captions: false }), coverTime.T));
|
|
149
|
+
files.cover = `${base}.cover.jpg`;
|
|
150
|
+
fs.copyFileSync(temp, files.cover);
|
|
151
|
+
} finally { fs.rmSync(temp, { force: true }); }
|
|
152
|
+
} else fs.rmSync(`${base}.cover.jpg`, { force: true });
|
|
153
|
+
const secs = (Date.now() - t0) / 1000;
|
|
154
|
+
log(`wrote ${path.relative(process.cwd(), out) || out} in ${secs.toFixed(1)}s`);
|
|
155
|
+
return { out, ...files, duration: (to - from) / fps, frames: to - from, seconds: secs, width, height };
|
|
156
|
+
}
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// Parser for script.md, the narration file of a video project.
|
|
2
|
+
//
|
|
3
|
+
// # Title (optional, not spoken)
|
|
4
|
+
// ## scene-id {hold=1 min=4} (starts a scene; attributes are optional)
|
|
5
|
+
// Narration text. [#mark] Markers name a moment, [pause 0.6] adds silence,
|
|
6
|
+
// and {DNS|D N S} shows "DNS" on screen but speaks "D N S".
|
|
7
|
+
// > director notes and <!-- comments --> are ignored.
|
|
8
|
+
|
|
9
|
+
const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
|
|
10
|
+
const ATTR_NUMBERS = new Set(['hold', 'min', 'lead', 'gap', 'max']);
|
|
11
|
+
|
|
12
|
+
export class ScriptError extends Error {
|
|
13
|
+
constructor(message, line) {
|
|
14
|
+
super(line ? `script.md line ${line}: ${message}` : `script.md: ${message}`);
|
|
15
|
+
this.line = line;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function normWord(w) {
|
|
20
|
+
return String(w)
|
|
21
|
+
.toLowerCase()
|
|
22
|
+
.normalize('NFKD')
|
|
23
|
+
.replace(/[̀-ͯ]/g, '')
|
|
24
|
+
.replace(/['’]/g, '')
|
|
25
|
+
.replace(/[^\p{L}\p{M}\p{N}%$€£+#@.]/gu, '')
|
|
26
|
+
.replace(/^\.+|\.+$/g, '');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function parseAttrs(src, line) {
|
|
30
|
+
const attrs = {};
|
|
31
|
+
if (!src) return attrs;
|
|
32
|
+
const token = /[^\s,=:]+[=:](?:"[^"]*"|'[^']*'|[^\s,]+)|[^\s,]+/y;
|
|
33
|
+
let i = 0;
|
|
34
|
+
while (i < src.length) {
|
|
35
|
+
if (/[\s,]/.test(src[i])) { i++; continue; }
|
|
36
|
+
token.lastIndex = i;
|
|
37
|
+
const part = token.exec(src)?.[0];
|
|
38
|
+
i = token.lastIndex;
|
|
39
|
+
const m = /^([a-zA-Z][\w-]*)\s*[=:]\s*(.+)$/.exec(part);
|
|
40
|
+
if (!m) throw new ScriptError(`cannot read scene attribute "${part}" (use key=value)`, line);
|
|
41
|
+
const [, key, raw] = m;
|
|
42
|
+
const value = raw.replace(/^["']|["']$/g, '');
|
|
43
|
+
if (key === 'chapter' && (!value.trim() || value.length > 60)) throw new ScriptError('chapter title must be 1 to 60 characters', line);
|
|
44
|
+
if (ATTR_NUMBERS.has(key)) {
|
|
45
|
+
const n = Number(value);
|
|
46
|
+
if (!Number.isFinite(n) || n < 0) throw new ScriptError(`attribute ${key} must be a number >= 0`, line);
|
|
47
|
+
attrs[key] = n;
|
|
48
|
+
} else {
|
|
49
|
+
attrs[key] = value;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return attrs;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Splits one scene's narration into units. A unit is a word (or an override
|
|
56
|
+
// group) with separate display and spoken text, a marker, or a pause.
|
|
57
|
+
export function tokenizeNarration(text, line = 0, language = 'en') {
|
|
58
|
+
const units = [];
|
|
59
|
+
const segmenter = ['ja', 'zh'].includes(language) ? new Intl.Segmenter(language, { granularity: 'word' }) : null;
|
|
60
|
+
const punctuation = segmenter ? /^[.,;:!?।。!?、,;:)」』)\]"'’”…]+$/ : /^[.,;:!?।)\]"'’…]+$/;
|
|
61
|
+
let i = 0;
|
|
62
|
+
let pendingSpace = false;
|
|
63
|
+
const n = text.length;
|
|
64
|
+
const pushWord = (display, spoken) => {
|
|
65
|
+
const prev = units[units.length - 1];
|
|
66
|
+
if (!pendingSpace && prev && prev.type === 'word' && punctuation.test(display)) {
|
|
67
|
+
prev.display += display;
|
|
68
|
+
prev.spoken += spoken;
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
units.push({ type: 'word', display, spoken, space: pendingSpace || !units.some((u) => u.type === 'word') });
|
|
72
|
+
pendingSpace = false;
|
|
73
|
+
};
|
|
74
|
+
while (i < n) {
|
|
75
|
+
const c = text[i];
|
|
76
|
+
if (/\s/.test(c)) { pendingSpace = true; i++; continue; }
|
|
77
|
+
if (text.startsWith('[#', i)) {
|
|
78
|
+
const end = text.indexOf(']', i);
|
|
79
|
+
const name = end === -1 ? '' : text.slice(i + 2, end);
|
|
80
|
+
if (!/^[A-Za-z0-9_-]+$/.test(name)) throw new ScriptError(`marker "${text.slice(i, end + 1 || i + 12)}" should look like [#name]`, line);
|
|
81
|
+
units.push({ type: 'mark', name });
|
|
82
|
+
i = end + 1;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (text.startsWith('[pause', i)) {
|
|
86
|
+
const end = text.indexOf(']', i);
|
|
87
|
+
const arg = end === -1 ? null : text.slice(i + 6, end).trim();
|
|
88
|
+
const sec = arg === '' ? 0.5 : Number(arg);
|
|
89
|
+
if (end === -1 || !Number.isFinite(sec) || sec < 0 || sec > 10) throw new ScriptError('pauses look like [pause] or [pause 0.8] (0 to 10 seconds)', line);
|
|
90
|
+
units.push({ type: 'pause', sec });
|
|
91
|
+
pendingSpace = true;
|
|
92
|
+
i = end + 1;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (c === '{') {
|
|
96
|
+
const end = text.indexOf('}', i);
|
|
97
|
+
const inner = end === -1 ? '' : text.slice(i + 1, end);
|
|
98
|
+
const bar = inner.indexOf('|');
|
|
99
|
+
if (end === -1 || bar === -1 || !inner.slice(0, bar).trim() || !inner.slice(bar + 1).trim()) {
|
|
100
|
+
throw new ScriptError('pronunciation overrides look like {shown|spoken}, for example {SQL|sequel}', line);
|
|
101
|
+
}
|
|
102
|
+
let j = end + 1;
|
|
103
|
+
while (j < n && !/\s/.test(text[j]) && text[j] !== '[' && text[j] !== '{' && (!segmenter || punctuation.test(text[j]))) j++;
|
|
104
|
+
const trail = text.slice(end + 1, j);
|
|
105
|
+
pushWord(inner.slice(0, bar).trim() + trail, inner.slice(bar + 1).trim() + trail);
|
|
106
|
+
i = j;
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
let j = i;
|
|
110
|
+
while (j < n && !/\s/.test(text[j]) && !text.startsWith('[#', j) && !text.startsWith('[pause', j) && text[j] !== '{') j++;
|
|
111
|
+
const word = text.slice(i, j);
|
|
112
|
+
if (segmenter) {
|
|
113
|
+
let prefix = '';
|
|
114
|
+
for (const part of segmenter.segment(word)) {
|
|
115
|
+
if (!part.isWordLike && (/[「『(“‘(]/u.test(part.segment) || !units.some(u => u.type === 'word'))) { prefix += part.segment; continue; }
|
|
116
|
+
pushWord(prefix + part.segment, prefix + part.segment);
|
|
117
|
+
prefix = '';
|
|
118
|
+
}
|
|
119
|
+
if (prefix) pushWord(prefix, prefix);
|
|
120
|
+
} else pushWord(word, word);
|
|
121
|
+
i = j;
|
|
122
|
+
}
|
|
123
|
+
return units;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function parseScript(source, { language = 'en' } = {}) {
|
|
127
|
+
const lines = String(source).replace(/\r\n?/g, '\n').split('\n');
|
|
128
|
+
let title = null;
|
|
129
|
+
const scenes = [];
|
|
130
|
+
let current = null;
|
|
131
|
+
let inComment = false;
|
|
132
|
+
const seen = new Set();
|
|
133
|
+
|
|
134
|
+
const flushParagraph = () => {
|
|
135
|
+
if (!current) return;
|
|
136
|
+
if (current._para.length) {
|
|
137
|
+
current._paras.push({ text: current._para.join(' '), line: current._paraLine });
|
|
138
|
+
current._para = [];
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
lines.forEach((raw, i) => {
|
|
143
|
+
const lineNo = i + 1;
|
|
144
|
+
let line = raw;
|
|
145
|
+
if (inComment) {
|
|
146
|
+
const end = line.indexOf('-->');
|
|
147
|
+
if (end === -1) return;
|
|
148
|
+
line = line.slice(end + 3);
|
|
149
|
+
inComment = false;
|
|
150
|
+
}
|
|
151
|
+
line = line.replace(/<!--[\s\S]*?-->/g, '');
|
|
152
|
+
const open = line.indexOf('<!--');
|
|
153
|
+
if (open !== -1) {
|
|
154
|
+
line = line.slice(0, open);
|
|
155
|
+
inComment = true;
|
|
156
|
+
}
|
|
157
|
+
const trimmed = line.trim();
|
|
158
|
+
|
|
159
|
+
const h1 = /^#\s+(.+)$/.exec(trimmed);
|
|
160
|
+
if (h1 && !trimmed.startsWith('##')) {
|
|
161
|
+
if (!current && title === null) title = h1[1].trim();
|
|
162
|
+
else throw new ScriptError('a single "#" title is only allowed once, before the first scene', lineNo);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
const h2 = /^##\s+([^\s{]+)\s*(?:\{([^}]*)\})?\s*$/.exec(trimmed);
|
|
166
|
+
if (h2) {
|
|
167
|
+
flushParagraph();
|
|
168
|
+
const id = h2[1];
|
|
169
|
+
if (!ID_RE.test(id)) throw new ScriptError(`scene id "${id}" may only use letters, digits, "-" and "_"`, lineNo);
|
|
170
|
+
if (seen.has(id)) throw new ScriptError(`scene id "${id}" is used twice`, lineNo);
|
|
171
|
+
seen.add(id);
|
|
172
|
+
current = { id, attrs: parseAttrs(h2[2], lineNo), line: lineNo, _paras: [], _para: [], _paraLine: lineNo };
|
|
173
|
+
scenes.push(current);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (trimmed.startsWith('##')) throw new ScriptError('scene headings look like "## scene-id" or "## scene-id {hold=1}"', lineNo);
|
|
177
|
+
if (trimmed.startsWith('>')) return;
|
|
178
|
+
if (!trimmed) {
|
|
179
|
+
flushParagraph();
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (!current) throw new ScriptError('narration must come after a "## scene-id" heading', lineNo);
|
|
183
|
+
if (!current._para.length) current._paraLine = lineNo;
|
|
184
|
+
current._para.push(trimmed);
|
|
185
|
+
});
|
|
186
|
+
if (inComment) throw new ScriptError('an HTML comment is never closed');
|
|
187
|
+
flushParagraph();
|
|
188
|
+
if (!scenes.length) throw new ScriptError('no scenes found; start one with "## scene-id"');
|
|
189
|
+
|
|
190
|
+
return {
|
|
191
|
+
title,
|
|
192
|
+
scenes: scenes.map((s) => {
|
|
193
|
+
const units = [];
|
|
194
|
+
s._paras.forEach((p, pi) => {
|
|
195
|
+
if (pi > 0) units.push({ type: 'pause', sec: null, paragraph: true });
|
|
196
|
+
units.push(...tokenizeNarration(p.text, p.line, language));
|
|
197
|
+
});
|
|
198
|
+
const words = units.filter((u) => u.type === 'word');
|
|
199
|
+
return {
|
|
200
|
+
id: s.id,
|
|
201
|
+
attrs: s.attrs,
|
|
202
|
+
line: s.line,
|
|
203
|
+
units,
|
|
204
|
+
text: words.map((w, i) => (i && w.space ? ' ' : '') + w.display).join(''),
|
|
205
|
+
spoken: words.map((w, i) => (i && w.space ? ' ' : '') + w.spoken).join(''),
|
|
206
|
+
};
|
|
207
|
+
}),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Groups a scene's units into speakable chunks. Each chunk is one sentence (or
|
|
212
|
+
// the text between explicit pauses) and is sent to the TTS model on its own,
|
|
213
|
+
// which keeps every request well under the model's context limit and gives
|
|
214
|
+
// exact control over the silence between sentences.
|
|
215
|
+
export function speechChunks(units, { sentenceGap = 0.3, paragraphGap = 0.55, pace = 1, language = 'en' } = {}) {
|
|
216
|
+
const cjk = ['ja', 'zh'].includes(language);
|
|
217
|
+
const sentenceEnd = cjk ? /[.!?…।。!?]["'’)\]」』)]*$/ : /[.!?…।]["'’)\]]*$/;
|
|
218
|
+
const chunks = [];
|
|
219
|
+
let cur = null;
|
|
220
|
+
let gapBefore = 0;
|
|
221
|
+
const close = () => {
|
|
222
|
+
if (cur && cur.words.length) chunks.push(cur);
|
|
223
|
+
cur = null;
|
|
224
|
+
};
|
|
225
|
+
units.forEach((u, index) => {
|
|
226
|
+
if (u.type === 'pause') {
|
|
227
|
+
close();
|
|
228
|
+
gapBefore = u.paragraph ? Math.max(gapBefore, paragraphGap / pace) : gapBefore + u.sec / pace;
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
if (u.type !== 'word') return;
|
|
232
|
+
if (!cur) {
|
|
233
|
+
cur = { gapBefore, words: [], text: '' };
|
|
234
|
+
gapBefore = 0;
|
|
235
|
+
}
|
|
236
|
+
cur.text += (cur.words.length && !cjk ? ' ' : '') + u.spoken;
|
|
237
|
+
cur.words.push({ unitIndex: index, display: u.display, spoken: u.spoken });
|
|
238
|
+
if (sentenceEnd.test(u.spoken)) {
|
|
239
|
+
close();
|
|
240
|
+
gapBefore = sentenceGap / pace;
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
close();
|
|
244
|
+
return chunks;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Resolves [#marks] to times once every word unit has a start and end time.
|
|
248
|
+
// A mark takes the start of the next word; a mark after the last word takes
|
|
249
|
+
// the end of the last word.
|
|
250
|
+
export function resolveMarks(units, wordTimes) {
|
|
251
|
+
const marks = {};
|
|
252
|
+
units.forEach((u, i) => {
|
|
253
|
+
if (u.type !== 'mark') return;
|
|
254
|
+
let t = null;
|
|
255
|
+
for (let j = i + 1; j < units.length; j++) {
|
|
256
|
+
if (units[j].type === 'word' && wordTimes[j]) { t = wordTimes[j].start; break; }
|
|
257
|
+
}
|
|
258
|
+
if (t === null) {
|
|
259
|
+
for (let j = i - 1; j >= 0; j--) {
|
|
260
|
+
if (units[j].type === 'word' && wordTimes[j]) { t = wordTimes[j].end; break; }
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
marks[u.name] = t ?? 0;
|
|
264
|
+
});
|
|
265
|
+
return marks;
|
|
266
|
+
}
|