// LIVE PRE-CLIP — `pnpm ops live-preclip`, record-live's `preclip` knob, the // video page's Live pre-clip panel (plans/live-preclip.md; the arithmetic is // lib/livePreclip.ts, the files lib/livePreclip-server.ts). // // ONE JOB PER STREAM (`live-preclip::`), beside the recorder's own, // never in its way: it only reads what the recorder has written. Every // `everyMinutes` a TICK: // // 1. reads live-recording.json and finds the part being written and the // file in it that holds the sound (findLiveSource); // 2. is skipped — and says so — when the machine is under the heavy slot's // memory floor (re-checked every minute), the store's disk is short, or // there are fewer than 30 s new ("no new data"); // 3. transcribes ONLY the new span (from 15 s before the end of what is // transcribed to 2 s short of the live edge, at most maxChunkMinutes) on a // worker lease (transcribeFile.ts runTranscribeFile: the cut is `ffmpeg -ss // -i `, in the work dir on the store's disk), with // word timings; the laugh scan (lib/clips/scan.mjs) reads the same WAV; // 4. splices the cues, words and scan into data//live-transcript.json on // the recording's clock — which IS the landed video's clock; // 5. hands it to umtool's clip finder (`POST /api/report/clips {mode: // "live"}`), which grows the stream's project. // // THE JOB IS THE QUEUE. One transcription is in flight at a time: while it // waits for a worker (the pool's "foreground" tier) or runs, nothing else is // asked for, and the next tick takes everything since — so a busy worker // coalesces ticks and they never pile up. Behind by more than a minute after a // tick (a late start, a long wait), the next one starts at once. // // WHEN THE STREAM ENDS (live-recording.json says it landed): the clock check // (the landed part is the one followed → "same recording"; else the audio // envelope of the landed video against the fingerprint taken while it was live), // then the wait for the final transcript (a stat every 2 minutes, up to a day), // then the supersede — the live transcript marked superseded, umtool told to // read the corpus from now on. A wait that runs out leaves "waiting-final"; // `live-preclip {action: "finalize"}` finishes it. // // NO NETWORK REQUEST: the recorder's files, the worker pool, umtool on this // machine. import path from "node:path"; import { mkdir, rm } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import { getSettings } from "../lib/settings"; import { getFreeBytes } from "../lib/diskSpace"; import { formatBytes } from "../lib/format"; import { liveRecordingSidecar } from "../lib/mediaImport-server"; import type { LiveRecordingRecord } from "../lib/liveCapture"; import { savedVideoDir } from "../lib/savedVideo"; import { loadSavedVideo } from "../lib/savedVideo-server"; import { savedVideoPath } from "../lib/savedVideo"; import { englishVttsByPreference, WHISPER_FILENAME } from "../lib/videoStatus"; import { readdirLogical } from "../lib/storedText-server"; import { umtoolUrl as resolveUmtoolUrl } from "../lib/umtoolUrl"; import { getWorkerToken } from "../lib/workerToken"; import { FINGERPRINT_HOP_SECONDS, FINGERPRINT_MAX_LAG_SECONDS, PRECLIP_DEFAULTS, PRECLIP_DEFAULT_MIN_FREE_MB, PRECLIP_MIN_FREE_DISK_BYTES, appendSpan, clock, compareEnvelopes, emptyLiveTranscript, fingerprintSpan, judgeClock, liveProjectSlug, newPreclipState, nextTickDelayMs, parsePreclipKnob, planTick, spliceScan, withLogLine, withSkip, type ClockCheck, type LivePreclipState, type LiveTranscriptDoc, type LiveWord, type PreclipOptions, type ScanPart, } from "../lib/livePreclip"; import { findLiveSource, livePreclipSidecar, liveTranscriptSidecar, preclipWorkDir, probeWith, readEnvelope, type LiveSource, type ProbeSeconds, } from "../lib/livePreclip-server"; import type { Cue } from "../lib/vtt"; import { getRegistry } from "../jobs/registry"; import { runManagedFunction, type JobRunContext, type StreamActionResult } from "../jobs/streamCommand"; import { runTranscribeFile } from "./transcribeFile"; import { readMemAvailableMb } from "./persistVideos"; export const LIVE_PRECLIP_JOB_KIND = "live-preclip"; export const LIVE_PRECLIP_RESULT_MARKER = "@@live-preclip "; export const LIVE_PRECLIP_ACTIONS = ["start", "stop", "status", "finalize"] as const; export type LivePreclipAction = (typeof LIVE_PRECLIP_ACTIONS)[number]; export const LIVE_PRECLIP_BODY_KEYS = [ "slug", "id", "action", "everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project", ] as const; // How long the job waits for live-recording.json (a pre-clip asked for at the // same moment as the recording), and for the final transcript after the landing. export const RECORD_WAIT_MS = 10 * 60_000; export const FINAL_WAIT_MS = 24 * 3600_000; export const FINAL_POLL_MS = 2 * 60_000; export const MEMORY_POLL_MS = 60_000; export const SOURCE_POLL_MS = 30_000; export function livePreclipQueueKey(slug: string, id: string): string { return `live-preclip:${slug}:${id}`; } /** settings.livePreclip over the built-in defaults. */ export function preclipDefaults(): Omit { return { ...PRECLIP_DEFAULTS, ...(getSettings().livePreclip ?? {}) }; } /** HEAVY_MIN_FREE_MB when set (0 = no floor), else the slot's 6000. */ export function memoryFloorMb(env: Readonly> = process.env): number { const raw = env.HEAVY_MIN_FREE_MB; const n = raw === undefined || raw === "" ? NaN : Number(raw); if (env.HEAVY === "0") return 0; return Number.isFinite(n) && n >= 0 ? n : PRECLIP_DEFAULT_MIN_FREE_MB; } export type LivePreclipRequest = { slug: string; id: string; action: LivePreclipAction; options: PreclipOptions }; type Check = { ok: true; value: T } | { ok: false; error: string }; const ID_RE = /^[\w.-]+$/; /** The ops body, judged without touching the disk. */ export function parseLivePreclipBody(body: Record, defaults = PRECLIP_DEFAULTS): Check { const slug = typeof body.slug === "string" ? body.slug.trim() : ""; if (!slug) return { ok: false, error: '"slug" is required' }; const id = typeof body.id === "string" ? body.id.trim() : ""; if (!id || !ID_RE.test(id) || id === "." || id === "..") return { ok: false, error: '"id" is required: the record\'s id' }; const action = body.action === undefined ? "start" : body.action; if (typeof action !== "string" || !(LIVE_PRECLIP_ACTIONS as readonly string[]).includes(action)) { return { ok: false, error: `"action" is one of ${LIVE_PRECLIP_ACTIONS.join(", ")}` }; } const knob: Record = {}; for (const k of ["everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"]) if (body[k] !== undefined) knob[k] = body[k]; const options = parsePreclipKnob(Object.keys(knob).length ? knob : true, defaults); if (!options || "error" in options) return { ok: false, error: options ? options.error : "no options" }; return { ok: true, value: { slug, id, action: action as LivePreclipAction, options } }; } // --- the dependencies (all replaceable in a test) ---------------------------------- export type TranscribeSpan = (o: { file: string; from: number; to: number; scratchParent: string; onLog: (s: string) => void; signal: AbortSignal; ctx?: JobRunContext; withWav?: (wav: string, seconds: number) => Promise; }) => Promise<{ cues: Cue[]; words: LiveWord[]; worker: string | null; ms: number; waitedMs: number }>; export type MineLive = (body: { slug: string; from: string; final?: boolean; check?: ClockCheck; }) => Promise<{ project: string; created: boolean; proposals: number; clips: number; href?: string; notes?: string[] }>; export type LivePreclipDeps = { now?: () => Date; sleep?: (ms: number, signal: AbortSignal) => Promise; memAvailableMb?: () => Promise; memoryFloorMb?: number; freeBytes?: (dir: string) => Promise; probe?: ProbeSeconds; transcribe?: TranscribeSpan; // The laugh scan of a span's WAV, on the recording's clock (null: none). scanWav?: (wav: string, from: number, seconds: number, scratch: string) => Promise; envelope?: (file: string, from: number, dur: number) => Promise; // Null: umtool is not configured (mining is skipped, said once). mine?: MineLive | null; savedVideo?: (videoDir: string) => Promise; hasFinalTranscript?: (videoDir: string) => Promise; recordWaitMs?: number; finalWaitMs?: number; finalPollMs?: number; memoryPollMs?: number; sourcePollMs?: number; }; function sleep(ms: number, signal: AbortSignal): Promise { return new Promise((resolve) => { if (signal.aborted || ms <= 0) return resolve(); const t = setTimeout(done, ms); function done() { clearTimeout(t); signal.removeEventListener("abort", done); resolve(); } signal.addEventListener("abort", done, { once: true }); }); } export function defaultTranscribe(paths: Paths): TranscribeSpan { return async (o) => { const r = await runTranscribeFile({ paths, request: { path: o.file, start: o.from, end: o.to, words: true }, onLog: o.onLog, signal: o.signal, ...(o.ctx ? { ctx: o.ctx } : {}), tier: "foreground", scratchParent: o.scratchParent, ...(o.withWav ? { withWav: o.withWav } : {}), }); return { cues: r.cues, words: (r.words ?? []).map((w) => ({ w: w.w, start: w.start, end: w.end, ...(w.conf !== undefined ? { conf: w.conf } : {}) })), worker: r.worker.id, ms: r.durationMs, waitedMs: r.waitedMs, }; }; } export function defaultScanWav(paths: Paths): NonNullable { return async (wav, from, seconds, scratch) => { const { resolveTagger, runAudioScan } = await import("../lib/clips/scan.mjs"); const tagger = resolveTagger({ repoRoot: paths.monorepoRoot, settings: getSettings() }); const scan = await runAudioScan({ file: wav, duration: seconds, clock: from, tagger: tagger.available ? tagger : null, scratch, ffmpeg: paths.ffmpegBin, }); return { t0: scan.t0, hop: scan.hop, window: scan.window, energy: scan.energy, laugh: scan.laugh, model: scan.model?.file ?? null }; }; } async function umtoolBody(res: Response): Promise> { try { const j = (await res.json()) as unknown; return j && typeof j === "object" && !Array.isArray(j) ? (j as Record) : {}; } catch { return {}; } } /** umtool's clips route, live mode: synchronous, a proposal pass. */ export function umtoolMiner(umtool: string, token: string, doFetch: typeof fetch = fetch): MineLive { return async (body) => { let res: Response; try { res = await doFetch(`${umtool}/api/report/clips`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ mode: "live", ...body }), signal: AbortSignal.timeout(5 * 60_000), }); } catch (e) { throw new Error(`umtool at ${umtool} did not answer (${(e as Error).message}) — is it running?`); } const j = await umtoolBody(res); if (!res.ok) throw new Error(`umtool refused the live clips request (HTTP ${res.status}): ${typeof j.error === "string" ? j.error : "no reason given"}`); return { project: String(j.project ?? body.slug), created: j.created === true, proposals: typeof j.proposals === "number" ? j.proposals : 0, clips: typeof j.clips === "number" ? j.clips : 0, ...(typeof j.href === "string" ? { href: j.href } : {}), ...(Array.isArray(j.notes) ? { notes: j.notes.filter((n): n is string => typeof n === "string") } : {}), }; }; } export async function hasCorpusTranscript(videoDir: string): Promise { // LOGICAL (lib/storedText.ts): a caption stored as `.zst` is a transcript. const entries = await readdirLogical(videoDir); return entries.includes(WHISPER_FILENAME) || englishVttsByPreference(entries).length > 0; } // --- the run --------------------------------------------------------------------------- export type LivePreclipRunOpts = { paths: Paths; slug: string; id: string; channelConfig: ChannelConfig; options: PreclipOptions; onLog: (s: string) => void; signal: AbortSignal; ctx?: JobRunContext; deps?: LivePreclipDeps; }; export type LivePreclipSummary = { slug: string; id: string; status: LivePreclipState["status"]; ticks: number; transcribedSeconds: number; cues: number; project: string | null; check?: ClockCheck; }; export async function runLivePreclip(o: LivePreclipRunOpts): Promise { const { paths, slug, id, options, signal } = o; const deps = o.deps ?? {}; const now = deps.now ?? (() => new Date()); const wait = deps.sleep ?? sleep; const probe = deps.probe ?? probeWith(paths.ffprobeBin); const transcribe = deps.transcribe ?? defaultTranscribe(paths); const scanWav = deps.scanWav ?? defaultScanWav(paths); const envelope = deps.envelope ?? ((f: string, a: number, d: number) => readEnvelope(f, a, d, paths.ffmpegBin)); const memory = deps.memAvailableMb ?? readMemAvailableMb; const floor = deps.memoryFloorMb ?? memoryFloorMb(); const free = deps.freeBytes ?? getFreeBytes; const hasFinal = deps.hasFinalTranscript ?? hasCorpusTranscript; let mine: MineLive | null; if (deps.mine !== undefined) mine = deps.mine; else { const umtool = resolveUmtoolUrl(); const token = getWorkerToken(); mine = umtool && token ? umtoolMiner(umtool, token) : null; } const say = (s: string) => o.onLog(s.endsWith("\n") ? s : `${s}\n`); const videoDir = path.join(paths.channelsDir, slug, "data", id); const slugStore = path.dirname(savedVideoDir(paths, o.channelConfig, slug, id)); const workDir = preclipWorkDir(slugStore, id); const project = options.project ?? liveProjectSlug(id); let state: LivePreclipState = newPreclipState(options, now(), o.ctx?.jobId); const prevState = await livePreclipSidecar.load(videoDir); if (prevState) state = { ...state, ticks: prevState.ticks, skipped: prevState.skipped, log: prevState.log, ...(prevState.mined ? { mined: prevState.mined } : {}) }; let doc: LiveTranscriptDoc = (await liveTranscriptSidecar.load(videoDir)) ?? emptyLiveTranscript(now()); if (doc.status !== "live") doc = { ...emptyLiveTranscript(now()), restarts: doc.restarts }; const note = async (line: string) => { say(`pre-clip: ${line}`); state = withLogLine(state, line, now()); await livePreclipSidecar.write(videoDir, state); }; const saveDoc = () => liveTranscriptSidecar.write(videoDir, doc); const summary = (): LivePreclipSummary => ({ slug, id, status: state.status, ticks: state.ticks, transcribedSeconds: doc.transcribedTo, cues: doc.cues.length, project: state.mined?.project ?? null, ...(state.check ? { check: state.check } : {}), }); const mineNow = async (extra: { final?: boolean; check?: ClockCheck } = {}) => { if (!options.mine) return; if (!mine) { if (!state.log.some((l) => /umtool is not configured/.test(l))) { await note("umtool is not configured on the editor (UMTOOL_URL, WORKER_TOKEN): the live transcript is kept, no windows are mined"); } return; } try { const r = await mine({ slug: project, from: `${slug}/${id}`, ...extra }); state = { ...state, mined: { project: r.project, ...(r.href ? { url: r.href } : {}), proposals: r.proposals, clips: r.clips, at: now().toISOString() } }; await note(`umtool: ${r.created ? "made" : "grew"} project ${r.project} — ${r.proposals} proposal(s), ${r.clips} clip(s)${extra.final ? " (final: it reads the corpus now)" : ""}`); for (const n of r.notes ?? []) await note(`umtool: ${n}`); } catch (e) { state = { ...state, mined: { ...(state.mined ?? { project, proposals: 0, clips: 0, at: now().toISOString() }), error: (e as Error).message } }; await note(`umtool: not mined this tick (${(e as Error).message})`); } }; await note( `following ${slug}/${id}: a tick every ${options.everyMinutes} min, at most ${options.maxChunkMinutes} min of audio each, ` + `${options.overlapSeconds} s overlap; ${options.scan ? "laugh scan on" : "no laugh scan"}; ${options.mine ? `windows into umtool project ${project}` : "no mining"}` + `${doc.transcribedTo > 0 ? `; resuming at ${clock(doc.transcribedTo)}` : ""}`, ); // 0. The recording's record (record-live writes it before its recorder starts). const waitedFrom = Date.now(); let record: LiveRecordingRecord | null = null; while (!signal.aborted) { record = await liveRecordingSidecar.load(videoDir); if (record) break; if (Date.now() - waitedFrom >= (deps.recordWaitMs ?? RECORD_WAIT_MS)) { state = { ...state, status: "failed", error: `${slug}/${id} has no live-recording.json: is it being recorded (pnpm ops record-live)?` }; await note(state.error!); throw new Error(state.error); } await wait(5_000, signal); } // 1. The ticks, while it records. let lastWait = ""; let memoryHeld = false; while (!signal.aborted) { record = (await liveRecordingSidecar.load(videoDir)) ?? record; if (!record || record.status !== "recording") break; const src = await findLiveSource({ slugStore, id, record, probe }); if ("wait" in src) { if (src.wait !== lastWait) { state = withSkip(state, "unreadable"); await note(`waiting: ${src.wait}`); lastWait = src.wait; } await wait(deps.sourcePollMs ?? SOURCE_POLL_MS, signal); continue; } lastWait = ""; // The basis: the part a transcript is on. if (doc.basis && doc.basis.stem !== src.stem) { const moved = await rebase(src); if (moved === "wait") { await wait(deps.sourcePollMs ?? SOURCE_POLL_MS, signal); continue; } } if (!doc.basis) doc = { ...doc, basis: { stem: src.stem, audioFile: src.audioFile, kind: src.kind } }; // The gates. const mem = floor > 0 ? await memory() : null; if (mem !== null && mem < floor) { if (!memoryHeld) { state = withSkip(state, "memory"); await note(`tick delayed: MemAvailable ${mem} MB is under the floor of ${floor} MB (HEAVY_MIN_FREE_MB); re-checked every minute`); memoryHeld = true; } await wait(deps.memoryPollMs ?? MEMORY_POLL_MS, signal); continue; } if (memoryHeld) await note(`memory back over the floor (${mem ?? "?"} MB): ticking`); memoryHeld = false; const freeBytes = await free(slugStore).catch(() => Infinity); if (freeBytes < PRECLIP_MIN_FREE_DISK_BYTES) { state = withSkip(state, "disk"); await note(`tick skipped: the store's disk has ${formatBytes(freeBytes)} free (a tick needs ${formatBytes(PRECLIP_MIN_FREE_DISK_BYTES)})`); await wait(options.everyMinutes * 60_000, signal); continue; } const recorded = (await probe(src.audioPath))?.seconds ?? null; state = { ...state, recordedSeconds: recorded }; // The fingerprint of the basis, once it holds enough (the landing's check). if (!doc.fingerprint && recorded !== null) { const span = fingerprintSpan(recorded); // At 60 s in, once that is well behind the live edge. if (span && span.from > 0 && recorded >= span.from + span.dur + 5) { const env = await envelope(src.audioPath, span.from, span.dur); if (env) doc = { ...doc, fingerprint: { from: span.from, hop: FINGERPRINT_HOP_SECONDS, env } }; } } const plan = planTick({ transcribedTo: doc.transcribedTo, recordedSeconds: recorded, opts: options }); if (plan.action === "wait") { state = withSkip(state, "no new data"); await note(`tick skipped: ${plan.reason}`); await saveDoc(); await wait(options.everyMinutes * 60_000, signal); continue; } // The tick. const n = state.ticks + 1; await mkdir(workDir, { recursive: true }); const scanned: { part: ScanPart | null } = { part: null }; const began = Date.now(); try { say(`pre-clip: tick ${n}: transcribing ${clock(plan.from)}–${clock(plan.to)} of ${src.audioFile}${plan.behind > 0 ? ` (${clock(plan.behind)} more behind it)` : ""}`); const t = await transcribe({ file: src.audioPath, from: plan.from, to: plan.to, scratchParent: workDir, onLog: say, signal, ...(o.ctx ? { ctx: o.ctx } : {}), ...(options.scan ? { withWav: async (wav: string, seconds: number) => { try { scanned.part = await scanWav(wav, plan.from, seconds, path.join(workDir, "scan")); } catch (e) { say(`pre-clip: the laugh scan of this span failed (${(e as Error).message}); the transcript is kept`); } }, } : {}), }); if (signal.aborted) break; doc = appendSpan(doc, { from: plan.from, to: plan.to, cues: t.cues, words: t.words, worker: t.worker, ms: t.ms, waitedMs: t.waitedMs }, now()); const scanPart = scanned.part; if (scanPart) { try { doc = { ...doc, scan: spliceScan(doc.scan, scanPart) }; } catch (e) { say(`pre-clip: the scan was not joined (${(e as Error).message})`); } } await saveDoc(); state = { ...state, ticks: n, transcribedSeconds: doc.transcribedTo }; await note( `tick ${n}: ${clock(plan.from)}–${clock(plan.to)} transcribed — ${t.cues.length} cue(s), ${t.words.length} word(s)` + `${t.worker ? ` on ${t.worker}` : ""} in ${Math.round(t.ms / 1000)} s${t.waitedMs >= 1000 ? ` after ${Math.round(t.waitedMs / 1000)} s waiting for the worker` : ""}` + `${scanPart ? `; scanned (${scanPart.model ?? "energy only"})` : ""}`, ); } catch (e) { if (signal.aborted) break; state = withSkip(state, "failed"); await note(`tick ${n} failed after ${Math.round((Date.now() - began) / 1000)} s: ${(e as Error).message}`); await wait(options.everyMinutes * 60_000, signal); continue; } finally { await rm(workDir, { recursive: true, force: true }).catch(() => {}); } await mineNow(); await livePreclipSidecar.write(videoDir, state); await wait(nextTickDelayMs(plan.behind, options), signal); } await rm(workDir, { recursive: true, force: true }).catch(() => {}); if (signal.aborted) { state = { ...state, status: "stopped" }; await note(`stopped at ${clock(doc.transcribedTo)} transcribed (the recording goes on; live-preclip {action: "start"} resumes)`); await saveDoc(); say(`${LIVE_PRECLIP_RESULT_MARKER}${JSON.stringify(summary())}`); return summary(); } // 2. The stream is over. if (!record || record.kept === undefined) { state = { ...state, status: "stopped" }; await note(`the recording ended ${record?.status ?? "?"} with nothing landed${record?.error ? ` (${record.error})` : ""}: the live transcript stays provisional`); say(`${LIVE_PRECLIP_RESULT_MARKER}${JSON.stringify(summary())}`); return summary(); } const landedPart = record.landedPart !== undefined ? record.parts[record.landedPart] : undefined; const check = await clockCheck(landedPart?.stem ?? null); doc = { ...doc, status: "landed", landed: { at: now().toISOString(), check } }; await saveDoc(); state = { ...state, status: "waiting-final", check }; await note(`landed: ${check.why}${check.verdict === "same" || check.verdict === "same-recording" ? "" : " — the project's windows are flagged"}`); await mineNow({ check }); // 3. The final transcript supersedes the live one. const until = Date.now() + (deps.finalWaitMs ?? FINAL_WAIT_MS); let said = false; while (!signal.aborted && !(await hasFinal(videoDir))) { if (!said) { await note("waiting for the final transcript (the landing handed the recording to the transcription lane)"); said = true; } if (Date.now() >= until) { await note('no final transcript yet: once there is one, pnpm ops live-preclip {"action": "finalize"} finishes the supersede'); say(`${LIVE_PRECLIP_RESULT_MARKER}${JSON.stringify(summary())}`); return summary(); } await wait(deps.finalPollMs ?? FINAL_POLL_MS, signal); } if (signal.aborted) { await note('stopped while waiting for the final transcript: pnpm ops live-preclip {"action": "finalize"} finishes it'); say(`${LIVE_PRECLIP_RESULT_MARKER}${JSON.stringify(summary())}`); return summary(); } await supersede(); say(`${LIVE_PRECLIP_RESULT_MARKER}${JSON.stringify(summary())}`); return summary(); // --- the pieces --- // A new part is being written (a restart, a fallback): its clock is the // old one when its audio at the fingerprint's span matches; else the live // transcript starts again on it. async function rebase(src: LiveSource): Promise<"same" | "restarted" | "wait"> { const fp = doc.fingerprint; if (fp) { const have = (await probe(src.audioPath))?.seconds ?? 0; const pad = FINGERPRINT_MAX_LAG_SECONDS; if (have < fp.from + fp.env.length * fp.hop + pad) { if (lastWait !== `rebase ${src.stem}`) { await note(`the recording moved to ${src.stem}; comparing its clock once it holds ${clock(fp.from + fp.env.length * fp.hop + pad)}`); lastWait = `rebase ${src.stem}`; } return "wait"; } const env = await envelope(src.audioPath, Math.max(0, fp.from - pad), fp.env.length * fp.hop + 2 * pad); const padFrames = Math.round(Math.min(pad, fp.from) / fp.hop); const verdict = env ? judgeClock(compareEnvelopes(fp.env, env, padFrames), fp.hop, now()) : null; if (verdict?.verdict === "same") { doc = { ...doc, basis: { stem: src.stem, audioFile: src.audioFile, kind: src.kind } }; await note(`the recording moved to ${src.stem}: the same clock (${verdict.why}); the live transcript goes on`); return "same"; } await note(`the recording moved to ${src.stem} on another clock (${verdict ? verdict.why : "its audio could not be read"}): the live transcript starts again on it`); } else { await note(`the recording moved to ${src.stem} before a fingerprint was taken: the live transcript starts again on it`); } doc = { ...emptyLiveTranscript(now()), restarts: doc.restarts + 1, basis: { stem: src.stem, audioFile: src.audioFile, kind: src.kind } }; await saveDoc(); return "restarted"; } async function clockCheck(landedStem: string | null): Promise { const at = now().toISOString(); if (doc.basis && landedStem && landedStem === doc.basis.stem) { return { verdict: "same-recording", why: `the landed video is the recording the live transcript followed (${landedStem})`, at }; } const fp = doc.fingerprint; if (!fp) return { verdict: "unverified", why: "no fingerprint was taken while it was live", at }; const saved = await (deps.savedVideo ?? defaultSavedVideo)(videoDir); if (!saved) return { verdict: "unverified", why: "the landed video's saved container is not readable", at }; const pad = Math.min(FINGERPRINT_MAX_LAG_SECONDS, fp.from); const env = await envelope(saved, fp.from - pad, fp.env.length * fp.hop + 2 * pad); if (!env) return { verdict: "unverified", why: "the landed video's audio could not be read at the fingerprint", at }; return judgeClock(compareEnvelopes(fp.env, env, Math.round(pad / fp.hop)), fp.hop, now()); } async function supersede() { doc = { ...doc, status: "superseded", supersededAt: now().toISOString() }; await saveDoc(); state = { ...state, status: "superseded" }; await note("the final transcript is here: the live transcript is superseded"); await mineNow({ final: true, ...(state.check ? { check: state.check } : {}) }); await livePreclipSidecar.write(videoDir, state); } } async function defaultSavedVideo(videoDir: string): Promise { const pointer = await loadSavedVideo(videoDir).catch(() => null); return pointer ? savedVideoPath(pointer) : null; } // --- the ops actions ----------------------------------------------------------------- function runningJobOf(slug: string, id: string) { const key = livePreclipQueueKey(slug, id); return getRegistry() .list() .find((j) => j.queueKey === key && (j.status === "running" || j.status === "queued")); } export async function startLivePreclipJob(o: { paths: Paths; slug: string; id: string; channelConfig: ChannelConfig; options: PreclipOptions; // Refuse unless the recording is in progress (an ops start); record-live // starts it before its record says so. requireRecording?: boolean; deps?: LivePreclipDeps; }): Promise { const videoDir = path.join(o.paths.channelsDir, o.slug, "data", o.id); if (o.requireRecording !== false) { const rec = await liveRecordingSidecar.load(videoDir); if (!rec) return { ok: false, error: `${o.slug}/${o.id} is not being recorded (no live-recording.json): start it with record-live {"preclip": true}` }; if (rec.status !== "recording") { return { ok: false, error: `${o.slug}/${o.id}'s recording is ${rec.status}, not in progress${rec.status === "landed" || rec.status === "cancelled" || rec.status === "interrupted" ? ' — "finalize" supersedes a live transcript once the final one is here' : ""}` }; } } const busy = runningJobOf(o.slug, o.id); if (busy) return { ok: false, info: true, error: `Pre-clip is already running for ${o.slug}/${o.id} (job ${busy.id})` }; return runManagedFunction({ kind: LIVE_PRECLIP_JOB_KIND, queueKey: livePreclipQueueKey(o.slug, o.id), paths: o.paths, channelSlug: o.slug, videoId: o.id, network: false, fn: async (onLog, signal, _p, ctx) => { await runLivePreclip({ paths: o.paths, slug: o.slug, id: o.id, channelConfig: o.channelConfig, options: o.options, onLog, signal, ctx, ...(o.deps ? { deps: o.deps } : {}) }); }, }); } /** Stop a running pre-clip (the recording is not touched). */ export function stopLivePreclip(slug: string, id: string): { ok: true; jobId: string } | { ok: false; error: string } { const job = runningJobOf(slug, id); if (!job) return { ok: false, error: `no pre-clip is running for ${slug}/${id}` }; getRegistry().cancel(job.id); return { ok: true, jobId: job.id }; } export type LivePreclipStatusView = { slug: string; id: string; job: { id: string; status: string } | null; state: LivePreclipState | null; transcript: { status: LiveTranscriptDoc["status"]; transcribedTo: number; cues: number; words: number; chunks: number; restarts: number; basis: LiveTranscriptDoc["basis"]; landed?: LiveTranscriptDoc["landed"]; lastCues: Cue[]; } | null; recording: { status: string; parts: number } | null; }; export async function livePreclipStatus(paths: Paths, slug: string, id: string): Promise { const videoDir = path.join(paths.channelsDir, slug, "data", id); const [state, doc, rec] = await Promise.all([livePreclipSidecar.load(videoDir), liveTranscriptSidecar.load(videoDir), liveRecordingSidecar.load(videoDir)]); const job = runningJobOf(slug, id); return { slug, id, job: job ? { id: job.id, status: job.status } : null, state, transcript: doc ? { status: doc.status, transcribedTo: doc.transcribedTo, cues: doc.cues.length, words: doc.words.length, chunks: doc.chunks.length, restarts: doc.restarts, basis: doc.basis, ...(doc.landed ? { landed: doc.landed } : {}), lastCues: doc.cues.slice(-8), } : null, recording: rec ? { status: rec.status, parts: rec.parts.length } : null, }; } /** The supersede by hand (`action: "finalize"`), once the final transcript is here. */ export async function finalizeLivePreclip(o: { paths: Paths; slug: string; id: string; options?: Pick; deps?: Pick; }): Promise<{ ok: true; project: string | null; check: ClockCheck | null } | { ok: false; error: string }> { const videoDir = path.join(o.paths.channelsDir, o.slug, "data", o.id); const now = o.deps?.now ?? (() => new Date()); if (runningJobOf(o.slug, o.id)) return { ok: false, error: `pre-clip is still running for ${o.slug}/${o.id}: it supersedes by itself, or stop it first` }; const doc = await liveTranscriptSidecar.load(videoDir); if (!doc) return { ok: false, error: `${o.slug}/${o.id} has no live transcript` }; if (!(await (o.deps?.hasFinalTranscript ?? hasCorpusTranscript)(videoDir))) { return { ok: false, error: `${o.slug}/${o.id} has no final transcript yet (transcript.json or an English caption track)` }; } const state = await livePreclipSidecar.load(videoDir); const check = doc.landed?.check ?? state?.check ?? null; await liveTranscriptSidecar.write(videoDir, { ...doc, status: "superseded", supersededAt: now().toISOString() }); let mine = o.deps?.mine; if (mine === undefined) { const umtool = resolveUmtoolUrl(); const token = getWorkerToken(); mine = umtool && token ? umtoolMiner(umtool, token) : null; } const project = o.options?.project ?? state?.mined?.project ?? liveProjectSlug(o.id); let mined: Awaited> | null = null; if (mine) mined = await mine({ slug: project, from: `${o.slug}/${o.id}`, final: true, ...(check ? { check } : {}) }); if (state) { await livePreclipSidecar.write( videoDir, withLogLine( { ...state, status: "superseded", ...(mined ? { mined: { project: mined.project, proposals: mined.proposals, clips: mined.clips, at: now().toISOString() } } : {}), }, `finalized by hand: the live transcript is superseded${mined ? `; umtool project ${mined.project} reads the corpus now` : ""}`, now(), ), ); } return { ok: true, project: mined?.project ?? null, check }; }