Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

34.1 KB
Raw Blame
// Real preset covers from measured runs (O8: "the renders become the preview media"). For each case of a
// run, the best render of the variant that earned it (the promoted candidate, or a variant you name, such
// as `catalog`: what ships today) is encoded small into public/previews/<suite>/ and listed in
// src/lib/preset-previews.generated.ts, which the gallery cards read instead of their procedural preview.
// Only Fuobe's own renders become covers: demo media never does, nor a render whose LoRAs aren't
// commercial. A person reviews the media and the generated file before committing them.
//
// Every URL the manifest lists carries its file's content version (`?v=`, contentVersion), so a cover made again
// under the same name gets a new URL: the site serves versioned covers with a year's cache (next.config.ts).
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { promote } from "./compare.mjs";
import { METRIC_INFO } from "./metric-info.mjs";
import { REPO_DIR, safeName } from "./paths.mjs";
import { jobScores, loadRun } from "./report.mjs";

export const COVERS_DIR = path.join(REPO_DIR, "public", "previews");
export const MANIFEST_FILE = path.join(REPO_DIR, "src", "lib", "preset-previews.generated.ts");

/** Longest side of a cover still, and of a cover clip (px); a clip's first seconds, at CLIP_FPS. */
const STILL_PX = 768;
const CLIP_PX = 512;
export const CLIP_SECONDS = 4;
export const CLIP_FPS = 24;
/**
 * Longest a clip that rests on its last frame keeps (s): a reveal is cut at its own end, not at CLIP_SECONDS. A clip
 * that keeps its whole length (`length: "full"`) is cut here too.
 */
const REST_CLIP_SECONDS = 8;
/** Frames at a clip's end crossfaded into its first ones: the cards play clips with `loop`, and this hides the jump. */
export const LOOP_FADE = 6;
/** Width of a poster's small copy (px), which the pickers' tiles show: enough for a 136 px tile on a 2x screen. */
const THUMB_PX = 320;

/** Where a poster's small copy goes: thumbs/ next to it (the pickers read it there: thumbOf, src/lib/preset-covers.ts). */
export const thumbOf = (poster) => poster.replace(/\/([^/]+)$/, "/thumbs/$1");

/** Width of a poster's smallest copy (px): the menus' 36 px rows and the phone's 52 px tiles, on a 2x screen. */
const MINI_PX = 96;
/** Where that copy goes: mini/ next to the poster, with the poster's version (miniOf, src/lib/preset-cards.ts). */
export const miniOf = (poster) => poster.replace(/\/([^/]+)$/, "/mini/$1");
/** The posters that get a mini copy: a preset's own, at /previews/presets/<id>.jpg (not its peak frame, not a template's). */
const MINI_POSTER = /^\/previews\/presets\/[^/]+\.jpg(\?|$)/;

/**
 * Which presets have a mini copy, each with the content version of the poster it was made from (contentVersion of the
 * poster alone): the menus show a mini only for a preset listed here, and a test checks each version against its
 * poster, so a mini never shows an old picture under its poster's new version. Kept by writeThumbs.
 */
export const MINIS_FILE = path.join(REPO_DIR, "src", "lib", "preset-minis.generated.ts");
const MINIS_HEADER = `/**
 * The presets whose poster has its 96 px copy for the bar's menus (public/previews/presets/mini/<id>.jpg), each with
 * the content version of the poster it was made from. The menus show a mini only for a preset listed here; a test
 * checks every version against its poster. Generated by pnpm eval:covers (writeThumbs): run it again rather than
 * editing.
 */
export const PRESET_MINIS: Record<string, string> = `;

/** The minis list next to a public dir: the repo's for the repo's public/, else a file in that dir (a test's). */
const minisFileFor = (publicDir) =>
  path.resolve(publicDir) === path.resolve(path.dirname(COVERS_DIR)) ? MINIS_FILE : path.join(publicDir, "preset-minis.generated.ts");

/** The minis list (id: the version of the poster each mini was made from); empty when there is none yet. */
export function readMinis(file = MINIS_FILE) {
  try {
    const text = fs.readFileSync(file, "utf8");
    return JSON.parse(
      text
        .slice(text.indexOf("=", text.indexOf("PRESET_MINIS")) + 1)
        .trim()
        .replace(/;\s*$/, ""),
    );
  } catch {
    return {};
  }
}

function writeMinis(minis, file) {
  const sorted = Object.fromEntries(Object.entries(minis).sort(([a], [b]) => a.localeCompare(b)));
  fs.mkdirSync(path.dirname(file), { recursive: true });
  fs.writeFileSync(file, `${MINIS_HEADER}${JSON.stringify(sorted, null, 2)};\n`);
}

