Skip to content
329 changes: 329 additions & 0 deletions packages/core/src/runtime/mediaProxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ function isProxied(el: HTMLMediaElement): boolean {
const settle = () => new Promise((resolveSettle) => setTimeout(resolveSettle, 0));

const STILL = "data:image/jpeg;base64,c3RpbGw=";
/** The server's answer for a still, and the poster a sealed frame shows from it. */
const jpegStill = () => new Response("jpeg", { headers: { "Content-Type": "image/jpeg" } });
const JPEG_STILL = "data:image/jpeg;base64,anBlZw==";
/** The element shows a frame, and a 2D canvas can draw it (jsdom has none). */
function showingFrame(el: HTMLVideoElement) {
Object.defineProperty(el, "readyState", { configurable: true, value: 4 });
Expand Down Expand Up @@ -721,6 +724,232 @@ describe("waiting for the proxy copy", () => {
expect(active.hasAttribute("poster")).toBe(false);
});

describe("the still a copy waits behind", () => {
const atPlayhead = (el: HTMLVideoElement) =>
syncRuntimeMedia({
clips: [
{
el,
start: 0,
mediaStart: 4,
duration: 10,
end: 10,
volume: null,
playbackRate: 1,
loop: false,
sourceDuration: null,
},
],
timeSeconds: 1,
playing: false,
playbackRate: 1,
});
/** The still answers at once; the copy is made after the first ask and served from then on. */
const routeServedLater = () => {
let served = false;
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL) => {
if (new URL(String(input), document.baseURI).searchParams.has("hf-proxy-still"))
return jpegStill();
if (served) return new Response("x", { status: 206 });
served = true;
return new Response(null, { status: 202, headers: { "Retry-After": "2" } });
}),
);
};

for (const origin of ["null", "http://localhost:3000"]) {
// fails without the fix: the copy swap kept the runtime's still as the page's own poster and put it back after
// the still was dropped, so the clip kept a stale still (open) or its fetched still (sealed) as its poster.
it(`never puts its still back once dropped, when the copy draws only after seeking (origin ${origin})`, async () => {
vi.useFakeTimers();
vi.stubGlobal("origin", origin);
routeServedLater();
const el = createVideo("/active.mp4");
showingFrame(el);
atPlayhead(el);

swapToProxy(el, HEVC_ENTRY, "proactive");
await vi.advanceTimersByTimeAsync(10);
expect(el.getAttribute("poster")).toMatch(
origin === "null" ? /^data:image\/jpeg;base64,/ : /hf-proxy-still=5\.0/,
);
await vi.advanceTimersByTimeAsync(10_000);
Object.defineProperty(el, "seeking", { configurable: true, value: true });
el.dispatchEvent(new Event("loadeddata"));
await vi.advanceTimersByTimeAsync(0);
Object.defineProperty(el, "seeking", { configurable: true, value: false });
el.dispatchEvent(new Event("seeked"));
await vi.advanceTimersByTimeAsync(0);

expect(el.hasAttribute("poster")).toBe(false);
});
}

// fails without the fix: the copy landing removed whatever poster the clip had, the page's own included.
it("keeps a poster the page sets while the copy is made", async () => {
vi.useFakeTimers();
routeServedLater();
const el = createVideo("/active.mp4");
atPlayhead(el);

swapToProxy(el, HEVC_ENTRY, "proactive");
await vi.advanceTimersByTimeAsync(0);
el.setAttribute("poster", "/cover.jpg");
await vi.advanceTimersByTimeAsync(10_000);
el.dispatchEvent(new Event("loadeddata"));
await vi.advanceTimersByTimeAsync(0);
expect(el.getAttribute("poster")).toBe("/cover.jpg");
});

const servedCopy = async (origin: string) => {
vi.useFakeTimers();
vi.stubGlobal("origin", origin);
routeServedLater();
const el = createVideo("/active.mp4");
atPlayhead(el);
swapToProxy(el, HEVC_ENTRY, "proactive");
await vi.advanceTimersByTimeAsync(10);
expect(el.hasAttribute("poster")).toBe(true);
await vi.advanceTimersByTimeAsync(10_000);
expect(el.getAttribute("src")).toContain("hf-proxy=");
return el;
};

for (const origin of ["null", "http://localhost:3000"]) {
// fails without the fix: only the copy drawing or failing dropped the still, so a clip that left the page
// after its copy was served kept the still (a sealed frame's full image) as its poster.
it(`drops its still when the clip leaves the page after its copy is served (origin ${origin})`, async () => {
const el = await servedCopy(origin);
el.remove();
await vi.advanceTimersByTimeAsync(0);
expect(el.hasAttribute("poster")).toBe(false);
});

it(`drops its still when the clip gets another file before its copy draws (origin ${origin})`, async () => {
const el = await servedCopy(origin);
el.dispatchEvent(new Event("emptied"));
await vi.advanceTimersByTimeAsync(0);
expect(el.hasAttribute("poster")).toBe(true);

el.setAttribute("src", "/other.mp4");
el.dispatchEvent(new Event("emptied"));
await vi.advanceTimersByTimeAsync(0);
expect(el.hasAttribute("poster")).toBe(false);
});
}

it("keeps a poster the page sets when the clip leaves the page before its copy draws", async () => {
const el = await servedCopy("null");
el.setAttribute("poster", "/cover.jpg");
el.remove();
await vi.advanceTimersByTimeAsync(0);
expect(el.getAttribute("poster")).toBe("/cover.jpg");
});
});

