Archilyzer · Source

archilyzer

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

commit 449feca23e3265efd95578b9d22a5eb03ea9d09f
parent 25156ab10ca6c9fd32d7e8a54b00776a7bacd9cb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 10:34:43 -0500

common, editor, umtool: a window past a whole saved recording's end is cut from it, clamped at the end

A clip whose cut ends in the last seconds of a locally saved recording asks
for a window that ends past the container (the cut plus its pad). The
saved-video check answered "not-covering" and the window went to the
platform's download queue: a network fetch of footage that is on disk.

lib/recordingEnd.mjs is the rule: a span that starts inside the container and
ends past it is held, cut to the container's end (two decimals, rounded down),
when the recording is KNOWN WHOLE -- its record's duration, else a landed live
recording's measured stream, within 2 s of the container. No known length, or
a stream longer than the container by more than 2 s, stays not-covering, as
does a window starting at or after the end.

savedWindowSource answers "covers" with a `clamp` (asked end, cut end on the
cue clock, the container's end, why); the one-clock map is applied first and
its offset at the end gives the cue-clock end. cutSavedVideoWindow names the
file for the seconds it holds and records the clamp in its sidecar; a window
carrying it ENDS THE RECORDING, so clipWindowContains holds any later span
starting inside it and the same padded ask is answered from the cache.
fetch-windows reports `atRecordingEnd` in its result and in the editor's plan;
umtool fetch prints "saved-video, clamped at the recording's end".

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

Diffstat:
Mcommon/controller/fetchWindows.test.ts | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/fetchWindows.ts | 18+++++++++++++++---
Mcommon/lib/clipWindow-server.ts | 4++++
Mcommon/lib/clipWindow.ts | 34+++++++++++++++++++++++++++++++---
Acommon/lib/recordingEnd.mjs | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/savedVideoWindow-server.test.ts | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/savedVideoWindow-server.ts | 57+++++++++++++++++++++++++++++++++++++++++++++++++--------
Meditor/app/channels/[slug]/videos/fetchWindowsAction.ts | 17++++++++++++++++-
Mumtool/lib/report/fetchCli.mjs | 6++++++
Mumtool/lib/report/fetchWindows.mjs | 8++++++++
Mumtool/lib/report/fetchWindows.test.mjs | 34++++++++++++++++++++++++++++++++++
11 files changed, 458 insertions(+), 15 deletions(-)

diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts @@ -961,3 +961,55 @@ 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); +}); 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; @@ -817,9 +823,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); @@ -1090,7 +1102,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 +1268,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 @@ -36,6 +36,9 @@ 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`): it holds any span starting inside it. + endsRecording?: true; }; // Every fetched window in a video dir, oldest-window-first by start second. @@ -91,6 +94,7 @@ export async function listClipWindows( provenance, ...(tier !== undefined ? { tier } : {}), ...(height !== undefined ? { height } : {}), + ...(provenance?.clamp ? { endsRecording: 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,28 @@ 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: it holds any span starting inside + // it (clipWindowContains), so the same padded ask is not cut again. + clamp?: ClipWindowClamp; }; +export type ClipWindowClamp = { askedTo: number; cutTo: number; recordingEnd: number; why: string }; + +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; + return { askedTo, cutTo, recordingEnd, why: typeof r.why === "string" ? r.why : "" }; +} + export type ClipWindowClock = { id: string; from: number; to: number; offset: number; certain: boolean }; export function coerceClipWindowClock(v: unknown): ClipWindowClock | undefined { @@ -413,20 +433,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/recordingEnd.mjs b/common/lib/recordingEnd.mjs @@ -0,0 +1,139 @@ +// 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 <= D + RECORDING_END_TOLERANCE_SECONDS. L is the record's own `duration` +// (metadata.info.json; ignored while the record says the stream is live or +// upcoming), else a LANDED live recording's measured stream length +// (live-recording.json `coverage.streamSeconds`). No known length is NOT whole: +// a partial recording (a live capture joined late, a download cut short) +// really may not hold the window, and a network fetch is then still right. +// +// 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 { readFile } from "node:fs/promises"; +import path from "node:path"; + +/** 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; + +/** @param {string} file @returns {Promise<any>} */ +async function readJson(file) { + try { + return JSON.parse(await readFile(file, "utf8")); + } catch { + return null; + } +} + +/** + * 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 && typeof meta === "object" && (meta.live_status === "is_live" || meta.live_status === "is_upcoming"); + 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")); + const s = Number(rec?.coverage?.streamSeconds); + if (rec?.status === "landed" && Number.isFinite(s) && s > 0) return { seconds: s, basis: "live-recording" }; + return null; +} + +/** + * Does a container of `containerSeconds` 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 duration in its record, no landed live recording), 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`, + }; +} + +/** + * 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,107 @@ 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/); +}); + +test("a landed live recording's measured stream says whole: clamped", async () => { + const c = await corpus(PICTURE); + await writeFile( + path.join(c.videoDir, "live-recording.json"), + JSON.stringify({ status: "landed", url: "https://example.com/live", startedAt: "2026-11-20T00:00:00.000Z", parts: [], coverage: { capturedSeconds: 8, streamSeconds: 9, basis: "duration", toleranceSeconds: 60, covers: true } }), + ); + 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/); +}); + +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 { 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,14 @@ 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. +export type SavedWindowClamp = { askedTo: number; cutTo: number; recordingEnd: number; why: string }; + // 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 +151,24 @@ 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") { + const whole = await recordingWholeness(opts.videoDir, durationSec); + if (!whole.whole) return { kind: "not-covering", container, durationSec, why: whole.why }; + // On the cue clock: the container's end less the map's offset there (past + // the map's last segment its offset holds: recordingClock clockOffsetAt). + const cutTo = mapped ? floor2(at.cutTo - mapped.offsetTo) : at.cutTo; + if (!(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: at.cutTo, why: whole.why }; + if (mapped) cut = { ...mapped, to: at.cutTo }; } return { kind: "covers", @@ -142,7 +176,8 @@ export async function savedWindowSource(opts: { container, durationSec, probe, - ...(map && mapped ? { clock: { map, mapped } } : {}), + ...(map && cut ? { clock: { map, mapped: cut } } : {}), + ...(clamp ? { clamp } : {}), }; } @@ -180,7 +215,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 +230,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 +278,7 @@ export async function cutSavedVideoWindow(opts: { }, } : {}), + ...(clamp ? { clamp: { askedTo: clamp.askedTo, cutTo: clamp.cutTo, recordingEnd: clamp.recordingEnd, why: clamp.why } } : {}), }; await writeClipProvenance(opts.videoDir, from, to, provenance, tier); const onClock = mapped @@ -249,7 +289,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/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/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 }); + } +});