@slidevideo/cli 0.1.1
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 +33 -0
- package/IMPRESSUM.md +13 -0
- package/LICENSE-TERMS.md +58 -0
- package/README.md +25 -0
- package/addons/slidevideo/geometry.ts +127 -0
- package/addons/slidevideo/global-top.vue +232 -0
- package/addons/slidevideo/package.json +1 -0
- package/addons/slidevideo/playback-entries.ts +14 -0
- package/addons/slidevideo/preview.ts +157 -0
- package/dist/adapters/browser-runtime.d.ts +37 -0
- package/dist/adapters/browser-runtime.js +1 -0
- package/dist/adapters/edge.d.ts +7 -0
- package/dist/adapters/edge.js +46 -0
- package/dist/adapters/elevenlabs.d.ts +7 -0
- package/dist/adapters/elevenlabs.js +58 -0
- package/dist/adapters/powerpoint-preview.d.ts +2 -0
- package/dist/adapters/powerpoint-preview.js +18 -0
- package/dist/adapters/powerpoint.d.ts +21 -0
- package/dist/adapters/powerpoint.js +434 -0
- package/dist/adapters/registry.d.ts +4 -0
- package/dist/adapters/registry.js +13 -0
- package/dist/adapters/slidev-inputs.d.ts +1 -0
- package/dist/adapters/slidev-inputs.js +86 -0
- package/dist/adapters/slidev-inspection.d.ts +3 -0
- package/dist/adapters/slidev-inspection.js +79 -0
- package/dist/adapters/slidev-server.d.ts +1 -0
- package/dist/adapters/slidev-server.js +48 -0
- package/dist/adapters/slidev.d.ts +30 -0
- package/dist/adapters/slidev.js +251 -0
- package/dist/annotation-paint.d.ts +19 -0
- package/dist/annotation-paint.js +13 -0
- package/dist/annotations.d.ts +27 -0
- package/dist/annotations.js +115 -0
- package/dist/assembly.d.ts +48 -0
- package/dist/assembly.js +138 -0
- package/dist/calibration.d.ts +24 -0
- package/dist/calibration.js +346 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +180 -0
- package/dist/compositor.d.ts +18 -0
- package/dist/compositor.js +155 -0
- package/dist/contracts.d.ts +358 -0
- package/dist/contracts.js +1 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +15 -0
- package/dist/executables.d.ts +23 -0
- package/dist/executables.js +165 -0
- package/dist/installation.d.ts +6 -0
- package/dist/installation.js +32 -0
- package/dist/license-key.d.ts +12 -0
- package/dist/license-key.js +55 -0
- package/dist/license-status.d.ts +16 -0
- package/dist/license-status.js +12 -0
- package/dist/media.d.ts +12 -0
- package/dist/media.js +57 -0
- package/dist/overlay-assets.d.ts +2 -0
- package/dist/overlay-assets.js +58 -0
- package/dist/pipeline.d.ts +50 -0
- package/dist/pipeline.js +257 -0
- package/dist/preview/contracts.d.ts +34 -0
- package/dist/preview/contracts.js +1 -0
- package/dist/preview/player.d.ts +1 -0
- package/dist/preview/player.js +129 -0
- package/dist/preview/server.d.ts +1 -0
- package/dist/preview/server.js +112 -0
- package/dist/preview/view.d.ts +1 -0
- package/dist/preview/view.js +36 -0
- package/dist/revoked-keys.json +1 -0
- package/dist/run.d.ts +12 -0
- package/dist/run.js +109 -0
- package/dist/setup-install.d.ts +7 -0
- package/dist/setup-install.js +98 -0
- package/dist/setup-license.d.ts +2 -0
- package/dist/setup-license.js +63 -0
- package/dist/setup.d.ts +34 -0
- package/dist/setup.js +218 -0
- package/dist/speech.d.ts +6 -0
- package/dist/speech.js +125 -0
- package/dist/storyboard.d.ts +6 -0
- package/dist/storyboard.js +86 -0
- package/dist/timing.d.ts +6 -0
- package/dist/timing.js +162 -0
- package/package.json +134 -0
- package/schemas/annotation-geometry.v1.json +130 -0
- package/schemas/revoked-keys.schema.json +11 -0
- package/schemas/run-manifest.v1.json +96 -0
- package/schemas/schedule.v1.json +108 -0
- package/schemas/schedule.v2.json +496 -0
- package/schemas/speech.v1.json +173 -0
- package/schemas/storyboard.v1.json +461 -0
- package/schemas/storyboard.v2.json +802 -0
- package/schemas/timing-evidence.v1.json +129 -0
- package/skills/slidevideo/SKILL.md +56 -0
- package/skills/slidevideo/references/production.md +76 -0
- package/skills/slidevideo/references/storyboard.md +272 -0
- package/tools/edge-tts/edge-tts.py +19 -0
- package/tools/edge-tts/requirements.lock +34 -0
- package/tools/powerpoint/Native.cs +277 -0
- package/tools/powerpoint/powerpoint.ps1 +714 -0
- package/tools/powerpoint/preview.ps1 +100 -0
- package/tools/powerpoint/requirements.json +11 -0
package/dist/setup.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { createInterface } from 'node:readline/promises';
|
|
4
|
+
import { parseEnv } from 'node:util';
|
|
5
|
+
import { chromium } from 'playwright';
|
|
6
|
+
import { browserCandidates, browserName, discoverExecutable, findOnPath, isExecutable, saveExecutablePaths, toolCandidate, withExecutables } from './executables.js';
|
|
7
|
+
import { requireCondition } from './errors.js';
|
|
8
|
+
import { packagePath, userConfigFile } from './installation.js';
|
|
9
|
+
import { execute } from './media.js';
|
|
10
|
+
import { ffmpegInstaller, installChromium, installEdgeEnvironment, runInstaller } from './setup-install.js';
|
|
11
|
+
import { hasLicenseTerminal, setupLicense } from './setup-license.js';
|
|
12
|
+
const windows = process.platform === 'win32';
|
|
13
|
+
const ffmpegInstructions = windows
|
|
14
|
+
? 'Install FFmpeg with winget install --id Gyan.FFmpeg --exact, or pass --ffmpeg and --ffprobe with the installed paths.'
|
|
15
|
+
: 'Install ffmpeg with libx264 and ffprobe through your distribution, or pass --ffmpeg and --ffprobe with the installed paths.';
|
|
16
|
+
const browserInstructions = 'Install Chromium and rerun setup, or pass --browser with its executable path.';
|
|
17
|
+
const edgeInstructions = `Install Python with venv support or uv, then run setup with --install. For manual setup, install the packages from ${packagePath('tools', 'edge-tts', 'requirements.lock')} in a virtual environment, then pass its interpreter with --python.`;
|
|
18
|
+
async function checkTool(tool, verify, instructions) {
|
|
19
|
+
const candidate = toolCandidate(tool);
|
|
20
|
+
if (!candidate || !isExecutable(candidate.path)) {
|
|
21
|
+
return { name: tool, ready: false, detail: `${candidate ? `Unavailable at ${candidate.path}. ` : ''}${instructions}` };
|
|
22
|
+
}
|
|
23
|
+
try {
|
|
24
|
+
const detail = await verify(candidate.path);
|
|
25
|
+
return { name: tool, ready: true, detail: `${detail} at ${candidate.path}` };
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
29
|
+
return { name: tool, ready: false, detail: `${candidate.path}: ${reason.split('\n')[0]}. ${instructions}` };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
async function powerpointChecks() {
|
|
33
|
+
const path = process.env.SystemRoot && join(process.env.SystemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
34
|
+
const powershell = path && isExecutable(path) ? path : findOnPath('powershell');
|
|
35
|
+
let result;
|
|
36
|
+
if (powershell) {
|
|
37
|
+
try {
|
|
38
|
+
result = JSON.parse((await execute(powershell, [
|
|
39
|
+
'-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
|
|
40
|
+
'-File', packagePath('tools', 'powerpoint', 'powerpoint.ps1'), '-CheckSetup',
|
|
41
|
+
], 30000)).toString());
|
|
42
|
+
}
|
|
43
|
+
catch { }
|
|
44
|
+
}
|
|
45
|
+
return [
|
|
46
|
+
{ name: 'powershell', ready: result?.powershell === true, detail: result?.powershell ? 'Windows PowerShell 5.1' : 'Enable Windows PowerShell 5.1 and its built-in .NET assemblies.' },
|
|
47
|
+
{ name: 'powerpoint', ready: result?.powerpoint === true, detail: result?.powerpoint ? 'Desktop PowerPoint is registered' : 'Install desktop PowerPoint and open it once.' },
|
|
48
|
+
{ name: 'desktop', ready: result?.desktop === true, detail: result?.desktop ? 'The interactive desktop is unlocked' : 'Run setup from a signed-in, unlocked Windows desktop.' },
|
|
49
|
+
];
|
|
50
|
+
}
|
|
51
|
+
async function checkBrowser(path) {
|
|
52
|
+
const name = browserName(path);
|
|
53
|
+
if (name === 'Google Chrome' || name === 'Microsoft Edge')
|
|
54
|
+
throw new Error(`${name} recording is unverified`);
|
|
55
|
+
const browser = await chromium.launch({ executablePath: path, headless: true, args: ['--no-sandbox', '--disable-dev-shm-usage'], timeout: 15000 });
|
|
56
|
+
try {
|
|
57
|
+
return `${name} ${browser.version()} launched`;
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
await browser.close();
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
async function checkPython(path) {
|
|
64
|
+
const lock = await readFile(packagePath('tools', 'edge-tts', 'requirements.lock'), 'utf8');
|
|
65
|
+
const requirements = [...lock.matchAll(/^([\w.-]+)==([^\s]+)$/gm)].map(([, name, version]) => [name, version]);
|
|
66
|
+
const probe = [
|
|
67
|
+
'import importlib.metadata as metadata, json, sys, edge_tts',
|
|
68
|
+
'for name, version in json.loads(sys.argv[1]):',
|
|
69
|
+
' if metadata.version(name) != version: sys.exit(f"{name} must have version {version}")',
|
|
70
|
+
'print(f"Python {sys.version.split()[0]} with Edge TTS {edge_tts.__version__}")',
|
|
71
|
+
].join('\n');
|
|
72
|
+
return (await execute(path, ['-c', probe, JSON.stringify(requirements)], 10000)).toString().trim();
|
|
73
|
+
}
|
|
74
|
+
async function choices(options) {
|
|
75
|
+
let { presentation, provider, 'voice-id': voiceId } = options;
|
|
76
|
+
const { install, manual } = options;
|
|
77
|
+
requireCondition(!(install && manual), 'OPTION', 'Choose either --install or --manual');
|
|
78
|
+
const interactive = process.stdin.isTTY && !options.json && !options.quiet;
|
|
79
|
+
if (interactive) {
|
|
80
|
+
const reader = createInterface({ input: process.stdin, output: process.stderr });
|
|
81
|
+
try {
|
|
82
|
+
presentation ??= (await reader.question('Presentation format (slidev/powerpoint) [slidev]: ')).trim().toLowerCase() || 'slidev';
|
|
83
|
+
provider ??= (await reader.question('Speech provider (edge-tts/elevenlabs) [edge-tts]: ')).trim().toLowerCase() || 'edge-tts';
|
|
84
|
+
if (provider === 'elevenlabs' && voiceId === undefined)
|
|
85
|
+
voiceId = await reader.question('ElevenLabs voice ID: ');
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
reader.close();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
requireCondition(presentation === 'slidev' || presentation === 'powerpoint', 'OPTION', 'Set --presentation to slidev or powerpoint');
|
|
92
|
+
requireCondition(provider === 'edge-tts' || provider === 'elevenlabs', 'OPTION', 'Set --provider to edge-tts or elevenlabs');
|
|
93
|
+
return { presentation, provider, voiceId: voiceId?.trim() || (provider === 'edge-tts' ? 'en-US-AriaNeural' : ''), install, manual, interactive };
|
|
94
|
+
}
|
|
95
|
+
export async function setup(options) {
|
|
96
|
+
const { presentation, provider, voiceId, install, manual, interactive } = await choices(options);
|
|
97
|
+
if (interactive && hasLicenseTerminal())
|
|
98
|
+
await setupLicense();
|
|
99
|
+
const supported = (process.platform === 'linux' || windows) && (presentation === 'slidev' || windows);
|
|
100
|
+
const installed = {};
|
|
101
|
+
const installationErrors = [];
|
|
102
|
+
const checks = async () => {
|
|
103
|
+
if (!supported)
|
|
104
|
+
return [{ name: 'platform', ready: false, detail: presentation === 'powerpoint' ? 'Use Windows with installed desktop PowerPoint.' : 'Use Linux or Windows.' }];
|
|
105
|
+
const media = [
|
|
106
|
+
checkTool('ffmpeg', async (path) => {
|
|
107
|
+
const encoders = (await execute(path, ['-hide_banner', '-encoders'], 10000)).toString();
|
|
108
|
+
if (!/^\s*V\S*\s+libx264\s/m.test(encoders))
|
|
109
|
+
throw new Error('FFmpeg needs the libx264 encoder');
|
|
110
|
+
if (presentation === 'powerpoint') {
|
|
111
|
+
const devices = (await execute(path, ['-hide_banner', '-devices'], 10000)).toString();
|
|
112
|
+
if (!/\bgdigrab\b/.test(devices))
|
|
113
|
+
throw new Error('FFmpeg needs the gdigrab input');
|
|
114
|
+
}
|
|
115
|
+
return (await execute(path, ['-version'], 10000)).toString().split(/\r?\n/, 1)[0];
|
|
116
|
+
}, ffmpegInstructions),
|
|
117
|
+
checkTool('ffprobe', async (path) => {
|
|
118
|
+
const version = (await execute(path, ['-version'], 10000)).toString().split(/\r?\n/, 1)[0];
|
|
119
|
+
if (!version.startsWith('ffprobe version '))
|
|
120
|
+
throw new Error('Expected the ffprobe executable');
|
|
121
|
+
return version;
|
|
122
|
+
}, ffmpegInstructions),
|
|
123
|
+
];
|
|
124
|
+
const visual = presentation === 'slidev'
|
|
125
|
+
? checkTool('browser', checkBrowser, browserInstructions).then(check => [check])
|
|
126
|
+
: powerpointChecks();
|
|
127
|
+
const speech = provider === 'edge-tts'
|
|
128
|
+
? checkTool('python', checkPython, edgeInstructions).then(check => [check])
|
|
129
|
+
: (async () => {
|
|
130
|
+
const dotenv = await readFile('.env', 'utf8').catch((error) => {
|
|
131
|
+
if (error.code === 'ENOENT')
|
|
132
|
+
return '';
|
|
133
|
+
throw error;
|
|
134
|
+
});
|
|
135
|
+
const credentials = parseEnv(dotenv);
|
|
136
|
+
const hasKey = !!(process.env.ELEVENLABS_API_KEY ?? credentials.ELEVENLABS_API_KEY ?? process.env.ELEVENLABS_KEY ?? credentials.ELEVENLABS_KEY)?.trim();
|
|
137
|
+
return [
|
|
138
|
+
{ name: 'elevenlabs-key', ready: hasKey, detail: hasKey ? 'ElevenLabs API key is set' : 'Set ELEVENLABS_API_KEY in your environment or project .env file.' },
|
|
139
|
+
{ name: 'elevenlabs-voice', ready: !!voiceId, detail: voiceId ? 'ElevenLabs voice ID supplied' : 'Pass --voice-id with your ElevenLabs voice ID.' },
|
|
140
|
+
];
|
|
141
|
+
})();
|
|
142
|
+
const [video, audio, ...mediaTools] = await Promise.all([visual, speech, ...media]);
|
|
143
|
+
return [...mediaTools, ...video, ...audio];
|
|
144
|
+
};
|
|
145
|
+
let dependencies = await checks();
|
|
146
|
+
const missing = (...names) => dependencies.some(check => !check.ready && names.includes(check.name));
|
|
147
|
+
const ffmpeg = missing('ffmpeg', 'ffprobe') ? ffmpegInstaller() : undefined;
|
|
148
|
+
const canInstall = ffmpeg || missing('browser', 'python');
|
|
149
|
+
let runInstall = install;
|
|
150
|
+
if (interactive && !install && !manual && canInstall) {
|
|
151
|
+
for (const check of dependencies.filter(check => !check.ready))
|
|
152
|
+
console.error(check.detail);
|
|
153
|
+
const reader = createInterface({ input: process.stdin, output: process.stderr });
|
|
154
|
+
try {
|
|
155
|
+
runInstall = /^y(?:es)?$/i.test((await reader.question('Install the supported missing dependencies now? [y/N]: ')).trim());
|
|
156
|
+
}
|
|
157
|
+
finally {
|
|
158
|
+
reader.close();
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (runInstall && canInstall) {
|
|
162
|
+
const attempt = async (name, operation) => {
|
|
163
|
+
try {
|
|
164
|
+
await operation();
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
installationErrors.push(`${name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
if (ffmpeg)
|
|
171
|
+
await attempt('FFmpeg', async () => {
|
|
172
|
+
await runInstaller(ffmpeg.command, ffmpeg.args);
|
|
173
|
+
for (const tool of ['ffmpeg', 'ffprobe']) {
|
|
174
|
+
if (!missing(tool))
|
|
175
|
+
continue;
|
|
176
|
+
const path = discoverExecutable(tool);
|
|
177
|
+
if (path)
|
|
178
|
+
installed[tool] = path;
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
if (missing('browser'))
|
|
182
|
+
await attempt('Chromium', async () => { installed.browser = await installChromium(); });
|
|
183
|
+
if (missing('python'))
|
|
184
|
+
await attempt('Edge TTS', async () => { installed.python = await installEdgeEnvironment(); });
|
|
185
|
+
dependencies = await withExecutables({ ...options, ...installed }, checks);
|
|
186
|
+
}
|
|
187
|
+
const paths = {};
|
|
188
|
+
for (const tool of ['browser', 'python', 'ffmpeg', 'ffprobe']) {
|
|
189
|
+
if (!dependencies.some(check => check.name === tool && check.ready))
|
|
190
|
+
continue;
|
|
191
|
+
const path = installed[tool] ?? (options[tool] !== undefined ? toolCandidate(tool)?.path : undefined);
|
|
192
|
+
if (path)
|
|
193
|
+
paths[tool] = path;
|
|
194
|
+
}
|
|
195
|
+
if (Object.keys(paths).length)
|
|
196
|
+
await saveExecutablePaths(paths);
|
|
197
|
+
const browsers = presentation === 'slidev' ? browserCandidates() : [];
|
|
198
|
+
const selected = installed.browser ?? toolCandidate('browser')?.path;
|
|
199
|
+
if (presentation === 'slidev' && selected && isExecutable(selected) && !browsers.some(item => item.path === selected)) {
|
|
200
|
+
browsers.push({ path: selected, name: browserName(selected) });
|
|
201
|
+
}
|
|
202
|
+
const browserRequirement = presentation === 'slidev'
|
|
203
|
+
? 'Slidev recording needs Chromium. The packaged release check uses Chromium on Linux. Google Chrome and Microsoft Edge are detected but their capture workflows are unverified.'
|
|
204
|
+
: undefined;
|
|
205
|
+
return {
|
|
206
|
+
version: 1,
|
|
207
|
+
command: 'setup',
|
|
208
|
+
status: dependencies.every(check => check.ready) ? 'ready' : 'missing_dependencies',
|
|
209
|
+
presentation,
|
|
210
|
+
voice: { provider, voice: voiceId || 'your-voice-id' },
|
|
211
|
+
config_file: userConfigFile(),
|
|
212
|
+
saved_paths: paths,
|
|
213
|
+
checks: dependencies,
|
|
214
|
+
browsers,
|
|
215
|
+
browser_requirement: browserRequirement,
|
|
216
|
+
installation_errors: installationErrors,
|
|
217
|
+
};
|
|
218
|
+
}
|
package/dist/speech.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { SpeechManifest, Storyboard, Narration, Voice, TtsAdapter, SpeechAsset, ProgressReporter } from './contracts.js';
|
|
2
|
+
export declare function speechKey(segment: Narration, voice: Voice, adapter: Pick<TtsAdapter, 'id' | 'version'>): string;
|
|
3
|
+
export type SpeechTiming = Pick<SpeechAsset, 'id' | 'duration_ms' | 'transcript' | 'alignment'>;
|
|
4
|
+
export declare function retainedSpeechTiming(segment: Narration, voice: Voice, adapter: TtsAdapter, cache?: string): Promise<SpeechTiming | undefined>;
|
|
5
|
+
export declare function checkSpeech(asset: SpeechAsset): Promise<void>;
|
|
6
|
+
export declare function generateSpeech(story: Storyboard, directory: string, adapters: Map<string, TtsAdapter>, cache?: string, progress?: ProgressReporter): Promise<SpeechManifest>;
|
package/dist/speech.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { mkdir, copyFile, readFile } from 'node:fs/promises';
|
|
2
|
+
import { join, resolve, dirname } from 'node:path';
|
|
3
|
+
import { Ajv } from 'ajv';
|
|
4
|
+
import { digest, json, saveJson, probe, hashFile, decode, executionScope, audioDuration } from './media.js';
|
|
5
|
+
import { requireCondition, ProductionError } from './errors.js';
|
|
6
|
+
const speechSchema = JSON.parse(await readFile(new URL('../schemas/speech.v1.json', import.meta.url), 'utf8'));
|
|
7
|
+
const validateSpeech = new Ajv({ allErrors: true }).compile(speechSchema);
|
|
8
|
+
function speechPath(directory, id, format) {
|
|
9
|
+
const path = resolve(directory, `${id}.${format}`);
|
|
10
|
+
requireCondition(dirname(path) === resolve(directory), 'SPEECH_PATH', `Speech destination escapes its directory: ${id}`);
|
|
11
|
+
return path;
|
|
12
|
+
}
|
|
13
|
+
export function speechKey(segment, voice, adapter) {
|
|
14
|
+
const options = Object.fromEntries(Object.entries(voice.options ?? {}).sort(([a], [b]) => a.localeCompare(b)));
|
|
15
|
+
return digest(JSON.stringify({ text: segment.text, provider: voice.provider, voice: voice.voice, options, adapter: adapter.id, version: adapter.version }));
|
|
16
|
+
}
|
|
17
|
+
function checkAlignment(asset) {
|
|
18
|
+
if (asset.alignment) {
|
|
19
|
+
const alignment = asset.alignment;
|
|
20
|
+
requireCondition(alignment.text === asset.transcript[alignment.form], 'ALIGNMENT_TEXT', `Alignment transcript mismatch: ${asset.id}`);
|
|
21
|
+
let end = 0;
|
|
22
|
+
let time = 0;
|
|
23
|
+
for (const unit of alignment.units) {
|
|
24
|
+
requireCondition(Number.isFinite(unit.start_ms) && Number.isFinite(unit.end_ms) && unit.start >= end && unit.start_ms >= time && unit.end_ms >= unit.start_ms && unit.end_ms <= asset.duration_ms + 100 && alignment.text.slice(unit.start, unit.end) === unit.text, 'ALIGNMENT_DATA', `Invalid alignment: ${asset.id}`);
|
|
25
|
+
end = unit.end;
|
|
26
|
+
time = unit.start_ms;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export async function retainedSpeechTiming(segment, voice, adapter, cache) {
|
|
31
|
+
if (!cache)
|
|
32
|
+
return undefined;
|
|
33
|
+
const key = speechKey(segment, voice, adapter);
|
|
34
|
+
const cached = join(resolve(cache), `${key}.json`);
|
|
35
|
+
let entry;
|
|
36
|
+
try {
|
|
37
|
+
entry = await json(cached);
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
if (error.code === 'ENOENT')
|
|
41
|
+
return undefined;
|
|
42
|
+
throw new ProductionError('CACHE_INPUT', `Cannot read speech cache entry ${cached}`);
|
|
43
|
+
}
|
|
44
|
+
const manifest = { version: 1, assets: [entry] };
|
|
45
|
+
requireCondition(validateSpeech(manifest), 'CACHE_INPUT', `Invalid speech cache entry for ${segment.id}: ${cached}`);
|
|
46
|
+
const asset = manifest.assets[0];
|
|
47
|
+
const provenance = asset.provenance;
|
|
48
|
+
const provenanceKey = speechKey({ ...segment, text: asset.transcript.original }, { provider: provenance.provider, voice: provenance.voice, options: provenance.options }, { id: provenance.adapter, version: provenance.version });
|
|
49
|
+
if (asset.key !== key || provenanceKey !== key || asset.transcript.original !== segment.text)
|
|
50
|
+
return undefined;
|
|
51
|
+
requireCondition(Number.isFinite(asset.duration_ms) && asset.duration_ms > 0, 'SPEECH_DURATION', `Invalid retained speech duration: ${segment.id}`);
|
|
52
|
+
checkAlignment(asset);
|
|
53
|
+
return { id: segment.id, duration_ms: asset.duration_ms, transcript: asset.transcript, alignment: asset.alignment };
|
|
54
|
+
}
|
|
55
|
+
export async function checkSpeech(asset) {
|
|
56
|
+
requireCondition(/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(asset.format), 'SPEECH_FORMAT', `Invalid speech file format for ${asset.id}`);
|
|
57
|
+
let hash;
|
|
58
|
+
try {
|
|
59
|
+
hash = await hashFile(asset.audio);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
throw new ProductionError('SPEECH_INPUT', `Cannot read speech audio for ${asset.id}: ${asset.audio}`);
|
|
63
|
+
}
|
|
64
|
+
requireCondition(hash === asset.sha256, 'SPEECH_INTEGRITY', `Speech asset changed: ${asset.id}`);
|
|
65
|
+
const properties = await probe(asset.audio);
|
|
66
|
+
requireCondition(properties.has_audio && properties.duration_ms > 0 && Math.abs(await audioDuration(asset.audio) - asset.duration_ms) < 1, 'SPEECH_DURATION', `Speech duration mismatch: ${asset.id}`);
|
|
67
|
+
checkAlignment(asset);
|
|
68
|
+
}
|
|
69
|
+
export async function generateSpeech(story, directory, adapters, cache, progress) {
|
|
70
|
+
await mkdir(directory, { recursive: true });
|
|
71
|
+
const assets = [];
|
|
72
|
+
progress?.(`Speech: ${story.narration.length} segments`);
|
|
73
|
+
for (const segment of story.narration) {
|
|
74
|
+
executionScope.getStore()?.throwIfAborted();
|
|
75
|
+
const voice = segment.voice ?? story.voice;
|
|
76
|
+
requireCondition(voice, 'VOICE_REQUIRED', `Narration ${segment.id} needs a voice`);
|
|
77
|
+
const adapter = adapters.get(voice.provider);
|
|
78
|
+
requireCondition(adapter, 'TTS_ADAPTER', `Unsupported TTS provider ${voice.provider}`, 3);
|
|
79
|
+
adapter.validate(voice);
|
|
80
|
+
const key = speechKey(segment, voice, adapter);
|
|
81
|
+
let asset;
|
|
82
|
+
const cached = cache ? join(resolve(cache), `${key}.json`) : undefined;
|
|
83
|
+
if (cached) {
|
|
84
|
+
let entry;
|
|
85
|
+
try {
|
|
86
|
+
entry = await json(cached);
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
if (error.code !== 'ENOENT')
|
|
90
|
+
throw new ProductionError('CACHE_INPUT', `Cannot read speech cache entry ${cached}`);
|
|
91
|
+
}
|
|
92
|
+
if (entry !== undefined) {
|
|
93
|
+
const manifest = { version: 1, assets: [entry] };
|
|
94
|
+
requireCondition(validateSpeech(manifest), 'CACHE_INPUT', `Invalid speech cache entry for ${segment.id}: ${cached}`);
|
|
95
|
+
asset = manifest.assets[0];
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (asset) {
|
|
99
|
+
progress?.(`Reusing cached speech ${segment.id} (${assets.length + 1}/${story.narration.length})`);
|
|
100
|
+
asset.audio = resolve(dirname(cached), asset.audio);
|
|
101
|
+
requireCondition(asset.key === key && asset.transcript.original === segment.text, 'CACHE_MISMATCH', `Cache does not match ${segment.id}`);
|
|
102
|
+
await checkSpeech(asset);
|
|
103
|
+
await decode(asset.audio);
|
|
104
|
+
const destination = speechPath(directory, segment.id, asset.format);
|
|
105
|
+
await copyFile(asset.audio, destination);
|
|
106
|
+
asset = { ...asset, id: segment.id, audio: destination };
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
progress?.(`Generating speech ${segment.id} (${assets.length + 1}/${story.narration.length})`);
|
|
110
|
+
const generated = await adapter.synthesize(segment, voice, speechPath(directory, segment.id, 'mp3'));
|
|
111
|
+
asset = { ...generated, key };
|
|
112
|
+
await checkSpeech(asset);
|
|
113
|
+
if (cached) {
|
|
114
|
+
const cachedAudio = speechPath(resolve(cache), key, asset.format);
|
|
115
|
+
await mkdir(resolve(cache), { recursive: true });
|
|
116
|
+
await copyFile(asset.audio, cachedAudio);
|
|
117
|
+
await saveJson(cached, { ...asset, audio: cachedAudio });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
assets.push(asset);
|
|
121
|
+
}
|
|
122
|
+
const manifest = { version: 1, assets };
|
|
123
|
+
await saveJson(join(directory, 'manifest.json'), manifest);
|
|
124
|
+
return manifest;
|
|
125
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Storyboard } from './contracts.js';
|
|
2
|
+
export declare function loadStoryboard(file: string): Promise<Storyboard>;
|
|
3
|
+
export declare function fingerprint(storyboard: string, files: string[]): Promise<{
|
|
4
|
+
inputs: Record<string, string>;
|
|
5
|
+
input_hash: string;
|
|
6
|
+
}>;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { dirname, extname, isAbsolute, resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { parse } from 'yaml';
|
|
5
|
+
import { Ajv } from 'ajv';
|
|
6
|
+
import { requireCondition, ProductionError } from './errors.js';
|
|
7
|
+
import { hashFile, digest } from './media.js';
|
|
8
|
+
const validators = await Promise.all([1, 2].map(async (version) => new Ajv({ allErrors: true }).compile(JSON.parse(await readFile(fileURLToPath(new URL(`../schemas/storyboard.v${version}.json`, import.meta.url)), 'utf8')))));
|
|
9
|
+
export async function loadStoryboard(file) {
|
|
10
|
+
let data;
|
|
11
|
+
try {
|
|
12
|
+
data = parse(await readFile(file, 'utf8'));
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
throw new ProductionError('STORYBOARD', `Cannot read storyboard: ${String(error)}`);
|
|
16
|
+
}
|
|
17
|
+
const version = data && typeof data === 'object' && 'version' in data ? data.version : undefined;
|
|
18
|
+
requireCondition(version === 1 || version === 2, 'SCHEMA', 'Storyboard version must be 1 or 2');
|
|
19
|
+
const validate = validators[version - 1];
|
|
20
|
+
requireCondition(validate(data), 'SCHEMA', JSON.stringify(validate.errors));
|
|
21
|
+
data.deck = resolve(dirname(file), data.deck);
|
|
22
|
+
data.media = data.media.map(media => ({ ...media, src: resolve(dirname(file), media.src) }));
|
|
23
|
+
const ids = new Set();
|
|
24
|
+
for (const item of [...data.scenes, ...data.narration, ...data.media, ...data.cues, ...(data.annotations ?? []), ...(data.overlays ?? []), ...data.scenes.flatMap(s => s.actions)]) {
|
|
25
|
+
requireCondition(!ids.has(item.id), 'DUPLICATE_ID', `Duplicate stable ID ${item.id}`);
|
|
26
|
+
ids.add(item.id);
|
|
27
|
+
}
|
|
28
|
+
const segments = new Set(data.narration.map(n => n.id));
|
|
29
|
+
const spoken = new Set();
|
|
30
|
+
const mediaIds = new Set(data.media.map(m => m.id));
|
|
31
|
+
for (const scene of data.scenes)
|
|
32
|
+
for (const action of scene.actions) {
|
|
33
|
+
if (action.type === 'speak') {
|
|
34
|
+
requireCondition(segments.has(action.segment) && !spoken.has(action.segment), 'SEGMENT_REFERENCE', `Narration ${action.segment} must exist and be scheduled once`);
|
|
35
|
+
spoken.add(action.segment);
|
|
36
|
+
}
|
|
37
|
+
if (action.type === 'play')
|
|
38
|
+
requireCondition(mediaIds.has(action.media), 'MEDIA_REFERENCE', `Unknown media ${action.media}`);
|
|
39
|
+
}
|
|
40
|
+
requireCondition(spoken.size === segments.size, 'UNSCHEDULED_NARRATION', 'Each narration segment must be scheduled exactly once');
|
|
41
|
+
for (const cue of data.cues) {
|
|
42
|
+
requireCondition(segments.has(cue.at.segment), 'CUE_REFERENCE', `Cue ${cue.id} references unknown narration ${cue.at.segment}`);
|
|
43
|
+
if (cue.action.type === 'play')
|
|
44
|
+
requireCondition(mediaIds.has(cue.action.media), 'MEDIA_REFERENCE', `Unknown media ${cue.action.media}`);
|
|
45
|
+
}
|
|
46
|
+
for (const annotation of data.annotations ?? []) {
|
|
47
|
+
const context = { annotation: annotation.id, target: annotation.target };
|
|
48
|
+
requireCondition(data.scenes.some(scene => scene.id === annotation.scene), 'ANNOTATION_SCENE', `Annotation ${annotation.id}: unknown scene ${annotation.scene}`, 2, context);
|
|
49
|
+
requireCondition(segments.has(annotation.at.segment), 'CUE_REFERENCE', `Annotation ${annotation.id}: unknown narration ${annotation.at.segment}`, 2, context);
|
|
50
|
+
if (annotation.target.type === 'region') {
|
|
51
|
+
const { x, y, width, height } = annotation.target;
|
|
52
|
+
requireCondition(x + width <= 1 && y + height <= 1, 'ANNOTATION_BOUNDS', `Annotation ${annotation.id}: region exceeds normalized slide bounds`, 2, context);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const scenes = new Set(data.scenes.map(scene => scene.id));
|
|
56
|
+
for (const overlay of data.overlays ?? []) {
|
|
57
|
+
const { x, y, width, height } = overlay.box;
|
|
58
|
+
requireCondition(x + width <= 1 && y + height <= 1, 'OVERLAY_BOUNDS', `Overlay ${overlay.id}: box exceeds the output frame`);
|
|
59
|
+
requireCondition(!isAbsolute(overlay.src) && /^(\.png|\.svg)$/i.test(extname(overlay.src)), 'OVERLAY_ASSET', `Overlay ${overlay.id}: supply a storyboard-relative PNG or SVG path`);
|
|
60
|
+
overlay.src = resolve(dirname(file), overlay.src);
|
|
61
|
+
for (const scene of [overlay.scene, ...(overlay.hide_in_scenes ?? [])]) {
|
|
62
|
+
requireCondition(scene === undefined || scenes.has(scene), 'OVERLAY_SCENE', `Overlay ${overlay.id}: unknown scene ${scene}`);
|
|
63
|
+
}
|
|
64
|
+
requireCondition(!overlay.scene || !overlay.hide_in_scenes, 'OVERLAY_SCENE', `Overlay ${overlay.id}: only video-wide overlays can hide in scenes`);
|
|
65
|
+
for (const { start, end } of overlay.visible ?? []) {
|
|
66
|
+
for (const boundary of [start, end]) {
|
|
67
|
+
requireCondition(typeof boundary === 'number' || segments.has(boundary.segment), 'CUE_REFERENCE', `Overlay ${overlay.id}: unknown narration segment`);
|
|
68
|
+
requireCondition(typeof boundary === 'number' || !overlay.scene || data.scenes
|
|
69
|
+
.find(scene => scene.id === overlay.scene)?.actions.some(action => action.type === 'speak' && action.segment === boundary.segment), 'OVERLAY_SCENE', `Overlay ${overlay.id}: phrase boundaries must refer to narration in scene ${overlay.scene}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return data;
|
|
74
|
+
}
|
|
75
|
+
export async function fingerprint(storyboard, files) {
|
|
76
|
+
const inputs = {};
|
|
77
|
+
for (const path of [...new Set([storyboard, ...files])].sort()) {
|
|
78
|
+
try {
|
|
79
|
+
inputs[path] = await hashFile(path);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
throw new ProductionError('MISSING_INPUT', `Cannot read required input ${path}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return { inputs, input_hash: digest(JSON.stringify(inputs)) };
|
|
86
|
+
}
|
package/dist/timing.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Schedule, SpeechManifest, Storyboard, TtsAdapter } from './contracts.js';
|
|
2
|
+
export declare function resolveTiming(story: Storyboard, speech: SpeechManifest): Promise<Schedule>;
|
|
3
|
+
export declare function resolvePreviewTiming(story: Storyboard, adapters: ReadonlyMap<string, TtsAdapter>, cache?: string): Promise<{
|
|
4
|
+
schedule: Schedule;
|
|
5
|
+
approximate: string[];
|
|
6
|
+
}>;
|
package/dist/timing.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { requireCondition } from './errors.js';
|
|
2
|
+
import { probe } from './media.js';
|
|
3
|
+
import { checkSpeech, retainedSpeechTiming } from './speech.js';
|
|
4
|
+
export async function resolveTiming(story, speech) {
|
|
5
|
+
for (const asset of speech.assets)
|
|
6
|
+
await checkSpeech(asset);
|
|
7
|
+
return resolveSchedule(story, speech.assets);
|
|
8
|
+
}
|
|
9
|
+
export async function resolvePreviewTiming(story, adapters, cache) {
|
|
10
|
+
const assets = [];
|
|
11
|
+
const approximate = [];
|
|
12
|
+
for (const segment of story.narration) {
|
|
13
|
+
const voice = segment.voice ?? story.voice;
|
|
14
|
+
requireCondition(voice, 'VOICE_REQUIRED', `Narration ${segment.id} needs a voice`);
|
|
15
|
+
const adapter = adapters.get(voice.provider);
|
|
16
|
+
requireCondition(adapter, 'TTS_ADAPTER', `Unsupported TTS provider ${voice.provider}`, 3);
|
|
17
|
+
adapter.validate(voice);
|
|
18
|
+
const retained = await retainedSpeechTiming(segment, voice, adapter, cache);
|
|
19
|
+
if (retained)
|
|
20
|
+
assets.push(retained);
|
|
21
|
+
else {
|
|
22
|
+
approximate.push(segment.id);
|
|
23
|
+
const words = segment.text.trim().split(/\s+/).filter(Boolean).length;
|
|
24
|
+
assets.push({ id: segment.id, duration_ms: Math.max(1000, words * 60000 / 150), transcript: { original: segment.text, normalized: segment.text }, alignment: null });
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return { schedule: await resolveSchedule(story, assets), approximate };
|
|
28
|
+
}
|
|
29
|
+
async function resolveSchedule(story, speech) {
|
|
30
|
+
const media = await Promise.all(story.media.map(async (item) => ({ ...item, ...await probe(item.src) })));
|
|
31
|
+
const assets = new Map(speech.map(asset => [asset.id, asset]));
|
|
32
|
+
const actions = [];
|
|
33
|
+
const segments = new Map();
|
|
34
|
+
let cursor = 0;
|
|
35
|
+
const sceneRanges = new Map();
|
|
36
|
+
function duration(action) {
|
|
37
|
+
if (action.type === 'speak') {
|
|
38
|
+
const asset = assets.get(action.segment);
|
|
39
|
+
requireCondition(asset, 'MISSING_SPEECH', `Generate speech before resolving ${action.segment}`);
|
|
40
|
+
requireCondition(asset.transcript.original === story.narration.find(n => n.id === action.segment)?.text, 'SPEECH_MISMATCH', `Speech text changed: ${action.segment}`);
|
|
41
|
+
return asset.duration_ms;
|
|
42
|
+
}
|
|
43
|
+
if (action.type === 'play') {
|
|
44
|
+
const clip = media.find(item => item.id === action.media);
|
|
45
|
+
const start = action.trim_start_ms ?? 0;
|
|
46
|
+
const end = action.trim_end_ms ?? clip.duration_ms;
|
|
47
|
+
requireCondition(start < end && end <= clip.duration_ms, 'MEDIA_TRIM', `Invalid trim for ${action.id}`);
|
|
48
|
+
requireCondition(action.audio !== 'source' || clip.has_audio, 'MEDIA_AUDIO', `Source audio missing for ${action.id}`);
|
|
49
|
+
return (end - start) / (action.rate ?? 1);
|
|
50
|
+
}
|
|
51
|
+
return action.duration_ms;
|
|
52
|
+
}
|
|
53
|
+
for (const scene of story.scenes) {
|
|
54
|
+
const start = cursor;
|
|
55
|
+
actions.push({ id: `${scene.id}:slide`, scene: scene.id, start_ms: cursor, end_ms: cursor, action: { id: `${scene.id}:slide`, type: 'slide', target: scene.slide, duration_ms: 0 } });
|
|
56
|
+
for (const action of scene.actions) {
|
|
57
|
+
const item = { id: action.id, scene: scene.id, start_ms: cursor, end_ms: cursor + duration(action), action };
|
|
58
|
+
actions.push(item);
|
|
59
|
+
if (action.type === 'speak')
|
|
60
|
+
segments.set(action.segment, item);
|
|
61
|
+
cursor = item.end_ms;
|
|
62
|
+
}
|
|
63
|
+
if (scene.duration_ms !== undefined) {
|
|
64
|
+
requireCondition(cursor - start <= scene.duration_ms, 'SCENE_DURATION', `Actions exceed fixed duration of scene ${scene.id}`);
|
|
65
|
+
cursor = start + scene.duration_ms;
|
|
66
|
+
}
|
|
67
|
+
sceneRanges.set(scene.id, { start, end: cursor });
|
|
68
|
+
}
|
|
69
|
+
function phrase(cue, annotation) {
|
|
70
|
+
const segment = segments.get(cue.at.segment);
|
|
71
|
+
const asset = assets.get(cue.at.segment);
|
|
72
|
+
const alignment = asset.alignment;
|
|
73
|
+
const context = { cue: cue.id, segment: cue.at.segment, ...(annotation ? { annotation: cue.id, target: annotation } : {}) };
|
|
74
|
+
requireCondition(alignment && alignment.units.length > 0, 'CUE_ALIGNMENT_REQUIRED', `Cue ${cue.id} requires alignment for ${cue.at.segment}`, 2, context);
|
|
75
|
+
const matches = [];
|
|
76
|
+
let pos = alignment.text.indexOf(cue.at.phrase);
|
|
77
|
+
while (pos >= 0) {
|
|
78
|
+
matches.push(pos);
|
|
79
|
+
pos = alignment.text.indexOf(cue.at.phrase, pos + 1);
|
|
80
|
+
}
|
|
81
|
+
requireCondition(matches.length > 0, 'CUE_PHRASE_MISSING', `Cue ${cue.id}: phrase not found in ${alignment.form} transcript`, 2, context);
|
|
82
|
+
requireCondition(cue.at.occurrence !== undefined || matches.length === 1, 'CUE_AMBIGUOUS', `Cue ${cue.id}: specify occurrence for repeated phrase`, 2, context);
|
|
83
|
+
const start = matches[(cue.at.occurrence ?? 1) - 1];
|
|
84
|
+
requireCondition(start !== undefined, 'CUE_OCCURRENCE', `Cue ${cue.id}: occurrence does not exist`, 2, context);
|
|
85
|
+
const end = start + cue.at.phrase.length;
|
|
86
|
+
const first = alignment.units.find(unit => unit.start === start);
|
|
87
|
+
const last = alignment.units.find(unit => unit.end === end);
|
|
88
|
+
requireCondition(first && last, 'CUE_BOUNDARY', `Cue ${cue.id}: exact phrase boundaries unavailable`, 2, context);
|
|
89
|
+
const time = segment.start_ms + (cue.at.boundary === 'start' ? first.start_ms : last.end_ms) + cue.at.offset_ms;
|
|
90
|
+
return { time, segment, context, cue_span: { segment: cue.at.segment, start, end, form: alignment.form } };
|
|
91
|
+
}
|
|
92
|
+
for (const cue of story.cues) {
|
|
93
|
+
const { time, segment, context, cue_span } = phrase(cue);
|
|
94
|
+
const action = { ...cue.action, id: cue.id };
|
|
95
|
+
const endTime = time + duration(action);
|
|
96
|
+
requireCondition(time >= 0 && endTime <= cursor, 'CUE_RANGE', `Cue ${cue.id} lies outside production`, 2, context);
|
|
97
|
+
actions.push({ id: cue.id, scene: segment.scene, start_ms: time, end_ms: endTime, action, cue_span });
|
|
98
|
+
}
|
|
99
|
+
actions.sort((a, b) => a.start_ms - b.start_ms);
|
|
100
|
+
let activeSlide = '';
|
|
101
|
+
let lastClick = 0;
|
|
102
|
+
for (let index = 0; index < actions.length; index++) {
|
|
103
|
+
const item = actions[index];
|
|
104
|
+
if (item.action.type === 'slide') {
|
|
105
|
+
activeSlide = item.action.target;
|
|
106
|
+
lastClick = 0;
|
|
107
|
+
}
|
|
108
|
+
if (item.action.type === 'reveal') {
|
|
109
|
+
requireCondition(item.action.click > lastClick, 'REVEAL_ORDER', `Reveal ${item.id} must advance clicks on ${activeSlide}`);
|
|
110
|
+
lastClick = item.action.click;
|
|
111
|
+
}
|
|
112
|
+
for (const other of actions.slice(index + 1)) {
|
|
113
|
+
const visual = ['slide', 'reveal'];
|
|
114
|
+
const competing = visual.includes(item.action.type) && visual.includes(other.action.type) || item.action.type === 'play' && other.action.type === 'play' && item.action.media === other.action.media;
|
|
115
|
+
requireCondition(!competing || other.start_ms >= item.end_ms && !(other.start_ms === item.start_ms && other.action.type === item.action.type), 'ACTION_CONFLICT', `Conflicting actions ${item.id} and ${other.id}`);
|
|
116
|
+
if (item.action.type === 'play' && other.action.type === 'slide')
|
|
117
|
+
requireCondition(other.start_ms >= item.end_ms, 'MEDIA_NAVIGATION', `Slide ${other.id} interrupts media ${item.id}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const annotations = (story.annotations ?? []).map(annotation => {
|
|
121
|
+
const { time, segment, context, cue_span } = phrase(annotation, annotation.target);
|
|
122
|
+
const end = time + annotation.duration_ms;
|
|
123
|
+
const range = sceneRanges.get(annotation.scene);
|
|
124
|
+
requireCondition(segment.scene === annotation.scene && time >= range.start && end <= range.end, 'ANNOTATION_RANGE', `Annotation ${annotation.id}: interval must fit its narration scene ${annotation.scene}`, 2, context);
|
|
125
|
+
const visuals = actions.filter(item => item.action.type === 'slide' || item.action.type === 'reveal');
|
|
126
|
+
const preceding = visuals.filter(item => item.start_ms <= time);
|
|
127
|
+
const slide = preceding.findLast(item => item.action.type === 'slide');
|
|
128
|
+
const state = preceding.at(-1);
|
|
129
|
+
requireCondition(time >= state.end_ms && !visuals.some(item => item.start_ms > time && item.start_ms < end), 'ANNOTATION_STATE', `Annotation ${annotation.id}: interval must fit one settled slide visit and reveal state`, 2, context);
|
|
130
|
+
const click = state.action.type === 'reveal' ? state.action.click : 0;
|
|
131
|
+
requireCondition(slide.action.type === 'slide', 'ANNOTATION_STATE', `Annotation ${annotation.id}: no active slide`, 2, context);
|
|
132
|
+
return { ...annotation, start_ms: time, end_ms: end, slide: slide.action.target, visit: slide.id, click, cue_span };
|
|
133
|
+
});
|
|
134
|
+
requireCondition(cursor > 0, 'EMPTY_PRODUCTION', 'Production needs a positive duration');
|
|
135
|
+
const overlays = (story.overlays ?? []).map(overlay => {
|
|
136
|
+
const { id, src, box, opacity } = overlay;
|
|
137
|
+
const scope = overlay.scene ? sceneRanges.get(overlay.scene) : { start: 0, end: cursor };
|
|
138
|
+
const at = (boundary) => typeof boundary === 'number' ? scope.start + boundary : phrase({ id, at: boundary }).time;
|
|
139
|
+
const visible = overlay.visible
|
|
140
|
+
? overlay.visible.map(interval => ({
|
|
141
|
+
start_ms: at(interval.start), end_ms: at(interval.end),
|
|
142
|
+
fade_in_ms: interval.fade_in_ms ?? 0, fade_out_ms: interval.fade_out_ms ?? 0,
|
|
143
|
+
})).sort((a, b) => a.start_ms - b.start_ms)
|
|
144
|
+
: [{ start_ms: scope.start, end_ms: scope.end, fade_in_ms: 0, fade_out_ms: 0 }];
|
|
145
|
+
for (const [index, interval] of visible.entries()) {
|
|
146
|
+
const { start_ms, end_ms, fade_in_ms, fade_out_ms } = interval;
|
|
147
|
+
requireCondition(start_ms >= scope.start && end_ms <= scope.end && start_ms < end_ms &&
|
|
148
|
+
fade_in_ms + fade_out_ms <= end_ms - start_ms &&
|
|
149
|
+
(index === 0 || start_ms >= visible[index - 1].end_ms), 'OVERLAY_RANGE', `Overlay ${id}: intervals must fit their scope, allow both fades, and avoid overlap`);
|
|
150
|
+
}
|
|
151
|
+
const hidden = (overlay.hide_in_scenes ?? []).map(scene => {
|
|
152
|
+
const range = sceneRanges.get(scene);
|
|
153
|
+
return { start_ms: range.start, end_ms: range.end };
|
|
154
|
+
});
|
|
155
|
+
return { id, src, box, opacity, visible, hidden };
|
|
156
|
+
});
|
|
157
|
+
return {
|
|
158
|
+
version: story.version, ...(story.version === 2 ? { annotations } : {}),
|
|
159
|
+
duration_ms: cursor, actions, media: media.map(({ id, src, duration_ms, has_audio }) => ({ id, src, duration_ms, has_audio })),
|
|
160
|
+
...(overlays.length ? { overlays } : {}),
|
|
161
|
+
};
|
|
162
|
+
}
|