Skip to content

Commit 0897dc8

Browse files
committed
feat: interleave html5 bakes within one shared in-flight budget
1 parent 652ba24 commit 0897dc8

2 files changed

Lines changed: 113 additions & 10 deletions

File tree

‎src/components/canvas/players/html5-player.ts‎

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,8 @@ export class Html5Player extends Player {
118118
private static bakes = new BakeQueue();
119119
// Pages still mounting. A bake joins the queue once they have, so the queue orders every clip that loaded together.
120120
private static readonly mounts = new Set<Promise<void>>();
121+
// Frames every bake has in flight. Bakes take turns, so they share one window and one memory budget.
122+
private static readonly inFlight = { frames: 0, bytes: 0 };
121123

122124
private iframe: HTMLIFrameElement | null = null;
123125
private renderedWidth: number = 0;
@@ -405,11 +407,11 @@ export class Html5Player extends Player {
405407

406408
private async queueBake(queuedFor: string | null, minScale: number): Promise<Blob[] | null> {
407409
while (Html5Player.mounts.size > 0) await Promise.allSettled([...Html5Player.mounts]);
408-
return Html5Player.bakes.add(this.bakeSlot, async () => {
410+
return Html5Player.bakes.add(this.bakeSlot, async turn => {
409411
// A content change while this waited in the queue would bake the new content at this capture's floor.
410412
if (this.disposed || this.contentHash !== queuedFor) return null;
411413
try {
412-
return await this.runCapture(minScale);
414+
return await this.runCapture(minScale, turn);
413415
} finally {
414416
this.bakeNextIndex = null;
415417
}
@@ -452,7 +454,7 @@ export class Html5Player extends Player {
452454
}
453455

454456
// A re-bake passes the scale it was started for, so a later, smaller sample can't bake softer frames.
455-
private async runCapture(minScale: number = 0): Promise<Blob[] | null> {
457+
private async runCapture(minScale: number = 0, turn: () => Promise<void> = async () => {}): Promise<Blob[] | null> {
456458
if (!this.iframe || !this.iframe.contentDocument || !this.iframe.contentWindow) return null;
457459

458460
const { contentHash } = this;
@@ -485,7 +487,11 @@ export class Html5Player extends Player {
485487
this.captureFramesTotal = frameCount;
486488
this.captureFramesDone = 0;
487489

488-
const framesInFlight = captureFramesInFlight(navigator.hardwareConcurrency, Math.trunc(W * scale) * Math.trunc(H * scale) * 4);
490+
const frameBytes = Math.trunc(W * scale) * Math.trunc(H * scale) * 4;
491+
const framesInFlight = captureFramesInFlight(navigator.hardwareConcurrency, frameBytes);
492+
const { inFlight } = Html5Player;
493+
const hasRoom = (): boolean =>
494+
inFlight.frames === 0 || (inFlight.frames < framesInFlight && inFlight.bytes + frameBytes <= CAPTURE_MEMORY_BUDGET_BYTES);
489495
// The playhead's frame goes first, so the clip under it plays soonest.
490496
const segments = passSegments(
491497
Array.from({ length: frameCount }, (_, i) => i),
@@ -505,15 +511,21 @@ export class Html5Player extends Player {
505511
let sliceStart = -Infinity;
506512
// Frames publish in the order they were issued, so the oldest in flight gates the window.
507513
while (published < frameCount) {
508-
if (issued < frameCount && pending.length < framesInFlight) {
514+
if (issued < frameCount && hasRoom()) {
509515
const idx = order[issued];
510516
this.bakeNextIndex = idx;
511-
if (freshPageAt.has(issued) && !(await this.loadFreshPage(this.iframe, stale, scale))) return null;
512517
if (performance.now() - sliceStart >= CAPTURE_SLICE_MS) {
513518
await nextFrame();
514519
if (stale()) return null;
520+
await turn();
521+
if (stale()) return null;
515522
sliceStart = performance.now();
516523
}
524+
}
525+
// Other bakes draw during their turns, so the window is read again once this one has its turn back.
526+
if (issued < frameCount && hasRoom()) {
527+
const idx = order[issued];
528+
if (freshPageAt.has(issued) && !(await this.loadFreshPage(this.iframe, stale, scale))) return null;
517529
this.seekHarness(idx / fps);
518530
forceLayout(this.iframe.contentDocument.body);
519531
const { styles, body } = this.serialiseIframe(W, H);
@@ -523,9 +535,14 @@ export class Html5Player extends Player {
523535
}
524536
let drawn = recent.get(body);
525537
if (!drawn) {
526-
drawn = foreignObjectSvgToWebp(foreignObjectSvg(W, H, styles, body), W, H, scale).then(
527-
bytes => new Blob([bytes as BlobPart], { type: "image/webp" })
528-
);
538+
inFlight.frames += 1;
539+
inFlight.bytes += frameBytes;
540+
drawn = foreignObjectSvgToWebp(foreignObjectSvg(W, H, styles, body), W, H, scale)
541+
.then(bytes => new Blob([bytes as BlobPart], { type: "image/webp" }))
542+
.finally(() => {
543+
inFlight.frames -= 1;
544+
inFlight.bytes -= frameBytes;
545+
});
529546
// Marks a queued frame's failure handled; awaiting it rethrows.
530547
drawn.catch(() => undefined);
531548
// A Map iterates in insertion order, so its first key is the oldest frame.
@@ -534,7 +551,7 @@ export class Html5Player extends Player {
534551
}
535552
pending.push({ idx, drawn });
536553
issued += 1;
537-
} else {
554+
} else if (pending.length > 0) {
538555
const { idx, drawn } = pending.shift()!;
539556
const frame = await drawn;
540557
if (stale()) return null;
@@ -547,6 +564,10 @@ export class Html5Player extends Player {
547564
progressStep = step;
548565
this.emitCaptureProgress();
549566
}
567+
} else {
568+
// Other bakes' frames fill the window, and they finish without their bakes' turns.
569+
await nextFrame();
570+
if (stale()) return null;
550571
}
551572
}
552573

‎tests/html5-player.test.ts‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -857,6 +857,48 @@ it.each([
857857
expect(markup.map(frame => /data-t="([^"]*)"/.exec(frame)?.[1])).toEqual(Array.from({ length: 60 }, (_, i) => String(i / 30)));
858858
});
859859

860+
const sliceEveryFrame = () => {
861+
let clock = 0;
862+
jest.spyOn(performance, "now").mockImplementation(() => {
863+
clock += 13;
864+
return clock;
865+
});
866+
};
867+
868+
const sharedInFlight = () => (Html5Player as unknown as { inFlight: { frames: number; bytes: number } }).inFlight;
869+
870+
it("waits for another bake's frames to leave the window before drawing its own", async () => {
871+
const { harness } = createStillPlayer();
872+
Object.assign(harness, { renderedWidth: 3840, renderedHeight: 2160 });
873+
jest.spyOn(Navigator.prototype, "hardwareConcurrency", "get").mockReturnValue(16);
874+
Object.assign(sharedInFlight(), { frames: 8, bytes: 8 * 3840 * 2160 * 4 });
875+
let waits = 0;
876+
jest.spyOn(window, "requestAnimationFrame").mockImplementation(callback => {
877+
waits += 1;
878+
if (waits === 5) Object.assign(sharedInFlight(), { frames: 0, bytes: 0 });
879+
setTimeout(() => callback(0), 0);
880+
return 0;
881+
});
882+
883+
expect(await harness.runCapture()).toHaveLength(60);
884+
expect(waits).toBeGreaterThanOrEqual(5);
885+
expect(sharedInFlight()).toEqual({ frames: 0, bytes: 0 });
886+
});
887+
888+
it("releases its share of the in-flight window when disposed mid-bake", async () => {
889+
const { player, harness } = createStillPlayer();
890+
const { held, releaseAll } = holdToBlob();
891+
const capture = harness.runCapture();
892+
await until(() => held.length > 0);
893+
894+
player.dispose();
895+
releaseAll();
896+
await capture;
897+
await flush();
898+
899+
expect(sharedInFlight()).toEqual({ frames: 0, bytes: 0 });
900+
});
901+
860902
it("returns no frames when the content changes while frames are in flight", async () => {
861903
const { harness } = createStillPlayer();
862904
jest.spyOn(Navigator.prototype, "hardwareConcurrency", "get").mockReturnValue(4);
@@ -1298,6 +1340,46 @@ it("bakes the clip that plays first ahead of one whose page loaded first", async
12981340
}
12991341
});
13001342

1343+
it("shares one in-flight window between bakes that take turns", async () => {
1344+
const a = createStillPlayer();
1345+
const b = createStillPlayer();
1346+
b.harness.contentHash = "other";
1347+
[a, b].forEach(({ harness }) => Object.assign(harness, { renderedWidth: 3840, renderedHeight: 2160 }));
1348+
jest.spyOn(Navigator.prototype, "hardwareConcurrency", "get").mockReturnValue(16);
1349+
sliceEveryFrame();
1350+
const { held, releaseAll } = holdToBlob();
1351+
const restore = emptyCaptureQueue();
1352+
try {
1353+
const captures = [a.harness.captureFrames(), b.harness.captureFrames()];
1354+
await until(() => held.length >= 8);
1355+
await flush(100);
1356+
expect(held).toHaveLength(8);
1357+
1358+
releaseAll();
1359+
expect((await Promise.all(captures)).map(frames => frames?.length)).toEqual([60, 60]);
1360+
} finally {
1361+
restore();
1362+
}
1363+
});
1364+
1365+
it("alternates overlapping clips' frames rather than baking one clip whole", async () => {
1366+
const a = createStillPlayer();
1367+
const b = createStillPlayer();
1368+
b.harness.contentHash = "other";
1369+
const order: string[] = [];
1370+
a.onSeek = seek => seek.startsWith("bake") && order.push("a");
1371+
b.onSeek = seek => seek.startsWith("bake") && order.push("b");
1372+
sliceEveryFrame();
1373+
const restore = emptyCaptureQueue();
1374+
try {
1375+
await Promise.all([a.harness.captureFrames(), b.harness.captureFrames()]);
1376+
1377+
expect(new Set(order.slice(0, 10)).size).toBe(2);
1378+
} finally {
1379+
restore();
1380+
}
1381+
});
1382+
13011383
it("drops a cached bake whose content changed during the lookup", async () => {
13021384
const { harness, events } = createStillPlayer();
13031385
let hit: (value: unknown) => void = () => {};

0 commit comments

Comments
 (0)