Skip to content

Commit c772385

Browse files
jrusso1020claude
andauthored
perf(producer): share the video box measuring across a chunk's capture workers (#9127)
* perf(producer): share the video box measuring across a chunk's capture workers A chunk captured by several BeginFrame workers measured how large each video is drawn by seeking one worker's page through every frame of the chunk while the other workers waited. Each worker now measures its own share of the frames on its own page, before the first-session check, and the shares merge to the boxes one pass would have measured. A worker lost before its share, or a chunk sent to screenshot capture, extracts at full size. One log line reports the pass: workers, frames and duration. Signed: Rames Jusso Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(producer): keep the measured boxes when the check sends a chunk to screenshot capture The shares usually land before the first-session check has finished, so settling the chunk at full size from the check only won when a share was still out, and the extraction size on that path depended on timing. The check no longer settles it: boxes that were measured are used, as before this branch. Also pins that a video one share saw at full size stays out of the merged boxes. Signed: Rames Jusso Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * test(producer): the fake page in the local box test returns what the page now returns Signed: Rames Jusso Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
1 parent 98b2153 commit c772385

10 files changed

Lines changed: 364 additions & 26 deletions

‎packages/engine/src/index.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,7 @@ export {
364364
type WorkerSizingBound,
365365
type WorkerSizingConfig,
366366
type LandedFrame,
367+
type ParallelCaptureHooks,
367368
type ParallelProgress,
368369
type ParallelWorkerPhaseDiagnostic,
369370
} from "./services/parallelCoordinator.js";
@@ -553,6 +554,9 @@ export {
553554
queryElementStacking,
554555
measureVideoShownBoxes,
555556
measureVideoShownBoxRanges,
557+
measureVideoShownBoxPart,
558+
mergeVideoShownBoxParts,
559+
type ShownBoxPart,
556560
type ShownBox,
557561
type ShownBoxRange,
558562
type VideoElementBounds,

‎packages/engine/src/services/parallelCoordinator-peerAbort.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,60 @@ describe("executeParallelCapture peer abort", () => {
313313
}
314314
});
315315

