// recordingClock-server — MEASURE a recording's time map and write it // (lane one-clock; the map itself, its fit and its lookups: ./recordingClock.mjs). // // The SOURCE is the file the cues were transcribed from — the video dir's // `audio.` (the one the transcribe path reads first, AUDIO_PREFERENCE) — // and the TARGET is the saved whole container. The source is decoded FROM ITS // START, as the transcriber decoded it: an mp3 cannot be seeked to the sample // (a VBR file's byte seek lands where its bitrate estimate says, not where the // samples are), and a cue's second is a count of samples from the first. Only // the probes are kept (≈ 20 s each), so a four-hour stream costs a streamed // decode, not its PCM in memory. The target is an mp4, whose index seeks // exactly, so each anchor decodes only its own search excerpt there, with the // same input seek the cutters use (evidenceClip.mjs cutArgs). // // No map is measured when the source shares the container's clock: a landed // container whose `audio.` was EXTRACTED from it (media-import.json, the // live recorder and import-media). Its cues are the container's own seconds. // // `data//clock.json` is a declared sidecar (sidecar-server.ts). A map that // is not ok is written too, with its reason: the next fetch knows the stream // was measured and why the map cannot be trusted, and says so instead of // measuring again. import { spawn } from "node:child_process"; import { stat } from "node:fs/promises"; import path from "node:path"; import { execa } from "execa"; import { sidecar, sidecarField } from "./sidecar-server"; import { CLOCK_DEFAULTS, CLOCK_FILE, CLOCK_VERSION, anchorTimes, clockMatches, coerceRecordingClock, describeClock, fitClock, measureAnchor, refineTimes, type RecordingClock, } from "./recordingClock.mjs"; import { audioFilesOf, present } from "./evidenceClip.mjs"; import { probeMedia } from "./evidenceClip-server"; import { loadSavedVideo } from "./savedVideo-server"; import { savedVideoPath, type SavedVideoPointer } from "./savedVideo"; import { coerceMediaImport, MEDIA_IMPORT_FILENAME } from "./mediaImport"; import { readJsonFile } from "./jsonFile-server"; import { loadTranscribeOutcome } from "./transcribeOutcome-server"; import "./childKillGuard"; export const recordingClockSidecar = sidecar(CLOCK_FILE, sidecarField(coerceRecordingClock), { indent: 2 }); export type ClockOptions = Partial; // ---- decoding --------------------------------------------------------------- /** * Decode `file` from its first sample, mono at `sampleRate`, keeping only the * spans asked for (seconds, the decoder's own clock). Stops reading at the * last span's end. */ export async function decodeSpansFromStart(opts: { ffmpegBin: string; file: string; spans: { from: number; to: number }[]; sampleRate: number; signal?: AbortSignal; }): Promise { const { sampleRate: sr } = opts; const spans = opts.spans.map((s) => ({ a: Math.max(0, Math.round(s.from * sr)), b: Math.max(0, Math.round(s.to * sr)), })); const out = spans.map((s) => new Float32Array(Math.max(0, s.b - s.a))); const end = spans.reduce((m, s) => Math.max(m, s.b), 0); if (end === 0) return out; const args = [ "-v", "error", "-nostdin", "-i", opts.file, "-vn", "-ac", "1", "-ar", String(sr), "-t", ((end + sr) / sr).toFixed(3), "-f", "f32le", "pipe:1", ]; await new Promise((resolve, reject) => { const child = spawn(opts.ffmpegBin, args, { stdio: ["ignore", "pipe", "pipe"] }); let err = ""; let pos = 0; // samples seen let carry: Buffer | null = null; const onAbort = () => child.kill("SIGKILL"); opts.signal?.addEventListener("abort", onAbort, { once: true }); child.stderr.on("data", (d: Buffer) => { err = (err + d.toString()).slice(-2000); }); child.stdout.on("data", (chunk: Buffer) => { let buf = carry ? Buffer.concat([carry, chunk]) : chunk; const whole = buf.length - (buf.length % 4); carry = whole < buf.length ? Buffer.from(buf.subarray(whole)) : null; buf = buf.subarray(0, whole); const n = whole / 4; const chunkStart = pos; const chunkEnd = pos + n; for (let i = 0; i < spans.length; i += 1) { const s = spans[i]; const lo = Math.max(s.a, chunkStart); const hi = Math.min(s.b, chunkEnd); for (let k = lo; k < hi; k += 1) out[i][k - s.a] = buf.readFloatLE((k - chunkStart) * 4); } pos = chunkEnd; }); child.on("error", reject); child.on("close", (code) => { opts.signal?.removeEventListener("abort", onAbort); if (opts.signal?.aborted) reject(new Error("cancelled")); else if (code !== 0) reject(new Error(`ffmpeg could not decode ${path.basename(opts.file)}: ${err.trim().split("\n").slice(-2).join(" | ")}`)); else resolve(); }); }); return out; } // The seconds an input seek lands short of, decoded and dropped by an output // seek. An input seek alone into an AAC track lands 10–55 ms off, varying with // the second (measured on an audio-only mp4: 48, 38, 54, 12 ms at four // seconds); seeking PRE_ROLL_S earlier and dropping the rest after the decoder // is exact at every one. const PRE_ROLL_S = 3; /** Decode [from, from + seconds) of `file`: an input seek PRE_ROLL_S early, then exact. */ export async function decodeExcerpt(opts: { ffmpegBin: string; file: string; from: number; seconds: number; sampleRate: number; signal?: AbortSignal; }): Promise { const from = Math.max(0, opts.from); const seek = Math.max(0, from - PRE_ROLL_S); const r = await execa( opts.ffmpegBin, [ "-v", "error", "-nostdin", "-ss", seek.toFixed(3), "-i", opts.file, "-ss", (from - seek).toFixed(3), "-t", opts.seconds.toFixed(3), "-vn", "-ac", "1", "-ar", String(opts.sampleRate), "-f", "f32le", "pipe:1", ], { encoding: "buffer", reject: false, timeout: 120_000, maxBuffer: 64 * 1024 * 1024, ...(opts.signal ? { cancelSignal: opts.signal } : {}), }, ); if (r.exitCode !== 0) { const err = Buffer.from(r.stderr ?? "").toString().trim().split("\n").slice(-2).join(" | "); throw new Error(`ffmpeg could not decode ${path.basename(opts.file)} at ${opts.from.toFixed(1)}s: ${err}`); } const buf = Buffer.from(r.stdout as Uint8Array); const n = Math.floor(buf.length / 4); const out = new Float32Array(n); for (let i = 0; i < n; i += 1) out[i] = buf.readFloatLE(i * 4); return out; } // ---- which files --------------------------------------------------------------- /** The file the cues were transcribed from: the best `audio.` there is. */ export async function transcriptionSourceOf(videoDir: string): Promise<{ name: string; path: string } | null> { for (const f of await audioFilesOf(videoDir)) if (await present(f.path)) return f; return null; } /** * Was the transcription source EXTRACTED from this container (a landed live * recording, an import)? Then the cues are already on its clock. */ export async function sourceSharesContainerClock(videoDir: string, pointer: SavedVideoPointer): Promise { const read = await readJsonFile(path.join(videoDir, MEDIA_IMPORT_FILENAME)); if (!read.ok) return false; const rec = coerceMediaImport(read.value); const last = rec?.entries?.[rec.entries.length - 1]; return !!last && last.audio === "extracted" && last.container?.file === pointer.file; } export type ClockPlan = | { kind: "no-container" } | { kind: "no-source" } | { kind: "same-clock"; source: string; container: string } | { kind: "current"; clock: RecordingClock; source: string; container: string } | { kind: "measure"; source: string; container: string; sourceBytes: number; targetBytes: number; transcribedAt: string | null; stale: RecordingClock | null; }; /** What a video dir needs: nothing, its map as it is, or a measurement. */ export async function planRecordingClock(videoDir: string): Promise { const pointer = await loadSavedVideo(videoDir); if (!pointer) return { kind: "no-container" }; const container = savedVideoPath(pointer); const src = await transcriptionSourceOf(videoDir); if (!src) return { kind: "no-source" }; if (await sourceSharesContainerClock(videoDir, pointer)) { return { kind: "same-clock", source: src.path, container }; } const [s, t, outcome] = await Promise.all([stat(src.path), stat(container), loadTranscribeOutcome(videoDir)]); const have = await recordingClockSidecar.load(videoDir); // The cues made again since the map was measured (a re-transcription) are // another clock's seconds until measured again. const sameCues = (have?.cues?.transcribedAt ?? null) === (outcome?.transcribedAt ?? null); if ( have && sameCues && have.target.file === path.basename(container) && have.source.file === src.name && clockMatches(have, { sourceBytes: s.size, targetBytes: t.size }) ) { return { kind: "current", clock: have, source: src.path, container }; } return { kind: "measure", source: src.path, container, sourceBytes: s.size, targetBytes: t.size, transcribedAt: outcome?.transcribedAt ?? null, stale: have, }; } // ---- measuring ------------------------------------------------------------------ /** * Measure the map of `videoDir`'s transcription source onto its saved * container: anchors every `everySeconds` and at `extra` (cue seconds — the * cited spans), refined inside every step until narrow; fitted; WRITTEN (ok or * not) unless `write: false`. */ export async function measureRecordingClock(opts: { ffmpegBin: string; ffprobeBin: string; videoDir: string; source: string; container: string; sourceBytes: number; targetBytes: number; // The transcript's transcribedAt (transcribe-outcome.json): which cues the // map is about. transcribedAt?: string | null; extra?: number[]; options?: ClockOptions; write?: boolean; onLog?: (line: string) => void; signal?: AbortSignal; now?: () => Date; }): Promise { const o = { ...CLOCK_DEFAULTS, ...(opts.options ?? {}) }; const sr = o.sampleRate; const log = (l: string) => opts.onLog?.(l.endsWith("\n") ? l : `${l}\n`); const [sp, tp] = await Promise.all([ probeMedia(opts.source, opts.ffprobeBin), probeMedia(opts.container, opts.ffprobeBin), ]); const sourceSec = sp?.durationSec ?? null; const targetSec = tp?.durationSec ?? null; if (!sourceSec || !targetSec) { throw new Error(`ffprobe could not read ${!sourceSec ? opts.source : opts.container}`); } const half = o.probeSeconds / 2; const measure = async (times: number[]) => { const probes = await decodeSpansFromStart({ ffmpegBin: opts.ffmpegBin, file: opts.source, spans: times.map((t) => ({ from: t - half, to: t + half })), sampleRate: sr, signal: opts.signal, }); const out = []; for (let i = 0; i < times.length; i += 1) { const at = times[i]; const searchStart = Math.max(0, at - half - o.searchSeconds); const searchEnd = Math.min(targetSec, at + half + o.searchSeconds); if (searchEnd - searchStart < o.probeSeconds) { out.push({ at, offset: null, score: 0, ratio: 0, ok: false, why: "past the container's end" }); continue; } const search = await decodeExcerpt({ ffmpegBin: opts.ffmpegBin, file: opts.container, from: searchStart, seconds: searchEnd - searchStart, sampleRate: sr, signal: opts.signal, }); out.push(measureAnchor({ at, probe: probes[i], search, searchStart, sampleRate: sr }, o)); } return out; }; const first = anchorTimes(sourceSec, { ...o, extra: opts.extra ?? [] }); log( ` ⏱ clock: ${path.basename(opts.source)} (${Math.round(sourceSec)} s, the cues' clock) against ` + `${path.basename(opts.container)} (${Math.round(targetSec)} s): ${first.length} anchor(s)`, ); let anchors = await measure(first); let fit = fitClock(anchors, o); for (let pass = 0; pass < o.maxRefinePasses; pass += 1) { const more = refineTimes(fit, o).filter((t) => t >= half && t <= sourceSec - half); if (!more.length) break; log(` ⏱ clock: a step between segments — ${more.length} more anchor(s) to narrow it`); anchors = [...anchors, ...(await measure(more))].sort((a, b) => a.at - b.at); fit = fitClock(anchors, o); } const createdAt = (opts.now?.() ?? new Date()).toISOString(); const clock: RecordingClock = { version: CLOCK_VERSION, id: `${createdAt}:${opts.targetBytes}`, createdAt, source: { file: path.basename(opts.source), bytes: opts.sourceBytes }, target: { file: path.basename(opts.container), bytes: opts.targetBytes }, ...(opts.transcribedAt ? { cues: { transcribedAt: opts.transcribedAt } } : {}), method: "xcorr", params: { sampleRate: sr, probeSeconds: o.probeSeconds, searchSeconds: o.searchSeconds, everySeconds: o.everySeconds, tolerance: o.tolerance, sourceSeconds: sourceSec, targetSeconds: targetSec, }, anchors, segments: fit.segments, gaps: fit.gaps, residual: fit.residual, ok: fit.ok, ...(fit.why ? { why: fit.why } : {}), }; if (opts.write !== false) await recordingClockSidecar.write(opts.videoDir, clock); log(` ⏱ clock ${opts.write !== false ? `→ ${CLOCK_FILE}` : "(not written)"}: ${describeClock(clock)}`); if (!clock.ok) { // The fallback (lane one-clock, part 4) is a transcript made from the saved // video itself -- one file, one clock -- and is not started from here. log( " ⏱ the map cannot be trusted: windows are cut on its best guess and said NOT certain — " + "check their quotes (umtool quote-check); re-transcribing from the saved video is the fallback.", ); } return clock; } /** * The map a cut from this video's saved container goes through: the current * one, else measured now (and written). Null when no map applies (no * container, no separate source, a source extracted from the container). */ export async function ensureRecordingClock(opts: { ffmpegBin: string; ffprobeBin: string; videoDir: string; extra?: number[]; options?: ClockOptions; onLog?: (line: string) => void; signal?: AbortSignal; }): Promise<{ clock: RecordingClock | null; measured: boolean; plan: ClockPlan["kind"] }> { const plan = await planRecordingClock(opts.videoDir); if (plan.kind === "current") return { clock: plan.clock, measured: false, plan: plan.kind }; if (plan.kind !== "measure") return { clock: null, measured: false, plan: plan.kind }; const clock = await measureRecordingClock({ ...opts, ...plan }); return { clock, measured: true, plan: plan.kind }; } /** * May a held window of this video answer for a cue span? Not when the * recording's map is due (measured on the next fetch-windows run: every window * there is on another clock) and not when it was cut through another map than * the current one. A video no map applies to: yes, as ever. */ export async function heldWindowOnClock( videoDir: string, provenance: { clock?: { id: string } } | null | undefined, ): Promise { let plan: ClockPlan; try { plan = await planRecordingClock(videoDir); } catch { // A file the plan could not stat (a drive not answering): the cut path's // own guards say so; the cache answers as before. return true; } if (plan.kind === "measure") return false; if (plan.kind === "current") return provenance?.clock?.id === plan.clock.id; return true; }