Archilyzer · Source

archilyzer

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

commit d397ad6a21802f7696a22d80bd9081e42831003e
parent c65635188cb2182a01683fd0b77e833268621b49
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 11:29:52 -0500

window-end review 1: a live length only from the ended stream, clamps re-checked and retired, the cut where both streams end

1. A landed live recording counts as whole only by the ended stream's own
   duration (coverage.basis "duration", covers, from the start) with no
   failure, live-edge fallback or missing stream on the record. The
   recorder's clock measures the recorder: one that died mid-stream is
   partial, not-covering as before. A post_live record's duration is not
   trusted. Lengths are compared on one clock (the container's end less the
   time map's offset at the end).
2. A clamp records the saved-video pointer it was cut from (file, bytes) and
   the known length it was judged by, and every lookup re-checks both (JSON
   reads, memoised by size and mtime; no probe). When they moved, the window
   answers only its own seconds (listClipWindows `clampStale`, the corpus
   tier's sidecar check), and fetch-windows retires it the way it retires a
   window cut on another clock, then asks the span again.
3. The clamp cuts where BOTH streams have data: the shorter of the picture's
   and the sound's ends, from the container's last packets, measured once per
   container per process, so the sync check never sets the window aside.
   umtool's saved-video tier ends the window there too.

Also: the build's narrower silence scan applies only at the recording's end
(ordinary windows scan as on main); a gap-joined clip's last piece is held to
where its footage stops (no frozen frame or silence past it) and the cut stops
there. Docs and the CHANGELOG follow.

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

Diffstat:
MOPERATING.md | 27++++++++++++++++++++-------
Mcommon/controller/fetchWindows.test.ts | 45+++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/fetchWindows.ts | 30++++++++++++++++++++++++++++++
Mcommon/lib/clipWindow-server.ts | 14++++++++++++--
Mcommon/lib/clipWindow.ts | 33+++++++++++++++++++++++++++++----
Mcommon/lib/evidenceClip.mjs | 49+++++++++++++++++++++++++++++++++++++++++++------
Mcommon/lib/recordingEnd.mjs | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mcommon/lib/savedVideoWindow-server.test.ts | 128+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/lib/savedVideoWindow-server.ts | 54+++++++++++++++++++++++++++++++++++++++++++-----------
Meditor/CHANGELOG.md | 11++++++++---
Mumtool/docs/report-video.md | 4+++-
Mumtool/report-to-video/build-video.mjs | 19++++++++++++++++---
Mumtool/report-to-video/sources.test.mjs | 99++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
13 files changed, 656 insertions(+), 62 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -1372,16 +1372,29 @@ pnpm ops reports-export --json '{"siteId":"example-site","formats":["html","md" - **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 the - record's `duration` (metadata.info.json; ignored while the record says the stream is live or upcoming), else a - landed live recording's measured `coverage.streamSeconds`, is at most 2 s longer than the container. yt-dlp's - duration is whole seconds, and the muxer rounds the last frame. - - The cut ends at the container's end, 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`), and its sidecar records - `clamp: {askedTo, cutTo, recordingEnd, why}`. Nothing is fetched. + - 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). diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts @@ -1013,3 +1013,48 @@ test("the recording's end: a window past a whole saved recording's end is cut cl 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 @@ -385,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>; @@ -416,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; @@ -538,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, @@ -898,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 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"; @@ -37,8 +38,13 @@ export type ClipWindow = { // 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. + // 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. @@ -94,7 +100,11 @@ export async function listClipWindows( provenance, ...(tier !== undefined ? { tier } : {}), ...(height !== undefined ? { height } : {}), - ...(provenance?.clamp ? { endsRecording: true as const } : {}), + ...(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 @@ -327,12 +327,24 @@ export type ClipProvenance = { // 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. + // 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; }; -export type ClipWindowClamp = { askedTo: number; cutTo: number; recordingEnd: number; why: string }; +// `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; @@ -341,7 +353,20 @@ export function coerceClipWindowClamp(v: unknown): ClipWindowClamp | undefined { 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 : "" }; + 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 }; diff --git a/common/lib/evidenceClip.mjs b/common/lib/evidenceClip.mjs @@ -53,7 +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 { recordingWholeness, windowHoldsSpan } from "./recordingEnd.mjs"; +import { bothStreamsEnd, clampHolds, recordingWholeness, windowHoldsSpan } from "./recordingEnd.mjs"; const execFileP = promisify(execFile); @@ -381,12 +381,38 @@ export async function ffprobeSource(file, bin = process.env.FFPROBE_BIN ?? "ffpr 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 { - const c = JSON.parse(await readFile(windowPath.slice(0, -ext.length) + ".json", "utf8"))?.clamp; - return !!c && typeof c === "object" && Number.isFinite(c.askedTo) && Number.isFinite(c.cutTo) && c.askedTo > c.cutTo; + st = await stat(sidecar); } catch { - return false; + 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 */ @@ -456,8 +482,19 @@ async function savedVideoWindows({ video, slug, channelsDir, platform, probe = f } // THE RECORDING'S END: a span starting inside and ending past a container // that holds the whole recording -- the container ends the recording. - if (want && want.to > w.to + WIN_EPS && want.from < w.to - WIN_EPS && (await recordingWholeness(videoDir, duration)).whole) { - w.endsRecording = true; + // 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(w); } diff --git a/common/lib/recordingEnd.mjs b/common/lib/recordingEnd.mjs @@ -20,12 +20,35 @@ // - 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. +// 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 @@ -42,8 +65,12 @@ // 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 { 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; @@ -54,15 +81,53 @@ 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 { - return JSON.parse(await readFile(file, "utf8")); + 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 @@ -70,17 +135,31 @@ async function readJson(file) { */ 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 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")); - const s = Number(rec?.coverage?.streamSeconds); - if (rec?.status === "landed" && Number.isFinite(s) && s > 0) return { seconds: s, basis: "live-recording" }; - return null; + return liveRecordingLength(rec); } /** - * Does a container of `containerSeconds` hold the WHOLE recording? With the + * 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 @@ -94,7 +173,7 @@ export async function recordingWholeness(videoDir, containerSeconds) { 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`, + 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"; @@ -110,6 +189,104 @@ export async function recordingWholeness(videoDir, containerSeconds) { } /** + * 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; diff --git a/common/lib/savedVideoWindow-server.test.ts b/common/lib/savedVideoWindow-server.test.ts @@ -460,17 +460,135 @@ test("no known length (no duration, no landed live recording): 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 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({ 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 } }), - ); + 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"); diff --git a/common/lib/savedVideoWindow-server.ts b/common/lib/savedVideoWindow-server.ts @@ -66,7 +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 { bothStreamsEnd, floor2, recordingWholeness, spanAtEnd } from "./recordingEnd.mjs"; import "./childKillGuard"; // A window cut from a container is seconds of re-encoding; a whole container @@ -93,7 +93,17 @@ export type SavedWindowSource = // 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 }; +// `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 @@ -159,16 +169,27 @@ export async function savedWindowSource(opts: { 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)) { + // 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: at.cutTo, why: whole.why }; - if (mapped) cut = { ...mapped, to: at.cutTo }; + 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", @@ -278,7 +299,18 @@ export async function cutSavedVideoWindow(opts: { }, } : {}), - ...(clamp ? { clamp: { askedTo: clamp.askedTo, cutTo: clamp.cutTo, recordingEnd: clamp.recordingEnd, why: clamp.why } } : {}), + ...(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 diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -6,9 +6,14 @@ 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 duration, else a landed live recording's measured stream, within 2 s of the container. The file is - named for what it holds. Its sidecar records `clamp` (the end asked, the end cut, why), and it answers the same - ask next time. + 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 diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -3171,7 +3171,9 @@ 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. Silence detection stops at the end, and +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; diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -1319,7 +1319,7 @@ 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: Math.min(to, hit.windowEnd) - 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, @@ -1483,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) { @@ -1544,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, @@ -1641,7 +1654,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, 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 ${playTo.toFixed(2)} is past the recording's end ${sourceEnd.toFixed(2)} — it plays to the end`, + 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; diff --git a/umtool/report-to-video/sources.test.mjs b/umtool/report-to-video/sources.test.mjs @@ -722,14 +722,27 @@ test("the recording's end: a whole saved recording serves a padded span past its } }); +// 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 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" } }), - ); + 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"); @@ -738,7 +751,29 @@ test("the recording's end: the editor's clamped window serves the same padded sp 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" })); - assert.equal(await resolveLocalSource({ video: VIDEO, slug: SLUG, from: 287, to: 302.5 }, { channelsDir: t.channelsDir, probe }), null); + 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 }); } @@ -762,7 +797,59 @@ test("the recording's end: the build's on-disk source stops its scan at the end 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 }); + } +});