/** A cover URL: the file's path, then `?v=` and its content version, 8 hex digits (none before it's versioned). */
const VERSIONED = /^([^?]*)(?:\?v=([0-9a-f]{8}))?$/;
/** A cover URL's path, without its version. */
export const bareUrl = (url) => VERSIONED.exec(String(url))?.[1] ?? String(url).split("?")[0];
/** A cover URL's version, or undefined when it has none. */
export const urlVersion = (url) => VERSIONED.exec(String(url))?.[2];

/**
 * A short content version: the first 8 hex digits of the sha256 of these files' bytes, one after another. A file
 * made again with other bytes gets another one, so its URL changes and every cache that kept the old file fetches it.
 */
export function contentVersion(files) {
  const hash = createHash("sha256");
  for (const f of files) hash.update(fs.readFileSync(f));
  return hash.digest("hex").slice(0, 8);
}

const HEADER = `/**
 * Real preset covers: renders from measured runs of the evaluation harness (scripts/eval, pnpm eval:covers),
 * keyed by preset id (a DoP motion or effect: "effect-thunder-god") or Soul look id ("v1-general"). The gallery
 * cards show them instead of the procedural preview. Each URL ends in its file's content version (?v=), so a cover
 * made again gets a new URL. Generated by pnpm eval:covers: run it again rather than editing.
 */
export interface PresetPreviewMedia {
  /**
   * A still (the clip's first frame for motions and effects), under /previews, with its version: the hash of the
   * still and of its 320 px copy in thumbs/ next to it, whose URL (thumbOf) keeps the same version.
   */
  poster: string;
  /** A short muted clip, for motions and effects, with its version. */
  video?: string;
  /** Where it came from: the run, its engine, the model and variant that made it. */
  run: string;
  engine: string;
  model: string;
  variant: string;
}

export const PRESET_PREVIEWS: Record<string, PresetPreviewMedia> = `;

/**
 * The manifest's entries as they stand (the JSON literal after the header); none when there is no file yet. A
 * file that can't be read as a manifest throws: writing over it would drop every other run's entries.
 */
export function readManifest(file = MANIFEST_FILE) {
  let text;
  try {
    text = fs.readFileSync(file, "utf8");
  } catch (e) {
    if (e?.code === "ENOENT") return {};
    throw e;
  }
  try {
    const at = text.indexOf("export const PRESET_PREVIEWS");
    if (at < 0) throw new Error("no PRESET_PREVIEWS");
    const entries = JSON.parse(text.slice(text.indexOf("=", at) + 1).trim().replace(/;\s*$/, ""));
    if (!entries || typeof entries !== "object" || Array.isArray(entries)) throw new Error("not an object");
    return entries;
  } catch (e) {
    throw new Error(`${file} isn't a covers manifest pnpm eval:covers can read (${e.message}): fix or restore it before making covers`);
  }
}

const SLIM_HEADER = `/**
 * Which presets have a real cover, for the pickers in the browser (read through presetCover, preset-covers.ts): for a
 * still at /previews/presets/<id>.jpg its version, for a clip at <id>.mp4 with its poster at <id>.jpg the poster's
 * and the clip's, or the URLs of a cover kept elsewhere. A version is the ?v= its URL ends in; the poster's also
 * stands for its small copy for the pickers' tiles, in thumbs/ next to it. The slim side of
 * preset-previews.generated.ts, whose provenance stays on the server.
 * Generated with it by pnpm eval:covers: run it again rather than editing.
 */
export type PresetCoverEntry = string | [poster: string, clip: string] | { poster: string; video?: string };

export const PRESET_COVERS: Record<string, PresetCoverEntry> = `;

/** A manifest entry as the slim map lists it: only its versions for a cover at the usual place, else its URLs. */
function slimEntry(id, e) {
  const base = `/previews/presets/${id}`;
  const poster = urlVersion(e.poster);
  const clip = e.video === undefined ? undefined : urlVersion(e.video);
  const usual = bareUrl(e.poster) === `${base}.jpg` && poster && (e.video === undefined || (bareUrl(e.video) === `${base}.mp4` && clip));
  if (usual) return e.video === undefined ? poster : [poster, clip];
  return { poster: e.poster, ...(e.video && { video: e.video }) };
}

