commit ee840110e67c29ee010f75f94972136ef72d546d
parent 25156ab10ca6c9fd32d7e8a54b00776a7bacd9cb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 13:04:47 -0500
Merge lane/window-end: a clip window that reaches a whole saved recording's end is cut from it
A window that starts inside a saved recording known to be whole and ends past it is clamped at the
recording's end and cut locally, with no request to the platform. A clamp is re-checked on every lookup;
the cut ends where both streams have data.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
26 files changed, 1473 insertions(+), 45 deletions(-)
diff --git a/OPERATING.md b/OPERATING.md
@@ -1369,6 +1369,37 @@ pnpm ops reports-export --json '{"siteId":"example-site","formats":["html","md"
- `fetch-windows` with `siteId` fetches every clip window the site's published reports cite that the disk does not
hold, one paced job per platform; a re-run resumes. It stays at 720: a site's evidence clip is cut inside
1280×720 from the plain `<from>-<to>.mp4` window.
+- **A window that runs past the end of a saved recording is cut from it, clamped at the end.** This is the last clip
+ of a recording plus its pad. The rule is in `common/lib/recordingEnd.mjs` and applies to `fetch-windows`,
+ fetch-window, `fetch_clip`, live-clip and the umtool build.
+ - The window must START inside the saved container and the recording must be KNOWN WHOLE. Known whole means a
+ known length is at most 2 s longer than the container's end, compared on one clock: the container's end on the
+ cue clock, which is its length less the time map's offset at the end. yt-dlp's duration is whole seconds, and
+ the muxer rounds the last frame.
+ - The known length is the record's `duration` (metadata.info.json). It is not trusted while the record says
+ `is_live`, `is_upcoming` or `post_live`.
+ - Else it is a landed live recording's stream length, and only the ended stream's OWN duration counts
+ (`coverage.basis: "duration"`, `covers`, from the start, with no live-edge fallback, no missing stream and no
+ failure on the record). The recorder's clock measures the recorder: a recorder that died mid-stream measures
+ itself whole.
+ - The cut ends where BOTH streams have data: the shorter of the picture's and the sound's ends, measured once per
+ container from its last packets. So the window passes the sync check. The end is two decimals rounded down, on
+ the cue clock through the recording's time map.
+ - The file is named for what it holds (`clips/<from>-<cutTo>.mp4`). Its sidecar records `clamp: {askedTo, cutTo,
+ recordingEnd, why, container: {file, bytes}, knownSeconds}`. Nothing is fetched.
+ - A window carrying the clamp holds any later span that starts inside it, so the same padded ask is a cache hit.
+ The answer lists the item under `"atRecordingEnd"`, and `umtool fetch --dry-run` prints `at end <clip>:
+ saved-video, clamped at the recording's end (asked to X, cut to Y)`.
+ - **A clamp is re-checked on every lookup** against the saved-video pointer (file and bytes) and the known length
+ (within 0.5 s). These are JSON reads, never a probe.
+ - When the container is another or a longer file, or the known end has moved, the window answers only its own
+ seconds. `fetch-windows` retires it, as it retires a window cut on another clock (listed under `retired`), and
+ asks the span again.
+ - Still `not-covering`, as before: a window that starts at or after the end; a container shorter than the known
+ length by more than 2 s, which is a partial recording; and a recording whose length is not known. The reason is
+ given (a whole-recording platform's item fails with it).
+ - So do not shorten a last clip to avoid a network fetch. Keep its whole end (`umtool window <p> <clip> --end E`),
+ then `umtool fetch <p> --dry-run`.
- A window asked taller than 720 (`"maxHeight"` on `fetch-windows`, fetch-window, `fetch_clip`; umtool sends it only
for a project with `render.tallWindows` on) is its own file beside the 720 one: `clips/<from>-<to>.h<tier>.mp4`,
with its own sidecar. The 720 window is never replaced, retired or re-fetched for this. An ask with no `maxHeight`
diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts
@@ -961,3 +961,100 @@ test("review 3 M1/M2: off clips:saved-video an X window is fetched only by a job
const on = await runInJobContext(jobCtx("platform:twitter"), async () => go(await corpus(), xItems().slice(0, 1), h));
assert.equal(on.fetched.length, 1, "on X's queue it is fetched");
});
+
+// THE RECORDING'S END (lane window-end): the last clip of a saved recording
+// known whole — its padded window ends past the container — is cut from the
+// saved video, clamped at its end, through the real saved-video tier: no
+// yt-dlp spawned, the clamp in the result, and the next run's same ask cached.
+test("the recording's end: a window past a whole saved recording's end is cut clamped, nothing spawned, then cached", async () => {
+ const { execFileSync } = await import("node:child_process");
+ const base = await corpus();
+ const transcriptsDir = path.dirname(base.channelsDir);
+ const savedVideosDir = path.join(transcriptsDir, "saved-videos");
+ const paths = { ...base, transcriptsDir, savedVideosDir, ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as unknown as Paths;
+ const videoDir = path.join(base.channelsDir, "c", "data", "last1");
+ const storeDir = path.join(savedVideosDir, "c", "last1");
+ await mkdir(videoDir, { recursive: true });
+ await mkdir(storeDir, { recursive: true });
+ execFileSync("ffmpeg", [
+ "-nostdin", "-v", "error", "-y",
+ "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=8",
+ "-f", "lavfi", "-i", "sine=frequency=440:duration=8",
+ "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest",
+ path.join(storeDir, "source-media.mp4"),
+ ]);
+ await writeFile(
+ path.join(videoDir, "saved-video.json"),
+ JSON.stringify({ storedAt: "2026-11-21T00:00:00.000Z", dir: storeDir, file: "source-media.mp4", bytes: 1, keepReason: "pin" }),
+ );
+ await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id: "last1", duration: 8 }));
+ // The clip ends 1 s before the end (7 of 8), padded 3 s: the window is 1–10.
+ const ask = { ...item("last1", "/last1", 1, 10), clipId: "m#last", pad: 3 };
+ const before = await spawns();
+ const h = harness();
+ const r = await go(paths, [ask], h);
+ assert.deepEqual(r.failed, []);
+ assert.deepEqual(r.fetched, [], "nothing fetched");
+ assert.deepEqual(r.cut.map((i) => i.clipId), ["m#last"]);
+ assert.equal((await spawns()) - before, 0, "no yt-dlp spawned for footage on disk");
+ assert.equal(r.atRecordingEnd?.length, 1);
+ const end = r.atRecordingEnd![0];
+ assert.equal(end.askedTo, 10);
+ assert.ok(end.cutTo > 7.5 && end.cutTo <= 8.1, `cut to ${end.cutTo}`);
+ assert.match(end.why, /whole recording/);
+ const names = await readdir(path.join(videoDir, "clips"));
+ assert.ok(names.includes(`1.00-${end.cutTo.toFixed(2)}.mp4`), names.join(" "));
+ const prov = parseClipProvenance(JSON.parse(await readFile(path.join(videoDir, "clips", `1.00-${end.cutTo.toFixed(2)}.json`), "utf8")));
+ assert.equal(prov?.source, "saved-video");
+ assert.equal(prov?.clamp?.askedTo, 10);
+ // The same padded ask again: answered from the clamped window, nothing cut or fetched.
+ const again = await go(paths, [ask], harness());
+ assert.deepEqual(again.cached.map((i) => i.clipId), ["m#last"]);
+ assert.deepEqual(again.cut, []);
+ assert.equal((await spawns()) - before, 0);
+});
+
+// REVIEW 1, finding 2: a clamp re-checked on every run. Its known end moved, or
+// its saved container replaced: the clamped window is retired (as a window cut
+// on another clock is) and the span is cut or fetched again.
+test("the recording's end: a clamp whose facts moved is retired, and the span asked again", async () => {
+ const { execFileSync } = await import("node:child_process");
+ const base = await corpus();
+ const transcriptsDir = path.dirname(base.channelsDir);
+ const savedVideosDir = path.join(transcriptsDir, "saved-videos");
+ const paths = { ...base, transcriptsDir, savedVideosDir, ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as unknown as Paths;
+ const videoDir = path.join(base.channelsDir, "c", "data", "last2");
+ const storeDir = path.join(savedVideosDir, "c", "last2");
+ await mkdir(videoDir, { recursive: true });
+ await mkdir(storeDir, { recursive: true });
+ execFileSync("ffmpeg", [
+ "-nostdin", "-v", "error", "-y",
+ "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=8",
+ "-f", "lavfi", "-i", "sine=frequency=440:duration=8",
+ "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest",
+ path.join(storeDir, "source-media.mp4"),
+ ]);
+ const pointer = { storedAt: "2026-11-21T00:00:00.000Z", dir: storeDir, file: "source-media.mp4", bytes: 1, keepReason: "pin" };
+ await writeFile(path.join(videoDir, "saved-video.json"), JSON.stringify(pointer));
+ await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id: "last2", duration: 8 }));
+ const ask = { ...item("last2", "/last2", 1, 10), clipId: "m#end", pad: 3 };
+ const first = await go(paths, [ask], harness());
+ assert.equal(first.atRecordingEnd?.length, 1);
+ const clamped = `1.00-${first.atRecordingEnd![0].cutTo.toFixed(2)}`;
+
+ // The saved container replaced by a longer copy (another size): retired, cut again from the new one.
+ await writeFile(path.join(videoDir, "saved-video.json"), JSON.stringify({ ...pointer, bytes: 2 }));
+ const before = await spawns();
+ const second = await go(paths, [ask], harness());
+ assert.deepEqual(second.retired, [`c/last2/clips/${clamped}`]);
+ assert.deepEqual(second.cut.map((i) => i.clipId), ["m#end"], "cut again from the saved video");
+ assert.equal((await spawns()) - before, 0);
+
+ // The recording's known end moved past the container: retired, and the span is not the saved video's any more.
+ await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id: "last2", duration: 60 }));
+ const third = await go(paths, [ask], harness());
+ assert.deepEqual(third.retired, [`c/last2/clips/${clamped}`]);
+ assert.deepEqual(third.cut, []);
+ assert.deepEqual(third.fetched.map((i) => i.clipId), ["m#end"], "the network, as for any span the saved video does not hold");
+ assert.equal((await readdir(path.join(videoDir, "clips"))).some((n) => n.startsWith(`${clamped}.`)), false, "the clamped window is gone");
+});
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts
@@ -314,9 +314,15 @@ export type FetchWindowsResult = {
// (clips.windowMaxHeight) clamped it.
lower?: { item: FetchWindowsItem; file: string; height: number | null; asked: number; why: string }[];
clampedFrom?: number;
+ // THE RECORDING'S END (lane window-end, lib/recordingEnd.mjs): of `cut`, the
+ // windows asked past the end of a saved recording known whole and cut to it —
+ // the end asked, the end cut (the window's name) and why.
+ atRecordingEnd?: FetchWindowsAtEnd[];
stopped?: FetchWindowsStop;
};
+export type FetchWindowsAtEnd = { item: FetchWindowsItem; askedTo: number; cutTo: number; why: string };
+
export type FetchWindowsProvenance = {
requestedBy: string;
manifest?: string;
@@ -379,6 +385,10 @@ export type FetchWindowsDeps = {
// cut made before the map): their seconds are another clock's. Returns the
// retired `<from>-<to>` names.
retireOffClock: (opts: { paths: Paths; slug: string; dirId: string; videoDir: string; clockId: string }) => Promise<string[]>;
+ // THE RECORDING'S END (lane window-end): remove the windows of a video whose
+ // clamp at the recording's end no longer holds (another or a longer saved
+ // container, the known length moved). Returns the retired `<from>-<to>` names.
+ retireStaleClamps: (opts: { paths: Paths; slug: string; dirId: string; videoDir: string }) => Promise<string[]>;
// A window's picture height, for a tall ask over a window with none
// recorded (probed once; the answer is written to its sidecar).
probeHeight: (file: string, paths: Paths) => Promise<number | null>;
@@ -410,6 +420,16 @@ async function retireOffClockWindows(o: {
return off.map((w) => `${w.from.toFixed(2)}-${w.to.toFixed(2)}`);
}
+// The windows of a video clamped at a recording's end whose clamp no longer
+// holds (clipWindow-server listClipWindows `clampStale`), evicted through the
+// targeted eviction, as the windows cut on another clock are.
+async function retireStaleClampWindows(o: { paths: Paths; slug: string; dirId: string; videoDir: string }): Promise<string[]> {
+ const stale = (await listClipWindows(o.videoDir, { tiers: true })).filter((w) => w.clampStale);
+ if (!stale.length) return [];
+ await evictClipWindows({ paths: o.paths, slug: o.slug, id: o.dirId, windows: stale.map((w) => ({ from: w.from, to: w.to })) });
+ return stale.map((w) => `${w.from.toFixed(2)}-${w.to.toFixed(2)}`);
+}
+
export type SaveWholeRecordingOpts = {
paths: Paths;
slug: string;
@@ -532,6 +552,7 @@ const DEFAULT_DEPS: FetchWindowsDeps = {
signal: o.signal,
}),
retireOffClock: retireOffClockWindows,
+ retireStaleClamps: retireStaleClampWindows,
probeHeight: (file, paths) => probeVideoHeight({ ffprobeBin: paths.ffprobeBin, file }),
renderHeld: renderModeHeldNow,
cutPlainFromTiered: cutPlainFromTieredWindow,
@@ -817,9 +838,15 @@ export async function fetchWindows({
signal: fetchSignal,
});
result.cut.push(item);
+ if (source.clamp) {
+ (result.atRecordingEnd ??= []).push({ item, askedTo: source.clamp.askedTo, cutTo: source.clamp.cutTo, why: source.clamp.why });
+ }
log(
` ✂ ${label}: cut from the saved video into clips/${cut.file}` +
- (beside ? ` (${cut.height ?? "?"}p, beside clips/${beside}, which stays as it is)` : ""),
+ (beside ? ` (${cut.height ?? "?"}p, beside clips/${beside}, which stays as it is)` : "") +
+ (source.clamp
+ ? ` — clamped at the recording's end (asked to ${source.clamp.askedTo.toFixed(2)}, cut to ${source.clamp.cutTo.toFixed(2)}): ${source.clamp.why}`
+ : ""),
);
} catch (e) {
fail(item, "cut-failed", (e as Error).message);
@@ -886,6 +913,21 @@ export async function fetchWindows({
const clockWanted = wholeRecordingFor(settings, channelConfigPlatform(config) ?? "", item, wholeRecording);
const clock = clockWanted ? await clockOf(item, label, videoDir, dirId) : null;
+ // A window clamped at the recording's end whose facts moved (another or a
+ // longer saved container, the known end moved) is retired first, as a
+ // window on another clock is, and the span is cut or fetched again below.
+ const staleClamps = await deps.retireStaleClamps({ paths, slug: item.slug, dirId, videoDir }).catch((e: unknown) => {
+ log(` ${label}: retiring the windows whose clamp at the recording's end no longer holds failed: ${(e as Error).message}`);
+ return [] as string[];
+ });
+ if (staleClamps.length) {
+ for (const n of staleClamps) (result.retired ??= []).push(`${item.slug}/${dirId}/clips/${n}`);
+ log(
+ ` ⏱ ${item.slug}/${dirId}: ${staleClamps.length} window(s) clamped at the recording's end retired — the saved video ` +
+ `or the recording's known length changed since: ${staleClamps.join(", ")}`,
+ );
+ }
+
// THE CACHE FIRST, here rather than only inside fetchWindowManaged, so a
// cached window owes no pause and is not counted as a network attempt —
// and IN SYNC (the header): a desynced held window is set aside here, and
@@ -1090,7 +1132,7 @@ export async function fetchWindows({
fail(
item,
"cut-failed",
- `the saved recording ends at ${saved.durationSec.toFixed(2)} s, before this window does`,
+ saved.why ?? `the saved recording ends at ${saved.durationSec.toFixed(2)} s, before this window does`,
);
done += 1;
progress();
@@ -1256,7 +1298,7 @@ export async function fetchWindows({
fail(
item,
"cut-failed",
- `the saved recording ends at ${after.durationSec.toFixed(2)} s, before this window does`,
+ after.why ?? `the saved recording ends at ${after.durationSec.toFixed(2)} s, before this window does`,
);
} else {
fail(item, "cut-failed", "the download reported success, but no saved video is on record");
diff --git a/common/lib/clipWindow-server.ts b/common/lib/clipWindow-server.ts
@@ -2,6 +2,7 @@
// layout and for why a `clips/` subdirectory is invisible to every video-dir
// enumerator in the repo.
+import { clampHolds } from "./recordingEnd.mjs";
import { readJsonFile, writeJsonAtomic } from "./jsonFile-server";
import path from "node:path";
import { mkdir, readFile, readdir, stat } from "node:fs/promises";
@@ -36,6 +37,14 @@ export type ClipWindow = {
// sidecar has a provenance — a height-only sidecar is what a window older
// than the field gets after its one probe.
height?: number;
+ // Its sidecar records a clamp at the recording's end (clipWindow.ts
+ // ClipProvenance `clamp`) that still holds against the saved-video pointer
+ // and the recording's known length now (recordingEnd.mjs clampHolds): it
+ // holds any span starting inside it. `clampStale`: a clamp whose facts moved
+ // (another or a longer container, the known end moved) -- an ordinary window
+ // of the seconds it holds, which fetch-windows retires.
+ endsRecording?: true;
+ clampStale?: true;
};
// Every fetched window in a video dir, oldest-window-first by start second.
@@ -91,6 +100,11 @@ export async function listClipWindows(
provenance,
...(tier !== undefined ? { tier } : {}),
...(height !== undefined ? { height } : {}),
+ ...(provenance?.clamp
+ ? (await clampHolds(videoDir, provenance.clamp))
+ ? { endsRecording: true as const }
+ : { clampStale: true as const }
+ : {}),
});
}
out.sort((a, b) => a.from - b.from || a.to - b.to || (a.tier ?? 0) - (b.tier ?? 0));
diff --git a/common/lib/clipWindow.ts b/common/lib/clipWindow.ts
@@ -322,8 +322,53 @@ export type ClipProvenance = {
// map's `id` and whether it was sure of the span (`certain`; false on a step
// or a map that is not ok -- the per-clip quote check settles those).
clock?: ClipWindowClock;
+ // CLAMPED AT THE RECORDING'S END (lane window-end, lib/recordingEnd.mjs): the
+ // window was asked past the end of a saved recording known whole and cut to
+ // it. `askedTo` the end asked and `cutTo` the end cut (the window's own `to`),
+ // both on the cue clock; `recordingEnd` the container second it ends at;
+ // `why` the sentence (the recording's known length, within the tolerance).
+ // A window carrying it ENDS THE RECORDING while its facts hold
+ // (clipWindow-server listClipWindows asks recordingEnd.mjs clampHolds): it
+ // holds any span starting inside it (clipWindowContains), so the same padded
+ // ask is not cut again. One whose facts moved is retired by fetch-windows.
+ clamp?: ClipWindowClamp;
};
+// `container` (the saved-video pointer's file and bytes) and `knownSeconds` (the
+// length it was judged whole by) are what a lookup re-checks (recordingEnd.mjs
+// clampHolds): a clamp whose facts have moved no longer ends the recording.
+export type ClipWindowClamp = {
+ askedTo: number;
+ cutTo: number;
+ recordingEnd: number;
+ why: string;
+ container?: { file: string; bytes: number | null };
+ knownSeconds?: number;
+};
+
+export function coerceClipWindowClamp(v: unknown): ClipWindowClamp | undefined {
+ if (!v || typeof v !== "object" || Array.isArray(v)) return undefined;
+ const r = v as Record<string, unknown>;
+ const askedTo = num(r.askedTo);
+ const cutTo = num(r.cutTo);
+ const recordingEnd = num(r.recordingEnd);
+ if (askedTo === undefined || cutTo === undefined || recordingEnd === undefined || !(askedTo > cutTo)) return undefined;
+ const c = r.container as Record<string, unknown> | undefined;
+ const container =
+ c && typeof c === "object" && typeof c.file === "string" && c.file !== ""
+ ? { file: c.file, bytes: typeof c.bytes === "number" && Number.isFinite(c.bytes) ? c.bytes : null }
+ : undefined;
+ const knownSeconds = num(r.knownSeconds);
+ return {
+ askedTo,
+ cutTo,
+ recordingEnd,
+ why: typeof r.why === "string" ? r.why : "",
+ ...(container ? { container } : {}),
+ ...(knownSeconds !== undefined ? { knownSeconds } : {}),
+ };
+}
+
export type ClipWindowClock = { id: string; from: number; to: number; offset: number; certain: boolean };
export function coerceClipWindowClock(v: unknown): ClipWindowClock | undefined {
@@ -413,20 +458,28 @@ export function parseClipProvenance(raw: unknown): ClipProvenance | null {
if (setAsideAt) out.setAsideAt = setAsideAt;
const clock = coerceClipWindowClock(r.clock);
if (clock) out.clock = clock;
+ const clamp = coerceClipWindowClamp(r.clamp);
+ if (clamp) out.clamp = clamp;
const height = num(r.height);
if (height !== undefined && Number.isInteger(height) && height > 0) out.height = height;
return out;
}
-export type ClipWindowSpan = { from: number; to: number };
+// `endsRecording`: the window ends where the recording does (its sidecar's
+// `clamp`, lane window-end) — no second after it exists to be held.
+export type ClipWindowSpan = { from: number; to: number; endsRecording?: boolean };
-// Does this window hold [from, to] whole, to the naming tolerance?
+// Does this window hold [from, to] whole, to the naming tolerance? A window
+// that ENDS THE RECORDING holds any span starting inside it: the seconds past
+// its end are nowhere (lib/recordingEnd.mjs windowHoldsSpan, the same rule).
export function clipWindowContains(
w: ClipWindowSpan,
from: number,
to: number,
): boolean {
- return !(w.from > from + WIN_EPS || w.to < to - WIN_EPS);
+ if (w.from > from + WIN_EPS) return false;
+ if (w.to >= to - WIN_EPS) return true;
+ return w.endsRecording === true && from < w.to - WIN_EPS;
}
// The TIGHTEST window containing [from, to], or null.
diff --git a/common/lib/evidenceClip.mjs b/common/lib/evidenceClip.mjs
@@ -29,6 +29,15 @@
// its pad — to WIN_EPS. Within a tier the tightest wins; across tiers the order
// above wins.
//
+// THE RECORDING'S END (lane window-end, ./recordingEnd.mjs): a window that ENDS
+// THE RECORDING holds any span starting inside it -- the seconds past its end
+// exist nowhere, so the last clip's pad past the end is not a reason to fetch.
+// Such a window is a saved container KNOWN WHOLE (its record's duration, else a
+// landed live recording's, within 2 s), for a span passing its end, and a
+// corpus window the editor cut clamped at that end (its sidecar's `clamp`).
+// The source it resolves to says `endsRecording: true`; its `windowEnd` is
+// where the footage stops.
+//
// A file in `data/<id>/` may be a RELATIVE symlink into `media/`, which may be
// an absolute symlink to another drive. Every candidate is `stat`ed through its
// links before it is returned, and a dangling one — an unmounted drive — is
@@ -44,6 +53,7 @@ import { promisify } from "node:util";
import { resolveVideoDir } from "./videoDir-server.mjs";
import { clockForContainer } from "./recordingClock-read.mjs";
import { mapSpan } from "./recordingClock.mjs";
+import { bothStreamsEnd, clampHolds, recordingWholeness, windowHoldsSpan } from "./recordingEnd.mjs";
const execFileP = promisify(execFile);
@@ -95,8 +105,9 @@ export async function listNames(dir) {
* @typedef {{ id: string, offset: number, certain: boolean }} SourceClock
* the recording's time map applied to a saved container (recordingClock.mjs):
* the offset the span was mapped by, and whether the map was sure of it
- * @typedef {{ name: string, path: string, from: number, to: number, height?: number, clock?: SourceClock }} SourceWindow
- * @typedef {{ kind: string, path: string, name: string, windowStart: number, windowEnd: number, height?: number, clock?: SourceClock }} LocalSource
+ * @typedef {{ name: string, path: string, from: number, to: number, height?: number, clock?: SourceClock, endsRecording?: boolean }} SourceWindow
+ * `endsRecording`: the window ends where the recording does (./recordingEnd.mjs)
+ * @typedef {{ kind: string, path: string, name: string, windowStart: number, windowEnd: number, height?: number, clock?: SourceClock, endsRecording?: boolean }} LocalSource
* @typedef {(file: string) => Promise<{ duration: number, height?: number } | null>} SourceProbe
* @typedef {{ video: string, slug?: string | null, channelsDir?: string | null, rawDir?: string | null, probe?: SourceProbe, platform?: string | null, want?: { from: number, to: number }, maxHeight?: number, heightOf?: (kind: string, w: SourceWindow) => Promise<number | null> }} TierContext
* `want`: the span being resolved, when there is one (resolveFromTiers sets it) -- the
@@ -112,13 +123,15 @@ export async function listNames(dir) {
*/
/**
- * Does this window hold [from, to] whole, to the tolerance?
- * @param {{ from: number, to: number }} w
+ * Does this window hold [from, to] whole, to the tolerance? A window that ENDS
+ * THE RECORDING (`endsRecording`) holds any span starting inside it
+ * (./recordingEnd.mjs windowHoldsSpan).
+ * @param {{ from: number, to: number, endsRecording?: boolean }} w
* @param {number} from
* @param {number} to
*/
export function windowContains(w, from, to) {
- return !(w.from > from + WIN_EPS || w.to < to - WIN_EPS);
+ return windowHoldsSpan(w, from, to);
}
/**
@@ -360,16 +373,68 @@ export async function ffprobeSource(file, bin = process.env.FFPROBE_BIN ?? "ffpr
// one context `{video, slug, channelsDir, probe}`. A tier that cannot apply (no
// channelsDir or slug) lists nothing.
+/**
+ * Does a corpus window's sidecar record a clamp at the recording's end (the
+ * editor's `clamp`, lib/clipWindow.ts)?
+ * @param {string} windowPath
+ */
+async function sidecarClamped(windowPath) {
+ const ext = CORPUS_WINDOW_EXTS.find((x) => windowPath.endsWith(x));
+ if (!ext) return false;
+ const c = await sidecarClampOf(windowPath.slice(0, -ext.length) + ".json");
+ if (!c) return false;
+ // Re-checked against the saved-video pointer and the known length NOW
+ // (recordingEnd.mjs clampHolds): one whose facts moved is an ordinary window.
+ return clampHolds(path.dirname(path.dirname(windowPath)), c);
+}
+
+// A sidecar's clamp by path, good while the sidecar keeps its size and mtime.
+/** @type {Map<string, { sig: string, clamp: any }>} */
+const clampMemo = new Map();
+
+/** @param {string} sidecar */
+async function sidecarClampOf(sidecar) {
+ let st;
+ try {
+ st = await stat(sidecar);
+ } catch {
+ return null;
+ }
+ const sig = `${st.size}:${st.mtimeMs}`;
+ const had = clampMemo.get(sidecar);
+ if (had && had.sig === sig) return had.clamp;
+ let clamp = null;
+ try {
+ const c = JSON.parse(await readFile(sidecar, "utf8"))?.clamp;
+ clamp = c && typeof c === "object" && Number.isFinite(c.askedTo) && Number.isFinite(c.cutTo) && c.askedTo > c.cutTo ? c : null;
+ } catch {
+ clamp = null;
+ }
+ if (clampMemo.size > 5000) clampMemo.clear();
+ clampMemo.set(sidecar, { sig, clamp });
+ return clamp;
+}
+
/** @param {TierContext} ctx */
-async function corpusWindows({ video, slug, channelsDir, platform, maxHeight }) {
+async function corpusWindows({ video, slug, channelsDir, platform, maxHeight, want }) {
if (!channelsDir || !slug) return [];
const dir = corpusClipsDir(await recordDirOf(channelsDir, slug, video, platform));
const names = await listNames(dir);
const plain = windowsFromBareNames(names, dir);
- if (!isTallAsk(maxHeight)) return plain;
+ const all = isTallAsk(maxHeight) ? [...plain, ...tieredWindowsFromNames(names, dir)] : plain;
+ // THE RECORDING'S END: a window starting by the span's start and ending
+ // before its end -- a near miss -- holds it when the editor cut it clamped at
+ // the recording's end. Only those sidecars are read.
+ if (want) {
+ for (const w of all) {
+ if (w.from <= want.from + WIN_EPS && w.to < want.to - WIN_EPS && w.to > want.from + WIN_EPS && (await sidecarClamped(w.path))) {
+ w.endsRecording = true;
+ }
+ }
+ }
+ if (!isTallAsk(maxHeight)) return all;
// A TALL ASK: the tiered windows too, and every window's recorded height
// (the editor writes it in the sidecar; an old window has none until asked).
- const all = [...plain, ...tieredWindowsFromNames(names, dir)];
for (const w of all) {
const h = await sidecarHeight(w.path);
if (h !== undefined) w.height = h;
@@ -401,20 +466,37 @@ async function savedVideoWindows({ video, slug, channelsDir, platform, probe = f
if (!Number.isFinite(duration) || duration <= 0) continue;
const height = c.height ?? info?.height;
const clock = want ? await clockForContainer(videoDir, c.path) : null;
+ /** @type {SourceWindow} */
+ let w = { name: c.name, path: c.path, from: 0, to: duration, ...(height ? { height } : {}) };
if (clock && want) {
const m = mapSpan(clock, want.from, want.to);
const shift = m.offsetFrom;
- out.push({
+ w = {
name: c.name,
path: c.path,
from: shift ? -shift : 0,
to: duration - shift,
...(height ? { height } : {}),
clock: { id: clock.id, offset: shift, certain: m.certain },
- });
- continue;
+ };
+ }
+ // THE RECORDING'S END: a span starting inside and ending past a container
+ // that holds the whole recording -- the container ends the recording.
+ // Whole on one clock: the container's end on the cue clock (less the
+ // map's offset AT THE END) against the recording's length. Its footage
+ // ends where both streams have data (recordingEnd.mjs bothStreamsEnd), on
+ // the clock the build maps the whole file by (`from`'s one offset).
+ if (want && want.to > w.to + WIN_EPS && want.from < w.to - WIN_EPS) {
+ const offsetEnd = clock ? mapSpan(clock, want.from, want.to).offsetTo : 0;
+ if ((await recordingWholeness(videoDir, duration - offsetEnd)).whole) {
+ const end = (await bothStreamsEnd(c.path, duration, process.env.FFPROBE_BIN ?? "ffprobe")) + w.from;
+ if (want.from < end - WIN_EPS) {
+ w.to = end;
+ w.endsRecording = true;
+ }
+ }
}
- out.push({ name: c.name, path: c.path, from: 0, to: duration, ...(height ? { height } : {}) });
+ out.push(w);
}
return out;
}
@@ -457,6 +539,7 @@ export const asSource = (kind, w) => ({
windowEnd: w.to,
...(w.height ? { height: w.height } : {}),
...(w.clock ? { clock: w.clock } : {}),
+ ...(w.endsRecording ? { endsRecording: true } : {}),
});
/**
diff --git a/common/lib/recordingEnd.mjs b/common/lib/recordingEnd.mjs
@@ -0,0 +1,316 @@
+// recordingEnd.mjs — A CLIP WINDOW THAT REACHES THE END OF A SAVED RECORDING.
+//
+// A clip whose cut ends in the last seconds of a recording asks for a window
+// that ends past it: the cut plus its pad (umtool pads 3 s each side). A saved
+// container holding that recording WHOLE has every second the window can get --
+// the pad past its end does not exist anywhere, on the platform either. So such
+// a window is cut from the saved container, CLAMPED to its end, instead of
+// going to the platform's queue for a network fetch of footage already on disk
+// (and of a video that may be private or gone by now).
+//
+// THE RULE, for a span [from, to] on the container's clock (after the one-clock
+// map, recordingClock.mjs) and a container of D seconds:
+// - to <= D (to WIN_EPS) held, as always;
+// - from >= D - WIN_EPS (starts at or after the end) NOT held -- nothing of it
+// is in the file;
+// - else, the recording KNOWN WHOLE held, clamped: cut [from, ⌊D⌋₂]
+// (two decimals, rounded DOWN so
+// a window's name never claims a
+// second the file lacks);
+// - else NOT held, as before.
+//
+// KNOWN WHOLE: a known length L of the recording that the container reaches,
+// L <= E + RECORDING_END_TOLERANCE_SECONDS, ON ONE CLOCK: E is the container's
+// end on the cue clock (its length less the recording's time map's offset
+// there, recordingClock.mjs; its length when there is no map), L the
+// platform's. L is the record's own `duration` (metadata.info.json; ignored
+// while the record says the stream is live, upcoming or `post_live` -- a VOD
+// still being processed reports a length that is not its last), else a LANDED
+// live recording's ended stream's own duration -- `coverage.basis` "duration"
+// (never the recorder's clock, which measures the recorder: a recorder that
+// died mid-stream measures itself whole), `coverage.covers`, from the start, no
+// live-edge fallback, no missing stream, no failure on the record. Anything
+// else is NOT whole: a partial recording (a live capture joined late or cut
+// short, a download cut short) really may not hold the window, and a network
+// fetch is then still right.
+//
+// A CLAMP IS RE-CHECKED ON EVERY LOOKUP (`clampHolds`): the window's sidecar
+// records the saved-video pointer it was cut from (file, bytes) and the known
+// length it was judged by; when the pointer names another file or size, or the
+// known length has moved, the window no longer ends the recording -- the
+// editor's fetch-windows retires it, as it retires a window cut on another
+// clock, and cuts the span again. JSON reads only (memoised by size and mtime),
+// never a probe.
+//
+// THE CUT ENDS WHERE BOTH STREAMS HAVE DATA (`containerStreamEnds`): at a
+// container's end its picture and sound often stop apart (a merged
+// bestvideo+bestaudio download, a live capture's last segments), and a window
+// cut to the format's end would carry that gap -- which the sync check sets
+// aside. So a clamp cuts to the shorter stream's end, measured once per
+// container (its last packets, read from 30 s before its end) and kept for the
+// process.
+//
+// THE TOLERANCE, 2 s: yt-dlp's `duration` is whole seconds on most platforms
+// (YouTube's lengthSeconds, Rumble's), so a container that holds the whole
+// recording can probe up to a second short of it; the other second is the
+// muxer's own rounding of the last frame and packet. A stream longer than the
+// container by more than that is a container that does not hold it.
+//
+// A window cut this way says so in its sidecar (`clamp`: the end asked, the end
+// cut, the container's end and why), and a window carrying it ENDS THE
+// RECORDING: it holds any later span that starts inside it (`windowHoldsSpan`),
+// so the next ask for the same padded span is answered from it, not cut again
+// and not fetched.
+//
+// Plain ESM with no app imports: umtool's report-to-video scripts run under
+// bare node and ask the same question of the same disk (evidenceClip.mjs).
+
+import { execFile } from "node:child_process";
+import { readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import { promisify } from "node:util";
+
+const execFileP = promisify(execFile);
+
+/** How far a container's length may fall short of the recording's known length and still be the whole of it. */
+export const RECORDING_END_TOLERANCE_SECONDS = 2;
+
+// lib/clipWindow.ts's and evidenceClip.mjs's WIN_EPS: the 2 dp naming tolerance.
+const EPS = 0.02;
+
+/** Two decimals, rounded down. @param {number} x */
+export const floor2 = (x) => Math.floor(x * 100 + 1e-6) / 100;
+
+// Parsed JSON by path, good while the file keeps its size and mtime: a
+// metadata.info.json can be tens of MB, and a build asks per clip.
+/** @type {Map<string, { sig: string, value: any }>} */
+const jsonMemo = new Map();
+
+/** @param {string} file @returns {Promise<any>} */
+async function readJson(file) {
+ let st;
+ try {
+ st = await stat(file);
+ } catch {
+ return null;
+ }
+ const sig = `${st.size}:${st.mtimeMs}`;
+ const had = jsonMemo.get(file);
+ if (had && had.sig === sig) return had.value;
+ let value = null;
+ try {
+ value = JSON.parse(await readFile(file, "utf8"));
+ } catch {
+ value = null;
+ }
+ // Only the few fields read here are kept, never a whole record.
+ const kept =
+ value && typeof value === "object" && !Array.isArray(value)
+ ? {
+ duration: value.duration,
+ live_status: value.live_status,
+ status: value.status,
+ fromStart: value.fromStart,
+ fallback: value.fallback,
+ missingStream: value.missingStream,
+ failureClass: value.failureClass,
+ error: value.error,
+ coverage: value.coverage,
+ file: value.file,
+ bytes: value.bytes,
+ dir: value.dir,
+ }
+ : null;
+ if (jsonMemo.size > 2000) jsonMemo.clear();
+ jsonMemo.set(file, { sig, value: kept });
+ return kept;
+}
+
+const NOT_FINAL = new Set(["is_live", "is_upcoming", "post_live"]);
+
+/**
+ * The recording's known length in seconds and where it came from, or null.
+ * @param {string} videoDir
+ * @returns {Promise<{ seconds: number, basis: "metadata" | "live-recording" } | null>}
+ */
+export async function recordingKnownLength(videoDir) {
+ const meta = await readJson(path.join(/* turbopackIgnore: true */ videoDir, "metadata.info.json"));
+ const live = !!meta && NOT_FINAL.has(meta.live_status);
+ const d = Number(meta?.duration);
+ if (!live && Number.isFinite(d) && d > 0) return { seconds: d, basis: "metadata" };
+ const rec = await readJson(path.join(/* turbopackIgnore: true */ videoDir, "live-recording.json"));
+ return liveRecordingLength(rec);
+}
+
+/**
+ * A live recording's record's length of the stream, when it is the ended
+ * stream's own and the record says the recording holds it all; else null. Pure.
+ * @param {any} rec live-recording.json
+ * @returns {{ seconds: number, basis: "live-recording" } | null}
+ */
+export function liveRecordingLength(rec) {
+ if (!rec || rec.status !== "landed") return null;
+ if (rec.fromStart !== true || rec.fallback || rec.missingStream || rec.failureClass || rec.error) return null;
+ const c = rec.coverage;
+ if (!c || c.basis !== "duration" || c.covers !== true) return null;
+ const s = Number(c.streamSeconds);
+ return Number.isFinite(s) && s > 0 ? { seconds: s, basis: "live-recording" } : null;
+}
+
+/**
+ * Does a container ending at `containerSeconds` ON THE CUE CLOCK (its length
+ * less the time map's offset at its end) hold the WHOLE recording? With the
+ * sentence that says why (or why not), for a sidecar and a log.
+ * @param {string} videoDir
+ * @param {number} containerSeconds
+ * @returns {Promise<{ whole: boolean, knownSeconds: number | null, basis: "metadata" | "live-recording" | null, why: string }>}
+ */
+export async function recordingWholeness(videoDir, containerSeconds) {
+ const known = await recordingKnownLength(videoDir);
+ const d = containerSeconds.toFixed(2);
+ if (!known) {
+ return {
+ whole: false,
+ knownSeconds: null,
+ basis: null,
+ why: `the saved recording ends at ${d} s and the recording's length is not known (no final duration in its record, no landed live recording that holds the whole stream by its own duration), so it may be partial`,
+ };
+ }
+ const where = known.basis === "metadata" ? "its record's duration" : "the live recording's measured stream";
+ const whole = known.seconds <= containerSeconds + RECORDING_END_TOLERANCE_SECONDS;
+ return {
+ whole,
+ knownSeconds: known.seconds,
+ basis: known.basis,
+ why: whole
+ ? `the saved recording ends at ${d} s, the whole recording (${where} is ${known.seconds} s, within ${RECORDING_END_TOLERANCE_SECONDS} s)`
+ : `the saved recording ends at ${d} s, short of the ${known.seconds} s recording (${where}): it does not hold this window`,
+ };
+}
+
+/**
+ * Does a clamped window still end the recording? Its sidecar's clamp names the
+ * saved-video pointer it was cut from and the known length it was judged by;
+ * both must be as they are now (the pointer's file and bytes; the known length
+ * within 0.5 s). JSON reads only. A clamp from before the pointer was recorded
+ * does not hold.
+ * @param {string} videoDir
+ * @param {{ container?: { file?: string, bytes?: number | null }, knownSeconds?: number } | null | undefined} clamp
+ */
+export async function clampHolds(videoDir, clamp) {
+ if (!clamp || !clamp.container || typeof clamp.container.file !== "string" || !Number.isFinite(clamp.knownSeconds)) return false;
+ const pointer = await readJson(path.join(/* turbopackIgnore: true */ videoDir, "saved-video.json"));
+ if (!pointer || pointer.file !== clamp.container.file) return false;
+ if ((Number.isFinite(pointer.bytes) ? pointer.bytes : null) !== (clamp.container.bytes ?? null)) return false;
+ const known = await recordingKnownLength(videoDir);
+ return !!known && Math.abs(known.seconds - Number(clamp.knownSeconds)) <= 0.5;
+}
+
+// The stream ends a container was measured to, by path, size and mtime.
+/** @type {Map<string, { sig: string, value: { video: number | null, audio: number | null } | null }>} */
+const endsMemo = new Map();
+
+/**
+ * Where a container's picture and its sound each end, in seconds from the
+ * file's start (as ffmpeg's -ss counts them): its last packets, read from 30 s
+ * before `durationSec`. Measured once per container per process. Null when it
+ * cannot be read.
+ * @param {string} file
+ * @param {number} durationSec the container's probed length
+ * @param {string} [ffprobeBin]
+ * @returns {Promise<{ video: number | null, audio: number | null } | null>}
+ */
+export async function containerStreamEnds(file, durationSec, ffprobeBin = "ffprobe") {
+ let st;
+ try {
+ st = await stat(file);
+ } catch {
+ return null;
+ }
+ const sig = `${st.size}:${st.mtimeMs}`;
+ const had = endsMemo.get(file);
+ if (had && had.sig === sig) return had.value;
+ let value = null;
+ try {
+ const from = Math.max(0, durationSec - 30);
+ const { stdout } = await execFileP(
+ ffprobeBin,
+ [
+ "-v", "error",
+ "-read_intervals", `${from.toFixed(3)}%`,
+ "-show_entries", "format=start_time:stream=index,codec_type:stream_disposition=attached_pic:packet=stream_index,pts_time,duration_time",
+ "-of", "json",
+ file,
+ ],
+ { maxBuffer: 1 << 26, timeout: 60_000 },
+ );
+ const doc = JSON.parse(stdout);
+ const start = Number(doc?.format?.start_time);
+ const zero = Number.isFinite(start) ? start : 0;
+ /** @type {Map<number, string>} */
+ const kinds = new Map();
+ for (const s of doc?.streams ?? []) {
+ if (s?.codec_type === "video" && s?.disposition?.attached_pic === 1) continue;
+ kinds.set(Number(s.index), String(s.codec_type));
+ }
+ /** @type {{ video: number | null, audio: number | null }} */
+ const ends = { video: null, audio: null };
+ for (const p of doc?.packets ?? []) {
+ const kind = kinds.get(Number(p.stream_index));
+ if (kind !== "video" && kind !== "audio") continue;
+ const t = Number(p.pts_time);
+ if (!Number.isFinite(t)) continue;
+ const d = Number(p.duration_time);
+ const e = t + (Number.isFinite(d) ? d : 0) - zero;
+ if (ends[kind] === null || e > /** @type {number} */ (ends[kind])) ends[kind] = e;
+ }
+ value = ends.video === null && ends.audio === null ? null : ends;
+ } catch {
+ value = null;
+ }
+ endsMemo.set(file, { sig, value });
+ return value;
+}
+
+/**
+ * The second a clamp may cut a container to: where BOTH its streams have data
+ * (the shorter of the two ends; the one there is, with one), never past its
+ * probed length. Its probed length when the ends cannot be read.
+ * @param {string} file
+ * @param {number} durationSec
+ * @param {string} [ffprobeBin]
+ */
+export async function bothStreamsEnd(file, durationSec, ffprobeBin = "ffprobe") {
+ const ends = await containerStreamEnds(file, durationSec, ffprobeBin);
+ const have = [ends?.video, ends?.audio].filter((x) => typeof x === "number" && Number.isFinite(x) && x > 0);
+ return have.length ? Math.min(durationSec, ...have) : durationSec;
+}
+
+/**
+ * Where a span stands against a container's end. Pure.
+ * "held" to <= end (to EPS);
+ * "past" from >= end - EPS: nothing of it is in the file;
+ * "clamp" it starts inside and ends past: cut to `cutTo` (⌊end⌋₂) if the recording is whole.
+ * @param {{ from: number, to: number }} span on the container's clock
+ * @param {number} end the container's length
+ * @returns {{ kind: "held" } | { kind: "past" } | { kind: "clamp", cutTo: number }}
+ */
+export function spanAtEnd(span, end) {
+ if (span.to <= end + EPS) return { kind: "held" };
+ if (span.from >= end - EPS) return { kind: "past" };
+ return { kind: "clamp", cutTo: floor2(end) };
+}
+
+/**
+ * Does a window hold [from, to]? Whole, to EPS -- or, for a window that ENDS
+ * THE RECORDING (`endsRecording`: a saved container known whole, a window cut
+ * clamped at its end), any span that starts inside it. Pure.
+ * @param {{ from: number, to: number, endsRecording?: boolean }} w
+ * @param {number} from
+ * @param {number} to
+ */
+export function windowHoldsSpan(w, from, to) {
+ if (w.from > from + EPS) return false;
+ if (w.to >= to - EPS) return true;
+ return w.endsRecording === true && from < w.to - EPS;
+}
diff --git a/common/lib/savedVideoWindow-server.test.ts b/common/lib/savedVideoWindow-server.test.ts
@@ -386,3 +386,225 @@ test("an ultrawide saved copy is cut tall once; the second tall ask cuts nothing
assert.deepEqual(second, { kind: "best", height: 810 });
assert.equal((await listClipWindows(c.videoDir, { tiers: true })).length, 1);
});
+
+// THE RECORDING'S END (lane window-end, lib/recordingEnd.mjs): a window that
+// starts inside a saved recording KNOWN WHOLE and ends past it is cut to its
+// end, the clamp recorded; one that starts past it, or a container shorter than
+// the stream it is of, is not-covering as before.
+async function writeMeta(videoDir: string, meta: Record<string, unknown>) {
+ await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify(meta));
+}
+
+test("the last clip: cut ending 1 s before the end, pad 3 s — cut from the saved video, clamped at its end", async () => {
+ const c = await corpus(PICTURE);
+ await writeMeta(c.videoDir, { id: ID, duration: 8 });
+ // The clip is 4–7 of an 8 s recording; its padded window is 1–10.
+ const src = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 });
+ assert.equal(src.kind, "covers");
+ if (src.kind !== "covers") return;
+ assert.ok(src.clamp, "the clamp is on the answer");
+ assert.equal(src.clamp?.askedTo, 10);
+ const end = src.durationSec;
+ assert.equal(src.clamp?.cutTo, Math.floor(end * 100 + 1e-6) / 100);
+ assert.equal(src.clamp?.recordingEnd, src.clamp?.cutTo);
+ assert.match(src.clamp?.why ?? "", /the whole recording \(its record's duration is 8 s, within 2 s\)/);
+ const logs: string[] = [];
+ const w = await cutSavedVideoWindow({
+ paths: c.paths,
+ videoDir: c.videoDir,
+ source: src,
+ from: 1,
+ to: 10,
+ provenance: { requestedBy: "test", clipId: "c9", pad: 3 },
+ onLog: (l) => logs.push(l),
+ });
+ const cutTo = src.clamp!.cutTo;
+ // The name is the footage the file holds, never the end asked.
+ assert.equal(w.file, `1.00-${cutTo.toFixed(2)}.mp4`);
+ assert.equal(w.to, cutTo);
+ const probe = await probeMedia(w.path);
+ assert.ok(Math.abs((probe?.durationSec ?? 0) - (cutTo - 1)) < 0.25, `duration ${probe?.durationSec}`);
+ const sidecar = JSON.parse(await readFile(path.join(c.videoDir, "clips", `1.00-${cutTo.toFixed(2)}.json`), "utf8"));
+ assert.deepEqual(
+ { askedTo: sidecar.clamp.askedTo, cutTo: sidecar.clamp.cutTo, recordingEnd: sidecar.clamp.recordingEnd },
+ { askedTo: 10, cutTo, recordingEnd: cutTo },
+ );
+ assert.match(sidecar.clamp.why, /whole recording/);
+ assert.match(logs.join(""), /clamped at the recording's end \(asked to 10\.00\)/);
+ // The window ENDS THE RECORDING: the same padded ask is answered from it, and so is a later one inside it.
+ assert.equal((await findContainingClipWindow(c.videoDir, 1, 10))?.file, w.file);
+ assert.equal((await findContainingClipWindow(c.videoDir, 3, 11))?.file, w.file);
+ assert.equal(await findContainingClipWindow(c.videoDir, 8.5, 11), null, "a span starting past the end is not held");
+});
+
+test("a window starting at or after the recording's end: not-covering, even known whole", async () => {
+ const c = await corpus(PICTURE);
+ await writeMeta(c.videoDir, { id: ID, duration: 8 });
+ const r = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 8.5, to: 12 });
+ assert.equal(r.kind, "not-covering");
+});
+
+test("a partial container against a longer stream: not-covering, and why", async () => {
+ const c = await corpus(PICTURE);
+ await writeMeta(c.videoDir, { id: ID, duration: 60 });
+ const r = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 });
+ assert.equal(r.kind, "not-covering");
+ if (r.kind === "not-covering") assert.match(r.why ?? "", /short of the 60 s recording/);
+});
+
+test("no known length (no duration, no landed live recording): not-covering — a partial recording may not cover", async () => {
+ const c = await corpus(PICTURE);
+ await writeMeta(c.videoDir, { id: ID, live_status: "is_live", duration: 8 });
+ const r = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 });
+ assert.equal(r.kind, "not-covering");
+ if (r.kind === "not-covering") assert.match(r.why ?? "", /length is not known/);
+});
+
+const LIVE = {
+ status: "landed",
+ url: "https://example.com/live",
+ startedAt: "2026-11-20T00:00:00.000Z",
+ fromStart: true,
+ parts: [],
+ coverage: { capturedSeconds: 8, streamSeconds: 9, basis: "duration", toleranceSeconds: 60, covers: true },
+};
+
+test("a landed live recording whose ended stream's own duration it holds says whole: clamped", async () => {
+ const c = await corpus(PICTURE);
+ await writeFile(path.join(c.videoDir, "live-recording.json"), JSON.stringify(LIVE));
+ const r = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 });
+ assert.equal(r.kind, "covers");
+ if (r.kind === "covers") assert.match(r.clamp?.why ?? "", /live recording's measured stream is 9 s/);
+});
+
+// REVIEW 1, finding 1: the recorder's clock measures the recorder. A from-start
+// recorder that died mid-stream and landed (the end-of-stream refresh still
+// said is_live, so the length is the clock's: its own parts) is partial.
+test("a from-start recorder that died mid-stream and landed: partial, not-covering", async () => {
+ const c = await corpus(PICTURE);
+ await writeMeta(c.videoDir, { id: ID, live_status: "is_live", duration: 8 });
+ const died = { ...LIVE, failureClass: "final", coverage: { capturedSeconds: 8, streamSeconds: 8, basis: "clock", toleranceSeconds: 60, covers: true } };
+ await writeFile(path.join(c.videoDir, "live-recording.json"), JSON.stringify(died));
+ const r = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 });
+ assert.equal(r.kind, "not-covering");
+ if (r.kind === "not-covering") assert.match(r.why ?? "", /length is not known/);
+ // Each fact alone makes it partial: the clock basis, a failure, a live-edge fallback, a missing stream, not covering, not from the start.
+ for (const bad of [
+ { coverage: { ...LIVE.coverage, basis: "clock" } },
+ { failureClass: "final" },
+ { fallback: "live-edge" },
+ { missingStream: "audio" },
+ { coverage: { ...LIVE.coverage, covers: false } },
+ { fromStart: false },
+ ]) {
+ await writeFile(path.join(c.videoDir, "live-recording.json"), JSON.stringify({ ...LIVE, ...bad }));
+ const x = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 });
+ assert.equal(x.kind, "not-covering", JSON.stringify(bad));
+ }
+});
+
+test("a post_live record's duration is not trusted: not-covering", async () => {
+ const c = await corpus(PICTURE);
+ await writeMeta(c.videoDir, { id: ID, live_status: "post_live", duration: 8 });
+ const r = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 });
+ assert.equal(r.kind, "not-covering");
+});
+
+test("a cut that does not reach the end carries no clamp key", async () => {
+ const c = await corpus(PICTURE);
+ await writeMeta(c.videoDir, { id: ID, duration: 8 });
+ const src = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 2, to: 5 });
+ assert.equal(src.kind, "covers");
+ if (src.kind !== "covers") return;
+ assert.equal("clamp" in src, false);
+ await cutSavedVideoWindow({ paths: c.paths, videoDir: c.videoDir, source: src, from: 2, to: 5, provenance: { requestedBy: "test" } });
+ const sidecar = JSON.parse(await readFile(path.join(c.videoDir, "clips", "2.00-5.00.json"), "utf8"));
+ assert.equal("clamp" in sidecar, false);
+});
+
+// REVIEW 1, finding 2: a clamp holds only while its facts do -- the
+// saved-video pointer (file, bytes) and the recording's known length.
+async function clampedWindow() {
+ const c = await corpus(PICTURE);
+ await writeMeta(c.videoDir, { id: ID, duration: 8 });
+ const src = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 });
+ assert.equal(src.kind, "covers");
+ if (src.kind !== "covers") throw new Error("not covers");
+ const w = await cutSavedVideoWindow({ paths: c.paths, videoDir: c.videoDir, source: src, from: 1, to: 10, provenance: { requestedBy: "test" } });
+ const sidecar = JSON.parse(await readFile(path.join(c.videoDir, "clips", w.file.replace(/\.mp4$/, ".json")), "utf8"));
+ assert.deepEqual(sidecar.clamp.container, { file: "source-media.mp4", bytes: 1 });
+ assert.equal(sidecar.clamp.knownSeconds, 8);
+ assert.equal((await findContainingClipWindow(c.videoDir, 1, 10))?.file, w.file, "held while its facts hold");
+ return { c, w };
+}
+
+test("a clamp whose recording's known end moved no longer answers the padded ask", async () => {
+ const { c, w } = await clampedWindow();
+ await writeMeta(c.videoDir, { id: ID, duration: 60 });
+ assert.equal(await findContainingClipWindow(c.videoDir, 1, 10), null);
+ const listed = (await listClipWindows(c.videoDir)).find((x) => x.file === w.file);
+ assert.equal(listed?.clampStale, true);
+ assert.equal(listed?.endsRecording, undefined);
+ // Its own seconds are still its own.
+ assert.equal((await findContainingClipWindow(c.videoDir, 2, 5))?.file, w.file);
+});
+
+test("a clamp whose saved container is another or a longer file no longer answers the padded ask", async () => {
+ const { c, w } = await clampedWindow();
+ const pointer = JSON.parse(await readFile(path.join(c.videoDir, "saved-video.json"), "utf8"));
+ await writeFile(path.join(c.videoDir, "saved-video.json"), JSON.stringify({ ...pointer, bytes: 999999 }));
+ assert.equal(await findContainingClipWindow(c.videoDir, 1, 10), null, "a longer file");
+ await writeFile(path.join(c.videoDir, "saved-video.json"), JSON.stringify({ ...pointer, file: "source-media.webm" }));
+ assert.equal(await findContainingClipWindow(c.videoDir, 1, 10), null, "another file");
+ await writeFile(path.join(c.videoDir, "saved-video.json"), JSON.stringify(pointer));
+ assert.equal((await findContainingClipWindow(c.videoDir, 1, 10))?.file, w.file, "the same pointer again: held");
+});
+
+// REVIEW 1, finding 3: at a container's end the picture and the sound stop
+// apart. The clamp cuts where both have data, so the sync check keeps it.
+async function uneven(videoSec: number, audioSec: number) {
+ const file = path.join(ROOT, "fixtures", `uneven-${videoSec}-${audioSec}.mp4`);
+ ff([
+ "-f", "lavfi", "-i", `testsrc=size=160x90:rate=10:duration=${videoSec}`,
+ "-f", "lavfi", "-i", `sine=frequency=440:duration=${audioSec}`,
+ "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", file,
+ ]);
+ return file;
+}
+
+for (const [v, a] of [[8, 7.6], [7.6, 8]] as const) {
+ test(`a container whose ${v > a ? "audio" : "video"} ends 0.4 s early: the clamp cuts where both streams have data, and the window stays in sync`, async () => {
+ const { findInSyncContainingClipWindow, ffprobeWindowProbe } = await import("./clipWindowSync-server");
+ const c = await corpus(await uneven(v, a));
+ await writeMeta(c.videoDir, { id: ID, duration: 8 });
+ const src = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 });
+ assert.equal(src.kind, "covers");
+ if (src.kind !== "covers") return;
+ assert.ok(src.clamp!.recordingEnd <= 7.65 && src.clamp!.recordingEnd >= 7.5, `cut to ${src.clamp!.recordingEnd}`);
+ const w = await cutSavedVideoWindow({ paths: c.paths, videoDir: c.videoDir, source: src, from: 1, to: 10, provenance: { requestedBy: "test" } });
+ const held = await findInSyncContainingClipWindow(c.videoDir, 1, 10, { probe: ffprobeWindowProbe("ffprobe") });
+ assert.deepEqual(held.desynced, [], "nothing set aside");
+ assert.equal(held.hit?.file, w.file);
+ });
+}
+
+
+test("one clock at the end of the file: the clamp is on the container's clock, the name on the cue clock", async () => {
+ const c = await corpus(PICTURE);
+ const container = path.join(c.storeDir, "source-media.mp4");
+ await writeClock(c.videoDir, container, 2);
+ await writeMeta(c.videoDir, { id: ID, duration: 8 });
+ // Cue 3–9 is the container's 5–11: past its end at ~8.
+ const src = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 3, to: 9 });
+ assert.equal(src.kind, "covers");
+ if (src.kind !== "covers") return;
+ const end = src.clamp!.recordingEnd;
+ assert.equal(src.clock?.mapped.from, 5);
+ assert.equal(src.clock?.mapped.to, end, "the container cut ends at the container's end");
+ assert.equal(src.clamp?.cutTo, Math.floor((end - 2) * 100 + 1e-6) / 100, "the cue-clock end is the container's end less the offset there");
+ const w = await cutSavedVideoWindow({ paths: c.paths, videoDir: c.videoDir, source: src, from: 3, to: 9, provenance: { requestedBy: "test" } });
+ assert.equal(w.file, `3.00-${src.clamp!.cutTo.toFixed(2)}.mp4`);
+ const sidecar = JSON.parse(await readFile(path.join(c.videoDir, "clips", w.file.replace(/\.mp4$/, ".json")), "utf8"));
+ assert.equal(sidecar.clock.from, 5);
+ assert.equal(sidecar.clock.to, end);
+});
diff --git a/common/lib/savedVideoWindow-server.ts b/common/lib/savedVideoWindow-server.ts
@@ -17,9 +17,20 @@
// silent fall-through to the network: the operator who can plug
// the drive in is the one who needs to hear it.
// not-covering a pointer whose container ends before the window does: the
-// network path.
+// network path. `why` says so when the recording's end was
+// weighed (below).
// covers cut it here.
//
+// THE RECORDING'S END (lane window-end, lib/recordingEnd.mjs): a window that
+// starts inside the container and ends past it — the last clip of a recording
+// and its pad — COVERS when the recording is known whole (its record's
+// duration, else a landed live recording's measured stream, within 2 s of the
+// container): `clamp` says the end asked, the end cut (the container's, two
+// decimals rounded down, on the cue clock) and why. The cut ends there, its
+// file is named for the seconds it holds, and its sidecar records the clamp.
+// One that starts at or after the end, or a container shorter than the stream
+// it is of, stays not-covering.
+//
// THE CUT IS evidenceClip-server's (`evidenceCutArgs`): seeked on the input
// and re-encoded, so the window's first frame is the asked-for second; H.264 +
// AAC in an mp4, fitted inside 1280×720 — the container a fetched window is
@@ -55,6 +66,7 @@ import { isDriveNotAnswering, onDrive } from "./storageHealth";
import type { Paths } from "./paths";
import { clockForContainer } from "./recordingClock-read.mjs";
import { mapSpan, type RecordingClock } from "./recordingClock.mjs";
+import { bothStreamsEnd, floor2, recordingWholeness, spanAtEnd } from "./recordingEnd.mjs";
import "./childKillGuard";
// A window cut from a container is seconds of re-encoding; a whole container
@@ -65,7 +77,7 @@ const CUT_TIMEOUT_MS = 10 * 60_000;
export type SavedWindowSource =
| { kind: "none" }
| { kind: "unreadable"; error: string }
- | { kind: "not-covering"; container: string; durationSec: number }
+ | { kind: "not-covering"; container: string; durationSec: number; why?: string }
| {
kind: "covers";
pointer: SavedVideoPointer;
@@ -75,8 +87,24 @@ export type SavedWindowSource =
// The recording's time map, when its video dir has one about THIS
// container (lib/recordingClock.mjs): the span is cut at `mapped`.
clock?: { map: RecordingClock; mapped: ReturnType<typeof mapSpan> };
+ // The window ends past the recording's end: cut to it (the header).
+ clamp?: SavedWindowClamp;
};
+// A window clamped at the recording's end: `askedTo` and `cutTo` on the cue
+// clock (the window's name), `recordingEnd` the container second it ends at.
+// `container` the saved-video pointer it was cut from and `knownSeconds` the
+// length it was judged whole by: a clamp holds only while both are as now
+// (recordingEnd.mjs clampHolds).
+export type SavedWindowClamp = {
+ askedTo: number;
+ cutTo: number;
+ recordingEnd: number;
+ why: string;
+ container: { file: string; bytes: number | null };
+ knownSeconds: number;
+};
+
// The media guard's sentence (lib/channelMedia.ts, ChannelMediaUnreachableError)
// with the saved container as its detail, so a refusal here reads like every
// other unreachable-media refusal the operator has seen.
@@ -133,8 +161,35 @@ export async function savedWindowSource(opts: {
const map = await clockForContainer(opts.videoDir, container);
const mapped = map ? mapSpan(map, opts.from, opts.to) : null;
const span = mapped ?? { from: opts.from, to: opts.to };
- if (opts.from < 0 || span.from < 0 || span.to > durationSec + WIN_EPS) {
- return { kind: "not-covering", container, durationSec };
+ if (opts.from < 0 || span.from < 0) return { kind: "not-covering", container, durationSec };
+ const at = spanAtEnd(span, durationSec);
+ if (at.kind === "past") {
+ return { kind: "not-covering", container, durationSec, why: `the window starts at or after the saved recording's end (${durationSec.toFixed(2)} s)` };
+ }
+ let clamp: SavedWindowClamp | undefined;
+ let cut = mapped;
+ if (at.kind === "clamp") {
+ // Whole, on one clock: the container's end on the cue clock (its length
+ // less the map's offset there -- past the map's last segment its offset
+ // holds, recordingClock clockOffsetAt) against the recording's length.
+ const offsetEnd = mapped ? mapped.offsetTo : 0;
+ const whole = await recordingWholeness(opts.videoDir, durationSec - offsetEnd);
+ if (!whole.whole || whole.knownSeconds === null) return { kind: "not-covering", container, durationSec, why: whole.why };
+ // The cut ends where both streams have data, so the window is in sync to its last frame.
+ const recordingEnd = floor2(await bothStreamsEnd(container, durationSec, opts.paths.ffprobeBin));
+ const cutTo = floor2(recordingEnd - offsetEnd);
+ if (!(span.from < recordingEnd - WIN_EPS) || !(cutTo > opts.from + WIN_EPS)) {
+ return { kind: "not-covering", container, durationSec, why: `the window starts at the saved recording's end (${durationSec.toFixed(2)} s)` };
+ }
+ clamp = {
+ askedTo: opts.to,
+ cutTo,
+ recordingEnd,
+ why: whole.why,
+ container: { file: pointer.file, bytes: Number.isFinite(pointer.bytes) ? pointer.bytes : null },
+ knownSeconds: whole.knownSeconds,
+ };
+ if (mapped) cut = { ...mapped, to: recordingEnd };
}
return {
kind: "covers",
@@ -142,7 +197,8 @@ export async function savedWindowSource(opts: {
container,
durationSec,
probe,
- ...(map && mapped ? { clock: { map, mapped } } : {}),
+ ...(map && cut ? { clock: { map, mapped: cut } } : {}),
+ ...(clamp ? { clamp } : {}),
};
}
@@ -180,7 +236,11 @@ export async function cutSavedVideoWindow(opts: {
onLog?: (line: string) => void;
signal?: AbortSignal;
}): Promise<ClipWindow> {
- const { from, to, source } = opts;
+ const { from, source } = opts;
+ // A window clamped at the recording's end is cut to it and NAMED for it:
+ // the file holds no second past the end, and its name says so.
+ const clamp = source.clamp;
+ const to = clamp ? clamp.cutTo : opts.to;
const tier = isWindowTier(opts.tier) ? opts.tier : undefined;
const box = tier ?? EVIDENCE_MAX_HEIGHT;
const dest = clipWindowPath(opts.videoDir, from, to, tier);
@@ -191,7 +251,7 @@ export async function cutSavedVideoWindow(opts: {
// has one; the file keeps the cue-clock name every reader asks for.
const mapped = source.clock?.mapped ?? null;
const cutFrom = mapped ? mapped.from : from;
- const cutTo = mapped ? mapped.to : to;
+ const cutTo = mapped ? mapped.to : clamp ? clamp.recordingEnd : to;
try {
const r = await execa(opts.paths.ffmpegBin, evidenceCutArgs(source.container, cutFrom, cutTo, kind, tmp, box), {
reject: false,
@@ -239,6 +299,18 @@ export async function cutSavedVideoWindow(opts: {
},
}
: {}),
+ ...(clamp
+ ? {
+ clamp: {
+ askedTo: clamp.askedTo,
+ cutTo: clamp.cutTo,
+ recordingEnd: clamp.recordingEnd,
+ why: clamp.why,
+ container: clamp.container,
+ knownSeconds: clamp.knownSeconds,
+ },
+ }
+ : {}),
};
await writeClipProvenance(opts.videoDir, from, to, provenance, tier);
const onClock = mapped
@@ -249,7 +321,8 @@ export async function cutSavedVideoWindow(opts: {
opts.onLog?.(
`Cut ${from.toFixed(2)}–${to.toFixed(2)}${onClock} from the saved video ${source.pointer.file} into ` +
`clips/${clipWindowFile(from, to, tier)} (${bytes} bytes` +
- `${height !== null ? `, ${height}p` : ""}${source.pointer.compacted ? ", from the compacted re-encode" : ""}); nothing fetched.\n`,
+ `${height !== null ? `, ${height}p` : ""}${source.pointer.compacted ? ", from the compacted re-encode" : ""}` +
+ `${clamp ? `; clamped at the recording's end (asked to ${clamp.askedTo.toFixed(2)}): ${clamp.why}` : ""}); nothing fetched.\n`,
);
return {
file: clipWindowFile(from, to, tier),
diff --git a/common/package.json b/common/package.json
@@ -49,6 +49,7 @@
"./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs",
"./lib/recordingClock.mjs": "./lib/recordingClock.mjs",
"./lib/recordingClock-read.mjs": "./lib/recordingClock-read.mjs",
+ "./lib/recordingEnd.mjs": "./lib/recordingEnd.mjs",
"./lib/jitter.mjs": "./lib/jitter.mjs",
"./lib/ttsTuning.mjs": "./lib/ttsTuning.mjs",
"./lib/montage/cueTextCache.mjs": "./lib/montage/cueTextCache.mjs",
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,24 @@
# Changelog
## [Unreleased]
+- **A clip window past the end of a saved recording is cut from the saved video, clamped at the end.**
+ - Before, the last clip of a recording asked for a window that ended past the saved container (its cut plus a
+ 3 s pad). The window was "not-covering" and went to the platform's download queue: a network fetch for footage
+ that was on disk.
+ - Now a window that starts inside the container is cut from it, to its end, when the recording is known whole:
+ the record's final duration (not while live, upcoming or `post_live`), else a landed live recording's ended
+ stream's own duration with nothing failed or missing. It must be within 2 s of the container's end on the same
+ clock.
+ - The cut ends where both the picture and the sound have data, so the window stays in sync. It is named for what
+ it holds, and its sidecar records `clamp` (the end asked, the end cut, the container it was cut from, the length
+ it was judged by).
+ - The window answers the same ask next time, until the container or the known length changes. Then fetch-windows
+ retires it and asks the span again.
+ - A window that starts at or after the end, a partial container, and a recording of unknown length stay
+ not-covering, with the reason.
+ - `fetch-windows` lists the window under `atRecordingEnd`. `umtool fetch --dry-run` says "saved-video, clamped at
+ the recording's end", and `umtool window` / `timeline insert` say so when the clip is written.
+ - The render holds the clip's end at the recording's last second, never padding with black or silence.
- **umtool: name a channel once for a whole cut.**
- A cut made from two recordings of one channel showed two names for it, the older record's uploader name and
the current one. Before, the only fix was to hand-edit `channelTitle` on every clip.
diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts
@@ -188,8 +188,15 @@ export type FetchWindowsActionResult =
// and why; and the asked height when clips.windowMaxHeight clamped it.
lower?: FetchWindowsLower[];
clampedFrom?: number;
+ // THE RECORDING'S END (lane window-end, lib/recordingEnd.mjs): of the
+ // saved-video group, the windows asked past the end of a saved recording
+ // known whole, which the job cuts clamped at it — the end asked, the end
+ // it will be cut to (the window's name) and why.
+ atRecordingEnd?: FetchWindowsAtEnd[];
};
+export type FetchWindowsAtEnd = { item: FetchWindowsItem; askedTo: number; cutTo: number; why: string };
+
export type FetchWindowsLower = { item: FetchWindowsItem; file: string; height: number | null; asked: number; why: string };
export type FetchWindowsInFlight = { item: FetchWindowsItem; jobId: string };
@@ -242,6 +249,7 @@ async function planFetchWindows(
stored: Set<FetchWindowsItem>;
lower: FetchWindowsLower[];
clampedFrom?: number;
+ atRecordingEnd: FetchWindowsAtEnd[];
}> {
const paths = getPaths();
const settings = getSettings();
@@ -252,6 +260,7 @@ async function planFetchWindows(
const { cap, clampedFrom } = clampWindowCap(maxHeight, ceiling);
const tier = windowTierOf(cap, ceiling);
const lower: FetchWindowsLower[] = [];
+ const atRecordingEnd: FetchWindowsAtEnd[] = [];
const heightProbe = (file: string) => probeVideoHeight({ ffprobeBin: paths.ffprobeBin, file });
const configs = new Map<string, ChannelConfig | null>();
const groups = new Map<string, FetchWindowsGroup>();
@@ -400,6 +409,9 @@ async function planFetchWindows(
queueKey,
items: [],
};
+ if (saved.kind === "covers" && saved.clamp) {
+ atRecordingEnd.push({ item, askedTo: saved.clamp.askedTo, cutTo: saved.clamp.cutTo, why: saved.clamp.why });
+ }
group.items.push(item);
groups.set(queueKey, group);
continue;
@@ -508,6 +520,7 @@ async function planFetchWindows(
registered,
lower,
...(clampedFrom !== undefined ? { clampedFrom } : {}),
+ atRecordingEnd,
};
}
@@ -651,7 +664,7 @@ export async function fetchWindowsAction(
const archive: ConnectedArchive | null = req.archive?.trim()
? findConnectedArchive(connectedArchives(getSettings().remoteArchives), req.archive)
: null;
- const { groups, cached, inFlight, unresolved, stored, registered, lower, clampedFrom } = await planFetchWindows(
+ const { groups, cached, inFlight, unresolved, stored, registered, lower, clampedFrom, atRecordingEnd } = await planFetchWindows(
req.items,
req.queueKey,
req.maxHeight,
@@ -675,6 +688,7 @@ export async function fetchWindowsAction(
refused: [],
...(lower.length ? { lower } : {}),
...(clampedFrom !== undefined ? { clampedFrom } : {}),
+ ...(atRecordingEnd.length ? { atRecordingEnd } : {}),
};
if (req.dryRun) return { ok: true, dryRun: true, ...base };
if (groups.length === 0) return { ok: true, dryRun: false, ...base };
@@ -761,6 +775,7 @@ export async function fetchWindowsAction(
refused,
...(lower.length ? { lower } : {}),
...(clampedFrom !== undefined ? { clampedFrom } : {}),
+ ...(atRecordingEnd.length ? { atRecordingEnd } : {}),
};
}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -1221,8 +1221,15 @@ async function cmdWindow() {
try {
const { updateTakeClip } = await import("../lib/report/takeEdit.mjs");
const res = await updateTakeClip(p.dir, take, clipId, patch);
- if (json) return out({ ok: true, take, ...res });
+ // The last clip's pad past a whole saved recording's end: said, nothing to change (lib/report/recordingEndNote.mjs).
+ const atEnd = await (async () => {
+ const { recordingEndOf } = await import("../lib/report/recordingEndNote.mjs");
+ const { resolveTakeManifest } = await import("../lib/report/takeManifest.mjs");
+ return recordingEndOf(p, (await resolveTakeManifest(p.dir, take)).manifest, res.entry).catch(() => null);
+ })();
+ if (json) return out({ ok: true, take, ...res, ...(atEnd ? { atRecordingEnd: atEnd } : {}) });
console.log(`${clipId} (take ${take}): ${res.before.start}–${res.before.end} -> ${res.entry.start}–${res.entry.end}`);
+ if (atEnd) console.log((await import("../lib/report/recordingEndNote.mjs")).recordingEndLine(atEnd));
if (res.entry.cutStart != null) console.log(` cut: ${res.entry.cutStart}–${res.entry.cutEnd}`);
if (gapsText(res.entry)) console.log(` gaps: ${gapsText(res.entry)}`);
if (patch.verdict !== undefined || patch.correction !== undefined) console.log(` review: ${reviewWords(res.entry)}`);
@@ -1241,10 +1248,14 @@ async function cmdWindow() {
// routes use: on a generated manifest the change is also an `edit` note
// for the agent that generates it, or the next rebuild undoes it silently.
const { result: res, editNotes } = await withEditNotes(p, () => updateClip(p.dir, clipId, patch));
- if (json) return out({ ok: true, ...res, editNotes });
+ // The last clip's pad past a whole saved recording's end: said, nothing to change (lib/report/recordingEndNote.mjs).
+ const { recordingEndOf, recordingEndLine } = await import("../lib/report/recordingEndNote.mjs");
+ const atEnd = await (async () => recordingEndOf(p, await (await import("../lib/projects/report.mjs")).readManifest(p.dir), res.entry))().catch(() => null);
+ if (json) return out({ ok: true, ...res, editNotes, ...(atEnd ? { atRecordingEnd: atEnd } : {}) });
console.log(
`${clipId}: ${res.before.start}–${res.before.end} -> ${res.entry.start}–${res.entry.end}`,
);
+ if (atEnd) console.log(recordingEndLine(atEnd));
if (res.entry.cutStart != null) {
console.log(
` cut: ${res.entry.cutStart}–${res.entry.cutEnd} ` +
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -50,6 +50,12 @@ clip says which one that is, and `umtool set` prints a NOTE. A window save that
clip's window is refused: widen the window, or clear `claim.at`. The On-screen table's claim column edits the
claim's id and verdict and keeps its knobs while the id stays the same.
+**A clip at the end of its recording.** A clip's `end` may run to the end of a saved recording known whole. Its
+fetch pad past that end is not a reason to shorten it. The editor cuts the window from the saved video, clamped at
+the end. `umtool window` / `timeline insert` print `at the recording's end: …`, `umtool fetch <p> --dry-run` prints
+`at end <clip>: saved-video, clamped at the recording's end`, and the render holds the end at the recording's last
+second. There is no knob: it is the rule in OPERATING.md, "Prepare and export reports".
+
## The cite follows the edge
A clip's `cite` is the second the clock prints and its `citeUrl`'s `t=` the second the QR opens; both
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -3161,6 +3161,25 @@ cannot resolve); **Start** queues one paced job per platform and the panel
follows them to their end, naming each window a job failed. Every run is
recorded in `fetch-runs.json` beside the manifest.
+THE LAST CLIP OF A RECORDING (lane window-end). A clip whose cut ends in the
+last seconds of a saved recording asks for a window that ends past it, because
+of the pad. When the recording is known whole (its record's duration, else a
+landed live recording's, within 2 s of the container), the editor cuts that
+window from the saved video, clamped at the end. Nothing is fetched. The dry
+run prints `at end <clip>: saved-video, clamped at the recording's end (asked
+to X, cut to Y) — why`, and `umtool window` / `timeline insert` print an
+`at the recording's end:` line.
+
+The build, cut points and every lookup read the clamped window (or the whole
+container) as ending the recording, while its clamp still matches the saved
+video and the recording's known length. A gap-joined clip's last piece stops
+at the end too. A montage phrase cut at the very end is not yet held there. Silence detection stops at the end, and
+the clip's end is held at the file's last second: it never snaps past it, and
+nothing is padded with black or silence. A clip whose own end is past the
+recording's plays to the end, with a note. So keep a last clip's whole ending;
+shortening it loses seconds that are on disk. The rule and its limits are in
+OPERATING.md, "Prepare and export reports".
+
TALLER WINDOWS ARE OPT-IN per project: `umtool look <p> tallWindows=true` ([knobs.md](knobs.md#taller-windows-rendertallwindows)).
Without it nothing here changes: no `maxHeight` in the body, no height probe, no taller window read. With it the
body carries `maxHeight`, the manifest's `render.maxHeightSource`, and the editor keeps a taller window beside the 720
diff --git a/umtool/lib/report/cutPoints.mjs b/umtool/lib/report/cutPoints.mjs
@@ -202,7 +202,8 @@ async function diskSourceOf(entry, ctx) {
const offset = await cached("offset", fk, async () => (await alignedClipSource(disk)).startOffset ?? 0);
const fetchStart = disk.fetchStart + offset;
const scan = disk.scan ? { from: Math.max(0, disk.scan.from - offset), to: disk.scan.to - offset } : null;
- return { path: src.path, fk, fetchStart, scan };
+ // A file ending the recording (the last clip's pad past it): where its footage stops, the build's own hold.
+ return { path: src.path, fk, fetchStart, scan, ...(Number.isFinite(disk.sourceEnd) ? { sourceEnd: disk.sourceEnd } : {}) };
}
/**
@@ -258,7 +259,7 @@ async function clipCutPoints(real, ctx) {
const pieced = disk.pieced ?? null;
const entry = pieced ? pieced.entry : real;
const src = { path: disk.path };
- const { fk, fetchStart, scan } = disk;
+ const { fk, fetchStart, scan, sourceEnd } = disk;
const k = snapKnobs(render);
const sil = await cached(
"silences",
@@ -269,7 +270,7 @@ async function clipCutPoints(real, ctx) {
const locked = lockedEdges(entry, render);
// A clip's gaps (gaps.mjs): no edge snaps across one, as in the build. None in a montage.
const clipGaps = montage ? [] : renderGaps(entry, render);
- const cut = renderCut({ sil, fetchStart, playFrom: pw.from, playTo: pw.to, render, locked, ...(clipGaps.length ? { gaps: clipGaps } : {}) });
+ const cut = renderCut({ sil, fetchStart, playFrom: pw.from, playTo: pw.to, render, locked, ...(clipGaps.length ? { gaps: clipGaps } : {}), ...(Number.isFinite(sourceEnd) ? { sourceEnd } : {}) });
const { cutA, cutB } = cut.file;
let segA = cutA;
let segB = cutB;
diff --git a/umtool/lib/report/fetchCli.mjs b/umtool/lib/report/fetchCli.mjs
@@ -70,6 +70,12 @@ export function summaryLines(s) {
for (const l of s.lower ?? []) {
lines.push(` lower ${l.clipId}: ${l.height !== null ? `${l.height}p` : "height unknown"} (asked ${l.asked}p) in ${l.file} — ${l.why}`);
}
+ // THE RECORDING'S END: the last clip's pad runs past a whole saved recording -- cut from it, to its end.
+ for (const e of s.atRecordingEnd ?? []) {
+ lines.push(
+ ` at end ${e.clipId}: saved-video, clamped at the recording's end (asked to ${e.askedTo.toFixed(2)}, cut to ${e.cutTo.toFixed(2)}) — ${e.why}`,
+ );
+ }
return lines;
}
diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs
@@ -403,6 +403,14 @@ export function summarizeAnswer(a) {
why: String(l.why ?? ""),
})),
...(Number.isFinite(Number(a?.clampedFrom)) ? { clampedFrom: Number(a.clampedFrom) } : {}),
+ // THE RECORDING'S END (lane window-end): windows asked past the end of a
+ // saved recording known whole, cut from it clamped at that end.
+ atRecordingEnd: (a?.atRecordingEnd ?? []).map((e) => ({
+ clipId: label(e.item),
+ askedTo: Number(e.askedTo),
+ cutTo: Number(e.cutTo),
+ why: String(e.why ?? ""),
+ })),
jobs: (a?.jobs ?? []).map((j) => ({ platform: j.platform, queueKey: j.queueKey ?? null, jobId: j.jobId, items: Number(j.items ?? 0) })),
};
}
diff --git a/umtool/lib/report/fetchWindows.test.mjs b/umtool/lib/report/fetchWindows.test.mjs
@@ -322,3 +322,37 @@ test("a tall project's body carries its maxHeightSource as maxHeight; the answer
assert.ok(lines.some((l) => /2160p asked; the editor's clips\.windowMaxHeight/.test(l)));
assert.deepEqual(summarizeAnswer({}).lower, []);
});
+
+// THE RECORDING'S END (lane window-end): the editor plans the last clip's
+// window on the saved-video queue, clamped at the recording's end, and the dry
+// run says so in those words.
+test("umtool fetch --dry-run: a window past a whole saved recording's end reads 'saved-video, clamped at the recording's end'", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "umtool-fetch-"));
+ try {
+ const dir = path.join(root, "synth-oops");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(MANIFEST, null, 2));
+ const ed = fakeEditor({
+ "POST /api/ops/fetch-windows": (b) => ({
+ ok: true,
+ dryRun: true,
+ groups: [{ platform: "saved-video", queueKey: "clips:saved-video", items: [b.items[1]] }],
+ cached: [],
+ inFlight: [],
+ unresolved: [],
+ atRecordingEnd: [{ item: b.items[1], askedTo: 7.5, cutTo: 6.96, why: "the saved recording ends at 6.96 s, the whole recording (its record's duration is 7 s, within 2 s)" }],
+ }),
+ });
+ const cfg = { url: "http://editor.test", token: "tok", fetch: ed.fetch };
+ const lines = [];
+ assert.equal(await fetchCommand(["synth-oops", "--dry-run"], { root, out: (s) => lines.push(s), err: (s) => lines.push(s), cfg, pollMs: 1 }), 0);
+ const text = lines.join("\n");
+ assert.match(text, /saved-video 1 window\(s\)/);
+ assert.match(text, /at end {5}s02: saved-video, clamped at the recording's end \(asked to 7\.50, cut to 6\.96\) — the saved recording ends at 6\.96 s/);
+ const doc = await readFetchRuns(dir);
+ assert.deepEqual(doc.runs[0].summary.atRecordingEnd, [{ clipId: "s02", askedTo: 7.5, cutTo: 6.96, why: "the saved recording ends at 6.96 s, the whole recording (its record's duration is 7 s, within 2 s)" }]);
+ assert.deepEqual(summarizeAnswer({}).atRecordingEnd, []);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/recordingEndNote.mjs b/umtool/lib/report/recordingEndNote.mjs
@@ -0,0 +1,73 @@
+// THE RECORDING'S END, SAID WHERE A CLIP'S EXTENT IS WRITTEN (lane window-end):
+// `umtool window` and `timeline insert` say when a clip's padded fetch window
+// runs past the end of a saved recording known whole -- the last clip of a
+// recording, its pad past the end. Nothing has to change: the editor cuts that
+// window from the saved video clamped at the end (common/lib/recordingEnd.mjs),
+// `umtool fetch --dry-run` says "saved-video, clamped at the recording's end",
+// and the render holds the clip's end there (snap.mjs `endAt`). So the clip
+// keeps its whole ending; shortening it to dodge a network fetch loses seconds
+// that are on disk.
+//
+// Cheap: the record's duration is read first, and a clip whose padded end is
+// more than the tolerance before it costs nothing more. Only a clip near the
+// end asks the disk (sources.mjs resolveLocalSource over the corpus tiers: a
+// window the editor already cut clamped, else the saved container's probe).
+// Never fetches, never writes.
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { resolveLocalSource, ffprobeSource } from "umtool-report-to-video/sources";
+import { RECORDING_END_TOLERANCE_SECONDS } from "yt-dlp-transcript-common/lib/recordingEnd.mjs";
+import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { channelFor, channelsDirFor, hasShadowChannels } from "../projects/report.mjs";
+
+/**
+ * Where a clip's padded fetch window stands against the end of its saved
+ * recording: null when it does not reach it (or nothing says where it is),
+ * else the end, the window and whether the clip's own end is past it.
+ *
+ * @param {{ dir: string }} project
+ * @param {Record<string, any>} manifest the manifest the clip is read in (a take's, for a take)
+ * @param {Record<string, any>} entry
+ * @param {{ probe?: Function, channelsDir?: string }} [opts]
+ * @returns {Promise<null | { recordingEnd: number, from: number, to: number, clipEndPast: boolean, source: string }>}
+ */
+export async function recordingEndOf(project, manifest, entry, opts = {}) {
+ if (!entry || entry.type !== "clip" || entry.src || !entry.video) return null;
+ const start = Number(entry.start);
+ const end = Number(entry.end);
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
+ const slug = channelFor(manifest, entry);
+ if (!slug) return null;
+ const render = manifest?.render ?? {};
+ const pad = Number.isFinite(Number(render.fetchPad)) ? Number(render.fetchPad) : 3;
+ const from = Number(Math.max(0, start - pad).toFixed(2));
+ const to = Number((end + pad).toFixed(2));
+ const channelsDir = opts.channelsDir ?? channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) });
+ // The record's own length first: far from the end, nothing is probed.
+ const videoDir = await resolveVideoDir(channelsDir, slug, String(entry.video)).catch(() => null);
+ if (videoDir) {
+ try {
+ const d = Number(JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8"))?.duration);
+ if (Number.isFinite(d) && d > 0 && to < d - RECORDING_END_TOLERANCE_SECONDS) return null;
+ } catch {
+ // No record: the disk is asked.
+ }
+ }
+ const hit = await resolveLocalSource(
+ { video: String(entry.video), slug, from, to },
+ { channelsDir, probe: opts.probe ?? ffprobeSource, kinds: ["corpus-window", "saved-video"], render },
+ );
+ if (!hit?.endsRecording || !(hit.windowEnd < to)) return null;
+ const recordingEnd = Number(hit.windowEnd.toFixed(2));
+ return { recordingEnd, from, to, clipEndPast: end > hit.windowEnd + 0.05, source: hit.kind };
+}
+
+/** The line `umtool window` / `timeline insert` print for it. Pure. */
+export function recordingEndLine(r) {
+ if (!r) return null;
+ return (
+ ` at the recording's end: its fetch window ${r.from.toFixed(2)}–${r.to.toFixed(2)} runs past the saved recording's end ` +
+ `(${r.recordingEnd.toFixed(2)} s, known whole) — cut from the saved video, clamped there; nothing is fetched` +
+ (r.clipEndPast ? `. Its end is past the recording's: it plays to ${r.recordingEnd.toFixed(2)}` : "")
+ );
+}
diff --git a/umtool/lib/report/recordingEndNote.test.mjs b/umtool/lib/report/recordingEndNote.test.mjs
@@ -0,0 +1,65 @@
+// THE RECORDING'S END at window / insert time (lane window-end): a clip whose
+// padded fetch window runs past a whole saved recording's end is said to be
+// cut from the saved video, clamped there; a clip far from the end, or a
+// partial recording, says nothing.
+//
+// Run with: node --test lib/report/recordingEndNote.test.mjs
+import assert from "node:assert/strict";
+import test from "node:test";
+import path from "node:path";
+import os from "node:os";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { recordingEndLine, recordingEndOf } from "./recordingEndNote.mjs";
+
+async function tree(meta) {
+ const root = await mkdtemp(path.join(os.tmpdir(), "umtool-recend-"));
+ const channelsDir = path.join(root, "channels");
+ const videoDir = path.join(channelsDir, "synth-chan", "data", "vid1");
+ const storeDir = path.join(root, "store");
+ await mkdir(videoDir, { recursive: true });
+ await mkdir(storeDir, { recursive: true });
+ await writeFile(path.join(storeDir, "source-media.mp4"), Buffer.alloc(16, 1));
+ await writeFile(path.join(videoDir, "saved-video.json"), JSON.stringify({ storedAt: "2026-11-21T00:00:00Z", dir: storeDir, file: "source-media.mp4", bytes: 16 }));
+ if (meta) await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify(meta));
+ const project = { dir: path.join(root, "proj") };
+ await mkdir(project.dir, { recursive: true });
+ const manifest = { provenance: { channelsDir, channelSlug: "synth-chan" }, render: { fetchPad: 3 } };
+ return { root, project, manifest };
+}
+
+const clip = (start, end) => ({ type: "clip", id: "last", video: "vid1", start, end });
+const probe = async () => ({ duration: 300.5 });
+
+test("a clip ending 1 s before a whole recording's end, pad 3: said, and the line names the clamp", async () => {
+ const t = await tree({ id: "vid1", duration: 300 });
+ try {
+ const r = await recordingEndOf(t.project, t.manifest, clip(290, 299.5), { probe });
+ assert.deepEqual(r, { recordingEnd: 300.5, from: 287, to: 302.5, clipEndPast: false, source: "saved-video" });
+ assert.match(recordingEndLine(r), /runs past the saved recording's end \(300\.50 s, known whole\) — cut from the saved video, clamped there; nothing is fetched$/);
+ // Its end itself past the recording's: it plays to the end.
+ const past = await recordingEndOf(t.project, t.manifest, clip(295, 301.5), { probe });
+ assert.equal(past.clipEndPast, true);
+ assert.match(recordingEndLine(past), /it plays to 300\.50$/);
+ } finally {
+ await rm(t.root, { recursive: true, force: true });
+ }
+});
+
+test("far from the end nothing is probed; a partial recording says nothing", async () => {
+ const t = await tree({ id: "vid1", duration: 300 });
+ try {
+ let probed = 0;
+ const counting = async () => (probed++, { duration: 300.5 });
+ assert.equal(await recordingEndOf(t.project, t.manifest, clip(100, 110), { probe: counting }), null);
+ assert.equal(probed, 0);
+ } finally {
+ await rm(t.root, { recursive: true, force: true });
+ }
+ const p = await tree({ id: "vid1", duration: 3600 });
+ try {
+ assert.equal(await recordingEndOf(p.project, p.manifest, clip(290, 299.5), { probe }), null);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+ assert.equal(recordingEndLine(null), null);
+});
diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs
@@ -659,6 +659,8 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
let result;
let editNotes = null;
let attribution = null;
+ // A clip inserted at a recording's end (its pad past a whole saved recording's): said (recordingEndNote.mjs).
+ let atEnd = null;
switch (verb) {
case "insert": {
const toSection = intFlag(flags, "--to-section");
@@ -722,6 +724,10 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
result = done.result;
editNotes = done.editNotes;
attribution = done.attribution;
+ {
+ const { recordingEndOf } = await import("./recordingEndNote.mjs");
+ atEnd = await recordingEndOf(project, manifest, attribution ?? result?.entry ?? null).catch(() => null);
+ }
if (done.attributionError) {
// The clip is in; only its header failed. Say both, and how to finish.
const msg = done.attributionError;
@@ -937,10 +943,11 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
}
if (json) {
- out(JSON.stringify({ ok: true, op: verb, ...result, ...(attribution ? { entry: attribution } : {}), editNotes }, null, 2));
+ out(JSON.stringify({ ok: true, op: verb, ...result, ...(attribution ? { entry: attribution } : {}), editNotes, ...(atEnd ? { atRecordingEnd: atEnd } : {}) }, null, 2));
return 0;
}
out(summaryOf(verb, result, attribution));
+ if (atEnd) out((await import("./recordingEndNote.mjs")).recordingEndLine(atEnd));
for (const line of result.reanchored ?? []) out(` re-anchored: ${line}`);
// What a restored clip's removal re-anchored or dropped stays as it is now: said, not undone.
for (const line of result.notPutBack ?? []) out(` not put back: ${line}`);
@@ -1067,13 +1074,21 @@ async function takeTimeline(project, take, verb, rest, flags, { out, json }) {
} else {
result = await edit.undoTakeEdit(project.dir, take, { token });
}
+ // A clip inserted at a recording's end (its pad past a whole saved recording's): said (recordingEndNote.mjs).
+ let atEnd = null;
+ if (verb === "insert" && result?.entry) {
+ const { recordingEndOf } = await import("./recordingEndNote.mjs");
+ const { resolveTakeManifest } = await import("./takeManifest.mjs");
+ atEnd = await (async () => recordingEndOf(project, (await resolveTakeManifest(project.dir, take)).manifest, result.entry))().catch(() => null);
+ }
if (json) {
- out(JSON.stringify({ ok: true, op: verb, take, ...result }, null, 2));
+ out(JSON.stringify({ ok: true, op: verb, take, ...result, ...(atEnd ? { atRecordingEnd: atEnd } : {}) }, null, 2));
return 0;
}
if (verb === "undo") out(`take ${take}: undid ${result.op}: restored ${result.restored} (the state before the undo kept as ${result.saved})`);
else {
out(`take ${take}: ${summaryOf(verb, result, null)}`);
+ if (atEnd) out((await import("./recordingEndNote.mjs")).recordingEndLine(atEnd));
out(` undo point: takes/${take}/${result.revision.rel} (umtool timeline ${project.id} --take ${take} undo)`);
}
return 0;
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -1307,6 +1307,11 @@ export async function onDiskClipSource(entry, meta, render, local, opts = {}) {
if (!hit) return null;
// What the log calls it: a fallback is not the same fact as an audio-only clip.
const kind = hit.kind === "audio" && use === "audio-fallback" ? "audio-fallback" : hit.kind;
+ // THE RECORDING'S END (lane window-end, sources.mjs `endsRecording`): the
+ // file ends the recording before the padded span does -- the last clip's pad
+ // runs past the end. `sourceEnd` is where its footage stops (source
+ // seconds): the scan stops there and the cut never passes it.
+ const ends = hit.endsRecording === true && hit.windowEnd < to;
return {
path: hit.path,
fetchStart: hit.windowStart,
@@ -1314,13 +1319,15 @@ export async function onDiskClipSource(entry, meta, render, local, opts = {}) {
source: kind,
// A whole container is hours long and silence detection decodes what it
// is given: give it the span a fetch would have produced, no more.
- ...(hit.kind === "raw-cache" ? {} : { scan: { from: from - hit.windowStart, to: to - hit.windowStart } }),
+ ...(hit.kind === "raw-cache" ? {} : { scan: { from: from - hit.windowStart, to: (ends ? hit.windowEnd : to) - hit.windowStart } }),
+ ...(ends ? { sourceEnd: hit.windowEnd } : {}),
log: {
id: entry.id, video: entry.video, from, to, cached: true, source: kind,
...(hit.kind !== "raw-cache" || hit.name !== name ? { reuse: hit.name } : {}),
local: hit.path,
window: [hit.windowStart, hit.windowEnd],
...(hit.height ? { height: hit.height } : {}),
+ ...(ends ? { atRecordingEnd: true } : {}),
},
};
}
@@ -1476,6 +1483,16 @@ export async function piecedClipSource(entry, meta, render, local, opts, outDir)
if (await onDiskClipSource(entry, meta, render, local, opts)) return null;
const parts = [];
for (const span of spans) parts.push({ span, ...(await fetchClipAligned(entry, meta, render, local, { ...opts, span })) });
+ // THE RECORDING'S END (lane window-end): the last piece's source ends the
+ // recording before its span does (its pad past the end): the piece is held
+ // to where its footage stops, so the joined file carries no frozen frame or
+ // silence past it, and the cut stops there too (`sourceEnd` on the pieces clock).
+ const last = parts[parts.length - 1];
+ if (Number.isFinite(last.sourceEnd) && last.sourceEnd < last.span.to && last.sourceEnd > last.span.from) {
+ last.span = { ...last.span, to: last.sourceEnd };
+ spans[spans.length - 1] = last.span;
+ }
+ const endsRecording = Number.isFinite(last.sourceEnd) && last.span.to === last.sourceEnd;
const probes = await Promise.all(parts.map((p) => probeMedia(p.path)));
const withPicture = probes.filter((p) => p.hasVideo).length;
if (withPicture && withPicture < parts.length) {
@@ -1537,7 +1554,10 @@ export async function piecedClipSource(entry, meta, render, local, opts, outDir)
id: entry.id, file: path.basename(file), seconds: Number(clock.total.toFixed(2)),
pieces: spans.map((s) => [Number(s.from.toFixed(2)), Number(s.to.toFixed(2))]),
});
- return { path: file, fetchStart: 0, cached: true, source: "pieces", clock, entry: virtualEntry(entry, clock) };
+ return {
+ path: file, fetchStart: 0, cached: true, source: "pieces", clock, entry: virtualEntry(entry, clock),
+ ...(endsRecording ? { sourceEnd: clock.total } : {}),
+ };
}
// The silences of a file, in its own seconds (cut-points.mjs detectSilence,
@@ -1579,7 +1599,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
// (piecedClipSource): `clipE` is the clip on that file's clock, `toReal`
// maps a cut on it back to the source's. Every other clip: itself, as ever.
const pieced = await piecedClipSource(entry, meta, render, dirs.local, opts, outDir);
- const { path: raw, fetchStart, scan } = pieced ?? (await fetchClipAligned(entry, meta, render, dirs.local, opts));
+ const { path: raw, fetchStart, scan, sourceEnd } = pieced ?? (await fetchClipAligned(entry, meta, render, dirs.local, opts));
const clipE = pieced ? pieced.entry : entry;
const toReal = pieced ? pieced.clock.toReal : (t) => t;
// Every file this writes in segments/ is written through a rename (the
@@ -1625,9 +1645,18 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
}
}
- // Desired cut points, expressed relative to the over-fetched file.
+ // Desired cut points, expressed relative to the over-fetched file. A file
+ // that ENDS THE RECORDING (onDiskClipSource `sourceEnd`: the last clip, its
+ // pad past the end) holds the end at its last second -- never a cut past it,
+ // so nothing is padded with black or silence for seconds that do not exist.
+ const endAt = Number.isFinite(sourceEnd) ? sourceEnd - fetchStart : null;
const wantA = playFrom - fetchStart;
- const wantB = playTo - fetchStart;
+ const wantB = endAt !== null ? Math.min(playTo - fetchStart, endAt) : playTo - fetchStart;
+ if (endAt !== null && playTo - fetchStart > endAt + 0.05) {
+ EMIT("note", {
+ message: `${entry.id}: its end ${toReal(playTo).toFixed(2)} is past the recording's end ${toReal(sourceEnd).toFixed(2)} — it plays to the end`,
+ });
+ }
const win = render.snapWindow ?? 1.6;
const sil = await detectSilence(raw, render, scan);
@@ -1654,6 +1683,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
// and no edge snaps across a gap (a gap's edges are exact).
const snapped = mont ? null : snapCut({
sil, wantA, wantB, render, locked: lockedEdges(clipE, render),
+ ...(endAt !== null ? { endAt } : {}),
...(clipGaps.length ? { gaps: clipGaps.map((g) => ({ from: g.from - fetchStart, to: g.to - fetchStart })) } : {}),
});
const a = mont ? mont.win.start : snapped.a;
diff --git a/umtool/report-to-video/snap.mjs b/umtool/report-to-video/snap.mjs
@@ -86,7 +86,8 @@ export const GAP_KEEP = GAP_LIMITS.keep;
* desired end, the end at least a second after the start.
*
* @param {{ sil: Array<{ s: number, e: number }>, wantA: number, wantB: number, render?: Record<string, any>,
- * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null }} o
+ * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null,
+ * endAt?: number | null }} o
* `wantA`/`wantB`: the play window's edges in the file's seconds; `locked`:
* which of them are the author's, exact (mute.mjs lockedEdges) -- each
* snapped only outward, inside its own silence; `gaps`: the clip's gaps
@@ -94,10 +95,17 @@ export const GAP_KEEP = GAP_LIMITS.keep;
* edge snaps across one (nor nearer it than GAP_KEEP): such a snap is not
* taken and the edge stays where it was asked
*/
-export function snapCut({ sil, wantA, wantB, render = {}, locked = null, gaps = null }) {
+export function snapCut({ sil, wantA, wantB: asked, render = {}, locked = null, gaps = null, endAt = null }) {
const win = render.snapWindow ?? SNAP_DEFAULTS.snapWindow;
+ // THE RECORDING'S END (lane window-end): a file that ends the recording
+ // (`endAt`, its last second on the file's clock) is never cut past it -- the
+ // end is held there and does not snap beyond it, so nothing is padded with
+ // black or silence for seconds that do not exist.
+ const end = Number.isFinite(endAt) ? Number(endAt) : Infinity;
+ const wantB = Math.min(asked, end);
let a = snap(wantA, sil, "start", win, render, { pinned: !!locked?.start });
let b = snap(wantB, sil, "end", win, render, { pinned: !!locked?.end });
+ if (b.at > end) b = { at: end, snapped: false };
if (gaps?.length) {
const first = gaps.reduce((m, g) => Math.min(m, g.from), Infinity);
const last = gaps.reduce((m, g) => Math.max(m, g.to), -Infinity);
@@ -105,7 +113,7 @@ export function snapCut({ sil, wantA, wantB, render = {}, locked = null, gaps =
if (b.at < wantB && b.at < last + GAP_KEEP) b = { at: wantB, snapped: false };
}
const cutA = Math.min(a.at, wantB - 1);
- const cutB = Math.max(b.at, cutA + 1);
+ const cutB = Math.min(Math.max(b.at, cutA + 1), Math.max(end, cutA));
return { win, a, b, cutA, cutB };
}
@@ -117,14 +125,18 @@ export const recordSecond = (fetchStart, t) => Number((fetchStart + t).toFixed(3
* file it is cut from: what `<id>.cut.json` records (`start`, `end`,
* `snapped`) for a clip with no room and no montage. `playFrom`/`playTo` are
* the play window (deck.mjs playWindow); `fetchStart` the file's first
- * second in the recording; `gaps` the clip's (gaps.mjs), source seconds.
+ * second in the recording; `gaps` the clip's (gaps.mjs), source seconds;
+ * `sourceEnd` the source second the file's footage ends at when it ends the
+ * recording (onDiskClipSource) -- the cut never passes it.
*
* @param {{ sil: Array<{ s: number, e: number }>, fetchStart: number, playFrom: number, playTo: number, render?: Record<string, any>,
- * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null }} o
+ * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null,
+ * sourceEnd?: number | null }} o
*/
-export function renderCut({ sil, fetchStart, playFrom, playTo, render = {}, locked = null, gaps = null }) {
+export function renderCut({ sil, fetchStart, playFrom, playTo, render = {}, locked = null, gaps = null, sourceEnd = null }) {
const c = snapCut({
sil, wantA: playFrom - fetchStart, wantB: playTo - fetchStart, render, locked,
+ ...(Number.isFinite(sourceEnd) ? { endAt: Number(sourceEnd) - fetchStart } : {}),
...(gaps?.length ? { gaps: gaps.map((g) => ({ from: g.from - fetchStart, to: g.to - fetchStart })) } : {}),
});
return {
diff --git a/umtool/report-to-video/snap.test.mjs b/umtool/report-to-video/snap.test.mjs
@@ -22,3 +22,22 @@ test("snap: snapTail / snapLead keep more of the pause, never more than it holds
assert.equal(Number(snap(20, SIL, "end", 1, render).at.toFixed(3)), 20.12);
assert.equal(snap(20.1, SIL, "start", 1, render).at, 20);
});
+
+// THE RECORDING'S END (lane window-end): a file that ends the recording holds
+// the cut's end at its last second -- never snapped or cut past it.
+test("snapCut / renderCut: a file ending the recording holds the end at its last second", async () => {
+ const { snapCut, renderCut } = await import("./snap.mjs");
+ // The file's last second is 9.5; a pause at 9.4-9.9 would snap the end past it.
+ const sil = [{ s: 9.4, e: 9.9 }];
+ const free = snapCut({ sil, wantA: 3, wantB: 9.45, render: {} });
+ assert.ok(free.cutB > 9.5, `without the end the snap goes to ${free.cutB}`);
+ const held = snapCut({ sil, wantA: 3, wantB: 9.45, render: {}, endAt: 9.5 });
+ assert.ok(held.cutB <= 9.5, `held at ${held.cutB}`);
+ // An end asked past the file's last second plays to it.
+ assert.equal(snapCut({ sil: [], wantA: 3, wantB: 12, render: {}, endAt: 9.5 }).cutB, 9.5);
+ // renderCut takes the source second: 100 + 9.5.
+ const cut = renderCut({ sil: [], fetchStart: 100, playFrom: 103, playTo: 112, render: {}, sourceEnd: 109.5 });
+ assert.equal(cut.end, 109.5);
+ // Nothing said: as before.
+ assert.equal(renderCut({ sil: [], fetchStart: 100, playFrom: 103, playTo: 112, render: {} }).end, 112);
+});
diff --git a/umtool/report-to-video/sources.test.mjs b/umtool/report-to-video/sources.test.mjs
@@ -29,6 +29,7 @@ import {
findContainingWindow,
localSources,
needsFetchMessage,
+ onDiskClipSource,
planLocalSources,
} from "./build-video.mjs";
@@ -689,3 +690,166 @@ test("a tall ask between rungs resolves the rung's window: 900 and 1000 read .h1
await rm(t.root, { recursive: true, force: true });
}
});
+
+// THE RECORDING'S END (lane window-end, common/lib/recordingEnd.mjs): the last
+// clip's padded span runs past a saved recording KNOWN WHOLE -- its container
+// serves it, ending the recording; a span starting past the end, or a
+// container shorter than its record, does not. A corpus window the editor cut
+// clamped at the end (its sidecar's `clamp`) serves the same padded span.
+test("the recording's end: a whole saved recording serves a padded span past its end; a partial one does not", async () => {
+ const t = await tree();
+ try {
+ await touch(path.join(t.storeDir, "source-media.mp4"));
+ await pointTo(t.videoDir, t.storeDir, "source-media.mp4");
+ const cfg = { channelsDir: t.channelsDir, probe: fakeProbe(300.5).probe };
+ // The clip is 290-299.5, padded 3: 287-302.5.
+ const want = { video: VIDEO, slug: SLUG, from: 287, to: 302.5 };
+ assert.equal(await resolveLocalSource(want, cfg), null, "no known length: a partial recording may not cover");
+ await writeFile(path.join(t.videoDir, "metadata.info.json"), JSON.stringify({ id: VIDEO, duration: 301 }));
+ const hit = await resolveLocalSource(want, cfg);
+ assert.equal(hit?.kind, "saved-video");
+ assert.equal(hit.windowEnd, 300.5);
+ assert.equal(hit.endsRecording, true);
+ assert.equal(await resolveLocalSource({ ...want, from: 300.6, to: 305 }, cfg), null, "a span starting past the end");
+ // The record says the stream is longer than the container: not whole.
+ await writeFile(path.join(t.videoDir, "metadata.info.json"), JSON.stringify({ id: VIDEO, duration: 3600 }));
+ assert.equal(await resolveLocalSource(want, cfg), null);
+ // A span inside the container is served as ever, and says nothing about the end.
+ const inside = await resolveLocalSource({ ...want, from: 100, to: 110 }, cfg);
+ assert.equal(inside.endsRecording, undefined);
+ } finally {
+ await rm(t.root, { recursive: true, force: true });
+ }
+});
+
+// The editor's clamp (common/lib/clipWindow.ts): the pointer it was cut from
+// and the known length it was judged by -- re-checked on every lookup.
+async function clampedCorpusWindow(t) {
+ await touch(path.join(t.storeDir, "source-media.mp4"));
+ await pointTo(t.videoDir, t.storeDir, "source-media.mp4");
+ await writeFile(path.join(t.videoDir, "metadata.info.json"), JSON.stringify({ id: VIDEO, duration: 300 }));
+ await touch(path.join(t.clipsDir, "287.00-300.49.mp4"));
+ await writeFile(
+ path.join(t.clipsDir, "287.00-300.49.json"),
+ JSON.stringify({
+ requestedBy: "umtool",
+ source: "saved-video",
+ clamp: { askedTo: 302.5, cutTo: 300.49, recordingEnd: 300.49, why: "whole", container: { file: "source-media.mp4", bytes: 16 }, knownSeconds: 300 },
+ }),
+ );
+}
+
+test("the recording's end: the editor's clamped window serves the same padded span, before the container is probed", async () => {
+ const t = await tree();
+ try {
+ await clampedCorpusWindow(t);
+ const { probe, calls } = fakeProbe(300.5);
+ const hit = await resolveLocalSource({ video: VIDEO, slug: SLUG, from: 287, to: 302.5 }, { channelsDir: t.channelsDir, probe });
+ assert.equal(hit?.kind, "corpus-window");
+ assert.equal(hit.name, "287.00-300.49.mp4");
+ assert.equal(hit.endsRecording, true);
+ assert.deepEqual(calls, [], "nothing probed");
+ // A window with no clamp in its sidecar is no answer for the padded span.
+ await writeFile(path.join(t.clipsDir, "287.00-300.49.json"), JSON.stringify({ requestedBy: "umtool" }));
+ const miss = await resolveLocalSource({ video: VIDEO, slug: SLUG, from: 287, to: 302.5 }, { channelsDir: t.channelsDir, probe });
+ assert.notEqual(miss?.kind, "corpus-window");
+ } finally {
+ await rm(t.root, { recursive: true, force: true });
+ }
+});
+
+// REVIEW 1, finding 2: a clamp whose facts moved is an ordinary window again.
+test("the recording's end: a clamped window whose known end moved, or whose container changed, ends nothing", async () => {
+ const t = await tree();
+ try {
+ await clampedCorpusWindow(t);
+ const cfg = { channelsDir: t.channelsDir, probe: fakeProbe(300.5).probe };
+ const want = { video: VIDEO, slug: SLUG, from: 287, to: 302.5 };
+ assert.equal((await resolveLocalSource(want, cfg))?.kind, "corpus-window");
+ await writeFile(path.join(t.videoDir, "metadata.info.json"), JSON.stringify({ id: VIDEO, duration: 3600 }));
+ assert.equal(await resolveLocalSource(want, cfg), null, "the known end moved: neither the window nor the container");
+ await writeFile(path.join(t.videoDir, "metadata.info.json"), JSON.stringify({ id: VIDEO, duration: 300 }));
+ await pointTo(t.videoDir, t.storeDir, "source-media.mp4", { bytes: 17 });
+ const other = await resolveLocalSource(want, cfg);
+ assert.notEqual(other?.kind, "corpus-window", "another container: the clamped window does not answer");
+ // Its own seconds are still served.
+ assert.equal((await resolveLocalSource({ ...want, to: 299 }, cfg))?.name, "287.00-300.49.mp4");
+ } finally {
+ await rm(t.root, { recursive: true, force: true });
+ }
+});
+
+test("the recording's end: the build's on-disk source stops its scan at the end and says where the footage stops", async () => {
+ const t = await tree();
+ try {
+ await touch(path.join(t.storeDir, "source-media.mp4"));
+ await pointTo(t.videoDir, t.storeDir, "source-media.mp4");
+ await writeFile(path.join(t.videoDir, "metadata.info.json"), JSON.stringify({ id: VIDEO, duration: 300 }));
+ const local = localSources({ rawDir: t.rawDir, channelsDir: t.channelsDir, probe: fakeProbe(300.5).probe });
+ // The clip ends 1 s before the end; the pad is 3 s.
+ const entry = { type: "clip", id: "last", channel: SLUG, video: VIDEO, start: 290, end: 299.5 };
+ const src = await onDiskClipSource(entry, null, { fetchPad: 3 }, local, {});
+ assert.equal(src?.source, "saved-video");
+ assert.equal(src.sourceEnd, 300.5);
+ assert.deepEqual(src.scan, { from: 287, to: 300.5 });
+ assert.equal(src.log.atRecordingEnd, true);
+ // A clip well inside: no sourceEnd, the scan as ever.
+ const mid = await onDiskClipSource({ ...entry, start: 100, end: 110 }, null, { fetchPad: 3 }, local, {});
+ assert.equal(mid.sourceEnd, undefined);
+ assert.deepEqual(mid.scan, { from: 97, to: 113 });
+ // REVIEW 1, nit: a corpus window a hair (under WIN_EPS) short of the span is scanned to the span, as on main.
+ await writeFile(path.join(t.clipsDir, "196.00-220.99.mp4"), Buffer.alloc(16, 1));
+ const hair = await onDiskClipSource({ ...entry, start: 199, end: 218 }, null, { fetchPad: 3 }, local, {});
+ assert.equal(hair.source, "corpus-window");
+ assert.deepEqual(hair.scan, { from: 0, to: 25 });
+ } finally {
+ await rm(t.root, { recursive: true, force: true });
+ }
+});
+
+// REVIEW 1: a gap-joined clip's LAST piece at the recording's end is held to
+// where its footage stops -- no frozen frame or silence past it in the joined
+// file -- and the cut stops there (`sourceEnd` on the pieces clock).
+test("the recording's end: a gap-joined clip's last piece stops at the end", async () => {
+ const { execFileSync, spawnSync } = await import("node:child_process");
+ if (!["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0)) return;
+ const { piecedClipSource } = await import("./build-video.mjs");
+ const root = await mkdtemp(path.join(os.tmpdir(), "rtv-pieces-end-"));
+ try {
+ const mk = (file, seconds) =>
+ execFileSync("ffmpeg", [
+ "-nostdin", "-v", "error", "-y",
+ "-f", "lavfi", "-i", `testsrc=size=160x90:rate=10:duration=${seconds}`,
+ "-f", "lavfi", "-i", `sine=frequency=440:duration=${seconds}`,
+ "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", file,
+ ]);
+ const first = path.join(root, "9.00-16.00.mp4");
+ const last = path.join(root, "source-media.mp4");
+ mk(first, 7);
+ // The recording's last 10.5 s, 90–100.5: it ends the recording.
+ mk(last, 10.5);
+ const local = {
+ rawDir: null,
+ channelsDir: null,
+ slugOf: () => SLUG,
+ resolve: async (_e, span) =>
+ span.from < 50 && span.to <= 16
+ ? { kind: "corpus-window", path: first, name: "9.00-16.00.mp4", windowStart: 9, windowEnd: 16 }
+ : span.from < 90
+ ? null
+ : { kind: "saved-video", path: last, name: "source-media.mp4", windowStart: 90, windowEnd: 100.5, endsRecording: true },
+ };
+ // 10-100 with 15-95 cut out: pieces 9-16 and 94-101, 78 s apart. The last ends past the recording's 100.5.
+ const entry = { type: "clip", id: "pe", channel: SLUG, video: VIDEO, start: 10, end: 100, gaps: [{ from: 15, to: 95 }] };
+ const render = { fps: 10, fetchPad: 1 };
+ await mkdir(path.join(root, "out", "segments"), { recursive: true });
+ const r = await piecedClipSource(entry, null, render, local, {}, path.join(root, "out"));
+ assert.ok(r, "cut from its pieces");
+ assert.deepEqual(r.clock.spans, [{ from: 9, to: 16 }, { from: 94, to: 100.5 }]);
+ assert.equal(r.sourceEnd, 13.5, "the end on the pieces clock: 7 + 6.5");
+ const out = execFileSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", r.path]).toString();
+ assert.ok(Math.abs(Number(out) - 13.5) < 0.15, `the joined file is ${out.trim()} s, no padding past the end`);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});