// 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"; import "./childKillGuard"; 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 { 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 { 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//clips/-.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; from: number; to: number; requestedBy: string; reason?: string; clipId?: string; manifest?: string; signal?: AbortSignal; }): Promise { 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(() => {}); } }