// 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//clips/-.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, LIVE_SHARE_MAX_BYTES, 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; 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 { 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 = { ok: true; value: T } | { ok: false; error: string }; export function parseLiveClipBody(body: Record): Check { 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; }; async function json(res: Response): Promise> { try { const j = (await res.json()) as unknown; return j && typeof j === "object" && !Array.isArray(j) ? (j as Record) : {}; } 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 { 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((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 | 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`; // X takes 512 MiB at most. A 2:20 short is far under it; one over is said, // not posted. if (bytes !== null && bytes > LIVE_SHARE_MAX_BYTES) { throw new Error(`the short of ${clip} is ${(bytes / 1024 / 1024).toFixed(0)} MiB, over X's 512 MiB — ${url}`); } return { project: req.project, clip, short: `shorts/${clip}.mp4`, url, bytes, window }; } export async function runLiveClipJob(o: { paths: Paths; request: LiveClipRequest; deps?: LiveClipDeps }): Promise { 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`); }, }); }