Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 18e9ea74c08511dfd590c05c786a1291187d4475
parent 7bef35c3f6b86db061a2e86013bf72a886ab0840
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 27 Oct 2026 12:25:57 -0400

live pre-clip: the tick, the live transcript, the clock check, the live window

A recording in progress transcribed while it records (plans/live-preclip.md):
lib/livePreclip.ts is the arithmetic (the tick plan, the overlap splice, the
scan by window index, the RMS-envelope clock check, the state);
lib/livePreclip-server.ts the files (which part and stream a tick reads, its
length, a window cut from it now); controller/livePreclip.ts the job
(live-preclip, one per stream, a worker lease per tick, coalesced, the memory
floor and the disk said, the landing's check and the supersede);
controller/liveClip.ts the live window and the share job. record-live takes
"preclip" and records each part's stem. transcribeFile takes a tier, a scratch
parent (never /tmp for a live tick) and the cut WAV for the laugh scan.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Acommon/controller/liveClip.ts | 273+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/livePreclip.test.ts | 309+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/livePreclip.ts | 788+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/recordLive.test.ts | 45+++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/recordLive.ts | 42+++++++++++++++++++++++++++++++++++++++---
Mcommon/controller/transcribeFile.ts | 13+++++++++++--
Mcommon/jobs/jobKinds.ts | 32++++++++++++++++++++++++++++++++
Mcommon/lib/clipWindow.ts | 6++++--
Mcommon/lib/liveCapture.ts | 3+++
Acommon/lib/livePreclip-server.test.ts | 195+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/livePreclip-server.ts | 209+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/livePreclip.test.ts | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/livePreclip.ts | 608+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13 files changed, 2721 insertions(+), 7 deletions(-)

diff --git a/common/controller/liveClip.ts b/common/controller/liveClip.ts @@ -0,0 +1,273 @@ +// A SHAREABLE CLIP OF A STREAM STILL LIVE (plans/live-preclip.md, "Shareable +// clips from a partial") — the operator's "in case something really +// interesting happens on a long stream". +// +// liveWindow `POST /api/media/live-window` (umtool asks it, WORKER_TOKEN): +// a window of the recording cut NOW into the clip cache, +// data/<id>/clips/<from>-<to>.mp4 — from the part being +// recorded while it records (the snapshot on demand: it reads +// the bytes written so far, so it is never older than the +// request), from the saved video once it has landed, or the +// window already in the cache. No network request; the +// recorder is only read. +// runLiveClipJob `pnpm ops live-clip {slug, id, start, end | clip, project?, +// replace?}`: umtool's `POST /api/report/live-share` — which +// asks the window above, adds the clip to the stream's +// project when it is given by seconds, and makes its short +// (build-video --short, no network, the live words as its +// captions) — followed to the end. The clip editor's Share now +// is the same umtool call. + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { liveRecordingSidecar } from "../lib/mediaImport-server"; +import { savedVideoDir } from "../lib/savedVideo"; +import { findContainingClipWindow, type ClipWindow } from "../lib/clipWindow-server"; +import { cutSavedVideoWindow, savedWindowSource } from "../lib/savedVideoWindow-server"; +import { checkLiveWindow, liveClipTooLong, liveProjectSlug, PROJECT_SLUG_RE } from "../lib/livePreclip"; +import { cutLiveWindow, findLiveSource, probeWith } from "../lib/livePreclip-server"; +import { umtoolUrl as resolveUmtoolUrl } from "../lib/umtoolUrl"; +import { getWorkerToken } from "../lib/workerToken"; +import { getRegistry } from "../jobs/registry"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; + +export const LIVE_CLIP_JOB_KIND = "live-clip"; +export const LIVE_CLIP_QUEUE = "live-clip"; +export const LIVE_CLIP_RESULT_MARKER = "@@live-clip "; +export const LIVE_CLIP_BODY_KEYS = ["slug", "id", "start", "end", "clip", "project", "replace"] as const; +export const LIVE_WINDOW_BODY_KEYS = ["slug", "id", "from", "to", "requestedBy", "manifest", "clipId", "reason"] as const; + +export type LiveWindowOutcome = + | { ok: true; window: Pick<ClipWindow, "path" | "file" | "from" | "to" | "bytes">; source: "cache" | "live-recording" | "saved-video"; recordedSeconds: number | null } + | { ok: false; status: number; error: string }; + +export async function liveWindow(o: { + paths: Paths; + slug: string; + id: string; + channelConfig: ChannelConfig; + from: number; + to: number; + requestedBy?: string; + manifest?: string; + clipId?: string; + reason?: string; + signal?: AbortSignal; +}): Promise<LiveWindowOutcome> { + const videoDir = path.join(o.paths.channelsDir, o.slug, "data", o.id); + const shape = checkLiveWindow(o.from, o.to, null); + if ("error" in shape) return { ok: false, status: 400, error: shape.error }; + const cached = await findContainingClipWindow(videoDir, shape.from, shape.to); + if (cached) return { ok: true, window: cached, source: "cache", recordedSeconds: null }; + const record = await liveRecordingSidecar.load(videoDir); + if (record?.status === "recording") { + const slugStore = path.dirname(savedVideoDir(o.paths, o.channelConfig, o.slug, o.id)); + const probe = probeWith(o.paths.ffprobeBin); + const src = await findLiveSource({ slugStore, id: o.id, record, probe }); + if ("wait" in src) return { ok: false, status: 409, error: `the recording cannot be read yet: ${src.wait}` }; + // Both files of a separate pair must hold the window. + const a = (await probe(src.audioPath))?.seconds ?? null; + const v = src.videoPath && src.videoPath !== src.audioPath ? ((await probe(src.videoPath))?.seconds ?? null) : a; + const recorded = a === null || v === null ? null : Math.min(a, v); + if (recorded === null) return { ok: false, status: 409, error: `the recording's length cannot be read yet (${src.stem})` }; + const win = checkLiveWindow(o.from, o.to, recorded); + if ("error" in win) return { ok: false, status: 409, error: win.error }; + const cut = await cutLiveWindow({ + ffmpegBin: o.paths.ffmpegBin, + videoDir, + source: src, + from: win.from, + to: win.to, + requestedBy: o.requestedBy ?? "live-clip", + ...(o.reason ? { reason: o.reason } : {}), + ...(o.clipId ? { clipId: o.clipId } : {}), + ...(o.manifest ? { manifest: o.manifest } : {}), + ...(o.signal ? { signal: o.signal } : {}), + }); + return { ok: true, window: cut, source: "live-recording", recordedSeconds: recorded }; + } + // Landed (or never recorded here): the saved video, as any window is cut. + const saved = await savedWindowSource({ paths: o.paths, slug: o.slug, videoDir, from: shape.from, to: shape.to }); + if (saved.kind === "unreadable") return { ok: false, status: 503, error: saved.error }; + if (saved.kind === "none") { + return { ok: false, status: 404, error: `${o.slug}/${o.id} is not being recorded and has no saved video to cut the window from` }; + } + if (saved.kind === "not-covering") { + return { ok: false, status: 409, error: `the saved video holds ${Math.round(saved.durationSec)} s; the window ends at ${shape.to} s` }; + } + const cut = await cutSavedVideoWindow({ + paths: o.paths, + videoDir, + source: saved, + from: shape.from, + to: shape.to, + provenance: { + requestedBy: o.requestedBy ?? "live-clip", + ...(o.reason ? { reason: o.reason } : {}), + ...(o.clipId ? { clipId: o.clipId } : {}), + ...(o.manifest ? { manifest: o.manifest } : {}), + }, + ...(o.signal ? { signal: o.signal } : {}), + }); + return { ok: true, window: cut, source: "saved-video", recordedSeconds: saved.durationSec }; +} + +// --- the ops job ------------------------------------------------------------------------ + +export type LiveClipRequest = { + slug: string; + id: string; + start?: number; + end?: number; + clip?: string; + project: string; + replace?: boolean; +}; + +type Check<T> = { ok: true; value: T } | { ok: false; error: string }; + +export function parseLiveClipBody(body: Record<string, unknown>): Check<LiveClipRequest> { + const slug = typeof body.slug === "string" ? body.slug.trim() : ""; + const id = typeof body.id === "string" ? body.id.trim() : ""; + if (!slug) return { ok: false, error: '"slug" is required' }; + if (!id || !/^[\w.-]+$/.test(id) || id === "." || id === "..") return { ok: false, error: '"id" is required: the record\'s id' }; + const project = body.project === undefined ? liveProjectSlug(id) : body.project; + if (typeof project !== "string" || !PROJECT_SLUG_RE.test(project)) return { ok: false, error: '"project" is a umtool project slug' }; + const out: LiveClipRequest = { slug, id, project }; + if (body.clip !== undefined) { + if (typeof body.clip !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$/.test(body.clip)) return { ok: false, error: '"clip" is a clip id of the project ("r003")' }; + if (body.start !== undefined || body.end !== undefined) return { ok: false, error: 'give "clip" or "start" and "end", not both' }; + out.clip = body.clip; + } else { + if (typeof body.start !== "number" || typeof body.end !== "number") return { ok: false, error: 'give "start" and "end" (seconds of the stream), or "clip"' }; + const long = liveClipTooLong(body.start, body.end); + if (long) return { ok: false, error: long }; + out.start = body.start; + out.end = body.end; + } + if (body.replace !== undefined) { + if (typeof body.replace !== "boolean") return { ok: false, error: '"replace" must be true or false' }; + out.replace = body.replace; + } + return { ok: true, value: out }; +} + +export type LiveClipDeps = { + fetch?: typeof fetch; + umtoolUrl?: string | null; + workerToken?: string; + pollMs?: number; + sleep?: (ms: number) => Promise<void>; +}; + +async function json(res: Response): Promise<Record<string, unknown>> { + try { + const j = (await res.json()) as unknown; + return j && typeof j === "object" && !Array.isArray(j) ? (j as Record<string, unknown>) : {}; + } catch { + return {}; + } +} + +export type LiveClipResult = { project: string; clip: string; short: string; url: string; bytes: number | null; window: { from: number; to: number } | null }; + +/** umtool's live share, followed to the end. */ +export async function runLiveClip(req: LiveClipRequest, o: { onLog: (s: string) => void; signal: AbortSignal; deps?: LiveClipDeps }): Promise<LiveClipResult> { + const deps = o.deps ?? {}; + const doFetch = deps.fetch ?? fetch; + const umtool = deps.umtoolUrl === undefined ? resolveUmtoolUrl() : deps.umtoolUrl; + const token = deps.workerToken ?? getWorkerToken(); + if (!umtool) throw new Error("UMTOOL_URL is not set on the editor: a live share is made by umtool"); + if (!token) throw new Error("WORKER_TOKEN is not set on the editor: umtool's live-share route is asked with it"); + const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" }; + const say = (s: string) => o.onLog(s.endsWith("\n") ? s : `${s}\n`); + const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms))); + const body = { + project: req.project, + from: `${req.slug}/${req.id}`, + ...(req.clip ? { clip: req.clip } : { start: req.start, end: req.end }), + ...(req.replace ? { replace: true } : {}), + }; + say(`Share ${req.clip ? `clip ${req.clip}` : `${req.start}–${req.end} s`} of ${req.slug}/${req.id} from umtool project ${req.project}`); + let res: Response; + try { + res = await doFetch(`${umtool}/api/report/live-share`, { method: "POST", headers, body: JSON.stringify(body), signal: o.signal }); + } catch (e) { + throw new Error(`umtool at ${umtool} did not answer (${(e as Error).message}) — is it running?`); + } + const posted = await json(res); + if (!res.ok) throw new Error(`umtool refused the share (HTTP ${res.status}): ${typeof posted.error === "string" ? posted.error : "no reason given"}`); + const job = posted.job as { id?: unknown } | undefined; + const jobId = typeof job?.id === "string" ? job.id : null; + const clip = typeof posted.clip === "string" ? posted.clip : req.clip ?? ""; + const window = posted.window && typeof posted.window === "object" ? (posted.window as { from: number; to: number }) : null; + if (!jobId || !clip) throw new Error(`umtool's answer named no job or clip: ${JSON.stringify(posted).slice(0, 300)}`); + if (window) say(`window ${window.from}–${window.to} s cut from the ${String(posted.windowSource ?? "recording")}`); + say(`umtool: making the short of ${clip} (job ${jobId})`); + let since = 0; + let failures = 0; + for (;;) { + if (o.signal.aborted) { + await doFetch(`${umtool}/api/report/shorts?cancel=${encodeURIComponent(jobId)}`, { method: "POST", headers }).catch(() => null); + throw new Error(`cancelled; umtool job ${jobId} was asked to stop`); + } + let view: Record<string, unknown> | null = null; + try { + const r = await doFetch(`${umtool}/api/report/shorts?job=${encodeURIComponent(jobId)}&since=${since}`, { headers, signal: o.signal }); + if (r.status === 404) throw new Error(`umtool no longer knows job ${jobId} (restarted?)`); + if (r.ok) view = await json(r); + } catch (e) { + if (/no longer knows/.test((e as Error).message)) throw e; + } + if (!view) { + if (++failures >= 15) throw new Error(`umtool at ${umtool} stopped answering while job ${jobId} ran`); + } else { + failures = 0; + const log = Array.isArray(view.log) ? view.log.filter((l): l is string => typeof l === "string") : []; + for (const line of log) say(`umtool: ${line.replace(/\n$/, "")}`); + since = typeof view.next === "number" ? view.next : since + log.length; + const state = typeof view.state === "string" ? view.state : "running"; + if (state !== "running") { + if (state !== "done") throw new Error(`umtool job ${jobId} failed: ${typeof view.error === "string" && view.error ? view.error : `the job ended ${state}`}`); + break; + } + } + await sleep(deps.pollMs ?? 2000); + } + // The size, from the list of shorts. + let bytes: number | null = null; + try { + const r = await doFetch(`${umtool}/api/report/shorts?project=${encodeURIComponent(req.project)}`, { headers }); + const j = await json(r); + const hit = Array.isArray(j.shorts) ? (j.shorts as { clip?: string; size?: number }[]).find((s) => s.clip === clip) : undefined; + bytes = typeof hit?.size === "number" ? hit.size : null; + } catch { + bytes = null; + } + const url = `${umtool}/api/report/shorts?project=${encodeURIComponent(req.project)}&clip=${encodeURIComponent(clip)}&file=1&download=1`; + return { project: req.project, clip, short: `shorts/${clip}.mp4`, url, bytes, window }; +} + +export async function runLiveClipJob(o: { paths: Paths; request: LiveClipRequest; deps?: LiveClipDeps }): Promise<StreamActionResult> { + const umtool = o.deps?.umtoolUrl === undefined ? resolveUmtoolUrl() : o.deps.umtoolUrl; + if (!umtool) return { ok: false, error: "UMTOOL_URL is not set on the editor: a live share is made by umtool (e.g. UMTOOL_URL=http://localhost:3050)" }; + if (!(o.deps?.workerToken ?? getWorkerToken())) return { ok: false, error: "WORKER_TOKEN is not set on the editor" }; + const busy = getRegistry() + .list() + .find((j) => j.queueKey === LIVE_CLIP_QUEUE && (j.status === "running" || j.status === "queued") && j.videoId === o.request.id); + if (busy) return { ok: false, info: true, error: `A share of ${o.request.slug}/${o.request.id} is already being made (job ${busy.id})` }; + return runManagedFunction({ + kind: LIVE_CLIP_JOB_KIND, + queueKey: LIVE_CLIP_QUEUE, + paths: o.paths, + channelSlug: o.request.slug, + videoId: o.request.id, + network: false, + fn: async (onLog, signal) => { + const r = await runLiveClip(o.request, { onLog, signal, ...(o.deps ? { deps: o.deps } : {}) }); + onLog(`The short: ${r.url}${r.bytes !== null ? ` (${(r.bytes / 1024 / 1024).toFixed(1)} MiB)` : ""}\n`); + onLog(`${LIVE_CLIP_RESULT_MARKER}${JSON.stringify(r)}\n`); + }, + }); +} diff --git a/common/controller/livePreclip.test.ts b/common/controller/livePreclip.test.ts @@ -0,0 +1,309 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { LiveRecordingRecord } from "../lib/liveCapture"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/livePreclip.test.ts +// +// Live pre-clip's loop (controller/livePreclip.ts) over a temp corpus: the +// recording is a record and part files on disk whose LENGTH is a number the +// test moves; the worker, the scan, umtool and the clock are stubs. Each +// `sleep` the loop takes runs the next step of the script — the world moving +// on while it waits. + +const ROOT = await mkdtemp(path.join(tmpdir(), "live-preclip-ctl-")); +const CORPUS = path.join(ROOT, "transcripts"); +process.env.TRANSCRIPTS_DIR = CORPUS; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +await mkdir(CORPUS, { recursive: true }); +await writeFile(process.env.SETTINGS_FILE, "{}"); + +const { getPaths } = await import("../lib/paths"); +const { runLivePreclip, parseLivePreclipBody, memoryFloorMb, finalizeLivePreclip } = await import("./livePreclip"); +const { liveRecordingSidecar } = await import("../lib/mediaImport-server"); +const { liveTranscriptSidecar, livePreclipSidecar } = await import("../lib/livePreclip-server"); +const { PRECLIP_DEFAULTS } = await import("../lib/livePreclip"); +type Deps = NonNullable<Parameters<typeof runLivePreclip>[0]["deps"]>; + +const paths = getPaths(); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const SLUG = "synth-live"; +const CONFIG = { handling: "transcribe", url: "https://www.youtube.com/@synth", platform: "youtube", name: "Synth" } as ChannelConfig; +const slugStore = path.join(paths.savedVideosDir, SLUG); +await mkdir(slugStore, { recursive: true }); + +const stemOf = (id: string, tag: string) => `.${id}.live-2026-10-27T12-00-00-000Z.${tag}`; + +async function setup(id: string) { + const videoDir = path.join(CORPUS, "channels", SLUG, "data", id); + await mkdir(videoDir, { recursive: true }); + const stem = stemOf(id, "ytdlp"); + await writeFile(path.join(slugStore, `${stem}.ts`), "growing"); + const record: LiveRecordingRecord = { + status: "recording", + url: `https://www.youtube.com/watch?v=${id}`, + platform: "youtube", + fromStart: true, + startedAt: "2026-10-27T12:00:00Z", + parts: [{ method: "ytdlp", url: "u", fromStart: true, startedAt: "2026-10-27T12:00:00Z", stem }], + }; + await liveRecordingSidecar.write(videoDir, record); + return { videoDir, stem, record }; +} + +// One cue a minute, at m·60 + 1 (and its word), inside [from, to). +function fakeTranscript(from: number, to: number) { + const cues = []; + const words = []; + for (let m = Math.ceil((from - 1) / 60); m * 60 + 1 < to; m += 1) { + const t = m * 60 + 1; + if (t < from) continue; + cues.push({ start: t, end: t + 2, text: `minute ${m}` }); + words.push({ w: `m${m}`, start: t, end: t + 0.4 }); + } + return { cues, words }; +} + +// An envelope of a recording on a given clock: the same "audio" at the same +// stream second, offset by the file's `shift` (a clock that differs). +const pattern = (t: number, seed: number) => Math.round((-30 + 12 * Math.sin(t * 1.7 + seed) + 6 * Math.sin(t * 0.31 * (seed + 1))) * 10) / 10; +function envelopeFor(seedOf: (file: string) => number, shiftOf: (file: string) => number = () => 0) { + return async (file: string, from: number, dur: number) => { + const out = []; + for (let k = 0; k < Math.round(dur / 0.1); k += 1) out.push(pattern(from + k * 0.1 + shiftOf(file), seedOf(file))); + return out; + }; +} + +function world(o: { recorded: Map<string, number>; script: (() => void | Promise<void>)[]; deps?: Partial<Deps> }) { + const calls: { from: number; to: number }[] = []; + const mined: Record<string, unknown>[] = []; + let mem = [9000]; + const lines: string[] = []; + const ac = new AbortController(); + let finalHere = false; + const deps: Deps = { + now: () => new Date("2026-10-27T12:30:00Z"), + sleep: async () => { + const step = o.script.shift(); + if (step) await step(); + else ac.abort(); + }, + memAvailableMb: async () => (mem.length > 1 ? mem.shift()! : mem[0]!), + memoryFloorMb: 6000, + freeBytes: async () => 1e12, + probe: async (file) => ({ seconds: o.recorded.get(path.basename(file)) ?? null, hasVideo: true, hasAudio: true }), + transcribe: async ({ from, to, withWav }) => { + calls.push({ from, to }); + await withWav?.("span.wav", to - from); + return { ...fakeTranscript(from, to), worker: "gpu", ms: 1000, waitedMs: 0 }; + }, + scanWav: async (_wav, from, seconds) => ({ t0: from, hop: 0.5, window: 1, energy: new Array(Math.floor(seconds / 0.5)).fill(-30), laugh: null, model: null }), + envelope: envelopeFor(() => 1), + mine: async (body) => { + mined.push(body); + return { project: body.slug, created: mined.length === 1, proposals: mined.length, clips: 0 }; + }, + savedVideo: async () => null, + hasFinalTranscript: async () => finalHere, + recordWaitMs: 1000, + ...o.deps, + }; + return { + deps, + calls, + mined, + lines, + ac, + setMem: (m: number[]) => (mem = m), + setFinal: (v: boolean) => (finalHere = v), + }; +} + +test("ticks: memory floor, a busy worker coalesced, catch-up, the landing, the supersede", async () => { + const id = "live001"; + const { videoDir, stem, record } = await setup(id); + const file = `${stem}.ts`; + const recorded = new Map([[file, 600]]); + const script: (() => void | Promise<void>)[] = []; + const w = world({ recorded, script }); + w.setMem([3000, 9000]); + // The first tick's worker takes 25 minutes to free up: the recording grows + // under it, and the next tick takes all of it (capped at 20 min, then a + // catch-up tick at once) — never one tick per period that passed. + const transcribe = w.deps.transcribe!; + w.deps.transcribe = async (o) => { + const r = await transcribe(o); + if (w.calls.length === 1) recorded.set(file, 600 + 25 * 60); + return r; + }; + script.push( + () => {}, // the memory wait + () => {}, // after tick 1 + () => {}, // after tick 2 (0 ms: catching up) + async () => { + // after tick 3: the stream ends and lands. + await liveRecordingSidecar.write(videoDir, { ...record, status: "landed", kept: "new", landedPart: 0, endedAt: "2026-10-27T13:00:00Z" }); + }, + () => w.setFinal(true), // the wait for the final transcript + ); + const summary = await runLivePreclip({ paths, slug: SLUG, id, channelConfig: CONFIG, options: { ...PRECLIP_DEFAULTS }, onLog: (l) => w.lines.push(l), signal: w.ac.signal, deps: w.deps }); + + assert.deepEqual(w.calls, [ + { from: 0, to: 598 }, + { from: 583, to: 1783 }, + { from: 1768, to: 2098 }, + ]); + const doc = (await liveTranscriptSidecar.load(videoDir))!; + assert.equal(doc.status, "superseded"); + assert.equal(doc.transcribedTo, 2098); + const starts = doc.cues.map((c) => c.start); + assert.deepEqual(starts, [...new Set(starts)], "no cue twice across the overlaps"); + assert.equal(doc.cues.length, 35, "a cue a minute, 0:01 … 34:01"); + assert.equal(doc.words.length, 35); + // The scan of each span, joined by window index across the overlaps. + assert.equal(doc.scan?.energy.length, 2098 / 0.5); + assert.equal(doc.landed?.check.verdict, "same-recording"); + const state = (await livePreclipSidecar.load(videoDir))!; + assert.equal(state.status, "superseded"); + assert.equal(state.ticks, 3); + assert.equal(state.skipped.memory, 1); + assert.ok(w.lines.some((l) => /tick delayed: MemAvailable 3000 MB is under the floor of 6000 MB/.test(l))); + // umtool: once per tick, once at the landing (with the check), once final. + assert.equal(w.mined.length, 5); + assert.deepEqual(w.mined[3], { slug: `${id}-live`, from: `${SLUG}/${id}`, check: doc.landed!.check }); + assert.equal(w.mined[4]!.final, true); + assert.equal(summary.status, "superseded"); +}); + +test("no new data is a skipped tick; a recording that lands nothing leaves the transcript provisional", async () => { + const id = "live002"; + const { videoDir, stem, record } = await setup(id); + const recorded = new Map([[`${stem}.ts`, 300]]); + const script: (() => void | Promise<void>)[] = [ + () => {}, // after tick 1; nothing new next time + async () => { + await liveRecordingSidecar.write(videoDir, { ...record, status: "failed", error: "the stream went private" }); + }, + ]; + const w = world({ recorded, script }); + const s = await runLivePreclip({ paths, slug: SLUG, id, channelConfig: CONFIG, options: { ...PRECLIP_DEFAULTS, mine: false }, onLog: () => {}, signal: w.ac.signal, deps: w.deps }); + assert.equal(w.calls.length, 1); + const state = (await livePreclipSidecar.load(videoDir))!; + assert.equal(state.skipped["no new data"], 1); + assert.ok(state.log.some((l) => /no new data \(0 s new/.test(l))); + assert.equal(s.status, "stopped"); + assert.equal((await liveTranscriptSidecar.load(videoDir))!.status, "live"); + assert.equal(w.mined.length, 0, "mine: false"); +}); + +test("a recorder restart on the same clock goes on; on another clock the transcript starts again", async () => { + for (const sameClock of [true, false]) { + const id = sameClock ? "live003" : "live004"; + const { videoDir, stem, record } = await setup(id); + const stem2 = stemOf(id, "browser"); + const recorded = new Map([[`${stem}.ts`, 600]]); + const script: (() => void | Promise<void>)[] = [ + async () => { + // The yt-dlp part ended; the browser fallback records from the DVR start. + await writeFile(path.join(slugStore, `${stem2}.ts`), "growing"); + recorded.set(`${stem2}.ts`, 900); + await liveRecordingSidecar.write(videoDir, { + ...record, + parts: [ + { ...record.parts[0]!, endedAt: "2026-10-27T12:10:00Z" }, + { method: "browser", url: "u2", fromStart: true, startedAt: "2026-10-27T12:10:00Z", stem: stem2 }, + ], + }); + }, + () => {}, + async () => { + await liveRecordingSidecar.write(videoDir, { ...record, status: "cancelled", endedAt: "x" }); + }, + ]; + const w = world({ + recorded, + script, + deps: { envelope: envelopeFor((f) => (sameClock || !f.includes("browser") ? 1 : 7)) }, + }); + await runLivePreclip({ paths, slug: SLUG, id, channelConfig: CONFIG, options: { ...PRECLIP_DEFAULTS, mine: false }, onLog: () => {}, signal: w.ac.signal, deps: w.deps }); + const doc = (await liveTranscriptSidecar.load(videoDir))!; + assert.equal(doc.basis?.stem, stem2); + if (sameClock) { + assert.deepEqual(w.calls, [{ from: 0, to: 598 }, { from: 583, to: 898 }]); + assert.equal(doc.restarts, 0); + } else { + assert.deepEqual(w.calls, [{ from: 0, to: 598 }, { from: 0, to: 898 }]); + assert.equal(doc.restarts, 1); + assert.equal(doc.transcribedTo, 898); + } + } +}); + +test("a landed video not the followed part: the clock check compares the fingerprint", async () => { + for (const [shift, verdict] of [[0, "same"], [1.5, "shifted"]] as const) { + const id = `live05${shift ? "b" : "a"}`; + const { videoDir, stem, record } = await setup(id); + const recorded = new Map([[`${stem}.ts`, 600]]); + const script: (() => void | Promise<void>)[] = [ + async () => { + await liveRecordingSidecar.write(videoDir, { ...record, status: "landed", kept: "new" }); + }, + ]; + const w = world({ + recorded, + script, + deps: { + savedVideo: async () => "/store/landed.mp4", + envelope: envelopeFor(() => 1, (f) => (f === "/store/landed.mp4" ? -shift : 0)), + finalWaitMs: 0, + }, + }); + const s = await runLivePreclip({ paths, slug: SLUG, id, channelConfig: CONFIG, options: { ...PRECLIP_DEFAULTS, mine: false }, onLog: () => {}, signal: w.ac.signal, deps: w.deps }); + assert.equal(s.check?.verdict, verdict, JSON.stringify(s.check)); + if (verdict === "shifted") assert.equal(s.check?.lagSeconds, 1.5); + assert.equal(s.status, "waiting-final", "the final wait ran out"); + const state = (await livePreclipSidecar.load(videoDir))!; + assert.ok(state.log.some((l) => /finalize/.test(l))); + // By hand, once the final transcript is here. + await writeFile(path.join(videoDir, "transcript.json"), "{}"); + const mined: Record<string, unknown>[] = []; + const f = await finalizeLivePreclip({ + paths, + slug: SLUG, + id, + deps: { mine: async (b) => (mined.push(b), { project: b.slug, created: false, proposals: 1, clips: 1 }) }, + }); + assert.equal(f.ok, true); + assert.equal(mined[0]!.final, true); + assert.equal((await liveTranscriptSidecar.load(videoDir))!.status, "superseded"); + assert.equal((await livePreclipSidecar.load(videoDir))!.status, "superseded"); + } +}); + +test("stopped: the job's cancel leaves the recording alone and says how to resume", async () => { + const id = "live006"; + const { videoDir, stem } = await setup(id); + const recorded = new Map([[`${stem}.ts`, 600]]); + const w = world({ recorded, script: [] }); + const s = await runLivePreclip({ paths, slug: SLUG, id, channelConfig: CONFIG, options: { ...PRECLIP_DEFAULTS, mine: false }, onLog: () => {}, signal: w.ac.signal, deps: w.deps }); + assert.equal(s.status, "stopped"); + assert.equal((await liveRecordingSidecar.load(videoDir))!.status, "recording"); + assert.ok((await livePreclipSidecar.load(videoDir))!.log.some((l) => /resumes/.test(l))); +}); + +test("parseLivePreclipBody and memoryFloorMb", () => { + assert.deepEqual(parseLivePreclipBody({ slug: "a", id: "b" }), { ok: true, value: { slug: "a", id: "b", action: "start", options: { ...PRECLIP_DEFAULTS } } }); + const r = parseLivePreclipBody({ slug: "a", id: "b", action: "start", everyMinutes: 5 }); + assert.equal(r.ok && r.value.options.everyMinutes, 5); + assert.equal(parseLivePreclipBody({ slug: "a", id: "b", action: "go" }).ok, false); + assert.equal(parseLivePreclipBody({ slug: "a", id: "../x" }).ok, false); + assert.equal(memoryFloorMb({}), 6000); + assert.equal(memoryFloorMb({ HEAVY_MIN_FREE_MB: "4000" }), 4000); + assert.equal(memoryFloorMb({ HEAVY: "0" }), 0); +}); diff --git a/common/controller/livePreclip.ts b/common/controller/livePreclip.ts @@ -0,0 +1,788 @@ +// 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:<slug>:<id>`), 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 +// <from> -i <the growing file>`, 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/<id>/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, readdir, 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 { 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<PreclipOptions, "project"> { + const s = (getSettings() as { livePreclip?: Partial<PreclipOptions> }).livePreclip; + return { ...PRECLIP_DEFAULTS, ...(s ?? {}) }; +} + +/** HEAVY_MIN_FREE_MB when set (0 = no floor), else the slot's 6000. */ +export function memoryFloorMb(env: Readonly<Record<string, string | undefined>> = 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<T> = { 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<string, unknown>, defaults = PRECLIP_DEFAULTS): Check<LivePreclipRequest> { + 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<string, unknown> = {}; + 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<void>; +}) => 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<void>; + memAvailableMb?: () => Promise<number | null>; + memoryFloorMb?: number; + freeBytes?: (dir: string) => Promise<number>; + 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<ScanPart | null>; + envelope?: (file: string, from: number, dur: number) => Promise<number[] | null>; + // Null: umtool is not configured (mining is skipped, said once). + mine?: MineLive | null; + savedVideo?: (videoDir: string) => Promise<string | null>; + hasFinalTranscript?: (videoDir: string) => Promise<boolean>; + recordWaitMs?: number; + finalWaitMs?: number; + finalPollMs?: number; + memoryPollMs?: number; + sourcePollMs?: number; +}; + +function sleep(ms: number, signal: AbortSignal): Promise<void> { + 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<LivePreclipDeps["scanWav"]> { + 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<Record<string, unknown>> { + try { + const j = (await res.json()) as unknown; + return j && typeof j === "object" && !Array.isArray(j) ? (j as Record<string, unknown>) : {}; + } 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<boolean> { + const entries = await readdir(videoDir).catch(() => [] as string[]); + 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<LivePreclipSummary> { + 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<ClockCheck> { + 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<string | null> { + 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<StreamActionResult> { + 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" ? ' — "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<LivePreclipStatusView> { + 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<PreclipOptions, "project">; + deps?: Pick<LivePreclipDeps, "mine" | "hasFinalTranscript" | "now">; +}): 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<ReturnType<MineLive>> | 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 }; +} diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -163,6 +163,51 @@ test("Rumble path A: yt-dlp --live-from-start into a staging part, then landed; assert.deepEqual((await readdir(slugStore)).filter((n) => n.startsWith(".")), [], "no staging left"); }); +test("preclip: the knob parsed (implies transcribe), the pre-clip asked for once the first part begins, each part's stem recorded", async () => { + const p = parseRecordLiveRequest({ slug: "s", url: "https://rumble.com/v1x-y.html", preclip: { everyMinutes: 5 } }); + assert.ok(!("error" in p)); + if ("error" in p) return; + assert.equal(p.preclip?.everyMinutes, 5); + assert.equal(p.preclip?.maxChunkMinutes, 20); + assert.equal(p.transcribe, true, "preclip implies the landing's transcription"); + const off = parseRecordLiveRequest({ slug: "s", url: "https://rumble.com/v1x-y.html", preclip: true, transcribe: false }); + assert.ok(!("error" in off) && off.transcribe === false && off.preclip?.everyMinutes === 10); + assert.match((parseRecordLiveRequest({ slug: "s", url: "https://rumble.com/v1x-y.html", preclip: { every: 1 } }) as { error: string }).error, /preclip/); + + const asked: { slug: string; id: string; every: number }[] = []; + const log: string[] = []; + await recordLiveRun({ + paths, + request: { slug: SLUG, url: "https://rumble.com/v3ccccc-show.html", preclip: p.preclip }, + plan: { url: "https://rumble.com/v3ccccc-show.html", platform: "rumble", id: "v3ccccc" }, + channelConfig: CONFIG, + cookiePolicy: NO_COOKIES, + onLog: (l) => void log.push(l), + signal: new AbortController().signal, + startPreclip: async (slug, id, options) => { + asked.push({ slug, id, every: options.everyMinutes }); + return { ok: true, jobId: "job-pre" }; + }, + deps: { + refresh: refreshWith(RUMBLE_META), + fetchText: async () => DVR, + spawn: async ({ args }) => { + // The pre-clip is asked for while the recorder runs. + await new Promise((r) => setImmediate(r)); + await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=60;"); + return { exitCode: 0, stderrTail: "", signalled: false }; + }, + land, + freeBytes: async () => 1e15, + handoff, + }, + }); + assert.deepEqual(asked, [{ slug: SLUG, id: "v3ccccc", every: 5 }]); + assert.ok(log.some((l) => /Live pre-clip: job job-pre/.test(l))); + const rec = await liveRecordingSidecar.load(path.join(CORPUS, "channels", SLUG, "data", "v3ccccc")); + assert.match(rec?.parts[0]?.stem ?? "", /^\.v3ccccc\.live-.+\.ytdlp$/); +}); + test("yt-dlp cannot start at the start: --no-live-from-start with ffmpeg at index 0; the longest part lands", async () => { const calls: string[][] = []; const s = await recordLiveRun({ diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -101,6 +101,7 @@ import { import { refreshVideoMetadata, type RefreshRunner } from "./refreshVideoMetadata"; import { findVideoSourceUrl } from "./undownloadedVideos"; import { jitterYtdlpSleeps } from "../lib/jitter"; +import { parsePreclipKnob, type PreclipOptions } from "../lib/livePreclip"; import { jitterMs } from "../lib/jitter"; export const RECORD_LIVE_JOB_KIND = "record-live"; @@ -117,6 +118,7 @@ export const RECORD_LIVE_BODY_KEYS = [ "doNotClean", "note", "dryRun", + "preclip", ] as const; // The user agent path B's ffmpeg and the playlist reads present (the pinned @@ -151,9 +153,16 @@ export type RecordLiveRequest = { doNotClean?: boolean; note?: string; dryRun?: boolean; + // LIVE PRE-CLIP (plans/live-preclip.md): transcribe and mine the recording + // while it records — its own job (controller/livePreclip.ts), started once + // the first part begins. Implies `transcribe` unless that is false. + preclip?: PreclipOptions; }; -export function parseRecordLiveRequest(body: Record<string, unknown>): RecordLiveRequest | { error: string } { +export function parseRecordLiveRequest( + body: Record<string, unknown>, + preclipDefaults?: Omit<PreclipOptions, "project">, +): RecordLiveRequest | { error: string } { const str = (k: string) => (typeof body[k] === "string" ? (body[k] as string).trim() : undefined); const slug = str("slug"); if (!slug) return { error: '"slug" is required' }; @@ -181,6 +190,12 @@ export function parseRecordLiveRequest(body: Record<string, unknown>): RecordLiv } const note = str("note"); if (note) out.note = note; + const preclip = parsePreclipKnob(body.preclip, preclipDefaults); + if (preclip && "error" in preclip) return preclip; + if (preclip) { + out.preclip = preclip; + if (out.transcribe === undefined) out.transcribe = true; + } return out; } @@ -518,6 +533,9 @@ export type RecordLiveJobOpts = { channelConfig: ChannelConfig; cookiePolicy: ResolvedCookiePolicy; requestTranscription?: (slug: string, id: string) => Promise<{ ok: boolean; jobId?: string; error?: string }>; + // The pre-clip job for this stream (request.preclip), asked for once the + // first part begins. + startPreclip?: (slug: string, id: string, options: PreclipOptions) => Promise<{ ok: boolean; jobId?: string; error?: string }>; afterRun?: () => void | Promise<void>; deps?: RecordLiveDeps; }; @@ -695,6 +713,12 @@ export async function recordLiveRun( : `Would record with yt-dlp ${fromStart ? "--live-from-start" : ""}${BROWSER_FALLBACK_PLATFORMS.has(plan.platform) ? ", the page's own playlist by ffmpeg if yt-dlp is refused" : ""}.`, ); say("Then the longest part is landed as the video's source (the store, audio, the archive line) and handed to the transcription lane."); + if (req.preclip) { + say( + `Live pre-clip: every ${req.preclip.everyMinutes} min the new span is transcribed (at most ${req.preclip.maxChunkMinutes} min a tick)` + + `${req.preclip.mine ? " and mined into a umtool project" : ""}, while it records.`, + ); + } summary.status = "landed"; say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); return summary; @@ -811,10 +835,22 @@ export async function recordLiveRun( // Each part by its stem's name (the files on disk are read back by it). const parts: { part: LivePart; stem: string }[] = []; + let preclipAsked = false; const begin = (method: LivePartMethod, url: string, file: string, fs: boolean) => { - const part: LivePart = { method, url, fromStart: fs, startedAt: now().toISOString() }; + const stem = path.basename(file).replace(/\.ts$/, ""); + const part: LivePart = { method, url, fromStart: fs, startedAt: now().toISOString(), stem }; record.parts.push(part); - parts.push({ part, stem: path.basename(file).replace(/\.ts$/, "") }); + parts.push({ part, stem }); + if (req.preclip && !preclipAsked && opts.startPreclip) { + preclipAsked = true; + // After the save that lists this part (the pre-clip reads the record). + setImmediate(() => { + void opts.startPreclip!(req.slug, id, req.preclip!).then( + (r) => say(r.ok ? `Live pre-clip: job ${r.jobId} (every ${req.preclip!.everyMinutes} min)` : `Live pre-clip was not started: ${r.error ?? "no job"}`), + (e: Error) => say(`Live pre-clip was not started: ${e.message}`), + ); + }); + } return part; }; const finish = (part: LivePart, note: string) => { diff --git a/common/controller/transcribeFile.ts b/common/controller/transcribeFile.ts @@ -475,13 +475,21 @@ export type RunTranscribeFileOpts = { onLog: (line: string) => void; signal?: AbortSignal; ctx?: Pick<JobRunContext, "jobId" | "addTask" | "updateTask" | "removeTask" | "recordTaskDone">; + // The pool tier asked for (default: transcribeFileTier of the cut's length). + tier?: SchedulerTier; + // Where the scratch dir is made (default the OS temp dir). Live pre-clip + // passes its work dir on the store's disk: /tmp may be a RAM tmpfs. + scratchParent?: string; + // Called with the cut WAV once it is transcribed, before the scratch goes: + // what live pre-clip's laugh scan reads, so the span is decoded once. + withWav?: (wav: string, seconds: number) => Promise<void>; }; export async function runTranscribeFile( opts: RunTranscribeFileOpts, ): Promise<TranscribeFileResult> { const { request: req, onLog, paths } = opts; - const scratch = await mkdtemp(path.join(os.tmpdir(), "archilyzer-transcribe-")); + const scratch = await mkdtemp(path.join(opts.scratchParent ?? os.tmpdir(), "archilyzer-transcribe-")); try { const wav = path.join(scratch, AUDIO_NAME); onLog(`Cutting ${describeRequest(req)} to 16 kHz mono WAV…`); @@ -508,7 +516,7 @@ export async function runTranscribeFile( // there (the last attempt's, when a transport failure moved it). const used: { worker?: Worker; startedAt?: number } = {}; const audioSec = wavSeconds(wavStat.size); - const tier = transcribeFileTier(audioSec); + const tier = opts.tier ?? transcribeFileTier(audioSec); onLog( `${req.workerId ? `Waiting for worker ${req.workerId}` : "Waiting for a free local worker"}` + (tier === "urgent" @@ -550,6 +558,7 @@ export async function runTranscribeFile( const raw = await readFile(path.join(scratch, "transcript.json"), "utf8"); const transcriptFormat = detectTranscriptFormat(raw) ?? "whisper-json"; const cues = offsetCues(parseTranscriptJson(raw, transcriptFormat), req.start ?? 0); + if (opts.withWav) await opts.withWav(wav, audioSec); return { version: 1, path: req.path, diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -905,6 +905,38 @@ const JOB_KINDS: Record<string, JobKindMeta> = { network: true, needsMedia: true, }, + // LIVE PRE-CLIP (plans/live-preclip.md, controller/livePreclip.ts — `pnpm + // ops live-preclip`, record-live's `preclip`): a recording in progress + // transcribed and mined while it records — a tick every few minutes reads + // only the new span of the growing file (never writing it), transcribes it + // on a worker lease, splices it into live-transcript.json and grows the + // stream's umtool project. One per stream on its own queue + // (`live-preclip:<slug>:<id>`), beside the recorder's: a stop never touches + // the recording. No network: the recorder's files, the pool, umtool here. + // `needsText`: its sidecars are beside the record. Not replayable: the ops + // start resumes from the live transcript. + "live-preclip": { + kind: "live-preclip", + label: "Live pre-clip", + drainable: false, + replayable: false, + queueKeyStrategy: "custom", + network: false, + needsText: true, + }, + // A SHAREABLE CLIP OF A STREAM STILL LIVE (controller/liveClip.ts — `pnpm + // ops live-clip`): the window cut now from the growing recording (no + // network), then umtool's short of it with the live transcript's captions, + // followed to the end. Its own queue (`live-clip`), one at a time. + "live-clip": { + kind: "live-clip", + label: "Live clip", + drainable: false, + replayable: false, + queueKeyStrategy: "custom", + network: false, + needsText: true, + }, // FIND CLIPS (release 36 lane A, controller/findClips.ts — the video page's // Find clips, `pnpm ops find-clips`): the clip finder's chain for one video, // each step skipped when its output exists — persist the source, the corpus diff --git a/common/lib/clipWindow.ts b/common/lib/clipWindow.ts @@ -201,7 +201,9 @@ export type ClipProvenance = { // "saved-video" for a window cut from the video's saved container (release 21 // D2, lib/savedVideoWindow-server.ts); "stored-media-url" for one fetched from // the media URL its metadata.info.json stores (release 32 R5, - // lib/storedMediaUrl.ts), with that URL's host in `sourceHost`. Absent on a + // lib/storedMediaUrl.ts), with that URL's host in `sourceHost`; + // "live-recording" for one cut from a live recording still in progress (live + // pre-clip's share, lib/livePreclip-server.ts cutLiveWindow). Absent on a // window fetched through the page. source?: ClipWindowSource; sourceHost?: string; @@ -241,7 +243,7 @@ export function coerceClipCopy(v: unknown): ClipCopy | undefined { return { from: r.from as ClipCopy["from"], url: r.url }; } -export const CLIP_WINDOW_SOURCES = ["saved-video", "stored-media-url"] as const; +export const CLIP_WINDOW_SOURCES = ["saved-video", "stored-media-url", "live-recording"] as const; export type ClipWindowSource = (typeof CLIP_WINDOW_SOURCES)[number]; const str = (v: unknown): string | undefined => diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts @@ -420,6 +420,9 @@ export type LivePartMethod = "ytdlp" | "browser" | "vod-poll"; export type LivePart = { method: LivePartMethod; + // The part's stem in the store's slug dir (livePartFiles): which files on + // disk are this part's — what live pre-clip follows while it records. + stem?: string; url: string; fromStart: boolean; startedAt: string; diff --git a/common/lib/livePreclip-server.test.ts b/common/lib/livePreclip-server.test.ts @@ -0,0 +1,195 @@ +// The snapshot and the clock of a recording IN PROGRESS, on real files: an +// MPEG-TS (the muxed recorders) and a separate fMP4 video + audio pair +// (YouTube's), each written in increments at arbitrary byte boundaries the way +// a recorder appends, with a 1 kHz burst at a known second of the stream. +// Tiny (160x90, 90 s), and skipped where ffmpeg has no libx264. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import path from "node:path"; +import { tmpdir } from "node:os"; +import { appendFile, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { execa } from "execa"; +import { windowWavArgs } from "../controller/transcribeFile"; +import type { LiveRecordingRecord } from "./liveCapture"; +import { cutLiveWindow, findLiveSource, liveWindowCutArgs, probeWith, readEnvelope } from "./livePreclip-server"; +import { compareEnvelopes, envelopeOf, judgeClock, planTick } from "./livePreclip"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "live-preclip-")); +const FF = process.env.FFMPEG_BIN ?? "ffmpeg"; +const FP = process.env.FFPROBE_BIN ?? "ffprobe"; +const probe = probeWith(FP); +const BURST_AT = 47; +const AUDIO = `aevalsrc='if(between(t,${BURST_AT},${BURST_AT}.5),0.8*sin(2*PI*1000*t),0.05*sin(2*PI*220*t)*(1+sin(2*PI*0.7*t)))':s=16000:d=90`; + +let haveX264 = true; +const ts = path.join(ROOT, "src.ts"); +const fv = path.join(ROOT, "src-video.mp4"); +const fa = path.join(ROOT, "src-audio.m4a"); +try { + // A stream whose clock does not start at 0 (a TS's first PTS is wherever + // the broadcast's was): -output_ts_offset. + await execa(FF, [ + "-v", "error", "-y", + "-f", "lavfi", "-i", "testsrc2=s=160x90:r=10:d=90", "-f", "lavfi", "-i", AUDIO, + "-c:v", "libx264", "-preset", "ultrafast", "-g", "20", "-c:a", "aac", "-b:a", "48k", + "-output_ts_offset", "1000", "-f", "mpegts", ts, + ]); + await execa(FF, ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=160x90:r=10:d=90", "-c:v", "libx264", "-preset", "ultrafast", "-g", "20", "-movflags", "+frag_keyframe+empty_moov+default_base_moof", "-f", "mp4", fv]); + await execa(FF, ["-v", "error", "-y", "-f", "lavfi", "-i", AUDIO, "-c:a", "aac", "-b:a", "48k", "-movflags", "+frag_keyframe+empty_moov+default_base_moof", "-frag_duration", "2000000", "-f", "mp4", fa]); +} catch { + haveX264 = false; +} + +/** A recorder, appending `src` to `dst` in pieces cut at arbitrary bytes. */ +async function grower(src: string, dst: string) { + const bytes = await readFile(src); + let at = 0; + await writeFile(dst, Buffer.alloc(0)); + return async (share: number) => { + const to = Math.min(bytes.length, Math.floor(bytes.length * share) + 37); + if (to > at) await appendFile(dst, bytes.subarray(at, to)); + at = to; + }; +} + +const peakAt = (env: number[], hop = 0.1) => env.indexOf(Math.max(...env)) * hop; + +function recording(stem: string): LiveRecordingRecord { + return { + status: "recording", + url: "https://example.com/live", + platform: "youtube", + fromStart: true, + startedAt: "2026-10-27T12:00:00Z", + parts: [{ method: "ytdlp", url: "https://example.com/live", fromStart: true, startedAt: "2026-10-27T12:00:00Z", stem }], + }; +} + +test("a growing MPEG-TS: its length grows, a span is read by time on the landed clock", async (t) => { + if (!haveX264) return t.skip("no ffmpeg with libx264 here"); + const store = path.join(ROOT, "ts-store"); + await mkdir(store, { recursive: true }); + const stem = ".vid1.live-2026-10-27T12-00-00-000Z.ytdlp"; + const part = path.join(store, `${stem}.ts`); + const grow = await grower(ts, part); + await grow(0.4); + const src = await findLiveSource({ slugStore: store, id: "vid1", record: recording(stem), probe }); + assert.ok(!("wait" in src), JSON.stringify(src)); + if ("wait" in src) return; + assert.equal(src.kind, "muxed"); + assert.equal(src.audioPath, part); + const early = (await probe(part))!.seconds!; + assert.ok(early > 25 && early < 45, `40% of 90 s reads as ${early}`); + + await grow(1); + const full = (await probe(part))!.seconds!; + assert.ok(full > 88, `the whole stream reads as ${full}`); + // The tick after the first: from 15 s before what was transcribed. + const plan = planTick({ transcribedTo: 40, recordedSeconds: full, opts: { maxChunkMinutes: 20, overlapSeconds: 15 } }); + assert.equal(plan.action, "transcribe"); + if (plan.action !== "transcribe") return; + assert.equal(plan.from, 25); + const wav = path.join(ROOT, "ts-span.wav"); + await execa(FF, windowWavArgs(part, wav, { start: plan.from, end: plan.to })); + const env = envelopeOf(await decodeWav(wav), 16000); + // The burst at 47 s of the stream is 22 s into a span from 25 s — so second + // S of the growing file is second S of the stream, whatever its first PTS. + assert.ok(Math.abs(peakAt(env) + plan.from - BURST_AT) < 0.25, `burst at ${peakAt(env) + plan.from}`); + + // The landing remuxes `-c copy` to mp4 (no -copyts): the burst is at 47 s there too. + const landed = path.join(ROOT, "landed.mp4"); + await execa(FF, ["-v", "error", "-y", "-i", part, "-map", "0:v?", "-map", "0:a?", "-c", "copy", "-movflags", "+faststart", "-f", "mp4", landed]); + const landedEnv = (await readEnvelope(landed, 40, 15, FF))!; + assert.ok(Math.abs(peakAt(landedEnv) + 40 - BURST_AT) < 0.25, `landed burst at ${peakAt(landedEnv) + 40}`); + // And the clock check says so: the same span, fingerprinted on the growing + // file and on the landed one. + const ref = (await readEnvelope(part, 40, 15, FF))!; + const probed = (await readEnvelope(landed, 38, 19, FF))!; + assert.equal(judgeClock(compareEnvelopes(ref, probed, 20), 0.1, new Date()).verdict, "same"); + + // A window cut now from the growing file: picture and sound, the burst 2 s in. + const videoDir = path.join(ROOT, "ts-video-dir"); + const win = await cutLiveWindow({ ffmpegBin: FF, videoDir, source: src, from: 45, to: 52, requestedBy: "test" }); + assert.equal(win.file, "45.00-52.00.mp4"); + const p = await probe(win.path); + assert.ok(p?.hasVideo && p.hasAudio); + assert.ok(Math.abs(p!.seconds! - 7) < 0.3, `window of ${p!.seconds} s`); + const wenv = (await readEnvelope(win.path, 0, 7, FF))!; + assert.ok(Math.abs(peakAt(wenv) - 2) < 0.25, `window burst at ${peakAt(wenv)}`); + // The picture from the window's first second (a TS seeks by timestamp, not + // to a keyframe: the cut's run-up is what keeps the first GOP). + const starts = await execa(FP, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=start_time", "-of", "csv=p=0", win.path]); + assert.ok(Number(String(starts.stdout).trim()) < 0.2, `picture starts at ${starts.stdout}`); + const side =JSON.parse(await readFile(path.join(videoDir, "clips", "45.00-52.00.json"), "utf8")); + assert.equal(side.source, "live-recording"); +}); + +test("a growing separate pair: the audio stream is read, the window takes both", async (t) => { + if (!haveX264) return t.skip("no ffmpeg with libx264 here"); + const store = path.join(ROOT, "pair-store"); + await mkdir(store, { recursive: true }); + const stem = ".vid2.live-2026-10-27T12-00-00-000Z.ytdlp"; + const video = path.join(store, `${stem}.f270.mp4`); + const audio = path.join(store, `${stem}.f234.mp4`); + const gv = await grower(fv, video); + const ga = await grower(fa, audio); + for (const share of [0.2, 0.55, 1]) { + await gv(share); + await ga(share); + const src = await findLiveSource({ slugStore: store, id: "vid2", record: recording(stem), probe }); + assert.ok(!("wait" in src), JSON.stringify(src)); + if ("wait" in src) return; + assert.equal(src.kind, "separate"); + assert.equal(src.audioPath, audio); + assert.equal(src.videoPath, video); + } + const seconds = (await probe(audio))!.seconds!; + assert.ok(seconds > 85, `audio reads ${seconds}`); + const wav = path.join(ROOT, "pair-span.wav"); + await execa(FF, windowWavArgs(audio, wav, { start: 40, end: 60 })); + const env = envelopeOf(await decodeWav(wav), 16000); + assert.ok(Math.abs(peakAt(env) + 40 - BURST_AT) < 0.25, `burst at ${peakAt(env) + 40}`); + + const args = liveWindowCutArgs(video, audio, 45, 52, "out.mp4"); + assert.deepEqual(args.filter((a) => a === "-i").length, 2); + assert.ok(args.includes("1:a:0")); + const videoDir = path.join(ROOT, "pair-video-dir"); + const src = await findLiveSource({ slugStore: store, id: "vid2", record: recording(stem), probe }); + if ("wait" in src) return; + const win = await cutLiveWindow({ ffmpegBin: FF, videoDir, source: src, from: 45, to: 52, requestedBy: "test" }); + const p = await probe(win.path); + assert.ok(p?.hasVideo && p.hasAudio, JSON.stringify(p)); + const wenv = (await readEnvelope(win.path, 0, 7, FF))!; + assert.ok(Math.abs(peakAt(wenv) - 2) < 0.25, `window burst at ${peakAt(wenv)}`); +}); + +test("findLiveSource: an ended part is not followed; nothing written yet is a wait", async () => { + const store = path.join(ROOT, "wait-store"); + await mkdir(store, { recursive: true }); + const stem = ".vid3.live-2026-10-27T12-00-00-000Z.ytdlp"; + const rec = recording(stem); + assert.deepEqual(await findLiveSource({ slugStore: store, id: "vid3", record: rec, probe }), { wait: "the recorder has written nothing yet" }); + await writeFile(path.join(store, `${stem}.ts`), "not media"); + const unreadable = await findLiveSource({ slugStore: store, id: "vid3", record: rec, probe }); + assert.ok("wait" in unreadable && /no audio ffprobe can read/.test(unreadable.wait)); + const ended = { ...rec, parts: [{ ...rec.parts[0]!, endedAt: "2026-10-27T13:00:00Z" }] }; + assert.deepEqual(await findLiveSource({ slugStore: store, id: "vid3", record: ended, probe }), { wait: "no part is being recorded" }); +}); + +/** A 16 kHz mono s16le WAV's samples. */ +async function decodeWav(file: string): Promise<Float32Array> { + const buf = await readFile(file); + // The data chunk: after the 44-byte header ffmpeg writes (plus a LIST chunk, sometimes). + const data = buf.indexOf(Buffer.from("data")); + const start = data + 8; + const n = Math.floor((buf.length - start) / 2); + const out = new Float32Array(n); + for (let i = 0; i < n; i += 1) out[i] = buf.readInt16LE(start + i * 2) / 32768; + return out; +} + +test.after(async () => { + await rm(ROOT, { recursive: true, force: true }); + void stat; +}); diff --git a/common/lib/livePreclip-server.ts b/common/lib/livePreclip-server.ts @@ -0,0 +1,209 @@ +// LIVE PRE-CLIP — the files (plans/live-preclip.md): its two sidecars, which +// file of a recording in progress a tick reads, how long it is, its audio's +// envelope, and a window cut out of it. +// +// EVERY READ HERE IS OF BYTES ALREADY WRITTEN. A recorder appends (MPEG-TS +// packets, fMP4 fragments, Kick's segments); nothing here writes, renames or +// truncates a part, so the recorder is never disturbed. ffmpeg reading a growing +// file stops at what is there (a partial last packet or fragment is dropped, +// measured 2026-10-27), and every span asked for ends PRECLIP_EDGE_SECONDS short +// of the live edge. +// +// SERVER-ONLY (node:fs, ffmpeg). + +import path from "node:path"; +import { mkdir, readdir, rename, rm, stat } from "node:fs/promises"; +import { execa } from "execa"; +import { sidecar, sidecarField } from "./sidecar-server"; +import { + LIVE_PRECLIP_FILENAME, + LIVE_TRANSCRIPT_FILENAME, + coerceLivePreclipState, + coerceLiveTranscript, + envelopeOf, + FINGERPRINT_HOP_SECONDS, + type LiveBasis, +} from "./livePreclip"; +import { livePartFiles, type LivePart, type LiveRecordingRecord } from "./liveCapture"; +import { EVIDENCE_AUDIO_BITRATE, EVIDENCE_CRF, EVIDENCE_MAX_HEIGHT, EVIDENCE_MAX_WIDTH, probeMedia } from "./evidenceClip-server"; +import { clipWindowFile, type ClipProvenance } from "./clipWindow"; +import { clipWindowPath, writeClipProvenance, type ClipWindow } from "./clipWindow-server"; +import { tmpPathFor } from "./jsonFile-server"; +import { decodeSpan } from "./montage/voiceMatch.mjs"; + +export const liveTranscriptSidecar = sidecar(LIVE_TRANSCRIPT_FILENAME, sidecarField(coerceLiveTranscript), { indent: 0 }); +export const livePreclipSidecar = sidecar(LIVE_PRECLIP_FILENAME, sidecarField(coerceLivePreclipState)); + +// The pre-clip's scratch (each tick's WAV, the scan's chunks): beside the +// recording's parts, on the store's disk — never /tmp, a RAM tmpfs here. +export function preclipWorkDir(slugStore: string, id: string): string { + return path.join(slugStore, `.${id}.preclip`); +} + +export type ProbeSeconds = (file: string) => Promise<{ seconds: number | null; hasVideo: boolean; hasAudio: boolean } | null>; + +export function probeWith(ffprobeBin: string): ProbeSeconds { + return async (file) => { + const p = await probeMedia(file, ffprobeBin); + return p ? { seconds: p.durationSec, hasVideo: p.hasVideo, hasAudio: p.hasAudio } : null; + }; +} + +export type LiveSource = LiveBasis & { + // Absolute paths: the file a tick reads (audio), and the picture's file when + // it is another one (a separate pair). + audioPath: string; + videoPath: string | null; + part: LivePart | null; +}; + +const sizeOf = (f: string) => stat(f).then((s) => s.size, () => 0); + +/** + * THE FILE A TICK READS: of the parts the recording lists without an end (the + * ones being written), a from-start one before one from now (Kick's VOD before + * its channel), then the one with the most bytes; in it, the muxed file, or of + * a separate pair the stream ffprobe hears audio in. A reason instead when + * there is nothing readable yet. + */ +export async function findLiveSource(o: { + slugStore: string; + id: string; + record: LiveRecordingRecord; + probe: ProbeSeconds; +}): Promise<LiveSource | { wait: string }> { + const names = await readdir(o.slugStore).catch(() => [] as string[]); + const groups = livePartFiles(o.id, names); + const open = o.record.parts.filter((p) => !p.endedAt); + const ranked: { part: LivePart | null; stem: string; bytes: number }[] = []; + for (const g of groups) { + const part = o.record.parts.find((p) => p.stem === g.stem) ?? null; + // A part the record says has ended is not the one being written. + if (part?.endedAt) continue; + // With the record listing open parts, an unlisted group is an earlier run's. + if (open.length && !part) continue; + let bytes = 0; + for (const f of [...g.finished, ...g.streams]) bytes += await sizeOf(path.join(o.slugStore, f)); + if (bytes > 0) ranked.push({ part, stem: g.stem, bytes }); + } + if (!ranked.length) return { wait: open.length ? "the recorder has written nothing yet" : "no part is being recorded" }; + ranked.sort((a, b) => Number(b.part?.fromStart ?? false) - Number(a.part?.fromStart ?? false) || b.bytes - a.bytes); + const best = ranked[0]!; + const g = groups.find((x) => x.stem === best.stem)!; + const at = (n: string) => path.join(o.slugStore, n); + // Muxed (or yt-dlp's finished merge): one file with the sound. + for (const f of g.finished) { + const p = await o.probe(at(f)); + if (p?.hasAudio) return { stem: g.stem, audioFile: f, kind: "muxed", audioPath: at(f), videoPath: p.hasVideo ? at(f) : null, part: best.part }; + } + let audio: string | null = null; + let video: string | null = null; + for (const f of g.streams) { + const p = await o.probe(at(f)); + if (!p) continue; + if (p.hasAudio && p.hasVideo) return { stem: g.stem, audioFile: f, kind: "muxed", audioPath: at(f), videoPath: at(f), part: best.part }; + if (p.hasAudio && !audio) audio = f; + else if (p.hasVideo && !video) video = f; + } + if (audio) return { stem: g.stem, audioFile: audio, kind: "separate", audioPath: at(audio), videoPath: video ? at(video) : null, part: best.part }; + return { wait: `${g.stem} holds no audio ffprobe can read yet` }; +} + +/** The RMS envelope (FINGERPRINT_HOP_SECONDS frames) of [from, from + dur) of a file's audio; null when ffmpeg reads nothing. */ +export async function readEnvelope(file: string, from: number, dur: number, ffmpegBin: string): Promise<number[] | null> { + try { + const rate = 8000; + const samples = await decodeSpan(file, Math.max(0, from), dur, { ffmpeg: ffmpegBin, rate }); + if (samples.length < rate) return null; + return envelopeOf(samples, rate, FINGERPRINT_HOP_SECONDS); + } catch { + return null; + } +} + +// Seconds a cut seeks BEFORE the window, then decodes and drops: an MPEG-TS +// seeks by timestamp, not to a keyframe (measured 2026-10-27: an input `-ss` +// into a TS with a 2 s GOP lost the first 1.1 s of picture), so the picture +// needs a GOP of run-up. The sound is exact either way. +export const LIVE_CUT_PREROLL_SECONDS = 10; + +/** + * ffmpeg's cut of [a, b] seconds from a recording into a window, in the + * clip-window cache's format (evidenceClip-server's: H.264 inside 1280×720 + + * AAC in an mp4, the first frame the asked-for second): seeked on the input + * LIVE_CUT_PREROLL_SECONDS early and trimmed on the output, with the sound from + * a second input for a separate pair. + */ +export function liveWindowCutArgs(video: string | null, audio: string, a: number, b: number, out: string): string[] { + const seek = Math.max(0, a - LIVE_CUT_PREROLL_SECONDS); + const input = (f: string) => ["-ss", seek.toFixed(3), "-i", f]; + const trim = ["-ss", (a - seek).toFixed(3), "-t", (b - a).toFixed(3)]; + const sound = ["-c:a", "aac", "-b:a", EVIDENCE_AUDIO_BITRATE, "-ac", "2"]; + const tail = ["-map_metadata", "-1", "-sn", "-dn", "-movflags", "+faststart", "-f", "mp4", out]; + const head = ["-nostdin", "-v", "error", "-y"]; + if (!video) return [...head, ...input(audio), ...trim, "-map", "0:a:0", "-vn", ...sound, ...tail]; + const pair = video !== audio; + return [ + ...head, + ...input(video), + ...(pair ? input(audio) : []), + ...trim, + "-map", "0:v:0", + "-map", pair ? "1:a:0" : "0:a:0?", + "-vf", `scale='min(${EVIDENCE_MAX_WIDTH},iw)':'min(${EVIDENCE_MAX_HEIGHT},ih)':force_original_aspect_ratio=decrease:force_divisible_by=2,format=yuv420p`, + "-c:v", "libx264", "-preset", "medium", "-profile:v", "high", "-crf", String(EVIDENCE_CRF), + ...sound, + ...tail, + ]; +} + +/** + * A window of the recording in progress, cut NOW (the snapshot on demand): + * into data/<id>/clips/<from>-<to>.mp4 with its provenance (`source: + * "live-recording"`), through a temp name no window parser accepts, so a + * reader never sees half of one. + */ +export async function cutLiveWindow(opts: { + ffmpegBin: string; + videoDir: string; + source: Pick<LiveSource, "audioPath" | "videoPath" | "stem">; + from: number; + to: number; + requestedBy: string; + reason?: string; + clipId?: string; + manifest?: string; + signal?: AbortSignal; +}): Promise<ClipWindow> { + const dest = clipWindowPath(opts.videoDir, opts.from, opts.to); + await mkdir(path.dirname(dest), { recursive: true }); + const tmp = tmpPathFor(dest); + try { + const r = await execa(opts.ffmpegBin, liveWindowCutArgs(opts.source.videoPath, opts.source.audioPath, opts.from, opts.to, tmp), { + reject: false, + timeout: 10 * 60_000, + ...(opts.signal ? { cancelSignal: opts.signal } : {}), + }); + if (r.exitCode !== 0) { + const err = String(r.stderr ?? "").trim().split("\n").slice(-3).join(" | "); + throw new Error(`ffmpeg could not cut ${opts.from}–${opts.to} s from the recording (${opts.source.stem})${err ? `: ${err}` : ""}`); + } + const bytes = (await stat(tmp)).size; + await rename(tmp, dest); + const now = new Date().toISOString(); + const provenance: ClipProvenance = { + requestedBy: opts.requestedBy, + ...(opts.manifest ? { manifest: opts.manifest } : {}), + ...(opts.clipId ? { clipId: opts.clipId } : {}), + ...(opts.reason ? { reason: opts.reason } : {}), + requestedAt: now, + bytes, + fetchedAt: now, + source: "live-recording", + }; + await writeClipProvenance(opts.videoDir, opts.from, opts.to, provenance); + return { file: clipWindowFile(opts.from, opts.to), path: dest, from: opts.from, to: opts.to, bytes, provenance }; + } finally { + await rm(tmp, { force: true }).catch(() => {}); + } +} diff --git a/common/lib/livePreclip.test.ts b/common/lib/livePreclip.test.ts @@ -0,0 +1,205 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + LIVE_CLIP_MAX_SECONDS, + PRECLIP_DEFAULTS, + PRECLIP_EDGE_SECONDS, + appendSpan, + coerceLivePreclipState, + coerceLiveTranscript, + compareEnvelopes, + emptyLiveTranscript, + envelopeOf, + fingerprintSpan, + judgeClock, + liveClipTooLong, + checkLiveWindow, + liveProjectSlug, + newPreclipState, + nextTickDelayMs, + parsePreclipKnob, + planTick, + spliceAt, + spliceCut, + spliceScan, + withLogLine, + withSkip, +} from "./livePreclip"; + +const now = new Date("2026-10-27T12:00:00Z"); + +test("parsePreclipKnob: off, defaults, keys over the defaults, refusals", () => { + assert.equal(parsePreclipKnob(undefined), null); + assert.equal(parsePreclipKnob(false), null); + assert.deepEqual(parsePreclipKnob(true), { ...PRECLIP_DEFAULTS }); + assert.deepEqual(parsePreclipKnob(true, { ...PRECLIP_DEFAULTS, everyMinutes: 5 }), { ...PRECLIP_DEFAULTS, everyMinutes: 5 }); + assert.deepEqual(parsePreclipKnob({ everyMinutes: 3, scan: false, project: "demo-live" }), { + ...PRECLIP_DEFAULTS, + everyMinutes: 3, + scan: false, + project: "demo-live", + }); + assert.match((parsePreclipKnob({ everyMinutes: 0 }) as { error: string }).error, /everyMinutes/); + assert.match((parsePreclipKnob({ every: 3 }) as { error: string }).error, /does not take "every"/); + assert.match((parsePreclipKnob({ project: "Not A Slug" }) as { error: string }).error, /project/); + assert.match((parsePreclipKnob("yes") as { error: string }).error, /preclip/); + assert.match((parsePreclipKnob({ maxChunkMinutes: 2, overlapSeconds: 60 }) as { error: string }).error, /overlap/); +}); + +test("liveProjectSlug: the id, lowercased, -live", () => { + assert.equal(liveProjectSlug("5-XlMxKT494"), "5-xlmxkt494-live"); + assert.equal(liveProjectSlug("v7h8pxg"), "v7h8pxg-live"); + assert.ok(liveProjectSlug("x".repeat(200)).length <= 80); +}); + +test("planTick: no new data, the first tick from 0, the overlap, the cap, behind", () => { + const opts = { maxChunkMinutes: 20, overlapSeconds: 15 }; + assert.deepEqual(planTick({ transcribedTo: 0, recordedSeconds: null, opts }).action, "wait"); + const idle = planTick({ transcribedTo: 600, recordedSeconds: 620, opts }); + assert.equal(idle.action, "wait"); + assert.match((idle as { reason: string }).reason, /no new data \(18 s new/); + assert.deepEqual(planTick({ transcribedTo: 0, recordedSeconds: 600, opts }), { action: "transcribe", from: 0, to: 598, behind: 0 }); + assert.deepEqual(planTick({ transcribedTo: 598, recordedSeconds: 1200, opts }), { action: "transcribe", from: 583, to: 1198, behind: 0 }); + // Two hours behind (the worker was busy, or pre-clip started late): one chunk, the rest behind. + const behind = planTick({ transcribedTo: 0, recordedSeconds: 7200, opts }); + assert.deepEqual(behind, { action: "transcribe", from: 0, to: 1200, behind: 7200 - PRECLIP_EDGE_SECONDS - 1200 }); + assert.equal(nextTickDelayMs(5998, { everyMinutes: 10 }), 0); + assert.equal(nextTickDelayMs(0, { everyMinutes: 10 }), 600_000); +}); + +test("planTick coalesces: however many periods passed, one tick covers what is new (up to the cap)", () => { + // The worker was busy for 25 minutes; five 5-minute ticks came due. One + // tick, from the overlap to the edge — never five. + const p = planTick({ transcribedTo: 300, recordedSeconds: 300 + 25 * 60, opts: { maxChunkMinutes: 30, overlapSeconds: 15 } }); + assert.deepEqual(p, { action: "transcribe", from: 285, to: 300 + 25 * 60 - PRECLIP_EDGE_SECONDS, behind: 0 }); +}); + +test("spliceAt / spliceCut: the old before the overlap's middle, the new from it, no duplicate", () => { + assert.equal(spliceCut(600, 585), 592.5); + assert.equal(spliceCut(600, 600), 600); + const old = [ + { start: 580, end: 588, text: "a" }, + { start: 588, end: 596, text: "b (cut short by the boundary)" }, + ]; + const incoming = [ + { start: 586, end: 590, text: "a-tail" }, + { start: 588.1, end: 597, text: "b whole" }, + { start: 597, end: 603, text: "c" }, + ]; + const got = spliceAt(old, incoming, spliceCut(596, 585)); + assert.deepEqual(got.map((c) => c.text), ["a", "b (cut short by the boundary)", "c"]); + const got2 = spliceAt(old, incoming, 588.05); + assert.deepEqual(got2.map((c) => c.text), ["a", "b (cut short by the boundary)", "b whole", "c"]); +}); + +test("appendSpan: transcribedTo, chunks, words spliced the same way", () => { + let doc = emptyLiveTranscript(now); + doc = appendSpan( + doc, + { from: 0, to: 598, cues: [{ start: 1, end: 3, text: "hi" }, { start: 590, end: 597, text: "cut" }], words: [{ w: "hi", start: 1, end: 1.4 }, { w: "cut", start: 590, end: 590.5 }], worker: "gpu", ms: 4000, waitedMs: 10 }, + now, + ); + doc = appendSpan( + doc, + { from: 583, to: 1198, cues: [{ start: 589.9, end: 597.5, text: "cut whole" }, { start: 700, end: 702, text: "later" }], words: [{ w: "cut", start: 589.9, end: 590.4 }, { w: "later", start: 700, end: 700.4 }], worker: "gpu", ms: 4000, waitedMs: 0 }, + now, + ); + assert.equal(doc.transcribedTo, 1198); + assert.deepEqual(doc.cues.map((c) => c.text), ["hi", "cut", "later"]); + assert.equal(doc.words.length, 3); + assert.equal(doc.chunks.length, 2); + assert.equal(coerceLiveTranscript(JSON.parse(JSON.stringify(doc)))?.cues.length, 3); + assert.equal(coerceLiveTranscript({ version: 2 }), null); +}); + +test("spliceScan: by window index, gaps silent, laugh kept when a span had no tagger", () => { + let s = spliceScan(null, { t0: 0, hop: 0.5, window: 1, energy: [-20, -21, -22, -23], laugh: [0.1, 0.2, 0.3, 0.4], model: "ced" }); + assert.deepEqual(s.energy, [-20, -21, -22, -23]); + // Overlap from window 2 (t0 1.0): rewritten, extended. + s = spliceScan(s, { t0: 1, hop: 0.5, window: 1, energy: [-30, -31, -32], laugh: [0.9, 0.8, 0.7], model: "ced" }); + assert.deepEqual(s.energy, [-20, -21, -30, -31, -32]); + assert.deepEqual(s.laugh, [0.1, 0.2, 0.9, 0.8, 0.7]); + // A gap (t0 4.0 = window 8), no tagger on this span. + s = spliceScan(s, { t0: 4, hop: 0.5, window: 1, energy: [-10], laugh: null, model: null }); + assert.deepEqual(s.energy, [-20, -21, -30, -31, -32, -120, -120, -120, -10]); + assert.deepEqual(s.laugh, [0.1, 0.2, 0.9, 0.8, 0.7, 0, 0, 0, 0]); + assert.equal(s.model, "ced"); + assert.throws(() => spliceScan(s, { t0: 5, hop: 0.25, window: 1, energy: [1], laugh: null, model: null }), /cannot join/); +}); + +function speechLike(seconds: number, rate: number, seed: number, offsetSamples = 0): Float32Array { + // Bursts of noise at pseudo-random lengths: an envelope with a shape. + const out = new Float32Array(Math.round(seconds * rate)); + let x = seed; + const rnd = () => ((x = (x * 1103515245 + 12345) % 2 ** 31) / 2 ** 31); + let on = true; + let left = 0; + // Warm the generator so offsetSamples shifts the same signal. + const total = out.length + offsetSamples; + const all = new Float32Array(total); + for (let i = 0; i < total; i += 1) { + if (left <= 0) { + on = !on; + left = Math.round((0.15 + rnd() * 0.6) * rate); + } + left -= 1; + all[i] = on ? (rnd() - 0.5) * 0.6 : (rnd() - 0.5) * 0.01; + } + out.set(all.subarray(offsetSamples, offsetSamples + out.length)); + return out; +} + +test("envelopeOf + compareEnvelopes + judgeClock: same, shifted, mismatch, flat", () => { + const rate = 8000; + const pad = 20; // 2 s at 0.1 s + const base = speechLike(34, rate, 7); + // ref = 30 s from 2 s in; probe = 34 s (2 s either side). + const ref = envelopeOf(base.subarray(2 * rate, 32 * rate), rate); + const probeSame = envelopeOf(base, rate); + const same = judgeClock(compareEnvelopes(ref, probeSame, pad), 0.1, now); + assert.equal(same.verdict, "same"); + // The same audio, 1.2 s later in the probed file. + const later = new Float32Array(base.length); + later.set(base.subarray(0, base.length - Math.round(1.2 * rate)), Math.round(1.2 * rate)); + const shifted = judgeClock(compareEnvelopes(ref, envelopeOf(later, rate), pad), 0.1, now); + assert.equal(shifted.verdict, "shifted"); + assert.equal(shifted.lagSeconds, 1.2); + const other = judgeClock(compareEnvelopes(ref, envelopeOf(speechLike(34, rate, 99), rate), pad), 0.1, now); + assert.equal(other.verdict, "mismatch"); + const silent = new Float32Array(34 * rate); + const flat = judgeClock(compareEnvelopes(ref, envelopeOf(silent, rate), pad), 0.1, now); + assert.equal(flat.verdict, "unverified"); +}); + +test("fingerprintSpan: 60 s in, else the start, else none", () => { + assert.deepEqual(fingerprintSpan(4000), { from: 60, dur: 30 }); + assert.deepEqual(fingerprintSpan(50), { from: 0, dur: 30 }); + assert.equal(fingerprintSpan(20), null); +}); + +test("the state: log lines kept to the last twelve, skips counted, coerced back", () => { + let s = newPreclipState({ ...PRECLIP_DEFAULTS }, now, "job1"); + for (let i = 0; i < 20; i += 1) s = withLogLine(s, `tick ${i}`, now); + s = withSkip(withSkip(s, "memory"), "memory"); + assert.equal(s.log.length, 12); + assert.match(s.log.at(-1)!, /tick 19$/); + assert.deepEqual(s.skipped, { memory: 2 }); + const back = coerceLivePreclipState(JSON.parse(JSON.stringify(s))); + assert.equal(back?.jobId, "job1"); + assert.equal(coerceLivePreclipState({ version: 1, status: "nope" }), null); +}); + +test("liveClipTooLong / checkLiveWindow: X's 2:20, inside what is recorded", () => { + assert.equal(liveClipTooLong(100, 160), null); + assert.equal(liveClipTooLong(0, LIVE_CLIP_MAX_SECONDS), null); + assert.match(liveClipTooLong(0, LIVE_CLIP_MAX_SECONDS + 1)!, /2:20/); + assert.match(liveClipTooLong(10, 5)!, /start before end/); + assert.deepEqual(checkLiveWindow(95.5, 164.5, 3600), { from: 95.5, to: 164.5 }); + assert.deepEqual(checkLiveWindow(3500, 3598, 3600), { from: 3500, to: 3598 }); + assert.match( + (checkLiveWindow(3590, 3610, 3600) as { error: string }).error, + /holds 1:00:00 so far; the window ends at 1:00:10 — ask again in 12 s/, + ); + assert.match((checkLiveWindow(0, 1000, 3600) as { error: string }).error, /at most 3:20/); + assert.deepEqual(checkLiveWindow(0, 30, null), { from: 0, to: 30 }); +}); diff --git a/common/lib/livePreclip.ts b/common/lib/livePreclip.ts @@ -0,0 +1,608 @@ +// 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 <from> -i <the +// growing file>`), 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.<x>.<y>` (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 `<id>-live`). + project?: string; +}; + +export const PRECLIP_DEFAULTS: Readonly<Omit<PreclipOptions, "project">> = 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<PreclipOptions, "project"> = 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<string, unknown>; + 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<string, unknown> => !!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<T extends { start: number }>(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<PreclipOptions, "maxChunkMinutes" | "overlapSeconds">; +}): 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<PreclipOptions, "everyMinutes">): 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<string, number>; + // 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<string> = 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<string, number>) : {}, + 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) }; +}