Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit e14909070255967ee0a34548bca1ae77f666c489
parent 4942667e0a07dd9f415e9abd3636299e91c1a223
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 19 Nov 2026 17:31:33 -0500

common: a clip's words come from what is really written

Review 1. Every sentence about a prepared clip and its file name now come
from ONE set of facts (describeClip): where the copy begins, the clip's
real first written time (the keyframe, never min(key, in mark)) and its
real end (the last frame before the out mark, at most the mark). A start
clamped to the copy says "Your copy begins at 0:00:30.0, after your Clip
in mark; the clip starts there.", an end past it "Your copy ends at ...,
before your Clip out mark; the clip ends there.", and "From ... to ..."
and the name agree with them. Marks clamp to the copy's own first
timestamp, which is the <video> clock (a copy may begin after 0).

The engine: each probe and save holds the shared input for its own
lifetime, so an older refused probe never disposes what a newer one
reads (and a probe whose input was disposed under it runs once more);
past the out mark at most 16 packets are held, so a long-GOP file never
holds the rest of itself; a clip built in memory is written as Blob
parts through a chunked StreamTarget (no growing buffer, no fast-start
copy), refused above 256 MB estimated, and stopped the moment its real
bytes pass that. An unknown length never reads "0:00:00.0 long"; a copy
whose first keyframe is after the out mark says so.