316+
it("every worker prepares its own session without waiting for worker 0's check, and a worker lost before that is reported", async () => {
317+
const root = mkdtempSync(join(tmpdir(), "hf-prepare-session-"));
318+
vi.doMock("./frameCapture.js", () => ({
319+
createCaptureSession: vi.fn(async (_url: string, outputDir: string) => {
320+
if (outputDir.endsWith("worker-2")) throw new Error("Protocol error: Target closed");
321+
return { browserConsoleBuffer: [] };
322+
}),
323+
initializeSession: vi.fn(async () => {}),
324+
captureFrame: vi.fn(async () => ({ path: join(root, "frame.jpg") })),
325+
captureFrameToBuffer: vi.fn(),
326+
captureFrameToBufferPipelined: vi.fn(),
327+
closeCaptureSession: vi.fn().mockResolvedValue(undefined),
328+
getCapturePerfSummary: vi.fn(() => ({ frames: 0 })),
329+
}));
330+
try {
331+
const { executeParallelCapture } = await import("./parallelCoordinator.js");
332+
const prepared: { workerId: number; workerCount: number }[] = [];
333+
const unprepared: number[] = [];
334+
let pass!: () => void;
335+
const result = executeParallelCapture(
336+
"http://127.0.0.1",
337+
root,
338+
[0, 1, 2].map((workerId) => ({
339+
workerId,
340+
startFrame: workerId,
341+
endFrame: workerId + 1,
342+
outputDir: join(root, `worker-${workerId}`),
343+
})),
344+
{ width: 320, height: 180, fps: { num: 30, den: 1 } },
345+
() => null,
346+
undefined,
347+
undefined,
348+
undefined,
349+
undefined,
350+
{
351+
verifyFirstSession: () => new Promise<void>((resolve) => (pass = resolve)),
352+
prepareSession: async (_session, worker) => {
353+
prepared.push(worker);
354+
},
355+
onSessionUnprepared: (workerId) => unprepared.push(workerId),
356+
},
357+
).catch(() => {});
358+
await vi.waitFor(() => expect(unprepared).toEqual([2]));
359+
expect(prepared.sort((a, b) => a.workerId - b.workerId)).toEqual([
360+
{ workerId: 0, workerCount: 3 },
361+
{ workerId: 1, workerCount: 3 },
362+
]);
363+
pass();
364+
await result;
365+
} finally {
366+
rmSync(root, { recursive: true, force: true });
367+
}
368+
});
369+
316370
it("a worker 0 that fails before its check does not leave the other workers waiting", async () => {
317371
const root = mkdtempSync(join(tmpdir(), "hf-first-session-dead-"));
318372
vi.doMock("./frameCapture.js", () => ({

‎packages/engine/src/services/parallelCoordinator.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -960,9 +960,11 @@ async function executeWorkerTask(
960960
onWorkerOperation?: (diagnostic: ParallelWorkerPhaseDiagnostic) => void,
961961
gate?: FirstSessionGate,
962962
onLoaded?: (session: CaptureSession) => Promise<void>,
963+
preparation?: SessionPreparation,
963964
): Promise<WorkerResult> {
964965
const startTime = Date.now();
965966
let framesCaptured = 0;
967+
let prepared = false;
966968

967969
if (!existsSync(task.outputDir)) mkdirSync(task.outputDir, { recursive: true });
968970

@@ -1029,6 +1031,8 @@ async function executeWorkerTask(
10291031
}
10301032
await initializeSession(activeSession);
10311033
await onLoaded?.(activeSession);
1034+
await preparation?.prepare(activeSession, task.workerId);
1035+
prepared = true;
10321036
if (gate) await (task.workerId === 0 ? gate.verify(activeSession) : gate.wait());
10331037
});
10341038
canvasDrawElement = activeSession.captureMode === "drawelement";
@@ -1065,6 +1069,7 @@ async function executeWorkerTask(
10651069
};
10661070
} catch (error) {
10671071
if (task.workerId === 0) gate?.fail(error);
1072+
if (!prepared) preparation?.missed(task.workerId);
10681073
const diagnostics = session ? selectWorkerDiagnostics(session.browserConsoleBuffer) : [];
10691074
const workerDiagnostic: CaptureWorkerDiagnostic = {
10701075
workerId: task.workerId,
@@ -1141,6 +1146,21 @@ export interface ParallelCaptureHooks {
11411146
onWorkerOperation?: (diagnostic: ParallelWorkerPhaseDiagnostic) => void;
11421147
/** Worker 0 runs this on its initialised session; the other workers wait for it. A rejection fails the pool. */
11431148
verifyFirstSession?: (session: CaptureSession) => Promise<void>;
1149+
/**
1150+
* Every worker runs this on its initialised session, before the first-session check. `workerCount` is how many
1151+
* workers the pool runs once memory has capped it. A rejection fails that worker.
1152+
*/
1153+
prepareSession?: (
1154+
session: CaptureSession,
1155+
worker: { workerId: number; workerCount: number },
1156+
) => Promise<void>;
1157+
/** A worker failed before it finished `prepareSession`, so its share will not arrive. */
1158+
onSessionUnprepared?: (workerId: number) => void;
1159+
}
1160+
1161+
interface SessionPreparation {
1162+
prepare: (session: CaptureSession, workerId: number) => Promise<void>;
1163+
missed: (workerId: number) => void;
11441164
}
11451165

11461166
interface FirstSessionGate {
@@ -1319,6 +1339,12 @@ export async function executeParallelCapture(
13191339
});
13201340
const onFailure = failureHandler.onFailure;
13211341
const gate = hooks?.verifyFirstSession && createFirstSessionGate(hooks.verifyFirstSession);
1342+
const prepareSession = hooks?.prepareSession;
1343+
const preparation: SessionPreparation | undefined = prepareSession && {
1344+
prepare: (session, workerId) =>
1345+
prepareSession(session, { workerId, workerCount: tasks.length }),
1346+
missed: (workerId) => hooks?.onSessionUnprepared?.(workerId),
1347+
};
13221348
const collected: CapturePerfSummary[] = [];
13231349
const results = await launchWithinMemory(tasks, (task, onLoaded) =>
13241350
executeWorkerTask(
@@ -1336,6 +1362,7 @@ export async function executeParallelCapture(
13361362
hooks?.onWorkerOperation,
13371363
gate,
13381364
onLoaded,
1365+
preparation,
13391366
).then((result) =>
13401367
result.perf ? { ...result, perf: retainCapturePerf(collected, result.perf) } : result,
13411368
),

‎packages/engine/src/services/videoFrameInjector-shownBoxes.browser.test.ts‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,12 @@ import { spawnSync } from "node:child_process";
22
import { afterAll, beforeAll, describe, expect, it } from "vitest";
33
import type { Browser, Page } from "puppeteer-core";
44
import { resolveHeadlessShellPath } from "./browserManager.js";
5-
import { measureVideoShownBoxRanges, measureVideoShownBoxes } from "./videoFrameInjector.js";
5+
import {
6+
measureVideoShownBoxPart,
7+
measureVideoShownBoxRanges,
8+
measureVideoShownBoxes,
9+
mergeVideoShownBoxParts,
10+
} from "./videoFrameInjector.js";
611
import { closeTestChrome, launchTestChrome } from "./__fixtures__/loopback.js";
712

813
const chromePath = resolveHeadlessShellPath();
@@ -61,6 +66,54 @@ describe.skipIf(!hasBrowser)("measureVideoShownBoxes in Chrome", () => {
6166
await page.close();
6267
});
6368

69+
it("shares of the frames measured on separate pages merge to what one pass measures", async () => {
70+
const ids = ["zoom", "late", "graded", "lane-clip", "natural", "missing"];
71+
const times = [0, 0.25, 0.5, 1];
72+
const whole = await open(page1, 2);
73+
const first = await open(page1, 2);
74+
const second = await open(page1, 2);
75+
const parts = await Promise.all([
76+
// `late` is never laid out in this share, which must not drop the box the other share saw
77+
measureVideoShownBoxPart(first, ids, [0, 0.25]),
78+
measureVideoShownBoxPart(second, ids, [0.5, 1]),
79+
]);
80+
expect(mergeVideoShownBoxParts(parts)).toEqual(await measureVideoShownBoxes(whole, ids, times));
81+
expect(mergeVideoShownBoxParts(parts).get("late")).toEqual({ width: 640, height: 360 });
82+
await Promise.all([whole, first, second].map((page) => page.close()));
83+
});
84+
85+
it("a video one share sees at full size keeps full size, whatever box another share measured", async () => {
86+
// `#zoom` is laid out normally until t=0.5, then switches to `object-fit: none`.
87+
const html = page1.replace(
88+
'document.getElementById("late").style.display',
89+
'document.getElementById("zoom").style.objectFit = t >= 0.5 ? "none" : "";\n document.getElementById("late").style.display',
90+
);
91+
const first = await open(html, 1);
92+
const second = await open(html, 1);
93+
const parts = await Promise.all([
94+
measureVideoShownBoxPart(first, ["zoom", "late"], [0, 0.25]),
95+
measureVideoShownBoxPart(second, ["zoom", "late"], [0.5, 1]),
96+
]);
97+
expect(Object.fromEntries(mergeVideoShownBoxParts(parts))).toEqual({
98+
late: { width: 320, height: 180 },
99+
});
100+
await Promise.all([first, second].map((page) => page.close()));
101+
});
102+
103+
it("a canvas seen in any share keeps every video full size", async () => {
104+
const plain = await open(page1, 1);
105+
const withCanvas = await open(
106+
page1.replace("<script>", '<canvas width="10" height="10"></canvas><script>'),
107+
1,
108+
);
109+
const parts = await Promise.all([
110+
measureVideoShownBoxPart(plain, ["zoom"], [0]),
111+
measureVideoShownBoxPart(withCanvas, ["zoom"], [1]),
112+
]);
113+
expect(mergeVideoShownBoxParts(parts).size).toBe(0);
114+
await Promise.all([plain, withCanvas].map((page) => page.close()));
115+
});
116+
64117
it("keeps every video full size when the page has a canvas that could sample it", async () => {
65118
const page = await open(
66119
page1.replace("<script>", '<canvas width="10" height="10"></canvas><script>'),

‎packages/engine/src/services/videoFrameInjector.ts‎

Lines changed: 78 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -382,8 +382,71 @@ export async function measureVideoShownBoxRanges(
382382
videoIds: readonly string[],
383383
times: readonly number[],
384384
): Promise<Map<string, ShownBoxRange>> {
385-
if (videoIds.length === 0 || times.length === 0) return new Map();
386-
const boxes = await page.evaluate(
385+
const seen = await seekAndMeasureVideoBoxes(page, videoIds, times);
386+
if (seen.everyFullSize) return new Map();
387+
const fullSize = new Set(seen.fullSize);
388+
return new Map(
389+
seen.boxes
390+
.filter(([id, box]) => !fullSize.has(id) && box.largest.width > 0 && box.largest.height > 0)
391+
.map(([id, box]) => [id, { largest: box.largest, smallest: box.smallest ?? box.largest }]),
392+
);
393+
}
394+
395+
/** What one pass over some of a render's frames saw; `mergeVideoShownBoxParts` joins the passes. */
396+
export interface ShownBoxPart {
397+
/** Each video's largest laid-out box over these frames, zero when it was never laid out. */
398+
largest: [string, ShownBox][];
399+
/** Videos that keep their full size. */
400+
fullSize: string[];
401+
/** A canvas could sample any video (or the page cannot be seeked), so every video keeps full size. */
402+
everyFullSize: boolean;
403+
}
404+
405+
/** As `measureVideoShownBoxes` for a share of the frames, so several pages can split one pass. */
406+
export async function measureVideoShownBoxPart(
407+
page: Page,
408+
videoIds: readonly string[],
409+
times: readonly number[],
410+
): Promise<ShownBoxPart> {
411+
const seen = await seekAndMeasureVideoBoxes(page, videoIds, times);
412+
return {
413+
largest: seen.boxes.map(([id, box]) => [id, box.largest]),
414+
fullSize: seen.fullSize,
415+
everyFullSize: seen.everyFullSize,
416+
};
417+
}
418+
419+
/** The boxes one pass over all the parts' frames would have measured. */
420+
export function mergeVideoShownBoxParts(parts: readonly ShownBoxPart[]): Map<string, ShownBox> {
421+
const merged = new Map<string, ShownBox>();
422+
if (parts.some((part) => part.everyFullSize)) return merged;
423+
const fullSize = new Set(parts.flatMap((part) => part.fullSize));
424+
for (const [id, box] of parts.flatMap((part) => part.largest)) {
425+
if (fullSize.has(id)) continue;
426+
const largest = merged.get(id) ?? { width: 0, height: 0 };
427+
largest.width = Math.max(largest.width, box.width);
428+
largest.height = Math.max(largest.height, box.height);
429+
merged.set(id, largest);
430+
}
431+
for (const [id, box] of merged) if (box.width <= 0 || box.height <= 0) merged.delete(id);
432+
return merged;
433+
}
434+
435+
interface SeenVideoBoxes {
436+
boxes: [string, { largest: ShownBox; smallest: ShownBox | null }][];
437+
fullSize: string[];
438+
everyFullSize: boolean;
439+
}
440+
441+
async function seekAndMeasureVideoBoxes(
442+
page: Page,
443+
videoIds: readonly string[],
444+
times: readonly number[],
445+
): Promise<SeenVideoBoxes> {
446+
if (videoIds.length === 0 || times.length === 0) {
447+
return { boxes: [], fullSize: [], everyFullSize: false };
448+
}
449+
return page.evaluate(
387450
async (
388451
ids: string[],
389452
seekTimes: number[],
@@ -393,7 +456,8 @@ export async function measureVideoShownBoxRanges(
393456
groupTag: string,
394457
) => {
395458
const hf = (window as Window & { __hf?: { seek?: (t: number) => void } }).__hf;
396-
if (typeof hf?.seek !== "function") return [];
459+
const everyFullSize = { boxes: [], fullSize: [], everyFullSize: true };
460+
if (typeof hf?.seek !== "function") return everyFullSize;
397461
const waitForSeek = (window as Window & { __hfWaitForSeekCompletion?: () => Promise<void> })
398462
.__hfWaitForSeekCompletion;
399463
const largest = new Map<string, ShownBox>();
@@ -443,15 +507,19 @@ export async function measureVideoShownBoxRanges(
443507
hf.seek(t);
444508
await waitForSeek?.();
445509
// A canvas could sample any video, so every video keeps full size.
446-
if (pageHasCanvas()) return [];
510+
if (pageHasCanvas()) return everyFullSize;
447511
for (const id of ids) measure(id);
448512
}
449-
return Array.from(largest)
450-
.filter(([id, box]) => !fullSize.has(id) && box.width > 0 && box.height > 0)
451-
.map(([id, box]): [string, { largest: ShownBox; smallest: ShownBox }] => [
452-
id,
453-
{ largest: box, smallest: smallest.get(id) ?? box },
454-
]);
513+
return {
514+
boxes: Array.from(largest).map(
515+
([id, box]): [string, { largest: ShownBox; smallest: ShownBox | null }] => [
516+
id,
517+
{ largest: box, smallest: smallest.get(id) ?? null },
518+
],
519+
),
520+
fullSize: Array.from(fullSize),
521+
everyFullSize: false,
522+
};
455523
},
456524
[...videoIds],
457525
[...times],
@@ -460,7 +528,6 @@ export async function measureVideoShownBoxRanges(
460528
HF_COLOR_GROUP_ATTR,
461529
HF_COLOR_GROUP_TAG,
462530
);
463-
return new Map(boxes);
464531
}
465532

466533
/**

0 commit comments

Comments
 (0)