@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.
Files changed (101) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/IMPRESSUM.md +13 -0
  3. package/LICENSE-TERMS.md +58 -0
  4. package/README.md +25 -0
  5. package/addons/slidevideo/geometry.ts +127 -0
  6. package/addons/slidevideo/global-top.vue +232 -0
  7. package/addons/slidevideo/package.json +1 -0
  8. package/addons/slidevideo/playback-entries.ts +14 -0
  9. package/addons/slidevideo/preview.ts +157 -0
  10. package/dist/adapters/browser-runtime.d.ts +37 -0
  11. package/dist/adapters/browser-runtime.js +1 -0
  12. package/dist/adapters/edge.d.ts +7 -0
  13. package/dist/adapters/edge.js +46 -0
  14. package/dist/adapters/elevenlabs.d.ts +7 -0
  15. package/dist/adapters/elevenlabs.js +58 -0
  16. package/dist/adapters/powerpoint-preview.d.ts +2 -0
  17. package/dist/adapters/powerpoint-preview.js +18 -0
  18. package/dist/adapters/powerpoint.d.ts +21 -0
  19. package/dist/adapters/powerpoint.js +434 -0
  20. package/dist/adapters/registry.d.ts +4 -0
  21. package/dist/adapters/registry.js +13 -0
  22. package/dist/adapters/slidev-inputs.d.ts +1 -0
  23. package/dist/adapters/slidev-inputs.js +86 -0
  24. package/dist/adapters/slidev-inspection.d.ts +3 -0
  25. package/dist/adapters/slidev-inspection.js +79 -0
  26. package/dist/adapters/slidev-server.d.ts +1 -0
  27. package/dist/adapters/slidev-server.js +48 -0
  28. package/dist/adapters/slidev.d.ts +30 -0
  29. package/dist/adapters/slidev.js +251 -0
  30. package/dist/annotation-paint.d.ts +19 -0
  31. package/dist/annotation-paint.js +13 -0
  32. package/dist/annotations.d.ts +27 -0
  33. package/dist/annotations.js +115 -0
  34. package/dist/assembly.d.ts +48 -0
  35. package/dist/assembly.js +138 -0
  36. package/dist/calibration.d.ts +24 -0
  37. package/dist/calibration.js +346 -0
  38. package/dist/cli.d.ts +2 -0
  39. package/dist/cli.js +180 -0
  40. package/dist/compositor.d.ts +18 -0
  41. package/dist/compositor.js +155 -0
  42. package/dist/contracts.d.ts +358 -0
  43. package/dist/contracts.js +1 -0
  44. package/dist/errors.d.ts +7 -0
  45. package/dist/errors.js +15 -0
  46. package/dist/executables.d.ts +23 -0
  47. package/dist/executables.js +165 -0
  48. package/dist/installation.d.ts +6 -0
  49. package/dist/installation.js +32 -0
  50. package/dist/license-key.d.ts +12 -0
  51. package/dist/license-key.js +55 -0
  52. package/dist/license-status.d.ts +16 -0
  53. package/dist/license-status.js +12 -0
  54. package/dist/media.d.ts +12 -0
  55. package/dist/media.js +57 -0
  56. package/dist/overlay-assets.d.ts +2 -0
  57. package/dist/overlay-assets.js +58 -0
  58. package/dist/pipeline.d.ts +50 -0
  59. package/dist/pipeline.js +257 -0
  60. package/dist/preview/contracts.d.ts +34 -0
  61. package/dist/preview/contracts.js +1 -0
  62. package/dist/preview/player.d.ts +1 -0
  63. package/dist/preview/player.js +129 -0
  64. package/dist/preview/server.d.ts +1 -0
  65. package/dist/preview/server.js +112 -0
  66. package/dist/preview/view.d.ts +1 -0
  67. package/dist/preview/view.js +36 -0
  68. package/dist/revoked-keys.json +1 -0
  69. package/dist/run.d.ts +12 -0
  70. package/dist/run.js +109 -0
  71. package/dist/setup-install.d.ts +7 -0
  72. package/dist/setup-install.js +98 -0
  73. package/dist/setup-license.d.ts +2 -0
  74. package/dist/setup-license.js +63 -0
  75. package/dist/setup.d.ts +34 -0
  76. package/dist/setup.js +218 -0
  77. package/dist/speech.d.ts +6 -0
  78. package/dist/speech.js +125 -0
  79. package/dist/storyboard.d.ts +6 -0
  80. package/dist/storyboard.js +86 -0
  81. package/dist/timing.d.ts +6 -0
  82. package/dist/timing.js +162 -0
  83. package/package.json +134 -0
  84. package/schemas/annotation-geometry.v1.json +130 -0
  85. package/schemas/revoked-keys.schema.json +11 -0
  86. package/schemas/run-manifest.v1.json +96 -0
  87. package/schemas/schedule.v1.json +108 -0
  88. package/schemas/schedule.v2.json +496 -0
  89. package/schemas/speech.v1.json +173 -0
  90. package/schemas/storyboard.v1.json +461 -0
  91. package/schemas/storyboard.v2.json +802 -0
  92. package/schemas/timing-evidence.v1.json +129 -0
  93. package/skills/slidevideo/SKILL.md +56 -0
  94. package/skills/slidevideo/references/production.md +76 -0
  95. package/skills/slidevideo/references/storyboard.md +272 -0
  96. package/tools/edge-tts/edge-tts.py +19 -0
  97. package/tools/edge-tts/requirements.lock +34 -0
  98. package/tools/powerpoint/Native.cs +277 -0
  99. package/tools/powerpoint/powerpoint.ps1 +714 -0
  100. package/tools/powerpoint/preview.ps1 +100 -0
  101. package/tools/powerpoint/requirements.json +11 -0
