// A STILL AT SECOND N (umtool redesign L6: Play's "Still" button, `umtool still`): one frame of a clip's fetched // window, grabbed with ffmpeg (`-ss -i -frames:v 1`) and saved beside the project's shots -- // `shots/`, where a clip's fx.zoom / fx.receipts and a still entry read their pictures from -- as // `shots/still--.png`. A single-frame grab: not heavy work, never the heavy slot. // // What it reads is a window ALREADY ON DISK (serve.mjs windowsFor: the project's out/clips-raw and the corpus clips // dirs the editor fetched into, a long recording's own file when the window is an excerpt of it). Nothing is // fetched: a second no fetched window holds is refused, and says to fetch it first. // // Plain ESM: the CLI runs it under bare node. import { execFile } from "node:child_process"; import { mkdir, readdir, rename, rm, stat } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { FFMPEG_BIN, FFPROBE_BIN } from "umtool-report-to-video/build-video"; import { censorRegionsOf, stillCensorArgs } from "umtool-report-to-video/clip-censor"; import { resolveInRoots } from "../paths.mjs"; import { clipsOf } from "../projects/report.mjs"; import { windowsFor } from "./serve.mjs"; const execFileP = promisify(execFile); /** The project's shots directory (relative to the project), where stills land. */ export const SHOTS_DIR = "shots"; const PICTURE_RE = /\.(png|jpe?g|webp)$/i; export class StillRefused extends Error { /** @param {string} message @param {number} [status] */ constructor(message, status = 400) { super(message); this.name = "StillRefused"; this.status = status; } } /** The file name a still of `clip` at `seconds` gets: `still--s.png`, the second to 2 dp (a dot as "_"). */ export const stillNameOf = (clip, seconds) => `still-${String(clip).replace(/[^A-Za-z0-9_-]+/g, "-")}-${(Math.round(seconds * 100) / 100).toFixed(2).replace(".", "_")}s.png`; /** * The window file a frame at `at` (a SOURCE second) is read from, and its offset: the fetched window that holds * it (an excerpt's own recording, which holds it too; a window laid in pieces is skipped -- its filler is black). * * @param {{ dir: string, id: string }} project * @param {Record} clip * @param {number} at */ export async function stillSourceOf(project, clip, at, { preferTall = false, ffprobe = null } = {}) { const windows = await windowsFor(project, clip); const found = []; for (const w of windows) { if (w.piecesOf) continue; const src = w.excerptOf ? { path: w.excerptOf.path, from: w.excerptOf.from } : { path: w.path, from: w.from }; const to = w.excerptOf ? Infinity : w.to; if (!(at >= src.from - 0.01 && at <= to + 0.01)) continue; const abs = resolveInRoots(src.path); if (!abs) continue; if (!(await stat(abs).catch(() => null))?.isFile()) continue; const hit = { file: abs, offset: Math.max(0, at - src.from) }; if (!preferTall) return hit; found.push(hit); } if (!found.length) return null; // The tallest picture of those that hold the second (a project fetching taller windows: render.tallWindows). const heightOf = async (f) => { const { stdout } = await execFileP(ffprobe ?? FFPROBE_BIN, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=height", "-of", "csv=p=0", f]).catch(() => ({ stdout: "0" })); return Number(String(stdout).trim()) || 0; }; let best = found[0]; let bestH = await heightOf(best.file); for (const f of found.slice(1)) { const h = await heightOf(f.file); if (h > bestH) { best = f; bestH = h; } } return best; } /** * Grab the frame of `clipId` at source second `at` into `shots/`. Returns `{ rel, file, clip, at, bytes }`. * Refused (StillRefused) for a clip not in the cut, a second outside every fetched window, or a window with * no picture. * * @param {{ dir: string, id: string }} project * @param {Record} manifest the cut the clip is in (the draft, or a version's) * @param {string} clipId * @param {number} at a source second * @param {{ ffmpeg?: string, name?: string | null }} [opts] */ export async function grabStill(project, manifest, clipId, at, { ffmpeg = FFMPEG_BIN, name = null, preferTall = false } = {}) { const clip = clipsOf(manifest).find((e) => e.id === clipId); if (!clip) throw new StillRefused(`no clip ${clipId} in ${project.id}`, 404); const t = Number(at); if (!Number.isFinite(t) || t < 0) throw new StillRefused("at is a source second, 0 or more"); const src = await stillSourceOf(project, clip, t, { preferTall }); if (!src) throw new StillRefused(`no fetched window of ${clip.video} holds ${t.toFixed(2)} s -- fetch ${clipId} first (umtool fetch ${project.id} --clips ${clipId})`, 409); const file = name ?? stillNameOf(clipId, t); if (!/^[A-Za-z0-9_.-]{1,120}\.png$/.test(file)) throw new StillRefused(`a still's name is letters, digits, . _ - and .png (got ${file})`); const dir = path.join(project.dir, SHOTS_DIR); await mkdir(dir, { recursive: true }); const out = path.join(dir, file); // Two grabs of one second at once never share a temp file. const tmp = path.join(dir, `.${file}.part-${process.pid}-${Math.random().toString(36).slice(2, 10)}.png`); try { // Its hidden regions at that second (report-to-video clip-censor.mjs): hidden in the still, as in every cut. const regions = censorRegionsOf(clip, manifest?.render ?? {}, manifest?.provenance ?? {}); let cen = []; if (regions.length) { const { stdout } = await execFileP(FFPROBE_BIN, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", src.file]); const [w, h] = String(stdout).trim().split(",").map(Number); if (!(w > 0 && h > 0)) throw new StillRefused(`${clipId} hides regions of its picture, and its window's size could not be read: no still is grabbed`, 500); cen = stillCensorArgs(regions, t, { width: w, height: h }); } await execFileP(ffmpeg, ["-v", "error", "-y", "-ss", src.offset.toFixed(3), "-i", src.file, ...cen, "-frames:v", "1", "-an", tmp], { timeout: 60_000 }); const st = await stat(tmp).catch(() => null); if (!st?.size) throw new StillRefused(`the window of ${clip.video} has no picture at ${t.toFixed(2)} s (an audio-only fetch?)`, 409); await rename(tmp, out); return { rel: `${SHOTS_DIR}/${file}`, file: out, clip: clipId, video: String(clip.video), at: Math.round(t * 100) / 100, bytes: st.size }; } catch (e) { if (e instanceof StillRefused) throw e; const msg = String(/** @type {any} */ (e)?.stderr || (e instanceof Error ? e.message : e)).trim().split("\n").slice(-2).join(" "); throw new StillRefused(`ffmpeg could not grab the frame: ${msg}`, 500); } finally { await rm(tmp, { force: true }); } } /** * The pictures in the project's shots/ (newest first): `{ rel, name, bytes, mtime, still }`, `still` when it is one * of these grabs (`still-*`), with its clip and second read back from its name. * * @param {string} dir */ export async function listShots(dir) { const root = path.join(dir, SHOTS_DIR); const names = await readdir(root).catch(() => []); const out = []; for (const n of names) { if (n.startsWith(".") || !PICTURE_RE.test(n)) continue; const st = await stat(path.join(root, n)).catch(() => null); if (!st?.isFile()) continue; const m = /^still-(.+)-(\d+)_(\d{2})s\.png$/.exec(n); out.push({ rel: `${SHOTS_DIR}/${n}`, name: n, bytes: st.size, mtime: new Date(st.mtimeMs).toISOString(), still: m ? { clip: m[1], at: Number(`${m[2]}.${m[3]}`) } : null, }); } return out.sort((a, b) => b.mtime.localeCompare(a.mtime) || a.name.localeCompare(b.name)); } /** A shots/ file's absolute path, never outside shots/ (null when it is not a picture there). */ export function shotFileOf(dir, rel) { const r = String(rel ?? ""); if (!r.startsWith(`${SHOTS_DIR}/`) || r.split("/").length !== 2 || r.includes("..") || !PICTURE_RE.test(r)) return null; return path.join(dir, ...r.split("/")); }