@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
@@ -0,0 +1,138 @@
1
+ import { join, dirname } from 'node:path';
2
+ import { lstat, mkdir, mkdtemp, link, rm, copyFile } from 'node:fs/promises';
3
+ import { execute, probe, decode, saveJson } from './media.js';
4
+ import { requireCondition } from './errors.js';
5
+ import { configuredLicense } from './executables.js';
6
+ import { annotationApplications, verifyAnnotations } from './annotations.js';
7
+ export async function assemble(story, schedule, speech, visual, directory, output, options = { verify_timing: false }) {
8
+ const licensed = options.licensed ?? configuredLicense();
9
+ requireCondition(visual.timing.status !== 'failed' && (!options.verify_timing || visual.timing.status === 'accepted'), 'TIMING_REQUIRED', 'Assembly cannot use failed or missing requested timing proof', 6);
10
+ const mapping = visual.origin?.mapping ?? (visual.timing.status === 'accepted' ? visual.timing.mapping : undefined);
11
+ requireCondition(mapping && Object.values(mapping).every(Number.isFinite) && mapping.trim_start_ms >= 0 && mapping.trim_end_ms > mapping.trim_start_ms, 'CAPTURE_ORIGIN', 'Assembly requires a usable capture origin', 6);
12
+ requireCondition(mapping.rate === 1, 'TIMING_RATE', 'Capture clock drift cannot be hidden by stretching narration', 6);
13
+ let exists = false;
14
+ try {
15
+ await lstat(output);
16
+ exists = true;
17
+ }
18
+ catch (error) {
19
+ if (error.code !== 'ENOENT')
20
+ throw error;
21
+ }
22
+ requireCondition(!exists, 'OUTPUT_EXISTS', `Output already exists: ${output}`);
23
+ await mkdir(dirname(output), { recursive: true });
24
+ await mkdir(directory, { recursive: true });
25
+ const lock = `${output}.lock`;
26
+ try {
27
+ await mkdir(lock);
28
+ }
29
+ catch (error) {
30
+ requireCondition(error.code !== 'EEXIST', 'OUTPUT_LOCKED', `Another assembly owns the output, or an interrupted process left ${lock}`);
31
+ throw error;
32
+ }
33
+ let temporaryDirectory;
34
+ try {
35
+ temporaryDirectory = await mkdtemp(`${output}.partial-`);
36
+ const temporary = join(temporaryDirectory, 'video.mp4');
37
+ const args = ['-v', 'error', '-xerror', '-y'];
38
+ const filters = [];
39
+ const tracks = [];
40
+ const transformations = [];
41
+ const { trim_start_ms, trim_end_ms, offset_ms } = mapping;
42
+ const originDelta = offset_ms - trim_start_ms;
43
+ if (options.verify_timing)
44
+ requireCondition(originDelta >= -100 && originDelta <= 100, 'TRIM_MAPPING', 'Presentation trim differs from measured origin', 6);
45
+ const audioOrigin = Math.max(0, originDelta);
46
+ const pictureLeadHold = Math.max(0, -originDelta);
47
+ const duration = (schedule.duration_ms + audioOrigin) / 1000;
48
+ const baseFilter = `trim=start=${trim_start_ms / 1000}:end=${trim_end_ms / 1000},setpts=PTS-STARTPTS,tpad=start_mode=clone:start_duration=${pictureLeadHold / 1000},fps=${story.output.fps},tpad=stop_mode=clone:stop_duration=${duration},trim=duration=${duration},format=yuv420p`;
49
+ const annotations = annotationApplications(story, schedule, visual, audioOrigin);
50
+ const renderer = annotations.length || schedule.overlays?.length || !licensed ? await import('./compositor.js') : undefined;
51
+ const layers = await renderer?.frameLayers(story.output, schedule, licensed, options.inputHashes) ?? [];
52
+ const streamCompositor = annotations.length > 0 || layers.some(layer => layer.opacityAt !== undefined);
53
+ let input = 1;
54
+ if (streamCompositor) {
55
+ args.push('-f', 'rawvideo', '-pixel_format', 'rgba', '-video_size', `${story.output.width}x${story.output.height}`, '-framerate', String(story.output.fps), '-i', 'pipe:0');
56
+ filters.push('[0:v]format=yuv420p[v]');
57
+ }
58
+ else {
59
+ args.push('-i', visual.file);
60
+ if (layers.length) {
61
+ const layerImage = join(temporaryDirectory, 'overlays.png');
62
+ await renderer.writeStaticFrameLayers(layerImage, story.output, layers);
63
+ args.push('-i', layerImage);
64
+ filters.push(`[0:v]${baseFilter}[base]`, '[base][1:v]overlay=eof_action=repeat[v]');
65
+ input++;
66
+ }
67
+ else
68
+ filters.push(`[0:v]${baseFilter}[v]`);
69
+ }
70
+ if (annotations.length)
71
+ await saveJson(join(directory, 'annotations-applied.json'), { version: 1, annotations });
72
+ for (const item of schedule.actions) {
73
+ if (item.action.type === 'speak') {
74
+ const segment = item.action.segment;
75
+ const asset = speech.assets.find(a => a.id === segment);
76
+ args.push('-i', asset.audio);
77
+ filters.push(`[${input}:a]atrim=duration=${asset.duration_ms / 1000},asetpts=PTS-STARTPTS,adelay=${item.start_ms + audioOrigin}:all=1[a${input}]`);
78
+ tracks.push(`[a${input}]`);
79
+ transformations.push({ id: item.id, kind: 'narration', start_ms: item.start_ms, duration_ms: asset.duration_ms });
80
+ input++;
81
+ }
82
+ if (item.action.type === 'play' && item.action.audio === 'source') {
83
+ const action = item.action;
84
+ const media = schedule.media.find(m => m.id === action.media);
85
+ args.push('-i', media.src);
86
+ filters.push(`[${input}:a]atrim=start=${(action.trim_start_ms ?? 0) / 1000}:end=${(action.trim_end_ms ?? media.duration_ms) / 1000},asetpts=PTS-STARTPTS,atempo=${action.rate ?? 1},volume=${action.volume},adelay=${item.start_ms + audioOrigin}:all=1[a${input}]`);
87
+ tracks.push(`[a${input}]`);
88
+ transformations.push({ id: item.id, kind: 'source', start_ms: item.start_ms, trim_start_ms: action.trim_start_ms ?? 0, trim_end_ms: action.trim_end_ms ?? media.duration_ms, rate: action.rate ?? 1, volume: action.volume });
89
+ input++;
90
+ }
91
+ }
92
+ if (tracks.length)
93
+ filters.push(`${tracks.join('')}amix=inputs=${tracks.length}:normalize=0,apad,atrim=duration=${duration}[a]`);
94
+ args.push('-filter_complex', filters.join(';'), '-map', '[v]');
95
+ if (tracks.length)
96
+ args.push('-map', '[a]', '-c:a', 'aac', '-b:a', '192k', '-ar', '48000');
97
+ args.push('-c:v', 'libx264', '-preset', 'fast', '-crf', '18', '-t', String(duration), '-movflags', '+faststart');
98
+ let compositor;
99
+ if (streamCompositor) {
100
+ compositor = await renderer.compositeFrames(visual.file, baseFilter, [...args, temporary], story.output, annotations, layers, Math.ceil(duration * story.output.fps - 1e-9), audioOrigin);
101
+ }
102
+ else
103
+ await execute('ffmpeg', [...args, temporary]);
104
+ if (options.verify_timing)
105
+ await decode(temporary);
106
+ const properties = await probe(temporary);
107
+ requireCondition(properties.width === story.output.width && properties.height === story.output.height && properties.has_audio === (tracks.length > 0) && Math.abs(properties.duration_ms - duration * 1000) <= 100, 'OUTPUT_MEDIA', 'Final media properties do not match the schedule', 7);
108
+ let annotationEvidence;
109
+ if (annotations.length && options.verify_timing) {
110
+ try {
111
+ annotationEvidence = await verifyAnnotations(temporary, visual.file, baseFilter, annotations, story, directory, output, frame => renderer.visibleFrameLayerBounds(layers, frame, story.output.fps, audioOrigin));
112
+ }
113
+ catch (error) {
114
+ await copyFile(temporary, join(directory, 'failed-composite.mp4'));
115
+ throw error;
116
+ }
117
+ }
118
+ try {
119
+ await link(temporary, output);
120
+ }
121
+ catch (error) {
122
+ requireCondition(error.code !== 'EEXIST', 'OUTPUT_EXISTS', `Output already exists: ${output}`);
123
+ throw error;
124
+ }
125
+ const report = { version: 1, output, properties, watermark: !licensed, ...(schedule.overlays?.length ? { image_overlays: schedule.overlays } : {}), decode: options.verify_timing ? 'passed' : 'not_evaluated', timing_status: visual.timing.status, ...(annotations.length ? { compositor, base_capture_timing: visual.timing.status, applied_annotations: annotations, final_composite: annotationEvidence ?? { status: 'not_evaluated', gaps: ['Final annotation frames were not verified. The user reviews the video.'] } } : {}), output_origin_delta_ms: originDelta, audio_origin_ms: audioOrigin, picture_lead_hold_ms: pictureLeadHold, final_hold: 'clone last content frame to scheduled end', trim_start_ms, trim_end_ms, mapping, transformations, editorial_review: 'user' };
126
+ await saveJson(join(directory, 'report.json'), report);
127
+ return report;
128
+ }
129
+ finally {
130
+ try {
131
+ if (temporaryDirectory)
132
+ await rm(temporaryDirectory, { recursive: true });
133
+ }
134
+ finally {
135
+ await rm(lock, { recursive: true });
136
+ }
137
+ }
138
+ }
@@ -0,0 +1,24 @@
1
+ import type { TimingEvidence } from './contracts.js';
2
+ export type Reference = {
3
+ id: string;
4
+ expected_ms: number;
5
+ before: string;
6
+ after: string;
7
+ mode: 'transition' | 'sample';
8
+ frame_period_ms: number;
9
+ settle_ms?: number;
10
+ exclude?: {
11
+ left: number;
12
+ top: number;
13
+ right: number;
14
+ bottom: number;
15
+ }[];
16
+ };
17
+ export type Marker = {
18
+ color: string;
19
+ observed_ms: number;
20
+ paint_interval_ms: number;
21
+ rendered_by_ms: number;
22
+ };
23
+ export declare function estimateOrigin(file: string, markers: Marker[], duration: number, directory: string): Promise<TimingEvidence>;
24
+ export declare function calibrate(file: string, markers: Marker[], references: Reference[], duration: number, directory: string): Promise<TimingEvidence>;
@@ -0,0 +1,346 @@
1
+ import { join } from 'node:path';
2
+ import { spawn } from 'node:child_process';
3
+ import { execute, executionScope, saveJson } from './media.js';
4
+ import { executable } from './executables.js';
5
+ import { ProductionError } from './errors.js';
6
+ const analysisWidth = 640;
7
+ const analysisHeight = 360;
8
+ const bytes = analysisWidth * analysisHeight * 3;
9
+ async function pixels(file) { return execute('ffmpeg', ['-v', 'error', '-i', file, '-vf', `scale=${analysisWidth}:${analysisHeight}`, '-frames:v', '1', '-pix_fmt', 'rgb24', '-f', 'rawvideo', '-']); }
10
+ async function* decodedFrames(file, range) {
11
+ const filters = [`scale=${analysisWidth}:${analysisHeight}`];
12
+ const args = ['-v', 'error', '-xerror'];
13
+ if (range) {
14
+ args.push('-copyts', '-seek_timestamp', '1', '-ss', String(Math.max(0, range.start_ms) / 1000));
15
+ filters.unshift(`select=between(t\\,${range.start_ms / 1000}\\,${range.end_ms / 1000})`);
16
+ }
17
+ args.push('-i', file, '-vf', filters.join(','), '-pix_fmt', 'rgb24', '-fps_mode', 'passthrough');
18
+ if (range)
19
+ args.push('-frames:v', String(range.last - range.first + 1));
20
+ args.push('-f', 'rawvideo', '-');
21
+ const child = spawn(executable('ffmpeg'), args, { stdio: ['ignore', 'pipe', 'pipe'], signal: executionScope.getStore(), killSignal: 'SIGKILL', windowsHide: true });
22
+ let error = '';
23
+ child.stderr.on('data', data => { error = (error + data.toString()).slice(-4000); });
24
+ const completion = new Promise((resolve, reject) => {
25
+ child.once('error', error => reject(new ProductionError('DEPENDENCY', `ffmpeg: ${error.message}`, 3)));
26
+ child.once('close', code => code === 0 ? resolve() : reject(new ProductionError('SUBPROCESS', `ffmpeg exited ${code}: ${error}`, 3)));
27
+ });
28
+ void completion.catch(() => { });
29
+ const timer = setTimeout(() => child.kill('SIGKILL'), 120000);
30
+ const frame = Buffer.alloc(bytes);
31
+ let filled = 0;
32
+ let index = range?.first ?? 0;
33
+ try {
34
+ for await (const chunk of child.stdout) {
35
+ let position = 0;
36
+ while (position < chunk.length) {
37
+ const count = Math.min(bytes - filled, chunk.length - position);
38
+ chunk.copy(frame, filled, position, position + count);
39
+ filled += count;
40
+ position += count;
41
+ if (filled === bytes) {
42
+ yield { frame, index: index++ };
43
+ filled = 0;
44
+ }
45
+ }
46
+ }
47
+ await completion;
48
+ if (filled)
49
+ throw new ProductionError('CAPTURE_FRAMES', 'Decoded capture ends with an incomplete frame', 6);
50
+ }
51
+ finally {
52
+ clearTimeout(timer);
53
+ if (child.exitCode === null)
54
+ child.kill('SIGKILL');
55
+ await completion.catch(() => { });
56
+ }
57
+ }
58
+ async function scanMarkers(file, markers, pts, range) {
59
+ const markerIndices = new Map();
60
+ const colors = markers.map(marker => ({ color: marker.color, rgb: marker.color.match(/[a-f0-9]{2}/g).map(value => parseInt(value, 16)) }));
61
+ const center = (analysisWidth * Math.floor(analysisHeight / 2) + Math.floor(analysisWidth / 2)) * 3;
62
+ const samples = [(analysisWidth * 10 + 10) * 3, center, (analysisWidth * (analysisHeight - 11) + analysisWidth - 11) * 3];
63
+ const matches = (frame, rgb) => samples.every(offset => rgb.every((value, channel) => Math.abs(frame[offset + channel] - value) < 45));
64
+ let firstContent;
65
+ let frameCount = 0;
66
+ for await (const { frame, index } of decodedFrames(file, range)) {
67
+ frameCount++;
68
+ for (const { color, rgb } of colors) {
69
+ if (!markerIndices.has(color) && matches(frame, rgb))
70
+ markerIndices.set(color, index);
71
+ }
72
+ if (firstContent === undefined && markerIndices.has('#ffff00') && index > markerIndices.get('#ffff00') && !matches(frame, [255, 255, 0]))
73
+ firstContent = pts[index];
74
+ }
75
+ return { markerIndices, firstContent, frameCount };
76
+ }
77
+ export async function estimateOrigin(file, markers, duration, directory) {
78
+ const data = JSON.parse((await execute('ffprobe', ['-v', 'error', '-read_intervals', '0%+10', '-select_streams', 'v:0', '-show_frames', '-show_entries', 'frame=best_effort_timestamp_time:stream=time_base', '-of', 'json', file])).toString());
79
+ const pts = (data.frames ?? []).map((frame) => Number(frame.best_effort_timestamp_time) * 1000);
80
+ const [tickNumerator, tickDenominator] = (data.streams?.[0]?.time_base ?? '').split('/').map(Number);
81
+ const tick = 1000 * tickNumerator / tickDenominator;
82
+ if (pts.length < 2 || !pts.every(Number.isFinite) || !Number.isFinite(tick) || markers.length !== 2 || markers[0].color !== '#ff00ff' || markers[1].color !== '#ffff00')
83
+ throw new ProductionError('CAPTURE_ORIGIN', 'Opening marker timestamps are unavailable. Preserve the capture and record a new run.', 6);
84
+ const { markerIndices, frameCount } = await scanMarkers(file, markers, pts, { first: 0, last: pts.length - 1, start_ms: pts[0] - tick / 2, end_ms: pts[pts.length - 1] + tick / 2 });
85
+ const intervals = markers.map(marker => {
86
+ const index = markerIndices.get(marker.color) ?? -1;
87
+ if (index <= 0 || !Number.isFinite(marker.observed_ms) || !Number.isFinite(marker.rendered_by_ms) || marker.rendered_by_ms < marker.observed_ms)
88
+ throw new ProductionError('CAPTURE_ORIGIN', `Opening marker ${marker.color} has no bounded decoded transition. Preserve the capture and record a new run.`, 6);
89
+ return { lower: pts[index - 1] - marker.rendered_by_ms - tick, upper: pts[index] - marker.observed_ms + tick };
90
+ });
91
+ const lower = Math.max(...intervals.map(interval => interval.lower));
92
+ const upper = Math.min(...intervals.map(interval => interval.upper));
93
+ if (frameCount !== pts.length || markerIndices.get('#ff00ff') >= markerIndices.get('#ffff00') || !Number.isFinite(lower) || !Number.isFinite(upper) || lower > upper)
94
+ throw new ProductionError('CAPTURE_ORIGIN', 'Opening markers do not establish a presentation-to-capture origin and content trim. Preserve the capture and record a new run.', 6);
95
+ const offset = (lower + upper) / 2;
96
+ const report = {
97
+ version: 1, status: 'not_evaluated', target_ms: 100, uncertainty_ms: (upper - lower) / 2,
98
+ mapping: { offset_ms: offset, offset_min_ms: lower, offset_max_ms: upper, rate: 1, trim_start_ms: Math.max(0, upper), trim_end_ms: offset + duration },
99
+ checks: [], coverage: [], gaps: ['The opening markers estimate capture origin only. The upper origin bound selects the opening trim, with any initial picture hold recorded by assembly. Per-cue timing and drift were not verified. Review the final video.'],
100
+ };
101
+ await saveJson(join(directory, 'calibration.json'), report);
102
+ return report;
103
+ }
104
+ export async function calibrate(file, markers, references, duration, directory) {
105
+ const checks = [];
106
+ const gaps = ['Checks cover the listed encoded visual transitions and source frames. They do not prove every frame or audible phoneme boundary.', 'Transition onset is the first decoded frame with mean RGB change above 8 on the reference mask and progress toward the settled image. Subthreshold changes are not measured.', 'Transition masks exclude visible video regions. Media timing uses separate source-frame samples.'];
107
+ const pending = new Set([...markers.map(marker => `marker:${marker.color}`), ...references.map(reference => reference.id)]);
108
+ const report = {
109
+ version: 1, status: 'failed', target_ms: 100, uncertainty_ms: 1000,
110
+ mapping: { offset_ms: 0, rate: 1, trim_start_ms: 0, trim_end_ms: 0 },
111
+ checks, coverage: references.map(reference => reference.id), gaps: [],
112
+ };
113
+ const checkpoint = async () => {
114
+ report.gaps = [...gaps, ...(pending.size ? [`Pending checks: ${[...pending].join(', ')}`] : [])];
115
+ await saveJson(join(directory, 'calibration.json'), report);
116
+ };
117
+ gaps.push('Capture origin has not yet been established.');
118
+ await checkpoint();
119
+ try {
120
+ const data = JSON.parse((await execute('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_frames', '-show_entries', 'frame=best_effort_timestamp_time:stream=time_base', '-of', 'json', file])).toString());
121
+ const pts = (data.frames ?? []).map((frame) => Number(frame.best_effort_timestamp_time) * 1000);
122
+ const [tickNumerator, tickDenominator] = (data.streams?.[0]?.time_base ?? '').split('/').map(Number);
123
+ const tick = 1000 * tickNumerator / tickDenominator;
124
+ let failed = pts.length < 2 || markers.length !== 6 || !pts.every(Number.isFinite) || !Number.isFinite(tick);
125
+ if (markers.length !== 6)
126
+ gaps.push('Verified timing requires all six calibration markers.');
127
+ if (pts.length < 2 || !pts.every(Number.isFinite) || !Number.isFinite(tick))
128
+ gaps.push('The capture timestamp inventory is unavailable or invalid.');
129
+ const markerFrames = {};
130
+ const { markerIndices, firstContent, frameCount } = await scanMarkers(file, markers, pts);
131
+ if (frameCount !== pts.length) {
132
+ failed = true;
133
+ gaps.push('The decoded frame count does not match the capture timestamps.');
134
+ }
135
+ const intervals = [];
136
+ for (const marker of markers) {
137
+ const index = markerIndices.get(marker.color) ?? -1;
138
+ if (index <= 0 || !Number.isFinite(marker.rendered_by_ms) || marker.rendered_by_ms < marker.observed_ms) {
139
+ failed = true;
140
+ gaps.push(`Missing bounded decoded transition for marker ${marker.color}`);
141
+ continue;
142
+ }
143
+ markerFrames[marker.color] = pts[index];
144
+ intervals.push({ lower: pts[index - 1] - marker.rendered_by_ms - tick, upper: pts[index] - marker.observed_ms + tick });
145
+ if (pts[index] - pts[index - 1] > 100) {
146
+ failed = true;
147
+ gaps.push(`Capture sampling exceeds 100 ms at marker ${marker.color}`);
148
+ }
149
+ }
150
+ const lower = Math.max(...intervals.map(interval => interval.lower));
151
+ const upper = Math.min(...intervals.map(interval => interval.upper));
152
+ const bounded = intervals.length === 6 && Number.isFinite(lower) && Number.isFinite(upper) && lower <= upper;
153
+ if (!bounded) {
154
+ failed = true;
155
+ gaps.push('Marker brackets do not establish a common presentation-to-capture offset.');
156
+ }
157
+ else
158
+ gaps.splice(gaps.indexOf('Capture origin has not yet been established.'), 1);
159
+ const offset = bounded ? (lower + upper) / 2 : 0;
160
+ const mappingUncertainty = bounded ? (upper - lower) / 2 : 1000;
161
+ const uncertainty = mappingUncertainty + Math.max(...references.map(reference => reference.frame_period_ms), 0) + tick;
162
+ if (!Number.isFinite(uncertainty))
163
+ failed = true;
164
+ const closing = markerFrames['#00ff00'];
165
+ if (firstContent === undefined || closing === undefined || Math.abs(firstContent - offset) > 100) {
166
+ failed = true;
167
+ gaps.push('Decoded opening content or closing trim does not satisfy the timing bound.');
168
+ }
169
+ report.uncertainty_ms = Number.isFinite(uncertainty) ? uncertainty : 1000;
170
+ report.mapping = { offset_ms: offset, offset_min_ms: bounded ? lower : 0, offset_max_ms: bounded ? upper : 0, rate: 1, trim_start_ms: firstContent ?? offset, trim_end_ms: Math.min(closing ?? offset + duration, offset + duration) };
171
+ for (const marker of markers) {
172
+ if (markerFrames[marker.color] !== undefined) {
173
+ const time = markerFrames[marker.color];
174
+ const index = markerIndices.get(marker.color);
175
+ const error = time - offset - marker.observed_ms;
176
+ const bound = mappingUncertainty + tick;
177
+ checks.push({ id: `marker:${marker.color}`, expected_ms: marker.observed_ms, observed_ms: time - offset, error_ms: error, evidence: file, frame_index: index, capture_ms: time, uncertainty_ms: bound, bracket_start_ms: pts[index - 1] - offset, bracket_end_ms: time - offset });
178
+ if (Math.abs(error) + bound > 100) {
179
+ failed = true;
180
+ gaps.push(`Timing bound exceeds target for marker ${marker.color}`);
181
+ }
182
+ }
183
+ pending.delete(`marker:${marker.color}`);
184
+ }
185
+ await checkpoint();
186
+ const pixelCache = new Map();
187
+ const referencePixels = (path) => {
188
+ let result = pixelCache.get(path);
189
+ if (!result) {
190
+ result = pixels(path);
191
+ pixelCache.set(path, result);
192
+ }
193
+ return result;
194
+ };
195
+ const prepared = [];
196
+ for (const reference of references) {
197
+ const before = await referencePixels(reference.before);
198
+ const after = await referencePixels(reference.after);
199
+ const mask = [];
200
+ for (let i = 0; i < bytes; i += 3) {
201
+ const x = i / 3 % analysisWidth / analysisWidth;
202
+ const y = Math.floor(i / 3 / analysisWidth) / analysisHeight;
203
+ if (reference.exclude?.some(rect => x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom))
204
+ continue;
205
+ if (Math.abs(before[i] - after[i]) + Math.abs(before[i + 1] - after[i + 1]) + Math.abs(before[i + 2] - after[i + 2]) > 90)
206
+ mask.push(i);
207
+ }
208
+ if (mask.length < 8) {
209
+ failed = true;
210
+ gaps.push(`No discriminating content for ${reference.id}`);
211
+ pending.delete(reference.id);
212
+ await checkpoint();
213
+ continue;
214
+ }
215
+ if (reference.mode === 'sample') {
216
+ let minX = analysisWidth;
217
+ let maxX = 0;
218
+ let minY = analysisHeight;
219
+ let maxY = 0;
220
+ for (const pixel of mask) {
221
+ const x = pixel / 3 % analysisWidth;
222
+ const y = Math.floor(pixel / 3 / analysisWidth);
223
+ minX = Math.min(minX, x);
224
+ maxX = Math.max(maxX, x);
225
+ minY = Math.min(minY, y);
226
+ maxY = Math.max(maxY, y);
227
+ }
228
+ const left = Math.max(0, minX - 26);
229
+ const right = Math.min(analysisWidth - 1, maxX + 26);
230
+ const top = Math.max(0, minY - 6);
231
+ const bottom = Math.min(analysisHeight - 1, maxY + 6);
232
+ mask.length = 0;
233
+ for (let y = top; y <= bottom; y++)
234
+ for (let x = left; x <= right; x++)
235
+ mask.push((y * analysisWidth + x) * 3);
236
+ }
237
+ const first = pts.findIndex(time => time - offset >= reference.expected_ms - 550);
238
+ let last = first;
239
+ while (last >= 0 && last < pts.length && pts[last] - offset <= reference.expected_ms + (reference.settle_ms ?? 0) + 550)
240
+ last++;
241
+ last--;
242
+ if (first < 0 || last < first) {
243
+ failed = true;
244
+ gaps.push(`Visible evidence missing for ${reference.id}`);
245
+ pending.delete(reference.id);
246
+ await checkpoint();
247
+ continue;
248
+ }
249
+ prepared.push({ reference, before, after, mask, first, last, distances: [] });
250
+ }
251
+ const windows = [];
252
+ for (const item of prepared.sort((a, b) => a.first - b.first)) {
253
+ const previous = windows[windows.length - 1];
254
+ if (previous && item.first <= previous.last + 1) {
255
+ previous.last = Math.max(previous.last, item.last);
256
+ previous.references.push(item);
257
+ }
258
+ else
259
+ windows.push({ first: item.first, last: item.last, references: [item] });
260
+ }
261
+ const decide = (item) => {
262
+ const { reference, before, after, mask, distances } = item;
263
+ pending.delete(reference.id);
264
+ if (distances.length !== item.last - item.first + 1) {
265
+ failed = true;
266
+ gaps.push(`Incomplete decoded window for ${reference.id}`);
267
+ return;
268
+ }
269
+ let found;
270
+ if (reference.mode === 'transition') {
271
+ let difference = 0;
272
+ for (const pixel of mask)
273
+ for (let channel = 0; channel < 3; channel++)
274
+ difference += Math.abs(after[pixel + channel] - before[pixel + channel]);
275
+ difference /= mask.length * 3;
276
+ const onset = distances.find((entry, index) => index > 0 && distances[index - 1].old <= 8 && entry.old > 8 && entry.current < difference - 8);
277
+ const settled = onset && distances.find(entry => entry.index >= onset.index && entry.current < 30 && entry.current < entry.old * 0.4);
278
+ if (!settled || settled.time - offset > reference.expected_ms + (reference.settle_ms ?? 0) + 100) {
279
+ failed = true;
280
+ gaps.push(`Settled visual state missing within the declared duration for ${reference.id}`);
281
+ return;
282
+ }
283
+ found = onset;
284
+ const previous = onset && distances.find(entry => entry.index === onset.index - 1);
285
+ if (!previous || previous.old > 8) {
286
+ failed = true;
287
+ gaps.push(`No bounded visible onset for ${reference.id}`);
288
+ return;
289
+ }
290
+ }
291
+ else
292
+ found = distances.reduce((best, entry) => !best || entry.current < best.current ? entry : best, undefined);
293
+ if (!found || found.index === 0 || (reference.mode === 'sample' && found.current > 30)) {
294
+ failed = true;
295
+ gaps.push(`Visible evidence missing for ${reference.id}`);
296
+ return;
297
+ }
298
+ const observed = found.time - offset;
299
+ const error = observed - reference.expected_ms;
300
+ const bound = mappingUncertainty + reference.frame_period_ms + tick;
301
+ checks.push({ id: reference.id, expected_ms: reference.expected_ms, observed_ms: observed, error_ms: error, evidence: file, frame_index: found.index, capture_ms: found.time, uncertainty_ms: bound, bracket_start_ms: pts[found.index - 1] - offset, bracket_end_ms: observed });
302
+ if (Math.abs(error) + bound > 100 || found.time - pts[found.index - 1] > 100) {
303
+ failed = true;
304
+ gaps.push(`Timing or capture-sampling bound exceeds target for ${reference.id}`);
305
+ }
306
+ };
307
+ for (const window of windows) {
308
+ const active = new Set();
309
+ let next = 0;
310
+ for await (const { frame, index } of decodedFrames(file, { first: window.first, last: window.last, start_ms: pts[window.first] - tick / 2, end_ms: pts[window.last] + tick / 2 })) {
311
+ while (next < window.references.length && window.references[next].first <= index)
312
+ active.add(window.references[next++]);
313
+ for (const item of active) {
314
+ let old = 0;
315
+ let current = 0;
316
+ for (const pixel of item.mask)
317
+ for (let channel = 0; channel < 3; channel++) {
318
+ old += Math.abs(frame[pixel + channel] - item.before[pixel + channel]);
319
+ current += Math.abs(frame[pixel + channel] - item.after[pixel + channel]);
320
+ }
321
+ item.distances.push({ time: pts[index], index, old: old / (item.mask.length * 3), current: current / (item.mask.length * 3) });
322
+ if (index === item.last) {
323
+ decide(item);
324
+ active.delete(item);
325
+ await checkpoint();
326
+ }
327
+ }
328
+ }
329
+ for (const item of window.references)
330
+ if (pending.has(item.reference.id)) {
331
+ decide(item);
332
+ await checkpoint();
333
+ }
334
+ }
335
+ executionScope.getStore()?.throwIfAborted();
336
+ report.status = failed || pending.size ? 'failed' : 'accepted';
337
+ await checkpoint();
338
+ return report;
339
+ }
340
+ catch (error) {
341
+ report.status = 'failed';
342
+ gaps.push(`Calibration interrupted or failed: ${error instanceof Error ? error.message : String(error)}`);
343
+ await checkpoint();
344
+ throw error;
345
+ }
346
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};