Files
hyperframes/packages/player/tests/perf/scenarios/02-fps.ts
T
Vance Ingalls 6f05fabbf8 perf(player): p0-1b perf tests for fps, scrub latency, and media sync drift (#400)
## Summary

Second slice of `P0-1` from the player perf proposal: plugs the three steady-state scenarios — sustained playback FPS, scrub latency, and media-sync drift — into the perf gate that landed in #399. Adds the multi-video fixture they all share, wires three new shards into CI, and seeds one new baseline (`droppedFramesMax`).

## Why

#399 stood up the harness and proved it with a single load-time scenario. By itself that's enough to catch regressions in initial composition setup, but it can't catch the things players actually fail at in production:

- **FPS regressions** — a render-loop change that drops the ticker from 60 to 45 fps still loads fast.
- **Scrub latency regressions** — the inline-vs-isolated split (#397) is exactly the kind of code path where a refactor can silently push everyone back to the postMessage round trip.
- **Media drift** — runtime mirror logic (#396 in this stack) and per-frame scheduling tweaks can both cause video to slip out of sync with the composition clock without producing a single console error.

Each of these is a target metric in the proposal with a concrete budget. This PR turns those budgets into gated CI signals and produces continuous data for them on every player/core/runtime change.

## What changed

### Fixture — `packages/player/tests/perf/fixtures/10-video-grid/`

- `index.html`: 10-second composition, 1920×1080, 30 fps, with 10 simultaneously-decoding video tiles in a 5×2 grid plus a subtle GSAP scale "breath" on each tile (so the rAF/RVFC loops have real work to do without GSAP dominating the budget the decoder needs).
- `sample.mp4`: small (~190 KB) clip checked in so the fixture is hermetic — no external CDN dependency, identical bytes on every run.
- Same `data-composition-id="main"` host pattern as `gsap-heavy`, so the existing harness loader works without changes.

### `02-fps.ts` — sustained playback frame rate

- Loads `10-video-grid`, calls `player.play()`, samples `requestAnimationFrame` callbacks inside the iframe for 5 s.
- Crucial sequencing: install the rAF sampler **before** `play()`, wait for `__player.isPlaying() === true`, **then reset the sample buffer** — otherwise the postMessage round-trip ramp-up window drags the average down by 5–10 fps.
- FPS = `(samples − 1) / (lastTs − firstTs in s)`; uses rAF timestamps (the same ones the compositor saw) rather than wall-clock `setTimeout`, so we're measuring real frame production.
- Dropped-frame definition matches Chrome DevTools: gap > 1.5× (1000/60 ms) ≈ 25 ms = "missed at least one vsync."
- Aggregation across runs: `min(fps)` and `max(droppedFrames)` — worst case wins, since the proposal asserts a floor on fps and a ceiling on drops.
- Emits `playback_fps_min` (higher-is-better, baseline `fpsMin = 55`) and `playback_dropped_frames_max` (lower-is-better, baseline `droppedFramesMax = 3`).

### `04-scrub.ts` — scrub latency, inline + isolated

- Loads `10-video-grid`, pauses, then issues 10 seek calls in two batches: first the synchronous **inline** path (`<hyperframes-player>`'s default same-origin `_trySyncSeek`), then the **isolated** path (forced by replacing `_trySyncSeek` with `() => false`, which makes the player fall back to the postMessage `_sendControl("seek")` bridge that cross-origin embeds and pre-#397 builds use).
- Inline runs first so the isolated mode's monkey-patch can't bleed back into the inline samples.
- Detection: a rAF watcher inside the iframe polls `__player.getTime()` until it's within `MATCH_TOLERANCE_S = 0.05 s` of the requested target. Tolerance exists because the postMessage bridge converts seconds → frame number → seconds, and that round-trip can introduce sub-frame quantization drift even for targets on the canonical fps grid.
- Timing: `performance.timeOrigin + performance.now()` in both contexts. `timeOrigin` is consistent across same-process frames, so `t1 − t0` is a true wall-clock latency, not a host-only or iframe-only stopwatch.
- Targets alternate forward/backward (`1.0, 7.0, 2.0, 8.0, 3.0, 9.0, 4.0, 6.0, 5.0, 0.5`) so no two consecutive seeks land near each other — protects the rAF watcher from matching against a stale `getTime()` value before the seek command is processed.
- Aggregation: `percentile(95)` across the pooled per-seek latencies from every run. With 10 seeks × 2 modes × 3 runs we get 30 samples per mode per CI shard, enough for a stable p95.
- Emits `scrub_latency_p95_inline_ms` (lower-is-better, baseline `scrubLatencyP95InlineMs = 33`) and `scrub_latency_p95_isolated_ms` (lower-is-better, baseline `scrubLatencyP95IsolatedMs = 80`).

### `05-drift.ts` — media sync drift

- Loads `10-video-grid`, plays 6 s, instruments **every** `video[data-start]` element with `requestVideoFrameCallback`. Each callback records `(compositionTime, actualMediaTime)` plus a snapshot of the clip transform (`clipStart`, `clipMediaStart`, `clipPlaybackRate`).
- Drift = `|actualMediaTime − ((compTime − clipStart) × clipPlaybackRate + clipMediaStart)|` — the same transform the runtime applies in `packages/core/src/runtime/media.ts`, snapshotted once at sampler install so the per-frame work is just subtract + multiply + abs.
- Sustain window is 6 s (not the proposal's 10 s) because the fixture composition is exactly 10 s long and we want headroom before the end-of-timeline pause/clamp behavior. With 10 videos × ~25 fps × 6 s we still pool ~1500 samples per run — more than enough for a stable p95.
- Same "reset buffer after play confirmed" gotcha as `02-fps.ts`: frames captured during the postMessage round-trip would compare a non-zero `mediaTime` against `getTime() === 0` and inflate drift by hundreds of ms.
- Aggregation: `max()` and `percentile(95)` across the pooled per-frame drifts. The proposal's max-drift ceiling of 500 ms is intentional — the runtime hard-resyncs when `|currentTime − relTime| > 0.5 s`, so a regression past 500 ms means the corrective resync kicked in and the viewer saw a jump.
- Emits `media_drift_max_ms` (lower-is-better, baseline `driftMaxMs = 500`) and `media_drift_p95_ms` (lower-is-better, baseline `driftP95Ms = 100`).

### Wiring

- `packages/player/tests/perf/index.ts`: add `fps`, `scrub`, `drift` to `ScenarioId`, `DEFAULT_RUNS`, the default scenario list (`--scenarios` defaults to all four), and three new dispatch branches.
- `packages/player/tests/perf/perf-gate.ts`: add `droppedFramesMax: number` to `PerfBaseline`. Other baseline keys for these scenarios were already seeded in #399.
- `packages/player/tests/perf/baseline.json`: add `droppedFramesMax: 3`.
- `.github/workflows/player-perf.yml`: three new matrix shards (`fps` / `scrub` / `drift`) at `runs: 3`. Same `paths-filter` and same artifact-upload pattern as the `load` shard, so the summary job aggregates them automatically.

## Methodology highlights

These three patterns recur in all three scenarios and are worth noting because they're load-bearing for the numbers we report:

1. **Reset buffer after play-confirmed.** The `play()` API is async (postMessage), so any samples captured before `__player.isPlaying() === true` belong to ramp-up, not steady-state. Both `02-fps` and `05-drift` clear `__perfRafSamples` / `__perfDriftSamples` *after* the wait. Without this, fps drops 5–10 and drift inflates by hundreds of ms.
2. **Iframe-side timing.** All three scenarios time inside the iframe (`performance.timeOrigin + performance.now()` for scrub, rAF/RVFC timestamps for fps/drift) rather than host-side. The iframe is what the user sees; host-side timing would conflate Puppeteer's IPC overhead with real player latency.
3. **Stop sampling before pause.** Sampler is deactivated *before* `pause()` is issued, so the pause command's postMessage round-trip can't perturb the tail of the measurement window.

## Test plan

- [x] Local: `bun run player:perf` runs all four scenarios end-to-end on the 10-video-grid fixture.
- [x] Each scenario produces metrics matching its declared `baselineKey` so `perf-gate.ts` can find them.
- [x] Typecheck, lint, format pass on the new files.
- [x] Existing player unit tests untouched (no production code changes in this PR).
- [ ] First CI run will confirm the new shards complete inside the workflow timeout and that the summary job picks up their `metrics.json` artifacts.

## Stack

Step `P0-1b` of the player perf proposal. Builds on:

- `P0-1a` (#399): the harness, runner, gate, and CI workflow this PR plugs new scenarios into.

Followed by:

- `P0-1c` (#401): `06-parity` — live playback frame vs. synchronously-seeked reference frame, compared via SSIM, on the existing `gsap-heavy` fixture from #399.
2026-04-22 18:10:08 -07:00

237 lines
9.3 KiB
TypeScript

/**
* Scenario 02: sustained playback against the composition clock.
*
* Loads the 10-video-grid fixture, calls `player.play()`, then samples
* `__player.getTime()` at fixed wall-clock intervals for ~5 seconds. The
* emitted metric is the ratio of composition-time advanced to wall-clock
* elapsed:
*
* composition_time_advancement_ratio = (getTime(end) - getTime(start)) / wallSeconds
*
* This reads ~1.0 when the runtime is keeping up with its intended playback
* speed and falls below 1.0 when the player stalls — a slow video decoder, a
* blocked main thread, a GC pause, anything that prevents the composition
* clock from advancing at real-time. The metric is independent of the host
* display refresh rate by construction: both numerator and denominator are
* wall-clock timestamps, neither is a frame count, so a 60Hz, 120Hz, or 240Hz
* runner sees the same value for a healthy player.
*
* Why we replaced the previous rAF-based FPS metric:
* The original implementation counted `requestAnimationFrame` ticks per
* wall-clock second and asserted `fps >= 55`. On a 120Hz CI runner that
* reads ~120 fps regardless of whether the composition is actually
* advancing, so the gate passed even when the player was silently stalling.
* See PR #400 review (jrusso1020 + miguel-heygen) for the full discussion;
* this implementation follows jrusso1020's "first choice" recommendation.
*
* Per the proposal:
* Test 1: Playback frame rate (player-perf-fps)
* Load 10-video composition → play 5s → measure how well the player kept
* up with the composition clock.
*
* Methodology details:
* - We install the wall-clock sampler before calling `play()` so the very
* first post-play tick is captured. We then wait for `__player.isPlaying()`
* to flip true (the parent→iframe `play` message is async via postMessage)
* and *reset* the sample buffer, so the measurement window only contains
* samples taken while the runtime was actively playing the timeline.
* - Sampling cadence is 100ms (10 samples/sec). That's fine-grained enough
* to spot a half-second stall but coarse enough that the sampler itself
* has negligible overhead. With a 5s window we collect ~50 samples; the
* ratio is computed from the first and last sample's `getTime()` values.
* - We use `setInterval` (not rAF) on purpose: rAF cadence is the metric we
* are trying to *avoid* depending on. `setInterval` is wall-clock-driven.
*
* Outputs one metric:
* - composition_time_advancement_ratio_min
* (higher-is-better, baseline key compositionTimeAdvancementRatioMin)
*
* Aggregation: `min(ratio)` across runs because the proposal asserts a floor
* — the worst run is the one that gates against regressions.
*/
import type { Browser, Frame, Page } from "puppeteer-core";
import { loadHostPage } from "../runner.ts";
import type { Metric } from "../perf-gate.ts";
export type FpsScenarioOpts = {
browser: Browser;
origin: string;
/** Number of measurement runs. */
runs: number;
/** If null, runs the default fixture (10-video-grid). */
fixture: string | null;
};
const DEFAULT_FIXTURE = "10-video-grid";
const PLAYBACK_DURATION_MS = 5_000;
const SAMPLE_INTERVAL_MS = 100;
const PLAY_CONFIRM_TIMEOUT_MS = 5_000;
const FRAME_LOOKUP_TIMEOUT_MS = 5_000;
declare global {
interface Window {
/** (wallClockMs, compositionTimeSec) pairs collected by the sampler. */
__perfPlaySamples?: Array<{ wall: number; comp: number }>;
/** setInterval handle used by the sampler; cleared at the end of the window. */
__perfPlaySamplerHandle?: number;
/** Hyperframes runtime player API exposed inside the composition iframe. */
__player?: {
play: () => void;
pause: () => void;
seek: (timeSeconds: number) => void;
getTime: () => number;
getDuration: () => number;
isPlaying: () => boolean;
};
}
}
type RunResult = {
ratio: number;
compElapsedSec: number;
wallElapsedSec: number;
samples: number;
};
/**
* Find the iframe Puppeteer Frame that hosts the fixture composition. The
* `<hyperframes-player>` shell wraps an iframe whose URL is derived from the
* player's `src` attribute, so we match by path substring rather than full URL.
*/
async function getFixtureFrame(page: Page, fixture: string): Promise<Frame> {
const expected = `/fixtures/${fixture}/`;
const deadline = Date.now() + FRAME_LOOKUP_TIMEOUT_MS;
while (Date.now() < deadline) {
const frame = page.frames().find((f) => f.url().includes(expected));
if (frame) return frame;
await new Promise((r) => setTimeout(r, 50));
}
throw new Error(`[scenario:fps] fixture frame not found for "${fixture}" within timeout`);
}
async function runOnce(
opts: FpsScenarioOpts,
fixture: string,
idx: number,
total: number,
): Promise<RunResult> {
const ctx = await opts.browser.createBrowserContext();
try {
const page = await ctx.newPage();
const { duration } = await loadHostPage(page, opts.origin, { fixture });
const frame = await getFixtureFrame(page, fixture);
// Install the wall-clock sampler in the iframe context. We use setInterval
// because rAF cadence is exactly the host-display-dependent signal we are
// trying NOT to depend on; setInterval is driven by the event loop and
// gives us samples at fixed wall-clock cadence regardless of refresh rate.
await frame.evaluate((sampleIntervalMs: number) => {
window.__perfPlaySamples = [];
window.__perfPlaySamplerHandle = window.setInterval(() => {
const comp = window.__player?.getTime?.();
if (typeof comp !== "number" || !Number.isFinite(comp)) return;
window.__perfPlaySamples!.push({
wall: performance.timeOrigin + performance.now(),
comp,
});
}, sampleIntervalMs);
}, SAMPLE_INTERVAL_MS);
// Issue play from the host page (parent of the iframe). The player's
// public `play()` posts a control message into the iframe.
await page.evaluate(() => {
const el = document.getElementById("player") as (HTMLElement & { play: () => void }) | null;
if (!el) throw new Error("[scenario:fps] player element missing on host page");
el.play();
});
// Wait for the runtime to actually transition to playing — this is the
// signal that the postMessage round trip + timeline.play() finished.
await frame.waitForFunction(() => window.__player?.isPlaying?.() === true, {
timeout: PLAY_CONFIRM_TIMEOUT_MS,
});
// Reset samples now that playback is confirmed running. Anything captured
// before this point belongs to the ramp-up window (composition clock at
// 0, wall clock advancing) and would skew the ratio toward 0.
await frame.evaluate(() => {
window.__perfPlaySamples = [];
});
// Sustain playback for the measurement window.
await new Promise((r) => setTimeout(r, PLAYBACK_DURATION_MS));
// Stop the sampler and harvest the samples before pausing the runtime,
// so the pause command can't perturb the tail of the sample window.
const samples = (await frame.evaluate(() => {
if (window.__perfPlaySamplerHandle !== undefined) {
clearInterval(window.__perfPlaySamplerHandle);
window.__perfPlaySamplerHandle = undefined;
}
return window.__perfPlaySamples ?? [];
})) as Array<{ wall: number; comp: number }>;
await page.evaluate(() => {
const el = document.getElementById("player") as (HTMLElement & { pause: () => void }) | null;
el?.pause();
});
if (samples.length < 2) {
throw new Error(
`[scenario:fps] run ${idx + 1}/${total}: only ${samples.length} composition-clock samples captured (composition duration ${duration}s)`,
);
}
const first = samples[0]!;
const last = samples[samples.length - 1]!;
const wallElapsedSec = (last.wall - first.wall) / 1000;
const compElapsedSec = last.comp - first.comp;
const ratio = wallElapsedSec > 0 ? compElapsedSec / wallElapsedSec : 0;
console.log(
`[scenario:fps] run[${idx + 1}/${total}] ratio=${ratio.toFixed(4)} compElapsed=${compElapsedSec.toFixed(3)}s wallElapsed=${wallElapsedSec.toFixed(3)}s samples=${samples.length}`,
);
await page.close();
return {
ratio,
compElapsedSec,
wallElapsedSec,
samples: samples.length,
};
} finally {
await ctx.close();
}
}
export async function runFps(opts: FpsScenarioOpts): Promise<Metric[]> {
const fixture = opts.fixture ?? DEFAULT_FIXTURE;
const runs = Math.max(1, opts.runs);
console.log(
`[scenario:fps] fixture=${fixture} runs=${runs} window=${PLAYBACK_DURATION_MS}ms sampleInterval=${SAMPLE_INTERVAL_MS}ms`,
);
const ratios: number[] = [];
for (let i = 0; i < runs; i++) {
const result = await runOnce(opts, fixture, i, runs);
ratios.push(result.ratio);
}
// Worst run wins: the proposal asserts a floor on this ratio, so a single
// bad run (slow decoder, GC pause, host contention) is the one that gates.
const ratioMin = Math.min(...ratios);
console.log(`[scenario:fps] aggregate min ratio=${ratioMin.toFixed(4)} runs=${runs}`);
return [
{
name: "composition_time_advancement_ratio_min",
baselineKey: "compositionTimeAdvancementRatioMin",
value: ratioMin,
unit: "ratio",
direction: "higher-is-better",
samples: ratios,
},
];
}