/** Write the manifest, and the slim covers map the pickers read next to it (preset-covers.generated.ts). */
export function writeManifest(entries, file = MANIFEST_FILE) {
  const sorted = Object.fromEntries(Object.entries(entries).sort(([a], [b]) => a.localeCompare(b)));
  fs.mkdirSync(path.dirname(file), { recursive: true });
  fs.writeFileSync(file, `${HEADER}${JSON.stringify(sorted, null, 2)};\n`);
  // A line per preset, most of them a version or two.
  const slim = Object.entries(sorted).map(([id, e]) => `  ${JSON.stringify(id)}: ${JSON.stringify(slimEntry(id, e))}`);
  fs.writeFileSync(path.join(path.dirname(file), "preset-covers.generated.ts"), `${SLIM_HEADER}{\n${slim.join(",\n")}\n};\n`);
}

/** A /previews URL (versioned or not) as a file in publicDir; null for anything else. */
export function previewFile(url, publicDir) {
  const parts = typeof url === "string" ? bareUrl(url).split("/").filter(Boolean) : [];
  return parts[0] === "previews" && !parts.includes("..") ? path.join(publicDir, ...parts) : null;
}

/**
 * The entries with each URL versioned from the file it names in publicDir (`?v=`, contentVersion): a poster from its
 * bytes and its small copy's (thumbOf keeps the poster's version, so the pair changes URL together), a clip from its
 * own. Hashes only: nothing is encoded. A URL whose file is missing loses any version it had; one outside /previews
 * stays as it is.
 */
export function withVersions(entries, publicDir = path.dirname(COVERS_DIR)) {
  const versioned = (url, withThumb) => {
    const file = previewFile(url, publicDir);
    if (!file) return url;
    if (!fs.existsSync(file)) return bareUrl(url);
    const thumb = withThumb ? previewFile(thumbOf(bareUrl(url)), publicDir) : null;
    return `${bareUrl(url)}?v=${contentVersion(thumb && fs.existsSync(thumb) ? [file, thumb] : [file])}`;
  };
  return Object.fromEntries(
    Object.entries(entries).map(([id, e]) => [id, { ...e, poster: versioned(e.poster, true), ...(e.video !== undefined && { video: versioned(e.video, false) }) }]),
  );
}

/**
 * Version the manifest's URLs from its files as they are (pnpm eval:covers --versions): for covers listed before
 * they had versions, or files changed by hand. First it makes each poster's small copy that's missing or older than
 * its poster (one copied in by hand), as every run does (writeThumbs), so a copy never shows the old picture under
 * the new version. Nothing else is encoded. Says how many URLs changed and which copies it made (`thumbs`), and lists
 * any URL left without a version (a file that's missing). A dry run writes nothing: `thumbs` lists the copies it
 * would make, and `changed` counts with the copies as they are.
 * @param {{ publicDir?: string, manifest?: string, dryRun?: boolean }} [opts]
 */
export function versionCovers(opts = {}) {
  const publicDir = opts.publicDir ?? path.dirname(COVERS_DIR);
  const before = readManifest(opts.manifest);
  const thumbs = opts.dryRun ? dueThumbs(before, publicDir).map((t) => t.thumb) : writeThumbs(before, publicDir);
  const after = withVersions(before, publicDir);
  const urls = (m) => Object.values(m).flatMap((e) => [e.poster, e.video].filter((u) => u !== undefined));
  const [was, now] = [urls(before), urls(after)];
  const result = {
    entries: Object.keys(after).length,
    urls: now.length,
    changed: now.filter((u, i) => u !== was[i]).length,
    thumbs: thumbs.map((f) => `/${path.relative(publicDir, f).split(path.sep).join("/")}`),
    unversioned: now.filter((u) => String(u).startsWith("/previews/") && !urlVersion(u)),
    manifest: opts.manifest ?? MANIFEST_FILE,
  };
  if (!opts.dryRun) writeManifest(after, opts.manifest);
  return result;
}

/**
 * The listed posters' small copies that are due: the pickers' (THUMB_PX in thumbs/) when missing or older than the
 * poster, the menus' (MINI_PX in mini/) when missing or made from another version of the poster (the minis list: a
 * file's time says nothing after a checkout). The ones writeThumbs makes.
 */
function dueThumbs(entries, publicDir) {
  const minis = readMinis(minisFileFor(publicDir));
  const due = [];
  for (const [id, e] of Object.entries(entries)) {
    const poster = previewFile(e.poster, publicDir);
    if (!poster || typeof e.poster !== "string" || !fs.existsSync(poster)) continue;
    const thumb = previewFile(thumbOf(e.poster), publicDir);
    if (thumb && !newer(thumb, poster)) due.push({ poster, thumb, px: THUMB_PX });
    // The mini copy is a preset poster's only (/previews/presets/<id>.jpg): the menus show no other cover that small.
    const mini = MINI_POSTER.test(e.poster) && previewFile(miniOf(e.poster), publicDir);
    if (mini && (!fs.existsSync(mini) || minis[id] !== contentVersion([poster]))) due.push({ poster, thumb: mini, px: MINI_PX, mini: id });
  }
  return due;
}