package/dist/cli.js ADDED
@@ -0,0 +1,180 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { existsSync } from 'node:fs';
4
+ import { readFile } from 'node:fs/promises';
5
+ import { servePreview } from './preview/server.js';
6
+ import { produce } from './pipeline.js';
7
+ import { resolve, join } from 'node:path';
8
+ import { json } from './media.js';
9
+ import { ProductionError, requireCondition } from './errors.js';
10
+ import { packagePath } from './installation.js';
11
+ import { withExecutables } from './executables.js';
12
+ import { setup } from './setup.js';
13
+ import { setupLicense } from './setup-license.js';
14
+ const commands = ['inspect', 'validate', 'play', 'tts', 'resolve', 'record', 'assemble', 'build'];
15
+ const documents = new Map([
16
+ ['license', 'LICENSE-TERMS.md'],
17
+ ['impressum', 'IMPRESSUM.md'],
18
+ ['skill', 'skills/slidevideo/SKILL.md'],
19
+ ['skill storyboard', 'skills/slidevideo/references/storyboard.md'],
20
+ ['skill production', 'skills/slidevideo/references/production.md'],
21
+ ]);
22
+ const setupHelp = `slidevideo setup [--presentation slidev|powerpoint] [--provider edge-tts|elevenlabs]
23
+
24
+ --voice-id <id> Voice ID for the storyboard. Required for ElevenLabs readiness.
25
+ --install Install supported missing tools.
26
+ --manual Check tools and print manual instructions without installing.
27
+ --browser/--python/--ffmpeg/--ffprobe <path> Check and save a custom executable.
28
+ --json Print the readiness report as JSON. Pass the workflow choices as options.
29
+ --license Manage activation in a terminal without checking dependencies.
30
+
31
+ Run without options in a terminal to choose the workflow interactively.
32
+ Setup exits 3 if the selected workflow is missing required dependencies.
33
+ `;
34
+ let command = process.argv[2] ?? 'help';
35
+ const jsonMode = process.argv.includes('--json');
36
+ let previewReady = false;
37
+ try {
38
+ const { values, positionals } = parseArgs({ options: {
39
+ storyboard: { type: 'string' }, port: { type: 'string' }, run: { type: 'string' }, 'cache-dir': { type: 'string' }, output: { type: 'string' }, export: { type: 'string' }, 'timeout-ms': { type: 'string' },
40
+ browser: { type: 'string' }, python: { type: 'string' }, ffmpeg: { type: 'string' }, ffprobe: { type: 'string' },
41
+ presentation: { type: 'string' }, provider: { type: 'string' }, 'voice-id': { type: 'string' }, install: { type: 'boolean' }, manual: { type: 'boolean' },
42
+ license: { type: 'boolean' },
43
+ json: { type: 'boolean' }, quiet: { type: 'boolean' }, resume: { type: 'boolean' }, 'verify-timing': { type: 'boolean' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' },
44
+ }, allowPositionals: true });
45
+ command = positionals[0] ?? 'help';
46
+ if (values.version) {
47
+ const { version } = JSON.parse(await readFile(packagePath('package.json'), 'utf8'));
48
+ console.log(values.json ? JSON.stringify({ version: 1, package_version: version }) : version);
49
+ }
50
+ else if (values.help || command === 'help') {
51
+ const help = command === 'setup' ? setupHelp : `slidevideo <setup|inspect|validate|play|tts|resolve|record|assemble|build|skill|license|impressum>
52
+
53
+ --storyboard <file> Required for presentation commands except assemble.
54
+ --run <directory> Required for artifact-producing commands.
55
+ --cache-dir <dir> Speech cache for tts or build, read-only timing metadata for play.
56
+ --port <number> Local play server port (default: auto).
57
+ --output <file> New final MP4 destination for assemble or build.
58
+ --resume Reuse intact build stages with matching inputs and mode.
59
+ --verify-timing Opt in to decoded timing proof for build or record; assemble checks the recorded mode.
60
+ --export <file> Optional resolved schedule export.
61
+ --timeout-ms <ms> Bounded stage timeout, default 180000.
62
+ --browser/--python/--ffmpeg/--ffprobe <path> Override a tool for this command.
63
+ --json One JSON result on stdout (play reports its URL at readiness).
64
+ --quiet Suppress progress on stderr.
65
+ --version Package version.
66
+
67
+ setup checks and configures the dependencies for your presentation format and speech provider.
68
+ Normal production leaves timing unevaluated and the video for user review.
69
+ inspect lists existing annotation targets without recording.
70
+ validate checks inputs without recording.
71
+ play --storyboard <file> serves silent slides and annotations with Play, Pause and Replay. Ctrl+C stops the server.
72
+ skill displays the bundled storyboard skill. Use skill storyboard or skill production for its references.
73
+ license displays the bundled license terms. Use setup --license to manage activation.
74
+ impressum displays the provider's contact details.
75
+ `;
76
+ console.log(values.json ? JSON.stringify({ version: 1, command, help }) : help);
77
+ }
78
+ else if (command === 'skill' || command === 'license' || command === 'impressum') {
79
+ const file = documents.get(positionals.join(' '));
80
+ const usage = command === 'skill' ? 'skill [storyboard|production]' : command;
81
+ requireCondition(file && Object.keys(values).every(key => key === 'json'), 'OPTION', `Use slidevideo ${usage} [--json].`);
82
+ const path = packagePath(file);
83
+ const document = await readFile(path, 'utf8');
84
+ const result = { version: 1, command, document, path: command === 'skill' ? path : undefined };
85
+ process.stdout.write(values.json ? JSON.stringify(result) + '\n' : document);
86
+ }
87
+ else if (command === 'setup' && values.license) {
88
+ requireCondition(positionals.length === 1 && Object.keys(values).every(key => key === 'license'), 'OPTION', 'Use slidevideo setup --license by itself in a terminal.');
89
+ await withExecutables({}, setupLicense);
90
+ }
91
+ else if (command === 'setup') {
92
+ requireCondition(positionals.length === 1 && !['storyboard', 'port', 'run', 'cache-dir', 'output', 'export', 'timeout-ms', 'resume', 'verify-timing'].some(key => key in values), 'OPTION', 'Run slidevideo setup --help for setup options');
93
+ const report = await withExecutables(values, () => setup(values));
94
+ if (values.json)
95
+ console.log(JSON.stringify(report));
96
+ else {
97
+ if (report.browser_requirement)
98
+ console.log(report.browser_requirement);
99
+ for (const browser of report.browsers)
100
+ console.log(`${browser.name} at ${browser.path}`);
101
+ for (const check of report.checks)
102
+ console.log(`${check.ready ? 'Ready' : 'Required'} ${check.name}: ${check.detail}`);
103
+ for (const error of report.installation_errors)
104
+ console.log(error);
105
+ if (Object.keys(report.saved_paths).length)
106
+ console.log(`Saved executable paths to ${report.config_file}`);
107
+ console.log(`Storyboard voice settings\nvoice:\n provider: ${report.voice.provider}\n voice: ${JSON.stringify(report.voice.voice)}`);
108
+ console.log(report.status === 'ready' ? 'The selected workflow is ready.' : 'The selected workflow needs the dependencies listed above.');
109
+ }
110
+ if (report.status !== 'ready')
111
+ process.exitCode = 3;
112
+ }
113
+ else {
114
+ requireCondition(commands.includes(command) && positionals.length === 1, 'COMMAND', 'Run slidevideo --help for available commands');
115
+ requireCondition(!['presentation', 'provider', 'voice-id', 'install', 'manual', 'license'].some(key => key in values), 'OPTION', 'Presentation, provider, voice ID, install and license options require setup');
116
+ const timeout = Number(values['timeout-ms'] ?? 180000);
117
+ requireCondition(Number.isInteger(timeout) && timeout >= 1000 && timeout <= 3600000, 'TIMEOUT', '--timeout-ms must be between 1000 and 3600000');
118
+ requireCondition(!values.output || ['assemble', 'build'].includes(command), 'OPTION', '--output requires assemble or build');
119
+ requireCondition(!values.resume || command === 'build', 'OPTION', '--resume requires build');
120
+ requireCondition(!values['cache-dir'] || ['tts', 'build', 'play'].includes(command), 'OPTION', '--cache-dir requires play, tts or build');
121
+ requireCondition(!values.export || ['resolve', 'build'].includes(command), 'OPTION', '--export requires resolve or build');
122
+ requireCondition(!values['verify-timing'] || ['record', 'assemble', 'build'].includes(command), 'OPTION', '--verify-timing requires record, assemble or build');
123
+ requireCondition(values.port === undefined || command === 'play', 'OPTION', '--port requires play');
124
+ await withExecutables(values, async () => {
125
+ if (command === 'play') {
126
+ requireCondition(values.storyboard, 'STORYBOARD_REQUIRED', 'play requires --storyboard');
127
+ requireCondition(values.run === undefined && values['timeout-ms'] === undefined, 'OPTION', 'play takes --storyboard, --cache-dir and --port; Ctrl+C stops the server');
128
+ const port = Number(values.port ?? 0);
129
+ requireCondition(values.port === undefined || /^\d+$/.test(values.port) && Number.isInteger(port) && port <= 65535, 'PREVIEW_PORT', '--port must be between 0 and 65535');
130
+ await servePreview(values.storyboard, values['cache-dir'], port, (url, approximate) => {
131
+ previewReady = true;
132
+ console.log(values.json ? JSON.stringify({ version: 1, command, status: 'ready', url, approximate, timing_status: 'not_evaluated' }) : `Open ${url} to preview the storyboard. Press Ctrl+C to stop.`);
133
+ });
134
+ }
135
+ else {
136
+ if (existsSync('.env'))
137
+ process.loadEnvFile('.env');
138
+ let operation = `${command} started`;
139
+ let started = Date.now();
140
+ const progress = values.quiet ? undefined : (message) => {
141
+ operation = message;
142
+ started = Date.now();
143
+ process.stderr.write(`[slidevideo] ${message}\n`);
144
+ };
145
+ progress?.(operation);
146
+ const heartbeat = progress ? setInterval(() => process.stderr.write(`[slidevideo] ${operation} (${Math.floor((Date.now() - started) / 1000)}s elapsed)\n`), 5000) : undefined;
147
+ try {
148
+ const result = await produce({ command, storyboard: values.storyboard, run: values.run, cache: values['cache-dir'], output: values.output, export: values.export, resume: values.resume, verify_timing: values['verify-timing'], timeout_ms: timeout, progress });
149
+ progress?.(`${command} completed`);
150
+ console.log(values.json || command === 'inspect' ? JSON.stringify(result) : `${command} completed${result.artifacts.video ? `: ${result.artifacts.video}` : ''}`);
151
+ }
152
+ catch (error) {
153
+ progress?.(`${command} failed`);
154
+ throw error;
155
+ }
156
+ finally {
157
+ clearInterval(heartbeat);
158
+ }
159
+ }
160
+ });
161
+ }
162
+ }
163
+ catch (error) {
164
+ const failure = error instanceof ProductionError ? error : new ProductionError('INTERNAL', error instanceof Error ? error.message : String(error), error instanceof TypeError ? 2 : 1);
165
+ let run;
166
+ const runIndex = process.argv.indexOf('--run');
167
+ if (runIndex >= 0 && process.argv[runIndex + 1]) {
168
+ try {
169
+ run = await json(join(resolve(process.argv[runIndex + 1]), 'manifest.json'));
170
+ }
171
+ catch { }
172
+ }
173
+ const result = { version: 1, command, status: 'failed', run_id: run?.run_id, completed_stages: Object.entries(run?.stages ?? {}).filter(([, stage]) => stage?.status === 'completed').map(([name]) => name), artifacts: run ? { manifest: join(resolve(process.argv[runIndex + 1]), 'manifest.json') } : {}, timing_status: 'not_accepted', warnings: [], errors: [{ stage: command, code: failure.code, message: failure.message, ...failure.context }] };
174
+ const diagnostic = jsonMode ? JSON.stringify(result) : `${failure.code}: ${failure.message}`;
175
+ if (previewReady)
176
+ console.error(diagnostic);
177
+ else
178
+ console.log(diagnostic);
179
+ process.exitCode = failure.exitCode;
180
+ }
@@ -0,0 +1,18 @@
1
+ import { type Canvas, type Image } from '@napi-rs/canvas';
2
+ import type { Rectangle, Schedule, Storyboard } from './contracts.js';
3
+ import type { AppliedAnnotation } from './annotations.js';
4
+ type FrameLayer = {
5
+ image: Image | Canvas;
6
+ rectangle: Rectangle;
7
+ opacityAt?: (time: number) => number;
8
+ opacity: number;
9
+ };
10
+ export declare function frameLayers(output: Storyboard['output'], schedule: Schedule, licensed: boolean, hashes?: Record<string, string>): Promise<FrameLayer[]>;
11
+ export declare function writeStaticFrameLayers(file: string, output: Storyboard['output'], layers: FrameLayer[]): Promise<void>;
12
+ export declare function visibleFrameLayerBounds(layers: FrameLayer[], frame: number, fps: number, audioOrigin: number): Rectangle[];
13
+ export declare function compositeFrames(source: string, baseFilter: string, encoderArgs: string[], output: Storyboard['output'], applications: AppliedAnnotation[], layers: FrameLayer[], frameCount: number, audioOrigin: number): Promise<{
14
+ renderer: string;
15
+ version: string;
16
+ frames: number;
17
+ }>;
18
+ export {};
@@ -0,0 +1,155 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { writeFile } from 'node:fs/promises';
3
+ import { pipeline } from 'node:stream/promises';
4
+ import { createCanvas, ImageData } from '@napi-rs/canvas';
5
+ import { executionScope } from './media.js';
6
+ import { executable } from './executables.js';
7
+ import { ProductionError, requireCondition } from './errors.js';
8
+ import { loadOverlayImage } from './overlay-assets.js';
9
+ export async function frameLayers(output, schedule, licensed, hashes) {
10
+ const layers = [];
11
+ const images = new Map();
12
+ for (const overlay of schedule.overlays ?? []) {
13
+ const image = images.get(overlay.src) ?? await loadOverlayImage(overlay, hashes?.[overlay.src]);
14
+ images.set(overlay.src, image);
15
+ const boxWidth = overlay.box.width * output.width;
16
+ const boxHeight = overlay.box.height * output.height;
17
+ const scale = Math.min(boxWidth / image.width, boxHeight / image.height);
18
+ const width = image.width * scale;
19
+ const height = image.height * scale;
20
+ const rectangle = {
21
+ x: overlay.box.x * output.width + (boxWidth - width) / 2,
22
+ y: overlay.box.y * output.height + (boxHeight - height) / 2,
23
+ width, height,
24
+ };
25
+ const first = overlay.visible[0];
26
+ const constant = overlay.visible.length === 1 && first.start_ms === 0 &&
27
+ first.end_ms === schedule.duration_ms && !first.fade_in_ms && !first.fade_out_ms && !overlay.hidden.length;
28
+ const opacityAt = constant ? undefined : (time) => {
29
+ if (overlay.hidden.some(interval => time >= interval.start_ms && time < interval.end_ms))
30
+ return 0;
31
+ const interval = overlay.visible.find(interval => time >= interval.start_ms && time < interval.end_ms);
32
+ if (!interval)
33
+ return 0;
34
+ return overlay.opacity * Math.min(1, interval.fade_in_ms ? (time - interval.start_ms) / interval.fade_in_ms : 1, interval.fade_out_ms ? (interval.end_ms - time) / interval.fade_out_ms : 1);
35
+ };
36
+ layers.push({ image, rectangle, opacity: overlay.opacity, opacityAt });
37
+ }
38
+ if (!licensed)
39
+ layers.push(watermark(output));
40
+ return layers;
41
+ }
42
+ function watermark(output) {
43
+ const text = 'slidevideo.io';
44
+ const size = Math.max(1, Math.round(output.height * 0.024));
45
+ const margin = Math.max(1, Math.round(Math.min(output.width, output.height) * 0.018));
46
+ const width = Math.max(1, Math.min(Math.ceil(size * 8), output.width - margin));
47
+ const height = Math.max(1, Math.min(Math.ceil(size * 1.5), output.height - margin));
48
+ const image = createCanvas(width, height);
49
+ const context = image.getContext('2d');
50
+ context.font = `600 ${size}px sans-serif`;
51
+ context.textAlign = 'right';
52
+ context.textBaseline = 'middle';
53
+ context.lineJoin = 'round';
54
+ context.lineWidth = Math.max(1, size * 0.1);
55
+ context.strokeStyle = '#222222';
56
+ context.fillStyle = '#ffffff';
57
+ const x = Math.max(0, width - Math.ceil(context.lineWidth));
58
+ const maxWidth = Math.max(1, width - 2 * Math.ceil(context.lineWidth));
59
+ context.strokeText(text, x, height / 2, maxWidth);
60
+ context.fillText(text, x, height / 2, maxWidth);
61
+ return { image, opacity: 0.5, rectangle: { x: output.width - margin - width, y: output.height - margin - height, width, height } };
62
+ }
63
+ function paintFrameLayers(context, layers, time) {
64
+ for (const layer of layers) {
65
+ const opacity = layer.opacityAt?.(time) ?? layer.opacity;
66
+ if (!opacity)
67
+ continue;
68
+ const { x, y, width, height } = layer.rectangle;
69
+ context.globalAlpha = opacity;
70
+ context.drawImage(layer.image, x, y, width, height);
71
+ }
72
+ context.globalAlpha = 1;
73
+ }
74
+ export async function writeStaticFrameLayers(file, output, layers) {
75
+ const canvas = createCanvas(output.width, output.height);
76
+ paintFrameLayers(canvas.getContext('2d'), layers, 0);
77
+ await writeFile(file, canvas.toBuffer('image/png'));
78
+ }
79
+ export function visibleFrameLayerBounds(layers, frame, fps, audioOrigin) {
80
+ const time = Math.max(0, frame * 1000 / fps - audioOrigin);
81
+ return layers.filter(layer => (layer.opacityAt?.(time) ?? layer.opacity) > 0).map(layer => layer.rectangle);
82
+ }
83
+ function completion(child, operation) {
84
+ let diagnostic = '';
85
+ child.stderr?.on('data', data => { diagnostic = (diagnostic + data.toString()).slice(-4000); });
86
+ const done = new Promise((resolve, reject) => {
87
+ child.once('error', error => reject(new ProductionError('ANNOTATION_COMPOSITOR', `${operation}: ${error.message}`, 7)));
88
+ child.once('close', code => code === 0 ? resolve() : reject(new ProductionError('ANNOTATION_COMPOSITOR', `${operation} exited ${code}: ${diagnostic}`, 7)));
89
+ });
90
+ void done.catch(() => { });
91
+ return done;
92
+ }
93
+ export async function compositeFrames(source, baseFilter, encoderArgs, output, applications, layers, frameCount, audioOrigin) {
94
+ const signal = executionScope.getStore();
95
+ signal?.throwIfAborted();
96
+ const canvas = createCanvas(output.width, output.height);
97
+ const context = canvas.getContext('2d', { alpha: false });
98
+ const bytes = output.width * output.height * 4;
99
+ const data = new Uint8ClampedArray(bytes);
100
+ const frame = Buffer.from(data.buffer);
101
+ const ffmpeg = executable('ffmpeg');
102
+ const decoder = spawn(ffmpeg, ['-v', 'error', '-xerror', '-i', source, '-vf', baseFilter, '-frames:v', String(frameCount), '-pix_fmt', 'rgba', '-fps_mode', 'passthrough', '-f', 'rawvideo', '-'], { stdio: ['ignore', 'pipe', 'pipe'], signal, killSignal: 'SIGKILL', windowsHide: true });
103
+ const decoded = completion(decoder, 'Composite frame decoding');
104
+ const encoder = spawn(ffmpeg, encoderArgs, { stdio: ['pipe', 'ignore', 'pipe'], signal, killSignal: 'SIGKILL', windowsHide: true });
105
+ const encoded = completion(encoder, 'Composite frame encoding');
106
+ let frames = 0;
107
+ async function* render(chunks) {
108
+ let filled = 0;
109
+ for await (const chunk of chunks) {
110
+ let position = 0;
111
+ while (position < chunk.length) {
112
+ signal?.throwIfAborted();
113
+ const count = Math.min(bytes - filled, chunk.length - position);
114
+ chunk.copy(frame, filled, position, position + count);
115
+ position += count;
116
+ filled += count;
117
+ if (filled !== bytes)
118
+ continue;
119
+ context.putImageData(new ImageData(data, output.width, output.height), 0, 0);
120
+ for (const annotation of applications) {
121
+ if (frames < annotation.first_frame || frames >= annotation.end_frame)
122
+ continue;
123
+ for (const paint of [annotation, ...(annotation.bottom_border ? [annotation.bottom_border] : [])]) {
124
+ context.save();
125
+ context.fillStyle = paint.color;
126
+ context.globalAlpha = paint.opacity;
127
+ context.globalCompositeOperation = paint.blend;
128
+ const rect = paint.rectangle;
129
+ context.fillRect(rect.x, rect.y, rect.width, rect.height);
130
+ context.restore();
131
+ }
132
+ }
133
+ paintFrameLayers(context, layers, Math.max(0, frames * 1000 / output.fps - audioOrigin));
134
+ const pixels = context.getImageData(0, 0, output.width, output.height).data;
135
+ yield Buffer.from(pixels.buffer, pixels.byteOffset, pixels.byteLength);
136
+ frames++;
137
+ filled = 0;
138
+ }
139
+ }
140
+ requireCondition(filled === 0 && frames === frameCount, 'ANNOTATION_FRAMES', `Compositor received ${frames} complete frames, expected ${frameCount}`, 7);
141
+ }
142
+ const timer = setTimeout(() => { decoder.kill('SIGKILL'); encoder.kill('SIGKILL'); }, 120000);
143
+ try {
144
+ await Promise.all([pipeline(decoder.stdout, render, encoder.stdin, { signal }), decoded, encoded]);
145
+ return { renderer: 'canvas-skia', version: '1.1.1', frames };
146
+ }
147
+ finally {
148
+ clearTimeout(timer);
149
+ if (decoder.exitCode === null)
150
+ decoder.kill('SIGKILL');
151
+ if (encoder.exitCode === null)
152
+ encoder.kill('SIGKILL');
153
+ await Promise.allSettled([decoded, encoded]);
154
+ }
155
+ }