// WHICH VIDEOS OF A SOURCE GROUP ARE THE SAME RECORDING (lane
// cross-source-dupes, slice 1). Pure: records and words in, pairs out. The
// scan (controller/copiesScan.ts) reads the disk and calls this.
//
// TWO STAGES, and the difference between them is the whole design:
//
// METADATA — recorded dates at most `dateWindowDays` apart and runtimes that
// agree (max(seconds, ratio × the longer)). Free, and measured at 99.7 %
// for "this stream is held elsewhere" but 3 % WRONG about WHICH copy (the
// adjacent day's stream of similar length). Good enough to HOLD a copy's
// work for a bounded wait, never to skip it.
// TEXT — probes spread through EACH copy's words, looked up in the other: at
// each, a 6-word phrase unique on both sides, and the signed offset between
// where it sits in each. A probe searches only its own stretch of words and
// a phrase the other side already gave is not counted again, so no phrase
// counts twice. The offsets that agree — runs of at least COPY_RUN_MIN
// inside one 20 s window, a stepped copy having several such runs — over
// the probes placed is the share of that side the other copy holds. Never
// the match count: two different streams of one speaker in one week share
// 4–20 of 40 phrases, at random offsets.
//
// WHAT CONFIRMS. Both shares at least COPY_SAME_FRACTION AND runtimes that
// agree: each copy holds the other, whole. Anything less is not a copy of the
// whole recording, and the lanes never skip or hold work for it:
// part-of — one side is (nearly) all inside the other but not the reverse,
// or the words agree both ways while the runtimes do not (a trim,
// a part, a muted stretch, a rerun inside a longer broadcast);
// overlaps — each holds only a stretch of the other (a shared passage, a
// third party's video both streams played, shared boilerplate).
// Measured on run 2 of the design pass (one direction, 1,379 text-same pairs):
// of the 1,031 whose runtimes agree, 1,025 reach 0.75 by summed runs, and no
// text-different pair had a single run of 4. The lane's LOG.md has the table.
//
// NO TIME IS MAPPED. The offsets are kept as evidence (their median and
// spread), never as a clock: two copies of one stream are measured stepped and
// drifting, and a constant offset would cut the wrong words. Nothing in slice 1
// reads a time across copies.
import type { SourceGroup } from "./settings";
import type { DateFrom } from "./dating";
export const COPY_PHRASE_WORDS = 6;
export const COPY_PROBES = 40;
// A window this wide holds one recording's consistent offsets.
export const COPY_OFFSET_WINDOW_SECONDS = 20;
// A run of agreeing offsets this long is a stretch the two copies share.
export const COPY_RUN_MIN = 4;
// Each side's share the other must hold, in both directions, to confirm.
export const COPY_SAME_FRACTION = 0.75;
// Below this on both sides the two share nothing worth reporting.
export const COPY_OVERLAP_FRACTION = 0.1;
// Fewer words than this on either side is "no text" — too little to probe.
export const COPY_MIN_WORDS = 200;
// How far past a probe's position a unique phrase is looked for (and never
// past the next probe's position).
const PROBE_SEARCH_WORDS = 300;
export type CopyRecord = {
channel: string;
// The data/
/ the video lives in (a Rumble video's dir is not its id).
// The lanes' pending lists and units name videos by this dir, so every pair
// is keyed by it.
dir: string;
id: string;
title: string;
// Seconds; 0 = unknown.
duration: number;
// YYYYMMDD, or null when undated.
date: string | null;
// Where `date` came from (lib/copies/dating.ts); absent: not said.
dateFrom?: DateFrom | null;
};
export type Word = { w: string; t: number };
export type CueLike = { start: number; end?: number; text: string };
type GramIndex = Map;
// One side's words with their phrase index, built once per video.
export type CopyText = { words: readonly Word[]; idx: GramIndex };
export type TextVerdict = "same" | "a-part-of-b" | "b-part-of-a" | "overlaps" | "different" | "no-text";
// Probes spread through one side, looked up in the other.
export type DirectionEvidence = {
probes: number;
// Probes whose phrase was found, unique, on the other side (each phrase once).
matched: number;
// Those inside runs of at least COPY_RUN_MIN agreeing offsets.
consistent: number;
// How many such runs (more than one: a stepped copy).
runs: number;
// consistent / probes, rounded to 0.001.
fraction: number;
};
export type TextEvidence = {
verdict: TextVerdict;
// a's probes found in b (how much of a b holds), and the reverse.
aInB: DirectionEvidence;
bInA: DirectionEvidence;
// EVIDENCE ONLY, never a clock: the median and spread of the largest run of
// a→b offsets (b's seconds minus a's), rounded to 0.1 s.
offsetMedianSeconds: number | null;
offsetSpreadSeconds: number | null;
};
// confirmed — the same recording, whole, by text and runtime (or a person's word);
// metadata — probably the same (date + runtime); one side has no words;
// part-of — one copy is inside the other (`part` says which);
// overlaps — they share a stretch, nothing more.
export type CopyLink = "confirmed" | "metadata" | "part-of" | "overlaps";
export type CopyCandidate = {
a: CopyRecord;
b: CopyRecord;
// Days between the two dates; null when one side is undated (a runtime
// candidate).
dateDeltaDays: number | null;
durationOk: boolean;
// How it was proposed: dated within the window (the default), or — one side
// dated only by its upload — by runtime, for the words to decide.
via?: "date" | "runtime";
};
export type CopyClassification = { link: CopyLink; part?: "a" | "b" } | null;
// The words of a cue list, each at a time spread across its cue's span.
export function cuesToWords(cues: readonly CueLike[]): Word[] {
const out: Word[] = [];
for (const c of cues) {
if (!c || typeof c.text !== "string" || typeof c.start !== "number" || !Number.isFinite(c.start)) continue;
const ws = c.text
.toLowerCase()
.replace(/[^\p{L}\p{N}\s]/gu, " ")
.split(/\s+/)
.filter(Boolean);
const end = typeof c.end === "number" && Number.isFinite(c.end) ? c.end : c.start;
const span = Math.max(0, end - c.start);
ws.forEach((w, i) => out.push({ w, t: c.start + (ws.length > 1 ? (span * i) / ws.length : 0) }));
}
return out;
}
function gramAt(ws: readonly Word[], i: number): string {
let key = ws[i].w;
for (let j = 1; j < COPY_PHRASE_WORDS; j++) key += " " + ws[i + j].w;
return key;
}
function gramIndex(ws: readonly Word[]): GramIndex {
const idx: GramIndex = new Map();
for (let i = 0; i + COPY_PHRASE_WORDS <= ws.length; i++) {
const key = gramAt(ws, i);
const e = idx.get(key);
if (e) e.n++;
else idx.set(key, { t: ws[i].t, n: 1, i });
}
return idx;
}
/** One side's words, indexed once: the scan keeps these per video. */
export function prepareCopyText(words: readonly Word[]): CopyText {
return { words, idx: gramIndex(words) };
}
const asText = (x: readonly Word[] | CopyText): CopyText =>
Array.isArray(x) ? prepareCopyText(x as readonly Word[]) : (x as CopyText);
const round1 = (x: number) => Math.round(x * 10) / 10;
const round3 = (x: number) => Math.round(x * 1000) / 1000;
// Runs of at least COPY_RUN_MIN sorted values inside one window, taken
// greedily largest first: each value belongs to one run at most.
function runsOf(sorted: readonly number[]): number[][] {
const left = [...sorted];
const runs: number[][] = [];
for (;;) {
let bi = 0;
let bj = -1;
for (let i = 0, j = 0; i < left.length; i++) {
while (left[i] - left[j] > COPY_OFFSET_WINDOW_SECONDS) j++;
if (i - j > bj - bi) {
bi = j;
bj = i;
}
}
if (bj - bi + 1 < COPY_RUN_MIN) break;
runs.push(left.splice(bi, bj - bi + 1));
}
return runs;
}
function direction(from: CopyText, to: CopyText, wanted: number): { ev: DirectionEvidence; runs: number[][] } {
const ws = from.words;
const usable = ws.length - COPY_PHRASE_WORDS + 1;
// A short side gets fewer probes, never two inside one phrase's stretch.
const probes = Math.max(1, Math.min(wanted, Math.floor(usable / COPY_PHRASE_WORDS)));
const offsets: number[] = [];
const usedTo = new Set();
for (let k = 0; k < probes; k++) {
const pos = Math.floor((usable * k) / probes);
const next = Math.floor((usable * (k + 1)) / probes);
const lim = Math.min(next, pos + PROBE_SEARCH_WORDS, usable);
for (let i = pos; i < lim; i++) {
const key = gramAt(ws, i);
if (from.idx.get(key)?.n !== 1) continue;
const hit = to.idx.get(key);
if (!hit || hit.n !== 1) continue;
// EACH PHRASE ONCE: a place on the other side already counted is not
// counted again.
if (usedTo.has(hit.i)) continue;
usedTo.add(hit.i);
offsets.push(hit.t - ws[i].t);
break;
}
}
const runs = runsOf([...offsets].sort((x, y) => x - y));
const consistent = runs.reduce((n, r) => n + r.length, 0);
return {
ev: { probes, matched: offsets.length, consistent, runs: runs.length, fraction: round3(consistent / probes) },
runs,
};
}
/**
* Whether `a` and `b` are the same recording by their words, probed in both
* directions. "same" here is the words only; `classifyCandidate` adds the
* runtimes before anything is confirmed.
*/
export function textEvidence(
a: readonly Word[] | CopyText,
b: readonly Word[] | CopyText,
opts: { probes?: number; minWords?: number } = {},
): TextEvidence {
const wanted = opts.probes ?? COPY_PROBES;
const minWords = opts.minWords ?? COPY_MIN_WORDS;
const ta = asText(a);
const tb = asText(b);
const empty: DirectionEvidence = { probes: 0, matched: 0, consistent: 0, runs: 0, fraction: 0 };
if (ta.words.length < minWords || tb.words.length < minWords) {
return { verdict: "no-text", aInB: empty, bInA: empty, offsetMedianSeconds: null, offsetSpreadSeconds: null };
}
const ab = direction(ta, tb, wanted);
const ba = direction(tb, ta, wanted);
const fa = ab.ev.fraction;
const fb = ba.ev.fraction;
const verdict: TextVerdict =
fa >= COPY_SAME_FRACTION && fb >= COPY_SAME_FRACTION
? "same"
: fa >= COPY_SAME_FRACTION
? "a-part-of-b"
: fb >= COPY_SAME_FRACTION
? "b-part-of-a"
: Math.max(fa, fb) >= COPY_OVERLAP_FRACTION
? "overlaps"
: "different";
const main = ab.runs[0] ?? null;
return {
verdict,
aInB: ab.ev,
bInA: ba.ev,
offsetMedianSeconds: main ? round1(main[Math.floor(main.length / 2)]) : null,
offsetSpreadSeconds: main ? round1(main[main.length - 1] - main[0]) : null,
};
}
function dayNumber(ymd: string): number {
return Date.UTC(Number(ymd.slice(0, 4)), Number(ymd.slice(4, 6)) - 1, Number(ymd.slice(6, 8))) / 86_400_000;
}
/** Whether two runtimes agree within max(seconds, ratio × the longer). Unknown (0) never agrees. */
export function runtimesAgree(
a: number,
b: number,
group: Pick,
): boolean {
if (!(a > 0) || !(b > 0)) return false;
const tol = Math.max(group.durationToleranceSeconds, Math.max(a, b) * group.durationToleranceRatio);
return Math.abs(a - b) <= tol;
}
/**
* Every pair of the group's videos dated within the window — across members,
* and inside one member when `withinChannels` — with `a` the more preferred
* side (the earlier channel in the group; inside one channel, the smaller dir).
* Deterministic order: by a's channel rank, a's dir, b's channel rank, b's dir.
*/
export function copyCandidates(
group: Pick<
SourceGroup,
"channels" | "dateWindowDays" | "durationToleranceSeconds" | "durationToleranceRatio" | "withinChannels"
>,
records: readonly CopyRecord[],
): CopyCandidate[] {
const rank = new Map(group.channels.map((c, i) => [c, i]));
const dated = records
.filter((r) => rank.has(r.channel) && r.date && /^\d{8}$/.test(r.date))
.map((r) => ({ r, day: dayNumber(r.date!) }));
const byDay = new Map();
for (const d of dated) {
const list = byDay.get(d.day);
if (list) list.push(d);
else byDay.set(d.day, [d]);
}
const order = (x: CopyRecord, y: CopyRecord) =>
rank.get(x.channel)! - rank.get(y.channel)! || (x.dir < y.dir ? -1 : x.dir > y.dir ? 1 : 0);
const seen = new Set();
const out: CopyCandidate[] = [];
for (const d of dated) {
for (let dd = -group.dateWindowDays; dd <= group.dateWindowDays; dd++) {
for (const e of byDay.get(d.day + dd) ?? []) {
if (e.r === d.r) continue;
const same = e.r.channel === d.r.channel;
if (same && !group.withinChannels) continue;
const [a, b] = order(d.r, e.r) <= 0 ? [d.r, e.r] : [e.r, d.r];
const key = `${a.channel}/${a.dir}\u0000${b.channel}/${b.dir}`;
if (seen.has(key)) continue;
seen.add(key);
out.push({
a,
b,
dateDeltaDays: Math.abs(dd),
durationOk: runtimesAgree(a.duration, b.duration, group),
via: "date",
});
}
}
}
return out.sort((x, y) => order(x.a, y.a) || order(x.b, y.b));
}
// THE RUNTIME SEARCH, for a video of a channel with NO recordedDate rule whose
// date says nothing about its stream (lib/copies/dating.ts: only an upload
// date, or none) and which found no candidate by date (a channel with a rule
// is dated by the operator's word, and is never searched from, as before): the other members' videos whose runtimes agree, nearest
// first, at most COPY_RUNTIME_PER_VIDEO of them, and at most
// COPY_RUNTIME_MAX_PAIRS such pairs in one scan. Both sides must have words:
// a runtime alone is no evidence of anything, so a runtime candidate is
// decided by its words or dropped (classifyCandidate), never held. The bound:
// at most min(8 × such videos, 2,000) text comparisons per scan, each about
// 0.15 s of one core measured on 4-hour streams — five minutes at worst.
export const COPY_RUNTIME_PER_VIDEO = 8;
export const COPY_RUNTIME_MAX_PAIRS = 2000;
export type RuntimeSearch = {
candidates: CopyCandidate[];
// Videos searched (undated or upload-dated, with words and a runtime, no date candidate).
searched: number;
// Such videos left unsearched once the scan's cap was reached.
capped: number;
};
const needsRuntimeSearch = (r: CopyRecord, ruled: ReadonlySet) =>
(!r.date || r.dateFrom === "upload") && !ruled.has(r.channel);
/** Whether any record would be searched by runtime (the scan reads no cue file otherwise). */
export function wantsRuntimeSearch(records: readonly CopyRecord[], ruled: ReadonlySet): boolean {
return records.some((r) => needsRuntimeSearch(r, ruled));
}
/**
* Runtime candidates for the videos whose date cannot pair them (above).
* `hasText` says which videos have words; `dated` holds the keys
* (`/`) of videos that already have a date candidate; `ruled`
* the channels with a recordedDate rule (never searched from); `breathe` is
* awaited before each searched video (the scan yields to the event loop there).
* Deterministic: by the searched video's rank and dir, then runtime distance.
*/
export async function runtimeCandidates(
group: Pick,
records: readonly CopyRecord[],
opts: {
hasText: (r: CopyRecord) => boolean;
dated: ReadonlySet;
ruled?: ReadonlySet;
perVideo?: number;
maxPairs?: number;
breathe?: () => Promise;
},
): Promise {
const ruled = opts.ruled ?? new Set();
const perVideo = opts.perVideo ?? COPY_RUNTIME_PER_VIDEO;
const maxPairs = opts.maxPairs ?? COPY_RUNTIME_MAX_PAIRS;
const rank = new Map(group.channels.map((c, i) => [c, i]));
const order = (x: CopyRecord, y: CopyRecord) =>
rank.get(x.channel)! - rank.get(y.channel)! || (x.dir < y.dir ? -1 : x.dir > y.dir ? 1 : 0);
const keyOf = (r: CopyRecord) => `${r.channel}/${r.dir}`;
const pool = records
.filter((r) => rank.has(r.channel) && r.duration > 0 && opts.hasText(r))
.sort((x, y) => x.duration - y.duration || order(x, y));
const wanted = pool.filter((r) => needsRuntimeSearch(r, ruled) && !opts.dated.has(keyOf(r))).sort(order);
const seen = new Set();
const out: CopyCandidate[] = [];
let searched = 0;
let capped = 0;
for (const r of wanted) {
if (out.length >= maxPairs) {
capped++;
continue;
}
await opts.breathe?.();
searched++;
// The pool is sorted by runtime: walk out from r's place both ways.
let lo = 0;
let hi = pool.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (pool[mid].duration < r.duration) lo = mid + 1;
else hi = mid;
}
const near: CopyRecord[] = [];
let i = lo - 1;
let j = lo;
const ok = (o: CopyRecord) => o.channel !== r.channel && runtimesAgree(r.duration, o.duration, group);
while (near.length < perVideo && (i >= 0 || j < pool.length)) {
const left = i >= 0 ? pool[i] : null;
const right = j < pool.length ? pool[j] : null;
const inLeft = left !== null && runtimesAgree(r.duration, left.duration, group);
const inRight = right !== null && runtimesAgree(r.duration, right.duration, group);
if (!inLeft && !inRight) break;
const takeLeft = inLeft && (!inRight || r.duration - left!.duration <= right!.duration - r.duration);
const o = takeLeft ? left! : right!;
if (takeLeft) i--;
else j++;
if (ok(o)) near.push(o);
}
for (const o of near) {
if (out.length >= maxPairs) break;
const [a, b] = order(r, o) <= 0 ? [r, o] : [o, r];
const key = `${keyOf(a)}\u0000${keyOf(b)}`;
if (seen.has(key)) continue;
seen.add(key);
out.push({
a,
b,
dateDeltaDays: a.date && b.date ? Math.abs(dayNumber(a.date) - dayNumber(b.date)) : null,
durationOk: true,
via: "runtime",
});
}
}
return { candidates: out, searched, capped };
}
/**
* What a candidate is, given its text evidence (null = one side has no text).
* With words on both sides they decide, and CONFIRMED needs the runtimes to
* agree as well: the words the same both ways and the runtimes apart is a trim
* or a part — the shorter side `part-of` the longer. With no words, agreeing
* runtimes make a METADATA-only pair and anything else no pair. Null: not a
* pair (the words say different recordings, or there is nothing to go on).
*/
export function classifyCandidate(c: CopyCandidate, text: TextEvidence | null): CopyClassification {
if (text && text.verdict !== "no-text") {
switch (text.verdict) {
case "same":
if (c.durationOk) return { link: "confirmed" };
return { link: "part-of", part: c.a.duration > 0 && c.a.duration <= c.b.duration ? "a" : "b" };
case "a-part-of-b":
return { link: "part-of", part: "a" };
case "b-part-of-a":
return { link: "part-of", part: "b" };
case "overlaps":
return { link: "overlaps" };
default:
return null;
}
}
// A runtime candidate has nothing but its runtime: no words, no pair.
if (c.via === "runtime") return null;
return c.durationOk ? { link: "metadata" } : null;
}