/**
 * Make the small copies of every listed poster: the one the pickers' tiles show (thumbOf: THUMB_PX wide, about 5 to 12
 * KB where the poster is 40 to 70) and the menus' rows (miniOf: MINI_PX wide, 2 to 4 KB), where either is missing or
 * older than its poster. Returns the files it made.
 */
export function writeThumbs(entries, publicDir = path.dirname(COVERS_DIR)) {
  const made = [];
  const file = minisFileFor(publicDir);
  const minis = readMinis(file);
  for (const { poster, thumb, px, mini } of dueThumbs(entries, publicDir)) {
    fs.mkdirSync(path.dirname(thumb), { recursive: true });
    run(["-i", poster, "-vf", `scale='min(${px},iw)':-2,format=yuvj420p`, "-frames:v", "1", "-q:v", "5", thumb]);
    made.push(thumb);
    if (mini) minis[mini] = contentVersion([poster]);
  }
  if (made.some((f) => path.basename(path.dirname(f)) === "mini")) writeMinis(minis, file);
  return made;
}

/** The preset a case's cover belongs to: a DoP preset id, a Soul look's Fuobe id, else the case id. */
function coverKey(row) {
  if (row.recipe?.kind === "soul-look" && row.recipe.look?.slug) return row.recipe.look.slug;
  return row.request?.presetId ?? row.caseId;
}

const mainOutput = (row) => (row.outputs ?? []).find((o) => (o.kind === "image" || o.kind === "video") && !["mask", "first-frame", "depth"].includes(o.role));

/** The best succeeded job of a case and variant on `metric` (the first one when nothing is scored). */
function bestJob(rows, metricsDoc, metric) {
  const better = METRIC_INFO[metric]?.better === "lower" ? (a, b) => a < b : (a, b) => a > b;
  let best = null;
  let score = null;
  for (const r of rows) {
    if (!mainOutput(r)) continue;
    const s = metric ? jobScores(r, metricsDoc)[metric] : undefined;
    if (!best || (typeof s === "number" && (score == null || better(s, score)))) {
      best = r;
      score = typeof s === "number" ? s : score;
    }
  }
  return best;
}

/** ffmpeg, or why there's none. `input` goes to its stdin; its stdout comes back (a Buffer). */
function run(args, input) {
  const r = spawnSync(process.env.FUOBE_FFMPEG ?? "ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", ...args], { input, maxBuffer: 1 << 30 });
  if (r.error?.code === "ENOENT") throw new Error("eval:covers needs ffmpeg to make small covers (install it, or set FUOBE_FFMPEG)");
  if (r.error) throw r.error;
  if (r.status !== 0) throw new Error(`ffmpeg failed: ${String(r.stderr ?? "").trim().split("\n").at(-1)}`);
  return r.stdout;
}

/** A y4m stream (ffmpeg's yuv4mpegpipe, 4:2:0) as its header line and each frame's bytes. */
export function readY4m(buf) {
  const nl = buf.indexOf(0x0a);
  const header = buf.subarray(0, Math.max(nl, 0)).toString("latin1");
  const w = Number(/ W(\d+)/.exec(header)?.[1]);
  const h = Number(/ H(\d+)/.exec(header)?.[1]);
  if (!header.startsWith("YUV4MPEG2") || !w || !h) throw new Error("ffmpeg didn't decode the clip");
  const size = w * h + 2 * Math.ceil(w / 2) * Math.ceil(h / 2);
  const frames = [];
  for (let at = nl + 1; at < buf.length; ) {
    // Each frame: "FRAME" (and any parameters) up to a newline, then its planes.
    const start = buf.indexOf(0x0a, at) + 1;
    if (start <= 0 || start + size > buf.length) break;
    frames.push(buf.subarray(start, start + size));
    at = start + size;
  }
  return { header, frames, luma: w * h };
}

/** How far apart two frames are: the mean difference of their luma (every 4th sample). */
function lumaGap(a, b, luma) {
  let sum = 0;
  let n = 0;
  for (let i = 0; i < luma; i += 4, n++) sum += Math.abs(a[i] - b[i]);
  return n ? sum / n : 0;
}

/**
 * Whether a clip loops already: going from its last frame back to its first is no bigger a step than most
 * of its own (an orbit that ends where it starts). Such a clip is cut, not crossfaded.
 * @param {Buffer[]} frames
 * @param {number} luma bytes of luma at the start of each frame
 */
