commit 5b754bcb78d88121023bbdd88fd7a34302daadcf
parent c817bf8cf24c23aaf14438f7fff6f81b96da0374
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 19 Nov 2026 16:41:07 -0500
export: e2e for clipping your own copy in the browser
ffmpeg makes the files in the test (keyframes every 2.0 s). WebM and MP4
(H.264 with B-frames, AAC) clips are downloaded and checked with ffprobe:
the source's codecs, a key first frame, keyframe-to-out length, audio and
video starting within one audio frame. The offset case lands on a
keyframe. Cancel under slow reads hands nothing over; a WAV gets the
refusal sentence. From the pick on, nothing but blob: URLs and, after
"Clip my copy", same-origin GETs of /_next/ chunks with no body; the
library's chunk is not among the first load's scripts; no service worker
is registered. The missing-source fixture takes custom cues.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
2 files changed, 331 insertions(+), 4 deletions(-)
diff --git a/export/e2e/fixtures/missing-source.ts b/export/e2e/fixtures/missing-source.ts
@@ -65,7 +65,7 @@ function summary(v: Vid) {
};
}
-function record(v: Vid) {
+function record(v: Vid, cues: ReadonlyArray<{ start: number; end: number; text: string }> = CUES) {
const base = summary(v);
const { state: _s, stateSince: _d, isDeleted: _i, isUnlisted: _u, date: _dt, ...rest } = base as Record<string, unknown>;
const st = v.record ? v.record.state : v.state === "maybe_missing" ? undefined : v.state;
@@ -77,7 +77,7 @@ function record(v: Vid) {
tags: [],
...(st ? { state: st } : {}),
...(st && since ? { stateSince: since } : {}),
- cues: CUES,
+ cues,
};
}
@@ -91,7 +91,7 @@ async function fulfillJson(route: Route, body: unknown) {
// visitor's cached record against a slow network).
export async function installMissingSourceRoutes(
page: Page,
- opts: { summariesDelayMs?: number } = {},
+ opts: { summariesDelayMs?: number; cues?: ReadonlyArray<{ start: number; end: number; text: string }> } = {},
): Promise<{ platformHits: string[] }> {
const platformHits: string[] = [];
await page.route(/youtube\.com|youtube-nocookie\.com|ytimg\.com|googlevideo\.com/, async (route) => {
@@ -125,7 +125,7 @@ export async function installMissingSourceRoutes(
slugToPage: Object.fromEntries(VIDS.map((v) => [v.id, 0])),
}),
);
- await page.route(/\/transcripts\/[^/]+\/page-\d+\.json$/, (route) => fulfillJson(route, VIDS.map(record)));
+ await page.route(/\/transcripts\/[^/]+\/page-\d+\.json$/, (route) => fulfillJson(route, VIDS.map((v) => record(v, opts.cues))));
await page.route("**/subs/manifest.json", (route) =>
fulfillJson(route, { version: 4, channels: [], totalCount: 0, liveChatTotalCount: 0, generatedAt: new Date().toISOString() }),
);
diff --git a/export/e2e/local-clip.spec.ts b/export/e2e/local-clip.spec.ts
@@ -0,0 +1,327 @@
+import { expect, test, type Page, type Request } from "@playwright/test";
+import { execFileSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { expectModalOpen } from "./helpers";
+import { installMissingSourceRoutes, makeWav, slugOf } from "./fixtures/missing-source";
+
+// A CLIP OF THE VISITOR'S OWN COPY, CUT IN THE BROWSER (lane browser-clip).
+// A real media file, made here by ffmpeg (keyframes every 2.0 s), is picked
+// as the visitor's copy; the Clip in / Clip out marks are set from cue clicks;
+// "Clip my copy" says where the clip really starts BEFORE saving; the
+// download is checked with ffprobe — the source's codecs (a stream copy, not
+// a re-encode), the length from the keyframe to the out mark, and audio and
+// video starting within one audio frame of each other.
+//
+// The file never leaves the browser: from the pick on, the page asks for
+// nothing but blob: URLs and, once a clip is asked for, the clipper's own
+// script chunk (a same-origin GET with no body) — and that chunk is not part
+// of the first load. The dev server registers no service worker, which is
+// asserted, so page.on("request") sees every request the page makes.
+
+function has(cmd: string): boolean {
+ try {
+ execFileSync(cmd, ["-version"], { stdio: "ignore" });
+ return true;
+ } catch {
+ return false;
+ }
+}
+const FFMPEG = has("ffmpeg") && has("ffprobe");
+
+const SLUG = slugOf("synthmem001");
+const TITLE_BASE = "Synth-members-stream";
+// Cues over the whole 12 s (the fixture's default four end at 6 s).
+const CUES = [
+ { start: 0, end: 2, text: "clip line zero" },
+ { start: 2, end: 4, text: "clip line two" },
+ { start: 4, end: 5, text: "clip line four" },
+ { start: 5, end: 7, text: "clip line five" },
+ { start: 7, end: 9, text: "clip line seven" },
+ { start: 9, end: 11, text: "clip line nine" },
+ { start: 11, end: 20, text: "clip line eleven" },
+];
+
+const CODECS = {
+ webm: {
+ args: ["-c:v", "libvpx-vp9", "-g", "50", "-keyint_min", "50", "-deadline", "realtime", "-cpu-used", "8", "-b:v", "200k", "-c:a", "libopus", "-b:a", "48k"],
+ mime: "video/webm",
+ },
+ mp4: {
+ args: ["-c:v", "libx264", "-profile:v", "main", "-bf", "2", "-g", "50", "-keyint_min", "50", "-sc_threshold", "0", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "64k"],
+ mime: "video/mp4",
+ },
+} as const;
+
+function makeMedia(path: string, kind: keyof typeof CODECS, opts: { seconds?: number; heavy?: boolean } = {}): void {
+ const seconds = opts.seconds ?? 12;
+ const video = opts.heavy
+ ? ["-f", "lavfi", "-i", `testsrc2=size=320x180:rate=25:duration=${seconds}`]
+ : ["-f", "lavfi", "-i", `testsrc2=size=160x90:rate=25:duration=${seconds}`];
+ // Noise makes a file too big to copy in a blink (the cancel case).
+ const heavy = opts.heavy ? ["-vf", "noise=alls=80:allf=t", "-b:v", "4M", "-minrate", "4M", "-maxrate", "4M"] : [];
+ execFileSync("ffmpeg", [
+ "-v", "error", "-y",
+ ...video,
+ "-f", "lavfi", "-i", `sine=frequency=440:sample_rate=48000:duration=${seconds}`,
+ ...CODECS[kind].args, ...heavy, "-shortest", path,
+ ]);
+}
+
+type Probe = { streams: { codec_type: string; codec_name: string; start_time: string }[]; format: { duration: string } };
+function ffprobe(path: string): Probe {
+ return JSON.parse(
+ execFileSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_type,codec_name,start_time:format=duration", "-of", "json", path], {
+ encoding: "utf8",
+ }),
+ );
+}
+function firstVideoFrameIsKey(path: string): boolean {
+ const out = execFileSync(
+ "ffprobe",
+ ["-v", "error", "-select_streams", "v:0", "-show_entries", "frame=key_frame", "-read_intervals", "%+#1", "-of", "csv=p=0", path],
+ { encoding: "utf8" },
+ );
+ return out.trim().split("\n")[0]?.trim() === "1";
+}
+
+const video = (page: Page) => page.locator('video[aria-label="Your copy"]');
+const clipGroup = (page: Page) => page.getByRole("group", { name: "Clip of your copy" });
+
+// Playback is the browser's; what is tested is the copy. play() starts
+// nothing, so every currentTime is exactly where the page put it.
+async function stillPlayback(page: Page) {
+ await page.addInitScript(() => {
+ HTMLMediaElement.prototype.play = function () {
+ return Promise.resolve();
+ };
+ });
+}
+
+async function cue(page: Page, text: string) {
+ await page.locator("li", { hasText: text }).getByRole("button").click();
+}
+
+async function markClip(page: Page, inText: string, outText: string) {
+ await cue(page, inText);
+ await page.getByRole("button", { name: "Mark clip start at current time" }).click();
+ await cue(page, outText);
+ await page.getByRole("button", { name: "Mark clip end at current time" }).click();
+}
+
+// Every request from `from` on: what it was, and whether the clip path may make it.
+type Seen = { url: string; method: string; post: string | null; type: string };
+function seen(r: Request): Seen {
+ return { url: r.url(), method: r.method(), post: r.postData(), type: r.resourceType() };
+}
+
+async function open(page: Page) {
+ await installMissingSourceRoutes(page, { cues: CUES });
+ await stillPlayback(page);
+ await page.goto(`/?v=${SLUG}`);
+ await expectModalOpen(page);
+ // The page has settled: the panel (it waits for the summaries) and the cues
+ // (the transcript record) are in.
+ await expect(page.getByTestId("source-missing").getByRole("button", { name: "Play your own copy" })).toBeVisible();
+ await expect(page.locator("li", { hasText: "clip line zero" })).toBeVisible();
+}
+
+async function pick(page: Page, file: { name: string; mimeType: string; buffer: Buffer }) {
+ await expect(page.getByRole("button", { name: "Play your own copy" })).toBeVisible();
+ await page.getByTestId("local-file-input").setInputFiles(file);
+ await expect(video(page)).toHaveAttribute("src", /^blob:/);
+}
+
+async function noServiceWorker(page: Page) {
+ const sw = await page.evaluate(async () => ({
+ controlled: navigator.serviceWorker?.controller != null,
+ registrations: (await navigator.serviceWorker?.getRegistrations?.())?.length ?? 0,
+ }));
+ expect(sw).toEqual({ controlled: false, registrations: 0 });
+}
+
+test.describe("export — clip your own copy in the browser", () => {
+ test.skip(!FFMPEG, "ffmpeg/ffprobe not on PATH");
+
+ test("WebM: says where the clip starts, saves a stream copy in step, and sends the file nowhere", async ({ page }, info) => {
+ const src = info.outputPath("synth-copy.webm");
+ makeMedia(src, "webm");
+ const FILE = { name: "my-synth-copy.webm", mimeType: CODECS.webm.mime, buffer: readFileSync(src) };
+
+ // The first load: every request, and every script's text.
+ const firstLoad: Seen[] = [];
+ const firstLoadScripts: Promise<string>[] = [];
+ let phase: "load" | "picked" | "clip" = "load";
+ const afterPick: Seen[] = [];
+ const afterClip: Seen[] = [];
+ const clipScripts: Promise<{ url: string; body: string }>[] = [];
+ page.on("request", (r) => {
+ if (phase === "load") firstLoad.push(seen(r));
+ else if (!r.url().startsWith("blob:")) (phase === "picked" ? afterPick : afterClip).push(seen(r));
+ });
+ page.on("response", (resp) => {
+ if (resp.request().resourceType() !== "script") return;
+ const body = resp.text().catch(() => "");
+ if (phase === "load") firstLoadScripts.push(body);
+ else clipScripts.push(body.then((b) => ({ url: resp.url(), body: b })));
+ });
+
+ await open(page);
+ phase = "picked";
+ await pick(page, FILE);
+ await markClip(page, "clip line five", "clip line nine");
+ // Nothing went out between the pick and asking for a clip.
+ expect(afterPick).toEqual([]);
+
+ phase = "clip";
+ await page.getByRole("button", { name: "Clip my copy" }).click();
+ const group = clipGroup(page);
+ await expect(group).toBeVisible();
+ // BEFORE saving: the range, the real start, the name.
+ await expect(group.getByTestId("local-clip-start")).toHaveText("Starts 1.0 s earlier, at the nearest keyframe (0:00:04.0).");
+ await expect(group).toContainText("From 0:00:05.0 to 0:00:09.0.");
+ await expect(group.getByTestId("local-clip-name")).toHaveText(`${TITLE_BASE}_00h00m04s-00h00m09s.webm`);
+ await expect(group).toContainText("Clipping uses Mediabunny 1.45.3 (MPL-2.0)");
+
+ const download = page.waitForEvent("download");
+ await group.getByRole("button", { name: "Save clip" }).click();
+ const d = await download;
+ expect(d.suggestedFilename()).toBe(`${TITLE_BASE}_00h00m04s-00h00m09s.webm`);
+ const out = info.outputPath("clip.webm");
+ await d.saveAs(out);
+ await expect(group.getByTestId("local-clip-done")).toContainText(`Your browser is saving ${TITLE_BASE}_00h00m04s-00h00m09s.webm`);
+
+ // The clip: copied, from a key frame, 9.0 − 4.0 s long, audio and video in step.
+ const probe = ffprobe(out);
+ const v = probe.streams.find((s) => s.codec_type === "video")!;
+ const a = probe.streams.find((s) => s.codec_type === "audio")!;
+ expect([v.codec_name, a.codec_name]).toEqual(["vp9", "opus"]);
+ expect(firstVideoFrameIsKey(out)).toBe(true);
+ expect(Math.abs(Number(probe.format.duration) - 5)).toBeLessThan(0.12);
+ // One Opus frame is 20 ms.
+ expect(Math.abs(Number(v.start_time) - Number(a.start_time))).toBeLessThanOrEqual(0.0205);
+
+ // The network, from the pick on: only the clipper's own chunk(s), asked
+ // for after "Clip my copy", same-origin GETs with no body, none naming the file.
+ const origin = new URL(page.url()).origin;
+ expect(afterClip.length).toBeGreaterThan(0);
+ for (const r of afterClip) {
+ const u = new URL(r.url);
+ expect(r.method, r.url).toBe("GET");
+ expect(r.post, r.url).toBeNull();
+ expect(u.origin, r.url).toBe(origin);
+ expect(u.pathname.startsWith("/_next/"), r.url).toBe(true);
+ expect(r.url).not.toContain("my-synth-copy");
+ }
+ // The library arrived with the clip, not with the first load.
+ const engineChunks = (await Promise.all(clipScripts)).filter((s) => s.body.includes("Vanilagy and contributors"));
+ expect(engineChunks.length).toBeGreaterThan(0);
+ const firstUrls = new Set(firstLoad.map((r) => r.url));
+ for (const c of engineChunks) expect(firstUrls.has(c.url), c.url).toBe(false);
+ for (const body of await Promise.all(firstLoadScripts)) expect(body.includes("Vanilagy and contributors")).toBe(false);
+ await noServiceWorker(page);
+ });
+
+ test("an offset moves the marks onto the file's clock; on a keyframe the clip starts at the mark", async ({ page }, info) => {
+ const src = info.outputPath("synth-copy.webm");
+ makeMedia(src, "webm");
+ await open(page);
+ await pick(page, { name: "my-synth-copy.webm", mimeType: CODECS.webm.mime, buffer: readFileSync(src) });
+ await page.getByRole("button", { name: "Offset +1 second" }).click();
+ await markClip(page, "clip line five", "clip line nine");
+ await page.getByRole("button", { name: "Clip my copy" }).click();
+ const group = clipGroup(page);
+ // Cue 0:05 + 1 s = 6.0 s into the file, a keyframe.
+ await expect(group.getByTestId("local-clip-start")).toHaveText("Starts at your Clip in mark.");
+ await expect(group).toContainText("From 0:00:05.0 to 0:00:09.0, with your offset +1.00 s applied.");
+ await expect(group.getByTestId("local-clip-name")).toHaveText(`${TITLE_BASE}_00h00m05s-00h00m09s.webm`);
+ const download = page.waitForEvent("download");
+ await group.getByRole("button", { name: "Save clip" }).click();
+ const out = info.outputPath("clip.webm");
+ await (await download).saveAs(out);
+ const probe = ffprobe(out);
+ expect(Math.abs(Number(probe.format.duration) - 4)).toBeLessThan(0.12);
+ });
+
+ test("MP4 (H.264 with B-frames, AAC): a stream copy in step, whether or not this browser can play it", async ({ page }, info) => {
+ const src = info.outputPath("synth-copy.mp4");
+ makeMedia(src, "mp4");
+ await open(page);
+ await pick(page, { name: "my-synth-copy.mp4", mimeType: CODECS.mp4.mime, buffer: readFileSync(src) });
+ await markClip(page, "clip line five", "clip line nine");
+ await page.getByRole("button", { name: "Clip my copy" }).click();
+ const group = clipGroup(page);
+ await expect(group.getByTestId("local-clip-start")).toHaveText("Starts 1.0 s earlier, at the nearest keyframe (0:00:04.0).");
+ await expect(group.getByTestId("local-clip-name")).toHaveText(`${TITLE_BASE}_00h00m04s-00h00m09s.mp4`);
+ const download = page.waitForEvent("download");
+ await group.getByRole("button", { name: "Save clip" }).click();
+ const out = info.outputPath("clip.mp4");
+ await (await download).saveAs(out);
+ const probe = ffprobe(out);
+ const v = probe.streams.find((s) => s.codec_type === "video")!;
+ const a = probe.streams.find((s) => s.codec_type === "audio")!;
+ expect([v.codec_name, a.codec_name]).toEqual(["h264", "aac"]);
+ expect(firstVideoFrameIsKey(out)).toBe(true);
+ expect(Math.abs(Number(probe.format.duration) - 5)).toBeLessThan(0.12);
+ // One AAC frame is 1024 samples at 48 kHz, about 21.3 ms; start_time
+ // already carries the container's edit-list offsets.
+ expect(Math.abs(Number(v.start_time) - Number(a.start_time))).toBeLessThanOrEqual(0.0215);
+ });
+
+ test("cancel stops the copy and offers nothing as finished", async ({ page }, info) => {
+ const src = info.outputPath("synth-big.webm");
+ makeMedia(src, "webm", { seconds: 20, heavy: true });
+ // The file reads slowly here (100 ms per 64 KiB), so the copy is still
+ // running when Cancel is pressed.
+ await page.addInitScript(() => {
+ const orig = Blob.prototype.stream;
+ Blob.prototype.stream = function (this: Blob) {
+ const reader = orig.call(this).getReader();
+ return new ReadableStream({
+ async pull(controller) {
+ const { done, value } = await reader.read();
+ if (done) return controller.close();
+ await new Promise((r) => setTimeout(r, Math.ceil(value.byteLength / 65536) * 100));
+ controller.enqueue(value);
+ },
+ cancel(reason) {
+ return reader.cancel(reason);
+ },
+ });
+ } as typeof Blob.prototype.stream;
+ });
+ await open(page);
+ await pick(page, { name: "my-synth-big.webm", mimeType: CODECS.webm.mime, buffer: readFileSync(src) });
+ await markClip(page, "clip line two", "clip line eleven");
+ await page.getByRole("button", { name: "Clip my copy" }).click();
+ const group = clipGroup(page);
+ await expect(group.getByTestId("local-clip-start")).toBeVisible({ timeout: 30_000 });
+ let downloads = 0;
+ page.on("download", () => downloads++);
+ await group.getByRole("button", { name: "Save clip" }).click();
+ await expect(group.getByRole("progressbar", { name: "Saving clip" })).toBeVisible();
+ // Saving moves the focus to Cancel.
+ const cancel = group.getByRole("button", { name: "Cancel the clip" });
+ await expect(cancel).toBeFocused();
+ await cancel.click();
+ await expect(group.getByTestId("local-clip-cancelled")).toHaveText("Cancelled; nothing was saved.");
+ await page.waitForTimeout(1500);
+ expect(downloads).toBe(0);
+ await noServiceWorker(page);
+ });
+
+ test("a file it cannot copy gets a plain sentence", async ({ page }) => {
+ await open(page);
+ await pick(page, { name: "my-synth-copy.wav", mimeType: "audio/wav", buffer: makeWav(12) });
+ // Before any mark the control says what it needs.
+ await expect(page.getByRole("button", { name: "Mark Clip in and Clip out first" })).toBeDisabled();
+ await markClip(page, "clip line two", "clip line five");
+ await page.getByRole("button", { name: "Clip my copy" }).click();
+ await expect(clipGroup(page).getByTestId("local-clip-refusal")).toHaveText(
+ "This file can't be clipped here: clipping takes MP4, MOV, M4A, WebM or MKV.",
+ );
+ // Close gives the focus back to the control.
+ await clipGroup(page).getByRole("button", { name: "Close the clip" }).click();
+ await expect(clipGroup(page)).toHaveCount(0);
+ await expect(page.getByRole("button", { name: "Clip my copy" })).toBeFocused();
+ });
+});