The panel: one live region stays mounted while a copy plays and its text
changes (the group's own lines are no longer live), so closing the group
during a save still says "Cancelled; nothing was saved."; when Cancel
goes (done, cancelled, failed) with the focus, the focus goes to "Clip
my copy". Closing the panel no longer revokes a finished clip's download
URL (a new clip, clearing the copy or five minutes do). The credit's
source link points at the v1.45.3 tag. A transient refusal is prepared
again, once, when its key is asked for again.

Tests: a flash and a beep at a known time (an A/V shift fails it),
video-only and audio-only sources, a copy starting at 3 s, an out mark
past the end, two prepares at once, the bounded window, the memory
limit, and a completed save to disk.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mcommon/components/LocalClipPanel.tsx | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
Mcommon/lib/localClip.test.ts | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
Mcommon/lib/localClip.ts | 135++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mcommon/lib/localClipEngine.test.ts | 225++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/lib/localClipEngine.ts | 276++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mcommon/lib/localClipJob.ts | 93+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
6 files changed, 757 insertions(+), 190 deletions(-)

diff --git a/common/components/LocalClipPanel.tsx b/common/components/LocalClipPanel.tsx @@ -3,14 +3,14 @@ import { useEffect, useRef, useState, useSyncExternalStore } from "react"; import { ScissorsIcon } from "lucide-react"; import { ControlButton, usePlayer } from "./PlayerProvider"; -import { formatBytes, formatClock } from "../lib/localClip"; +import { cancelledSentence, formatBytes, formatClock } from "../lib/localClip"; import { cancelLocalClip, clipKey, + closeLocalClip, getIdleLocalClipState, getLocalClipState, prepareLocalClip, - resetLocalClip, saveLocalClip, subscribeLocalClip, type ClipJobState, @@ -22,6 +22,10 @@ import { // 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. @@ -29,6 +33,7 @@ import { 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; @@ -55,10 +60,43 @@ function extOf(name: string): string { 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; @@ -66,13 +104,15 @@ export function LocalClipPanel() { const offset = localFile?.offset ?? 0; // Prepare (again) whenever what the clip depends on changes, unless one is - // being made. + // 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" || ("key" in st && st.key === key)) return; + if (st.phase === "saving") return; + if ("key" in st && st.key === key && !(st.phase === "refused" && st.retry)) return; void prepareLocalClip({ file, cueIn: clipStart!, @@ -84,14 +124,23 @@ export function LocalClipPanel() { }); }, [shown, key, file, data, clipStart, clipEnd, offset]); - // Saving moves the focus to Cancel. + // 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(); + 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 = () => { - resetLocalClip(); + const cancelled = closeLocalClip(); + setClosedNote(cancelled ? cancelledSentence(cancelled) : ""); setOpen(false); requestAnimationFrame(() => triggerRef.current?.querySelector("button")?.focus()); }; @@ -130,9 +179,16 @@ export function LocalClipPanel() { disabled={!canClip} highlight={shown} aria-expanded={shown} - onClick={() => (shown ? close() : setOpen(true))} + 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} @@ -154,7 +210,7 @@ export function LocalClipPanel() { </a>{" "} ·{" "} <a - href="https://github.com/Vanilagy/mediabunny" + href={LIBRARY_SOURCE} target="_blank" rel="noopener noreferrer" className="underline underline-offset-2 hover:text-white" @@ -187,7 +243,7 @@ function ClipBody({ if (!canClip && job.phase !== "saving") { return ( <> - <p aria-live="polite">Mark Clip in and Clip out first.</p> + <p>Mark Clip in and Clip out first.</p> <Actions>{closeButton}</Actions> </> ); @@ -197,7 +253,7 @@ function ClipBody({ case "preparing": return ( <> - <p role="status" aria-live="polite">Finding the keyframe…</p> + <p>Finding the keyframe…</p> <Actions>{closeButton}</Actions> </> ); @@ -205,7 +261,7 @@ function ClipBody({ case "failed": return ( <> - <p role="alert" data-testid="local-clip-refusal" className="text-rose-200"> + <p data-testid="local-clip-refusal" className="text-rose-200"> {job.sentence} </p> <Actions>{closeButton}</Actions> @@ -214,11 +270,16 @@ function ClipBody({ case "ready": return ( <> - <div aria-live="polite" data-testid="local-clip-ready" className="flex flex-col gap-0.5"> - <p>{job.range}</p> + <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"> @@ -262,28 +323,14 @@ function ClipBody({ case "done": return ( <> - <p role="status" data-testid="local-clip-done"> - {job.path === "disk" ? ( - <> - Saved <span className="font-mono text-white">{job.name}</span> ({formatBytes(job.bytes)}). - </> - ) : ( - <> - Your browser is saving <span className="font-mono text-white">{job.name}</span> ({formatBytes(job.bytes)}). - </> - )} - </p> + <p data-testid="local-clip-done">{doneSentence(job)}</p> <Actions>{closeButton}</Actions> </> ); case "cancelled": return ( <> - <p role="status" data-testid="local-clip-cancelled"> - {job.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."} - </p> + <p data-testid="local-clip-cancelled">{cancelledSentence(job.path)}</p> <Actions>{closeButton}</Actions> </> ); diff --git a/common/lib/localClip.test.ts b/common/lib/localClip.test.ts @@ -1,18 +1,17 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { - BLOB_LIMIT_BYTES, DISK_SAVE_ABOVE_BYTES, + MEMORY_LIMIT_BYTES, chooseOutput, clipFileName, + describeClip, estimateBytes, fileRange, formatBytes, formatClock, - rangeSentence, refusalSentence, savePath, - startSentence, type OutputSupport, } from "./localClip"; @@ -20,24 +19,28 @@ import { // 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, 12), { ok: true, fileIn: 5, fileOut: 9 }); - assert.deepEqual(fileRange(5, 9, 1, 12), { ok: true, fileIn: 6, fileOut: 10 }); + 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, 12), { ok: true, fileIn: 0, fileOut: 2 }); + 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, 12), { ok: true, fileIn: 10, fileOut: 12 }); - // An unknown duration clamps nothing at the top. - assert.deepEqual(fileRange(10, 20, 0, null), { ok: true, fileIn: 10, fileOut: 20 }); + 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, 12), { ok: false, reason: "order" }); - assert.deepEqual(fileRange(5, 5, 0, 12), { ok: false, reason: "order" }); - assert.deepEqual(fileRange(5, 5.05, 0, 12), { ok: false, reason: "short" }); - assert.deepEqual(fileRange(13, 20, 0, 12), { ok: false, reason: "outside" }); - assert.deepEqual(fileRange(1, 3, -5, 12), { ok: false, reason: "outside" }); + 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, 12), { ok: false, reason: "outside" }); + 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", () => { @@ -48,20 +51,53 @@ test("times read H:MM:SS.s", () => { 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", () => { - assert.equal(startSentence(5, 4, 0), "Starts 1.0 s earlier, at the nearest keyframe (0:00:04.0)."); - assert.equal(startSentence(312, 309.6, 0), "Starts 2.4 s earlier, at the nearest keyframe (0:05:09.6)."); + 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(startSentence(7, 6, 1), "Starts 1.0 s earlier, at the nearest keyframe (0:00:05.0)."); - assert.equal(startSentence(6, 6, 1), "Starts at your Clip in mark."); - assert.equal(startSentence(6.04, 6, 1), "Starts at your Clip in mark."); + 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(startSentence(3, 0.6, 2), "Starts 2.4 s earlier, before the transcript's 0:00."); + 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", () => { - assert.equal(rangeSentence(312, 363.4, 3), "From 0:05:12.0 to 0:06:03.4, with your offset +3.00 s applied."); - assert.equal(rangeSentence(5, 9, 0), "From 0:00:05.0 to 0:00:09.0."); + 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", () => { @@ -124,16 +160,16 @@ test("the size is estimated from the file's own byte rate", () => { 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 1 GiB", () => { - assert.equal(BLOB_LIMIT_BYTES, 1024 ** 3); - assert.equal(DISK_SAVE_ABOVE_BYTES, 256 * 1024 ** 2); +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(BLOB_LIMIT_BYTES, false), "memory"); - assert.equal(savePath(BLOB_LIMIT_BYTES + 1, false), "too-big"); - assert.equal(savePath(BLOB_LIMIT_BYTES + 1, true), "disk"); + 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", () => { @@ -151,14 +187,29 @@ test("every refusal is one plain sentence", () => { 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. Mark a shorter clip, or use a Chromium-based browser, which can save it straight to disk.", + "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. 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 @@ -6,7 +6,7 @@ // 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 (startSentence). +// 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 @@ -18,11 +18,14 @@ import { formatOffset } from "./localFileClock"; 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 2-3 times over -// while it is made). -export const BLOB_LIMIT_BYTES = 1024 ** 3; -// Above this, a browser that can write straight to disk does. -export const DISK_SAVE_ABOVE_BYTES = 256 * 1024 ** 2; +// 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; @@ -30,14 +33,23 @@ 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 it. `duration` -// null: the file's length is not known, so nothing is clamped at the top. -export function fileRange(cueIn: number, cueOut: number, offset: number, duration: number | null): FileRange { +// 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 top = duration !== null && Number.isFinite(duration) && duration > 0 ? duration : Infinity; - const fileIn = Math.min(Math.max(0, cueIn + offset), top); - const fileOut = Math.min(Math.max(0, cueOut + offset), top); + 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) }; } @@ -54,20 +66,65 @@ export function formatClock(seconds: number): string { return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}.${t}`; } -// Where the clip really starts. `fileIn` is the in mark in file time, `keyTs` -// the keyframe at or before it (file time), `offset` the visitor's. -export function startSentence(fileIn: number, keyTs: number, offset: number): string { - const lead = Math.max(0, fileIn - keyTs); - if (lead < AT_MARK_SECONDS) return "Starts at your Clip in mark."; - const realCue = keyTs - offset; - const by = `Starts ${lead.toFixed(1)} s earlier`; - if (realCue < 0) return `${by}, before the transcript's 0:00.`; - return `${by}, at the nearest keyframe (${formatClock(realCue)}).`; -} +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; +}; -export function rangeSentence(cueIn: number, cueOut: number, offset: number): string { - const range = `From ${formatClock(cueIn)} to ${formatClock(cueOut)}`; - return Math.round(offset * 100) === 0 ? `${range}.` : `${range}, with your offset ${formatOffset(offset)} applied.`; +// 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 @@ -165,19 +222,25 @@ export type SavePath = "memory" | "disk" | "too-big"; // 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 <= BLOB_LIMIT_BYTES) return "memory"; + 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; offset: number } + | { 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": @@ -186,14 +249,28 @@ export function refusalSentence(r: Refusal): string { 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 `Both marks are outside your copy (it is ${formatClock(r.duration)} long, offset ${formatOffset(r.offset)}).`; + 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. Mark a shorter clip, or use a Chromium-based browser, which can save it straight to disk.`; + 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 ? "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 @@ -1,11 +1,20 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; +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 { ClipCancelled, outputSupport, probeClip, saveClip } from "./localClipEngine"; -import { MkvOutputFormat, MovOutputFormat, Mp4OutputFormat, WebMOutputFormat } from "mediabunny"; +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 @@ -42,17 +51,57 @@ const SOURCES = { ], } as const; -function make(kind: keyof typeof SOURCES): string { - const out = join(dir, `source.${kind}`); +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", "testsrc2=size=160x90:rate=25:duration=12", - "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=12", + "-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( @@ -91,6 +140,8 @@ for (const kind of ["mp4", "webm"] as const) { 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); @@ -208,3 +259,163 @@ test("cancel while a read is in flight answers at once, and hands back no clip", 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 @@ -11,18 +11,21 @@ // 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; packets +// 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. Nothing here reaches the network or any storage -// (components/LocalFilePicker.test.ts reads this source). +// 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, - BufferTarget, EncodedAudioPacketSource, EncodedPacketSink, EncodedVideoPacketSource, @@ -47,6 +50,8 @@ import { type VideoCodec, } from "mediabunny"; import { + MEMORY_LIMIT_BYTES, + MIN_CLIP_SECONDS, chooseOutput, estimateBytes, fileRange, @@ -56,10 +61,21 @@ import { 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; @@ -68,19 +84,25 @@ export type ClipPlan = { hasAudio: boolean; // The file has tracks beyond the main video and audio; they are left out. extraTracks: boolean; - // The file's length in seconds, when the library could tell. + // Where the copy ends (its last timestamp), when the library could tell. duration: number | null; - // The marks in file time, and where the clip really starts (file time). + // 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 = - | { kind: "memory" } + // 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> }; @@ -95,6 +117,14 @@ export class ClipCancelled extends Error { } } +// 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 { @@ -114,32 +144,49 @@ function familyOf(format: InputFormat): ContainerFamily | null { return null; } -// One input per picked file, shared by the probe and the save, so the save -// does not read the file's headers and index again. -const inputs = new WeakMap<Blob, Input>(); - -function inputFor(file: Blob): Input { - let input = inputs.get(file); - if (!input || input.disposed) { - input = new Input({ source: new BlobSource(file), formats: FORMATS }); - inputs.set(file, input); +// 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); } - return input; + 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. +// 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 input = inputs.get(file); - inputs.delete(file); - if (input) await release(input); + 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 @@ -184,10 +231,36 @@ async function audioStartAt(sink: EncodedPacketSink, t: number): Promise<Encoded 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, its size — or the one refusal that says why not. +// 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 input = inputFor(file); + 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()); @@ -199,28 +272,40 @@ export async function probeClip(file: Blob, cueIn: number, cueOut: number, offse 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(); + const d = await input.computeDuration(copied); duration = Number.isFinite(d) && d > 0 ? d : null; } catch (e) { - if (isReadError(e)) throw e; + if (isReadError(e) || e instanceof InputDisposedError) throw e; } - const range = fileRange(cueIn, cueOut, offset, duration); + 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: duration ?? 0, offset } : { kind: "short" }, + refusal: range.reason === "outside" ? { kind: "outside", duration, offset } : { kind: "short" }, }; } - const start = video - ? await keyPacketAt(new EncodedPacketSink(video), range.fileIn) - : await audioStartAt(new EncodedPacketSink(audio!), range.fileIn); + 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 = Math.min(start.timestamp, range.fileIn); + 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, @@ -229,28 +314,33 @@ export async function probeClip(file: Blob, cueIn: number, cueOut: number, offse ext: choice.ext, hasVideo: video !== null, hasAudio: audio !== null, - extraTracks: tracks.length > (video ? 1 : 0) + (audio ? 1 : 0), + extraTracks: tracks.length > copied.length, duration, + fileStart, fileIn: range.fileIn, fileOut: range.fileOut, startTs, - estimate: estimateBytes(file.size, duration, 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. - if (!keep) await forgetClipInput(file); + // 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) }); -async function* videoPackets(sink: EncodedPacketSink, key: EncodedPacket, t0: number, out: number) { - // Packets presented at or after the out mark, held until a later packet (in - // decode order) shows they are needed: a B-frame before the mark refers to - // the P-frame after it. +// 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) { @@ -259,6 +349,7 @@ async function* videoPackets(sink: EncodedPacketSink, key: EncodedPacket, t0: nu 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)); } } @@ -272,12 +363,11 @@ async function* audioPackets(sink: EncodedPacketSink, first: EncodedPacket, t0: } } -function outputFormat(name: OutputFormatName, inMemory: boolean): OutputFormat { - // In memory, MP4/MOV put their index first (better for posting the file); - // streamed to disk, last (bounded memory). - const fastStart = inMemory ? ("in-memory" as const) : false; - if (name === "mp4") return new Mp4OutputFormat({ fastStart }); - if (name === "mov") return new MovOutputFormat({ fastStart }); +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(); } @@ -307,6 +397,60 @@ function guardWritable(dest: WritableStream<StreamTargetChunk>) { }; } +// 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 @@ -319,8 +463,10 @@ export async function saveClip( onProgress: (p: SaveProgress) => void, signal: AbortSignal, ): Promise<SaveResult> { - const input = inputFor(file); + 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 { @@ -329,18 +475,23 @@ export async function saveClip( 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.fileOut - t0); + const total = Math.max(1e-6, plan.endTs - t0); - const bufferTarget = target.kind === "memory" ? new BufferTarget() : null; - const outTarget = bufferTarget ?? new StreamTarget(guard!.stream, { chunked: true }); + 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, bufferTarget !== null), target: outTarget }); + 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; @@ -357,10 +508,10 @@ export async function saveClip( output.addAudioTrack(aSource); aMeta = { decoderConfig: ((await w(audio.getDecoderConfig())) as AudioDecoderConfig | null) ?? undefined }; } - if (!vSource && !aSource) throw new Error("nothing to copy"); + if (!vSource && !aSource) throw new Error(`${CLIP_ENGINE_MARK}: nothing to copy`); await w(output.start()); - const vIt = vSink && key ? videoPackets(vSink, key, t0, plan.fileOut) : null; + 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; @@ -369,6 +520,7 @@ export async function saveClip( 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)); @@ -388,29 +540,39 @@ export async function saveClip( 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 = bufferTarget?.buffer ? new Blob([bufferTarget.buffer], { type: mimeType }) : null; + 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 { - inputs.delete(file); - if (!signal.aborted) await release(input); + // 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): Refusal { +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 @@ -13,13 +13,7 @@ import type { ClipPlan, SaveTarget } from "./localClipEngine"; import { loadClipEngine } from "./localClipLoader"; -import { - clipFileName, - rangeSentence, - refusalSentence, - savePath, - startSentence, -} from "./localClip"; +import { describeClip, refusalSentence, savePath, type Refusal } from "./localClip"; export type ClipRequest = { file: File; @@ -35,23 +29,29 @@ type Prepared = { plan: ClipPlan; name: string; path: "memory" | "disk"; + // 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) - | { phase: "refused"; key: string; sentence: string } + // `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 } & 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. -const DOWNLOAD_URL_LIFETIME_MS = 60_000; +// 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>>; @@ -62,6 +62,8 @@ 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; @@ -101,11 +103,19 @@ function revokeDownload() { downloadUrl = null; } -// Probe the file for these marks: where the clip really starts, its name and -// how it will be saved — or the sentence that says why it cannot be. +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 }); @@ -113,30 +123,25 @@ export async function prepareLocalClip(req: ClipRequest): Promise<void> { engine ??= await loadClipEngine(); const probe = await engine.probeClip(req.file, req.cueIn, req.cueOut, req.offset); if (mine !== token) return; - if (!probe.ok) { - set({ phase: "refused", key, sentence: refusalSentence(probe.refusal) }); - return; - } + if (!probe.ok) return refuse(key, probe.refusal); const { plan } = probe; const path = savePath(plan.estimate, req.canSaveToDisk); - if (path === "too-big") { - set({ phase: "refused", key, sentence: refusalSentence({ kind: "too-big", bytes: plan.estimate }) }); - return; - } - const realStartCue = plan.startTs - req.offset; - const endCue = plan.fileOut - req.offset; - set({ - phase: "ready", - key, - plan, - path, - name: clipFileName(req.title, req.slug, realStartCue, endCue, plan.ext), - range: rangeSentence(req.cueIn, req.cueOut, req.offset), - start: startSentence(plan.fileIn, plan.startTs, req.offset), + 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, ...words }); } catch { if (mine !== token) return; - set({ phase: "refused", key, sentence: refusalSentence({ kind: "copy" }) }); + refuse(key, { kind: "copy" }); } } @@ -164,7 +169,7 @@ export async function saveLocalClip(target: SaveTarget): Promise<void> { saving = ac; const { phase: _phase, ...rest } = prepared; void _phase; - set({ ...rest, phase: "saving", fraction: 0, doneSeconds: 0, totalSeconds: prepared.plan.fileOut - prepared.plan.startTs }); + set({ ...rest, phase: "saving", fraction: 0, doneSeconds: 0, totalSeconds: prepared.plan.endTs - prepared.plan.startTs }); try { const eng = (engine ??= await loadClipEngine()); try { @@ -184,7 +189,7 @@ export async function saveLocalClip(target: SaveTarget): Promise<void> { } catch (e) { if (mine !== token) return; if (e instanceof eng.ClipCancelled) set({ phase: "cancelled", key: prepared.key, path: prepared.path }); - else set({ phase: "failed", key: prepared.key, sentence: refusalSentence(eng.saveFailure(e)) }); + else set({ phase: "failed", key: prepared.key, sentence: refusalSentence(eng.saveFailure(e, req.canSaveToDisk)) }); } } finally { if (saving === ac) saving = null; @@ -197,14 +202,28 @@ export function cancelLocalClip(): void { saving?.abort(); } -// Forget the job entirely (the copy was cleared or replaced, the video changed, -// the panel was closed): any clip being made is cancelled. -export function resetLocalClip(): void { +function forget(): "memory" | "disk" | null { token++; + const was = state.phase === "saving" ? state.path : null; saving?.abort(); saving = null; if (engine && current) void engine.forgetClipInput(current.file); current = null; - revokeDownload(); 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(); }