// LIVE PRE-CLIP — the pure half (plans/live-preclip.md): a live recording // transcribed and mined WHILE it records. // // A recording is append-only: what a recorder has written never changes, so a // tick reads the prefix already written (by time: `ffmpeg -ss -i `), never a copy. Second S of the growing file is second S of the // landed video (the landing's `-c copy` remux and the separate streams' merge // both subtract the input's start time, as `-ss` counts from it), so every time // here is on the landed video's clock. // // Everything here is pure: numbers and documents in, numbers and documents out. // The I/O — the files, ffmpeg, the worker lease, umtool — is // controller/livePreclip.ts. import type { Cue } from "./vtt"; // --- the two sidecars ------------------------------------------------------------- // The provisional transcript, beside the record. Never `transcript.json` (the // index, find-clips and the transcription lane read that one as THE transcript) // and never `transcript..` (a caption track). export const LIVE_TRANSCRIPT_FILENAME = "live-transcript.json"; // The pre-clip job's state: what it did, what it skipped and why. export const LIVE_PRECLIP_FILENAME = "live-preclip.json"; // --- the knob ------------------------------------------------------------------------ export type PreclipOptions = { // Minutes between two ticks. everyMinutes: number; // The most one tick transcribes; a recording further behind is caught up in // several ticks, back to back. maxChunkMinutes: number; // Seconds a tick re-reads before the end of what is transcribed, so a word // the boundary cut is heard whole once. overlapSeconds: number; // The laugh scan (CED when its model is there, energy always) of each span. scan: boolean; // Hand the transcript to umtool's clip finder after each tick. mine: boolean; // The umtool project's slug (default `-live`). project?: string; }; export const PRECLIP_DEFAULTS: Readonly> = Object.freeze({ everyMinutes: 10, maxChunkMinutes: 20, overlapSeconds: 15, scan: true, mine: true, }); export const PRECLIP_BOUNDS = Object.freeze({ everyMinutes: [1, 120] as const, maxChunkMinutes: [2, 60] as const, overlapSeconds: [0, 60] as const, }); // A tick with less than this new is not run ("no new data"). export const PRECLIP_MIN_NEW_SECONDS = 30; // The live edge is not read: the last seconds may be a fragment mid-write. export const PRECLIP_EDGE_SECONDS = 2; // A tick behind by more than this after it ran starts the next at once. export const PRECLIP_CATCH_UP_SECONDS = 60; // The store's disk must have this much free for a tick (its WAV is ~2 MB a // minute of audio, removed after the tick). export const PRECLIP_MIN_FREE_DISK_BYTES = 2 * 1024 ** 3; // The heavy slot's memory floor (scripts/queue-lock.mjs HEAVY_MIN_FREE_MB). export const PRECLIP_DEFAULT_MIN_FREE_MB = 6000; // The mining reads the transcript up to this far before its end: a proposal // near the live edge would be cut mid-thought (its tail is the next silence). export const PRECLIP_MINE_EDGE_SECONDS = 20; // A SHAREABLE CLIP OF A PARTIAL (the operator's second ask): sized for X. export const LIVE_CLIP_MAX_SECONDS = 140; export const LIVE_SHARE_MAX_BYTES = 512 * 1024 * 1024; export const PROJECT_SLUG_RE = /^[a-z0-9][a-z0-9-]{0,79}$/; /** The umtool project a stream's pre-clip writes, when none is named. */ export function liveProjectSlug(id: string): string { const base = id.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "stream"; return `${base.slice(0, 74)}-live`; } function bounded(v: unknown, key: keyof typeof PRECLIP_BOUNDS): number | { error: string } { const [lo, hi] = PRECLIP_BOUNDS[key]; if (typeof v !== "number" || !Number.isFinite(v) || v < lo || v > hi) { return { error: `"preclip.${key}" is a number from ${lo} to ${hi}` }; } return v; } /** * The `preclip` knob of record-live (and the options of `live-preclip start`): * absent or false = no pre-clip; true = the defaults (settings.livePreclip over * PRECLIP_DEFAULTS); an object = those keys over the defaults. */ export function parsePreclipKnob( v: unknown, defaults: Omit = PRECLIP_DEFAULTS, ): PreclipOptions | null | { error: string } { if (v === undefined || v === null || v === false) return null; if (v === true) return { ...defaults }; if (typeof v !== "object" || Array.isArray(v)) return { error: '"preclip" is true, or {"everyMinutes"?, "maxChunkMinutes"?, "overlapSeconds"?, "scan"?, "mine"?, "project"?}' }; const r = v as Record; const known = new Set(["everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"]); const unknown = Object.keys(r).filter((k) => !known.has(k)); if (unknown.length) return { error: `"preclip" does not take ${unknown.map((k) => `"${k}"`).join(", ")}` }; const out: PreclipOptions = { ...defaults }; for (const k of ["everyMinutes", "maxChunkMinutes", "overlapSeconds"] as const) { if (r[k] === undefined) continue; const n = bounded(r[k], k); if (typeof n !== "number") return n; out[k] = n; } for (const k of ["scan", "mine"] as const) { if (r[k] === undefined) continue; if (typeof r[k] !== "boolean") return { error: `"preclip.${k}" must be true or false` }; out[k] = r[k] as boolean; } if (r.project !== undefined) { if (typeof r.project !== "string" || !PROJECT_SLUG_RE.test(r.project)) { return { error: '"preclip.project" is a umtool project slug (lowercase letters, digits and dashes)' }; } out.project = r.project; } if (out.overlapSeconds * 2 >= out.maxChunkMinutes * 60) return { error: '"preclip.overlapSeconds" must be well under the chunk' }; return out; } // --- the live transcript ---------------------------------------------------------- export type LiveWord = { w: string; start: number; end: number; conf?: number }; // The laugh scan of the recording so far, on its clock (t0 0): window i covers // [i·hop, i·hop + window). `laugh` null when no tagger ran on any span. export type LiveScan = { hop: number; window: number; energy: number[]; laugh: number[] | null; model: string | null; }; // The part of the recording a transcript is on. A recorder restart or a // fallback writes a new part; its clock is the old one only when its opening // audio says so (compareEnvelopes). export type LiveBasis = { stem: string; // The file read: the muxed part, or the audio stream of a separate pair. audioFile: string; kind: "muxed" | "separate"; }; export type LiveChunk = { from: number; to: number; cues: number; words: number; worker: string | null; at: string; // The engine's time and the wait for a worker, ms. ms: number; waitedMs: number; }; export type LiveFingerprint = { from: number; hop: number; env: number[] }; export type ClockVerdict = "same-recording" | "same" | "shifted" | "mismatch" | "unverified"; export type ClockCheck = { verdict: ClockVerdict; // Seconds the landed video's audio lags the live transcript's (shifted). lagSeconds?: number; corr?: number; why: string; at: string; }; export type LiveTranscriptStatus = "live" | "landed" | "superseded"; export type LiveTranscriptDoc = { version: 1; provisional: true; status: LiveTranscriptStatus; basis: LiveBasis | null; // How many times the basis changed to a part on another clock. restarts: number; // Seconds of the recording transcribed, from 0. transcribedTo: number; cues: Cue[]; words: LiveWord[]; scan: LiveScan | null; chunks: LiveChunk[]; fingerprint: LiveFingerprint | null; updatedAt: string; landed?: { at: string; check: ClockCheck }; supersededAt?: string; }; export function emptyLiveTranscript(now: Date): LiveTranscriptDoc { return { version: 1, provisional: true, status: "live", basis: null, restarts: 0, transcribedTo: 0, cues: [], words: [], scan: null, chunks: [], fingerprint: null, updatedAt: now.toISOString(), }; } const isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v); const isObj = (v: unknown): v is Record => !!v && typeof v === "object" && !Array.isArray(v); export function coerceLiveTranscript(raw: unknown): LiveTranscriptDoc | null { if (!isObj(raw) || raw.version !== 1) return null; const status = raw.status === "landed" || raw.status === "superseded" ? raw.status : "live"; const cues = Array.isArray(raw.cues) ? (raw.cues as unknown[]).filter((c): c is Cue => isObj(c) && isNum(c.start) && isNum(c.end) && typeof c.text === "string") : []; const words = Array.isArray(raw.words) ? (raw.words as unknown[]).filter((w): w is LiveWord => isObj(w) && isNum(w.start) && isNum(w.end) && typeof w.w === "string") : []; const b = raw.basis; const basis: LiveBasis | null = isObj(b) && typeof b.stem === "string" && typeof b.audioFile === "string" ? { stem: b.stem, audioFile: b.audioFile, kind: b.kind === "separate" ? "separate" : "muxed" } : null; const s = raw.scan; const scan: LiveScan | null = isObj(s) && isNum(s.hop) && isNum(s.window) && Array.isArray(s.energy) ? { hop: s.hop, window: s.window, energy: (s.energy as unknown[]).map((x) => (isNum(x) ? x : -120)), laugh: Array.isArray(s.laugh) ? (s.laugh as unknown[]).map((x) => (isNum(x) ? x : 0)) : null, model: typeof s.model === "string" ? s.model : null, } : null; const f = raw.fingerprint; const fingerprint: LiveFingerprint | null = isObj(f) && isNum(f.from) && isNum(f.hop) && Array.isArray(f.env) ? { from: f.from, hop: f.hop, env: (f.env as unknown[]).map((x) => (isNum(x) ? x : -120)) } : null; return { version: 1, provisional: true, status, basis, restarts: isNum(raw.restarts) ? raw.restarts : 0, transcribedTo: isNum(raw.transcribedTo) ? raw.transcribedTo : 0, cues, words, scan, chunks: Array.isArray(raw.chunks) ? (raw.chunks as LiveChunk[]).filter((c) => isObj(c) && isNum(c.from) && isNum(c.to)) : [], fingerprint, updatedAt: typeof raw.updatedAt === "string" ? raw.updatedAt : new Date(0).toISOString(), ...(isObj(raw.landed) ? { landed: raw.landed as LiveTranscriptDoc["landed"] } : {}), ...(typeof raw.supersededAt === "string" ? { supersededAt: raw.supersededAt } : {}), }; } /** * Two transcriptions of one recording, the old up to `cut` and the new from it. * Both lists sorted by start; an entry is kept by where it STARTS, so a cue that * straddles the cut is taken once — from the side it starts on. */ export function spliceAt(old: readonly T[], incoming: readonly T[], cut: number): T[] { return [...old.filter((x) => x.start < cut), ...incoming.filter((x) => x.start >= cut)].sort((a, b) => a.start - b.start); } // Where a chunk takes over from what is transcribed: the middle of the overlap // (each side heard its half with the context of the other), or the chunk's // start when it does not overlap. export function spliceCut(transcribedTo: number, chunkFrom: number): number { return chunkFrom < transcribedTo ? Math.round(((chunkFrom + transcribedTo) / 2) * 1000) / 1000 : chunkFrom; } export type TranscribedSpan = { from: number; to: number; cues: readonly Cue[]; words: readonly LiveWord[]; worker: string | null; ms: number; waitedMs: number; }; /** The doc with one transcribed span spliced in (its cues and words already on the recording's clock). */ export function appendSpan(doc: LiveTranscriptDoc, span: TranscribedSpan, now: Date): LiveTranscriptDoc { const cut = spliceCut(doc.transcribedTo, span.from); const cues = spliceAt(doc.cues, span.cues, cut); const words = spliceAt(doc.words, span.words, cut); return { ...doc, cues, words, transcribedTo: Math.max(doc.transcribedTo, span.to), chunks: [ ...doc.chunks, { from: span.from, to: span.to, cues: span.cues.length, words: span.words.length, worker: span.worker, at: now.toISOString(), ms: span.ms, waitedMs: span.waitedMs, }, ], updatedAt: now.toISOString(), }; } // One span's scan (runAudioScan's shape: windows from t0, every hop). export type ScanPart = { t0: number; hop: number; window: number; energy: readonly number[]; laugh: readonly number[] | null; model: string | null }; /** * A span's scan written into the scan so far, by window index (t0 / hop). The * windows between the end of the scan and the span (a gap the scan did not * see) are silence (-120 dB) and no laugh. A span scanned with no tagger leaves * the laugh scores already there. */ export function spliceScan(acc: LiveScan | null, part: ScanPart): LiveScan { const hop = acc?.hop ?? part.hop; const window = acc?.window ?? part.window; if (Math.abs(hop - part.hop) > 1e-9 || Math.abs(window - part.window) > 1e-9) { throw new Error(`a scan of hop ${part.hop}/window ${part.window} cannot join one of ${hop}/${window}`); } const i0 = Math.max(0, Math.round(part.t0 / hop)); const n = i0 + part.energy.length; const energy = [...(acc?.energy ?? [])]; while (energy.length < n) energy.push(-120); part.energy.forEach((e, k) => (energy[i0 + k] = e)); let laugh = acc?.laugh ? [...acc.laugh] : null; if (part.laugh) { laugh = laugh ?? new Array(energy.length).fill(0); while (laugh.length < n) laugh.push(0); part.laugh.forEach((s, k) => ((laugh as number[])[i0 + k] = s)); } else if (laugh) while (laugh.length < energy.length) laugh.push(0); return { hop, window, energy, laugh, model: part.model ?? acc?.model ?? null }; } // --- the tick --------------------------------------------------------------------- export type TickPlan = | { action: "transcribe"; from: number; to: number; behind: number } | { action: "wait"; reason: string }; /** * What a tick does, given what is transcribed and what the file holds now: * transcribe `[from, to)` — from `overlapSeconds` before the end of the * transcript, to the live edge less PRECLIP_EDGE_SECONDS, at most * `maxChunkMinutes` — or wait, and why. `behind` is what is left after it. */ export function planTick(o: { transcribedTo: number; recordedSeconds: number | null; opts: Pick; }): TickPlan { if (o.recordedSeconds === null) return { action: "wait", reason: "the recording's length cannot be read yet" }; const edge = Math.max(0, o.recordedSeconds - PRECLIP_EDGE_SECONDS); const fresh = edge - o.transcribedTo; if (fresh < PRECLIP_MIN_NEW_SECONDS) { return { action: "wait", reason: `no new data (${Math.max(0, Math.round(fresh))} s new, a tick needs ${PRECLIP_MIN_NEW_SECONDS})` }; } const from = o.transcribedTo > 0 ? Math.max(0, o.transcribedTo - o.opts.overlapSeconds) : 0; const to = Math.min(edge, from + o.opts.maxChunkMinutes * 60); const r = (x: number) => Math.round(x * 1000) / 1000; return { action: "transcribe", from: r(from), to: r(to), behind: r(Math.max(0, edge - to)) }; } /** Milliseconds to the next tick: at once when still behind, else the period. */ export function nextTickDelayMs(behind: number, opts: Pick): number { return behind > PRECLIP_CATCH_UP_SECONDS ? 0 : opts.everyMinutes * 60_000; } // --- the clock check: an RMS envelope ---------------------------------------------- export const FINGERPRINT_FROM_SECONDS = 60; export const FINGERPRINT_SECONDS = 30; export const FINGERPRINT_HOP_SECONDS = 0.1; // The lag searched either way, seconds. export const FINGERPRINT_MAX_LAG_SECONDS = 10; export const CLOCK_MIN_CORR = 0.75; export const CLOCK_SAME_LAG_SECONDS = 0.3; // An envelope whose spread is under this (dB) is silence or a steady tone: it // cannot say where it is. export const FINGERPRINT_MIN_SPREAD_DB = 1.5; /** Where a fingerprint is taken in a recording of `seconds`: 60 s in, else the start; null when too short. */ export function fingerprintSpan(seconds: number): { from: number; dur: number } | null { if (seconds >= FINGERPRINT_FROM_SECONDS + FINGERPRINT_SECONDS) return { from: FINGERPRINT_FROM_SECONDS, dur: FINGERPRINT_SECONDS }; if (seconds >= FINGERPRINT_SECONDS + PRECLIP_EDGE_SECONDS) return { from: 0, dur: FINGERPRINT_SECONDS }; return null; } /** Each `hop`'s RMS level in dB (1 dp) of mono samples. */ export function envelopeOf(samples: Float32Array, rate: number, hop = FINGERPRINT_HOP_SECONDS): number[] { const n = Math.max(1, Math.round(rate * hop)); const out: number[] = []; for (let a = 0; a + n <= samples.length; a += n) { let s = 0; for (let i = a; i < a + n; i += 1) s += samples[i]! * samples[i]!; const rms = Math.sqrt(s / n); out.push(Math.round((rms > 1e-6 ? 20 * Math.log10(rms) : -120) * 10) / 10); } return out; } function spread(v: readonly number[]): number { if (v.length < 2) return 0; const m = v.reduce((a, b) => a + b, 0) / v.length; return Math.sqrt(v.reduce((a, b) => a + (b - m) ** 2, 0) / v.length); } function pearson(a: readonly number[], b: readonly number[]): number { const n = Math.min(a.length, b.length); if (n < 10) return 0; let ma = 0; let mb = 0; for (let i = 0; i < n; i += 1) { ma += a[i]!; mb += b[i]!; } ma /= n; mb /= n; let num = 0; let da = 0; let db = 0; for (let i = 0; i < n; i += 1) { const x = a[i]! - ma; const y = b[i]! - mb; num += x * y; da += x * x; db += y * y; } return da > 0 && db > 0 ? num / Math.sqrt(da * db) : 0; } /** * Where `probe` (the same span, read from another file — `pad` frames longer * on either side) best matches `ref`: the correlation, and the lag in frames * (positive: the probe's copy of the span is later). `probe[pad + k]` is the * frame `ref[k]` should be at when the clocks agree. */ export function compareEnvelopes( ref: readonly number[], probe: readonly number[], pad: number, ): { corr: number; lag: number; flat: boolean } { const flat = spread(ref) < FINGERPRINT_MIN_SPREAD_DB || spread(probe) < FINGERPRINT_MIN_SPREAD_DB; let best = { corr: -1, lag: 0 }; for (let lag = -pad; lag <= pad; lag += 1) { const start = pad + lag; if (start < 0) continue; const seg = probe.slice(start, start + ref.length); if (seg.length < ref.length * 0.8) continue; const c = pearson(ref, seg); if (c > best.corr + 1e-9 || (Math.abs(c - best.corr) <= 1e-9 && Math.abs(lag) < Math.abs(best.lag))) best = { corr: c, lag }; } return { corr: Math.round(best.corr * 1000) / 1000, lag: best.lag, flat }; } /** The verdict on two clocks, from compareEnvelopes. */ export function judgeClock( cmp: { corr: number; lag: number; flat: boolean }, hop: number, now: Date, ): ClockCheck { const at = now.toISOString(); const lagSeconds = Math.round(cmp.lag * hop * 1000) / 1000; if (cmp.flat) return { verdict: "unverified", corr: cmp.corr, why: "the compared audio is silence or a steady tone: it cannot say where it is", at }; if (cmp.corr < CLOCK_MIN_CORR) { return { verdict: "mismatch", corr: cmp.corr, why: `the landed video's audio does not match the live transcript's (best correlation ${cmp.corr})`, at }; } if (Math.abs(lagSeconds) <= CLOCK_SAME_LAG_SECONDS) { return { verdict: "same", corr: cmp.corr, lagSeconds, why: `the landed video starts where the live recording did (correlation ${cmp.corr}, ${lagSeconds} s)`, at }; } return { verdict: "shifted", corr: cmp.corr, lagSeconds, why: `the landed video is ${Math.abs(lagSeconds)} s ${lagSeconds > 0 ? "later" : "earlier"} than the live transcript's clock (correlation ${cmp.corr})`, at, }; } // --- the job's state ----------------------------------------------------------------- export type LivePreclipStatus = "running" | "waiting-final" | "superseded" | "stopped" | "failed"; export type LivePreclipState = { version: 1; status: LivePreclipStatus; jobId?: string; options: PreclipOptions; startedAt: string; updatedAt: string; ticks: number; recordedSeconds: number | null; transcribedSeconds: number; // Ticks not run, by reason ("no new data", "memory", "disk", "unreadable", // "failed"). skipped: Record; // The last lines of the job's log about ticks, newest last. log: string[]; mined?: { project: string; url?: string; proposals: number; clips: number; at: string; error?: string }; check?: ClockCheck; error?: string; }; export const PRECLIP_LOG_LINES = 12; export function newPreclipState(options: PreclipOptions, now: Date, jobId?: string): LivePreclipState { return { version: 1, status: "running", ...(jobId ? { jobId } : {}), options, startedAt: now.toISOString(), updatedAt: now.toISOString(), ticks: 0, recordedSeconds: null, transcribedSeconds: 0, skipped: {}, log: [], }; } const STATES: ReadonlySet = new Set(["running", "waiting-final", "superseded", "stopped", "failed"]); export function coerceLivePreclipState(raw: unknown): LivePreclipState | null { if (!isObj(raw) || raw.version !== 1 || typeof raw.status !== "string" || !STATES.has(raw.status)) return null; const opts = parsePreclipKnob(isObj(raw.options) ? raw.options : true); return { ...(raw as LivePreclipState), options: opts && !("error" in opts) ? opts : { ...PRECLIP_DEFAULTS }, ticks: isNum(raw.ticks) ? raw.ticks : 0, recordedSeconds: isNum(raw.recordedSeconds) ? raw.recordedSeconds : null, transcribedSeconds: isNum(raw.transcribedSeconds) ? raw.transcribedSeconds : 0, skipped: isObj(raw.skipped) ? (raw.skipped as Record) : {}, log: Array.isArray(raw.log) ? (raw.log as unknown[]).filter((l): l is string => typeof l === "string") : [], }; } /** The state with one more log line (the last PRECLIP_LOG_LINES kept). */ export function withLogLine(s: LivePreclipState, line: string, now: Date): LivePreclipState { return { ...s, log: [...s.log, `${now.toISOString().slice(11, 19)} ${line}`].slice(-PRECLIP_LOG_LINES), updatedAt: now.toISOString() }; } export function withSkip(s: LivePreclipState, reason: string): LivePreclipState { return { ...s, skipped: { ...s.skipped, [reason]: (s.skipped[reason] ?? 0) + 1 } }; } /** "1:02:03" / "4:05". */ export function clock(seconds: number): string { const t = Math.max(0, Math.round(seconds)); const h = Math.floor(t / 3600); const m = Math.floor((t % 3600) / 60); const s = t % 60; return h ? `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}` : `${m}:${String(s).padStart(2, "0")}`; } // --- a shareable clip's window ----------------------------------------------------- /** A share's clip (its cut) is at most X's 2:20. Null when it fits; else the sentence. */ export function liveClipTooLong(start: number, end: number): string | null { if (!isNum(start) || !isNum(end) || start < 0 || end <= start) return '"start" and "end" are seconds, start before end'; if (end - start > LIVE_CLIP_MAX_SECONDS + 1e-6) { return `a share is at most ${clock(LIVE_CLIP_MAX_SECONDS)} (X's limit); this clip is ${clock(end - start)}`; } return null; } // The source window a share's render reads is its clip's extent plus the // build's fetch pad (report-to-video/build-video.mjs fetchSpan): at most this. export const LIVE_WINDOW_MAX_SECONDS = LIVE_CLIP_MAX_SECONDS + 60; /** * A window cut from a recording in progress: inside what is recorded (short of * the live edge), at most LIVE_WINDOW_MAX_SECONDS. Refusals are sentences — * a window past the edge says how long to wait. */ export function checkLiveWindow( from: number, to: number, recordedSeconds: number | null, ): { from: number; to: number } | { error: string } { if (!isNum(from) || !isNum(to) || from < 0 || to <= from) return { error: '"from" and "to" are seconds, from before to' }; if (to - from > LIVE_WINDOW_MAX_SECONDS + 1e-6) { return { error: `a live window is at most ${clock(LIVE_WINDOW_MAX_SECONDS)}; this one is ${clock(to - from)}` }; } if (recordedSeconds !== null && to > recordedSeconds - PRECLIP_EDGE_SECONDS) { const wait = Math.ceil(to - (recordedSeconds - PRECLIP_EDGE_SECONDS)); return { error: `the recording holds ${clock(recordedSeconds)} so far; the window ends at ${clock(to)} — ask again in ${wait} s` }; } const r = (x: number) => Math.round(x * 100) / 100; return { from: r(from), to: r(to) }; }