// recordingEnd.mjs — A CLIP WINDOW THAT REACHES THE END OF A SAVED RECORDING. // // A clip whose cut ends in the last seconds of a recording asks for a window // that ends past it: the cut plus its pad (umtool pads 3 s each side). A saved // container holding that recording WHOLE has every second the window can get -- // the pad past its end does not exist anywhere, on the platform either. So such // a window is cut from the saved container, CLAMPED to its end, instead of // going to the platform's queue for a network fetch of footage already on disk // (and of a video that may be private or gone by now). // // THE RULE, for a span [from, to] on the container's clock (after the one-clock // map, recordingClock.mjs) and a container of D seconds: // - to <= D (to WIN_EPS) held, as always; // - from >= D - WIN_EPS (starts at or after the end) NOT held -- nothing of it // is in the file; // - else, the recording KNOWN WHOLE held, clamped: cut [from, ⌊D⌋₂] // (two decimals, rounded DOWN so // a window's name never claims a // second the file lacks); // - else NOT held, as before. // // KNOWN WHOLE: a known length L of the recording that the container reaches, // L <= E + RECORDING_END_TOLERANCE_SECONDS, ON ONE CLOCK: E is the container's // end on the cue clock (its length less the recording's time map's offset // there, recordingClock.mjs; its length when there is no map), L the // platform's. L is the record's own `duration` (metadata.info.json; ignored // while the record says the stream is live, upcoming or `post_live` -- a VOD // still being processed reports a length that is not its last), else a LANDED // live recording's ended stream's own duration -- `coverage.basis` "duration" // (never the recorder's clock, which measures the recorder: a recorder that // died mid-stream measures itself whole), `coverage.covers`, from the start, no // live-edge fallback, no missing stream, no failure on the record. Anything // else is NOT whole: a partial recording (a live capture joined late or cut // short, a download cut short) really may not hold the window, and a network // fetch is then still right. // // A CLAMP IS RE-CHECKED ON EVERY LOOKUP (`clampHolds`): the window's sidecar // records the saved-video pointer it was cut from (file, bytes) and the known // length it was judged by; when the pointer names another file or size, or the // known length has moved, the window no longer ends the recording -- the // editor's fetch-windows retires it, as it retires a window cut on another // clock, and cuts the span again. JSON reads only (memoised by size and mtime), // never a probe. // // THE CUT ENDS WHERE BOTH STREAMS HAVE DATA (`containerStreamEnds`): at a // container's end its picture and sound often stop apart (a merged // bestvideo+bestaudio download, a live capture's last segments), and a window // cut to the format's end would carry that gap -- which the sync check sets // aside. So a clamp cuts to the shorter stream's end, measured once per // container (its last packets, read from 30 s before its end) and kept for the // process. // // THE TOLERANCE, 2 s: yt-dlp's `duration` is whole seconds on most platforms // (YouTube's lengthSeconds, Rumble's), so a container that holds the whole // recording can probe up to a second short of it; the other second is the // muxer's own rounding of the last frame and packet. A stream longer than the // container by more than that is a container that does not hold it. // // A window cut this way says so in its sidecar (`clamp`: the end asked, the end // cut, the container's end and why), and a window carrying it ENDS THE // RECORDING: it holds any later span that starts inside it (`windowHoldsSpan`), // so the next ask for the same padded span is answered from it, not cut again // and not fetched. // // Plain ESM with no app imports: umtool's report-to-video scripts run under // bare node and ask the same question of the same disk (evidenceClip.mjs). import { execFile } from "node:child_process"; import { readFile, stat } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; const execFileP = promisify(execFile); /** How far a container's length may fall short of the recording's known length and still be the whole of it. */ export const RECORDING_END_TOLERANCE_SECONDS = 2; // lib/clipWindow.ts's and evidenceClip.mjs's WIN_EPS: the 2 dp naming tolerance. const EPS = 0.02; /** Two decimals, rounded down. @param {number} x */ export const floor2 = (x) => Math.floor(x * 100 + 1e-6) / 100; // Parsed JSON by path, good while the file keeps its size and mtime: a // metadata.info.json can be tens of MB, and a build asks per clip. /** @type {Map} */ const jsonMemo = new Map(); /** @param {string} file @returns {Promise} */ async function readJson(file) { let st; try { st = await stat(file); } catch { return null; } const sig = `${st.size}:${st.mtimeMs}`; const had = jsonMemo.get(file); if (had && had.sig === sig) return had.value; let value = null; try { value = JSON.parse(await readFile(file, "utf8")); } catch { value = null; } // Only the few fields read here are kept, never a whole record. const kept = value && typeof value === "object" && !Array.isArray(value) ? { duration: value.duration, live_status: value.live_status, status: value.status, fromStart: value.fromStart, fallback: value.fallback, missingStream: value.missingStream, failureClass: value.failureClass, error: value.error, coverage: value.coverage, file: value.file, bytes: value.bytes, dir: value.dir, } : null; if (jsonMemo.size > 2000) jsonMemo.clear(); jsonMemo.set(file, { sig, value: kept }); return kept; } const NOT_FINAL = new Set(["is_live", "is_upcoming", "post_live"]); /** * The recording's known length in seconds and where it came from, or null. * @param {string} videoDir * @returns {Promise<{ seconds: number, basis: "metadata" | "live-recording" } | null>} */ export async function recordingKnownLength(videoDir) { const meta = await readJson(path.join(/* turbopackIgnore: true */ videoDir, "metadata.info.json")); const live = !!meta && NOT_FINAL.has(meta.live_status); const d = Number(meta?.duration); if (!live && Number.isFinite(d) && d > 0) return { seconds: d, basis: "metadata" }; const rec = await readJson(path.join(/* turbopackIgnore: true */ videoDir, "live-recording.json")); return liveRecordingLength(rec); } /** * A live recording's record's length of the stream, when it is the ended * stream's own and the record says the recording holds it all; else null. Pure. * @param {any} rec live-recording.json * @returns {{ seconds: number, basis: "live-recording" } | null} */ export function liveRecordingLength(rec) { if (!rec || rec.status !== "landed") return null; if (rec.fromStart !== true || rec.fallback || rec.missingStream || rec.failureClass || rec.error) return null; const c = rec.coverage; if (!c || c.basis !== "duration" || c.covers !== true) return null; const s = Number(c.streamSeconds); return Number.isFinite(s) && s > 0 ? { seconds: s, basis: "live-recording" } : null; } /** * Does a container ending at `containerSeconds` ON THE CUE CLOCK (its length * less the time map's offset at its end) hold the WHOLE recording? With the * sentence that says why (or why not), for a sidecar and a log. * @param {string} videoDir * @param {number} containerSeconds * @returns {Promise<{ whole: boolean, knownSeconds: number | null, basis: "metadata" | "live-recording" | null, why: string }>} */ export async function recordingWholeness(videoDir, containerSeconds) { const known = await recordingKnownLength(videoDir); const d = containerSeconds.toFixed(2); if (!known) { return { whole: false, knownSeconds: null, basis: null, why: `the saved recording ends at ${d} s and the recording's length is not known (no final duration in its record, no landed live recording that holds the whole stream by its own duration), so it may be partial`, }; } const where = known.basis === "metadata" ? "its record's duration" : "the live recording's measured stream"; const whole = known.seconds <= containerSeconds + RECORDING_END_TOLERANCE_SECONDS; return { whole, knownSeconds: known.seconds, basis: known.basis, why: whole ? `the saved recording ends at ${d} s, the whole recording (${where} is ${known.seconds} s, within ${RECORDING_END_TOLERANCE_SECONDS} s)` : `the saved recording ends at ${d} s, short of the ${known.seconds} s recording (${where}): it does not hold this window`, }; } /** * Does a clamped window still end the recording? Its sidecar's clamp names the * saved-video pointer it was cut from and the known length it was judged by; * both must be as they are now (the pointer's file and bytes; the known length * within 0.5 s). JSON reads only. A clamp from before the pointer was recorded * does not hold. * @param {string} videoDir * @param {{ container?: { file?: string, bytes?: number | null }, knownSeconds?: number } | null | undefined} clamp */ export async function clampHolds(videoDir, clamp) { if (!clamp || !clamp.container || typeof clamp.container.file !== "string" || !Number.isFinite(clamp.knownSeconds)) return false; const pointer = await readJson(path.join(/* turbopackIgnore: true */ videoDir, "saved-video.json")); if (!pointer || pointer.file !== clamp.container.file) return false; if ((Number.isFinite(pointer.bytes) ? pointer.bytes : null) !== (clamp.container.bytes ?? null)) return false; const known = await recordingKnownLength(videoDir); return !!known && Math.abs(known.seconds - Number(clamp.knownSeconds)) <= 0.5; } // The stream ends a container was measured to, by path, size and mtime. /** @type {Map} */ const endsMemo = new Map(); /** * Where a container's picture and its sound each end, in seconds from the * file's start (as ffmpeg's -ss counts them): its last packets, read from 30 s * before `durationSec`. Measured once per container per process. Null when it * cannot be read. * @param {string} file * @param {number} durationSec the container's probed length * @param {string} [ffprobeBin] * @returns {Promise<{ video: number | null, audio: number | null } | null>} */ export async function containerStreamEnds(file, durationSec, ffprobeBin = "ffprobe") { let st; try { st = await stat(file); } catch { return null; } const sig = `${st.size}:${st.mtimeMs}`; const had = endsMemo.get(file); if (had && had.sig === sig) return had.value; let value = null; try { const from = Math.max(0, durationSec - 30); const { stdout } = await execFileP( ffprobeBin, [ "-v", "error", "-read_intervals", `${from.toFixed(3)}%`, "-show_entries", "format=start_time:stream=index,codec_type:stream_disposition=attached_pic:packet=stream_index,pts_time,duration_time", "-of", "json", file, ], { maxBuffer: 1 << 26, timeout: 60_000 }, ); const doc = JSON.parse(stdout); const start = Number(doc?.format?.start_time); const zero = Number.isFinite(start) ? start : 0; /** @type {Map} */ const kinds = new Map(); for (const s of doc?.streams ?? []) { if (s?.codec_type === "video" && s?.disposition?.attached_pic === 1) continue; kinds.set(Number(s.index), String(s.codec_type)); } /** @type {{ video: number | null, audio: number | null }} */ const ends = { video: null, audio: null }; for (const p of doc?.packets ?? []) { const kind = kinds.get(Number(p.stream_index)); if (kind !== "video" && kind !== "audio") continue; const t = Number(p.pts_time); if (!Number.isFinite(t)) continue; const d = Number(p.duration_time); const e = t + (Number.isFinite(d) ? d : 0) - zero; if (ends[kind] === null || e > /** @type {number} */ (ends[kind])) ends[kind] = e; } value = ends.video === null && ends.audio === null ? null : ends; } catch { value = null; } endsMemo.set(file, { sig, value }); return value; } /** * The second a clamp may cut a container to: where BOTH its streams have data * (the shorter of the two ends; the one there is, with one), never past its * probed length. Its probed length when the ends cannot be read. * @param {string} file * @param {number} durationSec * @param {string} [ffprobeBin] */ export async function bothStreamsEnd(file, durationSec, ffprobeBin = "ffprobe") { const ends = await containerStreamEnds(file, durationSec, ffprobeBin); const have = [ends?.video, ends?.audio].filter((x) => typeof x === "number" && Number.isFinite(x) && x > 0); return have.length ? Math.min(durationSec, ...have) : durationSec; } /** * Where a span stands against a container's end. Pure. * "held" to <= end (to EPS); * "past" from >= end - EPS: nothing of it is in the file; * "clamp" it starts inside and ends past: cut to `cutTo` (⌊end⌋₂) if the recording is whole. * @param {{ from: number, to: number }} span on the container's clock * @param {number} end the container's length * @returns {{ kind: "held" } | { kind: "past" } | { kind: "clamp", cutTo: number }} */ export function spanAtEnd(span, end) { if (span.to <= end + EPS) return { kind: "held" }; if (span.from >= end - EPS) return { kind: "past" }; return { kind: "clamp", cutTo: floor2(end) }; } /** * Does a window hold [from, to]? Whole, to EPS -- or, for a window that ENDS * THE RECORDING (`endsRecording`: a saved container known whole, a window cut * clamped at its end), any span that starts inside it. Pure. * @param {{ from: number, to: number, endsRecording?: boolean }} w * @param {number} from * @param {number} to */ export function windowHoldsSpan(w, from, to) { if (w.from > from + EPS) return false; if (w.to >= to - EPS) return true; return w.endsRecording === true && from < w.to - EPS; }