framesheet 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +247 -2
- package/dist/analysis.d.ts +84 -0
- package/dist/analysis.d.ts.map +1 -0
- package/dist/analysis.js +335 -0
- package/dist/analysis.js.map +1 -0
- package/dist/checks.d.ts +44 -0
- package/dist/checks.d.ts.map +1 -0
- package/dist/checks.js +200 -0
- package/dist/checks.js.map +1 -0
- package/dist/compose.d.ts +130 -0
- package/dist/compose.d.ts.map +1 -0
- package/dist/compose.js +266 -0
- package/dist/compose.js.map +1 -0
- package/dist/driver.d.ts +56 -0
- package/dist/driver.d.ts.map +1 -0
- package/dist/driver.js +94 -0
- package/dist/driver.js.map +1 -0
- package/dist/generated/assets.d.ts +13 -0
- package/dist/generated/assets.d.ts.map +1 -0
- package/dist/generated/assets.js +15 -0
- package/dist/generated/assets.js.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +17 -0
- package/dist/index.js.map +1 -0
- package/dist/inspect.d.ts +163 -0
- package/dist/inspect.d.ts.map +1 -0
- package/dist/inspect.js +593 -0
- package/dist/inspect.js.map +1 -0
- package/dist/marks.d.ts +49 -0
- package/dist/marks.d.ts.map +1 -0
- package/dist/marks.js +460 -0
- package/dist/marks.js.map +1 -0
- package/dist/marks.schema.json +307 -0
- package/dist/media.d.ts +22 -0
- package/dist/media.d.ts.map +1 -0
- package/dist/media.js +306 -0
- package/dist/media.js.map +1 -0
- package/dist/models.d.ts +208 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.js +9 -0
- package/dist/models.js.map +1 -0
- package/dist/pixels.d.ts +52 -0
- package/dist/pixels.d.ts.map +1 -0
- package/dist/pixels.js +275 -0
- package/dist/pixels.js.map +1 -0
- package/dist/pyfmt.d.ts +16 -0
- package/dist/pyfmt.d.ts.map +1 -0
- package/dist/pyfmt.js +54 -0
- package/dist/pyfmt.js.map +1 -0
- package/dist/report.schema.json +1326 -0
- package/dist/sources.d.ts +43 -0
- package/dist/sources.d.ts.map +1 -0
- package/dist/sources.js +164 -0
- package/dist/sources.js.map +1 -0
- package/dist/test.d.ts +46 -0
- package/dist/test.d.ts.map +1 -0
- package/dist/test.js +58 -0
- package/dist/test.js.map +1 -0
- package/dist/timing.d.ts +30 -0
- package/dist/timing.d.ts.map +1 -0
- package/dist/timing.js +128 -0
- package/dist/timing.js.map +1 -0
- package/dist/video.d.ts +65 -0
- package/dist/video.d.ts.map +1 -0
- package/dist/video.js +440 -0
- package/dist/video.js.map +1 -0
- package/package.json +79 -4
- package/src/analysis.ts +416 -0
- package/src/checks.ts +261 -0
- package/src/compose.ts +337 -0
- package/src/driver.ts +115 -0
- package/src/generated/assets.ts +20 -0
- package/src/index.ts +54 -0
- package/src/inspect.ts +722 -0
- package/src/marks.ts +481 -0
- package/src/media.ts +296 -0
- package/src/models.ts +225 -0
- package/src/pixels.ts +284 -0
- package/src/pyfmt.ts +55 -0
- package/src/sources.ts +175 -0
- package/src/test.ts +100 -0
- package/src/timing.ts +133 -0
- package/src/video.ts +513 -0
package/src/timing.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/** Duration detection and sample-time planning (port of timing.py). */
|
|
2
|
+
|
|
3
|
+
import type { AnimationTiming, DurationInfo } from "./models.js";
|
|
4
|
+
import { g, pyRound } from "./pyfmt.js";
|
|
5
|
+
|
|
6
|
+
export const FALLBACK_SECONDS = 3.0;
|
|
7
|
+
export const MAX_SECONDS = 60.0;
|
|
8
|
+
/** Use the LCM of loop periods only if it is at most this many times the longest period. */
|
|
9
|
+
export const LCM_FACTOR = 4;
|
|
10
|
+
/** One 60 fps frame: the last tile and the loop probe sit this far before the cycle end. */
|
|
11
|
+
export const EPSILON = 1 / 60;
|
|
12
|
+
|
|
13
|
+
/** Normalise raw runtime output (`window.__framesheet.timings()`) to full records. */
|
|
14
|
+
export function parseTimings(raw: unknown[]): AnimationTiming[] {
|
|
15
|
+
return raw.map((item) => {
|
|
16
|
+
const r = item as Record<string, unknown>;
|
|
17
|
+
return {
|
|
18
|
+
kind: r.kind as AnimationTiming["kind"],
|
|
19
|
+
target: (r.target as string | null | undefined) ?? null,
|
|
20
|
+
name: (r.name as string | null | undefined) ?? null,
|
|
21
|
+
start: Number(r.start),
|
|
22
|
+
duration: Number(r.duration),
|
|
23
|
+
iterations: r.iterations == null ? null : Number(r.iterations),
|
|
24
|
+
direction: (r.direction as string | undefined) ?? "normal",
|
|
25
|
+
period: Number(r.period),
|
|
26
|
+
end: r.end == null ? null : Number(r.end),
|
|
27
|
+
transform_box: (r.transform_box as string | null | undefined) ?? null,
|
|
28
|
+
};
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function gcd(a: number, b: number): number {
|
|
33
|
+
while (b) [a, b] = [b, a % b];
|
|
34
|
+
return a;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function lcm(periods: number[]): number {
|
|
38
|
+
const ticks = periods.map((p) => Math.max(1, pyRound(p * 100))); // 10 ms resolution
|
|
39
|
+
return ticks.reduce((a, b) => (a / gcd(a, b)) * b) / 100;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Pick the time span to sample.
|
|
44
|
+
*
|
|
45
|
+
* - Infinite animations contribute their loop period (`duration`, doubled for
|
|
46
|
+
* `alternate`). Several periods are combined with their least common multiple if that
|
|
47
|
+
* stays reasonable, otherwise the longest period wins.
|
|
48
|
+
* - A positive start (`begin`/`delay`) of a looping animation is added, so the warm-up
|
|
49
|
+
* before the first iteration is visible.
|
|
50
|
+
* - Finite animations contribute their end time (delay + duration x iterations).
|
|
51
|
+
*/
|
|
52
|
+
export function detectDuration(animations: AnimationTiming[], override?: number | null): DurationInfo {
|
|
53
|
+
const infinite = animations.filter((a) => a.iterations === null);
|
|
54
|
+
const finite = animations.filter((a) => a.iterations !== null && a.end !== null);
|
|
55
|
+
const looping = infinite.length > 0;
|
|
56
|
+
if (override != null) {
|
|
57
|
+
return {
|
|
58
|
+
seconds: override,
|
|
59
|
+
method: "override",
|
|
60
|
+
looping,
|
|
61
|
+
detail: `--duration ${g(override)}s`,
|
|
62
|
+
animations,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
if (animations.length === 0) {
|
|
66
|
+
return {
|
|
67
|
+
seconds: FALLBACK_SECONDS,
|
|
68
|
+
method: "fallback",
|
|
69
|
+
looping: false,
|
|
70
|
+
detail:
|
|
71
|
+
`no SMIL/CSS/Web Animations found; sampled the ${g(FALLBACK_SECONDS)}s ` +
|
|
72
|
+
"fallback (pass --duration for JS-driven animation)",
|
|
73
|
+
animations: [],
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
const parts: string[] = [];
|
|
77
|
+
let seconds = 0;
|
|
78
|
+
if (infinite.length) {
|
|
79
|
+
const periods = [...new Set(infinite.map((a) => pyRound(a.period, 3)))].sort((a, b) => a - b);
|
|
80
|
+
let cycle = lcm(periods);
|
|
81
|
+
const longest = periods[periods.length - 1];
|
|
82
|
+
const list = periods.map((p) => `${g(p)}s`).join(", ");
|
|
83
|
+
if (periods.length === 1) {
|
|
84
|
+
parts.push(`loop period ${g(periods[0])}s`);
|
|
85
|
+
} else if (cycle <= LCM_FACTOR * longest && cycle <= MAX_SECONDS) {
|
|
86
|
+
parts.push(`LCM of loop periods ${list}`);
|
|
87
|
+
} else {
|
|
88
|
+
cycle = longest;
|
|
89
|
+
parts.push(`longest of loop periods ${list} (no short common multiple)`);
|
|
90
|
+
}
|
|
91
|
+
seconds = cycle;
|
|
92
|
+
const warmup = Math.max(Math.max(...infinite.map((a) => a.start)), 0);
|
|
93
|
+
if (warmup > 0) {
|
|
94
|
+
seconds = Math.max(seconds, warmup + cycle);
|
|
95
|
+
parts.push(`+ ${g(warmup)}s positive begin/delay before the first loop`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (finite.length) {
|
|
99
|
+
const lastEnd = Math.max(...finite.map((a) => a.end ?? 0));
|
|
100
|
+
if (lastEnd > seconds) {
|
|
101
|
+
seconds = lastEnd;
|
|
102
|
+
parts.push(`finite animations end at ${g(lastEnd)}s`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const kinds = [...new Set(animations.map((a) => a.kind))].sort();
|
|
106
|
+
let detail = `${parts.join("; ")} (${animations.length} animation(s): ${kinds.join(", ")})`;
|
|
107
|
+
if (seconds > MAX_SECONDS) {
|
|
108
|
+
detail += `; capped at ${g(MAX_SECONDS)}s`;
|
|
109
|
+
seconds = MAX_SECONDS;
|
|
110
|
+
}
|
|
111
|
+
if (seconds <= 0) {
|
|
112
|
+
seconds = FALLBACK_SECONDS;
|
|
113
|
+
detail += `; zero-length, using ${g(FALLBACK_SECONDS)}s`;
|
|
114
|
+
}
|
|
115
|
+
return { seconds: pyRound(seconds, 3), method: "detected", looping, detail, animations };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The probe offset for loop checks: one 60 fps frame, or 1% of very short cycles. */
|
|
119
|
+
export function epsilon(duration: number): number {
|
|
120
|
+
return Math.min(EPSILON, duration / 100);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Evenly spaced times over `[0, duration]`. The last sample is one 60 fps frame *before*
|
|
125
|
+
* the end: at exactly `t=end` an infinite animation has already wrapped to its first
|
|
126
|
+
* frame, which would make every loop look seamless.
|
|
127
|
+
*/
|
|
128
|
+
export function sampleTimes(duration: number, frames: number): number[] {
|
|
129
|
+
if (frames < 2) return [0];
|
|
130
|
+
const times = Array.from({ length: frames }, (_, i) => pyRound((duration * i) / (frames - 1), 4));
|
|
131
|
+
times[times.length - 1] = pyRound(duration - epsilon(duration), 4);
|
|
132
|
+
return times;
|
|
133
|
+
}
|
package/src/video.ts
ADDED
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Video and animated-image inputs (port of video.py): exact seeks in Chromium, dense
|
|
3
|
+
* samples, pacing checks (static stretches, black/blank frames, cuts, mark overlaps), and
|
|
4
|
+
* the sheet with marks and a timeline.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { basename, join, resolve as resolvePath } from "node:path";
|
|
9
|
+
import type { Browser, Route } from "playwright-core";
|
|
10
|
+
import { contactSheet, heatmap, type Renderer } from "./compose.js";
|
|
11
|
+
import { VIDEO_JS } from "./generated/assets.js";
|
|
12
|
+
import {
|
|
13
|
+
activeLabels,
|
|
14
|
+
bandText,
|
|
15
|
+
hasBand,
|
|
16
|
+
type Issue,
|
|
17
|
+
tileOps,
|
|
18
|
+
tileWindows,
|
|
19
|
+
timelineOps,
|
|
20
|
+
} from "./marks.js";
|
|
21
|
+
import { isAnimatedImage, MIME_TYPES, probe as probeMedia, type Probe } from "./media.js";
|
|
22
|
+
import type {
|
|
23
|
+
ActivitySample,
|
|
24
|
+
DurationInfo,
|
|
25
|
+
Finding,
|
|
26
|
+
FrameMetrics,
|
|
27
|
+
ImageBuffers,
|
|
28
|
+
ImagePaths,
|
|
29
|
+
Marks,
|
|
30
|
+
Rect,
|
|
31
|
+
Report,
|
|
32
|
+
VideoInfo,
|
|
33
|
+
VideoTile,
|
|
34
|
+
} from "./models.js";
|
|
35
|
+
import { asRect } from "./models.js";
|
|
36
|
+
import { decode, diffStats, type Frame, frameStats, MotionAccumulator, sharpness, toCss } from "./pixels.js";
|
|
37
|
+
import { fixed, g, pct, pyRound } from "./pyfmt.js";
|
|
38
|
+
import { DEFAULT_HTML_SIZE, type Source, VIDEO_ORIGIN, VIDEO_PAGE } from "./sources.js";
|
|
39
|
+
|
|
40
|
+
/** A sample step changing fewer than 0.05% of pixels counts as "no visible change". */
|
|
41
|
+
export const STATIC_RATIO = 0.0005;
|
|
42
|
+
/** A step changing at least 40% of pixels ... */
|
|
43
|
+
export const CUT_RATIO = 0.4;
|
|
44
|
+
/** ... while both neighbouring steps change at most a quarter of that is an abrupt cut. */
|
|
45
|
+
export const CUT_NEIGHBOUR = 0.25;
|
|
46
|
+
/** Dense samples are at most this far apart (seconds), up to MAX_SAMPLES. */
|
|
47
|
+
export const SAMPLE_STEP = 0.25;
|
|
48
|
+
export const MAX_SAMPLES = 240;
|
|
49
|
+
export const MAX_TILES = 100;
|
|
50
|
+
const MAX_LISTED = 8;
|
|
51
|
+
export const DEFAULT_STATIC_STRETCH = 2.0;
|
|
52
|
+
|
|
53
|
+
export type TimesSpec = number[] | "marks";
|
|
54
|
+
|
|
55
|
+
export interface VideoOptions {
|
|
56
|
+
frames?: number;
|
|
57
|
+
every?: number;
|
|
58
|
+
times?: TimesSpec;
|
|
59
|
+
start?: number;
|
|
60
|
+
end?: number;
|
|
61
|
+
marks?: Marks | null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Range and tile times: `[start, end, times, mode]`. */
|
|
65
|
+
export function planTimes(total: number, o: VideoOptions = {}): [number, number, number[], string] {
|
|
66
|
+
const a = o.start ?? 0;
|
|
67
|
+
let b = o.end ?? total;
|
|
68
|
+
if (a < 0 || b <= a || b > total + 1e-6) {
|
|
69
|
+
throw new RangeError(`Invalid range ${g(a)}-${g(b)}s (the media is ${g(total)}s long)`);
|
|
70
|
+
}
|
|
71
|
+
b = Math.min(b, total);
|
|
72
|
+
let ts: number[];
|
|
73
|
+
let mode: string;
|
|
74
|
+
if (o.times === "marks") {
|
|
75
|
+
const marks = o.marks;
|
|
76
|
+
if (!marks) throw new RangeError("times='marks' needs marks");
|
|
77
|
+
ts = [
|
|
78
|
+
...marks.points.map((p) => p.t),
|
|
79
|
+
...marks.regions.map((r) => (r.start + r.end) / 2),
|
|
80
|
+
...marks.spans.map((s) => (s.start + s.end) / 2),
|
|
81
|
+
].filter((t) => a <= t && t <= b);
|
|
82
|
+
if (!ts.length) throw new RangeError("No mark falls inside the inspected range");
|
|
83
|
+
mode = "times from marks";
|
|
84
|
+
} else if (o.times !== undefined) {
|
|
85
|
+
ts = o.times.map(Number);
|
|
86
|
+
if (!ts.length) throw new RangeError("times must not be empty");
|
|
87
|
+
const bad = ts.filter((t) => !(a <= t && t <= b));
|
|
88
|
+
if (bad.length) throw new RangeError(`Times outside the range ${g(a)}-${g(b)}s: ${bad.map(g).join(", ")}`);
|
|
89
|
+
mode = "--times";
|
|
90
|
+
} else if (o.every !== undefined) {
|
|
91
|
+
const every = o.every;
|
|
92
|
+
if (!(every > 0)) throw new RangeError("every must be positive");
|
|
93
|
+
const n = Math.floor((b - a) / every + 1e-9) + 1;
|
|
94
|
+
if (n > MAX_TILES) throw new RangeError(`every=${g(every)}s gives ${n} tiles (max ${MAX_TILES})`);
|
|
95
|
+
ts = Array.from({ length: n }, (_, k) => a + k * every);
|
|
96
|
+
if (b - ts[ts.length - 1] > 1e-6) ts.push(b);
|
|
97
|
+
mode = `every ${g(every)}s`;
|
|
98
|
+
} else {
|
|
99
|
+
const frames = o.frames ?? 12;
|
|
100
|
+
if (!(frames >= 2 && frames <= MAX_TILES)) throw new RangeError("frames must be between 2 and 100");
|
|
101
|
+
ts = Array.from({ length: frames }, (_, i) => a + ((b - a) * i) / (frames - 1));
|
|
102
|
+
ts[ts.length - 1] = b;
|
|
103
|
+
mode = "evenly spaced";
|
|
104
|
+
}
|
|
105
|
+
const out = [...new Set(ts.map((t) => pyRound(t, 4)))].sort((x, y) => x - y);
|
|
106
|
+
if (out.length > MAX_TILES) throw new RangeError(`${out.length} tiles (max ${MAX_TILES})`);
|
|
107
|
+
return [a, b, out, mode];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Evenly spaced pacing samples over `[start, end]` (both ends included). */
|
|
111
|
+
export function denseTimes(start: number, end: number, heatFrames: number): number[] {
|
|
112
|
+
if (heatFrames <= 0) return [];
|
|
113
|
+
const count = Math.min(MAX_SAMPLES, Math.max(heatFrames, Math.ceil((end - start) / SAMPLE_STEP)));
|
|
114
|
+
return Array.from({ length: count + 1 }, (_, k) => pyRound(start + ((end - start) * k) / count, 4));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Maximal runs of sample steps without visible change lasting > `threshold` s. */
|
|
118
|
+
export function staticStretches(samples: ActivitySample[], threshold: number): [number, number][] {
|
|
119
|
+
const out: [number, number][] = [];
|
|
120
|
+
let runStart: number | null = null;
|
|
121
|
+
for (let k = 1; k <= samples.length; k++) {
|
|
122
|
+
const still = k < samples.length && samples[k].changed_ratio < STATIC_RATIO;
|
|
123
|
+
if (still && runStart === null) runStart = k - 1;
|
|
124
|
+
else if (!still && runStart !== null) {
|
|
125
|
+
const a = samples[runStart].t;
|
|
126
|
+
const b = samples[k - 1].t;
|
|
127
|
+
if (b - a > threshold) out.push([a, b]);
|
|
128
|
+
runStart = null;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Sample times where one step changes >= CUT_RATIO and its neighbours little. */
|
|
135
|
+
export function abruptCuts(samples: ActivitySample[]): number[] {
|
|
136
|
+
const out: number[] = [];
|
|
137
|
+
const n = samples.length;
|
|
138
|
+
for (let k = 1; k < n; k++) {
|
|
139
|
+
const r = samples[k].changed_ratio;
|
|
140
|
+
const prev = k >= 2 ? samples[k - 1].changed_ratio : 0;
|
|
141
|
+
const next = k + 1 < n ? samples[k + 1].changed_ratio : 0;
|
|
142
|
+
if (r >= CUT_RATIO && prev <= r * CUT_NEIGHBOUR && next <= r * CUT_NEIGHBOUR) out.push(samples[k].t);
|
|
143
|
+
}
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function runs(times: number[], flags: Map<number, boolean>): [number, number][] {
|
|
148
|
+
const out: [number, number][] = [];
|
|
149
|
+
let current: number[] = [];
|
|
150
|
+
for (const t of times) {
|
|
151
|
+
if (flags.get(t)) current.push(t);
|
|
152
|
+
else if (current.length) {
|
|
153
|
+
out.push([current[0], current[current.length - 1]]);
|
|
154
|
+
current = [];
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (current.length) out.push([current[0], current[current.length - 1]]);
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function listed(times: number[]): string {
|
|
162
|
+
const text = times
|
|
163
|
+
.slice(0, MAX_LISTED)
|
|
164
|
+
.map((t) => `${fixed(t, 2)}s`)
|
|
165
|
+
.join(", ");
|
|
166
|
+
return text + (times.length > MAX_LISTED ? ` (+${times.length - MAX_LISTED} more)` : "");
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const render = (severity: Finding["severity"], code: string, message: string, times: number[] | null): Finding => ({
|
|
170
|
+
severity,
|
|
171
|
+
code,
|
|
172
|
+
message,
|
|
173
|
+
check: "render",
|
|
174
|
+
element: null,
|
|
175
|
+
times,
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
/** Span boxes (captions) covering `target` region boxes while both are active. */
|
|
179
|
+
export function markOverlaps(marks: Marks, start: number, end: number): Finding[] {
|
|
180
|
+
const out: Finding[] = [];
|
|
181
|
+
const nrm = (x: number, y: number): [number, number] => (marks.frame ? [x / marks.frame.width, y / marks.frame.height] : [x, y]);
|
|
182
|
+
for (const s of marks.spans) {
|
|
183
|
+
for (const r of marks.regions) {
|
|
184
|
+
if (s.x === null || r.x === null || r.kind !== "target") continue;
|
|
185
|
+
const a = Math.max(s.start, r.start, start);
|
|
186
|
+
const b = Math.min(s.end, r.end, end);
|
|
187
|
+
if (a > b) continue;
|
|
188
|
+
const [sx, sy] = nrm(s.x, s.y!);
|
|
189
|
+
const [sx2, sy2] = nrm(s.x + s.w!, s.y! + s.h!);
|
|
190
|
+
const [rx, ry] = nrm(r.x, r.y!);
|
|
191
|
+
const [rx2, ry2] = nrm(r.x + r.w!, r.y! + r.h!);
|
|
192
|
+
const iw = Math.min(sx2, rx2) - Math.max(sx, rx);
|
|
193
|
+
const ih = Math.min(sy2, ry2) - Math.max(sy, ry);
|
|
194
|
+
if (iw <= 0 || ih <= 0) continue;
|
|
195
|
+
const share = (iw * ih) / ((rx2 - rx) * (ry2 - ry));
|
|
196
|
+
out.push(
|
|
197
|
+
render(
|
|
198
|
+
"warning",
|
|
199
|
+
"video-mark-overlap",
|
|
200
|
+
`Span "${s.label}" covers target "${r.label || "target"}" for t=${fixed(a, 2)}-${fixed(b, 2)}s (${pct(share, 0)} of the target box).`,
|
|
201
|
+
[pyRound(a, 4), pyRound(b, 4)],
|
|
202
|
+
),
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return out;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Findings plus timeline issues. */
|
|
210
|
+
export function videoFindings(
|
|
211
|
+
samples: ActivitySample[],
|
|
212
|
+
stats: Map<number, [boolean, boolean]>,
|
|
213
|
+
threshold: number,
|
|
214
|
+
marks: Marks | null,
|
|
215
|
+
start: number,
|
|
216
|
+
end: number,
|
|
217
|
+
): [Finding[], Issue[]] {
|
|
218
|
+
const findings: Finding[] = [];
|
|
219
|
+
let issues: Issue[] = [];
|
|
220
|
+
for (const [a, b] of staticStretches(samples, threshold)) {
|
|
221
|
+
findings.push(
|
|
222
|
+
render(
|
|
223
|
+
"warning",
|
|
224
|
+
"video-static-stretch",
|
|
225
|
+
`No visible change for ${fixed(b - a, 2)}s (t=${fixed(a, 2)}-${fixed(b, 2)}s; under ${pct(STATIC_RATIO, 2)} of pixels per sample): dead time?`,
|
|
226
|
+
[a, b],
|
|
227
|
+
),
|
|
228
|
+
);
|
|
229
|
+
issues.push({ kind: "static", start: a, end: b });
|
|
230
|
+
}
|
|
231
|
+
const times = samples.map((s) => s.t);
|
|
232
|
+
const kinds: ["black" | "blank", number, string][] = [
|
|
233
|
+
["black", 0, "black"],
|
|
234
|
+
["blank", 1, "one flat colour (blank)"],
|
|
235
|
+
];
|
|
236
|
+
for (const [kind, index, what] of kinds) {
|
|
237
|
+
const flags = new Map(times.map((t) => [t, stats.get(t)![index]]));
|
|
238
|
+
const hits = times.filter((t) => flags.get(t));
|
|
239
|
+
if (!hits.length) continue;
|
|
240
|
+
findings.push(render("warning", `video-${kind}-frames`, `${hits.length} sampled frame(s) are ${what}: t=${listed(hits)}.`, hits));
|
|
241
|
+
issues.push(...runs(times, flags).map(([a, b]) => ({ kind, start: a, end: b })));
|
|
242
|
+
}
|
|
243
|
+
const cuts = abruptCuts(samples);
|
|
244
|
+
if (cuts.length) {
|
|
245
|
+
findings.push(
|
|
246
|
+
render(
|
|
247
|
+
"info",
|
|
248
|
+
"video-abrupt-cut",
|
|
249
|
+
`Abrupt change (>= ${pct(CUT_RATIO, 0)} of pixels in one sample step, quiet neighbours) at t=${listed(cuts)}: a hard cut or a jump.`,
|
|
250
|
+
cuts,
|
|
251
|
+
),
|
|
252
|
+
);
|
|
253
|
+
issues.push(...cuts.map((t) => ({ kind: "cut" as const, start: t, end: t })));
|
|
254
|
+
}
|
|
255
|
+
if (marks) findings.push(...markOverlaps(marks, start, end));
|
|
256
|
+
// Python: sort by (start, kind), stable.
|
|
257
|
+
issues = issues
|
|
258
|
+
.map((it, i) => [it, i] as const)
|
|
259
|
+
.sort((x, y) => x[0].start - y[0].start || (x[0].kind < y[0].kind ? -1 : x[0].kind > y[0].kind ? 1 : 0) || x[1] - y[1])
|
|
260
|
+
.map(([it]) => it);
|
|
261
|
+
return [findings, issues];
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export function decodeHint(label: string, probe: Probe, error: string): string {
|
|
265
|
+
return (
|
|
266
|
+
`Chromium could not decode ${label} (${probe.container}/${probe.codec || "unknown codec"}): ${error}. ` +
|
|
267
|
+
"Playwright's Chromium may lack proprietary codecs (H.264/HEVC): re-encode to " +
|
|
268
|
+
"WebM/VP9 (ffmpeg -i in.mp4 -c:v libvpx-vp9 -crf 32 -b:v 0 out.webm) or use an " +
|
|
269
|
+
"installed Chrome (launchOptions: { channel: 'chrome' })."
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function tileLabel(t: number, i: number, count: number, start: number, end: number): string {
|
|
274
|
+
const label = `t=${fixed(t, 2)}s`;
|
|
275
|
+
if (i === 0 && t === start) return `${label} start`;
|
|
276
|
+
if (i === count - 1 && t === end) return `${label} end`;
|
|
277
|
+
return label;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Route handler serving `body` with HTTP range support (media elements seek by range). */
|
|
281
|
+
function serve(body: Buffer, contentType: string) {
|
|
282
|
+
return (route: Route) => {
|
|
283
|
+
const total = body.length;
|
|
284
|
+
const headers: Record<string, string> = { "Content-Type": contentType, "Accept-Ranges": "bytes" };
|
|
285
|
+
const m = /^bytes=(\d*)-(\d*)$/.exec(route.request().headers().range ?? "");
|
|
286
|
+
if (!m || total === 0) return route.fulfill({ status: 200, headers, body });
|
|
287
|
+
const first = Number(m[1] || 0);
|
|
288
|
+
const last = Math.min(m[2] ? Number(m[2]) : total - 1, total - 1);
|
|
289
|
+
if (first >= total || last < first) return route.fulfill({ status: 416, headers: { "Content-Range": `bytes */${total}` } });
|
|
290
|
+
headers["Content-Range"] = `bytes ${first}-${last}/${total}`;
|
|
291
|
+
return route.fulfill({ status: 206, headers, body: body.subarray(first, last + 1) });
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export interface VideoPipelineOptions extends VideoOptions {
|
|
296
|
+
duration?: number;
|
|
297
|
+
size?: [number, number];
|
|
298
|
+
scale?: number;
|
|
299
|
+
at?: number;
|
|
300
|
+
out?: string;
|
|
301
|
+
tile?: number;
|
|
302
|
+
columns?: number;
|
|
303
|
+
keepFrames?: boolean;
|
|
304
|
+
heatFrames?: number;
|
|
305
|
+
timeout?: number;
|
|
306
|
+
staticStretch?: number;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
type Built = { report: Report; images: ImageBuffers; paths: ImagePaths | null };
|
|
310
|
+
|
|
311
|
+
export async function inspectVideo(
|
|
312
|
+
src: Source,
|
|
313
|
+
browser: Browser,
|
|
314
|
+
renderer: Renderer,
|
|
315
|
+
o: VideoPipelineOptions,
|
|
316
|
+
autoScale: (size: [number, number]) => number,
|
|
317
|
+
): Promise<Built> {
|
|
318
|
+
const data = src.media!;
|
|
319
|
+
const probe = probeMedia(data, src.container ?? null);
|
|
320
|
+
let viewport: [number, number] = o.size ?? (probe.width && probe.height ? [probe.width, probe.height] : DEFAULT_HTML_SIZE);
|
|
321
|
+
const dsf = o.scale ?? (o.size ? 1 : autoScale(viewport));
|
|
322
|
+
const mime = MIME_TYPES[probe.container];
|
|
323
|
+
const decoder = isAnimatedImage(probe) ? "image-decoder" : "video";
|
|
324
|
+
const marks = o.marks ?? null;
|
|
325
|
+
const threshold = o.staticStretch ?? DEFAULT_STATIC_STRETCH;
|
|
326
|
+
const heatFrames = o.heatFrames ?? 48;
|
|
327
|
+
const context = await browser.newContext({
|
|
328
|
+
viewport: { width: viewport[0], height: viewport[1] },
|
|
329
|
+
deviceScaleFactor: dsf,
|
|
330
|
+
colorScheme: "light",
|
|
331
|
+
reducedMotion: "no-preference",
|
|
332
|
+
locale: "en-US",
|
|
333
|
+
timezoneId: "UTC",
|
|
334
|
+
});
|
|
335
|
+
try {
|
|
336
|
+
await context.route(`${VIDEO_ORIGIN}/video.html`, serve(Buffer.from(VIDEO_PAGE), "text/html; charset=utf-8"));
|
|
337
|
+
await context.route(`${VIDEO_ORIGIN}/media`, serve(data, mime));
|
|
338
|
+
const page = await context.newPage();
|
|
339
|
+
page.setDefaultTimeout(o.timeout ?? 30_000);
|
|
340
|
+
const consoleErrors: string[] = [];
|
|
341
|
+
page.on("pageerror", (err) => consoleErrors.push(`pageerror: ${err.message}`));
|
|
342
|
+
page.on("console", (msg) => {
|
|
343
|
+
if (msg.type() === "error") consoleErrors.push(`console.${msg.type()}: ${msg.text()}`);
|
|
344
|
+
});
|
|
345
|
+
await page.goto(src.url, { waitUntil: "load" });
|
|
346
|
+
await page.evaluate(VIDEO_JS);
|
|
347
|
+
type Loaded = { width: number; height: number; duration: number | null; fps: number | null; frame_count: number | null };
|
|
348
|
+
let loaded: Loaded;
|
|
349
|
+
try {
|
|
350
|
+
loaded = await page.evaluate(
|
|
351
|
+
([s, d, t]) => (window as unknown as { __framesheetVideo: { load(s: string, d: string, t: string): Promise<Loaded> } }).__framesheetVideo.load(s, d, t),
|
|
352
|
+
["/media", decoder, mime] as [string, string, string],
|
|
353
|
+
);
|
|
354
|
+
} catch (err) {
|
|
355
|
+
const first = String((err as Error).message ?? err).split("\n")[0];
|
|
356
|
+
throw new Error(decodeHint(src.label, probe, first));
|
|
357
|
+
}
|
|
358
|
+
const width = Number(loaded.width);
|
|
359
|
+
const height = Number(loaded.height);
|
|
360
|
+
if (!o.size && (width !== viewport[0] || height !== viewport[1])) {
|
|
361
|
+
viewport = [width, height];
|
|
362
|
+
await page.setViewportSize({ width, height });
|
|
363
|
+
}
|
|
364
|
+
const mediaDuration = loaded.duration === null ? null : pyRound(Number(loaded.duration), 4);
|
|
365
|
+
const total = o.duration || mediaDuration;
|
|
366
|
+
if (!total) throw new RangeError(`Unknown media duration of ${src.label}: pass duration`);
|
|
367
|
+
const [a, b, tileTimes, mode] = planTimes(total, o);
|
|
368
|
+
const fullAt = o.at === undefined ? a : pyRound(o.at, 4);
|
|
369
|
+
if (!(fullAt >= 0 && fullAt <= total)) throw new RangeError(`at ${g(fullAt)}s is outside the media (0-${g(total)}s)`);
|
|
370
|
+
const content = asRect(await page.evaluate("window.__framesheetVideo.contentBox()") as number[]);
|
|
371
|
+
const wanted = new Set([...tileTimes, fullAt]);
|
|
372
|
+
const everything = [...new Set([...wanted, ...denseTimes(a, b, heatFrames)])].sort((x, y) => x - y);
|
|
373
|
+
const kept = new Map<number, { png: Buffer; frame: Frame }>();
|
|
374
|
+
const mediaTimes = new Map<number, number | null>();
|
|
375
|
+
const samples: ActivitySample[] = [];
|
|
376
|
+
const stats = new Map<number, [boolean, boolean]>();
|
|
377
|
+
const motion = new MotionAccumulator();
|
|
378
|
+
let prev: Frame | null = null;
|
|
379
|
+
for (const t of everything) {
|
|
380
|
+
const mt = (await page.evaluate(
|
|
381
|
+
(time) => (window as unknown as { __framesheetVideo: { seek(t: number): Promise<number | null> } }).__framesheetVideo.seek(time),
|
|
382
|
+
t,
|
|
383
|
+
)) as number | null;
|
|
384
|
+
mediaTimes.set(t, mt === null ? null : pyRound(Number(mt), 4));
|
|
385
|
+
const png = await page.screenshot({ type: "png", caret: "hide", animations: "allow", scale: "device" });
|
|
386
|
+
const frame = decode(png);
|
|
387
|
+
if (wanted.has(t)) kept.set(t, { png, frame });
|
|
388
|
+
if (a <= t && t <= b) {
|
|
389
|
+
const ratio = prev ? diffStats(prev, frame)[0] : 0;
|
|
390
|
+
samples.push({ t, changed_ratio: pyRound(ratio, 5) });
|
|
391
|
+
stats.set(t, frameStats(frame));
|
|
392
|
+
motion.add(frame);
|
|
393
|
+
prev = frame;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
const tileFrames = tileTimes.map((t) => kept.get(t)!);
|
|
397
|
+
const metrics: FrameMetrics[] = [{ index: 0, t: tileTimes[0], changed_ratio: 0, changed_box: null, path: null }];
|
|
398
|
+
for (let i = 1; i < tileFrames.length; i++) {
|
|
399
|
+
const [ratio, box] = diffStats(tileFrames[i - 1].frame, tileFrames[i].frame);
|
|
400
|
+
metrics.push({ index: i, t: tileTimes[i], changed_ratio: pyRound(ratio, 5), changed_box: toCss(box, dsf), path: null });
|
|
401
|
+
}
|
|
402
|
+
const moving = samples.some((s) => s.changed_ratio > 0);
|
|
403
|
+
const info: DurationInfo = {
|
|
404
|
+
seconds: total,
|
|
405
|
+
method: o.duration ? "override" : "media",
|
|
406
|
+
looping: false,
|
|
407
|
+
detail: o.duration
|
|
408
|
+
? `--duration ${g(o.duration)}s${mediaDuration ? ` (media reports ${g(mediaDuration)}s)` : ""}`
|
|
409
|
+
: `media duration ${g(total)}s`,
|
|
410
|
+
animations: [],
|
|
411
|
+
};
|
|
412
|
+
const [findings, issues] = videoFindings(samples, stats, threshold, marks, a, b);
|
|
413
|
+
if (!moving) findings.push(render("info", "no-motion", "No animation found and no pixel changed: static.", null));
|
|
414
|
+
for (const msg of consoleErrors.slice(0, 5)) findings.push(render("warning", "console-error", msg, null));
|
|
415
|
+
const order = { error: 0, warning: 1, info: 2 };
|
|
416
|
+
findings.sort((x, y) => order[x.severity] - order[y.severity]);
|
|
417
|
+
|
|
418
|
+
const windows = tileWindows(tileTimes, a, b);
|
|
419
|
+
const n = tileTimes.length;
|
|
420
|
+
const tiles: VideoTile[] = tileTimes.map((t, i) => ({
|
|
421
|
+
index: i,
|
|
422
|
+
t,
|
|
423
|
+
media_time: mediaTimes.get(t) ?? null,
|
|
424
|
+
black: stats.get(t)![0],
|
|
425
|
+
blank: stats.get(t)![1],
|
|
426
|
+
duplicate: i > 0 && metrics[i].changed_ratio < STATIC_RATIO,
|
|
427
|
+
sharpness: sharpness(tileFrames[i].frame),
|
|
428
|
+
marks: marks ? activeLabels(marks, t, windows[i], i === n - 1) : [],
|
|
429
|
+
}));
|
|
430
|
+
const video: VideoInfo = {
|
|
431
|
+
container: probe.container,
|
|
432
|
+
codec: probe.codec,
|
|
433
|
+
decoder,
|
|
434
|
+
width,
|
|
435
|
+
height,
|
|
436
|
+
media_duration: mediaDuration,
|
|
437
|
+
fps: loaded.fps ?? probe.fps,
|
|
438
|
+
frame_count: loaded.frame_count ?? probe.frameCount,
|
|
439
|
+
start: a,
|
|
440
|
+
end: b,
|
|
441
|
+
static_threshold: threshold,
|
|
442
|
+
samples,
|
|
443
|
+
tiles,
|
|
444
|
+
};
|
|
445
|
+
const title = basename(src.label);
|
|
446
|
+
let facts = `${video.container}/${video.codec || "?"} ${width}x${height}`;
|
|
447
|
+
if (video.fps) facts += ` ${g(video.fps)} fps`;
|
|
448
|
+
const labels = tileTimes.map((t, i) => tileLabel(t, i, n, a, b));
|
|
449
|
+
const highlight = [0, n - 1].filter((i, k, arr) => arr.indexOf(i) === k && (labels[i].endsWith("start") || labels[i].endsWith("end")));
|
|
450
|
+
const activity = samples.map((s) => [s.t, s.changed_ratio] as [number, number]);
|
|
451
|
+
const sheet = await contactSheet(
|
|
452
|
+
renderer,
|
|
453
|
+
tileFrames.map((f) => ({ png: f.png, width: f.frame.width, height: f.frame.height })),
|
|
454
|
+
labels,
|
|
455
|
+
{
|
|
456
|
+
title,
|
|
457
|
+
subtitle: `${n} tiles over ${g(a)}-${g(b)}s (${mode}); ${facts}`,
|
|
458
|
+
tile: o.tile,
|
|
459
|
+
columns: o.columns,
|
|
460
|
+
highlight,
|
|
461
|
+
bands: marks && hasBand(marks) ? tileTimes.map((t) => bandText(marks, t)) : null,
|
|
462
|
+
overlay: marks
|
|
463
|
+
? (i, thumb) => tileOps(marks, tileTimes[i], windows[i], i === n - 1, { size: thumb, viewport, content })
|
|
464
|
+
: null,
|
|
465
|
+
footer: (w) => timelineOps(w, a, b, tileTimes, { marks, activity, issues }),
|
|
466
|
+
},
|
|
467
|
+
);
|
|
468
|
+
const heat = await heatmap(renderer, motion.first!, motion.acc!, {
|
|
469
|
+
title: `${title}: motion heatmap`,
|
|
470
|
+
subtitle: `pixels that change across ${motion.count} frames over ${g(a)}-${g(b)}s; background = t=${g(a)}s, dimmed`,
|
|
471
|
+
boxes: motion.box ? [motion.box] : [],
|
|
472
|
+
});
|
|
473
|
+
const images: ImageBuffers = { full: kept.get(fullAt)!.png, sheet, heatmap: heat };
|
|
474
|
+
if (o.keepFrames) images.frames = tileFrames.map((f) => f.png);
|
|
475
|
+
const out = o.out ? resolvePath(o.out) : null;
|
|
476
|
+
const paths: ImagePaths = out
|
|
477
|
+
? { full: join(out, "full.png"), sheet: join(out, "sheet.png"), heatmap: join(out, "heatmap.png"), report: join(out, "report.json") }
|
|
478
|
+
: { full: "full.png", sheet: "sheet.png", heatmap: "heatmap.png", report: "report.json" };
|
|
479
|
+
if (o.keepFrames) for (const m of metrics) m.path = join(out ?? "", "frames", `frame_${String(m.index).padStart(3, "0")}.png`);
|
|
480
|
+
const report: Report = {
|
|
481
|
+
source: src.label,
|
|
482
|
+
kind: "video",
|
|
483
|
+
viewport,
|
|
484
|
+
device_scale_factor: dsf,
|
|
485
|
+
canvas: content as Rect,
|
|
486
|
+
duration: info,
|
|
487
|
+
times: tileTimes,
|
|
488
|
+
full_at: fullAt,
|
|
489
|
+
images: paths,
|
|
490
|
+
findings,
|
|
491
|
+
frames: metrics,
|
|
492
|
+
elements: [],
|
|
493
|
+
loop: { checked: false, seamless: null, seam_ratio: null, step_ratio: null, seam_box: null, detail: "not checked for video input" },
|
|
494
|
+
console_errors: consoleErrors,
|
|
495
|
+
video,
|
|
496
|
+
marks,
|
|
497
|
+
};
|
|
498
|
+
if (out) {
|
|
499
|
+
mkdirSync(out, { recursive: true });
|
|
500
|
+
writeFileSync(paths.full, images.full);
|
|
501
|
+
writeFileSync(paths.sheet, images.sheet);
|
|
502
|
+
writeFileSync(paths.heatmap, images.heatmap);
|
|
503
|
+
if (images.frames) {
|
|
504
|
+
mkdirSync(join(out, "frames"), { recursive: true });
|
|
505
|
+
images.frames.forEach((png, i) => writeFileSync(join(out, "frames", `frame_${String(i).padStart(3, "0")}.png`), png));
|
|
506
|
+
}
|
|
507
|
+
writeFileSync(paths.report, `${JSON.stringify(report, null, 2)}\n`);
|
|
508
|
+
}
|
|
509
|
+
return { report, images, paths: out ? paths : null };
|
|
510
|
+
} finally {
|
|
511
|
+
await context.close().catch(() => undefined);
|
|
512
|
+
}
|
|
513
|
+
}
|