@slidevideo/cli 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +2 -2
  3. package/addons/slidevideo/geometry.ts +63 -30
  4. package/addons/slidevideo/global-top.vue +41 -9
  5. package/addons/slidevideo/playback-entries.ts +16 -5
  6. package/addons/slidevideo/preview.ts +26 -14
  7. package/dist/adapters/powerpoint.d.ts +7 -4
  8. package/dist/adapters/powerpoint.js +146 -40
  9. package/dist/adapters/slidev-inspection.d.ts +5 -2
  10. package/dist/adapters/slidev-inspection.js +3 -2
  11. package/dist/adapters/slidev.d.ts +3 -4
  12. package/dist/adapters/slidev.js +20 -19
  13. package/dist/annotation-paint.d.ts +65 -11
  14. package/dist/annotation-paint.js +290 -10
  15. package/dist/annotations.d.ts +13 -8
  16. package/dist/annotations.js +619 -88
  17. package/dist/assembly.d.ts +4 -2
  18. package/dist/assembly.js +23 -18
  19. package/dist/cli.js +102 -16
  20. package/dist/compositor.d.ts +10 -5
  21. package/dist/compositor.js +215 -128
  22. package/dist/contracts.d.ts +93 -30
  23. package/dist/contracts.js +2 -1
  24. package/dist/media.d.ts +5 -0
  25. package/dist/media.js +30 -0
  26. package/dist/pipeline.d.ts +37 -9
  27. package/dist/pipeline.js +62 -10
  28. package/dist/preview/contracts.d.ts +3 -3
  29. package/dist/preview/player.js +20 -15
  30. package/dist/preview/server.d.ts +2 -1
  31. package/dist/preview/server.js +6 -5
  32. package/dist/setup.d.ts +3 -0
  33. package/dist/setup.js +16 -1
  34. package/dist/skill-install.d.ts +35 -0
  35. package/dist/skill-install.js +132 -0
  36. package/dist/storyboard.js +9 -0
  37. package/package.json +4 -1
  38. package/schemas/annotation-geometry.v1.json +260 -28
  39. package/schemas/run-manifest.v1.json +31 -0
  40. package/schemas/schedule.v1.json +448 -182
  41. package/schemas/storyboard.v1.json +358 -174
  42. package/skills/slidevideo/SKILL.md +11 -9
  43. package/skills/slidevideo/references/decks.md +228 -0
  44. package/skills/slidevideo/references/production.md +14 -10
  45. package/skills/slidevideo/references/storyboard.md +69 -37
  46. package/tools/powerpoint/Native.cs +85 -1
  47. package/tools/powerpoint/powerpoint.ps1 +188 -101
  48. package/tools/powerpoint/preview.ps1 +10 -9
@@ -1,114 +1,645 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
1
4
  import { join } from 'node:path';
