commit c519e4e8e1bc3b358a3ac4fc867e3d6dccb0d48d
parent 77157a37a5b80a7f8a5742dc0a707c457b9900c3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 6 Nov 2026 22:16:05 -0500
Merge main into lane/cast (one-clock): the changelog's two new entries both kept
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
40 files changed, 3638 insertions(+), 62 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
@@ -204,12 +204,35 @@ of four videos byte-identical, the fourth with 65 of 84 cue texts rewritten and
shifted by up to **2.24 s**. `--cue-source auto|local|http` makes the choice explicit;
`local` refuses to fall back rather than silently cut from other cues.
+**Two FILES of one recording disagree too — by seconds, and not by a constant.** A Rumble
+channel's cues are parakeet's over `data/<id>/audio.mp3`, a separate audio-only download;
+its clips are cut from another file (the saved whole video, or a remote seek). Measured
+2026-11-06 with parakeet word timings on every fetched window of quartering-diet rev9-a3:
+c43 +13.1 s (the "310" misclip), c45 +13.6 s, c20 +5.2 s, k41 +2.6 s, c18 +1.6 s, k46 −0.7 s,
+c19 ≈ −1 s, c22 ≈ +2 s — and v7eqa6e had c44 at 0 s and c45 at +13.6 s: a STEP inside one
+stream. The rule (lane one-clock): **one clock per recording, the cues'.** A whole-recording
+platform's window (`clips.wholeRecordingPlatforms`, default Rumble) is never a remote seek —
+umtool asks `fetch-windows`, which saves the recording whole once and makes its time map
+current, `data/<id>/clock.json` (the transcription source cross-correlated against the saved
+container every 5 min and around each cited span, a piecewise-linear fit with its residual;
+`common/lib/recordingClock.mjs`); every window cut from the saved container, and the
+saved-video tier the render reads, goes through it, and windows cut on another clock are
+retired. A span on a step, or a map that could not be fitted, is cut on its best guess and
+said NOT certain — **`umtool quote-check <p>`** is the per-clip guarantee: the editor
+transcribes what each clip plays, the quote is found in it and in the cues, and a clip heard
+elsewhere is `moved` (`umtool window <p> <clip> --align` snaps the cut to the words) or
+`not-found`; `umtool check` blocks on both and a take refuses them unless `--quote-ruled`.
+
**Rumble videos have two ids** — the archive keys by the EMBED id, a local cue dir is
named for the URL SLUG — so a locally-authored manifest misses on every Rumble clip. It
fails loudly; fix with a per-clip `siteVideo`/`siteChannel`, or `--resolve-site-ids` to
scan the channel's shards (opt-in: a shard is up to 8 MB). Do **not** derive the id from
`citeUrl`: a citeUrl may deliberately cite a different recording (a mirror that reads
-better), whose clock is not the same.
+better), whose clock is not the same. The other way round — a manifest citing the EMBED id,
+asked of the corpus — is resolved on the disk side: on a Rumble channel, an id with no
+directory is looked up in the channel's `metadata.info.json` ids (`resolveVideoDirId`,
+`common/lib/videoDir-server.mjs`), so fetches, persists and the render find
+`data/<slug>/` (6 Nov: every embed-id fetch went to a `data/<embed>/` that did not exist).
This tooling is on `main` as of 2026-08-20.
diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts
@@ -7,7 +7,7 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { chmod, mkdir, mkdtemp, readFile, readdir, writeFile } from "node:fs/promises";
+import { chmod, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import {
@@ -751,3 +751,88 @@ test("whole recording: wholeRecording false restores the remote seek; a platform
assert.equal(none.downloads.length, 0);
assert.deepEqual(r4.fetched.map((i) => i.id), ["v1"]);
});
+
+// ONE CLOCK PER RECORDING (lane one-clock): a whole-recording channel's saved
+// video has its time map measured (once per run, anchored around every span the
+// run asks of it) before a window is answered or cut, and the windows cut on
+// another clock are retired.
+const RUMBLE_CONFIG = { url: "https://rumble.com/c/x", platform: "rumble" } as unknown as ChannelConfig;
+const CLOCK = {
+ version: 1, id: "k1", createdAt: "", source: { file: "audio.mp3", bytes: 1 }, target: { file: "source-media.mp4", bytes: 1 },
+ method: "xcorr" as const, params: {}, anchors: [], segments: [{ from: 0, to: 600, offset: 13.1, rate: 0, n: 3, rms: 0 }],
+ gaps: [], residual: { rms: 0, max: 0, n: 3 }, ok: true,
+};
+
+function clockHarness(plan: "measure" | "current") {
+ const w = wholeHarness({ saved: ["v1"] });
+ const ensured: { videoDir: string; extra: number[] }[] = [];
+ const retiredFor: string[] = [];
+ w.h.deps.readChannelConfig = async (_p, slug) => (slug === "c" ? RUMBLE_CONFIG : null);
+ w.h.deps.ensureClock = async ({ videoDir, extra }) => {
+ ensured.push({ videoDir: path.basename(videoDir), extra });
+ return { clock: CLOCK, measured: plan === "measure", plan };
+ };
+ w.h.deps.retireOffClock = async ({ videoDir, clockId }) => {
+ retiredFor.push(`${path.basename(videoDir)}:${clockId}`);
+ const clips = path.join(videoDir, "clips");
+ const names = (await readdir(clips).catch(() => [] as string[])).filter((n) => n.endsWith(".mp4"));
+ for (const n of names) await rm(path.join(clips, n));
+ return names.map((n) => n.replace(/\.mp4$/, ""));
+ };
+ return { ...w, ensured, retiredFor };
+}
+
+test("one clock: the map is measured once per video, around the run's spans, before the cuts", async () => {
+ const c = clockHarness("measure");
+ const logs: string[] = [];
+ const r = await fetchWindows({
+ paths: await corpus(),
+ items: [rumbleItem("v1", 10), rumbleItem("v1", 40)],
+ provenance: { requestedBy: "test" },
+ gapMs: 1000,
+ onLog: (l) => logs.push(l),
+ deps: c.h.deps,
+ });
+ assert.deepEqual(c.ensured, [{ videoDir: "v1", extra: [15, 45] }]);
+ assert.deepEqual(c.retiredFor, ["v1:k1"]);
+ assert.deepEqual(r.clocked, ["c/v1"]);
+ assert.deepEqual(c.cuts.map((x) => x.from), [10, 40]);
+});
+
+test("one clock: a held window cut on another clock is retired and cut again", async () => {
+ const c = clockHarness("current");
+ const paths = await corpus();
+ const clips = path.join(paths.channelsDir, "c", "data", "v1", "clips");
+ await mkdir(clips, { recursive: true });
+ await writeFile(path.join(clips, "0.00-60.00.mp4"), "mp4");
+ await writeFile(path.join(clips, "0.00-60.00.json"), JSON.stringify({ requestedBy: "umtool" }));
+ const logs: string[] = [];
+ const r = await fetchWindows({
+ paths,
+ items: [rumbleItem("v1", 10)],
+ provenance: { requestedBy: "test" },
+ gapMs: 1000,
+ onLog: (l) => logs.push(l),
+ deps: c.h.deps,
+ });
+ assert.equal(r.cached.length, 0);
+ assert.deepEqual(r.retired, ["c/v1/clips/0.00-60.00"]);
+ assert.deepEqual(c.cuts.map((x) => x.from), [10]);
+ assert.match(logs.join(""), /window\(s\) cut on another clock .* retired: 0\.00-60\.00/);
+});
+
+test("one clock: a window held ON the map's clock is answered from the cache", async () => {
+ const c = clockHarness("current");
+ c.h.deps.retireOffClock = async () => [];
+ const paths = await corpus();
+ const clips = path.join(paths.channelsDir, "c", "data", "v1", "clips");
+ await mkdir(clips, { recursive: true });
+ await writeFile(path.join(clips, "0.00-60.00.mp4"), "mp4");
+ await writeFile(
+ path.join(clips, "0.00-60.00.json"),
+ JSON.stringify({ requestedBy: "umtool", source: "saved-video", clock: { id: "k1", from: 13.1, to: 73.1, offset: 13.1, certain: true } }),
+ );
+ const r = await go(paths, [rumbleItem("v1", 10)], c.h);
+ assert.equal(r.cached.length, 1);
+ assert.equal(c.cuts.length, 0);
+});
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts
@@ -30,6 +30,10 @@ import {
} from "../lib/clipWindowSync";
import { channelConfigPlatform } from "../lib/videoId";
import { resolveVideoDirId } from "../lib/videoDir-server.mjs";
+import { ensureRecordingClock } from "../lib/recordingClock-server";
+import type { RecordingClock } from "../lib/recordingClock.mjs";
+import { listClipWindows } from "../lib/clipWindow-server";
+import { evictClipWindows } from "./evictClipWindows";
import {
cutSavedVideoWindow,
savedWindowSource,
@@ -157,6 +161,20 @@ import { findVideoSourceUrl } from "./undownloadedVideos";
// seek for that run. The editor puts these items on the platform's DOWNLOAD
// queue (fetchWindowsAction.ts), where a persist runs, not its clip queue.
//
+// ONE CLOCK PER RECORDING (lane one-clock, lib/recordingClock.mjs). The cues
+// of a whole-recording channel were transcribed from another file than the
+// saved video (a Rumble channel's audio.mp3): two downloads of one stream, two
+// clocks — 13.6 s apart, and stepping inside one stream, on 6 Nov. So before a
+// window of such a video is answered from clips/ or cut from its saved
+// container, its TIME MAP (`clock.json`) is made current: measured now when
+// missing or stale (anchored every 5 min and around every span this run asks
+// of it), right after a whole download too. The cut then goes through it
+// (savedVideoWindow-server.ts), and the video's windows cut on another clock —
+// a remote seek, a cut made before the map — are RETIRED through the targeted
+// eviction, and their spans cut again. A map that could not be measured is
+// said in the log and the windows are cut on the container's clock: the
+// per-clip quote check (umtool quote-check) is what catches those.
+//
// A JOB OF THIS KIND SPANS CHANNELS, so runManagedFunction's per-channel text
// guard has no channel to ask. It is asked here instead, once per channel: an
// item on a channel whose text is not readable fails as `unreachable` (its
@@ -252,6 +270,11 @@ export type FetchWindowsResult = {
// again, and fresh fetches that failed `desynced` — as
// `<slug>/<dir id>/clips/<name>.desynced.<ext>`.
setAside: string[];
+ // ONE CLOCK PER RECORDING (the header): videos whose time map this run
+ // measured (`<slug>/<dir id>`), and the windows it retired as cut on another
+ // clock (`<slug>/<dir id>/clips/<from>-<to>`).
+ clocked?: string[];
+ retired?: string[];
stopped?: FetchWindowsStop;
};
@@ -304,8 +327,41 @@ export type FetchWindowsDeps = {
assertMediaReachable: (paths: Paths, slug: string) => Promise<unknown>;
// Save a video's whole recording to the saved-video store (the header).
saveWholeRecording: (opts: SaveWholeRecordingOpts) => Promise<SaveWholeRecordingResult>;
+ // The recording's time map (lib/recordingClock-server.ts): the current one,
+ // else measured now and written; null when none applies.
+ ensureClock: (opts: {
+ paths: Paths;
+ videoDir: string;
+ extra: number[];
+ onLog: (line: string) => void;
+ signal?: AbortSignal;
+ }) => Promise<{ clock: RecordingClock | null; measured: boolean; plan: string }>;
+ // Remove the windows of a video NOT cut through `clockId` (a remote seek, a
+ // 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 windows of a video cut on another clock than `clockId`, evicted through
+// the targeted eviction (controller/evictClipWindows.ts: windows known bad).
+async function retireOffClockWindows(o: {
+ paths: Paths;
+ slug: string;
+ dirId: string;
+ videoDir: string;
+ clockId: string;
+}): Promise<string[]> {
+ const off = (await listClipWindows(o.videoDir)).filter((w) => w.provenance?.clock?.id !== o.clockId);
+ if (!off.length) return [];
+ await evictClipWindows({
+ paths: o.paths,
+ slug: o.slug,
+ id: o.dirId,
+ windows: off.map((w) => ({ from: w.from, to: w.to })),
+ });
+ return off.map((w) => `${w.from.toFixed(2)}-${w.to.toFixed(2)}`);
+}
+
export type SaveWholeRecordingOpts = {
paths: Paths;
slug: string;
@@ -418,6 +474,16 @@ const DEFAULT_DEPS: FetchWindowsDeps = {
recordFailedCopy,
storedMediaUrl,
probeWindow: (file, paths) => probeWindowStreams(file, paths.ffprobeBin),
+ ensureClock: (o) =>
+ ensureRecordingClock({
+ ffmpegBin: o.paths.ffmpegBin,
+ ffprobeBin: o.paths.ffprobeBin,
+ videoDir: o.videoDir,
+ extra: o.extra,
+ onLog: o.onLog,
+ signal: o.signal,
+ }),
+ retireOffClock: retireOffClockWindows,
assertMediaReachable: (paths, slug) => assertChannelMediaReachable(paths, slug),
saveWholeRecording: saveWholeRecordingManaged,
};
@@ -589,6 +655,50 @@ export async function fetchWindows({
const interrupted = (): FetchWindowsStop | null =>
signal?.aborted ? "cancel" : drainSignal?.aborted ? "drain" : null;
+ // ONE CLOCK PER RECORDING (the header): each video's time map, once per run
+ // (null: none applies). A video with no saved container is not remembered —
+ // a whole download later in the run gives it one.
+ const clocks = new Map<string, RecordingClock | null>();
+ const clockOf = async (
+ item: FetchWindowsItem,
+ label: string,
+ videoDir: string,
+ dirId: string,
+ ): Promise<RecordingClock | null> => {
+ if (clocks.has(videoDir)) return clocks.get(videoDir) ?? null;
+ // Anchors around every span of this video the run asks for.
+ const extra = work.filter((w) => w.slug === item.slug && w.id === item.id).map((w) => (w.from + w.to) / 2);
+ let r: Awaited<ReturnType<FetchWindowsDeps["ensureClock"]>>;
+ try {
+ r = await deps.ensureClock({ paths, videoDir, extra, onLog: fetchLog, signal: fetchSignal });
+ } catch (e) {
+ log(
+ ` ⏱ ${label}: the recording's clock could not be measured (${(e as Error).message}); ` +
+ "its windows are cut on the saved video's own clock — check their quotes (umtool quote-check).",
+ );
+ clocks.set(videoDir, null);
+ return null;
+ }
+ if (r.plan === "no-container") return null;
+ clocks.set(videoDir, r.clock);
+ if (!r.clock) return null;
+ if (r.measured) (result.clocked ??= []).push(`${item.slug}/${dirId}`);
+ const retired = await deps
+ .retireOffClock({ paths, slug: item.slug, dirId, videoDir, clockId: r.clock.id })
+ .catch((e: unknown) => {
+ log(` ⏱ ${label}: retiring the windows cut on another clock failed: ${(e as Error).message}`);
+ return [] as string[];
+ });
+ if (retired.length) {
+ for (const n of retired) (result.retired ??= []).push(`${item.slug}/${dirId}/clips/${n}`);
+ log(
+ ` ⏱ ${item.slug}/${dirId}: ${retired.length} window(s) cut on another clock (a remote seek, or before the map) ` +
+ `retired: ${retired.join(", ")} — cut again from the saved video on the cue clock.`,
+ );
+ }
+ return r.clock;
+ };
+
// A whole download that failed this run, by video dir: the video's other
// windows fail with its message, without a second attempt.
const wholeFailed = new Map<string, { message: string; failureClass: FetchWindowsFailureClass }>();
@@ -661,6 +771,11 @@ export async function fetchWindows({
});
const videoDir = path.join(paths.channelsDir, item.slug, "data", dirId);
+ // ONE CLOCK PER RECORDING: a whole-recording channel's saved video has its
+ // time map before anything is answered from its windows or cut from it.
+ const clockWanted = wholeRecordingFor(settings, channelConfigPlatform(config) ?? "", item, wholeRecording);
+ const clock = clockWanted ? await clockOf(item, label, videoDir, dirId) : null;
+
// 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
@@ -676,7 +791,18 @@ export async function fetchWindows({
progress();
continue;
}
- const { hit, desynced } = held;
+ const { desynced } = held;
+ let hit = held.hit;
+ // A held window cut on another clock than the recording's map is not this
+ // span's seconds: retired, and the span cut again below.
+ if (hit && clock && hit.provenance?.clock?.id !== clock.id) {
+ const retired = await deps
+ .retireOffClock({ paths, slug: item.slug, dirId, videoDir, clockId: clock.id })
+ .catch(() => [] as string[]);
+ for (const n of retired) (result.retired ??= []).push(`${item.slug}/${dirId}/clips/${n}`);
+ log(` ⏱ ${label}: clips/${hit.file} was cut on another clock — retired; cut again on the cue clock.`);
+ hit = null;
+ }
for (const d of desynced) {
result.setAside.push(`${item.slug}/${dirId}/clips/${d.setAsideAs}`);
log(
@@ -895,6 +1021,8 @@ export async function fetchWindows({
result.saved.push(`${item.slug}/${item.id}`);
const clean = await deps.recordClean(platform, paths).catch(() => null);
if (clean) log(clean);
+ // The map from the cues' clock onto the container just saved.
+ await clockOf(item, label, videoDir, dirId);
const after = await deps.savedWindowSource({
paths,
slug: item.slug,
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-read.mjs b/common/lib/recordingClock-read.mjs
@@ -0,0 +1,44 @@
+// recordingClock-read — the time map's READ, in plain JS (lane one-clock).
+//
+// evidenceClip.mjs's saved-video tier reads `data/<id>/clock.json` under bare
+// node (umtool's report-to-video scripts), so the read cannot be the TS
+// sidecar's (recordingClock-server.ts declares the file and writes it). The
+// shape check is the same one, coerceRecordingClock; like every sidecar read,
+// anything wrong reads as null.
+
+import { readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import { CLOCK_FILE, clockMatches, coerceRecordingClock } from "./recordingClock.mjs";
+
+/**
+ * A video dir's clock, or null (absent, unreadable, malformed).
+ * @param {string} videoDir
+ * @returns {Promise<import("./recordingClock.mjs").RecordingClock | null>}
+ */
+export async function readRecordingClock(videoDir) {
+ try {
+ return coerceRecordingClock(JSON.parse(await readFile(path.join(/* turbopackIgnore: true */ videoDir, CLOCK_FILE), "utf8")));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The clock that applies to cutting `container` — the map about THIS container
+ * (same size as when it was measured) — or null: none, or a stale one (the
+ * video saved again: its map is another file's).
+ * @param {string} videoDir
+ * @param {string} container the saved container's path
+ * @returns {Promise<import("./recordingClock.mjs").RecordingClock | null>}
+ */
+export async function clockForContainer(videoDir, container) {
+ const clock = await readRecordingClock(videoDir);
+ if (!clock) return null;
+ if (path.basename(container) !== clock.target.file) return null;
+ try {
+ const s = await stat(container);
+ return clockMatches(clock, { targetBytes: s.size }) ? clock : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/common/lib/recordingClock-server.test.ts b/common/lib/recordingClock-server.test.ts
@@ -0,0 +1,161 @@
+// The time map measured from real files (lane one-clock): a synthetic stream
+// encoded as the transcription source (`audio.mp3`) and, shifted, with a
+// stretch of something else spliced in, as the saved container (an AAC mp4) —
+// the 6 Nov shape: +2.5 s, then +13.1 s after the splice. ffmpeg encodes both;
+// the measurement decodes them as it would a real stream.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/recordingClock-server.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, rm, stat, writeFile, readFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { execa } from "execa";
+import { clockOffsetAt, mapSpan } from "./recordingClock.mjs";
+import {
+ ensureRecordingClock,
+ planRecordingClock,
+ recordingClockSidecar,
+} from "./recordingClock-server";
+import { clockForContainer, readRecordingClock } from "./recordingClock-read.mjs";
+
+const FFMPEG = process.env.FFMPEG_BIN ?? "ffmpeg";
+const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe";
+const SR = 16000;
+
+function speech(seconds: number, seed: number): Float32Array {
+ let s = seed >>> 0 || 1;
+ const rnd = () => {
+ s ^= s << 13;
+ s >>>= 0;
+ s ^= s >>> 17;
+ s ^= s << 5;
+ s >>>= 0;
+ return s / 4294967296;
+ };
+ const out = new Float32Array(Math.round(seconds * SR));
+ let i = 0;
+ while (i < out.length) {
+ const burst = Math.round((0.08 + rnd() * 0.3) * SR);
+ const amp = rnd() < 0.2 ? 0 : 0.05 + rnd() * 0.3;
+ // A voiced-ish burst: a pitch around 120–220 Hz plus noise.
+ const f0 = 120 + rnd() * 100;
+ for (let k = 0; k < burst && i < out.length; k += 1, i += 1) {
+ out[i] = amp * (0.6 * Math.sin((2 * Math.PI * f0 * k) / SR) + 0.4 * (rnd() * 2 - 1));
+ }
+ }
+ return out;
+}
+
+const dirs: string[] = [];
+after(async () => {
+ for (const d of dirs) await rm(d, { recursive: true, force: true });
+});
+
+async function encode(samples: Float32Array, out: string, codec: string[]) {
+ const raw = `${out}.f32`;
+ await writeFile(raw, Buffer.from(samples.buffer, samples.byteOffset, samples.byteLength));
+ await execa(FFMPEG, ["-v", "error", "-y", "-f", "f32le", "-ar", String(SR), "-ac", "1", "-i", raw, ...codec, out]);
+ await rm(raw);
+}
+
+async function fixture() {
+ const root = await mkdtemp(path.join(os.tmpdir(), "clock-"));
+ dirs.push(root);
+ const videoDir = path.join(root, "channels", "c", "data", "v1slug");
+ const store = path.join(root, "saved-videos", "c", "v1slug");
+ await mkdir(videoDir, { recursive: true });
+ await mkdir(store, { recursive: true });
+ const src = speech(420, 11);
+ const cut = Math.round(200 * SR);
+ const tgt = new Float32Array(Math.round((420 + 2.5 + 10.6) * SR));
+ tgt.set(speech(2.5, 5), 0);
+ tgt.set(src.subarray(0, cut), Math.round(2.5 * SR));
+ tgt.set(speech(10.6, 77), Math.round(2.5 * SR) + cut);
+ tgt.set(src.subarray(cut), Math.round(2.5 * SR) + cut + Math.round(10.6 * SR));
+ await encode(src, path.join(videoDir, "audio.mp3"), ["-c:a", "libmp3lame", "-q:a", "5"]);
+ await encode(tgt, path.join(store, "source-media.mp4"), ["-c:a", "aac", "-b:a", "96k"]);
+ const bytes = (await stat(path.join(store, "source-media.mp4"))).size;
+ await writeFile(
+ path.join(videoDir, "saved-video.json"),
+ JSON.stringify({ storedAt: "2026-11-06T00:00:00.000Z", dir: store, file: "source-media.mp4", bytes }),
+ );
+ return { videoDir, container: path.join(store, "source-media.mp4") };
+}
+
+const OPTS = { sampleRate: 4000, probeSeconds: 10, searchSeconds: 20, everySeconds: 60, minGapSeconds: 10 };
+
+test("a step and an offset, measured from an mp3 against an AAC mp4, written as clock.json", async () => {
+ const { videoDir, container } = await fixture();
+ assert.equal((await planRecordingClock(videoDir)).kind, "measure");
+ const logs: string[] = [];
+ const r = await ensureRecordingClock({
+ ffmpegBin: FFMPEG,
+ ffprobeBin: FFPROBE,
+ videoDir,
+ extra: [150],
+ options: OPTS,
+ onLog: (l) => logs.push(l),
+ });
+ assert.equal(r.measured, true);
+ const clock = r.clock!;
+ assert.equal(clock.ok, true, clock.why);
+ assert.equal(clock.segments.length, 2, JSON.stringify(clock.segments));
+ // Exact to the sample: the source decoded from its start, the target seeked
+ // with a pre-roll (an input seek alone lands an AAC excerpt 10–55 ms off).
+ assert.ok(Math.abs(clock.segments[0].offset - 2.5) < 0.002, `before ${clock.segments[0].offset}`);
+ assert.ok(Math.abs(clock.segments[1].offset - 13.1) < 0.002, `after ${clock.segments[1].offset}`);
+ assert.ok(Math.abs(clock.segments[1].offset - clock.segments[0].offset - 10.6) < 0.002);
+ assert.ok(clock.gaps[0].from < 200 && clock.gaps[0].to > 200, JSON.stringify(clock.gaps));
+ assert.ok((clock.residual.rms ?? 1) < 0.005);
+ assert.ok(logs.some((l) => /clock → clock\.json: ok/.test(l)), logs.join(""));
+ // On disk, read back by both readers; current now, not measured again.
+ assert.deepEqual(await recordingClockSidecar.load(videoDir), clock);
+ assert.deepEqual(await readRecordingClock(videoDir), clock);
+ assert.deepEqual(await clockForContainer(videoDir, container), clock);
+ const again = await ensureRecordingClock({ ffmpegBin: FFMPEG, ffprobeBin: FFPROBE, videoDir, options: OPTS });
+ assert.equal(again.measured, false);
+ assert.equal(again.plan, "current");
+ // The map: a span before the splice +2.5, after it +13.1, across it uncertain.
+ assert.ok(Math.abs(clockOffsetAt(clock, 100).offset - 2.5) < 0.002);
+ assert.equal(mapSpan(clock, 300, 310).certain, true);
+ assert.equal(mapSpan(clock, 190, 210).certain, false);
+});
+
+test("a container saved again makes the map stale; a source extracted from the container needs none", async () => {
+ const { videoDir, container } = await fixture();
+ await ensureRecordingClock({ ffmpegBin: FFMPEG, ffprobeBin: FFPROBE, videoDir, options: { ...OPTS, everySeconds: 200 } });
+ const pointer = JSON.parse(await readFile(path.join(videoDir, "saved-video.json"), "utf8"));
+ await writeFile(container, Buffer.alloc(1000));
+ assert.equal(await clockForContainer(videoDir, container), null);
+ assert.equal((await planRecordingClock(videoDir)).kind, "measure");
+ await writeFile(
+ path.join(videoDir, "media-import.json"),
+ JSON.stringify({
+ entries: [
+ {
+ at: "2026-10-26T19:36:46.301Z",
+ via: "record-live",
+ source: { path: "/x.ts", name: "x.ts", bytes: 1, moved: true },
+ finalized: "remuxed",
+ container: { file: pointer.file, seconds: 1, bytes: 1000 },
+ kept: "new",
+ audio: "extracted",
+ },
+ ],
+ }),
+ );
+ assert.equal((await planRecordingClock(videoDir)).kind, "same-clock");
+});
+
+test("no saved container, or no separate source: nothing to measure", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "clock-none-"));
+ dirs.push(root);
+ assert.equal((await planRecordingClock(root)).kind, "no-container");
+ const store = path.join(root, "store");
+ await mkdir(store);
+ await writeFile(path.join(store, "source-media.mp4"), "x");
+ await writeFile(path.join(root, "saved-video.json"), JSON.stringify({ dir: store, file: "source-media.mp4", bytes: 1 }));
+ assert.equal((await planRecordingClock(root)).kind, "no-source");
+});
diff --git a/common/lib/recordingClock-server.ts b/common/lib/recordingClock-server.ts
@@ -0,0 +1,401 @@
+// recordingClock-server — MEASURE a recording's time map and write it
+// (lane one-clock; the map itself, its fit and its lookups: ./recordingClock.mjs).
+//
+// The SOURCE is the file the cues were transcribed from — the video dir's
+// `audio.<fmt>` (the one the transcribe path reads first, AUDIO_PREFERENCE) —
+// and the TARGET is the saved whole container. The source is decoded FROM ITS
+// START, as the transcriber decoded it: an mp3 cannot be seeked to the sample
+// (a VBR file's byte seek lands where its bitrate estimate says, not where the
+// samples are), and a cue's second is a count of samples from the first. Only
+// the probes are kept (≈ 20 s each), so a four-hour stream costs a streamed
+// decode, not its PCM in memory. The target is an mp4, whose index seeks
+// exactly, so each anchor decodes only its own search excerpt there, with the
+// same input seek the cutters use (evidenceClip.mjs cutArgs).
+//
+// No map is measured when the source shares the container's clock: a landed
+// container whose `audio.<fmt>` was EXTRACTED from it (media-import.json, the
+// live recorder and import-media). Its cues are the container's own seconds.
+//
+// `data/<id>/clock.json` is a declared sidecar (sidecar-server.ts). A map that
+// is not ok is written too, with its reason: the next fetch knows the stream
+// was measured and why the map cannot be trusted, and says so instead of
+// measuring again.
+
+import { spawn } from "node:child_process";
+import { stat } from "node:fs/promises";
+import path from "node:path";
+import { execa } from "execa";
+import { sidecar, sidecarField } from "./sidecar-server";
+import {
+ CLOCK_DEFAULTS,
+ CLOCK_FILE,
+ CLOCK_VERSION,
+ anchorTimes,
+ clockMatches,
+ coerceRecordingClock,
+ describeClock,
+ fitClock,
+ measureAnchor,
+ refineTimes,
+ type RecordingClock,
+} from "./recordingClock.mjs";
+import { audioFilesOf, present } from "./evidenceClip.mjs";
+import { probeMedia } from "./evidenceClip-server";
+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 });
+
+export type ClockOptions = Partial<typeof CLOCK_DEFAULTS>;
+
+// ---- decoding ---------------------------------------------------------------
+
+/**
+ * Decode `file` from its first sample, mono at `sampleRate`, keeping only the
+ * spans asked for (seconds, the decoder's own clock). Stops reading at the
+ * last span's end.
+ */
+export async function decodeSpansFromStart(opts: {
+ ffmpegBin: string;
+ file: string;
+ spans: { from: number; to: number }[];
+ sampleRate: number;
+ signal?: AbortSignal;
+}): Promise<Float32Array[]> {
+ const { sampleRate: sr } = opts;
+ const spans = opts.spans.map((s) => ({
+ a: Math.max(0, Math.round(s.from * sr)),
+ b: Math.max(0, Math.round(s.to * sr)),
+ }));
+ const out = spans.map((s) => new Float32Array(Math.max(0, s.b - s.a)));
+ const end = spans.reduce((m, s) => Math.max(m, s.b), 0);
+ if (end === 0) return out;
+ const args = [
+ "-v", "error", "-nostdin",
+ "-i", opts.file,
+ "-vn", "-ac", "1", "-ar", String(sr),
+ "-t", ((end + sr) / sr).toFixed(3),
+ "-f", "f32le", "pipe:1",
+ ];
+ await new Promise<void>((resolve, reject) => {
+ const child = spawn(opts.ffmpegBin, args, { stdio: ["ignore", "pipe", "pipe"] });
+ let err = "";
+ let pos = 0; // samples seen
+ let carry: Buffer | null = null;
+ const onAbort = () => child.kill("SIGKILL");
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
+ child.stderr.on("data", (d: Buffer) => {
+ err = (err + d.toString()).slice(-2000);
+ });
+ child.stdout.on("data", (chunk: Buffer) => {
+ let buf = carry ? Buffer.concat([carry, chunk]) : chunk;
+ const whole = buf.length - (buf.length % 4);
+ carry = whole < buf.length ? Buffer.from(buf.subarray(whole)) : null;
+ buf = buf.subarray(0, whole);
+ const n = whole / 4;
+ const chunkStart = pos;
+ const chunkEnd = pos + n;
+ for (let i = 0; i < spans.length; i += 1) {
+ const s = spans[i];
+ const lo = Math.max(s.a, chunkStart);
+ const hi = Math.min(s.b, chunkEnd);
+ for (let k = lo; k < hi; k += 1) out[i][k - s.a] = buf.readFloatLE((k - chunkStart) * 4);
+ }
+ pos = chunkEnd;
+ });
+ child.on("error", reject);
+ child.on("close", (code) => {
+ opts.signal?.removeEventListener("abort", onAbort);
+ if (opts.signal?.aborted) reject(new Error("cancelled"));
+ else if (code !== 0) reject(new Error(`ffmpeg could not decode ${path.basename(opts.file)}: ${err.trim().split("\n").slice(-2).join(" | ")}`));
+ else resolve();
+ });
+ });
+ return out;
+}
+
+// The seconds an input seek lands short of, decoded and dropped by an output
+// seek. An input seek alone into an AAC track lands 10–55 ms off, varying with
+// the second (measured on an audio-only mp4: 48, 38, 54, 12 ms at four
+// seconds); seeking PRE_ROLL_S earlier and dropping the rest after the decoder
+// is exact at every one.
+const PRE_ROLL_S = 3;
+
+/** Decode [from, from + seconds) of `file`: an input seek PRE_ROLL_S early, then exact. */
+export async function decodeExcerpt(opts: {
+ ffmpegBin: string;
+ file: string;
+ from: number;
+ seconds: number;
+ sampleRate: number;
+ signal?: AbortSignal;
+}): Promise<Float32Array> {
+ const from = Math.max(0, opts.from);
+ const seek = Math.max(0, from - PRE_ROLL_S);
+ const r = await execa(
+ opts.ffmpegBin,
+ [
+ "-v", "error", "-nostdin",
+ "-ss", seek.toFixed(3),
+ "-i", opts.file,
+ "-ss", (from - seek).toFixed(3),
+ "-t", opts.seconds.toFixed(3),
+ "-vn", "-ac", "1", "-ar", String(opts.sampleRate),
+ "-f", "f32le", "pipe:1",
+ ],
+ {
+ encoding: "buffer",
+ reject: false,
+ timeout: 120_000,
+ maxBuffer: 64 * 1024 * 1024,
+ ...(opts.signal ? { cancelSignal: opts.signal } : {}),
+ },
+ );
+ if (r.exitCode !== 0) {
+ const err = Buffer.from(r.stderr ?? "").toString().trim().split("\n").slice(-2).join(" | ");
+ throw new Error(`ffmpeg could not decode ${path.basename(opts.file)} at ${opts.from.toFixed(1)}s: ${err}`);
+ }
+ const buf = Buffer.from(r.stdout as Uint8Array);
+ const n = Math.floor(buf.length / 4);
+ const out = new Float32Array(n);
+ for (let i = 0; i < n; i += 1) out[i] = buf.readFloatLE(i * 4);
+ return out;
+}
+
+// ---- which files ---------------------------------------------------------------
+
+/** The file the cues were transcribed from: the best `audio.<fmt>` there is. */
+export async function transcriptionSourceOf(videoDir: string): Promise<{ name: string; path: string } | null> {
+ for (const f of await audioFilesOf(videoDir)) if (await present(f.path)) return f;
+ return null;
+}
+
+/**
+ * Was the transcription source EXTRACTED from this container (a landed live
+ * recording, an import)? Then the cues are already on its clock.
+ */
+export async function sourceSharesContainerClock(videoDir: string, pointer: SavedVideoPointer): Promise<boolean> {
+ const read = await readJsonFile(path.join(videoDir, MEDIA_IMPORT_FILENAME));
+ if (!read.ok) return false;
+ const rec = coerceMediaImport(read.value);
+ const last = rec?.entries?.[rec.entries.length - 1];
+ return !!last && last.audio === "extracted" && last.container?.file === pointer.file;
+}
+
+export type ClockPlan =
+ | { kind: "no-container" }
+ | { 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;
+ 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> {
+ const pointer = await loadSavedVideo(videoDir);
+ if (!pointer) return { kind: "no-container" };
+ const container = savedVideoPath(pointer);
+ const src = await transcriptionSourceOf(videoDir);
+ if (!src) return { kind: "no-source" };
+ if (await sourceSharesContainerClock(videoDir, pointer)) {
+ return { kind: "same-clock", source: src.path, container };
+ }
+ const [s, t, outcome] = await Promise.all([stat(src.path), stat(container), loadTranscribeOutcome(videoDir)]);
+ const have = await recordingClockSidecar.load(videoDir);
+ // 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,
+ transcribedAt: outcome?.transcribedAt ?? null,
+ stale: have,
+ };
+}
+
+// ---- measuring ------------------------------------------------------------------
+
+/**
+ * Measure the map of `videoDir`'s transcription source onto its saved
+ * container: anchors every `everySeconds` and at `extra` (cue seconds — the
+ * cited spans), refined inside every step until narrow; fitted; WRITTEN (ok or
+ * not) unless `write: false`.
+ */
+export async function measureRecordingClock(opts: {
+ ffmpegBin: string;
+ ffprobeBin: string;
+ videoDir: string;
+ source: string;
+ 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;
+ onLog?: (line: string) => void;
+ signal?: AbortSignal;
+ now?: () => Date;
+}): Promise<RecordingClock> {
+ const o = { ...CLOCK_DEFAULTS, ...(opts.options ?? {}) };
+ const sr = o.sampleRate;
+ const log = (l: string) => opts.onLog?.(l.endsWith("\n") ? l : `${l}\n`);
+ const [sp, tp] = await Promise.all([
+ probeMedia(opts.source, opts.ffprobeBin),
+ probeMedia(opts.container, opts.ffprobeBin),
+ ]);
+ const sourceSec = sp?.durationSec ?? null;
+ const targetSec = tp?.durationSec ?? null;
+ if (!sourceSec || !targetSec) {
+ throw new Error(`ffprobe could not read ${!sourceSec ? opts.source : opts.container}`);
+ }
+ const half = o.probeSeconds / 2;
+ const measure = async (times: number[]) => {
+ const probes = await decodeSpansFromStart({
+ ffmpegBin: opts.ffmpegBin,
+ file: opts.source,
+ spans: times.map((t) => ({ from: t - half, to: t + half })),
+ sampleRate: sr,
+ signal: opts.signal,
+ });
+ const out = [];
+ for (let i = 0; i < times.length; i += 1) {
+ const at = times[i];
+ const searchStart = Math.max(0, at - half - o.searchSeconds);
+ const searchEnd = Math.min(targetSec, at + half + o.searchSeconds);
+ if (searchEnd - searchStart < o.probeSeconds) {
+ out.push({ at, offset: null, score: 0, ratio: 0, ok: false, why: "past the container's end" });
+ continue;
+ }
+ const search = await decodeExcerpt({
+ ffmpegBin: opts.ffmpegBin,
+ file: opts.container,
+ from: searchStart,
+ seconds: searchEnd - searchStart,
+ sampleRate: sr,
+ signal: opts.signal,
+ });
+ out.push(measureAnchor({ at, probe: probes[i], search, searchStart, sampleRate: sr }, o));
+ }
+ return out;
+ };
+
+ const first = anchorTimes(sourceSec, { ...o, extra: opts.extra ?? [] });
+ log(
+ ` ⏱ clock: ${path.basename(opts.source)} (${Math.round(sourceSec)} s, the cues' clock) against ` +
+ `${path.basename(opts.container)} (${Math.round(targetSec)} s): ${first.length} anchor(s)`,
+ );
+ let anchors = await measure(first);
+ let fit = fitClock(anchors, o);
+ for (let pass = 0; pass < o.maxRefinePasses; pass += 1) {
+ const more = refineTimes(fit, o).filter((t) => t >= half && t <= sourceSec - half);
+ if (!more.length) break;
+ log(` ⏱ clock: a step between segments — ${more.length} more anchor(s) to narrow it`);
+ anchors = [...anchors, ...(await measure(more))].sort((a, b) => a.at - b.at);
+ fit = fitClock(anchors, o);
+ }
+ const createdAt = (opts.now?.() ?? new Date()).toISOString();
+ const clock: RecordingClock = {
+ version: CLOCK_VERSION,
+ id: `${createdAt}:${opts.targetBytes}`,
+ 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,
+ probeSeconds: o.probeSeconds,
+ searchSeconds: o.searchSeconds,
+ everySeconds: o.everySeconds,
+ tolerance: o.tolerance,
+ sourceSeconds: sourceSec,
+ targetSeconds: targetSec,
+ },
+ anchors,
+ segments: fit.segments,
+ gaps: fit.gaps,
+ residual: fit.residual,
+ ok: fit.ok,
+ ...(fit.why ? { why: fit.why } : {}),
+ };
+ if (opts.write !== false) await recordingClockSidecar.write(opts.videoDir, clock);
+ log(` ⏱ clock ${opts.write !== false ? `→ ${CLOCK_FILE}` : "(not written)"}: ${describeClock(clock)}`);
+ if (!clock.ok) {
+ // The fallback (lane one-clock, part 4) is a transcript made from the saved
+ // video itself -- one file, one clock -- and is not started from here.
+ log(
+ " ⏱ the map cannot be trusted: windows are cut on its best guess and said NOT certain — " +
+ "check their quotes (umtool quote-check); re-transcribing from the saved video is the fallback.",
+ );
+ }
+ return clock;
+}
+
+/**
+ * The map a cut from this video's saved container goes through: the current
+ * one, else measured now (and written). Null when no map applies (no
+ * container, no separate source, a source extracted from the container).
+ */
+export async function ensureRecordingClock(opts: {
+ ffmpegBin: string;
+ ffprobeBin: string;
+ videoDir: string;
+ extra?: number[];
+ options?: ClockOptions;
+ onLog?: (line: string) => void;
+ signal?: AbortSignal;
+}): Promise<{ clock: RecordingClock | null; measured: boolean; plan: ClockPlan["kind"] }> {
+ const plan = await planRecordingClock(opts.videoDir);
+ if (plan.kind === "current") return { clock: plan.clock, measured: false, plan: plan.kind };
+ if (plan.kind !== "measure") return { clock: null, measured: false, plan: plan.kind };
+ const clock = await measureRecordingClock({ ...opts, ...plan });
+ return { clock, measured: true, plan: plan.kind };
+}
+
+/**
+ * May a held window of this video answer for a cue span? Not when the
+ * recording's map is due (measured on the next fetch-windows run: every window
+ * there is on another clock) and not when it was cut through another map than
+ * the current one. A video no map applies to: yes, as ever.
+ */
+export async function heldWindowOnClock(
+ videoDir: string,
+ provenance: { clock?: { id: string } } | null | undefined,
+): Promise<boolean> {
+ let plan: ClockPlan;
+ try {
+ plan = await planRecordingClock(videoDir);
+ } catch {
+ // A file the plan could not stat (a drive not answering): the cut path's
+ // own guards say so; the cache answers as before.
+ return true;
+ }
+ if (plan.kind === "measure") return false;
+ if (plan.kind === "current") return provenance?.clock?.id === plan.clock.id;
+ return true;
+}
diff --git a/common/lib/recordingClock.mjs b/common/lib/recordingClock.mjs
@@ -0,0 +1,548 @@
+// recordingClock — ONE CLOCK PER RECORDING (lane one-clock, 6 Nov 2026).
+//
+// A recording's cues are timed on the file that was TRANSCRIBED (a Rumble
+// channel's `audio.mp3`, a separate audio-only download of the stream), and its
+// clip windows are cut from ANOTHER file — the saved whole video, or a remote
+// seek. Two downloads of one live stream are not one clock: measured on the
+// rev9-a3 pass of quartering-diet with parakeet word timings on every fetched
+// window, seven Rumble clips played the wrong words (c43 +13.1 s, c45 +13.6 s,
+// c20 +5.2 s, k41 +2.6 s, c18 +1.6 s, k46 −0.7 s, c19 ≈ −1 s), and not one
+// constant per recording: v7eqa6e had c44 at 0 s and c45 at +13.6 s, a step
+// inside one stream (a dropped stretch in one of the two downloads).
+//
+// So a recording whose windows are cut from its saved video gets a TIME MAP,
+// `data/<id>/clock.json`: the transcription source's audio (the cue clock) is
+// cross-correlated against the saved container's audio at anchors across the
+// stream — every few minutes, and around each cited span — and a
+// piecewise-linear map is fitted, offset(t) = target − source, with its residual.
+// A window asked for in cue seconds is cut from the container at the MAPPED
+// seconds and keeps its cue-clock name, so every reader (the render, the bench,
+// the moment page) stays on the one clock the cues and the manifests use.
+//
+// Between two segments that disagree there is a STEP, somewhere in a gap the
+// anchors could not narrow further; a span that touches a gap is not mapped
+// with confidence (`certain: false`) and falls to the per-clip quote check. A
+// map whose residual is bad (music, silence, a different edit) is written with
+// `ok: false` and the reason, and nothing cuts through it.
+//
+// This file is PURE and plain JS (umtool's report-to-video scripts run under
+// bare node and read the map through evidenceClip.mjs): the correlation, the
+// fit, the lookups and the file's shape. Decoding and the sidecar's writer are
+// ./recordingClock-server.ts.
+
+export const CLOCK_FILE = "clock.json";
+export const CLOCK_VERSION = 1;
+
+/**
+ * @typedef {{ sampleRate: number, probeSeconds: number, searchSeconds: number, everySeconds: number,
+ * minScore: number, minPeakRatio: number, tolerance: number, minGapSeconds: number, refinePerGap: number,
+ * maxRefinePasses: number, maxRate: number, maxRms: number, minAnchors: number, minUsableShare: number }} ClockParams
+ */
+
+/**
+ * The knobs, with the values the 6 Nov streams were measured with. Seconds
+ * unless named otherwise.
+ * @type {Readonly<ClockParams>}
+ */
+export const CLOCK_DEFAULTS = Object.freeze({
+ // Decode rate for both sides: speech correlates sharply at 8 kHz, and a lag
+ // is resolved to an eighth of a millisecond.
+ sampleRate: 8000,
+ // The source excerpt at each anchor (centred on it).
+ probeSeconds: 20,
+ // How far either side the target is searched. The largest offset measured
+ // on 6 Nov was 13.6 s.
+ searchSeconds: 45,
+ // The regular anchors' spacing across the stream.
+ everySeconds: 300,
+ // Normalised cross-correlation a match must reach, and how far above the
+ // best peak elsewhere (≥ 0.25 s away) it must stand.
+ minScore: 0.35,
+ minPeakRatio: 1.15,
+ // Two anchors on one segment agree to within this (after its drift).
+ tolerance: 0.08,
+ // A gap between two segments is narrowed until it is at most this wide.
+ minGapSeconds: 10,
+ // Anchors measured per gap per refinement pass.
+ refinePerGap: 7,
+ // Passes of refinement.
+ maxRefinePasses: 4,
+ // The steepest drift (seconds per second) one segment may have: two sound
+ // cards' clocks, or a stream resampled a hair off. Measured 6.13e-4 on
+ // v6w89mk (0 s at 2:30, +4.69 s at 2:10:27). A second anchor joins a
+ // one-anchor run within tolerance + this × the time between them.
+ maxRate: 1e-3,
+ // The fitted map is `ok` only under this RMS residual.
+ maxRms: 0.05,
+ // ...with at least this many usable anchors, this share of those measured.
+ minAnchors: 3,
+ minUsableShare: 0.4,
+});
+
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+
+// ---- FFT -------------------------------------------------------------------
+
+/** The smallest power of two ≥ n. */
+export function nextPow2(n) {
+ let p = 1;
+ while (p < n) p *= 2;
+ return p;
+}
+
+/**
+ * In-place iterative radix-2 complex FFT. `re`/`im` have a power-of-two length.
+ * @param {Float64Array} re
+ * @param {Float64Array} im
+ * @param {boolean} [inverse]
+ */
+export function fft(re, im, inverse = false) {
+ const n = re.length;
+ for (let i = 1, j = 0; i < n; i += 1) {
+ let bit = n >> 1;
+ for (; j & bit; bit >>= 1) j ^= bit;
+ j ^= bit;
+ if (i < j) {
+ let t = re[i];
+ re[i] = re[j];
+ re[j] = t;
+ t = im[i];
+ im[i] = im[j];
+ im[j] = t;
+ }
+ }
+ for (let len = 2; len <= n; len <<= 1) {
+ const ang = ((inverse ? 2 : -2) * Math.PI) / len;
+ const wr = Math.cos(ang);
+ const wi = Math.sin(ang);
+ const half = len >> 1;
+ for (let i = 0; i < n; i += len) {
+ let cr = 1;
+ let ci = 0;
+ for (let k = 0; k < half; k += 1) {
+ const a = i + k;
+ const b = a + half;
+ const xr = re[b] * cr - im[b] * ci;
+ const xi = re[b] * ci + im[b] * cr;
+ re[b] = re[a] - xr;
+ im[b] = im[a] - xi;
+ re[a] += xr;
+ im[a] += xi;
+ const ncr = cr * wr - ci * wi;
+ ci = cr * wi + ci * wr;
+ cr = ncr;
+ }
+ }
+ }
+ if (inverse) {
+ for (let i = 0; i < n; i += 1) {
+ re[i] /= n;
+ im[i] /= n;
+ }
+ }
+}
+
+/**
+ * Pre-emphasis and mean removal: a first difference sharpens the correlation
+ * peak (speech's low end is broad and correlates with itself over tens of
+ * milliseconds) and the mean would otherwise bias every lag alike.
+ * @param {ArrayLike<number>} x
+ * @returns {Float64Array}
+ */
+export function whiten(x) {
+ const out = new Float64Array(x.length);
+ let prev = 0;
+ let sum = 0;
+ for (let i = 0; i < x.length; i += 1) {
+ const v = Number(x[i]) || 0;
+ out[i] = v - 0.97 * prev;
+ prev = v;
+ sum += out[i];
+ }
+ const mean = x.length ? sum / x.length : 0;
+ for (let i = 0; i < out.length; i += 1) out[i] -= mean;
+ return out;
+}
+
+/**
+ * Where `probe` sits inside `search`: the lag (samples into `search`) with the
+ * highest normalised cross-correlation, that score, and the best score at least
+ * `guard` samples away (how unique the match is).
+ *
+ * @param {ArrayLike<number>} probe
+ * @param {ArrayLike<number>} search at least as long as `probe`
+ * @param {{ guard?: number }} [opts]
+ * @returns {{ lag: number, score: number, second: number } | null} null when
+ * either side is silent or `search` is shorter than `probe`
+ */
+export function locate(probe, search, { guard = 2000 } = {}) {
+ const p = whiten(probe);
+ const s = whiten(search);
+ const n = p.length;
+ const m = s.length;
+ if (n < 16 || m < n) return null;
+ let ep = 0;
+ for (let i = 0; i < n; i += 1) ep += p[i] * p[i];
+ if (!(ep > 1e-9)) return null;
+ const N = nextPow2(m);
+ const ar = new Float64Array(N);
+ const ai = new Float64Array(N);
+ const br = new Float64Array(N);
+ const bi = new Float64Array(N);
+ ar.set(p);
+ br.set(s);
+ fft(ar, ai);
+ fft(br, bi);
+ // conj(A) · B: c[k] = Σ p[i] s[i + k]
+ for (let i = 0; i < N; i += 1) {
+ const r = ar[i] * br[i] + ai[i] * bi[i];
+ const im = ar[i] * bi[i] - ai[i] * br[i];
+ ar[i] = r;
+ ai[i] = im;
+ }
+ fft(ar, ai, true);
+ // The energy of every n-long stretch of `search`, from prefix sums.
+ const pre = new Float64Array(m + 1);
+ for (let i = 0; i < m; i += 1) pre[i + 1] = pre[i] + s[i] * s[i];
+ const lags = m - n + 1;
+ const ncc = new Float64Array(lags);
+ let best = -Infinity;
+ let at = -1;
+ const floor = ep * 1e-6;
+ for (let k = 0; k < lags; k += 1) {
+ const es = pre[k + n] - pre[k];
+ const v = es > floor ? ar[k] / Math.sqrt(ep * es) : 0;
+ ncc[k] = v;
+ if (v > best) {
+ best = v;
+ at = k;
+ }
+ }
+ if (at < 0) return null;
+ let second = 0;
+ for (let k = 0; k < lags; k += 1) {
+ if (Math.abs(k - at) <= guard) continue;
+ if (ncc[k] > second) second = ncc[k];
+ }
+ return { lag: at, score: best, second };
+}
+
+/**
+ * One anchor: the source excerpt centred on `at` (cue clock) found in the
+ * target excerpt that starts at `searchStart` (target clock).
+ *
+ * @param {{ at: number, probe: ArrayLike<number>, search: ArrayLike<number>, searchStart: number, sampleRate: number }} a
+ * @param {Partial<typeof CLOCK_DEFAULTS>} [opts]
+ * @returns {{ at: number, offset: number | null, score: number, ratio: number, ok: boolean, why?: string }}
+ */
+export function measureAnchor({ at, probe, search, searchStart, sampleRate }, opts = {}) {
+ const o = { ...CLOCK_DEFAULTS, ...opts };
+ const hit = locate(probe, search, { guard: Math.round(0.25 * sampleRate) });
+ if (!hit) return { at, offset: null, score: 0, ratio: 0, ok: false, why: "silent" };
+ const probeStart = at - probe.length / sampleRate / 2;
+ const offset = round4(searchStart + hit.lag / sampleRate - probeStart);
+ const ratio = hit.second > 1e-9 ? hit.score / hit.second : 99;
+ const score = round4(hit.score);
+ if (hit.score < o.minScore) return { at, offset, score, ratio: round4(ratio), ok: false, why: "weak" };
+ if (ratio < o.minPeakRatio) return { at, offset, score, ratio: round4(ratio), ok: false, why: "ambiguous" };
+ return { at, offset, score, ratio: round4(Math.min(ratio, 99)), ok: true };
+}
+
+const round4 = (x) => Math.round(x * 1e4) / 1e4;
+
+// ---- the anchors --------------------------------------------------------------
+
+/**
+ * Where to measure: every `everySeconds` across the source (the first half a
+ * step in), plus the extra seconds (around each cited span), each kept where a
+ * whole probe fits. Sorted, deduplicated to a tenth of the probe.
+ *
+ * @param {number} duration the source's length
+ * @param {{ extra?: number[] } & Partial<typeof CLOCK_DEFAULTS>} [opts]
+ * @returns {number[]}
+ */
+export function anchorTimes(duration, { extra = [], ...rest } = {}) {
+ const o = { ...CLOCK_DEFAULTS, ...rest };
+ const half = o.probeSeconds / 2;
+ const lo = half;
+ const hi = duration - half;
+ if (!(hi >= lo)) return [];
+ const out = [];
+ for (let t = Math.min(o.everySeconds / 2, hi); t <= hi + 1e-9; t += o.everySeconds) out.push(t);
+ if (out.length && hi - out[out.length - 1] > o.everySeconds / 3) out.push(hi);
+ for (const x of extra) if (fin(x)) out.push(Math.min(hi, Math.max(lo, x)));
+ out.sort((a, b) => a - b);
+ const dedup = [];
+ for (const t of out) {
+ if (!dedup.length || t - dedup[dedup.length - 1] > o.probeSeconds / 10) dedup.push(round4(t));
+ }
+ return dedup;
+}
+
+// ---- the fit -----------------------------------------------------------------
+
+/** Least squares offset = a + b·(t − t0) over the points; rate 0 for a run too short to say. */
+function fitLine(points) {
+ const n = points.length;
+ const t0 = points[0].at;
+ const span = points[n - 1].at - t0;
+ if (n < 2 || span < 60) {
+ const sorted = points.map((p) => p.offset).sort((a, b) => a - b);
+ const med = sorted[Math.floor((n - 1) / 2)];
+ return { t0, offset: med, rate: 0 };
+ }
+ let sx = 0;
+ let sy = 0;
+ let sxx = 0;
+ let sxy = 0;
+ for (const p of points) {
+ const x = p.at - t0;
+ sx += x;
+ sy += p.offset;
+ sxx += x * x;
+ sxy += x * p.offset;
+ }
+ const den = n * sxx - sx * sx;
+ const rate = den > 1e-12 ? (n * sxy - sx * sy) / den : 0;
+ return { t0, offset: (sy - rate * sx) / n, rate };
+}
+
+const lineAt = (l, t) => l.offset + l.rate * (t - l.t0);
+
+/**
+ * The piecewise-linear map from the measured anchors. Consecutive usable anchors
+ * that agree (to `tolerance`, after the run's drift) are one SEGMENT; one that
+ * disagrees while the next agrees again is an OUTLIER; otherwise a new segment
+ * starts and the stretch between the two is a GAP (a step somewhere in it).
+ *
+ * @param {{ at: number, offset: number | null, ok: boolean }[]} anchors
+ * @param {Partial<typeof CLOCK_DEFAULTS>} [opts]
+ */
+export function fitClock(anchors, opts = {}) {
+ const o = { ...CLOCK_DEFAULTS, ...opts };
+ const good = anchors
+ .filter((a) => a.ok && fin(a.offset) && fin(a.at))
+ .sort((a, b) => a.at - b.at);
+ /** @type {{ at: number, offset: number }[][]} */
+ const runs = [];
+ /** @type {number[]} */
+ const outliers = [];
+ let run = null;
+ for (let i = 0; i < good.length; i += 1) {
+ const p = good[i];
+ if (!run) {
+ run = [p];
+ runs.push(run);
+ continue;
+ }
+ const line = fitLine(run);
+ // One anchor so far says nothing of drift: the next joins it within the
+ // drift a segment may have; after that, the run's own line decides.
+ const allowed = run.length === 1 ? o.tolerance + o.maxRate * Math.abs(p.at - run[0].at) : o.tolerance;
+ if (Math.abs(p.offset - lineAt(line, p.at)) <= allowed) {
+ run.push(p);
+ continue;
+ }
+ const q = good[i + 1];
+ if (q && Math.abs(q.offset - lineAt(line, q.at)) <= o.tolerance) {
+ outliers.push(p.at);
+ continue;
+ }
+ run = [p];
+ runs.push(run);
+ }
+ const segments = runs.map((r) => {
+ const l = fitLine(r);
+ let ss = 0;
+ for (const p of r) ss += (p.offset - lineAt(l, p.at)) ** 2;
+ return {
+ from: r[0].at,
+ to: r[r.length - 1].at,
+ offset: round4(lineAt(l, r[0].at)),
+ rate: Number(l.rate.toExponential(6)),
+ n: r.length,
+ rms: round4(Math.sqrt(ss / r.length)),
+ };
+ });
+ // A GAP is wider than the stretch between the two anchors: each anchor's probe
+ // reached half a probe beyond its centre, and a probe that straddles the step
+ // still matches the side holding most of it — so the step may sit up to half
+ // a probe inside either neighbour's centre.
+ const margin = o.probeSeconds / 2;
+ const gaps = [];
+ for (let i = 1; i < segments.length; i += 1) {
+ gaps.push({ from: round4(segments[i - 1].to - margin), to: round4(segments[i].from + margin) });
+ }
+ let ss = 0;
+ let max = 0;
+ let n = 0;
+ for (const r of runs) {
+ const l = fitLine(r);
+ for (const p of r) {
+ const d = Math.abs(p.offset - lineAt(l, p.at));
+ ss += d * d;
+ max = Math.max(max, d);
+ n += 1;
+ }
+ }
+ const residual = { rms: n ? round4(Math.sqrt(ss / n)) : null, max: n ? round4(max) : null, n };
+ const measured = anchors.length;
+ const why = [];
+ if (n < Math.min(o.minAnchors, measured)) why.push(`${n} usable anchor(s) of ${measured}`);
+ else if (measured && n / measured < o.minUsableShare) why.push(`only ${n} of ${measured} anchors matched (music, silence or a different edit?)`);
+ if (residual.rms !== null && residual.rms > o.maxRms) why.push(`residual ${residual.rms}s over ${o.maxRms}s`);
+ if (outliers.length > Math.max(1, n / 4)) why.push(`${outliers.length} anchors disagree with their neighbours`);
+ if (!segments.length) why.push("no anchor matched");
+ return {
+ segments,
+ gaps,
+ outliers,
+ residual,
+ ok: why.length === 0,
+ ...(why.length ? { why: why.join("; ") } : {}),
+ };
+}
+
+/**
+ * Seconds to measure next: inside every gap still wider than `minGapSeconds`,
+ * `refinePerGap` evenly spaced anchors.
+ * @param {{ gaps: { from: number, to: number }[] }} fit
+ * @param {Partial<typeof CLOCK_DEFAULTS>} [opts]
+ * @returns {number[]}
+ */
+export function refineTimes(fit, opts = {}) {
+ const o = { ...CLOCK_DEFAULTS, ...opts };
+ const out = [];
+ const margin = o.probeSeconds / 2;
+ for (const g of fit.gaps ?? []) {
+ // Between the two anchors' centres (fitClock widened the gap by a margin).
+ const from = g.from + margin;
+ const w = g.to - margin - from;
+ if (!(w > o.minGapSeconds)) continue;
+ const k = Math.max(1, Math.min(o.refinePerGap, Math.ceil(w / o.minGapSeconds) - 1));
+ for (let i = 1; i <= k; i += 1) out.push(round4(from + (w * i) / (k + 1)));
+ }
+ return out;
+}
+
+// ---- the lookups ---------------------------------------------------------------
+
+/**
+ * The offset (target − source) at cue second `t`: the segment holding it, else
+ * the nearest segment's edge value. `certain` is false inside a gap (a step lies
+ * somewhere in it) and for a map that is not `ok`.
+ *
+ * @param {RecordingClock} clock
+ * @param {number} t
+ * @returns {{ offset: number, certain: boolean, segment: number }}
+ */
+export function clockOffsetAt(clock, t) {
+ const segs = clock?.segments ?? [];
+ if (!segs.length) return { offset: 0, certain: false, segment: -1 };
+ const at = (s, x) => s.offset + s.rate * (Math.min(s.to, Math.max(s.from, x)) - s.from);
+ const ok = clock.ok === true;
+ // The segment whose centre-span holds t, else the nearer neighbour.
+ let i = 0;
+ while (i < segs.length - 1 && t > segs[i].to) {
+ const next = segs[i + 1];
+ if (t < next.from) {
+ if (next.from - t < t - segs[i].to) i += 1;
+ break;
+ }
+ i += 1;
+ }
+ // Inside a gap (a step lies somewhere in it): not certain.
+ const inGap = (clock.gaps ?? []).some((g) => t > g.from && t < g.to);
+ return { offset: round4(at(segs[i], t)), certain: ok && !inGap, segment: i };
+}
+
+/**
+ * A cue-clock span on the target's clock. `certain` only when both ends sit on
+ * ONE segment of an `ok` map (a span across a step has no single offset).
+ *
+ * @param {RecordingClock} clock
+ * @param {number} from
+ * @param {number} to
+ * @returns {{ from: number, to: number, offsetFrom: number, offsetTo: number, certain: boolean }}
+ */
+export function mapSpan(clock, from, to) {
+ const a = clockOffsetAt(clock, from);
+ const b = clockOffsetAt(clock, to);
+ return {
+ from: round4(Math.max(0, from + a.offset)),
+ to: round4(to + b.offset),
+ offsetFrom: a.offset,
+ offsetTo: b.offset,
+ certain: a.certain && b.certain && a.segment === b.segment,
+ };
+}
+
+// ---- the file ----------------------------------------------------------------
+
+/**
+ * @typedef {{ file: string, bytes: number }} ClockFileRef
+ * @typedef {{
+ * version: number,
+ * id: string,
+ * 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 }[],
+ * segments: { from: number, to: number, offset: number, rate: number, n: number, rms: number }[],
+ * gaps: { from: number, to: number }[],
+ * residual: { rms: number | null, max: number | null, n: number },
+ * ok: boolean,
+ * why?: string,
+ * }} RecordingClock
+ */
+
+/**
+ * The file's shape, checked: the clock or null (a sidecar's read never throws).
+ * @param {unknown} v
+ * @returns {RecordingClock | null}
+ */
+export function coerceRecordingClock(v) {
+ if (!v || typeof v !== "object" || Array.isArray(v)) return null;
+ const c = /** @type {Record<string, any>} */ (v);
+ if (c.version !== CLOCK_VERSION || typeof c.id !== "string" || !c.id) return null;
+ const ref = (r) => r && typeof r === "object" && typeof r.file === "string" && fin(r.bytes);
+ if (!ref(c.source) || !ref(c.target)) return null;
+ if (!Array.isArray(c.segments) || !Array.isArray(c.gaps) || !Array.isArray(c.anchors)) return null;
+ const segOk = (s) => s && fin(s.from) && fin(s.to) && fin(s.offset) && fin(s.rate) && s.to >= s.from;
+ if (!c.segments.every(segOk)) return null;
+ if (!c.gaps.every((g) => g && fin(g.from) && fin(g.to))) return null;
+ if (typeof c.ok !== "boolean") return null;
+ return /** @type {RecordingClock} */ (c);
+}
+
+/**
+ * Is this clock about THESE two files? A container saved again, or a source
+ * downloaded again, is another clock: the map is stale and nothing cuts
+ * through it.
+ * @param {RecordingClock} clock
+ * @param {{ sourceBytes?: number | null, targetBytes?: number | null }} now
+ */
+export function clockMatches(clock, { sourceBytes = null, targetBytes = null } = {}) {
+ if (sourceBytes !== null && clock.source.bytes !== sourceBytes) return false;
+ if (targetBytes !== null && clock.target.bytes !== targetBytes) return false;
+ return true;
+}
+
+/** One line for a log: the segments' offsets, the gaps, the residual. */
+export function describeClock(clock) {
+ const segs = (clock.segments ?? []).map(
+ (s) => `${s.offset >= 0 ? "+" : ""}${s.offset.toFixed(2)}s @${Math.round(s.from)}–${Math.round(s.to)}s`,
+ );
+ const gaps = (clock.gaps ?? []).map((g) => `${Math.round(g.from)}–${Math.round(g.to)}s`);
+ const res = clock.residual?.rms === null || clock.residual?.rms === undefined ? "?" : `${(clock.residual.rms * 1000).toFixed(1)} ms`;
+ const used = (clock.anchors ?? []).filter((a) => a.ok).length;
+ return (
+ `${clock.ok ? "ok" : "NOT ok"}: ${segs.join(", ") || "no segment"}` +
+ (gaps.length ? `; step(s) inside ${gaps.join(", ")}` : "") +
+ `; residual ${res} over ${used}/${(clock.anchors ?? []).length} anchors` +
+ (clock.why ? ` — ${clock.why}` : "")
+ );
+}
diff --git a/common/lib/recordingClock.test.ts b/common/lib/recordingClock.test.ts
@@ -0,0 +1,234 @@
+// One clock per recording (lane one-clock): the correlation finds a synthetic
+// offset, a step inside the stream is found and narrowed, a drift is fitted, a
+// silent or unmatched stream is not ok, and the lookups map a cue span onto the
+// target's clock — or say they cannot.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/recordingClock.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ CLOCK_DEFAULTS,
+ anchorTimes,
+ clockMatches,
+ clockOffsetAt,
+ coerceRecordingClock,
+ describeClock,
+ fitClock,
+ locate,
+ mapSpan,
+ measureAnchor,
+ refineTimes,
+ type RecordingClock,
+} from "./recordingClock.mjs";
+
+const SR = 4000;
+
+// Speech-like: noise in syllable-length bursts with pauses, from a seeded PRNG.
+function speech(seconds: number, seed: number): Float32Array {
+ let s = seed >>> 0 || 1;
+ const rnd = () => {
+ s ^= s << 13;
+ s >>>= 0;
+ s ^= s >>> 17;
+ s ^= s << 5;
+ s >>>= 0;
+ return s / 4294967296;
+ };
+ const out = new Float32Array(Math.round(seconds * SR));
+ let i = 0;
+ while (i < out.length) {
+ const burst = Math.round((0.08 + rnd() * 0.3) * SR);
+ const amp = rnd() < 0.2 ? 0 : 0.2 + rnd();
+ for (let k = 0; k < burst && i < out.length; k += 1, i += 1) out[i] = amp * (rnd() * 2 - 1);
+ }
+ return out;
+}
+
+function concat(...parts: Float32Array[]): Float32Array {
+ const out = new Float32Array(parts.reduce((n, p) => n + p.length, 0));
+ let o = 0;
+ for (const p of parts) {
+ out.set(p, o);
+ o += p.length;
+ }
+ return out;
+}
+
+const slice = (x: Float32Array, from: number, to: number) =>
+ x.subarray(Math.max(0, Math.round(from * SR)), Math.min(x.length, Math.round(to * SR)));
+
+// Measure every anchor the way the server does: the source probe centred on
+// `at`, the target searched ±search around it.
+function measureAll(source: Float32Array, target: Float32Array, times: number[], opts = {}) {
+ const o = { ...CLOCK_DEFAULTS, sampleRate: SR, probeSeconds: 10, searchSeconds: 20, ...opts };
+ return times.map((at) => {
+ const probe = slice(source, at - o.probeSeconds / 2, at + o.probeSeconds / 2);
+ const searchStart = Math.max(0, at - o.probeSeconds / 2 - o.searchSeconds);
+ const search = slice(target, searchStart, at + o.probeSeconds / 2 + o.searchSeconds);
+ return measureAnchor({ at, probe, search, searchStart, sampleRate: SR }, o);
+ });
+}
+
+// The 6 Nov shape: the target starts 2.5 s later, and 10.6 s of something
+// else sits in it at source second 400 — so c44-like spans before it are +2.5,
+// c45-like spans after it +13.1.
+const SOURCE = speech(900, 7);
+const TARGET = concat(speech(2.5, 99), slice(SOURCE, 0, 400), speech(10.6, 123), slice(SOURCE, 400, 900));
+
+test("locate finds an excerpt inside a longer signal to the sample", () => {
+ const probe = slice(SOURCE, 100, 110);
+ const search = slice(TARGET, 80, 140);
+ const hit = locate(probe, search, { guard: SR / 4 });
+ assert.ok(hit);
+ // SOURCE 100 is TARGET 102.5; the search starts at 80.
+ assert.equal(hit.lag, Math.round(22.5 * SR));
+ assert.ok(hit.score > 0.99, `score ${hit.score}`);
+ assert.ok(hit.second < 0.2, `second ${hit.second}`);
+});
+
+test("locate gives up on silence", () => {
+ assert.equal(locate(new Float32Array(SR * 2), slice(TARGET, 0, 10)), null);
+});
+
+test("anchors every step, plus the extra seconds, inside the probe's reach", () => {
+ const t = anchorTimes(1000, { everySeconds: 300, probeSeconds: 20, extra: [5, 512, 513] });
+ assert.deepEqual(t, [10, 150, 450, 512, 750, 990]);
+});
+
+test("a step inside the stream: two segments, a gap, refined until narrow", () => {
+ const o = { probeSeconds: 10, searchSeconds: 20, everySeconds: 120, minGapSeconds: 10 };
+ let anchors = measureAll(SOURCE, TARGET, anchorTimes(900, { ...o }), o);
+ let fit = fitClock(anchors, o);
+ assert.equal(fit.segments.length, 2);
+ assert.equal(fit.gaps.length, 1);
+ for (let pass = 0; pass < 4; pass += 1) {
+ const more = refineTimes(fit, o);
+ if (!more.length) break;
+ anchors = [...anchors, ...measureAll(SOURCE, TARGET, more, o)];
+ fit = fitClock(anchors, o);
+ }
+ assert.equal(fit.ok, true, fit.why);
+ assert.equal(fit.segments.length, 2);
+ assert.ok(Math.abs(fit.segments[0].offset - 2.5) < 0.001, `first ${fit.segments[0].offset}`);
+ assert.ok(Math.abs(fit.segments[1].offset - 13.1) < 0.001, `second ${fit.segments[1].offset}`);
+ const g = fit.gaps[0];
+ // The step is at source 400: the gap holds it, and is at most minGap plus a
+ // probe (half a probe beyond either anchor) wide.
+ assert.ok(g.from < 400 && g.to > 400, JSON.stringify(g));
+ assert.ok(g.to - g.from <= 10 + 10, JSON.stringify(g));
+ assert.ok((fit.residual.rms ?? 1) < 0.001);
+});
+
+test("a drift is one segment with a rate, and the map follows it", () => {
+ // 40 ms per hour of drift on top of +1.6 s, as two sound cards would.
+ const rate = 0.04 / 3600;
+ const anchors = [30, 330, 630, 930, 1230, 1530].map((at) => ({ at, offset: 1.6 + rate * at, ok: true }));
+ const fit = fitClock(anchors);
+ assert.equal(fit.segments.length, 1);
+ assert.ok(Math.abs(fit.segments[0].rate - rate) < 1e-9);
+ const clock = clockOf(fit);
+ assert.ok(Math.abs(clockOffsetAt(clock, 1000).offset - (1.6 + rate * 1000)) < 1e-4);
+});
+
+test("a stream that drifts 0.06 % (v6w89mk, 6 Nov) is ONE segment from its sparse first anchors", () => {
+ // Measured: 0 s at 150 s, +4.69 s at 7827 s; the first pass anchors every 300 s.
+ const rate = 6.128e-4;
+ const anchors = [150, 450, 750, 1050, 1350, 1650, 1950, 4350, 7827].map((at) => ({
+ at,
+ offset: Math.round((rate * (at - 150) + (at % 2 ? 0.02 : -0.02)) * 1e4) / 1e4,
+ ok: true,
+ }));
+ const fit = fitClock(anchors);
+ assert.equal(fit.segments.length, 1, JSON.stringify(fit.segments));
+ assert.equal(fit.ok, true, fit.why);
+ assert.ok(Math.abs(fit.segments[0].rate - rate) < 2e-5, String(fit.segments[0].rate));
+ const clock = clockOf(fit);
+ // c22's span (cue 4324.6): +2.56 s on the saved video.
+ assert.ok(Math.abs(clockOffsetAt(clock, 4324.6).offset - 2.56) < 0.05, String(clockOffsetAt(clock, 4324.6).offset));
+ // A real step still splits: 13.1 s is no drift.
+ const stepped = fitClock([...anchors.slice(0, 4), ...[2250, 2550, 2850].map((at) => ({ at, offset: 13.1 + rate * at, ok: true }))]);
+ assert.equal(stepped.segments.length, 2);
+});
+
+test("one anchor that disagrees between two that agree is an outlier, not a step", () => {
+ const anchors = [
+ { at: 100, offset: 2, ok: true },
+ { at: 400, offset: 2, ok: true },
+ { at: 700, offset: 9.7, ok: true },
+ { at: 1000, offset: 2, ok: true },
+ { at: 1300, offset: 2.01, ok: true },
+ ];
+ const fit = fitClock(anchors);
+ assert.equal(fit.segments.length, 1);
+ assert.deepEqual(fit.outliers, [700]);
+ assert.equal(fit.ok, true);
+});
+
+test("a stream that does not match is not ok, and says why", () => {
+ const other = speech(900, 4242);
+ const o = { probeSeconds: 10, searchSeconds: 20, everySeconds: 120 };
+ const anchors = measureAll(SOURCE, other, anchorTimes(900, o), o);
+ assert.ok(anchors.every((a) => !a.ok));
+ const fit = fitClock(anchors, o);
+ assert.equal(fit.ok, false);
+ assert.match(fit.why ?? "", /usable anchor|no anchor/);
+});
+
+function clockOf(fit: ReturnType<typeof fitClock>, extra: Partial<RecordingClock> = {}): RecordingClock {
+ return {
+ version: 1,
+ id: "t",
+ createdAt: "2026-11-06T00:00:00.000Z",
+ source: { file: "audio.mp3", bytes: 10 },
+ target: { file: "source-media.mp4", bytes: 20 },
+ method: "xcorr",
+ params: {},
+ anchors: [],
+ segments: fit.segments,
+ gaps: fit.gaps,
+ residual: fit.residual,
+ ok: fit.ok,
+ ...extra,
+ };
+}
+
+test("mapSpan: a span on one segment maps with its offset; across the step it is uncertain", () => {
+ const clock = clockOf({
+ segments: [
+ { from: 60, to: 395, offset: 2.5, rate: 0, n: 4, rms: 0 },
+ { from: 405, to: 840, offset: 13.1, rate: 0, n: 4, rms: 0 },
+ ],
+ gaps: [{ from: 395, to: 405 }],
+ outliers: [],
+ residual: { rms: 0, max: 0, n: 8 },
+ ok: true,
+ });
+ assert.deepEqual(mapSpan(clock, 100, 110), { from: 102.5, to: 112.5, offsetFrom: 2.5, offsetTo: 2.5, certain: true });
+ assert.deepEqual(mapSpan(clock, 600, 610), { from: 613.1, to: 623.1, offsetFrom: 13.1, offsetTo: 13.1, certain: true });
+ // Before the first anchor and after the last: the edge segment's value.
+ assert.equal(mapSpan(clock, 0, 5).certain, true);
+ assert.equal(clockOffsetAt(clock, 890).offset, 13.1);
+ // Inside the gap, or across it: not certain.
+ assert.equal(mapSpan(clock, 398, 402).certain, false);
+ assert.equal(mapSpan(clock, 390, 420).certain, false);
+ // A map that is not ok maps nothing with confidence.
+ assert.equal(mapSpan({ ...clock, ok: false }, 100, 110).certain, false);
+});
+
+test("the file's shape: coerce, matches, describe", () => {
+ const clock = clockOf({
+ segments: [{ from: 60, to: 840, offset: 13.1, rate: 0, n: 4, rms: 0.0004 }],
+ gaps: [],
+ outliers: [],
+ residual: { rms: 0.0004, max: 0.0009, n: 4 },
+ ok: true,
+ });
+ assert.deepEqual(coerceRecordingClock(JSON.parse(JSON.stringify(clock))), clock);
+ assert.equal(coerceRecordingClock({ ...clock, version: 2 }), null);
+ assert.equal(coerceRecordingClock({ ...clock, segments: [{ from: 1 }] }), null);
+ assert.equal(coerceRecordingClock(null), null);
+ assert.equal(clockMatches(clock, { sourceBytes: 10, targetBytes: 20 }), true);
+ assert.equal(clockMatches(clock, { targetBytes: 21 }), false);
+ assert.match(describeClock(clock), /^ok: \+13\.10s @60–840s; residual 0\.4 ms/);
+});
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/lib/sidecar-server.test.ts b/common/lib/sidecar-server.test.ts
@@ -40,6 +40,7 @@ import {
loadExcludeTruncatedCheck,
setExcludedFromTruncatedCheck,
} from "./excludeTruncatedCheck-server";
+import "./recordingClock-server";
import type { AvailabilityRecord } from "./availability";
import type { DownloadOutcomeRecord } from "./downloadOutcome";
import type { TranscribeOutcomeRecord } from "./transcribeOutcome";
@@ -48,7 +49,7 @@ async function scratch(): Promise<string> {
return mkdtemp(path.join(os.tmpdir(), "sidecar-"));
}
-test("every declared sidecar filename escapes SUB_FILE_RE, and all seventeen are declared", () => {
+test("every declared sidecar filename escapes SUB_FILE_RE, and all eighteen are declared", () => {
assert.deepEqual([...SIDECAR_FILENAMES].sort(), [
"ai-digest.json",
"ai-digest.overrides.json",
@@ -56,6 +57,7 @@ test("every declared sidecar filename escapes SUB_FILE_RE, and all seventeen are
"attribution.json",
"audio-integrity.json",
"availability.json",
+ "clock.json",
"diarization.json",
"do-not-clean.json",
"download-outcome.json",
diff --git a/common/lib/videoDir-server.mjs b/common/lib/videoDir-server.mjs
@@ -3,11 +3,135 @@
// (b)). Plain JS for umtool's bare-node scripts; server-only (node:fs). It
// never computes a path from the cwd: every root arrives as an argument.
-import { readFileSync, statSync } from "node:fs";
-import { readFile, stat } from "node:fs/promises";
+import { closeSync, openSync, readdirSync, readFileSync, readSync, statSync } from "node:fs";
+import { open, readdir, readFile, stat } from "node:fs/promises";
import path from "node:path";
import { channelConfigPlatform, pickVideoDirId, twitchVodDirId } from "./videoDirId.mjs";
+// ---- Rumble's two ids (lane one-clock) -----------------------------------------
+//
+// A Rumble video has two ids (AGENTS.md). yt-dlp's `id` — what the archive
+// serves, what every report and manifest cites — is the EMBED id (`v7drc5w`);
+// a channel downloaded from its page URLs names the DIRECTORY for the URL slug
+// (`v7fxp3e`, from https://rumble.com/v7fxp3e-title.html). An embed id has no
+// directory, so every fetch asked by it went to a `data/<embed>/` that did not
+// exist: no saved video found, no metadata, the URL guessed as the embed page
+// (a 403 on 6 Nov), the persist "unknown". So on a RUMBLE channel an id with
+// no directory of its own is looked up in the channel's metadata: the
+// directory whose metadata.info.json `id` is that id. The index is built once
+// per process from the head of each file (yt-dlp writes `id` first) and grows
+// by the directories it has not read when `data/` changes; an id it does not
+// know stays as it is.
+
+const RUMBLE_ID_RE = /^v[0-9a-z]{4,9}$/;
+const HEAD_BYTES = 512;
+const ID_IN_HEAD_RE = /"id"\s*:\s*"([^"]+)"/;
+
+/** @type {Map<string, { mtimeMs: number, seen: Set<string>, byId: Map<string, string> }>} */
+const rumbleIndexes = new Map();
+
+/** @param {string} head @returns {string | null} */
+function idOfHead(head) {
+ const m = ID_IN_HEAD_RE.exec(head);
+ return m ? m[1] : null;
+}
+
+/** @param {string} file */
+async function readHead(file) {
+ let fh;
+ try {
+ fh = await open(file, "r");
+ const buf = Buffer.alloc(HEAD_BYTES);
+ const { bytesRead } = await fh.read(buf, 0, HEAD_BYTES, 0);
+ return buf.subarray(0, bytesRead).toString("utf8");
+ } catch {
+ return "";
+ } finally {
+ await fh?.close().catch(() => {});
+ }
+}
+
+/** @param {string} file */
+function readHeadSync(file) {
+ let fd = -1;
+ try {
+ fd = openSync(file, "r");
+ const buf = Buffer.alloc(HEAD_BYTES);
+ const n = readSync(fd, buf, 0, HEAD_BYTES, 0);
+ return buf.subarray(0, n).toString("utf8");
+ } catch {
+ return "";
+ } finally {
+ if (fd >= 0) closeSync(fd);
+ }
+}
+
+/**
+ * The directory of a Rumble channel holding the record `id` (its embed id), or
+ * null when no directory's metadata names it.
+ * @param {string} dataDir
+ * @param {string} id
+ * @returns {Promise<string | null>}
+ */
+export async function rumbleDirIdByMetadata(dataDir, id) {
+ let st;
+ try {
+ st = await stat(dataDir);
+ } catch {
+ return null;
+ }
+ let idx = rumbleIndexes.get(dataDir);
+ if (!idx) {
+ idx = { mtimeMs: -1, seen: new Set(), byId: new Map() };
+ rumbleIndexes.set(dataDir, idx);
+ }
+ if (idx.mtimeMs !== st.mtimeMs) {
+ const names = await readdir(dataDir).catch(() => /** @type {string[]} */ ([]));
+ for (const name of names) {
+ if (idx.seen.has(name)) continue;
+ idx.seen.add(name);
+ const metaId = idOfHead(await readHead(path.join(/* turbopackIgnore: true */ dataDir, name, "metadata.info.json")));
+ if (metaId && metaId !== name && !idx.byId.has(metaId)) idx.byId.set(metaId, name);
+ }
+ idx.mtimeMs = st.mtimeMs;
+ }
+ return idx.byId.get(id) ?? null;
+}
+
+/**
+ * `rumbleDirIdByMetadata`, synchronously.
+ * @param {string} dataDir
+ * @param {string} id
+ * @returns {string | null}
+ */
+export function rumbleDirIdByMetadataSync(dataDir, id) {
+ let st;
+ try {
+ st = statSync(dataDir);
+ } catch {
+ return null;
+ }
+ let idx = rumbleIndexes.get(dataDir);
+ if (!idx) {
+ idx = { mtimeMs: -1, seen: new Set(), byId: new Map() };
+ rumbleIndexes.set(dataDir, idx);
+ }
+ if (idx.mtimeMs !== st.mtimeMs) {
+ let names = /** @type {string[]} */ ([]);
+ try {
+ names = readdirSync(dataDir);
+ } catch {}
+ for (const name of names) {
+ if (idx.seen.has(name)) continue;
+ idx.seen.add(name);
+ const metaId = idOfHead(readHeadSync(path.join(/* turbopackIgnore: true */ dataDir, name, "metadata.info.json")));
+ if (metaId && metaId !== name && !idx.byId.has(metaId)) idx.byId.set(metaId, name);
+ }
+ idx.mtimeMs = st.mtimeMs;
+ }
+ return idx.byId.get(id) ?? null;
+}
+
/** @param {string} p */
async function isDir(p) {
try {
@@ -36,8 +160,10 @@ export async function readChannelPlatform(channelsDir, slug) {
/**
* The directory id a record lives in, on this disk. Only a `v<digits>` id
- * costs a read (the channel's config when no platform is given, and two
- * stats); every other id is returned as it is.
+ * (Twitch) or a Rumble-shaped `v<5-10 of a-z0-9>` id costs a read (the
+ * channel's config when no platform is given, then stats; a Rumble embed id
+ * with no directory, the channel's metadata index); every other id is returned
+ * as it is.
* @param {string} channelsDir
* @param {string} slug
* @param {string} recordId
@@ -46,9 +172,15 @@ export async function readChannelPlatform(channelsDir, slug) {
* @returns {Promise<string>}
*/
export async function resolveVideoDirId(channelsDir, slug, recordId, opts = {}) {
- if (twitchVodDirId(recordId) === null) return recordId;
+ const rumbleShaped = RUMBLE_ID_RE.test(recordId);
+ if (twitchVodDirId(recordId) === null && !rumbleShaped) return recordId;
const platform = opts.platform !== undefined ? opts.platform : await readChannelPlatform(channelsDir, slug);
- if (platform !== "twitch") return recordId;
+ if (platform === "rumble" && rumbleShaped) {
+ const dataDir = path.join(/* turbopackIgnore: true */ channelsDir, slug, "data");
+ if (await isDir(path.join(/* turbopackIgnore: true */ dataDir, recordId))) return recordId;
+ return (await rumbleDirIdByMetadata(dataDir, recordId)) ?? recordId;
+ }
+ if (platform !== "twitch" || twitchVodDirId(recordId) === null) return recordId;
const dataDir = path.join(/* turbopackIgnore: true */ channelsDir, slug, "data");
const n = /** @type {string} */ (twitchVodDirId(recordId));
const [hasN, hasV] = await Promise.all([
@@ -97,7 +229,8 @@ function isDirSync(p) {
* @returns {string}
*/
export function resolveVideoDirIdSync(channelsDir, slug, recordId, opts = {}) {
- if (twitchVodDirId(recordId) === null) return recordId;
+ const rumbleShaped = RUMBLE_ID_RE.test(recordId);
+ if (twitchVodDirId(recordId) === null && !rumbleShaped) return recordId;
let platform = opts.platform;
if (platform === undefined) {
try {
@@ -108,7 +241,12 @@ export function resolveVideoDirIdSync(channelsDir, slug, recordId, opts = {}) {
platform = null;
}
}
- if (platform !== "twitch") return recordId;
+ if (platform === "rumble" && rumbleShaped) {
+ const dataDir = path.join(/* turbopackIgnore: true */ channelsDir, slug, "data");
+ if (isDirSync(path.join(/* turbopackIgnore: true */ dataDir, recordId))) return recordId;
+ return rumbleDirIdByMetadataSync(dataDir, recordId) ?? recordId;
+ }
+ if (platform !== "twitch" || twitchVodDirId(recordId) === null) return recordId;
const dataDir = path.join(/* turbopackIgnore: true */ channelsDir, slug, "data");
return pickVideoDirId(recordId, {
platform,
diff --git a/common/lib/videoDirId.test.ts b/common/lib/videoDirId.test.ts
@@ -113,3 +113,36 @@ test("the synchronous resolver gives the same answers (release 23 F1b)", () => {
const yt = channel("yt-sync", { handling: "youtube", platform: "youtube" }, [N]);
assert.equal(resolveVideoDirIdSync(yt, "yt-sync", `v${N}`), `v${N}`);
});
+
+// RUMBLE'S TWO IDS (lane one-clock): a manifest cites the EMBED id, the
+// directory is named for the URL slug; on a Rumble channel the embed id is
+// found through the directory's metadata.info.json `id`.
+test("a Rumble embed id resolves to the URL-slug directory whose metadata names it", async () => {
+ const root = mkdtempSync(path.join(tmpdir(), "rumble-ids-"));
+ try {
+ const data = path.join(root, "rc", "data");
+ mkdirSync(path.join(data, "v7fxp3e"), { recursive: true });
+ writeFileSync(path.join(root, "rc", "config.json"), JSON.stringify({ platform: "rumble", url: "https://rumble.com/c/X" }));
+ writeFileSync(
+ path.join(data, "v7fxp3e", "metadata.info.json"),
+ JSON.stringify({ id: "v7drc5w", title: "t", webpage_url: "https://rumble.com/v7fxp3e-t.html" }),
+ );
+ assert.equal(await resolveVideoDirId(root, "rc", "v7drc5w"), "v7fxp3e");
+ assert.equal(resolveVideoDirIdSync(root, "rc", "v7drc5w"), "v7fxp3e");
+ assert.equal(await resolveVideoDir(root, "rc", "v7drc5w"), path.join(data, "v7fxp3e"));
+ // The slug id is its own directory; an id nobody names stays as it is.
+ assert.equal(await resolveVideoDirId(root, "rc", "v7fxp3e"), "v7fxp3e");
+ assert.equal(await resolveVideoDirId(root, "rc", "v9zzzzz"), "v9zzzzz");
+ // A directory added later is found once data/ changes.
+ mkdirSync(path.join(data, "v7gwn3w"));
+ writeFileSync(path.join(data, "v7gwn3w", "metadata.info.json"), JSON.stringify({ id: "v7eqa6e" }));
+ assert.equal(await resolveVideoDirId(root, "rc", "v7eqa6e"), "v7gwn3w");
+ assert.equal(resolveVideoDirIdSync(root, "rc", "v7eqa6e"), "v7gwn3w");
+ // Not a Rumble channel: never guessed at.
+ writeFileSync(path.join(root, "rc", "config.json"), JSON.stringify({ platform: "youtube" }));
+ assert.equal(await resolveVideoDirId(root, "rc", "v7drc5w"), "v7drc5w");
+ assert.equal(await resolveVideoDirId(root, "rc", "v7drc5w", { platform: "rumble" }), "v7fxp3e");
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
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/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -2,6 +2,7 @@
## [Unreleased]
- **umtool: each character has a voice, auditioned on a page, the same in every project.** The operator wanted to "pick different voices for different characters, and in UI alone be able to try rendering different ones to compare … and try to maintain consistent voices for different repeating characters" -- tonight TheQuartering's reads were re-voiced by hand after scoring five voices against his real one. `/projects/<p>/voices` (from the Cut tab's Reads and voices) lists every character a project's reads use, the voice each reads in now and where it comes from (the cast, the project, the narrator's, the default), its reads in another voice, and its real voice. **Audition** reads one line (its own words here, a stock line, or typed) in 2-6 stock voices -- a job: the editor's tts, then each one's closeness to the real voice (speakers.json, TitaNet, local) -- played side by side at one loudness beside the real voice, a reference never a target. **Use for this project** or **Use everywhere** (the cast, `<reports>/.umtool/cast.json`), then the items to re-read, queued. A recording of an item can be made a character's read: kept, cleaned, converted to its stock voice. Every read -- a single post's and each piece of a thread read -- asks the same order (the read's own, the project's map, the cast, the narrator's, the default), and a cast voice of another engine is synthesized by it. `umtool cast ls|add|set|rm|undo|project|audition|use|reread`, `posts narrate … --recording`, and `umtool lint` warns when a cast character is read in another voice.
+- **Rumble clips play the words their quotes say: one clock per recording.** On 6 Nov seven Rumble clips of the weight video played other words than their quotes, c43 13.1 seconds early (the "310" clip), and one stream was right at 10 minutes and 13.6 seconds off at 38. A Rumble channel's transcript is made from a separate audio download, and its clips were cut from another file; the two do not keep the same time, and not by a constant. The operator: "stop trying to grab rumble individual clips and instead grab whole streams and clip after." **Whole, never seeked:** umtool's fetch (the bench's fetch more, `umtool fetch`, a build's fetch) asks for a Rumble clip through Fetch windows, which saves the stream once and cuts the clip from it; nothing falls back to a seek, and a failed save says why. **The right video:** a report cites a Rumble video by its embed id while the archive keeps it under its page's id; every fetch, save and render now finds the video under either (6 Nov: every such fetch went to a folder that did not exist, and one got a Rumble 403). **The time map:** before a clip is cut from a saved Rumble stream, the stream's audio is matched against the audio the transcript was made from, every 5 minutes and around each clip, and the map (`clock.json` beside the video, with how well it fits) moves every cut onto the transcript's time; clips cut before the map, or by a seek, are cut again. A stretch where the two files part (a dropped piece of the stream) is narrowed to a few seconds, and a clip on it is said to be uncertain. **The check:** `umtool quote-check <project>` has the editor transcribe what each clip will actually play and finds the quote in it: `moved` (heard seconds away), `not-found`, or `ok`; `umtool window <p> <clip> --align` puts the cut on the words as heard, `umtool check` blocks on a moved or missing quote, a take refuses one unless a person rules it (`--quote-ruled`), and `umtool prep --status` counts them. Needs a restart of the editor (umtool's half works at once).
- **umtool: a counter series nobody counted shows 0, and a text card can count.** The Leaflit side-tally video has no title or totals cards, so the deck's counter is the only place the counts show, and it left out "Left" (the point of the video: she never once says she is on the left) because the tally drew only the series some mark used. A series of `deck.counter` that says `showAt: "always"` (its own, or the counter's) is now a cell from the first frame, dim at 0, whether or not anything counts it; a series that says nothing (so a counter `umtool migrate` wrote draws what it drew), a `first` series, and the fact-check verdicts' tally of a cut without a `deck.counter` are as before, and a cut that counts nothing still draws no counter. Her two X posts are text cards (`teaser`s), which could not carry a mark, so they did not step the count. A teaser now takes marks as a clip does (`umtool set <p> x-d28 mark.add=CENTER@2.15`, the second counted from the card's start; validated, stamped over the card, counted, in Play and the On-screen table), and a teaser that carries one keeps the deck up over it, with no title of its own, so the count is seen to step. A teaser that dips still hides the deck at the black.
- **Free disk, weekly, with one command: `archilyzer housekeeping`.** On 6 Nov /home was at 37 GB free, and a session freed 83 GB by hand. The operator: "We should build a regularly run command for this after we're done." It runs three passes of the apps' own commands. **Superseded takes:** `umtool prune --versions` deletes whole takes through `umtool takes delete`. Per version line it keeps the highest built number; the line is the take id with its digits folded (`draft-3` and `draft-4`), and a letter is never folded (`v6c` is not `v6d`, `release-6u` is not `release-6`). An older take goes only once the newer one is 7 days old (`--grace`). It also keeps any take picked, pinned, given any verdict, rendering, a build's base, the manifest's, with operator notes on it, or refused by `takes delete`, and skips a project whose verdicts file cannot be read. **Work files:** every project's takes' work files by its prune policy; in a project idle 3 days, the newest and picked takes' work goes too (`--idle-work`). **Worktrees:** `pnpm wt prune` removes merged, clean, idle worktrees with no process in them and no ignored files of anyone's (a corpus, an env file, a changed settings file, a nested repository), keeping their branches. A project or worktree touched in the last 3 days is left alone, and a run is skipped while a render, an e2e suite or a heavy job runs, or when that cannot be checked. Each run is recorded in `~/.local/state/archilyzer/housekeeping.json`. **Worktree ports no longer move:** a worktree's port block is recorded when it is added, so removing another worktree cannot shift a running suite's ports. **Upgrading:** `archilyzer service install` (host mode) now also installs `archilyzer-housekeeping.timer`, weekly; `--dry-run` shows it first, and `--no-housekeeping` leaves it out. OPERATING.md, "Free disk".
- **Sync new and Resume backfill are separate actions for an X or Bluesky channel.** A fetch meant to get new posts could walk old history instead. If an account's full-history walk had stopped part-way, the next plain fetch, from Sync or the schedule too, resumed that walk and skipped the newest posts. On 6 Nov one such fetch read 100 posts the archive already held, stopped as "caught up" with 0 new, and missed 85 newer posts. It then cleared the walk's saved place, so the place was lost as well. The operator: "We should have distinct 'sync new' and 'resume backfill' actions, they are different actions for different purposes". **Sync new** (the channel page's first button; a plain `fetch-posts`, Sync and the scheduler) now always reads from the newest post down to the newest one archived, and never moves or clears the backfill's place. A sync that stops part-way keeps its own place and finishes on the next sync. **Resume backfill** (the button, shown only when a full-history walk is unfinished; `pnpm ops resume-backfill`, or `fetch-posts "backfill": true`; `--backfill` on `archilyzer posts fetch`; `backfill` on the MCP enqueue tool) continues that walk and does nothing else. When one is unfinished, the channel page says so: "backfill unfinished — N archived; Resume backfill continues it". The job log's first line names the mode. Resume backfill is refused when no walk is unfinished, and on a forum thread, which already reads its newest pages before its history. An X search channel has one walk and refuses it too. Re-fetch full history and Fetch older posts are unchanged. **Upgrading:** a `posts-state.json` from before this keeps one `cursor`. It is read as the unfinished backfill's place, so nothing is lost, and the next fetch rewrites it. Needs a restart of the editor.
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -115,7 +115,7 @@ import {
type StoredUrlWhy,
} from "yt-dlp-transcript-common/lib/storedMediaUrl";
import { storedMediaUrl } from "yt-dlp-transcript-common/lib/storedMediaUrl-server";
-import { CLIP_WINDOW_MIN_GAP_SECONDS } from "yt-dlp-transcript-common/controller/fetchWindows";
+import { CLIP_WINDOW_MIN_GAP_SECONDS, wholeRecordingFor } from "yt-dlp-transcript-common/controller/fetchWindows";
import { probeVideoHeight } from "yt-dlp-transcript-common/ytdlp/ffprobeDuration";
import { detectPlatform } from "yt-dlp-transcript-common/lib/platform";
import { channelConfigPlatform } from "yt-dlp-transcript-common/lib/videoId";
@@ -127,6 +127,7 @@ import {
recordDownloadBackoff,
} from "yt-dlp-transcript-common/jobs/downloadBackoff";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { heldWindowOnClock } from "yt-dlp-transcript-common/lib/recordingClock-server";
import { resolveCookiePolicy } from "yt-dlp-transcript-common/lib/cookiePolicy";
import {
downloadOneManaged,
@@ -1600,7 +1601,15 @@ export async function fetchWindowAction(req: {
const { hit } = await findInSyncContainingClipWindow(videoDir, from, to, {
probe: ffprobeWindowProbe(paths.ffprobeBin),
});
- if (hit) {
+ // ONE CLOCK PER RECORDING (controller/fetchWindows.ts): a whole-recording
+ // channel's held window answers only when cut through the video's current
+ // time map; an off-clock one is passed over (the next fetch-windows run
+ // retires it) and the span is cut from the saved container below.
+ const clocked =
+ hit &&
+ wholeRecordingFor(getSettings(), channelConfigPlatform(r.config) ?? "", {}, undefined) &&
+ !(await heldWindowOnClock(videoDir, hit.provenance));
+ if (hit && !clocked) {
// The window's own height, read off its header: a window holds seconds,
// so the probe is quick, and it is the only record of how tall a window
// fetched under an earlier cap is.
diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts
@@ -24,6 +24,7 @@ import {
} from "yt-dlp-transcript-common/lib/clipWindowSync-server";
import { sourceGoneState } from "yt-dlp-transcript-common/lib/sourceGone-server";
import { savedWindowSource } from "yt-dlp-transcript-common/lib/savedVideoWindow-server";
+import { heldWindowOnClock } from "yt-dlp-transcript-common/lib/recordingClock-server";
import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig";
import {
isValidChannelSlug,
@@ -229,7 +230,12 @@ async function planFetchWindows(
probe: ffprobeWindowProbe(paths.ffprobeBin),
setAside: false,
});
- if (held.hit) {
+ // ONE CLOCK PER RECORDING (controller/fetchWindows.ts): a whole-recording
+ // channel's held window answers only when it was cut through the video's
+ // current time map; otherwise the span goes on (to the saved container,
+ // whose job measures the map and retires the off-clock window).
+ const clockedChannel = wholeRecordingFor(settings, channelConfigPlatform(config) ?? "", item, wholeRecording);
+ if (held.hit && (!clockedChannel || (await heldWindowOnClock(videoDir, held.hit.provenance)))) {
cached.push(item);
continue;
}
diff --git a/umtool/app/api/report/fetch-windows/route.ts b/umtool/app/api/report/fetch-windows/route.ts
@@ -75,7 +75,7 @@ export async function POST(request: Request) {
if (action !== "dry-run" && action !== "start") {
return Response.json({ error: 'action must be "dry-run", "start" or "follow"' }, { status: 400, headers });
}
- const { body, skipped } = await projectFetchBody(project);
+ const { body, skipped } = await projectFetchBody(project, { localIds: true });
if (!body.items.length) return Response.json({ error: "no clip windows to fetch" }, { status: 400, headers });
const answer = await postFetchWindows(cfg, body, { dryRun: action === "dry-run" });
const run = await recordFetchRun(project.dir, { body, answer });
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -17,6 +17,7 @@
// umtool links <project> [--json] [--fix] do the clip QRs open on their sites (out/links.json)
// umtool cast [ls|add|set|rm|undo|project|audition|use|reread] … the characters' voices across projects (castCli.mjs)
// umtool speaker-check <project> [--clip <id> …] [--set 'Name=…'] [--list] which named voice each clip is (speaker-check.json)
+// umtool quote-check <project> [--clips a,b] [--status] is each clip's quote in the seconds it plays (quote-check.json)
// umtool check-joins <project> --take <id> [--json] [--all] do the post joins of a rendered take carry on, or jump
// umtool link-policy <project> [--via <site>] [--direct a,b] [--clear] [--fix] cite via site X; these channels direct
// umtool decisions [--json]
@@ -29,6 +30,7 @@
// [--correction TEXT] [--verdict confirmed|incorrect|'']
// [--reject not-matching|wrong-speaker|irrelevant|repeats|weak|privacy|other [--note TEXT]]
// [--cut-start S] [--cut-end E] [--lock-cut] the cut inside the extent
+// [--align] the cut snapped to the quote as heard (quote-check.json); [--quote-ruled]
// [--gap FROM-TO]… [--gap-remove S] [--gaps 'A-B,C-D' | ''] seconds cut out of its middle
// [--take <id>] a take's clip: the edit goes into the take's patch (walk a take)
// umtool walk <project> [--take <id>] [--all] [--json] the walk: clips in walk order, verdicts, fetched
@@ -871,6 +873,10 @@ function usage() {
" project's characters and their drift, an audition of candidate voices (scored against the real voice)",
" umtool speaker-check <project> [--clip <id> …] [--json] which of the project's named voices (speakers.json) each",
" clip is: TitaNet-small, local -> speaker-check.json; --set 'Name=<clip>,<channel>/<id>,channel:<slug>' / --remove / --list",
+ " umtool quote-check <project> [--clips a,b] [--pad S] [--json] | --status is each clip's quote in the seconds it plays?",
+ " the cut ±15 s of the source the render would use, transcribed by the editor (words on), the quote",
+ " found in it and in the cues: ok | moved (heard N s away: window --align) | not-found -> quote-check.json;",
+ " check calls moved and not-found blocking, and a take refuses them unless the clip is --quote-ruled",
" umtool check-joins <project> --take <id> [--json] [--all] [--limit <n>] every boundary of the take's master where the",
" next post item draws a post the one before showed: its join, the SSIM across it, the largest jump",
" umtool link-policy <project> [--via <site id|url>] [--direct a,b] [--clear] [--fix] [--json] the link policy",
@@ -899,6 +905,9 @@ function usage() {
" takes it out, on record): not-matching|wrong-speaker (fact errors: incorrect, the note its",
" correction) or irrelevant|repeats|weak|privacy|other (rejected; other needs --note)",
" --cut-start S --cut-end E --lock-cut the cut the video renders",
+ " --align the cut snapped to the quote as HEARD (quote-check.json: a breath before its first word,",
+ " its last let ring; the extent widened to hold it; lockCut kept) -- the per-clip fix for a moved quote",
+ " --quote-ruled / --no-quote-ruled a person heard it and rules the quote check's verdict: a take renders it",
" --move-stamp first|nearest|<s> | --clear-stamp with --start/--end: a stamp's second (claim.at,",
" a mark's at) the new window would leave outside moves to the first second that plays, the nearest,",
" or <s>, or loses its at -- in the same write; --move-mute nearest | --clear-mute the mute mark's",
@@ -1184,6 +1193,8 @@ const COMMANDS = {
cast: async () => process.exit(await (await import("../lib/report/castCli.mjs")).castCommand(argv.slice(argv.indexOf("cast") + 1))),
// Which named voice each clip is (UI notes #15): lib/report/speakerCheck.mjs.
"speaker-check": async () => process.exit(await (await import("../lib/report/speakerCheck.mjs")).speakerCheckCommand(argv.slice(argv.indexOf("speaker-check") + 1))),
+ // Is each clip's quote in the seconds it plays (lane one-clock): the editor transcribes, quote-check.json keeps the rows.
+ "quote-check": async () => process.exit(await (await import("../lib/report/quoteCheck.mjs")).quoteCheckCommand(argv.slice(argv.indexOf("quote-check") + 1))),
// Do a rendered take's post joins carry on (operator, 4 Nov, mid-7): lib/report/checkJoinsCli.mjs.
"check-joins": async () => process.exit(await (await import("../lib/report/checkJoinsCli.mjs")).checkJoinsCommand(argv.slice(argv.indexOf("check-joins") + 1))),
// The project's link policy (UI notes #10): lib/report/linksCli.mjs.
@@ -1290,6 +1301,8 @@ async function cmdWindow() {
["--lock-cut", "lockCut"],
// The walk's favourite: a trailer candidate (lib/report/trailerCandidates.mjs).
["--star", "star"],
+ // A person heard it: the quote check's verdict is ruled (lib/report/quoteCheck.mjs quoteGate).
+ ["--quote-ruled", "quoteRuled"],
]) {
if (has(flag)) patch[key] = true;
if (has(`--no-${flag.slice(2)}`)) patch[key] = false;
@@ -1369,6 +1382,28 @@ async function cmdWindow() {
die(e?.message ?? String(e));
}
}
+ // --align: the cut snapped to the quote as HEARD by the quote check
+ // (lib/report/quoteCheck.mjs alignPatch), from the clip as the project's
+ // manifest (or the take's) holds it now.
+ if (has("--align")) {
+ if (patch.cutStart !== undefined || patch.cutEnd !== undefined) die("--align sets the cut; give it or --cut-start/--cut-end, not both");
+ const { alignPatch, readQuoteCheck } = await import("../lib/report/quoteCheck.mjs");
+ const doc = await readQuoteCheck(p.dir);
+ let entry = null;
+ if (val("--take") !== undefined) {
+ const { resolveTakeManifest } = await import("../lib/report/takeManifest.mjs");
+ entry = ((await resolveTakeManifest(p.dir, val("--take"))).manifest.timeline ?? []).find((e) => e.id === clipId) ?? null;
+ } else {
+ const { readManifest } = await import("../lib/projects/report.mjs");
+ entry = ((await readManifest(p.dir))?.timeline ?? []).find((e) => e.id === clipId) ?? null;
+ }
+ if (!entry) die(`no clip ${clipId}`);
+ try {
+ Object.assign(patch, alignPatch(entry, doc.clips[clipId]));
+ } catch (e) {
+ die(e?.message ?? String(e));
+ }
+ }
if (!Object.keys(patch).length) die("nothing to change");
// --take <id>: the clip is the TAKE's (walk a take), and the edit goes into
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -30,6 +30,8 @@ Inbox cannot disagree about what is wrong with one.
| `links <project> [--json] [--fix]` | do the clip QRs open on their sites? `corpus.json` → the channel's manifest → `slugToPage` → the shard's record, one request at a time, shards from the cue cache; recorded in `out/links.json`, which `check` reads (`link-dead` blocking, `links-unverified`, `links-unchecked`); `--fix` rewrites a Twitch id the site serves as `v<id>`; **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)). The same record dates each site's deploy: a cited video newer than it is `site-deploy-behind` ([knobs.md](knobs.md#the-sites-the-links-depend-on)) |
| `link-policy <project> [--via <site id \| https://…>] [--direct <slug,…>] [--clear] [--fix] [--json]` | the project's **link policy** (`provenance.linkPolicy`): cite via site X, these channels direct. With no flag, prints it and every clip whose QR breaks it; `--fix` rewrites each one that has a fix through the window writer; new clips are written by it. **Exit 1** when a clip still breaks it ([knobs.md](knobs.md#the-link-policy)) |
| `patch-markers <project> [<file>.patch.json] [--fix] [--json]` | take patches whose deck markers name a clip not in the cut (a take made with one is refused); `--fix` gives each the `after` of the cut's marker of the same label; **exit 1** when one is left ([knobs.md](knobs.md#take-patches-follow-a-removal)) |
+| `quote-check <project> [--clips a,b] [--pad S] [--json]` · `quote-check <project> --status` | **is each clip's quote in the seconds it plays?** The cut ±15 s of the source the render would cut it from, transcribed by the editor (`pnpm ops transcribe`, words on — its transcription lane), the quote found in those words and in the cues: `ok`, `moved` (heard more than 0.5 s from where the cues have it), `not-found`; rows in `quote-check.json`, stale when the cut or the quote changes; `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays)) |
+| `window <project> <clip> --align` · `--quote-ruled` / `--no-quote-ruled` | the cut snapped to the quote as HEARD (0.15 s before its first word, 0.3 s after its last, the extent widened to hold it, `lockCut`); a person's ruling on the quote check (a take renders a ruled clip) |
| `window <project> <clip> --take <take> …` | a **take's** clip (walk a take): the same fields, written into the take's patch (`takes/<take>/take.json`) with an undo point first; the project's manifest is untouched ([clip-bench.md](clip-bench.md#walking-a-take)) |
| `walk <project> [--take <take>] [--all] [--json]` | the clip bench's **walk**: every clip in walk order with its window, verdict and whether a fetched file holds it, and (→) the ones the walk visits — fetched and needing a verdict; `--all` every fetched one; `--take` walks a take (a draft too); the bench's address to start at |
| `link <project> <site>/<report>` · `link <project> --clear` | the manifest names the article it is the video of (settles `link-ambiguous`) |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -99,6 +99,35 @@ the cut is the check's `patch-markers-stale` row (open: a take made with it is r
cut's markers** (`umtool patch-markers <p> [<file>] --fix`): each such marker takes the `after` of the
cut's marker with the same label; one no marker of the cut shares a label with is left, and named.
+## The quote check (is the quote where the clip plays?)
+
+A clip's seconds are its CUES' seconds, and its picture and sound are cut from another file: on 6 Nov
+seven Rumble clips of quartering-diet played other words than their quotes (c43 13.1 s early: the "310"
+misclip), and only listening caught it. `umtool quote-check <p> [--clips a,b]` listens instead: each
+clip's cut ±15 s (`--pad`) of the source the render would use is transcribed by the editor (its
+transcription lane, words on), and the quote is found in those words — numbers one token however they
+are written, a word one letter off still a match, an ellipsis splitting it into fragments found in
+order — and in the recording's cues. The rows (`quote-check.json`, one per clip, with the cut, the
+quote and the source judged):
+
+| row | means | what settles it |
+|---|---|---|
+| `ok` | heard within 0.5 s of where the cues have it | — |
+| `moved` | heard N s away (with no cues: heard outside the cut) | `umtool window <p> <clip> --align` — the cut on the words as heard (0.15 s before the first, 0.3 s after the last, the extent widened, `lockCut`); or fetch it again (`umtool fetch <p> --refetch <clip>`: a Rumble clip comes from the saved whole recording through its clock) |
+| `not-found` | not in the seconds checked | the refetch, a new quote, or `--quote-ruled` |
+| `no-window` | nothing on disk holds the cut | `umtool fetch <p>` |
+
+A row is about the clip as it was: a cut or a quote changed since makes it stale, and it says nothing
+until checked again (`prep --status` counts the stale ones). `umtool check` calls a current `moved` or
+`not-found` BLOCKING (`clip-quote-moved`, `clip-quote-missing`, with the fix), and a take refuses the
+clip like an incorrect one — unless a person heard it and ruled: `umtool window <p> <clip>
+--quote-ruled` (`quoteRuled` on the clip; `--no-quote-ruled` clears it).
+
+The recording's own clock is the editor's (AGENTS.md, "Two FILES of one recording disagree too"): a
+Rumble window is cut from the saved whole recording through `data/<id>/clock.json`, so a clip fetched
+since reads `ok`; the check is what catches a span on a step of that map, a map that could not be
+fitted, and the windows fetched before it.
+
## Do the QR links open?
`umtool links <p> [--json] [--fix]`, or **Check links** on the project page's link rows, resolves every
diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs
@@ -1068,6 +1068,13 @@ export const REPORT_DECISION_KINDS = [
// would count its marks, and the video would cite a clip somebody already
// said is wrong. Remove it, fix it and re-confirm, or clear the verdict.
"clip-incorrect",
+ // The QUOTE CHECK (lib/report/quoteCheck.mjs, lane one-clock): a clip whose
+ // quote is not heard in the seconds it plays, or heard seconds away from its
+ // cut. BLOCKING: the video would put the quote's words on screen over other
+ // words (6 Nov: c43 played 13 s early). Fixed by `umtool window --align`, a
+ // refetch, or ruled by a person (`--quote-ruled`).
+ "clip-quote-missing",
+ "clip-quote-moved",
// A clip REJECTED for a cut reason (irrelevant, repeats, weak, privacy,
// other -- not a fact error) that is still in the timeline. `open`, not
// blocking: the report is right, and Play the cut already skips it; the
@@ -1423,6 +1430,21 @@ export async function reportDecisions(ctx, summary) {
for (const e of incorrectClips(clips)) {
add("clip-incorrect", e.id, incorrectWhy(e), "blocking", { href: clipHref(e.id) });
}
+ // A CLIP WHOSE QUOTE IS NOT WHERE IT PLAYS (the quote check's rows, when
+ // there are any; a stale row -- the cut or the quote changed since -- says
+ // nothing).
+ {
+ const { quoteGate, readQuoteCheck } = await import("../report/quoteCheck.mjs");
+ for (const g of quoteGate(clips, await readQuoteCheck(dir))) {
+ const moved = g.status === "moved";
+ add(moved ? "clip-quote-moved" : "clip-quote-missing", g.id, g.why.replace("<p>", id), "blocking", {
+ href: clipHref(g.id),
+ fix: moved
+ ? `umtool window ${id} ${g.id} --align # or --quote-ruled, having heard it`
+ : `umtool fetch ${id} --refetch ${g.id} && umtool quote-check ${id} --clips ${g.id} # or --quote-ruled, having heard it`,
+ });
+ }
+ }
// A clip rejected (irrelevant, weak, …) but kept in place: open, never blocking.
for (const e of rejectedClips(clips)) {
add("clip-rejected", e.id, rejectedWhy(e, id), "open", { href: clipHref(e.id) });
diff --git a/umtool/lib/report/fetchCli.mjs b/umtool/lib/report/fetchCli.mjs
@@ -140,7 +140,7 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con
let fetched;
try {
- fetched = await projectFetchBody(project, { reason, take });
+ fetched = await projectFetchBody(project, { reason, take, localIds: true });
} catch (e) {
if (take) throw new CliError(`${project.id}: ${e instanceof Error ? e.message : String(e)}`);
throw e;
@@ -154,12 +154,23 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con
out(`${who}: no clip windows to fetch${skipped.length ? ` (${skipped.length} skipped)` : ""}`);
return 0;
}
+ if (fetched.mapped?.length && !json) {
+ const { mappedLine } = await import("umtool-report-to-video/recording-ids");
+ out(`${who}: asked by directory id: ${mappedLine(fetched.mapped)}`);
+ }
const dryRun = args.includes("--dry-run");
// A REFETCH EVICTS FIRST, and waits: the fetch takes a cache hit before
// anything else, so it must not be asked until the eviction has ended.
let refetch = null;
if (refetchClips.length || refetchVideos.length) {
- const plan = refetchEvictions(body, skipped, { clipIds: refetchClips, videos: refetchVideos });
+ // A video named by its cited id (a Rumble embed id) is the directory the body asks for.
+ const { localVideoId } = await import("umtool-report-to-video/recording-ids");
+ const videos = [];
+ for (const v of refetchVideos) {
+ const at = String(v).indexOf("/");
+ videos.push(at > 0 ? `${v.slice(0, at)}/${await localVideoId({ slug: v.slice(0, at), id: v.slice(at + 1) })}` : v);
+ }
+ const plan = refetchEvictions(body, skipped, { clipIds: refetchClips, videos });
if (!plan.ok) throw new CliError(plan.error);
refetch = [];
for (const req of plan.requests) {
diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs
@@ -177,10 +177,15 @@ export function bodyHash(body) {
* patch, not the cut) is asked for, and a DRAFT take needs no render first.
* The body names takes/<id>/take.json as the manifest it came from.
*
+ * `localIds` (what is POSTED, never what a page shows): each item's id is the
+ * DIRECTORY id the corpus keeps the recording under -- a Rumble embed id, which
+ * the manifest cites, becomes its URL slug's directory (recording-ids.mjs) --
+ * and `mapped` lists the ids that changed.
+ *
* @param {{ id: string, dir: string }} project
- * @param {{ reason?: string | null, take?: string | null }} [opts]
+ * @param {{ reason?: string | null, take?: string | null, localIds?: boolean }} [opts]
*/
-export async function projectFetchBody(project, { reason = null, take = null } = {}) {
+export async function projectFetchBody(project, { reason = null, take = null, localIds = false } = {}) {
let manifestPath = path.join(project.dir, MANIFEST_FILE);
let manifest;
if (take) {
@@ -191,7 +196,11 @@ export async function projectFetchBody(project, { reason = null, take = null } =
manifest = JSON.parse(await readFile(manifestPath, "utf8"));
}
const rulings = await readMontageRulings(project.dir);
- return { manifest, manifestPath, ...fetchWindowsBody(manifest, { manifestPath, project: project.id, rulings, reason }) };
+ const built = fetchWindowsBody(manifest, { manifestPath, project: project.id, rulings, reason });
+ if (!localIds) return { manifest, manifestPath, ...built, mapped: [] };
+ const { withLocalIds } = await import("umtool-report-to-video/recording-ids");
+ const local = await withLocalIds(built.body.items);
+ return { manifest, manifestPath, ...built, body: { ...built.body, items: local.items }, mapped: local.mapped };
}
// ---------------------------------------------------------------------------
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -244,7 +244,9 @@ function keptSecondNear(entry, at) {
}
const WINDOW_FIELDS = ["start", "end"];
-const FLAG_FIELDS = ["lock", "lockStart", "lockEnd", "lockCut"];
+// `quoteRuled` (lane one-clock): a person heard the clip and rules the quote
+// check's verdict (lib/report/quoteCheck.mjs quoteGate) -- a flag like the locks.
+const FLAG_FIELDS = ["lock", "lockStart", "lockEnd", "lockCut", "quoteRuled"];
/** Same tolerance the resolver and the build use for a stored 2 dp edge. */
const WIN_EPS = 0.02;
diff --git a/umtool/lib/report/prepCli.mjs b/umtool/lib/report/prepCli.mjs
@@ -51,6 +51,33 @@ export function stateLine(s) {
const stamp = () => new Date().toISOString().slice(11, 19);
+/**
+ * The quote check's verdicts on the project's clips as they are now (lane
+ * one-clock, quoteCheck.mjs): "quotes: 40 ok, 2 moved (c43, c45), 1 not found
+ * (c19) — umtool window <p> <clip> --align"; null with no check on record.
+ * @param {string} dir
+ */
+export async function quoteLine(dir) {
+ const [{ readQuoteCheck, rowIsCurrent }, { readManifest }] = await Promise.all([import("./quoteCheck.mjs"), import("../projects/report.mjs")]);
+ const doc = await readQuoteCheck(dir);
+ if (!Object.keys(doc.clips).length) return null;
+ const m = await readManifest(dir);
+ /** @type {Record<string, string[]>} */
+ const by = {};
+ for (const e of m?.timeline ?? []) {
+ if (e?.type !== "clip") continue;
+ const row = doc.clips[e.id];
+ const st = !row ? "unchecked" : !rowIsCurrent(row, e) ? "stale" : e.quoteRuled && (row.status === "moved" || row.status === "not-found") ? "ruled" : row.status;
+ (by[st] ??= []).push(e.id);
+ }
+ const part = (k, label) => (by[k]?.length ? `${by[k].length} ${label}${k === "ok" || k === "unchecked" || k === "stale" ? "" : ` (${by[k].join(", ")})`}` : null);
+ const parts = [part("ok", "ok"), part("moved", "moved"), part("not-found", "not found"), part("ruled", "ruled"), part("stale", "stale"), part("unchecked", "unchecked")].filter(Boolean);
+ return {
+ counts: Object.fromEntries(Object.entries(by).map(([k, v]) => [k, v.length])),
+ line: ` quotes: ${parts.join(", ")}${by.moved?.length ? " — umtool window <p> <clip> --align" : ""}${by.stale?.length || by.unchecked?.length ? " — umtool quote-check <p>" : ""}`,
+ };
+}
+
/** The runner's progress as lines (stderr, and prep.log when it runs detached). */
export function eventLine(project, ev) {
if (ev.ev === "start" && ev.take) project = `${project} take ${ev.take}`;
@@ -140,10 +167,12 @@ export async function prepCommand(args, { root = REPORTS_ROOT, out = (s) => cons
if (args.includes("--status")) {
const s = await benchPrepState(project, { clips, take });
- if (json) out(JSON.stringify(s, null, 2));
+ const quotes = await quoteLine(project.dir);
+ if (json) out(JSON.stringify({ ...s, ...(quotes ? { quoteCheck: quotes.counts } : {}) }, null, 2));
else {
out(stateLine(s));
for (const it of s.items) if (it.state === "failed") out(` ✗ ${it.id}: ${it.error ?? "failed"}`);
+ if (quotes) out(quotes.line);
}
return 0;
}
diff --git a/umtool/lib/report/quoteCheck.mjs b/umtool/lib/report/quoteCheck.mjs
@@ -0,0 +1,368 @@
+// `umtool quote-check <project>` (lane one-clock): IS EACH CLIP'S QUOTE IN THE
+// SECONDS IT PLAYS?
+//
+// For every clip with a quote: the source the render would cut it from (the
+// raw cache, a corpus window, the saved video through its clock — sources.mjs
+// resolveLocalSource, exactly the build's lookup), its cut ± SEARCH_PAD_S of
+// it transcribed by the editor (`pnpm ops transcribe` with words: the GPU lane,
+// paced and queued there; nothing is decoded here), the quote found in those
+// words (quote-in-audio.mjs) and in the recording's cues, and the offset
+// between the two. `<project>/quote-check.json` keeps one row per clip:
+//
+// ok heard within ON_TIME_S of where the cues have it
+// moved heard, but seconds away: the render plays other words at the cut
+// -- `umtool window <p> <clip> --align` snaps the cut to them
+// not-found not in the seconds checked
+// no-window nothing on disk holds the cut (fetch first)
+//
+// A row remembers the cut and the source it judged: a clip whose cut or
+// source changed since reads as STALE, and is checked again on the next run.
+// `umtool check` reads the rows (projects/report.mjs: clip-quote-moved,
+// clip-quote-missing, blocking), and a take refuses a clip whose quote was not
+// found or moved unless the clip says `quoteRuled` (`umtool window <p> <clip>
+// --quote-ruled`: heard and ruled by a person).
+//
+// Plain ESM: the CLI runs under bare node; the app reads the file.
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { createCueSource, siteOriginFromManifest } from "umtool-report-to-video/cues";
+import { cueWords, findQuote, ON_TIME_S, quoteOffset } from "umtool-report-to-video/quote-in-audio";
+import { resolveLocalSource } from "umtool-report-to-video/sources";
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { kindMakesTakes } from "../projects/kinds.mjs";
+import { channelsLayersFor, hasShadowChannels, readManifest } from "../projects/report.mjs";
+
+export const QUOTE_CHECK_FILE = "quote-check.json";
+/** Seconds either side of the cut that are transcribed: the 6 Nov offsets reached 13.6 s. */
+export const SEARCH_PAD_S = 15;
+/** Cues read either side of the searched span, to find the quote in. */
+const CUE_PAD_S = 30;
+/** The cut's edges after --align: a breath before the first word, the last word let ring. */
+export const ALIGN_LEAD_S = 0.15;
+export const ALIGN_TAIL_S = 0.3;
+
+const r2 = (x) => Math.round(Number(x) * 100) / 100;
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+
+/** The span a clip plays: its cut, else its extent. */
+export const playedSpan = (e) => ({ from: r2(e.cutStart ?? e.start), to: r2(e.cutEnd ?? e.end) });
+
+/** The source's identity a row was judged on: a change makes the row stale. */
+export const sourceKey = (s) =>
+ s ? `${s.kind}:${s.path}@${r2(s.windowStart)}${s.clock ? `#${s.clock.id}` : ""}` : null;
+
+/**
+ * Is this row about the clip as it is now? Same cut, same source.
+ * @param {Record<string, any> | null | undefined} row
+ * @param {Record<string, any>} entry
+ * @param {string | null} [srcKey] the source as it resolves now, when known
+ */
+export function rowIsCurrent(row, entry, srcKey = undefined) {
+ if (!row) return false;
+ const p = playedSpan(entry);
+ if (Math.abs(row.cut?.from - p.from) > 0.011 || Math.abs(row.cut?.to - p.to) > 0.011) return false;
+ if (String(row.quote ?? "") !== String(entry.quote ?? "")) return false;
+ if (srcKey !== undefined && row.source?.key !== srcKey) return false;
+ return true;
+}
+
+/** The file, or an empty one. */
+export async function readQuoteCheck(dir) {
+ try {
+ const doc = JSON.parse(await readFile(path.join(dir, QUOTE_CHECK_FILE), "utf8"));
+ return doc && typeof doc === "object" && doc.clips && typeof doc.clips === "object" ? doc : { version: 1, clips: {} };
+ } catch {
+ return { version: 1, clips: {} };
+ }
+}
+
+async function writeQuoteCheck(dir, doc) {
+ const file = path.join(dir, QUOTE_CHECK_FILE);
+ const tmp = `${file}.tmp-${process.pid}`;
+ await writeFile(tmp, `${JSON.stringify(doc, null, 1)}\n`);
+ await rename(tmp, file);
+ return file;
+}
+
+/**
+ * The clips to check and where each one's seconds are. Pure but for the disk
+ * lookups the build makes.
+ * @param {string} dir
+ * @param {Record<string, any>} manifest
+ * @param {{ channelsDirs: string[], rawDir?: string, clipIds?: string[], pad?: number, probe?: any }} opts
+ */
+export async function planQuoteCheck(dir, manifest, { channelsDirs, rawDir = path.join(dir, "out", "clips-raw"), clipIds = [], pad = SEARCH_PAD_S, probe } = /** @type {any} */ ({})) {
+ const prov = manifest?.provenance ?? {};
+ const rows = [];
+ for (const e of manifest?.timeline ?? []) {
+ if (e?.type !== "clip" || e.src) continue;
+ if (clipIds.length && !clipIds.includes(e.id)) continue;
+ const slug = e.channel ?? prov.channelSlug ?? null;
+ const cut = playedSpan(e);
+ const base = { id: e.id, slug, video: e.video ?? null, quote: e.quote ?? null, cut };
+ if (!String(e.quote ?? "").trim()) {
+ rows.push({ ...base, skip: "no-quote" });
+ continue;
+ }
+ if (!slug || !e.video || !fin(cut.from) || !fin(cut.to)) {
+ rows.push({ ...base, skip: "no-window" });
+ continue;
+ }
+ const src = await resolveLocalSource(
+ { video: e.video, slug, from: cut.from, to: cut.to },
+ { rawDir, channelsDir: channelsDirs[0], fallbackChannelsDir: channelsDirs[1] ?? null, ...(probe ? { probe } : {}) },
+ );
+ if (!src) {
+ rows.push({ ...base, skip: "no-window" });
+ continue;
+ }
+ // The searched span, on the cue clock, inside what the source holds.
+ const from = Math.max(src.windowStart, cut.from - pad);
+ const to = Math.min(src.windowEnd, cut.to + pad);
+ rows.push({
+ ...base,
+ source: { kind: src.kind, path: src.path, name: src.name, windowStart: src.windowStart, windowEnd: src.windowEnd, ...(src.clock ? { clock: src.clock } : {}), key: sourceKey(src) },
+ span: { from: r2(from), to: r2(to) },
+ // The same span in the source FILE's seconds: what the editor transcribes.
+ file: { start: r2(Math.max(0, from - src.windowStart)), end: r2(Math.max(0, to - src.windowStart)) },
+ });
+ }
+ return rows;
+}
+
+/**
+ * One clip's verdict from the words heard (CUE clock) and the recording's cues.
+ * @param {{ quote: string, cut: { from: number, to: number }, span: { from: number, to: number } }} row
+ * @param {{ w?: string, text?: string, start: number, end: number }[]} heardWords
+ * @param {{ start: number, end: number, text: string }[] | null} cues
+ */
+export function judgeClip(row, heardWords, cues) {
+ const heard = findQuote(row.quote, heardWords);
+ const cued = cues ? findQuote(row.quote, cueWords(cues, { from: row.span.from - CUE_PAD_S, to: row.span.to + CUE_PAD_S })) : null;
+ let offset = heard.found && cued?.found ? quoteOffset(heard, cued) : null;
+ // No cues to compare with: where the clip's cut starts is the best guess of
+ // where the quote should be.
+ const against = offset !== null ? "cues" : heard.found ? "cut" : null;
+ if (offset === null && heard.found && heard.from !== null) offset = r2(heard.from - row.cut.from);
+ // Moved: heard away from where the cues have it -- or, with no cues to ask,
+ // heard outside the cut (the cut does not play it).
+ const outsideCut = heard.found && (heard.from < row.cut.from - ON_TIME_S || heard.to > row.cut.to + ON_TIME_S);
+ const status = !heard.found
+ ? "not-found"
+ : against === "cues"
+ ? Math.abs(/** @type {number} */ (offset)) > ON_TIME_S ? "moved" : "ok"
+ : outsideCut ? "moved" : "ok";
+ return {
+ status,
+ offset,
+ against,
+ match: heard.match,
+ heard: heard.found ? { from: heard.from, to: heard.to } : null,
+ cued: cued?.found ? { from: cued.from, to: cued.to } : null,
+ words: heard.heard.slice(0, 400),
+ };
+}
+
+/** "c43 moved +13.06 s (heard 2132.90–2140.10, cues 2119.84–…)" */
+export function rowLine(id, row) {
+ const off = fin(row.offset) ? ` ${row.offset >= 0 ? "+" : ""}${row.offset.toFixed(2)} s` : "";
+ const where = row.heard ? ` heard ${row.heard.from.toFixed(2)}–${row.heard.to.toFixed(2)}` : "";
+ const src = row.source ? ` [${row.source.kind}${row.source.clock ? `, clock ${row.source.clock.certain ? "" : "NOT "}certain` : ""}]` : "";
+ return `${String(id).padEnd(5)} ${String(row.status).padEnd(9)}${off}${where}${row.match !== undefined ? ` match ${row.match}` : ""}${src}`;
+}
+
+/**
+ * The clips a render must refuse: a CURRENT row that says the quote was not
+ * heard, or heard elsewhere, on a clip nobody ruled (`quoteRuled`).
+ * @param {Record<string, any>[]} timeline
+ * @param {{ clips: Record<string, any> }} doc
+ * @returns {{ id: string, status: string, why: string }[]}
+ */
+export function quoteGate(timeline, doc) {
+ const out = [];
+ for (const e of timeline ?? []) {
+ if (e?.type !== "clip" || e.quoteRuled) continue;
+ const row = doc?.clips?.[e.id];
+ if (!rowIsCurrent(row, e)) continue;
+ if (row.status === "not-found") {
+ out.push({ id: e.id, status: row.status, why: `${e.id}: its quote is not in the seconds it plays (umtool quote-check, match ${row.match})` });
+ } else if (row.status === "moved") {
+ out.push({
+ id: e.id,
+ status: row.status,
+ why: `${e.id}: its quote is heard ${row.offset >= 0 ? "+" : ""}${Number(row.offset).toFixed(2)} s from its cut — umtool window <p> ${e.id} --align`,
+ });
+ }
+ }
+ return out;
+}
+
+/**
+ * The window patch that snaps a clip's cut to its quote as HEARD (the row's
+ * heard span), widening the extent to hold it; lockCut set so no resolver
+ * re-derives the cut from cues the audio disagrees with.
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any> | null | undefined} row
+ */
+export function alignPatch(entry, row) {
+ if (!row) throw new Error(`${entry.id} has no quote check: umtool quote-check <p> --clips ${entry.id}`);
+ if (!rowIsCurrent(row, entry)) throw new Error(`${entry.id}: its quote check is stale (the cut or the quote changed): run umtool quote-check again`);
+ if (!row.heard) throw new Error(`${entry.id}: its quote was not heard (${row.status}) — nothing to align to; fetch it again (umtool fetch <p> --refetch ${entry.id}) or rule it`);
+ const cutStart = r2(Math.max(0, row.heard.from - ALIGN_LEAD_S));
+ const cutEnd = r2(row.heard.to + ALIGN_TAIL_S);
+ const patch = { cutStart, cutEnd, lockCut: true };
+ if (entry.start > cutStart) patch.start = cutStart;
+ if (entry.end < cutEnd) patch.end = cutEnd;
+ return patch;
+}
+
+// ---------------------------------------------------------------------------
+// The run.
+// ---------------------------------------------------------------------------
+
+/**
+ * Transcribe through the editor: `POST /api/ops/transcribe {path, start, end,
+ * words: true, out}`, waited for; the words on the FILE's clock.
+ * @param {{ path: string, start: number, end: number, out: string }} req
+ */
+async function editorWords(req, { emit }) {
+ const { askEditorOp } = await import("umtool-report-to-video/narrate-via-editor");
+ await askEditorOp("/api/ops/transcribe", { path: req.path, start: req.start, end: req.end, words: true, out: req.out }, { emit });
+ const doc = JSON.parse(await readFile(req.out, "utf8"));
+ return Array.isArray(doc.words) ? doc.words : [];
+}
+
+/**
+ * Check the planned clips; merge the rows into quote-check.json.
+ * @param {string} dir
+ * @param {Record<string, any>} manifest
+ * @param {Awaited<ReturnType<typeof planQuoteCheck>>} plan
+ * @param {{ transcribe?: typeof editorWords, cuesOf?: (slug: string, video: string) => Promise<any[] | null>, log?: (l: string) => void, now?: () => Date }} [opts]
+ */
+export async function runQuoteCheck(dir, manifest, plan, { transcribe = editorWords, cuesOf = null, log = () => {}, now = () => new Date() } = {}) {
+ const doc = await readQuoteCheck(dir);
+ const work = path.join(dir, "out", "quote-check");
+ await mkdir(work, { recursive: true });
+ const cueSource = cuesOf
+ ? null
+ : createCueSource({ channelsDirs: channelsLayersFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) }), siteOrigin: siteOriginFromManifest(manifest) });
+ const cueMemo = new Map();
+ const cues = async (slug, video) => {
+ const k = `${slug}/${video}`;
+ if (!cueMemo.has(k)) {
+ cueMemo.set(
+ k,
+ cuesOf
+ ? await cuesOf(slug, video)
+ : await cueSource
+ .load(slug, video, {})
+ .then((r) => r?.cues ?? null)
+ .catch(() => null),
+ );
+ }
+ return cueMemo.get(k);
+ };
+ const results = {};
+ for (const p of plan) {
+ const checkedAt = now().toISOString();
+ if (p.skip) {
+ results[p.id] = { status: p.skip, cut: p.cut, quote: p.quote, checkedAt };
+ log(rowLine(p.id, results[p.id]));
+ continue;
+ }
+ const out = path.join(work, `${p.id}.words.json`);
+ let words;
+ try {
+ words = await transcribe({ path: p.source.path, start: p.file.start, end: p.file.end, out }, { emit: () => {} });
+ } catch (e) {
+ log(`${p.id}: the transcription failed: ${e instanceof Error ? e.message : String(e)}`);
+ continue;
+ }
+ // The words on the CUE clock: the file's seconds + where the file starts on it.
+ const heardWords = words.map((w) => ({ w: w.w ?? w.text, start: w.start + p.source.windowStart, end: w.end + p.source.windowStart }));
+ const verdict = judgeClip(p, heardWords, await cues(p.slug, p.video));
+ results[p.id] = { ...verdict, cut: p.cut, quote: p.quote, span: p.span, source: p.source, checkedAt };
+ log(rowLine(p.id, results[p.id]));
+ }
+ const merged = { version: 1, checkedAt: now().toISOString(), clips: { ...doc.clips, ...results } };
+ const file = await writeQuoteCheck(dir, merged);
+ return { file, doc: merged, results };
+}
+
+// ---------------------------------------------------------------------------
+// The CLI.
+// ---------------------------------------------------------------------------
+
+export const QUOTE_CHECK_USAGE = [
+ "usage: umtool quote-check <project> [--clips a,b] [--pad S] [--json] transcribe what each clip plays; find its quote",
+ " umtool quote-check <project> --status [--json] the rows as they stand (stale ones said)",
+ "",
+ `Each clip's cut ±${SEARCH_PAD_S} s (--pad) of the source the render would cut it from is transcribed by the`,
+ "editor (its transcription lane, words on), and the quote is found in those words and in the recording's",
+ `cues: ok (within ${ON_TIME_S} s), moved (heard elsewhere: umtool window <p> <clip> --align), not-found.`,
+ `Rows go to <project>/${QUOTE_CHECK_FILE}; umtool check reads them, and a take refuses a moved or`,
+ "missing quote unless the clip is ruled (umtool window <p> <clip> --quote-ruled).",
+].join("\n");
+
+class CliError extends Error {}
+
+export async function quoteCheckCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, transcribe, cuesOf } = {}) {
+ try {
+ const words = [];
+ /** @type {Record<string, string[]>} */
+ const flags = {};
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (a === "--json" || a === "--status" || a === "--help") flags[a] = ["1"];
+ else if (a.startsWith("--")) (flags[a] ??= []).push(args[++i] ?? "");
+ else words.push(a);
+ }
+ if (flags["--help"] || !words.length) {
+ log(QUOTE_CHECK_USAGE);
+ return flags["--help"] ? 0 : 2;
+ }
+ const r = await resolveProject(words[0], reportsRoot);
+ if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${words[0]}"`);
+ const project = r.project;
+ if (!kindMakesTakes(project.kind)) throw new CliError(`${project.id} is a ${project.kind}, not a report video`);
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new CliError(`${project.id} has no manifest`);
+ const json = !!flags["--json"];
+
+ if (flags["--status"]) {
+ const doc = await readQuoteCheck(project.dir);
+ const rows = [];
+ for (const e of manifest.timeline ?? []) {
+ if (e?.type !== "clip") continue;
+ const row = doc.clips[e.id];
+ rows.push({ id: e.id, ...(row ?? { status: "unchecked" }), current: rowIsCurrent(row, e) });
+ }
+ if (json) log(JSON.stringify({ project: project.id, clips: rows }, null, 1));
+ else for (const row of rows) log(`${rowLine(row.id, row)}${row.current || row.status === "unchecked" ? "" : " (stale: the cut or the quote changed)"}`);
+ return 0;
+ }
+
+ const clipIds = (flags["--clips"] ?? []).flatMap((s) => s.split(",")).map((s) => s.trim()).filter(Boolean);
+ const pad = flags["--pad"] ? Number(flags["--pad"].at(-1)) : SEARCH_PAD_S;
+ if (!(pad >= 0 && pad <= 60)) throw new CliError("--pad is seconds, 0 to 60");
+ const channelsDirs = channelsLayersFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) });
+ if (!channelsDirs.length) throw new CliError("no channels directory (CHANNELS_DIR) to read the windows from");
+ const plan = await planQuoteCheck(project.dir, manifest, { channelsDirs, clipIds, pad });
+ if (clipIds.length && !plan.length) throw new CliError(`none of ${clipIds.join(", ")} is a clip of ${project.id}`);
+ const { file, results } = await runQuoteCheck(project.dir, manifest, plan, {
+ ...(transcribe ? { transcribe } : {}),
+ ...(cuesOf ? { cuesOf } : {}),
+ log: json ? () => {} : log,
+ });
+ if (json) log(JSON.stringify({ project: project.id, file, clips: results }, null, 1));
+ else {
+ const count = (s) => Object.values(results).filter((x) => x.status === s).length;
+ log(`→ ${file}: ${count("ok")} ok, ${count("moved")} moved, ${count("not-found")} not found, ${count("no-window")} with no window`);
+ }
+ return 0;
+ } catch (e) {
+ err(e instanceof CliError ? `umtool quote-check: ${e.message}` : `umtool quote-check: ${e instanceof Error ? e.stack ?? e.message : String(e)}`);
+ return e instanceof CliError ? 2 : 1;
+ }
+}
diff --git a/umtool/lib/report/quoteCheck.test.mjs b/umtool/lib/report/quoteCheck.test.mjs
@@ -0,0 +1,183 @@
+// quoteCheck.mjs (lane one-clock): the plan finds what the render would play,
+// the run judges each clip from the words the editor heard and the cues, the
+// gate refuses a moved or missing quote unless ruled, and --align snaps the cut
+// to the words. The words and cues are the 6 Nov c43 window's
+// (report-to-video/fixtures/rev9-a3-rumble-words.json): heard 13 s late.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { alignPatch, judgeClip, planQuoteCheck, quoteCheckCommand, quoteGate, readQuoteCheck, rowIsCurrent, runQuoteCheck } from "./quoteCheck.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIX = JSON.parse(await readFile(path.join(HERE, "..", "..", "report-to-video", "fixtures", "rev9-a3-rumble-words.json"), "utf8"));
+const C43 = FIX.clips.find((c) => c.id === "c43");
+const C44 = FIX.clips.find((c) => c.id === "c44");
+
+async function project() {
+ const root = await mkdtemp(path.join(os.tmpdir(), "quote-check-"));
+ const dir = path.join(root, "diet");
+ const raw = path.join(dir, "out", "clips-raw");
+ await mkdir(raw, { recursive: true });
+ const channels = path.join(root, "channels");
+ await mkdir(channels, { recursive: true });
+ // The windows the render would play: the project's raw cache, named for the cue clock.
+ for (const c of [C43, C44]) await writeFile(path.join(raw, `${c.video}_${c.window[0].toFixed(2)}-${c.window[1].toFixed(2)}.mp4`), "mp4");
+ const manifest = {
+ provenance: { channelSlug: "the-quartering-rumble", channelsDir: channels, channelsFallback: false },
+ timeline: [
+ { type: "clip", id: "c43", channel: C43.channel, video: C43.video, start: 2119.34, end: 2127.44, quote: C43.quote },
+ { type: "clip", id: "c44", channel: C44.channel, video: C44.video, start: 633.42, end: 644.16, quote: C44.quote },
+ { type: "clip", id: "c99", channel: C44.channel, video: C44.video, start: 10, end: 20 },
+ ],
+ };
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest));
+ return { root, dir, channels, manifest };
+}
+
+// The editor, stood in for: the fixture's words between start and end, on the file's clock.
+const fakeTranscribe = async (req) => {
+ const clip = [C43, C44].find((c) => req.path.includes(c.video));
+ return clip.words.filter((w) => w.start >= req.start - 0.01 && w.end <= req.end + 0.01);
+};
+const fakeCues = async (_slug, video) => [C43, C44].find((c) => c.video === video)?.cues ?? null;
+
+test("plan, run, gate, align: c43 is heard 13 s late; c44 where its cues say", async () => {
+ const p = await project();
+ try {
+ const plan = await planQuoteCheck(p.dir, p.manifest, { channelsDirs: [p.channels] });
+ const c43 = plan.find((r) => r.id === "c43");
+ assert.equal(c43.source.kind, "raw-cache");
+ assert.equal(c43.source.windowStart, C43.window[0]);
+ // The cut ±15 s, inside the window the render would cut from.
+ assert.deepEqual(c43.span, { from: 2104.34, to: 2142.44 });
+ assert.deepEqual(c43.file, { start: 0, end: 38.1 });
+ assert.equal(plan.find((r) => r.id === "c99").skip, "no-quote");
+
+ const lines = [];
+ const { doc } = await runQuoteCheck(p.dir, p.manifest, plan, { transcribe: fakeTranscribe, cuesOf: fakeCues, log: (l) => lines.push(l) });
+ assert.equal(doc.clips.c43.status, "moved");
+ assert.ok(Math.abs(doc.clips.c43.offset - 13.1) < 0.15, String(doc.clips.c43.offset));
+ assert.equal(doc.clips.c43.against, "cues");
+ assert.equal(doc.clips.c44.status, "ok");
+ assert.equal(doc.clips.c99.status, "no-quote");
+ assert.match(lines.join("\n"), /c43 +moved +\+13\.\d\d s heard 2132\.\d\d/);
+ assert.deepEqual(await readQuoteCheck(p.dir), doc);
+
+ // The gate: c43 refused, c44 not; ruled, c43 renders; a changed cut is stale and says nothing.
+ assert.deepEqual(quoteGate(p.manifest.timeline, doc).map((g) => [g.id, g.status]), [["c43", "moved"]]);
+ const ruled = p.manifest.timeline.map((e) => (e.id === "c43" ? { ...e, quoteRuled: true } : e));
+ assert.deepEqual(quoteGate(ruled, doc), []);
+ const moved = p.manifest.timeline.map((e) => (e.id === "c43" ? { ...e, cutStart: 2120, cutEnd: 2127 } : e));
+ assert.equal(rowIsCurrent(doc.clips.c43, moved[0]), false);
+ assert.deepEqual(quoteGate(moved, doc), []);
+
+ // --align: the cut on the words as heard, the extent widened to hold it.
+ const patch = alignPatch(p.manifest.timeline[0], doc.clips.c43);
+ assert.equal(patch.lockCut, true);
+ assert.ok(Math.abs(patch.cutStart - (doc.clips.c43.heard.from - 0.15)) < 0.011);
+ assert.ok(patch.cutStart > 2132 && patch.cutEnd > 2140, JSON.stringify(patch));
+ assert.equal(patch.start, undefined);
+ assert.equal(patch.end, patch.cutEnd);
+ assert.throws(() => alignPatch(moved[0], doc.clips.c43), /stale/);
+ assert.throws(() => alignPatch(p.manifest.timeline[0], null), /no quote check/);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("judge: not heard is not-found; with no cues the cut is what the offset is measured from", () => {
+ const row = { quote: C43.quote, cut: { from: 2119.34, to: 2127.44 }, span: { from: 2104.34, to: 2142.44 } };
+ const words = C43.words.map((w) => ({ ...w, start: w.start + C43.window[0], end: w.end + C43.window[0] }));
+ const noCues = judgeClip(row, words, null);
+ assert.equal(noCues.against, "cut");
+ // Against the cut only: moved when the words are heard outside the cut (the cut does not play them).
+ assert.equal(noCues.status, "moved");
+ const inside = judgeClip({ ...row, cut: { from: 2130, to: 2142 } }, words, null);
+ assert.equal(inside.status, "ok");
+ const elsewhere = judgeClip({ ...row, quote: "I promise you by this time next year I will be down 100 pounds" }, words, C43.cues);
+ assert.equal(elsewhere.status, "not-found");
+});
+
+test("the CLI: a project's clips checked through the injected editor, --status after", async () => {
+ const p = await project();
+ try {
+ const out = [];
+ const code = await quoteCheckCommand(["diet", "--clips", "c43"], {
+ reportsRoot: p.root,
+ log: (l) => out.push(l),
+ err: (l) => out.push(`ERR ${l}`),
+ transcribe: fakeTranscribe,
+ cuesOf: fakeCues,
+ });
+ assert.equal(code, 0, out.join("\n"));
+ assert.match(out.join("\n"), /0 ok, 1 moved, 0 not found/);
+ const st = [];
+ assert.equal(await quoteCheckCommand(["diet", "--status"], { reportsRoot: p.root, log: (l) => st.push(l), err: (l) => st.push(l) }), 0);
+ assert.match(st.join("\n"), /c43 +moved/);
+ assert.match(st.join("\n"), /c44 +unchecked/);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("umtool check: a moved quote and a missing one are blocking, with the fix; ruled or stale, nothing", async () => {
+ const { decisionsFor } = await import("../projects/core.mjs");
+ const { walkProjects } = await import("../projects/walk.mjs");
+ const root = await mkdtemp(path.join(os.tmpdir(), "quote-decisions-"));
+ try {
+ const channelsDir = path.join(root, "channels");
+ const vdir = path.join(channelsDir, "chan", "data", "vid");
+ await mkdir(vdir, { recursive: true });
+ await writeFile(path.join(vdir, "transcript.cues.json"), JSON.stringify({ cues: Array.from({ length: 200 }, (_, i) => ({ start: i, end: i + 1, text: `Line ${i}.` })) }));
+ const dir = path.join(root, "reports", "cut");
+ await mkdir(dir, { recursive: true });
+ const clip = (id, start, extra = {}) => ({ type: "clip", id, video: "vid", start, end: start + 5, cite: start, lock: true, quote: `Line ${start}`, ...extra });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({
+ schemaVersion: 1, slug: "cut", title: "Cut",
+ provenance: { channelSlug: "chan", channelsDir: path.relative(dir, channelsDir), siteOrigin: "https://example.test" },
+ render: { width: 1920, height: 1080, fps: 30 },
+ timeline: [clip("a", 10), clip("b", 20), clip("c", 30, { quoteRuled: true }), clip("d", 40)],
+ }));
+ const row = (start, status, extra = {}) => ({ status, cut: { from: start, to: start + 5 }, quote: `Line ${start}`, match: 0.3, ...extra });
+ await writeFile(path.join(dir, "quote-check.json"), JSON.stringify({
+ version: 1,
+ clips: {
+ a: row(10, "moved", { offset: 13.06, match: 1, heard: { from: 23.06, to: 25 } }),
+ b: row(20, "not-found"),
+ c: row(30, "not-found"),
+ d: { ...row(40, "not-found"), cut: { from: 41, to: 45 } },
+ },
+ }));
+ const [ref] = (await walkProjects(path.join(root, "reports"))).filter((p) => p.id === "cut");
+ const ds = (await decisionsFor(ref, path.join(root, "reports"))).filter((d) => d.kind.startsWith("clip-quote"));
+ assert.deepEqual(ds.map((d) => [d.kind, d.target, d.severity]), [
+ ["clip-quote-moved", "a", "blocking"],
+ ["clip-quote-missing", "b", "blocking"],
+ ]);
+ assert.match(ds[0].why, /a: its quote is heard \+13\.06 s from its cut — umtool window cut a --align/);
+ assert.equal(ds[0].fix, "umtool window cut a --align # or --quote-ruled, having heard it");
+ assert.match(ds[1].fix, /umtool fetch cut --refetch b/);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("prep --status says the quote check's verdicts on the clips as they are now", async () => {
+ const { quoteLine } = await import("./prepCli.mjs");
+ const p = await project();
+ try {
+ assert.equal(await quoteLine(p.dir), null);
+ const plan = await planQuoteCheck(p.dir, p.manifest, { channelsDirs: [p.channels] });
+ await runQuoteCheck(p.dir, p.manifest, plan, { transcribe: fakeTranscribe, cuesOf: fakeCues });
+ const q = await quoteLine(p.dir);
+ assert.equal(q.line, " quotes: 1 ok, 1 moved (c43) — umtool window <p> <clip> --align");
+ assert.deepEqual(q.counts, { moved: 1, ok: 1, "no-quote": 1 });
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -690,6 +690,19 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
// blocking (clip-incorrect), and a take is a render like any other.
const wrong = incorrectClips(renderDoc.timeline);
if (wrong.length) throw new Error(`${spec.id}: ${wrong.map(incorrectWhy).join("; ")}`);
+ // A clip whose quote the quote check did not hear where it plays (lane
+ // one-clock, lib/report/quoteCheck.mjs): refused the same way, unless a
+ // person ruled it (`quoteRuled`). No check on record refuses nothing.
+ {
+ const { quoteGate, readQuoteCheck } = await import("./quoteCheck.mjs");
+ const unheard = quoteGate(renderDoc.timeline, await readQuoteCheck(projectDir));
+ if (unheard.length) {
+ throw new Error(
+ `${spec.id}: ${unheard.map((u) => u.why.replace("<p>", path.basename(projectDir))).join("; ")} ` +
+ "(heard and right after all: umtool window <p> <clip> --quote-ruled)",
+ );
+ }
+ }
await mkdir(takeDir, { recursive: true });
await opts.onTakeDir?.(takeDir, spec.id);
diff --git a/umtool/report-to-video/fetch-via-editor.mjs b/umtool/report-to-video/fetch-via-editor.mjs
@@ -28,6 +28,8 @@
import path from "node:path";
import { readFile } from "node:fs/promises";
+import { corpusChannelsDir, isWholeRecording, localVideoId, mappedLine, recordingPlatform, withLocalIds } from "./recording-ids.mjs";
+import { resolveLocalSource } from "./sources.mjs";
const DEFAULT_EDITOR = "http://localhost:3001";
// One poll a second while a job runs, one every five while it waits its turn.
@@ -226,6 +228,37 @@ async function notePlace(jobId, label, last) {
return line;
}
+// Every fetch-windows job, polled to its end; the failed ones' reasons. A job
+// that stopped short (a rate limit, two 403s) fails with the reason; asking
+// again later resumes it, the fetched windows answering from the cache.
+// No deadline: a batch queued behind hours of other work is waited for.
+async function waitForJobs(jobs) {
+ const pending = new Map(jobs.map((j) => [j.jobId, j]));
+ for (const jobId of pending.keys()) waitingOn.add(jobId);
+ const failed = [];
+ const last = new Map();
+ const places = new Map();
+ while (pending.size > 0) {
+ await sleep(QUEUED_POLL_MS);
+ for (const [jobId, j] of pending) {
+ const p = await pollJob(jobId);
+ const label = j.platform ? ` (${j.platform}, ${j.items} window(s))` : "";
+ if (p.status !== last.get(jobId)) {
+ last.set(jobId, p.status);
+ EMIT("note", { message: ` editor job ${jobId}${label}: ${p.status}` });
+ }
+ if (p.status === "queued") places.set(jobId, await notePlace(jobId, label, places.get(jobId)));
+ if (p.status === "done") pending.delete(jobId);
+ else if (p.status === "failed" || p.status === "cancelled") {
+ pending.delete(jobId);
+ failed.push(`${jobId} ${p.status}: ${String(p.error ?? "").split("\n").slice(-3).join(" / ")}`);
+ }
+ if (!pending.has(jobId)) waitingOn.delete(jobId);
+ }
+ }
+ return failed;
+}
+
if (wantAll) {
if (argv.includes("--full")) die("--all fetches windows; --full is one clip's whole recording");
const clips = (whole.timeline ?? []).filter((e) => e.type === "clip");
@@ -248,11 +281,15 @@ if (wantAll) {
EMIT("done", { out: null, nothingToFetch: true });
process.exit(0);
}
+ // Each recording asked for by its DIRECTORY id (a Rumble embed id → its URL
+ // slug's directory: recording-ids.mjs).
+ const local = await withLocalIds(items);
+ if (local.mapped.length) EMIT("note", { message: ` asked by directory id: ${mappedLine(local.mapped)}` });
const res = await ask(`${editorUrl}/api/ops/fetch-windows`, {
method: "POST",
headers,
body: JSON.stringify({
- items,
+ items: local.items,
requestedBy: "umtool",
manifest: manifestId,
...(maxHeight !== undefined ? { maxHeight } : {}),
@@ -274,33 +311,7 @@ if (wantAll) {
for (const r of body.refused ?? []) {
EMIT("note", { message: ` ${r.platform}: ${r.items} window(s) not started — ${r.error}` });
}
- // Every job, polled to its end. A job that stopped short (a rate limit, two
- // 403s) fails with the reason; asking again later resumes it, the fetched
- // windows answering from the cache.
- // No deadline: a batch queued behind hours of other work is waited for.
- const pending = new Map(body.jobs.map((j) => [j.jobId, j]));
- for (const jobId of pending.keys()) waitingOn.add(jobId);
- const failed = [];
- const last = new Map();
- const places = new Map();
- while (pending.size > 0) {
- await sleep(QUEUED_POLL_MS);
- for (const [jobId, j] of pending) {
- const p = await pollJob(jobId);
- const label = ` (${j.platform}, ${j.items} window(s))`;
- if (p.status !== last.get(jobId)) {
- last.set(jobId, p.status);
- EMIT("note", { message: ` editor job ${jobId}${label}: ${p.status}` });
- }
- if (p.status === "queued") places.set(jobId, await notePlace(jobId, label, places.get(jobId)));
- if (p.status === "done") pending.delete(jobId);
- else if (p.status === "failed" || p.status === "cancelled") {
- pending.delete(jobId);
- failed.push(`${jobId} ${p.status}: ${String(p.error ?? "").split("\n").slice(-3).join(" / ")}`);
- }
- if (!pending.has(jobId)) waitingOn.delete(jobId);
- }
- }
+ const failed = await waitForJobs(body.jobs);
const unfinished = failed.length + (body.refused?.length ?? 0) + (body.unresolved?.length ?? 0);
if (unfinished > 0) {
die(`not every window was fetched:\n ${[...failed, ...(body.refused ?? []).map((r) => `${r.platform}: ${r.error}`)].join("\n ") || "see the notes above"}`);
@@ -345,6 +356,14 @@ if (!channelSlug) {
const { from, to } = windowOf(entry);
+// THE DIRECTORY ID the corpus keeps this recording under (a Rumble embed id →
+// its URL slug's directory), asked here so the editor is never sent to a
+// data/<embed>/ that does not exist.
+const videoId = await localVideoId({ slug: channelSlug, id: entry.video });
+if (videoId !== entry.video) {
+ EMIT("note", { message: ` ${entry.id}: ${channelSlug}/${entry.video} is the directory ${videoId} here (a Rumble embed id)` });
+}
+
// WHY THESE SECONDS. Stored beside the file so a directory of windows can be
// read back months later. The clip's own note is the closest thing the manifest
// has to a reason; the manifest id and the clip id say the rest.
@@ -360,6 +379,66 @@ EMIT("fetch", {
cached: false,
});
+// A WHOLE-RECORDING PLATFORM'S WINDOW (settings.clips.wholeRecordingPlatforms,
+// default Rumble) is NEVER a remote seek: it is asked of fetch-windows, which
+// saves the whole recording once (on the platform's download queue), makes its
+// clock current and cuts the window from it on the cue clock. The window is
+// then read off this corpus. Nothing here falls back to a seek.
+if (!wantFull && (await isWholeRecording({ slug: channelSlug, webpageUrl: entry.webpageUrl ?? null }))) {
+ const platform = await recordingPlatform({ slug: channelSlug, webpageUrl: entry.webpageUrl ?? null });
+ EMIT("note", {
+ message: ` ${entry.id}: a ${platform} window is cut from the whole recording, never seeked — asking fetch-windows for ${channelSlug}/${videoId}`,
+ });
+ const res = await ask(`${editorUrl}/api/ops/fetch-windows`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({
+ items: [
+ {
+ slug: channelSlug,
+ id: videoId,
+ from,
+ to,
+ clipId: entry.id,
+ pad: Math.max(padBefore, padAfter),
+ reason: String(reason).slice(0, 400),
+ ...(entry.webpageUrl ? { webpageUrl: entry.webpageUrl } : {}),
+ },
+ ],
+ requestedBy: "umtool",
+ manifest: manifestId,
+ ...(maxHeight !== undefined ? { maxHeight } : {}),
+ }),
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok || !body.ok) die(`the editor refused (HTTP ${res.status}): ${body.error ?? "no reason given"}`);
+ const refusals = [
+ ...(body.unresolved ?? []).map((u) => u.error),
+ ...(body.refused ?? []).map((r) => `${r.platform}: ${r.error}`),
+ ];
+ if (refusals.length) die(`the editor did not start the whole-recording fetch: ${refusals.join(" / ")}`);
+ const jobs = [
+ ...(body.jobs ?? []),
+ ...(body.inFlight ?? []).map((f) => ({ jobId: f.jobId, platform: platform ?? "", items: 1 })),
+ ];
+ for (const j of jobs) EMIT("note", { message: ` queued on the editor as job ${j.jobId} (the whole recording, then the cut)` });
+ const failed = await waitForJobs(jobs);
+ if (failed.length) die(`the whole-recording fetch failed (no seek was tried):\n ${failed.join("\n ")}`);
+ const hit = await resolveLocalSource(
+ { video: videoId, slug: channelSlug, from, to },
+ { channelsDir: corpusChannelsDir(), kinds: ["corpus-window"] },
+ );
+ if (!hit) {
+ die(
+ `fetch-windows finished, but no window holding ${from}–${to} of ${channelSlug}/${videoId} is in ` +
+ `${corpusChannelsDir()} — not seeking; see the editor's /jobs log`,
+ );
+ }
+ EMIT("fetch", { id: entry.id, video: entry.video, from: hit.windowStart, to: hit.windowEnd, cached: true, reuse: hit.name });
+ EMIT("done", { out: hit.path, fetchStart: hit.windowStart, cached: jobs.length === 0 });
+ process.exit(0);
+}
+
const res = await ask(`${editorUrl}/api/media/fetch-window`, {
method: "POST",
headers,
@@ -368,7 +447,7 @@ const res = await ask(`${editorUrl}/api/media/fetch-window`, {
// describe a request the editor does not have.
body: JSON.stringify({
channelSlug,
- videoId: entry.video,
+ videoId,
webpageUrl: entry.webpageUrl ?? undefined,
...(wantFull ? { full: true } : { from, to, pad: Math.max(padBefore, padAfter) }),
...(maxHeight !== undefined ? { maxHeight } : {}),
diff --git a/umtool/report-to-video/fetch-via-editor.test.mjs b/umtool/report-to-video/fetch-via-editor.test.mjs
@@ -291,3 +291,120 @@ test("a window already being fetched (the editor's dedupe) is followed, and says
await ed.close();
}
});
+
+// ONE CLOCK PER RECORDING (lane one-clock): a clip on a whole-recording
+// platform is asked of fetch-windows by its DIRECTORY id (the Rumble embed id
+// the manifest cites → the URL slug's directory), waited for, and read off the
+// corpus — never a /api/media/fetch-window seek.
+async function rumbleCorpus() {
+ const root = await mkdtemp(path.join(os.tmpdir(), "fve-rumble-"));
+ const { mkdir } = await import("node:fs/promises");
+ const videoDir = path.join(root, "channels", "rc", "data", "v7fxp3e");
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(path.join(root, "channels", "rc", "config.json"), JSON.stringify({ platform: "rumble" }));
+ await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id: "v7drc5w", webpage_url: "https://rumble.com/v7fxp3e-x.html" }));
+ return { root, channelsDir: path.join(root, "channels"), videoDir };
+}
+
+async function routedEditor(routes) {
+ const seen = [];
+ const server = http.createServer((req, res) => {
+ let raw = "";
+ req.on("data", (c) => (raw += c));
+ req.on("end", async () => {
+ seen.push({ method: req.method, url: req.url, body: raw ? JSON.parse(raw) : null });
+ const key = Object.keys(routes).find((k) => req.url.startsWith(k));
+ const a = key ? await routes[key](raw ? JSON.parse(raw) : null) : { status: 404, body: { error: "no route" } };
+ res.writeHead(a.status, { "content-type": "application/json" });
+ res.end(JSON.stringify(a.body));
+ });
+ });
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ const { port } = /** @type {import("node:net").AddressInfo} */ (server.address());
+ return { seen, url: `http://127.0.0.1:${port}`, close: () => new Promise((r) => server.close(r)) };
+}
+
+async function runRumble(editorUrl, channelsDir) {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "fve-m-"));
+ try {
+ const manifest = path.join(dir, "video.manifest.json");
+ await writeFile(
+ manifest,
+ JSON.stringify({ provenance: { manifestId: "d" }, timeline: [{ id: "c43", type: "clip", channel: "rc", video: "v7drc5w", start: 10, end: 20 }] }),
+ );
+ return await new Promise((resolve) => {
+ execFile(
+ process.execPath,
+ [SCRIPT, manifest, "--fetch-only", "c43", "--progress", "ndjson"],
+ {
+ env: {
+ ...process.env,
+ ARCHILYZER_EDITOR_URL: editorUrl,
+ WORKER_TOKEN: "tok",
+ CHANNELS_DIR: channelsDir,
+ SETTINGS_FILE: path.join(dir, "no-settings.json"),
+ FETCH_VIA_EDITOR_POLL_MS: "5",
+ },
+ },
+ (err, stdout) => resolve({ code: err ? err.code : 0, events: stdout.split("\n").filter(Boolean).map((l) => JSON.parse(l)) }),
+ );
+ });
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
+test("a Rumble clip: fetch-windows by the directory id, then the window off the corpus; no seek", async () => {
+ const c = await rumbleCorpus();
+ const { mkdir } = await import("node:fs/promises");
+ const ed = await routedEditor({
+ "/api/ops/fetch-windows": async () => ({
+ status: 200,
+ body: { ok: true, dryRun: false, jobs: [{ platform: "rumble", queueKey: "platform:rumble", jobId: "j1", items: 1 }], groups: [], refused: [], cached: [], inFlight: [], unresolved: [] },
+ }),
+ "/api/media/fetch-window/j1": async () => {
+ // The job "ran": the editor cut the window on the cue clock.
+ await mkdir(path.join(c.videoDir, "clips"), { recursive: true });
+ await writeFile(path.join(c.videoDir, "clips", "7.00-23.00.mp4"), "mp4");
+ return { status: 200, body: { status: "done" } };
+ },
+ "/api/ops/job/": async () => ({ status: 200, body: { job: {} } }),
+ });
+ try {
+ const { code, events } = await runRumble(ed.url, c.channelsDir);
+ assert.equal(code, 0, JSON.stringify(events));
+ const post = ed.seen.find((s) => s.url === "/api/ops/fetch-windows");
+ assert.equal(post.body.items[0].id, "v7fxp3e");
+ assert.deepEqual([post.body.items[0].from, post.body.items[0].to], [7, 23]);
+ assert.equal(ed.seen.some((s) => s.method === "POST" && s.url === "/api/media/fetch-window"), false, "never a seek");
+ const done = events.find((e) => e.ev === "done");
+ assert.equal(done.out, path.join(c.videoDir, "clips", "7.00-23.00.mp4"));
+ assert.equal(done.fetchStart, 7);
+ assert.ok(events.some((e) => e.ev === "note" && /rc\/v7drc5w is the directory v7fxp3e/.test(e.message)));
+ assert.ok(events.some((e) => e.ev === "note" && /a rumble window is cut from the whole recording, never seeked/.test(e.message)));
+ } finally {
+ await ed.close();
+ await rm(c.root, { recursive: true, force: true });
+ }
+});
+
+test("a Rumble clip whose whole-recording fetch fails: exit 1, and still no seek", async () => {
+ const c = await rumbleCorpus();
+ const ed = await routedEditor({
+ "/api/ops/fetch-windows": async () => ({
+ status: 200,
+ body: { ok: true, dryRun: false, jobs: [{ platform: "rumble", queueKey: "platform:rumble", jobId: "j2", items: 1 }], groups: [], refused: [], cached: [], inFlight: [], unresolved: [] },
+ }),
+ "/api/media/fetch-window/j2": async () => ({ status: 200, body: { status: "failed", error: "the whole recording was not saved: HTTP Error 403" } }),
+ "/api/ops/job/": async () => ({ status: 200, body: { job: {} } }),
+ });
+ try {
+ const { code, events } = await runRumble(ed.url, c.channelsDir);
+ assert.equal(code, 1);
+ assert.ok(events.some((e) => e.ev === "note" && /no seek was tried/.test(e.message) && /403/.test(e.message)));
+ assert.equal(ed.seen.some((s) => s.method === "POST" && s.url === "/api/media/fetch-window"), false);
+ } finally {
+ await ed.close();
+ await rm(c.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/fixtures/rev9-a3-rumble-words.json b/umtool/report-to-video/fixtures/rev9-a3-rumble-words.json
@@ -0,0 +1 @@
+{"note":"rev9-a3 (quartering-diet, 6 Nov 2026): parakeet word timings of fetched Rumble windows (on the window file's clock; add `window[0]` for the cue clock) and the recording's cues around them. The editing agent measured c43 +13.1 s, c45 +13.6 s, c20 +5.2 s, k46 -0.7 s, c44 0 s.","clips":[{"id":"c43","channel":"the-quartering-rumble","video":"v7drc5w","quote":"so total loss now is thirty eight point five pounds started at three hundred forty nine I'm down to three hundred ten point five","window":[2104.34,2142.44],"words":[{"w":"If","start":2.16,"end":2.32},{"w":"the","start":2.72,"end":2.8},{"w":"link's","start":2.8,"end":3.28},{"w":"not","start":3.28,"end":3.44},{"w":"working","start":3.44,"end":3.6},{"w":"and","start":3.68,"end":3.84},{"w":"you","start":3.84,"end":3.92},{"w":"can't","start":3.92,"end":4.24},{"w":"figure","start":4.24,"end":4.48},{"w":"that","start":4.56,"end":4.72},{"w":"out.","start":4.72,"end":4.88},{"w":"Look","start":7.04,"end":7.2},{"w":"good","start":7.36,"end":7.44},{"w":"by","start":7.6,"end":7.68},{"w":"the","start":7.68,"end":7.76},{"w":"way,","start":7.76,"end":7.84},{"w":"Jeremy,","start":7.92,"end":8.32},{"w":"I'm","start":8.4,"end":8.72},{"w":"down","start":8.72,"end":8.8},{"w":"twenty","start":8.88,"end":9.04},{"w":"now","start":9.12,"end":9.2},{"w":"from","start":9.28,"end":9.44},{"w":"your","start":9.52,"end":9.6},{"w":"inspiration.","start":9.76,"end":10.32},{"w":"Dude,","start":10.48,"end":10.72},{"w":"I'm","start":11.36,"end":11.6},{"w":"so","start":11.6,"end":11.76},{"w":"proud","start":11.76,"end":12},{"w":"of","start":12.08,"end":12.16},{"w":"you.","start":12.16,"end":12.32},{"w":"That's","start":12.48,"end":12.88},{"w":"amazing.","start":12.88,"end":13.44},{"w":"That's","start":15.68,"end":16.08},{"w":"crazy","start":16.08,"end":16.48},{"w":"good,","start":16.56,"end":16.72},{"w":"dude.","start":16.8,"end":17.12},{"w":"I","start":19.04,"end":19.2},{"w":"weighed","start":19.2,"end":19.52},{"w":"in","start":19.52,"end":19.68},{"w":"this","start":19.68,"end":19.76},{"w":"morning","start":19.76,"end":20},{"w":"and","start":20.08,"end":20.24},{"w":"the","start":20.24,"end":20.32},{"w":"weight","start":20.32,"end":20.64},{"w":"loss","start":20.64,"end":20.96},{"w":"has","start":20.96,"end":21.12},{"w":"slowed,","start":21.2,"end":21.68},{"w":"but","start":22.56,"end":22.8},{"w":"I","start":23.2,"end":23.28},{"w":"lost","start":23.76,"end":24.08},{"w":"another","start":24.4,"end":24.64},{"w":"pound","start":25.44,"end":25.76},{"w":"and","start":25.84,"end":25.92},{"w":"a","start":25.92,"end":26},{"w":"half,","start":26.08,"end":26.32},{"w":"I","start":26.48,"end":26.64},{"w":"think","start":26.64,"end":26.8},{"w":"last","start":27.04,"end":27.12},{"w":"week.","start":27.36,"end":27.68},{"w":"So","start":28.56,"end":28.72},{"w":"total","start":28.88,"end":29.2},{"w":"loss","start":29.28,"end":29.6},{"w":"now","start":29.68,"end":29.84},{"w":"is","start":29.92,"end":30.08},{"w":"thirty","start":30.16,"end":30.48},{"w":"eight","start":30.64,"end":30.8},{"w":"point","start":30.88,"end":31.04},{"w":"five","start":31.2,"end":31.36},{"w":"pounds.","start":31.52,"end":31.92},{"w":"I","start":32.72,"end":32.8},{"w":"started","start":32.96,"end":33.2},{"w":"at","start":33.2,"end":33.28},{"w":"three","start":33.36,"end":33.44},{"w":"hundred","start":33.52,"end":33.6},{"w":"forty","start":33.68,"end":33.84},{"w":"nine,","start":33.92,"end":34.08},{"w":"I'm","start":34.24,"end":34.48},{"w":"down","start":34.48,"end":34.64},{"w":"to","start":34.64,"end":34.72},{"w":"three","start":34.8,"end":34.88},{"w":"hundred","start":34.96,"end":35.12},{"w":"ten","start":35.12,"end":35.2},{"w":"point","start":35.36,"end":35.52},{"w":"five.","start":35.68,"end":35.84},{"w":"My","start":36.4,"end":36.48},{"w":"goal","start":36.56,"end":36.72},{"w":"is","start":36.88,"end":36.96},{"w":"probably","start":36.96,"end":37.04},{"w":"two","start":37.28,"end":37.36},{"w":"and","start":37.52,"end":37.6},{"w":"a","start":37.6,"end":37.68},{"w":"quarter.","start":37.68,"end":37.92}],"cues":[{"start":2078,"end":2084.72,"text":"I can't figure out the ad too confusing for me but here's a little support in a way I can figure out appreciate the paladin"},{"start":2087.28,"end":2090.88,"text":"basically just go to the Google Play store and download Rumble Wallet"},{"start":2093.84,"end":2096,"text":"if the link's not working and you can't figure that out"},{"start":2098.64,"end":2104.56,"text":"good by the way Jeremy I'm down twenty now from your inspiration dude I'm so proud of you that's amazing"},{"start":2106.96,"end":2108.4,"text":"that's crazy good dude"},{"start":2110.24,"end":2112.96,"text":"I weighed in this morning and the weight loss has slowed"},{"start":2113.76,"end":2115.84,"text":"but I lost another"},{"start":2116.72,"end":2118.96,"text":"pound and a half I think last week"},{"start":2119.84,"end":2123.2,"text":"so total loss now is thirty eight point five pounds"},{"start":2124.24,"end":2127.04,"text":"started at three hundred forty nine I'm down to three hundred ten point five"},{"start":2127.92,"end":2129.84,"text":"my goal is probably two and a quarter"},{"start":2131.12,"end":2138.4,"text":"I'd be I'd be very happy even at two hundred forty even though that would still technically be obese I think or certainly overweight"},{"start":2139.76,"end":2140,"text":"but"},{"start":2140.88,"end":2141.6,"text":"two twenty five"},{"start":2142.4,"end":2142.88,"text":"thirty five"},{"start":2144,"end":2147.92,"text":"which means what I have another seventy five eighty five pounds to lose"},{"start":2149.28,"end":2151.2,"text":"I think I can do that by the end of next year"},{"start":2153.84,"end":2154.88,"text":"by the end of next year."},{"start":2157.36,"end":2159.12,"text":"Melanie's helping me out with some"},{"start":2160.08,"end":2161.2,"text":"I asked her to do some"},{"start":2162.24,"end":2170.24,"text":"by Melanie and I'm still great friends she's helping me out because she sent me a workout list to do like workout exercises"}]},{"id":"c44","channel":"the-quartering-rumble","video":"v7eqa6e","quote":"I am now down fifty point one pounds in eleven weeks and I am under three hundred for the first time since college","window":[618.42,659.16],"words":[{"w":"Oh","start":0,"end":0.08},{"w":"no,","start":0.56,"end":0.64},{"w":"I","start":0.72,"end":0.8},{"w":"didn't","start":0.88,"end":1.12},{"w":"I","start":2.4,"end":2.48},{"w":"shook","start":2.48,"end":2.72},{"w":"up","start":2.72,"end":2.88},{"w":"my","start":2.88,"end":3.04},{"w":"water","start":3.04,"end":3.2},{"w":"and","start":3.28,"end":3.44},{"w":"I","start":3.44,"end":3.6},{"w":"didn't","start":3.6,"end":3.84},{"w":"close","start":3.84,"end":4.16},{"w":"the","start":4.16,"end":4.32},{"w":"top.","start":4.32,"end":4.48},{"w":"That'll","start":4.96,"end":5.44},{"w":"teach","start":5.44,"end":5.76},{"w":"me.","start":5.76,"end":5.92},{"w":"Also,","start":11.6,"end":11.92},{"w":"weight","start":12.72,"end":12.88},{"w":"loss","start":12.96,"end":13.2},{"w":"journey","start":13.28,"end":13.68},{"w":"announcement.","start":13.84,"end":14.32},{"w":"I","start":15.44,"end":15.6},{"w":"am","start":15.6,"end":15.68},{"w":"now","start":15.76,"end":15.92},{"w":"down","start":16,"end":16.24},{"w":"fifty","start":16.4,"end":16.72},{"w":"point","start":16.72,"end":16.88},{"w":"one","start":17.04,"end":17.2},{"w":"pounds","start":17.36,"end":17.76},{"w":"in","start":18.96,"end":19.12},{"w":"eleven","start":19.2,"end":19.44},{"w":"weeks","start":19.6,"end":20},{"w":"and","start":22.08,"end":22.32},{"w":"I","start":22.8,"end":22.88},{"w":"am","start":22.88,"end":23.04},{"w":"under","start":23.12,"end":23.36},{"w":"three","start":23.44,"end":23.6},{"w":"hundred","start":23.6,"end":23.68},{"w":"for","start":24,"end":24.16},{"w":"the","start":24.16,"end":24.24},{"w":"first","start":24.24,"end":24.4},{"w":"time","start":24.4,"end":24.56},{"w":"since","start":24.56,"end":24.88},{"w":"college.","start":24.96,"end":25.44},{"w":"Obviously","start":26.32,"end":26.72},{"w":"I","start":26.8,"end":26.88},{"w":"have","start":26.96,"end":27.04},{"w":"a","start":27.04,"end":27.12},{"w":"long","start":27.2,"end":27.28},{"w":"way","start":27.36,"end":27.52},{"w":"to","start":27.52,"end":27.68},{"w":"go.","start":27.68,"end":27.84},{"w":"I","start":29.44,"end":29.52},{"w":"want","start":29.68,"end":29.84},{"w":"to","start":29.92,"end":30.08},{"w":"get","start":30.08,"end":30.24},{"w":"I","start":30.56,"end":30.64},{"w":"mean,","start":30.72,"end":30.88},{"w":"whatever","start":31.04,"end":31.44},{"w":"the","start":31.44,"end":31.68},{"w":"internet","start":31.68,"end":32.08},{"w":"scales","start":32.16,"end":32.48},{"w":"say","start":32.64,"end":32.72},{"w":"I","start":32.8,"end":32.96},{"w":"should","start":32.96,"end":33.12},{"w":"be","start":33.12,"end":33.2},{"w":"at","start":33.2,"end":33.28},{"w":"like","start":33.44,"end":33.52},{"w":"two","start":33.6,"end":33.76},{"w":"hundred","start":33.76,"end":33.92},{"w":"twenty","start":33.92,"end":34.08},{"w":"at","start":35.2,"end":35.36},{"w":"six.","start":35.44,"end":35.52},{"w":"I","start":37.76,"end":37.92},{"w":"don't","start":37.92,"end":38.16},{"w":"think","start":38.16,"end":38.24},{"w":"I'll","start":38.32,"end":38.56},{"w":"ever","start":38.56,"end":38.64},{"w":"get","start":38.8,"end":38.88},{"w":"to","start":38.88,"end":38.96},{"w":"two","start":39.04,"end":39.12},{"w":"hundred","start":39.12,"end":39.28},{"w":"twenty.","start":39.36,"end":39.52}],"cues":[{"start":603.28,"end":609.92,"text":"it's abundantly obvious that Jeremy adores his animals that's not even in question exactly anybody who actually watches the show you know what I mean like"},{"start":611.04,"end":613.92,"text":"yeah but people create like an alternate reality"},{"start":614.8,"end":619.52,"text":"because I don't know I don't know it gets clicks I guess so no I didn't"},{"start":620.8,"end":624.48,"text":"I shook up my water and I didn't close the top that'll teach me"},{"start":630.08,"end":630.32,"text":"also"},{"start":631.2,"end":632.72,"text":"weight loss journey announcement"},{"start":633.92,"end":636.16,"text":"I am now down fifty point one pounds"},{"start":637.44,"end":638.48,"text":"in eleven weeks"},{"start":640.48,"end":643.76,"text":"and I am under three hundred for the first time since college"},{"start":644.72,"end":646.32,"text":"obviously I have a long way to go"},{"start":647.92,"end":652.56,"text":"I want to get I mean whatever the internet scales say I should be at like two hundred twenty"},{"start":653.6,"end":654,"text":"at six"},{"start":656.24,"end":657.92,"text":"I don't think I'll ever get to twenty"},{"start":658.8,"end":660.8,"text":"but I'd be really happy at like"},{"start":662,"end":669.68,"text":"two thirty two forty so we got another seventy to go so my goal was fifty by Christmas I got there now"},{"start":670.32,"end":670.56,"text":"and"},{"start":672.08,"end":679.6,"text":"you know I'm not going to take the foot off the gas maybe now I can be down fifty five or sixty by Christmas because I have another what"}]},{"id":"c45","channel":"the-quartering-rumble","video":"v7eqa6e","quote":"when I started my weight loss journey I was at almost three hundred ninety pounds so I've lost almost a hundred since starting it.","window":[2294.18,2337.8],"words":[{"w":"A","start":1.52,"end":1.68},{"w":"little","start":1.68,"end":1.84},{"w":"bit","start":1.84,"end":1.92},{"w":"QR","start":2.96,"end":3.28},{"w":"code","start":3.36,"end":3.6},{"w":"too","start":3.68,"end":3.76},{"w":"small.","start":3.84,"end":3.92},{"w":"There","start":4.16,"end":4.24},{"w":"should","start":4.24,"end":4.32},{"w":"be","start":4.4,"end":4.48},{"w":"a","start":4.48,"end":4.56},{"w":"link","start":4.64,"end":4.8},{"w":"in","start":4.88,"end":4.96},{"w":"the","start":4.96,"end":5.04},{"w":"description","start":5.04,"end":5.44},{"w":"you","start":5.52,"end":5.6},{"w":"can","start":5.6,"end":5.68},{"w":"use","start":5.76,"end":5.84},{"w":"too.","start":6,"end":6.16},{"w":"I","start":10.72,"end":10.88},{"w":"think","start":10.88,"end":10.96},{"w":"let","start":12.4,"end":12.56},{"w":"me","start":12.56,"end":12.64},{"w":"go","start":12.8,"end":13.04},{"w":"here.","start":13.04,"end":13.28},{"w":"From","start":15.68,"end":15.84},{"w":"Devin,","start":15.92,"end":16.32},{"w":"congrats","start":16.4,"end":16.96},{"w":"on","start":16.96,"end":17.12},{"w":"being","start":17.12,"end":17.28},{"w":"under","start":17.28,"end":17.44},{"w":"three","start":17.52,"end":17.6},{"w":"hundred","start":17.6,"end":17.68},{"w":"pounds.","start":17.84,"end":18.08},{"w":"People","start":18.24,"end":18.4},{"w":"don't","start":18.48,"end":18.72},{"w":"realize","start":18.72,"end":19.04},{"w":"how","start":19.04,"end":19.2},{"w":"difficult","start":19.2,"end":19.6},{"w":"that","start":19.6,"end":19.68},{"w":"is.","start":19.68,"end":19.76},{"w":"Keep","start":20,"end":20.16},{"w":"it","start":20.16,"end":20.24},{"w":"up","start":20.32,"end":20.4},{"w":"dude.","start":20.48,"end":20.8},{"w":"Well,","start":21.28,"end":21.44},{"w":"you","start":21.68,"end":21.76},{"w":"know,","start":21.84,"end":22},{"w":"I'll","start":22.48,"end":22.8},{"w":"tell","start":22.8,"end":22.96},{"w":"you","start":22.96,"end":23.04},{"w":"this,","start":23.12,"end":23.28},{"w":"it's","start":23.36,"end":23.68},{"w":"very","start":23.68,"end":23.92},{"w":"easy","start":23.92,"end":24.08},{"w":"to","start":24.16,"end":24.24},{"w":"get","start":24.24,"end":24.4},{"w":"over","start":24.4,"end":24.56},{"w":"three","start":24.72,"end":24.88},{"w":"hundred.","start":24.88,"end":24.96},{"w":"When","start":29.12,"end":29.28},{"w":"I","start":29.28,"end":29.44},{"w":"started","start":29.44,"end":29.68},{"w":"my","start":29.68,"end":29.84},{"w":"weight","start":29.84,"end":30},{"w":"loss","start":30.08,"end":30.32},{"w":"journey,","start":30.4,"end":30.8},{"w":"I","start":30.96,"end":31.12},{"w":"was","start":31.12,"end":31.28},{"w":"at","start":31.28,"end":31.44},{"w":"almost","start":31.6,"end":31.92},{"w":"three","start":32,"end":32.08},{"w":"hundred","start":32.24,"end":32.4},{"w":"ninety","start":32.56,"end":32.88},{"w":"pounds.","start":32.88,"end":33.28},{"w":"So","start":34.24,"end":34.4},{"w":"I've","start":34.4,"end":34.72},{"w":"lost","start":34.72,"end":34.88},{"w":"almost","start":35.04,"end":35.28},{"w":"a","start":35.44,"end":35.52},{"w":"hundred","start":35.52,"end":35.6},{"w":"since","start":35.92,"end":36.08},{"w":"starting","start":36.16,"end":36.32},{"w":"it.","start":36.4,"end":36.48},{"w":"I","start":36.64,"end":36.8},{"w":"started","start":36.8,"end":37.04},{"w":"it","start":37.04,"end":37.2},{"w":"with","start":37.2,"end":37.36},{"w":"intermittent","start":37.36,"end":37.84},{"w":"fasting","start":38,"end":38.48},{"w":"to","start":39.04,"end":39.2},{"w":"get","start":39.2,"end":39.36},{"w":"down","start":39.36,"end":39.44},{"w":"to","start":39.6,"end":39.68},{"w":"whatever","start":39.92,"end":40.24},{"w":"I","start":40.32,"end":40.4},{"w":"was","start":40.4,"end":40.48},{"w":"at","start":40.56,"end":40.64},{"w":"three","start":40.8,"end":40.88},{"w":"hundred","start":40.96,"end":41.04},{"w":"fifty","start":41.12,"end":41.36},{"w":"something","start":41.44,"end":41.52},{"w":"and","start":42.48,"end":42.56},{"w":"I","start":42.64,"end":42.72},{"w":"fell","start":42.8,"end":42.96},{"w":"off","start":42.96,"end":43.04},{"w":"the","start":43.2,"end":43.28},{"w":"weight.","start":43.28,"end":43.36}],"cues":[{"start":2273.28,"end":2277.76,"text":"shout out to the six thousand wonderful people in viewing right now"},{"start":2279.04,"end":2280.4,"text":"I know news is a little bit"},{"start":2282.08,"end":2286.8,"text":"a little bit QR code is too small there should be a link in the description you can use too"},{"start":2291.36,"end":2291.6,"text":"I think"},{"start":2293.04,"end":2293.92,"text":"let me go here"},{"start":2296.32,"end":2304.32,"text":"from Devin congrats on being under three hundred pounds people don't realize how difficult that is keep it up dude. Well you know I'll tell you this it's"},{"start":2304.32,"end":2305.76,"text":"very easy to get over three hundred"},{"start":2309.68,"end":2314,"text":"when I started my weight loss journey I was at almost three hundred ninety pounds"},{"start":2314.96,"end":2322.4,"text":"so I've lost almost a hundred since starting it. I started it with intermittent fasting to get down to whatever I was at three hundred fifty something"},{"start":2323.36,"end":2325.84,"text":"and then I fell off the wagon so then I started"},{"start":2327.52,"end":2331.2,"text":"intermittent fasting plus keto plus walking"},{"start":2332.4,"end":2340.32,"text":"and I lost another fifty I've got seventy to go or so hopefully I don't look all old when I lose the weight that'll be the bummer"},{"start":2342.56,"end":2350.16,"text":"like look what happened to John Goodman when he lost the weight look what happened to who's the fat funny guy"},{"start":2351.12,"end":2351.84,"text":"Jonah Hill"},{"start":2352.72,"end":2356.08,"text":"he lost that weight and he looks thirty years older"}]},{"id":"c20","channel":"the-quartering-rumble","video":"v6pmznn","quote":"I promise you, by this time next year I will be down 100 pounds","window":[7486.82,7506.74],"words":[{"w":"Damn,","start":1.12,"end":1.44},{"w":"he","start":1.6,"end":1.68},{"w":"is","start":2,"end":2.08},{"w":"eighty.","start":2.16,"end":2.4},{"w":"Is","start":2.8,"end":2.88},{"w":"he","start":3.04,"end":3.12},{"w":"seventy","start":3.28,"end":3.44},{"w":"nine?","start":3.52,"end":3.68},{"w":"He","start":3.92,"end":4},{"w":"actually","start":4,"end":4.08},{"w":"does","start":4.16,"end":4.24},{"w":"look","start":4.32,"end":4.4},{"w":"good.","start":4.56,"end":4.64},{"w":"He","start":5.04,"end":5.12},{"w":"looks","start":5.2,"end":5.36},{"w":"nine.","start":5.36,"end":5.44},{"w":"Great.","start":6,"end":6.16},{"w":"Yeah,","start":6.4,"end":6.48},{"w":"holy","start":6.8,"end":7.04},{"w":"crap.","start":7.2,"end":7.52},{"w":"What","start":7.84,"end":7.92},{"w":"a","start":8,"end":8.08},{"w":"miracle","start":8.08,"end":8.4},{"w":"genetics.","start":8.48,"end":8.88},{"w":"Imagine","start":9.12,"end":9.6},{"w":"if","start":9.68,"end":9.76},{"w":"he","start":9.76,"end":9.84},{"w":"wasn't","start":9.84,"end":10.32},{"w":"fat.","start":10.32,"end":10.48},{"w":"Well,","start":10.8,"end":10.88},{"w":"yeah,","start":11.2,"end":11.28},{"w":"what'll","start":11.52,"end":11.84},{"w":"happen","start":11.84,"end":11.92},{"w":"though","start":12,"end":12.16},{"w":"is","start":12.24,"end":12.32},{"w":"like,","start":12.4,"end":12.48},{"w":"you'll","start":12.56,"end":12.8},{"w":"see,","start":12.8,"end":12.88},{"w":"I","start":13.04,"end":13.12},{"w":"promise","start":13.2,"end":13.52},{"w":"you","start":13.6,"end":13.68},{"w":"by","start":13.84,"end":14},{"w":"this","start":14,"end":14.08},{"w":"time","start":14.08,"end":14.24},{"w":"next","start":14.24,"end":14.32},{"w":"year","start":14.48,"end":14.64},{"w":"I","start":14.72,"end":14.8},{"w":"will","start":14.8,"end":14.96},{"w":"be","start":15.04,"end":15.12},{"w":"down","start":15.12,"end":15.2},{"w":"one","start":15.36,"end":15.44},{"w":"hundred","start":15.44,"end":15.52},{"w":"pounds","start":15.6,"end":15.92},{"w":"and","start":16,"end":16.16},{"w":"I'll","start":16.16,"end":16.4},{"w":"look","start":16.4,"end":16.56},{"w":"ten","start":16.56,"end":16.72},{"w":"years","start":16.72,"end":16.88},{"w":"older.","start":16.88,"end":17.28},{"w":"Like","start":17.52,"end":17.6},{"w":"there's","start":17.84,"end":18.08},{"w":"something","start":18.08,"end":18.16},{"w":"that","start":18.24,"end":18.32},{"w":"happens","start":18.32,"end":18.56},{"w":"when","start":18.64,"end":18.8},{"w":"big","start":18.88,"end":18.96},{"w":"guys","start":19.04,"end":19.12},{"w":"lose","start":19.28,"end":19.44},{"w":"weight.","start":19.52,"end":19.76}],"cues":[{"start":7463.1,"end":7469.34,"text":"you can still do cardio in a wheelchair, you can do you can do a lot of stuff in a wheelchair."},{"start":7469.34,"end":7477.9,"text":"So I mean, you know, I don't really do looks pretty good for 80. He's not 80. No, if he's 80,"},{"start":7477.9,"end":7484.7,"text":"then he looks great. I know. Can I say he's 80? There's no way. Damn, he is 80."},{"start":7484.7,"end":7489.82,"text":"He's 79. He actually does look the first. He looks great. Yeah. Holy crap."},{"start":7489.82,"end":7494.62,"text":"Miracle genetics. Imagine if he wasn't fat. Well, yeah, what will happen though is like,"},{"start":7494.62,"end":7498.86,"text":"you'll see, I promise you by this time next year, I will be down 100 pounds and I'll look 10 years"},{"start":7498.86,"end":7503.74,"text":"older. Like there's something that happens when big guys lose weight, you know, it's worth it."},{"start":7503.74,"end":7510.06,"text":"Yeah. Yeah. It's worth it. Yeah. Also, the thing is, though, is you don't carry a lot of weight"},{"start":7510.06,"end":7515.9,"text":"in your face, though. No, that might be okay. I because yeah, I don't think you're going to have"},{"start":7515.9,"end":7522.38,"text":"a ton of problems. Yeah, it'll be all right. Yeah, I take it all back. This guy's killing it."},{"start":7522.38,"end":7531.18,"text":"Like, I don't care if he is 400 pounds. He's 80 years old, like, slay king. Yeah."}]},{"id":"k46","channel":"the-quartering-rumble","video":"v6qogub","quote":"My goal is to lose 100 pounds by Christmas. Trust me, I have a plan and I'm going to try to stick to it.","window":[810.52,854.42],"words":[{"w":"in","start":1.12,"end":1.2},{"w":"April.","start":1.2,"end":1.52},{"w":"I","start":1.68,"end":1.76},{"w":"lost","start":1.84,"end":2},{"w":"about","start":2.08,"end":2.24},{"w":"ten","start":2.24,"end":2.32},{"w":"pounds","start":2.4,"end":2.72},{"w":"in","start":2.8,"end":2.88},{"w":"April.","start":2.88,"end":3.28},{"w":"My","start":4.8,"end":4.96},{"w":"goal","start":4.96,"end":5.2},{"w":"is","start":5.2,"end":5.28},{"w":"to","start":5.36,"end":5.44},{"w":"lose","start":5.52,"end":5.68},{"w":"one","start":5.76,"end":5.92},{"w":"hundred","start":5.92,"end":6.08},{"w":"pounds","start":6.16,"end":6.48},{"w":"by","start":6.56,"end":6.72},{"w":"Christmas.","start":6.72,"end":7.28},{"w":"I","start":7.92,"end":8.08},{"w":"know","start":8.08,"end":8.24},{"w":"that's","start":8.4,"end":8.64},{"w":"a","start":8.64,"end":8.8},{"w":"lot","start":8.8,"end":8.96},{"w":"and","start":9.36,"end":9.52},{"w":"generally","start":9.52,"end":9.84},{"w":"that","start":10,"end":10.16},{"w":"triggers","start":10.16,"end":10.4},{"w":"everyone","start":10.56,"end":10.88},{"w":"giving","start":10.96,"end":11.28},{"w":"unsolicited","start":11.28,"end":11.92},{"w":"health","start":12.16,"end":12.48},{"w":"advice.","start":12.56,"end":13.04},{"w":"Trust","start":15.2,"end":15.52},{"w":"me,","start":15.52,"end":15.6},{"w":"I","start":16.48,"end":16.56},{"w":"have","start":16.72,"end":16.88},{"w":"a","start":16.88,"end":17.04},{"w":"plan","start":17.04,"end":17.28},{"w":"and","start":17.76,"end":18},{"w":"I'm","start":18.64,"end":18.88},{"w":"going","start":18.96,"end":19.04},{"w":"to","start":19.04,"end":19.12},{"w":"try","start":19.2,"end":19.36},{"w":"to","start":19.36,"end":19.52},{"w":"stick","start":19.52,"end":19.68},{"w":"to","start":19.68,"end":19.84},{"w":"it.","start":19.84,"end":19.92},{"w":"So","start":20.08,"end":20.16},{"w":"one","start":20.32,"end":20.4},{"w":"hundred","start":20.4,"end":20.48},{"w":"pounds","start":20.64,"end":20.96},{"w":"by","start":21.12,"end":21.28},{"w":"Christmas.","start":21.36,"end":21.92},{"w":"That's","start":22.72,"end":23.12},{"w":"roughly","start":23.92,"end":24.48},{"w":"ten","start":24.96,"end":25.12},{"w":"or","start":25.52,"end":25.68},{"w":"fifteen","start":25.76,"end":26.08},{"w":"pounds","start":26.16,"end":26.48},{"w":"a","start":26.64,"end":26.72},{"w":"month.","start":26.72,"end":27.04},{"w":"When","start":27.76,"end":27.84},{"w":"you're","start":27.92,"end":28.08},{"w":"one","start":28.16,"end":28.24},{"w":"hundred","start":28.24,"end":28.32},{"w":"pounds","start":28.48,"end":28.72},{"w":"overweight,","start":28.8,"end":29.28},{"w":"I","start":29.44,"end":29.6},{"w":"should","start":29.6,"end":29.76},{"w":"be","start":29.76,"end":29.84},{"w":"able","start":29.92,"end":30.08},{"w":"to","start":30.08,"end":30.24},{"w":"do","start":30.24,"end":30.32},{"w":"it.","start":30.32,"end":30.48},{"w":"It","start":30.72,"end":30.88},{"w":"should","start":30.88,"end":31.04},{"w":"be","start":31.12,"end":31.28},{"w":"close.","start":31.28,"end":31.6},{"w":"And","start":33.28,"end":33.44},{"w":"last","start":33.52,"end":33.68},{"w":"month","start":33.68,"end":33.92},{"w":"I","start":34,"end":34.08},{"w":"was","start":34.16,"end":34.32},{"w":"only","start":34.32,"end":34.48},{"w":"like","start":34.64,"end":34.8},{"w":"half","start":35.04,"end":35.28},{"w":"assinant.","start":35.68,"end":36.32},{"w":"Actually,","start":36.64,"end":36.96},{"w":"I","start":37.04,"end":37.12},{"w":"was","start":37.12,"end":37.2},{"w":"like","start":37.28,"end":37.36},{"w":"quarter","start":37.44,"end":37.76},{"w":"assinant","start":37.92,"end":38.4},{"w":"last","start":38.56,"end":38.72},{"w":"week.","start":38.8,"end":39.04},{"w":"Quarter","start":39.36,"end":39.76},{"w":"assin.","start":40,"end":40.48}],"cues":[{"start":784.02,"end":795.02,"text":"Like, everyone just automatically leaves a like on the video when they get in here. Let's get on that homepage and see if we can start finding some new people."},{"start":795.02,"end":803.02,"text":"Same thing I try to do every weekend. Take over the world. That's right. So, what do I got going on?"},{"start":803.02,"end":816.02,"text":"I had a doctor's appointment this morning for my foot. Everything looks good. It's healing. I've lost 10 pounds in April. I lost about 10 pounds in April."},{"start":816.02,"end":826.02,"text":"My goal is to lose 100 pounds by Christmas. I know that's a lot. And generally that triggers everyone giving unsolicited health advice."},{"start":826.02,"end":839.02,"text":"Trust me, I have a plan and I'm going to try to stick to it. So 100 pounds by Christmas. That's roughly 10 or 15 pounds a month."},{"start":839.02,"end":844.02,"text":"When you're 100 pounds overweight, I should be able to do it. It should be close."},{"start":844.02,"end":853.02,"text":"And last month, I was only like half-assen it. Actually, I was like quarter-assen it last week. Quarter-assen?"},{"start":853.02,"end":861.02,"text":"Because, you know, my foot was hurt and I had to stop working out for the last week."},{"start":861.02,"end":869.02,"text":"I hope Jeremy's coffee can be survived. I don't buy it, but it's cool. He thinks, well, yeah, I'm going to talk about that later. I think I'm going to do a little."},{"start":869.02,"end":881.02,"text":"I was thinking about putting out some sort of contest like I'll shave my head if we just break even."}]}]}
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -28,6 +28,8 @@
"./reframe": "./reframe.mjs",
"./side-card": "./side-card.mjs",
"./check-availability": "./check-availability.mjs",
+ "./recording-ids": "./recording-ids.mjs",
+ "./quote-in-audio": "./quote-in-audio.mjs",
"./check-joins": "./check-joins.mjs",
"./chunked-encode": "./chunked-encode.mjs",
"./claims": "./claims.mjs",
diff --git a/umtool/report-to-video/quote-in-audio.mjs b/umtool/report-to-video/quote-in-audio.mjs
@@ -0,0 +1,378 @@
+// quote-in-audio — IS THE QUOTE IN THE SECONDS THE CLIP PLAYS? (lane one-clock)
+//
+// The per-clip guarantee the operator's ear was giving: transcribe what the
+// render will actually play (the clip's source window, words timed), find the
+// clip's `quote` in those words, and say how far from the cue clock's seconds
+// it is. On 6 Nov seven Rumble clips played other words than their quotes
+// (c43 +13.1 s: the 9:18 "310" misclip, c45 +13.6 s, c20 +5.2 s, k41 +2.6 s,
+// c18 +1.6 s, k46 −0.7 s, c19 ≈ −1 s) and only listening caught it.
+//
+// THE MATCH is loose on purpose: the quote is prose a person wrote about speech
+// a machine transcribed. Case, punctuation, `[bracketed]` editorial words and
+// apostrophes go; NUMBERS are one token however they are written ("thirty eight
+// point five" = "38.5", "a hundred" = "100", "three hundred ten point five" =
+// "310.5"); a word one letter off still counts ("weighed"/"waited" does not —
+// two letters). An ellipsis splits the quote into fragments found in order. The
+// alignment is a local one (Smith–Waterman over tokens), so a quote that starts
+// a word early or runs past the window is still found by its middle.
+//
+// Pure. The transcription is the caller's (lib/report/quoteCheck.mjs asks the
+// editor's transcribe op); words arrive on the CUE clock.
+
+const ONES = {
+ zero: 0, oh: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10,
+ eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18, nineteen: 19,
+};
+const TENS = { twenty: 20, thirty: 30, forty: 40, fourty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90 };
+const DIGIT_WORDS = { zero: "0", oh: "0", one: "1", two: "2", three: "3", four: "4", five: "5", six: "6", seven: "7", eight: "8", nine: "9" };
+
+/** The minimum share of the quote's tokens a match must align to be FOUND. */
+export const MIN_MATCH = 0.6;
+/** Within this many seconds of the cue clock, a found quote is where the clip says. */
+export const ON_TIME_S = 0.5;
+
+/**
+ * Raw word tokens of a text: lower case, no `[bracketed]` editorial, no
+ * apostrophes, digits with their decimal point and thousands commas folded.
+ * @param {string} text
+ * @returns {string[]}
+ */
+export function rawTokens(text) {
+ return String(text ?? "")
+ .toLowerCase()
+ .replace(/\[[^\]]*\]/g, " ")
+ .replace(/(\d),(\d{3})\b/g, "$1$2")
+ .replace(/%/g, " percent ")
+ .replace(/[’'`]/g, "")
+ .replace(/(\d)\.(\d)/g, "$1\u0000$2")
+ .replace(/[^a-z0-9\u0000]+/g, " ")
+ .replace(/\u0000/g, ".")
+ .split(" ")
+ .filter(Boolean);
+}
+
+/**
+ * Fold every run of number words into one numeric token, keeping which raw
+ * tokens each output token came from.
+ * @param {string[]} toks
+ * @returns {{ t: string, from: number, to: number }[]} `from`/`to`: raw token indexes (inclusive)
+ */
+export function foldNumbers(toks) {
+ const out = [];
+ let i = 0;
+ while (i < toks.length) {
+ const w = toks[i];
+ const startsNumber = w in ONES || w in TENS || (w === "a" && toks[i + 1] === "hundred");
+ if (!startsNumber) {
+ out.push({ t: w, from: i, to: i });
+ i += 1;
+ continue;
+ }
+ let total = 0;
+ let cur = 0;
+ let j = i;
+ let lastKind = "";
+ for (; j < toks.length; j += 1) {
+ const x = toks[j];
+ if (x in ONES) {
+ // "twenty twenty one", "five five": a second small number starts anew.
+ if (lastKind === "one" || (lastKind === "ten" && ONES[x] >= 10)) break;
+ cur += ONES[x];
+ lastKind = "one";
+ } else if (x in TENS) {
+ if (lastKind === "one" || lastKind === "ten") break;
+ cur += TENS[x];
+ lastKind = "ten";
+ } else if (x === "a" && toks[j + 1] === "hundred" && lastKind === "") {
+ cur = 1;
+ lastKind = "a";
+ } else if (x === "hundred" && (lastKind === "one" || lastKind === "a" || lastKind === "ten")) {
+ cur = (cur || 1) * 100;
+ lastKind = "hundred";
+ } else if (x === "thousand" && lastKind !== "") {
+ total += (cur || 1) * 1000;
+ cur = 0;
+ lastKind = "thousand";
+ } else if (x === "and" && (lastKind === "hundred" || lastKind === "thousand") && (toks[j + 1] in ONES || toks[j + 1] in TENS)) {
+ lastKind = "and";
+ } else break;
+ }
+ let value = String(total + cur);
+ let end = j - 1;
+ // "point five", "point one five": decimals digit by digit.
+ if (toks[j] === "point" && toks[j + 1] in DIGIT_WORDS) {
+ let k = j + 1;
+ let dec = "";
+ while (k < toks.length && toks[k] in DIGIT_WORDS) {
+ dec += DIGIT_WORDS[toks[k]];
+ k += 1;
+ }
+ value = `${value}.${dec}`;
+ end = k - 1;
+ j = k;
+ }
+ if (end < i) {
+ out.push({ t: w, from: i, to: i });
+ i += 1;
+ continue;
+ }
+ out.push({ t: value, from: i, to: end });
+ i = end + 1;
+ }
+ return out;
+}
+
+/** A text as match tokens. @param {string} text @returns {string[]} */
+export const quoteTokens = (text) => foldNumbers(rawTokens(text)).map((x) => x.t);
+
+/**
+ * Timed words as match tokens: each token keeps the start of its first word and
+ * the end of its last.
+ * @param {{ w?: string, text?: string, start: number, end: number }[]} words
+ * @returns {{ t: string, start: number, end: number }[]}
+ */
+export function timedTokens(words) {
+ const raw = [];
+ for (const w of words ?? []) {
+ rawTokens(w.w ?? w.text ?? "").forEach((t, k) =>
+ raw.push({ t, start: Number(w.start), end: Number(w.end), anchor: k === 0 && w.anchor === true }),
+ );
+ }
+ return foldNumbers(raw.map((r) => r.t)).map((x) => ({
+ t: x.t,
+ start: raw[x.from].start,
+ end: raw[x.to].end,
+ ...(raw[x.from].anchor ? { anchor: true } : {}),
+ }));
+}
+
+function lev1(a, b) {
+ if (a === b) return true;
+ if (a.length < 4 || b.length < 4 || Math.abs(a.length - b.length) > 1) return false;
+ let i = 0;
+ let j = 0;
+ let edits = 0;
+ while (i < a.length && j < b.length) {
+ if (a[i] === b[j]) {
+ i += 1;
+ j += 1;
+ continue;
+ }
+ edits += 1;
+ if (edits > 1) return false;
+ if (a.length > b.length) i += 1;
+ else if (b.length > a.length) j += 1;
+ else {
+ i += 1;
+ j += 1;
+ }
+ }
+ return edits + (a.length - i) + (b.length - j) <= 1;
+}
+
+/** Same token: equal, a near spelling, or one number written two ways ("40" / "40.0"). */
+export function sameToken(a, b) {
+ if (a === b) return true;
+ const na = Number(a);
+ const nb = Number(b);
+ if (/^\d/.test(a) && /^\d/.test(b) && Number.isFinite(na) && na === nb) return true;
+ return lev1(a, b);
+}
+
+/**
+ * The best LOCAL alignment of `q` inside `w` (Smith–Waterman: match +2,
+ * mismatch −1, gap −1), searching from `w[from]` on.
+ * @param {string[]} q
+ * @param {{ t: string }[]} w
+ * @param {number} [from]
+ * @returns {{ pairs: [number, number][], score: number }} pairs: [q index, w index], in order
+ */
+export function alignLocal(q, w, from = 0) {
+ const n = q.length;
+ const m = w.length - from;
+ if (!n || m <= 0) return { pairs: [], score: 0 };
+ const H = Array.from({ length: n + 1 }, () => new Float64Array(m + 1));
+ const B = Array.from({ length: n + 1 }, () => new Uint8Array(m + 1)); // 1 diag, 2 up, 3 left
+ let best = 0;
+ let bi = 0;
+ let bj = 0;
+ for (let i = 1; i <= n; i += 1) {
+ for (let j = 1; j <= m; j += 1) {
+ const match = sameToken(q[i - 1], w[from + j - 1].t);
+ const d = H[i - 1][j - 1] + (match ? 2 : -1);
+ const u = H[i - 1][j] - 1;
+ const l = H[i][j - 1] - 1;
+ let v = 0;
+ let b = 0;
+ if (d > v) [v, b] = [d, 1];
+ if (u > v) [v, b] = [u, 2];
+ if (l > v) [v, b] = [l, 3];
+ H[i][j] = v;
+ B[i][j] = b;
+ if (v > best) [best, bi, bj] = [v, i, j];
+ }
+ }
+ const pairs = [];
+ let i = bi;
+ let j = bj;
+ while (i > 0 && j > 0 && H[i][j] > 0) {
+ const b = B[i][j];
+ if (b === 1) {
+ if (sameToken(q[i - 1], w[from + j - 1].t)) pairs.push([i - 1, from + j - 1]);
+ i -= 1;
+ j -= 1;
+ } else if (b === 2) i -= 1;
+ else if (b === 3) j -= 1;
+ else break;
+ }
+ pairs.reverse();
+ return { pairs, score: best };
+}
+
+/**
+ * Find a clip's quote in timed words (CUE clock).
+ *
+ * @param {string} quote
+ * @param {{ w?: string, text?: string, start: number, end: number }[]} words
+ * @param {{ expectedStart?: number | null, expectedEnd?: number | null, minMatch?: number }} [opts]
+ * `expectedStart`/`expectedEnd`: where the clip says the quote is (its
+ * quoteStart/quoteEnd, else its cut, else its extent) — the offset is
+ * measured from there.
+ * @returns {{
+ * found: boolean, match: number, tokens: number, matched: number,
+ * from: number | null, to: number | null, offset: number | null,
+ * fragments: { text: string, match: number, from: number | null, to: number | null }[],
+ * pairs: { q: number, start: number, end: number, anchor?: boolean }[],
+ * heard: string,
+ * }}
+ * `pairs`: each matched quote token (its index in the whole quote) and the
+ * seconds it was heard at — what quoteOffset compares two findings by.
+ */
+export function findQuote(quote, words, { expectedStart = null, expectedEnd = null, minMatch = MIN_MATCH } = {}) {
+ const w = timedTokens(words);
+ const frags = String(quote ?? "")
+ .split(/\.{3}|…/)
+ .map((f) => f.trim())
+ .filter((f) => quoteTokens(f).length);
+ const total = frags.reduce((n, f) => n + quoteTokens(f).length, 0);
+ const fragments = [];
+ const timed = [];
+ let after = 0;
+ let matched = 0;
+ let first = null;
+ let firstQ = 0;
+ let last = null;
+ let base = 0;
+ for (const f of frags) {
+ const q = quoteTokens(f);
+ const { pairs } = alignLocal(q, w, after);
+ const share = q.length ? pairs.length / q.length : 0;
+ for (const [qi, wi] of pairs) {
+ timed.push({ q: base + qi, start: w[wi].start, end: w[wi].end, ...(w[wi].anchor ? { anchor: true } : {}) });
+ }
+ base += q.length;
+ if (!pairs.length) {
+ fragments.push({ text: f, match: 0, from: null, to: null });
+ continue;
+ }
+ matched += pairs.length;
+ const a = w[pairs[0][1]];
+ const b = w[pairs[pairs.length - 1][1]];
+ fragments.push({ text: f, match: round2(share), from: a.start, to: b.end });
+ if (first === null) {
+ first = a;
+ // How far into the whole quote the first matched token is.
+ firstQ = fragments.length === 1 ? pairs[0][0] : 0;
+ }
+ last = b;
+ after = pairs[pairs.length - 1][1] + 1;
+ }
+ const share = total ? matched / total : 0;
+ // Short quotes (under four tokens) must match whole.
+ const need = total < 4 ? 1 : minMatch;
+ const found = share >= need && first !== null;
+ let offset = null;
+ if (found && Number.isFinite(expectedStart)) {
+ // The expected second of the first MATCHED token: the quote's own span,
+ // shared out by token, when the clip says where it ends too.
+ const span = Number.isFinite(expectedEnd) && expectedEnd > expectedStart ? expectedEnd - expectedStart : 0;
+ const at = expectedStart + (total ? (span * firstQ) / total : 0);
+ offset = round2(first.start - at);
+ }
+ const heard = w
+ .filter((x) => found && x.start >= (first?.start ?? 0) - 0.01 && x.end <= (last?.end ?? 0) + 0.01)
+ .map((x) => x.t)
+ .join(" ");
+ return {
+ found,
+ match: round2(share),
+ tokens: total,
+ matched,
+ from: found ? first.start : null,
+ to: found ? last.end : null,
+ offset,
+ fragments,
+ pairs: found ? timed : [],
+ heard,
+ };
+}
+
+/**
+ * How far the quote was HEARD from where the CUES have it: the median, over the
+ * quote's tokens both found, of heard − cued. Null when they share none.
+ * @param {{ pairs: { q: number, start: number }[] }} heard
+ * @param {{ pairs: { q: number, start: number }[] }} cued
+ */
+export function quoteOffset(heard, cued) {
+ // A cue's FIRST word is timed exactly (the cue starts on it); the words after
+ // it are spread over the cue and can be seconds off where the speaker paused
+ // inside one. The exact ones decide when the quote shares any.
+ const exact = cued.pairs.filter((p) => p.anchor);
+ const use = heard.pairs.some((h) => exact.some((c) => c.q === h.q)) ? exact : cued.pairs;
+ const at = new Map(use.map((p) => [p.q, p.start]));
+ const d = heard.pairs.filter((p) => at.has(p.q)).map((p) => p.start - /** @type {number} */ (at.get(p.q)));
+ if (!d.length) return null;
+ d.sort((a, b) => a - b);
+ const mid = d.length >> 1;
+ return round2(d.length % 2 ? d[mid] : (d[mid - 1] + d[mid]) / 2);
+}
+
+/**
+ * Cues as timed words: each cue's words spread over its span by their length
+ * (a cue carries no word timings; this is good to a fraction of a second, and
+ * the offsets that matter are seconds).
+ * @param {{ start: number, end: number, text: string }[]} cues
+ * @param {{ from?: number, to?: number }} [span] only the cues overlapping it
+ * @returns {{ w: string, start: number, end: number, anchor?: boolean }[]} `anchor`: a
+ * cue's first word, timed exactly
+ */
+export function cueWords(cues, { from = -Infinity, to = Infinity } = {}) {
+ const out = [];
+ for (const c of cues ?? []) {
+ const s = Number(c.start);
+ const e = Number(c.end);
+ if (!(e >= from && s <= to)) continue;
+ const ws = String(c.text ?? "").split(/\s+/).filter(Boolean);
+ const total = ws.reduce((n, x) => n + x.length + 1, 0);
+ let at = s;
+ ws.forEach((x, k) => {
+ const d = total ? ((e - s) * (x.length + 1)) / total : 0;
+ out.push({ w: x, start: round2(at), end: round2(at + d), ...(k === 0 ? { anchor: true } : {}) });
+ at += d;
+ });
+ }
+ return out;
+}
+
+const round2 = (x) => Math.round(x * 100) / 100;
+
+/**
+ * The verdict for a found (or not) quote: `ok` within ON_TIME_S of the cue
+ * clock, `moved` further, `not-found`.
+ * @param {ReturnType<typeof findQuote>} r
+ */
+export function quoteStatus(r, onTime = ON_TIME_S) {
+ if (!r.found) return "not-found";
+ if (r.offset !== null && Math.abs(r.offset) > onTime) return "moved";
+ return "ok";
+}
diff --git a/umtool/report-to-video/quote-in-audio.test.mjs b/umtool/report-to-video/quote-in-audio.test.mjs
@@ -0,0 +1,94 @@
+// quote-in-audio.mjs (lane one-clock): numbers however written, fragments in
+// order, and the offsets the rev9-a3 pass measured by ear and by hand — from
+// the parakeet words of the windows that were fetched on 6 Nov and the cues
+// they were cut by (fixtures/rev9-a3-rumble-words.json).
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import path from "node:path";
+import {
+ cueWords,
+ findQuote,
+ foldNumbers,
+ quoteOffset,
+ quoteStatus,
+ quoteTokens,
+ rawTokens,
+ sameToken,
+} from "./quote-in-audio.mjs";
+
+const FIX = JSON.parse(
+ readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "fixtures", "rev9-a3-rumble-words.json"), "utf8"),
+);
+
+test("numbers are one token however they are written", () => {
+ assert.deepEqual(quoteTokens("thirty eight point five pounds"), ["38.5", "pounds"]);
+ assert.deepEqual(quoteTokens("I'm down to 310.5"), ["im", "down", "to", "310.5"]);
+ assert.deepEqual(quoteTokens("three hundred ten point five"), ["310.5"]);
+ assert.deepEqual(quoteTokens("a hundred and ten"), ["110"]);
+ assert.deepEqual(quoteTokens("lose about one hundred pounds"), ["lose", "about", "100", "pounds"]);
+ assert.deepEqual(quoteTokens("1,000 [sic] people, 17%"), ["1000", "people", "17", "percent"]);
+ assert.deepEqual(quoteTokens("fifty point one pounds in eleven weeks"), ["50.1", "pounds", "in", "11", "weeks"]);
+ // "twenty twenty one" is two numbers, not 41.
+ assert.deepEqual(quoteTokens("twenty twenty one"), ["20", "21"]);
+ assert.deepEqual(foldNumbers(rawTokens("down twenty now")), [
+ { t: "down", from: 0, to: 0 },
+ { t: "20", from: 1, to: 1 },
+ { t: "now", from: 2, to: 2 },
+ ]);
+ assert.equal(sameToken("40", "40.0"), true);
+ assert.equal(sameToken("weighed", "weighd"), true);
+ assert.equal(sameToken("weighed", "waited"), false);
+});
+
+const words = (list, t0 = 0) =>
+ list.split(" ").map((w, i) => ({ w, start: t0 + i * 0.4, end: t0 + i * 0.4 + 0.3 }));
+
+test("a quote with its numbers mangled both ways is found where it was said", () => {
+ const heard = words("so total loss now is thirty eight point five pounds I started at three hundred forty nine I'm down to three hundred ten point five my goal", 100);
+ const r = findQuote("total loss now is 38.5 pounds, started at 349, I'm down to 310.5", heard, { expectedStart: 100.4 });
+ assert.equal(r.found, true);
+ assert.equal(r.match >= 0.9, true, String(r.match));
+ assert.equal(r.from, 100.4);
+ assert.equal(r.offset, 0);
+ assert.equal(quoteStatus(r), "ok");
+});
+
+test("an ellipsis: fragments found in order; a quote that is not there is not found", () => {
+ const heard = words("I have begun what is commonly referred to as dry January which only about 17 percent of people can complete I've also begun intermittent fasting today", 10);
+ const r = findQuote("I have begun what is commonly referred to as dry January... I've also begun intermittent fasting today.", heard);
+ assert.equal(r.found, true);
+ assert.equal(r.fragments.length, 2);
+ assert.ok(r.fragments.every((f) => f.match === 1));
+ const miss = findQuote("I promise you, by this time next year I will be down 100 pounds", heard);
+ assert.equal(miss.found, false);
+ assert.equal(quoteStatus(miss), "not-found");
+ // Short quotes match whole or not at all.
+ assert.equal(findQuote("dry February", heard).found, false);
+});
+
+test("cue words: a cue's words spread over it, its first word exact", () => {
+ const w = cueWords([{ start: 10, end: 12, text: "a bb ccc" }, { start: 20, end: 21, text: "x" }], { from: 0, to: 15 });
+ assert.deepEqual(w.map((x) => [x.w, x.start, x.anchor ?? false]), [["a", 10, true], ["bb", 10.44, false], ["ccc", 11.11, false]]);
+});
+
+// THE 6 NOV WINDOWS. Heard = the window's words on the cue clock (window start
+// + the file's seconds); cued = the same quote found in the cues. The editing
+// agent's offsets: c43 +13.1, c45 +13.6, c20 +5.2, k46 -0.7, c44 0.
+const EXPECTED = { c43: [13.1, 0.15], c45: [13.6, 0.15], c20: [5.2, 0.5], k46: [-0.7, 0.3], c44: [0, 0.15] };
+
+for (const clip of FIX.clips) {
+ test(`rev9-a3 ${clip.id} (${clip.channel}/${clip.video}): the quote is heard ${EXPECTED[clip.id][0]} s from its cues`, () => {
+ const [from, to] = clip.window;
+ const heard = findQuote(clip.quote, clip.words.map((w) => ({ ...w, start: w.start + from, end: w.end + from })));
+ const cued = findQuote(clip.quote, cueWords(clip.cues, { from: from - 30, to: to + 30 }));
+ assert.equal(heard.found, true, `heard ${heard.match}`);
+ assert.equal(cued.found, true, `cued ${cued.match}`);
+ const off = quoteOffset(heard, cued);
+ const [want, tol] = EXPECTED[clip.id];
+ assert.ok(Math.abs(off - want) <= tol, `${clip.id}: ${off} vs ${want}`);
+ });
+}
diff --git a/umtool/report-to-video/recording-ids.mjs b/umtool/report-to-video/recording-ids.mjs
@@ -0,0 +1,126 @@
+// recording-ids — which recording, and how to fetch it (lane one-clock).
+//
+// TWO THINGS umtool's fetch path must decide before it asks the editor:
+//
+// 1. THE DIRECTORY ID. A manifest cites a Rumble clip by its EMBED id (the
+// archive's), while the corpus names the video's directory for the URL
+// slug. Asked by the embed id, the editor looked in a `data/<embed>/` that
+// does not exist: no saved video, no metadata, the URL guessed as the embed
+// page (6 Nov: a 403), persist-videos "unknown". common's resolveVideoDirId
+// maps the two through the channel's metadata (videoDir-server.mjs); this
+// asks it HERE, on the corpus this checkout reads, so every request names
+// the directory — whichever editor build answers.
+//
+// 2. WHOLE OR WINDOW. A clip on a whole-recording platform
+// (settings.clips.wholeRecordingPlatforms, default ["rumble"]) is never a
+// remote seek: it goes through fetch-windows, which saves the whole
+// recording once, measures its clock and cuts the window from it. A remote
+// Rumble seek put the picture 1–4 s off the sound, and the 6 Nov windows
+// played words 13 s away from their cues.
+//
+// Plain ESM for bare node (fetch-via-editor.mjs, lib/report/fetchWindows.mjs).
+
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { readChannelPlatform, resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { detectPlatform } from "yt-dlp-transcript-common/lib/detectPlatform.mjs";
+
+const REPO_ROOT = path.resolve(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url)), "..", "..");
+
+/** The default when settings.json says nothing (common/lib/clipSettings.ts DEFAULT_CLIPS_SETTINGS). */
+export const DEFAULT_WHOLE_RECORDING_PLATFORMS = Object.freeze(["rumble"]);
+
+/** The corpus whose directories the ids are resolved in: CHANNELS_DIR, else the checkout's. */
+export function corpusChannelsDir(env = process.env) {
+ return env.CHANNELS_DIR ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "transcripts", "channels");
+}
+
+/**
+ * settings.json's `clips.wholeRecordingPlatforms` (the editor's file: SETTINGS_FILE,
+ * else the checkout's), normalized as clipSettings.ts does; the default when the
+ * file or the key is absent.
+ * @param {string} [file]
+ * @returns {string[]}
+ */
+export function wholeRecordingPlatforms(file = process.env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json")) {
+ let raw;
+ try {
+ raw = JSON.parse(readFileSync(file, "utf8"))?.clips?.wholeRecordingPlatforms;
+ } catch {
+ raw = undefined;
+ }
+ if (!Array.isArray(raw)) return [...DEFAULT_WHOLE_RECORDING_PLATFORMS];
+ const out = [];
+ for (const p of raw) {
+ const v = String(p ?? "").trim().toLowerCase();
+ if (v && !out.includes(v)) out.push(v);
+ }
+ return out;
+}
+
+/**
+ * The directory id the corpus keeps a cited recording under (a Rumble embed id
+ * → its URL slug's directory); the id itself when the corpus is not here or
+ * names no other.
+ * @param {{ channelsDir?: string, slug: string, id: string }} a
+ */
+export async function localVideoId({ channelsDir = corpusChannelsDir(), slug, id }) {
+ if (!slug || !id) return id;
+ try {
+ return await resolveVideoDirId(channelsDir, slug, String(id));
+ } catch {
+ return id;
+ }
+}
+
+/**
+ * The platform a clip's recording is on: its channel's (config.json, on this
+ * corpus), else its own page URL's host. Null for neither.
+ * @param {{ channelsDir?: string, slug: string, webpageUrl?: string | null }} a
+ */
+export async function recordingPlatform({ channelsDir = corpusChannelsDir(), slug, webpageUrl = null }) {
+ const own = slug ? await readChannelPlatform(channelsDir, slug) : null;
+ if (own) return String(own).toLowerCase();
+ const fromUrl = webpageUrl ? detectPlatform(webpageUrl) : null;
+ return fromUrl ? String(fromUrl).toLowerCase() : null;
+}
+
+/**
+ * Is this clip's recording one whose windows are cut from the whole recording?
+ * @param {{ channelsDir?: string, slug: string, webpageUrl?: string | null, platforms?: string[] }} a
+ */
+export async function isWholeRecording({ channelsDir = corpusChannelsDir(), slug, webpageUrl = null, platforms = wholeRecordingPlatforms() }) {
+ const p = await recordingPlatform({ channelsDir, slug, webpageUrl });
+ return !!p && platforms.includes(p);
+}
+
+/**
+ * fetch-windows items with each `id` resolved to its directory id, and the ids
+ * that changed (`{slug, cited, dir}`, once each) for the log. The editor's
+ * route refuses an unknown item key, so the cited id travels beside, not in.
+ * @template {{ slug: string, id: string }} I
+ * @param {I[]} items
+ * @param {{ channelsDir?: string }} [opts]
+ * @returns {Promise<{ items: I[], mapped: { slug: string, cited: string, dir: string }[] }>}
+ */
+export async function withLocalIds(items, { channelsDir = corpusChannelsDir() } = {}) {
+ const memo = new Map();
+ const out = [];
+ const mapped = [];
+ for (const it of items) {
+ const key = `${it.slug}\u0000${it.id}`;
+ if (!memo.has(key)) {
+ const dir = await localVideoId({ channelsDir, slug: it.slug, id: it.id });
+ memo.set(key, dir);
+ if (dir && dir !== it.id) mapped.push({ slug: it.slug, cited: it.id, dir });
+ }
+ const dirId = memo.get(key);
+ out.push(dirId && dirId !== it.id ? { ...it, id: dirId } : it);
+ }
+ return { items: out, mapped };
+}
+
+/** "the-quartering-rumble/v7drc5w → v7fxp3e, …" */
+export const mappedLine = (mapped) =>
+ mapped.map((m) => `${m.slug}/${m.cited} → ${m.dir}`).join(", ");
diff --git a/umtool/report-to-video/recording-ids.test.mjs b/umtool/report-to-video/recording-ids.test.mjs
@@ -0,0 +1,64 @@
+// recording-ids.mjs (lane one-clock): a cited Rumble embed id is asked for by
+// its directory, and the settings' whole-recording list decides whole or window.
+//
+// Run with: pnpm test:scripts
+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 { isWholeRecording, localVideoId, mappedLine, recordingPlatform, wholeRecordingPlatforms, withLocalIds } from "./recording-ids.mjs";
+
+async function corpus() {
+ const root = await mkdtemp(path.join(os.tmpdir(), "rec-ids-"));
+ const channelsDir = path.join(root, "channels");
+ await mkdir(path.join(channelsDir, "rc", "data", "v7fxp3e"), { recursive: true });
+ await writeFile(path.join(channelsDir, "rc", "config.json"), JSON.stringify({ platform: "rumble" }));
+ await writeFile(path.join(channelsDir, "rc", "data", "v7fxp3e", "metadata.info.json"), JSON.stringify({ id: "v7drc5w" }));
+ await mkdir(path.join(channelsDir, "yt"), { recursive: true });
+ await writeFile(path.join(channelsDir, "yt", "config.json"), JSON.stringify({ url: "https://www.youtube.com/@x" }));
+ return { root, channelsDir };
+}
+
+test("ids: an embed id becomes its directory; items keep everything else; the mapping is said once", async () => {
+ const c = await corpus();
+ try {
+ assert.equal(await localVideoId({ channelsDir: c.channelsDir, slug: "rc", id: "v7drc5w" }), "v7fxp3e");
+ assert.equal(await localVideoId({ channelsDir: c.channelsDir, slug: "rc", id: "v7fxp3e" }), "v7fxp3e");
+ const { items, mapped } = await withLocalIds(
+ [
+ { slug: "rc", id: "v7drc5w", from: 1, to: 2, clipId: "c43" },
+ { slug: "rc", id: "v7drc5w", from: 5, to: 9, clipId: "c44" },
+ { slug: "yt", id: "abcdefghijk", from: 1, to: 2 },
+ ],
+ { channelsDir: c.channelsDir },
+ );
+ assert.deepEqual(items.map((i) => i.id), ["v7fxp3e", "v7fxp3e", "abcdefghijk"]);
+ assert.deepEqual(items[0], { slug: "rc", id: "v7fxp3e", from: 1, to: 2, clipId: "c43" });
+ assert.deepEqual(mapped, [{ slug: "rc", cited: "v7drc5w", dir: "v7fxp3e" }]);
+ assert.equal(mappedLine(mapped), "rc/v7drc5w → v7fxp3e");
+ } finally {
+ await rm(c.root, { recursive: true, force: true });
+ }
+});
+
+test("whole or window: the channel's platform (else the page URL's) against the settings' list", async () => {
+ const c = await corpus();
+ try {
+ const none = path.join(c.root, "missing-settings.json");
+ assert.deepEqual(wholeRecordingPlatforms(none), ["rumble"]);
+ const listed = path.join(c.root, "settings.json");
+ await writeFile(listed, JSON.stringify({ clips: { wholeRecordingPlatforms: ["Rumble", "youtube", "rumble", ""] } }));
+ assert.deepEqual(wholeRecordingPlatforms(listed), ["rumble", "youtube"]);
+ await writeFile(listed, JSON.stringify({ clips: { wholeRecordingPlatforms: [] } }));
+ assert.deepEqual(wholeRecordingPlatforms(listed), []);
+ assert.equal(await recordingPlatform({ channelsDir: c.channelsDir, slug: "rc" }), "rumble");
+ assert.equal(await recordingPlatform({ channelsDir: c.channelsDir, slug: "yt" }), "youtube");
+ assert.equal(await recordingPlatform({ channelsDir: c.channelsDir, slug: "nope", webpageUrl: "https://rumble.com/v1-x.html" }), "rumble");
+ assert.equal(await isWholeRecording({ channelsDir: c.channelsDir, slug: "rc", platforms: ["rumble"] }), true);
+ assert.equal(await isWholeRecording({ channelsDir: c.channelsDir, slug: "yt", platforms: ["rumble"] }), false);
+ assert.equal(await isWholeRecording({ channelsDir: c.channelsDir, slug: "rc", platforms: [] }), false);
+ } finally {
+ await rm(c.root, { recursive: true, force: true });
+ }
+});
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 {