Archilyzer · Source

archilyzer

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

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

umtool, common: the build and every lookup read a window at the recording's end as ending it

evidenceClip.mjs (umtool's sources and the sites' evidence cut) takes the
same rule as the editor (lib/recordingEnd.mjs): a saved container known
whole, for a span passing its end, and a corpus window whose sidecar records
the editor's clamp ENDS THE RECORDING and holds any span starting inside it.
The source says `endsRecording`. Only near-miss sidecars are read; the
container's record is read only for a span past its probed end.

The build's on-disk source stops its silence scan at the end and carries
`sourceEnd`; snapCut / renderCut take it as `endAt` / `sourceEnd` and never
cut or snap past it, so the last clip plays to the recording's last second
with no black or silent padding (a note when its own end was past it). The
cut-points route reads the same.

`umtool window` and `timeline insert` (project and take) print an
"at the recording's end" line when a clip's padded window runs past a whole
saved recording's end (lib/report/recordingEndNote.mjs: the record's duration
first, so a clip far from the end costs no probe). Docs: OPERATING.md,
umtool/docs/report-video.md and knobs.md, the CHANGELOG.

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

Diffstat:
MOPERATING.md | 18++++++++++++++++++
Mcommon/lib/evidenceClip.mjs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mcommon/package.json | 1+
Meditor/CHANGELOG.md | 13+++++++++++++
Mumtool/bin/umtool.mjs | 15+++++++++++++--
Mumtool/docs/knobs.md | 6++++++
Mumtool/docs/report-video.md | 17+++++++++++++++++
Mumtool/lib/report/cutPoints.mjs | 7++++---
Aumtool/lib/report/recordingEndNote.mjs | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/recordingEndNote.test.mjs | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/timelineCli.mjs | 19+++++++++++++++++--
Mumtool/report-to-video/build-video.mjs | 25+++++++++++++++++++++----
Mumtool/report-to-video/snap.mjs | 24++++++++++++++++++------
Mumtool/report-to-video/snap.test.mjs | 19+++++++++++++++++++
Mumtool/report-to-video/sources.test.mjs | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
15 files changed, 420 insertions(+), 29 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -1369,6 +1369,24 @@ pnpm ops reports-export --json '{"siteId":"example-site","formats":["html","md" - `fetch-windows` with `siteId` fetches every clip window the site's published reports cite that the disk does not hold, one paced job per platform; a re-run resumes. It stays at 720: a site's evidence clip is cut inside 1280×720 from the plain `<from>-<to>.mp4` window. +- **A window that runs past the end of a saved recording is cut from it, clamped at the end.** This is the last clip + of a recording plus its pad. The rule is in `common/lib/recordingEnd.mjs` and applies to `fetch-windows`, + fetch-window, `fetch_clip`, live-clip and the umtool build. + - The window must START inside the saved container and the recording must be KNOWN WHOLE. Known whole means 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. + - 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)`. + - Still `not-covering`, as before: a window that starts at or after the end; a container shorter than the known + length by more than 2 s, which is a partial recording; and a recording whose length is not known. The reason is + given (a whole-recording platform's item fails with it). + - So do not shorten a last clip to avoid a network fetch. Keep its whole end (`umtool window <p> <clip> --end E`), + then `umtool fetch <p> --dry-run`. - A window asked taller than 720 (`"maxHeight"` on `fetch-windows`, fetch-window, `fetch_clip`; umtool sends it only for a project with `render.tallWindows` on) is its own file beside the 720 one: `clips/<from>-<to>.h<tier>.mp4`, with its own sidecar. The 720 window is never replaced, retired or re-fetched for this. An ask with no `maxHeight` diff --git a/common/lib/evidenceClip.mjs b/common/lib/evidenceClip.mjs @@ -29,6 +29,15 @@ // its pad — to WIN_EPS. Within a tier the tightest wins; across tiers the order // above wins. // +// THE RECORDING'S END (lane window-end, ./recordingEnd.mjs): a window that ENDS +// THE RECORDING holds any span starting inside it -- the seconds past its end +// exist nowhere, so the last clip's pad past the end is not a reason to fetch. +// Such a window is a saved container KNOWN WHOLE (its record's duration, else a +// landed live recording's, within 2 s), for a span passing its end, and a +// corpus window the editor cut clamped at that end (its sidecar's `clamp`). +// The source it resolves to says `endsRecording: true`; its `windowEnd` is +// where the footage stops. +// // A file in `data/<id>/` may be a RELATIVE symlink into `media/`, which may be // an absolute symlink to another drive. Every candidate is `stat`ed through its // links before it is returned, and a dangling one — an unmounted drive — is @@ -44,6 +53,7 @@ import { promisify } from "node:util"; import { resolveVideoDir } from "./videoDir-server.mjs"; import { clockForContainer } from "./recordingClock-read.mjs"; import { mapSpan } from "./recordingClock.mjs"; +import { recordingWholeness, windowHoldsSpan } from "./recordingEnd.mjs"; const execFileP = promisify(execFile); @@ -95,8 +105,9 @@ export async function listNames(dir) { * @typedef {{ id: string, offset: number, certain: boolean }} SourceClock * the recording's time map applied to a saved container (recordingClock.mjs): * the offset the span was mapped by, and whether the map was sure of it - * @typedef {{ name: string, path: string, from: number, to: number, height?: number, clock?: SourceClock }} SourceWindow - * @typedef {{ kind: string, path: string, name: string, windowStart: number, windowEnd: number, height?: number, clock?: SourceClock }} LocalSource + * @typedef {{ name: string, path: string, from: number, to: number, height?: number, clock?: SourceClock, endsRecording?: boolean }} SourceWindow + * `endsRecording`: the window ends where the recording does (./recordingEnd.mjs) + * @typedef {{ kind: string, path: string, name: string, windowStart: number, windowEnd: number, height?: number, clock?: SourceClock, endsRecording?: boolean }} LocalSource * @typedef {(file: string) => Promise<{ duration: number, height?: number } | null>} SourceProbe * @typedef {{ video: string, slug?: string | null, channelsDir?: string | null, rawDir?: string | null, probe?: SourceProbe, platform?: string | null, want?: { from: number, to: number }, maxHeight?: number, heightOf?: (kind: string, w: SourceWindow) => Promise<number | null> }} TierContext * `want`: the span being resolved, when there is one (resolveFromTiers sets it) -- the @@ -112,13 +123,15 @@ export async function listNames(dir) { */ /** - * Does this window hold [from, to] whole, to the tolerance? - * @param {{ from: number, to: number }} w + * Does this window hold [from, to] whole, to the tolerance? A window that ENDS + * THE RECORDING (`endsRecording`) holds any span starting inside it + * (./recordingEnd.mjs windowHoldsSpan). + * @param {{ from: number, to: number, endsRecording?: boolean }} w * @param {number} from * @param {number} to */ export function windowContains(w, from, to) { - return !(w.from > from + WIN_EPS || w.to < to - WIN_EPS); + return windowHoldsSpan(w, from, to); } /** @@ -360,16 +373,42 @@ export async function ffprobeSource(file, bin = process.env.FFPROBE_BIN ?? "ffpr // one context `{video, slug, channelsDir, probe}`. A tier that cannot apply (no // channelsDir or slug) lists nothing. +/** + * Does a corpus window's sidecar record a clamp at the recording's end (the + * editor's `clamp`, lib/clipWindow.ts)? + * @param {string} windowPath + */ +async function sidecarClamped(windowPath) { + const ext = CORPUS_WINDOW_EXTS.find((x) => windowPath.endsWith(x)); + if (!ext) return false; + 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; + } catch { + return false; + } +} + /** @param {TierContext} ctx */ -async function corpusWindows({ video, slug, channelsDir, platform, maxHeight }) { +async function corpusWindows({ video, slug, channelsDir, platform, maxHeight, want }) { if (!channelsDir || !slug) return []; const dir = corpusClipsDir(await recordDirOf(channelsDir, slug, video, platform)); const names = await listNames(dir); const plain = windowsFromBareNames(names, dir); - if (!isTallAsk(maxHeight)) return plain; + const all = isTallAsk(maxHeight) ? [...plain, ...tieredWindowsFromNames(names, dir)] : plain; + // THE RECORDING'S END: a window starting by the span's start and ending + // before its end -- a near miss -- holds it when the editor cut it clamped at + // the recording's end. Only those sidecars are read. + if (want) { + for (const w of all) { + if (w.from <= want.from + WIN_EPS && w.to < want.to - WIN_EPS && w.to > want.from + WIN_EPS && (await sidecarClamped(w.path))) { + w.endsRecording = true; + } + } + } + if (!isTallAsk(maxHeight)) return all; // A TALL ASK: the tiered windows too, and every window's recorded height // (the editor writes it in the sidecar; an old window has none until asked). - const all = [...plain, ...tieredWindowsFromNames(names, dir)]; for (const w of all) { const h = await sidecarHeight(w.path); if (h !== undefined) w.height = h; @@ -401,20 +440,26 @@ async function savedVideoWindows({ video, slug, channelsDir, platform, probe = f if (!Number.isFinite(duration) || duration <= 0) continue; const height = c.height ?? info?.height; const clock = want ? await clockForContainer(videoDir, c.path) : null; + /** @type {SourceWindow} */ + let w = { name: c.name, path: c.path, from: 0, to: duration, ...(height ? { height } : {}) }; if (clock && want) { const m = mapSpan(clock, want.from, want.to); const shift = m.offsetFrom; - out.push({ + w = { name: c.name, path: c.path, from: shift ? -shift : 0, to: duration - shift, ...(height ? { height } : {}), clock: { id: clock.id, offset: shift, certain: m.certain }, - }); - continue; + }; + } + // THE RECORDING'S END: a span starting inside and ending past a container + // that holds the whole recording -- the container ends the recording. + if (want && want.to > w.to + WIN_EPS && want.from < w.to - WIN_EPS && (await recordingWholeness(videoDir, duration)).whole) { + w.endsRecording = true; } - out.push({ name: c.name, path: c.path, from: 0, to: duration, ...(height ? { height } : {}) }); + out.push(w); } return out; } @@ -457,6 +502,7 @@ export const asSource = (kind, w) => ({ windowEnd: w.to, ...(w.height ? { height: w.height } : {}), ...(w.clock ? { clock: w.clock } : {}), + ...(w.endsRecording ? { endsRecording: true } : {}), }); /** diff --git a/common/package.json b/common/package.json @@ -49,6 +49,7 @@ "./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs", "./lib/recordingClock.mjs": "./lib/recordingClock.mjs", "./lib/recordingClock-read.mjs": "./lib/recordingClock-read.mjs", + "./lib/recordingEnd.mjs": "./lib/recordingEnd.mjs", "./lib/jitter.mjs": "./lib/jitter.mjs", "./lib/ttsTuning.mjs": "./lib/ttsTuning.mjs", "./lib/montage/cueTextCache.mjs": "./lib/montage/cueTextCache.mjs", diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,19 @@ # Changelog ## [Unreleased] +- **A clip window past the end of a saved recording is cut from the saved video, clamped at the end.** + - Before, the last clip of a recording asked for a window that ended past the saved container (its cut plus a + 3 s pad). The window was "not-covering" and went to the platform's download queue: a network fetch for footage + that was on disk. + - Now a window that starts inside the container is cut from it, to its end, when the recording is known whole: + the record's 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. + - A window that starts at or after the end, a partial container, and a recording of unknown length stay + not-covering, with the reason. + - `fetch-windows` lists the window under `atRecordingEnd`. `umtool fetch --dry-run` says "saved-video, clamped at + the recording's end", and `umtool window` / `timeline insert` say so when the clip is written. + - The render holds the clip's end at the recording's last second, never padding with black or silence. - **umtool: name a channel once for a whole cut.** - A cut made from two recordings of one channel showed two names for it, the older record's uploader name and the current one. Before, the only fix was to hand-edit `channelTitle` on every clip. diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -1221,8 +1221,15 @@ async function cmdWindow() { try { const { updateTakeClip } = await import("../lib/report/takeEdit.mjs"); const res = await updateTakeClip(p.dir, take, clipId, patch); - if (json) return out({ ok: true, take, ...res }); + // The last clip's pad past a whole saved recording's end: said, nothing to change (lib/report/recordingEndNote.mjs). + const atEnd = await (async () => { + const { recordingEndOf } = await import("../lib/report/recordingEndNote.mjs"); + const { resolveTakeManifest } = await import("../lib/report/takeManifest.mjs"); + return recordingEndOf(p, (await resolveTakeManifest(p.dir, take)).manifest, res.entry).catch(() => null); + })(); + if (json) return out({ ok: true, take, ...res, ...(atEnd ? { atRecordingEnd: atEnd } : {}) }); console.log(`${clipId} (take ${take}): ${res.before.start}–${res.before.end} -> ${res.entry.start}–${res.entry.end}`); + if (atEnd) console.log((await import("../lib/report/recordingEndNote.mjs")).recordingEndLine(atEnd)); if (res.entry.cutStart != null) console.log(` cut: ${res.entry.cutStart}–${res.entry.cutEnd}`); if (gapsText(res.entry)) console.log(` gaps: ${gapsText(res.entry)}`); if (patch.verdict !== undefined || patch.correction !== undefined) console.log(` review: ${reviewWords(res.entry)}`); @@ -1241,10 +1248,14 @@ async function cmdWindow() { // routes use: on a generated manifest the change is also an `edit` note // for the agent that generates it, or the next rebuild undoes it silently. const { result: res, editNotes } = await withEditNotes(p, () => updateClip(p.dir, clipId, patch)); - if (json) return out({ ok: true, ...res, editNotes }); + // The last clip's pad past a whole saved recording's end: said, nothing to change (lib/report/recordingEndNote.mjs). + const { recordingEndOf, recordingEndLine } = await import("../lib/report/recordingEndNote.mjs"); + const atEnd = await (async () => recordingEndOf(p, await (await import("../lib/projects/report.mjs")).readManifest(p.dir), res.entry))().catch(() => null); + if (json) return out({ ok: true, ...res, editNotes, ...(atEnd ? { atRecordingEnd: atEnd } : {}) }); console.log( `${clipId}: ${res.before.start}–${res.before.end} -> ${res.entry.start}–${res.entry.end}`, ); + if (atEnd) console.log(recordingEndLine(atEnd)); if (res.entry.cutStart != null) { console.log( ` cut: ${res.entry.cutStart}–${res.entry.cutEnd} ` + diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -50,6 +50,12 @@ clip says which one that is, and `umtool set` prints a NOTE. A window save that clip's window is refused: widen the window, or clear `claim.at`. The On-screen table's claim column edits the claim's id and verdict and keeps its knobs while the id stays the same. +**A clip at the end of its recording.** A clip's `end` may run to the end of a saved recording known whole. Its +fetch pad past that end is not a reason to shorten it. The editor cuts the window from the saved video, clamped at +the end. `umtool window` / `timeline insert` print `at the recording's end: …`, `umtool fetch <p> --dry-run` prints +`at end <clip>: saved-video, clamped at the recording's end`, and the render holds the end at the recording's last +second. There is no knob: it is the rule in OPERATING.md, "Prepare and export reports". + ## The cite follows the edge A clip's `cite` is the second the clock prints and its `citeUrl`'s `t=` the second the QR opens; both diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -3161,6 +3161,23 @@ cannot resolve); **Start** queues one paced job per platform and the panel follows them to their end, naming each window a job failed. Every run is recorded in `fetch-runs.json` beside the manifest. +THE LAST CLIP OF A RECORDING (lane window-end). A clip whose cut ends in the +last seconds of a saved recording asks for a window that ends past it, because +of the pad. When the recording is known whole (its record's duration, else a +landed live recording's, within 2 s of the container), the editor cuts that +window from the saved video, clamped at the end. Nothing is fetched. The dry +run prints `at end <clip>: saved-video, clamped at the recording's end (asked +to X, cut to Y) — why`, and `umtool window` / `timeline insert` print an +`at the recording's end:` line. + +The build, cut points and every lookup read the clamped window (or the whole +container) as ending the recording. Silence detection stops at the end, and +the clip's end is held at the file's last second: it never snaps past it, and +nothing is padded with black or silence. A clip whose own end is past the +recording's plays to the end, with a note. So keep a last clip's whole ending; +shortening it loses seconds that are on disk. The rule and its limits are in +OPERATING.md, "Prepare and export reports". + TALLER WINDOWS ARE OPT-IN per project: `umtool look <p> tallWindows=true` ([knobs.md](knobs.md#taller-windows-rendertallwindows)). Without it nothing here changes: no `maxHeight` in the body, no height probe, no taller window read. With it the body carries `maxHeight`, the manifest's `render.maxHeightSource`, and the editor keeps a taller window beside the 720 diff --git a/umtool/lib/report/cutPoints.mjs b/umtool/lib/report/cutPoints.mjs @@ -202,7 +202,8 @@ async function diskSourceOf(entry, ctx) { const offset = await cached("offset", fk, async () => (await alignedClipSource(disk)).startOffset ?? 0); const fetchStart = disk.fetchStart + offset; const scan = disk.scan ? { from: Math.max(0, disk.scan.from - offset), to: disk.scan.to - offset } : null; - return { path: src.path, fk, fetchStart, scan }; + // A file ending the recording (the last clip's pad past it): where its footage stops, the build's own hold. + return { path: src.path, fk, fetchStart, scan, ...(Number.isFinite(disk.sourceEnd) ? { sourceEnd: disk.sourceEnd } : {}) }; } /** @@ -258,7 +259,7 @@ async function clipCutPoints(real, ctx) { const pieced = disk.pieced ?? null; const entry = pieced ? pieced.entry : real; const src = { path: disk.path }; - const { fk, fetchStart, scan } = disk; + const { fk, fetchStart, scan, sourceEnd } = disk; const k = snapKnobs(render); const sil = await cached( "silences", @@ -269,7 +270,7 @@ async function clipCutPoints(real, ctx) { const locked = lockedEdges(entry, render); // A clip's gaps (gaps.mjs): no edge snaps across one, as in the build. None in a montage. const clipGaps = montage ? [] : renderGaps(entry, render); - const cut = renderCut({ sil, fetchStart, playFrom: pw.from, playTo: pw.to, render, locked, ...(clipGaps.length ? { gaps: clipGaps } : {}) }); + const cut = renderCut({ sil, fetchStart, playFrom: pw.from, playTo: pw.to, render, locked, ...(clipGaps.length ? { gaps: clipGaps } : {}), ...(Number.isFinite(sourceEnd) ? { sourceEnd } : {}) }); const { cutA, cutB } = cut.file; let segA = cutA; let segB = cutB; diff --git a/umtool/lib/report/recordingEndNote.mjs b/umtool/lib/report/recordingEndNote.mjs @@ -0,0 +1,73 @@ +// THE RECORDING'S END, SAID WHERE A CLIP'S EXTENT IS WRITTEN (lane window-end): +// `umtool window` and `timeline insert` say when a clip's padded fetch window +// runs past the end of a saved recording known whole -- the last clip of a +// recording, its pad past the end. Nothing has to change: the editor cuts that +// window from the saved video clamped at the end (common/lib/recordingEnd.mjs), +// `umtool fetch --dry-run` says "saved-video, clamped at the recording's end", +// and the render holds the clip's end there (snap.mjs `endAt`). So the clip +// keeps its whole ending; shortening it to dodge a network fetch loses seconds +// that are on disk. +// +// Cheap: the record's duration is read first, and a clip whose padded end is +// more than the tolerance before it costs nothing more. Only a clip near the +// end asks the disk (sources.mjs resolveLocalSource over the corpus tiers: a +// window the editor already cut clamped, else the saved container's probe). +// Never fetches, never writes. +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { resolveLocalSource, ffprobeSource } from "umtool-report-to-video/sources"; +import { RECORDING_END_TOLERANCE_SECONDS } from "yt-dlp-transcript-common/lib/recordingEnd.mjs"; +import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { channelFor, channelsDirFor, hasShadowChannels } from "../projects/report.mjs"; + +/** + * Where a clip's padded fetch window stands against the end of its saved + * recording: null when it does not reach it (or nothing says where it is), + * else the end, the window and whether the clip's own end is past it. + * + * @param {{ dir: string }} project + * @param {Record<string, any>} manifest the manifest the clip is read in (a take's, for a take) + * @param {Record<string, any>} entry + * @param {{ probe?: Function, channelsDir?: string }} [opts] + * @returns {Promise<null | { recordingEnd: number, from: number, to: number, clipEndPast: boolean, source: string }>} + */ +export async function recordingEndOf(project, manifest, entry, opts = {}) { + if (!entry || entry.type !== "clip" || entry.src || !entry.video) return null; + const start = Number(entry.start); + const end = Number(entry.end); + if (!Number.isFinite(start) || !Number.isFinite(end)) return null; + const slug = channelFor(manifest, entry); + if (!slug) return null; + const render = manifest?.render ?? {}; + const pad = Number.isFinite(Number(render.fetchPad)) ? Number(render.fetchPad) : 3; + const from = Number(Math.max(0, start - pad).toFixed(2)); + const to = Number((end + pad).toFixed(2)); + const channelsDir = opts.channelsDir ?? channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) }); + // The record's own length first: far from the end, nothing is probed. + const videoDir = await resolveVideoDir(channelsDir, slug, String(entry.video)).catch(() => null); + if (videoDir) { + try { + const d = Number(JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8"))?.duration); + if (Number.isFinite(d) && d > 0 && to < d - RECORDING_END_TOLERANCE_SECONDS) return null; + } catch { + // No record: the disk is asked. + } + } + const hit = await resolveLocalSource( + { video: String(entry.video), slug, from, to }, + { channelsDir, probe: opts.probe ?? ffprobeSource, kinds: ["corpus-window", "saved-video"], render }, + ); + if (!hit?.endsRecording || !(hit.windowEnd < to)) return null; + const recordingEnd = Number(hit.windowEnd.toFixed(2)); + return { recordingEnd, from, to, clipEndPast: end > hit.windowEnd + 0.05, source: hit.kind }; +} + +/** The line `umtool window` / `timeline insert` print for it. Pure. */ +export function recordingEndLine(r) { + if (!r) return null; + return ( + ` at the recording's end: its fetch window ${r.from.toFixed(2)}–${r.to.toFixed(2)} runs past the saved recording's end ` + + `(${r.recordingEnd.toFixed(2)} s, known whole) — cut from the saved video, clamped there; nothing is fetched` + + (r.clipEndPast ? `. Its end is past the recording's: it plays to ${r.recordingEnd.toFixed(2)}` : "") + ); +} diff --git a/umtool/lib/report/recordingEndNote.test.mjs b/umtool/lib/report/recordingEndNote.test.mjs @@ -0,0 +1,65 @@ +// THE RECORDING'S END at window / insert time (lane window-end): a clip whose +// padded fetch window runs past a whole saved recording's end is said to be +// cut from the saved video, clamped there; a clip far from the end, or a +// partial recording, says nothing. +// +// Run with: node --test lib/report/recordingEndNote.test.mjs +import assert from "node:assert/strict"; +import test from "node:test"; +import path from "node:path"; +import os from "node:os"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { recordingEndLine, recordingEndOf } from "./recordingEndNote.mjs"; + +async function tree(meta) { + const root = await mkdtemp(path.join(os.tmpdir(), "umtool-recend-")); + const channelsDir = path.join(root, "channels"); + const videoDir = path.join(channelsDir, "synth-chan", "data", "vid1"); + const storeDir = path.join(root, "store"); + await mkdir(videoDir, { recursive: true }); + await mkdir(storeDir, { recursive: true }); + await writeFile(path.join(storeDir, "source-media.mp4"), Buffer.alloc(16, 1)); + await writeFile(path.join(videoDir, "saved-video.json"), JSON.stringify({ storedAt: "2026-11-21T00:00:00Z", dir: storeDir, file: "source-media.mp4", bytes: 16 })); + if (meta) await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify(meta)); + const project = { dir: path.join(root, "proj") }; + await mkdir(project.dir, { recursive: true }); + const manifest = { provenance: { channelsDir, channelSlug: "synth-chan" }, render: { fetchPad: 3 } }; + return { root, project, manifest }; +} + +const clip = (start, end) => ({ type: "clip", id: "last", video: "vid1", start, end }); +const probe = async () => ({ duration: 300.5 }); + +test("a clip ending 1 s before a whole recording's end, pad 3: said, and the line names the clamp", async () => { + const t = await tree({ id: "vid1", duration: 300 }); + try { + const r = await recordingEndOf(t.project, t.manifest, clip(290, 299.5), { probe }); + assert.deepEqual(r, { recordingEnd: 300.5, from: 287, to: 302.5, clipEndPast: false, source: "saved-video" }); + assert.match(recordingEndLine(r), /runs past the saved recording's end \(300\.50 s, known whole\) — cut from the saved video, clamped there; nothing is fetched$/); + // Its end itself past the recording's: it plays to the end. + const past = await recordingEndOf(t.project, t.manifest, clip(295, 301.5), { probe }); + assert.equal(past.clipEndPast, true); + assert.match(recordingEndLine(past), /it plays to 300\.50$/); + } finally { + await rm(t.root, { recursive: true, force: true }); + } +}); + +test("far from the end nothing is probed; a partial recording says nothing", async () => { + const t = await tree({ id: "vid1", duration: 300 }); + try { + let probed = 0; + const counting = async () => (probed++, { duration: 300.5 }); + assert.equal(await recordingEndOf(t.project, t.manifest, clip(100, 110), { probe: counting }), null); + assert.equal(probed, 0); + } finally { + await rm(t.root, { recursive: true, force: true }); + } + const p = await tree({ id: "vid1", duration: 3600 }); + try { + assert.equal(await recordingEndOf(p.project, p.manifest, clip(290, 299.5), { probe }), null); + } finally { + await rm(p.root, { recursive: true, force: true }); + } + assert.equal(recordingEndLine(null), null); +}); diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -659,6 +659,8 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => let result; let editNotes = null; let attribution = null; + // A clip inserted at a recording's end (its pad past a whole saved recording's): said (recordingEndNote.mjs). + let atEnd = null; switch (verb) { case "insert": { const toSection = intFlag(flags, "--to-section"); @@ -722,6 +724,10 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => result = done.result; editNotes = done.editNotes; attribution = done.attribution; + { + const { recordingEndOf } = await import("./recordingEndNote.mjs"); + atEnd = await recordingEndOf(project, manifest, attribution ?? result?.entry ?? null).catch(() => null); + } if (done.attributionError) { // The clip is in; only its header failed. Say both, and how to finish. const msg = done.attributionError; @@ -937,10 +943,11 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => } if (json) { - out(JSON.stringify({ ok: true, op: verb, ...result, ...(attribution ? { entry: attribution } : {}), editNotes }, null, 2)); + out(JSON.stringify({ ok: true, op: verb, ...result, ...(attribution ? { entry: attribution } : {}), editNotes, ...(atEnd ? { atRecordingEnd: atEnd } : {}) }, null, 2)); return 0; } out(summaryOf(verb, result, attribution)); + if (atEnd) out((await import("./recordingEndNote.mjs")).recordingEndLine(atEnd)); for (const line of result.reanchored ?? []) out(` re-anchored: ${line}`); // What a restored clip's removal re-anchored or dropped stays as it is now: said, not undone. for (const line of result.notPutBack ?? []) out(` not put back: ${line}`); @@ -1067,13 +1074,21 @@ async function takeTimeline(project, take, verb, rest, flags, { out, json }) { } else { result = await edit.undoTakeEdit(project.dir, take, { token }); } + // A clip inserted at a recording's end (its pad past a whole saved recording's): said (recordingEndNote.mjs). + let atEnd = null; + if (verb === "insert" && result?.entry) { + const { recordingEndOf } = await import("./recordingEndNote.mjs"); + const { resolveTakeManifest } = await import("./takeManifest.mjs"); + atEnd = await (async () => recordingEndOf(project, (await resolveTakeManifest(project.dir, take)).manifest, result.entry))().catch(() => null); + } if (json) { - out(JSON.stringify({ ok: true, op: verb, take, ...result }, null, 2)); + out(JSON.stringify({ ok: true, op: verb, take, ...result, ...(atEnd ? { atRecordingEnd: atEnd } : {}) }, null, 2)); return 0; } if (verb === "undo") out(`take ${take}: undid ${result.op}: restored ${result.restored} (the state before the undo kept as ${result.saved})`); else { out(`take ${take}: ${summaryOf(verb, result, null)}`); + if (atEnd) out((await import("./recordingEndNote.mjs")).recordingEndLine(atEnd)); out(` undo point: takes/${take}/${result.revision.rel} (umtool timeline ${project.id} --take ${take} undo)`); } return 0; diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -1307,6 +1307,11 @@ export async function onDiskClipSource(entry, meta, render, local, opts = {}) { if (!hit) return null; // What the log calls it: a fallback is not the same fact as an audio-only clip. const kind = hit.kind === "audio" && use === "audio-fallback" ? "audio-fallback" : hit.kind; + // THE RECORDING'S END (lane window-end, sources.mjs `endsRecording`): the + // file ends the recording before the padded span does -- the last clip's pad + // runs past the end. `sourceEnd` is where its footage stops (source + // seconds): the scan stops there and the cut never passes it. + const ends = hit.endsRecording === true && hit.windowEnd < to; return { path: hit.path, fetchStart: hit.windowStart, @@ -1314,13 +1319,15 @@ export async function onDiskClipSource(entry, meta, render, local, opts = {}) { source: kind, // A whole container is hours long and silence detection decodes what it // is given: give it the span a fetch would have produced, no more. - ...(hit.kind === "raw-cache" ? {} : { scan: { from: from - hit.windowStart, to: to - hit.windowStart } }), + ...(hit.kind === "raw-cache" ? {} : { scan: { from: from - hit.windowStart, to: Math.min(to, hit.windowEnd) - hit.windowStart } }), + ...(ends ? { sourceEnd: hit.windowEnd } : {}), log: { id: entry.id, video: entry.video, from, to, cached: true, source: kind, ...(hit.kind !== "raw-cache" || hit.name !== name ? { reuse: hit.name } : {}), local: hit.path, window: [hit.windowStart, hit.windowEnd], ...(hit.height ? { height: hit.height } : {}), + ...(ends ? { atRecordingEnd: true } : {}), }, }; } @@ -1579,7 +1586,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // (piecedClipSource): `clipE` is the clip on that file's clock, `toReal` // maps a cut on it back to the source's. Every other clip: itself, as ever. const pieced = await piecedClipSource(entry, meta, render, dirs.local, opts, outDir); - const { path: raw, fetchStart, scan } = pieced ?? (await fetchClipAligned(entry, meta, render, dirs.local, opts)); + const { path: raw, fetchStart, scan, sourceEnd } = pieced ?? (await fetchClipAligned(entry, meta, render, dirs.local, opts)); const clipE = pieced ? pieced.entry : entry; const toReal = pieced ? pieced.clock.toReal : (t) => t; // Every file this writes in segments/ is written through a rename (the @@ -1625,9 +1632,18 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, } } - // Desired cut points, expressed relative to the over-fetched file. + // Desired cut points, expressed relative to the over-fetched file. A file + // that ENDS THE RECORDING (onDiskClipSource `sourceEnd`: the last clip, its + // pad past the end) holds the end at its last second -- never a cut past it, + // so nothing is padded with black or silence for seconds that do not exist. + const endAt = Number.isFinite(sourceEnd) ? sourceEnd - fetchStart : null; const wantA = playFrom - fetchStart; - const wantB = playTo - fetchStart; + const wantB = endAt !== null ? Math.min(playTo - fetchStart, endAt) : playTo - fetchStart; + if (endAt !== null && playTo - fetchStart > endAt + 0.05) { + EMIT("note", { + message: `${entry.id}: its end ${playTo.toFixed(2)} is past the recording's end ${sourceEnd.toFixed(2)} — it plays to the end`, + }); + } const win = render.snapWindow ?? 1.6; const sil = await detectSilence(raw, render, scan); @@ -1654,6 +1670,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // and no edge snaps across a gap (a gap's edges are exact). const snapped = mont ? null : snapCut({ sil, wantA, wantB, render, locked: lockedEdges(clipE, render), + ...(endAt !== null ? { endAt } : {}), ...(clipGaps.length ? { gaps: clipGaps.map((g) => ({ from: g.from - fetchStart, to: g.to - fetchStart })) } : {}), }); const a = mont ? mont.win.start : snapped.a; diff --git a/umtool/report-to-video/snap.mjs b/umtool/report-to-video/snap.mjs @@ -86,7 +86,8 @@ export const GAP_KEEP = GAP_LIMITS.keep; * desired end, the end at least a second after the start. * * @param {{ sil: Array<{ s: number, e: number }>, wantA: number, wantB: number, render?: Record<string, any>, - * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null }} o + * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null, + * endAt?: number | null }} o * `wantA`/`wantB`: the play window's edges in the file's seconds; `locked`: * which of them are the author's, exact (mute.mjs lockedEdges) -- each * snapped only outward, inside its own silence; `gaps`: the clip's gaps @@ -94,10 +95,17 @@ export const GAP_KEEP = GAP_LIMITS.keep; * edge snaps across one (nor nearer it than GAP_KEEP): such a snap is not * taken and the edge stays where it was asked */ -export function snapCut({ sil, wantA, wantB, render = {}, locked = null, gaps = null }) { +export function snapCut({ sil, wantA, wantB: asked, render = {}, locked = null, gaps = null, endAt = null }) { const win = render.snapWindow ?? SNAP_DEFAULTS.snapWindow; + // THE RECORDING'S END (lane window-end): a file that ends the recording + // (`endAt`, its last second on the file's clock) is never cut past it -- the + // end is held there and does not snap beyond it, so nothing is padded with + // black or silence for seconds that do not exist. + const end = Number.isFinite(endAt) ? Number(endAt) : Infinity; + const wantB = Math.min(asked, end); let a = snap(wantA, sil, "start", win, render, { pinned: !!locked?.start }); let b = snap(wantB, sil, "end", win, render, { pinned: !!locked?.end }); + if (b.at > end) b = { at: end, snapped: false }; if (gaps?.length) { const first = gaps.reduce((m, g) => Math.min(m, g.from), Infinity); const last = gaps.reduce((m, g) => Math.max(m, g.to), -Infinity); @@ -105,7 +113,7 @@ export function snapCut({ sil, wantA, wantB, render = {}, locked = null, gaps = if (b.at < wantB && b.at < last + GAP_KEEP) b = { at: wantB, snapped: false }; } const cutA = Math.min(a.at, wantB - 1); - const cutB = Math.max(b.at, cutA + 1); + const cutB = Math.min(Math.max(b.at, cutA + 1), Math.max(end, cutA)); return { win, a, b, cutA, cutB }; } @@ -117,14 +125,18 @@ export const recordSecond = (fetchStart, t) => Number((fetchStart + t).toFixed(3 * file it is cut from: what `<id>.cut.json` records (`start`, `end`, * `snapped`) for a clip with no room and no montage. `playFrom`/`playTo` are * the play window (deck.mjs playWindow); `fetchStart` the file's first - * second in the recording; `gaps` the clip's (gaps.mjs), source seconds. + * second in the recording; `gaps` the clip's (gaps.mjs), source seconds; + * `sourceEnd` the source second the file's footage ends at when it ends the + * recording (onDiskClipSource) -- the cut never passes it. * * @param {{ sil: Array<{ s: number, e: number }>, fetchStart: number, playFrom: number, playTo: number, render?: Record<string, any>, - * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null }} o + * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null, + * sourceEnd?: number | null }} o */ -export function renderCut({ sil, fetchStart, playFrom, playTo, render = {}, locked = null, gaps = null }) { +export function renderCut({ sil, fetchStart, playFrom, playTo, render = {}, locked = null, gaps = null, sourceEnd = null }) { const c = snapCut({ sil, wantA: playFrom - fetchStart, wantB: playTo - fetchStart, render, locked, + ...(Number.isFinite(sourceEnd) ? { endAt: Number(sourceEnd) - fetchStart } : {}), ...(gaps?.length ? { gaps: gaps.map((g) => ({ from: g.from - fetchStart, to: g.to - fetchStart })) } : {}), }); return { diff --git a/umtool/report-to-video/snap.test.mjs b/umtool/report-to-video/snap.test.mjs @@ -22,3 +22,22 @@ test("snap: snapTail / snapLead keep more of the pause, never more than it holds assert.equal(Number(snap(20, SIL, "end", 1, render).at.toFixed(3)), 20.12); assert.equal(snap(20.1, SIL, "start", 1, render).at, 20); }); + +// THE RECORDING'S END (lane window-end): a file that ends the recording holds +// the cut's end at its last second -- never snapped or cut past it. +test("snapCut / renderCut: a file ending the recording holds the end at its last second", async () => { + const { snapCut, renderCut } = await import("./snap.mjs"); + // The file's last second is 9.5; a pause at 9.4-9.9 would snap the end past it. + const sil = [{ s: 9.4, e: 9.9 }]; + const free = snapCut({ sil, wantA: 3, wantB: 9.45, render: {} }); + assert.ok(free.cutB > 9.5, `without the end the snap goes to ${free.cutB}`); + const held = snapCut({ sil, wantA: 3, wantB: 9.45, render: {}, endAt: 9.5 }); + assert.ok(held.cutB <= 9.5, `held at ${held.cutB}`); + // An end asked past the file's last second plays to it. + assert.equal(snapCut({ sil: [], wantA: 3, wantB: 12, render: {}, endAt: 9.5 }).cutB, 9.5); + // renderCut takes the source second: 100 + 9.5. + const cut = renderCut({ sil: [], fetchStart: 100, playFrom: 103, playTo: 112, render: {}, sourceEnd: 109.5 }); + assert.equal(cut.end, 109.5); + // Nothing said: as before. + assert.equal(renderCut({ sil: [], fetchStart: 100, playFrom: 103, playTo: 112, render: {} }).end, 112); +}); diff --git a/umtool/report-to-video/sources.test.mjs b/umtool/report-to-video/sources.test.mjs @@ -29,6 +29,7 @@ import { findContainingWindow, localSources, needsFetchMessage, + onDiskClipSource, planLocalSources, } from "./build-video.mjs"; @@ -689,3 +690,79 @@ test("a tall ask between rungs resolves the rung's window: 900 and 1000 read .h1 await rm(t.root, { recursive: true, force: true }); } }); + +// THE RECORDING'S END (lane window-end, common/lib/recordingEnd.mjs): the last +// clip's padded span runs past a saved recording KNOWN WHOLE -- its container +// serves it, ending the recording; a span starting past the end, or a +// container shorter than its record, does not. A corpus window the editor cut +// clamped at the end (its sidecar's `clamp`) serves the same padded span. +test("the recording's end: a whole saved recording serves a padded span past its end; a partial one does not", async () => { + const t = await tree(); + try { + await touch(path.join(t.storeDir, "source-media.mp4")); + await pointTo(t.videoDir, t.storeDir, "source-media.mp4"); + const cfg = { channelsDir: t.channelsDir, probe: fakeProbe(300.5).probe }; + // The clip is 290-299.5, padded 3: 287-302.5. + const want = { video: VIDEO, slug: SLUG, from: 287, to: 302.5 }; + assert.equal(await resolveLocalSource(want, cfg), null, "no known length: a partial recording may not cover"); + await writeFile(path.join(t.videoDir, "metadata.info.json"), JSON.stringify({ id: VIDEO, duration: 301 })); + const hit = await resolveLocalSource(want, cfg); + assert.equal(hit?.kind, "saved-video"); + assert.equal(hit.windowEnd, 300.5); + assert.equal(hit.endsRecording, true); + assert.equal(await resolveLocalSource({ ...want, from: 300.6, to: 305 }, cfg), null, "a span starting past the end"); + // The record says the stream is longer than the container: not whole. + await writeFile(path.join(t.videoDir, "metadata.info.json"), JSON.stringify({ id: VIDEO, duration: 3600 })); + assert.equal(await resolveLocalSource(want, cfg), null); + // A span inside the container is served as ever, and says nothing about the end. + const inside = await resolveLocalSource({ ...want, from: 100, to: 110 }, cfg); + assert.equal(inside.endsRecording, undefined); + } finally { + await rm(t.root, { recursive: true, force: true }); + } +}); + +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" } }), + ); + const { probe, calls } = fakeProbe(300.5); + const hit = await resolveLocalSource({ video: VIDEO, slug: SLUG, from: 287, to: 302.5 }, { channelsDir: t.channelsDir, probe }); + assert.equal(hit?.kind, "corpus-window"); + assert.equal(hit.name, "287.00-300.49.mp4"); + assert.equal(hit.endsRecording, true); + assert.deepEqual(calls, [], "nothing probed"); + // A window with no clamp in its sidecar is no answer for the padded span. + await writeFile(path.join(t.clipsDir, "287.00-300.49.json"), JSON.stringify({ requestedBy: "umtool" })); + assert.equal(await resolveLocalSource({ video: VIDEO, slug: SLUG, from: 287, to: 302.5 }, { channelsDir: t.channelsDir, probe }), null); + } finally { + await rm(t.root, { recursive: true, force: true }); + } +}); + +test("the recording's end: the build's on-disk source stops its scan at the end and says where the footage stops", async () => { + const t = await tree(); + try { + await touch(path.join(t.storeDir, "source-media.mp4")); + await pointTo(t.videoDir, t.storeDir, "source-media.mp4"); + await writeFile(path.join(t.videoDir, "metadata.info.json"), JSON.stringify({ id: VIDEO, duration: 300 })); + const local = localSources({ rawDir: t.rawDir, channelsDir: t.channelsDir, probe: fakeProbe(300.5).probe }); + // The clip ends 1 s before the end; the pad is 3 s. + const entry = { type: "clip", id: "last", channel: SLUG, video: VIDEO, start: 290, end: 299.5 }; + const src = await onDiskClipSource(entry, null, { fetchPad: 3 }, local, {}); + assert.equal(src?.source, "saved-video"); + assert.equal(src.sourceEnd, 300.5); + assert.deepEqual(src.scan, { from: 287, to: 300.5 }); + assert.equal(src.log.atRecordingEnd, true); + // A clip well inside: no sourceEnd, the scan as ever. + const mid = await onDiskClipSource({ ...entry, start: 100, end: 110 }, null, { fetchPad: 3 }, local, {}); + assert.equal(mid.sourceEnd, undefined); + assert.deepEqual(mid.scan, { from: 97, to: 113 }); + } finally { + await rm(t.root, { recursive: true, force: true }); + } +});