describe("in a sealed frame", () => {
const atPlayhead = (el: HTMLVideoElement) =>
syncRuntimeMedia({
clips: [
{
el,
start: 0,
mediaStart: 4,
duration: 10,
end: 10,
volume: null,
playbackRate: 1,
loop: false,
sourceDuration: null,
},
],
timeSeconds: 1,
playing: false,
playbackRate: 1,
});
/** The proxy route: the still answers when `stillAnswer` settles, the copy is still being made. */
const routeWithStill = (stillAnswer: Promise<Response>) => {
const route = vi.fn(async (input: RequestInfo | URL) =>
new URL(String(input), document.baseURI).searchParams.has("hf-proxy-still")
? stillAnswer
: new Response(null, { status: 202, headers: { "Retry-After": "2" } }),
);
vi.stubGlobal("fetch", route);
return route;
};
const stillAsked = (route: ReturnType<typeof routeWithStill>) =>
route.mock.calls
.map(([input]) => new URL(String(input), document.baseURI))
.find((url) => url.searchParams.has("hf-proxy-still"));

// fails without the fix: the still's URL became the poster, and the browser held that load back in a sealed frame
// for as long as the copy took, so the clip showed nothing where its frame had been.
it("fetches the still and shows it from the answer, then drops it with the copy", async () => {
vi.useFakeTimers();
vi.stubGlobal("origin", "null");
const route = routeWithStill(Promise.resolve(jpegStill()));
const el = createVideo("/active.mp4");
atPlayhead(el);

swapToProxy(el, HEVC_ENTRY, "proactive");
await vi.advanceTimersByTimeAsync(10);
expect(stillAsked(route)?.searchParams.get("hf-proxy-still")).toBe("5.0");
expect(el.getAttribute("poster")).toBe(JPEG_STILL);

route.mockImplementation(async () => new Response("x", { status: 206 }));
await vi.advanceTimersByTimeAsync(10_000);
el.dispatchEvent(new Event("loadeddata"));
await vi.advanceTimersByTimeAsync(0);
expect(el.hasAttribute("poster")).toBe(false);
});

// fails without the fix: the answer replaced a poster the page set while the still was being fetched, and the
// copy landing then removed the page's poster.
it("keeps a poster the page sets while the still is fetched", async () => {
vi.useFakeTimers();
vi.stubGlobal("origin", "null");
let answerStill: (res: Response) => void = () => {};
const route = routeWithStill(new Promise((answer) => (answerStill = answer)));
const el = createVideo("/active.mp4");
atPlayhead(el);

swapToProxy(el, HEVC_ENTRY, "proactive");
await vi.advanceTimersByTimeAsync(0);
el.setAttribute("poster", "/cover.jpg");
answerStill(jpegStill());
await vi.advanceTimersByTimeAsync(10);
expect(el.getAttribute("poster")).toBe("/cover.jpg");

route.mockImplementation(async () => new Response("x", { status: 206 }));
await vi.advanceTimersByTimeAsync(10_000);
el.dispatchEvent(new Event("loadeddata"));
await vi.advanceTimersByTimeAsync(0);
expect(el.getAttribute("poster")).toBe("/cover.jpg");
});

it("never shows a still that answers after its copy has landed", async () => {
vi.useFakeTimers();
vi.stubGlobal("origin", "null");
let answerStill: (res: Response) => void = () => {};
const route = routeWithStill(new Promise((answer) => (answerStill = answer)));
const el = createVideo("/active.mp4");
atPlayhead(el);

swapToProxy(el, HEVC_ENTRY, "proactive");
await vi.advanceTimersByTimeAsync(0);
route.mockImplementation(async () => new Response("x", { status: 206 }));
await vi.advanceTimersByTimeAsync(10_000);
el.dispatchEvent(new Event("loadeddata"));
await vi.advanceTimersByTimeAsync(0);

answerStill(jpegStill());
await vi.advanceTimersByTimeAsync(10);
expect(el.hasAttribute("poster")).toBe(false);
});
});

