@slidevideo/cli 0.3.0 → 0.3.2
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/CHANGELOG.md +20 -0
- package/README.md +3 -3
- package/addons/slidevideo/geometry.ts +334 -1
- package/addons/slidevideo/global-top.vue +57 -6
- package/addons/slidevideo/preview.ts +242 -25
- package/assets/fonts/OFL-LICENSES.txt +95 -0
- package/assets/fonts/instrument-serif-latin-2.woff2 +0 -0
- package/assets/fonts/instrument-serif-latin-ext-1.woff2 +0 -0
- package/assets/fonts/jetbrains-mono-latin-4.woff2 +0 -0
- package/assets/fonts/jetbrains-mono-latin-ext-3.woff2 +0 -0
- package/assets/fonts/plus-jakarta-sans-latin-6.woff2 +0 -0
- package/assets/fonts/plus-jakarta-sans-latin-ext-5.woff2 +0 -0
- package/dist/adapters/edge.d.ts +1 -0
- package/dist/adapters/edge.js +4 -3
- package/dist/adapters/elevenlabs.d.ts +1 -0
- package/dist/adapters/elevenlabs.js +4 -3
- package/dist/adapters/powerpoint-preview.d.ts +1 -1
- package/dist/adapters/powerpoint-preview.js +13 -2
- package/dist/adapters/powerpoint.js +91 -14
- package/dist/adapters/slidev-inspection.js +7 -2
- package/dist/annotation-paint.d.ts +195 -5
- package/dist/annotation-paint.js +1188 -2
- package/dist/annotations.d.ts +26 -2
- package/dist/annotations.js +1117 -29
- package/dist/assembly.js +143 -37
- package/dist/captions.d.ts +6 -0
- package/dist/captions.js +320 -0
- package/dist/cli.js +59 -19
- package/dist/compositor.d.ts +17 -2
- package/dist/compositor.js +108 -26
- package/dist/contracts.d.ts +254 -14
- package/dist/media.js +24 -1
- package/dist/pipeline.d.ts +6 -1
- package/dist/pipeline.js +68 -20
- package/dist/preview/contracts.d.ts +15 -0
- package/dist/preview/player.js +527 -34
- package/dist/preview/server.d.ts +1 -1
- package/dist/preview/server.js +125 -4
- package/dist/preview/view.d.ts +1 -1
- package/dist/preview/view.js +26 -7
- package/dist/run.d.ts +1 -0
- package/dist/run.js +20 -0
- package/dist/speech.d.ts +13 -3
- package/dist/speech.js +164 -45
- package/dist/stamp-fonts.d.ts +17 -0
- package/dist/stamp-fonts.js +202 -0
- package/dist/storyboard.js +60 -3
- package/dist/timing.d.ts +4 -1
- package/dist/timing.js +322 -14
- package/dist/update-check-worker.js +43 -11
- package/dist/update-check.js +14 -10
- package/package.json +12 -1
- package/schemas/annotation-geometry.v1.json +111 -0
- package/schemas/schedule.v1.json +1672 -84
- package/schemas/storyboard.v1.json +3725 -85
- package/skills/slidevideo/SKILL.md +5 -5
- package/skills/slidevideo/references/decks.md +6 -4
- package/skills/slidevideo/references/production.md +12 -11
- package/skills/slidevideo/references/storyboard.md +268 -5
- package/tools/powerpoint/powerpoint.ps1 +155 -6
- package/tools/powerpoint/preview.ps1 +68 -1
package/dist/preview/server.js
CHANGED
|
@@ -8,17 +8,82 @@ import { ProductionError, requireCondition } from '../errors.js';
|
|
|
8
8
|
import { executionScope } from '../media.js';
|
|
9
9
|
import { loadStoryboard } from '../storyboard.js';
|
|
10
10
|
import { resolvePreviewTiming } from '../timing.js';
|
|
11
|
+
import { resolveSpeechCache } from '../speech.js';
|
|
12
|
+
import { BUNDLED_STAMP_FONTS, bundledFontPath } from '../stamp-fonts.js';
|
|
11
13
|
import { playerPage } from './view.js';
|
|
12
14
|
function send(res, status, contentType, body) {
|
|
13
15
|
res.writeHead(status, { 'Content-Type': contentType });
|
|
14
16
|
res.end(body);
|
|
15
17
|
}
|
|
18
|
+
function audioContentType(format) {
|
|
19
|
+
switch (format.toLowerCase()) {
|
|
20
|
+
case 'mp3': return 'audio/mpeg';
|
|
21
|
+
case 'wav': return 'audio/wav';
|
|
22
|
+
case 'ogg': return 'audio/ogg';
|
|
23
|
+
case 'm4a': return 'audio/mp4';
|
|
24
|
+
case 'webm': return 'audio/webm';
|
|
25
|
+
case 'aac': return 'audio/aac';
|
|
26
|
+
default: return 'application/octet-stream';
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
async function sendAudio(req, res, filePath, format) {
|
|
30
|
+
const data = await readFile(filePath);
|
|
31
|
+
const contentType = audioContentType(format);
|
|
32
|
+
const range = req.headers.range;
|
|
33
|
+
if (range) {
|
|
34
|
+
const match = /^bytes=(\d*)-(\d*)$/.exec(range.trim());
|
|
35
|
+
if (!match || (!match[1] && !match[2]) || data.length === 0) {
|
|
36
|
+
res.writeHead(416, { 'Content-Range': `bytes */${data.length}` });
|
|
37
|
+
res.end();
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
let start;
|
|
41
|
+
let end;
|
|
42
|
+
if (!match[1]) {
|
|
43
|
+
const suffix = Number(match[2]);
|
|
44
|
+
if (suffix === 0) {
|
|
45
|
+
res.writeHead(416, { 'Content-Range': `bytes */${data.length}` });
|
|
46
|
+
res.end();
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
start = Math.max(0, data.length - suffix);
|
|
50
|
+
end = data.length - 1;
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
start = Number(match[1]);
|
|
54
|
+
end = match[2] ? Math.min(data.length - 1, Number(match[2])) : data.length - 1;
|
|
55
|
+
}
|
|
56
|
+
if (start >= data.length || start > end) {
|
|
57
|
+
res.writeHead(416, { 'Content-Range': `bytes */${data.length}` });
|
|
58
|
+
res.end();
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const chunk = data.subarray(start, end + 1);
|
|
62
|
+
res.writeHead(206, {
|
|
63
|
+
'Content-Type': contentType,
|
|
64
|
+
'Content-Length': chunk.length,
|
|
65
|
+
'Content-Range': `bytes ${start}-${end}/${data.length}`,
|
|
66
|
+
'Accept-Ranges': 'bytes',
|
|
67
|
+
'Cache-Control': 'private, max-age=3600',
|
|
68
|
+
});
|
|
69
|
+
res.end(chunk);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
res.writeHead(200, {
|
|
73
|
+
'Content-Type': contentType,
|
|
74
|
+
'Content-Length': data.length,
|
|
75
|
+
'Accept-Ranges': 'bytes',
|
|
76
|
+
'Cache-Control': 'private, max-age=3600',
|
|
77
|
+
});
|
|
78
|
+
res.end(data);
|
|
79
|
+
}
|
|
16
80
|
export async function servePreview(storyboard, cache, port, viewport = defaultViewport, ready) {
|
|
17
81
|
let origin = '';
|
|
18
82
|
let config;
|
|
19
83
|
let session;
|
|
20
84
|
let adapter;
|
|
21
85
|
let directory;
|
|
86
|
+
let audioFiles = new Map();
|
|
22
87
|
let preserveDiagnostics = false;
|
|
23
88
|
const controller = new AbortController();
|
|
24
89
|
const stop = () => controller.abort();
|
|
@@ -38,12 +103,44 @@ export async function servePreview(storyboard, cache, port, viewport = defaultVi
|
|
|
38
103
|
return send(res, 405, 'text/plain', 'Method not allowed');
|
|
39
104
|
if (pathname === '/')
|
|
40
105
|
return send(res, 200, 'text/html; charset=utf-8', playerPage);
|
|
106
|
+
if (pathname === '/favicon.ico') {
|
|
107
|
+
res.writeHead(204);
|
|
108
|
+
res.end();
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
41
111
|
if (pathname === '/config.json')
|
|
42
112
|
return send(res, 200, 'application/json', JSON.stringify(config));
|
|
43
113
|
if (pathname === '/preview/player.js' || pathname === '/annotation-paint.js') {
|
|
44
114
|
const file = pathname === '/preview/player.js' ? './player.js' : '../annotation-paint.js';
|
|
45
115
|
return send(res, 200, 'text/javascript', await readFile(new URL(file, import.meta.url)));
|
|
46
116
|
}
|
|
117
|
+
if (pathname === '/fonts/manifest.json') {
|
|
118
|
+
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
119
|
+
res.setHeader('Cache-Control', 'private, max-age=3600');
|
|
120
|
+
return send(res, 200, 'application/json', JSON.stringify(BUNDLED_STAMP_FONTS));
|
|
121
|
+
}
|
|
122
|
+
if (pathname.startsWith('/fonts/')) {
|
|
123
|
+
const fontName = pathname.slice('/fonts/'.length);
|
|
124
|
+
const fontFile = bundledFontPath(fontName);
|
|
125
|
+
if (!fontFile)
|
|
126
|
+
return send(res, 404, 'text/plain', 'Not found');
|
|
127
|
+
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
128
|
+
res.setHeader('Cache-Control', 'private, max-age=3600');
|
|
129
|
+
return send(res, 200, 'font/woff2', await readFile(fontFile));
|
|
130
|
+
}
|
|
131
|
+
if (pathname.startsWith('/audio/')) {
|
|
132
|
+
let segment;
|
|
133
|
+
try {
|
|
134
|
+
segment = decodeURIComponent(pathname.slice('/audio/'.length));
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return send(res, 400, 'text/plain', 'Invalid audio segment');
|
|
138
|
+
}
|
|
139
|
+
const file = audioFiles.get(segment);
|
|
140
|
+
if (!file)
|
|
141
|
+
return send(res, 404, 'text/plain', 'Not found');
|
|
142
|
+
return sendAudio(req, res, file.path, file.format);
|
|
143
|
+
}
|
|
47
144
|
send(res, 404, 'text/plain', 'Not found');
|
|
48
145
|
}
|
|
49
146
|
const server = createServer((req, res) => {
|
|
@@ -59,13 +156,15 @@ export async function servePreview(storyboard, cache, port, viewport = defaultVi
|
|
|
59
156
|
process.once('SIGTERM', stop);
|
|
60
157
|
try {
|
|
61
158
|
await executionScope.run({ signal: controller.signal, bounded: false }, async () => {
|
|
62
|
-
const
|
|
159
|
+
const source = resolve(storyboard);
|
|
160
|
+
const story = await loadStoryboard(source);
|
|
63
161
|
requireCondition(!story.overlays?.length, 'PREVIEW_CAPABILITY', 'Image overlays require an exported video. Use slidevideo build to review them.', 3);
|
|
64
162
|
adapter = presentationAdapter(story.deck);
|
|
65
163
|
requireCondition(adapter.startPreview, 'PREVIEW_CAPABILITY', `Adapter ${adapter.id} does not support preview`, 3);
|
|
66
164
|
const inspection = await adapter.inspect(story.deck);
|
|
67
165
|
await adapter.validate(story, inspection, { viewport });
|
|
68
|
-
const { schedule, approximate } = await resolvePreviewTiming(story, ttsAdapters, cache);
|
|
166
|
+
const { schedule, approximate, approximateCues, audio: verifiedAudio } = await resolvePreviewTiming(story, ttsAdapters, resolveSpeechCache(source, cache));
|
|
167
|
+
audioFiles = verifiedAudio;
|
|
69
168
|
await adapter.validate(story, inspection, { viewport, schedule });
|
|
70
169
|
controller.signal.throwIfAborted();
|
|
71
170
|
await new Promise((resolve, reject) => {
|
|
@@ -79,10 +178,32 @@ export async function servePreview(storyboard, cache, port, viewport = defaultVi
|
|
|
79
178
|
controller.signal.throwIfAborted();
|
|
80
179
|
session = await adapter.startPreview(story, schedule, directory, origin, viewport);
|
|
81
180
|
controller.signal.throwIfAborted();
|
|
181
|
+
const slideActions = schedule.actions.filter(item => item.action.type === 'slide');
|
|
182
|
+
const scenes = slideActions.map((item, index) => {
|
|
183
|
+
const target = item.action.type === 'slide' ? item.action.target : '';
|
|
184
|
+
const isSceneStart = item.id === `${item.scene}:slide`;
|
|
185
|
+
return {
|
|
186
|
+
id: isSceneStart ? item.scene : `${item.scene} · ${target}`,
|
|
187
|
+
slide: target,
|
|
188
|
+
start_ms: item.start_ms,
|
|
189
|
+
end_ms: slideActions[index + 1]?.start_ms ?? schedule.duration_ms,
|
|
190
|
+
};
|
|
191
|
+
});
|
|
192
|
+
const audio = [];
|
|
193
|
+
for (const item of schedule.actions) {
|
|
194
|
+
if (item.action.type === 'speak' && audioFiles.has(item.action.segment)) {
|
|
195
|
+
audio.push({
|
|
196
|
+
segment: item.action.segment,
|
|
197
|
+
start_ms: item.start_ms,
|
|
198
|
+
end_ms: item.end_ms,
|
|
199
|
+
url: `/audio/${encodeURIComponent(item.action.segment)}`,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|
|
82
203
|
config = { deck: basename(story.deck), width: viewport.width, height: viewport.height,
|
|
83
|
-
duration: schedule.duration_ms, approximate,
|
|
204
|
+
duration: schedule.duration_ms, approximate, approximate_cues: approximateCues, scenes, audio,
|
|
84
205
|
stage: 'url' in session ? { url: session.url } : { annotations: schedule.annotations } };
|
|
85
|
-
ready(origin, approximate);
|
|
206
|
+
ready(origin, approximate, approximateCues);
|
|
86
207
|
await new Promise(resolve => controller.signal.addEventListener('abort', () => resolve(), { once: true }));
|
|
87
208
|
});
|
|
88
209
|
}
|
package/dist/preview/view.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const playerPage
|
|
1
|
+
export declare const playerPage: string;
|
package/dist/preview/view.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
+
import { stampFontFaceCss } from '../stamp-fonts.js';
|
|
1
2
|
export const playerPage = `<!doctype html>
|
|
2
3
|
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
3
4
|
<title>Storyboard preview · SlideVideo</title>
|
|
4
5
|
<style>
|
|
6
|
+
${stampFontFaceCss()}
|
|
5
7
|
:root { color-scheme: dark; font: 15px Inter, system-ui, sans-serif; color: #e9edf1; background: #111419 }
|
|
6
8
|
* { box-sizing: border-box }
|
|
7
9
|
body { margin: 0; min-height: 100dvh; display: grid; grid-template-rows: auto 1fr auto }
|
|
@@ -11,17 +13,31 @@ header { border-bottom: 1px solid #333942 }
|
|
|
11
13
|
header strong { letter-spacing: -.045em; font-size: 1.1rem }
|
|
12
14
|
#deck { color: #b7c0c9; padding-left: .75rem; border-left: 1px solid #525964; overflow-wrap: anywhere }
|
|
13
15
|
main { display: grid; place-items: center; min-height: 0; padding: clamp(.5rem, 2vw, 2rem) }
|
|
14
|
-
#stage { position: relative; width: min(100%, calc((100dvh -
|
|
16
|
+
#stage { position: relative; width: min(100%, calc((100dvh - 13rem) * var(--ratio, 1.7778))); aspect-ratio: var(--ratio, 1.7778); background: #090b0d; overflow: hidden; box-shadow: 0 8px 32px #0005 }
|
|
15
17
|
iframe, canvas { display: block; width: 100%; height: 100%; border: 0; object-fit: contain }
|
|
16
18
|
iframe { pointer-events: none }
|
|
17
19
|
footer { border-top: 1px solid #333942 }
|
|
18
20
|
.controls { flex-wrap: wrap; justify-content: space-between }
|
|
19
|
-
|
|
21
|
+
.transport { flex-wrap: wrap }
|
|
22
|
+
button, select { font: inherit; font-weight: 600; border: 1px solid #48515c; border-radius: .45rem; color: inherit; background: #272e36; padding: .5rem .85rem; cursor: pointer }
|
|
23
|
+
select { font-weight: 500; max-width: 18rem; text-overflow: ellipsis }
|
|
20
24
|
#play { background: #adedd6; border-color: transparent; color: #112a22 }
|
|
21
|
-
|
|
22
|
-
button:
|
|
25
|
+
#mute[aria-pressed="true"] { color: #9aa5b1 }
|
|
26
|
+
button:disabled, select:disabled { opacity: .42; cursor: default }
|
|
27
|
+
button:focus-visible, select:focus-visible, #timeline:focus-visible { outline: 2px solid #adedd6; outline-offset: 3px }
|
|
23
28
|
#clock { font-variant-numeric: tabular-nums; white-space: nowrap }
|
|
24
|
-
|
|
29
|
+
#timeline { position: relative; height: 1.5rem; display: flex; align-items: center; margin: 0 0 .85rem; cursor: pointer; touch-action: none; user-select: none; border-radius: .25rem }
|
|
30
|
+
#timeline[aria-disabled="true"] { opacity: .42; cursor: default; pointer-events: none }
|
|
31
|
+
.timeline-track { position: relative; width: 100%; height: .35rem; background: #303742; border-radius: 999px; transition: height .12s ease }
|
|
32
|
+
#timeline:hover .timeline-track, #timeline:focus-visible .timeline-track, #timeline.dragging .timeline-track { height: .48rem }
|
|
33
|
+
#timeline-fill { position: absolute; inset: 0 auto 0 0; width: 0%; background: #adedd6; border-radius: 999px; pointer-events: none }
|
|
34
|
+
#timeline-markers { position: absolute; inset: 0; pointer-events: none }
|
|
35
|
+
.scene-marker { position: absolute; top: 50%; transform: translate(-50%, -50%); width: 10px; height: 1.1rem; padding: 0; border: 0; border-radius: 2px; background: transparent; pointer-events: auto; cursor: pointer }
|
|
36
|
+
.scene-marker::after { content: ''; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 2px; height: .75rem; border-radius: 1px; background: #8a96a6; transition: background-color .12s ease, height .12s ease }
|
|
37
|
+
.scene-marker:hover::after, .scene-marker:focus-visible::after { background: #ffffff; height: 1rem }
|
|
38
|
+
.scene-marker.active::after { background: #adedd6 }
|
|
39
|
+
#timeline-thumb { position: absolute; top: 50%; left: 0%; width: .85rem; height: .85rem; border-radius: 50%; background: #adedd6; border: 2px solid #111419; transform: translate(-50%, -50%); pointer-events: none; box-shadow: 0 1px 4px #0008; transition: transform .12s ease }
|
|
40
|
+
#timeline:hover #timeline-thumb, #timeline.dragging #timeline-thumb { transform: translate(-50%, -50%) scale(1.18) }
|
|
25
41
|
#status, #pacing { color: #bbc4ce }
|
|
26
42
|
#pacing { margin: .75rem 0 0; font-size: .9rem }
|
|
27
43
|
[data-error] #status { color: #ffb9ad }
|
|
@@ -29,8 +45,11 @@ progress { width: 100%; height: .25rem; accent-color: #adedd6; display: block; m
|
|
|
29
45
|
</style></head>
|
|
30
46
|
<body><header><strong>SlideVideo</strong><span id="deck">Storyboard preview</span></header>
|
|
31
47
|
<main><div id="stage"></div></main>
|
|
32
|
-
<footer
|
|
48
|
+
<footer>
|
|
49
|
+
<div id="timeline" role="slider" tabindex="0" aria-label="Playback position" aria-valuemin="0" aria-valuemax="1" aria-valuenow="0" aria-valuetext="0:00" aria-disabled="true">
|
|
50
|
+
<div class="timeline-track"><div id="timeline-fill"></div><div id="timeline-markers"></div><div id="timeline-thumb"></div></div>
|
|
51
|
+
</div>
|
|
33
52
|
<div class="controls"><div class="transport">
|
|
34
|
-
<button id="play" disabled>Play</button><button id="pause" disabled>Pause</button><button id="restart" disabled>Replay</button>
|
|
53
|
+
<button id="play" disabled>Play</button><button id="pause" disabled>Pause</button><button id="restart" disabled>Replay</button><button id="mute" type="button" aria-pressed="false" disabled>Audio</button><select id="scene" aria-label="Jump to scene" disabled></select>
|
|
35
54
|
</div><span id="status" role="status">Loading presentation…</span><span id="clock"></span></div><p id="pacing" hidden></p></footer>
|
|
36
55
|
<script type="module" src="/preview/player.js"></script></body></html>`;
|
package/dist/run.d.ts
CHANGED
package/dist/run.js
CHANGED
|
@@ -4,6 +4,26 @@ import { randomUUID } from 'node:crypto';
|
|
|
4
4
|
import { hashFile, json, saveJson } from './media.js';
|
|
5
5
|
import { requireCondition, ProductionError } from './errors.js';
|
|
6
6
|
import { packagePath } from './installation.js';
|
|
7
|
+
function formatRunTimestamp(now) {
|
|
8
|
+
const pad = (value) => String(value).padStart(2, '0');
|
|
9
|
+
return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
|
|
10
|
+
}
|
|
11
|
+
export async function createDefaultRunDirectory(baseDir = resolve('runs'), now = new Date()) {
|
|
12
|
+
await mkdir(baseDir, { recursive: true });
|
|
13
|
+
const stamp = formatRunTimestamp(now);
|
|
14
|
+
for (let suffix = 1; suffix <= 1000; suffix++) {
|
|
15
|
+
const candidate = join(baseDir, suffix === 1 ? stamp : `${stamp}-${suffix}`);
|
|
16
|
+
try {
|
|
17
|
+
await mkdir(candidate);
|
|
18
|
+
return candidate;
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
if (error.code !== 'EEXIST')
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
throw new ProductionError('NEW_RUN_REQUIRED', `Could not allocate a unique run directory under ${baseDir}`);
|
|
26
|
+
}
|
|
7
27
|
export class Run {
|
|
8
28
|
directory;
|
|
9
29
|
manifest;
|
package/dist/speech.d.ts
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
import type { SpeechManifest, Storyboard, Narration, Voice, TtsAdapter, SpeechAsset, ProgressReporter } from './contracts.js';
|
|
2
|
+
export declare function resolveSpeechCache(storyboard: string, cache?: string | false): string | undefined;
|
|
2
3
|
export declare function speechKey(segment: Narration, voice: Voice, adapter: Pick<TtsAdapter, 'id' | 'version'>): string;
|
|
4
|
+
export type VerifiedSpeechAudio = {
|
|
5
|
+
path: string;
|
|
6
|
+
format: string;
|
|
7
|
+
};
|
|
3
8
|
export type SpeechTiming = Pick<SpeechAsset, 'id' | 'duration_ms' | 'transcript' | 'alignment'>;
|
|
4
|
-
export
|
|
5
|
-
|
|
6
|
-
|
|
9
|
+
export type RetainedSpeech = {
|
|
10
|
+
timing: SpeechTiming;
|
|
11
|
+
audio?: VerifiedSpeechAudio;
|
|
12
|
+
};
|
|
13
|
+
export declare function retainedSpeechTiming(segment: Narration, voice: Voice, adapter: TtsAdapter, cache?: string): Promise<RetainedSpeech | undefined>;
|
|
14
|
+
export type VerifiedSpeech = Map<string, number>;
|
|
15
|
+
export declare function checkSpeech(asset: SpeechAsset, verified?: VerifiedSpeech): Promise<void>;
|
|
16
|
+
export declare function generateSpeech(story: Storyboard, directory: string, adapters: Map<string, TtsAdapter>, cache?: string, progress?: ProgressReporter, verified?: VerifiedSpeech): Promise<SpeechManifest>;
|
package/dist/speech.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { mkdir, copyFile, readFile } from 'node:fs/promises';
|
|
2
2
|
import { join, resolve, dirname } from 'node:path';
|
|
3
3
|
import { Ajv } from 'ajv';
|
|
4
|
-
import { digest, json, saveJson, probe, hashFile,
|
|
4
|
+
import { digest, json, saveJson, probe, hashFile, executionScope, executionSignal, audioDuration } from './media.js';
|
|
5
5
|
import { requireCondition, ProductionError } from './errors.js';
|
|
6
6
|
const speechSchema = JSON.parse(await readFile(new URL('../schemas/speech.v1.json', import.meta.url), 'utf8'));
|
|
7
7
|
const validateSpeech = new Ajv({ allErrors: true }).compile(speechSchema);
|
|
@@ -10,6 +10,11 @@ function speechPath(directory, id, format) {
|
|
|
10
10
|
requireCondition(dirname(path) === resolve(directory), 'SPEECH_PATH', `Speech destination escapes its directory: ${id}`);
|
|
11
11
|
return path;
|
|
12
12
|
}
|
|
13
|
+
export function resolveSpeechCache(storyboard, cache) {
|
|
14
|
+
if (cache === false)
|
|
15
|
+
return undefined;
|
|
16
|
+
return resolve(cache ?? join(dirname(resolve(storyboard)), '.slidevideo', 'speech'));
|
|
17
|
+
}
|
|
13
18
|
export function speechKey(segment, voice, adapter) {
|
|
14
19
|
const options = Object.fromEntries(Object.entries(voice.options ?? {}).sort(([a], [b]) => a.localeCompare(b)));
|
|
15
20
|
return digest(JSON.stringify({ text: segment.text, provider: voice.provider, voice: voice.voice, options, adapter: adapter.id, version: adapter.version }));
|
|
@@ -54,9 +59,20 @@ export async function retainedSpeechTiming(segment, voice, adapter, cache) {
|
|
|
54
59
|
return undefined;
|
|
55
60
|
requireCondition(Number.isFinite(asset.duration_ms) && asset.duration_ms > 0, 'SPEECH_DURATION', `Invalid retained speech duration: ${segment.id}`);
|
|
56
61
|
checkAlignment(asset);
|
|
57
|
-
|
|
62
|
+
let audio;
|
|
63
|
+
if (/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(asset.format)) {
|
|
64
|
+
const audioPath = resolve(dirname(cached), asset.audio);
|
|
65
|
+
if (dirname(audioPath) === resolve(cache)) {
|
|
66
|
+
try {
|
|
67
|
+
if (await hashFile(audioPath) === asset.sha256)
|
|
68
|
+
audio = { path: audioPath, format: asset.format };
|
|
69
|
+
}
|
|
70
|
+
catch { }
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return { timing: { id: segment.id, duration_ms: asset.duration_ms, transcript: asset.transcript, alignment: asset.alignment }, ...(audio ? { audio } : {}) };
|
|
58
74
|
}
|
|
59
|
-
export async function checkSpeech(asset) {
|
|
75
|
+
export async function checkSpeech(asset, verified) {
|
|
60
76
|
requireCondition(/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(asset.format), 'SPEECH_FORMAT', `Invalid speech file format for ${asset.id}`);
|
|
61
77
|
let hash;
|
|
62
78
|
try {
|
|
@@ -66,63 +82,166 @@ export async function checkSpeech(asset) {
|
|
|
66
82
|
throw new ProductionError('SPEECH_INPUT', `Cannot read speech audio for ${asset.id}: ${asset.audio}`);
|
|
67
83
|
}
|
|
68
84
|
requireCondition(hash === asset.sha256, 'SPEECH_INTEGRITY', `Speech asset changed: ${asset.id}`);
|
|
69
|
-
const
|
|
70
|
-
|
|
85
|
+
const knownDuration = verified?.get(hash);
|
|
86
|
+
if (knownDuration !== undefined) {
|
|
87
|
+
requireCondition(Math.abs(knownDuration - asset.duration_ms) < 1, 'SPEECH_DURATION', `Speech duration mismatch: ${asset.id}`);
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
const properties = await probe(asset.audio);
|
|
91
|
+
const durationMs = await audioDuration(asset.audio);
|
|
92
|
+
requireCondition(properties.has_audio && properties.duration_ms > 0 && Math.abs(durationMs - asset.duration_ms) < 1, 'SPEECH_DURATION', `Speech duration mismatch: ${asset.id}`);
|
|
93
|
+
verified?.set(hash, durationMs);
|
|
94
|
+
}
|
|
71
95
|
checkAlignment(asset);
|
|
72
96
|
}
|
|
73
|
-
|
|
97
|
+
class ConcurrencyLimiter {
|
|
98
|
+
limit;
|
|
99
|
+
active = 0;
|
|
100
|
+
queue = [];
|
|
101
|
+
constructor(limit) {
|
|
102
|
+
this.limit = limit;
|
|
103
|
+
}
|
|
104
|
+
async run(signal, fn) {
|
|
105
|
+
signal.throwIfAborted();
|
|
106
|
+
if (this.active >= this.limit) {
|
|
107
|
+
await new Promise((resolve, reject) => {
|
|
108
|
+
const onAbort = () => {
|
|
109
|
+
const index = this.queue.indexOf(release);
|
|
110
|
+
if (index >= 0)
|
|
111
|
+
this.queue.splice(index, 1);
|
|
112
|
+
reject(signal.reason);
|
|
113
|
+
};
|
|
114
|
+
const release = () => {
|
|
115
|
+
signal.removeEventListener('abort', onAbort);
|
|
116
|
+
resolve();
|
|
117
|
+
};
|
|
118
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
119
|
+
this.queue.push(release);
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
signal.throwIfAborted();
|
|
123
|
+
this.active++;
|
|
124
|
+
try {
|
|
125
|
+
return await fn();
|
|
126
|
+
}
|
|
127
|
+
finally {
|
|
128
|
+
this.active--;
|
|
129
|
+
const next = this.queue.shift();
|
|
130
|
+
if (next)
|
|
131
|
+
next();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
export async function generateSpeech(story, directory, adapters, cache, progress, verified) {
|
|
74
136
|
await mkdir(directory, { recursive: true });
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
137
|
+
const total = story.narration.length;
|
|
138
|
+
const assets = new Array(total);
|
|
139
|
+
progress?.(`Speech: ${total} segments`);
|
|
140
|
+
const prepared = story.narration.map((segment, index) => {
|
|
79
141
|
const voice = segment.voice ?? story.voice;
|
|
80
142
|
requireCondition(voice, 'VOICE_REQUIRED', `Narration ${segment.id} needs a voice`);
|
|
81
143
|
const adapter = adapters.get(voice.provider);
|
|
82
144
|
requireCondition(adapter, 'TTS_ADAPTER', `Unsupported TTS provider ${voice.provider}`, 3);
|
|
83
145
|
adapter.validate(voice);
|
|
84
146
|
const key = speechKey(segment, voice, adapter);
|
|
85
|
-
let asset;
|
|
86
147
|
const cached = cache ? join(resolve(cache), `${key}.json`) : undefined;
|
|
87
|
-
|
|
88
|
-
|
|
148
|
+
return { index, segment, voice, adapter, key, cached };
|
|
149
|
+
});
|
|
150
|
+
const parentScope = executionScope.getStore();
|
|
151
|
+
parentScope?.signal.throwIfAborted();
|
|
152
|
+
const local = new AbortController();
|
|
153
|
+
const onParentAbort = () => local.abort(parentScope.signal.reason);
|
|
154
|
+
parentScope?.signal.addEventListener('abort', onParentAbort, { once: true });
|
|
155
|
+
const providerLimiters = new Map();
|
|
156
|
+
const limiterFor = (adapter) => {
|
|
157
|
+
let limiter = providerLimiters.get(adapter.id);
|
|
158
|
+
if (!limiter) {
|
|
159
|
+
limiter = new ConcurrencyLimiter(Math.max(1, adapter.concurrency ?? 2));
|
|
160
|
+
providerLimiters.set(adapter.id, limiter);
|
|
161
|
+
}
|
|
162
|
+
return limiter;
|
|
163
|
+
};
|
|
164
|
+
const cacheLimiter = new ConcurrencyLimiter(4);
|
|
165
|
+
const inFlightByKey = new Map();
|
|
166
|
+
let started = 0;
|
|
167
|
+
let firstError;
|
|
168
|
+
const recordError = (error) => {
|
|
169
|
+
if (firstError === undefined)
|
|
170
|
+
firstError = error;
|
|
171
|
+
if (!local.signal.aborted)
|
|
172
|
+
local.abort(error);
|
|
173
|
+
};
|
|
174
|
+
try {
|
|
175
|
+
const tasks = prepared.map(({ index, segment, voice, adapter, key, cached }) => executionScope.run({ signal: local.signal, bounded: parentScope?.bounded ?? false }, async () => {
|
|
89
176
|
try {
|
|
90
|
-
|
|
177
|
+
local.signal.throwIfAborted();
|
|
178
|
+
let cachedAsset;
|
|
179
|
+
if (cached && !inFlightByKey.has(key)) {
|
|
180
|
+
let entry;
|
|
181
|
+
try {
|
|
182
|
+
entry = await json(cached);
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
if (error.code !== 'ENOENT')
|
|
186
|
+
throw new ProductionError('CACHE_INPUT', `Cannot read speech cache entry ${cached}`);
|
|
187
|
+
}
|
|
188
|
+
if (entry !== undefined) {
|
|
189
|
+
const manifest = { version: 1, assets: [entry] };
|
|
190
|
+
requireCondition(validateSpeech(manifest), 'CACHE_INPUT', `Invalid speech cache entry for ${segment.id}: ${cached}`);
|
|
191
|
+
cachedAsset = manifest.assets[0];
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (cachedAsset) {
|
|
195
|
+
const asset = await cacheLimiter.run(local.signal, async () => {
|
|
196
|
+
progress?.(`Reusing cached speech ${segment.id} (${++started}/${total})`);
|
|
197
|
+
const resolvedAudio = resolve(dirname(cached), cachedAsset.audio);
|
|
198
|
+
const candidate = { ...cachedAsset, audio: resolvedAudio };
|
|
199
|
+
requireCondition(matchesSpeechCache(candidate, segment, voice, adapter), 'CACHE_MISMATCH', `Cache does not match ${segment.id}`);
|
|
200
|
+
await checkSpeech(candidate, verified);
|
|
201
|
+
const destination = speechPath(directory, segment.id, candidate.format);
|
|
202
|
+
await copyFile(candidate.audio, destination);
|
|
203
|
+
return { ...candidate, id: segment.id, audio: destination };
|
|
204
|
+
});
|
|
205
|
+
assets[index] = asset;
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const existing = inFlightByKey.get(key);
|
|
209
|
+
if (existing) {
|
|
210
|
+
const source = await existing;
|
|
211
|
+
local.signal.throwIfAborted();
|
|
212
|
+
const destination = speechPath(directory, segment.id, source.format);
|
|
213
|
+
await copyFile(source.audio, destination);
|
|
214
|
+
assets[index] = { ...source, id: segment.id, audio: destination };
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
const synthPromise = limiterFor(adapter).run(local.signal, async () => {
|
|
218
|
+
progress?.(`Generating speech ${segment.id} (${++started}/${total})`);
|
|
219
|
+
const generated = await adapter.synthesize(segment, voice, speechPath(directory, segment.id, 'mp3'));
|
|
220
|
+
const asset = { ...generated, key };
|
|
221
|
+
await checkSpeech(asset, verified);
|
|
222
|
+
if (cached) {
|
|
223
|
+
const cachedAudio = speechPath(resolve(cache), key, asset.format);
|
|
224
|
+
await mkdir(resolve(cache), { recursive: true });
|
|
225
|
+
await copyFile(asset.audio, cachedAudio);
|
|
226
|
+
await saveJson(cached, { ...asset, audio: `${key}.${asset.format}` });
|
|
227
|
+
}
|
|
228
|
+
return asset;
|
|
229
|
+
});
|
|
230
|
+
inFlightByKey.set(key, synthPromise);
|
|
231
|
+
assets[index] = await synthPromise;
|
|
91
232
|
}
|
|
92
233
|
catch (error) {
|
|
93
|
-
|
|
94
|
-
throw new ProductionError('CACHE_INPUT', `Cannot read speech cache entry ${cached}`);
|
|
95
|
-
}
|
|
96
|
-
if (entry !== undefined) {
|
|
97
|
-
const manifest = { version: 1, assets: [entry] };
|
|
98
|
-
requireCondition(validateSpeech(manifest), 'CACHE_INPUT', `Invalid speech cache entry for ${segment.id}: ${cached}`);
|
|
99
|
-
asset = manifest.assets[0];
|
|
234
|
+
recordError(error);
|
|
100
235
|
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
await checkSpeech(asset);
|
|
107
|
-
await decode(asset.audio);
|
|
108
|
-
const destination = speechPath(directory, segment.id, asset.format);
|
|
109
|
-
await copyFile(asset.audio, destination);
|
|
110
|
-
asset = { ...asset, id: segment.id, audio: destination };
|
|
111
|
-
}
|
|
112
|
-
else {
|
|
113
|
-
progress?.(`Generating speech ${segment.id} (${assets.length + 1}/${story.narration.length})`);
|
|
114
|
-
const generated = await adapter.synthesize(segment, voice, speechPath(directory, segment.id, 'mp3'));
|
|
115
|
-
asset = { ...generated, key };
|
|
116
|
-
await checkSpeech(asset);
|
|
117
|
-
if (cached) {
|
|
118
|
-
const cachedAudio = speechPath(resolve(cache), key, asset.format);
|
|
119
|
-
await mkdir(resolve(cache), { recursive: true });
|
|
120
|
-
await copyFile(asset.audio, cachedAudio);
|
|
121
|
-
await saveJson(cached, { ...asset, audio: `${key}.${asset.format}` });
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
assets.push(asset);
|
|
236
|
+
}));
|
|
237
|
+
await Promise.allSettled(tasks);
|
|
238
|
+
}
|
|
239
|
+
finally {
|
|
240
|
+
parentScope?.signal.removeEventListener('abort', onParentAbort);
|
|
125
241
|
}
|
|
242
|
+
if (firstError !== undefined)
|
|
243
|
+
throw firstError;
|
|
244
|
+
executionSignal()?.throwIfAborted();
|
|
126
245
|
const manifest = { version: 1, assets };
|
|
127
246
|
await saveJson(join(directory, 'manifest.json'), manifest);
|
|
128
247
|
return manifest;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Annotation, StampFont } from './contracts.js';
|
|
2
|
+
export type BundledFontSpec = {
|
|
3
|
+
key: StampFont;
|
|
4
|
+
family: string;
|
|
5
|
+
files: {
|
|
6
|
+
file: string;
|
|
7
|
+
style: 'normal' | 'italic';
|
|
8
|
+
unicodeRange: string;
|
|
9
|
+
}[];
|
|
10
|
+
};
|
|
11
|
+
export declare const BUNDLED_STAMP_FONTS: readonly BundledFontSpec[];
|
|
12
|
+
export declare function bundledFontPath(file: string): string | undefined;
|
|
13
|
+
export declare function stampFontInputFiles(annotations: readonly Annotation[]): string[];
|
|
14
|
+
export declare function stampFontFaceCss(baseUrl?: string): string;
|
|
15
|
+
export declare function ensureStampFonts(): void;
|
|
16
|
+
export declare function unsupportedStampGlyph(text: string, font?: StampFont): string | undefined;
|
|
17
|
+
export declare function measureStampText(font: string, text: string): number;
|