Skip to content

Commit 652ba24

Browse files
committed
feat: bake html5 frames from the playhead into a store indexed by frame
1 parent deb3a24 commit 652ba24

4 files changed

Lines changed: 62 additions & 10 deletions

File tree

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
/** A pass's frames from the anchor on, then those before it. Pages only seek forward, so each segment needs a fresh page. */
2+
export function passSegments(indices: readonly number[], anchor: number): number[][] {
3+
return [indices.filter(i => i >= anchor), indices.filter(i => i < anchor)].filter(segment => segment.length > 0);
4+
}

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

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
} from "@shotstack/shotstack-canvas";
1818
import * as pixi from "pixi.js";
1919

20+
import { passSegments } from "./bake-order";
2021
import { BakeQueue } from "./bake-queue";
2122
import { computeHtml5CacheKey, html5CacheGet, html5CachePut } from "./html5-cache";
2223
import { createCaptureLoadingGraphic, createPlaceholderGraphic } from "./placeholder-graphic";
@@ -423,6 +424,11 @@ export class Html5Player extends Player {
423424
return start + (idx + 1) / this.captureFps;
424425
}
425426

427+
// The frame on screen at the playhead, or past the last frame once the playhead has left the clip.
428+
private bakeAnchor(frameCount: number): number {
429+
return Math.min(Math.max(0, Math.floor((this.edit.playbackTime - this.getStart()) * this.captureFps)), frameCount);
430+
}
431+
426432
// After a tick, an active clip's global transform is the size the canvas shows it at. An inactive clip's own
427433
// transform isn't applied, so its bake reads only the viewport's zoom and may re-bake once the clip is active.
428434
private async bakeScale(minScale: number): Promise<number> {
@@ -480,24 +486,35 @@ export class Html5Player extends Player {
480486
this.captureFramesDone = 0;
481487

482488
const framesInFlight = captureFramesInFlight(navigator.hardwareConcurrency, Math.trunc(W * scale) * Math.trunc(H * scale) * 4);
483-
const blobs: Blob[] = [];
484-
const pending: Promise<Blob>[] = [];
489+
// The playhead's frame goes first, so the clip under it plays soonest.
490+
const segments = passSegments(
491+
Array.from({ length: frameCount }, (_, i) => i),
492+
this.bakeAnchor(frameCount)
493+
);
494+
const order = segments.flat();
495+
// Where each segment after the first starts in the issue order.
496+
const freshPageAt = new Set(segments.slice(0, -1).map((_, i) => segments.slice(0, i + 1).flat().length));
497+
const frames: Array<Blob | undefined> = new Array(frameCount);
498+
const pending: { idx: number; drawn: Promise<Blob> }[] = [];
485499
// The SVG is a frame's whole input, so a frame that repeats a recent one draws identical bytes and shares its Blob.
486500
const recent = new Map<string, Promise<Blob>>();
487501
let recentStyles = "";
488502
let issued = 0;
489-
this.bakeNextIndex = 0;
503+
let published = 0;
490504
let progressStep = 0;
491505
let sliceStart = -Infinity;
492-
// Frames publish in order, so the oldest in flight gates the window.
493-
while (blobs.length < frameCount) {
506+
// Frames publish in the order they were issued, so the oldest in flight gates the window.
507+
while (published < frameCount) {
494508
if (issued < frameCount && pending.length < framesInFlight) {
509+
const idx = order[issued];
510+
this.bakeNextIndex = idx;
511+
if (freshPageAt.has(issued) && !(await this.loadFreshPage(this.iframe, stale, scale))) return null;
495512
if (performance.now() - sliceStart >= CAPTURE_SLICE_MS) {
496513
await nextFrame();
497514
if (stale()) return null;
498515
sliceStart = performance.now();
499516
}
500-
this.seekHarness(issued / fps);
517+
this.seekHarness(idx / fps);
501518
forceLayout(this.iframe.contentDocument.body);
502519
const { styles, body } = this.serialiseIframe(W, H);
503520
if (styles !== recentStyles) {
@@ -515,13 +532,14 @@ export class Html5Player extends Player {
515532
if (recent.size >= REPEAT_WINDOW_FRAMES) recent.delete(recent.keys().next().value!);
516533
recent.set(body, drawn);
517534
}
518-
pending.push(drawn);
535+
pending.push({ idx, drawn });
519536
issued += 1;
520-
this.bakeNextIndex = issued;
521537
} else {
522-
const frame = await pending.shift()!;
538+
const { idx, drawn } = pending.shift()!;
539+
const frame = await drawn;
523540
if (stale()) return null;
524-
blobs.push(frame);
541+
frames[idx] = frame;
542+
published += 1;
525543
this.captureFramesDone += 1;
526544
// Steps, not frames: enough for a ring to fill smoothly, and bounded whatever the frame count.
527545
const step = Math.floor((this.captureFramesDone / frameCount) * CAPTURE_PROGRESS_STEPS);
@@ -532,6 +550,8 @@ export class Html5Player extends Player {
532550
}
533551
}
534552

553+
// Every index has published by now.
554+
const blobs = frames as Blob[];
535555
if (!(await this.adoptBake(blobs, cacheKey, scale, stale))) return null;
536556
this.emitCaptureCompleted(frameCount);
537557

‎tests/bake-order.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { passSegments } from "@canvas/players/bake-order";
2+
3+
it("splits a pass at the playhead, ahead first", () => {
4+
const all = Array.from({ length: 10 }, (_, i) => i);
5+
6+
expect(passSegments(all, 4)).toEqual([
7+
[4, 5, 6, 7, 8, 9],
8+
[0, 1, 2, 3]
9+
]);
10+
expect(passSegments(all, 0)).toEqual([all]);
11+
expect(passSegments(all, 10)).toEqual([all]);
12+
});

‎tests/html5-player.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -737,6 +737,22 @@ it("keeps a still taken mid-capture and the capture from changing each other's f
737737
expect(seeks.indexOf("still 0.1")).toBeLessThan(seeks.indexOf(`bake ${59 / 30}`));
738738
});
739739

740+
it("bakes from the playhead to the clip's end, then from a fresh page up to the playhead", async () => {
741+
const { harness, edit, iframe, seeks } = createStillPlayer(); // 2 s at 30 fps: 60 frames
742+
Object.assign(edit, { playbackTime: 1 });
743+
const loads = jest.spyOn(HTMLIFrameElement.prototype, "srcdoc", "set");
744+
loads.mockClear();
745+
746+
const frames = (await harness.runCapture())!;
747+
748+
const order = [...Array.from({ length: 30 }, (_, i) => 30 + i), ...Array.from({ length: 30 }, (_, i) => i)];
749+
expect(seeks.filter(seek => seek.startsWith("bake"))).toEqual(order.map(i => `bake ${i / 30}`));
750+
expect(loads.mock.contexts.filter(context => context === iframe)).toHaveLength(2);
751+
const markup = await Promise.all(frames.map(frameMarkup));
752+
expect(markup.map(frame => /data-t="([^"]*)"/.exec(frame)?.[1])).toEqual(Array.from({ length: 60 }, (_, i) => String(i / 30)));
753+
expect(markup.some(frame => frame.includes("data-rewound"))).toBe(false);
754+
});
755+
740756
it("draws a frame only when the page changed, reusing the last frame's blob", async () => {
741757
const { harness } = createStillPlayer(); // 2 s at 30 fps: 60 frames
742758
const seek = jest.mocked(harness.seekHarness);

0 commit comments

Comments
 (0)