// Sampling a saved video into frames (release 30, lane P): ONE ffmpeg per // batch of the stream (half an hour by default), never one process per frame. // Each batch writes its frames as JPEGs scaled to the profile's width and, on // the same decode, a tiny grey thumbnail per frame on stdout for the dHash. // // By default only the KEYFRAMES are decoded (`-skip_frame nokey`): a 4-hour // 1080p stream decodes in a minute or two instead of half an hour, and a // frame's picture is then the keyframe nearest its grid time — at most a // keyframe interval away (two seconds or so on a stream). `t` is always the // grid time in SOURCE seconds, so clips cut from it line up within that. // // The cache is a directory of JPEGs plus `index.json` (the grid, the width and // each frame's hash). A re-run reuses every frame the index already has on the // same grid and width. Server-only (node:child_process, node:fs). import { spawn } from "node:child_process"; import { mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises"; import path from "node:path"; import { writeJsonAtomic } from "../jsonFile-server"; import { hashesOf, THUMB_H, THUMB_W } from "./dhash"; import type { FrameRef } from "./types"; export const FRAME_INDEX_FILE = "index.json"; export const DEFAULT_BATCH_SECONDS = 1800; export type FrameIndex = { everySeconds: number; width: number; keyframesOnly: boolean; // The part of the picture kept, as fractions of it: [x, y, w, h]; absent = all of it. crop?: Crop; frames: FrameRef[]; }; /** A region of the picture as fractions of its width and height: [x, y, w, h]. */ export type Crop = [number, number, number, number]; /** Whether a crop is four fractions that stay inside the picture. */ export function isCrop(v: unknown): v is Crop { return ( Array.isArray(v) && v.length === 4 && v.every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0 && n <= 1) && v[2] > 0.05 && v[3] > 0.05 && v[0] + v[2] <= 1.0001 && v[1] + v[3] <= 1.0001 ); } const sameCrop = (a?: Crop, b?: Crop) => (!a && !b) || (!!a && !!b && a.every((v, i) => Math.abs(v - b[i]) < 1e-6)); /** A grid time as the frame's file name: `t000012340.jpg` (centiseconds). */ export const frameFileOf = (t: number) => `t${String(Math.round(t * 100)).padStart(9, "0")}.jpg`; /** The grid: from, from+N, … below `to`, rounded to the centisecond. */ export function gridOf(from: number, to: number, every: number): number[] { const out: number[] = []; if (!(every > 0) || !(to > from)) return out; for (let k = 0; ; k++) { const t = Math.round((from + k * every) * 100) / 100; if (t >= to) break; out.push(t); } return out; } /** The batches a grid is sampled in: [from, to) windows of at most `seconds`, on grid points. */ export function batchesOf(grid: readonly number[], every: number, seconds = DEFAULT_BATCH_SECONDS): number[][] { const per = Math.max(1, Math.floor(seconds / every)); const out: number[][] = []; for (let i = 0; i < grid.length; i += per) out.push(grid.slice(i, i + per)); return out; } export async function readFrameIndex(dir: string): Promise { try { const v = JSON.parse(await readFile(path.join(dir, FRAME_INDEX_FILE), "utf8")) as FrameIndex; return v && Array.isArray(v.frames) && typeof v.everySeconds === "number" && typeof v.width === "number" ? v : null; } catch { return null; } } export async function probeDuration(file: string, ffprobe = "ffprobe"): Promise { const out = await runCapture(ffprobe, ["-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", file]).catch(() => null); const d = out ? Number(out.stdout.toString("utf8").trim()) : NaN; return Number.isFinite(d) && d > 0 ? d : null; } function runCapture(cmd: string, args: string[], signal?: AbortSignal): Promise<{ stdout: Buffer; stderr: string }> { return new Promise((resolve, reject) => { const p = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], signal }); const out: Buffer[] = []; let err = ""; p.stdout.on("data", (c: Buffer) => out.push(c)); p.stderr.on("data", (c: Buffer) => { err += c.toString("utf8"); if (err.length > 20_000) err = err.slice(-10_000); }); p.on("error", reject); p.on("close", (code) => { if (code === 0) resolve({ stdout: Buffer.concat(out), stderr: err }); else reject(new Error(`${cmd} exited ${code}: ${err.trim().split("\n").slice(-3).join(" | ")}`)); }); }); } /** The ffmpeg arguments for one batch (exported for the test). */ export function batchArgs(o: { source: string; start: number; seconds: number; every: number; width: number; outPattern: string; keyframesOnly: boolean; crop?: Crop }): string[] { // The crop comes after the sampling (it then runs on one frame in N) and // before both the JPEG and the thumbnail, so a webcam or an overlay beside // the region does not make two frames of one picture differ. const crop = o.crop ? `,crop=trunc(iw*${o.crop[2]}/2)*2:trunc(ih*${o.crop[3]}/2)*2:trunc(iw*${o.crop[0]}):trunc(ih*${o.crop[1]})` : ""; return [ "-hide_banner", "-loglevel", "error", "-nostdin", ...(o.keyframesOnly ? ["-skip_frame", "nokey"] : []), "-ss", String(o.start), "-t", String(o.seconds), "-i", o.source, "-filter_complex", `[0:v]fps=1/${o.every}:round=near${crop},split=2[a][b];[a]scale=${o.width}:-2:flags=area[big];[b]scale=${THUMB_W}:${THUMB_H}:flags=area,format=gray[small]`, "-map", "[big]", "-q:v", "3", "-start_number", "0", o.outPattern, "-map", "[small]", "-f", "rawvideo", "pipe:1", ]; } /** * Sample `[from, to)` of `source` every `every` seconds into `dir`. Frames the * index already has (same grid step, width and decode mode) are kept and not * decoded again; a batch with any frame missing is decoded whole. Answers the * index, every frame of the range in order. */ export async function sampleFrames(o: { source: string; dir: string; from: number; to: number; every: number; width: number; keyframesOnly?: boolean; crop?: Crop; batchSeconds?: number; ffmpeg?: string; signal?: AbortSignal; onLog?: (line: string) => void; onBatch?: (done: number, total: number) => void; }): Promise { const keyframesOnly = o.keyframesOnly ?? true; await mkdir(o.dir, { recursive: true }); const prev = await readFrameIndex(o.dir); const same = prev && prev.everySeconds === o.every && prev.width === o.width && prev.keyframesOnly === keyframesOnly && sameCrop(prev.crop, o.crop); const have = new Map(); if (same) { const files = new Set(await readdir(o.dir).catch(() => [] as string[])); for (const f of prev!.frames) if (files.has(f.file)) have.set(f.t, f); } const grid = gridOf(o.from, o.to, o.every); const batches = batchesOf(grid, o.every, o.batchSeconds); const index: FrameIndex = { everySeconds: o.every, width: o.width, keyframesOnly, ...(o.crop ? { crop: o.crop } : {}), frames: [] }; // Frames outside this run's range stay in the index. const keepOutside = same ? prev!.frames.filter((f) => (f.t < o.from || f.t >= o.to) && have.has(f.t)) : []; let done = 0; for (const batch of batches) { if (o.signal?.aborted) throw new Error("cancelled"); if (batch.every((t) => have.has(t))) { for (const t of batch) index.frames.push(have.get(t)!); o.onBatch?.(++done, batches.length); continue; } const start = batch[0]; const seconds = Math.round((batch[batch.length - 1] - start + o.every) * 100) / 100; const tmp = path.join(o.dir, `.batch-${process.pid}-${Math.round(start * 100)}`); await rm(tmp, { recursive: true, force: true }); await mkdir(tmp, { recursive: true }); try { const { stdout } = await runCapture( o.ffmpeg ?? "ffmpeg", batchArgs({ source: o.source, start, seconds, every: o.every, width: o.width, outPattern: path.join(tmp, "%06d.jpg"), keyframesOnly, ...(o.crop ? { crop: o.crop } : {}) }), o.signal, ); const hashes = hashesOf(stdout); const written = (await readdir(tmp)).filter((f) => /^\d{6}\.jpg$/.test(f)).sort(); const n = Math.min(batch.length, hashes.length, written.length); for (let k = 0; k < n; k++) { const t = batch[k]; const file = frameFileOf(t); await rename(path.join(tmp, written[k]), path.join(o.dir, file)); index.frames.push({ t, file, hash: hashes[k] }); } if (n < batch.length) o.onLog?.(`frames ${batch[0]}–${batch[batch.length - 1]} s: ${n} of ${batch.length} decoded (the stream ends or has no picture there)`); } finally { await rm(tmp, { recursive: true, force: true }); } o.onBatch?.(++done, batches.length); // The index after every batch: a cut run keeps what it decoded. await writeIndex(o.dir, index, keepOutside); } await writeIndex(o.dir, index, keepOutside); return index; } async function writeIndex(dir: string, index: FrameIndex, outside: FrameRef[]): Promise { const frames = [...outside, ...index.frames].sort((a, b) => a.t - b.t); const seen = new Set(); await writeJsonAtomic(path.join(dir, FRAME_INDEX_FILE), { ...index, frames: frames.filter((f) => (seen.has(f.t) ? false : (seen.add(f.t), true))) }, { indent: 0 }); } /** The cache's size on disk, and remove it. */ export async function frameCacheBytes(dir: string): Promise { let total = 0; for (const f of await readdir(dir).catch(() => [] as string[])) total += (await stat(path.join(dir, f)).catch(() => null))?.size ?? 0; return total; } export async function removeFrameCache(dir: string): Promise { const there = await stat(dir).then(() => true, () => false); if (there) await rm(dir, { recursive: true, force: true }); return there; }