2
- import { execute, hashFile, saveJson } from './media.js';
3
- import { requireCondition } from './errors.js';
4
- import { annotationPaint } from './annotation-paint.js';
5
- export function annotationApplications(story, schedule, visual, audioOrigin) {
6
- return schedule.annotations.map(annotation => {
5
+ import { balancedSum, execute, executionSignal, ffmpegFilterScriptFlags, hashFile, saveJson } from './media.js';
6
+ import { executable } from './executables.js';
7
+ import { ProductionError, requireCondition } from './errors.js';
8
+ import { effectPrimitives, findTargetGeometry, highlightPaint, underlineFragmentPrimitives, underlineFragmentsVisible, underlinePaint, underlineWipeFractions, } from './annotation-paint.js';
9
+ function toRgbPrimitive(paint) {
10
+ return {
11
+ ...paint,
12
+ rgb: [
13
+ Number.parseInt(paint.color.slice(1, 3), 16),
14
+ Number.parseInt(paint.color.slice(3, 5), 16),
15
+ Number.parseInt(paint.color.slice(5, 7), 16),
16
+ ],
17
+ };
18
+ }
19
+ function inside(rect, x, y) {
20
+ return x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height;
21
+ }
22
+ function blendChannel(value, item, channel) {
23
+ const color = item.rgb[channel];
24
+ const painted = item.blend === 'darken' ? Math.min(value, color) : color;
25
+ return value * (1 - item.opacity) + painted * item.opacity;
26
+ }
27
+ class RawFrameReader {
28
+ chunks = [];
29
+ buffered = 0;
30
+ iterator;
31
+ ended = false;
32
+ constructor(stream) {
33
+ this.iterator = stream[Symbol.asyncIterator]();
34
+ }
35
+ async readInto(target) {
36
+ const size = target.length;
37
+ while (this.buffered < size && !this.ended) {
38
+ const next = await this.iterator.next();
39
+ if (next.done) {
40
+ this.ended = true;
41
+ break;
42
+ }
43
+ const chunk = Buffer.isBuffer(next.value) ? next.value : Buffer.from(next.value);
44
+ this.chunks.push(chunk);
45
+ this.buffered += chunk.length;
46
+ }
47
+ if (this.buffered < size)
48
+ return false;
49
+ let written = 0;
50
+ while (written < size) {
51
+ const head = this.chunks[0];
52
+ const needed = size - written;
53
+ if (head.length <= needed) {
54
+ head.copy(target, written);
55
+ written += head.length;
56
+ this.chunks.shift();
57
+ }
58
+ else {
59
+ head.copy(target, written, 0, needed);
60
+ this.chunks[0] = head.subarray(needed);
61
+ written += needed;
62
+ }
63
+ }
64
+ this.buffered -= size;
65
+ return true;
66
+ }
67
+ async expectEnd() {
68
+ if (this.buffered > 0)
69
+ return false;
70
+ if (this.ended)
71
+ return true;
72
+ const next = await this.iterator.next();
73
+ if (next.done) {
74
+ this.ended = true;
75
+ return true;
76
+ }
77
+ const chunk = Buffer.isBuffer(next.value) ? next.value : Buffer.from(next.value);
78
+ return chunk.length === 0;
79
+ }
80
+ }
81
+ function decoderCompletion(child, label) {
82
+ let diagnostic = '';
83
+ child.stderr?.on('data', data => { diagnostic = (diagnostic + data.toString()).slice(-4000); });
84
+ const done = new Promise((resolve, reject) => {
85
+ child.once('error', error => reject(new ProductionError('ANNOTATION_EVIDENCE', `${label}: ${error.message}`, 6)));
86
+ child.once('close', code => code === 0 ? resolve() : reject(new ProductionError('ANNOTATION_EVIDENCE', `${label} exited ${code}: ${diagnostic}`, 6)));
87
+ });
88
+ void done.catch(() => { });
89
+ return done;
90
+ }
91
+ function hasMeasurableRects(rects, video) {
92
+ return rects.some(rect => {
93
+ const left = Math.max(0, Math.ceil(rect.x));
94
+ const right = Math.min(video.width, Math.floor(rect.x + rect.width));
95
+ const top = Math.max(0, Math.ceil(rect.y));
96
+ const bottom = Math.min(video.height, Math.floor(rect.y + rect.height));
97
+ return right - left >= 2 && bottom - top >= 2;
98
+ });
99
+ }
100
+ function measureRegion(finalFrame, baseFrame, video, covered, appPrimitives, targetAppIndex, targetOppositePrimitives, sampleRects) {
101
+ let expectedError = 0;
102
+ let oppositeError = 0;
103
+ let contrast = 0;
104
+ let count = 0;
105
+ for (const rect of sampleRects) {
106
+ const left = Math.max(0, Math.ceil(rect.x));
107
+ const right = Math.min(video.width, Math.floor(rect.x + rect.width));
108
+ const top = Math.max(0, Math.ceil(rect.y));
109
+ const bottom = Math.min(video.height, Math.floor(rect.y + rect.height));
110
+ const w = right - left;
111
+ const h = bottom - top;
112
+ if (w < 2 || h < 2)
113
+ continue;
114
+ const mx = w >= 16 ? 4 : w >= 8 ? 2 : w >= 3 ? 1 : 0;
115
+ const my = h >= 16 ? 4 : h >= 8 ? 2 : h >= 3 ? 1 : 0;
116
+ const x0 = left + mx;
117
+ const x1 = right - mx;
118
+ const y0 = top + my;
119
+ const y1 = bottom - my;
120
+ const stepX = Math.max(1, Math.floor((x1 - x0) / 256));
121
+ const stepY = Math.max(1, Math.floor((y1 - y0) / 32));
122
+ for (let y = y0; y < y1; y += stepY) {
123
+ for (let x = x0; x < x1; x += stepX) {
124
+ const px = x + 0.5;
125
+ const py = y + 0.5;
126
+ if (covered.some(bounds => inside(bounds, px, py)))
127
+ continue;
128
+ const offset = (y * video.width + x) * 3;
129
+ for (const channel of [0, 1, 2]) {
130
+ let expected = baseFrame[offset + channel];
131
+ let opposite = expected;
132
+ for (let appIndex = 0; appIndex < appPrimitives.length; appIndex++) {
133
+ for (const primitive of appPrimitives[appIndex]) {
134
+ if (inside(primitive.rectangle, px, py))
135
+ expected = blendChannel(expected, primitive, channel);
136
+ }
137
+ const oppositeList = appIndex === targetAppIndex ? targetOppositePrimitives : appPrimitives[appIndex];
138
+ for (const primitive of oppositeList) {
139
+ if (inside(primitive.rectangle, px, py))
140
+ opposite = blendChannel(opposite, primitive, channel);
141
+ }
142
+ }
143
+ expectedError += Math.abs(finalFrame[offset + channel] - expected);
144
+ oppositeError += Math.abs(finalFrame[offset + channel] - opposite);
145
+ contrast += Math.abs(expected - opposite);
146
+ count++;
147
+ }
148
+ }
149
+ }
150
+ }
151
+ const passed = count > 0 && contrast / count >= 4 && expectedError / count <= 12 && expectedError < oppositeError * 0.7;
152
+ return {
153
+ count,
154
+ expected_error: count ? expectedError / count : null,
155
+ opposite_error: count ? oppositeError / count : null,
156
+ contrast: count ? contrast / count : null,
157
+ passed,
158
+ };
159
+ }
160
+ export function annotationApplications(video, schedule, visual, audioOrigin) {
161
+ const observations = visual.annotation_geometry ?? [];
162
+ return schedule.annotations.map((annotation) => {
7
163
  const context = { annotation: annotation.id, target: annotation.target };
8
- const candidates = (visual.annotation_geometry ?? []).filter(item => item.id === annotation.id);
9
- requireCondition(candidates.length === 1, 'ANNOTATION_GEOMETRY', `Annotation ${annotation.id}: missing or ambiguous capture geometry`, 5, context);
10
- const geometry = candidates[0];
11
- const { content, bounds, viewport } = geometry;
12
- const finite = [content.x, content.y, content.width, content.height, bounds.x, bounds.y, bounds.width, bounds.height, viewport.width, viewport.height, geometry.samples, geometry.observed_start_ms, geometry.observed_end_ms].every(Number.isFinite);
13
- requireCondition(finite && geometry.scene === annotation.scene && geometry.slide === annotation.slide && geometry.visit === annotation.visit && geometry.click === annotation.click && geometry.start_ms === annotation.start_ms && geometry.end_ms === annotation.end_ms && geometry.samples >= 2 && geometry.observed_start_ms >= annotation.start_ms && geometry.observed_start_ms < annotation.end_ms && geometry.observed_end_ms >= annotation.end_ms, 'ANNOTATION_GEOMETRY', `Annotation ${annotation.id}: incomplete or stale playback geometry`, 5, context);
14
- requireCondition(viewport.width === visual.properties.width && viewport.height === visual.properties.height && viewport.width === story.output.width && viewport.height === story.output.height && content.x >= -0.01 && content.y >= -0.01 && content.width > 0 && content.height > 0 && content.x + content.width <= viewport.width + 0.01 && content.y + content.height <= viewport.height + 0.01 && bounds.x >= -0.00001 && bounds.y >= -0.00001 && bounds.width > 0 && bounds.height > 0 && bounds.x + bounds.width <= 1.00001 && bounds.y + bounds.height <= 1.00001, 'ANNOTATION_GEOMETRY', `Annotation ${annotation.id}: invalid viewport, slide-content rectangle or target bounds`, 5, context);
164
+ const geometry = findTargetGeometry(observations, annotation, annotation.target);
165
+ requireCondition(geometry, 'ANNOTATION_GEOMETRY', `Annotation ${annotation.id}: missing or ambiguous capture geometry`, 5, context);
166
+ const { content, fragments, viewport } = geometry;
167
+ const finite = [
168
+ content.x, content.y, content.width, content.height,
169
+ viewport.width, viewport.height,
170
+ geometry.samples, geometry.observed_start_ms, geometry.observed_end_ms,
171
+ ...fragments.flatMap(fragment => [fragment.x, fragment.y, fragment.width, fragment.height]),
172
+ ].every(Number.isFinite);
173
+ requireCondition(finite &&
174
+ geometry.scene === annotation.scene &&
175
+ geometry.slide === annotation.slide &&
176
+ geometry.visit === annotation.visit &&
177
+ geometry.click === annotation.click &&
178
+ geometry.start_ms <= annotation.start_ms &&
179
+ geometry.end_ms >= annotation.end_ms &&
180
+ geometry.samples >= 2 &&
181
+ geometry.observed_start_ms >= geometry.start_ms &&
182
+ geometry.observed_start_ms < annotation.end_ms &&
183
+ geometry.observed_end_ms >= annotation.end_ms, 'ANNOTATION_GEOMETRY', `Annotation ${annotation.id}: incomplete or stale playback geometry`, 5, context);
184
+ requireCondition(viewport.width === visual.properties.width &&
185
+ viewport.height === visual.properties.height &&
186
+ viewport.width === video.width &&
187
+ viewport.height === video.height &&
188
+ content.x >= -0.01 &&
189
+ content.y >= -0.01 &&
190
+ content.width > 0 &&
191
+ content.height > 0 &&
192
+ content.x + content.width <= viewport.width + 0.01 &&
193
+ content.y + content.height <= viewport.height + 0.01 &&
194
+ fragments.length >= 1 &&
195
+ fragments.every(bounds => bounds.x >= -0.00001 && bounds.y >= -0.00001 && bounds.width > 0 && bounds.height > 0 && bounds.x + bounds.width <= 1.00001 && bounds.y + bounds.height <= 1.00001), 'ANNOTATION_GEOMETRY', `Annotation ${annotation.id}: invalid viewport, slide-content rectangle or target bounds`, 5, context);
15
196
  const target = annotation.target;
16
- if (target.type === 'region')
17
- requireCondition(['x', 'y', 'width', 'height'].every(key => Math.abs(bounds[key] - target[key]) < 0.00001), 'ANNOTATION_GEOMETRY', `Annotation ${annotation.id}: region geometry differs from authored coordinates`, 5, context);
197
+ if (target.type === 'region') {
198
+ requireCondition(fragments.length === 1 && ['x', 'y', 'width', 'height'].every(key => Math.abs(fragments[0][key] - target[key]) < 0.00001), 'ANNOTATION_GEOMETRY', `Annotation ${annotation.id}: region geometry differs from authored coordinates`, 5, context);
199
+ }
18
200
  const start_ms = annotation.start_ms + audioOrigin;
19
201
  const end_ms = annotation.end_ms + audioOrigin;
20
- const first_frame = Math.ceil(start_ms * story.output.fps / 1000 - 1e-9);
21
- const end_frame = Math.ceil(end_ms * story.output.fps / 1000 - 1e-9);
22
- requireCondition(first_frame < end_frame, 'ANNOTATION_FRAME_RANGE', `Annotation ${annotation.id}: interval contains no output frame at ${story.output.fps} fps`, 2, context);
23
- return { id: annotation.id, start_ms, end_ms, first_frame, end_frame, ...annotationPaint(annotation, geometry), geometry };
202
+ const first_frame = Math.ceil(start_ms * video.fps / 1000 - 1e-9);
203
+ const end_frame = Math.ceil(end_ms * video.fps / 1000 - 1e-9);
204
+ requireCondition(first_frame < end_frame, 'ANNOTATION_FRAME_RANGE', `Annotation ${annotation.id}: interval contains no output frame at ${video.fps} fps`, 2, context);
205
+ switch (annotation.effect) {
206
+ case 'highlight': {
207
+ const painted = highlightPaint({ appearance: annotation.appearance, start_ms, end_ms }, geometry);
208
+ return { ...painted, id: annotation.id, first_frame, end_frame, geometry };
209
+ }
210
+ case 'underline': {
211
+ const painted = underlinePaint({ appearance: annotation.appearance, motion: annotation.motion, start_ms, end_ms }, geometry);
212
+ requireCondition(underlineFragmentsVisible(painted), 'ANNOTATION_GEOMETRY', `Annotation ${annotation.id}: underline is clipped outside the slide-content rectangle`, 5, context);
213
+ return { ...painted, id: annotation.id, first_frame, end_frame, geometry };
214
+ }
215
+ }
24
216
  });
25
217
  }
26
- export async function verifyAnnotations(file, base, baseFilter, applications, story, directory, output, overlayBounds = () => [], sha256) {
218
+ export async function verifyAnnotations(file, base, baseFilter, applications, video, directory, output, overlayBounds = () => [], sha256) {
27
219
  const evidenceFile = join(directory, 'annotations-evidence.json');
28
220
  const provenance = { sha256: sha256 ?? await hashFile(file), base: { file: base, filter: baseFilter } };
29
221
  await saveJson(evidenceFile, { version: 1, status: 'failed', file: join(directory, 'failed-composite.mp4'), ...provenance, checks: [], gaps: ['Final composite verification did not complete.'] });
30
222
  const metadata = JSON.parse((await execute('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_frames', '-show_entries', 'frame=best_effort_timestamp_time', '-of', 'json', file])).toString());
31
- const requested = applications.flatMap(item => [item.first_frame - 1, item.first_frame, item.end_frame - 1, item.end_frame]);
32
- const indices = [...new Set(requested.filter(index => index >= 0 && index < metadata.frames.length))].sort((a, b) => a - b);
33
- const select = `select='${indices.map(index => `eq(n,${index})`).join('+')}',scale=320:180,format=rgb24`;
34
- const frames = await execute('ffmpeg', ['-v', 'error', '-xerror', '-i', file, '-vf', select, '-fps_mode', 'passthrough', '-f', 'rawvideo', '-']);
35
- const originals = await execute('ffmpeg', ['-v', 'error', '-xerror', '-i', base, '-vf', `${baseFilter},${select}`, '-fps_mode', 'passthrough', '-f', 'rawvideo', '-']);
36
- const bytes = 320 * 180 * 3;
37
- requireCondition(frames.length === indices.length * bytes && originals.length === frames.length, 'ANNOTATION_EVIDENCE', 'Final and base frame decoding did not return the requested encoded frame samples', 6);
38
- const checks = [];
223
+ const totalFrames = metadata.frames.length;
224
+ const tasksByFrame = new Map();
225
+ const orderedChecks = [];
39
226
  const gaps = [];
40
- const layers = applications.flatMap(item => [
41
- { ...item, part: 'fill' },
42
- ...(item.bottom_border ? [{ ...item, ...item.bottom_border, part: 'bottom_border' }] : []),
43
- ]);
44
- const rgb = layers.map(item => [1, 3, 5].map(offset => Number.parseInt(item.color.slice(offset, offset + 2), 16)));
45
- function blend(value, item, color) {
46
- const painted = item.blend === 'darken' ? Math.min(value, color) : color;
47
- return value * (1 - item.opacity) + painted * item.opacity;
48
- }
49
- function inside(rect, x, y) {
50
- return x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height;
51
- }
52
- for (const [layer, item] of layers.entries()) {
53
- if (item.first_frame >= item.end_frame || item.first_frame >= metadata.frames.length) {
227
+ const coverage = [];
228
+ const requiredActiveParts = [];
229
+ let nextOrder = 0;
230
+ const enqueue = (frameIndex, run) => {
231
+ const order = nextOrder++;
232
+ const list = tasksByFrame.get(frameIndex) ?? [];
233
+ list.push({ frameIndex, order, run });
234
+ tasksByFrame.set(frameIndex, list);
235
+ return order;
236
+ };
237
+ const checkBoundaryTimestamp = (id, boundary, frameIndex, expectedTime) => {
238
+ const observed = Number(metadata.frames[frameIndex].best_effort_timestamp_time) * 1000;
239
+ if (!Number.isFinite(observed) || Math.abs(observed - expectedTime) + 1000 / video.fps > 100) {
240
+ gaps.push(`${id}:${boundary}: encoded timestamp uncertainty exceeds 100 ms`);
241
+ }
242
+ };
243
+ for (const [appIndex, item] of applications.entries()) {
244
+ if (item.first_frame >= item.end_frame || item.first_frame >= totalFrames) {
54
245
  gaps.push(`${item.id}: no active encoded frame is available to prove appearance`);
55
246
  continue;
56
247
  }
57
- for (const [boundary, first, expectedTime] of [['start', item.first_frame, item.start_ms], ['end', item.end_frame, item.end_ms]]) {
58
- if (first >= metadata.frames.length) {
59
- gaps.push(`${item.id}:${boundary}: no encoded frame exists after this boundary`);
60
- continue;
248
+ switch (item.effect) {
249
+ case 'highlight': {
250
+ for (const [fragmentIndex, fragment] of item.fragments.entries()) {
251
+ const suffix = item.fragments.length === 1 ? '' : `:${fragmentIndex}`;
252
+ const parts = [
253
+ { part: `fill${suffix}`, paint: fragment.fill },
254
+ ...(fragment.bottom_border ? [{ part: `bottom_border${suffix}`, paint: fragment.bottom_border }] : []),
255
+ ];
256
+ for (const { part, paint } of parts) {
257
+ requiredActiveParts.push({ id: item.id, part });
258
+ const targetRgb = toRgbPrimitive(paint);
259
+ coverage.push(`${item.id}:${part}:start,end`);
260
+ for (const [boundary, boundaryFrame, expectedTime] of [['start', item.first_frame, item.start_ms], ['end', item.end_frame, item.end_ms]]) {
261
+ if (boundaryFrame >= totalFrames) {
262
+ gaps.push(`${item.id}:${boundary}: no encoded frame exists after this boundary`);
263
+ continue;
264
+ }
265
+ for (const index of [boundaryFrame - 1, boundaryFrame].filter(frame => frame >= 0)) {
266
+ const expectedActive = index >= item.first_frame && index < item.end_frame;
267
+ const order = enqueue(index, (finalFrame, baseFrame, covered, appPrimitives, timestampMs) => {
268
+ const current = appPrimitives[appIndex];
269
+ const oppositeList = expectedActive
270
+ ? current.filter(entry => entry.rectangle !== paint.rectangle)
271
+ : [...current, targetRgb];
272
+ const metrics = measureRegion(finalFrame, baseFrame, video, covered, appPrimitives, appIndex, oppositeList, [paint.rectangle]);
273
+ orderedChecks.push({
274
+ order,
275
+ entry: {
276
+ annotation: item.id,
277
+ part,
278
+ boundary,
279
+ frame_index: index,
280
+ encoded_ms: timestampMs,
281
+ expected_active: expectedActive,
282
+ expected_error: metrics.expected_error,
283
+ opposite_error: metrics.opposite_error,
284
+ contrast: metrics.contrast,
285
+ passed: metrics.passed,
286
+ },
287
+ gap: metrics.passed ? undefined : `${item.id}:${part}:${boundary}: frame ${index} does not distinguish the expected highlight state from its opposite`,
288
+ });
289
+ });
290
+ }
291
+ checkBoundaryTimestamp(item.id, boundary, boundaryFrame, expectedTime);
292
+ }
293
+ }
294
+ }
295
+ break;
61
296
  }
62
- for (const index of [first - 1, first].filter(index => index >= 0)) {
63
- const frameOffset = indices.indexOf(index) * bytes;
64
- const covered = overlayBounds(index);
65
- let expectedError = 0;
66
- let oppositeError = 0;
67
- let contrast = 0;
68
- let count = 0;
69
- for (let y = 0; y < 180; y++)
70
- for (let x = 0; x < 320; x++) {
71
- const px = (x + 0.5) * story.output.width / 320;
72
- const py = (y + 0.5) * story.output.height / 180;
73
- const rect = item.rectangle;
74
- if (px < rect.x + story.output.width / 320 * 2 || px >= rect.x + rect.width - story.output.width / 320 * 2 || py < rect.y + story.output.height / 180 * 2 || py >= rect.y + rect.height - story.output.height / 180 * 2)
75
- continue;
76
- if (covered.some(bounds => inside(bounds, px, py)))
297
+ case 'underline': {
298
+ const lastAvailable = Math.min(item.end_frame, totalFrames) - 1;
299
+ const settledFirst = item.in_ms > 0 ? Math.ceil((item.start_ms + item.in_ms) * video.fps / 1000 - 1e-9) : item.first_frame;
300
+ const settledLast = item.out_ms > 0 ? Math.floor((item.end_ms - item.out_ms) * video.fps / 1000 + 1e-9) - 1 : item.end_frame - 1;
301
+ let activeStartFrame = settledFirst;
302
+ let activeEndFrame = Math.min(settledLast, lastAvailable);
303
+ if (activeStartFrame > activeEndFrame) {
304
+ let bestFrame = item.first_frame;
305
+ let bestSpan = -1;
306
+ for (let frame = item.first_frame; frame <= lastAvailable; frame++) {
307
+ const { wipeStart, wipeEnd } = underlineWipeFractions(item, frame * 1000 / video.fps);
308
+ const span = Math.max(0, wipeEnd - wipeStart);
309
+ if (span > bestSpan) {
310
+ bestSpan = span;
311
+ bestFrame = frame;
312
+ }
313
+ }
314
+ activeStartFrame = bestFrame;
315
+ activeEndFrame = bestFrame;
316
+ }
317
+ for (const [fragmentIndex, fragment] of item.fragments.entries()) {
318
+ const suffix = item.fragments.length === 1 ? '' : `:${fragmentIndex}`;
319
+ const part = `stroke${suffix}`;
320
+ requiredActiveParts.push({ id: item.id, part });
321
+ const settledPaints = underlineFragmentPrimitives(fragment, fragment.rectangle.x, fragment.rectangle.x + fragment.rectangle.width).map(toRgbPrimitive);
322
+ const settledRects = settledPaints.map(entry => entry.rectangle);
323
+ const singleFragmentEffect = { ...item, fragments: [fragment] };
324
+ coverage.push(`${item.id}:${part}:start,end`);
325
+ if (item.first_frame - 1 >= 0) {
326
+ const clearStartIndex = item.first_frame - 1;
327
+ const order = enqueue(clearStartIndex, (finalFrame, baseFrame, covered, appPrimitives, timestampMs) => {
328
+ const oppositeList = [...appPrimitives[appIndex], ...settledPaints];
329
+ const metrics = measureRegion(finalFrame, baseFrame, video, covered, appPrimitives, appIndex, oppositeList, settledRects);
330
+ orderedChecks.push({
331
+ order,
332
+ entry: {
333
+ annotation: item.id,
334
+ part,
335
+ boundary: 'start',
336
+ frame_index: clearStartIndex,
337
+ encoded_ms: timestampMs,
338
+ expected_active: false,
339
+ expected_error: metrics.expected_error,
340
+ opposite_error: metrics.opposite_error,
341
+ contrast: metrics.contrast,
342
+ passed: metrics.passed,
343
+ },
344
+ gap: metrics.passed ? undefined : `${item.id}:${part}:start: frame ${clearStartIndex} does not distinguish the expected underline state from its opposite`,
345
+ });
346
+ });
347
+ }
348
+ {
349
+ const activeIndex = activeStartFrame;
350
+ const activeRects = effectPrimitives([singleFragmentEffect], activeIndex * 1000 / video.fps).map(entry => entry.rectangle);
351
+ const order = enqueue(activeIndex, (finalFrame, baseFrame, covered, appPrimitives, timestampMs) => {
352
+ const oppositeList = appPrimitives[appIndex].filter(entry => !(entry.rectangle.y === fragment.rectangle.y && entry.rectangle.x >= fragment.rectangle.x && entry.rectangle.x + entry.rectangle.width <= fragment.rectangle.x + fragment.rectangle.width));
353
+ const metrics = measureRegion(finalFrame, baseFrame, video, covered, appPrimitives, appIndex, oppositeList, activeRects);
354
+ orderedChecks.push({
355
+ order,
356
+ entry: {
357
+ annotation: item.id,
358
+ part,
359
+ boundary: 'start',
360
+ frame_index: activeIndex,
361
+ encoded_ms: timestampMs,
362
+ expected_active: true,
363
+ expected_error: metrics.expected_error,
364
+ opposite_error: metrics.opposite_error,
365
+ contrast: metrics.contrast,
366
+ passed: metrics.passed,
367
+ },
368
+ gap: metrics.passed ? undefined : `${item.id}:${part}:start: frame ${activeIndex} does not distinguish the expected underline state from its opposite`,
369
+ });
370
+ });
371
+ }
372
+ checkBoundaryTimestamp(item.id, 'start', item.first_frame, item.start_ms);
373
+ if (item.end_frame >= totalFrames) {
374
+ gaps.push(`${item.id}:end: no encoded frame exists after this boundary`);
375
+ }
376
+ else {
377
+ {
378
+ const activeIndex = activeEndFrame;
379
+ const activeRects = effectPrimitives([singleFragmentEffect], activeIndex * 1000 / video.fps).map(entry => entry.rectangle);
380
+ const order = enqueue(activeIndex, (finalFrame, baseFrame, covered, appPrimitives, timestampMs) => {
381
+ const oppositeList = appPrimitives[appIndex].filter(entry => !(entry.rectangle.y === fragment.rectangle.y && entry.rectangle.x >= fragment.rectangle.x && entry.rectangle.x + entry.rectangle.width <= fragment.rectangle.x + fragment.rectangle.width));
382
+ const metrics = measureRegion(finalFrame, baseFrame, video, covered, appPrimitives, appIndex, oppositeList, activeRects);
383
+ orderedChecks.push({
384
+ order,
385
+ entry: {
386
+ annotation: item.id,
387
+ part,
388
+ boundary: 'end',
389
+ frame_index: activeIndex,
390
+ encoded_ms: timestampMs,
391
+ expected_active: true,
392
+ expected_error: metrics.expected_error,
393
+ opposite_error: metrics.opposite_error,
394
+ contrast: metrics.contrast,
395
+ passed: metrics.passed,
396
+ },
397
+ gap: metrics.passed ? undefined : `${item.id}:${part}:end: frame ${activeIndex} does not distinguish the expected underline state from its opposite`,
398
+ });
399
+ });
400
+ }
401
+ {
402
+ const clearEndIndex = item.end_frame;
403
+ const order = enqueue(clearEndIndex, (finalFrame, baseFrame, covered, appPrimitives, timestampMs) => {
404
+ const oppositeList = [...appPrimitives[appIndex], ...settledPaints];
405
+ const metrics = measureRegion(finalFrame, baseFrame, video, covered, appPrimitives, appIndex, oppositeList, settledRects);
406
+ orderedChecks.push({
407
+ order,
408
+ entry: {
409
+ annotation: item.id,
410
+ part,
411
+ boundary: 'end',
412
+ frame_index: clearEndIndex,
413
+ encoded_ms: timestampMs,
414
+ expected_active: false,
415
+ expected_error: metrics.expected_error,
416
+ opposite_error: metrics.opposite_error,
417
+ contrast: metrics.contrast,
418
+ passed: metrics.passed,
419
+ },
420
+ gap: metrics.passed ? undefined : `${item.id}:${part}:end: frame ${clearEndIndex} does not distinguish the expected underline state from its opposite`,
421
+ });
422
+ });
423
+ }
424
+ checkBoundaryTimestamp(item.id, 'end', item.end_frame, item.end_ms);
425
+ }
426
+ }
427
+ const totalWidth = item.fragments.reduce((sum, fragment) => sum + Math.max(0, fragment.rectangle.width), 0);
428
+ const fullUnderlinePaints = item.fragments.flatMap(fragment => underlineFragmentPrimitives(fragment, fragment.rectangle.x, fragment.rectangle.x + fragment.rectangle.width).map(toRgbPrimitive));
429
+ const buildWipeRegions = (timeMs) => {
430
+ const { wipeStart, wipeEnd } = underlineWipeFractions(item, timeMs);
431
+ const globalStart = Math.round(totalWidth * wipeStart);
432
+ const globalEnd = Math.round(totalWidth * wipeEnd);
433
+ const activeRects = [];
434
+ const clearRects = [];
435
+ let cursor = 0;
436
+ for (const fragment of item.fragments) {
437
+ const width = Math.max(0, fragment.rectangle.width);
438
+ const localStart = Math.max(0, Math.min(width, globalStart - cursor));
439
+ const localEnd = Math.max(0, Math.min(width, globalEnd - cursor));
440
+ cursor += width;
441
+ const guardedActiveLeft = fragment.rectangle.x + localStart + (localStart > 0 ? 3 : 0);
442
+ const guardedActiveRight = fragment.rectangle.x + localEnd - (localEnd < width ? 3 : 0);
443
+ if (guardedActiveRight > guardedActiveLeft) {
444
+ activeRects.push(...underlineFragmentPrimitives(fragment, guardedActiveLeft, guardedActiveRight).map(entry => entry.rectangle));
445
+ }
446
+ if (localStart > 3) {
447
+ clearRects.push(...underlineFragmentPrimitives(fragment, fragment.rectangle.x, fragment.rectangle.x + localStart - 3).map(entry => entry.rectangle));
448
+ }
449
+ if (localEnd + 3 < width) {
450
+ clearRects.push(...underlineFragmentPrimitives(fragment, fragment.rectangle.x + localEnd + 3, fragment.rectangle.x + width).map(entry => entry.rectangle));
451
+ }
452
+ }
453
+ return { activeRects, clearRects };
454
+ };
455
+ if (item.in_ms > 0) {
456
+ let midIn;
457
+ let bestDist = Infinity;
458
+ for (let frame = item.first_frame; frame <= lastAvailable; frame++) {
459
+ const timeMs = frame * 1000 / video.fps;
460
+ if (timeMs >= item.start_ms + item.in_ms)
461
+ break;
462
+ const { wipeStart, wipeEnd } = underlineWipeFractions(item, timeMs);
463
+ if (wipeStart === 0 && wipeEnd > 0 && wipeEnd < 1) {
464
+ const regions = buildWipeRegions(timeMs);
465
+ if (hasMeasurableRects(regions.activeRects, video) && hasMeasurableRects(regions.clearRects, video)) {
466
+ const dist = Math.abs(wipeEnd - 0.5);
467
+ if (dist < bestDist) {
468
+ bestDist = dist;
469
+ midIn = { frame, ...regions };
470
+ }
471
+ }
472
+ }
473
+ }
474
+ if (midIn === undefined) {
475
+ coverage.push(`${item.id}:wipe_in:unobservable_at_${video.fps}fps`);
476
+ gaps.push(`${item.id}:stroke:wipe_in: wipe_in (${item.in_ms} ms) has no observable partial frame at ${video.fps} fps`);
477
+ }
478
+ else {
479
+ coverage.push(`${item.id}:wipe_in:frame_${midIn.frame}`);
480
+ const { frame: wipeFrame, activeRects, clearRects } = midIn;
481
+ const order = enqueue(wipeFrame, (finalFrame, baseFrame, covered, appPrimitives, timestampMs) => {
482
+ const activeMetrics = measureRegion(finalFrame, baseFrame, video, covered, appPrimitives, appIndex, [], activeRects);
483
+ const clearMetrics = measureRegion(finalFrame, baseFrame, video, covered, appPrimitives, appIndex, fullUnderlinePaints, clearRects);
484
+ const passed = activeMetrics.passed && clearMetrics.passed;
485
+ orderedChecks.push({
486
+ order,
487
+ entry: {
488
+ annotation: item.id,
489
+ part: 'stroke',
490
+ boundary: 'wipe_in',
491
+ frame_index: wipeFrame,
492
+ encoded_ms: timestampMs,
493
+ expected_active: 'partial',
494
+ wiped_expected_error: activeMetrics.expected_error,
495
+ wiped_opposite_error: activeMetrics.opposite_error,
496
+ unwiped_expected_error: clearMetrics.expected_error,
497
+ unwiped_opposite_error: clearMetrics.opposite_error,
498
+ contrast: activeMetrics.contrast !== null && clearMetrics.contrast !== null
499
+ ? Math.min(activeMetrics.contrast, clearMetrics.contrast)
500
+ : null,
501
+ passed,
502
+ },
503
+ gap: passed ? undefined : `${item.id}:stroke:wipe_in: frame ${wipeFrame} does not prove partial left-to-right wipe-in progression`,
504
+ });
505
+ });
506
+ }
507
+ }
508
+ if (item.out_ms > 0) {
509
+ let midOut;
510
+ let bestDist = Infinity;
511
+ for (let frame = item.first_frame; frame <= lastAvailable; frame++) {
512
+ const timeMs = frame * 1000 / video.fps;
513
+ if (timeMs <= item.end_ms - item.out_ms)
77
514
  continue;
78
- const offset = frameOffset + (y * 320 + x) * 3;
79
- for (let channel = 0; channel < 3; channel++) {
80
- let expected = originals[offset + channel];
81
- let opposite = expected;
82
- for (const [otherLayer, other] of layers.entries()) {
83
- if (!inside(other.rectangle, px, py))
84
- continue;
85
- const active = index >= other.first_frame && index < other.end_frame;
86
- if (active)
87
- expected = blend(expected, other, rgb[otherLayer][channel]);
88
- if (otherLayer === layer ? !active : active)
89
- opposite = blend(opposite, other, rgb[otherLayer][channel]);
515
+ const { wipeStart, wipeEnd } = underlineWipeFractions(item, timeMs);
516
+ if (wipeEnd === 1 && wipeStart > 0 && wipeStart < 1) {
517
+ const regions = buildWipeRegions(timeMs);
518
+ if (hasMeasurableRects(regions.activeRects, video) && hasMeasurableRects(regions.clearRects, video)) {
519
+ const dist = Math.abs(wipeStart - 0.5);
520
+ if (dist < bestDist) {
521
+ bestDist = dist;
522
+ midOut = { frame, ...regions };
523
+ }
90
524
  }
91
- expectedError += Math.abs(frames[offset + channel] - expected);
92
- oppositeError += Math.abs(frames[offset + channel] - opposite);
93
- contrast += Math.abs(expected - opposite);
94
- count++;
95
525
  }
96
526
  }
97
- const timestamp = Number(metadata.frames[index].best_effort_timestamp_time) * 1000;
98
- const passed = count > 0 && contrast / count >= 4 && expectedError / count <= 12 && expectedError < oppositeError * 0.7;
99
- checks.push({ annotation: item.id, part: item.part, boundary, frame_index: index, encoded_ms: timestamp, expected_active: index >= item.first_frame && index < item.end_frame, expected_error: count ? expectedError / count : null, opposite_error: count ? oppositeError / count : null, contrast: count ? contrast / count : null, passed });
100
- if (!passed)
101
- gaps.push(`${item.id}:${item.part}:${boundary}: frame ${index} does not distinguish the expected highlight state from its opposite`);
527
+ if (midOut === undefined) {
528
+ coverage.push(`${item.id}:wipe_out:unobservable_at_${video.fps}fps`);
529
+ gaps.push(`${item.id}:stroke:wipe_out: wipe_out (${item.out_ms} ms) has no observable partial frame at ${video.fps} fps`);
530
+ }
531
+ else {
532
+ coverage.push(`${item.id}:wipe_out:frame_${midOut.frame}`);
533
+ const { frame: wipeFrame, activeRects, clearRects } = midOut;
534
+ const order = enqueue(wipeFrame, (finalFrame, baseFrame, covered, appPrimitives, timestampMs) => {
535
+ const activeMetrics = measureRegion(finalFrame, baseFrame, video, covered, appPrimitives, appIndex, [], activeRects);
536
+ const clearMetrics = measureRegion(finalFrame, baseFrame, video, covered, appPrimitives, appIndex, fullUnderlinePaints, clearRects);
537
+ const passed = activeMetrics.passed && clearMetrics.passed;
538
+ orderedChecks.push({
539
+ order,
540
+ entry: {
541
+ annotation: item.id,
542
+ part: 'stroke',
543
+ boundary: 'wipe_out',
544
+ frame_index: wipeFrame,
545
+ encoded_ms: timestampMs,
546
+ expected_active: 'partial',
547
+ wiped_expected_error: clearMetrics.expected_error,
548
+ wiped_opposite_error: clearMetrics.opposite_error,
549
+ remaining_expected_error: activeMetrics.expected_error,
550
+ remaining_opposite_error: activeMetrics.opposite_error,
551
+ contrast: activeMetrics.contrast !== null && clearMetrics.contrast !== null
552
+ ? Math.min(activeMetrics.contrast, clearMetrics.contrast)
553
+ : null,
554
+ passed,
555
+ },
556
+ gap: passed ? undefined : `${item.id}:stroke:wipe_out: frame ${wipeFrame} does not prove partial left-to-right wipe-out progression`,
557
+ });
558
+ });
559
+ }
560
+ }
561
+ break;
102
562
  }
103
- const observed = Number(metadata.frames[first].best_effort_timestamp_time) * 1000;
104
- if (!Number.isFinite(observed) || Math.abs(observed - expectedTime) + 1000 / story.output.fps > 100)
105
- gaps.push(`${item.id}:${boundary}: encoded timestamp uncertainty exceeds 100 ms`);
106
563
  }
107
564
  }
108
- for (const item of layers)
109
- if (!checks.some(check => check.annotation === item.id && check.part === item.part && check.expected_active === true && check.passed === true))
110
- gaps.push(`${item.id}:${item.part}: no verified active encoded frame proves appearance`);
111
- const evidence = { version: 1, status: gaps.length ? 'failed' : 'accepted', file: gaps.length ? join(directory, 'failed-composite.mp4') : output, ...provenance, source: 'final encoded MP4 compared with decoded unannotated capture in the same output timebase', target_ms: 100, checks, gaps };
565
+ const indices = [...tasksByFrame.keys()].sort((a, b) => a - b);
566
+ if (indices.length > 0) {
567
+ const select = `select='${balancedSum(indices.map(index => `eq(n,${index})`))}',format=rgb24`;
568
+ const filterFlags = await ffmpegFilterScriptFlags();
569
+ const filterDirectory = await mkdtemp(join(tmpdir(), 'slidevideo-verify-'));
570
+ const bytes = video.width * video.height * 3;
571
+ const finalFrame = Buffer.alloc(bytes);
572
+ const baseFrame = Buffer.alloc(bytes);
573
+ let finalDecoder;
574
+ let baseDecoder;
575
+ try {
576
+ const finalFilterFile = join(filterDirectory, 'final-filter.txt');
577
+ const baseFilterFile = join(filterDirectory, 'base-filter.txt');
578
+ await Promise.all([
579
+ writeFile(finalFilterFile, select),
580
+ writeFile(baseFilterFile, `${baseFilter},${select}`),
581
+ ]);
582
+ const signal = executionSignal();
583
+ const ffmpegBin = executable('ffmpeg');
584
+ finalDecoder = spawn(ffmpegBin, ['-v', 'error', '-xerror', '-i', file, filterFlags.video, finalFilterFile, '-fps_mode', 'passthrough', '-f', 'rawvideo', '-'], { stdio: ['ignore', 'pipe', 'pipe'], signal });
585
+ baseDecoder = spawn(ffmpegBin, ['-v', 'error', '-xerror', '-i', base, filterFlags.video, baseFilterFile, '-fps_mode', 'passthrough', '-f', 'rawvideo', '-'], { stdio: ['ignore', 'pipe', 'pipe'], signal });
586
+ const finalDone = decoderCompletion(finalDecoder, 'Final composite verification decode');
587
+ const baseDone = decoderCompletion(baseDecoder, 'Base capture verification decode');
588
+ const finalReader = new RawFrameReader(finalDecoder.stdout);
589
+ const baseReader = new RawFrameReader(baseDecoder.stdout);
590
+ for (const index of indices) {
591
+ const [gotFinal, gotBase] = await Promise.all([
592
+ finalReader.readInto(finalFrame),
593
+ baseReader.readInto(baseFrame),
594
+ ]);
595
+ requireCondition(gotFinal && gotBase, 'ANNOTATION_EVIDENCE', 'Final and base frame decoding did not return the requested encoded frame samples', 6);
596
+ const outputTime = index * 1000 / video.fps;
597
+ const timestampMs = Number(metadata.frames[index].best_effort_timestamp_time) * 1000;
598
+ const covered = overlayBounds(index);
599
+ const appPrimitives = applications.map(app => index >= app.first_frame && index < app.end_frame
600
+ ? effectPrimitives([app], outputTime).map(toRgbPrimitive)
601
+ : []);
602
+ for (const task of tasksByFrame.get(index) ?? []) {
603
+ task.run(finalFrame, baseFrame, covered, appPrimitives, timestampMs);
604
+ }
605
+ }
606
+ const [finalEnded, baseEnded] = await Promise.all([
607
+ finalReader.expectEnd(),
608
+ baseReader.expectEnd(),
609
+ ]);
610
+ requireCondition(finalEnded && baseEnded, 'ANNOTATION_EVIDENCE', 'Final and base frame decoding returned unexpected trailing frame bytes', 6);
611
+ await Promise.all([finalDone, baseDone]);
612
+ }
613
+ finally {
614
+ if (finalDecoder && finalDecoder.exitCode === null && finalDecoder.signalCode === null)
615
+ finalDecoder.kill();
616
+ if (baseDecoder && baseDecoder.exitCode === null && baseDecoder.signalCode === null)
617
+ baseDecoder.kill();
618
+ await rm(filterDirectory, { recursive: true, force: true });
619
+ }
620
+ }
621
+ orderedChecks.sort((a, b) => a.order - b.order);
622
+ const checks = orderedChecks.map(item => item.entry);
623
+ for (const item of orderedChecks) {
624
+ if (item.gap)
625
+ gaps.push(item.gap);
626
+ }
627
+ for (const { id, part } of requiredActiveParts) {
628
+ if (!checks.some(check => check.annotation === id && check.part === part && check.expected_active === true && check.passed === true)) {
629
+ gaps.push(`${id}:${part}: no verified active encoded frame proves appearance`);
630
+ }
631
+ }
632
+ const evidence = {
633
+ version: 1,
634
+ status: gaps.length ? 'failed' : 'accepted',
635
+ file: gaps.length ? join(directory, 'failed-composite.mp4') : output,
636
+ ...provenance,
637
+ source: 'final encoded MP4 compared with decoded unannotated capture in the same output timebase',
638
+ target_ms: 100,
639
+ coverage,
640
+ checks,
641
+ gaps,
642
+ };
112
643
  await saveJson(evidenceFile, evidence);
113
644
  requireCondition(evidence.status === 'accepted', 'ANNOTATION_TIMING', `Final composite annotation timing failed. See ${evidenceFile}`, 6);
114
645
  return evidence;