describe("on a hidden capture page", () => {
const clipAt = (el: HTMLVideoElement) =>
syncRuntimeMedia({
Expand Down Expand Up @@ -1327,6 +1556,106 @@ describe("preview quality: lighter copies of heavy files", () => {
}
const making = () => new Response(null, { status: 202, headers: { "Retry-After": "2" } });

for (const origin of ["null", "http://localhost:3000"]) {
// A held clip whose newer copy started with no src gets its file back, not an empty src, so its file's first
// frame drops the still.
it(`drops its still once its file draws again, after a copy that started with no src (origin ${origin})`, async () => {
vi.useFakeTimers();
vi.stubGlobal("origin", origin);
let made = false;
vi.stubGlobal(
"fetch",
vi.fn(async (url: string) => {
if (String(url).includes("hf-proxy-still")) return jpegStill();
if (!String(url).includes("hf-proxy")) return new Response("x", { status: 206 });
return made ? new Response("x", { status: 206 }) : making();
}),
);
// Heavy below Full, not oversized at Full: Full puts the original back.
const staged = await stage({ "/video.mp4": MID });
const el = staged.video();
const media = await import("./media");
media.syncRuntimeMedia({
getCompositionDuration: () => 0,
clips: [
{
el,
start: 0,
mediaStart: 4,
duration: 10,
end: 10,
volume: null,
playbackRate: 1,
loop: false,
sourceDuration: null,
},
],
timeSeconds: 1,
playing: false,
playbackRate: 1,
});
staged.setPreviewQuality(0.5);
await vi.advanceTimersByTimeAsync(0);
// The level drops again while the clip is held: the new copy's job starts with no src on the clip.
staged.setPreviewQuality(0.25);
await vi.advanceTimersByTimeAsync(10);
expect(el.hasAttribute("src")).toBe(false);
expect(el.hasAttribute("poster")).toBe(true);

made = true;
await vi.advanceTimersByTimeAsync(10_000);
expect(params(el).get("hf-proxy-light")).toBe("1");
staged.setPreviewQuality(1);
await vi.advanceTimersByTimeAsync(0);
expect(el.getAttribute("src")).toBe("/video.mp4");
el.dispatchEvent(new Event("loadeddata"));
await vi.advanceTimersByTimeAsync(0);

expect(el.hasAttribute("poster")).toBe(false);
});

it(`drops its still when the clip leaves the page while its copy is made (origin ${origin})`, async () => {
vi.useFakeTimers();
vi.stubGlobal("origin", origin);
vi.stubGlobal(
"fetch",
vi.fn(async (url: string) =>
String(url).includes("hf-proxy-still") ? jpegStill() : making(),
),
);
const staged = await stage({ "/video.mp4": HEAVY });
const el = staged.video();
const media = await import("./media");
media.syncRuntimeMedia({
getCompositionDuration: () => 0,
clips: [
{
el,
start: 0,
mediaStart: 4,
duration: 10,
end: 10,
volume: null,
playbackRate: 1,
loop: false,
sourceDuration: null,
},
],
timeSeconds: 1,
playing: false,
playbackRate: 1,
});
staged.maybeProxyProactively(el);
await vi.advanceTimersByTimeAsync(10);
expect(el.hasAttribute("poster")).toBe(true);

el.remove();
await vi.advanceTimersByTimeAsync(10_000);

expect(el.hasAttribute("poster")).toBe(false);
});
}

it("never loads the file while its copy is made, and plays a copy at the shown box", async () => {
let made = false;
const { el, proxySrc } = await waitingForItsCopy(() =>
Expand Down
Loading
Loading