export function loopsAlready(frames, luma) {
  if (frames.length < 3) return false;
  const steps = frames.slice(1).map((f, i) => lumaGap(frames[i], f, luma)).sort((a, b) => a - b);
  return lumaGap(frames.at(-1), frames[0], luma) <= Math.max(steps[Math.floor((steps.length - 1) * 0.9)], 1);
}

/**
 * A loop without a seam: the first `fade` frames are dropped from the start and blended into the last `fade`
 * instead, so the clip's end runs into its new beginning (the cards play clip covers with `loop`).
 * @param {Buffer[]} frames
 * @param {number} fade
 */
export function seamless(frames, fade) {
  const n = frames.length;
  if (!fade || n < 2 * fade) return frames;
  const out = frames.slice(fade);
  for (let k = 0; k < fade; k++) {
    const a = (k + 1) / (fade + 1);
    const tail = frames[n - fade + k];
    const head = frames[k];
    const blend = Buffer.allocUnsafe(tail.length);
    for (let i = 0; i < blend.length; i++) blend[i] = Math.round(tail[i] * (1 - a) + head[i] * a);
    out[n - 2 * fade + k] = blend;
  }
  return out;
}

/**
 * A loop that keeps every frame: `fade` frames are added after the last one, dissolving from it to the first, so the
 * clip shows its whole length clean and its loop goes back to its first frame without a jump. For a clip whose end
 * matters (`length: "full"`), which seamless would blend into its opening.
 * @param {Buffer[]} frames
 * @param {number} fade
 */
export function dissolveBack(frames, fade) {
  if (!fade || frames.length < 2) return frames;
  const last = frames.at(-1);
  const first = frames[0];
  const out = frames.slice();
  for (let k = 0; k < fade; k++) {
    const a = (k + 1) / (fade + 1);
    const blend = Buffer.allocUnsafe(last.length);
    for (let i = 0; i < blend.length; i++) blend[i] = Math.round(last[i] * (1 - a) + first[i] * a);
    out.push(blend);
  }
  return out;
}

/** An ffmpeg scale filter that fits a picture within `px` on its longest side, never enlarging it. */
const fit = (px) => `scale='if(gt(iw,ih),min(${px},iw),-2)':'if(gt(iw,ih),-2,min(${px},ih))'`;

/**
 * A cover clip's frames, cut and looped as encode() cuts them (its `opts`), decoded through `scale` (an ffmpeg filter:
 * the published clip's fit(CLIP_PX), or a larger copy's width), so a copy of any size has the same frames at the same
 * times. `rest` is the index of the frame a card rests on (a reveal's last, or the frame at `rest` seconds), or null
 * when its poster is its first frame; `stream` turns frames back into a y4m stream.
 * @param {string} src
 * @param {{ rest?: "start" | "end" | number, length?: "full" }} opts
 * @param {string} scale
 */
export function coverLoop(src, opts, scale) {
  const atEnd = opts.rest === "end";
  // A clip that rests on a moment of its own (seconds): kept whole, like a reveal, with that frame its poster.
  const atTime = typeof opts.rest === "number" && opts.rest >= 0 ? opts.rest : null;
  const whole = atEnd || atTime !== null;
  // How much of the clip its loop keeps: the first CLIP_SECONDS, or all of it (up to REST_CLIP_SECONDS).
  const full = opts.length === "full";
  const keep = full ? REST_CLIP_SECONDS : CLIP_SECONDS;
  // Decoded at CLIP_FPS: what it keeps, plus the frames the crossfade takes back from the start (a reveal or a full
  // clip: all of it, as a full clip's dissolve is added after its end).
  const seconds = whole || full ? REST_CLIP_SECONDS : keep + LOOP_FADE / CLIP_FPS;
  const y4m = run(["-i", src, "-t", String(seconds), "-an", "-sn", "-dn", "-vf", `${scale},fps=${CLIP_FPS},format=yuv420p`, "-f", "yuv4mpegpipe", "-"]);
  const { header, frames, luma } = readY4m(y4m);
  if (frames.length < 2) throw new Error(`${src} has no frames to make a clip of`);
  const cut = frames.slice(0, keep * CLIP_FPS);
  const fade = Math.min(LOOP_FADE, Math.floor(frames.length / 4));
  const looped = whole ? frames : loopsAlready(cut, luma) ? cut : full ? dissolveBack(cut, fade) : seamless(frames, fade);
  const stream = (list) => Buffer.concat([Buffer.from(`${header}\n`, "latin1"), ...list.flatMap((fr) => [Buffer.from("FRAME\n"), fr])]);
  const rest = !whole ? null : atEnd ? looped.length - 1 : Math.min(looped.length - 1, Math.round(atTime * CLIP_FPS));
  return { looped, rest, stream };
}

