commit 195d8681c0815d3dfee99d52122440e56e75b469
parent 730804e29a82c6ad91d229c88fafcca6dff8ea2a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 19 Nov 2026 18:07:56 -0500
Merge lane/browser-clip: "Clip my copy" cuts the visitor's own file in the browser
With a local copy playing on a video page, the Clip in and Clip out marks
make a downloadable clip in the browser by a stream copy (no re-encode),
through Mediabunny 1.45.3 (MPL-2.0, loaded on demand, noted in
export/THIRD-PARTY-NOTICES.md). The page says the real span before the save:
a start moved to a keyframe, or a start or end held by where the copy begins
or ends, and the file name follows the same times. The file is read in
slices and never leaves the browser. A clip too big for memory is saved
straight to disk where the browser can, and refused with a sentence where it
cannot; a cancel never leaves a partial file offered as finished.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
17 files changed, 3175 insertions(+), 8 deletions(-)
diff --git a/common/components/LocalClipPanel.tsx b/common/components/LocalClipPanel.tsx
@@ -0,0 +1,346 @@
+"use client";
+
+import { useEffect, useRef, useState, useSyncExternalStore } from "react";
+import { ScissorsIcon } from "lucide-react";
+import { ControlButton, usePlayer } from "./PlayerProvider";
+import { cancelledSentence, formatBytes, formatClock } from "../lib/localClip";
+import {
+ cancelLocalClip,
+ clipKey,
+ closeLocalClip,
+ getIdleLocalClipState,
+ getLocalClipState,
+ prepareLocalClip,
+ saveLocalClip,
+ subscribeLocalClip,
+ type ClipJobState,
+} from "../lib/localClipJob";
+
+// A CLIP OF THE VISITOR'S OWN COPY (lane browser-clip), in the "Your copy"
+// bar: the modal's Clip in / Clip out marks (cue clock, the visitor's offset
+// applied) cut from the picked file by a stream copy, in this browser. The
+// page says where the clip really starts — the keyframe at or before the in
+// mark — before anything is saved.
+//
+// Screen readers hear it through ONE live region that stays mounted while a
+// copy is playing (its text changes; the group's own lines are not live), so a
+// clip cancelled by closing the group is still said.
+//
+// Nothing in this file may reach the network or storage; LocalFilePicker.test.ts
+// reads this source too. The engine is loaded by lib/localClipJob.ts only when
+// the visitor opens this panel.
+
+export const CLIP_BUTTON = "Clip my copy";
+const CLIP_BUTTON_OFF = "Mark Clip in and Clip out first";
+const LIBRARY_VERSION = "1.45.3";
+const LIBRARY_SOURCE = `https://github.com/Vanilagy/mediabunny/tree/v${LIBRARY_VERSION}`;
+
+type Picker = (opts: {
+ suggestedName: string;
+ types: { description: string; accept: Record<string, string[]> }[];
+}) => Promise<{ createWritable: () => Promise<WritableStream> }>;
+
+function savePicker(): Picker | null {
+ if (typeof window === "undefined") return null;
+ const p = (window as unknown as { showSaveFilePicker?: unknown }).showSaveFilePicker;
+ return typeof p === "function" ? (p.bind(window) as Picker) : null;
+}
+
+const MIME_BY_EXT: Record<string, string> = {
+ ".mp4": "video/mp4",
+ ".m4a": "audio/mp4",
+ ".mov": "video/quicktime",
+ ".webm": "video/webm",
+ ".mkv": "video/x-matroska",
+ ".mka": "audio/x-matroska",
+};
+
+function extOf(name: string): string {
+ const i = name.lastIndexOf(".");
+ return i >= 0 ? name.slice(i) : "";
+}
+
+function doneSentence(job: Extract<ClipJobState, { phase: "done" }>): string {
+ return job.path === "disk"
+ ? `Saved ${job.name} (${formatBytes(job.bytes)}).`
+ : `Your browser is saving ${job.name} (${formatBytes(job.bytes)}).`;
+}
+
+// What the live region says for a state: the sentence that changed, never the
+// running percentage.
+function announcement(job: ClipJobState, canClip: boolean): string {
+ if (!canClip && job.phase !== "saving") return job.phase === "idle" ? "" : "Mark Clip in and Clip out first.";
+ switch (job.phase) {
+ case "idle":
+ return "";
+ case "preparing":
+ return "Finding the keyframe…";
+ case "refused":
+ case "failed":
+ return job.sentence;
+ case "ready":
+ return [job.range, job.start, job.end, `About ${formatBytes(job.plan.estimate)}, saved as ${job.name}.`]
+ .filter(Boolean)
+ .join(" ");
+ case "saving":
+ return `Saving ${job.name}.`;
+ case "done":
+ return doneSentence(job);
+ case "cancelled":
+ return cancelledSentence(job.path);
+ }
+}
+
+export function LocalClipPanel() {
+ const { data, clipStart, clipEnd, localFile, getLocalFile } = usePlayer();
+ const job = useSyncExternalStore(subscribeLocalClip, getLocalClipState, getIdleLocalClipState);
+ const [open, setOpen] = useState(false);
+ // Said by the live region after the group closed (a save cancelled by it).
+ const [closedNote, setClosedNote] = useState("");
+ const triggerRef = useRef<HTMLSpanElement | null>(null);
+ const groupRef = useRef<HTMLDivElement | null>(null);
+ const canClip = clipStart !== null && clipEnd !== null && clipEnd > clipStart;
+ const shown = open || job.phase !== "idle";
+ const offset = localFile?.offset ?? 0;
+
+ // Prepare (again) whenever what the clip depends on changes, unless one is
+ // being made; a refusal that may not hold (a failed read) is prepared again
+ // when its key is asked for again (the job allows that once).
+ const file = getLocalFile();
+ const key = file && canClip ? clipKey({ file, cueIn: clipStart!, cueOut: clipEnd!, offset }) : null;
+ useEffect(() => {
+ if (!shown || !file || key === null || !data) return;
+ const st = getLocalClipState();
+ if (st.phase === "saving") return;
+ if ("key" in st && st.key === key && !(st.phase === "refused" && st.retry)) return;
+ void prepareLocalClip({
+ file,
+ cueIn: clipStart!,
+ cueOut: clipEnd!,
+ offset,
+ title: data.title,
+ slug: data.slug,
+ canSaveToDisk: savePicker() !== null,
+ });
+ }, [shown, key, file, data, clipStart, clipEnd, offset]);
+
+ // Saving moves the focus to Cancel; when Cancel goes (done, cancelled,
+ // failed) and took the focus with it, the focus goes to "Clip my copy".
+ const savingNow = job.phase === "saving";
+ const wasSaving = useRef(false);
+ useEffect(() => {
+ if (savingNow) {
+ groupRef.current?.querySelector<HTMLButtonElement>('[data-clip-action="cancel"]')?.focus();
+ } else if (wasSaving.current) {
+ const active = document.activeElement;
+ if (!active || active === document.body || !active.isConnected) triggerRef.current?.querySelector("button")?.focus();
+ }
+ wasSaving.current = savingNow;
+ }, [savingNow]);
+
+ const close = () => {
+ const cancelled = closeLocalClip();
+ setClosedNote(cancelled ? cancelledSentence(cancelled) : "");
+ setOpen(false);
+ requestAnimationFrame(() => triggerRef.current?.querySelector("button")?.focus());
+ };
+
+ const save = async (st: Extract<ClipJobState, { phase: "ready" }>, to: "memory" | "disk") => {
+ if (to === "disk") {
+ const picker = savePicker();
+ if (!picker) return;
+ const ext = extOf(st.name);
+ let writable: WritableStream;
+ try {
+ // First, before anything else awaits: the picker needs the click.
+ const handle = await picker({
+ suggestedName: st.name,
+ types: [{ description: "Clip", accept: { [MIME_BY_EXT[ext] ?? "video/mp4"]: [ext] } }],
+ });
+ writable = await handle.createWritable();
+ } catch {
+ return; // The visitor closed the picker: still ready.
+ }
+ await saveLocalClip({ kind: "disk", writable });
+ } else {
+ await saveLocalClip({ kind: "memory" });
+ }
+ };
+
+ if (!localFile) return null;
+
+ return (
+ <>
+ <span ref={triggerRef} className="contents">
+ <ControlButton
+ title={canClip ? CLIP_BUTTON : CLIP_BUTTON_OFF}
+ label="Clip my copy"
+ icon={<ScissorsIcon className="size-4" />}
+ disabled={!canClip}
+ highlight={shown}
+ aria-expanded={shown}
+ onClick={() => {
+ if (shown) return close();
+ setClosedNote("");
+ setOpen(true);
+ }}
+ />
+ </span>
+ <p role="status" aria-live="polite" aria-atomic="true" data-testid="local-clip-status" className="sr-only">
+ {shown ? announcement(job, canClip) : closedNote}
+ </p>
+ {shown && (
+ <div
+ ref={groupRef}
+ role="group"
+ aria-label="Clip of your copy"
+ data-testid="local-clip"
+ className="basis-full flex flex-col gap-1.5 rounded-md bg-black/30 p-2"
+ >
+ <ClipBody job={job} canClip={canClip} onSave={save} onClose={close} />
+ <p className="text-[11px] text-zinc-400">
+ Clipping uses Mediabunny {LIBRARY_VERSION} (MPL-2.0):{" "}
+ <a
+ href="https://mozilla.org/MPL/2.0/"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline underline-offset-2 hover:text-white"
+ >
+ licence
+ </a>{" "}
+ ·{" "}
+ <a
+ href={LIBRARY_SOURCE}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline underline-offset-2 hover:text-white"
+ >
+ source
+ </a>
+ </p>
+ </div>
+ )}
+ </>
+ );
+}
+
+function Actions({ children }: { children: React.ReactNode }) {
+ return <div className="flex flex-wrap items-center gap-2">{children}</div>;
+}
+
+function ClipBody({
+ job,
+ canClip,
+ onSave,
+ onClose,
+}: {
+ job: ClipJobState;
+ canClip: boolean;
+ onSave: (st: Extract<ClipJobState, { phase: "ready" }>, to: "memory" | "disk") => void;
+ onClose: () => void;
+}) {
+ const closeButton = <ControlButton title="Close the clip" label="Close" icon={<span aria-hidden="true" className="hidden" />} onClick={onClose} />;
+ if (!canClip && job.phase !== "saving") {
+ return (
+ <>
+ <p>Mark Clip in and Clip out first.</p>
+ <Actions>{closeButton}</Actions>
+ </>
+ );
+ }
+ switch (job.phase) {
+ case "idle":
+ case "preparing":
+ return (
+ <>
+ <p>Finding the keyframe…</p>
+ <Actions>{closeButton}</Actions>
+ </>
+ );
+ case "refused":
+ case "failed":
+ return (
+ <>
+ <p data-testid="local-clip-refusal" className="text-rose-200">
+ {job.sentence}
+ </p>
+ <Actions>{closeButton}</Actions>
+ </>
+ );
+ case "ready":
+ return (
+ <>
+ <div data-testid="local-clip-ready" className="flex flex-col gap-0.5">
+ <p data-testid="local-clip-range">{job.range}</p>
+ <p data-testid="local-clip-start" className="text-amber-200">
+ {job.start}
+ </p>
+ {job.end && (
+ <p data-testid="local-clip-end" className="text-amber-200">
+ {job.end}
+ </p>
+ )}
+ <p>
+ About {formatBytes(job.plan.estimate)} · saved as{" "}
+ <span data-testid="local-clip-name" className="font-mono text-white">
+ {job.name}
+ </span>
+ {job.path === "disk" ? " · you choose where it goes" : ""}
+ </p>
+ {job.plan.extraTracks && <p>Only the main video and audio are kept.</p>}
+ </div>
+ <Actions>
+ <ControlButton title="Save clip" label="Save clip" icon={<span aria-hidden="true" className="hidden" />} onClick={() => onSave(job, job.path)} />
+ {job.path === "memory" && job.canSaveToDisk && (
+ <ControlButton
+ title="Save the clip to a file you choose"
+ label="Save to a file…"
+ icon={<span aria-hidden="true" className="hidden" />}
+ onClick={() => onSave(job, "disk")}
+ />
+ )}
+ {closeButton}
+ </Actions>
+ </>
+ );
+ case "saving": {
+ const pct = Math.floor(job.fraction * 100);
+ return (
+ <>
+ <p>
+ Saving <span className="font-mono text-white">{job.name}</span>
+ </p>
+ <div className="flex items-center gap-2">
+ <progress aria-label="Saving clip" max={1} value={job.fraction} className="w-40" />
+ <span data-testid="local-clip-progress" className="font-mono">
+ {pct} % · {formatClock(job.doneSeconds)} of {formatClock(job.totalSeconds)}
+ </span>
+ </div>
+ <Actions>
+ <ControlButton
+ title="Cancel the clip"
+ label="Cancel"
+ icon={<span aria-hidden="true" className="hidden" />}
+ data-clip-action="cancel"
+ onClick={cancelLocalClip}
+ />
+ </Actions>
+ </>
+ );
+ }
+ case "done":
+ return (
+ <>
+ <p data-testid="local-clip-done">{doneSentence(job)}</p>
+ <Actions>{closeButton}</Actions>
+ </>
+ );
+ case "cancelled":
+ return (
+ <>
+ <p data-testid="local-clip-cancelled">{cancelledSentence(job.path)}</p>
+ <Actions>{closeButton}</Actions>
+ </>
+ );
+ }
+}
diff --git a/common/components/LocalFileBar.tsx b/common/components/LocalFileBar.tsx
@@ -3,6 +3,7 @@
import { CrosshairIcon, SquareIcon } from "lucide-react";
import { ControlButton, usePlayer } from "./PlayerProvider";
import { LocalFilePicker } from "./LocalFilePicker";
+import { LocalClipPanel } from "./LocalClipPanel";
import { formatOffset } from "../lib/localFileClock";
// THE VISITOR'S OWN COPY, IN THE MODAL (lane missing-source, slice 2).
@@ -11,7 +12,8 @@ import { formatOffset } from "../lib/localFileClock";
// in the player slot's panel, so nothing shows here.)
// - A copy playing: its name, the offset, the four nudges, "This line is
// playing now" (the next cue click sets the offset) and Stop, which gives
-// the focus back to the "Play your own copy" control in its place.
+// the focus back to the "Play your own copy" control in its place; and
+// "Clip my copy" (LocalClipPanel), which cuts the marked clip from it.
//
// Nothing in this file may reach the network or storage (the offset is written
// by the provider through lib/localFileClock.ts); LocalFilePicker.test.ts
@@ -90,6 +92,8 @@ export function LocalFileBar() {
icon={<SquareIcon className="size-4" />}
onClick={stopLocalFile}
/>
+ {/* A clip of this copy, cut in the browser (lane browser-clip). */}
+ <LocalClipPanel />
{localSyncArmed && (
<p role="status" className="basis-full text-amber-200">
Click the line you hear now (Esc cancels).
diff --git a/common/components/LocalFilePicker.test.ts b/common/components/LocalFilePicker.test.ts
@@ -20,6 +20,12 @@ const FILES = [
"./LocalFileBar.tsx",
"../lib/localFileClock.ts",
"../lib/sourceMissing.ts",
+ // The in-browser clipper (lane browser-clip): its panel, its job, its pure
+ // part and the engine that drives the library.
+ "./LocalClipPanel.tsx",
+ "../lib/localClipJob.ts",
+ "../lib/localClip.ts",
+ "../lib/localClipEngine.ts",
];
const FORBIDDEN: ReadonlyArray<[string, RegExp]> = [
@@ -51,3 +57,30 @@ for (const rel of FILES) {
}
});
}
+
+// The clipper's one door: lib/localClipLoader.ts may hold a dynamic import,
+// and only of the engine — so the library loads when a clip is asked for and
+// nothing else rides in with it.
+test("../lib/localClipLoader.ts holds exactly one dynamic import, of the engine, and nothing else forbidden", () => {
+ const src = code(readFileSync(fileURLToPath(new URL("../lib/localClipLoader.ts", import.meta.url)), "utf8"));
+ const imports = src.match(/\bimport\s*\(([^)]*)\)/g) ?? [];
+ assert.deepEqual(imports, ['import("./localClipEngine")']);
+ for (const [name, re] of FORBIDDEN) {
+ if (name === "a dynamic import") continue;
+ assert.ok(!re.test(src), `localClipLoader.ts mentions ${name}`);
+ }
+ assert.ok(!/^\s*import\s/m.test(src), "localClipLoader.ts has a static import");
+});
+
+// The engine takes from the library only what a stream copy of a local Blob
+// needs: no URL, HLS or stream sources (the library's own network doors).
+test("../lib/localClipEngine.ts imports no network source from the library", () => {
+ const src = code(readFileSync(fileURLToPath(new URL("../lib/localClipEngine.ts", import.meta.url)), "utf8"));
+ const m = src.match(/import\s*\{([^}]*)\}\s*from\s*"mediabunny"/);
+ assert.ok(m, "the engine imports from mediabunny");
+ const names = m![1].split(",").map((s) => s.trim().replace(/^type\s+/, "")).filter(Boolean);
+ for (const bad of ["UrlSource", "StreamSource", "ReadableStreamSource", "HLS", "HLS_FORMATS", "ALL_FORMATS", "FilePathSource", "FilePathTarget"]) {
+ assert.ok(!names.includes(bad), `the engine imports ${bad}`);
+ }
+ assert.ok(names.includes("BlobSource"));
+});
diff --git a/common/components/PlayerProvider.tsx b/common/components/PlayerProvider.tsx
@@ -54,6 +54,7 @@ import {
toFileTime,
writeOffset,
} from "../lib/localFileClock";
+import { resetLocalClip } from "../lib/localClipJob";
const ReactPlayer = dynamic(() => import("react-player/youtube"), {
ssr: false,
@@ -244,6 +245,9 @@ type PlayerState = {
localSyncArmed: boolean;
openLocalFile: (file: File) => void;
clearLocalFile: () => void;
+ // The picked File itself, for the in-browser clipper (lane browser-clip),
+ // while its copy is active for this video; null otherwise. Never state.
+ getLocalFile: () => File | null;
// "Stop": clear the copy and give focus back to the "Play your own copy"
// control that takes its place (takeLocalPickerFocus, read once by it).
stopLocalFile: () => void;
@@ -559,9 +563,11 @@ export function PlayerProvider({
const pendingSeekRef = useRef<number | null>(null);
const currentTimeRef = useRef(0);
currentTimeRef.current = currentTime;
- // The visitor's own copy (slice 2). The File itself is never kept: only its
- // object URL (revoked when it is replaced, cleared, the video changes or the
- // provider unmounts) and its name, shown on screen and nowhere else.
+ // The visitor's own copy (slice 2). Its object URL (revoked when it is
+ // replaced, cleared, the video changes or the provider unmounts) and its
+ // name, shown on screen and nowhere else. The File itself is held in a ref
+ // for exactly as long as its URL, for the clipper (lane browser-clip), and
+ // is never put in state.
const [local, setLocal] = useState<{ slug: string; url: string; name: string } | null>(null);
const [localOffset, setLocalOffset] = useState(0);
const [localError, setLocalError] = useState(false);
@@ -571,6 +577,7 @@ export function PlayerProvider({
// The file element's own time, as its last progress event said.
const localRawRef = useRef(0);
const localUrlRef = useRef<string | null>(null);
+ const localFileRef = useRef<File | null>(null);
const readyForSlugRef = useRef<string | null>(null);
// The YouTube embed said it cannot play this video (removed, private,
// embedding off). Its progress events are then the dead player's 0, never
@@ -854,6 +861,9 @@ export function PlayerProvider({
const revokeLocalUrl = useCallback(() => {
if (localUrlRef.current) URL.revokeObjectURL(localUrlRef.current);
localUrlRef.current = null;
+ localFileRef.current = null;
+ // A clip of that copy, prepared or being made, goes with it.
+ resetLocalClip();
}, []);
const openLocalFile = useCallback(
@@ -862,6 +872,7 @@ export function PlayerProvider({
revokeLocalUrl();
const url = URL.createObjectURL(file);
localUrlRef.current = url;
+ localFileRef.current = file;
localRawRef.current = 0;
setLocalError(false);
setLocalSyncArmed(false);
@@ -919,6 +930,11 @@ export function PlayerProvider({
const armLocalSync = useCallback((on: boolean) => setLocalSyncArmed(on), []);
+ const getLocalFile = useCallback(
+ () => (localActive ? localFileRef.current : null),
+ [localActive],
+ );
+
// Another video, or none: the copy belonged to the one it was picked on.
useEffect(() => {
if (local && local.slug !== activeSlug) clearLocalFile();
@@ -1233,6 +1249,7 @@ export function PlayerProvider({
localSyncArmed: localActive && localSyncArmed,
openLocalFile,
clearLocalFile,
+ getLocalFile,
stopLocalFile,
takeLocalPickerFocus,
nudgeLocalOffset,
@@ -1274,6 +1291,7 @@ export function PlayerProvider({
localSyncArmed,
openLocalFile,
clearLocalFile,
+ getLocalFile,
stopLocalFile,
takeLocalPickerFocus,
nudgeLocalOffset,
diff --git a/common/lib/localClip.test.ts b/common/lib/localClip.test.ts
@@ -0,0 +1,215 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ DISK_SAVE_ABOVE_BYTES,
+ MEMORY_LIMIT_BYTES,
+ chooseOutput,
+ clipFileName,
+ describeClip,
+ estimateBytes,
+ fileRange,
+ formatBytes,
+ formatClock,
+ refusalSentence,
+ savePath,
+ type OutputSupport,
+} from "./localClip";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/localClip.test.ts
+
+test("the marks go to the file through the offset, clamped to the file", () => {
+ assert.deepEqual(fileRange(5, 9, 0, 0, 12), { ok: true, fileIn: 5, fileOut: 9 });
+ assert.deepEqual(fileRange(5, 9, 1, 0, 12), { ok: true, fileIn: 6, fileOut: 10 });
+ // A negative offset: the copy starts later than the cues.
+ assert.deepEqual(fileRange(1, 4, -2, 0, 12), { ok: true, fileIn: 0, fileOut: 2 });
+ // Past the end: cut at the end.
+ assert.deepEqual(fileRange(10, 20, 0, 0, 12), { ok: true, fileIn: 10, fileOut: 12 });
+ // An unknown end clamps nothing at the top.
+ assert.deepEqual(fileRange(10, 20, 0, 0, null), { ok: true, fileIn: 10, fileOut: 20 });
+ // A copy whose first timestamp is not 0: clamped to where it begins.
+ assert.deepEqual(fileRange(1, 6, 0, 3, 15), { ok: true, fileIn: 3, fileOut: 6 });
+});
+
+test("a range that is empty, backwards, too short or off the file is refused", () => {
+ assert.deepEqual(fileRange(9, 5, 0, 0, 12), { ok: false, reason: "order" });
+ assert.deepEqual(fileRange(5, 5, 0, 0, 12), { ok: false, reason: "order" });
+ assert.deepEqual(fileRange(5, 5.05, 0, 0, 12), { ok: false, reason: "short" });
+ assert.deepEqual(fileRange(13, 20, 0, 0, 12), { ok: false, reason: "outside" });
+ assert.deepEqual(fileRange(1, 3, -5, 0, 12), { ok: false, reason: "outside" });
+ // Only a sliver left inside the file.
+ assert.deepEqual(fileRange(11.95, 20, 0, 0, 12), { ok: false, reason: "outside" });
+ // Both marks before a copy that begins at 3 s.
+ assert.deepEqual(fileRange(0.5, 2.5, 0, 3, 15), { ok: false, reason: "outside" });
+});
+
+test("times read H:MM:SS.s", () => {
+ assert.equal(formatClock(0), "0:00:00.0");
+ assert.equal(formatClock(4), "0:00:04.0");
+ assert.equal(formatClock(309.64), "0:05:09.6");
+ assert.equal(formatClock(3599.96), "1:00:00.0");
+ assert.equal(formatClock(-3), "0:00:00.0");
+});
+
+const base = { title: "Synth stream", slug: "ch-abc", ext: ".webm" };
+
+test("where the clip really starts is said before saving", () => {
+ const at = (cueIn: number, cueOut: number, offset: number, startTs: number, endTs: number, fileStart = 0) =>
+ describeClip({ ...base, cueIn, cueOut, offset, fileStart, startTs, endTs }).start;
+ assert.equal(at(5, 9, 0, 4, 9), "Starts 1.0 s earlier, at the nearest keyframe (0:00:04.0).");
+ assert.equal(at(312, 320, 0, 309.6, 320), "Starts 2.4 s earlier, at the nearest keyframe (0:05:09.6).");
+ // On the cue clock: the keyframe at 6.0 s into the file, offset +1 s, is the cues' 0:05.
+ assert.equal(at(6, 9, 1, 6, 10), "Starts 1.0 s earlier, at the nearest keyframe (0:00:05.0).");
+ assert.equal(at(5, 9, 1, 6, 10), "Starts at your Clip in mark.");
+ assert.equal(at(5.04, 9, 1, 6, 10), "Starts at your Clip in mark.");
+ // A real start before the transcript's 0:00 (a copy with a lead-in).
+ assert.equal(at(1, 5, 2, 0.6, 7), "Starts 2.4 s earlier, before the transcript's 0:00.");
+});
+
+test("the range sentence names the offset only when there is one", () => {
+ const range = (offset: number) =>
+ describeClip({ ...base, cueIn: 312, cueOut: 363.4, offset, fileStart: 0, startTs: 312 + offset, endTs: 363.4 + offset }).range;
+ assert.equal(range(3), "From 0:05:12.0 to 0:06:03.4, with your offset +3.00 s applied.");
+ assert.equal(range(0), "From 0:05:12.0 to 0:06:03.4.");
+});
+
+test("a mark outside the copy: the page says what is really written, and the name agrees", () => {
+ // A trimmed copy, offset -30 s, marks at cue 0:10-0:50: the copy begins at cue 0:30.
+ const trimmed = describeClip({ ...base, cueIn: 10, cueOut: 50, offset: -30, fileStart: 0, startTs: 0, endTs: 20 });
+ assert.equal(trimmed.range, "From 0:00:30.0 to 0:00:50.0, with your offset −30.00 s applied.");
+ assert.equal(trimmed.start, "Your copy begins at 0:00:30.0, after your Clip in mark; the clip starts there.");
+ assert.equal(trimmed.end, null);
+ assert.equal(trimmed.name, "Synth-stream_00h00m30s-00h00m50s.webm");
+ // The copy ends before the out mark.
+ const short = describeClip({ ...base, cueIn: 5, cueOut: 20, offset: 0, fileStart: 0, startTs: 4, endTs: 12 });
+ assert.equal(short.range, "From 0:00:05.0 to 0:00:12.0.");
+ assert.equal(short.start, "Starts 1.0 s earlier, at the nearest keyframe (0:00:04.0).");
+ assert.equal(short.end, "Your copy ends at 0:00:12.0, before your Clip out mark; the clip ends there.");
+ assert.equal(short.name, "Synth-stream_00h00m04s-00h00m12s.webm");
+ // A copy whose first timestamp is 3 s, whose first keyframe is there too.
+ const late = describeClip({ ...base, cueIn: 1, cueOut: 6, offset: 0, fileStart: 2.98, startTs: 3, endTs: 6 });
+ assert.equal(late.start, "Your copy begins at 0:00:03.0, after your Clip in mark; the clip starts there.");
+ assert.equal(late.name, "Synth-stream_00h00m03s-00h00m06s.webm");
+ // The copy begins before the mark but its first keyframe comes after it.
+ const key = describeClip({ ...base, cueIn: 1, cueOut: 6, offset: 0, fileStart: 0, startTs: 2.5, endTs: 6 });
+ assert.equal(key.start, "Starts 1.5 s later, at your copy's first keyframe (0:00:02.5).");
+ assert.equal(key.range, "From 0:00:02.5 to 0:00:06.0.");
+ assert.equal(key.name, "Synth-stream_00h00m02s-00h00m06s.webm");
+ // The copy begins after the mark, and its first keyframe later still.
+ const both = describeClip({ ...base, cueIn: 1, cueOut: 6, offset: 0, fileStart: 2, startTs: 2.5, endTs: 6 });
+ assert.equal(both.start, "Your copy begins at 0:00:02.0, after your Clip in mark; the clip starts at its first keyframe (0:00:02.5).");
+});
+
+test("the saved file is named from the title and the clip's real times, never the picked file", () => {
+ assert.equal(clipFileName("Some Stream: Title?", "ch-abc", 309.6, 363.4, ".mp4"), "Some-Stream-Title_00h05m09s-00h06m04s.mp4");
+ assert.equal(clipFileName("Ünïcode — 日本語 / x", "s", 4, 9, ".webm"), "Ünïcode-日本語-x_00h00m04s-00h00m09s.webm");
+ // Windows-forbidden characters never survive.
+ const name = clipFileName('a<b>c:d"e/f\\g|h?i*j', "s", 0, 1, ".mkv");
+ assert.equal(name, "a-b-c-d-e-f-g-h-i-j_00h00m00s-00h00m01s.mkv");
+ // Empty title: the slug; neither: "clip".
+ assert.equal(clipFileName(" ", "ch-abc", 0, 1, ".mp4"), "ch-abc_00h00m00s-00h00m01s.mp4");
+ assert.equal(clipFileName("", "", 0, 1, ".mp4"), "clip_00h00m00s-00h00m01s.mp4");
+ // Cut at 80 characters, never ending in a dash.
+ const long = clipFileName("word ".repeat(40), "s", 0, 1, ".mp4");
+ const base = long.split("_")[0];
+ assert.ok(base.length <= 80, base);
+ assert.ok(!base.endsWith("-"));
+ // An hour boundary, and a real start before 0 clamped.
+ assert.equal(clipFileName("t", "s", 3599.5, 3600, ".mp4"), "t_00h59m59s-01h00m00s.mp4");
+ assert.equal(clipFileName("t", "s", -2.4, 9, ".mp4"), "t_00h00m00s-00h00m09s.mp4");
+ // A float a hair over a whole second does not round the end up.
+ assert.equal(clipFileName("t", "s", 4, 9.0000001, ".mp4"), "t_00h00m04s-00h00m09s.mp4");
+});
+
+const SUPPORT: OutputSupport = {
+ mp4: ["avc", "hevc", "vp9", "av1", "vp8", "aac", "opus", "mp3", "flac"],
+ mov: ["avc", "hevc", "vp9", "av1", "vp8", "aac", "opus", "mp3", "flac", "pcm-u8"],
+ mkv: ["avc", "hevc", "vp9", "av1", "vp8", "aac", "opus", "mp3", "flac", "vorbis"],
+ webm: ["vp9", "av1", "vp8", "opus", "vorbis"],
+};
+
+test("the clip keeps its container family", () => {
+ assert.deepEqual(chooseOutput("mp4", "avc", "aac", SUPPORT), { ok: true, format: "mp4", ext: ".mp4" });
+ assert.deepEqual(chooseOutput("mp4", null, "aac", SUPPORT), { ok: true, format: "mp4", ext: ".m4a" });
+ assert.deepEqual(chooseOutput("mov", "avc", "aac", SUPPORT), { ok: true, format: "mov", ext: ".mov" });
+ assert.deepEqual(chooseOutput("webm", "vp9", "opus", SUPPORT), { ok: true, format: "webm", ext: ".webm" });
+ assert.deepEqual(chooseOutput("webm", null, "opus", SUPPORT), { ok: true, format: "webm", ext: ".webm" });
+ assert.deepEqual(chooseOutput("mkv", "avc", "aac", SUPPORT), { ok: true, format: "mkv", ext: ".mkv" });
+ assert.deepEqual(chooseOutput("mkv", null, "aac", SUPPORT), { ok: true, format: "mkv", ext: ".mka" });
+});
+
+test("a codec the family cannot hold falls back once (MP4 → MOV, WebM → MKV), else is refused", () => {
+ assert.deepEqual(chooseOutput("mp4", "avc", "pcm-u8", SUPPORT), { ok: true, format: "mov", ext: ".mov" });
+ assert.deepEqual(chooseOutput("webm", "avc", "opus", SUPPORT), { ok: true, format: "mkv", ext: ".mkv" });
+ assert.deepEqual(chooseOutput("mkv", "avc", "pcm-u8", SUPPORT), { ok: false, track: "audio", codec: "pcm-u8" });
+ assert.deepEqual(chooseOutput("mp4", "mpeg4", "aac", SUPPORT), { ok: false, track: "video", codec: "mpeg4" });
+ // An unknown codec (the library could not name it).
+ assert.deepEqual(chooseOutput("mp4", "", "aac", SUPPORT), { ok: false, track: "video", codec: "" });
+ // Nothing to copy at all.
+ assert.deepEqual(chooseOutput("mp4", null, null, SUPPORT), { ok: false, track: "none", codec: "" });
+});
+
+test("the size is estimated from the file's own byte rate", () => {
+ assert.equal(estimateBytes(1_000_000, 100, 10), 100_000);
+ assert.equal(estimateBytes(1_000_000, 0, 10), 1_000_000);
+ assert.equal(estimateBytes(1_000_000, null, 10), 1_000_000);
+ assert.equal(estimateBytes(1_000_000, 100, 1000), 1_000_000);
+ assert.equal(formatBytes(512), "1 KB");
+ assert.equal(formatBytes(47_800_000), "48 MB");
+ assert.equal(formatBytes(4_780_000), "4.8 MB");
+ assert.equal(formatBytes(2_300_000_000), "2.3 GB");
+});
+
+test("memory for a small clip, the disk for a big one when the browser can, else a refusal over 256 MB", () => {
+ assert.equal(MEMORY_LIMIT_BYTES, 256_000_000);
+ assert.equal(DISK_SAVE_ABOVE_BYTES, 128_000_000);
+ assert.equal(savePath(10_000_000, true), "memory");
+ assert.equal(savePath(10_000_000, false), "memory");
+ assert.equal(savePath(DISK_SAVE_ABOVE_BYTES + 1, true), "disk");
+ assert.equal(savePath(DISK_SAVE_ABOVE_BYTES + 1, false), "memory");
+ assert.equal(savePath(MEMORY_LIMIT_BYTES, false), "memory");
+ assert.equal(savePath(MEMORY_LIMIT_BYTES + 1, false), "too-big");
+ assert.equal(savePath(MEMORY_LIMIT_BYTES + 1, true), "disk");
+});
+
+test("every refusal is one plain sentence", () => {
+ assert.equal(refusalSentence({ kind: "container" }), "This file can't be clipped here: clipping takes MP4, MOV, M4A, WebM or MKV.");
+ assert.equal(
+ refusalSentence({ kind: "codec", track: "video", codec: "mpeg4" }),
+ "This file's video (mpeg4) can't be copied into a clip without re-encoding, which this page does not do.",
+ );
+ assert.equal(
+ refusalSentence({ kind: "codec", track: "audio", codec: "" }),
+ "This file's audio (an unknown format) can't be copied into a clip without re-encoding, which this page does not do.",
+ );
+ assert.equal(refusalSentence({ kind: "codec", track: "none", codec: "" }), "This file has no video or audio to clip.");
+ assert.equal(
+ refusalSentence({ kind: "outside", duration: 2530, offset: 3 }),
+ "Both marks are outside your copy (it is 0:42:10.0 long, offset +3.00 s).",
+ );
+ // A copy whose length is not known never reads "0:00:00.0 long".
+ assert.equal(refusalSentence({ kind: "outside", duration: null, offset: 3 }), "Both marks are outside your copy (offset +3.00 s).");
+ assert.equal(refusalSentence({ kind: "short" }), "Mark a clip at least 0.1 s long.");
+ assert.equal(
+ refusalSentence({ kind: "too-big", bytes: 2_300_000_000 }),
+ "This clip would be about 2.3 GB, too big to build in this browser's memory (at most 256 MB). Mark a shorter clip, or use a Chromium-based browser, which can save it straight to disk.",
+ );
+ // Bigger than the estimate said, found while it was being made.
+ assert.equal(
+ refusalSentence({ kind: "grew", canSaveToDisk: false }),
+ "This clip grew past 256 MB while it was being made, too big for this browser's memory; nothing was saved. Mark a shorter clip, or use a Chromium-based browser, which can save it straight to disk.",
+ );
+ assert.equal(
+ refusalSentence({ kind: "grew", canSaveToDisk: true }),
+ "This clip grew past 256 MB while it was being made, too big for this browser's memory; nothing was saved. Save it to a file you choose instead, or mark a shorter clip.",
+ );
+ assert.equal(
+ refusalSentence({ kind: "read" }),
+ "Your browser could not read the file. It may have moved or changed since you picked it; pick it again.",
+ );
+ assert.equal(
+ refusalSentence({ kind: "no-key" }),
+ "Your copy has no keyframe before your Clip out mark, so no clip can start there. Mark a later Clip out.",
+ );
+ assert.equal(refusalSentence({ kind: "copy" }), "This file could not be copied into a clip; nothing was saved.");
+});
diff --git a/common/lib/localClip.ts b/common/lib/localClip.ts
@@ -0,0 +1,276 @@
+// A CLIP OF THE VISITOR'S OWN COPY, CUT IN THE BROWSER (lane browser-clip).
+//
+// The export site can stream-copy a part of a file the visitor picked — no
+// re-encode, nothing uploaded — between the modal's Clip in / Clip out marks.
+// The marks are on the CUE clock; the file is reached through the visitor's
+// offset (lib/localFileClock.ts): fileTime = cueTime + offset.
+//
+// A stream copy starts on a keyframe, so the clip may start a little before
+// the in mark; the page says where BEFORE the visitor saves (describeClip).
+//
+// This module is the pure part: the time maths, the sentences, the saved
+// file's name and the output format. No I/O, no library import — the copy
+// itself is lib/localClipEngine.ts, loaded only when a clip is asked for.
+
+import { formatOffset } from "./localFileClock";
+
+// Shorter than this is not a clip.
+export const MIN_CLIP_SECONDS = 0.1;
+// A keyframe this close to the in mark is "at the mark".
+export const AT_MARK_SECONDS = 0.05;
+// Built in memory, a clip can be at most this big. It is held about twice
+// over at its peak (the written parts, then the Blob made from them), so a
+// clip at the limit stays near half a gigabyte; the real bytes written are
+// checked against it as the clip is made, since the estimate can be low.
+export const MEMORY_LIMIT_BYTES = 256_000_000;
+// Above this estimate, a browser that can write straight to disk does: half
+// the memory limit, so an estimate that is low by up to 2x still fits.
+export const DISK_SAVE_ABOVE_BYTES = 128_000_000;
+// The longest title part of a saved file's name.
+const NAME_MAX = 80;
+
+export type FileRange =
+ | { ok: true; fileIn: number; fileOut: number }
+ | { ok: false; reason: "order" | "short" | "outside" };
+
+// The marks (cue clock) as a range of the file, clamped to the file's own
+// first and last timestamps (on the <video> clock, which is the container's:
+// a copy may begin later than 0). `fileEnd` null: the end is not known, so
+// nothing is clamped at the top.
+export function fileRange(
+ cueIn: number,
+ cueOut: number,
+ offset: number,
+ fileStart: number,
+ fileEnd: number | null,
+): FileRange {
+ if (!(cueOut > cueIn)) return { ok: false, reason: "order" };
+ if (cueOut - cueIn < MIN_CLIP_SECONDS) return { ok: false, reason: "short" };
+ const bottom = Number.isFinite(fileStart) && fileStart > 0 ? fileStart : 0;
+ const top = fileEnd !== null && Number.isFinite(fileEnd) && fileEnd > bottom ? fileEnd : Infinity;
+ const fileIn = Math.min(Math.max(bottom, cueIn + offset), top);
+ const fileOut = Math.min(Math.max(bottom, cueOut + offset), top);
+ if (fileOut - fileIn < MIN_CLIP_SECONDS) return { ok: false, reason: "outside" };
+ return { ok: true, fileIn: round6(fileIn), fileOut: round6(fileOut) };
+}
+
+const round6 = (v: number) => Math.round(v * 1e6) / 1e6;
+
+// H:MM:SS.s, to the tenth.
+export function formatClock(seconds: number): string {
+ const tenths = Math.max(0, Math.round(seconds * 10));
+ const h = Math.floor(tenths / 36000);
+ const m = Math.floor((tenths % 36000) / 600);
+ const s = Math.floor((tenths % 600) / 10);
+ const t = tenths % 10;
+ return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}.${t}`;
+}
+
+export type ClipFacts = {
+ // The marks, on the cue clock, and the visitor's offset (fileTime = cue + offset).
+ cueIn: number;
+ cueOut: number;
+ offset: number;
+ // File time: where the copy itself begins, and the clip's REAL first and
+ // last written times (the first packet written, the end of the last one,
+ // no later than the out mark).
+ fileStart: number;
+ startTs: number;
+ endTs: number;
+ title: string;
+ slug: string;
+ ext: string;
+};
+
+export type ClipWords = {
+ // "From … to …": the part of the marked range the clip holds.
+ range: string;
+ // Where it really starts, against the in mark.
+ start: string;
+ // Said only when the copy ends before the out mark.
+ end: string | null;
+ // The saved file's name, from the same real start and end.
+ name: string;
+};
+
+// Every sentence and the name about a prepared clip, from ONE set of facts:
+// the real first and last written times, mapped back to the cue clock.
+export function describeClip(f: ClipFacts): ClipWords {
+ const toCue = (t: number) => t - f.offset;
+ const markIn = f.cueIn + f.offset;
+ const markOut = f.cueOut + f.offset;
+ const startCue = toCue(f.startTs);
+ const endCue = Math.min(f.cueOut, toCue(f.endTs));
+ const lead = markIn - f.startTs;
+ let start: string;
+ if (lead >= AT_MARK_SECONDS) {
+ const by = `Starts ${lead.toFixed(1)} s earlier`;
+ start = startCue < 0 ? `${by}, before the transcript's 0:00.` : `${by}, at the nearest keyframe (${formatClock(startCue)}).`;
+ } else if (lead > -AT_MARK_SECONDS) {
+ start = "Starts at your Clip in mark.";
+ } else if (f.fileStart > markIn) {
+ const begins = `Your copy begins at ${formatClock(toCue(f.fileStart))}, after your Clip in mark`;
+ start =
+ f.startTs - f.fileStart < AT_MARK_SECONDS
+ ? `${begins}; the clip starts there.`
+ : `${begins}; the clip starts at its first keyframe (${formatClock(startCue)}).`;
+ } else {
+ start = `Starts ${(-lead).toFixed(1)} s later, at your copy's first keyframe (${formatClock(startCue)}).`;
+ }
+ const end =
+ f.endTs < markOut - AT_MARK_SECONDS
+ ? `Your copy ends at ${formatClock(endCue)}, before your Clip out mark; the clip ends there.`
+ : null;
+ const from = Math.max(f.cueIn, startCue);
+ const span = `From ${formatClock(from)} to ${formatClock(endCue)}`;
+ const range = Math.round(f.offset * 100) === 0 ? `${span}.` : `${span}, with your offset ${formatOffset(f.offset)} applied.`;
+ return { range, start, end, name: clipFileName(f.title, f.slug, startCue, endCue, f.ext) };
+}
+
+// 00h05m09s: whole seconds, the start floored and the end rounded up (to the
+// tenth first, so 9.0000001 stays 9).
+function stamp(seconds: number, up: boolean): string {
+ const tenths = Math.max(0, Math.round(seconds * 10)) / 10;
+ const s = up ? Math.ceil(tenths) : Math.floor(tenths);
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = s % 60;
+ return `${String(h).padStart(2, "0")}h${String(m).padStart(2, "0")}m${String(sec).padStart(2, "0")}s`;
+}
+
+function nameBase(text: string): string {
+ const runs = text.normalize("NFC").match(/[\p{L}\p{M}\p{N}]+/gu);
+ if (!runs) return "";
+ let base = runs.join("-");
+ if ([...base].length > NAME_MAX) base = [...base].slice(0, NAME_MAX).join("");
+ return base.replace(/-+$/, "");
+}
+
+// `<title>_<start>-<end><ext>` from the video's title (else its slug, else
+// "clip") and the clip's REAL start (the keyframe, on the cue clock) and end.
+// Never the picked file's name.
+export function clipFileName(title: string, slug: string, startCue: number, endCue: number, ext: string): string {
+ const base = nameBase(title) || nameBase(slug) || "clip";
+ return `${base}_${stamp(startCue, false)}-${stamp(endCue, true)}${ext}`;
+}
+
+export type ContainerFamily = "mp4" | "mov" | "webm" | "mkv";
+export type OutputFormatName = "mp4" | "mov" | "webm" | "mkv";
+// The codecs each output format can hold, as the library says
+// (getSupportedCodecs); handed in so this module stays library-free.
+export type OutputSupport = Record<OutputFormatName, readonly string[]>;
+
+export type OutputChoice =
+ | { ok: true; format: OutputFormatName; ext: string }
+ | { ok: false; track: "video" | "audio" | "none"; codec: string };
+
+const FALLBACK: Record<ContainerFamily, OutputFormatName | null> = {
+ mp4: "mov",
+ mov: null,
+ webm: "mkv",
+ mkv: null,
+};
+
+function extFor(format: OutputFormatName, hasVideo: boolean): string {
+ if (format === "mp4") return hasVideo ? ".mp4" : ".m4a";
+ if (format === "mkv") return hasVideo ? ".mkv" : ".mka";
+ return `.${format}`;
+}
+
+// The clip keeps its container family; a codec the family's format cannot
+// hold falls back once (MP4 → MOV, WebM → MKV), else the file is refused —
+// never re-encoded. A codec of "" is one the library could not name.
+export function chooseOutput(
+ family: ContainerFamily,
+ videoCodec: string | null,
+ audioCodec: string | null,
+ support: OutputSupport,
+): OutputChoice {
+ if (videoCodec === null && audioCodec === null) return { ok: false, track: "none", codec: "" };
+ const holds = (f: OutputFormatName) =>
+ (videoCodec === null || (videoCodec !== "" && support[f].includes(videoCodec))) &&
+ (audioCodec === null || (audioCodec !== "" && support[f].includes(audioCodec)));
+ const first: OutputFormatName = family;
+ for (const f of [first, FALLBACK[family]]) {
+ if (f && holds(f)) return { ok: true, format: f, ext: extFor(f, videoCodec !== null) };
+ }
+ const last = FALLBACK[family] ?? first;
+ const videoFits = videoCodec === null || (videoCodec !== "" && support[last].includes(videoCodec));
+ return videoFits
+ ? { ok: false, track: "audio", codec: audioCodec ?? "" }
+ : { ok: false, track: "video", codec: videoCodec ?? "" };
+}
+
+// The clip's size from the file's own byte rate.
+export function estimateBytes(fileBytes: number, duration: number | null, clipSeconds: number): number {
+ if (duration === null || !(duration > 0)) return fileBytes;
+ return Math.min(fileBytes, Math.ceil((fileBytes * clipSeconds) / duration));
+}
+
+export function formatBytes(bytes: number): string {
+ if (bytes < 1e6) return `${Math.max(1, Math.round(bytes / 1e3))} KB`;
+ if (bytes < 1e7) return `${(bytes / 1e6).toFixed(1)} MB`;
+ if (bytes < 1e9) return `${Math.round(bytes / 1e6)} MB`;
+ return `${(bytes / 1e9).toFixed(1)} GB`;
+}
+
+export type SavePath = "memory" | "disk" | "too-big";
+
+// Where a clip of `estimate` bytes is built: in memory and handed over as a
+// download, or written straight to a file the visitor picks (a browser with
+// showSaveFilePicker) when it is big; refused when it is too big for memory
+// and the browser cannot write to disk.
+export function savePath(estimate: number, canSaveToDisk: boolean): SavePath {
+ if (canSaveToDisk && estimate > DISK_SAVE_ABOVE_BYTES) return "disk";
+ if (estimate <= MEMORY_LIMIT_BYTES) return "memory";
+ return "too-big";
+}
+
+export type Refusal =
+ | { kind: "container" }
+ | { kind: "codec"; track: "video" | "audio" | "none"; codec: string }
+ | { kind: "outside"; duration: number | null; offset: number }
+ | { kind: "short" }
+ | { kind: "too-big"; bytes: number }
+ // The real bytes passed the memory limit while the clip was being made.
+ | { kind: "grew"; canSaveToDisk: boolean }
+ | { kind: "read" }
+ // The copy's first keyframe comes after the Clip out mark.
+ | { kind: "no-key" }
+ | { kind: "copy" };
+
+const SHORTER_OR_DISK = "Mark a shorter clip, or use a Chromium-based browser, which can save it straight to disk.";
+
+export function refusalSentence(r: Refusal): string {
+ switch (r.kind) {
+ case "container":
+ return "This file can't be clipped here: clipping takes MP4, MOV, M4A, WebM or MKV.";
+ case "codec":
+ if (r.track === "none") return "This file has no video or audio to clip.";
+ return `This file's ${r.track} (${r.codec || "an unknown format"}) can't be copied into a clip without re-encoding, which this page does not do.`;
+ case "outside":
+ return r.duration === null
+ ? `Both marks are outside your copy (offset ${formatOffset(r.offset)}).`
+ : `Both marks are outside your copy (it is ${formatClock(r.duration)} long, offset ${formatOffset(r.offset)}).`;
+ case "short":
+ return "Mark a clip at least 0.1 s long.";
+ case "too-big":
+ return `This clip would be about ${formatBytes(r.bytes)}, too big to build in this browser's memory (at most ${formatBytes(MEMORY_LIMIT_BYTES)}). ${SHORTER_OR_DISK}`;
+ case "grew":
+ return `This clip grew past ${formatBytes(MEMORY_LIMIT_BYTES)} while it was being made, too big for this browser's memory; nothing was saved. ${r.canSaveToDisk ? "Save it to a file you choose instead, or mark a shorter clip." : SHORTER_OR_DISK}`;
+ case "read":
+ return "Your browser could not read the file. It may have moved or changed since you picked it; pick it again.";
+ case "no-key":
+ return "Your copy has no keyframe before your Clip out mark, so no clip can start there. Mark a later Clip out.";
+ case "copy":
+ return "This file could not be copied into a clip; nothing was saved.";
+ }
+}
+
+// What a cancelled clip leaves behind. A picked file's writer was aborted, but
+// a browser may still leave an empty file where the visitor chose to save.
+export function cancelledSentence(path: "memory" | "disk"): string {
+ return path === "disk"
+ ? "Cancelled; the clip was not written. Your browser may leave an empty file where you chose to save it."
+ : "Cancelled; nothing was saved.";
+}
diff --git a/common/lib/localClipEngine.test.ts b/common/lib/localClipEngine.test.ts
@@ -0,0 +1,421 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { execFileSync, spawnSync } from "node:child_process";
+import { mkdtempSync, openAsBlob, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ CLIP_ENGINE_MARK,
+ ClipCancelled,
+ ClipTooBig,
+ HELD_PAST_OUT_MAX,
+ clipVideoPackets,
+ outputSupport,
+ probeClip,
+ saveClip,
+} from "./localClipEngine";
+import { EncodedPacket, MkvOutputFormat, MovOutputFormat, Mp4OutputFormat, WebMOutputFormat } from "mediabunny";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/localClipEngine.test.ts
+//
+// The stream copy itself, in Node over a Blob of a file ffmpeg makes here
+// (keyframes every 2.0 s, B-frames in the H.264 one), checked with ffprobe:
+// the codecs are the source's (nothing re-encoded), the clip starts on a key
+// frame at the keyframe the probe named, lasts out − keyframe, and its audio
+// and video start within one audio frame of each other. Skipped, with the
+// reason, on a machine with no ffmpeg.
+
+function has(cmd: string): boolean {
+ try {
+ execFileSync(cmd, ["-version"], { stdio: "ignore" });
+ return true;
+ } catch {
+ return false;
+ }
+}
+const FFMPEG = has("ffmpeg") && has("ffprobe");
+const skip = FFMPEG ? false : "ffmpeg/ffprobe not on PATH";
+
+const dir = mkdtempSync(join(tmpdir(), "local-clip-engine-"));
+process.on("exit", () => rmSync(dir, { recursive: true, force: true }));
+
+const SOURCES = {
+ mp4: [
+ "-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",
+ ],
+ webm: [
+ "-c:v", "libvpx-vp9", "-g", "50", "-keyint_min", "50", "-deadline", "realtime", "-cpu-used", "8", "-b:v", "200k",
+ "-c:a", "libopus", "-b:a", "48k",
+ ],
+} as const;
+
+const TESTSRC = ["-f", "lavfi", "-i", "testsrc2=size=160x90:rate=25:duration=12"];
+const TONE = ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=12"];
+
+function make(kind: keyof typeof SOURCES, extra: string[] = [], name = `source.${kind}`): string {
+ const out = join(dir, name);
+ execFileSync("ffmpeg", ["-v", "error", "-y", ...TESTSRC, ...TONE, ...SOURCES[kind], ...extra, "-shortest", out]);
+ return out;
+}
+
+// Black video with ONE white frame at 6.00 s, silence with ONE 1 kHz beep
+// from 6.00 s: a clip that shifted its audio against its video is caught by
+// where the flash and the beep land.
+function makeFlashBeep(kind: keyof typeof SOURCES): string {
+ const out = join(dir, `flash-beep.${kind}`);
+ execFileSync("ffmpeg", [
+ "-v", "error", "-y",
+ "-f", "lavfi", "-i", "color=c=black:s=160x90:r=25:d=12,drawbox=x=0:y=0:w=iw:h=ih:color=white:t=fill:enable='between(t,5.99,6.01)'",
+ "-f", "lavfi", "-i", "aevalsrc='0.8*sin(2*PI*1000*t)*between(t,6,6.2)':s=48000:d=12",
+ ...SOURCES[kind], "-shortest", out,
+ ]);
+ return out;
+}
+
+// Where, on the clip's own clock, the first bright frame is and the beep starts.
+function flashAndBeep(path: string): { flash: number; beep: number } {
+ const v = execFileSync("ffmpeg", ["-v", "error", "-i", path, "-an", "-vf", "signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-", "-f", "null", "-"], {
+ encoding: "utf8",
+ });
+ let flash = NaN;
+ let pts = NaN;
+ for (const line of v.split("\n")) {
+ const t = /pts_time:([\d.]+)/.exec(line);
+ if (t) pts = Number(t[1]);
+ const y = /YAVG=([\d.]+)/.exec(line);
+ if (y && Number(y[1]) > 128 && Number.isNaN(flash)) flash = pts;
+ }
+ // silencedetect reports on stderr.
+ const err = spawnSync("ffmpeg", ["-v", "info", "-nostats", "-i", path, "-vn", "-af", "silencedetect=n=-30dB:d=0.05", "-f", "null", "-"], {
+ encoding: "utf8",
+ }).stderr;
+ const end = /silence_end: ([\d.]+)/.exec(err);
+ return { flash, beep: end ? Number(end[1]) : NaN };
+}
+
+async function saveToFile(src: Blob, plan: Parameters<typeof saveClip>[1], name: string): Promise<string> {
+ const saved = await saveClip(src, plan, { kind: "memory" }, () => {}, new AbortController().signal);
+ const out = join(dir, name);
+ writeFileSync(out, Buffer.from(await saved.blob!.arrayBuffer()));
+ return out;
+}
+
+type Probe = { streams: { codec_type: string; codec_name: string; start_time: string; duration?: 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,duration:format=duration", "-of", "json", path], {
+ encoding: "utf8",
+ }),
+ );
+}
+function firstFrameIsKey(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";
+}
+
+test("the output support handed to the pure module is the library's own", () => {
+ const s = outputSupport();
+ assert.deepEqual(s.mp4, new Mp4OutputFormat().getSupportedCodecs());
+ assert.deepEqual(s.mov, new MovOutputFormat().getSupportedCodecs());
+ assert.deepEqual(s.mkv, new MkvOutputFormat().getSupportedCodecs());
+ assert.deepEqual(s.webm, new WebMOutputFormat().getSupportedCodecs());
+});
+
+for (const kind of ["mp4", "webm"] as const) {
+ test(`${kind}: a stream copy from the keyframe before the in mark`, { skip }, async () => {
+ const src = await openAsBlob(make(kind));
+ // Marks 5.0 → 9.0 on the cue clock, no offset: the keyframe is 4.0.
+ const probe = await probeClip(src, 5, 9, 0);
+ assert.ok(probe.ok, JSON.stringify(probe));
+ if (!probe.ok) return;
+ const { plan } = probe;
+ assert.equal(plan.format, kind);
+ assert.equal(plan.ext, `.${kind}`);
+ assert.ok(Math.abs(plan.startTs - 4) < 0.05, `keyframe at ${plan.startTs}`);
+ assert.equal(plan.fileIn, 5);
+ assert.equal(plan.fileOut, 9);
+ assert.equal(plan.endTs, 9);
+ assert.ok(Math.abs(plan.fileStart) < 0.05, `the copy begins at ${plan.fileStart}`);
+ assert.ok(plan.duration !== null && Math.abs(plan.duration - 12) < 0.1);
+ assert.equal(plan.hasVideo, true);
+ assert.equal(plan.hasAudio, true);
+ assert.equal(plan.extraTracks, false);
+
+ const progress: number[] = [];
+ const saved = await saveClip(src, plan, { kind: "memory" }, (p) => progress.push(p.fraction), new AbortController().signal);
+ assert.ok(saved.blob);
+ assert.ok(saved.bytes > 0);
+ assert.equal(saved.blob!.size, saved.bytes);
+ assert.ok(progress.length > 0 && progress.at(-1)! >= 0.95, `progress ${progress.at(-1)}`);
+ const out = join(dir, `clip.${kind}`);
+ writeFileSync(out, Buffer.from(await saved.blob!.arrayBuffer()));
+
+ const info = ffprobe(out);
+ const v = info.streams.find((s) => s.codec_type === "video")!;
+ const a = info.streams.find((s) => s.codec_type === "audio")!;
+ // Copied, not re-encoded.
+ assert.equal(v.codec_name, kind === "mp4" ? "h264" : "vp9");
+ assert.equal(a.codec_name, kind === "mp4" ? "aac" : "opus");
+ assert.ok(firstFrameIsKey(out), "the first frame is a key frame");
+ // out − keyframe = 5.0 s, give or take a frame.
+ const duration = Number(info.format.duration);
+ assert.ok(Math.abs(duration - 5) < 0.12, `duration ${duration}`);
+ // A/V in step at the cut: the two start within one audio frame (AAC 1024
+ // samples at 48 kHz ≈ 21.3 ms; Opus 20 ms).
+ const gap = Math.abs(Number(v.start_time) - Number(a.start_time));
+ assert.ok(gap <= 0.0215, `video starts at ${v.start_time}, audio at ${a.start_time}`);
+ });
+}
+
+test("an offset moves the in mark onto a keyframe: the clip starts at the mark", { skip }, async () => {
+ const src = await openAsBlob(make("webm"));
+ // Cue 5.0 + offset 1 = file 6.0, a keyframe.
+ const probe = await probeClip(src, 5, 9, 1);
+ assert.ok(probe.ok);
+ if (!probe.ok) return;
+ assert.equal(probe.plan.fileIn, 6);
+ assert.equal(probe.plan.fileOut, 10);
+ assert.ok(Math.abs(probe.plan.startTs - 6) < 0.05, `keyframe at ${probe.plan.startTs}`);
+});
+
+test("marks outside the file, and a file that is not a container it reads, are refused", { skip }, async () => {
+ const src = await openAsBlob(make("mp4"));
+ const outside = await probeClip(src, 20, 25, 0);
+ assert.deepEqual(outside.ok ? null : outside.refusal.kind, "outside");
+ const wav = join(dir, "tone.wav");
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=duration=2", wav]);
+ const notOurs = await probeClip(await openAsBlob(wav), 0.5, 1.5, 0);
+ assert.deepEqual(notOurs.ok ? null : notOurs.refusal, { kind: "container" });
+});
+
+test("cancel stops the copy, aborts the disk writer and never closes (commits) it", { skip }, async () => {
+ const src = await openAsBlob(make("mp4"));
+ const probe = await probeClip(src, 1, 11, 0);
+ assert.ok(probe.ok);
+ if (!probe.ok) return;
+ const calls: string[] = [];
+ const writable = new WritableStream({
+ async write() {
+ calls.push("write");
+ await new Promise((r) => setTimeout(r, 20));
+ },
+ close() {
+ calls.push("close");
+ },
+ abort() {
+ calls.push("abort");
+ },
+ });
+ const ac = new AbortController();
+ const run = saveClip(src, probe.plan, { kind: "disk", writable }, (p) => {
+ if (p.fraction > 0.2) ac.abort();
+ }, ac.signal);
+ await assert.rejects(run, ClipCancelled);
+ assert.ok(calls.includes("abort"), calls.join(","));
+ assert.ok(!calls.includes("close"), calls.join(","));
+});
+
+test("cancel while a read is in flight answers at once, and hands back no clip", { skip }, async () => {
+ const path = join(dir, "heavy.webm");
+ execFileSync("ffmpeg", [
+ "-v", "error", "-y",
+ "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=25:duration=20",
+ "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=20",
+ "-vf", "noise=alls=80:allf=t", ...SOURCES.webm, "-b:v", "4M", "-minrate", "4M", "-maxrate", "4M", "-shortest", path,
+ ]);
+ const src = await openAsBlob(path);
+ // The file reads slowly (100 ms per 64 KiB), as from a slow disk.
+ const orig = Blob.prototype.stream;
+ Blob.prototype.stream = function (this: Blob) {
+ const reader = orig.call(this).getReader();
+ return new ReadableStream({
+ async pull(c) {
+ const { done, value } = await reader.read();
+ if (done) return c.close();
+ await new Promise((r) => setTimeout(r, Math.ceil(value.byteLength / 65536) * 100));
+ c.enqueue(value);
+ },
+ cancel: (r) => reader.cancel(r),
+ });
+ } as typeof Blob.prototype.stream;
+ try {
+ const probe = await probeClip(src, 2, 19, 0);
+ assert.ok(probe.ok);
+ if (!probe.ok) return;
+ const ac = new AbortController();
+ const run = saveClip(src, probe.plan, { kind: "memory" }, () => {}, ac.signal);
+ await new Promise((r) => setTimeout(r, 400));
+ const at = Date.now();
+ ac.abort();
+ await assert.rejects(run, ClipCancelled);
+ assert.ok(Date.now() - at < 300, `cancel took ${Date.now() - at} ms`);
+ } finally {
+ Blob.prototype.stream = orig;
+ }
+});
+
+for (const kind of ["mp4", "webm"] as const) {
+ test(`${kind}: a flash and a beep at 6.0 s land together at 2.0 s in a clip from the 4.0 s keyframe`, { skip }, async () => {
+ const src = await openAsBlob(makeFlashBeep(kind));
+ const probe = await probeClip(src, 5, 9, 0);
+ assert.ok(probe.ok, JSON.stringify(probe));
+ if (!probe.ok) return;
+ assert.ok(Math.abs(probe.plan.startTs - 4) < 0.05);
+ const { flash, beep } = flashAndBeep(await saveToFile(src, probe.plan, `flash-beep-clip.${kind}`));
+ // One video frame is 40 ms; the beep's onset is within an audio frame.
+ assert.ok(Math.abs(flash - 2) <= 0.045, `the flash is at ${flash}`);
+ assert.ok(Math.abs(beep - 2) <= 0.03, `the beep is at ${beep}`);
+ assert.ok(Math.abs(flash - beep) <= 0.045, `flash ${flash}, beep ${beep}`);
+ });
+}
+
+test("video only (H.264, no audio): a clip from the keyframe", { skip }, async () => {
+ const src = await openAsBlob(make("mp4", ["-an"], "video-only.mp4"));
+ const probe = await probeClip(src, 5, 9, 0);
+ assert.ok(probe.ok, JSON.stringify(probe));
+ if (!probe.ok) return;
+ assert.equal(probe.plan.hasAudio, false);
+ assert.equal(probe.plan.ext, ".mp4");
+ const info = ffprobe(await saveToFile(src, probe.plan, "video-only-clip.mp4"));
+ assert.deepEqual(info.streams.map((s) => s.codec_name), ["h264"]);
+ assert.ok(Math.abs(Number(info.format.duration) - 5) < 0.12, info.format.duration);
+});
+
+for (const [name, args, ext, codec] of [
+ ["audio-only.m4a", ["-vn", "-c:a", "aac", "-b:a", "64k"], ".m4a", "aac"],
+ ["audio-only.webm", ["-vn", "-c:a", "libopus", "-b:a", "48k"], ".webm", "opus"],
+] as const) {
+ test(`audio only (${codec}): a clip from the in mark, within one audio frame`, { skip }, async () => {
+ const path = join(dir, name);
+ execFileSync("ffmpeg", ["-v", "error", "-y", ...TONE, ...args, path]);
+ const src = await openAsBlob(path);
+ const probe = await probeClip(src, 5, 9, 0);
+ assert.ok(probe.ok, JSON.stringify(probe));
+ if (!probe.ok) return;
+ assert.equal(probe.plan.hasVideo, false);
+ assert.equal(probe.plan.ext, ext);
+ assert.ok(probe.plan.startTs <= 5 && 5 - probe.plan.startTs < 0.025, `starts at ${probe.plan.startTs}`);
+ const info = ffprobe(await saveToFile(src, probe.plan, `clip-${name}`));
+ assert.deepEqual(info.streams.map((s) => s.codec_name), [codec]);
+ assert.ok(Math.abs(Number(info.format.duration) - 4) < 0.06, info.format.duration);
+ });
+}
+
+for (const kind of ["mp4", "webm"] as const) {
+ test(`${kind}: a copy whose first timestamp is 3 s is clipped on its own (the <video>) clock`, { skip }, async () => {
+ const src = await openAsBlob(make(kind, ["-output_ts_offset", "3"], `late-start.${kind}`));
+ // Before the copy begins: clamped to its first keyframe, at 3.0.
+ const early = await probeClip(src, 1, 6, 0);
+ assert.ok(early.ok, JSON.stringify(early));
+ if (!early.ok) return;
+ assert.ok(Math.abs(early.plan.fileStart - 3) < 0.025, `begins at ${early.plan.fileStart}`);
+ assert.ok(Math.abs(early.plan.startTs - 3) < 0.001, `starts at ${early.plan.startTs}`);
+ assert.equal(early.plan.endTs, 6);
+ const info = ffprobe(await saveToFile(src, early.plan, `late-start-clip.${kind}`));
+ assert.ok(Math.abs(Number(info.format.duration) - 3) < 0.12, info.format.duration);
+ // Keyframes are every 2 s from 3.0: a mark at 6.0 starts at 5.0.
+ const later = await probeClip(src, 6, 9, 0);
+ assert.ok(later.ok && Math.abs(later.plan.startTs - 5) < 0.001, JSON.stringify(later));
+ });
+}
+
+test("an out mark past the copy's end: the plan's real end is the copy's", { skip }, async () => {
+ const src = await openAsBlob(make("webm"));
+ const probe = await probeClip(src, 8, 20, 0);
+ assert.ok(probe.ok, JSON.stringify(probe));
+ if (!probe.ok) return;
+ assert.ok(Math.abs(probe.plan.endTs - 12) < 0.05, `ends at ${probe.plan.endTs}`);
+ assert.ok(probe.plan.endTs <= probe.plan.fileOut);
+});
+
+test("two prepares of one file: an older refused one never disposes what the newer one reads", { skip }, async () => {
+ const src = await openAsBlob(make("mp4"));
+ const [refused, live] = await Promise.all([probeClip(src, 20, 25, 0), probeClip(src, 5, 9, 0)]);
+ assert.equal(refused.ok ? null : refused.refusal.kind, "outside");
+ assert.ok(live.ok, JSON.stringify(live));
+ if (!live.ok) return;
+ const saved = await saveClip(src, live.plan, { kind: "memory" }, () => {}, new AbortController().signal);
+ assert.ok(saved.blob && saved.blob.size > 0);
+});
+
+test("past the out mark, at most a bounded reorder window of packets is ever held", async () => {
+ // One keyframe, then 300 delta frames (a long-GOP or MediaRecorder file).
+ const all = Array.from(
+ { length: 301 },
+ (_, i) => new EncodedPacket(new Uint8Array(4), i === 0 ? "key" : "delta", i * 0.04, 0.04, i),
+ );
+ let pulled = 0;
+ const sink = {
+ async *packets(start: EncodedPacket) {
+ for (const p of all.slice(start.sequenceNumber)) {
+ pulled++;
+ yield p;
+ }
+ },
+ };
+ const out: EncodedPacket[] = [];
+ for await (const p of clipVideoPackets(sink as never, all[0], 0, 2)) out.push(p);
+ // 50 frames are before 2.0 s; the scan gives up after the window.
+ assert.equal(out.length, 50);
+ assert.ok(pulled <= 50 + HELD_PAST_OUT_MAX + 1, `pulled ${pulled}`);
+ assert.equal(HELD_PAST_OUT_MAX, 16);
+});
+
+test("a clip built in memory stops, with nothing handed over, once its real bytes pass the limit", { skip }, async () => {
+ const src = await openAsBlob(make("webm"));
+ const probe = await probeClip(src, 1, 11, 0);
+ assert.ok(probe.ok);
+ if (!probe.ok) return;
+ await assert.rejects(
+ saveClip(src, probe.plan, { kind: "memory", limit: 20_000 }, () => {}, new AbortController().signal),
+ ClipTooBig,
+ );
+});
+
+test("a completed save to disk writes the whole clip and closes (commits) the file", { skip }, async () => {
+ const src = await openAsBlob(make("mp4"));
+ const probe = await probeClip(src, 5, 9, 0);
+ assert.ok(probe.ok);
+ if (!probe.ok) return;
+ let file = new Uint8Array(0);
+ const calls: string[] = [];
+ const writable = new WritableStream<{ type: "write"; data: Uint8Array; position: number }>({
+ write(chunk) {
+ calls.push("write");
+ const end = chunk.position + chunk.data.byteLength;
+ if (end > file.byteLength) {
+ const grown = new Uint8Array(end);
+ grown.set(file);
+ file = grown;
+ }
+ file.set(chunk.data, chunk.position);
+ },
+ close() {
+ calls.push("close");
+ },
+ abort() {
+ calls.push("abort");
+ },
+ });
+ const saved = await saveClip(src, probe.plan, { kind: "disk", writable }, () => {}, new AbortController().signal);
+ assert.equal(saved.blob, null);
+ assert.equal(saved.bytes, file.byteLength);
+ assert.equal(calls.at(-1), "close");
+ assert.ok(!calls.includes("abort"));
+ const out = join(dir, "disk-clip.mp4");
+ writeFileSync(out, file);
+ const info = ffprobe(out);
+ assert.deepEqual(info.streams.map((s) => s.codec_name).sort(), ["aac", "h264"]);
+ assert.ok(firstFrameIsKey(out));
+ assert.ok(Math.abs(Number(info.format.duration) - 5) < 0.12, info.format.duration);
+});
+
+test("the engine carries a marker string, so its lazy chunk can be told apart", () => {
+ assert.equal(CLIP_ENGINE_MARK, "archilyzer-local-clip-engine");
+});
diff --git a/common/lib/localClipEngine.ts b/common/lib/localClipEngine.ts
@@ -0,0 +1,578 @@
+// THE STREAM COPY (lane browser-clip): a part of the visitor's own file, cut
+// in the browser with Mediabunny (MPL-2.0; export/THIRD-PARTY-NOTICES.md).
+//
+// Loaded ONLY through lib/localClipLoader.ts's dynamic import, when a clip is
+// asked for, so the site's first load does not carry the library.
+//
+// Why not Mediabunny's Conversion API: in 1.45.3 any trim start after a
+// track's first timestamp forces a re-encode (conversion.ts, needsTranscode /
+// needsResample). So the copy is done here with the packet API:
+// - the start is the verified key packet at or before the in mark (T0), and
+// every track is shifted by the same T0, so A/V keep their timing;
+// - video: every packet, in decode order, up to the last one presented
+// before the out mark (the frames it depends on come before it in decode
+// order), stopping at the first key packet past the mark or after a
+// bounded reorder window (HELD_PAST_OUT_MAX packets) past it; packets
+// presented before T0 (open-GOP leading pictures) are dropped;
+// - audio: from the packet at T0 to the out mark, nothing before T0;
+// - the two are fed to the muxer interleaved by timestamp, so it never holds
+// a whole track in memory.
+// The file is read by ranges (BlobSource: File.slice, an 8 MiB cache), never
+// whole. Times are the container's own, which is the <video> element's clock
+// (a copy may begin later than 0). A clip built in memory is written in
+// chunks it keeps as Blob parts (no growing buffer), and stops the moment its
+// real bytes pass the memory limit. Nothing here reaches the network or any
+// storage (components/LocalFilePicker.test.ts reads this source).
+
+import {
+ BlobSource,
+ EncodedAudioPacketSource,
+ EncodedPacketSink,
+ EncodedVideoPacketSource,
+ Input,
+ InputDisposedError,
+ MATROSKA,
+ MP4,
+ MkvOutputFormat,
+ MovOutputFormat,
+ Mp4OutputFormat,
+ Output,
+ QTFF,
+ StreamTarget,
+ UnsupportedInputFormatError,
+ WEBM,
+ WebMOutputFormat,
+ type AudioCodec,
+ type EncodedPacket,
+ type InputFormat,
+ type OutputFormat,
+ type StreamTargetChunk,
+ type VideoCodec,
+} from "mediabunny";
+import {
+ MEMORY_LIMIT_BYTES,
+ MIN_CLIP_SECONDS,
+ chooseOutput,
+ estimateBytes,
+ fileRange,
+ type ContainerFamily,
+ type OutputFormatName,
+ type OutputSupport,
+ type Refusal,
+} from "./localClip";
+
+// Names this module's lazy chunk (export/e2e/local-clip.spec.ts looks for it,
+// since a minifier strips the library's licence header).
+export const CLIP_ENGINE_MARK = "archilyzer-local-clip-engine";
+
+const FORMATS = [MP4, QTFF, MATROSKA, WEBM];
+const VERIFY = { verifyKeyPackets: true } as const;
+// How much media time passes between two progress reports.
+const PROGRESS_STEP_SECONDS = 0.25;
+// Past the out mark, how many packets (decode order) may be held waiting to
+// learn whether an earlier-presented frame needs them: a B-frame reorder
+// window. The scan stops there, so a long-GOP or one-keyframe file never
+// holds the rest of itself in memory.
+export const HELD_PAST_OUT_MAX = 16;
+// A packet presented this close before the out mark still counts as before it.
+const EPSILON = 1e-6;
+
+export type ClipPlan = {
+ format: OutputFormatName;
+ ext: string;
+ hasVideo: boolean;
+ hasAudio: boolean;
+ // The file has tracks beyond the main video and audio; they are left out.
+ extraTracks: boolean;
+ // Where the copy ends (its last timestamp), when the library could tell.
+ duration: number | null;
+ // File time (the <video> clock): where the copy begins, the marks clamped
+ // to the copy, and the clip's REAL first written time (the keyframe) and
+ // real end (the end of the last frame before the out mark, at most the mark).
+ fileStart: number;
+ fileIn: number;
+ fileOut: number;
+ startTs: number;
+ endTs: number;
+ estimate: number;
+};
+
+export type ProbeResult = { ok: true; plan: ClipPlan } | { ok: false; refusal: Refusal };
+
+export type SaveTarget =
+ // Built in memory; refused once its real bytes pass `limit`
+ // (default MEMORY_LIMIT_BYTES).
+ | { kind: "memory"; limit?: number }
+ // A file the visitor picked (showSaveFilePicker's createWritable()).
+ | { kind: "disk"; writable: WritableStream<StreamTargetChunk> };
+
+export type SaveProgress = { fraction: number; doneSeconds: number; totalSeconds: number; bytes: number };
+
+export type SaveResult = { blob: Blob | null; bytes: number; mimeType: string };
+
+export class ClipCancelled extends Error {
+ constructor() {
+ super("The clip was cancelled.");
+ this.name = "ClipCancelled";
+ }
+}
+
+// A clip built in memory passed the limit while it was being made.
+export class ClipTooBig extends Error {
+ constructor(limit: number) {
+ super(`The clip grew past ${limit} bytes in memory.`);
+ this.name = "ClipTooBig";
+ }
+}
+
+// What each output format can hold, from the library itself.
+export function outputSupport(): OutputSupport {
+ return {
+ mp4: new Mp4OutputFormat().getSupportedCodecs(),
+ mov: new MovOutputFormat().getSupportedCodecs(),
+ mkv: new MkvOutputFormat().getSupportedCodecs(),
+ webm: new WebMOutputFormat().getSupportedCodecs(),
+ };
+}
+
+function familyOf(format: InputFormat): ContainerFamily | null {
+ // WEBM is a MATROSKA, so it is asked first.
+ if (format === WEBM) return "webm";
+ if (format === MATROSKA) return "mkv";
+ if (format === QTFF) return "mov";
+ if (format === MP4) return "mp4";
+ return null;
+}
+
+// One input per picked file, shared by the probes and the save so the save
+// does not read the file's headers and index again. Each probe or save holds
+// it for its own lifetime (`users`): a probe that ends never disposes an input
+// another one is still reading. It is kept for the save once a probe
+// succeeds, and let go when nobody holds it and it is not kept.
+type Held = { input: Input; users: number; kept: boolean };
+const held = new WeakMap<Blob, Held>();
+
+function acquire(file: Blob): Held {
+ let h = held.get(file);
+ if (!h || h.input.disposed) {
+ h = { input: new Input({ source: new BlobSource(file), formats: FORMATS }), users: 0, kept: false };
+ held.set(file, h);
+ }
+ h.users++;
+ return h;
+}
+
+async function letGo(file: Blob, h: Held, keep: boolean): Promise<void> {
+ h.users--;
+ if (keep) h.kept = true;
+ if (h.users > 0 || h.kept) return;
+ if (held.get(file) === h) held.delete(file);
+ await release(h.input);
+}
+
+// dispose() on an input whose format was never found leaves an unhandled
+// rejection behind (1.45.3: it chains .then on the failed demuxer promise), so
+// such an input is left to the library's own finalizer, which frees its reads.
+async function release(input: Input): Promise<void> {
+ if (input.disposed) return;
+ if (await input.canRead().catch(() => false)) input.dispose();
+}
+
+// Let go of a file's input (its reads, its cache). The job calls this when the
+// clip is closed, or the copy is cleared or replaced. A probe still reading it
+// lets it go when it ends.
+export async function forgetClipInput(file: Blob): Promise<void> {
+ const h = held.get(file);
+ if (!h) return;
+ held.delete(file);
+ h.kept = false;
+ if (h.users === 0) await release(h.input);
+}
+
+// `p`, or a ClipCancelled the moment `signal` aborts: a cancel never waits on
+// a read or a write the library has in flight. (`p` itself is still handled.)
+function abortable<T>(p: Promise<T>, signal: AbortSignal): Promise<T> {
+ if (signal.aborted) {
+ p.catch(() => {});
+ return Promise.reject(new ClipCancelled());
+ }
+ return new Promise<T>((resolve, reject) => {
+ const onAbort = () => reject(new ClipCancelled());
+ signal.addEventListener("abort", onAbort, { once: true });
+ p.then(
+ (v) => {
+ signal.removeEventListener("abort", onAbort);
+ resolve(v);
+ },
+ (e) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(e);
+ },
+ );
+ });
+}
+
+function isReadError(e: unknown): boolean {
+ const name = (e as { name?: unknown } | null)?.name;
+ return name === "NotReadableError" || name === "NotFoundError";
+}
+
+function refusalFor(e: unknown): Refusal {
+ if (e instanceof UnsupportedInputFormatError) return { kind: "container" };
+ if (isReadError(e)) return { kind: "read" };
+ return { kind: "copy" };
+}
+
+async function keyPacketAt(sink: EncodedPacketSink, t: number): Promise<EncodedPacket | null> {
+ return (await sink.getKeyPacket(t, VERIFY)) ?? (await sink.getFirstKeyPacket(VERIFY));
+}
+
+async function audioStartAt(sink: EncodedPacketSink, t: number): Promise<EncodedPacket | null> {
+ return (await sink.getPacket(t)) ?? (await sink.getFirstPacket());
+}
+
+// Where the last frame presented before `out` ends, over the copied tracks:
+// the clip's real end (the out mark, or the copy's own end before it).
+async function realEnd(sinks: EncodedPacketSink[], out: number): Promise<number> {
+ let end = -Infinity;
+ for (const sink of sinks) {
+ const p = await sink.getPacket(out - EPSILON);
+ if (p) end = Math.max(end, p.timestamp + p.duration);
+ }
+ return Number.isFinite(end) ? Math.min(out, end) : out;
+}
+
+// The marks (cue clock) against the file: the output format, where the clip
+// really starts and ends, its size — or the one refusal that says why not.
+export async function probeClip(file: Blob, cueIn: number, cueOut: number, offset: number): Promise<ProbeResult> {
+ const first = await probeOnce(file, cueIn, cueOut, offset);
+ // Its input was disposed under it (the copy was cleared and picked again
+ // between two awaits): once more, on a fresh input.
+ return first === DISPOSED ? ((await probeOnce(file, cueIn, cueOut, offset)) as ProbeResult) : first;
+}
+
+const DISPOSED = Symbol("disposed");
+
+async function probeOnce(
+ file: Blob,
+ cueIn: number,
+ cueOut: number,
+ offset: number,
+): Promise<ProbeResult | typeof DISPOSED> {
+ const h = acquire(file);
+ const input = h.input;
+ let keep = false;
+ try {
+ const family = familyOf(await input.getFormat());
+ if (!family) return { ok: false, refusal: { kind: "container" } };
+ const tracks = await input.getTracks();
+ const video = await input.getPrimaryVideoTrack();
+ const audio = await input.getPrimaryAudioTrack();
+ const videoCodec = video ? ((await video.getCodec()) ?? "") : null;
+ const audioCodec = audio ? ((await audio.getCodec()) ?? "") : null;
+ const choice = chooseOutput(family, videoCodec, audioCodec, outputSupport());
+ if (!choice.ok) return { ok: false, refusal: { kind: "codec", track: choice.track, codec: choice.codec } };
+ const copied = [video, audio].filter((t) => t !== null);
+
+ let duration: number | null = null;
+ try {
+ const d = await input.computeDuration(copied);
+ duration = Number.isFinite(d) && d > 0 ? d : null;
+ } catch (e) {
+ if (isReadError(e) || e instanceof InputDisposedError) throw e;
+ }
+ let fileStart = 0;
+ try {
+ const t = await input.getFirstTimestamp(copied);
+ fileStart = Number.isFinite(t) && t > 0 ? t : 0;
+ } catch (e) {
+ if (isReadError(e) || e instanceof InputDisposedError) throw e;
+ }
+ const range = fileRange(cueIn, cueOut, offset, fileStart, duration);
+ if (!range.ok) {
+ return {
+ ok: false,
+ refusal: range.reason === "outside" ? { kind: "outside", duration, offset } : { kind: "short" },
+ };
+ }
+
+ const vSink = video ? new EncodedPacketSink(video) : null;
+ const aSink = audio ? new EncodedPacketSink(audio) : null;
+ // The REAL first written time: the keyframe at or before the in mark —
+ // or, before the copy's first keyframe, that keyframe itself.
+ const start = vSink ? await keyPacketAt(vSink, range.fileIn) : await audioStartAt(aSink!, range.fileIn);
+ if (!start) return { ok: false, refusal: { kind: "copy" } };
+ const startTs = start.timestamp;
+ // The copy's first keyframe comes after the out mark.
+ if (!(range.fileOut - startTs >= MIN_CLIP_SECONDS)) return { ok: false, refusal: { kind: "no-key" } };
+ const endTs = await realEnd([vSink, aSink].filter((x) => x !== null), range.fileOut);
+ keep = true;
+ return {
+ ok: true,
+ plan: {
+ format: choice.format,
+ ext: choice.ext,
+ hasVideo: video !== null,
+ hasAudio: audio !== null,
+ extraTracks: tracks.length > copied.length,
+ duration,
+ fileStart,
+ fileIn: range.fileIn,
+ fileOut: range.fileOut,
+ startTs,
+ endTs,
+ estimate: estimateBytes(file.size, duration, endTs - startTs),
+ },
+ };
+ } catch (e) {
+ if (e instanceof InputDisposedError) return DISPOSED;
+ return { ok: false, refusal: refusalFor(e) };
+ } finally {
+ // Kept for the save; a refusal lets it go, unless another holds it.
+ await letGo(file, h, keep);
+ }
+}
+
+const shift = (p: EncodedPacket, t0: number) => p.clone({ timestamp: Math.max(0, p.timestamp - t0) });
+
+// The video packets of the clip, in decode order, shifted by `t0`. Packets
+// presented at or after the out mark are held until a later packet (in decode
+// order) presented before it shows they are needed (a B-frame before the mark
+// refers to the P-frame after it) — at most HELD_PAST_OUT_MAX of them, then the
+// scan stops. (Exported for its test.)
+export async function* clipVideoPackets(sink: EncodedPacketSink, key: EncodedPacket, t0: number, out: number) {
+ const held: EncodedPacket[] = [];
+ for await (const p of sink.packets(key, undefined, VERIFY)) {
+ if (p.timestamp < out) {
+ for (const h of held) yield h;
+ held.length = 0;
+ if (p.timestamp >= t0) yield shift(p, t0);
+ } else {
+ if (p.type === "key" && p.sequenceNumber !== key.sequenceNumber) return;
+ if (held.length >= HELD_PAST_OUT_MAX) return;
+ held.push(shift(p, t0));
+ }
+ }
+}
+
+async function* audioPackets(sink: EncodedPacketSink, first: EncodedPacket, t0: number, out: number) {
+ for await (const p of sink.packets(first)) {
+ if (p.timestamp >= out) return;
+ if (p.timestamp < t0) continue;
+ yield shift(p, t0);
+ }
+}
+
+function outputFormat(name: OutputFormatName): OutputFormat {
+ // MP4/MOV put their index last, in memory as on disk: "in-memory" fast start
+ // would hold every sample until the end, a third copy of the clip.
+ if (name === "mp4") return new Mp4OutputFormat({ fastStart: false });
+ if (name === "mov") return new MovOutputFormat({ fastStart: false });
+ if (name === "webm") return new WebMOutputFormat();
+ return new MkvOutputFormat();
+}
+
+// The disk writer behind a door we hold: on cancel or failure the writer is
+// ABORTED (a picked file's changes are discarded), and the muxer's later
+// close() is then a no-op — it would otherwise commit a half-written file.
+function guardWritable(dest: WritableStream<StreamTargetChunk>) {
+ const writer = dest.getWriter();
+ let stopped = false;
+ const stream = new WritableStream<StreamTargetChunk>({
+ write: (chunk) => (stopped ? undefined : writer.write(chunk)),
+ close: () => (stopped ? undefined : writer.close()),
+ abort: (reason) => {
+ if (stopped) return;
+ stopped = true;
+ return writer.abort(reason);
+ },
+ });
+ return {
+ stream,
+ abort: async () => {
+ if (stopped) return;
+ stopped = true;
+ await writer.abort().catch(() => {});
+ },
+ };
+}
+
+// The in-memory clip, written as the library's chunks and kept as Blob parts:
+// appends are kept as they come, a write over bytes already kept (a header
+// patched at the end) is copied into them. The real size is checked on every
+// write; past `limit` the writes stop and `overLimit` is set.
+function memoryParts(limit: number) {
+ const parts: Uint8Array<ArrayBuffer>[] = [];
+ const starts: number[] = [];
+ let size = 0;
+ let overLimit = false;
+ const patch = (data: Uint8Array, position: number) => {
+ // Copy `data` into the kept parts it overlaps.
+ for (let i = 0; i < parts.length; i++) {
+ const a = Math.max(position, starts[i]);
+ const b = Math.min(position + data.byteLength, starts[i] + parts[i].byteLength);
+ if (a < b) parts[i].set(data.subarray(a - position, b - position), a - starts[i]);
+ }
+ };
+ const stream = new WritableStream<StreamTargetChunk>({
+ write(chunk) {
+ const { data, position } = chunk;
+ const end = position + data.byteLength;
+ if (Math.max(size, end) > limit) {
+ overLimit = true;
+ throw new ClipTooBig(limit);
+ }
+ if (position < size) patch(data.subarray(0, Math.min(data.byteLength, size - position)), position);
+ if (end <= size) return;
+ if (position > size) {
+ // A gap (never written by these muxers, but cheap to be right about).
+ parts.push(new Uint8Array(position - size));
+ starts.push(size);
+ size = position;
+ }
+ const tail = data.subarray(size - position);
+ // A view into a bigger buffer would keep all of it alive: copy it.
+ const own = tail.byteOffset === 0 && tail.byteLength === tail.buffer.byteLength ? tail : tail.slice();
+ parts.push(own);
+ starts.push(size);
+ size = end;
+ },
+ });
+ return {
+ stream,
+ get overLimit() {
+ return overLimit;
+ },
+ blob: (type: string) => new Blob(parts, { type }),
+ drop: () => {
+ parts.length = 0;
+ starts.length = 0;
+ },
+ };
+}
+
+type Head<T> = IteratorResult<T, void>;
+
+// Copy the planned clip into the target. Resolves with the clip (a Blob when
+// built in memory); rejects with ClipCancelled when `signal` aborts, having
+// aborted a disk writer and released everything.
+export async function saveClip(
+ file: Blob,
+ plan: ClipPlan,
+ target: SaveTarget,
+ onProgress: (p: SaveProgress) => void,
+ signal: AbortSignal,
+): Promise<SaveResult> {
+ const h = acquire(file);
+ const input = h.input;
+ const guard = target.kind === "disk" ? guardWritable(target.writable) : null;
+ const memory = target.kind === "memory" ? memoryParts(target.limit ?? MEMORY_LIMIT_BYTES) : null;
+ const w = <T,>(p: Promise<T>) => abortable(p, signal);
+ let output: Output | null = null;
+ try {
+ if (signal.aborted) throw new ClipCancelled();
+ const video = plan.hasVideo ? await w(input.getPrimaryVideoTrack()) : null;
+ const audio = plan.hasAudio ? await w(input.getPrimaryAudioTrack()) : null;
+ const vSink = video ? new EncodedPacketSink(video) : null;
+ const aSink = audio ? new EncodedPacketSink(audio) : null;
+ // The same start the probe found (the same calls on the same file).
+ const key = vSink ? await w(keyPacketAt(vSink, plan.fileIn)) : null;
+ const aFirst = aSink ? await w(audioStartAt(aSink, key ? key.timestamp : plan.fileIn)) : null;
+ const t0 = key ? key.timestamp : (aFirst?.timestamp ?? plan.startTs);
+ const total = Math.max(1e-6, plan.endTs - t0);
+
+ const outTarget = new StreamTarget(memory ? memory.stream : guard!.stream, { chunked: true });
+ let bytes = 0;
+ outTarget.on("write", ({ end }) => {
+ if (end > bytes) bytes = end;
+ });
+ output = new Output({ format: outputFormat(plan.format), target: outTarget });
+ const tooBig = () => {
+ if (memory && (memory.overLimit || bytes > (target.kind === "memory" ? (target.limit ?? MEMORY_LIMIT_BYTES) : Infinity))) {
+ throw new ClipTooBig(target.kind === "memory" ? (target.limit ?? MEMORY_LIMIT_BYTES) : 0);
+ }
+ };
+
+ let vSource: EncodedVideoPacketSource | null = null;
+ let aSource: EncodedAudioPacketSource | null = null;
+ let vMeta: EncodedVideoChunkMetadata | undefined;
+ let aMeta: EncodedAudioChunkMetadata | undefined;
+ if (video && key) {
+ vSource = new EncodedVideoPacketSource((await w(video.getCodec())) as VideoCodec);
+ const rotation = await w(video.getRotation());
+ output.addVideoTrack(vSource, rotation && (plan.format === "mp4" || plan.format === "mov") ? { rotation } : {});
+ vMeta = { decoderConfig: ((await w(video.getDecoderConfig())) as VideoDecoderConfig | null) ?? undefined };
+ }
+ if (audio && aFirst) {
+ aSource = new EncodedAudioPacketSource((await w(audio.getCodec())) as AudioCodec);
+ output.addAudioTrack(aSource);
+ aMeta = { decoderConfig: ((await w(audio.getDecoderConfig())) as AudioDecoderConfig | null) ?? undefined };
+ }
+ if (!vSource && !aSource) throw new Error(`${CLIP_ENGINE_MARK}: nothing to copy`);
+ await w(output.start());
+
+ const vIt = vSink && key ? clipVideoPackets(vSink, key, t0, plan.fileOut) : null;
+ const aIt = aSink && aFirst ? audioPackets(aSink, aFirst, t0, plan.fileOut) : null;
+ const done: Head<EncodedPacket> = { done: true, value: undefined };
+ let v: Head<EncodedPacket> = vIt ? await w(vIt.next()) : done;
+ let a: Head<EncodedPacket> = aIt ? await w(aIt.next()) : done;
+ let reached = 0;
+ let reported = -Infinity;
+ while (!v.done || !a.done) {
+ if (signal.aborted) throw new ClipCancelled();
+ tooBig();
+ const takeVideo = !v.done && (a.done || v.value.timestamp <= a.value.timestamp);
+ if (takeVideo && !v.done) {
+ await w(vSource!.add(v.value, vMeta));
+ reached = Math.max(reached, v.value.timestamp + v.value.duration);
+ v = await w(vIt!.next());
+ } else if (!a.done) {
+ await w(aSource!.add(a.value, aMeta));
+ if (!vSource) reached = Math.max(reached, a.value.timestamp + a.value.duration);
+ a = await w(aIt!.next());
+ }
+ if (reached - reported >= PROGRESS_STEP_SECONDS) {
+ reported = reached;
+ onProgress({ fraction: Math.min(1, reached / total), doneSeconds: Math.min(reached, total), totalSeconds: total, bytes });
+ }
+ }
+ vSource?.close();
+ aSource?.close();
+ const mimeType = await w(output.getMimeType());
+ await w(output.finalize());
+ tooBig();
+ if (signal.aborted) throw new ClipCancelled();
+ onProgress({ fraction: 1, doneSeconds: total, totalSeconds: total, bytes });
+ // Only now, with the copy complete, does the clip exist as a Blob.
+ const blob = memory ? memory.blob(mimeType) : null;
+ memory?.drop();
+ return { blob, bytes: blob ? blob.size : bytes, mimeType };
+ } catch (e) {
+ // A disk writer is aborted before anything is said; the rest is released
+ // behind (the input first: a read in flight is what the copy waits on).
+ await guard?.abort();
+ memory?.drop();
+ const out = output as Output | null;
+ if (held.get(file) === h) held.delete(file);
+ h.kept = false;
+ void (async () => {
+ await release(input);
+ await out?.cancel().catch(() => {});
+ })();
+ if (signal.aborted || e instanceof ClipCancelled || e instanceof InputDisposedError) throw new ClipCancelled();
+ if (memory?.overLimit || e instanceof ClipTooBig) throw new ClipTooBig(target.kind === "memory" ? (target.limit ?? MEMORY_LIMIT_BYTES) : 0);
+ throw e;
+ } finally {
+ // The save is the input's last use: let it go once nobody holds it (on a
+ // cancel it was released above, and nothing here waits on it).
+ h.kept = false;
+ if (signal.aborted) h.users--;
+ else await letGo(file, h, false);
+ }
+}
+
+// What the panel says when a save fails for a reason other than a cancel.
+export function saveFailure(e: unknown, canSaveToDisk: boolean): Refusal {
+ if (e instanceof ClipTooBig) return { kind: "grew", canSaveToDisk };
+ return isReadError(e) ? { kind: "read" } : { kind: "copy" };
+}
diff --git a/common/lib/localClipJob.ts b/common/lib/localClipJob.ts
@@ -0,0 +1,233 @@
+// THE ONE CLIP JOB OF THE VISITOR'S OWN COPY (lane browser-clip).
+//
+// A module store, not component state: Esc collapses the modal to the
+// mini-player and unmounts the clip panel, and that must not cancel a clip
+// being made. Clearing the copy, picking another or changing the video does
+// (the provider calls resetLocalClip).
+//
+// The engine (and with it the library) is loaded through localClipLoader's
+// dynamic import on the first prepare — never before a clip is asked for.
+// A clip built in memory becomes a Blob only once the copy is complete, and is
+// handed over as a download from an object URL; nothing here reaches the
+// network or any storage (components/LocalFilePicker.test.ts reads this source).
+
+import type { ClipPlan, SaveTarget } from "./localClipEngine";
+import { loadClipEngine } from "./localClipLoader";
+import { describeClip, refusalSentence, savePath, type Refusal } from "./localClip";
+
+export type ClipRequest = {
+ file: File;
+ cueIn: number;
+ cueOut: number;
+ offset: number;
+ title: string;
+ slug: string;
+ canSaveToDisk: boolean;
+};
+
+type Prepared = {
+ plan: ClipPlan;
+ name: string;
+ // How "Save clip" saves it: in memory (a download), or to a file the
+ // visitor picks (a big clip, on a browser that can). A browser that can
+ // also offers the file for a small clip ("Save to a file…").
+ path: "memory" | "disk";
+ canSaveToDisk: boolean;
+ // From describeClip, one set of facts: the range the clip holds, where it
+ // really starts, where it ends when that is before the out mark.
+ range: string;
+ start: string;
+ end: string | null;
+};
+
+export type ClipJobState =
+ | { phase: "idle" }
+ | { phase: "preparing"; key: string }
+ | ({ phase: "ready"; key: string } & Prepared)
+ // `retry`: the refusal may not hold the next time (a read that failed, a
+ // copy that broke), so asking for the same key again prepares again.
+ | { phase: "refused"; key: string; sentence: string; retry: boolean }
+ | ({ phase: "saving"; key: string; fraction: number; doneSeconds: number; totalSeconds: number; to: "memory" | "disk" } & Prepared)
+ | { phase: "done"; key: string; name: string; bytes: number; path: "memory" | "disk" }
+ | { phase: "cancelled"; key: string; path: "memory" | "disk" }
+ | { phase: "failed"; key: string; sentence: string };
+
+const IDLE: ClipJobState = { phase: "idle" };
+// How long a finished in-memory clip's object URL stays alive for the
+// download, unless a new clip or clearing the copy lets it go first.
+const DOWNLOAD_URL_LIFETIME_MS = 5 * 60_000;
+
+type Engine = Awaited<ReturnType<typeof loadClipEngine>>;
+
+let state: ClipJobState = IDLE;
+let engine: Engine | null = null;
+let current: ClipRequest | null = null;
+let token = 0;
+let saving: AbortController | null = null;
+let downloadUrl: string | null = null;
+let downloadTimer: ReturnType<typeof setTimeout> | null = null;
+// The last key whose transient refusal was prepared again: once, not forever.
+let retriedKey: string | null = null;
+const listeners = new Set<() => void>();
+const fileIds = new WeakMap<File, number>();
+let nextFileId = 1;
+
+function set(next: ClipJobState) {
+ state = next;
+ for (const l of listeners) l();
+}
+
+export function subscribeLocalClip(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+export function getLocalClipState(): ClipJobState {
+ return state;
+}
+
+export function getIdleLocalClipState(): ClipJobState {
+ return IDLE;
+}
+
+// What a prepared clip depends on: the file, the marks, the offset.
+export function clipKey(req: Pick<ClipRequest, "file" | "cueIn" | "cueOut" | "offset">): string {
+ let id = fileIds.get(req.file);
+ if (id === undefined) {
+ id = nextFileId++;
+ fileIds.set(req.file, id);
+ }
+ return `${id}|${req.cueIn}|${req.cueOut}|${req.offset}`;
+}
+
+function revokeDownload() {
+ if (downloadTimer !== null) clearTimeout(downloadTimer);
+ downloadTimer = null;
+ if (downloadUrl) URL.revokeObjectURL(downloadUrl);
+ downloadUrl = null;
+}
+
+const transient = (r: Refusal) => r.kind === "read" || r.kind === "copy";
+
+function refuse(key: string, r: Refusal) {
+ const retry = transient(r) && retriedKey !== key;
+ set({ phase: "refused", key, sentence: refusalSentence(r), retry });
+}
+
+// Probe the file for these marks: where the clip really starts and ends, its
+// name and how it will be saved — or the sentence that says why it cannot be.
+export async function prepareLocalClip(req: ClipRequest): Promise<void> {
+ if (state.phase === "saving") return;
+ const key = clipKey(req);
+ if (state.phase === "refused" && state.key === key && state.retry) retriedKey = key;
+ const mine = ++token;
+ current = req;
+ set({ phase: "preparing", key });
+ try {
+ engine ??= await loadClipEngine();
+ const probe = await engine.probeClip(req.file, req.cueIn, req.cueOut, req.offset);
+ if (mine !== token) return;
+ if (!probe.ok) return refuse(key, probe.refusal);
+ const { plan } = probe;
+ const path = savePath(plan.estimate, req.canSaveToDisk);
+ if (path === "too-big") return refuse(key, { kind: "too-big", bytes: plan.estimate });
+ const words = describeClip({
+ cueIn: req.cueIn,
+ cueOut: req.cueOut,
+ offset: req.offset,
+ fileStart: plan.fileStart,
+ startTs: plan.startTs,
+ endTs: plan.endTs,
+ title: req.title,
+ slug: req.slug,
+ ext: plan.ext,
+ });
+ set({ phase: "ready", key, plan, path, canSaveToDisk: req.canSaveToDisk, ...words });
+ } catch {
+ if (mine !== token) return;
+ refuse(key, { kind: "copy" });
+ }
+}
+
+function startDownload(blob: Blob, name: string) {
+ revokeDownload();
+ downloadUrl = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = downloadUrl;
+ a.download = name;
+ a.rel = "noopener";
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ downloadTimer = setTimeout(revokeDownload, DOWNLOAD_URL_LIFETIME_MS);
+}
+
+// Make the prepared clip. `target` is memory (a download when it is done) or
+// a file the visitor has just picked to write to.
+export async function saveLocalClip(target: SaveTarget): Promise<void> {
+ if (state.phase !== "ready" || !current) return;
+ const prepared = state;
+ const req = current;
+ const mine = ++token;
+ const ac = new AbortController();
+ saving = ac;
+ const { phase: _phase, ...rest } = prepared;
+ void _phase;
+ set({ ...rest, phase: "saving", to: target.kind, fraction: 0, doneSeconds: 0, totalSeconds: prepared.plan.endTs - prepared.plan.startTs });
+ try {
+ const eng = (engine ??= await loadClipEngine());
+ try {
+ const result = await eng.saveClip(
+ req.file,
+ prepared.plan,
+ target,
+ (p) => {
+ if (mine !== token || state.phase !== "saving") return;
+ set({ ...state, fraction: p.fraction, doneSeconds: p.doneSeconds, totalSeconds: p.totalSeconds });
+ },
+ ac.signal,
+ );
+ if (mine !== token) return;
+ if (result.blob) startDownload(result.blob, prepared.name);
+ set({ phase: "done", key: prepared.key, name: prepared.name, bytes: result.bytes, path: target.kind });
+ } catch (e) {
+ if (mine !== token) return;
+ if (e instanceof eng.ClipCancelled) set({ phase: "cancelled", key: prepared.key, path: target.kind });
+ else set({ phase: "failed", key: prepared.key, sentence: refusalSentence(eng.saveFailure(e, req.canSaveToDisk)) });
+ }
+ } finally {
+ if (saving === ac) saving = null;
+ }
+}
+
+// Stop a clip being made. Nothing is handed over as finished: an in-memory
+// clip never becomes a Blob, a disk writer is aborted, not closed.
+export function cancelLocalClip(): void {
+ saving?.abort();
+}
+
+function forget(): "memory" | "disk" | null {
+ token++;
+ const was = state.phase === "saving" ? state.to : null;
+ saving?.abort();
+ saving = null;
+ if (engine && current) void engine.forgetClipInput(current.file);
+ current = null;
+ if (state.phase !== "idle") set(IDLE);
+ return was;
+}
+
+// The panel was closed: any clip being made is cancelled (its path is
+// returned, so the panel can say so), but a finished clip's download URL is
+// left to its timer — the browser may still be reading it.
+export function closeLocalClip(): "memory" | "disk" | null {
+ return forget();
+}
+
+// Forget the job entirely (the copy was cleared or replaced, the video
+// changed): any clip being made is cancelled, and a finished one's download
+// URL is let go.
+export function resetLocalClip(): void {
+ forget();
+ revokeDownload();
+}
diff --git a/common/lib/localClipLoader.ts b/common/lib/localClipLoader.ts
@@ -0,0 +1,8 @@
+// The ONE door to the clipper's engine (lane browser-clip): a dynamic import,
+// so the engine and the library it bundles are fetched only when a visitor
+// asks for a clip of their own copy, never on the site's first load.
+// components/LocalFilePicker.test.ts holds this file to exactly this import.
+
+export function loadClipEngine() {
+ return import("./localClipEngine");
+}
diff --git a/common/package.json b/common/package.json
@@ -110,6 +110,7 @@
"lmdb": "^3.5.4",
"lucide-react": "^1.16.0",
"markdown-to-jsx": "^7.7.4",
+ "mediabunny": "1.45.3",
"p-limit": "^7.3.0",
"parse-torrent": "^11.0.24",
"radix-ui": "^1.6.0",
diff --git a/export/CHANGELOG.md b/export/CHANGELOG.md
@@ -1,6 +1,24 @@
# Changelog
## [Unreleased]
+- **Clip my copy: cut a clip from your own file, in the browser.**
+ - With your own copy playing, **Clip my copy** (in the "Your copy" bar) cuts the clip between the **Clip in** and
+ **Clip out** marks from that file. The marks are on the transcript's clock; your offset is applied.
+ - It is a stream copy, so there is no re-encode and the quality is the file's own. A clip therefore starts on a
+ keyframe, and before you save, the page says where: "Starts 2.4 s earlier, at the nearest keyframe (0:05:09.6)."
+ or "Starts at your Clip in mark." A mark outside your copy says what is really written instead: "Your copy
+ begins at 0:00:30.0, after your Clip in mark; the clip starts there." or "Your copy ends at 0:41:58.2, before
+ your Clip out mark; the clip ends there.", and the range and the file name agree. Times are your file's own
+ clock, the one its player shows, even when the file does not start at 0.
+ - It takes MP4, MOV, M4A, WebM and MKV. A file it cannot copy gets one sentence saying why. A clip keeps its
+ container (MP4 falls back to MOV, WebM to MKV, when a codec needs it).
+ - The saved file is named from the video's title and the clip's real times, e.g.
+ `Some-Title_00h05m09s-00h06m04s.mp4`, never from your file's name. A clip up to 256 MB is built in the browser's
+ memory and downloaded (and stopped, with a sentence, if it grows past that while it is made); in a browser that
+ can save straight to disk (Chromium-based), **Save to a file…** writes it to a file you pick, which is how a clip
+ over 128 MB is always saved there. Progress and **Cancel** are shown, and a cancelled clip is never handed over.
+ - The file is read in pieces, never whole, and nothing about it leaves the browser. The clipping library
+ (Mediabunny 1.45.3, MPL-2.0; `export/THIRD-PARTY-NOTICES.md`) is loaded only when you ask for a clip.
- **A video whose source is no longer public says so, with the day, and mounts no dead player.**
- A members-only, private or removed video gets one sentence in the player's place, e.g. "This stream is no
longer public on YouTube (members-only; first seen 19 Nov 2026). The transcript is kept here." The day is
diff --git a/export/THIRD-PARTY-NOTICES.md b/export/THIRD-PARTY-NOTICES.md
@@ -0,0 +1,397 @@
+# Third-party notices (export site)
+
+The export site's built pages include third-party code. This file names what
+is bundled under a licence other than the project's own (MIT, `LICENSE` at the
+root of the repository).
+
+## Mediabunny 1.45.3
+
+- What: a pure-TypeScript media toolkit. The site's "Clip my copy" control
+ (the visitor's own file, cut in the browser by a stream copy) loads it on
+ demand, as a separate script chunk; it is not part of the first load.
+- Package: `mediabunny@1.45.3` on npm, unmodified.
+- Copyright: Copyright (c) 2026-present, Vanilagy and contributors.
+- Licence: Mozilla Public License 2.0 (MPL-2.0). The full text follows.
+- Source Code Form: the npm package `mediabunny@1.45.3` (it ships its
+ TypeScript source under `src/`), and the upstream repository at that
+ version's tag, https://github.com/Vanilagy/mediabunny/tree/v1.45.3.
+- This code is used unmodified. The page that offers the clip names the library,
+ its licence and where its source is.
+
+---
+
+```text
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+ means each individual or legal entity that creates, contributes to
+ the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+ means the combination of the Contributions of others (if any) used
+ by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+ means Source Code Form to which the initial Contributor has attached
+ the notice in Exhibit A, the Executable Form of such Source Code
+ Form, and Modifications of such Source Code Form, in each case
+ including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ (a) that the initial Contributor has attached the notice described
+ in Exhibit B to the Covered Software; or
+
+ (b) that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the
+ terms of a Secondary License.
+
+1.6. "Executable Form"
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+ means a work that combines Covered Software with other material, in
+ a separate file or files, that is not Covered Software.
+
+1.8. "License"
+ means this document.
+
+1.9. "Licensable"
+ means having the right to grant, to the maximum extent possible,
+ whether at the time of the initial grant or subsequently, any and
+ all of the rights conveyed by this License.
+
+1.10. "Modifications"
+ means any of the following:
+
+ (a) any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered
+ Software; or
+
+ (b) any new file in Source Code Form that contains any Covered
+ Software.
+
+1.11. "Patent Claims" of a Contributor
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the
+ License, by the making, using, selling, offering for sale, having
+ made, import, or transfer of either its Contributions or its
+ Contributor Version.
+
+1.12. "Secondary License"
+ means either the GNU General Public License, Version 2.0, the GNU
+ Lesser General Public License, Version 2.1, the GNU Affero General
+ Public License, Version 3.0, or any later versions of those
+ licenses.
+
+1.13. "Source Code Form"
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that
+ controls, is controlled by, or is under common control with You. For
+ purposes of this definition, "control" means (a) the power, direct
+ or indirect, to cause the direction or management of such entity,
+ whether by contract or otherwise, or (b) ownership of more than
+ fifty percent (50%) of the outstanding shares or beneficial
+ ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+ for sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+ or
+
+(b) for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+ Form, as described in Section 3.1, and You must inform recipients of
+ the Executable Form how they can obtain a copy of such Source Code
+ Form by reasonable means in a timely manner, at a charge no more
+ than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter
+ the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+* *
+* 6. Disclaimer of Warranty *
+* ------------------------- *
+* *
+* Covered Software is provided under this License on an "as is" *
+* basis, without warranty of any kind, either expressed, implied, or *
+* statutory, including, without limitation, warranties that the *
+* Covered Software is free of defects, merchantable, fit for a *
+* particular purpose or non-infringing. The entire risk as to the *
+* quality and performance of the Covered Software is with You. *
+* Should any Covered Software prove defective in any respect, You *
+* (not any Contributor) assume the cost of any necessary servicing, *
+* repair, or correction. This disclaimer of warranty constitutes an *
+* essential part of this License. No use of any Covered Software is *
+* authorized under this License except under this disclaimer. *
+* *
+************************************************************************
+
+************************************************************************
+* *
+* 7. Limitation of Liability *
+* -------------------------- *
+* *
+* Under no circumstances and under no legal theory, whether tort *
+* (including negligence), contract, or otherwise, shall any *
+* Contributor, or anyone who distributes Covered Software as *
+* permitted above, be liable to You for any direct, indirect, *
+* special, incidental, or consequential damages of any character *
+* including, without limitation, damages for lost profits, loss of *
+* goodwill, work stoppage, computer failure or malfunction, or any *
+* and all other commercial damages or losses, even if such party *
+* shall have been informed of the possibility of such damages. This *
+* limitation of liability shall not apply to liability for death or *
+* personal injury resulting from such party's negligence to the *
+* extent applicable law prohibits such limitation. Some *
+* jurisdictions do not allow the exclusion or limitation of *
+* incidental or consequential damages, so this exclusion and *
+* limitation may not apply to You. *
+* *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+ This Source Code Form is subject to the terms of the Mozilla Public
+ License, v. 2.0. If a copy of the MPL was not distributed with this
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+ This Source Code Form is "Incompatible With Secondary Licenses", as
+ defined by the Mozilla Public License, v. 2.0.
+```
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,592 @@
+import { expect, test, type Page, type Request } from "@playwright/test";
+import { execFileSync, spawnSync } from "node:child_process";
+import { readFileSync, writeFileSync } 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.
+//
+// A flash and a beep at one known moment catch an A/V shift; a stubbed
+// showSaveFilePicker (an in-memory writable in the page) runs the disk path
+// to the end.
+//
+// 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");
+// The engine's marker string (common/lib/localClipEngine.ts, CLIP_ENGINE_MARK):
+// how its lazy chunk is told apart, since a minifier strips licence headers.
+const ENGINE_MARK = "archilyzer-local-clip-engine";
+
+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,
+ ]);
+}
+
+// Black video with ONE white frame at 6.00 s (content time), silence with ONE
+// 1 kHz beep from 6.00 s. `extra` goes to the output (e.g. a later start).
+function makeFlashBeep(path: string, kind: keyof typeof CODECS, extra: string[] = []): void {
+ execFileSync("ffmpeg", [
+ "-v", "error", "-y",
+ "-f", "lavfi", "-i", "color=c=black:s=160x90:r=25:d=12,drawbox=x=0:y=0:w=iw:h=ih:color=white:t=fill:enable='between(t,5.99,6.01)'",
+ "-f", "lavfi", "-i", "aevalsrc='0.8*sin(2*PI*1000*t)*between(t,6,6.2)':s=48000:d=12",
+ ...CODECS[kind].args, ...extra, "-shortest", path,
+ ]);
+}
+
+// Where, on the clip's own clock, the first bright frame is and the beep starts.
+function flashAndBeep(path: string): { flash: number; beep: number } {
+ const v = execFileSync("ffmpeg", ["-v", "error", "-i", path, "-an", "-vf", "signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-", "-f", "null", "-"], {
+ encoding: "utf8",
+ });
+ let flash = NaN;
+ let pts = NaN;
+ for (const line of v.split("\n")) {
+ const t = /pts_time:([\d.]+)/.exec(line);
+ if (t) pts = Number(t[1]);
+ const y = /YAVG=([\d.]+)/.exec(line);
+ if (y && Number(y[1]) > 128 && Number.isNaN(flash)) flash = pts;
+ }
+ const err = spawnSync("ffmpeg", ["-v", "info", "-nostats", "-i", path, "-vn", "-af", "silencedetect=n=-30dB:d=0.05", "-f", "null", "-"], {
+ encoding: "utf8",
+ }).stderr;
+ const end = /silence_end: ([\d.]+)/.exec(err);
+ return { flash, beep: end ? Number(end[1]) : NaN };
+}
+
+// The flash and the beep land together, `at` seconds into the clip.
+function expectInStep(path: string, at: number) {
+ const { flash, beep } = flashAndBeep(path);
+ // One video frame is 40 ms; the beep's onset is within an audio frame.
+ expect(Math.abs(flash - at), `flash at ${flash}`).toBeLessThanOrEqual(0.045);
+ expect(Math.abs(beep - at), `beep at ${beep}`).toBeLessThanOrEqual(0.03);
+ expect(Math.abs(flash - beep), `flash ${flash}, beep ${beep}`).toBeLessThanOrEqual(0.045);
+}
+
+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" });
+// The ONE live region, mounted while a copy plays.
+const clipStatus = (page: Page) => page.getByTestId("local-clip-status");
+const clipToggle = (page: Page) => page.getByRole("button", { name: "Clip my copy" });
+
+// showSaveFilePicker, stubbed with a writable that keeps the file in the page.
+async function stubSavePicker(page: Page) {
+ await page.addInitScript(() => {
+ type Chunk = { type: "write"; data: Uint8Array; position: number };
+ const saved: { name: string | null; calls: string[]; bytes: Uint8Array | null } = { name: null, calls: [], bytes: null };
+ (window as unknown as { __saved: typeof saved }).__saved = saved;
+ (window as unknown as { showSaveFilePicker: unknown }).showSaveFilePicker = async (opts: { suggestedName: string }) => {
+ saved.name = opts.suggestedName;
+ return {
+ createWritable: async () => {
+ let file = new Uint8Array(0);
+ return new WritableStream<Chunk>({
+ write(chunk) {
+ saved.calls.push("write");
+ const end = chunk.position + chunk.data.byteLength;
+ if (end > file.byteLength) {
+ const grown = new Uint8Array(end);
+ grown.set(file);
+ file = grown;
+ }
+ file.set(chunk.data, chunk.position);
+ },
+ close() {
+ saved.calls.push("close");
+ saved.bytes = file;
+ },
+ abort() {
+ saved.calls.push("abort");
+ },
+ });
+ },
+ };
+ };
+ });
+}
+
+async function savedFile(page: Page): Promise<{ name: string | null; calls: string[]; bytes: Buffer | null }> {
+ const r = await page.evaluate(() => {
+ const s = (window as unknown as { __saved: { name: string | null; calls: string[]; bytes: Uint8Array | null } }).__saved;
+ let b64: string | null = null;
+ if (s.bytes) {
+ let bin = "";
+ for (let i = 0; i < s.bytes.length; i += 0x8000) bin += String.fromCharCode(...s.bytes.subarray(i, i + 0x8000));
+ b64 = btoa(bin);
+ }
+ return { name: s.name, calls: s.calls, b64 };
+ });
+ return { name: r.name, calls: r.calls, bytes: r.b64 === null ? null : Buffer.from(r.b64, "base64") };
+}
+
+// Every object URL the page revokes.
+async function spyRevokes(page: Page) {
+ await page.addInitScript(() => {
+ const revoked: string[] = [];
+ (window as unknown as { __revoked: string[] }).__revoked = revoked;
+ const orig = URL.revokeObjectURL.bind(URL);
+ URL.revokeObjectURL = (u: string) => {
+ revoked.push(u);
+ orig(u);
+ };
+ });
+}
+const revoked = (page: Page) => page.evaluate(() => (window as unknown as { __revoked: string[] }).__revoked);
+
+// 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 spyRevokes(page);
+ 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.getByTestId("local-clip-range")).toHaveText("From 0:00:05.0 to 0:00:09.0.");
+ await expect(group.getByTestId("local-clip-end")).toHaveCount(0);
+ // The live region says the same, once.
+ await expect(clipStatus(page)).toContainText("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.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`);
+ await expect(clipStatus(page)).toContainText(`Your browser is saving ${TITLE_BASE}_00h00m04s-00h00m09s.webm`);
+ // Closing the panel leaves the download's URL alive; clearing the copy lets it go.
+ const downloadUrl = d.url();
+ expect(downloadUrl).toMatch(/^blob:/);
+ await group.getByRole("button", { name: "Close the clip" }).click();
+ await expect(clipGroup(page)).toHaveCount(0);
+ expect(await revoked(page)).not.toContain(downloadUrl);
+
+ // 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(ENGINE_MARK));
+ 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(ENGINE_MARK)).toBe(false);
+ await noServiceWorker(page);
+
+ await page.getByRole("button", { name: "Stop using my copy" }).click();
+ await expect.poll(() => revoked(page)).toContain(downloadUrl);
+ });
+
+ 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");
+ makeFlashBeep(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);
+ // The flash and the beep at 6.0 s land together, 2.0 s after the 4.0 s keyframe.
+ expectInStep(out, 2);
+ });
+
+ test("cancel stops the copy and offers nothing as finished", async ({ page }, info) => {
+ // Two slow saves, each cancelled.
+ test.setTimeout(90_000);
+ 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 expect(clipStatus(page)).toHaveText("Cancelled; nothing was saved.");
+ // Cancel is gone, and the focus with it: it lands on "Clip my copy".
+ await expect(clipToggle(page)).toBeFocused();
+
+ // Again, and this time "Clip my copy" is toggled off mid-save: the live
+ // region, still there, says so.
+ await group.getByRole("button", { name: "Close the clip" }).click();
+ await clipToggle(page).click();
+ await expect(clipGroup(page).getByTestId("local-clip-start")).toBeVisible({ timeout: 30_000 });
+ await clipGroup(page).getByRole("button", { name: "Save clip" }).click();
+ await expect(clipGroup(page).getByRole("progressbar", { name: "Saving clip" })).toBeVisible();
+ await clipToggle(page).click();
+ await expect(clipGroup(page)).toHaveCount(0);
+ await expect(clipStatus(page)).toHaveText("Cancelled; nothing was saved.");
+ await page.waitForTimeout(1500);
+ expect(downloads).toBe(0);
+ await noServiceWorker(page);
+ });
+
+ test("to a file you choose: the disk path writes the whole clip, in step, and closes the file", async ({ page }, info) => {
+ const src = info.outputPath("synth-copy.webm");
+ makeFlashBeep(src, "webm");
+ await stubSavePicker(page);
+ await open(page);
+ await pick(page, { name: "my-synth-copy.webm", mimeType: CODECS.webm.mime, buffer: readFileSync(src) });
+ await markClip(page, "clip line five", "clip line nine");
+ await clipToggle(page).click();
+ const group = clipGroup(page);
+ const name = `${TITLE_BASE}_00h00m04s-00h00m09s.webm`;
+ await expect(group.getByTestId("local-clip-name")).toHaveText(name);
+ let downloads = 0;
+ page.on("download", () => downloads++);
+ await group.getByRole("button", { name: "Save the clip to a file you choose" }).click();
+ await expect(group.getByTestId("local-clip-done")).toHaveText(/^Saved Synth-members-stream_00h00m04s-00h00m09s\.webm \(\d+(\.\d)? (KB|MB)\)\.$/);
+ await expect(clipStatus(page)).toContainText(`Saved ${name}`);
+ // Cancel went with the save, and the focus went to "Clip my copy".
+ await expect(clipToggle(page)).toBeFocused();
+ const saved = await savedFile(page);
+ expect(saved.name).toBe(name);
+ expect(saved.calls.at(-1)).toBe("close");
+ expect(saved.calls).not.toContain("abort");
+ expect(downloads).toBe(0);
+ const out = info.outputPath("disk-clip.webm");
+ writeFileSync(out, saved.bytes!);
+ const probe = ffprobe(out);
+ expect(probe.streams.map((s) => s.codec_name).sort()).toEqual(["opus", "vp9"]);
+ expect(firstVideoFrameIsKey(out)).toBe(true);
+ expect(Math.abs(Number(probe.format.duration) - 5)).toBeLessThan(0.12);
+ expectInStep(out, 2);
+ });
+
+ test("a mark outside the copy: the page says where the clip really starts and ends, and the name agrees", 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) });
+ // Marks at cue 0:00 and 0:09, then the offset to −2 s: the in mark is
+ // before the copy begins (its 0.0 s is cue 0:02).
+ await markClip(page, "clip line zero", "clip line nine");
+ await page.getByRole("button", { name: "Offset −1 second" }).click();
+ await page.getByRole("button", { name: "Offset −1 second" }).click();
+ await clipToggle(page).click();
+ const group = clipGroup(page);
+ await expect(group.getByTestId("local-clip-start")).toHaveText(
+ "Your copy begins at 0:00:02.0, after your Clip in mark; the clip starts there.",
+ );
+ await expect(group.getByTestId("local-clip-range")).toHaveText("From 0:00:02.0 to 0:00:09.0, with your offset −2.00 s applied.");
+ await expect(group.getByTestId("local-clip-end")).toHaveCount(0);
+ await expect(group.getByTestId("local-clip-name")).toHaveText(`${TITLE_BASE}_00h00m02s-00h00m09s.webm`);
+ let download = page.waitForEvent("download");
+ await group.getByRole("button", { name: "Save clip" }).click();
+ let out = info.outputPath("clamped-start.webm");
+ await (await download).saveAs(out);
+ // File 0.0 → 7.0.
+ expect(Math.abs(Number(ffprobe(out).format.duration) - 7)).toBeLessThan(0.12);
+ await group.getByRole("button", { name: "Close the clip" }).click();
+
+ // Marks at cue 0:05 and 0:11, then the offset to +2 s: the out mark is
+ // past the copy's end (its 12.0 s is cue 0:10).
+ await markClip(page, "clip line five", "clip line eleven");
+ for (let i = 0; i < 4; i++) await page.getByRole("button", { name: "Offset +1 second" }).click();
+ await clipToggle(page).click();
+ await expect(group.getByTestId("local-clip-end")).toHaveText(
+ "Your copy ends at 0:00:10.0, before your Clip out mark; the clip ends there.",
+ );
+ 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-range")).toHaveText("From 0:00:05.0 to 0:00:10.0, with your offset +2.00 s applied.");
+ await expect(group.getByTestId("local-clip-name")).toHaveText(`${TITLE_BASE}_00h00m04s-00h00m10s.webm`);
+ download = page.waitForEvent("download");
+ await group.getByRole("button", { name: "Save clip" }).click();
+ out = info.outputPath("clamped-end.webm");
+ await (await download).saveAs(out);
+ // File 6.0 → 12.0.
+ expect(Math.abs(Number(ffprobe(out).format.duration) - 6)).toBeLessThan(0.12);
+ });
+
+ test("a copy whose first timestamp is 3 s: the page's times are the <video> clock's", async ({ page }, info) => {
+ const src = info.outputPath("late-start.webm");
+ // The flash and the beep are 6.0 s into the content, so 9.0 s on the file's clock.
+ makeFlashBeep(src, "webm", ["-output_ts_offset", "3"]);
+ await open(page);
+ await pick(page, { name: "my-late-copy.webm", mimeType: CODECS.webm.mime, buffer: readFileSync(src) });
+ // Cue 0:09 shows the flash: the <video> clock is the container's.
+ await cue(page, "clip line nine");
+ await expect.poll(() => video(page).evaluate((v: HTMLVideoElement) => v.currentTime)).toBeCloseTo(9, 2);
+ await expect
+ .poll(
+ () =>
+ video(page).evaluate((v: HTMLVideoElement) => {
+ if (v.seeking || v.readyState < 2) return -1;
+ const c = document.createElement("canvas");
+ c.width = v.videoWidth;
+ c.height = v.videoHeight;
+ const g = c.getContext("2d")!;
+ g.drawImage(v, 0, 0);
+ const d = g.getImageData(0, 0, c.width, c.height).data;
+ let sum = 0;
+ for (let i = 0; i < d.length; i += 4) sum += d[i];
+ return sum / (d.length / 4);
+ }),
+ { timeout: 10_000 },
+ )
+ .toBeGreaterThan(128);
+ // Keyframes are every 2 s from 3.0: cue 0:07 is one.
+ await markClip(page, "clip line seven", "clip line eleven");
+ await clipToggle(page).click();
+ const group = clipGroup(page);
+ await expect(group.getByTestId("local-clip-start")).toHaveText("Starts at your Clip in mark.");
+ await expect(group.getByTestId("local-clip-name")).toHaveText(`${TITLE_BASE}_00h00m07s-00h00m11s.webm`);
+ const download = page.waitForEvent("download");
+ await group.getByRole("button", { name: "Save clip" }).click();
+ const out = info.outputPath("late-start-clip.webm");
+ await (await download).saveAs(out);
+ // The flash and beep the page showed at cue 0:09 are 2.0 s into the clip.
+ expectInStep(out, 2);
+ });
+
+ 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.",
+ );
+ await expect(clipStatus(page)).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();
+ });
+});
diff --git a/export/package.json b/export/package.json
@@ -29,6 +29,7 @@
"@tanstack/react-query": "^5.99.1",
"hls.js": "^1.6.16",
"lucide-react": "^1.16.0",
+ "mediabunny": "1.45.3",
"next": "16.2.3",
"react": "19.2.4",
"react-dom": "19.2.4",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
@@ -68,6 +68,9 @@ importers:
markdown-to-jsx:
specifier: ^7.7.4
version: 7.7.17(react@19.2.4)
+ mediabunny:
+ specifier: 1.45.3
+ version: 1.45.3
next:
specifier: 16.2.3
version: 16.2.3(@babel/core@7.29.0(supports-color@10.2.2))(@playwright/test@1.59.1)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
@@ -199,6 +202,9 @@ importers:
lucide-react:
specifier: ^1.16.0
version: 1.16.0(react@19.2.4)
+ mediabunny:
+ specifier: 1.45.3
+ version: 1.45.3
next:
specifier: 16.2.3
version: 16.2.3(@babel/core@7.29.0(supports-color@10.2.2))(@playwright/test@1.59.1)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
@@ -2382,6 +2388,12 @@ packages:
'@types/d3-timer@3.0.2':
resolution: {integrity: sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==}
+ '@types/dom-mediacapture-transform@0.1.12':
+ resolution: {integrity: sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==}
+
+ '@types/dom-webcodecs@0.1.13':
+ resolution: {integrity: sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==}
+
'@types/estree@1.0.8':
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
@@ -4023,6 +4035,9 @@ packages:
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
engines: {node: '>= 0.4'}
+ mediabunny@1.45.3:
+ resolution: {integrity: sha512-GUCPYjR+5olLM7DRmupCXCmZkkSrKHVl1gyW2RztpObqLfrix19kWGf/9WgWzDW0g49DvfGXpl+zfArCx5HDMQ==}
+
memoize-one@5.2.1:
resolution: {integrity: sha512-zYiwtZUcYyXKo/np96AGZAckk+FWWsUdJ3cHGGmld7+AhvcWmQyGCYUh1hc4Q/pkOhb65dQR/pqCyK0cOaHz4Q==}
@@ -6987,6 +7002,12 @@ snapshots:
'@types/d3-timer@3.0.2': {}
+ '@types/dom-mediacapture-transform@0.1.12':
+ dependencies:
+ '@types/dom-webcodecs': 0.1.13
+
+ '@types/dom-webcodecs@0.1.13': {}
+
'@types/estree@1.0.8': {}
'@types/fs-extra@11.0.4':
@@ -8845,6 +8866,11 @@ snapshots:
math-intrinsics@1.1.0: {}
+ mediabunny@1.45.3:
+ dependencies:
+ '@types/dom-mediacapture-transform': 0.1.12
+ '@types/dom-webcodecs': 0.1.13
+
memoize-one@5.2.1: {}
memory-chunk-store@1.3.5: