commit 075a0498434c59d702d4587aa45a7ed20674d27c
parent 17bb576466b199032cd5a50f168dd2bc39921c30
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 6 Nov 2026 20:57:21 -0500
common: windows cut from a saved video go through the recording's clock; the saved-video tier serves the cue clock
savedWindowSource reads the video dir's clock.json when it is about THIS
container (same file, same size) and checks coverage at the mapped seconds;
cutSavedVideoWindow cuts the container at the mapped span, keeps the cue-clock
name every reader asks for, and records the map in the window's provenance
(`clock: {id, from, to, offset, certain}`; certain false on a step or a map
that is not ok, said in the log -- the quote check settles those).
evidenceClip.mjs's saved-video tier (the render's and the moment page's
local source) gets the span being resolved and, with a map, shifts the
container's window start by the offset there: `t - windowStart` is the
container second the cue's words are at. A listing with no span, or no map,
is [0, duration] as before. The source carries `clock` through asSource.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
8 files changed, 244 insertions(+), 14 deletions(-)
diff --git a/common/lib/clipWindow.ts b/common/lib/clipWindow.ts
@@ -228,8 +228,27 @@ export type ClipProvenance = {
// set it aside, and when (`setAsideAt`).
sync?: RecordedClipWindowSync;
setAsideAt?: string;
+ // ONE CLOCK PER RECORDING (lane one-clock, lib/recordingClock.mjs): a window
+ // cut from a saved container through the recording's time map. Its NAME is
+ // on the cue clock; the container seconds cut were `from`/`to` here, the
+ // map's `id` and whether it was sure of the span (`certain`; false on a step
+ // or a map that is not ok -- the per-clip quote check settles those).
+ clock?: ClipWindowClock;
};
+export type ClipWindowClock = { id: string; from: number; to: number; offset: number; certain: boolean };
+
+export function coerceClipWindowClock(v: unknown): ClipWindowClock | undefined {
+ if (!v || typeof v !== "object" || Array.isArray(v)) return undefined;
+ const r = v as Record<string, unknown>;
+ const id = str(r.id);
+ const from = num(r.from);
+ const to = num(r.to);
+ const offset = num(r.offset);
+ if (!id || from === undefined || to === undefined || offset === undefined || typeof r.certain !== "boolean") return undefined;
+ return { id, from, to, offset, certain: r.certain };
+}
+
export type ClipAudioCheck = { verdict: "clean" | "partial"; attempts: number };
export const CLIP_COPY_SOURCES = ["wayback", "archive.org"] as const;
@@ -298,6 +317,8 @@ export function parseClipProvenance(raw: unknown): ClipProvenance | null {
if (sync) out.sync = sync;
const setAsideAt = str(r.setAsideAt);
if (setAsideAt) out.setAsideAt = setAsideAt;
+ const clock = coerceClipWindowClock(r.clock);
+ if (clock) out.clock = clock;
return out;
}
diff --git a/common/lib/evidenceClip.mjs b/common/lib/evidenceClip.mjs
@@ -42,6 +42,8 @@ import { readdir, readFile, stat } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { resolveVideoDir } from "./videoDir-server.mjs";
+import { clockForContainer } from "./recordingClock-read.mjs";
+import { mapSpan } from "./recordingClock.mjs";
const execFileP = promisify(execFile);
@@ -72,10 +74,15 @@ export async function listNames(dir) {
}
/**
- * @typedef {{ name: string, path: string, from: number, to: number, height?: number }} SourceWindow
- * @typedef {{ kind: string, path: string, name: string, windowStart: number, windowEnd: number, height?: number }} LocalSource
+ * @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 {(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 }} TierContext
+ * @typedef {{ video: string, slug?: string | null, channelsDir?: string | null, rawDir?: string | null, probe?: SourceProbe, platform?: string | null, want?: { from: number, to: number } }} TierContext
+ * `want`: the span being resolved, when there is one (resolveFromTiers sets it) -- the
+ * saved-video tier maps it through the recording's clock
* @typedef {{ kind: string, windows: (ctx: TierContext) => Promise<SourceWindow[]>, audio?: boolean }} SourceTier
*/
@@ -296,12 +303,21 @@ async function corpusWindows({ video, slug, channelsDir, platform }) {
return windowsFromBareNames(await listNames(dir), dir);
}
+// ONE CLOCK PER RECORDING (lane one-clock). A container whose video dir holds
+// a time map (`clock.json`, recordingClock.mjs: the transcription source's
+// clock onto this container's) is a window on the CUE clock: for the span being
+// resolved, its start is shifted by the map's offset there, so `t - windowStart`
+// lands on the container second the cue second `t` was spoken at. With no span
+// (a listing) or no map, it is [0, duration] as it always was. A span on a
+// step of the map is mapped by the nearer segment and says `certain: false` --
+// the per-clip quote check is what settles it.
/** @param {TierContext} ctx */
-async function savedVideoWindows({ video, slug, channelsDir, platform, probe = ffprobeSource }) {
+async function savedVideoWindows({ video, slug, channelsDir, platform, probe = ffprobeSource, want }) {
if (!channelsDir || !slug) return [];
/** @type {SourceWindow[]} */
const out = [];
- for (const c of await wholeContainersOf(await recordDirOf(channelsDir, slug, video, platform))) {
+ const videoDir = await recordDirOf(channelsDir, slug, video, platform);
+ for (const c of await wholeContainersOf(videoDir)) {
// Existence BEFORE the probe: an unmounted drive must not cost a timeout.
if (!(await present(c.path))) continue;
const info = await probe(c.path);
@@ -310,6 +326,20 @@ async function savedVideoWindows({ video, slug, channelsDir, platform, probe = f
// not cover is the one failure worse than a miss.
if (!Number.isFinite(duration) || duration <= 0) continue;
const height = c.height ?? info?.height;
+ const clock = want ? await clockForContainer(videoDir, c.path) : null;
+ if (clock && want) {
+ const m = mapSpan(clock, want.from, want.to);
+ const shift = m.offsetFrom;
+ out.push({
+ 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;
+ }
out.push({ name: c.name, path: c.path, from: 0, to: duration, ...(height ? { height } : {}) });
}
return out;
@@ -352,6 +382,7 @@ export const asSource = (kind, w) => ({
windowStart: w.from,
windowEnd: w.to,
...(w.height ? { height: w.height } : {}),
+ ...(w.clock ? { clock: w.clock } : {}),
});
/**
@@ -373,7 +404,7 @@ export async function resolveFromTiers(tiers, ctx, from, to, opts = {}) {
const { allow = (tier) => !tier.audio, preferName = () => null } = opts;
for (const tier of tiers) {
if (!allow(tier)) continue;
- const windows = (await tier.windows(ctx)).filter((w) => windowContains(w, from, to));
+ const windows = (await tier.windows({ ...ctx, want: { from, to } })).filter((w) => windowContains(w, from, to));
const exactName = preferName(tier);
windows.sort((a, b) =>
Number(b.name === exactName) - Number(a.name === exactName) || (a.to - a.from) - (b.to - b.from));
diff --git a/common/lib/recordingClock-server.ts b/common/lib/recordingClock-server.ts
@@ -45,6 +45,7 @@ import { loadSavedVideo } from "./savedVideo-server";
import { savedVideoPath, type SavedVideoPointer } from "./savedVideo";
import { coerceMediaImport, MEDIA_IMPORT_FILENAME } from "./mediaImport";
import { readJsonFile } from "./jsonFile-server";
+import { loadTranscribeOutcome } from "./transcribeOutcome-server";
export const recordingClockSidecar = sidecar(CLOCK_FILE, sidecarField(coerceRecordingClock), { indent: 2 });
@@ -189,7 +190,15 @@ export type ClockPlan =
| { kind: "no-source" }
| { kind: "same-clock"; source: string; container: string }
| { kind: "current"; clock: RecordingClock; source: string; container: string }
- | { kind: "measure"; source: string; container: string; sourceBytes: number; targetBytes: number; stale: RecordingClock | null };
+ | {
+ kind: "measure";
+ source: string;
+ container: string;
+ sourceBytes: number;
+ targetBytes: number;
+ transcribedAt: string | null;
+ stale: RecordingClock | null;
+ };
/** What a video dir needs: nothing, its map as it is, or a measurement. */
export async function planRecordingClock(videoDir: string): Promise<ClockPlan> {
@@ -201,12 +210,29 @@ export async function planRecordingClock(videoDir: string): Promise<ClockPlan> {
if (await sourceSharesContainerClock(videoDir, pointer)) {
return { kind: "same-clock", source: src.path, container };
}
- const [s, t] = await Promise.all([stat(src.path), stat(container)]);
+ const [s, t, outcome] = await Promise.all([stat(src.path), stat(container), loadTranscribeOutcome(videoDir)]);
const have = await recordingClockSidecar.load(videoDir);
- if (have && have.target.file === path.basename(container) && have.source.file === src.name && clockMatches(have, { sourceBytes: s.size, targetBytes: t.size })) {
+ // The cues made again since the map was measured (a re-transcription) are
+ // another clock's seconds until measured again.
+ const sameCues = (have?.cues?.transcribedAt ?? null) === (outcome?.transcribedAt ?? null);
+ if (
+ have &&
+ sameCues &&
+ have.target.file === path.basename(container) &&
+ have.source.file === src.name &&
+ clockMatches(have, { sourceBytes: s.size, targetBytes: t.size })
+ ) {
return { kind: "current", clock: have, source: src.path, container };
}
- return { kind: "measure", source: src.path, container, sourceBytes: s.size, targetBytes: t.size, stale: have };
+ return {
+ kind: "measure",
+ source: src.path,
+ container,
+ sourceBytes: s.size,
+ targetBytes: t.size,
+ transcribedAt: outcome?.transcribedAt ?? null,
+ stale: have,
+ };
}
// ---- measuring ------------------------------------------------------------------
@@ -225,6 +251,9 @@ export async function measureRecordingClock(opts: {
container: string;
sourceBytes: number;
targetBytes: number;
+ // The transcript's transcribedAt (transcribe-outcome.json): which cues the
+ // map is about.
+ transcribedAt?: string | null;
extra?: number[];
options?: ClockOptions;
write?: boolean;
@@ -296,6 +325,7 @@ export async function measureRecordingClock(opts: {
createdAt,
source: { file: path.basename(opts.source), bytes: opts.sourceBytes },
target: { file: path.basename(opts.container), bytes: opts.targetBytes },
+ ...(opts.transcribedAt ? { cues: { transcribedAt: opts.transcribedAt } } : {}),
method: "xcorr",
params: {
sampleRate: sr,
diff --git a/common/lib/recordingClock.mjs b/common/lib/recordingClock.mjs
@@ -479,6 +479,7 @@ export function mapSpan(clock, from, to) {
* createdAt: string,
* source: ClockFileRef,
* target: ClockFileRef,
+ * cues?: { transcribedAt: string },
* method: "xcorr",
* params: Record<string, number>,
* anchors: { at: number, offset: number | null, score: number, ratio: number, ok: boolean, why?: string }[],
diff --git a/common/lib/savedVideoWindow-server.test.ts b/common/lib/savedVideoWindow-server.test.ts
@@ -204,3 +204,65 @@ test("an ffmpeg that fails leaves no window behind", async () => {
);
assert.deepEqual(await readdir(path.join(c.videoDir, "clips")), []);
});
+
+// ONE CLOCK PER RECORDING (lane one-clock): a video dir with a time map about
+// this container cuts the cue span at the mapped seconds and keeps the cue name.
+async function writeClock(videoDir: string, container: string, offset: number, extra: Record<string, unknown> = {}) {
+ const { stat } = await import("node:fs/promises");
+ const bytes = (await stat(container)).size;
+ await writeFile(
+ path.join(videoDir, "clock.json"),
+ JSON.stringify({
+ version: 1,
+ id: "clock-1",
+ createdAt: "2026-11-06T00:00:00.000Z",
+ source: { file: "audio.mp3", bytes: 1 },
+ target: { file: path.basename(container), bytes },
+ method: "xcorr",
+ params: {},
+ anchors: [],
+ segments: [{ from: 0, to: 8, offset, rate: 0, n: 3, rms: 0 }],
+ gaps: [],
+ residual: { rms: 0, max: 0, n: 3 },
+ ok: true,
+ ...extra,
+ }),
+ );
+}
+
+test("a time map: the cue span is cut at the container's mapped seconds, named on the cue clock", async () => {
+ const c = await corpus(PICTURE);
+ const container = path.join(c.storeDir, "source-media.mp4");
+ await writeClock(c.videoDir, container, 2);
+ const src = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 3 });
+ assert.equal(src.kind, "covers");
+ if (src.kind !== "covers") return;
+ assert.equal(src.clock?.mapped.from, 3);
+ assert.equal(src.clock?.mapped.to, 5);
+ const logs: string[] = [];
+ const w = await cutSavedVideoWindow({
+ paths: c.paths,
+ videoDir: c.videoDir,
+ source: src,
+ from: 1,
+ to: 3,
+ provenance: { requestedBy: "test" },
+ onLog: (l) => logs.push(l),
+ });
+ assert.equal(w.file, "1.00-3.00.mp4");
+ const sidecar = JSON.parse(await readFile(path.join(c.videoDir, "clips", "1.00-3.00.json"), "utf8"));
+ assert.deepEqual(sidecar.clock, { id: "clock-1", from: 3, to: 5, offset: 2, certain: true });
+ assert.match(logs.join(""), /Cut 1\.00–3\.00 on the cue clock \(the container's 3\.00–5\.00, \+2\.00 s\)/);
+ // The mapped end past the container: not covering.
+ const past = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 5, to: 7 });
+ assert.equal(past.kind, "not-covering");
+});
+
+test("a time map about another container (saved again) is not applied", async () => {
+ const c = await corpus(PICTURE);
+ const container = path.join(c.storeDir, "source-media.mp4");
+ await writeClock(c.videoDir, container, 2, { target: { file: "source-media.mp4", bytes: 12 } });
+ const src = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 3 });
+ assert.equal(src.kind, "covers");
+ if (src.kind === "covers") assert.equal(src.clock, undefined);
+});
diff --git a/common/lib/savedVideoWindow-server.ts b/common/lib/savedVideoWindow-server.ts
@@ -52,6 +52,8 @@ import { loadSavedVideo } from "./savedVideo-server";
import { readSavedVideosMarker, SavedVideosStoreInTransitionError } from "./savedVideoStore";
import { isDriveNotAnswering, onDrive } from "./storageHealth";
import type { Paths } from "./paths";
+import { clockForContainer } from "./recordingClock-read.mjs";
+import { mapSpan, type RecordingClock } from "./recordingClock.mjs";
// A window cut from a container is seconds of re-encoding; a whole container
// on a platter seeks once. Generous, so only a wedged ffmpeg reaches it —
@@ -68,6 +70,9 @@ export type SavedWindowSource =
container: string;
durationSec: number;
probe: MediaProbe;
+ // The recording's time map, when its video dir has one about THIS
+ // container (lib/recordingClock.mjs): the span is cut at `mapped`.
+ clock?: { map: RecordingClock; mapped: ReturnType<typeof mapSpan> };
};
// The media guard's sentence (lib/channelMedia.ts, ChannelMediaUnreachableError)
@@ -121,10 +126,22 @@ export async function savedWindowSource(opts: {
return unreachable(opts.slug, `its saved video ${container} could not be read by ffprobe`);
}
const durationSec = probe.durationSec;
- if (opts.from < 0 || opts.to > durationSec + WIN_EPS) {
+ // ONE CLOCK PER RECORDING: a span asked for in cue seconds is on the
+ // container at the map's seconds, and covered only if those are.
+ const map = await clockForContainer(opts.videoDir, container);
+ const mapped = map ? mapSpan(map, opts.from, opts.to) : null;
+ const span = mapped ?? { from: opts.from, to: opts.to };
+ if (opts.from < 0 || span.from < 0 || span.to > durationSec + WIN_EPS) {
return { kind: "not-covering", container, durationSec };
}
- return { kind: "covers", pointer, container, durationSec, probe };
+ return {
+ kind: "covers",
+ pointer,
+ container,
+ durationSec,
+ probe,
+ ...(map && mapped ? { clock: { map, mapped } } : {}),
+ };
}
export type SavedWindowProvenance = {
@@ -161,8 +178,13 @@ export async function cutSavedVideoWindow(opts: {
await mkdir(path.dirname(dest), { recursive: true });
const tmp = tmpPathFor(dest);
const kind = source.probe.hasVideo ? "video" : "audio";
+ // The container seconds: the cue span through the recording's map, when it
+ // has one; the file keeps the cue-clock name every reader asks for.
+ const mapped = source.clock?.mapped ?? null;
+ const cutFrom = mapped ? mapped.from : from;
+ const cutTo = mapped ? mapped.to : to;
try {
- const r = await execa(opts.paths.ffmpegBin, evidenceCutArgs(source.container, from, to, kind, tmp), {
+ const r = await execa(opts.paths.ffmpegBin, evidenceCutArgs(source.container, cutFrom, cutTo, kind, tmp), {
reject: false,
timeout: CUT_TIMEOUT_MS,
...(opts.signal ? { cancelSignal: opts.signal } : {}),
@@ -188,10 +210,26 @@ export async function cutSavedVideoWindow(opts: {
// When the window landed — for a cut, when it was cut.
fetchedAt: now,
source: "saved-video",
+ ...(mapped && source.clock
+ ? {
+ clock: {
+ id: source.clock.map.id,
+ from: mapped.from,
+ to: mapped.to,
+ offset: mapped.offsetFrom,
+ certain: mapped.certain,
+ },
+ }
+ : {}),
};
await writeClipProvenance(opts.videoDir, from, to, provenance);
+ const onClock = mapped
+ ? ` on the cue clock (the container's ${cutFrom.toFixed(2)}–${cutTo.toFixed(2)}, ` +
+ `${mapped.offsetFrom >= 0 ? "+" : ""}${mapped.offsetFrom.toFixed(2)} s` +
+ `${mapped.certain ? "" : " — NOT certain: the span sits on a step of the recording's clock, or its map is not ok; check the quote"})`
+ : "";
opts.onLog?.(
- `Cut ${from.toFixed(2)}–${to.toFixed(2)} from the saved video ${source.pointer.file} into ` +
+ `Cut ${from.toFixed(2)}–${to.toFixed(2)}${onClock} from the saved video ${source.pointer.file} into ` +
`clips/${clipWindowFile(from, to)} (${bytes} bytes); nothing fetched.\n`,
);
return {
diff --git a/common/package.json b/common/package.json
@@ -42,6 +42,8 @@
"./lib/cueWiden.mjs": "./lib/cueWiden.mjs",
"./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs",
"./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs",
+ "./lib/recordingClock.mjs": "./lib/recordingClock.mjs",
+ "./lib/recordingClock-read.mjs": "./lib/recordingClock-read.mjs",
"./lib/jitter.mjs": "./lib/jitter.mjs",
"./lib/montage/cueTextCache.mjs": "./lib/montage/cueTextCache.mjs",
"./lib/montage/phraseScan.mjs": "./lib/montage/phraseScan.mjs",
diff --git a/umtool/report-to-video/sources.test.mjs b/umtool/report-to-video/sources.test.mjs
@@ -201,6 +201,51 @@ test("saved-video: the pointer's container is the window [0, probed duration], h
}
});
+// ONE CLOCK PER RECORDING (lane one-clock): a video dir with a time map about
+// its saved container serves a span on the CUE clock -- the window's start is
+// shifted by the map's offset there, so `t - windowStart` lands on the second
+// the cue's words are in the container. Across a step: the nearer segment,
+// not certain. A map about another container (saved again): not applied.
+test("saved-video: the recording's clock.json maps the span; a stale one is ignored", 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 clock = {
+ version: 1, id: "c1", createdAt: "2026-11-06T00:00:00Z",
+ source: { file: "audio.mp3", bytes: 9 }, target: { file: "source-media.mp4", bytes: 16 },
+ method: "xcorr", params: {}, anchors: [],
+ segments: [
+ { from: 150, to: 1500, offset: 0, rate: 0, n: 5, rms: 0 },
+ { from: 1600, to: 5000, offset: 13.6, rate: 0, n: 9, rms: 0 },
+ ],
+ gaps: [{ from: 1490, to: 1610 }],
+ residual: { rms: 0, max: 0, n: 14 }, ok: true,
+ };
+ await writeFile(path.join(t.videoDir, "clock.json"), JSON.stringify(clock));
+ const cfg = { channelsDir: t.channelsDir, probe: fakeProbe(6000).probe };
+ // c44-like: before the step, offset 0.
+ const c44 = await resolveLocalSource({ video: VIDEO, slug: SLUG, from: 633, to: 644 }, cfg);
+ assert.equal(c44.windowStart, 0);
+ assert.deepEqual(c44.clock, { id: "c1", offset: 0, certain: true });
+ // c45-like: after it, +13.6 -- the cue second 2309 is the container's 2322.6.
+ const c45 = await resolveLocalSource({ video: VIDEO, slug: SLUG, from: 2309, to: 2322 }, cfg);
+ assert.equal(c45.windowStart, -13.6);
+ assert.equal(2309 - c45.windowStart, 2322.6);
+ assert.deepEqual(c45.clock, { id: "c1", offset: 13.6, certain: true });
+ // Inside the gap: mapped, not certain.
+ const step = await resolveLocalSource({ video: VIDEO, slug: SLUG, from: 1550, to: 1560 }, cfg);
+ assert.equal(step.clock.certain, false);
+ // The container saved again (another size): the map is not this file's.
+ await writeFile(path.join(t.videoDir, "clock.json"), JSON.stringify({ ...clock, target: { file: "source-media.mp4", bytes: 17 } }));
+ const stale = await resolveLocalSource({ video: VIDEO, slug: SLUG, from: 2309, to: 2322 }, cfg);
+ assert.equal(stale.windowStart, 0);
+ assert.equal(stale.clock, undefined);
+ } finally {
+ await rm(t.root, { recursive: true, force: true });
+ }
+});
+
test("saved-video: a source-media container still in the video dir, through a relative link into media/", async () => {
const t = await tree();
try {