/**
 * A still at most STILL_PX wide/tall (a 4:2:0 JPEG), or a clip's first seconds at most CLIP_PX that loops
 * without a jump (crossfaded, unless it loops already), with its first frame as the poster.
 *
 * With `rest: "end"` (a reveal that ends on its result), the clip keeps its own end (up to REST_CLIP_SECONDS) and
 * is not crossfaded; its poster is its last frame, whose time comes back as `at`: a card shows that frame at rest
 * and starts the clip there, so nothing jumps. With `rest` a number of seconds the same holds for the frame at that
 * time (a clip whose telling moment comes before its end, such as a headline that resolves to a logo).
 *
 * With `length: "full"` (an effect whose end matters), the clip keeps its whole length (up to REST_CLIP_SECONDS)
 * instead of its first CLIP_SECONDS. Every frame shows clean: its loop dissolves from its last frame back to its first
 * after the end (dissolveBack) rather than over it, and its first frame is the poster.
 * @param {string} src
 * @param {"image" | "video"} kind
 * @param {string} destBase
 * @param {{ rest?: "start" | "end" | number, length?: "full" }} [opts]
 * @returns {{ poster: string, video?: string, at?: number }}
 */
export function encode(src, kind, destBase, opts = {}) {
  if (kind === "video") {
    const { looped, rest, stream } = coverLoop(src, opts, fit(CLIP_PX));
    run(["-f", "yuv4mpegpipe", "-i", "-", "-an", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "28", "-map_metadata", "-1", "-movflags", "+faststart", `${destBase}.mp4`], stream(looped));
    if (rest !== null) {
      run(["-f", "yuv4mpegpipe", "-i", "-", "-frames:v", "1", "-vf", "format=yuvj420p", "-q:v", "4", `${destBase}.jpg`], stream([looped[rest]]));
      return { poster: `${destBase}.jpg`, video: `${destBase}.mp4`, at: Math.round((rest / CLIP_FPS) * 1000) / 1000 };
    }
    run(["-i", `${destBase}.mp4`, "-frames:v", "1", "-vf", "format=yuvj420p", "-q:v", "4", `${destBase}.jpg`]);
    return { poster: `${destBase}.jpg`, video: `${destBase}.mp4` };
  }
  run(["-i", src, "-vf", `${fit(STILL_PX)},format=yuvj420p`, "-frames:v", "1", "-q:v", "3", `${destBase}.jpg`]);
  return { poster: `${destBase}.jpg` };
}

/**
 * Make covers from a run.
 * @param {string} dir the run folder
 * @param {{ variant?: string, dryRun?: boolean, publicDir?: string, manifest?: string }} [opts]
 *   variant: take this variant's renders for every case (default: the promoted candidate's, promoted cases only)
 *   publicDir: the site's public folder (covers go to <publicDir>/previews/<suite>/); manifest: the generated file
 */
