commit 8c36dacf05a58a6c9b0aa9597c51ff46ab13b1c6
parent 08a958ebbd6f348320785f8b3e932464b2009468
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 19 Nov 2026 16:25:00 -0500
common: localClip, the pure part of clipping a visitor's own copy
The marks (cue clock) to a range of the file through the offset; the
sentence that says where a stream copy really starts (the keyframe at or
before the in mark); the saved file's name from the title and the real
times, never the picked file's; the output format (keep the container
family, fall back once, never re-encode); the size estimate and where the
clip is built (memory up to 1 GiB, the disk above 256 MB when the browser
can); one sentence per refusal.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
2 files changed, 363 insertions(+), 0 deletions(-)
diff --git a/common/lib/localClip.test.ts b/common/lib/localClip.test.ts
@@ -0,0 +1,164 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ BLOB_LIMIT_BYTES,
+ DISK_SAVE_ABOVE_BYTES,
+ chooseOutput,
+ clipFileName,
+ estimateBytes,
+ fileRange,
+ formatBytes,
+ formatClock,
+ rangeSentence,
+ refusalSentence,
+ savePath,
+ startSentence,
+ 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, 12), { ok: true, fileIn: 5, fileOut: 9 });
+ assert.deepEqual(fileRange(5, 9, 1, 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 });
+ // 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 });
+});
+
+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" });
+ // Only a sliver left inside the file.
+ assert.deepEqual(fileRange(11.95, 20, 0, 12), { 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");
+});
+
+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).");
+ // 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.");
+ // 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.");
+});
+
+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.");
+});
+
+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 1 GiB", () => {
+ assert.equal(BLOB_LIMIT_BYTES, 1024 ** 3);
+ assert.equal(DISK_SAVE_ABOVE_BYTES, 256 * 1024 ** 2);
+ 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");
+});
+
+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).",
+ );
+ 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.",
+ );
+ 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: "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,199 @@
+// 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 (startSentence).
+//
+// 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 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;
+// 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 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 {
+ 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);
+ 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}`;
+}
+
+// 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 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.`;
+}
+
+// 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 <= BLOB_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: "short" }
+ | { kind: "too-big"; bytes: number }
+ | { kind: "read" }
+ | { kind: "copy" };
+
+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 `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.`;
+ case "read":
+ return "Your browser could not read the file. It may have moved or changed since you picked it; pick it again.";
+ case "copy":
+ return "This file could not be copied into a clip; nothing was saved.";
+ }
+}