export function makeCovers(dir, opts = {}) {
  const L = loadRun(dir);
  if (L.run.engine === "demo") throw new Error("A demo run's media is the demo provider's, not Fuobe's: it never becomes a cover");
  const publicDir = opts.publicDir ?? path.dirname(COVERS_DIR);
  const outDir = path.join(publicDir, "previews", safeName(L.run.suite));
  // The promote verdicts (as the run's scores and ratings stand now) say which cases earned a cover, and on which metric to pick the render.
  const doc = promote(dir);
  const byCase = new Map(doc.results.map((r) => [r.caseId, r]));
  const variant = opts.variant ?? doc.candidate;
  const picked = [];
  const skipped = [];
  for (const caseId of [...new Set(L.rows.map((r) => r.caseId))]) {
    const verdict = byCase.get(caseId);
    if (!opts.variant && verdict?.verdict !== "promote") {
      skipped.push({ caseId, why: `${verdict?.verdict ?? "no verdict"}: only a promoted recipe's render becomes a cover (--variant <name> takes another variant's, such as what ships today)` });
      continue;
    }
    const rows = L.rows.filter((r) => r.caseId === caseId && r.variant === variant && r.status === "succeeded");
    // Licence: information on the cover (`licence`); with --commercial-only a render whose LoRAs can't be sold is left out.
    const lib = new Map((rows[0]?.recipe?.loras ?? []).map((l) => [l.file, l]));
    const blocked = (rows[0]?.recipe?.applied ?? []).filter((l) => lib.get(l.file)?.commercial === false);
    const licence = rows[0]?.recipe?.commercialOk === false || blocked.length ? `non-commercial LoRA${blocked.length > 1 ? "s" : ""} ${blocked.map((l) => l.file).join(", ")}`.trim() : undefined;
    if (licence && opts.commercialOnly) {
      skipped.push({ caseId, why: `${licence} (--commercial-only)` });
      continue;
    }
    const metric = verdict?.mainMetric ?? null;
    const best = bestJob(rows, L.metrics, metric);
    if (!best) {
      skipped.push({ caseId, why: `no ${variant} render` });
      continue;
    }
    picked.push({ caseId, key: coverKey(best), row: best, metric, score: metric ? (jobScores(best, L.metrics)[metric] ?? null) : null, ...(licence && { licence }) });
  }
  const result = { runId: L.run.runId, engine: L.run.engine, variant, covers: [], skipped, manifest: opts.manifest ?? MANIFEST_FILE, folder: outDir };
  if (opts.dryRun) {
    result.covers = picked.map((p) => ({ key: p.key, caseId: p.caseId, job: p.row.id, metric: p.metric, score: p.score, ...(p.licence && { licence: p.licence }) }));
    return result;
  }
  if (picked.length) fs.mkdirSync(outDir, { recursive: true });
  const manifest = readManifest(opts.manifest);
  for (const p of picked) {
    const out = mainOutput(p.row);
    const files = encode(path.join(dir, out.file), out.kind, path.join(outDir, safeName(p.key)));
    const web = (f) => `/${path.relative(publicDir, f).split(path.sep).join("/")}`;
    const before = manifest[p.key];
    manifest[p.key] = { poster: web(files.poster), ...(files.video && { video: web(files.video) }), run: L.run.runId, engine: L.run.engine, model: p.row.model?.id ?? "", variant };
    // A measured cover replaces any other (a masters cover in /previews/presets): its files go with it.
    dropReplaced(before, manifest, publicDir);
    result.covers.push({ key: p.key, caseId: p.caseId, job: p.row.id, metric: p.metric, score: p.score, ...(p.licence && { licence: p.licence }), ...manifest[p.key] });
  }
  if (picked.length) {
    writeThumbs(manifest, publicDir);
    const versioned = withVersions(manifest, publicDir);
    writeManifest(versioned, opts.manifest);
    for (const c of result.covers) Object.assign(c, pick(versioned[c.key], ["poster", "video"]));
  }
  return result;
}

const pick = (o, keys) => Object.fromEntries(keys.filter((k) => o?.[k] !== undefined).map((k) => [k, o[k]]));

/** Remove a replaced entry's files that no entry names any more (its cover now lives in another folder). */
function dropReplaced(old, manifest, publicDir) {
  if (!old) return;
  // By path: the old entry's URLs carry the versions of its old files, the new one's none yet.
  const files = (e) => [e.poster, e.video, typeof e.poster === "string" && thumbOf(e.poster)].filter(Boolean).map(bareUrl);
  const named = new Set(Object.values(manifest).flatMap(files));
  for (const url of files(old)) {
    const file = previewFile(url, publicDir);
    if (!named.has(url) && file) fs.rmSync(file, { force: true });
  }
}

/** What a masters folder holds for a preset: its rendered clip, else its start still. */
const MASTER_CLIP = "clip.mp4";
const MASTER_STILL = "start.png";

export const newer = (file, than) => {
  try {
    return fs.statSync(file).mtimeMs >= fs.statSync(than).mtimeMs;
  } catch {
    return false;
  }
};

function readMeta(folder) {
  try {
    const meta = JSON.parse(fs.readFileSync(path.join(folder, "meta.json"), "utf8"));
    return meta && typeof meta === "object" ? meta : {};
  } catch {
    return {};
  }
}

/**
 * Covers from rendered masters that aren't a run's (pnpm eval:covers --from-masters <dir>), such as the
 * preview renders made in ComfyUI for the gallery. One folder per preset id: its clip.mp4 becomes a clip
 * cover (the first 4 s, the first frame as its poster), else its start.png a still cover; the encoding is
 * makeCovers'. A folder's meta.json `{"length": "full"}` makes its clip cover keep the clip's whole length (up to
 * REST_CLIP_SECONDS) instead of its first 4 s, for an effect whose end matters. Each cover records the provenance
 * it's given: the run, engine, model (`videoModel` for a clip) and variant; a folder's meta.json can name its own
 * `model` and `variant`. The manifest is merged:
 * entries other runs wrote stay, and only the ids found here are replaced. An id whose cover another run
 * made elsewhere (a measured eval cover, another suite's) is skipped, so a later masters run never undoes it;
 * `replace` takes it over (and removes its files). Run it again as masters land: a cover newer than its master
 * is kept (force makes it again), and a preset whose cover was a clip and is now a still loses the old clip.
 * @param {string} dir the masters folder
 * @param {{ run: string, engine?: string, model?: string, videoModel?: string, variant?: string, suite?: string,
 *   only?: string[], force?: boolean, replace?: boolean, dryRun?: boolean, publicDir?: string, manifest?: string }} opts
 */
export function coversFromMasters(dir, opts) {
  if (!opts?.run) throw new Error("Covers from masters need a run name for their provenance (--run)");
  if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new Error(`No masters folder at ${dir}`);
  const publicDir = opts.publicDir ?? path.dirname(COVERS_DIR);
  const outDir = path.join(publicDir, "previews", safeName(opts.suite ?? "presets"));
  const engine = opts.engine ?? "comfyui";
  const variant = opts.variant ?? "";
  const only = opts.only?.length ? new Set(opts.only) : null;
  const picked = [];
  const skipped = [];
  for (const id of fs.readdirSync(dir).sort()) {
    const folder = path.join(dir, id);
    if ((only && !only.has(id)) || !fs.statSync(folder).isDirectory()) continue;
    if (safeName(id) !== id || id.startsWith("_")) {
      skipped.push({ id, why: "not a preset id (folders are named by preset id, such as effect-set-on-fire)" });
      continue;
    }
    const clip = path.join(folder, MASTER_CLIP);
    const kind = fs.existsSync(clip) ? "video" : fs.existsSync(path.join(folder, MASTER_STILL)) ? "image" : null;
    if (!kind) {
      skipped.push({ id, why: `no ${MASTER_CLIP} or ${MASTER_STILL} yet` });
      continue;
    }
    const meta = readMeta(folder);
    const model = typeof meta.model === "string" ? meta.model : ((kind === "video" ? opts.videoModel : opts.model) ?? "");
    const full = kind === "video" && meta.length === "full";
    picked.push({ id, kind, src: kind === "video" ? clip : path.join(folder, MASTER_STILL), meta: path.join(folder, "meta.json"), ...(full && { length: "full" }), model, variant: typeof meta.variant === "string" ? meta.variant : variant });
  }
  for (const id of only ?? []) if (!picked.some((p) => p.id === id) && !skipped.some((s) => s.id === id)) skipped.push({ id, why: "no folder" });
  const result = { run: opts.run, engine, covers: [], skipped, manifest: opts.manifest ?? MANIFEST_FILE, folder: outDir };
  const web = (f) => `/${path.relative(publicDir, f).split(path.sep).join("/")}`;
  const manifest = readManifest(opts.manifest);
  // Another run's cover outside this suite's folder (a measured one, say) stays unless replace says otherwise.
  const ours = picked.filter((p) => {
    const cur = manifest[p.id];
    if (!cur || opts.replace || String(cur.poster).startsWith(`${web(outDir)}/`)) return true;
    skipped.push({ id: p.id, why: `its cover is ${cur.run || "another run"}'s (${bareUrl(cur.poster)}): --replace takes it over` });
    return false;
  });
  if (ours.length && !opts.dryRun) fs.mkdirSync(outDir, { recursive: true });
  for (const p of ours) {
    const base = path.join(outDir, safeName(p.id));
    const files = { poster: `${base}.jpg`, ...(p.kind === "video" && { video: `${base}.mp4` }) };
    // Up to date: the cover is newer than its master and any meta.json (and a clip's poster than the clip it's taken from).
    const fresh = (file) => newer(file, p.src) && (!fs.existsSync(p.meta) || newer(file, p.meta));
    const kept = !opts.force && (p.kind === "video" ? fresh(files.video) && newer(files.poster, files.video) : fresh(files.poster) && !fs.existsSync(`${base}.mp4`));
    const entry = { poster: web(files.poster), ...(files.video && { video: web(files.video) }), run: opts.run, engine, model: p.model, variant: p.variant };
    if (!opts.dryRun) {
      if (!kept) {
        encode(p.src, p.kind, base, p.length ? { length: p.length } : {});
        if (p.kind === "image") fs.rmSync(`${base}.mp4`, { force: true });
      }
      const before = manifest[p.id];
      manifest[p.id] = entry;
      dropReplaced(before, manifest, publicDir);
    }
    result.covers.push({ key: p.id, kind: p.kind, from: p.src, ...(p.length && { length: p.length }), ...(kept && { kept: true }), ...entry });
  }
  if (ours.length && !opts.dryRun) {
    writeThumbs(manifest, publicDir);
    const versioned = withVersions(manifest, publicDir);
    writeManifest(versioned, opts.manifest);
    for (const c of result.covers) Object.assign(c, pick(versioned[c.key], ["poster", "video"]));
  }
  return result;
}